Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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 $<TARGET_FILE:nilcompiler>
--interpreter $<TARGET_FILE:nilinterpreter>
--assembler $<TARGET_FILE:nilassembler>
--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 $<TARGET_FILE:nilcompiler>
--interpreter $<TARGET_FILE:nilinterpreter>
--assembler $<TARGET_FILE:nilassembler>
--linker $<TARGET_FILE:nillinker>
--runtime $<TARGET_FILE:nilruntime>
--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)
Expand Down Expand Up @@ -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
)
Expand All @@ -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"
Expand Down
9 changes: 9 additions & 0 deletions docs/standard-library/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
102 changes: 70 additions & 32 deletions matrix/docs/next-version-findings.md
Original file line number Diff line number Diff line change
Expand Up @@ -1740,37 +1740,75 @@ 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 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. 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
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.
61 changes: 58 additions & 3 deletions nilcompiler/src/codegen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3801,6 +3801,61 @@ class emitter {
}
}

// Direct native dispatch bypasses the declared wrapper's parameter
// 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
// 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<const ast_identifier_expr &>(*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<std::string> scalar_type;
if (native_call_declaration && index < native_call_declaration->params.size() &&
ce.args[index]->inferred_type) {
const auto &parameter = 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<std::string> 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";
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);
}
}
}
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
Expand All @@ -3813,7 +3868,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]);
Expand All @@ -3832,8 +3887,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 = "<call>";
if (ce.callee && ce.callee->kind == ast_node_kind::identifier_expr_node) {
Expand Down
42 changes: 42 additions & 0 deletions nilcompiler/src/llvm_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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::Type *>(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])) !=
Expand Down Expand Up @@ -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::Type *>(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 {
Expand Down Expand Up @@ -8489,6 +8529,8 @@ int NativeCodegen::executeJIT(const std::vector<std::string> &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);
Expand Down
Loading
Loading