diff --git a/CMakeLists.txt b/CMakeLists.txt index 1961f27d..a690a681 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2352,6 +2352,7 @@ if(BUILD_TESTING) LABELS "typecheck;analysis;rc" TIMEOUT 120) foreach(parity_fixture IN ITEMS scientific-literals scientific-literals-matrix formatted-text formatted-text-matrix + tuple-arrays tuple-arrays-matrix signed-numbers-matrix integer-literal-widths integer-literal-widths-matrix checked-text-spans checked-text-spans-matrix @@ -2409,6 +2410,22 @@ if(BUILD_TESTING) --llvm "${NIL_ENABLE_LLVM}") set_tests_properties(nil.tuple-contract PROPERTIES LABELS "ny;matrix;analysis;tuples;routes" TIMEOUT 180) + add_test(NAME nil.tuple-array-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/tuple_array_contract.py" + --compiler $ --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.tuple-array-contract PROPERTIES + LABELS "ny;matrix;analysis;tuples;arrays;routes" TIMEOUT 240) + if(TARGET nilassembler AND TARGET nillinker) + add_test(NAME nil.tuple-array-nil-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/tuple_array_nil_contract.py" + --interpreter $ --assembler $ + --linker $ --runtime $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.tuple-array-nil-contract PROPERTIES + LABELS "nil;native;interpreter;arrays;tuples" TIMEOUT 120) + endif() add_test( NAME ny.scientific-literals-contract COMMAND "${Python3_EXECUTABLE}" diff --git a/docs/advanced/nil-format.md b/docs/advanced/nil-format.md index e791f7d4..295b6b08 100644 --- a/docs/advanced/nil-format.md +++ b/docs/advanced/nil-format.md @@ -245,11 +245,14 @@ can type-check but still fails if it reads before initialization. ## Native arrays and aggregate references Native arrays are runtime descriptors with exact element kinds for `i32`, -`i64`, `bool`, `u8`, `f64`, and NUL-free `text`. `f64` values retain their bits; -text elements hold traced text pointers, not integer values. Function and -field boundaries preserve array element identity. An out-of-range read yields -the element's zero value (`0.0` or empty text for the added kinds); an -out-of-range write is a no-op. Nested array elements remain unsupported. +`i64`, `bool`, `u8`, `f64`, NUL-free `text`, and supported structural tuples. +`f64` values retain their bits; text and tuple elements hold traced pointers. +Tuple metadata preserves the exact ordered `@nil_tuple` schema, including +nominal type names. Function and field boundaries preserve array element +identity. Scalar out-of-range reads yield the element's zero value; tuple reads +fail on an invalid index or uninitialized element rather than fabricating a +default tuple. Out-of-range writes are no-ops. Arrays of records, enums and +nested arrays remain unsupported natively. The public STL array primitives lower to `INTEROP_CALL intrinsic operation arity result_type element_type`, where @@ -260,7 +263,8 @@ is exact element metadata, not an FFI calling convention. Constructors return Size and index arguments use the `i32` contract; constructors reject negative sizes and raw NIL values outside that range instead of truncating or clamping. The historical four-operand `array.length 1 i64` form remains readable. -Declared `f32` helpers and aggregate-element constructors reject explicitly. +Declared `f32` helpers and unsupported aggregate-element constructors reject +explicitly. Tuple constructors, getters and setters require matching schemas. Nested struct fields hold nominally typed object handles, matching the VM's reference semantics. `ref` and aggregate-only `REF_LOCAL` preserve that @@ -283,7 +287,7 @@ allocators themselves do not collect. Return values are spilled by the caller before another safepoint can run. The same instrumentation is used by JIT, native compilation and standalone assembly. -The runtime traces owned blocks and text-array elements, including reachable +The runtime traces owned blocks and text/tuple-array elements, including reachable cycles and nested aggregate/enum payloads. It follows only known owned address ranges, not arbitrary words as host pointers. Numeric words that resemble addresses may conservatively retain an object. Static root slots are reused diff --git a/docs/design/NIL-0015-structural-tuples.md b/docs/design/NIL-0015-structural-tuples.md index c51c476d..ca07f60a 100644 --- a/docs/design/NIL-0015-structural-tuples.md +++ b/docs/design/NIL-0015-structural-tuples.md @@ -44,6 +44,33 @@ array unpacking retains its separate interpreter behavior. Static positional access must be within the shape's arity. Numeric member tokenization keeps `value.0.1` distinct from decimal literals. +## Tuple arrays + +Native tuple arrays use a distinct managed element kind containing traced tuple +handles. Their exact `tuple` metadata selects the annotated record +schema; names of nominal types inside the shape retain their case. Empty arrays +materialize the schema too. Construction, indexed replacement, append and the +generic array intrinsics validate the same element shape, including when source +type checking is disabled. A tuple handle cannot be substituted for a different +ordered shape. Fresh literals may apply checked element conversions at a +declared construction boundary; existing tuple values and arrays remain invariant. + +The container is mutable while tuple slots remain immutable. Replacing an array +element leaves extracted tuple handles intact. Shared record/reference fields +retain identity through aliasing, copying, array growth and function returns. +Native tracing follows tuple handles and their transitive text/aggregate fields. + +Ordinary and destructuring loops evaluate their array expression once. Literal, +named and function-returned arrays use indexed traversal of the selected array; +rebinding a source variable does not retarget the running loop. Bindings keep +their normal scope and control-flow behavior, including `break` and `continue`. + +Tuple-array reads require a valid initialized element. Out-of-range reads fail +instead of manufacturing a tuple with default fields. Out-of-range writes remain +no-ops, and existing scalar-array bounds behavior is unchanged. This extension +does not enable native arrays with record, enum or array elements, nor arbitrary +pointer-valued array storage. + ## Boundaries - No empty tuple/unit value; existing Ny `()` remains the `void` type. @@ -53,8 +80,8 @@ access must be within the shape's arity. Numeric member tokenization keeps destructured with another declaration. Module/global destructuring is not supported. - Owned buffers and borrows cannot be tuple elements. -- Arrays of tuples execute only in the interpreter until native aggregate - arrays receive their own qualified layout contract. +- Tuple arrays require one exact supported schema. Native arrays of records, + enums and nested arrays remain outside this layout contract. - Tuple patterns support bindings, wildcards, scalar literals and nested tuples. This does not expand nested enum-payload patterns. - A tuple inside a public signature has its canonical structural shape, but @@ -68,6 +95,16 @@ reference identity, discarded positions and match forms through executable text/binary NIL, bundles and LLVM routes. `tests/tools/tuple_contract.py` checks invalid shapes, slot writes, huge/out-of-range positions and arity errors, verifies cross-language consumers using source and binary libraries with the -original source files removed, and tests the interpreter/native tuple-array -boundary. Interpreter loop coverage includes named and literal arrays as well -as singleton tuples in both frontends. +original source files removed. Its tuple-array loop cases cover direct, named +and returned arrays, singleton tuples, discarded positions, evaluation order +and control flow in both frontends and execution modes. + +`tests/language/tuple-arrays.ny`, `tests/language/tuple-arrays-matrix.matrix` and +`tests/tools/tuple_array_contract.py` cover indexing, whole-tuple replacement, +scalar/text/nested fields, shared record identities, growth and returned values, +concrete and generic enum fields, typed base/interior/one-past pointers, +generic standard-library primitives and overlapping checked copies. The contract +also exercises cross-language source/binary-library consumers, exact schema +rejection before output replacement, tuple bounds failures and remaining native +aggregate-array exclusions. Native runtime tests inspect transitive collection +and reclamation through tuple arrays. diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index 4b5f93a0..d153fc93 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -46,7 +46,7 @@ modules, `nilstd` with the matching Ny and Matrix sources, compiled HTML in `doc hash-bearing `manifest.json`. The complete command set is `nilcompiler`, `nilinterpreter`, `nilassembler`, -`nillinker`, `nillsp`, `nildebugger`, `nilschema`, `nilagent`, and `nilbuild` (with the host +`nillinker`, `nillsp`, `nildebugger`, `nilschema`, `nilagent`, `nilbuild`, and `aperture` (with the host platform's executable suffix where needed). The helper validates this layout and only replaces the active SDK after the entire standard library and smoke path pass. @@ -103,7 +103,7 @@ LLVM is optional. If CMake cannot find it, configure with compiler, NIL interpreter, debugger, language server, assembler, and linker are always built. `NIL_BUILD_EXPERIMENTAL_TOOLS=OFF` omits only `nilschema` and `nilagent` in a direct developer build. The SDK helper keeps the option enabled -because the complete SDK includes all nine commands. +because the complete SDK includes all ten commands. Aperture is a separately versioned preview. When tests are enabled, CMake requires Python rather than silently omitting the route matrix and application contracts. Set `NIL_RUN_TESTS=OFF` with the helper, diff --git a/docs/language-reference/functions.md b/docs/language-reference/functions.md index f3d86cb9..53011c5d 100644 --- a/docs/language-reference/functions.md +++ b/docs/language-reference/functions.md @@ -42,7 +42,8 @@ end fn Supported native function boundaries currently include integer and boolean words, `f64`, named/concrete generic enums, text, `array`, -`ptr`, and validated concrete struct layouts. Generic struct +arrays of supported structural tuples, `ptr`, and validated +concrete struct layouts. Generic struct schemas are materialized for supported field layouts, including `f64`/`u8` fields, nested struct handles and `ref`. These references preserve shared object identity; they are not scalar stack references or a borrow checker. Scalar references, diff --git a/docs/language-reference/tuples.md b/docs/language-reference/tuples.md index 0ba5020e..2ba70e0e 100644 --- a/docs/language-reference/tuples.md +++ b/docs/language-reference/tuples.md @@ -65,19 +65,54 @@ a mutable record field without replacing the tuple's slot. This follows the existing record-handle contract, not C by-value aggregate layout. Tuples can nest and participate in generic function signatures. Scalar, text, -and supported record/reference elements use the existing native field layouts. +and supported record/reference, enum and typed-pointer elements use the existing +native field layouts. Owned buffers and borrows cannot be hidden inside tuples. Record field, pointer, and foreign-call restrictions still apply; tuples do not establish a C-compatible ABI. Tuple patterns support binding names, `_`, scalar literals and nested tuple patterns in Ny `match` and Matrix `consider`. Guards execute after the pattern -has bound its names. Tuple-array loops can unpack elements in the interpreter; -arrays of tuple handles remain outside the native array contract and are -rejected by native compilation. Loop unpacking requires tuple elements with -matching arity; scalar arrays and numeric ranges cannot be unpacked. Existing -interpreter unpacking of homogeneous nested arrays remains available. -Declaration destructuring is local only. +has bound its names. Declaration destructuring is local only. + +## Arrays of tuples + +Tuple arrays work in interpreted and native code. Every element has the same +ordered tuple schema. The array is mutable: indexing, whole-element replacement, +`push`, and the shared `nil.std.collections` array primitives preserve that +schema. The tuple slots themselves remain immutable. Array aliases observe +replacement and growth, while a previously extracted tuple keeps its value. +Contained record and reference values keep their shared identities. + +```ny +let points: array<(f64, f64)> = [(1.0, 2.0), (3.0, 4.0)] +points[0] = (-1.5, 2.5) +points.push((5.0, 6.0)) +for (x, y) in points + println(x + y) +end for +``` + +Ny `for (x, y) in points` and Matrix `repeat for each (x, y) in points` +unpack tuples with matching arity. A loop evaluates its array expression once, +including a function call returning the array. Rebinding the source variable +inside the body does not change that selected array. Ordinary iteration binds +the entire tuple; `_` can discard individual positions. Scalar arrays and +numeric ranges cannot be unpacked into tuple bindings. Existing interpreter +unpacking of homogeneous nested arrays remains available. + +An out-of-range tuple-array read is a runtime error, including reads through +`get`. A tuple has no synthetic zero/default value. Out-of-range writes are +no-ops, and scalar arrays keep their existing zero-valued read behavior. Use +checked collection operations or validate bounds before reading. Native arrays +whose elements are records, enums or arrays remain unsupported; a supported +tuple may itself contain supported record/reference elements or nested tuples. +Declared enum fields retain their concrete type, including generic arguments. +Typed raw-pointer fields preserve the pointer value, including an interior or +one-past pointer; storing a pointer in a tuple does not transfer ownership or +permit dereferencing one-past storage. Release the original allocation explicitly +after its final use. See [NIL-0015](../design/NIL-0015-structural-tuples.md) for the representation and -[tuple contract tests](../../tests/tools/tuple_contract.py) for route coverage. +the [tuple](../../tests/tools/tuple_contract.py) and +[tuple-array](../../tests/tools/tuple_array_contract.py) contracts for route coverage. diff --git a/docs/language-reference/types.md b/docs/language-reference/types.md index 7c134b8d..58798290 100644 --- a/docs/language-reference/types.md +++ b/docs/language-reference/types.md @@ -118,12 +118,16 @@ array, tuple, and native-call layouts have narrower contracts than a general C-compatible ABI. Standard-library collections are separate APIs, not an implied built-in map literal or interchangeable `vec` syntax. -The evidenced native array elements are `i32`, `i64`, `u8`, `bool`, `f64`, and -NUL-free text. Typed out-of-range reads return the element's zero value; -out-of-range writes do nothing. `push` requires a compatible element and +Native array elements include `i32`, `i64`, `u8`, `bool`, `f64`, NUL-free text, +and supported structural tuples. Scalar out-of-range reads return the element's +zero value; tuple-array reads fail because a tuple has no default zero value. +Out-of-range writes do nothing. `push` requires a compatible element and preserves aliases when the descriptor grows. Use an explicit cast before pushing an integer into `array`; storage does not reinterpret its bits. -Nested arrays and raw `ptr`/`ptr` remain outside this native subset. +Tuple arrays retain one exact ordered schema and permit whole-element +replacement while tuple slots stay immutable. See the [tuple reference](tuples.md). +Native arrays of records, enums and nested arrays, and raw +`ptr`/`ptr`, remain outside this subset. ## Structs and generic enums diff --git a/docs/release/v1-profile.md b/docs/release/v1-profile.md index 03413e72..934e2e18 100644 --- a/docs/release/v1-profile.md +++ b/docs/release/v1-profile.md @@ -77,9 +77,11 @@ parallel map, and sleep. The manuals define their precise limits: Source `println` has exactly one argument on every route, including unchecked frontend mode. Use `println("")` for a blank line. -The nine SDK commands are `nilcompiler`, `nilinterpreter`, `nilassembler`, -`nillinker`, `nildebugger`, `nillsp`, `nilbuild`, `nilschema`, and `nilagent`. The last two are -experimental utilities, not v1 language guarantees. The LSP has a deliberately +The ten SDK commands are `nilcompiler`, `nilinterpreter`, `nilassembler`, +`nillinker`, `nildebugger`, `nillsp`, `nilbuild`, `nilschema`, `nilagent`, and `aperture`. +`nilschema` and `nilagent` are experimental utilities, not v1 language guarantees. +Aperture is a separately versioned analysis/debugging preview; packaging it does +not extend the v1 language or debugger guarantees. The LSP has a deliberately limited capability set. `nilbuild` supports the [local-project profile](../tools/projects.md), with process execution qualified on Linux. `nypm` and `nilaix` are not part of this release. diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index ec5b7bbe..33e853dc 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -216,11 +216,16 @@ end paragraph The output is `1` then `3`; the array becomes `[1, 1, 2, 3]`. Ny calls the same function as `try_copy_range(pixels, 0, pixels, 1, 3)`. -The supported test slice covers `i32`, `i64`, `u8`, `bool`, `f64`, and NUL-free -`text`. It does not expand native support for record arrays, nested arrays, or -other scalar layouts. Checked byte stores retain the existing `u8` conversion +The scalar test slice covers `i32`, `i64`, `u8`, `bool`, `f64`, and NUL-free +`text`. The [tuple-array contract](../../tests/tools/tuple_array_contract.py) +adds generic construction, indexed/intrinsic access and overlapping checked +copies with exact tuple schemas. Copies preserve tuple values and contained +reference identities. Native record, enum and nested-array element arrays +remain unsupported. Checked byte stores retain the existing `u8` conversion rules; these APIs validate indices and ranges, not numeric conversions. -The older raw array accessors keep their existing zero/no-op bounds behavior. +Raw scalar array accessors retain their zero/no-op bounds behavior. Raw tuple +reads outside the array fail because no default tuple exists; use checked +operations or validate bounds before reading. The related `copy_to` guards on `list`, `queue`, `stack`, `hash_set`, and `dictionary` now check remaining destination space by subtraction. Invalid @@ -229,8 +234,8 @@ write. This fixes the extreme-offset overflow identified by the independent 3D validation project. Its copied SDK remains a historical test subject. Further array work remains: real vector reservation/resizing, strided buffer -views with ownership rules, and native aggregate arrays. None is implied by -these helpers. +views with ownership rules, and native record/enum/nested-array element layouts. +None is implied by these helpers. ## Stable index ordering diff --git a/docs/tools/index.md b/docs/tools/index.md index 45b0a047..fe2bfbc4 100644 --- a/docs/tools/index.md +++ b/docs/tools/index.md @@ -15,7 +15,7 @@ A complete SDK has the following top-level shape: ```text nilcompiler nilinterpreter nilassembler nillinker nillsp nildebugger nilschema nilagent -nilbuild +nilbuild aperture nillib/ nilstd/ docs/ manifest.json ``` @@ -35,6 +35,18 @@ and regenerates imported bodies. Direct compiled-body linking is a later format step, so `nillib` is a source-independent distribution today, not yet a zero-recompilation module cache. +Earlier sealed `nil.sdk.v1` generations contain the original nine commands; +validation continues to accept that complete inventory. New SDK builds require +Aperture, include its digest in the manifest and build evidence, and check its +help/version identity. Aperture retains its own preview version. + +## `aperture` + +Aperture is the framework's analysis and debugging preview, with `explore`, +`memory`, `trace`, and `agent` commands. Run `aperture --help` for its command +interface. Its prototype capabilities are separate from the v1 language and +`nildebugger` contracts. See the [Aperture overview](../../aperture/README.md). + ## `nilbuild` The [project driver](projects.md) provides `describe`, `check`, `build` and diff --git a/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index c21d00b2..39569609 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -694,5 +694,13 @@ reference values retain their existing identities. `(x)` groups an expression; `(x,)` is a one-element tuple. Its type is `tuple of (T)`. Use `_` to discard a position while destructuring. Names in a declaration are flat; nested tuple patterns are available in `consider`. Empty tuples, dynamic positional indexing -and global destructuring are not supported. See the shared +and global destructuring are not supported. + +`array of tuple of (number, text)` works in interpreted and native code. The +array can replace or append complete tuples while each tuple's slots stay +immutable. Use `repeat for each (count, label) in items` to unpack each element; +the array expression is evaluated once, including a paragraph call. An +out-of-range tuple-array read fails because there is no default tuple value. +Native arrays of records, choices and nested arrays remain unsupported. +See the shared [tuple reference](../docs/language-reference/tuples.md) for the exact contract. diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 033451b1..b1ed87aa 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1578,7 +1578,8 @@ interpolation and tuple editing alongside the new literal forms. ### F50 — Tuples need one structural type and representation across both languages -**Status:** Implemented for nonempty typed tuple values and local destructuring. +**Status:** Implemented for nonempty typed tuple values, local destructuring +and typed tuple arrays in the interpreter and native routes. The old checker and interpreter contained tuple-like `zip` and array-unpacking heuristics, while the surface documentation correctly withheld general tuples. @@ -1600,10 +1601,10 @@ and binary NIL, bundles, native routes, and cross-language consumers using source and binary libraries with the original source files removed. It also checks failure before replacing output. -**Follow-up:** Native arrays of tuple handles need their own storage contract; -the interpreter can already unpack such arrays. Nested declaration patterns, -named elements, unit values, user-defined tuple formatting and C ABI mapping -remain explicit future work. See [NIL-0015](../../docs/design/NIL-0015-structural-tuples.md). +**Follow-up:** The tuple-array storage and loop contract is implemented in F52. +Nested declaration patterns, named elements, unit values, user-defined tuple +formatting and C ABI mapping remain explicit future work. See +[NIL-0015](../../docs/design/NIL-0015-structural-tuples.md). ### F51 — Interpolation needs typed conversion and original expression spans @@ -1653,3 +1654,63 @@ currently callers must explicitly produce a supported scalar or text value. Precision and presentation options remain library calls rather than a second formatting grammar. The legacy implicit form still lacks original embedded name spans and retains its conservative editor exclusion. + +### F52 — Tuple arrays need exact schemas, managed lifetime and explicit bounds + +**Observation:** Typed tuple values alone did not make collections of tuples +portable. Native arrays had scalar element kinds only, generic array intrinsics +rejected tuples, and interpreter tuple-loop support could fall back to generic +iterator behavior. Disabling the source type checker also allowed mixed tuple +schemas into arrays. Treating an invalid read as scalar zero could then appear +to produce a tuple that had never been constructed. + +**Resolution:** Tuple arrays now have an explicit native element kind carrying +managed tuple handles and their exact ordered schema. Nominal names inside a +tuple retain their case. The VM checks the annotated schema and initialization +of stored tuples; native lowering and runtime tracing preserve tuple handles +and their reachable text, record and reference values. Empty arrays carry the +same schema as populated ones. Source mismatches reject before replacing an +output artifact, including when `--no-typecheck` is requested. Fresh tuple +literals can apply checked scalar conversions at declared construction +boundaries; existing tuple values and array types remain invariant. + +Raw NIL must also prove each tuple slot's declared kind and nominal identity. +An enum value cannot stand in for a record, different concrete generic enum +types cannot alias through a shared variant name, and an integer is not proof +of a live allocation. Pointer checks verify the allocation type and alignment, +including null and logical one-past values. Positive source cases preserve declared choices and live +typed base/interior/one-past pointers without changing pointer ownership rules. +Textual NIL loading now retains enum variants and payload types. Intrinsic +results retain concrete enum metadata, including generic `Result` values; +older annotated wrappers can recover that identity from their declared return. + +Indexed reads, whole-element replacement, append, generic new/get/set/length +and checked range copies share that representation. Array aliases observe +mutation and growth; extracted tuple values keep their immutable slots and +contained reference identities. Tuple loops evaluate the selected array once, +including direct paragraph returns, and retain ordinary binding scopes, +wildcards, `break` and `continue`. Rebinding the source name does not retarget +the active loop. + +Out-of-range tuple reads and uninitialized tuple slots fail explicitly. There +is no synthetic default tuple. Out-of-range writes remain no-ops, and existing +scalar-array read defaults are unchanged. Native arrays whose elements are +records, choices or other arrays remain excluded; support for tuple handles +does not establish a general aggregate-array ABI. + +**Coverage:** Paired Ny/Matrix tuple-array fixtures and +`tests/tools/tuple_array_contract.py` specify source and binary execution, +bundles, native compilation, cross-frontend source/binary-library consumption, +generic standard-library calls, overlap copies, schema failures and bounds. +The tuple contract includes direct, named and returned array loops. Native +runtime tests inspect aliasing, growth, transitive collection and reclamation. +Raw text/binary NIL tests cover malformed nominal fields and initialization, +legacy intrinsic wrappers, and collection at the tuple-initializer allocation +boundary. + +**Follow-up:** Extend other aggregate-array layouts only with equally explicit +schema, initialization and lifetime contracts. Nested declaration patterns, +custom formatting and native FFI layout remain separate work from storing +typed tuple handles. +The VM still represents raw pointers as integers: a matching virtual address +can establish a live allocation, but cannot establish the value's provenance. diff --git a/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index 7c6bcb58..35b6dd3b 100644 --- a/matrix/docs/ny-surface-inventory.md +++ b/matrix/docs/ny-surface-inventory.md @@ -136,7 +136,7 @@ about whether a value changed representation. | `*alias` on `ref` | no spelling | rejected in Ny | | `owned` | `owned array of ` | executed for `integer`, `long`, `byte` | | `borrow` / `borrow_mut` | `shared view of ` / `exclusive view of ` | executed | -| `(T, U)`, `(a, b)`, `let (a,b) = value` | `tuple of (T, U)`, `(a, b)`, `value (a,b) is result` | shared typed immutable tuple slots; native aggregate-array limits remain | +| `(T, U)`, `(a, b)`, `let (a,b) = value` | `tuple of (T, U)`, `(a, b)`, `value (a,b) is result` | shared immutable tuple slots and typed tuple arrays on VM/native routes; record/enum/nested-array element arrays remain excluded natively | Out-of-range typed array reads yield the element's zero value and out-of-range writes are a no-op. Matrix keeps that, because changing it would change NIL diff --git a/matrix/docs/types-and-text.md b/matrix/docs/types-and-text.md index a69d4635..e02a4a94 100644 --- a/matrix/docs/types-and-text.md +++ b/matrix/docs/types-and-text.md @@ -88,6 +88,14 @@ Array types remain invariant. The remaining inference questions are tracked in [F30](next-version-findings.md#f30--large-integer-expressions-can-narrow-before-an-i64-argument-conversion). Ny APIs accepting `i32` may instead require `becomes override integer`. +Tuples use `tuple of (number, text)` and can be stored in +`array of tuple of (number, text)` on interpreted and native routes. Each array +element retains the exact ordered tuple type; whole-element writes do not make +tuple slots mutable. Reading outside a tuple array is an error rather than a +synthetic tuple value. Scalar-array read defaults remain unchanged. Native +arrays of records, choices and nested arrays remain unsupported. See the +[tuple contract](../../docs/language-reference/tuples.md#arrays-of-tuples). + **`main` is a special case.** The NIL entry contract is `main() -> i32`. Matrix writes `main returns number` and the lowering emits `i32` for that one function. A process exit status is eight bits in practice, so nothing is lost, diff --git a/nilcompiler/src/array_intrinsic.hpp b/nilcompiler/src/array_intrinsic.hpp index 328b3861..2395891d 100644 --- a/nilcompiler/src/array_intrinsic.hpp +++ b/nilcompiler/src/array_intrinsic.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -23,6 +24,81 @@ inline std::string canonical_array_scalar(std::string type) { return type; } +// Array storage preserves nominal type identity. Normalize built-in aliases +// recursively, but never lowercase a record name inside a tuple shape. +inline std::string canonical_array_type(std::string type) { + type.erase(std::remove_if(type.begin(), type.end(), [](unsigned char ch) { + return std::isspace(ch) != 0; + }), type.end()); + std::size_t position = 0; + const auto parse = [&](const auto &self, unsigned depth) -> std::string { + if (depth >= 64) + throw std::runtime_error("array element type is excessively nested"); + const auto begin = position; + while (position < type.size() && type[position] != '<' && + type[position] != '>' && type[position] != ',') { + const auto character = static_cast(type[position]); + if (!std::isalnum(character) && character != '_' && character != ':' && + character != '.' && character != '-') + throw std::runtime_error("array element type has invalid syntax"); + ++position; + } + if (begin == position) + throw std::runtime_error("array element type has an empty type name"); + std::string name = type.substr(begin, position - begin); + const auto scalar = canonical_array_scalar(name); + if (scalar == "i32" || scalar == "i64" || scalar == "u8" || + scalar == "bool" || scalar == "f64" || scalar == "f32" || + scalar == "text" || scalar == "void") + name = scalar; + if (position < type.size() && type[position] == '<') { + ++position; + name += '<'; + bool first = true; + do { + if (!first) { name += ','; ++position; } + name += self(self, depth + 1); + first = false; + } while (position < type.size() && type[position] == ','); + if (position == type.size() || type[position] != '>') + throw std::runtime_error("array element type has unbalanced generic arguments"); + ++position; + name += '>'; + } + return name; + }; + auto result = parse(parse, 0); + if (position != type.size()) + throw std::runtime_error("array element type has trailing type syntax"); + return result; +} + +inline std::optional> +array_tuple_elements(const std::string &type) { + std::string canonical; + try { canonical = canonical_array_type(type); } + catch (const std::runtime_error &) { return std::nullopt; } + if (canonical.rfind("tuple<", 0) != 0 || canonical.back() != '>') + return std::nullopt; + std::vector elements; + std::size_t begin = 6; + unsigned depth = 0; + for (std::size_t index = begin; index + 1 < canonical.size(); ++index) { + if (canonical[index] == '<') ++depth; + else if (canonical[index] == '>') --depth; + else if (canonical[index] == ',' && depth == 0) { + elements.push_back(canonical.substr(begin, index - begin)); + begin = index + 1; + } + } + elements.push_back(canonical.substr(begin, canonical.size() - begin - 1)); + return elements; +} + +inline bool is_array_tuple_type(const std::string &type) { + return array_tuple_elements(type).has_value(); +} + inline bool is_array_intrinsic(const std::string &name) { return name == "array.new_with_value" || name == "array.new_u8" || name == "array.new_f32" || name == "array.get" || @@ -47,9 +123,10 @@ inline array_intrinsic_contract parse_array_intrinsic( !is_array_intrinsic(operands[1])) throw std::runtime_error("array intrinsic requires exact typed metadata"); const auto &name = operands[1]; - const std::string element = canonical_array_scalar(operands[4]); + const std::string element = canonical_array_type(operands[4]); if (element != "i32" && element != "i64" && element != "u8" && - element != "bool" && element != "f64" && element != "text") + element != "bool" && element != "f64" && element != "text" && + !is_array_tuple_type(element)) throw std::runtime_error("array intrinsic has unsupported element type '" + element + "'"); if ((name.find("_u8") != std::string::npos && element != "u8") || name.find("_f32") != std::string::npos) @@ -65,7 +142,7 @@ inline array_intrinsic_contract parse_array_intrinsic( ? "array<" + element + ">" : operation == array_intrinsic_operation::get ? element : operation == array_intrinsic_operation::length ? "i32" : "void"; - auto encoded_result = canonical_array_scalar(operands[3]); + auto encoded_result = canonical_array_type(operands[3]); if (encoded_result == "array" || encoded_result == "array") encoded_result = "array"; if (operands[2] != std::to_string(count) || encoded_result != result) diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index 6de51196..f0d69e48 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -1037,6 +1037,13 @@ static size_t get_native_size(codegen &cg, const std::string &type_name) { return 8; } +static bool is_declared_enum_type(codegen &cg, const std::string &type) { + const auto parsed = parse_generic_type_name(type); + const auto base = canonical_builtin_enum_base(parsed ? parsed->base_name : type); + return cg.lookup_enum_decl(base) || + cg.lookup_enum_decl(cg.lookup_enum_fqn(base)); +} + class emitter { public: emitter(nil_function &out, nil_module &mod, codegen &cg, @@ -1360,11 +1367,13 @@ class emitter { const auto parsed = parse_generic_type_name(array_type); if (!parsed || parsed->base_name != "array" || parsed->type_args.size() != 1) return reject("array intrinsic declaration requires an exact array type"); - const std::vector operands = { + std::vector operands = { "intrinsic", name, std::to_string(argument_count), result, - canonical_array_scalar(parsed->type_args[0])}; + parsed->type_args[0]}; array_intrinsic_contract contract; try { + operands[3] = canonical_array_type(operands[3]); + operands[4] = canonical_array_type(operands[4]); contract = parse_array_intrinsic(operands); } catch (const std::runtime_error &error) { return reject(error.what()); @@ -1382,13 +1391,18 @@ class emitter { if (declaration.params.size() != expected.size()) return reject("array intrinsic declaration has an invalid parameter count"); for (std::size_t index = 0; index < expected.size(); ++index) { - auto actual = canonical_array_scalar(substitute_nil_type_name( - declaration.params[index].type_name.value_or(""), concrete)); - if (actual == "array" || actual == "array") - actual = "array"; + std::string actual; + try { + actual = canonical_array_type(substitute_nil_type_name( + declaration.params[index].type_name.value_or(""), concrete)); + } catch (const std::runtime_error &error) { + return reject(error.what()); + } if (actual != expected[index]) return reject("array intrinsic declaration has an invalid parameter type"); } + if (is_array_tuple_type(contract.element)) + cg_.materialize_struct_schema(contract.element, mod_, line, 0, true); push_instr("INTEROP_CALL", operands, line); return true; } @@ -1926,18 +1940,28 @@ class emitter { } } - // Optimization: if the iterable is a named identifier and the emitter has - // seen a corresponding local variable with a container type (array / vec - // / slice), perform an index-based loop instead of using the generic - // iterator protocol. This avoids iterator overhead and enables more - // efficient codegen for common container loops. - if (!handled && for_s.iterable && - for_s.iterable->kind == ast_node_kind::identifier_expr_node) { - const auto &id = - static_cast(*for_s.iterable); - auto it = local_var_types.find(id.name); - if (it != local_var_types.end()) { - std::string var_type = it->second; + // Typed arrays use the same index-based lowering for names, literals, + // calls, and member expressions. Evaluate the array once before binding + // loop variables, so side effects and a binding that shadows its source + // cannot change which container the loop traverses. Other containers + // retain their existing named-local optimization. + if (!handled && for_s.iterable) { + std::string var_type = unambiguous_expression_type(*for_s.iterable); + std::string container_local; + const bool named = for_s.iterable->kind == ast_node_kind::identifier_expr_node; + if (named) { + const auto &id = static_cast(*for_s.iterable); + const auto local = local_var_types.find(id.name); + if (var_type.empty() && local != local_var_types.end()) + var_type = substitute_nil_type_name(local->second, substitutions); + if (local != local_var_types.end()) container_local = id.name; + } + const auto iterable_container = parse_generic_type_name(var_type); + const bool array_expression = + (iterable_container && iterable_container->base_name == "array" && + !iterable_container->type_args.empty()) || + (var_type.size() > 2 && var_type.compare(var_type.size() - 2, 2, "[]") == 0); + if (array_expression || !container_local.empty()) { // Helper lambdas for trimming and numeric detection auto trim_local = [](std::string s) { @@ -2014,6 +2038,12 @@ class emitter { // Implement index-based iteration for this container const bool typed_array = pos_array != std::string::npos || var_type.rfind("[]") != std::string::npos; + if (typed_array) { + container_local = new_temp("iterable"); + emit_expr(*for_s.iterable); + push_instr("STORE_LOCAL", {container_local}, for_s.line); + local_var_types[container_local] = var_type; + } std::string tmp_len = new_temp("len"); std::string tmp_idx = new_temp("idx"); @@ -2023,7 +2053,7 @@ class emitter { push_instr("STORE_LOCAL", {tmp_len}, for_s.line); } else { // Query runtime length: __ritual_len(container) - push_instr("LOAD_LOCAL", {id.name}, for_s.line); + push_instr("LOAD_LOCAL", {container_local}, for_s.line); if (typed_array) push_instr("LEN", {}, for_s.line); else @@ -2048,7 +2078,7 @@ class emitter { push_instr("JMP_IF_NOT", {end}, for_s.line); // value = __ritual_index(container, idx) - push_instr("LOAD_LOCAL", {id.name}, for_s.line); + push_instr("LOAD_LOCAL", {container_local}, for_s.line); push_instr("LOAD_LOCAL", {tmp_idx}, for_s.line); if (typed_array) push_instr("GET_INDEX", {}, for_s.line); @@ -2067,6 +2097,7 @@ class emitter { push_instr("STORE_LOCAL", {tmp_val}, for_s.line); for (size_t ii = 0; ii < for_s.variables.size(); ++ii) { const auto &pv = for_s.variables[ii]; + if (pv.name == "_") continue; push_instr("LOAD_LOCAL", {tmp_val}, for_s.line); if (elem_type && !extract_tuple_parts(*elem_type).empty()) { cg_.materialize_struct_schema(substitute_nil_type_name(*elem_type, substitutions), mod_, for_s.line); @@ -2247,6 +2278,7 @@ class emitter { // loop variables. for (size_t ii = 0; ii < for_s.variables.size(); ++ii) { const auto &pv = for_s.variables[ii]; + if (pv.name == "_") continue; push_instr("LOAD_LOCAL", {tmp_val}, for_s.line); const auto container = parse_generic_type_name( substitute_nil_type_name(for_s.iterable->inferred_type.value_or(""), substitutions)); @@ -2843,6 +2875,10 @@ class emitter { // instead of accepting a wildcard handle or trusting the first value. if (element_type == "any") element_type = unambiguous_array_element_type(arr); + // An empty array still exposes its tuple shape through its element + // metadata, even when no tuple constructor otherwise emits the schema. + if (is_array_tuple_type(element_type)) + cg_.materialize_struct_schema(element_type, mod_, arr.line, 0, true); push_instr("NEW_ARRAY_LITERAL", {std::to_string(arr.elements.size()), element_type}, arr.line); break; @@ -3840,14 +3876,8 @@ class emitter { if (!ce.type_args.empty()) { // Apply substitutions to type args std::vector concrete_type_args; - for (const auto &arg : ce.type_args) { - auto it = substitutions.find(arg); - if (it != substitutions.end()) { - concrete_type_args.push_back(it->second); - } else { - concrete_type_args.push_back(arg); - } - } + for (const auto &arg : ce.type_args) + concrete_type_args.push_back(substitute_nil_type_name(arg, substitutions)); // Mangle name: foo -> foo__i32 // Save FQN before type-arg suffix (used for queue_specialization key) @@ -3911,7 +3941,11 @@ class emitter { raw_ret = *fn_decl_for_intrinsic_check->return_type; } if (!raw_ret.empty() && raw_ret != "void") { - if (raw_ret == "text" || raw_ret == "String") { + if (is_declared_enum_type(cg_, raw_ret)) { + // Intrinsics return typed managed enum values. Their register + // width is not a substitute for the concrete generic identity. + ret_type_str = canonical_nil_type_name(raw_ret); + } else if (raw_ret == "text" || raw_ret == "String") { ret_type_str = "text"; } else { size_t sz = get_native_size(cg_, raw_ret); @@ -6062,7 +6096,9 @@ codegen::assemble_module(const ast_program &program, call.args.push_back(std::to_string(fn_decl.params.size())); std::string ret_type_str = "void"; - if (fn_decl.return_type.has_value()) { + if (is_declared_enum_type(*this, fn.return_type)) { + ret_type_str = canonical_nil_type_name(fn.return_type); + } else if (fn_decl.return_type.has_value()) { ret_type_str = *fn_decl.return_type; size_t sz = get_native_size( *this, ret_type_str); // Need `get_native_size` visibility? diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index a273f2ba..2fe4f4fa 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -419,6 +419,8 @@ native_array_kind_for_element(const std::string &type) { return NYRT_ARRAY_F64; if (normalized == "text" || normalized == "string" || normalized == "str") return NYRT_ARRAY_TEXT; + if (is_array_tuple_type(type)) + return NYRT_ARRAY_TUPLE; return std::nullopt; } @@ -430,24 +432,6 @@ static bool is_native_scalar_abi_type(const std::string &type) { normalized == "f64" || normalized == "bool" || normalized == "char"; } -static std::optional -native_generic_argument(const std::string &type, const std::string &name) { - const std::string normalized = normalize_nil_type(type); - const std::string prefix = name + "<"; - if (normalized.size() <= prefix.size() + 1 || - normalized.rfind(prefix, 0) != 0 || normalized.back() != '>') { - return std::nullopt; - } - const std::string argument = - normalized.substr(prefix.size(), normalized.size() - prefix.size() - 1); - if (argument.empty() || argument.find('<') != std::string::npos || - argument.find('>') != std::string::npos || - argument.find(',') != std::string::npos) { - return std::nullopt; - } - return argument; -} - static std::optional> native_generic_arguments(const std::string &type, const std::string &name) { const std::string normalized = compact_nil_type(type); @@ -487,18 +471,30 @@ native_generic_arguments(const std::string &type, const std::string &name) { return arguments; } +static std::optional +native_generic_argument(const std::string &type, const std::string &name) { + // A container has one argument even when that argument contains a nested + // tuple or generic record. Nominal case must survive extraction. + const auto compact = compact_nil_type(type); + if (normalize_nil_type(compact.substr(0, name.size() + 1)) != name + "<") + return std::nullopt; + const auto arguments = native_generic_arguments(type, name); + return arguments && arguments->size() == 1 + ? std::optional(arguments->front()) : std::nullopt; +} + static native_handle_kind native_handle_kind_for_nil_type(const std::string &type) { const std::string normalized = normalize_nil_type(type); if (normalized == "text" || normalized == "string" || normalized == "str") return native_handle_kind::text; - if (const auto element = native_generic_argument(normalized, "array")) { + if (const auto element = native_generic_argument(type, "array")) { return native_array_kind_for_element(*element).has_value() ? native_handle_kind::scalar_array : native_handle_kind::unsupported; } - if (const auto element = native_generic_argument(normalized, "ptr")) { + if (const auto element = native_generic_argument(type, "ptr")) { return is_native_word_element_type(*element) ? native_handle_kind::integer_pointer : native_handle_kind::unsupported; @@ -519,6 +515,9 @@ static bool native_handle_types_compatible(const std::string &actual, if (expected_kind == native_handle_kind::scalar_array) { const auto actual_element = native_generic_argument(actual, "array"); const auto expected_element = native_generic_argument(expected, "array"); + if (actual_element && expected_element && + (is_array_tuple_type(*actual_element) || is_array_tuple_type(*expected_element))) + return canonical_array_type(*actual_element) == canonical_array_type(*expected_element); return actual_element && expected_element && native_array_kind_for_element(*actual_element) == native_array_kind_for_element(*expected_element); @@ -1803,6 +1802,16 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return nullptr; const std::string normalized = normalize_nil_type(element_type); auto *i64_type = llvm::Type::getInt64Ty(ctx); + if (is_array_tuple_type(element_type)) { + if (!value->getType()->isPointerTy() || + canonical_array_type(impl_->nilType(value)) != canonical_array_type(element_type) || + !is_native_aggregate_nil_type(mod, element_type)) { + std::cerr << "[NativeCodegen] " << operation + << " requires an exact tuple element of type '" << element_type << "'\n"; + return nullptr; + } + return impl_->builder->CreatePtrToInt(value, i64_type, "ny.array.tuple.bits"); + } if (normalized == "f64") { if (normalize_nil_type(impl_->nilType(value)) != "f64") { std::cerr << "[NativeCodegen] " << operation @@ -1864,6 +1873,9 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto native_array_loaded_value = [&](llvm::Value *word, const std::string &element_type) -> llvm::Value * { const auto kind = native_array_kind_for_element(element_type); + if (kind == NYRT_ARRAY_TUPLE) + return impl_->builder->CreateIntToPtr( + word, llvm::PointerType::getUnqual(ctx), "ny.array.tuple.value"); if (kind == NYRT_ARRAY_F64) return impl_->builder->CreateBitCast( word, llvm::Type::getDoubleTy(ctx), "ny.array.f64.value"); @@ -2158,10 +2170,40 @@ bool NativeCodegen::generateModule(const nil_module &mod) { std::unordered_set reachable_structs; std::vector struct_worklist; + std::unordered_set visited_layout_types; + bool valid_tuple_schemas = true; auto add_struct_type = [&](const std::string &type) { - if (const auto *definition = find_native_aggregate_definition(mod, type)) { - if (reachable_structs.insert(definition).second) + std::vector pending{type}; + while (!pending.empty()) { + const auto current = compact_nil_type(pending.back()); + pending.pop_back(); + if (!visited_layout_types.insert(current).second) + continue; + const auto *definition = find_native_aggregate_definition(mod, current); + if (is_array_tuple_type(current)) { + const auto fields = native_generic_arguments(current, "tuple"); + bool valid = definition && fields && definition->fields.size() == fields->size() && + compact_nil_type(definition->name) == current && + std::find(definition->annotations.begin(), definition->annotations.end(), + "@nil_tuple") != definition->annotations.end(); + if (valid) + for (std::size_t i = 0; i < fields->size(); ++i) + valid = valid && definition->fields[i].first == std::to_string(i) && + canonical_array_type(definition->fields[i].second) == canonical_array_type((*fields)[i]); + if (!valid) { + std::cerr << "[NativeCodegen] tuple type '" << current + << "' requires its exact ordered @nil_tuple schema\n"; + valid_tuple_schemas = false; + } + } + if (definition && reachable_structs.insert(definition).second) struct_worklist.push_back(definition); + if (const auto element = native_generic_argument(current, "array")) + pending.push_back(*element); + if (const auto *enumeration = find_nil_enum_definition(mod, current)) + for (const auto &variant : enumeration->variants) + if (const auto payloads = native_enum_variant_payload_types(variant)) + pending.insert(pending.end(), payloads->begin(), payloads->end()); } }; @@ -2185,6 +2227,15 @@ bool NativeCodegen::generateModule(const nil_module &mod) { !instruction.args.empty()) { add_struct_type(instruction.args[0]); } + if (opcode == Opcode::NEW_ARRAY_LITERAL && instruction.args.size() >= 2) + add_struct_type(instruction.args[1]); + if (opcode == Opcode::INTEROP_CALL && instruction.args.size() == 5 && + instruction.args[0] == "intrinsic" && is_array_intrinsic(instruction.args[1])) { + add_struct_type(instruction.args[3]); + add_struct_type(instruction.args[4]); + } + if (opcode == Opcode::NEW_VARIANT && instruction.args.size() >= 3) + add_struct_type(instruction.args[2]); } } @@ -2207,6 +2258,9 @@ bool NativeCodegen::generateModule(const nil_module &mod) { } } + if (!valid_tuple_schemas) + return false; + // Acyclic nested objects are supported. Keep recursive schema shapes closed // until nullable/recursive initialization has a defined language contract. // Peel leaves iteratively so malformed deeply nested schemas cannot consume @@ -2219,7 +2273,11 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto &pending = pending_dependencies[definition]; for (const auto &[field_name, field_type] : definition->fields) { (void)field_name; - if (const auto *nested = find_native_aggregate_definition(mod, field_type)) { + // An array is a handle, but its tuple schema still contributes a + // dependency. Recursive aggregate graphs keep the existing rejection. + const auto element = native_generic_argument(field_type, "array"); + if (const auto *nested = find_native_aggregate_definition( + mod, element && is_array_tuple_type(*element) ? *element : field_type)) { ++pending; dependent_structs[nested].push_back(definition); } @@ -3216,12 +3274,13 @@ bool NativeCodegen::generateModule(const nil_module &mod) { const std::string value_type = nil_parameter_type(fn.params[1]); if (!element_type || !native_array_kind_for_element(*element_type) || normalize_nil_type(size_type) != "i32" || - normalize_nil_type(value_type) != - normalize_nil_type(*element_type) || + canonical_array_type(value_type) != + canonical_array_type(*element_type) || native_handle_kind_for_nil_type(fn.return_type) != native_handle_kind::scalar_array || !size_arg->getType()->isIntegerTy() || - (native_handle_kind_for_nil_type(value_type) == native_handle_kind::text + ((native_handle_kind_for_nil_type(value_type) == native_handle_kind::text || + is_array_tuple_type(value_type)) ? !val_arg->getType()->isPointerTy() : !val_arg->getType()->isIntegerTy()) || !impl_->current_function->getReturnType()->isPointerTy()) { @@ -3326,13 +3385,14 @@ bool NativeCodegen::generateModule(const nil_module &mod) { native_generic_argument(array_type, "array"); if (!element_type || !native_array_kind_for_element(*element_type) || normalize_nil_type(index_type) != "i32" || - normalize_nil_type(fn.return_type) != - normalize_nil_type(*element_type) || + canonical_array_type(fn.return_type) != + canonical_array_type(*element_type) || native_handle_kind_for_nil_type(array_type) != native_handle_kind::scalar_array || !arr_arg->getType()->isPointerTy() || !idx_arg->getType()->isIntegerTy() || - (native_handle_kind_for_nil_type(fn.return_type) == native_handle_kind::text + ((native_handle_kind_for_nil_type(fn.return_type) == native_handle_kind::text || + is_array_tuple_type(fn.return_type)) ? !impl_->current_function->getReturnType()->isPointerTy() : !impl_->current_function->getReturnType()->isIntegerTy())) { std::cerr << "[NativeCodegen] array.get intrinsic '" << fn.name @@ -3353,7 +3413,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { {arr_arg, llvm::ConstantInt::get(ctx, llvm::APInt(32, *kind, false)), impl_->coerceToI64(idx_arg)}); - if (*kind == NYRT_ARRAY_TEXT) + if (*kind == NYRT_ARRAY_TEXT || *kind == NYRT_ARRAY_TUPLE) value = native_array_loaded_value(value, *element_type); else value = impl_->castInteger(value, @@ -3382,13 +3442,14 @@ bool NativeCodegen::generateModule(const nil_module &mod) { const std::string value_type = nil_parameter_type(fn.params[2]); if (!element_type || !native_array_kind_for_element(*element_type) || normalize_nil_type(index_type) != "i32" || - normalize_nil_type(value_type) != - normalize_nil_type(*element_type) || + canonical_array_type(value_type) != + canonical_array_type(*element_type) || native_handle_kind_for_nil_type(array_type) != native_handle_kind::scalar_array || !arr_arg->getType()->isPointerTy() || !idx_arg->getType()->isIntegerTy() || - (native_handle_kind_for_nil_type(value_type) == native_handle_kind::text + ((native_handle_kind_for_nil_type(value_type) == native_handle_kind::text || + is_array_tuple_type(value_type)) ? !val_arg->getType()->isPointerTy() : !val_arg->getType()->isIntegerTy()) || !impl_->current_function->getReturnType()->isVoidTy()) { @@ -4677,6 +4738,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << array_type << "' in function '" << fn.name << "'\n"; return false; } + require_initialized_struct(value, "array__push"); auto *stored_value = native_storage_word(value, *element, "array__push"); if (!stored_value) return false; @@ -5473,7 +5535,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { // Pointer If target is "i32", "i64", "any", we want Int const auto target_handle_kind = - native_handle_kind_for_nil_type(normalized_target); + native_handle_kind_for_nil_type(target_type); const bool target_is_aggregate = is_native_aggregate_nil_type(mod, target_type); const bool target_is_ptr = @@ -5509,7 +5571,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { impl_->pushValue(val, target_type); } else if (target_is_ptr) { if (!src_ty->isPointerTy() || source_type.empty() || - !native_handle_types_compatible(source_type, normalized_target)) { + !native_handle_types_compatible(source_type, target_type)) { std::cerr << "[NativeCodegen] ordinary CAST cannot convert '" << (source_type.empty() ? std::string("untyped scalar") : source_type) @@ -5518,7 +5580,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << "'; only exact compatible handle casts are allowed\n"; return false; } - impl_->pushValue(val, normalized_target); + impl_->pushValue(val, canonical_array_type(target_type)); } else if (target_enum != nullptr) { if (!src_ty->isIntegerTy() || source_enum != target_enum) { std::cerr << "[NativeCodegen] ordinary CAST cannot convert '" @@ -6439,6 +6501,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { for (std::size_t index = contract.argument_count; index > 0; --index) arguments[index - 1] = impl_->popValue(); const auto kind = native_array_kind_for_element(contract.element); + if (!kind) return false; const auto integer_argument = [&](std::size_t index) -> llvm::Value * { auto *value = arguments[index]; const auto nil_type = normalize_nil_type(impl_->nilType(value)); @@ -6475,6 +6538,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto *kind_type = llvm::Type::getInt32Ty(ctx); if (contract.operation == array_intrinsic_operation::create) { auto *size = integer_argument(0); + require_initialized_struct(arguments[1], func_name); auto *initial = native_storage_word(arguments[1], contract.element, func_name); if (!size || !initial) return false; @@ -6514,6 +6578,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { {array, kind_value, index}); impl_->pushValue(native_array_loaded_value(word, contract.element), contract.element); } else { + require_initialized_struct(arguments[2], func_name); auto *value = native_storage_word(arguments[2], contract.element, func_name); if (!value) return false; @@ -7317,13 +7382,13 @@ bool NativeCodegen::generateModule(const nil_module &mod) { std::cerr << "[NativeCodegen] NEW_ARRAY_LITERAL in function '" << fn.name << "' requires exact contextual element metadata " - "(i32, i64, bool, u8, f64, or text); got '" + "(i32, i64, bool, u8, f64, text, or tuple); got '" << (minstr.args.size() < 2 ? std::string("") : minstr.args[1]) << "'\n"; return false; } - const std::string element_type = normalize_nil_type(minstr.args[1]); + const std::string element_type = canonical_array_type(minstr.args[1]); if (!native_array_kind_for_element(element_type)) { if (element_type == "f32" || element_type == "f64") { std::cerr << "[NativeCodegen] floating-point array elements are " @@ -7391,6 +7456,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return false; } + require_initialized_struct(val, "NEW_ARRAY_LITERAL"); llvm::Value *val_to_store = native_storage_word(val, element_type, "NEW_ARRAY_LITERAL"); if (!val_to_store) @@ -7533,6 +7599,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << fn.name << "'\n"; return false; } + require_initialized_struct(val, "SET_INDEX"); llvm::Value *val_to_store = native_storage_word(val, *element_type, "SET_INDEX"); if (!val_to_store) { diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 7909c5f4..c1fc3171 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -135,6 +135,7 @@ std::uint64_t stride_for_kind(std::uint32_t kind) noexcept { case NYRT_ARRAY_I64: case NYRT_ARRAY_F64: case NYRT_ARRAY_TEXT: + case NYRT_ARRAY_TUPLE: return sizeof(std::int64_t); case NYRT_ARRAY_BOOL: case NYRT_ARRAY_U8: @@ -349,7 +350,8 @@ nyrt_array *make_array(std::uint32_t kind, std::uint64_t length) noexcept { void *make_buffer(std::uint32_t kind, std::uint64_t length) noexcept { // New array element kinds do not implicitly expand the raw-pointer ABI. - if (kind == NYRT_ARRAY_F64 || kind == NYRT_ARRAY_TEXT) + if (kind != NYRT_ARRAY_I32 && kind != NYRT_ARRAY_I64 && + kind != NYRT_ARRAY_BOOL && kind != NYRT_ARRAY_U8) return nullptr; const std::uint64_t stride = stride_for_kind(kind); std::size_t byte_count = 0; @@ -458,6 +460,7 @@ std::uint64_t load_value(const nyrt_array &array, static_cast(array.data)[index]); case NYRT_ARRAY_F64: case NYRT_ARRAY_TEXT: + case NYRT_ARRAY_TUPLE: return static_cast(array.data)[index]; case NYRT_ARRAY_BOOL: case NYRT_ARRAY_U8: @@ -490,6 +493,7 @@ void store_value(nyrt_array &array, std::uint64_t index, break; case NYRT_ARRAY_F64: case NYRT_ARRAY_TEXT: + case NYRT_ARRAY_TUPLE: // f64 is an IEEE bit pattern; text is a context/static-lifetime address. // Neither is an integer conversion, nor does array growth own/free text. static_cast(array.data)[index] = value; @@ -970,7 +974,8 @@ void nyrt_collect() noexcept { pending.pop_back(); const auto &item = objects[index]; if (item.array) { - if (item.array->kind == NYRT_ARRAY_TEXT) + if (item.array->kind == NYRT_ARRAY_TEXT || + item.array->kind == NYRT_ARRAY_TUPLE) scan(item.array->data, item.array->length * item.array->stride); } else { // Object/enum layouts use aligned word slots. Conservatively retaining @@ -1069,9 +1074,15 @@ std::uint64_t nyrt_array_get(const void *value, std::uint32_t expected_kind, std::int64_t index) noexcept { const auto *array = checked_array(value, expected_kind); if (array == nullptr || index < 0 || - static_cast(index) >= array->length) + static_cast(index) >= array->length) { + if (expected_kind == NYRT_ARRAY_TUPLE) + nyrt_fail("NIL native runtime error: tuple array read is out of bounds or has an invalid handle\n"); return 0; - return load_value(*array, static_cast(index)); + } + const auto result = load_value(*array, static_cast(index)); + if (expected_kind == NYRT_ARRAY_TUPLE && result == 0) + nyrt_fail("NIL native runtime error: tuple array read encountered an uninitialized element\n"); + return result; } std::int32_t nyrt_array_set(void *value, std::uint32_t expected_kind, diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index f4f83c16..6bd3d0ca 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -15,6 +15,9 @@ enum nyrt_array_kind : std::uint32_t { NYRT_ARRAY_U8 = 4, NYRT_ARRAY_F64 = 5, NYRT_ARRAY_TEXT = 6, + // Compiler-proven, fully initialized tuple object handles. The runtime + // traces the handles; exact tuple schema identity remains in typed NIL. + NYRT_ARRAY_TUPLE = 7, }; // Additive database ABI. Success is 1, failure 0; outputs are context-owned. diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index 069fff3a..b11d93e1 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -1153,7 +1153,10 @@ static void attach_class_metadata(std::vector &program, nil_module throw std::runtime_error("Class instruction outside a declared function"); } validate_nil_class_contract(metadata); - if (!program.empty() && !metadata.classes.empty()) + // Tuple arrays also use exact record schemas at execution time, including + // modules that declare no classes at all. + if (!program.empty() && (!metadata.classes.empty() || !metadata.structs.empty() || + !metadata.enums.empty())) program.front().module_metadata = std::make_shared(std::move(metadata)); } @@ -2041,7 +2044,7 @@ parseProgram(std::istream &is, declaration_line.record(line, input_line); source_debug.record(line, input_line); if (!in_function && !in_struct_definition && !in_enum_definition && - parse_class_record(line, input_line, fault_metadata, klass, nullptr)) continue; + parse_class_record(line, input_line, fault_metadata, klass, &pending_annotations)) continue; if (line.find("const ") == 0) { if (++parsed_constants > max_constant_count) { throw std::runtime_error( @@ -2088,7 +2091,9 @@ parseProgram(std::istream &is, std::to_string(input_line)); } in_struct_definition = true; - fault_metadata.structs.push_back({trim_textual_field(line.substr(7)), {}}); + fault_metadata.structs.push_back({trim_textual_field(line.substr(7)), {}, + std::move(pending_annotations)}); + pending_annotations.clear(); continue; } if (line == "end struct") { @@ -2106,7 +2111,9 @@ parseProgram(std::istream &is, std::to_string(input_line)); } in_enum_definition = true; - fault_metadata.enums.push_back({trim_textual_field(line.substr(5)), {}}); + fault_metadata.enums.push_back({trim_textual_field(line.substr(5)), {}, + std::move(pending_annotations)}); + pending_annotations.clear(); continue; } if (line == "end enum") { @@ -2124,8 +2131,21 @@ parseProgram(std::istream &is, trim_textual_field(line.substr(0, colon)), trim_textual_field(line.substr(colon + 1))); continue; } - if (in_enum_definition) + if (in_enum_definition) { + const auto colon = line.find(':'); + nil_enum_def::variant variant; + variant.name = trim_textual_field(line.substr(0, colon)); + if (colon != std::string::npos) + variant.associated_type = trim_textual_field(line.substr(colon + 1)); + if (variant.name.empty()) + throw std::runtime_error("Malformed enum variant at textual NIL line " + + std::to_string(input_line)); + auto &variants = fault_metadata.enums.back().variants; + variants.push_back(std::move(variant)); + if (variants.size() > max_parameter_count) + throw std::runtime_error("Textual NIL enum variant count exceeds safety limit"); continue; + } if (line[0] == '@') { if (!in_function && line.rfind("@test ", 0) != 0) { declaration_line.annotation(line, input_line); diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 0d56aac6..4a7a849d 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -1347,6 +1347,14 @@ bool type_checker::type_contains_class(const std::string &type) { return false; } +bool type_checker::type_contains_tuple(const std::string &type) { + const auto parts = parse_generic_type_string(resolve_type(type).name); + if (parts.base_name == "tuple") return true; + for (const auto &argument : parts.type_args) + if (type_contains_tuple(argument)) return true; + return false; +} + bool type_checker::check_assignment_type(const type_info &expected, const type_info &actual, ast_expr *value) { @@ -1358,6 +1366,28 @@ bool type_checker::check_assignment_type(const type_info &expected, if (value) value->rejected_tuple_operation = "Tuple storage type mismatch: expected '" + target + "', got '" + source + "'"; return false; }; + // A newly constructed array can contextualize each fresh tuple. Existing + // arrays retain invariant element layouts; no array handle is reinterpreted. + if (target_tuple.base_name == "array" && target_tuple.type_args.size() == 1 && + type_contains_tuple(target_tuple.type_args.front()) && value && + value->kind == ast_node_kind::array_literal_expr_node) { + auto &array = static_cast(*value); + for (auto &element : array.elements) { + if (!element || !check_assignment_type(resolve_type(target_tuple.type_args.front()), + resolve_type(element->inferred_type.value_or("")), element.get())) + return reject_tuple(); + } + value->inferred_type = target; + return true; + } + const auto source_shape = parse_generic_type_string(source); + if ((target_tuple.base_name == "array" || source_shape.base_name == "array") && + (type_contains_tuple(target) || type_contains_tuple(source))) { + // The historical array compatibility rule applies to freshly + // constructed empty literals, not aliases of an existing storage handle. + if (target != source) return reject_tuple(); + return true; + } if (target_tuple.base_name == "tuple" && value && value->kind == ast_node_kind::struct_literal_expr_node) { auto &tuple = static_cast(*value); @@ -1383,8 +1413,8 @@ bool type_checker::check_assignment_type(const type_info &expected, return true; } const bool compatible = are_types_compatible(expected, actual); - if (!compatible && (target_tuple.base_name == "tuple" || - parse_generic_type_string(source).base_name == "tuple")) return reject_tuple(); + if (!compatible && (type_contains_tuple(target) || type_contains_tuple(source))) + return reject_tuple(); return compatible; } @@ -2893,6 +2923,13 @@ void type_checker::visit(ast_variable_decl &p) { // Check initializer if present type_info init_type = type_unknown; if (p.initializer) { + if (p.type_name && p.initializer->kind == ast_node_kind::array_literal_expr_node) { + const auto declared = resolve_type(*p.type_name); + const auto context = parse_generic_type_string(declared.name); + if (context.base_name == "array" && context.type_args.size() == 1 && + type_contains_tuple(context.type_args.front())) + p.initializer->inferred_type = declared.name; + } p.initializer->accept(*this); if (last_expr_type_) { init_type = *last_expr_type_; @@ -3556,7 +3593,8 @@ void type_checker::visit(ast_return_stmt &s) { auto &array = static_cast(*s.value); const auto context = parse_generic_type_string(current_function_return_type_->name); - if (array.elements.empty() && context.base_name == "array" && + if ((array.elements.empty() || type_contains_tuple(current_function_return_type_->name)) && + context.base_name == "array" && context.type_args.size() == 1 && context.type_args[0] != "any" && context.type_args[0] != "") { s.value->inferred_type = current_function_return_type_->name; @@ -4230,6 +4268,14 @@ void type_checker::visit(ast_for_in_stmt &s) { std::string type_to_register = var_type.has_value() ? *var_type : std::string("any"); + // A tuple-loop wildcard consumes its position without introducing a + // binding, matching tuple declaration and match-pattern destructuring. + if (var.name == "_" && (s.tuple_pattern || vars.size() > 1)) { + if (s.variables.size() > i) + s.variables[i].type_name = type_to_register; + continue; + } + // Insert variable symbol with inferred type and preserve mutability symbol sym(var.name, symbol_kind::variable_symbol, nullptr, std::optional(type_to_register), var.is_mut, false, @@ -4238,9 +4284,13 @@ void type_checker::visit(ast_for_in_stmt &s) { diagnostic_source_file_, var.name_span); if (sym.semantic_id) semantics_.symbols[*sym.semantic_id].lexical_local = true; - if (!symbols_.insert_symbol(sym)) - add_error(var.line, "Loop variable '" + var.name + - "' already declared in this scope"); + if (!symbols_.insert_symbol(sym)) { + const std::string message = "Loop variable '" + var.name + + "' already declared in this scope"; + add_error(var.line, message); + if (s.iterable && (s.tuple_pattern || vars.size() > 1)) + s.iterable->rejected_tuple_operation = "Invalid tuple loop binding: " + message; + } // Mutate AST so future type-checking sees the variable type when it checks // a reference to the same name inside the loop. Assign into actual AST @@ -4622,6 +4672,11 @@ void type_checker::visit(ast_call_expr &e) { "use positional arguments for this callable"); }}; if (check_runtime_primitive(e)) return; + // Explicit generic arguments belong to the caller's lexical/module + // context. Preserve their canonical nominal identities on the AST before + // lowering or specializing a callee declared in a different module. + for (auto &argument : e.type_args) + argument = resolve_type(argument).name; /* std::cerr << "[type_checker] visit(call_expr) line " << e.line << " * callee_kind=" << (int)e.callee->kind << " expected=" << * (int)ast_node_kind::member_access_expr_node << std::endl; */ @@ -4804,12 +4859,21 @@ void type_checker::visit(ast_call_expr &e) { const auto ¶meter = callee.params[i + parameter_offset]; if (!parameter.type_name) continue; const auto expected = resolve_type(instantiate_generic_type(*parameter.type_name, substitutions)); - // Legacy general argument inference is intentionally unchanged. - // Class boundaries, however, require an explicit checked proof. - if ((type_contains_class(expected.name) || type_contains_class(arg_types[i].name)) && - !check_assignment_type(expected, arg_types[i], e.args[i].get())) + // Aggregate boundaries require an explicit checked storage proof. + // A fresh tuple/array literal may receive element context; an + // existing tuple or array handle must retain its exact shape. + const bool tuple_boundary = type_contains_tuple(expected.name) || + type_contains_tuple(arg_types[i].name); + const bool class_boundary = type_contains_class(expected.name) || + type_contains_class(arg_types[i].name); + if ((tuple_boundary || class_boundary) && + !check_assignment_type(expected, arg_types[i], e.args[i].get())) { add_error(e.line, "Function '" + callee.name + "' argument " + - std::to_string(i + 1) + " has incompatible class type"); + std::to_string(i + 1) + " has incompatible " + + (tuple_boundary ? "tuple storage type" : "class type")); + if (tuple_boundary) + e.rejected_tuple_operation = "Function argument has incompatible tuple storage type"; + } } for (std::size_t argument_index = 0; argument_index < e.args.size() && @@ -5545,6 +5609,9 @@ void type_checker::visit(ast_call_expr &e) { if (!order_named_arguments({{"start", "length"}, false})) return; } if (builtin_receiver.base_name == "array" && method_name == "push") { + const bool tuple_storage = builtin_receiver.type_args.size() == 1 && + type_contains_tuple(builtin_receiver.type_args.front()); + const auto before = diagnostics_.size(); if (e.args.size() != 1) { add_error(e.line, "Array.push expects 1 argument, got " + std::to_string(e.args.size())); @@ -5562,13 +5629,18 @@ void type_checker::visit(ast_call_expr &e) { const bool storage_conversion = (expected.name == "u8" || expected.name == "bool") && integer_storage_value(actual.name); - if (!storage_conversion && !are_types_compatible(expected, actual)) { + const bool compatible = tuple_storage + ? check_assignment_type(expected, actual, e.args.front().get()) + : are_types_compatible(expected, actual); + if (!storage_conversion && !compatible) { add_error(e.line, "Array.push element type mismatch. Expected '" + expected.name + "', got '" + actual.name + "'"); } } if (!e.type_args.empty()) add_error(e.line, "Array.push does not accept method type arguments"); + if (tuple_storage && diagnostics_.size() != before) + e.rejected_tuple_operation = "Invalid tuple array push: element schema and argument contract must match"; last_expr_type_ = type_void; ma->inferred_type = type_void.name; e.inferred_type = type_void.name; @@ -6245,7 +6317,9 @@ void type_checker::visit(ast_assignment_expr &e) { e.value->accept(*this); const type_info val_type = last_expr_type_.value_or(type_unknown); if (target_type && - !(storage_conversion ? storage_types_compatible(*target_type, val_type) + !(storage_conversion && !type_contains_tuple(target_type->name) && + !type_contains_tuple(val_type.name) + ? storage_types_compatible(*target_type, val_type) : check_assignment_type(*target_type, val_type, e.value.get()))) { add_error(e.line, "Type mismatch in " + assignment_kind + "assignment. Expected '" + target_type->name + @@ -6813,6 +6887,27 @@ void type_checker::visit(ast_match_expr &e) { } void type_checker::visit(ast_array_literal_expr &e) { + if (e.inferred_type) { + const auto context_type = resolve_type(*e.inferred_type); + const auto context = parse_generic_type_string(context_type.name); + if (context.base_name == "array" && context.type_args.size() == 1 && + type_contains_tuple(context.type_args.front())) { + const auto expected = resolve_type(context.type_args.front()); + for (auto &element : e.elements) { + element->accept(*this); + const auto actual = last_expr_type_.value_or(type_unknown); + if (!check_assignment_type(expected, actual, element.get())) { + const std::string message = "Array element type mismatch. Expected '" + + expected.name + "', got '" + actual.name + "'"; + add_error(e.line, message); + e.rejected_tuple_operation = message; + } + } + last_expr_type_ = context_type; + e.inferred_type = context_type.name; + return; + } + } if (e.elements.empty()) { if (e.inferred_type) { const auto context = parse_generic_type_string(*e.inferred_type); @@ -6848,9 +6943,13 @@ void type_checker::visit(ast_array_literal_expr &e) { // Recheck every element against the final width: a previously compatible // bool/i32 pair does not make bool compatible with a later i64 element. for (const auto &type : element_types) { - if (!are_types_compatible(*elem_type, type)) - add_error(e.line, "Array element type mismatch. Expected '" + - elem_type->name + "', got '" + type.name + "'"); + if (!are_types_compatible(*elem_type, type)) { + const std::string message = "Array element type mismatch. Expected '" + + elem_type->name + "', got '" + type.name + "'"; + add_error(e.line, message); + if (type_contains_tuple(elem_type->name) || type_contains_tuple(type.name)) + e.rejected_tuple_operation = message; + } } // Construct array type string: array diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index b65ea9a7..213d41eb 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -221,6 +221,7 @@ class type_checker : public ast_node::ast_visitor { std::vector class_fields(const symbol &receiver, int line); bool class_assignable(const std::string &expected, const std::string &actual); bool type_contains_class(const std::string &type); + bool type_contains_tuple(const std::string &type); bool check_assignment_type(const type_info &expected, const type_info &actual, ast_expr *value); bool class_method_is_virtual(const symbol &receiver, const std::string &name); diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 5d669f93..feaa9b86 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -890,6 +890,8 @@ void VM::executeInstruction(const Instruction &instr) { std::holds_alternative(value); }; const auto array_default_value = [](const HeapBlock &block) -> Value { + if (is_array_tuple_type(block.element_type)) + throw std::runtime_error("tuple array read is out of bounds or has an invalid handle"); // Match intrinsic metadata normalization for supported scalar types. // Keep the original block metadata intact: nominal aggregate names are // case-sensitive even though built-in scalar aliases are normalized here. @@ -902,9 +904,181 @@ void VM::executeInstruction(const Instruction &instr) { return ArrayHandle{}; return int64_t(0); }; + const auto validate_tuple_schema = [&](const auto &self, const std::string &type, + const std::string &operation, + unsigned depth) -> const nil_struct_def * { + const auto shape = array_tuple_elements(type); + const auto reject = [&]() { + throw std::runtime_error(operation + ": requires an exact declared tuple schema for '" + type + "'"); + }; + if (!shape || depth >= 64 || !class_metadata_) + reject(); + const nil_struct_def *schema = nullptr; + for (const auto &candidate : class_metadata_->structs) { + if (canonical_array_type(candidate.name) != canonical_array_type(type)) continue; + if (schema) reject(); + schema = &candidate; + } + if (!schema || schema->fields.size() != shape->size() || + std::find(schema->annotations.begin(), schema->annotations.end(), "@nil_tuple") == schema->annotations.end()) + reject(); + for (std::size_t index = 0; index < shape->size(); ++index) { + if (schema->fields[index].first != std::to_string(index) || + canonical_array_type(schema->fields[index].second) != (*shape)[index]) + reject(); + if (is_array_tuple_type((*shape)[index])) + (void)self(self, (*shape)[index], operation, depth + 1); + } + return schema; + }; + const auto resolve_storage_schema = [&](const auto &definitions, const std::string &type) { + using Definition = typename std::decay_t::value_type; + const Definition *match = nullptr; + const auto expected = canonical_array_type(type); + for (const auto &candidate : definitions) { + if (canonical_array_type(candidate.name) != expected) continue; + if (match) return static_cast(nullptr); + match = &candidate; + } + if (match) return match; + const auto suffix = "::" + expected; + for (const auto &candidate : definitions) { + const auto actual = canonical_array_type(candidate.name); + if (actual.size() <= suffix.size() || + actual.compare(actual.size() - suffix.size(), suffix.size(), suffix) != 0) continue; + if (match) return static_cast(nullptr); + match = &candidate; + } + return match; + }; + std::unordered_set validated_storage_objects; + const auto validate_tuple_value = [&](const auto &self, const Value &value, + const std::string &type, + const std::string &operation, + unsigned depth) -> void { + const auto expected = canonical_array_type(type); + const auto reject = [&]() { + throw std::runtime_error(operation + ": expected a fully initialized tuple element of exact type '" + type + "'"); + }; + if (depth >= 64 || !class_metadata_) reject(); + if (expected == "text") { + if (!std::holds_alternative(value)) reject(); + return; + } + if (expected == "f64") { + if (!std::holds_alternative(value)) reject(); + return; + } + if (expected == "i32" || expected == "i64" || expected == "u8" || expected == "bool") { + const auto *integer = std::get_if(&value); + if (!integer || (expected == "i32" && (*integer < INT32_MIN || *integer > INT32_MAX)) || + (expected == "u8" && (*integer < 0 || *integer > 255)) || + (expected == "bool" && *integer != 0 && *integer != 1)) reject(); + return; + } + if (expected.rfind("ptr<", 0) == 0) { + const auto *pointer = std::get_if(&value); + if (!pointer) reject(); + if (*pointer == 0) return; // A null raw pointer remains a valid stored value. + const auto location = findHeapPointer(*pointer, true); + const auto element = expected.substr(4, expected.size() - 5); + if (!location || canonical_array_type(location->block->type_name) != element) reject(); + return; + } + if (expected.rfind("array<", 0) == 0) { + const auto *handle = std::get_if(&value); + if (!handle) reject(); + const auto found = heap_.find(handle->address); + if (found == heap_.end() || found->second.type_name != "array" || + "array<" + canonical_array_type(found->second.element_type) + ">" != expected) reject(); + return; + } + if (const auto *enumeration = resolve_storage_schema(class_metadata_->enums, expected)) { + const auto *item = std::get_if(&value); + if (!item) reject(); + const auto tag = canonical_variant_name(item->variant_name); + const auto separator = tag.rfind("::"); + const auto owner = separator == std::string::npos ? std::string{} : tag.substr(0, separator); + const auto concrete = item->type_name.empty() ? owner : item->type_name; + if (concrete.empty() || resolve_storage_schema(class_metadata_->enums, concrete) != enumeration) reject(); + auto schema_owner = canonical_array_type(enumeration->name); + if (owner.find('<') == std::string::npos) { + const auto generic = schema_owner.find('<'); + if (generic != std::string::npos) schema_owner.resize(generic); + } + const auto suffix = "::" + owner; + if (!owner.empty() && owner != schema_owner && + (schema_owner.size() <= suffix.size() || + schema_owner.compare(schema_owner.size() - suffix.size(), suffix.size(), suffix) != 0)) reject(); + const auto variant_name = separator == std::string::npos ? tag : tag.substr(separator + 2); + const auto variant = std::find_if(enumeration->variants.begin(), enumeration->variants.end(), + [&](const auto &candidate) { return candidate.name == variant_name; }); + if (variant == enumeration->variants.end()) reject(); + std::vector payload_types; + const auto &payload = variant->associated_type; + if (!payload.empty()) { + if (payload.front() == '(' && payload.back() == ')') { + const auto parts = array_tuple_elements("tuple<" + payload.substr(1, payload.size() - 2) + ">"); + if (!parts) reject(); + payload_types = *parts; + } else payload_types.push_back(payload); + } + if (payload_types.size() != item->payloads.size()) reject(); + for (std::size_t index = 0; index < payload_types.size(); ++index) + std::visit([&](const auto &stored) { + using Payload = std::decay_t; + if constexpr (std::is_same_v>) { + if (!stored) reject(); + self(self, Value(*stored), payload_types[index], operation, depth + 1); + } else self(self, Value(stored), payload_types[index], operation, depth + 1); + }, item->payloads[index]); + return; + } + auto nominal = expected; + if (nominal.rfind("ref<", 0) == 0 && nominal.back() == '>') + nominal = nominal.substr(4, nominal.size() - 5); + const auto *schema = is_array_tuple_type(nominal) + ? validate_tuple_schema(validate_tuple_schema, nominal, operation, depth) + : resolve_storage_schema(class_metadata_->structs, nominal); + const auto *object = std::get_if(&value); + if (!schema || !object || !object->data) reject(); + const auto *actual_schema = resolve_storage_schema(class_metadata_->structs, object->type_name); + if (find_nil_class(*class_metadata_, nominal)) { + validateClassValue(value, nominal); + if (!actual_schema) reject(); + schema = actual_schema; + } else if (actual_schema != schema) reject(); + // Repeated record references preserve aliasing, and recursive interpreter + // records must not recurse forever during this storage-boundary check. + if (!validated_storage_objects.insert(object->data.get()).second) return; + const auto &data = *object->data; + if (data.fields.size() + data.array_fields.size() + data.string_fields.size() + + data.double_fields.size() + data.struct_fields.size() + data.enum_fields.size() != schema->fields.size()) reject(); + for (const auto &[field, field_type] : schema->fields) { + std::optional stored; + const auto take = [&](const auto &fields) { + if (const auto found = fields.find(field); found != fields.end()) { + if (stored) reject(); + using Stored = std::decay_tsecond)>; + if constexpr (std::is_same_v>) { + if (!found->second) reject(); + stored = Value(*found->second); + } else stored = Value(found->second); + } + }; + take(data.fields); take(data.array_fields); take(data.string_fields); + take(data.double_fields); take(data.struct_fields); take(data.enum_fields); + if (!stored) reject(); + self(self, *stored, field_type, operation, depth + 1); + } + }; const auto canonical_pointer_value = - [](const HeapBlock &block, const Value &value, + [&](const HeapBlock &block, const Value &value, const std::string &operation) -> Value { + if (block.type_name == "array" && is_array_tuple_type(block.element_type)) { + validate_tuple_value(validate_tuple_value, value, block.element_type, operation, 0); + return value; + } const std::string storage_type = canonical_array_scalar( block.type_name == "array" ? block.element_type : block.type_name); if (storage_type == "f64") { @@ -2033,6 +2207,8 @@ void VM::executeInstruction(const Instruction &instr) { } } const auto contract = parse_array_intrinsic(metadata); + if (is_array_tuple_type(contract.element)) + (void)validate_tuple_schema(validate_tuple_schema, contract.element, fn_name, 0); if (args.size() != contract.argument_count) throw std::runtime_error("array intrinsic argument count mismatch"); const auto integer = [&](std::size_t index) { @@ -2056,20 +2232,22 @@ void VM::executeInstruction(const Instruction &instr) { block.element_type = contract.element; block.element_count = static_cast(count); const Value initial = canonical_pointer_value(block, args[1], fn_name); - if (memory_mode_ == MemoryMode::SAFE_GC && gc_critical_depth_ == 0 && - ++alloc_count_ >= gc_threshold_) - gcCollect(); block.data.assign(static_cast(count), initial); const auto handle = next_ptr_; next_ptr_ += static_cast(extent); storeHeapBlock(handle, std::move(block)); pushStack(ArrayHandle{handle}); + // The result now roots the initializer's nested array handles. The + // popped intrinsic arguments alone are not roots during collection. + if (memory_mode_ == MemoryMode::SAFE_GC && gc_critical_depth_ == 0 && + ++alloc_count_ >= gc_threshold_) + gcCollect(); return; } const auto *handle = std::get_if(&args[0]); const auto found = handle ? heap_.find(handle->address) : heap_.end(); if (found == heap_.end() || found->second.type_name != "array" || - canonical_array_scalar(found->second.element_type) != contract.element) + canonical_array_type(found->second.element_type) != contract.element) throw std::runtime_error("array intrinsic requires a matching typed array handle"); auto &block = found->second; if (contract.operation == array_intrinsic_operation::length) { @@ -4593,6 +4771,24 @@ void VM::executeInstruction(const Instruction &instr) { lib_name + "::" + fn_name); if (returns_void) stack_.resize(result_base); + else if (auto *result = std::get_if(&stack_.back()); + result && result->type_name.empty()) { + result->type_name = canonical_array_type(instr.args[3]); + // Older intrinsic wrappers encoded all enum results using their i64 + // storage representation. Only the matching annotated wrapper may + // supply its declared concrete enum identity for that legacy encoding. + if (lib_name == "intrinsic" && result->type_name == "i64" && + class_metadata_ && !call_stack_.empty()) { + const auto &frame = call_stack_.back(); + if (frame.entry_pc < program_.size()) { + const auto &annotations = program_[frame.entry_pc].function_annotations; + const auto annotation = "@intrinsic(\"" + fn_name + "\")"; + if (std::find(annotations.begin(), annotations.end(), annotation) != annotations.end() && + resolve_storage_schema(class_metadata_->enums, frame.return_type)) + result->type_name = canonical_array_type(frame.return_type); + } + } + } } break; // Math Opcodes @@ -5357,6 +5553,8 @@ void VM::executeInstruction(const Instruction &instr) { HeapBlock block; block.type_name = "array"; block.element_type = instr.args.size() >= 2 ? instr.args[1] : "any"; + if (is_array_tuple_type(block.element_type)) + (void)validate_tuple_schema(validate_tuple_schema, block.element_type, "NEW_ARRAY_LITERAL", 0); block.element_count = count; block.data.resize(count); @@ -5397,10 +5595,11 @@ void VM::executeInstruction(const Instruction &instr) { const auto exact = heap_.find(ptr); if (array && exact != heap_.end() && exact->second.type_name == "array") { - value = array_default_value(exact->second); if (idx >= 0 && static_cast(idx) < exact->second.data.size()) value = exact->second.data[static_cast(idx)]; + else + value = array_default_value(exact->second); } else if (const auto current = findHeapPointer(ptr, true)) { const auto moved = moveHeapPointer(*current, idx, false); if (moved) { @@ -5493,6 +5692,8 @@ void VM::executeInstruction(const Instruction &instr) { int arg_count = std::stoi(instr.args[1]); EnumValue ev; ev.variant_name = canonical_variant_name(instr.args[0]); + if (instr.args.size() >= 3) + ev.type_name = canonical_array_type(instr.args[2]); // Pop payload arguments in reverse order and store them std::vector payloads; diff --git a/nilcompiler/src/vm.hpp b/nilcompiler/src/vm.hpp index c5135018..04a4cd1f 100644 --- a/nilcompiler/src/vm.hpp +++ b/nilcompiler/src/vm.hpp @@ -242,6 +242,8 @@ using EnumPayload = struct EnumValue { std::string variant_name; // e.g., "Option::Some" or "Result::Ok" std::vector payloads; + // Concrete NEW_VARIANT/intrinsic result identity survives generic unit tags. + std::string type_name; }; // Array instance diff --git a/nilstd/README.md b/nilstd/README.md index 7c30110b..987219d3 100644 --- a/nilstd/README.md +++ b/nilstd/README.md @@ -114,7 +114,11 @@ correctly through shared aliases. Gather validates every requested index before constructing its separate result array. Indices and counts are `i32` (`override integer` in Matrix). The exercised element types are `i32`, `i64`, `u8`, `bool`, `f64`, and NUL-free `text`. -Ny and Matrix consumer fixtures cover the same API. See the +Paired tuple-array fixtures also cover generic construction, access and checked +overlapping copies, preserving tuple schemas and contained reference identities. +Raw tuple-array reads outside the array fail instead of returning a default +tuple; scalar defaults remain unchanged. Ny and Matrix consumer fixtures cover +the shared APIs. See the [checked-array contract](../docs/standard-library/index.md#checked-arrays) for signatures, naming, zero-length rules, and remaining work. diff --git a/nilstd/src/collections/array.ny b/nilstd/src/collections/array.ny index f75119fe..fa5b63d5 100644 --- a/nilstd/src/collections/array.ny +++ b/nilstd/src/collections/array.ny @@ -2,10 +2,11 @@ module nil.std.collections # Runtime-backed array primitives. Intrinsic declarations intentionally have # no fallback body; their annotations provide the implementation. -# The verified element kinds are i32, i64, u8, bool, f64, and text. The f32 -# declarations below are reserved and reject on use until their ABI is defined. -# Sizes are nonnegative i32 values. Out-of-bounds reads yield the element's -# zero value and writes are no-ops, matching built-in array indexing. +# Element kinds include i32, i64, u8, bool, f64, text, and supported structural +# tuples. The f32 declarations are reserved until their ABI is defined. +# Sizes are nonnegative i32 values. Out-of-bounds scalar reads yield zero; +# tuple reads fail because there is no default tuple. Writes outside the array +# are no-ops, matching built-in array indexing. @intrinsic("array.new_with_value") pub fn new_with_value(size: i32, value: T) -> array diff --git a/scripts/assemble-release.py b/scripts/assemble-release.py index 642e60d0..4a605ce3 100644 --- a/scripts/assemble-release.py +++ b/scripts/assemble-release.py @@ -175,7 +175,8 @@ def numeric_version(value: str) -> tuple[int, ...]: def elf_inventory(sdk: Path, readelf: str) -> dict[str, Any]: records = [] - for name in (*TOOLS, "nillib/native/libnil.so"): + for name in (*sdk_validator.inventory_tools(path.name for path in sdk.iterdir()), + "nillib/native/libnil.so"): tool = sdk / name with tool.open("rb") as stream: if stream.read(4) != b"\x7fELF": @@ -248,6 +249,20 @@ def validate_dependency_policy(policy: dict[str, Any], notices: bytes, raise ReleaseError("reviewed LLVM/GCC versions differ from qualified build evidence") +def validate_tool_versions(sdk: Path, version: str) -> dict[str, str]: + for name in sdk_validator.LEGACY_TOOLS: + if capture([str(sdk / name), "--version"]).strip() != name + " " + version: + raise ReleaseError(name + " --version does not match committed VERSION") + auxiliary = {} + if (sdk / "aperture").is_file(): + identity = capture([str(sdk / "aperture"), "--version"]).strip() + match = re.fullmatch(r"aperture ([^\s]+) \(NIL Framework\)", identity) + if match is None: + raise ReleaseError("aperture --version does not identify the Aperture preview") + auxiliary["aperture"] = match.group(1) + return auxiliary + + def validate_vsix(path: Path, version: str) -> str: if not stat.S_ISREG(path.lstat().st_mode) or path.stat().st_size > 128 * 1024 * 1024: raise ReleaseError("VSIX must be a bounded regular archive") @@ -428,9 +443,7 @@ def assemble(args: argparse.Namespace) -> Path: validate_dependency_policy(policy, notices, inventory, manifest["qualification"]["evidence"]["build"]) vsix_name = validate_vsix(args.vsix, version) if args.vsix else None vsix_digest = sha256(args.vsix) if args.vsix else None - for name in TOOLS: - if capture([str(sdk / name), "--version"]).strip() != name + " " + version: - raise ReleaseError(name + " --version does not match committed VERSION") + auxiliary_versions = validate_tool_versions(sdk, version) # Mandatory installed-tool execution, not merely trusted historical evidence. capture([sys.executable, str(SCRIPTS / "validate-sdk.py"), str(sdk), "--require-rc-checks", "--expected-revision", args.expected_revision], timeout=1800) @@ -459,7 +472,8 @@ def assemble(args: argparse.Namespace) -> Path: "manifestSha256": records["manifest.json"][1], "qualification": "rc-checks"}, "assets": [{"name": path.name, "bytes": path.stat().st_size, "sha256": sha256(path)} for path in sorted(stage.iterdir())], - "verification": {"installedSdkSmoke": "passed", "allToolVersions": version, + "verification": {"installedSdkSmoke": "passed", "frameworkToolVersions": version, + "auxiliaryToolVersions": auxiliary_versions, "archiveNormalization": "nil.sdk-tar.v1", "dependencyReview": "explicit policy assertion; not automatic legal or transitive dependency verification", "builddCompatibility": "not yet qualified; local assembly is not publication"}, diff --git a/scripts/check-sdk-routes.py b/scripts/check-sdk-routes.py index b10bbc50..47a26389 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -44,6 +44,7 @@ "scientific-literals", "scientific-literals-matrix", "signed-numbers-matrix", "formatted-text", "formatted-text-matrix", "tuples", "tuples-matrix", + "tuple-arrays", "tuple-arrays-matrix", "integer-literal-widths", "integer-literal-widths-matrix", "checked-text-spans", "checked-text-spans-matrix", "checked-i64-conversion", "checked-i64-conversion-matrix", diff --git a/scripts/package-sdk.py b/scripts/package-sdk.py index 6e16dd34..6e6729a1 100755 --- a/scripts/package-sdk.py +++ b/scripts/package-sdk.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Compile Ny's standard library and seal a staged SDK with a manifest.""" +"""Compile NIL's standard library and seal a staged SDK with a manifest.""" from __future__ import annotations @@ -25,22 +25,12 @@ is_nil_library, is_nil_v2_library, is_static_archive, nil_library_format, nil_library_version, ) -from sdk_qualification import collect_qualification, qualification_errors, source_identity +from sdk_qualification import TOOLS, collect_qualification, qualification_errors, source_identity from sdk_sources import is_source, module_declarations, module_artifact_path from sdk_runtime import STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS, shared_library_valid -REQUIRED_TOOLS = ( - "nilcompiler", - "nilinterpreter", - "nilassembler", - "nillinker", - "nillsp", - "nildebugger", - "nilschema", - "nilagent", - "nilbuild", -) +REQUIRED_TOOLS = TOOLS MANIFEST_NAME = "manifest.json" NATIVE_RUNTIME_ARCHIVE_NAMES = STATIC_NAMES diff --git a/scripts/sdk_qualification.py b/scripts/sdk_qualification.py index f8204306..5efb626a 100644 --- a/scripts/sdk_qualification.py +++ b/scripts/sdk_qualification.py @@ -18,8 +18,11 @@ from sdk_capabilities import capability_errors, collect_capabilities, record_capabilities from sdk_runtime import STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS -TOOLS = ("nilcompiler", "nilinterpreter", "nilassembler", "nillinker", "nillsp", - "nildebugger", "nilschema", "nilagent", "nilbuild") +LEGACY_TOOLS = ("nilcompiler", "nilinterpreter", "nilassembler", "nillinker", "nillsp", + "nildebugger", "nilschema", "nilagent", "nilbuild") +# New packages include the separately versioned Aperture preview. Historical +# sealed SDKs retain their original nine-tool manifest/evidence contract. +TOOLS = LEGACY_TOOLS + ("aperture",) DIGEST = re.compile(r"[0-9a-f]{64}") @@ -289,7 +292,7 @@ def qualification_errors(manifest: dict[str, Any], require_rc: bool = False, tools = manifest.get("tools") if isinstance(manifest.get("tools"), list) else [] expected_tools = {tool.get("name"): tool.get("sha256") for tool in tools if isinstance(tool, dict) and isinstance(tool.get("name"), str)} - if evidence.get("tools") != expected_tools or set(expected_tools) != set(TOOLS): + if evidence.get("tools") != expected_tools or set(expected_tools) not in (set(LEGACY_TOOLS), set(TOOLS)): errors.append("qualification tool hashes differ from the packaged tools") if evidence.get("runtime_sha256") != runtime.get("sha256"): errors.append("qualification runtime hash differs from the packaged runtime") diff --git a/scripts/validate-sdk.py b/scripts/validate-sdk.py index 4bf1250d..023304c2 100755 --- a/scripts/validate-sdk.py +++ b/scripts/validate-sdk.py @@ -24,22 +24,12 @@ is_nil_library, is_nil_v2_library, is_static_archive, nil_library_format, nil_library_version, ) -from sdk_qualification import qualification_errors +from sdk_qualification import LEGACY_TOOLS, TOOLS, qualification_errors from sdk_sources import is_source, module_artifact_path, canonical_std_namespace from sdk_runtime import STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS, shared_library_valid, shared_runtime_smoke -REQUIRED_TOOLS = ( - "nilcompiler", - "nilinterpreter", - "nilassembler", - "nillinker", - "nillsp", - "nildebugger", - "nilschema", - "nilagent", - "nilbuild", -) +REQUIRED_TOOLS = TOOLS SDK_DIRECTORIES = ("nillib", "nilstd", "docs") RELEASE_DOCUMENTATION_FILES = { "docs/release/THIRD_PARTY_NOTICES.txt", @@ -86,6 +76,11 @@ def executable_name(name: str) -> str: return name + (".exe" if os.name == "nt" else "") +def inventory_tools(paths) -> tuple[str, ...]: + """Recognize the two sealed v1 inventories, without permitting omissions.""" + return REQUIRED_TOOLS if executable_name("aperture") in paths else LEGACY_TOOLS + + def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: @@ -152,7 +147,7 @@ def inventory_tree(root: Path, errors: list[str]) -> tuple[dict[str, Path], set[ def root_layout_errors(sdk: Path) -> list[str]: errors: list[str] = [] expected_files = { - *(executable_name(name) for name in REQUIRED_TOOLS), + *(executable_name(name) for name in LEGACY_TOOLS), "LICENSE", MANIFEST_NAME, } @@ -177,6 +172,8 @@ def root_layout_errors(sdk: Path) -> list[str]: actual_directories.add(entry.name) else: errors.append("SDK root contains a special entry: {}".format(entry.name)) + if executable_name("aperture") in actual_files: + expected_files.add(executable_name("aperture")) if actual_files != expected_files: errors.append( "SDK root files differ: missing={} extra={}".format( @@ -278,7 +275,7 @@ def validate_exact_layout( errors: list[str], ) -> None: expected_root_files = { - *(executable_name(name) for name in REQUIRED_TOOLS), + *(executable_name(name) for name in inventory_tools(files)), "LICENSE", MANIFEST_NAME, } @@ -433,9 +430,10 @@ def validate_tools( files, errors, ) - if names != list(REQUIRED_TOOLS): + expected_tools = inventory_tools(files) + if names != list(expected_tools): errors.append("manifest tool names must be the canonical ordered tool set") - expected_paths = [executable_name(name) for name in REQUIRED_TOOLS] + expected_paths = [executable_name(name) for name in expected_tools] if paths != expected_paths: errors.append("manifest tool paths must name each canonical root executable exactly once") @@ -705,6 +703,7 @@ def tool_identity_error( usage: str, cwd: Path, environment: dict[str, str], + version_suffix: str = "", ) -> str | None: try: help_process = subprocess.run( @@ -752,7 +751,8 @@ def tool_identity_error( return "SDK {} --version could not run: {}".format(name, exc) if ( version_process.returncode != 0 - or re.fullmatch(re.escape(name) + r" [^\s]+\n?", version_process.stdout) + or re.fullmatch(re.escape(name) + r" [^\s]+" + + re.escape(version_suffix) + r"\n?", version_process.stdout) is None or version_process.stderr ): @@ -859,6 +859,13 @@ def run_smoke(sdk: Path, native_enabled: bool) -> list[str]: ) if identity_error is not None: errors.append(identity_error) + aperture = sdk / executable_name("aperture") + if aperture.is_file(): + identity_error = tool_identity_error( + aperture, "aperture", "Usage: aperture", root, smoke_environment, + version_suffix=" (NIL Framework)") + if identity_error is not None: + errors.append(identity_error) if errors: return errors @@ -1145,11 +1152,12 @@ def run_smoke(sdk: Path, native_enabled: bool) -> list[str]: def validation_success_message( - structural_only: bool, module_count: int, page_count: int + structural_only: bool, module_count: int, page_count: int, + tool_count: int = len(REQUIRED_TOOLS), ) -> str: summary = ( "{} tools, {} logical library modules, {} documentation pages".format( - len(REQUIRED_TOOLS), module_count, page_count + tool_count, module_count, page_count ) ) if structural_only: @@ -1230,7 +1238,8 @@ def main() -> int: for error in errors: print("- {}".format(error)) return 1 - print(validation_success_message(args.skip_smoke, module_count, page_count)) + print(validation_success_message(args.skip_smoke, module_count, page_count, + len(inventory_tools(files)))) qualification = manifest.get("qualification", {}) mode = qualification.get("mode", "development (legacy manifest)") print("SDK qualification: {} (not a language release declaration)".format(mode)) diff --git a/tests/language/tuple-arrays-matrix.matrix b/tests/language/tuple-arrays-matrix.matrix new file mode 100644 index 00000000..4a8226d5 --- /dev/null +++ b/tests/language/tuple-arrays-matrix.matrix @@ -0,0 +1,166 @@ +book tuple_arrays +read everything from nil.std.collections +read everything from nil.std.core +read everything from nil.std.core + +counter begin record + field total as number +end record + +reading-state begin choice + when Ready holding override integer + when Idle +end choice + +repeat-pair of type T receives item as T returns array of T begin paragraph + value values as array of T is new-with-value of T with size being 2, `value` being item + append item to values + give values +end paragraph + +make-owned returns array of tuple of (number, text) begin paragraph + value values as array of tuple of (number, text) is [] + variable index as override integer is 0 + repeat while index is less than 257 + value entry as tuple of (number, text) is (index, formatted "owned-{index}") + append entry to values + set index to index plus 1 + end repeat + give values +end paragraph + +fresh-pairs returns array of tuple of (number, text) begin paragraph + give [(1, "returned"), ((2 becomes number), "wide")] +end paragraph + +main returns override integer begin paragraph + value first as tuple of (number, text, floating, boolean) is (41, "first", -1.5, true) + value second as tuple of (number, text, floating, boolean) is (42, "second", 2.25, false) + value items is [first, second] + value alias is items + value retained is items at 0 + say the length of items + say (items at 0).0 + say (items at 1).1 + say (items at 0).2 + say (items at 1).3 + set items at 0 to second + say (alias at 0).0 + say retained.1 + append first to alias + say the length of items + say (items at 2).1 + set items at -1 to first + set items at 3 to second + say the length of items + say (items at 0).0 + + value nested is [((1, "nested"), (false, -0.5)), ((2, "tail"), (true, 0.25))] + say (nested at 0).0.1 + say (nested at 1).1.0 + say (nested at 0).1.1 + value singles as array of tuple of (number) is [((9 becomes number),), ((10 becomes number),)] + say (singles at 1).0 + + value object is build counter with total being 5 + value references is [(object, "shared")] + value saved is references at 0 + set saved.0.total to 17 + say (references at 0).0.total + set references at 0 to ((build counter with total being 23), "replacement") + say saved.0.total + say (references at 0).0.total + + value repeated is repeat-pair of tuple of (number, text, floating, boolean) with item being first + say length of tuple of (number, text, floating, boolean) with arr being repeated + evaluate array-set of tuple of (number, text, floating, boolean) with arr being repeated, idx being 1, `value` being second + value selected is get of tuple of (number, text, floating, boolean) with arr being repeated, idx being 1 + say selected.1 + evaluate array-set of tuple of (number, text, floating, boolean) with arr being repeated, idx being -1, `value` being second + evaluate array-set of tuple of (number, text, floating, boolean) with arr being repeated, idx being 3, `value` being second + say (repeated at 0).1 + say try-copy-range of tuple of (number, text, floating, boolean) with source being repeated, source-offset being 0, destination being repeated, destination-offset being 1, count being 2 + say (repeated at 1).1 + say (repeated at 2).1 + say try-copy-range of tuple of (number, text, floating, boolean) with source being repeated, source-offset being 1, destination being repeated, destination-offset being 0, count being 2 + say (repeated at 0).1 + say (repeated at 1).1 + say try-copy-range of tuple of (number, text, floating, boolean) with source being repeated, source-offset being 0, destination being repeated, destination-offset being 2, count being 2 + say (repeated at 2).1 + + value empty as array of tuple of (number, text, floating, boolean) is [] + say the length of empty + append second to empty + say (empty at 0).0 + value filled is new-with-value of tuple of (counter, text) with size being 2, `value` being (object, "filled") + set (filled at 0).0.total to 31 + say (filled at 1).0.total + say object.total + value returned-values is make-owned with nothing + value owned-alias is returned-values + value first-owned is returned-values at 0 + append ((257 becomes number), "added") to owned-alias + say the length of returned-values + say first-owned.1 + say (returned-values at 128).1 + say (returned-values at 256).0 + say (returned-values at 257).1 + value converted as array of tuple of (number, text) is [(1, "declared"), ((2 becomes number), "wide")] + set converted at 0 to (3, "replaced") + append (4, "pushed") to converted + say (converted at 0).0 + say (converted at 2).0 + value returned-pairs is fresh-pairs with nothing + say (returned-pairs at 0).1 + say (returned-pairs at 1).0 + + value active as reading-state is reading-state.Ready holding 73 + value inactive as reading-state is reading-state.Idle + value states is [(active, "active"), (inactive, "idle")] + consider (states at 0).0 + when reading-state.Ready holding amount then say amount + when reading-state.Idle then say 0 + end consider + set states at 0 to (inactive, "replaced") + consider (states at 0).0 + when reading-state.Ready holding amount then say amount + when reading-state.Idle then say (states at 0).1 + end consider + value present as Option of number is Option.Some holding (91 becomes number) + value absent as Option of number is Option.None + value options is [(present,), (absent,)] + consider (options at 0).0 + when Option.Some holding amount then say amount + when Option.None then say 0 + end consider + consider (options at 1).0 + when Option.Some holding amount then say amount + when Option.None then say "empty" + end consider + + value parsed is [((Convert.try-to-i32 with "94"),), ((Convert.try-to-i32 with "invalid"),)] + consider (parsed at 0).0 + when Result.Ok holding amount then say amount + when Result.Error holding _ then say "unexpected" + end consider + consider (parsed at 1).0 + when Result.Ok holding _ then say "unexpected" + when Result.Error holding _ then say "parse rejected" + end consider + + allocate raw as pointer to override integer sized 3 + set raw at 0 to 81 + set raw at 1 to 82 + set raw at 2 to 83 + value pointers is [(raw, "base"), (raw plus 1, "interior"), (raw plus 3, "one-past")] + value base-pointer is (pointers at 0).0 + value interior-pointer is (pointers at 1).0 + value end-pointer is (pointers at 2).0 + say base-pointer at 0 + say interior-pointer at 0 + value last-pointer is end-pointer minus 1 + say last-pointer at 0 + say end-pointer equals (raw plus 3) + release raw + give 0 +end paragraph diff --git a/tests/language/tuple-arrays-matrix.stdout b/tests/language/tuple-arrays-matrix.stdout new file mode 100644 index 00000000..ca5cd87a --- /dev/null +++ b/tests/language/tuple-arrays-matrix.stdout @@ -0,0 +1,52 @@ +2 +41 +second +-1.5 +0 +42 +first +3 +first +3 +42 +nested +1 +-0.5 +10 +17 +17 +23 +3 +second +first +1 +first +second +1 +first +second +0 +second +0 +42 +31 +31 +258 +owned-0 +owned-128 +256 +added +3 +4 +returned +2 +73 +replaced +91 +empty +94 +parse rejected +81 +82 +83 +1 diff --git a/tests/language/tuple-arrays.ny b/tests/language/tuple-arrays.ny new file mode 100644 index 00000000..04604052 --- /dev/null +++ b/tests/language/tuple-arrays.ny @@ -0,0 +1,166 @@ +module tuple_arrays +import nil.std.collections +import nil.std.core +import nil.std.core + +struct Counter + value: i64 +end struct + +enum ReadingState + Ready(i32) + Idle +end enum + +fn repeat_pair(item: T) -> array + let values: array = new_with_value(2, item) + values.push(item) + return values +end fn + +fn make_owned() -> array<(i64, text)> + let values: array<(i64, text)> = [] + let mut index: i32 = 0 + while index < 257 + let entry: (i64, text) = (index, $"owned-{index}") + values.push(entry) + index = index + 1 + end while + return values +end fn + +fn fresh_pairs() -> array<(i64, text)> + return [(1, "returned"), (2 as i64, "wide")] +end fn + +fn main() -> i32 + let first: (i64, text, f64, bool) = (41, "first", -1.5, true) + let second: (i64, text, f64, bool) = (42, "second", 2.25, false) + let items = [first, second] + let alias = items + let retained = items[0] + println(items.len()) + println(items[0].0) + println(items[1].1) + println(items[0].2) + println(items[1].3) + items[0] = second + println(alias[0].0) + println(retained.1) + alias.push(first) + println(items.len()) + println(items[2].1) + items[-1] = first + items[3] = second + println(items.len()) + println(items[0].0) + + let nested = [((1, "nested"), (false, -0.5)), ((2, "tail"), (true, 0.25))] + println(nested[0].0.1) + println(nested[1].1.0) + println(nested[0].1.1) + let singles: array<(i64,)> = [(9 as i64,), (10 as i64,)] + println(singles[1].0) + + let object = Counter { value: 5 } + let references = [(object, "shared")] + let saved = references[0] + saved.0.value = 17 + println(references[0].0.value) + references[0] = (Counter { value: 23 }, "replacement") + println(saved.0.value) + println(references[0].0.value) + + let repeated = repeat_pair<(i64, text, f64, bool)>(first) + println(length<(i64, text, f64, bool)>(repeated)) + array_set<(i64, text, f64, bool)>(repeated, 1, second) + let selected = get<(i64, text, f64, bool)>(repeated, 1) + println(selected.1) + array_set<(i64, text, f64, bool)>(repeated, -1, second) + array_set<(i64, text, f64, bool)>(repeated, 3, second) + println(repeated[0].1) + println(try_copy_range<(i64, text, f64, bool)>(repeated, 0, repeated, 1, 2)) + println(repeated[1].1) + println(repeated[2].1) + println(try_copy_range<(i64, text, f64, bool)>(repeated, 1, repeated, 0, 2)) + println(repeated[0].1) + println(repeated[1].1) + println(try_copy_range<(i64, text, f64, bool)>(repeated, 0, repeated, 2, 2)) + println(repeated[2].1) + + let empty: array<(i64, text, f64, bool)> = [] + println(empty.len()) + empty.push(second) + println(empty[0].0) + let filled = new_with_value<(Counter, text)>(2, (object, "filled")) + filled[0].0.value = 31 + println(filled[1].0.value) + println(object.value) + let returned_values = make_owned() + let owned_alias = returned_values + let first_owned = returned_values[0] + owned_alias.push((257 as i64, "added")) + println(returned_values.len()) + println(first_owned.1) + println(returned_values[128].1) + println(returned_values[256].0) + println(returned_values[257].1) + let converted: array<(i64, text)> = [(1, "declared"), (2 as i64, "wide")] + converted[0] = (3, "replaced") + converted.push((4, "pushed")) + println(converted[0].0) + println(converted[2].0) + let returned_pairs = fresh_pairs() + println(returned_pairs[0].1) + println(returned_pairs[1].0) + + let active: ReadingState = ReadingState.Ready(73) + let inactive: ReadingState = ReadingState.Idle + let states = [(active, "active"), (inactive, "idle")] + match states[0].0 + ReadingState.Ready(amount) -> println(amount) + ReadingState.Idle -> println(0) + end match + states[0] = (inactive, "replaced") + match states[0].0 + ReadingState.Ready(amount) -> println(amount) + ReadingState.Idle -> println(states[0].1) + end match + let present: Option = Option.Some(91 as i64) + let absent: Option = Option.None + let options = [(present,), (absent,)] + match options[0].0 + Option.Some(amount) -> println(amount) + Option.None -> println(0) + end match + match options[1].0 + Option.Some(amount) -> println(amount) + Option.None -> println("empty") + end match + + let parsed = [(Convert.try_to_i32("94"),), (Convert.try_to_i32("invalid"),)] + match parsed[0].0 + Result.Ok(amount) -> println(amount) + Result.Error(_) -> println("unexpected") + end match + match parsed[1].0 + Result.Ok(_) -> println("unexpected") + Result.Error(_) -> println("parse rejected") + end match + + let raw = allocate(3) + raw[0] = 81 + raw[1] = 82 + raw[2] = 83 + let pointers = [(raw, "base"), (raw + 1, "interior"), (raw + 3, "one-past")] + let base_pointer = pointers[0].0 + let interior_pointer = pointers[1].0 + let end_pointer = pointers[2].0 + println(base_pointer[0]) + println(interior_pointer[0]) + let last_pointer = end_pointer - 1 + println(last_pointer[0]) + println(end_pointer == raw + 3) + deallocate(raw) + return 0 +end fn diff --git a/tests/language/tuple-arrays.stdout b/tests/language/tuple-arrays.stdout new file mode 100644 index 00000000..ca5cd87a --- /dev/null +++ b/tests/language/tuple-arrays.stdout @@ -0,0 +1,52 @@ +2 +41 +second +-1.5 +0 +42 +first +3 +first +3 +42 +nested +1 +-0.5 +10 +17 +17 +23 +3 +second +first +1 +first +second +1 +first +second +0 +second +0 +42 +31 +31 +258 +owned-0 +owned-128 +256 +added +3 +4 +returned +2 +73 +replaced +91 +empty +94 +parse rejected +81 +82 +83 +1 diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index 4eb3e819..3250b6f4 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -1,5 +1,6 @@ #include "native_runtime.hpp" #include "integer_conversion.hpp" +#include "array_intrinsic.hpp" #include #include @@ -241,10 +242,93 @@ void check_array_contract(bool &ok) { nyrt_array_get(texts, NYRT_ARRAY_TEXT, 82) == 0, "text array kind/bounds validation failed"); ok &= expect(nyrt_buffer_new(NYRT_ARRAY_F64, 1) == nullptr && - nyrt_buffer_new(NYRT_ARRAY_TEXT, 1) == nullptr, + nyrt_buffer_new(NYRT_ARRAY_TEXT, 1) == nullptr && + nyrt_buffer_new(NYRT_ARRAY_TUPLE, 1) == nullptr, "new array kinds expanded the raw-pointer ABI unexpectedly"); } +void check_tuple_array_contract(bool &ok) { + const auto bits = [](const void *value) { + return static_cast(reinterpret_cast(value)); + }; + const auto text = nyrt_i64_to_text(987654321); + auto *nested_array = nyrt_array_new_with_value(NYRT_ARRAY_I64, 1, 73); + auto *nested = static_cast(nyrt_alloc(16)); + auto *tuple = static_cast(nyrt_alloc(16)); + void *array = nyrt_array_new_with_value(NYRT_ARRAY_TUPLE, 2, bits(tuple)); + if (!expect(text && nested_array && nested && tuple && array, + "could not allocate tuple array test graph")) { + ok = false; + return; + } + nested[0] = bits(text); + nested[1] = bits(nested_array); + tuple[0] = bits(nested); + tuple[1] = 42; + for (int index = 0; index < 80; ++index) + ok &= expect(nyrt_array_push(array, NYRT_ARRAY_TUPLE, bits(tuple)) == 1, + "tuple array growth failed"); + ok &= expect(nyrt_array_length(array, NYRT_ARRAY_TUPLE) == 82 && + nyrt_array_get(array, NYRT_ARRAY_TUPLE, 81) == bits(tuple), + "tuple array did not preserve shared object identity across growth"); + ok &= expect(nyrt_array_set(array, NYRT_ARRAY_TUPLE, -1, 0) == 0 && + nyrt_array_set(array, NYRT_ARRAY_TEXT, 0, 0) == 0 && + nyrt_array_length(array, NYRT_ARRAY_TEXT) == -1, + "tuple array bounds or runtime kind mismatch was accepted"); + + // The sole published root is the outer array, so retaining the transitive + // tuple/text/array graph proves payload slots participate in native tracing. + std::uint64_t root = bits(array); + const void *slots[] = {&root}; + nyrt_roots_enter(slots, 1); + nyrt_collect(); + ok &= expect(nyrt_managed_objects() == 5, + "tuple array tracing did not retain exactly its reachable graph"); + ok &= expect(nyrt_array_get(array, NYRT_ARRAY_TUPLE, 0) == bits(tuple) && + tuple[0] == bits(nested) && nested[1] == bits(nested_array) && + nyrt_array_get(nested_array, NYRT_ARRAY_I64, 0) == 73, + "tuple array lost a transitive aggregate or array during collection"); + ok &= expect_text(reinterpret_cast(static_cast(nested[0])), + "987654321", "tuple array lost transitive text during collection"); + auto *replacement = static_cast(nyrt_alloc(8)); + if (replacement) { + replacement[0] = 17; + for (int index = 0; index < 82; ++index) + ok &= expect(nyrt_array_set(array, NYRT_ARRAY_TUPLE, index, bits(replacement)) == 1, + "tuple array replacement failed"); + nyrt_collect(); + ok &= expect(nyrt_managed_objects() == 2 && + nyrt_array_length(nested_array, NYRT_ARRAY_I64) == -1, + "replaced tuple array elements retained an unreachable graph"); + } else { + ok = false; + } + root = 0; + nyrt_collect(); + ok &= expect(nyrt_managed_objects() == 0, + "unrooted tuple array graph survived collection"); + nyrt_roots_leave(slots); + + ok &= expect(ny::canonical_array_type("tuple>>") == + "tuple>>", + "tuple array canonicalization erased nominal identity"); + ok &= expect(!ny::is_array_tuple_type("tuple<>") && + !ny::is_array_tuple_type("tuple") && + !ny::is_array_tuple_type("tuple>"), + "malformed tuple array metadata was accepted"); + const auto contract = ny::parse_array_intrinsic({"intrinsic", "array.get", "2", + "tuple", "tuple"}); + ok &= expect(contract.element == "tuple", + "tuple array intrinsic did not canonicalize scalar aliases"); + bool wrong_case_rejected = false; + try { + (void)ny::parse_array_intrinsic({"intrinsic", "array.get", "2", + "tuple", "tuple"}); + } catch (const std::runtime_error &) { wrong_case_rejected = true; } + ok &= expect(wrong_case_rejected, + "tuple array intrinsic ignored case-sensitive nominal identity"); +} + void check_buffer_contract(bool &ok) { ok &= expect(nyrt_buffer_new(999, 1) == nullptr, "unknown buffer kind was accepted"); @@ -665,6 +749,7 @@ int main() { check_buffer_contract(ok); check_conversion_contract(ok); check_file_contract(ok); + check_tuple_array_contract(ok); auto *owned = static_cast(nyrt_alloc(8)); ok &= expect(owned != nullptr, "could not allocate context-owned storage"); diff --git a/tests/release_artifact_tests.py b/tests/release_artifact_tests.py index f8dbb8f6..3c5a42a9 100644 --- a/tests/release_artifact_tests.py +++ b/tests/release_artifact_tests.py @@ -218,6 +218,20 @@ def test_older_sdk_documentation_is_still_structurally_allowed(self): class ArchiveTests(unittest.TestCase): + def test_framework_versions_remain_pinned_with_independent_aperture_preview(self): + with tempfile.TemporaryDirectory() as directory: + sdk = Path(directory) + def identity(arguments): + name = Path(arguments[0]).name + return "aperture 0.1.0-dev (NIL Framework)" if name == "aperture" else name + " " + VERSION + with patch.object(release, "capture", side_effect=identity): + self.assertEqual(release.validate_tool_versions(sdk, VERSION), {}) + (sdk / "aperture").write_text("fixture") + self.assertEqual(release.validate_tool_versions(sdk, VERSION), {"aperture": "0.1.0-dev"}) + with patch.object(release, "capture", return_value="nilcompiler wrong"): + with self.assertRaisesRegex(release.ReleaseError, "nilcompiler.*committed VERSION"): + release.validate_tool_versions(sdk, VERSION) + def test_atomic_no_replace_preserves_existing_empty_directory(self): if sys.platform != "linux": self.skipTest("release assembly targets Linux only") @@ -239,7 +253,7 @@ def test_normalized_archive_is_deterministic_and_keeps_sdk_root_tools(self): sdk = root / "sdk" sdk.mkdir() files = {} - for relative in ("nilcompiler", "manifest.json", "nillib/core.nil", "nilstd/core.ny", "docs/index.html"): + for relative in ("nilcompiler", "aperture", "manifest.json", "nillib/core.nil", "nilstd/core.ny", "docs/index.html"): path = sdk / relative path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(relative.encode()) @@ -256,7 +270,7 @@ def test_normalized_archive_is_deterministic_and_keeps_sdk_root_tools(self): for member in archive: self.assertEqual((member.uid, member.gid, member.uname, member.gname, member.mtime), (0, 0, "", "", 1234)) self.assertFalse(member.issym() or member.islnk()) - if member.name.endswith("/nilcompiler"): + if member.name.endswith(("/nilcompiler", "/aperture")): self.assertEqual(member.mode, 0o755) elif member.isfile(): self.assertEqual(member.mode, 0o644) @@ -400,6 +414,7 @@ def validate(*args): stack.enter_context(patch.object(release, "elf_inventory", return_value={ **INVENTORY, "platform": {"os": "linux", "architecture": "x86_64"}})) stack.enter_context(patch.object(release, "capture", side_effect=lambda command, **kw: + "aperture 0.1.0-dev (NIL Framework)" if Path(command[0]).name == "aperture" else Path(command[0]).name + " " + VERSION if Path(command[0]).name in release.TOOLS else "")) return argparse.Namespace(repo_root=ROOT, sdk=sdk, output=root / "release-a", expected_revision=REVISION, dependency_policy=policy_path, notices=notices_path, vsix=None) diff --git a/tests/sdk_native_archive_validation.py b/tests/sdk_native_archive_validation.py index ed5c274b..5c44a991 100644 --- a/tests/sdk_native_archive_validation.py +++ b/tests/sdk_native_archive_validation.py @@ -505,7 +505,7 @@ def file_record(key: str, path: Path) -> dict: "--skip-smoke success did not identify its structural-only scope" ) if full_message != ( - "NIL Framework SDK contract valid: 9 tools, 15 logical library modules, " + "NIL Framework SDK contract valid: 10 tools, 15 logical library modules, " "17 documentation pages" ): raise AssertionError("full SDK validation success wording regressed") diff --git a/tests/sdk_qualification_tests.py b/tests/sdk_qualification_tests.py index d3c12c97..ab26c8b5 100644 --- a/tests/sdk_qualification_tests.py +++ b/tests/sdk_qualification_tests.py @@ -53,6 +53,14 @@ def rejection(self, value, expected): def test_positive_metadata(self): self.assertEqual(qualification.qualification_errors(fixture(), True, "a" * 40), []) + def test_aperture_hash_is_bound_and_legacy_tool_evidence_remains_valid(self): + value = fixture() + value["qualification"]["evidence"]["tools"]["aperture"] = "e" * 64 + self.rejection(value, "tool hashes differ") + value["tools"] = [tool for tool in value["tools"] if tool["name"] != "aperture"] + del value["qualification"]["evidence"]["tools"]["aperture"] + self.assertEqual(qualification.qualification_errors(value, True, "a" * 40), []) + def test_nil_sdk_requires_matching_shared_runtime_evidence(self): value = fixture() value["schema"] = "nil.sdk.v1" @@ -388,6 +396,75 @@ def test_both_runtime_forms_required_and_returned(self): with self.assertRaisesRegex(SystemExit, "matching shared native runtime"): self.package.validate_stage_input(self.root) + def test_new_packages_require_executable_aperture(self): + aperture = self.root / self.package.executable_name("aperture") + aperture.unlink() + with self.assertRaisesRegex(SystemExit, "missing files=.*aperture"): + self.package.validate_stage_input(self.root) + if os.name != "nt": + aperture.write_text("fixture") + aperture.chmod(0o644) + with self.assertRaisesRegex(SystemExit, "tool is not executable.*aperture"): + self.package.validate_stage_input(self.root) + + def test_sealed_tool_inventory_accepts_legacy_or_aperture_and_rejects_mismatch(self): + spec = importlib.util.spec_from_file_location("nil_validator_inventory_test", ROOT / "scripts/validate-sdk.py") + validator = importlib.util.module_from_spec(spec) + spec.loader.exec_module(validator) + native = self.root / "nillib/native" + native.mkdir(parents=True) + self.static.rename(native / self.static.name) + self.shared.rename(native / self.shared.name) + (self.root / "manifest.json").write_text("{}") + + def records(names): + return [{"name": name, "path": validator.executable_name(name), + "bytes": (self.root / validator.executable_name(name)).stat().st_size, + "sha256": validator.sha256(self.root / validator.executable_name(name))} + for name in names] + + full_records = records(validator.REQUIRED_TOOLS) + errors = validator.root_layout_errors(self.root) + files, directories = validator.inventory_tree(self.root, errors) + validator.validate_exact_layout(self.root, files, directories, errors) + validator.validate_tools(full_records, files, errors) + self.assertEqual(errors, []) + errors = [] + validator.validate_tools(full_records[:-1], files, errors) + self.assertTrue(any("canonical ordered tool set" in error for error in errors), errors) + aperture = self.root / validator.executable_name("aperture") + aperture.write_text("changed payload") + errors = [] + validator.validate_tools(full_records, files, errors) + self.assertTrue(any("aperture hash mismatch" in error for error in errors), errors) + aperture.unlink() + errors = validator.root_layout_errors(self.root) + files, directories = validator.inventory_tree(self.root, errors) + validator.validate_exact_layout(self.root, files, directories, errors) + validator.validate_tools(full_records[:-1], files, errors) + self.assertEqual(errors, []) + validator.validate_tools(full_records, files, errors) + self.assertTrue(any("missing file: aperture" in error for error in errors), errors) + (self.root / "unexpected-tool").write_text("fixture") + self.assertTrue(validator.root_layout_errors(self.root)) + self.assertIn("9 tools", validator.validation_success_message(False, 1, 1, 9)) + + def test_aperture_identity_keeps_its_preview_version(self): + spec = importlib.util.spec_from_file_location("nil_validator_identity_test", ROOT / "scripts/validate-sdk.py") + validator = importlib.util.module_from_spec(spec) + spec.loader.exec_module(validator) + outputs = [subprocess.CompletedProcess([], 0, "Usage: aperture \n", ""), + subprocess.CompletedProcess([], 0, "aperture 0.1.0-dev (NIL Framework)\n", "")] + with patch.object(validator.subprocess, "run", side_effect=outputs): + self.assertIsNone(validator.tool_identity_error( + self.root / "aperture", "aperture", "Usage: aperture", self.root, {}, + version_suffix=" (NIL Framework)")) + outputs[-1] = subprocess.CompletedProcess([], 0, "nilcompiler 1.0.0-rc.1\n", "") + with patch.object(validator.subprocess, "run", side_effect=outputs): + self.assertIn("version identity failed", validator.tool_identity_error( + self.root / "aperture", "aperture", "Usage: aperture", self.root, {}, + version_suffix=" (NIL Framework)")) + def test_duplicate_or_malformed_shared_runtime_rejected(self): (self.root / "libnil.dylib").write_bytes(self.shared.read_bytes()) with self.assertRaisesRegex(SystemExit, "matching shared native runtime"): diff --git a/tests/tools/tuple_array_contract.py b/tests/tools/tuple_array_contract.py new file mode 100644 index 00000000..a7c5097c --- /dev/null +++ b/tests/tools/tuple_array_contract.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""Tuple arrays preserve schemas, identity, and bounds across both frontends.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +REPOSITORY = Path(__file__).resolve().parents[2] + + +def program(language: str, body: str, declarations: str = '', imports: str = '') -> str: + if language == 'ny': + return (imports + declarations + 'fn main() -> i32\n' + body + + '\nreturn 0\nend fn\n') + return ('book tuple_array_contract\n' + imports + declarations + + 'main returns override integer begin paragraph\n' + body + + '\ngive 0\nend paragraph\n') + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--stdlib', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + compiler, interpreter, stdlib = (path.resolve() for path in + (args.compiler, args.interpreter, args.stdlib)) + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_LIBRARY_PATH'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-tuple-array-contract-') as directory: + root = Path(directory) + + def run(command, status=0): + result = subprocess.run(command, cwd=root, env=environment, + capture_output=True, text=True, + stdin=subprocess.DEVNULL, timeout=120) + assert result.returncode == status, (list(map(str, command)), result.returncode, + result.stdout[:4000], result.stderr[:4000]) + return result + + for language in ('ny', 'matrix'): + source = REPOSITORY / 'tests/language' / ( + 'tuple-arrays.ny' if language == 'ny' else 'tuple-arrays-matrix.matrix') + run([sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, '--source', source, + '--expected-stdout', source.with_suffix('.stdout'), '--expected-exit', '0', + '--compiler-arg=--sdk-path', '--compiler-arg=' + str(stdlib), + '--routes', 'all' if args.llvm == 'ON' else + 'text-interpreter,binary-interpreter,bundle-text,bundle-binary', + '--work-dir', root / language, '--strict']) + checks += 6 if args.llvm == 'ON' else 4 + analysis = json.loads(run([compiler, '--sdk-path', stdlib, '--analyze', + '--semantic-index', source]).stdout) + assert analysis['success'], analysis['diagnostics'] + checks += 1 + + # Cross-frontend consumers keep tuple schemas and array element identity, + # including a binary provider whose original source file is absent. + for provider_language in ('ny', 'matrix'): + provider_root = root / ('provider-' + provider_language) + provider_root.mkdir() + provider = provider_root / ('provider.' + provider_language) + provider.write_text( + 'module provider\npub fn make() -> array<(i64,text)>\n' + 'let pair: (i64,text) = (42,"cross")\nreturn [pair,pair]\nend fn\n' + 'pub fn identity(items: array) -> array\nreturn items\nend fn\n' + if provider_language == 'ny' else + 'book provider\npublic make returns array of tuple of (number,text) begin paragraph\n' + 'value pair as tuple of (number,text) is (42,"cross")\ngive [pair,pair]\nend paragraph\n' + 'public identity of type T receives items as array of T returns array of T begin paragraph\n' + 'give items\nend paragraph\n') + consumer_language = 'matrix' if provider_language == 'ny' else 'ny' + consumer = root / ('consumer-' + provider_language + '.' + consumer_language) + consumer.write_text(program(consumer_language, + 'let values = make()\nlet alias = identity<(i64,text)>(values)\n' + 'alias[1] = (43 as i64,"updated")\n' + 'println(values[0].0)\nprintln(values[0].1)\n' + 'println(values[1].0)\nprintln(values[1].1)' + if consumer_language == 'ny' else + 'value values is make with nothing\n' + 'value alias is identity of tuple of (number,text) with items being values\n' + 'set alias at 1 to ((43 becomes number),"updated")\n' + 'say (values at 0).0\nsay (values at 0).1\n' + 'say (values at 1).0\nsay (values at 1).1', + imports='import provider.*\n' if consumer_language == 'ny' else + 'read everything from provider\n')) + libraries = root / ('libraries-' + provider_language) + libraries.mkdir() + for dependency_mode in ('source', 'binary'): + if dependency_mode == 'binary': + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-o', libraries / 'provider.nil', provider]) + provider.unlink() + search = libraries + else: + search = provider_root + for encoding, flags in [('text', []), ('binary', ['--emit-binary-nil'])]: + artifact = root / ('consumer-' + provider_language + '-' + dependency_mode + '-' + encoding + '.nil') + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-I', search, + *flags, '-o', artifact, consumer]) + output = run([interpreter, '--no-ai', artifact]) + assert output.stdout == '42\ncross\n43\nupdated\n' and not output.stderr, output + checks += 1 + if args.llvm == 'ON': + executable = root / ('consumer-' + provider_language + '-' + dependency_mode) + run([compiler, '--quiet', '--no-stdlib', '--native', '-I', search, + '-o', executable, consumer]) + output = run([executable]) + assert output.stdout == '42\ncross\n43\nupdated\n' and not output.stderr, output + checks += 1 + + invalid = [ + ('literal-schema', 'let items = [(1,"a"),(2,true)]', + 'value items is [(1,"a"),(2,true)]'), + ('declared-schema', 'let items: array<(i32,text)> = [(1,true)]', + 'value items as array of tuple of (override integer,text) is [(1,true)]'), + ('set-schema', 'let items = [(1,"a")]\nitems[0] = (2,true)', + 'value items is [(1,"a")]\nset items at 0 to (2,true)'), + ('push-schema', 'let items = [(1,"a")]\nitems.push((2,true))', + 'value items is [(1,"a")]\nappend (2,true) to items'), + ('set-arity', 'let items = [(1,"a")]\nitems[0] = (2,"b",true)', + 'value items is [(1,"a")]\nset items at 0 to (2,"b",true)'), + ('push-width', 'let items = [(1,"a")]\nlet wrong = (2 as i64,"b")\nitems.push(wrong)', + 'value items is [(1,"a")]\nvalue wrong is ((2 becomes number),"b")\nappend wrong to items'), + ('mutable-slot', 'let items = [(1,"a")]\nitems[0].0 = 2', + 'value items is [(1,"a")]\nset (items at 0).0 to 2'), + ] + for name, ny, matrix in invalid: + for language, body in [('ny', ny), ('matrix', matrix)]: + path = root / (name + '.' + language) + path.write_text(program(language, body)) + for unchecked in (False, True): + for flags in (['--no-bundle'], ['--no-bundle', '--emit-binary-nil'], + *([['--native']] if args.llvm == 'ON' else [])): + output = root / 'protected-output' + output.write_bytes(b'keep previous artifact') + result = run([compiler, '--quiet', '--no-stdlib', *flags, + *(['--no-typecheck'] if unchecked else []), + '-o', output, path], 1) + assert 'tuple' in result.stderr.lower(), (name, language, result.stderr) + assert output.read_bytes() == b'keep previous artifact' + checks += 1 + analysis = json.loads(run([compiler, '--no-stdlib', '--analyze', path], 1).stdout) + assert not analysis['success'] and analysis['diagnostics'], (name, language, analysis) + checks += 1 + + # Function parameters obey the same tuple storage identity contract as + # locals and indexed writes, including unchecked compilation. + for language in ('ny', 'matrix'): + ny = language == 'ny' + declaration = ( + 'fn first_value(items: array<(i64,text)>) -> i64\n' + 'return items[0].0\nend fn\n' if ny else + 'first-value receives items as array of tuple of (number,text) returns number begin paragraph\n' + 'give (items at 0).0\nend paragraph\n') + for name, values in [('schema', '[(1,true)]'), + ('width', '[(1,"wrong-width")]'), + ('wildcard', '[]')]: + body = (f'let wrong = {values}\nprintln(first_value(wrong))' if ny else + f'value wrong is {values}\nsay first-value with items being wrong') + path = root / ('argument-' + name + '.' + language) + path.write_text(program(language, body, declaration)) + for unchecked in (False, True): + for flags in (['--no-bundle'], ['--no-bundle', '--emit-binary-nil'], + *([['--native']] if args.llvm == 'ON' else [])): + output = root / 'protected-argument' + output.write_bytes(b'keep previous artifact') + result = run([compiler, '--quiet', '--no-stdlib', *flags, + *(['--no-typecheck'] if unchecked else []), + '-o', output, path], 1) + assert 'tuple' in result.stderr.lower(), (name, language, result.stderr) + assert output.read_bytes() == b'keep previous artifact' + checks += 1 + analysis = json.loads(run([compiler, '--no-stdlib', '--analyze', path], 1).stdout) + assert not analysis['success'] and any('tuple' in item['message'].lower() + for item in analysis['diagnostics']), (name, language, analysis) + checks += 1 + + body = ( + 'println(first_value([(1,"literal")]))\n' + 'let exact: array<(i64,text)> = [(2,"existing")]\n' + 'println(first_value(exact))' if ny else + 'say first-value with items being [(1,"literal")]\n' + 'value exact as array of tuple of (number,text) is [(2,"existing")]\n' + 'say first-value with items being exact') + path = root / ('argument-positive.' + language) + path.write_text(program(language, body, declaration)) + stdout = path.with_suffix('.stdout') + stdout.write_text('1\n2\n') + run([sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, '--source', path, + '--expected-stdout', stdout, '--expected-exit', '0', + '--compiler-arg=--no-stdlib', '--routes', + 'all' if args.llvm == 'ON' else + 'text-interpreter,binary-interpreter,bundle-text,bundle-binary', + '--work-dir', root / ('argument-positive-' + language), '--strict']) + checks += 6 if args.llvm == 'ON' else 4 + for flags, suffix in [([], 'text'), (['--emit-binary-nil'], 'binary'), + *([(['--native'], 'native')] if args.llvm == 'ON' else [])]: + artifact = root / ('argument-positive-' + language + '-' + suffix) + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '--no-typecheck', + *flags, '-o', artifact, path]) + result = run([artifact] if suffix == 'native' else [interpreter, '--no-ai', artifact]) + assert result.stdout == stdout.read_text() and not result.stderr, result + checks += 1 + + # Tuple bounds failures must be explicit: no fabricated tuple schema or + # zero-valued record may be returned to a subsequent field projection. + for language in ('ny', 'matrix'): + for name, ny, matrix in [ + ('negative-index', 'let items = [(1,"a")]\nlet missing = items[-1]', + 'value items is [(1,"a")]\nvalue missing is items at -1'), + ('past-end-index', 'let items = [(1,"a")]\nlet missing = items[1]', + 'value items is [(1,"a")]\nvalue missing is items at 1'), + ('empty-index', 'let items: array<(i32,text)> = []\nlet missing = items[0]', + 'value items as array of tuple of (override integer,text) is []\nvalue missing is items at 0'), + ('intrinsic-get', 'let items = [(1,"a")]\nlet missing = get<(i32,text)>(items, 1)', + 'value items is [(1,"a")]\nvalue missing is get of tuple of (override integer,text) with arr being items, idx being 1'), + ]: + path = root / (name + '.' + language) + path.write_text(program(language, ny if language == 'ny' else matrix, + imports='import nil.std.collections\n' if language == 'ny' else + 'read everything from nil.std.collections\n')) + for flags, suffix in [([], 'text'), (['--emit-binary-nil'], 'binary'), + *([(['--native'], 'native')] if args.llvm == 'ON' else [])]: + artifact = root / (name + '-' + language + '-' + suffix) + run([compiler, '--quiet', '--sdk-path', stdlib, '--no-bundle', + *flags, '-o', artifact, path]) + command = [artifact] if suffix == 'native' else [interpreter, '--no-ai', artifact] + output = subprocess.run(command, cwd=root, env=environment, text=True, + capture_output=True, timeout=30) + assert output.returncode != 0 and 'tuple' in output.stderr.lower(), ( + name, language, suffix, output.returncode, output.stdout, output.stderr) + assert not output.stdout, output.stdout + checks += 1 + + if args.llvm == 'ON': + unsupported = [ + ('records', 'struct Record\nvalue: i32\nend struct\n', + 'record-value begin record\nfield item as override integer\nend record\n', + 'let items = [Record { value: 1 }]', + 'value items is [(build record-value with item being 1)]'), + ('enums', 'enum Choice\nOne\nend enum\n', + 'choice-value begin choice\nwhen One\nend choice\n', + 'let items = [Choice.One]', 'value items is [choice-value.One]'), + ('nested-arrays', '', '', 'let items = [[1,2]]', 'value items is [[1,2]]'), + ] + for name, ny_decl, matrix_decl, ny_body, matrix_body in unsupported: + for language, declaration, body in [('ny', ny_decl, ny_body), + ('matrix', matrix_decl, matrix_body)]: + path = root / ('unsupported-' + name + '.' + language) + path.write_text(program(language, body, declaration)) + output = root / 'protected-native' + output.write_bytes(b'keep previous executable') + result = run([compiler, '--quiet', '--no-stdlib', '--native', '-o', output, path], 1) + assert ('[NativeCodegen]' in result.stderr and + 'array' in result.stderr.lower()), result.stderr + assert output.read_bytes() == b'keep previous executable' + checks += 1 + print(f'tuple array contract: {checks} checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/tuple_array_nil_contract.py b/tests/tools/tuple_array_nil_contract.py new file mode 100644 index 00000000..01a4cc65 --- /dev/null +++ b/tests/tools/tuple_array_nil_contract.py @@ -0,0 +1,311 @@ +#!/usr/bin/env python3 +"""Tuple-array schemas and initialized values survive raw text/binary NIL.""" + +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import struct +import subprocess +import tempfile + + +PAIR = "tuple" +SCHEMAS = [(PAIR, [("0", "i64"), ("1", "text")], ["@nil_tuple"])] +ENUMS = [ + ("Other", [("One", "")]), + ("Expected", [("One", ""), ("Payload", "i64")]), + ("expected", [("One", "")]), + ("Generic", [("None", ""), ("Some", "i64")]), + ("Generic", [("None", ""), ("Some", "text")]), + ("Result", [("Ok", "i32"), ("Error", "text")]), +] + + +def instructions(source: str) -> list[tuple[str, list[str]]]: + return [(parts[0], parts[1:]) for line in source.splitlines() + if (parts := line.split())] + + +def encode(body, schemas, binary, extra_functions=()): + body = body + instructions("PUSH_CONST 0\nRET") + functions = [("main", "i32", [], body), *extra_functions] + if not binary: + lines = ['module tuple_array_nil', 'const word = "retained text"'] + for name, fields, annotations in schemas: + lines += annotations + ["struct " + name] + lines += [field + ": " + kind for field, kind in fields] + lines += ["end struct"] + for name, variants in ENUMS: + lines += ["enum " + name] + lines += [variant + (": " + payload if payload else "") + for variant, payload in variants] + lines += ["end enum"] + for name, result_type, annotations, function_body in functions: + lines += annotations + [f"function {name}() -> {result_type}:"] + lines += [" ".join([opcode, *(json.dumps(argument) for argument in args)]) + for opcode, args in function_body] + lines += ["end function"] + return ("\n".join(lines + [""])).encode() + + def u32(value): + return struct.pack(" {PAIR}\nSTORE_LOCAL filled\n" + f"LOAD_LOCAL filled\nINTEROP_CALL intrinsic array.length 1 i32 {PAIR}\nCALL println 1\n" + f"LOAD_LOCAL filled\nPUSH_CONST 1\nINTEROP_CALL intrinsic array.get 2 {PAIR} {PAIR}\n" + "GET_FIELD 0\nCALL println 1") + expected = "42\nretained text\n2\n42\n" + nested_pair = "tuple,text>" + nested_schemas = [(nested_pair, [("0", "array"), ("1", "text")], ["@nil_tuple"])] + # The VM collects on allocation 1024. At that precise boundary the only + # owner of allocation 1023 is the tuple initializer popped by the intrinsic. + # Publishing the result before collecting must retain that nested array. + gc_control = instructions("NEW_ARRAY_LITERAL 0 i64\nPOP") * 1022 + gc_control += instructions(f"PUSH_CONST 1\nNEW_STRUCT {nested_pair}\n" + "PUSH_CONST 73\nNEW_ARRAY_LITERAL 1 i64\nSET_FIELD 0\n" + "PUSH_CONST_STR word\nSET_FIELD 1\n" + f"INTEROP_CALL intrinsic array.new_with_value 2 array<{nested_pair}> {nested_pair}\n" + "PUSH_CONST 0\nGET_INDEX\nGET_FIELD 0\nPUSH_CONST 0\nGET_INDEX\nCALL println 1") + invalid = [ + ("missing-schema", instructions(f"NEW_ARRAY_LITERAL 0 {PAIR}\nPOP"), []), + ("unannotated-schema", instructions(f"NEW_ARRAY_LITERAL 0 {PAIR}\nPOP"), + [(PAIR, SCHEMAS[0][1], [])]), + ("wrong-field-order", instructions(f"NEW_ARRAY_LITERAL 0 {PAIR}\nPOP"), + [(PAIR, [("1", "text"), ("0", "i64")], ["@nil_tuple"])]), + ("wrong-field-type", instructions(f"NEW_ARRAY_LITERAL 0 {PAIR}\nPOP"), + [(PAIR, [("0", "text"), ("1", "text")], ["@nil_tuple"])]), + ("partial-literal", partial + instructions(f"NEW_ARRAY_LITERAL 1 {PAIR}\nPOP"), SCHEMAS), + ("partial-push", instructions(f"NEW_ARRAY_LITERAL 0 {PAIR}") + partial + + instructions("CALL array__push 2"), SCHEMAS), + ("partial-set", construct + instructions(f"NEW_ARRAY_LITERAL 1 {PAIR}\nPUSH_CONST 0") + + partial + instructions("SET_INDEX"), SCHEMAS), + ("partial-create", instructions("PUSH_CONST 2") + partial + + instructions(f"INTEROP_CALL intrinsic array.new_with_value 2 array<{PAIR}> {PAIR}\nPOP"), SCHEMAS), + ("scalar-insertion", instructions(f"PUSH_CONST 42\nNEW_ARRAY_LITERAL 1 {PAIR}\nPOP"), SCHEMAS), + ("intrinsic-result-shape", instructions("PUSH_CONST 2") + construct + + instructions(f"INTEROP_CALL intrinsic array.new_with_value 2 array> {PAIR}\nPOP"), SCHEMAS), + ] + nominal_schemas = [ + ("Widget", [("value", "i64")], []), + ("widget", [("value", "i64")], []), + ("tuple", [("0", "Widget")], ["@nil_tuple"]), + ("tuple", [("0", "widget")], ["@nil_tuple"]), + ] + nominal_tuple = instructions("NEW_STRUCT tuple\nNEW_STRUCT Widget\n" + "PUSH_CONST 73\nSET_FIELD value\nSET_FIELD 0") + invalid += [ + ("case-different-array", nominal_tuple + + instructions("NEW_ARRAY_LITERAL 1 tuple\nPOP"), nominal_schemas), + ("case-different-field", instructions("NEW_STRUCT tuple\nNEW_STRUCT widget\n" + "PUSH_CONST 73\nSET_FIELD value\nSET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple\nPOP"), nominal_schemas), + ] + def singleton_schema(element): + return [(f"tuple<{element}>", [("0", element)], ["@nil_tuple"])] + + enum_schemas = singleton_schema("Expected") + invalid += [ + ("enum-for-record", instructions("NEW_STRUCT tuple\nNEW_VARIANT Other::One 0\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple\nPOP"), nominal_schemas), + ("unrelated-enum", instructions("NEW_STRUCT tuple\nNEW_VARIANT Other::One 0\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple\nPOP"), enum_schemas), + ("case-different-enum", instructions("NEW_STRUCT tuple\nNEW_VARIANT expected::One 0\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple\nPOP"), enum_schemas), + ("unknown-variant", instructions("NEW_STRUCT tuple\nNEW_VARIANT Expected::Missing 0\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple\nPOP"), enum_schemas), + ("wrong-enum-payload", instructions("NEW_STRUCT tuple\nPUSH_CONST_STR word\n" + "NEW_VARIANT Expected::Payload 1 Expected i64\nSET_FIELD 0\n" + "NEW_ARRAY_LITERAL 1 tuple\nPOP"), enum_schemas), + ("wrong-generic-unit-enum", instructions("NEW_STRUCT tuple>\n" + "NEW_VARIANT Generic::None 0 Generic void\nSET_FIELD 0\n" + "NEW_ARRAY_LITERAL 1 tuple>\nPOP"), singleton_schema("Generic")), + ("missing-record-schema", instructions("NEW_STRUCT tuple\nNEW_STRUCT Missing\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple\nPOP"), singleton_schema("Missing")), + ("partial-record", instructions("NEW_STRUCT tuple\nNEW_STRUCT Widget\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple\nPOP"), nominal_schemas), + ("exact-record-before-suffix", instructions("NEW_STRUCT tuple\nNEW_STRUCT other::Widget\n" + "PUSH_CONST 73\nSET_FIELD value\nSET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple\nPOP"), + nominal_schemas + [("other::Widget", [("value", "i64")], [])]), + ("integer-for-pointer", instructions("NEW_STRUCT tuple>\nPUSH_CONST 42\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple>\nPOP"), singleton_schema("ptr")), + ("wrong-pointer-kind", instructions("NEW_STRUCT tuple>\nPUSH_CONST 1\nALLOC i64\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple>\nPOP"), singleton_schema("ptr")), + ] + enum_control_schemas = singleton_schema("Generic") + singleton_schema("Result") + enum_control = instructions("NEW_STRUCT tuple>\nPUSH_CONST 91\n" + "NEW_VARIANT Generic::Some 1 Generic i64\nSET_FIELD 0\n" + "NEW_ARRAY_LITERAL 1 tuple>\nPUSH_CONST 0\nGET_INDEX\nGET_FIELD 0\n" + "UNWRAP_VARIANT 1 Generic i64\nCALL println 1\n" + "NEW_STRUCT tuple>\nNEW_VARIANT Generic::None 0 Generic void\nSET_FIELD 0\n" + "NEW_ARRAY_LITERAL 1 tuple>\nPUSH_CONST 0\nGET_INDEX\nGET_FIELD 0\n" + "IS_VARIANT Generic::None Generic void\nCALL println 1") + builtin_enum_control = instructions( + "NEW_STRUCT tuple>\nPUSH_CONST_STR word\n" + "INTEROP_CALL intrinsic convert.try_to_i32 1 Result\nSET_FIELD 0\n" + "NEW_ARRAY_LITERAL 1 tuple>\nPUSH_CONST 0\nGET_INDEX\nGET_FIELD 0\n" + "IS_VARIANT Result::Error Result text\nCALL println 1") + legacy_wrapper = instructions("PUSH_CONST_STR word\n" + "INTEROP_CALL intrinsic convert.try_to_i32 1 i64\nRET") + legacy_control = instructions("NEW_STRUCT tuple>\nCALL legacy_convert 0\n" + "SET_FIELD 0\nNEW_ARRAY_LITERAL 1 tuple>\n" + "PUSH_CONST 0\nGET_INDEX\nGET_FIELD 0\n" + "IS_VARIANT Result::Error Result text\nCALL println 1") + + with tempfile.TemporaryDirectory(prefix="nil-tuple-array-wire-") as directory: + root = Path(directory) + + def run(command): + return subprocess.run([str(value) for value in command], cwd=root, + env=environment, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=60) + + def success(result, output=None): + assert result.returncode == 0 and not result.stderr, result + assert output is None or result.stdout == output, result + + def source(name, body, schemas, binary, extra_functions=()): + path = root / (name + (".binary.nil" if binary else ".text.nil")) + path.write_bytes(encode(body, schemas, binary, extra_functions)) + return path + + def native(path, name, output): + nonlocal checks + obj, executable = root / (name + ".o"), root / name + success(run([paths["assembler"], "-o", obj, path])) + success(run([paths["linker"], "--runtime", paths["runtime"], + "-o", executable, obj])) + success(run([executable]), output) + checks += 1 + + for binary in (False, True): + path = source("valid", control, SCHEMAS, binary) + success(run([paths["interpreter"], "--no-ai", path]), expected) + checks += 1 + gc_path = source("initializer-gc", gc_control, nested_schemas, binary) + success(run([paths["interpreter"], "--no-ai", gc_path]), "73\n") + checks += 1 + enum_path = source("enum-values", enum_control + builtin_enum_control, + enum_control_schemas, binary) + success(run([paths["interpreter"], "--no-ai", enum_path]), "91\n1\n1\n") + checks += 1 + for annotations in (["@intrinsic(\"convert.try_to_i32\")"], + ["@intrinsic(\"convert.try_to_i64\")"], []): + legacy_path = source("legacy-wrapper", legacy_control, + singleton_schema("Result"), binary, + [("legacy_convert", "Result", annotations, legacy_wrapper)]) + result = run([paths["interpreter"], "--no-ai", legacy_path]) + if annotations == ["@intrinsic(\"convert.try_to_i32\")"]: + success(result, "1\n") + else: + assert result.returncode > 0 and not result.stdout and "tuple" in result.stderr, result + checks += 1 + if args.llvm == "ON": + native(path, "valid", expected) + native(gc_path, "initializer-gc", "73\n") + # Native builtins are lowered through annotated wrappers; the + # source fixtures cover that route. This raw direct instruction + # exercises only the VM's intrinsic result metadata boundary. + native(source("generic-enum-values", enum_control, + enum_control_schemas, binary), "enum-values", "91\n1\n") + identity = nominal_tuple + instructions( + "NEW_ARRAY_LITERAL 1 tuple\nCAST array>\n" + "PUSH_CONST 0\nGET_INDEX\nGET_FIELD 0\nGET_FIELD value\nCALL println 1") + native(source("identity", identity, nominal_schemas, binary), "identity", "73\n") + for name, body, schemas in invalid: + path = source(name, body, schemas, binary) + result = run([paths["interpreter"], "--no-ai", path]) + assert result.returncode > 0 and not result.stdout, (name, result) + assert "tuple" in result.stderr.lower() or "array intrinsic" in result.stderr, (name, result) + checks += 1 + if args.llvm == "ON": + obj = root / "protected.o" + sentinel = b"preserve existing object\n" + obj.write_bytes(sentinel) + result = run([paths["assembler"], "-o", obj, path]) + assert result.returncode > 0 and not result.stdout, (name, result) + assert obj.read_bytes() == sentinel, name + checks += 1 + if args.llvm == "ON": + cast = nominal_tuple + instructions( + "NEW_ARRAY_LITERAL 1 tuple\nCAST array>\nPOP") + path = source("cross-case-cast", cast, nominal_schemas, binary) + result = run([paths["assembler"], "-o", root / "cast.o", path]) + assert result.returncode > 0 and "only exact compatible handle casts" in result.stderr, result + checks += 1 + for name, body in [ + ("empty-get", instructions(f"NEW_ARRAY_LITERAL 0 {PAIR}\nPUSH_CONST 0\nGET_INDEX\nPOP")), + ("negative-get", construct + instructions(f"NEW_ARRAY_LITERAL 1 {PAIR}\nPUSH_CONST -1\nGET_INDEX\nPOP")), + ("intrinsic-get", construct + instructions(f"NEW_ARRAY_LITERAL 1 {PAIR}\nPUSH_CONST 5\n" + f"INTEROP_CALL intrinsic array.get 2 {PAIR} {PAIR}\nPOP")), + ]: + path = source(name, body, SCHEMAS, binary) + result = run([paths["interpreter"], "--no-ai", path]) + assert result.returncode > 0 and not result.stdout and "tuple array read" in result.stderr, result + checks += 1 + if args.llvm == "ON": + obj, executable = root / "bounds.o", root / "bounds" + success(run([paths["assembler"], "-o", obj, path])) + success(run([paths["linker"], "--runtime", paths["runtime"], "-o", executable, obj])) + result = run([executable]) + assert result.returncode > 0 and not result.stdout and "tuple array read" in result.stderr, result + checks += 1 + print(f"tuple array NIL contract: {checks} checks passed") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/tools/tuple_contract.py b/tests/tools/tuple_contract.py index a322d763..ecb889db 100644 --- a/tests/tools/tuple_contract.py +++ b/tests/tools/tuple_contract.py @@ -122,6 +122,11 @@ def run(command, status=0): 'repeat for each (a,b,c) in [(1,2)]\nsay a\nend repeat', 'arity'), ('named-loop-arity', 'let items = [(1,2)]\nfor (a,b,c) in items\nprintln(a)\nend for', 'value items is [(1,2)]\nrepeat for each (a,b,c) in items\nsay a\nend repeat', 'arity'), + ('duplicate-loop', 'for (same,same) in [(1,2)]\nprintln(same)\nend for', + 'repeat for each (same,same) in [(1,2)]\nsay same\nend repeat', 'already declared'), + ('array-wildcard-alias', 'let unknown = []\nlet items: array<(i32,text)> = unknown', + 'value unknown is []\nvalue items as array of tuple of (override integer,text) is unknown', + 'Type mismatch'), ] for name, ny, matrix, message in invalid: for language, body in [('ny', ny), ('matrix', matrix)]: @@ -170,46 +175,101 @@ def run(command, status=0): assert output.read_bytes() == b'unchanged' checks += 1 - # Tuple-array iteration uses typed field projection in the interpreter; - # native aggregate-array support remains a separate, explicit boundary. + # Every typed array expression uses index-based iteration. Exercise the + # same generated suite through the interpreter, bundles, JIT and AOT. for language in ('ny', 'matrix'): - for name, values, bindings, prints, expected in [ - ('pair', '[(1,"a"),(2,"b")]', '(amount,label)', - ['amount', 'label'], '1\na\n2\nb\n'), - ('singleton', '[(1,),(2,)]', '(amount,)', ['amount'], '1\n2\n'), - ]: - for named in (False, True): - iterable = 'items' if named else values - if language == 'ny': - declaration = f'let items = {values}\n' if named else '' - body = declaration + f'for {bindings} in {iterable}\n' - body += ''.join(f'println({value})\n' for value in prints) - source = 'fn main() -> i32\n' + body + 'end for\nreturn 0\nend fn\n' - else: - declaration = f'value items is {values}\n' if named else '' - body = declaration + f'repeat for each {bindings} in {iterable}\n' - body += ''.join(f'say {value}\n' for value in prints) - source = ('book tuple_loop\nmain returns override integer begin paragraph\n' + - body + 'end repeat\ngive 0\nend paragraph\n') - path = root / f'loop-{name}-{named}.{language}' - path.write_text(source) - artifact = root / 'loop.nil' - run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '-o', artifact, path]) - result = run([interpreter, '--no-ai', artifact]) - assert result.stdout == expected and not result.stderr, result - assert '__ritual_tuple_get' not in artifact.read_text() - checks += 1 - if args.llvm == 'ON': - # A direct construction isolates the layout boundary from the - # separately unsupported generic native iterator fallback. - path = root / 'tuple-array.ny' - path.write_text('fn main() -> i32\nlet items = [(1,"a"),(2,"b")]\nreturn 0\nend fn\n') - output = root / 'tuple-array.native' - output.write_bytes(b'keep previous executable') - result = run([compiler, '--quiet', '--no-stdlib', '--native', '-o', output, path], 1) - assert "array element type 'tuple<" in result.stderr.lower(), result.stderr - assert output.read_bytes() == b'keep previous executable' - checks += 1 + ny = language == 'ny' + declarations = ['let mut calls: i32 = 0\n' if ny else + 'book tuple_loops\nvariable calls as override integer is 0\n'] + body, expected = [], [] + cases = [ + ('pairs', '[(1,"a"),(2,"b")]', '(amount,label)', + ['amount', 'label'], ['1', 'a', '2', 'b'], + '(i32,text)', 'tuple of (override integer,text)'), + ('singles', '[(3,),(4,)]', '(amount,)', ['amount'], ['3', '4'], + '(i32,)', 'tuple of (override integer)'), + ('whole', '[(5,"c"),(6,"d")]', 'item', ['item.0', 'item.1'], + ['5', 'c', '6', 'd'], '(i32,text)', 'tuple of (override integer,text)'), + ('wildcards', '[(7,8,9),(10,11,12)]', '(_,amount,_)', ['amount'], + ['8', '11'], '(i32,i32,i32)', + 'tuple of (override integer,override integer,override integer)'), + ('scalars', '[13,14]', 'amount', ['amount'], ['13', '14'], + 'i32', 'override integer'), + ] + for name, values, bindings, prints, output, ny_type, matrix_type in cases: + factory = 'make_' + name + declarations.append( + f'fn {factory}() -> array<{ny_type}>\ncalls = calls + 1\n' + f'return {values}\nend fn\n' if ny else + f'{factory} returns array of {matrix_type} begin paragraph\n' + f'set calls to calls plus 1\ngive {values}\nend paragraph\n') + for mode in ('direct', 'named', 'call'): + if mode == 'named': + body.append(f'let {name} = {values}\n' if ny else + f'value {name} is {values}\n') + iterable = (values if mode == 'direct' else name if mode == 'named' else + factory + ('()' if ny else ' with nothing')) + body.append(f'for {bindings} in {iterable}\n' if ny else + f'repeat for each {bindings} in {iterable}\n') + body.extend(f'println({value})\n' if ny else f'say {value}\n' for value in prints) + body.append('end for\n' if ny else 'end repeat\n') + expected.extend(output) + # A call returning an array is evaluated once per loop, including + # singleton tuple destructuring and ordinary tuple value bindings. + body.append('println(calls)\n' if ny else 'say calls\n') + expected.append(str(len(cases))) + body.append( + 'let items = [(15,"outer")]\n' + 'for items in items\nprintln(items.0)\nend for\n' + 'for (items,_) in items\nprintln(items)\nend for\n' + 'println(items[0].0)\n' + 'let mut source = [(16,),(17,)]\n' + 'for (amount,) in source\nsource = [(90,),(91,)]\n' + 'println(amount)\nend for\n' + 'for (amount,label) in [(1,"first"),(2,"skip"),(3,"third"),(4,"stop")]\n' + 'if amount == 2 then\ncontinue\nend if\n' + 'if amount == 4 then\nbreak\nend if\n' + 'let amount = amount + 100\nprintln(amount)\nprintln(label)\nend for\n' + if ny else + 'value items is [(15,"outer")]\n' + 'repeat for each items in items\nsay items.0\nend repeat\n' + 'repeat for each (items,_) in items\nsay items\nend repeat\n' + 'say (items at 0).0\n' + 'variable source is [(16,),(17,)]\n' + 'repeat for each (amount,) in source\nset source to [(90,),(91,)]\n' + 'say amount\nend repeat\n' + 'repeat for each (amount,label) in [(1,"first"),(2,"skip"),(3,"third"),(4,"stop")]\n' + 'when amount equals 2 then\ncontinue repeating\nend when\n' + 'when amount equals 4 then\nstop repeating\nend when\n' + 'value amount is amount plus 100\nsay amount\nsay label\nend repeat\n') + expected.extend(['15', '15', '15', '16', '17', '101', 'first', '103', 'third']) + source = root / ('typed-loops.' + language) + source.write_text(''.join(declarations) + + ('fn main() -> i32\n' if ny else + 'main returns override integer begin paragraph\n') + ''.join(body) + + ('return 0\nend fn\n' if ny else 'give 0\nend paragraph\n')) + stdout = source.with_suffix('.stdout') + stdout.write_text('\n'.join(expected) + '\n') + run([sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, '--source', source, + '--expected-stdout', stdout, '--expected-exit', '0', + '--compiler-arg=--no-stdlib', '--routes', + 'all' if args.llvm == 'ON' else + 'text-interpreter,binary-interpreter,bundle-text,bundle-binary', + '--work-dir', root / ('typed-loops-' + language), '--strict']) + checks += 6 if args.llvm == 'ON' else 4 + # Unchecked mode must preserve exact array/tuple metadata too. + for encoding, flags in [('text', []), ('binary', ['--emit-binary-nil']), + *([('native', ['--native'])] if args.llvm == 'ON' else [])]: + artifact = root / ('typed-loops-' + language + '-' + encoding) + run([compiler, '--quiet', '--no-stdlib', '--no-typecheck', '--no-bundle', + *flags, '-o', artifact, source]) + result = run([artifact] if encoding == 'native' else [interpreter, '--no-ai', artifact]) + assert result.stdout == stdout.read_text() and not result.stderr, result + if encoding == 'text': + nil = artifact.read_text() + assert '__ritual_iter' not in nil and '__ritual_tuple_get' not in nil, nil + checks += 1 print(f'tuple contract: {checks} checks passed')