diff --git a/CMakeLists.txt b/CMakeLists.txt index 9f391d39..97abfc03 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -88,6 +88,12 @@ if(BUILD_TESTING) target_compile_features(ny_class_vm_tests PRIVATE cxx_std_17) add_test(NAME nil.class-contract COMMAND $) + add_executable(nil_binding_reference_contract_tests tests/binding_reference_contract_tests.cpp) + target_link_libraries(nil_binding_reference_contract_tests PRIVATE nilcompiler_core) + target_compile_features(nil_binding_reference_contract_tests PRIVATE cxx_std_17) + add_test(NAME nil.binding-reference-contract COMMAND $) + set_tests_properties(nil.binding-reference-contract PROPERTIES LABELS "nil;references;rc" TIMEOUT 30) + add_executable(ny_context_manifest_tests tests/context_manifest_tests.cpp) target_link_libraries(ny_context_manifest_tests PRIVATE nilcompiler_core) target_compile_features(ny_context_manifest_tests PRIVATE cxx_std_17) @@ -1119,6 +1125,11 @@ if(BUILD_TESTING) --compiler $ --interpreter $ --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --llvm "${NIL_ENABLE_LLVM}") set_tests_properties(matrix.named-arguments PROPERTIES LABELS "matrix;analysis;routes" TIMEOUT 120) + add_test(NAME matrix.parameters + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/matrix/parameter_contract.py" + --compiler $ --interpreter $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(matrix.parameters PROPERTIES LABELS "matrix;analysis;routes;references" TIMEOUT 240) add_test(NAME nil.reflection-consumer COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/reflection_contract.py" --compiler $ --interpreter $ diff --git a/docs/advanced/nil-format.md b/docs/advanced/nil-format.md index 295b6b08..a720bf44 100644 --- a/docs/advanced/nil-format.md +++ b/docs/advanced/nil-format.md @@ -271,6 +271,11 @@ reference semantics. `ref` and aggregate-only `REF_LOCAL` preserve that object identity across calls, returns, fields, and local aliases. They are not raw pointer reinterpretations, scalar stack references, or a borrow/lifetime checker. Recursive layouts and references to unsupported targets fail closed. +Explicit scalar/text binding-reference parameters use a separate compiler-owned +cell schema and nonescaping call contract described in +[NIL-0019](../design/NIL-0019-binding-reference-parameters.md). They reuse typed +record field operations and pass a cell handle to another checked reference +parameter; they do not reinterpret `REF_LOCAL` as a raw scalar stack address. Native construction checks intersect initialized fields across control-flow paths. An object must be fully initialized before a read, local store, call, return, or other escape; one branch's stores cannot prove another branch safe. diff --git a/docs/design/NIL-0019-binding-reference-parameters.md b/docs/design/NIL-0019-binding-reference-parameters.md new file mode 100644 index 00000000..8982d71c --- /dev/null +++ b/docs/design/NIL-0019-binding-reference-parameters.md @@ -0,0 +1,135 @@ +# NIL-0019: Explicit binding-reference parameters + +- **Status:** Accepted; initial scalar/text implementation +- **Scope:** Ny and Matrix parameter syntax, shared checking and NIL lowering, + VM/native execution, source tooling + +## Decision + +Parameter declarations distinguish an immutable local binding, a mutable local +binding, and a reference to the caller's binding. Both languages accept `mut` +and `mutable` for callee-local assignment, and `ref` and `reference` for +caller-binding parameters. Matrix also retains `variable` as a compatibility +alias for local mutability. The caller passes an ordinary value to a locally +mutable parameter. + +Caller-binding mutation requires a separate modifier at both ends of the call: + +| Operation | Ny | Matrix | +| --- | --- | --- | +| Mutable local parameter | `mut amount: i64` | `mutable amount as number` | +| Caller-binding parameter | `ref amount: i64` | `reference amount as number` | +| Explicit binding argument | `update(ref total)` | `update with amount being reference to total` | + +These examples use the canonical display spellings: short forms in Ny and long +forms in Matrix. Either spelling works in either language without changing its +grammar. Ny accepts `update(reference total)`; Matrix accepts +`update with amount being ref to total`, retaining its `to` keyword. The aliases +also apply to existing uses such as Ny `let mutable`, Matrix `on mut receiver`, +Ny `reference`, and Matrix `ref to Record`. + +All four spellings are reserved keywords in both languages. Existing bindings +named `mutable` or `reference` in Ny, or `mut` or `ref` in Matrix, must be renamed +or, in Matrix, written as escaped identifiers. + +The parameter's source type remains its scalar/text value type. Assigning the +parameter updates the referenced binding; reading or returning the parameter +produces its value. A reference parameter can forward the same binding to +another reference parameter with the explicit argument syntax. + +Writes are immediate. Passing one binding to multiple parameters creates +aliases to the same storage, and a later read observes earlier writes. A fault +does not undo completed writes. Copy-back on normal return would obscure both +aliasing and fault behavior, so it is not the contract. + +## Initial checked profile + +The supported value types are exactly `i32`, `i64`, `u8`, `bool`, `f64`, and +`text`, including their ordinary frontend aliases. Parameter and target types +must match exactly: reference passing does not apply numeric promotion or +create a converted temporary. + +Targets are mutable local bindings, mutable by-value parameters, or existing +reference parameters. Immutable bindings, globals, fields, indexed elements, +temporary expressions, and unsupported value types are rejected. References +cannot be stored as values, returned, captured, or inserted into aggregates. +Returning the referenced scalar/text value is allowed. + +Reference parameters are restricted to ordinary non-generic named functions. +Methods, anonymous functions, function values, foreign/intrinsic boundaries, +defaulted reference parameters, and variadic reference parameters are outside +the initial profile. These exclusions are checked, including before emission +when ordinary type checking is disabled. + +Matrix's `and` parameter separator recognizes optional `more` and parameter-mode +modifiers before the next `name as type` sequence. `more mutable` remains a +callee-local variadic binding; `more reference` is rejected. A receiver's +existing `on mutable receiver` clause is unchanged. + +## Relationship to object references + +`ref` in Ny and `reference to Record` in Matrix preserve shared object +identity. Rebinding a local holding an object handle does not redirect its +existing aliases. That behavior is unchanged. + +The new mode is expressed before a parameter's name, not in its value type: +`reference amount as number` addresses a caller binding, whereas +`amount as reference to Record` accepts an object handle. It does not create +first-class scalar reference types or provide a general borrow checker. + +## Lowering and lifetime + +The compiler represents each addressed lexical binding with a private typed +cell whose sole field is `value`. The reserved schema name is +`$nil.binding.cell.T`, marked `@nil_binding_cell`; a lowered reference parameter +has the NIL type `ref<$nil.binding.cell.T>`. Existing typed record creation, +field access, and direct-call instructions carry the implementation. + +Cell identity follows the compiler's lexical storage slot. Shadowed source +names remain separate bindings. Addressing the same binding twice uses the +same cell, and forwarding an existing reference passes that cell without +copying or scheduling a later write-back. Cell initialization occurs before +user operations that access the addressed binding. + +The VM uses its shared record storage. Native cells live within the creating +function's stack frame. A shared NIL validation pass constrains their schemas, +uses, direct calls, and escape paths before execution or native lowering. +The synchronous, nonescaping calling contract keeps the owning frame alive +until all callees using its cells return. The internal representation is not +a public FFI layout or user-constructible reference type. + +## Tooling + +Source signatures display `mutable` or `reference` in Matrix and `mut` or +`ref` in Ny, regardless of the spelling used in source. The `nil.signature.v1` +parameter records add boolean `mutable` and `reference` fields; clients that +read older compiler output may treat +those fields as absent. The value type is still the source scalar/text type. + +Source debug metadata maps an addressed name to its cell slot using the +internal `binding_ref` marker. Source inspection unwraps the cell's `value` +and exposes type `T`, so locals, watches, evaluation, and DAP present the +program's binding. Instruction-only inspection retains its existing storage +view. The lightweight language server and TextMate grammar recognize the +parameter modifiers independently of compiler analysis. + +## Validation scope + +Qualification covers both frontends and the shared VM/native execution paths: +local mutability, all supported reference value types, exact-type rejection, +forwarding, repeated aliases, recursion, lexical shadowing, and writes observed +after faults. Invalid escape and declaration forms must fail before replacing +an output artifact, including with `--no-typecheck`. + +Text operations and array reads assigned through reference parameters are +covered on all execution routes, including unmanaged native execution. +Ordinary callbacks can coexist with reference parameters on the existing +VM and bundle routes; this feature does not add native indirect-call support. +Reference arguments still require direct calls, including in serialized NIL. + +Source-import consumers must retain parameter modes across the Ny/Matrix +boundary. Serialized NIL validation must reject forged cell schemas and +escaping uses. Editor checks cover modifier completion, parameter locations, +highlighting, signature labels, and source debugger values. These are the +acceptance requirements for the profile; the existence of this record alone +does not establish a passing test run or broader reference support. diff --git a/docs/design/README.md b/docs/design/README.md index 75381e67..4964e6ac 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -41,6 +41,7 @@ not assigned architecture identifiers. | NIL-0015 | [Structural tuples](NIL-0015-structural-tuples.md) | Implemented nonempty typed values and local destructuring | | NIL-0016 | [Shared text patterns and collected queries](NIL-0016-patterns-and-queries.md) | Implemented initial byte-pattern and eager array-query profiles | | NIL-0017 | [Versioned NILData and one shared value model](NIL-0017-nildata.md) | Implemented initial bounded document profile | +| NIL-0019 | [Explicit binding-reference parameters](NIL-0019-binding-reference-parameters.md) | Accepted; initial scalar/text implementation | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/language-reference/functions.md b/docs/language-reference/functions.md index 53011c5d..1f363101 100644 --- a/docs/language-reference/functions.md +++ b/docs/language-reference/functions.md @@ -46,14 +46,15 @@ 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, -slices, unsupported scalar widths, and recursive layouts remain fail-closed in +they are not references to the caller's variable binding. The explicit scalar +binding-reference parameter mode below has a separate, nonescaping contract. +Slices, unsupported scalar widths, and recursive layouts remain fail-closed in the native backend. ### Mutable parameters -`mut` makes the callee's local parameter binding mutable. It does not mutate an -ordinary scalar variable in the caller. +`mut` or `mutable` makes the callee's local parameter binding mutable. It does +not mutate an ordinary scalar variable in the caller. ```ny fn increment_local(mut value: i32) -> i32 @@ -66,13 +67,87 @@ let incremented = increment_local(original) # original is 5; incremented is 6 ``` +Matrix accepts `mutable` and `mut`; the existing `variable` spelling remains +an alias in parameter declarations. Ordinary Matrix local declarations still +use `variable`; Ny local declarations accept `let mut` and `let mutable`. + +```matrix +increment-local receives mutable amount as number returns number begin paragraph + set amount to amount plus 1 + give amount +end paragraph +``` + +Use either commas or `and` between parameter declarations. Modifiers remain +part of the following parameter, as in `receives initial as number and mutable +amount as number`. A variadic mutable binding uses `more mutable values as number`. + An aggregate parameter or `ref` shares object identity with its caller; field mutations are visible through aliases, while rebinding the parameter -does not redirect the caller's binding. Scalar `ref` creation is rejected. +does not redirect the caller's binding. These shared handles do not carry borrowing or lifetime proofs. Explicit [owned buffers](../advanced/owned-buffers.md) have a separate checked local ownership/borrowing contract; owners and loans cannot be function parameters. +### Reference parameters + +`ref` or `reference` before a parameter name allows the function to update the +caller's binding. Both languages accept both spellings. The call must +explicitly identify the binding too: Ny accepts `ref total` or `reference total`, +and Matrix accepts `reference to total` or `ref to total`. The aliases keep each +language's surrounding syntax unchanged. + +```ny +fn increment(ref amount: i64) + amount = amount + 1 +end fn + +fn main() -> i32 + let mut total: i64 = 5 + increment(ref total) + println(total) # 6 + return 0 +end fn +``` + +```matrix +increment receives reference amount as number begin paragraph + set amount to amount plus 1 +end paragraph + +main returns number begin paragraph + variable total as number is 5 + evaluate increment with amount being reference to total + say total !!! 6 + give 0 +end paragraph +``` + +The initial profile supports `i32`, `i64`, `u8`, `bool`, `f64`, and `text`. +The target must be a mutable local or mutable parameter of exactly the declared +type. A reference parameter can forward its binding using the same explicit +call syntax. Passing an immutable value, global, field, indexed element, +temporary, or a numerically convertible but different type is rejected. + +Writes take effect immediately. Two reference arguments naming the same local +observe the same storage, and a write remains visible if a later operation +raises a fault. This is not copy-in/copy-out or a transaction. Reading or +returning `amount` produces its scalar/text value; the binding reference itself +cannot be saved, returned, captured, or placed in a collection or field. + +Reference parameters currently belong to ordinary non-generic named functions. +Methods, anonymous functions, function values, foreign/intrinsic boundaries, +defaulted reference parameters, and variadic reference parameters are rejected. +`amount as reference to Record` remains the existing shared object-handle type; +it does not acquire the caller-binding behavior of `reference amount as number`. +See [NIL-0019](../design/NIL-0019-binding-reference-parameters.md) for the +representation and scope of this parameter mode. + +The aliases also apply to existing reference types: Ny accepts +`ref` / `reference`, and Matrix accepts +`reference to Record` / `ref to Record`. Signature help uses Ny's short forms +and Matrix's long forms regardless of which alias appears in the declaration. + ### Default parameters Default expressions are retained in the syntax tree, but omitted arguments are diff --git a/docs/language-reference/lexical-structure.md b/docs/language-reference/lexical-structure.md index a89c91e9..12b0a238 100644 --- a/docs/language-reference/lexical-structure.md +++ b/docs/language-reference/lexical-structure.md @@ -24,7 +24,8 @@ Examples: `x`, `myFunction`, `counter_1`, `_private` |---------|-------------| | `fn` | Function declaration | | `let` | Immutable variable | -| `mut` | Mutable variable | +| `mut`, `mutable` | Mutable binding modifier | +| `ref`, `reference` | Reference type, expression, or parameter modifier | | `const` | Constant | | `if` | Conditional | | `else` | Alternative branch | diff --git a/docs/language-reference/types.md b/docs/language-reference/types.md index 58798290..bffc5ca8 100644 --- a/docs/language-reference/types.md +++ b/docs/language-reference/types.md @@ -154,21 +154,35 @@ default. Native nested structs and `ref` use the same shared object-handle behavior as the interpreter. Updating an object through a field or reference is visible through its other aliases. This is not by-value C struct layout, -automatic ownership, or Rust-style borrowing. Scalar references and recursive -layouts are not implemented. Source `ref value` accepts only a local or +automatic ownership, or Rust-style borrowing. Recursive layouts remain +unsupported. Outside an explicit binding-reference call argument, source +`ref value` accepts only a local or parameter with a nominal struct/class type (including a concrete generic struct). It creates an alias to that object, not to the variable's storage: rebinding the original local does not redirect an existing reference. Use `alias.field` and `alias.method()` directly. Explicit `*alias` reads/writes are rejected for `ref`; dereference syntax belongs to raw `ptr` operations. -Scalar, array, enum, function, raw-pointer, erased `any`, nested-reference, +General scalar, array, enum, function, raw-pointer, erased `any`, nested-reference, global and temporary/field-expression reference creation fail semantic checking. Emitted reference operations still require proof with `--no-typecheck`; diagnostic continuation cannot generate the unsupported operation. Uninstantiated generic bodies may not reach generation. Declaration-only `ref` types and generic constraints do not imply an executable borrow/lifetime contract. +[Reference parameters](functions.md#reference-parameters) provide a separate +scalar/text calling convention: `fn update(ref amount: i64)` accepts an explicit +`update(ref total)` argument naming an exactly typed mutable local or parameter. +The callee reads and writes the caller's binding, and can forward it during the +synchronous call. This mode does not introduce first-class `ref` values: +the reference cannot be stored, returned, or captured. Existing `ref` +object identity and rebinding behavior are unchanged. + +`reference` is an alias for `ref` in Ny, including `reference` types, +`reference value` expressions, and reference parameter declarations. Matrix +likewise accepts `ref` for `reference`, retaining its `ref to Record` type and +`ref to value` expression grammar. + ### Classes Non-generic concrete classes support instance methods, inherited fields and diff --git a/matrix/MATRIX-GUIDE.md b/matrix/MATRIX-GUIDE.md index 39569609..d3bf1e28 100644 --- a/matrix/MATRIX-GUIDE.md +++ b/matrix/MATRIX-GUIDE.md @@ -246,6 +246,21 @@ hyphens and underscores. Unknown, duplicate and missing labels are errors. Argument expressions are lowered in parameter order; a `more` tail follows the fixed parameters of a variadic paragraph. +Parameters are immutable unless their declaration says otherwise. +`receives mutable amount as number` lets the paragraph reassign its local copy; +`mut` is the short spelling, and `variable` remains an alias in this position. +To change the caller's binding, declare `receives reference amount as number` and call it +with `amount being reference to total`. `ref` can replace `reference` in both +places: `receives ref amount as number` and `amount being ref to total`. +Here `total` must be a mutable local or parameter of exactly the same type. +Writes are immediate, including before a +later fault, and the reference cannot escape the call. This initial mode +supports scalar/text parameters on ordinary non-generic named paragraphs; +see the [complete parameter contract](../docs/language-reference/functions.md#reference-parameters). +An existing `reference to Record` type still denotes a shared object handle. +It also accepts the short spelling `ref to Record`. Both spellings are +case-insensitive in Matrix. + An immutable local paragraph value retains parameter names from its declared paragraph, anonymous paragraph or immutable local initializer. Function-typed parameters, mutable callbacks and other values without a checked name contract diff --git a/matrix/README.md b/matrix/README.md index 6788bf0e..9b10594e 100644 --- a/matrix/README.md +++ b/matrix/README.md @@ -53,11 +53,11 @@ construct. Matrix keeps `[` `]` for array literals, `(` `)` for grouping, `,` for list separation, `.` for member access and `::` for path qualification. Everything else is a word. -**2. One canonical phrasing per construct.** The temptation with a -natural-language surface is to accept synonyms — `returns`, `gives`, `yields`. -Synonyms make the grammar ambiguous, make diffs unstable, and make two agents -produce two spellings of one program. Matrix's naturalness comes from word -*order*, not from vocabulary breadth. There is one spelling for each thing. +**2. One canonical phrasing per construct.** Matrix's naturalness comes from +word *order*, rather than a broad vocabulary of alternative grammatical forms. +Documentation and signature help use canonical spellings. The shared +`mut`/`mutable` and `ref`/`reference` aliases map to the same tokens in both +languages while preserving each language's word order and punctuation. **3. A word is reused when the relation is the same, not when the word is free.** `.` is already multi-context in Ny — member access, decimal point, @@ -117,6 +117,43 @@ trait objects, generic classes, postfix `?` or overload sets, because NIL cannot execute them today. Matrix gains those spellings when the runtime gains the capability, not before. +## Parameter modes + +Ordinary parameters are immutable bindings inside the paragraph. Prefix a +parameter with `mutable` to reassign its local value, or `reference` to update +the caller's binding explicitly: + +```matrix +increment-local receives mutable amount as number returns number begin paragraph + set amount to amount plus 1 + give amount +end paragraph + +increment receives reference amount as number begin paragraph + set amount to amount plus 1 +end paragraph + +main returns number begin paragraph + variable total as number is 5 + say increment-local with amount being total !!! 6; total is still 5 + evaluate increment with amount being reference to total + say total !!! 6 + give 0 +end paragraph +``` + +Both languages accept `mut`/`mutable` and `ref`/`reference`. Matrix keeps the +`to` in reference expressions, so `ref to total` is the short form above; +Ny writes `ref total` or `reference total`. Matrix's `variable` remains an +alias for `mutable` in a parameter header. Reference parameters initially +support exact scalar/text types on ordinary non-generic +named paragraphs, with mutable locals or parameters as their targets. Writes +are immediate, aliases share the binding, and references cannot escape the +call. Existing `reference to Record` types still refer to shared objects. +See the [function reference](../docs/language-reference/functions.md#parameters) +and [NIL-0019](../docs/design/NIL-0019-binding-reference-parameters.md) for the +supported modes and their limits. + ## Why this language, beyond syntax Matrix is intended to become a language for both AI agents and humans, including @@ -381,8 +418,9 @@ feedback or a two-pass scan, diagnostics get harder to word, and the structural anchoring described above is exactly what would be given up. The surviving ambiguity is documented rather than hidden: in a parameter -header, `and` requires two tokens of lookahead (`and as`) to distinguish -a further parameter from a boolean operand inside a parameter default. Matrix +header, `and` uses bounded lookahead through optional `more` and parameter-mode +modifiers to find ` as`. This distinguishes a further parameter from a +boolean operand inside a parameter default. Matrix therefore restricts parameter defaults to literal atoms. Since Ny retains default expressions in the syntax tree but **rejects omitted arguments at the call site**, this costs nothing today. diff --git a/matrix/docs/grammar.ebnf b/matrix/docs/grammar.ebnf index ead59506..2ce7b179 100644 --- a/matrix/docs/grammar.ebnf +++ b/matrix/docs/grammar.ebnf @@ -11,9 +11,9 @@ * lowercase is canonical, but 'BEGIN CHOICE' and 'Begin Choice' are the same * token pair. Folding is ASCII-only (see the lexical section). * - * Design constraint: the grammar is LL(1) except at the two places marked - * LL(2), both of which are consequences of accepting the draft's 'and' - * between parameter declarations. See README.md. + * Parameter separators use bounded lookahead past optional modifiers to + * distinguish 'and [more] [mode] identifier as' from a type/default clause. + * See README.md. *) (* ------------------------------------------------------------------ *) @@ -106,18 +106,26 @@ paragraph_decl = { modifier } identifier [ generic_clause ] [ 'returns' type ] [ 'begin' 'paragraph' { statement } 'end' 'paragraph' ] ; -receiver_clause = 'on' [ 'mutable' ] 'receiver' - | 'on' 'reference' +mutable_keyword = 'mutable' | 'mut' ; +reference_keyword = 'reference' | 'ref' ; +receiver_clause = 'on' [ mutable_keyword ] 'receiver' + | 'on' reference_keyword | 'without' 'receiver' ; (* associated function: no 'my' *) -(* LL(2): after a complete 'name as type', an 'and' is a further parameter - * only when followed by 'identifier as'. Parameter defaults are therefore +(* After a complete parameter, an 'and' starts a further parameter only when + * followed by '[more] [mode] identifier as'. Parameter defaults are therefore * restricted to literal atoms, so no parameter can end in a boolean - * expression. *) -param_list = param { ( ',' | 'and' ) param } - | 'more' identifier 'as' type ; -param = [ 'variable' ] identifier 'as' type + * expression. 'more' must be final. 'mutable' and legacy 'variable' allow + * callee-local assignment. 'reference' aliases the caller's binding and + * requires an explicit 'reference to name' argument of exactly the same type. + * Reference mode is checked only for ordinary non-generic named paragraphs + * with scalar/text parameters; defaults, variadics, methods, anonymous + * paragraphs and paragraph values cannot carry it. It is not the existing + * 'name as reference to Record' object-handle type. *) +param_list = param { ( ',' | 'and' ) param } ; +param = [ 'more' ] [ parameter_mode ] identifier 'as' type [ 'defaulting' 'to' ( literal | signed_number | ( 'negative' | 'minus' ) unary ) ] ; +parameter_mode = mutable_keyword | 'variable' | reference_keyword ; generic_clause = 'of' generic_param { ',' generic_param } ; (* Several bounds are joined with 'and'. A bound is a type name, so 'and @@ -194,7 +202,7 @@ type = ergonomic_type | 'shared' 'view' 'of' type | 'exclusive' 'view' 'of' type | 'pointer' 'to' type - | 'reference' 'to' type + | reference_keyword 'to' type | nominal_type ; (* TIER ONE: what a program says unless it has a reason not to. Width, @@ -367,7 +375,7 @@ primary = literal | '(' expression ')' | '(' expression ',' [ expression { ',' expression } [ ',' ] ] ')' | 'build' nominal_type [ 'with' field_init { ',' field_init } ] - | 'reference' 'to' identifier + | reference_keyword 'to' identifier | 'apply' identifier 'across' expression | 'now' 'in' 'milliseconds' | when_expr diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 07a0c86a..c68decdf 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -2017,6 +2017,82 @@ native rejection of mismatched layouts with checking disabled. This supplies emission context; it does not replace the remaining enum payload validation work recorded in F62. +### F75 — Parameter mutability needs a discoverable local and caller-binding distinction + +**Observation:** Writing Matrix by hand exposed a discoverability problem: +ordinary parameters are immutable, and the existing `variable` parameter +modifier was easy to miss. Reassigning a callee's local parameter and changing +the caller's variable are separate operations that need separate spellings. + +**Decision and implementation:** `mutable amount as number` enables local +reassignment; `variable amount as number` remains compatible. Caller writes use +`reference amount as number` and an explicit `amount being reference to total` +argument. Ny keeps `mut amount: i64` and adds `ref amount: i64` with `ref total` +at the call. Both frontends share checking, typed cells, and direct-call +lowering. The parameter remains a scalar/text value in source inspection. + +Both languages accept the short and long spellings `mut` / `mutable` and +`ref` / `reference`. This keeps familiar abbreviations available while allowing +the prose forms in Ny as well. Each language retains its grammar: Ny accepts +`update(reference total)` and Matrix accepts `update with ref to total`. +Signature help uses canonical Ny short forms and Matrix long forms, regardless +of the source spelling. Existing reference types and receiver clauses accept +the same aliases. + +The parser and editor tooling also recognize modifiers after the `and` +parameter separator and combined `more mutable` / `more variable` prefixes. +Signature help exposes the selected mode, and debugger source inspection +unwraps internal cells instead of showing implementation storage. +Variadic signature labels also preserve each language's modifier order +(`mut ..rest` in Ny, `more mutable rest` in Matrix) and show the declared +element type rather than the array collected inside the function. Existing +signature type metadata continues to describe that collected array. + +**Initial boundary:** References accept exactly typed mutable locals/parameters +for `i32`, `i64`, `u8`, `bool`, `f64`, and `text`. Forwarding and repeated aliases +share immediate writes, including writes before a fault. References cannot +escape the synchronous call. Methods, anonymous functions, function values, +generic functions, defaults, variadics, foreign/intrinsic calls, aggregate +reference targets, globals, fields, and indexed targets are rejected. Existing +object-handle reference semantics remain unchanged. + +**Next-version work:** Evaluate broader addressable places and callable forms +only with explicit lifetime, aliasing, and ABI rules. Do not infer support from +a parsed reference type or relax the current checked boundary. The detailed +decision and acceptance scope are in +[NIL-0019](../../docs/design/NIL-0019-binding-reference-parameters.md). + +### F76 — An imported type alias can override a local callable during Matrix lowering + +**Status: Unresolved; pre-existing behavior.** Importing a Ny function-type alias +named `Callback` and declaring a Matrix local named `callback` creates a folded +name collision. The local initializer is emitted correctly, but a later call +can resolve to the imported type alias instead of the local callable: + +```matrix +read Callback from parameter_callbacks +!!! parameter_callbacks declares: pub type Callback = fn(i64) -> i64 +!!! Inside a paragraph, with an ordinary number-to-number paragraph in scope: +value callback is the paragraph ordinary +say callback with total +``` + +**Confirmed evidence:** A control program with no reference parameters emits +`PUSH_FN_PTR reference_callbacks__ordinary` followed by `STORE_LOCAL callback`, +then incorrectly emits `CALL reference_callbacks__parameter_callbacks__Callback 1` +for the source call. The reference-parameter compatibility probe exposed this +through the stricter NIL provenance check's unknown-callee diagnostic, but the +incorrect call target is also present in the control program. + +**Workaround:** Rename the local callable to a name that does not fold to the +imported alias, such as `operation`. That spelling passes the parameter +compatibility fixture. The binding-reference change does not fix the underlying +resolution defect. + +**Required follow-up:** Preserve the checker's lexical value binding when +lowering calls, rather than allowing the imported type-alias map to replace it. +Cover folded case/separator collisions, local shadowing, source imports, and +binary-library imports in both analysis and executable-call regressions. ## NILData migration — 2026-10-26 diff --git a/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index 35b6dd3b..d0186820 100644 --- a/matrix/docs/ny-surface-inventory.md +++ b/matrix/docs/ny-surface-inventory.md @@ -132,7 +132,7 @@ about whether a value changed representation. | `allocate(2)` | `allocate values as pointer to integer sized 2` | executed | | `deallocate(p)` | `release values` | executed | | `ref` | `reference to ` | executed, shared object handle | -| `ref value` | `reference to value` | executed; nominal struct/class locals and parameters only | +| `ref value` | `reference to value` | shared object handles for nominal struct/class locals and parameters; explicit scalar/text binding-reference call arguments have the separate contract in §6 | | `*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 | @@ -231,27 +231,29 @@ unguarded `otherwise` and one value-producing expression per arm, as Ny does. | Ny | Matrix | Route state | | --- | --- | --- | -| `fn f(a: i32) -> i32 ... end fn` | `f receives a as integer returns integer begin function ... end function` | executed | -| `fn f(m: text)` (void) | `f receives m as text begin function ... end function` | executed | -| `fn f() -> i32` | `f returns integer begin function ... end function` | executed | +| `fn f(a: i32) -> i32 ... end fn` | `f receives a as override integer returns override integer begin paragraph ... end paragraph` | executed | +| `fn f(m: text)` (void) | `f receives m as text begin paragraph ... end paragraph` | executed | +| `fn f() -> i32` | `f returns override integer begin paragraph ... end paragraph` | executed | | `f(1, 2)` | `f with a being 1, b being 2` | executed | | `f()` | `f with nothing` | executed | -| `mut value: i32` parameter | `variable value as integer` parameter | executed, callee-local | -| `..values: i32` variadic | `receives more values as integer` | executed for `integer` | +| `mut amount: i32` / `mutable amount: i32` parameter | `mutable amount as override integer` / `mut amount as override integer`; `variable` remains an alias | callee-local mutation | +| `ref amount: i64` / `reference amount: i64` parameter | `reference amount as number` / `ref amount as number` parameter | explicit caller-binding mutation; ordinary non-generic named functions, exact scalar/text types only | +| `f(ref total)` / `f(reference total)` | `f with amount being reference to total` / `f with amount being ref to total` | mutable local/parameter target; immediate writes and forwarding, no escaping binding reference | +| `..values: i32` variadic | `receives more values as override integer` | executed for `override integer` | | default parameter expressions | `defaulting to ` | **parsed; omitted arguments rejected** | | `fn square(x) -> i32 => x * x` | no spelling | not implemented in Ny | | overload sets | **no spelling** | duplicate names produce duplicate NIL labels | -| named function value | `the function f` | executed on interpreted routes | -| noncapturing lambda | `anonymous receives ... begin function ... end function` | executed on interpreted routes | +| named function value | `the paragraph f` | executed on interpreted routes; reference-parameter functions cannot become values | +| noncapturing lambda | `anonymous receives ... begin paragraph ... end paragraph` | executed on interpreted routes; reference parameters rejected | | capturing closure | **no spelling** | rejected in Ny | `returns` terminates the parameter list. Omitting `returns` means `returns nothing`. In a parameter header `and` is accepted in place of `,` -because each item has the fixed shape ` as `: +because each item has the fixed shape `[more] [mode] as `: ```text -add_two receives left as integer and right as integer returns integer begin function -add_two receives left as integer, right as integer returns integer begin function +add-two receives left as number and mutable right as number returns number begin paragraph +add-two receives left as number, mutable right as number returns number begin paragraph ``` Both are the same declaration. Named call arguments lower to positional NIL @@ -259,6 +261,15 @@ arguments in declaration order; because Ny has no overload resolution, argument names are checked against the single declaration and are never used to select between candidates. +`mutable` allows reassignment of the callee's parameter binding. `reference` +allows writes to the caller's mutable local or parameter, and the call must +say `reference to name`. Binding-reference parameters support `i32`, `i64`, +`u8`, `bool`, `f64`, and `text`; they reject defaults, variadics, generic +functions, methods, anonymous paragraphs, and function-value use. Reusing one +target for two arguments aliases the same binding. Writes remain visible after +a later fault, and only the referenced value can be returned or stored. +See [NIL-0019](../../docs/design/NIL-0019-binding-reference-parameters.md). + --- ## 7. Records and choices diff --git a/matrix/samples/04-paragraphs.matrix b/matrix/samples/04-paragraphs.matrix index eee6152a..d6153cef 100644 --- a/matrix/samples/04-paragraphs.matrix +++ b/matrix/samples/04-paragraphs.matrix @@ -35,7 +35,8 @@ end paragraph !!! A mutable parameter is the callee's own binding. It does not mutate the !!! caller's scalar, exactly as Ny's "mut" parameter does not. -increment_local receives variable amount as number returns number begin paragraph +!!! The older "variable amount" spelling remains a parameter alias. +increment_local receives mutable amount as number returns number begin paragraph set amount to amount plus 1 give amount end paragraph diff --git a/nilcompiler/src/analysis.cpp b/nilcompiler/src/analysis.cpp index 529f5936..b791bac9 100644 --- a/nilcompiler/src/analysis.cpp +++ b/nilcompiler/src/analysis.cpp @@ -566,13 +566,22 @@ std::string analysis_session::signature_json() const { if (matrix::nil_symbol(written) == name) name = written; } const auto type = surface(parameter.type); - const std::string parameter_label = (parameter.variadic ? (matrix_language ? "more " : "..") : "") + - name + (matrix_language ? " as " : ": ") + type; + auto declared_type = parameter.type; + if (parameter.variadic && declared_type.rfind("array<", 0) == 0 && + declared_type.size() > 7 && declared_type.back() == '>') + declared_type = declared_type.substr(6, declared_type.size() - 7); + const std::string mode = parameter.binding_reference ? (matrix_language ? "reference " : "ref ") : + parameter.mutable_binding ? (matrix_language ? "mutable " : "mut ") : ""; + const std::string variadic = parameter.variadic ? (matrix_language ? "more " : "..") : ""; + const std::string parameter_label = (matrix_language ? variadic + mode : mode + variadic) + + name + (matrix_language ? " as " : ": ") + surface(declared_type); if (index) { label += ", "; parameters += ','; } label += parameter_label; parameters += "{\"name\":" + quoted(static_cast(name)) + ",\"type\":" + quoted(type) + ",\"label\":" + quoted(parameter_label) + ",\"variadic\":" + - (parameter.variadic ? "true" : "false") + '}'; + (parameter.variadic ? "true" : "false") + ",\"mutable\":" + + (parameter.mutable_binding ? "true" : "false") + ",\"reference\":" + + (parameter.binding_reference ? "true" : "false") + '}'; } const auto return_type = surface(query.return_type); label += (matrix_language ? " returns " : ") -> ") + return_type; diff --git a/nilcompiler/src/ast.hpp b/nilcompiler/src/ast.hpp index c981a636..cb4b5f4f 100644 --- a/nilcompiler/src/ast.hpp +++ b/nilcompiler/src/ast.hpp @@ -351,6 +351,9 @@ struct ast_expr : public ast_node { // primitive stack reference. Only successful semantic checking grants this // proof, and any semantic error invalidates it before diagnostic continuation. bool checked_reference_handle = false; + // A direct argument borrowing a mutable caller binding. This proof is + // separate from an ordinary ref aggregate handle and cannot escape a call. + bool checked_binding_reference = false; // Affine ownership proof. This is erased when any semantic check fails. bool checked_ownership = false; std::optional checked_callable_parameters; @@ -426,6 +429,8 @@ struct ast_param { bool is_mut = false; // optional mut marker for variable params (e.g., for mut x) bool is_variadic = false; // true for rest/varargs params (e.g., ..args: T) + bool is_ref = false; // aliases the caller's binding for this synchronous call + bool checked_binding_reference = false; int line = 0; std::optional> default_value; // default parameter expression diff --git a/nilcompiler/src/binding_reference.hpp b/nilcompiler/src/binding_reference.hpp new file mode 100644 index 00000000..d5dc8a6e --- /dev/null +++ b/nilcompiler/src/binding_reference.hpp @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2008 - 2026 Execute Software. All rights reserved. + * SPDX-License-Identifier: MIT + */ +#ifndef NIL_BINDING_REFERENCE_HPP +#define NIL_BINDING_REFERENCE_HPP + +#include +#include +#include +#include + +namespace ny { +inline constexpr const char *nil_binding_cell_prefix = "$nil.binding.cell."; + +inline std::string compact_binding_type(std::string type) { + type.erase(std::remove_if(type.begin(), type.end(), + [](unsigned char c) { return std::isspace(c) != 0; }), type.end()); + return type; +} + +inline bool is_binding_scalar_type(const std::string &type) { + return type == "i32" || type == "i64" || type == "u8" || type == "bool" || + type == "f64" || type == "text"; +} + +inline bool contains_binding_cell_type(const std::string &type) { + return compact_binding_type(type).find(nil_binding_cell_prefix) != std::string::npos; +} + +inline std::optional binding_cell_value_type(const std::string &raw) { + const auto type = compact_binding_type(raw); + const std::string prefix = nil_binding_cell_prefix; + if (type.rfind(prefix, 0) != 0) return std::nullopt; + const auto value = type.substr(prefix.size()); + return is_binding_scalar_type(value) ? std::optional(value) : std::nullopt; +} + +inline std::optional binding_reference_value_type(const std::string &raw) { + const auto type = compact_binding_type(raw); + if (type.rfind("ref<", 0) != 0 || type.back() != '>') return std::nullopt; + return binding_cell_value_type(type.substr(4, type.size() - 5)); +} +} // namespace ny +#endif diff --git a/nilcompiler/src/class_contract.cpp b/nilcompiler/src/class_contract.cpp index a3d6acd0..ce0085ca 100644 --- a/nilcompiler/src/class_contract.cpp +++ b/nilcompiler/src/class_contract.cpp @@ -121,6 +121,9 @@ void validate_nil_class_contract(const nil_module &module) { for (const auto &instruction : function.body) if (instruction.opname == "CLASS_UPCAST" || instruction.opname == "CALL_METHOD") invalid("class instructions require explicit class metadata"); + // Binding-reference cells use the same CFG provenance engine even when + // the program declares no classes. + validate_nil_class_provenance(module); return; } std::unordered_map functions; diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index 92880967..fb49871e 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -5,6 +5,7 @@ */ #include "codegen.hpp" #include "array_intrinsic.hpp" +#include "binding_reference.hpp" #include "inline_asm.hpp" #include "diagnostics.hpp" #include "nil_contract.hpp" @@ -374,6 +375,23 @@ static std::vector specialization_type_arguments( return parsed->type_args; } +// Binding references are a calling convention, not a new source value type. +// The reserved schema name cannot collide with a Ny/Matrix declaration. Its +// handle is only exposed to another checked reference parameter; the source +// binding continues to have the field's scalar type. +static std::string binding_cell_name(const std::string &type) { + return std::string(nil_binding_cell_prefix) + canonical_nil_type_name(type); +} + +static std::optional +binding_parameter_type(const std::string &type) { + return binding_reference_value_type(canonical_nil_type_name(type)); +} + +static bool supported_binding_scalar(const std::string &type) { + return is_binding_scalar_type(type); +} + static bool append_serialized_nil_parameter( nil_function &function, const ast_param ¶meter, const std::map &substitutions = {}, @@ -389,10 +407,144 @@ static bool append_serialized_nil_parameter( type = substitute_nil_type_name(type, substitutions); if (type.empty()) return false; + if (parameter.is_ref && !parameter.checked_binding_reference) + return false; + if (parameter.is_ref) + type = "ref<" + binding_cell_name(type) + ">"; function.params.push_back(parameter.name + ": " + type); return true; } +// Use lexical NIL slots rather than source spellings: two nested declarations +// called "amount" must never share storage. Every reference marker is collected +// before any access is rewritten, including markers in a later branch. Cells +// are initialized once per invocation, so two arguments addressing one binding +// share it immediately and forwarding a reference never performs copy-back. +static void lower_binding_references(nil_module &module) { + struct cell_binding { + std::string type; + std::string storage; + bool reference_parameter = false; + bool value_parameter = false; + }; + for (auto &function : module.functions) { + std::map cells; + std::set parameters; + for (const auto ¶meter : function.params) { + const auto colon = parameter.find(':'); + if (colon == std::string::npos) continue; + const auto name = parameter.substr(0, colon); + parameters.insert(name); + if (const auto type = binding_parameter_type(parameter.substr(colon + 1))) + cells.emplace(name, cell_binding{*type, name, true, false}); + } + for (const auto &instruction : function.body) { + if (instruction.opname != "BINDING_REF_LOCAL") continue; + if (instruction.args.size() != 2) + throw std::runtime_error("Invalid internal binding-reference marker"); + auto [where, inserted] = cells.emplace(instruction.args[0], + cell_binding{instruction.args[1], {}, false, + parameters.count(instruction.args[0]) != 0}); + if (!inserted && where->second.type != instruction.args[1]) + throw std::runtime_error("Binding reference has conflicting storage types"); + } + if (cells.empty()) continue; + std::size_t next_storage = 0; + for (auto &[slot, cell] : cells) { + if (!supported_binding_scalar(cell.type)) + throw std::runtime_error("Binding reference requires i32, i64, u8, bool, f64, or text"); + if (!cell.reference_parameter) + cell.storage = "$nil.binding.storage." + std::to_string(next_storage++); + const auto schema_name = binding_cell_name(cell.type); + const auto existing = std::find_if(module.structs.begin(), module.structs.end(), + [&](const auto &schema) { return schema.name == schema_name; }); + if (existing == module.structs.end()) + module.structs.push_back({schema_name, {{"value", cell.type}}, {"@nil_binding_cell"}}); + else if (existing->fields != std::vector>{{"value", cell.type}}) + throw std::runtime_error("Conflicting internal binding-reference schema"); + } + + const auto parameter_count = function.params.size(); + if (function.body.size() < parameter_count) + throw std::runtime_error("Binding-reference function lacks its parameter prologue"); + for (std::size_t index = 0; index < parameter_count; ++index) { + const auto ¶meter = function.params[parameter_count - index - 1]; + const auto name = parameter.substr(0, parameter.find(':')); + const auto &instruction = function.body[index]; + if (instruction.opname != "STORE_LOCAL" || instruction.args != std::vector{name}) + throw std::runtime_error("Binding-reference function has an invalid parameter prologue"); + } + + std::vector body; + const auto append = [&](const nil_instruction &original, const std::string &op, + std::vector args) { + auto generated = original; + generated.opname = op; + generated.args = std::move(args); + body.push_back(std::move(generated)); + }; + for (std::size_t index = 0; index < parameter_count; ++index) + body.push_back(function.body[index]); + // No user statement is attributed to the compiler's storage setup. The + // original parameter slots remain valid until each cell is initialized. + nil_instruction setup; + setup.source_file = function.source_file; + for (const auto &[slot, cell] : cells) { + if (cell.reference_parameter) continue; + append(setup, "NEW_STRUCT", {binding_cell_name(cell.type)}); + if (cell.value_parameter) { + append(setup, "LOAD_LOCAL", {slot}); + } else if (cell.type == "text") { + const std::string empty = "$nil.binding.empty-text"; + if (std::none_of(module.string_constants.begin(), module.string_constants.end(), + [&](const auto &entry) { return entry.first == empty; })) + module.string_constants.emplace_back(empty, ""); + append(setup, "PUSH_CONST_STR", {empty}); + } else { + append(setup, "PUSH_CONST", {cell.type == "f64" ? "0.0" : "0"}); + } + if (cell.type != "text") append(setup, "CAST", {cell.type}); + append(setup, "SET_FIELD", {"value"}); + append(setup, "STORE_LOCAL", {cell.storage}); + } + + std::size_t scratch = 0; + for (std::size_t index = parameter_count; index < function.body.size(); ++index) { + auto instruction = function.body[index]; + for (auto &debug : instruction.debug_locals) { + const auto cell = cells.find(debug.storage); + if (cell == cells.end()) continue; + debug.storage = cell->second.storage; + debug.type = "binding_ref<" + cell->second.type + ">"; + } + const auto cell = instruction.args.empty() ? cells.end() : cells.find(instruction.args[0]); + if (instruction.opname == "BINDING_REF_LOCAL") { + if (cell == cells.end()) + throw std::runtime_error("Binding reference has no storage cell"); + append(instruction, cell->second.reference_parameter ? "LOAD_LOCAL" : "REF_LOCAL", + {cell->second.storage}); + } else if (instruction.opname == "LOAD_LOCAL" && cell != cells.end()) { + append(instruction, "LOAD_LOCAL", {cell->second.storage}); + append(instruction, "GET_FIELD", {"value"}); + } else if (instruction.opname == "STORE_LOCAL" && cell != cells.end()) { + const auto temporary = "$nil.binding.value." + std::to_string(scratch++); + // Re-establish the checked source storage type even when the ordinary + // producer (for example an array index) has no precise CFG category. + // CAST preserves text identity and cannot erase cell provenance. + append(instruction, "CAST", {cell->second.type}); + append(instruction, "STORE_LOCAL", {temporary}); + append(instruction, "LOAD_LOCAL", {cell->second.storage}); + append(instruction, "LOAD_LOCAL", {temporary}); + append(instruction, "SET_FIELD", {"value"}); + append(instruction, "STORE_LOCAL", {cell->second.storage}); + } else { + body.push_back(std::move(instruction)); + } + } + function.body = std::move(body); + } +} + static std::string canonical_builtin_enum_base(std::string base_name) { const std::size_t separator = base_name.rfind("::"); const std::size_t leaf_start = @@ -1089,7 +1241,8 @@ class emitter { "bind the value to a local before taking its reference"); return; } - if (!expression.checked_reference_handle) { + if (!expression.checked_reference_handle && + !expression.checked_binding_reference) { cg_.reject_codegen_construct( expression.line, "reference creation requires a checked aggregate handle", @@ -1107,6 +1260,21 @@ class emitter { "bind the aggregate value to a local before taking its reference"); return; } + if (expression.checked_binding_reference) { + const auto type = substitute_nil_type_name( + operand->inferred_type.value_or(""), substitutions); + if (!supported_binding_scalar(type)) { + cg_.reject_codegen_construct(expression.line, + "binding reference requires an exact supported scalar type", + "use i32, i64, u8, bool, f64, or text"); + return; + } + // This compiler-only marker is removed after lexical slots have been + // assigned throughout the function. That pass sees references inside + // branches before rewriting the declaration and every earlier access. + push_instr("BINDING_REF_LOCAL", {identifier.name, type}, expression.line); + return; + } push_instr("REF_LOCAL", {identifier.name}, expression.line); } @@ -5245,6 +5413,7 @@ class emitter { instruction.opname == "STORE_LOCAL" || instruction.opname == "OWN_BIND" || instruction.opname == "OWN_MOVE" || + instruction.opname == "BINDING_REF_LOCAL" || instruction.opname == "REF_LOCAL") && !instruction.args.empty()) { const auto binding = local_bindings.find(instruction.args.front()); if (binding != local_bindings.end()) @@ -6900,6 +7069,10 @@ codegen::assemble_module(const ast_program &program, } try { + lower_binding_references(*mod); + if (std::any_of(mod->structs.begin(), mod->structs.end(), + [](const auto &schema) { return binding_cell_value_type(schema.name).has_value(); })) + validate_nil_class_contract(*mod); validate_nil_parallel_contract(*mod); validate_nil_owned_contract(*mod); } catch (const std::exception &error) { diff --git a/nilcompiler/src/lexer.cpp b/nilcompiler/src/lexer.cpp index c79facfe..02d8ecc5 100644 --- a/nilcompiler/src/lexer.cpp +++ b/nilcompiler/src/lexer.cpp @@ -382,7 +382,7 @@ token lexer::identifier() { kind = token_kind::loop_kw; else if (text == "do") kind = token_kind::do_kw; - else if (text == "mut") + else if (text == "mut" || text == "mutable") kind = token_kind::mut_kw; else if (text == "import") kind = token_kind::import_kw; @@ -422,7 +422,7 @@ token lexer::identifier() { kind = token_kind::allocate_kw; else if (text == "deallocate") kind = token_kind::deallocate_kw; - else if (text == "ref") + else if (text == "ref" || text == "reference") kind = token_kind::ref_kw; else if (text == "fn") kind = token_kind::fn_kw; diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index b3d1701e..a566cfc8 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -1,5 +1,6 @@ #include "llvm_backend.hpp" #include "array_intrinsic.hpp" +#include "binding_reference.hpp" #include "codegen.hpp" #include "concurrency_contract.hpp" #include "owned_contract.hpp" @@ -5192,7 +5193,17 @@ bool NativeCodegen::generateModule(const nil_module &mod) { const std::uint64_t allocation_size = std::max(1, type_size.getFixedValue()); llvm::Value *pointer = nullptr; - if (impl_->memory_mode == MemoryMode::SAFE_GC) { + if (binding_cell_value_type(definition->name)) { + // The shared NIL provenance validator proves that binding cells + // stay within the active call chain and are constructed once in + // the invocation prologue. Stack storage therefore has the exact + // lifetime required by both memory modes, with no hidden manual- + // mode allocation for the user to release. + auto &entry = impl_->current_function->getEntryBlock(); + llvm::IRBuilder<> storage(&entry, entry.begin()); + pointer = storage.CreateAlloca(layout_it->second.llvm_type, nullptr, + "nil.binding.cell"); + } else if (impl_->memory_mode == MemoryMode::SAFE_GC) { auto *runtime_type = llvm::FunctionType::get(llvm::PointerType::getUnqual(ctx), {llvm::Type::getInt64Ty(ctx)}, false); diff --git a/nilcompiler/src/matrix_lexer.cpp b/nilcompiler/src/matrix_lexer.cpp index 8ee689b8..693fccf6 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -74,8 +74,10 @@ const keyword_entry keyword_table[] = { // cannot rescue it ('a-b' is a different name). The receiver clauses are // spelled without it. {"on", kw::on, "on"}, - {"mutable", kw::mutable_, "mutable"}, {"without", kw::without, "without"}, - {"reference", kw::reference, "reference"}, {"my", kw::my, "my"}, + {"mutable", kw::mutable_, "mutable"}, {"mut", kw::mutable_, "mutable"}, + {"without", kw::without, "without"}, + {"reference", kw::reference, "reference"}, {"ref", kw::reference, "reference"}, + {"my", kw::my, "my"}, {"receives", kw::receives, "receives"}, {"returns", kw::returns, "returns"}, {"more", kw::more, "more"}, {"defaulting", kw::defaulting, "defaulting"}, {"anonymous", kw::anonymous, "anonymous"}, {"the", kw::the, "the"}, diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index 04d1dda4..c9be3183 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -821,8 +821,10 @@ parser::parse_parameters(std::vector &names) { const int line = peek().line; bool variadic = false; if (match(kw::more)) variadic = true; - // 'variable x as T' makes the callee's own binding mutable. - const bool mutable_binding = match(kw::variable); + // Mutable/variable change the callee's own binding; reference borrows the + // caller's binding and requires an explicit reference argument at the call. + const bool reference_binding = match(kw::reference); + const bool mutable_binding = reference_binding || match(kw::mutable_) || match(kw::variable); if (!peek().is_name()) { error(peek(), "expected a parameter name, found '" + peek().lexeme + "'", @@ -854,13 +856,20 @@ parser::parse_parameters(std::vector &names) { params.emplace_back(name, type, mutable_binding, line, default_value, variadic); params.back().name_span = name_span(name_token); + params.back().is_ref = reference_binding; names.push_back(name); if (variadic) break; // a variadic tail is final if (match(matrix::token_kind::comma)) continue; // 'and' separates parameter declarations only, where ' as ' // keeps it unambiguous. - if (check(kw::and_) && peek(2).is(kw::as)) { advance(); continue; } + if (check(kw::and_)) { + std::size_t next = 1; + if (peek(next).is(kw::more)) ++next; + if (peek(next).is(kw::mutable_) || peek(next).is(kw::variable) || + peek(next).is(kw::reference)) ++next; + if (peek(next).is_name() && peek(next + 1).is(kw::as)) { advance(); continue; } + } break; } return params; diff --git a/nilcompiler/src/nil_loader.cpp b/nilcompiler/src/nil_loader.cpp index b11d93e1..39b5ce23 100644 --- a/nilcompiler/src/nil_loader.cpp +++ b/nilcompiler/src/nil_loader.cpp @@ -1,5 +1,6 @@ #include "nil_loader.hpp" #include "nil_contract.hpp" +#include "binding_reference.hpp" #include "concurrency_contract.hpp" #include "owned_contract.hpp" #include "numeric_literal.hpp" @@ -545,16 +546,28 @@ struct fault_flow_state { std::map> initialized_fields; }; +static std::optional, std::string>> +fault_callable_signature(const std::string &raw); + bool class_sensitive_type(const std::string &raw, const nil_module &module) { std::unordered_set visited; - std::vector pending{raw}; + std::vector pending{compact_binding_type(raw)}; while (!pending.empty()) { auto type = pending.back(); pending.pop_back(); if (type.rfind("ref<", 0) == 0 && type.back() == '>') type = type.substr(4, type.size() - 5); if (!visited.insert(type).second) continue; + // Compiler-owned binding cells carry stack storage in native code. Use + // the existing exact-provenance CFG analysis for these handles too, so + // casts, unknown calls, globals, arrays and raw pointers cannot erase the + // bounded lifetime proven by their reference-parameter contract. + if (contains_binding_cell_type(type)) return true; if (find_nil_class(module, type)) return true; + if (const auto signature = fault_callable_signature(type)) { + pending.push_back(signature->second); + pending.insert(pending.end(), signature->first.begin(), signature->first.end()); + } for (const auto &schema : module.structs) if (schema.name == type) - for (const auto &field : schema.fields) pending.push_back(field.second); + for (const auto &field : schema.fields) pending.push_back(compact_binding_type(field.second)); } return false; } @@ -562,6 +575,10 @@ bool class_sensitive_type(const std::string &raw, const nil_module &module) { constexpr const char *unproven_class_value = "#class-unproven"; bool class_provenance_type(const std::string &type, const nil_module &module) { if (type == unproven_class_value) return true; + // An opaque cast of a callable must not disguise a class-returning target + // as a scalar callback, including through nested callable signatures. + if (type.rfind("#callable:", 0) == 0) + return class_sensitive_type(type.substr(10), module); if (!type.empty() && (type.front() == '@' || type.front() == '!')) { const auto marker = type.find('@'); if (marker != std::string::npos) return class_sensitive_type(type.substr(marker + 1), module); @@ -580,7 +597,57 @@ bool same_regions(const std::vector &a, return true; } +// Function values are VM strings at runtime, but their checked structural +// signature must survive this analysis. An ordinary callback in a function +// that also uses a binding reference still has its existing VM contract. +static std::optional, std::string>> +fault_callable_signature(const std::string &raw) { + const auto type = compact_binding_type(raw); + if (type.rfind("fn(", 0) != 0) return std::nullopt; + std::vector parameters; + std::size_t start = 3; + unsigned parentheses = 1, angles = 0; + for (std::size_t index = start; index < type.size(); ++index) { + const char c = type[index]; + if (c == '(') ++parentheses; + else if (c == ')') { + if (--parentheses != 0) continue; + if (index != start) parameters.push_back(type.substr(start, index - start)); + else if (!parameters.empty()) return std::nullopt; + if (type.substr(index + 1, 2) != "->" || index + 3 == type.size()) return std::nullopt; + return std::make_pair(std::move(parameters), type.substr(index + 3)); + } else if (c == '<') ++angles; + else if (c == '>' && index && type[index - 1] != '-' && angles) --angles; + else if (c == ',' && parentheses == 1 && angles == 0) { + if (index == start) return std::nullopt; + parameters.push_back(type.substr(start, index - start)); + start = index + 1; + } + } + return std::nullopt; +} + +static std::string fault_callable_type(const nil_function &function) { + std::string signature = "fn("; + for (const auto ¶meter : function.params) { + const auto colon = parameter.find(':'); + if (colon == std::string::npos) return "#text"; + if (signature.size() != 3) signature += ','; + signature += compact_binding_type(parameter.substr(colon + 1)); + } + signature += ")->" + compact_binding_type(function.return_type); + return fault_callable_signature(signature) ? "#callable:" + signature : "#text"; +} + std::string fault_stack_type(const std::string &type, const nil_module &module) { + if (contains_binding_cell_type(type)) { + const auto canonical = compact_binding_type(type); + for (const auto &schema : module.structs) + if (canonical == schema.name || canonical == "ref<" + schema.name + ">") + return "@" + canonical; + return unproven_class_value; + } + if (fault_callable_signature(type)) return "#callable:" + compact_binding_type(type); if (type == "i32" || type == "i64" || type == "u8" || type == "bool") return "#word"; if (type == "f64") return "#float"; if (type == "text") return "#text"; @@ -638,6 +705,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, if (!labels.count(args[0])) fail("jump target must exist in the owning function", pc); if (ops[pc] == Opcode::FAULT_RAISE || ops[pc] == Opcode::FAULT_MATCH || ops[pc] == Opcode::FAULT_BIND) { const auto &type = args.back(); + if (contains_binding_cell_type(type)) fail("binding-reference cells cannot be fault payloads", pc); if (find_nil_class(module, type)) fail("classes cannot be fault payloads", pc); if (type == "void" || type == "any" || type == "bool" || type == "i32" || type == "i64" || type == "u8" || type == "f64" || type == "text" || @@ -746,6 +814,14 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, const auto checked = fault_stack_type(expected, module); if ((class_type(checked) || class_type(actual)) && checked != actual) fail("class argument or storage requires its exact checked static view", pc); + if (checked.rfind("#callable:", 0) == 0 && checked != actual) + fail("callable argument or storage requires its exact checked signature", pc); + }; + const auto opaque_stack_type = [&](const std::string &raw) { + const auto type = fault_stack_type(raw, module); + if (type.rfind("#callable:", 0) == 0) + fail("opaque result metadata cannot establish a checked callable signature", pc); + return type; }; const auto exception_edge = [&](fault_flow_state exceptional) { if (exceptional.regions.empty()) return; @@ -807,8 +883,14 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, } case Opcode::PUSH_CONST: state.stack.push_back(is_floating_literal_spelling(args[0]) ? "#float" : "#word"); break; - case Opcode::PUSH_CONST_STR: case Opcode::PUSH_FN_PTR: + case Opcode::PUSH_CONST_STR: state.stack.push_back("#text"); break; + case Opcode::PUSH_FN_PTR: { + const auto target = std::find_if(module.functions.begin(), module.functions.end(), + [&](const auto &candidate) { return candidate.name == args[0]; }); + state.stack.push_back(target == module.functions.end() ? "#text" : fault_callable_type(*target)); + break; + } case Opcode::LOAD_LOCAL: { const auto local = state.locals.find(args[0]); state.stack.push_back(local == state.locals.end() ? "?" : local->second); break; @@ -825,10 +907,15 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, std::any_of(module.structs.begin(), module.structs.end(), [&](const auto &schema) { return schema.name == local->second.substr(1); })) state.stack.push_back("@ref<" + local->second.substr(1) + ">"); + else if (local != state.locals.end() && class_provenance_type(local->second, module)) + state.stack.push_back(unproven_class_value); else state.stack.push_back("?"); break; } - case Opcode::LOAD_GLOBAL: state.stack.push_back(args.size() == 2 ? fault_stack_type(args[1], module) : "?"); break; + case Opcode::LOAD_GLOBAL: { + const auto type = args.size() == 2 ? opaque_stack_type(args[1]) : "?"; + state.stack.push_back(type); break; + } case Opcode::STORE_GLOBAL: reject_class_operands(1); pop(1); break; case Opcode::POP: pop(1); break; @@ -857,7 +944,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, for (const auto &schema : module.structs) if (schema.name == owner.substr(1)) for (const auto &field : schema.fields) - if (field.first == args[0]) { field_type = fault_stack_type(field.second, module); known_field = true; } + if (field.first == args[0]) { field_type = opaque_stack_type(field.second); known_field = true; } if (class_type(owner) && !known_field) fail("class field read requires a declared field", pc); state.stack.push_back(field_type); break; } @@ -870,6 +957,9 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, bool known_field = false; for (const auto &schema : module.structs) if (schema.name == nominal) for (const auto &field : schema.fields) if (field.first == args[0]) { + if (binding_cell_value_type(nominal) && + fault_stack_type(field.second, module) != state.stack.back()) + fail("binding-reference cell write requires its exact scalar value category", pc); check_class_argument(field.second, state.stack.back()); known_field = true; } if ((class_type(owner) || class_type(state.stack.back())) && !known_field) @@ -911,13 +1001,34 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, if (args.size() == 3 && class_sensitive_type(args[2], module)) fail("enum payload metadata cannot fabricate class provenance", pc); pop(1); const auto count = args.empty() ? 0 : std::stoull(args[0]); - for (std::size_t i = 0; i < count; ++i) state.stack.push_back(args.size() == 3 ? fault_stack_type(args[2], module) : "?"); + for (std::size_t i = 0; i < count; ++i) state.stack.push_back(args.size() == 3 ? opaque_stack_type(args[2]) : "?"); break; } case Opcode::CALL: { exception_edge(state); const auto count = static_cast(std::stoull(args[1])); if (state.stack.size() < count) fail("call argument underflow", pc); + const auto local_callable = state.locals.find(args[0]); + if (local_callable != state.locals.end() && local_callable->second.rfind("#callable:", 0) == 0) { + const auto signature = fault_callable_signature(local_callable->second.substr(10)); + if (!signature || signature->first.size() != count) + fail("indirect call requires its exact callable signature and argument count", pc); + // Reference parameters deliberately require direct calls. A known + // ordinary callback signature can establish its result category but + // cannot authorize passing caller storage or class provenance. + reject_class_operands(count); + for (const auto &type : signature->first) + if (class_sensitive_type(type, module)) + fail("indirect calls cannot receive binding-reference or class storage", pc); + if (class_sensitive_type(signature->second, module)) + fail("indirect calls cannot return binding-reference or class storage", pc); + pop(count); + if (signature->second != "void") + state.stack.push_back(fault_stack_type(signature->second, module)); + break; + } + if (local_callable != state.locals.end()) + fail("indirect call lacks a checked callable signature", pc); const auto callee = std::find_if(module.functions.begin(), module.functions.end(), [&](const auto &fn) { return fn.name == args[0]; }); if (callee != module.functions.end()) { if (callee->return_type.empty() || callee->params.size() != count) @@ -932,12 +1043,34 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, } else reject_class_operands(count); pop(count); if (callee != module.functions.end()) { - if (callee->return_type != "void") state.stack.push_back(fault_stack_type(callee->return_type, module)); + if (callee->return_type != "void") { + const auto result_type = fault_stack_type(callee->return_type, module); + if (result_type.rfind("#callable:", 0) == 0 && + (callee->body.empty() || std::any_of(callee->annotations.begin(), callee->annotations.end(), + [](const auto &annotation) { + const auto dispatch = compact_binding_type(annotation); + return dispatch.rfind("@intrinsic", 0) == 0 || dispatch.rfind("@interop", 0) == 0 || + dispatch.rfind("@ritual", 0) == 0 || dispatch.rfind("@native", 0) == 0; + }))) + fail("external calls cannot establish a checked callable result", pc); + state.stack.push_back(result_type); + } } else if (args[0] == "println" || args[0] == "core__print" || args[0] == "console__writeln" || args[0] == "console__write" || args[0] == "console__sys_write" || args[0] == "array__push" || args[0] == "array__set") { // Historical adapters with a fixed void result. } else if (args[0] == "panic" || args[0] == "ny__lang__core__panic") terminal = true; + else if (args[0] == "String__substr" || args[0] == "String__substring" || + args[0] == "String__to_uppercase" || args[0] == "String__to_upper" || + args[0] == "String__to_lowercase" || args[0] == "String__to_lower" || + args[0] == "String__trim" || args[0] == "String__replace" || + args[0] == "core__to_string" || args[0] == "core__to_string_i64" || + args[0] == "core__to_string_f64") + state.stack.push_back("#text"); + else if (args[0] == "String__len" || args[0] == "String__length" || + args[0] == "String__contains" || args[0] == "String__starts_with" || + args[0] == "String__ends_with" || args[0] == "String__find") + state.stack.push_back("#word"); else if (args[0].rfind("__ritual_", 0) == 0 || args[0].rfind("String__", 0) == 0 || args[0].rfind("array__", 0) == 0 || args[0].rfind("core__to_string", 0) == 0) state.stack.push_back("?"); @@ -972,7 +1105,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, pop(static_cast(std::stoull(args[2]))); if (args.size() < 4) fail("interop in a fault-bearing function requires explicit result metadata", pc); if (class_sensitive_type(args[3], module)) fail("interop cannot synthesize class provenance", pc); - if (args[3] != "void") state.stack.push_back(fault_stack_type(args[3], module)); + if (args[3] != "void") state.stack.push_back(opaque_stack_type(args[3])); break; } case Opcode::INLINE_ASM: @@ -986,6 +1119,8 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, const auto target_type = fault_stack_type(args[0], module); if (class_type(source_type) || class_type(target_type)) fail("CAST cannot fabricate or erase class provenance; use CLASS_UPCAST", pc); + if (target_type.rfind("#callable:", 0) == 0 && source_type != target_type) + fail("CAST cannot fabricate or change a callable signature", pc); if (!target_type.empty() && target_type.front() == '@' && source_type != target_type) fail("cast cannot fabricate a concrete fault payload", pc); pop(1); state.stack.push_back(target_type); break; @@ -1012,7 +1147,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, case Opcode::LABEL: case Opcode::NOP: break; case Opcode::NEG: reject_class_operands(1); - pop(1); state.stack.push_back(args.empty() ? "?" : fault_stack_type(args[0], module)); break; + pop(1); state.stack.push_back(args.empty() ? "?" : opaque_stack_type(args[0])); break; case Opcode::MATH_SIN: case Opcode::MATH_COS: case Opcode::MATH_TAN: case Opcode::MATH_ASIN: case Opcode::MATH_ACOS: case Opcode::MATH_ATAN: case Opcode::MATH_SQRT: case Opcode::MATH_EXP: case Opcode::MATH_LOG: @@ -1029,7 +1164,7 @@ nil_fault_analysis analyze_fault_body(const nil_function &function, case Opcode::MOD: case Opcode::BIT_AND: case Opcode::BIT_OR: case Opcode::BIT_XOR: case Opcode::SHL: case Opcode::SHR: case Opcode::PTR_ADD: case Opcode::PTR_SUB: reject_class_operands(2); - pop(2); state.stack.push_back(args.empty() ? "?" : fault_stack_type(args[0], module)); break; + pop(2); state.stack.push_back(args.empty() ? "?" : opaque_stack_type(args[0])); break; case Opcode::COUNT: fail("invalid opcode", pc); break; } if (!terminal) enqueue(pc + 1, state, false, pc); @@ -1051,36 +1186,121 @@ void validate_nil_fault_contract(const nil_module &module) { void validate_nil_class_provenance(const nil_module &module) { std::unordered_set related; + const auto invalid_binding = [](const std::string &message) { + throw std::runtime_error("NIL binding-reference contract: " + message); + }; + std::set binding_schemas; + for (const auto &schema : module.structs) { + if (contains_binding_cell_type(schema.name)) { + const auto type = binding_cell_value_type(schema.name); + if (!type || compact_binding_type(schema.name) != schema.name || + schema.fields != std::vector>{{"value", *type}} || + std::find(schema.annotations.begin(), schema.annotations.end(), "@nil_binding_cell") == schema.annotations.end() || + !binding_schemas.insert(schema.name).second || find_nil_class(module, schema.name)) + invalid_binding("storage requires one exact compiler-owned scalar cell schema"); + related.insert(schema.name); + related.insert("ref<" + schema.name + ">"); + } + for (const auto &field : schema.fields) + if (contains_binding_cell_type(field.second)) + invalid_binding("a binding-reference cell cannot be stored in an aggregate field"); + } + for (const auto &enumeration : module.enums) + for (const auto &variant : enumeration.variants) + if (contains_binding_cell_type(variant.associated_type)) + invalid_binding("a binding-reference cell cannot be stored in an enum payload"); + for (const auto &klass : module.classes) + for (const auto &method : klass.methods) { + if (contains_binding_cell_type(method.receiver_type) || contains_binding_cell_type(method.return_type)) + invalid_binding("binding references are unavailable in virtual method signatures"); + for (const auto &type : method.parameter_types) + if (contains_binding_cell_type(type)) + invalid_binding("binding references are unavailable in virtual method signatures"); + } + std::set binding_callable_names; + for (const auto &function : module.functions) { + if (!binding_schemas.empty() && !binding_callable_names.insert(function.name).second) + invalid_binding("function names must be unambiguous when binding references are present"); + if (contains_binding_cell_type(function.return_type)) + invalid_binding("a function cannot return binding-reference storage"); + bool has_reference_parameter = false; + for (const auto ¶meter : function.params) { + const auto colon = parameter.find(':'); + const auto type = colon == std::string::npos ? std::string{} : compact_binding_type(parameter.substr(colon + 1)); + if (!contains_binding_cell_type(type)) continue; + const auto scalar = binding_reference_value_type(type); + if (!scalar || !binding_schemas.count(std::string(nil_binding_cell_prefix) + *scalar)) + invalid_binding("parameters require an exact ref scalar storage contract"); + has_reference_parameter = true; + } + if (has_reference_parameter) + for (const auto &annotation : function.annotations) { + const auto dispatch = compact_binding_type(annotation); + if (dispatch.rfind("@intrinsic", 0) == 0 || dispatch.rfind("@interop", 0) == 0 || + dispatch.rfind("@ritual", 0) == 0 || dispatch.rfind("@native", 0) == 0) + invalid_binding("binding references cannot cross an external or intrinsic boundary"); + } + // Native storage is one alloca per constructor. Re-entering a constructor + // in a loop would reuse its address while an earlier alias is still live. + // Compiler constructors occur in the straight-line invocation prologue. + bool in_prologue = true; + for (const auto &instruction : function.body) { + if (binding_schemas.empty() && + std::any_of(instruction.args.begin(), instruction.args.end(), + [](const auto &argument) { return contains_binding_cell_type(argument); })) + invalid_binding("binding-reference instructions require explicit cell schemas"); + if (instruction.opname == "LABEL" || instruction.opname == "JMP" || + instruction.opname == "JMP_IF" || instruction.opname == "JMP_IF_NOT" || + instruction.opname == "CALL" || instruction.opname == "CALL_METHOD" || + instruction.opname == "RET" || instruction.opname.rfind("FAULT_", 0) == 0) + in_prologue = false; + if (instruction.opname == "NEW_STRUCT" && !instruction.args.empty() && + contains_binding_cell_type(instruction.args[0]) && + (!in_prologue || !binding_schemas.count(instruction.args[0]))) + invalid_binding("cells must be constructed from an exact schema in the invocation prologue"); + } + } for (const auto &klass : module.classes) { related.insert(klass.name); related.insert("ref<" + klass.name + ">"); } + // Most modules have neither classes nor binding cells. Their ordinary call + // graphs need no provenance walk after the metadata checks above. + if (related.empty()) return; bool changed = true; while (changed) { changed = false; for (const auto &schema : module.structs) if (!related.count(schema.name) && std::any_of(schema.fields.begin(), schema.fields.end(), - [&](const auto &field) { return related.count(field.second) != 0; })) + [&](const auto &field) { + return related.count(compact_binding_type(field.second)) != 0 || + class_sensitive_type(field.second, module) || fault_callable_signature(field.second).has_value(); + })) changed = related.insert(schema.name).second || changed; } + const auto related_type = [&](const std::string &raw) { + const auto type = compact_binding_type(raw); + return related.count(type) != 0 || contains_binding_cell_type(type) || + fault_callable_signature(type).has_value(); + }; for (const auto &function : module.functions) { - bool relevant = related.count(function.return_type) != 0; + bool relevant = related_type(function.return_type); for (const auto ¶meter : function.params) { const auto colon = parameter.find(':'); const auto start = colon == std::string::npos ? std::string::npos : parameter.find_first_not_of(" \t", colon + 1); - if (start != std::string::npos && related.count(parameter.substr(start))) relevant = true; + if (start != std::string::npos && related_type(parameter.substr(start))) relevant = true; } for (const auto &instruction : function.body) { if (instruction.opname == "CLASS_UPCAST" || instruction.opname == "CALL_METHOD") relevant = true; for (const auto &argument : instruction.args) - if (related.count(argument)) relevant = true; - if (instruction.opname == "CALL" && !instruction.args.empty()) + if (related_type(argument)) relevant = true; + if ((instruction.opname == "CALL" || instruction.opname == "PUSH_FN_PTR") && !instruction.args.empty()) for (const auto &target : module.functions) if (target.name == instruction.args[0]) { - if (related.count(target.return_type)) relevant = true; + if (related_type(target.return_type)) relevant = true; for (const auto ¶meter : target.params) { const auto colon = parameter.find(':'); const auto start = colon == std::string::npos ? std::string::npos : parameter.find_first_not_of(" \t", colon + 1); - if (start != std::string::npos && related.count(parameter.substr(start))) relevant = true; + if (start != std::string::npos && related_type(parameter.substr(start))) relevant = true; } } } @@ -1107,6 +1327,7 @@ static void validate_fault_program(const std::vector &program, function = &module.functions.back(); function->name = instruction.args[0]; function->return_type = instruction.function_return_type; + function->annotations = instruction.function_annotations; for (std::size_t i = 0; i < instruction.function_param_count; ++i) function->params.push_back("arg" + std::to_string(i) + ":" + (i < instruction.function_parameter_types.size() ? instruction.function_parameter_types[i] : "any")); @@ -1141,6 +1362,7 @@ static void attach_class_metadata(std::vector &program, nil_module function = &metadata.functions.back(); function->name = instruction.args.at(0); function->return_type = instruction.function_return_type; + function->annotations = instruction.function_annotations; for (std::size_t i = 0; i < instruction.function_param_count; ++i) function->params.push_back("arg" + std::to_string(i) + ":" + (i < instruction.function_parameter_types.size() ? instruction.function_parameter_types[i] : "any")); @@ -1167,6 +1389,14 @@ void validate_nil_class_contract(const std::vector &program) { for (const auto &instruction : program) if (instruction.op == Opcode::CLASS_UPCAST || instruction.op == Opcode::CALL_METHOD) throw std::runtime_error("NIL class instructions require explicit module metadata"); + else { + for (const auto &argument : instruction.args) + if (contains_binding_cell_type(argument)) + throw std::runtime_error("NIL binding-reference instructions require explicit module metadata"); + for (const auto &type : instruction.function_parameter_types) + if (contains_binding_cell_type(type)) + throw std::runtime_error("NIL binding-reference parameters require explicit module metadata"); + } return; } auto declarations = *metadata; diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index cfe3e76b..9735322a 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -1398,7 +1398,8 @@ parser::parse_function_declaration(visibility_kind vis, bool is_abstract, while (true) { bool is_mut = false; bool is_variadic = false; - if (match(token_kind::mut_kw)) { + const bool is_ref = match(token_kind::ref_kw); + if (is_ref || match(token_kind::mut_kw)) { is_mut = true; } // Variadic rest parameter: ..name: type @@ -1420,6 +1421,7 @@ parser::parse_function_declaration(visibility_kind vis, bool is_abstract, param.line = p.line; param.is_mut = is_mut; param.is_variadic = is_variadic; + param.is_ref = is_ref; // Optional type annotation: support `param: type` (MVP) if (match(token_kind::colon)) { @@ -3111,6 +3113,8 @@ std::shared_ptr parser::parse_unary() { match(token_kind::tilde)) { auto op = previous(); auto right = parse_unary(); + if (op.kind == token_kind::ref_kw) + return std::make_shared(right, op.line); if (op.kind == token_kind::minus && right && right->kind == ast_node_kind::number_literal_node) { auto &number = static_cast(*right); diff --git a/nilcompiler/src/semantic_index.hpp b/nilcompiler/src/semantic_index.hpp index aac6aa81..f3b26591 100644 --- a/nilcompiler/src/semantic_index.hpp +++ b/nilcompiler/src/semantic_index.hpp @@ -48,6 +48,8 @@ struct signature_parameter { std::string name, type; bool variadic = false; std::optional span; + bool mutable_binding = false; + bool binding_reference = false; }; struct signature_result { bool available = false; diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 0b49b219..bc1094dc 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -571,6 +571,10 @@ bool type_checker::check(ast_program &program) { for (auto *value : checked_class_conversions_) value->checked_class_upcast.reset(); for (auto *value : checked_reference_handles_) value->checked_reference_handle = false; + for (auto *value : checked_binding_references_) + value->checked_binding_reference = false; + for (auto *parameter : checked_reference_parameters_) + parameter->checked_binding_reference = false; for (auto *call : checked_class_calls_) { call->concrete_class_receiver.reset(); call->class_method_owner.reset(); @@ -2863,6 +2867,7 @@ void type_checker::visit(ast_function_decl &p) { // Register parameters for (auto ¶m : p.params) { + param.checked_binding_reference = false; // Resolve canonical parameter type if a type annotation is provided. std::optional canonical_param_type = std::nullopt; if (param.type_name.has_value()) { @@ -2873,6 +2878,21 @@ void type_checker::visit(ast_function_decl &p) { } if (canonical_param_type) param.type_name = canonical_param_type; + if (param.is_ref) { + const auto errors_before = diagnostics_.size(); + if (!p.body || native_dispatch_annotations || current_class_name_ || + !p.generic_params.empty() || p.is_virtual || p.is_abstract || p.is_override) + add_error(param.line, "Reference parameters require an ordinary non-generic function body; methods and foreign dispatch are unavailable"); + if (param.is_variadic || param.default_value) + add_error(param.line, "Reference parameters cannot be variadic or have defaults"); + const auto type = canonical_param_type.value_or(""); + if (type != "i32" && type != "i64" && type != "u8" && type != "bool" && + type != "f64" && type != "String") + add_error(param.line, "Reference parameters currently support i32, i64, u8, bool, f64 and text bindings"); + param.is_mut = true; + param.checked_binding_reference = diagnostics_.size() == errors_before; + checked_reference_parameters_.push_back(¶m); + } // Preserve `is_mut` on parameter symbols so the symbol table accurately // reflects parameter mutability for later analysis. if (!symbols_.insert_symbol_with_context( @@ -4631,7 +4651,8 @@ void type_checker::capture_signature(const ast_call_expr &call, const symbol &bi for (std::size_t index = parameter_offset; index < binding.params.size(); ++index) { const auto ¶meter = binding.params[index]; result.parameters.push_back({parameter.name, parameter.type_name.value_or("any"), - parameter.is_variadic, parameter.name_span}); + parameter.is_variadic, parameter.name_span, parameter.is_mut, + parameter.is_ref}); } } else if (node.kind == ast_node_kind::variable_decl_node && binding.type_name && binding.checked_callable_parameters && !binding.is_mut) { @@ -4753,17 +4774,43 @@ void type_checker::visit(ast_call_expr &e) { e.class_instance_call = false; e.class_argument_types.clear(); const bool saved_class_call = checking_class_call_; + const auto *saved_direct_callee = direct_call_callee_; checking_class_call_ = true; + direct_call_callee_ = e.callee.get(); if (e.callee && !bounded_receiver) e.callee->accept(*this); checking_class_call_ = saved_class_call; + direct_call_callee_ = saved_direct_callee; const bool signature_eligible = signature_selected && diagnostics_.size() == signature_errors; + // A direct `ref local` argument can mean an object handle or a caller binding. + // Delay its handle proof until resolution selects the parameter mode. All + // other contexts retain the existing aggregate-only reference rules. + std::vector pending_references; + struct reference_argument_guard { + std::function check; + ~reference_argument_guard() { check(); } + } reference_guard{[&] { + for (auto *reference : pending_references) { + if (!reference->checked_binding_reference && reference->operand) + check_reference_handle(*reference, *reference->operand, + resolve_type(reference->operand->inferred_type.value_or(""))); + } + }}; // Visit arguments first to resolve their types for inference std::vector arg_types; for (auto &arg : e.args) { if (arg) { - arg->accept(*this); + if (arg->kind == ast_node_kind::ref_expr_node) { + auto &reference = static_cast(*arg); + reference.checked_binding_reference = false; + reference.checked_reference_handle = false; + if (reference.operand) reference.operand->accept(*this); + const auto operand = last_expr_type_.value_or(type_unknown); + last_expr_type_ = resolve_type("ref<" + operand.name + ">"); + reference.inferred_type = last_expr_type_->name; + pending_references.push_back(&reference); + } else arg->accept(*this); arg_types.push_back(last_expr_type_.value_or(type_unknown)); } else { arg_types.push_back(type_unknown); @@ -4913,6 +4960,13 @@ void type_checker::visit(ast_call_expr &e) { const auto ¶meter = callee.params[parameter_index]; if (!parameter.type_name) continue; auto expected = resolve_type(instantiate_generic_type(*parameter.type_name, substitutions)); + if (parameter.is_ref) { + if (!e.args[i] || e.args[i]->kind != ast_node_kind::ref_expr_node) + add_error(e.line, "Reference parameter '" + parameter.name + + "' requires an explicit reference to a mutable local binding"); + else check_binding_reference_argument(static_cast(*e.args[i]), expected); + continue; + } // Variadic parameters are represented as array in the body, but // every source argument in their tail must satisfy the element type. if (parameter.is_variadic) { @@ -6183,8 +6237,8 @@ bool type_checker::check_reference_handle(ast_expr &reference, ast_expr &operand reference.checked_reference_handle = false; // REF_LOCAL preserves an aggregate object handle, not the address of a // binding. Primitive values must never be copied and then interpreted as - // heap addresses by READ_PTR/WRITE_PTR. A future scalar-reference feature - // requires its own cell/lifetime ABI rather than widening this proof. + // heap addresses by READ_PTR/WRITE_PTR. Binding-reference arguments use + // their separate checked cell/lifetime ABI rather than widening this proof. if (operand.kind != ast_node_kind::identifier_expr_node) { add_error(reference.line, "Reference target must be a local struct or class handle; " @@ -6215,6 +6269,32 @@ bool type_checker::check_reference_handle(ast_expr &reference, ast_expr &operand return true; } +bool type_checker::check_binding_reference_argument(ast_ref_expr &argument, + const type_info &expected) { + argument.checked_binding_reference = false; + const auto errors_before = diagnostics_.size(); + if (!argument.operand || argument.operand->kind != ast_node_kind::identifier_expr_node) { + add_error(argument.line, "Reference argument requires a mutable local binding, not a temporary, field or index"); + return false; + } + const auto &identifier = static_cast(*argument.operand); + const auto *local = symbols_.lookup_non_global(identifier.name); + if (!local || local->kind != symbol_kind::variable_symbol || identifier.resolved_global_name) { + add_error(argument.line, "Reference argument requires a mutable local binding; globals are unavailable"); + return false; + } + if (!local->is_mut) + add_error(argument.line, "Cannot pass immutable binding '" + identifier.name + "' to a reference parameter"); + const auto actual = resolve_type(local->type_name.value_or("")); + if (actual.name != expected.name) + add_error(argument.line, "Reference argument requires the exact type '" + expected.name + + "', got '" + actual.name + "'; references do not perform numeric or handle conversions"); + if (diagnostics_.size() != errors_before) return false; + argument.checked_binding_reference = true; + checked_binding_references_.push_back(&argument); + return true; +} + void type_checker::visit(ast_unary_expr &e) { if (e.operand) e.operand->accept(*this); @@ -6573,6 +6653,9 @@ void type_checker::visit(ast_identifier_expr &e) { if (value.kind == symbol_kind::function_symbol && (!value.defining_node || value.defining_node->kind == ast_node_kind::function_decl_node)) { + if (direct_call_callee_ != &e && std::any_of(value.params.begin(), value.params.end(), + [](const ast_param ¶meter) { return parameter.is_ref; })) + add_error(e.line, "Functions with reference parameters must be called directly; reference-parameter function values are unavailable"); e.checked_callable_parameters = callable_parameters(value.params); // Function references are structural values even when found through a // type alias or a copied module-member symbol. Their return type alone @@ -9114,6 +9197,11 @@ void type_checker::visit(ast_ref_expr &e) { } void type_checker::visit(ast_lambda_expr &e) { + for (auto ¶meter : e.params) { + parameter.checked_binding_reference = false; + if (parameter.is_ref) + add_error(parameter.line, "Reference parameters are unavailable on anonymous functions"); + } e.checked_callable_parameters = callable_parameters(e.params); // Build function type: fn(T1, T2, ...) -> R std::string fn_type = "fn("; diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index e8b74354..8b21f175 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -231,6 +231,10 @@ class type_checker : public ast_node::ast_visitor { bool check_reference_handle(ast_expr &reference, ast_expr &operand, const type_info &operand_type); std::vector checked_reference_handles_; + std::vector checked_binding_references_; + std::vector checked_reference_parameters_; + bool check_binding_reference_argument(ast_ref_expr &argument, + const type_info &expected); std::vector checked_parallel_calls_; bool check_runtime_primitive(ast_call_expr &call); @@ -263,6 +267,7 @@ class type_checker : public ast_node::ast_visitor { active_impl_generic_bounds_; bool in_loop_ = false; bool checking_class_call_ = false; + const ast_expr *direct_call_callee_ = nullptr; std::vector checked_attempts_; std::vector checked_fault_handlers_; std::vector checked_raises_; diff --git a/nildebugger/debugger_core.cpp b/nildebugger/debugger_core.cpp index 50a0296d..b6d4ba4b 100644 --- a/nildebugger/debugger_core.cpp +++ b/nildebugger/debugger_core.cpp @@ -1098,8 +1098,33 @@ std::vector Debugger::get_source_locals(int frame_idx) const { for (const auto& entry : visible) { const auto& binding = *entry.second; const auto value = locals.find(binding.storage); - if (value != locals.end()) result.push_back( - {binding.name, binding.storage, binding.type, value->second}); + if (value == locals.end()) continue; + LocalVariable local{binding.name, binding.storage, binding.type, value->second}; + // Reference parameters and addressed locals use a compiler-owned + // cell. Source inspection exposes the binding's scalar value, + // while instruction-only NIL still shows exact runtime storage. + if (binding.type.rfind("binding_ref<", 0) == 0 && binding.type.back() == '>') { + const auto type = binding.type.substr(12, binding.type.size() - 13); + const auto* cell = std::get_if(&value->second); + if (cell && cell->data && cell->type_name == "$nil.binding.cell." + type) { + std::optional referent; + if (type == "i32" || type == "i64" || type == "u8" || type == "bool") { + const auto field = cell->fields().find("value"); + if (field != cell->fields().end()) referent = Value{field->second}; + } else if (type == "f64") { + const auto field = cell->double_fields().find("value"); + if (field != cell->double_fields().end()) referent = Value{field->second}; + } else if (type == "text") { + const auto field = cell->string_fields().find("value"); + if (field != cell->string_fields().end()) referent = Value{field->second}; + } + if (referent) { + local.type = type; + local.value = std::move(*referent); + } + } + } + result.push_back(std::move(local)); } } else { for (const auto& entry : locals) result.push_back( diff --git a/nildebugger/tests/dap_protocol.py b/nildebugger/tests/dap_protocol.py index 7e2cc83a..88803518 100644 --- a/nildebugger/tests/dap_protocol.py +++ b/nildebugger/tests/dap_protocol.py @@ -190,6 +190,54 @@ def asynchronous_session(debugger, program): client.close() +def reference_parameter_session(debugger, compiler, root): + sources = { + "ny": "module reference_debug\nfn mutate(ref amount: i64)\n" + " amount = amount + 1\n println(amount)\nend fn\n" + "fn main() -> i32\n let mut total: i64 = 40\n mutate(ref total)\n" + " println(total)\n return 0\nend fn\n", + "matrix": "book reference-debug\nmutate receives reference amount as number begin paragraph\n" + " set amount to amount plus 1\n say amount\nend paragraph\n" + "main returns override integer begin paragraph\n variable total as number is 40\n" + " evaluate mutate with reference to total\n say total\n give 0\nend paragraph\n", + } + for language, contents in sources.items(): + source = root / ("reference-debug." + language) + source.write_text(contents, encoding="utf-8") + for binary in (False, True): + program = root / ("reference-" + language + ("-binary.nil" if binary else "-text.nil")) + compile_program(compiler, program, source, binary=binary) + client = Client(debugger) + try: + client.initialize(program, stop_on_entry=False) + points = client.breakpoints(source, 4, 9) + assert len(points) == 2 and all(point["verified"] for point in points), points + client.request("configurationDone") + assert client.event("stopped")["reason"] == "breakpoint" + frames = client.stack() + assert len(frames) == 2 and frames[0]["line"] == 4 and frames[1]["line"] == 8, frames + for frame, name in ((frames[0], "amount"), (frames[1], "total")): + assert Path(frame["source"]["path"]) == source, frame + assert client.evaluate(name, frame["id"]) == "41", (language, binary, name) + scope = client.request("scopes", {"frameId": frame["id"]})["body"]["scopes"][0] + variables = client.request("variables", { + "variablesReference": scope["variablesReference"]})["body"]["variables"] + # The source-level reference remains a scalar in both + # frames, with no compiler cell object or child handle. + assert [(item["name"], item["value"], item["variablesReference"]) + for item in variables] == [(name, "41", 0)], variables + client.request("continue", {"threadId": 1}) + assert client.event("stopped")["reason"] == "breakpoint" + frames = client.stack() + assert len(frames) == 1 and frames[0]["line"] == 9, frames + assert client.evaluate("total", frames[0]["id"]) == "41" + client.request("continue", {"threadId": 1}) + assert client.event("exited")["exitCode"] == 0 + client.event("terminated") + finally: + client.close() + + def binary_library_session(debugger, compiler, root): producer = root / "producer" consumer = root / "consumer" @@ -289,12 +337,13 @@ def main(): compile_program(compiler, loop_nil, loop) asynchronous_session(debugger, loop_nil) binary_library_session(debugger, compiler, root) + reference_parameter_session(debugger, compiler, root) for malformed in (b"Content-Length: 1048577\r\n\r\n", b"Content-Length: 2\r\nContent-Length: 2\r\n\r\n{}", b"Content-Length: -1\r\n\r\n", b"Content-Length: 10\r\n\r\n{}", b"Content-Length: 1\r\n\r\nx", b"Bad\r\n\r\n", b"Content-Length: 2\n\n{}", b"X: " + b"a" * 8193): result = subprocess.run([str(debugger), "--dap"], input=malformed, capture_output=True, timeout=5) assert result.returncode != 0 and result.stdout == b"", result - print("DAP: text/binary source paths, shadows, frames, stepping, output, pause, termination, and malformed framing passed") + print("DAP: text/binary source paths, shadows, reference parameters, frames, stepping, output, pause, termination, and malformed framing passed") if __name__ == "__main__": diff --git a/nildebugger/tests/debugger_core_tests.cpp b/nildebugger/tests/debugger_core_tests.cpp index 856e1ad2..f926c2a2 100644 --- a/nildebugger/tests/debugger_core_tests.cpp +++ b/nildebugger/tests/debugger_core_tests.cpp @@ -564,6 +564,50 @@ void test_json_value_serialization() { "array field serialization"); } +void test_source_binding_reference_inspection() { + for (const auto& type : {"i32", "i64", "u8", "bool", "f64", "text"}) { + const std::string scalar_type = type; + const std::string code = + "module reference_inspection\nfunction main:\n" + "LOAD_GLOBAL CELL ; line 1\nSTORE_LOCAL hidden_cell ; line 1\n" + "# source_debug 2 \"/source/reference.ny\" 1 \"amount\" \"hidden_cell\" \"binding_ref<" + + scalar_type + ">\" 1\nNOP ; line 2\nRET ; line 3\nend function\n"; + TempNilFile fixture("binding-reference-" + scalar_type, code); + Debugger debugger; + require(debugger.load_program(fixture.path().string()), "could not load reference inspection fixture"); + StructValue cell; + cell.type_name = "$nil.binding.cell." + scalar_type; + if (scalar_type == "f64") cell.double_fields()["value"] = 1.25; + else if (scalar_type == "text") cell.string_fields()["value"] = "hello"; + else cell.fields()["value"] = scalar_type == "bool" ? 1 : 42; + auto& vm = debugger.get_vm(); + vm.resetExecution("main"); + vm.setGlobal("CELL", Value{cell}); + for (int step = 0; step < 8 && vm.getProgram().at(vm.getPC()).op != ny::Opcode::NOP; ++step) + require(vm.stepInstruction(), "reference inspection fixture ended before its source stop"); + const auto locals = debugger.get_source_locals(); + require(locals.size() == 1 && locals[0].name == "amount" && locals[0].type == scalar_type, + "source reference inspection exposed its internal cell type"); + const auto expected = scalar_type == "f64" ? "1.25" : scalar_type == "text" ? "\"hello\"" : + scalar_type == "bool" ? "1" : "42"; + require(debugger.evaluate_expression("amount") == expected, + "source reference expression did not unwrap its scalar value"); + require(debugger.get_locals_json().find("$nil.binding.cell.") == std::string::npos, + "source locals JSON leaked its reference cell"); + if (scalar_type == "i64") { + cell.fields()["value"] = 43; + require(debugger.evaluate_expression("amount") == "43", "reference inspection cached a stale value"); + } + cell.type_name = "OrdinaryRecord"; + vm.resetExecution("main"); + vm.setGlobal("CELL", Value{cell}); + for (int step = 0; step < 8 && vm.getProgram().at(vm.getPC()).op != ny::Opcode::NOP; ++step) + require(vm.stepInstruction(), "record inspection fixture ended before its source stop"); + require(std::holds_alternative(debugger.get_source_locals().at(0).value), + "reference metadata incorrectly unwrapped an unrelated record"); + } +} + void test_vm_input_routing() { std::istringstream source(R"NIL(module input_routing function main: @@ -718,6 +762,7 @@ int main() { test_per_vm_callback_isolation(path); test_step_over_out_and_frame_cleanup(path); test_json_value_serialization(); + test_source_binding_reference_inspection(); test_vm_input_routing(); test_execute_true_preserves_injected_globals(); test_rejects_missing_main_and_v2_library(path); diff --git a/nillsp/matrix_parser.cpp b/nillsp/matrix_parser.cpp index 15f6882d..af3e7df2 100644 --- a/nillsp/matrix_parser.cpp +++ b/nillsp/matrix_parser.cpp @@ -72,7 +72,9 @@ std::vector lex(const std::string& text, ParseResult& out) { } else if (name_start(text[i])) { while (i < text.size() && name_part(text[i])) ++i; const auto spelling = text.substr(start, i - start); - const auto word = lowercase(spelling); + auto word = lowercase(spelling); + if (word == "mut") word = "mutable"; + else if (word == "ref") word = "reference"; auto quote = i; while (quote < text.size() && (text[quote] == ' ' || text[quote] == '\t')) ++quote; if (word == "formatted" && quote > i && quote < text.size() && text[quote] == '"') { @@ -172,6 +174,14 @@ class Indexer { while (begin < tokens.size() && tokens[begin].word == "\n" && tokens[begin].text == "\n") ++begin; return begin; } + std::size_t parameter_name(std::size_t begin) const { + begin = significant(begin); + if (begin < tokens.size() && tokens[begin].word == "more") begin = significant(begin + 1); + if (begin < tokens.size() && (tokens[begin].word == "mutable" || tokens[begin].word == "variable" || + tokens[begin].word == "reference")) + begin = significant(begin + 1); + return begin; + } std::size_t header_end(std::size_t begin) const { for (auto i = begin; i < tokens.size(); ++i) { if (tokens[i].word == "end" || tokens[i].word == "otherwise") return i; @@ -179,7 +189,7 @@ class Indexer { if (tokens[i].text != "\n") return i; const auto next = significant(i); if (next == tokens.size()) return i; - const auto following = significant(next + 1); + const auto following = significant(parameter_name(next) + 1); const auto previous = i > begin ? tokens[i - 1].word : ""; if (declaration_clause(tokens[next].word) || tokens[next].word == "meeting" || previous == "," || previous == "and" || previous == "as" || @@ -216,24 +226,26 @@ class Indexer { while (begin < end) { if (tokens[begin].word == "on" || tokens[begin].word == "without") break; if (tokens[begin].word == "," || tokens[begin].word == "and" || tokens[begin].word == "\n") { ++begin; continue; } + const auto declaration_begin = begin; const bool variadic = tokens[begin].word == "more"; - if (variadic || tokens[begin].word == "variable") ++begin; + begin = parameter_name(begin); if (begin >= end) break; const auto name = begin++; if (begin >= end || tokens[begin].word != "as") break; const auto type_begin = ++begin; while (begin < end) { const auto& word = tokens[begin].word; - auto next = significant(begin + 1); - if (next < end && tokens[next].word == "variable") next = significant(next + 1); + const auto next = parameter_name(begin + 1); const auto after = significant(next + 1); if (word == "on" || word == "without" || word == "defaulting" || ((word == "," || word == "and") && next < end && after < end && tokens[after].word == "as")) break; ++begin; } + auto type_end = begin; + while (type_end > type_begin && tokens[type_end - 1].word == "\n") --type_end; const auto id = add(tokens[name], symbol_kind::Variable, scope, parent, - tokens[name].start, begin > type_begin ? tokens[begin - 1].end : tokens[name].end); - out.symbols[id].type = (variadic ? "array of " : "") + joined(type_begin, begin); + tokens[declaration_begin].start, type_end > type_begin ? tokens[type_end - 1].end : tokens[name].end); + out.symbols[id].type = (variadic ? "array of " : "") + joined(type_begin, type_end); if (begin < end && tokens[begin].word == "defaulting") { while (begin < end && tokens[begin].word != "," && tokens[begin].word != "and") ++begin; } @@ -635,16 +647,22 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: if (begin < text.size() && text[begin] == '`') return {}; if (begin > 0 && (text[begin - 1] == '.' || text[begin - 1] == ':' || text[begin - 1] == '`')) return {}; ParseResult context; - const auto before = lex(text.substr(offsets[position.line], begin - offsets[position.line]), context); + const auto before = lex(text.substr(0, begin), context); const auto last = before.empty() ? "" : before.back().word; if (last == "my") return {}; const auto prefix = lowercase(text.substr(begin, *at - begin)); // These are language spellings, not speculative imported library symbols. std::vector words; int kind = 14; + bool parameter_clause = false; + for (auto token = before.rbegin(); token != before.rend(); ++token) { + if (token->word == "receives") { parameter_clause = true; break; } + if (token->word == "begin" || token->word == "end" || token->word == "returns" || + (token->word == "\n" && token->text != "\n")) break; + } if (last == "as" || last == "returns" || last == "becomes" || last == "means" || last == "of" || last == "holding" || last == "to") { - words = {"number", "floating", "boolean", "text", "nothing", "override", "array of", "tuple of", "pointer to", "reference to", "owned array of", "shared view of", "exclusive view of"}; + words = {"number", "floating", "boolean", "text", "nothing", "override", "array of", "tuple of", "pointer to", "reference to", "ref to", "owned array of", "shared view of", "exclusive view of"}; kind = 25; // TypeParameter: language type vocabulary } else if (last == "override") words = {"integer", "long", "byte", "double"}; else if (last == "begin") words = {"paragraph", "record", "class", "choice", "contract", "implementation", "extension", "test", "text"}; @@ -654,7 +672,17 @@ std::vector matrix_keywords(const ParseResult& parsed, const std: else if (last == "shifted") words = {"left by", "right by"}; else if (last == "the") words = {"length of", "paragraph"}; else if (last == "with") words = {"nothing", "more"}; - else if (last == "value" || last == "variable" || last == "constant" || last == "field" || last == "book") return {}; + else if (last == "receives") words = {"mutable", "mut", "variable", "reference", "ref", "more"}; + else if (parameter_clause && last == "more") words = {"mutable", "mut", "variable"}; + else if (parameter_clause && (last == "," || last == "and" || last == "\n")) + words = {"mutable", "mut", "variable", "reference", "ref", "more"}; + else if (last == "reference") { + const auto previous = before.size() > 1 ? before[before.size() - 2].word : ""; + if (parameter_clause && (previous == "receives" || previous == "and" || previous == "," || previous == "\n")) + return {}; + words = {"to"}; + } + else if (last == "value" || last == "variable" || last == "mutable" || last == "constant" || last == "field" || last == "book") return {}; else if (last.empty() || last == "\n") words = {"value", "variable", "constant", "set", "say", "give", "evaluate", "when", "otherwise", "repeat", "consider", "attempt", "caught", "always", "raise", "append", "allocate", "release", "own", "borrow", "move", "stop repeating", "continue repeating", "book", "library", "read", "cite", "public", "end"}; else words = {"true", "false", "nothing", "build", "my", "the length of", "the paragraph", "anonymous", "formatted", "quote", "newline", "tab", "negative", "plus", "minus", "times", "over", "remainder", "equals", "does not equal", "is less than", "is greater than", "is at least", "is at most", "and", "or", "not", "bitwise", "shifted", "becomes", "with", "receives", "returns", "begin"}; std::vector result; diff --git a/nillsp/ny_parser.cpp b/nillsp/ny_parser.cpp index efc82cb3..d9f26eb9 100644 --- a/nillsp/ny_parser.cpp +++ b/nillsp/ny_parser.cpp @@ -28,6 +28,7 @@ std::string matrix_type_base(std::string type) { // References expose the referent, but arrays and pointers do not pretend // to be records just because their element type is a record. if (matrix_key(type).rfind("reference to ", 0) == 0) type.erase(0, 13); + else if (matrix_key(type).rfind("ref to ", 0) == 0) type.erase(0, 7); const auto generic = matrix_key(type).find(" of "); if (generic != std::string::npos) { // Locate in the original spelling (the key may remove separators). @@ -113,7 +114,9 @@ std::vector lex(const std::string& text, ParseResult& out) { } std::string type_base(std::string type) { - if (type.rfind("ref<", 0) == 0 || type.rfind("ptr<", 0) == 0) + if (type.rfind("reference<", 0) == 0) + type = type.substr(10, type.size() > 11 ? type.size() - 11 : 0); + else if (type.rfind("ref<", 0) == 0 || type.rfind("ptr<", 0) == 0) type = type.substr(4, type.size() > 5 ? type.size() - 5 : 0); const auto generic = type.find('<'); if (generic != std::string::npos) type.resize(generic); @@ -184,8 +187,11 @@ class Indexer { void parameters(std::size_t begin, std::size_t end, int scope, int parent, const std::string& owner) { while (begin < end) { - while (begin < end && (tokens[begin].text == "mut" || tokens[begin].text == ".." || - tokens[begin].text == "\n" || tokens[begin].text == ",")) ++begin; + while (begin < end && (tokens[begin].text == "\n" || tokens[begin].text == ",")) ++begin; + const auto declaration_begin = begin; + while (begin < end && (tokens[begin].text == "mut" || tokens[begin].text == "mutable" || + tokens[begin].text == "ref" || tokens[begin].text == "reference" || + tokens[begin].text == ".." || tokens[begin].text == "\n")) ++begin; if (begin == end) break; const auto name = begin++; const auto type_begin = begin < end && tokens[begin].text == ":" ? ++begin : begin; @@ -199,10 +205,11 @@ class Indexer { } if (!name_start(tokens[name].text.front())) continue; const auto id = add(tokens[name], symbol_kind::Variable, scope, parent, - tokens[name].start, tokens[begin - 1].end); + tokens[declaration_begin].start, tokens[begin - 1].end); out.symbols[id].type = joined(type_begin, begin); if (tokens[name].text == "self" && out.symbols[id].type.empty()) out.symbols[id].type = owner; - if (out.symbols[id].type == "Self" || out.symbols[id].type == "ref") + if (out.symbols[id].type == "Self" || out.symbols[id].type == "ref" || + out.symbols[id].type == "reference") out.symbols[id].type = owner; } } @@ -252,7 +259,7 @@ class Indexer { void variable(int scope, int parent, std::size_t declaration_start) { const bool constant = at("const"); ++cursor; - if (at("mut")) ++cursor; + if (at("mut") || at("mutable")) ++cursor; if (at("(")) { std::vector names; ++cursor; diff --git a/tests/binding_reference_contract_tests.cpp b/tests/binding_reference_contract_tests.cpp new file mode 100644 index 00000000..39da0a33 --- /dev/null +++ b/tests/binding_reference_contract_tests.cpp @@ -0,0 +1,428 @@ +#include "binding_reference.hpp" +#include "codegen.hpp" +#include "nil_contract.hpp" +#include "nil_loader.hpp" +#include "vm.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +int failures = 0; +int checks = 0; +const std::string cell = "$nil.binding.cell.i64"; +const std::string reference = "ref<" + cell + ">"; + +void check(bool condition, const std::string &label) { + ++checks; + if (!condition) { + ++failures; + std::cerr << "FAIL: " << label << '\n'; + } +} + +void rejects(const std::function &operation, const std::string &label) { + bool rejected = false; + try { operation(); } + catch (const std::runtime_error &) { rejected = true; } + check(rejected, label); +} + +ny::nil_function function(std::string name, std::vector parameters, + std::string result, std::vector body) { + ny::nil_function value; + value.name = std::move(name); + value.params = std::move(parameters); + value.return_type = std::move(result); + value.body = std::move(body); + return value; +} + +std::vector initialized_cell() { + return {{"NEW_STRUCT", {cell}}, {"PUSH_CONST", {"5"}}, {"CAST", {"i64"}}, + {"SET_FIELD", {"value"}}, {"STORE_LOCAL", {"storage"}}}; +} + +ny::nil_module fixture() { + ny::nil_module module; + module.module_name = "binding_reference_contract"; + module.structs = {{cell, {{"value", "i64"}}, {"@nil_binding_cell"}}}; + module.functions = { + function("bump", {"target:" + reference}, "void", + {{"STORE_LOCAL", {"target"}}, {"LOAD_LOCAL", {"target"}}, + {"LOAD_LOCAL", {"target"}}, {"GET_FIELD", {"value"}}, + {"PUSH_CONST", {"1"}}, {"ADD", {"i64"}}, {"SET_FIELD", {"value"}}, + {"POP", {}}, {"RET", {}}}), + function("forward", {"target:" + reference}, "void", + {{"STORE_LOCAL", {"target"}}, {"LOAD_LOCAL", {"target"}}, + {"CALL", {"bump", "1"}}, {"RET", {}}}), + function("aliases", {"first:" + reference, "second:" + reference}, "void", + {{"STORE_LOCAL", {"second"}}, {"STORE_LOCAL", {"first"}}, + {"LOAD_LOCAL", {"first"}}, {"LOAD_LOCAL", {"first"}}, {"GET_FIELD", {"value"}}, + {"PUSH_CONST", {"1"}}, {"ADD", {"i64"}}, {"SET_FIELD", {"value"}}, {"POP", {}}, + {"LOAD_LOCAL", {"second"}}, {"LOAD_LOCAL", {"second"}}, {"GET_FIELD", {"value"}}, + {"PUSH_CONST", {"10"}}, {"ADD", {"i64"}}, {"SET_FIELD", {"value"}}, {"POP", {}}, + {"LOAD_LOCAL", {"first"}}, {"LOAD_LOCAL", {"first"}}, {"GET_FIELD", {"value"}}, + {"LOAD_LOCAL", {"second"}}, {"GET_FIELD", {"value"}}, {"ADD", {"i64"}}, + {"SET_FIELD", {"value"}}, {"POP", {}}, {"RET", {}}}), + function("main", {}, "void", initialized_cell())}; + auto &body = module.functions.back().body; + const std::vector tail = { + {"REF_LOCAL", {"storage"}}, {"REF_LOCAL", {"storage"}}, {"CALL", {"aliases", "2"}}, + {"REF_LOCAL", {"storage"}}, {"CALL", {"forward", "1"}}, + {"LOAD_LOCAL", {"storage"}}, {"GET_FIELD", {"value"}}, {"CONSOLE_WRITELN", {}}, {"RET", {}}}; + body.insert(body.end(), tail.begin(), tail.end()); + return module; +} + +std::string serialize(const ny::nil_module &module, bool binary) { + std::ostringstream output; + if (binary) { + ny::codegen_options options; + ny::nil_binary_writer writer(output, options); + writer.emit_binary_module(module); + } else { + ny::nil_writer writer(output); + writer.emit_text_module(module); + } + return output.str(); +} + +std::vector parse(const ny::nil_module &module, bool binary, + std::unordered_map &constants) { + std::istringstream input(serialize(module, binary)); + return binary ? ny::parseBinaryProgram(input, constants) : ny::parseProgram(input, constants); +} + +void rejected_module(const ny::nil_module &module, const std::string &label) { + rejects([&] { ny::validate_nil_class_contract(module); }, label + " direct validation"); + for (bool binary : {false, true}) { + const auto encoded = serialize(module, binary); + const std::string format = binary ? " binary" : " text"; + rejects([&] { + std::istringstream input(encoded); + if (binary) (void)ny::parseBinaryNilModule(input); + else (void)ny::parseTextNilModule(input); + }, label + format + " module"); + rejects([&] { + std::istringstream input(encoded); + std::unordered_map constants; + if (binary) (void)ny::parseBinaryProgram(input, constants); + else (void)ny::parseProgram(input, constants); + }, label + format + " VM loader"); + } +} + +void rejected_tail(std::vector tail, const std::string &label, + std::string result = "void") { + auto module = fixture(); + module.functions.back().return_type = std::move(result); + auto &body = module.functions.back().body; + body = initialized_cell(); + body.insert(body.end(), tail.begin(), tail.end()); + rejected_module(module, label); +} + +void positive_encodings() { + for (bool binary : {false, true}) { + const auto module = fixture(); + ny::validate_nil_class_contract(module); + std::unordered_map constants; + auto program = parse(module, binary, constants); + check(!program.empty() && program.front().module_metadata && + program.front().module_metadata->structs.front().annotations == + std::vector{"@nil_binding_cell"}, + "both VM encodings retain explicit compiler cell schema"); + ny::VM vm; + std::ostringstream output; + vm.setOutputStream(output); + vm.loadProgram(program, constants); + vm.execute(); + check(output.str() == "33\n", "same binding aliases immediately and forwards without copying"); + output.str(""); output.clear(); + vm.resetExecution("main"); + for (unsigned steps = 0; steps < 160 && vm.getPC() < vm.getProgram().size(); ++steps) + vm.stepInstruction(); + check(output.str() == "33\n", "debugger reset reconstructs cells and stepping preserves aliases"); + + std::istringstream input(serialize(module, binary)); + const auto decoded = binary ? ny::parseBinaryNilModule(input) : ny::parseTextNilModule(input); + check(decoded->functions.front().params == std::vector{"target:" + reference} && + decoded->structs.front().annotations == std::vector{"@nil_binding_cell"}, + "native module readers retain exact cell and reference signatures"); + + // A loader result is not a permanent validation token: embedders can edit + // instruction vectors or replace their shared metadata before VM loading. + auto unregistered = program; + unregistered.front().module_metadata.reset(); + rejects([&] { vm.loadProgram(unregistered, constants); }, "missing VM metadata rejects cell program"); + + auto forged = program; + auto metadata = std::make_shared(*program.front().module_metadata); + metadata->structs.front().annotations.clear(); + forged.front().module_metadata = metadata; + rejects([&] { vm.loadProgram(forged, constants); }, "VM rechecks forged schema annotation"); + + auto changed = program; + for (auto &instruction : changed) + if (instruction.op == ny::Opcode::REF_LOCAL) { + instruction.op = ny::Opcode::PUSH_CONST; + instruction.args = {"0"}; + break; + } + rejects([&] { vm.loadProgram(changed, constants); }, "VM rechecks changed cell argument provenance"); + } +} + +void negative_contracts() { + rejected_tail({{"LOAD_LOCAL", {"storage"}}, {"RET", {}}}, "returning a cell", cell); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"RET", {}}}, "returning a reference", reference); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"RET", {}}}, "erasing returned storage to any", "any"); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"STORE_GLOBAL", {"escaped"}}, {"RET", {}}}, "global escape"); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"NEW_ARRAY_LITERAL", {"1"}}, {"POP", {}}, {"RET", {}}}, "array escape"); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"NEW_VARIANT", {"Container::Item", "1"}}, {"POP", {}}, {"RET", {}}}, "enum escape"); + rejected_tail({{"PUSH_CONST", {"0"}}, {"REF_LOCAL", {"storage"}}, {"WRITE_PTR", {}}, {"RET", {}}}, "raw-pointer escape"); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"CAST", {"i64"}}, {"POP", {}}, {"RET", {}}}, "cast erases storage provenance"); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"CALL", {"external", "1"}}, {"RET", {}}}, "unknown call escape"); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"INTEROP_CALL", {"intrinsic", "external", "1", "void"}}, {"RET", {}}}, "foreign call escape"); + rejected_tail({{"LOAD_LOCAL", {"storage"}}, {"CALL", {"bump", "1"}}, {"RET", {}}}, "value cell is not an explicit reference"); + rejected_tail({{"PUSH_CONST", {"0"}}, {"CALL", {"bump", "1"}}, {"RET", {}}}, "forged scalar reference argument"); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"FAULT_RAISE", {cell}}}, "cell as fault payload"); + rejected_tail({{"LABEL", {"again"}}, {"NEW_STRUCT", {cell}}, {"PUSH_CONST", {"0"}}, + {"SET_FIELD", {"value"}}, {"POP", {}}, {"JMP", {"again"}}}, "constructor in loop"); + rejected_tail({{"REF_LOCAL", {"storage"}}, {"CALL", {"bump", "1"}}, + {"NEW_STRUCT", {cell}}, {"PUSH_CONST", {"0"}}, {"SET_FIELD", {"value"}}, + {"POP", {}}, {"RET", {}}}, "constructor after a call"); + + auto bad = fixture(); + bad.structs.push_back({"Box", {{"item", "i64"}}}); + bad.functions.back().body = initialized_cell(); + const std::vector field_escape = { + {"NEW_STRUCT", {"Box"}}, {"REF_LOCAL", {"storage"}}, {"SET_FIELD", {"item"}}, {"POP", {}}, {"RET", {}}}; + bad.functions.back().body.insert(bad.functions.back().body.end(), field_escape.begin(), field_escape.end()); + rejected_module(bad, "field escape cannot erase reference type"); + bad = fixture(); + bad.structs.push_back({"Box", {{"item", reference}}}); + rejected_module(bad, "schema cannot retain a reference field"); + bad = fixture(); + bad.enums.push_back({"Container", {{"Item", reference}}}); + rejected_module(bad, "enum schema cannot retain a reference payload"); + bad = fixture(); + bad.structs.push_back({"$nil.binding.cell.i32", {{"value", "i32"}}, {"@nil_binding_cell"}}); + bad.functions.front().params.front() = "target:ref<$nil.binding.cell.i32>"; + rejected_module(bad, "reference widths must agree at the call boundary"); + bad = fixture(); + bad.functions.front().params.front() = "target:" + cell; + rejected_module(bad, "cell values are forbidden parameter signatures"); + bad = fixture(); + bad.functions.front().annotations = {"@intrinsic(\"external\")"}; + rejected_module(bad, "reference parameter cannot cross an intrinsic ABI"); + bad = fixture(); + bad.functions.front().annotations = {" @intrinsic(\"external\")"}; + // Writers reject leading whitespace themselves; direct consumers must also + // reject this in-memory module before native lowering. + rejects([&] { ny::validate_nil_class_contract(bad); }, + "whitespace cannot disguise an intrinsic reference ABI"); + bad = fixture(); + bad.functions.front().body = {{"STORE_LOCAL", {"target"}}, {"REF_LOCAL", {"target"}}, + {"STORE_GLOBAL", {"escaped"}}, {"RET", {}}}; + rejected_module(bad, "referencing a reference cannot erase its lifetime provenance"); + bad = fixture(); + bad.functions.front().params.front() = "target: ref< $nil.binding.cell.i64 >"; + bad.functions.front().body = {{"STORE_LOCAL", {"target"}}, {"LOAD_LOCAL", {"target"}}, + {"CALL", {"external", "1"}}, {"RET", {}}}; + rejected_module(bad, "whitespace cannot erase reference argument provenance"); + for (const auto &type : {std::string("i64"), std::string("f64"), std::string("text")}) { + ny::nil_module wrong_value; + wrong_value.module_name = "wrong_cell_scalar"; + const auto schema = std::string(ny::nil_binding_cell_prefix) + type; + wrong_value.structs = {{schema, {{"value", type}}, {"@nil_binding_cell"}}}; + wrong_value.string_constants = {{"S0", "wrong"}}; + const ny::nil_instruction scalar = type == "i64" + ? ny::nil_instruction{"PUSH_CONST_STR", {"S0"}} + : ny::nil_instruction{"PUSH_CONST", {type == "f64" ? "1" : "1.5"}}; + wrong_value.functions = {function("main", {}, "void", + {{"NEW_STRUCT", {schema}}, scalar, {"SET_FIELD", {"value"}}, + {"STORE_LOCAL", {"storage"}}, {"RET", {}}})}; + rejected_module(wrong_value, "cell scalar category must agree for " + type); + } + bad = fixture(); + bad.functions.push_back(bad.functions.front()); + rejected_module(bad, "duplicate function identity cannot change a reference callee"); + bad = fixture(); + bad.functions.insert(bad.functions.end() - 1, + function("escape", {"value:any"}, "void", {{"STORE_LOCAL", {"value"}}, + {"LOAD_LOCAL", {"value"}}, {"STORE_GLOBAL", {"escaped"}}, {"RET", {}}})); + bad.functions.back().body = initialized_cell(); + const std::vector shadowed_call = { + {"PUSH_FN_PTR", {"escape"}}, {"STORE_LOCAL", {"bump"}}, + {"REF_LOCAL", {"storage"}}, {"CALL", {"bump", "1"}}, {"RET", {}}}; + bad.functions.back().body.insert(bad.functions.back().body.end(), shadowed_call.begin(), shadowed_call.end()); + rejected_module(bad, "local function value cannot redirect a checked reference call"); + for (const auto &target : {std::string("escape"), std::string("bump")}) { + bad = fixture(); + bad.functions.insert(bad.functions.end() - 1, + function("escape", {"value:any"}, "void", {{"STORE_LOCAL", {"value"}}, + {"LOAD_LOCAL", {"value"}}, {"STORE_GLOBAL", {"escaped"}}, {"RET", {}}})); + bad.functions.back().body = initialized_cell(); + const std::vector indirect_call = { + {"PUSH_FN_PTR", {target}}, {"STORE_LOCAL", {"callback"}}, + {"REF_LOCAL", {"storage"}}, {"CALL", {"callback", "1"}}, {"RET", {}}}; + bad.functions.back().body.insert(bad.functions.back().body.end(), indirect_call.begin(), indirect_call.end()); + rejected_module(bad, "local indirect target cannot receive a binding reference: " + target); + } + bad = fixture(); + bad.functions.insert(bad.functions.end() - 1, + function("escape", {"value:any"}, "void", {{"STORE_LOCAL", {"value"}}, + {"LOAD_LOCAL", {"value"}}, {"STORE_GLOBAL", {"escaped"}}, {"RET", {}}})); + bad.functions.insert(bad.functions.end() - 1, + function("invoke", {"worker:fn(any)->void", "target:" + reference}, "void", + {{"STORE_LOCAL", {"target"}}, {"STORE_LOCAL", {"worker"}}, + {"LOAD_LOCAL", {"target"}}, {"CALL", {"worker", "1"}}, {"RET", {}}})); + bad.functions.back().body = initialized_cell(); + const std::vector indirect_parameter_call = { + {"PUSH_FN_PTR", {"escape"}}, {"REF_LOCAL", {"storage"}}, + {"CALL", {"invoke", "2"}}, {"RET", {}}}; + bad.functions.back().body.insert(bad.functions.back().body.end(), + indirect_parameter_call.begin(), indirect_parameter_call.end()); + rejected_module(bad, "function-valued parameter cannot receive a binding reference indirectly"); + bad = fixture(); + bad.structs.clear(); + rejected_module(bad, "reference requires declared cell schema"); + bad = fixture(); + bad.structs.front().annotations.clear(); + rejected_module(bad, "cell schema requires compiler annotation"); + bad = fixture(); + bad.structs.front().fields.front().second = "text"; + rejected_module(bad, "cell schema scalar must match its exact name"); + bad = fixture(); + bad.structs.front().fields.push_back({"extra", "i64"}); + rejected_module(bad, "cell schema has exactly one field"); + bad = fixture(); + bad.structs.push_back(bad.structs.front()); + rejected_module(bad, "cell schema must be unique"); + + ny::VM vm; + rejects([&] { vm.loadProgram({{ny::Opcode::NEW_STRUCT, {cell}}}, {}); }, + "raw VM instruction embedding cannot invent cell metadata"); +} + +void class_callable_contracts() { + // Callable metadata must preserve sensitive result types recursively. This + // module deliberately has no binding-cell schema: class-only programs need + // the same protection when a function value is cast or passed onward. + ny::nil_module module; + module.module_name = "class_callable_provenance"; + module.structs = {{"Object", {}}}; + module.classes = {{"Object", false, {}, {}}}; + module.functions = { + function("make_object", {}, "Object", {{"NEW_STRUCT", {"Object"}}, {"RET", {}}}), + function("main", {}, "void", {{"CALL", {"make_object", "0"}}, {"POP", {}}, {"RET", {}}})}; + ny::validate_nil_class_contract(module); + check(true, "class callable regression baseline has valid class metadata"); + + auto bad = module; + bad.functions.back().body = { + {"PUSH_FN_PTR", {"make_object"}}, {"CAST", {"fn()->text"}}, + {"STORE_LOCAL", {"callback"}}, {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}}; + rejected_module(bad, "casting a known callable cannot erase its class result"); + + bad = module; + bad.functions.insert(bad.functions.end() - 1, + function("invoke", {"worker:fn()->Object"}, "void", + {{"STORE_LOCAL", {"worker"}}, {"LOAD_LOCAL", {"worker"}}, + {"CAST", {"fn()->text"}}, {"STORE_LOCAL", {"callback"}}, + {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}})); + bad.functions.back().body = { + {"PUSH_FN_PTR", {"make_object"}}, {"CALL", {"invoke", "1"}}, {"RET", {}}}; + rejected_module(bad, "casting a callable parameter cannot erase its class result"); + + bad = module; + bad.functions.insert(bad.functions.end() - 1, + function("make_callback", {}, "fn()->Object", {{"PUSH_FN_PTR", {"make_object"}}, {"RET", {}}})); + bad.functions.back().body = { + {"PUSH_FN_PTR", {"make_callback"}}, {"CAST", {"fn()->fn()->text"}}, + {"STORE_LOCAL", {"outer"}}, {"CALL", {"outer", "0"}}, {"STORE_LOCAL", {"inner"}}, + {"CALL", {"inner", "0"}}, {"POP", {}}, {"RET", {}}}; + rejected_module(bad, "casting a nested callable cannot erase its eventual class result"); + + // Opaque values cannot manufacture a checked callback signature. Keep an + // addressed binding in these callers so every forged producer is checked + // within the class/cell provenance profile. + auto opaque = module; + opaque.structs.push_back({cell, {{"value", "i64"}}, {"@nil_binding_cell"}}); + opaque.string_constants = {{"S0", "make_object"}, {"S1", "safe text"}}; + opaque.functions.back().body = initialized_cell(); + const auto append_main = [](ny::nil_module &target, const std::vector &tail) { + auto &body = target.functions.back().body; + body.insert(body.end(), tail.begin(), tail.end()); + }; + + bad = opaque; + append_main(bad, {{"PUSH_CONST_STR", {"S0"}}, {"CAST", {"fn()->text"}}, + {"STORE_LOCAL", {"callback"}}, {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}}); + rejected_module(bad, "raw function-name text cannot be cast to a checked callable"); + + bad = opaque; + bad.functions.insert(bad.functions.end() - 1, + function("fake_callback", {}, "fn()->text", {{"PUSH_CONST_STR", {"S0"}}, {"RET", {}}})); + append_main(bad, {{"CALL", {"fake_callback", "0"}}, {"STORE_LOCAL", {"callback"}}, + {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}}); + rejected_module(bad, "callable return metadata cannot bless a raw function-name string"); + + bad = opaque; + bad.functions.insert(bad.functions.end() - 1, + function("safe_text", {}, "text", {{"PUSH_CONST_STR", {"S1"}}, {"RET", {}}})); + append_main(bad, {{"PUSH_CONST_STR", {"S0"}}, {"STORE_LOCAL", {"safe_text"}}, + {"CALL", {"safe_text", "0"}}, {"POP", {}}, {"RET", {}}}); + rejected_module(bad, "raw local function name cannot shadow a checked direct target"); + + bad = opaque; + append_main(bad, {{"LOAD_GLOBAL", {"callback", "fn()->text"}}, + {"STORE_LOCAL", {"callback"}}, {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}}); + rejected_module(bad, "global load metadata cannot manufacture a checked callable"); + + bad = opaque; + bad.structs.push_back({"CallbackBox", {{"callback", "fn()->text"}}}); + bad.functions.insert(bad.functions.end() - 1, + function("read_box", {"box:CallbackBox"}, "void", {{"STORE_LOCAL", {"box"}}, + {"LOAD_LOCAL", {"box"}}, {"GET_FIELD", {"callback"}}, {"STORE_LOCAL", {"callback"}}, + {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}})); + append_main(bad, {{"RET", {}}}); + rejected_module(bad, "field type metadata cannot manufacture a checked callable"); + + bad = opaque; + bad.enums.push_back({"Choice", {{"Callback", "text"}}}); + append_main(bad, {{"PUSH_CONST_STR", {"S0"}}, {"NEW_VARIANT", {"Choice::Callback", "1"}}, + {"UNWRAP_VARIANT", {"1", "Choice", "fn()->text"}}, {"STORE_LOCAL", {"callback"}}, + {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}}); + rejected_module(bad, "enum result metadata cannot manufacture a checked callable"); + + bad = opaque; + append_main(bad, {{"INTEROP_CALL", {"intrinsic", "foreign_callback", "0", "fn()->text"}}, + {"STORE_LOCAL", {"callback"}}, {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}}); + rejected_module(bad, "interop result metadata cannot manufacture a checked callable"); + + bad = opaque; + append_main(bad, {{"PUSH_CONST", {"1"}}, {"PUSH_CONST", {"2"}}, {"ADD", {"fn()->text"}}, + {"STORE_LOCAL", {"callback"}}, {"CALL", {"callback", "0"}}, {"POP", {}}, {"RET", {}}}); + rejected_module(bad, "arithmetic result metadata cannot manufacture a checked callable"); +} +} // namespace + +int main() { + try { positive_encodings(); negative_contracts(); class_callable_contracts(); } + catch (const std::exception &error) { + std::cerr << "Unexpected exception: " << error.what() << '\n'; + return 1; + } + if (failures) return 1; + std::cout << "PASS: " << checks << " binding-reference storage and lifetime checks\n"; + return 0; +} diff --git a/tests/language/random-generators.ny b/tests/language/random-generators.ny index 4dc50fd6..7e57977f 100644 --- a/tests/language/random-generators.ny +++ b/tests/language/random-generators.ny @@ -17,9 +17,9 @@ end fn fn check_float_range(lower: f64, upper: f64, input: i64) let stream = random_generator.new(input) - let reference = stream.clone() - let first = reference.next_i32() - let second = reference.next_i32() + let reference_stream = stream.clone() + let first = reference_stream.next_i32() + let second = reference_stream.next_i32() let actual = stream.range_f64(lower, upper) require(is_finite(actual) and actual >= lower and actual < upper, "instance finite half-open interval") require(stream.next_i32() == second, "instance float range consumes one draw") diff --git a/tests/lsp_matrix_protocol.py b/tests/lsp_matrix_protocol.py index a242e179..2fc757f9 100644 --- a/tests/lsp_matrix_protocol.py +++ b/tests/lsp_matrix_protocol.py @@ -264,6 +264,80 @@ def test_multiline_headers_receiver_and_ownership_bindings(self) -> None: result, _ = completion("main begin paragraph\n consider 42\n when observed then\n say obs|\n end consider\nend paragraph") self.assertEqual(set(result), {"observed"}) + def test_mutable_and_variadic_parameters_keep_names_types_and_locations(self) -> None: + source = """sample receives mutable current-value as number and variable old-value as text and + more mutable remaining-values as number + returns number begin paragraph + say | + give current-value +end paragraph +""" + result, notes = completion(source) + self.assertEqual(set(symbols(result)), {"sample", "current-value", "old-value", "remaining-values"}) + self.assertEqual(result["current-value"]["detail"], "mutable current-value as number") + self.assertEqual(result["old-value"]["detail"], "variable old-value as text") + self.assertEqual(result["remaining-values"]["detail"], "more mutable remaining-values as number") + self.assertEqual(notes[0]["params"]["diagnostics"], []) + located = source.replace("say |", "say current-v|alue") + replies, _ = protocol.session([opened(located.replace("|", "")), request("definition", located), + request("hover", located, identifier=3)]) + self.assertEqual(replies[2][0]["range"]["start"], {"line": 0, "character": 24}) + self.assertIn("mutable current-value as number", replies[3]["contents"]["value"]) + for modifiers in ("mutable", "mut", "variable", "more mutable", "more mut", "more variable"): + with self.subTest(modifiers=modifiers): + result, _ = completion(f"sample receives\n {modifiers} input-value as number begin paragraph\n say input-|\nend paragraph\n") + self.assertEqual(set(result), {"input-value"}) + self.assertEqual(result["input-value"]["detail"], f"{modifiers} input-value as number") + result, _ = completion(f"main begin paragraph\n value operation is anonymous receives {modifiers} input-value as number returns number begin paragraph\n say input-|\n give 0\n end paragraph\nend paragraph\n") + self.assertEqual(set(result), {"input-value"}) + + def test_parameter_modifier_keyword_completion(self) -> None: + for source, expected in ( + ("sample receives |", {"mutable", "mut", "variable", "reference", "ref", "more"}), + ("sample receives more mu|", {"mutable", "mut"}), + ("sample receives first as number and mu|", {"mutable", "mut"}), + ("sample receives first as number,\n mu|", {"mutable", "mut"}), + ("sample receives first as number,\n more mu|", {"mutable", "mut"}), + ("sample receives first as number and re|", {"reference", "ref"}), + ("sample receives mutable |", set()), + ("sample receives mut |", set()), + ("sample receives reference |", set()), + ("sample receives ref |", set()), + ("sample receives value-name as reference |", {"to"}), + ("sample receives value-name as ref |", {"to"}), + ("main begin paragraph\n evaluate sample with reference |", {"to"}), + ("main begin paragraph\n evaluate sample with ref |", {"to"}), + ("main begin paragraph\n say sample with more mu|", set()), + ): + with self.subTest(source=source): + result, _ = completion(source) + keywords = {name for name, item in result.items() if item.get("detail") == "Matrix language"} + self.assertEqual(keywords, expected) + + def test_reference_parameters_preserve_referent_type_and_definition(self) -> None: + source = """update receives first-value as number and reference current-value as number + returns number begin paragraph + set current-value to current-value plus first-value + give current-v|alue +end paragraph +""" + result, notes = completion(source) + self.assertEqual(set(result), {"current-value"}) + self.assertEqual(result["current-value"]["detail"], "reference current-value as number") + self.assertEqual(notes[0]["params"]["diagnostics"], []) + replies, _ = protocol.session([opened(source.replace("|", "")), request("definition", source)]) + self.assertEqual(replies[2][0]["range"]["start"], {"line": 0, "character": source.index("current-value")}) + result, _ = completion(source.replace("first-value as number and reference", "\n reference")) + self.assertEqual(set(result), {"current-value"}) + result, _ = completion(source.replace("reference current-value", "ref current-value")) + self.assertEqual(set(result), {"current-value"}) + self.assertEqual(result["current-value"]["detail"], "ref current-value as number") + + def test_short_reference_type_preserves_member_completion(self) -> None: + source = 'Point begin record\n field count as number\nend record\nmain receives point as ref to Point begin paragraph\n say point.|\nend paragraph\n' + result, _ = completion(source) + self.assertEqual(set(result), {"count"}) + def test_non_capturing_paragraph_and_escaped_names_with_spaces(self) -> None: source = """value global-count is 1 main receives outer-param as number begin paragraph diff --git a/tests/lsp_semantic_protocol.py b/tests/lsp_semantic_protocol.py index 71e63cc5..2c1460b6 100644 --- a/tests/lsp_semantic_protocol.py +++ b/tests/lsp_semantic_protocol.py @@ -77,6 +77,24 @@ def completion(source: str, marker: str = "|", *, extra: list[dict] | None = Non class SemanticProtocol(unittest.TestCase): + def test_reference_parameter_name_and_definition(self) -> None: + for modifier in ('ref', 'reference', 'mut', 'mutable'): + with self.subTest(modifier=modifier): + source = f'fn update({modifier} amount: i64) -> i64\n amount = amount + 1\n return amo|unt\nend fn\n' + result, notes = completion(source) + self.assertEqual(set(result), {'amount'}) + self.assertEqual(result['amount']['detail'], modifier + ' amount: i64') + replies, _ = session([opened(source.replace('|', '')), query('definition', source, '|')]) + self.assertEqual(replies[2][0]['range']['start'], {'line': 0, 'character': 11 + len(modifier)}) + self.assertEqual(notes[0]['params']['diagnostics'], []) + + def test_long_mutability_and_reference_type_aliases(self) -> None: + result, _ = completion('fn main()\n let mutable total: i64 = 1\n println(tot|al)\nend fn\n') + self.assertEqual(set(result), {'total'}) + source = 'struct Point\n count: i64\nend struct\nfn main(point: reference)\n println(point.|)\nend fn\n' + result, _ = completion(source) + self.assertEqual(set(result), {'count'}) + def test_formatted_text_holes_and_nested_literals(self) -> None: prefix = 'fn main()\n let height: f64 = -1.6\n' for value in ('$"height: {hei|ght}"', '$"{height|}"', diff --git a/tests/matrix/parameter_contract.py b/tests/matrix/parameter_contract.py new file mode 100644 index 00000000..1cbfe6ff --- /dev/null +++ b/tests/matrix/parameter_contract.py @@ -0,0 +1,682 @@ +#!/usr/bin/env python3 +"""Mutable copies and caller-binding references agree across both frontends/routes.""" + +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] + +# Matching fixtures make aliasing observable before a function returns. Merely +# copying parameter values back afterward cannot satisfy this contract. +MATRIX = '''book parameter_contract +Changed begin record + field code as number +end record +write-then-raise receives reference target as number begin paragraph + set target to 90 + raise Changed with code being 1 +end paragraph +local-copy receives mutable amount as number and variable adjustment as number returns number begin paragraph + set amount to amount plus adjustment + set adjustment to 100 + give amount +end paragraph +replace-rest receives mutable first as number and more mutable rest as number returns number begin paragraph + set first to first plus 1 + set rest to [8 becomes number, 9 becomes number] + give first plus (rest at 0) plus (rest at 1) +end paragraph +legacy-rest receives more variable rest as number returns number begin paragraph + set rest to [7 becomes number] + give rest at 0 +end paragraph +bump receives reference target as number returns nothing begin paragraph + set target to target plus 1 +end paragraph +aliases receives reference first as number and reference second as number returns number begin paragraph + set first to first plus 1 + set second to second plus 10 + set first to first plus second + give second +end paragraph +forward receives reference target as number returns nothing begin paragraph + evaluate bump with reference to target +end paragraph +recurse receives count as number and reference target as number returns nothing begin paragraph + when count is greater than 0 then + set target to target plus 1 + evaluate recurse with target being reference to target, count being count minus 1 + set target to target plus 10 + end when +end paragraph +mutable-forward receives mutable target as number returns number begin paragraph + evaluate forward with reference to target + give target +end paragraph +shadow receives reference target as number returns nothing begin paragraph + evaluate bump with reference to target + when true then + variable target as number is 100 + evaluate bump with reference to target + say target + end when + set target to target plus 1 +end paragraph +scalars receives reference integer-value as override integer and reference byte-value as override byte and reference truth as boolean and reference fraction as floating and reference label as text returns nothing begin paragraph + set integer-value to integer-value plus 2 + set byte-value to 255 becomes override byte + set truth to not truth + set fraction to fraction plus 0.25 + set label to label plus "!" +end paragraph +main returns override integer begin paragraph + variable total as number is 5 + say local-copy with adjustment being 2, amount being total + say total + say replace-rest with 2, 10, 20 + say legacy-rest with more 1, 2 + say aliases with second being reference to total, first being reference to total + say total + evaluate forward with target being reference to total + evaluate recurse with count being 3, target being reference to total + say total + say mutable-forward with total + say total + when true then + variable total as number is 40 + evaluate bump with reference to total + say total + end when + say total + evaluate shadow with reference to total + say total + set total to total plus 1 + say local-copy with total, 3 + say total + variable small as override integer is 4 + variable octet as override byte is 0 becomes override byte + variable truth as boolean is false + variable fraction as floating is 1.25 + variable label as text is "updated" + evaluate scalars with integer-value being reference to small, byte-value being reference to octet, truth being reference to truth, fraction being reference to fraction, label being reference to label + say small + say octet + say truth + say fraction + say label + attempt + evaluate write-then-raise with reference to total + caught Changed as problem + say total + end attempt + say total + give 0 +end paragraph +''' + +NY = '''module parameter_contract +struct Changed + code: i64 +end struct +fn write_then_raise(ref target: i64) + target = 90 + raise Changed { code: 1 } +end fn +fn local_copy(mut amount: i64, mut adjustment: i64) -> i64 + amount = amount + adjustment + adjustment = 100 + return amount +end fn +fn replace_rest(mut first: i64, mut ..rest: i64) -> i64 + first = first + 1 + rest = [8 as i64, 9 as i64] + return first + rest[0] + rest[1] +end fn +fn legacy_rest(mut ..rest: i64) -> i64 + rest = [7 as i64] + return rest[0] +end fn +fn bump(ref target: i64) + target = target + 1 +end fn +fn aliases(ref first: i64, ref second: i64) -> i64 + first = first + 1 + second = second + 10 + first = first + second + return second +end fn +fn forward(ref target: i64) + bump(ref target) +end fn +fn recurse(count: i64, ref target: i64) + if count > 0 then + target = target + 1 + recurse(count - 1, ref target) + target = target + 10 + end if +end fn +fn mutable_forward(mut target: i64) -> i64 + forward(ref target) + return target +end fn +fn shadow(ref target: i64) + bump(ref target) + if true then + let mut target: i64 = 100 + bump(ref target) + println(target) + end if + target = target + 1 +end fn +fn scalars(ref integer_value: i32, ref byte_value: u8, ref truth: bool, ref fraction: f64, ref label: text) + integer_value = integer_value + 2 + byte_value = 255 as u8 + truth = not truth + fraction = fraction + 0.25 + label = label + "!" +end fn +fn main() -> i32 + let mut total: i64 = 5 + println(local_copy(total, 2)) + println(total) + println(replace_rest(2, 10, 20)) + println(legacy_rest(1, 2)) + println(aliases(ref total, ref total)) + println(total) + forward(ref total) + recurse(3, ref total) + println(total) + println(mutable_forward(total)) + println(total) + if true then + let mut total: i64 = 40 + bump(ref total) + println(total) + end if + println(total) + shadow(ref total) + println(total) + total = total + 1 + println(local_copy(total, 3)) + println(total) + let mut small: i32 = 4 + let mut octet: u8 = 0 as u8 + let mut truth: bool = false + let mut fraction: f64 = 1.25 + let mut label: text = "updated" + scalars(ref small, ref octet, ref truth, ref fraction, ref label) + println(small) + println(octet) + println(truth) + println(fraction) + println(label) + attempt + write_then_raise(ref total) + fault Changed as problem + println(total) + end attempt + println(total) + return 0 +end fn +''' +EXPECTED = '7\n5\n20\n7\n32\n32\n66\n67\n66\n41\n66\n101\n68\n72\n69\n6\n255\n1\n1.5\nupdated!\n90\n90\n' + +CALLBACK_NY = '''module reference_callbacks +fn bump(ref target: i64) + target = target + 1 +end fn +fn ordinary(amount: i64) -> i64 + return amount + 10 +end fn +fn invoke(worker: fn(i64) -> i64, ref target: i64) + target = worker(target) +end fn +fn choose_callback(worker: fn(i64) -> i64) -> fn(i64) -> i64 + return worker +end fn +fn main() -> i32 + let mut total: i64 = 5 + bump(ref total) + let callback = ordinary + println(callback(total)) + invoke(ordinary, ref total) + println(total) + let returned = choose_callback(ordinary) + let copied = returned + println(copied(2)) + return 0 +end fn +''' + +CALLBACK_MATRIX = '''book reference-callbacks +read Callback from parameter_callbacks +bump receives reference target as number begin paragraph + set target to target plus 1 +end paragraph +ordinary receives amount as number returns number begin paragraph + give amount plus 10 +end paragraph +invoke receives worker as Callback and reference target as number begin paragraph + set target to worker with target +end paragraph +choose-callback receives worker as Callback returns Callback begin paragraph + give worker +end paragraph +main returns override integer begin paragraph + variable total as number is 5 + evaluate bump with reference to total + value operation is the paragraph ordinary + say operation with total + evaluate invoke with the paragraph ordinary, reference to total + say total + value returned is choose-callback with the paragraph ordinary + value copied is the paragraph returned + say copied with 2 + give 0 +end paragraph +''' + +TEXT_NY = '''module reference_text_operations +fn decorated(label: text) -> text + return label + "!" +end fn +fn shorten(ref label: text) + label = label.substr(1, 2) +end fn +fn from_array(ref label: text) + let values: array = ["new"] + label = values[0] +end fn +fn from_function(ref label: text) + label = decorated(label) +end fn +fn main() -> i32 + let mut label: text = "abcd" + shorten(ref label) + println(label) + from_array(ref label) + println(label) + from_function(ref label) + println(label) + return 0 +end fn +''' + +TEXT_MATRIX = '''book reference-text-operations +decorated receives label as text returns text begin paragraph + give label plus "!" +end paragraph +shorten receives reference label as text begin paragraph + set label to label.substr with 1, 2 +end paragraph +from-array receives reference label as text begin paragraph + value values as array of text is ["new"] + set label to values at 0 +end paragraph +from-function receives reference label as text begin paragraph + set label to decorated with label +end paragraph +main returns override integer begin paragraph + variable label as text is "abcd" + evaluate shorten with reference to label + say label + evaluate from-array with reference to label + say label + evaluate from-function with reference to label + say label + give 0 +end paragraph +''' + +ALIASES_NY = '''module parameter_aliases +struct Parcel + item: i64 +end struct +fn adjust(mutable amount: i64, mut adjustment: i64, reference first: i64, ref second: i64) -> i64 + amount = amount + adjustment + adjustment = 99 + first = first + amount + second = second + 1 + return amount +end fn +fn increment(reference target: i64) + target = target + 1 +end fn +fn relay(ref target: i64) + increment(reference target) +end fn +fn rest(mutable ..items: i64) -> i64 + items = [4 as i64] + return items[0] +end fn +fn touch(sample: reference) + sample.item = 23 +end fn +fn main() -> i32 + let mutable total: i64 = 5 + println(adjust(total, 2, reference total, ref total)) + println(total) + relay(reference total) + println(total) + println(rest(1, 2)) + let mutable original = Parcel { item: 17 } + let first_handle: ref = reference original + let second_handle: reference = ref original + touch(first_handle) + println(second_handle.item) + original = Parcel { item: 29 } + second_handle.item = 31 + println(original.item) + println(first_handle.item) + return 0 +end fn +''' + +ALIASES_MATRIX = '''book parameter-aliases +Parcel begin record + field item as number +end record +adjust receives mut amount as number and mutable adjustment as number and ref first as number, reference second as number returns number begin paragraph + set amount to amount plus adjustment + set adjustment to 99 + set first to first plus amount + set second to second plus 1 + give amount +end paragraph +increment receives ref target as number begin paragraph + set target to target plus 1 +end paragraph +relay receives reference target as number begin paragraph + evaluate increment with ref to target +end paragraph +rest receives more mut items as number returns number begin paragraph + set items to [4 becomes number] + give items at 0 +end paragraph +touch receives sample as ref to Parcel begin paragraph + set sample.item to 23 +end paragraph +main returns override integer begin paragraph + variable total as number is 5 + say adjust with amount being total, adjustment being 2, first being reference to total, second being ref to total + say total + evaluate relay with ref to total + say total + say rest with 1, 2 + variable original is build Parcel with item being 17 + value first-handle as reference to Parcel is ref to original + value second-handle as ref to Parcel is reference to original + evaluate touch with first-handle + say second-handle.item + set original to build Parcel with item being 29 + set second-handle.item to 31 + say original.item + say first-handle.item + give 0 +end paragraph +''' + + +def main() -> int: + 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) + parser.add_argument('--llvm', choices=('ON', 'OFF'), default='OFF') + args = parser.parse_args() + compiler = args.compiler.resolve(strict=True) + interpreter = args.interpreter.resolve(strict=True) + 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-parameter-contract-') as directory: + root = Path(directory) + common = [compiler, '--no-stdlib', '-I', root] + if args.stdlib: + common += ['--sdk-path', args.stdlib.resolve(strict=True)] + + def run(command, status=0): + result = subprocess.run(command, cwd=root, env=environment, + stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120) + assert result.returncode == status, (list(map(str, command)), result.returncode, + result.stdout[:6000], result.stderr[:6000]) + return result + + for language, source in (('ny', NY), ('matrix', MATRIX)): + path = root / ('parameter-contract.' + language) + path.write_text(source, encoding='utf-8') + expected = path.with_suffix('.stdout') + expected.write_text(EXPECTED, encoding='utf-8') + routes = 'all' if args.llvm == 'ON' else 'text-interpreter,binary-interpreter,bundle-text,bundle-binary' + run([sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, + '--source', path, '--expected-stdout', expected, '--expected-exit', '0', + '--compiler-arg=--no-stdlib', '--routes', routes, + '--work-dir', root / (language + '-routes'), '--strict']) + checks += 6 if args.llvm == 'ON' else 4 + if args.llvm == 'ON': + executable = root / ('parameter-' + language + '-unmanaged') + run([*common, '--quiet', '--native', '--unmanaged', '-o', executable, path]) + executed = run([executable]) + assert (executed.stdout, executed.stderr) == (EXPECTED, ''), (language, executed) + checks += 1 + analysis = json.loads(run([*common, '--analyze', '--semantic-index', path]).stdout) + assert analysis['success'] and analysis['semantic'], analysis + checks += 1 + + # Existing callbacks remain usable alongside addressed bindings and as + # ordinary function-valued parameters of a direct reference callee. + # Native indirect calls retain their pre-existing unsupported status. + (root / 'parameter_callbacks.ny').write_text( + 'module parameter_callbacks\npub type Callback = fn(i64) -> i64\n', + encoding='utf-8') + for name, ny, matrix, stdout, native in ( + ('callbacks', CALLBACK_NY, CALLBACK_MATRIX, '16\n16\n12\n', False), + ('text-operations', TEXT_NY, TEXT_MATRIX, 'bc\nnew\nnew!\n', True), + ('keyword-aliases', ALIASES_NY, ALIASES_MATRIX, '7\n13\n14\n4\n23\n29\n31\n', True), + ): + for language, source in (('ny', ny), ('matrix', matrix)): + path = root / (name + '.' + language) + path.write_text(source, encoding='utf-8') + expected = path.with_suffix('.stdout') + expected.write_text(stdout, encoding='utf-8') + native_enabled = native and args.llvm == 'ON' + routes = 'all' if native_enabled else 'text-interpreter,binary-interpreter,bundle-text,bundle-binary' + run([sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, + '--source', path, '--expected-stdout', expected, '--expected-exit', '0', + '--compiler-arg=--no-stdlib', '--compiler-arg=-I', + '--compiler-arg=' + str(root), '--routes', routes, + '--work-dir', root / (name + '-' + language + '-routes'), '--strict']) + checks += 6 if native_enabled else 4 + if native_enabled: + executable = root / (name + '-' + language + '-unmanaged') + run([*common, '--quiet', '--native', '--unmanaged', '-o', executable, path]) + executed = run([executable]) + assert (executed.stdout, executed.stderr) == (stdout, ''), (name, language, executed) + checks += 1 + + # Both source imports and source-less binary libraries must preserve + # the parameter mode while forwarding a binding across frontends. + for provider_language in ('ny', 'matrix'): + provider = root / ('provider.' + provider_language) + provider.write_text( + 'module provider\npub fn bump(ref target: i64)\ntarget = target + 1\nend fn\n' + if provider_language == 'ny' else + 'book provider\npublic bump receives reference target as number begin paragraph\n' + 'set target to target plus 1\nend paragraph\n', encoding='utf-8') + consumer_language = 'matrix' if provider_language == 'ny' else 'ny' + consumer = root / ('consumer.' + consumer_language) + consumer.write_text( + 'import provider.*\nfn relay(ref target: i64)\nbump(ref target)\nend fn\n' + 'fn main() -> i32\nlet mut total: i64 = 41\nrelay(ref total)\nprintln(total)\nreturn 0\nend fn\n' + if consumer_language == 'ny' else + 'book consumer\nread everything from provider\n' + 'relay receives reference target as number begin paragraph\n' + 'evaluate bump with target being reference to target\nend paragraph\n' + 'main returns override integer begin paragraph\nvariable total as number is 41\n' + 'evaluate relay with reference to total\nsay total\ngive 0\nend paragraph\n', encoding='utf-8') + library = root / 'provider.nil' + for dependency in ('source', 'library'): + if dependency == 'library': + run([*common, '--quiet', '--no-bundle', '--emit-library', + '--emit-binary-nil', '-o', library, provider]) + provider.unlink() + for encoding, flags in (('text', []), ('binary', ['--emit-binary-nil']), + *((('native', ['--native']),) if args.llvm == 'ON' else ())): + output = root / ('import-' + provider_language + '-' + dependency + '-' + encoding) + run([*common, '--quiet', '--no-bundle', *flags, '-o', output, consumer]) + command = [output] if encoding == 'native' else [interpreter, '--no-ai', output] + result = run(command) + assert (result.stdout, result.stderr) == ('42\n', ''), result + checks += 1 + library.unlink() + consumer.unlink() + + def program(language, body, declarations=''): + if language == 'ny': + return declarations + '\nfn main() -> i32\n' + body + '\nreturn 0\nend fn\n' + return 'book parameter_invalid\n' + declarations + '\nmain returns override integer begin paragraph\n' + body + '\ngive 0\nend paragraph\n' + + declarations = { + 'ny': 'fn bump(ref target: i64)\ntarget = target + 1\nend fn\n', + 'matrix': 'bump receives reference target as number begin paragraph\nset target to target plus 1\nend paragraph\n', + } + # Short and full keywords are lexical aliases, including when a + # reference form must be rejected. Check semantic rejection rather + # than accepting a parser error as equivalent behavior. + for language in ('ny', 'matrix'): + for reference_word in ('ref', 'reference'): + if language == 'ny': + bump = f'fn bump({reference_word} target: i64)\ntarget = target + 1\nend fn\n' + alias_invalid = ( + ('immutable', f'let total: i64 = 1\nbump({reference_word} total)', bump), + ('wrong-width', f'let mutable total: i32 = 1\nbump({reference_word} total)', bump), + ('standalone-scalar', f'let mutable total: i64 = 1\nlet borrowed = {reference_word} total', ''), + ('variadic', '', f'fn invalid({reference_word} ..items: i64)\nend fn\n'), + ) + else: + bump = f'bump receives {reference_word} target as number begin paragraph\nset target to target plus 1\nend paragraph\n' + alias_invalid = ( + ('immutable', f'value total as number is 1\nevaluate bump with {reference_word} to total', bump), + ('wrong-width', f'variable total as override integer is 1\nevaluate bump with {reference_word} to total', bump), + ('standalone-scalar', f'variable total as number is 1\nvalue borrowed is {reference_word} to total', ''), + ('variadic', '', f'invalid receives more {reference_word} items as number begin paragraph\nend paragraph\n'), + ) + for name, body, extra in alias_invalid: + path = root / ('alias-' + reference_word + '-' + name + '.' + language) + path.write_text(program(language, body, extra), encoding='utf-8') + for flags in ([], ['--no-typecheck']): + output = root / 'protected-alias-output' + output.write_bytes(b'previous successful artifact') + result = run([*common, '--quiet', '--no-bundle', *flags, '-o', output, path], 1) + assert result.stderr.strip(), (name, language, reference_word, result) + assert not any(marker in result.stderr for marker in ('Parse error', 'Syntax error')), result + assert output.read_bytes() == b'previous successful artifact', (name, language, reference_word) + checks += 1 + + invalid = [ + ('immutable-local', 'let total: i64 = 1\nbump(ref total)', + 'value total as number is 1\nevaluate bump with reference to total'), + ('wrong-width', 'let mut total: i32 = 1\nbump(ref total)', + 'variable total as override integer is 1\nevaluate bump with reference to total'), + ('wrong-kind', 'let mut total: text = "1"\nbump(ref total)', + 'variable total as text is "1"\nevaluate bump with reference to total'), + ('missing-reference', 'let mut total: i64 = 1\nbump(total)', + 'variable total as number is 1\nevaluate bump with total'), + ('temporary', 'bump(ref (1 as i64))', + 'evaluate bump with reference to (1 becomes number)'), + ('expression', 'let mut total: i64 = 1\nbump(ref (total + 1))', + 'variable total as number is 1\nevaluate bump with reference to (total plus 1)'), + ('index', 'let mut totals: array = [1]\nbump(ref totals[0])', + 'variable totals as array of number is [1]\nevaluate bump with reference to (totals at 0)'), + ('function-value', 'let callback = bump', 'value callback is the paragraph bump'), + ] + for name, ny, matrix in invalid: + for language, body in (('ny', ny), ('matrix', matrix)): + source = program(language, body, declarations[language]) + path = root / (name + '.' + language) + path.write_text(source, encoding='utf-8') + for flags in ([], ['--emit-binary-nil'], ['--no-typecheck'], + ['--no-typecheck', '--emit-binary-nil'], + *([['--native']] if args.llvm == 'ON' else [])): + output = root / 'protected-output' + output.write_bytes(b'previous successful artifact') + result = run([*common, '--quiet', '--no-bundle', *flags, + '-o', output, path], 1) + assert result.stderr.strip(), (name, language, flags, result) + assert output.read_bytes() == b'previous successful artifact', (name, language, flags) + checks += 1 + + # A callable expression is not a direct call to its nested function + # identifiers. Callee traversal must not accidentally authorize a + # reference-parameter function as an ordinary function-pointer value. + for name, body, extra in [ + ('conditional-callee', '(if true then bump else bump end if)(1)', ''), + ('indexed-callee', '[bump][0](1)', ''), + ('nested-callee', 'choose(bump)(1)', + 'fn choose(worker: fn(i64) -> void) -> fn(i64) -> void\nreturn worker\nend fn\n'), + ]: + path = root / (name + '.ny') + path.write_text(program('ny', body, declarations['ny'] + extra), encoding='utf-8') + analysis = json.loads(run([*common, '--analyze', path], 1).stdout) + assert not analysis['success'] and any('must be called directly' in item['message'] + for item in analysis['diagnostics']), (name, analysis) + checks += 1 + for flags in ([], ['--no-typecheck']): + output = root / 'protected-indirect-call' + output.write_bytes(b'previous successful artifact') + run([*common, '--quiet', '--no-bundle', *flags, '-o', output, path], 1) + assert output.read_bytes() == b'previous successful artifact', (name, flags) + checks += 1 + + # Declaration-time restrictions and hidden aliases must be enforced + # even when the function is never invoked or checking is disabled. + invalid_declarations = [ + ('generic', 'fn invalid(ref target: T)\nend fn\n', + 'invalid of type T receives reference target as T begin paragraph\nend paragraph\n'), + ('readonly-value', 'fn readonly(target: i64)\ntarget = 2\nend fn\n', + 'readonly receives target as number begin paragraph\nset target to 2\nend paragraph\n'), + ('readonly-forward', 'fn readonly(target: i64)\nbump(ref target)\nend fn\n', + 'readonly receives target as number begin paragraph\nevaluate bump with reference to target\nend paragraph\n'), + ('global', 'let mut total: i64 = 1\nfn use_global()\nbump(ref total)\nend fn\n', + 'variable total as number is 1\nuse-global begin paragraph\nevaluate bump with reference to total\nend paragraph\n'), + ('default', 'fn invalid(ref target: i64 = 1)\nend fn\n', + 'invalid receives reference target as number defaulting to 1 begin paragraph\nend paragraph\n'), + ('variadic', 'fn invalid(ref ..target: i64)\nend fn\n', + 'invalid receives more reference target as number begin paragraph\nend paragraph\n'), + ('array', 'fn invalid(ref target: array)\nend fn\n', + 'invalid receives reference target as array of number begin paragraph\nend paragraph\n'), + ('record', 'struct Parcel\nitem: i64\nend struct\nfn invalid(ref target: Parcel)\nend fn\n', + 'Parcel begin record\nfield item as number\nend record\ninvalid receives reference target as Parcel begin paragraph\nend paragraph\n'), + ('field', 'struct Parcel\nitem: i64\nend struct\nfn invalid()\nlet mut record = Parcel { item: 1 }\nbump(ref record.item)\nend fn\n', + 'Parcel begin record\nfield item as number\nend record\ninvalid begin paragraph\nvariable sample is build Parcel with item being 1\nevaluate bump with reference to sample.item\nend paragraph\n'), + ('lambda', 'fn invalid()\nlet callback = fn(ref target: i64)\ntarget = 1\nend fn\nend fn\n', + 'invalid begin paragraph\nvalue callback is anonymous receives reference target as number begin paragraph\nset target to 1\nend paragraph\nend paragraph\n'), + ('method', 'struct Parcel\nitem: i64\nend struct\nimpl Parcel\nfn invalid(self, ref target: i64)\ntarget = 1\nend fn\nend impl\n', + 'Parcel begin record\nfield item as number\nend record\nParcel begin implementation\ninvalid receives reference target as number begin paragraph\nset target to 1\nend paragraph\nend implementation\n'), + ] + for name, ny, matrix in invalid_declarations: + for language, declaration in (('ny', ny), ('matrix', matrix)): + path = root / ('declaration-' + name + '.' + language) + path.write_text(program(language, '', declarations[language] + declaration), encoding='utf-8') + for flags in ([], ['--no-typecheck']): + output = root / 'protected-declaration' + output.write_bytes(b'previous successful artifact') + result = run([*common, '--quiet', '--no-bundle', *flags, '-o', output, path], 1) + assert result.stderr.strip(), (name, language, result) + assert output.read_bytes() == b'previous successful artifact', (name, language, flags) + checks += 1 + print(f'PASS: {checks} mutable/reference parameter checks') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tests/tools/class_polymorphism.py b/tests/tools/class_polymorphism.py index f8d77505..75df3d1e 100644 --- a/tests/tools/class_polymorphism.py +++ b/tests/tools/class_polymorphism.py @@ -42,7 +42,7 @@ def program(body: str, extra: str = "") -> str: "downcast_return": program("", f"fn make() -> Derived {{ return {base} }}"), "downcast_field": program(f"let value = Holder {{ item: {base} }}", "struct Holder { item: Derived }"), "unrelated": program("let value: Base = Other { value: 1 }"), - "reference_covariance": program(f"let value = {derived}\nlet reference: ref = ref value"), + "reference_covariance": program(f"let value = {derived}\nlet borrowed: ref = ref value"), "pointer_covariance": program("let pointer = allocate(1)\nlet base: ptr = pointer"), "array_covariance": program(f"let values = [{derived}]\nlet bases: array = values"), "inferred_if_base_first": program(f"let value = if true then {base} else {derived} end if"), @@ -149,9 +149,9 @@ class Child inherits Parent end class fn main() -> i32 let child = Child { value: 7 } -let reference = ref child -println(reference.read()) -println(reference.inherited()) +let borrowed = ref child +println(borrowed.read()) +println(borrowed.inherited()) let parent: Parent = child let parent_reference = ref parent println(parent_reference.read()) diff --git a/tests/tools/signature_contract.py b/tests/tools/signature_contract.py index a79cfd1a..839a7741 100644 --- a/tests/tools/signature_contract.py +++ b/tests/tools/signature_contract.py @@ -120,6 +120,32 @@ def query(marked, *, name='main.ny', dependencies=None, mode='workspace', assert value['label'] == 'combine receives first as number, second-value as number returns number', value assert value['active_parameter'] == 1 assert query(matrix.replace('|9', '9').replace('first being 7', 'first being |7'), name='first.matrix', status=0)['active_parameter'] == 0 + for spelling in ('mutable', 'mut', 'variable'): + mutable = matrix.replace('first as number', spelling + ' first as number') + value = query(mutable, name='mutable-' + spelling + '.matrix', status=0) + assert value['parameters'][0]['label'] == 'mutable first as number', value + assert value['parameters'][0]['mutable'] is True + assert value['parameters'][1]['mutable'] is False + value = query(ny.replace('first: i32', 'mut first: i32'), name='mutable.ny', status=0) + assert value['parameters'][0]['label'] == 'mut first: i32', value + assert value['parameters'][0]['mutable'] is True + value = query(ny.replace('first: i32', 'mutable first: i32'), name='long-mutable.ny', status=0) + assert value['parameters'][0]['label'] == 'mut first: i32', value + assert value['parameters'][0]['mutable'] is True + reference_ny = ('fn update(ref amount: i64) -> i64\namount = amount + 1\nreturn amount\nend fn\n' + 'fn main() -> i64\nlet mut total: i64 = 4\nreturn update(ref |total)\nend fn\n') + reference_matrix = ('book references\nupdate receives reference amount as number returns number begin paragraph\n' + 'set amount to amount plus 1\ngive amount\nend paragraph\n' + 'main returns number begin paragraph\nvariable total as number is 4\n' + 'give update with amount being reference to |total\nend paragraph\n') + for name, source, label in (('reference.ny', reference_ny, 'ref amount: i64'), + ('long-reference.ny', reference_ny.replace('ref ', 'reference '), 'ref amount: i64'), + ('reference.matrix', reference_matrix, 'reference amount as number'), + ('short-reference.matrix', reference_matrix.replace('reference ', 'ref '), 'reference amount as number')): + value = query(source, name=name, status=0) + assert value['parameters'][0]['label'] == label, value + assert value['parameters'][0]['reference'] is True, value + assert value['parameters'][0]['mutable'] is True, value assert query(matrix.replace('second_value being |9', 'unknown being |9'), name='unknown.matrix', status=1)['active_parameter'] is None assert query(matrix.replace('second_value being |9, first being 7', '|nothing'), name='empty.matrix', status=1)['active_parameter'] == 0 bare = matrix_decl + 'main returns number begin paragraph\ngive combine with |\nend paragraph\n' @@ -171,6 +197,28 @@ def query(marked, *, name='main.ny', dependencies=None, mode='workspace', variadic = 'fn values(first: i32, ..rest: i32) -> i32\nreturn first\nend fn\nfn main() -> i32\nreturn values(1, 2, |3)\nend fn\n' value = query(variadic, status=0) assert value['active_parameter'] == 1 and value['parameters'][1]['variadic'] is True + assert value['parameters'][1]['label'] == '..rest: i32', value + assert value['parameters'][1]['type'] == 'array', value + value = query(variadic.replace('..rest:', 'mut ..rest:'), name='mutable-variadic.ny', status=0) + assert value['parameters'][1]['label'] == 'mut ..rest: i32', value + assert value['parameters'][1]['type'] == 'array', value + assert value['parameters'][1]['mutable'] and value['parameters'][1]['variadic'] + assert value['active_parameter'] == 1 + value = query(variadic.replace('..rest:', 'mutable ..rest:'), name='long-mutable-variadic.ny', status=0) + assert value['parameters'][1]['label'] == 'mut ..rest: i32', value + assert value['parameters'][1]['mutable'] and value['parameters'][1]['variadic'] + for mode in ('', 'mutable ', 'mut ', 'variable '): + matrix_variadic = ('book signatures.variadic\n' + 'combine receives first as override integer, more ' + mode + 'rest as override integer ' + 'returns override integer begin paragraph\ngive first\nend paragraph\n' + 'main returns override integer begin paragraph\n' + 'give combine with first being 1, more 2, |3\nend paragraph\n') + value = query(matrix_variadic, name='variadic-' + (mode.strip() or 'plain') + '.matrix', status=0) + assert value['parameters'][1]['label'] == ('more ' + ('mutable ' if mode else '') + + 'rest as override integer'), value + assert value['parameters'][1]['type'] == 'array', value + assert value['parameters'][1]['mutable'] == bool(mode) and value['parameters'][1]['variadic'] + assert value['active_parameter'] == 1 method = ('struct Counter\nvalue: i32\nend struct\nimpl Counter\n' 'fn add(self: Counter, amount: i32) -> i32\nreturn amount\nend fn\n' 'pub fn create(amount: i32) -> Counter\nreturn Counter { value: amount }\nend fn\nend impl\n' diff --git a/vscode/src/signatureModel.ts b/vscode/src/signatureModel.ts index de1138f9..86cb4149 100644 --- a/vscode/src/signatureModel.ts +++ b/vscode/src/signatureModel.ts @@ -11,7 +11,7 @@ export interface CompilerSignature { length: number; sources: SemanticSource[]; label: string; - parameters: Array<{ name: string; type: string; label: string; variadic: boolean }>; + parameters: Array<{ name: string; type: string; label: string; variadic: boolean; mutable?: boolean; reference?: boolean }>; active_parameter: number | null; return_type: string; } @@ -48,7 +48,9 @@ export function parseCompilerSignature(value: unknown): CompilerSignature | unde const parameter = value.parameters[index]; if (!record(parameter) || !singleLine(parameter.name) || !parameter.name || !singleLine(parameter.type) || !singleLine(parameter.label) || !parameter.label || !value.label.includes(parameter.label) || - typeof parameter.variadic !== "boolean" || (parameter.variadic && index !== value.parameters.length - 1)) return fail(); + typeof parameter.variadic !== "boolean" || (parameter.variadic && index !== value.parameters.length - 1) || + (parameter.mutable !== undefined && typeof parameter.mutable !== "boolean") || + (parameter.reference !== undefined && typeof parameter.reference !== "boolean")) return fail(); } return value as unknown as CompilerSignature; } diff --git a/vscode/src/test/grammar.test.ts b/vscode/src/test/grammar.test.ts index 550f50d4..47738e07 100644 --- a/vscode/src/test/grammar.test.ts +++ b/vscode/src/test/grammar.test.ts @@ -54,6 +54,21 @@ test("grammar compiles and scopes canonical declarations", async () => { assert.ok(scopesForFragment(grammar, "type UserId = i64", "UserId").includes("entity.name.type.ny")); }); +test("Ny short and long mutability/reference aliases retain keyword and binding scopes", async () => { + const grammar = await loadNyGrammar(); + assert.ok(grammar); + for (const word of ["mut", "mutable"]) { + assert.ok(scopesForFragment(grammar, `fn update(${word} amount: i64)`, word).includes("storage.modifier.ny")); + assert.ok(scopesForFragment(grammar, `let ${word} amount: i64 = 0`, word).includes("storage.modifier.mutable.ny")); + assert.ok(scopesForFragment(grammar, `let ${word} amount: i64 = 0`, "amount").includes("variable.other.readwrite.ny")); + } + for (const word of ["ref", "reference"]) { + assert.ok(scopesForFragment(grammar, `fn update(${word} amount: i64)`, word).includes("keyword.operator.word.ny")); + assert.ok(scopesForFragment(grammar, `update(${word} amount)`, word).includes("keyword.operator.word.ny")); + assert.ok(scopesForFragment(grammar, `fn read(item: ${word})`, word).includes("keyword.operator.word.ny")); + } +}); + test("Ny explicit interpolation scopes expressions, nested strings, and literal braces", async () => { const grammar = await loadNyGrammar(); assert.ok(grammar); diff --git a/vscode/src/test/matrixGrammar.test.ts b/vscode/src/test/matrixGrammar.test.ts index a59ef170..71900c39 100644 --- a/vscode/src/test/matrixGrammar.test.ts +++ b/vscode/src/test/matrixGrammar.test.ts @@ -133,6 +133,53 @@ test("Matrix folds ASCII keywords while preserving complete hyphenated and escap assert.equal(escaped.tokens.filter(t => t.scopes.some(s => s.startsWith("keyword"))).length, 1); }); +test("Matrix mutable parameter modifiers preserve name scopes in every header position", async () => { + const grammar = await loadMatrixGrammar(); + for (const prefix of ["receives mutable", "receives more mutable", "receives more variable", + "receives first as number and mutable", "receives first as number, variable", + "receives first as number and more mutable", "receives first as number, more variable"]) { + const line = `sample ${prefix} input-value as number returns number begin paragraph`; + assertScope(grammar, line, "input-value", "variable.parameter"); + if (prefix.includes("mutable")) assertScope(grammar, line, "mutable", "storage.modifier"); + } + for (const line of [" mutable input-value as number", " more mutable input-value as number", + " MUTABLE input-value AS NUMBER"]) { + assertScope(grammar, line, "input-value", "variable.parameter"); + assertScope(grammar, line, line.includes("MUTABLE") ? "MUTABLE" : "mutable", "storage.modifier"); + } + assertScope(grammar, "variable input-value as number is 0", "input-value", "variable.other.readwrite"); +}); + +test("Matrix binding references scope parameters separately from reference expressions and types", async () => { + const grammar = await loadMatrixGrammar(); + for (const prefix of ["receives reference", "receives first as number and reference", + "receives first as number, reference", ""]) { + const line = prefix ? `update ${prefix} amount as number begin paragraph` : " reference amount as number"; + assertScope(grammar, line, "reference", "storage.modifier"); + assertScope(grammar, line, "amount", "variable.parameter"); + } + assertScope(grammar, "update with amount being reference to total", "reference", "storage.type.builtin"); + assertScope(grammar, "item as reference to Record", "reference", "storage.type.builtin"); +}); + +test("Matrix short mut/ref aliases preserve parameter and reference scopes", async () => { + const grammar = await loadMatrixGrammar(); + for (const prefix of ["receives mut", "receives more mut", "receives first as number and mut", + "receives ref", "receives first as number, ref"]) { + const line = `update ${prefix} amount as number begin paragraph`; + assertScope(grammar, line, "amount", "variable.parameter"); + assertScope(grammar, line, prefix.includes("mut") ? "mut" : "ref", "storage.modifier"); + } + assertScope(grammar, " MUT amount as number", "MUT", "storage.modifier"); + assertScope(grammar, " REF amount as number", "amount", "variable.parameter"); + assertScope(grammar, "update with amount being ref to total", "ref", "storage.type.builtin"); + assertScope(grammar, "item as ref to Record", "ref", "storage.type.builtin"); + for (const word of ["mut", "mutable"]) + assertScope(grammar, `change on ${word} receiver begin paragraph`, word, "keyword.other.modifier"); + for (const name of ["mut-value", "ref-value", "mutable-value", "reference-value"]) + assertScope(grammar, "say " + name, name, "variable.other.readwrite"); +}); + test("Matrix scopes imports, named calls, and precise type overrides", async () => { const grammar = await loadMatrixGrammar(); assertScope(grammar, "read everything from ny.lang.text", "ny.lang.text", "entity.name.namespace"); diff --git a/vscode/src/test/signatureModel.test.ts b/vscode/src/test/signatureModel.test.ts index ea2480e1..e997e4a8 100644 --- a/vscode/src/test/signatureModel.test.ts +++ b/vscode/src/test/signatureModel.test.ts @@ -40,6 +40,24 @@ test("signature accepts empty argument regions and does not require successful c assert.equal(parseCompilerSignature(undefined), undefined); }); +test("signature accepts optional mutable parameter metadata and rendered modifiers", () => { + const value = fixture(); + value.parameters[0]!.mutable = true; + value.parameters[0]!.label = "mutable first as number"; + value.label = "combine receives mutable first as number, second as text returns text"; + value.parameters[1]!.mutable = false; + assert.deepEqual(parseCompilerSignature(value), value); +}); + +test("signature accepts reference parameter metadata without changing its scalar type", () => { + const value = fixture(); + value.parameters[0]!.mutable = true; + value.parameters[0]!.reference = true; + value.parameters[0]!.label = "reference first as number"; + value.label = "combine receives reference first as number, second as text returns text"; + assert.deepEqual(parseCompilerSignature(value), value); +}); + test("signature rejects invalid identities, byte boundaries and parameter metadata", () => { for (const mutate of [ (v: any) => v.schema = "nil.signature.v2", @@ -60,7 +78,9 @@ test("signature rejects invalid identities, byte boundaries and parameter metada (v: any) => v.parameters[0].name = "", (v: any) => v.parameters[0].type = "\0", (v: any) => v.parameters[0].variadic = true, - (v: any) => v.parameters[1].variadic = "false" + (v: any) => v.parameters[1].variadic = "false", + (v: any) => v.parameters[0].mutable = "true", + (v: any) => v.parameters[0].reference = "true" ]) { const value = fixture(); mutate(value); assert.throws(() => parseCompilerSignature(value)); } diff --git a/vscode/syntaxes/matrix.tmLanguage.json b/vscode/syntaxes/matrix.tmLanguage.json index cd7c8f8e..cd54b547 100644 --- a/vscode/syntaxes/matrix.tmLanguage.json +++ b/vscode/syntaxes/matrix.tmLanguage.json @@ -111,7 +111,7 @@ "declarations": { "patterns": [ { - "match": "((?