From 917dab492883178b0ea9b57bce3a526b597e6373 Mon Sep 17 00:00:00 2001 From: Thorsten Fuchs <76904008+ThorFuchs@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:30:17 +0200 Subject: [PATCH 1/7] feat: integrate opt-in exact value and schema DSLs Keep trusted authored staging separate from finite iterative finalization. Reuse one engine ledger through schema document admission; preserve exact keys, numbers, omission and native schema authority. Add real-engine semantic, lifecycle, compiler and public consumer qualification. --- AGENTS.md | 4 +- CHANGELOG.md | 5 + Documentation/Architecture/API.md | 28 +- .../Architecture/DualDSL/Decisions.md | 87 +++ Documentation/Architecture/DualDSL/Plan.md | 39 + .../Architecture/DualDSL/Progress.json | 18 + .../Architecture/ExtractionManifest.json | 54 +- Documentation/Architecture/ResourceLimits.md | 11 + Documentation/CI/README.md | 19 +- Documentation/DocumentationTooling.md | 10 +- Documentation/Qualification/DualDSL/README.md | 24 + Documentation/README.md | 8 + Examples/Consumer/Package.swift | 4 +- .../Sources/Consumer/READMEExamples.swift | 18 + Examples/DualDSL/Package.swift | 15 + Examples/DualDSL/README.md | 11 + .../Sources/DualDSLConsumer/main.swift | 62 ++ Package.swift | 8 +- README.md | 45 +- Scripts/build_documentation.py | 6 +- Scripts/build_documentation_site.py | 14 +- Scripts/ci.py | 36 +- Scripts/documentation_catalog.py | 10 +- Scripts/qualify_dual_dsl.py | 167 ++++ Scripts/wasm_support.py | 4 +- .../Documentation.docc/JSONDSLCore.md | 38 + Sources/JSONDSLCore/JSONContent.swift | 545 ++++++++++++++ Sources/JSONDSLCore/JSONDSLNode.swift | 172 +++++ .../Documentation.docc/AuthoredSchemas.md | 54 ++ .../Documentation.docc/JSONSchemaDSL.md | 40 + Sources/JSONSchemaDSL/JSONSchemaDSL.swift | 711 ++++++++++++++++++ .../Documentation.docc/AuthoredValues.md | 43 ++ .../Documentation.docc/JSONValueDSL.md | 28 + Sources/JSONValueDSL/JSONValueDSL.swift | 187 +++++ .../DualDSL/DefinitionInsideProperties.swift | 2 + .../DualDSL/ElementInsideObject.swift | 3 + .../DualDSL/FieldInsideSchema.swift | 3 + .../DualDSL/ImplicitFloatingPoint.swift | 2 + .../DualDSL/PropertyInsideDefinitions.swift | 2 + .../DualDSL/SchemaClauseInsideArray.swift | 3 + Tests/JSONDSLTests/DSLPrototypeTests.swift | 298 ++++++++ Tests/JSONDSLTests/IntegrationTests.swift | 36 + .../JSONDSLTests/ResourceLifecycleTests.swift | 220 ++++++ Tests/JSONDSLTests/SemanticTests.swift | 479 ++++++++++++ Tests/JSONDSLTests/StressTypeCheckTests.swift | 259 +++++++ 45 files changed, 3794 insertions(+), 38 deletions(-) create mode 100644 Documentation/Architecture/DualDSL/Decisions.md create mode 100644 Documentation/Architecture/DualDSL/Plan.md create mode 100644 Documentation/Architecture/DualDSL/Progress.json create mode 100644 Documentation/Qualification/DualDSL/README.md create mode 100644 Examples/DualDSL/Package.swift create mode 100644 Examples/DualDSL/README.md create mode 100644 Examples/DualDSL/Sources/DualDSLConsumer/main.swift create mode 100644 Scripts/qualify_dual_dsl.py create mode 100644 Sources/JSONDSLCore/Documentation.docc/JSONDSLCore.md create mode 100644 Sources/JSONDSLCore/JSONContent.swift create mode 100644 Sources/JSONDSLCore/JSONDSLNode.swift create mode 100644 Sources/JSONSchemaDSL/Documentation.docc/AuthoredSchemas.md create mode 100644 Sources/JSONSchemaDSL/Documentation.docc/JSONSchemaDSL.md create mode 100644 Sources/JSONSchemaDSL/JSONSchemaDSL.swift create mode 100644 Sources/JSONValueDSL/Documentation.docc/AuthoredValues.md create mode 100644 Sources/JSONValueDSL/Documentation.docc/JSONValueDSL.md create mode 100644 Sources/JSONValueDSL/JSONValueDSL.swift create mode 100644 Tests/CompileNegative/DualDSL/DefinitionInsideProperties.swift create mode 100644 Tests/CompileNegative/DualDSL/ElementInsideObject.swift create mode 100644 Tests/CompileNegative/DualDSL/FieldInsideSchema.swift create mode 100644 Tests/CompileNegative/DualDSL/ImplicitFloatingPoint.swift create mode 100644 Tests/CompileNegative/DualDSL/PropertyInsideDefinitions.swift create mode 100644 Tests/CompileNegative/DualDSL/SchemaClauseInsideArray.swift create mode 100644 Tests/JSONDSLTests/DSLPrototypeTests.swift create mode 100644 Tests/JSONDSLTests/IntegrationTests.swift create mode 100644 Tests/JSONDSLTests/ResourceLifecycleTests.swift create mode 100644 Tests/JSONDSLTests/SemanticTests.swift create mode 100644 Tests/JSONDSLTests/StressTypeCheckTests.swift diff --git a/AGENTS.md b/AGENTS.md index 03c4ab6..fbc61dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,9 +4,11 @@ Swift-JSON requires Swift tools/compiler 6.4+, Swift language mode 6 and macOS/SDK 27+. Read README.md, CONTRIBUTING.md and the relevant contracts in Documentation/Architecture before changing behavior. -- Keep six public products: JSON, JSONSchema, JSONStreaming, JSONPatch, JSONHTML and JSONBridges. +- Keep eight public products: JSON, JSONSchema, JSONStreaming, JSONPatch, JSONHTML, JSONBridges, JSONValueDSL and JSONSchemaDSL. JSONHTML depends on JSON only; the maintainer-approved 1.3 addition preserves historical four-product releases. The E2-approved opt-in JSONBridges depends on JSON only and is never re-exported by core. + The P1.2-approved optional DSL products use JSONDSLCore without a standalone core product. + Trusted authored DSL staging is outside finalization quotas; never imply a staging/RSS bound. JSONRegexRuntime is package-private. Root package dependencies remain empty. - Preserve exact bounded decimals, decoded Unicode scalar identity, ordered objects with order-independent equality, one strict UTF-8 grammar, native diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b102a8..f3e03c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ ## Unreleased +- Add opt-in JSONValueDSL and JSONSchemaDSL products for typed, trusted authored + values and Draft 2020-12 declarations. Exact values and schema semantics remain + owned by the existing engine. Finalization uses one finite iterative ledger; + authored staging and callbacks are explicitly outside its resource accounting. + - Add E2's shallow JSON parsing, checked object construction, decimal-text and pre-parsed Pointer entry points; exact-key membership and three-state presence composition; and direct validation from an immutable compiled schema plan. diff --git a/Documentation/Architecture/API.md b/Documentation/Architecture/API.md index bd17ce9..9d9d73c 100644 --- a/Documentation/Architecture/API.md +++ b/Documentation/Architecture/API.md @@ -1,7 +1,7 @@ # Public API contract This document describes the implemented public interface. Native compiler symbol -graphs supply the complete declarations in the six DocC catalogs. Examples +graphs supply the complete declarations in the eight product DocC catalogs and the shared DSL structure reference. Examples in the [README](../../README.md) are compiled and executed by the public consumer. ## Products and ownership @@ -9,6 +9,8 @@ in the [README](../../README.md) are compiled and executed by the public consume | Product | Main entry points | Owned implementation boundary | | --- | --- | --- | | JSON | JSON, JSONNumber, JSONObject, JSONParser, JSONWriter, JSONValueEncoder, JSONValueDecoder, JSONPointer, JSONDocument | Shared strict codec, exact decimal model, bounded traversal and native coding | +| JSONValueDSL | JSONValueDSL.object/array, Field, Element, Elements | Trusted authored staging; finite iterative exact finalization | +| JSONSchemaDSL | JSONSchemaDSL.document/boolean, Schema, Property, Definition, PatternProperty, DependentSchema, RequiredDependency, Rule | Trusted authored schema declarations; existing document/compiler/validator authority | | JSONBridges | BinaryInteger.jsonNumber, FixedWidthInteger/Double/Decimal.init(jsonNumber:), Double.jsonNumberFromRoundTripText | Optional one-delegate numeric conversions; explicit fidelity, no new authority | | JSONSchema | JSONSchemaDocument, JSONSchemaRegistry, JSONSchemaCompiler, CompiledJSONSchema, JSONSchemaValidator | Offline immutable plan, invocation-owned evaluation and private native regex | | JSONStreaming | JSONEventSequence, JSONValueSequence, NDJSONValueSequence, JSONTopLevelArraySequence, JSONAsyncWriter | Exclusive pull state, shared codec, strict framing and awaited handoffs | @@ -16,7 +18,7 @@ in the [README](../../README.md) are compiled and executed by the public consume | JSONHTML | JSONHTMLRenderer, JSONHTMLRenderingOptions, JSONHTMLLimits, JSONHTMLRenderReport, JSONHTMLAnnotation, JSONExportDocument, JSONExportOptions, JSONExportReport | Exact HTML, native Apple transfer, immutable prepared JSON/text/Markdown/static HTML/opt-in styled RTF and cumulative budgets | JSON imports no siblings. JSONSchema depends on JSON and package-private -JSONRegexRuntime. Streaming, Patch, HTML and Bridges depend on JSON. There are six public +JSONRegexRuntime. Streaming, Patch, HTML and Bridges depend on JSON. There are eight public products and no external root-package dependencies. Runtime code uses no HTTP, UI, MCP or documentation-tool dependencies. @@ -211,3 +213,25 @@ JSONHTMLRenderer also accepts JSONDocument in its four rendering/report methods. Caller annotations use exact typed paths, explicit missing-parent attachment and coherent value byte spans without schema execution or source-byte archival. See [diagnostic rendering](Release1.3/DiagnosticAnnotations.md). + +## Optional Dual DSL P1.2 + +The two DSL products do not change or re-export the existing core entry points. +JSONDSLCore has no standalone product; its public structural builder types occur +in the optional generic signatures. See the [decisions](DualDSL/Decisions.md). +Callbacks, content emission and staging are trusted and unmetered. Finalization +uses one finite invocation ledger through iterative construction and, for schemas, +document admission. This does not imply whole-pipeline cumulative billing, staging +retention, caller instruction or RSS bounds. No whole-DSL report is supplied. + +Exact duplicate names throw JSONFailure/duplicateKey. Decoded scalar identity and +order are preserved. Missing declarations emit nothing; null, empty containers and +Boolean schemas differ. Array flattening requires Elements(contentsOf:). Implicit +numbers accept BinaryInteger only, with explicit JSONNumber for decimals. E2 and +JSONBridges remain unchanged; DSL targets import neither bridge nor framework DSL. + +Schema rawKeyword preserves declarations for existing compiler classification. +No requiredness/default/format/reference/annotation policy is inferred. Invalid +instances return false; malformed schemas, offline missing resources, nonproductive +cycles, resource failures and cancellation remain operational errors. Factories +never validate or publish a candidate schema as already compiled. diff --git a/Documentation/Architecture/DualDSL/Decisions.md b/Documentation/Architecture/DualDSL/Decisions.md new file mode 100644 index 0000000..c99cd0c --- /dev/null +++ b/Documentation/Architecture/DualDSL/Decisions.md @@ -0,0 +1,87 @@ +# Dual DSL decisions + +## D1 — Trusted authored staging, finite finalization + +P1.2 adopts the explicitly permitted authored-configuration boundary. Result-builder +callbacks, wrappers, collection emission, IR assembly and integer literal construction +are trusted, unmetered staging. They can allocate or run caller computation before +finalization. This API is not an untrusted-input entry point, an instruction quota, +a staging-retention guarantee, an RSS bound or a whole-pipeline cumulative report. +Use existing bounded parsers/accumulators for dynamic untrusted input. + +Finalization is a separate checked phase. One invocation-owned JSONWorkMeter covers +iterative lowering, exact key/index admission, output slots, literal payload traversal, +work/cancellation and, for schemas, JSONSchemaDocument admission. Existing package +hooks are reused; JSON, JSONSchema and JSONBridges source need no changes. No helper +restarts this finalization ledger. A caught owned failure remains terminal, including +at the package continuation boundary. No partially finalized value is returned. +There is deliberately no public whole-DSL `WithReport` API. Tests distinguish the +finalization counters from unaccounted staging; existing 49 baseline probes remain. + +## D2 — Flat staging lifetime and iterative lowering + +The prototype's recursive indirect enum and per-container checked materialization +are replaced with a flat private token sequence. The public node's object/array/literal +factory spellings remain, but it is a struct rather than a pattern-matchable enum. +Nested typed declarations assemble these tokens without flattening JSON array values. +Finalization uses explicit frames and the engine's exact-key index and admission helpers. +IR teardown does not recursively own child IR nodes. Literal JSON retains its existing +engine lifetime semantics. Depth failures use JSONFailure/resource/maxDepth, replacing +the prototype-only JSONDSLBuildFailure; no second resource-error model is added. + +Qualification must cover default-cap rejection of deeply staged inputs, accepted depth +boundaries, cancellation in owned finalization and terminal errors. Arbitrary caller- +configured depths and callback recursion are not implied by a finite tested depth. + +## D3 — Separate products and semantic authorities + +JSONValueDSL and JSONSchemaDSL add no dependency to core or each other. Shared typed +builder protocols are public declarations in JSONDSLCore because optional public generic +signatures reference them; the helper module has no independently selectable product. +Objects use ordered exact-key semantics, arrays preserve nesting, omission emits nothing, +and duplicate keywords/properties/definitions fail. There is no String dictionary merge. + +The schema DSL emits ordinary JSONSchemaDocument. The existing compiler and validator +alone govern dialect, vocabularies, regex, references, annotations, requiredness and +invalidity versus operational errors. Explicit offline registry resources use existing +JSONSchemaDocument/JSONSchemaRegistry APIs; no ID-to-retrieval inference or network resolver. + +## D4 — E2 reconciliation and minimal naming + +Merged E2/JSONBridges remains unchanged and opt-in. DSL implicit numeric inputs remain +BinaryInteger only; exact decimals require explicit JSONNumber. No Float/Double overload, +Optional bridge, floating literal, coercion or automatic requiredness is added. +JSONValueDSL and JSONSchemaDSL remain distinct discovery namespaces. An umbrella product, +typed ObjectSchema/StringSchema/ArraySchema synonyms, automatic references/derivation and +new Boolean-schema overload aliases are deferred: existing Rule(Boolean), table Boolean +initializers and rawKeyword preserve the complete declaration without another surface. +The identical prototype rawSchemaKeyword synonym is removed in favor of rawKeyword. + +## D5 — Compiler strategy (pending measurement) + +The initial integration retains variadic buildBlock and conditional context conformances. +G4 records actual Swift 6.4 timings, diagnostics and memory observations before selecting +it over a pairwise buildPartialBlock alternative. Measurements under concurrent host load +are observations, not a quiet-host or broad compiler-throughput guarantee. + +## D6 — Empty enum is distinct from malformed schema + +The initial integration test incorrectly grouped an empty enum with malformed +length/count declarations. Actual compiler behavior and the pinned validation +meta-schema accept an enum array with no entries. Draft 2020-12 validation +[section 6.1.2](https://json-schema.org/draft/2020-12/draft-bhutton-json-schema-validation-01#name-enum) +requires an array and recommends a nonempty one. The corrected case compiles +both DSL and handwritten declarations and proves ordinary invalidity for all +six JSON kinds. Negative bounds, zero multipleOf, empty oneOf and duplicate +required names remain explicit compilation failures. No engine behavior changed. + +## D7 — Real module qualification instead of facade shadowing + +A native Swift 6.4 consumer with its own Field, Element, Schema and Property +declarations cannot spell JSONValueDSL.Field or JSONSchemaDSL.Schema when the +prototype facade enums shadow their modules. P1.2 therefore uses module-level +object/array/document/boolean factories. Existing authored calls retain the same +JSONValueDSL.object and JSONSchemaDSL.document spelling, while declaration types +can be qualified with their actual module. No umbrella, alias or synonym is added. +This is an unreleased prototype declaration-shape change, not an engine API change. +The compiler harness retains explicit collision cases in both configurations. diff --git a/Documentation/Architecture/DualDSL/Plan.md b/Documentation/Architecture/DualDSL/Plan.md new file mode 100644 index 0000000..0b2eb2a --- /dev/null +++ b/Documentation/Architecture/DualDSL/Plan.md @@ -0,0 +1,39 @@ +# Dual DSL P1.2 integration + +This is an unreleased integration on `codex/dual-dsl-p1.2`, based on current main +`e8c3e4bd9ae40d797f07a527ea98879acee3c057`. The supplied packet inspected +`9517233ef0a3c1b961b738df58fe3ee4081d780c`; the intervening E2 merge adds entry points +and JSONBridges. Existing six products and core implementation remain authoritative. +The requested JSONValueDSL and JSONSchemaDSL are additive opt-in products. JSONDSLCore +has no standalone product. Root dependencies, platforms and all 49 profiles remain unchanged. + +The maintainer-supplied packet SHA-256 is +`a69432b69f59d3d587502c2453fed3d00259845b9335a551b962965be10f9588`. +Its 32-file manifest verified. Only its three DSL source roots and six negative +fixtures are adapted. Neither signature shim is an engine input. Its sixteen +positive cases are ported from XCTest to Swift Testing and real JSONLimits. +Original and adaptation contributions retain Apache-2.0. + +## Gates and reviewable increments + +1. **G0 baseline:** pin source/SDK/compiler; record manifest and file collisions; + run production native baseline in an untouched detached worktree. +2. **G1/G3 integration:** add opt-in targets, iterative flat staging/lowering, + exact admission and shared finalization/document ledger. Compile the real consumer. +3. **G2 semantics:** port all sixteen cases, implement V-01–V-20 parity against + exact manual JSON and hand-written schemas; retain unchanged official suite policies. +4. **G4 compiler qualification:** exact-domain negative fixtures and measured + 16/64/128/256 blocks, nesting, choices, loops and mixed schema contexts; compare + pairwise composition when the observed scaling warrants it. +5. **G5 API/docs:** public comments and DocC, compiled README and guides; record + accepted/rejected namespace and sugar decisions against merged E2. +6. **G6 final qualification:** exact-count native/safety/docs and real Linux lanes; + public consumer, strict concurrency, source/diff/receipts and remaining limitations. + +Each coherent increment is committed locally. No push, PR, merge, tag or publication +is authorized by this integration request. Existing release and sibling worktrees +are preserved. A passing shim or typecheck is never a semantic qualification claim. + +Private input and raw receipts live in ignored `Artifacts/DualDSLP1.2`; source identity, +commands, exits, toolchains, suite counts and source hashes accompany actual outcomes. +[Progress](Progress.json) records incomplete gates without rewriting older release history. diff --git a/Documentation/Architecture/DualDSL/Progress.json b/Documentation/Architecture/DualDSL/Progress.json new file mode 100644 index 0000000..899b6d9 --- /dev/null +++ b/Documentation/Architecture/DualDSL/Progress.json @@ -0,0 +1,18 @@ +{ + "wave": "P1.2", + "base_commit": "e8c3e4bd9ae40d797f07a527ea98879acee3c057", + "packet_baseline": "9517233ef0a3c1b961b738df58fe3ee4081d780c", + "packet_sha256": "a69432b69f59d3d587502c2453fed3d00259845b9335a551b962965be10f9588", + "branch": "codex/dual-dsl-p1.2", + "release_ready": false, + "gates": { + "P1.2-G0": "in_progress", + "P1.2-G1": "in_progress", + "P1.2-G2": "in_progress", + "P1.2-G3": "in_progress", + "P1.2-G4": "pending", + "P1.2-G5": "pending", + "P1.2-G6": "pending" + }, + "scope": "Trusted authored staging; finite iterative shared-ledger finalization; no staging/RSS/caller-work claim" +} diff --git a/Documentation/Architecture/ExtractionManifest.json b/Documentation/Architecture/ExtractionManifest.json index 735d569..f61232c 100644 --- a/Documentation/Architecture/ExtractionManifest.json +++ b/Documentation/Architecture/ExtractionManifest.json @@ -17,7 +17,7 @@ "blob_sha": "25cb8eab982ed0fc41e5f1dde5abeab18113f55e", "destination": "Sources/JSON/Value/JSON.swift", "disposition": "Six enum case concepts selectively adapted; equality/hash traversal and exact object/key storage rewritten.", - "attribution": "Original Thor Fuchs 2024\u20132026 header retained; Reference LICENSE and NOTICE preserved.", + "attribution": "Original Thor Fuchs 2024–2026 header retained; Reference LICENSE and NOTICE preserved.", "validation": [ "Tests/JSONTests/ValueTests.swift", "Tests/JSONTests/PresenceTests.swift" @@ -163,7 +163,7 @@ "blob_sha": null, "destination": "Sources/JSONRegexRuntime/RegexUnicodeTables.swift", "disposition": "407 immutable tables generated by original deterministic Python generator from fixed Unicode data; no generated Regress table copied. Regeneration compares bytes and provenance.", - "attribution": "\u00a9 2020 Unicode, Inc.; Unicode-3.0 copyright/permission notice retained in Licenses/Unicode-3.0.txt.", + "attribution": "© 2020 Unicode, Inc.; Unicode-3.0 copyright/permission notice retained in Licenses/Unicode-3.0.txt.", "validation": "Byte-equal regeneration and native exact-alias/GC/binary/Script/Script_Extensions/IdentifierName vectors", "evidence": "Scripts/ci.py: current native, safety and documentation receipts" }, @@ -174,7 +174,7 @@ "blob_sha": null, "destination": "Sources/JSONSchema/Formats/JSONIDNAData.swift and Tests/Fixtures/Unicode/NormalizationTest-13.0.0.txt", "disposition": "Original generator derives RFC5892/5893, NFC and UTS46 nontransitional STD3 tables; normalization fixture copied byte-for-byte. No external engine or system Unicode authority.", - "attribution": "\u00a9 2019\u20132020 Unicode, Inc.; Unicode-3.0 notice preserved in Licenses/Unicode-3.0.txt.", + "attribution": "© 2019–2020 Unicode, Inc.; Unicode-3.0 notice preserved in Licenses/Unicode-3.0.txt.", "validation": "18853 normalization cases (94265 native comparisons); 874 independent optional format cases; byte-equal regeneration", "evidence": "Scripts/ci.py: current native, safety and documentation receipts" }, @@ -188,6 +188,54 @@ "attribution": "BSD-3-Clause alternative; Licenses/json-schema-spec-BSD-AFL.txt", "validation": "Tests/JSONSchemaTests/EvaluationOutputTests.swift", "evidence": "Scripts/ci.py: current native, safety and documentation receipts" + }, + { + "repository": "Maintainer-supplied SwiftJSON-DualDSL-Prototypes-P1 packet", + "commit": null, + "source_archive_sha256": "a69432b69f59d3d587502c2453fed3d00259845b9335a551b962965be10f9588", + "original_path": "Sources/JSONDSLCore/JSONContent.swift", + "original_sha256": "278865ff3843c3bc3f697f3ce56329c35418ae6598201aa743effa3b75c1fa4a", + "destination": "Sources/JSONDSLCore", + "disposition": "Typed authored DSL adapted against actual Swift 6.4 JSON/JSONSchema; flat iterative IR and shared finalization meter replace prototype recursive lowering. Neither shim copied.", + "attribution": "SPDX Apache-2.0 prototype notices retained; integration is original Apache-2.0 code.", + "validation": [ + "Tests/JSONDSLTests", + "Tests/CompileNegative/DualDSL", + "Examples/DualDSL" + ], + "evidence": "Scripts/ci.py: actual native, safety, docs and supported platform receipts; no shim qualification claim" + }, + { + "repository": "Maintainer-supplied SwiftJSON-DualDSL-Prototypes-P1 packet", + "commit": null, + "source_archive_sha256": "a69432b69f59d3d587502c2453fed3d00259845b9335a551b962965be10f9588", + "original_path": "Sources/JSONValueDSL/JSONValueDSL.swift", + "original_sha256": "7a846ed54455977a585fb53f5646795e5dbcae3a949a0e8be43f0b333f2a025e", + "destination": "Sources/JSONValueDSL", + "disposition": "Typed authored DSL adapted against actual Swift 6.4 JSON/JSONSchema; flat iterative IR and shared finalization meter replace prototype recursive lowering. Neither shim copied.", + "attribution": "SPDX Apache-2.0 prototype notices retained; integration is original Apache-2.0 code.", + "validation": [ + "Tests/JSONDSLTests", + "Tests/CompileNegative/DualDSL", + "Examples/DualDSL" + ], + "evidence": "Scripts/ci.py: actual native, safety, docs and supported platform receipts; no shim qualification claim" + }, + { + "repository": "Maintainer-supplied SwiftJSON-DualDSL-Prototypes-P1 packet", + "commit": null, + "source_archive_sha256": "a69432b69f59d3d587502c2453fed3d00259845b9335a551b962965be10f9588", + "original_path": "Sources/JSONSchemaDSL/JSONSchemaDSL.swift", + "original_sha256": "852ec7d7c9f6d5957fa3711c3e1b5ea3daeadf0ea67241ceb90ed1511bbd2f48", + "destination": "Sources/JSONSchemaDSL", + "disposition": "Typed authored DSL adapted against actual Swift 6.4 JSON/JSONSchema; flat iterative IR and shared finalization meter replace prototype recursive lowering. Neither shim copied.", + "attribution": "SPDX Apache-2.0 prototype notices retained; integration is original Apache-2.0 code.", + "validation": [ + "Tests/JSONDSLTests", + "Tests/CompileNegative/DualDSL", + "Examples/DualDSL" + ], + "evidence": "Scripts/ci.py: actual native, safety, docs and supported platform receipts; no shim qualification claim" } ], "original_implementation_notes": [ diff --git a/Documentation/Architecture/ResourceLimits.md b/Documentation/Architecture/ResourceLimits.md index 5a5c9c0..b497955 100644 --- a/Documentation/Architecture/ResourceLimits.md +++ b/Documentation/Architecture/ResourceLimits.md @@ -121,3 +121,14 @@ so retained reusable scratch is zero. Live owned capacities still charge retainedBytes. Scalar scanning and immutable plan-local regex sharing remain the qualified choices; no SIMD or prefilter optimization is claimed. Native performance observations are separate from the logical policy in [performance notes](../Performance/README.md). + +## Optional authored DSL boundary (P1.2) + +JSONValueDSL and JSONSchemaDSL explicitly accept trusted authored staging. Their +callbacks, content collection and flat IR assembly are outside the checked phase; +there is no staging-retention, caller-instruction, RSS or whole-DSL cumulative +claim. This is an authoring exception, not a new untrusted-input operation. +The iterative finalizer shares one existing ledger through schema-document +admission, without nested resets. Returned values satisfy their finite profile. +These additional operations do not change the 49 metrics, weights or defaults. +See [decisions and qualification](DualDSL/Decisions.md). diff --git a/Documentation/CI/README.md b/Documentation/CI/README.md index 15091c0..b533eef 100644 --- a/Documentation/CI/README.md +++ b/Documentation/CI/README.md @@ -8,12 +8,12 @@ are recorded; macOS/SDK 27 and Swift 6.4 remain minimums. Pushes to main, pull requests and manual dispatch run three lanes: - Native: public inventory, manifest/dependency graph, release build, debug and - release Swift Testing, five-product example, rooted JSON/JSONSchema consumer, + release Swift Testing, public multi-product example, rooted JSON/JSONSchema consumer, public cap tests and pinned independent suites under an external timeout. - Safety: full Address Sanitizer tests, targeted shared-state Thread Sanitizer tests, and strict memory safety compilation with warnings as errors. - Documentation: public symbol graphs, complete authored API/parameter comments, - executed README examples, five native DocC catalogs with warnings as errors, + executed README examples, eight product DocC catalogs plus the shared DSL structure reference with warnings as errors, native static-hosting transforms and site route/asset checks. Actions are pinned by commit. Jobs have read-only repository permissions and @@ -109,3 +109,18 @@ regex 12, streaming 14, patch 11 and portable HTML 61. Its public consumer requi remain required. The first failed inherited expectations are retained; no blanket nonzero/exit-zero replacement is used. Real receiving-app and physical-device UI observations remain separate from automated SDK/API and portable execution. + +## Dual DSL development qualification + +`python3 Scripts/ci.py --lane dsl` runs all 47 actual-engine DSL Swift Testing +functions in Debug and Release, six intended-domain compiler rejections in both +configurations, qualified-name collision probes, native compiler scaling experiments +and the separate public consumer in both configurations. Native/Linux lanes also +require the DSL imports and consumer. Root discovery is 343 functions on Mac and +329 on Linux/WASI, in eight exact bundles; all 173 parameter invocations and 49 +baseline metric probes remain unchanged. Native shared-state TSan discovery is +13 functions (12 portable), including independent DSL finalization with shared plans. + +The P1.2 compiler experiment builds local variadic and pairwise builder modules +against the same real engine. Measurements retain host load and compiler RSS; +these do not imply runtime, staging-retention or caller-work guarantees. diff --git a/Documentation/DocumentationTooling.md b/Documentation/DocumentationTooling.md index b46024c..ffe2a07 100644 --- a/Documentation/DocumentationTooling.md +++ b/Documentation/DocumentationTooling.md @@ -1,7 +1,7 @@ # Building and maintaining the DocC catalogs Swift source comments are the API documentation authority. Native compiler symbol -graphs supply the declarations and links for six Swift DocC catalogs. Each catalog +graphs supply the declarations and links for eight public-product Swift DocC catalogs plus a shared DSL structure reference. Each catalog combines the product reference with curated Topics and a focused usage guide. See the [Swift DocC documentation](https://www.swift.org/documentation/docc/). @@ -19,7 +19,7 @@ python3 Scripts/ci.py --lane docs The lane records native preflight, extracts fresh public symbol graphs, requires summaries and named-parameter documentation on every authored public declaration, checks README Swift fences against their executable consumer source, runs that -consumer, and compiles all six DocC catalogs with warnings as errors. Zero public +consumer, and compiles all nine DocC catalogs with warnings as errors. Zero public symbols, missing comments, stale examples or a failed catalog fail the lane. | Output | Purpose | @@ -33,9 +33,9 @@ symbols, missing comments, stale examples or a failed catalog fail the lane. | `.build/handoff/docc/symbols/` | Public compiler symbol graphs grouped by product | | `.build/handoff/docc/coverage.json` | Counts and documentation-coverage failures | | `.build/handoff/docc/receipt.json` | Commands, toolchain, counts, exits and diagnostics | -| `.build/handoff/docc/compiled-catalogs.tar.gz` | All six compiled catalogs with their exact native filenames | +| `.build/handoff/docc/compiled-catalogs.tar.gz` | All nine compiled catalogs with their exact native filenames | | `.build/handoff/docc/compiled-catalogs.MANIFEST.sha256` | Independently verifiable hashes for every archived catalog file | -| `.build/handoff/pages/site/` | Static site, landing page and all six references under the project base path | +| `.build/handoff/pages/site/` | Static site, landing page and eight public-product references and the supporting DSL reference under the project base path | | `.build/handoff/pages/receipt.json` | Native transformations, input/output hashes and route/asset verification | Open a `.doccarchive` in Xcode for the compiled reference. To preview a source @@ -64,7 +64,7 @@ The manifest and receipt preserve file-level and archive-level digests. The docs lane uses native `docc process-archive transform-for-static-hosting` to prepare each qualified archive under `/Swift-JSON/`. A shared landing -page links all six references and guides. The build verifies product/guide routes, +page links eight public-product references and the supporting DSL reference and guides. The build verifies product/guide routes, local HTML links and assets, rejects private-path/credential markers and symlinks, and records a file manifest. Only the generated site is packaged for Pages; source graphs, command logs and private maintainer records are not website content. diff --git a/Documentation/Qualification/DualDSL/README.md b/Documentation/Qualification/DualDSL/README.md new file mode 100644 index 0000000..22f78af --- /dev/null +++ b/Documentation/Qualification/DualDSL/README.md @@ -0,0 +1,24 @@ +# Dual DSL P1.2 qualification + +This development wave qualifies actual engine behavior; the input's Linux 6.2.1 shims +are neither production source nor conformance evidence. See the +[plan](../../Architecture/DualDSL/Plan.md), [decisions](../../Architecture/DualDSL/Decisions.md) +and [progress](../../Architecture/DualDSL/Progress.json). + +| Contract | Regression evidence | +| --- | --- | +| Exact number/scalar authority and no silent merge | JSONDSLTests dslV01/V02/V04/V05; actual core constructors/comparisons | +| Omission, null, empty and Boolean schemas | dslV06/V07/V08And09; public compiler/evaluator | +| No inferred schema semantics | dslV10–V17, manual raw/annotation/verdict parity | +| Whole-root finalization ceilings and terminal failure | ResourceLifecycleTests; schema admission shares the same finalizer | +| Entry/inner cancellation and no successful publication | deterministic dslV19 tests with no sleeps | +| Iterative staging lifetime and depth boundary | 5000 staged levels rejected at finite depth; accepted depth 128 | +| Immutable independent finalization/plan invocations | dslSharedFinalizationAndPlansAreInvocationOwned | +| Compile-time domain exclusions and scaling | six original negative fixtures plus the G4 native harness | +| Public module direction, docs and consumer | production manifest checks, native DocC and Examples/DualDSL | + +V-03 is a compiler-negative assertion, not a runtime test. V-18/V-19 are actual +resource/cancellation tests. V-20 is repeated exact raw, verdict and annotation parity +across manual and DSL paths. Official JSON/schema suites and their policy exclusions +remain unchanged. Test counts, toolchains, source pins and receipts are reported after +execution, not inferred from this mapping. No gate is closed by this document alone. diff --git a/Documentation/README.md b/Documentation/README.md index 44892ae..d603e2f 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -51,3 +51,11 @@ Original code is Apache-2.0. See the [license](../LICENSE), [notice](../NOTICE), [adaptation manifest](Architecture/ExtractionManifest.json) and [pinned inputs](Architecture/UpstreamPins.json). Qualification inputs are separate from the empty library dependency graph. + +## Optional authored DSLs (P1.2 development) + +- [Integration plan and source boundary](Architecture/DualDSL/Plan.md) +- [Resource, naming and compiler decisions](Architecture/DualDSL/Decisions.md) +- [Real-engine acceptance mapping](Qualification/DualDSL/README.md) +- [Typed value guide](../Sources/JSONValueDSL/Documentation.docc/AuthoredValues.md) +- [Typed schema guide](../Sources/JSONSchemaDSL/Documentation.docc/AuthoredSchemas.md) diff --git a/Examples/Consumer/Package.swift b/Examples/Consumer/Package.swift index 29ce69a..a8c55af 100644 --- a/Examples/Consumer/Package.swift +++ b/Examples/Consumer/Package.swift @@ -13,7 +13,9 @@ let package = Package( .product(name: "JSONStreaming", package: "Swift-JSON"), .product(name: "JSONPatch", package: "Swift-JSON"), .product(name: "JSONHTML", package: "Swift-JSON"), - .product(name: "JSONBridges", package: "Swift-JSON") + .product(name: "JSONBridges", package: "Swift-JSON"), + .product(name: "JSONValueDSL", package: "Swift-JSON"), + .product(name: "JSONSchemaDSL", package: "Swift-JSON") ])], swiftLanguageModes: [.v6] ) diff --git a/Examples/Consumer/Sources/Consumer/READMEExamples.swift b/Examples/Consumer/Sources/Consumer/READMEExamples.swift index 124f41e..c9007d1 100644 --- a/Examples/Consumer/Sources/Consumer/READMEExamples.swift +++ b/Examples/Consumer/Sources/Consumer/READMEExamples.swift @@ -1,6 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // Compiled README examples; checked by the documentation lane. import JSONBridges +import JSONValueDSL +import JSONSchemaDSL import JSON import Foundation import JSONSchema @@ -41,6 +43,22 @@ func runREADMEExamples() throws { let bridgeRounded = try Double(jsonNumber: bridgeTenth, policy: .rounded) precondition(bridgeRounded == 0.1) + let authoredTenth = try JSONNumber(parsing: "0.1") + let authoredJSON = try JSONValueDSL.object { + Field("amount", exactNumber: authoredTenth) + Field.array("nested") { Element.array { Element(1); Element(2) } } + } + let authoredSchema = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { + Property("amount") { Schema.type(.number); Schema.minimum(authoredTenth) } + } + Schema.required("amount") + } + let authoredPlan = try JSONSchemaCompiler().compile(authoredSchema) + let authoredResult = try JSONSchemaValidator().validate(authoredJSON, against: authoredPlan) + precondition(authoredResult.isValid) + let parser = JSONParser() let value = try parser.parse(#"{"count":9007199254740993,"note":null}"#) let count = try JSONPointer(parsing: "/count").resolve(in: value) diff --git a/Examples/DualDSL/Package.swift b/Examples/DualDSL/Package.swift new file mode 100644 index 0000000..24ca6df --- /dev/null +++ b/Examples/DualDSL/Package.swift @@ -0,0 +1,15 @@ +// swift-tools-version: 6.4 +// SPDX-License-Identifier: Apache-2.0 +import PackageDescription +let package = Package( + name: "DualDSLConsumer", + platforms: [.macOS("27.0"), .iOS("27.0")], + dependencies: [.package(name: "Swift-JSON", path: "../..")], + targets: [.executableTarget(name: "DualDSLConsumer", dependencies: [ + .product(name: "JSON", package: "Swift-JSON"), + .product(name: "JSONSchema", package: "Swift-JSON"), + .product(name: "JSONValueDSL", package: "Swift-JSON"), + .product(name: "JSONSchemaDSL", package: "Swift-JSON") + ])], + swiftLanguageModes: [.v6] +) diff --git a/Examples/DualDSL/README.md b/Examples/DualDSL/README.md new file mode 100644 index 0000000..f2f9704 --- /dev/null +++ b/Examples/DualDSL/README.md @@ -0,0 +1,11 @@ +# Actual-engine Dual DSL consumer + +Run `swift run --package-path Examples/DualDSL DualDSLConsumer` on the supported +Swift 6.4 toolchain. This separate package imports only public products, not +JSONDSLCore, private meters or either signature shim. It checks exact integers, +explicit decimals, scalar-distinct keys, nested arrays, an explicitly selected +local definition, positive/negative verdicts and missing-resource operational failure. + +The builder is for trusted authored configuration. Staging and caller computation +are not budgeted; finalization and schema-document admission use finite limits. +This consumer is not a whole-pipeline resource or downstream protocol claim. diff --git a/Examples/DualDSL/Sources/DualDSLConsumer/main.swift b/Examples/DualDSL/Sources/DualDSLConsumer/main.swift new file mode 100644 index 0000000..3ebd16c --- /dev/null +++ b/Examples/DualDSL/Sources/DualDSLConsumer/main.swift @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: Apache-2.0 +import JSON +import JSONSchema +import JSONSchemaDSL +import JSONValueDSL + +let tenth = try JSONNumber(parsing: "0.1") +let instance = try JSONValueDSL.object { + Field("id", UInt64(9_007_199_254_740_993)) + Field("amount", exactNumber: tenth) + Field("é", 1) + Field("e\u{301}", 2) + Field.array("nested") { + Element.array { + Element(1) + Element(2) + } + } +} +let schema = try JSONSchemaDSL.document { + Schema.schemaURI("https://json-schema.org/draft/2020-12/schema") + Schema.type(.object) + Schema.properties { + Property("id") { Schema.type(.integer) } + Property("amount") { Schema.reference("#/$defs/Amount") } + } + Schema.required("id", "amount") + Schema.definitions { + Definition("Amount") { + Schema.type(.number) + Schema.minimum(tenth) + Schema.multipleOf(tenth) + } + } +} +let plan = try JSONSchemaCompiler().compile(schema) +let validator = JSONSchemaValidator() +let validResult = try validator.validate(instance, against: plan) +precondition(validResult.isValid) +let elevenHundredths = try JSONNumber(parsing: "0.11") +let invalid = try JSONValueDSL.object { + Field("id", 1) + Field("amount", exactNumber: elevenHundredths) +} +let invalidResult = try validator.validate(invalid, against: plan) +precondition(!invalidResult.isValid) +let absent = try JSONValueDSL.object { Field("id", 1) } +let absentResult = try validator.validate(absent, against: plan) +precondition(!absentResult.isValid) +precondition(instance.objectValue?["é"] == 1 && instance.objectValue?["e\u{301}"] == 2) +precondition(instance.objectValue?["nested"]?.arrayValue?.count == 1) +let missing = try JSONSchemaDSL.document { Schema.reference("https://not-supplied.invalid/schema") } +var observedOperational = false +do { _ = try JSONSchemaCompiler().compile(missing) } catch let error as JSONSchemaCompilationFailure { + precondition(error.category == .missingResource) + observedOperational = true +} +precondition(observedOperational) +let bytes = try JSONWriter().write(instance) +let restored = try JSONParser().parse(bytes) +precondition(restored == instance) +print("DUAL_DSL_CONSUMER passed valid=1 invalid=2 operational=1 exact_keys=2 nested_arrays=1") diff --git a/Package.swift b/Package.swift index e8a0209..8aa14d1 100644 --- a/Package.swift +++ b/Package.swift @@ -11,10 +11,16 @@ let package = Package( .library(name: "JSONStreaming", targets: ["JSONStreaming"]), .library(name: "JSONPatch", targets: ["JSONPatch"]), .library(name: "JSONHTML", targets: ["JSONHTML"]), - .library(name: "JSONBridges", targets: ["JSONBridges"]) + .library(name: "JSONBridges", targets: ["JSONBridges"]), + .library(name: "JSONValueDSL", targets: ["JSONValueDSL"]), + .library(name: "JSONSchemaDSL", targets: ["JSONSchemaDSL"]) ], targets: [ .target(name: "JSON"), + .target(name: "JSONDSLCore", dependencies: ["JSON"]), + .target(name: "JSONValueDSL", dependencies: ["JSON", "JSONDSLCore"]), + .target(name: "JSONSchemaDSL", dependencies: ["JSON", "JSONSchema", "JSONDSLCore"]), + .testTarget(name: "JSONDSLTests", dependencies: ["JSON", "JSONSchema", "JSONDSLCore", "JSONValueDSL", "JSONSchemaDSL"]), .target(name: "JSONBridges", dependencies: ["JSON"]), .testTarget(name: "JSONBridgesTests", dependencies: ["JSONBridges", "JSON"]), .target(name: "JSONRegexRuntime", dependencies: ["JSON"]), diff --git a/README.md b/README.md index 5c37627..a370dee 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,8 @@ Choose the products your application needs: | **JSONSchema** | Draft 2020-12 compilation/evaluation, offline registries, bounded regex, annotations and raw declaration inspection | | **JSONStreaming** | Pull syntax events and values, strict NDJSON, root-array elements and awaited output chunks | | **JSONHTML** | Exact HTML, offline exploration and immutable native transfer/export (1.3 development) | +| **JSONValueDSL** | Opt-in typed authored objects/arrays with exact values and finite finalization (P1.2 development) | +| **JSONSchemaDSL** | Opt-in typed authored Draft 2020-12 declarations using the existing engine (P1.2 development) | | **JSONBridges** | Opt-in native integer, Double and Foundation Decimal conversions (E2 development) | | **JSONPatch** | Staged RFC 6902 JSON Patch and RFC 7396 Merge Patch | @@ -100,7 +102,7 @@ Then add products to your target dependencies: Add `JSONStreaming`, `JSONPatch` and the 1.3 development product `JSONHTML` in the same way when needed. A local checkout can use `.package(path: "../Swift-JSON")`. The requirement above accepts compatible 1.x -releases. See the [six-product consumer](Examples/Consumer) for a complete buildable +releases. See the [eight-product consumer](Examples/Consumer) for a complete buildable manifest. The website tracks `main`; release assets include compiled DocC catalogues for the exact released source. @@ -137,6 +139,47 @@ text is distinct from its exact binary rational. Read the [numeric fidelity guide](Sources/JSONBridges/Documentation.docc/NumericFidelity.md) and [before/after crosswalk](Documentation/Ergonomics/README.md). +## Typed authored DSLs (P1.2 development) + +Select the optional `JSONValueDSL` and `JSONSchemaDSL` products explicitly. They add +syntax over the same exact model and schema engine; neither is imported by core. +These APIs are development additions on main's feature line, not additions to older tags. + +```swift +import JSONValueDSL +import JSONSchemaDSL + +let authoredTenth = try JSONNumber(parsing: "0.1") +let authoredJSON = try JSONValueDSL.object { + Field("amount", exactNumber: authoredTenth) + Field.array("nested") { Element.array { Element(1); Element(2) } } +} +let authoredSchema = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { + Property("amount") { Schema.type(.number); Schema.minimum(authoredTenth) } + } + Schema.required("amount") +} +let authoredPlan = try JSONSchemaCompiler().compile(authoredSchema) +let authoredResult = try JSONSchemaValidator().validate(authoredJSON, against: authoredPlan) +precondition(authoredResult.isValid) +``` + +This syntax is for **trusted authored configuration**. Callbacks, wrapper collection +and staging are unmetered. Only iterative finalization and schema-document admission +share a finite ledger; there is no staging/RSS bound or whole-DSL cumulative report. +Use checked accumulators or the parser for dynamic untrusted input. Exact duplicates +throw, scalar-distinct keys remain distinct, omitted branches emit nothing, and arrays +expand only through explicit `Elements(contentsOf:)`. There is no implicit Float/Double +bridge, requiredness inference, default application or custom schema validator. + +See the [value guide](Sources/JSONValueDSL/Documentation.docc/AuthoredValues.md), +[schema guide](Sources/JSONSchemaDSL/Documentation.docc/AuthoredSchemas.md), +[public-only consumer](Examples/DualDSL) and [qualification scope](Documentation/Qualification/DualDSL). +The shared JSONDSLCore module has no standalone product; its typed composition contracts +support the two optional APIs. Typed schema synonyms and an umbrella import remain deferred. + ## Parse, inspect and write exact values ```swift diff --git a/Scripts/build_documentation.py b/Scripts/build_documentation.py index 779a5a3..f0ab717 100644 --- a/Scripts/build_documentation.py +++ b/Scripts/build_documentation.py @@ -28,7 +28,7 @@ def run(command, log, timeout): def package_catalogs(output): """Preserve native DocC filenames inside an artifact with a portable outer name.""" records = [] - for product in documentation_catalog.PRODUCTS: + for product in documentation_catalog.CATALOGS: catalog = output / (product + '.doccarchive') paths = sorted(catalog.rglob('*')) if not any(p.is_file() for p in paths): @@ -60,7 +60,7 @@ def package_catalogs(output): 'bytes': archive.stat().st_size, 'verified_files': len(records), 'manifest': str(manifest.relative_to(ROOT)), 'manifest_sha256': hashlib.sha256(manifest.read_bytes()).hexdigest(), - 'policy': 'Six native DocC archives; exact internal filenames, sorted entries and normalized tar/gzip metadata.'} + 'policy': 'Eight product DocC archives plus the shared DSL structure reference; exact internal filenames, sorted entries and normalized tar/gzip metadata.'} def main(): @@ -89,7 +89,7 @@ def main(): receipt['readme_examples'] = dict(run(command, output / 'readme-examples.log', 900), executable_fences=example_count) if receipt['readme_examples']['exit_code']: raise ValueError('Compiled README examples failed') - for product in documentation_catalog.PRODUCTS: + for product in documentation_catalog.CATALOGS: graphs = output / 'symbols' / product if graphs.exists(): shutil.rmtree(graphs) diff --git a/Scripts/build_documentation_site.py b/Scripts/build_documentation_site.py index fa1c658..c55d5a1 100644 --- a/Scripts/build_documentation_site.py +++ b/Scripts/build_documentation_site.py @@ -13,7 +13,7 @@ import sys import urllib.parse -from documentation_catalog import PRODUCTS +from documentation_catalog import PRODUCTS, CATALOGS from preflight import collect ROOT = pathlib.Path(__file__).resolve().parents[1] @@ -25,14 +25,18 @@ 'JSONStreaming': ('Completion and backpressure', 'completionandbackpressure'), 'JSONPatch': ('Choosing and applying patches', 'applyingpatches'), 'JSONHTML': ('Exact interactive HTML', 'interactiverendering'), - 'JSONBridges': ('Opt-in native conversions', 'numericfidelity')} + 'JSONBridges': ('Opt-in native conversions', 'numericfidelity'), + 'JSONValueDSL': ('Trusted exact value authoring', 'authoredvalues'), + 'JSONSchemaDSL': ('Authored schemas, engine validation', 'authoredschemas')} DESCRIPTIONS = { 'JSON': 'Exact values, strict UTF-8, native Codable, Pointer, presence and finite resource reports.', 'JSONSchema': 'Draft 2020-12, explicit offline registries, immutable plans, annotations and bounded regex.', 'JSONStreaming': 'Pull events and values, strict NDJSON, root-array completion and awaited output chunks.', 'JSONPatch': 'Transactional RFC 6902 JSON Patch and RFC 7396 Merge Patch with exact value semantics.', 'JSONHTML': 'Exact standalone HTML with offline disclosure/search and native-byte copy/download.', - 'JSONBridges': 'Opt-in trusted integer construction and policy-explicit Double and Foundation Decimal projection.'} + 'JSONBridges': 'Opt-in trusted integer construction and policy-explicit Double and Foundation Decimal projection.', + 'JSONValueDSL': 'Typed authored objects and arrays with exact values, omission and finite finalization.', + 'JSONSchemaDSL': 'Typed authored Draft 2020-12 declarations, compiled and evaluated by the existing engine.'} class Links(HTMLParser): @@ -99,7 +103,7 @@ def landing(commit):
Public Swift documentation

Exact JSON. Clear contracts.

-

Keep decimal values exact, Unicode scalar keys distinct and resource use explicit. Explore five Swift libraries that carry those semantics from input bytes to validated, transformed and encoded output.

+

Keep decimal values exact, Unicode scalar keys distinct and resource use explicit. Explore eight Swift libraries that carry those semantics from input bytes to validated, transformed and encoded output.

Swift 6.4+ · Swift language mode 6 · macOS/SDK 27+ · No package dependencies

{''.join(cards)}

Start with the contract

@@ -171,7 +175,7 @@ def main(): if site.exists(): shutil.rmtree(site) site.mkdir() - for product in PRODUCTS: + for product in CATALOGS: command = ['xcrun', 'docc', 'process-archive', 'transform-for-static-hosting', str(catalogs / (product + '.doccarchive')), '--output-path', str(site / product), '--hosting-base-path', BASE_PATH + '/' + product] diff --git a/Scripts/ci.py b/Scripts/ci.py index d1e1d03..ac3fe7a 100644 --- a/Scripts/ci.py +++ b/Scripts/ci.py @@ -7,7 +7,7 @@ from testing_events import read_events, ROOT_PARAMETER_CASES ROOT = pathlib.Path(__file__).resolve().parents[1] -SHARED_TESTS = 'independentCodecFacadesAndExactValuesCanBeSharedAcrossTasks|concurrentSchemaEvaluationsHaveExclusiveDynamicRegexAndAnnotationState|sharedRegexProgramHasExclusiveConcurrentSearchState|immutableIndexedObjectCanBeSharedAcrossTasks|qaSharedPayloadAndRootHaveIndependentConcurrentReadScopes|sha256InputCapacityAndConcurrentInvocationsRemainIndependent|sharedFormattedHTMLRendererHasIndependentConcurrentInvocations|sharedAnnotatedDocumentRendererHasIndependentConcurrentInvocations|sharedExportPreparationsHaveIndependentConcurrentState|applePDFSimultaneousJobsHaveIndependentStateAndCancellation|e2SharedBridgeInputsHaveInvocationOwnedState|e2SharedCompiledPlanFacadeHasIndependentInvocationState' +SHARED_TESTS = 'independentCodecFacadesAndExactValuesCanBeSharedAcrossTasks|concurrentSchemaEvaluationsHaveExclusiveDynamicRegexAndAnnotationState|sharedRegexProgramHasExclusiveConcurrentSearchState|immutableIndexedObjectCanBeSharedAcrossTasks|qaSharedPayloadAndRootHaveIndependentConcurrentReadScopes|sha256InputCapacityAndConcurrentInvocationsRemainIndependent|sharedFormattedHTMLRendererHasIndependentConcurrentInvocations|sharedAnnotatedDocumentRendererHasIndependentConcurrentInvocations|sharedExportPreparationsHaveIndependentConcurrentState|applePDFSimultaneousJobsHaveIndependentStateAndCancellation|e2SharedBridgeInputsHaveInvocationOwnedState|e2SharedCompiledPlanFacadeHasIndependentInvocationState|dslSharedFinalizationAndPlansAreInvocationOwned' R0_TESTS = 'readerProbe|indexProbes|duplicateRecognitionPrecedesValueAndClosingSyntax' def snapshot(): @@ -25,7 +25,7 @@ def commands(lane, output): # Root behavior/corpora remain required. SwiftData and Apple SDK/lifetime # probes are separate Apple acceptance; they never become Linux passes. return [c for c in commands('native', ROOT / output) - if not any(x in c for x in ['Tools/MobileQualification', '--mode'])] + [ + if not any(x in c for x in ['Tools/MobileQualification', 'Scripts/qualify_release_1_1.py'])] + [ ['python3', '-B', 'Scripts/qualify_linux_reproduction.py', '--output', str(output / 'reproduction')]] if lane == 'linux-safety': # Every behavior case uses Swift Testing. Do not start the generated @@ -53,6 +53,14 @@ def commands(lane, output): ['swift', 'run', '-c', 'release', '--package-path', 'Tools/JSONHTMLBrowser', 'BrowserFixtures', str(output / 'fixtures')], ['python3', '-B', 'Scripts/qualify_html_browser.py', '--fixtures', str(output / 'fixtures'), '--output', str(output / 'browser')], ] + if lane == 'dsl': + return [ + ['swift', 'test', '--filter', 'JSONDSLTests'], + ['swift', 'test', '-c', 'release', '--filter', 'JSONDSLTests'], + ['python3', '-B', 'Scripts/qualify_dual_dsl.py', '--mode', 'compiler', '--output', str(output / 'compiler')], + ['swift', 'run', '--package-path', 'Examples/DualDSL', 'DualDSLConsumer'], + ['swift', 'run', '-c', 'release', '--package-path', 'Examples/DualDSL', 'DualDSLConsumer'], + ] if lane == 'native': return [ ['python3', '-B', 'Scripts/public_check.py'], @@ -65,6 +73,8 @@ def commands(lane, output): ['python3', '-B', 'Scripts/qualify_release_1_1.py', '--mode', 'reader', '--output', str(output / 'reader.json')], ['swift', 'run', '-c', 'release', '--package-path', 'Examples/Consumer', 'Consumer'], ['python3', '-B', 'Scripts/qualify_ergonomics.py'], + ['python3', '-B', 'Scripts/qualify_dual_dsl.py', '--mode', 'imports', '--output', str(output / 'dsl-imports')], + ['swift', 'run', '-c', 'release', '--package-path', 'Examples/DualDSL', 'DualDSLConsumer'], ['swift', 'test', '--package-path', 'Tools/MobileQualification'], ['swift', 'run', '-c', 'release', '--package-path', 'Tools/MobileQualification', 'MobileQualification'], ['swift', 'test', '--package-path', 'Tools/MCPReadiness'], @@ -113,8 +123,10 @@ def check_result(command, code, log, events=None): if events is not None: counts = events['bundle_counts'] if command[:2] == ['swift', 'test']: - expected = [38] if 'export|Export|apple' in command else [14] if 'Tools/WasmAudit' in command else [2, 3, 3, 11] if 'qa' in command else [7] if R0_TESTS in command else [3] if 'Tools/MCPReadiness' in command or 'Tools/MobileQualification' in command else [1] if 'Tools/Qualification' in command else [1, 1, 2, 3 if sys.platform == 'linux' else 4, 4] if 'thread' in command else sorted([10, 11, 12, 14, 61 if sys.platform == 'linux' else 75, 55, 119]) + expected = [47] if 'JSONDSLTests' in command else [38] if 'export|Export|apple' in command else [14] if 'Tools/WasmAudit' in command else [2, 3, 3, 11] if 'qa' in command else [7] if R0_TESTS in command else [3] if 'Tools/MCPReadiness' in command or 'Tools/MobileQualification' in command else [1] if 'Tools/Qualification' in command else [1, 1, 1, 2, 3 if sys.platform == 'linux' else 4, 4] if 'thread' in command else sorted([10, 11, 12, 14, 47, 61 if sys.platform == 'linux' else 75, 55, 119]) passed = passed and sorted(counts) == expected + if events is not None and '--filter' not in command and not any(x.startswith('Tools/') for x in command): + passed = passed and events['module_function_counts'] == {'JSONTests': 119, 'JSONBridgesTests': 10, 'JSONSchemaTests': 55, 'JSONRegexRuntimeTests': 12, 'JSONStreamingTests': 14, 'JSONPatchTests': 11, 'JSONHTMLTests': 61 if sys.platform == 'linux' else 75, 'JSONDSLTests': 47} if '--filter' not in command and not any(x.startswith('Tools/') for x in command): passed = passed and (events['parameterized_functions'] == ROOT_PARAMETER_CASES if events is not None else sum(int(n) for n in re.findall(r'with (\d+) test cases passed', log)) == 173) if 'Tools/Qualification' in command: @@ -124,10 +136,13 @@ def check_result(command, code, log, events=None): passed = passed and len(probes) == 49 and dict(probes) == expected_probes if command == ['swift', 'package', 'dump-package'] and passed: d = json.loads(log) - passed = sorted(p['name'] for p in d['products']) == ['JSON', 'JSONBridges', 'JSONHTML', 'JSONPatch', 'JSONSchema', 'JSONStreaming'] and not d['dependencies'] and d['swiftLanguageVersions'] == ['6'] and d['toolsVersion']['_version'] == '6.4.0' and d['platforms'] == [{'options': [], 'platformName': 'macos', 'version': '27.0'}, {'options': [], 'platformName': 'ios', 'version': '27.0'}] - passed = passed and {p['name']: p['targets'] for p in d['products']} == {name: [name] for name in ['JSON', 'JSONSchema', 'JSONStreaming', 'JSONPatch', 'JSONHTML', 'JSONBridges']} + passed = sorted(p['name'] for p in d['products']) == ['JSON', 'JSONBridges', 'JSONHTML', 'JSONPatch', 'JSONSchema', 'JSONSchemaDSL', 'JSONStreaming', 'JSONValueDSL'] and not d['dependencies'] and d['swiftLanguageVersions'] == ['6'] and d['toolsVersion']['_version'] == '6.4.0' and d['platforms'] == [{'options': [], 'platformName': 'macos', 'version': '27.0'}, {'options': [], 'platformName': 'ios', 'version': '27.0'}] + passed = passed and {p['name']: p['targets'] for p in d['products']} == {name: [name] for name in ['JSON', 'JSONSchema', 'JSONStreaming', 'JSONPatch', 'JSONHTML', 'JSONBridges', 'JSONValueDSL', 'JSONSchemaDSL']} targets = {t['name']: t for t in d['targets']} - passed = passed and set(targets) == {'JSON', 'JSONBridges', 'JSONSchema', 'JSONStreaming', 'JSONPatch', 'JSONHTML', 'JSONRegexRuntime', 'JSONTests', 'JSONBridgesTests', 'JSONSchemaTests', 'JSONStreamingTests', 'JSONPatchTests', 'JSONHTMLTests', 'JSONRegexRuntimeTests'} and targets['JSONHTML']['dependencies'] == [{'byName': ['JSON', None]}] and targets['JSONBridges']['dependencies'] == [{'byName': ['JSON', None]}] + passed = passed and set(targets) == {'JSON', 'JSONBridges', 'JSONSchema', 'JSONStreaming', 'JSONPatch', 'JSONHTML', 'JSONRegexRuntime', 'JSONDSLCore', 'JSONValueDSL', 'JSONSchemaDSL', 'JSONDSLTests', 'JSONTests', 'JSONBridgesTests', 'JSONSchemaTests', 'JSONStreamingTests', 'JSONPatchTests', 'JSONHTMLTests', 'JSONRegexRuntimeTests'} and targets['JSONHTML']['dependencies'] == [{'byName': ['JSON', None]}] and targets['JSONBridges']['dependencies'] == [{'byName': ['JSON', None]}] + passed = passed and not targets['JSON']['dependencies'] + for name, dependencies in [('JSONDSLCore', ['JSON']), ('JSONValueDSL', ['JSON', 'JSONDSLCore']), ('JSONSchemaDSL', ['JSON', 'JSONSchema', 'JSONDSLCore'])]: + passed = passed and targets[name]['dependencies'] == [{'byName': [name, None]} for name in dependencies] if command == ['swift', 'package', 'show-dependencies', '--format', 'json'] and passed: passed = json.loads(log)['dependencies'] == [] if command[:2] == ['swift', 'run'] and 'Tools/MobileQualification' in command: @@ -136,6 +151,11 @@ def check_result(command, code, log, events=None): passed = passed and 'TESTING_EVENT_RECEIPTS passed cases=19' in log.splitlines() if command[:3] == ['python3', '-B', 'Scripts/qualify_ergonomics.py']: passed = passed and 'ERGONOMICS_COMPILER passed commands=8 guide_fences=3' in log.splitlines() + if command[:3] == ['python3', '-B', 'Scripts/qualify_dual_dsl.py']: + mode = command[command.index('--mode') + 1] + passed = passed and ('DUAL_DSL_COMPILER passed negatives=12 configurations=2 mode=' + mode) in log.splitlines() + if command[:2] == ['swift', 'run'] and 'Examples/DualDSL' in command: + passed = passed and 'DUAL_DSL_CONSUMER passed valid=1 invalid=2 operational=1 exact_keys=2 nested_arrays=1' in log.splitlines() if command[:3] == ['python3', '-B', 'Scripts/verify_html_assets.py']: passed = passed and 'JSONHTML_ASSETS passed count=2' in log.splitlines() if 'BrowserFixtures' in command: @@ -146,7 +166,7 @@ def check_result(command, code, log, events=None): def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--lane', choices=['native', 'safety', 'docs', 'r0', 'qa', 'linux', 'linux-safety', 'wasm', 'browser', 'export'], required=True) + parser.add_argument('--lane', choices=['native', 'safety', 'docs', 'r0', 'qa', 'linux', 'linux-safety', 'wasm', 'browser', 'export', 'dsl'], required=True) parser.add_argument('--output') args = parser.parse_args() output = ROOT / (args.output or '.build/ci/' + args.lane) @@ -212,7 +232,7 @@ def save(): if receipt['status'] == 'passed' and args.lane == 'wasm': try: wasi = json.loads((output / 'probes/wasi.json').read_text()) - if wasi['status'] != 'passed' or wasi['root_counts'] != {'JSONTests':119,'JSONBridgesTests':10,'JSONSchemaTests':55,'JSONRegexRuntimeTests':12,'JSONStreamingTests':14,'JSONPatchTests':11,'JSONHTMLTests':61}: + if wasi['status'] != 'passed' or wasi['root_counts'] != {'JSONTests':119,'JSONBridgesTests':10,'JSONSchemaTests':55,'JSONRegexRuntimeTests':12,'JSONStreamingTests':14,'JSONPatchTests':11,'JSONHTMLTests':61,'JSONDSLTests':47}: raise ValueError('Missing WASI qualification boundary') receipt['materialized_wasi'] = {'path':'probes/wasi.json','sha256':hashlib.sha256((output / 'probes/wasi.json').read_bytes()).hexdigest()} except (OSError,KeyError,ValueError,TypeError) as error: diff --git a/Scripts/documentation_catalog.py b/Scripts/documentation_catalog.py index add1f6e..55680e8 100644 --- a/Scripts/documentation_catalog.py +++ b/Scripts/documentation_catalog.py @@ -7,7 +7,9 @@ import urllib.parse ROOT = pathlib.Path(__file__).resolve().parents[1] -PRODUCTS = ('JSON', 'JSONSchema', 'JSONStreaming', 'JSONPatch', 'JSONHTML', 'JSONBridges') +PRODUCTS = ('JSON', 'JSONSchema', 'JSONStreaming', 'JSONPatch', 'JSONHTML', 'JSONBridges', 'JSONValueDSL', 'JSONSchemaDSL') +SUPPORT_MODULES = ('JSONDSLCore',) +CATALOGS = PRODUCTS + SUPPORT_MODULES def public_symbols(graph_dir): @@ -16,7 +18,7 @@ def public_symbols(graph_dir): for graph in sorted(graph_dir.glob('*.json')): data = json.loads(graph.read_text()) module = data['module']['name'] - if module not in PRODUCTS: + if module not in CATALOGS: continue for symbol in data['symbols']: location = symbol.get('location') @@ -33,7 +35,7 @@ def public_symbols(graph_dir): raise ValueError('Non-public symbol in public graph') identifier = symbol['identifier']['precise'] symbols[identifier] = dict(symbol, module=module, source=relative.as_posix()) - for module in PRODUCTS: + for module in CATALOGS: if not any(s['module'] == module for s in symbols.values()): raise ValueError('No authored symbols for ' + module) return sorted(symbols.values(), key=lambda s: (s['module'], s['pathComponents'], s['identifier']['precise'])) @@ -56,7 +58,7 @@ def verify_comments(symbols): failures.append(label + ': missing parameter ' + name) return {'authored_public_symbols': len(symbols), 'documented_public_symbols': sum(bool(comment_text(s).strip()) for s in symbols), - 'products': {m: sum(s['module'] == m for s in symbols) for m in PRODUCTS}, + 'products': {m: sum(s['module'] == m for s in symbols) for m in CATALOGS}, 'policy': 'All authored public declarations and named parameters; compiler-synthesized declarations and extension containers excluded.', 'errors': failures} diff --git a/Scripts/qualify_dual_dsl.py b/Scripts/qualify_dual_dsl.py new file mode 100644 index 0000000..be13456 --- /dev/null +++ b/Scripts/qualify_dual_dsl.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +"""Qualify actual-engine DSL domain typing and reproducible compiler scaling experiments.""" +import argparse, datetime, hashlib, json, os, pathlib, platform, re, subprocess, sys, time + +ROOT = pathlib.Path(__file__).resolve().parents[1] +NEGATIVES = { + 'DefinitionInsideProperties.swift': ('Definition', 'JSONSchemaPropertiesContent'), + 'ElementInsideObject.swift': ('Element', 'JSONValueFieldsContent'), + 'FieldInsideSchema.swift': ('Field', 'JSONSchemaClausesContent'), + 'ImplicitFloatingPoint.swift': ('initializer', 'no exact matches'), + 'PropertyInsideDefinitions.swift': ('Property', 'JSONSchemaDefinitionsContent'), + 'SchemaClauseInsideArray.swift': ('SchemaClause', 'JSONValueElementsContent'), +} +POSITIVE = '''import JSONValueDSL +import JSONSchemaDSL +func authored(_ include: Bool, _ names: [String]) throws { + _ = try JSONValueDSL.object { + Field("id", UInt64.max) + if include { Field("flag", true) } else { Field("other", "value") } + Field.array("a") { for name in names { Element(name) }; Element.array { Element(1) } } + } + _ = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { for name in names { Property(name) { Schema.type(.string) } } } + Schema.definitions { Definition("n") { Schema.type(.integer) } } + Schema.anyOf { Rule(false); Rule { Schema.type(.object) } } + } +} +''' +QUALIFIED = '''import JSONValueDSL +import JSONSchemaDSL +enum Field {}; enum Element {}; enum Schema {}; enum Property {}; enum Rule {}; enum Definition {} +func qualifiedDeclarations() throws { + _ = try JSONValueDSL.object { + JSONValueDSL.Field("exact", UInt64.max) + JSONValueDSL.Field.array("items") { JSONValueDSL.Element(1) } + } + _ = try JSONSchemaDSL.document { + JSONSchemaDSL.Schema.type(.object) + JSONSchemaDSL.Schema.properties { + JSONSchemaDSL.Property("exact") { JSONSchemaDSL.Schema.type(.integer) } + } + JSONSchemaDSL.Schema.definitions { + JSONSchemaDSL.Definition("accept") { JSONSchemaDSL.Schema.anyOf { JSONSchemaDSL.Rule(true) } } + } + } +} +''' + + +def fixtures(): + result = {} + for width in (16, 64, 128, 256): + fields = '\n'.join('Field("f%d", %d)' % (n, n) for n in range(width)) + properties = '\n'.join('Property("f%d") { Schema.type(.string) }' % n for n in range(width)) + result['value-%d' % width] = 'import JSONValueDSL\nfunc fixture() throws -> Int { let value = try JSONValueDSL.object {\n' + fields + '\n}; return value.objectValue!.count }\n' + result['schema-%d' % width] = 'import JSONSchemaDSL\nfunc fixture() throws -> Int { let schema = try JSONSchemaDSL.document { Schema.properties {\n' + properties + '\n} }; return schema.raw.objectValue!["properties"]!.objectValue!.count }\n' + inner = 'Element(1)' + for _ in range(24): inner = 'Element.array { ' + inner + ' }' + result['nested-24'] = 'import JSONValueDSL\nfunc fixture() throws { _ = try JSONValueDSL.array { ' + inner + ' } }\n' + result['mixed-choices-loops'] = POSITIVE + result['inference'] = '''import JSONValueDSL +import JSONSchemaDSL +func fixture(_ include: Bool) throws { + let fields = ["a", "b", "c"] + _ = try JSONValueDSL.object { for (i, name) in fields.enumerated() { Field(name, UInt64(i)) }; if include { Field.object("nested") { Field("ok", true) } } } + _ = try JSONSchemaDSL.document { Schema.properties { for name in fields { Property(name) { if include { Schema.type(.string) } else { Schema.type(.null) } } } }; Schema.prefixItems { Rule { Schema.anyOf { Rule(true); Rule(false) } } } } +} +''' + return result + + +def partial_source(source): + start = source.index('public static func buildBlock') + opening = source.index('{', start); depth = 1; end = opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}'); end += 1 + replacement = '''public static func buildBlock() -> JSONContentEmpty { .init() } + public static func buildPartialBlock(first: First) -> First { first } + public static func buildPartialBlock(accumulated: Accumulated, next: Next) -> JSONContentTuple { .init(accumulated, next) }''' + domains = [('JSONValueFieldsContent', 'writeValueFields', 'JSONDSLMember'), ('JSONValueElementsContent', 'writeValueElements', 'JSONDSLNode'), ('JSONSchemaClausesContent', 'writeSchemaClauses', 'JSONDSLMember'), ('JSONSchemaPropertiesContent', 'writeSchemaProperties', 'JSONDSLMember'), ('JSONSchemaNodesContent', 'writeSchemaNodes', 'JSONDSLNode'), ('JSONSchemaDependenciesContent', 'writeSchemaDependencies', 'JSONDSLMember'), ('JSONSchemaPatternsContent', 'writeSchemaPatterns', 'JSONDSLMember'), ('JSONSchemaDefinitionsContent', 'writeSchemaDefinitions', 'JSONDSLMember'), ('JSONSchemaDependentSchemasContent', 'writeDependentSchemas', 'JSONDSLMember')] + empty = '\npublic struct JSONContentEmpty: ' + ', '.join(x[0] for x in domains) + ' { public init() {}\n' + empty += '\n'.join('public func '+method+'(to value: inout ['+kind+']) {}' for _,method,kind in domains) + '\n}\n' + return source[:start] + replacement + source[end:] + empty + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--mode', choices=['imports', 'compiler'], default='imports') + parser.add_argument('--output', default='.build/ci/dual-dsl') + args = parser.parse_args(); output = ROOT / args.output; output.mkdir(parents=True, exist_ok=True) + sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest() + record = dict(schema_version=1, status='running', mode=args.mode, source_commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip(), commands=[], measurements=[], source_inputs=[], started_utc=datetime.datetime.now(datetime.timezone.utc).isoformat()) + for directory in ['Sources/JSONDSLCore','Sources/JSONValueDSL','Sources/JSONSchemaDSL','Tests/CompileNegative/DualDSL']: + record['source_inputs'] += [dict(path=p.relative_to(ROOT).as_posix(),sha256=sha(p)) for p in sorted((ROOT/directory).rglob('*.swift'))] + consumer = (ROOT/'Examples/DualDSL/Sources/DualDSLConsumer/main.swift').read_text() + assert 'JSONDSLCore' not in consumer and 'JSONWorkMeter' not in consumer + guide_fences = 0 + for name in ['Sources/JSONValueDSL/Documentation.docc/AuthoredValues.md', 'Sources/JSONSchemaDSL/Documentation.docc/AuthoredSchemas.md']: + blocks = re.findall(r'```swift\n(.*?)\n```', (ROOT/name).read_text(), re.S) + assert len(blocks) == 1 and blocks[0] in consumer, name + guide_fences += 1 + record['guide_fences'] = guide_fences + def save(): (output/'receipt.json').write_text(json.dumps(record,indent=2)+'\n') + def run(name, command, rejection=(), timed=False, timeout=180): + log=output/(name+'.log'); start=time.monotonic() + measured=['/usr/bin/time','-l']+command if timed and sys.platform=='darwin' else command + with log.open('w') as stream: + try: code=subprocess.run(measured,cwd=ROOT,stdout=stream,stderr=subprocess.STDOUT,timeout=timeout).returncode + except subprocess.TimeoutExpired: code=None + elapsed=time.monotonic()-start; text=log.read_text(); bad_import=any(s in text for s in ["no such module",'cannot load module','unable to load standard library']) + passed=code==0 if not rejection else code==1 and not bad_import and all(s in text for s in rejection) + memory=re.search(r'(\d+)\s+maximum resident set size',text) + row=dict(name=name,command=measured,exit_code=code,expected_rejection=list(rejection),status='passed' if passed else 'failed',seconds=elapsed,maximum_resident_set_bytes=int(memory[1]) if memory else None,log=log.relative_to(ROOT).as_posix(),log_sha256=sha(log)) + record['commands'].append(row);save() + print(name,code,round(elapsed,3),row['status'],flush=True) + if not passed:raise ValueError('Compiler contract failed: '+name) + return row + try: + flags=['swiftc','-swift-version','6','-strict-concurrency=complete','-warnings-as-errors'] + if sys.platform=='darwin': + sdk=subprocess.check_output(['xcrun','--sdk','macosx','--show-sdk-path'],text=True).strip() + flags+=['-sdk',sdk,'-target',platform.machine()+'-apple-macosx27.0'] + paths={} + for config in ('debug','release'): + products=pathlib.Path(subprocess.check_output(['swift','build','-c',config,'--show-bin-path'],cwd=ROOT,text=True).strip()) + include=products/'Modules' if (products/'Modules').is_dir() else products + for module in ('JSON','JSONSchema','JSONDSLCore','JSONValueDSL','JSONSchemaDSL'): + p=include/(module+'.swiftmodule');assert p.is_file() or p.is_dir(),p + paths[config]=(products,include) + source=output/(config+'-public-positive.swift');source.write_text(POSITIVE) + run(config+'-public-positive',flags+['-I',str(include),'-typecheck',str(source)]) + source=output/(config+'-qualified-declarations.swift');source.write_text(QUALIFIED) + run(config+'-qualified-declarations',flags+['-I',str(include),'-typecheck',str(source)]) + for filename,tokens in NEGATIVES.items(): + source=ROOT/'Tests/CompileNegative/DualDSL'/filename + run(config+'-'+source.stem,flags+['-I',str(include),'-typecheck',str(source)],rejection=tokens) + if args.mode=='compiler': + if sys.platform!='darwin':raise ValueError('Native Xcode compiler comparison requires macOS') + products,include=paths['debug']; sources=fixtures() + record['host_observations']=dict(os=platform.platform(),load_average=os.getloadavg(),cpu_count=os.cpu_count(),policy='Concurrent host load is retained; elapsed/compiler RSS observations are not quiet-host, runtime, staging-retention or caller instruction guarantees') + for name,text in sources.items(): (output/(name+'.swift')).write_text(text) + identity=json.loads(subprocess.check_output(['swift','package','show-dependencies','--format','json'],cwd=ROOT,text=True))['identity'] + package=re.sub('[^a-zA-Z0-9_]','_',identity) + alt=output/'partial';alt.mkdir(exist_ok=True) + common=flags+['-package-name',package,'-parse-as-library','-emit-module'] + original=ROOT/'Sources/JSONDSLCore/JSONContent.swift'; changed=alt/'JSONContent.swift';changed.write_text(partial_source(original.read_text())) + core_sources=[str(changed)]+[str(p) for p in sorted((ROOT/'Sources/JSONDSLCore').glob('*.swift')) if p.name!='JSONContent.swift'] + run('partial-core-module',common+['-module-name','JSONDSLCore','-I',str(include)]+core_sources+['-emit-module-path',str(alt/'JSONDSLCore.swiftmodule')]) + for module in ['JSONValueDSL','JSONSchemaDSL']: + run('partial-'+module+'-module',common+['-module-name',module,'-I',str(alt),'-I',str(include)]+[str(p) for p in sorted((ROOT/'Sources'/module).glob('*.swift'))]+['-emit-module-path',str(alt/(module+'.swiftmodule'))]) + for strategy,includes in [('variadic',['-I',str(include)]),('partial',['-I',str(alt),'-I',str(include)])]: + for name in sources: + row=run(strategy+'-'+name,flags+includes+['-typecheck',str(output/(name+'.swift'))],timed=True) + record['measurements'].append(dict(strategy=strategy,fixture=name,source_sha256=sha(output/(name+'.swift')),seconds=row['seconds'],maximum_resident_set_bytes=row['maximum_resident_set_bytes'])) + record['comparison_scope']='Both strategies compile real DSL sources against real JSON/JSONSchema; alternative modules are local experiment outputs, not shipped code or semantic shims.' + assert len([c for c in record['commands'] if c['expected_rejection']])==12 + assert all(sha(ROOT/r['path'])==r['sha256'] for r in record['source_inputs']) + record['status']='passed'; record['negative_fixtures']=6;record['configurations']=2 + except (OSError,ValueError,KeyError,AssertionError,subprocess.SubprocessError) as error: + record['status']='failed';record['error']=str(error) + record['finished_utc']=datetime.datetime.now(datetime.timezone.utc).isoformat();save() + if record['status']=='passed':print('DUAL_DSL_COMPILER passed negatives=12 configurations=2 mode='+args.mode) + return 0 if record['status']=='passed' else 1 + +if __name__=='__main__':raise SystemExit(main()) diff --git a/Scripts/wasm_support.py b/Scripts/wasm_support.py index 392473e..fcd6a4c 100644 --- a/Scripts/wasm_support.py +++ b/Scripts/wasm_support.py @@ -7,7 +7,7 @@ ROOT = pathlib.Path(__file__).resolve().parents[1] SDK = 'swift-6.4.0-RELEASE_wasm' COUNTS = {'JSONTests': 119, 'JSONBridgesTests': 10, 'JSONSchemaTests': 55, 'JSONRegexRuntimeTests': 12, - 'JSONStreamingTests': 14, 'JSONPatchTests': 11, 'JSONHTMLTests': 61} + 'JSONStreamingTests': 14, 'JSONPatchTests': 11, 'JSONHTMLTests': 61, 'JSONDSLTests': 47} GROUPS = {'core': 6, 'resources': 1, 'schema': 2, 'streaming': 3, 'html': 6} def main(): @@ -54,7 +54,7 @@ def binary(scratch, config, name): run('sdk', [swift, 'sdk', 'list'], lambda c, t: c == 0 and SDK in t.splitlines()) run('wasmkit-version', [wasmkit, '--version']); run('node-version', [node, '--version']) manifest = json.loads(run('root-manifest', [swift, 'package', 'dump-package'])) - if manifest['dependencies'] or sorted(p['name'] for p in manifest['products']) != ['JSON', 'JSONBridges', 'JSONHTML', 'JSONPatch', 'JSONSchema', 'JSONStreaming']: + if manifest['dependencies'] or sorted(p['name'] for p in manifest['products']) != ['JSON', 'JSONBridges', 'JSONHTML', 'JSONPatch', 'JSONSchema', 'JSONSchemaDSL', 'JSONStreaming', 'JSONValueDSL']: raise ValueError('Changed public products/dependencies') def invoke(engine, path, mode='command', arguments=(), repo=True, resources=True): if engine == 'node': diff --git a/Sources/JSONDSLCore/Documentation.docc/JSONDSLCore.md b/Sources/JSONDSLCore/Documentation.docc/JSONDSLCore.md new file mode 100644 index 0000000..56b9a13 --- /dev/null +++ b/Sources/JSONDSLCore/Documentation.docc/JSONDSLCore.md @@ -0,0 +1,38 @@ +# ``JSONDSLCore`` + +Shared typed structure for the two optional DSL products. + +## Overview + +This supporting module has no standalone SwiftPM product. Its public structural types +appear in the generic signatures of JSONValueDSL and JSONSchemaDSL. It imports JSON +only, with no framework result builder, parser, validator or external dependency. + +The builder preserves typed tuples, optional content, choices and loop iterations. +Conditional context conformances decide which declarations are eligible in each domain. +There is no runtime shape inference, String dictionary merge or semantic interpretation. +Protocol implementations and staging are trusted authored code. JSONDSLNode factories +assemble a flat IR; only materialize performs finite iterative finalization. The schema +facade uses a package continuation of the same ledger through engine document admission. + +## Topics + +### Structural composition +- ``JSONContentBuilder`` +- ``JSONContentTuple`` +- ``JSONContentOptional`` +- ``JSONContentChoice`` +- ``JSONContentLoop`` + +### Trusted staging +- ``JSONDSLNode`` +- ``JSONDSLMember`` +- ``JSONValueFieldsContent`` +- ``JSONValueElementsContent`` +- ``JSONSchemaClausesContent`` +- ``JSONSchemaPropertiesContent`` +- ``JSONSchemaDefinitionsContent`` +- ``JSONSchemaPatternsContent`` +- ``JSONSchemaDependentSchemasContent`` +- ``JSONSchemaDependenciesContent`` +- ``JSONSchemaNodesContent`` diff --git a/Sources/JSONDSLCore/JSONContent.swift b/Sources/JSONDSLCore/JSONContent.swift new file mode 100644 index 0000000..c884c96 --- /dev/null +++ b/Sources/JSONDSLCore/JSONContent.swift @@ -0,0 +1,545 @@ +// SPDX-License-Identifier: Apache-2.0 +import JSON + +// A SwiftUI-ContentBuilder-inspired but fully independent typed content structure. +// The builder itself is intentionally domain-agnostic: contexts supply conformance. +// No SwiftUI import, SwiftUI types, implicit JSON coercion or runtime reflection. + +/// Typed sibling storage whose context conformances determine domain eligibility. +public struct JSONContentTuple { + /// Typed siblings in their original authored order. + public let elements: (repeat each Element) + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public init(_ elements: repeat each Element) { self.elements = (repeat each elements) } +} +/// Optional typed content; absence emits no declaration. +public struct JSONContentOptional { + /// Selected typed content, or nil for omission. + public let component: Component? + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - component: The selected typed content, or nil to omit it. + public init(_ component: Component?) { self.component = component } +} +/// Exactly one selected branch without semantic coercion. +public enum JSONContentChoice { + /// Content selected by the first conditional branch. + case first(First) + /// Content selected by the second conditional branch. + case second(Second) +} +/// Ordered typed iterations in trusted authored staging. +public struct JSONContentLoop { + /// Typed loop iterations in order. + public let components: [Component] + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - components: Typed loop iterations in their original order. + public init(_ components: [Component]) { self.components = components } +} + +/// Structural composition shared by the two optional DSL products. +@resultBuilder +public enum JSONContentBuilder { + /// Preserves typed siblings in a variadic tuple; domain eligibility comes from conditional conformances. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public static func buildBlock(_ elements: repeat each Element) -> JSONContentTuple< + repeat each Element + > { + .init(repeat each elements) + } + /// Preserves optional content; nil contributes no declaration. + /// + /// - Parameters: + /// - component: The selected typed content, or nil to omit it. + public static func buildOptional(_ component: Component?) -> JSONContentOptional { + .init(component) + } + /// Preserves the selected branch without a substitute null or Boolean schema. + /// + /// - Parameters: + /// - first: The selected first branch, preserving its domain eligibility. + public static func buildEither(first: First) -> JSONContentChoice { + .first(first) + } + /// Preserves the selected branch without a substitute null or Boolean schema. + /// + /// - Parameters: + /// - second: The selected second branch, preserving its domain eligibility. + public static func buildEither(second: Second) -> JSONContentChoice { + .second(second) + } + /// Preserves loop iterations in order for their containing typed context. + /// + /// - Parameters: + /// - components: Typed loop iterations in their original order. + public static func buildArray(_ components: [Component]) -> JSONContentLoop { + .init(components) + } + /// Forwards available typed content without erasure or semantic interpretation. + /// + /// - Parameters: + /// - component: The selected typed content, or nil to omit it. + public static func buildLimitedAvailability(_ component: Component) -> Component { component } +} + +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONValueFieldsContent { + /// Emits ordered object members into trusted, unmetered staging. + /// + /// - Parameters: + /// - members: The caller-owned ordered buffer; emission performs no admission or evaluation. + func writeValueFields(to members: inout [JSONDSLMember]) +} +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONValueElementsContent { + /// Emits ordered array elements into trusted, unmetered staging. + /// + /// - Parameters: + /// - elements: The caller-owned ordered buffer; emission performs no admission or evaluation. + func writeValueElements(to elements: inout [JSONDSLNode]) +} +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONSchemaClausesContent { + /// Emits explicit schema keyword declarations into trusted, unmetered staging. + /// + /// - Parameters: + /// - members: The caller-owned ordered buffer; emission performs no admission or evaluation. + func writeSchemaClauses(to members: inout [JSONDSLMember]) +} +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONSchemaPropertiesContent { + /// Emits named property schemas into trusted, unmetered staging. + /// + /// - Parameters: + /// - members: The caller-owned ordered buffer; emission performs no admission or evaluation. + func writeSchemaProperties(to members: inout [JSONDSLMember]) +} +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONSchemaNodesContent { + /// Emits ordered Boolean or object subschemas into trusted, unmetered staging. + /// + /// - Parameters: + /// - nodes: The caller-owned ordered buffer; emission performs no admission or evaluation. + func writeSchemaNodes(to nodes: inout [JSONDSLNode]) +} +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONSchemaDependenciesContent { + /// Emits dependent-required declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + func writeSchemaDependencies(to members: inout [JSONDSLMember]) +} +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONSchemaPatternsContent { + /// Emits pattern-keyed schemas into trusted, unmetered staging. + /// + /// - Parameters: + /// - members: The caller-owned ordered buffer; emission performs no admission or evaluation. + func writeSchemaPatterns(to members: inout [JSONDSLMember]) +} +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONSchemaDefinitionsContent { + /// Emits named schema definitions into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + func writeSchemaDefinitions(to members: inout [JSONDSLMember]) +} +/// A typed staging emission contract; implementations are trusted authored code, outside finalization accounting. +public protocol JSONSchemaDependentSchemasContent { + /// Emits dependent schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + func writeDependentSchemas(to members: inout [JSONDSLMember]) +} + +// Context-specific conditional conformances mirror ContentBuilder's design principle. +// Deliberately not type-erased; wrong-domain items are compile-time errors. + +extension JSONContentTuple: JSONValueFieldsContent where repeat each Element: JSONValueFieldsContent { + /// Emits ordered object members into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeValueFields(to members: inout [JSONDSLMember]) { + for element in repeat each self.elements { element.writeValueFields(to: &members) } + } +} +extension JSONContentOptional: JSONValueFieldsContent where Component: JSONValueFieldsContent { + /// Emits ordered object members into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeValueFields(to members: inout [JSONDSLMember]) { + component?.writeValueFields(to: &members) + } +} +extension JSONContentChoice: JSONValueFieldsContent +where First: JSONValueFieldsContent, Second: JSONValueFieldsContent { + /// Emits ordered object members into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeValueFields(to members: inout [JSONDSLMember]) { + switch self { + case .first(let item): item.writeValueFields(to: &members) + case .second(let item): item.writeValueFields(to: &members) + } + } +} +extension JSONContentLoop: JSONValueFieldsContent where Component: JSONValueFieldsContent { + /// Emits ordered object members into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeValueFields(to members: inout [JSONDSLMember]) { + for component in components { component.writeValueFields(to: &members) } + } +} + +extension JSONContentTuple: JSONValueElementsContent where repeat each Element: JSONValueElementsContent { + /// Emits array elements into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public func writeValueElements(to elements: inout [JSONDSLNode]) { + for element in repeat each self.elements { element.writeValueElements(to: &elements) } + } +} +extension JSONContentOptional: JSONValueElementsContent where Component: JSONValueElementsContent { + /// Emits array elements into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public func writeValueElements(to elements: inout [JSONDSLNode]) { + component?.writeValueElements(to: &elements) + } +} +extension JSONContentChoice: JSONValueElementsContent +where First: JSONValueElementsContent, Second: JSONValueElementsContent { + /// Emits array elements into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public func writeValueElements(to elements: inout [JSONDSLNode]) { + switch self { + case .first(let item): item.writeValueElements(to: &elements) + case .second(let item): item.writeValueElements(to: &elements) + } + } +} +extension JSONContentLoop: JSONValueElementsContent where Component: JSONValueElementsContent { + /// Emits array elements into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public func writeValueElements(to elements: inout [JSONDSLNode]) { + for component in components { component.writeValueElements(to: &elements) } + } +} + +extension JSONContentTuple: JSONSchemaClausesContent where repeat each Element: JSONSchemaClausesContent { + /// Emits schema keyword declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaClauses(to members: inout [JSONDSLMember]) { + for element in repeat each self.elements { element.writeSchemaClauses(to: &members) } + } +} +extension JSONContentOptional: JSONSchemaClausesContent where Component: JSONSchemaClausesContent { + /// Emits schema keyword declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaClauses(to members: inout [JSONDSLMember]) { + component?.writeSchemaClauses(to: &members) + } +} +extension JSONContentChoice: JSONSchemaClausesContent +where First: JSONSchemaClausesContent, Second: JSONSchemaClausesContent { + /// Emits schema keyword declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaClauses(to members: inout [JSONDSLMember]) { + switch self { + case .first(let item): item.writeSchemaClauses(to: &members) + case .second(let item): item.writeSchemaClauses(to: &members) + } + } +} +extension JSONContentLoop: JSONSchemaClausesContent where Component: JSONSchemaClausesContent { + /// Emits schema keyword declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaClauses(to members: inout [JSONDSLMember]) { + for component in components { component.writeSchemaClauses(to: &members) } + } +} + +extension JSONContentTuple: JSONSchemaPropertiesContent +where repeat each Element: JSONSchemaPropertiesContent { + /// Emits property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaProperties(to members: inout [JSONDSLMember]) { + for element in repeat each self.elements { element.writeSchemaProperties(to: &members) } + } +} +extension JSONContentOptional: JSONSchemaPropertiesContent where Component: JSONSchemaPropertiesContent { + /// Emits property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaProperties(to members: inout [JSONDSLMember]) { + component?.writeSchemaProperties(to: &members) + } +} +extension JSONContentChoice: JSONSchemaPropertiesContent +where First: JSONSchemaPropertiesContent, Second: JSONSchemaPropertiesContent { + /// Emits property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaProperties(to members: inout [JSONDSLMember]) { + switch self { + case .first(let item): item.writeSchemaProperties(to: &members) + case .second(let item): item.writeSchemaProperties(to: &members) + } + } +} +extension JSONContentLoop: JSONSchemaPropertiesContent where Component: JSONSchemaPropertiesContent { + /// Emits property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaProperties(to members: inout [JSONDSLMember]) { + for component in components { component.writeSchemaProperties(to: &members) } + } +} + +extension JSONContentTuple: JSONSchemaNodesContent where repeat each Element: JSONSchemaNodesContent { + /// Emits subschemas in a composition list into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - nodes: The unmetered staged subschema list, preserving order and Boolean schemas. + public func writeSchemaNodes(to nodes: inout [JSONDSLNode]) { + for element in repeat each self.elements { element.writeSchemaNodes(to: &nodes) } + } +} +extension JSONContentOptional: JSONSchemaNodesContent where Component: JSONSchemaNodesContent { + /// Emits subschemas in a composition list into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - nodes: The unmetered staged subschema list, preserving order and Boolean schemas. + public func writeSchemaNodes(to nodes: inout [JSONDSLNode]) { component?.writeSchemaNodes(to: &nodes) } +} +extension JSONContentChoice: JSONSchemaNodesContent +where First: JSONSchemaNodesContent, Second: JSONSchemaNodesContent { + /// Emits subschemas in a composition list into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - nodes: The unmetered staged subschema list, preserving order and Boolean schemas. + public func writeSchemaNodes(to nodes: inout [JSONDSLNode]) { + switch self { + case .first(let item): item.writeSchemaNodes(to: &nodes) + case .second(let item): item.writeSchemaNodes(to: &nodes) + } + } +} +extension JSONContentLoop: JSONSchemaNodesContent where Component: JSONSchemaNodesContent { + /// Emits subschemas in a composition list into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - nodes: The unmetered staged subschema list, preserving order and Boolean schemas. + public func writeSchemaNodes(to nodes: inout [JSONDSLNode]) { + for component in components { component.writeSchemaNodes(to: &nodes) } + } +} + +extension JSONContentTuple: JSONSchemaDependenciesContent +where repeat each Element: JSONSchemaDependenciesContent { + /// Emits dependent-required declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDependencies(to members: inout [JSONDSLMember]) { + for element in repeat each self.elements { element.writeSchemaDependencies(to: &members) } + } +} +extension JSONContentOptional: JSONSchemaDependenciesContent where Component: JSONSchemaDependenciesContent { + /// Emits dependent-required declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDependencies(to members: inout [JSONDSLMember]) { + component?.writeSchemaDependencies(to: &members) + } +} +extension JSONContentChoice: JSONSchemaDependenciesContent +where First: JSONSchemaDependenciesContent, Second: JSONSchemaDependenciesContent { + /// Emits dependent-required declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDependencies(to members: inout [JSONDSLMember]) { + switch self { + case .first(let item): item.writeSchemaDependencies(to: &members) + case .second(let item): item.writeSchemaDependencies(to: &members) + } + } +} +extension JSONContentLoop: JSONSchemaDependenciesContent where Component: JSONSchemaDependenciesContent { + /// Emits dependent-required declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDependencies(to members: inout [JSONDSLMember]) { + for component in components { component.writeSchemaDependencies(to: &members) } + } +} + +extension JSONContentTuple: JSONSchemaPatternsContent where repeat each Element: JSONSchemaPatternsContent { + /// Emits patterned property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaPatterns(to members: inout [JSONDSLMember]) { + for element in repeat each self.elements { element.writeSchemaPatterns(to: &members) } + } +} +extension JSONContentOptional: JSONSchemaPatternsContent where Component: JSONSchemaPatternsContent { + /// Emits patterned property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaPatterns(to members: inout [JSONDSLMember]) { + component?.writeSchemaPatterns(to: &members) + } +} +extension JSONContentChoice: JSONSchemaPatternsContent +where First: JSONSchemaPatternsContent, Second: JSONSchemaPatternsContent { + /// Emits patterned property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaPatterns(to members: inout [JSONDSLMember]) { + switch self { + case .first(let item): item.writeSchemaPatterns(to: &members) + case .second(let item): item.writeSchemaPatterns(to: &members) + } + } +} +extension JSONContentLoop: JSONSchemaPatternsContent where Component: JSONSchemaPatternsContent { + /// Emits patterned property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaPatterns(to members: inout [JSONDSLMember]) { + for component in components { component.writeSchemaPatterns(to: &members) } + } +} + +extension JSONContentTuple: JSONSchemaDefinitionsContent +where repeat each Element: JSONSchemaDefinitionsContent { + /// Emits named schema definitions into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDefinitions(to members: inout [JSONDSLMember]) { + for element in repeat each self.elements { element.writeSchemaDefinitions(to: &members) } + } +} +extension JSONContentOptional: JSONSchemaDefinitionsContent where Component: JSONSchemaDefinitionsContent { + /// Emits named schema definitions into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDefinitions(to members: inout [JSONDSLMember]) { + component?.writeSchemaDefinitions(to: &members) + } +} +extension JSONContentChoice: JSONSchemaDefinitionsContent +where First: JSONSchemaDefinitionsContent, Second: JSONSchemaDefinitionsContent { + /// Emits named schema definitions into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDefinitions(to members: inout [JSONDSLMember]) { + switch self { + case .first(let item): item.writeSchemaDefinitions(to: &members) + case .second(let item): item.writeSchemaDefinitions(to: &members) + } + } +} +extension JSONContentLoop: JSONSchemaDefinitionsContent where Component: JSONSchemaDefinitionsContent { + /// Emits named schema definitions into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDefinitions(to members: inout [JSONDSLMember]) { + for component in components { component.writeSchemaDefinitions(to: &members) } + } +} + +extension JSONContentTuple: JSONSchemaDependentSchemasContent +where repeat each Element: JSONSchemaDependentSchemasContent { + /// Emits dependent schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeDependentSchemas(to members: inout [JSONDSLMember]) { + for element in repeat each self.elements { element.writeDependentSchemas(to: &members) } + } +} +extension JSONContentOptional: JSONSchemaDependentSchemasContent +where Component: JSONSchemaDependentSchemasContent { + /// Emits dependent schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeDependentSchemas(to members: inout [JSONDSLMember]) { + component?.writeDependentSchemas(to: &members) + } +} +extension JSONContentChoice: JSONSchemaDependentSchemasContent +where First: JSONSchemaDependentSchemasContent, Second: JSONSchemaDependentSchemasContent { + /// Emits dependent schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeDependentSchemas(to members: inout [JSONDSLMember]) { + switch self { + case .first(let item): item.writeDependentSchemas(to: &members) + case .second(let item): item.writeDependentSchemas(to: &members) + } + } +} +extension JSONContentLoop: JSONSchemaDependentSchemasContent +where Component: JSONSchemaDependentSchemasContent { + /// Emits dependent schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeDependentSchemas(to members: inout [JSONDSLMember]) { + for component in components { component.writeDependentSchemas(to: &members) } + } +} + +extension JSONContentTuple: Sendable where repeat each Element: Sendable {} +extension JSONContentOptional: Sendable where Component: Sendable {} +extension JSONContentChoice: Sendable where First: Sendable, Second: Sendable {} +extension JSONContentLoop: Sendable where Component: Sendable {} diff --git a/Sources/JSONDSLCore/JSONDSLNode.swift b/Sources/JSONDSLCore/JSONDSLNode.swift new file mode 100644 index 0000000..41f8d7e --- /dev/null +++ b/Sources/JSONDSLCore/JSONDSLNode.swift @@ -0,0 +1,172 @@ +// SPDX-License-Identifier: Apache-2.0 +import JSON + +/// An ordered member in trusted, authored DSL staging. +/// +/// Staging is not resource admission. The containing DSL finalizes the complete tree. +public struct JSONDSLMember: Sendable { + /// The literal decoded-scalar member name; it is not a Pointer or dotted path. + public let key: String + /// The exact staged payload; admission occurs at finalization. + public let value: JSONDSLNode + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ key: String, _ value: JSONDSLNode) { + self.key = key + self.value = value + } +} + +/// A flat staging representation, without a recursive owned IR lifetime. +/// +/// Factories are trusted authoring operations, outside the finalization budget. +/// They preserve literal containers, exact keys and numbers without interpretation. +public struct JSONDSLNode: Sendable { + private enum Token: Sendable { + case literal(JSON) + case object, array + case key(String) + case endObject, endArray + } + private let tokens: [Token] + private init(_ tokens: [Token]) { self.tokens = tokens } + + /// Stages an exact JSON payload without admitting it or flattening its containers. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func literal(_ value: JSON) -> Self { Self([.literal(value)]) } + /// Combines ordered members into flat, unmetered staging; this factory does not finalize. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public static func object(_ members: [JSONDSLMember]) -> Self { + var tokens: [Token] = [.object] + for member in members { + tokens.append(.key(member.key)) + tokens.append(contentsOf: member.value.tokens) + } + tokens.append(.endObject) + return Self(tokens) + } + /// Combines ordered elements into flat, unmetered staging; literal arrays remain single values. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public static func array(_ elements: [Self]) -> Self { + var tokens: [Token] = [.array] + for element in elements { tokens.append(contentsOf: element.tokens) } + tokens.append(.endArray) + return Self(tokens) + } + + /// Finalizes trusted staging through one finite invocation-owned ledger. + /// + /// This does not account for staging, caller callbacks, or process RSS. + /// - Parameters: + /// - limits: Inclusive finite finalization capacities and work limits. + /// - Throws: Exact duplicate keys, resource/configuration failure or cancellation. + public func materialize(limits: JSONLimits = .balanced) throws -> JSON { + try finalize(limits: limits, domain: .core) { value, _ in value } + } + + private struct Frame { + let object: Bool + var members: [JSONMember] = [] + var values: [JSON] = [] + var index = JSONExactKeyIndex() + var key: JSONKey? + } + + /// The schema facade continues this exact ledger through document admission. + package func finalize( + limits: JSONLimits, domain: JSONOperationDomain, + checkpointObserver: (@Sendable (UInt64) -> Void)? = nil, + _ finish: (JSON, inout JSONWorkMeter) throws -> Result + ) throws -> Result { + var meter = try JSONWorkMeter(limits: limits, domain: domain) + meter.checkpointObserver = checkpointObserver + var frames: [Frame] = [] + var root: JSON? + func requireSlot(_ frames: [Frame], meter: borrowing JSONWorkMeter) throws { + if let parent = frames.last, !parent.object { + try meter.require(.arrayItems, UInt64(parent.values.count) + 1) + } + } + func append(_ value: JSON, frames: inout [Frame], root: inout JSON?, meter: inout JSONWorkMeter) + throws + { + guard !frames.isEmpty else { + guard root == nil else { throw JSONFailure(.configuration, code: .invalidOperation) } + root = value + return + } + let position = frames.count - 1 + if frames[position].object { + guard let key = frames[position].key else { + throw JSONFailure(.configuration, code: .invalidOperation) + } + guard + try frames[position].index.insert( + key, position: frames[position].members.count, meter: &meter) + else { + throw JSONFailure(.syntax, code: .duplicateKey) + } + try meter.retain(JSONLogicalWeights.member) + frames[position].members.append(JSONMember(key, value: value)) + frames[position].key = nil + } else { + try meter.retain(JSONLogicalWeights.arraySlot) + frames[position].values.append(value) + } + } + for token in tokens { + try meter.work() + switch token { + case .literal(let value): + try requireSlot(frames, meter: meter) + try JSONAdmission.value(value, meter: &meter, owned: true, depth: UInt64(frames.count)) + try append(value, frames: &frames, root: &root, meter: &meter) + case .object, .array: + try requireSlot(frames, meter: meter) + try meter.require(.maxDepth, UInt64(frames.count) + 1) + try meter.charge(.nodes) + try meter.retain(JSONLogicalWeights.node) + try meter.retain(JSONLogicalWeights.frame) + if case .object = token { + frames.append(Frame(object: true)) + } else { + frames.append(Frame(object: false)) + } + case .key(let spelling): + guard let last = frames.last, last.object, last.key == nil else { + throw JSONFailure(.configuration, code: .invalidOperation) + } + try meter.require(.objectMembers, UInt64(last.members.count) + 1) + try JSONAdmission.text(spelling, key: true, meter: &meter, owned: true) + let key = try JSONKey(spelling, meter: &meter) + guard try last.index.find(key, meter: &meter) == nil else { + throw JSONFailure(.syntax, code: .duplicateKey) + } + frames[frames.count - 1].key = key + case .endObject, .endArray: + guard let frame = frames.popLast(), frame.key == nil else { + throw JSONFailure(.configuration, code: .invalidOperation) + } + try meter.release(JSONLogicalWeights.frame) + let value: JSON = + frame.object + ? .object(JSONObject(admitted: frame.members, index: frame.index)) : .array(frame.values) + try append(value, frames: &frames, root: &root, meter: &meter) + } + } + guard frames.isEmpty, let root else { throw JSONFailure(.configuration, code: .invalidOperation) } + try meter.checkpoint() + let result = try finish(root, &meter) + try meter.checkpoint() + return result + } +} diff --git a/Sources/JSONSchemaDSL/Documentation.docc/AuthoredSchemas.md b/Sources/JSONSchemaDSL/Documentation.docc/AuthoredSchemas.md new file mode 100644 index 0000000..9e5fd2a --- /dev/null +++ b/Sources/JSONSchemaDSL/Documentation.docc/AuthoredSchemas.md @@ -0,0 +1,54 @@ +# Authored schemas, engine validation + +Emit an exact declaration, then explicitly compile and evaluate it. + +The following example is compiled and run by `Examples/DualDSL` after its value example. + +```swift +let schema = try JSONSchemaDSL.document { + Schema.schemaURI("https://json-schema.org/draft/2020-12/schema") + Schema.type(.object) + Schema.properties { + Property("id") { Schema.type(.integer) } + Property("amount") { Schema.reference("#/$defs/Amount") } + } + Schema.required("id", "amount") + Schema.definitions { + Definition("Amount") { + Schema.type(.number) + Schema.minimum(tenth) + Schema.multipleOf(tenth) + } + } +} +let plan = try JSONSchemaCompiler().compile(schema) +let validator = JSONSchemaValidator() +``` + +Import JSON, JSONSchema and JSONSchemaDSL. The source example in `Examples/DualDSL` +also validates a positive instance, two negative instances and a missing-resource +operational failure. A document containing only definitions does not select one; +use an explicit reference such as the one above. IDs and reference text are preserved. +Externally supplied resources use the existing JSONSchemaDocument retrieval identity +and immutable JSONSchemaRegistry; the DSL never fetches a URL or infers a registry. + +`Property` does not imply requiredness, `defaultValue` does not fill missing values, +and `format` does not select assertion policy. Use existing JSONSchemaOptions. +`Rule(false)` is a false subschema; `Rule {}` is an empty object schema; neither is +JSON null. Explicit `rawKeyword` preserves unknown metadata and malformed declarations +for the existing compiler to classify. There is no synonym that silently repairs them. +An empty enum compiles as an empty allowed set and produces ordinary invalidity; +negative lengths and an empty oneOf remain compilation failures under the engine. + +Duplicate exact names fail during finalization; scalar-distinct names remain distinct. +Resource/configuration failures and cancellation throw. An invalid instance returns +`isValid == false`; malformed declarations, missing resources, nonproductive reference +cycles and operational exhaustion throw. Branches do not swallow these failures. +Annotations and dynamic scope remain engine-owned and are compared with handwritten +schema paths in the real-engine tests. + +The authored closure, typed wrappers and staged buffers are unmetered. A flat IR avoids +recursive owned staging-node teardown; finalization uses explicit frames and one finite +ledger through document admission. This is not a whole-DSL resource report, an instruction +quota for caller code, a staging retention cap or process RSS guarantee. Use the existing +checked JSONSchemaBuilder and explicit accumulators for dynamic bounded construction. diff --git a/Sources/JSONSchemaDSL/Documentation.docc/JSONSchemaDSL.md b/Sources/JSONSchemaDSL/Documentation.docc/JSONSchemaDSL.md new file mode 100644 index 0000000..4eccef0 --- /dev/null +++ b/Sources/JSONSchemaDSL/Documentation.docc/JSONSchemaDSL.md @@ -0,0 +1,40 @@ +# ``JSONSchemaDSL`` + +Typed authored Draft 2020-12 declarations, with the existing engine as authority. + +## Overview + +``document(limits:_:)`` emits ordinary JSONSchemaDocument. +``Schema`` supplies explicit keyword declarations. Properties, definitions, +pattern properties, dependent schemas and composition rules have distinct typed +contexts; using a declaration in the wrong context fails Swift compilation. +``boolean(_:limits:)`` emits a Boolean schema without inventing an +object or substituting JSON null. + +Only JSONSchemaCompiler interprets dialects, references and vocabulary requirements. +Only JSONSchemaValidator produces instance verdicts and evaluation annotations. +Compilation is separate from document admission. Properties infer no requiredness, +defaults never mutate instances, format stays annotation by default, and references +resolve only through the existing explicit offline registry. No DSL validator exists. + +Authored callbacks and staging are trusted and unmetered. One finite finalization +ledger continues through JSONSchemaDocument admission; it is not a staging/RSS or +whole-pipeline cumulative-accounting promise. + +## Topics + +### Authoring and evaluation +- +- ``document(limits:_:)`` +- ``boolean(_:limits:)`` +- ``Schema`` +- ``SchemaType`` +- ``SchemaClause`` + +### Typed contexts +- ``Property`` +- ``Definition`` +- ``PatternProperty`` +- ``DependentSchema`` +- ``RequiredDependency`` +- ``Rule`` diff --git a/Sources/JSONSchemaDSL/JSONSchemaDSL.swift b/Sources/JSONSchemaDSL/JSONSchemaDSL.swift new file mode 100644 index 0000000..9bee977 --- /dev/null +++ b/Sources/JSONSchemaDSL/JSONSchemaDSL.swift @@ -0,0 +1,711 @@ +// SPDX-License-Identifier: Apache-2.0 +import JSON +import JSONDSLCore +import JSONSchema + +/// Stages one schema document; only finalization is checked and callbacks/staging are unmetered. +/// +/// - Parameters: +/// - limits: Inclusive finite finalization capacities and work quotas; staging is excluded. +/// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. +public func document( + limits: JSONLimits = .balanced, + @JSONContentBuilder _ content: () -> Content +) throws -> JSONSchemaDocument { + try Task.checkCancellation() + try limits.validate() + var entries: [JSONDSLMember] = [] + content().writeSchemaClauses(to: &entries) + return try JSONDSLNode.object(entries).finalize(limits: limits, domain: .schemaCompilation) { + raw, meter in + try JSONSchemaDocument(raw, meter: &meter) + } +} +/// Admits an ordinary Boolean schema through the existing JSONSchemaDocument authority. +/// +/// - Parameters: +/// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. +/// - limits: Inclusive finite finalization capacities and work quotas; staging is excluded. +public func boolean(_ allowsAll: Bool, limits: JSONLimits = .balanced) throws -> JSONSchemaDocument +{ + try JSONSchemaDocument(.boolean(allowsAll), limits: limits) +} + +/// One staged schema declaration (`keyword: exact value`), not an evaluation rule. +public struct SchemaClause: Sendable, JSONSchemaClausesContent { + /// The staged exact keyword/value declaration. + public let entry: JSONDSLMember + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - name: The exact declaration name or keyword-specific text, without normalization. + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ name: String, value: JSONDSLNode) { entry = .init(name, value) } + /// Emits schema keyword declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaClauses(to members: inout [JSONDSLMember]) { members.append(entry) } +} + +/// Document/schema keyword types; no type inference from sibling declarations. +public enum SchemaType: String, Sendable { + /// The explicit JSON Schema `object` type name. + case object + /// The explicit JSON Schema `array` type name. + case array + /// The explicit JSON Schema `string` type name. + case string + /// The explicit JSON Schema `number` type name. + case number + /// The explicit JSON Schema `integer` type name. + case integer + /// The explicit JSON Schema `boolean` type name. + case boolean + /// The explicit JSON Schema `null` type name. + case null +} + +/// Fluent namespace that covers standard Draft 2020-12 keywords, but does not +/// infer effective schema shape, override compiler policy or resolve remote refs. +public enum Schema { + private static func one(_ key: String, _ value: JSON) -> SchemaClause { + .init(key, value: .literal(value)) + } + private static func jsonStringArray(_ values: [String]) -> JSONDSLNode { + .array(values.map { .literal(.string($0)) }) + } + private static func jsonArray(_ values: [JSON]) -> JSONDSLNode { .array(values.map(JSONDSLNode.literal)) } + private static func makeObject(_ content: Content) -> JSONDSLNode { + var entries: [JSONDSLMember] = [] + content.writeSchemaClauses(to: &entries) + return .object(entries) + } + private static func schemaKeyword( + _ name: String, _ content: Content + ) -> SchemaClause { .init(name, value: makeObject(content)) } + + // Core and identification. + /// Declares `$schema` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func schemaURI(_ value: String) -> SchemaClause { one("$schema", .string(value)) } + /// Declares `$id` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func identifier(_ value: String) -> SchemaClause { one("$id", .string(value)) } + /// Declares `$anchor` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func anchor(_ value: String) -> SchemaClause { one("$anchor", .string(value)) } + /// Declares `$dynamicAnchor` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func dynamicAnchor(_ value: String) -> SchemaClause { + one("$dynamicAnchor", .string(value)) + } + /// Declares `$ref` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func reference(_ value: String) -> SchemaClause { one("$ref", .string(value)) } + /// Declares `$dynamicRef` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func dynamicReference(_ value: String) -> SchemaClause { + one("$dynamicRef", .string(value)) + } + /// Declares `$comment` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func comment(_ value: String) -> SchemaClause { one("$comment", .string(value)) } + /// Declares `$vocabulary` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - entries: Ordered URI/requirement or named declaration pairs; exact duplicates fail finalization. + public static func vocabulary(_ entries: [(String, Bool)]) -> SchemaClause { + .init("$vocabulary", value: .object(entries.map { .init($0.0, .literal(.boolean($0.1))) })) + } + /// Declares `$defs` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func definitions( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { + var entries: [JSONDSLMember] = [] + content().writeSchemaDefinitions(to: &entries) + return .init("$defs", value: .object(entries)) + } + + // Scalar assertions and typed vocabularies. + /// Declares `type` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func type(_ value: SchemaType) -> SchemaClause { one("type", .string(value.rawValue)) } + /// Declares `type` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - values: Explicit exact payloads in declaration order; nested arrays remain values. + public static func types(_ values: [SchemaType]) -> SchemaClause { + .init("type", value: jsonStringArray(values.map(\.rawValue))) + } + /// Declares `enum` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - values: Explicit exact payloads in declaration order; nested arrays remain values. + public static func enumValues(_ values: [JSON]) -> SchemaClause { + .init("enum", value: jsonArray(values)) + } + /// Declares `const` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func constant(_ value: JSON) -> SchemaClause { one("const", value) } + /// Declares `minimum` using an explicit exact decimal without binary floating-point narrowing. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func minimum(_ value: JSONNumber) -> SchemaClause { one("minimum", .number(value)) } + /// Declares `maximum` using an explicit exact decimal without binary floating-point narrowing. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func maximum(_ value: JSONNumber) -> SchemaClause { one("maximum", .number(value)) } + /// Declares `exclusiveMinimum` using an explicit exact decimal without binary floating-point narrowing. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func exclusiveMinimum(_ value: JSONNumber) -> SchemaClause { + one("exclusiveMinimum", .number(value)) + } + /// Declares `exclusiveMaximum` using an explicit exact decimal without binary floating-point narrowing. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func exclusiveMaximum(_ value: JSONNumber) -> SchemaClause { + one("exclusiveMaximum", .number(value)) + } + /// Declares `multipleOf` using an explicit exact decimal without binary floating-point narrowing. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func multipleOf(_ value: JSONNumber) -> SchemaClause { one("multipleOf", .number(value)) } + /// Declares `minLength` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func minLength(_ value: Int) -> SchemaClause { + one("minLength", .number(JSONNumber(integer: value))) + } + /// Declares `maxLength` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func maxLength(_ value: Int) -> SchemaClause { + one("maxLength", .number(JSONNumber(integer: value))) + } + /// Declares `pattern` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func pattern(_ value: String) -> SchemaClause { one("pattern", .string(value)) } + /// Declares `minItems` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func minItems(_ value: Int) -> SchemaClause { + one("minItems", .number(JSONNumber(integer: value))) + } + /// Declares `maxItems` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func maxItems(_ value: Int) -> SchemaClause { + one("maxItems", .number(JSONNumber(integer: value))) + } + /// Declares `uniqueItems` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func uniqueItems(_ value: Bool) -> SchemaClause { one("uniqueItems", .boolean(value)) } + /// Declares `minContains` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func minContains(_ value: Int) -> SchemaClause { + one("minContains", .number(JSONNumber(integer: value))) + } + /// Declares `maxContains` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func maxContains(_ value: Int) -> SchemaClause { + one("maxContains", .number(JSONNumber(integer: value))) + } + /// Declares `minProperties` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func minProperties(_ value: Int) -> SchemaClause { + one("minProperties", .number(JSONNumber(integer: value))) + } + /// Declares `maxProperties` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func maxProperties(_ value: Int) -> SchemaClause { + one("maxProperties", .number(JSONNumber(integer: value))) + } + /// Declares required names explicitly; property declarations never infer requiredness. + /// + /// - Parameters: + /// - names: Explicit required member names, preserved in declaration order. + public static func required(_ names: String...) -> SchemaClause { + .init("required", value: jsonStringArray(names)) + } + /// Declares format metadata; assertion policy remains with the existing compiler and validator. + /// + /// - Parameters: + /// - name: The exact declaration name or keyword-specific text, without normalization. + public static func format(_ name: String) -> SchemaClause { one("format", .string(name)) } + + // Metadata/annotation vocabulary; not assertions and never mutate an instance. + /// Declares `title` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func title(_ value: String) -> SchemaClause { one("title", .string(value)) } + /// Declares `description` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func description(_ value: String) -> SchemaClause { one("description", .string(value)) } + /// Declares default metadata without inserting or changing any instance value. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func defaultValue(_ value: JSON) -> SchemaClause { one("default", value) } + /// Declares `examples` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - values: Explicit exact payloads in declaration order; nested arrays remain values. + public static func examples(_ values: [JSON]) -> SchemaClause { + .init("examples", value: jsonArray(values)) + } + /// Declares `deprecated` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func deprecated(_ value: Bool = true) -> SchemaClause { one("deprecated", .boolean(value)) } + /// Declares `readOnly` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func readOnly(_ value: Bool = true) -> SchemaClause { one("readOnly", .boolean(value)) } + /// Emits typed declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func writeOnly(_ value: Bool = true) -> SchemaClause { one("writeOnly", .boolean(value)) } + /// Declares `contentEncoding` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func contentEncoding(_ value: String) -> SchemaClause { + one("contentEncoding", .string(value)) + } + /// Declares `contentMediaType` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public static func contentMediaType(_ value: String) -> SchemaClause { + one("contentMediaType", .string(value)) + } + + // Object applicators. + /// Declares `properties` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func properties( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { + var members: [JSONDSLMember] = [] + content().writeSchemaProperties(to: &members) + return .init("properties", value: .object(members)) + } + /// Declares `patternProperties` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func patternProperties( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { + var members: [JSONDSLMember] = [] + content().writeSchemaPatterns(to: &members) + return .init("patternProperties", value: .object(members)) + } + /// Declares `dependentSchemas` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func dependentSchemas( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { + var members: [JSONDSLMember] = [] + content().writeDependentSchemas(to: &members) + return .init("dependentSchemas", value: .object(members)) + } + /// Declares `dependentRequired` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func dependentRequired( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { + var members: [JSONDSLMember] = [] + content().writeSchemaDependencies(to: &members) + return .init("dependentRequired", value: .object(members)) + } + /// Declares `propertyNames` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func propertyNames( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("propertyNames", content()) } + /// Declares `additionalProperties` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public static func additionalProperties(_ allowsAll: Bool) -> SchemaClause { + one("additionalProperties", .boolean(allowsAll)) + } + /// Declares `additionalProperties` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func additionalProperties( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("additionalProperties", content()) } + /// Declares `unevaluatedProperties` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public static func unevaluatedProperties(_ allowsAll: Bool) -> SchemaClause { + one("unevaluatedProperties", .boolean(allowsAll)) + } + /// Declares `unevaluatedProperties` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func unevaluatedProperties( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("unevaluatedProperties", content()) } + + // Array applicators. + /// Declares `items` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public static func items(_ allowsAll: Bool) -> SchemaClause { one("items", .boolean(allowsAll)) } + /// Declares `items` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func items( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("items", content()) } + /// Declares `prefixItems` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func prefixItems( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { + var nodes: [JSONDSLNode] = [] + content().writeSchemaNodes(to: &nodes) + return .init("prefixItems", value: .array(nodes)) + } + /// Declares `contains` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func contains( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("contains", content()) } + /// Declares `unevaluatedItems` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public static func unevaluatedItems(_ allowsAll: Bool) -> SchemaClause { + one("unevaluatedItems", .boolean(allowsAll)) + } + /// Declares `unevaluatedItems` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func unevaluatedItems( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("unevaluatedItems", content()) } + + // Logical/conditional applicators. + private static func alternatives(_ name: String, content: Content) + -> SchemaClause + { + var nodes: [JSONDSLNode] = [] + content.writeSchemaNodes(to: &nodes) + return .init(name, value: .array(nodes)) + } + /// Declares `allOf` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func allOf( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { alternatives("allOf", content: content()) } + /// Declares `anyOf` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func anyOf( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { alternatives("anyOf", content: content()) } + /// Declares `oneOf` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func oneOf( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { alternatives("oneOf", content: content()) } + /// Declares `not` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func not( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("not", content()) } + /// Declares `if` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func ifSchema( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("if", content()) } + /// Declares `then` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func thenSchema( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("then", content()) } + /// Declares `else` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func elseSchema( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("else", content()) } + /// Declares `contentSchema` without repairing, validating or evaluating its schema semantics. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func contentSchema( + @JSONContentBuilder _ content: () -> Content + ) -> SchemaClause { schemaKeyword("contentSchema", content()) } + + // Full-fidelity escape: preservation of extension metadata, unknown optional vocabularies. + // The canonical compiler, not this DSL, determines whether a keyword is admitted. + /// Preserves an exact raw declaration; the existing compiler determines its syntax and meaning. + /// + /// - Parameters: + /// - name: The exact declaration name or keyword-specific text, without normalization. + /// - exactValue: The exact authored input for this declaration; no semantic fallback is applied. + public static func rawKeyword(_ name: String, _ exactValue: JSON) -> SchemaClause { + one(name, exactValue) + } +} + +/// Declares one subschema in an alternatives list (or a Boolean schema). +public struct Rule: Sendable, JSONSchemaNodesContent { + /// The staged subschema, without evaluation or inferred constraints. + public let node: JSONDSLNode + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public init(@JSONContentBuilder _ content: () -> Content) { + var members: [JSONDSLMember] = [] + content().writeSchemaClauses(to: &members) + node = .object(members) + } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public init(_ allowsAll: Bool) { node = .literal(.boolean(allowsAll)) } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - raw: The exact authored input for this declaration; no semantic fallback is applied. + public init(raw: JSON) { node = .literal(raw) } + /// Emits subschemas in a composition list into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - nodes: The unmetered staged subschema list, preserving order and Boolean schemas. + public func writeSchemaNodes(to nodes: inout [JSONDSLNode]) { nodes.append(node) } +} + +/// A property/definition/pattern property entry. Exact duplicate names are checked later. +public struct Property: Sendable, JSONSchemaPropertiesContent { + /// The ordered exact named subschema declaration. + public let member: JSONDSLMember + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - name: The exact declaration name or keyword-specific text, without normalization. + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public init( + _ name: String, @JSONContentBuilder _ content: () -> Content + ) { + var members: [JSONDSLMember] = [] + content().writeSchemaClauses(to: &members) + member = .init(name, .object(members)) + } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - name: The exact declaration name or keyword-specific text, without normalization. + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public init(_ name: String, allowsAll: Bool) { member = .init(name, .literal(.boolean(allowsAll))) } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - name: The exact declaration name or keyword-specific text, without normalization. + /// - rawSchema: The exact authored input for this declaration; no semantic fallback is applied. + public init(_ name: String, rawSchema: JSON) { member = .init(name, .literal(rawSchema)) } + /// Emits property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaProperties(to members: inout [JSONDSLMember]) { members.append(member) } +} + +/// A dependentRequired entry. Does not silently infer presence from properties. +public struct RequiredDependency: Sendable, JSONSchemaDependenciesContent { + /// The literal decoded-scalar member name; it is not a Pointer or dotted path. + public let key: String + /// Explicit required member names; no property inference is performed. + public let names: [String] + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - requires: Explicit required member names; none are inferred from property declarations. + public init(_ key: String, requires: [String]) { + self.key = key + self.names = requires + } + /// Emits dependent-required declarations into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDependencies(to members: inout [JSONDSLMember]) { + members.append(.init(key, .array(names.map { .literal(.string($0)) }))) + } +} + +/// A named `$defs` entry. It cannot be placed in `properties` by accident. +public struct Definition: Sendable, JSONSchemaDefinitionsContent { + /// The ordered exact named subschema declaration. + public let member: JSONDSLMember + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - name: The exact declaration name or keyword-specific text, without normalization. + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public init( + _ name: String, @JSONContentBuilder _ content: () -> Content + ) { + var entries: [JSONDSLMember] = [] + content().writeSchemaClauses(to: &entries) + member = .init(name, .object(entries)) + } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - name: The exact declaration name or keyword-specific text, without normalization. + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public init(_ name: String, allowsAll: Bool) { member = .init(name, .literal(.boolean(allowsAll))) } + /// Emits named schema definitions into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaDefinitions(to members: inout [JSONDSLMember]) { members.append(member) } +} + +/// A regular-expression property key. The compiler validates the pattern dialect. +public struct PatternProperty: Sendable, JSONSchemaPatternsContent { + /// The ordered exact named subschema declaration. + public let member: JSONDSLMember + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - pattern: The exact pattern text; regex validity belongs to the schema compiler. + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public init( + _ pattern: String, @JSONContentBuilder _ content: () -> Content + ) { + var entries: [JSONDSLMember] = [] + content().writeSchemaClauses(to: &entries) + member = .init(pattern, .object(entries)) + } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - pattern: The exact pattern text; regex validity belongs to the schema compiler. + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public init(_ pattern: String, allowsAll: Bool) { member = .init(pattern, .literal(.boolean(allowsAll))) } + /// Emits patterned property schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeSchemaPatterns(to members: inout [JSONDSLMember]) { members.append(member) } +} + +/// A dependentSchemas entry (subschema, not a list of required property names). +public struct DependentSchema: Sendable, JSONSchemaDependentSchemasContent { + /// The ordered exact named subschema declaration. + public let member: JSONDSLMember + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public init( + _ key: String, @JSONContentBuilder _ content: () -> Content + ) { + var entries: [JSONDSLMember] = [] + content().writeSchemaClauses(to: &entries) + member = .init(key, .object(entries)) + } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - allowsAll: True for an accepting Boolean schema, false for a rejecting Boolean schema. + public init(_ key: String, allowsAll: Bool) { member = .init(key, .literal(.boolean(allowsAll))) } + /// Emits dependent schemas into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeDependentSchemas(to members: inout [JSONDSLMember]) { members.append(member) } +} diff --git a/Sources/JSONValueDSL/Documentation.docc/AuthoredValues.md b/Sources/JSONValueDSL/Documentation.docc/AuthoredValues.md new file mode 100644 index 0000000..33f0752 --- /dev/null +++ b/Sources/JSONValueDSL/Documentation.docc/AuthoredValues.md @@ -0,0 +1,43 @@ +# Trusted exact value authoring + +Keep authored structure separate from bounded finalization. + +The following example is compiled and run by `Examples/DualDSL`. + +```swift +let tenth = try JSONNumber(parsing: "0.1") +let instance = try JSONValueDSL.object { + Field("id", UInt64(9_007_199_254_740_993)) + Field("amount", exactNumber: tenth) + Field("é", 1) + Field("e\u{301}", 2) + Field.array("nested") { + Element.array { + Element(1) + Element(2) + } + } +} +``` + +Import JSON for its exact-number API and JSONValueDSL for syntax. These declarations +retain distinct decoded scalar keys, their insertion order and exact numeric values. +Finalization throws existing JSONFailure for exact duplicates and resource/configuration +failures; cancellation propagates as CancellationError. A partial value is not returned. +Errors must not be replaced with null or defaults. Parse explicit decimal text before +entering the nonthrowing authored closure, so conversion errors propagate normally. + +`if`/`else` selects content; a missing branch contributes no declaration. `for` preserves +iteration order. `Field("note", .null)` is an explicit null member, distinct from absence. +`Elements(contentsOf:)` expands exactly the supplied values; an array within that list +remains an array value. An empty object remains `{}` and an empty array remains `[]`. + +Finalization traverses literal payloads too. All returned values satisfy the supplied +finite profile, with cumulative finalization work and inner cancellation checkpoints. +The existing 49-cap owners and logical weight version are unchanged. The builder +callback and earlier staging allocations are not billed by that finalization ledger. +Caller computation and process RSS are not owned work or logical-retention metrics. +No public whole-DSL report or untrusted staging guarantee is provided in P1.2. + +The shared generic builder types live in JSONDSLCore without a standalone product. +Applications select the JSONValueDSL product; core JSON does not import or re-export it. diff --git a/Sources/JSONValueDSL/Documentation.docc/JSONValueDSL.md b/Sources/JSONValueDSL/Documentation.docc/JSONValueDSL.md new file mode 100644 index 0000000..f164def --- /dev/null +++ b/Sources/JSONValueDSL/Documentation.docc/JSONValueDSL.md @@ -0,0 +1,28 @@ +# ``JSONValueDSL`` + +Typed authored JSON objects and arrays over the existing exact value model. + +## Overview + +Use ``object(limits:_:)`` or ``array(limits:_:)`` +for trusted source-authored declarations. ``Field`` contributes one literal key, +``Element`` contributes one array value, and ``Elements`` explicitly expands a list. +Missing conditional content emits nothing. Nested arrays remain single elements. +Integer input is exact; decimals require an explicit JSONNumber. There is no implicit +Float/Double, Optional or dictionary conversion and no dotted-path interpretation. + +Callbacks, typed wrappers, IR collection and staging are unmetered trusted authoring. +Only finalization is a checked operation. It uses one invocation-owned finite ledger +with iterative frames and the engine's exact admission and key index. Staging is not +an untrusted-input boundary, a live-retention/RSS cap or a whole-pipeline work report. +Use JSON's checked accumulators or strict parser for dynamic untrusted input. + +## Topics + +### Authoring +- +- ``object(limits:_:)`` +- ``array(limits:_:)`` +- ``Field`` +- ``Element`` +- ``Elements`` diff --git a/Sources/JSONValueDSL/JSONValueDSL.swift b/Sources/JSONValueDSL/JSONValueDSL.swift new file mode 100644 index 0000000..ce0fa2f --- /dev/null +++ b/Sources/JSONValueDSL/JSONValueDSL.swift @@ -0,0 +1,187 @@ +// SPDX-License-Identifier: Apache-2.0 +import JSON +import JSONDSLCore + +/// Stages one object; only finalization is checked and callbacks/staging are unmetered. +/// +/// - Parameters: +/// - limits: Inclusive finite finalization capacities and work quotas; staging is excluded. +/// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. +public func object( + limits: JSONLimits = .balanced, + @JSONContentBuilder _ content: () -> Content +) throws -> JSON { + try Task.checkCancellation() + try limits.validate() + var members: [JSONDSLMember] = [] + content().writeValueFields(to: &members) + return try JSONDSLNode.object(members).materialize(limits: limits) +} +/// Stages one array; only finalization is checked and callbacks/staging are unmetered. +/// +/// - Parameters: +/// - limits: Inclusive finite finalization capacities and work quotas; staging is excluded. +/// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. +public func array( + limits: JSONLimits = .balanced, + @JSONContentBuilder _ content: () -> Content +) throws -> JSON { + try Task.checkCancellation() + try limits.validate() + var nodes: [JSONDSLNode] = [] + content().writeValueElements(to: &nodes) + return try JSONDSLNode.array(nodes).materialize(limits: limits) +} + +/// One ordered object member. Keys are literal decoded Unicode scalars; no dotted path coercion. +public struct Field: Sendable, JSONValueFieldsContent { + /// The literal decoded-scalar member name; it is not a Pointer or dotted path. + public let key: String + /// The exact staged payload; admission occurs at finalization. + public let value: JSONDSLNode + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ key: String, _ value: JSON) { + self.key = key + self.value = .literal(value) + } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ key: String, _ value: String) { self.init(key, .string(value)) } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ key: String, _ value: Bool) { self.init(key, .boolean(value)) } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ key: String, _ value: Integer) { + self.init(key, .number(JSONNumber(integer: value))) + } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ key: String, exactNumber value: JSONNumber) { self.init(key, .number(value)) } + /// Stages one object; only finalization is checked and callbacks/staging are unmetered. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func object( + _ key: String, @JSONContentBuilder _ content: () -> Content + ) -> Self { + var members: [JSONDSLMember] = [] + content().writeValueFields(to: &members) + return Self(key: key, value: .object(members)) + } + /// Stages one array; only finalization is checked and callbacks/staging are unmetered. + /// + /// - Parameters: + /// - key: The literal decoded-scalar key, without path parsing or normalization. + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func array( + _ key: String, @JSONContentBuilder _ content: () -> Content + ) -> Self { + var nodes: [JSONDSLNode] = [] + content().writeValueElements(to: &nodes) + return Self(key: key, value: .array(nodes)) + } + private init(key: String, value: JSONDSLNode) { + self.key = key + self.value = value + } + /// Emits ordered object members into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - members: The unmetered ordered staging buffer; this is not a checked accumulator. + public func writeValueFields(to members: inout [JSONDSLMember]) { members.append(.init(key, value)) } +} + +/// One array item. A nested JSON array remains one element; never silently flattens. +public struct Element: Sendable, JSONValueElementsContent { + /// The exact staged payload; admission occurs at finalization. + public let value: JSONDSLNode + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ value: JSON) { self.value = .literal(value) } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ value: String) { self.init(.string(value)) } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ value: Bool) { self.init(.boolean(value)) } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - value: The exact declared payload; it is not coerced or interpreted by the DSL. + public init(_ value: Integer) { self.init(.number(JSONNumber(integer: value))) } + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - exactNumber: The exact authored input for this declaration; no semantic fallback is applied. + public init(exactNumber: JSONNumber) { self.init(.number(exactNumber)) } + /// Stages one object; only finalization is checked and callbacks/staging are unmetered. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func object(@JSONContentBuilder _ content: () -> Content) + -> Self + { + var members: [JSONDSLMember] = [] + content().writeValueFields(to: &members) + return Self(value: .object(members)) + } + /// Stages one array; only finalization is checked and callbacks/staging are unmetered. + /// + /// - Parameters: + /// - content: Trusted synchronous authored declarations; callback execution and staging are unmetered. + public static func array(@JSONContentBuilder _ content: () -> Content) + -> Self + { + var nodes: [JSONDSLNode] = [] + content().writeValueElements(to: &nodes) + return Self(value: .array(nodes)) + } + private init(value: JSONDSLNode) { self.value = value } + /// Emits array elements into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public func writeValueElements(to elements: inout [JSONDSLNode]) { elements.append(value) } +} + +/// Explicit sequence expansion (rather than implicit flattening of array values). +public struct Elements: Sendable, JSONValueElementsContent { + /// Caller-supplied values to expand explicitly, preserving array values as single elements. + public let values: [JSON] + /// Stores exact authored content without admission, coercion or schema evaluation. + /// + /// - Parameters: + /// - values: Explicit exact payloads in declaration order; nested arrays remain values. + public init(contentsOf values: [JSON]) { self.values = values } + /// Emits array elements into trusted staging; this does not perform admission or evaluation. + /// + /// - Parameters: + /// - elements: Typed siblings or array elements in their authored order. + public func writeValueElements(to elements: inout [JSONDSLNode]) { + elements.append(contentsOf: values.map(JSONDSLNode.literal)) + } +} diff --git a/Tests/CompileNegative/DualDSL/DefinitionInsideProperties.swift b/Tests/CompileNegative/DualDSL/DefinitionInsideProperties.swift new file mode 100644 index 0000000..c7d9fb7 --- /dev/null +++ b/Tests/CompileNegative/DualDSL/DefinitionInsideProperties.swift @@ -0,0 +1,2 @@ +import JSONSchemaDSL +let _ = try JSONSchemaDSL.document { Schema.properties { Definition("id") { Schema.type(.string) } } } diff --git a/Tests/CompileNegative/DualDSL/ElementInsideObject.swift b/Tests/CompileNegative/DualDSL/ElementInsideObject.swift new file mode 100644 index 0000000..9d08907 --- /dev/null +++ b/Tests/CompileNegative/DualDSL/ElementInsideObject.swift @@ -0,0 +1,3 @@ +import JSONSchemaDSL +import JSONValueDSL +let _ = try JSONValueDSL.object { Element("not-an-object-field") } diff --git a/Tests/CompileNegative/DualDSL/FieldInsideSchema.swift b/Tests/CompileNegative/DualDSL/FieldInsideSchema.swift new file mode 100644 index 0000000..c53a4a7 --- /dev/null +++ b/Tests/CompileNegative/DualDSL/FieldInsideSchema.swift @@ -0,0 +1,3 @@ +import JSONSchemaDSL +import JSONValueDSL +let _ = try JSONSchemaDSL.document { Field("invalid", "value") } diff --git a/Tests/CompileNegative/DualDSL/ImplicitFloatingPoint.swift b/Tests/CompileNegative/DualDSL/ImplicitFloatingPoint.swift new file mode 100644 index 0000000..ed67149 --- /dev/null +++ b/Tests/CompileNegative/DualDSL/ImplicitFloatingPoint.swift @@ -0,0 +1,2 @@ +import JSONValueDSL +let _ = try JSONValueDSL.object { Field("cannot-assume-fidelity", 0.1) } diff --git a/Tests/CompileNegative/DualDSL/PropertyInsideDefinitions.swift b/Tests/CompileNegative/DualDSL/PropertyInsideDefinitions.swift new file mode 100644 index 0000000..8b2e45b --- /dev/null +++ b/Tests/CompileNegative/DualDSL/PropertyInsideDefinitions.swift @@ -0,0 +1,2 @@ +import JSONSchemaDSL +let _ = try JSONSchemaDSL.document { Schema.definitions { Property("id") { Schema.type(.string) } } } diff --git a/Tests/CompileNegative/DualDSL/SchemaClauseInsideArray.swift b/Tests/CompileNegative/DualDSL/SchemaClauseInsideArray.swift new file mode 100644 index 0000000..eddb431 --- /dev/null +++ b/Tests/CompileNegative/DualDSL/SchemaClauseInsideArray.swift @@ -0,0 +1,3 @@ +import JSONSchemaDSL +import JSONValueDSL +let _ = try JSONValueDSL.array { Schema.type(.string) } diff --git a/Tests/JSONDSLTests/DSLPrototypeTests.swift b/Tests/JSONDSLTests/DSLPrototypeTests.swift new file mode 100644 index 0000000..14343f0 --- /dev/null +++ b/Tests/JSONDSLTests/DSLPrototypeTests.swift @@ -0,0 +1,298 @@ +import JSON +import JSONDSLCore +import JSONSchema +import JSONSchemaDSL +import JSONValueDSL +// SPDX-License-Identifier: Apache-2.0 +import Testing + +@Suite struct DSLPrototypeTests { + @Test func prototypeValueObjectNestedArrayConditionalAndLoop() throws { + let addOptional = true + let doc = try JSONValueDSL.object { + Field("id", UInt64(9_007_199_254_740_993)) + Field("title", "A customer") + Field("verified", true) + if addOptional { Field("note", .null) } + Field.array("tags") { + Element("one") + Element("two") + Element.array { + Element(10) + Element(20) + } + for i in 1...3 { Element(i) } + } + Field.object("meta") { + Field("kind", "demo") + Field("active", false) + } + } + let o = try #require(doc.objectValue) + #expect((o.members.map { $0.key.string }) == (["id", "title", "verified", "note", "tags", "meta"])) + #expect((o["note"]) == (.null)) + #expect((o["tags"]?.arrayValue?.count) == (6)) + #expect((o["tags"]?.arrayValue?[2].arrayValue?.count) == (2)) + #expect((o["meta"]?.objectValue?["kind"]) == (.string("demo"))) + } + @Test func prototypeEmptyContainersAndNoFlattening() throws { + let value = try JSONValueDSL.object { + Field.object("empty") {} + Field.array("nested") { + Element.array { Element(1) } + } + } + #expect((value.objectValue?["empty"]?.objectValue?.members.count) == (0)) + let a = try #require(value.objectValue?["nested"]?.arrayValue) + #expect((a.count) == (1)) + #expect((a[0].arrayValue?.count) == (1)) + } + @Test func prototypeConditionalAbsenceIsNotNull() throws { + let show = false + let doc = try JSONValueDSL.object { + Field("a", 1) + if show { Field("b", .null) } + } + #expect((doc.objectValue?["b"]) == nil) + #expect((doc.objectValue?.members.count) == (1)) + } + @Test func prototypeChoiceAndExplicitFlatten() throws { + let simple = false + let doc = try JSONValueDSL.array { + Element("initial") + if simple { Element(1) } else { Element(2) } + Elements(contentsOf: [3, 4]) + } + let a = try #require(doc.arrayValue) + #expect((a.count) == (4)) + #expect((a[1]) == (.number(JSONNumber(integer: 2)))) + } + @Test func prototypeDuplicateValueKeysMustThrow() throws { + #expect(throws: JSONFailure.self) { + try JSONValueDSL.object { + Field("name", "first") + Field("name", "second") + } + } + } + @Test func prototypeUnicodeScalarDistinctKeysRemainDistinct() throws { + let a = "\u{e9}" + let b = "e\u{301}" + #expect((a) == (b)) // Swift canonical String equality: demonstration of trap. + let obj = try JSONValueDSL.object { + Field(a, 1) + Field(b, 2) + } + #expect((obj.objectValue?.members.count) == (2)) + #expect(!(JSONKey(a) == JSONKey(b))) + } + @Test func prototypeSchemaRichDraft202012Shape() throws { + let schema = try JSONSchemaDSL.document { + Schema.schemaURI("https://json-schema.org/draft/2020-12/schema") + Schema.identifier("https://example.test/customer") + Schema.title("Customer") + Schema.description("Demo shape") + Schema.type(.object) + Schema.minProperties(1) + Schema.maxProperties(12) + Schema.properties { + Property("id") { Schema.reference("#/$defs/ID") } + Property("name") { + Schema.type(.string) + Schema.minLength(2) + Schema.maxLength(100) + Schema.pattern("^[^0-9]+$") + } + Property("state") { + Schema.enumValues(["new", "active", "closed"]) + Schema.defaultValue("new") + } + Property("orders") { + Schema.type(.array) + Schema.minItems(0) + Schema.uniqueItems(true) + Schema.items { + Schema.type(.integer) + Schema.minimum(JSONNumber(integer: 0)) + } + } + Property("sentinel", allowsAll: false) + } + Schema.required("id", "name") + Schema.patternProperties { PatternProperty("^x-") { Schema.type(.string) } } + Schema.dependentRequired { RequiredDependency("card", requires: ["billingAddress"]) } + Schema.dependentSchemas { DependentSchema("country") { Schema.type(.object) } } + Schema.propertyNames { Schema.type(.string) } + Schema.additionalProperties(false) + Schema.unevaluatedProperties(false) + Schema.definitions { + Definition("ID") { + Schema.type(.integer) + Schema.minimum(JSONNumber(integer: 0)) + } + } + Schema.rawKeyword("x-internal-note", "preserved") + } + let obj = try #require(schema.raw.objectValue) + #expect((obj["type"]) == (.string("object"))) + #expect((obj["properties"]?.objectValue?.members.count) == (5)) + #expect((obj["$defs"]?.objectValue?.members.count) == (1)) + #expect((obj["x-internal-note"]) == (.string("preserved"))) + #expect((obj["dependentRequired"]?.objectValue?.members.count) == (1)) + let plan = try JSONSchemaCompiler().compile(schema) + #expect( + try JSONSchemaValidator().validate(JSONParser().parse(#"{"id":1,"name":"Ada"}"#), against: plan) + .isValid) + #expect( + try !JSONSchemaValidator().validate(JSONParser().parse(#"{"id":-1,"name":"Ada"}"#), against: plan) + .isValid) + } + @Test func prototypeArrayCompositionConditionalAndBooleanSchema() throws { + let include = true + let schema = try JSONSchemaDSL.document { + Schema.type(.array) + Schema.prefixItems { + Rule { Schema.type(.string) } + Rule(false) + if include { Rule { Schema.type(.number) } } + } + Schema.contains { Schema.type(.string) } + Schema.minContains(1) + Schema.maxContains(3) + Schema.unevaluatedItems(false) + Schema.anyOf { + Rule { Schema.minItems(1) } + Rule(true) + } + Schema.oneOf { + Rule(false) + Rule(true) + } + Schema.allOf { + Rule(true) + Rule { Schema.maxItems(10) } + } + Schema.not { Schema.type(.null) } + Schema.ifSchema { Schema.minItems(2) } + Schema.thenSchema { Schema.minItems(3) } + Schema.elseSchema { Schema.minItems(1) } + } + let obj = try #require(schema.raw.objectValue) + #expect((obj["prefixItems"]?.arrayValue?.count) == (3)) + #expect((obj["oneOf"]?.arrayValue?.count) == (2)) + #expect((obj["allOf"]?.arrayValue?.count) == (2)) + let plan = try JSONSchemaCompiler().compile(schema) + #expect(try JSONSchemaValidator().validate(.array(["ok"]), against: plan).isValid) + #expect(try !JSONSchemaValidator().validate(.array(["ok", 1]), against: plan).isValid) + } + @Test func prototypeSchemaVocabularyAndAnnotations() throws { + let c = try JSONSchemaDSL.document { + Schema.vocabulary([("https://example.test/v", true)]) + Schema.anchor("hello") + Schema.dynamicAnchor("node") + Schema.dynamicReference("#node") + Schema.comment("not an assertion") + Schema.format("email") + Schema.contentEncoding("base64") + Schema.contentMediaType("text/plain") + Schema.contentSchema { Schema.type(.string) } + Schema.examples(["Ada", "Grace"]) + Schema.deprecated(true) + Schema.readOnly(true) + Schema.writeOnly(false) + } + #expect((c.raw.objectValue?["$vocabulary"]) != nil) + #expect((c.raw.objectValue?["readOnly"]) == (.boolean(true))) + let plan = try JSONSchemaCompiler().compile(c) + do { + _ = try JSONSchemaValidator().validate("person@example.test", against: plan) + Issue.record("Self dynamic reference is nonproductive, not invalidity") + } catch let error as JSONSchemaEvaluationFailure { + #expect(error.category == .nonproductiveReference) + } + } + @Test func prototypeSchemaDuplicateKeywordsAndPropertiesFail() throws { + #expect(throws: JSONFailure.self) { + try JSONSchemaDSL.document { + Schema.type(.object) + Schema.type(.array) + } + } + #expect(throws: JSONFailure.self) { + try JSONSchemaDSL.document { + Schema.properties { + Property("id") { Schema.type(.string) } + Property("id") { Schema.type(.integer) } + } + } + } + } + @Test func prototypeSchemaConditionalsAndLoopsDoNotEmitFalseSchemas() throws { + let shouldInclude = false + let schema = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { + for name in ["alpha", "beta"] { Property(name) { Schema.type(.string) } } + if shouldInclude { Property("absent", allowsAll: false) } + } + } + let props = try #require(schema.raw.objectValue?["properties"]?.objectValue) + #expect((props.members.map { $0.key.string }) == (["alpha", "beta"])) + #expect((props["absent"]) == nil) + } + @Test func prototypeSchemaBooleanRoot() throws { + let accepting = try JSONSchemaDSL.boolean(true) + let rejecting = try JSONSchemaDSL.boolean(false) + #expect((accepting.raw) == (.boolean(true))) + #expect((rejecting.raw) == (.boolean(false))) + } + @Test func prototypeExactDecimalInputShape() throws { + let exact = try JSONNumber(parsing: "0.1") + let value = try JSONValueDSL.object { Field("decimal", exactNumber: exact) } + #expect((value.objectValue?["decimal"]) == (.number(exact))) + let zero = try JSONNumber(parsing: "0.0") + let schema = try JSONSchemaDSL.document { + Schema.type(.number) + Schema.multipleOf(exact) + Schema.minimum(zero) + } + #expect((schema.raw.objectValue?["multipleOf"]) == (.number(exact))) + } + @Test func prototypePrototypeCapacityAndDepthPreflight() throws { + var limit = JSONLimits.balanced + limit[.maxDepth] = 12 + limit[.arrayItems] = 2 + limit[.objectMembers] = 2 + #expect(throws: JSONFailure.self) { + try JSONValueDSL.array(limits: limit) { + Element(1) + Element(2) + Element(3) + } + } + #expect(throws: JSONFailure.self) { + try JSONValueDSL.object(limits: limit) { + Field("a", 1) + Field("b", 2) + Field("c", 3) + } + } + var shallow = JSONLimits.balanced + shallow[.maxDepth] = 1 + #expect(throws: JSONFailure.self) { + try JSONValueDSL.object(limits: shallow) { + Field.object("a") { Field.object("b") { Field("c", 1) } } + } + } + } + @Test func prototypeTypeBuilderNoConflationOfKeywordAndProperty() throws { + let doc = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { + Property("empty") {} + } + } + #expect( + (doc.raw.objectValue?["properties"]?.objectValue?["empty"]?.objectValue?.members.count) == (0)) + } +} diff --git a/Tests/JSONDSLTests/IntegrationTests.swift b/Tests/JSONDSLTests/IntegrationTests.swift new file mode 100644 index 0000000..336eec8 --- /dev/null +++ b/Tests/JSONDSLTests/IntegrationTests.swift @@ -0,0 +1,36 @@ +import JSON +import JSONSchema +import JSONSchemaDSL +import JSONValueDSL +// SPDX-License-Identifier: Apache-2.0 +import Testing + +@Test func dslExactEngineIntegration() throws { + let tenth = try JSONNumber(parsing: "0.1") + let value = try JSONValueDSL.object { + Field("amount", exactNumber: tenth) + Field("id", UInt64(9_007_199_254_740_993)) + Field.array("nested") { + Element.array { + Element(1) + Element(2) + } + } + } + let manual = try JSONParser().parse(#"{"amount":0.1,"id":9007199254740993,"nested":[[1,2]]}"#) + #expect(value == manual) + let schema = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { + Property("amount") { + Schema.type(.number) + Schema.minimum(tenth) + } + } + Schema.required("amount") + } + let plan = try JSONSchemaCompiler().compile(schema) + #expect(try JSONSchemaValidator().validate(value, against: plan).isValid) + #expect( + try !JSONSchemaValidator().validate(JSONParser().parse(#"{"amount":0.09}"#), against: plan).isValid) +} diff --git a/Tests/JSONDSLTests/ResourceLifecycleTests.swift b/Tests/JSONDSLTests/ResourceLifecycleTests.swift new file mode 100644 index 0000000..aa5e1bc --- /dev/null +++ b/Tests/JSONDSLTests/ResourceLifecycleTests.swift @@ -0,0 +1,220 @@ +import JSON +import JSONDSLCore +import JSONSchema +import JSONSchemaDSL +import JSONValueDSL +import Synchronization +// SPDX-License-Identifier: Apache-2.0 +import Testing + +@Test func dslV18ParentNodeCapacityIncludesAllNestedChildren() throws { + var limits = JSONLimits.balanced + limits[.nodes] = 4 + let accepted = try JSONValueDSL.object(limits: limits) { + Field.array("a") { + Element(1) + Element(2) + } + } + #expect(accepted == (try JSONParser().parse(#"{"a":[1,2]}"#))) + limits[.nodes] = 3 + do { + _ = try JSONValueDSL.object(limits: limits) { + Field.array("a") { + Element(1) + Element(2) + } + } + Issue.record("Parent quota must include nested children") + } catch let error as JSONFailure { + #expect(error.category == .resource && error.code == .limitExceeded) + #expect(error.resource?.metric == .nodes && error.resource?.attemptedUsage == 4) + } +} + +@Test func dslFinalizationSharesWorkAndRetentionAcrossSiblings() throws { + let node = JSONDSLNode.object([ + .init("one", .array([.literal(1), .literal(2)])), + .init("two", .object([.init("text", .literal("é"))])), + ]) + let stats = try node.finalize(limits: .balanced, domain: .core) { _, meter in meter.statistics() } + #expect(stats[.nodes] == 6 && stats[.workUnits] > 10 && stats.peakLogicalRetainedBytes > 0) + var limits = JSONLimits.balanced + limits[.workUnits] = stats[.workUnits] + _ = try node.materialize(limits: limits) + limits[.workUnits] -= 1 + do { + _ = try node.materialize(limits: limits) + Issue.record("Work must not reset at siblings") + } catch let error as JSONFailure { + #expect(error.resource?.metric == .workUnits && error.code == .limitExceeded) + } + limits = .balanced + limits[.retainedBytes] = stats.peakLogicalRetainedBytes + _ = try node.materialize(limits: limits) + limits[.retainedBytes] -= 1 + do { + _ = try node.materialize(limits: limits) + Issue.record("Overlapping finalization ownership must be charged") + } catch let error as JSONFailure { + #expect(error.resource?.metric == .retainedBytes && error.code == .limitExceeded) + } +} + +@Test func dslSchemaDocumentAdmissionContinuesTheSameLedger() throws { + let node = JSONDSLNode.object([.init("title", .literal("x"))]) + let stats = try node.finalize(limits: .balanced, domain: .schemaCompilation) { raw, meter in + _ = try JSONSchemaDocument(raw, meter: &meter) + return meter.statistics() + } + #expect(stats.domain == .schemaCompilation && stats[.nodes] == 4 && stats[.schemaNodes] == 4) + var limits = JSONLimits.balanced + limits[.nodes] = 4 + _ = try JSONSchemaDSL.document(limits: limits) { Schema.title("x") } + limits[.nodes] = 3 + do { + _ = try JSONSchemaDSL.document(limits: limits) { Schema.title("x") } + Issue.record("Document admission must not start a fresh meter") + } catch let error as JSONFailure { + #expect(error.resource?.domain == .schemaCompilation && error.resource?.metric == .nodes) + #expect(error.resource?.attemptedUsage == 4) + } +} + +@Test func dslLiteralPayloadAdmissionCannotBypassCoreCaps() throws { + let payloads: [(JSON, JSONResourceMetric, UInt64)] = [ + (.array([1, 2]), .arrayItems, 1), + (.object(try JSONObject(members: [.init("long", value: 1)])), .keyBytes, 3), + (.string("é"), .stringBytes, 1), + (.number(try JSONNumber(parsing: "1234")), .numberDigits, 3), + (.number(try JSONNumber(parsing: "1e9")), .absoluteExponent, 8), + ] + for (payload, metric, cap) in payloads { + var limits = JSONLimits.balanced + limits[metric] = cap + do { + _ = try JSONValueDSL.array(limits: limits) { Element(payload) } + Issue.record("Literal payload must be admitted") + } catch let error as JSONFailure { + #expect(error.code == .limitExceeded && error.resource?.metric == metric) + } + } +} + +@Test func dslFinalizationFailureIsTerminalEvenWhenPackageContinuationCatchesIt() throws { + var observed = false + do { + _ = try JSONDSLNode.literal(.null).finalize(limits: .balanced, domain: .core) { value, meter in + do { try meter.work(UInt64.max) } catch let error as JSONFailure { + observed = true + #expect(error.code == .counterOverflow) + } + return value + } + Issue.record("Caught finalization failure must prevent publication") + } catch let error as JSONFailure { #expect(observed && error.code == .counterOverflow) } +} + +@Test func dslFlatIRRejectsFiveThousandLevelsWithoutRecursiveLoweringOrIRTeardown() throws { + var node = JSONDSLNode.literal(.null) + for _ in 0..<5_000 { node = .array([node]) } + var limits = JSONLimits.balanced + limits[.maxDepth] = 64 + do { + _ = try node.materialize(limits: limits) + Issue.record("Deep staging must fail the finalization ceiling") + } catch let error as JSONFailure { + #expect(error.resource?.metric == .maxDepth && error.resource?.attemptedUsage == 65) + } + var admitted = JSONDSLNode.literal(.null) + for _ in 0..<128 { admitted = .array([admitted]) } + let exact = try admitted.materialize() + #expect( + try JSONWriter().writeString(exact) == String(repeating: "[", count: 128) + "null" + + String(repeating: "]", count: 128)) +} + +@Test func dslV19CancellationAtEntryDoesNotRunAuthoredCallback() async throws { + let started = Mutex(false) + let gate = AsyncStream.makeStream() + let task = Task { + for await _ in gate.stream { break } + return try JSONValueDSL.object { + Field( + "visited", + started.withLock { state -> Bool in + state = true + return true + }) + } + } + task.cancel() + gate.continuation.yield(()) + gate.continuation.finish() + await #expect(throws: CancellationError.self) { try await task.value } + #expect(started.withLock { !$0 }) +} + +@Test func dslV19CancellationInsideOwnedFinalizationNeverReturnsAValue() async throws { + let cancelled = Mutex(false) + let handle = Mutex?>(nil) + let gate = AsyncStream.makeStream() + let node = JSONDSLNode.array((0..<4_096).map { .literal(.number(JSONNumber(integer: $0))) }) + let task = Task { + for await _ in gate.stream { break } + var limits = JSONLimits.balanced + limits[.cancellationQuantum] = 1 + return try node.finalize( + limits: limits, domain: .core, + checkpointObserver: { work in + if work >= 64 { + cancelled.withLock { $0 = true } + handle.withLock { $0?.cancel() } + } + } + ) { value, _ in value } + } + handle.withLock { $0 = task } + gate.continuation.yield(()) + gate.continuation.finish() + await #expect(throws: CancellationError.self) { try await task.value } + #expect(cancelled.withLock { $0 }) + handle.withLock { $0 = nil } +} + +@Test func dslSharedFinalizationAndPlansAreInvocationOwned() async throws { + let declaration = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { + Property("id") { + Schema.type(.integer) + Schema.minimum(JSONNumber(integer: 1)) + } + } + Schema.required("id") + } + let plan = try JSONSchemaCompiler().compile(declaration) + let field = Field("id", UInt64(9_007_199_254_740_993)) + try await withThrowingTaskGroup(of: Bool.self) { group in + for index in 0..<32 { + group.addTask { + var limits = JSONLimits.balanced + if index.isMultiple(of: 2) { + limits[.nodes] = 1 + do { + _ = try JSONValueDSL.object(limits: limits) { field } + return false + } catch let error as JSONFailure { return error.resource?.metric == .nodes } + } + let value = try JSONValueDSL.object { field } + return try JSONSchemaValidator().validate(value, against: plan).isValid + } + } + var completed = 0 + for try await outcome in group { + #expect(outcome) + completed += 1 + } + #expect(completed == 32) + } +} diff --git a/Tests/JSONDSLTests/SemanticTests.swift b/Tests/JSONDSLTests/SemanticTests.swift new file mode 100644 index 0000000..f8f7091 --- /dev/null +++ b/Tests/JSONDSLTests/SemanticTests.swift @@ -0,0 +1,479 @@ +import JSON +import JSONSchema +import JSONSchemaDSL +import JSONValueDSL +// SPDX-License-Identifier: Apache-2.0 +import Testing + +private func parity( + _ declaration: JSONSchemaDocument, _ text: String, + valid: [String], invalid: [String], registry: JSONSchemaRegistry = .empty +) throws { + let handwritten = try JSONSchemaDocument(JSONParser().parse(text)) + #expect(try JSONComparison.equals(declaration.raw, handwritten.raw)) + let compiler = JSONSchemaCompiler() + let authored = try compiler.compile(declaration, registry: registry) + let manual = try compiler.compile(handwritten, registry: registry) + let validator = JSONSchemaValidator(options: .init(collectAnnotations: true)) + for (instances, expected) in [(valid, true), (invalid, false)] { + for text in instances { + let instance = try JSONParser().parse(text) + let a = try validator.validate(instance, against: authored) + let b = try validator.validate(instance, against: manual) + #expect(a.isValid == expected) + #expect(a.isValid == b.isValid) + #expect(a.annotations.map(\.value) == b.annotations.map(\.value)) + #expect(a.annotations.map(\.keywordLocation) == b.annotations.map(\.keywordLocation)) + } + } +} + +private func duplicate(_ body: () throws -> Void) throws { + do { + try body() + Issue.record("Exact duplicate declaration must throw") + } catch let error as JSONFailure { + #expect(error.category == .syntax && error.code == .duplicateKey) + #expect(error.resource == nil) + } +} + +@Test func dslV01ExactIntegersIncludeBoth128BitBoundaries() throws { + let value = try JSONValueDSL.object { + Field("large", UInt64(9_007_199_254_740_993)) + Field("signed", Int128.min) + Field("unsigned", UInt128.max) + } + let expected = try JSONParser().parse( + "{\"large\":9007199254740993,\"signed\":\(Int128.min),\"unsigned\":\(UInt128.max)}") + #expect(value == expected) + #expect(try #require(value.objectValue?["signed"]?.numberValue).integer(as: Int128.self) == Int128.min) + #expect( + try #require(value.objectValue?["unsigned"]?.numberValue).integer(as: UInt128.self) == UInt128.max) +} + +@Test func dslV02ExactDecimalLexemeAndMultipleOfNeverUseEpsilon() throws { + let tenth = try JSONNumber(parsing: "1.00e-1") + let value = try JSONValueDSL.object { Field("n", exactNumber: tenth) } + #expect(try #require(value.objectValue?["n"]?.numberValue).numericText(style: .preserved) == "1.00e-1") + let schema = try JSONSchemaDSL.document { + Schema.type(.number) + Schema.minimum(tenth) + Schema.multipleOf(tenth) + Schema.maximum(JSONNumber(integer: 2)) + } + try parity( + schema, #"{"type":"number","minimum":1.00e-1,"multipleOf":1.00e-1,"maximum":2}"#, + valid: ["0.1", "0.3", "2"], invalid: ["0.0999999999999999999999", "0.3000000000000000000001", "2.1"]) +} + +@Test func dslV04EveryExactDuplicateTableRejects() throws { + try duplicate { + _ = try JSONValueDSL.object { + Field("same", 1) + Field("same", 2) + } + } + try duplicate { + _ = try JSONSchemaDSL.document { + Schema.title("a") + Schema.title("b") + } + } + try duplicate { + _ = try JSONSchemaDSL.document { + Schema.properties { + Property("id") {} + Property("id") {} + } + } + } + try duplicate { + _ = try JSONSchemaDSL.document { + Schema.definitions { + Definition("id") {} + Definition("id") {} + } + } + } + try duplicate { + _ = try JSONSchemaDSL.document { + Schema.patternProperties { + PatternProperty("x") {} + PatternProperty("x") {} + } + } + } + try duplicate { + _ = try JSONSchemaDSL.document { + Schema.dependentSchemas { + DependentSchema("x") {} + DependentSchema("x") {} + } + } + } + try duplicate { + _ = try JSONSchemaDSL.document { + Schema.dependentRequired { + RequiredDependency("x", requires: ["a"]) + RequiredDependency("x", requires: ["b"]) + } + } + } + try duplicate { + _ = try JSONSchemaDSL.document { + Schema.vocabulary([("https://e.test/v", false), ("https://e.test/v", false)]) + } + } +} + +@Test func dslV05ScalarKeysLiteralPathsOrderAndEquality() throws { + let value = try JSONValueDSL.object { + Field("é", 1) + Field("e\u{301}", 2) + Field("a/b~.c", 3) + Field("", .null) + } + let object = try #require(value.objectValue) + #expect( + object.members.map { Array($0.key.string.unicodeScalars) } + == ["é", "e\u{301}", "a/b~.c", ""].map { Array($0.unicodeScalars) }) + #expect(object["é"] == 1 && object["e\u{301}"] == 2) + #expect(try JSONPointer(parsing: "/a~1b~0.c").resolve(in: value) == 3) + let reversed = try JSONValueDSL.object { + Field("", .null) + Field("a/b~.c", 3) + Field("e\u{301}", 2) + Field("é", 1) + } + #expect(value == reversed) + #expect(try JSONWriter().writeString(value) != JSONWriter().writeString(reversed)) + let schema = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { + Property("é") { Schema.constant(1) } + Property("e\u{301}") { Schema.constant(2) } + } + Schema.required("é", "e\u{301}") + } + try parity( + schema, + #"{"type":"object","properties":{"é":{"const":1},"e\u0301":{"const":2}},"required":["é","e\u0301"]}"#, + valid: [#"{"é":1,"e\u0301":2}"#], invalid: [#"{"é":1}"#, #"{"é":2,"e\u0301":1}"#]) +} + +@Test func dslV06ConditionalOmissionHasNoSubstituteValue() throws { + let include = false + let value = try JSONValueDSL.object { + if include { Field("missing", .null) } + Field("null", .null) + } + #expect(try value.presence(of: "missing") == .absent) + #expect(try value.presence(of: "null") == .null) + let schema = try JSONSchemaDSL.document { + if include { Schema.not {} } + Schema.properties { if include { Property("missing", allowsAll: false) } } + } + try parity(schema, #"{"properties":{}}"#, valid: ["null", "{}", #"{"missing":1}"#], invalid: []) +} + +@Test func dslV07OnlyExplicitElementsExpand() throws { + let one = try JSONValueDSL.array { + Element.array { + Element(1) + Element(2) + } + Element(.array([3, 4])) + } + let expanded = try JSONValueDSL.array { Elements(contentsOf: [.array([1, 2]), 3, 4]) } + #expect(one == (try JSONParser().parse("[[1,2],[3,4]]"))) + #expect(expanded == (try JSONParser().parse("[[1,2],3,4]"))) +} + +@Test func dslV08And09FalseTrueEmptyAndNullRemainDistinct() throws { + let rejecting = try JSONSchemaDSL.boolean(false) + let accepting = try JSONSchemaDSL.boolean(true) + let empty = try JSONSchemaDSL.document {} + #expect(rejecting.raw == .boolean(false) && accepting.raw == .boolean(true)) + #expect(empty.raw.objectValue?.isEmpty == true && empty.raw != rejecting.raw && empty.raw != .null) + try parity(rejecting, "false", valid: [], invalid: ["null", "{}", "false", "0"]) + try parity(accepting, "true", valid: ["null", "{}", "false", "0"], invalid: []) + try parity(empty, "{}", valid: ["null", "{}", "false", "0"], invalid: []) + #expect(throws: JSONSchemaCompilationFailure.self) { try JSONSchemaDocument(.null) } +} + +@Test func dslV10RequirednessIsOnlyExplicit() throws { + let optional = try JSONSchemaDSL.document { + Schema.properties { Property("n") { Schema.type(.integer) } } + } + let required = try JSONSchemaDSL.document { + Schema.properties { Property("n") { Schema.type(.integer) } } + Schema.required("n") + } + try parity( + optional, #"{"properties":{"n":{"type":"integer"}}}"#, valid: ["{}", #"{"n":1}"#], + invalid: [#"{"n":"1"}"#]) + try parity( + required, #"{"properties":{"n":{"type":"integer"}},"required":["n"]}"#, valid: [#"{"n":1}"#], + invalid: ["{}", #"{"n":null}"#]) +} + +@Test func dslV11DefaultAndUnknownMetadataNeverMutateInstances() throws { + let schema = try JSONSchemaDSL.document { + Schema.properties { + Property("n") { + Schema.type(.integer) + Schema.defaultValue(7) + } + } + Schema.rawKeyword("x-note", "A declaration, not an instruction") + } + let instance = try JSONValueDSL.object {} + let result = try JSONSchemaValidator().validate(instance, against: JSONSchemaCompiler().compile(schema)) + #expect(result.isValid && instance.objectValue?.isEmpty == true) + let property = try schema.node(at: JSONPointer(parsing: "/properties/n")) + #expect(try property.declaration(of: "default") == .value(7)) + #expect( + try schema.node().declaration(of: "x-note") == .value(.string("A declaration, not an instruction"))) +} + +@Test func dslV12FormatPolicyStaysWithValidator() throws { + let schema = try JSONSchemaDSL.document { + Schema.type(.string) + Schema.format("email") + } + let plan = try JSONSchemaCompiler().compile(schema) + let annotation = try JSONSchemaValidator(options: .init(collectAnnotations: true)).validate( + "bad", against: plan) + #expect(annotation.isValid) + #expect( + annotation.annotations.contains { $0.keyword == JSONKey("format") && $0.value == .string("email") }) + #expect( + try !JSONSchemaValidator(options: .init(formatAssertion: true)).validate("bad", against: plan).isValid + ) + #expect( + try JSONSchemaValidator(options: .init(formatAssertion: true)).validate( + "person@example.test", against: plan + ).isValid) +} + +@Test func dslV13AlternativesAndConditionalsPreserveDeclarations() throws { + let schema = try JSONSchemaDSL.document { + Schema.allOf { + Rule { Schema.type(.integer) } + Rule { Schema.minimum(JSONNumber(integer: 0)) } + } + Schema.anyOf { + Rule { Schema.multipleOf(JSONNumber(integer: 2)) } + Rule { Schema.constant(3) } + } + Schema.oneOf { + Rule(false) + Rule(true) + } + Schema.ifSchema { Schema.minimum(JSONNumber(integer: 10)) } + Schema.thenSchema { Schema.maximum(JSONNumber(integer: 12)) } + Schema.elseSchema { Schema.maximum(JSONNumber(integer: 6)) } + Schema.not { Schema.constant(4) } + } + try parity( + schema, + #"{"allOf":[{"type":"integer"},{"minimum":0}],"anyOf":[{"multipleOf":2},{"const":3}],"oneOf":[false,true],"if":{"minimum":10},"then":{"maximum":12},"else":{"maximum":6},"not":{"const":4}}"#, + valid: ["0", "2", "3", "6", "10", "12"], invalid: ["-2", "1", "4", "8", "14", "0.1"]) +} + +@Test func dslV14PointerAnchorAndNestedIdentifierUseCompiler() throws { + let schema = try JSONSchemaDSL.document { + Schema.identifier("https://e.test/root") + Schema.definitions { + Definition("a/b~") { + Schema.type(.integer) + Schema.anchor("small") + } + Definition("child") { + Schema.identifier("child") + Schema.type(.integer) + } + } + Schema.allOf { + Rule { Schema.reference("#/$defs/a~1b~0") } + Rule { Schema.reference("#sm%61ll") } + Rule { Schema.reference("child") } + } + } + try parity( + schema, + ##"{"$id":"https://e.test/root","$defs":{"a/b~":{"type":"integer","$anchor":"small"},"child":{"$id":"child","type":"integer"}},"allOf":[{"$ref":"#/$defs/a~1b~0"},{"$ref":"#sm%61ll"},{"$ref":"child"}]}"##, + valid: ["1"], invalid: ["\"1\"", "1.1"]) +} + +@Test func dslV14DynamicScopeAndOfflineRegistryAreUnmodified() throws { + let base = try JSONSchemaDSL.document { + Schema.identifier("https://e.test/tree") + Schema.dynamicAnchor("node") + Schema.type(.object) + Schema.properties { Property("child") { Schema.dynamicReference("#node") } } + } + let resource = try JSONSchemaDocument(base.raw, retrievalURI: JSONSchemaURI("https://e.test/tree")) + let registry = try JSONSchemaRegistry(documents: [resource]) + let schema = try JSONSchemaDSL.document { + Schema.identifier("https://e.test/strict") + Schema.dynamicAnchor("node") + Schema.reference("https://e.test/tree") + Schema.unevaluatedProperties(false) + } + try parity( + schema, + ##"{"$id":"https://e.test/strict","$dynamicAnchor":"node","$ref":"https://e.test/tree","unevaluatedProperties":false}"##, + valid: ["{}", #"{"child":{}}"#], invalid: [#"{"extra":1}"#, #"{"child":{"extra":1}}"#], + registry: registry) + do { + _ = try JSONSchemaCompiler().compile(schema) + Issue.record("Offline resource must be explicitly supplied") + } catch let error as JSONSchemaCompilationFailure { #expect(error.category == .missingResource) } +} + +@Test func dslV15RequiredUnknownVocabularyRemainsAnOperationalFailure() throws { + let meta = try JSONSchemaDSL.document { + Schema.identifier("https://e.test/dialect") + Schema.schemaURI("https://json-schema.org/draft/2020-12/schema") + Schema.vocabulary([("https://e.test/unknown-vocabulary", true)]) + } + let registry = try JSONSchemaRegistry(documents: [ + JSONSchemaDocument(meta.raw, retrievalURI: JSONSchemaURI("https://e.test/dialect")) + ]) + let schema = try JSONSchemaDSL.document { + Schema.schemaURI("https://e.test/dialect") + Schema.rawKeyword("custom", .null) + } + do { + _ = try JSONSchemaCompiler().compile(schema, registry: registry) + Issue.record("Required unknown vocabulary must throw") + } catch let error as JSONSchemaCompilationFailure { #expect(error.category == .vocabulary) } +} + +@Test func dslV16MalformedBoundsAndEmptyAlternativesAreNotRepaired() throws { + let malformed = [ + try JSONSchemaDSL.document { Schema.minLength(-1) }, + try JSONSchemaDSL.document { Schema.multipleOf(JSONNumber(integer: 0)) }, + try JSONSchemaDSL.document { Schema.oneOf {} }, + try JSONSchemaDSL.document { Schema.required("same", "same") }, + ] + for declaration in malformed { + do { + _ = try JSONSchemaCompiler().compile(declaration) + Issue.record("Malformed declaration must fail compilation") + } catch let error as JSONSchemaCompilationFailure { + #expect(error.category == .schemaSyntax || error.category == .metaSchema) + } + } + let huge = try JSONNumber(parsing: "1e100") + let schema = try JSONSchemaDSL.document { + Schema.type(.integer) + Schema.minimum(huge) + } + try parity( + schema, #"{"type":"integer","minimum":1e100}"#, valid: ["1e100"], + invalid: ["99999999999999999999999999999999999999999999"]) +} + +@Test func dslV17ContainsAndUnevaluatedAnnotationsRemainEngineOwned() throws { + let schema = try JSONSchemaDSL.document { + Schema.contains { Schema.type(.integer) } + Schema.minContains(1) + Schema.maxContains(2) + Schema.unevaluatedItems(false) + } + try parity( + schema, #"{"contains":{"type":"integer"},"minContains":1,"maxContains":2,"unevaluatedItems":false}"#, + valid: ["[1]", "[1,2]"], invalid: ["[]", "[1,2,3]", #"[1,"x"]"#]) + let plan = try JSONSchemaCompiler().compile(schema) + let report = try JSONSchemaValidator(options: .init(collectAnnotations: true)).validate( + .array([1, 2]), against: plan) + #expect(report.annotations.contains { $0.keyword == JSONKey("contains") && $0.value == .array([0, 1]) }) +} + +@Test func dslV17SuccessfulAnyOfBranchesUnionEvaluatedProperties() throws { + let schema = try JSONSchemaDSL.document { + Schema.anyOf { + Rule { + Schema.properties { Property("a") { Schema.type(.integer) } } + Schema.required("a") + } + Rule { + Schema.properties { Property("b") { Schema.type(.string) } } + Schema.required("b") + } + } + Schema.unevaluatedProperties(false) + } + try parity( + schema, + #"{"anyOf":[{"properties":{"a":{"type":"integer"}},"required":["a"]},{"properties":{"b":{"type":"string"}},"required":["b"]}],"unevaluatedProperties":false}"#, + valid: [#"{"a":1}"#, #"{"b":"yes"}"#, #"{"a":1,"b":"yes"}"#], + invalid: ["{}", #"{"a":1,"b":2}"#, #"{"a":1,"extra":1}"#]) +} + +@Test func dslV20AdditionalKeywordShapeAndScalarLengthParity() throws { + let schema = try JSONSchemaDSL.document { + Schema.types([.string, .null]) + Schema.minLength(2) + Schema.maxLength(3) + Schema.examples(["e\u{301}", .null]) + Schema.readOnly() + Schema.writeOnly(false) + Schema.deprecated(false) + Schema.contentEncoding("base64") + Schema.contentMediaType("text/plain") + Schema.contentSchema { Schema.type(.string) } + } + try parity( + schema, + #"{"type":["string","null"],"minLength":2,"maxLength":3,"examples":["e\u0301",null],"readOnly":true,"writeOnly":false,"deprecated":false,"contentEncoding":"base64","contentMediaType":"text/plain","contentSchema":{"type":"string"}}"#, + valid: ["null", #""e\u0301""#, #""abc""#], invalid: [#""é""#, #""abcd""#, "1"]) +} + +// Draft 2020-12 validation section 6.1.2 recommends nonempty enum arrays but +// does not require them. Preserve the real compiler's empty-set behavior. +@Test func dslEmptyEnumCompilesAndRejectsEveryInstance() throws { + let schema = try JSONSchemaDSL.document { Schema.enumValues([]) } + try parity(schema, #"{"enum":[]}"#, valid: [], invalid: ["null", "true", "1", "[]", "{}", #""text""#]) +} + +@Test func dslNumericObjectAndDependencyFactoriesMatchWrittenVocabulary() throws { + let schema = try JSONSchemaDSL.document { + Schema.type(.object); Schema.minProperties(1); Schema.maxProperties(3) + Schema.propertyNames { Schema.pattern("^[a-z]") } + Schema.properties { + Property("n") { + Schema.type(.integer); Schema.minimum(JSONNumber(integer: 0)); Schema.maximum(JSONNumber(integer: 10)) + Schema.exclusiveMinimum(JSONNumber(integer: 0)); Schema.exclusiveMaximum(JSONNumber(integer: 10)) + Schema.multipleOf(JSONNumber(integer: 3)) + } + Property("flag") { Schema.type(.boolean) } + } + Schema.patternProperties { PatternProperty("^x-") { Schema.type(.string) } } + Schema.dependentRequired { RequiredDependency("n", requires: ["flag"]) } + Schema.dependentSchemas { DependentSchema("flag") { Schema.required("n") } } + Schema.additionalProperties(false) + } + try parity(schema, #"{"type":"object","minProperties":1,"maxProperties":3,"propertyNames":{"pattern":"^[a-z]"},"properties":{"n":{"type":"integer","minimum":0,"maximum":10,"exclusiveMinimum":0,"exclusiveMaximum":10,"multipleOf":3},"flag":{"type":"boolean"}},"patternProperties":{"^x-":{"type":"string"}},"dependentRequired":{"n":["flag"]},"dependentSchemas":{"flag":{"required":["n"]}},"additionalProperties":false}"#, + valid: [#"{"n":3,"flag":false}"#, #"{"n":9,"flag":true,"x-one":"yes"}"#], + invalid: ["{}", #"{"n":3}"#, #"{"flag":true}"#, #"{"n":0,"flag":true}"#, #"{"n":10,"flag":true}"#, #"{"n":3,"flag":true,"x-a":1}"#, #"{"n":3,"flag":true,"other":1}"#, #"{"n":3,"flag":true,"x-a":"a","x-b":"b"}"#]) +} + +@Test func dslSchemaValuedApplicatorsAndRawBooleanEscapePreserveMeaning() throws { + let schema = try JSONSchemaDSL.document { + Schema.type(.array); Schema.minItems(1); Schema.maxItems(3); Schema.uniqueItems(true) + Schema.prefixItems { Rule { Schema.type(.string) } } + Schema.items { Schema.type(.integer) } + Schema.unevaluatedItems { Schema.type(.integer) } + } + try parity(schema, #"{"type":"array","minItems":1,"maxItems":3,"uniqueItems":true,"prefixItems":[{"type":"string"}],"items":{"type":"integer"},"unevaluatedItems":{"type":"integer"}}"#, + valid: [#"["first"]"#, #"["first",1,2]"#], invalid: ["[]", #"["first",1,1]"#, #"["first","second"]"#, #"["first",1,2,3]"#]) + let object = try JSONSchemaDSL.document { Schema.type(.object); Schema.additionalProperties { Schema.type(.integer) }; Schema.unevaluatedProperties { Schema.type(.integer) } } + try parity(object, #"{"type":"object","additionalProperties":{"type":"integer"},"unevaluatedProperties":{"type":"integer"}}"#, + valid: ["{}", #"{"anything":1}"#], invalid: [#"{"anything":"1"}"#]) + let noNames = try JSONSchemaDSL.document { Schema.rawKeyword("propertyNames", .boolean(false)) } + try parity(noNames, #"{"propertyNames":false}"#, valid: ["{}", "null"], invalid: [#"{"name":1}"#]) +} diff --git a/Tests/JSONDSLTests/StressTypeCheckTests.swift b/Tests/JSONDSLTests/StressTypeCheckTests.swift new file mode 100644 index 0000000..a2fa18b --- /dev/null +++ b/Tests/JSONDSLTests/StressTypeCheckTests.swift @@ -0,0 +1,259 @@ +import JSON +import JSONSchema +import JSONSchemaDSL +import JSONValueDSL +// SPDX-License-Identifier: Apache-2.0 +import Testing + +@Suite struct StressTypeCheckTests { + /// Compile-time fixture: 96 heterogeneously placed declarations without + /// fixed-arity buildBlock overloads. No speed claim without proper profiling. + @Test func prototypeWideSchemaAndValueBlocks() throws { + let schema = try JSONSchemaDSL.document { + Schema.type(.object) + Schema.properties { + Property("field001") { Schema.type(.string) } + Property("field002") { Schema.type(.string) } + Property("field003") { Schema.type(.string) } + Property("field004") { + Schema.type(.string) + Schema.minLength(4) + } + Property("field005") { Schema.type(.string) } + Property("field006") { Schema.type(.string) } + Property("field007") { Schema.type(.string) } + Property("field008") { + Schema.type(.string) + Schema.minLength(1) + } + Property("field009") { Schema.type(.string) } + Property("field010") { Schema.type(.string) } + Property("field011") { Schema.type(.string) } + Property("field012") { + Schema.type(.string) + Schema.minLength(5) + } + Property("field013") { Schema.type(.string) } + Property("field014") { Schema.type(.string) } + Property("field015") { Schema.type(.string) } + Property("field016") { + Schema.type(.string) + Schema.minLength(2) + } + Property("field017") { Schema.type(.string) } + Property("field018") { Schema.type(.string) } + Property("field019") { Schema.type(.string) } + Property("field020") { + Schema.type(.string) + Schema.minLength(6) + } + Property("field021") { Schema.type(.string) } + Property("field022") { Schema.type(.string) } + Property("field023") { Schema.type(.string) } + Property("field024") { + Schema.type(.string) + Schema.minLength(3) + } + Property("field025") { Schema.type(.string) } + Property("field026") { Schema.type(.string) } + Property("field027") { Schema.type(.string) } + Property("field028") { + Schema.type(.string) + Schema.minLength(0) + } + Property("field029") { Schema.type(.string) } + Property("field030") { Schema.type(.string) } + Property("field031") { Schema.type(.string) } + Property("field032") { + Schema.type(.string) + Schema.minLength(4) + } + Property("field033") { Schema.type(.string) } + Property("field034") { Schema.type(.string) } + Property("field035") { Schema.type(.string) } + Property("field036") { + Schema.type(.string) + Schema.minLength(1) + } + Property("field037") { Schema.type(.string) } + Property("field038") { Schema.type(.string) } + Property("field039") { Schema.type(.string) } + Property("field040") { + Schema.type(.string) + Schema.minLength(5) + } + Property("field041") { Schema.type(.string) } + Property("field042") { Schema.type(.string) } + Property("field043") { Schema.type(.string) } + Property("field044") { + Schema.type(.string) + Schema.minLength(2) + } + Property("field045") { Schema.type(.string) } + Property("field046") { Schema.type(.string) } + Property("field047") { Schema.type(.string) } + Property("field048") { + Schema.type(.string) + Schema.minLength(6) + } + Property("field049") { Schema.type(.string) } + Property("field050") { Schema.type(.string) } + Property("field051") { Schema.type(.string) } + Property("field052") { + Schema.type(.string) + Schema.minLength(3) + } + Property("field053") { Schema.type(.string) } + Property("field054") { Schema.type(.string) } + Property("field055") { Schema.type(.string) } + Property("field056") { + Schema.type(.string) + Schema.minLength(0) + } + Property("field057") { Schema.type(.string) } + Property("field058") { Schema.type(.string) } + Property("field059") { Schema.type(.string) } + Property("field060") { + Schema.type(.string) + Schema.minLength(4) + } + Property("field061") { Schema.type(.string) } + Property("field062") { Schema.type(.string) } + Property("field063") { Schema.type(.string) } + Property("field064") { + Schema.type(.string) + Schema.minLength(1) + } + Property("field065") { Schema.type(.string) } + Property("field066") { Schema.type(.string) } + Property("field067") { Schema.type(.string) } + Property("field068") { + Schema.type(.string) + Schema.minLength(5) + } + Property("field069") { Schema.type(.string) } + Property("field070") { Schema.type(.string) } + Property("field071") { Schema.type(.string) } + Property("field072") { + Schema.type(.string) + Schema.minLength(2) + } + Property("field073") { Schema.type(.string) } + Property("field074") { Schema.type(.string) } + Property("field075") { Schema.type(.string) } + Property("field076") { + Schema.type(.string) + Schema.minLength(6) + } + Property("field077") { Schema.type(.string) } + Property("field078") { Schema.type(.string) } + Property("field079") { Schema.type(.string) } + Property("field080") { + Schema.type(.string) + Schema.minLength(3) + } + Property("field081") { Schema.type(.string) } + Property("field082") { Schema.type(.string) } + Property("field083") { Schema.type(.string) } + Property("field084") { + Schema.type(.string) + Schema.minLength(0) + } + Property("field085") { Schema.type(.string) } + Property("field086") { Schema.type(.string) } + Property("field087") { Schema.type(.string) } + Property("field088") { + Schema.type(.string) + Schema.minLength(4) + } + Property("field089") { Schema.type(.string) } + Property("field090") { Schema.type(.string) } + Property("field091") { Schema.type(.string) } + Property("field092") { + Schema.type(.string) + Schema.minLength(1) + } + Property("field093") { Schema.type(.string) } + Property("field094") { Schema.type(.string) } + Property("field095") { Schema.type(.string) } + Property("field096") { + Schema.type(.string) + Schema.minLength(5) + } + } + } + #expect((schema.raw.objectValue?["properties"]?.objectValue?.members.count) == (96)) + let doc = try JSONValueDSL.object { + Field("field001", "value1") + Field("field002", "value2") + Field("field003", "value3") + Field("field004", "value4") + Field("field005", "value5") + Field("field006", "value6") + Field("field007", "value7") + Field("field008", "value8") + Field("field009", "value9") + Field("field010", "value10") + Field("field011", "value11") + Field("field012", "value12") + Field("field013", "value13") + Field("field014", "value14") + Field("field015", "value15") + Field("field016", "value16") + Field("field017", "value17") + Field("field018", "value18") + Field("field019", "value19") + Field("field020", "value20") + Field("field021", "value21") + Field("field022", "value22") + Field("field023", "value23") + Field("field024", "value24") + Field("field025", "value25") + Field("field026", "value26") + Field("field027", "value27") + Field("field028", "value28") + Field("field029", "value29") + Field("field030", "value30") + Field("field031", "value31") + Field("field032", "value32") + Field("field033", "value33") + Field("field034", "value34") + Field("field035", "value35") + Field("field036", "value36") + Field("field037", "value37") + Field("field038", "value38") + Field("field039", "value39") + Field("field040", "value40") + Field("field041", "value41") + Field("field042", "value42") + Field("field043", "value43") + Field("field044", "value44") + Field("field045", "value45") + Field("field046", "value46") + Field("field047", "value47") + Field("field048", "value48") + Field("field049", "value49") + Field("field050", "value50") + Field("field051", "value51") + Field("field052", "value52") + Field("field053", "value53") + Field("field054", "value54") + Field("field055", "value55") + Field("field056", "value56") + Field("field057", "value57") + Field("field058", "value58") + Field("field059", "value59") + Field("field060", "value60") + Field("field061", "value61") + Field("field062", "value62") + Field("field063", "value63") + Field("field064", "value64") + } + #expect((doc.objectValue?.members.count) == (64)) + let plan = try JSONSchemaCompiler().compile(schema) + #expect(try JSONSchemaValidator().validate(doc, against: plan).isValid) + #expect( + try !JSONSchemaValidator().validate(JSONParser().parse(#"{"field001":1}"#), against: plan).isValid + ) + } +} From 8fc83cad69df9f28af133c173391ae677804e304 Mon Sep 17 00:00:00 2001 From: Thorsten Fuchs <76904008+ThorFuchs@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:53:01 +0200 Subject: [PATCH 2/7] docs: qualify DSL declarations and supporting catalog routes Retain measured variadic composition, record real native and WASI outcomes and the disk blocker, preserve all product-guide checks, and complete prototype test provenance. --- .../Architecture/DualDSL/Decisions.md | 23 +++++++++++---- Documentation/Architecture/DualDSL/Plan.md | 10 +++---- .../Architecture/DualDSL/Progress.json | 29 ++++++++++++++----- .../Architecture/ExtractionManifest.json | 24 +++++++++++++++ Documentation/CI/README.md | 8 ++--- Documentation/DocumentationTooling.md | 7 +++-- Scripts/build_documentation_site.py | 5 +++- 7 files changed, 80 insertions(+), 26 deletions(-) diff --git a/Documentation/Architecture/DualDSL/Decisions.md b/Documentation/Architecture/DualDSL/Decisions.md index c99cd0c..5f3eb74 100644 --- a/Documentation/Architecture/DualDSL/Decisions.md +++ b/Documentation/Architecture/DualDSL/Decisions.md @@ -57,12 +57,23 @@ new Boolean-schema overload aliases are deferred: existing Rule(Boolean), table initializers and rawKeyword preserve the complete declaration without another surface. The identical prototype rawSchemaKeyword synonym is removed in favor of rawKeyword. -## D5 — Compiler strategy (pending measurement) - -The initial integration retains variadic buildBlock and conditional context conformances. -G4 records actual Swift 6.4 timings, diagnostics and memory observations before selecting -it over a pairwise buildPartialBlock alternative. Measurements under concurrent host load -are observations, not a quiet-host or broad compiler-throughput guarantee. +## D5 — Retain measured variadic composition + +Native Swift 6.4 compiled both strategies against the real engine. The final +comparison passed 41 commands, including 22 scaling probes: value/schema blocks +of 16/64/128/256 declarations, nested depth 24, choices/loops and mixed inference. +All six domain-negative fixtures rejected in both configurations, and ordinary +and module-qualified consumers compiled with complete strict concurrency. + +The final 256-property schema typecheck took 3.765 s with variadic composition +versus 5.304 s with pairwise partial blocks; compiler maximum resident sizes were +122,929,152 and 137,789,440 bytes respectively. An earlier integration run measured +1.097 s versus 5.513 s. All raw fixture hashes and measurements are retained; neither +run was quiet (final load averages approximately 600/587/533). Some small branching +fixtures favored partial composition. These observations justify retaining the +working variadic strategy through the tested scale, not a general speed guarantee. +Compiler RSS does not bound DSL staging, finalization retention or process RSS. +The alternative modules remain experiment outputs and are not shipped code. ## D6 — Empty enum is distinct from malformed schema diff --git a/Documentation/Architecture/DualDSL/Plan.md b/Documentation/Architecture/DualDSL/Plan.md index 0b2eb2a..4788e74 100644 --- a/Documentation/Architecture/DualDSL/Plan.md +++ b/Documentation/Architecture/DualDSL/Plan.md @@ -9,9 +9,8 @@ has no standalone product. Root dependencies, platforms and all 49 profiles rema The maintainer-supplied packet SHA-256 is `a69432b69f59d3d587502c2453fed3d00259845b9335a551b962965be10f9588`. -Its 32-file manifest verified. Only its three DSL source roots and six negative -fixtures are adapted. Neither signature shim is an engine input. Its sixteen -positive cases are ported from XCTest to Swift Testing and real JSONLimits. +Its 32-file manifest verified. Its three DSL source roots and six negative fixtures are adapted. Neither +signature shim is an engine input. Its sixteen positive cases are ported from XCTest to Swift Testing and real JSONLimits. Original and adaptation contributions retain Apache-2.0. ## Gates and reviewable increments @@ -30,8 +29,9 @@ Original and adaptation contributions retain Apache-2.0. 6. **G6 final qualification:** exact-count native/safety/docs and real Linux lanes; public consumer, strict concurrency, source/diff/receipts and remaining limitations. -Each coherent increment is committed locally. No push, PR, merge, tag or publication -is authorized by this integration request. Existing release and sibling worktrees +Each coherent increment is committed on the isolated feature branch. The maintainer +authorized a branch push and existing ARM64/x86_64 Linux CI after native checks. +PR creation, merging, tagging and release publication remain separate. Existing release and sibling worktrees are preserved. A passing shim or typecheck is never a semantic qualification claim. Private input and raw receipts live in ignored `Artifacts/DualDSLP1.2`; source identity, diff --git a/Documentation/Architecture/DualDSL/Progress.json b/Documentation/Architecture/DualDSL/Progress.json index 899b6d9..222b83c 100644 --- a/Documentation/Architecture/DualDSL/Progress.json +++ b/Documentation/Architecture/DualDSL/Progress.json @@ -6,13 +6,26 @@ "branch": "codex/dual-dsl-p1.2", "release_ready": false, "gates": { - "P1.2-G0": "in_progress", - "P1.2-G1": "in_progress", - "P1.2-G2": "in_progress", - "P1.2-G3": "in_progress", - "P1.2-G4": "pending", - "P1.2-G5": "pending", - "P1.2-G6": "pending" + "P1.2-G0": "passed", + "P1.2-G1": "passed", + "P1.2-G2": "passed", + "P1.2-G3": "passed", + "P1.2-G4": "passed", + "P1.2-G5": "in_progress", + "P1.2-G6": "in_progress" }, - "scope": "Trusted authored staging; finite iterative shared-ledger finalization; no staging/RSS/caller-work claim" + "scope": "Trusted authored staging; finite iterative shared-ledger finalization; no staging/RSS/caller-work claim", + "observed": { + "baseline_native_commands": 17, + "dsl_tests_per_configuration": 47, + "native_root_functions": 343, + "baseline_parameter_invocations": 173, + "compiler_commands": 41, + "negative_rejections": 12, + "native_safety": "passed after retained transient PDF failure and unchanged full rerun", + "native_lane": "13 commands passed; downstream mobile tool build blocked by ENOSPC; full lane not passed", + "docs": "1005/1005 comments;9 catalogs passed; route fix privately verified, final lane pending", + "wasi": "real public release consumer passed Node and WasmKit; consumer scope only", + "linux": "authorized branch push/CI pending native completion or explicit changed-condition authorization" + } } diff --git a/Documentation/Architecture/ExtractionManifest.json b/Documentation/Architecture/ExtractionManifest.json index f61232c..853ae69 100644 --- a/Documentation/Architecture/ExtractionManifest.json +++ b/Documentation/Architecture/ExtractionManifest.json @@ -236,6 +236,30 @@ "Examples/DualDSL" ], "evidence": "Scripts/ci.py: actual native, safety, docs and supported platform receipts; no shim qualification claim" + }, + { + "repository": "Maintainer-supplied SwiftJSON-DualDSL-Prototypes-P1 packet", + "commit": null, + "source_archive_sha256": "a69432b69f59d3d587502c2453fed3d00259845b9335a551b962965be10f9588", + "original_path": "Tests/DSLPrototypesTests/DSLPrototypeTests.swift", + "original_sha256": "57ea84d6729740abb326819a316cd72cd756aec2e4c7990a5b9bb2f61000f2b8", + "destination": "Tests/JSONDSLTests/DSLPrototypeTests.swift", + "disposition": "Ported all16 XCTest prototype cases to Swift Testing and actual JSONLimits; full schemas also compile and evaluate actual positive/negative or explicitly operational outcomes. No shim is used.", + "attribution": "Apache-2.0 prototype SPDX retained; original integration cases extend actual-engine qualification.", + "validation": "Scripts/ci.py --lane dsl; native and safety exact discovery", + "evidence": "Actual-engine Debug/Release/ASan receipts and real public consumer" + }, + { + "repository": "Maintainer-supplied SwiftJSON-DualDSL-Prototypes-P1 packet", + "commit": null, + "source_archive_sha256": "a69432b69f59d3d587502c2453fed3d00259845b9335a551b962965be10f9588", + "original_path": "Tests/DSLPrototypesTests/StressTypeCheckTests.swift", + "original_sha256": "56a803836cb115e84c35abe65c15a3800e082e11593096a4143b73f76f3ff98c", + "destination": "Tests/JSONDSLTests/StressTypeCheckTests.swift", + "disposition": "Ported all16 XCTest prototype cases to Swift Testing and actual JSONLimits; full schemas also compile and evaluate actual positive/negative or explicitly operational outcomes. No shim is used.", + "attribution": "Apache-2.0 prototype SPDX retained; original integration cases extend actual-engine qualification.", + "validation": "Scripts/ci.py --lane dsl; native and safety exact discovery", + "evidence": "Actual-engine Debug/Release/ASan receipts and real public consumer" } ], "original_implementation_notes": [ diff --git a/Documentation/CI/README.md b/Documentation/CI/README.md index b533eef..dda7b95 100644 --- a/Documentation/CI/README.md +++ b/Documentation/CI/README.md @@ -63,7 +63,7 @@ distribution, architecture or libc claims. `python3 Scripts/ci.py --lane wasm` requires the matching Swift.org 6.4.0 compiler, SDK and WasmKit plus Node. It records cross-build and runtime outcomes separately. -Node executes the complete 256-function/173-parameter portable root suites, +Node executes the current 329-function/173-parameter portable root suites, independent corpus policies and all 49 cap outcomes. Both hosts execute the frozen public consumer; WasmKit retains its separately recorded 14-function consumer scope. The [WASI contract](../Architecture/WebAssembly.md) defines host/safety scopes. @@ -77,9 +77,9 @@ Apple SDK declaration probes. It builds all five products in iPhoneOS and simulator consumers. A bounded offscreen WebPage region experiment remains outside the production API. The lane establishes native API/file transport and SDK builds, not share sheets or receiving-editor UI. Explicit paginated PDF and simulator/device execution have separate materialized receipts. -Current root discovery is 270 functions on Mac (75 HTML) and 256 on Linux/WASI -(61 HTML). The focused export lane requires 38 functions on Mac. Ten Mac shared -functions, including independent PDF cancellation, run under Thread Sanitizer. All 49 cap checks +Current root discovery is 343 functions on Mac (75 HTML, 47 DSL) and 329 on Linux/WASI +(61 HTML, 47 DSL). The focused export lane requires 38 functions on Mac. Thirteen Mac shared +functions, including independent PDF cancellation and DSL finalization, run under Thread Sanitizer. All 49 cap checks and the 173 baseline parameterized invocations remain required. ## Structured Swift Testing receipts diff --git a/Documentation/DocumentationTooling.md b/Documentation/DocumentationTooling.md index ffe2a07..d7d5c04 100644 --- a/Documentation/DocumentationTooling.md +++ b/Documentation/DocumentationTooling.md @@ -1,8 +1,8 @@ # Building and maintaining the DocC catalogs Swift source comments are the API documentation authority. Native compiler symbol -graphs supply the declarations and links for eight public-product Swift DocC catalogs plus a shared DSL structure reference. Each catalog -combines the product reference with curated Topics and a focused usage guide. +graphs supply the declarations and links for eight public-product Swift DocC catalogs plus a shared DSL structure reference. Each product catalog combines its reference with curated Topics and a focused +usage guide; the supporting DSL catalog documents shared structural declarations. See the [Swift DocC documentation](https://www.swift.org/documentation/docc/). ## Build locally @@ -30,6 +30,9 @@ symbols, missing comments, stale examples or a failed catalog fail the lane. | `.build/handoff/docc/JSONHTML.doccarchive` | Exact formatted HTML API and rendering guide | | `.build/handoff/docc/JSONPatch.doccarchive` | Patch API and choosing/applying patches guide | | `.build/handoff/docc/JSONBridges.doccarchive` | Opt-in native numeric conversion and fidelity guide | +| `.build/handoff/docc/JSONValueDSL.doccarchive` | Trusted value authoring API and guide | +| `.build/handoff/docc/JSONSchemaDSL.doccarchive` | Trusted schema authoring API and guide | +| `.build/handoff/docc/JSONDSLCore.doccarchive` | Shared structural reference; no standalone product | | `.build/handoff/docc/symbols/` | Public compiler symbol graphs grouped by product | | `.build/handoff/docc/coverage.json` | Counts and documentation-coverage failures | | `.build/handoff/docc/receipt.json` | Commands, toolchain, counts, exits and diagnostics | diff --git a/Scripts/build_documentation_site.py b/Scripts/build_documentation_site.py index c55d5a1..1485755 100644 --- a/Scripts/build_documentation_site.py +++ b/Scripts/build_documentation_site.py @@ -188,7 +188,10 @@ def main(): receipt['transforms'].append(entry) if result.returncode: raise ValueError('Native static-hosting transformation failed: ' + product) - for route in [product.lower(), 'documentation/' + GUIDES[product][1]]: + routes = [product.lower()] + if product in PRODUCTS: + routes.append('documentation/' + GUIDES[product][1]) + for route in routes: if not (site / product / 'documentation' / route / 'index.html').is_file(): raise ValueError('Missing product root or guide: ' + route) # DocC transforms its emitted routes but retains the original archive From 345d4b11cd8e4f00fe53063f9f1d1e13030aa3ea Mon Sep 17 00:00:00 2001 From: Thorsten Fuchs <76904008+ThorFuchs@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:00:13 +0200 Subject: [PATCH 3/7] docs: record actual DSL native qualification and recovery Record all production command outcomes, complete sanitizer rerun, corpus and cap counts, strict DocC and actual completion evidence. Keep Linux pending and authored staging limitations explicit. --- .../Architecture/DualDSL/Progress.json | 12 +-- .../Qualification/DualDSL/NativeResults.md | 82 +++++++++++++++++++ 2 files changed, 89 insertions(+), 5 deletions(-) create mode 100644 Documentation/Qualification/DualDSL/NativeResults.md diff --git a/Documentation/Architecture/DualDSL/Progress.json b/Documentation/Architecture/DualDSL/Progress.json index 222b83c..162d737 100644 --- a/Documentation/Architecture/DualDSL/Progress.json +++ b/Documentation/Architecture/DualDSL/Progress.json @@ -11,7 +11,7 @@ "P1.2-G2": "passed", "P1.2-G3": "passed", "P1.2-G4": "passed", - "P1.2-G5": "in_progress", + "P1.2-G5": "passed", "P1.2-G6": "in_progress" }, "scope": "Trusted authored staging; finite iterative shared-ledger finalization; no staging/RSS/caller-work claim", @@ -23,9 +23,11 @@ "compiler_commands": 41, "negative_rejections": 12, "native_safety": "passed after retained transient PDF failure and unchanged full rerun", - "native_lane": "13 commands passed; downstream mobile tool build blocked by ENOSPC; full lane not passed", - "docs": "1005/1005 comments;9 catalogs passed; route fix privately verified, final lane pending", + "native_lane": "All19 production commands passed across retained13-command run plus6-command source-equivalent continuation after ENOSPC; no uninterrupted full-lane exit0 claimed", + "docs": "passed:1005/1005 comments,9 catalogs,1530 routes,7636 links", "wasi": "real public release consumer passed Node and WasmKit; consumer scope only", - "linux": "authorized branch push/CI pending native completion or explicit changed-condition authorization" - } + "linux": "maintainer-authorized feature-branch push and ARM64/x86_64 CI pending execution", + "completion": "passed:3 actual SourceKit-LSP contexts; interactive Xcode UI not claimed" + }, + "native_results": "Documentation/Qualification/DualDSL/NativeResults.md" } diff --git a/Documentation/Qualification/DualDSL/NativeResults.md b/Documentation/Qualification/DualDSL/NativeResults.md new file mode 100644 index 0000000..131f24e --- /dev/null +++ b/Documentation/Qualification/DualDSL/NativeResults.md @@ -0,0 +1,82 @@ +# Dual DSL P1.2 native qualification + +This unreleased integration uses the actual engine, not the packet's signature shims. +Base: `e8c3e4bd9ae40d797f07a527ea98879acee3c057`; implementation: +`917dab492883178b0ea9b57bce3a526b597e6373`; documentation correction: +`8fc83cad69df9f28af133c173391ae677804e304`. Library, manifest and test sources +are identical between the latter two commits. The intervening changes are records, +provenance and documentation tooling. Root dependencies remain empty; existing six +products gain no dependency on the two optional DSL products. + +## Observed native results + +macOS 27.0 arm64; Xcode 27.2 (27B5019j), SDK 27.2; Apple Swift 6.4 +(swiftlang-6.4.0.34.1), Swift language mode 6. Commands select the matching Xcode +and SDK explicitly; no system toolchain setting or baseline is changed. + +- Untouched baseline: all 17 production native commands passed, 296 functions + per configuration and 173 parameter invocations. +- Integration: all 47 DSL Swift Testing functions passed Debug and Release. + Full root Debug, Release and Address Sanitizer: 343 functions in eight exact + bundles, retaining all 173 parameter invocations. Shared-state Thread Sanitizer: + 13 functions. Strict memory safety compilation with warnings as errors passed. +- Production native commands 0–12 passed. ENOSPC then interrupted the downstream + mobile-tool build and receipt writer. The exact remaining six commands passed + in a source-equivalent continuation with serial builds and cleanup of completed + task-owned tool caches. This is 19 individually passed commands across retained + receipts, not a single uninterrupted native-lane exit-zero claim. +- Mobile tool: three behavior tests, eight public fixtures, awaited cancellation + and three separately exited disk persistence phases with eight rows. This is + native SDK/tool execution, not a new physical-device qualification claim. +- Rooted consumer: 20 explicitly selected cases, eight positive/twelve negative + and two operational checks. Independent syntax: 318 observed, 287 evaluated, + 31 policy. Schema: 2337 observed, 2300 evaluated, 37 policy. Authored cases: 82; + budget cases: nine; deterministic malformed replay: 4396. All 49 cap probes + passed. Policy cases are not evaluated successes. +- Six compiler-negative fixtures rejected for intended domain typing in Debug + and Release. The final compiler experiment passed 41 commands and two guide + fences, including 22 measured strategy/fixture combinations. Qualified-name + collision consumers passed. See [the compiler decision](../../Architecture/DualDSL/Decisions.md). +- Separate public DSL consumer passed Debug/Release: one valid, two ordinary + invalid and one missing-resource operational outcome, exact scalar keys and + nested arrays. SourceKit-LSP returned the required value/schema factories, + qualified types and Schema keywords in three real completion contexts. No + interactive Xcode UI session is claimed. +- Documentation lane passed: 1005/1005 authored public declarations with named + parameters, nine strict DocC catalogs, compiled README examples, 1530 static + routes and 7636 verified local links. The helper catalog has no public product; + all eight product guides remain mandatory. +- Matching Swift.org 6.4 WASI SDK: the real public release consumer built and + passed in Node and WasmKit. This is consumer scope, not a new full WASI or + host-sanitizer claim. Linux execution remains a separately recorded gate. + +The first full ASan run recorded an unchanged PDF cancellation test receiving +`JSONPDFFailure.timedOut` rather than cancellation on a heavily loaded host. The +same case passed independently without edits, followed by a complete passing +safety rerun. Failed receipts remain part of the private return evidence. The +initial SDK mismatch, missing-comment diagnostics, site-route assumption and +concurrent SwiftPM manifest-output contamination are retained with their fixes; +no failure is relabeled as a pass or policy exclusion. + +## Public additions and semantic authority + +| Addition | Authority and regression coverage | +| --- | --- | +| `JSONValueDSL.object/array`, Field, Element, Elements | JSON/JSONNumber, exact JSONObject admission/index; V01–V07, duplicate tables, literal caps and public consumer | +| `JSONSchemaDSL.document/boolean`, Schema keyword factories and typed tables | JSONSchemaDocument, existing compiler/validator and explicit registry; V08–V17/V20, full prototype examples, annotation/verdict/manual-raw parity | +| JSONDSLCore typed composition and flat node/member staging | Domain-constrained native Swift composition; six negative fixtures, choices/loops/nesting, 16–256 declaration probes | +| Iterative finalization and package schema continuation | Existing invocation-owned engine meter and admission; V18/V19, inclusive work/retention/node caps, terminal error, depth and cancellation tests | +| Immutable declarations and conditional Sendable | Native compiler, 32 independent task invocations, shared immutable plan and exact shared-state TSan discovery | + +Trusted callbacks, wrapper construction, emission and IR staging remain unmetered. +There is no whole-DSL cumulative report, staging cancellation/retention guarantee, +RSS bound or caller-instruction quota. Finalization uses one finite ledger through +schema document admission. Compiler/evaluator invocations remain separate explicit +engine operations. The next architecture question is whether an additional bounded +dynamic-authoring API merits metering from the first staged append; it is not +silently added to this authored API. + +Runtime throughput is not benchmarked by the compiler experiment. Its loaded-host +compiler elapsed time/RSS observations justify the retained strategy only through +the tested scale. Projection, text-sequence framing, extra numeric coercions, online +resolution and new schema semantics remain outside this wave. From 6f6bd90467aae0354dc5dcfdc7e125a5f6e8d2de Mon Sep 17 00:00:00 2001 From: Thorsten Fuchs <76904008+ThorFuchs@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:13:26 +0200 Subject: [PATCH 4/7] ci: verify the exact Linux container checkout identity Trust only GITHUB_WORKSPACE in the ephemeral container and assert its HEAD matches GITHUB_SHA before qualification. Preserve metadata failures and all native, corpus, cap, privacy and compiler checks. --- .github/workflows/linux.yml | 6 ++++++ Documentation/Architecture/DualDSL/Progress.json | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 5324728..729b003 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -40,6 +40,12 @@ jobs: with: persist-credentials: false fetch-depth: 0 + - name: Verify the checked-out container workspace + run: | + # The image user differs from the checkout owner. Trust this exact + # ephemeral workspace so Git identity and full-history checks run. + git config --global --add safe.directory "$GITHUB_WORKSPACE" + test "$(git rev-parse HEAD)" = "$GITHUB_SHA" - run: python3 -B Scripts/ci.py --lane '${{ matrix.lane }}' - name: Preserve Linux receipts if: always() diff --git a/Documentation/Architecture/DualDSL/Progress.json b/Documentation/Architecture/DualDSL/Progress.json index 162d737..0978217 100644 --- a/Documentation/Architecture/DualDSL/Progress.json +++ b/Documentation/Architecture/DualDSL/Progress.json @@ -26,7 +26,7 @@ "native_lane": "All19 production commands passed across retained13-command run plus6-command source-equivalent continuation after ENOSPC; no uninterrupted full-lane exit0 claimed", "docs": "passed:1005/1005 comments,9 catalogs,1530 routes,7636 links", "wasi": "real public release consumer passed Node and WasmKit; consumer scope only", - "linux": "maintainer-authorized feature-branch push and ARM64/x86_64 CI pending execution", + "linux": "run38679209482:both safety lanes passed; both full lanes passed9 commands then failed Git ownership metadata before DSL compiler imports. Narrow exact-checkout trust/SHA verification added to ephemeral workflow; rerun pending.", "completion": "passed:3 actual SourceKit-LSP contexts; interactive Xcode UI not claimed" }, "native_results": "Documentation/Qualification/DualDSL/NativeResults.md" From ed08ed4b397cf84e05084dc325b4b7232da3358b Mon Sep 17 00:00:00 2001 From: Thorsten Fuchs <76904008+ThorFuchs@users.noreply.github.com> Date: Thu, 15 Oct 2026 06:33:25 +0200 Subject: [PATCH 5/7] docs: close DSL qualification with verified portable evidence Record both Linux architectures full and safety outcomes, byte-identical clean reproduction, actual WASI DSL tests and Apple SDK builds. Preserve failed attempts and explicit staging/platform scopes; keep merging and release publication separate. --- .../Architecture/DualDSL/Progress.json | 21 ++++++-- .../Qualification/DualDSL/LinuxResults.md | 51 +++++++++++++++++++ .../Qualification/DualDSL/NativeResults.md | 8 ++- 3 files changed, 74 insertions(+), 6 deletions(-) create mode 100644 Documentation/Qualification/DualDSL/LinuxResults.md diff --git a/Documentation/Architecture/DualDSL/Progress.json b/Documentation/Architecture/DualDSL/Progress.json index 0978217..11322c4 100644 --- a/Documentation/Architecture/DualDSL/Progress.json +++ b/Documentation/Architecture/DualDSL/Progress.json @@ -12,7 +12,7 @@ "P1.2-G3": "passed", "P1.2-G4": "passed", "P1.2-G5": "passed", - "P1.2-G6": "in_progress" + "P1.2-G6": "passed" }, "scope": "Trusted authored staging; finite iterative shared-ledger finalization; no staging/RSS/caller-work claim", "observed": { @@ -25,9 +25,20 @@ "native_safety": "passed after retained transient PDF failure and unchanged full rerun", "native_lane": "All19 production commands passed across retained13-command run plus6-command source-equivalent continuation after ENOSPC; no uninterrupted full-lane exit0 claimed", "docs": "passed:1005/1005 comments,9 catalogs,1530 routes,7636 links", - "wasi": "real public release consumer passed Node and WasmKit; consumer scope only", - "linux": "run38679209482:both safety lanes passed; both full lanes passed9 commands then failed Git ownership metadata before DSL compiler imports. Narrow exact-checkout trust/SHA verification added to ephemeral workflow; rerun pending.", - "completion": "passed:3 actual SourceKit-LSP contexts; interactive Xcode UI not claimed" + "wasi": "passed:47 new DSL tests Debug/Release in Node; portable root bundles compiled; public release consumer Node/WasmKit. No new execution of other root corpora or host sanitizers claimed", + "linux": "passed:run38680343090 at6f6bd90467aae0354dc5dcfdc7e125a5f6e8d2de; ARM64/x86_64 full16 and safety4 commands each;329 root functions/173 parameters,12 portable TSan; actual receipts and identical archive bytes verified", + "completion": "passed:3 actual SourceKit-LSP contexts; interactive Xcode UI not claimed", + "apple_sdk": "passed:iPhoneOS/iPhoneSimulator27.2 public DSL consumer builds at existing minimum27; SDK-only scope" }, - "native_results": "Documentation/Qualification/DualDSL/NativeResults.md" + "native_results": "Documentation/Qualification/DualDSL/NativeResults.md", + "qualification_status": "passed", + "release_readiness_reason": "Qualified feature candidate; maintainer API/merge and release authorization remain separate, not a failed technical gate", + "qualified_ci_source": "6f6bd90467aae0354dc5dcfdc7e125a5f6e8d2de", + "linux_results": "Documentation/Qualification/DualDSL/LinuxResults.md", + "remaining_limitations": [ + "Trusted authored staging/callbacks excluded from finalization work and retention accounting", + "No whole-DSL report, caller instruction quota or hard process RSS/throughput guarantee", + "Interactive Xcode UI and new physical-device execution not claimed", + "All other WASI corpus/sanitizer execution remains its separately qualified existing scope" + ] } diff --git a/Documentation/Qualification/DualDSL/LinuxResults.md b/Documentation/Qualification/DualDSL/LinuxResults.md new file mode 100644 index 0000000..8385b96 --- /dev/null +++ b/Documentation/Qualification/DualDSL/LinuxResults.md @@ -0,0 +1,51 @@ +# Dual DSL P1.2 Linux qualification + +[Recovery run 38680343090](https://github.com/ThorFuchs/Swift-JSON/actions/runs/38680343090) +passed all four jobs at `6f6bd90467aae0354dc5dcfdc7e125a5f6e8d2de`. +Both ARM64 and x86_64 used Ubuntu 24.04, Swift 6.4.0 and the unchanged official +multi-architecture image pin +`swift@sha256:31d14d727f4451f25e29bac9c42563a098c39ac66415e8bad970f48038e38aca`. +The actual environment and every command/log digest are in the downloaded receipts. + +Each architecture passed 16 full qualification commands and four safety commands. +Debug, Release and ASan each required eight exact bundles, 329 functions and all +173 parameter invocations. Shared-state TSan required 12 portable functions; +strict-memory-safety compilation passed. Six intended compiler negatives rejected +in each of two configurations, with public positive and qualified-name collision +consumers. The separate public DSL consumer passed real valid/invalid/operational +outcomes. All 49 cap probes and unchanged independent corpus policies passed: +318 syntax cases (287 evaluated/31 policy), 2337 schema cases (2300 evaluated/37 +policy), 82 authored, nine budget and 4396 malformed replay cases. Policy cases +are not evaluated successes, and operational errors are not false verdicts. + +Both jobs independently rebuilt identical candidate bytes, verified the manifest, +extracted without Git metadata, built all products, ran six integrity/resource +functions and executed the public consumer with compiled README DSL examples. +Archive SHA-256 is +`3f00c91f205bbafb9c722e6bb5d5c0f4ba9996c359f046a16d12bac91699e547`, +1,352,635 bytes, 931 entries including its 930-file source manifest. This matches +the local immutable source archive byte-for-byte. Every job's source-input map +matches that archive, with unchanged-source assertions and actual Git SHA recorded. + +[First run 38679209482](https://github.com/ThorFuchs/Swift-JSON/actions/runs/38679209482) +is retained as failed. Its two safety jobs passed; its full lanes passed nine +commands then stopped before the DSL compiler probes when Git rejected container +checkout ownership. The recovery trusts only the exact ephemeral GITHUB_WORKSPACE +and asserts HEAD equals GITHUB_SHA before qualification. No wildcard trust, host +configuration or test relaxation was added. Git identity and full privacy/history +checks now execute, rather than being skipped for an unreadable Git checkout. + +The native results remain separately qualified, including the transparent ENOSPC +continuation and the retained PDF timeout followed by an unchanged complete passing +safety rerun. No Apple/device claim is inferred from Linux. Additional iPhoneOS and +iPhoneSimulator 27.2 SDK builds (minimum 27) passed the public DSL consumer. Matching +Swift 6.4 WASI builds compiled portable root bundles, and all 47 new DSL tests passed +Debug and Release in Node; the public release consumer also passed WasmKit. These +additional scopes do not imply a new full WASI corpus/sanitizer or physical-device run. + +Only reporting/qualification records may follow this tested source identity in the +freeze commit. Library, test, manifest, consumer and qualification-harness source +are unchanged since the implementation commit. The workflow change is confined +to exact container checkout identity verification; protected checks and release +publication remain separate. Trusted unmetered authoring and finite finalization +retain their explicit resource boundary. diff --git a/Documentation/Qualification/DualDSL/NativeResults.md b/Documentation/Qualification/DualDSL/NativeResults.md index 131f24e..2c2f379 100644 --- a/Documentation/Qualification/DualDSL/NativeResults.md +++ b/Documentation/Qualification/DualDSL/NativeResults.md @@ -48,7 +48,7 @@ and SDK explicitly; no system toolchain setting or baseline is changed. all eight product guides remain mandatory. - Matching Swift.org 6.4 WASI SDK: the real public release consumer built and passed in Node and WasmKit. This is consumer scope, not a new full WASI or - host-sanitizer claim. Linux execution remains a separately recorded gate. + host-sanitizer claim. Linux execution is recorded in [the separate results](LinuxResults.md). The first full ASan run recorded an unchanged PDF cancellation test receiving `JSONPDFFailure.timedOut` rather than cancellation on a heavily loaded host. The @@ -80,3 +80,9 @@ Runtime throughput is not benchmarked by the compiler experiment. Its loaded-hos compiler elapsed time/RSS observations justify the retained strategy only through the tested scale. Projection, text-sequence framing, extra numeric coercions, online resolution and new schema semantics remain outside this wave. + +The final portable follow-up also executed all 47 new DSL functions in both +configurations in Node, after compiling the portable root bundles. It preserves +the limited WASI scope above for other suites and host sanitizers. Real public DSL +consumer cross-builds passed iPhoneOS/iPhoneSimulator 27.2 SDKs at minimum iOS 27; +these are build observations, separate from the native persistence tool and devices. From a2cf3c494eda7ac919c9544797776d8d427dfb57 Mon Sep 17 00:00:00 2001 From: Thorsten Fuchs <76904008+ThorFuchs@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:28:02 +0200 Subject: [PATCH 6/7] docs: align DSL release and catalogue inventory --- README.md | 14 ++++++++------ RELEASING.md | 3 ++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index a370dee..9288be4 100644 --- a/README.md +++ b/README.md @@ -74,8 +74,8 @@ Choose the products your application needs: SwiftPM dependency graph is empty. Qualification and benchmark tools are separate packages. -The Linux development increment adds portable schema integrity for all four products -without runtime dependencies. Its initial qualification scope is Swift 6.4+, +Linux support includes portable schema integrity without runtime dependencies. +Its qualification scope is Swift 6.4+, 64-bit Ubuntu 24.04/glibc; see the [Linux contract](Documentation/Architecture/Linux.md) for execution gates and limits. Apple platform requirements remain unchanged. @@ -497,11 +497,13 @@ Browse the [public documentation site](https://thorfuchs.github.io/Swift-JSON/): [JSONPatch](https://thorfuchs.github.io/Swift-JSON/JSONPatch/documentation/jsonpatch/). The site tracks `main` and publishes only after all three native CI lanes pass. -The [documentation index](Documentation/README.md) links the behavior contracts. The five DocC catalogs -provide public API references, focused guides, parameter descriptions and failure -contracts, compiled from the native Swift public symbol graphs. +The [documentation index](Documentation/README.md) links the behavior contracts. +Eight product DocC catalogues provide public API references, focused guides, +parameter descriptions and failure contracts, compiled from native Swift public +symbol graphs. A ninth catalogue documents shared DSL composition types; its +helper module has no standalone product. -Build all five catalogs on a supported native host: +Build all nine catalogues on a supported native host: ```sh python3 Scripts/ci.py --lane docs diff --git a/RELEASING.md b/RELEASING.md index 6cb011b..a0a8b7d 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -6,7 +6,8 @@ or releases. Published version tags are protected against updates and deletion. 1. Require passed native, safety and documentation lanes for the exact candidate commit on macOS/SDK 27+ and Swift 6.4+ with language mode 6. -2. Review six public products (including JSONHTML and opt-in JSONBridges), the empty root dependency graph, compiled external +2. Review eight public products (including JSONHTML, opt-in JSONBridges and the + two opt-in DSLs), the empty root dependency graph, compiled external consumers, populated pinned suites, policy exclusions, all 49 finite caps, schema/regex behavior and cancellation boundaries. 3. Review licenses, provenance, public file inventory and documentation links. From 64264218dc0073a5738ab557bfa25b3bb9f6fa7a Mon Sep 17 00:00:00 2001 From: Thorsten Fuchs <76904008+ThorFuchs@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:30:55 +0200 Subject: [PATCH 7/7] docs: clarify supporting DSL catalogue route --- Documentation/DocumentationTooling.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Documentation/DocumentationTooling.md b/Documentation/DocumentationTooling.md index d7d5c04..cc4695f 100644 --- a/Documentation/DocumentationTooling.md +++ b/Documentation/DocumentationTooling.md @@ -67,7 +67,9 @@ The manifest and receipt preserve file-level and archive-level digests. The docs lane uses native `docc process-archive transform-for-static-hosting` to prepare each qualified archive under `/Swift-JSON/`. A shared landing -page links eight public-product references and the supporting DSL reference and guides. The build verifies product/guide routes, +page links all eight product references and guides. The supporting DSL reference is +also deployed at `/Swift-JSON/JSONDSLCore/documentation/jsondslcore/`, without a +product card. The build verifies product/guide and supporting-reference routes, local HTML links and assets, rejects private-path/credential markers and symlinks, and records a file manifest. Only the generated site is packaged for Pages; source graphs, command logs and private maintainer records are not website content.