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
37 changes: 25 additions & 12 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2298,37 +2298,40 @@ if(BUILD_TESTING)
)
set_tests_properties(ny.qualified-enum-contract PROPERTIES
LABELS "typecheck;analysis;rc" TIMEOUT 120)
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)
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
average-f64 average-f64-matrix)
if(parity_fixture MATCHES "-matrix$")
set(parity_frontend matrix)
else()
set(numeric_frontend ny)
set(parity_frontend ny)
endif()
add_ny_route_test(
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"
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.${numeric_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/${numeric_fixture}.${numeric_frontend}"
--expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${numeric_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.${numeric_fixture} PROPERTIES
set_tests_properties(ny.tools.${parity_fixture} PROPERTIES
LABELS "tools;native;rc" SKIP_RETURN_CODE 77 TIMEOUT 240)
endif()
endforeach()
Expand All @@ -2351,6 +2354,16 @@ if(BUILD_TESTING)
)
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
69 changes: 69 additions & 0 deletions docs/standard-library/floating-averages.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Floating-point averages

`average_f64(items: array<f64>) -> Option<f64>` is available from
`nil.std.core` in both Ny and Matrix. The legacy `ny.lang.core` import resolves
to the same implementation.

| Input | Result |
| --- | --- |
| Empty array | `None`. |
| Nonempty array of finite values | `Some(mean)`, with a finite approximation to the arithmetic mean inside the input's minimum/maximum interval. |
| Any NaN or infinity | The original ordered `sum_f64(items) / count` computation, wrapped in `Some`. |

The function leaves the input and its aliases unchanged. It takes O(n) time
and O(1) auxiliary storage. `sum_f64` retains its existing ordered, uncompensated
addition behavior, including intermediate overflow.

```ny
import nil.std.core

fn main() -> i32
let mean = average_f64([1e308, 1e308]).unwrap()
println(mean == 1e308)
return 0
end fn
```

```matrix
book examples.floating-averages

read everything from nil.std.core

main returns override integer begin paragraph
value mean is (average-f64 with arr being [1e308, 1e308]).unwrap with nothing
say mean equals 1e308
give 0
end paragraph
```

The previous implementation overflowed while summing the two values in these
examples. The updated implementation keeps two compensated subtotals: values
of magnitude at most one remain unscaled, while larger values are divided by
a power of two greater than the array length. This leaves headroom for the
large subtotal without underflowing the small inputs. The final merge retains
addition residuals and restores the original scale when cancellation makes
that safe. A final range clamp prevents rounding from escaping the input
interval, including at the largest finite value.

The correction uses a magnitude-ordered addition residual, as described in
[Ogita, Rump and Oishi, *Accurate Sum and Dot Product*, section 1.1](https://www.tuhh.de/ti3/paper/rump/OgRuOi05.pdf).
This implementation does not provide an exact accumulator, guaranteed correct
rounding, a universal ULP bound, or order-independent results. Severe
cancellation can still erase a representable residual: for example,
`[1e100, 1e308, 1.7976931348623157e308, -1e308, -1.7976931348623157e308]`
can produce zero instead of a value near `2e99`. That accuracy limit remains
follow-up work. Values close to zero can also round to zero normally.

For nonfinite inputs, retaining ordered summation is deliberate. A NaN
propagates; opposite infinities produce NaN. Intermediate finite overflow can
also affect the result: `[1e308, 1e308, -infinity]` still produces NaN after
the first two terms overflow. This compatibility path does not use the finite
averaging algorithm.

Paired Ny and Matrix fixtures cover ordinary means, extreme magnitudes,
cancellation, subnormal values and rounding ties, empty arrays, signed zeros,
nonfinite inputs and source preservation. Finite reference values are derived
from exact rational sums of the binary64 inputs. These fixtures run through
the textual/binary interpreter, bundles, LLVM JIT/AOT, standalone
assembler/linker pipelines, and installed source/binary libraries. Their
individual tolerances establish the tested cases, not a general error bound.
12 changes: 10 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,12 @@ 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.
The [floating-average reference](floating-averages.md) defines bounded finite
averaging, nonfinite compatibility behavior and numerical accuracy limits.

```text
nilstd/
Expand Down Expand Up @@ -305,6 +311,8 @@ This changes the older library behavior around NaNs. It does not change
the language's IEEE operators: NaN remains unequal to itself under `==`,
and ordinary ordered comparisons with NaN remain false. `sum_f64` and
`average_f64` continue to propagate NaN through ordinary arithmetic.
For finite inputs, `average_f64` uses compensated subtotals to avoid sum
overflow; see the [averaging contract](floating-averages.md) for accuracy limits.
Sorting preserves the original relative order of signed zeros and NaNs.

The explicitly named insertion sorts remain O(n²). `merge_sort_i32` retains
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