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
6 changes: 3 additions & 3 deletions bench/operations-status.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@
"measured_commit": "90bc2ae4c397f6e2bbb1af687cc8e30688010123",
"projected_measured_commit": "df240799de22ea8588865a7f594262053c2e92f1",
"measured_at_unix": 1792952860,
"latest_relevant_commit": "f497d20c6c0cacb751ef9f7dcb23720b6a0eac0f",
"latest_relevant_committed_at_unix": 1795755771,
"pending_relevant_commit_count": 124,
"latest_relevant_commit": "8f1ef82204c86c57d37b28add2031c43662a56e9",
"latest_relevant_committed_at_unix": 1795756946,
"pending_relevant_commit_count": 127,
"next_action": "Public progress history remains paused; private benchmark bridge comparisons do not add rows."
},
"landscape": {
Expand Down
2 changes: 1 addition & 1 deletion crates/rustia-compiler/src/EGM.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
- [compiled_call.rs](./compiled_call.rs) lowers a numeric closure with at most one numeric argument and one host-supplied capture to a backend-independent numeric expression tree. The generated Rust backend consumes that tree. The source byte and token limits apply before recursive parsing, and lowering checks that the closure actually reads or writes the declared capture. A closure may perform multiple straight-line writes to that capture and return one numeric value or no values. Bundle-based generation returns the frozen source and entry graph digests, compiler ABI, backend, and digest of the emitted Rust bytes.
- Preparing a numeric call compiles ordinary bytecode from the same admitted entry. Each instance roots an ordinary VM closure. An embedder can instead bind an existing closure by matching its numeric bytecode and keep its current capture. A host invocation can share its remaining fuel with the compiled call. At a healthy, idle boundary the VM counts the straight-line numeric instructions and advances its logical clock when the backend commits a result. A mismatched receipt, unsupported operand (including raw noncanonical NaNs), active transaction, or call that can exceed its fuel or memory allowance or cross a collection boundary uses the interpreter on that same closure.
- Stateless helpers with one numeric argument can use the same scalar lowering for a returned arithmetic expression. This backend also admits the standard `math.abs` operation; it has no setup, captures, or module resolver.
- [hosted_rust.rs](./hosted_rust.rs) lowers a wider checked Luau subset to Rust source against a caller-supplied value and operation adapter. It supports ordinary modules and isolated callbacks. The caller supplies admitted capture names and the available global set. Rustia applies the same builtin lookup rule as its interpreter compiler. The output depends on the adapter for values, calls, operators, captures and module resolution. Hosted loops emit an adapter checkpoint before each body, including empty bodies. An adapter can debit the VM invocation's shared fuel without claiming bytecode-equivalent instruction metering. Standalone modules can use an adapter-provided host namespace and builtin catalog to check direct declarations, literal imports and writable globals at compile time.
- [hosted_rust.rs](./hosted_rust.rs) lowers a wider checked Luau subset to Rust source against a caller-supplied value and operation adapter. It supports ordinary modules and isolated callbacks. The caller supplies admitted capture names and the available global set. Rustia applies the same builtin lookup rule as its interpreter compiler. The output depends on the adapter for values, calls, operators, captures and module resolution. Hosted numeric-for bounds and interpolation use the adapter for coercion and string operations, so rooted VM strings can stay in their owner. Hosted loops emit an adapter checkpoint before each body, including empty bodies. An adapter can debit the VM invocation's shared fuel without claiming bytecode-equivalent instruction metering. Standalone modules can use an adapter-provided host namespace and builtin catalog to check direct declarations, literal imports and writable globals at compile time.
- [compiled_host_call.rs](./compiled_host_call.rs) emits native/Wasm-portable Rust for a zero-argument callback with setup captures, text-literal calls or methods, and bounded branching. The embedding retains setup, handle resolution and host dispatch. Generated control flow does not charge interpreter instruction fuel.
- [callback_source.rs](./callback_source.rs) extracts an embedder-selected module callback or named factory export. It preserves source lines, reports candidate capture names and only nominates direct literal imports that are safe to analyze for specialization. Path resolution, backend selection, interpreted initialization and artifact publication remain caller decisions.
- Hosts can gate each syntactically supported setup capture by its namespace, member and exact literal argument bytes. The compiler validates the capture syntax and reports denied declarations with a source span.
Expand Down
60 changes: 55 additions & 5 deletions crates/rustia-compiler/src/hosted_rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ pub fn emit_module(
/// Lower a module or isolated callback to Rust against a caller-supplied
/// `compiled_runtime` adapter. Unsupported syntax returns a source diagnostic.
/// Selection, capture binding, VM state and execution remain caller-owned.
/// Each loop body begins with a call to the adapter's `Host::loop_checkpoint`.
/// Hosted loops use `Host::loop_checkpoint` and `Host::number`. Interpolation
/// uses `Host::interpolation_value` and the adapter's concatenation operator.
pub fn emit(
file: &str,
source: &[u8],
Expand Down Expand Up @@ -437,12 +438,25 @@ impl Emitter<'_> {
let variable = self.declare(variable);
let body = self.loop_body(body)?;
self.scopes.pop();
let bounds = if self.standalone {
format!(
"let mut current = ({start}).number()?;\n\
let limit = ({limit}).number()?;\n\
let step = ({step}).number()?;\n"
)
} else {
format!(
"let start_value = {start};\n\
let limit_value = {limit};\n\
let step_value = {step};\n\
let mut current = host.number(&start_value)?;\n\
let limit = host.number(&limit_value)?;\n\
let step = host.number(&step_value)?;\n"
)
};
writeln!(
output,
"{{\nlet mut current = ({start}).number()?;\n\
let limit = ({limit}).number()?;\n\
let step = ({step}).number()?;\n\
while if step > 0.0 {{ current <= limit }} else {{ current >= limit }} {{\n\
"{{\n{bounds}while if step > 0.0 {{ current <= limit }} else {{ current >= limit }} {{\n\
{checkpoint}let l{variable} = cell(Value::Number(current));\n\
let next = current + step;\n\
current = next;\n{body}}}\n}}"
Expand Down Expand Up @@ -675,6 +689,42 @@ impl Emitter<'_> {
Expr::InterpolatedString {
parts, expressions, ..
} => {
if !self.standalone {
let mut code = String::from("{ ");
let mut first = true;
for part in parts {
let part = match part {
rustia_parser::InterpolatedStringPart::Text(bytes) => {
if bytes.is_empty() {
continue;
}
format!("Value::from_bytes(vec!{bytes:?})")
}
rustia_parser::InterpolatedStringPart::Expr(index) => {
let value = self.expr(&expressions[*index])?;
format!(
"{{ let value = {value}; host.interpolation_value(value)? }}"
)
}
};
if first {
writeln!(code, "#[allow(unused_mut)] let mut text = {part};").unwrap();
first = false;
} else {
writeln!(
code,
"let part = {part}; text = host.binary(\"..\", text, part)?;"
)
.unwrap();
}
}
code.push_str(if first {
"Value::String(String::new()) }"
} else {
"text }"
});
return Ok(code);
}
let mut code = String::from("{ let mut text = Vec::<u8>::new();");
for part in parts {
match part {
Expand Down
35 changes: 35 additions & 0 deletions crates/rustia-compiler/tests/hosted_rust.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,41 @@
use rustia_compiler::hosted_rust::{emit, Options};
use std::collections::BTreeSet;

#[test]
fn hosted_numeric_loops_and_interpolation_use_adapter_values() {
use rustia_compiler::hosted_rust::emit_module;

let source = b"return function(v)
for i = v, v, v do return `prefix:{v}:suffix` end
end";
let hosted = emit(
"strings.luau",
source,
"entry",
Options {
captures: Some(&BTreeSet::new()),
supports_builtin: |_| false,
},
)
.unwrap();
assert_eq!(hosted.matches("host.number(&").count(), 3);
let evaluated_step = hosted.find("let step_value = ").unwrap();
let first_coercion = hosted.find("host.number(&start_value)?").unwrap();
assert!(evaluated_step < first_coercion);
assert_eq!(
hosted.matches("host.interpolation_value(value)?").count(),
1
);
assert_eq!(
hosted.matches("host.binary(\"..\", text, part)?").count(),
2
);

let standalone = emit_module("strings.luau", source, "entry", "adapter", None).unwrap();
assert_eq!(standalone.matches(".number()?").count(), 3);
assert!(standalone.contains("text.extend(adapter::string_bytes"));
}

#[test]
fn callback_captures_and_builtin_order_follow_lexical_scope() {
let captures = BTreeSet::from(["count"]);
Expand Down
17 changes: 13 additions & 4 deletions crates/rustia-vm/src/bytecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,12 +767,21 @@ impl ConstantStorage {

#[inline]
pub(crate) fn stable_bytes_hash(value: &[u8]) -> u64 {
stable_bytes_hash_parts([value])
}

#[inline]
pub(crate) fn stable_bytes_hash_parts<const N: usize>(parts: [&[u8]; N]) -> u64 {
let mut hash = 0xcbf2_9ce4_8422_2325_u64;
for byte in value {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
let mut len = 0_u64;
for part in parts {
len = len.wrapping_add(part.len() as u64);
for byte in part {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
}
mix_stable_hash(hash ^ value.len() as u64)
mix_stable_hash(hash ^ len)
}

#[inline]
Expand Down
19 changes: 17 additions & 2 deletions crates/rustia-vm/src/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use smallvec::SmallVec;
use std::collections::{BTreeMap, BTreeSet};
use std::mem::size_of;

use crate::bytecode::{stable_bytes_hash, SharedProgramString};
use crate::bytecode::{stable_bytes_hash, stable_bytes_hash_parts, SharedProgramString};
use crate::number::table_key_number_bits;
use crate::value::{ShortString, Value, ValueKind, SHORT_STRING_CAPACITY};

Expand Down Expand Up @@ -1777,6 +1777,12 @@ impl VmCell {
}
}

pub(crate) fn find_concatenated_string_atom(&self, lhs: &[u8], rhs: &[u8]) -> Option<u32> {
string_index_lookup_matching(&self.root, stable_bytes_hash_parts([lhs, rhs]), |bytes| {
bytes.strip_prefix(lhs) == Some(rhs)
})
}

#[inline]
pub(crate) fn string_atom_equals_bytes(&mut self, atom: u32, value: &[u8]) -> Option<bool> {
{
Expand Down Expand Up @@ -3409,6 +3415,15 @@ impl VmCell {

#[inline]
fn string_index_lookup(root: &RootData, value: &[u8], stable_hash: u64) -> Option<u32> {
string_index_lookup_matching(root, stable_hash, |bytes| bytes == value)
}

#[inline]
fn string_index_lookup_matching(
root: &RootData,
stable_hash: u64,
matches: impl Fn(&[u8]) -> bool,
) -> Option<u32> {
if root.string_index.is_empty() {
return None;
}
Expand All @@ -3426,7 +3441,7 @@ fn string_index_lookup(root: &RootData, value: &[u8], stable_hash: u64) -> Optio
indexed_value.is_some(),
"string index contains an invalid atom"
);
if indexed_value.is_some_and(|candidate| candidate.as_bytes() == value) {
if indexed_value.is_some_and(|candidate| matches(candidate.as_bytes())) {
return Some(atom);
}
position = (position + 1) & (root.string_index.len() - 1);
Expand Down
74 changes: 72 additions & 2 deletions crates/rustia-vm/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19351,8 +19351,10 @@ impl Vm {
let text = self.coerce_to_string(registers, instruction.b)?;
let count = string_repeat_count(get_number(registers, instruction.c)?)?;
let result_len = string_repeat_len(text.len(), count)?;
let growth = self.heap.planned_owned_string_live_bytes(result_len);
self.ensure_memory_growth(growth, &[])?;
self.ensure_planned_memory_growth(
|vm| vm.heap.planned_owned_string_live_bytes(result_len),
&[],
)?;
let output = repeat_string(&text, count)?;
Ok(self.heap.intern_string_value_bytes(&output))
}
Expand Down Expand Up @@ -31636,6 +31638,74 @@ mod inline_cache_tests {
assert_eq!(vm.current_live_bytes(), before + growth);
}

#[test]
fn concatenation_admits_the_result_before_interning() {
let mut vm = Vm::new(Profile::ReproducibleStandard);
let left = vm.create_retained_string_bytes(&[b'a'; 100]).unwrap();
let right = vm.create_retained_string_bytes(&[b'b'; 100]).unwrap();
let lhs = left.value(&vm).unwrap();
let rhs = right.value(&vm).unwrap();
vm.collect_garbage();
let baseline = vm.current_live_bytes();
let atoms = vm.heap.string_atom_count();
let growth = vm.heap.planned_owned_string_live_bytes(200);
let program = Program::new(Function::new(vec![], 0), vec![]);
let concat = |vm: &mut Vm| -> Result<Value> {
let mut state = vm.begin_execution();
let mut execution = Execution {
state: &mut state,
hosts: &mut RejectHostDispatcher,
};
let step = vm.concat_operands_step(&program, lhs, rhs, 0, &mut execution)?;
vm.finish_implicit_step(step, &mut execution, first_result_or_nil)
};

vm.settings.memory_limit_bytes = Some(baseline + growth - 1);
assert!(matches!(
concat(&mut vm).unwrap_err().kind,
ErrorKind::OutOfMemory
));
assert_eq!(vm.heap.string_atom_count(), atoms);
assert_eq!(vm.current_live_bytes(), baseline);

vm.settings.memory_limit_bytes = Some(baseline + growth);
let result = concat(&mut vm).unwrap();
let expected: Vec<_> = [b'a'; 100].into_iter().chain([b'b'; 100]).collect();
assert_eq!(vm.string_value_bytes(result).unwrap().unwrap(), expected);

vm.settings.memory_limit_bytes = None;
let result = vm.retain_value(result).unwrap();
vm.settings.memory_limit_bytes = Some(vm.current_live_bytes());
assert_eq!(
concat(&mut vm).unwrap().as_string_atom(),
result.value(&vm).unwrap().as_string_atom()
);
}

#[test]
fn quota_limited_concat_preserves_inline_string_representation() {
let mut vm = Vm::new(Profile::ReproducibleStandard);
let atom = vm.heap.intern_string_bytes(b"ab");
let _atom_root = vm.retain_value(Value::string_atom(atom)).unwrap();
vm.settings.memory_limit_bytes = Some(vm.current_live_bytes());

let lhs = Value::short_string(b"a").unwrap();
let rhs = Value::short_string(b"b").unwrap();
let program = Program::new(Function::new(vec![], 0), vec![]);
let mut state = vm.begin_execution();
let mut execution = Execution {
state: &mut state,
hosts: &mut RejectHostDispatcher,
};
let step = vm
.concat_operands_step(&program, lhs, rhs, 0, &mut execution)
.unwrap();
let result = vm
.finish_implicit_step(step, &mut execution, first_result_or_nil)
.unwrap();
assert_eq!(result.as_short_string().unwrap().as_bytes(), b"ab");
}

#[test]
fn split_admits_the_result_array_and_new_atoms_together() {
let mut vm = Vm::new(Profile::ReproducibleStandard);
Expand Down
2 changes: 1 addition & 1 deletion crates/rustia-vm/src/vm/EGM.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ This private module directory separates specialized VM call paths and host integ
- [import_continuations.rs](./import_continuations.rs): validates/copies the bounded import descriptor and resumes the next lane after an implicit lookup. Expanded-call resume variants retain already evaluated arguments and method keys, so late lookup never replays argument evaluation, receiver selection or fuel charges.
- Generalized `__iter` preparation saves its pending instruction and resumes the returned iterator/state/control triple once. The setup metamethod retains its non-yieldable boundary; the actual iterator step keeps the existing coroutine continuation. Borrowed stateless entry calls do not install a loaded program.
- Transferred errors regain the saved triggering instruction/source before protected unwinding, matching synchronous opcode errors without replacing an existing location or explicit suppression.
- [implicit_operations.rs](./implicit_operations.rs) and [implicit_operators.rs](./implicit_operators.rs): shared direct/callback resolution for indexed/global reads and writes, method lookup, equality, arithmetic, ordering, concatenation and length. Bytecode saves first/discard/truthy/method-validation completion without repeating lookup or effects. Original cache paths remain shared with synchronous native users.
- [implicit_operations.rs](./implicit_operations.rs) and [implicit_operators.rs](./implicit_operators.rs): shared direct/callback resolution for indexed/global reads and writes, method lookup, equality, arithmetic, ordering, concatenation and length. Bytecode saves first/discard/truthy/method-validation completion without repeating lookup or effects. Primitive concatenation admits result storage with both operands rooted through quota collection. Original cache paths remain shared with synchronous native users.
- [native_continuations.rs](./native_continuations.rs): isolated saved-completion prototype for function-based gsub replacements, tostring metamethod results and foreach/foreachi iteration cursors; the existing driver owns their roots, program references, fallible snapshots and control-memory accounting. Foreach retains its selected key and snapshotted array length, reads later values after each callback, and stops on the first non-nil result. [native_completion_tests.rs](./native_completion_tests.rs) covers borrowed stateless entries, callback depth precedence and native-service quota admission.
- [host_functions.rs](./host_functions.rs): dispatch to facade-owned typed host callbacks.
- [scoped_host.rs](./scoped_host.rs): borrowed low-level callback execution scope;
Expand Down
Loading
Loading