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
62 changes: 51 additions & 11 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2298,36 +2298,37 @@ if(BUILD_TESTING)
)
set_tests_properties(ny.qualified-enum-contract PROPERTIES
LABELS "typecheck;analysis;rc" TIMEOUT 120)
foreach(scientific_frontend IN ITEMS ny matrix)
if(scientific_frontend STREQUAL "ny")
set(scientific_fixture scientific-literals)
foreach(numeric_fixture IN ITEMS scientific-literals scientific-literals-matrix
integer-literal-widths integer-literal-widths-matrix)
if(numeric_fixture MATCHES "-matrix$")
set(numeric_frontend matrix)
else()
set(scientific_fixture scientific-literals-matrix)
set(numeric_frontend ny)
endif()
add_ny_route_test(
ny.routes.${scientific_fixture}
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.${scientific_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.stdout"
ny.routes.${numeric_fixture}
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${numeric_fixture}.${numeric_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${numeric_fixture}.stdout"
--expected-exit 0
--routes all
--compiler-arg=--sdk-path
--compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src
)
if(TARGET nilassembler AND TARGET nillinker)
add_test(
NAME ny.tools.${scientific_fixture}
NAME ny.tools.${numeric_fixture}
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/native_toolchain_pipeline.py"
--compiler $<TARGET_FILE:nilcompiler>
--assembler $<TARGET_FILE:nilassembler>
--linker $<TARGET_FILE:nillinker>
--runtime $<TARGET_FILE:nilruntime>
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.${scientific_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.stdout"
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${numeric_fixture}.${numeric_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${numeric_fixture}.stdout"
--stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src"
--work-dir "${CMAKE_CURRENT_BINARY_DIR}/tests/tools"
)
set_tests_properties(ny.tools.${scientific_fixture} PROPERTIES
set_tests_properties(ny.tools.${numeric_fixture} PROPERTIES
LABELS "tools;native;rc" SKIP_RETURN_CODE 77 TIMEOUT 240)
endif()
endforeach()
Expand All @@ -2340,6 +2341,16 @@ if(BUILD_TESTING)
)
set_tests_properties(ny.scientific-literals-contract PROPERTIES
LABELS "typecheck;analysis;rc" TIMEOUT 120)
add_test(
NAME ny.integer-literals-contract
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/integer_literals_contract.py"
--compiler $<TARGET_FILE:nilcompiler>
--interpreter $<TARGET_FILE:nilinterpreter>
--llvm "${NIL_ENABLE_LLVM}"
)
set_tests_properties(ny.integer-literals-contract PROPERTIES
LABELS "typecheck;analysis;rc" TIMEOUT 180)
add_ny_route_test(
ny.routes.canonical-option-result-methods
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/canonical-option-result-methods.ny"
Expand Down Expand Up @@ -2634,6 +2645,35 @@ if(BUILD_TESTING)
absolute-overflow
core-absolute-overflow-reject.stderr
)
foreach(absolute_frontend IN ITEMS ny matrix)
if(absolute_frontend STREQUAL "ny")
set(absolute_fixture core-absolute-i64-overflow)
else()
set(absolute_fixture core-absolute-i64-overflow-matrix)
endif()
add_ny_route_test(
ny.routes.${absolute_fixture}
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${absolute_fixture}.${absolute_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/routes/empty.stdout"
--expected-stderr "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/core-absolute-i64-overflow.stderr"
--expected-exit 1
--routes text-interpreter,binary-interpreter,bundle-text,bundle-binary
--compiler-arg=--sdk-path
--compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src
)
if(NIL_ENABLE_LLVM)
add_ny_route_test(
ny.routes.native-${absolute_fixture}
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${absolute_fixture}.${absolute_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/routes/empty.stdout"
--expected-stderr "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/core-absolute-i64-overflow.native.stderr"
--expected-exit 1
--routes llvm-jit,llvm-aot
--compiler-arg=--sdk-path
--compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src
)
endif()
endforeach()
add_ny_core_algorithm_reject_test(
ny.routes.core-gcd-overflow-reject
gcd-overflow
Expand Down
62 changes: 62 additions & 0 deletions docs/design/NIL-0007-integer-literal-widths.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# NIL-0007: Integer literal widths and range validation

**Status:** Implemented.

**Scope:** Shared Ny/Matrix literal semantics, array inference and diagnostics.

## Problem

Every integer literal previously inferred `i32`, including values that need
64 bits. A large literal could print correctly through the VM's value carrier
yet truncate when stored or used in arithmetic. The expression
`-9223372036854775807 - 1` consequently evaluated to zero before conversion to
an `i64` parameter. Array inference also retained the first element's type,
allowing a later `i64` value to narrow silently into an inferred `array<i32>`.
This also broke the standard library's `abs_i64` overflow guard: zero panicked
and the minimum signed value wrapped instead of reporting overflow.

## Decision

Decimal integer literals use `i32` when representable and `i64` otherwise,
within the signed 64-bit range. Negated literal boundary values support
`-2147483648` as `i32` and `-9223372036854775808` as `i64` without decoding an
unrepresentable positive intermediate. Values outside that range are source
errors, including in editor analysis and when type checking is disabled.

Hexadecimal literals retain their established mask behavior: values through
`0xFFFFFFFF` infer `i32`, while larger supported values infer `i64`. An
`i32` mask is interpreted at 32 bits when stored or used by typed arithmetic;
an explicit `0xFFFFFFFF as i64` retains the positive value `4294967295`.
Positive hexadecimal values above `0x7FFFFFFFFFFFFFFF` are rejected. Negating
`0x8000000000000000` can represent the signed 64-bit minimum; this does not
introduce unsigned 64-bit values.

Inferred integer arrays join `i32` and `i64` elements to `i64`, in either order.
This applies to typed variables as well as literal elements. It does not make
`array<i32>` and `array<i64>` interchangeable; callers must still supply the
declared element type at an array boundary.

## Compatibility and limits

Ordinary arithmetic still uses operand types and wraps at its resolved width.
`2147483647 + 1` remains `i32` arithmetic. An outer `i64` destination or
parameter does not widen that inner operation. Explicit scalar casts and
storage conversions continue to narrow by retaining low bits.

Existing programs that relied on implicit narrowing of large decimal literals
must state the intended `i32` conversion. Existing 32-bit hexadecimal masks
retain their width. The two frontends share these rules; Matrix's intended
universal `number` default and broader contextual expression typing remain
separate decisions. `--no-typecheck` retains its legacy untyped arithmetic
contract; range validation is still mandatory.

## Verification

Paired source fixtures exercise scalar boundaries, both forms of match,
globals, nested calls, explicit wrapping, hexadecimal masks and integer arrays.
Core-library checks cover `abs_i64(0)`, wide negative inputs and rejection of
the signed minimum on both frontends and all enabled execution routes.
Rejection tests cover ordinary expressions, patterns, unused defaults, editor
analysis, unchecked compilation and preservation of existing output files.
Qualify both frontends through textual/binary NIL, bundles, LLVM JIT/AOT and
the assembler/linker pipelines, including installed source/binary libraries.
1 change: 1 addition & 0 deletions docs/design/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ not assigned architecture identifiers.
| NIL-0004 | [Debugger state belongs to the VM](../../notebook/decisions/NIL-0004-debugger-state-belongs-to-the-vm.md) | Implemented as a preview |
| NIL-0005 | [Generated non-void fallthrough is explicit](../../notebook/decisions/NIL-0005-generated-nonvoid-fallthrough-is-explicit.md) | Implemented and verified |
| NIL-0006 | [Opt-in AI control for NIL programs](NIL-0006-ai-module.md) | Partial Windows prototype; interpreter introspection and Unix transport remain proposed |
| NIL-0007 | [Integer literal widths and range validation](NIL-0007-integer-literal-widths.md) | Implemented |
| 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
6 changes: 6 additions & 0 deletions docs/language-reference/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,14 @@ not supply placeholder values.
42 # i32
42 as i64 # explicit width
0xFF # hex
2147483648 # inferred i64
```

Decimal literals infer `i32` or `i64` by representable range. Hexadecimal
literals through `0xFFFFFFFF` retain 32-bit mask semantics. Out-of-range
integers are rejected before code generation; see the
[integer width contract](types.md#scalar-values).

### Float Literals
```ny
3.14 # f64
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 @@ -23,7 +23,14 @@ Scalar casts to these targets fail explicitly. Do not use their acceptance in
a declaration as evidence of supported arithmetic or layout. `char`, general
references, and arbitrary foreign types also need independent qualification.

Integer literals initially infer `i32`; floating literals infer `f64`.
Decimal integer literals infer `i32` when representable, otherwise `i64`.
Negated literal boundaries include `-2147483648` (`i32`) and
`-9223372036854775808` (`i64`). Values outside signed 64-bit range are source
errors. Floating literals infer `f64`.

Hexadecimal values through `0xFFFFFFFF` retain `i32` mask semantics; larger
supported values infer `i64`. Positive values above `0x7FFFFFFFFFFFFFFF` are
rejected; negated `0x8000000000000000` can represent the signed minimum.
Use explicit types or casts when width matters:

```ny
Expand All @@ -35,8 +42,9 @@ let fraction: f64 = 0.5
An outer `i64` destination or parameter does not widen arithmetic inside its
initializer or argument. Bind or cast an operand before that arithmetic:
`(2147483647 as i64) + 1` is `2147483648`, while `2147483647 + 1` wraps at
`i32` before assignment. Oversized bare integer operands currently lack a
range diagnostic; see [F30](../../matrix/docs/next-version-findings.md#f30--large-integer-expressions-can-narrow-before-an-i64-argument-conversion).
`i32` before assignment. See [NIL-0007](../design/NIL-0007-integer-literal-widths.md)
for literal ranges, hexadecimal compatibility and the boundary between literal
inference and contextual typing.

### Arithmetic and conversions

Expand Down Expand Up @@ -89,6 +97,12 @@ println(values[0])
values[1] = 7
```

Inferred integer arrays containing both `i32` and `i64` elements use `i64`
regardless of element order. For example, `[1, 2147483648]` and
`[2147483648, 1]` both infer `array<i64>`. This also applies to typed variable
elements. Array types remain invariant: an `array<i64>` cannot be passed as
`array<i32>` through an implicit element conversion.

Typed pointers use `ptr<T>`. Allocation and deallocation are explicit:

```ny
Expand Down
56 changes: 41 additions & 15 deletions matrix/docs/next-version-findings.md
Original file line number Diff line number Diff line change
Expand Up @@ -921,9 +921,10 @@ evidence are under `build/random-library-work`.

### F30 — Large integer expressions can narrow before an i64 argument conversion

**Status:** Confirmed authoring/diagnostic gap; no inference change in this pass.
**Status:** Literal-range and mixed-integer-array fixes implemented; contextual
typing and Matrix's universal `number` default remain open.

**Evidence:** Passing `-9223372036854775807 - 1` to an `i64` parameter produces
**Evidence before the fix:** Passing `-9223372036854775807 - 1` to an `i64` parameter produces
zero on both frontends and all six routes. The emitted NIL performs `NEG i32`
and `SUB i32` before the call. The generator's normalization was correct; its
test had constructed the wrong seed. Oversized bare literals are accepted
Expand All @@ -939,16 +940,41 @@ unannotated arithmetic therefore does not yet follow the intended wider
declared types and inferred literal expressions. The probe sources, NIL and
12 successful route executions are in `build/random-library-work/width-probes`.

**Workaround:** Bind `let maximum: i64 = 9223372036854775807` in Ny or
`value maximum as number is 9223372036854775807` in Matrix, then construct the
minimum with `-maximum - 1` or `minus maximum minus 1`. The paired RNG fixtures
use this form and verify the true i64 extrema against independent oracles.
An explicit cast on the literal operand also fixes its arithmetic width.

**Next step / acceptance:** Define literal-range and contextual-inference policy
for both frontends. Diagnose values outside an inferred integer width, or adopt
specified wider inference; keep explicit wrapping arithmetic distinct from
accidental narrowing of a literal. Matrix's intended `number` default needs
matching inferred expression/array behavior and documentation. Cover nested
arithmetic, calls, arrays, editor diagnostics and all execution routes before
changing the language contract.
**Resolution:** [NIL-0007](../../docs/design/NIL-0007-integer-literal-widths.md)
defines shared range-aware inference: decimal literals use `i32` when
representable and `i64` otherwise. Signed boundary literals represent both
minimum values directly. Hexadecimal masks through `0xFFFFFFFF` retain their
historical `i32` width; larger supported hexadecimal values use `i64`. Values
outside the signed 64-bit carrier range fail before artifact output, including
unused/default expressions, editor analysis and unchecked compilation.
Mixed `i32`/`i64` arrays now infer `array<i64>` in either element order,
including elements supplied by typed variables. Array types remain invariant.
The original large-literal expression now constructs the intended i64 minimum.
This repairs the existing `abs_i64` guard in `nil.std.core`: the old SDK
panicked for zero and returned the unchanged minimum value for overflow.
The baseline reproducer is under `build/integer-width-work/abs-baseline`.

**Verification:** Paired
[Ny](../../tests/language/integer-literal-widths.ny) and
[Matrix](../../tests/language/integer-literal-widths-matrix.matrix) fixtures cover
integer boundaries, globals, nested calls, both match forms, wide array values,
explicit narrowing, retained wrapping behavior and core `abs_i64` results.
Separate paired overflow fixtures require `abs_i64` to reject the signed
minimum on every enabled execution route. The
[contract runner](../../tests/tools/integer_literals_contract.py) checks invalid
source literals and existing-artifact preservation across compilation modes,
editor diagnostics, array invariance, and the type-checking-disabled flag.
Fixtures are registered for all six routes, standalone assembler/linker
pipelines and installed source/binary-library consumption.

**Remaining context / workaround:** To widen arithmetic on small operands,
bind one operand as `i64` in Ny or `number` in Matrix before the operation.
For example, `(2147483647 as i64) + 1` retains the wider result. The signed
minimum itself can now be written directly in either language.

**Next step / acceptance:** Decide broader contextual inference and Matrix's
intended universal `number` default separately. Small literals still infer
`i32`, so `2147483647 + 1` still wraps before assignment to `i64`; a parameter
or destination annotation does not change an inner expression's width. A
future change must cover generic identities, mixed-language arrays/calls and
explicit narrow arithmetic, with matching editor and execution evidence.
7 changes: 4 additions & 3 deletions matrix/docs/ny-surface-inventory.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,10 @@ semantic weight.
| `char` | no spelling | needs independent qualification |
| `any` | no spelling | erasure/recovery is rejected |

Integer literals infer `integer`; floating literals infer `real`. Matrix keeps
Ny's promotion order `real`, `long`, `integer`, `byte` and Ny's wrapping
integer arithmetic at the resolved width.
Decimal integer literals infer `i32` or `i64` by range; 32-bit hexadecimal masks
retain `i32` inference. Floating literals infer `f64`. Matrix keeps Ny's
promotion order `f64`, `i64`, `i32`, `u8` and wrapping integer arithmetic at
the resolved width. See the shared [literal-width decision](../../docs/design/NIL-0007-integer-literal-widths.md).

### Conversions

Expand Down
14 changes: 9 additions & 5 deletions matrix/docs/types-and-text.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,18 @@ gets a message naming the real constraint instead of "unknown identifier".

### Two consequences worth knowing

**A declared `number` is 64-bit; current literal inference is still 32-bit.**
Matrix's intended ordinary integer type is the wider `number`, but unannotated
integer literals and their arithmetic currently share Ny's `i32` inference.
**A declared `number` is 64-bit; small integer literals still infer 32 bits.**
Ny and Matrix infer decimal literals as `i32` when representable and `i64`
otherwise. Negated boundary literals represent the signed minima directly;
values outside signed 64-bit range are rejected. Hexadecimal values through
`0xFFFFFFFF` retain 32-bit mask semantics. Matrix's intended universal
`number` default remains a separate language decision.
For example, `2147483647 plus 1` wraps before conversion even if assigned to
a `number` or passed to a `number` parameter. Bind an operand as `number`, or
cast it with `becomes override long`, before performing arithmetic that needs
64 bits. An `array of number` also needs correctly typed elements; its annotation
does not widen an inferred integer-literal array. This discrepancy is tracked
64 bits. Mixed `i32`/`i64` array elements now infer `array of number` in either
order; an unannotated all-small-literal array still infers `array of override integer`.
Array types remain invariant. The remaining inference questions are tracked
in [F30](next-version-findings.md#f30--large-integer-expressions-can-narrow-before-an-i64-argument-conversion).
Ny APIs accepting `i32` may instead require `becomes override integer`.

Expand Down
Loading
Loading