diff --git a/CMakeLists.txt b/CMakeLists.txt index 53128e02..092bf63d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2298,16 +2298,17 @@ if(BUILD_TESTING) ) set_tests_properties(ny.qualified-enum-contract PROPERTIES LABELS "typecheck;analysis;rc" TIMEOUT 120) - foreach(scientific_frontend IN ITEMS ny matrix) - if(scientific_frontend STREQUAL "ny") - set(scientific_fixture scientific-literals) + foreach(numeric_fixture IN ITEMS scientific-literals scientific-literals-matrix + integer-literal-widths integer-literal-widths-matrix) + if(numeric_fixture MATCHES "-matrix$") + set(numeric_frontend matrix) else() - set(scientific_fixture scientific-literals-matrix) + set(numeric_frontend ny) endif() add_ny_route_test( - ny.routes.${scientific_fixture} - --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.${scientific_frontend}" - --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${scientific_fixture}.stdout" + ny.routes.${numeric_fixture} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${numeric_fixture}.${numeric_frontend}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${numeric_fixture}.stdout" --expected-exit 0 --routes all --compiler-arg=--sdk-path @@ -2315,19 +2316,19 @@ if(BUILD_TESTING) ) if(TARGET nilassembler AND TARGET nillinker) add_test( - NAME ny.tools.${scientific_fixture} + NAME ny.tools.${numeric_fixture} COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/native_toolchain_pipeline.py" --compiler $ --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/${numeric_fixture}.${numeric_frontend}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${numeric_fixture}.stdout" --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src" --work-dir "${CMAKE_CURRENT_BINARY_DIR}/tests/tools" ) - set_tests_properties(ny.tools.${scientific_fixture} PROPERTIES + set_tests_properties(ny.tools.${numeric_fixture} PROPERTIES LABELS "tools;native;rc" SKIP_RETURN_CODE 77 TIMEOUT 240) endif() endforeach() @@ -2340,6 +2341,16 @@ if(BUILD_TESTING) ) set_tests_properties(ny.scientific-literals-contract PROPERTIES LABELS "typecheck;analysis;rc" TIMEOUT 120) + add_test( + NAME ny.integer-literals-contract + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/integer_literals_contract.py" + --compiler $ + --interpreter $ + --llvm "${NIL_ENABLE_LLVM}" + ) + set_tests_properties(ny.integer-literals-contract PROPERTIES + LABELS "typecheck;analysis;rc" TIMEOUT 180) add_ny_route_test( ny.routes.canonical-option-result-methods --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/canonical-option-result-methods.ny" @@ -2634,6 +2645,35 @@ if(BUILD_TESTING) absolute-overflow core-absolute-overflow-reject.stderr ) + foreach(absolute_frontend IN ITEMS ny matrix) + if(absolute_frontend STREQUAL "ny") + set(absolute_fixture core-absolute-i64-overflow) + else() + set(absolute_fixture core-absolute-i64-overflow-matrix) + endif() + add_ny_route_test( + ny.routes.${absolute_fixture} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${absolute_fixture}.${absolute_frontend}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/routes/empty.stdout" + --expected-stderr "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/core-absolute-i64-overflow.stderr" + --expected-exit 1 + --routes text-interpreter,binary-interpreter,bundle-text,bundle-binary + --compiler-arg=--sdk-path + --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src + ) + if(NIL_ENABLE_LLVM) + add_ny_route_test( + ny.routes.native-${absolute_fixture} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/${absolute_fixture}.${absolute_frontend}" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/routes/empty.stdout" + --expected-stderr "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/core-absolute-i64-overflow.native.stderr" + --expected-exit 1 + --routes llvm-jit,llvm-aot + --compiler-arg=--sdk-path + --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src + ) + endif() + endforeach() add_ny_core_algorithm_reject_test( ny.routes.core-gcd-overflow-reject gcd-overflow 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/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index 29eda0c0..07f55675 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -921,9 +921,10 @@ evidence are under `build/random-library-work`. ### F30 — Large integer expressions can narrow before an i64 argument conversion -**Status:** Confirmed authoring/diagnostic gap; no inference change in this pass. +**Status:** Literal-range and mixed-integer-array fixes implemented; contextual +typing and Matrix's universal `number` default remain open. -**Evidence:** Passing `-9223372036854775807 - 1` to an `i64` parameter produces +**Evidence before the fix:** Passing `-9223372036854775807 - 1` to an `i64` parameter produces zero on both frontends and all six routes. The emitted NIL performs `NEG i32` and `SUB i32` before the call. The generator's normalization was correct; its test had constructed the wrong seed. Oversized bare literals are accepted @@ -939,16 +940,41 @@ unannotated arithmetic therefore does not yet follow the intended wider declared types and inferred literal expressions. The probe sources, NIL and 12 successful route executions are in `build/random-library-work/width-probes`. -**Workaround:** Bind `let maximum: i64 = 9223372036854775807` in Ny or -`value maximum as number is 9223372036854775807` in Matrix, then construct the -minimum with `-maximum - 1` or `minus maximum minus 1`. The paired RNG fixtures -use this form and verify the true i64 extrema against independent oracles. -An explicit cast on the literal operand also fixes its arithmetic width. - -**Next step / acceptance:** Define literal-range and contextual-inference policy -for both frontends. Diagnose values outside an inferred integer width, or adopt -specified wider inference; keep explicit wrapping arithmetic distinct from -accidental narrowing of a literal. Matrix's intended `number` default needs -matching inferred expression/array behavior and documentation. Cover nested -arithmetic, calls, arrays, editor diagnostics and all execution routes before -changing the language contract. +**Resolution:** [NIL-0007](../../docs/design/NIL-0007-integer-literal-widths.md) +defines shared range-aware inference: decimal literals use `i32` when +representable and `i64` otherwise. Signed boundary literals represent both +minimum values directly. Hexadecimal masks through `0xFFFFFFFF` retain their +historical `i32` width; larger supported hexadecimal values use `i64`. Values +outside the signed 64-bit carrier range fail before artifact output, including +unused/default expressions, editor analysis and unchecked compilation. +Mixed `i32`/`i64` arrays now infer `array` 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. 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/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/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/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/scripts/check-sdk-routes.py b/scripts/check-sdk-routes.py index e65225a1..7462c159 100644 --- a/scripts/check-sdk-routes.py +++ b/scripts/check-sdk-routes.py @@ -42,6 +42,7 @@ "vector-norms", "vector-norms-matrix", "qualified-enum-patterns", "qualified-enum-patterns-matrix", "scientific-literals", "scientific-literals-matrix", + "integer-literal-widths", "integer-literal-widths-matrix", "random-generators", "random-generators-matrix", "math-runtime") 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/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/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()