From 0ee5aa5157435b1104a792c5ff1b4919331a13eb Mon Sep 17 00:00:00 2001 From: Nathan Date: Mon, 26 Oct 2026 19:28:03 -0400 Subject: [PATCH 1/5] Propose Matrix shell profile with executable syntax proof --- docs/design/NIL-0018-matrix-shell-profile.md | 245 +++++++++++++++++++ docs/design/README.md | 1 + matrix/README.md | 12 +- matrix/docs/authority-and-sandboxing.md | 42 ++-- matrix/docs/next-version-findings.md | 28 +++ matrix/samples/shell-profile-preview.matrix | 56 +++++ matrix/samples/shell-profile-preview.stdout | 6 + 7 files changed, 369 insertions(+), 21 deletions(-) create mode 100644 docs/design/NIL-0018-matrix-shell-profile.md create mode 100644 matrix/samples/shell-profile-preview.matrix create mode 100644 matrix/samples/shell-profile-preview.stdout diff --git a/docs/design/NIL-0018-matrix-shell-profile.md b/docs/design/NIL-0018-matrix-shell-profile.md new file mode 100644 index 00000000..9a6020e2 --- /dev/null +++ b/docs/design/NIL-0018-matrix-shell-profile.md @@ -0,0 +1,245 @@ +# NIL-0018: A Matrix profile for interactive shell work + +Status: proposed; the companion example runs as an ordinary hosted Matrix +program. No shell command, interactive evaluator, restricted VM, or Anomalous +execution route is implemented by this record. + +## Purpose and existing direction + +Use Matrix for interactive work and scripts so that learning the shell also +teaches the language used to build Anomalous applications. Keep its named calls, +immutable values, explicit blocks, checked results and typed queries. Reuse the +Matrix lexer/parser, shared type checker, NIL representation and language tools. + +Anomalous already proposes **Canticle** as a shell/session environment in its +ADR 0010 and `docs/architecture/canticle.md`. Its syntax is still proposed. The +recommendation is to make Matrix the language surface of that environment while +preserving its shared human/machine invocation model, explicit authority, +structured results and preview/commit requirements. This framework proposal +does not amend or accept an Anomalous ADR. + +Anomalous ADR 0092 selects an unprivileged native interpreter vessel. ADR 0093 +requires artifact-derived authority bounded by that interpreter's ceiling. +Running the current hosted C++ VM on Linux does not establish either property. +The newer `ANPG` startup descriptor and program arena are scaffolding: the +current native program profile explicitly supplies no NIL execution, edition +mapping, or console transport. + +## What a person would write + +The following is a **target interactive example**, not runnable shell syntax +today. Command names and their schemas are illustrative. The session supplies +the named object and authority bindings; writing their names cannot create them. + +```matrix +value response is list-files with location being workspace, authority being workspace_read +consider response + when Result.Ok holding entries then + value sources is collect begin query + from each entry in entries + where entry.extension equals ".mat" + order by entry.name + take 20 + give entry + end query + evaluate present with sources + when Result.Error holding failure then + evaluate present-error with failure +end consider +``` + +The proposed local `present` adapter projects the typed value as a table. A +machine receives the same value with its schema, without reading terminal cells. +`present-error` renders only the permitted error fields with source, operation +and trace information; failure does not produce an empty success table. These +adapters are proposed session APIs, not existing standard-library functions. +Their projection is local; persistence or disclosure to another principal is +an explicit operation. Automatic checked-result propagation would require a +separate, shared language decision and must not silently call `unwrap`. + +Current queries cannot use the record rows shown here: the shared query profile +admits scalar/text and supported tuple elements. Named record rows are a real +language/runtime prerequisite for this interface, not a new shell-only table +type. The [executable syntax proof](../../matrix/samples/shell-profile-preview.matrix) +uses tuples and explicit `Result` handling under the existing contract. + +The prompt should accept a submission containing statements and a final +expression. Saved programs retain ordinary `.mat`/`.matrix` pages. Exporting a +session creates a normal book/paragraph with explicit inputs, rather than a +different script grammar. The current parser requires those declarations; +submission parsing and final-value return are work to implement. + +## Initial profile + +| Area | First hosted prototype | Follow-up | +| --- | --- | --- | +| Values | Existing scalar/text, supported tuples and arrays; `Option`/`Result` | Named record arrays and checked domain values | +| Computation | Immutable bindings, arithmetic, comparison, explicit formatted text, conditionals, collected queries | User paragraphs and bounded iteration after transitive validation | +| Commands | Typed, versioned mock `help` and system observations | Real observation adapters admitted by Anomalous | +| Imports | A fixed, explicitly admitted module catalog | Versioned user modules after effect/operation verification | +| Session | Explicit inputs and outputs; new code never replays prior effects | Retained bindings with managed ownership and deterministic cleanup | +| Effects | No live external operations in the syntax proof | Observation, then preview/commit, cancellation and recovery | + +The execution profile excludes raw memory, assembly, arbitrary foreign calls, +user intrinsic declarations, general recursion, unbounded loops, unrestricted +parallelism and dynamic evaluation. The full Matrix language retains its systems +features; this is an admitted workload profile with its own limits. + +`value` prevents rebinding but does not make an array deeply immutable. Session +publication must account for aliases: a failed submission must not leave earlier +bindings changed through a shared array. Admit read-only operations first, then +define ownership/copy rules before permitting updates to retained values. + +Do not introduce command search through `PATH`, implicit environment expansion, +word splitting, globbing, command substitution or execution of unknown names. +Formatted text remains text. Foreign programs eventually use an explicit +operation with an executable identity and an array of arguments. + +## Shared execution and authority + +```text +Matrix submission -> Matrix parser -> shared AST/type checker -> typed NIL +structured request -> checked schema/resolver ----------------------^ + profile verifier + | + bounded executor + | + typed host command adapter + | + Anomalous invocation/policy boundary +``` + +Both entry paths must produce equivalent resolved operations and pass the same +limits. A structured request cannot assert that it is already checked or trusted. +Use a small schema for the admitted profile, rather than accepting arbitrary +internal compiler AST objects. Retain source spans or request-node identities +for equivalent diagnostic attribution. + +The host catalog binds each command to an exact operation identity, schema +version, argument slots, result type and effect summary. Generated declarations +allow ordinary Matrix named-call checking and completion. Runtime dispatch must +reject an unregistered command; it must not fall through to native-library +loading. Default-deny checks must cover transitive calls, indirect calls, +initializers, imports and serialized NIL, including paths that do not execute. +The existing worker verifier is a starting point, not a general authority proof. + +Authority references are opaque host-owned bindings, not public records, +integers, NILData objects or bearer tokens in source. Resolving a name or passing +type checking confers no authority. Admission bounds the program, while each +invocation still validates its current grant, principal, target and revocation +state. A compile-time family allowlist cannot replace that check. + +Pure evaluation may construct a request; it must not discover its effects by +performing them. Material operations require a resolved preview and a later +commit bound to exact targets, versions, policy and an idempotency identity. +Stale plans fail explicitly. Cancellation, unknown completion, partial effects +and compensation remain distinct outcomes. These are later implementation gates, +not capabilities of the example. + +## NILData and sessions + +NILData can carry versioned request and result envelopes, examples and history +metadata. It is a data encoding, not an executor, authority token or AST schema. +Encoding executable node names does not authorize their evaluation. Unknown +versions and node kinds must be rejected by a separate decoder. + +Do not use normalized NILData text as a cryptographic plan digest. NILData +preserves numeric spellings, and different spellings may have the same numeric +meaning. The bound-plan schema must define identity and canonical encoding +separately; it must also exclude capability material and respect disclosure +policy. Initial equality tests can compare resolved typed operations directly. + +History retention is an explicit session policy. Source, arguments, completion +queries, result values and traces may all contain sensitive data. A session must +not persist everything merely because it was typed at the prompt. Projection +must escape terminal controls and preserve structured values; exporting or +sharing a result is a separate operation. + +## Runtime gaps to close + +- The Matrix parser has no submission entry point or incremental completeness + result. Add it using existing expression/statement parsing and original source + locations. Do not create a second shell parser by rewriting source strings. +- `VM::loadProgram` resets globals, heap and execution state. Recompiling and + replaying the complete session would repeat effects. Define a retained binding + contract and transactional publication of new bindings instead. +- The VM has host callbacks, injectable streams, exit trapping and instruction + stepping, but no general sandbox/profile enforcement. External dispatch can + reach native-library loading. An allowlisted host adapter needs a closed path. +- Instruction stepping alone does not bound allocations, parsing/type checking, + output, native calls or the work performed inside one intrinsic. Give each + phase explicit budgets, cancellation behavior and host resource containment. +- Existing `ny.context.v2` inspection reports authored intent. It is not the + authority manifest required by Anomalous ADR 0093. Reserved NIL format fields + must not be repurposed without their own version/compatibility decision. +- Anomalous's copied runtime and refresh script still use old Ny SDK layout + assumptions. Reconcile that consumer with `exec-nil-framework`, `nilcompiler`, + `nilinterpreter`, `nilstd` and `nillib` before adopting the new fixtures. + +## Alternatives and task corpus + +The existing Canticle draft is the contrasting candidate: its proposed +`invoke ... with [...]`, `|>` and explicit `preview`/`commit` forms offer useful +effect visibility, but require another grammar and toolchain. A Matrix profile +reuses language knowledge and tools; its command/effect boundary must remain +visible through typed catalog declarations and inspected operations. + +| Task | Matrix direction | Canticle draft | Acceptance evidence needed | +| --- | --- | --- | --- | +| Inspect system state | Named observation call and checked result | `invoke` with authority bindings | Equal resolved operation and error on both inputs | +| Filter unhealthy vessels | Existing collected query; named record rows pending | Typed pipeline | Equal ordered rows; no text scraping | +| Preview a removal | Explicit typed preview/commit operations | Dedicated preview/commit forms | Exact plan identity; stale/denied commit does nothing | +| Pass hostile text to a program | Explicit argument array | Explicit foreign-program rite | One argument preserved; no parsing or expansion | +| Deadline on concurrent observations | Deferred structured operation | Deferred structured concurrency | Bounded fan-out, cancellation and partial-error attribution | +| Handle one failed item | Explicit `Result` matching | Result propagation and later matching | Successful rows retained only under an explicit partial-result contract | +| Use a secret once | Deferred opaque governed value | Proposed `secret` | No ordinary formatting, history or serialization exposure | +| Human/machine equivalent request | Same resolver and profile verification | Same bound program | Differential source/request corpus and trace attribution | + +This is an architectural comparison, not measured usability or security +evidence. The companion program demonstrates existing Matrix syntax and hosted +execution only. Actual submission, hostile-input, resource and authority tests +are required before selecting a deployable profile. + +## Implementation sequence + +1. Reconcile the copied SDK and document the Anomalous consumer baseline. +2. Add Matrix submission parsing and a pure, default-deny profile verifier. + Exercise complete/incomplete/error input and text/request equivalence without + a live executor or host effects. +3. Add a bounded hosted evaluator with typed mock observations, final-value + rendering and explicit session binding ownership. Test no effect replay, + forged handles, unknown operations, budget exhaustion and cancellation. +4. Generate command signatures for completion/help from the same versioned + catalog used by checking and dispatch. Add native named record-row support + through the shared language implementation. +5. Qualify Anomalous interpreter execution and its observation adapters under + its existing ADRs; run the shared language corpus and profile rejection cases. +6. Add mutations only with verified preview, commit, freshness, revocation, + idempotency and attributable failure behavior. + +Source references reviewed: `matrix_parser.*`, `vm.*`, +`concurrency_contract.cpp`, the query and array contracts, and Anomalous ADRs +0010/0092/0093/0094, Canticle architecture, `program_startup.rs`, +`native_program_profile.rs` and `refresh-ny-runtime.sh` (2026-10-26). + +## Reproducing the syntax proof + +From the framework repository root, with a qualified Linux SDK available: + +```sh +python3 tests/routes/ny_route_matrix.py \ + --source matrix/samples/shell-profile-preview.matrix \ + --compiler /path/to/sdk/nilcompiler \ + --interpreter /path/to/sdk/nilinterpreter \ + --compiler-arg=--sdk-path --compiler-arg=/path/to/sdk/nilstd \ + --routes text-interpreter,binary-interpreter,llvm-aot \ + --expected-stdout matrix/samples/shell-profile-preview.stdout \ + --expected-exit 0 --work-dir build/matrix-shell-preview \ + --report-json build/matrix-shell-preview.json --strict +``` + +All three routes passed with identical expected output, exit zero and empty +stderr on 2026-10-26 using SDK source revision `9e33415`. The proof calls only +fixed in-memory fixture paragraphs. It includes a finite display loop and local +`say` statements as a normal program; this does not establish admission under +the proposed restricted shell profile. diff --git a/docs/design/README.md b/docs/design/README.md index 75381e67..20ecedf0 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -41,6 +41,7 @@ not assigned architecture identifiers. | NIL-0015 | [Structural tuples](NIL-0015-structural-tuples.md) | Implemented nonempty typed values and local destructuring | | NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | | NIL-0017 | [Versioned NILData and one shared value model](NIL-0017-nildata.md) | Implemented initial bounded document profile | +| NIL-0018 | [A Matrix profile for interactive shell work](NIL-0018-matrix-shell-profile.md) | Proposed; ordinary hosted syntax example only | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/matrix/README.md b/matrix/README.md index 6788bf0e..71bea2bc 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -29,7 +29,7 @@ which. | Front-end integration plan | [`docs/front-end-plan.md`](docs/front-end-plan.md) | | Next-version findings and validation notes | [`docs/next-version-findings.md`](docs/next-version-findings.md) — confirmed limitations, design friction, fixes, and acceptance checks | | Sample programs | [`samples/`](samples/) | -| Shell subset — **extension, not core** | Grammar support ships; the design proposal and its sample corpus are not published yet | +| Shell profile | [NIL-0018 proposal](../docs/design/NIL-0018-matrix-shell-profile.md) and ordinary hosted syntax example; submission parsing and restricted execution are not implemented | | Lexer, parser, lowering | **Implemented through stage 6** — see [`docs/front-end-plan.md`](docs/front-end-plan.md) for the stage-by-stage status and exit evidence | Source files use the `.matrix` extension, or `.mat` as the short form. Both @@ -120,11 +120,11 @@ the capability, not before. ## Why this language, beyond syntax Matrix is intended to become a language for both AI agents and humans, including -in embedded and OS-level settings. That design proposes a NIL runtime integrated -inside a kernel, with a kernel-enforced authority set and a chain of trust -starting at the boot loader. These kernel and sandboxing capabilities are a -design goal, -not a property of the current desktop toolchain. Today Matrix programs use +in embedded and OS-level settings, with kernel-enforced authority and a chain of +trust starting at the boot loader. Anomalous selects an unprivileged native +interpreter vessel rather than a kernel-resident executor. These authority and +sandboxing capabilities are a design goal, not a property of the current desktop +toolchain. Today Matrix programs use both the interpreter and native compilation routes, subject to the shared runtime's supported-feature contracts. diff --git a/matrix/docs/authority-and-sandboxing.md b/matrix/docs/authority-and-sandboxing.md index 2e05c2f8..2651f0be 100644 --- a/matrix/docs/authority-and-sandboxing.md +++ b/matrix/docs/authority-and-sandboxing.md @@ -1,17 +1,24 @@ # Authority, sandboxing, and the kernel boundary -Matrix's reason to exist beyond syntax: it is intended to become the default -both-AI-and-human language for embedded and OS-level settings, with the NIL runtime -integrated *inside* the kernel rather than running on top of it. The purpose is -to sandbox agents, humans, and the kernel itself — and to sandbox the language -at compile time against a kernel-enforced authority set, with the chain of -trust starting at the boot loader. +Matrix is intended for people and agents working in embedded and OS-level +settings. The authority design bounds programs against kernel-enforced grants, +with a chain of trust starting at the boot loader. The compiler can diagnose +inadmissible effects, but enforcement must not depend on trusting the compiler +or the submitted source. This document records the design rule that follows from that, and what it costs. Nothing here is implemented. The base surface in `samples/` does not depend on it, and the grammar reserves the syntax so adding it later is not a breaking change. +Early sketches placed the executor inside the kernel; that is not the selected +Anomalous route. Kernel enforcement does not require a kernel-resident executor. Anomalous ADR +0092 instead selects an unprivileged native interpreter vessel, with the +edition's authority bounded by admission and supervised service invocations. +The [Matrix shell profile proposal](../../docs/design/NIL-0018-matrix-shell-profile.md) +follows that direction. The hosted VM and executable-context inspection do not +yet implement this general authority boundary. + ## The rule: full power, zero ambient authority Matrix keeps every capability a systems language needs — raw pointers, pointer @@ -34,10 +41,11 @@ and something other than you decides whether you may." ## Why the artifact, not the source, is the thing checked -A kernel sees NIL. It does not see Matrix, and it has no reason to trust -whatever produced the NIL — not `matrixc`, not `nilcompiler`, not a hand editor. -Source-level checking is a developer convenience. Artifact-level verification -is the security boundary. +An artifact verifier sees NIL rather than Matrix and must not trust whatever +produced it — not `matrixc`, not `nilcompiler`, not a hand editor. Source-level +checking is a developer convenience. Artifact verification is an admission +boundary. Where that verifier runs is part of the host architecture; this does +not require the kernel itself to parse NIL. This is not a new mechanism to invent. **Ny already ships it, in narrow form.** `parallel_map` worker call graphs are verified against an explicit allowlist of @@ -95,9 +103,12 @@ anything in reserved sections. Section 4 is currently `reserved u32 0` with nonzero records rejected — which is the correct fail-closed behaviour and exactly why it cannot simply be repurposed. -The kernel's runtime check then reduces to: `declared ⊆ granted`, evaluated -once, before the first instruction. Everything expensive happens at compile and -load time. +Admission must verify that the artifact's derived requirements fit its declared +ceiling and the granted execution profile before the first instruction. That +family-level check does not authorize every later operation. Each service call +must still validate its principal, live grant, target, scope and revocation +state; commits also validate the exact preview and its freshness. Compile/load +checks and per-invocation authorization have different responsibilities. ## What this is not @@ -130,8 +141,9 @@ one, and the review round trip that rejects it, are never spent. - `requires` is reserved in the grammar now, so adding it is additive. - Inline assembly **stays** in the surface (`samples/13`, `samples/15`). The VM-first focus already means interpreted routes reject `INLINE_ASM`, so - nothing in the VM path executes machine code today; that is a route fact, not - the security design. + that opcode is unavailable on those routes. Foreign calls and native-library + dispatch still exist in the hosted VM; rejecting inline assembly is not a + sandbox or a guarantee that a program cannot reach native code. - `note intrinsic` stays writable, but it is the authority surface in miniature: naming a provider is requesting a capability. Whether an ordinary area may declare intrinsics at all is the first real policy question to diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 07a0c86a..ca5948ef 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2081,3 +2081,31 @@ VSIX packaging pass. The packaging check blocks credential construction and network access; it does not claim validation of credentialed Azure publishing. Remove the temporary override once the upstream dependency range admits a patched version. See the [upstream advisory](https://github.com/AzureAD/microsoft-authentication-library-for-js/security/advisories/GHSA-xcx6-jx8p-x3h5). + +### F70 — A shell profile needs session semantics and named structured rows + +**Observation:** Matrix already supplies named calls, checked results and eager +queries, but its parser accepts complete books/paragraphs rather than prompt +submissions. The README previously implied that shell grammar support shipped; +that status has been corrected. The VM's program load resets state, so replaying +prior submissions to recreate bindings would also replay their effects. + +The shared query/native array profile accepts supported scalar, text and tuple +elements, not direct record rows. Tuple field indexes work but obscure the intent +of a human-facing query. Named record arrays should extend the shared language +and runtime rather than become a second collection system inside the shell. +`value` also prevents rebinding, not mutation through array aliases; session +state needs explicit ownership and publication rules. + +**Design checkpoint:** [NIL-0018](../../docs/design/NIL-0018-matrix-shell-profile.md) +proposes Matrix as the language surface for Anomalous's existing Canticle session +model. A fixed-data example passes text NIL, binary NIL and LLVM AOT routes. It +is an ordinary hosted Matrix program; submission parsing, profile verification, +resource enforcement, real service adapters and native Anomalous execution are +not implemented by this checkpoint. + +Anomalous already has newer program-descriptor scaffolding than its initial +runtime handoff describes, but no live NIL execution in that profile. Its runtime +refresh script still assumes the old Ny checkout/tool/library names; reconcile +the copied SDK before adopting newer examples. Framework executable-context +inspection also remains authored intent, not a derived authority grant. diff --git a/matrix/samples/shell-profile-preview.matrix b/matrix/samples/shell-profile-preview.matrix new file mode 100644 index 00000000..31cb4053 --- /dev/null +++ b/matrix/samples/shell-profile-preview.matrix @@ -0,0 +1,56 @@ +!!! Host-only syntax proof. Observations are fixed in-memory fixture data. +!!! This is an ordinary Matrix page, not a shell, OS adapter, or permission model. +!!! Tuple rows keep the example within both VM and native query support; +!!! direct arrays of records are not in the current native array profile. +book anomalous.shell.syntax-proof + +read everything from nil.std.core +read everything from nil.std.collections + +show-help returns nothing begin paragraph + say "Matrix syntax proof: fixed observations only" +end paragraph + +fixture-status receives vessel-name as text returns Result of text, text begin paragraph + when vessel-name equals "renderer" then + give Result.Ok holding "degraded" + end when + give Result.Error holding ("No fixture vessel named " plus vessel-name) +end paragraph + +main returns number begin paragraph + evaluate show-help with nothing + + !!! Each row is (name, healthy, observation count). + !!! 'value' prevents rebinding; it does not promise deep array immutability. + value vessels is [("desktop", true, 0), ("renderer", false, 3), ("indexer", false, 1)] + value unhealthy is collect begin query + from each vessel in vessels + where vessel.1 equals false + order by vessel.2 descending + take 10 + give (vessel.0, vessel.2) + end query + + say "Unhealthy fixture vessels:" + repeat for each vessel in unhealthy + say formatted "{vessel.0}: {vessel.1}" + end repeat + + value observed is fixture-status with vessel-name being "renderer" + consider observed + when Result.Ok holding status then + say "renderer status: " plus status + when Result.Error holding message then + say message + end consider + + value missing is fixture-status with vessel-name being "missing" + consider missing + when Result.Ok holding status then + say status + when Result.Error holding message then + say message + end consider + give 0 +end paragraph diff --git a/matrix/samples/shell-profile-preview.stdout b/matrix/samples/shell-profile-preview.stdout new file mode 100644 index 00000000..65f2ab95 --- /dev/null +++ b/matrix/samples/shell-profile-preview.stdout @@ -0,0 +1,6 @@ +Matrix syntax proof: fixed observations only +Unhealthy fixture vessels: +renderer: 3 +indexer: 1 +renderer status: degraded +No fixture vessel named missing From d37140c274bf41854aa8113f27207ade3e8583db Mon Sep 17 00:00:00 2001 From: Nathan Date: Mon, 26 Oct 2026 20:17:55 -0400 Subject: [PATCH 2/5] Qualify external Anomalous decision references --- docs/design/NIL-0018-matrix-shell-profile.md | 19 ++++++++++--------- matrix/docs/authority-and-sandboxing.md | 7 ++++--- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/design/NIL-0018-matrix-shell-profile.md b/docs/design/NIL-0018-matrix-shell-profile.md index 9a6020e2..f982bcab 100644 --- a/docs/design/NIL-0018-matrix-shell-profile.md +++ b/docs/design/NIL-0018-matrix-shell-profile.md @@ -12,14 +12,15 @@ immutable values, explicit blocks, checked results and typed queries. Reuse the Matrix lexer/parser, shared type checker, NIL representation and language tools. Anomalous already proposes **Canticle** as a shell/session environment in its -ADR 0010 and `docs/architecture/canticle.md`. Its syntax is still proposed. The -recommendation is to make Matrix the language surface of that environment while +decision record 0010 and `docs/architecture/canticle.md`. Its syntax is still +proposed. The recommendation is to make Matrix the language surface of that environment while preserving its shared human/machine invocation model, explicit authority, structured results and preview/commit requirements. This framework proposal -does not amend or accept an Anomalous ADR. +does not amend or accept an Anomalous decision record. -Anomalous ADR 0092 selects an unprivileged native interpreter vessel. ADR 0093 -requires artifact-derived authority bounded by that interpreter's ceiling. +Anomalous decision record 0092 selects an unprivileged native interpreter vessel. +Its decision record 0093 requires artifact-derived authority bounded by that +interpreter's ceiling. Running the current hosted C++ VM on Linux does not establish either property. The newer `ANPG` startup descriptor and program arena are scaffolding: the current native program profile explicitly supplies no NIL execution, edition @@ -170,8 +171,8 @@ sharing a result is a separate operation. output, native calls or the work performed inside one intrinsic. Give each phase explicit budgets, cancellation behavior and host resource containment. - Existing `ny.context.v2` inspection reports authored intent. It is not the - authority manifest required by Anomalous ADR 0093. Reserved NIL format fields - must not be repurposed without their own version/compatibility decision. + authority manifest required by Anomalous decision record 0093. Reserved NIL + format fields must not be repurposed without their own version/compatibility decision. - Anomalous's copied runtime and refresh script still use old Ny SDK layout assumptions. Reconcile that consumer with `exec-nil-framework`, `nilcompiler`, `nilinterpreter`, `nilstd` and `nillib` before adopting the new fixtures. @@ -218,8 +219,8 @@ are required before selecting a deployable profile. idempotency and attributable failure behavior. Source references reviewed: `matrix_parser.*`, `vm.*`, -`concurrency_contract.cpp`, the query and array contracts, and Anomalous ADRs -0010/0092/0093/0094, Canticle architecture, `program_startup.rs`, +`concurrency_contract.cpp`, the query and array contracts, Anomalous decision +records 0010/0092/0093/0094, Canticle architecture, `program_startup.rs`, `native_program_profile.rs` and `refresh-ny-runtime.sh` (2026-10-26). ## Reproducing the syntax proof diff --git a/matrix/docs/authority-and-sandboxing.md b/matrix/docs/authority-and-sandboxing.md index 2651f0be..ba8798ad 100644 --- a/matrix/docs/authority-and-sandboxing.md +++ b/matrix/docs/authority-and-sandboxing.md @@ -12,9 +12,10 @@ depend on it, and the grammar reserves the syntax so adding it later is not a breaking change. Early sketches placed the executor inside the kernel; that is not the selected -Anomalous route. Kernel enforcement does not require a kernel-resident executor. Anomalous ADR -0092 instead selects an unprivileged native interpreter vessel, with the -edition's authority bounded by admission and supervised service invocations. +Anomalous route. Kernel enforcement does not require a kernel-resident executor. +Anomalous decision record 0092 instead selects an unprivileged native interpreter +vessel, with the edition's authority bounded by admission and supervised service +invocations. The [Matrix shell profile proposal](../../docs/design/NIL-0018-matrix-shell-profile.md) follows that direction. The hosted VM and executable-context inspection do not yet implement this general authority boundary. From c1678565552612124bb597729deaa14979806bb8 Mon Sep 17 00:00:00 2001 From: Nathan Date: Mon, 26 Oct 2026 20:35:58 -0400 Subject: [PATCH 3/5] Add check-only Matrix shell submission profile --- CMakeLists.txt | 22 + docs/design/NIL-0018-matrix-shell-profile.md | 60 ++- docs/tools/index.md | 8 +- docs/tools/matrix-submissions.md | 149 ++++++ matrix/README.md | 2 +- matrix/docs/next-version-findings.md | 41 +- nilcompiler/CMakeLists.txt | 3 + nilcompiler/src/formatted_text.hpp | 29 +- nilcompiler/src/main.cpp | 17 + nilcompiler/src/matrix_lexer.cpp | 33 +- nilcompiler/src/matrix_lexer.hpp | 13 +- nilcompiler/src/matrix_parser.cpp | 249 ++++++++- nilcompiler/src/matrix_parser.hpp | 36 +- nilcompiler/src/matrix_submission.cpp | 266 ++++++++++ nilcompiler/src/matrix_submission.hpp | 41 ++ nilcompiler/src/submission_profile.cpp | 516 +++++++++++++++++++ nilcompiler/src/submission_profile.hpp | 26 + nilcompiler/src/submission_request.cpp | 298 +++++++++++ nilcompiler/src/submission_request.hpp | 34 ++ nilcompiler/src/type_checker.cpp | 14 + tests/matrix_submission_contract.py | 194 +++++++ tests/matrix_submission_parser_tests.cpp | 209 ++++++++ tests/submission_profile_tests.cpp | 210 ++++++++ tests/submission_request_tests.cpp | 340 ++++++++++++ 24 files changed, 2753 insertions(+), 57 deletions(-) create mode 100644 docs/tools/matrix-submissions.md create mode 100644 nilcompiler/src/matrix_submission.cpp create mode 100644 nilcompiler/src/matrix_submission.hpp create mode 100644 nilcompiler/src/submission_profile.cpp create mode 100644 nilcompiler/src/submission_profile.hpp create mode 100644 nilcompiler/src/submission_request.cpp create mode 100644 nilcompiler/src/submission_request.hpp create mode 100644 tests/matrix_submission_contract.py create mode 100644 tests/matrix_submission_parser_tests.cpp create mode 100644 tests/submission_profile_tests.cpp create mode 100644 tests/submission_request_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f391d39..51657651 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -133,6 +133,24 @@ if(BUILD_TESTING) add_test(NAME parser.inline-assembly COMMAND $) + add_executable(nil_matrix_submission_parser_tests tests/matrix_submission_parser_tests.cpp) + target_link_libraries(nil_matrix_submission_parser_tests PRIVATE nilcompiler_core) + target_compile_features(nil_matrix_submission_parser_tests PRIVATE cxx_std_17) + add_test(NAME matrix.submission-parser COMMAND $) + set_tests_properties(matrix.submission-parser PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 30) + + add_executable(nil_submission_profile_tests tests/submission_profile_tests.cpp) + target_link_libraries(nil_submission_profile_tests PRIVATE nilcompiler_core) + target_compile_features(nil_submission_profile_tests PRIVATE cxx_std_17) + add_test(NAME nil.submission-profile COMMAND $) + set_tests_properties(nil.submission-profile PROPERTIES LABELS "shell;contracts;rc" TIMEOUT 30) + + add_executable(nil_submission_request_tests tests/submission_request_tests.cpp) + target_link_libraries(nil_submission_request_tests PRIVATE nilcompiler_core) + target_compile_features(nil_submission_request_tests PRIVATE cxx_std_17) + add_test(NAME matrix.submission-request COMMAND $) + set_tests_properties(matrix.submission-request PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 30) + add_executable(nil_pattern_engine_tests tests/pattern_engine_tests.cpp) target_link_libraries(nil_pattern_engine_tests PRIVATE nilruntime) target_include_directories(nil_pattern_engine_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") @@ -612,6 +630,10 @@ if(BUILD_TESTING) COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/compiler_inputs.py" --compiler $) set_tests_properties(nilcompiler.input-contract PROPERTIES LABELS "tools;rc" TIMEOUT 60) + add_test(NAME matrix.submission-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix_submission_contract.py" + --compiler $) + set_tests_properties(matrix.submission-contract PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 90) add_test( NAME ny.scalar-contract COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/scalar_contract.py" diff --git a/docs/design/NIL-0018-matrix-shell-profile.md b/docs/design/NIL-0018-matrix-shell-profile.md index f982bcab..43be441e 100644 --- a/docs/design/NIL-0018-matrix-shell-profile.md +++ b/docs/design/NIL-0018-matrix-shell-profile.md @@ -1,8 +1,9 @@ # NIL-0018: A Matrix profile for interactive shell work -Status: proposed; the companion example runs as an ordinary hosted Matrix -program. No shell command, interactive evaluator, restricted VM, or Anomalous -execution route is implemented by this record. +Status: admission prototype implemented. The compiler checks Matrix submissions +and versioned NILData requests through a shared pure profile. An interactive +evaluator, retained session, host commands and Anomalous execution remain proposed. +The companion syntax example runs as an ordinary hosted Matrix program. ## Purpose and existing direction @@ -67,10 +68,36 @@ uses tuples and explicit `Result` handling under the existing contract. The prompt should accept a submission containing statements and a final expression. Saved programs retain ordinary `.mat`/`.matrix` pages. Exporting a session creates a normal book/paragraph with explicit inputs, rather than a -different script grammar. The current parser requires those declarations; -submission parsing and final-value return are work to implement. - -## Initial profile +different script grammar. The compiler now has a separate submission entry point +using the existing statement/expression parser. It checks local statements and +an optional final expression without requiring a book or paragraph declaration. + +## Implemented admission slice + +`nilcompiler --check-submission ` and +`nilcompiler --check-submission-request ` inspect a submission without +executing it. Both pass an AST allowlist, the ordinary shared type checker and +a separate generated-NIL verifier. The latter admits one synthetic function, +validates stack/local shapes and fresh tuple initialization, and rejects calls, +unknown operations and backward branches. Neither command imports a library or +enters the VM/native execution paths. See the [command and request contract](../tools/matrix-submissions.md). + +Profile `matrix.pure.v1` admits immutable local bindings, concrete scalar/text, +supported tuple/array expressions, numeric casts, formatting and conditionals. +All calls, imports, mutation, loops, queries, annotations, pointers and assembly +are excluded, including in dead branches. `Option`/`Result`, command catalogs, +retained bindings and runtime quotas require later work. Parsing distinguishes +complete, incomplete and invalid input; a complete parse can still fail type or +profile checks. Limits bound input, syntax depth, AST size and generated NIL; +they do not establish execution-time or heap bounds. + +Structured requests use schema `nil.matrix.submission-request.v1`, with exact +fields, a closed expression vocabulary and no authority-bearing fields. They +construct shared AST nodes directly. They cannot supply source, arbitrary AST +objects or serialized NIL to bypass admission. Differential tests compare typed +NIL from source and request inputs. + +## Planned hosted profile | Area | First hosted prototype | Follow-up | | --- | --- | --- | @@ -158,9 +185,9 @@ sharing a result is a separate operation. ## Runtime gaps to close -- The Matrix parser has no submission entry point or incremental completeness - result. Add it using existing expression/statement parsing and original source - locations. Do not create a second shell parser by rewriting source strings. +- Submission parsing and check-only admission are implemented. A prompt still + needs line collection, result rendering and an evaluator; parsing is not + incremental across calls and each check is independent. - `VM::loadProgram` resets globals, heap and execution state. Recompiling and replaying the complete session would repeat effects. Define a retained binding contract and transactional publication of new bindings instead. @@ -198,15 +225,16 @@ visible through typed catalog declarations and inspected operations. This is an architectural comparison, not measured usability or security evidence. The companion program demonstrates existing Matrix syntax and hosted -execution only. Actual submission, hostile-input, resource and authority tests -are required before selecting a deployable profile. +execution only. The implemented tests cover submission admission and hostile +inputs; execution resource limits and authority behavior remain qualification +requirements before selecting a deployable profile. ## Implementation sequence 1. Reconcile the copied SDK and document the Anomalous consumer baseline. -2. Add Matrix submission parsing and a pure, default-deny profile verifier. - Exercise complete/incomplete/error input and text/request equivalence without - a live executor or host effects. +2. **Implemented:** Matrix submission parsing and a pure, default-deny profile + verifier. Exercise complete/incomplete/error input and text/request equivalence + without a live executor or host effects. 3. Add a bounded hosted evaluator with typed mock observations, final-value rendering and explicit session binding ownership. Test no effect replay, forged handles, unknown operations, budget exhaustion and cancellation. @@ -243,4 +271,4 @@ All three routes passed with identical expected output, exit zero and empty stderr on 2026-10-26 using SDK source revision `9e33415`. The proof calls only fixed in-memory fixture paragraphs. It includes a finite display loop and local `say` statements as a normal program; this does not establish admission under -the proposed restricted shell profile. +the implemented pure submission profile. diff --git a/docs/tools/index.md b/docs/tools/index.md index 05e9c652..87501e3f 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -63,9 +63,15 @@ project process execution is currently qualified on Linux. ## `nilcompiler` -`nilcompiler` parses and type-checks one or more `.ny` inputs. It can generate +`nilcompiler` parses and type-checks Ny and Matrix inputs. It can generate NIL or use the optional LLVM backend. +For Matrix prompt-style input, `--check-submission ` checks local +statements and a final expression against the initial pure shell profile. +`--check-submission-request ` checks the equivalent structured NILData +request. Both return JSON without execution or retained session state. See +[Matrix submission inspection](matrix-submissions.md). + ```text nilcompiler [options] --output [more-inputs.ny ...] nilcompiler [more-inputs.ny ...] diff --git a/docs/tools/matrix-submissions.md b/docs/tools/matrix-submissions.md new file mode 100644 index 00000000..fa637603 --- /dev/null +++ b/docs/tools/matrix-submissions.md @@ -0,0 +1,149 @@ +# Matrix submission inspection + +The compiler provides a check-only entry point for the first Matrix shell +profile. It accepts local statements followed by an optional final expression, +without a book or paragraph wrapper. This is the admission foundation for the +[Anomalous shell proposal](../design/NIL-0018-matrix-shell-profile.md). + +```sh +printf 'value amount is 40\namount plus 2\n' | nilcompiler --check-submission - +nilcompiler --check-submission session.mat +nilcompiler --check-submission-request request.nildata +``` + +Each command reads one bounded regular file or standard input through EOF and +writes one JSON report to standard output. It performs parsing, profile checks, +ordinary type checking and NIL generation. It does not execute the submission, +retain bindings, import libraries or write a compiled artifact. These commands +must be used alone; compilation/output switches cannot change their behavior. + +## Results and completeness + +The report schema is `nil.matrix.submission-check.v1`; the admission profile is +`matrix.pure.v1`. Reports include `input_kind`, `status`, `executed: false`, +`result_type`, `nil`, `instruction_count` and `diagnostics`. Only a complete, +admitted submission has a result type and generated NIL. The type is `void` +when there is no final expression. `nil` contains inspection text, not a runtime +authorization or a serialized session. There is no evaluated result field. + +| Status | Exit code | Meaning | +| --- | --- | --- | +| `complete` | 0 | Parsing, type checking and both profile gates passed. | +| `incomplete` | 2 | Matrix syntax needs more input, such as an operand or closing block. | +| `invalid` | 1 | Input, parsing, schema, type or profile checks failed. | + +Malformed command options produce a normal command-line error rather than a +submission report. NILData requests must be complete documents; malformed or +incomplete requests are invalid. A caller collecting interactive lines can +resubmit the accumulated Matrix text after an incomplete result. Checks do not +share parser or execution state. + +Diagnostics carry stage, code, message, location, line, column and length. Matrix +parser diagnostics retain original source positions; later stages can provide +line-only positions. Structured expression errors identify request paths such +as `$.value` or `$.bindings[0].value`. Zero positions mean unavailable. + +## Admitted computation + +The initial profile admits immutable `value` bindings, supported scalar/text +expressions, tuple construction/destructuring, concrete arrays and indexing, +numeric casts, formatted text and conditionals. A single bare expression may +appear at the end. Use a value position or parentheses for a value-producing +conditional when its syntax would otherwise select a statement. + +Calls (including library functions), imports, named declarations, annotations, +mutation, loops, collected queries, pointer/reference operations and assembly +are rejected. Both branches are checked, even if one is unreachable. The +generated NIL gate independently checks the entire function, type metadata, +stack/local initialization, fresh tuple construction and forward control flow. +It rejects any unknown or forbidden opcode. + +This is a narrower profile than ordinary Matrix. Its exclusions do not change +the language accepted in normal books. The full-program +`shell-profile-preview.matrix` sample uses calls, queries and output, so it is +not an admitted pure submission. + +Admission does not prove that evaluation will succeed: division by zero and +out-of-range indexing can pass checking. Before execution is added, a hosted +evaluator needs allocation/work budgets, cancellation, result projection and +explicit ownership rules for retained bindings. Live Anomalous commands also +need their separate invocation and authority checks. + +## Structured request schema + +A NILData request constructs the same shared AST directly. It cannot embed +Matrix source, serialized NIL, arbitrary compiler AST fields or authority claims. +Every object has an exact set of required fields; unknown fields, versions and +node kinds are errors. + +```nildata +nildata 1 +object + schema is "nil.matrix.submission-request.v1" + profile is "matrix.pure.v1" + bindings is an array + item is an object + name is "amount" + value is an object + kind is "number" + value is "40" + end object + end object + end array + value is an object + kind is "binary" + operator is "plus" + left is an object + kind is "name" + name is "amount" + end object + right is an object + kind is "number" + value is "2" + end object + end object +end object +``` + +The four envelope fields are `schema`, `profile`, `bindings` and `value`. +Bindings are ordered `{name, value}` objects; each value is an expression. +The final `value` is an expression or null for a void submission. Names use +one unescaped Matrix identifier, with Matrix folding and duplicate-name rules. +References must resolve to an earlier binding; they cannot name host operations. + +Each expression has `kind` and the following additional required fields: + +| Kind | Fields | +| --- | --- | +| `number` | `value`: exact numeric token as text, such as `"-1.6"`; checked by the shared numeric rules | +| `text` | `value`: text | +| `boolean` | `value`: boolean | +| `name` | `name`: binding name | +| `unary` | `operator`, `operand` | +| `binary` | `operator`, `left`, `right` | +| `tuple`, `array` | `items`: expression array | +| `index` | `target`, `index`: expressions | +| `member` | `target`: expression; `index`: canonical nonnegative integer text for a tuple position | +| `cast` | `value`: expression; `type`: `bool`, `i32`, `i64`, `u8` or `f64` | +| `conditional` | `condition`, `then`, `otherwise`: expressions | + +Unary operators are `negative`, `not` and `bitwise-not`. Binary operators are +`plus`, `minus`, `times`, `divided-by`, `modulo`, `equals`, `not-equals`, +`less-than`, `less-or-equal`, `greater-than`, `greater-or-equal`, `and`, `or`, +`bitwise-and`, `bitwise-or`, `bitwise-xor`, `shift-left` and `shift-right`. +Type/profile validation still applies to decoded expressions. + +## Bounds and tests + +Both inputs are limited to 65,536 bytes of valid UTF-8 with no embedded NUL. +Matrix submission scanning has a 4,096-token limit and parsing has a 64-level +nesting limit. Requests also use the shared NILData format limits and a 32-level +expression decoder limit. AST/profile checks allow at most 4,096 nodes and 64 +levels, with additional limits for local names, collections and type shapes. +Generated NIL is capped at 4,096 instructions, 256 locals/stack slots and 1 MiB +of tracked text. These are admission limits, not execution quotas. + +`matrix.submission-parser`, `matrix.submission-request`, +`nil.submission-profile` and `matrix.submission-contract` cover completeness, +strict decoding, forbidden AST/NIL operations, resource limits, diagnostics, +source/request equivalence and command isolation. They run without an executor. diff --git a/matrix/README.md b/matrix/README.md index 71bea2bc..51d6b8d1 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -29,7 +29,7 @@ which. | Front-end integration plan | [`docs/front-end-plan.md`](docs/front-end-plan.md) | | Next-version findings and validation notes | [`docs/next-version-findings.md`](docs/next-version-findings.md) — confirmed limitations, design friction, fixes, and acceptance checks | | Sample programs | [`samples/`](samples/) | -| Shell profile | [NIL-0018 proposal](../docs/design/NIL-0018-matrix-shell-profile.md) and ordinary hosted syntax example; submission parsing and restricted execution are not implemented | +| Shell profile | [Pure submission checking](../docs/tools/matrix-submissions.md) for Matrix and NILData requests is implemented; execution, sessions and Anomalous adapters remain [proposed](../docs/design/NIL-0018-matrix-shell-profile.md) | | Lexer, parser, lowering | **Implemented through stage 6** — see [`docs/front-end-plan.md`](docs/front-end-plan.md) for the stage-by-stage status and exit evidence | Source files use the `.matrix` extension, or `.mat` as the short form. Both diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index ca5948ef..113f491d 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2100,12 +2100,47 @@ state needs explicit ownership and publication rules. **Design checkpoint:** [NIL-0018](../../docs/design/NIL-0018-matrix-shell-profile.md) proposes Matrix as the language surface for Anomalous's existing Canticle session model. A fixed-data example passes text NIL, binary NIL and LLVM AOT routes. It -is an ordinary hosted Matrix program; submission parsing, profile verification, -resource enforcement, real service adapters and native Anomalous execution are -not implemented by this checkpoint. +is an ordinary hosted Matrix program. The subsequent admission slice implements +submission parsing and pure AST/NIL profile verification (F71); execution +resource enforcement, real service adapters and native Anomalous execution +remain open. Anomalous already has newer program-descriptor scaffolding than its initial runtime handoff describes, but no live NIL execution in that profile. Its runtime refresh script still assumes the old Ny checkout/tool/library names; reconcile the copied SDK before adopting newer examples. Framework executable-context inspection also remains authored intent, not a derived authority grant. + +### F71 — Interactive completeness and admission need explicit contracts + +**Observation:** Full-page error recovery cannot tell a prompt whether more +input could complete a statement. Page-wide declaration prescanning also treated +column-one local bindings as types, and folded tuple/local spellings could +disagree with the shared AST's exact symbol names. Wrapping text in a synthetic +book would obscure source locations without resolving either problem. + +**Implemented:** A dedicated submission entry point reuses the existing Matrix +statement/expression parser and preserves original spans. Structured lexical +EOF information distinguishes incomplete input from malformed input, including +unfinished interpolation containing an earlier error. Submission local and +tuple names resolve consistently under Matrix folding. A strict versioned +NILData request decoder constructs the same shared AST, with node paths retained +through profile and type diagnostics. + +The compiler's [submission commands](../../docs/tools/matrix-submissions.md) +check a pure profile at both AST and generated NIL levels without execution. +The NIL gate checks all instructions, forward control flow, initialized locals, +stack shapes and fresh tuple initialization. Source/request equivalence, +forbidden effects (including dead branches), malformed metadata, resource +bounds and command isolation have regression coverage. Standard input uses +binary mode on Windows to prevent control-character truncation and CRLF byte +offset changes; Windows runtime qualification still belongs to its platform CI. + +**Remaining friction:** A checked expression can still fail at runtime, and +bounded syntax/instruction counts do not bound allocation or work inside an +operation. The first profile therefore excludes all calls and queries, even +otherwise pure library operations. A bounded evaluator, typed value projection, +retained-binding ownership and command catalogs are the next steps. The request +schema initially covers expression bindings and a final value, not every Matrix +statement or formatting shorthand. Adding either route must preserve the shared +profile and diagnostic contract. diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 57cd2fa8..529812eb 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -30,6 +30,9 @@ set(NILCOMPILER_CORE_SOURCES src/matrix_parser.cpp src/matrix_diagnostics.cpp src/matrix_hag_bridge.cpp + src/matrix_submission.cpp + src/submission_profile.cpp + src/submission_request.cpp src/codegen.cpp src/vm.cpp src/preprocessor.cpp diff --git a/nilcompiler/src/formatted_text.hpp b/nilcompiler/src/formatted_text.hpp index 1aff2053..3dc75c4c 100644 --- a/nilcompiler/src/formatted_text.hpp +++ b/nilcompiler/src/formatted_text.hpp @@ -34,6 +34,7 @@ struct formatted_text_piece { std::string text; std::size_t start = 0; std::size_t length = 0; + bool closed = true; }; struct formatted_text_scan { @@ -41,6 +42,7 @@ struct formatted_text_scan { std::size_t end = 0; std::size_t error_offset = 0; std::string error; + bool incomplete = false; }; inline bool formatted_name_byte(unsigned char c) { @@ -58,9 +60,10 @@ inline std::size_t formatted_expression_end(const std::string &source, formatted_text_scan &result) { std::size_t cursor = begin; unsigned braces = 1; - const auto fail = [&](std::size_t at, const std::string &message) { + const auto fail = [&](std::size_t at, const std::string &message, bool incomplete = false) { result.error_offset = at; result.error = message; + result.incomplete = incomplete; return source.size(); }; while (cursor < source.size()) { @@ -73,7 +76,7 @@ inline std::size_t formatted_expression_end(const std::string &source, if (!matrix && source.compare(cursor, 3, "###") == 0) { const auto end = source.find("###", cursor + 3); if (end == std::string::npos) - return fail(cursor, "unterminated comment in interpolation"); + return fail(cursor, "unterminated comment in interpolation", true); if (source.find_first_of("\r\n", cursor) < end) return fail(cursor, "interpolation expressions must stay on one line"); cursor = end + 3; @@ -85,7 +88,7 @@ inline std::size_t formatted_expression_end(const std::string &source, if (!matrix && source.compare(cursor, 2, "/*") == 0) { const auto end = source.find("*/", cursor + 2); if (end == std::string::npos) - return fail(cursor, "unterminated comment in interpolation"); + return fail(cursor, "unterminated comment in interpolation", true); if (source.find_first_of("\r\n", cursor) < end) return fail(cursor, "interpolation expressions must stay on one line"); cursor = end + 2; @@ -111,6 +114,7 @@ inline std::size_t formatted_expression_end(const std::string &source, if (!nested.error.empty()) { result.error_offset = nested.error_offset; result.error = nested.error; + result.incomplete = nested.incomplete; return source.size(); } cursor = nested.end; @@ -132,14 +136,14 @@ inline std::size_t formatted_expression_end(const std::string &source, break; } } - if (!closed) return fail(opening, "unterminated literal in interpolation"); + if (!closed) return fail(opening, "unterminated literal in interpolation", true); continue; } if (c == '{') ++braces; if (c == '}' && --braces == 0) return cursor; ++cursor; } - return fail(begin - 1, "unterminated interpolation; expected '}'"); + return fail(begin - 1, "unterminated interpolation; expected '}'", true); } inline formatted_text_scan scan_formatted_text(const std::string &source, @@ -148,9 +152,10 @@ inline formatted_text_scan scan_formatted_text(const std::string &source, unsigned depth) { formatted_text_scan result; result.end = source.size(); - const auto fail = [&](std::size_t at, const std::string &message) { + const auto fail = [&](std::size_t at, const std::string &message, bool incomplete = false) { result.error_offset = at; result.error = message; + result.incomplete = incomplete; }; if (depth >= 64) { fail(quote, "interpolation nesting exceeds 64 levels"); @@ -184,7 +189,14 @@ inline formatted_text_scan scan_formatted_text(const std::string &source, flush(); const auto begin = cursor + 1; const auto end = formatted_expression_end(source, begin, matrix, depth + 1, result); - if (!result.error.empty()) return result; + if (!result.error.empty()) { + // Preserve an unfinished expression for Matrix submission parsing. + // Its normal lexer/parser can still reject a malformed earlier token. + if (result.incomplete) + result.pieces.push_back({true, source.substr(begin), begin, + source.size() - begin, false}); + return result; + } result.pieces.push_back({true, source.substr(begin, end - begin), begin, end - begin}); cursor = end + 1; literal_start = cursor; @@ -220,7 +232,8 @@ inline formatted_text_scan scan_formatted_text(const std::string &source, ++cursor; } } - fail(quote, "unterminated formatted text; expected a closing quote"); + flush(); + fail(quote, "unterminated formatted text; expected a closing quote", true); return result; } diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 4b82726f..9eed31da 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -17,6 +17,7 @@ #include "matrix_diagnostics.hpp" #include "matrix_parser.hpp" +#include "matrix_submission.hpp" #include "parser.hpp" #include "type_checker.hpp" #include "executable_context.hpp" @@ -386,6 +387,8 @@ static void print_usage(std::ostream &out = std::cerr) { << " [--emit-reflection ]\n" << " [--disable-rule ] [--warnings-as-errors]\n" << " nilcompiler --list-analysis-rules List built-in analyzer rules as JSON\n" + << " nilcompiler --check-submission Check a pure Matrix submission; no execution\n" + << " nilcompiler --check-submission-request Check a NILData submission request\n" << " nilcompiler --to-nildata \n" << " nilcompiler --to-json \n" << " nilcompiler --import-nydata \n" @@ -648,6 +651,20 @@ static int convert_nildata(const std::string &operation, const std::string &path } static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) { + // Submission inspection never enters ordinary import discovery, compilation + // output handling, bundling, JIT, or execution. Refuse mixed command modes. + for (int i = 1; i < argc; ++i) { + const std::string option = argv[i]; + if (option == "--") break; + if (option != "--check-submission" && + option != "--check-submission-request") continue; + if (argc != 3 || i != 1 || analysis) { + std::cerr << "Error: use nilcompiler " << option << " alone\n"; + return 1; + } + return matrix::run_submission_check_cli( + option == "--check-submission-request", argv[2]); + } // Inspection is a separate, read-only command. Do not partially process a // compilation or accept extra output/execute options around its input. for (int i = 1; i < argc; ++i) { diff --git a/nilcompiler/src/matrix_lexer.cpp b/nilcompiler/src/matrix_lexer.cpp index 8ee689b8..22537c42 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -186,8 +186,10 @@ char lexer::advance() { return c; } -void lexer::error(int line, int col, std::string message, std::string hint) { - errors_.push_back({line, col, std::move(message), std::move(hint)}); +void lexer::error(int line, int col, std::string message, std::string hint, + bool incomplete) { + errors_.push_back({line, col, std::move(message), std::move(hint), incomplete, + token_start_}); } token lexer::make(token_kind kind, const std::string &lexeme, int line, @@ -297,7 +299,7 @@ token lexer::scan_backtick_identifier() { } if (at_end() || peek() != '`') { error(line, col, "unterminated escaped identifier", - "an escaped identifier is written `like-this` on one line"); + "an escaped identifier is written `like-this` on one line", at_end()); token t = make(token_kind::invalid, spelling, line, col); t.key = fold_key(spelling); return t; @@ -320,7 +322,7 @@ token lexer::scan_number(bool tuple_position) { spelling.push_back(advance()); spelling.push_back(advance()); if (!std::isxdigit(static_cast(peek()))) { - error(line, col, "hexadecimal literal has no digits"); + error(line, col, "hexadecimal literal has no digits", {}, at_end()); } while (std::isxdigit(static_cast(peek()))) spelling.push_back(advance()); @@ -346,7 +348,9 @@ token lexer::scan_number(bool tuple_position) { if (ny::is_floating_literal_spelling(spelling)) { double value = 0.0; if (const auto *message = ny::parse_floating_literal(spelling, value)) - error(line, col, message); + error(line, col, message, {}, at_end() && !spelling.empty() && + (spelling.back() == 'e' || spelling.back() == 'E' || + spelling.back() == '+' || spelling.back() == '-')); } token t = make(token_kind::number_literal, spelling, line, col); t.key = spelling; @@ -369,7 +373,7 @@ token lexer::scan_string() { error(line, col, "unterminated text literal", "a quoted literal stays on one line and has no escape sequences; " "use 'plus quote plus' for a literal quote, or a 'begin text' " - "block for multi-line content"); + "block for multi-line content", at_end()); return make(token_kind::invalid, contents, line, col); } advance(); // closing quote @@ -397,7 +401,9 @@ void lexer::scan_formatted_string(std::vector &tokens, }; if (!scanned.error.empty()) { error(positions.line(scanned.error_offset), positions.column(scanned.error_offset), - scanned.error); + scanned.error, {}, scanned.incomplete); + } + if (!scanned.error.empty() && (!scanned.incomplete || !retain_incomplete_)) { emit(token_kind::invalid, scanned.error, scanned.error_offset, 1); } else { emit(token_kind::formatted_string_begin, "formatted \"", word.start, @@ -408,7 +414,7 @@ void lexer::scan_formatted_string(std::vector &tokens, continue; } emit(token_kind::interpolation_begin, "{", piece.start - 1, 1); - lexer expression(piece.text, interpolation_depth_ + 1); + lexer expression(piece.text, interpolation_depth_ + 1, retain_incomplete_); for (auto value : expression.scan()) { if (value.kind == token_kind::end_of_file) continue; if (value.line == 1) value.column += positions.column(piece.start) - 1; @@ -419,11 +425,14 @@ void lexer::scan_formatted_string(std::vector &tokens, for (const auto &failure : expression.errors()) { const auto column = failure.column + (failure.line == 1 ? positions.column(piece.start) - 1 : 0); error(failure.line + positions.line(piece.start) - 1, column, - failure.message, failure.hint); + failure.message, failure.hint, failure.incomplete && !piece.closed); + errors_.back().start = piece.start + failure.start; } - emit(token_kind::interpolation_end, "}", piece.start + piece.length, 1); + if (piece.closed) + emit(token_kind::interpolation_end, "}", piece.start + piece.length, 1); } - emit(token_kind::formatted_string_end, "\"", scanned.end - 1, 1); + if (scanned.error.empty()) + emit(token_kind::formatted_string_end, "\"", scanned.end - 1, 1); } pos_ = scanned.end; line_ = positions.line(pos_); @@ -473,7 +482,7 @@ token lexer::scan_text_block(int line, int col) { } if (!terminated) { error(line, col, "unterminated 'begin text' block", - "close it with a line whose only content is 'end text'"); + "close it with a line whose only content is 'end text'", true); return make(token_kind::invalid, "", line, col); } diff --git a/nilcompiler/src/matrix_lexer.hpp b/nilcompiler/src/matrix_lexer.hpp index bcd0070b..d067221a 100644 --- a/nilcompiler/src/matrix_lexer.hpp +++ b/nilcompiler/src/matrix_lexer.hpp @@ -167,6 +167,9 @@ struct lex_error { int column = 0; std::string message; std::string hint; + // True only when appending input can complete the lexical construct. + bool incomplete = false; + std::size_t start = 0; }; // Fold one identifier to its lookup key: ASCII-lowercase, with every '-' and @@ -188,8 +191,10 @@ const char *keyword_name(kw k); class lexer { public: - explicit lexer(const std::string &source, unsigned interpolation_depth = 0) - : src_(source), interpolation_depth_(interpolation_depth) {} + explicit lexer(const std::string &source, unsigned interpolation_depth = 0, + bool retain_incomplete = false) + : src_(source), interpolation_depth_(interpolation_depth), + retain_incomplete_(retain_incomplete) {} std::vector scan(); const std::vector &errors() const { return errors_; } @@ -203,6 +208,7 @@ class lexer { int line_ = 1; int col_ = 1; unsigned interpolation_depth_ = 0; + bool retain_incomplete_ = false; bool at_end() const { return pos_ >= src_.size(); } char peek(size_t ahead = 0) const { @@ -222,7 +228,8 @@ class lexer { // True when 'begin' is immediately followed by 'text' and end of line. bool text_block_follows() const; token scan_backtick_identifier(); - void error(int line, int col, std::string message, std::string hint = {}); + void error(int line, int col, std::string message, std::string hint = {}, + bool incomplete = false); }; } // namespace matrix diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 04d1dda4..21782304 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -11,6 +11,8 @@ namespace matrix { namespace { +struct submission_abort { submission_state state; }; + bool exact_phrase_word(const token &value, const char *word) { if ((value.kind != matrix::token_kind::identifier && value.kind != matrix::token_kind::keyword) || value.escaped_identifier) return false; @@ -147,16 +149,32 @@ std::string nil_path(const std::string &written) { } // namespace parser::parser(const std::string &source, const parser_options &opts) - : filename_(opts.filename), signature_cursor_(opts.signature_cursor) { + : filename_(opts.filename), signature_cursor_(opts.signature_cursor), + source_size_(source.size()), submission_requested_(opts.submission) { + if (opts.submission && source.size() > submission_source_limit) { + token eof; + eof.kind = matrix::token_kind::end_of_file; + tokens_.push_back(eof); + submission_limit_error(eof, "submission exceeds the 65536-byte source limit"); + return; + } if (signature_cursor_ && *signature_cursor_ <= source.size()) { auto start = *signature_cursor_; while (start && (source[start - 1] == ' ' || source[start - 1] == '\t')) --start; signature_blank_start_ = start; } - lexer lex(source); + lexer lex(source, 0, opts.submission); tokens_ = lex.scan(); - prescan_declarations(); + if (opts.submission && tokens_.size() > submission_token_limit + 1) { + submission_limit_error(tokens_[submission_token_limit], + "submission exceeds the 4096-token limit"); + return; + } + prescan_declarations(opts.submission); for (const auto &e : lex.errors()) { + lexical_incomplete_ |= e.incomplete; + lexical_invalid_ |= !e.incomplete; + if (e.incomplete) incomplete_tokens_.push_back(e.start); matrix::diagnostic rich; rich.level = matrix::severity::error; rich.code = "MX0001"; @@ -184,7 +202,7 @@ parser::parser(const std::string &source, const parser_options &opts) // back to its written spelling in resolve_name, which is the right answer for // the standard library: 'read-regular-bytes' becomes 'read_regular_bytes', // matching Ny's snake_case declaration. -void parser::prescan_declarations() { +void parser::prescan_declarations(bool submission) { const auto record = [&](const token &t) { if (!t.is_name()) return; declared_.emplace(t.key, nil_symbol(t.lexeme)); @@ -207,11 +225,11 @@ void parser::prescan_declarations() { // one book whose folded keys match but whose spellings differ are one // name, which the checker reports only as "already declared in this // scope" without saying that case folding is the reason. - if (here.is_name() && here.column == 1 && + if (!submission && here.is_name() && here.column == 1 && (next.is(kw::receives) || next.is(kw::returns) || next.is(kw::begin) || next.is(kw::means) || next.is(kw::inherits) || next.is(kw::provides))) record_type(here); - if ((here.is(kw::constant) || here.is(kw::value) || + if (!submission && (here.is(kw::constant) || here.is(kw::value) || here.is(kw::variable)) && here.column <= 8 && next.is_name()) record_type(next); @@ -236,6 +254,24 @@ void parser::prescan_declarations() { next.is_name()) record(next); + // A submission's tuple destructuring names are locals just like scalar + // bindings. Keep their declared spelling for folded references as well. + if (submission) { + std::size_t opening = tokens_.size(); + if ((here.is(kw::value) || here.is(kw::variable) || here.is(kw::constant)) && + next.kind == token_kind::left_paren) + opening = i + 1; + if (here.is(kw::for_) && next.reads("each") && i + 2 < tokens_.size() && + tokens_[i + 2].kind == token_kind::left_paren) + opening = i + 2; + for (auto binding = opening + (opening < tokens_.size()); + binding < tokens_.size() && tokens_[binding].is_name(); binding += 2) { + record(tokens_[binding]); + if (binding + 1 >= tokens_.size() || tokens_[binding + 1].kind != token_kind::comma) + break; + } + } + // A parameter binding: ' as ' anywhere in a header. if (here.is_name() && next.is(kw::as)) record(here); @@ -342,6 +378,37 @@ void parser::error(const token &at, std::string message, std::string hint, d.message = std::move(message); if (!hint.empty()) d.hint = std::move(hint); diagnostics_.push_back(std::move(d)); + if (parsing_submission_) { + const bool lexical_end = at.kind == matrix::token_kind::invalid && + std::find(incomplete_tokens_.begin(), incomplete_tokens_.end(), at.start) != + incomplete_tokens_.end(); + throw submission_abort{at.kind == matrix::token_kind::end_of_file || lexical_end + ? submission_state::incomplete + : submission_state::invalid}; + } +} + +void parser::submission_limit_error(const token &at, const char *message) { + lexical_invalid_ = true; + // Resource limits cannot be repaired by appending more source, even at EOF. + const bool was_parsing = parsing_submission_; + parsing_submission_ = false; + error(at, message, {}, "MX1001"); + parsing_submission_ = was_parsing; + if (was_parsing) throw submission_abort{submission_state::invalid}; +} + +parser::submission_depth_guard::submission_depth_guard(parser &value) + : owner(value), active(value.parsing_submission_) { + if (active) { + if (owner.submission_depth_ >= submission_depth_limit) + owner.submission_limit_error(owner.peek(), + "submission exceeds the 64-level parser nesting limit"); + ++owner.submission_depth_; + } +} +parser::submission_depth_guard::~submission_depth_guard() { + if (active) --owner.submission_depth_; } // Keywords an agent is likely to bring from another language, with the Matrix @@ -518,6 +585,7 @@ void parser::recover_to_declaration() { // type is an error: 'as byte' is rejected and 'as override byte' is the // spelling, so every exact width is marked and greppable. std::optional parser::parse_type() { + submission_depth_guard depth(*this); const token &start = peek(); if (match(kw::tuple)) { @@ -1291,12 +1359,20 @@ std::shared_ptr parser::parse_program() { // 'sleep for ...' are appended once, after the page's own declarations. for (auto &decl : synthesized_) program->declarations.push_back(decl); + validate_integer_literals(); + return program; +} + +void parser::validate_integer_literals() { // Check every source integer, including unused/default expressions. Only // direct unary minimum literals may use the positive boundary magnitude. for (size_t index = 0; index < tokens_.size(); ++index) { const auto &number = tokens_[index]; if (number.kind != matrix::token_kind::number_literal || ny::is_floating_literal_spelling(number.lexeme)) continue; + if (submission_requested_ && + std::find(incomplete_tokens_.begin(), incomplete_tokens_.end(), number.start) != + incomplete_tokens_.end()) continue; ny::integer_literal_info info; if (const auto *message = ny::parse_integer_literal(number.lexeme, info)) { const auto boundary = integer_boundaries_.find(index); @@ -1305,7 +1381,107 @@ std::shared_ptr parser::parse_program() { error(number, message); } } - return program; +} + +bool parser::submission_declaration_start() const { + switch (peek().word) { + case kw::book: case kw::library: case kw::chapter: case kw::read: case kw::cite: + case kw::public_: case kw::abstract: case kw::virtual_: case kw::replaces: + case kw::context: case kw::note: case kw::field: case kw::test: + return true; + default: break; + } + if (!peek().is_name()) return false; + if (peek(1).is(kw::begin)) + return !(exact_phrase_word(peek(), "collect") && exact_phrase_word(peek(2), "query")); + return peek(1).is(kw::receives) || peek(1).is(kw::returns) || + peek(1).is(kw::means) || peek(1).is(kw::inherits) || peek(1).is(kw::provides) || + (peek(1).is(kw::of) && peek(2).is(kw::type)); +} + +bool parser::submission_statement_start() { + if (check(kw::when)) { + // 'when condition give ...' is unambiguously a value. The form containing + // 'then' retains its existing statement interpretation at statement level; + // parentheses can request value position for either spelling. + const auto saved = pos_; + advance(); + parse_expression(); + const bool value_position = check(kw::give); + pos_ = saved; + return !value_position; + } + switch (peek().word) { + case kw::value: case kw::variable: case kw::constant: case kw::set: + case kw::say: case kw::give: case kw::evaluate: case kw::append: + case kw::when: case kw::repeat: case kw::stop: case kw::continue_: + case kw::consider: case kw::allocate: case kw::release: case kw::attempt: + case kw::raise: case kw::own: case kw::borrow: case kw::move: + case kw::sleep: case kw::assembly: + return true; + default: return false; + } +} + +submission_parse_result parser::parse_submission() { + submission_parse_result result; + if (source_size_ > submission_source_limit && !lexical_invalid_) + submission_limit_error(peek(), "submission exceeds the 65536-byte source limit"); + if (tokens_.size() > submission_token_limit + 1 && !lexical_invalid_) + submission_limit_error(tokens_[submission_token_limit], "submission exceeds the 4096-token limit"); + if (lexical_invalid_) { + result.diagnostics = rich_; + return result; + } + // A submission has local bindings, even at column one. Page-wide collision + // heuristics for book declarations must not turn those bindings into types. + declared_.clear(); + declared_types_.clear(); + prescan_declarations(true); + signature_cursor_.reset(); + signature_blank_start_.reset(); + submission_requested_ = true; + parsing_submission_ = true; + result.body = std::make_shared(1); + result.body->source_file = filename_; + result.state = submission_state::complete; + try { + if (pos_ != 0) + error(peek(), "a submission parser cannot reuse an already consumed token stream", {}, "MX1002"); + skip_terminators(); + while (!at_end()) { + if (submission_declaration_start()) + error(peek(), "books, imports and named declarations are unavailable in a submission", + "use local value bindings and expressions, or compile a full Matrix page", "MX1002"); + if (submission_statement_start()) { + auto statement = parse_statement(); + if (statement) result.body->statements.push_back(std::move(statement)); + } else { + result.value = parse_expression(); + skip_terminators(); + if (!at_end()) + error(peek(), "a bare expression must be the final item in a submission", {}, "MX1002"); + break; + } + skip_terminators(); + } + if (lexical_incomplete_) result.state = submission_state::incomplete; + } catch (const submission_abort &failure) { + result.state = failure.state; + } + parsing_submission_ = false; + // A malformed integer earlier in the input stays invalid even if a later + // operand or block is unfinished. Use the same boundary validation as pages. + const auto diagnostic_count = diagnostics_.size(); + validate_integer_literals(); + if (diagnostics_.size() != diagnostic_count || lexical_invalid_) + result.state = submission_state::invalid; + if (result.state != submission_state::complete) { + result.body.reset(); + result.value.reset(); + } + result.diagnostics = rich_; + return result; } // --------------------------------------------------------------------------- @@ -1886,7 +2062,8 @@ std::shared_ptr parser::parse_binding_statement() { return nullptr; } const token binding = advance(); - auto child = std::make_shared(nil_symbol(binding.lexeme), + auto child = std::make_shared( + parsing_submission_ ? resolve_name(binding.lexeme) : nil_symbol(binding.lexeme), nullptr, std::nullopt, mutable_binding, false, binding.line); child->name_span = name_span(binding); child->is_const = constant_binding; @@ -1914,7 +2091,8 @@ std::shared_ptr parser::parse_binding_statement() { return nullptr; } const token &name_token = peek(); - const std::string name = nil_symbol(advance().lexeme); + const std::string written_name = advance().lexeme; + const std::string name = parsing_submission_ ? resolve_name(written_name) : nil_symbol(written_name); reject_type_name_collision(name_token, name_token.lexeme); std::optional type; if (match(kw::as)) type = parse_type(); @@ -1994,6 +2172,7 @@ std::shared_ptr parser::parse_append() { // 'when c then ... [otherwise when c then ...] [otherwise ...] end when' std::shared_ptr parser::parse_when_statement() { + submission_depth_guard depth(*this); const int line = peek().line; advance(); // 'when' auto condition = parse_expression(); @@ -2070,7 +2249,8 @@ std::shared_ptr parser::parse_repeat() { if (check(matrix::token_kind::right_paren)) break; if (!peek().is_name()) { expected_name("in tuple loop bindings"); return nullptr; } const auto binding = advance(); - bindings.emplace_back(nil_symbol(binding.lexeme), std::nullopt, false, binding.line, std::nullopt); + bindings.emplace_back(parsing_submission_ ? resolve_name(binding.lexeme) : nil_symbol(binding.lexeme), + std::nullopt, false, binding.line, std::nullopt); bindings.back().name_span = name_span(binding); } while (match(matrix::token_kind::comma)); expect(matrix::token_kind::right_paren, "')'", "after tuple loop bindings"); @@ -2088,7 +2268,8 @@ std::shared_ptr parser::parse_repeat() { } const token &var_token = peek(); const int var_line = peek().line; - const std::string var = nil_symbol(advance().lexeme); + const std::string written_var = advance().lexeme; + const std::string var = parsing_submission_ ? resolve_name(written_var) : nil_symbol(written_var); // Use the vector constructor even for one variable: codegen's range and // iterator paths both test `variables.size() == 1`, and the single-variable @@ -2131,8 +2312,16 @@ std::shared_ptr parser::parse_repeat() { } std::shared_ptr parser::parse_statement() { + submission_depth_guard depth(*this); const token &start = peek(); const int line = start.line; + if (parsing_submission_ && submission_declaration_start()) + error(start, "named declarations and imports are unavailable in a submission", {}, "MX1002"); + if (parsing_submission_ && check(kw::end) && peek(1).kind == token_kind::end_of_file) + error(peek(1), "expected a block kind after 'end'"); + if (parsing_submission_ && (check(kw::stop) || check(kw::continue_)) && + peek(1).kind == token_kind::end_of_file) + error(peek(1), "expected 'repeating' after the control-flow keyword"); if (peek().is_name() && peek(1).is(kw::begin) && exact_phrase_word(peek(2), "pattern")) { const auto name = advance(); @@ -2202,7 +2391,10 @@ std::shared_ptr parser::parse_statement() { // no symbol precedence to misremember; '(' ')' group. // --------------------------------------------------------------------------- -ny::ast_expr_ptr parser::parse_expression() { return parse_or(); } +ny::ast_expr_ptr parser::parse_expression() { + submission_depth_guard depth(*this); + return parse_or(); +} ny::ast_expr_ptr parser::parse_or() { auto left = parse_and(); @@ -2231,6 +2423,7 @@ ny::ast_expr_ptr parser::parse_and() { ny::ast_expr_ptr parser::parse_not() { if (check(kw::not_)) { + submission_depth_guard depth(*this); const int line = peek().line; advance(); auto operand = parse_not(); @@ -2254,6 +2447,10 @@ ny::ast_expr_ptr parser::parse_comparison() { left, ny::token_kind::double_equal, right, line); } + if (parsing_submission_ && check(kw::does) && + (peek(1).kind == token_kind::end_of_file || + (peek(1).is(kw::not_) && peek(2).kind == token_kind::end_of_file))) + error(tokens_.back(), "expected 'does not equal' followed by a value"); if (check(kw::does) && peek(1).is(kw::not_) && check_word("equal", 2)) { advance(); advance(); advance(); auto right = parse_bitwise(); @@ -2277,6 +2474,10 @@ ny::ast_expr_ptr parser::parse_comparison() { auto right = parse_bitwise(); return std::make_shared(left, op, right, line); } + if (parsing_submission_ && (peek(1).kind == token_kind::end_of_file || + ((check_word("less", 1) || check_word("greater", 1) || peek(1).is(kw::at)) && + peek(2).kind == token_kind::end_of_file))) + error(tokens_.back(), "expected the rest of the comparison after 'is'"); error(peek(), "incomplete comparison after 'is'", "the comparisons are 'is less than', 'is greater than', " "'is at most', 'is at least', 'equals' and 'does not equal'"); @@ -2294,6 +2495,8 @@ ny::ast_expr_ptr parser::parse_bitwise() { if (peek(1).is(kw::and_)) op = ny::token_kind::amp; else if (peek(1).is(kw::or_)) op = ny::token_kind::pipe; else if (peek(1).is(kw::xor_)) op = ny::token_kind::caret; + if (parsing_submission_ && peek(1).kind == token_kind::end_of_file) + error(peek(1), "expected 'and', 'or' or 'xor' after 'bitwise'"); if (op == ny::token_kind::invalid) break; // 'bitwise not' is unary advance(); advance(); auto right = parse_shift(); @@ -2313,6 +2516,10 @@ ny::ast_expr_ptr parser::parse_shift() { else if (check_word("right", 1) && check_word("by", 2)) op = ny::token_kind::greater_greater; if (op == ny::token_kind::invalid) { + if (parsing_submission_ && (peek(1).kind == token_kind::end_of_file || + ((check_word("left", 1) || check_word("right", 1)) && + peek(2).kind == token_kind::end_of_file))) + error(tokens_.back(), "expected 'shifted left by' or 'shifted right by' followed by a value"); error(peek(), "incomplete shift", "write 'shifted left by ' or 'shifted right by '"); break; @@ -2373,11 +2580,14 @@ ny::ast_expr_ptr parser::parse_multiplicative() { } ny::ast_expr_ptr parser::parse_unary() { + if (parsing_submission_ && check(kw::bitwise) && peek(1).kind == token_kind::end_of_file) + error(peek(1), "expected 'not' after unary 'bitwise'"); const int line = peek().line; // 'negative' is unary only; 'minus' remains the compatibility spelling. // The lexer emits numeric_sign only when '-' touches the following digits. if (match(kw::negative) || match(kw::minus) || match(matrix::token_kind::numeric_sign)) { + submission_depth_guard depth(*this); auto operand = parse_unary(); if (operand && operand->kind == ny::ast_node_kind::number_literal_node) { auto &number = static_cast(*operand); @@ -2390,6 +2600,7 @@ ny::ast_expr_ptr parser::parse_unary() { line); } if (check(kw::bitwise) && peek(1).is(kw::not_)) { + submission_depth_guard depth(*this); advance(); advance(); auto operand = parse_unary(); return std::make_shared(ny::token_kind::tilde, operand, @@ -2574,6 +2785,7 @@ ny::ast_expr_ptr parser::parse_postfix() { // 'when c give a otherwise give b end when' as a value. ny::ast_expr_ptr parser::parse_when_expression() { + submission_depth_guard depth(*this); const int line = peek().line; advance(); // 'when' auto condition = parse_expression(); @@ -2598,6 +2810,8 @@ ny::ast_expr_ptr parser::parse_when_expression() { advance(); advance(); } else { + if (parsing_submission_ && check(kw::end) && peek(1).kind == token_kind::end_of_file) + error(peek(1), "expected 'when' after 'end'"); error(peek(), "expected 'end when' to close a value-position 'when'"); } return std::make_shared(condition, then_value, else_value, @@ -2610,6 +2824,9 @@ ny::ast_expr_ptr parser::parse_primary() { return parse_query_expression(); const token &start = peek(); const int line = start.line; + if (parsing_submission_ && (check(kw::now) || check(kw::reference)) && + peek(1).kind == token_kind::end_of_file) + error(peek(1), "expected the rest of the value expression"); if (check(matrix::token_kind::number_literal)) { auto number = std::make_shared(advance().lexeme, line); @@ -2695,6 +2912,7 @@ ny::ast_expr_ptr parser::parse_primary() { // 'the length of e' -> e.len(); 'the paragraph f' -> a paragraph value. if (match(kw::the)) { if (match_word("length")) { + submission_depth_guard depth(*this); if (!expect(kw::of, "after 'the length'")) return nullptr; auto subject = parse_postfix(); auto member = @@ -2722,6 +2940,7 @@ ny::ast_expr_ptr parser::parse_primary() { // and a transitive call graph that cannot touch globals, handles, text, // arrays, I/O, clocks or faults. if (match(kw::apply)) { + submission_depth_guard depth(*this); if (!peek().is_name()) { error(peek(), "expected a worker paragraph name after 'apply'", "the worker must be a statically resolved paragraph, not a value"); @@ -2777,6 +2996,7 @@ ny::ast_expr_ptr parser::parse_primary() { // 'reference to x' aliases an existing nominal aggregate handle. if (check(kw::reference) && peek(1).is(kw::to)) { + submission_depth_guard depth(*this); advance(); advance(); auto operand = parse_postfix(); return std::make_shared(operand, line); @@ -3080,6 +3300,7 @@ ny::ast_expr_ptr parser::parse_build() { // A literal, '_', a bare binding, or 'Type.Variant [holding binding]'. ny::ast_pattern parser::parse_pattern() { + submission_depth_guard depth(*this); ny::ast_pattern pattern; if (match(matrix::token_kind::left_paren)) { pattern.kind = ny::ast_pattern_kind::constructor_pattern; @@ -3196,6 +3417,8 @@ std::shared_ptr parser::parse_consider_statement() { continue; } + if (parsing_submission_ && check(kw::end) && peek(1).kind == token_kind::end_of_file) + error(peek(1), "expected 'consider' after 'end'"); if (!expect(kw::when, "to begin a 'consider' arm")) { const int bad = peek().line; while (!at_end() && peek().line == bad) advance(); @@ -3248,6 +3471,8 @@ ny::ast_expr_ptr parser::parse_consider_expression() { if (match(kw::otherwise)) { pattern_expr = std::make_shared("_", line); } else { + if (parsing_submission_ && check(kw::end) && peek(1).kind == token_kind::end_of_file) + error(peek(1), "expected 'consider' after 'end'"); if (!expect(kw::when, "to begin a 'consider' arm")) break; // ast_match_case holds the pattern as an expression, and codegen reads a // specific shape: member_access(identifier(choice), variant) for a unit diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index 44e652dc..780ced23 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -61,6 +61,22 @@ namespace matrix { struct parser_options { std::string filename; std::optional signature_cursor; + // Set before construction for untrusted interactive input: unlike a page, + // a submission is bounded before the constructor starts lexing it. + bool submission = false; +}; + +inline constexpr std::size_t submission_source_limit = 64 * 1024; +inline constexpr std::size_t submission_token_limit = 4096; +inline constexpr std::size_t submission_depth_limit = 64; + +enum class submission_state { complete, incomplete, invalid }; + +struct submission_parse_result { + submission_state state = submission_state::invalid; + std::shared_ptr body; + ny::ast_expr_ptr value; + std::vector diagnostics; }; class parser { @@ -69,6 +85,10 @@ class parser { const parser_options &opts = parser_options()); std::shared_ptr parse_program(); + // Parse ordinary Matrix statements and an optional final bare expression. + // No book/paragraph wrapper is inserted, so original source spans survive. + // On incomplete/invalid input no partial executable AST is returned. + submission_parse_result parse_submission(); const std::vector &diagnostics() const { return diagnostics_; } // The same diagnostics with spans, codes and hints, for the renderer in @@ -96,6 +116,20 @@ class parser { std::string filename_; std::optional signature_cursor_, signature_blank_start_; bool recovered_signature_call_ = false; + std::size_t source_size_ = 0, submission_depth_ = 0; + bool submission_requested_ = false, parsing_submission_ = false; + bool lexical_incomplete_ = false, lexical_invalid_ = false; + std::vector incomplete_tokens_; + struct submission_depth_guard { + parser &owner; + bool active; + explicit submission_depth_guard(parser &owner); + ~submission_depth_guard(); + }; + void validate_integer_literals(); + void submission_limit_error(const token &at, const char *message); + bool submission_statement_start(); + bool submission_declaration_start() const; // Folded lookup key -> the NIL symbol fixed by the DECLARATION site. // References fold against this, which is what makes 'READ-SENSOR', @@ -117,7 +151,7 @@ class parser { void reject_type_name_collision(const token &at, const std::string &written); // Collect declaration spellings from the token stream before parsing. - void prescan_declarations(); + void prescan_declarations(bool submission = false); // Resolve a written reference to its declared NIL symbol, falling back to // the written spelling for names declared elsewhere (a read book, the // standard library) whose declaration this page never sees. diff --git a/nilcompiler/src/matrix_submission.cpp b/nilcompiler/src/matrix_submission.cpp new file mode 100644 index 00000000..c9c1a517 --- /dev/null +++ b/nilcompiler/src/matrix_submission.cpp @@ -0,0 +1,266 @@ +#include "matrix_submission.hpp" +#include "matrix_parser.hpp" +#include "submission_request.hpp" +#include "submission_profile.hpp" +#include "codegen.hpp" +#include "secure_file_io.hpp" +#include "type_checker.hpp" +#include "../../common/strict_json.hpp" + +#include +#include +#include +#ifdef _WIN32 +#include +#include +#endif + +namespace matrix { +namespace { + +using nil::detail::json; + +std::string diagnostic_text(const std::string &text) { + try { + nil::detail::valid_utf8(text); + return text; + } catch (const std::exception &) { + // A filesystem path may contain arbitrary bytes. Keep the protocol valid + // UTF-8 even when the input cannot be opened or decoded. + constexpr char hex[] = "0123456789abcdef"; + std::string escaped; + for (unsigned char byte : text) { + if (byte < 0x80) escaped.push_back(static_cast(byte)); + else { + escaped += "\\x"; + escaped.push_back(hex[byte >> 4]); + escaped.push_back(hex[byte & 15]); + } + } + return escaped; + } +} + +void issue(submission_report &report, const std::string &stage, + const std::string &message, const std::string &location, + int line = 0, const std::string &code = "MS0001") { + // Keep failure reports bounded even for large identifier/literal diagnostics. + const auto safe = diagnostic_text(message); + std::string bounded = safe; + if (bounded.size() > 4096) { + bounded.resize(4096); + while (!bounded.empty() && + (static_cast(safe[bounded.size()]) & 0xc0) == 0x80) + bounded.pop_back(); + bounded += "..."; + } + if (report.diagnostics.size() < 64) + report.diagnostics.push_back({stage, code, bounded, diagnostic_text(location), line, 0, 0}); +} + +void validate_input(const std::string &source) { + if (source.size() > submission_max_input_bytes) + throw std::runtime_error("submission input exceeds 65536 bytes"); + nil::detail::valid_utf8(source); + if (source.find('\0') != std::string::npos) + throw std::runtime_error("submission input must not contain NUL"); +} + +void check_tree(submission_report &report, + const std::shared_ptr &body, + const ny::ast_expr_ptr &value, const std::string &filename) { + if (!body) throw std::runtime_error("submission has no statement body"); + for (const auto &diagnostic : ny::validate_submission_ast(*body, value)) + issue(report, "profile", diagnostic.message, + diagnostic.source_file.empty() ? filename : diagnostic.source_file, diagnostic.line, + "MS1001"); + if (!report.diagnostics.empty()) return; + + // Infer the expression in its actual lexical context through the ordinary + // shared checker. An expression statement is legal in a void paragraph. + // After inference it becomes the synthetic return and is checked again. + auto block = std::make_shared(*body); + if (value) + block->statements.push_back( + std::make_shared(value, value->line)); + auto function = std::make_shared( + "__nil_submission", std::vector{}, "void", block); + ny::ast_program program; + program.filename = filename; + program.declarations.push_back(function); + const auto check = [&]() { + ny::type_checker checker; + if (checker.check(program)) return true; + for (const auto &diagnostic : checker.get_diagnostics()) + issue(report, "type", diagnostic.message, + diagnostic.source_file.empty() ? filename : diagnostic.source_file, + diagnostic.line, "MS2001"); + if (report.diagnostics.empty()) + issue(report, "type", "submission failed type checking", filename, + 0, "MS2001"); + return false; + }; + if (!check()) return; + const std::string result_type = value ? value->inferred_type.value_or("") : "void"; + if (result_type.empty()) { + issue(report, "type", "submission result has no concrete type", filename, + value ? value->line : 0, "MS2001"); + return; + } + if (value) { + function->return_type = result_type; + block->statements.back() = + std::make_shared(value, value->line); + if (!check()) return; + } + + ny::codegen_options options; + options.include_debug_info = false; + options.include_source_debug = false; + options.mode = ny::build_mode::release_mode; + ny::codegen generator(options); + std::vector diagnostics; + const auto module = generator.generate_module(program, &diagnostics); + for (const auto &diagnostic : diagnostics) + issue(report, "lowering", diagnostic.message, filename, diagnostic.line, + "MS3001"); + if (!report.diagnostics.empty()) return; + if (!module) throw std::runtime_error("submission lowering produced no module"); + try { + ny::validate_nil_submission_profile(*module); + } catch (const std::exception &error) { + issue(report, "nil-profile", error.what(), filename, 0, "MS1002"); + return; + } + std::ostringstream output; + ny::nil_writer writer(output, options); + writer.emit_text_module(*module); + auto text = output.str(); + if (text.size() > 1024 * 1024) + throw std::runtime_error("submission NIL output exceeds 1048576 bytes"); + for (const auto &compiled : module->functions) + report.instruction_count += compiled.body.size(); + report.result_type = module->functions.front().return_type; + report.nil_text = std::move(text); + report.status = "complete"; +} + +} // namespace + +submission_report check_submission_source(const std::string &source, + const std::string &filename) { + submission_report report; + report.input_kind = "matrix"; + try { + validate_input(source); + parser_options options; + options.filename = filename; + options.submission = true; + parser frontend(source, options); + const auto parsed = frontend.parse_submission(); + if (parsed.state != submission_state::complete) { + report.status = parsed.state == submission_state::incomplete + ? "incomplete" : "invalid"; + for (const auto &diagnostic : parsed.diagnostics) { + const auto before = report.diagnostics.size(); + issue(report, "parse", diagnostic.message, filename, + diagnostic.primary.line, diagnostic.code); + if (report.diagnostics.size() != before) { + report.diagnostics.back().column = diagnostic.primary.column; + report.diagnostics.back().length = diagnostic.primary.length; + } + } + return report; + } + check_tree(report, parsed.body, parsed.value, filename); + } catch (const std::exception &error) { + issue(report, "input", error.what(), filename); + } + return report; +} + +submission_report check_submission_request(const std::string &source, + const std::string &filename) { + submission_report report; + report.input_kind = "nildata-request"; + try { + validate_input(source); + const auto decoded = decode_submission_request(source); + check_tree(report, decoded.body, decoded.value, filename); + } catch (const submission_request_error &error) { + issue(report, "request", error.what(), error.path, 0, "MS4001"); + } catch (const std::exception &error) { + issue(report, "request", error.what(), filename, 0, "MS4001"); + } + return report; +} + +std::string submission_report_json(const submission_report &report) { + auto out = json::map(); + out.object["schema"] = json::str("nil.matrix.submission-check.v1"); + out.object["profile"] = json::str("matrix.pure.v1"); + out.object["input_kind"] = json::str(report.input_kind); + out.object["status"] = json::str(report.status); + out.object["executed"] = json::flag(false); + out.object["result_type"] = report.status == "complete" + ? json::str(report.result_type) : json{}; + out.object["nil"] = report.status == "complete" + ? json::str(report.nil_text) : json{}; + json count; + count.type = json::kind::number; + count.text = std::to_string(report.instruction_count); + out.object["instruction_count"] = std::move(count); + auto diagnostics = json::list(); + for (const auto &diagnostic : report.diagnostics) { + auto item = json::map(); + item.object["stage"] = json::str(diagnostic.stage); + item.object["code"] = json::str(diagnostic.code); + item.object["message"] = json::str(diagnostic.message); + item.object["location"] = json::str(diagnostic.location); + for (const auto &entry : {std::make_pair("line", diagnostic.line), + std::make_pair("column", diagnostic.column), + std::make_pair("length", diagnostic.length)}) { + json number; + number.type = json::kind::number; + number.text = std::to_string(entry.second); + item.object[entry.first] = std::move(number); + } + diagnostics.array.push_back(std::move(item)); + } + out.object["diagnostics"] = std::move(diagnostics); + return nil::detail::dump(out); +} + +int run_submission_check_cli(bool request, const std::string &path) { + submission_report report; + report.input_kind = request ? "nildata-request" : "matrix"; + try { + std::string source; + if (path == "-") { +#ifdef _WIN32 + if (_setmode(_fileno(stdin), _O_BINARY) == -1) + throw std::runtime_error("cannot enable binary submission stdin"); +#endif + char byte; + while (std::cin.get(byte)) { + if (source.size() == submission_max_input_bytes) + throw std::runtime_error("submission input exceeds 65536 bytes"); + source.push_back(byte); + } + if (!std::cin.eof()) throw std::runtime_error("cannot read submission input"); + } else { + const auto input = ny::detail::read_regular_file_bounded( + path, submission_max_input_bytes); + if (!input.ok) throw std::runtime_error(input.error); + source.assign(input.bytes.begin(), input.bytes.end()); + } + report = request ? check_submission_request(source, path) + : check_submission_source(source, path); + } catch (const std::exception &error) { + issue(report, "input", error.what(), path); + } + std::cout << submission_report_json(report) << '\n'; + return report.status == "complete" ? 0 : report.status == "incomplete" ? 2 : 1; +} + +} // namespace matrix diff --git a/nilcompiler/src/matrix_submission.hpp b/nilcompiler/src/matrix_submission.hpp new file mode 100644 index 00000000..3f52c436 --- /dev/null +++ b/nilcompiler/src/matrix_submission.hpp @@ -0,0 +1,41 @@ +#ifndef NIL_MATRIX_SUBMISSION_HPP +#define NIL_MATRIX_SUBMISSION_HPP + +#include +#include +#include + +namespace matrix { + +inline constexpr std::size_t submission_max_input_bytes = 64 * 1024; + +struct submission_issue { + std::string stage; + std::string code; + std::string message; + std::string location; + int line = 0; + int column = 0; + int length = 0; +}; + +// Admission/inspection only. The report is not an execution authorization or +// a runtime resource guarantee; no VM or native executor is entered here. +struct submission_report { + std::string status = "invalid"; + std::string input_kind; + std::string result_type; + std::string nil_text; + std::size_t instruction_count = 0; + std::vector diagnostics; +}; + +submission_report check_submission_source(const std::string &source, + const std::string &filename); +submission_report check_submission_request(const std::string &source, + const std::string &filename); +std::string submission_report_json(const submission_report &report); +int run_submission_check_cli(bool request, const std::string &path); + +} // namespace matrix +#endif diff --git a/nilcompiler/src/submission_profile.cpp b/nilcompiler/src/submission_profile.cpp new file mode 100644 index 00000000..8d3d9c0c --- /dev/null +++ b/nilcompiler/src/submission_profile.cpp @@ -0,0 +1,516 @@ +#include "submission_profile.hpp" +#include "codegen.hpp" +#include "numeric_literal.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace ny { +namespace { +constexpr std::size_t max_nodes = 4096, max_items = 256, max_bytes = 1024 * 1024; +constexpr unsigned max_depth = 64; +struct rejection { int line; std::string message; std::string source_file; }; +[[noreturn]] void reject(int line, const std::string &message) { + throw rejection{line, "pure submission profile: " + message, {}}; +} +void bytes(std::size_t &total, const std::string &text, int line) { + if (text.size() > max_bytes - total) reject(line, "text budget exceeded"); + total += text.size(); +} +bool name(const std::string &text) { + return !text.empty() && text.size() <= 256 && + std::all_of(text.begin(), text.end(), [](unsigned char c) { + // Keep names unambiguous when the validated artifact is serialized as + // textual NIL; punctuation such as comments and quotes is not a name. + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '_' || c == '$' || c == '.' || c >= 128; + }); +} +bool integer_type(const std::string &type) { + return type == "i32" || type == "i64" || type == "u8" || type == "bool"; +} +bool scalar_type(const std::string &type) { + return integer_type(type) || type == "f64" || type == "text"; +} +struct shape { std::string name; std::vector elements; }; +class shape_parser { + const std::string &text; + std::size_t at = 0, nodes = 0; + bool aliases; + void space() { + if (aliases) while (at < text.size() && (text[at] == ' ' || text[at] == '\t')) ++at; + } + shape part(unsigned depth) { + if (depth > 32 || ++nodes > max_items) reject(0, "type shape exceeds limits"); + space(); + const auto first = at; + while (at < text.size() && ((text[at] >= 'a' && text[at] <= 'z') || + (text[at] >= 'A' && text[at] <= 'Z') || (text[at] >= '0' && text[at] <= '9'))) ++at; + auto base = text.substr(first, at - first); + space(); + if (aliases && (base == "String" || base == "string")) base = "text"; + if (aliases && base == "int") base = "i32"; + if (scalar_type(base)) return {base, {}}; + if ((base != "array" && base != "tuple") || at == text.size() || text[at++] != '<') + reject(0, "unsupported type shape"); + shape result{base, {}}; + do { + result.elements.push_back(part(depth + 1)); + space(); + if (at == text.size()) reject(0, "unterminated type shape"); + if (text[at] == '>') { ++at; break; } + if (text[at++] != ',') reject(0, "invalid type separator"); + } while (true); + if (base == "array" && result.elements.size() != 1) reject(0, "array requires one element type"); + return result; + } +public: + shape_parser(const std::string &source, bool source_aliases) : text(source), aliases(source_aliases) {} + shape parse() { + if (text.size() > 4096) reject(0, "type spelling exceeds limits"); + auto result = part(0); + space(); + if (at != text.size()) reject(0, "trailing type syntax"); + return result; + } +}; +std::string spelling(const shape &type) { + if (type.elements.empty()) return type.name; + std::string result = type.name + '<'; + for (std::size_t i = 0; i < type.elements.size(); ++i) { + if (i) result += ','; + result += spelling(type.elements[i]); + } + return result + '>'; +} +shape type_shape(const std::string &text, bool aliases = false) { return shape_parser(text, aliases).parse(); } +std::size_t count(const std::string &text, std::size_t maximum, int line) { + std::size_t value = 0; + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value); + if (text.empty() || parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || + value > maximum || std::to_string(value) != text) reject(line, "invalid bounded integer operand"); + return value; +} +std::string literal_type(const std::string &text, int line, bool minimum = false) { + if (text.empty() || text.size() > 256) reject(line, "numeric literal exceeds limits"); + if (is_floating_literal_spelling(text)) { + double value; + if (const auto *error = parse_floating_literal(text, value)) reject(line, error); + return "f64"; + } + integer_literal_info value; + if (const auto *error = parse_integer_literal(text, value, minimum)) reject(line, error); + return "integer"; +} +bool binary_operator(token_kind op) { + switch (op) { + case token_kind::plus: case token_kind::minus: case token_kind::star: + case token_kind::slash: case token_kind::percent: case token_kind::mod_kw: + case token_kind::double_equal: case token_kind::not_equal: case token_kind::less: + case token_kind::less_equal: case token_kind::greater: case token_kind::greater_equal: + case token_kind::amp: case token_kind::pipe: case token_kind::caret: + case token_kind::less_less: case token_kind::greater_greater: + case token_kind::amp_amp: case token_kind::pipe_pipe: return true; + default: return false; + } +} +class ast_admission { + std::size_t nodes = 0, text_bytes = 0; + std::vector> scopes{{}}; + template void located(const ast_node &node, Action action) { + try { action(); } + catch (rejection &error) { + // The innermost rejected node owns the diagnostic, including JSON paths + // attached by the typed request decoder. Outer nodes only fill gaps. + if (error.source_file.empty()) error.source_file = node.source_file; + if (error.line == 0) error.line = node.line; + throw; + } + } + void enter(const ast_node &node, unsigned depth) { + if (depth > max_depth || ++nodes > max_nodes) reject(node.line, "AST budget exceeded"); + if (!node.annotations.empty()) reject(node.line, "annotations are not admitted"); + if (node.rejected_tuple_operation) reject(node.line, "rejected tuple operation"); + bytes(text_bytes, node.source_file, node.line); + } + template const T &as(const ast_node &node) { + const auto *result = dynamic_cast(&node); + if (!result) reject(node.line, "AST kind does not match its node"); + return *result; + } + void declared_type(const std::optional &type, int line) { + if (!type) return; + try { (void)type_shape(*type, true); } + catch (const rejection &) { reject(line, "only scalar, array and structural tuple types are admitted"); } + } + void binding(const ast_variable_decl &variable, unsigned depth, bool component = false) { + located(variable, [&] { binding_impl(variable, depth, component); }); + } + void binding_impl(const ast_variable_decl &variable, unsigned depth, bool component) { + enter(variable, depth); + if (variable.is_mut || variable.is_pub || variable.visibility != visibility_kind::visibility_private) + reject(variable.line, "only private immutable local bindings are admitted"); + declared_type(variable.type_name, variable.line); + if (component) { + if (variable.initializer || !variable.tuple_bindings.empty()) reject(variable.line, "invalid tuple binding component"); + } else { + if (!variable.initializer) reject(variable.line, "local bindings require an initializer"); + expression(variable.initializer, depth + 1); + } + if (!variable.tuple_bindings.empty()) { + if (variable.tuple_bindings.size() > max_items) reject(variable.line, "too many tuple bindings"); + for (const auto &item : variable.tuple_bindings) { + if (!item) reject(variable.line, "missing tuple binding"); + binding(*item, depth + 1, true); + } + } else { + if (!name(variable.name)) reject(variable.line, "invalid local name"); + if (variable.name == "_" && component) return; + if (!scopes.back().insert(variable.name).second) reject(variable.line, "duplicate local binding"); + if (scopes.back().size() > max_items) reject(variable.line, "too many local bindings"); + } + } + void scoped(const ast_stmt_ptr &node, unsigned depth) { + scopes.emplace_back(); statement(node, depth); scopes.pop_back(); + } + void expression(const ast_expr_ptr &node, unsigned depth, bool minimum = false) { + if (!node) reject(0, "missing expression"); + located(*node, [&] { expression_impl(node, depth, minimum); }); + } + void expression_impl(const ast_expr_ptr &node, unsigned depth, bool minimum) { + enter(*node, depth); + declared_type(node->inferred_type, node->line); + if (node->checked_class_upcast || node->checked_reference_handle || node->checked_ownership || node->checked_callable_parameters) + reject(node->line, "reference, ownership, class and callable values are not admitted"); + switch (node->kind) { + case ast_node_kind::number_literal_node: + (void)literal_type(as(*node).value, node->line, minimum); return; + case ast_node_kind::string_literal_node: + bytes(text_bytes, as(*node).value, node->line); return; + case ast_node_kind::char_literal_node: + bytes(text_bytes, as(*node).value, node->line); return; + case ast_node_kind::boolean_literal_node: (void)as(*node); return; + case ast_node_kind::identifier_expr_node: { + const auto &id = as(*node); + if (id.resolved_global_name) reject(node->line, "global values are not admitted"); + for (auto scope = scopes.rbegin(); scope != scopes.rend(); ++scope) if (scope->count(id.name)) return; + reject(node->line, "identifier is not an immutable submission local"); + } + case ast_node_kind::binary_expr_node: { + const auto &value = as(*node); + if (!binary_operator(value.op)) reject(node->line, "operator is not admitted"); + expression(value.left, depth + 1); expression(value.right, depth + 1); return; + } + case ast_node_kind::unary_expr_node: { + const auto &value = as(*node); + if (value.op != token_kind::minus && value.op != token_kind::tilde && value.op != token_kind::not_kw) + reject(node->line, "unary operator is not admitted"); + expression(value.operand, depth + 1, value.op == token_kind::minus); return; + } + case ast_node_kind::cast_expr_node: { + const auto &value = as(*node); + const auto type = type_shape(value.target_type, true); + if (!type.elements.empty() || !scalar_type(type.name) || type.name == "text") + reject(node->line, "only numeric scalar casts are admitted"); + expression(value.operand, depth + 1); return; + } + case ast_node_kind::array_literal_expr_node: { + const auto &value = as(*node); + if (value.elements.size() > max_items) reject(node->line, "array literal exceeds limits"); + for (const auto &item : value.elements) expression(item, depth + 1); + return; + } + case ast_node_kind::struct_literal_expr_node: { + const auto &value = as(*node); + if (!value.tuple_literal || value.type_name != "tuple" || !value.type_args.empty() || value.fields.empty() || value.fields.size() > max_items) + reject(node->line, "only structural tuple construction is admitted"); + for (std::size_t i = 0; i < value.fields.size(); ++i) { + if (value.fields[i].first != std::to_string(i)) reject(node->line, "invalid tuple position"); + expression(value.fields[i].second, depth + 1); + } + return; + } + case ast_node_kind::index_expr_node: { + const auto &value = as(*node); + expression(value.object, depth + 1); expression(value.index, depth + 1); return; + } + case ast_node_kind::member_access_expr_node: { + const auto &value = as(*node); + (void)count(value.member_name, max_items - 1, node->line); + expression(value.object, depth + 1); return; + } + case ast_node_kind::if_expr_node: { + const auto &value = as(*node); + expression(value.condition, depth + 1); + expression(value.then_expr, depth + 1); expression(value.else_expr, depth + 1); return; + } + case ast_node_kind::interpolated_string_expr_node: { + const auto &value = as(*node); + if (value.parts.size() > max_items) reject(node->line, "too many formatted text parts"); + for (const auto &part : value.parts) { + if (part.is_literal) { + if (part.expression) reject(node->line, "hidden expression in formatted text literal"); + bytes(text_bytes, part.literal_value, node->line); + } else { + if (!part.literal_value.empty()) reject(node->line, "invalid formatted text expression"); + expression(part.expression, depth + 1); + } + } + return; + } + default: reject(node->line, "expression kind is not admitted (calls, effects and queries are excluded)"); + } + } + void statement(const ast_stmt_ptr &node, unsigned depth) { + if (!node) reject(0, "missing statement"); + located(*node, [&] { statement_impl(node, depth); }); + } + void statement_impl(const ast_stmt_ptr &node, unsigned depth) { + enter(*node, depth); + switch (node->kind) { + case ast_node_kind::block_stmt_node: { + scopes.emplace_back(); + for (const auto &item : as(*node).statements) statement(item, depth + 1); + scopes.pop_back(); return; + } + case ast_node_kind::decl_stmt_node: { + const auto &declaration = as(*node).declaration; + if (!declaration || declaration->kind != ast_node_kind::variable_decl_node) + reject(node->line, "only local binding declarations are admitted"); + binding(as(*declaration), depth + 1); return; + } + case ast_node_kind::expr_stmt_node: expression(as(*node).expression, depth + 1); return; + case ast_node_kind::if_stmt_node: { + const auto &value = as(*node); + expression(value.condition, depth + 1); scoped(value.then_branch, depth + 1); + if (value.else_branch) scoped(value.else_branch, depth + 1); + return; + } + default: reject(node->line, "statement kind is not admitted (effects, loops and declarations are excluded)"); + } + } +public: + void validate(const ast_block_stmt &body, const ast_expr_ptr &value) { + located(body, [&] { + enter(body, 0); + for (const auto &item : body.statements) statement(item, 1); + if (value) expression(value, 1); + }); + } +}; + +struct stack_value { + std::string type; + // Only a NEW_STRUCT result may be initialized, in ascending field order. + // Complete tuples cease to be mutable as soon as their final field is set. + std::optional constructing; + bool operator==(const stack_value &other) const { return type == other.type && constructing == other.constructing; } +}; +struct flow { + std::vector stack; + std::map locals; + std::set assigned; +}; +std::string value_type(const std::string &type) { return integer_type(type) ? "integer" : type; } +bool numeric(const stack_value &value) { return !value.constructing && (value.type == "integer" || value.type == "f64"); } + +void nil_admission(const nil_module &module) { + if (module.module_name != "root" || module.is_library || !module.dependencies.empty() || + !module.embedded_sources.empty() || !module.classes.empty() || !module.enums.empty() || !module.tests.empty() || + module.functions.size() != 1) reject(0, "NIL must contain only the synthetic root submission function"); + const auto &function = module.functions.front(); + if (function.name != "__nil_submission" || !function.params.empty() || !function.generic_params.empty() || + function.is_inline || function.is_test || !function.annotations.empty() || function.source_line < 0) + reject(0, "invalid synthetic function metadata"); + std::size_t text_bytes = 0; + bytes(text_bytes, function.source_file, 0); + if (function.body.empty() || function.body.size() > max_nodes || module.structs.size() > max_items || + module.string_constants.size() > max_items) reject(0, "NIL module budget exceeded"); + std::map schemas; + for (const auto &definition : module.structs) { + const auto type = type_shape(definition.name); + if (type.name != "tuple" || definition.annotations != std::vector{"@nil_tuple"} || + definition.fields.size() != type.elements.size() || !schemas.emplace(definition.name, type).second) + reject(0, "only exact generated tuple schemas are admitted"); + bytes(text_bytes, definition.name, 0); + for (std::size_t i = 0; i < type.elements.size(); ++i) { + if (definition.fields[i].first != std::to_string(i) || definition.fields[i].second != spelling(type.elements[i])) + reject(0, "tuple schema does not match its structural name"); + bytes(text_bytes, definition.fields[i].second, 0); + } + } + const auto check_type = [&](const std::string &text) { + const auto type = type_shape(text); + const auto visit = [&](const auto &self, const shape &part) -> void { + if (part.name == "tuple" && !schemas.count(spelling(part))) reject(0, "missing generated tuple schema"); + for (const auto &child : part.elements) self(self, child); + }; + visit(visit, type); + return type; + }; + for (const auto &schema : schemas) (void)check_type(schema.first); + if (function.return_type != "void") (void)check_type(function.return_type); + std::set constants; + for (const auto &constant : module.string_constants) { + if (!name(constant.first) || !constants.insert(constant.first).second) reject(0, "invalid or duplicate string constant"); + bytes(text_bytes, constant.first, 0); bytes(text_bytes, constant.second, 0); + } + std::map labels; + const std::set arithmetic = {"ADD","SUB","MUL","DIV","MOD","NEG","BIT_AND","BIT_OR","BIT_XOR","SHL","SHR"}; + const std::set comparisons = {"CMP_EQ","CMP_NE","CMP_LT","CMP_LE","CMP_GT","CMP_GE"}; + const std::set bare = {"RET","POP","NOT","STR_CONCAT","GET_INDEX"}; + const auto &body = function.body; + for (std::size_t pc = 0; pc < body.size(); ++pc) { + const auto &instruction = body[pc]; const auto &op = instruction.opname; const auto &args = instruction.args; + const int line = instruction.debug_line; + if (args.size() > 2) reject(line, "too many NIL instruction operands"); + if (line < 0 || !instruction.source_file.empty() || !instruction.debug_locals.empty()) reject(line, "unexpected instruction debug metadata"); + bytes(text_bytes, op, line); + for (const auto &argument : args) bytes(text_bytes, argument, line); + auto arity = [&](std::size_t expected) { if (args.size() != expected) reject(line, "invalid operands for " + op); }; + if (bare.count(op) || comparisons.count(op)) arity(0); + else if (arithmetic.count(op)) { + arity(1); + if (args[0] != "i32" && args[0] != "i64" && args[0] != "u8" && args[0] != "f64") reject(line, "invalid arithmetic metadata"); + if ((op.rfind("BIT_",0) == 0 || op == "SHL" || op == "SHR") && args[0] == "f64") reject(line, "invalid integer arithmetic metadata"); + } else if (op == "PUSH_CONST") { arity(1); (void)literal_type(args[0], line); } + else if (op == "PUSH_CONST_STR") { arity(1); if (!constants.count(args[0])) reject(line, "unknown string constant"); } + else if (op == "CAST" || op == "TO_STRING") { + arity(1); + if (!integer_type(args[0]) && args[0] != "f64") reject(line, "unsupported scalar conversion metadata"); + } else if (op == "LOAD_LOCAL" || op == "STORE_LOCAL" || op == "JMP" || op == "JMP_IF" || op == "JMP_IF_NOT" || op == "LABEL") { + arity(1); if (!name(args[0])) reject(line, "invalid local or label name"); + if (op == "LABEL" && !labels.emplace(args[0], pc).second) reject(line, "duplicate label"); + } else if (op == "NEW_ARRAY_LITERAL") { arity(2); (void)count(args[0], max_items, line); (void)check_type(args[1]); } + else if (op == "NEW_STRUCT") { arity(1); if (!schemas.count(args[0])) reject(line, "unknown tuple schema"); } + else if (op == "SET_FIELD" || op == "GET_FIELD") { arity(1); (void)count(args[0], max_items - 1, line); } + else reject(line, "forbidden or unknown NIL opcode " + op); + } + // Inspect every branch, including unreachable ones, before data flow. + for (std::size_t pc = 0; pc < body.size(); ++pc) { + const auto &instruction = body[pc]; + if (instruction.opname != "JMP" && instruction.opname != "JMP_IF" && instruction.opname != "JMP_IF_NOT") continue; + const auto target = labels.find(instruction.args[0]); + if (target == labels.end() || target->second <= pc) reject(instruction.debug_line, "branches require an existing forward local label"); + } + std::vector> incoming(body.size()); + incoming.front() = flow{}; + auto enqueue = [&](std::size_t pc, const flow &state, int line) { + if (pc >= body.size()) reject(line, "submission function falls through without a return"); + if (!incoming[pc]) { incoming[pc] = state; return; } + auto &prior = *incoming[pc]; + if (prior.stack != state.stack) reject(line, "incompatible stack shapes at branch join"); + for (auto local = prior.locals.begin(); local != prior.locals.end();) { + const auto other = state.locals.find(local->first); + if (other == state.locals.end()) local = prior.locals.erase(local); + else { if (!(local->second == other->second)) reject(line, "incompatible local shapes at branch join"); ++local; } + } + prior.assigned.insert(state.assigned.begin(), state.assigned.end()); + if (prior.assigned.size() > max_items) reject(line, "local budget exceeded"); + }; + for (std::size_t pc = 0; pc < body.size(); ++pc) { + const auto &instruction = body[pc]; const auto &op = instruction.opname; const auto &args = instruction.args; + const int line = instruction.debug_line; + if (!incoming[pc]) reject(line, "unreachable NIL instructions are not admitted"); + flow state = std::move(*incoming[pc]); incoming[pc].reset(); + const auto pop = [&]() { + if (state.stack.empty()) reject(line, "NIL operand stack underflow"); + auto result = state.stack.back(); state.stack.pop_back(); + if (result.constructing) reject(line, "tuple escapes before initialization completes"); + return result; + }; + const auto push = [&](stack_value value) { + if (state.stack.size() >= max_items) reject(line, "NIL operand stack budget exceeded"); + state.stack.push_back(std::move(value)); + }; + const auto matches = [&](const stack_value &value, const std::string &type) { + if (value.constructing || value.type != value_type(type)) reject(line, "value does not match its scalar or collection metadata"); + }; + if (op == "PUSH_CONST") push({literal_type(args[0], line), {}}); + else if (op == "PUSH_CONST_STR") push({"text", {}}); + else if (op == "LOAD_LOCAL") { + const auto found = state.locals.find(args[0]); + if (found == state.locals.end()) reject(line, "load of an uninitialized local"); + push(found->second); + } else if (op == "STORE_LOCAL") { + const auto value = pop(); + if (!state.assigned.insert(args[0]).second) reject(line, "local mutation is not admitted"); + if (state.assigned.size() > max_items) reject(line, "local budget exceeded"); + state.locals.emplace(args[0], value); + } else if (arithmetic.count(op)) { + const auto right = pop(); + if (!numeric(right)) reject(line, "arithmetic requires scalar operands"); + if (op != "NEG") { + const auto left = pop(); if (!numeric(left)) reject(line, "arithmetic requires scalar operands"); + if (args[0] != "f64" && left.type != "integer") reject(line, "integer arithmetic requires integer operands"); + } + if (args[0] != "f64" && right.type != "integer") reject(line, "integer arithmetic requires integer operands"); + push({value_type(args[0]), {}}); + } else if (comparisons.count(op)) { + const auto right = pop(), left = pop(); + if (!(numeric(left) && numeric(right)) && !(left.type == "text" && right.type == "text")) reject(line, "comparison requires scalar or text operands"); + push({"integer", {}}); + } else if (op == "CAST" || op == "TO_STRING") { + const auto value = pop(); if (!numeric(value)) reject(line, "scalar conversion requires a numeric value"); + if (op == "TO_STRING") matches(value, args[0]); + push({op == "TO_STRING" ? "text" : value_type(args[0]), {}}); + } else if (op == "NOT") { + const auto value = pop(); if (value.type != "integer") reject(line, "boolean operator requires an integer/boolean"); + push({"integer", {}}); + } else if (op == "STR_CONCAT") { + const auto right = pop(), left = pop(); matches(right, "text"); matches(left, "text"); push({"text", {}}); + } else if (op == "NEW_ARRAY_LITERAL") { + const auto size = count(args[0], max_items, line); + for (std::size_t i = 0; i < size; ++i) matches(pop(), args[1]); + push({"array<" + args[1] + ">", {}}); + } else if (op == "GET_INDEX") { + matches(pop(), "i32"); const auto array = pop(); + const auto type = type_shape(array.type); + if (type.name != "array") reject(line, "indexing requires an admitted array"); + push({value_type(spelling(type.elements.front())), {}}); + } else if (op == "NEW_STRUCT") push({args[0], 0}); + else if (op == "SET_FIELD") { + const auto value = pop(); + if (state.stack.empty() || !state.stack.back().constructing) reject(line, "tuple mutation is not admitted"); + auto &target = state.stack.back(); const auto &fields = schemas.at(target.type).elements; + const auto index = count(args[0], max_items - 1, line); + if (index != *target.constructing || index >= fields.size()) reject(line, "tuple fields require ordered, single initialization"); + matches(value, spelling(fields[index])); + if (++*target.constructing == fields.size()) target.constructing.reset(); + } else if (op == "GET_FIELD") { + const auto value = pop(); const auto schema = schemas.find(value.type); + const auto index = count(args[0], max_items - 1, line); + if (schema == schemas.end() || index >= schema->second.elements.size()) reject(line, "field access requires an existing tuple position"); + push({value_type(spelling(schema->second.elements[index])), {}}); + } else if (op == "POP") (void)pop(); + else if (op == "RET") { + if (function.return_type != "void") matches(pop(), function.return_type); + if (!state.stack.empty()) reject(line, "return leaves values on the operand stack"); + continue; + } else if (op == "JMP" || op == "JMP_IF" || op == "JMP_IF_NOT") { + if (op != "JMP") matches(pop(), "bool"); + enqueue(labels.at(args[0]), state, line); + if (op == "JMP") continue; + } + enqueue(pc + 1, state, line); + } +} +} // namespace + +std::vector +validate_submission_ast(const ast_block_stmt &body, const ast_expr_ptr &value) { + try { ast_admission{}.validate(body, value); return {}; } + catch (const rejection &error) { return {{error.line, error.message, error.source_file}}; } +} +void validate_nil_submission_profile(const nil_module &module) { + try { nil_admission(module); } + catch (const rejection &error) { + throw std::runtime_error(error.message + (error.line > 0 ? " at line " + std::to_string(error.line) : "")); + } +} +} // namespace ny diff --git a/nilcompiler/src/submission_profile.hpp b/nilcompiler/src/submission_profile.hpp new file mode 100644 index 00000000..45776672 --- /dev/null +++ b/nilcompiler/src/submission_profile.hpp @@ -0,0 +1,26 @@ +#ifndef NY_COMPILER_SUBMISSION_PROFILE_HPP +#define NY_COMPILER_SUBMISSION_PROFILE_HPP + +#include "ast.hpp" +#include +#include + +namespace ny { +struct nil_module; +struct submission_diagnostic { + int line = 0; + std::string message; + std::string source_file; +}; + +// Admission for the initial pure submission profile, not an execution sandbox. +// The body and optional final expression share the outer lexical scope. Ordinary +// type checking must still succeed before generating and admitting NIL. +std::vector +validate_submission_ast(const ast_block_stmt &body, const ast_expr_ptr &value); + +// Independently inspect the complete generated artifact, including instructions +// that would be skipped at runtime. Throws std::runtime_error on rejection. +void validate_nil_submission_profile(const nil_module &module); +} // namespace ny +#endif diff --git a/nilcompiler/src/submission_request.cpp b/nilcompiler/src/submission_request.cpp new file mode 100644 index 00000000..016171bc --- /dev/null +++ b/nilcompiler/src/submission_request.cpp @@ -0,0 +1,298 @@ +#include "submission_request.hpp" + +#include "matrix_lexer.hpp" +#include "nildata.hpp" +#include "numeric_literal.hpp" +#include "../../common/strict_json.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace matrix { +namespace { +using nil::detail::json; +constexpr std::size_t max_source_bytes = 64 * 1024; +constexpr std::size_t max_ast_nodes = 4096; +constexpr unsigned max_expression_depth = 32; + +[[noreturn]] void fail(const std::string &path, const std::string &message) { + throw submission_request_error(path, message); +} + +std::string item_path(const std::string &path, std::size_t index) { + return path + "[" + std::to_string(index) + "]"; +} + +void fields(const json &node, const std::string &path, + std::initializer_list names) { + if (node.type != json::kind::object) fail(path, "expected an object"); + for (const auto &field : node.object) { + if (std::none_of(names.begin(), names.end(), [&](const char *name) { + return field.first == name; + })) + fail(path + "[" + nil::detail::quote(field.first) + "]", "unknown field"); + } + for (const auto *name : names) + if (!node.object.count(name)) fail(path + "." + name, "missing field"); +} + +const std::string &text(const json &node, const std::string &path) { + if (node.type != json::kind::string) fail(path, "expected text"); + return node.text; +} + +const std::vector &array(const json &node, const std::string &path) { + if (node.type != json::kind::array) fail(path, "expected an array"); + return node.array; +} + +// Native text cannot represent an embedded NUL. Reject it even in unknown +// fields, rather than letting a consumer see a truncated schema or name. +void reject_nul(const json &node, const std::string &path) { + if (node.type == json::kind::string && node.text.find('\0') != std::string::npos) + fail(path, "embedded NUL is not supported"); + for (std::size_t i = 0; i < node.array.size(); ++i) + reject_nul(node.array[i], item_path(path, i)); + for (const auto &entry : node.object) { + const auto child = path + "[" + nil::detail::quote(entry.first) + "]"; + if (entry.first.find('\0') != std::string::npos) + fail(child, "embedded NUL is not supported in field names"); + reject_nul(entry.second, child); + } +} + +std::string identifier(const json &node, const std::string &path) { + const auto &spelling = text(node, path); + lexer scanner(spelling); + const auto tokens = scanner.scan(); + if (scanner.has_errors() || tokens.size() != 2 || + tokens[0].kind != token_kind::identifier || + tokens[0].escaped_identifier || tokens[0].start != 0 || + tokens[0].length != spelling.size() || tokens[0].lexeme != spelling || + tokens[1].kind != token_kind::end_of_file) + fail(path, "expected one unescaped Matrix identifier"); + return spelling; +} + +class decoder { + std::size_t nodes_ = 0; + std::map symbols_; + + template + std::shared_ptr make(const std::string &path, Args &&...args) { + if (++nodes_ > max_ast_nodes) fail(path, "AST exceeds 4096 nodes"); + auto node = std::make_shared(std::forward(args)...); + node->source_file = path; + return node; + } + + ny::ast_expr_ptr negative(ny::ast_expr_ptr operand, const std::string &path) { + if (auto literal = std::dynamic_pointer_cast(operand)) { + if (const auto boundary = ny::negated_integer_boundary(literal->value)) { + literal->value = *boundary; + literal->source_file = path; + return literal; + } + } + return make(path, ny::token_kind::minus, std::move(operand)); + } + + ny::ast_expr_ptr number(const json &node, const std::string &path, + bool allow_minimum_magnitude, unsigned depth) { + fields(node, path, {"kind", "value"}); + const auto &spelling = text(node.at("value"), path + ".value"); + bool is_json_number = false; + try { + const auto parsed = nil::detail::json_parser(spelling).parse(); + is_json_number = parsed.type == json::kind::number && parsed.text == spelling; + } catch (const std::runtime_error &) { + // Replace parser offsets with the request field that owns the token. + } + if (!is_json_number) + fail(path + ".value", "expected an exact JSON numeric token as text"); + const bool negated = spelling.front() == '-'; + const auto magnitude = negated ? spelling.substr(1) : spelling; + if (ny::is_floating_literal_spelling(spelling)) { + double ignored = 0; + if (const auto error = ny::parse_floating_literal(spelling, ignored)) + fail(path + ".value", error); + } else { + ny::integer_literal_info info; + if (const auto error = ny::parse_integer_literal( + spelling, info, allow_minimum_magnitude)) + fail(path + ".value", error); + } + auto literal = make(path, magnitude); + if (!negated) return literal; + // Match Matrix unary parsing, including i32/i64 minimum-literal folding. + if (!ny::negated_integer_boundary(magnitude) && depth == max_expression_depth) + fail(path, "expression nesting exceeds 32 levels"); + return negative(std::move(literal), path); + } + + ny::ast_expr_ptr expression(const json &node, const std::string &path, + unsigned depth = 1, + bool allow_minimum_magnitude = false) { + if (depth > max_expression_depth) + fail(path, "expression nesting exceeds 32 levels"); + if (node.type != json::kind::object) fail(path, "expected an expression object"); + const auto tag = node.object.find("kind"); + if (tag == node.object.end()) fail(path + ".kind", "missing field"); + const auto &kind = text(tag->second, path + ".kind"); + if (kind == "number") + return number(node, path, allow_minimum_magnitude, depth); + if (kind == "text") { + fields(node, path, {"kind", "value"}); + return make(path, text(node.at("value"), path + ".value")); + } + if (kind == "boolean") { + fields(node, path, {"kind", "value"}); + if (node.at("value").type != json::kind::boolean) + fail(path + ".value", "expected a boolean"); + return make(path, node.at("value").boolean); + } + if (kind == "name") { + fields(node, path, {"kind", "name"}); + const auto spelling = identifier(node.at("name"), path + ".name"); + const auto resolved = symbols_.find(fold_key(spelling)); + return make(path, resolved == symbols_.end() + ? nil_symbol(spelling) : resolved->second); + } + if (kind == "unary") { + fields(node, path, {"kind", "operator", "operand"}); + const auto &op = text(node.at("operator"), path + ".operator"); + if (op != "negative" && op != "not" && op != "bitwise-not") + fail(path + ".operator", "unknown unary operator"); + auto operand = expression(node.at("operand"), path + ".operand", depth + 1, + op == "negative"); + if (op == "negative") return negative(std::move(operand), path); + return make(path, op == "not" ? ny::token_kind::not_kw + : ny::token_kind::tilde, + std::move(operand)); + } + if (kind == "binary") { + fields(node, path, {"kind", "operator", "left", "right"}); + static const std::map operations = { + {"plus", ny::token_kind::plus}, {"minus", ny::token_kind::minus}, + {"times", ny::token_kind::star}, {"divided-by", ny::token_kind::slash}, + {"modulo", ny::token_kind::percent}, {"equals", ny::token_kind::double_equal}, + {"not-equals", ny::token_kind::not_equal}, + {"less-than", ny::token_kind::less}, {"less-or-equal", ny::token_kind::less_equal}, + {"greater-than", ny::token_kind::greater}, {"greater-or-equal", ny::token_kind::greater_equal}, + {"and", ny::token_kind::amp_amp}, {"or", ny::token_kind::pipe_pipe}, + {"bitwise-and", ny::token_kind::amp}, {"bitwise-or", ny::token_kind::pipe}, + {"bitwise-xor", ny::token_kind::caret}, + {"shift-left", ny::token_kind::less_less}, {"shift-right", ny::token_kind::greater_greater}}; + const auto &op = text(node.at("operator"), path + ".operator"); + const auto found = operations.find(op); + if (found == operations.end()) fail(path + ".operator", "unknown binary operator"); + auto left = expression(node.at("left"), path + ".left", depth + 1); + auto right = expression(node.at("right"), path + ".right", depth + 1); + return make(path, std::move(left), found->second, std::move(right)); + } + if (kind == "tuple" || kind == "array") { + fields(node, path, {"kind", "items"}); + const auto &items = array(node.at("items"), path + ".items"); + if (kind == "tuple") { + if (items.empty()) fail(path + ".items", "a tuple requires at least one element"); + std::vector> members; + for (std::size_t i = 0; i < items.size(); ++i) + members.emplace_back(std::to_string(i), + expression(items[i], item_path(path + ".items", i), depth + 1)); + auto result = make(path, "tuple", std::move(members)); + result->tuple_literal = true; + return result; + } + std::vector elements; + for (std::size_t i = 0; i < items.size(); ++i) + elements.push_back(expression(items[i], item_path(path + ".items", i), depth + 1)); + return make(path, std::move(elements)); + } + if (kind == "index") { + fields(node, path, {"kind", "target", "index"}); + auto target = expression(node.at("target"), path + ".target", depth + 1); + auto index = expression(node.at("index"), path + ".index", depth + 1); + return make(path, std::move(target), std::move(index)); + } + if (kind == "member") { + fields(node, path, {"kind", "target", "index"}); + const auto &index = text(node.at("index"), path + ".index"); + std::int64_t ignored = 0; + const auto converted = std::from_chars(index.data(), index.data() + index.size(), ignored); + if (index.empty() || index.front() < '0' || index.front() > '9' || + (index.size() > 1 && index.front() == '0') || + converted.ec != std::errc{} || converted.ptr != index.data() + index.size()) + fail(path + ".index", "expected a canonical nonnegative i64 tuple position as text"); + auto target = expression(node.at("target"), path + ".target", depth + 1); + return make(path, std::move(target), index); + } + if (kind == "cast") { + fields(node, path, {"kind", "value", "type"}); + const auto &type = text(node.at("type"), path + ".type"); + if (type != "bool" && type != "i32" && type != "i64" && type != "u8" && type != "f64") + fail(path + ".type", "expected a supported canonical primitive type"); + auto value = expression(node.at("value"), path + ".value", depth + 1); + return make(path, std::move(value), type); + } + if (kind == "conditional") { + fields(node, path, {"kind", "condition", "then", "otherwise"}); + auto condition = expression(node.at("condition"), path + ".condition", depth + 1); + auto then = expression(node.at("then"), path + ".then", depth + 1); + auto otherwise = expression(node.at("otherwise"), path + ".otherwise", depth + 1); + return make(path, std::move(condition), std::move(then), std::move(otherwise)); + } + fail(path + ".kind", "unknown expression kind " + nil::detail::quote(kind)); + } + +public: + decoded_submission_request decode(const json &root) { + reject_nul(root, "$"); + fields(root, "$", {"schema", "profile", "bindings", "value"}); + if (text(root.at("schema"), "$.schema") != "nil.matrix.submission-request.v1") + fail("$.schema", "unsupported submission request schema"); + if (text(root.at("profile"), "$.profile") != "matrix.pure.v1") + fail("$.profile", "unsupported submission profile"); + const auto &bindings = array(root.at("bindings"), "$.bindings"); + // Match Matrix's declaration spelling table before resolving references. + std::vector names; + for (std::size_t i = 0; i < bindings.size(); ++i) { + const auto path = item_path("$.bindings", i); + fields(bindings[i], path, {"name", "value"}); + const auto spelling = identifier(bindings[i].at("name"), path + ".name"); + names.push_back(nil_symbol(spelling)); + if (!symbols_.emplace(fold_key(spelling), names.back()).second) + fail(path + ".name", "duplicate binding after Matrix name normalization"); + } + decoded_submission_request result; + result.body = make("$.bindings"); + for (std::size_t i = 0; i < bindings.size(); ++i) { + const auto path = item_path("$.bindings", i); + auto value = expression(bindings[i].at("value"), path + ".value"); + auto declaration = make(path, names[i], std::move(value)); + result.body->statements.push_back(make(path, std::move(declaration))); + } + if (root.at("value").type != json::kind::null) + result.value = expression(root.at("value"), "$.value"); + return result; + } +}; +} // namespace + +decoded_submission_request decode_submission_request(const std::string &source) { + if (source.size() > max_source_bytes) fail("$", "request exceeds 64 KiB"); + if (source.find('\0') != std::string::npos) fail("$", "embedded NUL is not supported"); + json root; + try { + const auto encoded = nil::data::to_json(source); + root = nil::detail::json_parser(encoded).parse(); + } catch (const std::runtime_error &error) { + fail("$", error.what()); + } + return decoder{}.decode(root); +} +} // namespace matrix diff --git a/nilcompiler/src/submission_request.hpp b/nilcompiler/src/submission_request.hpp new file mode 100644 index 00000000..bb8f05ad --- /dev/null +++ b/nilcompiler/src/submission_request.hpp @@ -0,0 +1,34 @@ +#ifndef NIL_MATRIX_SUBMISSION_REQUEST_HPP +#define NIL_MATRIX_SUBMISSION_REQUEST_HPP + +#include "ast.hpp" +#include +#include +#include + +namespace matrix { + +struct decoded_submission_request { + std::shared_ptr body; + ny::ast_expr_ptr value; // null for a void submission +}; + +struct submission_request_error : std::runtime_error { + std::string path; + submission_request_error(const std::string &location, const std::string &message) + : std::runtime_error(location + ": " + message), path(location) {} +}; + +// Decode nil.matrix.submission-request.v1, carried by a versioned NILData +// document, directly to the shared AST. This grants no authority and performs +// no execution. Ordinary type checking and matrix.pure.v1 admission remain +// mandatory. Schema errors throw submission_request_error with a request path. +// +// Limits: 64 KiB input, 4096 constructed AST nodes and expression depth 32. +// NILData's own document nesting limit also applies. Names are one unescaped +// Matrix identifier, with ordinary Matrix case/separator-folded lookup. A node's +// source_file is its request path; line 0 denotes the absence of source lines. +decoded_submission_request decode_submission_request(const std::string &source); + +} // namespace matrix +#endif diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 0b49b219..022bc74b 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -3679,6 +3679,7 @@ void type_checker::visit(ast_if_stmt &s) { } void type_checker::visit(ast_member_access_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); // std::cerr << "[type_checker] visit(member_access) member='" << // e.member_name << "'" << std::endl; Check if object is a type (e.g. Enum // name) @@ -3783,6 +3784,7 @@ void type_checker::visit(ast_member_access_expr &e) { } void type_checker::visit(ast_struct_literal_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); if (e.tuple_literal) { const auto before = diagnostics_.size(); std::string type = "tuple<"; @@ -6010,6 +6012,7 @@ void type_checker::visit(ast_call_expr &e) { } void type_checker::visit(ast_binary_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); if (e.left) e.left->accept(*this); type_info left_type = last_expr_type_.value_or(type_unknown); @@ -6121,6 +6124,7 @@ void type_checker::visit(ast_binary_expr &e) { } void type_checker::visit(ast_cast_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); e.checked_identity = false; if (e.operand) e.operand->accept(*this); @@ -6216,6 +6220,7 @@ bool type_checker::check_reference_handle(ast_expr &reference, ast_expr &operand } void type_checker::visit(ast_unary_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); if (e.operand) e.operand->accept(*this); @@ -6521,6 +6526,7 @@ void type_checker::visit(ast_assignment_expr &e) { } void type_checker::visit(ast_identifier_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); capture_completion(e); e.resolved_global_name.reset(); e.checked_callable_parameters.reset(); @@ -6843,11 +6849,13 @@ void type_checker::visit(ast_identifier_expr &e) { } void type_checker::visit(ast_string_literal &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); last_expr_type_ = type_string; e.inferred_type = last_expr_type_->name; } void type_checker::visit(ast_number_literal &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); if (is_floating_literal_spelling(e.value)) { last_expr_type_ = type_f64; } else { @@ -6864,6 +6872,7 @@ void type_checker::visit(ast_number_literal &e) { } void type_checker::visit(ast_char_literal &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); last_expr_type_ = resolve_type("u8"); e.inferred_type = last_expr_type_->name; } @@ -7141,6 +7150,7 @@ void type_checker::visit(ast_query_expr &e) { } void type_checker::visit(ast_array_literal_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); if (e.inferred_type) { const auto context_type = resolve_type(*e.inferred_type); const auto context = parse_generic_type_string(context_type.name); @@ -7213,6 +7223,7 @@ void type_checker::visit(ast_array_literal_expr &e) { } void type_checker::visit(ast_index_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); e.object->accept(*this); type_info obj_type = last_expr_type_.value_or(type_unknown); @@ -9057,6 +9068,7 @@ void type_checker::visit(ast_hotreload_expr &e) { } void type_checker::visit(ast_if_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); // Conditions and both value arms are checked, even when the condition is a // constant. A dead arm cannot silently turn an unrelated value into zero. if (e.condition) { @@ -9208,6 +9220,7 @@ void type_checker::validate_scalar_text_calls() { } void type_checker::visit(ast_interpolated_string_expr &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); for (const auto &part : e.parts) { if (!part.is_literal && part.expression) { part.expression->accept(*this); @@ -9230,6 +9243,7 @@ void type_checker::visit(ast_interpolated_string_expr &e) { } void type_checker::visit(ast_boolean_literal &e) { + diagnostic_source_scope source_scope(diagnostic_source_file_, e.source_file); last_expr_type_ = type_bool; e.inferred_type = "bool"; } diff --git a/tests/matrix_submission_contract.py b/tests/matrix_submission_contract.py new file mode 100644 index 00000000..4bb0d414 --- /dev/null +++ b/tests/matrix_submission_contract.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +"""CLI admission contract: check Matrix/NILData without executing a program.""" +import argparse +import json +import os +import re +from pathlib import Path +import subprocess +import tempfile + + +def nildata(value): + def lines(item, prefix="", indent=""): + if isinstance(item, (dict, list)): + kind = "object" if isinstance(item, dict) else "array" + out = [indent + prefix + ("an " if prefix else "") + kind] + entries = item.items() if isinstance(item, dict) else ((None, v) for v in item) + for key, child in entries: + name = "item" if key is None else json.dumps(key) + out += lines(child, name + " is ", indent + " ") + return out + [indent + "end " + kind] + return [indent + prefix + json.dumps(item, ensure_ascii=False)] + return "nildata 1\n" + "\n".join(lines(value)) + "\n" + + +def number(value): + return {"kind": "number", "value": str(value)} + + +def name(value): + return {"kind": "name", "name": value} + + +def binary(op, left, right): + return {"kind": "binary", "operator": op, "left": left, "right": right} + + +def envelope(value, bindings=()): + return {"schema": "nil.matrix.submission-request.v1", "profile": "matrix.pure.v1", + "bindings": [{"name": key, "value": val} for key, val in bindings], "value": value} + + +def instructions(text): + # Matrix and request nodes have different source locations. Retain every + # operation/schema/constant while ignoring textual source-line comments. + return "\n".join(re.sub(r"\s+; line [0-9]+$", "", line).rstrip() + for line in text.splitlines()) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--compiler", required=True) + compiler = str(Path(parser.parse_args().compiler).resolve()) + checks = 0 + with tempfile.TemporaryDirectory(prefix="matrix-submission-") as temporary: + work = Path(temporary) + + def run(source=b"", *, request=False, status="complete", result_type=None, path="-"): + nonlocal checks + if isinstance(source, str): + source = source.encode() + option = "--check-submission-request" if request else "--check-submission" + result = subprocess.run([compiler, option, str(path)], input=source, + cwd=work, capture_output=True, timeout=10) + assert result.stderr == b"", (source, result.stderr) + report = json.loads(result.stdout) + assert report["schema"] == "nil.matrix.submission-check.v1", report + assert report["profile"] == "matrix.pure.v1", report + assert report["input_kind"] == ("nildata-request" if request else "matrix"), report + assert report["executed"] is False, report + assert report["status"] == status, (source, report) + assert result.returncode == {"complete": 0, "incomplete": 2, "invalid": 1}[status], report + if status == "complete": + assert not report["diagnostics"] and report["nil"] and report["instruction_count"] > 0, report + if result_type is not None: + assert report["result_type"] == result_type, report + else: + assert report["nil"] is None and report["result_type"] is None, report + assert report["diagnostics"], report + checks += 1 + return report + + # These would fail or have effects if the checker ran their generated NIL. + run("1 over 0", result_type="i32") + run("[1, 2] at 1000", result_type="i32") + for source, expected in [ + ("", "void"), ("!!! comment only\n", "void"), + ("42", "i32"), ("2147483648", "i64"), ("negative 1.6", "f64"), ("-2147483648", "i32"), + ("-9223372036854775808", "i64"), ("true and false", "bool"), + ('"hello"', "text"), ("value amount is 40\namount plus 2", "i32"), + ("value Amount is 2\nAMOUNT times 3", "i32"), + ("value amount is 2\n", "void"), ("[1, 2, 3]", "array"), + ("value (Frame-Count, other) is (1, 2)\nFRAME_COUNT", "i32"), + ('value amount is 2\nformatted "amount: {amount}"', "text"), + ("(when true give 1 otherwise give 2 end when)", "i32"), + ("when true then\nvalue amount is 1\nend when", "void"), + ("1 becomes floating", "f64"), + ]: + run(source, result_type=expected) + + for source in ["1 plus", "value answer is", '"unfinished', + "when true then\nvalue x is 1\n", "[1,", "(1,"]: + run(source, status="incomplete") + for source in ["1 2", "value x is 1\nvalue X is 2\nx", "unknown_name plus 1", + "-9223372036854775809", "1 plus true"]: + run(source, status="invalid") + for source in ['say "host output"', "evaluate dangerous with 1", + "variable x is 1", "value x is 1\nset x to 2", + "while true\nend while", "book demo", "use nil.std.io", + 'when false then\nsay "dead effect"\nend when']: + run(source, status="invalid") + + pairs = [ + ("40 plus 2", envelope(binary("plus", number(40), number(2)))), + ("value amount is 40\namount plus 2", + envelope(binary("plus", name("amount"), number(2)), [("amount", number(40))])), + ("negative 1.6", envelope(number("-1.6"))), + ("-2147483648", envelope(number("-2147483648"))), + ("-9223372036854775808", envelope(number("-9223372036854775808"))), + ('"hello"', envelope({"kind": "text", "value": "hello"})), + ("[1, 2] at 0", envelope({"kind": "index", "target": { + "kind": "array", "items": [number(1), number(2)]}, "index": number(0)})), + ("(1, true)", envelope({"kind": "tuple", "items": [number(1), + {"kind": "boolean", "value": True}]})), + ("(1, true).0", envelope({"kind": "member", "target": { + "kind": "tuple", "items": [number(1), {"kind": "boolean", "value": True}]}, "index": "0"})), + ("1 becomes floating", envelope({"kind": "cast", "value": number(1), "type": "f64"})), + ("(when true give 1 otherwise give 2 end when)", envelope({ + "kind": "conditional", "condition": {"kind": "boolean", "value": True}, + "then": number(1), "otherwise": number(2)})), + ("bitwise not 1", envelope({"kind": "unary", "operator": "bitwise-not", "operand": number(1)})), + ("", envelope(None)), + ] + for source, request in pairs: + human = run(source) + machine = run(nildata(request), request=True) + assert instructions(human["nil"]) == instructions(machine["nil"]), (source, human, machine) + assert human["result_type"] == machine["result_type"], (human, machine) + + bad = envelope(number(1)) + bad["authority"] = "root" + report = run(nildata(bad), request=True, status="invalid") + assert report["diagnostics"][0]["location"] == '$["authority"]', report + bad = envelope({"kind": "call", "name": "execute"}) + run(nildata(bad), request=True, status="invalid") + bad = envelope(number(1)) + bad["profile"] = "matrix.unrestricted" + run(nildata(bad), request=True, status="invalid") + report = run(nildata(envelope({"kind": "array", "items": [ + binary("plus", number(1), {"kind": "boolean", "value": True})]})), + request=True, status="invalid") + assert report["diagnostics"][0]["stage"] == "type", report + assert report["diagnostics"][0]["location"] == "$.value.items[0]", report + report = run(nildata(envelope(name("missing"))), request=True, status="invalid") + assert report["diagnostics"][0]["location"] == "$.value", report + + for source in [b"\xff", b"1\0", b"1\x1a invalid suffix", b"#" + b"x" * 65536, + b"(" * 80 + b"1" + b")" * 80, + b"1" + b" plus 1" * 3000]: + run(source, status="invalid") + for source in [b"\xff", b"nildata 1\nnull\0", b" " * 65537]: + run(source, request=True, status="invalid") + + source_file = work / "input.mat" + source_file.write_text("1 plus 2") + run(path=source_file, result_type="i32") + run(path=work, status="invalid") + run(path=work / "missing", status="invalid") + if os.name == "posix": + link = work / "linked.mat" + link.symlink_to(source_file) + run(path=link, status="invalid") + fifo = work / "fifo.mat" + os.mkfifo(fifo) + run(path=fifo, status="invalid") + + # Compilation switches cannot weaken or redirect the admission command. + sentinel = work / "untouched.nil" + sentinel.write_text("sentinel") + for extra in [["--no-typecheck"], ["--native"], ["--jit"], + ["--output", str(sentinel)], ["--sdk-path", str(work)], + ["--check-submission-request", "-"]]: + result = subprocess.run([compiler, "--check-submission", "-", *extra], + input=b"1", cwd=work, capture_output=True, timeout=10) + assert result.returncode != 0, (extra, result) + assert sentinel.read_text() == "sentinel" + checks += 1 + assert sorted(p.name for p in work.iterdir()) == sorted([ + "input.mat", "untouched.nil", *(["linked.mat", "fifo.mat"] if os.name == "posix" else [])]) + print(f"Matrix submission CLI: {checks} checks passed") + + +if __name__ == "__main__": + main() diff --git a/tests/matrix_submission_parser_tests.cpp b/tests/matrix_submission_parser_tests.cpp new file mode 100644 index 00000000..62a9b54e --- /dev/null +++ b/tests/matrix_submission_parser_tests.cpp @@ -0,0 +1,209 @@ +#include "matrix_parser.hpp" +#include "formatted_text.hpp" + +#include +#include +#include + +namespace { +using matrix::submission_state; + +void require(bool condition, const std::string &message) { + if (!condition) throw std::runtime_error(message); +} + +matrix::submission_parse_result parse(const std::string &source, + submission_state expected = submission_state::complete) { + matrix::parser_options options; + options.filename = "submission.matrix"; + options.submission = true; + matrix::parser parser(source, options); + auto result = parser.parse_submission(); + if (result.state != expected) { + std::cerr << "Source: " << source.substr(0, 300) << '\n'; + for (const auto &diagnostic : result.diagnostics) + std::cerr << diagnostic.primary.line << ':' << diagnostic.primary.column + << ": " << diagnostic.message << '\n'; + } + require(result.state == expected, "unexpected submission state"); + if (expected == submission_state::complete) { + require(result.body && result.diagnostics.empty(), "complete submission has a body and no diagnostics"); + } else { + require(!result.body && !result.value && !result.diagnostics.empty(), + "unfinished or invalid input must not expose a partial executable AST"); + } + return result; +} + +template +std::shared_ptr cast(const std::shared_ptr &node) { + auto result = std::dynamic_pointer_cast(node); + require(result != nullptr, "unexpected AST node"); + return result; +} + +void values_and_statements() { + for (const auto *source : {"", " \t\r\n", "!!! an empty submission\n", "; ."}) { + const auto result = parse(source); + require(result.body->statements.empty() && !result.value, "empty submission is void"); + } + const auto arithmetic = cast(parse("1 plus 2 times 3").value); + require(arithmetic->op == ny::token_kind::plus && + cast(arithmetic->right)->op == ny::token_kind::star, + "ordinary Matrix operator precedence is preserved"); + const auto source = std::string("!!! café\r\nvalue Sensor-Reading is 7\r\nSENSOR_reading plus 1"); + const auto result = parse(source); + require(result.body->statements.size() == 1 && result.body->source_file == "submission.matrix", + "local binding and final value share the original submission"); + const auto declaration = cast( + cast(result.body->statements[0])->declaration); + const auto reference = cast(cast(result.value)->left); + require(declaration->name == "Sensor_Reading" && reference->name == declaration->name, + "local references fold case and separators"); + require(declaration->line == 2 && reference->line == 3 && declaration->name_span && reference->name_span, + "submission lines and editable spans are retained"); + require(source.substr(declaration->name_span->start, declaration->name_span->length) == "Sensor-Reading" && + source.substr(reference->name_span->start, reference->name_span->length) == "SENSOR_reading", + "source spans use original UTF-8 bytes, without a synthetic wrapper"); + const auto shadow = parse("value sample is 1\nwhen true then\n value SAMPLE is 2\nend when\nsample"); + const auto conditional = cast(shadow.body->statements[1]); + const auto inner = cast(cast( + cast(conditional->then_branch)->statements[0])->declaration); + require(inner->name == "sample", "shadowing declarations and references share their folded symbol"); + const auto tuple = parse("value (Frame-Count, other) is (1, 2)\nFRAME_COUNT"); + const auto destructuring = cast( + cast(tuple.body->statements[0])->declaration); + require(destructuring->tuple_bindings[0]->name == "Frame_Count" && + cast(tuple.value)->name == "Frame_Count", + "tuple destructuring records folded local names"); + const auto duplicate = parse("value sample is 1\nvalue SAMPLE is 2"); + require(cast(cast(duplicate.body->statements[1])->declaration)->name == "sample", + "same-scope folded duplicates reach shared duplicate-binding checks"); + parse("value rows is [(\"renderer\", 3), (\"desktop\", 0)]\n" + "collect begin query\nfrom each row in rows\nwhere row.1 is greater than 0\n" + "order by row.1 descending\ngive row.0\nend query"); + const auto call_source = std::string("status with vessel-name being \"renderer\", verbose being true"); + const auto call = cast(parse(call_source).value); + require(call->argument_names.size() == 2 && call->argument_names[0] == "vessel-name" && + call->argument_span && call->argument_span->start == call_source.find("with") + 4, + "named arguments and their original spans survive"); + parse("when true give 1 otherwise give 2 end when"); + parse("(when true then give 1 otherwise give 2 end when)"); + parse("(consider 1 when 1 give 2 otherwise give 3 end consider)"); + // Parse effects with the ordinary grammar; the separate profile validates them. + parse("variable x is 1\nset x to 2\nsay x\nevaluate status with nothing"); + parse("repeat while false\nsay 1\nend repeat"); + parse("attempt\nsay 1\ncaught anything as problem\nsay 2\nend attempt"); + for (const auto *source : {"1\n2", "1; say 2", "1\nvalue x is 2", "1 plus )", "value is 1"}) + parse(source, submission_state::invalid); +} + +void text_and_interpolation() { + require(cast(parse("\"C:\\dir\\file\"").value)->value == "C:\\dir\\file", + "quoted Matrix text is raw"); + require(cast(parse("begin text\n hello \"world\"\n C:\\dir\nend text\n").value)->value == + "hello \"world\"\nC:\\dir", "raw blocks use existing dedentation"); + const auto source = std::string("!!! λ\nvalue frame-count is 3\nformatted \"count {FRAME_COUNT plus 1} {{literal}}\""); + const auto formatted = cast(parse(source).value); + const auto reference = cast(cast(formatted->parts[1].expression)->left); + require(reference->line == 3 && reference->name_span && + source.substr(reference->name_span->start, reference->name_span->length) == "FRAME_COUNT", + "formatted expressions preserve original byte ranges"); + parse("formatted \"outer {formatted \"inner {1 plus 2}\"}\""); + for (const auto *source : {"\"unfinished", "`unfinished", "begin text\nhello", "formatted \"unfinished", + "formatted \"{1 plus", "formatted \"{\"unfinished", "formatted \"{0x", + "formatted \"{formatted \"nested {1"}) + parse(source, submission_state::incomplete); + for (const auto *source : {"\"unfinished\n", "`unfinished\n", "formatted \"line\nbreak\"", + "formatted \"{}\"", "formatted \"bad }", "formatted \"{1 plus }\"", + "formatted \"{1 @", "formatted \"{1 plus )", "formatted \"{0x}\"", + "value is 1\n\"unfinished", "value x is )\nformatted \"unfinished"}) + parse(source, submission_state::invalid); + + // Shared formatted scanning keeps full-page Ny/Matrix success/error behavior. + for (bool matrix : {false, true}) { + const auto valid = ny::scan_formatted_text("\"a {1 plus 2} {{b}}\"", 0, matrix); + require(valid.error.empty() && !valid.incomplete && valid.pieces.size() == 3, + "complete formatted scanner behavior is unchanged"); + const auto unfinished = ny::scan_formatted_text("\"a {1", 0, matrix); + require(!unfinished.error.empty() && unfinished.incomplete, "EOF status is structured"); + const auto bad = ny::scan_formatted_text("\"a }", 0, matrix); + require(!bad.error.empty() && !bad.incomplete, "invalid brace is never a continuation"); + } + matrix::parser page("book format\nmain begin paragraph\nsay formatted \"{1 plus 2}\"\nend paragraph\n"); + require(page.parse_program() && !page.has_errors(), "normal Matrix page still parses"); + matrix::parser malformed_page("book format\nmain begin paragraph\nsay formatted \"{1"); + malformed_page.parse_program(); + require(malformed_page.has_errors(), "normal Matrix page rejects unfinished formatting"); +} + +void continuations_and_rejections() { + for (const auto *source : {"value", "value total", "value total is", "value total as array of", + "1 plus", "negative", "not", "bitwise", "1 bitwise", "1 does not", + "1 is", "1 is less", "1 shifted", "1 shifted right", "1 shifted right by", + "(", "[1,", "call with", "call with arg being", "the length of", "reference", "now", + "when true", "when true then", "when true then\nsay 1\nend", + "repeat", "repeat forever", "repeat forever\nend", "attempt\nsay 1", + "consider 1\nwhen 1 then\nsay 2\nend", "0x", "1e", "1e-", + "(when true give 1 otherwise give 2 end"}) + parse(source, submission_state::incomplete); + for (const auto *source : {"book test", "library test", "read nil.std.core", "cite nil.std.core", + "helper begin paragraph\nend paragraph", "Point begin record\nend record", + "helper of type T returns T begin paragraph\nend paragraph", + "pattern-name begin pattern\nend pattern", "note intrinsic \"unsafe\"", + "repeat forever\nread nil.std.core\nend repeat", "end", "1 is bogus", + "1 shifted sideways", "1 does wrong", "1 plus )", "[1,)", + "when true then\nvalue is 1", "repeat forever\nend when", + "(when true give 1 otherwise give 2 end)", "0xg", "1e9999"}) + parse(source, submission_state::invalid); + const auto incomplete = parse("value answer is\n", submission_state::incomplete); + require(incomplete.diagnostics.back().primary.line == 2 && + incomplete.diagnostics.back().primary.column == 1, + "missing operands point to the original EOF location"); + const auto invalid = parse("\nvalue is 1", submission_state::invalid); + require(invalid.diagnostics.front().primary.line == 2 && + invalid.diagnostics.front().primary.column == 7, + "malformed earlier tokens retain original diagnostic columns"); +} + +void integer_boundaries_and_limits() { + for (const auto *source : {"9223372036854775807", "-9223372036854775808", "negative 9223372036854775808", + "minus 9223372036854775808", "-0x8000000000000000", "-1.6"}) + parse(source); + for (const auto *source : {"9223372036854775808", "-9223372036854775809", "0x8000000000000000", + "value x is 9223372036854775808\n1 plus", "9223372036854775808 plus"}) + parse(source, submission_state::invalid); + parse(std::string("!!!") + std::string(matrix::submission_source_limit - 3, ' ')); + parse(std::string(matrix::submission_source_limit + 1, ' '), submission_state::invalid); + parse(std::string(matrix::submission_token_limit, ';')); + parse(std::string(matrix::submission_token_limit + 1, ';'), submission_state::invalid); + parse(std::string(63, '(') + "1" + std::string(63, ')')); + parse(std::string(64, '(') + "1" + std::string(64, ')'), submission_state::invalid); + std::string unary, type, blocks, reference; + for (int i = 0; i < 70; ++i) { + unary += "negative "; type += "array of "; blocks += "repeat forever\n"; + reference += "reference to "; + } + parse(unary + "1", submission_state::invalid); + parse("value x as " + type + "number is []", submission_state::invalid); + parse(blocks, submission_state::invalid); + parse(reference + "x", submission_state::invalid); + // Normal full pages retain their previous unbounded nesting behavior. + matrix::parser page("book depth\nmain begin paragraph\nsay " + std::string(70, '(') + "1" + + std::string(70, ')') + "\nend paragraph\n"); + require(page.parse_program() && !page.has_errors(), "submission limits do not alter page parsing"); +} +} // namespace + +int main() { + try { + values_and_statements(); + text_and_interpolation(); + continuations_and_rejections(); + integer_boundaries_and_limits(); + std::cout << "Matrix submission parser tests passed\n"; + } catch (const std::exception &error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/submission_profile_tests.cpp b/tests/submission_profile_tests.cpp new file mode 100644 index 00000000..10e5a124 --- /dev/null +++ b/tests/submission_profile_tests.cpp @@ -0,0 +1,210 @@ +#include "submission_profile.hpp" +#include "codegen.hpp" +#include +#include +#include + +namespace { +using namespace ny; +int failures = 0, checks = 0; +using body = std::vector; +void expect(const std::string &name, bool actual, bool expected) { + ++checks; + if (actual != expected) { ++failures; std::cerr << "FAIL " << name << '\n'; } +} +nil_module module(body instructions = {{"PUSH_CONST", {"3"}}, {"CAST", {"i32"}}, {"RET", {}}}, std::string result = "i32") { + nil_module value; + value.module_name = "root"; + nil_function function; + function.name = "__nil_submission"; + function.return_type = std::move(result); + function.body = std::move(instructions); + value.functions.push_back(std::move(function)); + return value; +} +bool admitted(const nil_module &value, bool verbose = false) { + try { validate_nil_submission_profile(value); return true; } + catch (const std::runtime_error &error) { if (verbose) std::cerr << error.what() << '\n'; return false; } +} +void nil_case(const std::string &name, const nil_module &value, bool accepted) { + expect(name, admitted(value, accepted), accepted); +} +void mutation(const std::string &name, const std::function &change) { + auto value = module(); change(value); nil_case(name, value, false); +} +ast_expr_ptr number(std::string value = "1") { return std::make_shared(std::move(value), 7); } +ast_expr_ptr call() { return std::make_shared(std::make_shared("effect")); } +ast_stmt_ptr local(const std::string &name, ast_expr_ptr value, bool mutable_value = false) { + return std::make_shared(std::make_shared(name, std::move(value), std::nullopt, mutable_value)); +} +void ast_case(const std::string &name, const std::vector &statements, ast_expr_ptr value, bool accepted) { + ast_block_stmt block; block.statements = statements; + expect(name, validate_submission_ast(block, value).empty(), accepted); +} +} +int main() { + using namespace ny; + nil_case("scalar", module(), true); + nil_case("void", module({{"RET", {}}}, "void"), true); + nil_case("typed arithmetic", module({{"PUSH_CONST", {"2"}}, {"PUSH_CONST", {"3"}}, {"ADD", {"i32"}}, {"RET", {}}}), true); + nil_case("float arithmetic", module({{"PUSH_CONST", {"2.5"}}, {"NEG", {"f64"}}, {"RET", {}}}, "f64"), true); + nil_case("local", module({{"PUSH_CONST", {"2"}}, {"STORE_LOCAL", {"x"}}, {"LOAD_LOCAL", {"x"}}, {"RET", {}}}), true); + nil_case("array index", module({{"PUSH_CONST", {"2"}}, {"PUSH_CONST", {"3"}}, {"NEW_ARRAY_LITERAL", {"2","i32"}}, + {"STORE_LOCAL", {"values"}}, {"LOAD_LOCAL", {"values"}}, {"PUSH_CONST", {"0"}}, {"GET_INDEX", {}}, {"RET", {}}}), true); + nil_case("empty concrete array", module({{"NEW_ARRAY_LITERAL", {"0","i32"}}, {"RET", {}}}, "array"), true); + auto text = module({{"PUSH_CONST_STR", {"S1"}}, {"PUSH_CONST", {"42"}}, {"TO_STRING", {"i32"}}, {"STR_CONCAT", {}}, {"RET", {}}}, "text"); + text.string_constants.emplace_back("S1", "literal CALL external\n# safe data"); + nil_case("formatted text", text, true); + auto tuple = module({{"NEW_STRUCT", {"tuple"}}, {"PUSH_CONST", {"2"}}, {"CAST", {"i32"}}, {"SET_FIELD", {"0"}}, + {"PUSH_CONST_STR", {"S1"}}, {"SET_FIELD", {"1"}}, {"RET", {}}}, "tuple"); + tuple.string_constants.emplace_back("S1", "text"); + tuple.structs.push_back({"tuple", {{"0","i32"},{"1","text"}}, {"@nil_tuple"}}); + nil_case("fresh tuple", tuple, true); + auto tuple_field = tuple; tuple_field.functions[0].body.pop_back(); + tuple_field.functions[0].body.insert(tuple_field.functions[0].body.end(), {{"STORE_LOCAL", {"tuple"}}, {"LOAD_LOCAL", {"tuple"}}, {"GET_FIELD", {"1"}}, {"RET", {}}}); + tuple_field.functions[0].return_type = "text"; + nil_case("immutable tuple field", tuple_field, true); + auto nested = module({{"NEW_STRUCT", {"tuple>"}}}, "tuple>"); + nested.structs = tuple.structs; nested.structs.push_back({"tuple>", {{"0","tuple"}}, {"@nil_tuple"}}); + nested.string_constants = tuple.string_constants; + auto &nested_body = nested.functions[0].body; + nested_body.insert(nested_body.end(), tuple.functions[0].body.begin(), tuple.functions[0].body.end()-1); + nested_body.insert(nested_body.end(), {{"SET_FIELD", {"0"}}, {"RET", {}}}); + nil_case("nested fresh tuple", nested, true); + auto conditional = module({{"PUSH_CONST", {"1"}}, {"JMP_IF_NOT", {"else"}}, {"PUSH_CONST", {"2"}}, + {"STORE_LOCAL", {"result"}}, {"JMP", {"end"}}, {"LABEL", {"else"}}, {"PUSH_CONST", {"3"}}, + {"STORE_LOCAL", {"result"}}, {"LABEL", {"end"}}, {"LOAD_LOCAL", {"result"}}, {"RET", {}}}); + nil_case("branch-specific immutable result", conditional, true); + + for (const auto &opcode : {"CALL", "CALL_METHOD", "CALL_INDIRECT", "PUSH_FN_PTR", "INTEROP_CALL", "INLINE_ASM", + "CONSOLE_WRITE", "TIME_NOW", "ALLOC", "READ_PTR", "WRITE_PTR", "PTR_ADD", "REF_LOCAL", "OWN_ALLOC", + "STORE_GLOBAL", "LOAD_GLOBAL", "PARALLEL_MAP", "NEW_VARIANT", "ARRAY_PUSH", "SET_INDEX", "FAULT_RAISE", "UNKNOWN", "push_const"}) { + mutation(std::string("forbidden ") + opcode, [&](auto &value) { value.functions[0].body.insert(value.functions[0].body.begin(), {opcode, {}}); }); + mutation(std::string("dead forbidden ") + opcode, [&](auto &value) { value.functions[0].body.push_back({opcode, {}}); }); + } + mutation("extra function", [](auto &value) { value.functions.push_back(value.functions[0]); }); + mutation("wrong function", [](auto &value) { value.functions[0].name = "main"; }); + mutation("forged module", [](auto &value) { value.module_name = "outside"; }); + mutation("library", [](auto &value) { value.is_library = true; }); + mutation("dependency", [](auto &value) { value.dependencies.push_back("host"); }); + mutation("embedded source", [](auto &value) { value.embedded_sources.push_back({"evil.ny", "effect()"}); }); + mutation("class", [](auto &value) { value.classes.push_back({}); }); + mutation("enum", [](auto &value) { value.enums.push_back({}); }); + mutation("tests metadata", [](auto &value) { value.tests.push_back("__nil_submission"); }); + mutation("test flag", [](auto &value) { value.functions[0].is_test = true; }); + mutation("inline flag", [](auto &value) { value.functions[0].is_inline = true; }); + mutation("parameter", [](auto &value) { value.functions[0].params.push_back("capability: ptr"); }); + mutation("generic", [](auto &value) { value.functions[0].generic_params.push_back("T"); }); + mutation("invalid declaration line", [](auto &value) { value.functions[0].source_line = -1; }); + mutation("constant name syntax injection", [](auto &value) { value.string_constants.emplace_back("s;CALL", "data"); }); + for (const auto &annotation : {"@intrinsic(\"io.open\")", "@interop(\"libhost\")", "@extern", "@custom", "@nil_tuple"}) + mutation(std::string("function annotation ") + annotation, [&](auto &value) { value.functions[0].annotations.push_back(annotation); }); + for (const auto &type : {"ptr", "fn()->i32", "owned", "Custom", "any", "array", "tuple>", "array", "tuple<>", "i32 trailing"}) + mutation(std::string("forbidden return ") + type, [&](auto &value) { value.functions[0].return_type = type; }); + for (const auto &value : {"NaN", "Infinity", "1 trailing", "1e9999", "9223372036854775808", "0;CALL"}) + mutation(std::string("invalid constant ") + value, [&](auto &result) { result.functions[0].body[0].args = {value}; }); + mutation("extra operand", [](auto &value) { value.functions[0].body[0].args.push_back("CALL"); }); + mutation("missing operand", [](auto &value) { value.functions[0].body[0].args.clear(); }); + mutation("bad cast", [](auto &value) { value.functions[0].body[1].args = {"ptr"}; }); + mutation("extra return operand", [](auto &value) { value.functions[0].body.back().args = {"outside"}; }); + mutation("missing return", [](auto &value) { value.functions[0].body.pop_back(); }); + mutation("empty function", [](auto &value) { value.functions[0].body.clear(); }); + nil_case("stack underflow", module({{"ADD", {"i32"}}, {"RET", {}}}), false); + nil_case("unbound local", module({{"LOAD_LOCAL", {"x"}}, {"RET", {}}}), false); + nil_case("mutated local", module({{"PUSH_CONST", {"1"}}, {"STORE_LOCAL", {"x"}}, {"PUSH_CONST", {"2"}}, {"STORE_LOCAL", {"x"}}, {"RET", {}}}, "void"), false); + nil_case("leftover operand", module({{"PUSH_CONST", {"1"}}, {"PUSH_CONST", {"2"}}, {"RET", {}}}), false); + nil_case("cycle", module({{"LABEL", {"again"}}, {"JMP", {"again"}}, {"RET", {}}}, "void"), false); + nil_case("missing branch label", module({{"JMP", {"missing"}}, {"RET", {}}}, "void"), false); + nil_case("duplicate label", module({{"LABEL", {"x"}}, {"LABEL", {"x"}}, {"RET", {}}}, "void"), false); + nil_case("dead safe code", module({{"RET", {}}, {"PUSH_CONST", {"1"}}, {"POP", {}}}, "void"), false); + auto bad_join = conditional; bad_join.string_constants.emplace_back("S", "wrong"); bad_join.functions[0].body[6] = {"PUSH_CONST_STR", {"S"}}; + nil_case("incompatible branch local", bad_join, false); + auto maybe_local = conditional; maybe_local.functions[0].body[7] = {"STORE_LOCAL", {"other"}}; + nil_case("conditionally uninitialized local", maybe_local, false); + auto duplicate_constant = text; duplicate_constant.string_constants.push_back(duplicate_constant.string_constants[0]); + nil_case("duplicate string constant", duplicate_constant, false); + auto unknown_constant = text; unknown_constant.functions[0].body[0].args = {"absent"}; + nil_case("unknown string constant", unknown_constant, false); + auto bad_text_arithmetic = text; bad_text_arithmetic.functions[0].body[3] = {"ADD", {"i32"}}; + nil_case("text arithmetic operand", bad_text_arithmetic, false); + nil_case("untyped array", module({{"NEW_ARRAY_LITERAL", {"0","any"}}, {"RET", {}}}, "array"), false); + nil_case("forged array metadata", module({{"PUSH_CONST", {"1.5"}}, {"NEW_ARRAY_LITERAL", {"1","i32"}}, {"RET", {}}}, "array"), false); + nil_case("malformed array count", module({{"NEW_ARRAY_LITERAL", {"-1","i32"}}, {"RET", {}}}, "array"), false); + for (const auto &change : std::vector>{ + [](auto &value) { value.structs[0].annotations.push_back("@intrinsic"); }, + [](auto &value) { value.structs[0].annotations.clear(); }, + [](auto &value) { value.structs[0].fields[0].second = "text"; }, + [](auto &value) { value.structs[0].fields[0].first = "danger"; }, + [](auto &value) { value.structs.push_back(value.structs[0]); }, + [](auto &value) { value.structs.clear(); }, + [](auto &value) { value.functions[0].body[3].args = {"1"}; }, + [](auto &value) { value.functions[0].body.erase(value.functions[0].body.begin()+5); }, + [](auto &value) { value.functions[0].body.insert(value.functions[0].body.end()-1, {{"PUSH_CONST", {"3"}}, {"SET_FIELD", {"0"}}}); } + }) { auto value = tuple; change(value); nil_case("forged or mutable tuple", value, false); } + mutation("instruction count bound", [](auto &value) { value.functions[0].body.resize(4097, {"RET", {}}); }); + mutation("text budget", [](auto &value) { value.string_constants.emplace_back("huge", std::string(1024*1024+1, 'x')); }); + mutation("instruction debug injection", [](auto &value) { value.functions[0].body[0].source_file = "untrusted"; }); + + ast_case("empty AST", {}, {}, true); + ast_case("literal AST", {}, number(), true); + ast_case("immutable local AST", {local("value", number())}, std::make_shared("value"), true); + ast_case("arithmetic AST", {}, std::make_shared(number(), token_kind::plus, number()), true); + ast_case("minimum literal AST", {}, std::make_shared(token_kind::minus, number("9223372036854775808")), true); + ast_case("numeric cast AST", {}, std::make_shared(number(), "f64"), true); + ast_case("array AST", {}, std::make_shared(std::vector{number(),number()}), true); + ast_case("conditional AST", {}, std::make_shared(std::make_shared(true), number(), number()), true); + auto ast_tuple = std::make_shared("tuple", std::vector>{{"0",number()},{"1",std::make_shared("text")}}); + ast_tuple->tuple_literal = true; + auto destructuring = std::make_shared("", ast_tuple); + destructuring->tuple_bindings = {std::make_shared("left"),std::make_shared("right")}; + ast_case("tuple destructuring AST", {std::make_shared(destructuring)}, std::make_shared("left"), true); + ast_case("tuple field AST", {}, std::make_shared(ast_tuple,"0"), true); + auto typed_tuple = std::make_shared("typed", ast_tuple, "tuple"); + ast_case("source tuple aliases and spacing", {std::make_shared(typed_tuple)}, {}, true); + ast_case("interpolation AST", {}, std::make_shared(std::vector{{true,"value ",{}},{false,"",number()}}), true); + ast_case("call AST", {}, call(), false); + ast_case("function value AST", {}, std::make_shared("__nil_submission"), false); + ast_case("global AST", {}, std::make_shared("outside"), false); + ast_case("mutable local AST", {local("value",number(),true)}, {}, false); + ast_case("escaped punctuation local AST", {local("value;CALL",number())}, {}, false); + ast_case("mutation AST", {local("value",number())}, std::make_shared(std::make_shared("value"),number()), false); + ast_case("dead conditional call AST", {}, std::make_shared(std::make_shared(false), call(), number()), false); + ast_case("dead statement call AST", {std::make_shared(std::make_shared(false),std::make_shared(call()))}, {}, false); + ast_case("hidden interpolation call AST", {}, std::make_shared(std::vector{{false,"",call()}}), false); + ast_case("hidden interpolation literal AST", {}, std::make_shared(std::vector{{true,"safe",call()}}), false); + ast_case("array hidden call AST", {}, std::make_shared(std::vector{call()}), false); + ast_case("pointer dereference AST", {}, std::make_shared(token_kind::star,number()), false); + ast_case("pointer cast AST", {}, std::make_shared(number(),"ptr"), false); + ast_case("reference AST", {}, std::make_shared(token_kind::ref_kw,number()), false); + ast_case("method access AST", {}, std::make_shared(number(),"danger"), false); + ast_case("query AST", {}, std::make_shared(), false); + ast_case("return AST", {std::make_shared(number())}, {}, false); + ast_case("print AST", {std::make_shared(std::vector{number()})}, {}, false); + ast_case("assembly AST", {std::make_shared("syscall")}, {}, false); + ast_case("loop AST", {std::make_shared(std::make_shared(false),std::make_shared())}, {}, false); + ast_case("import AST", {std::make_shared(std::make_shared("nil.std.io"))}, {}, false); + auto annotated = number(); annotated->annotations.push_back({}); + ast_case("annotated expression AST", {}, annotated, false); + auto illegal_type = std::make_shared("x",number(),"ptr"); + ast_case("pointer local type AST", {std::make_shared(illegal_type)}, {}, false); + auto branch_block = std::make_shared(); branch_block->statements = {local("hidden",number())}; + ast_case("branch local cannot escape AST", {std::make_shared(number(),branch_block)}, std::make_shared("hidden"), false); + auto deep = number(); + for (int i=0;i<70;++i) deep = std::make_shared(token_kind::minus,deep); + ast_case("AST depth bound", {}, deep, false); + std::vector many(4097,std::make_shared(number())); + ast_case("AST node bound", many, {}, false); + auto diagnostics = validate_submission_ast(ast_block_stmt{}, annotated); + expect("source line retained", !diagnostics.empty() && diagnostics[0].line == 7, true); + auto missing = std::make_shared("missing"); + missing->source_file = "$.value.left"; + auto invalid_binary = std::make_shared(missing, token_kind::plus, number()); + invalid_binary->source_file = "$.value"; + diagnostics = validate_submission_ast(ast_block_stmt{}, invalid_binary); + expect("innermost request node path retained", diagnostics.size() == 1 && diagnostics[0].source_file == "$.value.left", true); + auto forbidden = call(); forbidden->source_file = "$.value"; + diagnostics = validate_submission_ast(ast_block_stmt{}, forbidden); + expect("forbidden request node path retained", diagnostics.size() == 1 && diagnostics[0].source_file == "$.value", true); + std::cout << checks << " submission admission checks; " << failures << " failures\n"; + return failures ? 1 : 0; +} diff --git a/tests/submission_request_tests.cpp b/tests/submission_request_tests.cpp new file mode 100644 index 00000000..86194e7b --- /dev/null +++ b/tests/submission_request_tests.cpp @@ -0,0 +1,340 @@ +#include "submission_request.hpp" +#include "nildata.hpp" +#include "numeric_literal.hpp" +#include "../common/strict_json.hpp" + +#include +#include +#include +#include +#include +#include + +namespace { +using nil::detail::json; +int failures = 0; + +void check(bool condition, const std::string &message) { + if (!condition) { + ++failures; + std::cerr << "FAIL: " << message << '\n'; + } +} + +json object(std::initializer_list> fields) { + auto result = json::map(); + result.object = fields; + return result; +} + +json list(std::initializer_list items) { + auto result = json::list(); + result.array = items; + return result; +} + +json number(const std::string &spelling) { + return object({{"kind", json::str("number")}, {"value", json::str(spelling)}}); +} + +json name(const std::string &spelling) { + return object({{"kind", json::str("name")}, {"name", json::str(spelling)}}); +} + +json boolean(bool value) { + return object({{"kind", json::str("boolean")}, {"value", json::flag(value)}}); +} + +json unary(const std::string &op, json value) { + return object({{"kind", json::str("unary")}, {"operator", json::str(op)}, + {"operand", std::move(value)}}); +} + +json envelope(json value = {}, json bindings = json::list()) { + return object({{"schema", json::str("nil.matrix.submission-request.v1")}, + {"profile", json::str("matrix.pure.v1")}, + {"bindings", std::move(bindings)}, {"value", std::move(value)}}); +} + +std::string document(const json &value) { + return nil::data::from_json(nil::detail::dump(value)); +} + +matrix::decoded_submission_request decode(json value, json bindings = json::list()) { + return matrix::decode_submission_request(document(envelope(std::move(value), std::move(bindings)))); +} + +void rejects_source(const std::string &source, const std::string &path, + const std::string &reason, const std::string &description) { + try { + matrix::decode_submission_request(source); + check(false, description + " must be rejected"); + } catch (const matrix::submission_request_error &error) { + const std::string message = error.what(); + check(error.path == path && message.rfind(path, 0) == 0 && message.find(reason) != std::string::npos, + description + " must identify its request path and reason: " + message); + } +} + +void rejects(json request, const std::string &path, const std::string &reason, + const std::string &description) { + rejects_source(document(request), path, reason, description); +} + +void test_envelope_and_names() { + auto empty = decode({}); + check(empty.body && empty.body->statements.empty() && !empty.value, + "null final value represents a void submission"); + check(empty.body->source_file == "$.bindings" && empty.body->line == 0, + "synthetic AST locations carry request paths without invented source lines"); + + auto bindings = list({object({{"name", json::str("Frame-Count")}, {"value", number("7")}}), + object({{"name", json::str("saved")}, {"value", name("FRAMECOUNT")}})}); + auto request = decode(name("frame_count"), bindings); + auto statement = std::dynamic_pointer_cast(request.body->statements[0]); + auto declaration = std::dynamic_pointer_cast(statement->declaration); + auto reference = std::dynamic_pointer_cast(request.value); + check(declaration && declaration->name == "Frame_Count" && !declaration->is_mut && + !declaration->is_const && !declaration->type_name, + "bindings use ordinary immutable Matrix value declarations"); + check(reference && reference->name == "Frame_Count" && !reference->resolved_global_name, + "references use declaration spelling after Matrix case/separator folding"); + auto saved_stmt = std::dynamic_pointer_cast(request.body->statements[1]); + auto saved = std::dynamic_pointer_cast(saved_stmt->declaration); + auto saved_reference = std::dynamic_pointer_cast(saved->initializer); + check(saved_reference && saved_reference->name == "Frame_Count" && + saved_reference->source_file == "$.bindings[1].value", + "binding initializers resolve through the same name table and retain paths"); + + for (const auto &spelling : {"normal", "CamelCase", "two-parts", "two_parts", "a_s", "caf\xc3\xa9"}) { + auto allowed = decode(name(spelling)); + check(allowed.value && allowed.value->kind == ny::ast_node_kind::identifier_expr_node, + std::string("ordinary Matrix identifier accepted: ") + spelling); + } + for (const auto &spelling : {"", "name ", " name", "a b", "`escaped`", "book::name", + "host.call", "name\n", "name // ignored", "begin", "42", "bad--name"}) + rejects(envelope(name(spelling)), "$.value.name", "unescaped Matrix identifier", + std::string("non-simple identifier ") + nil::detail::quote(spelling)); + + bindings.array.push_back(object({{"name", json::str("frame_count")}, {"value", number("8")}})); + rejects(envelope({}, bindings), "$.bindings[2].name", "duplicate binding", + "case and separator folded binding collision"); + rejects(envelope({}, list({object({{"name", json::str("foo")}, {"value", {}}})})), + "$.bindings[0].value", "expression object", "null binding value"); +} + +void test_numbers() { + for (const auto &spelling : {"0", "2147483647", "2147483648", "9223372036854775807", + "1.5", "6.02e23", "5e-324", "0e999999999999999999"}) { + auto value = std::dynamic_pointer_cast(decode(number(spelling)).value); + check(value && value->value == spelling, std::string("numeric lexeme preserved: ") + spelling); + } + for (const auto &spelling : {"-1", "-0", "-0.0", "-1.5", "-5e-324"}) { + auto value = std::dynamic_pointer_cast(decode(number(spelling)).value); + auto magnitude = value ? std::dynamic_pointer_cast(value->operand) : nullptr; + check(value && value->op == ny::token_kind::minus && magnitude && + magnitude->value == std::string(spelling).substr(1), + std::string("signed number uses Matrix unary semantics: ") + spelling); + } + for (const auto &spelling : {"-2147483648", "-9223372036854775808"}) { + auto raw = std::dynamic_pointer_cast(decode(number(spelling)).value); + auto explicit_negative = std::dynamic_pointer_cast( + decode(unary("negative", number(std::string(spelling).substr(1)))).value); + ny::integer_literal_info info; + check(raw && raw->value == spelling && explicit_negative && explicit_negative->value == spelling && + !ny::parse_integer_literal(raw->value, info), + std::string("signed boundary matches raw and explicit unary forms: ") + spelling); + check(std::string(info.inferred_type()) == (std::string(spelling) == "-2147483648" ? "i32" : "i64"), + "signed boundaries keep their Matrix inferred scalar width"); + } + auto double_negative = std::dynamic_pointer_cast( + decode(unary("negative", number("-9223372036854775808"))).value); + check(double_negative && std::dynamic_pointer_cast(double_negative->operand), + "double negation of a signed minimum remains ordinary typed arithmetic"); + + for (const auto &spelling : {"", " 1", "1 ", "+1", "01", "-01", "0x10", "NaN", "Infinity", + "true", "null", "[]", "1,2", "1.", ".5", "1e", "1\n"}) + rejects(envelope(number(spelling)), "$.value.value", "exact JSON numeric token", + std::string("invalid exact numeric token ") + nil::detail::quote(spelling)); + for (const auto &spelling : {"9223372036854775808", "-9223372036854775809", "18446744073709551616", + "1e309", "1e-400", "-1e400", "-1e-400"}) + rejects(envelope(number(spelling)), "$.value.value", "representable", + std::string("out of range numeric token ") + spelling); + rejects(envelope(unary("not", number("9223372036854775808"))), + "$.value.operand.value", "representable", "positive signed minimum without negative operator"); + auto wrong_number = number("1"); + wrong_number.object["value"] = nil::detail::json_parser("1").parse(); + rejects(envelope(wrong_number), "$.value.value", "expected text", "numeric value must be lexical text"); +} + +void test_expression_shapes() { + const std::string literal_text = "line\n\"quoted\"\\path\t\xc3\xa9"; + auto literal = std::dynamic_pointer_cast( + decode(object({{"kind", json::str("text")}, {"value", json::str(literal_text)}})).value); + check(literal && literal->value == literal_text, "text is decoded once without source-language escaping"); + auto flag = std::dynamic_pointer_cast(decode(boolean(true)).value); + check(flag && flag->value, "boolean uses its typed schema value"); + for (const auto &operation : std::map{ + {"negative", ny::token_kind::minus}, {"not", ny::token_kind::not_kw}, + {"bitwise-not", ny::token_kind::tilde}}) { + auto value = std::dynamic_pointer_cast(decode(unary(operation.first, number("4"))).value); + check(value && value->op == operation.second, "canonical unary operator maps to shared AST: " + operation.first); + } + for (const auto &operation : std::map{ + {"plus", ny::token_kind::plus}, {"minus", ny::token_kind::minus}, + {"times", ny::token_kind::star}, {"divided-by", ny::token_kind::slash}, + {"modulo", ny::token_kind::percent}, {"equals", ny::token_kind::double_equal}, + {"not-equals", ny::token_kind::not_equal}, {"less-than", ny::token_kind::less}, + {"less-or-equal", ny::token_kind::less_equal}, {"greater-than", ny::token_kind::greater}, + {"greater-or-equal", ny::token_kind::greater_equal}, {"and", ny::token_kind::amp_amp}, + {"or", ny::token_kind::pipe_pipe}, {"bitwise-and", ny::token_kind::amp}, + {"bitwise-or", ny::token_kind::pipe}, {"bitwise-xor", ny::token_kind::caret}, + {"shift-left", ny::token_kind::less_less}, {"shift-right", ny::token_kind::greater_greater}}) { + auto value = std::dynamic_pointer_cast(decode(object({ + {"kind", json::str("binary")}, {"operator", json::str(operation.first)}, + {"left", number("3")}, {"right", number("2")}})).value); + check(value && value->op == operation.second && value->left->source_file == "$.value.left" && + value->right->source_file == "$.value.right", "binary child order and opcode: " + operation.first); + } + + auto tuple = object({{"kind", json::str("tuple")}, {"items", list({number("1"), boolean(false)})}}); + auto tuple_ast = std::dynamic_pointer_cast(decode(tuple).value); + check(tuple_ast && tuple_ast->tuple_literal && tuple_ast->type_name == "tuple" && + tuple_ast->fields.size() == 2 && tuple_ast->fields[0].first == "0" && + tuple_ast->fields[1].first == "1", "tuple uses ordered shared structural fields"); + auto member = std::dynamic_pointer_cast(decode(object({ + {"kind", json::str("member")}, {"target", tuple}, {"index", json::str("1")}})).value); + check(member && member->member_name == "1" && member->object->source_file == "$.value.target", + "tuple projection decodes a static position"); + auto array = object({{"kind", json::str("array")}, {"items", list({number("1"), number("2")})}}); + auto array_ast = std::dynamic_pointer_cast(decode(array).value); + check(array_ast && array_ast->elements.size() == 2, "array retains ordered elements"); + auto index = std::dynamic_pointer_cast(decode(object({ + {"kind", json::str("index")}, {"target", array}, {"index", number("0")}})).value); + check(index && index->object && index->index && index->index->source_file == "$.value.index", + "index retains both target and subscript expressions"); + auto conditional = std::dynamic_pointer_cast(decode(object({ + {"kind", json::str("conditional")}, {"condition", boolean(true)}, + {"then", number("1")}, {"otherwise", number("2")}})).value); + check(conditional && conditional->condition && conditional->then_expr && conditional->else_expr, + "conditional retains all three independent expressions"); + for (const auto &type : {"bool", "i32", "i64", "u8", "f64"}) { + auto cast = std::dynamic_pointer_cast(decode(object({ + {"kind", json::str("cast")}, {"value", number("1")}, {"type", json::str(type)}})).value); + check(cast && cast->target_type == type && !cast->checked_identity, + std::string("primitive cast is decoded without forging checker proof: ") + type); + } + // These are structurally valid requests. The independent checker must still + // reject undeclared references, heterogeneous arrays, invalid casts, etc. + check(decode(name("undefined-name")).value != nullptr, + "decoder does not invent bindings for unresolved names"); + check(decode(object({{"kind", json::str("array")}, {"items", list({})}})).value != nullptr, + "empty array type inference remains a checker responsibility"); +} + +void test_schema_rejections() { + for (const auto &field : {"schema", "profile", "bindings", "value"}) { + auto missing = envelope(); missing.object.erase(field); + rejects(missing, std::string("$.") + field, "missing field", std::string("missing envelope ") + field); + } + for (const auto &field : {"capabilities", "authority", "trusted", "imports", "source", "statements", "execute"}) { + auto forged = envelope(); forged.object[field] = json::flag(true); + rejects(forged, "$[" + nil::detail::quote(field) + "]", "unknown field", + std::string("forged envelope field ") + field); + } + auto punctuated_key = envelope(); punctuated_key.object["unknown: field"] = json::flag(true); + rejects(punctuated_key, "$[\"unknown: field\"]", "unknown field", + "diagnostic path remains structural when an unknown key contains a colon"); + auto schema = envelope(); schema.object["schema"] = json::str("nil.matrix.submission-request.v2"); + rejects(schema, "$.schema", "unsupported", "unknown schema version"); + auto profile = envelope(); profile.object["profile"] = json::str("matrix.privileged.v1"); + rejects(profile, "$.profile", "unsupported", "unknown authority profile"); + auto wrong_bindings = envelope(); wrong_bindings.object["bindings"] = json::str("none"); + rejects(wrong_bindings, "$.bindings", "array", "wrong binding collection type"); + rejects(envelope({}, list({number("1")})), "$.bindings[0][\"kind\"]", "unknown field", "expression in binding slot"); + rejects(envelope({}, list({object({{"name", json::str("x")}, {"value", number("1")}, + {"mutable", json::flag(true)}})})), + "$.bindings[0][\"mutable\"]", "unknown field", "mutable binding request"); + rejects(envelope(json::str("say dangerous")), "$.value", "expression object", "source text in expression slot"); + rejects(envelope(object({})), "$.value.kind", "missing field", "expression without kind"); + for (const auto &kind : {"call", "query", "import", "assembly", "allocate", "statement", "null", "Number"}) + rejects(envelope(object({{"kind", json::str(kind)}})), "$.value.kind", "unknown expression kind", + std::string("unsupported expression kind ") + kind); + for (const auto &field : {"inferred_type", "checked_identity", "resolved_global_name", "annotations", "source_file"}) { + auto forged = number("1"); forged.object[field] = json::str("trusted"); + rejects(envelope(forged), "$.value[" + nil::detail::quote(field) + "]", "unknown field", + std::string("forged AST metadata ") + field); + } + rejects(envelope(object({{"kind", json::str("boolean")}, {"value", json::str("true")}})), + "$.value.value", "boolean", "text instead of boolean"); + rejects(envelope(object({{"kind", json::str("tuple")}, {"items", list({})}})), + "$.value.items", "at least one", "empty tuple"); + rejects(envelope(unary("minus", number("1"))), "$.value.operator", "unknown unary operator", + "noncanonical unary alias"); + rejects(envelope(object({{"kind", json::str("binary")}, {"operator", json::str("assign")}, + {"left", number("1")}, {"right", number("2")}})), + "$.value.operator", "unknown binary operator", "assignment operator"); + for (const auto &position : {"", "-1", "+1", "01", "1.0", "1e1", "1 ", "9223372036854775808", "run"}) + rejects(envelope(object({{"kind", json::str("member")}, {"target", name("pair")}, + {"index", json::str(position)}})), "$.value.index", "tuple position", + std::string("noncanonical tuple position ") + nil::detail::quote(position)); + for (const auto &type : {"number", "floating", "text", "f32", "i16", "u64", "ptr", "array", "Host", "void"}) + rejects(envelope(object({{"kind", json::str("cast")}, {"value", number("1")}, + {"type", json::str(type)}})), "$.value.type", "primitive type", + std::string("noncanonical or unsupported cast ") + type); +} + +void test_encoding_and_limits() { + rejects_source("{}", "$", "nildata", "unversioned JSON input"); + rejects_source("nildata 1\nobject\n", "$", "end object", "truncated NILData"); + rejects_source("nildata 1\nobject\nx is 1\nx is 2\nend object\n", "$", "duplicate", "duplicate source fields"); + auto raw_nul = document(envelope()); raw_nul += '\0'; + rejects_source(raw_nul, "$", "NUL", "raw embedded NUL"); + auto invalid_utf8 = document(envelope()); invalid_utf8 += char(0xff); + rejects_source(invalid_utf8, "$", "UTF-8", "invalid UTF-8 source"); + rejects(envelope(object({{"kind", json::str("text")}, {"value", json::str(std::string("a\0b", 3))}})), + "$[\"value\"][\"value\"]", "NUL", "escaped NUL in text value"); + auto nul_key = envelope(); nul_key.object[std::string("a\0b", 3)] = json::flag(true); + rejects(nul_key, "$[\"a\\u0000b\"]", "NUL", "escaped NUL in field name"); + + auto exact_limit = document(envelope()); exact_limit.resize(64 * 1024, ' '); + check(!matrix::decode_submission_request(exact_limit).value, "exactly 64 KiB remains within the source bound"); + exact_limit += ' '; + rejects_source(exact_limit, "$", "64 KiB", "source one byte beyond limit"); + + // Build malformed depth directly: the NILData encoder independently enforces + // its nesting bound and would reject before the decoder under test is called. + std::string deep = "nildata 1\nobject\nschema is \"nil.matrix.submission-request.v1\"\n" + "profile is \"matrix.pure.v1\"\nbindings is an array\nend array\nvalue is an object\n"; + for (int i = 0; i < 35; ++i) + deep += "kind is \"unary\"\noperator is \"not\"\noperand is an object\n"; + deep += "kind is \"boolean\"\nvalue is true\nend object\n"; + for (int i = 0; i < 35; ++i) deep += "end object\n"; + deep += "end object\n"; + rejects_source(deep, "$", "32", "excessively nested expression document"); + + auto many = json::list(); + for (int i = 0; i < 400; ++i) many.array.push_back(number(std::to_string(i))); + auto wide = decode(object({{"kind", json::str("array")}, {"items", std::move(many)}})); + auto array = std::dynamic_pointer_cast(wide.value); + check(array && array->elements.size() == 400, "a bounded wide expression is retained without truncation"); +} +} // namespace + +int main() { + try { + test_envelope_and_names(); + test_numbers(); + test_expression_shapes(); + test_schema_rejections(); + test_encoding_and_limits(); + } catch (const std::exception &error) { + check(false, std::string("unexpected exception: ") + error.what()); + } + if (failures) { + std::cerr << failures << " submission request test(s) failed\n"; + return 1; + } + std::cout << "submission request tests passed\n"; + return 0; +} From 541ac6f18a417ce063064aed343bf3242dd93fed Mon Sep 17 00:00:00 2001 From: Nathan Date: Mon, 26 Oct 2026 20:38:53 -0400 Subject: [PATCH 4/5] Update shell profile implementation status --- docs/design/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/README.md b/docs/design/README.md index 20ecedf0..3b94af84 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -41,7 +41,7 @@ not assigned architecture identifiers. | NIL-0015 | [Structural tuples](NIL-0015-structural-tuples.md) | Implemented nonempty typed values and local destructuring | | NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | | NIL-0017 | [Versioned NILData and one shared value model](NIL-0017-nildata.md) | Implemented initial bounded document profile | -| NIL-0018 | [A Matrix profile for interactive shell work](NIL-0018-matrix-shell-profile.md) | Proposed; ordinary hosted syntax example only | +| NIL-0018 | [A Matrix profile for interactive shell work](NIL-0018-matrix-shell-profile.md) | Pure submission checking implemented; evaluator, sessions and host commands proposed | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references From 83c4e654a567da4eb8179a0f9eea3b16e7e7c822 Mon Sep 17 00:00:00 2001 From: Nathan Date: Mon, 26 Oct 2026 21:08:54 -0400 Subject: [PATCH 5/5] Add bounded Matrix evaluation and immutable shell sessions --- CMakeLists.txt | 22 ++ docs/design/NIL-0018-matrix-shell-profile.md | 136 ++++--- docs/design/README.md | 2 +- docs/tools/index.md | 8 +- docs/tools/matrix-submissions.md | 254 +++++++++--- matrix/README.md | 2 +- matrix/docs/next-version-findings.md | 86 ++++- nilcompiler/CMakeLists.txt | 3 + nilcompiler/src/main.cpp | 22 +- nilcompiler/src/matrix_lexer.cpp | 6 +- nilcompiler/src/matrix_lexer.hpp | 4 +- nilcompiler/src/matrix_parser.cpp | 4 +- nilcompiler/src/matrix_parser.hpp | 3 + nilcompiler/src/matrix_submission.cpp | 4 +- nilcompiler/src/submission_request.cpp | 12 +- nilcompiler/src/submission_request.hpp | 4 +- nilcompiler/src/submission_session.cpp | 198 ++++++++++ nilcompiler/src/submission_session.hpp | 45 +++ nilcompiler/src/submission_session_cli.cpp | 361 ++++++++++++++++++ nilcompiler/src/submission_session_cli.hpp | 10 + .../src/submission_session_compile.cpp | 314 +++++++++++++++ .../src/submission_session_compile.hpp | 34 ++ nilcompiler/src/submission_value.hpp | 37 ++ nilcompiler/src/type_checker.cpp | 14 +- nilcompiler/src/vm.cpp | 344 +++++++++++++++++ nilcompiler/src/vm.hpp | 20 + tests/matrix_session_contract.py | 273 +++++++++++++ tests/matrix_submission_parser_tests.cpp | 15 + tests/submission_session_compile_tests.cpp | 123 ++++++ tests/submission_session_tests.cpp | 144 +++++++ tests/submission_vm_tests.cpp | 214 +++++++++++ 31 files changed, 2581 insertions(+), 137 deletions(-) create mode 100644 nilcompiler/src/submission_session.cpp create mode 100644 nilcompiler/src/submission_session.hpp create mode 100644 nilcompiler/src/submission_session_cli.cpp create mode 100644 nilcompiler/src/submission_session_cli.hpp create mode 100644 nilcompiler/src/submission_session_compile.cpp create mode 100644 nilcompiler/src/submission_session_compile.hpp create mode 100644 nilcompiler/src/submission_value.hpp create mode 100644 tests/matrix_session_contract.py create mode 100644 tests/submission_session_compile_tests.cpp create mode 100644 tests/submission_session_tests.cpp create mode 100644 tests/submission_vm_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 51657651..264b1aae 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -151,6 +151,24 @@ if(BUILD_TESTING) add_test(NAME matrix.submission-request COMMAND $) set_tests_properties(matrix.submission-request PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 30) + add_executable(nil_submission_vm_tests tests/submission_vm_tests.cpp) + target_link_libraries(nil_submission_vm_tests PRIVATE nilcompiler_core) + target_compile_features(nil_submission_vm_tests PRIVATE cxx_std_17) + add_test(NAME nil.submission-vm COMMAND $) + set_tests_properties(nil.submission-vm PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 30) + + add_executable(nil_submission_session_compile_tests tests/submission_session_compile_tests.cpp) + target_link_libraries(nil_submission_session_compile_tests PRIVATE nilcompiler_core) + target_compile_features(nil_submission_session_compile_tests PRIVATE cxx_std_17) + add_test(NAME matrix.session-compile COMMAND $) + set_tests_properties(matrix.session-compile PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 30) + + add_executable(nil_submission_session_tests tests/submission_session_tests.cpp) + target_link_libraries(nil_submission_session_tests PRIVATE nilcompiler_core) + target_compile_features(nil_submission_session_tests PRIVATE cxx_std_17) + add_test(NAME matrix.session COMMAND $) + set_tests_properties(matrix.session PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 30) + add_executable(nil_pattern_engine_tests tests/pattern_engine_tests.cpp) target_link_libraries(nil_pattern_engine_tests PRIVATE nilruntime) target_include_directories(nil_pattern_engine_tests PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/nilcompiler/src") @@ -634,6 +652,10 @@ if(BUILD_TESTING) COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix_submission_contract.py" --compiler $) set_tests_properties(matrix.submission-contract PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 90) + add_test(NAME matrix.session-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix_session_contract.py" + --compiler $) + set_tests_properties(matrix.session-contract PROPERTIES LABELS "matrix;shell;rc" TIMEOUT 90) add_test( NAME ny.scalar-contract COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/scalar_contract.py" diff --git a/docs/design/NIL-0018-matrix-shell-profile.md b/docs/design/NIL-0018-matrix-shell-profile.md index 43be441e..e1b8e96b 100644 --- a/docs/design/NIL-0018-matrix-shell-profile.md +++ b/docs/design/NIL-0018-matrix-shell-profile.md @@ -1,8 +1,9 @@ # NIL-0018: A Matrix profile for interactive shell work -Status: admission prototype implemented. The compiler checks Matrix submissions -and versioned NILData requests through a shared pure profile. An interactive -evaluator, retained session, host commands and Anomalous execution remain proposed. +Status: pure hosted prototype implemented. The compiler checks and evaluates +Matrix submissions and versioned NILData requests through a shared profile. The +interactive shell retains immutable owned values with transactional publication. +Host commands, command catalogs and native Anomalous execution remain proposed. The companion syntax example runs as an ordinary hosted Matrix program. ## Purpose and existing direction @@ -67,8 +68,8 @@ uses tuples and explicit `Result` handling under the existing contract. The prompt should accept a submission containing statements and a final expression. Saved programs retain ordinary `.mat`/`.matrix` pages. Exporting a -session creates a normal book/paragraph with explicit inputs, rather than a -different script grammar. The compiler now has a separate submission entry point +session would create a normal book/paragraph with explicit inputs; session +export and persistent history are not implemented. The compiler now has a separate submission entry point using the existing statement/expression parser. It checks local statements and an optional final expression without requiring a book or paragraph declaration. @@ -85,11 +86,11 @@ enters the VM/native execution paths. See the [command and request contract](../ Profile `matrix.pure.v1` admits immutable local bindings, concrete scalar/text, supported tuple/array expressions, numeric casts, formatting and conditionals. All calls, imports, mutation, loops, queries, annotations, pointers and assembly -are excluded, including in dead branches. `Option`/`Result`, command catalogs, -retained bindings and runtime quotas require later work. Parsing distinguishes -complete, incomplete and invalid input; a complete parse can still fail type or -profile checks. Limits bound input, syntax depth, AST size and generated NIL; -they do not establish execution-time or heap bounds. +are excluded, including in dead branches. `Option`/`Result` and command catalogs +remain outside this profile. Parsing distinguishes complete, incomplete and +invalid input; a complete parse can still fail type or profile checks. Admission +limits bound input, syntax depth, AST size and generated NIL. The evaluator adds +separate execution and publication limits described below. Structured requests use schema `nil.matrix.submission-request.v1`, with exact fields, a closed expression vocabulary and no authority-bearing fields. They @@ -97,26 +98,59 @@ construct shared AST nodes directly. They cannot supply source, arbitrary AST objects or serialized NIL to bypass admission. Differential tests compare typed NIL from source and request inputs. -## Planned hosted profile - -| Area | First hosted prototype | Follow-up | +## Implemented hosted evaluator and session + +`--evaluate-submission` and `--evaluate-submission-request` execute an admitted +submission in a fresh shared VM and return `nil.matrix.submission-evaluation.v1` +JSON. `--matrix-shell` adds line collection, complete/incomplete detection, +explicit `:begin`/`:submit` transactions, typed results and binding inspection. +The shared C++ session API accepts both source and request input against the +same retained values. The single-evaluation CLI commands use fresh sessions. + +Retained bindings are owned data snapshots with exact types. Compilation restores +those values as typed literal AST data, then compiles only the new computation; +previous source and expressions are never replayed. New top-level bindings are +returned with the final value in a generated tuple. The host validates the +snapshot, cumulative state, compiler restorability and serialized result before +publishing the entire transaction. Failure or cancellation leaves existing +bindings unchanged. Nested locals and destructuring discards do not persist. + +The loaded program is independently revalidated, and the VM checks its admitted +operations before executing them. Default limits allow 16,384 instructions, +16 MiB of charged work, 1 MiB text/snapshot payloads, 4,096 snapshot nodes and +32 levels of snapshot depth. Sessions allow 64 bindings, 1,024 retained nodes, +1 MiB retained state and 1 MiB successful result reports. A one-second deadline +covers execution and publication after compilation/loading, with cooperative +checks at instructions and publication checkpoints. These limits do not measure +process RSS or provide hard preemption. API cancellation is checked between +instructions, during export and before publication. + +Typed scalar payloads are JSON strings, preserving `i64` precision, finite float +round trips and negative zero. Arrays and tuples contain typed child values. +Nonfinite results fail publication. The shell writes no persistent history and +provides no host operations. Its `:cancel` command discards pending input; +host callbacks provide cancellation during evaluation. Native submission +execution and Anomalous integration remain unimplemented. + +| Area | Implemented hosted profile | Follow-up | | --- | --- | --- | -| Values | Existing scalar/text, supported tuples and arrays; `Option`/`Result` | Named record arrays and checked domain values | -| Computation | Immutable bindings, arithmetic, comparison, explicit formatted text, conditionals, collected queries | User paragraphs and bounded iteration after transitive validation | -| Commands | Typed, versioned mock `help` and system observations | Real observation adapters admitted by Anomalous | -| Imports | A fixed, explicitly admitted module catalog | Versioned user modules after effect/operation verification | -| Session | Explicit inputs and outputs; new code never replays prior effects | Retained bindings with managed ownership and deterministic cleanup | -| Effects | No live external operations in the syntax proof | Observation, then preview/commit, cancellation and recovery | +| Values | Scalar/text, supported tuples and concrete arrays | `Option`/`Result`, named record arrays and checked domain values | +| Computation | Immutable bindings, arithmetic, comparison, formatted text and conditionals | Collected queries, user paragraphs and bounded iteration after transitive validation | +| Commands | Session controls only; no language-level host commands | Typed catalog, mock observations, then Anomalous adapters | +| Imports | Rejected | Fixed admitted catalog, then versioned modules after effect/operation verification | +| Session | Owned typed values; atomic publication; no computation replay | Persistence/export policy and more efficient typed data import | +| Effects | Rejected | Observation, then preview/commit, cancellation and recovery | The execution profile excludes raw memory, assembly, arbitrary foreign calls, user intrinsic declarations, general recursion, unbounded loops, unrestricted parallelism and dynamic evaluation. The full Matrix language retains its systems features; this is an admitted workload profile with its own limits. -`value` prevents rebinding but does not make an array deeply immutable. Session -publication must account for aliases: a failed submission must not leave earlier -bindings changed through a shared array. Admit read-only operations first, then -define ownership/copy rules before permitting updates to retained values. +`value` in ordinary Matrix prevents rebinding but does not make arrays deeply +immutable. The current shell profile rejects mutation and copies owned values +across VM boundaries, so a failed submission cannot change earlier arrays through +a retained VM alias. Any future update operations need an explicit ownership and +publication contract. Do not introduce command search through `PATH`, implicit environment expansion, word splitting, globbing, command substitution or execution of unknown names. @@ -130,11 +164,12 @@ Matrix submission -> Matrix parser -> shared AST/type checker -> typed NIL structured request -> checked schema/resolver ----------------------^ profile verifier | - bounded executor - | - typed host command adapter + bounded shared VM | - Anomalous invocation/policy boundary + owned typed result / session + +Future effectful extension: +checked command catalog -> typed host adapter -> Anomalous invocation/policy ``` Both entry paths must produce equivalent resolved operations and pass the same @@ -143,7 +178,7 @@ Use a small schema for the admitted profile, rather than accepting arbitrary internal compiler AST objects. Retain source spans or request-node identities for equivalent diagnostic attribution. -The host catalog binds each command to an exact operation identity, schema +A future host catalog must bind each command to an exact operation identity, schema version, argument slots, result type and effect summary. Generated declarations allow ordinary Matrix named-call checking and completion. Runtime dispatch must reject an unregistered command; it must not fall through to native-library @@ -185,18 +220,23 @@ sharing a result is a separate operation. ## Runtime gaps to close -- Submission parsing and check-only admission are implemented. A prompt still - needs line collection, result rendering and an evaluator; parsing is not - incremental across calls and each check is independent. -- `VM::loadProgram` resets globals, heap and execution state. Recompiling and - replaying the complete session would repeat effects. Define a retained binding - contract and transactional publication of new bindings instead. -- The VM has host callbacks, injectable streams, exit trapping and instruction - stepping, but no general sandbox/profile enforcement. External dispatch can - reach native-library loading. An allowlisted host adapter needs a closed path. -- Instruction stepping alone does not bound allocations, parsing/type checking, - output, native calls or the work performed inside one intrinsic. Give each - phase explicit budgets, cancellation behavior and host resource containment. +- The implemented shell uses the hosted shared VM. Anomalous still needs its + native interpreter/console integration and consumer qualification; there is no + native submission evaluator in this framework slice. +- Retained values are restored as typed literal AST data. This avoids executable + history replay but adds work proportional to retained data and consumes the + compiler's AST/instruction/text budgets. A future direct data import must + preserve exact types, ownership and default-deny admission. +- General VM host callbacks and foreign dispatch are outside the pure profile. + Calls remain rejected. An admitted host catalog needs a closed dispatch path, + exact schemas, transitive operation checks and live authorization. +- Logical VM budgets and cooperative deadlines do not bound process RSS or + preempt compiler/runtime operations. Production embedding needs its own host + containment and lifecycle policy. Initial compilation has structural bounds + but is outside the execution/publication deadline. +- Scalar/text array reads currently produce defaults out of range, while tuple + array reads fail. Define a shared checked indexing contract rather than a + shell-only interpretation; see F73 in the findings log. - Existing `ny.context.v2` inspection reports authored intent. It is not the authority manifest required by Anomalous decision record 0093. Reserved NIL format fields must not be repurposed without their own version/compatibility decision. @@ -226,8 +266,9 @@ visible through typed catalog declarations and inspected operations. This is an architectural comparison, not measured usability or security evidence. The companion program demonstrates existing Matrix syntax and hosted execution only. The implemented tests cover submission admission and hostile -inputs; execution resource limits and authority behavior remain qualification -requirements before selecting a deployable profile. +inputs; additional suites exercise bounded evaluation, owned snapshots and +transactional sessions. Native consumer qualification and authority behavior +remain requirements before selecting a deployable Anomalous profile. ## Implementation sequence @@ -235,12 +276,13 @@ requirements before selecting a deployable profile. 2. **Implemented:** Matrix submission parsing and a pure, default-deny profile verifier. Exercise complete/incomplete/error input and text/request equivalence without a live executor or host effects. -3. Add a bounded hosted evaluator with typed mock observations, final-value - rendering and explicit session binding ownership. Test no effect replay, - forged handles, unknown operations, budget exhaustion and cancellation. +3. **Implemented:** A bounded pure hosted evaluator, typed value projection, + input collection and owned retained bindings. Regression suites cover rollback, + restoration, malformed values, budget exhaustion and cancellation; typed mock + observations remain future catalog work. 4. Generate command signatures for completion/help from the same versioned - catalog used by checking and dispatch. Add native named record-row support - through the shared language implementation. + catalog used by checking and dispatch, starting with typed mock observations. + Add native named record-row support through the shared language implementation. 5. Qualify Anomalous interpreter execution and its observation adapters under its existing ADRs; run the shared language corpus and profile rejection cases. 6. Add mutations only with verified preview, commit, freshness, revocation, diff --git a/docs/design/README.md b/docs/design/README.md index 3b94af84..4e594028 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -41,7 +41,7 @@ not assigned architecture identifiers. | NIL-0015 | [Structural tuples](NIL-0015-structural-tuples.md) | Implemented nonempty typed values and local destructuring | | NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | | NIL-0017 | [Versioned NILData and one shared value model](NIL-0017-nildata.md) | Implemented initial bounded document profile | -| NIL-0018 | [A Matrix profile for interactive shell work](NIL-0018-matrix-shell-profile.md) | Pure submission checking implemented; evaluator, sessions and host commands proposed | +| NIL-0018 | [A Matrix profile for interactive shell work](NIL-0018-matrix-shell-profile.md) | Pure checking, bounded hosted evaluation and immutable sessions implemented; host commands and Anomalous execution proposed | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/tools/index.md b/docs/tools/index.md index 87501e3f..9ebc2522 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -69,8 +69,12 @@ NIL or use the optional LLVM backend. For Matrix prompt-style input, `--check-submission ` checks local statements and a final expression against the initial pure shell profile. `--check-submission-request ` checks the equivalent structured NILData -request. Both return JSON without execution or retained session state. See -[Matrix submission inspection](matrix-submissions.md). +request. Both return JSON without execution or retained session state. +`--evaluate-submission ` and `--evaluate-submission-request ` +run the same pure profile in a bounded hosted VM and return typed JSON values. +`--matrix-shell` retains immutable values across interactive submissions, with +atomic publication and explicit input blocks. No host commands or native shell +evaluator are included. See [Matrix submissions and pure sessions](matrix-submissions.md). ```text nilcompiler [options] --output [more-inputs.ny ...] diff --git a/docs/tools/matrix-submissions.md b/docs/tools/matrix-submissions.md index fa637603..9ae0885f 100644 --- a/docs/tools/matrix-submissions.md +++ b/docs/tools/matrix-submissions.md @@ -1,51 +1,166 @@ -# Matrix submission inspection +# Matrix submissions and pure sessions -The compiler provides a check-only entry point for the first Matrix shell -profile. It accepts local statements followed by an optional final expression, -without a book or paragraph wrapper. This is the admission foundation for the -[Anomalous shell proposal](../design/NIL-0018-matrix-shell-profile.md). +The compiler checks and evaluates Matrix statements followed by an optional +final expression, without a book or paragraph wrapper. The interactive shell +retains immutable, owned values between submissions. Matrix source and strict +NILData requests share the parser/type-checker/profile pipeline described in +[NIL-0018](../design/NIL-0018-matrix-shell-profile.md). ```sh printf 'value amount is 40\namount plus 2\n' | nilcompiler --check-submission - -nilcompiler --check-submission session.mat +printf 'value amount is 40\namount plus 2\n' | nilcompiler --evaluate-submission - nilcompiler --check-submission-request request.nildata +nilcompiler --evaluate-submission-request request.nildata +nilcompiler --matrix-shell ``` -Each command reads one bounded regular file or standard input through EOF and -writes one JSON report to standard output. It performs parsing, profile checks, -ordinary type checking and NIL generation. It does not execute the submission, -retain bindings, import libraries or write a compiled artifact. These commands -must be used alone; compilation/output switches cannot change their behavior. +The check and evaluate commands read one bounded regular file or standard input +through EOF, then write one JSON report. Each evaluation command creates a fresh +session. Use `--matrix-shell` or the C++ `matrix::submission_session` API to keep +bindings across submissions. Every command must be used alone: normal compiler +switches cannot disable checking, add imports, select native execution, or write +an output artifact. -## Results and completeness +## Check-only reports -The report schema is `nil.matrix.submission-check.v1`; the admission profile is +`--check-submission ` and `--check-submission-request ` retain +their existing inspection behavior. They parse, check the AST profile, run the +ordinary type checker, generate NIL and verify that artifact. They do not +execute or retain bindings. + +Their report schema is `nil.matrix.submission-check.v1`, with admission profile `matrix.pure.v1`. Reports include `input_kind`, `status`, `executed: false`, `result_type`, `nil`, `instruction_count` and `diagnostics`. Only a complete, -admitted submission has a result type and generated NIL. The type is `void` -when there is no final expression. `nil` contains inspection text, not a runtime -authorization or a serialized session. There is no evaluated result field. +admitted submission has a result type and generated NIL. `void` means there is +no final expression. The `nil` field is inspection text; it is neither an +execution authorization nor a serialized session. + +## Evaluation reports and values + +`--evaluate-submission ` and +`--evaluate-submission-request ` use schema +`nil.matrix.submission-evaluation.v1`. Reports retain the check fields except +`nil`, and add `committed`, `value`, `added`, `binding_count` and +`instructions_executed`. `executed` records whether VM instructions ran; +`committed` records whether the entire transaction passed publication checks. +A failed transaction returns no value or newly added bindings. A successful +expression-only or empty submission can commit without adding a binding. + +Values have explicit types. Every scalar payload is a JSON **string**, including +integers, finite floats and booleans. This preserves the full `i64` range when a +client uses JSON numbers with limited precision. Collection values carry an +`elements` array of recursively typed values. For example, the `value` field for +`(9223372036854775807, true)` is: + +```json +{ + "type": "tuple", + "elements": [ + {"type": "i64", "scalar": "9223372036854775807"}, + {"type": "bool", "scalar": "true"} + ] +} +``` -| Status | Exit code | Meaning | +Integer payloads use canonical decimal text. Float payloads use round-trip +precision with a decimal point or exponent; negative zero is preserved. +Nonfinite floats cannot be published. Text remains a string, with controls +escaped by JSON serialization. A `void` result has `value: null`; each entry in +`added` is `{ "name": ..., "value": ... }` using the same typed representation. + +| Status | Single-evaluation exit code | Meaning | | --- | --- | --- | -| `complete` | 0 | Parsing, type checking and both profile gates passed. | +| `complete` | 0 | Checking, execution and publication succeeded; for check-only commands, both admission gates passed. | | `incomplete` | 2 | Matrix syntax needs more input, such as an operand or closing block. | -| `invalid` | 1 | Input, parsing, schema, type or profile checks failed. | +| `invalid` | 1 | Input, parsing, schema, type, session-name or profile checks failed. | +| `runtime-error` | 1 | Admitted computation or typed result export failed. | +| `budget-exceeded` | 1 | Execution, state, restoration or report limits prevented publication. | +| `cancelled` | 1 | The embedding host requested cooperative cancellation. | + +Malformed command options produce a command-line error rather than a submission +report. NILData requests must be complete documents; an unfinished request is +invalid. Diagnostics carry stage, code, message, location, line, column and +length. Parser diagnostics preserve original Matrix positions; later stages may +provide only a line. Structured expression errors use paths such as `$.value` +or `$.bindings[0].value`. Zero positions mean unavailable. The runtime identifies +the executing instruction's source line when available. + +## Interactive use + +A complete line evaluates immediately. Incomplete Matrix input accumulates until +it forms a complete submission. Inside `begin text`, command-like lines remain +literal payload; close the block with `end text` before using a shell command. To make several otherwise complete lines one +transaction, use an explicit block: + +```text +:begin +value Frame-Count as number is 40 +value next-count is frame_count plus 2 +next-count +:submit +FRAMECOUNT +:bindings +:quit +``` -Malformed command options produce a normal command-line error rather than a -submission report. NILData requests must be complete documents; malformed or -incomplete requests are invalid. A caller collecting interactive lines can -resubmit the accumulated Matrix text after an incomplete result. Checks do not -share parser or execution state. +The first submission publishes both bindings and returns `42`. The next +expression reads the retained `Frame_Count` as `i64`. Matrix case/separator +folding applies across submissions; redeclaring an existing folded name fails. +Session binding names must be unescaped Matrix identifiers. Nested block locals +are not retained, and `_` in tuple destructuring does not create a binding. -Diagnostics carry stage, code, message, location, line, column and length. Matrix -parser diagnostics retain original source positions; later stages can provide -line-only positions. Structured expression errors identify request paths such -as `$.value` or `$.bindings[0].value`. Zero positions mean unavailable. +| Command | Behavior | +| --- | --- | +| `:begin` | Start an atomic input block; defer evaluation until `:submit`. | +| `:submit` | Evaluate pending input; incomplete input stays pending. | +| `:cancel` | Discard pending input without changing retained values. | +| `:bindings` | List retained names and typed values; piped output uses `nil.matrix.session-bindings.v1`. | +| `:reset` | Clear retained bindings and pending input. | +| `:quit` | Exit and discard pending input. | +| `:help` | Show commands; piped input receives `nil.matrix.shell-help.v1` JSON. | + +When both input and output are terminals, the shell shows prompts and readable +typed results: `42 : i32`, or `count = 42 : i32` for a binding. Text is quoted and +escaped, arrays use `[1, 2]`, and tuples use `(1, true)`; a one-element tuple +retains its comma. Empty success prints `ok`, and an empty `:bindings` prints +`No retained bindings.` Diagnostics show their status, message and available +source position. Terminal controls and directional characters are escaped. + +With piped input or output there are no prompts; results, binding inspection and +help use JSON records. Single-evaluation commands always return JSON, including +when run in a terminal. A failed shell submission does not stop later input. +The piped shell exits 1 if any input failed, otherwise 2 if EOF leaves incomplete +input or an unsubmitted atomic block, otherwise 0. Interactive `:quit` exits 0. +An oversized line or accumulated submission enters discard mode. Input resumes +only after `:submit`, `:cancel` or `:reset` (or exits with `:quit`), so the +remaining lines of a rejected submission cannot run separately. + +`:cancel` manages input collection; it is not an asynchronous interrupt for a +running evaluation. Embedding hosts can supply a cancellation callback, checked +between VM instructions, during value export and before publication. The shell +stores no persistent source history, result log or session file. There is no +command expansion, process launch, environment expansion or host filesystem API +inside the language profile. + +## Ownership and publication + +Every evaluation uses a fresh shared VM. Retained values are owned scalar/text, +array and tuple snapshots with exact types, not VM addresses or mutable aliases. +The compiler restores those snapshots as typed literal AST data, then compiles +the new submission. It never reruns earlier expressions or reconstructs source +text from values. Both source and request calls on the same +`matrix::submission_session` instance see those bindings. + +New top-level bindings are published together only after execution, typed +snapshot export, cumulative state limits, compiler restoration checks and report +projection succeed. Parse/type/profile failures, runtime errors, nonfinite +results, exhausted budgets and cancellation leave prior bindings unchanged. +An embedding host owns one session on one thread; the API does not provide +concurrent access or persistence. ## Admitted computation -The initial profile admits immutable `value` bindings, supported scalar/text +Profile `matrix.pure.v1` admits immutable `value` bindings, supported scalar/text expressions, tuple construction/destructuring, concrete arrays and indexing, numeric casts, formatted text and conditionals. A single bare expression may appear at the end. Use a value position or parentheses for a value-producing @@ -53,21 +168,20 @@ conditional when its syntax would otherwise select a statement. Calls (including library functions), imports, named declarations, annotations, mutation, loops, collected queries, pointer/reference operations and assembly -are rejected. Both branches are checked, even if one is unreachable. The -generated NIL gate independently checks the entire function, type metadata, -stack/local initialization, fresh tuple construction and forward control flow. -It rejects any unknown or forbidden opcode. - -This is a narrower profile than ordinary Matrix. Its exclusions do not change -the language accepted in normal books. The full-program -`shell-profile-preview.matrix` sample uses calls, queries and output, so it is -not an admitted pure submission. - -Admission does not prove that evaluation will succeed: division by zero and -out-of-range indexing can pass checking. Before execution is added, a hosted -evaluator needs allocation/work budgets, cancellation, result projection and -explicit ownership rules for retained bindings. Live Anomalous commands also -need their separate invocation and authority checks. +are rejected, including in branches that would not run. The generated NIL gate +independently checks all instructions, type metadata, stack/local initialization, +fresh tuple construction and forward control flow. The VM revalidates its loaded +program and rejects forbidden operations before execution. No host catalog or +Anomalous adapter is installed. Evaluation uses the hosted shared VM; there is +no native submission evaluator. + +These exclusions apply to the shell profile, not ordinary Matrix books. The +`shell-profile-preview.matrix` sample is a full program using calls, queries and +output, so it is not an admitted pure submission. Admission does not prove +runtime success: integer division by zero can pass checking. Array indexing +currently follows the shared language's existing behavior: an out-of-range +scalar/text array read returns a default value, while a tuple-array read fails. +This inconsistency is recorded as [F73](../../matrix/docs/next-version-findings.md#f73--array-indexing-needs-one-checked-failure-contract). ## Structured request schema @@ -109,7 +223,8 @@ The four envelope fields are `schema`, `profile`, `bindings` and `value`. Bindings are ordered `{name, value}` objects; each value is an expression. The final `value` is an expression or null for a void submission. Names use one unescaped Matrix identifier, with Matrix folding and duplicate-name rules. -References must resolve to an earlier binding; they cannot name host operations. +References must resolve to an earlier binding in the request or an existing +binding supplied by the session API. They cannot name host operations. Each expression has `kind` and the following additional required fields: @@ -133,17 +248,42 @@ Unary operators are `negative`, `not` and `bitwise-not`. Binary operators are `bitwise-and`, `bitwise-or`, `bitwise-xor`, `shift-left` and `shift-right`. Type/profile validation still applies to decoded expressions. -## Bounds and tests +## Bounds and verification + +Inputs remain limited to 65,536 bytes of valid UTF-8 with no embedded NUL. +Matrix scanning allows 4,096 tokens and parsing allows 64 nesting levels. +Requests also use the shared NILData limits and a 32-level expression decoder +limit. AST admission allows at most 4,096 nodes and 64 levels, with additional +name, collection and type-shape limits. Generated NIL allows 4,096 instructions, +256 locals/stack slots and 1 MiB of tracked text. Retained data restoration counts +against these compiler limits too. + +The hosted defaults are: + +| Resource | Default | +| --- | --- | +| Executed VM instructions | 16,384 | +| Charged VM work | 16 MiB | +| Individual text / exported snapshot bytes | 1 MiB each | +| Exported snapshot nodes / depth | 4,096 / 32 | +| Retained session bindings / value nodes | 64 / 1,024 | +| Retained state / successful result report | 1 MiB each | +| Execution and publication deadline | 1 second | -Both inputs are limited to 65,536 bytes of valid UTF-8 with no embedded NUL. -Matrix submission scanning has a 4,096-token limit and parsing has a 64-level -nesting limit. Requests also use the shared NILData format limits and a 32-level -expression decoder limit. AST/profile checks allow at most 4,096 nodes and 64 -levels, with additional limits for local names, collections and type shapes. -Generated NIL is capped at 4,096 instructions, 256 locals/stack slots and 1 MiB -of tracked text. These are admission limits, not execution quotas. +The execution deadline begins after initial compilation and program loading. +Checks run between instructions and at publication checkpoints, including after +snapshot/restoration work and report projection. These are cooperative logical +limits, not process RSS accounting, hard preemption or a general OS sandbox. +Initial parsing/checking uses its structural limits rather than this deadline. +Diagnostic reports can exceed a host's deliberately tiny successful-report +limit. Hosts may configure supported limits through the C++ API; these are not +CLI switches. -`matrix.submission-parser`, `matrix.submission-request`, -`nil.submission-profile` and `matrix.submission-contract` cover completeness, -strict decoding, forbidden AST/NIL operations, resource limits, diagnostics, -source/request equivalence and command isolation. They run without an executor. +The admission suites remain `matrix.submission-parser`, +`matrix.submission-request`, `nil.submission-profile` and +`matrix.submission-contract`. Runtime regression suites are +`nil.submission-vm`, `matrix.session-compile`, `matrix.session` and +`matrix.session-contract`, covering typed restoration, source/request binding +lookup, rollback, cancellation, resource accounting, option isolation and shell +input boundaries. Their presence defines the checks to run; it does not qualify +a native Anomalous runtime or a host authority adapter. diff --git a/matrix/README.md b/matrix/README.md index 51d6b8d1..0819d826 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -29,7 +29,7 @@ which. | Front-end integration plan | [`docs/front-end-plan.md`](docs/front-end-plan.md) | | Next-version findings and validation notes | [`docs/next-version-findings.md`](docs/next-version-findings.md) — confirmed limitations, design friction, fixes, and acceptance checks | | Sample programs | [`samples/`](samples/) | -| Shell profile | [Pure submission checking](../docs/tools/matrix-submissions.md) for Matrix and NILData requests is implemented; execution, sessions and Anomalous adapters remain [proposed](../docs/design/NIL-0018-matrix-shell-profile.md) | +| Shell profile | [Pure submissions and sessions](../docs/tools/matrix-submissions.md) provide Matrix/NILData checking, bounded hosted VM evaluation and retained immutable values; host commands and native Anomalous execution remain [proposed](../docs/design/NIL-0018-matrix-shell-profile.md) | | Lexer, parser, lowering | **Implemented through stage 6** — see [`docs/front-end-plan.md`](docs/front-end-plan.md) for the stage-by-stage status and exit evidence | Source files use the `.matrix` extension, or `.mat` as the short form. Both diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 113f491d..783699eb 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2085,8 +2085,8 @@ patched version. See the [upstream advisory](https://github.com/AzureAD/microsof ### F70 — A shell profile needs session semantics and named structured rows **Observation:** Matrix already supplies named calls, checked results and eager -queries, but its parser accepts complete books/paragraphs rather than prompt -submissions. The README previously implied that shell grammar support shipped; +queries, but its parser initially accepted complete books/paragraphs rather than +prompt submissions. The README previously implied that shell grammar support shipped; that status has been corrected. The VM's program load resets state, so replaying prior submissions to recreate bindings would also replay their effects. @@ -2101,9 +2101,9 @@ state needs explicit ownership and publication rules. proposes Matrix as the language surface for Anomalous's existing Canticle session model. A fixed-data example passes text NIL, binary NIL and LLVM AOT routes. It is an ordinary hosted Matrix program. The subsequent admission slice implements -submission parsing and pure AST/NIL profile verification (F71); execution -resource enforcement, real service adapters and native Anomalous execution -remain open. +submission parsing and pure AST/NIL profile verification (F71), followed by +bounded hosted evaluation and owned retained bindings (F72). Real service +adapters and native Anomalous execution remain open. Anomalous already has newer program-descriptor scaffolding than its initial runtime handoff describes, but no live NIL execution in that profile. Its runtime @@ -2139,8 +2139,80 @@ offset changes; Windows runtime qualification still belongs to its platform CI. **Remaining friction:** A checked expression can still fail at runtime, and bounded syntax/instruction counts do not bound allocation or work inside an operation. The first profile therefore excludes all calls and queries, even -otherwise pure library operations. A bounded evaluator, typed value projection, -retained-binding ownership and command catalogs are the next steps. The request +otherwise pure library operations. F72 adds bounded evaluation, typed projection +and owned retained bindings; command catalogs remain future work. The request schema initially covers expression bindings and a final value, not every Matrix statement or formatting shorthand. Adding either route must preserve the shared profile and diagnostic contract. + + +### F72 — Session state needs owned values and atomic publication + +**Observation:** The VM resets its heap and globals when loading a program. +Replaying earlier submissions would recompute their expressions, and retaining +VM handles would couple old values to a discarded heap. A successful type check +also cannot guarantee that execution, result export or retained-state budgets +will succeed. + +**Implemented:** The hosted pure session exports exact typed, owned data and +restores it as literal AST initializers in the next submission. It preserves +scalar widths, finite float round trips, negative zero, concrete empty arrays +and nested tuple/array shapes. Matrix and NILData input use the same session +bindings with Matrix folded-name resolution. Prior computation is never replayed, +and no source text is reconstructed from values. + +Only new top-level bindings are returned for publication. The host checks the +complete result, cumulative state, compiler restorability and serialized report +before swapping in the new state. Parse/type/profile errors, runtime failure, +nonfinite results, exhausted budgets and cancellation publish nothing. The VM +revalidates admitted programs and applies instruction, logical work, text and +snapshot limits. Shell `:begin`/`:submit` blocks make several input lines one +transaction; `:cancel` discards pending input. + +**Remaining friction:** Restoring data through literal AST nodes increases +compilation cost with retained state and consumes admission budgets. Successful +state publication therefore checks that the whole candidate remains restorable. +A direct typed data import could reduce this work but must preserve the same +ownership and exact-shape checks. Limits are cooperative logical bounds, not +process RSS limits or hard preemption; initial compilation is outside the +execution/publication deadline. The CLI stores no persistent history. Host +catalogs, observations, queries/calls in the pure profile and Anomalous native +execution remain absent. See the [session contract](../../docs/tools/matrix-submissions.md). + +### F73 — Array indexing needs one checked failure contract + +**Observation:** Existing shared array indexing has inconsistent failure +semantics: an out-of-range scalar/text array read returns its default value +(zero, false or empty text), while a tuple-array read reports an error. For +example, `[1] at 2` evaluates to zero, but `[(1, true)] at 2` fails. This behavior +predates the shell; introducing the evaluator made the inconsistency visible at +an interactive boundary. + +**Current handling:** The pure evaluator preserves the shared language behavior. +A tuple-array failure rolls back the complete submission, including any earlier +new bindings in that submission. No shell-specific indexing rule has been added. + +**Follow-up:** Establish a shared checked indexing API or language contract with +explicit success/failure values and consistent VM/native behavior. Test negative +indexes, exact-end indexes, empty arrays and each admitted element shape. Avoid +silently replacing a missing row with a valid-looking default while documenting +how existing default-returning indexing remains compatible or migrates. + +### F74 — Nested generic resolution repeated work exponentially + +**Observation:** The session corpus exposed a compiler stall on a small nested +array expression. Shared `type_checker::resolve_type()` recursively resolved +each generic argument once to build the canonical name, then resolved it again +for instantiation. Built-in arrays do not cache a nominal instantiation, so each +additional nesting level doubled that repeated work. The issue affected normal +checking as well as submission compilation; input-size and nesting ceilings did +not make this implementation cost reasonable. + +**Fixed:** Generic instantiation reuses the arguments already resolved while +forming the canonical name. The change preserves type semantics and existing +profile depth ceilings. A 24-level nested-array regression exercises check-only +admission, session compilation and retained-data restoration; the CLI corpus +also exercises 20 levels. A local 20-level check fell from approximately 9.8 +seconds before the fix to 0.03 seconds afterward. This is a regression +observation, not a portable benchmark guarantee; the tests guard the algorithmic +path without asserting a machine-specific latency target. diff --git a/nilcompiler/CMakeLists.txt b/nilcompiler/CMakeLists.txt index 529812eb..3b95ef0d 100644 --- a/nilcompiler/CMakeLists.txt +++ b/nilcompiler/CMakeLists.txt @@ -33,6 +33,9 @@ set(NILCOMPILER_CORE_SOURCES src/matrix_submission.cpp src/submission_profile.cpp src/submission_request.cpp + src/submission_session.cpp + src/submission_session_compile.cpp + src/submission_session_cli.cpp src/codegen.cpp src/vm.cpp src/preprocessor.cpp diff --git a/nilcompiler/src/main.cpp b/nilcompiler/src/main.cpp index 9eed31da..9368ede5 100644 --- a/nilcompiler/src/main.cpp +++ b/nilcompiler/src/main.cpp @@ -18,6 +18,7 @@ #include "matrix_diagnostics.hpp" #include "matrix_parser.hpp" #include "matrix_submission.hpp" +#include "submission_session_cli.hpp" #include "parser.hpp" #include "type_checker.hpp" #include "executable_context.hpp" @@ -389,6 +390,9 @@ static void print_usage(std::ostream &out = std::cerr) { << " nilcompiler --list-analysis-rules List built-in analyzer rules as JSON\n" << " nilcompiler --check-submission Check a pure Matrix submission; no execution\n" << " nilcompiler --check-submission-request Check a NILData submission request\n" + << " nilcompiler --evaluate-submission Evaluate a bounded pure Matrix submission\n" + << " nilcompiler --evaluate-submission-request Evaluate a NILData submission request\n" + << " nilcompiler --matrix-shell Start a bounded pure Matrix session\n" << " nilcompiler --to-nildata \n" << " nilcompiler --to-json \n" << " nilcompiler --import-nydata \n" @@ -651,17 +655,25 @@ static int convert_nildata(const std::string &operation, const std::string &path } static int compile_main(int argc, char *argv[], ny::analysis_session *analysis) { - // Submission inspection never enters ordinary import discovery, compilation - // output handling, bundling, JIT, or execution. Refuse mixed command modes. + // Submission commands use their own admission and bounded evaluation paths. + // They never enter ordinary import discovery, output handling or JIT. for (int i = 1; i < argc; ++i) { const std::string option = argv[i]; if (option == "--") break; - if (option != "--check-submission" && + const bool shell = option == "--matrix-shell"; + const bool evaluate = option == "--evaluate-submission" || + option == "--evaluate-submission-request"; + if (!shell && !evaluate && option != "--check-submission" && option != "--check-submission-request") continue; - if (argc != 3 || i != 1 || analysis) { - std::cerr << "Error: use nilcompiler " << option << " alone\n"; + if (argc != (shell ? 2 : 3) || i != 1 || analysis) { + std::cerr << "Error: use nilcompiler " << option + << (shell ? "" : " ") << " alone\n"; return 1; } + if (shell) return matrix::run_matrix_shell_cli(); + if (evaluate) + return matrix::run_submission_evaluate_cli( + option == "--evaluate-submission-request", argv[2]); return matrix::run_submission_check_cli( option == "--check-submission-request", argv[2]); } diff --git a/nilcompiler/src/matrix_lexer.cpp b/nilcompiler/src/matrix_lexer.cpp index 22537c42..4bde8834 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -187,9 +187,9 @@ char lexer::advance() { } void lexer::error(int line, int col, std::string message, std::string hint, - bool incomplete) { + bool incomplete, bool open_text_block) { errors_.push_back({line, col, std::move(message), std::move(hint), incomplete, - token_start_}); + token_start_, open_text_block}); } token lexer::make(token_kind kind, const std::string &lexeme, int line, @@ -482,7 +482,7 @@ token lexer::scan_text_block(int line, int col) { } if (!terminated) { error(line, col, "unterminated 'begin text' block", - "close it with a line whose only content is 'end text'", true); + "close it with a line whose only content is 'end text'", true, true); return make(token_kind::invalid, "", line, col); } diff --git a/nilcompiler/src/matrix_lexer.hpp b/nilcompiler/src/matrix_lexer.hpp index d067221a..f9ce3d65 100644 --- a/nilcompiler/src/matrix_lexer.hpp +++ b/nilcompiler/src/matrix_lexer.hpp @@ -170,6 +170,8 @@ struct lex_error { // True only when appending input can complete the lexical construct. bool incomplete = false; std::size_t start = 0; + // At EOF inside raw text, subsequent lines are payload, not shell commands. + bool open_text_block = false; }; // Fold one identifier to its lookup key: ASCII-lowercase, with every '-' and @@ -229,7 +231,7 @@ class lexer { bool text_block_follows() const; token scan_backtick_identifier(); void error(int line, int col, std::string message, std::string hint = {}, - bool incomplete = false); + bool incomplete = false, bool open_text_block = false); }; } // namespace matrix diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 21782304..9358c9c7 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -149,7 +149,7 @@ std::string nil_path(const std::string &written) { } // namespace parser::parser(const std::string &source, const parser_options &opts) - : filename_(opts.filename), signature_cursor_(opts.signature_cursor), + : filename_(opts.filename), external_names_(opts.external_names), signature_cursor_(opts.signature_cursor), source_size_(source.size()), submission_requested_(opts.submission) { if (opts.submission && source.size() > submission_source_limit) { token eof; @@ -1437,6 +1437,8 @@ submission_parse_result parser::parse_submission() { // heuristics for book declarations must not turn those bindings into types. declared_.clear(); declared_types_.clear(); + for (const auto &name : external_names_) + declared_.emplace(fold_key(name), nil_symbol(name)); prescan_declarations(true); signature_cursor_.reset(); signature_blank_start_.reset(); diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index 780ced23..c378b83f 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -64,6 +64,8 @@ struct parser_options { // Set before construction for untrusted interactive input: unlike a page, // a submission is bounded before the constructor starts lexing it. bool submission = false; + // Existing immutable session names, in their original NIL spelling. + std::vector external_names; }; inline constexpr std::size_t submission_source_limit = 64 * 1024; @@ -114,6 +116,7 @@ class parser { std::vector diagnostics_; std::vector rich_; std::string filename_; + std::vector external_names_; std::optional signature_cursor_, signature_blank_start_; bool recovered_signature_call_ = false; std::size_t source_size_ = 0, submission_depth_ = 0; diff --git a/nilcompiler/src/matrix_submission.cpp b/nilcompiler/src/matrix_submission.cpp index c9c1a517..45985d4f 100644 --- a/nilcompiler/src/matrix_submission.cpp +++ b/nilcompiler/src/matrix_submission.cpp @@ -215,8 +215,8 @@ std::string submission_report_json(const submission_report &report) { auto item = json::map(); item.object["stage"] = json::str(diagnostic.stage); item.object["code"] = json::str(diagnostic.code); - item.object["message"] = json::str(diagnostic.message); - item.object["location"] = json::str(diagnostic.location); + item.object["message"] = json::str(diagnostic_text(diagnostic.message)); + item.object["location"] = json::str(diagnostic_text(diagnostic.location)); for (const auto &entry : {std::make_pair("line", diagnostic.line), std::make_pair("column", diagnostic.column), std::make_pair("length", diagnostic.length)}) { diff --git a/nilcompiler/src/submission_request.cpp b/nilcompiler/src/submission_request.cpp index 016171bc..5b425484 100644 --- a/nilcompiler/src/submission_request.cpp +++ b/nilcompiler/src/submission_request.cpp @@ -250,7 +250,12 @@ class decoder { } public: - decoded_submission_request decode(const json &root) { + decoded_submission_request decode(const json &root, const std::vector &existing_names) { + for (const auto &existing : existing_names) { + const auto spelling = identifier(json::str(existing), "$session.bindings"); + if (!symbols_.emplace(fold_key(spelling), nil_symbol(spelling)).second) + fail("$session.bindings", "duplicate existing binding after Matrix name normalization"); + } reject_nul(root, "$"); fields(root, "$", {"schema", "profile", "bindings", "value"}); if (text(root.at("schema"), "$.schema") != "nil.matrix.submission-request.v1") @@ -283,7 +288,8 @@ class decoder { }; } // namespace -decoded_submission_request decode_submission_request(const std::string &source) { +decoded_submission_request decode_submission_request( + const std::string &source, const std::vector &existing_names) { if (source.size() > max_source_bytes) fail("$", "request exceeds 64 KiB"); if (source.find('\0') != std::string::npos) fail("$", "embedded NUL is not supported"); json root; @@ -293,6 +299,6 @@ decoded_submission_request decode_submission_request(const std::string &source) } catch (const std::runtime_error &error) { fail("$", error.what()); } - return decoder{}.decode(root); + return decoder{}.decode(root, existing_names); } } // namespace matrix diff --git a/nilcompiler/src/submission_request.hpp b/nilcompiler/src/submission_request.hpp index bb8f05ad..b570a895 100644 --- a/nilcompiler/src/submission_request.hpp +++ b/nilcompiler/src/submission_request.hpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace matrix { @@ -28,7 +29,8 @@ struct submission_request_error : std::runtime_error { // NILData's own document nesting limit also applies. Names are one unescaped // Matrix identifier, with ordinary Matrix case/separator-folded lookup. A node's // source_file is its request path; line 0 denotes the absence of source lines. -decoded_submission_request decode_submission_request(const std::string &source); +decoded_submission_request decode_submission_request( + const std::string &source, const std::vector &existing_names = {}); } // namespace matrix #endif diff --git a/nilcompiler/src/submission_session.cpp b/nilcompiler/src/submission_session.cpp new file mode 100644 index 00000000..4d240958 --- /dev/null +++ b/nilcompiler/src/submission_session.cpp @@ -0,0 +1,198 @@ +#include "submission_session.hpp" +#include "nil_loader.hpp" +#include "submission_profile.hpp" +#include "vm.hpp" +#include "../../common/strict_json.hpp" + +#include +#include +#include + +namespace matrix { +namespace { +using nil::detail::json; + +json count(std::size_t value) { + json result; + result.type = json::kind::number; + result.text = std::to_string(value); + return result; +} + +json value_json(const ny::submission_value &value) { + auto result = json::map(); + result.object["type"] = json::str(value.type); + if (value.type.rfind("array<", 0) == 0 || value.type.rfind("tuple<", 0) == 0) { + auto items = json::list(); + for (const auto &child : value.elements) items.array.push_back(value_json(child)); + result.object["elements"] = std::move(items); + } else result.object["scalar"] = json::str(value.scalar); + return result; +} + +[[noreturn]] void budget(const std::string &message) { + throw ny::pure_execution_error(ny::pure_execution_error::kind::budget, message); +} + +void validate_state(const std::vector &bindings, + const session_limits &limits) { + std::size_t nodes = 0, bytes = 0; + const auto charge = [&](std::size_t amount) { + if (amount > limits.max_state_bytes - bytes) budget("retained session byte budget exceeded"); + bytes += amount; + }; + const auto visit = [&](const auto &self, const ny::submission_value &value, unsigned depth) -> void { + if (++nodes > limits.max_state_nodes || depth > 32) budget("retained session value budget exceeded"); + charge(value.type.size()); charge(value.scalar.size()); + for (const auto &child : value.elements) self(self, child, depth + 1); + }; + for (const auto &binding : bindings) { + charge(binding.name.size()); + visit(visit, binding.value, 0); + } +} + +void failure(evaluation_report &report, const std::string &status, + const std::string &message, const std::string &filename, int line) { + report.check.status = status; + report.check.nil_text.clear(); + report.value.reset(); + report.added.clear(); + report.committed = false; + auto bounded = message.substr(0, 4096); + if (message.size() > bounded.size()) { + while (!bounded.empty() && (static_cast(message[bounded.size()]) & 0xc0) == 0x80) + bounded.pop_back(); + bounded += "..."; + } + report.check.diagnostics.push_back({"runtime", status == "budget-exceeded" ? "MS6002" : + status == "cancelled" ? "MS6003" : "MS6001", std::move(bounded), filename, line, 0, 0}); +} +} // namespace + +submission_session::submission_session(session_limits limits) : limits_(std::move(limits)) { + if (!limits_.max_state_bytes || limits_.max_state_bytes > 1024 * 1024 || + !limits_.max_state_nodes || limits_.max_state_nodes > 1024 || + !limits_.max_report_bytes || limits_.max_report_bytes > 1024 * 1024 || + !limits_.max_execution_ms || limits_.max_execution_ms > 10000) + throw std::invalid_argument("session limits must be positive and within the hosted profile ceilings"); + ny::VM validation; + validation.configurePureExecution(limits_.execution); +} + +evaluation_report submission_session::evaluate(const std::string &source, bool request, + const std::string &filename) { + evaluation_report report; + report.binding_count = bindings_.size(); + auto prepared = prepare_session_submission(source, request, filename, bindings_); + report.check = std::move(prepared.report); + if (report.check.status != "complete") return report; + ny::VM vm; + int line = 0; + try { + if (!prepared.module) throw std::runtime_error("checked submission has no executable module"); + // Recheck the actual artifact at the execution boundary. The public checker + // report and its text cannot be presented as proof of admission. + ny::validate_nil_submission_profile(*prepared.module); + ny::codegen_options options; + options.include_debug_info = false; + options.include_source_debug = false; + std::ostringstream bytes(std::ios::out | std::ios::binary); + ny::nil_binary_writer writer(bytes, options); + writer.emit_binary_module(*prepared.module); + const auto binary = bytes.str(); + if (binary.size() > 2 * 1024 * 1024) budget("compiled submission binary budget exceeded"); + std::istringstream input(binary, std::ios::in | std::ios::binary); + std::unordered_map constants; + const auto program = ny::parseBinaryProgram(input, constants); + vm.configurePureExecution(limits_.execution); + vm.loadProgram(program, constants); + vm.resetExecution("__nil_submission"); + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(limits_.max_execution_ms); + do { + if (std::chrono::steady_clock::now() >= deadline) budget("submission execution deadline exceeded"); + if (vm.getPC() < vm.getProgram().size()) line = vm.getProgram()[vm.getPC()].line; + } while (vm.stepInstruction()); + report.instructions_executed = vm.pureInstructionsExecuted(); + report.executed = report.instructions_executed != 0; + const auto expected = prepared.binding_names.size() + (prepared.has_value ? 1 : 0); + if (!expected) { + if (!vm.getStack().empty()) throw std::runtime_error("void submission left an unexpected value"); + } else { + if (vm.getStack().size() != 1) throw std::runtime_error("submission returned an invalid value count"); + auto result = vm.snapshotPureValue(vm.getStack().back(), prepared.module->functions.front().return_type); + if (result.type.rfind("tuple<", 0) != 0 || result.elements.size() != expected) + throw std::runtime_error("submission returned an invalid result envelope"); + std::size_t index = 0; + if (prepared.has_value) { + report.value = std::move(result.elements[index++]); + if (report.value->type != report.check.result_type) + throw std::runtime_error("submission result does not match the checked type"); + } + for (const auto &name : prepared.binding_names) + report.added.push_back({name, std::move(result.elements[index++])}); + } + auto candidate = bindings_; + candidate.insert(candidate.end(), report.added.begin(), report.added.end()); + validate_state(candidate, limits_); + // A retained value must remain representable through the admitted shared + // compiler pipeline. This compiles data only, never previous computations. + if (!report.added.empty()) { + const auto restorable = prepare_session_submission("", false, "", candidate); + if (restorable.report.status != "complete") + budget("retained values exceed the compiler restoration profile"); + } + if (limits_.execution.cancelled && limits_.execution.cancelled()) + throw ny::pure_execution_error(ny::pure_execution_error::kind::cancelled, "submission cancelled before publication"); + if (std::chrono::steady_clock::now() >= deadline) + budget("submission execution/publication deadline exceeded"); + report.binding_count = candidate.size(); + report.committed = true; + // Validate projection before publication: failure cannot partially publish + // bindings that a client never received successfully. + if (evaluation_report_json(report).size() > limits_.max_report_bytes) + budget("submission result report budget exceeded"); + if (std::chrono::steady_clock::now() >= deadline) + budget("submission result projection deadline exceeded"); + bindings_.swap(candidate); + return report; + } catch (const ny::pure_execution_error &error) { + failure(report, error.reason == ny::pure_execution_error::kind::cancelled ? + "cancelled" : "budget-exceeded", error.what(), filename, line); + } catch (const std::exception &error) { + failure(report, "runtime-error", error.what(), filename, line); + } + report.instructions_executed = vm.pureInstructionsExecuted(); + report.executed = report.instructions_executed != 0; + report.binding_count = bindings_.size(); + return report; +} + +std::string submission_value_json(const ny::submission_value &value) { + return nil::detail::dump(value_json(value)); +} + +std::string evaluation_report_json(const evaluation_report &report) { + // Reuse the existing bounded UTF-8 diagnostic projection and field contract. + auto checked = report.check; + checked.nil_text.clear(); + auto out = nil::detail::json_parser(submission_report_json(checked)).parse(); + out.object.erase("nil"); + out.object["schema"] = json::str("nil.matrix.submission-evaluation.v1"); + out.object["executed"] = json::flag(report.executed); + out.object["committed"] = json::flag(report.committed); + out.object["value"] = report.value ? value_json(*report.value) : json{}; + out.object["binding_count"] = count(report.binding_count); + out.object["instructions_executed"] = count(report.instructions_executed); + auto added = json::list(); + for (const auto &binding : report.added) { + auto item = json::map(); + item.object["name"] = json::str(binding.name); + item.object["value"] = value_json(binding.value); + added.array.push_back(std::move(item)); + } + out.object["added"] = std::move(added); + return nil::detail::dump(out); +} +} // namespace matrix diff --git a/nilcompiler/src/submission_session.hpp b/nilcompiler/src/submission_session.hpp new file mode 100644 index 00000000..f8c74aed --- /dev/null +++ b/nilcompiler/src/submission_session.hpp @@ -0,0 +1,45 @@ +#ifndef NIL_SUBMISSION_SESSION_HPP +#define NIL_SUBMISSION_SESSION_HPP + +#include "submission_session_compile.hpp" +#include + +namespace matrix { + +struct session_limits { + ny::pure_execution_limits execution; + std::size_t max_state_bytes = 1024 * 1024; + std::size_t max_state_nodes = 1024; + std::size_t max_report_bytes = 1024 * 1024; + std::size_t max_execution_ms = 1000; +}; + +struct evaluation_report { + submission_report check; + bool executed = false; + bool committed = false; + std::optional value; + std::vector added; + std::size_t instructions_executed = 0; + std::size_t binding_count = 0; +}; + +// One thread owns a session. Only fully checked owned data crosses transactions; +// each evaluation uses a new VM and publishes all new bindings atomically. +class submission_session { +public: + explicit submission_session(session_limits limits = {}); + evaluation_report evaluate(const std::string &source, bool request = false, + const std::string &filename = ""); + void reset() { bindings_.clear(); } + const std::vector &bindings() const { return bindings_; } +private: + session_limits limits_; + std::vector bindings_; +}; + +std::string submission_value_json(const ny::submission_value &value); +std::string evaluation_report_json(const evaluation_report &report); + +} // namespace matrix +#endif diff --git a/nilcompiler/src/submission_session_cli.cpp b/nilcompiler/src/submission_session_cli.cpp new file mode 100644 index 00000000..db0162d2 --- /dev/null +++ b/nilcompiler/src/submission_session_cli.cpp @@ -0,0 +1,361 @@ +#include "submission_session_cli.hpp" + +#include "submission_session.hpp" +#include "matrix_lexer.hpp" +#include "secure_file_io.hpp" +#include "../../common/strict_json.hpp" + +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#include +#else +#include +#endif + +namespace matrix { +namespace { +using nil::detail::json; + +void binary_stdin() { +#ifdef _WIN32 + if (_setmode(_fileno(stdin), _O_BINARY) == -1) + throw std::runtime_error("cannot enable binary submission stdin"); +#endif +} + +bool terminal() { +#ifdef _WIN32 + return _isatty(_fileno(stdin)) && _isatty(_fileno(stdout)); +#else + return isatty(fileno(stdin)) && isatty(fileno(stdout)); +#endif +} + +std::string safe_text(const std::string &value) { + try { + nil::detail::valid_utf8(value); + return value; + } catch (const std::exception &) { + constexpr char hex[] = "0123456789abcdef"; + std::string out; + for (const unsigned char byte : value) { + if (byte < 0x80) out += static_cast(byte); + else { + out += "\\x"; + out += hex[byte >> 4]; + out += hex[byte & 15]; + } + } + return out; + } +} + +evaluation_report input_error(const std::string &message, const std::string &location, + std::size_t binding_count, bool request = false, + bool incomplete = false) { + evaluation_report report; + report.check.input_kind = request ? "nildata-request" : "matrix"; + report.check.status = incomplete ? "incomplete" : "invalid"; + report.check.diagnostics.push_back({"input", "MS5001", safe_text(message), + safe_text(location), 0, 0, 0}); + report.binding_count = binding_count; + return report; +} + +int exit_status(const evaluation_report &report) { + return report.check.status == "complete" ? 0 : report.check.status == "incomplete" ? 2 : 1; +} + +std::string terminal_quote(const std::string &text) { + const auto quoted = nil::detail::quote(safe_text(text)); + std::string out; + constexpr char hex[] = "0123456789abcdef"; + for (std::size_t i = 0; i < quoted.size();) { + const auto start = i; + const auto first = static_cast(quoted[i++]); + unsigned point = first; + unsigned continuation = 0; + if (first >= 0xf0) { point &= 7; continuation = 3; } + else if (first >= 0xe0) { point &= 15; continuation = 2; } + else if (first >= 0xc0) { point &= 31; continuation = 1; } + while (continuation--) + point = (point << 6) | (static_cast(quoted[i++]) & 63); + // JSON already quotes C0 controls. Also escape terminal C1 controls and + // invisible directional/separator characters that can disguise output. + if ((point >= 0x7f && point <= 0x9f) || point == 0x61c || + (point >= 0x200b && point <= 0x200f) || + (point >= 0x2028 && point <= 0x202e) || + (point >= 0x2060 && point <= 0x206f) || point == 0xfeff) { + out += "\\u"; + for (int shift = 12; shift >= 0; shift -= 4) out += hex[(point >> shift) & 15]; + } else out.append(quoted, start, i - start); + } + return out; +} + +std::string terminal_text(const std::string &text) { + const auto quoted = terminal_quote(text); + return quoted.substr(1, quoted.size() - 2); +} + +std::string display_value(const ny::submission_value &value) { + const bool array = value.type.rfind("array<", 0) == 0; + const bool tuple = value.type.rfind("tuple<", 0) == 0; + if (!array && !tuple) + return value.type == "text" ? terminal_quote(value.scalar) : terminal_text(value.scalar); + std::string out = array ? "[" : "("; + for (std::size_t i = 0; i < value.elements.size(); ++i) { + if (i) out += ", "; + out += display_value(value.elements[i]); + } + if (tuple && value.elements.size() == 1) out += ','; + return out + (array ? "]" : ")"); +} + +void display_binding(const submission_binding &binding) { + std::cout << terminal_text(binding.name) << " = " << display_value(binding.value) + << " : " << terminal_text(binding.value.type) << '\n'; +} + +void print(const evaluation_report &report, bool interactive = false) { + if (!interactive) { + std::cout << evaluation_report_json(report) << '\n'; + return; + } + if (report.check.status == "complete") { + if (report.value) + std::cout << display_value(*report.value) << " : " << terminal_text(report.value->type) << '\n'; + for (const auto &binding : report.added) display_binding(binding); + if (!report.value && report.added.empty()) std::cout << "ok\n"; + return; + } + for (const auto &diagnostic : report.check.diagnostics) { + std::cout << terminal_text(report.check.status) << ": " << terminal_text(diagnostic.message); + if (!diagnostic.location.empty()) { + std::cout << " (" << terminal_text(diagnostic.location); + if (diagnostic.line > 0) { + std::cout << ':' << diagnostic.line; + if (diagnostic.column > 0) std::cout << ':' << diagnostic.column; + } + std::cout << ')'; + } + std::cout << '\n'; + } + if (report.check.diagnostics.empty()) std::cout << terminal_text(report.check.status) << '\n'; +} + +std::string read_source(const std::string &path) { + if (path != "-") { + const auto input = ny::detail::read_regular_file_bounded(path, submission_max_input_bytes); + if (!input.ok) throw std::runtime_error(input.error); + return std::string(input.bytes.begin(), input.bytes.end()); + } + binary_stdin(); + std::string source; + char byte; + while (std::cin.get(byte)) { + if (source.size() == submission_max_input_bytes) + throw std::runtime_error("submission input exceeds 65536 bytes"); + source += byte; + } + if (!std::cin.eof()) throw std::runtime_error("cannot read submission input"); + return source; +} + +struct shell_line { + std::string text; + bool present = false, newline = false, oversized = false; +}; + +shell_line read_line() { + shell_line result; + char byte; + while (std::cin.get(byte)) { + result.present = true; + if (byte == '\n') { + result.newline = true; + return result; + } + // Keep draining an oversized physical line without growing its buffer. + if (result.text.size() == submission_max_input_bytes) result.oversized = true; + else result.text += byte; + } + if (!std::cin.eof()) throw std::runtime_error("cannot read Matrix shell input"); + return result; +} + +bool open_text_block(const std::string &source) { + lexer scanner(source, 0, true); + (void)scanner.scan(); + for (const auto &error : scanner.errors()) + if (error.open_text_block) return true; + return false; +} + +void print_bindings(const submission_session &session, bool interactive) { + if (interactive) { + if (session.bindings().empty()) std::cout << "No retained bindings.\n"; + for (const auto &binding : session.bindings()) display_binding(binding); + return; + } + // Values are already validated, owned data. Compose their canonical JSON + // directly: reparsing typed value objects would impose a second, lower + // nesting limit because each value adds both an object and an elements array. + std::string report = "{\"schema\":\"nil.matrix.session-bindings.v1\",\"bindings\":["; + bool first = true; + for (const auto &binding : session.bindings()) { + if (!first) report += ','; + first = false; + report += "{\"name\":" + nil::detail::quote(binding.name) + + ",\"value\":" + submission_value_json(binding.value) + "}"; + } + report += "],\"binding_count\":" + std::to_string(session.bindings().size()) + "}"; + std::cout << report << '\n'; +} + +void help(bool interactive) { + const std::pair commands[] = { + {":begin", "Begin an atomic submission; nothing runs until :submit."}, + {":submit", "Evaluate the pending atomic submission."}, + {":cancel", "Discard pending input."}, + {":bindings", "List retained names and typed values."}, + {":reset", "Clear retained values and pending input."}, + {":quit", "Exit and discard pending input."}, + {":help", "Show these commands."}}; + if (interactive) { + std::cout << "Matrix pure shell. Complete lines evaluate immediately; incomplete input continues.\n"; + for (const auto &command : commands) + std::cout << command.first << " " << command.second << '\n'; + return; + } + auto report = json::map(); + report.object["schema"] = json::str("nil.matrix.shell-help.v1"); + auto entries = json::list(); + for (const auto &command : commands) { + auto entry = json::map(); + entry.object["command"] = json::str(command.first); + entry.object["description"] = json::str(command.second); + entries.array.push_back(std::move(entry)); + } + report.object["commands"] = std::move(entries); + std::cout << nil::detail::dump(report) << '\n'; +} +} // namespace + +int run_submission_evaluate_cli(bool request, const std::string &path) { + evaluation_report report; + try { + submission_session session; + report = session.evaluate(read_source(path), request, path); + } catch (const std::exception &error) { + report = input_error(error.what(), path, 0, request); + } + print(report); + return exit_status(report); +} + +int run_matrix_shell_cli() { + submission_session session; + const bool interactive = terminal(); + bool failed = false, explicit_block = false, discarding = false; + std::string pending; + std::optional incomplete; + const auto clear = [&] { + pending.clear(); + incomplete.reset(); + explicit_block = false; + discarding = false; + }; + const auto reject = [&](const std::string &message) { + print(input_error(message, "", session.bindings().size()), interactive); + failed = true; + }; + const auto evaluate = [&] { + auto report = session.evaluate(pending, false, ""); + if (report.check.status == "incomplete") { + incomplete = std::move(report); + if (explicit_block) print(*incomplete, interactive); + return; + } + print(report, interactive); + failed |= exit_status(report) != 0; + clear(); + }; + try { + binary_stdin(); + if (interactive) help(true); + for (;;) { + if (interactive) { + std::cout << (discarding ? "discard> " : explicit_block ? "block> " : pending.empty() ? "matrix> " : "...> "); + std::cout.flush(); + } + auto line = read_line(); + if (!line.present) break; + if (line.oversized) { + reject("submission line exceeds 65536 bytes; pending input discarded"); + pending.clear(); incomplete.reset(); + // The unbuffered suffix might contain a raw-text opener. Require an + // explicit recovery command before interpreting any following line. + discarding = true; + continue; + } + auto command = line.text; + if (!command.empty() && command.back() == '\r') command.pop_back(); + const bool literal_line = !discarding && !pending.empty() && + !command.empty() && command.front() == ':' && open_text_block(pending); + if (!literal_line) { + if (command == ":quit") return interactive ? 0 : failed ? 1 : 0; + if (command == ":help") { help(interactive); continue; } + if (command == ":bindings") { print_bindings(session, interactive); continue; } + if (command == ":cancel") { clear(); continue; } + if (command == ":reset") { session.reset(); clear(); continue; } + if (command == ":submit") { + if (discarding) { clear(); continue; } + if (!explicit_block && pending.empty()) { reject("no pending submission to submit"); continue; } + evaluate(); + continue; + } + if (discarding) continue; + if (command == ":begin") { + if (explicit_block || !pending.empty()) reject("pending input already exists; submit or cancel it first"); + else explicit_block = true; + continue; + } + if (!command.empty() && command.front() == ':') { + reject("unknown shell command; use :help"); + continue; + } + } + if (pending.empty() && !explicit_block && line.text.find_first_not_of(" \t\r") == std::string::npos) + continue; + const auto bytes = line.text.size() + (line.newline ? 1 : 0); + if (bytes > submission_max_input_bytes - pending.size()) { + reject("submission input exceeds 65536 bytes; pending input discarded"); + discarding = true; + pending.clear(); incomplete.reset(); + continue; + } + pending += line.text; + if (line.newline) pending += '\n'; + if (!explicit_block) evaluate(); + } + if (explicit_block && !discarding) { + print(input_error("atomic submission is pending; use :submit or :cancel", "", + session.bindings().size(), false, true), interactive); + return failed ? 1 : 2; + } + if (incomplete) { + print(*incomplete, interactive); + return failed ? 1 : 2; + } + } catch (const std::exception &error) { + reject(error.what()); + } + return failed ? 1 : 0; +} +} // namespace matrix diff --git a/nilcompiler/src/submission_session_cli.hpp b/nilcompiler/src/submission_session_cli.hpp new file mode 100644 index 00000000..406c2b53 --- /dev/null +++ b/nilcompiler/src/submission_session_cli.hpp @@ -0,0 +1,10 @@ +#ifndef NIL_MATRIX_SUBMISSION_SESSION_CLI_HPP +#define NIL_MATRIX_SUBMISSION_SESSION_CLI_HPP + +#include + +namespace matrix { +int run_submission_evaluate_cli(bool request, const std::string &path); +int run_matrix_shell_cli(); +} // namespace matrix +#endif diff --git a/nilcompiler/src/submission_session_compile.cpp b/nilcompiler/src/submission_session_compile.cpp new file mode 100644 index 00000000..613b0874 --- /dev/null +++ b/nilcompiler/src/submission_session_compile.cpp @@ -0,0 +1,314 @@ +#include "submission_session_compile.hpp" +#include "matrix_parser.hpp" +#include "submission_request.hpp" +#include "submission_profile.hpp" +#include "codegen.hpp" +#include "numeric_literal.hpp" +#include "type_checker.hpp" +#include "../../common/strict_json.hpp" + +#include +#include +#include +#include +#include +#include + +namespace matrix { +namespace { +constexpr std::size_t max_snapshot_nodes = 4096; +constexpr std::size_t max_snapshot_bytes = 1024 * 1024; + +void fail(const std::string &message) { throw std::runtime_error(message); } +std::string safe_text(const std::string &text) { + try { nil::detail::valid_utf8(text); return text; } + catch (const std::exception &) { + constexpr char hex[] = "0123456789abcdef"; + std::string result; + for (unsigned char byte : text) { + if (byte < 128) result.push_back(static_cast(byte)); + else { result += "\\x"; result.push_back(hex[byte >> 4]); result.push_back(hex[byte & 15]); } + } + return result; + } +} +void issue(submission_report &report, const std::string &stage, + const std::string &message, const std::string &location, + int line = 0, const std::string &code = "MS5001") { + if (report.diagnostics.size() >= 64) return; + auto text = safe_text(message); + if (text.size() > 4096) { + auto end = std::size_t{4096}; + while (end && (static_cast(text[end]) & 0xc0) == 0x80) --end; + text.resize(end); text += "..."; + } + report.diagnostics.push_back({stage, code, std::move(text), safe_text(location), line, 0, 0}); +} +void validate_name(const std::string &name) { + if (name.empty() || name.size() > 256 || nil_symbol(name) != name) + fail("session binding has an invalid canonical Matrix name"); + nil::detail::valid_utf8(name); + lexer scanner(name); + const auto tokens = scanner.scan(); + if (scanner.has_errors() || tokens.size() != 2 || + tokens[0].kind != token_kind::identifier || tokens[0].escaped_identifier || + tokens[0].start != 0 || tokens[0].length != name.size() || + tokens[0].lexeme != name || tokens[1].kind != token_kind::end_of_file) + fail("session bindings require an unescaped Matrix identifier"); +} + +struct type_shape { std::string name, spelling; std::vector children; }; +type_shape parse_shape(const std::string &type) { + if (type.empty() || type.size() > 4096) fail("invalid session value type"); + std::size_t at = 0, nodes = 0; + const auto parse = [&](const auto &self, unsigned depth) -> type_shape { + if (depth > 32 || ++nodes > 256) fail("session value type exceeds shape limits"); + const auto start = at; + while (at < type.size() && ((type[at] >= 'a' && type[at] <= 'z') || + (type[at] >= '0' && type[at] <= '9'))) ++at; + type_shape result{type.substr(start, at - start), {}, {}}; + if (result.name == "array" || result.name == "tuple") { + if (at == type.size() || type[at++] != '<') fail("invalid session collection type"); + do { + result.children.push_back(self(self, depth + 1)); + if (at == type.size()) fail("unterminated session collection type"); + if (type[at] == '>') { ++at; break; } + if (type[at++] != ',') fail("invalid session collection type separator"); + } while (true); + if (result.name == "array" && result.children.size() != 1) + fail("session arrays require exactly one element type"); + } else if (result.name != "i32" && result.name != "i64" && result.name != "u8" && + result.name != "f64" && result.name != "bool" && result.name != "text") { + fail("unsupported session value type"); + } + result.spelling = type.substr(start, at - start); + return result; + }; + auto result = parse(parse, 0); + if (at != type.size()) fail("session value type is not canonical"); + return result; +} + +class snapshot_literals { + std::size_t nodes = 0, bytes = 0; + template + std::shared_ptr make(const std::string &path, Args&&... args) { + auto node = std::make_shared(std::forward(args)...); + node->source_file = path; + return node; + } +public: + ny::ast_expr_ptr expression(const ny::submission_value &value, + const std::string &path, unsigned depth = 0) { + if (++nodes > max_snapshot_nodes || depth > 32) + fail("session snapshot exceeds value nesting or node limits"); + if (value.type.size() > max_snapshot_bytes - bytes) fail("session snapshot exceeds byte limit"); + bytes += value.type.size(); + if (value.scalar.size() > max_snapshot_bytes - bytes) fail("session snapshot exceeds byte limit"); + bytes += value.scalar.size(); + const auto type = parse_shape(value.type); + if (type.name == "array" || type.name == "tuple") { + if (!value.scalar.empty() || value.elements.size() > 256) + fail("invalid session collection payload"); + if (type.name == "tuple" && value.elements.size() != type.children.size()) + fail("session tuple payload does not match its type"); + std::vector elements; + for (std::size_t i = 0; i < value.elements.size(); ++i) { + const auto &expected = type.children[type.name == "array" ? 0 : i].spelling; + if (value.elements[i].type != expected) + fail("session collection element does not match its exact type"); + elements.push_back(expression(value.elements[i], path + "[" + std::to_string(i) + "]", depth + 1)); + } + if (type.name == "array") { + auto array = make(path, std::move(elements)); + array->inferred_type = value.type; // Preserves concrete empty arrays. + return array; + } + std::vector> fields; + for (std::size_t i = 0; i < elements.size(); ++i) + fields.emplace_back(std::to_string(i), std::move(elements[i])); + auto tuple = make(path, "tuple", std::move(fields)); + tuple->tuple_literal = true; + return tuple; + } + if (!value.elements.empty()) fail("scalar session value contains collection elements"); + if (type.name == "text") { + nil::detail::valid_utf8(value.scalar); + return make(path, value.scalar); + } + if (type.name == "bool") { + if (value.scalar != "true" && value.scalar != "false") fail("invalid session boolean payload"); + return make(path, value.scalar == "true"); + } + if (value.scalar.size() > 256) fail("session numeric payload exceeds limit"); + if (type.name == "f64") { + double parsed; + if (!ny::is_floating_literal_spelling(value.scalar) || + ny::parse_floating_literal(value.scalar, parsed)) fail("invalid session floating-point payload"); + } else { + std::int64_t parsed = 0; + const auto result = std::from_chars(value.scalar.data(), value.scalar.data() + value.scalar.size(), parsed); + if (result.ec != std::errc{} || result.ptr != value.scalar.data() + value.scalar.size() || + std::to_string(parsed) != value.scalar) fail("invalid canonical session integer payload"); + if ((type.name == "u8" && (parsed < 0 || parsed > 255)) || + (type.name == "i32" && (parsed < INT32_MIN || parsed > INT32_MAX))) + fail("session integer payload is outside its declared width"); + } + auto literal = make(path, value.scalar); + // A small retained i64/u8 must not silently infer i32 when restored. + return make(path, literal, type.name); + } +}; + +void compile(prepared_session_submission &out, + const std::shared_ptr &source_body, + const ny::ast_expr_ptr &value, const std::string &filename, + const std::vector &bindings) { + auto &report = out.report; + auto body = std::make_shared(); + body->source_file = filename; + snapshot_literals snapshots; + std::set names; + for (const auto &binding : bindings) { + validate_name(binding.name); + if (!names.insert(fold_key(binding.name)).second) fail("duplicate retained binding after Matrix name normalization"); + const auto path = "$session.bindings." + binding.name; + auto declaration = std::make_shared( + binding.name, snapshots.expression(binding.value, path), binding.value.type); + declaration->source_file = path; + body->statements.push_back(std::make_shared(declaration)); + } + for (const auto &statement : source_body->statements) { + body->statements.push_back(statement); + const auto declaration = std::dynamic_pointer_cast(statement); + if (!declaration) continue; + const auto variable = std::dynamic_pointer_cast(declaration->declaration); + if (!variable) continue; + const auto collect = [&](const ny::ast_variable_decl &binding, bool component) { + if (component && binding.name == "_") return; + validate_name(binding.name); + if (!names.insert(fold_key(binding.name)).second) + throw submission_request_error(binding.source_file.empty() ? filename : binding.source_file, + "binding already exists after Matrix name normalization: " + binding.name); + out.binding_names.push_back(binding.name); + }; + if (variable->tuple_bindings.empty()) collect(*variable, false); + else for (const auto &component : variable->tuple_bindings) if (component) collect(*component, true); + } + if (bindings.size() + out.binding_names.size() > submission_session_max_bindings) + fail("session cannot retain more than 64 bindings"); + for (const auto &diagnostic : ny::validate_submission_ast(*body, value)) + issue(report, "profile", diagnostic.message, + diagnostic.source_file.empty() ? filename : diagnostic.source_file, diagnostic.line, "MS1001"); + if (!report.diagnostics.empty()) return; + + std::vector> fields; + if (value) fields.emplace_back("0", value); + for (const auto &name : out.binding_names) + fields.emplace_back(std::to_string(fields.size()), std::make_shared(name)); + std::shared_ptr result; + if (!fields.empty()) { + result = std::make_shared("tuple", std::move(fields)); + result->tuple_literal = true; + result->source_file = filename; + body->statements.push_back(std::make_shared(result)); + } + auto function = std::make_shared( + "__nil_submission", std::vector{}, "void", body); + ny::ast_program program; + program.filename = filename; + program.declarations.push_back(function); + const auto check = [&]() { + ny::type_checker checker; + if (checker.check(program)) return true; + for (const auto &diagnostic : checker.get_diagnostics()) + issue(report, "type", diagnostic.message, + diagnostic.source_file.empty() ? filename : diagnostic.source_file, diagnostic.line, "MS2001"); + if (report.diagnostics.empty()) issue(report, "type", "submission failed type checking", filename, 0, "MS2001"); + return false; + }; + if (!check()) return; + if (result) { + if (!result->inferred_type) fail("session result has no inferred type"); + function->return_type = *result->inferred_type; + body->statements.back() = std::make_shared(result); + if (!check()) return; + } + ny::codegen_options options; + options.include_debug_info = false; + options.include_source_debug = false; + options.mode = ny::build_mode::release_mode; + ny::codegen generator(options); + std::vector diagnostics; + auto module = generator.generate_module(program, &diagnostics); + for (const auto &diagnostic : diagnostics) + issue(report, "lowering", diagnostic.message, filename, diagnostic.line, "MS3001"); + if (!report.diagnostics.empty()) return; + if (!module) fail("submission lowering produced no module"); + try { ny::validate_nil_submission_profile(*module); } + catch (const std::exception &error) { issue(report, "nil-profile", error.what(), filename, 0, "MS1002"); return; } + std::ostringstream serialized; + ny::nil_writer writer(serialized, options); + writer.emit_text_module(*module); + report.nil_text = serialized.str(); + if (report.nil_text.size() > 1024 * 1024) fail("submission NIL output exceeds 1048576 bytes"); + for (const auto &compiled : module->functions) report.instruction_count += compiled.body.size(); + report.result_type = "void"; + if (value) { + const auto shape = parse_shape(module->functions.front().return_type); + if (shape.name != "tuple" || shape.children.empty()) fail("invalid generated session result envelope"); + report.result_type = shape.children.front().spelling; + } + out.has_value = static_cast(value); + out.module = std::move(module); + report.status = "complete"; +} +} // namespace + +prepared_session_submission prepare_session_submission( + const std::string &source, bool request, const std::string &filename, + const std::vector &bindings) { + prepared_session_submission out; + out.report.input_kind = request ? "nildata-request" : "matrix"; + try { + if (source.size() > submission_max_input_bytes) fail("submission input exceeds 65536 bytes"); + nil::detail::valid_utf8(source); + if (source.find('\0') != std::string::npos) fail("submission input must not contain NUL"); + if (bindings.size() > submission_session_max_bindings) fail("session cannot retain more than 64 bindings"); + std::vector names; + for (const auto &binding : bindings) { validate_name(binding.name); names.push_back(binding.name); } + if (request) { + const auto decoded = decode_submission_request(source, names); + compile(out, decoded.body, decoded.value, filename, bindings); + } else { + parser_options options; + options.filename = filename; + options.submission = true; + options.external_names = names; + parser frontend(source, options); + const auto parsed = frontend.parse_submission(); + if (parsed.state != submission_state::complete) { + out.report.status = parsed.state == submission_state::incomplete ? "incomplete" : "invalid"; + for (const auto &diagnostic : parsed.diagnostics) { + const auto before = out.report.diagnostics.size(); + issue(out.report, "parse", diagnostic.message, filename, diagnostic.primary.line, diagnostic.code); + if (out.report.diagnostics.size() != before) { + out.report.diagnostics.back().column = diagnostic.primary.column; + out.report.diagnostics.back().length = diagnostic.primary.length; + } + } + return out; + } + compile(out, parsed.body, parsed.value, filename, bindings); + } + } catch (const submission_request_error &error) { + issue(out.report, request ? "request" : "session", error.what(), error.path, 0, request ? "MS4001" : "MS5001"); + } catch (const std::exception &error) { + issue(out.report, "session", error.what(), filename); + } + if (out.report.status != "complete") { + out.module.reset(); out.has_value = false; out.binding_names.clear(); out.report.nil_text.clear(); + } + return out; +} +} // namespace matrix diff --git a/nilcompiler/src/submission_session_compile.hpp b/nilcompiler/src/submission_session_compile.hpp new file mode 100644 index 00000000..acbe491a --- /dev/null +++ b/nilcompiler/src/submission_session_compile.hpp @@ -0,0 +1,34 @@ +#ifndef NIL_SUBMISSION_SESSION_COMPILE_HPP +#define NIL_SUBMISSION_SESSION_COMPILE_HPP + +#include "matrix_submission.hpp" +#include "submission_value.hpp" +#include + +namespace ny { struct nil_module; } +namespace matrix { + +inline constexpr std::size_t submission_session_max_bindings = 64; +struct submission_binding { + std::string name; + ny::submission_value value; +}; +struct prepared_session_submission { + submission_report report; + std::shared_ptr module; + bool has_value = false; + // The result tuple contains the final expression first, when present, + // followed by these new top-level bindings in declaration order. + std::vector binding_names; +}; + +// Compile only the new submission. Retained values become fresh typed data +// literals; no prior source or AST is replayed. This does not execute or publish +// state. The caller must evaluate and validate the complete result before +// atomically committing any new binding. +prepared_session_submission prepare_session_submission( + const std::string &source, bool request, const std::string &filename, + const std::vector &bindings); + +} // namespace matrix +#endif diff --git a/nilcompiler/src/submission_value.hpp b/nilcompiler/src/submission_value.hpp new file mode 100644 index 00000000..ce42cc7f --- /dev/null +++ b/nilcompiler/src/submission_value.hpp @@ -0,0 +1,37 @@ +#ifndef NIL_SUBMISSION_VALUE_HPP +#define NIL_SUBMISSION_VALUE_HPP + +#include +#include +#include +#include +#include + +namespace ny { +// Owned data only: no VM addresses, mutable aliases, or executable history. +struct submission_value { + std::string type; + std::string scalar; + std::vector elements; +}; + +struct pure_execution_limits { + std::size_t max_instructions = 16384; + std::size_t max_work_bytes = 16 * 1024 * 1024; + std::size_t max_text_bytes = 1024 * 1024; + std::size_t max_snapshot_nodes = 4096; + std::size_t max_snapshot_depth = 32; + std::size_t max_snapshot_bytes = 1024 * 1024; + // Called between instructions and snapshot nodes; true requests cancellation. + std::function cancelled; +}; + +class pure_execution_error : public std::runtime_error { +public: + enum class kind { budget, cancelled }; + kind reason; + pure_execution_error(kind reason, const std::string &message) + : std::runtime_error(message), reason(reason) {} +}; +} // namespace ny +#endif diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 022bc74b..9d6ee742 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -744,7 +744,12 @@ type_info type_checker::resolve_type(const std::string &name) { * base_info.name.c_str()); */ /* fflush(stderr); */ - // Resolve args - use 'any' fallback if arg resolution returns error type + // Resolve each argument once. Built-in containers such as array do not + // create a cached nominal instantiation; resolving their arguments again + // below doubles the recursive work at every level of a nested type. + std::vector resolved_args; + resolved_args.reserve(parts.type_args.size()); + // Use 'any' in the display name if argument resolution returns an error. std::string resolved_name = base_info.name + "<"; for (size_t i = 0; i < parts.type_args.size(); ++i) { if (i > 0) @@ -754,6 +759,7 @@ type_info type_checker::resolve_type(const std::string &name) { // arg[" << i << "]='" << parts.type_args[i] << "'\n"; /* fflush(stderr); */ type_info arg_info = resolve_type(parts.type_args[i]); + resolved_args.push_back(arg_info.name); // CASCADING ERROR FIX: If the resolved arg is an error/unknown type // marker, substitute 'any' to prevent the error from infecting the entire // module. Error markers start with '<' (e.g. "", "") @@ -830,11 +836,7 @@ type_info type_checker::resolve_type(const std::string &name) { } if (!base_for_instantiation.empty()) { - std::vector args; - for (const auto &arg : parts.type_args) { - args.push_back(resolve_type(arg).name); - } - instantiate_generic_node(base_for_instantiation, resolved_name, args); + instantiate_generic_node(base_for_instantiation, resolved_name, resolved_args); } } return {resolved_name, true}; diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index d448d17a..16ec7d48 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -1,4 +1,6 @@ #include "vm.hpp" +#include "submission_profile.hpp" +#include "../../common/strict_json.hpp" #include "concurrency_contract.hpp" #include "owned_contract.hpp" #include "parallel_support.hpp" @@ -702,6 +704,344 @@ int64_t invoke_native(void *fn_ptr, const std::vector &args) { } // ---------------------------- +namespace { +[[noreturn]] void pure_budget(const std::string &message) { + throw pure_execution_error(pure_execution_error::kind::budget, + "pure execution budget: " + message); +} +[[noreturn]] void pure_invalid(const std::string &message) { + throw std::runtime_error("pure execution: " + message); +} +const char *pure_operation(Opcode opcode) { +#define PURE_OP(name) case Opcode::name: return #name + switch (opcode) { + PURE_OP(PUSH_CONST); PURE_OP(PUSH_CONST_STR); PURE_OP(LOAD_LOCAL); + PURE_OP(STORE_LOCAL); PURE_OP(POP); PURE_OP(RET); PURE_OP(LABEL); + PURE_OP(JMP); PURE_OP(JMP_IF); PURE_OP(JMP_IF_NOT); + PURE_OP(CMP_EQ); PURE_OP(CMP_NE); PURE_OP(CMP_LT); PURE_OP(CMP_LE); + PURE_OP(CMP_GT); PURE_OP(CMP_GE); PURE_OP(NOT); PURE_OP(ADD); + PURE_OP(SUB); PURE_OP(MUL); PURE_OP(DIV); PURE_OP(MOD); PURE_OP(NEG); + PURE_OP(BIT_AND); PURE_OP(BIT_OR); PURE_OP(BIT_XOR); PURE_OP(SHL); + PURE_OP(SHR); PURE_OP(NEW_STRUCT); PURE_OP(GET_FIELD); PURE_OP(SET_FIELD); + PURE_OP(NEW_ARRAY_LITERAL); PURE_OP(GET_INDEX); PURE_OP(STR_CONCAT); + PURE_OP(TO_STRING); PURE_OP(CAST); + default: pure_invalid("forbidden opcode"); + } +#undef PURE_OP +} +void pure_cancel(const pure_execution_limits &limits) { + if (limits.cancelled && limits.cancelled()) + throw pure_execution_error(pure_execution_error::kind::cancelled, + "pure execution cancelled"); +} +} // namespace + +void VM::configurePureExecution(pure_execution_limits limits) { + if (!program_.empty() || memory_profile_started_ || pure_limits_) + pure_invalid("configure limits on a fresh VM before loading a program"); + if (!limits.max_instructions || !limits.max_work_bytes || !limits.max_text_bytes || + !limits.max_snapshot_nodes || !limits.max_snapshot_depth || !limits.max_snapshot_bytes) + throw std::invalid_argument("pure execution limits must be positive"); + // Hosts may lower or moderately raise limits, but cannot accidentally remove + // structural recursion/size guards or overflow the accounting arithmetic. + if (limits.max_instructions > 1024 * 1024 || + limits.max_work_bytes > 1024ULL * 1024 * 1024 || + limits.max_text_bytes > 16 * 1024 * 1024 || + limits.max_snapshot_nodes > 65536 || limits.max_snapshot_depth > 64 || + limits.max_snapshot_bytes > 16 * 1024 * 1024) + throw std::invalid_argument("pure execution limits exceed supported maximums"); + pure_limits_ = std::move(limits); + memory_profile_allowed_ = false; + memory_mode_ = MemoryMode::UNSAFE_MANUAL; + trap_process_exit_ = true; +} + +void VM::validatePureProgram(const std::vector &program, + const std::unordered_map &constants) const { + if (program.size() < 4 || program.size() > 4099) + pure_invalid("expected one bounded synthetic function"); + const auto &skip = program.front(), &entry = program[1], &end = program.back(); + if (skip.op != Opcode::JMP || skip.args.size() != 1 || + entry.op != Opcode::LABEL || !entry.is_function_entry || entry.is_function_end || + entry.args != std::vector{"__nil_submission"} || + entry.function_param_count || !entry.function_parameter_types.empty() || + !entry.function_annotations.empty() || end.op != Opcode::LABEL || + !end.is_function_end || end.is_function_entry || end.args != skip.args || + skip.is_function_entry || skip.is_function_end) + pure_invalid("invalid synthetic function boundaries"); + nil_module module; + if (skip.module_metadata) module = *skip.module_metadata; + module.module_name = "root"; // Flattened VM metadata omits the module header. + module.functions.clear(); + module.string_constants.clear(); + nil_function function; + function.name = entry.args.front(); + function.return_type = entry.function_return_type; + for (std::size_t i = 2; i + 1 < program.size(); ++i) { + const auto &instruction = program[i]; + if (instruction.is_function_entry || instruction.is_function_end || + instruction.function_param_count || !instruction.function_return_type.empty() || + !instruction.function_parameter_types.empty() || !instruction.function_annotations.empty() || + instruction.module_metadata) + pure_invalid("unexpected function or module metadata"); + nil_instruction copied; + copied.opname = pure_operation(instruction.op); + copied.args = instruction.args; + copied.debug_line = instruction.line; + copied.source_file = instruction.source_file; + copied.debug_locals = instruction.debug_locals; + function.body.push_back(std::move(copied)); + } + module.functions.push_back(std::move(function)); + for (const auto &[name, value] : constants) { + const auto *text = std::get_if(&value); + if (!text) pure_invalid("only text constants are admitted"); + if (text->size() > pure_limits_->max_text_bytes) pure_budget("text limit exceeded"); + module.string_constants.emplace_back(name, *text); + } + validate_nil_submission_profile(module); +} + +void VM::chargePureWork(std::size_t bytes) { + if (bytes > pure_limits_->max_work_bytes - pure_work_bytes_) + pure_budget("work byte limit exceeded"); + pure_work_bytes_ += bytes; +} + +void VM::chargePureValue(const Value &value, unsigned depth, std::size_t &nodes) { + // Charge before descending or copying. Repeated aliases deliberately count + // repeatedly: their later materialization must fit the same logical budget. + if (depth > pure_limits_->max_snapshot_depth || + ++nodes > pure_limits_->max_snapshot_nodes) + pure_budget("value shape limit exceeded"); + chargePureWork(8 * sizeof(Value)); + const auto copy_cost = [&](const std::string &text) { + if (text.size() > pure_limits_->max_work_bytes / 8) pure_budget("work byte limit exceeded"); + chargePureWork(8 * text.size()); + }; + const auto text_cost = [&](const std::string &text) { + if (text.size() > pure_limits_->max_text_bytes) pure_budget("text limit exceeded"); + copy_cost(text); + }; + if (const auto *text = std::get_if(&value)) text_cost(*text); + else if (const auto *tuple = std::get_if(&value)) { + if (!tuple->data || !tuple->static_class_view.empty() || + tuple->type_name.rfind("tuple<", 0) != 0 || !tuple->enum_fields().empty()) + pure_invalid("unsupported aggregate value"); + copy_cost(tuple->type_name); + const auto &data = *tuple->data; + for (const auto &[name, scalar] : data.fields) { (void)scalar; copy_cost(name); chargePureWork(64); } + for (const auto &[name, scalar] : data.double_fields) { (void)scalar; copy_cost(name); chargePureWork(64); } + for (const auto &[name, text] : data.string_fields) { copy_cost(name); text_cost(text); } + for (const auto &[name, nested] : data.struct_fields) { + copy_cost(name); + if (!nested) pure_invalid("null tuple field"); + chargePureValue(*nested, depth + 1, nodes); + } + for (const auto &[name, array] : data.array_fields) { + copy_cost(name); chargePureValue(array, depth + 1, nodes); + } + } else if (const auto *array = std::get_if(&value)) { + const auto found = heap_.find(array->address); + if (found == heap_.end() || found->second.type_name != "array") + pure_invalid("invalid array handle"); + copy_cost(found->second.element_type); + for (const auto &element : found->second.data) + chargePureValue(element, depth + 1, nodes); + } else if (!std::holds_alternative(value) && !std::holds_alternative(value)) + pure_invalid("unsupported runtime value"); +} + +void VM::preflightPureInstruction(const Instruction &instruction) { + (void)pure_operation(instruction.op); // Defense in depth after whole-artifact admission. + pure_cancel(*pure_limits_); + if (pure_instructions_ == pure_limits_->max_instructions) + pure_budget("instruction limit exceeded"); + // Reserve fixed instruction/container overhead and charge all dynamic work + // before the ordinary interpreter can copy values or allocate a result. + chargePureWork(256); + std::size_t nodes = 0; + const auto operand = [&](std::size_t from_top) -> const Value & { + requireStackValues(from_top + 1, "pure preflight"); + return stack_[stack_.size() - 1 - from_top]; + }; + const auto charge = [&](const Value &value) { chargePureValue(value, 0, nodes); }; + for (const auto &arg : instruction.args) chargePureWork(8 * arg.size()); + switch (instruction.op) { + case Opcode::PUSH_CONST_STR: charge(constants_.at(instruction.args.at(0))); break; + case Opcode::LOAD_LOCAL: { + if (call_stack_.empty()) pure_invalid("local load without frame"); + const auto found = call_stack_.back().locals.find(instruction.args.at(0)); + if (found == call_stack_.back().locals.end()) pure_invalid("uninitialized local"); + charge(found->second); break; + } + case Opcode::STR_CONCAT: { + const auto *right = std::get_if(&operand(0)); + const auto *left = std::get_if(&operand(1)); + if (!left || !right) pure_invalid("concatenation requires text"); + if (right->size() > pure_limits_->max_text_bytes || + left->size() > pure_limits_->max_text_bytes - right->size()) + pure_budget("concatenated text limit exceeded"); + charge(operand(1)); charge(operand(0)); break; + } + case Opcode::NEW_ARRAY_LITERAL: { + const auto count = static_cast(std::stoull(instruction.args.at(0))); + requireStackValues(count, "pure array construction"); + if (count > 256) pure_budget("array element limit exceeded"); + chargePureWork(256 + count * sizeof(Value)); + for (std::size_t i = 0; i < count; ++i) charge(operand(i)); + break; + } + case Opcode::NEW_STRUCT: chargePureWork(512); break; + case Opcode::GET_FIELD: charge(operand(0)); break; + case Opcode::SET_FIELD: charge(operand(0)); chargePureWork(256); break; + case Opcode::GET_INDEX: charge(operand(0)); charge(operand(1)); break; + case Opcode::TO_STRING: { + charge(operand(0)); + // Probe the same bounded scalar formatter before the VM consumes its + // operand. Its fixed scratch/output capacity is covered even when a host + // chooses a text limit smaller than one formatted scalar. + chargePureWork(512); + std::size_t length = 0; + const auto &source = operand(0); + if (const auto *integer = std::get_if(&source)) + length = instruction.args.at(0) == "bool" ? (*integer ? 4 : 5) + : scalar_text(*integer).size(); + else if (const auto *floating = std::get_if(&source)) + length = scalar_text(*floating).size(); + else pure_invalid("formatting requires a scalar operand"); + if (length > pure_limits_->max_text_bytes) pure_budget("formatted text limit exceeded"); + break; + } + case Opcode::STORE_LOCAL: case Opcode::POP: case Opcode::NOT: + case Opcode::NEG: case Opcode::JMP_IF: case Opcode::JMP_IF_NOT: + case Opcode::CAST: + charge(operand(0)); chargePureWork(512); break; + case Opcode::RET: + if (availableStackValues()) charge(operand(0)); + break; + case Opcode::CMP_EQ: case Opcode::CMP_NE: case Opcode::CMP_LT: + case Opcode::CMP_LE: case Opcode::CMP_GT: case Opcode::CMP_GE: + case Opcode::ADD: case Opcode::SUB: case Opcode::MUL: case Opcode::DIV: + case Opcode::MOD: case Opcode::BIT_AND: case Opcode::BIT_OR: case Opcode::BIT_XOR: + case Opcode::SHL: case Opcode::SHR: + charge(operand(0)); charge(operand(1)); break; + case Opcode::PUSH_CONST: case Opcode::LABEL: case Opcode::JMP: break; + default: pure_invalid("forbidden opcode"); + } + ++pure_instructions_; +} + +submission_value VM::snapshotPureValue(const Value &value, const std::string &type) const { + if (!pure_limits_) pure_invalid("snapshot requires pure execution mode"); + const auto &limits = *pure_limits_; + std::size_t nodes = 0, bytes = 0; + const auto reserve = [&](std::size_t count) { + if (count > limits.max_snapshot_bytes - bytes) pure_budget("snapshot byte limit exceeded"); + bytes += count; + }; + const auto text_check = [&](const std::string &text) { + if (text.size() > limits.max_text_bytes) pure_budget("text limit exceeded"); + nil::detail::valid_utf8(text); + }; + const auto visit = [&](const auto &self, const Value ¤t, + const std::string &expected, unsigned depth) -> submission_value { + pure_cancel(limits); + if (depth > limits.max_snapshot_depth || ++nodes > limits.max_snapshot_nodes) + pure_budget("snapshot shape limit exceeded"); + if (expected.empty() || expected.size() > 4096) pure_invalid("invalid snapshot type"); + reserve(64 + expected.size()); + submission_value out; + out.type = expected; + if (expected == "text") { + const auto *text = std::get_if(¤t); + if (!text) pure_invalid("text snapshot type mismatch"); + text_check(*text); reserve(text->size()); out.scalar = *text; + } else if (expected == "bool" || expected == "i32" || expected == "i64" || expected == "u8") { + const auto *integer = std::get_if(¤t); + if (!integer || (expected == "bool" && *integer != 0 && *integer != 1) || + (expected == "u8" && (*integer < 0 || *integer > 255)) || + (expected == "i32" && (*integer < INT32_MIN || *integer > INT32_MAX))) + pure_invalid("integer snapshot type mismatch"); + out.scalar = expected == "bool" ? (*integer ? "true" : "false") : std::to_string(*integer); + reserve(out.scalar.size()); + } else if (expected == "f64") { + const auto *floating = std::get_if(¤t); + if (!floating || !std::isfinite(*floating)) + pure_invalid("snapshot requires a finite f64 value"); + std::ostringstream text; + text.imbue(std::locale::classic()); + text << std::setprecision(std::numeric_limits::max_digits10) << *floating; + out.scalar = text.str(); + if (out.scalar.find_first_of(".eE") == std::string::npos) out.scalar += ".0"; + reserve(out.scalar.size()); + } else if (expected.rfind("array<", 0) == 0 && expected.back() == '>') { + const auto *handle = std::get_if(¤t); + if (!handle) pure_invalid("array snapshot type mismatch"); + const auto found = heap_.find(handle->address); + if (found == heap_.end() || found->second.type_name != "array" || + "array<" + found->second.element_type + ">" != expected || + found->second.element_count != found->second.data.size()) + pure_invalid("array snapshot metadata mismatch"); + const auto &block = found->second; + if (block.data.size() > limits.max_snapshot_nodes - nodes) + pure_budget("snapshot node limit exceeded"); + out.elements.reserve(block.data.size()); + for (const auto &element : block.data) + out.elements.push_back(self(self, element, block.element_type, depth + 1)); + } else if (expected.rfind("tuple<", 0) == 0) { + const auto *tuple = std::get_if(¤t); + if (!tuple || !tuple->data || tuple->type_name != expected || + !tuple->static_class_view.empty() || !class_metadata_) + pure_invalid("tuple snapshot type mismatch"); + const auto fields = array_tuple_elements(expected); + const nil_struct_def *schema = nullptr; + for (const auto &candidate : class_metadata_->structs) + if (candidate.name == expected) { + if (schema) pure_invalid("duplicate tuple schema"); + schema = &candidate; + } + if (!fields || !schema || schema->annotations != std::vector{"@nil_tuple"} || + schema->fields.size() != fields->size()) pure_invalid("invalid tuple schema"); + const auto &data = *tuple->data; + if (data.fields.size() + data.string_fields.size() + data.double_fields.size() + + data.array_fields.size() + data.struct_fields.size() != fields->size() || + !data.enum_fields.empty()) pure_invalid("incomplete tuple snapshot"); + if (fields->size() > limits.max_snapshot_nodes - nodes) + pure_budget("snapshot node limit exceeded"); + out.elements.reserve(fields->size()); + for (std::size_t i = 0; i < fields->size(); ++i) { + const auto name = std::to_string(i); + if (schema->fields[i] != std::make_pair(name, (*fields)[i])) + pure_invalid("tuple schema does not match its structural type"); + std::optional field; + const auto take = [&](const auto &map) { + const auto found = map.find(name); + if (found == map.end()) return; + if (field) pure_invalid("duplicate tuple field"); + using Stored = std::decay_tsecond)>; + if constexpr (std::is_same_v>) { + if (!found->second) pure_invalid("null tuple field"); + field = *found->second; + } else if constexpr (std::is_same_v) { + text_check(found->second); + // The temporary VM Value copy must also fit before it allocates. + if (found->second.size() > limits.max_snapshot_bytes - bytes) + pure_budget("snapshot byte limit exceeded"); + field = found->second; + } else field = found->second; + }; + take(data.fields); take(data.string_fields); take(data.double_fields); + take(data.array_fields); take(data.struct_fields); + if (!field) pure_invalid("missing tuple field"); + out.elements.push_back(self(self, *field, (*fields)[i], depth + 1)); + } + } else pure_invalid("unsupported snapshot type"); + return out; + }; + return visit(visit, value, type, 0); +} + VM::VM() : pc_(0) {} void VM::beginMemoryProfile() { @@ -739,6 +1079,8 @@ void VM::resetRuntimeState(const std::string &root_function) { file_handles_.clear(); next_file_handle_ = 1; stack_.clear(); + pure_instructions_ = 0; + pure_work_bytes_ = 0; globals_.clear(); gc_marked_structs_.clear(); heap_.clear(); @@ -759,6 +1101,7 @@ void VM::resetRuntimeState(const std::string &root_function) { void VM::loadProgram(const std::vector &program, const std::unordered_map &constants) { + if (pure_limits_) validatePureProgram(program, constants); validate_nil_parallel_contract(program); validate_nil_owned_contract(program); validate_nil_fault_contract(program); @@ -928,6 +1271,7 @@ catch (...) { } void VM::executeInstruction(const Instruction &instr) { + if (pure_limits_) preflightPureInstruction(instr); if (memory_profile_.enabled()) memory_profile_.site(instr.source_file, call_stack_.empty() ? "" : call_stack_.back().fn_name, diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index 80e229e3..80059f34 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -17,6 +17,7 @@ #include "source_debug.hpp" #include "database_runtime.hpp" #include "memory_profile.hpp" +#include "submission_value.hpp" namespace ny { @@ -283,6 +284,16 @@ class VM { const std::unordered_map &constants); void execute(bool reset = true); + // Opt-in admission and logical resource bounds for a fresh pure submission. + // Limits cover VM work and owned snapshots, not process RSS. Configure before + // loading a program; ambient profiling and effectful opcodes are disabled. + void configurePureExecution(pure_execution_limits limits = {}); + submission_value snapshotPureValue(const Value &value, + const std::string &type) const; + std::size_t pureInstructionsExecuted() const { return pure_instructions_; } + std::size_t pureWorkBytesCharged() const { return pure_work_bytes_; } + + // Memory mode configuration void setMemoryMode(MemoryMode mode) { memory_mode_ = mode; } MemoryMode getMemoryMode() const { return memory_mode_; } @@ -379,6 +390,15 @@ class VM { bool hasGlobal(const std::string &name) const { return globals_.count(name) > 0; } private: + std::optional pure_limits_; + std::size_t pure_instructions_ = 0; + std::size_t pure_work_bytes_ = 0; + void preflightPureInstruction(const Instruction &instruction); + void chargePureWork(std::size_t bytes); + void chargePureValue(const Value &value, unsigned depth, std::size_t &nodes); + void validatePureProgram(const std::vector &program, + const std::unordered_map &constants) const; + MemoryMode memory_mode_ = MemoryMode::UNSAFE_MANUAL; // Default to unsafe std::vector args_; diff --git a/tests/matrix_session_contract.py b/tests/matrix_session_contract.py new file mode 100644 index 00000000..d0c80de4 --- /dev/null +++ b/tests/matrix_session_contract.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""Bounded Matrix evaluator and retained-value shell CLI contract.""" +import argparse +import json +import os +from pathlib import Path +import subprocess +import tempfile + + +def nildata(value): + def lines(item, prefix="", indent=""): + if isinstance(item, (dict, list)): + kind = "object" if isinstance(item, dict) else "array" + out = [indent + prefix + ("an " if prefix else "") + kind] + entries = item.items() if isinstance(item, dict) else ((None, v) for v in item) + for key, child in entries: + out += lines(child, ("item" if key is None else json.dumps(key)) + " is ", indent + " ") + return out + [indent + "end " + kind] + return [indent + prefix + json.dumps(item, ensure_ascii=False)] + return "nildata 1\n" + "\n".join(lines(value)) + "\n" + + +def number(value): + return {"kind": "number", "value": str(value)} + + +def envelope(value, bindings=()): + return {"schema": "nil.matrix.submission-request.v1", "profile": "matrix.pure.v1", + "bindings": [{"name": name, "value": value} for name, value in bindings], "value": value} + + +def scalar(value, kind, spelling): + assert value == {"type": kind, "scalar": spelling}, value + + +def evaluation(report, status="complete"): + assert report["schema"] == "nil.matrix.submission-evaluation.v1", report + assert report["profile"] == "matrix.pure.v1", report + assert report["status"] == status and "nil" not in report, report + if status == "complete": + assert report["executed"] and report["committed"] and not report["diagnostics"], report + assert report["instructions_executed"] > 0, report + else: + assert not report["committed"] and report["value"] is None and not report["added"], report + assert report["diagnostics"], report + if status in {"invalid", "incomplete"}: + assert not report["executed"] and report["instructions_executed"] == 0, report + return report + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--compiler", required=True) + compiler = str(Path(parser.parse_args().compiler).resolve()) + checks = 0 + with tempfile.TemporaryDirectory(prefix="matrix-session-") as temporary: + work = Path(temporary) + profile = work / "must-not-create-profile.jsonl" + env = {**os.environ, "NIL_MEMORY_PROFILE": str(profile)} + + def command(arguments, source="", code=0): + nonlocal checks + if isinstance(source, str): + source = source.encode() + result = subprocess.run([compiler, *arguments], input=source, cwd=work, + env=env, capture_output=True, timeout=15) + assert result.returncode == code, (arguments, source[:500], result) + assert not result.stderr, (arguments, result.stderr) + assert not profile.exists(), "bounded evaluation must ignore ambient memory-profile output" + checks += 1 + return result + + def once(source="", request=False, status="complete", path="-"): + flag = "--evaluate-submission-request" if request else "--evaluate-submission" + result = command([flag, str(path)], source, + 0 if status == "complete" else 2 if status == "incomplete" else 1) + report = evaluation(json.loads(result.stdout), status) + assert report["input_kind"] == ("nildata-request" if request else "matrix"), report + return report + + def shell(source, code=0): + result = command(["--matrix-shell"], source, code) + # Pipe mode has no prompt, command echo, history, or human prose. + reports = [json.loads(line) for line in result.stdout.splitlines()] + return reports, result.stdout + + for source, kind, spelling in [ + ("40 plus 2", "i32", "42"), + ("-9223372036854775808", "i64", "-9223372036854775808"), + ("9223372036854775807", "i64", "9223372036854775807"), + ("false and (1 over 0 equals 0)", "bool", "false"), + ("true or (1 over 0 equals 0)", "bool", "true"), + ("[1, 2] at 1", "i32", "2"), + ("[1, 2] at 1000", "i32", "0"), + ('"line" plus newline plus "end"', "text", "line\nend"), + ]: + scalar(once(source)["value"], kind, spelling) + assert once("")["value"] is None + for source in ["1 over 0", "[(1, true)] at 2"]: + report = once(source, status="runtime-error") + assert report["executed"] and report["binding_count"] == 0, report + for source in ["1 plus true", 'say "host output"', "variable amount is 1", + "value amount is 1\nset amount to 2", "repeat forever\nend repeat"]: + once(source, status="invalid") + once("1 plus", status="incomplete") + + pairs = [ + ("42", envelope(number(42))), + ("-9223372036854775808", envelope(number("-9223372036854775808"))), + ('"text"', envelope({"kind": "text", "value": "text"})), + ("value amount is 40\namount plus 2", envelope( + {"kind": "binary", "operator": "plus", "left": {"kind": "name", "name": "amount"}, + "right": number(2)}, [("amount", number(40))])), + ("(1, true)", envelope({"kind": "tuple", "items": [number(1), {"kind": "boolean", "value": True}]})), + ] + for source, request in pairs: + human, machine = once(source), once(nildata(request), request=True) + for key in ["value", "added", "binding_count", "result_type"]: + assert human[key] == machine[key], (key, human, machine) + once(nildata(envelope({"kind": "call", "name": "host"})), request=True, status="invalid") + + reports, _ = shell( + "value Frame-Count is 40\nFRAME_count plus 2\n" + 'value pairs is [(1, "one"), (2, "two")]\n' + "pairs at 1\n(pairs at 0).1\n:bindings\n:quit\nthis must not run\n") + assert len(reports) == 6, reports + for report in reports[:5]: + evaluation(report) + scalar(reports[1]["value"], "i32", "42") + scalar(reports[3]["value"]["elements"][1], "text", "two") + scalar(reports[4]["value"], "text", "one") + assert reports[5]["schema"] == "nil.matrix.session-bindings.v1", reports[5] + assert reports[5]["binding_count"] == 2, reports[5] + assert [item["name"] for item in reports[5]["bindings"]] == ["Frame_Count", "pairs"], reports[5] + + nested = "[" * 20 + "1" + "]" * 20 + reports, _ = shell("value nested is " + nested + "\n:bindings\n:quit\n") + evaluation(reports[0]) + assert len(reports) == 2 and reports[1]["binding_count"] == 1, reports + item = reports[1]["bindings"][0]["value"] + for _ in range(20): + assert len(item["elements"]) == 1, item + item = item["elements"][0] + scalar(item, "i32", "1") + + reports, _ = shell("value answer is\n40 plus 2\nanswer\n:quit\n") + assert len(reports) == 2, reports + scalar(evaluation(reports[1])["value"], "i32", "42") + reports, _ = shell("value kept is 7\nvalue missing is\n", code=2) + assert len(reports) == 2, reports + assert evaluation(reports[1], "incomplete")["binding_count"] == 1 + reports, _ = shell(":begin\nvalue never-committed is 3\n", code=2) + assert len(reports) == 1, reports + assert evaluation(reports[0], "incomplete")["binding_count"] == 0 + + reports, _ = shell( + "value kept is 7\n" + ":begin\nvalue staged is 9\n1 over 0\n:submit\n:bindings\nkept\n" + ":begin\nvalue invalid-stage is 2\n1 plus true\n:submit\n:bindings\n" + ":begin\nvalue accepted is kept plus 3\naccepted times 2\n:submit\naccepted\n:quit\n", code=1) + assert len(reports) == 8, reports + evaluation(reports[1], "runtime-error") + evaluation(reports[4], "invalid") + for index in [2, 5]: + assert reports[index]["binding_count"] == 1, reports[index] + assert [item["name"] for item in reports[index]["bindings"]] == ["kept"], reports[index] + scalar(evaluation(reports[3])["value"], "i32", "7") + scalar(evaluation(reports[6])["value"], "i32", "20") + scalar(evaluation(reports[7])["value"], "i32", "10") + assert [item["name"] for item in reports[6]["added"]] == ["accepted"], reports[6] + + reports, _ = shell( + "value kept is 7\n:begin\nvalue cancelled is 8\n:cancel\n:bindings\n" + "value unfinished is\n:cancel\n:begin\nvalue discarded is 1\n:reset\n" + ":bindings\nvalue fresh is 9\nfresh\n:quit\n") + assert len(reports) == 5, reports + assert [item["name"] for item in reports[1]["bindings"]] == ["kept"], reports[1] + assert reports[2]["bindings"] == [] and reports[2]["binding_count"] == 0, reports[2] + scalar(evaluation(reports[4])["value"], "i32", "9") + reports, _ = shell("value gone is 1\n:reset\ngone\n", code=1) + assert len(reports) == 2 and evaluation(reports[1], "invalid")["binding_count"] == 0 + + # A raw text block owns every payload line, including shell command + # spellings. Only after end text may the shell interpret commands again. + payload = "\n".join([":reset", ":quit", ":submit", ":bindings", ":cancel", ":begin", ":help"]) + reports, _ = shell("value kept is 7\nvalue message is begin text\n" + payload + + "\nend text\n:bindings\nkept\n:quit\n") + assert len(reports) == 4, reports + evaluation(reports[1]) + assert reports[2]["binding_count"] == 2, reports[2] + scalar(reports[2]["bindings"][1]["value"], "text", payload) + scalar(evaluation(reports[3])["value"], "i32", "7") + reports, _ = shell("value kept is 7\n:begin\nvalue message is begin text\n" + payload + + "\nend text\nmessage\n:submit\n:bindings\n:quit\n") + assert len(reports) == 3, reports + scalar(evaluation(reports[1])["value"], "text", payload) + assert reports[2]["binding_count"] == 2, reports[2] + + # Oversized atomic input must not turn later block lines into separate + # submissions, and one oversized physical line is drained with a cap. + comments = "!!!" + "x" * 40000 + "\n" + reports, _ = shell("value kept is 7\n:begin\n" + comments + comments + + "value escaped is 99\n:submit\nkept\n:bindings\n", code=1) + assert len(reports) == 4, reports + evaluation(reports[1], "invalid") + scalar(evaluation(reports[2])["value"], "i32", "7") + assert [item["name"] for item in reports[3]["bindings"]] == ["kept"], reports[3] + reports, _ = shell("value kept is 7\n" + "x" * 65537 + + "\nvalue escaped is 99\n:cancel\nkept\n", code=1) + assert len(reports) == 3, reports + evaluation(reports[1], "invalid") + scalar(evaluation(reports[2])["value"], "i32", "7") + + # Implicit multiline input has the same discard boundary as :begin. + # Repeated oversized lines cannot clear discard mode accidentally. + reports, _ = shell("value kept is 7\nvalue message is begin text\n" + "x" * 65537 + + "\n" + "y" * 65537 + + "\nvalue escaped is 99\nend text\n:cancel\n:bindings\nkept\n", code=1) + assert len(reports) == 5, reports + evaluation(reports[1], "invalid") + evaluation(reports[2], "invalid") + assert [item["name"] for item in reports[3]["bindings"]] == ["kept"], reports[3] + scalar(evaluation(reports[4])["value"], "i32", "7") + reports, _ = shell("value kept is 7\nwhen true then\n" + comments + comments + + "value escaped is 99\nend when\n:submit\n:bindings\n", code=1) + assert len(reports) == 3, reports + evaluation(reports[1], "invalid") + assert [item["name"] for item in reports[2]["bindings"]] == ["kept"], reports[2] + + # ESC/newline/tab data remains JSON text, never active terminal control. + reports, output = shell('value message is "\x1b[31m" plus newline plus tab\n:bindings\n:quit\n') + assert b"\x1b" not in output, output + scalar(reports[1]["bindings"][0]["value"], "text", "\x1b[31m\n\t") + reports, _ = shell(":quit extra\n1\n:quit\n", code=1) + assert len(reports) == 2, reports + evaluation(reports[0], "invalid") + scalar(evaluation(reports[1])["value"], "i32", "1") + reports, _ = shell(":help\n:quit\r\n") + assert len(reports) == 1 and reports[0]["schema"] == "nil.matrix.shell-help.v1", reports + + for source in [b"\xff", b"1\0", b"1\x1a trailing", b" " * 65537]: + once(source, status="invalid") + source_file = work / "input.matrix" + source_file.write_text("40 plus 2") + scalar(once(path=source_file)["value"], "i32", "42") + once(path=work, status="invalid") + once(path=work / "missing", status="invalid") + if os.name == "posix": + link = work / "linked.matrix" + link.symlink_to(source_file) + once(path=link, status="invalid") + fifo = work / "fifo.matrix" + os.mkfifo(fifo) + once(path=fifo, status="invalid") + + sentinel = work / "untouched.nil" + sentinel.write_text("sentinel") + for first in [["--evaluate-submission", "-"], ["--evaluate-submission-request", "-"], ["--matrix-shell"]]: + for extra in [["--no-typecheck"], ["--native"], ["--jit"], ["--output", str(sentinel)], + ["--sdk-path", str(work)], ["--check-submission", "-"], ["--matrix-shell"]]: + result = subprocess.run([compiler, *first, *extra], input=b"1", cwd=work, + env=env, capture_output=True, timeout=15) + assert result.returncode != 0 and sentinel.read_text() == "sentinel", (first, extra, result) + assert not profile.exists() + checks += 1 + assert sorted(item.name for item in work.iterdir()) == sorted([ + "input.matrix", "untouched.nil", *(["linked.matrix", "fifo.matrix"] if os.name == "posix" else [])]) + print(f"Matrix session CLI: {checks} checks passed") + + +if __name__ == "__main__": + main() diff --git a/tests/matrix_submission_parser_tests.cpp b/tests/matrix_submission_parser_tests.cpp index 62a9b54e..2ccc18df 100644 --- a/tests/matrix_submission_parser_tests.cpp +++ b/tests/matrix_submission_parser_tests.cpp @@ -99,6 +99,21 @@ void values_and_statements() { } void text_and_interpolation() { + for (const auto &source : {std::string("begin text\n:reset\n:quit\n"), + std::string("value payload is begin text\n:submit\n")}) { + matrix::lexer scanner(source, 0, true); + scanner.scan(); + require(scanner.errors().size() == 1 && scanner.errors().front().incomplete && + scanner.errors().front().open_text_block, + "raw block EOF exposes structured literal context"); + } + for (const auto &source : {std::string("\"unfinished"), std::string("formatted \"unfinished"), + std::string("begin text\n:reset\nend text\n")}) { + matrix::lexer scanner(source, 0, true); + scanner.scan(); + for (const auto &error : scanner.errors()) + require(!error.open_text_block, "only an unterminated raw block opens multiline literal context"); + } require(cast(parse("\"C:\\dir\\file\"").value)->value == "C:\\dir\\file", "quoted Matrix text is raw"); require(cast(parse("begin text\n hello \"world\"\n C:\\dir\nend text\n").value)->value == diff --git a/tests/submission_session_compile_tests.cpp b/tests/submission_session_compile_tests.cpp new file mode 100644 index 00000000..de3cf506 --- /dev/null +++ b/tests/submission_session_compile_tests.cpp @@ -0,0 +1,123 @@ +#include "submission_session_compile.hpp" +#include "codegen.hpp" +#include +#include + +namespace { +int checks = 0, failures = 0; +void expect(bool condition, const std::string &message) { + ++checks; + if (!condition) { ++failures; std::cerr << "FAIL " << message << '\n'; } +} +matrix::prepared_session_submission compile( + const std::string &source, const std::vector &bindings = {}, + bool request = false, const std::string &status = "complete") { + auto result = matrix::prepare_session_submission(source, request, "session.matrix", bindings); + expect(result.report.status == status, source + ": expected " + status + ", got " + result.report.status); + if (result.report.status != status) + for (const auto &issue : result.report.diagnostics) + std::cerr << issue.location << ": " << issue.message << '\n'; + expect(static_cast(result.module) == (status == "complete"), "module available only after successful admission"); + return result; +} +ny::submission_value scalar(std::string type, std::string value) { + return {std::move(type), std::move(value), {}}; +} +std::string request(const std::string &name) { + return "nildata 1\nobject\n" + " schema is \"nil.matrix.submission-request.v1\"\n" + " profile is \"matrix.pure.v1\"\n" + " bindings is an array\n end array\n" + " value is an object\n kind is \"name\"\n name is \"" + name + "\"\n" + " end object\nend object\n"; +} +} +int main() { + const std::vector prior = {{"Frame_Count", scalar("i64", "41")}}; + auto source = compile("frame-count plus 1", prior); + expect(source.report.result_type == "i64" && source.has_value && source.binding_names.empty(), + "retained folded name and scalar width survive compilation"); + expect(source.module && source.module->functions.front().params.empty(), "snapshot compilation requires no imported VM locals"); + const auto machine = compile(request("FRAMECOUNT"), prior, true); + expect(machine.report.result_type == "i64", "request resolves existing folded names"); + compile("value FRAMECOUNT is 2", prior, false, "invalid"); + compile("unknown plus 1", prior, false, "invalid"); + compile("frame-count plus", prior, false, "incomplete"); + compile("say frame-count", prior, false, "invalid"); + + auto defined = compile("value total is frame-count plus 1\nvalue (left, _) is (2, 3)\ntotal", prior); + expect(defined.binding_names == std::vector{"total", "left"}, "exports new top-level names in source order"); + expect(defined.module && defined.module->functions.front().return_type == "tuple", + "return envelope contains final expression then export values"); + auto scoped = compile("when true then\n value hidden is 1\nend when\nvalue hidden is 2\nhidden"); + expect(scoped.binding_names == std::vector{"hidden"}, "nested bindings do not become session exports"); + expect(scoped.report.nil_text.find("$ny.local.") != std::string::npos, + "test exercises codegen-renamed top-level storage"); + auto nested_only = compile("when true then\n value private-name is 1\nend when"); + expect(nested_only.binding_names.empty() && nested_only.report.result_type == "void", "block-local state remains local"); + auto empty = compile("", prior); + expect(!empty.has_value && empty.report.result_type == "void" && empty.binding_names.empty(), "empty submission returns void"); + auto declaration = compile("value count is 1"); + expect(!declaration.has_value && declaration.report.result_type == "void" && declaration.binding_names.size() == 1, + "binding-only result hides its internal tuple from the user result type"); + + for (const auto &value : {scalar("u8", "255"), scalar("i32", "-2147483648"), + scalar("i64", "-9223372036854775808"), scalar("f64", "-0.0"), + scalar("f64", "4.9406564584124654e-324"), scalar("bool", "true"), + scalar("text", "a quote \" and newline\n")}) { + auto restored = compile("kept", {{"kept", value}}); + expect(restored.report.result_type == value.type, "restored scalar retains exact type " + value.type); + } + ny::submission_value empty_array{"array", "", {}}; + auto array = compile("items", {{"items", empty_array}}); + expect(array.report.result_type == "array", "empty array retains its element type"); + ny::submission_value tuple{"tuple", "", {scalar("i64", "1"), scalar("text", "two")}}; + auto tuple_result = compile("pair", {{"pair", tuple}}); + expect(tuple_result.report.result_type == tuple.type, "tuple fields retain exact scalar types"); + ny::submission_value nested{"array>", "", {tuple}}; + auto nested_result = compile("items", {{"items", nested}}); + expect(nested_result.report.result_type == nested.type, "array tuple snapshots retain structure"); + + // Generic resolution must visit each nested argument once. Previously the + // built-in array path repeated resolution for nominal instantiation, making + // this tiny input take exponential time (the test timeout catches regression). + constexpr std::size_t nested_depth = 24; + const auto deep_source = "value deep is " + std::string(nested_depth, '[') + "1" + + std::string(nested_depth, ']'); + std::string deep_type = "i32"; + ny::submission_value deep_value = scalar("i32", "1"); + for (std::size_t i = 0; i < nested_depth; ++i) { + deep_type = "array<" + deep_type + ">"; + deep_value = {deep_type, "", {std::move(deep_value)}}; + } + const auto checked_deep = matrix::check_submission_source(deep_source, "nested.matrix"); + expect(checked_deep.status == "complete", "deep array check-only admission remains practical"); + const auto compiled_deep = compile(deep_source); + expect(compiled_deep.module && compiled_deep.module->functions.front().return_type == "tuple<" + deep_type + ">", + "deep array session compilation preserves its structural type"); + const auto restored_deep = compile("kept", {{"kept", deep_value}}); + expect(restored_deep.report.result_type == deep_type, "deep array restoration remains practical and exact"); + + compile("kept", {{"kept", scalar("u8", "256")}}, false, "invalid"); + compile("kept", {{"kept", scalar("i32", "2147483648")}}, false, "invalid"); + compile("kept", {{"kept", scalar("i64", "01")}}, false, "invalid"); + compile("kept", {{"kept", scalar("f64", "nan")}}, false, "invalid"); + compile("kept", {{"kept", scalar("bool", "1")}}, false, "invalid"); + compile("kept", {{"kept", {"array", "", {scalar("i32", "1")}}}}, false, "invalid"); + compile("kept", {{"kept", {"tuple", "", {}}}}, false, "invalid"); + compile("kept", {{"kept", {"text", "scalar", {scalar("i32", "1")}}}}, false, "invalid"); + compile("kept", {{"kept", scalar("ptr", "0")}}, false, "invalid"); + compile("kept", {{"kept", scalar("text", std::string(1, char(0xff)))}}, false, "invalid"); + compile("", {{"Frame_Count", scalar("i32", "1")}, {"framecount", scalar("i32", "2")}}, false, "invalid"); + compile("", {{"say", scalar("i32", "1")}}, false, "invalid"); + std::vector full; + for (int i = 0; i < 64; ++i) full.push_back({"item" + std::to_string(i), scalar("i32", "1")}); + compile("item0", full); + compile("value extra is 1", full, false, "invalid"); + full.push_back({"overflow", scalar("i32", "1")}); + compile("", full, false, "invalid"); + compile(std::string(65537, ' '), {}, false, "invalid"); + compile(std::string(1, char(0xff)), {}, false, "invalid"); + std::cout << checks << " session compilation checks, " << failures << " failures\n"; + return failures ? 1 : 0; +} diff --git a/tests/submission_session_tests.cpp b/tests/submission_session_tests.cpp new file mode 100644 index 00000000..b0d7a87a --- /dev/null +++ b/tests/submission_session_tests.cpp @@ -0,0 +1,144 @@ +#include "submission_session.hpp" +#include "../common/strict_json.hpp" + +#include +#include + +namespace { +int checks = 0; +void expect(bool condition, const std::string &message) { + ++checks; + if (!condition) throw std::runtime_error(message); +} +matrix::evaluation_report complete(matrix::submission_session &session, + const std::string &source) { + auto report = session.evaluate(source); + expect(report.check.status == "complete", source + ": " + matrix::evaluation_report_json(report)); + expect(report.executed && report.committed, "successful transaction must execute and commit"); + return report; +} +void scalar(matrix::submission_session &session, const std::string &source, + const std::string &type, const std::string &value) { + const auto report = complete(session, source); + expect(report.value && report.value->type == type && report.value->scalar == value, + source + ": unexpected typed result " + matrix::evaluation_report_json(report)); +} +void rollback(matrix::submission_session &session, const std::string &source, + const std::string &status, bool executed) { + const auto size = session.bindings().size(); + const auto report = session.evaluate(source); + expect(report.check.status == status, source + ": " + matrix::evaluation_report_json(report)); + expect(!report.committed && !report.value && report.added.empty(), "failed transaction leaked output"); + expect(report.executed == executed, "failed transaction execution flag mismatch"); + expect(session.bindings().size() == size && report.binding_count == size, "failure changed retained bindings"); +} + +void retained_values() { + matrix::submission_session session; + auto first = complete(session, "value Answer is 40 plus 2"); + expect(first.check.result_type == "void" && !first.value && first.added.size() == 1, "binding-only transaction"); + scalar(session, "ANSWER", "i32", "42"); + const auto restored = matrix::prepare_session_submission("answer", false, "next.mat", session.bindings()); + expect(restored.report.status == "complete" && restored.report.nil_text.find("ADD") == std::string::npos, + "retained data must not replay its original addition"); + scalar(session, "value long-value as number is 7\nlong-value", "i64", "7"); + scalar(session, "LONG_VALUE", "i64", "7"); + scalar(session, "value byte-value is 255 becomes override byte\nbyte-value", "u8", "255"); + scalar(session, "byte-value", "u8", "255"); + scalar(session, "value flag is true\nflag", "bool", "true"); + scalar(session, "flag", "bool", "true"); + scalar(session, "value minimum is -9223372036854775808\nminimum", "i64", "-9223372036854775808"); + scalar(session, "minimum", "i64", "-9223372036854775808"); + complete(session, "value negative-zero is -0.0"); + scalar(session, "negative-zero", "f64", "-0.0"); + complete(session, "value message is \"hello\""); + scalar(session, "message plus \" world\"", "text", "hello world"); + complete(session, "value numbers is [1, 2, 3]"); + complete(session, "value copied is numbers"); + scalar(session, "copied at 1", "i32", "2"); + complete(session, "value empty as array of number is []"); + const auto empty = complete(session, "empty"); + expect(empty.value && empty.value->type == "array" && empty.value->elements.empty(), + "retained empty arrays keep their concrete element type"); + complete(session, "value (Frame-Count, name) is (9, \"renderer\")"); + scalar(session, "FRAME_COUNT", "i32", "9"); + scalar(session, "name", "text", "renderer"); + const auto tuple = complete(session, "(answer, name, numbers)"); + expect(tuple.value && tuple.value->elements.size() == 3 && tuple.value->elements[2].elements.size() == 3, + "nested owned value projection"); + const auto json = nil::detail::json_parser(matrix::evaluation_report_json(tuple)).parse(); + expect(json.at("schema").text == "nil.matrix.submission-evaluation.v1", "evaluation schema"); + expect(json.object.count("nil") == 0, "runtime result must not expose internal binding envelope NIL"); + const auto before = session.bindings().size(); + complete(session, "when true then\nvalue hidden is 9\nend when"); + expect(session.bindings().size() == before, "nested bindings must not persist"); + rollback(session, "hidden", "invalid", false); + session.reset(); + expect(session.bindings().empty(), "reset clears retained data"); + rollback(session, "answer", "invalid", false); +} + +void transactions() { + matrix::submission_session session; + complete(session, "value seed is 7"); + rollback(session, "value temporary is 9\n1 over 0", "runtime-error", true); + rollback(session, "temporary", "invalid", false); + scalar(session, "seed", "i32", "7"); + const auto bad_path = session.evaluate("1 over 0", false, std::string(1, char(0xff)) + ".mat"); + const auto diagnostic = nil::detail::json_parser(matrix::evaluation_report_json(bad_path)).parse(); + expect(diagnostic.at("status").text == "runtime-error", "runtime diagnostics are valid UTF-8 for arbitrary file paths"); + scalar(session, "[1] at 2", "i32", "0"); + rollback(session, "value temporary is 9\n[(1, true)] at 2", "runtime-error", true); + rollback(session, "value temporary is 9\n1 plus true", "invalid", false); + rollback(session, "value temporary is 9\nsay \"effect\"", "invalid", false); + rollback(session, "value temporary is 9\n1e308 times 1e308", "runtime-error", true); + rollback(session, "value SEED is 8", "invalid", false); + rollback(session, "value later is", "incomplete", false); + scalar(session, "seed", "i32", "7"); + auto scope = complete(session, "when true then\nvalue local is 8\nend when\nvalue local is 4\nlocal"); + expect(scope.value && scope.value->scalar == "4" && scope.added.size() == 1, "export uses lexical slot resolution"); + scalar(session, "local", "i32", "4"); + const std::string request = + "nildata 1\nobject\nschema is \"nil.matrix.submission-request.v1\"\n" + "profile is \"matrix.pure.v1\"\nbindings is an array\nend array\n" + "value is an object\nkind is \"name\"\nname is \"SEED\"\nend object\nend object\n"; + const auto machine = session.evaluate(request, true, "request.nildata"); + expect(machine.committed && machine.value && machine.value->scalar == "7", "request reads retained source value"); +} + +void limits() { + matrix::session_limits limits; + limits.execution.max_instructions = 1; + matrix::submission_session short_run(limits); + rollback(short_run, "value lost is 1", "budget-exceeded", true); + limits = {}; + limits.max_state_bytes = 8; + matrix::submission_session small_state(limits); + complete(small_state, "value x is 1"); + rollback(small_state, "value y is 2", "budget-exceeded", true); + scalar(small_state, "x", "i32", "1"); + limits = {}; + limits.max_report_bytes = 64; + matrix::submission_session small_report(limits); + rollback(small_report, "value x is 1", "budget-exceeded", true); + limits = {}; + bool cancelled = false; + limits.execution.cancelled = [&] { return cancelled; }; + matrix::submission_session cancel_run(limits); + complete(cancel_run, "value retained is 3"); + cancelled = true; + rollback(cancel_run, "value lost is 9", "cancelled", false); + cancelled = false; + scalar(cancel_run, "retained", "i32", "3"); + limits = {}; + limits.execution.max_work_bytes = 1024; + matrix::submission_session limited_work(limits); + rollback(limited_work, "value payload is \"" + std::string(2048, 'x') + "\"", "budget-exceeded", true); +} +} // namespace + +int main() { + try { retained_values(); transactions(); limits(); } + catch (const std::exception &error) { std::cerr << error.what() << '\n'; return 1; } + std::cout << checks << " session checks passed\n"; +} diff --git a/tests/submission_vm_tests.cpp b/tests/submission_vm_tests.cpp new file mode 100644 index 00000000..9b6848b9 --- /dev/null +++ b/tests/submission_vm_tests.cpp @@ -0,0 +1,214 @@ +#include "codegen.hpp" +#include "nil_loader.hpp" +#include "submission_profile.hpp" +#include "vm.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +int failures = 0; +void check(bool ok, const std::string &name) { + if (!ok) { ++failures; std::cerr << "FAIL: " << name << '\n'; } +} +ny::nil_module module(std::string type, std::vector body) { + ny::nil_module result; + result.module_name = "root"; + ny::nil_function function; + function.name = "__nil_submission"; + function.return_type = std::move(type); + function.body = std::move(body); + result.functions.push_back(std::move(function)); + return result; +} +void load(ny::VM &vm, const ny::nil_module &module) { + ny::validate_nil_submission_profile(module); + std::ostringstream source; + ny::nil_writer(source).emit_text_module(module); + std::istringstream input(source.str()); + std::unordered_map constants; + auto program = ny::parseProgram(input, constants); + vm.loadProgram(program, constants); + vm.resetExecution("__nil_submission"); +} +void finish(ny::VM &vm) { while (vm.stepInstruction()) {} } +ny::submission_value evaluate(const ny::nil_module &module, ny::pure_execution_limits limits = {}) { + ny::VM vm; + vm.configurePureExecution(std::move(limits)); + load(vm, module); + finish(vm); + return vm.snapshotPureValue(vm.getStack().back(), module.functions.front().return_type); +} +void rejects(const std::function &action, const std::string &name) { + try { action(); check(false, name); } + catch (const std::runtime_error &) {} +} +void budget(const std::function &action, const std::string &name, + ny::pure_execution_error::kind kind = ny::pure_execution_error::kind::budget) { + try { action(); check(false, name); } + catch (const ny::pure_execution_error &error) { check(error.reason == kind, name + " typed reason"); } + catch (const std::exception &error) { check(false, name + ": " + error.what()); } +} +void scalars() { + const auto integer = evaluate(module("i32", {{"PUSH_CONST", {"2147483647"}}, + {"PUSH_CONST", {"1"}}, {"ADD", {"i32"}}, {"RET", {}}})); + check(integer.type == "i32" && integer.scalar == "-2147483648", "shared VM i32 overflow semantics"); + const auto boolean = evaluate(module("bool", {{"PUSH_CONST", {"4"}}, + {"PUSH_CONST", {"5"}}, {"CMP_LT", {}}, {"RET", {}}})); + check(boolean.scalar == "true", "canonical boolean snapshot"); + const auto negative_zero = evaluate(module("f64", {{"PUSH_CONST", {"-0.0"}}, {"RET", {}}})); + check(negative_zero.scalar == "-0.0", "negative zero survives snapshot"); + const auto floating = evaluate(module("f64", {{"PUSH_CONST", {"0.1"}}, {"RET", {}}})); + check(std::stod(floating.scalar) == 0.1, "f64 roundtrip snapshot"); + rejects([&] { (void)evaluate(module("i32", {{"PUSH_CONST", {"1"}}, + {"PUSH_CONST", {"0"}}, {"DIV", {"i32"}}, {"RET", {}}})); }, "division failure propagates"); + ny::VM vm; vm.configurePureExecution(); + rejects([&] { (void)vm.snapshotPureValue(std::numeric_limits::infinity(), "f64"); }, + "nonfinite snapshot rejected"); + rejects([&] { (void)vm.snapshotPureValue(int64_t(2), "bool"); }, "noncanonical boolean rejected"); + rejects([&] { (void)vm.snapshotPureValue(ny::ArrayHandle{1}, "array"); }, "foreign array handle rejected"); +} +ny::nil_module text_module() { + auto result = module("text", {{"PUSH_CONST_STR", {"a"}}, {"PUSH_CONST_STR", {"a"}}, + {"STR_CONCAT", {}}, {"RET", {}}}); + result.string_constants = {{"a", "abcd"}}; + return result; +} +void limits() { + auto limits = ny::pure_execution_limits{}; + limits.max_text_bytes = 7; + ny::VM vm; vm.configurePureExecution(limits); load(vm, text_module()); + while (vm.getProgram()[vm.getPC()].op != ny::Opcode::STR_CONCAT) vm.stepInstruction(); + const auto count = vm.pureInstructionsExecuted(); + budget([&] { vm.stepInstruction(); }, "concatenation checked before mutation"); + check(vm.getStack().size() == 2 && std::get(vm.getStack()[0]) == "abcd" && + std::get(vm.getStack()[1]) == "abcd" && vm.pureInstructionsExecuted() == count, + "failed preflight preserves operands and execution count"); + + limits = {}; limits.max_text_bytes = 3; + ny::VM formatting; formatting.configurePureExecution(limits); + load(formatting, module("text", {{"PUSH_CONST", {"1234"}}, {"TO_STRING", {"i32"}}, {"RET", {}}})); + while (formatting.getProgram()[formatting.getPC()].op != ny::Opcode::TO_STRING) formatting.stepInstruction(); + const auto format_count = formatting.pureInstructionsExecuted(); + budget([&] { formatting.stepInstruction(); }, "formatting respects a small custom text budget"); + check(formatting.getStack().size() == 1 && std::get(formatting.getStack().back()) == 1234 && + formatting.pureInstructionsExecuted() == format_count, "formatting failure preserves its scalar operand"); + limits.max_text_bytes = 2; + check(evaluate(module("text", {{"PUSH_CONST", {"42"}}, {"TO_STRING", {"i32"}}, {"RET", {}}}), limits).scalar == "42", + "small text budget admits an exactly fitting scalar"); + limits.max_text_bytes = 4; + check(evaluate(module("text", {{"PUSH_CONST", {"1"}}, {"TO_STRING", {"bool"}}, {"RET", {}}}), limits).scalar == "true", + "boolean formatting uses its actual text size"); + + auto small_tuple = module("tuple", {{"NEW_STRUCT", {"tuple"}}, + {"PUSH_CONST_STR", {"t"}}, {"SET_FIELD", {"0"}}, {"RET", {}}}); + small_tuple.structs = {{"tuple", {{"0", "text"}}, {"@nil_tuple"}}}; + small_tuple.string_constants = {{"t", "a"}}; + limits.max_text_bytes = 1; + check(evaluate(small_tuple, limits).elements.front().scalar == "a", + "text budget applies to values rather than tuple metadata"); + + limits = {}; limits.max_instructions = 1; + budget([&] { (void)evaluate(module("i32", {{"PUSH_CONST", {"42"}}, {"RET", {}}}), limits); }, + "instruction budget"); + limits = {}; limits.max_work_bytes = 300; + budget([&] { (void)evaluate(text_module(), limits); }, "work budget"); + limits = {}; limits.max_snapshot_bytes = 70; + budget([&] { (void)evaluate(text_module(), limits); }, "snapshot byte budget"); + limits = {}; limits.cancelled = [] { return true; }; + budget([&] { (void)evaluate(text_module(), limits); }, "cancellation", + ny::pure_execution_error::kind::cancelled); + + bool cancelled = false; + limits = {}; limits.cancelled = [&] { return cancelled; }; + ny::VM snapshot; snapshot.configurePureExecution(limits); load(snapshot, text_module()); finish(snapshot); + cancelled = true; + budget([&] { (void)snapshot.snapshotPureValue(snapshot.getStack().back(), "text"); }, + "snapshot cancellation", ny::pure_execution_error::kind::cancelled); + + limits = {}; limits.max_snapshot_nodes = 2; + budget([&] { (void)evaluate(module("array", {{"PUSH_CONST", {"1"}}, + {"PUSH_CONST", {"2"}}, {"NEW_ARRAY_LITERAL", {"2", "i32"}}, {"RET", {}}}), limits); }, + "aggregate node budget"); +} +void ownership() { + const auto array = evaluate(module("array", {{"PUSH_CONST", {"3"}}, + {"PUSH_CONST", {"7"}}, {"NEW_ARRAY_LITERAL", {"2", "i32"}}, {"RET", {}}})); + check(array.elements.size() == 2 && array.elements[0].scalar == "3" && array.elements[1].scalar == "7", + "array snapshot outlives VM heap"); + auto nested = module("array>", {{"PUSH_CONST", {"9"}}, + {"NEW_ARRAY_LITERAL", {"1", "i32"}}, {"NEW_ARRAY_LITERAL", {"1", "array"}}, {"RET", {}}}); + check(evaluate(nested).elements.front().elements.front().scalar == "9", "nested array snapshot"); + + auto tuple = module("tuple>", {{"NEW_STRUCT", {"tuple>"}}, + {"PUSH_CONST_STR", {"t"}}, {"SET_FIELD", {"0"}}, {"PUSH_CONST", {"9"}}, + {"NEW_ARRAY_LITERAL", {"1", "i32"}}, {"SET_FIELD", {"1"}}, {"RET", {}}}); + tuple.structs = {{"tuple>", {{"0", "text"}, {"1", "array"}}, {"@nil_tuple"}}}; + tuple.string_constants = {{"t", "owned"}}; + ny::VM vm; vm.configurePureExecution(); load(vm, tuple); finish(vm); + const auto result = vm.snapshotPureValue(vm.getStack().back(), tuple.functions.front().return_type); + std::get(vm.getStack().back()).data->string_fields["0"] = "changed"; + check(result.elements[0].scalar == "owned" && result.elements[1].elements[0].scalar == "9", + "tuple snapshot does not retain mutable StructData aliases"); + vm.resetExecution("__nil_submission"); + check(result.elements[1].elements[0].scalar == "9", "snapshot survives reset"); + check(vm.pureInstructionsExecuted() == 0 && vm.pureWorkBytesCharged() == 0, "reset starts fresh budgets"); +} +void admission() { + auto valid = module("i32", {{"PUSH_CONST", {"42"}}, {"RET", {}}}); + std::ostringstream text; ny::nil_writer(text).emit_text_module(valid); + std::istringstream input(text.str()); + std::unordered_map constants; + const auto program = ny::parseProgram(input, constants); + auto altered = program; + altered[2] = {ny::Opcode::TIME_NOW, {}}; + rejects([&] { ny::VM vm; vm.configurePureExecution(); vm.loadProgram(altered, constants); }, + "raw executable alteration is revalidated"); + altered = program; + altered.insert(altered.end() - 1, {ny::Opcode::CONSOLE_WRITELN, {}}); + rejects([&] { ny::VM vm; vm.configurePureExecution(); vm.loadProgram(altered, constants); }, + "effectful unreachable instruction denied before execution"); + altered = program; altered[2] = {ny::Opcode::JMP, {"__nil_submission"}}; + rejects([&] { ny::VM vm; vm.configurePureExecution(); vm.loadProgram(altered, constants); }, + "branch out of admitted body rejected"); + rejects([&] { ny::VM vm; vm.loadProgram(program, constants); vm.configurePureExecution(); }, + "pure mode requires fresh VM"); +} +void no_ambient_profile() { + const auto directory = std::filesystem::temp_directory_path() / + ("nil-pure-profile-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + std::filesystem::create_directory(directory); + const auto path = directory / "capture.json"; + const auto *old = std::getenv("NIL_MEMORY_PROFILE"); + const std::string prior = old ? old : ""; + const bool had_prior = old != nullptr; +#ifdef _WIN32 + _putenv_s("NIL_MEMORY_PROFILE", path.string().c_str()); +#else + setenv("NIL_MEMORY_PROFILE", path.string().c_str(), 1); +#endif + (void)evaluate(module("i32", {{"PUSH_CONST", {"1"}}, {"RET", {}}})); + check(!std::filesystem::exists(path), "pure execution ignores ambient Aperture output"); +#ifdef _WIN32 + _putenv_s("NIL_MEMORY_PROFILE", prior.c_str()); +#else + if (had_prior) setenv("NIL_MEMORY_PROFILE", prior.c_str(), 1); else unsetenv("NIL_MEMORY_PROFILE"); +#endif + std::filesystem::remove_all(directory); +} +} // namespace + +int main() { + try { scalars(); limits(); ownership(); admission(); no_ambient_profile(); } + catch (const std::exception &error) { check(false, std::string("unexpected exception: ") + error.what()); } + if (!failures) std::cout << "pure submission VM tests passed\n"; + return failures ? 1 : 0; +}