From 97536c395ce88609ea1a9ea14349416ced8ecfd1 Mon Sep 17 00:00:00 2001 From: Nathan Date: Fri, 23 Oct 2026 15:10:43 -0400 Subject: [PATCH 1/2] Fix native console and scalar call parity and VM allocation totals --- CMakeLists.txt | 33 +++- docs/standard-library/index.md | 9 + matrix/docs/next-version-findings.md | 99 ++++++---- nilcompiler/src/codegen.cpp | 56 +++++- nilcompiler/src/llvm_backend.cpp | 42 ++++ nilcompiler/src/native_runtime.cpp | 25 +++ nilcompiler/src/native_runtime.hpp | 4 + nilcompiler/src/vm.cpp | 22 ++- nilstd/src/io/console.ny | 5 + nilstd/src/io/package.ny | 12 +- tests/language/gc-array-growth.ny | 83 ++++++++ tests/language/gc-array-growth.stdout | 1 + tests/native_runtime_tests.cpp | 41 ++++ tests/tools/aperture_memory_contract.py | 39 ++-- tests/tools/fixtures/console-input.matrix | 15 ++ tests/tools/fixtures/console-input.ny | 15 ++ tests/tools/native_argument_contract.py | 223 ++++++++++++++++++++++ tests/tools/native_console_contract.py | 222 +++++++++++++++++++++ 18 files changed, 887 insertions(+), 59 deletions(-) create mode 100644 tests/language/gc-array-growth.ny create mode 100644 tests/language/gc-array-growth.stdout create mode 100644 tests/tools/fixtures/console-input.matrix create mode 100644 tests/tools/fixtures/console-input.ny create mode 100644 tests/tools/native_argument_contract.py create mode 100644 tests/tools/native_console_contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 98369284..20fa7424 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1008,6 +1008,24 @@ if(BUILD_TESTING) --compiler-arg=--sdk-path --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src ) + add_test(NAME nil.native-argument-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/native_argument_contract.py" + --compiler $ + --interpreter $ + --assembler $ + --llvm "${NIL_ENABLE_LLVM}") + set_tests_properties(nil.native-argument-contract PROPERTIES LABELS "interop;routes" TIMEOUT 180) + if(NIL_ENABLE_LLVM) + add_test(NAME nil.native-console-contract + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/native_console_contract.py" + --compiler $ + --interpreter $ + --assembler $ + --linker $ + --runtime $ + --stdlib "${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src") + set_tests_properties(nil.native-console-contract PROPERTIES LABELS "console;native;routes" TIMEOUT 180) + endif() if(TARGET aperture) add_executable(nil_vm_memory_profile_tests tests/vm_memory_profile_tests.cpp) target_link_libraries(nil_vm_memory_profile_tests PRIVATE nilcompiler_core) @@ -2898,7 +2916,7 @@ if(BUILD_TESTING) --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/system-exit-runtime.ny" --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/system-exit-runtime.stdout" --expected-exit 7 - --routes text-interpreter,binary-interpreter + --routes all --compiler-arg=--sdk-path --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src ) @@ -2912,6 +2930,19 @@ if(BUILD_TESTING) --compiler-arg=--sdk-path --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src ) + foreach(gc_growth_mode IN ITEMS safe unsafe) + add_ny_route_test( + ny.routes.gc-array-growth-${gc_growth_mode} + --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/gc-array-growth.ny" + --expected-stdout "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/gc-array-growth.stdout" + --expected-exit 0 + --routes text-interpreter,binary-interpreter + --compiler-arg=--sdk-path + --compiler-arg=${CMAKE_CURRENT_SOURCE_DIR}/nilstd/src + --interpreter-arg=--memory-mode=${gc_growth_mode} + --program-arg=${gc_growth_mode} + ) + endforeach() add_ny_route_test( ny.routes.gc-runtime --source "${CMAKE_CURRENT_SOURCE_DIR}/tests/language/gc-runtime.ny" diff --git a/docs/standard-library/index.md b/docs/standard-library/index.md index 33e853dc..e0731d54 100644 --- a/docs/standard-library/index.md +++ b/docs/standard-library/index.md @@ -78,6 +78,15 @@ The active tree includes these deliberately scoped families: - Base64/hex encoding under `nil.std.security` - timed suspension on interpreted and native routes under `nil.std.threading` +Console output, `nil.std.io.read_line`, and `flush` support the interpreter, +native executables, and LLVM JIT. Line input preserves bytes except for the +trailing LF; an empty line and a final nonempty line without LF are valid. +EOF and input errors fault explicitly. On POSIX, CR is preserved. Native text +uses a NUL-terminated ABI and rejects embedded NUL input; the interpreter can +retain that byte. Input publishes pending console output before reading, and +`flush` publishes standard output explicitly. Native input text is managed by +the runtime and included in Aperture's text allocation measurements. + For untrusted file/container input, `nil.std.io.read_regular_bytes` accepts an explicit byte ceiling and rejects the final-component symlink, special file, short/growing read, and observed metadata change before returning bytes. diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index d414b41a..d619371a 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1740,37 +1740,72 @@ debugger snapshots need separate contracts. The first capture owns one runtime session; restarting a paused VM must mark its old capture abandoned rather than silently combining executions. See the [Aperture design](../../aperture/docs/DESIGN.md). -### F54 — Native system-call arguments and console input still have route gaps +### F54 — Native system-call arguments and console input needed route parity **Observation:** Aperture's real-program qualification exposed two existing -native limitations. Importing `nil.std.system.*` and calling `exit(7)` passes -source checking and works in the interpreter, but direct native compilation -rejects the call with `std_sys.exit requires one i32 operand`. Writing -`exit(7 as i32)` qualifies the native boundary and preserves exit status 7 on -both routes. The source declaration already requires `i32`; an accepted literal -argument should acquire the same scalar representation as an explicitly cast -argument before native interop lowering. - -Separately, `nil.std.io.read_line()` works in the interpreter but native -compilation rejects its reachable `console.read_line` intrinsic as unsupported. -These two failures reproduce through direct native compilation with the SDK that -predates Aperture recording, so they are not profiling regressions. - -The public `nil.std.runtime.collect` wrapper also retains a VM-only -`gc.collect` intrinsic; native lowering rejects an explicit call. Native managed -safepoints do collect automatically. Profiling the existing text-lifetime stress -fixture confirms that reclaimed native storage appears in collection counters -while rooted strings survive. An explicit cross-route collection API remains -separate work from observing the collector that already runs. - -**Current handling:** Aperture passes program arguments without shell expansion -and keeps standard input attached to the target. Its contract tests exercise -space-containing and empty arguments on both routes, and line input on the VM. -Native console input is not claimed as supported. Explicitly typed `exit` -arguments qualify orderly exit profiling in both execution routes. - -**Follow-up:** Apply declared scalar parameter conversions consistently at native -interop calls, then add a paired literal/variable/explicit-cast contract. Add -native console line input with an explicit EOF, encoding and allocation-lifetime -contract, including memory-source attribution for the returned text. These are -language/runtime parity tasks rather than profiler-specific workarounds. +native limitations. `nil.std.system.exit(7)` passed source checking and worked +in the interpreter, but native compilation required an explicit `as i32` cast. +Direct native dispatch bypassed the declared wrapper's scalar parameter +boundary. Separately, native lowering did not implement the reachable +`console.read_line` and `console.flush` intrinsics. + +**Implemented:** Source lowering now applies declared scalar parameter +conversions before direct annotated interop/intrinsic dispatch. Literals, +variables, returned values, reordered Matrix named arguments, and declarations +loaded from source or binary libraries use the existing scalar conversion +semantics. Integer narrowing wraps as it does at other scalar storage +boundaries; nonfinite or out-of-range floating-to-integer conversion faults. +Text, arrays and pointer handles cannot become implicit numeric arguments. +Raw NIL and forged provider declarations must still satisfy exact native ABI +checks. This is a lowering fix; broad scalar compatibility diagnostics in the +analysis/typechecking API remain a separate task. + +Native line input and flushing now have runtime, wrapper, direct NIL, and JIT +implementations. Line input strips LF, preserves an empty line or a final +nonempty unterminated line, and faults on EOF or input errors. On POSIX, CR is +retained. UTF-8 bytes are preserved. Native text's existing NUL-terminated ABI +requires explicit rejection of embedded NUL, while the VM retains that byte. +Reading publishes a preceding console prompt before blocking. Returned native +text is managed storage that survives collection when rooted and appears in +Aperture allocation sites. Console contracts exercise Ny and Matrix, both +memory modes, long input, prompt visibility, failures and invalid ABI metadata. +Aperture exercises stdin forwarding and EOF failure reports on both routes. + +**Follow-up:** The public `nil.std.runtime.collect`, `stats`, and critical-section +wrappers still need a coherent native API. Native managed safepoints already +collect automatically, and Aperture observes reclaimed storage. Simply exposing +the internal collection helper would be misleading: it deliberately does +nothing without compiler-managed root frames. Public collection also needs +safe/unsafe mode checks, generation validation, nested critical sections, and +per-context counters with defined reset and overflow behavior. + +Public GC statistics and Aperture measure different scopes. VM GC statistics +count raw buffers and eight-byte array slots; native managed storage includes +text, records, descriptors and capacity, while raw allocations are separate. +Define those units and the returned statistics object's own allocation before +claiming cross-route equivalence. Windows console behavior still needs platform +qualification. + +Imported library allocation sites can retain a function name without a source +file when the library lacks debug metadata; a full caller stack is not captured. +An embedding host that enables the C++ input stream's `eofbit` exception mask +can also turn a valid final unterminated line into an error. Normal CLI stream +defaults are covered; custom exception-mask behavior needs a shared VM/native +input policy and a separate embedding contract. + +### F55 — VM array growth omitted cumulative allocation statistics + +**Observation:** Appending to an array increased `current_heap_usage` but left +`stats().total_allocated` unchanged. Growing an initially empty array could make +live bytes exceed cumulative bytes, including through an alias. + +**Implemented:** Each successful append charges one existing eight-byte GC +array slot to the cumulative counter. The shared accounting helper saturates +at the public signed 64-bit limit. Element replacement, explicit free, and +collection do not add or subtract cumulative allocation bytes. Safe and unsafe +VM contracts cover repeated growth, aliases, `i32`/`u8`/`bool` arrays, raw buffer +accounting, and reclamation after frames depart. + +**Follow-up:** This preserves the public GC statistics' historical slot unit. +Aperture's typed payload measurement remains independent; it must not be +silently substituted for the GC API's byte counts. diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index f0d69e48..c0dfe82b 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -3801,6 +3801,56 @@ class emitter { } } + // Direct native dispatch bypasses the declared wrapper's parameter + // boundary. Preserve that boundary explicitly: PUSH_CONST uses a word + // representation even for an i32 literal, and an accepted scalar + // argument can have a different width from the declared parameter. + // This is source lowering only; handwritten NIL must still satisfy the + // native provider's exact operand and declaration contracts. + const ast_function_decl *native_call_declaration = nullptr; + auto call_substitutions = substitutions; + if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) { + const auto &id = static_cast(*ce.callee); + const auto name = cg_.lookup_function_fqn(id.name, current_module_); + const auto *declaration = cg_.lookup_function_decl(name); + if (declaration && native_dispatch_annotation_count(*declaration) == 1) { + native_call_declaration = declaration; + for (std::size_t index = 0; + index < declaration->generic_params.size() && index < ce.type_args.size(); + ++index) + call_substitutions[declaration->generic_params[index].name] = + substitute_nil_type_name(ce.type_args[index], substitutions); + } + } + const auto emit_call_argument = [&](std::size_t index) { + std::optional scalar_type; + if (native_call_declaration && index < native_call_declaration->params.size() && + ce.args[index]->inferred_type) { + const auto ¶meter = native_call_declaration->params[index]; + if (parameter.type_name && !parameter.is_variadic) { + auto expected = substitute_nil_type_name(*parameter.type_name, call_substitutions); + if (expected == "int") expected = "i32"; + static const std::set scalar_types = { + "i32", "i64", "u8", "bool", "f64", "f32"}; + if (scalar_types.count(expected)) { + auto actual = substitute_nil_type_name(*ce.args[index]->inferred_type, substitutions); + if (actual == "int") actual = "i32"; + if (!scalar_types.count(actual)) { + cg_.reject_codegen_construct(ce.line, + "Native function '" + native_call_declaration->name + "' argument " + + std::to_string(index + 1) + " requires a scalar for parameter '" + + parameter.name + "' of type '" + expected + "', got '" + actual + "'", + "pass a checked scalar value; handles and text are not numeric arguments"); + return; + } + scalar_type = std::move(expected); + } + } + } + emit_expr(*ce.args[index], scalar_type); + emit_scalar_boundary(scalar_type, ce.args[index]->line); + }; + // Effective arg count (adjusted when variadic args are packed into array) size_t effective_arg_count = ce.args.size(); // Check for variadic last param — pack trailing args into @@ -3813,7 +3863,7 @@ class emitter { if (!vdecl->params.empty() && vdecl->params.back().is_variadic) { size_t fixed = vdecl->params.size() - 1; for (size_t i = 0; i < fixed && i < ce.args.size(); ++i) - emit_expr(*ce.args[i]); + emit_call_argument(i); size_t nvar = ce.args.size() > fixed ? ce.args.size() - fixed : 0; for (size_t i = fixed; i < ce.args.size(); ++i) emit_expr(*ce.args[i]); @@ -3832,8 +3882,8 @@ class emitter { } } if (!did_vararg_pack) { - for (const auto &arg : ce.args) - emit_expr(*arg); + for (std::size_t index = 0; index < ce.args.size(); ++index) + emit_call_argument(index); } std::string fname = ""; if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) { diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 4d0a482a..1486d889 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -2874,6 +2874,28 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << operation << "' in function '" << fn.name << "'\n"; return false; } + } else if (dispatch_name == "@intrinsic" && + (dispatch_provider == "console.read_line" || + dispatch_provider == "console.flush")) { + const bool reading = dispatch_provider == "console.read_line"; + if (!fn.params.empty() || impl_->current_function->arg_size() != 0 || + normalize_nil_type(fn.return_type) != (reading ? "text" : "void") || + (reading ? !impl_->current_function->getReturnType()->isPointerTy() + : !impl_->current_function->getReturnType()->isVoidTy())) { + std::cerr << "[NativeCodegen] " << dispatch_provider + << " requires the exact () -> " + << (reading ? "text" : "void") << " ABI\n"; + return false; + } + auto *runtime_type = llvm::FunctionType::get( + reading ? static_cast(llvm::PointerType::getUnqual(ctx)) + : llvm::Type::getVoidTy(ctx), {}, false); + auto runtime = impl_->module->getOrInsertFunction( + reading ? "nyrt_read_line" : "nyrt_flush_stdout", runtime_type); + auto *value = impl_->builder->CreateCall(runtime_type, runtime.getCallee(), {}); + if (reading) impl_->builder->CreateRet(value); + else impl_->builder->CreateRetVoid(); + annotation_handled = true; } else if (console_write || console_writeln || console_error) { if (fn.params.size() != 1 || native_handle_kind_for_nil_type(nil_parameter_type(fn.params[0])) != @@ -6523,6 +6545,24 @@ bool NativeCodegen::generateModule(const nil_module &mod) { // allowlist as strict as the wrapper lowering above; everything else // must fail closed instead of entering the legacy foreign-call path. if (lib_name == "intrinsic") { + if (func_name == "console.read_line" || func_name == "console.flush") { + const bool reading = func_name == "console.read_line"; + if (minstr.args.size() != 4 || minstr.args[2] != "0" || + minstr.args[3] != (reading ? "text" : "void")) { + std::cerr << "[NativeCodegen] " << func_name + << " requires the exact () -> " + << (reading ? "text" : "void") << " ABI\n"; + return false; + } + auto *runtime_type = llvm::FunctionType::get( + reading ? static_cast(llvm::PointerType::getUnqual(ctx)) + : llvm::Type::getVoidTy(ctx), {}, false); + auto runtime = impl_->module->getOrInsertFunction( + reading ? "nyrt_read_line" : "nyrt_flush_stdout", runtime_type); + auto *value = impl_->builder->CreateCall(runtime_type, runtime.getCallee(), {}); + if (reading) impl_->pushValue(value, "text"); + break; + } if (is_array_intrinsic(func_name) && minstr.args.size() == 5) { array_intrinsic_contract contract; try { @@ -8489,6 +8529,8 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_exit", &nyrt_exit); expose_runtime_symbol("nyrt_write_stdout", &nyrt_write_stdout); expose_runtime_symbol("nyrt_write_stderr", &nyrt_write_stderr); + expose_runtime_symbol("nyrt_read_line", &nyrt_read_line); + expose_runtime_symbol("nyrt_flush_stdout", &nyrt_flush_stdout); expose_runtime_symbol("nyrt_array_new", &nyrt_array_new); expose_runtime_symbol("nyrt_array_new_with_value", &nyrt_array_new_with_value); diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index 37941917..1a228fcf 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -1085,6 +1086,30 @@ void nyrt_write_stderr(const char *text, std::int32_t newline) noexcept { std::fputc('\n', stderr); } +const char *nyrt_read_line() noexcept { + // Console output uses C stdio. Publish pending prompts even if an embedder + // has disabled C++ stream synchronization or changed std::cin's tie. + std::fflush(stdout); + try { + std::string line; + if (!std::getline(std::cin, line)) + nyrt_fail("NIL native runtime error: console.read_line: input is unavailable or reached EOF\n"); + // Native text is a NUL-terminated ABI. Never turn a valid input prefix + // into an apparently successful read by silently dropping the suffix. + if (line.find('\0') != std::string::npos) + nyrt_fail("NIL native runtime error: console.read_line: embedded NUL is unsupported by native text\n"); + if (const char *result = own_string(line)) + return result; + } catch (const std::ios_base::failure &) { + nyrt_fail("NIL native runtime error: console.read_line: input is unavailable or reached EOF\n"); + } catch (...) { + // Allocation failures also stay inside the C ABI boundary. + } + nyrt_fail("NIL native runtime error: console.read_line: could not allocate input text\n"); +} + +void nyrt_flush_stdout() noexcept { std::fflush(stdout); } + void *nyrt_array_new(std::uint32_t kind, std::int64_t length) noexcept { if (length < 0) return nullptr; diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index c7544748..8eccd999 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -111,6 +111,10 @@ const char *nyrt_arg(std::int64_t index) noexcept; void nyrt_write_stdout(const char *text, std::int32_t newline) noexcept; void nyrt_write_stderr(const char *text, std::int32_t newline) noexcept; +// Reads through LF, retaining any CR and accepting a final unterminated line. +// The result is managed text; EOF, host errors and embedded NUL fail explicitly. +const char *nyrt_read_line() noexcept; +void nyrt_flush_stdout() noexcept; void *nyrt_array_new(std::uint32_t kind, std::int64_t length) noexcept; void *nyrt_array_new_with_value(std::uint32_t kind, std::int64_t length, diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 0f1bd766..cc9b03ff 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -82,6 +82,16 @@ std::uint64_t heap_element_stride(const std::string &type_name) { return 8; } +void account_heap_allocation(std::uint64_t &total, std::uint64_t bytes) { + const auto observable_limit = + static_cast(std::numeric_limits::max()); + const auto increment = std::min(bytes, observable_limit); + if (total > observable_limit - increment) + total = observable_limit; + else + total += increment; +} + using detail::IntegerParseResult; using detail::parse_signed_integer; @@ -1581,6 +1591,10 @@ void VM::executeInstruction(const Instruction &instr) { it->second.data.push_back( canonical_pointer_value(it->second, args[1], "array__push")); it->second.element_count++; + // Match the GC statistics' logical heap slots, independently of + // Aperture's typed payload bytes. Charge only a successful append. + account_heap_allocation(total_allocated_bytes_, + heap_element_stride(it->second.type_name)); if (memory_profile_.enabled()) memory_profile_.resize( reinterpret_cast(static_cast(handle)), @@ -6494,13 +6508,7 @@ void VM::releaseHeapBlock(int64_t pointer) { void VM::storeHeapBlock(int64_t pointer, HeapBlock block) { const std::uint64_t bytes = heapBlockBytes(block); - const std::uint64_t observable_limit = - static_cast(std::numeric_limits::max()); - if (total_allocated_bytes_ > - observable_limit - std::min(bytes, observable_limit)) - total_allocated_bytes_ = observable_limit; - else - total_allocated_bytes_ += bytes; + account_heap_allocation(total_allocated_bytes_, bytes); heap_[pointer] = std::move(block); if (memory_profile_.enabled()) { const auto &stored = heap_.at(pointer); diff --git a/nilstd/src/io/console.ny b/nilstd/src/io/console.ny index 2bc57886..91af8260 100644 --- a/nilstd/src/io/console.ny +++ b/nilstd/src/io/console.ny @@ -2,6 +2,10 @@ module nil.std.io import nil.std.core # Line-Oriented Input +# Reads one line, preserving its bytes except for the trailing LF. Empty lines +# and a final nonempty line without LF are valid; EOF or an input error faults. +# On POSIX, CR is preserved. Native text cannot contain NUL, so native input +# rejects that byte explicitly. Flushes pending console output before reading. @intrinsic("console.read_line") pub fn read_line() -> text end fn @@ -19,6 +23,7 @@ end fn pub fn write_error(s: text) end fn +# Publishes pending standard output before continuing. @intrinsic("console.flush") pub fn flush() end fn diff --git a/nilstd/src/io/package.ny b/nilstd/src/io/package.ny index 9fe2d586..095309a4 100644 --- a/nilstd/src/io/package.ny +++ b/nilstd/src/io/package.ny @@ -1,6 +1,6 @@ @pragma once # ============================================================================= -# ny.lang.io — I/O Package +# nil.std.io — I/O Package # ============================================================================= # File system, streaming, path, and console I/O. # @@ -15,12 +15,14 @@ # - Checksum: bounded and incremental CRC-32 (checksum.ny) # # The interpreter backs the file, stream, path, and console declarations. -# Their native route is not certified yet. The unbuilt compression prototype -# is preserved under experimental/ and is not part of the active SDK. +# Console output, line input, and flushing also support native execution. +# Other native I/O coverage is scoped by the standard-library documentation. +# The unbuilt compression prototype is preserved under experimental/ and is +# not part of the active SDK. # # Cross-refs: -# ny.lang.core — Result, IDisposable -# ny.lang.text — StreamReader/Writer use text encoding +# nil.std.core — Result, IDisposable +# nil.std.text — StreamReader/Writer use text encoding # ============================================================================= package nil.std.io diff --git a/tests/language/gc-array-growth.ny b/tests/language/gc-array-growth.ny new file mode 100644 index 00000000..6cf08bcd --- /dev/null +++ b/tests/language/gc-array-growth.ny @@ -0,0 +1,83 @@ +import nil.std.runtime.* +import nil.std.system.* + +fn require(passed: bool, label: text) + if not passed then panic(label) end if +end fn + +fn check_growth(first: T, second: T) + let mut values: array = [] + let mut alias = values + let before = stats() + let mut index: i32 = 0 + while index < 65 + values.push(first) + index = index + 1 + end while + let grown = stats() + # GC statistics retain their historical eight-byte array-slot unit for + # every element type, independent of Aperture's typed payload accounting. + require(grown.total_allocated - before.total_allocated == (520 as i64), "array growth charges cumulative bytes") + require(grown.current_heap_usage - before.current_heap_usage == (520 as i64), "array growth charges live bytes") + require(grown.live_allocations == before.live_allocations, "array growth preserves allocation identity") + require(grown.total_allocated >= grown.current_heap_usage, "cumulative bytes cover live heap") + + index = 0 + while index < 17 + alias.push(second) + index = index + 1 + end while + let aliased = stats() + require(values.len() == 82, "alias appends reach original array") + require(aliased.total_allocated - grown.total_allocated == (136 as i64), "alias growth is charged exactly once") + require(aliased.current_heap_usage - grown.current_heap_usage == (136 as i64), "alias growth live bytes") + require(aliased.live_allocations == before.live_allocations, "alias growth shares one allocation") + require(aliased.current_heap_usage == allocated_bytes(), "statistics agree with allocated_bytes") + + values[0] = second + let written = stats() + require(alias[0] == second, "aliases share element writes") + require(written.total_allocated == aliased.total_allocated, "element writes do not allocate") + require(written.current_heap_usage == aliased.current_heap_usage, "element writes preserve heap size") +end fn + +fn check_free() + let before = stats() + let buffer = allocate(11) + buffer[0] = 37 as u8 + let allocated = stats() + require(allocated.total_allocated - before.total_allocated == (11 as i64), "raw allocation retains its typed byte unit") + deallocate(buffer) + let freed = stats() + require(freed.total_allocated == allocated.total_allocated, "free preserves cumulative allocation bytes") + require(freed.current_heap_usage == before.current_heap_usage, "free removes live bytes") + require(freed.live_allocations == before.live_allocations, "free removes the allocation") +end fn + +fn main() -> i32 + require(arg_count() == (1 as i64), "expected safe or unsafe fixture argument") + let mode = arg(0 as i64) + require(mode == "safe" or mode == "unsafe", "unknown fixture argument") + let before = stats() + enter_critical_section() + check_growth(10, 20) + check_growth(1 as u8, 255 as u8) + check_growth(true, false) + check_free() + leave_critical_section() + + let grown = stats() + require(grown.total_allocated - before.total_allocated == (1979 as i64), "all successful allocations counted once") + require(grown.current_heap_usage - before.current_heap_usage == (1968 as i64), "three grown arrays remain live before collection") + require(grown.total_allocated >= grown.current_heap_usage, "cumulative allocation invariant after free") + if mode == "safe" then + collect(2) + let collected = stats() + require(collected.total_allocated == grown.total_allocated, "collection preserves cumulative allocation bytes") + require(collected.current_heap_usage == before.current_heap_usage, "collection reclaims departed array frames") + require(collected.live_allocations == before.live_allocations, "collection reclaims array identities") + require(collected.total_collections == grown.total_collections + (1 as i64), "explicit collection counted once") + end if + println("GC array growth accounting passed") + return 0 +end fn diff --git a/tests/language/gc-array-growth.stdout b/tests/language/gc-array-growth.stdout new file mode 100644 index 00000000..f156865f --- /dev/null +++ b/tests/language/gc-array-growth.stdout @@ -0,0 +1 @@ +GC array growth accounting passed diff --git a/tests/native_runtime_tests.cpp b/tests/native_runtime_tests.cpp index 3250b6f4..5f49a6a8 100644 --- a/tests/native_runtime_tests.cpp +++ b/tests/native_runtime_tests.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -125,6 +126,45 @@ void check_substring_contract(bool &ok) { "substring unexpectedly used scalar instead of byte offsets"); } +void check_console_input_contract(bool &ok) { + nyrt_context_begin(0, nullptr); + const std::string expected[] = {"", "snowman-\xE2\x98\x83", "retained\r", + std::string(200000, 'x'), "last"}; + std::string bytes; + for (std::size_t index = 0; index < 5; ++index) { + bytes += expected[index]; + if (index != 4) bytes += '\n'; + } + std::istringstream input(bytes); + const auto original_state = std::cin.rdstate(); + auto *original_input = std::cin.rdbuf(input.rdbuf()); + std::uint64_t values[5] = {}; + const void *slots[] = {&values[0], &values[1], &values[2], &values[3], &values[4]}; + nyrt_roots_enter(slots, 5); + std::uint64_t expected_bytes = 0; + for (std::size_t index = 0; index < 5; ++index) { + const auto *line = nyrt_read_line(); + values[index] = reinterpret_cast(line); + expected_bytes += expected[index].size() + 1; + nyrt_collect(); + for (std::size_t retained = 0; retained <= index; ++retained) + ok &= expect_text(reinterpret_cast(values[retained]), + expected[retained], "read_line changed input or lost a managed root"); + ok &= expect(nyrt_managed_bytes() == expected_bytes && + nyrt_managed_objects() == index + 1, + "read_line did not account for its owned text storage"); + } + // A final nonempty line succeeds without LF. Its text survives the EOF bit. + std::cin.rdbuf(original_input); + std::cin.clear(original_state); + for (auto &value : values) value = 0; + nyrt_collect(); + ok &= expect(nyrt_managed_bytes() == 0 && nyrt_managed_objects() == 0, + "read_line text was not reclaimed after its roots expired"); + nyrt_roots_leave(slots); + nyrt_context_end(); +} + void check_scalar_formatting(bool &ok) { ok &= expect_text(nyrt_text_i64(std::numeric_limits::min()), "-9223372036854775808", "formatting lost the signed minimum"); @@ -791,5 +831,6 @@ int main() { "context cleanup left a stale raw buffer usable"); nyrt_context_end(); + check_console_input_contract(ok); return ok ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/tests/tools/aperture_memory_contract.py b/tests/tools/aperture_memory_contract.py index b39c024c..b17aa8ec 100644 --- a/tests/tools/aperture_memory_contract.py +++ b/tests/tools/aperture_memory_contract.py @@ -237,7 +237,7 @@ def validate(path, route, source=None): 'raise Problem { code: 7 }\nreturn 0\nend fn\n') explicit_exit = root / 'explicit exit.ny' explicit_exit.write_text('import nil.std.system.*\nfn main() -> i32\n' - 'let values = [42]\nprintln(values[0])\nexit(7 as i32)\nreturn 0\nend fn\n') + 'let values = [42]\nprintln(values[0])\nexit(7)\nreturn 0\nend fn\n') for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): flags = ['--native'] if route == 'native' else [] output = root / ('owned-' + route + '.json') @@ -259,26 +259,43 @@ def validate(path, route, source=None): checks += 2 forwarding = root / 'arguments and input.ny' + forwarding.write_text('import nil.std.system.*\nimport nil.std.io.*\n' + 'fn main() -> i32\nlet values = [42]\nprintln(arg_count())\n' + 'println(arg(0))\nprintln(arg(1))\nprintln(arg(2))\n' + 'println(read_line())\nprintln(values[0])\nreturn 0\nend fn\n') for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): - # console.read_line is currently VM-only; argument forwarding is - # qualified on both routes without implying native console support. - forwarding.write_text('import nil.std.system.*\n' + - ('import nil.std.io.*\n' if route == 'vm' else '') + - 'fn main() -> i32\nlet values = [42]\nprintln(arg_count())\n' - 'println(arg(0))\nprintln(arg(1))\nprintln(arg(2))\n' + - ('println(read_line())\n' if route == 'vm' else '') + - 'println(values[0])\nreturn 0\nend fn\n') flags = ['--native'] if route == 'native' else [] output = root / ('arguments-' + route + '.json') result = run([aperture, 'memory', '--sdk-path', stdlib, '--output', output, *flags, forwarding, '--', 'space argument', '', '$(touch INJECTED)'], input_text='hello from stdin\n') - expected_forwarding = '3\nspace argument\n\n$(touch INJECTED)\n' + ('hello from stdin\n' if route == 'vm' else '') + '42\n' + expected_forwarding = '3\nspace argument\n\n$(touch INJECTED)\nhello from stdin\n42\n' assert result.stdout == expected_forwarding, result - validate(output, route, forwarding) + profile = validate(output, route, forwarding) + if route == 'native': + # The imported wrapper owns this allocation. Libraries without + # source metadata still retain its function identity. + assert any(site['kind'] == 'text' and 'read_line' in site['function'] + and site['allocated_bytes'] == 17 + for site in profile['sites']), profile assert not (root / 'INJECTED').exists(), 'program argument was interpreted by a shell' checks += 1 + # Console EOF is a target failure, with a usable incomplete profile. + eof_source = root / 'console EOF.ny' + eof_source.write_text('import nil.std.io.*\nfn main() -> i32\n' + 'let values = [42]\nprintln(values[0])\nprintln(read_line())\nreturn 0\nend fn\n') + for route in ('vm', 'native') if args.llvm == 'ON' else ('vm',): + output = root / ('console-eof-' + route + '.json') + flags = ['--native'] if route == 'native' else [] + result = run([aperture, 'memory', '--sdk-path', stdlib, '--output', output, + *flags, eof_source], 1, input_text='') + assert result.stdout == '42\n' and 'console.read_line' in result.stderr, result + profile = json.loads(output.read_text()) + assert profile['status'] == 'failed' and not profile['completed'], profile + assert profile['totals']['allocated_objects'] >= 1, profile + checks += 1 + # The requested destination must be writable and fresh before target # execution. Existing files, target source, and symlink referents survive. sentinel = root / 'existing.json' diff --git a/tests/tools/fixtures/console-input.matrix b/tests/tools/fixtures/console-input.matrix new file mode 100644 index 00000000..b799406a --- /dev/null +++ b/tests/tools/fixtures/console-input.matrix @@ -0,0 +1,15 @@ +book nil.tests.console_input + +read everything from nil.std.io + +receive returns text begin paragraph + give read_line with nothing +end paragraph + +main returns override integer begin paragraph + evaluate write with s being "input> " + evaluate flush with nothing + value line is receive with nothing + evaluate writeln with s being line + give 0 +end paragraph diff --git a/tests/tools/fixtures/console-input.ny b/tests/tools/fixtures/console-input.ny new file mode 100644 index 00000000..d6b4a238 --- /dev/null +++ b/tests/tools/fixtures/console-input.ny @@ -0,0 +1,15 @@ +module nil.tests.console_input + +import nil.std.io + +fn receive() -> text + return read_line() +end fn + +fn main() -> i32 + write("input> ") + flush() + let line = receive() + writeln(line) + return 0 +end fn diff --git a/tests/tools/native_argument_contract.py b/tests/tools/native_argument_contract.py new file mode 100644 index 00000000..e97ed9a0 --- /dev/null +++ b/tests/tools/native_argument_contract.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Declared scalar arguments retain their representation at native dispatch.""" +from __future__ import annotations + +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--interpreter', type=Path, required=True) + parser.add_argument('--assembler', type=Path, required=True) + parser.add_argument('--llvm', choices=('ON', 'OFF'), required=True) + args = parser.parse_args() + compiler, interpreter, assembler = (path.resolve() for path in + (args.compiler, args.interpreter, args.assembler)) + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NIL_', 'NY_'))} + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil native arguments ') as directory: + root = Path(directory) + + def run(command, status=0, stdout='', diagnostic=None): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=root, + env=environment, stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=120) + assert (result.returncode == status and result.stdout == stdout and + (diagnostic in result.stderr if diagnostic else not result.stderr)), ( + command, result.returncode, result.stdout, result.stderr, + status, stdout, diagnostic) + checks += 1 + return result + + def program(language, body, declarations='', imports=''): + if language == 'ny': + return imports + declarations + '\nfn main() -> i32\n' + body + '\nreturn 0\nend fn\n' + return ('book consumer\n' + imports + declarations + + '\nmain returns override integer begin paragraph\n' + body + + '\ngive 0\nend paragraph\n') + + declarations = { + 'ny': '@interop("std_sys")\nfn exit(code: i32)\nend fn\n' + 'fn returned() -> i64\nprintln("once")\nreturn 7\nend fn\n', + 'matrix': 'note interop "std_sys"\nexit receives code as override integer begin paragraph\nend paragraph\n' + 'returned returns number begin paragraph\nsay "once"\ngive 7\nend paragraph\n', + } + cases = [ + ('literal', 'exit(7)', 'evaluate exit with code being 7', ''), + ('variable', 'let code: i64 = 7\nexit(code)', + 'value code as number is 7\nevaluate exit with code being code', ''), + ('exact', 'let code: i32 = 7\nexit(code)', + 'value code as override integer is 7\nevaluate exit with code being code', ''), + ('returned', 'exit(returned())', + 'evaluate exit with code being (returned with nothing)', 'once\n'), + ('explicit', 'exit(7 as i32)', + 'evaluate exit with code being (7 becomes override integer)', ''), + ('floating', 'exit(7.9)', 'evaluate exit with code being 7.9', ''), + # Narrowing follows existing CAST/storage modulo semantics. It is + # deliberately tested rather than accidentally relying on LLVM + # coercion or OS truncation of the process exit code. + ('narrowing', 'let code: i64 = 4294967303\nexit(code)', + 'value code as number is 4294967303\nevaluate exit with code being code', ''), + ] + + def execute(source, name, search=None, status=7, stdout='', diagnostic=None, + native=True): + base = [compiler, '--quiet', '--no-stdlib'] + if search: + base += ['-I', search] + for encoding, flags in (('text', []), ('binary', ['--emit-binary-nil'])): + artifact = root / (name + '-' + encoding + '.nil') + run([*base, '--no-bundle', *flags, '-o', artifact, source]) + run([interpreter, '--no-ai', artifact], status, stdout, diagnostic) + if native and args.llvm == 'ON': + artifact = root / (name + '.native') + run([*base, '--native', '-o', artifact, source]) + run([artifact], status, stdout, diagnostic) + run([*base, '--native', '--jit', '-o', root / (name + '.jit'), source], + status, stdout, diagnostic) + + for language in ('ny', 'matrix'): + for name, ny, matrix, stdout in cases: + source = root / (name + '.' + language) + source.write_text(program(language, ny if language == 'ny' else matrix, + declarations[language])) + execute(source, name + '-' + language, stdout=stdout) + + # A scalar conversion must still check nonfinite/out-of-range + # floating values before the process-exit provider can run. + source = root / ('outside-range.' + language) + source.write_text(program(language, + 'exit(1e30)' if language == 'ny' else + 'evaluate exit with code being 1e30', declarations[language])) + execute(source, 'outside-range-' + language, status=1, + diagnostic='CAST: floating-point value is non-finite or outside i64 range') + + # Lexical callable values take precedence over the declaration + # named exit. Native indirect calls are unavailable; VM values + # must retain their i64 argument without the global i32 boundary. + for kind in ('named', 'lambda'): + if language == 'ny': + extra = 'fn wide(value: i64) -> i64\nreturn value\nend fn\n' + body = ('let exit = wide\n' if kind == 'named' else + 'let exit = fn(value: i64) -> i64\nreturn value\nend fn\n') + body += 'println(exit(4294967303))' + else: + extra = 'wide receives item as number returns number begin paragraph\ngive item\nend paragraph\n' + body = ('value exit is the paragraph wide\n' if kind == 'named' else + 'value exit is anonymous receives item as number returns number begin paragraph\n' + 'give item\nend paragraph\n') + body += 'say exit with item being 4294967303' + source = root / ('shadow-' + kind + '.' + language) + source.write_text(program(language, body, declarations[language] + extra)) + execute(source, 'shadow-' + kind + '-' + language, status=0, + stdout='4294967303\n', native=False) + + # Source and binary-only libraries retain the annotated parameter + # declaration. Matrix named arguments have already been reordered by + # the checker when codegen applies each declared scalar boundary. + for provider_language in ('ny', 'matrix'): + providers = root / ('provider-' + provider_language) + libraries = root / ('libraries-' + provider_language) + providers.mkdir() + libraries.mkdir() + provider = providers / ('boundary.' + provider_language) + provider.write_text( + 'module boundary\n@interop("std_sys")\npub fn exit(code: i32)\nend fn\n' + '@intrinsic("math.pow")\npub fn power(base: f64, exponent: f64) -> f64\nend fn\n' + if provider_language == 'ny' else + 'book boundary\nnote interop "std_sys"\npublic exit receives code as override integer begin paragraph\nend paragraph\n' + 'note intrinsic "math.pow"\npublic power receives base as floating, exponent as floating returns floating\n') + for dependency in ('source', 'binary'): + if dependency == 'binary': + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', '--emit-binary-nil', + '--emit-library', '-o', libraries / 'boundary.nil', provider]) + provider.unlink() + search = providers if dependency == 'source' else libraries + for language in ('ny', 'matrix'): + source = root / ('consumer-' + provider_language + '-' + dependency + '.' + language) + source.write_text(program(language, + 'println(power(3,2))\nexit(7)' if language == 'ny' else + 'say power with exponent being 2, base being 3\n' + 'evaluate exit with code being 7', imports= + 'import boundary.*\n' if language == 'ny' else + 'read everything from boundary\n')) + execute(source, 'library-' + provider_language + '-' + dependency + '-' + language, + search, stdout='9\n') + + # Applying scalar storage conversions must not turn handles/text into + # implicit numeric parsing or pointer casts. + invalid = [ + ('text', 'exit("7")', 'evaluate exit with code being "7"', 'requires a scalar'), + ('pointer', 'let p = allocate(1)\nexit(p)', + 'allocate p as pointer to override integer sized 1\nevaluate exit with code being p', 'requires a scalar'), + ('array', 'exit([7])', 'evaluate exit with code being [7]', 'requires a scalar'), + ('function', 'exit(returned)', + 'evaluate exit with code being the paragraph returned', 'requires a scalar'), + ('missing', 'exit()', 'evaluate exit with nothing', 'expects 1 arguments'), + ] + for language in ('ny', 'matrix'): + for name, ny, matrix, diagnostic in invalid: + source = root / ('invalid-' + name + '.' + language) + source.write_text(program(language, ny if language == 'ny' else matrix, + declarations[language])) + for flags in (['--no-bundle'], ['--no-bundle', '--emit-binary-nil'], + *([['--native'], ['--native', '--jit']] if args.llvm == 'ON' else [])): + output = root / 'protected-output' + output.write_bytes(b'previous artifact') + run([compiler, '--quiet', '--no-stdlib', *flags, '-o', output, source], + status=1, diagnostic=diagnostic) + assert output.read_bytes() == b'previous artifact' + + if args.llvm == 'ON': + # Source casts qualify operands without relaxing provider ABIs. + # A forged declaration still produces a rejected i64/f64 operand. + for language in ('ny', 'matrix'): + for width in ('i64', 'f64'): + source = root / ('forged-' + width + '.' + language) + declaration = ( + f'@interop("std_sys")\nfn exit(code: {width})\nend fn\n' + if language == 'ny' else + 'note interop "std_sys"\nexit receives code as ' + + ('number' if width == 'i64' else 'floating') + + ' begin paragraph\nend paragraph\n') + source.write_text(program(language, + 'exit(7)' if language == 'ny' else + 'evaluate exit with code being 7', declaration)) + for flags in (['--native'], ['--native', '--jit']): + output = root / 'protected-output' + output.write_bytes(b'previous artifact') + run([compiler, '--quiet', '--no-stdlib', *flags, '-o', output, source], + status=1, diagnostic='std_sys.exit requires one i32 operand') + assert output.read_bytes() == b'previous artifact' + + raw = root / 'raw.nil' + output = root / 'raw.o' + valid = ('module raw\nfunction main() -> i32:\n' + 'PUSH_CONST 7\nCAST i32\nINTEROP_CALL std_sys exit 1 void\n' + 'PUSH_CONST 0\nCAST i32\nRET\nend function\n') + raw.write_text(valid) + run([assembler, '-o', output, raw], stdout=f'Assembled {raw} to {output}\n') + invalid_nil = [ + (valid.replace('CAST i32\nINTEROP_CALL', 'INTEROP_CALL'), 'requires one i32 operand'), + (valid.replace('exit 1 void', 'exit 1 void i64'), 'malformed std_sys'), + (valid.replace('exit 1 void', 'exit 2 void'), 'malformed std_sys'), + (valid.replace('exit 1 void', 'exit 1 i32'), 'malformed std_sys'), + ] + for payload, diagnostic in invalid_nil: + raw.write_text(payload) + output.write_bytes(b'previous object') + run([assembler, '-o', output, raw], status=1, diagnostic=diagnostic) + assert output.read_bytes() == b'previous object' + + print(f'{checks} native argument conversion and ABI checks passed') + + +if __name__ == '__main__': + main() diff --git a/tests/tools/native_console_contract.py b/tests/tools/native_console_contract.py new file mode 100644 index 00000000..a6a39425 --- /dev/null +++ b/tests/tools/native_console_contract.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""Console line input preserves bytes and fails explicitly at native ABI limits.""" +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import selectors +import subprocess +import tempfile + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + for name in ('compiler', 'interpreter', 'assembler', 'linker', 'runtime', 'stdlib'): + parser.add_argument('--' + name, type=Path, required=True) + args = parser.parse_args() + tools = {key: str(value.resolve(strict=True)) for key, value in vars(args).items()} + environment = {key: value for key, value in os.environ.items() + if not key.startswith(('NY_', 'NIL_'))} + checks = 0 + fixtures = Path(__file__).resolve().parent / 'fixtures' + with tempfile.TemporaryDirectory(prefix='nil console contract ') as directory: + root = Path(directory) + + def run(command, *, data=b'', status=0, env=None, stdin=None): + nonlocal checks + result = subprocess.run(list(map(str, command)), cwd=root, + env=environment if env is None else env, + input=data if stdin is None else None, stdin=stdin, + capture_output=True, timeout=120) + assert result.returncode == status, (command, result) + checks += 1 + return result + + def build_native(nil, name, unmanaged=False): + obj, executable = root / (name + '.o'), root / name + flags = ['--unmanaged'] if unmanaged else [] + run([tools['assembler'], *flags, '-o', obj, nil]) + run([tools['linker'], '--runtime', tools['runtime'], '-o', executable, obj]) + return [executable] + + def check_prompt(command): + nonlocal checks + if os.name == 'nt': + return + with subprocess.Popen(list(map(str, command)), cwd=root, env=environment, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) as child: + try: + with selectors.DefaultSelector() as selector: + selector.register(child.stdout, selectors.EVENT_READ) + assert selector.select(timeout=10), 'console prompt was not flushed' + assert os.read(child.stdout.fileno(), 7) == b'input> ' + output, error = child.communicate(b'answer\n', timeout=10) + assert child.returncode == 0 and output == b'answer\n' and not error, (output, error) + checks += 1 + finally: + if child.poll() is None: + child.kill() + child.wait(timeout=10) + + cases = [b'\n', b' spaced words \n', 'snowman-☃ café\n'.encode(), + b'carriage\r\n', b'last line', b'x' * 200000 + b'\n'] + native_commands = [] + for language in ('ny', 'matrix'): + source = fixtures / ('console-input.' + language) + nil = root / (language + '.nil') + binary_nil = root / (language + '-binary.nil') + compile_flags = [tools['compiler'], '--quiet', '--no-bundle', '--no-stdlib', + '--sdk-path', tools['stdlib']] + run([*compile_flags, '--debug-info', '-o', nil, source]) + run([*compile_flags, '--debug-info', '--emit-binary-nil', '-o', binary_nil, source]) + for mode in ('safe', 'unsafe'): + vm = [tools['interpreter'], '--no-ai', '--memory-mode=' + mode, nil] + binary_vm = [tools['interpreter'], '--no-ai', '--memory-mode=' + mode, binary_nil] + native = build_native(nil, language + '-' + mode, mode == 'unsafe') + native_commands.append(native) + for command in (vm, binary_vm, native): + for data in cases: + expected = b'input> ' + (data[:-1] if data.endswith(b'\n') else data) + b'\n' + result = run(command, data=data) + assert result.stdout == expected and not result.stderr, result + result = run(command, status=1) + assert result.stdout == b'input> ', result + assert b'console.read_line: input is unavailable or reached EOF' in result.stderr, result + + # JIT must resolve the same runtime symbols as linked objects. + jit = [*compile_flags, '--native', '--jit', + *(['--unmanaged'] if mode == 'unsafe' else []), + '-o', root / (language + '-' + mode + '.jit'), source] + result = run(jit, data='JIT café\n'.encode()) + assert result.stdout == 'input> JIT café\n'.encode() and not result.stderr, result + result = run(jit, status=1) + assert b'console.read_line: input is unavailable or reached EOF' in result.stderr, result + + # The VM can hold embedded NUL. Native text currently cannot; + # its read must fail rather than return the innocent prefix. + binary = b'before\0private-after\n' + for command in (vm, binary_vm): + result = run(command, data=binary) + assert result.stdout == b'input> ' + binary and not result.stderr, result + result = run(native, data=binary, status=1) + assert result.stdout == b'input> ' and b'embedded NUL' in result.stderr, result + assert b'private-after' not in result.stderr, result + + # Verify the explicit flush while the child is still blocked + # on stdin. Reading only after process exit would miss it. + check_prompt(native) + + # The generated wrapper must root the returned input text and + # attribute its one allocation to the actual read_line body. + report = root / (language + '-' + mode + '.json') + result = run(native, data=b'profiled\n', env={**environment, 'NIL_MEMORY_PROFILE': str(report)}) + assert result.stdout == b'input> profiled\n' and not result.stderr, result + profile = json.loads(report.read_text()) + assert profile['completed'] and not profile['errors'], profile + sites = [site for site in profile['sites'] if site['kind'] == 'text'] + assert len(sites) == 1 and sites[0]['allocated_bytes'] == 9, sites + assert 'read_line' in sites[0]['function'], sites + + # A directory descriptor is readable at the OS level but cannot yield + # stream input. Exercise host read errors separately from clean EOF. + if os.name == 'posix': + descriptor = os.open(root, os.O_RDONLY) + try: + for command in native_commands: + result = run(command, status=1, stdin=descriptor) + assert b'input is unavailable or reached EOF' in result.stderr, result + finally: + os.close(descriptor) + + direct = root / 'direct.nil' + direct.write_text('''module console_direct +function main() -> i32: +INTEROP_CALL intrinsic console.flush 0 void +INTEROP_CALL intrinsic console.read_line 0 text +CALL println 1 +INTEROP_CALL intrinsic console.read_line 0 text +CALL println 1 +PUSH_CONST 0 +RET +end function +''') + for mode in ('safe', 'unsafe'): + command = build_native(direct, 'direct-' + mode, mode == 'unsafe') + result = run(command, data=b'one\ntwo') + assert result.stdout == b'one\ntwo\n' and not result.stderr, result + result = run(command, data=b'one\n', status=1) + assert result.stdout == b'one\n' and b'reached EOF' in result.stderr, result + + # read_line also publishes a preceding prompt without an explicit + # flush, independent of the host C++ stream synchronization setting. + prompt = root / 'implicit-flush.nil' + prompt.write_text('''module console_prompt +const prompt = "input> " +@intrinsic("console.write") +function output(value: text) -> void: +end function +function main() -> i32: +PUSH_CONST_STR prompt +CALL output 1 +INTEROP_CALL intrinsic console.read_line 0 text +CALL println 1 +PUSH_CONST 0 +RET +end function +''') + for mode in ('safe', 'unsafe'): + command = build_native(prompt, 'implicit-flush-' + mode, mode == 'unsafe') + check_prompt(command) + + # Check flush itself before a host wait, with no read_line that could + # otherwise publish the buffered prompt on its behalf. + if os.name != 'nt': + explicit = root / 'explicit-flush.nil' + explicit.write_text(prompt.read_text().replace( + 'INTEROP_CALL intrinsic console.read_line 0 text\nCALL println 1', + 'INTEROP_CALL intrinsic console.flush 0 void\nPUSH_CONST 60000\nTIME_SLEEP')) + for mode in ('safe', 'unsafe'): + command = build_native(explicit, 'explicit-flush-' + mode, mode == 'unsafe') + with subprocess.Popen(list(map(str, command)), cwd=root, env=environment, + stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, + stderr=subprocess.PIPE) as child: + try: + with selectors.DefaultSelector() as selector: + selector.register(child.stdout, selectors.EVENT_READ) + assert selector.select(timeout=10), 'console.flush did not publish output before waiting' + assert os.read(child.stdout.fileno(), 7) == b'input> ' + assert child.poll() is None, 'flush check ended before its host wait' + checks += 1 + finally: + if child.poll() is None: + child.terminate() + child.wait(timeout=10) + + invalid = { + 'read-extra-argument': ('', 'PUSH_CONST 1\nINTEROP_CALL intrinsic console.read_line 1 text\nPOP'), + 'read-extra-metadata': ('', 'INTEROP_CALL intrinsic console.read_line 0 text i32\nPOP'), + 'read-wrong-return': ('', 'INTEROP_CALL intrinsic console.read_line 0 ptr\nPOP'), + 'read-missing-return': ('', 'INTEROP_CALL intrinsic console.read_line 0'), + 'flush-wrong-return': ('', 'INTEROP_CALL intrinsic console.flush 0 text\nPOP'), + 'flush-extra-argument': ('', 'PUSH_CONST 1\nINTEROP_CALL intrinsic console.flush 1 void'), + 'wrapper-read-argument': ('@intrinsic("console.read_line")\nfunction wrong(value: i32) -> text:\nend function', 'PUSH_CONST 1\nCALL wrong 1\nPOP'), + 'wrapper-read-return': ('@intrinsic("console.read_line")\nfunction wrong() -> ptr:\nend function', 'CALL wrong 0\nPOP'), + 'wrapper-flush-return': ('@intrinsic("console.flush")\nfunction wrong() -> text:\nend function', 'CALL wrong 0\nPOP'), + 'wrapper-flush-argument': ('@intrinsic("console.flush")\nfunction wrong(value: i32) -> void:\nend function', 'PUSH_CONST 1\nCALL wrong 1'), + } + for name, (declaration, body) in invalid.items(): + nil, output = root / (name + '.nil'), root / (name + '.o') + nil.write_text('module rejected_console\n' + declaration + + '\nfunction main() -> i32:\n' + body + '\nPUSH_CONST 0\nRET\nend function\n') + result = run([tools['assembler'], '-o', output, nil], status=1) + assert b'requires the exact () ->' in result.stderr, result + assert not output.exists(), output + print(f'native console contract: {checks} executions/checks passed') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) From ec1bcd771e169d078e95b16216ca329e7467a286 Mon Sep 17 00:00:00 2001 From: Nathan Date: Fri, 23 Oct 2026 15:17:29 -0400 Subject: [PATCH 2/2] Preserve provider validation during native scalar normalization --- matrix/docs/next-version-findings.md | 17 +++-- nilcompiler/src/codegen.cpp | 25 ++++--- tests/tools/native_argument_contract.py | 89 ++++++++++++++++++++----- 3 files changed, 96 insertions(+), 35 deletions(-) diff --git a/matrix/docs/next-version-findings.md b/matrix/docs/next-version-findings.md index d619371a..1f49cc18 100644 --- a/matrix/docs/next-version-findings.md +++ b/matrix/docs/next-version-findings.md @@ -1749,16 +1749,19 @@ Direct native dispatch bypassed the declared wrapper's scalar parameter boundary. Separately, native lowering did not implement the reachable `console.read_line` and `console.flush` intrinsics. -**Implemented:** Source lowering now applies declared scalar parameter -conversions before direct annotated interop/intrinsic dispatch. Literals, +**Implemented:** Source lowering now normalizes declared scalar parameter +representations before direct annotated interop/intrinsic dispatch. Literals, variables, returned values, reordered Matrix named arguments, and declarations loaded from source or binary libraries use the existing scalar conversion semantics. Integer narrowing wraps as it does at other scalar storage -boundaries; nonfinite or out-of-range floating-to-integer conversion faults. -Text, arrays and pointer handles cannot become implicit numeric arguments. -Raw NIL and forged provider declarations must still satisfy exact native ABI -checks. This is a lowering fix; broad scalar compatibility diagnostics in the -analysis/typechecking API remain a separate task. +boundaries. Floating-to-integer conversion requires an explicit source cast; +its nonfinite and out-of-range checks remain intact. Boolean and non-scalar +operands retain their representation so provider validation can reject them. +In particular, implicit conversion must not make a fractional sleep duration +silently succeed. Raw NIL and forged provider declarations must still satisfy +exact native ABI checks. This is a lowering fix; broad scalar compatibility +diagnostics in the analysis/typechecking API remain a separate task, including +VM values whose handle representation alone cannot prove their source type. Native line input and flushing now have runtime, wrapper, direct NIL, and JIT implementations. Line input strips LF, preserves an empty line or a final diff --git a/nilcompiler/src/codegen.cpp b/nilcompiler/src/codegen.cpp index c0dfe82b..73224204 100644 --- a/nilcompiler/src/codegen.cpp +++ b/nilcompiler/src/codegen.cpp @@ -3802,7 +3802,7 @@ class emitter { } // Direct native dispatch bypasses the declared wrapper's parameter - // boundary. Preserve that boundary explicitly: PUSH_CONST uses a word + // boundary. Preserve scalar representation explicitly: PUSH_CONST uses a word // representation even for an i32 literal, and an accepted scalar // argument can have a different width from the declared parameter. // This is source lowering only; handwritten NIL must still satisfy the @@ -3835,15 +3835,20 @@ class emitter { if (scalar_types.count(expected)) { auto actual = substitute_nil_type_name(*ce.args[index]->inferred_type, substitutions); if (actual == "int") actual = "i32"; - if (!scalar_types.count(actual)) { - cg_.reject_codegen_construct(ce.line, - "Native function '" + native_call_declaration->name + "' argument " + - std::to_string(index + 1) + " requires a scalar for parameter '" + - parameter.name + "' of type '" + expected + "', got '" + actual + "'", - "pass a checked scalar value; handles and text are not numeric arguments"); - return; - } - scalar_type = std::move(expected); + const bool floating_argument = actual == "f64" || actual == "f32"; + const bool floating_parameter = expected == "f64" || expected == "f32"; + const bool boolean_argument = actual == "bool"; + const bool boolean_parameter = expected == "bool"; + // Providers own their value/category checks. Do not turn a + // fractional duration into an integer or parse text/handles as + // numeric values, including under --no-typecheck (which can + // still leave inferred_type metadata). Float-to-integer + // conversion and changes of boolean category therefore require + // an explicit source cast. + if (scalar_types.count(actual) && + (!floating_argument || floating_parameter) && + boolean_argument == boolean_parameter) + scalar_type = std::move(expected); } } } diff --git a/tests/tools/native_argument_contract.py b/tests/tools/native_argument_contract.py index e97ed9a0..7e92590b 100644 --- a/tests/tools/native_argument_contract.py +++ b/tests/tools/native_argument_contract.py @@ -59,7 +59,8 @@ def program(language, body, declarations='', imports=''): 'evaluate exit with code being (returned with nothing)', 'once\n'), ('explicit', 'exit(7 as i32)', 'evaluate exit with code being (7 becomes override integer)', ''), - ('floating', 'exit(7.9)', 'evaluate exit with code being 7.9', ''), + ('floating', 'exit(7.9 as i32)', + 'evaluate exit with code being (7.9 becomes override integer)', ''), # Narrowing follows existing CAST/storage modulo semantics. It is # deliberately tested rather than accidentally relying on LLVM # coercion or OS truncation of the process exit code. @@ -94,8 +95,8 @@ def execute(source, name, search=None, status=7, stdout='', diagnostic=None, # floating values before the process-exit provider can run. source = root / ('outside-range.' + language) source.write_text(program(language, - 'exit(1e30)' if language == 'ny' else - 'evaluate exit with code being 1e30', declarations[language])) + 'exit(1e30 as i32)' if language == 'ny' else + 'evaluate exit with code being (1e30 becomes override integer)', declarations[language])) execute(source, 'outside-range-' + language, status=1, diagnostic='CAST: floating-point value is non-finite or outside i64 range') @@ -151,29 +152,81 @@ def execute(source, name, search=None, status=7, stdout='', diagnostic=None, execute(source, 'library-' + provider_language + '-' + dependency + '-' + language, search, stdout='9\n') - # Applying scalar storage conversions must not turn handles/text into - # implicit numeric parsing or pointer casts. + # Representation normalization must not become implicit numeric + # parsing, float truncation or pointer casts. Preserve provider checks + # on both checked and unchecked source paths. Raw VM pointers and + # booleans are integer words, so only native code can reject their + # exact ABI type. invalid = [ - ('text', 'exit("7")', 'evaluate exit with code being "7"', 'requires a scalar'), + ('text', 'exit("7")', 'evaluate exit with code being "7"'), ('pointer', 'let p = allocate(1)\nexit(p)', - 'allocate p as pointer to override integer sized 1\nevaluate exit with code being p', 'requires a scalar'), - ('array', 'exit([7])', 'evaluate exit with code being [7]', 'requires a scalar'), + 'allocate p as pointer to override integer sized 1\nevaluate exit with code being p'), + ('array', 'exit([7])', 'evaluate exit with code being [7]'), ('function', 'exit(returned)', - 'evaluate exit with code being the paragraph returned', 'requires a scalar'), - ('missing', 'exit()', 'evaluate exit with nothing', 'expects 1 arguments'), + 'evaluate exit with code being the paragraph returned'), + ('boolean', 'let code: bool = true\nexit(code)', + 'value code as boolean is true\nevaluate exit with code being code'), + ('fraction', 'exit(7.9)', 'evaluate exit with code being 7.9'), + ('huge_float', 'exit(1e30)', 'evaluate exit with code being 1e30'), ] for language in ('ny', 'matrix'): - for name, ny, matrix, diagnostic in invalid: + for name, ny, matrix in invalid: source = root / ('invalid-' + name + '.' + language) source.write_text(program(language, ny if language == 'ny' else matrix, declarations[language])) - for flags in (['--no-bundle'], ['--no-bundle', '--emit-binary-nil'], - *([['--native'], ['--native', '--jit']] if args.llvm == 'ON' else [])): - output = root / 'protected-output' - output.write_bytes(b'previous artifact') - run([compiler, '--quiet', '--no-stdlib', *flags, '-o', output, source], - status=1, diagnostic=diagnostic) - assert output.read_bytes() == b'previous artifact' + for unchecked in ([], ['--no-typecheck']): + for encoding in ([], ['--emit-binary-nil']): + output = root / 'invalid.nil' + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', *unchecked, + *encoding, '-o', output, source]) + if name not in ('pointer', 'boolean'): + run([interpreter, '--no-ai', output], status=1, + diagnostic='std_sys.exit: expected one integer code') + if args.llvm == 'ON': + for flags in (['--native'], ['--native', '--jit']): + output = root / 'protected-output' + output.write_bytes(b'previous artifact') + run([compiler, '--quiet', '--no-stdlib', *unchecked, *flags, + '-o', output, source], status=1, + diagnostic='NativeCodegen') + assert output.read_bytes() == b'previous artifact' + + source = root / ('missing.' + language) + source.write_text(program(language, 'exit()' if language == 'ny' else + 'evaluate exit with nothing', declarations[language])) + for flags in (['--no-bundle'], ['--no-bundle', '--emit-binary-nil'], + *([['--native'], ['--native', '--jit']] if args.llvm == 'ON' else [])): + output = root / 'protected-output' + output.write_bytes(b'previous artifact') + run([compiler, '--quiet', '--no-stdlib', *flags, '-o', output, source], + status=1, diagnostic='expects 1 arguments') + assert output.read_bytes() == b'previous artifact' + + # Sleep deliberately validates integer durations itself. An + # implicit CAST here would silently turn 0.5 into a zero wait. + for name, value in (('fraction', '0.5'), ('text', '"invalid"'), + ('huge', '9223372036854775808.0')): + source = root / ('duration-' + name + '.' + language) + declaration = ('@intrinsic("time.sleep")\nfn sleep_ms(value: i64)\nend fn\n' + if language == 'ny' else + 'note intrinsic "time.sleep"\nsleep-ms receives item as number\n') + body = 'sleep_ms(' + value + ')' if language == 'ny' else \ + 'evaluate sleep-ms with item being ' + value + source.write_text(program(language, body, declaration)) + for unchecked in ([], ['--no-typecheck']): + for encoding in ([], ['--emit-binary-nil']): + output = root / 'invalid-duration.nil' + run([compiler, '--quiet', '--no-stdlib', '--no-bundle', *unchecked, + *encoding, '-o', output, source]) + run([interpreter, '--no-ai', output], status=1, + diagnostic='TIME_SLEEP: expected an integer duration') + if args.llvm == 'ON': + output = root / 'protected-duration' + output.write_bytes(b'previous artifact') + run([compiler, '--quiet', '--no-stdlib', '--native', *unchecked, + '-o', output, source], status=1, + diagnostic='TIME_SLEEP requires one integer duration') + assert output.read_bytes() == b'previous artifact' if args.llvm == 'ON': # Source casts qualify operands without relaxing provider ABIs.