From c07d3a44e32d92c8389e0e3a0d13b7d05a6ae04b Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 16 Nov 2026 03:19:18 +0800 Subject: [PATCH 1/2] feat(core): add checked number conversion and numeric array join --- build.rs | 2 + docs/callable-runtime.md | 2 +- pd-vm-nostd/src/generated_builtin_ids.rs | 2 + pd-vm-nostd/src/vm.rs | 130 +++++++++- src/builtins/catalog.rs | 1 + src/builtins/runtime/core.rs | 226 ++++++++++++++++- src/builtins/runtime/mod.rs | 38 +++ src/compiler/typing/context.rs | 308 +++++++++++++++++++++++ tests/aot_tagged_number_tests.rs | 152 +++++++++++ tests/wire/catalog_contract_tests.rs | 39 ++- 10 files changed, 891 insertions(+), 9 deletions(-) diff --git a/build.rs b/build.rs index b59e3c02..93656adb 100644 --- a/build.rs +++ b/build.rs @@ -1876,6 +1876,7 @@ fn appended_builtin_order() -> &'static [&'static str] { "__map_iter_close", "__bind_callable", "__detach_local", + "__checked_int_from_number", "__json_decode_typed", "__json_encode_typed", "__logical_render", @@ -1911,6 +1912,7 @@ fn required_internal_builtin_stubs() -> &'static [&'static str] { "__to_string", "__bind_callable", "__detach_local", + "__checked_int_from_number", ] } diff --git a/docs/callable-runtime.md b/docs/callable-runtime.md index 5ed74d10..187e5a8e 100644 --- a/docs/callable-runtime.md +++ b/docs/callable-runtime.md @@ -24,7 +24,7 @@ VMBC v14 is the current format. Other versions and malformed resource schemas ar Every VM-visible builtin (ordinary, internal, and special-call) has one explicit, immutable `u16` call index assigned in `src/builtins/catalog.rs`. `build.rs` parses that catalog and generates the `BuiltinFunction` enum discriminants, `call_index`/`from_call_index`, the `builtin_call_index` reverse lookup, and the `BUILTIN_CATALOG` iteration from the explicit IDs; no ID is derived from catalog length or source order. -- **Immutable explicit IDs.** IDs never change once assigned. Adding or reordering catalog entries never renumbers existing entries; new builtins take the next free ID in their documented block (extension `0x0000..=0xFF8F` for future builtins and host imports, special-call `0xFF90..=0xFFA1`, ordinary `0xFFA2..=0xFFFF`). The reserved sentinel gap `0xFF90..=0xFF92` stays unassigned. +- **Immutable explicit IDs.** IDs never change once assigned. Adding or reordering catalog entries never renumbers existing entries; new builtins take the next free ID in their documented block (extension `0x0000..=0xFF8B` for future builtins and host imports, special-call `0xFF8C..=0xFFA1`, ordinary `0xFFA2..=0xFFFF`). The reserved sentinel gap `0xFF91..=0xFF92` stays unassigned. `0xFF90` is the internal `__checked_int_from_number` builtin (`number` → `int`): tagged integers retain their exact value, while only finite, exactly integral floats within `[-2^63, 2^63)` convert. Other numbers fail with the assertion-failed host error; non-numbers fail the number type check. Std and no-std dispatch on the same ID. - **Build-time validation.** The build fails on duplicate IDs, duplicate source names, duplicate Rust variants, out-of-block IDs, class/gate inconsistencies, a discovered runtime callable without an explicit ID, or a catalog entry without a runtime callable. - **Shared std/no-std IDs.** `pd-vm-nostd` dispatches on the same static indices through the checked-in generated mirror `pd-vm-nostd/src/generated_builtin_ids.rs`; the workspace test `static_builtin_ids_are_frozen` fails when the mirror drifts from the catalog. - **Current format identity.** VMBC and the internal bytecode ABI use version 14, with catalog fingerprint format v3. diff --git a/pd-vm-nostd/src/generated_builtin_ids.rs b/pd-vm-nostd/src/generated_builtin_ids.rs index ef66d0b4..df44f602 100644 --- a/pd-vm-nostd/src/generated_builtin_ids.rs +++ b/pd-vm-nostd/src/generated_builtin_ids.rs @@ -11,6 +11,7 @@ #![allow(dead_code)] +pub const CHECKED_INT_FROM_NUMBER_CALL_INDEX: u16 = 0xFF90; pub const DETACH_LOCAL_CALL_INDEX: u16 = 0xFF93; pub const JSON_DECODE_TYPED_CALL_INDEX: u16 = 0xFF8C; pub const JSON_ENCODE_TYPED_CALL_INDEX: u16 = 0xFF8D; @@ -131,6 +132,7 @@ pub const ALL_CALL_INDICES: &[u16] = &[ JSON_ENCODE_TYPED_CALL_INDEX, LOGICAL_RENDER_CALL_INDEX, MAP_EDIT_CALL_INDEX, + CHECKED_INT_FROM_NUMBER_CALL_INDEX, DETACH_LOCAL_CALL_INDEX, BIND_CALLABLE_CALL_INDEX, MAP_ITER_CLOSE_CALL_INDEX, diff --git a/pd-vm-nostd/src/vm.rs b/pd-vm-nostd/src/vm.rs index 6e68e9f4..de2efc8d 100644 --- a/pd-vm-nostd/src/vm.rs +++ b/pd-vm-nostd/src/vm.rs @@ -811,9 +811,10 @@ impl Vm { fn call_core_builtin(&mut self, index: u16, arity: u8) -> Option> { use super::generated_builtin_ids::{ ARRAY_NEW_CALL_INDEX, ARRAY_PUSH_CALL_INDEX, BIND_CALLABLE_CALL_INDEX, - CONCAT_CALL_INDEX, DETACH_LOCAL_CALL_INDEX, GET_CALL_INDEX, HAS_CALL_INDEX, - JSON_DECODE_TYPED_CALL_INDEX, JSON_ENCODE_TYPED_CALL_INDEX, LOGICAL_RENDER_CALL_INDEX, - MAP_EDIT_CALL_INDEX, MAP_NEW_CALL_INDEX, SET_CALL_INDEX, + CHECKED_INT_FROM_NUMBER_CALL_INDEX, CONCAT_CALL_INDEX, DETACH_LOCAL_CALL_INDEX, + GET_CALL_INDEX, HAS_CALL_INDEX, JSON_DECODE_TYPED_CALL_INDEX, + JSON_ENCODE_TYPED_CALL_INDEX, LOGICAL_RENDER_CALL_INDEX, MAP_EDIT_CALL_INDEX, + MAP_NEW_CALL_INDEX, SET_CALL_INDEX, }; Some(match index { @@ -1041,6 +1042,28 @@ impl Vm { | LOGICAL_RENDER_CALL_INDEX => { return Some(Err(VmError::InvalidCall(index))); } + CHECKED_INT_FROM_NUMBER_CALL_INDEX => { + if let Err(error) = + self.require_builtin_arity("__checked_int_from_number", arity, 1) + { + return Some(Err(error)); + } + let start = match self.stack.len().checked_sub(1) { + Some(start) => start, + None => return Some(Err(VmError::StackUnderflow)), + }; + let value = match self.stack.get(start) { + Some(Value::Int(value)) => *value, + Some(Value::Float(value)) => match checked_float_to_int(*value) { + Some(value) => value, + None => return Some(Err(VmError::HostError("assertion failed"))), + }, + _ => return Some(Err(VmError::TypeMismatch("number"))), + }; + self.stack.truncate(start); + self.stack.push(Value::Int(value)); + Ok(()) + } _ => return None, }) } @@ -1246,6 +1269,19 @@ fn as_float(value: NumericValue) -> f64 { } } +/// Convert a finite, exactly representable float into a signed integer. +/// +/// Mirrors the std conversion domain: `i64::MAX as f64` rounds up to 2^63, so +/// the accepted upper bound is strict, and any fractional or subnormal value +/// fails the exactness check after truncation. +fn checked_float_to_int(value: f64) -> Option { + if !value.is_finite() || value < i64::MIN as f64 || value >= i64::MAX as f64 { + return None; + } + let converted = value as i64; + (converted as f64 == value).then_some(converted) +} + fn checked_int_div(lhs: i64, rhs: i64) -> VmResult { if rhs == 0 { return Err(VmError::DivisionByZero); @@ -1353,4 +1389,92 @@ mod tests { "no-std MapEdit must keep a null entry when remove is false" ); } + fn checked_int_program(value: Value) -> Program { + let mut code = vec![OpCode::Ldc as u8]; + code.extend_from_slice(&0u32.to_le_bytes()); + code.push(OpCode::Call as u8); + code.extend_from_slice( + &crate::generated_builtin_ids::CHECKED_INT_FROM_NUMBER_CALL_INDEX.to_le_bytes(), + ); + code.push(1); + code.push(OpCode::Ret as u8); + Program::new(vec![value], code, Vec::new()) + } + + #[test] + fn checked_int_from_number_core_dispatch_preserves_tagged_int_and_exact_floats() { + let upper = i64::MAX as f64; + let below_upper = f64::from_bits(upper.to_bits() - 1); + let cases = [ + (Value::Int((1_i64 << 53) + 1), Value::Int((1_i64 << 53) + 1)), + (Value::Int(i64::MAX), Value::Int(i64::MAX)), + (Value::Int(i64::MIN), Value::Int(i64::MIN)), + (Value::Float(-0.0), Value::Int(0)), + (Value::Float(i64::MIN as f64), Value::Int(i64::MIN)), + (Value::Float(below_upper), Value::Int(below_upper as i64)), + ]; + for (input, expected) in cases { + let mut vm = Vm::new(checked_int_program(input)); + vm.set_fuel(10_000_000); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), core::slice::from_ref(&expected)); + assert!( + vm.fuel().is_some_and(|remaining| remaining <= 10_000_000), + "the guest entry must draw on the fresh fuel budget" + ); + } + } + + #[test] + fn checked_int_from_number_core_dispatch_reports_std_error_parity() { + let upper = i64::MAX as f64; + for input in [ + Value::Float(f64::NAN), + Value::Float(upper), + Value::Float(0.5), + ] { + let mut vm = Vm::new(checked_int_program(input)); + vm.set_fuel(10_000_000); + let error = vm + .run() + .expect_err("non-finite or out-of-range float must fail"); + assert_eq!(error, VmError::HostError("assertion failed")); + assert!( + vm.fuel().is_some_and(|remaining| remaining <= 10_000_000), + "the failing guest entry must report remaining fuel" + ); + } + let mut vm = Vm::new(checked_int_program(Value::Bool(true))); + vm.set_fuel(10_000_000); + let error = vm.run().expect_err("non-number must fail"); + assert_eq!(error, VmError::TypeMismatch("number")); + assert!( + vm.fuel().is_some_and(|remaining| remaining <= 10_000_000), + "the type-rejecting guest entry must report remaining fuel" + ); + } + + #[test] + fn checked_int_from_number_core_dispatch_rejects_invalid_arity() { + for (arity, constants) in [(0u8, Vec::new()), (2u8, vec![Value::Int(1), Value::Int(2)])] { + let mut code = Vec::new(); + for index in 0..u32::from(arity) { + code.push(OpCode::Ldc as u8); + code.extend_from_slice(&index.to_le_bytes()); + } + code.push(OpCode::Call as u8); + code.extend_from_slice( + &crate::generated_builtin_ids::CHECKED_INT_FROM_NUMBER_CALL_INDEX.to_le_bytes(), + ); + code.push(arity); + code.push(OpCode::Ret as u8); + let mut vm = Vm::new(Program::new(constants, code, Vec::new())); + vm.set_fuel(10_000_000); + assert!(matches!( + vm.run(), + Err(VmError::InvalidCallArity { import, expected: 1, got }) + if import == "__checked_int_from_number" && got == arity + )); + } + } } diff --git a/src/builtins/catalog.rs b/src/builtins/catalog.rs index 6e4fa4ce..3ea7286e 100644 --- a/src/builtins/catalog.rs +++ b/src/builtins/catalog.rs @@ -145,6 +145,7 @@ builtin_id!(0xFF96, "__map_iter_take_value", MapIterTakeValue, Internal, none); builtin_id!(0xFF95, "__map_iter_close", MapIterClose, Internal, none); builtin_id!(0xFF94, "__bind_callable", BindCallable, Internal, none); builtin_id!(0xFF93, "__detach_local", DetachLocal, Internal, none); +builtin_id!(0xFF90, "__checked_int_from_number", CheckedIntFromNumber, Internal, none); builtin_id!(0xFF8C, "__json_decode_typed", JsonDecodeTyped, Internal, none); builtin_id!(0xFF8D, "__json_encode_typed", JsonEncodeTyped, Internal, none); builtin_id!(0xFF8E, "__logical_render", LogicalRender, Internal, none); diff --git a/src/builtins/runtime/core.rs b/src/builtins/runtime/core.rs index 314eb975..3f66d3a6 100644 --- a/src/builtins/runtime/core.rs +++ b/src/builtins/runtime/core.rs @@ -2,7 +2,7 @@ use super::typed::{ VmArrayHandle, VmArrayRef, VmBytesHandle, VmBytesRef, VmMapHandle, VmMapRef, VmStringRef, VmValueOwned, VmValueRef, take_arg, }; -use super::{AnyValue, UnknownValue, VmArray, VmBytes, VmMap, arg, return_one}; +use super::{AnyValue, NumberValue, UnknownValue, VmArray, VmBytes, VmMap, arg, return_one}; use crate::bytecode::{SharedArray, SharedMap}; use crate::vm::{CallReturn, Value, VmError, VmResult}; use pd_host_function::pd_host_function; @@ -21,6 +21,48 @@ fn builtin_bind_callable_metadata(_prototype_id: i64, captures: VmArrayRef<'_>) #[pd_host_function(name = "__detach_local")] fn builtin_detach_local_metadata(_slot: i64) {} +/// Convert a generic number into a checked signed integer. +/// +/// Metadata-only: no other runtime builtin dispatches through this adapter. +#[allow(dead_code)] +#[pd_host_function(name = "__checked_int_from_number")] +fn builtin_checked_int_from_number_metadata(number: NumberValue) -> VmResult { + checked_number_to_int(number) +} + +/// Convert a VM number into a signed integer without an `f64` round trip. +/// +/// A tagged `Int` is already the exact value, so it is returned unchanged. +/// A `Float` is accepted only when it is finite, inside the half-open +/// `[-2^63, 2^63)` range, and exactly representable as an `i64`. Any other +/// float fails with the same host-error payload as a failed `assert`. +fn checked_number_to_int(number: NumberValue) -> VmResult { + match number { + NumberValue::Int(value) => Ok(value), + NumberValue::Float(value) => { + // `i64::MAX as f64` rounds up to exactly 2^63, one past the largest + // representable integer, so the accepted upper bound is strict. + if !value.is_finite() || value < i64::MIN as f64 || value >= i64::MAX as f64 { + return Err(checked_int_assertion_failure()); + } + let converted = value as i64; + if converted as f64 != value { + return Err(checked_int_assertion_failure()); + } + Ok(converted) + } + } +} + +fn checked_int_assertion_failure() -> VmError { + VmError::HostError("assertion failed".to_string()) +} + +pub(super) fn builtin_checked_int_from_number(args: &[Value]) -> VmResult { + let number = arg::(args, 0, "number")?; + checked_number_to_int(number).map(return_one) +} + /// Return the length of a string, array, or map. #[pd_host_function(name = "len")] pub(super) fn builtin_len_string_impl(text: VmStringRef<'_>) -> i64 { @@ -980,6 +1022,7 @@ pub(super) fn core_host_module() -> super::host_modules::StandardHostModule { const OWNED: &[fn() -> crate::host_extension::HostFunctionDescriptor] = &[ builtin_bind_callable_metadata_descriptor, builtin_detach_local_metadata_descriptor, + builtin_checked_int_from_number_metadata_descriptor, builtin_len_string_descriptor, builtin_len_array_descriptor, builtin_len_bytes_descriptor, @@ -1031,11 +1074,14 @@ pub(super) fn core_host_module() -> super::host_modules::StandardHostModule { mod tests { use super::*; use crate::builtins::BuiltinFunction; + use crate::vm::Vm; + use crate::{BytecodeBuilder, OpCode, Program}; use std::sync::Arc; #[test] fn internal_builtins_have_unique_reserved_call_indices() { let reserved = [ + (BuiltinFunction::CheckedIntFromNumber, 0xFF90), (BuiltinFunction::MapIterInit, 0xFF99), (BuiltinFunction::MapIterNext, 0xFF98), (BuiltinFunction::MapIterTakeKey, 0xFF97), @@ -1049,7 +1095,11 @@ mod tests { assert_eq!(builtin.call_index(), index); assert_eq!(BuiltinFunction::from_call_index(index), Some(builtin)); } - for name in ["__bind_callable", "__detach_local"] { + for name in [ + "__bind_callable", + "__detach_local", + "__checked_int_from_number", + ] { assert!( !crate::builtins::language_builtin_specs() .iter() @@ -1057,7 +1107,7 @@ mod tests { "internal callable metadata operation must not be language-visible: {name}" ); } - for reserved_index in 0xFF90..=0xFF92 { + for reserved_index in 0xFF91..=0xFF92 { assert_eq!(BuiltinFunction::from_call_index(reserved_index), None); } } @@ -1236,4 +1286,174 @@ mod tests { }; assert_eq!(*map_count, 2); } + + fn assert_assertion_failure(error: &VmError) { + assert!( + matches!(error, VmError::HostError(message) if message == "assertion failed"), + "{error:?}" + ); + } + + #[test] + fn checked_int_from_number_preserves_all_tagged_int_inputs() { + for expected in [ + i64::MIN, + i64::MAX, + 9_007_199_254_740_993, // 2^53 + 1, not exactly representable as f64 + 0, + 65_536, + ] { + assert_eq!( + checked_number_to_int(NumberValue::Int(expected)).expect("tagged Int must pass"), + expected, + "tagged Int {expected} must be preserved without an f64 round trip" + ); + } + } + + #[test] + fn checked_int_from_number_accepts_exact_finite_floats() { + let lower = i64::MIN as f64; + let upper = i64::MAX as f64; + let largest_below_upper = f64::from_bits(upper.to_bits() - 1); + for (input, expected) in [(0.0, 0), (-0.0, 0), (-1.0, -1), (lower, i64::MIN)] { + assert_eq!( + checked_number_to_int(NumberValue::Float(input)) + .expect("exact finite float must pass"), + expected, + "float {input} must convert exactly" + ); + } + assert_eq!( + checked_number_to_int(NumberValue::Float(largest_below_upper)) + .expect("largest f64 below 2^63 must pass"), + largest_below_upper as i64 + ); + } + + #[test] + fn checked_int_from_number_rejects_non_finite_and_out_of_range_floats() { + let upper = i64::MAX as f64; // rounds up to 2^63, one past i64::MAX + let lower = i64::MIN as f64; // -2^63, exactly representable + let below_lower = f64::from_bits(lower.to_bits() + 1); + for input in [ + f64::NAN, + f64::INFINITY, + f64::NEG_INFINITY, + upper, + below_lower, + ] { + let Err(error) = checked_number_to_int(NumberValue::Float(input)) else { + panic!("float {input} must not convert"); + }; + assert_assertion_failure(&error); + } + } + + #[test] + fn checked_int_from_number_rejects_inexact_floats_like_a_failed_assert() { + for input in [0.5, -0.5, 65_535.5, f64::from_bits(1)] { + let Err(error) = checked_number_to_int(NumberValue::Float(input)) else { + panic!("inexact float {input} must not convert"); + }; + assert_assertion_failure(&error); + } + + let mut vm = Vm::new(Program::new(Vec::new(), vec![OpCode::Ret as u8])); + let Err(conversion) = crate::builtins::runtime::execute_builtin_call( + &mut vm, + BuiltinFunction::CheckedIntFromNumber, + &mut [Value::Float(f64::NAN)], + ) else { + panic!("non-finite float must fail through the builtin dispatch"); + }; + let Err(assertion) = crate::builtins::runtime::execute_builtin_call( + &mut vm, + BuiltinFunction::Assert, + &mut [Value::Bool(false)], + ) else { + panic!("a false assert must fail"); + }; + assert_eq!( + format!("{conversion:?}"), + format!("{assertion:?}"), + "the conversion failure must reuse the builtin assert error payload" + ); + } + + #[test] + fn checked_int_from_number_rejects_non_number_values() { + for value in [Value::Bool(true), Value::Null, Value::string("1")] { + let Err(error) = builtin_checked_int_from_number(&[value]) else { + panic!("non-number input must not convert"); + }; + assert!( + matches!(error, VmError::TypeMismatch("number")), + "non-number input must keep the number type mismatch: {error:?}" + ); + } + } + + #[test] + fn checked_int_from_number_id_name_signature_and_arity_are_explicit() { + let builtin = BuiltinFunction::from_call_index(0xFF90) + .expect("checked number-to-int builtin must exist at call index 0xFF90"); + assert_eq!(builtin, BuiltinFunction::CheckedIntFromNumber); + assert_eq!(builtin.call_index(), 0xFF90); + assert_eq!(builtin.name(), "__checked_int_from_number"); + assert_eq!(builtin.arity(), 1); + + let signatures = builtin.callable_signatures(); + assert_eq!(signatures.len(), 1, "one callable schema is published"); + let signature = signatures[0]; + assert_eq!(signature.params.len(), 1); + assert_eq!( + signature.params[0].ty, + crate::builtins::CallableParamType::Number + ); + assert_eq!(signature.return_type, "int"); + + for (argc, constants) in [(0u8, Vec::new()), (2u8, vec![Value::Int(1), Value::Int(1)])] { + let mut code = BytecodeBuilder::new(); + for index in 0..argc { + code.ldc(u32::from(index)); + } + code.call(0xFF90, argc); + code.ret(); + let mut vm = Vm::new(Program::new(constants, code.finish())); + vm.set_jit_config(crate::JitConfig { + enabled: false, + hot_loop_threshold: 1, + max_trace_len: 512, + }); + vm.set_fuel(10_000_000); + let Err(error) = vm.run() else { + panic!("arity {argc} must be rejected"); + }; + match error { + VmError::InvalidCallArity { + import, + expected, + got, + } => { + assert_eq!(import, "__checked_int_from_number"); + assert_eq!((expected, got), (1, argc)); + } + other => panic!("unexpected arity error: {other:?}"), + } + assert_eq!( + vm.aot_exec_count(), + 0, + "the arity rejection must not enter the AOT backend" + ); + assert_eq!( + vm.jit_native_exec_count(), + 0, + "the arity rejection must not enter native JIT" + ); + vm.reset_for_reuse() + .expect("the rejected arity VM must reset for reuse"); + assert_eq!(vm.host_context().resource_count(), 0); + } + } } diff --git a/src/builtins/runtime/mod.rs b/src/builtins/runtime/mod.rs index 9f6046ce..391a971d 100644 --- a/src/builtins/runtime/mod.rs +++ b/src/builtins/runtime/mod.rs @@ -207,6 +207,9 @@ pub(crate) fn execute_builtin_call( .map(IntoBuiltinCallOutcome::into_builtin_call_outcome), BuiltinFunction::FormatTemplate => core::builtin_format_template(args) .map(IntoBuiltinCallOutcome::into_builtin_call_outcome), + BuiltinFunction::CheckedIntFromNumber => { + core::builtin_checked_int_from_number(args).map(BuiltinCallOutcome::Return) + } BuiltinFunction::ToString => { core::builtin_to_string(args).map(IntoBuiltinCallOutcome::into_builtin_call_outcome) } @@ -253,4 +256,39 @@ mod tests { } } } + + #[test] + fn checked_int_from_number_preserves_large_int_input() { + let builtin = BuiltinFunction::from_call_index(0xFF90) + .expect("checked number-to-int builtin must exist at call index 0xFF90"); + let mut vm = Vm::new(Program::new(Vec::new(), vec![OpCode::Ret as u8])); + // 2^53 + 1 is not exactly representable as an f64, so any f64 round trip + // would round it to 2^53 and lose the low bit. + let expected = Value::Int((1_i64 << 53) + 1); + let mut args = [expected.clone()]; + + let outcome = execute_builtin_call(&mut vm, builtin, &mut args) + .expect("checked number-to-int should accept a tagged Int"); + + match outcome { + BuiltinCallOutcome::Return(values) => { + let returned = values.as_slice(); + assert_eq!( + returned.len(), + 1, + "checked number-to-int must return exactly one value" + ); + assert_eq!( + returned[0], expected, + "checked number-to-int must preserve the tagged Int without an f64 round trip" + ); + } + BuiltinCallOutcome::Halt => { + panic!("checked number-to-int should not halt builtin execution"); + } + BuiltinCallOutcome::Pending(op_id) => { + panic!("checked number-to-int should not yield pending host op {op_id}"); + } + } + } } diff --git a/src/compiler/typing/context.rs b/src/compiler/typing/context.rs index 22804c36..acbbbf61 100644 --- a/src/compiler/typing/context.rs +++ b/src/compiler/typing/context.rs @@ -157,6 +157,26 @@ struct CallableBody<'a> { body_expr: &'a Expr, } +/// Only fully known numeric array shapes may share a widened conditional schema. +fn is_known_numeric_array_schema(schema: &TypeSchema) -> bool { + match schema { + TypeSchema::Array(inner) => matches!( + inner.as_ref(), + TypeSchema::Int | TypeSchema::Float | TypeSchema::Number + ), + TypeSchema::ArrayTuple(items) => { + !items.is_empty() + && items.iter().all(|item| { + matches!( + item, + TypeSchema::Int | TypeSchema::Float | TypeSchema::Number + ) + }) + } + _ => false, + } +} + impl<'a> TypeContext<'a> { #[allow(clippy::too_many_arguments)] pub(super) fn new( @@ -1466,6 +1486,12 @@ impl<'a> TypeContext<'a> { (Some(TypeSchema::Null), rhs) => rhs, (lhs, Some(TypeSchema::Null)) => lhs, (Some(lhs), Some(rhs)) if lhs == rhs => Some(lhs), + (Some(lhs), Some(rhs)) + if is_known_numeric_array_schema(&lhs) + && is_known_numeric_array_schema(&rhs) => + { + Some(TypeSchema::Array(Box::new(TypeSchema::Number))) + } _ => None, } } @@ -4178,3 +4204,285 @@ mod tests { .expect("a catalog-resolved call must bypass the incompatible legacy signature"); } } +#[cfg(test)] +mod numeric_array_conditional_join_tests { + use super::*; + + /// Rule: an `if` whose two branches are both known numeric arrays + /// (`[int]`, `[float]` or `[number]` elements, or a non-empty tuple whose + /// elements are all numeric) shares the result schema `[number]`. Equality + /// is decided first, so identical schemas keep their precise shape, and + /// bool/unknown/missing/heterogeneous branches stay at `None`. + #[test] + fn known_numeric_arrays_share_conditional_result_schema() { + let empty_impls: HashMap = HashMap::new(); + let empty_decls: HashMap = HashMap::new(); + let empty_structs: HashMap = HashMap::new(); + let empty_names: HashMap = HashMap::new(); + let empty_returns: HashMap = HashMap::new(); + let empty_signatures: HashMap = HashMap::new(); + let mut context = TypeContext::new( + &empty_impls, + &empty_decls, + &empty_structs, + &empty_names, + &empty_returns, + &empty_signatures, + TypingMode::Strict, + None, + ); + + // Leaf facts are authored into the real state; both branches are + // `Expr::Var(slot)`, so `infer_expr_schema` reads the canonical + // `LocalTypeState` bindings instead of a hand-written inference stub. + let mut state = LocalTypeState::default(); + state.set_with_schema_origin( + 1, + BoundType::Array, + Some(TypeSchema::ArrayTuple(vec![TypeSchema::Number])), + false, + ); + state.set_with_schema_origin( + 2, + BoundType::Array, + Some(TypeSchema::ArrayTuple(vec![TypeSchema::Int])), + false, + ); + state.set_with_schema_origin( + 3, + BoundType::Array, + Some(TypeSchema::Array(Box::new(TypeSchema::Number))), + false, + ); + state.set_with_schema_origin( + 4, + BoundType::Array, + Some(TypeSchema::Array(Box::new(TypeSchema::Int))), + false, + ); + state.set_with_schema_origin( + 5, + BoundType::Array, + Some(TypeSchema::Array(Box::new(TypeSchema::Float))), + false, + ); + state.set_with_schema_origin( + 6, + BoundType::Array, + Some(TypeSchema::Array(Box::new(TypeSchema::Bool))), + false, + ); + state.set_with_schema_origin( + 7, + BoundType::Array, + Some(TypeSchema::Array(Box::new(TypeSchema::Unknown))), + false, + ); + state.set_with_schema_origin( + 8, + BoundType::Array, + Some(TypeSchema::ArrayTuple(vec![ + TypeSchema::Int, + TypeSchema::Bool, + ])), + false, + ); + // Slot 9 stays unbound: one branch of the last negative case has no + // known schema at all and must not be widened from the other side. + + // Fixture precondition: the case-1 leaves really are the authored + // tuple shapes, so the join assertions below exercise the conditional + // rule rather than test setup. + assert_eq!( + state.schema(1), + Some(&TypeSchema::ArrayTuple(vec![TypeSchema::Number])), + "fixture: slot 1 must carry the authored [number] tuple" + ); + assert_eq!( + state.schema(2), + Some(&TypeSchema::ArrayTuple(vec![TypeSchema::Int])), + "fixture: slot 2 must carry the authored [int] tuple" + ); + + let conditional = |then_slot: LocalSlot, else_slot: LocalSlot| Expr::IfElse { + condition: Box::new(Expr::Bool(true)), + then_expr: Box::new(Expr::Var(then_slot)), + else_expr: Box::new(Expr::Var(else_slot)), + }; + + let number_array = TypeSchema::Array(Box::new(TypeSchema::Number)); + // Exactly eight cases, one real `infer_expr_schema` pipeline each: no + // extra recursive probes outside a case. + let cases: [(&str, LocalSlot, LocalSlot, Option); 8] = [ + ( + "number tuple vs int tuple", + 1, + 2, + Some(number_array.clone()), + ), + ( + "number tuple vs array number", + 1, + 3, + Some(number_array.clone()), + ), + ("array int vs array float", 4, 5, Some(number_array.clone())), + ( + "equal int tuple", + 2, + 2, + Some(TypeSchema::ArrayTuple(vec![TypeSchema::Int])), + ), + ("array bool vs array int", 6, 4, None), + ("array unknown vs array int", 7, 4, None), + ("missing branch vs int tuple", 9, 2, None), + ("heterogeneous tuple vs int tuple", 8, 2, None), + ]; + + let mut joined_by_case: Vec<(&str, Option)> = Vec::with_capacity(cases.len()); + for (name, then_slot, else_slot, _) in &cases { + let expr = conditional(*then_slot, *else_slot); + let then_raw = state.schema(*then_slot).cloned(); + let else_raw = state.schema(*else_slot).cloned(); + let joined = context.infer_expr_schema(&expr, &state); + eprintln!( + "numeric-array conditional case `{name}`: then={then_raw:?} else={else_raw:?} joined={joined:?}" + ); + joined_by_case.push((*name, joined)); + } + + // `[number]` joined with `[int]` yields the shared numeric supertype + // `[number]`. + assert_eq!( + &joined_by_case[0].1, &cases[0].3, + "known numeric tuple and int tuple must share the [number] conditional schema" + ); + assert_eq!( + &joined_by_case[1].1, &cases[1].3, + "a [number] tuple and a [number] array must share the [number] conditional schema" + ); + assert_eq!( + &joined_by_case[2].1, &cases[2].3, + "int and float numeric arrays must share the [number] conditional schema" + ); + // Equality is decided first: an identical pair keeps its precise + // schema instead of being widened to `[number]`. + assert_eq!( + &joined_by_case[3].1, &cases[3].3, + "an identical int tuple must keep its precise tuple schema" + ); + assert_eq!( + &joined_by_case[4].1, &cases[4].3, + "a bool array branch must not join against a numeric array" + ); + assert_eq!( + &joined_by_case[5].1, &cases[5].3, + "an unknown-element array branch must not join against a numeric array" + ); + assert_eq!( + &joined_by_case[6].1, &cases[6].3, + "a branch with no known schema must keep the conditional result unknown" + ); + assert_eq!( + &joined_by_case[7].1, &cases[7].3, + "a heterogeneous tuple (with a bool element) must not join against a numeric tuple" + ); + } + + /// Every shape the numeric-array rule deliberately excludes is checked + /// through a real `Expr::IfElse` inference against a known numeric array + /// on the other branch; each must stay at `None`. + #[test] + fn excluded_shapes_do_not_join_numeric_array_conditionals() { + let empty_impls: HashMap = HashMap::new(); + let empty_decls: HashMap = HashMap::new(); + let empty_structs: HashMap = HashMap::new(); + let empty_names: HashMap = HashMap::new(); + let empty_returns: HashMap = HashMap::new(); + let empty_signatures: HashMap = HashMap::new(); + let mut context = TypeContext::new( + &empty_impls, + &empty_decls, + &empty_structs, + &empty_names, + &empty_returns, + &empty_signatures, + TypingMode::Strict, + None, + ); + + let mut state = LocalTypeState::default(); + state.set_with_schema_origin( + 1, + BoundType::Array, + Some(TypeSchema::Array(Box::new(TypeSchema::Number))), + false, + ); + + // One real `infer_expr_schema` pipeline per excluded shape. + let shapes: [(&str, BoundType, TypeSchema); 8] = [ + ( + "empty tuple", + BoundType::Array, + TypeSchema::ArrayTuple(Vec::new()), + ), + ( + "rest tuple", + BoundType::Array, + TypeSchema::ArrayTupleRest { + prefix: vec![TypeSchema::Int], + rest: Box::new(TypeSchema::Number), + }, + ), + ( + "optional numeric array", + BoundType::Unknown, + TypeSchema::Optional(Box::new(TypeSchema::Array(Box::new(TypeSchema::Number)))), + ), + ( + "named instantiation", + BoundType::Unknown, + TypeSchema::Named("Numbers".to_string(), vec![TypeSchema::Number]), + ), + ( + "generic parameter", + BoundType::Unknown, + TypeSchema::GenericParam("T".to_string()), + ), + ( + "host resource", + BoundType::Unknown, + TypeSchema::Resource(crate::ResourceTypeKey::new("io.file").expect("valid key")), + ), + ( + "nested int array", + BoundType::Array, + TypeSchema::Array(Box::new(TypeSchema::Array(Box::new(TypeSchema::Int)))), + ), + ( + "string-element array", + BoundType::Array, + TypeSchema::Array(Box::new(TypeSchema::String)), + ), + ]; + + for (offset, (_, bound, schema)) in shapes.iter().enumerate() { + let slot = 2 + offset as LocalSlot; + state.set_with_schema_origin(slot, *bound, Some(schema.clone()), false); + } + + for (offset, (name, _, _)) in shapes.iter().enumerate() { + let slot = 2 + offset as LocalSlot; + let expr = Expr::IfElse { + condition: Box::new(Expr::Bool(true)), + then_expr: Box::new(Expr::Var(1)), + else_expr: Box::new(Expr::Var(slot)), + }; + let joined = context.infer_expr_schema(&expr, &state); + assert_eq!( + joined, None, + "excluded shape `{name}` must not join against a known numeric array" + ); + } + } +} diff --git a/tests/aot_tagged_number_tests.rs b/tests/aot_tagged_number_tests.rs index 86d9a458..3465b951 100644 --- a/tests/aot_tagged_number_tests.rs +++ b/tests/aot_tagged_number_tests.rs @@ -448,3 +448,155 @@ fn number_parameter_relational_comparison_is_native() { &[Value::Bool(true)], ); } + +const CHECKED_INT_BUILTIN: &str = "__checked_int_from_number"; + +fn checked_int_call_index() -> u16 { + vm::BUILTIN_CATALOG + .iter() + .find(|builtin| builtin.name() == CHECKED_INT_BUILTIN) + .expect("the checked number-to-int builtin must be catalogued") + .call_index() +} + +fn checked_int_program(value: Value) -> Program { + let mut code = BytecodeBuilder::new(); + code.ldc(0); + code.call(checked_int_call_index(), 1); + code.ret(); + Program::new(vec![value], code.finish()) +} + +fn checked_int_machine(program: Program) -> Vm { + let mut machine = Vm::new_with_jit_config( + program, + JitConfig { + enabled: false, + hot_loop_threshold: 1, + max_trace_len: 512, + }, + ); + machine.set_fuel(10_000_000); + machine +} + +#[test] +fn checked_int_from_number_direct_and_loaded_bytecode_preserve_tagged_int() { + let expected = Value::Int((1_i64 << 53) + 1); + let program = checked_int_program(expected.clone()); + + let mut direct = checked_int_machine(program.clone()); + assert_eq!(direct.run().unwrap(), VmStatus::Halted); + assert_eq!(direct.stack(), std::slice::from_ref(&expected)); + assert_eq!( + direct.aot_exec_count(), + 0, + "the reference path is the interpreter" + ); + direct + .reset_for_reuse() + .expect("the direct reference VM must reset for reuse"); + assert_eq!(direct.host_context().resource_count(), 0); + + let encoded = vm::encode_program(&program).expect("checked int program must encode"); + let decoded = vm::decode_program(&encoded).expect("checked int program must decode"); + let mut loaded = checked_int_machine(decoded); + assert_eq!(loaded.run().unwrap(), VmStatus::Halted); + assert_eq!(loaded.stack(), std::slice::from_ref(&expected)); + loaded + .reset_for_reuse() + .expect("the loaded reference VM must reset for reuse"); + assert_eq!(loaded.host_context().resource_count(), 0); +} + +#[test] +fn checked_int_from_number_generic_native_parity_preserves_tagged_int() { + for (value, expected) in [ + (Value::Int((1_i64 << 53) + 1), Value::Int((1_i64 << 53) + 1)), + (Value::Int(i64::MAX), Value::Int(i64::MAX)), + (Value::Float(42.0), Value::Int(42)), + ] { + let program = checked_int_program(value); + + let mut reference = checked_int_machine(program.clone()); + assert_eq!(reference.run().unwrap(), VmStatus::Halted); + assert_eq!(reference.stack(), std::slice::from_ref(&expected)); + assert_eq!(reference.aot_exec_count(), 0); + reference + .reset_for_reuse() + .expect("the reference VM must reset for reuse"); + assert_eq!(reference.host_context().resource_count(), 0); + + let mut native = checked_int_machine(program); + native + .compile_aot() + .expect("a generic builtin call must lower to a native call boundary"); + assert_ssa(&native); + assert_eq!(native.run().unwrap(), VmStatus::Halted); + assert_eq!(native.stack(), std::slice::from_ref(&expected)); + assert!( + native.aot_exec_count() > 0, + "the native call boundary must actually execute" + ); + native + .reset_for_reuse() + .expect("the native VM must reset for reuse"); + assert_eq!(native.host_context().resource_count(), 0); + } +} + +#[test] +fn checked_int_from_number_native_boundary_reports_the_assert_failure() { + // i64::MAX as f64 rounds up to 2^63, which is outside the checked domain. + let program = checked_int_program(Value::Float(i64::MAX as f64)); + + let mut reference = checked_int_machine(program.clone()); + let reference_error = reference + .run() + .expect_err("2^63 is not a representable i64"); + assert!( + matches!( + reference_error, + VmError::HostError(ref message) if message == "assertion failed" + ), + "{reference_error:?}" + ); + reference + .reset_for_reuse() + .expect("the failing reference VM must reset for reuse"); + assert_eq!(reference.host_context().resource_count(), 0); + + let mut native = checked_int_machine(program); + native + .compile_aot() + .expect("a generic builtin call must lower to a native call boundary"); + assert_ssa(&native); + let native_error = native + .run() + .expect_err("the native boundary must fail rather than succeed"); + assert!( + format!("{native_error}").contains("assertion failed"), + "the native boundary must preserve the host error: {native_error:?}" + ); + assert!( + native.aot_exec_count() > 0, + "the native call boundary must actually execute before failing" + ); + native + .reset_for_reuse() + .expect("the failing native VM must reset for reuse"); + assert_eq!(native.host_context().resource_count(), 0); +} + +#[test] +fn checked_int_from_number_rejects_non_number_through_vm() { + let mut machine = checked_int_machine(checked_int_program(Value::Bool(true))); + assert!(matches!( + machine.run(), + Err(VmError::TypeMismatch("number")) + )); + machine + .reset_for_reuse() + .expect("the rejected VM must reset"); + assert_eq!(machine.host_context().resource_count(), 0); +} diff --git a/tests/wire/catalog_contract_tests.rs b/tests/wire/catalog_contract_tests.rs index 05c934ff..3fae8790 100644 --- a/tests/wire/catalog_contract_tests.rs +++ b/tests/wire/catalog_contract_tests.rs @@ -34,7 +34,8 @@ const SQLITE_RESERVED_TOP_END: u16 = u16::MAX; /// Reserved sentinel gap inside the special-call block (see the catalog docs /// and `core.rs::internal_builtins_have_unique_reserved_call_indices`). -const RESERVED_GAP_START: u16 = 0xFF90; +/// `0xFF90` is owned by `__checked_int_from_number`. +const RESERVED_GAP_START: u16 = 0xFF91; const RESERVED_GAP_END: u16 = 0xFF92; #[derive(Clone, Debug, PartialEq, Eq)] @@ -196,7 +197,7 @@ fn static_builtin_ids_are_frozen() { } // Reserved sentinel ranges stay empty: the extension block (future - // builtins and host imports) and the 0xFF90..=0xFF92 gap. + // builtins and host imports) and the 0xFF91..=0xFF92 gap. for entry in &entries { assert!( entry.id > EXTENSION_BLOCK_END, @@ -428,3 +429,37 @@ fn appending_or_reordering_catalog_entries_does_not_renumber_existing_ids() { } } } + +/// The checked Number-to-Int internal builtin owns the sentinel-adjacent +/// 0xFF90 slot with one explicit catalog ID: source name, Rust variant, class, +/// generated enum name, and reverse lookup all agree, and the remaining +/// sentinel slots stay free. +#[test] +fn checked_int_from_number_owns_explicit_sentinel_adjacent_id() { + let entries = parse_catalog(&catalog_source()); + let entry = entries + .iter() + .find(|entry| entry.id == 0xFF90) + .expect("0xFF90 must be assigned to the checked number-to-int builtin"); + assert_eq!(entry.source_name, "__checked_int_from_number"); + assert_eq!(entry.variant, "CheckedIntFromNumber"); + assert_eq!(entry.class, "Internal"); + assert_eq!(entry.feature_gate, "none"); + + // Internal names remain unavailable through the guest-facing source lookup. + assert_eq!(builtin_call_index("__checked_int_from_number"), None); + assert_eq!( + BUILTIN_CATALOG + .iter() + .find(|builtin| builtin.call_index() == 0xFF90) + .map(|builtin| builtin.name()), + Some("__checked_int_from_number") + ); + + for reserved in [RESERVED_GAP_START, RESERVED_GAP_END] { + assert!( + entries.iter().all(|entry| entry.id != reserved), + "sentinel slot 0x{reserved:04X} must stay unassigned" + ); + } +} From afefa8f014cdf94d4380e60888c4bdc32ed4f260 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 16 Nov 2026 13:59:35 +0800 Subject: [PATCH 2/2] fix(compiler): clear reused slot schemas without losing declarations --- src/compiler/assign_declaration.rs | 548 ++++++++++++++++++++++ src/compiler/codegen.rs | 36 +- src/compiler/mod.rs | 1 + src/compiler/pipeline.rs | 2 + tests/float_div_reused_slot_hint_tests.rs | 527 +++++++++++++++++++++ 5 files changed, 1113 insertions(+), 1 deletion(-) create mode 100644 src/compiler/assign_declaration.rs create mode 100644 tests/float_div_reused_slot_hint_tests.rs diff --git a/src/compiler/assign_declaration.rs b/src/compiler/assign_declaration.rs new file mode 100644 index 00000000..21370b83 --- /dev/null +++ b/src/compiler/assign_declaration.rs @@ -0,0 +1,548 @@ +//! Private logical-declaration identity for `Stmt::Assign`. +//! +//! A physical `Drop` clears the slot schema, and compaction then reuses that +//! slot. The declaration must stay with the assignment, not with the slot. +//! It is not a field of [`Stmt`]: downstream frontends construct `Assign` +//! directly. Compaction remaps slots in place and does not reorder the tree, +//! so a structural path captured before compaction still names the same +//! assignment afterwards, including on a cloned function or closure body. + +use std::collections::HashMap; + +use super::ir::{ClosureExpr, Expr, FrontendIr, LocalSlot, Stmt, TypeSchema}; + +const STEP_STMT: u32 = 1; +const STEP_EXPR: u32 = 2; +const STEP_INIT: u32 = 3; +const STEP_POST: u32 = 4; +const STEP_COND: u32 = 5; +const STEP_THEN: u32 = 6; +const STEP_ELSE: u32 = 7; +const STEP_BODY: u32 = 8; +const STEP_TAIL: u32 = 9; +const STEP_ARG: u32 = 10; +const STEP_ARM: u32 = 11; +const STEP_DEFAULT: u32 = 12; +const STEP_PAYLOAD: u32 = 13; +const STEP_OK: u32 = 14; +const STEP_ERR: u32 = 15; +const STEP_SOME: u32 = 16; +const STEP_NONE: u32 = 17; +const STEP_VALUE: u32 = 18; +const STEP_FALLBACK: u32 = 19; +const STEP_KEY: u32 = 20; +const STEP_CONTAINER: u32 = 21; +const STEP_LEFT: u32 = 22; +const STEP_RIGHT: u32 = 23; +const STEP_OPERAND: u32 = 24; +const STEP_RECEIVER: u32 = 25; +const STEP_ARGUMENT: u32 = 26; +const STEP_CLOSURE: u32 = 27; +const STEP_CALLEE: u32 = 28; +const STEP_BODY_EXPR: u32 = 29; + +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct AssignPath(Vec); + +#[derive(Clone, Debug, Default)] +pub(super) struct AssignDeclarationSidecar { + root: HashMap, + functions: HashMap>, +} + +#[derive(Clone, Debug, Default)] +pub(super) struct AssignDeclarationMap { + by_stmt: HashMap, +} + +impl AssignDeclarationMap { + pub(super) fn schema_of(&self, stmt: &Stmt) -> Option<&TypeSchema> { + self.by_stmt.get(&stmt_key(stmt)) + } +} + +pub(super) fn capture(ir: &FrontendIr) -> AssignDeclarationSidecar { + let mut sidecar = AssignDeclarationSidecar::default(); + let mut root_decls = HashMap::new(); + collect_lets(&ir.stmts, None, &mut root_decls); + record_assigns(&ir.stmts, None, &root_decls, &mut sidecar.root); + + for (index, function_impl) in &ir.function_impls { + let mut decls = HashMap::new(); + if let Some(decl) = ir.functions.iter().find(|decl| decl.index == *index) { + for (slot, schema) in function_impl.param_slots.iter().zip(&decl.arg_schemas) { + if let Some(schema) = schema { + decls.insert(*slot, schema.clone()); + } + } + } + collect_lets( + &function_impl.body_stmts, + Some(&function_impl.body_expr), + &mut decls, + ); + let mut recorded = HashMap::new(); + record_assigns( + &function_impl.body_stmts, + Some(&function_impl.body_expr), + &decls, + &mut recorded, + ); + if !recorded.is_empty() { + sidecar.functions.insert(*index, recorded); + } + } + sidecar +} + +pub(super) fn bind_stmts( + sidecar: &AssignDeclarationSidecar, + stmts: &[Stmt], +) -> AssignDeclarationMap { + bind_known(&sidecar.root, stmts, None) +} + +pub(super) fn bind_function( + sidecar: &AssignDeclarationSidecar, + index: u16, + stmts: &[Stmt], + body_expr: &Expr, +) -> AssignDeclarationMap { + let Some(known) = sidecar.functions.get(&index) else { + return AssignDeclarationMap::default(); + }; + bind_known(known, stmts, Some(body_expr)) +} + +/// Schemas of every assignment in `closure`, in walker preorder. +/// +/// The queued closure is a clone, so its statement addresses differ from the +/// tree currently being compiled. The vec is taken from the parent node and +/// zipped onto the clone later. A length mismatch means the clone is not the +/// same shape; the caller must not apply a shifted schema. +pub(super) fn preorder_schemas( + closure: &ClosureExpr, + map: &AssignDeclarationMap, +) -> Vec> { + let mut out = Vec::new(); + let mut visit = Preorder { + known: &map.by_stmt, + out: &mut out, + }; + let mut path = Vec::new(); + walk_expr(&closure.body, &mut path, &mut visit); + out +} + +pub(super) fn bind_preorder( + closure: &ClosureExpr, + schemas: &[Option], +) -> AssignDeclarationMap { + let mut out = HashMap::new(); + let mut visit = Install { + schemas, + cursor: 0, + out: &mut out, + }; + let mut path = Vec::new(); + walk_expr(&closure.body, &mut path, &mut visit); + if visit.cursor != schemas.len() { + return AssignDeclarationMap::default(); + } + AssignDeclarationMap { by_stmt: out } +} + +fn bind_known( + known: &HashMap, + stmts: &[Stmt], + body_expr: Option<&Expr>, +) -> AssignDeclarationMap { + let mut out = HashMap::new(); + let mut visit = BindAssigns { + known, + out: &mut out, + }; + walk_scope(stmts, body_expr, &mut visit); + AssignDeclarationMap { by_stmt: out } +} + +fn collect_lets( + stmts: &[Stmt], + body_expr: Option<&Expr>, + decls: &mut HashMap, +) { + let mut visit = CollectLets { decls }; + walk_scope(stmts, body_expr, &mut visit); +} + +fn record_assigns( + stmts: &[Stmt], + body_expr: Option<&Expr>, + decls: &HashMap, + out: &mut HashMap, +) { + let mut visit = RecordAssigns { decls, out }; + walk_scope(stmts, body_expr, &mut visit); +} + +fn walk_scope(stmts: &[Stmt], body_expr: Option<&Expr>, visit: &mut impl Visitor) { + let mut path = Vec::new(); + walk_stmts(stmts, &mut path, visit); + if let Some(body_expr) = body_expr { + path.push(STEP_BODY_EXPR); + walk_expr(body_expr, &mut path, visit); + } +} + +trait Visitor { + fn on_let(&mut self, slot: LocalSlot, schema: &Option); + fn on_assign(&mut self, stmt: &Stmt, slot: LocalSlot, path: &[u32]); +} + +struct CollectLets<'a> { + decls: &'a mut HashMap, +} + +impl Visitor for CollectLets<'_> { + fn on_let(&mut self, slot: LocalSlot, schema: &Option) { + if let Some(schema) = schema { + self.decls.insert(slot, schema.clone()); + } + } + + fn on_assign(&mut self, _stmt: &Stmt, _slot: LocalSlot, _path: &[u32]) {} +} + +struct RecordAssigns<'a> { + decls: &'a HashMap, + out: &'a mut HashMap, +} + +impl Visitor for RecordAssigns<'_> { + fn on_let(&mut self, _slot: LocalSlot, _schema: &Option) {} + + fn on_assign(&mut self, _stmt: &Stmt, slot: LocalSlot, path: &[u32]) { + if let Some(schema) = self.decls.get(&slot) { + self.out.insert(AssignPath(path.to_vec()), schema.clone()); + } + } +} + +struct BindAssigns<'a> { + known: &'a HashMap, + out: &'a mut HashMap, +} + +impl Visitor for BindAssigns<'_> { + fn on_let(&mut self, _slot: LocalSlot, _schema: &Option) {} + + fn on_assign(&mut self, stmt: &Stmt, _slot: LocalSlot, path: &[u32]) { + if let Some(schema) = self.known.get(&AssignPath(path.to_vec())) { + self.out.insert(stmt_key(stmt), schema.clone()); + } + } +} + +struct Preorder<'a> { + known: &'a HashMap, + out: &'a mut Vec>, +} + +impl Visitor for Preorder<'_> { + fn on_let(&mut self, _slot: LocalSlot, _schema: &Option) {} + + fn on_assign(&mut self, stmt: &Stmt, _slot: LocalSlot, _path: &[u32]) { + self.out.push(self.known.get(&stmt_key(stmt)).cloned()); + } +} + +struct Install<'a> { + schemas: &'a [Option], + cursor: usize, + out: &'a mut HashMap, +} + +impl Visitor for Install<'_> { + fn on_let(&mut self, _slot: LocalSlot, _schema: &Option) {} + + fn on_assign(&mut self, stmt: &Stmt, _slot: LocalSlot, _path: &[u32]) { + if let Some(Some(schema)) = self.schemas.get(self.cursor) { + self.out.insert(stmt_key(stmt), schema.clone()); + } + self.cursor += 1; + } +} + +fn stmt_key(stmt: &Stmt) -> usize { + stmt as *const Stmt as usize +} + +fn walk_stmts(stmts: &[Stmt], path: &mut Vec, visit: &mut impl Visitor) { + for (index, stmt) in stmts.iter().enumerate() { + path.push(STEP_STMT); + path.push(index as u32); + walk_stmt(stmt, path, visit); + path.pop(); + path.pop(); + } +} + +fn walk_stmt(stmt: &Stmt, path: &mut Vec, visit: &mut impl Visitor) { + match stmt { + Stmt::Let { + index, + declared_schema, + expr, + .. + } => { + visit.on_let(*index, declared_schema); + push_step(path, STEP_EXPR, |path| walk_expr(expr, path, visit)); + } + Stmt::Assign { index, expr, .. } => { + visit.on_assign(stmt, *index, path); + push_step(path, STEP_EXPR, |path| walk_expr(expr, path, visit)); + } + Stmt::Expr { expr, .. } => { + push_step(path, STEP_EXPR, |path| walk_expr(expr, path, visit)); + } + Stmt::IfElse { + condition, + then_branch, + else_branch, + .. + } => { + push_step(path, STEP_COND, |path| walk_expr(condition, path, visit)); + push_step(path, STEP_THEN, |path| walk_stmts(then_branch, path, visit)); + push_step(path, STEP_ELSE, |path| walk_stmts(else_branch, path, visit)); + } + Stmt::For { + init, + condition, + post, + body, + .. + } => { + push_step(path, STEP_INIT, |path| walk_stmt(init, path, visit)); + push_step(path, STEP_COND, |path| walk_expr(condition, path, visit)); + push_step(path, STEP_POST, |path| walk_stmt(post, path, visit)); + push_step(path, STEP_BODY, |path| walk_stmts(body, path, visit)); + } + Stmt::While { + condition, body, .. + } => { + push_step(path, STEP_COND, |path| walk_expr(condition, path, visit)); + push_step(path, STEP_BODY, |path| walk_stmts(body, path, visit)); + } + Stmt::ClosureLet { closure, .. } => { + push_step(path, STEP_CLOSURE, |path| { + walk_expr(&closure.body, path, visit) + }); + } + Stmt::Noop { .. } + | Stmt::FuncDecl { .. } + | Stmt::Break { .. } + | Stmt::Continue { .. } + | Stmt::Drop { .. } => {} + } +} + +fn walk_expr(expr: &Expr, path: &mut Vec, visit: &mut impl Visitor) { + match expr { + Expr::OptionalGet { container, key, .. } => { + push_step(path, STEP_CONTAINER, |path| { + walk_expr(container, path, visit) + }); + push_step(path, STEP_KEY, |path| walk_expr(key, path, visit)); + } + Expr::OptionUnwrapOr { + value, fallback, .. + } => { + push_step(path, STEP_VALUE, |path| walk_expr(value, path, visit)); + push_step(path, STEP_FALLBACK, |path| walk_expr(fallback, path, visit)); + } + Expr::Call(_, _, args, _, _) + | Expr::ModuleCall(_, _, args, _) + | Expr::LocalCall(_, _, args, _) => walk_args(args, path, visit), + Expr::Closure(closure) => { + push_step(path, STEP_CLOSURE, |path| { + walk_expr(&closure.body, path, visit) + }); + } + Expr::ClosureCall(closure, args) => { + push_step(path, STEP_CALLEE, |path| { + push_step(path, STEP_CLOSURE, |path| { + walk_expr(&closure.body, path, visit) + }); + }); + walk_args(args, path, visit); + } + Expr::Add(lhs, rhs) + | Expr::Sub(lhs, rhs) + | Expr::Mul(lhs, rhs) + | Expr::Div(lhs, rhs) + | Expr::Mod(lhs, rhs) + | Expr::And(lhs, rhs) + | Expr::Or(lhs, rhs) + | Expr::Eq(lhs, rhs) + | Expr::Lt(lhs, rhs) + | Expr::Gt(lhs, rhs) => { + push_step(path, STEP_LEFT, |path| walk_expr(lhs, path, visit)); + push_step(path, STEP_RIGHT, |path| walk_expr(rhs, path, visit)); + } + Expr::Neg(inner) + | Expr::Not(inner) + | Expr::ToOwned(inner) + | Expr::Borrow(inner) + | Expr::BorrowMut(inner) => { + push_step(path, STEP_OPERAND, |path| walk_expr(inner, path, visit)); + } + Expr::IfElse { + condition, + then_expr, + else_expr, + } => { + push_step(path, STEP_COND, |path| walk_expr(condition, path, visit)); + push_step(path, STEP_THEN, |path| walk_expr(then_expr, path, visit)); + push_step(path, STEP_ELSE, |path| walk_expr(else_expr, path, visit)); + } + Expr::Match { + value, + arms, + default, + .. + } => { + push_step(path, STEP_VALUE, |path| walk_expr(value, path, visit)); + for (index, (_, arm)) in arms.iter().enumerate() { + path.push(STEP_ARM); + path.push(index as u32); + walk_expr(arm, path, visit); + path.pop(); + path.pop(); + } + push_step(path, STEP_DEFAULT, |path| walk_expr(default, path, visit)); + } + Expr::Block { stmts, expr } => { + push_step(path, STEP_BODY, |path| walk_stmts(stmts, path, visit)); + push_step(path, STEP_TAIL, |path| walk_expr(expr, path, visit)); + } + Expr::ResultConstruct { payload, .. } => { + push_step(path, STEP_PAYLOAD, |path| walk_expr(payload, path, visit)); + } + Expr::ResultMatch { + value, + ok_expr, + err_expr, + .. + } => { + push_step(path, STEP_VALUE, |path| walk_expr(value, path, visit)); + push_step(path, STEP_OK, |path| walk_expr(ok_expr, path, visit)); + push_step(path, STEP_ERR, |path| walk_expr(err_expr, path, visit)); + } + Expr::ResultQuery { value, .. } + | Expr::ResultTry { value, .. } + | Expr::ResultConvert { value, .. } => { + push_step(path, STEP_VALUE, |path| walk_expr(value, path, visit)); + } + Expr::ResultMethod { + receiver, argument, .. + } + | Expr::OptionMethod { + receiver, argument, .. + } => { + push_step(path, STEP_RECEIVER, |path| walk_expr(receiver, path, visit)); + push_step(path, STEP_ARGUMENT, |path| walk_expr(argument, path, visit)); + } + Expr::OptionConstruct { payload, .. } => { + if let Some(payload) = payload { + push_step(path, STEP_PAYLOAD, |path| walk_expr(payload, path, visit)); + } + } + Expr::OptionMatch { + value, + some_expr, + none_expr, + .. + } => { + push_step(path, STEP_VALUE, |path| walk_expr(value, path, visit)); + push_step(path, STEP_SOME, |path| walk_expr(some_expr, path, visit)); + push_step(path, STEP_NONE, |path| walk_expr(none_expr, path, visit)); + } + Expr::Null + | Expr::Unit + | Expr::Int(_) + | Expr::Float(_) + | Expr::Bool(_) + | Expr::String(_) + | Expr::Bytes(_) + | Expr::FunctionRef(_, _) + | Expr::ModuleFunctionRef(_, _) + | Expr::UnresolvedFunctionRef { .. } + | Expr::Var(_) + | Expr::MoveVar(_) + | Expr::MoveField { .. } + | Expr::MoveIndex { .. } => {} + } +} + +fn walk_args(args: &[Expr], path: &mut Vec, visit: &mut impl Visitor) { + for (index, arg) in args.iter().enumerate() { + path.push(STEP_ARG); + path.push(index as u32); + walk_expr(arg, path, visit); + path.pop(); + path.pop(); + } +} + +fn push_step(path: &mut Vec, step: u32, walk: impl FnOnce(&mut Vec)) { + path.push(step); + walk(path); + path.pop(); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::compiler::ir::AssignmentKind; + + #[test] + fn closure_clone_keeps_assign_declaration_identity() { + let closure = ClosureExpr { + param_slots: Vec::new(), + capture_copies: Vec::new(), + body: Box::new(Expr::Block { + stmts: vec![Stmt::Assign { + kind: AssignmentKind::Set, + index: 3, + expr: Expr::Int(2), + line: 1, + }], + expr: Box::new(Expr::Var(3)), + }), + }; + let mut known = AssignDeclarationMap::default(); + let Expr::Block { stmts, .. } = closure.body.as_ref() else { + panic!("closure body"); + }; + known + .by_stmt + .insert(stmt_key(&stmts[0]), TypeSchema::Number); + let schemas = preorder_schemas(&closure, &known); + assert_eq!(schemas, vec![Some(TypeSchema::Number)]); + + let cloned = closure.clone(); + let bound = bind_preorder(&cloned, &schemas); + let Expr::Block { stmts, .. } = cloned.body.as_ref() else { + panic!("cloned body"); + }; + assert_eq!(bound.schema_of(&stmts[0]), Some(&TypeSchema::Number)); + assert_ne!(stmt_key(&stmts[0]), stmt_key(closure_assign(&closure))); + } + + fn closure_assign(closure: &ClosureExpr) -> &Stmt { + let Expr::Block { stmts, .. } = closure.body.as_ref() else { + panic!("closure body"); + }; + &stmts[0] + } +} diff --git a/src/compiler/codegen.rs b/src/compiler/codegen.rs index af7486e4..12c28cd4 100644 --- a/src/compiler/codegen.rs +++ b/src/compiler/codegen.rs @@ -70,6 +70,9 @@ pub struct Compiler { in_callable: bool, /// Err-path `Ret` sites and the owned locals to close before the frame drain. ret_cleanups: Vec, + assign_declarations: super::assign_declaration::AssignDeclarationSidecar, + assign_declaration_map: super::assign_declaration::AssignDeclarationMap, + pending_closure_schemas: Vec>>, } struct LoopContext { @@ -137,6 +140,9 @@ impl Compiler { closure_param_hints: HashMap::new(), in_callable: false, ret_cleanups: Vec::new(), + assign_declarations: super::assign_declaration::AssignDeclarationSidecar::default(), + assign_declaration_map: super::assign_declaration::AssignDeclarationMap::default(), + pending_closure_schemas: Vec::new(), } } @@ -169,6 +175,13 @@ impl Compiler { self.root_local_count = root_local_count; } + pub(super) fn set_assign_declarations( + &mut self, + declarations: super::assign_declaration::AssignDeclarationSidecar, + ) { + self.assign_declarations = declarations; + } + pub fn set_function_impls(&mut self, function_impls: HashMap) { self.function_impls = function_impls; } @@ -249,6 +262,8 @@ impl Compiler { )>, ) -> Result { let named_functions = self.prepare_named_callables()?; + self.assign_declaration_map = + super::assign_declaration::bind_stmts(&self.assign_declarations, stmts); for (index, stmt) in stmts.iter().enumerate() { self.capture_owner = Some(super::capture_certification::CaptureOwner::RootStatement( index, @@ -272,6 +287,9 @@ impl Compiler { let mut closure_index = 0usize; while closure_index < self.pending_closures.len() { let (prototype_id, closure) = self.pending_closures[closure_index].clone(); + let schemas = self.pending_closure_schemas[closure_index].clone(); + self.assign_declaration_map = + super::assign_declaration::bind_preorder(&closure, &schemas); self.compile_closure_body(prototype_id, &closure)?; closure_index += 1; } @@ -498,6 +516,12 @@ impl Compiler { .get(&function_index) .cloned() .expect("prepared function implementation must exist"); + self.assign_declaration_map = super::assign_declaration::bind_function( + &self.assign_declarations, + function_index, + &function_impl.body_stmts, + &function_impl.body_expr, + ); let prototype_id = self.function_prototype_ids[&function_index]; let entry_ip = self.assembler.position(); let callable_snapshot = self.callable_bindings.clone(); @@ -612,8 +636,9 @@ impl Compiler { Stmt::Assign { index, expr, line, .. } => { + let declared = self.assign_declaration_map.schema_of(stmt).cloned(); self.assembler.mark_line(*line); - self.assign_expr_to_slot(*index, None, expr)?; + self.assign_expr_to_slot(*index, declared.as_ref(), expr)?; } Stmt::ClosureLet { line, .. } => { self.assembler.mark_line(*line); @@ -814,6 +839,10 @@ impl Compiler { Stmt::Drop { index, line } => { self.assembler.mark_line(*line); self.assign_expr_to_slot(*index, None, &Expr::Null)?; + // The Null store retires the physical value. Clear schema and + // declared origin too, matching typing's Drop, so a later + // occupant of this slot cannot inherit the dead value's schema. + self.type_state.set(*index, typing::BoundType::Null); } } Ok(()) @@ -2365,6 +2394,11 @@ impl Compiler { }), }); self.pending_closures.push((prototype_id, closure.clone())); + self.pending_closure_schemas + .push(super::assign_declaration::preorder_schemas( + closure, + &self.assign_declaration_map, + )); self.emit_bind_callable( prototype_id, closure.capture_copies.iter().map(|(source, target)| { diff --git a/src/compiler/mod.rs b/src/compiler/mod.rs index 23fb3299..7f80762c 100644 --- a/src/compiler/mod.rs +++ b/src/compiler/mod.rs @@ -8,6 +8,7 @@ use crate::assembler::AssemblerError; #[cfg(feature = "runtime")] use crate::vm::Vm; +mod assign_declaration; pub(crate) mod capture_certification; pub use capture_certification::CertifiedCompilation; mod codegen; diff --git a/src/compiler/pipeline.rs b/src/compiler/pipeline.rs index 64fa04f3..d50f44fe 100644 --- a/src/compiler/pipeline.rs +++ b/src/compiler/pipeline.rs @@ -1160,6 +1160,7 @@ fn compile_owned_ir_with_capture_output( // value identities, so the classification is strictly more precise on // the unallocated IR. let callable_use_facts = materialization::classify_named_callables(&parsed); + let assign_declarations = super::assign_declaration::capture(&parsed); let (parsed, entry_local_types, root_slots) = match local_layout { LocalLayoutPolicy::Compact if origins.is_none() => ( lifetime::allocate_local_slots(parsed).map_err(SourceError::Parse)?, @@ -1298,6 +1299,7 @@ fn compile_owned_ir_with_capture_output( let host_import_signatures = typing::build_host_import_signatures(&functions, &function_impls); let mut compiler = Compiler::new(); + compiler.set_assign_declarations(assign_declarations); compiler.set_type_inference(type_info); compiler.set_typing_mode(typing_mode); compiler.set_source(source); diff --git a/tests/float_div_reused_slot_hint_tests.rs b/tests/float_div_reused_slot_hint_tests.rs new file mode 100644 index 00000000..c6064c23 --- /dev/null +++ b/tests/float_div_reused_slot_hint_tests.rs @@ -0,0 +1,527 @@ +#![cfg(feature = "runtime")] + +use vm::{OpCode, Value, ValueType, Vm, VmStatus, compile_source, disassemble_program}; + +fn div_hints(program: &vm::Program) -> Vec<(usize, Option<(ValueType, ValueType)>)> { + let hints = program + .type_map + .as_ref() + .map(|type_map| &type_map.operand_types); + let code = &program.code; + let mut ip = 0usize; + let mut found = Vec::new(); + while ip < code.len() { + let start = ip; + let opcode = code[ip]; + ip += 1; + let width = match opcode { + x if x == OpCode::Ldc as u8 || x == OpCode::Br as u8 || x == OpCode::Brfalse as u8 => 4, + x if x == OpCode::Ldloc as u8 + || x == OpCode::Stloc as u8 + || x == OpCode::CallValue as u8 => + { + 1 + } + x if x == OpCode::Call as u8 => 3, + x if x == OpCode::CallScript as u8 => 5, + _ => 0, + }; + if ip + width > code.len() { + break; + } + if opcode == OpCode::Div as u8 { + let hint = hints.and_then(|hints| hints.get(&start).copied()); + found.push((start, hint)); + } + ip += width; + } + found +} + +fn compile_and_run( + source: &str, +) -> ( + vm::CompiledProgram, + Result, + Vec, +) { + let compiled = compile_source(source).unwrap_or_else(|error| panic!("{source}\n{error}")); + let mut machine = Vm::new(compiled.program.clone().with_local_count(compiled.locals)); + machine.set_fuel(100_000); + let status = machine.run(); + let stack = machine.stack().to_vec(); + (compiled, status, stack) +} + +/// An Int binding and a later Float binding can share one physical slot once +/// the Float value is dead. Reassigning the Int and dividing it by 1.0 must +/// keep an Int/Float hint and perform numeric division. +#[test] +fn reused_physical_slot_keeps_int_float_div_hint() { + let source = r#" + fn produce() -> int { 7 } + fn probe() -> float { + let mut checked: int = 0; + let temporary: float = 1.5; + let sink = temporary + 0.0; + let pad0 = 1; + let pad1 = 2; + let pad2 = 3; + let pad3 = 4; + let pad4 = 5; + let pad5 = 6; + checked = produce(); + let mut out = sink; + if pad0 + pad1 + pad2 + pad3 + pad4 + pad5 == 21 { + out = checked / 1.0; + } + out + } + probe(); + "#; + let (compiled, status, stack) = compile_and_run(source); + let hints = div_hints(&compiled.program); + let listing = disassemble_program(&compiled.program); + assert!( + hints + .iter() + .any(|(_, hint)| *hint == Some((ValueType::Int, ValueType::Float))), + "expected an Int/Float div hint, got {hints:?}\nlocals={}\n{listing}", + compiled.locals + ); + assert!( + hints + .iter() + .all(|(_, hint)| *hint != Some((ValueType::Float, ValueType::Float))), + "Int local was hinted Float/Float: {hints:?}\nlocals={}\n{listing}", + compiled.locals + ); + let status = status.unwrap_or_else(|error| { + panic!( + "runtime {error:?}\nhints={hints:?}\nlocals={}\n{listing}", + compiled.locals + ) + }); + assert_eq!(status, VmStatus::Halted, "{listing}"); + assert_eq!(stack.last(), Some(&Value::Float(7.0)), "{listing}"); +} + +fn hint_values( + hints: &[(usize, Option<(ValueType, ValueType)>)], +) -> Vec> { + hints.iter().map(|(_, hint)| *hint).collect() +} + +fn assert_div_result(source: &str, expected_hint: (ValueType, ValueType), expected: Value) { + let (compiled, status, stack) = compile_and_run(source); + let hints = div_hints(&compiled.program); + let listing = disassemble_program(&compiled.program); + assert!( + hints.iter().any(|(_, hint)| *hint == Some(expected_hint)), + "expected div hint {expected_hint:?}, got {hints:?}\nlocals={}\n{listing}", + compiled.locals + ); + let status = status.unwrap_or_else(|error| { + panic!( + "runtime {error:?}\nhints={hints:?}\nlocals={}\n{listing}", + compiled.locals + ) + }); + assert_eq!(status, VmStatus::Halted, "{listing}"); + assert_eq!(stack.last(), Some(&expected), "{listing}"); +} + +#[test] +fn int_float_div_without_slot_reuse_is_numeric() { + assert_div_result( + r#" + fn produce() -> int { 7 } + fn probe() -> float { + let checked = produce(); + checked / 1.0 + } + probe(); + "#, + (ValueType::Int, ValueType::Float), + Value::Float(7.0), + ); +} + +#[test] +fn reused_physical_slot_keeps_float_float_div_hint() { + assert_div_result( + r#" + fn produce() -> float { 8.0 } + fn probe() -> float { + let mut checked: float = 0.0; + let temporary: int = 7; + let sink = temporary + 0; + let pad0 = 1.0; + let pad1 = 2.0; + let pad2 = 3.0; + let pad3 = 4.0; + let pad4 = 5.0; + let pad5 = 6.0; + checked = produce(); + let mut out = sink + pad0; + if pad1 + pad2 + pad3 + pad4 + pad5 == 20.0 { + out = checked / 2.0; + } + out + } + probe(); + "#, + (ValueType::Float, ValueType::Float), + Value::Float(4.0), + ); +} + +const NUMBER_DIV_CONTROL: &str = r#" + fn produce() -> number { 7 } + fn probe() -> float { + let checked = produce(); + checked / 1.0 + } + probe(); +"#; + +const NUMBER_DIV_REUSED_SLOT: &str = r#" + fn produce() -> number { 7 } + fn probe() -> float { + let mut checked: number = 0; + let temporary: float = 1.5; + let sink = temporary + 0.0; + let pad0 = 1; + let pad1 = 2; + let pad2 = 3; + let pad3 = 4; + let pad4 = 5; + let pad5 = 6; + checked = produce(); + let mut out = sink; + if pad0 + pad1 + pad2 + pad3 + pad4 + pad5 == 21 { + out = checked / 1.0; + } + out + } + probe(); +"#; + +/// A dead float and a later untyped number binding can share one physical +/// slot. The number is physically an int. Dividing it by 1.0 must keep the +/// same generic hint as a number division that never occupied a float slot. +#[test] +fn reused_physical_slot_number_producer_keeps_generic_div_hint() { + let (control_compiled, control_status, control_stack) = compile_and_run(NUMBER_DIV_CONTROL); + let control_hints = div_hints(&control_compiled.program); + let control_values = hint_values(&control_hints); + assert!( + control_values + .iter() + .all(|hint| *hint != Some((ValueType::Float, ValueType::Float))), + "number control was specialized Float/Float: {control_hints:?}" + ); + let control_status = control_status.unwrap_or_else(|error| panic!("control runtime {error:?}")); + assert_eq!(control_status, VmStatus::Halted); + assert_eq!(control_stack.last(), Some(&Value::Float(7.0))); + + let (compiled, status, stack) = compile_and_run(NUMBER_DIV_REUSED_SLOT); + let hints = div_hints(&compiled.program); + let listing = disassemble_program(&compiled.program); + let values = hint_values(&hints); + assert_eq!( + values, control_values, + "expected generic number div hint {control_values:?}, got {hints:?}\n\ + guest={status:?}\nsource={NUMBER_DIV_REUSED_SLOT}\nlocals={}\n{listing}", + compiled.locals + ); + assert!( + hints + .iter() + .all(|(_, hint)| *hint != Some((ValueType::Float, ValueType::Float))), + "stale Float/Float hint on number reuse: {hints:?}\n\ + guest={status:?}\nsource={NUMBER_DIV_REUSED_SLOT}\nlocals={}\n{listing}", + compiled.locals + ); + let status = status.unwrap_or_else(|error| { + panic!( + "runtime {error:?}\nhints={hints:?}\nlocals={}\nsource={NUMBER_DIV_REUSED_SLOT}\n{listing}", + compiled.locals + ) + }); + assert_eq!(status, VmStatus::Halted, "{listing}"); + assert_eq!(stack.last(), Some(&Value::Float(7.0)), "{listing}"); +} + +/// `let mut n: number = 0; n = 2` is the source form of a declared number +/// binding followed by an int store. The declaration stays number: the div +/// hint matches a direct number binding, not a narrowed Int/Float hint. +#[test] +fn declared_number_reassignment_keeps_number_div_hint() { + let declared = r#" + fn probe() -> float { + let n: number = 2; + n / 1.0 + } + probe(); + "#; + let reassigned = r#" + fn probe() -> float { + let mut n: number = 0; + n = 2; + n / 1.0 + } + probe(); + "#; + let (declared_compiled, declared_status, declared_stack) = compile_and_run(declared); + let declared_hints = div_hints(&declared_compiled.program); + let declared_values = hint_values(&declared_hints); + let declared_status = + declared_status.unwrap_or_else(|error| panic!("declared runtime {error:?}")); + assert_eq!(declared_status, VmStatus::Halted); + assert_eq!(declared_stack.last(), Some(&Value::Float(2.0))); + + let (compiled, status, stack) = compile_and_run(reassigned); + let hints = div_hints(&compiled.program); + let listing = disassemble_program(&compiled.program); + let values = hint_values(&hints); + assert_eq!( + values, declared_values, + "declared number was narrowed: got {hints:?}, direct number hint {declared_values:?}\n\ + guest={status:?}\nsource={reassigned}\nlocals={}\n{listing}", + compiled.locals + ); + assert!( + hints + .iter() + .all(|(_, hint)| *hint != Some((ValueType::Int, ValueType::Float))), + "number declaration narrowed to Int/Float: {hints:?}\n{listing}" + ); + let status = status.unwrap_or_else(|error| panic!("runtime {error:?}\n{listing}")); + assert_eq!(status, VmStatus::Halted, "{listing}"); + assert_eq!(stack.last(), Some(&Value::Float(2.0)), "{listing}"); +} + +/// An untyped parameter is not a concrete Int. After a dead float reuses its +/// slot, dividing the restored value by 1.0 must keep the same generic hint +/// as an untyped division that never occupied a float slot. +#[test] +fn reused_physical_slot_untyped_producer_keeps_generic_div_hint() { + let control = r#" + fn probe(value) -> float { + value / 1.0 + } + probe(7); + "#; + let reused = r#" + fn probe(value) -> float { + let mut checked = value; + let temporary: float = 1.5; + let sink = temporary + 0.0; + let pad0 = 1; + let pad1 = 2; + let pad2 = 3; + let pad3 = 4; + let pad4 = 5; + let pad5 = 6; + checked = value; + let mut out = sink; + if pad0 + pad1 + pad2 + pad3 + pad4 + pad5 == 21 { + out = checked / 1.0; + } + out + } + probe(7); + "#; + let (control_compiled, control_status, control_stack) = compile_and_run(control); + let control_values = hint_values(&div_hints(&control_compiled.program)); + assert!( + control_values + .iter() + .all(|hint| *hint != Some((ValueType::Float, ValueType::Float))), + "untyped control was specialized Float/Float: {control_values:?}" + ); + let control_status = control_status.unwrap_or_else(|error| panic!("control runtime {error:?}")); + assert_eq!(control_status, VmStatus::Halted); + assert_eq!(control_stack.last(), Some(&Value::Float(7.0))); + + let (compiled, status, stack) = compile_and_run(reused); + let hints = div_hints(&compiled.program); + let listing = disassemble_program(&compiled.program); + let values = hint_values(&hints); + assert_eq!( + values, control_values, + "expected generic untyped div hint {control_values:?}, got {hints:?}\n\ + guest={status:?}\nsource={reused}\nlocals={}\n{listing}", + compiled.locals + ); + assert!( + hints + .iter() + .all(|(_, hint)| *hint != Some((ValueType::Float, ValueType::Float))), + "stale Float/Float hint on untyped reuse: {hints:?}\n\ + guest={status:?}\nsource={reused}\nlocals={}\n{listing}", + compiled.locals + ); + let status = status.unwrap_or_else(|error| { + panic!( + "runtime {error:?}\nhints={hints:?}\nlocals={}\nsource={reused}\n{listing}", + compiled.locals + ) + }); + assert_eq!(status, VmStatus::Halted, "{listing}"); + assert_eq!(stack.last(), Some(&Value::Float(7.0)), "{listing}"); +} + +const NUMBER_LITERAL_CONTROL: &str = r#" + fn probe() -> float { + let n: number = 2; + n / 1.0 + } + probe(); +"#; + +fn assert_reused_number_matches_generic_control(source: &str) { + let (control_compiled, control_status, control_stack) = compile_and_run(NUMBER_LITERAL_CONTROL); + let control_values = hint_values(&div_hints(&control_compiled.program)); + assert!( + control_values + .iter() + .all(|hint| *hint != Some((ValueType::Int, ValueType::Float))), + "number control narrowed to Int/Float: {control_values:?}" + ); + let control_status = control_status.unwrap_or_else(|error| panic!("control runtime {error:?}")); + assert_eq!(control_status, VmStatus::Halted); + assert_eq!(control_stack.last(), Some(&Value::Float(2.0))); + + let (compiled, status, stack) = compile_and_run(source); + let hints = div_hints(&compiled.program); + let listing = disassemble_program(&compiled.program); + assert!( + compiled.locals > 8, + "physical reuse requires compaction, locals={}\nsource={source}\n{listing}", + compiled.locals + ); + let values = hint_values(&hints); + assert_eq!( + values, control_values, + "nested declared number was narrowed: got {hints:?}, no-reuse number hint {control_values:?}\n\ + guest={status:?}\nsource={source}\nlocals={}\n{listing}", + compiled.locals + ); + assert!( + hints + .iter() + .all(|(_, hint)| *hint != Some((ValueType::Int, ValueType::Float))), + "nested number declaration narrowed to Int/Float: {hints:?}\n\ + guest={status:?}\nsource={source}\nlocals={}\n{listing}", + compiled.locals + ); + let status = status.unwrap_or_else(|error| { + panic!( + "runtime {error:?}\nhints={hints:?}\nlocals={}\nsource={source}\n{listing}", + compiled.locals + ) + }); + assert_eq!(status, VmStatus::Halted, "{listing}"); + assert_eq!(stack.last(), Some(&Value::Float(2.0)), "{listing}"); +} + +/// Source form: if-expression branch, not a statement `if`. The branch is +/// `Expr::Block` nested in `Expr::IfElse`. A dead float reuses the number +/// binding's physical slot before the branch assigns `2`. +#[test] +fn reused_slot_if_expr_keeps_declared_number_div_hint() { + assert_reused_number_matches_generic_control( + r#" + fn probe() -> float { + let mut checked: number = 0; + let temporary: float = 1.5; + let sink = temporary + 0.0; + let pad0 = 1; + let pad1 = 2; + let pad2 = 3; + let pad3 = 4; + let pad4 = 5; + let pad5 = 6; + let pad6 = 7; + let out = if pad0 + pad1 + pad2 + pad3 + pad4 + pad5 + pad6 == 28 => { + checked = 2; + checked / 1.0 + } else => { + sink + }; + out + } + probe(); + "#, + ); +} + +/// Source form: Result match arm is an if-expression. The assignment is not a +/// direct ResultMatch child; the parser only accepts an expression arm. The +/// if-expression is reached only by entering ResultMatch. +#[test] +fn reused_slot_result_match_keeps_declared_number_div_hint() { + assert_reused_number_matches_generic_control( + r#" + fn probe() -> float { + let mut checked: number = 0; + let temporary: float = 1.5; + let sink = temporary + 0.0; + let pad0 = 1; + let pad1 = 2; + let pad2 = 3; + let pad3 = 4; + let pad4 = 5; + let pad5 = 6; + let flag: Result = Result::Ok(1); + let out = match flag { + Result::Ok(_) => if pad0 + pad1 + pad2 + pad3 + pad4 + pad5 == 21 => { + checked = 2; + checked / 1.0 + } else => { + sink + }, + Result::Err(_) => sink, + }; + out + } + probe(); + "#, + ); +} + +/// Source form: the if-expression is a call argument, not a let initializer. +/// Reaching the assignment requires entering `Expr::Call` args and then +/// `Expr::IfElse`. +#[test] +fn reused_slot_call_arg_keeps_declared_number_div_hint() { + assert_reused_number_matches_generic_control( + r#" + fn identity(value: float) -> float { + value + } + fn probe() -> float { + let mut checked: number = 0; + let temporary: float = 1.5; + let sink = temporary + 0.0; + let pad0 = 1; + let pad1 = 2; + let pad2 = 3; + let pad3 = 4; + let pad4 = 5; + let pad5 = 6; + let pad6 = 7; + let out = identity(if pad0 + pad1 + pad2 + pad3 + pad4 + pad5 + pad6 == 28 => { + checked = 2; + checked / 1.0 + } else => { + sink + }); + out + } + probe(); + "#, + ); +}