From 4bc00f57a3d31524e2591d7e3a788e68fff7e271 Mon Sep 17 00:00:00 2001 From: Nathan Date: Sun, 18 Oct 2026 11:53:55 -0400 Subject: [PATCH 1/2] Add checked text spans and native i64 parsing --- CMakeLists.txt | 36 +++-- docs/standard-library/index.md | 8 +- docs/standard-library/integer-conversion.md | 52 +++++++ docs/standard-library/text-spans.md | 66 +++++++++ matrix/docs/next-version-findings.md | 131 +++++++++++++++++- nilcompiler/src/integer_conversion.hpp | 75 ++++++++++ nilcompiler/src/llvm_backend.cpp | 28 ++-- nilcompiler/src/native_runtime.cpp | 85 +++++------- nilcompiler/src/native_runtime.hpp | 4 + nilcompiler/src/vm.cpp | 73 +--------- nilstd/README.md | 10 +- nilstd/src/text/package.ny | 18 +-- nilstd/src/text/string_checked.matrix | 21 +++ nilstd/src/text/string_utils.ny | 10 +- scripts/check-sdk-routes.py | 2 + .../checked-i64-conversion-matrix.matrix | 84 +++++++++++ .../checked-i64-conversion-matrix.stdout | 17 +++ tests/language/checked-i64-conversion.ny | 67 +++++++++ tests/language/checked-i64-conversion.stdout | 17 +++ .../language/checked-text-spans-matrix.matrix | 108 +++++++++++++++ .../language/checked-text-spans-matrix.stdout | 5 + tests/language/checked-text-spans.ny | 109 +++++++++++++++ tests/language/checked-text-spans.stdout | 5 + tests/native_runtime_tests.cpp | 86 ++++++++++++ .../checked_integer_conversion_contract.py | 81 +++++++++++ 25 files changed, 1031 insertions(+), 167 deletions(-) create mode 100644 docs/standard-library/integer-conversion.md create mode 100644 docs/standard-library/text-spans.md create mode 100644 nilcompiler/src/integer_conversion.hpp create mode 100644 nilstd/src/text/string_checked.matrix create mode 100644 tests/language/checked-i64-conversion-matrix.matrix create mode 100644 tests/language/checked-i64-conversion-matrix.stdout create mode 100644 tests/language/checked-i64-conversion.ny create mode 100644 tests/language/checked-i64-conversion.stdout create mode 100644 tests/language/checked-text-spans-matrix.matrix create mode 100644 tests/language/checked-text-spans-matrix.stdout create mode 100644 tests/language/checked-text-spans.ny create mode 100644 tests/language/checked-text-spans.stdout create mode 100644 tests/tools/checked_integer_conversion_contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 092bf63d..33a5135d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2298,17 +2298,19 @@ 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) + 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 @@ -2316,19 +2318,19 @@ if(BUILD_TESTING) ) 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 $ --assembler $ --linker $ --runtime $ - --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() @@ -2351,6 +2353,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 $ + --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" diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 8e47fadb..6788efe8 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -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 @@ -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/ diff --git a/docs/standard-library/integer-conversion.md b/docs/standard-library/integer-conversion.md new file mode 100644 index 00000000..bee37393 --- /dev/null +++ b/docs/standard-library/integer-conversion.md @@ -0,0 +1,52 @@ +# Checked decimal integer conversion + +`Convert.try_to_i32(value: text) -> Result` and +`Convert.try_to_i64(value: text) -> Result` 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` 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. diff --git a/docs/standard-library/text-spans.md b/docs/standard-library/text-spans.md new file mode 100644 index 00000000..cedb99c8 --- /dev/null +++ b/docs/standard-library/text-spans.md @@ -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` | `Some` containing the entire requested byte span, or `None` if any part is outside the text. | +| `try_char_at(s: text, index: i64) -> Option` | `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. diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 07f55675..1a574c13 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -755,7 +755,8 @@ all checker contracts instead of inferring provenance from the final line number ### F24 — Reflection formatting exposed missing native conversion intrinsics -**Status:** Formatter fixed; broader conversion parity remains open. +**Status:** Formatter fixed; checked i64 parsing now has native support; +broader conversion parity remains open. A pure Matrix diagnostic formatter using `Convert.char_to_i32`, `Convert.i32_to_char`, and `Convert.to_hex_padded` compiled and ran in the VM but @@ -764,6 +765,13 @@ and small Ny control-character constants. The paired Ny/Matrix fixtures exercise UTF-8, quotes, backslashes, control escaping, and declaration values through all six routes. Do not infer native support for every `Convert` intrinsic from this. +The v1 library pass also found that `Convert.try_to_i64` succeeded in both +interpreted frontends but failed LLVM lowering. Native support now constructs +the existing `Result` with the correct payload width and managed +error text. VM/native integer parsing shares one implementation; paired +fixtures and direct ABI tests pin signed extrema, invalid input and exact +errors. See the [checked integer-conversion contract](../../docs/standard-library/integer-conversion.md). + ### F25 — Fully qualified enum patterns silently miss matching values **Status:** Fixed for checked statement and expression patterns in Ny and Matrix. @@ -978,3 +986,124 @@ intended universal `number` default separately. Small literals still infer 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. + +### F31 — Text substring bounds overflowed before clamping + +**Status:** Compatibility fix and checked text-span APIs implemented. + +**Evidence:** With the prior SDK, `substring("abcd", 1, 9223372036854775807)` +returns empty text rather than `"bcd"`. Adding start and length wraps before +the bounds check, then the narrowed count is negative. The underlying text +runtime already checks the remaining length safely; the library wrapper +introduced the error. Baseline evidence is in +`build/text-core-work/substring-baseline.json` in the v1 library checkout. + +**Resolution:** Validate the start, then compare the requested length with +`size - start`. The existing helper retains its empty/clipped result policy. +Matrix-authored `try_substring` and `try_char_at` add exact checked byte access +as `Option`, including `Some("")` for valid empty spans and `None` for +invalid bounds. They retain `i64` arguments until validation and share the +same public `nil.std.text` identity across frontends and legacy imports. +See the [text-span contract](../../docs/standard-library/text-spans.md). + +**Verification:** Paired source fixtures cover whole/empty/end spans, invalid +and extreme positions/counts, UTF-8 byte positions, source preservation, +aliases, returned values and compatibility clamping. They are registered for +all execution routes, standalone assembler/linker pipelines and installed +source/binary libraries. + +**Authoring friction:** A Matrix documentation example using +`when Option.Some holding value then say value` fails because `value` is a +reserved binding name, but the diagnostic says it expected `then`. Renaming +the binding to `span` works. A future diagnostic should identify the reserved +pattern binding directly; no grammar change was made in this pass. + +### F32 — Floating averages can overflow for finite inputs + +**Status:** Confirmed open numerical bug. + +`average_f64` currently computes `sum_f64(items) / count`. For +`[1e308, 1e308]`, the intermediate sum overflows to positive infinity although +the mean `1e308` is representable. Negative inputs behave symmetrically, and +`[1e308, 1e308, -1e308]` also produces positive infinity instead of a finite +mean. Paired Ny/Matrix probes reproduce these results on all six routes; +sources and reports are under `build/text-core-work/average-overflow` in the +v1 library checkout. + +**Next step:** Implement a bounded finite-input averaging algorithm without +changing `sum_f64` or the existing empty/NaN/infinity contracts. Qualify extreme +magnitudes, cancellation, subnormals and ordinary rounding against independent +numerical oracles. Scaling the inputs is a candidate, but its loss of very +small terms under severe cancellation needs explicit consideration. + +### F33 — Native iteration over an array literal selects an absent iterator + +**Status:** Confirmed open lowering bug. + +Iterating directly over a text array literal prints its values in the VM, but +native compilation names an undefined `__ritual_iter` callee. Both Ny and +Matrix reproduce this on the prior SDK. Indexed traversal of a bound array +using `range`/`repeat while` works and is used by the checked-conversion +fixtures. Minimal programs and the VM/native comparison are preserved under +`build/convert-audit/foreach-literal` in the v1 library checkout. + +**Next step:** Carry the iterable expression's resolved array type into loop +lowering, including literals and returned arrays, and qualify element widths, +text lifetimes and empty arrays across routes. + +### F34 — Renamed module aliases survive into unresolved function calls + +**Status:** Confirmed open name-resolution bug. + +Ny `namespace words = ny.lang.text` followed by `words::substring(...)` +passes source compilation but emits a call containing the alias name rather +than the actual module owner. The VM reports an unknown function. Matrix's +`read nil.std.text as words` has the same lowering failure when combined with +an ordinary import that makes the function discoverable. These minimal cases +use the existing `substring`, so the checked-span addition did not cause the +failure. Prior-SDK sources and diagnostics are under +`build/text-core-work/friction-repros/namespace-alias.*` and +`baseline-results.json`. + +Fully qualified canonical and legacy module names work; the checked-text +fixtures exercise those spellings. Namespace renaming is distinct from the +supported built-in `ny.lang.*` to `nil.std.*` compatibility mapping. + +**Next step:** Resolve renamed import/namespace owners consistently during +checking and code generation, with mixed-language source and binary-library +tests. + +### F35 — A Matrix generic parameter can consume the next parameter + +**Status:** Confirmed open parser bug. + +A signature containing `actual as Option of text, label as text` fails at +the second parameter's `as`, reporting `expected 'begin paragraph' to open +the body` and MX0105. Moving the generic parameter last allows the equivalent +program to compile and print `ok`. The prior SDK reproduces both outcomes; +minimal sources and exact diagnostics are in +`build/text-core-work/friction-repros/generic-parameter.matrix` and +`baseline-results.json`. + +The checked-text fixtures put `Option of text` last as a temporary workaround. +**Next step:** Distinguish commas within generic arguments from commas between +function parameters, then test nested generic types and named arguments without +requiring parameter reordering. + +### F36 — Conversion intrinsics do not preserve a custom Result owner + +**Status:** Confirmed open provider-declaration validation gap. + +A user-defined `custom::Result` can be declared as the return type of a +function annotated `@intrinsic("convert.try_to_i32")`. The native ABI check +accepts its shape, but the provider constructs the standard `Result::Ok` tag; +matching the custom result misses. The VM has the same mismatch. The prior-SDK +probe returns its fallthrough sentinel `99` instead of parsed value `7` on +both routes. Evidence is under `build/text-core-work/review/provider-owner*`. + +The existing public `nil.std.core.Convert` API uses the standard Result owner +and is unaffected. The new checked-i64 provider follows the same ownership +convention; this pass tests malformed structural signatures but does not add +custom enum support. **Next step:** Reject an incompatible nominal provider +owner during source/NIL validation, or explicitly support that owner throughout +construction and matching, with matching VM/native evidence. diff --git a/nilcompiler/src/integer_conversion.hpp b/nilcompiler/src/integer_conversion.hpp new file mode 100644 index 00000000..92eb5b4d --- /dev/null +++ b/nilcompiler/src/integer_conversion.hpp @@ -0,0 +1,75 @@ +#ifndef NIL_COMPILER_INTEGER_CONVERSION_HPP +#define NIL_COMPILER_INTEGER_CONVERSION_HPP + +#include +#include +#include + +namespace ny::detail { + +struct IntegerParseResult { + bool ok = false; + std::int64_t value = 0; + const char *error = nullptr; +}; + +inline int ascii_digit_value(char character) noexcept { + const unsigned char byte = static_cast(character); + if (byte >= '0' && byte <= '9') return byte - '0'; + if (byte >= 'a' && byte <= 'z') return byte - 'a' + 10; + if (byte >= 'A' && byte <= 'Z') return byte - 'A' + 10; + return -1; +} + +// Runtime text conversion is distinct from source-literal inference. Consume +// the complete byte span, with no whitespace, separators, or implicit radix. +// Error reasons are static storage so native noexcept callers cannot allocate +// or throw while validating input. Each caller adds its public API prefix. +inline IntegerParseResult parse_signed_integer(std::string_view text, int base, + bool accept_prefix) noexcept { + if (base < 2 || base > 36) + return {false, 0, "base must be between 2 and 36"}; + if (text.empty()) + return {false, 0, "value is empty"}; + + std::size_t position = 0; + bool negative = false; + if (text[position] == '+' || text[position] == '-') { + negative = text[position] == '-'; + ++position; + } + if (accept_prefix && position + 2 <= text.size() && text[position] == '0') { + const char prefix = text[position + 1]; + if ((base == 16 && (prefix == 'x' || prefix == 'X')) || + (base == 2 && (prefix == 'b' || prefix == 'B')) || + (base == 8 && (prefix == 'o' || prefix == 'O'))) + position += 2; + } + if (position == text.size()) + return {false, 0, "value has no digits"}; + + const std::uint64_t positive_limit = + static_cast(std::numeric_limits::max()); + const std::uint64_t limit = negative ? positive_limit + 1U : positive_limit; + std::uint64_t magnitude = 0; + for (; position < text.size(); ++position) { + const int digit = ascii_digit_value(text[position]); + if (digit < 0 || digit >= base) + return {false, 0, "value contains a digit outside the requested base"}; + if (magnitude > (limit - static_cast(digit)) / + static_cast(base)) + return {false, 0, "value is outside the i64 range"}; + magnitude = magnitude * static_cast(base) + + static_cast(digit); + } + + if (!negative) + return {true, static_cast(magnitude), nullptr}; + if (magnitude == positive_limit + 1U) + return {true, std::numeric_limits::min(), nullptr}; + return {true, -static_cast(magnitude), nullptr}; +} + +} // namespace ny::detail + +#endif diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 422c585d..6442ff1c 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -2876,24 +2876,32 @@ bool NativeCodegen::generateModule(const nil_module &mod) { } else if (ann.find("@intrinsic(\"convert.try_to_i32\")") != std::string::npos || ann.find("@intrinsic(convert.try_to_i32)") != + std::string::npos || + ann.find("@intrinsic(\"convert.try_to_i64\")") != + std::string::npos || + ann.find("@intrinsic(convert.try_to_i64)") != std::string::npos) { + const bool i32_conversion = ann.find("try_to_i32") != std::string::npos; + const std::string payload_type = i32_conversion ? "i32" : "i64"; const auto result_arguments = native_generic_arguments(fn.return_type, "result"); if (fn.params.size() != 1 || native_handle_kind_for_nil_type(nil_parameter_type(fn.params[0])) != native_handle_kind::text || !result_arguments || result_arguments->size() != 2 || - (*result_arguments)[0] != "i32" || + (*result_arguments)[0] != payload_type || native_handle_kind_for_nil_type((*result_arguments)[1]) != native_handle_kind::text || impl_->current_function->arg_size() != 1 || !impl_->current_function->getReturnType()->isIntegerTy(64)) { - std::cerr << "[NativeCodegen] convert.try_to_i32 requires the exact " - "(text) -> Result ABI\n"; + std::cerr << "[NativeCodegen] convert.try_to_" << payload_type + << " requires the exact (text) -> Result<" << payload_type + << ",text> ABI\n"; return false; } - auto *value_out = - impl_->builder->CreateAlloca(llvm::Type::getInt32Ty(ctx)); + auto *parsed_type = i32_conversion ? llvm::Type::getInt32Ty(ctx) + : llvm::Type::getInt64Ty(ctx); + auto *value_out = impl_->builder->CreateAlloca(parsed_type); auto *error_out = impl_->builder->CreateAlloca(llvm::PointerType::getUnqual(ctx)); auto runtime_type = @@ -2902,8 +2910,8 @@ bool NativeCodegen::generateModule(const nil_module &mod) { llvm::PointerType::getUnqual(ctx), llvm::PointerType::getUnqual(ctx)}, false); - auto runtime = - impl_->module->getOrInsertFunction("nyrt_try_i32", runtime_type); + auto runtime = impl_->module->getOrInsertFunction( + i32_conversion ? "nyrt_try_i32" : "nyrt_try_i64", runtime_type); auto *status = impl_->builder->CreateCall( runtime_type, runtime.getCallee(), {impl_->current_function->getArg(0), value_out, error_out}); @@ -2916,10 +2924,9 @@ bool NativeCodegen::generateModule(const nil_module &mod) { status, llvm::ConstantInt::get(ctx, llvm::APInt(32, 0))), success, failure); impl_->builder->SetInsertPoint(success); - auto *parsed = - impl_->builder->CreateLoad(llvm::Type::getInt32Ty(ctx), value_out); + auto *parsed = impl_->builder->CreateLoad(parsed_type, value_out); auto *ok_variant = emit_single_payload_variant("Result::Ok", parsed, - fn.return_type, "i32"); + fn.return_type, payload_type); if (!ok_variant) return false; impl_->builder->CreateRet(ok_variant); @@ -8337,6 +8344,7 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_read_regular_bytes", &nyrt_read_regular_bytes); expose_runtime_symbol("nyrt_write_bytes_atomic", &nyrt_write_bytes_atomic); expose_runtime_symbol("nyrt_try_i32", &nyrt_try_i32); + expose_runtime_symbol("nyrt_try_i64", &nyrt_try_i64); expose_runtime_symbol("nyrt_i32_to_text", &nyrt_i32_to_text); expose_runtime_symbol("nyrt_i64_to_text", &nyrt_i64_to_text); if (auto define_error = impl_->jit->getMainJITDylib().define( diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 1fadc9ac..e83a5506 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1,5 +1,6 @@ #include "native_runtime.hpp" #include "database_runtime.hpp" +#include "integer_conversion.hpp" #include "secure_file_io.hpp" #include "time_support.hpp" @@ -420,6 +421,31 @@ void set_error(const char **error_out, std::string_view message) noexcept { } } +template +std::int32_t try_decimal_integer(const char *text, Integer *value_out, + const char **error_out, + const char *operation) noexcept { + if (value_out != nullptr) *value_out = 0; + if (error_out != nullptr) *error_out = nullptr; + const auto fail = [&](const char *reason) { + // The operation and reason are fixed internal strings, never user input. + // Format without host allocation before copying into managed error storage. + char message[160] = {}; + std::snprintf(message, sizeof(message), "%s: %s", operation, reason); + set_error(error_out, message); + return std::int32_t{0}; + }; + if (text == nullptr || value_out == nullptr) + return fail("invalid arguments"); + const auto parsed = ny::detail::parse_signed_integer(text, 10, false); + if (!parsed.ok) return fail(parsed.error); + if (parsed.value < std::numeric_limits::min() || + parsed.value > std::numeric_limits::max()) + return fail("value is outside the i32 range"); + *value_out = static_cast(parsed.value); + return 1; +} + std::uint64_t load_value(const nyrt_array &array, std::uint64_t index) noexcept { switch (array.kind) { @@ -1229,61 +1255,12 @@ std::int32_t nyrt_write_bytes_atomic(const char *path, const void *value, std::int32_t nyrt_try_i32(const char *text, std::int32_t *value_out, const char **error_out) noexcept { - if (value_out != nullptr) - *value_out = 0; - if (error_out != nullptr) - *error_out = nullptr; - if (text == nullptr || value_out == nullptr) { - set_error(error_out, "convert.try_to_i32: invalid arguments"); - return 0; - } - if (*text == '\0') { - set_error(error_out, "convert.try_to_i32: value is empty"); - return 0; - } - - const char *cursor = text; - bool negative = false; - if (*cursor == '+' || *cursor == '-') { - negative = *cursor == '-'; - ++cursor; - } - if (*cursor == '\0') { - set_error(error_out, "convert.try_to_i32: value has no digits"); - return 0; - } - - const std::uint64_t positive_limit = - static_cast(std::numeric_limits::max()); - const std::uint64_t limit = negative ? positive_limit + 1U : positive_limit; - std::uint64_t magnitude = 0; - for (; *cursor != '\0'; ++cursor) { - if (*cursor < '0' || *cursor > '9') { - set_error(error_out, "convert.try_to_i32: value contains a digit outside " - "the requested base"); - return 0; - } - const auto digit = static_cast(*cursor - '0'); - if (magnitude > (limit - digit) / 10) { - set_error(error_out, - "convert.try_to_i32: value is outside the i64 range"); - return 0; - } - magnitude = magnitude * 10 + digit; - } + return try_decimal_integer(text, value_out, error_out, "convert.try_to_i32"); +} - const std::int64_t signed_value = - !negative ? static_cast(magnitude) - : (magnitude == positive_limit + 1U - ? std::numeric_limits::min() - : -static_cast(magnitude)); - if (signed_value < std::numeric_limits::min() || - signed_value > std::numeric_limits::max()) { - set_error(error_out, "convert.try_to_i32: value is outside the i32 range"); - return 0; - } - *value_out = static_cast(signed_value); - return 1; +std::int32_t nyrt_try_i64(const char *text, std::int64_t *value_out, + const char **error_out) noexcept { + return try_decimal_integer(text, value_out, error_out, "convert.try_to_i64"); } const char *nyrt_i32_to_text(std::int32_t value) noexcept { diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index af9c7d47..226f2b76 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -138,6 +138,10 @@ std::int32_t nyrt_write_bytes_atomic(const char *path, const void *bytes, std::int32_t nyrt_try_i32(const char *text, std::int32_t *value_out, const char **error_out) noexcept; +// Additive conversion ABI. Native text is NUL-free; failures clear value_out +// and return a context-owned error using the same lifetime as nyrt_try_i32. +std::int32_t nyrt_try_i64(const char *text, std::int64_t *value_out, + const char **error_out) noexcept; const char *nyrt_i32_to_text(std::int32_t value) noexcept; const char *nyrt_i64_to_text(std::int64_t value) noexcept; diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 216e641e..98ac78da 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -7,6 +7,7 @@ #include "matrix_hag_bridge.hpp" #include "nil_contract.hpp" #include "numeric_literal.hpp" +#include "integer_conversion.hpp" #include "secure_file_io.hpp" #include "time_support.hpp" #include @@ -80,68 +81,8 @@ std::uint64_t heap_element_stride(const std::string &type_name) { return 8; } -struct IntegerParseResult { - bool ok = false; - std::int64_t value = 0; - std::string error; -}; - -int ascii_digit_value(char character) { - const unsigned char byte = static_cast(character); - if (byte >= '0' && byte <= '9') - return byte - '0'; - if (byte >= 'a' && byte <= 'z') - return byte - 'a' + 10; - if (byte >= 'A' && byte <= 'Z') - return byte - 'A' + 10; - return -1; -} - -IntegerParseResult parse_signed_integer(const std::string &text, int base, - bool accept_prefix) { - if (base < 2 || base > 36) - return {false, 0, "base must be between 2 and 36"}; - if (text.empty()) - return {false, 0, "value is empty"}; - - std::size_t position = 0; - bool negative = false; - if (text[position] == '+' || text[position] == '-') { - negative = text[position] == '-'; - ++position; - } - if (accept_prefix && position + 2 <= text.size() && text[position] == '0') { - const char prefix = text[position + 1]; - if ((base == 16 && (prefix == 'x' || prefix == 'X')) || - (base == 2 && (prefix == 'b' || prefix == 'B')) || - (base == 8 && (prefix == 'o' || prefix == 'O'))) - position += 2; - } - if (position == text.size()) - return {false, 0, "value has no digits"}; - - const std::uint64_t positive_limit = - static_cast(std::numeric_limits::max()); - const std::uint64_t limit = negative ? positive_limit + 1U : positive_limit; - std::uint64_t magnitude = 0; - for (; position < text.size(); ++position) { - const int digit = ascii_digit_value(text[position]); - if (digit < 0 || digit >= base) - return {false, 0, "value contains a digit outside the requested base"}; - if (magnitude > - (limit - static_cast(digit)) / - static_cast(base)) - return {false, 0, "value is outside the i64 range"}; - magnitude = magnitude * static_cast(base) + - static_cast(digit); - } - - if (!negative) - return {true, static_cast(magnitude), {}}; - if (magnitude == positive_limit + 1U) - return {true, std::numeric_limits::min(), {}}; - return {true, -static_cast(magnitude), {}}; -} +using detail::IntegerParseResult; +using detail::parse_signed_integer; std::string format_signed_integer(std::int64_t value, int base, bool uppercase) { @@ -2210,11 +2151,11 @@ void VM::executeInstruction(const Instruction &instr) { if (parsed.ok) push_ok(parsed.value); else - push_error("convert.try_to_i32: " + parsed.error); + push_error(std::string("convert.try_to_i32: ") + parsed.error); } else if (parsed.ok) { pushStack(parsed.value); } else { - throw std::runtime_error("convert.to_i32: " + parsed.error); + throw std::runtime_error(std::string("convert.to_i32: ") + parsed.error); } return; } @@ -2227,11 +2168,11 @@ void VM::executeInstruction(const Instruction &instr) { if (parsed.ok) push_ok(parsed.value); else - push_error("convert.try_to_i64: " + parsed.error); + push_error(std::string("convert.try_to_i64: ") + parsed.error); } else if (parsed.ok) { pushStack(parsed.value); } else { - throw std::runtime_error("convert.to_i64: " + parsed.error); + throw std::runtime_error(std::string("convert.to_i64: ") + parsed.error); } return; } diff --git a/nilstd/README.md b/nilstd/README.md index 5051c833..f05979e6 100644 --- a/nilstd/README.md +++ b/nilstd/README.md @@ -23,7 +23,7 @@ are first-party packages rather than standard-library modules and live in ## Current status -The active tree contains 71 sources (68 Ny and three Matrix) organized into 16 +The active tree contains 74 sources (68 Ny and six Matrix) organized into 16 logical SDK modules: `prelude` plus `nil.std.core`, `collections`, `datetime`, `db`, `diagnostics`, `io`, `math`, `net`, `nydata`, `reflection`, `runtime`, `security`, `system`, `text`, and @@ -45,13 +45,19 @@ below. | Area | Files | Status | | --- | ---: | --- | -| `src/` | 68 Ny files, 3 Matrix files | Sixteen logical SDK modules. Checked-array helpers, stable sorting, and reflection value utilities are implemented in Matrix and consumed from both frontends. | +| `src/` | 68 Ny files, 6 Matrix files | Sixteen logical SDK modules. Matrix contributes checked arrays/text spans, stable sorting, reflection values, vector helpers and independent random generators, consumed from both frontends. | | `experimental/` | 65 Ny files | Design sources excluded from `nilstd`/`nillib` because language semantics, executable providers, or behavioral evidence are incomplete. | | `tests/` | 8 Ny files | Preserved design-era tests; these are still separate from the registered route fixtures under the repository-level `tests/` tree. | | `native/` | 14 C/C++ files | Preserved platform/provider shims; source presence alone is neither a build, shipment, nor native-support claim. | ### Active evidence boundary +Checked text access (`try_substring`, `try_char_at`) and checked decimal +`Convert.try_to_i64` parsing have paired Ny/Matrix VM/native fixtures. See the +[text-span contract](../docs/standard-library/text-spans.md) and +[integer-conversion contract](../docs/standard-library/integer-conversion.md) +for exact bounds, errors and representation limits. + Registered textual/binary interpreter fixtures cover the exercised core algorithms and conversions, canonical `Option`/`Result` operations, collections, date/time, SQL construction, diagnostics, file/path/stream I/O, math, HTTP diff --git a/nilstd/src/text/package.ny b/nilstd/src/text/package.ny index b77d08bb..0ffd9eeb 100644 --- a/nilstd/src/text/package.ny +++ b/nilstd/src/text/package.ny @@ -1,22 +1,8 @@ @pragma once -# ============================================================================= -# ny.lang.text — Text Processing Package -# ============================================================================= -# String manipulation, building, encoding, and regular expressions. -# Mirrors C# System.Text. -# -# Provides: -# - String extensions: trim, split, starts_with, ends_with, pad (string.ny) -# - StringBuilder: efficient mutable string building (string_builder.ny) -# - String utilities: format, join, parse helpers (string_utils.ny) -# - Regex: match, replace, split, capture groups (regex.ny) -# -# Cross-refs: -# ny.lang.core — text primitive type and extensions -# ny.lang.io — StreamReader/Writer use text encoding -# ============================================================================= +# nil.std.text — byte-indexed text utilities and checked text spans. package nil.std.text import nil.std.text.string_utils +import nil.std.text.string_checked # Experimental: string_builder, regex diff --git a/nilstd/src/text/string_checked.matrix b/nilstd/src/text/string_checked.matrix new file mode 100644 index 00000000..ff2a1b66 --- /dev/null +++ b/nilstd/src/text/string_checked.matrix @@ -0,0 +1,21 @@ +!!! Checked byte spans. Empty spans at the end are valid; invalid bounds +!!! return None. These operations do not decode Unicode characters. +book nil.std.text + +read everything from nil.std.core + +public try-substring receives s as text, start as override long, length as override long returns Option of text begin paragraph + value size as override long is (the length of s) becomes override long + when start is less than 0 or start is greater than size or length is less than 0 then + give Option.None + end when + !!! Validate before subtraction; adding start and length could overflow. + when length is greater than (size minus start) then + give Option.None + end when + give Option.Some holding (s.substr with start being start, length being length) +end paragraph + +public try-char-at receives s as text, index as override long returns Option of text begin paragraph + give try-substring with s being s, start being index, length being 1 +end paragraph diff --git a/nilstd/src/text/string_utils.ny b/nilstd/src/text/string_utils.ny index 8efaf47f..7a08699f 100644 --- a/nilstd/src/text/string_utils.ny +++ b/nilstd/src/text/string_utils.ny @@ -676,12 +676,14 @@ pub fn reverse(s: text) -> text end fn pub fn substring(s: text, start: i64, length: i64) -> text - if start < 0 or start >= s.len() as i64 or length <= 0 then + let size: i64 = s.len() as i64 + if start < 0 or start >= size or length <= 0 then return "" end if - let end_pos = start + length - if end_pos > s.len() as i64 then - return s.substr(start as i32, (s.len() as i64 - start) as i32) + # Subtract after validating start so a large length cannot wrap the bound. + let available: i64 = size - start + if length > available then + return s.substr(start as i32, available as i32) end if return s.substr(start as i32, length as i32) end fn diff --git a/scripts/check-sdk-routes.py b/scripts/check-sdk-routes.py index 7462c159..10751148 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -43,6 +43,8 @@ "qualified-enum-patterns", "qualified-enum-patterns-matrix", "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", "random-generators", "random-generators-matrix", "math-runtime") diff --git a/tests/language/checked-i64-conversion-matrix.matrix b/tests/language/checked-i64-conversion-matrix.matrix new file mode 100644 index 00000000..6db84e40 --- /dev/null +++ b/tests/language/checked-i64-conversion-matrix.matrix @@ -0,0 +1,84 @@ +book validation.checked-i64-conversion +read everything from ny.lang.core +read everything from ny.lang.collections + +read-decimal receives source-text as text returns Result of override long, text begin paragraph + give Convert.try-to-i64 with source-text +end paragraph + +require-error receives source-text as text, expected-message as text returns nothing begin paragraph + consider read-decimal with source-text + when Result.Ok holding ignored then + evaluate panic with "invalid decimal input was accepted" + when Result.Error holding message then + evaluate assert-true with condition being (message equals expected-message), message being "exact i64 parse error" + end consider +end paragraph + +churn returns override long begin paragraph + variable total as override long is 0 + !!! 5 MiB of array payload crosses the native safe-mode 4 MiB GC threshold. + repeat for index from 0 to 640 + value items is new-with-value of override long with size being 1024, `value` being (index becomes override long) + set total to total plus (items at 0) + end repeat + give total +end paragraph + +main returns override integer begin paragraph + value zero is read-decimal with "0" + value plus-zero is read-decimal with "+0" + value minus-zero is read-decimal with "-0" + value padded is read-decimal with "+0007" + value long-padding is read-decimal with "00000000000000000000000000000000000000000000000001" + value above-i32 is read-decimal with "2147483648" + value below-i32 is read-decimal with "-2147483649" + value wide is read-decimal with "4294967296" + value maximum is read-decimal with "9223372036854775807" + value plus-maximum is read-decimal with "+9223372036854775807" + value minimum is read-decimal with "-9223372036854775808" + say zero.unwrap with nothing + say plus-zero.unwrap with nothing + say minus-zero.unwrap with nothing + say padded.unwrap with nothing + say long-padding.unwrap with nothing + say above-i32.unwrap with nothing + say below-i32.unwrap with nothing + say wide.unwrap with nothing + say maximum.unwrap with nothing + say plus-maximum.unwrap with nothing + say minimum.unwrap with nothing + + evaluate require-error with source-text being "", expected-message being "convert.try_to_i64: value is empty" + value signs is ["+", "-"] + repeat for index from 0 to (the length of signs) + evaluate require-error with source-text being (signs at index), expected-message being "convert.try_to_i64: value has no digits" + end repeat + value malformed is [" 1", "1 ", "1" plus tab, "1" plus newline, "1.0", "1e3", "0x10", "1_000", "++1", "+-1", "--1", "+ 1", "12", "١", "12x"] + repeat for index from 0 to (the length of malformed) + evaluate require-error with source-text being (malformed at index), expected-message being "convert.try_to_i64: value contains a digit outside the requested base" + end repeat + value overflow is ["9223372036854775808", "+9223372036854775808", "-9223372036854775809", "18446744073709551615", "999999999999999999999999999999999999999999999999999999999999999999", "9223372036854775808x"] + repeat for index from 0 to (the length of overflow) + evaluate require-error with source-text being (overflow at index), expected-message being "convert.try_to_i64: value is outside the i64 range" + end repeat + say "checked-i64-errors-ok" + + value retained-success is read-decimal with ("9223372036" plus "854775807") + value retained-failure is read-decimal with ("bad" plus "-decimal") + say churn with nothing + say retained-success.unwrap with nothing + consider retained-failure + when Result.Ok holding ignored then + evaluate panic with "retained failure changed variant" + when Result.Error holding message then say message + end consider + value narrow-maximum is Convert.try-to-i32 with "2147483647" + say narrow-maximum.unwrap with nothing + consider Convert.try-to-i32 with "2147483648" + when Result.Ok holding ignored then + evaluate panic with "i32 destination range was lost" + when Result.Error holding message then say message + end consider + give 0 +end paragraph diff --git a/tests/language/checked-i64-conversion-matrix.stdout b/tests/language/checked-i64-conversion-matrix.stdout new file mode 100644 index 00000000..c81cf53c --- /dev/null +++ b/tests/language/checked-i64-conversion-matrix.stdout @@ -0,0 +1,17 @@ +0 +0 +0 +7 +1 +2147483648 +-2147483649 +4294967296 +9223372036854775807 +9223372036854775807 +-9223372036854775808 +checked-i64-errors-ok +204480 +9223372036854775807 +convert.try_to_i64: value contains a digit outside the requested base +2147483647 +convert.try_to_i32: value is outside the i32 range diff --git a/tests/language/checked-i64-conversion.ny b/tests/language/checked-i64-conversion.ny new file mode 100644 index 00000000..e2eda958 --- /dev/null +++ b/tests/language/checked-i64-conversion.ny @@ -0,0 +1,67 @@ +import nil.std.core +import nil.std.collections + +fn read_decimal(source_text: text) -> Result + return Convert.try_to_i64(source_text) +end fn + +fn require_error(source_text: text, expected_message: text) + match read_decimal(source_text) + Result.Ok(_) -> panic("invalid decimal input was accepted") + Result.Error(message) -> assert_true(message == expected_message, "exact i64 parse error") + end match +end fn + +fn churn() -> i64 + let mut total: i64 = 0 + # 5 MiB of array payload crosses the native safe-mode 4 MiB GC threshold. + for index in range(640) + let items = new_with_value(1024, index as i64) + total = total + items[0] + end for + return total +end fn + +fn main() -> i32 + println(read_decimal("0").unwrap()) + println(read_decimal("+0").unwrap()) + println(read_decimal("-0").unwrap()) + println(read_decimal("+0007").unwrap()) + println(read_decimal("00000000000000000000000000000000000000000000000001").unwrap()) + println(read_decimal("2147483648").unwrap()) + println(read_decimal("-2147483649").unwrap()) + println(read_decimal("4294967296").unwrap()) + println(read_decimal("9223372036854775807").unwrap()) + println(read_decimal("+9223372036854775807").unwrap()) + println(read_decimal("-9223372036854775808").unwrap()) + + require_error("", "convert.try_to_i64: value is empty") + let signs = ["+", "-"] + for index in range(signs.len()) + require_error(signs[index], "convert.try_to_i64: value has no digits") + end for + let malformed = [" 1", "1 ", "1\t", "1\n", "1.0", "1e3", "0x10", "1_000", "++1", "+-1", "--1", "+ 1", "12", "١", "12x"] + for index in range(malformed.len()) + require_error(malformed[index], "convert.try_to_i64: value contains a digit outside the requested base") + end for + let overflow = ["9223372036854775808", "+9223372036854775808", "-9223372036854775809", "18446744073709551615", "999999999999999999999999999999999999999999999999999999999999999999", "9223372036854775808x"] + for index in range(overflow.len()) + require_error(overflow[index], "convert.try_to_i64: value is outside the i64 range") + end for + println("checked-i64-errors-ok") + + let retained_success = read_decimal("9223372036" + "854775807") + let retained_failure = read_decimal("bad" + "-decimal") + println(churn()) + println(retained_success.unwrap()) + match retained_failure + Result.Ok(_) -> panic("retained failure changed variant") + Result.Error(message) -> println(message) + end match + println(Convert.try_to_i32("2147483647").unwrap()) + match Convert.try_to_i32("2147483648") + Result.Ok(_) -> panic("i32 destination range was lost") + Result.Error(message) -> println(message) + end match + return 0 +end fn diff --git a/tests/language/checked-i64-conversion.stdout b/tests/language/checked-i64-conversion.stdout new file mode 100644 index 00000000..c81cf53c --- /dev/null +++ b/tests/language/checked-i64-conversion.stdout @@ -0,0 +1,17 @@ +0 +0 +0 +7 +1 +2147483648 +-2147483649 +4294967296 +9223372036854775807 +9223372036854775807 +-9223372036854775808 +checked-i64-errors-ok +204480 +9223372036854775807 +convert.try_to_i64: value contains a digit outside the requested base +2147483647 +convert.try_to_i32: value is outside the i32 range diff --git a/tests/language/checked-text-spans-matrix.matrix b/tests/language/checked-text-spans-matrix.matrix new file mode 100644 index 00000000..6d891c23 --- /dev/null +++ b/tests/language/checked-text-spans-matrix.matrix @@ -0,0 +1,108 @@ +!!! Literal snapshots and byte reconstruction are independent of the span implementation. +book validation.checked-text-spans + +read everything from ny.lang.core +read everything from ny.lang.text +read everything from nil.std.text + +require receives ok as boolean, label as text returns nothing begin paragraph + evaluate assert-true with condition being ok, message being label +end paragraph + +present receives expected as text, label as text, actual as Option of text returns nothing begin paragraph + evaluate require with ok being (actual.is-some with nothing), label being label + evaluate require with ok being ((actual.unwrap with nothing) equals expected), label being label +end paragraph + +absent receives label as text, actual as Option of text returns nothing begin paragraph + evaluate require with ok being (actual.is-none with nothing), label being label +end paragraph + +main returns override integer begin paragraph + variable source as text is "abcdef" + value alias is source + evaluate present with actual being (try-substring with s being "", start being 0, length being 0), expected being "", label being "empty source has a valid empty span" + evaluate present with actual being (try-substring with s being source, start being 0, length being 0), expected being "", label being "empty prefix" + evaluate present with actual being (try-substring with s being source, start being 3, length being 0), expected being "", label being "empty interior" + evaluate present with actual being (try-substring with s being source, start being 6, length being 0), expected being "", label being "empty endpoint" + evaluate present with actual being (try-substring with s being source, start being 0, length being 6), expected being "abcdef", label being "whole source" + evaluate present with actual being (try-substring with s being source, start being 1, length being 3), expected being "bcd", label being "interior span" + evaluate present with actual being (try-substring with s being source, start being 5, length being 1), expected being "f", label being "last byte" + evaluate absent with actual being (try-substring with s being "", start being 0, length being 1), label being "nonempty span in empty source" + evaluate absent with actual being (try-substring with s being "", start being 1, length being 0), label being "empty span beyond empty source" + evaluate absent with actual being (try-substring with s being source, start being 6, length being 1), label being "nonempty endpoint" + evaluate absent with actual being (try-substring with s being source, start being 5, length being 2), label being "span crosses endpoint" + evaluate absent with actual being (try-substring with s being source, start being 1, length being 6), label being "length must fit remaining bytes" + evaluate require with ok being (not ((try-substring with s being source, start being 6, length being 0).is-none with nothing)), label being "Some empty is not None" + say "checked text distinguishes empty spans from missing spans" + + value invalid-starts as array of number is [minus 1, minus 2147483648, minus 9223372036854775808, 7, 2147483647, 2147483648, 9223372036854775807] + repeat for each start in invalid-starts + evaluate absent with actual being (try-substring with s being source, start being start, length being 0), label being "invalid start with empty span" + evaluate absent with actual being (try-substring with s being source, start being start, length being 1), label being "invalid start with one byte" + evaluate absent with actual being (try-char-at with s being source, index being start), label being "invalid character index" + end repeat + value invalid-lengths as array of number is [minus 1, minus 2147483648, minus 9223372036854775808, 7, 2147483647, 2147483648, 9223372036854775807] + repeat for each count in invalid-lengths + evaluate absent with actual being (try-substring with s being source, start being 0, length being count), label being "invalid span length" + evaluate absent with actual being (try-substring with s being source, start being 1, length being count), label being "overflowing or invalid endpoint" + end repeat + evaluate absent with actual being (try-substring with s being source, start being 9223372036854775807, length being 9223372036854775807), label being "both bounds maximal" + evaluate absent with actual being (try-substring with s being source, start being minus 9223372036854775808, length being minus 9223372036854775808), label being "both bounds minimal" + evaluate absent with actual being (try-char-at with s being "", index being 0), label being "empty source has no character" + evaluate absent with actual being (try-char-at with s being source, index being 6), label being "character endpoint is exclusive" + evaluate present with actual being (try-char-at with s being source, index being 0), expected being "a", label being "first character" + evaluate present with actual being (try-char-at with s being source, index being 5), expected being "f", label being "last character" + evaluate require with ok being (source equals "abcdef" and alias equals "abcdef"), label being "rejected calls preserve source and alias" + say "checked text rejects signed-width extremes without mutation" + + !!! A(1), é(2), 🙂(4), Z(1): byte spans may split Unicode scalars. + value utf8 is "Aé🙂Z" + evaluate require with ok being ((the length of utf8) equals 8), label being "byte length is distinct from scalar count" + evaluate present with actual being (try-substring with s being utf8, start being 1, length being 2), expected being "é", label being "two-byte scalar span" + evaluate present with actual being (try-substring with s being utf8, start being 3, length being 4), expected being "🙂", label being "four-byte scalar span" + evaluate present with actual being (try-substring with s being utf8, start being 7, length being 1), expected being "Z", label being "byte after Unicode scalars" + evaluate present with actual being (try-substring with s being utf8, start being 8, length being 0), expected being "", label being "UTF-8 empty endpoint" + value first-half is (try-char-at with s being utf8, index being 1).unwrap with nothing + value second-half is (try-char-at with s being utf8, index being 2).unwrap with nothing + evaluate require with ok being ((the length of first-half) equals 1 and (the length of second-half) equals 1), label being "character access returns one byte" + evaluate require with ok being (first-half plus second-half equals "é"), label being "split scalar bytes reconstruct exactly" + value crossing is (try-substring with s being utf8, start being 2, length being 3).unwrap with nothing + evaluate require with ok being ((the length of crossing) equals 3), label being "span may start and end inside UTF-8 scalars" + value prefix is (try-substring with s being utf8, start being 0, length being 2).unwrap with nothing + value suffix is (try-substring with s being utf8, start being 5, length being 3).unwrap with nothing + evaluate require with ok being (prefix plus crossing plus suffix equals utf8), label being "partial scalar spans preserve exact byte order" + variable rebuilt as text is "" + variable index as number is 0 + repeat while index is less than 8 + value part is (try-char-at with s being utf8, index being index).unwrap with nothing + evaluate require with ok being ((the length of part) equals 1), label being "every valid byte index is present" + set rebuilt to rebuilt plus part + set index to index plus 1 + end repeat + evaluate require with ok being (rebuilt equals "Aé🙂Z"), label being "all byte accesses reconstruct the literal" + evaluate absent with actual being (try-char-at with s being utf8, index being 8), label being "UTF-8 character endpoint" + say "checked text spans preserve UTF-8 bytes including partial scalars" + + evaluate present with actual being (try-substring with s being ((try-substring with s being source, start being 1, length being 4).unwrap with nothing), start being 1, length being 2), expected being "cd", label being "nested checked spans" + evaluate require with ok being ((the length of ((try-substring with s being source, start being 1, length being 3).unwrap with nothing)) equals 3), label being "nested Option and text methods" + evaluate present with actual being (nil.std.text::try-substring with s being source, start being 2, length being 2), expected being "cd", label being "canonical qualified import" + evaluate present with actual being (nil.std.text::try-char-at with s being source, index being 3), expected being "d", label being "canonical qualified character import" + value retained is (try-substring with s being source, start being 1, length being 3).unwrap with nothing + set source to "changed" + evaluate require with ok being (alias equals "abcdef" and retained equals "bcd"), label being "results and aliases survive source reassignment" + say "checked text composes through methods and standard imports" + + evaluate require with ok being ((substring with s being alias, start being 1, length being 9223372036854775807) equals "bcdef"), label being "legacy length clamps before overflow" + evaluate require with ok being ((substring with s being alias, start being 2, length being 9223372036854775807) equals "cdef"), label being "legacy maximal length from interior" + evaluate require with ok being ((substring with s being alias, start being 1, length being 2147483647) equals "bcdef"), label being "legacy i32 maximum length" + evaluate require with ok being ((substring with s being alias, start being 1, length being 2147483648) equals "bcdef"), label being "legacy length above i32 maximum" + evaluate require with ok being ((substring with s being alias, start being minus 1, length being 2) equals ""), label being "legacy negative start remains empty" + evaluate require with ok being ((substring with s being alias, start being 0, length being minus 9223372036854775808) equals ""), label being "legacy negative length remains empty" + evaluate require with ok being ((substring with s being alias, start being 9223372036854775807, length being 1) equals ""), label being "legacy outside start remains empty" + evaluate require with ok being ((substring with s being alias, start being 6, length being 0) equals ""), label being "legacy endpoint remains empty" + evaluate require with ok being ((char-at with s being alias, index being 6) equals "" and (char-at with s being alias, index being 9223372036854775807) equals ""), label being "legacy missing character remains empty" + evaluate absent with actual being (try-substring with s being alias, start being 1, length being 9223372036854775807), label being "checked span rejects legacy clamped request" + say "legacy text clamping remains compatible at full-width bounds" + give 0 +end paragraph diff --git a/tests/language/checked-text-spans-matrix.stdout b/tests/language/checked-text-spans-matrix.stdout new file mode 100644 index 00000000..91e801db --- /dev/null +++ b/tests/language/checked-text-spans-matrix.stdout @@ -0,0 +1,5 @@ +checked text distinguishes empty spans from missing spans +checked text rejects signed-width extremes without mutation +checked text spans preserve UTF-8 bytes including partial scalars +checked text composes through methods and standard imports +legacy text clamping remains compatible at full-width bounds diff --git a/tests/language/checked-text-spans.ny b/tests/language/checked-text-spans.ny new file mode 100644 index 00000000..148907d1 --- /dev/null +++ b/tests/language/checked-text-spans.ny @@ -0,0 +1,109 @@ +module validation.checked_text_spans + +import nil.std.core +import nil.std.text +import ny.lang.text + +fn require(ok: bool, label: text) + assert_true(ok, label) +end fn + +fn present(actual: Option, expected: text, label: text) + require(actual.is_some(), label) + require(actual.unwrap() == expected, label) +end fn + +fn absent(actual: Option, label: text) + require(actual.is_none(), label) +end fn + +fn main() -> i32 + let mut source: text = "abcdef" + let alias = source + present(try_substring("", 0, 0), "", "empty source has a valid empty span") + present(try_substring(source, 0, 0), "", "empty prefix") + present(try_substring(source, 3, 0), "", "empty interior") + present(try_substring(source, 6, 0), "", "empty endpoint") + present(try_substring(source, 0, 6), "abcdef", "whole source") + present(try_substring(source, 1, 3), "bcd", "interior span") + present(try_substring(source, 5, 1), "f", "last byte") + absent(try_substring("", 0, 1), "nonempty span in empty source") + absent(try_substring("", 1, 0), "empty span beyond empty source") + absent(try_substring(source, 6, 1), "nonempty endpoint") + absent(try_substring(source, 5, 2), "span crosses endpoint") + absent(try_substring(source, 1, 6), "length must fit remaining bytes") + require(not try_substring(source, 6, 0).is_none(), "Some empty is not None") + println("checked text distinguishes empty spans from missing spans") + + let invalid_starts: array = [-1, -2147483648, -9223372036854775808, + 7, 2147483647, 2147483648, 9223372036854775807] + for start in invalid_starts + absent(try_substring(source, start, 0), "invalid start with empty span") + absent(try_substring(source, start, 1), "invalid start with one byte") + absent(try_char_at(source, start), "invalid character index") + end for + let invalid_lengths: array = [-1, -2147483648, -9223372036854775808, + 7, 2147483647, 2147483648, 9223372036854775807] + for count in invalid_lengths + absent(try_substring(source, 0, count), "invalid span length") + absent(try_substring(source, 1, count), "overflowing or invalid endpoint") + end for + absent(try_substring(source, 9223372036854775807, 9223372036854775807), "both bounds maximal") + absent(try_substring(source, -9223372036854775808, -9223372036854775808), "both bounds minimal") + absent(try_char_at("", 0), "empty source has no character") + absent(try_char_at(source, 6), "character endpoint is exclusive") + present(try_char_at(source, 0), "a", "first character") + present(try_char_at(source, 5), "f", "last character") + require(source == "abcdef" and alias == "abcdef", "rejected calls preserve source and alias") + println("checked text rejects signed-width extremes without mutation") + + # UTF-8 bytes: A(1), é(2), 🙂(4), Z(1). Splitting a code point is allowed. + # Length plus reconstruction checks exact bytes without printing invalid UTF-8. + let utf8 = "Aé🙂Z" + require(utf8.len() == 8, "byte length is distinct from scalar count") + present(try_substring(utf8, 1, 2), "é", "two-byte scalar span") + present(try_substring(utf8, 3, 4), "🙂", "four-byte scalar span") + present(try_substring(utf8, 7, 1), "Z", "byte after Unicode scalars") + present(try_substring(utf8, 8, 0), "", "UTF-8 empty endpoint") + let first_half = try_char_at(utf8, 1).unwrap() + let second_half = try_char_at(utf8, 2).unwrap() + require(first_half.len() == 1 and second_half.len() == 1, "character access returns one byte") + require(first_half + second_half == "é", "split scalar bytes reconstruct exactly") + let crossing = try_substring(utf8, 2, 3).unwrap() + require(crossing.len() == 3, "span may start and end inside UTF-8 scalars") + require(try_substring(utf8, 0, 2).unwrap() + crossing + try_substring(utf8, 5, 3).unwrap() == utf8, + "partial scalar spans preserve exact byte order") + let mut rebuilt: text = "" + let mut index: i64 = 0 + while index < 8 + let byte = try_char_at(utf8, index).unwrap() + require(byte.len() == 1, "every valid byte index is present") + rebuilt = rebuilt + byte + index = index + 1 + end while + require(rebuilt == "Aé🙂Z", "all byte accesses reconstruct the literal") + absent(try_char_at(utf8, 8), "UTF-8 character endpoint") + println("checked text spans preserve UTF-8 bytes including partial scalars") + + present(try_substring(try_substring(source, 1, 4).unwrap(), 1, 2), "cd", "nested checked spans") + require(try_substring(source, 1, 3).unwrap().len() == 3, "nested Option and text methods") + present(ny::lang::text::try_substring(source, 2, 2), "cd", "legacy qualified import") + present(ny::lang::text::try_char_at(source, 3), "d", "legacy qualified character import") + let retained = try_substring(source, 1, 3).unwrap() + source = "changed" + require(alias == "abcdef" and retained == "bcd", "results and aliases survive source reassignment") + println("checked text composes through methods and standard imports") + + require(substring(alias, 1, 9223372036854775807) == "bcdef", "legacy length clamps before overflow") + require(substring(alias, 2, 9223372036854775807) == "cdef", "legacy maximal length from interior") + require(substring(alias, 1, 2147483647) == "bcdef", "legacy i32 maximum length") + require(substring(alias, 1, 2147483648) == "bcdef", "legacy length above i32 maximum") + require(substring(alias, -1, 2) == "", "legacy negative start remains empty") + require(substring(alias, 0, -9223372036854775808) == "", "legacy negative length remains empty") + require(substring(alias, 9223372036854775807, 1) == "", "legacy outside start remains empty") + require(substring(alias, 6, 0) == "", "legacy endpoint remains empty") + require(char_at(alias, 6) == "" and char_at(alias, 9223372036854775807) == "", "legacy missing character remains empty") + absent(try_substring(alias, 1, 9223372036854775807), "checked span rejects legacy clamped request") + println("legacy text clamping remains compatible at full-width bounds") + return 0 +end fn diff --git a/tests/language/checked-text-spans.stdout b/tests/language/checked-text-spans.stdout new file mode 100644 index 00000000..91e801db --- /dev/null +++ b/tests/language/checked-text-spans.stdout @@ -0,0 +1,5 @@ +checked text distinguishes empty spans from missing spans +checked text rejects signed-width extremes without mutation +checked text spans preserve UTF-8 bytes including partial scalars +checked text composes through methods and standard imports +legacy text clamping remains compatible at full-width bounds diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index c9648cc8..0436e4a0 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -1,4 +1,5 @@ #include "native_runtime.hpp" +#include "integer_conversion.hpp" #include #include @@ -404,6 +405,91 @@ void check_conversion_contract(bool &ok) { "minimum i64 formatting failed"); ok &= expect_text(nyrt_i64_to_text(INT64_MAX), "9223372036854775807", "maximum i64 formatting failed"); + + struct i64_success_case { + const char *text; + std::int64_t expected; + }; + const i64_success_case wide_successes[] = { + {"0", 0}, {"+0", 0}, {"-0", 0}, {"+0007", 7}, + {"00000000000000000000000000000000000000000000000001", 1}, + {"2147483648", 2147483648LL}, {"-2147483649", -2147483649LL}, + {"9223372036854775807", INT64_MAX}, + {"+9223372036854775807", INT64_MAX}, + {"-9223372036854775808", INT64_MIN}, + }; + for (const auto &test : wide_successes) { + std::int64_t parsed = -7; + const char *wide_error = reinterpret_cast(std::uintptr_t{1}); + ok &= expect(nyrt_try_i64(test.text, &parsed, &wide_error) == 1 && + parsed == test.expected && wide_error == nullptr, + "valid i64 conversion did not preserve all signed bits"); + } + const failure_case wide_failures[] = { + {"", "value is empty"}, {"+", "value has no digits"}, + {"-", "value has no digits"}, + {" 1", "value contains a digit outside the requested base"}, + {"1 ", "value contains a digit outside the requested base"}, + {"1\t", "value contains a digit outside the requested base"}, + {"1\n", "value contains a digit outside the requested base"}, + {"1.0", "value contains a digit outside the requested base"}, + {"1e3", "value contains a digit outside the requested base"}, + {"0x10", "value contains a digit outside the requested base"}, + {"1_000", "value contains a digit outside the requested base"}, + {"++1", "value contains a digit outside the requested base"}, + {"+-1", "value contains a digit outside the requested base"}, + {"--1", "value contains a digit outside the requested base"}, + {"+ 1", "value contains a digit outside the requested base"}, + {"12", "value contains a digit outside the requested base"}, + {"١", "value contains a digit outside the requested base"}, + {"12x", "value contains a digit outside the requested base"}, + {"9223372036854775808", "value is outside the i64 range"}, + {"-9223372036854775809", "value is outside the i64 range"}, + {"18446744073709551615", "value is outside the i64 range"}, + }; + for (const auto &test : wide_failures) { + std::int64_t parsed = 42; + const char *wide_error = nullptr; + ok &= expect(nyrt_try_i64(test.text, &parsed, &wide_error) == 0 && parsed == 0 && + wide_error != nullptr && + wide_error == std::string("convert.try_to_i64: ") + test.expected_error, + "invalid i64 conversion did not preserve exact interpreter errors"); + } + std::int64_t wide_value = 42; + const char *wide_error = nullptr; + const std::string huge_integer(400, '9'); + ok &= expect(nyrt_try_i64(huge_integer.c_str(), &wide_value, &wide_error) == 0 && + wide_value == 0 && wide_error != nullptr && + wide_error == std::string("convert.try_to_i64: value is outside the i64 range"), + "long i64 magnitude did not fail before host overflow"); + ok &= expect(nyrt_try_i64(nullptr, &wide_value, &wide_error) == 0 && wide_value == 0 && + wide_error != nullptr && + wide_error == std::string("convert.try_to_i64: invalid arguments"), + "null i64 input did not clear output and report invalid arguments"); + ok &= expect(nyrt_try_i64("1", nullptr, &wide_error) == 0 && wide_error != nullptr, + "null i64 value output was accepted"); + ok &= expect(nyrt_try_i64("-9223372036854775808", &wide_value, nullptr) == 1 && + wide_value == INT64_MIN && + nyrt_try_i64("bad", &wide_value, nullptr) == 0 && wide_value == 0, + "optional i64 error output changed status or value behavior"); + const char *retained_error = nullptr; + nyrt_try_i64("bad", &wide_value, &retained_error); + nyrt_try_i64("", &wide_value, &wide_error); + ok &= expect(nyrt_try_i64("7", &wide_value, &wide_error) == 1 && wide_value == 7 && + wide_error == nullptr && retained_error != nullptr && + retained_error == std::string("convert.try_to_i64: value contains a digit outside the requested base"), + "later conversion invalidated an earlier owned error or retained a stale error"); + + // VM text retains its byte length; the native C-string ABI accepts only + // NUL-free text, which the compiler checks before calling the runtime. + // Exercise the shared span parser rather than pretending a C string can + // distinguish a terminator from an embedded byte with an unseen suffix. + for (const auto input : {std::string_view("12\0x", 4), std::string_view("\0", 1)}) { + const auto parsed = ny::detail::parse_signed_integer(input, 10, false); + ok &= expect(!parsed.ok && parsed.value == 0 && parsed.error != nullptr && + parsed.error == std::string("value contains a digit outside the requested base"), + "length-aware integer conversion accepted an embedded NUL"); + } } void check_file_contract(bool &ok) { diff --git a/tests/tools/checked_integer_conversion_contract.py b/tests/tools/checked_integer_conversion_contract.py new file mode 100644 index 00000000..1f258df4 --- /dev/null +++ b/tests/tools/checked_integer_conversion_contract.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Native checked integer providers require exact parameter and Result layouts.""" + +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--stdlib', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + if args.llvm == 'OFF': + print('Native conversion ABI checks require LLVM') + return 77 + compiler, stdlib = args.compiler.resolve(), args.stdlib.resolve() + environment = os.environ.copy() + for name in ('NY_LIBRARY_PATH', 'NIL_LIBRARY_PATH', 'NY_STDLIB_PATH', + 'NIL_STDLIB_PATH', 'NY_LEX_DUMP', 'NY_PARSE_TRACE'): + environment.pop(name, None) + # The ordinary canonical Result comes from core. Each malformed provider + # changes one boundary independently, with a well-typed call that reaches + # LLVM validation rather than failing ordinary argument/type checking. + cases = ( + ('wrong-input', 'i64', 'value: i32', 'Result', '1'), + ('wrong-success', 'i64', 'value: text', 'Result', '"1"'), + ('wrong-error', 'i64', 'value: text', 'Result', '"1"'), + ('wrong-arity', 'i64', 'first: text, second: text', 'Result', '"1", "2"'), + ('wrong-return', 'i64', 'value: text', 'i64', '"1"'), + ('i32-wrong-success', 'i32', 'value: text', 'Result', '"1"'), + ) + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-checked-integer-abi-') as directory: + root = Path(directory) + sources = [] + for name, width, parameters, result, arguments in cases: + path = root / f'{name}.ny' + path.write_text('import nil.std.core\n' + f'@intrinsic("convert.try_to_{width}")\n' + f'fn malformed({parameters}) -> {result}\nend fn\n' + 'fn main() -> i32\n' + f'let parsed = malformed({arguments})\n' + 'return 0\nend fn\n') + sources.append((path, f'convert.try_to_{width} requires the exact ' + f'(text) -> Result<{width},text> ABI')) + # Native text has no byte-length argument at this ABI. Reachable NUL + # constants must be rejected before a C string could truncate them. + for language, source in ( + ('ny', 'import nil.std.core\nfn main() -> i32\n' + 'let parsed = Convert.try_to_i64("12\0x")\nreturn 0\nend fn\n'), + ('matrix', 'book tests.checked-integer-nul\nread everything from nil.std.core\n' + 'main returns override integer begin paragraph\n' + 'value parsed is Convert.try-to-i64 with "12\0x"\n' + 'give 0\nend paragraph\n'), + ): + path = root / f'embedded-nul.{language}' + # Matrix quoted text is raw, so this is an actual NUL source byte. + path.write_text(source) + sources.append((path, 'contains an embedded NUL byte')) + for path, message in sources: + for flags in (('--native',), ('--native', '--jit')): + output = root / 'protected-output' + output.write_bytes(b'previous artifact') + command = [compiler, '--quiet', '--no-stdlib', '--sdk-path', stdlib, + *flags, '--output', output, path] + result = subprocess.run(command, cwd=root, env=environment, + capture_output=True, text=True, timeout=30) + assert result.returncode == 1 and not result.stdout and message in result.stderr, ( + command, result.returncode, result.stdout, result.stderr, message) + assert output.read_bytes() == b'previous artifact', command + checks += 1 + print(f'{checks} checked integer ABI and embedded-NUL rejection checks passed') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) From 65a0b60cf617b949f2d5a23e0858291ae8188762 Mon Sep 17 00:00:00 2001 From: Nathan Date: Sun, 18 Oct 2026 12:18:52 -0400 Subject: [PATCH 2/2] Fix finite floating-point average overflow --- CMakeLists.txt | 3 +- docs/standard-library/floating-averages.md | 69 ++++++++++++ docs/standard-library/index.md | 4 + matrix/docs/next-version-findings.md | 30 +++-- nilstd/README.md | 5 + nilstd/src/core/sorting.ny | 83 +++++++++++++- scripts/check-sdk-routes.py | 1 + tests/language/average-f64-matrix.matrix | 122 +++++++++++++++++++++ tests/language/average-f64-matrix.stdout | 6 + tests/language/average-f64.ny | 117 ++++++++++++++++++++ tests/language/average-f64.stdout | 6 + 11 files changed, 437 insertions(+), 9 deletions(-) create mode 100644 docs/standard-library/floating-averages.md create mode 100644 tests/language/average-f64-matrix.matrix create mode 100644 tests/language/average-f64-matrix.stdout create mode 100644 tests/language/average-f64.ny create mode 100644 tests/language/average-f64.stdout diff --git a/CMakeLists.txt b/CMakeLists.txt index 33a5135d..b895a11b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2301,7 +2301,8 @@ if(BUILD_TESTING) 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) + checked-i64-conversion checked-i64-conversion-matrix + average-f64 average-f64-matrix) if(parity_fixture MATCHES "-matrix$") set(parity_frontend matrix) else() diff --git a/docs/standard-library/floating-averages.md b/docs/standard-library/floating-averages.md new file mode 100644 index 00000000..6e56f613 --- /dev/null +++ b/docs/standard-library/floating-averages.md @@ -0,0 +1,69 @@ +# Floating-point averages + +`average_f64(items: array) -> Option` 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. diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 6788efe8..ec5b7bbe 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -20,6 +20,8 @@ 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/ @@ -309,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 diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 1a574c13..7e809932 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1020,9 +1020,9 @@ pattern binding directly; no grammar change was made in this pass. ### F32 — Floating averages can overflow for finite inputs -**Status:** Confirmed open numerical bug. +**Status:** Fixed for finite-input overflow; severe-cancellation accuracy remains limited. -`average_f64` currently computes `sum_f64(items) / count`. For +`average_f64` previously computed `sum_f64(items) / count`. For `[1e308, 1e308]`, the intermediate sum overflows to positive infinity although the mean `1e308` is representable. Negative inputs behave symmetrically, and `[1e308, 1e308, -1e308]` also produces positive infinity instead of a finite @@ -1030,11 +1030,27 @@ mean. Paired Ny/Matrix probes reproduce these results on all six routes; sources and reports are under `build/text-core-work/average-overflow` in the v1 library checkout. -**Next step:** Implement a bounded finite-input averaging algorithm without -changing `sum_f64` or the existing empty/NaN/infinity contracts. Qualify extreme -magnitudes, cancellation, subnormals and ordinary rounding against independent -numerical oracles. Scaling the inputs is a candidate, but its loss of very -small terms under severe cancellation needs explicit consideration. +**Resolution:** Accumulate two compensated subtotals. Values of magnitude at +most one retain their scale so subnormal terms survive; larger values use an +exact power-of-two divisor greater than the count, leaving overflow headroom. +Retain the rounding tail when merging the subtotals, restore the original +scale when safe, and clamp the result to the input interval. `sum_f64` is +unchanged. Empty inputs still return `None`; any nonfinite input deliberately +uses the original ordered sum/division path, including its order dependence. + +**Verification:** Paired Ny/Matrix fixtures cover finite extremes, repeated +maximum values, cancellation across both subtotals, subnormal ties, aliases +and nonfinite compatibility on all execution routes and installed libraries. +Finite expectations come from exact rational arithmetic on the binary64 +inputs. The [averaging contract](../../docs/standard-library/floating-averages.md) +records the algorithm and evidence boundary. + +**Remaining numerical limitation:** Compensation is not exact accumulation. +For `[1e100, 1e308, 1.7976931348623157e308, -1e308, -1.7976931348623157e308]`, +the small residual can still disappear, yielding zero instead of a mean near +`2e99`. Do not promise correct rounding, universal ULP accuracy or permutation +invariance. An exact or expanded accumulator is separate future work. There +is no new public API or compiler intrinsic in this fix. ### F33 — Native iteration over an array literal selects an absent iterator diff --git a/nilstd/README.md b/nilstd/README.md index f05979e6..7c30110b 100644 --- a/nilstd/README.md +++ b/nilstd/README.md @@ -52,6 +52,11 @@ below. ### Active evidence boundary +Finite `average_f64` inputs use compensated subtotals to avoid intermediate +sum overflow. Paired Ny/Matrix fixtures cover the VM and native paths; the +[floating-average contract](../docs/standard-library/floating-averages.md) +describes nonfinite compatibility behavior and the remaining accuracy limits. + Checked text access (`try_substring`, `try_char_at`) and checked decimal `Convert.try_to_i64` parsing have paired Ny/Matrix VM/native fixtures. See the [text-span contract](../docs/standard-library/text-spans.md) and diff --git a/nilstd/src/core/sorting.ny b/nilstd/src/core/sorting.ny index 9153bf50..50c5d452 100644 --- a/nilstd/src/core/sorting.ny +++ b/nilstd/src/core/sorting.ny @@ -443,12 +443,93 @@ pub fn sum_f64(arr: array) -> f64 return total end fn +# Recover the addition roundoff by subtracting the larger operand first. +# Callers keep the operands and their sum finite; reassociation is unsafe. +fn average_f64_roundoff(left: f64, right: f64, total: f64) -> f64 + let mut left_size = left + let mut right_size = right + if left_size < 0.0 then left_size = -left_size end if + if right_size < 0.0 then right_size = -right_size end if + if left_size >= right_size then + return (left - total) + right + end if + return (right - total) + left +end fn + +# Merge the two subtotals and their corrections without allocating an array. +fn average_f64_merge(a: f64, b: f64, c: f64, d: f64) -> f64 + let first = a + b + let mut error = average_f64_roundoff(a, b, first) + let second = first + c + error = error + average_f64_roundoff(first, c, second) + let third = second + d + error = error + average_f64_roundoff(second, d, third) + return third + error +end fn + +# A finite mean must not overflow merely because its unscaled sum does. +# Compensate two sums: values of magnitude <= 1 stay unscaled, preserving +# subnormals, while larger values use an exact power-of-two divisor > count. +# This is an approximation, not an exact or correctly rounded reduction. pub fn average_f64(arr: array) -> Option let n = arr.length() if n == 0 then return Option.None end if - return Option.Some(sum_f64(arr) / (n as f64)) + let count = n as f64 + let mut scale: f64 = 1.0 + while scale < count do + scale = scale * 2.0 + end while + scale = scale * 2.0 + + let mut large: f64 = 0.0 + let mut large_error: f64 = 0.0 + let mut small: f64 = 0.0 + let mut small_error: f64 = 0.0 + let mut lower = arr[0] + let mut upper = arr[0] + let mut i = 0 + while i < n do + let item = arr[i] + if item != item or (item - item) != 0.0 then + # Retain the original ordered IEEE arithmetic for nonfinite input. + return Option.Some(sum_f64(arr) / count) + end if + if item < lower then lower = item end if + if item > upper then upper = item end if + if item >= -1.0 and item <= 1.0 then + let next = small + item + small_error = small_error + average_f64_roundoff(small, item, next) + small = next + else + let scaled = item / scale + let next = large + scaled + large_error = large_error + average_f64_roundoff(large, scaled, next) + large = next + end if + i = i + 1 + end while + + let large_total = large + large_error + let large_tail = average_f64_roundoff(large, large_error, large_total) + let mut mean: f64 = 0.0 + if large_total >= -1.0 and large_total <= 1.0 then + # Cancellation made the large subtotal safe to restore. Merge before + # dividing so tiny residuals and subnormal ties survive the reduction. + let restored = large_total * scale + let restored_tail = large_tail * scale + mean = average_f64_merge(restored, small, restored_tail, small_error) / count + else + # The large subtotal dominates the small group, whose magnitude is at + # most count / scale <= 1/2. Keep this merge scaled to avoid overflow. + let combined = average_f64_merge(large_total, small / scale, large_tail, small_error / scale) + mean = combined / (count / scale) + end if + # Rounding at the largest finite value must not escape the input range. + if mean < lower then mean = lower end if + if mean > upper then mean = upper end if + return Option.Some(mean) end fn # ============================================================================= diff --git a/scripts/check-sdk-routes.py b/scripts/check-sdk-routes.py index 10751148..78651dcd 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -45,6 +45,7 @@ "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", "random-generators", "random-generators-matrix", "math-runtime") diff --git a/tests/language/average-f64-matrix.matrix b/tests/language/average-f64-matrix.matrix new file mode 100644 index 00000000..49255cc4 --- /dev/null +++ b/tests/language/average-f64-matrix.matrix @@ -0,0 +1,122 @@ +book validation.average-f64 +read everything from ny.lang.core +read everything from ny.lang.math + +require receives ok as boolean, label as text returns nothing begin paragraph + when not ok then evaluate panic with label end when +end paragraph + +!!! Oracles are nearest binary64 values of exact Fraction sums of the binary64 +!!! inputs divided by count. Nonzero tolerances below are four oracle ULPs; +!!! zero tolerances deliberately cover exact results and subnormal rounding. +near receives items as array of floating, expected as floating, tolerance as floating, label as text returns nothing begin paragraph + value result is average-f64 with arr being items + evaluate require with ok being (result.is-some with nothing), label being label + value actual is result.unwrap with nothing + evaluate require with ok being (is-finite with actual), label being label + variable lower is items at 0 + variable upper is items at 0 + repeat for index from 0 to (the length of items) + when (items at index) is less than lower then set lower to (items at index) end when + when (items at index) is greater than upper then set upper to (items at index) end when + end repeat + evaluate require with ok being (actual is at least lower and actual is at most upper), label being label + evaluate require with ok being ((abs with (actual minus expected)) is at most tolerance), label being label +end paragraph + +nan-mean receives items as array of floating, label as text returns nothing begin paragraph + value result is average-f64 with arr being items + evaluate require with ok being (result.is-some with nothing), label being label + value actual is result.unwrap with nothing + evaluate require with ok being (actual does not equal actual), label being label +end paragraph + +infinite-mean receives items as array of floating, expected as floating, label as text returns nothing begin paragraph + value result is average-f64 with arr being items + evaluate require with ok being (result.is-some with nothing), label being label + value actual is result.unwrap with nothing + evaluate require with ok being (actual equals expected), label being label +end paragraph + +main returns override integer begin paragraph + value empty-mean is average-f64 with arr being [] + evaluate require with ok being (empty-mean.is-none with nothing), label being "empty mean is absent" + evaluate near with items being [2.0, 4.0, 6.0], expected being 4.0, tolerance being 0.0, label being "ordinary exact mean" + evaluate near with items being [0.1, 0.2, 0.3], expected being 0.2, tolerance being 1.1102230246251565e-16, label being "fractional mean" + evaluate near with items being [minus 3.0, 0.0, 3.0], expected being 0.0, tolerance being 0.0, label being "ordinary cancellation" + evaluate near with items being [0.0, minus 0.0], expected being 0.0, tolerance being 0.0, label being "zero mean" + value zero-mean is average-f64 with arr being [minus 0.0, minus 0.0] + evaluate require with ok being ((atan2 with y being (zero-mean.unwrap with nothing), x being minus 1.0) is greater than 0.0), label being "negative-zero mean retains positive zero" + value original is [2.0, minus 0.0, 8.0] + value alias is original + evaluate near with items being original, expected being 3.3333333333333335, tolerance being 1.7763568394002505e-15, label being "input alias mean" + evaluate require with ok being ((the length of alias) equals 3 and (alias at 0) equals 2.0 and (alias at 2) equals 8.0), label being "input values preserved" + evaluate require with ok being ((atan2 with y being (alias at 1), x being minus 1.0) is less than 0.0), label being "input negative zero preserved" + say "ordinary means and source aliases" + + value maximum is 1.7976931348623157e308 + evaluate near with items being [maximum], expected being maximum, tolerance being 0.0, label being "maximum singleton" + evaluate near with items being [minus maximum], expected being minus maximum, tolerance being 0.0, label being "minimum singleton" + evaluate near with items being [1e308, 1e308], expected being 1e308, tolerance being 7.98336123813888e292, label being "positive intermediate overflow" + evaluate near with items being [minus 1e308, minus 1e308], expected being minus 1e308, tolerance being 7.98336123813888e292, label being "negative intermediate overflow" + evaluate near with items being [maximum, maximum, maximum], expected being maximum, tolerance being 7.98336123813888e292, label being "maximum repeated" + evaluate near with items being [maximum, maximum, maximum, maximum, maximum], expected being maximum, tolerance being 0.0, label being "constant maximum endpoint" + evaluate near with items being [minus maximum, minus maximum, minus maximum], expected being minus maximum, tolerance being 7.98336123813888e292, label being "minimum repeated" + evaluate near with items being [1e308, 1e308, minus 1e308], expected being 3.333333333333333e307, tolerance being 1.99584030953472e292, label being "positive mixed overflow" + evaluate near with items being [1e308, minus 1e308, 1e308], expected being 3.333333333333333e307, tolerance being 1.99584030953472e292, label being "mixed permutation" + evaluate near with items being [minus 1e308, minus 1e308, 1e308], expected being minus 3.333333333333333e307, tolerance being 1.99584030953472e292, label being "negative mixed overflow" + evaluate near with items being [1e308, 1e308, minus 1e308, minus 1e308], expected being 0.0, tolerance being 0.0, label being "balanced overflowing groups" + evaluate near with items being [maximum, minus maximum], expected being 0.0, tolerance being 0.0, label being "opposite maxima" + say "finite overflow and mixed signs" + + evaluate near with items being [1e16, 1.0, minus 1e16], expected being 0.3333333333333333, tolerance being 2.220446049250313e-16, label being "moderate cancellation residue" + evaluate near with items being [1e16, 1.0, 1.0, minus 1e16], expected being 0.5, tolerance being 0.0, label being "two cancellation units" + evaluate near with items being [3.0, 1.0000000000000002, minus 2.0, minus 1.0, minus 1.0], expected being 4.4408920985006264e-17, tolerance being 2.465190328815662e-32, label being "compensation tail before small terms" + evaluate near with items being [2.0000000000000004, 1.9999999999999998, minus 1.0, minus 1.0, minus 1.0, minus 1.0], expected being 3.700743415417188e-17, tolerance being 2.465190328815662e-32, label being "opposite compensation tails" + evaluate near with items being [minus 1.0, 2.0000000000000004, minus 1.0, 1.9999999999999998, minus 1.0, minus 1.0], expected being 3.700743415417188e-17, tolerance being 2.465190328815662e-32, label being "compensation tail permutation" + evaluate near with items being [minus 2.0000000000000004, minus 1.9999999999999998, 1.0, 1.0, 1.0, 1.0], expected being minus 3.700743415417188e-17, tolerance being 2.465190328815662e-32, label being "negative compensation tails" + evaluate near with items being [1e308, 1.0, minus 1e308], expected being 0.3333333333333333, tolerance being 2.220446049250313e-16, label being "extreme cancellation residue" + evaluate near with items being [1e308, 1e308, minus 1e308, minus 1e308, 3e-300], expected being 6.000000000000001e-301, tolerance being 3.3156184e-316, label being "tiny residue after overflow" + evaluate near with items being [3e-300, minus 1e308, 1e308, minus 1e308, 1e308], expected being 6.000000000000001e-301, tolerance being 3.3156184e-316, label being "tiny residue permutation" + evaluate near with items being [1e308, 1e-308, minus 1e308], expected being 3.33333333333333e-309, tolerance being 2e-323, label being "subnormal cancellation residue" + evaluate near with items being [maximum, minus maximum, 2.2250738585072014e-308], expected being 7.41691286169067e-309, tolerance being 2e-323, label being "minimum normal residue" + evaluate near with items being [1e308, 1e308, minus 1e308, minus 1e308, 5e-324], expected being 0.0, tolerance being 0.0, label being "unrepresentable final residue rounds to zero" + say "compensated cancellation" + + value tiny is 5e-324 + evaluate near with items being [tiny, tiny], expected being tiny, tolerance being 0.0, label being "repeated minimum subnormal" + evaluate near with items being [minus tiny, minus tiny], expected being minus tiny, tolerance being 0.0, label being "negative minimum subnormal" + evaluate near with items being [tiny, 0.0, tiny], expected being tiny, tolerance being 0.0, label being "subnormal thirds" + evaluate near with items being [tiny, 0.0], expected being 0.0, tolerance being 0.0, label being "subnormal tie rounds to even zero" + evaluate near with items being [1.5e-323, 0.0], expected being 1e-323, tolerance being 0.0, label being "subnormal tie rounds to even nonzero" + evaluate near with items being [tiny, 1e-323, 1.5e-323], expected being 1e-323, tolerance being 0.0, label being "mixed subnormal mean" + evaluate near with items being [2.2250738585072014e-308, 2.2250738585072014e-308, 2.2250738585072014e-308], expected being 2.2250738585072014e-308, tolerance being 0.0, label being "minimum normal repeated" + evaluate near with items being [2.2250738585072014e-308, 2.225073858507201e-308], expected being 2.2250738585072014e-308, tolerance being 0.0, label being "normal boundary tie" + say "subnormal means and rounding" + + variable large-values as array of floating is [] + variable small-values as array of floating is [] + repeat for index from 0 to 257 + append maximum to large-values + append tiny to small-values + end repeat + evaluate near with items being large-values, expected being maximum, tolerance being 7.98336123813888e292, label being "257 maximum values" + evaluate near with items being small-values, expected being tiny, tolerance being 0.0, label being "257 minimum subnormals" + say "repeated maximum and subnormal means" + + value infinity is exp with 1000.0 + value nan is sqrt with minus 1.0 + evaluate infinite-mean with items being [infinity], expected being infinity, label being "positive infinity singleton" + evaluate infinite-mean with items being [minus infinity], expected being minus infinity, label being "negative infinity singleton" + evaluate infinite-mean with items being [infinity, 1e308, 1e308], expected being infinity, label being "positive infinity propagates" + evaluate infinite-mean with items being [minus infinity, 1e308, 1e308], expected being minus infinity, label being "negative infinity precedes large terms" + evaluate nan-mean with items being [nan], label being "NaN singleton" + evaluate nan-mean with items being [1.0, nan, 2.0], label being "NaN inside input" + evaluate nan-mean with items being [infinity, minus infinity], label being "opposite infinities" + evaluate nan-mean with items being [infinity, nan, minus infinity], label being "NaN and infinities" + evaluate nan-mean with items being [1e308, 1e308, minus infinity], label being "historical overflow before opposite infinity" + evaluate nan-mean with items being [minus 1e308, minus 1e308, infinity], label being "historical negative overflow before infinity" + evaluate require with ok being ((sum-f64 with arr being [1e308, 1e308]) equals infinity), label being "sum retains ordinary overflowing arithmetic" + say "nonfinite input contracts" + give 0 +end paragraph diff --git a/tests/language/average-f64-matrix.stdout b/tests/language/average-f64-matrix.stdout new file mode 100644 index 00000000..ff124b0b --- /dev/null +++ b/tests/language/average-f64-matrix.stdout @@ -0,0 +1,6 @@ +ordinary means and source aliases +finite overflow and mixed signs +compensated cancellation +subnormal means and rounding +repeated maximum and subnormal means +nonfinite input contracts diff --git a/tests/language/average-f64.ny b/tests/language/average-f64.ny new file mode 100644 index 00000000..9755c9fa --- /dev/null +++ b/tests/language/average-f64.ny @@ -0,0 +1,117 @@ +import nil.std.core +import nil.std.math + +fn require(ok: bool, label: text) + if not ok then panic(label) end if +end fn + +# Oracles are nearest binary64 values of exact Fraction sums of the binary64 +# inputs divided by count. Nonzero tolerances below are four oracle ULPs; +# zero tolerances deliberately cover exact results and subnormal rounding. +fn near(items: array, expected: f64, tolerance: f64, label: text) + let result = average_f64(items) + require(result.is_some(), label) + let actual = result.unwrap() + require(is_finite(actual), label) + let mut lower = items[0] + let mut upper = items[0] + for index in range(items.len()) + if items[index] < lower then lower = items[index] end if + if items[index] > upper then upper = items[index] end if + end for + require(actual >= lower and actual <= upper, label) + require(abs(actual - expected) <= tolerance, label) +end fn + +fn nan_mean(items: array, label: text) + let result = average_f64(items) + require(result.is_some(), label) + let actual = result.unwrap() + require(actual != actual, label) +end fn + +fn infinite_mean(items: array, expected: f64, label: text) + let result = average_f64(items) + require(result.is_some() and result.unwrap() == expected, label) +end fn + +fn main() -> i32 + require(average_f64([]).is_none(), "empty mean is absent") + near([2.0, 4.0, 6.0], 4.0, 0.0, "ordinary exact mean") + near([0.1, 0.2, 0.3], 0.2, 1.1102230246251565e-16, "fractional mean") + near([-3.0, 0.0, 3.0], 0.0, 0.0, "ordinary cancellation") + near([0.0, -0.0], 0.0, 0.0, "zero mean") + require(atan2(average_f64([-0.0, -0.0]).unwrap(), -1.0) > 0.0, "negative-zero mean retains positive zero") + let original = [2.0, -0.0, 8.0] + let alias = original + near(original, 3.3333333333333335, 1.7763568394002505e-15, "input alias mean") + require(alias.len() == 3 and alias[0] == 2.0 and alias[2] == 8.0, "input values preserved") + require(atan2(alias[1], -1.0) < 0.0, "input negative zero preserved") + println("ordinary means and source aliases") + + let maximum = 1.7976931348623157e308 + near([maximum], maximum, 0.0, "maximum singleton") + near([-maximum], -maximum, 0.0, "minimum singleton") + near([1e308, 1e308], 1e308, 7.98336123813888e292, "positive intermediate overflow") + near([-1e308, -1e308], -1e308, 7.98336123813888e292, "negative intermediate overflow") + near([maximum, maximum, maximum], maximum, 7.98336123813888e292, "maximum repeated") + near([maximum, maximum, maximum, maximum, maximum], maximum, 0.0, "constant maximum endpoint") + near([-maximum, -maximum, -maximum], -maximum, 7.98336123813888e292, "minimum repeated") + near([1e308, 1e308, -1e308], 3.333333333333333e307, 1.99584030953472e292, "positive mixed overflow") + near([1e308, -1e308, 1e308], 3.333333333333333e307, 1.99584030953472e292, "mixed permutation") + near([-1e308, -1e308, 1e308], -3.333333333333333e307, 1.99584030953472e292, "negative mixed overflow") + near([1e308, 1e308, -1e308, -1e308], 0.0, 0.0, "balanced overflowing groups") + near([maximum, -maximum], 0.0, 0.0, "opposite maxima") + println("finite overflow and mixed signs") + + near([1e16, 1.0, -1e16], 0.3333333333333333, 2.220446049250313e-16, "moderate cancellation residue") + near([1e16, 1.0, 1.0, -1e16], 0.5, 0.0, "two cancellation units") + near([3.0, 1.0000000000000002, -2.0, -1.0, -1.0], 4.4408920985006264e-17, 2.465190328815662e-32, "compensation tail before small terms") + near([2.0000000000000004, 1.9999999999999998, -1.0, -1.0, -1.0, -1.0], 3.700743415417188e-17, 2.465190328815662e-32, "opposite compensation tails") + near([-1.0, 2.0000000000000004, -1.0, 1.9999999999999998, -1.0, -1.0], 3.700743415417188e-17, 2.465190328815662e-32, "compensation tail permutation") + near([-2.0000000000000004, -1.9999999999999998, 1.0, 1.0, 1.0, 1.0], -3.700743415417188e-17, 2.465190328815662e-32, "negative compensation tails") + near([1e308, 1.0, -1e308], 0.3333333333333333, 2.220446049250313e-16, "extreme cancellation residue") + near([1e308, 1e308, -1e308, -1e308, 3e-300], 6.000000000000001e-301, 3.3156184e-316, "tiny residue after overflow") + near([3e-300, -1e308, 1e308, -1e308, 1e308], 6.000000000000001e-301, 3.3156184e-316, "tiny residue permutation") + near([1e308, 1e-308, -1e308], 3.33333333333333e-309, 2e-323, "subnormal cancellation residue") + near([maximum, -maximum, 2.2250738585072014e-308], 7.41691286169067e-309, 2e-323, "minimum normal residue") + near([1e308, 1e308, -1e308, -1e308, 5e-324], 0.0, 0.0, "unrepresentable final residue rounds to zero") + println("compensated cancellation") + + let tiny = 5e-324 + near([tiny, tiny], tiny, 0.0, "repeated minimum subnormal") + near([-tiny, -tiny], -tiny, 0.0, "negative minimum subnormal") + near([tiny, 0.0, tiny], tiny, 0.0, "subnormal thirds") + near([tiny, 0.0], 0.0, 0.0, "subnormal tie rounds to even zero") + near([1.5e-323, 0.0], 1e-323, 0.0, "subnormal tie rounds to even nonzero") + near([tiny, 1e-323, 1.5e-323], 1e-323, 0.0, "mixed subnormal mean") + near([2.2250738585072014e-308, 2.2250738585072014e-308, 2.2250738585072014e-308], 2.2250738585072014e-308, 0.0, "minimum normal repeated") + near([2.2250738585072014e-308, 2.225073858507201e-308], 2.2250738585072014e-308, 0.0, "normal boundary tie") + println("subnormal means and rounding") + + let mut large_values: array = [] + let mut small_values: array = [] + for index in range(257) + large_values.push(maximum) + small_values.push(tiny) + end for + near(large_values, maximum, 7.98336123813888e292, "257 maximum values") + near(small_values, tiny, 0.0, "257 minimum subnormals") + println("repeated maximum and subnormal means") + + let infinity = exp(1000.0) + let nan = sqrt(-1.0) + infinite_mean([infinity], infinity, "positive infinity singleton") + infinite_mean([-infinity], -infinity, "negative infinity singleton") + infinite_mean([infinity, 1e308, 1e308], infinity, "positive infinity propagates") + infinite_mean([-infinity, 1e308, 1e308], -infinity, "negative infinity precedes large terms") + nan_mean([nan], "NaN singleton") + nan_mean([1.0, nan, 2.0], "NaN inside input") + nan_mean([infinity, -infinity], "opposite infinities") + nan_mean([infinity, nan, -infinity], "NaN and infinities") + nan_mean([1e308, 1e308, -infinity], "historical overflow before opposite infinity") + nan_mean([-1e308, -1e308, infinity], "historical negative overflow before infinity") + require(sum_f64([1e308, 1e308]) == infinity, "sum retains ordinary overflowing arithmetic") + println("nonfinite input contracts") + return 0 +end fn diff --git a/tests/language/average-f64.stdout b/tests/language/average-f64.stdout new file mode 100644 index 00000000..ff124b0b --- /dev/null +++ b/tests/language/average-f64.stdout @@ -0,0 +1,6 @@ +ordinary means and source aliases +finite overflow and mixed signs +compensated cancellation +subnormal means and rounding +repeated maximum and subnormal means +nonfinite input contracts