Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 $<TARGET_FILE:ny_class_vm_tests>)

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 $<TARGET_FILE:nil_binding_reference_contract_tests>)
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)
Expand Down Expand Up @@ -1119,6 +1125,11 @@ if(BUILD_TESTING)
--compiler $<TARGET_FILE:nilcompiler> --interpreter $<TARGET_FILE:nilinterpreter>
--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 $<TARGET_FILE:nilcompiler> --interpreter $<TARGET_FILE:nilinterpreter>
--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 $<TARGET_FILE:nilcompiler> --interpreter $<TARGET_FILE:nilinterpreter>
Expand Down
5 changes: 5 additions & 0 deletions docs/advanced/nil-format.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,11 @@ reference semantics. `ref<Struct>` 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.
Expand Down
135 changes: 135 additions & 0 deletions docs/design/NIL-0019-binding-reference-parameters.md
Original file line number Diff line number Diff line change
@@ -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<Record>`, 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<Struct>` 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<T>` 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.
1 change: 1 addition & 0 deletions docs/design/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
85 changes: 80 additions & 5 deletions docs/language-reference/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,15 @@ arrays of supported structural tuples, `ptr<i32/i64/u8/bool>`, and validated
concrete struct layouts. Generic struct
schemas are materialized for supported field layouts, including `f64`/`u8`
fields, nested struct handles and `ref<Struct>`. 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
Expand All @@ -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<Struct>` 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<Record>` / `reference<Record>`, 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
Expand Down
3 changes: 2 additions & 1 deletion docs/language-reference/lexical-structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
20 changes: 17 additions & 3 deletions docs/language-reference/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,21 +154,35 @@ default.
Native nested structs and `ref<Struct>` 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<T>`; dereference syntax belongs to raw `ptr<T>` 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<T>` 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<i64>` values:
the reference cannot be stored, returned, or captured. Existing `ref<Struct>`
object identity and rebinding behavior are unchanged.

`reference` is an alias for `ref` in Ny, including `reference<Struct>` 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
Expand Down
15 changes: 15 additions & 0 deletions matrix/MATRIX-GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading