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": "c911b1180e0e4294a70c52a4c76e2ac0c587ec76",
"latest_relevant_committed_at_unix": 1795752408,
"pending_relevant_commit_count": 122,
"latest_relevant_commit": "f497d20c6c0cacb751ef9f7dcb23720b6a0eac0f",
"latest_relevant_committed_at_unix": 1795755771,
"pending_relevant_commit_count": 124,
"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-vm/src/EGM.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

## Invariants

- [byte_string.rs](./byte_string.rs) shares byte indexing, slicing, conversion and allocation bounds between VM instructions, native builtins and compiled embedders. Callers own value coercion and storage.
- [byte_string.rs](./byte_string.rs) shares byte indexing, slicing, conversion and allocation bounds between VM instructions, native builtins and compiled embedders. Callers own value coercion and storage. The VM splits into borrowed byte slices, admits the result array before reserving its storage, and accounts for new atoms while retaining the earlier pieces.

- [number/math.rs](./number/math.rs) supplies stateless standard math kernels to VM instructions, native builtins and compiled embedders. Callers handle arity, value coercion and stateful libraries.

Expand Down
40 changes: 25 additions & 15 deletions crates/rustia-vm/src/byte_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,20 +174,30 @@ pub fn repeat_string(text: &[u8], count: i64) -> Result<Vec<u8>> {
}

pub fn split_luau_string(text: &[u8], separator: &[u8]) -> Vec<Vec<u8>> {
if separator.is_empty() {
return text.iter().map(|byte| vec![*byte]).collect();
}
split_parts(text, separator).map(<[u8]>::to_vec).collect()
}

let mut parts = Vec::new();
let mut start = 0;
while let Some(offset) = text[start..]
.windows(separator.len())
.position(|window| window == separator)
{
let end = start + offset;
parts.push(text[start..end].to_vec());
start = end + separator.len();
}
parts.push(text[start..].to_vec());
parts
/// Borrow each piece, including trailing empty pieces for nonempty separators.
pub(crate) fn split_parts<'a>(
text: &'a [u8],
separator: &'a [u8],
) -> impl Iterator<Item = &'a [u8]> {
let mut remaining = Some(text);
std::iter::from_fn(move || {
let text = remaining.take()?;
if separator.is_empty() {
let (part, tail) = text.split_at_checked(1)?;
remaining = Some(tail);
return Some(part);
}
if let Some(end) = text
.windows(separator.len())
.position(|part| part == separator)
{
remaining = Some(&text[end + separator.len()..]);
Some(&text[..end])
} else {
Some(text)
}
})
}
8 changes: 6 additions & 2 deletions crates/rustia-vm/src/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1815,15 +1815,19 @@ impl VmCell {
}

pub fn alloc_array_table(&mut self, values: &[Value]) -> u32 {
self.try_alloc_array_table(values.to_vec())
.expect("table slot limit exceeded")
}

pub(crate) fn try_alloc_array_table(&mut self, values: Vec<Value>) -> Option<u32> {
self.insert_table_data(TableData {
array: values.to_vec(),
array: values,
hash: empty_hash_part(self.table_layout),
readonly: false,
metatable: None,
shape_version: 0,
mutation_version: 0,
})
.expect("table slot limit exceeded")
}

/// Allocates a PUC-layout table with pre-sized array and node parts,
Expand Down
168 changes: 146 additions & 22 deletions crates/rustia-vm/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub use scoped_host::VmHostCall;
use expanded_calls::{ExpandedCallFlow, ExpandedCallState};

use crate::byte_string::{
char_byte, luau_string_sub, repeat_string, reverse_string_bytes, split_luau_string,
char_byte, luau_string_sub, repeat_string, reverse_string_bytes, split_parts,
string_byte_slice, string_library_index, string_repeat_count, string_repeat_len,
};
#[cfg(test)]
Expand Down Expand Up @@ -3261,26 +3261,29 @@ impl Vm {
&mut self,
additional_live_bytes: usize,
transient_roots: &[Value],
) -> Result<()> {
self.ensure_planned_memory_growth(|_| additional_live_bytes, transient_roots)
}

fn ensure_planned_memory_growth(
&mut self,
additional_live_bytes: impl Fn(&mut Self) -> usize,
transient_roots: &[Value],
) -> Result<()> {
let Some(limit) = self.settings.memory_limit_bytes else {
return Ok(());
};
if self
.current_live_bytes()
.saturating_add(additional_live_bytes)
<= limit
{
return Ok(());
}
self.collect_for_memory_limit(transient_roots);
if self
.current_live_bytes()
.saturating_add(additional_live_bytes)
<= limit
{
return Ok(());
let fits = |vm: &mut Self| {
let additional = additional_live_bytes(vm);
vm.current_live_bytes().saturating_add(additional) <= limit
};
if !fits(self) {
self.collect_for_memory_limit(transient_roots);
if !fits(self) {
return Err(Error::new(ErrorKind::OutOfMemory).without_source_location());
}
}
Err(Error::new(ErrorKind::OutOfMemory).without_source_location())
Ok(())
}

pub fn register_extension_op(&mut self, op: ExtensionOp) -> Result<u16> {
Expand Down Expand Up @@ -19398,12 +19401,40 @@ impl Vm {
} else {
b",".to_vec()
};
let parts = split_luau_string(&text, &separator);
let values = parts
.iter()
.map(|part| self.heap.intern_string_value_bytes(part))
.collect::<Vec<_>>();
Ok(Value::table(self.heap.alloc_array_table(&values)))
let count = if separator.is_empty() {
text.len()
} else {
split_parts(&text, &separator).count()
};
let table_growth = VmCell::filled_array_table_live_bytes(count);
self.ensure_memory_growth(table_growth, &[])?;
let mut values = Vec::new();
values
.try_reserve_exact(count)
.map_err(|_| Error::new(ErrorKind::OutOfMemory).without_source_location())?;
for part in split_parts(&text, &separator) {
let value = if let Some(short) = Value::short_string(part) {
short
} else if let Some(atom) = self.heap.find_string_atom_bytes(part) {
Value::string_atom(atom)
} else {
// Account for the reserved result table alongside each new
// atom. Earlier parts remain rooted through quota collection.
self.ensure_planned_memory_growth(
|vm| {
table_growth
.saturating_add(vm.heap.planned_owned_string_live_bytes(part.len()))
},
&values,
)?;
self.heap.intern_string_value_bytes(part)
};
values.push(value);
}
self.heap
.try_alloc_array_table(values)
.map(Value::table)
.ok_or_else(|| Error::new(ErrorKind::OutOfMemory).without_source_location())
}

fn math_unary(
Expand Down Expand Up @@ -31605,6 +31636,99 @@ mod inline_cache_tests {
assert_eq!(vm.current_live_bytes(), before + growth);
}

#[test]
fn split_admits_the_result_array_and_new_atoms_together() {
let mut vm = Vm::new(Profile::ReproducibleStandard);
let text = vm.create_retained_string_bytes(&[b'x'; 200]).unwrap();
vm.collect_garbage();
let text_value = text.value(&vm).unwrap();
let baseline = vm.current_live_bytes();
let array_growth = VmCell::filled_array_table_live_bytes(200);
vm.settings.memory_limit_bytes = Some(baseline + array_growth - 1);
let empty = Value::short_string(b"").unwrap();
let failure = vm.native_string_split(&[text_value, empty]).unwrap_err();
assert!(matches!(failure.kind, ErrorKind::OutOfMemory));
assert_eq!(vm.current_live_bytes(), baseline);

vm.settings.memory_limit_bytes = Some(baseline + array_growth);
let array = vm.native_string_split(&[text_value, empty]).unwrap();
let last = vm.raw_table_get_value(array, Value::number(200.)).unwrap();
assert_eq!(vm.string_value_bytes(last).unwrap().unwrap(), b"x");

vm.settings.memory_limit_bytes = None;
let mut bytes = [b'v'; 205];
bytes[200..].copy_from_slice(b",tail");
let text = vm.create_retained_string_bytes(&bytes).unwrap();
vm.collect_garbage();
let text_value = text.value(&vm).unwrap();
let baseline = vm.current_live_bytes();
let atoms = vm.heap.string_atom_count();
let growth =
VmCell::filled_array_table_live_bytes(2) + vm.heap.planned_owned_string_live_bytes(200);
vm.settings.memory_limit_bytes = Some(baseline + growth - 1);
let failure = vm.native_string_split(&[text_value]).unwrap_err();
assert!(matches!(failure.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 table = vm.native_string_split(&[text_value]).unwrap();
let part = vm.raw_table_get_value(table, Value::number(1.)).unwrap();
assert_eq!(
vm.string_value_bytes(part).unwrap().unwrap(),
vec![b'v'; 200]
);
assert!(vm.current_live_bytes() <= baseline + growth);
}

#[test]
fn split_replans_atom_index_growth_after_quota_collection() {
const PART_LEN: usize = 65_536;
let mut vm = Vm::new(Profile::ReproducibleStandard);
let mut bytes = vec![b'v'; PART_LEN];
bytes.extend_from_slice(b",tail");
let text = vm.create_retained_string_bytes(&bytes).unwrap();
vm.collect_garbage();
let count = vm.heap.string_atom_count();
let mut roots = Vec::new();
for index in count..count.next_power_of_two() {
let key = format!("retained-split-test-atom-{index}");
roots.push(vm.create_retained_string_bytes(key.as_bytes()).unwrap());
}

let add_garbage = |vm: &mut Vm| {
vm.heap
.intern_string_bytes(b"unretained-split-test-atom-one");
vm.heap
.intern_string_bytes(b"unretained-split-test-atom-two");
};
add_garbage(&mut vm);
vm.collect_garbage();
let collected_live = vm.current_live_bytes();
let collected_growth = vm.heap.planned_owned_string_live_bytes(PART_LEN);
add_garbage(&mut vm);
let initial_live = vm.current_live_bytes();
let initial_growth = vm.heap.planned_owned_string_live_bytes(PART_LEN);
let table_growth = VmCell::filled_array_table_live_bytes(2);
let limit = collected_live + table_growth + collected_growth - 1;
assert!(initial_live + table_growth <= limit, "the table alone fits");
assert!(
initial_live + table_growth + initial_growth > limit,
"the atom admission triggers collection"
);
assert!(
collected_live + table_growth + initial_growth <= limit,
"reusing the old estimate would incorrectly admit the split"
);

vm.settings.memory_limit_bytes = Some(limit);
let value = text.value(&vm).unwrap();
let failure = vm.native_string_split(&[value]).unwrap_err();
assert!(matches!(failure.kind, ErrorKind::OutOfMemory));
assert_eq!(vm.current_live_bytes(), collected_live);
drop(roots);
}

#[test]
fn loaded_program_quota_admission_counts_tape_metadata_exactly() {
let mut planned_code = Vec::new();
Expand Down
2 changes: 1 addition & 1 deletion design/50-conformance.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ no portable contract outside its representable domain; see
| `string.rep(s,n)` — NO separator arg | specified (Luau) | Luau `str_rep` takes only `(s,n)`; n<=0→""; **ignores any 3rd arg** (Lua 5.4 `sep` is absent) | Match: 2-arg only, ignore extra args, no separator | both | DIVERGENCE from Lua 5.4 `rep(s,n,sep)`; code ported from 5.4 silently drops the separator |
| `string.reverse` | specified | Byte reversal | Exact | both | — |
| `string.lower` / `string.upper` | specified / locale-sensitive in C | Uses `tolower`/`toupper` per byte; in C locale = ASCII only (A-Z<->a-z) | ASCII-only case fold per byte | both | Must NOT use Unicode case folding; Luau is byte+C-locale = ASCII. Risk: Rust `to_ascii_lowercase` is correct, `to_lowercase` is wrong |
| `string.split(s, sep=",")` (Luau ext) | specified (Luau) | Splits on literal `sep` (default ","); returns array table incl trailing empty; empty sep → one entry per byte | Exact, incl empty-sep per-byte behavior | both | Luau-only function; pure-byte memcmp split |
| `string.split(s, sep=",")` (Luau ext) | specified (Luau) | Splits on literal `sep` (default ","); returns array table incl trailing empty; empty sep → one entry per byte | Exact, incl empty-sep per-byte behavior | both | Luau-only function; literal byte comparison and quota-admitted result array and new atoms |
| String method indexing `("x"):m()` | specified | String metatable `__index = string` library table | P1 implements direct string-library method lookup for implemented string natives; full metatable machinery remains a later parity item | both | Current behavior covers ordinary string method calls such as `err:sub(...)`; exact metatable shape is still pending. |
| Pattern class `%a` (isalpha) | specified, but ctype is C-locale | Matches `isalpha` (ASCII letters in C locale) | ASCII `[A-Za-z]` | both | Must hardcode ASCII ctype, not Unicode. Luau never setlocale → de-facto ASCII |
| `%d` (isdigit) | specified | `[0-9]` | `[0-9]` | both | — |
Expand Down
Loading