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
74 changes: 63 additions & 11 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2298,36 +2298,39 @@ 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(parity_fixture IN ITEMS scientific-literals scientific-literals-matrix
integer-literal-widths integer-literal-widths-matrix
checked-text-spans checked-text-spans-matrix
checked-i64-conversion checked-i64-conversion-matrix)
if(parity_fixture MATCHES "-matrix$")
set(parity_frontend matrix)
else()
set(scientific_fixture scientific-literals-matrix)
set(parity_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.${parity_fixture}
--source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${parity_fixture}.${parity_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${parity_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.${parity_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/${parity_fixture}.${parity_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${parity_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.${parity_fixture} PROPERTIES
LABELS "tools;native;rc" SKIP_RETURN_CODE 77 TIMEOUT 240)
endif()
endforeach()
Expand All @@ -2340,6 +2343,26 @@ 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_test(
NAME ny.checked-integer-conversion-contract
COMMAND "${Python3_EXECUTABLE}"
"${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/checked_integer_conversion_contract.py"
--compiler $<TARGET_FILE:nilcompiler>
--stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src"
--llvm "${NIL_ENABLE_LLVM}"
)
set_tests_properties(ny.checked-integer-conversion-contract PROPERTIES
LABELS "native;rc" SKIP_RETURN_CODE 77 TIMEOUT 120)
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 +2657,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
8 changes: 6 additions & 2 deletions docs/standard-library/index.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Standard-library status

Ny and Matrix share `nilstd`, one standard library compiled to NIL. Its 73 active
sources (68 Ny and five Matrix) form 16 logical SDK modules, including `prelude`.
Ny and Matrix share `nilstd`, one standard library compiled to NIL. Its 74 active
sources (68 Ny and six Matrix) form 16 logical SDK modules, including `prelude`.
Support remains evidence-scoped. Focused fixtures exercise `nilstd` and `nillib`
through textual/binary NIL, bundles, LLVM JIT and AOT, and standalone
assembler/linker pipelines. Local SDK qualification records the exact source
Expand All @@ -16,6 +16,10 @@ three-component lengths, finite-value checks, and checked normalization shared
by Ny and Matrix.
The [random-generator reference](random.md) defines independent mutable
streams, reproducible seeds, cloning, and bounded integer/floating sampling.
The [checked text-span reference](text-spans.md) defines exact byte ranges,
empty-span results, and overflow-safe compatibility slicing.
The [checked integer-conversion reference](integer-conversion.md) covers
decimal parsing and matching `Result` behavior on VM and native routes.

```text
nilstd/
Expand Down
52 changes: 52 additions & 0 deletions docs/standard-library/integer-conversion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Checked decimal integer conversion

`Convert.try_to_i32(value: text) -> Result<i32, text>` and
`Convert.try_to_i64(value: text) -> Result<i64, text>` parse signed decimal
integers without panicking on malformed input or overflow. Import
`nil.std.core` from either language. Matrix uses the method spellings
`Convert.try-to-i32` and `Convert.try-to-i64`.

Accepted input contains an optional leading `+` or `-` followed by one or more
ASCII decimal digits. Leading zeros and signed zero are valid. Whitespace,
radix prefixes, digit separators, decimal points, exponent notation, Unicode
digits and trailing characters are rejected. The whole text must match;
there is no trimming or partial parse.

`Result.Ok` contains the exact signed value, including either width's minimum
and maximum. `Result.Error` contains text prefixed by the called conversion's
intrinsic name, such as `convert.try_to_i64: value is outside the i64 range`.
Error details distinguish empty input, a sign without digits, an invalid
digit, and overflow. Parsing stops at the first error; an overflowing prefix
can therefore be reported before a later invalid character. `try_to_i32`
first parses within `i64` bounds, then checks the narrower destination.

```ny
import nil.std.core

fn main() -> i32
match Convert.try_to_i64("9223372036854775807")
Result.Ok(value) -> println(value)
Result.Error(message) -> println(message)
end match
return 0
end fn
```

The interpreter and native runtime share the integer parser. LLVM lowering
constructs the same `Result<i64, text>` value used by the interpreter, with a
64-bit success payload and managed error text. The additive `nyrt_try_i64`
runtime entry point follows the existing checked-i32 convention: success
returns `1`, writes the value, and clears the error; failure returns `0`,
zeros an available value output and supplies an error when requested.

The native C entry point accepts NUL-terminated text. It has no length
parameter and cannot represent embedded NUL bytes; native language text
retains the framework's NUL-free contract. The interpreter's length-aware
parser rejects an embedded NUL as an invalid digit.

Direct ABI tests and paired Ny/Matrix fixtures cover boundaries, malformed
input, exact errors, returned results and error-text lifetime. The fixtures
run through text/binary NIL, bundles, LLVM JIT/AOT, standalone assembler/linker
execution and installed source/binary libraries. This is a native claim for
these checked decimal integer APIs; other `Convert` operations retain their
separate support boundaries.
66 changes: 66 additions & 0 deletions docs/standard-library/text-spans.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Checked text spans

`nil.std.text` provides checked access to text bytes. Both Ny and Matrix use
the same Matrix-authored implementation in `string_checked.matrix`.

| Function | Result |
| --- | --- |
| `try_substring(s: text, start: i64, length: i64) -> Option<text>` | `Some` containing the entire requested byte span, or `None` if any part is outside the text. |
| `try_char_at(s: text, index: i64) -> Option<text>` | `Some` containing one byte at an existing index, or `None`. |

A valid span requires `0 <= start <= s.len()` and
`0 <= length <= s.len() - start`. Bounds are checked at their original `i64`
width before conversion to the text runtime's index type. Validation uses
subtraction after checking the start, so extreme inputs cannot overflow an
addition and appear valid.

Empty spans are valid: `try_substring("", 0, 0)` and
`try_substring("abc", 3, 0)` both return `Some("")`. A negative length, a
start beyond the end even with zero length, or a span extending past the end
returns `None`. `try_char_at("abc", 3)` returns `None` because there is no
byte at the end position. Neither operation changes the source text.

```ny
import nil.std.text

fn main() -> i32
match try_substring("frame:42", 6, 2)
Option.Some(value) -> println(value)
Option.None -> println("missing field")
end match
return 0
end fn
```

```matrix
book text-span-example
read everything from nil.std.text

main returns number begin paragraph
consider try-substring with s being "frame:42", start being 6, length being 2
when Option.Some holding span then say span
when Option.None then say "missing field"
end consider
give 0
end paragraph
```

Both examples print `42`. Legacy `ny.lang.text` imports remain aliases of the
same module.

These APIs use byte positions, as do the existing text runtime primitives.
They do not validate UTF-8 boundaries or count Unicode scalars or grapheme
clusters. A one-byte result can be part of a multibyte sequence. Native text
remains NUL-free; these helpers do not change its representation.

The compatibility helpers keep their existing policy: `substring` returns
empty text for an invalid start or nonpositive count and clips an oversized
positive count to the remaining bytes. Its clamp now handles even the maximum
`i64` count without overflow. `char_at` returns empty text for an invalid
index. Use the checked forms when an invalid request must be distinguishable
from an empty result.

Paired Ny/Matrix fixtures cover exact spans, empty results, invalid bounds,
signed extrema, UTF-8 byte positions, aliases, and the compatibility clamp.
They are registered for text/binary NIL, bundles, LLVM JIT/AOT, standalone
assembler/linker execution, and installed source/binary libraries.
Loading
Loading