diff --git a/CMakeLists.txt b/CMakeLists.txt index 53128e02..33a5135d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2298,16 +2298,19 @@ if(BUILD_TESTING) ) set_tests_properties(ny.qualified-enum-contract PROPERTIES LABELS "typecheck;analysis;rc" TIMEOUT 120) - foreach(scientific_frontend IN ITEMS ny matrix) - if(scientific_frontend STREQUAL "ny") - set(scientific_fixture scientific-literals) + foreach(parity_fixture IN ITEMS scientific-literals scientific-literals-matrix + integer-literal-widths integer-literal-widths-matrix + checked-text-spans checked-text-spans-matrix + checked-i64-conversion checked-i64-conversion-matrix) + if(parity_fixture MATCHES "-matrix$") + set(parity_frontend matrix) else() - set(scientific_fixture scientific-literals-matrix) + set(parity_frontend ny) endif() add_ny_route_test( - ny.routes.${scientific_fixture} - --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.${scientific_frontend}" - --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.stdout" + ny.routes.${parity_fixture} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${parity_fixture}.${parity_frontend}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${parity_fixture}.stdout" --expected-exit 0 --routes all --compiler-arg=--sdk-path @@ -2315,19 +2318,19 @@ if(BUILD_TESTING) ) if(TARGET nilassembler AND TARGET nillinker) add_test( - NAME ny.tools.${scientific_fixture} + NAME ny.tools.${parity_fixture} COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/native_toolchain_pipeline.py" --compiler $ --assembler $ --linker $ --runtime $ - --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.${scientific_frontend}" - --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.stdout" + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${parity_fixture}.${parity_frontend}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${parity_fixture}.stdout" --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --work-dir "${CMAKE_CURRENT_BINARY_DIR}/tests/tools" ) - set_tests_properties(ny.tools.${scientific_fixture} PROPERTIES + set_tests_properties(ny.tools.${parity_fixture} PROPERTIES LABELS "tools;native;rc" SKIP_RETURN_CODE 77 TIMEOUT 240) endif() endforeach() @@ -2340,6 +2343,26 @@ if(BUILD_TESTING) ) set_tests_properties(ny.scientific-literals-contract PROPERTIES LABELS "typecheck;analysis;rc" TIMEOUT 120) + add_test( + NAME ny.integer-literals-contract + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/integer_literals_contract.py" + --compiler $ + --interpreter $ + --llvm "${NIL_ENABLE_LLVM}" + ) + set_tests_properties(ny.integer-literals-contract PROPERTIES + LABELS "typecheck;analysis;rc" TIMEOUT 180) + add_test( + NAME ny.checked-integer-conversion-contract + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/checked_integer_conversion_contract.py" + --compiler $ + --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" @@ -2634,6 +2657,35 @@ if(BUILD_TESTING) absolute-overflow core-absolute-overflow-reject.stderr ) + foreach(absolute_frontend IN ITEMS ny matrix) + if(absolute_frontend STREQUAL "ny") + set(absolute_fixture core-absolute-i64-overflow) + else() + set(absolute_fixture core-absolute-i64-overflow-matrix) + endif() + add_ny_route_test( + ny.routes.${absolute_fixture} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${absolute_fixture}.${absolute_frontend}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/routes/empty.stdout" + --expected-stderr "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/core-absolute-i64-overflow.stderr" + --expected-exit 1 + --routes text-interpreter,binary-interpreter,bundle-text,bundle-binary + --compiler-arg=--sdk-path + --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src + ) + if(NIL_ENABLE_LLVM) + add_ny_route_test( + ny.routes.native-${absolute_fixture} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${absolute_fixture}.${absolute_frontend}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/routes/empty.stdout" + --expected-stderr "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/core-absolute-i64-overflow.native.stderr" + --expected-exit 1 + --routes llvm-jit,llvm-aot + --compiler-arg=--sdk-path + --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src + ) + endif() + endforeach() add_ny_core_algorithm_reject_test( ny.routes.core-gcd-overflow-reject gcd-overflow diff --git a/docs/design/NIL-0007-integer-literal-widths.md b/docs/design/NIL-0007-integer-literal-widths.md new file mode 100644 index 00000000..d4dd8967 --- /dev/null +++ b/docs/design/NIL-0007-integer-literal-widths.md @@ -0,0 +1,62 @@ +# NIL-0007: Integer literal widths and range validation + +**Status:** Implemented. + +**Scope:** Shared Ny/Matrix literal semantics, array inference and diagnostics. + +## Problem + +Every integer literal previously inferred `i32`, including values that need +64 bits. A large literal could print correctly through the VM's value carrier +yet truncate when stored or used in arithmetic. The expression +`-9223372036854775807 - 1` consequently evaluated to zero before conversion to +an `i64` parameter. Array inference also retained the first element's type, +allowing a later `i64` value to narrow silently into an inferred `array`. +This also broke the standard library's `abs_i64` overflow guard: zero panicked +and the minimum signed value wrapped instead of reporting overflow. + +## Decision + +Decimal integer literals use `i32` when representable and `i64` otherwise, +within the signed 64-bit range. Negated literal boundary values support +`-2147483648` as `i32` and `-9223372036854775808` as `i64` without decoding an +unrepresentable positive intermediate. Values outside that range are source +errors, including in editor analysis and when type checking is disabled. + +Hexadecimal literals retain their established mask behavior: values through +`0xFFFFFFFF` infer `i32`, while larger supported values infer `i64`. An +`i32` mask is interpreted at 32 bits when stored or used by typed arithmetic; +an explicit `0xFFFFFFFF as i64` retains the positive value `4294967295`. +Positive hexadecimal values above `0x7FFFFFFFFFFFFFFF` are rejected. Negating +`0x8000000000000000` can represent the signed 64-bit minimum; this does not +introduce unsigned 64-bit values. + +Inferred integer arrays join `i32` and `i64` elements to `i64`, in either order. +This applies to typed variables as well as literal elements. It does not make +`array` and `array` interchangeable; callers must still supply the +declared element type at an array boundary. + +## Compatibility and limits + +Ordinary arithmetic still uses operand types and wraps at its resolved width. +`2147483647 + 1` remains `i32` arithmetic. An outer `i64` destination or +parameter does not widen that inner operation. Explicit scalar casts and +storage conversions continue to narrow by retaining low bits. + +Existing programs that relied on implicit narrowing of large decimal literals +must state the intended `i32` conversion. Existing 32-bit hexadecimal masks +retain their width. The two frontends share these rules; Matrix's intended +universal `number` default and broader contextual expression typing remain +separate decisions. `--no-typecheck` retains its legacy untyped arithmetic +contract; range validation is still mandatory. + +## Verification + +Paired source fixtures exercise scalar boundaries, both forms of match, +globals, nested calls, explicit wrapping, hexadecimal masks and integer arrays. +Core-library checks cover `abs_i64(0)`, wide negative inputs and rejection of +the signed minimum on both frontends and all enabled execution routes. +Rejection tests cover ordinary expressions, patterns, unused defaults, editor +analysis, unchecked compilation and preservation of existing output files. +Qualify both frontends through textual/binary NIL, bundles, LLVM JIT/AOT and +the assembler/linker pipelines, including installed source/binary libraries. diff --git a/docs/design/README.md b/docs/design/README.md index b87b7fe7..a8b102fc 100644 --- a/docs/design/README.md +++ b/docs/design/README.md @@ -30,6 +30,7 @@ not assigned architecture identifiers. | NIL-0004 | [Debugger state belongs to the VM](../../notebook/decisions/NIL-0004-debugger-state-belongs-to-the-vm.md) | Implemented as a preview | | NIL-0005 | [Generated non-void fallthrough is explicit](../../notebook/decisions/NIL-0005-generated-nonvoid-fallthrough-is-explicit.md) | Implemented and verified | | NIL-0006 | [Opt-in AI control for NIL programs](NIL-0006-ai-module.md) | Partial Windows prototype; interpreter introspection and Unix transport remain proposed | +| NIL-0007 | [Integer literal widths and range validation](NIL-0007-integer-literal-widths.md) | Implemented | | NIL-0093 | [Executable context is artifact self-description](NIL-0093-executable-context.md) | Implemented within the documented inspection profile | ## Retained Ny feature references diff --git a/docs/language-reference/expressions.md b/docs/language-reference/expressions.md index 4dbb0cd3..0a9968e6 100644 --- a/docs/language-reference/expressions.md +++ b/docs/language-reference/expressions.md @@ -10,8 +10,14 @@ not supply placeholder values. 42 # i32 42 as i64 # explicit width 0xFF # hex +2147483648 # inferred i64 ``` +Decimal literals infer `i32` or `i64` by representable range. Hexadecimal +literals through `0xFFFFFFFF` retain 32-bit mask semantics. Out-of-range +integers are rejected before code generation; see the +[integer width contract](types.md#scalar-values). + ### Float Literals ```ny 3.14 # f64 diff --git a/docs/language-reference/types.md b/docs/language-reference/types.md index 76fe3214..7c134b8d 100644 --- a/docs/language-reference/types.md +++ b/docs/language-reference/types.md @@ -23,7 +23,14 @@ Scalar casts to these targets fail explicitly. Do not use their acceptance in a declaration as evidence of supported arithmetic or layout. `char`, general references, and arbitrary foreign types also need independent qualification. -Integer literals initially infer `i32`; floating literals infer `f64`. +Decimal integer literals infer `i32` when representable, otherwise `i64`. +Negated literal boundaries include `-2147483648` (`i32`) and +`-9223372036854775808` (`i64`). Values outside signed 64-bit range are source +errors. Floating literals infer `f64`. + +Hexadecimal values through `0xFFFFFFFF` retain `i32` mask semantics; larger +supported values infer `i64`. Positive values above `0x7FFFFFFFFFFFFFFF` are +rejected; negated `0x8000000000000000` can represent the signed minimum. Use explicit types or casts when width matters: ```ny @@ -35,8 +42,9 @@ let fraction: f64 = 0.5 An outer `i64` destination or parameter does not widen arithmetic inside its initializer or argument. Bind or cast an operand before that arithmetic: `(2147483647 as i64) + 1` is `2147483648`, while `2147483647 + 1` wraps at -`i32` before assignment. Oversized bare integer operands currently lack a -range diagnostic; see [F30](../../matrix/docs/next-version-findings.md#f30--large-integer-expressions-can-narrow-before-an-i64-argument-conversion). +`i32` before assignment. See [NIL-0007](../design/NIL-0007-integer-literal-widths.md) +for literal ranges, hexadecimal compatibility and the boundary between literal +inference and contextual typing. ### Arithmetic and conversions @@ -89,6 +97,12 @@ println(values[0]) values[1] = 7 ``` +Inferred integer arrays containing both `i32` and `i64` elements use `i64` +regardless of element order. For example, `[1, 2147483648]` and +`[2147483648, 1]` both infer `array`. This also applies to typed variable +elements. Array types remain invariant: an `array` cannot be passed as +`array` through an implicit element conversion. + Typed pointers use `ptr`. Allocation and deallocation are explicit: ```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 29eda0c0..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. @@ -921,9 +929,10 @@ evidence are under `build/random-library-work`. ### F30 — Large integer expressions can narrow before an i64 argument conversion -**Status:** Confirmed authoring/diagnostic gap; no inference change in this pass. +**Status:** Literal-range and mixed-integer-array fixes implemented; contextual +typing and Matrix's universal `number` default remain open. -**Evidence:** Passing `-9223372036854775807 - 1` to an `i64` parameter produces +**Evidence before the fix:** Passing `-9223372036854775807 - 1` to an `i64` parameter produces zero on both frontends and all six routes. The emitted NIL performs `NEG i32` and `SUB i32` before the call. The generator's normalization was correct; its test had constructed the wrong seed. Oversized bare literals are accepted @@ -939,16 +948,162 @@ unannotated arithmetic therefore does not yet follow the intended wider declared types and inferred literal expressions. The probe sources, NIL and 12 successful route executions are in `build/random-library-work/width-probes`. -**Workaround:** Bind `let maximum: i64 = 9223372036854775807` in Ny or -`value maximum as number is 9223372036854775807` in Matrix, then construct the -minimum with `-maximum - 1` or `minus maximum minus 1`. The paired RNG fixtures -use this form and verify the true i64 extrema against independent oracles. -An explicit cast on the literal operand also fixes its arithmetic width. - -**Next step / acceptance:** Define literal-range and contextual-inference policy -for both frontends. Diagnose values outside an inferred integer width, or adopt -specified wider inference; keep explicit wrapping arithmetic distinct from -accidental narrowing of a literal. Matrix's intended `number` default needs -matching inferred expression/array behavior and documentation. Cover nested -arithmetic, calls, arrays, editor diagnostics and all execution routes before -changing the language contract. +**Resolution:** [NIL-0007](../../docs/design/NIL-0007-integer-literal-widths.md) +defines shared range-aware inference: decimal literals use `i32` when +representable and `i64` otherwise. Signed boundary literals represent both +minimum values directly. Hexadecimal masks through `0xFFFFFFFF` retain their +historical `i32` width; larger supported hexadecimal values use `i64`. Values +outside the signed 64-bit carrier range fail before artifact output, including +unused/default expressions, editor analysis and unchecked compilation. +Mixed `i32`/`i64` arrays now infer `array` in either element order, +including elements supplied by typed variables. Array types remain invariant. +The original large-literal expression now constructs the intended i64 minimum. +This repairs the existing `abs_i64` guard in `nil.std.core`: the old SDK +panicked for zero and returned the unchanged minimum value for overflow. +The baseline reproducer is under `build/integer-width-work/abs-baseline`. + +**Verification:** Paired +[Ny](../../tests/language/integer-literal-widths.ny) and +[Matrix](../../tests/language/integer-literal-widths-matrix.matrix) fixtures cover +integer boundaries, globals, nested calls, both match forms, wide array values, +explicit narrowing, retained wrapping behavior and core `abs_i64` results. +Separate paired overflow fixtures require `abs_i64` to reject the signed +minimum on every enabled execution route. The +[contract runner](../../tests/tools/integer_literals_contract.py) checks invalid +source literals and existing-artifact preservation across compilation modes, +editor diagnostics, array invariance, and the type-checking-disabled flag. +Fixtures are registered for all six routes, standalone assembler/linker +pipelines and installed source/binary-library consumption. + +**Remaining context / workaround:** To widen arithmetic on small operands, +bind one operand as `i64` in Ny or `number` in Matrix before the operation. +For example, `(2147483647 as i64) + 1` retains the wider result. The signed +minimum itself can now be written directly in either language. + +**Next step / acceptance:** Decide broader contextual inference and Matrix's +intended universal `number` default separately. Small literals still infer +`i32`, so `2147483647 + 1` still wraps before assignment to `i64`; a parameter +or destination annotation does not change an inner expression's width. A +future change must cover generic identities, mixed-language arrays/calls and +explicit narrow arithmetic, with matching editor and execution evidence. + +### 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/matrix/docs/ny-surface-inventory.md b/matrix/docs/ny-surface-inventory.md index 11dce349..f0445197 100644 --- a/matrix/docs/ny-surface-inventory.md +++ b/matrix/docs/ny-surface-inventory.md @@ -95,9 +95,10 @@ semantic weight. | `char` | no spelling | needs independent qualification | | `any` | no spelling | erasure/recovery is rejected | -Integer literals infer `integer`; floating literals infer `real`. Matrix keeps -Ny's promotion order `real`, `long`, `integer`, `byte` and Ny's wrapping -integer arithmetic at the resolved width. +Decimal integer literals infer `i32` or `i64` by range; 32-bit hexadecimal masks +retain `i32` inference. Floating literals infer `f64`. Matrix keeps Ny's +promotion order `f64`, `i64`, `i32`, `u8` and wrapping integer arithmetic at +the resolved width. See the shared [literal-width decision](../../docs/design/NIL-0007-integer-literal-widths.md). ### Conversions diff --git a/matrix/docs/types-and-text.md b/matrix/docs/types-and-text.md index 6b1b647e..66c89300 100644 --- a/matrix/docs/types-and-text.md +++ b/matrix/docs/types-and-text.md @@ -71,14 +71,18 @@ gets a message naming the real constraint instead of "unknown identifier". ### Two consequences worth knowing -**A declared `number` is 64-bit; current literal inference is still 32-bit.** -Matrix's intended ordinary integer type is the wider `number`, but unannotated -integer literals and their arithmetic currently share Ny's `i32` inference. +**A declared `number` is 64-bit; small integer literals still infer 32 bits.** +Ny and Matrix infer decimal literals as `i32` when representable and `i64` +otherwise. Negated boundary literals represent the signed minima directly; +values outside signed 64-bit range are rejected. Hexadecimal values through +`0xFFFFFFFF` retain 32-bit mask semantics. Matrix's intended universal +`number` default remains a separate language decision. For example, `2147483647 plus 1` wraps before conversion even if assigned to a `number` or passed to a `number` parameter. Bind an operand as `number`, or cast it with `becomes override long`, before performing arithmetic that needs -64 bits. An `array of number` also needs correctly typed elements; its annotation -does not widen an inferred integer-literal array. This discrepancy is tracked +64 bits. Mixed `i32`/`i64` array elements now infer `array of number` in either +order; an unannotated all-small-literal array still infers `array of override integer`. +Array types remain invariant. The remaining inference questions are tracked in [F30](next-version-findings.md#f30--large-integer-expressions-can-narrow-before-an-i64-argument-conversion). Ny APIs accepting `i32` may instead require `becomes override integer`. diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index 60e51920..6b7de73f 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -1439,6 +1439,62 @@ class emitter { push_instr(opcode, {type}, expression.line); } + // Recover only unambiguous expression types for direct AST clients that do + // not run the checker. This supplies array element metadata, without adding + // typed arithmetic or implicit scalar storage conversions to that path. + std::string unambiguous_expression_type(const ast_expr &expression) const { + if (expression.inferred_type) + return substitute_nil_type_name(*expression.inferred_type, substitutions); + switch (expression.kind) { + case ast_node_kind::number_literal_node: { + const auto &number = static_cast(expression); + if (is_floating_literal_spelling(number.value)) return "f64"; + integer_literal_info info; + return parse_integer_literal(number.value, info) ? "" : info.inferred_type(); + } + case ast_node_kind::boolean_literal_node: return "bool"; + case ast_node_kind::char_literal_node: return "u8"; + case ast_node_kind::string_literal_node: return "text"; + case ast_node_kind::cast_expr_node: + return substitute_nil_type_name( + static_cast(expression).target_type, substitutions); + case ast_node_kind::identifier_expr_node: { + const auto &name = static_cast(expression).name; + const auto local = local_var_types.find(name); + return local == local_var_types.end() ? "" : + substitute_nil_type_name(local->second, substitutions); + } + case ast_node_kind::unary_expr_node: { + const auto &unary = static_cast(expression); + if (unary.operand && (unary.op == token_kind::minus || unary.op == token_kind::tilde)) + return unambiguous_expression_type(*unary.operand); + return {}; + } + case ast_node_kind::array_literal_expr_node: { + const auto &array = static_cast(expression); + const auto element = unambiguous_array_element_type(array); + return element == "any" ? "" : "array<" + element + ">"; + } + default: return {}; + } + } + + std::string unambiguous_array_element_type(const ast_array_literal_expr &array) const { + std::string result; + for (const auto &element : array.elements) { + if (!element) return "any"; + auto type = unambiguous_expression_type(*element); + if (type.empty() || type == "any" || type == "__local" || type == "") + return "any"; + if (type == "int") type = "i32"; + if (result.empty()) result = type; + else if ((result == "i32" && type == "i64") || + (result == "i64" && type == "i32")) result = "i64"; + else if (result != type) return "any"; + } + return result.empty() ? "any" : result; + } + void emit_stmt(const ast_stmt &s) { switch (s.kind) { case ast_node_kind::block_stmt_node: { @@ -1467,6 +1523,10 @@ class emitter { ds.declaration->kind == ast_node_kind::variable_decl_node) { const auto &vd = static_cast(*ds.declaration); + const auto fallback_type = vd.initializer + ? unambiguous_expression_type(*vd.initializer) : std::string{}; + const auto local_type = vd.type_name.value_or( + fallback_type.empty() ? "__local" : fallback_type); if (vd.initializer) { emit_expr(*vd.initializer, vd.type_name); // NY-001: When a type annotation is present (e.g. `let x: f64 = @@ -1479,7 +1539,7 @@ class emitter { // The initializer resolves before introducing the new binding: // `let value = value + 1` reads the visible outer declaration. declare_local(vd.name, - vd.type_name.value_or(vd.initializer->inferred_type.value_or("__local"))); + local_type); nil_instruction instr; instr.opname = "STORE_LOCAL"; instr.args.push_back(vd.name); @@ -1496,7 +1556,7 @@ class emitter { // Always mark as a known local (even without type) so the identifier // handler can distinguish locals from fn-pointer references. local_var_types[vd.name] = - vd.type_name.value_or(vd.initializer ? vd.initializer->inferred_type.value_or("__local") : "__local"); + local_type; } break; } @@ -2312,8 +2372,22 @@ class emitter { // Load target, push literal, compare for equality push_instr("LOAD_LOCAL", {tmp_target}, match_s.line); if (arm.pattern.literal_kind == ast_node_kind::number_literal_node) { + integer_literal_info integer; + const bool integral = !is_floating_literal_spelling(arm.pattern.literal_value); + if (integral) { + if (const auto *message = parse_integer_literal(arm.pattern.literal_value, integer)) { + cg_.reject_codegen_construct(match_s.line, message, + "use a signed i64 value or a supported floating-point literal"); + break; + } + } push_instr("PUSH_CONST", {arm.pattern.literal_value}, match_s.line); + // Newly accepted signed hexadecimal patterns must match the + // existing unary NEG expression, including 32-bit mask wrap. + if (integral && integer.negative && integer.hexadecimal && + integer.inferred_type() == std::string_view("i32")) + push_instr("CAST", {"i32"}, match_s.line); } else if (arm.pattern.literal_kind == ast_node_kind::boolean_literal_node) { push_instr("PUSH_CONST", {arm.pattern.literal_value == "true" ? "1" : "0"}, match_s.line); @@ -2653,6 +2727,14 @@ class emitter { switch (e.kind) { case ast_node_kind::number_literal_node: { const auto &num = static_cast(e); + if (!is_floating_literal_spelling(num.value)) { + integer_literal_info integer; + if (const auto *message = parse_integer_literal(num.value, integer)) { + cg_.reject_codegen_construct(num.line, message, + "use a signed i64 value or a supported floating-point literal"); + break; + } + } push_instr("PUSH_CONST", {num.value}, num.line); break; } @@ -2712,28 +2794,11 @@ class emitter { element && *element != "any") element_type = *element; } - if (element_type == "any" && !arr.elements.empty() && - arr.elements.front()->inferred_type) { - element_type = *arr.elements.front()->inferred_type; - } - // `--no-typecheck` deliberately leaves inferred_type unset. Preserve - // the unambiguous builtin literal type anyway so native lowering can - // enforce an exact array ABI instead of accepting a wildcard handle. - if (element_type == "any" && !arr.elements.empty()) { - const auto &first = *arr.elements.front(); - if (first.kind == ast_node_kind::number_literal_node) { - const auto &number = static_cast(first); - element_type = is_floating_literal_spelling(number.value) - ? "f64" - : "i32"; - } else if (first.kind == ast_node_kind::boolean_literal_node) { - element_type = "bool"; - } else if (first.kind == ast_node_kind::char_literal_node) { - element_type = "u8"; - } else if (first.kind == ast_node_kind::string_literal_node) { - element_type = "text"; - } - } + // Direct AST clients may omit checker metadata. Recover every known + // element's width so native lowering can enforce an exact array ABI + // instead of accepting a wildcard handle or trusting the first value. + if (element_type == "any") + element_type = unambiguous_array_element_type(arr); push_instr("NEW_ARRAY_LITERAL", {std::to_string(arr.elements.size()), element_type}, arr.line); break; 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/lexer.cpp b/nilcompiler/src/lexer.cpp index 44764e16..4571e939 100644 --- a/nilcompiler/src/lexer.cpp +++ b/nilcompiler/src/lexer.cpp @@ -445,6 +445,10 @@ token lexer::number() { while (std::isxdigit(static_cast(peek()))) { advance(); } + // Keep an invalid adjacent identifier suffix in the numeric token so it + // remains a source-literal error even when type-check errors are ignored. + while (std::isalnum(static_cast(peek())) || peek() == '_') + advance(); std::string text = src.substr(start, current - start); return token{token_kind::number_literal, text, line}; } 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/matrix_lexer.cpp b/nilcompiler/src/matrix_lexer.cpp index a5756c0f..9da38d17 100644 --- a/nilcompiler/src/matrix_lexer.cpp +++ b/nilcompiler/src/matrix_lexer.cpp @@ -318,6 +318,8 @@ token lexer::scan_number() { } while (std::isxdigit(static_cast(peek()))) spelling.push_back(advance()); + while (std::isalnum(static_cast(peek())) || peek() == '_') + spelling.push_back(advance()); token t = make(token_kind::number_literal, spelling, line, col); t.key = spelling; return t; diff --git a/nilcompiler/src/matrix_parser.cpp b/nilcompiler/src/matrix_parser.cpp index f938a73a..9fa8b6b6 100644 --- a/nilcompiler/src/matrix_parser.cpp +++ b/nilcompiler/src/matrix_parser.cpp @@ -1,4 +1,5 @@ #include "matrix_parser.hpp" +#include "numeric_literal.hpp" #include "standard_namespace.hpp" #include @@ -1190,6 +1191,20 @@ std::shared_ptr parser::parse_program() { // 'sleep for ...' are appended once, after the page's own declarations. for (auto &decl : synthesized_) program->declarations.push_back(decl); + // Check every source integer, including unused/default expressions. Only + // direct unary minimum literals may use the positive boundary magnitude. + for (size_t index = 0; index < tokens_.size(); ++index) { + const auto &number = tokens_[index]; + if (number.kind != matrix::token_kind::number_literal || + ny::is_floating_literal_spelling(number.lexeme)) continue; + ny::integer_literal_info info; + if (const auto *message = ny::parse_integer_literal(number.lexeme, info)) { + const auto boundary = integer_boundaries_.find(index); + if (boundary == integer_boundaries_.end() || + ny::parse_integer_literal(boundary->second->value, info)) + error(number, message); + } + } return program; } @@ -2196,6 +2211,13 @@ ny::ast_expr_ptr parser::parse_unary() { // Prefix 'minus' is negation, as in English ("minus five"). if (match(kw::minus)) { auto operand = parse_unary(); + if (operand && operand->kind == ny::ast_node_kind::number_literal_node) { + auto &number = static_cast(*operand); + if (const auto folded = ny::negated_integer_boundary(number.value)) { + number.value = *folded; + return operand; + } + } return std::make_shared(ny::token_kind::minus, operand, line); } @@ -2452,8 +2474,12 @@ ny::ast_expr_ptr parser::parse_primary() { const token &start = peek(); const int line = start.line; - if (check(matrix::token_kind::number_literal)) - return std::make_shared(advance().lexeme, line); + if (check(matrix::token_kind::number_literal)) { + auto number = std::make_shared(advance().lexeme, line); + if (ny::is_integer_minimum_magnitude(number->value)) + integer_boundaries_.emplace(pos_ - 1, number); + return number; + } if (check(matrix::token_kind::string_literal)) return std::make_shared(advance().lexeme, line); @@ -2807,9 +2833,16 @@ ny::ast_expr_ptr parser::parse_build() { ny::ast_pattern parser::parse_pattern() { ny::ast_pattern pattern; + const bool negative_number = check(kw::minus) && + peek(1).kind == matrix::token_kind::number_literal; + if (negative_number) advance(); if (check(matrix::token_kind::number_literal)) { pattern.kind = ny::ast_pattern_kind::literal_pattern; - pattern.literal_value = advance().lexeme; + const auto number = advance(); + pattern.literal_value = (negative_number ? "-" : "") + number.lexeme; + if (negative_number && ny::is_integer_minimum_magnitude(number.lexeme)) + integer_boundaries_.emplace(pos_ - 1, + std::make_shared(pattern.literal_value, number.line)); pattern.literal_kind = ny::ast_node_kind::number_literal_node; return pattern; } @@ -2958,9 +2991,9 @@ ny::ast_expr_ptr parser::parse_consider_expression() { // A literal arm compares the target against a value, which is an // ordinary expression pattern. - if (check(matrix::token_kind::number_literal)) { - pattern_expr = std::make_shared( - advance().lexeme, arm_line); + if (check(matrix::token_kind::number_literal) || + (check(kw::minus) && peek(1).kind == matrix::token_kind::number_literal)) { + pattern_expr = parse_unary(); if (match(kw::provided)) guard = parse_expression(); match(kw::then); // optional, for symmetry with the statement form if (!expect(kw::give, "before the value of a 'consider' arm")) break; diff --git a/nilcompiler/src/matrix_parser.hpp b/nilcompiler/src/matrix_parser.hpp index 788ee986..c97dbaa4 100644 --- a/nilcompiler/src/matrix_parser.hpp +++ b/nilcompiler/src/matrix_parser.hpp @@ -80,6 +80,8 @@ class parser { private: std::vector tokens_; + std::unordered_map> + integer_boundaries_; size_t pos_ = 0; std::vector diagnostics_; std::vector rich_; 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/numeric_literal.hpp b/nilcompiler/src/numeric_literal.hpp index ba731e02..bdeb1d48 100644 --- a/nilcompiler/src/numeric_literal.hpp +++ b/nilcompiler/src/numeric_literal.hpp @@ -3,6 +3,10 @@ #include #include +#include +#include +#include +#include #include namespace ny { @@ -22,6 +26,64 @@ inline bool is_floating_literal_spelling(std::string_view spelling) { spelling.find_first_of(".eE") != std::string_view::npos; } +struct integer_literal_info { + std::uint64_t magnitude = 0; + bool negative = false; + bool hexadecimal = false; + + const char *inferred_type() const { + // Preserve hexadecimal masks' historical 32-bit arithmetic contract. + const std::uint64_t narrow_limit = hexadecimal ? UINT32_MAX + : negative ? std::uint64_t(INT32_MAX) + 1 : INT32_MAX; + return magnitude <= narrow_limit ? "i32" : "i64"; + } +}; + +// Parse a source integer without overflowing a host signed integer. The one +// extra positive magnitude is permitted only while recognizing unary minimum +// literals; it must never reach a PUSH_CONST as a positive signed word. +inline const char *parse_integer_literal(std::string_view spelling, + integer_literal_info &result, + bool allow_minimum_magnitude = false) { + result = {}; + if (!spelling.empty() && (spelling.front() == '+' || spelling.front() == '-')) { + result.negative = spelling.front() == '-'; + spelling.remove_prefix(1); + } + result.hexadecimal = has_hexadecimal_integer_prefix(spelling); + if (result.hexadecimal) spelling.remove_prefix(2); + if (spelling.empty()) return "integer literal requires digits"; + const auto converted = std::from_chars(spelling.data(), + spelling.data() + spelling.size(), result.magnitude, + result.hexadecimal ? 16 : 10); + if (converted.ec == std::errc::invalid_argument || + converted.ptr != spelling.data() + spelling.size()) + return "invalid character in integer literal"; + const std::uint64_t limit = std::uint64_t(INT64_MAX) + + (result.negative || allow_minimum_magnitude ? 1 : 0); + if (converted.ec == std::errc::result_out_of_range || result.magnitude > limit) + return "integer literal is outside the representable signed i64 range"; + return nullptr; +} + +inline bool is_integer_minimum_magnitude(std::string_view spelling) { + integer_literal_info info; + return !parse_integer_literal(spelling, info, true) && !info.negative && + info.magnitude == std::uint64_t(INT64_MAX) + 1; +} + +// Fold only the two signed boundaries. Other negations remain ordinary typed +// arithmetic, including hexadecimal i32 masks and double-negation wrapping. +inline std::optional +negated_integer_boundary(std::string_view spelling) { + integer_literal_info info; + if (parse_integer_literal(spelling, info, true) || info.negative) return {}; + if ((!info.hexadecimal && info.magnitude == std::uint64_t(INT32_MAX) + 1) || + info.magnitude == std::uint64_t(INT64_MAX) + 1) + return "-" + std::string(spelling); + return {}; +} + // Source literals and textual/binary NIL must agree on both spelling and // rounding. stod is locale-sensitive and rejects representable subnormals on // platforms whose strtod sets ERANGE for them; from_chars does neither. diff --git a/nilcompiler/src/parser.cpp b/nilcompiler/src/parser.cpp index add28055..17ac7676 100644 --- a/nilcompiler/src/parser.cpp +++ b/nilcompiler/src/parser.cpp @@ -35,6 +35,17 @@ namespace ny { static thread_local std::optional parser_current_module; +// Nested matches temporarily replace the enclosing target/body boundary. +// Patterns and guards disable it: subtraction immediately before their arrow +// belongs to the expression, not to a following negative literal arm. +struct match_boundary_scope { + std::optional &boundary; + const std::optional previous; + match_boundary_scope(std::optional &value, size_t depth) + : boundary(value), previous(value) { boundary = depth; } + ~match_boundary_scope() { boundary = previous; } +}; + // ---------------------------- // Utilities // ---------------------------- @@ -467,6 +478,22 @@ std::shared_ptr parser::parse_program() { synchronize(); } } + // Validate the complete token stream, not just expressions reached by the + // checker/code generator. Defaults, unused lambdas and unchecked builds + // must diagnose unsupported integer words as well. Unary minimum literals + // have replaced their positive boundary spelling by this point. + for (size_t index = 0; index < tokens_.size(); ++index) { + const auto &number = tokens_[index]; + if (number.kind != token_kind::number_literal || + is_floating_literal_spelling(number.lexeme)) continue; + integer_literal_info info; + if (const auto *message = parse_integer_literal(number.lexeme, info)) { + const auto boundary = integer_boundaries_.find(index); + if (boundary == integer_boundaries_.end() || + parse_integer_literal(boundary->second->value, info)) + add_error(number, message); + } + } return program; } @@ -2716,6 +2743,11 @@ std::shared_ptr parser::parse_expr_statement() { // Expressions (precedence climbing) // ---------------------------- std::shared_ptr parser::parse_expression() { + struct depth_scope { + size_t &depth; + explicit depth_scope(size_t &value) : depth(value) { ++depth; } + ~depth_scope() { --depth; } + } scope(expression_depth_); return parse_assignment(); } @@ -2848,7 +2880,12 @@ std::shared_ptr parser::parse_comparison() { std::shared_ptr parser::parse_term() { auto expr = parse_factor(); - while (match(token_kind::plus) || match(token_kind::minus)) { + while (check(token_kind::plus) || check(token_kind::minus)) { + // A numeric arm following an expression/return can begin with unary + // minus. Its arrow distinguishes it from a multiline subtraction. + if (match_arm_boundary_depth_ == expression_depth_ && + check(token_kind::minus) && is_match_arm_start()) break; + advance(); auto op = previous(); auto right = parse_factor(); expr = std::make_shared(expr, op.kind, right, op.line); @@ -2894,6 +2931,14 @@ std::shared_ptr parser::parse_unary() { match(token_kind::tilde)) { auto op = previous(); auto right = parse_unary(); + if (op.kind == token_kind::minus && right && + right->kind == ast_node_kind::number_literal_node) { + auto &number = static_cast(*right); + if (const auto folded = negated_integer_boundary(number.value)) { + number.value = *folded; + return right; + } + } return std::make_shared(op.kind, right, op.line); } else if (match(token_kind::not_kw)) { auto op = previous(); @@ -3249,7 +3294,10 @@ std::shared_ptr parser::parse_primary() { if (match(token_kind::number_literal)) { auto num_tok = previous(); debug_peek("matched number_literal"); - return std::make_shared(num_tok.lexeme, num_tok.line); + auto number = std::make_shared(num_tok.lexeme, num_tok.line); + if (is_integer_minimum_magnitude(number->value)) + integer_boundaries_.emplace(pos_ - 1, number); + return number; } if (match(token_kind::string_literal)) { auto str_tok = previous(); @@ -3469,6 +3517,7 @@ std::shared_ptr parser::parse_primary() { std::shared_ptr parser::parse_match_expression() { // 'match' already consumed token start_tok = previous(); + match_boundary_scope boundary(match_arm_boundary_depth_, expression_depth_ + 1); // Parse target expression auto target = parse_expression(); @@ -3487,6 +3536,8 @@ std::shared_ptr parser::parse_match_expression() { if (!use_braces && check(token_kind::end_kw)) break; + // Patterns and guards may contain subtraction before the arrow. + match_arm_boundary_depth_.reset(); // Pattern ast_expr_ptr pattern = nullptr; @@ -3515,6 +3566,7 @@ std::shared_ptr parser::parse_match_expression() { // Body: For expression-style match arms we accept a single expression // statement. For block-style match arms, parse_statement handles both. + match_arm_boundary_depth_ = expression_depth_ + 1; auto body = parse_statement(); cases.emplace_back(pattern, guard, body); @@ -3663,11 +3715,20 @@ ast_pattern parser::parse_pattern() { } } + // A sign belongs to the literal in a statement pattern, including signed + // minima whose positive magnitude cannot be represented as an i64 word. + const bool negative_number = check(token_kind::minus) && + pos_ + 1 < tokens_.size() && + tokens_[pos_ + 1].kind == token_kind::number_literal; + if (negative_number) advance(); // Numeric literal pattern if (match(token_kind::number_literal)) { token n = previous(); pat.kind = ast_pattern_kind::literal_pattern; - pat.literal_value = n.lexeme; + pat.literal_value = (negative_number ? "-" : "") + n.lexeme; + if (negative_number && is_integer_minimum_magnitude(n.lexeme)) + integer_boundaries_.emplace(pos_ - 1, + std::make_shared(pat.literal_value, n.line)); return pat; } @@ -3750,7 +3811,9 @@ bool parser::is_match_arm_start() const { } // First token must be an identifier (variant, `_`, bare name) or literal. - bool first_ok = (first.kind == token_kind::identifier || + const bool negative_number = first.kind == token_kind::minus && + i + 1 < tokens_.size() && tokens_[i + 1].kind == token_kind::number_literal; + bool first_ok = (negative_number || first.kind == token_kind::identifier || first.kind == token_kind::number_literal || first.kind == token_kind::true_kw || first.kind == token_kind::false_kw || @@ -3760,6 +3823,7 @@ bool parser::is_match_arm_start() const { return false; i++; // consume the identifier / literal + if (negative_number) ++i; // Skip optional `:: qualifier` or `.qualifier` sequences while (i + 1 < tokens_.size() && @@ -3794,6 +3858,7 @@ bool parser::is_match_arm_start() const { std::shared_ptr parser::parse_match_statement() { // 'match' already consumed by the caller (i.e., parse_statement) token start_tok = previous(); + match_boundary_scope boundary(match_arm_boundary_depth_, expression_depth_ + 1); // Parse the target expression for the match statement. auto target = parse_expression(); @@ -3812,6 +3877,7 @@ std::shared_ptr parser::parse_match_statement() { if (!use_braces && check(token_kind::end_kw)) break; + match_arm_boundary_depth_.reset(); // Parse the structural pattern for this arm ast_pattern pattern = parse_pattern(); @@ -3828,6 +3894,7 @@ std::shared_ptr parser::parse_match_statement() { // A single `->` after a pattern-like token signals a new arm; statement // keywords (return, let, if, …) signal more statements in this arm. int body_line = previous().line; + match_arm_boundary_depth_ = expression_depth_ + 1; auto body_block = std::make_shared(body_line); body_block->statements.push_back(parse_statement()); while (!is_at_end() && diff --git a/nilcompiler/src/parser.hpp b/nilcompiler/src/parser.hpp index 97c62ca4..cbbb2b7d 100644 --- a/nilcompiler/src/parser.hpp +++ b/nilcompiler/src/parser.hpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include "ast.hpp" @@ -213,7 +214,13 @@ class parser { // Token stream / source tracking std::vector tokens_; + // Keep the AST spelling for the single magnitude that becomes valid only + // under direct unary minus, including otherwise unused/default expressions. + std::unordered_map> + integer_boundaries_; size_t pos_ = 0; // current token index (points at the next token) + size_t expression_depth_ = 0; + std::optional match_arm_boundary_depth_; parser_options options_; // Local copy of preprocessor options (for convenience in the parser). diff --git a/nilcompiler/src/type_checker.cpp b/nilcompiler/src/type_checker.cpp index 276f18ae..0d8111aa 100644 --- a/nilcompiler/src/type_checker.cpp +++ b/nilcompiler/src/type_checker.cpp @@ -822,7 +822,7 @@ bool type_checker::are_types_compatible(const type_info &t1, } // Allow i32 ↔ i64 implicit conversion (integer literal coercion). - // Integer literals are always typed as i32; comparing them to i64 variables + // Small integer literals infer i32; comparing them to i64 variables // (e.g. `handle < 0`) is valid and common. if ((t1.name == "i32" && t2.name == "i64") || (t1.name == "i64" && t2.name == "i32")) { @@ -1589,37 +1589,9 @@ type_info type_checker::infer_literal_type(const std::string &literal) const { double value = 0.0; if (!parse_floating_literal(literal, value)) return type_f64; } - if (has_hexadecimal_integer_prefix(literal)) return type_i32; - - // Decimal integer detection (floating/hex literals handled above). - bool numeric = true; - bool has_dot = false; - for (size_t i = 0; i < literal.size(); ++i) { - char c = literal[i]; - if (c == '+' || c == '-') { - // sign allowed at start only - if (i > 0) { - numeric = false; - break; - } - continue; - } - if (c == '.') { - if (has_dot) { - numeric = false; - break; - } - has_dot = true; - continue; - } - if (!std::isdigit(static_cast(c))) { - numeric = false; - break; - } - } - if (numeric) { - return has_dot ? type_f64 : type_i32; - } + integer_literal_info integer; + if (!parse_integer_literal(literal, integer)) + return integer.inferred_type() == std::string_view("i64") ? type_i64 : type_i32; // Fallback to string return type_string; @@ -5850,11 +5822,17 @@ void type_checker::visit(ast_string_literal &e) { } void type_checker::visit(ast_number_literal &e) { - // Infer i32 or f64 based on content if (is_floating_literal_spelling(e.value)) { last_expr_type_ = type_f64; } else { - last_expr_type_ = type_i32; + integer_literal_info integer; + if (const auto *message = parse_integer_literal(e.value, integer)) { + add_error(e.line, message); + last_expr_type_ = type_unknown; + } else { + last_expr_type_ = integer.inferred_type() == std::string_view("i64") + ? type_i64 : type_i32; + } } e.inferred_type = last_expr_type_->name; } @@ -6053,17 +6031,28 @@ void type_checker::visit(ast_array_literal_expr &e) { } std::optional elem_type; + std::vector element_types; for (auto &el : e.elements) { el->accept(*this); type_info t = last_expr_type_.value_or(type_unknown); + element_types.push_back(t); if (!elem_type.has_value()) { elem_type = t; } else { - if (!are_types_compatible(*elem_type, t)) { - add_error(e.line, "Array element type mismatch. Expected '" + - elem_type->name + "', got '" + t.name + "'"); - } - } + // Scalar i32/i64 compatibility must not make an array's width depend + // on element order. Existing array values remain invariant; this join + // applies only while constructing a new literal. + if ((elem_type->name == "i32" && t.name == "i64") || + (elem_type->name == "i64" && t.name == "i32")) + elem_type = type_i64; + } + } + // Recheck every element against the final width: a previously compatible + // bool/i32 pair does not make bool compatible with a later i64 element. + for (const auto &type : element_types) { + if (!are_types_compatible(*elem_type, type)) + add_error(e.line, "Array element type mismatch. Expected '" + + elem_type->name + "', got '" + type.name + "'"); } // Construct array type string: array diff --git a/nilcompiler/src/type_checker.hpp b/nilcompiler/src/type_checker.hpp index 3d413278..ce5ee7b5 100644 --- a/nilcompiler/src/type_checker.hpp +++ b/nilcompiler/src/type_checker.hpp @@ -266,6 +266,7 @@ class type_checker : public ast_node::ast_visitor { // Built-in types type_info type_void{"void", true}; type_info type_i32{"i32", true}; + type_info type_i64{"i64", true}; type_info type_f64{"f64", true}; type_info type_bool{"bool", true}; type_info type_string{"String", true}; 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 e65225a1..10751148 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -42,6 +42,9 @@ "vector-norms", "vector-norms-matrix", "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/language/core-absolute-i64-overflow-matrix.matrix b/tests/language/core-absolute-i64-overflow-matrix.matrix new file mode 100644 index 00000000..5dd738f8 --- /dev/null +++ b/tests/language/core-absolute-i64-overflow-matrix.matrix @@ -0,0 +1,7 @@ +book tests.core-absolute-i64-overflow +read everything from nil.std.core + +main returns override integer begin paragraph + say abs-i64 with x being minus 9223372036854775808 + give 0 +end paragraph diff --git a/tests/language/core-absolute-i64-overflow.native.stderr b/tests/language/core-absolute-i64-overflow.native.stderr new file mode 100644 index 00000000..a8244cf6 --- /dev/null +++ b/tests/language/core-absolute-i64-overflow.native.stderr @@ -0,0 +1 @@ +NIL native runtime error: panic: abs_i64: result is outside the i64 range diff --git a/tests/language/core-absolute-i64-overflow.ny b/tests/language/core-absolute-i64-overflow.ny new file mode 100644 index 00000000..d3344078 --- /dev/null +++ b/tests/language/core-absolute-i64-overflow.ny @@ -0,0 +1,6 @@ +import nil.std.core + +fn main() -> i32 + println(abs_i64(-9223372036854775808)) + return 0 +end fn diff --git a/tests/language/core-absolute-i64-overflow.stderr b/tests/language/core-absolute-i64-overflow.stderr new file mode 100644 index 00000000..d0467ca8 --- /dev/null +++ b/tests/language/core-absolute-i64-overflow.stderr @@ -0,0 +1 @@ +NIL interpreter runtime error: panic: abs_i64: result is outside the i64 range diff --git a/tests/language/integer-literal-widths-matrix.matrix b/tests/language/integer-literal-widths-matrix.matrix new file mode 100644 index 00000000..e084c5cc --- /dev/null +++ b/tests/language/integer-literal-widths-matrix.matrix @@ -0,0 +1,118 @@ +!!! Values and arithmetic distinguish inferred integer from long on every route. +book tests.integer-literal-widths-matrix +read everything from nil.std.core + +constant global-wide is 4294967296 +constant global-minimum is minus 9223372036854775808 + +wide-sum receives items as array of override long returns override long begin paragraph + give (items at 0) plus (items at 1) +end paragraph + +narrow-first receives items as array of override integer returns override integer begin paragraph + give items at 0 +end paragraph + +literal-return returns override long begin paragraph + give 4294967296 +end paragraph + +increment receives input as override long returns override long begin paragraph + give input plus 1 +end paragraph + +classify receives input as override long returns override integer begin paragraph + consider input + when 4294967296 then give 2 + when minus 9223372036854775808 then give 1 + when 0x7FFFFFFFFFFFFFFF then give 3 + otherwise give 0 + end consider + give 0 +end paragraph + +classify-mask receives input as override integer returns override integer begin paragraph + consider input + when 0 then give 0 + when minus 0xFFFFFFFF then give 6 + otherwise give 0 + end consider + give 0 +end paragraph + +main returns override integer begin paragraph + say 2147483647 + say 2147483647 plus 1 + say minus 2147483648 + say minus 2147483648 minus 1 + say minus (2147483648) + say minus (minus 2147483648) + say 2147483648 + say 2147483648 plus 1 + say 4294967295 plus 1 + say minus 2147483649 minus 1 + say 9223372036854775807 + say 9223372036854775807 plus 1 + say minus 9223372036854775808 + say minus 9223372036854775808 minus 1 + say minus (minus 9223372036854775808) + say minus 0x8000000000000000 + say 0x7FFFFFFF plus 1 + say 0x80000000 + say 0xFFFFFFFF + value sign-mask is 0x80000000 + value all-bits is 0xFFFFFFFF + say sign-mask + say all-bits + say 0xFFFFFFFF becomes override long + say minus 0x80000000 + say 0x100000000 + say 0x7FFFFFFFFFFFFFFF + say 0xFFFFFFFF bitwise and 0x80000000 + say 0x100000000 bitwise or 0x00000001 + say 0x100000000 shifted right by 32 + say 4294967295 shifted right by 32 + say global-wide + say global-minimum + say increment with input being (literal-return with nothing) + + value low-first is [1, 2147483648] + value high-first is [2147483648, 1] + say wide-sum with items being low-first + say wide-sum with items being high-first + value small is 7 + value wide is 4294967296 + value variables-low-first is [small, wide] + value variables-high-first is [wide, small] + say wide-sum with items being variables-low-first + say wide-sum with items being variables-high-first + value signed-masks is [all-bits, 4294967296] + say wide-sum with items being signed-masks + say wide-sum with items being [0xFFFFFFFF, 4294967296] + say wide-sum with items being [4294967296, 0xFFFFFFFF] + value minimums is [minus 2147483648, minus 9223372036854775808] + say minimums at 0 + say minimums at 1 + say narrow-first with items being [0xFFFFFFFF, 0x80000000] + + value narrowed as override integer is 4294967297 + value narrow-items as array of override integer is [2147483648, 4294967297] + say narrowed + say narrow-items at 0 + say narrow-items at 1 + say 4294967295 becomes override integer + say (minus 2147483649) becomes override integer + say (4294967295 becomes override integer) becomes override long + + say classify with input being minus 9223372036854775808 + say classify with input being 4294967296 + say classify with input being 9223372036854775807 + say consider minus 9223372036854775808 when minus 9223372036854775808 give 4 otherwise give 0 end consider + say consider 4294967296 when 0x100000000 give 5 otherwise give 0 end consider + say classify-mask with input being 1 + say consider 1 when minus 0xFFFFFFFF give 7 otherwise give 0 end consider + say abs-i64 with x being 0 + say abs-i64 with x being minus 4294967296 + say abs-i32 with x being 0 + give 0 +end paragraph diff --git a/tests/language/integer-literal-widths-matrix.stdout b/tests/language/integer-literal-widths-matrix.stdout new file mode 100644 index 00000000..b86fefb8 --- /dev/null +++ b/tests/language/integer-literal-widths-matrix.stdout @@ -0,0 +1,58 @@ +2147483647 +-2147483648 +-2147483648 +2147483647 +-2147483648 +-2147483648 +2147483648 +2147483649 +4294967296 +-2147483650 +9223372036854775807 +-9223372036854775808 +-9223372036854775808 +9223372036854775807 +-9223372036854775808 +-9223372036854775808 +-2147483648 +2147483648 +4294967295 +-2147483648 +-1 +4294967295 +-2147483648 +4294967296 +9223372036854775807 +-2147483648 +4294967297 +1 +0 +4294967296 +-9223372036854775808 +4294967297 +2147483649 +2147483649 +4294967303 +4294967303 +4294967295 +8589934591 +8589934591 +-2147483648 +-9223372036854775808 +-1 +1 +-2147483648 +1 +-1 +2147483647 +-1 +1 +2 +3 +4 +5 +6 +7 +0 +4294967296 +0 diff --git a/tests/language/integer-literal-widths.ny b/tests/language/integer-literal-widths.ny new file mode 100644 index 00000000..ea538ea7 --- /dev/null +++ b/tests/language/integer-literal-widths.ny @@ -0,0 +1,125 @@ +# Values and arithmetic distinguish inferred i32 from i64 on every route. +import nil.std.core + +const global_wide = 4294967296 +const global_minimum = -9223372036854775808 + +fn wide_sum(items: array) -> i64 + return items[0] + items[1] +end fn + +fn narrow_first(items: array) -> i32 + return items[0] +end fn + +fn literal_return() -> i64 + return 4294967296 +end fn + +fn increment(value: i64) -> i64 + return value + 1 +end fn + +fn classify(value: i64) -> i32 + match value + 4294967296 -> return 2 + -9223372036854775808 -> return 1 + 0x7FFFFFFFFFFFFFFF -> return 3 + _ -> return 0 + end match + return 0 +end fn + +fn classify_mask(value: i32) -> i32 + match value + 0 -> return 0 + -0xFFFFFFFF -> return 6 + _ -> return 0 + end match + return 0 +end fn + +fn main() -> i32 + println(2147483647) + println(2147483647 + 1) + println(-2147483648) + println(-2147483648 - 1) + println(-(2147483648)) + println(-(-2147483648)) + println(2147483648) + println(2147483648 + 1) + println(4294967295 + 1) + println(-2147483649 - 1) + println(9223372036854775807) + println(9223372036854775807 + 1) + println(-9223372036854775808) + println(-9223372036854775808 - 1) + println(-(-9223372036854775808)) + println(-0x8000000000000000) + println(0x7FFFFFFF + 1) + println(0x80000000) + println(0xFFFFFFFF) + let sign_mask = 0x80000000 + let all_bits = 0xFFFFFFFF + println(sign_mask) + println(all_bits) + println(0xFFFFFFFF as i64) + println(-0x80000000) + println(0x100000000) + println(0x7FFFFFFFFFFFFFFF) + println(0xFFFFFFFF & 0x80000000) + println(0x100000000 | 0x00000001) + println(0x100000000 >> 32) + println(4294967295 >> 32) + println(global_wide) + println(global_minimum) + println(increment(literal_return())) + + let low_first = [1, 2147483648] + let high_first = [2147483648, 1] + println(wide_sum(low_first)) + println(wide_sum(high_first)) + let small = 7 + let wide = 4294967296 + let variables_low_first = [small, wide] + let variables_high_first = [wide, small] + println(wide_sum(variables_low_first)) + println(wide_sum(variables_high_first)) + let signed_masks = [all_bits, 4294967296] + println(wide_sum(signed_masks)) + println(wide_sum([0xFFFFFFFF, 4294967296])) + println(wide_sum([4294967296, 0xFFFFFFFF])) + let minimums = [-2147483648, -9223372036854775808] + println(minimums[0]) + println(minimums[1]) + println(narrow_first([0xFFFFFFFF, 0x80000000])) + + let narrowed: i32 = 4294967297 + let narrow_items: array = [2147483648 as i32, 4294967297 as i32] + println(narrowed) + println(narrow_items[0]) + println(narrow_items[1]) + println(4294967295 as i32) + println((-2147483649) as i32) + println((4294967295 as i32) as i64) + + println(classify(-9223372036854775808)) + println(classify(4294967296)) + println(classify(9223372036854775807)) + println(match -9223372036854775808 { -9223372036854775808 -> 4; _ -> 0; }) + println(match 4294967296 { 0x100000000 -> 5; _ -> 0; }) + println(classify_mask(1)) + println(match 1 { -0xFFFFFFFF -> 7; _ -> 0; }) + println(abs_i64(0)) + println(abs_i64(-4294967296)) + println(abs_i32(0)) + println(match 1 { 2 - 1 -> 8; _ -> 0; }) + println(match 1 { 1 when 2 == 3 - 1 -> 9; _ -> 0; }) + match 7 + -1 -> println(0) + 7 -> println(match 1 { 2 - 1 -> 10; _ -> 0; }) + -2 -> println(0) + _ -> println(0) + end match + return 0 +end fn diff --git a/tests/language/integer-literal-widths.stdout b/tests/language/integer-literal-widths.stdout new file mode 100644 index 00000000..e0dcbdec --- /dev/null +++ b/tests/language/integer-literal-widths.stdout @@ -0,0 +1,61 @@ +2147483647 +-2147483648 +-2147483648 +2147483647 +-2147483648 +-2147483648 +2147483648 +2147483649 +4294967296 +-2147483650 +9223372036854775807 +-9223372036854775808 +-9223372036854775808 +9223372036854775807 +-9223372036854775808 +-9223372036854775808 +-2147483648 +2147483648 +4294967295 +-2147483648 +-1 +4294967295 +-2147483648 +4294967296 +9223372036854775807 +-2147483648 +4294967297 +1 +0 +4294967296 +-9223372036854775808 +4294967297 +2147483649 +2147483649 +4294967303 +4294967303 +4294967295 +8589934591 +8589934591 +-2147483648 +-9223372036854775808 +-1 +1 +-2147483648 +1 +-1 +2147483647 +-1 +1 +2 +3 +4 +5 +6 +7 +0 +4294967296 +0 +8 +9 +10 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/parser_tests.cpp b/tests/parser_tests.cpp index b1670e7e..89592d10 100644 --- a/tests/parser_tests.cpp +++ b/tests/parser_tests.cpp @@ -3,6 +3,7 @@ #include "nil_loader.hpp" #include "type_checker.hpp" #include "matrix_lexer.hpp" +#include "matrix_parser.hpp" #include "numeric_literal.hpp" #include @@ -483,6 +484,113 @@ void test_scientific_numeric_literals() { } } +void test_integer_literal_ranges_and_unchecked_arrays() { + for (const auto &entry : std::vector>{ + {"2147483647", "i32"}, {"-2147483648", "i32"}, + {"2147483648", "i64"}, {"-2147483649", "i64"}, + {"9223372036854775807", "i64"}, {"-9223372036854775808", "i64"}, + {"0xFFFFFFFF", "i32"}, {"0x100000000", "i64"}, + {"-0x8000000000000000", "i64"}, {"0002147483648", "i64"}}) { + ny::integer_literal_info info; + check(!ny::parse_integer_literal(entry.first, info) && + info.inferred_type() == entry.second, + "integer literal width for " + entry.first); + } + for (const auto *spelling : {"9223372036854775808", "-9223372036854775809", + "0x8000000000000000", "0xFFFFFFFFFFFFFFFF", + "18446744073709551616", "0x", "12junk"}) { + ny::integer_literal_info info; + check(ny::parse_integer_literal(spelling, info) != nullptr, + std::string("invalid signed integer is rejected: ") + spelling); + } + for (const auto *spelling : {"9223372036854775808", "0x8000000000000000"}) { + ny::parser valid("fn main() -> i32\nlet value = -(" + std::string(spelling) + + ")\nreturn 0\nend fn\n"); + valid.parse_program(); + check(!valid.has_errors(), "Ny parenthesized unary minimum parses"); + matrix::parser valid_matrix("book tests.integer-boundaries\nmain returns number begin paragraph\n" + "value sample is minus (" + std::string(spelling) + ")\ngive 0\nend paragraph\n"); + valid_matrix.parse_program(); + check(!valid_matrix.has_errors(), "Matrix parenthesized unary minimum parses"); + ny::parser invalid("fn unused(value: i64 = " + std::string(spelling) + + ")\nend fn\n"); + invalid.parse_program(); + check(invalid.has_errors(), "unused default cannot hide a positive minimum magnitude"); + } + + ny::parser unchecked( + "fn main() -> i32\n" + " let wide = 2147483648\n let small: i32 = 1\n" + " let a = [1, 2147483648]\n let b = [2147483648, 1]\n" + " let c = [small, wide]\n let d = [wide, small]\n" + " let e = [-2147483648, 0xFFFFFFFF]\n" + " let f = [1, 0x100000000]\n" + " let legacy = 2147483647 + 1\n return 0\nend fn\n"); + const auto program = unchecked.parse_program(); + check(program && !unchecked.has_errors(), "unchecked array fixture parses"); + if (!program || unchecked.has_errors()) return; + // Deliberately skip type_checker::check. The CLI's --no-typecheck flag still + // invokes the checker and therefore cannot qualify this fallback by itself. + ny::codegen generator; + std::vector diagnostics; + const auto module = generator.generate_module(*program, &diagnostics); + check(module && diagnostics.empty(), "unchecked literal/variable arrays lower"); + if (module) { + std::vector elements; + bool legacy_word_add = false; + for (const auto &function : module->functions) + for (const auto &instruction : function.body) { + if (instruction.opname == "NEW_ARRAY_LITERAL" && instruction.args.size() == 2) + elements.push_back(instruction.args[1]); + if (instruction.opname == "ADD" && instruction.args.empty()) legacy_word_add = true; + } + check(elements == std::vector{"i64", "i64", "i64", "i64", "i32", "i64"}, + "unchecked arrays join every literal/variable width symmetrically"); + check(legacy_word_add, "unchecked arithmetic keeps legacy untyped word semantics"); + } + for (const auto *elements : {"1, true, 2147483648", "2147483648, true, 1"}) { + ny::parser mixed("fn main() -> i32\nlet values = [" + std::string(elements) + + "]\nreturn 0\nend fn\n"); + const auto mixed_program = mixed.parse_program(); + ny::type_checker checker; + check(mixed_program && !checker.check(*mixed_program), + "final integer array width cannot inherit bool/i32 compatibility"); + } + ny::parser arms("fn main() -> i32\nmatch 7\n" + "0 -> return 2\n - 1\n" + "-2 -> return 3\n_ -> return 0\nend match\nreturn 0\nend fn\n"); + const auto arm_program = arms.parse_program(); + check(arm_program && !arms.has_errors(), + "negative later arms coexist with multiline subtraction"); + if (arm_program && !arms.has_errors()) { + const auto function = std::dynamic_pointer_cast(arm_program->declarations[0]); + const auto block = std::dynamic_pointer_cast(function->body); + const auto match = std::dynamic_pointer_cast(block->statements[0]); + const auto result = match && !match->arms.empty() + ? std::dynamic_pointer_cast(match->arms[0].body) : nullptr; + const auto subtraction = result ? std::dynamic_pointer_cast(result->value) : nullptr; + check(match && match->arms.size() == 3 && subtraction && + subtraction->op == ny::token_kind::minus, + "only a numeric pattern followed by an arrow ends the previous expression"); + } + ny::parser arithmetic_patterns( + "fn main() -> i32\n" + "println(match 1 { 2 - 1 -> 7; _ -> 0; })\n" + "println(match 1 { 1 when 2 == 3 - 1 -> 8; _ -> 0; })\n" + "match 7\n-1 -> return 1\n" + "7 -> println(match 1 { 2 - 1 -> 7; _ -> 0; })\n" + "-2 -> return 2\n_ -> return 0\nend match\n" + "return 0\nend fn\n"); + const auto arithmetic_program = arithmetic_patterns.parse_program(); + check(arithmetic_program && !arithmetic_patterns.has_errors(), + "subtraction in patterns/guards and nested matches is not an arm boundary"); + if (arithmetic_program && !arithmetic_patterns.has_errors()) { + ny::type_checker checker; + check(checker.check(*arithmetic_program), + "arithmetic expression patterns and guards retain their checked meaning"); + } +} + } // namespace int main() { @@ -497,6 +605,7 @@ int main() { test_checker_sessions_do_not_share_impl_visitation(); test_enum_variant_mismatch_terminates(); test_scientific_numeric_literals(); + test_integer_literal_ranges_and_unchecked_arrays(); if (failures != 0) return 1; 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()) diff --git a/tests/tools/integer_literals_contract.py b/tests/tools/integer_literals_contract.py new file mode 100644 index 00000000..c4daf17b --- /dev/null +++ b/tests/tools/integer_literals_contract.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Check integer literal rejection, editor diagnostics, and no-typecheck routes.""" + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile + + +REPOSITORY = Path(__file__).resolve().parents[2] +SENTINEL = b'previous artifact' + + +def source_with_literal(language, context, literal): + """Keep unused defaults in the source-validation contract as well.""" + if language == 'ny': + prefix = '' + if context == 'default': + prefix = f'fn unused(value: i64 = {literal}) -> i64\nreturn value\nend fn\n' + body = 'println(0)' + elif context == 'statement-pattern': + body = f'match 1\n{literal} -> println(1)\nend match' + elif context == 'expression-pattern': + body = f'println(match 1 {{ {literal} -> 1; _ -> 0; }})' + else: + body = f'let invalid = {literal}' + return f'{prefix}fn main() -> i32\n{body}\nreturn 0\nend fn\n' + literal = 'minus ' + literal[1:] if literal.startswith('-') else literal + prefix = 'book tests.invalid-integer\n' + if context == 'default': + # A Matrix default is a primary expression; parentheses admit unary minus. + prefix += ('unused receives input as override long defaulting to ' + f'({literal}) returns override long begin paragraph\n' + 'give input\nend paragraph\n') + body = 'say 0' + elif context == 'statement-pattern': + body = f'consider 1\nwhen {literal} then say 1\nend consider' + elif context == 'expression-pattern': + body = f'say consider 1 when {literal} give 1 otherwise give 0 end consider' + else: + body = f'value invalid is {literal}' + return (prefix + 'main returns override integer begin paragraph\n' + f'{body}\ngive 0\nend paragraph\n') + + +def rejected_source(compiler, path, flags, environment, root, expected_message=None): + output = root / 'protected-output' + output.write_bytes(SENTINEL) + command = [compiler, '--quiet', '--no-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 result.stderr, ( + command, result.returncode, result.stdout, result.stderr) + if expected_message is not None: + assert expected_message in result.stderr, (command, result.stderr, expected_message) + assert output.read_bytes() == SENTINEL, command + + +def rejected_analysis(compiler, path, environment, root, expected_message=None): + result = subprocess.run([compiler, '--analyze', '--no-stdlib', path], cwd=root, + env=environment, capture_output=True, text=True, timeout=30) + assert result.returncode == 1 and not result.stderr, result + analysis = json.loads(result.stdout) + assert not analysis['success'], analysis + errors = [item for item in analysis['diagnostics'] if item['severity'] == 'error'] + assert errors, analysis + if expected_message is not None: + assert any(expected_message in item['message'] for item in errors), analysis + return errors + + +def check_flag_routes(compiler, interpreter, llvm, root, environment): + # This flag suppresses semantic errors but still runs checker inference. + # Keep its consumer checks focused on values/array joins, not the separate + # historical differences in untyped scalar arithmetic overflow. + sources = { + 'ny': '''fn total(items: array) -> i64 + return items[0] + items[1] +end fn +fn main() -> i32 + let small = 7 + let wide = 4294967296 + println(total([1, 2147483648])) + println(total([2147483648, 1])) + println(total([small, wide])) + println(total([wide, small])) + println(-9223372036854775808) + println(9223372036854775807) + println(0x100000000) + return 0 +end fn +''', + 'matrix': '''book tests.integer-width-flag +total receives items as array of override long returns override long begin paragraph + give (items at 0) plus (items at 1) +end paragraph +main returns override integer begin paragraph + value small is 7 + value wide is 4294967296 + say total with items being [1, 2147483648] + say total with items being [2147483648, 1] + say total with items being [small, wide] + say total with items being [wide, small] + say minus 9223372036854775808 + say 9223372036854775807 + say 0x100000000 + give 0 +end paragraph +''', + } + expected = root / 'flag.stdout' + expected.write_text('2147483649\n2147483649\n4294967303\n4294967303\n' + '-9223372036854775808\n9223372036854775807\n4294967296\n') + routes = ('all' if llvm == 'ON' else + 'text-interpreter,binary-interpreter,bundle-text,bundle-binary') + for language, source in sources.items(): + path = root / f'flag.{language}' + path.write_text(source) + command = [sys.executable, REPOSITORY / 'tests/routes/ny_route_matrix.py', + '--compiler', compiler, '--interpreter', interpreter, + '--source', path, '--expected-stdout', expected, '--expected-exit', '0', + '--routes', routes, '--compiler-arg=--no-stdlib', + '--compiler-arg=--no-typecheck', '--work-dir', root / f'flag-{language}', + '--strict'] + result = subprocess.run(command, cwd=root, env=environment, capture_output=True, + text=True, timeout=180) + assert result.returncode == 0, (command, result.stdout, result.stderr) + return 12 if llvm == 'ON' else 8 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + compiler, interpreter = args.compiler.resolve(), args.interpreter.resolve() + environment = os.environ.copy() + for name in ('NY_LIBRARY_PATH', 'NIL_LIBRARY_PATH', 'NY_LEX_DUMP', + 'NY_PARSE_TRACE', 'NY_STDLIB_PATH'): + environment.pop(name, None) + flags = [('--no-bundle',), ('--no-bundle', '--emit-binary-nil'), + (), ('--emit-binary-nil',), ('--no-bundle', '--no-typecheck')] + if args.llvm == 'ON': + flags += [('--native',), ('--native', '--jit')] + out_of_range = ('9223372036854775808', '18446744073709551616', '9' * 400, + '-9223372036854775809', '-' + '9' * 400, + '0x8000000000000000', '0xFFFFFFFFFFFFFFFF', + '0x10000000000000000', '-0x8000000000000001') + malformed = ('0x', '0X', '0xG', '0x12G') + # Matrix renders its public `number` spelling in place of the shared i64 name. + cases = [(value, 'outside the representable signed') for value in out_of_range] + cases += [(value, None) for value in malformed] + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-integer-literals-') as directory: + root = Path(directory) + for language in ('ny', 'matrix'): + for index, (literal, expected_message) in enumerate(cases): + for context in ('expression', 'statement-pattern', 'expression-pattern', 'default'): + path = root / f'invalid-{index}-{context}.{language}' + path.write_text(source_with_literal(language, context, literal)) + for route_flags in flags: + rejected_source(compiler, path, route_flags, environment, root, + expected_message) + checks += 1 + rejected_analysis(compiler, path, environment, root, expected_message) + checks += 1 + # A numeric join inside a fresh literal does not make existing + # arrays covariant. Check both conversion directions explicitly. + for source_type, destination_type in (('i32', 'i64'), ('i64', 'i32')): + if language == 'ny': + source = ('fn main() -> i32\n' + f'let original: array<{source_type}> = ' + f'[1 as {source_type}, 2 as {source_type}]\n' + f'let invalid: array<{destination_type}> = original\n' + 'return 0\nend fn\n') + else: + names = {'i32': 'override integer', 'i64': 'override long'} + source = ('book tests.array-invariance\n' + 'main returns override integer begin paragraph\n' + f'value original as array of {names[source_type]} is [1, 2]\n' + f'value invalid as array of {names[destination_type]} is original\n' + 'give 0\nend paragraph\n') + path = root / f'invariant-{source_type}.{language}' + path.write_text(source) + display = ({'i32': 'i32', 'i64': 'i64'} if language == 'ny' else + {'i32': 'override integer', 'i64': 'number'}) + expected_message = (f"Expected 'array<{display[destination_type]}>', " + f"got 'array<{display[source_type]}>'") + for route_flags in flags: + if '--no-typecheck' not in route_flags: + rejected_source(compiler, path, route_flags, environment, root, + expected_message) + checks += 1 + errors = rejected_analysis(compiler, path, environment, root, expected_message) + invalid_start = source.index('let invalid' if language == 'ny' else 'value invalid') + assert any(item['start'] == invalid_start and expected_message in item['message'] + for item in errors), errors + checks += 1 + # Revisiting the completed join is essential: bool is compatible + # with i32 in some scalar contexts, but it is not an i64 element. + for index, array in enumerate(('[1, true, 2147483648]', + '[2147483648, true, 1]')): + path = root / f'invalid-array-{index}.{language}' + path.write_text(source_with_literal(language, 'expression', array)) + for route_flags in flags: + if '--no-typecheck' not in route_flags: + rejected_source(compiler, path, route_flags, environment, root, + 'Array element type mismatch') + checks += 1 + rejected_analysis(compiler, path, environment, root, + 'Array element type mismatch') + checks += 1 + executions = check_flag_routes(compiler, interpreter, args.llvm, root, environment) + print(f'{checks} paired integer-literal rejection/analysis checks and ' + f'{executions} no-typecheck route executions passed') + + +if __name__ == '__main__': + main()