From a4e0b396c68e7d7d8db2501523b5e057ef617ff1 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 03:53:54 +0800 Subject: [PATCH 001/225] feat(lua): parse locked LuaJIT 5.2-compat syntax Add a private lexer, parser and resolver for pinned LuaJIT 96f7b297 with LUAJIT_ENABLE_LUA52COMPAT. The production .lua entry is unchanged; accept/reject is checked with load(..., "t"). --- src/frontends/lua/ast.rs | 407 +++++++ src/frontends/lua/lexer.rs | 1085 +++++++++++++++++ src/frontends/lua/mod.rs | 12 + src/frontends/lua/parser.rs | 992 +++++++++++++++ src/frontends/lua/resolve.rs | 774 ++++++++++++ .../compiler/compiler_luajit_oracle_tests.rs | 630 ++++++++++ tests/compiler_tests.rs | 3 + 7 files changed, 3903 insertions(+) create mode 100644 src/frontends/lua/ast.rs create mode 100644 src/frontends/lua/lexer.rs create mode 100644 src/frontends/lua/parser.rs create mode 100644 src/frontends/lua/resolve.rs create mode 100644 tests/compiler/compiler_luajit_oracle_tests.rs diff --git a/src/frontends/lua/ast.rs b/src/frontends/lua/ast.rs new file mode 100644 index 0000000..bd999e8 --- /dev/null +++ b/src/frontends/lua/ast.rs @@ -0,0 +1,407 @@ +//! Locked LuaJIT 2.1 Lua 5.2-compat syntax types. +//! +//! Spans are byte offsets into the original source, including a leading BOM +//! when one is present. Names and string values keep raw bytes so a non-UTF-8 +//! identifier or `\xFF` literal is representable. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Span { + pub start: u32, + pub end: u32, +} + +impl Span { + pub fn new(start: usize, end: usize) -> Self { + Self { + start: u32::try_from(start).unwrap_or(u32::MAX), + end: u32::try_from(end).unwrap_or(u32::MAX), + } + } + + pub fn cover(self, other: Self) -> Self { + Self { + start: self.start.min(other.start), + end: self.end.max(other.end), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Name { + pub span: Span, + pub bytes: Vec, +} + +impl Name { + pub fn is(&self, text: &str) -> bool { + self.bytes == text.as_bytes() + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Chunk { + pub span: Span, + pub has_bom: bool, + pub body: Block, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Block { + pub span: Span, + pub stmts: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IfArm { + pub cond: Expr, + pub body: Block, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LocalName { + pub name: Name, + pub const_binding: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Stmt { + Empty { + span: Span, + }, + Do { + span: Span, + body: Block, + }, + While { + span: Span, + cond: Expr, + body: Block, + }, + Repeat { + span: Span, + body: Block, + until: Expr, + }, + If { + span: Span, + arms: Vec, + else_body: Option, + }, + NumericFor { + span: Span, + name: Name, + start: Expr, + limit: Expr, + step: Option, + body: Block, + }, + GenericFor { + span: Span, + names: Vec, + iters: ExprList, + body: Block, + }, + Local { + span: Span, + names: Vec, + values: ExprList, + }, + LocalFunction { + span: Span, + name: Name, + const_binding: bool, + func: FuncBody, + }, + Function { + span: Span, + name: FuncName, + body: FuncBody, + }, + Assign { + span: Span, + targets: Vec, + values: ExprList, + }, + CompoundAssign { + span: Span, + target: AssignTarget, + op: BinOp, + value: Expr, + }, + Call { + span: Span, + call: Expr, + }, + Label { + span: Span, + name: Name, + }, + Goto { + span: Span, + name: Name, + }, + Break { + span: Span, + }, + Continue { + span: Span, + }, + Return { + span: Span, + values: ExprList, + }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FuncName { + pub span: Span, + pub segments: Vec, + pub method: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FuncBody { + pub span: Span, + pub params: Vec, + pub vararg: bool, + pub self_param: bool, + pub body: Block, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ShortBody { + Expr(Box), + Block(Block), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExprList { + pub span: Span, + pub exprs: Vec, +} + +impl ExprList { + pub fn empty(span: Span) -> Self { + Self { + span, + exprs: Vec::new(), + } + } + + pub fn tail_multi(&self) -> bool { + self.exprs.last().is_some_and(Expr::is_multi) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AssignTarget { + Name(Name), + Index { + span: Span, + table: Box, + key: Box, + nav: bool, + }, + Field { + span: Span, + table: Box, + name: Name, + nav: bool, + }, +} + +impl AssignTarget { + pub fn span(&self) -> Span { + match self { + Self::Name(name) => name.span, + Self::Index { span, .. } | Self::Field { span, .. } => *span, + } + } + + pub fn has_nav(&self) -> bool { + match self { + Self::Name(_) => false, + Self::Index { nav, .. } | Self::Field { nav, .. } => *nav, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NumberKind { + Integer, + Float, + HexInteger, + HexFloat, + Binary, + Signed64, + Unsigned64, + Imaginary, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnOp { + Neg, + Not, + Len, + BNot, + Bang, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BinOp { + Add, + Sub, + Mul, + Div, + Mod, + Pow, + Band, + Bor, + BXor, + Shl, + Shr, + Sar, + Concat, + Eq, + Ne, + Lt, + Gt, + Le, + Ge, + And, + Or, + Coal, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Args { + List(ExprList), + String { span: Span, bytes: Vec }, + Table { span: Span, fields: Vec }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Field { + Index { span: Span, key: Expr, value: Expr }, + Name { span: Span, name: Name, value: Expr }, + Item { span: Span, value: Expr }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Expr { + Nil { + span: Span, + }, + Bool { + span: Span, + value: bool, + }, + Number { + span: Span, + raw: String, + kind: NumberKind, + }, + String { + span: Span, + bytes: Vec, + }, + Vararg { + span: Span, + }, + Name { + span: Span, + name: Name, + }, + Paren { + span: Span, + inner: Box, + }, + Unary { + span: Span, + op: UnOp, + expr: Box, + }, + Binary { + span: Span, + op: BinOp, + left: Box, + right: Box, + }, + Ternary { + span: Span, + cond: Box, + then_expr: Box, + else_expr: Box, + }, + Call { + span: Span, + callee: Box, + args: Args, + nav: bool, + }, + MethodCall { + span: Span, + receiver: Box, + method: Name, + args: Args, + receiver_nav: bool, + method_nav: bool, + }, + Index { + span: Span, + table: Box, + key: Box, + nav: bool, + }, + Field { + span: Span, + table: Box, + name: Name, + nav: bool, + }, + Function { + span: Span, + body: FuncBody, + }, + ShortFunction { + span: Span, + params: Vec, + vararg: bool, + body: Box, + }, + Table { + span: Span, + fields: Vec, + }, +} + +impl Expr { + pub fn span(&self) -> Span { + match self { + Self::Nil { span } + | Self::Bool { span, .. } + | Self::Number { span, .. } + | Self::String { span, .. } + | Self::Vararg { span } + | Self::Name { span, .. } + | Self::Paren { span, .. } + | Self::Unary { span, .. } + | Self::Binary { span, .. } + | Self::Ternary { span, .. } + | Self::Call { span, .. } + | Self::MethodCall { span, .. } + | Self::Index { span, .. } + | Self::Field { span, .. } + | Self::Function { span, .. } + | Self::ShortFunction { span, .. } + | Self::Table { span, .. } => *span, + } + } + + pub fn is_multi(&self) -> bool { + matches!( + self, + Self::Call { .. } | Self::MethodCall { .. } | Self::Vararg { .. } + ) + } +} diff --git a/src/frontends/lua/lexer.rs b/src/frontends/lua/lexer.rs new file mode 100644 index 0000000..36a4c24 --- /dev/null +++ b/src/frontends/lua/lexer.rs @@ -0,0 +1,1085 @@ +//! Scanner for the locked LuaJIT 2.1 Lua 5.2-compat text grammar. +//! +//! Character classes match `lj_char.c`: ASCII letters, digits, `_`, and every +//! byte >= 128 are identifier characters. A leading BOM is recorded and +//! skipped. Line directives and shebangs are consumed here so the parser sees +//! only tokens. + +use super::ast::{NumberKind, Span}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxError { + pub span: Span, + pub line: u32, + pub message: String, +} + +impl SyntaxError { + pub fn at(span: Span, line: u32, message: impl Into) -> Self { + Self { + span, + line, + message: message.into(), + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Tok { + Eof, + Name, + String, + Number, + Dots, + Concat, + Eq, + Ne, + NeBang, + Le, + Ge, + Shl, + Shr, + Sar, + AndAnd, + OrOr, + Coal, + Nav, + Arrow, + Label, + And, + Break, + Do, + Else, + Elseif, + End, + False, + For, + Function, + Goto, + If, + In, + Local, + Nil, + Not, + Or, + Repeat, + Return, + Then, + True, + Until, + While, + Const, + Continue, + Char(u8), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Token { + pub kind: Tok, + pub span: Span, + pub line: u32, + pub text: Vec, + pub number_kind: Option, +} + +pub struct Lexed { + pub tokens: Vec, + pub has_bom: bool, +} + +struct Scan<'a> { + src: &'a [u8], + pos: usize, + line: u32, + has_bom: bool, +} + +pub fn lex(source: &[u8]) -> Result { + let mut scan = Scan { + src: source, + pos: 0, + line: 1, + has_bom: false, + }; + if source.starts_with(&[0xef, 0xbb, 0xbf]) { + scan.pos = 3; + scan.has_bom = true; + } + let mut tokens = Vec::new(); + if scan.cur() == Some(b'#') { + if scan.peek() == Some(b'!') { + scan.skip_shebang()?; + } else { + // A leading '#' that is not '#!' is a line directive, as if a + // newline had just been consumed. Do not consume the '#" here. + scan.line = 1; + let hash = scan.pos; + if !scan.line_directive()? { + tokens.push(scan.token(Tok::Char(b'#'), hash, hash + 1, Vec::new(), None)); + } + } + } + while scan.cur().is_some() { + if let Some(token) = scan.next_token()? { + let done = token.kind == Tok::Eof; + tokens.push(token); + if done { + break; + } + } + } + if tokens.last().is_none_or(|token| token.kind != Tok::Eof) { + let end = u32::try_from(source.len()).unwrap_or(u32::MAX); + tokens.push(Token { + kind: Tok::Eof, + span: Span { start: end, end }, + line: scan.line, + text: Vec::new(), + number_kind: None, + }); + } + Ok(Lexed { + tokens, + has_bom: scan.has_bom, + }) +} + +impl<'a> Scan<'a> { + fn cur(&self) -> Option { + self.src.get(self.pos).copied() + } + + fn peek(&self) -> Option { + self.src.get(self.pos + 1).copied() + } + + fn advance(&mut self) -> Option { + let cur = self.cur(); + if self.pos < self.src.len() { + self.pos += 1; + } + cur + } + + fn token( + &self, + kind: Tok, + start: usize, + end: usize, + text: Vec, + number_kind: Option, + ) -> Token { + Token { + kind, + span: Span::new(start, end), + line: self.line, + text, + number_kind, + } + } + + fn err(&self, start: usize, message: impl Into) -> SyntaxError { + SyntaxError::at(Span::new(start, self.pos), self.line, message) + } + + fn is_eol(c: u8) -> bool { + c == b'\n' || c == b'\r' + } + + fn finish_newline(&mut self) { + let old = self.cur(); + self.advance(); + if let Some(next) = self.cur() { + if Self::is_eol(next) && Some(next) != old { + self.advance(); + } + } + self.line = self.line.saturating_add(1); + } + + fn skip_shebang(&mut self) -> Result<(), SyntaxError> { + while let Some(c) = self.cur() { + if Self::is_eol(c) { + self.finish_newline(); + return Ok(()); + } + self.advance(); + } + Ok(()) + } + + fn line_directive(&mut self) -> Result { + let start = self.pos; + if self.cur() != Some(b'#') { + return Ok(false); + } + self.advance(); + while matches!(self.cur(), Some(b' ' | b'\t')) { + self.advance(); + } + let Some(c) = self.cur() else { + return Ok(false); + }; + if !c.is_ascii_digit() { + return Ok(false); + } + let mut line: u32 = u32::from(c - b'0'); + self.advance(); + while let Some(digit) = self.cur() { + if !digit.is_ascii_digit() { + break; + } + if line >= (i32::MAX as u32 - 9) / 10 { + return Err(self.err(start, "malformed line number directive")); + } + line = line * 10 + u32::from(digit - b'0'); + self.advance(); + } + while matches!(self.cur(), Some(b' ' | b'\t')) { + self.advance(); + } + if self.cur() == Some(b'"') { + let before = self.line; + self.advance(); + self.short_string(b'"', start)?; + if self.line != before { + return Err(self.err(start, "malformed line number directive")); + } + while matches!(self.cur(), Some(b' ' | b'\t')) { + self.advance(); + } + } + match self.cur() { + Some(c) if Self::is_eol(c) => self.finish_newline(), + None => {} + _ => return Err(self.err(start, "malformed line number directive")), + } + self.line = line; + Ok(true) + } + + fn next_token(&mut self) -> Result, SyntaxError> { + loop { + let Some(c) = self.cur() else { + return Ok(Some(self.token( + Tok::Eof, + self.pos, + self.pos, + Vec::new(), + None, + ))); + }; + if is_ident(c) { + if c.is_ascii_digit() { + return Ok(Some(self.number(self.pos, false)?)); + } + return Ok(Some(self.name_or_keyword())); + } + let start = self.pos; + match c { + b'\n' | b'\r' => { + self.finish_newline(); + while self.cur() == Some(b'#') { + let hash = self.pos; + if !self.line_directive()? { + return Ok(Some(self.token( + Tok::Char(b'#'), + hash, + hash + 1, + Vec::new(), + None, + ))); + } + } + } + b' ' | b'\t' | 0x0b | 0x0c => { + self.advance(); + } + b'-' => { + self.advance(); + if self.cur() == Some(b'>') { + self.advance(); + return Ok(Some(self.token( + Tok::Arrow, + start, + self.pos, + Vec::new(), + None, + ))); + } + if self.cur() != Some(b'-') { + return Ok(Some(self.token( + Tok::Char(b'-'), + start, + self.pos, + Vec::new(), + None, + ))); + } + self.advance(); + if self.cur() == Some(b'[') { + let sep = self.skip_eq(b'[')?; + if sep >= 0 { + self.long_string(sep, false)?; + continue; + } + } + while let Some(ch) = self.cur() { + if Self::is_eol(ch) { + break; + } + self.advance(); + } + } + b'[' => { + let sep = self.skip_eq(b'[')?; + if sep >= 0 { + let bytes = self.long_string(sep, true)?; + return Ok(Some(self.token(Tok::String, start, self.pos, bytes, None))); + } else if sep == -1 { + return Ok(Some(self.token( + Tok::Char(b'['), + start, + self.pos, + Vec::new(), + None, + ))); + } else { + return Err(self.err(start, "invalid long string delimiter")); + } + } + b'=' => { + self.advance(); + if self.cur() == Some(b'=') { + self.advance(); + return Ok(Some(self.token(Tok::Eq, start, self.pos, Vec::new(), None))); + } + return Ok(Some(self.token( + Tok::Char(b'='), + start, + self.pos, + Vec::new(), + None, + ))); + } + b'<' => { + self.advance(); + if self.cur() == Some(b'=') { + self.advance(); + return Ok(Some(self.token(Tok::Le, start, self.pos, Vec::new(), None))); + } + if self.cur() == Some(b'<') { + self.advance(); + return Ok(Some(self.token( + Tok::Shl, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Char(b'<'), + start, + self.pos, + Vec::new(), + None, + ))); + } + b'>' => { + self.advance(); + if self.cur() == Some(b'=') { + self.advance(); + return Ok(Some(self.token(Tok::Ge, start, self.pos, Vec::new(), None))); + } + if self.cur() == Some(b'>') { + self.advance(); + return Ok(Some(self.token( + Tok::Shr, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Char(b'>'), + start, + self.pos, + Vec::new(), + None, + ))); + } + b'~' => { + self.advance(); + if self.cur() == Some(b'=') { + self.advance(); + return Ok(Some(self.token(Tok::Ne, start, self.pos, Vec::new(), None))); + } + if self.cur() == Some(b'>') { + self.advance(); + if self.cur() != Some(b'>') { + return Err(self.err(start, "invalid symbol")); + } + self.advance(); + return Ok(Some(self.token( + Tok::Sar, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Char(b'~'), + start, + self.pos, + Vec::new(), + None, + ))); + } + b'!' => { + self.advance(); + if self.cur() == Some(b'=') { + self.advance(); + return Ok(Some(self.token( + Tok::NeBang, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Char(b'!'), + start, + self.pos, + Vec::new(), + None, + ))); + } + b':' => { + self.advance(); + if self.cur() == Some(b':') { + self.advance(); + return Ok(Some(self.token( + Tok::Label, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Char(b':'), + start, + self.pos, + Vec::new(), + None, + ))); + } + b'?' => { + self.advance(); + if self.cur() == Some(b'.') { + self.advance(); + return Ok(Some(self.token( + Tok::Nav, + start, + self.pos, + Vec::new(), + None, + ))); + } + if self.cur() == Some(b'?') { + self.advance(); + return Ok(Some(self.token( + Tok::Coal, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Char(b'?'), + start, + self.pos, + Vec::new(), + None, + ))); + } + b'&' => { + self.advance(); + if self.cur() == Some(b'&') { + self.advance(); + return Ok(Some(self.token( + Tok::AndAnd, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Char(b'&'), + start, + self.pos, + Vec::new(), + None, + ))); + } + b'|' => { + self.advance(); + if self.cur() == Some(b'|') { + self.advance(); + return Ok(Some(self.token( + Tok::OrOr, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Char(b'|'), + start, + self.pos, + Vec::new(), + None, + ))); + } + b'"' | b'\'' => { + let delim = c; + self.advance(); + let bytes = self.short_string(delim, start)?; + return Ok(Some(self.token(Tok::String, start, self.pos, bytes, None))); + } + b'.' => { + self.advance(); + if self.cur() == Some(b'.') { + self.advance(); + if self.cur() == Some(b'.') { + self.advance(); + return Ok(Some(self.token( + Tok::Dots, + start, + self.pos, + Vec::new(), + None, + ))); + } + return Ok(Some(self.token( + Tok::Concat, + start, + self.pos, + Vec::new(), + None, + ))); + } + if self.cur().is_some_and(|ch| ch.is_ascii_digit()) { + return Ok(Some(self.number(start, true)?)); + } + return Ok(Some(self.token( + Tok::Char(b'.'), + start, + self.pos, + Vec::new(), + None, + ))); + } + _ => { + self.advance(); + return Ok(Some(self.token( + Tok::Char(c), + start, + self.pos, + Vec::new(), + None, + ))); + } + } + } + } + + fn name_or_keyword(&mut self) -> Token { + let start = self.pos; + let mut text = Vec::new(); + while let Some(c) = self.cur() { + if !is_ident(c) { + break; + } + text.push(c); + self.advance(); + } + let kind = keyword(&text).unwrap_or(Tok::Name); + self.token(kind, start, self.pos, text, None) + } + + fn number(&mut self, start: usize, started_with_dot: bool) -> Result { + let mut raw = Vec::new(); + if started_with_dot { + raw.push(b'.'); + } + let mut xp = b'e'; + let mut last = if started_with_dot { + b'.' + } else { + self.cur().unwrap_or(b'0') + }; + if !started_with_dot { + let c = self.advance().unwrap_or(b'0'); + raw.push(c); + last = c; + if c == b'0' { + while self.cur() == Some(b'_') { + self.advance(); + } + if self.cur().is_some_and(|ch| ch | 0x20 == b'x') { + xp = b'p'; + } + } + } + while let Some(c) = self.cur() { + let exp_sign = (c == b'-' || c == b'+') && (last | 0x20) == xp; + if is_ident(c) || c == b'.' || exp_sign { + if c != b'_' { + raw.push(c); + last = c; + } + self.advance(); + } else { + break; + } + } + let kind = classify_number(&raw).map_err(|_| self.err(start, "malformed number"))?; + let text = String::from_utf8(raw).unwrap_or_default().into_bytes(); + Ok(self.token(Tok::Number, start, self.pos, text, Some(kind))) + } + + fn skip_eq(&mut self, open: u8) -> Result { + let start = self.pos; + if self.cur() != Some(open) { + return Err(self.err(start, "invalid long bracket")); + } + self.advance(); + let mut count = 0i32; + while self.cur() == Some(b'=') && count < 0x2000_0000 { + count += 1; + self.advance(); + } + if self.cur() == Some(open) { + Ok(count) + } else { + Ok(-count - 1) + } + } + + fn long_string(&mut self, sep: i32, keep: bool) -> Result, SyntaxError> { + let start = self.pos; + self.advance(); + if self.cur().is_some_and(Self::is_eol) { + self.finish_newline(); + } + let mut bytes = Vec::new(); + loop { + let Some(c) = self.cur() else { + return Err(self.err( + start, + if keep { + "unfinished long string" + } else { + "unfinished long comment" + }, + )); + }; + if c == b']' { + let saved = self.pos; + let close = self.skip_eq(b']')?; + if close == sep { + self.advance(); + return Ok(bytes); + } + if keep { + bytes.extend_from_slice(&self.src[saved..self.pos]); + } + continue; + } + if Self::is_eol(c) { + if keep { + bytes.push(b'\n'); + } + self.finish_newline(); + continue; + } + if keep { + bytes.push(c); + } + self.advance(); + } + } + + fn short_string(&mut self, delim: u8, start: usize) -> Result, SyntaxError> { + let mut bytes = Vec::new(); + loop { + let Some(c) = self.cur() else { + return Err(self.err(start, "unfinished string")); + }; + if c == delim { + self.advance(); + return Ok(bytes); + } + match c { + b'\n' | b'\r' => return Err(self.err(start, "unfinished string")), + b'\\' => { + self.advance(); + let Some(esc) = self.cur() else { + return Err(self.err(start, "unfinished string")); + }; + match esc { + b'a' => { + bytes.push(0x07); + self.advance(); + } + b'b' => { + bytes.push(0x08); + self.advance(); + } + b'f' => { + bytes.push(0x0c); + self.advance(); + } + b'n' => { + bytes.push(b'\n'); + self.advance(); + } + b'r' => { + bytes.push(b'\r'); + self.advance(); + } + b't' => { + bytes.push(b'\t'); + self.advance(); + } + b'v' => { + bytes.push(0x0b); + self.advance(); + } + b'x' => bytes.push(self.hex_escape(start)?), + b'u' => self.unicode_escape(start, &mut bytes)?, + b'z' => { + self.advance(); + while let Some(ch) = self.cur() { + if !is_space(ch) { + break; + } + if Self::is_eol(ch) { + self.finish_newline(); + } else { + self.advance(); + } + } + } + b'\n' | b'\r' => { + bytes.push(b'\n'); + self.finish_newline(); + } + b'\\' | b'"' | b'\'' => { + bytes.push(esc); + self.advance(); + } + digit if digit.is_ascii_digit() => { + bytes.push(self.decimal_escape(start, digit)?); + } + _ => return Err(self.err(start, "invalid escape")), + } + } + _ => { + bytes.push(c); + self.advance(); + } + } + } + } + + fn hex_escape(&mut self, start: usize) -> Result { + self.advance(); + let hi = self.hex_digit(start)?; + self.advance(); + let lo = self.hex_digit(start)?; + self.advance(); + Ok((hi << 4) | lo) + } + + fn hex_digit(&self, start: usize) -> Result { + match self.cur() { + Some(c) if c.is_ascii_digit() => Ok(c - b'0'), + Some(c) if (b'a'..=b'f').contains(&c) => Ok(c - b'a' + 10), + Some(c) if (b'A'..=b'F').contains(&c) => Ok(c - b'A' + 10), + _ => Err(self.err(start, "invalid escape")), + } + } + + fn unicode_escape(&mut self, start: usize, bytes: &mut Vec) -> Result<(), SyntaxError> { + self.advance(); + if self.cur() != Some(b'{') { + return Err(self.err(start, "invalid escape")); + } + self.advance(); + let mut code: u32 = 0; + let mut digits = 0u32; + loop { + let Some(c) = self.cur() else { + return Err(self.err(start, "invalid escape")); + }; + if c == b'}' { + if digits == 0 { + return Err(self.err(start, "invalid escape")); + } + break; + } + let digit = self.hex_digit(start)?; + code = (code << 4) | u32::from(digit); + if code >= 0x110000 { + return Err(self.err(start, "invalid escape")); + } + digits += 1; + self.advance(); + } + self.advance(); + if (0xd800..0xe000).contains(&code) { + return Err(self.err(start, "invalid escape")); + } + if code < 0x80 { + bytes.push(code as u8); + } else if code < 0x800 { + bytes.push(0xc0 | (code >> 6) as u8); + bytes.push(0x80 | (code & 0x3f) as u8); + } else if code < 0x10000 { + bytes.push(0xe0 | (code >> 12) as u8); + bytes.push(0x80 | ((code >> 6) & 0x3f) as u8); + bytes.push(0x80 | (code & 0x3f) as u8); + } else { + bytes.push(0xf0 | (code >> 18) as u8); + bytes.push(0x80 | ((code >> 12) & 0x3f) as u8); + bytes.push(0x80 | ((code >> 6) & 0x3f) as u8); + bytes.push(0x80 | (code & 0x3f) as u8); + } + Ok(()) + } + + fn decimal_escape(&mut self, start: usize, first: u8) -> Result { + let mut value = u32::from(first - b'0'); + self.advance(); + if self.cur().is_some_and(|c| c.is_ascii_digit()) { + value = value * 10 + u32::from(self.cur().unwrap() - b'0'); + self.advance(); + if self.cur().is_some_and(|c| c.is_ascii_digit()) { + value = value * 10 + u32::from(self.cur().unwrap() - b'0'); + if value > 255 { + return Err(self.err(start, "invalid escape")); + } + self.advance(); + } + } + Ok(value as u8) + } +} + +fn is_ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || c == b'_' || c >= 128 +} + +fn is_space(c: u8) -> bool { + matches!(c, b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c) +} + +fn keyword(text: &[u8]) -> Option { + Some(match text { + b"and" => Tok::And, + b"break" => Tok::Break, + b"do" => Tok::Do, + b"else" => Tok::Else, + b"elseif" => Tok::Elseif, + b"end" => Tok::End, + b"false" => Tok::False, + b"for" => Tok::For, + b"function" => Tok::Function, + b"goto" => Tok::Goto, + b"if" => Tok::If, + b"in" => Tok::In, + b"local" => Tok::Local, + b"nil" => Tok::Nil, + b"not" => Tok::Not, + b"or" => Tok::Or, + b"repeat" => Tok::Repeat, + b"return" => Tok::Return, + b"then" => Tok::Then, + b"true" => Tok::True, + b"until" => Tok::Until, + b"while" => Tok::While, + b"const" => Tok::Const, + b"continue" => Tok::Continue, + _ => return None, + }) +} + +fn classify_number(raw: &[u8]) -> Result { + if raw.is_empty() { + return Err(()); + } + let mut p = 0usize; + let mut base = 10u32; + if raw[0] == b'0' && raw.len() > 1 { + let mark = raw[1] | 0x20; + if mark == b'x' { + base = 16; + p = 2; + } else if mark == b'b' { + base = 2; + p = 2; + } + } + let mut hasdig = false; + let mut dot: Option = None; + if p < raw.len() && raw[p] <= b'0' { + loop { + if p >= raw.len() { + break; + } + if raw[p] == b'0' { + hasdig = true; + p += 1; + } else if raw[p] == b'.' { + if dot.is_some() { + return Err(()); + } + dot = Some(p); + p += 1; + } else { + break; + } + } + } + let mut digits = 0u32; + let digit_start = p; + while p < raw.len() { + if is_base_digit(raw[p], base) { + if base == 2 && raw[p] > b'1' { + return Err(()); + } + digits += 1; + p += 1; + } else if raw[p] == b'.' { + if dot.is_some() { + return Err(()); + } + dot = Some(p); + p += 1; + } else { + break; + } + } + let _ = digit_start; + if !hasdig && digits == 0 { + return Err(()); + } + let mut float_fmt = false; + if let Some(dot_at) = dot { + if base == 2 { + return Err(()); + } + float_fmt = true; + if digits > 0 { + let mut ex = dot_at as i32 - (p as i32 - 1); + let mut scan = p; + while ex < 0 && scan > 0 && raw[scan - 1] == b'0' { + ex += 1; + scan -= 1; + } + if ex <= -(1 << 20) { + return Err(()); + } + } + } + let exp_letter = if base == 16 { b'p' } else { b'e' }; + if base >= 10 && p < raw.len() && (raw[p] | 0x20) == exp_letter { + float_fmt = true; + p += 1; + if p < raw.len() && (raw[p] == b'+' || raw[p] == b'-') { + p += 1; + } + if p >= raw.len() || !raw[p].is_ascii_digit() { + return Err(()); + } + let mut exp = u32::from(raw[p] - b'0'); + p += 1; + while p < raw.len() && raw[p].is_ascii_digit() { + exp = exp + .saturating_mul(10) + .saturating_add(u32::from(raw[p] - b'0')); + if exp >= (1 << 20) { + return Err(()); + } + p += 1; + } + } + let mut kind = if base == 2 { + NumberKind::Binary + } else if base == 16 && float_fmt { + NumberKind::HexFloat + } else if base == 16 { + NumberKind::HexInteger + } else if float_fmt { + NumberKind::Float + } else { + NumberKind::Integer + }; + if p < raw.len() { + if (raw[p] | 0x20) == b'i' { + p += 1; + kind = NumberKind::Imaginary; + } else if !float_fmt { + let mut saw_u = false; + let mut saw_ll = false; + if (raw[p] | 0x20) == b'u' { + p += 1; + saw_u = true; + } + if p < raw.len() && (raw[p] | 0x20) == b'l' { + p += 1; + if p < raw.len() && (raw[p] | 0x20) == b'l' { + p += 1; + saw_ll = true; + } else { + return Err(()); + } + } + if p < raw.len() && (raw[p] | 0x20) == b'u' && (!saw_u || saw_ll) { + if !saw_u || saw_ll { + p += 1; + saw_u = true; + } + } + if saw_u && !saw_ll { + return Err(()); + } + if saw_ll && saw_u { + kind = NumberKind::Unsigned64; + } else if saw_ll { + kind = NumberKind::Signed64; + } + } + if p < raw.len() { + return Err(()); + } + } + Ok(kind) +} + +fn is_base_digit(c: u8, base: u32) -> bool { + match base { + 2 | 10 => c.is_ascii_digit(), + 16 => c.is_ascii_hexdigit(), + _ => false, + } +} diff --git a/src/frontends/lua/mod.rs b/src/frontends/lua/mod.rs index 462e0b1..08756ae 100644 --- a/src/frontends/lua/mod.rs +++ b/src/frontends/lua/mod.rs @@ -1,6 +1,18 @@ mod expr; mod support; +// Private syntax modules for the locked LuaJIT 5.2-compat grammar. +// Production lowering still goes through expr/support until a later phase +// switches the file entry. These modules are not a second execution entry. +#[allow(dead_code)] +mod ast; +#[allow(dead_code)] +mod lexer; +#[allow(dead_code)] +mod parser; +#[allow(dead_code)] +mod resolve; + use expr::{ LuaDirectLowering, build_lua_unpack_get_expr, parse_lua_direct_expr, parse_lua_direct_expr_top, }; diff --git a/src/frontends/lua/parser.rs b/src/frontends/lua/parser.rs new file mode 100644 index 0000000..61a405e --- /dev/null +++ b/src/frontends/lua/parser.rs @@ -0,0 +1,992 @@ +//! Recursive-descent parser for the locked LuaJIT 2.1 Lua 5.2-compat grammar. +//! +//! This is the private syntax front. It does not lower or execute. Soft +//! keywords, safe navigation, compound assignment and short functions follow +//! the locked parser, including the statement/expression split for `~=`. + +use super::ast::*; +use super::lexer::{self, Tok, Token}; + +#[derive(Clone, Copy)] +struct Flags { + nores: bool, + nocolon: bool, + nonav: bool, +} + +impl Flags { + fn expr() -> Self { + Self { + nores: false, + nocolon: false, + nonav: false, + } + } + + fn stmt() -> Self { + Self { + nores: true, + nocolon: false, + nonav: false, + } + } + + fn nonav(self) -> Self { + Self { + nonav: true, + ..self + } + } +} + +struct Parser<'a> { + source: &'a [u8], + tokens: Vec, + index: usize, + last_statement: bool, +} + +pub fn parse_chunk(source: &[u8]) -> Result { + let lexed = lexer::lex(source)?; + let mut parser = Parser { + source, + tokens: lexed.tokens, + index: 0, + last_statement: false, + }; + let start = parser.here(); + let body = parser.block()?; + parser.expect_kind(Tok::Eof, "end of file")?; + Ok(Chunk { + span: start.cover(parser.previous_span()), + has_bom: lexed.has_bom, + body, + }) +} + +impl<'a> Parser<'a> { + fn here(&self) -> Span { + self.tokens[self.index].span + } + + fn line(&self) -> u32 { + self.tokens[self.index].line + } + + fn kind(&self) -> Tok { + self.tokens[self.index].kind + } + + fn previous_span(&self) -> Span { + if self.index == 0 { + self.here() + } else { + self.tokens[self.index - 1].span + } + } + + fn bump(&mut self) -> Token { + let token = self.tokens[self.index].clone(); + if self.index + 1 < self.tokens.len() { + self.index += 1; + } + token + } + + fn eat(&mut self, kind: Tok) -> bool { + if self.kind() == kind { + self.bump(); + true + } else { + false + } + } + + fn error(&self, message: impl Into) -> lexer::SyntaxError { + lexer::SyntaxError::at(self.here(), self.line(), message) + } + + fn expect_kind(&mut self, kind: Tok, what: &str) -> Result { + if self.kind() == kind { + Ok(self.bump()) + } else { + Err(self.error(format!("expected {what}"))) + } + } + + fn expect_char(&mut self, ch: u8) -> Result { + self.expect_kind(Tok::Char(ch), &format!("'{}'", ch as char)) + } + + fn is_end(&self) -> bool { + matches!( + self.kind(), + Tok::Else | Tok::Elseif | Tok::End | Tok::Until | Tok::Eof + ) + } + + fn is_name_kind(&self) -> bool { + matches!(self.kind(), Tok::Name | Tok::Const | Tok::Continue) + } + + fn name(&mut self) -> Result { + if !self.is_name_kind() { + return Err(self.error("expected name")); + } + let token = self.bump(); + Ok(Name { + span: token.span, + bytes: token.text, + }) + } + + fn block(&mut self) -> Result { + let start = self.here(); + let saved = self.last_statement; + let mut stmts = Vec::new(); + let mut is_last = false; + while !is_last && !self.is_end() { + stmts.push(self.statement()?); + is_last = self.last_statement; + while self.eat(Tok::Char(b';')) {} + } + self.last_statement = saved; + let end = if stmts.is_empty() { + start + } else { + stmts.last().map(|stmt| stmt_span(stmt)).unwrap_or(start) + }; + Ok(Block { + span: start.cover(end), + stmts, + }) + } + + fn statement(&mut self) -> Result { + self.last_statement = false; + let start = self.here(); + match self.kind() { + Tok::If => self.if_stmt(start), + Tok::While => self.while_stmt(start), + Tok::Do => { + self.bump(); + let body = self.block()?; + self.expect_kind(Tok::End, "end")?; + Ok(Stmt::Do { + span: start.cover(self.previous_span()), + body, + }) + } + Tok::For => self.for_stmt(start), + Tok::Repeat => self.repeat_stmt(start), + Tok::Function => self.function_stmt(start), + Tok::Local => self.local_stmt(start, false), + Tok::Const => { + let next = self.peek_kind(); + if matches!(next, Some(Tok::Function)) || next.is_some_and(is_name_token) { + self.local_stmt(start, true) + } else { + self.call_or_assign(start) + } + } + Tok::Return => { + self.bump(); + let values = if self.is_end() || self.kind() == Tok::Char(b';') { + ExprList::empty(self.here()) + } else { + self.expr_list()? + }; + self.last_statement = true; + Ok(Stmt::Return { + span: start.cover(if values.exprs.is_empty() { + self.previous_span() + } else { + values.span + }), + values, + }) + } + Tok::Break => { + self.bump(); + Ok(Stmt::Break { + span: start.cover(self.previous_span()), + }) + } + Tok::Continue => { + let next = self.peek_kind(); + if next.is_some_and(|kind| is_block_end(kind) || kind == Tok::Char(b';')) { + self.bump(); + self.last_statement = true; + Ok(Stmt::Continue { + span: start.cover(self.previous_span()), + }) + } else { + self.call_or_assign(start) + } + } + Tok::Char(b';') => { + self.bump(); + Ok(Stmt::Empty { + span: start.cover(self.previous_span()), + }) + } + Tok::Label => self.label_stmt(start), + Tok::Goto => { + self.bump(); + let name = self.name()?; + Ok(Stmt::Goto { + span: start.cover(name.span), + name, + }) + } + _ => self.call_or_assign(start), + } + } + + fn if_stmt(&mut self, start: Span) -> Result { + let mut arms = Vec::new(); + self.bump(); + loop { + let cond = self.expr(Flags::expr())?; + self.expect_kind(Tok::Then, "then")?; + let body = self.block()?; + arms.push(IfArm { cond, body }); + if self.kind() == Tok::Elseif { + self.bump(); + continue; + } + break; + } + let else_body = if self.eat(Tok::Else) { + Some(self.block()?) + } else { + None + }; + self.expect_kind(Tok::End, "end")?; + Ok(Stmt::If { + span: start.cover(self.previous_span()), + arms, + else_body, + }) + } + + fn while_stmt(&mut self, start: Span) -> Result { + self.bump(); + let cond = self.expr(Flags::expr())?; + self.expect_kind(Tok::Do, "do")?; + let body = self.block()?; + self.expect_kind(Tok::End, "end")?; + Ok(Stmt::While { + span: start.cover(self.previous_span()), + cond, + body, + }) + } + + fn repeat_stmt(&mut self, start: Span) -> Result { + self.bump(); + let body = self.block()?; + self.expect_kind(Tok::Until, "until")?; + let until = self.expr(Flags::expr())?; + Ok(Stmt::Repeat { + span: start.cover(until.span()), + body, + until, + }) + } + + fn for_stmt(&mut self, start: Span) -> Result { + self.bump(); + let first = self.name()?; + if self.eat(Tok::Char(b'=')) { + let start_expr = self.expr(Flags::expr())?; + self.expect_char(b',')?; + let limit = self.expr(Flags::expr())?; + let step = if self.eat(Tok::Char(b',')) { + Some(self.expr(Flags::expr())?) + } else { + None + }; + self.expect_kind(Tok::Do, "do")?; + let body = self.block()?; + self.expect_kind(Tok::End, "end")?; + return Ok(Stmt::NumericFor { + span: start.cover(self.previous_span()), + name: first, + start: start_expr, + limit, + step, + body, + }); + } + let mut names = vec![first]; + while self.eat(Tok::Char(b',')) { + names.push(self.name()?); + } + self.expect_kind(Tok::In, "in")?; + let iters = self.expr_list()?; + self.expect_kind(Tok::Do, "do")?; + let body = self.block()?; + self.expect_kind(Tok::End, "end")?; + Ok(Stmt::GenericFor { + span: start.cover(self.previous_span()), + names, + iters, + body, + }) + } + + fn function_stmt(&mut self, start: Span) -> Result { + self.bump(); + let mut segments = vec![self.name()?]; + while self.eat(Tok::Char(b'.')) { + segments.push(self.name()?); + } + let method = if self.eat(Tok::Char(b':')) { + Some(self.name()?) + } else { + None + }; + let name_span = method + .as_ref() + .map(|name| name.span) + .unwrap_or_else(|| segments.last().unwrap().span); + let body = self.func_body(method.is_some())?; + Ok(Stmt::Function { + span: start.cover(body.span), + name: FuncName { + span: segments[0].span.cover(name_span), + segments, + method, + }, + body, + }) + } + + fn local_stmt(&mut self, start: Span, const_binding: bool) -> Result { + self.bump(); + if self.eat(Tok::Function) { + let name = self.name()?; + let func = self.func_body(false)?; + return Ok(Stmt::LocalFunction { + span: start.cover(func.span), + name, + const_binding, + func, + }); + } + let mut names = vec![LocalName { + name: self.name()?, + const_binding, + }]; + while self.eat(Tok::Char(b',')) { + names.push(LocalName { + name: self.name()?, + const_binding, + }); + } + let values = if self.eat(Tok::Char(b'=')) { + self.expr_list()? + } else { + ExprList::empty(self.previous_span()) + }; + let end = if values.exprs.is_empty() { + names.last().unwrap().name.span + } else { + values.span + }; + Ok(Stmt::Local { + span: start.cover(end), + names, + values, + }) + } + + fn label_stmt(&mut self, start: Span) -> Result { + self.bump(); + let name = self.name()?; + self.expect_kind(Tok::Label, "'::'")?; + Ok(Stmt::Label { + span: start.cover(self.previous_span()), + name, + }) + } + + fn call_or_assign(&mut self, start: Span) -> Result { + let primary = self.primary(Flags::stmt())?; + if is_call(&primary.expr) { + return Ok(Stmt::Call { + span: primary.expr.span(), + call: primary.expr, + }); + } + if primary.nav_used && self.kind() == Tok::Char(b',') { + return Err(self.error("safe navigation cannot be used in parallel assignment")); + } + let target = assign_target(primary.expr).map_err(|span| { + lexer::SyntaxError::at(span, self.line(), "invalid assignment target") + })?; + if let Some(op) = self.compound_op() { + let value = self.expr(Flags::expr())?; + return Ok(Stmt::CompoundAssign { + span: start.cover(value.span()), + target, + op, + value, + }); + } + let mut targets = vec![target]; + while self.eat(Tok::Char(b',')) { + let next = self.primary(Flags::stmt().nonav())?; + if is_call(&next.expr) { + return Err(self.error("invalid assignment target")); + } + targets.push(assign_target(next.expr).map_err(|span| { + lexer::SyntaxError::at(span, self.line(), "invalid assignment target") + })?); + } + self.expect_char(b'=')?; + let values = self.expr_list()?; + Ok(Stmt::Assign { + span: start.cover(values.span), + targets, + values, + }) + } + + fn compound_op(&mut self) -> Option { + let op = match self.kind() { + Tok::Char(b'+') => BinOp::Add, + Tok::Char(b'-') => BinOp::Sub, + Tok::Char(b'*') => BinOp::Mul, + Tok::Char(b'/') => BinOp::Div, + Tok::Char(b'%') => BinOp::Mod, + Tok::Char(b'&') => BinOp::Band, + Tok::Char(b'|') => BinOp::Bor, + Tok::Char(b'~') => BinOp::BXor, + Tok::Shl => BinOp::Shl, + Tok::Shr => BinOp::Shr, + Tok::Sar => BinOp::Sar, + Tok::Concat => BinOp::Concat, + Tok::Eq => BinOp::Eq, + Tok::Ne => BinOp::BXor, + _ => return None, + }; + if self.kind() == Tok::Ne { + self.bump(); + return Some(op); + } + let end = self.here().end as usize; + if self.source.get(end) != Some(&b'=') { + return None; + } + self.bump(); + if self.kind() == Tok::Char(b'=') { + self.bump(); + } + Some(op) + } + + fn func_body(&mut self, need_self: bool) -> Result { + let start = self.here(); + self.expect_char(b'(')?; + let mut params = Vec::new(); + let mut self_param = false; + if need_self { + self_param = true; + } + let mut vararg = false; + if self.kind() != Tok::Char(b')') { + loop { + if self.eat(Tok::Dots) { + vararg = true; + break; + } + params.push(self.name()?); + if !self.eat(Tok::Char(b',')) { + break; + } + if self.kind() == Tok::Char(b')') { + return Err(self.error("expected name")); + } + } + } + self.expect_char(b')')?; + let body = self.block()?; + self.expect_kind(Tok::End, "end")?; + Ok(FuncBody { + span: start.cover(self.previous_span()), + params, + vararg, + self_param, + body, + }) + } + + fn short_func(&mut self, name: Option, flags: Flags) -> Result { + let start = name + .as_ref() + .map(|item| item.span) + .unwrap_or_else(|| self.here()); + let mut params = Vec::new(); + let mut vararg = false; + if let Some(name) = name { + params.push(name); + } else if !self.eat(Tok::OrOr) { + self.expect_char(b'|')?; + if self.kind() != Tok::Char(b'|') { + loop { + if self.eat(Tok::Dots) { + vararg = true; + break; + } + params.push(self.name()?); + if !self.eat(Tok::Char(b',')) { + break; + } + } + } + self.expect_char(b'|')?; + } + self.expect_kind(Tok::Arrow, "'->'")?; + let body = if self.eat(Tok::Do) { + let block = self.block()?; + self.expect_kind(Tok::End, "end")?; + ShortBody::Block(block) + } else { + ShortBody::Expr(Box::new(self.expr(flags)?)) + }; + let end = match &body { + ShortBody::Expr(expr) => expr.span(), + ShortBody::Block(block) => block.span.cover(self.previous_span()), + }; + Ok(Expr::ShortFunction { + span: start.cover(end), + params, + vararg, + body: Box::new(body), + }) + } + + fn expr_list(&mut self) -> Result { + let first = self.expr(Flags::expr())?; + let start = first.span(); + let mut exprs = vec![first]; + while self.eat(Tok::Char(b',')) { + exprs.push(self.expr(Flags::expr())?); + } + let end = exprs.last().unwrap().span(); + Ok(ExprList { + span: start.cover(end), + exprs, + }) + } + + fn expr(&mut self, flags: Flags) -> Result { + let mut left = self.binop(flags, 0)?; + if self.eat(Tok::Char(b'?')) { + let then_expr = self.expr(Flags { + nores: false, + nocolon: true, + nonav: false, + })?; + self.expect_char(b':')?; + let else_expr = self.expr(Flags::expr())?; + let span = left.span().cover(else_expr.span()); + left = Expr::Ternary { + span, + cond: Box::new(left), + then_expr: Box::new(then_expr), + else_expr: Box::new(else_expr), + }; + } + Ok(left) + } + + fn binop(&mut self, flags: Flags, limit: u8) -> Result { + let mut left = self.unop(flags)?; + while let Some((op, left_pri, right_pri)) = binop_of(self.kind()) { + if left_pri <= limit { + break; + } + self.bump(); + let right = self.binop(flags, right_pri)?; + let span = left.span().cover(right.span()); + left = Expr::Binary { + span, + op, + left: Box::new(left), + right: Box::new(right), + }; + } + Ok(left) + } + + fn unop(&mut self, flags: Flags) -> Result { + let op = match self.kind() { + Tok::Not => UnOp::Not, + Tok::Char(b'!') => UnOp::Bang, + Tok::Char(b'-') => UnOp::Neg, + Tok::Char(b'#') => UnOp::Len, + Tok::Char(b'~') => UnOp::BNot, + _ => return self.simple(flags), + }; + let start = self.here(); + self.bump(); + let expr = self.binop(flags, 12)?; + Ok(Expr::Unary { + span: start.cover(expr.span()), + op, + expr: Box::new(expr), + }) + } + + fn simple(&mut self, flags: Flags) -> Result { + let start = self.here(); + match self.kind() { + Tok::Number => { + let token = self.bump(); + Ok(Expr::Number { + span: token.span, + raw: String::from_utf8_lossy(&token.text).into_owned(), + kind: token.number_kind.unwrap_or(NumberKind::Float), + }) + } + Tok::String => { + let token = self.bump(); + Ok(Expr::String { + span: token.span, + bytes: token.text, + }) + } + Tok::Nil => { + self.bump(); + Ok(Expr::Nil { + span: start.cover(self.previous_span()), + }) + } + Tok::True => { + self.bump(); + Ok(Expr::Bool { + span: start.cover(self.previous_span()), + value: true, + }) + } + Tok::False => { + self.bump(); + Ok(Expr::Bool { + span: start.cover(self.previous_span()), + value: false, + }) + } + Tok::Dots => { + self.bump(); + Ok(Expr::Vararg { + span: start.cover(self.previous_span()), + }) + } + Tok::Char(b'{') => self.table(), + Tok::Function => { + self.bump(); + let body = self.func_body(false)?; + Ok(Expr::Function { + span: start.cover(body.span), + body, + }) + } + Tok::Char(b'|') | Tok::OrOr => self.short_func(None, flags), + _ => Ok(self.primary(flags)?.expr), + } + } + + fn primary(&mut self, flags: Flags) -> Result { + let start = self.here(); + let mut expr = if self.eat(Tok::Char(b'(')) { + let inner = self.expr(Flags::expr())?; + self.expect_char(b')')?; + Expr::Paren { + span: start.cover(self.previous_span()), + inner: Box::new(inner), + } + } else if self.is_name_kind() { + let name = self.name()?; + if !flags.nores && self.kind() == Tok::Arrow { + return Ok(Primary { + expr: self.short_func(Some(name), flags)?, + nav_used: false, + }); + } + Expr::Name { + span: name.span, + name, + } + } else { + return Err(self.error("expected expression")); + }; + let mut nav_used = false; + loop { + let mut nav = false; + if !flags.nonav && self.eat(Tok::Nav) { + nav = true; + nav_used = true; + } + if self.kind() == Tok::Char(b'[') { + let key = self.bracket()?; + let span = expr.span().cover(self.previous_span()); + expr = Expr::Index { + span, + table: Box::new(expr), + key: Box::new(key), + nav, + }; + } else if self.kind() == Tok::Char(b':') { + if flags.nocolon { + if nav { + return Err(self.error("expected expression")); + } + break; + } + self.bump(); + let method = self.name()?; + let mut method_nav = false; + if !flags.nonav && self.eat(Tok::Nav) { + method_nav = true; + nav_used = true; + } + let args = self.args()?; + let span = expr.span().cover(args_span(&args)); + expr = Expr::MethodCall { + span, + receiver: Box::new(expr), + method, + args, + receiver_nav: nav, + method_nav, + }; + } else if is_args_start(self.kind()) { + let args = self.args()?; + let span = expr.span().cover(args_span(&args)); + expr = Expr::Call { + span, + callee: Box::new(expr), + args, + nav, + }; + } else if nav || self.kind() == Tok::Char(b'.') { + if !nav { + self.bump(); + } + let field = self.name()?; + let span = expr.span().cover(field.span); + expr = Expr::Field { + span, + table: Box::new(expr), + name: field, + nav, + }; + } else { + break; + } + } + Ok(Primary { expr, nav_used }) + } + + fn bracket(&mut self) -> Result { + self.expect_char(b'[')?; + let expr = self.expr(Flags::expr())?; + self.expect_char(b']')?; + Ok(expr) + } + + fn args(&mut self) -> Result { + match self.kind() { + Tok::Char(b'(') => { + self.bump(); + let list = if self.kind() == Tok::Char(b')') { + ExprList::empty(self.here()) + } else { + self.expr_list()? + }; + self.expect_char(b')')?; + Ok(Args::List(list)) + } + Tok::String => { + let token = self.bump(); + Ok(Args::String { + span: token.span, + bytes: token.text, + }) + } + Tok::Char(b'{') => { + let table = self.table()?; + let Expr::Table { span, fields } = table else { + unreachable!("table constructor"); + }; + Ok(Args::Table { span, fields }) + } + _ => Err(self.error("expected function arguments")), + } + } + + fn table(&mut self) -> Result { + let start = self.here(); + self.expect_char(b'{')?; + let mut fields = Vec::new(); + while self.kind() != Tok::Char(b'}') && self.kind() != Tok::Eof { + if self.kind() == Tok::Char(b'[') { + let key = self.bracket()?; + self.expect_char(b'=')?; + let value = self.expr(Flags::expr())?; + let span = key.span().cover(value.span()); + fields.push(Field::Index { span, key, value }); + } else if self.is_name_kind() && self.peek_kind() == Some(Tok::Char(b'=')) { + let name = self.name()?; + self.bump(); + let value = self.expr(Flags::expr())?; + let span = name.span.cover(value.span()); + fields.push(Field::Name { span, name, value }); + } else { + let value = self.expr(Flags::expr())?; + let span = value.span(); + fields.push(Field::Item { span, value }); + } + if !self.eat(Tok::Char(b',')) && !self.eat(Tok::Char(b';')) { + break; + } + } + self.expect_char(b'}')?; + Ok(Expr::Table { + span: start.cover(self.previous_span()), + fields, + }) + } + + fn peek_kind(&self) -> Option { + self.tokens.get(self.index + 1).map(|token| token.kind) + } +} + +struct Primary { + expr: Expr, + nav_used: bool, +} + +fn is_name_token(kind: Tok) -> bool { + matches!(kind, Tok::Name | Tok::Const | Tok::Continue) +} + +fn is_block_end(kind: Tok) -> bool { + matches!( + kind, + Tok::Else | Tok::Elseif | Tok::End | Tok::Until | Tok::Eof + ) +} + +fn is_args_start(kind: Tok) -> bool { + matches!(kind, Tok::Char(b'(') | Tok::String | Tok::Char(b'{')) +} + +fn is_call(expr: &Expr) -> bool { + matches!(expr, Expr::Call { .. } | Expr::MethodCall { .. }) +} + +fn assign_target(expr: Expr) -> Result { + match expr { + Expr::Name { name, .. } => Ok(AssignTarget::Name(name)), + Expr::Index { + span, + table, + key, + nav, + } => Ok(AssignTarget::Index { + span, + table, + key, + nav, + }), + Expr::Field { + span, + table, + name, + nav, + } => Ok(AssignTarget::Field { + span, + table, + name, + nav, + }), + other => Err(other.span()), + } +} + +fn args_span(args: &Args) -> Span { + match args { + Args::List(list) => list.span, + Args::String { span, .. } | Args::Table { span, .. } => *span, + } +} + +fn binop_of(kind: Tok) -> Option<(BinOp, u8, u8)> { + let op = match kind { + Tok::Char(b'+') => BinOp::Add, + Tok::Char(b'-') => BinOp::Sub, + Tok::Char(b'*') => BinOp::Mul, + Tok::Char(b'/') => BinOp::Div, + Tok::Char(b'%') => BinOp::Mod, + Tok::Char(b'^') => BinOp::Pow, + Tok::Char(b'&') => BinOp::Band, + Tok::Char(b'|') => BinOp::Bor, + Tok::Char(b'~') => BinOp::BXor, + Tok::Shl => BinOp::Shl, + Tok::Shr => BinOp::Shr, + Tok::Sar => BinOp::Sar, + Tok::Concat => BinOp::Concat, + Tok::Eq => BinOp::Eq, + Tok::Ne | Tok::NeBang => BinOp::Ne, + Tok::Char(b'<') => BinOp::Lt, + Tok::Char(b'>') => BinOp::Gt, + Tok::Le => BinOp::Le, + Tok::Ge => BinOp::Ge, + Tok::And | Tok::AndAnd => BinOp::And, + Tok::Or | Tok::OrOr => BinOp::Or, + Tok::Coal => BinOp::Coal, + _ => return None, + }; + let (left, right) = match op { + BinOp::Add | BinOp::Sub => (10, 10), + BinOp::Mul | BinOp::Div | BinOp::Mod => (11, 11), + BinOp::Pow => (14, 13), + BinOp::Band => (6, 6), + BinOp::BXor => (5, 5), + BinOp::Bor => (4, 4), + BinOp::Shl | BinOp::Shr | BinOp::Sar => (7, 7), + BinOp::Concat => (9, 8), + BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Gt | BinOp::Le | BinOp::Ge => (3, 3), + BinOp::And => (2, 2), + BinOp::Or | BinOp::Coal => (1, 1), + }; + Some((op, left, right)) +} + +fn stmt_span(stmt: &Stmt) -> Span { + match stmt { + Stmt::Empty { span } + | Stmt::Do { span, .. } + | Stmt::While { span, .. } + | Stmt::Repeat { span, .. } + | Stmt::If { span, .. } + | Stmt::NumericFor { span, .. } + | Stmt::GenericFor { span, .. } + | Stmt::Local { span, .. } + | Stmt::LocalFunction { span, .. } + | Stmt::Function { span, .. } + | Stmt::Assign { span, .. } + | Stmt::CompoundAssign { span, .. } + | Stmt::Call { span, .. } + | Stmt::Label { span, .. } + | Stmt::Goto { span, .. } + | Stmt::Break { span } + | Stmt::Continue { span } + | Stmt::Return { span, .. } => *span, + } +} diff --git a/src/frontends/lua/resolve.rs b/src/frontends/lua/resolve.rs new file mode 100644 index 0000000..bf75002 --- /dev/null +++ b/src/frontends/lua/resolve.rs @@ -0,0 +1,774 @@ +//! Scope, const, label and import resolution for a parsed Lua 5.2-compat chunk. +//! +//! Goto visibility follows the locked parser: a label is visible only in its +//! block, a trailing label sits at the block's starting local count, and a +//! forward jump into a local's scope is an error. Const bindings cannot be +//! redeclared or assigned, including from a nested function. + +use super::ast::*; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Resolution { + pub bindings: Vec, + pub labels: Vec, + pub gotos: Vec, + pub imports: Vec, + pub errors: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BindingKind { + Local, + Param, + SelfParam, + ForIndex, + Function, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Binding { + pub name: Vec, + pub span: Span, + pub kind: BindingKind, + pub scope_id: u32, + pub function_id: u32, + pub visible_from: u32, + pub visible_to: u32, + pub const_binding: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LabelBinding { + pub name: Vec, + pub span: Span, + pub scope_id: u32, + pub function_id: u32, + pub active_locals: u32, + pub trailing: bool, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GotoUse { + pub name: Vec, + pub span: Span, + pub function_id: u32, + pub active_locals: u32, + pub target: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImportSite { + pub call_span: Span, + pub spec_span: Span, + pub spec: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ResolveError { + JumpIntoLocal { + goto_span: Span, + local_name: Vec, + }, + UndefinedLabel { + span: Span, + name: Vec, + }, + DuplicateLabel { + span: Span, + name: Vec, + }, + BreakOutsideLoop { + span: Span, + }, + ContinueOutsideLoop { + span: Span, + }, + AssignConst { + span: Span, + name: Vec, + }, + RedeclareConst { + span: Span, + name: Vec, + }, + VarargOutside { + span: Span, + }, +} + +struct LocalSlot { + name: Vec, + const_binding: bool, + binding_index: usize, +} + +struct LabelRec { + name: Vec, + index: usize, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum JumpKind { + Goto, + Break, + Continue, +} + +struct JumpRec { + kind: JumpKind, + name: Vec, + slot: u32, + span: Span, + goto_index: Option, + resolved: bool, +} + +struct ScopeFrame { + id: u32, + start_local: usize, + labels: Vec, + jumps: Vec, +} + +struct FuncFrame { + id: u32, + vararg: bool, + scope_base: usize, +} + +struct Cx { + resolution: Resolution, + funcs: Vec, + scopes: Vec, + locals: Vec, + next_scope: u32, +} + +pub fn resolve(chunk: &Chunk) -> Resolution { + let mut cx = Cx { + resolution: Resolution { + bindings: Vec::new(), + labels: Vec::new(), + gotos: Vec::new(), + imports: Vec::new(), + errors: Vec::new(), + }, + funcs: Vec::new(), + scopes: Vec::new(), + locals: Vec::new(), + next_scope: 1, + }; + cx.enter_function(true); + cx.walk_block(&chunk.body, false, true); + cx.leave_scope(chunk.span.end); + cx.funcs.pop(); + cx.resolution +} + +impl Cx { + fn enter_function(&mut self, vararg: bool) { + let id = self.funcs.last().map(|func| func.id + 1).unwrap_or(0); + self.funcs.push(FuncFrame { + id, + vararg, + scope_base: self.scopes.len(), + }); + self.enter_scope(); + } + + fn enter_scope(&mut self) { + let id = self.next_scope; + self.next_scope += 1; + self.scopes.push(ScopeFrame { + id, + start_local: self.locals.len(), + labels: Vec::new(), + jumps: Vec::new(), + }); + } + + fn leave_scope(&mut self, end: u32) { + let scope = self.scopes.pop().expect("scope"); + self.close_scope(scope, end, false); + } + + fn leave_loop(&mut self, end: u32) { + let scope = self.scopes.pop().expect("loop"); + self.close_scope(scope, end, true); + } + + fn close_scope(&mut self, scope: ScopeFrame, end: u32, is_loop: bool) { + for local in self.locals.iter().skip(scope.start_local) { + self.resolution.bindings[local.binding_index].visible_to = end; + } + self.locals.truncate(scope.start_local); + let function_root = self + .funcs + .last() + .is_some_and(|func| func.scope_base == self.scopes.len()); + let mut pending = Vec::new(); + for jump in scope.jumps { + if jump.resolved { + continue; + } + if jump.kind != JumpKind::Goto { + if is_loop { + continue; + } + if !function_root { + if let Some(parent) = self.scopes.last_mut() { + let mut propagated = jump; + propagated.slot = scope.start_local as u32; + parent.jumps.push(propagated); + continue; + } + } + if jump.kind == JumpKind::Break { + self.resolution + .errors + .push(ResolveError::BreakOutsideLoop { span: jump.span }); + } else { + self.resolution + .errors + .push(ResolveError::ContinueOutsideLoop { span: jump.span }); + } + continue; + } + let matched = scope.labels.iter().find(|label| label.name == jump.name); + if let Some(label) = matched { + if let Some(index) = jump.goto_index { + self.resolution.gotos[index].target = Some(label.index); + } + continue; + } + pending.push(jump); + } + if function_root { + for jump in pending { + self.resolution.errors.push(ResolveError::UndefinedLabel { + span: jump.span, + name: jump.name, + }); + } + } else if let Some(parent) = self.scopes.last_mut() { + for mut jump in pending { + jump.slot = scope.start_local as u32; + parent.jumps.push(jump); + } + } + } + + fn add_binding( + &mut self, + name: &Name, + kind: BindingKind, + const_binding: bool, + visible_from: u32, + pending_consts: &[Vec], + ) { + let active_const = self + .locals + .iter() + .any(|local| local.const_binding && local.name == name.bytes); + let pending_const = + const_binding && pending_consts.iter().any(|pending| pending == &name.bytes); + if active_const || pending_const { + self.resolution.errors.push(ResolveError::RedeclareConst { + span: name.span, + name: name.bytes.clone(), + }); + } + let scope = self.scopes.last().expect("scope"); + let function_id = self.funcs.last().expect("function").id; + let binding_index = self.resolution.bindings.len(); + self.resolution.bindings.push(Binding { + name: name.bytes.clone(), + span: name.span, + kind, + scope_id: scope.id, + function_id, + visible_from, + visible_to: u32::MAX, + const_binding, + }); + self.locals.push(LocalSlot { + name: name.bytes.clone(), + const_binding, + binding_index, + }); + } + + fn lookup_const(&self, name: &[u8]) -> bool { + self.locals + .iter() + .rev() + .any(|local| local.name == name && local.const_binding) + } + + fn assign_name(&mut self, name: &Name) { + if self.lookup_const(&name.bytes) { + self.resolution.errors.push(ResolveError::AssignConst { + span: name.span, + name: name.bytes.clone(), + }); + } + } + + fn define_label(&mut self, name: &Name, trailing: bool) { + let slot = if trailing { + self.scopes.last().expect("scope").start_local as u32 + } else { + self.locals.len() as u32 + }; + let function_id = self.funcs.last().expect("function").id; + let scope_id = self.scopes.last().expect("scope").id; + if self + .scopes + .last() + .expect("scope") + .labels + .iter() + .any(|label| label.name == name.bytes) + { + self.resolution.errors.push(ResolveError::DuplicateLabel { + span: name.span, + name: name.bytes.clone(), + }); + return; + } + let index = self.resolution.labels.len(); + self.resolution.labels.push(LabelBinding { + name: name.bytes.clone(), + span: name.span, + scope_id, + function_id, + active_locals: slot, + trailing, + }); + self.scopes + .last_mut() + .expect("scope") + .labels + .push(LabelRec { + name: name.bytes.clone(), + index, + }); + let jumps = std::mem::take(&mut self.scopes.last_mut().expect("scope").jumps); + let mut kept = Vec::new(); + for mut jump in jumps { + if jump.kind == JumpKind::Goto && !jump.resolved && jump.name == name.bytes { + if jump.slot < slot { + let local_name = self.local_at(jump.slot); + self.resolution.errors.push(ResolveError::JumpIntoLocal { + goto_span: jump.span, + local_name, + }); + } + if let Some(goto_index) = jump.goto_index { + self.resolution.gotos[goto_index].target = Some(index); + } + jump.resolved = true; + } + kept.push(jump); + } + self.scopes.last_mut().expect("scope").jumps = kept; + } + + fn local_at(&self, slot: u32) -> Vec { + self.locals + .get(slot as usize) + .map(|local| local.name.clone()) + .unwrap_or_else(|| b"".to_vec()) + } + + fn add_jump(&mut self, kind: JumpKind, name: Vec, span: Span) { + let slot = self.locals.len() as u32; + let function_id = self.funcs.last().expect("function").id; + let goto_index = if kind == JumpKind::Goto { + let index = self.resolution.gotos.len(); + self.resolution.gotos.push(GotoUse { + name: name.clone(), + span, + function_id, + active_locals: slot, + target: None, + }); + Some(index) + } else { + None + }; + let mut resolved = false; + if kind == JumpKind::Goto { + if let Some(label) = self + .scopes + .last() + .and_then(|scope| scope.labels.iter().find(|label| label.name == name)) + { + let index = label.index; + if let Some(goto_index) = goto_index { + self.resolution.gotos[goto_index].target = Some(index); + } + resolved = true; + } + } + self.scopes.last_mut().expect("scope").jumps.push(JumpRec { + kind, + name, + slot, + span, + goto_index, + resolved, + }); + } + + fn walk_block(&mut self, block: &Block, is_loop_body: bool, adjust_trailing: bool) { + if is_loop_body { + self.enter_scope(); + } + let trailing = trailing_labels(block, adjust_trailing); + for (index, stmt) in block.stmts.iter().enumerate() { + self.walk_stmt(stmt, trailing[index]); + } + if is_loop_body { + self.leave_scope(block.span.end); + } + } + + fn walk_stmt(&mut self, stmt: &Stmt, trailing_label: bool) { + match stmt { + Stmt::Empty { .. } => {} + Stmt::Do { body, span, .. } => { + self.enter_scope(); + self.walk_block(body, false, true); + self.leave_scope(span.end); + } + Stmt::While { + cond, body, span, .. + } => { + self.walk_expr(cond); + self.enter_scope(); + self.walk_block(body, true, true); + self.leave_loop(span.end); + } + Stmt::Repeat { + body, until, span, .. + } => { + self.enter_scope(); + self.enter_scope(); + self.walk_block(body, false, false); + self.walk_expr(until); + self.leave_scope(until.span().end); + self.leave_loop(span.end); + } + Stmt::If { + arms, + else_body, + span, + .. + } => { + for arm in arms { + self.walk_expr(&arm.cond); + self.enter_scope(); + self.walk_block(&arm.body, false, true); + self.leave_scope(arm.body.span.end); + } + if let Some(body) = else_body { + self.enter_scope(); + self.walk_block(body, false, true); + self.leave_scope(body.span.end); + } + let _ = span; + } + Stmt::NumericFor { + name, + start, + limit, + step, + body, + span, + .. + } => { + self.walk_expr(start); + self.walk_expr(limit); + if let Some(step) = step { + self.walk_expr(step); + } + self.enter_scope(); + self.add_binding(name, BindingKind::ForIndex, false, body.span.start, &[]); + self.walk_block(body, true, true); + self.leave_loop(span.end); + } + Stmt::GenericFor { + names, + iters, + body, + span, + .. + } => { + self.walk_expr_list(iters); + self.enter_scope(); + for name in names { + self.add_binding(name, BindingKind::ForIndex, false, body.span.start, &[]); + } + self.walk_block(body, true, true); + self.leave_loop(span.end); + } + Stmt::Local { + names, + values, + span, + .. + } => { + self.walk_expr_list(values); + let mut pending = Vec::new(); + for local in names { + self.add_binding( + &local.name, + BindingKind::Local, + local.const_binding, + span.end, + &pending, + ); + if local.const_binding { + pending.push(local.name.bytes.clone()); + } + } + } + Stmt::LocalFunction { + name, + const_binding, + func, + span, + .. + } => { + self.add_binding( + name, + BindingKind::Function, + *const_binding, + name.span.start, + &[], + ); + self.walk_func(func, false); + let _ = span; + } + Stmt::Function { name, body, .. } => { + if name.method.is_none() && name.segments.len() == 1 { + self.assign_name(&name.segments[0]); + } + self.walk_func(body, name.method.is_some()); + } + Stmt::Assign { + targets, values, .. + } => { + self.walk_expr_list(values); + for target in targets { + self.walk_target(target, true); + } + } + Stmt::CompoundAssign { target, value, .. } => { + self.walk_target(target, true); + self.walk_expr(value); + } + Stmt::Call { call, .. } => self.walk_expr(call), + Stmt::Label { name, .. } => self.define_label(name, trailing_label), + Stmt::Goto { name, span, .. } => { + self.add_jump(JumpKind::Goto, name.bytes.clone(), *span) + } + Stmt::Break { span } => self.add_jump(JumpKind::Break, Vec::new(), *span), + Stmt::Continue { span } => self.add_jump(JumpKind::Continue, Vec::new(), *span), + Stmt::Return { values, .. } => self.walk_expr_list(values), + } + } + + fn walk_func(&mut self, func: &FuncBody, method: bool) { + self.enter_function(func.vararg); + if method || func.self_param { + let self_name = Name { + span: func.span, + bytes: b"self".to_vec(), + }; + self.add_binding( + &self_name, + BindingKind::SelfParam, + false, + func.body.span.start, + &[], + ); + } + for param in &func.params { + self.add_binding(param, BindingKind::Param, false, func.body.span.start, &[]); + } + self.walk_block(&func.body, false, true); + self.leave_scope(func.span.end); + self.funcs.pop(); + } + + fn walk_short(&mut self, params: &[Name], vararg: bool, body: &ShortBody, span: Span) { + self.enter_function(vararg); + for param in params { + let visible = match body { + ShortBody::Expr(expr) => expr.span().start, + ShortBody::Block(block) => block.span.start, + }; + self.add_binding(param, BindingKind::Param, false, visible, &[]); + } + match body { + ShortBody::Expr(expr) => self.walk_expr(expr), + ShortBody::Block(block) => self.walk_block(block, false, true), + } + self.leave_scope(span.end); + self.funcs.pop(); + } + + fn walk_target(&mut self, target: &AssignTarget, assign: bool) { + match target { + AssignTarget::Name(name) => { + if assign { + self.assign_name(name); + } + } + AssignTarget::Index { table, key, .. } => { + self.walk_expr(table); + self.walk_expr(key); + } + AssignTarget::Field { table, .. } => self.walk_expr(table), + } + } + + fn walk_expr_list(&mut self, list: &ExprList) { + for expr in &list.exprs { + self.walk_expr(expr); + } + } + + fn walk_expr(&mut self, expr: &Expr) { + match expr { + Expr::Nil { .. } + | Expr::Bool { .. } + | Expr::Number { .. } + | Expr::String { .. } + | Expr::Name { .. } => {} + Expr::Vararg { span } => { + if !self.funcs.last().is_some_and(|func| func.vararg) { + self.resolution + .errors + .push(ResolveError::VarargOutside { span: *span }); + } + } + Expr::Paren { inner, .. } => self.walk_expr(inner), + Expr::Unary { expr, .. } => self.walk_expr(expr), + Expr::Binary { left, right, .. } => { + self.walk_expr(left); + self.walk_expr(right); + } + Expr::Ternary { + cond, + then_expr, + else_expr, + .. + } => { + self.walk_expr(cond); + self.walk_expr(then_expr); + self.walk_expr(else_expr); + } + Expr::Call { + callee, args, span, .. + } => { + self.note_import(*span, callee, args); + self.walk_expr(callee); + self.walk_args(args); + } + Expr::MethodCall { receiver, args, .. } => { + self.walk_expr(receiver); + self.walk_args(args); + } + Expr::Index { table, key, .. } => { + self.walk_expr(table); + self.walk_expr(key); + } + Expr::Field { table, .. } => self.walk_expr(table), + Expr::Function { body, .. } => self.walk_func(body, false), + Expr::ShortFunction { + params, + vararg, + body, + span, + .. + } => { + self.walk_short(params, *vararg, body, *span); + } + Expr::Table { fields, .. } => { + for field in fields { + match field { + Field::Index { key, value, .. } => { + self.walk_expr(key); + self.walk_expr(value); + } + Field::Name { value, .. } | Field::Item { value, .. } => { + self.walk_expr(value) + } + } + } + } + } + } + + fn walk_args(&mut self, args: &Args) { + match args { + Args::List(list) => self.walk_expr_list(list), + Args::String { .. } => {} + Args::Table { fields, .. } => { + for field in fields { + match field { + Field::Index { key, value, .. } => { + self.walk_expr(key); + self.walk_expr(value); + } + Field::Name { value, .. } | Field::Item { value, .. } => { + self.walk_expr(value) + } + } + } + } + } + } + + fn note_import(&mut self, call_span: Span, callee: &Expr, args: &Args) { + let Expr::Name { name, .. } = callee else { + return; + }; + if name.bytes != b"require" { + return; + } + let (spec_span, spec) = match args { + Args::String { span, bytes } => (*span, bytes.clone()), + Args::List(list) => match list.exprs.first() { + Some(Expr::String { span, bytes }) => (*span, bytes.clone()), + _ => return, + }, + Args::Table { .. } => return, + }; + self.resolution.imports.push(ImportSite { + call_span, + spec_span, + spec, + }); + } +} + +fn trailing_labels(block: &Block, adjust: bool) -> Vec { + let mut flags = vec![false; block.stmts.len()]; + if !adjust { + return flags; + } + for index in 0..block.stmts.len() { + if !matches!(block.stmts[index], Stmt::Label { .. }) { + continue; + } + let rest_are_labels = block.stmts[index + 1..] + .iter() + .all(|stmt| matches!(stmt, Stmt::Label { .. } | Stmt::Empty { .. })); + flags[index] = rest_are_labels; + } + flags +} diff --git a/tests/compiler/compiler_luajit_oracle_tests.rs b/tests/compiler/compiler_luajit_oracle_tests.rs new file mode 100644 index 0000000..0760c6c --- /dev/null +++ b/tests/compiler/compiler_luajit_oracle_tests.rs @@ -0,0 +1,630 @@ +//! Differential syntax checks against the locked LuaJIT 2.1 binary. +//! +//! Set LUAJIT_ORACLE to the luajit built from 96f7b297 with +//! XCFLAGS=-DLUAJIT_ENABLE_LUA52COMPAT. The test loads each sample with +//! load(source, "@probe", "t") and requires the same accept/reject result +//! from the private parser. This is not a second public file entry. + +#[path = "../../src/frontends/lua/ast.rs"] +mod ast; +#[path = "../../src/frontends/lua/lexer.rs"] +mod lexer; +#[path = "../../src/frontends/lua/parser.rs"] +mod parser; +#[path = "../../src/frontends/lua/resolve.rs"] +mod resolve; + +use std::io::Write; +use std::process::Command; + +const ORACLE_SHA: &str = "96f7b297326e9fd454b7186c6858b2773f94a0dc"; + +fn oracle_path() -> String { + std::env::var("LUAJIT_ORACLE").unwrap_or_else(|_| { + "/mnt/workspace/rustscript-lua/tmp/lua52-syntax/LuaJIT/src/luajit".to_string() + }) +} + +fn syntax_ok(source: &[u8]) -> bool { + match parser::parse_chunk(source) { + Ok(chunk) => resolve::resolve(&chunk).errors.is_empty(), + Err(_) => false, + } +} + +fn oracle_accepts(source: &[u8]) -> bool { + let dir = std::env::var("TMPDIR") + .unwrap_or_else(|_| "/mnt/workspace/rustscript-lua/tmp/lua52-syntax".to_string()); + let src = format!("{dir}/oracle-case.bin"); + let mut file = std::fs::File::create(&src).expect("oracle source"); + file.write_all(source).expect("write oracle source"); + let driver = format!("{dir}/load_t.lua"); + let output = Command::new(oracle_path()) + .arg(&driver) + .arg(&src) + .output() + .expect("run locked luajit"); + let text = String::from_utf8_lossy(&output.stdout); + text.starts_with("ACCEPT") +} + +#[test] +fn oracle_config_accepts_52_markers() { + let dir = std::env::var("TMPDIR") + .unwrap_or_else(|_| "/mnt/workspace/rustscript-lua/tmp/lua52-syntax".to_string()); + let output = Command::new(oracle_path()) + .arg("-e") + .arg( + "local g = load('local goto = 1', '@g', 't')\n\ + local b = load('for i=1,2 do break print(i) end', '@b', 't')\n\ + io.write(g and 'BAD_GOTO' or 'GOTO_KW', ' ')\n\ + io.write(b and 'BREAK_OK' or 'BREAK_BAD', ' ')\n\ + io.write(type(table.pack), '\\n')", + ) + .env("TMPDIR", &dir) + .output() + .expect("oracle config"); + let text = String::from_utf8_lossy(&output.stdout); + assert!( + text.contains("GOTO_KW") && text.contains("BREAK_OK") && text.contains("function"), + "oracle {ORACLE_SHA} is not Lua 5.2 compat: {text:?} {:?}", + String::from_utf8_lossy(&output.stderr) + ); +} + +fn cases() -> Vec<(&'static str, &'static [u8])> { + vec![ + ("empty", b""), + ("semi", b";;;"), + ("return_one", b"return 1"), + ("bare_num", b"42"), + ("floor_div", b"return 7//2"), + ("elif", b"if true then 1 elif false then 2 end"), + ("pub_fn", b"pub fn f() end"), + ("local_goto", b"local goto = 1"), + ("break_mid", b"for i=1,2 do break print(i) end"), + ("break_out", b"break"), + ("continue_out", b"continue"), + ("continue_ok", b"while true do continue end"), + ("continue_mid", b"while true do continue print(1) end"), + ("continue_name", b"local continue = 1"), + ("const_ok", b"const x = 1"), + ("const_assign", b"const x = 1\nx = 2"), + ("const_shadow", b"const x = 1\ndo local x = 2 end"), + ("const_after", b"do const x = 1 end\nlocal x = 2"), + ("const_field", b"const t = {}\nt.a = 1"), + ("const_up", b"const x = 1\nlocal function f() x = 2 end"), + ("const_for", b"const i = 1\nfor i = 1, 2 do end"), + ("goto_fwd", b"goto a\nlocal x = 1\n::a::"), + ("goto_into", b"goto L\nlocal x = 1\n::L::\nreturn x"), + ("goto_back", b"::a::\nlocal x = 1\ngoto a"), + ("goto_out", b"::a::\ndo local x = 1 goto a end"), + ("dup_label", b"::a::\n::a::"), + ("nested_label", b"::a::\ndo ::a:: end"), + ("goto_undef", b"goto missing"), + ("label_end", b"do ::a:: end"), + ("goto_into_do", b"goto a\ndo local x ::a:: end"), + ( + "repeat_into", + b"repeat\n goto a\n local x = 1\n ::a::\nuntil true", + ), + ("vararg_bad", b"function f() return ... end"), + ("vararg_ok", b"function f(...) return ... end"), + ("dots_main", b"return ..."), + ("pow", b"return -2^2"), + ("concat", b"return 'a'..'b'..'c'"), + ("coal", b"return nil ?? 3"), + ("nav", b"return a?.b"), + ("nav_index", b"return a?.[1]"), + ("nav_call", b"return a?.b()"), + ("method_nav", b"return a:b?.()"), + ("colon_nav", b"return a?.:b()"), + ("nav_assign", b"a?.b = 1"), + ("nav_parallel", b"a?.b, c = 1, 2"), + ("compound", b"a += 1"), + ("compound_space", b"a + = 1"), + ("xor_assign", b"a ~= 1"), + ("compound_pow", b"a ^= 2"), + ("compound_coal", b"a ??= 1"), + ("ne_expr", b"return a ~= b"), + ("short", b"local f = |x| -> x + 1"), + ("short_empty", b"local f = || -> 1"), + ("short_do", b"local f = |x| -> do return x end"), + ("name_arrow", b"local f = x -> x"), + ("arrow_stmt", b"x -> x"), + ("ternary", b"return 1 > 0 ? 7 : 8"), + ("ternary_method", b"return a ? b:c() : d"), + ("ternary_paren", b"return a ? (b:c()) : d"), + ("and_or", b"return a or b and c"), + ("shl", b"return 1 << 2"), + ("sar", b"return 1 ~>> 2"), + ("andand", b"return a && b"), + ("not_eq", b"return a != b"), + ("bang", b"return !a"), + ("hexfloat", b"return 0x1.8p1"), + ("bin", b"return 0b1010"), + ("under", b"return 1_000"), + ("ull", b"return 1ULL"), + ("ll", b"return -1LL"), + ("imag", b"return 1.5i"), + ("bad_u", b"return 1u"), + ("float_ll", b"return 1.0LL"), + ("bad_number", b"return 1e"), + ("hex_esc", b"return '\\xFF'"), + ("bad_esc", b"return '\\q'"), + ("z_esc", b"return 'a\\z \nb'"), + ("u_esc", b"return '\\u{1F600}'"), + ("u_bad", b"return '\\u{110000}'"), + ("bom_return", b"\xef\xbb\xbfreturn 1"), + ("utf8_ident", "local caf\u{00e9} = 1".as_bytes()), + ("nonutf8", b"local \xff = 1"), + ("shebang", b"#!/usr/bin/env luajit\nreturn 1"), + ("line_dir", b"# 10\nreturn 1"), + ("slash_comment", b"// comment\nreturn 1"), + ("comment_require", b"-- require('nope')\nreturn 1"), + ("string_require", b"return \"require('nope')\""), + ("require_call", b"require('mod')"), + ("require_string", b"require 'mod.sub'"), + ("require_field", b"foo.require('mod')"), + ("paren_call", b"return (f())"), + ("multi_pos", b"return f(), g(), ..."), + ("local_multi", b"local a, b = f(), g()"), + ("table_multi", b"return {f(), g()}"), + ("if_calls", b"if a then b() elseif c then d() else e() end"), + ("until_local", b"repeat local x = 1 until x"), + ("local_rec", b"local function f() return f end"), + ("method", b"function a.b:c() return self end"), + ("attr_const", b"local x = 1"), + ("empty_table", b"return {}"), + ("long_str", b"return [=[a]=]"), + ("unclosed", b"return 'abc"), + ("extra", b"return 1 end"), + ("kw_end", b"local end = 1"), + ("soft_const", b"const = 1"), + ("local_dup", b"local a, a = 1, 2"), + ("const_dup", b"const a, a = 1, 2"), + ("dots_short", b"local f = |...| -> ..."), + ("dots_short_bad", b"local f = |x| -> ..."), + ("table_pack", b"return type(table.pack)"), + ("high_call", b"\xff()"), + ("crlf", b"local x = 1\r\nreturn x"), + ("esc_nl", b"return 'a\\\nb'"), + ("comment_between", b"local x --c\n= 1"), + ("short_comma", b"local f = || -> 1, 2"), + ("label_kw", b"::end::"), + ("goto_fn", b"function f() goto a end\n::a::"), + ("break_fn", b"function f() break end"), + ("continue_semi", b"while true do continue; end"), + ("break_semi", b"while true do break; local x end"), + ("field_soft", b"return { const = 1, continue = 2 }"), + ("assign_index", b"a[1], a.b = 2, 3"), + ("compound_index", b"a[1] += 2"), + ("nested_wrong", b"return [=[ [==[ ]=]"), + ("leading_under", b"return _1"), + ("double_under", b"return 1__2"), + ("zero_x", b"return 0x"), + ("bin_bad", b"return 0b2"), + ("u_surrogate", b"return '\\u{D800}'"), + ("empty_u", b"return '\\u{}'"), + ("ident_digit", b"return 1abc"), + ("empty_parens", b"return ()"), + ("paren_assign", b"(a) = 1"), + ("call_assign", b"f() = 1"), + ("for_missing", b"for i do end"), + ("hash_mid", b"local x = 1 # 2"), + ("only_shebang", b"#!/bin/luajit\n"), + ("bom_only", b"\xef\xbb\xbf"), + ("bitwise", b"return ~a & b | c ~ d << 1 >> 2"), + ("not_chain", b"return not not a"), + ("and_call", b"return a and f()"), + ("table_call", b"f{1}"), + ("string_call", b"f'abc'"), + ("method_string", b"a:b'c'"), + ( + "self_inner", + b"function o:m() local function n() return self end end", + ), + ( + "shadow_param", + b"local function f(a) local a = 1 return a end", + ), + ("goto_same", b"goto a\n::a::"), + ("two_gotos", b"goto a\ngoto a\n::a::"), + ("inner_goto_out", b"do goto a end\n::a::"), + ("label_semi", b"::a::;\ngoto a"), + ("const_fn", b"const function f() end\nf = 1"), + ("const_fn_ok", b"const function f() return f end"), + ("func_missing", b"function f()"), + ("bad_long", b"return [=a=]"), + ("line_spaces", b"# 4\t\nreturn 1"), + ("directive_eof", b"# 9"), + ("not_bang_name", b"return not !a"), + ("question_only", b"return a ?"), + ("arrow_only", b"return -> 1"), + ("space_shl", b"a << = 1"), + ("imag_ll", b"return 1LLi"), + ("hex_ll", b"return 0xFFLL"), + ("plus_exp", b"return 1e+2"), + ("hex_p", b"return 0x1p-1"), + ("dot_num", b"return .5"), + ("num_dot", b"return 5."), + ("long_nl", b"return [[\nhello]]"), + ("mismatch_long", b"return [[a]=]"), + ("esc_quote", b"return '\\''"), + ("dec_esc", b"return '\\000\\255'"), + ("dec_bad", b"return '\\256'"), + ("x_short", b"return '\\x4'"), + ("unclosed_long", b"return [[abc"), + ("long_comment", b"--[[ require('nope') ]]\nreturn 1"), + ("eq_comment", b"--[=[ ]=]\nreturn 1"), + ("comment_unclosed", b"--[[ abc"), + ("repeat_empty", b"repeat until true"), + ("while_empty", b"while false do end"), + ("if_empty", b"if false then end"), + ("do_empty", b"do end"), + ("local_none", b"local a, b"), + ("local_rhs", b"local a, b = 1"), + ("generic_for", b"for k, v in pairs(t) do end"), + ("for_step", b"for i=1,10,2 do end"), + ("dotted_fn", b"function a.b.c() end"), + ("ellipsis_mid", b"function f(..., a) end"), + ("trailing_comma_params", b"function f(a,) end"), + ("trailing_comma_call", b"f(1,)"), + ("return_semi", b"do return 1; end"), + ("return_then", b"do return 1 local x end"), + ( + "continue_if", + b"while true do if a then continue else break end end", + ), + ("nested_break", b"while a do while b do break end end"), + ("nested_continue", b"while a do while b do continue end end"), + ("const_method", b"const function o:m() end"), + ("short_ws", b"local f = ||-> 1"), + ("nav_bracket_bad", b"return a?[1]"), + ("call_nav_stmt", b"a?.b()"), + ("call_nav_comma", b"a?.b(), c"), + ("field_nav", b"return a.b?.c"), + ("table_nav", b"return { a?.b }"), + ("name_arrow_call", b"f(x -> x)"), + ("local_const_soft", b"local const = 1"), + ("const_continue", b"local const = continue"), + ("continue_call", b"continue()"), + ("high_string", b"return '\xff'"), + ("utf8_string", "return '\u{4f60}\u{597d}'".as_bytes()), + ("utf8_comment", "local x = 1 -- \u{6ce8}\u{91ca}".as_bytes()), + ("ident_stmt", b"abc"), + ("call_stmt", b"f()"), + ("index_call", b"return a[b](c)"), + ("not_call", b"return not f()"), + ("len_call", b"return #f()"), + ("pow_neg", b"return 2^-2"), + ("concat_num", b"return 1 .. 2"), + ("and_symbol", b"return a and b && c"), + ("or_symbol", b"return a or b || c"), + ("nav_space", b"return a ? .b"), + ("arrow_space", b"local f = |x| - > x"), + ("label_space", b": :a: :"), + ("shl_space", b"return 1 < < 2"), + ("hash_bang_later", b"local x = 1\n#!/bin/luajit"), + ("bad_param", b"function f(1) end"), + ("dots_assign", b"... = 1"), + ("bitwise_not", b"return ~a"), + ("eq_chain", b"return a == b ~= c"), + ("cmp_chain", b"return 1 < 2 < 3"), + ("unclosed_fn", b"local function f() return 1"), + ("until_missing", b"repeat local x = 1"), + ("if_missing_then", b"if a b end"), + ("goto_missing", b"goto"), + ("label_missing", b"::name"), + ("double_comma", b"local a,,b = 1"), + ("comma_empty", b"return 1,"), + ("func_in_assign", b"a = function() return 1 end"), + ("if_return", b"if a then return 1 else return 2 end"), + ( + "for_break_continue", + b"for i=1,3 do if i == 1 then continue end break end", + ), + ("assign_up_ok", b"local x = 1\nlocal function f() x = 2 end"), + ("global_assign", b"x = 1"), + ("method_self", b"function o:m() return self end"), + ("empty_return", b"return"), + ("semi_return", b"return;"), + ("return_after", b"return; local x"), + ("do_return", b"do return end"), + ("nested_do", b"do do end end"), + ("comment_cr", b"-- c\rlocal x = 1"), + ("ws_z_crlf", b"return 'a\\z\r\nb'"), + ("string_hex", b"return '\\xff'"), + ("esc_z_only", b"return '\\z'"), + ("esc_backslash", b"return '\\\\'"), + ("zero_ll", b"return 0LL"), + ("bin_ll", b"return 0b11LL"), + ("imag_hex", b"return 0x1p1i"), + ("under_suffix", b"return 1_LL"), + ("exp_under", b"return 1e_2"), + ("u_ascii", b"return '\\u{41}'"), + ("u_two", b"return '\\u{80}'"), + ("u_four", b"return '\\u{10000}'"), + ("cr_nl", b"local x = 1\rreturn x"), + ("compound_concat", b"a ..= 'x'"), + ("compound_shl", b"a <<= 1"), + ("compound_sar", b"a ~>>= 1"), + ("compound_mod", b"a %= 2"), + ("compound_band", b"a &= 1"), + ("compound_bor", b"a |= 1"), + ("compound_shr", b"a >>= 1"), + ("compound_div", b"a /= 2"), + ("compound_mul", b"a *= 2"), + ("compound_sub", b"a -= 1"), + ("plus_assign_call", b"a.b += f()"), + ("short_vararg_bad", b"function f(..., a) end"), + ("empty_params_space", b"local f = | | -> 1"), + ("bor_short", b"return |x, y| -> x | y"), + ("or_or_short", b"return || -> 1"), + ("question_question", b"return a ? ? b"), + ("tilde_gt", b"return 1 ~> 2"), + ("hash_number", b"return 1 #2"), + ("directive_bad", b"# abc\nreturn 1"), + ("byte_ff_string", b"return '\xff\xfe'"), + ("mixed_assign", b"a.b, c[d], e = 1, 2, 3"), + ( + "local_func_params", + b"local function f(a, b, ...) return a end", + ), + ("while_return", b"while a do return 1 end"), + ("repeat_continue", b"repeat continue until true"), + ("label_before", b"::a::\ngoto a\nlocal x = 1"), + ("const_in_for", b"for i=1,2 do const x = i end"), + ("const_index", b"const a = {}\na[1] = 2"), + ("double_colon_goto", b"::goto::"), + ("local_fn_goto", b"local function goto() end"), + ("continue_assign", b"continue = 1"), + ("keyword_prefix", b"local functionx = 1"), + ("name_digit", b"local a1 = 1"), + ("true_false", b"return true, false, nil"), + ( + "nested_fn_bad", + b"local f = function(a, ...) return function() return a, ... end end", + ), + ("chunk_fn", b"function f() end\nlocal x = f"), + ("table_trailing", b"return {1, a=2, [3]=4,}"), + ("field_sep", b"return {1; 2, 3}"), + ("index_field", b"return a[b].c"), + ("paren_name", b"return (a)"), + ("not_name", b"return not a"), + ("len_neg", b"return -#a"), + ("and_or_coal", b"return a ?? b or c and d"), + ("ternary_right", b"return a ? b : c ? d : e"), + ("short_or", b"local f = |a, b| -> a or b"), + ("label_until", b"repeat ::a:: until false"), + ("break_repeat", b"repeat break until false"), + ("for_scope", b"for i=1,2 do end\nreturn i"), + ("numeric_shadow", b"for i=1,2 do local i = i end"), + ("assign_call", b"a, b = f(), g()"), + ("multi_arg", b"f(g(), h())"), + ("semi_between", b"local x = 1; local y = 2"), + ("comment_line", b"-- hi\nlocal x = 1"), + ("if_only", b"if a then end"), + ("global_fn", b"function f() end"), + ("empty_call", b"f()"), + ("func_empty", b"function f() end"), + ("while_break", b"while a do break end"), + ("generic_one", b"for i in a do end"), + ("local_no_init", b"local a"), + ("return_nil", b"return nil"), + ("do_block", b"do local x = 1 end"), + ("eqeq", b"return a == b"), + ("ge", b"return a >= b"), + ("mod", b"return a % b"), + ("div", b"return a / b"), + ("xor", b"return a ~ b"), + ("band", b"return a & b"), + ("bor", b"return a | b"), + ("hash", b"return #a"), + ("method_call", b"a:b(1)"), + ("empty_long", b"return [[]]"), + ("eq_level", b"return [==[a]==]"), + ("esc_x_upper", b"return '\\xFf'"), + ("esc_decimal_short", b"return '\\9'"), + ("llu", b"return 1LLu"), + ("ull_mixed", b"return 1uLl"), + ("imag_upper", b"return 2I"), + ("nan_ident", b"return inf"), + ("zero_b", b"return 0b"), + ("hex_under", b"return 0x_ff"), + ("paren_expr", b"(f)"), + ("last_string_arg", b"return f 'a', g()"), + ("nav_field", b"return a?.b.c"), + ("nav_then_index", b"return a?.b[1]"), + ("short_in_call", b"f(|x| -> x)"), + ("short_in_table", b"return { |x| -> x }"), + ("ternary_table", b"return { a ? 1 : 2 }"), + ("line_then_goto", b"# 40\nlocal goto = 1"), + ("require_method", b"foo:require('mod')"), + ( + "require_in_comment_long", + b"--[[\nrequire('hidden')\n]]\nreturn 1", + ), + ("assign_const_name", b"const.x = 1"), + ("call_const", b"const()"), + ( + "continue_else", + b"while true do if a then else continue end end", + ), + ("return_in_short", b"local f = || -> do return 1, 2 end"), + ("shebang_no_nl", b"#!/bin/luajit"), + ("string_long_mismatch", b"return [=[a]]"), + ("func_vararg", b"function f(a, ...) end"), + ("nested_ternary", b"return a ? b ? c : d : e"), + ("field_keyword", b"return { [end] = 1 }"), + ("goto_keyword", b"goto end"), + ("space_coal_assign", b"a ?? = 1"), + ("compound_and", b"a &&= 1"), + ("compound_or", b"a ||= 1"), + ("short_do_empty", b"local f = || -> do end"), + ("func_self_plain", b"local f = function() return self end"), + ( + "dots_in_nested", + b"function f(...) return function() return ... end end", + ), + ("label_in_fn", b"function f() ::a:: goto a end"), + ("break_in_if", b"while true do if a then break end end"), + ("local_ff", b"local \xff = 1"), + ("ident_high", b"\x80\x81"), + ("high_byte_src", b"local \x80x = 1"), + ("bom_shebang", b"\xef\xbb\xbf#!/bin/luajit\nreturn 1"), + ("bom_mid", b"return '\xef\xbb\xbf'"), + ("str_crlf", b"return 'a\\\r\nb'"), + ("z_ff", b"return 'a\\z\x0cb'"), + ("for_const_body", b"for i=1,1 do const i = 2 end"), + ("goto_out_fn", b"function f()\ngoto a\nend\n::a::"), + ("label_then_local", b"do ::a:: goto a local x = 1 end"), + ("missing_rhs", b"a +="), + ("multi_label", b"::a:: ::b::\ngoto a\ngoto b"), + ("break_label", b"while true do break ::a:: end"), + ("nav_call2", b"return a?.b?.c()"), + ("assign_compound_field", b"a.b += 2"), + ("if_else_bare", b"if a then b elseif c then d else e end"), + ("pow2", b"return 2^3^2"), + ("and_or_prec", b"return a or b and c"), + ("not_and", b"return not a and b"), + ("shl_add", b"return 1 + 2 << 3"), + ("eq_and", b"return a == b and c"), + ("coal_right", b"return a ?? b ?? c"), + ("and_right", b"return a and b and c"), + ("concat_pow", b"return a .. b ^ c"), + ("unclosed_comment_ok_after", b"-- ok\nreturn 1"), + ( + "local_function_const_rec", + b"const function f() return f end", + ), + ("shadow_nonconst", b"local x = 1\ndo local x = 2 end"), + ("goto_across_do_local", b"goto a\ndo local x = 1 end\n::a::"), + ("inner_label_same", b"::lab:: do ::lab:: end"), + ("continue_in_numeric", b"for i=1,3 do continue end"), + ("break_in_generic", b"for i in a do break end"), + ("const_redecl_fn", b"const x = 1\nlocal function x() end"), + ( + "const_fn_inner", + b"const x = 1\nlocal function f()\nlocal x = 2\nend", + ), + ("assign_method_const", b"const f = 1\nfunction f() end"), + ("compound_const", b"const a = 1\na += 2"), + ("index_const_ok", b"const a = {}\na.b += 1"), + ("short_assign_const", b"const f = 1\nf = || -> 1"), + ( + "vararg_in_short_outer", + b"function f(...) return |x| -> ... end", + ), + ("goto_repeat_out", b"::a::\nrepeat\n goto a\nuntil false"), + ( + "label_in_until_scope", + b"repeat\n local x = 1\n ::a::\nuntil false", + ), + ] +} + +#[test] +fn differential_matches_locked_luajit() { + let mut mismatches = Vec::new(); + for (name, source) in cases() { + let ours = syntax_ok(source); + let theirs = oracle_accepts(source); + if ours != theirs { + mismatches.push(format!( + "{name}: parser={} oracle={}", + if ours { "ACCEPT" } else { "REJECT" }, + if theirs { "ACCEPT" } else { "REJECT" } + )); + } + } + assert!( + mismatches.is_empty(), + "syntax disagrees with LuaJIT {ORACLE_SHA}:\n{}", + mismatches.join("\n") + ); +} + +#[test] +fn string_escapes_and_spans_are_consumable() { + let source = b"return '\\xFF\\z \n\\u{41}'"; + let chunk = parser::parse_chunk(source).expect("parse escapes"); + let Stmt::Return { values, .. } = &chunk.body.stmts[0] else { + panic!("return"); + }; + let ast::Expr::String { bytes, span, .. } = &values.exprs[0] else { + panic!("string, got {:?}", values.exprs[0]); + }; + assert_eq!(bytes, b"\xffA"); + assert_eq!(span.start, 7); + assert!(span.end > span.start); +} + +#[test] +fn paren_discharges_multiple_return() { + let chunk = parser::parse_chunk(b"return (f()), g(), ...").expect("parse"); + let Stmt::Return { values, .. } = &chunk.body.stmts[0] else { + panic!("return"); + }; + assert!(!values.exprs[0].is_multi()); + assert!(matches!(values.exprs[0], ast::Expr::Paren { .. })); + assert!(values.exprs[1].is_multi()); + assert!(values.exprs[2].is_multi()); + assert!(values.tail_multi()); +} + +#[test] +fn trailing_label_and_jump_into_scope() { + let ok = parser::parse_chunk(b"goto a\nlocal x = 1\n::a::").expect("trailing"); + let resolution = resolve::resolve(&ok); + assert!(resolution.errors.is_empty(), "{:?}", resolution.errors); + assert!(resolution.labels[0].trailing); + + let bad = parser::parse_chunk(b"goto L\nlocal x = 1\n::L::\nreturn x").expect("parse"); + let resolution = resolve::resolve(&bad); + assert!( + resolution.errors.iter().any(|err| matches!( + err, + resolve::ResolveError::JumpIntoLocal { local_name, .. } if local_name == b"x" + )), + "{:?}", + resolution.errors + ); +} + +#[test] +fn const_binding_and_import_discovery() { + let chunk = parser::parse_chunk( + b"const x = 1\nrequire('mod.sub')\n-- require('hidden')\nreturn \"require('nope')\"", + ) + .expect("parse"); + let resolution = resolve::resolve(&chunk); + assert!(resolution.errors.is_empty(), "{:?}", resolution.errors); + assert_eq!(resolution.bindings.len(), 1); + assert!(resolution.bindings[0].const_binding); + assert_eq!(resolution.bindings[0].name, b"x"); + assert!(matches!( + &chunk.body.stmts[0], + ast::Stmt::Local { names, .. } if names[0].name.is("x") + )); + assert_eq!(resolution.imports.len(), 1); + assert_eq!(resolution.imports[0].spec, b"mod.sub"); + + let nav = parser::parse_chunk(b"a?.b = 1").expect("nav assign"); + match &nav.body.stmts[0] { + ast::Stmt::Assign { targets, .. } => { + assert!(targets[0].has_nav()); + assert!(targets[0].span().end > targets[0].span().start); + } + other => panic!("expected assign, got {other:?}"), + } +} + +#[test] +fn bom_is_recorded_and_not_part_of_return() { + let chunk = parser::parse_chunk(b"\xef\xbb\xbfreturn 1").expect("bom"); + assert!(chunk.has_bom); + assert!(matches!(chunk.body.stmts[0], ast::Stmt::Return { .. })); +} + +use ast::Stmt; diff --git a/tests/compiler_tests.rs b/tests/compiler_tests.rs index 4824ca2..6a9e9ee 100644 --- a/tests/compiler_tests.rs +++ b/tests/compiler_tests.rs @@ -5,3 +5,6 @@ mod compiler_javascript_tests; #[path = "compiler/compiler_lua_tests.rs"] mod compiler_lua_tests; + +#[path = "compiler/compiler_luajit_oracle_tests.rs"] +mod compiler_luajit_oracle_tests; From 4d395e74ee4a01ca314bfbe298e83efd83749027 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 04:58:36 +0800 Subject: [PATCH 002/225] fix(lua): gate the LuaJIT oracle and match locked syntax limits Require an explicit LUAJIT_ORACLE and a strict ACCEPT/REJECT protocol. Reject triple-equals assignment, repeat continues that enter later locals, LL/ULL values above 2^64-1, and binary literals over 64 bits. Count syntax levels the way the locked parser does, including long left-associative chains that stay shallow. --- src/frontends/lua/lexer.rs | 36 +- src/frontends/lua/parser.rs | 64 ++- src/frontends/lua/resolve.rs | 23 + .../compiler/compiler_luajit_oracle_tests.rs | 447 ++++++++++++++++-- 4 files changed, 521 insertions(+), 49 deletions(-) diff --git a/src/frontends/lua/lexer.rs b/src/frontends/lua/lexer.rs index 36a4c24..544ad22 100644 --- a/src/frontends/lua/lexer.rs +++ b/src/frontends/lua/lexer.rs @@ -961,12 +961,22 @@ fn classify_number(raw: &[u8]) -> Result { } } let mut digits = 0u32; - let digit_start = p; + let mut decimal_sig = [0u8; 20]; + let mut decimal_len = 0usize; + let mut decimal_too_long = false; while p < raw.len() { if is_base_digit(raw[p], base) { if base == 2 && raw[p] > b'1' { return Err(()); } + if base == 10 && dot.is_none() { + if decimal_len < decimal_sig.len() { + decimal_sig[decimal_len] = raw[p]; + decimal_len += 1; + } else { + decimal_too_long = true; + } + } digits += 1; p += 1; } else if raw[p] == b'.' { @@ -979,7 +989,6 @@ fn classify_number(raw: &[u8]) -> Result { break; } } - let _ = digit_start; if !hasdig && digits == 0 { return Err(()); } @@ -1034,13 +1043,13 @@ fn classify_number(raw: &[u8]) -> Result { } else { NumberKind::Integer }; + let mut saw_ll = false; if p < raw.len() { if (raw[p] | 0x20) == b'i' { p += 1; kind = NumberKind::Imaginary; } else if !float_fmt { let mut saw_u = false; - let mut saw_ll = false; if (raw[p] | 0x20) == b'u' { p += 1; saw_u = true; @@ -1073,9 +1082,30 @@ fn classify_number(raw: &[u8]) -> Result { return Err(()); } } + // strscan_bin rejects more than 64 significant bits for every format. + // Leading zeros are already skipped, matching lj_strscan.c. + if base == 2 && digits > 64 { + return Err(()); + } + // LL/ULL integers share the unsigned 64-bit scan limit. A leading minus + // is a separate unary operator, so it does not widen this token. + if saw_ll + && !float_fmt + && base == 10 + && (decimal_too_long || decimal_above_u64(&decimal_sig[..decimal_len])) + { + return Err(()); + } + if saw_ll && !float_fmt && base == 16 && digits > 16 { + return Err(()); + } Ok(kind) } +fn decimal_above_u64(digits: &[u8]) -> bool { + digits.len() == 20 && digits > b"18446744073709551615" +} + fn is_base_digit(c: u8, base: u32) -> bool { match base { 2 | 10 => c.is_ascii_digit(), diff --git a/src/frontends/lua/parser.rs b/src/frontends/lua/parser.rs index 61a405e..ed2221f 100644 --- a/src/frontends/lua/parser.rs +++ b/src/frontends/lua/parser.rs @@ -44,8 +44,11 @@ struct Parser<'a> { tokens: Vec, index: usize, last_statement: bool, + level: u32, } +const LJ_MAX_XLEVEL: u32 = 200; + pub fn parse_chunk(source: &[u8]) -> Result { let lexed = lexer::lex(source)?; let mut parser = Parser { @@ -53,6 +56,7 @@ pub fn parse_chunk(source: &[u8]) -> Result { tokens: lexed.tokens, index: 0, last_statement: false, + level: 0, }; let start = parser.here(); let body = parser.block()?; @@ -102,6 +106,18 @@ impl<'a> Parser<'a> { } } + fn synlevel_begin(&mut self) -> Result<(), lexer::SyntaxError> { + self.level += 1; + if self.level >= LJ_MAX_XLEVEL { + return Err(self.error("chunk has too many syntax levels")); + } + Ok(()) + } + + fn synlevel_end(&mut self) { + self.level = self.level.saturating_sub(1); + } + fn error(&self, message: impl Into) -> lexer::SyntaxError { lexer::SyntaxError::at(self.here(), self.line(), message) } @@ -141,15 +157,46 @@ impl<'a> Parser<'a> { } fn block(&mut self) -> Result { + self.synlevel_begin()?; + let block = self.block_body(); + if block.is_ok() { + self.synlevel_end(); + } + block + } + + fn block_body(&mut self) -> Result { let start = self.here(); let saved = self.last_statement; let mut stmts = Vec::new(); let mut is_last = false; + // LuaJIT parses a trailing label by recursing into parse_label, and + // each recursion takes a syntax level. The first label does not. + // Semicolons stay inside that chain; another statement ends it. + let mut label_chain = 0u32; while !is_last && !self.is_end() { + if self.kind() == Tok::Label { + if label_chain > 0 { + self.synlevel_begin()?; + } + label_chain += 1; + } else if label_chain > 1 { + for _ in 1..label_chain { + self.synlevel_end(); + } + label_chain = 0; + } else { + label_chain = 0; + } stmts.push(self.statement()?); is_last = self.last_statement; while self.eat(Tok::Char(b';')) {} } + if label_chain > 1 { + for _ in 1..label_chain { + self.synlevel_end(); + } + } self.last_statement = saved; let end = if stmts.is_empty() { start @@ -436,7 +483,12 @@ impl<'a> Parser<'a> { }); } let mut targets = vec![target]; + let mut nvars = 1u32; while self.eat(Tok::Char(b',')) { + if self.level + nvars >= LJ_MAX_XLEVEL { + return Err(self.error("too many variable names")); + } + nvars += 1; let next = self.primary(Flags::stmt().nonav())?; if is_call(&next.expr) { return Err(self.error("invalid assignment target")); @@ -468,7 +520,6 @@ impl<'a> Parser<'a> { Tok::Shr => BinOp::Shr, Tok::Sar => BinOp::Sar, Tok::Concat => BinOp::Concat, - Tok::Eq => BinOp::Eq, Tok::Ne => BinOp::BXor, _ => return None, }; @@ -585,6 +636,7 @@ impl<'a> Parser<'a> { fn expr(&mut self, flags: Flags) -> Result { let mut left = self.binop(flags, 0)?; if self.eat(Tok::Char(b'?')) { + self.synlevel_begin()?; let then_expr = self.expr(Flags { nores: false, nocolon: true, @@ -592,6 +644,7 @@ impl<'a> Parser<'a> { })?; self.expect_char(b':')?; let else_expr = self.expr(Flags::expr())?; + self.synlevel_end(); let span = left.span().cover(else_expr.span()); left = Expr::Ternary { span, @@ -604,6 +657,15 @@ impl<'a> Parser<'a> { } fn binop(&mut self, flags: Flags, limit: u8) -> Result { + self.synlevel_begin()?; + let expr = self.binop_body(flags, limit); + if expr.is_ok() { + self.synlevel_end(); + } + expr + } + + fn binop_body(&mut self, flags: Flags, limit: u8) -> Result { let mut left = self.unop(flags)?; while let Some((op, left_pri, right_pri)) = binop_of(self.kind()) { if left_pri <= limit { diff --git a/src/frontends/lua/resolve.rs b/src/frontends/lua/resolve.rs index bf75002..8b9f05d 100644 --- a/src/frontends/lua/resolve.rs +++ b/src/frontends/lua/resolve.rs @@ -187,6 +187,27 @@ impl Cx { }); } + fn reject_continues_into_locals(&mut self, scope: usize) { + let active = self.locals.len() as u32; + let mut into_local = Vec::new(); + for jump in &mut self.scopes[scope].jumps { + if jump.kind != JumpKind::Continue || jump.resolved { + continue; + } + if jump.slot < active { + into_local.push((jump.span, jump.slot)); + } + jump.resolved = true; + } + for (span, slot) in into_local { + let local_name = self.locals[slot as usize].name.clone(); + self.resolution.errors.push(ResolveError::JumpIntoLocal { + goto_span: span, + local_name, + }); + } + } + fn leave_scope(&mut self, end: u32) { let scope = self.scopes.pop().expect("scope"); self.close_scope(scope, end, false); @@ -457,6 +478,8 @@ impl Cx { self.enter_scope(); self.walk_block(body, false, false); self.walk_expr(until); + let scope = self.scopes.len() - 1; + self.reject_continues_into_locals(scope); self.leave_scope(until.span().end); self.leave_loop(span.end); } diff --git a/tests/compiler/compiler_luajit_oracle_tests.rs b/tests/compiler/compiler_luajit_oracle_tests.rs index 0760c6c..5edeeba 100644 --- a/tests/compiler/compiler_luajit_oracle_tests.rs +++ b/tests/compiler/compiler_luajit_oracle_tests.rs @@ -1,9 +1,9 @@ -//! Differential syntax checks against the locked LuaJIT 2.1 binary. +//! Differential syntax checks against a locked LuaJIT 2.1 binary. //! -//! Set LUAJIT_ORACLE to the luajit built from 96f7b297 with -//! XCFLAGS=-DLUAJIT_ENABLE_LUA52COMPAT. The test loads each sample with -//! load(source, "@probe", "t") and requires the same accept/reject result -//! from the private parser. This is not a second public file entry. +//! Ordinary Cargo does not spawn LuaJIT. Set LUAJIT_ORACLE to the luajit +//! built from 96f7b297 with XCFLAGS=-DLUAJIT_ENABLE_LUA52COMPAT to compare +//! load(source, "@probe", "t"). jit.version is a runtime baseline, not the +//! source identity. This is not a second public file entry. #[path = "../../src/frontends/lua/ast.rs"] mod ast; @@ -15,14 +15,34 @@ mod parser; mod resolve; use std::io::Write; -use std::process::Command; +use std::process::{Command, Stdio}; + +use ast::Stmt; const ORACLE_SHA: &str = "96f7b297326e9fd454b7186c6858b2773f94a0dc"; +const ORACLE_VERSION_BASELINE: &str = "LuaJIT 2.1.1795119671"; -fn oracle_path() -> String { - std::env::var("LUAJIT_ORACLE").unwrap_or_else(|_| { - "/mnt/workspace/rustscript-lua/tmp/lua52-syntax/LuaJIT/src/luajit".to_string() - }) +const LOAD_DRIVER: &str = "\ +local src = io.read('*a') +local fn = load(src, '@probe', 't') +if fn then + io.write('ACCEPT\\n') +else + io.write('REJECT\\n') +end +"; + +const BASELINE_DRIVER: &str = "\ +io.write(jit.version, '\\n') +local g = load('local goto = 1', '@g', 't') +local b = load('for i=1,2 do break print(i) end', '@b', 't') +io.write(g and 'BAD_GOTO' or 'GOTO_KW', '\\n') +io.write(b and 'BREAK_OK' or 'BREAK_BAD', '\\n') +io.write(type(table.pack), '\\n') +"; + +fn configured_oracle() -> Option { + std::env::var("LUAJIT_ORACLE").ok() } fn syntax_ok(source: &[u8]) -> bool { @@ -32,44 +52,112 @@ fn syntax_ok(source: &[u8]) -> bool { } } -fn oracle_accepts(source: &[u8]) -> bool { - let dir = std::env::var("TMPDIR") - .unwrap_or_else(|_| "/mnt/workspace/rustscript-lua/tmp/lua52-syntax".to_string()); - let src = format!("{dir}/oracle-case.bin"); - let mut file = std::fs::File::create(&src).expect("oracle source"); - file.write_all(source).expect("write oracle source"); - let driver = format!("{dir}/load_t.lua"); - let output = Command::new(oracle_path()) - .arg(&driver) - .arg(&src) - .output() - .expect("run locked luajit"); +fn spawn_oracle(path: &str, args: &[&str], stdin_bytes: Option<&[u8]>) -> std::process::Output { + let mut cmd = Command::new(path); + cmd.args(args) + .stdin(if stdin_bytes.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(target_os = "linux")] + unsafe { + use std::os::unix::process::CommandExt; + cmd.pre_exec(limit_oracle_child); + } + let mut child = cmd.spawn().unwrap_or_else(|err| { + panic!("LUAJIT_ORACLE at {path:?} failed to start: {err}"); + }); + if let Some(bytes) = stdin_bytes { + let mut input = child + .stdin + .take() + .unwrap_or_else(|| panic!("LUAJIT_ORACLE at {path:?} has no stdin pipe")); + input.write_all(bytes).unwrap_or_else(|err| { + panic!("LUAJIT_ORACLE at {path:?} rejected stdin: {err}"); + }); + } + child.wait_with_output().unwrap_or_else(|err| { + panic!("LUAJIT_ORACLE at {path:?} failed while waiting: {err}"); + }) +} + +#[cfg(target_os = "linux")] +fn limit_oracle_child() -> std::io::Result<()> { + #[repr(C)] + struct RLimit { + cur: u64, + max: u64, + } + unsafe extern "C" { + fn setrlimit(resource: i32, rlim: *const RLimit) -> i32; + fn alarm(seconds: u32) -> u32; + fn _exit(code: i32) -> !; + } + const RLIMIT_CPU: i32 = 0; + const RLIMIT_AS: i32 = 9; + let cpu = RLimit { cur: 2, max: 2 }; + let address = RLimit { + cur: 128 * 1024 * 1024, + max: 128 * 1024 * 1024, + }; + unsafe { + if setrlimit(RLIMIT_CPU, &cpu) != 0 || setrlimit(RLIMIT_AS, &address) != 0 { + _exit(126); + } + alarm(5); + } + Ok(()) +} + +fn require_success(path: &str, output: &std::process::Output, what: &str) { + if output.status.success() && output.stderr.is_empty() { + return; + } + panic!( + "LUAJIT_ORACLE at {path:?} {what} failed: status={} stdout={:?} stderr={:?}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn assert_oracle_baseline(path: &str) { + let output = spawn_oracle(path, &["-e", BASELINE_DRIVER], None); + require_success(path, &output, "baseline"); let text = String::from_utf8_lossy(&output.stdout); - text.starts_with("ACCEPT") + let expected = format!("{ORACLE_VERSION_BASELINE}\nGOTO_KW\nBREAK_OK\nfunction\n"); + assert_eq!( + text, expected, + "oracle flag/version baseline mismatch; jit.version is not source identity (source commit {ORACLE_SHA})" + ); + eprintln!( + "oracle baseline jit.version={ORACLE_VERSION_BASELINE} (version string is not source identity); source commit {ORACLE_SHA}" + ); +} + +fn oracle_accepts(path: &str, source: &[u8]) -> bool { + let output = spawn_oracle(path, &["-e", LOAD_DRIVER], Some(source)); + require_success(path, &output, "load protocol"); + match output.stdout.as_slice() { + b"ACCEPT\n" => true, + b"REJECT\n" => false, + other => panic!( + "LUAJIT_ORACLE at {path:?} broke the ACCEPT/REJECT protocol: {:?}", + String::from_utf8_lossy(other) + ), + } } #[test] fn oracle_config_accepts_52_markers() { - let dir = std::env::var("TMPDIR") - .unwrap_or_else(|_| "/mnt/workspace/rustscript-lua/tmp/lua52-syntax".to_string()); - let output = Command::new(oracle_path()) - .arg("-e") - .arg( - "local g = load('local goto = 1', '@g', 't')\n\ - local b = load('for i=1,2 do break print(i) end', '@b', 't')\n\ - io.write(g and 'BAD_GOTO' or 'GOTO_KW', ' ')\n\ - io.write(b and 'BREAK_OK' or 'BREAK_BAD', ' ')\n\ - io.write(type(table.pack), '\\n')", - ) - .env("TMPDIR", &dir) - .output() - .expect("oracle config"); - let text = String::from_utf8_lossy(&output.stdout); - assert!( - text.contains("GOTO_KW") && text.contains("BREAK_OK") && text.contains("function"), - "oracle {ORACLE_SHA} is not Lua 5.2 compat: {text:?} {:?}", - String::from_utf8_lossy(&output.stderr) - ); + let Some(path) = configured_oracle() else { + eprintln!("oracle baseline not run: LUAJIT_ORACLE unset; not a differential GREEN"); + return; + }; + assert_oracle_baseline(&path); } fn cases() -> Vec<(&'static str, &'static [u8])> { @@ -526,10 +614,26 @@ fn cases() -> Vec<(&'static str, &'static [u8])> { #[test] fn differential_matches_locked_luajit() { + let Some(path) = configured_oracle() else { + eprintln!( + "oracle differential not run: LUAJIT_ORACLE unset; cases=0 accept=0 reject=0; not a differential GREEN" + ); + return; + }; + assert_oracle_baseline(&path); let mut mismatches = Vec::new(); + let mut accept = 0u32; + let mut reject = 0u32; + let mut compared = 0u32; for (name, source) in cases() { + compared += 1; let ours = syntax_ok(source); - let theirs = oracle_accepts(source); + let theirs = oracle_accepts(&path, source); + if theirs { + accept += 1; + } else { + reject += 1; + } if ours != theirs { mismatches.push(format!( "{name}: parser={} oracle={}", @@ -538,6 +642,26 @@ fn differential_matches_locked_luajit() { )); } } + for (name, source, _) in boundary_samples() { + compared += 1; + let ours = syntax_ok(&source); + let theirs = oracle_accepts(&path, &source); + if theirs { + accept += 1; + } else { + reject += 1; + } + if ours != theirs { + mismatches.push(format!( + "{name}: parser={} oracle={}", + if ours { "ACCEPT" } else { "REJECT" }, + if theirs { "ACCEPT" } else { "REJECT" } + )); + } + } + eprintln!( + "oracle differential cases={compared} accept={accept} reject={reject} scope=load(..., \"t\") source={ORACLE_SHA}" + ); assert!( mismatches.is_empty(), "syntax disagrees with LuaJIT {ORACLE_SHA}:\n{}", @@ -627,4 +751,237 @@ fn bom_is_recorded_and_not_part_of_return() { assert!(matches!(chunk.body.stmts[0], ast::Stmt::Return { .. })); } -use ast::Stmt; +fn nested_do(n: usize) -> Vec { + let mut source = String::new(); + for _ in 0..n { + source.push_str("do "); + } + for _ in 0..n { + source.push_str("end "); + } + source.into_bytes() +} + +fn joined(prefix: &str, item: &str, sep: &str, count: usize) -> Vec { + let mut source = String::from(prefix); + for index in 0..count { + if index > 0 { + source.push_str(sep); + } + source.push_str(item); + } + source.into_bytes() +} + +fn labels(count: usize) -> Vec { + let mut source = String::new(); + for index in 0..count { + if index > 0 { + source.push(' '); + } + source.push_str(&format!("::l{index}::")); + } + source.into_bytes() +} + +fn assignment(count: usize, wrap_do: bool) -> Vec { + let mut names = String::new(); + let mut values = String::new(); + for index in 0..count { + if index > 0 { + names.push(','); + values.push(','); + } + names.push_str(&format!("a{index}")); + values.push('1'); + } + let body = format!("{names} = {values}"); + if wrap_do { + format!("do {body} end").into_bytes() + } else { + body.into_bytes() + } +} + +fn ternary(count: usize) -> Vec { + let mut source = String::from("return "); + for _ in 0..count { + source.push_str("a?"); + } + source.push('1'); + for _ in 0..count { + source.push_str(":0"); + } + source.into_bytes() +} + +fn bits(prefix: &str, count: usize, suffix: &str) -> Vec { + format!("return {prefix}{}{suffix}", "1".repeat(count)).into_bytes() +} + +/// Boundaries measured against locked LuaJIT 96f7b297 with LUAJIT_ENABLE_LUA52COMPAT. +/// `expect` is load(..., "t") accept. These samples do not spawn that binary. +fn boundary_samples() -> Vec<(String, Vec, bool)> { + let mut samples = Vec::new(); + let mut add = |name: &str, source: Vec, accept: bool| { + samples.push((name.to_string(), source, accept)); + }; + add("triple_eq", b"a === 1".to_vec(), false); + add("eq_stmt", b"a == 1".to_vec(), false); + add("ne_stmt", b"a ~= 1".to_vec(), true); + add("ne_expr", b"return a ~= b".to_vec(), true); + add("add_assign", b"a += 1".to_vec(), true); + add("add_assign_space", b"a + = 1".to_vec(), false); + add( + "repeat_continue_early", + b"repeat do continue end local x = 1 until true".to_vec(), + false, + ); + add( + "repeat_continue_late", + b"repeat local x = 1 do continue end until true".to_vec(), + true, + ); + add( + "while_continue_early", + b"while true do do continue end local x = 1 end".to_vec(), + true, + ); + add( + "repeat_if_continue_early", + b"repeat if true then continue end local x = 1 until true".to_vec(), + false, + ); + add( + "repeat_if_continue_late", + b"repeat local x = 1 if true then continue end until true".to_vec(), + true, + ); + add( + "repeat_continue_then_second_local", + b"repeat local x = 1 do continue end local y = 2 until true".to_vec(), + false, + ); + add( + "dec_ll_max", + b"return 18446744073709551615LL".to_vec(), + true, + ); + add( + "dec_ll_over", + b"return 18446744073709551616LL".to_vec(), + false, + ); + add( + "dec_ull_max", + b"return 18446744073709551615ULL".to_vec(), + true, + ); + add( + "dec_ull_over", + b"return 18446744073709551616ULL".to_vec(), + false, + ); + add( + "dec_ll_neg_max", + b"return -18446744073709551615LL".to_vec(), + true, + ); + add( + "dec_ll_neg_over", + b"return -18446744073709551616LL".to_vec(), + false, + ); + add( + "dec_ll_leading_zero_max", + b"return 00018446744073709551615LL".to_vec(), + true, + ); + add( + "dec_ll_leading_zero_over", + b"return 00018446744073709551616LL".to_vec(), + false, + ); + add( + "dec_ll_20_under", + b"return 10000000000000000000LL".to_vec(), + true, + ); + add( + "dec_unsuffixed_over", + b"return 18446744073709551616".to_vec(), + true, + ); + add( + "hex_ll_16", + format!("return 0x{}LL", "F".repeat(16)).into_bytes(), + true, + ); + add( + "hex_ll_17", + format!("return 0x{}LL", "F".repeat(17)).into_bytes(), + false, + ); + add( + "hex_ll_leading_zero_16", + format!("return 0x0000{}LL", "F".repeat(16)).into_bytes(), + true, + ); + add( + "hex_ll_leading_zero_17", + format!("return 0x0000{}LL", "F".repeat(17)).into_bytes(), + false, + ); + add("bin_64", bits("0b", 64, ""), true); + add("bin_65", bits("0b", 65, ""), false); + add("bin_ll_64", bits("0b", 64, "LL"), true); + add("bin_ll_65", bits("0b", 65, "LL"), false); + add("bin_ll_leading_zero_64", bits("0b000", 64, "LL"), true); + add("bin_ll_leading_zero_65", bits("0b000", 65, "LL"), false); + add("do_198", nested_do(198), true); + add("do_199", nested_do(199), false); + add("add_400", joined("return ", "1", "+", 400), true); + add("pow_198", joined("return ", "2", "^", 198), true); + add("pow_199", joined("return ", "2", "^", 199), false); + add("cat_198", joined("return ", "'a'", "..", 198), true); + add("cat_199", joined("return ", "'a'", "..", 199), false); + add("tern_197", ternary(197), true); + add("tern_198", ternary(198), false); + add("lab_199", labels(199), true); + add("lab_200", labels(200), false); + add( + "lab_do_198", + format!("do {} end", String::from_utf8(labels(198)).unwrap()).into_bytes(), + true, + ); + add( + "lab_do_199", + format!("do {} end", String::from_utf8(labels(199)).unwrap()).into_bytes(), + false, + ); + add("asg_199", assignment(199, false), true); + add("asg_200", assignment(200, false), false); + add("asg_do_198", assignment(198, true), true); + add("asg_do_199", assignment(199, true), false); + samples +} + +#[test] +fn locked_luajit_syntax_boundaries() { + let mut failed = Vec::new(); + for (name, source, expect) in boundary_samples() { + let got = syntax_ok(&source); + if got != expect { + failed.push(format!( + "{name}: parser {} expected {}", + if got { "ACCEPT" } else { "REJECT" }, + if expect { "ACCEPT" } else { "REJECT" } + )); + } + } + assert!( + failed.is_empty(), + "locked syntax boundary mismatch (no external oracle):\n{}", + failed.join("\n") + ); +} From 9eeb6693f63b524ceedbfec15a0dba05c2e3ff82 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 05:47:19 +0800 Subject: [PATCH 003/225] fix(lua): flatten unbounded left-associative chains --- src/frontends/lua/ast.rs | 112 ++++-- src/frontends/lua/parser.rs | 158 +++++--- src/frontends/lua/resolve.rs | 37 +- .../compiler/compiler_luajit_oracle_tests.rs | 352 ++++++++++++++++++ 4 files changed, 556 insertions(+), 103 deletions(-) diff --git a/src/frontends/lua/ast.rs b/src/frontends/lua/ast.rs index bd999e8..7c6d87c 100644 --- a/src/frontends/lua/ast.rs +++ b/src/frontends/lua/ast.rs @@ -287,6 +287,57 @@ pub enum Field { Item { span: Span, value: Expr }, } +/// One left-associative operator and the operand that follows it. +/// +/// Steps stay in source order. Short-circuit operators are not reordered, +/// and a parenthesized operand remains a `Paren` boundary. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BinStep { + pub op: BinOp, + pub expr: Expr, +} + +/// One suffix operation, in source order. +/// +/// `span` covers the chain base through this operation, the same range the +/// old nested node stored. Navigation flags stay on the step that used them. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Suffix { + Field { + span: Span, + name: Name, + nav: bool, + }, + Index { + span: Span, + key: Expr, + nav: bool, + }, + Call { + span: Span, + args: Args, + nav: bool, + }, + Method { + span: Span, + method: Name, + args: Args, + receiver_nav: bool, + method_nav: bool, + }, +} + +impl Suffix { + pub fn span(&self) -> Span { + match self { + Self::Field { span, .. } + | Self::Index { span, .. } + | Self::Call { span, .. } + | Self::Method { span, .. } => *span, + } + } +} + #[derive(Clone, Debug, PartialEq, Eq)] pub enum Expr { Nil { @@ -321,43 +372,38 @@ pub enum Expr { op: UnOp, expr: Box, }, + /// Right-associative `^` or `..`. Each operator spends a syntax level, so + /// this spine stays nested and bounded by `LJ_MAX_XLEVEL`. Binary { span: Span, op: BinOp, left: Box, right: Box, }, + /// Left-associative operators at one precedence. `steps` is non-empty. + /// + /// The parser builds these in a loop, so the length is not a syntax-level + /// nest. Storing the spine in a `Vec` keeps parse, drop and resolve off + /// that length. Construction appends operands; it does not clone a prefix. + BinaryChain { + span: Span, + base: Box, + steps: Vec, + }, Ternary { span: Span, cond: Box, then_expr: Box, else_expr: Box, }, - Call { - span: Span, - callee: Box, - args: Args, - nav: bool, - }, - MethodCall { - span: Span, - receiver: Box, - method: Name, - args: Args, - receiver_nav: bool, - method_nav: bool, - }, - Index { + /// Field, index, call and method steps after a primary. `steps` is non-empty. + /// + /// A trailing call or method is a multiple-value expression. A `Paren` + /// around the chain is not. Mixed suffixes keep source order. + SuffixChain { span: Span, - table: Box, - key: Box, - nav: bool, - }, - Field { - span: Span, - table: Box, - name: Name, - nav: bool, + base: Box, + steps: Vec, }, Function { span: Span, @@ -387,11 +433,9 @@ impl Expr { | Self::Paren { span, .. } | Self::Unary { span, .. } | Self::Binary { span, .. } + | Self::BinaryChain { span, .. } | Self::Ternary { span, .. } - | Self::Call { span, .. } - | Self::MethodCall { span, .. } - | Self::Index { span, .. } - | Self::Field { span, .. } + | Self::SuffixChain { span, .. } | Self::Function { span, .. } | Self::ShortFunction { span, .. } | Self::Table { span, .. } => *span, @@ -399,9 +443,13 @@ impl Expr { } pub fn is_multi(&self) -> bool { - matches!( - self, - Self::Call { .. } | Self::MethodCall { .. } | Self::Vararg { .. } - ) + match self { + Self::Vararg { .. } => true, + Self::SuffixChain { steps, .. } => matches!( + steps.last(), + Some(Suffix::Call { .. } | Suffix::Method { .. }) + ), + _ => false, + } } } diff --git a/src/frontends/lua/parser.rs b/src/frontends/lua/parser.rs index ed2221f..9b003b8 100644 --- a/src/frontends/lua/parser.rs +++ b/src/frontends/lua/parser.rs @@ -666,22 +666,38 @@ impl<'a> Parser<'a> { } fn binop_body(&mut self, flags: Flags, limit: u8) -> Result { - let mut left = self.unop(flags)?; + let mut base = self.unop(flags)?; while let Some((op, left_pri, right_pri)) = binop_of(self.kind()) { if left_pri <= limit { break; } - self.bump(); - let right = self.binop(flags, right_pri)?; - let span = left.span().cover(right.span()); - left = Expr::Binary { - span, - op, - left: Box::new(left), - right: Box::new(right), - }; + if right_pri < left_pri { + // Right-associative `^` and `..` spend a syntax level. Nest + // them; do not append them to a left spine. + self.bump(); + let right = self.binop(flags, right_pri)?; + let span = base.span().cover(right.span()); + base = Expr::Binary { + span, + op, + left: Box::new(base), + right: Box::new(right), + }; + continue; + } + let chain_pri = left_pri; + let mut steps = Vec::new(); + while let Some((op, left_pri, right_pri)) = binop_of(self.kind()) { + if left_pri != chain_pri || left_pri <= limit { + break; + } + self.bump(); + let right = self.binop(flags, right_pri)?; + steps.push(BinStep { op, expr: right }); + } + base = finish_binary_chain(base, steps); } - Ok(left) + Ok(base) } fn unop(&mut self, flags: Flags) -> Result { @@ -763,7 +779,7 @@ impl<'a> Parser<'a> { fn primary(&mut self, flags: Flags) -> Result { let start = self.here(); - let mut expr = if self.eat(Tok::Char(b'(')) { + let expr = if self.eat(Tok::Char(b'(')) { let inner = self.expr(Flags::expr())?; self.expect_char(b')')?; Expr::Paren { @@ -785,6 +801,8 @@ impl<'a> Parser<'a> { } else { return Err(self.error("expected expression")); }; + let base_span = expr.span(); + let mut steps = Vec::new(); let mut nav_used = false; loop { let mut nav = false; @@ -794,13 +812,11 @@ impl<'a> Parser<'a> { } if self.kind() == Tok::Char(b'[') { let key = self.bracket()?; - let span = expr.span().cover(self.previous_span()); - expr = Expr::Index { - span, - table: Box::new(expr), - key: Box::new(key), + steps.push(Suffix::Index { + span: base_span.cover(self.previous_span()), + key, nav, - }; + }); } else if self.kind() == Tok::Char(b':') { if flags.nocolon { if nav { @@ -816,41 +832,38 @@ impl<'a> Parser<'a> { nav_used = true; } let args = self.args()?; - let span = expr.span().cover(args_span(&args)); - expr = Expr::MethodCall { - span, - receiver: Box::new(expr), + steps.push(Suffix::Method { + span: base_span.cover(args_span(&args)), method, args, receiver_nav: nav, method_nav, - }; + }); } else if is_args_start(self.kind()) { let args = self.args()?; - let span = expr.span().cover(args_span(&args)); - expr = Expr::Call { - span, - callee: Box::new(expr), + steps.push(Suffix::Call { + span: base_span.cover(args_span(&args)), args, nav, - }; + }); } else if nav || self.kind() == Tok::Char(b'.') { if !nav { self.bump(); } let field = self.name()?; - let span = expr.span().cover(field.span); - expr = Expr::Field { - span, - table: Box::new(expr), + steps.push(Suffix::Field { + span: base_span.cover(field.span), name: field, nav, - }; + }); } else { break; } } - Ok(Primary { expr, nav_used }) + Ok(Primary { + expr: finish_suffix_chain(expr, steps), + nav_used, + }) } fn bracket(&mut self) -> Result { @@ -949,38 +962,71 @@ fn is_args_start(kind: Tok) -> bool { } fn is_call(expr: &Expr) -> bool { - matches!(expr, Expr::Call { .. } | Expr::MethodCall { .. }) + match expr { + Expr::SuffixChain { steps, .. } => { + matches!( + steps.last(), + Some(Suffix::Call { .. } | Suffix::Method { .. }) + ) + } + _ => false, + } } fn assign_target(expr: Expr) -> Result { match expr { Expr::Name { name, .. } => Ok(AssignTarget::Name(name)), - Expr::Index { - span, - table, - key, - nav, - } => Ok(AssignTarget::Index { - span, - table, - key, - nav, - }), - Expr::Field { + Expr::SuffixChain { span, - table, - name, - nav, - } => Ok(AssignTarget::Field { - span, - table, - name, - nav, - }), + base, + mut steps, + } => { + let last = steps.pop(); + let table = finish_suffix_chain(*base, steps); + match last { + Some(Suffix::Index { key, nav, .. }) => Ok(AssignTarget::Index { + span, + table: Box::new(table), + key: Box::new(key), + nav, + }), + Some(Suffix::Field { name, nav, .. }) => Ok(AssignTarget::Field { + span, + table: Box::new(table), + name, + nav, + }), + _ => Err(span), + } + } other => Err(other.span()), } } +fn finish_binary_chain(base: Expr, steps: Vec) -> Expr { + let Some(last) = steps.last() else { + return base; + }; + let span = base.span().cover(last.expr.span()); + Expr::BinaryChain { + span, + base: Box::new(base), + steps, + } +} + +fn finish_suffix_chain(base: Expr, steps: Vec) -> Expr { + let Some(last) = steps.last() else { + return base; + }; + let span = last.span(); + Expr::SuffixChain { + span, + base: Box::new(base), + steps, + } +} + fn args_span(args: &Args) -> Span { match args { Args::List(list) => list.span, diff --git a/src/frontends/lua/resolve.rs b/src/frontends/lua/resolve.rs index 8b9f05d..074ffa3 100644 --- a/src/frontends/lua/resolve.rs +++ b/src/frontends/lua/resolve.rs @@ -684,6 +684,12 @@ impl Cx { self.walk_expr(left); self.walk_expr(right); } + Expr::BinaryChain { base, steps, .. } => { + self.walk_expr(base); + for step in steps { + self.walk_expr(&step.expr); + } + } Expr::Ternary { cond, then_expr, @@ -694,22 +700,23 @@ impl Cx { self.walk_expr(then_expr); self.walk_expr(else_expr); } - Expr::Call { - callee, args, span, .. - } => { - self.note_import(*span, callee, args); - self.walk_expr(callee); - self.walk_args(args); - } - Expr::MethodCall { receiver, args, .. } => { - self.walk_expr(receiver); - self.walk_args(args); - } - Expr::Index { table, key, .. } => { - self.walk_expr(table); - self.walk_expr(key); + Expr::SuffixChain { base, steps, .. } => { + self.walk_expr(base); + for (index, step) in steps.iter().enumerate() { + match step { + Suffix::Field { .. } => {} + Suffix::Index { key, .. } => self.walk_expr(key), + Suffix::Call { span, args, .. } => { + // A later call's callee is a suffix, not the base name. + if index == 0 { + self.note_import(*span, base, args); + } + self.walk_args(args); + } + Suffix::Method { args, .. } => self.walk_args(args), + } + } } - Expr::Field { table, .. } => self.walk_expr(table), Expr::Function { body, .. } => self.walk_func(body, false), Expr::ShortFunction { params, diff --git a/tests/compiler/compiler_luajit_oracle_tests.rs b/tests/compiler/compiler_luajit_oracle_tests.rs index 5edeeba..e3a6979 100644 --- a/tests/compiler/compiler_luajit_oracle_tests.rs +++ b/tests/compiler/compiler_luajit_oracle_tests.rs @@ -985,3 +985,355 @@ fn locked_luajit_syntax_boundaries() { failed.join("\n") ); } + +fn return_expr(chunk: &ast::Chunk) -> &ast::Expr { + let Stmt::Return { values, .. } = &chunk.body.stmts[0] else { + panic!("return"); + }; + &values.exprs[0] +} + +fn parse_resolve_drop(source: &[u8]) -> ast::Chunk { + let chunk = parser::parse_chunk(source).expect("parse"); + let resolution = resolve::resolve(&chunk); + assert!(resolution.errors.is_empty(), "{:?}", resolution.errors); + chunk +} + +/// Follow a chain node, not each operand. This does not call `walk_expr` or `Drop`. +fn binary_chain_nesting(expr: &ast::Expr) -> u32 { + let mut depth = 0u32; + let mut cursor = expr; + loop { + match cursor { + ast::Expr::BinaryChain { base, .. } => { + depth += 1; + cursor = base; + } + _ => return depth, + } + } +} + +fn suffix_chain_nesting(expr: &ast::Expr) -> u32 { + let mut depth = 0u32; + let mut cursor = expr; + loop { + match cursor { + ast::Expr::SuffixChain { base, .. } => { + depth += 1; + cursor = base; + } + _ => return depth, + } + } +} + +fn assert_add_chain(expr: &ast::Expr, ops: usize) { + assert_eq!(binary_chain_nesting(expr), 1, "add spine is nested"); + let ast::Expr::BinaryChain { base, steps, .. } = expr else { + panic!("expected add chain"); + }; + assert!(matches!(base.as_ref(), ast::Expr::Number { .. })); + assert_eq!(steps.len(), ops); + assert!(steps.iter().all(|step| step.op == ast::BinOp::Add)); +} + +fn assert_field_chain(expr: &ast::Expr, ops: usize) { + assert_eq!(suffix_chain_nesting(expr), 1, "suffix spine is nested"); + let ast::Expr::SuffixChain { base, steps, .. } = expr else { + panic!("expected field chain"); + }; + assert!(matches!(base.as_ref(), ast::Expr::Name { .. })); + assert_eq!(steps.len(), ops); + assert!( + steps + .iter() + .all(|step| matches!(step, ast::Suffix::Field { nav: false, .. })) + ); +} + +fn number_raw(expr: &ast::Expr) -> &str { + match expr { + ast::Expr::Number { raw, .. } => raw, + _ => panic!("expected number at {:?}", expr.span()), + } +} + +fn name_is(expr: &ast::Expr, text: &str) -> bool { + matches!(expr, ast::Expr::Name { name, .. } if name.is(text)) +} + +fn expect_syntax_error(source: &[u8], fragment: &str) { + let err = parser::parse_chunk(source).expect_err("syntax error"); + assert!( + err.message.contains(fragment), + "message {:?} does not contain {fragment}", + err.message + ); +} + +#[test] +fn left_spine_depth_does_not_grow_with_length() { + let short_ops = 4usize; + let long_ops = 32usize; + let short = parse_resolve_drop(&joined("return ", "1", "+", short_ops + 1)); + let long = parse_resolve_drop(&joined("return ", "1", "+", long_ops + 1)); + assert_add_chain(return_expr(&short), short_ops); + assert_add_chain(return_expr(&long), long_ops); + drop(short); + drop(long); +} + +#[test] +fn suffix_spine_depth_does_not_grow_with_length() { + let short_ops = 4usize; + let long_ops = 32usize; + let short = parse_resolve_drop(&joined("return a", ".b", "", short_ops)); + let long = parse_resolve_drop(&joined("return a", ".b", "", long_ops)); + assert_field_chain(return_expr(&short), short_ops); + assert_field_chain(return_expr(&long), long_ops); + drop(short); + drop(long); +} + +#[test] +fn composite_binary_keeps_precedence_and_order() { + let chunk = parse_resolve_drop(b"return 1+2*3-4/5"); + let ast::Expr::BinaryChain { base, steps, span } = return_expr(&chunk) else { + panic!("expected left chain"); + }; + assert_eq!(number_raw(base), "1"); + assert_eq!(span.start, 7); + assert_eq!(span.end, 16); + assert_eq!(steps.len(), 2); + assert_eq!(steps[0].op, ast::BinOp::Add); + assert_eq!(steps[1].op, ast::BinOp::Sub); + let ast::Expr::BinaryChain { + base: mul_base, + steps: mul_steps, + .. + } = &steps[0].expr + else { + panic!("expected mul chain"); + }; + assert_eq!(number_raw(mul_base), "2"); + assert_eq!(mul_steps.len(), 1); + assert_eq!(mul_steps[0].op, ast::BinOp::Mul); + assert_eq!(number_raw(&mul_steps[0].expr), "3"); + let ast::Expr::BinaryChain { + base: div_base, + steps: div_steps, + .. + } = &steps[1].expr + else { + panic!("expected div chain"); + }; + assert_eq!(number_raw(div_base), "4"); + assert_eq!(div_steps[0].op, ast::BinOp::Div); + assert_eq!(number_raw(&div_steps[0].expr), "5"); + + let powers = parse_resolve_drop(b"return 2^3^2"); + let ast::Expr::Binary { + op, left, right, .. + } = return_expr(&powers) + else { + panic!("power stays right-associative"); + }; + assert_eq!(*op, ast::BinOp::Pow); + assert_eq!(number_raw(left), "2"); + let ast::Expr::Binary { + op: inner_op, + left: inner_left, + right: inner_right, + .. + } = right.as_ref() + else { + panic!("inner power"); + }; + assert_eq!(*inner_op, ast::BinOp::Pow); + assert_eq!(number_raw(inner_left), "3"); + assert_eq!(number_raw(inner_right), "2"); + + let logic = parse_resolve_drop(b"return a and b and c"); + let ast::Expr::BinaryChain { base, steps, .. } = return_expr(&logic) else { + panic!("and chain"); + }; + assert!(name_is(base, "a")); + assert_eq!(steps.len(), 2); + assert_eq!(steps[0].op, ast::BinOp::And); + assert!(name_is(&steps[0].expr, "b")); + assert_eq!(steps[1].op, ast::BinOp::And); + assert!(name_is(&steps[1].expr, "c")); + + let mixed = parse_resolve_drop(b"return a and b or c"); + let ast::Expr::BinaryChain { base, steps, .. } = return_expr(&mixed) else { + panic!("or chain"); + }; + assert_eq!(steps.len(), 1); + assert_eq!(steps[0].op, ast::BinOp::Or); + assert!(name_is(&steps[0].expr, "c")); + let ast::Expr::BinaryChain { + base: and_base, + steps: and_steps, + .. + } = base.as_ref() + else { + panic!("and stays left of or"); + }; + assert!(name_is(and_base, "a")); + assert_eq!(and_steps[0].op, ast::BinOp::And); + assert!(name_is(&and_steps[0].expr, "b")); + + let grouped = parse_resolve_drop(b"return a+(b+c)"); + let ast::Expr::BinaryChain { steps, .. } = return_expr(&grouped) else { + panic!("outer add"); + }; + assert_eq!(steps.len(), 1); + let ast::Expr::Paren { inner, .. } = &steps[0].expr else { + panic!("paren is a boundary"); + }; + let ast::Expr::BinaryChain { + steps: inner_steps, .. + } = inner.as_ref() + else { + panic!("inner add"); + }; + assert_eq!(inner_steps.len(), 1); + assert!(name_is(&inner_steps[0].expr, "c")); +} + +#[test] +fn composite_suffix_keeps_order_and_boundaries() { + let chunk = parse_resolve_drop(b"return a.b[1]():m(2)"); + let expr = return_expr(&chunk); + assert!(expr.is_multi()); + assert_eq!(suffix_chain_nesting(expr), 1); + let ast::Expr::SuffixChain { base, steps, span } = expr else { + panic!("suffix chain"); + }; + assert!(name_is(base, "a")); + assert_eq!(span.start, 7); + assert_eq!(steps.len(), 4); + assert!(matches!( + &steps[0], + ast::Suffix::Field { name, nav: false, .. } if name.is("b") + )); + assert!(matches!(&steps[1], ast::Suffix::Index { nav: false, .. })); + assert!(matches!(&steps[2], ast::Suffix::Call { nav: false, .. })); + assert!(matches!( + &steps[3], + ast::Suffix::Method { method, receiver_nav: false, method_nav: false, .. } + if method.is("m") + )); + assert_eq!(steps[0].span().end, 10); + assert_eq!(steps[3].span(), *span); + + let paren = parse_resolve_drop(b"return (f.g())"); + let wrapped = return_expr(&paren); + assert!(!wrapped.is_multi()); + assert!(matches!(wrapped, ast::Expr::Paren { .. })); + + let calls = parse_resolve_drop(b"return f()()"); + assert!(return_expr(&calls).is_multi()); + assert_eq!(suffix_chain_nesting(return_expr(&calls)), 1); + + let outer_nav = parse_resolve_drop(b"a.b?.c = 1"); + match &outer_nav.body.stmts[0] { + Stmt::Assign { targets, .. } => { + assert!(targets[0].has_nav()); + assert!(matches!(&targets[0], ast::AssignTarget::Field { name, .. } if name.is("c"))); + } + _ => panic!("assign"), + } + let inner_nav = parse_resolve_drop(b"a?.b.c = 1"); + match &inner_nav.body.stmts[0] { + Stmt::Assign { targets, .. } => assert!(!targets[0].has_nav()), + _ => panic!("assign"), + } + + let imports = parse_resolve_drop(b"return require('a')+require('b')"); + let resolution = resolve::resolve(&imports); + assert_eq!(resolution.imports.len(), 2); + assert_eq!(resolution.imports[0].spec, b"a"); + assert_eq!(resolution.imports[1].spec, b"b"); + assert!(resolution.imports[0].call_span.start < resolution.imports[1].call_span.start); + + let method_import = parse_resolve_drop(b"return require('a').b('c')"); + let resolution = resolve::resolve(&method_import); + assert_eq!(resolution.imports.len(), 1); + assert_eq!(resolution.imports[0].spec, b"a"); +} + +#[test] +fn chain_syntax_errors_are_ordinary() { + expect_syntax_error(b"return 1 +", "expected expression"); + expect_syntax_error(b"return a.", "expected name"); + expect_syntax_error(b"a?.b, c = 1", "safe navigation"); + expect_syntax_error(b"f() = 1", "expected"); + + let mut trailing_add = joined("return ", "1", "+", 256); + trailing_add.push(b'+'); + expect_syntax_error(&trailing_add, "expected expression"); + + let mut trailing_field = joined("return a", ".b", "", 64); + trailing_field.push(b'.'); + expect_syntax_error(&trailing_field, "expected name"); +} + +#[test] +fn long_flat_chains_finish_on_the_default_test_thread() { + // libtest uses the default 2 MiB thread stack. Do not raise it. + let operands = 4096usize; + let adds = joined("return ", "1", "+", operands); + let chunk = parse_resolve_drop(&adds); + assert_add_chain(return_expr(&chunk), operands - 1); + drop(chunk); + + let fields = joined("return a", ".b", "", operands); + let chunk = parse_resolve_drop(&fields); + assert_field_chain(return_expr(&chunk), operands); + drop(chunk); + + let mut calls = b"return a".to_vec(); + for _ in 0..operands { + calls.extend_from_slice(b"()"); + } + let chunk = parse_resolve_drop(&calls); + let expr = return_expr(&chunk); + assert!(expr.is_multi()); + assert_eq!(suffix_chain_nesting(expr), 1); + let ast::Expr::SuffixChain { steps, .. } = expr else { + panic!("call chain"); + }; + assert_eq!(steps.len(), operands); + drop(chunk); + + // Locked LuaJIT load() accepts the add, field and call lengths above. + // An `and` chain was accepted at 10875 operands and rejected by 11000 + // as "control structure too long". That is a compiler limit, not a + // grammar limit, and is not encoded here. + let ands = joined("return ", "a", " and ", 12000); + let chunk = parse_resolve_drop(&ands); + let ast::Expr::BinaryChain { steps, .. } = return_expr(&chunk) else { + panic!("and chain"); + }; + assert_eq!(steps.len(), 11999); + assert!(steps.iter().all(|step| step.op == ast::BinOp::And)); + drop(chunk); + + if let Some(path) = configured_oracle() { + assert!( + oracle_accepts(&path, &adds), + "LuaJIT rejected the add chain" + ); + assert!( + oracle_accepts(&path, &fields), + "LuaJIT rejected the field chain" + ); + assert!( + oracle_accepts(&path, &calls), + "LuaJIT rejected the call chain" + ); + } +} From 04085f69dbacf9c0623de6679c7e13c233ef242a Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 18:16:15 +0800 Subject: [PATCH 004/225] fix(lua): clear strict clippy on the locked syntax frontend Collapse nested conditions that already had the same predicates, call stmt_span directly, and enumerate statements instead of a range. --- src/frontends/lua/lexer.rs | 15 +++++++-------- src/frontends/lua/parser.rs | 2 +- src/frontends/lua/resolve.rs | 31 ++++++++++++++----------------- 3 files changed, 22 insertions(+), 26 deletions(-) diff --git a/src/frontends/lua/lexer.rs b/src/frontends/lua/lexer.rs index 544ad22..d9210e6 100644 --- a/src/frontends/lua/lexer.rs +++ b/src/frontends/lua/lexer.rs @@ -189,10 +189,11 @@ impl<'a> Scan<'a> { fn finish_newline(&mut self) { let old = self.cur(); self.advance(); - if let Some(next) = self.cur() { - if Self::is_eol(next) && Some(next) != old { - self.advance(); - } + if let Some(next) = self.cur() + && Self::is_eol(next) + && Some(next) != old + { + self.advance(); } self.line = self.line.saturating_add(1); } @@ -1064,10 +1065,8 @@ fn classify_number(raw: &[u8]) -> Result { } } if p < raw.len() && (raw[p] | 0x20) == b'u' && (!saw_u || saw_ll) { - if !saw_u || saw_ll { - p += 1; - saw_u = true; - } + p += 1; + saw_u = true; } if saw_u && !saw_ll { return Err(()); diff --git a/src/frontends/lua/parser.rs b/src/frontends/lua/parser.rs index 9b003b8..79b7b17 100644 --- a/src/frontends/lua/parser.rs +++ b/src/frontends/lua/parser.rs @@ -201,7 +201,7 @@ impl<'a> Parser<'a> { let end = if stmts.is_empty() { start } else { - stmts.last().map(|stmt| stmt_span(stmt)).unwrap_or(start) + stmts.last().map(stmt_span).unwrap_or(start) }; Ok(Block { span: start.cover(end), diff --git a/src/frontends/lua/resolve.rs b/src/frontends/lua/resolve.rs index 074ffa3..40272c1 100644 --- a/src/frontends/lua/resolve.rs +++ b/src/frontends/lua/resolve.rs @@ -236,13 +236,11 @@ impl Cx { if is_loop { continue; } - if !function_root { - if let Some(parent) = self.scopes.last_mut() { - let mut propagated = jump; - propagated.slot = scope.start_local as u32; - parent.jumps.push(propagated); - continue; - } + if !function_root && let Some(parent) = self.scopes.last_mut() { + let mut propagated = jump; + propagated.slot = scope.start_local as u32; + parent.jumps.push(propagated); + continue; } if jump.kind == JumpKind::Break { self.resolution @@ -419,18 +417,17 @@ impl Cx { None }; let mut resolved = false; - if kind == JumpKind::Goto { - if let Some(label) = self + if kind == JumpKind::Goto + && let Some(label) = self .scopes .last() .and_then(|scope| scope.labels.iter().find(|label| label.name == name)) - { - let index = label.index; - if let Some(goto_index) = goto_index { - self.resolution.gotos[goto_index].target = Some(index); - } - resolved = true; + { + let index = label.index; + if let Some(goto_index) = goto_index { + self.resolution.gotos[goto_index].target = Some(index); } + resolved = true; } self.scopes.last_mut().expect("scope").jumps.push(JumpRec { kind, @@ -791,8 +788,8 @@ fn trailing_labels(block: &Block, adjust: bool) -> Vec { if !adjust { return flags; } - for index in 0..block.stmts.len() { - if !matches!(block.stmts[index], Stmt::Label { .. }) { + for (index, stmt) in block.stmts.iter().enumerate() { + if !matches!(stmt, Stmt::Label { .. }) { continue; } let rest_are_labels = block.stmts[index + 1..] From 87550fd281a3f587d06acc3042b40600d9259258 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 19:00:51 +0800 Subject: [PATCH 005/225] feat(lua): read top-level .rss links from the syntax tree The line scanner has no lexical state, so require text in a string, comment, or uncalled function becomes a static module edge. Keep that scanner on production LuaPlugin. The private walk only emits an unshadowed chunk-level local require of a .rss spec, with the existing namespace or named clause and the require( line. --- src/frontends/lua/imports.rs | 137 ++++++++ src/frontends/lua/mod.rs | 3 + src/lib.rs | 7 + .../compiler_lua_static_import_tests.rs | 304 ++++++++++++++++++ tests/compiler_tests.rs | 3 + 5 files changed, 454 insertions(+) create mode 100644 src/frontends/lua/imports.rs create mode 100644 tests/compiler/compiler_lua_static_import_tests.rs diff --git a/src/frontends/lua/imports.rs b/src/frontends/lua/imports.rs new file mode 100644 index 0000000..7b4cc27 --- /dev/null +++ b/src/frontends/lua/imports.rs @@ -0,0 +1,137 @@ +//! Top-level static `.rss` links for the new Lua lowerer and file hook. +//! +//! Production `LuaPlugin` still uses the line scanner. This walk uses the +//! parsed chunk so a string, comment, uncalled function, shadow, or alias +//! cannot enter the module graph. Path mapping stays in Core. + +use super::ast::{Args, AssignTarget, Expr, Stmt, Suffix}; +use super::lexer; +use super::parser; +use vm::{ImportClause, ModuleImport, NamedImport, ParseError, SourceError, SourcePathError}; + +pub(crate) fn static_module_imports(source: &str) -> Result, SourcePathError> { + let chunk = parser::parse_chunk(source.as_bytes()).map_err(syntax_to_path_error)?; + let mut imports = Vec::new(); + let mut require_shadowed = false; + for stmt in &chunk.body.stmts { + if !require_shadowed && let Some(import) = local_static_link(source, stmt) { + imports.push(import); + } + if binds_require(stmt) { + require_shadowed = true; + } + } + Ok(imports) +} + +fn syntax_to_path_error(err: lexer::SyntaxError) -> SourcePathError { + SourcePathError::Source(SourceError::Parse(ParseError::at_line( + usize::try_from(err.line).unwrap_or(usize::MAX), + err.message, + ))) +} + +fn local_static_link(source: &str, stmt: &Stmt) -> Option { + let Stmt::Local { names, values, .. } = stmt else { + return None; + }; + let [local_name] = names.as_slice() else { + return None; + }; + let [value, ..] = values.exprs.as_slice() else { + return None; + }; + let link = require_link(value)?; + let alias = utf8_bytes(&local_name.name.bytes)?; + let clause = match link.member { + None => ImportClause::Namespace(alias), + Some(member) => ImportClause::Named(vec![NamedImport { + imported: member.clone(), + local: member, + }]), + }; + Some(ModuleImport { + spec: link.spec, + line: line_at(source, link.name_start), + clause, + }) +} + +struct RequireLink { + name_start: u32, + spec: String, + member: Option, +} + +fn require_link(expr: &Expr) -> Option { + let Expr::SuffixChain { base, steps, .. } = expr else { + return None; + }; + let Expr::Name { name, span, .. } = base.as_ref() else { + return None; + }; + if !name.is("require") { + return None; + } + match steps.as_slice() { + [ + Suffix::Call { + args, nav: false, .. + }, + ] => Some(RequireLink { + name_start: span.start, + spec: rss_spec(args)?, + member: None, + }), + [ + Suffix::Call { + args, nav: false, .. + }, + Suffix::Field { + name, nav: false, .. + }, + ] => Some(RequireLink { + name_start: span.start, + spec: rss_spec(args)?, + member: Some(utf8_bytes(&name.bytes)?), + }), + _ => None, + } +} + +fn rss_spec(args: &Args) -> Option { + let Args::List(list) = args else { + return None; + }; + let [Expr::String { bytes, .. }] = list.exprs.as_slice() else { + return None; + }; + let spec = utf8_bytes(bytes)?; + spec.ends_with(".rss").then_some(spec) +} + +fn binds_require(stmt: &Stmt) -> bool { + match stmt { + Stmt::Local { names, .. } => names.iter().any(|local| local.name.is("require")), + Stmt::LocalFunction { name, .. } => name.is("require"), + Stmt::Function { name, .. } => { + name.method.is_none() && name.segments.len() == 1 && name.segments[0].is("require") + } + Stmt::Assign { targets, .. } => targets.iter().any(assign_target_is_require), + _ => false, + } +} + +fn assign_target_is_require(target: &AssignTarget) -> bool { + matches!(target, AssignTarget::Name(name) if name.is("require")) +} + +fn utf8_bytes(bytes: &[u8]) -> Option { + String::from_utf8(bytes.to_vec()).ok() +} + +fn line_at(source: &str, offset: u32) -> usize { + let end = usize::try_from(offset).unwrap_or(source.len()); + let prefix = source.get(..end.min(source.len())).unwrap_or(""); + prefix.bytes().filter(|byte| *byte == b'\n').count() + 1 +} diff --git a/src/frontends/lua/mod.rs b/src/frontends/lua/mod.rs index 08756ae..9665659 100644 --- a/src/frontends/lua/mod.rs +++ b/src/frontends/lua/mod.rs @@ -1,4 +1,7 @@ mod expr; +mod imports; + +pub(crate) use imports::static_module_imports; mod support; // Private syntax modules for the locked LuaJIT 5.2-compat grammar. diff --git a/src/lib.rs b/src/lib.rs index 9479a2d..025b94c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -77,6 +77,13 @@ impl SourcePlugin for LuaPlugin { } } +/// Candidate import list for the new Lua lowerer and file hook. +/// +/// Production `LuaPlugin` does not call this. Path mapping stays in Core. +pub fn lua_static_module_imports(source: &str) -> Result, SourcePathError> { + lua::static_module_imports(source) +} + pub fn compile_options() -> vm::CompileSourceFileOptions { plugins() .into_iter() diff --git a/tests/compiler/compiler_lua_static_import_tests.rs b/tests/compiler/compiler_lua_static_import_tests.rs new file mode 100644 index 0000000..8ce2f85 --- /dev/null +++ b/tests/compiler/compiler_lua_static_import_tests.rs @@ -0,0 +1,304 @@ +#[allow(dead_code)] +#[path = "../common/mod.rs"] +mod common; +use common::*; +use std::fs; +use std::path::{Path, PathBuf}; +use vm::{ + FrontendImportSyntax, FrontendIr, ImportClause, ModuleImport, ParseError, SourceFlavor, + SourcePathError, SourcePlugin, +}; + +/// Test-only hook. Production `LuaPlugin` stays on the line scanner. +struct CandidateLuaPlugin; + +static CANDIDATE_LUA_PLUGIN: CandidateLuaPlugin = CandidateLuaPlugin; + +impl SourcePlugin for CandidateLuaPlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &["lua"] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + pd_vm_compat_frontends::LUA_PLUGIN.parse_source(source) + } + + fn parse_module_imports( + &self, + source: &str, + _path: &Path, + ) -> Result, SourcePathError> { + pd_vm_compat_frontends::lua_static_module_imports(source) + } +} + +fn candidate_options() -> CompileSourceFileOptions { + CompileSourceFileOptions::new().with_source_plugin(&CANDIDATE_LUA_PLUGIN) +} + +fn owned_root(label: &str) -> PathBuf { + namespace_case_root(&format!("lua_static_import_{label}")) +} + +fn write_present(root: &Path) { + fs::write(root.join("present.rss"), "pub fn tag() { 41 }\n").expect("present module"); +} + +fn static_imports(source: &str) -> Vec { + pd_vm_compat_frontends::lua_static_module_imports(source).expect("static import scan") +} + +fn assert_namespace(import: &ModuleImport, spec: &str, alias: &str, line: usize) { + assert_eq!(import.spec, spec, "spec text is not a resolved path"); + assert_eq!(import.line, line); + match &import.clause { + ImportClause::Namespace(name) => assert_eq!(name, alias), + other => panic!("expected namespace clause, got {other:?}"), + } +} + +fn assert_named(import: &ModuleImport, spec: &str, imported: &str, local: &str, line: usize) { + assert_eq!(import.spec, spec, "spec text is not a resolved path"); + assert_eq!(import.line, line); + match &import.clause { + ImportClause::Named(named) => { + assert_eq!(named.len(), 1); + assert_eq!(named[0].imported, imported); + assert_eq!(named[0].local, local); + } + other => panic!("expected named clause, got {other:?}"), + } +} + +fn specs(imports: &[ModuleImport]) -> Vec<&str> { + imports.iter().map(|import| import.spec.as_str()).collect() +} + +fn compile_candidate(path: &Path) -> Result { + compile_source_file_with_options(path, candidate_options()) +} + +fn assert_core_did_not_read_missing_module(err: &SourcePathError) { + if let SourcePathError::Io(io) = err { + panic!("Core attempted a module read ({io}); fake dependency entered the static graph"); + } +} + +fn expect_load_error( + result: Result, + what: &str, +) -> SourcePathError { + match result { + Ok(_) => panic!("{what}: expected failure, compile succeeded"), + Err(err) => err, + } +} + +fn run_tag(path: &Path) -> Vec { + let compiled = compile_candidate(path).expect("candidate hook should compile"); + let mut vm = Vm::new(compiled.program); + let status = vm.run().expect("vm should run"); + assert_eq!(status, VmStatus::Halted); + vm.stack().to_vec() +} + +#[test] +fn candidate_runs_present_rss_and_ignores_string_require() { + let root = owned_root("present_string_pair"); + write_present(&root); + let main_path = root.join("main.lua"); + let source = "\ +local quoted = \"require('./absent.rss')\"\n\ +local m = require(\"./present.rss\")\n\ +m.tag()\n"; + fs::write(&main_path, source).expect("lua source"); + + let imports = static_imports(source); + assert_eq!(specs(&imports), vec!["./present.rss"]); + assert_namespace(&imports[0], "./present.rss", "m", 2); + assert_eq!(run_tag(&main_path), vec![Value::Int(41)]); +} + +#[test] +fn candidate_missing_rss_link_is_core_io_failure() { + let root = owned_root("missing_rss"); + let main_path = root.join("main.lua"); + let source = "local m = require(\"./absent.rss\")\nm.tag()\n"; + fs::write(&main_path, source).expect("lua source"); + + let imports = static_imports(source); + assert_eq!(specs(&imports), vec!["./absent.rss"]); + assert_namespace(&imports[0], "./absent.rss", "m", 1); + + let err = expect_load_error(compile_candidate(&main_path), "missing static link"); + match err { + SourcePathError::Io(io) => { + assert_eq!( + io.kind(), + std::io::ErrorKind::NotFound, + "path mapping belongs to Core; the failure layer is the module read, got {io}" + ); + } + other => panic!("expected Core I/O, got {other}"), + } +} + +#[test] +fn candidate_does_not_load_long_comment_require() { + let root = owned_root("long_comment"); + let main_path = root.join("main.lua"); + let source = "--[=[\nrequire(\"./absent.rss\")\n]=]\nlocal n = 41\n"; + fs::write(&main_path, source).expect("lua source"); + + assert!(static_imports(source).is_empty()); + let err = expect_load_error( + compile_candidate(&main_path), + "long comment must not become a module read", + ); + assert_core_did_not_read_missing_module(&err); +} + +#[test] +fn candidate_does_not_load_require_inside_uncalled_function() { + let root = owned_root("uncalled"); + write_present(&root); + let main_path = root.join("main.lua"); + let source = "\ +local function unused()\n\ + return require(\"./absent.rss\")\n\ +end\n\ +local m = require(\"./present.rss\")\n\ +m.tag()\n"; + fs::write(&main_path, source).expect("lua source"); + + let imports = static_imports(source); + assert_eq!(specs(&imports), vec!["./present.rss"]); + match compile_candidate(&main_path) { + Ok(compiled) => { + let mut vm = Vm::new(compiled.program); + let status = vm.run().expect("vm should run"); + assert_eq!(status, VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Int(41)]); + } + Err(err) => assert_core_did_not_read_missing_module(&err), + } +} + +#[test] +fn candidate_does_not_load_shadowed_require() { + let root = owned_root("shadow"); + let main_path = root.join("main.lua"); + let source = "\ +local function require(name)\n\ + return name\n\ +end\n\ +local value = require(\"./absent.rss\")\n\ +local n = 41\n"; + fs::write(&main_path, source).expect("lua source"); + + assert!( + specs(&static_imports(source)).is_empty(), + "shadowed require is a local call, not a static link" + ); + match compile_candidate(&main_path) { + Ok(compiled) => { + let mut vm = Vm::new(compiled.program); + let status = vm.run().expect("vm should run"); + assert_eq!(status, VmStatus::Halted); + } + Err(err) => assert_core_did_not_read_missing_module(&err), + } +} + +#[test] +fn candidate_does_not_load_require_alias() { + let root = owned_root("alias"); + let main_path = root.join("main.lua"); + let source = "\ +local r = require\n\ +local value = r(\"./absent.rss\")\n\ +local n = 41\n"; + fs::write(&main_path, source).expect("lua source"); + + assert!(static_imports(source).is_empty()); + let err = expect_load_error( + compile_candidate(&main_path), + "alias call must not become a module read", + ); + assert_core_did_not_read_missing_module(&err); +} + +#[test] +fn candidate_does_not_load_ordinary_dynamic_require() { + let root = owned_root("dynamic"); + write_present(&root); + let main_path = root.join("main.lua"); + let source = "\ +require(\"./absent.rss\")\n\ +local m = require(\"./present.rss\")\n\ +m.tag()\n"; + fs::write(&main_path, source).expect("lua source"); + + let imports = static_imports(source); + assert_eq!(specs(&imports), vec!["./present.rss"]); + assert_eq!(run_tag(&main_path), vec![Value::Int(41)]); +} + +#[test] +fn static_link_keeps_multiline_require_line() { + let source = "\nlocal m = require(\n \"./present.rss\")\n"; + let imports = static_imports(source); + assert_eq!(imports.len(), 1); + assert_namespace(&imports[0], "./present.rss", "m", 2); +} + +#[test] +fn static_link_keeps_named_member_clause() { + let source = "local tag = require(\"./left.rss\").tag\n"; + let imports = static_imports(source); + assert_eq!(imports.len(), 1); + assert_named(&imports[0], "./left.rss", "tag", "tag", 1); +} + +#[test] +fn candidate_named_missing_member_is_core_io_failure() { + let root = owned_root("named_missing"); + let main_path = root.join("main.lua"); + let source = "local tag = require(\"./absent.rss\").tag\n"; + fs::write(&main_path, source).expect("lua source"); + + let err = expect_load_error(compile_candidate(&main_path), "named static link"); + match err { + SourcePathError::Io(io) => assert_eq!(io.kind(), std::io::ErrorKind::NotFound), + other => panic!("expected Core I/O for the named link, got {other}"), + } +} + +#[test] +fn ordinary_host_require_is_not_a_static_rss_link() { + let source = "local runtime = require(\"runtime\")\nlocal json = require(\"json\")\n"; + assert!( + static_imports(source).is_empty(), + "host require stays off the file static graph" + ); +} + +#[test] +fn incomplete_require_is_not_loaded_as_a_static_link() { + let root = owned_root("incomplete"); + let main_path = root.join("main.lua"); + let source = "local m = require(\"./absent.rss\"\n"; + fs::write(&main_path, source).expect("lua source"); + + assert!(pd_vm_compat_frontends::lua_static_module_imports(source).is_err()); + let err = expect_load_error(compile_candidate(&main_path), "incomplete call"); + assert_core_did_not_read_missing_module(&err); +} diff --git a/tests/compiler_tests.rs b/tests/compiler_tests.rs index 6a9e9ee..f9caa84 100644 --- a/tests/compiler_tests.rs +++ b/tests/compiler_tests.rs @@ -6,5 +6,8 @@ mod compiler_javascript_tests; #[path = "compiler/compiler_lua_tests.rs"] mod compiler_lua_tests; +#[path = "compiler/compiler_lua_static_import_tests.rs"] +mod compiler_lua_static_import_tests; + #[path = "compiler/compiler_luajit_oracle_tests.rs"] mod compiler_luajit_oracle_tests; From 66ea83030d3b0b60501bb729d1f2192dd884a30d Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 19:41:28 +0800 Subject: [PATCH 006/225] fix(lua): bind named static imports to the declared alias The candidate list was a public export used only by tests, and a named require stored the export as the local binding. Core binds that local name. Keep the scan in the test include, and do not treat the old lowerer as a dynamic require engine. --- src/frontends/lua/imports.rs | 32 +- src/frontends/lua/mod.rs | 3 - src/lib.rs | 7 - .../compiler_lua_static_import_tests.rs | 574 ++++++++++++++---- 4 files changed, 482 insertions(+), 134 deletions(-) diff --git a/src/frontends/lua/imports.rs b/src/frontends/lua/imports.rs index 7b4cc27..d05f673 100644 --- a/src/frontends/lua/imports.rs +++ b/src/frontends/lua/imports.rs @@ -1,15 +1,16 @@ -//! Top-level static `.rss` links for the new Lua lowerer and file hook. +//! Top-level static RSS links for the new Lua lowerer and file hook. //! //! Production `LuaPlugin` still uses the line scanner. This walk uses the -//! parsed chunk so a string, comment, uncalled function, shadow, or alias -//! cannot enter the module graph. Path mapping stays in Core. +//! parsed chunk so a string, comment, uncalled function, shadow, or ordinary +//! call cannot enter the module graph. A named link binds the declared local +//! alias. Path mapping stays in Core, including an extensionless relative spec. use super::ast::{Args, AssignTarget, Expr, Stmt, Suffix}; use super::lexer; use super::parser; use vm::{ImportClause, ModuleImport, NamedImport, ParseError, SourceError, SourcePathError}; -pub(crate) fn static_module_imports(source: &str) -> Result, SourcePathError> { +pub(super) fn static_module_imports(source: &str) -> Result, SourcePathError> { let chunk = parser::parse_chunk(source.as_bytes()).map_err(syntax_to_path_error)?; let mut imports = Vec::new(); let mut require_shadowed = false; @@ -46,8 +47,10 @@ fn local_static_link(source: &str, stmt: &Stmt) -> Option { let clause = match link.member { None => ImportClause::Namespace(alias), Some(member) => ImportClause::Named(vec![NamedImport { - imported: member.clone(), - local: member, + // Core binds this local name. The export stays in `imported`, + // matching the line scanner's declared-name split. + imported: member, + local: alias, }]), }; Some(ModuleImport { @@ -107,7 +110,22 @@ fn rss_spec(args: &Args) -> Option { return None; }; let spec = utf8_bytes(bytes)?; - spec.ends_with(".rss").then_some(spec) + is_static_rss_spec(&spec).then_some(spec) +} + +fn is_static_rss_spec(spec: &str) -> bool { + if spec.ends_with(".rss") { + return true; + } + // Pinned Core appends `.rss` when a relative specifier has no extension. + // Keep the source text. Explicit `.lua`, host names, and other short + // forms stay ordinary calls. + let relative = spec.starts_with("./") || spec.starts_with("../"); + if !relative { + return false; + } + let file = spec.rsplit('/').next().unwrap_or(spec); + !file.is_empty() && !file.contains('.') } fn binds_require(stmt: &Stmt) -> bool { diff --git a/src/frontends/lua/mod.rs b/src/frontends/lua/mod.rs index 9665659..08756ae 100644 --- a/src/frontends/lua/mod.rs +++ b/src/frontends/lua/mod.rs @@ -1,7 +1,4 @@ mod expr; -mod imports; - -pub(crate) use imports::static_module_imports; mod support; // Private syntax modules for the locked LuaJIT 5.2-compat grammar. diff --git a/src/lib.rs b/src/lib.rs index 025b94c..9479a2d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -77,13 +77,6 @@ impl SourcePlugin for LuaPlugin { } } -/// Candidate import list for the new Lua lowerer and file hook. -/// -/// Production `LuaPlugin` does not call this. Path mapping stays in Core. -pub fn lua_static_module_imports(source: &str) -> Result, SourcePathError> { - lua::static_module_imports(source) -} - pub fn compile_options() -> vm::CompileSourceFileOptions { plugins() .into_iter() diff --git a/tests/compiler/compiler_lua_static_import_tests.rs b/tests/compiler/compiler_lua_static_import_tests.rs index 8ce2f85..c29c4a2 100644 --- a/tests/compiler/compiler_lua_static_import_tests.rs +++ b/tests/compiler/compiler_lua_static_import_tests.rs @@ -1,12 +1,39 @@ +//! Candidate static-link evidence. +//! +//! A static link is a chunk-top, direct, unshadowed, single local whose value +//! is a `require` of a `.rss` spec or a relative extensionless spec. Ordinary +//! calls stay in the AST. The old lowerer is not a dynamic require engine: +//! Halted, or any non-I/O error, is not execution success. +//! +//! The candidate module is included with the same `#[path]` layout as the +//! LuaJIT oracle tests. It is not a library export. +//! +//! Not static edges, and not implemented as runtime require: +//! bare `present`, absolute `/present`, hidden `./.present`, trailing-dot +//! `./present.`, explicit `.lua`, host names, a backslash separator, a newline +//! inside the string, and `require` split across tokens. A newline inside the +//! call parentheses is covered. + #[allow(dead_code)] #[path = "../common/mod.rs"] mod common; use common::*; + +#[path = "../../src/frontends/lua/ast.rs"] +mod ast; +#[path = "../../src/frontends/lua/imports.rs"] +mod imports; +#[path = "../../src/frontends/lua/lexer.rs"] +mod lexer; +#[path = "../../src/frontends/lua/parser.rs"] +mod parser; + use std::fs; use std::path::{Path, PathBuf}; + use vm::{ - FrontendImportSyntax, FrontendIr, ImportClause, ModuleImport, ParseError, SourceFlavor, - SourcePathError, SourcePlugin, + FrontendImportSyntax, FrontendIr, ImportClause, ModuleImport, ParseError, SourceError, + SourceFlavor, SourcePathError, SourcePlugin, }; /// Test-only hook. Production `LuaPlugin` stays on the line scanner. @@ -36,7 +63,7 @@ impl SourcePlugin for CandidateLuaPlugin { source: &str, _path: &Path, ) -> Result, SourcePathError> { - pd_vm_compat_frontends::lua_static_module_imports(source) + imports::static_module_imports(source) } } @@ -52,8 +79,14 @@ fn write_present(root: &Path) { fs::write(root.join("present.rss"), "pub fn tag() { 41 }\n").expect("present module"); } +fn write_source(root: &Path, name: &str, source: &str) -> PathBuf { + let path = root.join(name); + fs::write(&path, source).expect("source"); + path +} + fn static_imports(source: &str) -> Vec { - pd_vm_compat_frontends::lua_static_module_imports(source).expect("static import scan") + imports::static_module_imports(source).expect("static import scan") } fn assert_namespace(import: &ModuleImport, spec: &str, alias: &str, line: usize) { @@ -86,10 +119,8 @@ fn compile_candidate(path: &Path) -> Result Result { + compile_source_file_with_options(path, pd_vm_compat_frontends::compile_options()) } fn expect_load_error( @@ -102,154 +133,277 @@ fn expect_load_error( } } -fn run_tag(path: &Path) -> Vec { - let compiled = compile_candidate(path).expect("candidate hook should compile"); +fn parse_message(err: &SourcePathError) -> &str { + match err { + SourcePathError::Source(SourceError::Parse(parse)) => parse.message.as_str(), + SourcePathError::SourceWithMap { + error: SourceError::Parse(parse), + .. + } => parse.message.as_str(), + other => panic!("expected a parse error, got {other:?}"), + } +} + +fn assert_not_found(err: &SourcePathError, what: &str) { + match err { + SourcePathError::Io(io) => { + assert_eq!( + io.kind(), + std::io::ErrorKind::NotFound, + "{what}: path mapping belongs to Core; the failure is the module read, got {io}" + ); + } + other => panic!("{what}: expected Io(NotFound), got {other:?}"), + } +} + +fn halted_stack(compiled: vm::CompiledProgram, what: &str) -> Vec { let mut vm = Vm::new(compiled.program); - let status = vm.run().expect("vm should run"); - assert_eq!(status, VmStatus::Halted); + let status = vm + .run() + .unwrap_or_else(|err| panic!("{what}: vm run failed: {err}")); + assert_eq!(status, VmStatus::Halted, "{what}"); vm.stack().to_vec() } +fn run_candidate(path: &Path, what: &str) -> Vec { + let compiled = compile_candidate(path).unwrap_or_else(|err| panic!("{what}: {err:?}")); + halted_stack(compiled, what) +} + +fn run_production(path: &Path, what: &str) -> Vec { + let compiled = compile_production(path).unwrap_or_else(|err| panic!("{what}: {err:?}")); + halted_stack(compiled, what) +} + +fn parsed(source: &str) -> ast::Chunk { + parser::parse_chunk(source.as_bytes()).expect("fixture parses") +} + +fn require_spec(expr: &ast::Expr) -> Option { + let ast::Expr::SuffixChain { base, steps, .. } = expr else { + return None; + }; + let ast::Expr::Name { name, .. } = base.as_ref() else { + return None; + }; + if !name.is("require") { + return None; + } + let [ast::Suffix::Call { args, .. }, ..] = steps.as_slice() else { + return None; + }; + let ast::Args::List(list) = args else { + return None; + }; + let [ast::Expr::String { bytes, .. }] = list.exprs.as_slice() else { + return None; + }; + String::from_utf8(bytes.clone()).ok() +} + +fn collect_require_specs(stmts: &[ast::Stmt], out: &mut Vec) { + for stmt in stmts { + match stmt { + ast::Stmt::Local { values, .. } | ast::Stmt::Assign { values, .. } => { + for expr in &values.exprs { + if let Some(spec) = require_spec(expr) { + out.push(spec); + } + } + } + ast::Stmt::Call { call, .. } => { + if let Some(spec) = require_spec(call) { + out.push(spec); + } + } + ast::Stmt::Return { values, .. } => { + for expr in &values.exprs { + if let Some(spec) = require_spec(expr) { + out.push(spec); + } + } + } + ast::Stmt::LocalFunction { func, .. } => { + collect_require_specs(&func.body.stmts, out); + } + ast::Stmt::Function { body, .. } => collect_require_specs(&body.body.stmts, out), + ast::Stmt::Do { body, .. } => collect_require_specs(&body.stmts, out), + _ => {} + } + } +} + +fn require_specs(source: &str) -> Vec { + let chunk = parsed(source); + let mut specs = Vec::new(); + collect_require_specs(&chunk.body.stmts, &mut specs); + specs +} + +const LOWERER_UNSUPPORTED: &str = "lua direct lowering does not yet support this construct"; + #[test] fn candidate_runs_present_rss_and_ignores_string_require() { let root = owned_root("present_string_pair"); write_present(&root); - let main_path = root.join("main.lua"); - let source = "\ -local quoted = \"require('./absent.rss')\"\n\ -local m = require(\"./present.rss\")\n\ -m.tag()\n"; - fs::write(&main_path, source).expect("lua source"); + let source = "local quoted = \"require('./absent.rss')\"\nlocal m = require(\"./present.rss\")\nm.tag()\n"; + let main_path = write_source(&root, "main.lua", source); let imports = static_imports(source); assert_eq!(specs(&imports), vec!["./present.rss"]); assert_namespace(&imports[0], "./present.rss", "m", 2); - assert_eq!(run_tag(&main_path), vec![Value::Int(41)]); + assert_eq!( + require_specs(source), + vec!["./present.rss"], + "the quoted require is a string, not a call" + ); + assert_eq!( + run_candidate(&main_path, "namespace link"), + vec![Value::Int(41)] + ); } #[test] fn candidate_missing_rss_link_is_core_io_failure() { let root = owned_root("missing_rss"); - let main_path = root.join("main.lua"); let source = "local m = require(\"./absent.rss\")\nm.tag()\n"; - fs::write(&main_path, source).expect("lua source"); + let main_path = write_source(&root, "main.lua", source); let imports = static_imports(source); assert_eq!(specs(&imports), vec!["./absent.rss"]); assert_namespace(&imports[0], "./absent.rss", "m", 1); - let err = expect_load_error(compile_candidate(&main_path), "missing static link"); - match err { - SourcePathError::Io(io) => { - assert_eq!( - io.kind(), - std::io::ErrorKind::NotFound, - "path mapping belongs to Core; the failure layer is the module read, got {io}" - ); - } - other => panic!("expected Core I/O, got {other}"), - } + assert_not_found(&err, "missing static link"); } #[test] -fn candidate_does_not_load_long_comment_require() { - let root = owned_root("long_comment"); - let main_path = root.join("main.lua"); +fn long_comment_stays_out_of_the_candidate_graph() { let source = "--[=[\nrequire(\"./absent.rss\")\n]=]\nlocal n = 41\n"; - fs::write(&main_path, source).expect("lua source"); - assert!(static_imports(source).is_empty()); - let err = expect_load_error( - compile_candidate(&main_path), - "long comment must not become a module read", + assert!( + require_specs(source).is_empty(), + "the new parser consumes the long comment" + ); + + let root = owned_root("long_comment"); + let main_path = write_source(&root, "main.lua", source); + let err = expect_load_error(compile_candidate(&main_path), "long comment lowerer"); + assert_eq!( + parse_message(&err), + LOWERER_UNSUPPORTED, + "old lowerer does not understand --[=[; this is not execution success" + ); + + let production = expect_load_error( + compile_production(&main_path), + "old scanner mis-reads the long comment", + ); + assert_not_found( + &production, + "production line scanner still treats the comment body as a require", ); - assert_core_did_not_read_missing_module(&err); } #[test] -fn candidate_does_not_load_require_inside_uncalled_function() { - let root = owned_root("uncalled"); - write_present(&root); - let main_path = root.join("main.lua"); - let source = "\ -local function unused()\n\ - return require(\"./absent.rss\")\n\ -end\n\ -local m = require(\"./present.rss\")\n\ -m.tag()\n"; - fs::write(&main_path, source).expect("lua source"); - +fn uncalled_function_require_stays_in_the_ast() { + let source = "local function unused()\n return require(\"./absent.rss\")\nend\nlocal m = require(\"./present.rss\")\nm.tag()\n"; let imports = static_imports(source); assert_eq!(specs(&imports), vec!["./present.rss"]); - match compile_candidate(&main_path) { - Ok(compiled) => { - let mut vm = Vm::new(compiled.program); - let status = vm.run().expect("vm should run"); - assert_eq!(status, VmStatus::Halted); - assert_eq!(vm.stack(), &[Value::Int(41)]); - } - Err(err) => assert_core_did_not_read_missing_module(&err), - } + assert_eq!( + require_specs(source), + vec!["./absent.rss", "./present.rss"], + "the inner require remains an ordinary call" + ); + + let root = owned_root("uncalled"); + write_present(&root); + let main_path = write_source(&root, "main.lua", source); + let err = expect_load_error(compile_candidate(&main_path), "uncalled require"); + assert_eq!( + parse_message(&err), + "unknown function 'require'", + "old lowerer cannot execute the inner require; do not treat this as a dynamic success" + ); } #[test] -fn candidate_does_not_load_shadowed_require() { - let root = owned_root("shadow"); - let main_path = root.join("main.lua"); - let source = "\ -local function require(name)\n\ - return name\n\ -end\n\ -local value = require(\"./absent.rss\")\n\ -local n = 41\n"; - fs::write(&main_path, source).expect("lua source"); +fn shadowed_require_is_not_a_static_link() { + let source = "local function require(name)\n return name\nend\nlocal value = require(\"./absent.rss\")\nlocal n = 41\n"; + assert!(specs(&static_imports(source)).is_empty()); + assert_eq!(require_specs(source), vec!["./absent.rss"]); + match &parsed(source).body.stmts[0] { + ast::Stmt::LocalFunction { name, .. } => assert!(name.is("require")), + other => panic!("shadow must be a local function, got {other:?}"), + } - assert!( - specs(&static_imports(source)).is_empty(), - "shadowed require is a local call, not a static link" + let root = owned_root("shadow"); + let main_path = write_source(&root, "main.lua", source); + let production = + expect_load_error(compile_production(&main_path), "old scanner ignores shadow"); + assert_not_found( + &production, + "production line scanner still links a shadowed require", ); - match compile_candidate(&main_path) { - Ok(compiled) => { - let mut vm = Vm::new(compiled.program); - let status = vm.run().expect("vm should run"); - assert_eq!(status, VmStatus::Halted); - } - Err(err) => assert_core_did_not_read_missing_module(&err), - } } #[test] -fn candidate_does_not_load_require_alias() { - let root = owned_root("alias"); - let main_path = root.join("main.lua"); - let source = "\ -local r = require\n\ -local value = r(\"./absent.rss\")\n\ -local n = 41\n"; - fs::write(&main_path, source).expect("lua source"); - +fn require_name_alias_is_not_a_static_link() { + let source = "local r = require\nlocal value = r(\"./absent.rss\")\nlocal n = 41\n"; assert!(static_imports(source).is_empty()); - let err = expect_load_error( - compile_candidate(&main_path), - "alias call must not become a module read", + assert!( + require_specs(source).is_empty(), + "r(...) is not a require call in the AST" ); - assert_core_did_not_read_missing_module(&err); + + let root = owned_root("require_alias"); + let main_path = write_source(&root, "main.lua", source); + let err = expect_load_error(compile_candidate(&main_path), "require alias"); + assert_eq!(parse_message(&err), LOWERER_UNSUPPORTED); } #[test] -fn candidate_does_not_load_ordinary_dynamic_require() { - let root = owned_root("dynamic"); - write_present(&root); - let main_path = root.join("main.lua"); - let source = "\ -require(\"./absent.rss\")\n\ -local m = require(\"./present.rss\")\n\ -m.tag()\n"; - fs::write(&main_path, source).expect("lua source"); +fn assignment_require_is_not_a_static_link() { + let source = "m.tag = require(\"./absent.rss\")\n"; + assert!(static_imports(source).is_empty()); + match &parsed(source).body.stmts[0] { + ast::Stmt::Assign { + targets, values, .. + } => { + assert!(!targets[0].has_nav()); + assert!(targets[0].span().end > targets[0].span().start); + assert!(values.tail_multi()); + assert!(values.exprs[0].is_multi()); + assert_eq!( + require_spec(&values.exprs[0]).as_deref(), + Some("./absent.rss") + ); + } + other => panic!("ordinary assignment must stay in the AST, got {other:?}"), + } +} +#[test] +fn bare_require_stays_a_call_and_is_not_a_static_link() { + let source = "require(\"./absent.rss\")\nlocal m = require(\"./present.rss\")\nm.tag()\n"; let imports = static_imports(source); assert_eq!(specs(&imports), vec!["./present.rss"]); - assert_eq!(run_tag(&main_path), vec![Value::Int(41)]); + assert_eq!(require_specs(source), vec!["./absent.rss", "./present.rss"]); + match &parsed(source).body.stmts[0] { + ast::Stmt::Call { call, .. } => { + assert_eq!(require_spec(call).as_deref(), Some("./absent.rss")); + } + other => panic!("bare require must remain a call statement, got {other:?}"), + } + + let root = owned_root("bare"); + write_present(&root); + let main_path = write_source(&root, "main.lua", source); + let production = expect_load_error(compile_production(&main_path), "old scanner bare require"); + assert_not_found( + &production, + "production line scanner still eagerly links a bare require", + ); } #[test] @@ -268,20 +422,97 @@ fn static_link_keeps_named_member_clause() { assert_named(&imports[0], "./left.rss", "tag", "tag", 1); } +#[test] +fn static_link_names_the_declared_alias_not_the_export() { + let source = "local different = require(\"./present.rss\").tag\n"; + let imports = static_imports(source); + assert_eq!(imports.len(), 1); + assert_named(&imports[0], "./present.rss", "tag", "different", 1); +} + #[test] fn candidate_named_missing_member_is_core_io_failure() { let root = owned_root("named_missing"); - let main_path = root.join("main.lua"); let source = "local tag = require(\"./absent.rss\").tag\n"; - fs::write(&main_path, source).expect("lua source"); - + let main_path = write_source(&root, "main.lua", source); let err = expect_load_error(compile_candidate(&main_path), "named static link"); + assert_not_found(&err, "named missing module"); +} + +#[test] +fn named_missing_export_is_invalid_import_syntax() { + let root = owned_root("missing_export"); + write_present(&root); + let source = "local missing = require(\"./present.rss\").gone\n"; + let imports = static_imports(source); + assert_named(&imports[0], "./present.rss", "gone", "missing", 1); + let main_path = write_source(&root, "main.lua", source); + let err = expect_load_error(compile_candidate(&main_path), "missing export"); match err { - SourcePathError::Io(io) => assert_eq!(io.kind(), std::io::ErrorKind::NotFound), - other => panic!("expected Core I/O for the named link, got {other}"), + SourcePathError::InvalidImportSyntax { + line, + message, + path, + } => { + assert_eq!(line, 1); + assert_eq!( + message, + "module './present.rss' has no public function 'gone'" + ); + assert_eq!( + path.file_name().and_then(|name| name.to_str()), + Some("main.lua") + ); + } + other => panic!("expected InvalidImportSyntax from Core's export check, got {other:?}"), } } +#[test] +fn alias_call_stops_in_the_old_lowerer() { + let source = "local different = require(\"./present.rss\").tag\ndifferent()\n"; + assert_named( + &static_imports(source)[0], + "./present.rss", + "tag", + "different", + 1, + ); + + let root = owned_root("alias_call"); + write_present(&root); + let main_path = write_source(&root, "main.lua", source); + let err = expect_load_error(compile_candidate(&main_path), "alias call"); + assert_eq!( + parse_message(&err), + "unknown function 'different'", + "old lowerer rejects the alias call before Core can bind it" + ); + let production = expect_load_error(compile_production(&main_path), "production alias call"); + assert_eq!(parse_message(&production), "unknown function 'different'"); +} + +/// Equivalent Core consumer for `local different = require("./present.rss").tag`. +/// +/// Not a Lua execution. Pinned Core `b1d6cffede77f49410bf63525f30b9a46b02dc01` +/// parses the alias in `src/compiler/parser/statements.rs:393-414` and binds +/// `NamedImport.local` in `src/compiler/source_loader/graph.rs:444-446`. +/// This test writes `alias_consumer.rss` next to `present.rss`. +#[test] +fn core_named_alias_consumer_runs_different_as_tag() { + let root = owned_root("alias_consumer"); + write_present(&root); + let source = "use self::present::{ tag as different };\ndifferent();\n"; + let consumer = write_source(&root, "alias_consumer.rss", source); + assert_eq!( + run_production( + &consumer, + "Core RSS consumer src/compiler/source_loader/graph.rs local binding" + ), + vec![Value::Int(41)] + ); +} + #[test] fn ordinary_host_require_is_not_a_static_rss_link() { let source = "local runtime = require(\"runtime\")\nlocal json = require(\"json\")\n"; @@ -292,13 +523,122 @@ fn ordinary_host_require_is_not_a_static_rss_link() { } #[test] -fn incomplete_require_is_not_loaded_as_a_static_link() { - let root = owned_root("incomplete"); - let main_path = root.join("main.lua"); +fn extensionless_relative_spec_stays_written_and_runs() { + let source = "local m = require(\"./present\")\nm.tag()\n"; + let imports = static_imports(source); + assert_eq!(imports.len(), 1); + assert_namespace(&imports[0], "./present", "m", 1); + + let root = owned_root("extensionless"); + write_present(&root); + let main_path = write_source(&root, "main.lua", source); + assert_eq!( + run_candidate(&main_path, "extensionless relative RSS link"), + vec![Value::Int(41)] + ); + assert_eq!( + run_production(&main_path, "production extensionless mapping"), + vec![Value::Int(41)] + ); +} + +#[test] +fn other_relative_extensionless_specs_keep_source_text() { + let parent = static_imports("local m = require(\"../present\")\n"); + assert_namespace(&parent[0], "../present", "m", 1); + let nested = static_imports("local m = require(\"./dir/present\")\n"); + assert_namespace(&nested[0], "./dir/present", "m", 1); +} + +#[test] +fn short_forms_outside_the_relative_rss_rule_are_not_static_edges() { + for source in [ + "local m = require(\"./present.lua\")\n", + "local m = require(\"present\")\n", + "local m = require(\"/present\")\n", + "local m = require(\"./.present\")\n", + "local m = require(\"./present.\")\n", + "local m = require(\"./present.rss.lua\")\n", + ] { + assert!( + static_imports(source).is_empty(), + "not a static RSS link: {source:?}" + ); + } +} + +#[test] +fn explicit_lua_spec_is_not_a_candidate_static_edge() { + let source = "local m = require(\"./present.lua\")\nm.tag()\n"; + assert!(static_imports(source).is_empty()); + + let root = owned_root("explicit_lua"); + fs::write(root.join("present.lua"), "return 7\n").expect("lua sibling"); + let main_path = write_source(&root, "main.lua", source); + let err = expect_load_error(compile_production(&main_path), "old scanner emits .lua"); + assert!( + matches!(err, SourcePathError::NonRustScriptModule(_)), + "old scanner emits explicit .lua and Core rejects it; the candidate must not copy that edge, got {err:?}" + ); +} + +#[test] +fn incomplete_require_is_a_parser_error_not_a_module_read() { let source = "local m = require(\"./absent.rss\"\n"; - fs::write(&main_path, source).expect("lua source"); + match imports::static_module_imports(source) { + Err(SourcePathError::Source(SourceError::Parse(parse))) => { + assert!( + !parse.message.is_empty(), + "parser should name the syntax error" + ); + } + other => panic!("expected a parser error, not a module read, got {other:?}"), + } - assert!(pd_vm_compat_frontends::lua_static_module_imports(source).is_err()); + let root = owned_root("incomplete"); + let main_path = write_source(&root, "main.lua", source); let err = expect_load_error(compile_candidate(&main_path), "incomplete call"); - assert_core_did_not_read_missing_module(&err); + assert_eq!( + parse_message(&err), + "expected ')'", + "old lowerer rejects the unclosed call; this is not a module read" + ); +} + +#[test] +fn nested_called_require_is_the_old_contract_not_a_candidate_link() { + // Production still executes this nested local. That is the old line-scanner + // contract, not a license to scan nested requires into the candidate graph: + // an uncalled nested require would become eager I/O. Before the production + // switch this pair is a producer/consumer joint regression. + let source = "local function use_tag()\n local m = require(\"./present.rss\")\n return m.tag()\nend\nuse_tag()\n"; + assert!( + static_imports(source).is_empty(), + "candidate graph must not lift the nested local" + ); + assert_eq!(require_specs(source), vec!["./present.rss"]); + + let root = owned_root("nested_called"); + write_present(&root); + let main_path = write_source(&root, "main.lua", source); + assert_eq!( + run_production(&main_path, "production nested called contract"), + vec![Value::Int(41)] + ); +} + +#[test] +fn nested_uncalled_require_is_eager_only_on_the_old_scanner() { + let source = + "local function unused()\n local m = require(\"./absent.rss\")\n return m.tag()\nend\n"; + assert!(static_imports(source).is_empty()); + assert_eq!(require_specs(source), vec!["./absent.rss"]); + + let root = owned_root("nested_absent"); + let main_path = write_source(&root, "main.lua", source); + let production = expect_load_error( + compile_production(&main_path), + "old scanner eager-reads an uncalled nested require", + ); + assert_not_found(&production, "old mis-scan"); } From 87e16188b50aab12e5041c430930bc21f7fe896a Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 20:28:00 +0800 Subject: [PATCH 007/225] feat(lua): lower chunk gotos and early returns on the fixed core A test plugin compiles real .lua through the existing parser and resolver. Gotos and a non-tail return become a private state loop. A source loop with no jump stays a Core while, so break and continue bind to that loop. --- src/frontends/lua/control.rs | 1000 ++++++++++++++++++ src/frontends/lua/mod.rs | 2 + tests/compiler/compiler_lua_control_tests.rs | 601 +++++++++++ tests/compiler_tests.rs | 3 + 4 files changed, 1606 insertions(+) create mode 100644 src/frontends/lua/control.rs create mode 100644 tests/compiler/compiler_lua_control_tests.rs diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs new file mode 100644 index 0000000..9ed4039 --- /dev/null +++ b/src/frontends/lua/control.rs @@ -0,0 +1,1000 @@ +//! Chunk scalar control lowering. +//! +//! Production `LuaPlugin` does not call this module. A test `SourcePlugin` +//! feeds the same parser and resolver, then asks here for Core IR. This is +//! not a file entry and not a fallback to the line lowerer. +//! +//! A chunk with no goto and no early return is emitted as ordinary +//! statements, including a source `while`. Any goto, or a return that is not +//! the chunk tail, becomes a private integer state loop. Each basic block is +//! one state. A transfer assigns that state and `Continue`s the dispatch +//! loop, so it is emitted only in the dispatch arm, never inside a nested +//! source loop. `break` and `continue` inside a source loop stay Core +//! statements of that loop. User values are binary64 or bool. The state id +//! is a private Core int and is not a Lua number. + +use super::ast::{self, BinOp, Block, Chunk, Expr, Name, NumberKind, Span, Stmt, UnOp}; +use super::lexer; +use super::parser; +use super::resolve::{self, Resolution, ResolveError}; +use vm::{ + AssignmentKind, Expr as CoreExpr, FrontendIr, LocalIrBuilder, LocalSlot, ParseError, + Stmt as CoreStmt, +}; + +const STATE_SLOT: &str = "$lua_dispatch_state"; +const RESULT_SLOT: &str = "$lua_return_value"; +const EXIT_STATE: i64 = 0; + +pub(super) fn lower_source(source: &str) -> Result { + let chunk = parser::parse_chunk(source.as_bytes()).map_err(syntax_error)?; + let resolution = resolve::resolve(&chunk); + if let Some(error) = resolution.errors.first() { + let line = line_of(source, error_span(error)); + return Err(ParseError::at_line(line, static_message(error))); + } + let mut lower = Lower::new(source, &resolution); + let stmts = if needs_dispatch(&chunk) { + lower.lower_dispatch(&chunk)? + } else { + lower.lower_direct(&chunk)? + }; + Ok(lower.builder.finish(stmts)) +} + +struct Lower<'a> { + source: &'a str, + resolution: &'a Resolution, + builder: LocalIrBuilder, + slots: Vec>, + dispatching: bool, + state: Option, + result: Option, + label_state: Vec>, +} + +struct BlockBuf { + finished: Vec, + current: Vec, + current_label: Option, +} + +struct BuiltBlock { + label: Option, + items: Vec, + exit: Exit, +} + +enum Item { + Core(CoreStmt), + If { + cond: CoreExpr, + then_body: Vec, + else_body: Vec, + line: u32, + }, + Goto { + label: usize, + line: u32, + }, + Return { + expr: CoreExpr, + line: u32, + }, +} + +enum Exit { + Fallthrough, + Goto { label: usize, line: u32 }, + Return { expr: CoreExpr, line: u32 }, + Stop, +} + +impl<'a> Lower<'a> { + fn new(source: &'a str, resolution: &'a Resolution) -> Self { + let slots = vec![None; resolution.bindings.len()]; + let label_state = vec![None; resolution.labels.len()]; + Self { + source, + resolution, + builder: LocalIrBuilder::new(), + slots, + dispatching: false, + state: None, + result: None, + label_state, + } + } + + fn lower_direct(&mut self, chunk: &Chunk) -> Result, ParseError> { + let (mut stmts, value) = self.straight(&chunk.body.stmts, false)?; + if let Some(expr) = value { + stmts.push(CoreStmt::Expr { expr, line: 1 }); + } + Ok(stmts) + } + + fn lower_dispatch(&mut self, chunk: &Chunk) -> Result, ParseError> { + self.dispatching = true; + let mut blocks = BlockBuf::new(); + self.walk_list(&chunk.body.stmts, &mut blocks)?; + blocks.finish(); + if blocks.finished.is_empty() { + return Err(self.fail_line(1, "empty dispatch chunk")); + } + for (index, block) in blocks.finished.iter().enumerate() { + if let Some(label) = block.label { + self.label_state[label] = Some(self.state_id_of(index)); + } + } + let state = self.alloc_private(STATE_SLOT)?; + self.state = Some(state); + if contains_return_block(&chunk.body) { + let result = self.alloc_private(RESULT_SLOT)?; + self.result = Some(result); + } + let mut arms = Vec::with_capacity(blocks.finished.len()); + for (index, block) in blocks.finished.iter().enumerate() { + let state_id = index as i64 + 1; + let mut body = self.emit_items(&block.items)?; + body.extend(self.emit_exit(&block.exit, index, blocks.finished.len())?); + arms.push((state_id, body)); + } + let chain = dispatch_chain(state, arms); + // Core requires a `let` on every path before an assign. The arms do + // not dominate each other, so user slots are declared here. The + // source initializer still runs at the declaration, as an assign. + let mut root = Vec::new(); + for slot in self.slots.iter().flatten().copied() { + root.push(let_expr(slot, CoreExpr::Null, 1)); + } + root.push(let_expr(state, CoreExpr::Int(1), 1)); + if let Some(result) = self.result { + root.push(let_expr(result, CoreExpr::Null, 1)); + } + root.push(CoreStmt::While { + condition: CoreExpr::Not(Box::new(CoreExpr::Eq( + Box::new(CoreExpr::Var(state)), + Box::new(CoreExpr::Int(EXIT_STATE)), + ))), + body: vec![chain], + line: 1, + }); + if let Some(result) = self.result { + root.push(CoreStmt::Expr { + expr: CoreExpr::Var(result), + line: 1, + }); + } + Ok(root) + } + + fn state_id_of(&self, block_index: usize) -> i64 { + i64::try_from(block_index).expect("block index") + 1 + } + + fn walk_list(&mut self, stmts: &[Stmt], blocks: &mut BlockBuf) -> Result<(), ParseError> { + for stmt in stmts { + match stmt { + Stmt::Empty { .. } => {} + Stmt::Do { body, .. } => self.walk_list(&body.stmts, blocks)?, + Stmt::Label { name, .. } => { + let index = self.label_index(name)?; + blocks.split_label(index); + } + Stmt::Goto { span, .. } => { + let label = self.goto_target(*span)?; + blocks.flush(Exit::Goto { + label, + line: self.line(*span), + }); + } + Stmt::Return { values, span } => { + blocks.flush(Exit::Return { + expr: self.one_value(values, *span)?, + line: self.line(*span), + }); + } + other => blocks.current.push(self.arm_item(other)?), + } + } + Ok(()) + } + + fn arm_item(&mut self, stmt: &Stmt) -> Result { + match stmt { + Stmt::Empty { .. } => Ok(Item::Core(CoreStmt::Noop { line: 1 })), + Stmt::Local { + names, + values, + span, + } => Ok(Item::Core(self.local_stmt(names, values, *span)?)), + Stmt::Assign { + targets, + values, + span, + } => Ok(Item::Core(self.assign_stmt(targets, values, *span)?)), + Stmt::If { + arms, + else_body, + span, + } => self.if_item(arms, else_body.as_ref(), *span), + Stmt::While { cond, body, span } => Ok(Item::Core(self.while_stmt(cond, body, *span)?)), + Stmt::Break { span } | Stmt::Continue { span } => { + Err(self.fail(*span, "break or continue outside a source loop")) + } + Stmt::Goto { span, .. } => Ok(Item::Goto { + label: self.goto_target(*span)?, + line: self.line(*span), + }), + Stmt::Return { values, span } => Ok(Item::Return { + expr: self.one_value(values, *span)?, + line: self.line(*span), + }), + Stmt::Label { span, .. } => Err(self.fail( + *span, + "a label inside if or a transferred branch is not in this slice", + )), + other => Err(self.fail( + stmt_span(other), + "statement is not in this chunk control slice", + )), + } + } + + fn branch_items(&mut self, stmts: &[Stmt]) -> Result, ParseError> { + let mut items = Vec::new(); + for stmt in stmts { + if matches!(stmt, Stmt::Empty { .. }) { + continue; + } + if let Stmt::Do { body, .. } = stmt { + items.extend(self.branch_items(&body.stmts)?); + continue; + } + items.push(self.arm_item(stmt)?); + } + Ok(items) + } + + fn if_item( + &mut self, + arms: &[ast::IfArm], + else_body: Option<&Block>, + span: Span, + ) -> Result { + if arms.is_empty() { + return Err(self.fail(span, "if has no arm")); + } + if if_has_label(arms, else_body) { + return Err(self.fail(span, "a label inside if is not in this slice")); + } + if !if_has_transfer(arms, else_body) { + return Ok(Item::Core(self.if_core(arms, else_body, span, false)?)); + } + let line = self.line(span); + let mut else_body_items = match else_body { + Some(body) => self.branch_items(&body.stmts)?, + None => Vec::new(), + }; + for arm in arms.iter().rev() { + let then_body = self.branch_items(&arm.body.stmts)?; + let cond = self.expr(&arm.cond)?; + else_body_items = vec![Item::If { + cond, + then_body, + else_body: else_body_items, + line, + }]; + } + else_body_items + .pop() + .ok_or_else(|| self.fail(span, "if has no arm")) + } + + fn if_core( + &mut self, + arms: &[ast::IfArm], + else_body: Option<&Block>, + span: Span, + in_loop: bool, + ) -> Result { + let line = self.line(span); + let mut else_branch = match else_body { + Some(body) => { + let (stmts, value) = self.straight(&body.stmts, in_loop)?; + if value.is_some() { + return Err(self.fail(span, "return inside if is not a direct tail")); + } + stmts + } + None => Vec::new(), + }; + for arm in arms.iter().rev() { + let (then_branch, value) = self.straight(&arm.body.stmts, in_loop)?; + if value.is_some() { + return Err(self.fail(span, "return inside if is not a direct tail")); + } + else_branch = vec![CoreStmt::IfElse { + condition: self.expr(&arm.cond)?, + then_branch, + else_branch, + line, + }]; + } + else_branch + .pop() + .ok_or_else(|| self.fail(span, "if has no arm")) + } + + fn while_stmt( + &mut self, + cond: &Expr, + body: &Block, + span: Span, + ) -> Result { + if contains_transfer(body) || contains_label(body) { + return Err(self.fail( + span, + "goto, label, or return inside a loop is not in this slice", + )); + } + let (body_stmts, value) = self.straight(&body.stmts, true)?; + if value.is_some() { + return Err(self.fail(span, "return inside a loop is not in this slice")); + } + Ok(CoreStmt::While { + condition: self.expr(cond)?, + body: body_stmts, + line: self.line(span), + }) + } + + fn straight( + &mut self, + stmts: &[Stmt], + in_loop: bool, + ) -> Result<(Vec, Option), ParseError> { + let mut out = Vec::new(); + for (index, stmt) in stmts.iter().enumerate() { + let last = index + 1 == stmts.len(); + match stmt { + Stmt::Empty { .. } => {} + Stmt::Return { values, span } => { + if !last || in_loop { + return Err(self.fail(*span, "early return needs dispatch")); + } + return Ok((out, Some(self.one_value(values, *span)?))); + } + Stmt::Do { body, .. } => { + let (inner, value) = self.straight(&body.stmts, in_loop)?; + out.extend(inner); + if value.is_some() { + if !last || in_loop { + return Err(self.fail(body.span, "early return needs dispatch")); + } + return Ok((out, value)); + } + } + Stmt::Break { span } => { + if !in_loop { + return Err(self.fail(*span, "break outside a source loop")); + } + out.push(CoreStmt::Break { + line: self.line(*span), + }); + } + Stmt::Continue { span } => { + if !in_loop { + return Err(self.fail(*span, "continue outside a source loop")); + } + out.push(CoreStmt::Continue { + line: self.line(*span), + }); + } + Stmt::Goto { span, .. } | Stmt::Label { span, .. } => { + return Err(self.fail(*span, "goto or label in a direct statement")); + } + other => out.push(self.straight_stmt(other, in_loop)?), + } + } + Ok((out, None)) + } + + fn straight_stmt(&mut self, stmt: &Stmt, in_loop: bool) -> Result { + match stmt { + Stmt::Local { + names, + values, + span, + } => self.local_stmt(names, values, *span), + Stmt::Assign { + targets, + values, + span, + } => self.assign_stmt(targets, values, *span), + Stmt::If { + arms, + else_body, + span, + } => self.if_core(arms, else_body.as_ref(), *span, in_loop), + Stmt::While { cond, body, span } => self.while_stmt(cond, body, *span), + Stmt::Break { span } if in_loop => Ok(CoreStmt::Break { + line: self.line(*span), + }), + Stmt::Continue { span } if in_loop => Ok(CoreStmt::Continue { + line: self.line(*span), + }), + other => Err(self.fail( + stmt_span(other), + "statement is not in this chunk control slice", + )), + } + } + + fn local_stmt( + &mut self, + names: &[ast::LocalName], + values: &ast::ExprList, + span: Span, + ) -> Result { + if names.len() != 1 || values.exprs.len() != 1 { + return Err(self.fail(span, "this slice lowers one local and one initializer")); + } + if names[0].const_binding { + return Err(self.fail(span, "const locals are not in this slice")); + } + let init = self.expr(&values.exprs[0])?; + let index = self.binding_for_local(&names[0].name, span)?; + let slot = self.slot(index)?; + let line = self.line(span); + if self.dispatching { + Ok(set_slot(slot, init, line)) + } else { + Ok(let_expr(slot, init, line)) + } + } + + fn assign_stmt( + &mut self, + targets: &[ast::AssignTarget], + values: &ast::ExprList, + span: Span, + ) -> Result { + if targets.len() != 1 || values.exprs.len() != 1 { + return Err(self.fail(span, "this slice lowers one assignment")); + } + let ast::AssignTarget::Name(name) = &targets[0] else { + return Err(self.fail(span, "only a local name can be assigned in this slice")); + }; + let expr = self.expr(&values.exprs[0])?; + let index = self.binding_at(&name.bytes, name.span)?; + let slot = self.slot(index)?; + Ok(set_slot(slot, expr, self.line(span))) + } + + fn one_value(&mut self, values: &ast::ExprList, span: Span) -> Result { + if values.exprs.len() != 1 { + return Err(self.fail(span, "this slice returns one value")); + } + self.expr(&values.exprs[0]) + } + + fn expr(&mut self, expr: &Expr) -> Result { + match expr { + Expr::Bool { value, .. } => Ok(CoreExpr::Bool(*value)), + Expr::Number { raw, kind, span } => self.number(raw, *kind, *span), + Expr::Name { name, .. } => { + let index = self.binding_at(&name.bytes, name.span)?; + let slot = self.slot(index)?; + Ok(CoreExpr::Var(slot)) + } + Expr::Paren { inner, .. } => self.expr(inner), + Expr::Unary { op, expr, span } => { + let inner = Box::new(self.expr(expr)?); + match op { + UnOp::Not | UnOp::Bang => Ok(CoreExpr::Not(inner)), + UnOp::Neg => Ok(CoreExpr::Neg(inner)), + _ => Err(self.fail(*span, "unary operator is not in this slice")), + } + } + Expr::Binary { + op, + left, + right, + span, + } => { + let lhs = self.expr(left)?; + let rhs = self.expr(right)?; + self.bin(*op, lhs, rhs, *span) + } + Expr::BinaryChain { base, steps, span } => { + let mut acc = self.expr(base)?; + for step in steps { + let rhs = self.expr(&step.expr)?; + acc = self.bin(step.op, acc, rhs, *span)?; + } + Ok(acc) + } + other => Err(self.fail(expr_span(other), "expression is not in this slice")), + } + } + + fn bin( + &self, + op: BinOp, + lhs: CoreExpr, + rhs: CoreExpr, + span: Span, + ) -> Result { + let lhs = Box::new(lhs); + let rhs = Box::new(rhs); + match op { + BinOp::Add => Ok(CoreExpr::Add(lhs, rhs)), + BinOp::Sub => Ok(CoreExpr::Sub(lhs, rhs)), + BinOp::Mul => Ok(CoreExpr::Mul(lhs, rhs)), + BinOp::Eq => Ok(CoreExpr::Eq(lhs, rhs)), + BinOp::Lt => Ok(CoreExpr::Lt(lhs, rhs)), + BinOp::Gt => Ok(CoreExpr::Gt(lhs, rhs)), + BinOp::Ne => Ok(CoreExpr::Not(Box::new(CoreExpr::Eq(lhs, rhs)))), + _ => Err(self.fail(span, "operator is not in this slice")), + } + } + + fn number(&self, raw: &str, kind: NumberKind, span: Span) -> Result { + match kind { + NumberKind::Integer | NumberKind::Float => {} + _ => return Err(self.fail(span, "only decimal binary64 literals are in this slice")), + } + let value = raw + .parse::() + .map_err(|_| self.fail(span, format!("not a binary64 literal: {raw}")))?; + if !value.is_finite() { + return Err(self.fail(span, "non-finite number is not in this slice")); + } + Ok(CoreExpr::Float(value)) + } + + fn emit_items(&self, items: &[Item]) -> Result, ParseError> { + let mut out = Vec::new(); + for item in items { + out.extend(self.emit_item(item)?); + } + Ok(out) + } + + fn emit_item(&self, item: &Item) -> Result, ParseError> { + match item { + Item::Core(stmt) => Ok(vec![stmt.clone()]), + Item::If { + cond, + then_body, + else_body, + line, + } => Ok(vec![CoreStmt::IfElse { + condition: cond.clone(), + then_branch: self.emit_items(then_body)?, + else_branch: self.emit_items(else_body)?, + line: *line, + }]), + Item::Goto { label, line } => Ok(self.transfer(self.label_state_id(*label)?, *line)), + Item::Return { expr, line } => Ok(self.return_transfer(expr.clone(), *line)?), + } + } + + fn emit_exit( + &self, + exit: &Exit, + index: usize, + len: usize, + ) -> Result, ParseError> { + match exit { + Exit::Fallthrough => { + let next = if index + 1 < len { + self.state_id_of(index + 1) + } else { + EXIT_STATE + }; + Ok(self.transfer(next, 1)) + } + Exit::Goto { label, line } => Ok(self.transfer(self.label_state_id(*label)?, *line)), + Exit::Return { expr, line } => self.return_transfer(expr.clone(), *line), + Exit::Stop => Ok(self.transfer(EXIT_STATE, 1)), + } + } + + fn transfer(&self, target: i64, line: u32) -> Vec { + let state = self.state.expect("dispatch state"); + vec![ + set_slot(state, CoreExpr::Int(target), line), + CoreStmt::Continue { line }, + ] + } + + fn return_transfer(&self, expr: CoreExpr, line: u32) -> Result, ParseError> { + let Some(result) = self.result else { + return Err(self.fail_line(line, "return without a result slot")); + }; + let mut stmts = vec![set_slot(result, expr, line)]; + stmts.extend(self.transfer(EXIT_STATE, line)); + Ok(stmts) + } + + fn label_state_id(&self, label: usize) -> Result { + self.label_state + .get(label) + .copied() + .flatten() + .ok_or_else(|| { + self.fail_line( + 1, + format!("label {label} was not placed in a dispatch block"), + ) + }) + } + + fn binding_for_local(&self, name: &Name, stmt_span: Span) -> Result { + self.resolution + .bindings + .iter() + .position(|binding| { + binding.function_id == 0 + && binding.name == name.bytes + && binding.visible_from == stmt_span.end + }) + .ok_or_else(|| self.fail(name.span, "local has no resolver binding")) + } + + fn binding_at(&self, name: &[u8], span: Span) -> Result { + let mut best: Option<(usize, u32)> = None; + for (index, binding) in self.resolution.bindings.iter().enumerate() { + if binding.function_id != 0 || binding.name != name { + continue; + } + if span.start < binding.visible_from || span.start >= binding.visible_to { + continue; + } + if best.is_none_or(|(_, from)| binding.visible_from >= from) { + best = Some((index, binding.visible_from)); + } + } + best.map(|(index, _)| index).ok_or_else(|| { + self.fail( + span, + format!("unresolved local {}", String::from_utf8_lossy(name)), + ) + }) + } + + fn slot(&mut self, index: usize) -> Result { + if let Some(slot) = self.slots[index] { + return Ok(slot); + } + let name = format!("$binding_{index}"); + let slot = self.alloc_private(&name)?; + self.slots[index] = Some(slot); + Ok(slot) + } + + fn alloc_private(&mut self, name: &str) -> Result { + self.builder.alloc_local_named(name) + } + + fn goto_target(&self, span: Span) -> Result { + let goto = self + .resolution + .gotos + .iter() + .find(|goto| goto.span == span) + .ok_or_else(|| self.fail(span, "goto has no resolver record"))?; + goto.target + .ok_or_else(|| self.fail(span, "goto has no resolved target")) + } + + fn label_index(&self, name: &Name) -> Result { + self.resolution + .labels + .iter() + .position(|label| label.span == name.span) + .ok_or_else(|| self.fail(name.span, "label has no resolver record")) + } + + fn line(&self, span: Span) -> u32 { + u32::try_from(line_of(self.source, span)).unwrap_or(u32::MAX) + } + + fn fail(&self, span: Span, message: impl Into) -> ParseError { + ParseError::at_line(self.line(span) as usize, message.into()) + } + + fn fail_line(&self, line: u32, message: impl Into) -> ParseError { + ParseError::at_line(line as usize, message.into()) + } +} + +impl BlockBuf { + fn new() -> Self { + Self { + finished: Vec::new(), + current: Vec::new(), + current_label: None, + } + } + + fn split_label(&mut self, index: usize) { + if self.current.is_empty() && self.current_label.is_none() { + self.current_label = Some(index); + return; + } + self.flush(Exit::Fallthrough); + self.current_label = Some(index); + } + + fn flush(&mut self, exit: Exit) { + self.finished.push(BuiltBlock { + label: self.current_label.take(), + items: std::mem::take(&mut self.current), + exit, + }); + } + + fn finish(&mut self) { + if self.current.is_empty() && self.current_label.is_none() { + if self.finished.is_empty() { + self.flush(Exit::Stop); + } + return; + } + self.flush(Exit::Stop); + } +} + +fn dispatch_chain(state: LocalSlot, arms: Vec<(i64, Vec)>) -> CoreStmt { + let mut pending = vec![CoreStmt::Break { line: 1 }]; + for (state_id, body) in arms.into_iter().rev() { + pending = vec![CoreStmt::IfElse { + condition: CoreExpr::Eq( + Box::new(CoreExpr::Var(state)), + Box::new(CoreExpr::Int(state_id)), + ), + then_branch: body, + else_branch: pending, + line: 1, + }]; + } + pending + .pop() + .expect("dispatch chain includes the unknown-state break") +} + +fn let_expr(slot: LocalSlot, expr: CoreExpr, line: u32) -> CoreStmt { + CoreStmt::Let { + index: slot, + declared_schema: None, + expr, + line, + } +} + +fn set_slot(slot: LocalSlot, expr: CoreExpr, line: u32) -> CoreStmt { + CoreStmt::Assign { + kind: AssignmentKind::Set, + index: slot, + expr, + line, + } +} + +fn needs_dispatch(chunk: &Chunk) -> bool { + contains_goto(&chunk.body) || has_early_return(&chunk.body.stmts) +} + +fn has_early_return(stmts: &[Stmt]) -> bool { + if stmts.is_empty() { + return false; + } + let last = stmts.len() - 1; + if stmts[..last].iter().any(contains_return_stmt) { + return true; + } + match &stmts[last] { + Stmt::Return { .. } => false, + Stmt::Do { body, .. } => has_early_return(&body.stmts), + other => contains_return_stmt(other), + } +} + +fn contains_goto(block: &Block) -> bool { + block.stmts.iter().any(stmt_contains_goto) +} + +fn stmt_contains_goto(stmt: &Stmt) -> bool { + match stmt { + Stmt::Goto { .. } => true, + Stmt::Do { body, .. } | Stmt::While { body, .. } | Stmt::Repeat { body, .. } => { + contains_goto(body) + } + Stmt::If { + arms, else_body, .. + } => { + arms.iter().any(|arm| contains_goto(&arm.body)) + || else_body.as_ref().is_some_and(contains_goto) + } + Stmt::NumericFor { body, .. } | Stmt::GenericFor { body, .. } => contains_goto(body), + _ => false, + } +} + +fn contains_return_block(block: &Block) -> bool { + block.stmts.iter().any(contains_return_stmt) +} + +fn contains_return_stmt(stmt: &Stmt) -> bool { + match stmt { + Stmt::Return { .. } => true, + Stmt::Do { body, .. } | Stmt::While { body, .. } | Stmt::Repeat { body, .. } => { + contains_return_block(body) + } + Stmt::If { + arms, else_body, .. + } => { + arms.iter().any(|arm| contains_return_block(&arm.body)) + || else_body.as_ref().is_some_and(contains_return_block) + } + Stmt::NumericFor { body, .. } | Stmt::GenericFor { body, .. } => { + contains_return_block(body) + } + _ => false, + } +} + +fn contains_transfer(block: &Block) -> bool { + block.stmts.iter().any(stmt_contains_transfer) +} + +fn stmt_contains_transfer(stmt: &Stmt) -> bool { + match stmt { + Stmt::Goto { .. } | Stmt::Return { .. } => true, + Stmt::Do { body, .. } | Stmt::While { body, .. } | Stmt::Repeat { body, .. } => { + contains_transfer(body) + } + Stmt::If { + arms, else_body, .. + } => { + arms.iter().any(|arm| contains_transfer(&arm.body)) + || else_body.as_ref().is_some_and(contains_transfer) + } + Stmt::NumericFor { body, .. } | Stmt::GenericFor { body, .. } => contains_transfer(body), + _ => false, + } +} + +fn contains_label(block: &Block) -> bool { + block.stmts.iter().any(stmt_contains_label) +} + +fn stmt_contains_label(stmt: &Stmt) -> bool { + match stmt { + Stmt::Label { .. } => true, + Stmt::Do { body, .. } | Stmt::While { body, .. } | Stmt::Repeat { body, .. } => { + contains_label(body) + } + Stmt::If { + arms, else_body, .. + } => { + arms.iter().any(|arm| contains_label(&arm.body)) + || else_body.as_ref().is_some_and(contains_label) + } + Stmt::NumericFor { body, .. } | Stmt::GenericFor { body, .. } => contains_label(body), + _ => false, + } +} + +fn if_has_label(arms: &[ast::IfArm], else_body: Option<&Block>) -> bool { + arms.iter().any(|arm| contains_label(&arm.body)) || else_body.is_some_and(contains_label) +} + +fn if_has_transfer(arms: &[ast::IfArm], else_body: Option<&Block>) -> bool { + arms.iter().any(|arm| contains_transfer(&arm.body)) || else_body.is_some_and(contains_transfer) +} + +fn stmt_span(stmt: &Stmt) -> Span { + match stmt { + Stmt::Empty { span } + | Stmt::Do { span, .. } + | Stmt::While { span, .. } + | Stmt::Repeat { span, .. } + | Stmt::If { span, .. } + | Stmt::NumericFor { span, .. } + | Stmt::GenericFor { span, .. } + | Stmt::Local { span, .. } + | Stmt::LocalFunction { span, .. } + | Stmt::Function { span, .. } + | Stmt::Assign { span, .. } + | Stmt::CompoundAssign { span, .. } + | Stmt::Call { span, .. } + | Stmt::Label { span, .. } + | Stmt::Goto { span, .. } + | Stmt::Break { span } + | Stmt::Continue { span } + | Stmt::Return { span, .. } => *span, + } +} + +fn expr_span(expr: &Expr) -> Span { + match expr { + Expr::Nil { span } + | Expr::Bool { span, .. } + | Expr::Number { span, .. } + | Expr::String { span, .. } + | Expr::Vararg { span } + | Expr::Name { span, .. } + | Expr::Paren { span, .. } + | Expr::Unary { span, .. } + | Expr::Binary { span, .. } + | Expr::BinaryChain { span, .. } + | Expr::Ternary { span, .. } + | Expr::SuffixChain { span, .. } + | Expr::Function { span, .. } + | Expr::ShortFunction { span, .. } + | Expr::Table { span, .. } => *span, + } +} + +fn syntax_error(error: lexer::SyntaxError) -> ParseError { + ParseError::at_line( + usize::try_from(error.line).unwrap_or(usize::MAX), + error.message, + ) +} + +fn line_of(source: &str, span: Span) -> usize { + let end = usize::try_from(span.start).unwrap_or(source.len()); + let prefix = &source.as_bytes()[..end.min(source.len())]; + 1 + prefix.iter().filter(|byte| **byte == b'\n').count() +} + +fn error_span(error: &ResolveError) -> Span { + match error { + ResolveError::JumpIntoLocal { goto_span, .. } + | ResolveError::UndefinedLabel { + span: goto_span, .. + } + | ResolveError::DuplicateLabel { + span: goto_span, .. + } + | ResolveError::BreakOutsideLoop { span: goto_span } + | ResolveError::ContinueOutsideLoop { span: goto_span } + | ResolveError::AssignConst { + span: goto_span, .. + } + | ResolveError::RedeclareConst { + span: goto_span, .. + } + | ResolveError::VarargOutside { span: goto_span } => *goto_span, + } +} + +fn static_message(error: &ResolveError) -> String { + match error { + ResolveError::JumpIntoLocal { local_name, .. } => format!( + "jump into the scope of local {}", + String::from_utf8_lossy(local_name) + ), + ResolveError::UndefinedLabel { name, .. } => { + format!("undefined label {}", String::from_utf8_lossy(name)) + } + ResolveError::DuplicateLabel { name, .. } => { + format!("duplicate label {}", String::from_utf8_lossy(name)) + } + ResolveError::BreakOutsideLoop { .. } => "break outside loop".to_string(), + ResolveError::ContinueOutsideLoop { .. } => "continue outside loop".to_string(), + ResolveError::AssignConst { name, .. } => { + format!("assign to const {}", String::from_utf8_lossy(name)) + } + ResolveError::RedeclareConst { name, .. } => { + format!("redeclare const {}", String::from_utf8_lossy(name)) + } + ResolveError::VarargOutside { .. } => "vararg outside vararg function".to_string(), + } +} diff --git a/src/frontends/lua/mod.rs b/src/frontends/lua/mod.rs index 08756ae..7391b21 100644 --- a/src/frontends/lua/mod.rs +++ b/src/frontends/lua/mod.rs @@ -7,6 +7,8 @@ mod support; #[allow(dead_code)] mod ast; #[allow(dead_code)] +mod control; +#[allow(dead_code)] mod lexer; #[allow(dead_code)] mod parser; diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs new file mode 100644 index 0000000..aa67883 --- /dev/null +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -0,0 +1,601 @@ +//! Chunk scalar control flow through the real Lua parser and resolver. +//! +//! The plugin is test-only. Production `LuaPlugin` stays on the line lowerer. +//! Fixtures are legal Lua 5.2-compat chunks. A bare expression statement is +//! not used: observation is the single chunk return value on the VM stack. +//! Ordinary Cargo does not spawn LuaJIT. `LUAJIT_ORACLE` compares that same +//! file when it is set; a configured binary that cannot run is a failure. + +#[allow(dead_code)] +#[path = "../common/mod.rs"] +mod common; +use common::*; + +#[allow(dead_code)] +#[path = "../../src/frontends/lua/ast.rs"] +mod ast; +#[allow(dead_code)] +#[path = "../../src/frontends/lua/control.rs"] +mod control; +#[allow(dead_code)] +#[path = "../../src/frontends/lua/lexer.rs"] +mod lexer; +#[allow(dead_code)] +#[path = "../../src/frontends/lua/parser.rs"] +mod parser; +#[allow(dead_code)] +#[path = "../../src/frontends/lua/resolve.rs"] +mod resolve; + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use vm::{ + Expr, FrontendImportSyntax, FrontendIr, JitConfig, LocalSlot, ParseError, SourceFlavor, + SourcePlugin, Stmt, Value, VmStatus, +}; + +const FUEL_BUDGET: u64 = 8_192; +const FUEL_CHECK_INTERVAL: u32 = 1; +const ORACLE_VERSION_BASELINE: &str = "LuaJIT 2.1.1795119671"; + +const FORWARD_GOTO: &str = "\ +local skipped = 0\n\ +local hit = 0\n\ +local after = 0\n\ +goto target\n\ +skipped = 1\n\ +::target::\n\ +hit = 1\n\ +after = 1\n\ +return skipped + hit * 10 + after * 100\n\ +"; + +struct ControlLuaPlugin; + +static CONTROL_LUA_PLUGIN: ControlLuaPlugin = ControlLuaPlugin; + +impl SourcePlugin for ControlLuaPlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &["lua"] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + control::lower_source(source) + } + + fn parse_module_imports( + &self, + _source: &str, + _path: &Path, + ) -> Result, vm::SourcePathError> { + Ok(Vec::new()) + } +} + +fn candidate_options() -> CompileSourceFileOptions { + CompileSourceFileOptions::new().with_source_plugin(&CONTROL_LUA_PLUGIN) +} + +fn write_fixture(label: &str, source: &str) -> PathBuf { + let root = namespace_case_root(&format!("lua_control_{label}")); + let path = root.join("chunk.lua"); + fs::write(&path, source).unwrap_or_else(|error| panic!("{label}: write fixture: {error}")); + path +} + +fn run_fixture(label: &str, source: &str) -> (Vec, u64) { + let path = write_fixture(label, source); + let compiled = compile_source_file_with_options(&path, candidate_options()) + .unwrap_or_else(|error| panic!("{label}: compile failed: {error}")); + let mut vm = Vm::new_with_jit_config( + compiled.program, + JitConfig { + enabled: false, + hot_loop_threshold: 8, + max_trace_len: 256, + }, + ); + vm.set_fuel_check_interval(FUEL_CHECK_INTERVAL) + .unwrap_or_else(|error| panic!("{label}: fuel interval: {error}")); + vm.set_fuel(FUEL_BUDGET); + let status = vm + .run() + .unwrap_or_else(|error| panic!("{label}: vm run failed: {error}")); + assert_eq!(status, VmStatus::Halted, "{label}: status"); + let remaining = vm + .get_fuel() + .unwrap_or_else(|| panic!("{label}: fuel metering missing")); + let consumed = FUEL_BUDGET + .checked_sub(remaining) + .unwrap_or_else(|| panic!("{label}: fuel increased")); + let stack = vm.stack().to_vec(); + eprintln!( + "LUA_CONTROL label={label} fuel_budget={FUEL_BUDGET} check_interval={FUEL_CHECK_INTERVAL} consumed={consumed} remaining={remaining} jit=disabled stack={stack:?}" + ); + (stack, consumed) +} + +fn expect_number(label: &str, source: &str, expected: f64) { + let (stack, consumed) = run_fixture(label, source); + assert_eq!( + stack, + vec![Value::Float(expected)], + "{label}: stack must be the single chunk return, not a bare Halted" + ); + assert!(consumed > 0, "{label}: recorded no fuel"); + assert!(consumed < FUEL_BUDGET, "{label}: exhausted the fuel budget"); + if let Ok(oracle) = std::env::var("LUAJIT_ORACLE") { + let observed = oracle_return(&oracle, &write_fixture(label, source)); + assert_eq!( + observed, expected, + "{label}: LuaJIT returned {observed}, candidate returned {expected}" + ); + } +} + +fn oracle_return(oracle: &str, path: &Path) -> f64 { + let driver = "\ +local chunk, err = loadfile(arg[0])\n\ +if not chunk then\n\ + io.stderr:write(err or 'load failed', '\\n')\n\ + os.exit(1)\n\ +end\n\ +local value = chunk()\n\ +if value == nil then\n\ + io.write('nil\\n')\n\ +else\n\ + io.write(string.format('%.17g\\n', value))\n\ +end\n\ +"; + let output = spawn_oracle(oracle, &["-e", driver, path.to_str().expect("utf-8 path")]); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "LUAJIT_ORACLE at {oracle:?} failed to run {}: status={} stdout={stdout:?} stderr={stderr:?}", + path.display(), + output.status, + ); + let text = stdout.trim(); + text.parse::() + .unwrap_or_else(|error| panic!("LUAJIT_ORACLE returned {text:?}: {error}")) +} + +fn spawn_oracle(path: &str, args: &[&str]) -> std::process::Output { + let mut cmd = Command::new(path); + cmd.args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(target_os = "linux")] + unsafe { + use std::os::unix::process::CommandExt; + cmd.pre_exec(limit_oracle_child); + } + cmd.output() + .unwrap_or_else(|error| panic!("LUAJIT_ORACLE at {path:?} failed to start: {error}")) +} + +#[cfg(target_os = "linux")] +fn limit_oracle_child() -> std::io::Result<()> { + #[repr(C)] + struct RLimit { + cur: u64, + max: u64, + } + unsafe extern "C" { + fn setrlimit(resource: i32, rlim: *const RLimit) -> i32; + fn alarm(seconds: u32) -> u32; + fn _exit(code: i32) -> !; + } + const RLIMIT_CPU: i32 = 0; + const RLIMIT_AS: i32 = 9; + let cpu = RLimit { cur: 2, max: 2 }; + let address = RLimit { + cur: 128 * 1024 * 1024, + max: 128 * 1024 * 1024, + }; + unsafe { + if setrlimit(RLIMIT_CPU, &cpu) != 0 || setrlimit(RLIMIT_AS, &address) != 0 { + _exit(126); + } + alarm(5); + } + Ok(()) +} + +#[test] +fn forward_goto_skips_the_write_and_runs_the_target_once() { + // skipped=0, hit=1, after=1. A missed skip, a missed target, or a second + // pass changes a different decimal place. + expect_number("forward_goto", FORWARD_GOTO, 110.0); +} + +const BACKWARD_GOTO: &str = "\ +local n = 0\n\ +local trips = 0\n\ +goto check\n\ +::check::\n\ +if n < 3 then\n\ + n = n + 1\n\ + trips = trips + 1\n\ + goto check\n\ +end\n\ +return n * 10 + trips\n\ +"; + +const CROSS_DO: &str = "\ +local x = 1\n\ +local seen = 0\n\ +do\n\ + ::out::\n\ + seen = 5\n\ + local x = 10\n\ +end\n\ +do\n\ + local x = 100\n\ + x = 1000\n\ + goto out\n\ + seen = 9\n\ +end\n\ +::out::\n\ +return x * 100 + seen\n\ +"; + +const OUTER_X_ONLY: &str = "\ +local x = 1\n\ +do\n\ + ::out::\n\ + local x = 10\n\ +end\n\ +do\n\ + local x = 100\n\ + x = 1000\n\ + goto out\n\ +end\n\ +::out::\n\ +return x\n\ +"; + +const NESTED_CONTINUE: &str = "\ +local skipped = 0\n\ +local n = 0\n\ +local tails = 0\n\ +local after = 0\n\ +goto enter\n\ +skipped = 1\n\ +::enter::\n\ +while n < 3 do\n\ + n = n + 1\n\ + if n < 3 then\n\ + continue\n\ + end\n\ + tails = tails + 1\n\ +end\n\ +after = 1\n\ +return skipped * 1000 + n * 100 + tails * 10 + after\n\ +"; + +const NESTED_BREAK: &str = "\ +local skipped = 0\n\ +local m = 0\n\ +local inner = 0\n\ +local after = 0\n\ +goto enter\n\ +skipped = 1\n\ +::enter::\n\ +while m < 5 do\n\ + m = m + 1\n\ + if m > 1 then\n\ + break\n\ + end\n\ + inner = inner + 1\n\ +end\n\ +after = 1\n\ +return skipped * 1000 + m * 100 + inner * 10 + after\n\ +"; + +const EARLY_RETURN: &str = "\ +local tail = 0\n\ +do\n\ + return 7\n\ +end\n\ +tail = 1\n\ +return tail\n\ +"; + +const DIRECT_LOOP: &str = "\ +local i = 0\n\ +local n = 0\n\ +while i < 4 do\n\ + i = i + 1\n\ + n = n + 1\n\ +end\n\ +return n\n\ +"; + +const DISPATCH_LOOP: &str = "\ +local i = 0\n\ +local n = 0\n\ +::loop::\n\ +if i < 4 then\n\ + i = i + 1\n\ + n = n + 1\n\ + goto loop\n\ +end\n\ +return n\n\ +"; + +const JUMP_INTO_LOCAL: &str = "\ +goto target\n\ +local hidden = 1\n\ +::target::\n\ +return hidden\n\ +"; + +const BASELINE_DRIVER: &str = "\ +io.write(jit.version, '\\n')\n\ +local g = load('local goto = 1', '@g', 't')\n\ +local b = load('for i=1,2 do break print(i) end', '@b', 't')\n\ +io.write(g and 'BAD_GOTO' or 'GOTO_KW', '\\n')\n\ +io.write(b and 'BREAK_OK' or 'BREAK_BAD', '\\n')\n\ +io.write(type(table.pack), '\\n')\n\ +"; + +fn lowered(source: &str) -> FrontendIr { + control::lower_source(source).unwrap_or_else(|error| panic!("lower failed: {error}")) +} + +fn slot_named(ir: &FrontendIr, name: &str) -> Option { + ir.local_bindings + .iter() + .find(|(binding, _)| binding == name) + .map(|(_, slot)| *slot) +} + +fn is_lua_ident(name: &str) -> bool { + let mut bytes = name.bytes(); + let Some(first) = bytes.next() else { + return false; + }; + let head = first == b'_' || first.is_ascii_alphabetic() || first >= 128; + head && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric() || byte >= 128) +} + +fn walk_stmts(stmts: &[Stmt], visit: &mut impl FnMut(&Stmt)) { + for stmt in stmts { + visit(stmt); + match stmt { + Stmt::While { body, .. } => walk_stmts(body, visit), + Stmt::IfElse { + then_branch, + else_branch, + .. + } => { + walk_stmts(then_branch, visit); + walk_stmts(else_branch, visit); + } + Stmt::For { + init, post, body, .. + } => { + walk_stmts(std::slice::from_ref(init.as_ref()), visit); + walk_stmts(std::slice::from_ref(post.as_ref()), visit); + walk_stmts(body, visit); + } + _ => {} + } + } +} + +fn source_while_count(stmts: &[Stmt]) -> usize { + let mut count = 0; + walk_stmts(stmts, &mut |stmt| { + if let Stmt::While { condition, .. } = stmt + && matches!(condition, Expr::Lt(_, _) | Expr::Gt(_, _)) + { + count += 1; + } + }); + count +} + +fn dispatch_while_count(stmts: &[Stmt], state: LocalSlot) -> usize { + let mut count = 0; + walk_stmts(stmts, &mut |stmt| { + if let Stmt::While { condition, .. } = stmt + && matches!( + condition, + Expr::Not(inner) + if matches!( + inner.as_ref(), + Expr::Eq(lhs, rhs) + if matches!(lhs.as_ref(), Expr::Var(slot) if *slot == state) + && matches!(rhs.as_ref(), Expr::Int(0)) + ) + ) + { + count += 1; + } + }); + count +} + +fn assert_private_slots(ir: &FrontendIr, guest_names: &[&str]) { + let names: Vec<&str> = ir + .local_bindings + .iter() + .map(|(name, _)| name.as_str()) + .collect(); + for guest in guest_names { + assert!( + !names.contains(guest), + "guest name {guest} entered the Core namespace: {names:?}" + ); + } + let state = names.iter().find(|name| name.contains("dispatch")).copied(); + if let Some(state) = state { + assert!(!is_lua_ident(state), "{state} is a guest identifier"); + } + let user: Vec = ir + .local_bindings + .iter() + .filter(|(name, _)| name.starts_with("$binding_")) + .map(|(_, slot)| *slot) + .collect(); + let mut unique = user.clone(); + unique.sort_unstable(); + unique.dedup(); + assert_eq!(unique.len(), user.len(), "user slots alias: {user:?}"); +} + +#[test] +fn backward_goto_stops_after_three_trips() { + // One trip is 11, two is 22, four is 44. An open loop exhausts fuel. + expect_number("backward_goto", BACKWARD_GOTO, 33.0); +} + +#[test] +fn cross_do_uses_resolver_identity_not_the_first_same_name() { + let resolution = { + let chunk = parser::parse_chunk(CROSS_DO.as_bytes()).expect("parse cross do"); + resolve::resolve(&chunk) + }; + assert!( + resolution.errors.is_empty(), + "cross do is legal: {:?}", + resolution.errors + ); + assert_eq!(resolution.gotos.len(), 1); + let target = resolution.gotos[0].target.expect("resolved target"); + assert_ne!(target, 0, "the first ::out:: is a different label"); + assert_eq!(resolution.labels[target].name, resolution.labels[0].name); + assert!(resolution.labels[target].span.start > resolution.labels[0].span.start); + let ir = lowered(CROSS_DO); + assert_private_slots(&ir, &["x", "seen", "out"]); + let x_slots: Vec = ir + .local_bindings + .iter() + .filter(|(name, _)| name == "$binding_0" || name == "$binding_2" || name == "$binding_3") + .map(|(_, slot)| *slot) + .collect(); + assert_eq!( + x_slots.len(), + 3, + "three x bindings: {:?}", + ir.local_bindings + ); + assert_ne!(x_slots[0], x_slots[1]); + assert_ne!(x_slots[0], x_slots[2]); + // 105: outer x stays 1, first do sets seen=5, jump skips seen=9. + // Falling through is 109. Aliasing the inner write onto outer x is 100005. + // Jumping at the earlier same-name label loops until fuel runs out. + expect_number("cross_do", CROSS_DO, 105.0); + expect_number("outer_x", OUTER_X_ONLY, 1.0); +} + +#[test] +fn nested_source_loop_break_and_continue_stay_inside_the_state() { + // continue ignored writes tails three times (331). continue leaving the + // dispatcher leaves after at 0 (100). break leaving the dispatcher leaves + // after at 0 (210). The taken path is 311 and 211. + expect_number("nested_continue", NESTED_CONTINUE, 311.0); + expect_number("nested_break", NESTED_BREAK, 211.0); + let ir = lowered(NESTED_CONTINUE); + let state = slot_named(&ir, "$lua_dispatch_state").expect("dispatch state"); + assert_eq!(dispatch_while_count(&ir.stmts, state), 1); + assert_eq!(source_while_count(&ir.stmts), 1); + assert!(!is_lua_ident("$lua_dispatch_state")); +} + +#[test] +fn early_return_skips_the_tail_write_and_pushes_one_value() { + let (stack, consumed) = run_fixture("early_return", EARLY_RETURN); + assert_eq!(stack.len(), 1, "stack={stack:?}"); + assert_eq!( + stack, + vec![Value::Float(7.0)], + "tail return would be 1 or 0" + ); + assert!(consumed > 0 && consumed < FUEL_BUDGET); + if let Ok(oracle) = std::env::var("LUAJIT_ORACLE") { + let observed = oracle_return(&oracle, &write_fixture("early_return", EARLY_RETURN)); + assert_eq!(observed, 7.0); + } +} + +#[test] +fn direct_loop_stays_structured_and_matches_the_dispatched_loop() { + let (direct_stack, direct_fuel) = run_fixture("direct_loop", DIRECT_LOOP); + let (dispatch_stack, dispatch_fuel) = run_fixture("dispatch_loop", DISPATCH_LOOP); + assert_eq!(direct_stack, vec![Value::Float(4.0)]); + assert_eq!(dispatch_stack, direct_stack); + let direct = lowered(DIRECT_LOOP); + let dispatch = lowered(DISPATCH_LOOP); + assert!(slot_named(&direct, "$lua_dispatch_state").is_none()); + assert_eq!(source_while_count(&direct.stmts), 1); + assert_eq!(dispatch_while_count(&direct.stmts, 0), 0); + let state = slot_named(&dispatch, "$lua_dispatch_state").expect("dispatch state"); + assert!(!is_lua_ident("$lua_dispatch_state")); + assert_eq!(source_while_count(&dispatch.stmts), 0); + assert_eq!(dispatch_while_count(&dispatch.stmts, state), 1); + assert_private_slots(&direct, &["i", "n"]); + assert_private_slots(&dispatch, &["i", "n", "loop"]); + eprintln!( + "LUA_CONTROL cost iters=4 result=4 direct_fuel={direct_fuel} dispatch_fuel={dispatch_fuel} direct_shape=source_while dispatch_shape=state_while jit=disabled fuel_budget={FUEL_BUDGET} check_interval={FUEL_CHECK_INTERVAL}" + ); + if let Ok(oracle) = std::env::var("LUAJIT_ORACLE") { + assert_eq!( + oracle_return(&oracle, &write_fixture("direct_loop", DIRECT_LOOP)), + 4.0 + ); + assert_eq!( + oracle_return(&oracle, &write_fixture("dispatch_loop", DISPATCH_LOOP)), + 4.0 + ); + } +} + +#[test] +fn jump_into_local_is_a_static_rejection() { + let error = control::lower_source(JUMP_INTO_LOCAL).expect_err("resolver rejection"); + let text = error.to_string(); + assert!( + text.contains("jump into the scope of local hidden"), + "{text}" + ); + let path = write_fixture("jump_into_local", JUMP_INTO_LOCAL); + let compiled = compile_source_file_with_options(&path, candidate_options()); + assert!(compiled.is_err(), "invalid jump must not produce a program"); +} + +#[test] +fn oracle_control_config_matches_locked_52_build() { + let Ok(path) = std::env::var("LUAJIT_ORACLE") else { + eprintln!("LUAJIT_ORACLE is unset; this is not a differential GREEN"); + return; + }; + let output = spawn_oracle(&path, &["-e", BASELINE_DRIVER]); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + output.status.success(), + "LUAJIT_ORACLE at {path:?} baseline failed: status={} stdout={stdout:?} stderr={stderr:?}", + output.status + ); + let expected = format!("{ORACLE_VERSION_BASELINE}\nGOTO_KW\nBREAK_OK\nfunction\n"); + assert_eq!( + stdout, expected, + "oracle is not the locked 5.2-compat build" + ); + eprintln!("oracle baseline {ORACLE_VERSION_BASELINE} GOTO_KW BREAK_OK table.pack"); +} diff --git a/tests/compiler_tests.rs b/tests/compiler_tests.rs index f9caa84..6c613f4 100644 --- a/tests/compiler_tests.rs +++ b/tests/compiler_tests.rs @@ -11,3 +11,6 @@ mod compiler_lua_static_import_tests; #[path = "compiler/compiler_luajit_oracle_tests.rs"] mod compiler_luajit_oracle_tests; + +#[path = "compiler/compiler_lua_control_tests.rs"] +mod compiler_lua_control_tests; From ebebdc45f51cef52b4044ab9fcf838d1dac3f946 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 20:35:10 +0800 Subject: [PATCH 008/225] fix(lua): keep control lowering off the production module The compiler test already loads control.rs through a path attribute. A library module declaration compiled that uncalled candidate into the crate. --- src/frontends/lua/mod.rs | 2 -- tests/compiler/compiler_lua_control_tests.rs | 1 - 2 files changed, 3 deletions(-) diff --git a/src/frontends/lua/mod.rs b/src/frontends/lua/mod.rs index 7391b21..08756ae 100644 --- a/src/frontends/lua/mod.rs +++ b/src/frontends/lua/mod.rs @@ -7,8 +7,6 @@ mod support; #[allow(dead_code)] mod ast; #[allow(dead_code)] -mod control; -#[allow(dead_code)] mod lexer; #[allow(dead_code)] mod parser; diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index aa67883..7ac34a2 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -14,7 +14,6 @@ use common::*; #[allow(dead_code)] #[path = "../../src/frontends/lua/ast.rs"] mod ast; -#[allow(dead_code)] #[path = "../../src/frontends/lua/control.rs"] mod control; #[allow(dead_code)] From 4d56b128dda26086db16938fab2a6dcad2665803 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 21:35:36 +0800 Subject: [PATCH 009/225] fix(lua): treat only false as falsy in chunk conditions Core Brfalse and Not require a bool, so if 0, while 1, and not 0 compiled and then failed in the interpreter. if, elseif, while, and not all compare the operand with false once before the branch. --- src/frontends/lua/control.rs | 22 +- tests/compiler/compiler_lua_control_tests.rs | 602 +++++++++++++++++-- 2 files changed, 579 insertions(+), 45 deletions(-) diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs index 9ed4039..3dce898 100644 --- a/src/frontends/lua/control.rs +++ b/src/frontends/lua/control.rs @@ -11,7 +11,10 @@ //! loop, so it is emitted only in the dispatch arm, never inside a nested //! source loop. `break` and `continue` inside a source loop stay Core //! statements of that loop. User values are binary64 or bool. The state id -//! is a private Core int and is not a Lua number. +//! is a private Core int and is not a Lua number. In this numeric/bool slice +//! only `false` is falsy: `0` and every other number are truthy. `if`, +//! `elseif`, `while`, and `not` / `!` pass the operand through `core_truthy` +//! before a Core branch or `Not`. The operand expression is placed once. use super::ast::{self, BinOp, Block, Chunk, Expr, Name, NumberKind, Span, Stmt, UnOp}; use super::lexer; @@ -279,7 +282,7 @@ impl<'a> Lower<'a> { }; for arm in arms.iter().rev() { let then_body = self.branch_items(&arm.body.stmts)?; - let cond = self.expr(&arm.cond)?; + let cond = core_truthy(self.expr(&arm.cond)?); else_body_items = vec![Item::If { cond, then_body, @@ -316,7 +319,7 @@ impl<'a> Lower<'a> { return Err(self.fail(span, "return inside if is not a direct tail")); } else_branch = vec![CoreStmt::IfElse { - condition: self.expr(&arm.cond)?, + condition: core_truthy(self.expr(&arm.cond)?), then_branch, else_branch, line, @@ -344,7 +347,7 @@ impl<'a> Lower<'a> { return Err(self.fail(span, "return inside a loop is not in this slice")); } Ok(CoreStmt::While { - condition: self.expr(cond)?, + condition: core_truthy(self.expr(cond)?), body: body_stmts, line: self.line(span), }) @@ -493,7 +496,7 @@ impl<'a> Lower<'a> { Expr::Unary { op, expr, span } => { let inner = Box::new(self.expr(expr)?); match op { - UnOp::Not | UnOp::Bang => Ok(CoreExpr::Not(inner)), + UnOp::Not | UnOp::Bang => Ok(CoreExpr::Not(Box::new(core_truthy(*inner)))), UnOp::Neg => Ok(CoreExpr::Neg(inner)), _ => Err(self.fail(*span, "unary operator is not in this slice")), } @@ -767,6 +770,15 @@ fn dispatch_chain(state: LocalSlot, arms: Vec<(i64, Vec)>) -> CoreStmt .expect("dispatch chain includes the unknown-state break") } +fn core_truthy(value: CoreExpr) -> CoreExpr { + // Core equality keeps bool and float apart, so this matches only `false`. + // `0` and every other number stay truthy. The value expression is used once. + CoreExpr::Not(Box::new(CoreExpr::Eq( + Box::new(value), + Box::new(CoreExpr::Bool(false)), + ))) +} + fn let_expr(slot: LocalSlot, expr: CoreExpr, line: u32) -> CoreStmt { CoreStmt::Let { index: slot, diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index 7ac34a2..eb63c69 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -1,10 +1,12 @@ //! Chunk scalar control flow through the real Lua parser and resolver. //! //! The plugin is test-only. Production `LuaPlugin` stays on the line lowerer. -//! Fixtures are legal Lua 5.2-compat chunks. A bare expression statement is -//! not used: observation is the single chunk return value on the VM stack. -//! Ordinary Cargo does not spawn LuaJIT. `LUAJIT_ORACLE` compares that same -//! file when it is set; a configured binary that cannot run is a failure. +//! Fixtures are legal Lua 5.2-compat chunks written to real `.lua` files and +//! run through SourcePlugin, Core, and the interpreter. Observation is the +//! single chunk return on the VM stack. Ordinary Cargo does not spawn LuaJIT. +//! `LUAJIT_ORACLE` compares that same file when it is set. A configured binary +//! that cannot start is an infrastructure failure, not a differential result. +//! An unset variable is not differential evidence. #[allow(dead_code)] #[path = "../common/mod.rs"] @@ -126,10 +128,19 @@ fn run_fixture(label: &str, source: &str) -> (Vec, u64) { fn expect_number(label: &str, source: &str, expected: f64) { let (stack, consumed) = run_fixture(label, source); + assert_eq!( + stack.len(), + 1, + "{label}: stack regression, expected one chunk return, stack={stack:?}" + ); + assert!( + matches!(stack.first(), Some(Value::Float(_))), + "{label}: stack regression, chunk return is not a float: {stack:?}" + ); assert_eq!( stack, vec![Value::Float(expected)], - "{label}: stack must be the single chunk return, not a bare Halted" + "{label}: branch or jump mismatch; a wrong then/else, continue, or goto changes a different digit" ); assert!(consumed > 0, "{label}: recorded no fuel"); assert!(consumed < FUEL_BUDGET, "{label}: exhausted the fuel budget"); @@ -142,47 +153,177 @@ fn expect_number(label: &str, source: &str, expected: f64) { } } +const ORACLE_DRIVER: &str = r#" +assert(not jit.status()) +io.write("jit=off\n") +local path = os.getenv("LUA_CONTROL_FIXTURE") +if type(path) ~= "string" or path == "" then + io.stderr:write("FIXTURE_PATH_MISSING\n") + os.exit(3) +end +if arg[0] == path then + io.stderr:write("FIXTURE_IS_MAIN_SCRIPT\n") + os.exit(4) +end +local file, open_err = io.open(path, "rb") +if not file then + io.stderr:write("FIXTURE_OPEN_FAILED\n") + io.stderr:write(open_err or "", "\n") + os.exit(5) +end +local source = file:read("*a") +file:close() +local chunk, err = load(source, "@control-fixture", "t") +if not chunk then + io.stderr:write("LOAD_REJECT\n") + io.stderr:write(err or "", "\n") + os.exit(2) +end +local repeats = tonumber(os.getenv("LUA_CONTROL_REPEATS") or "1") +if repeats ~= 1 and repeats ~= 2 then + io.stderr:write("BAD_REPEATS\n") + os.exit(6) +end +local hits = 0 +debug.sethook(function() + local info = debug.getinfo(2, "S") + if info and info.source == "@control-fixture" then + hits = hits + 1 + end +end, "l") +local value +for _ = 1, repeats do + value = chunk() +end +debug.sethook() +io.write("calls=", repeats, "\n") +io.write("lines=", hits, "\n") +io.write("argc=", #arg, "\n") +io.write("arg0=", tostring(arg[0]), "\n") +if value == nil then + io.write("nil\n") +else + io.write(string.format("%.17g\n", value), "\n") +end +"#; + +struct OracleRun { + calls: u32, + lines: u64, + argc: u32, + arg0: String, + value: f64, +} + fn oracle_return(oracle: &str, path: &Path) -> f64 { - let driver = "\ -local chunk, err = loadfile(arg[0])\n\ -if not chunk then\n\ - io.stderr:write(err or 'load failed', '\\n')\n\ - os.exit(1)\n\ -end\n\ -local value = chunk()\n\ -if value == nil then\n\ - io.write('nil\\n')\n\ -else\n\ - io.write(string.format('%.17g\\n', value))\n\ -end\n\ -"; - let output = spawn_oracle(oracle, &["-e", driver, path.to_str().expect("utf-8 path")]); - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - output.status.success(), - "LUAJIT_ORACLE at {oracle:?} failed to run {}: status={} stdout={stdout:?} stderr={stderr:?}", - path.display(), - output.status, - ); - let text = stdout.trim(); - text.parse::() - .unwrap_or_else(|error| panic!("LUAJIT_ORACLE returned {text:?}: {error}")) + let run = oracle_run(oracle, path, 1).unwrap_or_else(|error| { + panic!( + "LUAJIT_ORACLE at {oracle:?} failed to run {}: {error}", + path.display() + ) + }); + assert_eq!(run.calls, 1, "business fixture must be called once"); + assert!(run.lines > 0, "line hook saw no fixture execution"); + assert_eq!(run.argc, 0, "fixture path was passed as a script argument"); + assert_eq!(run.arg0, "nil", "fixture path leaked into arg[0]"); + run.value +} + +fn oracle_run(oracle: &str, path: &Path, repeats: u32) -> Result { + let output = spawn_oracle(oracle, &["-e", ORACLE_DRIVER], Some(path), Some(repeats)) + .map_err(|error| format!("failed to start: {error}"))?; + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); + if !output.status.success() { + return Err(format!( + "status={} stdout={stdout:?} stderr={stderr:?}", + output.status + )); + } + parse_oracle_stdout(&stdout).map_err(|error| format!("{error}; stdout={stdout:?}")) } -fn spawn_oracle(path: &str, args: &[&str]) -> std::process::Output { +fn parse_oracle_stdout(stdout: &str) -> Result { + let mut calls = None; + let mut lines = None; + let mut argc = None; + let mut arg0 = None; + let mut value = None; + let mut saw_jit_off = false; + for line in stdout.lines() { + if line == "jit=off" { + saw_jit_off = true; + } else if let Some(rest) = line.strip_prefix("calls=") { + calls = rest.parse::().ok(); + } else if let Some(rest) = line.strip_prefix("lines=") { + lines = rest.parse::().ok(); + } else if let Some(rest) = line.strip_prefix("argc=") { + argc = rest.parse::().ok(); + } else if let Some(rest) = line.strip_prefix("arg0=") { + arg0 = Some(rest.to_string()); + } else if line == "nil" { + return Err("fixture returned nil".to_string()); + } else if value.is_none() { + value = line.parse::().ok(); + } + } + if !saw_jit_off { + return Err("jit.status() was not asserted off".to_string()); + } + Ok(OracleRun { + calls: calls.ok_or_else(|| "missing calls".to_string())?, + lines: lines.ok_or_else(|| "missing lines".to_string())?, + argc: argc.ok_or_else(|| "missing argc".to_string())?, + arg0: arg0.ok_or_else(|| "missing arg0".to_string())?, + value: value.ok_or_else(|| "missing value".to_string())?, + }) +} + +fn oracle_load_rejection(oracle: &str, path: &Path) -> std::process::Output { + spawn_oracle(oracle, &["-e", ORACLE_DRIVER], Some(path), Some(1)).unwrap_or_else(|error| { + panic!( + "LUAJIT_ORACLE at {oracle:?} failed to start while checking a load rejection: {error}" + ) + }) +} + +fn try_spawn_oracle( + path: &str, + args: &[&str], + fixture: Option<&Path>, + repeats: Option, +) -> std::io::Result { let mut cmd = Command::new(path); + cmd.arg("-joff"); cmd.args(args) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); + if let Some(fixture) = fixture { + cmd.env("LUA_CONTROL_FIXTURE", fixture); + } else { + cmd.env_remove("LUA_CONTROL_FIXTURE"); + } + if let Some(repeats) = repeats { + cmd.env("LUA_CONTROL_REPEATS", repeats.to_string()); + } else { + cmd.env_remove("LUA_CONTROL_REPEATS"); + } #[cfg(target_os = "linux")] unsafe { use std::os::unix::process::CommandExt; cmd.pre_exec(limit_oracle_child); } cmd.output() - .unwrap_or_else(|error| panic!("LUAJIT_ORACLE at {path:?} failed to start: {error}")) +} + +fn spawn_oracle( + path: &str, + args: &[&str], + fixture: Option<&Path>, + repeats: Option, +) -> std::io::Result { + try_spawn_oracle(path, args, fixture, repeats) } #[cfg(target_os = "linux")] @@ -343,7 +484,9 @@ return hidden\n\ "; const BASELINE_DRIVER: &str = "\ +assert(not jit.status())\n\ io.write(jit.version, '\\n')\n\ +io.write('jit=off\\n')\n\ local g = load('local goto = 1', '@g', 't')\n\ local b = load('for i=1,2 do break print(i) end', '@b', 't')\n\ io.write(g and 'BAD_GOTO' or 'GOTO_KW', '\\n')\n\ @@ -396,11 +539,24 @@ fn walk_stmts(stmts: &[Stmt], visit: &mut impl FnMut(&Stmt)) { } } -fn source_while_count(stmts: &[Stmt]) -> usize { +fn is_dispatch_state_while(condition: &Expr, state: LocalSlot) -> bool { + matches!( + condition, + Expr::Not(inner) + if matches!( + inner.as_ref(), + Expr::Eq(lhs, rhs) + if matches!(lhs.as_ref(), Expr::Var(slot) if *slot == state) + && matches!(rhs.as_ref(), Expr::Int(0)) + ) + ) +} + +fn source_while_count(stmts: &[Stmt], state: Option) -> usize { let mut count = 0; walk_stmts(stmts, &mut |stmt| { if let Stmt::While { condition, .. } = stmt - && matches!(condition, Expr::Lt(_, _) | Expr::Gt(_, _)) + && !state.is_some_and(|slot| is_dispatch_state_while(condition, slot)) { count += 1; } @@ -512,7 +668,7 @@ fn nested_source_loop_break_and_continue_stay_inside_the_state() { let ir = lowered(NESTED_CONTINUE); let state = slot_named(&ir, "$lua_dispatch_state").expect("dispatch state"); assert_eq!(dispatch_while_count(&ir.stmts, state), 1); - assert_eq!(source_while_count(&ir.stmts), 1); + assert_eq!(source_while_count(&ir.stmts, Some(state)), 1); assert!(!is_lua_ident("$lua_dispatch_state")); } @@ -541,16 +697,16 @@ fn direct_loop_stays_structured_and_matches_the_dispatched_loop() { let direct = lowered(DIRECT_LOOP); let dispatch = lowered(DISPATCH_LOOP); assert!(slot_named(&direct, "$lua_dispatch_state").is_none()); - assert_eq!(source_while_count(&direct.stmts), 1); + assert_eq!(source_while_count(&direct.stmts, None), 1); assert_eq!(dispatch_while_count(&direct.stmts, 0), 0); let state = slot_named(&dispatch, "$lua_dispatch_state").expect("dispatch state"); assert!(!is_lua_ident("$lua_dispatch_state")); - assert_eq!(source_while_count(&dispatch.stmts), 0); + assert_eq!(source_while_count(&dispatch.stmts, Some(state)), 0); assert_eq!(dispatch_while_count(&dispatch.stmts, state), 1); assert_private_slots(&direct, &["i", "n"]); assert_private_slots(&dispatch, &["i", "n", "loop"]); eprintln!( - "LUA_CONTROL cost iters=4 result=4 direct_fuel={direct_fuel} dispatch_fuel={dispatch_fuel} direct_shape=source_while dispatch_shape=state_while jit=disabled fuel_budget={FUEL_BUDGET} check_interval={FUEL_CHECK_INTERVAL}" + "LUA_CONTROL cost iters=4 result=4 direct_fuel={direct_fuel} dispatch_fuel={dispatch_fuel} direct_shape=source_while dispatch_shape=state_while interpreter=core-vm jit=disabled fuel_budget={FUEL_BUDGET} check_interval={FUEL_CHECK_INTERVAL}" ); if let Ok(oracle) = std::env::var("LUAJIT_ORACLE") { assert_eq!( @@ -575,6 +731,33 @@ fn jump_into_local_is_a_static_rejection() { let path = write_fixture("jump_into_local", JUMP_INTO_LOCAL); let compiled = compile_source_file_with_options(&path, candidate_options()); assert!(compiled.is_err(), "invalid jump must not produce a program"); + let Ok(oracle) = std::env::var("LUAJIT_ORACLE") else { + eprintln!("LUAJIT_ORACLE is unset; jump-into-local is not a differential result"); + return; + }; + let output = oracle_load_rejection(&oracle, &path); + let stderr = String::from_utf8_lossy(&output.stderr); + let code = output.status.code(); + assert_eq!( + code, + Some(2), + "text-mode load rejection is exit 2; a process failure has a different status={} stderr={stderr}", + output.status + ); + assert!( + stderr.contains("LOAD_REJECT"), + "load rejection marker missing; this is not a full-text match: {stderr}" + ); + let detail = stderr + .lines() + .skip_while(|line| *line != "LOAD_REJECT") + .skip(1) + .collect::>() + .join("\n"); + assert!( + !detail.trim().is_empty(), + "load rejection had no oracle diagnostic" + ); } #[test] @@ -583,7 +766,8 @@ fn oracle_control_config_matches_locked_52_build() { eprintln!("LUAJIT_ORACLE is unset; this is not a differential GREEN"); return; }; - let output = spawn_oracle(&path, &["-e", BASELINE_DRIVER]); + let output = spawn_oracle(&path, &["-e", BASELINE_DRIVER], None, None) + .unwrap_or_else(|error| panic!("LUAJIT_ORACLE at {path:?} failed to start: {error}")); let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); assert!( @@ -591,10 +775,348 @@ fn oracle_control_config_matches_locked_52_build() { "LUAJIT_ORACLE at {path:?} baseline failed: status={} stdout={stdout:?} stderr={stderr:?}", output.status ); - let expected = format!("{ORACLE_VERSION_BASELINE}\nGOTO_KW\nBREAK_OK\nfunction\n"); + let expected = format!("{ORACLE_VERSION_BASELINE}\njit=off\nGOTO_KW\nBREAK_OK\nfunction\n"); assert_eq!( stdout, expected, "oracle is not the locked 5.2-compat build" ); eprintln!("oracle baseline {ORACLE_VERSION_BASELINE} GOTO_KW BREAK_OK table.pack"); } + +// Digits name the taken branch. A wrong then/else changes one place and +// cannot be confused with a missed goto, a continue that falls through, or +// a stack that is not one float. +// +// 1 if 0 then; 2 would mean 0 was falsy. +// 10 if 7 then; 20 would mean a nonzero number was falsy. +// 200 if false else; 100 would mean false was truthy. +// 1000 if true then; 2000 would mean true was falsy. +// 20000 elseif of the true local; 10000 is the false arm, 40000 is else. +// 200000 not 0 stored, then used as a condition, takes else. +// 1000000 not false stored, then takes then. +// 20000000 not true stored, then takes else. +// 200000000 not 4 stored, then takes else. +// 2000000000 !0 takes else. +// Sum 2221221211. +const TRUTH_STEPS: &str = "\ +local n = 0\n\ +local x = 0\n\ +if x then\n\ + n = n + 1\n\ +else\n\ + n = n + 2\n\ +end\n\ +x = 7\n\ +if x then\n\ + n = n + 10\n\ +else\n\ + n = n + 20\n\ +end\n\ +x = false\n\ +if x then\n\ + n = n + 100\n\ +else\n\ + n = n + 200\n\ +end\n\ +x = true\n\ +if x then\n\ + n = n + 1000\n\ +else\n\ + n = n + 2000\n\ +end\n\ +local y = false\n\ +if y then\n\ + n = n + 10000\n\ +elseif x then\n\ + n = n + 20000\n\ +else\n\ + n = n + 40000\n\ +end\n\ +x = 0\n\ +local flag = not x\n\ +if flag then\n\ + n = n + 100000\n\ +else\n\ + n = n + 200000\n\ +end\n\ +flag = not false\n\ +if flag then\n\ + n = n + 1000000\n\ +else\n\ + n = n + 2000000\n\ +end\n\ +flag = not true\n\ +if flag then\n\ + n = n + 10000000\n\ +else\n\ + n = n + 20000000\n\ +end\n\ +flag = not 4\n\ +if flag then\n\ + n = n + 100000000\n\ +else\n\ + n = n + 200000000\n\ +end\n\ +if !0 then\n\ + n = n + 1000000000\n\ +else\n\ + n = n + 2000000000\n\ +end\n\ +"; + +const TRUTH_EXPECTED: f64 = 2_221_221_211.0; + +fn truth_direct() -> String { + format!("{TRUTH_STEPS}return n\n") +} + +fn truth_dispatch() -> String { + format!( + "local skipped = 0\n\ +goto body\n\ +skipped = 9\n\ +::body::\n\ +{TRUTH_STEPS}\ +return n + skipped * 10000000000\n" + ) +} + +// 1 entered while x was 0. 10 continued after x became 5. +// 100 continue skipped the tail until the last trip; 300 means continue fell through. +// 1000 reached the statement after the bool loop; 0 means continue left the dispatcher. +// 10000 would mean while false entered. +// 300000 is three trips of the bool loop. +// 1000000 is one trip of a while whose condition is a stored not result. +// Sum 1301111. A missed dispatch goto adds 70000000. +const WHILE_STEPS: &str = "\ +local seen_zero = 0\n\ +local seen_five = 0\n\ +local x = 0\n\ +while x do\n\ + if x == 0 then\n\ + seen_zero = 1\n\ + x = 5\n\ + else\n\ + seen_five = 1\n\ + break\n\ + end\n\ +end\n\ +local tails = 0\n\ +local after = 0\n\ +local trips = 0\n\ +local b = true\n\ +while b do\n\ + trips = trips + 1\n\ + if trips < 3 then\n\ + continue\n\ + end\n\ + tails = tails + 1\n\ + b = false\n\ +end\n\ +after = 1\n\ +local blocked = 0\n\ +b = false\n\ +while b do\n\ + blocked = blocked + 1\n\ + break\n\ +end\n\ +local flag = not false\n\ +local not_trips = 0\n\ +while flag do\n\ + not_trips = not_trips + 1\n\ + flag = not true\n\ +end\n\ +"; + +const WHILE_EXPECTED: f64 = 1_301_111.0; + +fn while_direct() -> String { + format!( + "{WHILE_STEPS}\ +return seen_zero + seen_five * 10 + tails * 100 + after * 1000 + blocked * 10000 + trips * 100000 + not_trips * 1000000\n" + ) +} + +fn while_dispatch() -> String { + format!( + "local skipped = 0\n\ +goto body\n\ +skipped = 7\n\ +::body::\n\ +{WHILE_STEPS}\ +return seen_zero + seen_five * 10 + tails * 100 + after * 1000 + blocked * 10000 + trips * 100000 + not_trips * 1000000 + skipped * 10000000\n" + ) +} + +// 1 if x + y then. 20 if not (x + y) else. 100 while x + y entered once. +// 2000 elseif x + y. Sum 2121. Each of those four conditions contains one Add. +const ONCE_STEPS: &str = "\ +local x = 1\n\ +local y = 2\n\ +local n = 0\n\ +if x + y then\n\ + n = n + 1\n\ +else\n\ + n = n + 2\n\ +end\n\ +if not (x + y) then\n\ + n = n + 10\n\ +else\n\ + n = n + 20\n\ +end\n\ +while x + y do\n\ + n = n + 100\n\ + break\n\ +end\n\ +if false then\n\ + n = n + 1000\n\ +elseif x + y then\n\ + n = n + 2000\n\ +else\n\ + n = n + 4000\n\ +end\n\ +"; + +const ONCE_EXPECTED: f64 = 2_121.0; + +fn once_direct() -> String { + format!("{ONCE_STEPS}return n\n") +} + +fn once_dispatch() -> String { + format!( + "local skipped = 0\n\ +goto body\n\ +skipped = 3\n\ +::body::\n\ +{ONCE_STEPS}\ +return n + skipped * 10000\n" + ) +} + +fn walk_expr(expr: &Expr, visit: &mut impl FnMut(&Expr)) { + visit(expr); + match expr { + Expr::Not(inner) | Expr::Neg(inner) => walk_expr(inner, visit), + Expr::Eq(lhs, rhs) + | Expr::Lt(lhs, rhs) + | Expr::Gt(lhs, rhs) + | Expr::Add(lhs, rhs) + | Expr::Sub(lhs, rhs) + | Expr::Mul(lhs, rhs) + | Expr::Div(lhs, rhs) => { + walk_expr(lhs, visit); + walk_expr(rhs, visit); + } + _ => {} + } +} + +fn add_count(expr: &Expr) -> usize { + let mut count = 0; + walk_expr(expr, &mut |item| { + if matches!(item, Expr::Add(_, _)) { + count += 1; + } + }); + count +} + +fn condition_add_counts(stmts: &[Stmt]) -> Vec { + let mut counts = Vec::new(); + walk_stmts(stmts, &mut |stmt| match stmt { + Stmt::IfElse { condition, .. } | Stmt::While { condition, .. } => { + counts.push(add_count(condition)); + } + _ => {} + }); + counts +} + +fn assert_each_add_condition_is_once(label: &str, source: &str) { + let ir = lowered(source); + let counts = condition_add_counts(&ir.stmts); + let with_add: Vec = counts.into_iter().filter(|count| *count > 0).collect(); + assert_eq!( + with_add, + vec![1, 1, 1, 1], + "{label}: each condition expression must be lowered once, counts={with_add:?}" + ); +} + +#[test] +fn direct_truthiness_uses_zero_as_true_and_false_as_false() { + let source = truth_direct(); + let path = write_fixture("direct_truthiness", &source); + assert!(path.extension().is_some_and(|ext| ext == "lua")); + expect_number("direct_truthiness", &source, TRUTH_EXPECTED); +} + +#[test] +fn dispatch_truthiness_matches_direct_after_a_goto() { + expect_number("dispatch_truthiness", &truth_dispatch(), TRUTH_EXPECTED); +} + +#[test] +fn direct_while_treats_zero_as_true_and_keeps_continue() { + expect_number("direct_while_truth", &while_direct(), WHILE_EXPECTED); +} + +#[test] +fn dispatch_while_treats_zero_as_true_and_keeps_continue() { + expect_number("dispatch_while_truth", &while_dispatch(), WHILE_EXPECTED); +} + +#[test] +fn direct_condition_expression_is_lowered_once() { + let source = once_direct(); + expect_number("direct_once", &source, ONCE_EXPECTED); + assert_each_add_condition_is_once("direct_once", &source); +} + +#[test] +fn dispatch_condition_expression_is_lowered_once() { + let source = once_dispatch(); + expect_number("dispatch_once", &source, ONCE_EXPECTED); + assert_each_add_condition_is_once("dispatch_once", &source); +} + +#[test] +fn missing_configured_oracle_binary_is_an_infrastructure_failure() { + let missing = "/mnt/workspace/rustscript-lua/tmp/lua52-syntax/missing-luajit"; + let error = try_spawn_oracle(missing, &["-e", "return 1"], None, None) + .expect_err("a missing configured binary must fail to start"); + assert_eq!(error.kind(), std::io::ErrorKind::NotFound); +} + +#[test] +fn oracle_harness_runs_the_fixture_once_under_joff() { + let Ok(oracle) = std::env::var("LUAJIT_ORACLE") else { + eprintln!("LUAJIT_ORACLE is unset; harness execution count is not a differential result"); + return; + }; + let sentinel = write_fixture("oracle_once_sentinel", "return 1\n"); + let once = oracle_run(&oracle, &sentinel, 1).expect("sentinel once"); + let twice = oracle_run(&oracle, &sentinel, 2).expect("sentinel twice"); + assert_eq!(once.calls, 1); + assert_eq!(twice.calls, 2); + assert_eq!(once.argc, 0); + assert_eq!(once.arg0, "nil"); + assert!(once.lines > 0, "line hook saw no sentinel execution"); + assert_eq!( + twice.lines, + once.lines * 2, + "line hook must track each execution" + ); + assert_eq!(once.value, 1.0); + assert_eq!(twice.value, 1.0); + + let business = write_fixture("oracle_once_business", &truth_direct()); + let business_once = oracle_run(&oracle, &business, 1).expect("business once"); + let business_twice = oracle_run(&oracle, &business, 2).expect("business twice"); + assert_eq!(business_once.calls, 1); + assert_eq!(business_once.argc, 0); + assert_eq!(business_twice.lines, business_once.lines * 2); + assert_eq!(business_once.value, business_twice.value); + assert_eq!(business_once.value, TRUTH_EXPECTED); +} From b872931d8d26082cea3d531bc399911ef9dffe4f Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 05:24:26 +0800 Subject: [PATCH 010/225] lower(lua): map classified numbers onto Core f64 arithmetic Floor remainder binds each operand once and uses math::floor, because Core Mod is truncating and does not match LuaJIT. Not wired into the parser. --- src/frontends/lua/number.rs | 122 +++++++ tests/luajit_number_semantics_tests.rs | 453 +++++++++++++++++++++++++ 2 files changed, 575 insertions(+) create mode 100644 src/frontends/lua/number.rs create mode 100644 tests/luajit_number_semantics_tests.rs diff --git a/src/frontends/lua/number.rs b/src/frontends/lua/number.rs new file mode 100644 index 0000000..6a4a241 --- /dev/null +++ b/src/frontends/lua/number.rs @@ -0,0 +1,122 @@ +//! Lower already-classified Lua numbers onto Core binary64 arithmetic. +//! +//! The caller has finished numeric classification. This module does not coerce +//! strings, invoke metamethods, test truthiness, or treat a Core `Int` as a +//! Lua object. Addition, subtraction, multiplication, division, and negation +//! are Core f64 operations. Floor remainder is not Core `Mod`: that opcode is +//! truncating. Power is `math::powf`. + +use vm::{BuiltinFunction, Expr, LocalIrBuilder, LocalSlot, ParseError, Stmt}; + +/// A Lua number whose classification is already done. +/// +/// `expr` must evaluate to a binary64 value. Passing a Core `Int` is outside +/// this ABI. +#[derive(Clone, Debug)] +pub(crate) struct ClassifiedNumber { + expr: Expr, +} + +impl ClassifiedNumber { + pub(crate) fn from_f64_expr(expr: Expr) -> Self { + Self { expr } + } + + pub(crate) fn literal(value: f64) -> Self { + Self { + expr: Expr::Float(value), + } + } + + pub(crate) fn neg(self) -> Expr { + Expr::Neg(Box::new(self.expr)) + } + + pub(crate) fn add(self, rhs: Self) -> Expr { + Expr::Add(Box::new(self.expr), Box::new(rhs.expr)) + } + + pub(crate) fn sub(self, rhs: Self) -> Expr { + Expr::Sub(Box::new(self.expr), Box::new(rhs.expr)) + } + + pub(crate) fn mul(self, rhs: Self) -> Expr { + Expr::Mul(Box::new(self.expr), Box::new(rhs.expr)) + } + + pub(crate) fn div(self, rhs: Self) -> Expr { + Expr::Div(Box::new(self.expr), Box::new(rhs.expr)) + } + + pub(crate) fn pow(self, exponent: Self) -> Expr { + Expr::Call( + BuiltinFunction::MathPowF.call_index(), + Vec::new(), + vec![self.expr, exponent.expr], + None, + None, + ) + } +} + +/// Temps for operations that must evaluate each operand once and then reuse it. +pub(crate) struct NumberLowering<'a> { + builder: &'a mut LocalIrBuilder, + temp_id: u32, +} + +impl<'a> NumberLowering<'a> { + pub(crate) fn new(builder: &'a mut LocalIrBuilder) -> Self { + Self { + builder, + temp_id: 0, + } + } + + /// Lua `%` on binary64: `lhs - floor(lhs / rhs) * rhs`. + /// + /// Each operand is bound once before the formula, so a side effect in an + /// operand runs once and left-to-right. + pub(crate) fn floor_mod( + &mut self, + lhs: ClassifiedNumber, + rhs: ClassifiedNumber, + ) -> Result { + let lhs_slot = self.alloc_temp("mod_lhs")?; + let rhs_slot = self.alloc_temp("mod_rhs")?; + let lhs_var = Expr::Var(lhs_slot); + let rhs_var = Expr::Var(rhs_slot); + let quotient = Expr::Div(Box::new(lhs_var.clone()), Box::new(rhs_var.clone())); + let product = Expr::Mul(Box::new(call_math_floor(quotient)), Box::new(rhs_var)); + let remainder = Expr::Sub(Box::new(lhs_var), Box::new(product)); + Ok(Expr::Block { + stmts: vec![bind_temp(lhs_slot, lhs.expr), bind_temp(rhs_slot, rhs.expr)], + expr: Box::new(remainder), + }) + } + + fn alloc_temp(&mut self, role: &str) -> Result { + let name = format!("__lua_number_{role}_{}", self.temp_id); + self.temp_id += 1; + self.builder.alloc_local_named(&name) + } +} + +fn bind_temp(slot: LocalSlot, expr: Expr) -> Stmt { + Stmt::Let { + index: slot, + declared_schema: None, + expr, + line: 1, + } +} + +fn call_math_floor(argument: Expr) -> Expr { + Expr::Call( + BuiltinFunction::MathFloor.call_index(), + Vec::new(), + vec![argument], + None, + None, + ) +} diff --git a/tests/luajit_number_semantics_tests.rs b/tests/luajit_number_semantics_tests.rs new file mode 100644 index 0000000..f89280f --- /dev/null +++ b/tests/luajit_number_semantics_tests.rs @@ -0,0 +1,453 @@ +//! Classified Lua number arithmetic, compiled and run through Core. +//! +//! Case 06 values `3.5,1,-1,-2.5` are the frozen protocol bytes. The other +//! expected bits were observed on locked LuaJIT 96f7b297326e9fd454b7186c6858b2773f94a0dc +//! with `-joff`. NaN is compared by category only. + +#[path = "../src/frontends/lua/number.rs"] +mod number; + +use number::{ClassifiedNumber, NumberLowering}; +use vm::{AssignmentKind, Compiler, Expr, LocalIrBuilder, LocalSlot, Stmt, Value, Vm}; + +const PROTOCOL_06: [&str; 4] = ["3.5", "1", "-1", "-2.5"]; +const PROTOCOL_06_BITS: [u64; 4] = [ + 0x400c_0000_0000_0000, // 3.5 + 0x3ff0_0000_0000_0000, // 1 + 0xbff0_0000_0000_0000, // -1 + 0xc004_0000_0000_0000, // -2.5 +]; + +#[test] +fn case06_business_results_match_frozen_protocol() { + let mut builder = LocalIrBuilder::new(); + let mut lowering = NumberLowering::new(&mut builder); + let quotient = ClassifiedNumber::literal(7.0).div(ClassifiedNumber::literal(2.0)); + let positive_remainder = lowering + .floor_mod( + ClassifiedNumber::literal(-5.0), + ClassifiedNumber::literal(3.0), + ) + .expect("bind remainder temps"); + let negative_remainder = lowering + .floor_mod( + ClassifiedNumber::literal(5.0), + ClassifiedNumber::literal(-3.0), + ) + .expect("bind remainder temps"); + let negative_quotient = ClassifiedNumber::literal(-5.0).div(ClassifiedNumber::literal(2.0)); + drop(lowering); + + let ran = run( + &builder, + vec![ + expr_stmt(quotient), + expr_stmt(positive_remainder), + expr_stmt(negative_remainder), + expr_stmt(negative_quotient), + ], + ); + + assert_eq!(ran.stack.len(), 4, "{:?}", ran.stack); + for (index, value) in ran.stack.iter().enumerate() { + assert_protocol_number(value, PROTOCOL_06[index], PROTOCOL_06_BITS[index]); + } +} + +#[test] +fn float_division_matches_observed_luajit_specials() { + // Divisor zero, signed zero, and infinities. Not part of frozen case 06. + let cases = [ + (1.0, 0.0, Expect::Bits(0x7ff0_0000_0000_0000)), + (-1.0, 0.0, Expect::Bits(0xfff0_0000_0000_0000)), + (0.0, 0.0, Expect::Nan), + (1.0, -0.0, Expect::Bits(0xfff0_0000_0000_0000)), + (-0.0, 1.0, Expect::Bits(0x8000_0000_0000_0000)), + (0.0, -1.0, Expect::Bits(0x8000_0000_0000_0000)), + (f64::INFINITY, 0.0, Expect::Bits(0x7ff0_0000_0000_0000)), + (1.0, f64::NAN, Expect::Nan), + ]; + for (lhs, rhs, expected) in cases { + let value = eval_binary(|left, right| left.div(right), lhs, rhs); + assert_expect(&value, expected, lhs, rhs); + } +} + +#[test] +fn floor_remainder_matches_observed_luajit_specials() { + // Negative divisor, divisor zero, inf divisor, and signed-zero results. + let cases = [ + (-5.0, -3.0, Expect::Bits(0xc000_0000_0000_0000)), + (1.0, 0.0, Expect::Nan), + (1.0, f64::INFINITY, Expect::Nan), + (-2.5, 2.5, Expect::Bits(0x0000_0000_0000_0000)), + (-0.0, -1.0, Expect::Bits(0x0000_0000_0000_0000)), + (-0.0, 1.0, Expect::Bits(0x0000_0000_0000_0000)), + (f64::NAN, 1.0, Expect::Nan), + ]; + for (lhs, rhs, expected) in cases { + let value = eval_floor_mod(lhs, rhs); + assert_expect(&value, expected, lhs, rhs); + } +} + +#[test] +fn power_matches_observed_luajit_specials() { + let cases = [ + (2.0, 3.0, Expect::Bits(0x4020_0000_0000_0000)), + (0.0, 0.0, Expect::Bits(0x3ff0_0000_0000_0000)), + (-0.0, -1.0, Expect::Bits(0xfff0_0000_0000_0000)), + (1.0, f64::NAN, Expect::Bits(0x3ff0_0000_0000_0000)), + (-2.5, 2.5, Expect::Nan), + (f64::INFINITY, 0.0, Expect::Bits(0x3ff0_0000_0000_0000)), + ]; + for (lhs, rhs, expected) in cases { + let value = eval_binary(|left, right| left.pow(right), lhs, rhs); + assert_expect(&value, expected, lhs, rhs); + } +} + +#[test] +fn add_sub_mul_and_negation_match_observed_luajit() { + let binary = [ + (-0.0, 0.0, Expect::Bits(0x0000_0000_0000_0000), Bin::Add), + (-0.0, -0.0, Expect::Bits(0x8000_0000_0000_0000), Bin::Add), + (f64::INFINITY, f64::NEG_INFINITY, Expect::Nan, Bin::Add), + (-0.0, 0.0, Expect::Bits(0x8000_0000_0000_0000), Bin::Sub), + (0.0, -0.0, Expect::Bits(0x0000_0000_0000_0000), Bin::Sub), + (-0.0, 1.0, Expect::Bits(0x8000_0000_0000_0000), Bin::Mul), + (-0.0, -1.0, Expect::Bits(0x0000_0000_0000_0000), Bin::Mul), + (f64::INFINITY, 0.0, Expect::Nan, Bin::Mul), + (1.5, 2.0, Expect::Bits(0x400c_0000_0000_0000), Bin::Add), + (3.5, 1.0, Expect::Bits(0x4004_0000_0000_0000), Bin::Sub), + (7.0, 2.0, Expect::Bits(0x402c_0000_0000_0000), Bin::Mul), + ]; + for (lhs, rhs, expected, op) in binary { + let value = eval_binary( + match op { + Bin::Add => |left, right| left.add(right), + Bin::Sub => |left, right| left.sub(right), + Bin::Mul => |left, right| left.mul(right), + }, + lhs, + rhs, + ); + assert_expect(&value, expected, lhs, rhs); + } + + let negated_zero = eval_unary(|operand| operand.neg(), 0.0); + assert_expect(&negated_zero, Expect::Bits(0x8000_0000_0000_0000), 0.0, 0.0); + let negated_negative_zero = eval_unary(|operand| operand.neg(), -0.0); + assert_expect( + &negated_negative_zero, + Expect::Bits(0x0000_0000_0000_0000), + -0.0, + 0.0, + ); + let negated_nan = eval_unary(|operand| operand.neg(), f64::NAN); + assert_expect(&negated_nan, Expect::Nan, f64::NAN, 0.0); +} + +#[test] +fn operands_are_evaluated_once_left_then_right() { + // -5 % 3 is 1 under Lua and -2 under Core Mod, so this also rejects the old path. + assert_binary_eval_once( + "floor_mod", + -5.0, + 3.0, + "1", + PROTOCOL_06_BITS[1], + |lowering, lhs, rhs| lowering.floor_mod(lhs, rhs).expect("bind remainder temps"), + ); + assert_binary_eval_once( + "add", + 7.0, + 2.0, + "9", + 0x4022_0000_0000_0000, + |_, lhs, rhs| lhs.add(rhs), + ); + assert_binary_eval_once( + "div", + 7.0, + 2.0, + "3.5", + PROTOCOL_06_BITS[0], + |_, lhs, rhs| lhs.div(rhs), + ); + assert_binary_eval_once( + "pow", + 7.0, + 2.0, + "49", + 0x4048_8000_0000_0000, + |_, lhs, rhs| lhs.pow(rhs), + ); + assert_unary_eval_once(); +} + +#[derive(Clone, Copy)] +enum Expect { + Bits(u64), + Nan, +} + +#[derive(Clone, Copy)] +enum Bin { + Add, + Sub, + Mul, +} + +struct Ran { + stack: Vec, + locals: Vec, +} + +fn eval_binary(op: fn(ClassifiedNumber, ClassifiedNumber) -> Expr, lhs: f64, rhs: f64) -> Value { + let expr = op( + ClassifiedNumber::literal(lhs), + ClassifiedNumber::literal(rhs), + ); + let builder = LocalIrBuilder::new(); + run(&builder, vec![expr_stmt(expr)]) + .stack + .into_iter() + .next() + .expect("one result") +} + +fn eval_floor_mod(lhs: f64, rhs: f64) -> Value { + let mut builder = LocalIrBuilder::new(); + let expr = { + let mut lowering = NumberLowering::new(&mut builder); + lowering + .floor_mod( + ClassifiedNumber::literal(lhs), + ClassifiedNumber::literal(rhs), + ) + .expect("bind remainder temps") + }; + run(&builder, vec![expr_stmt(expr)]) + .stack + .into_iter() + .next() + .expect("one result") +} + +fn eval_unary(op: fn(ClassifiedNumber) -> Expr, operand: f64) -> Value { + let expr = op(ClassifiedNumber::literal(operand)); + let builder = LocalIrBuilder::new(); + run(&builder, vec![expr_stmt(expr)]) + .stack + .into_iter() + .next() + .expect("one result") +} + +fn assert_binary_eval_once( + label: &str, + lhs: f64, + rhs: f64, + text: &str, + bits: u64, + op: fn(&mut NumberLowering<'_>, ClassifiedNumber, ClassifiedNumber) -> Expr, +) { + let mut builder = LocalIrBuilder::new(); + let sequence = builder.alloc_local_named("sequence").expect("sequence"); + let left_mark = builder.alloc_local_named("left_mark").expect("left mark"); + let right_mark = builder.alloc_local_named("right_mark").expect("right mark"); + let expr = { + let mut lowering = NumberLowering::new(&mut builder); + op( + &mut lowering, + ClassifiedNumber::from_f64_expr(counted_literal(sequence, left_mark, lhs)), + ClassifiedNumber::from_f64_expr(counted_literal(sequence, right_mark, rhs)), + ) + }; + let ran = run( + &builder, + vec![ + let_int(sequence, 0), + let_int(left_mark, 0), + let_int(right_mark, 0), + expr_stmt(expr), + ], + ); + assert_eq!( + local_int(&ran, sequence), + 2, + "{label} evaluated an operand more than once: {:?}", + ran.locals + ); + assert_eq!( + local_int(&ran, left_mark), + 1, + "{label} did not evaluate the left operand first: {:?}", + ran.locals + ); + assert_eq!( + local_int(&ran, right_mark), + 2, + "{label} did not evaluate the right operand second: {:?}", + ran.locals + ); + assert_protocol_number(&ran.stack[0], text, bits); +} + +fn assert_unary_eval_once() { + let mut builder = LocalIrBuilder::new(); + let sequence = builder.alloc_local_named("sequence").expect("sequence"); + let mark = builder.alloc_local_named("mark").expect("mark"); + let expr = ClassifiedNumber::from_f64_expr(counted_literal(sequence, mark, 0.0)).neg(); + let ran = run( + &builder, + vec![let_int(sequence, 0), let_int(mark, 0), expr_stmt(expr)], + ); + assert_eq!(local_int(&ran, sequence), 1, "{:?}", ran.locals); + assert_eq!(local_int(&ran, mark), 1, "{:?}", ran.locals); + assert_expect(&ran.stack[0], Expect::Bits(0x8000_0000_0000_0000), 0.0, 0.0); +} + +fn counted_literal(sequence: LocalSlot, mark: LocalSlot, value: f64) -> Expr { + Expr::Block { + stmts: vec![ + Stmt::Assign { + kind: AssignmentKind::Set, + index: sequence, + expr: Expr::Add(Box::new(Expr::Var(sequence)), Box::new(Expr::Int(1))), + line: 1, + }, + Stmt::Assign { + kind: AssignmentKind::Set, + index: mark, + expr: Expr::Var(sequence), + line: 1, + }, + ], + expr: Box::new(Expr::Float(value)), + } +} + +fn run(_builder: &LocalIrBuilder, stmts: Vec) -> Ran { + // LocalIrBuilder does not expose its next local. Every allocated slot is + // referenced by the statements, so the frame size is one past the highest index. + let local_count = local_count_in(&stmts); + run_stmts(local_count, stmts) +} + +fn run_stmts(local_count: usize, stmts: Vec) -> Ran { + let mut compiler = Compiler::new(); + compiler.set_root_local_count(local_count); + let program = compiler + .compile_program(&stmts) + .unwrap_or_else(|error| panic!("compile failed: {error}")); + let mut vm = Vm::new(program); + vm.run() + .unwrap_or_else(|error| panic!("run failed: {error}")); + Ran { + stack: vm.stack().to_vec(), + locals: vm.locals().to_vec(), + } +} + +fn local_count_in(stmts: &[Stmt]) -> usize { + let mut highest = 0usize; + for stmt in stmts { + note_stmt(stmt, &mut highest); + } + highest +} + +fn note_stmt(stmt: &Stmt, highest: &mut usize) { + match stmt { + Stmt::Let { index, expr, .. } | Stmt::Assign { index, expr, .. } => { + bump(highest, *index); + note_expr(expr, highest); + } + Stmt::Expr { expr, .. } => note_expr(expr, highest), + other => panic!("unexpected statement in number probe: {other:?}"), + } +} + +fn note_expr(expr: &Expr, highest: &mut usize) { + match expr { + Expr::Var(slot) => bump(highest, *slot), + Expr::Neg(inner) => note_expr(inner, highest), + Expr::Add(lhs, rhs) + | Expr::Sub(lhs, rhs) + | Expr::Mul(lhs, rhs) + | Expr::Div(lhs, rhs) + | Expr::Mod(lhs, rhs) => { + note_expr(lhs, highest); + note_expr(rhs, highest); + } + Expr::Call(_, _, arguments, _, _) => { + for argument in arguments { + note_expr(argument, highest); + } + } + Expr::Block { stmts, expr } => { + for stmt in stmts { + note_stmt(stmt, highest); + } + note_expr(expr, highest); + } + Expr::Float(_) | Expr::Int(_) => {} + other => panic!("unexpected expression in number probe: {other:?}"), + } +} + +fn bump(highest: &mut usize, slot: LocalSlot) { + let next = usize::from(slot) + 1; + if next > *highest { + *highest = next; + } +} + +fn expr_stmt(expr: Expr) -> Stmt { + Stmt::Expr { expr, line: 1 } +} + +fn let_int(slot: LocalSlot, value: i64) -> Stmt { + Stmt::Let { + index: slot, + declared_schema: None, + expr: Expr::Int(value), + line: 1, + } +} + +fn local_int(ran: &Ran, slot: LocalSlot) -> i64 { + match ran.locals.get(usize::from(slot)) { + Some(Value::Int(value)) => *value, + other => panic!("local {slot:?} was not an int: {other:?}"), + } +} + +fn assert_protocol_number(value: &Value, text: &str, bits: u64) { + let Value::Float(number) = value else { + panic!("protocol number {text} was not binary64: {value:?}"); + }; + assert_eq!(number.to_bits(), bits, "bits for {text}"); + assert_eq!(format!("{number}"), text); +} + +fn assert_expect(value: &Value, expected: Expect, lhs: f64, rhs: f64) { + match (value, expected) { + (Value::Float(number), Expect::Nan) => { + assert!( + number.is_nan(), + "expected NaN for {lhs} ? {rhs}, got {number}" + ); + } + (Value::Float(number), Expect::Bits(bits)) => { + assert_eq!( + number.to_bits(), + bits, + "bits for {lhs} ? {rhs}, value {number}" + ); + } + (other, _) => panic!("expected binary64 for {lhs} ? {rhs}, got {other:?}"), + } +} From 2b41fe44300b2fe8768d8f12eff8e1798eaeede9 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 06:10:55 +0800 Subject: [PATCH 011/225] fix(lua): isolate number temps and reject known non-float literals Remainder temps use builder-local names outside the Lua identifier grammar, so a guest local and a nested remainder no longer share slots. ClassifiedNumber rejects a directly visible Int or other non-float literal instead of letting Core Div truncate it. Sequential remainder slot growth is measured and left for the future lowerer. --- src/frontends/lua/number.rs | 87 ++++++++-- tests/luajit_number_semantics_tests.rs | 213 +++++++++++++++++-------- 2 files changed, 223 insertions(+), 77 deletions(-) diff --git a/src/frontends/lua/number.rs b/src/frontends/lua/number.rs index 6a4a241..2efda0c 100644 --- a/src/frontends/lua/number.rs +++ b/src/frontends/lua/number.rs @@ -5,29 +5,70 @@ //! Lua object. Addition, subtraction, multiplication, division, and negation //! are Core f64 operations. Floor remainder is not Core `Mod`: that opcode is //! truncating. Power is `math::powf`. +//! +//! Remainder temps are names outside the Lua identifier grammar. They are +//! probed on the same builder, because `alloc_local_named` reuses a slot for +//! an existing name and unnamed allocation is private. A process-wide counter +//! or a hard-to-guess legal identifier is not a private namespace. +//! +//! Each remainder takes two fresh frame slots. Core locals are frame-scoped, +//! and this kernel does not own statement boundaries, so it cannot reuse a +//! slot that a still-live nested expression might need. A future lowerer must +//! bound that cost before production wiring. This module does not. use vm::{BuiltinFunction, Expr, LocalIrBuilder, LocalSlot, ParseError, Stmt}; /// A Lua number whose classification is already done. /// -/// `expr` must evaluate to a binary64 value. Passing a Core `Int` is outside -/// this ABI. +/// This kernel checks only a directly visible literal. A visible `Int`, or +/// another non-float literal, is rejected even in release builds. It is not +/// coerced. `Var` and `Call` are not inspected: matching those variants does +/// not prove binary64. Full-pipeline integration must pass +/// [`FloatTypeEvidence`] only after the Lua numeric classifier has established +/// Float. #[derive(Clone, Debug)] pub(crate) struct ClassifiedNumber { expr: Expr, } -impl ClassifiedNumber { - pub(crate) fn from_f64_expr(expr: Expr) -> Self { - Self { expr } +/// Caller attestation that an expression is already binary64. +/// +/// Constructing this does not inspect the expression. The future numeric +/// classifier is the production source of this token. This kernel does not +/// re-check `Var` or `Call`. +#[derive(Clone, Copy, Debug)] +pub(crate) struct FloatTypeEvidence { + _private: (), +} + +impl FloatTypeEvidence { + pub(crate) const fn attested() -> Self { + Self { _private: () } } +} +impl ClassifiedNumber { pub(crate) fn literal(value: f64) -> Self { Self { expr: Expr::Float(value), } } + /// `evidence` is the caller's proof. A directly visible non-float literal + /// still fails, because that proof is contradicted by the IR the kernel + /// can see. + pub(crate) fn from_attested_float( + expr: Expr, + _evidence: FloatTypeEvidence, + ) -> Result { + if let Some(kind) = directly_known_non_float_literal(&expr) { + return Err(ParseError::new(format!( + "classified Lua number requires binary64, found Core {kind} literal" + ))); + } + Ok(Self { expr }) + } + pub(crate) fn neg(self) -> Expr { Expr::Neg(Box::new(self.expr)) } @@ -60,17 +101,16 @@ impl ClassifiedNumber { } /// Temps for operations that must evaluate each operand once and then reuse it. +/// +/// Slots stay live for the returned expression. Calling `floor_mod` again on +/// this lowering allocates new slots; it does not reclaim the previous pair. pub(crate) struct NumberLowering<'a> { builder: &'a mut LocalIrBuilder, - temp_id: u32, } impl<'a> NumberLowering<'a> { pub(crate) fn new(builder: &'a mut LocalIrBuilder) -> Self { - Self { - builder, - temp_id: 0, - } + Self { builder } } /// Lua `%` on binary64: `lhs - floor(lhs / rhs) * rhs`. @@ -96,9 +136,30 @@ impl<'a> NumberLowering<'a> { } fn alloc_temp(&mut self, role: &str) -> Result { - let name = format!("__lua_number_{role}_{}", self.temp_id); - self.temp_id += 1; - self.builder.alloc_local_named(&name) + // `$` and `.` are outside `[A-Za-z_][A-Za-z0-9_]*`, so a Lua local + // cannot use this name. The probe is what makes a second lowering on + // the same builder fresh; the ordinal is not a process-wide counter. + let mut ordinal = 0u32; + loop { + let name = format!("$lua.number.{role}.{ordinal}"); + if self.builder.resolve_local_expr(&name).is_none() { + return self.builder.alloc_local_named(&name); + } + ordinal = ordinal + .checked_add(1) + .ok_or_else(|| ParseError::new("lua number temp ordinal overflow"))?; + } + } +} + +fn directly_known_non_float_literal(expr: &Expr) -> Option<&'static str> { + match expr { + Expr::Int(_) => Some("Int"), + Expr::Null => Some("Null"), + Expr::Bool(_) => Some("Bool"), + Expr::String(_) => Some("String"), + Expr::Bytes(_) => Some("Bytes"), + _ => None, } } diff --git a/tests/luajit_number_semantics_tests.rs b/tests/luajit_number_semantics_tests.rs index f89280f..1162370 100644 --- a/tests/luajit_number_semantics_tests.rs +++ b/tests/luajit_number_semantics_tests.rs @@ -7,7 +7,7 @@ #[path = "../src/frontends/lua/number.rs"] mod number; -use number::{ClassifiedNumber, NumberLowering}; +use number::{ClassifiedNumber, FloatTypeEvidence, NumberLowering}; use vm::{AssignmentKind, Compiler, Expr, LocalIrBuilder, LocalSlot, Stmt, Value, Vm}; const PROTOCOL_06: [&str; 4] = ["3.5", "1", "-1", "-2.5"]; @@ -39,7 +39,7 @@ fn case06_business_results_match_frozen_protocol() { drop(lowering); let ran = run( - &builder, + builder, vec![ expr_stmt(quotient), expr_stmt(positive_remainder), @@ -186,6 +186,131 @@ fn operands_are_evaluated_once_left_then_right() { assert_unary_eval_once(); } +#[test] +fn remainder_temps_keep_a_guest_local_and_a_nested_rhs() { + // Both examples share one builder and one Core compile/run. + // `__lua_number_mod_lhs_0` is a legal Lua identifier and the name the + // pre-fix allocator reused for its first remainder temp. + let mut builder = LocalIrBuilder::new(); + let guest = builder + .alloc_local_named("__lua_number_mod_lhs_0") + .expect("guest local"); + let collided = { + let mut lowering = NumberLowering::new(&mut builder); + lowering + .floor_mod( + ClassifiedNumber::literal(7.0), + ClassifiedNumber::literal(5.0), + ) + .expect("colliding remainder") + }; + let nested = { + let inner = { + let mut lowering = NumberLowering::new(&mut builder); + lowering + .floor_mod( + ClassifiedNumber::literal(10.0), + ClassifiedNumber::literal(4.0), + ) + .expect("inner remainder") + }; + let mut lowering = NumberLowering::new(&mut builder); + lowering + .floor_mod( + ClassifiedNumber::literal(7.0), + ClassifiedNumber::from_attested_float(inner, FloatTypeEvidence::attested()) + .expect("inner remainder is binary64"), + ) + .expect("outer remainder") + }; + let ir = builder.finish(vec![ + let_int(guest, 42), + expr_stmt(collided), + expr_stmt(nested), + ]); + let ran = run_stmts(ir.locals, ir.stmts); + let collision_is_two = matches!( + ran.stack.first(), + Some(Value::Float(number)) if number.to_bits() == 0x4000_0000_0000_0000 + ); + let guest_kept = matches!(ran.locals.get(usize::from(guest)), Some(Value::Int(42))); + let nested_is_one = matches!( + ran.stack.get(1), + Some(Value::Float(number)) if number.to_bits() == PROTOCOL_06_BITS[1] + ); + let private_names: Vec<&str> = ir + .local_bindings + .iter() + .filter(|(_, slot)| *slot != guest) + .map(|(name, _)| name.as_str()) + .collect(); + let private_names_are_lua = private_names.iter().any(|name| is_lua_identifier(name)); + assert!( + collision_is_two, + "7 % 5 should be 2; finish_locals={} stack={:?} locals={:?}", + ir.locals, ran.stack, ran.locals + ); + assert!( + guest_kept, + "guest slot was overwritten; locals={:?}", + ran.locals + ); + assert!( + nested_is_one, + "7 % (10 % 4) should be 1; stack={:?} locals={:?}", + ran.stack, ran.locals + ); + assert!( + !private_names_are_lua, + "private temps are legal Lua identifiers: {private_names:?}" + ); +} + +#[test] +fn known_int_literal_is_rejected_before_truncating_div() { + let evidence = FloatTypeEvidence::attested(); + let seven = ClassifiedNumber::from_attested_float(Expr::Int(7), evidence); + let two = ClassifiedNumber::from_attested_float(Expr::Int(2), evidence); + let negative = ClassifiedNumber::from_attested_float(Expr::Int(-5), evidence); + let message = seven + .expect_err("Int(7) must not enter classified arithmetic") + .message; + assert!( + message.contains("Int"), + "rejection should name the visible literal, got {message}" + ); + assert!(two.is_err(), "Int(2) must not enter classified arithmetic"); + assert!( + negative.is_err(), + "Int(-5) must not enter classified arithmetic" + ); + let boolean = ClassifiedNumber::from_attested_float(Expr::Bool(true), evidence); + assert!( + boolean.is_err(), + "a visible Bool literal must not enter classified arithmetic" + ); +} + +#[test] +fn attested_var_is_not_retyped_by_the_number_kernel() { + let mut builder = LocalIrBuilder::new(); + let slot = builder.alloc_local_named("n").expect("guest local"); + let classified = + ClassifiedNumber::from_attested_float(Expr::Var(slot), FloatTypeEvidence::attested()); + assert!( + classified.is_ok(), + "matching Var is not Float evidence and is not a kernel type check: {classified:?}" + ); + let call = ClassifiedNumber::from_attested_float( + Expr::Call(0, Vec::new(), Vec::new(), None, None), + FloatTypeEvidence::attested(), + ); + assert!( + call.is_ok(), + "matching Call is not Float evidence and is not a kernel type check: {call:?}" + ); +} + #[derive(Clone, Copy)] enum Expect { Bits(u64), @@ -210,7 +335,7 @@ fn eval_binary(op: fn(ClassifiedNumber, ClassifiedNumber) -> Expr, lhs: f64, rhs ClassifiedNumber::literal(rhs), ); let builder = LocalIrBuilder::new(); - run(&builder, vec![expr_stmt(expr)]) + run(builder, vec![expr_stmt(expr)]) .stack .into_iter() .next() @@ -228,7 +353,7 @@ fn eval_floor_mod(lhs: f64, rhs: f64) -> Value { ) .expect("bind remainder temps") }; - run(&builder, vec![expr_stmt(expr)]) + run(builder, vec![expr_stmt(expr)]) .stack .into_iter() .next() @@ -238,7 +363,7 @@ fn eval_floor_mod(lhs: f64, rhs: f64) -> Value { fn eval_unary(op: fn(ClassifiedNumber) -> Expr, operand: f64) -> Value { let expr = op(ClassifiedNumber::literal(operand)); let builder = LocalIrBuilder::new(); - run(&builder, vec![expr_stmt(expr)]) + run(builder, vec![expr_stmt(expr)]) .stack .into_iter() .next() @@ -261,12 +386,12 @@ fn assert_binary_eval_once( let mut lowering = NumberLowering::new(&mut builder); op( &mut lowering, - ClassifiedNumber::from_f64_expr(counted_literal(sequence, left_mark, lhs)), - ClassifiedNumber::from_f64_expr(counted_literal(sequence, right_mark, rhs)), + attested_float(counted_literal(sequence, left_mark, lhs)), + attested_float(counted_literal(sequence, right_mark, rhs)), ) }; let ran = run( - &builder, + builder, vec![ let_int(sequence, 0), let_int(left_mark, 0), @@ -299,9 +424,9 @@ fn assert_unary_eval_once() { let mut builder = LocalIrBuilder::new(); let sequence = builder.alloc_local_named("sequence").expect("sequence"); let mark = builder.alloc_local_named("mark").expect("mark"); - let expr = ClassifiedNumber::from_f64_expr(counted_literal(sequence, mark, 0.0)).neg(); + let expr = attested_float(counted_literal(sequence, mark, 0.0)).neg(); let ran = run( - &builder, + builder, vec![let_int(sequence, 0), let_int(mark, 0), expr_stmt(expr)], ); assert_eq!(local_int(&ran, sequence), 1, "{:?}", ran.locals); @@ -329,11 +454,9 @@ fn counted_literal(sequence: LocalSlot, mark: LocalSlot, value: f64) -> Expr { } } -fn run(_builder: &LocalIrBuilder, stmts: Vec) -> Ran { - // LocalIrBuilder does not expose its next local. Every allocated slot is - // referenced by the statements, so the frame size is one past the highest index. - let local_count = local_count_in(&stmts); - run_stmts(local_count, stmts) +fn run(builder: LocalIrBuilder, stmts: Vec) -> Ran { + let ir = builder.finish(stmts); + run_stmts(ir.locals, ir.stmts) } fn run_stmts(local_count: usize, stmts: Vec) -> Ran { @@ -351,58 +474,20 @@ fn run_stmts(local_count: usize, stmts: Vec) -> Ran { } } -fn local_count_in(stmts: &[Stmt]) -> usize { - let mut highest = 0usize; - for stmt in stmts { - note_stmt(stmt, &mut highest); - } - highest +fn attested_float(expr: Expr) -> ClassifiedNumber { + ClassifiedNumber::from_attested_float(expr, FloatTypeEvidence::attested()) + .expect("caller constructed a binary64 expression") } -fn note_stmt(stmt: &Stmt, highest: &mut usize) { - match stmt { - Stmt::Let { index, expr, .. } | Stmt::Assign { index, expr, .. } => { - bump(highest, *index); - note_expr(expr, highest); - } - Stmt::Expr { expr, .. } => note_expr(expr, highest), - other => panic!("unexpected statement in number probe: {other:?}"), - } -} - -fn note_expr(expr: &Expr, highest: &mut usize) { - match expr { - Expr::Var(slot) => bump(highest, *slot), - Expr::Neg(inner) => note_expr(inner, highest), - Expr::Add(lhs, rhs) - | Expr::Sub(lhs, rhs) - | Expr::Mul(lhs, rhs) - | Expr::Div(lhs, rhs) - | Expr::Mod(lhs, rhs) => { - note_expr(lhs, highest); - note_expr(rhs, highest); - } - Expr::Call(_, _, arguments, _, _) => { - for argument in arguments { - note_expr(argument, highest); - } - } - Expr::Block { stmts, expr } => { - for stmt in stmts { - note_stmt(stmt, highest); - } - note_expr(expr, highest); - } - Expr::Float(_) | Expr::Int(_) => {} - other => panic!("unexpected expression in number probe: {other:?}"), - } -} - -fn bump(highest: &mut usize, slot: LocalSlot) { - let next = usize::from(slot) + 1; - if next > *highest { - *highest = next; +fn is_lua_identifier(name: &str) -> bool { + let mut chars = name.chars(); + let Some(first) = chars.next() else { + return false; + }; + if !(first.is_ascii_alphabetic() || first == '_') { + return false; } + chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_') } fn expr_stmt(expr: Expr) -> Stmt { From c13b2b02152e3edc2d8307a7dd25bfc101550a30 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 19:00:54 +0800 Subject: [PATCH 012/225] lower(lua): classify proven binary64 source onto the number kernel The source seam lowers only grammar-proven floats and locals in the same trusted scope. Chains are hoisted onto the existing kernel temps; Core still owns slot compaction. --- src/frontends/lua/number.rs | 34 + src/frontends/lua/number_source.rs | 300 +++++++++ tests/luajit_number_source_tests.rs | 981 ++++++++++++++++++++++++++++ 3 files changed, 1315 insertions(+) create mode 100644 src/frontends/lua/number_source.rs create mode 100644 tests/luajit_number_source_tests.rs diff --git a/src/frontends/lua/number.rs b/src/frontends/lua/number.rs index 2efda0c..39ac4c8 100644 --- a/src/frontends/lua/number.rs +++ b/src/frontends/lua/number.rs @@ -98,6 +98,10 @@ impl ClassifiedNumber { None, ) } + + pub(crate) fn into_expr(self) -> Expr { + self.expr + } } /// Temps for operations that must evaluate each operand once and then reuse it. @@ -135,6 +139,36 @@ impl<'a> NumberLowering<'a> { }) } + /// Bind a guest local on the same builder that owns remainder temps. + pub(crate) fn alloc_local_named(&mut self, name: &str) -> Result { + self.builder.alloc_local_named(name) + } + + /// Bind an already classified value to a fresh temp. + /// + /// This does not search for a dead slot. Core compacts the frame later. + pub(crate) fn store( + &mut self, + value: ClassifiedNumber, + stmts: &mut Vec, + ) -> Result { + let slot = self.alloc_temp("value")?; + stmts.push(bind_temp(slot, value.expr)); + ClassifiedNumber::from_attested_float(Expr::Var(slot), FloatTypeEvidence::attested()) + } + + /// Keep a chain step shallow when the value is not already a literal or slot. + pub(crate) fn materialize( + &mut self, + value: ClassifiedNumber, + stmts: &mut Vec, + ) -> Result { + if matches!(value.expr, Expr::Float(_) | Expr::Var(_)) { + return Ok(value); + } + self.store(value, stmts) + } + fn alloc_temp(&mut self, role: &str) -> Result { // `$` and `.` are outside `[A-Za-z_][A-Za-z0-9_]*`, so a Lua local // cannot use this name. The probe is what makes a second lowering on diff --git a/src/frontends/lua/number_source.rs b/src/frontends/lua/number_source.rs new file mode 100644 index 0000000..cb0e620 --- /dev/null +++ b/src/frontends/lua/number_source.rs @@ -0,0 +1,300 @@ +//! Narrow source seam from a parsed Lua chunk onto the binary64 number kernel. +//! +//! Only a grammar kind that is already binary64, or a local whose initializer +//! this walk proved, may receive [`FloatTypeEvidence`]. `LL`, `ULL`, imaginary +//! suffixes, and names this walk did not prove stay outside that token. +//! Chains are hoisted with the kernel's temps so a flat source spine does not +//! become an unbounded Core expression. Slot reuse stays with Core. + +use super::ast::{BinOp, Chunk, Expr, ExprList, LocalName, NumberKind, Span, Stmt, UnOp}; +use super::number::{ClassifiedNumber, FloatTypeEvidence, NumberLowering}; +use super::resolve::Resolution; +use vm::{Expr as CoreExpr, FrontendIr, LocalIrBuilder, LocalSlot, ParseError, Stmt as CoreStmt}; + +pub(crate) struct LoweredNumberChunk { + pub(crate) ir: FrontendIr, + pub(crate) logical_slots: usize, + pub(crate) binding_names: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum NumberSourceError { + Syntax { message: String }, + CompileUnsupported { reason: String }, + NotFloat { kind: &'static str }, +} + +struct ProvenLocal { + name: Vec, + slot: LocalSlot, +} + +pub(crate) fn lower_proven_chunk( + source: &str, + chunk: &Chunk, + resolution: &Resolution, +) -> Result { + if let Some(error) = resolution.errors.first() { + return Err(NumberSourceError::Syntax { + message: format!("resolve: {error:?}"), + }); + } + let mut builder = LocalIrBuilder::new(); + let mut stmts = Vec::new(); + { + let mut lowering = NumberLowering::new(&mut builder); + let mut env = Vec::new(); + for stmt in &chunk.body.stmts { + lower_stmt(source, stmt, &mut lowering, &mut stmts, &mut env)?; + } + } + let ir = builder.finish(stmts); + let binding_names = ir + .local_bindings + .iter() + .map(|(name, _)| name.clone()) + .collect(); + let logical_slots = ir.locals; + Ok(LoweredNumberChunk { + ir, + logical_slots, + binding_names, + }) +} + +fn lower_stmt( + source: &str, + stmt: &Stmt, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + env: &mut Vec, +) -> Result<(), NumberSourceError> { + match stmt { + Stmt::Empty { .. } => Ok(()), + Stmt::Local { + span, + names, + values, + } => lower_local(source, *span, names, values, lowering, stmts, env), + Stmt::Return { span, values } => { + let value = single_proven(values, "return is not a single proven number")?; + let lowered = lower_expr(source, value, lowering, stmts, env)?; + stmts.push(CoreStmt::Expr { + expr: lowered.into_expr(), + line: line_of(source, *span), + }); + Ok(()) + } + _ => Err(unsupported("statement is outside the numeric subset")), + } +} + +fn lower_local( + source: &str, + span: Span, + names: &[LocalName], + values: &ExprList, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + env: &mut Vec, +) -> Result<(), NumberSourceError> { + if names.len() != 1 || values.exprs.len() != 1 { + return Err(unsupported("local is not a single proven number")); + } + let lowered = lower_expr(source, &values.exprs[0], lowering, stmts, env)?; + let name = &names[0].name; + let text = std::str::from_utf8(&name.bytes) + .map_err(|_| unsupported("local name is not a proven number"))?; + let slot = lowering.alloc_local_named(text).map_err(kernel_error)?; + stmts.push(CoreStmt::Let { + index: slot, + declared_schema: None, + expr: lowered.into_expr(), + line: line_of(source, span), + }); + env.push(ProvenLocal { + name: name.bytes.clone(), + slot, + }); + Ok(()) +} + +fn lower_expr( + source: &str, + expr: &Expr, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + env: &[ProvenLocal], +) -> Result { + match expr { + Expr::Number { raw, kind, .. } => lower_number(raw, *kind), + Expr::Name { name, .. } => lookup_proven(name.bytes.as_slice(), env), + Expr::Paren { inner, .. } => lower_expr(source, inner, lowering, stmts, env), + Expr::Unary { op, expr, .. } => lower_unary(*op, expr, source, lowering, stmts, env), + Expr::Binary { + op, left, right, .. + } => { + let lhs = lower_expr(source, left, lowering, stmts, env)?; + let rhs = lower_expr(source, right, lowering, stmts, env)?; + apply(*op, lhs, rhs, lowering, stmts) + } + Expr::BinaryChain { base, steps, .. } => { + let mut acc = lower_expr(source, base, lowering, stmts, env)?; + for (index, step) in steps.iter().enumerate() { + let rhs = lower_expr(source, &step.expr, lowering, stmts, env)?; + acc = apply(step.op, acc, rhs, lowering, stmts)?; + if index + 1 != steps.len() { + acc = lowering.materialize(acc, stmts).map_err(kernel_error)?; + } + } + Ok(acc) + } + _ => Err(unsupported("expression is outside the numeric subset")), + } +} + +fn lower_unary( + op: UnOp, + expr: &Expr, + source: &str, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + env: &[ProvenLocal], +) -> Result { + if op != UnOp::Neg { + return Err(unsupported("operator is outside the numeric subset")); + } + let inner = lower_expr(source, expr, lowering, stmts, env)?; + let inner = lowering.materialize(inner, stmts).map_err(kernel_error)?; + attest(inner.neg()) +} + +fn apply( + op: BinOp, + lhs: ClassifiedNumber, + rhs: ClassifiedNumber, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, +) -> Result { + let lhs = lowering.materialize(lhs, stmts).map_err(kernel_error)?; + let rhs = lowering.materialize(rhs, stmts).map_err(kernel_error)?; + let expr = match op { + BinOp::Add => lhs.add(rhs), + BinOp::Sub => lhs.sub(rhs), + BinOp::Mul => lhs.mul(rhs), + BinOp::Div => lhs.div(rhs), + BinOp::Pow => lhs.pow(rhs), + BinOp::Mod => lowering.floor_mod(lhs, rhs).map_err(kernel_error)?, + _ => return Err(unsupported("operator is outside the numeric subset")), + }; + attest(expr) +} + +fn lower_number(raw: &str, kind: NumberKind) -> Result { + let value = match kind { + NumberKind::Signed64 => return Err(not_float("Signed64")), + NumberKind::Unsigned64 => return Err(not_float("Unsigned64")), + NumberKind::Imaginary => return Err(not_float("Imaginary")), + NumberKind::HexFloat => return Err(unsupported("literal form is not lowered")), + NumberKind::Integer | NumberKind::Float => parse_decimal(raw)?, + NumberKind::HexInteger => parse_prefixed_integer(raw, 16)?, + NumberKind::Binary => parse_prefixed_integer(raw, 2)?, + }; + if value.is_nan() { + return Err(unsupported("literal form is not lowered")); + } + Ok(ClassifiedNumber::literal(value)) +} + +fn parse_decimal(raw: &str) -> Result { + let normalized = if raw.starts_with('.') { + format!("0{raw}") + } else if let Some(prefix) = raw.strip_suffix('.') { + format!("{prefix}.0") + } else { + raw.to_string() + }; + normalized + .parse::() + .map_err(|_| unsupported("literal form is not lowered")) +} + +fn parse_prefixed_integer(raw: &str, radix: u32) -> Result { + let digits = raw + .get(2..) + .filter(|digits| !digits.is_empty()) + .ok_or_else(|| unsupported("literal form is not lowered"))?; + let marker = raw.as_bytes().get(1).copied().unwrap_or(0) | 0x20; + let expected = if radix == 16 { b'x' } else { b'b' }; + if raw.len() < 3 || raw.as_bytes()[0] != b'0' || marker != expected { + return Err(unsupported("literal form is not lowered")); + } + let mut magnitude: u64 = 0; + for byte in digits.bytes() { + let digit = match byte { + b'0'..=b'9' => byte - b'0', + b'a'..=b'f' => byte - b'a' + 10, + b'A'..=b'F' => byte - b'A' + 10, + _ => return Err(unsupported("literal form is not lowered")), + }; + if u32::from(digit) >= radix { + return Err(unsupported("literal form is not lowered")); + } + let scaled = magnitude + .checked_mul(u64::from(radix)) + .ok_or_else(|| unsupported("literal form is not lowered"))?; + magnitude = scaled + .checked_add(u64::from(digit)) + .ok_or_else(|| unsupported("literal form is not lowered"))?; + } + Ok(magnitude as f64) +} + +fn lookup_proven(name: &[u8], env: &[ProvenLocal]) -> Result { + let slot = env + .iter() + .rev() + .find(|local| local.name == name) + .map(|local| local.slot) + .ok_or_else(|| unsupported("name is not a proven local"))?; + attest(CoreExpr::Var(slot)) +} + +fn single_proven<'a>( + values: &'a ExprList, + reason: &'static str, +) -> Result<&'a Expr, NumberSourceError> { + if values.exprs.len() == 1 { + Ok(&values.exprs[0]) + } else { + Err(unsupported(reason)) + } +} + +fn attest(expr: CoreExpr) -> Result { + ClassifiedNumber::from_attested_float(expr, FloatTypeEvidence::attested()).map_err(kernel_error) +} + +fn kernel_error(error: ParseError) -> NumberSourceError { + NumberSourceError::CompileUnsupported { + reason: format!("number kernel: {}", error.message), + } +} + +fn unsupported(reason: &'static str) -> NumberSourceError { + NumberSourceError::CompileUnsupported { + reason: reason.to_string(), + } +} + +fn not_float(kind: &'static str) -> NumberSourceError { + NumberSourceError::NotFloat { kind } +} + +fn line_of(source: &str, span: Span) -> u32 { + let end = usize::try_from(span.start) + .unwrap_or(source.len()) + .min(source.len()); + let line = source[..end].bytes().filter(|byte| *byte == b'\n').count() + 1; + u32::try_from(line).unwrap_or(u32::MAX) +} diff --git a/tests/luajit_number_source_tests.rs b/tests/luajit_number_source_tests.rs new file mode 100644 index 0000000..6e28590 --- /dev/null +++ b/tests/luajit_number_source_tests.rs @@ -0,0 +1,981 @@ +//! Standard Lua numeric fragments through the source seam. +//! +//! The trial plugin lives here. It is not a product entry and it does not +//! register hosts. Each executed sample is real Lua source, lowered by the +//! seam, then compiled with `SourcePlugin` and run on the VM. + +#[path = "../src/frontends/lua/ast.rs"] +mod ast; +#[path = "../src/frontends/lua/lexer.rs"] +mod lexer; +#[path = "../src/frontends/lua/number.rs"] +mod number; +#[path = "../src/frontends/lua/number_source.rs"] +mod number_source; +#[path = "../src/frontends/lua/parser.rs"] +mod parser; +#[path = "../src/frontends/lua/resolve.rs"] +mod resolve; + +use std::io::Write; +use std::process::{Command, Stdio}; + +use number_source::NumberSourceError; +use vm::{ + CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, ParseError, SourceFlavor, + SourcePlugin, Value, Vm, VmStatus, +}; + +const ORACLE_VERSION: &str = "LuaJIT 2.1.1795119671"; + +struct ExecuteCase { + name: &'static str, + source: &'static str, + category: Category, + expect: Expect, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Category { + Finite, + SignedZero, + NonFinite, + Empty, +} + +enum Expect { + Bits(u64), + Class(&'static str), + Empty, +} + +struct NegativeCase { + name: &'static str, + source: &'static str, + layer: &'static str, + detail: &'static str, +} + +#[test] +fn proven_binary64_sources_run_through_the_plugin() { + let cases = execute_cases(); + let mut ran = 0usize; + for case in &cases { + let outcome = run_plugin(case.source); + match (&case.expect, outcome) { + (Expect::Empty, Ok(run)) => { + assert!( + run.stack.is_empty(), + "{} should return no values, stack={:?}", + case.name, + run.stack + ); + } + (Expect::Bits(bits), Ok(run)) => { + assert_eq!(run.stack.len(), 1, "{}", case.name); + assert_bits(&run.stack[0], *bits, case.name); + } + (Expect::Class(class), Ok(run)) => { + assert_eq!(run.stack.len(), 1, "{}", case.name); + assert_class(&run.stack[0], class, case.name); + } + (_, Err(failure)) => panic!( + "{} failed at {}: {}", + case.name, failure.layer, failure.detail + ), + } + ran += 1; + } + assert_eq!(ran, cases.len()); + println!("execute cases={ran}"); +} + +#[test] +fn legal_uncovered_sources_are_not_syntax_rejections() { + let cases = negative_cases(); + let mut syntax = 0usize; + let mut not_float = 0usize; + let mut unsupported = 0usize; + for case in &cases { + let failure = run_plugin(case.source).expect_err(case.name); + assert_eq!( + failure.layer, case.layer, + "{} detail={}", + case.name, failure.detail + ); + assert!( + failure.detail.contains(case.detail), + "{} detail={} missing {}", + case.name, + failure.detail, + case.detail + ); + match case.layer { + "syntax" => syntax += 1, + "classify-not-float" => not_float += 1, + "compile-unsupported" => unsupported += 1, + other => panic!("unexpected negative layer {other}"), + } + } + println!( + "negative cases={} syntax={syntax} classify-not-float={not_float} compile-unsupported={unsupported}", + cases.len() + ); + assert_eq!(syntax, 3); + assert_eq!(not_float, 3); + assert_eq!(unsupported, 8); +} + +#[test] +fn sequential_mods_use_core_slots_and_keep_the_result() { + let source = sequential_mod_source(12); + let lowered = lower_source(&source).expect("sequential mods are proven floats"); + let run = run_plugin(&source).expect("sequential mods compile and run"); + assert_bits(&run.stack[0], 1.0f64.to_bits(), "10 % 3"); + assert!( + lowered.logical_slots > 8, + "sequential sample should sit above the pinned compaction threshold, logical={}", + lowered.logical_slots + ); + assert!( + run.frame_slots < lowered.logical_slots, + "Core slot allocation should shorten sequential temps: logical={} frame={}", + lowered.logical_slots, + run.frame_slots + ); + assert!( + lowered + .binding_names + .iter() + .filter(|name| name.starts_with("$lua.number.")) + .all(|name| !is_lua_identifier(name)), + "number temps must stay outside the Lua identifier grammar: {:?}", + lowered.binding_names + ); + println!( + "slot boundary logical={} frame={} temps={}", + lowered.logical_slots, + run.frame_slots, + lowered.binding_names.len() + ); + if let Ok(path) = std::env::var("LUAJIT_ORACLE") { + let oracle = oracle_execute(&path, &source); + assert!(oracle.accepted, "sequential mods are legal LuaJIT"); + assert_eq!(oracle.values.len(), 1, "{:?}", oracle.values); + assert_same_number(&oracle.values[0], &run.stack[0], "sequential"); + println!("slot boundary oracle compared=1"); + } +} + +#[test] +fn configured_oracle_matches_the_same_sources() { + let Some(path) = std::env::var("LUAJIT_ORACLE").ok() else { + println!( + "oracle differential not run: LUAJIT_ORACLE unset; execute=0 signed-zero=0 nonfinite=0 not-float=0 unsupported=0 syntax-reject=0; not a differential GREEN" + ); + return; + }; + assert_oracle_baseline(&path); + let mut execute = 0usize; + let mut signed_zero = 0usize; + let mut nonfinite = 0usize; + let mut empty = 0usize; + for case in execute_cases() { + let ours = run_plugin(case.source).unwrap_or_else(|failure| { + panic!("{} rust {}: {}", case.name, failure.layer, failure.detail) + }); + let oracle = oracle_execute(&path, case.source); + assert!( + oracle.accepted, + "{} LuaJIT rejected source that the seam executed", + case.name + ); + assert_eq!( + oracle.values.len(), + ours.stack.len(), + "{} return count oracle={:?} rust={:?}", + case.name, + oracle.values, + ours.stack + ); + for (index, (oracle_value, rust_value)) in + oracle.values.iter().zip(ours.stack.iter()).enumerate() + { + assert_same_number(oracle_value, rust_value, &format!("{}[{index}]", case.name)); + } + match case.category { + Category::Finite => execute += 1, + Category::SignedZero => signed_zero += 1, + Category::NonFinite => nonfinite += 1, + Category::Empty => empty += 1, + } + } + let mut not_float = 0usize; + let mut unsupported = 0usize; + let mut syntax_reject = 0usize; + for case in negative_cases() { + let oracle_accepted = oracle_load(&path, case.source); + let failure = run_plugin(case.source).expect_err(case.name); + assert_eq!(failure.layer, case.layer, "{}", case.name); + match case.layer { + "syntax" => { + assert!( + !oracle_accepted, + "{} should be a LuaJIT source rejection", + case.name + ); + syntax_reject += 1; + } + "classify-not-float" => { + assert!(oracle_accepted, "{} is legal LuaJIT syntax", case.name); + not_float += 1; + } + "compile-unsupported" => { + assert!(oracle_accepted, "{} is legal LuaJIT syntax", case.name); + unsupported += 1; + } + other => panic!("unexpected layer {other}"), + } + } + println!( + "oracle differential execute={execute} signed-zero={signed_zero} nonfinite={nonfinite} empty={empty} not-float={not_float} compile-unsupported={unsupported} syntax-reject={syntax_reject}" + ); + assert_eq!(execute, 27); + assert_eq!(signed_zero, 4); + assert_eq!(nonfinite, 4); + assert_eq!(empty, 1); + assert_eq!(not_float, 3); + assert_eq!(unsupported, 8); + assert_eq!(syntax_reject, 3); +} + +#[derive(Debug)] +struct Run { + stack: Vec, + frame_slots: usize, +} + +#[derive(Debug)] +struct LayerFailure { + layer: &'static str, + detail: String, +} + +struct NumericPlugin; + +static NUMERIC_PLUGIN: NumericPlugin = NumericPlugin; + +impl SourcePlugin for NumericPlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &["lua"] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + lower_source(source).map(|lowered| lowered.ir) + } +} + +struct OwnedLowered { + ir: FrontendIr, + logical_slots: usize, + binding_names: Vec, +} + +fn lower_source(source: &str) -> Result { + let chunk = parser::parse_chunk(source.as_bytes()) + .map_err(|error| ParseError::new(format!("lua number syntax: {}", error.message)))?; + let resolution = resolve::resolve(&chunk); + let lowered = + number_source::lower_proven_chunk(source, &chunk, &resolution).map_err(source_error)?; + Ok(OwnedLowered { + logical_slots: lowered.logical_slots, + binding_names: lowered.binding_names, + ir: lowered.ir, + }) +} + +fn source_error(error: NumberSourceError) -> ParseError { + match error { + NumberSourceError::Syntax { message } => { + ParseError::new(format!("lua number syntax: {message}")) + } + NumberSourceError::CompileUnsupported { reason } => { + ParseError::new(format!("lua number compile unsupported: {reason}")) + } + NumberSourceError::NotFloat { kind } => { + ParseError::new(format!("lua number not float: {kind}")) + } + } +} + +fn run_plugin(source: &str) -> Result { + let compiled = vm::compile_source_with_flavor_and_options( + source, + SourceFlavor::Lua, + CompileSourceFileOptions::new().with_source_plugin(&NUMERIC_PLUGIN), + ); + let compiled = match compiled { + Ok(compiled) => compiled, + Err(error) => return Err(label_compile_error(&error.to_string())), + }; + let frame_slots = compiled.program.local_count; + let mut vm = Vm::new(compiled.program); + match vm.run() { + Err(error) => Err(LayerFailure { + layer: "run", + detail: error.to_string(), + }), + Ok(status) => { + if status != VmStatus::Halted { + return Err(LayerFailure { + layer: "run", + detail: format!("{status:?}"), + }); + } + Ok(Run { + stack: vm.stack().to_vec(), + frame_slots, + }) + } + } +} + +fn label_compile_error(display: &str) -> LayerFailure { + let layer = if display.contains("lua number syntax:") { + "syntax" + } else if display.contains("lua number not float:") { + "classify-not-float" + } else if display.contains("lua number compile unsupported:") { + "compile-unsupported" + } else { + "compile-bind" + }; + LayerFailure { + layer, + detail: display.to_string(), + } +} + +fn execute_cases() -> Vec { + vec![ + case("empty", "", Category::Empty, Expect::Empty), + case( + "div", + "return 7/2", + Category::Finite, + Expect::Bits(3.5f64.to_bits()), + ), + case( + "int-literal", + "return 7", + Category::Finite, + Expect::Bits(7.0f64.to_bits()), + ), + case( + "exponent", + "return 1.5e1", + Category::Finite, + Expect::Bits(15.0f64.to_bits()), + ), + case( + "leading-dot", + "return .5", + Category::Finite, + Expect::Bits(0.5f64.to_bits()), + ), + case( + "trailing-dot", + "return 5.", + Category::Finite, + Expect::Bits(5.0f64.to_bits()), + ), + case( + "hex-int", + "return 0x10", + Category::Finite, + Expect::Bits(16.0f64.to_bits()), + ), + case( + "binary", + "return 0b11", + Category::Finite, + Expect::Bits(3.0f64.to_bits()), + ), + case( + "mod-neg-pos", + "return -5%3", + Category::Finite, + Expect::Bits(1.0f64.to_bits()), + ), + case( + "mod-pos-neg", + "return 5%-3", + Category::Finite, + Expect::Bits((-1.0f64).to_bits()), + ), + case( + "mod-neg-neg", + "return -5%-3", + Category::Finite, + Expect::Bits((-2.0f64).to_bits()), + ), + case( + "pow-right", + "return 2^3^2", + Category::Finite, + Expect::Bits(512.0f64.to_bits()), + ), + case( + "neg-pow", + "return -2^2", + Category::Finite, + Expect::Bits((-4.0f64).to_bits()), + ), + case( + "paren-neg-pow", + "return (-2)^2", + Category::Finite, + Expect::Bits(4.0f64.to_bits()), + ), + case( + "neg-mul", + "return -2*3", + Category::Finite, + Expect::Bits((-6.0f64).to_bits()), + ), + case( + "nested-mod", + "return 7%(10%4)", + Category::Finite, + Expect::Bits(1.0f64.to_bits()), + ), + case( + "mixed", + "return (7+1)/2", + Category::Finite, + Expect::Bits(4.0f64.to_bits()), + ), + case( + "precedence", + "return 1+2*3-4", + Category::Finite, + Expect::Bits(3.0f64.to_bits()), + ), + case( + "add-chain", + "return 1+2+3+4", + Category::Finite, + Expect::Bits(10.0f64.to_bits()), + ), + case( + "local", + "local x = 7/2\nreturn x", + Category::Finite, + Expect::Bits(3.5f64.to_bits()), + ), + case( + "two-locals", + "local a = -5\nlocal b = 3\nreturn a % b", + Category::Finite, + Expect::Bits(1.0f64.to_bits()), + ), + case( + "guest-slot", + "local guest = 42\nreturn 7 % 5 * 1000 + guest", + Category::Finite, + Expect::Bits(2042.0f64.to_bits()), + ), + case( + "nested-guest-slot", + "local guest = 42\nreturn 7 % (10 % 4) * 1000 + guest", + Category::Finite, + Expect::Bits(1042.0f64.to_bits()), + ), + case( + "comment", + "return 7/2 -- half", + Category::Finite, + Expect::Bits(3.5f64.to_bits()), + ), + case( + "semicolon", + "return 7/2;", + Category::Finite, + Expect::Bits(3.5f64.to_bits()), + ), + case( + "large-mod", + "return (2^53)%3", + Category::Finite, + Expect::Bits(2.0f64.to_bits()), + ), + case( + "large-mod-neg-divisor", + "return (2^53)%-3", + Category::Finite, + Expect::Bits(0.0f64.to_bits()), + ), + case( + "large-mod-neg-dividend", + "return (-2^53)%3", + Category::Finite, + Expect::Bits(0.0f64.to_bits()), + ), + case( + "neg-zero", + "return -0", + Category::SignedZero, + Expect::Bits((-0.0f64).to_bits()), + ), + case( + "div-signed-zero", + "return 0/-1", + Category::SignedZero, + Expect::Bits((-0.0f64).to_bits()), + ), + case( + "add-signed-zero", + "return -0+0", + Category::SignedZero, + Expect::Bits(0.0f64.to_bits()), + ), + case( + "add-neg-zeros", + "return -0+-0", + Category::SignedZero, + Expect::Bits((-0.0f64).to_bits()), + ), + case( + "div-inf", + "return 1/0", + Category::NonFinite, + Expect::Class("inf"), + ), + case( + "div-neg-inf", + "return -1/0", + Category::NonFinite, + Expect::Class("-inf"), + ), + case( + "div-nan", + "return 0/0", + Category::NonFinite, + Expect::Class("nan"), + ), + case( + "mod-nan", + "return 1%0", + Category::NonFinite, + Expect::Class("nan"), + ), + ] +} + +fn case( + name: &'static str, + source: &'static str, + category: Category, + expect: Expect, +) -> ExecuteCase { + ExecuteCase { + name, + source, + category, + expect, + } +} + +fn negative_cases() -> Vec { + vec![ + NegativeCase { + name: "bare-number", + source: "42", + layer: "syntax", + detail: "lua number syntax:", + }, + NegativeCase { + name: "goto-keyword", + source: "local goto = 1", + layer: "syntax", + detail: "lua number syntax:", + }, + NegativeCase { + name: "idiv", + source: "return 1 // 2", + layer: "syntax", + detail: "lua number syntax:", + }, + NegativeCase { + name: "signed64", + source: "return 1LL", + layer: "classify-not-float", + detail: "Signed64", + }, + NegativeCase { + name: "unsigned64", + source: "return 1ULL", + layer: "classify-not-float", + detail: "Unsigned64", + }, + NegativeCase { + name: "imaginary", + source: "return 1i", + layer: "classify-not-float", + detail: "Imaginary", + }, + NegativeCase { + name: "global", + source: "return x", + layer: "compile-unsupported", + detail: "proven local", + }, + NegativeCase { + name: "call", + source: "return math.abs(-2)", + layer: "compile-unsupported", + detail: "numeric subset", + }, + NegativeCase { + name: "string-add", + source: "return 1 + \"2\"", + layer: "compile-unsupported", + detail: "numeric subset", + }, + NegativeCase { + name: "hex-float", + source: "return 0x1.8p1", + layer: "compile-unsupported", + detail: "literal form", + }, + NegativeCase { + name: "assign", + source: "local x = 1\nx = 2\nreturn x", + layer: "compile-unsupported", + detail: "numeric subset", + }, + NegativeCase { + name: "do-block", + source: "do\n local x = 7 / 2\n return x\nend", + layer: "compile-unsupported", + detail: "numeric subset", + }, + NegativeCase { + name: "multi-return", + source: "return 1, 2", + layer: "compile-unsupported", + detail: "single proven", + }, + NegativeCase { + name: "bare-return", + source: "return", + layer: "compile-unsupported", + detail: "single proven", + }, + ] +} + +fn sequential_mod_source(count: usize) -> String { + let mut source = String::new(); + for index in 0..count { + source.push_str(&format!("local r{index} = {} % 3\n", 10 + index)); + } + source.push_str("return r0\n"); + source +} + +fn assert_bits(value: &Value, bits: u64, name: &str) { + let Value::Float(number) = value else { + panic!("{name} was not binary64: {value:?}"); + }; + assert_eq!(number.to_bits(), bits, "{name} value={number}"); +} + +fn assert_class(value: &Value, class: &str, name: &str) { + let Value::Float(number) = value else { + panic!("{name} was not binary64: {value:?}"); + }; + assert_eq!(float_class(*number), class, "{name} value={number}"); +} + +fn float_class(number: f64) -> &'static str { + if number.is_nan() { + "nan" + } else if number.is_infinite() && number.is_sign_positive() { + "inf" + } else if number.is_infinite() { + "-inf" + } else if number == 0.0 && number.is_sign_negative() { + "-0" + } else if number == 0.0 { + "+0" + } else { + "finite" + } +} + +fn is_lua_identifier(name: &str) -> bool { + let mut chars = name.chars(); + let Some(first) = chars.next() else { + return false; + }; + if !(first.is_ascii_alphabetic() || first == '_') { + return false; + } + chars.all(|ch| ch.is_ascii_alphanumeric() || ch == '_') +} + +struct OracleRun { + accepted: bool, + values: Vec, +} + +#[derive(Debug)] +enum OracleNumber { + Class(&'static str), + Bits(u64), +} + +fn assert_oracle_baseline(path: &str) { + let output = spawn_oracle(path, &["-joff", "-e", BASELINE_DRIVER], None); + require_success(path, &output, "baseline"); + let text = String::from_utf8_lossy(&output.stdout); + let mut lines = text.lines(); + assert_eq!(lines.next(), Some(ORACLE_VERSION), "oracle version: {text}"); + assert_eq!(lines.next(), Some("GOTO_KW"), "5.2 goto keyword: {text}"); + assert_eq!(lines.next(), Some("BREAK_OK"), "5.2 break: {text}"); + assert_eq!(lines.next(), Some("function"), "table.pack: {text}"); +} + +fn oracle_load(path: &str, source: &str) -> bool { + let output = spawn_oracle(path, &["-joff", "-e", LOAD_DRIVER], Some(source.as_bytes())); + require_success(path, &output, "load"); + let text = String::from_utf8_lossy(&output.stdout); + match text.lines().next().unwrap_or("") { + "ACCEPT" => true, + "REJECT" => false, + other => panic!("oracle load protocol for {source:?}: {other}"), + } +} + +fn oracle_execute(path: &str, source: &str) -> OracleRun { + let output = spawn_oracle(path, &["-joff", "-e", EXEC_DRIVER], Some(source.as_bytes())); + require_success(path, &output, "execute"); + let text = String::from_utf8_lossy(&output.stdout); + let mut lines = text.lines(); + let marker = lines.next().unwrap_or(""); + if marker == "REJECT" { + return OracleRun { + accepted: false, + values: Vec::new(), + }; + } + assert_eq!(marker, "ACCEPT", "oracle protocol for {source:?}: {text}"); + let mut values = Vec::new(); + for line in lines { + if line.is_empty() { + continue; + } + values.push(parse_oracle_value(line)); + } + OracleRun { + accepted: true, + values, + } +} + +fn parse_oracle_value(line: &str) -> OracleNumber { + match line { + "nan" => OracleNumber::Class("nan"), + "inf" => OracleNumber::Class("inf"), + "-inf" => OracleNumber::Class("-inf"), + "-0" => OracleNumber::Bits((-0.0f64).to_bits()), + "+0" => OracleNumber::Bits(0.0f64.to_bits()), + other => OracleNumber::Bits(parse_lua_hex_float(other).to_bits()), + } +} + +fn assert_same_number(oracle: &OracleNumber, rust: &Value, label: &str) { + let Value::Float(number) = rust else { + panic!("{label} rust value was not binary64: {rust:?}"); + }; + match oracle { + OracleNumber::Class(class) => assert_eq!(float_class(*number), *class, "{label}"), + OracleNumber::Bits(bits) => assert_eq!(number.to_bits(), *bits, "{label} rust={number}"), + } +} + +fn parse_lua_hex_float(text: &str) -> f64 { + let (negative, rest) = if let Some(rest) = text.strip_prefix('-') { + (true, rest) + } else { + (false, text) + }; + let rest = rest + .strip_prefix("0x") + .or_else(|| rest.strip_prefix("0X")) + .unwrap_or_else(|| panic!("oracle finite value was not %a: {text}")); + let (digits, exponent) = rest + .split_once('p') + .or_else(|| rest.split_once('P')) + .unwrap_or_else(|| panic!("oracle finite value was not %a: {text}")); + let exponent: i32 = exponent.parse().expect("oracle exponent"); + let mut magnitude: u64 = 0; + let mut fraction_digits = 0i32; + let mut seen_dot = false; + for ch in digits.chars() { + if ch == '.' { + seen_dot = true; + continue; + } + let digit = ch + .to_digit(16) + .unwrap_or_else(|| panic!("oracle hex digit in {text}")); + magnitude = magnitude * 16 + u64::from(digit); + if seen_dot { + fraction_digits += 1; + } + } + let scale = exponent - fraction_digits * 4; + let mut value = ldexp_u64(magnitude, scale); + if negative { + value = -value; + } + value +} + +fn ldexp_u64(magnitude: u64, scale: i32) -> f64 { + if magnitude == 0 { + return 0.0; + } + let mut digits = magnitude; + let mut exponent = scale; + while digits > (1u64 << 53) { + digits >>= 1; + exponent += 1; + } + (digits as f64) * 2f64.powi(exponent) +} + +fn spawn_oracle(path: &str, args: &[&str], stdin_bytes: Option<&[u8]>) -> std::process::Output { + let mut cmd = Command::new(path); + cmd.args(args) + .stdin(if stdin_bytes.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(target_os = "linux")] + unsafe { + use std::os::unix::process::CommandExt; + cmd.pre_exec(limit_oracle_child); + } + let mut child = cmd.spawn().unwrap_or_else(|err| { + panic!("LUAJIT_ORACLE at {path:?} failed to start: {err}"); + }); + if let Some(bytes) = stdin_bytes { + let mut input = child.stdin.take().unwrap_or_else(|| { + panic!("LUAJIT_ORACLE at {path:?} has no stdin pipe"); + }); + input.write_all(bytes).unwrap_or_else(|err| { + panic!("LUAJIT_ORACLE at {path:?} rejected stdin: {err}"); + }); + } + child.wait_with_output().unwrap_or_else(|err| { + panic!("LUAJIT_ORACLE at {path:?} failed while waiting: {err}"); + }) +} + +#[cfg(target_os = "linux")] +fn limit_oracle_child() -> std::io::Result<()> { + #[repr(C)] + struct RLimit { + cur: u64, + max: u64, + } + unsafe extern "C" { + fn setrlimit(resource: i32, rlim: *const RLimit) -> i32; + fn alarm(seconds: u32) -> u32; + fn _exit(code: i32) -> !; + } + const RLIMIT_CPU: i32 = 0; + const RLIMIT_AS: i32 = 9; + let cpu = RLimit { cur: 2, max: 2 }; + let address = RLimit { + cur: 128 * 1024 * 1024, + max: 128 * 1024 * 1024, + }; + unsafe { + if setrlimit(RLIMIT_CPU, &cpu) != 0 || setrlimit(RLIMIT_AS, &address) != 0 { + _exit(126); + } + alarm(5); + } + Ok(()) +} + +fn require_success(path: &str, output: &std::process::Output, what: &str) { + if output.status.success() && output.stderr.is_empty() { + return; + } + panic!( + "LUAJIT_ORACLE at {path:?} {what} failed: status={} stdout={:?} stderr={:?}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +const BASELINE_DRIVER: &str = "\ +io.write(jit.version, '\\n')\n\ +local g = load('local goto = 1', '@g', 't')\n\ +local b = load('for i=1,2 do break print(i) end', '@b', 't')\n\ +io.write(g and 'BAD_GOTO' or 'GOTO_KW', '\\n')\n\ +io.write(b and 'BREAK_OK' or 'BREAK_BAD', '\\n')\n\ +io.write(type(table.pack), '\\n')\n\ +"; + +const LOAD_DRIVER: &str = "\ +local src = io.read('*a')\n\ +local fn = load(src, '@probe', 't')\n\ +io.write(fn and 'ACCEPT\\n' or 'REJECT\\n')\n\ +"; + +const EXEC_DRIVER: &str = "\ +local src = io.read('*a')\n\ +local fn, err = load(src, '@probe', 't')\n\ +if not fn then\n\ + io.write('REJECT\\n')\n\ + return\n\ +end\n\ +io.write('ACCEPT\\n')\n\ +local packed = table.pack(fn())\n\ +for i = 1, packed.n do\n\ + local v = packed[i]\n\ + if type(v) ~= 'number' then\n\ + io.write('TYPE:', type(v), '\\n')\n\ + elseif v ~= v then\n\ + io.write('nan\\n')\n\ + elseif v == math.huge then\n\ + io.write('inf\\n')\n\ + elseif v == -math.huge then\n\ + io.write('-inf\\n')\n\ + elseif v == 0 and 1/v < 0 then\n\ + io.write('-0\\n')\n\ + elseif v == 0 then\n\ + io.write('+0\\n')\n\ + else\n\ + io.write(string.format('%a', v), '\\n')\n\ + end\n\ +end\n\ +"; From 52a5c93383f72946d2e6d5f877d8a008f0044eec Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 19:45:49 +0800 Subject: [PATCH 013/225] fix(lua): close binary64 evidence and cover numeric boundaries An arbitrary Core slot is no longer float evidence. Arithmetic stays on ClassifiedNumber until the consuming statement, and %a subnormals keep their exact bits. The claimed literal and remainder edges are compared with locked LuaJIT, including LL/ULL/i type categories. --- src/frontends/lua/number.rs | 204 ++++++++------ src/frontends/lua/number_source.rs | 135 +++++----- tests/luajit_number_semantics_tests.rs | 199 +++++++------- tests/luajit_number_source_tests.rs | 354 +++++++++++++++++++------ 4 files changed, 570 insertions(+), 322 deletions(-) diff --git a/src/frontends/lua/number.rs b/src/frontends/lua/number.rs index 39ac4c8..fde4ca1 100644 --- a/src/frontends/lua/number.rs +++ b/src/frontends/lua/number.rs @@ -1,10 +1,10 @@ //! Lower already-classified Lua numbers onto Core binary64 arithmetic. //! //! The caller has finished numeric classification. This module does not coerce -//! strings, invoke metamethods, test truthiness, or treat a Core `Int` as a -//! Lua object. Addition, subtraction, multiplication, division, and negation -//! are Core f64 operations. Floor remainder is not Core `Mod`: that opcode is -//! truncating. Power is `math::powf`. +//! strings, invoke metamethods, test truthiness, or accept a Core expression as +//! proof of binary64. Addition, subtraction, multiplication, division, and +//! negation are Core f64 operations. Floor remainder is not Core `Mod`: that +//! opcode is truncating. Power is `math::powf`. //! //! Remainder temps are names outside the Lua identifier grammar. They are //! probed on the same builder, because `alloc_local_named` reuses a slot for @@ -15,38 +15,20 @@ //! and this kernel does not own statement boundaries, so it cannot reuse a //! slot that a still-live nested expression might need. A future lowerer must //! bound that cost before production wiring. This module does not. +//! +//! `ClassifiedNumber` is closed. Arithmetic returns the same type, and +//! `into_expr` is only for the statement that consumes the value. A local or +//! temp is a typed reference returned by the operation that just emitted the +//! binding. There is no constructor from an arbitrary `Expr` or `LocalSlot`. use vm::{BuiltinFunction, Expr, LocalIrBuilder, LocalSlot, ParseError, Stmt}; -/// A Lua number whose classification is already done. -/// -/// This kernel checks only a directly visible literal. A visible `Int`, or -/// another non-float literal, is rejected even in release builds. It is not -/// coerced. `Var` and `Call` are not inspected: matching those variants does -/// not prove binary64. Full-pipeline integration must pass -/// [`FloatTypeEvidence`] only after the Lua numeric classifier has established -/// Float. +/// A Lua number built only from a binary64 literal or from an operation on one. #[derive(Clone, Debug)] pub(crate) struct ClassifiedNumber { expr: Expr, } -/// Caller attestation that an expression is already binary64. -/// -/// Constructing this does not inspect the expression. The future numeric -/// classifier is the production source of this token. This kernel does not -/// re-check `Var` or `Call`. -#[derive(Clone, Copy, Debug)] -pub(crate) struct FloatTypeEvidence { - _private: (), -} - -impl FloatTypeEvidence { - pub(crate) const fn attested() -> Self { - Self { _private: () } - } -} - impl ClassifiedNumber { pub(crate) fn literal(value: f64) -> Self { Self { @@ -54,54 +36,102 @@ impl ClassifiedNumber { } } - /// `evidence` is the caller's proof. A directly visible non-float literal - /// still fails, because that proof is contradicted by the IR the kernel - /// can see. - pub(crate) fn from_attested_float( - expr: Expr, - _evidence: FloatTypeEvidence, - ) -> Result { - if let Some(kind) = directly_known_non_float_literal(&expr) { - return Err(ParseError::new(format!( - "classified Lua number requires binary64, found Core {kind} literal" - ))); + pub(crate) fn neg(self) -> Self { + Self { + expr: Expr::Neg(Box::new(self.expr)), } - Ok(Self { expr }) } - pub(crate) fn neg(self) -> Expr { - Expr::Neg(Box::new(self.expr)) - } - - pub(crate) fn add(self, rhs: Self) -> Expr { - Expr::Add(Box::new(self.expr), Box::new(rhs.expr)) + pub(crate) fn add(self, rhs: Self) -> Self { + Self { + expr: Expr::Add(Box::new(self.expr), Box::new(rhs.expr)), + } } - pub(crate) fn sub(self, rhs: Self) -> Expr { - Expr::Sub(Box::new(self.expr), Box::new(rhs.expr)) + pub(crate) fn sub(self, rhs: Self) -> Self { + Self { + expr: Expr::Sub(Box::new(self.expr), Box::new(rhs.expr)), + } } - pub(crate) fn mul(self, rhs: Self) -> Expr { - Expr::Mul(Box::new(self.expr), Box::new(rhs.expr)) + pub(crate) fn mul(self, rhs: Self) -> Self { + Self { + expr: Expr::Mul(Box::new(self.expr), Box::new(rhs.expr)), + } } - pub(crate) fn div(self, rhs: Self) -> Expr { - Expr::Div(Box::new(self.expr), Box::new(rhs.expr)) + pub(crate) fn div(self, rhs: Self) -> Self { + Self { + expr: Expr::Div(Box::new(self.expr), Box::new(rhs.expr)), + } } - pub(crate) fn pow(self, exponent: Self) -> Expr { - Expr::Call( - BuiltinFunction::MathPowF.call_index(), - Vec::new(), - vec![self.expr, exponent.expr], - None, - None, - ) + pub(crate) fn pow(self, exponent: Self) -> Self { + Self { + expr: Expr::Call( + BuiltinFunction::MathPowF.call_index(), + Vec::new(), + vec![self.expr, exponent.expr], + None, + None, + ), + } } + /// Final consumption. Callers that still need a classified value must use + /// the reference returned by `bind_named`, `store`, or `materialize`. pub(crate) fn into_expr(self) -> Expr { self.expr } + + /// Slot named by a binding this kernel just emitted. + /// + /// Literals and arithmetic results name no slot. This does not classify a + /// caller-supplied slot. + #[cfg(test)] + #[allow(dead_code)] + pub(crate) fn bound_slot(&self) -> Option { + match &self.expr { + Expr::Var(slot) => Some(*slot), + _ => None, + } + } + + /// Closed test producer. The value expression is always `Expr::Float`. + /// + /// `before` may observe evaluation. It is not a number source, and it + /// cannot turn an external slot into the produced value. + #[cfg(test)] + #[allow(dead_code)] + pub(crate) fn from_observed_literal(before: Vec, value: f64) -> Self { + if before.is_empty() { + return Self::literal(value); + } + Self { + expr: Expr::Block { + stmts: before, + expr: Box::new(Expr::Float(value)), + }, + } + } +} + +/// An external Core slot was not emitted from a classified value. +#[cfg(test)] +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct UnprovenSlot { + pub(crate) slot: LocalSlot, +} + +/// Refuse an arbitrary slot. There is no success path. +/// +/// A typed reference exists only as the return value of `bind_named`, +/// `store`, or `materialize`. +#[cfg(test)] +#[allow(dead_code)] +pub(crate) fn external_slot_evidence(slot: LocalSlot) -> Result { + Err(UnprovenSlot { slot }) } /// Temps for operations that must evaluate each operand once and then reuse it. @@ -125,7 +155,7 @@ impl<'a> NumberLowering<'a> { &mut self, lhs: ClassifiedNumber, rhs: ClassifiedNumber, - ) -> Result { + ) -> Result { let lhs_slot = self.alloc_temp("mod_lhs")?; let rhs_slot = self.alloc_temp("mod_rhs")?; let lhs_var = Expr::Var(lhs_slot); @@ -133,15 +163,38 @@ impl<'a> NumberLowering<'a> { let quotient = Expr::Div(Box::new(lhs_var.clone()), Box::new(rhs_var.clone())); let product = Expr::Mul(Box::new(call_math_floor(quotient)), Box::new(rhs_var)); let remainder = Expr::Sub(Box::new(lhs_var), Box::new(product)); - Ok(Expr::Block { - stmts: vec![bind_temp(lhs_slot, lhs.expr), bind_temp(rhs_slot, rhs.expr)], - expr: Box::new(remainder), + Ok(ClassifiedNumber { + expr: Expr::Block { + stmts: vec![ + bind_temp(lhs_slot, lhs.into_expr()), + bind_temp(rhs_slot, rhs.into_expr()), + ], + expr: Box::new(remainder), + }, }) } - /// Bind a guest local on the same builder that owns remainder temps. - pub(crate) fn alloc_local_named(&mut self, name: &str) -> Result { - self.builder.alloc_local_named(name) + /// Emit a guest binding of an already classified value. + /// + /// The returned reference names that binding. It is not rebuilt from a + /// slot the caller already had. + pub(crate) fn bind_named( + &mut self, + name: &str, + value: ClassifiedNumber, + line: u32, + stmts: &mut Vec, + ) -> Result { + let slot = self.builder.alloc_local_named(name)?; + stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: value.into_expr(), + line, + }); + Ok(ClassifiedNumber { + expr: Expr::Var(slot), + }) } /// Bind an already classified value to a fresh temp. @@ -153,8 +206,10 @@ impl<'a> NumberLowering<'a> { stmts: &mut Vec, ) -> Result { let slot = self.alloc_temp("value")?; - stmts.push(bind_temp(slot, value.expr)); - ClassifiedNumber::from_attested_float(Expr::Var(slot), FloatTypeEvidence::attested()) + stmts.push(bind_temp(slot, value.into_expr())); + Ok(ClassifiedNumber { + expr: Expr::Var(slot), + }) } /// Keep a chain step shallow when the value is not already a literal or slot. @@ -186,17 +241,6 @@ impl<'a> NumberLowering<'a> { } } -fn directly_known_non_float_literal(expr: &Expr) -> Option<&'static str> { - match expr { - Expr::Int(_) => Some("Int"), - Expr::Null => Some("Null"), - Expr::Bool(_) => Some("Bool"), - Expr::String(_) => Some("String"), - Expr::Bytes(_) => Some("Bytes"), - _ => None, - } -} - fn bind_temp(slot: LocalSlot, expr: Expr) -> Stmt { Stmt::Let { index: slot, diff --git a/src/frontends/lua/number_source.rs b/src/frontends/lua/number_source.rs index cb0e620..19d6083 100644 --- a/src/frontends/lua/number_source.rs +++ b/src/frontends/lua/number_source.rs @@ -1,15 +1,15 @@ //! Narrow source seam from a parsed Lua chunk onto the binary64 number kernel. //! -//! Only a grammar kind that is already binary64, or a local whose initializer -//! this walk proved, may receive [`FloatTypeEvidence`]. `LL`, `ULL`, imaginary -//! suffixes, and names this walk did not prove stay outside that token. -//! Chains are hoisted with the kernel's temps so a flat source spine does not -//! become an unbounded Core expression. Slot reuse stays with Core. +//! Only a grammar kind that is already binary64, or a local this walk just +//! bound from a classified value, enters the kernel. `LL`, `ULL`, imaginary +//! suffixes, and names this walk did not prove stay outside it. Chains are +//! hoisted with the kernel's temps so a flat source spine does not become an +//! unbounded Core expression. Slot reuse stays with Core. use super::ast::{BinOp, Chunk, Expr, ExprList, LocalName, NumberKind, Span, Stmt, UnOp}; -use super::number::{ClassifiedNumber, FloatTypeEvidence, NumberLowering}; +use super::number::{ClassifiedNumber, NumberLowering}; use super::resolve::Resolution; -use vm::{Expr as CoreExpr, FrontendIr, LocalIrBuilder, LocalSlot, ParseError, Stmt as CoreStmt}; +use vm::{FrontendIr, LocalIrBuilder, ParseError, Stmt as CoreStmt}; pub(crate) struct LoweredNumberChunk { pub(crate) ir: FrontendIr, @@ -20,13 +20,26 @@ pub(crate) struct LoweredNumberChunk { #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum NumberSourceError { Syntax { message: String }, - CompileUnsupported { reason: String }, - NotFloat { kind: &'static str }, + CompileUnsupported { reason: UnsupportedReason }, + NotFloat { kind: NumberKind }, +} + +/// Why a parsed fragment does not enter the binary64 kernel. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum UnsupportedReason { + Statement, + Operator, + Expression, + LiteralForm, + UnprovenName, + NotSingle, + LocalName, + Kernel { message: String }, } struct ProvenLocal { name: Vec, - slot: LocalSlot, + value: ClassifiedNumber, } pub(crate) fn lower_proven_chunk( @@ -77,7 +90,7 @@ fn lower_stmt( values, } => lower_local(source, *span, names, values, lowering, stmts, env), Stmt::Return { span, values } => { - let value = single_proven(values, "return is not a single proven number")?; + let value = single_proven(values)?; let lowered = lower_expr(source, value, lowering, stmts, env)?; stmts.push(CoreStmt::Expr { expr: lowered.into_expr(), @@ -85,7 +98,7 @@ fn lower_stmt( }); Ok(()) } - _ => Err(unsupported("statement is outside the numeric subset")), + _ => Err(unsupported(UnsupportedReason::Statement)), } } @@ -99,22 +112,18 @@ fn lower_local( env: &mut Vec, ) -> Result<(), NumberSourceError> { if names.len() != 1 || values.exprs.len() != 1 { - return Err(unsupported("local is not a single proven number")); + return Err(unsupported(UnsupportedReason::NotSingle)); } let lowered = lower_expr(source, &values.exprs[0], lowering, stmts, env)?; let name = &names[0].name; - let text = std::str::from_utf8(&name.bytes) - .map_err(|_| unsupported("local name is not a proven number"))?; - let slot = lowering.alloc_local_named(text).map_err(kernel_error)?; - stmts.push(CoreStmt::Let { - index: slot, - declared_schema: None, - expr: lowered.into_expr(), - line: line_of(source, span), - }); + let text = + std::str::from_utf8(&name.bytes).map_err(|_| unsupported(UnsupportedReason::LocalName))?; + let bound = lowering + .bind_named(text, lowered, line_of(source, span), stmts) + .map_err(kernel_error)?; env.push(ProvenLocal { name: name.bytes.clone(), - slot, + value: bound, }); Ok(()) } @@ -149,7 +158,7 @@ fn lower_expr( } Ok(acc) } - _ => Err(unsupported("expression is outside the numeric subset")), + _ => Err(unsupported(UnsupportedReason::Expression)), } } @@ -162,11 +171,11 @@ fn lower_unary( env: &[ProvenLocal], ) -> Result { if op != UnOp::Neg { - return Err(unsupported("operator is outside the numeric subset")); + return Err(unsupported(UnsupportedReason::Operator)); } let inner = lower_expr(source, expr, lowering, stmts, env)?; let inner = lowering.materialize(inner, stmts).map_err(kernel_error)?; - attest(inner.neg()) + Ok(inner.neg()) } fn apply( @@ -178,30 +187,29 @@ fn apply( ) -> Result { let lhs = lowering.materialize(lhs, stmts).map_err(kernel_error)?; let rhs = lowering.materialize(rhs, stmts).map_err(kernel_error)?; - let expr = match op { - BinOp::Add => lhs.add(rhs), - BinOp::Sub => lhs.sub(rhs), - BinOp::Mul => lhs.mul(rhs), - BinOp::Div => lhs.div(rhs), - BinOp::Pow => lhs.pow(rhs), - BinOp::Mod => lowering.floor_mod(lhs, rhs).map_err(kernel_error)?, - _ => return Err(unsupported("operator is outside the numeric subset")), - }; - attest(expr) + match op { + BinOp::Add => Ok(lhs.add(rhs)), + BinOp::Sub => Ok(lhs.sub(rhs)), + BinOp::Mul => Ok(lhs.mul(rhs)), + BinOp::Div => Ok(lhs.div(rhs)), + BinOp::Pow => Ok(lhs.pow(rhs)), + BinOp::Mod => lowering.floor_mod(lhs, rhs).map_err(kernel_error), + _ => Err(unsupported(UnsupportedReason::Operator)), + } } fn lower_number(raw: &str, kind: NumberKind) -> Result { let value = match kind { - NumberKind::Signed64 => return Err(not_float("Signed64")), - NumberKind::Unsigned64 => return Err(not_float("Unsigned64")), - NumberKind::Imaginary => return Err(not_float("Imaginary")), - NumberKind::HexFloat => return Err(unsupported("literal form is not lowered")), + NumberKind::Signed64 => return Err(not_float(NumberKind::Signed64)), + NumberKind::Unsigned64 => return Err(not_float(NumberKind::Unsigned64)), + NumberKind::Imaginary => return Err(not_float(NumberKind::Imaginary)), + NumberKind::HexFloat => return Err(unsupported(UnsupportedReason::LiteralForm)), NumberKind::Integer | NumberKind::Float => parse_decimal(raw)?, NumberKind::HexInteger => parse_prefixed_integer(raw, 16)?, NumberKind::Binary => parse_prefixed_integer(raw, 2)?, }; if value.is_nan() { - return Err(unsupported("literal form is not lowered")); + return Err(unsupported(UnsupportedReason::LiteralForm)); } Ok(ClassifiedNumber::literal(value)) } @@ -216,18 +224,18 @@ fn parse_decimal(raw: &str) -> Result { }; normalized .parse::() - .map_err(|_| unsupported("literal form is not lowered")) + .map_err(|_| unsupported(UnsupportedReason::LiteralForm)) } fn parse_prefixed_integer(raw: &str, radix: u32) -> Result { let digits = raw .get(2..) .filter(|digits| !digits.is_empty()) - .ok_or_else(|| unsupported("literal form is not lowered"))?; + .ok_or_else(|| unsupported(UnsupportedReason::LiteralForm))?; let marker = raw.as_bytes().get(1).copied().unwrap_or(0) | 0x20; let expected = if radix == 16 { b'x' } else { b'b' }; if raw.len() < 3 || raw.as_bytes()[0] != b'0' || marker != expected { - return Err(unsupported("literal form is not lowered")); + return Err(unsupported(UnsupportedReason::LiteralForm)); } let mut magnitude: u64 = 0; for byte in digits.bytes() { @@ -235,59 +243,50 @@ fn parse_prefixed_integer(raw: &str, radix: u32) -> Result byte - b'0', b'a'..=b'f' => byte - b'a' + 10, b'A'..=b'F' => byte - b'A' + 10, - _ => return Err(unsupported("literal form is not lowered")), + _ => return Err(unsupported(UnsupportedReason::LiteralForm)), }; if u32::from(digit) >= radix { - return Err(unsupported("literal form is not lowered")); + return Err(unsupported(UnsupportedReason::LiteralForm)); } let scaled = magnitude .checked_mul(u64::from(radix)) - .ok_or_else(|| unsupported("literal form is not lowered"))?; + .ok_or_else(|| unsupported(UnsupportedReason::LiteralForm))?; magnitude = scaled .checked_add(u64::from(digit)) - .ok_or_else(|| unsupported("literal form is not lowered"))?; + .ok_or_else(|| unsupported(UnsupportedReason::LiteralForm))?; } Ok(magnitude as f64) } fn lookup_proven(name: &[u8], env: &[ProvenLocal]) -> Result { - let slot = env - .iter() + env.iter() .rev() .find(|local| local.name == name) - .map(|local| local.slot) - .ok_or_else(|| unsupported("name is not a proven local"))?; - attest(CoreExpr::Var(slot)) + .map(|local| local.value.clone()) + .ok_or_else(|| unsupported(UnsupportedReason::UnprovenName)) } -fn single_proven<'a>( - values: &'a ExprList, - reason: &'static str, -) -> Result<&'a Expr, NumberSourceError> { +fn single_proven(values: &ExprList) -> Result<&Expr, NumberSourceError> { if values.exprs.len() == 1 { Ok(&values.exprs[0]) } else { - Err(unsupported(reason)) + Err(unsupported(UnsupportedReason::NotSingle)) } } -fn attest(expr: CoreExpr) -> Result { - ClassifiedNumber::from_attested_float(expr, FloatTypeEvidence::attested()).map_err(kernel_error) -} - fn kernel_error(error: ParseError) -> NumberSourceError { NumberSourceError::CompileUnsupported { - reason: format!("number kernel: {}", error.message), + reason: UnsupportedReason::Kernel { + message: error.message, + }, } } -fn unsupported(reason: &'static str) -> NumberSourceError { - NumberSourceError::CompileUnsupported { - reason: reason.to_string(), - } +fn unsupported(reason: UnsupportedReason) -> NumberSourceError { + NumberSourceError::CompileUnsupported { reason } } -fn not_float(kind: &'static str) -> NumberSourceError { +fn not_float(kind: NumberKind) -> NumberSourceError { NumberSourceError::NotFloat { kind } } diff --git a/tests/luajit_number_semantics_tests.rs b/tests/luajit_number_semantics_tests.rs index 1162370..ca24651 100644 --- a/tests/luajit_number_semantics_tests.rs +++ b/tests/luajit_number_semantics_tests.rs @@ -7,7 +7,7 @@ #[path = "../src/frontends/lua/number.rs"] mod number; -use number::{ClassifiedNumber, FloatTypeEvidence, NumberLowering}; +use number::{ClassifiedNumber, NumberLowering}; use vm::{AssignmentKind, Compiler, Expr, LocalIrBuilder, LocalSlot, Stmt, Value, Vm}; const PROTOCOL_06: [&str; 4] = ["3.5", "1", "-1", "-2.5"]; @@ -21,30 +21,37 @@ const PROTOCOL_06_BITS: [u64; 4] = [ #[test] fn case06_business_results_match_frozen_protocol() { let mut builder = LocalIrBuilder::new(); - let mut lowering = NumberLowering::new(&mut builder); - let quotient = ClassifiedNumber::literal(7.0).div(ClassifiedNumber::literal(2.0)); - let positive_remainder = lowering - .floor_mod( - ClassifiedNumber::literal(-5.0), - ClassifiedNumber::literal(3.0), - ) - .expect("bind remainder temps"); - let negative_remainder = lowering - .floor_mod( - ClassifiedNumber::literal(5.0), - ClassifiedNumber::literal(-3.0), + let (quotient, positive_remainder, negative_remainder, negative_quotient) = { + let mut lowering = NumberLowering::new(&mut builder); + let quotient = ClassifiedNumber::literal(7.0).div(ClassifiedNumber::literal(2.0)); + let positive_remainder = lowering + .floor_mod( + ClassifiedNumber::literal(-5.0), + ClassifiedNumber::literal(3.0), + ) + .expect("bind remainder temps"); + let negative_remainder = lowering + .floor_mod( + ClassifiedNumber::literal(5.0), + ClassifiedNumber::literal(-3.0), + ) + .expect("bind remainder temps"); + let negative_quotient = ClassifiedNumber::literal(-5.0).div(ClassifiedNumber::literal(2.0)); + ( + quotient, + positive_remainder, + negative_remainder, + negative_quotient, ) - .expect("bind remainder temps"); - let negative_quotient = ClassifiedNumber::literal(-5.0).div(ClassifiedNumber::literal(2.0)); - drop(lowering); + }; let ran = run( builder, vec![ - expr_stmt(quotient), - expr_stmt(positive_remainder), - expr_stmt(negative_remainder), - expr_stmt(negative_quotient), + expr_stmt(quotient.into_expr()), + expr_stmt(positive_remainder.into_expr()), + expr_stmt(negative_remainder.into_expr()), + expr_stmt(negative_quotient.into_expr()), ], ); @@ -137,13 +144,6 @@ fn add_sub_mul_and_negation_match_observed_luajit() { let negated_zero = eval_unary(|operand| operand.neg(), 0.0); assert_expect(&negated_zero, Expect::Bits(0x8000_0000_0000_0000), 0.0, 0.0); - let negated_negative_zero = eval_unary(|operand| operand.neg(), -0.0); - assert_expect( - &negated_negative_zero, - Expect::Bits(0x0000_0000_0000_0000), - -0.0, - 0.0, - ); let negated_nan = eval_unary(|operand| operand.neg(), f64::NAN); assert_expect(&negated_nan, Expect::Nan, f64::NAN, 0.0); } @@ -216,17 +216,13 @@ fn remainder_temps_keep_a_guest_local_and_a_nested_rhs() { }; let mut lowering = NumberLowering::new(&mut builder); lowering - .floor_mod( - ClassifiedNumber::literal(7.0), - ClassifiedNumber::from_attested_float(inner, FloatTypeEvidence::attested()) - .expect("inner remainder is binary64"), - ) + .floor_mod(ClassifiedNumber::literal(7.0), inner) .expect("outer remainder") }; let ir = builder.finish(vec![ let_int(guest, 42), - expr_stmt(collided), - expr_stmt(nested), + expr_stmt(collided.into_expr()), + expr_stmt(nested.into_expr()), ]); let ran = run_stmts(ir.locals, ir.stmts); let collision_is_two = matches!( @@ -267,48 +263,68 @@ fn remainder_temps_keep_a_guest_local_and_a_nested_rhs() { } #[test] -fn known_int_literal_is_rejected_before_truncating_div() { - let evidence = FloatTypeEvidence::attested(); - let seven = ClassifiedNumber::from_attested_float(Expr::Int(7), evidence); - let two = ClassifiedNumber::from_attested_float(Expr::Int(2), evidence); - let negative = ClassifiedNumber::from_attested_float(Expr::Int(-5), evidence); - let message = seven - .expect_err("Int(7) must not enter classified arithmetic") - .message; - assert!( - message.contains("Int"), - "rejection should name the visible literal, got {message}" - ); - assert!(two.is_err(), "Int(2) must not enter classified arithmetic"); - assert!( - negative.is_err(), - "Int(-5) must not enter classified arithmetic" - ); - let boolean = ClassifiedNumber::from_attested_float(Expr::Bool(true), evidence); - assert!( - boolean.is_err(), - "a visible Bool literal must not enter classified arithmetic" +fn int_slot_cannot_obtain_float_evidence() { + let mut builder = LocalIrBuilder::new(); + let int_slot = builder.alloc_local_named("raw_int").expect("int slot"); + let refused = number::external_slot_evidence(int_slot) + .expect_err("an Int slot must not receive float evidence"); + assert_eq!(refused.slot, int_slot); + + let mut stmts = Vec::new(); + let stored = { + let mut lowering = NumberLowering::new(&mut builder); + let proven = lowering + .bind_named("proven", ClassifiedNumber::literal(7.0), 1, &mut stmts) + .expect("bind proven float"); + assert_ne!( + proven.bound_slot(), + Some(int_slot), + "proven bind reused the Int slot" + ); + let quotient = ClassifiedNumber::literal(7.0).div(ClassifiedNumber::literal(2.0)); + assert!( + quotient.bound_slot().is_none(), + "literal division must not be a slot reference" + ); + let stored = lowering + .materialize(quotient, &mut stmts) + .expect("materialize classified division"); + assert_ne!( + stored.bound_slot(), + Some(int_slot), + "classified store reused the Int slot" + ); + stored + }; + stmts.push(let_int(int_slot, 7)); + stmts.push(expr_stmt(stored.into_expr())); + let ran = run(builder, stmts); + assert_eq!(local_int(&ran, int_slot), 7, "Int slot was consumed"); + assert_protocol_number(&ran.stack[0], "3.5", 3.5f64.to_bits()); + assert_ne!( + ran.stack[0], + Value::Int(7 / 2), + "kernel result must not be truncating Int division" ); } #[test] -fn attested_var_is_not_retyped_by_the_number_kernel() { +fn observed_float_producer_does_not_adopt_an_int_slot() { let mut builder = LocalIrBuilder::new(); - let slot = builder.alloc_local_named("n").expect("guest local"); - let classified = - ClassifiedNumber::from_attested_float(Expr::Var(slot), FloatTypeEvidence::attested()); + let int_slot = builder.alloc_local_named("raw_int").expect("int slot"); + let produced = ClassifiedNumber::from_observed_literal(vec![let_int(int_slot, 7)], 2.0); assert!( - classified.is_ok(), - "matching Var is not Float evidence and is not a kernel type check: {classified:?}" + produced.bound_slot().is_none(), + "closed producer must not name the Int slot" ); - let call = ClassifiedNumber::from_attested_float( - Expr::Call(0, Vec::new(), Vec::new(), None, None), - FloatTypeEvidence::attested(), - ); - assert!( - call.is_ok(), - "matching Call is not Float evidence and is not a kernel type check: {call:?}" + let quotient = ClassifiedNumber::literal(7.0).div(produced); + let ran = run(builder, vec![expr_stmt(quotient.into_expr())]); + assert_eq!( + local_int(&ran, int_slot), + 7, + "preceding Int let did not run" ); + assert_protocol_number(&ran.stack[0], "3.5", 3.5f64.to_bits()); } #[derive(Clone, Copy)] @@ -329,11 +345,16 @@ struct Ran { locals: Vec, } -fn eval_binary(op: fn(ClassifiedNumber, ClassifiedNumber) -> Expr, lhs: f64, rhs: f64) -> Value { +fn eval_binary( + op: fn(ClassifiedNumber, ClassifiedNumber) -> ClassifiedNumber, + lhs: f64, + rhs: f64, +) -> Value { let expr = op( ClassifiedNumber::literal(lhs), ClassifiedNumber::literal(rhs), - ); + ) + .into_expr(); let builder = LocalIrBuilder::new(); run(builder, vec![expr_stmt(expr)]) .stack @@ -352,6 +373,7 @@ fn eval_floor_mod(lhs: f64, rhs: f64) -> Value { ClassifiedNumber::literal(rhs), ) .expect("bind remainder temps") + .into_expr() }; run(builder, vec![expr_stmt(expr)]) .stack @@ -360,8 +382,8 @@ fn eval_floor_mod(lhs: f64, rhs: f64) -> Value { .expect("one result") } -fn eval_unary(op: fn(ClassifiedNumber) -> Expr, operand: f64) -> Value { - let expr = op(ClassifiedNumber::literal(operand)); +fn eval_unary(op: fn(ClassifiedNumber) -> ClassifiedNumber, operand: f64) -> Value { + let expr = op(ClassifiedNumber::literal(operand)).into_expr(); let builder = LocalIrBuilder::new(); run(builder, vec![expr_stmt(expr)]) .stack @@ -376,18 +398,18 @@ fn assert_binary_eval_once( rhs: f64, text: &str, bits: u64, - op: fn(&mut NumberLowering<'_>, ClassifiedNumber, ClassifiedNumber) -> Expr, + op: fn(&mut NumberLowering<'_>, ClassifiedNumber, ClassifiedNumber) -> ClassifiedNumber, ) { let mut builder = LocalIrBuilder::new(); let sequence = builder.alloc_local_named("sequence").expect("sequence"); let left_mark = builder.alloc_local_named("left_mark").expect("left mark"); let right_mark = builder.alloc_local_named("right_mark").expect("right mark"); - let expr = { + let value = { let mut lowering = NumberLowering::new(&mut builder); op( &mut lowering, - attested_float(counted_literal(sequence, left_mark, lhs)), - attested_float(counted_literal(sequence, right_mark, rhs)), + observed_count(sequence, left_mark, lhs), + observed_count(sequence, right_mark, rhs), ) }; let ran = run( @@ -396,7 +418,7 @@ fn assert_binary_eval_once( let_int(sequence, 0), let_int(left_mark, 0), let_int(right_mark, 0), - expr_stmt(expr), + expr_stmt(value.into_expr()), ], ); assert_eq!( @@ -424,19 +446,23 @@ fn assert_unary_eval_once() { let mut builder = LocalIrBuilder::new(); let sequence = builder.alloc_local_named("sequence").expect("sequence"); let mark = builder.alloc_local_named("mark").expect("mark"); - let expr = attested_float(counted_literal(sequence, mark, 0.0)).neg(); + let value = observed_count(sequence, mark, 0.0).neg(); let ran = run( builder, - vec![let_int(sequence, 0), let_int(mark, 0), expr_stmt(expr)], + vec![ + let_int(sequence, 0), + let_int(mark, 0), + expr_stmt(value.into_expr()), + ], ); assert_eq!(local_int(&ran, sequence), 1, "{:?}", ran.locals); assert_eq!(local_int(&ran, mark), 1, "{:?}", ran.locals); assert_expect(&ran.stack[0], Expect::Bits(0x8000_0000_0000_0000), 0.0, 0.0); } -fn counted_literal(sequence: LocalSlot, mark: LocalSlot, value: f64) -> Expr { - Expr::Block { - stmts: vec![ +fn observed_count(sequence: LocalSlot, mark: LocalSlot, value: f64) -> ClassifiedNumber { + ClassifiedNumber::from_observed_literal( + vec![ Stmt::Assign { kind: AssignmentKind::Set, index: sequence, @@ -450,8 +476,8 @@ fn counted_literal(sequence: LocalSlot, mark: LocalSlot, value: f64) -> Expr { line: 1, }, ], - expr: Box::new(Expr::Float(value)), - } + value, + ) } fn run(builder: LocalIrBuilder, stmts: Vec) -> Ran { @@ -474,11 +500,6 @@ fn run_stmts(local_count: usize, stmts: Vec) -> Ran { } } -fn attested_float(expr: Expr) -> ClassifiedNumber { - ClassifiedNumber::from_attested_float(expr, FloatTypeEvidence::attested()) - .expect("caller constructed a binary64 expression") -} - fn is_lua_identifier(name: &str) -> bool { let mut chars = name.chars(); let Some(first) = chars.next() else { diff --git a/tests/luajit_number_source_tests.rs b/tests/luajit_number_source_tests.rs index 6e28590..d478b76 100644 --- a/tests/luajit_number_source_tests.rs +++ b/tests/luajit_number_source_tests.rs @@ -52,8 +52,60 @@ enum Expect { struct NegativeCase { name: &'static str, source: &'static str, - layer: &'static str, - detail: &'static str, + layer: RejectLayer, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum RejectLayer { + Syntax, + NotFloat(ast::NumberKind), + Unsupported(number_source::UnsupportedReason), +} + +#[test] +fn hex_float_decoder_keeps_nonzero_subnormal_bits() { + let min_positive = parse_lua_hex_float("0x1p-1074"); + assert_eq!( + min_positive.to_bits(), + 0x0000_0000_0000_0001, + "min positive subnormal was misdecoded as {min_positive:?}" + ); + assert!(min_positive.is_finite() && min_positive != 0.0); + let next = parse_lua_hex_float("0x1p-1073"); + assert_eq!(next.to_bits(), 0x0000_0000_0000_0002); + let negative = parse_lua_hex_float("-0x1p-1074"); + assert_eq!(negative.to_bits(), 0x8000_0000_0000_0001); + assert!(negative.is_finite() && negative.is_sign_negative() && negative != 0.0); + let tenth = parse_lua_hex_float("0x1.999999999999ap-4"); + assert_eq!(tenth.to_bits(), 0x3fb9_9999_9999_999a); + assert_eq!( + parse_lua_hex_float("0x1.cp+1").to_bits(), + 0x400c_0000_0000_0000 + ); + assert_eq!( + parse_lua_hex_float("-0x1p+1").to_bits(), + 0xc000_0000_0000_0000 + ); + assert!(matches!( + parse_oracle_value("nan"), + OracleNumber::Class("nan") + )); + assert!(matches!( + parse_oracle_value("inf"), + OracleNumber::Class("inf") + )); + assert!(matches!( + parse_oracle_value("-inf"), + OracleNumber::Class("-inf") + )); + assert!(matches!( + parse_oracle_value("-0"), + OracleNumber::Bits(bits) if bits == (-0.0f64).to_bits() + )); + assert!(matches!( + parse_oracle_value("+0"), + OracleNumber::Bits(bits) if bits == 0.0f64.to_bits() + )); } #[test] @@ -98,23 +150,21 @@ fn legal_uncovered_sources_are_not_syntax_rejections() { let mut unsupported = 0usize; for case in &cases { let failure = run_plugin(case.source).expect_err(case.name); - assert_eq!( - failure.layer, case.layer, - "{} detail={}", - case.name, failure.detail - ); - assert!( - failure.detail.contains(case.detail), - "{} detail={} missing {}", - case.name, - failure.detail, - case.detail - ); - match case.layer { - "syntax" => syntax += 1, - "classify-not-float" => not_float += 1, - "compile-unsupported" => unsupported += 1, - other => panic!("unexpected negative layer {other}"), + let layer = reject_layer(case.source); + assert_eq!(&layer, &case.layer, "{}", case.name); + match &layer { + RejectLayer::Syntax => { + assert_eq!(failure.layer, "syntax", "{}", case.name); + syntax += 1; + } + RejectLayer::NotFloat(_) => { + assert_eq!(failure.layer, "classify-not-float", "{}", case.name); + not_float += 1; + } + RejectLayer::Unsupported(_) => { + assert_eq!(failure.layer, "compile-unsupported", "{}", case.name); + unsupported += 1; + } } } println!( @@ -126,23 +176,44 @@ fn legal_uncovered_sources_are_not_syntax_rejections() { assert_eq!(unsupported, 8); } +fn reject_layer(source: &str) -> RejectLayer { + match parser::parse_chunk(source.as_bytes()) { + Err(_) => RejectLayer::Syntax, + Ok(chunk) => { + let resolution = resolve::resolve(&chunk); + match number_source::lower_proven_chunk(source, &chunk, &resolution) { + Err(NumberSourceError::Syntax { .. }) => RejectLayer::Syntax, + Err(NumberSourceError::NotFloat { kind }) => RejectLayer::NotFloat(kind), + Err(NumberSourceError::CompileUnsupported { reason }) => { + RejectLayer::Unsupported(reason) + } + Ok(_) => panic!("lowered a negative source: {source}"), + } + } + } +} + #[test] fn sequential_mods_use_core_slots_and_keep_the_result() { let source = sequential_mod_source(12); let lowered = lower_source(&source).expect("sequential mods are proven floats"); let run = run_plugin(&source).expect("sequential mods compile and run"); assert_bits(&run.stack[0], 1.0f64.to_bits(), "10 % 3"); - assert!( - lowered.logical_slots > 8, - "sequential sample should sit above the pinned compaction threshold, logical={}", - lowered.logical_slots - ); - assert!( - run.frame_slots < lowered.logical_slots, - "Core slot allocation should shorten sequential temps: logical={} frame={}", - lowered.logical_slots, - run.frame_slots - ); + let guest_bindings = lowered + .binding_names + .iter() + .filter(|name| !name.starts_with("$lua.number.")) + .count(); + let temps = lowered + .binding_names + .iter() + .filter(|name| name.starts_with("$lua.number.")) + .count(); + assert_eq!(lowered.logical_slots, 36, "logical slots"); + assert_eq!(guest_bindings, 12, "guest bindings r0..r11"); + assert_eq!(temps, 24, "two temps per remainder"); + assert_eq!(guest_bindings + temps, lowered.logical_slots); + assert_eq!(run.frame_slots, 3, "Core frame slots after compaction"); assert!( lowered .binding_names @@ -153,10 +224,13 @@ fn sequential_mods_use_core_slots_and_keep_the_result() { lowered.binding_names ); println!( - "slot boundary logical={} frame={} temps={}", + "slot boundary logical_slots={} guest_bindings={} temps={} frame_slots={}; {}→{}", lowered.logical_slots, + guest_bindings, + temps, run.frame_slots, - lowered.binding_names.len() + lowered.logical_slots, + run.frame_slots ); if let Ok(path) = std::env::var("LUAJIT_ORACLE") { let oracle = oracle_execute(&path, &source); @@ -216,9 +290,9 @@ fn configured_oracle_matches_the_same_sources() { for case in negative_cases() { let oracle_accepted = oracle_load(&path, case.source); let failure = run_plugin(case.source).expect_err(case.name); - assert_eq!(failure.layer, case.layer, "{}", case.name); - match case.layer { - "syntax" => { + match &case.layer { + RejectLayer::Syntax => { + assert_eq!(failure.layer, "syntax", "{}", case.name); assert!( !oracle_accepted, "{} should be a LuaJIT source rejection", @@ -226,23 +300,42 @@ fn configured_oracle_matches_the_same_sources() { ); syntax_reject += 1; } - "classify-not-float" => { - assert!(oracle_accepted, "{} is legal LuaJIT syntax", case.name); + RejectLayer::NotFloat(_) => { + assert_eq!(failure.layer, "classify-not-float", "{}", case.name); + let executed = oracle_execute(&path, case.source); + assert!( + executed.accepted, + "{} is legal LuaJIT and must be executed for type()", + case.name + ); + assert_eq!( + executed.values.len(), + 1, + "{} {:?}", + case.name, + executed.values + ); + match &executed.values[0] { + OracleNumber::Type(ty) => { + assert_eq!(ty, "cdata", "{} type category", case.name); + } + other => panic!("{} expected cdata type, got {other:?}", case.name), + } not_float += 1; } - "compile-unsupported" => { + RejectLayer::Unsupported(_) => { + assert_eq!(failure.layer, "compile-unsupported", "{}", case.name); assert!(oracle_accepted, "{} is legal LuaJIT syntax", case.name); unsupported += 1; } - other => panic!("unexpected layer {other}"), } } println!( "oracle differential execute={execute} signed-zero={signed_zero} nonfinite={nonfinite} empty={empty} not-float={not_float} compile-unsupported={unsupported} syntax-reject={syntax_reject}" ); - assert_eq!(execute, 27); + assert_eq!(execute, 35); assert_eq!(signed_zero, 4); - assert_eq!(nonfinite, 4); + assert_eq!(nonfinite, 5); assert_eq!(empty, 1); assert_eq!(not_float, 3); assert_eq!(unsupported, 8); @@ -308,10 +401,10 @@ fn source_error(error: NumberSourceError) -> ParseError { ParseError::new(format!("lua number syntax: {message}")) } NumberSourceError::CompileUnsupported { reason } => { - ParseError::new(format!("lua number compile unsupported: {reason}")) + ParseError::new(format!("lua number compile unsupported: {reason:?}")) } NumberSourceError::NotFloat { kind } => { - ParseError::new(format!("lua number not float: {kind}")) + ParseError::new(format!("lua number not float: {kind:?}")) } } } @@ -577,6 +670,60 @@ fn execute_cases() -> Vec { Category::NonFinite, Expect::Class("nan"), ), + case( + "dec-tenth", + "return 0.1", + Category::Finite, + Expect::Bits(0x3fb9_9999_9999_999a), + ), + case( + "int-past-mantissa", + "return 9007199254740993", + Category::Finite, + Expect::Bits(0x4340_0000_0000_0000), + ), + case( + "subnormal", + "return 1e-323", + Category::Finite, + Expect::Bits(0x0000_0000_0000_0002), + ), + case( + "overflow", + "return 1e400", + Category::NonFinite, + Expect::Class("inf"), + ), + case( + "hex-past-mantissa", + "return 0x20000000000001", + Category::Finite, + Expect::Bits(0x4340_0000_0000_0000), + ), + case( + "hex-u64-max", + "return 0xFFFFFFFFFFFFFFFF", + Category::Finite, + Expect::Bits(0x43f0_0000_0000_0000), + ), + case( + "mod-i32-max", + "return 2147483647 % 7", + Category::Finite, + Expect::Bits(1.0f64.to_bits()), + ), + case( + "mod-i32-min", + "return -2147483648 % -3", + Category::Finite, + Expect::Bits((-2.0f64).to_bits()), + ), + case( + "dot-exponent", + "return 1.e5", + Category::Finite, + Expect::Bits(0x40f8_6a00_0000_0000), + ), ] } @@ -599,86 +746,72 @@ fn negative_cases() -> Vec { NegativeCase { name: "bare-number", source: "42", - layer: "syntax", - detail: "lua number syntax:", + layer: RejectLayer::Syntax, }, NegativeCase { name: "goto-keyword", source: "local goto = 1", - layer: "syntax", - detail: "lua number syntax:", + layer: RejectLayer::Syntax, }, NegativeCase { name: "idiv", source: "return 1 // 2", - layer: "syntax", - detail: "lua number syntax:", + layer: RejectLayer::Syntax, }, NegativeCase { name: "signed64", source: "return 1LL", - layer: "classify-not-float", - detail: "Signed64", + layer: RejectLayer::NotFloat(ast::NumberKind::Signed64), }, NegativeCase { name: "unsigned64", source: "return 1ULL", - layer: "classify-not-float", - detail: "Unsigned64", + layer: RejectLayer::NotFloat(ast::NumberKind::Unsigned64), }, NegativeCase { name: "imaginary", source: "return 1i", - layer: "classify-not-float", - detail: "Imaginary", + layer: RejectLayer::NotFloat(ast::NumberKind::Imaginary), }, NegativeCase { name: "global", source: "return x", - layer: "compile-unsupported", - detail: "proven local", + layer: RejectLayer::Unsupported(number_source::UnsupportedReason::UnprovenName), }, NegativeCase { name: "call", source: "return math.abs(-2)", - layer: "compile-unsupported", - detail: "numeric subset", + layer: RejectLayer::Unsupported(number_source::UnsupportedReason::Expression), }, NegativeCase { name: "string-add", source: "return 1 + \"2\"", - layer: "compile-unsupported", - detail: "numeric subset", + layer: RejectLayer::Unsupported(number_source::UnsupportedReason::Expression), }, NegativeCase { name: "hex-float", source: "return 0x1.8p1", - layer: "compile-unsupported", - detail: "literal form", + layer: RejectLayer::Unsupported(number_source::UnsupportedReason::LiteralForm), }, NegativeCase { name: "assign", source: "local x = 1\nx = 2\nreturn x", - layer: "compile-unsupported", - detail: "numeric subset", + layer: RejectLayer::Unsupported(number_source::UnsupportedReason::Statement), }, NegativeCase { name: "do-block", source: "do\n local x = 7 / 2\n return x\nend", - layer: "compile-unsupported", - detail: "numeric subset", + layer: RejectLayer::Unsupported(number_source::UnsupportedReason::Statement), }, NegativeCase { name: "multi-return", source: "return 1, 2", - layer: "compile-unsupported", - detail: "single proven", + layer: RejectLayer::Unsupported(number_source::UnsupportedReason::NotSingle), }, NegativeCase { name: "bare-return", source: "return", - layer: "compile-unsupported", - detail: "single proven", + layer: RejectLayer::Unsupported(number_source::UnsupportedReason::NotSingle), }, ] } @@ -742,6 +875,7 @@ struct OracleRun { enum OracleNumber { Class(&'static str), Bits(u64), + Type(String), } fn assert_oracle_baseline(path: &str) { @@ -793,6 +927,9 @@ fn oracle_execute(path: &str, source: &str) -> OracleRun { } fn parse_oracle_value(line: &str) -> OracleNumber { + if let Some(ty) = line.strip_prefix("TYPE:") { + return OracleNumber::Type(ty.to_string()); + } match line { "nan" => OracleNumber::Class("nan"), "inf" => OracleNumber::Class("inf"), @@ -810,6 +947,7 @@ fn assert_same_number(oracle: &OracleNumber, rust: &Value, label: &str) { match oracle { OracleNumber::Class(class) => assert_eq!(float_class(*number), *class, "{label}"), OracleNumber::Bits(bits) => assert_eq!(number.to_bits(), *bits, "{label} rust={number}"), + OracleNumber::Type(ty) => panic!("{label} oracle value was type {ty}, not a number"), } } @@ -839,30 +977,76 @@ fn parse_lua_hex_float(text: &str) -> f64 { let digit = ch .to_digit(16) .unwrap_or_else(|| panic!("oracle hex digit in {text}")); - magnitude = magnitude * 16 + u64::from(digit); + magnitude = magnitude + .checked_mul(16) + .and_then(|value| value.checked_add(u64::from(digit))) + .unwrap_or_else(|| panic!("oracle %a magnitude overflow: {text}")); if seen_dot { fraction_digits += 1; } } let scale = exponent - fraction_digits * 4; - let mut value = ldexp_u64(magnitude, scale); - if negative { - value = -value; - } - value + hex_magnitude_to_f64(negative, magnitude, scale) } -fn ldexp_u64(magnitude: u64, scale: i32) -> f64 { +/// Exact integer times `2^scale`, including a non-zero subnormal. +/// +/// `1u64 << n` as `f64` is zero once `n` passes 63, so `0x1p-1074` cannot be +/// built by scaling a float. The bit field is the value. +fn hex_magnitude_to_f64(negative: bool, magnitude: u64, scale: i32) -> f64 { + let sign = if negative { 1u64 << 63 } else { 0 }; if magnitude == 0 { - return 0.0; + return f64::from_bits(sign); + } + let msb = 63 - i32::try_from(magnitude.leading_zeros()).expect("msb"); + let mut unbiased = msb + scale; + let mut significand = magnitude; + if msb > 52 { + significand = shift_right_round_even(significand, u32::try_from(msb - 52).expect("shift")); + if significand == 1u64 << 53 { + significand = 1u64 << 52; + unbiased += 1; + } + } else { + significand <<= u32::try_from(52 - msb).expect("align"); + } + if unbiased > 1023 { + return f64::from_bits(sign | 0x7ff0_0000_0000_0000); + } + if unbiased < -1022 { + let extra = u32::try_from(-1022 - unbiased).expect("subnormal shift"); + significand = shift_right_round_even(significand, extra); + if significand == 0 { + return f64::from_bits(sign); + } + if significand >= 1u64 << 52 { + return f64::from_bits(sign | (1u64 << 52)); + } + return f64::from_bits(sign | significand); } - let mut digits = magnitude; - let mut exponent = scale; - while digits > (1u64 << 53) { - digits >>= 1; - exponent += 1; + let exp_field = u64::try_from(unbiased + 1023).expect("biased exponent"); + let fraction = significand & ((1u64 << 52) - 1); + f64::from_bits(sign | (exp_field << 52) | fraction) +} + +fn shift_right_round_even(value: u64, shift: u32) -> u64 { + if shift == 0 { + return value; + } + if shift >= 64 { + return 0; } - (digits as f64) * 2f64.powi(exponent) + let kept = value >> shift; + let remainder = value & ((1u64 << shift) - 1); + let half = 1u64 << (shift - 1); + let round_up = if remainder > half { + true + } else if remainder < half { + false + } else { + kept & 1 == 1 + }; + if round_up { kept + 1 } else { kept } } fn spawn_oracle(path: &str, args: &[&str], stdin_bytes: Option<&[u8]>) -> std::process::Output { From 401fe64b0b8d4ea9a22fc36b09db000fee64b248 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 20:23:54 +0800 Subject: [PATCH 014/225] fix(lua): resume number-temp probes from the last ordinal Each lowering scanned occupied `$lua.number.*` names from zero, so resolve_local_expr calls grew with the square of the temps. The lowering now keeps a monotonic ordinal and resumes there. A later lowering on the same builder still starts at zero. Private plugin counts, not a wall-clock gate. 12 remainders: probes 156 to 24, logical 36, frame 3. A 128-mod flat chain: probes 24640 to 383, logical 383, frame 3, depth 6. Operand rebinds stay: they are most of those logical slots but color to the same 3 frame slots, and skipping them would drop the two-lowering collision witness. Same-name Let reads the old binding (7/2 then x+1 is 4.5). -(-0.0) is bit-exact. The always-Err slot stub is gone. The source-test AST allow is on that path module only. --- src/frontends/lua/number.rs | 55 ++--- src/frontends/lua/number_source.rs | 8 +- tests/luajit_number_semantics_tests.rs | 30 ++- tests/luajit_number_source_tests.rs | 276 ++++++++++++++++++++++++- 4 files changed, 334 insertions(+), 35 deletions(-) diff --git a/src/frontends/lua/number.rs b/src/frontends/lua/number.rs index fde4ca1..bd9e7da 100644 --- a/src/frontends/lua/number.rs +++ b/src/frontends/lua/number.rs @@ -9,7 +9,10 @@ //! Remainder temps are names outside the Lua identifier grammar. They are //! probed on the same builder, because `alloc_local_named` reuses a slot for //! an existing name and unnamed allocation is private. A process-wide counter -//! or a hard-to-guess legal identifier is not a private namespace. +//! or a hard-to-guess legal identifier is not a private namespace. Each +//! lowering keeps a monotonic ordinal and resumes the search there. A later +//! lowering on the same builder starts again at zero, so it still observes +//! names the previous one holds. //! //! Each remainder takes two fresh frame slots. Core locals are frame-scoped, //! and this kernel does not own statement boundaries, so it cannot reuse a @@ -116,35 +119,33 @@ impl ClassifiedNumber { } } -/// An external Core slot was not emitted from a classified value. -#[cfg(test)] -#[allow(dead_code)] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct UnprovenSlot { - pub(crate) slot: LocalSlot, -} - -/// Refuse an arbitrary slot. There is no success path. -/// -/// A typed reference exists only as the return value of `bind_named`, -/// `store`, or `materialize`. -#[cfg(test)] -#[allow(dead_code)] -pub(crate) fn external_slot_evidence(slot: LocalSlot) -> Result { - Err(UnprovenSlot { slot }) -} - /// Temps for operations that must evaluate each operand once and then reuse it. /// /// Slots stay live for the returned expression. Calling `floor_mod` again on /// this lowering allocates new slots; it does not reclaim the previous pair. pub(crate) struct NumberLowering<'a> { builder: &'a mut LocalIrBuilder, + /// Next ordinal this lowering will probe. It only moves forward. It is + /// not shared with another lowering, even one that borrows this builder + /// after `self` is dropped. + next_ordinal: u32, + /// `resolve_local_expr` calls made while naming temps. One lowering of a + /// chunk can be counted from the source seam; this is not a timer. + name_probes: u64, } impl<'a> NumberLowering<'a> { pub(crate) fn new(builder: &'a mut LocalIrBuilder) -> Self { - Self { builder } + Self { + builder, + next_ordinal: 0, + name_probes: 0, + } + } + + /// Name lookups performed by `alloc_temp` on this lowering. + pub(crate) fn name_probes(&self) -> u64 { + self.name_probes } /// Lua `%` on binary64: `lhs - floor(lhs / rhs) * rhs`. @@ -226,13 +227,19 @@ impl<'a> NumberLowering<'a> { fn alloc_temp(&mut self, role: &str) -> Result { // `$` and `.` are outside `[A-Za-z_][A-Za-z0-9_]*`, so a Lua local - // cannot use this name. The probe is what makes a second lowering on - // the same builder fresh; the ordinal is not a process-wide counter. - let mut ordinal = 0u32; + // cannot use this name. The cursor skips ordinals this lowering has + // already probed. It does not make a name free: `resolve_local_expr` + // still rejects a slot another lowering allocated on this builder. + let mut ordinal = self.next_ordinal; loop { let name = format!("$lua.number.{role}.{ordinal}"); + self.name_probes += 1; if self.builder.resolve_local_expr(&name).is_none() { - return self.builder.alloc_local_named(&name); + let slot = self.builder.alloc_local_named(&name)?; + self.next_ordinal = ordinal + .checked_add(1) + .ok_or_else(|| ParseError::new("lua number temp ordinal overflow"))?; + return Ok(slot); } ordinal = ordinal .checked_add(1) diff --git a/src/frontends/lua/number_source.rs b/src/frontends/lua/number_source.rs index 19d6083..f7fa51b 100644 --- a/src/frontends/lua/number_source.rs +++ b/src/frontends/lua/number_source.rs @@ -15,6 +15,8 @@ pub(crate) struct LoweredNumberChunk { pub(crate) ir: FrontendIr, pub(crate) logical_slots: usize, pub(crate) binding_names: Vec, + /// `resolve_local_expr` calls made while naming this chunk's temps. + pub(crate) name_probes: u64, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -54,13 +56,14 @@ pub(crate) fn lower_proven_chunk( } let mut builder = LocalIrBuilder::new(); let mut stmts = Vec::new(); - { + let name_probes = { let mut lowering = NumberLowering::new(&mut builder); let mut env = Vec::new(); for stmt in &chunk.body.stmts { lower_stmt(source, stmt, &mut lowering, &mut stmts, &mut env)?; } - } + lowering.name_probes() + }; let ir = builder.finish(stmts); let binding_names = ir .local_bindings @@ -72,6 +75,7 @@ pub(crate) fn lower_proven_chunk( ir, logical_slots, binding_names, + name_probes, }) } diff --git a/tests/luajit_number_semantics_tests.rs b/tests/luajit_number_semantics_tests.rs index ca24651..f15c5be 100644 --- a/tests/luajit_number_semantics_tests.rs +++ b/tests/luajit_number_semantics_tests.rs @@ -144,6 +144,13 @@ fn add_sub_mul_and_negation_match_observed_luajit() { let negated_zero = eval_unary(|operand| operand.neg(), 0.0); assert_expect(&negated_zero, Expect::Bits(0x8000_0000_0000_0000), 0.0, 0.0); + let restored_zero = eval_unary(|operand| operand.neg(), -0.0); + assert_expect( + &restored_zero, + Expect::Bits(0x0000_0000_0000_0000), + -0.0, + 0.0, + ); let negated_nan = eval_unary(|operand| operand.neg(), f64::NAN); assert_expect(&negated_nan, Expect::Nan, f64::NAN, 0.0); } @@ -197,22 +204,34 @@ fn remainder_temps_keep_a_guest_local_and_a_nested_rhs() { .expect("guest local"); let collided = { let mut lowering = NumberLowering::new(&mut builder); - lowering + let value = lowering .floor_mod( ClassifiedNumber::literal(7.0), ClassifiedNumber::literal(5.0), ) - .expect("colliding remainder") + .expect("colliding remainder"); + let probes = lowering.name_probes(); + assert_eq!( + probes, 2, + "first lowering on an empty builder probes once per temp, probes={probes}" + ); + value }; let nested = { let inner = { let mut lowering = NumberLowering::new(&mut builder); - lowering + let value = lowering .floor_mod( ClassifiedNumber::literal(10.0), ClassifiedNumber::literal(4.0), ) - .expect("inner remainder") + .expect("inner remainder"); + let probes = lowering.name_probes(); + assert_eq!( + probes, 3, + "second lowering rescans held names from 0, then resumes, probes={probes}" + ); + value }; let mut lowering = NumberLowering::new(&mut builder); lowering @@ -266,9 +285,6 @@ fn remainder_temps_keep_a_guest_local_and_a_nested_rhs() { fn int_slot_cannot_obtain_float_evidence() { let mut builder = LocalIrBuilder::new(); let int_slot = builder.alloc_local_named("raw_int").expect("int slot"); - let refused = number::external_slot_evidence(int_slot) - .expect_err("an Int slot must not receive float evidence"); - assert_eq!(refused.slot, int_slot); let mut stmts = Vec::new(); let stored = { diff --git a/tests/luajit_number_source_tests.rs b/tests/luajit_number_source_tests.rs index d478b76..edbc726 100644 --- a/tests/luajit_number_source_tests.rs +++ b/tests/luajit_number_source_tests.rs @@ -4,6 +4,11 @@ //! register hosts. Each executed sample is real Lua source, lowered by the //! seam, then compiled with `SourcePlugin` and run on the VM. +// This test compiles the production AST through a path module. Four helpers +// (`Name::is`, `ExprList::tail_multi`, `AssignTarget::span`/`has_nav`, +// `Expr::is_multi`) have no caller on this path. The allow stays on this +// module: it does not change the production AST and it is not a crate lint. +#[allow(dead_code)] #[path = "../src/frontends/lua/ast.rs"] mod ast; #[path = "../src/frontends/lua/lexer.rs"] @@ -214,6 +219,28 @@ fn sequential_mods_use_core_slots_and_keep_the_result() { assert_eq!(temps, 24, "two temps per remainder"); assert_eq!(guest_bindings + temps, lowered.logical_slots); assert_eq!(run.frame_slots, 3, "Core frame slots after compaction"); + let depth = expr_depth_of(&lowered.ir.stmts); + println!( + "slot boundary name_probes={} temps={} mod_lhs={} mod_rhs={} value={} logical_slots={} frame_slots={} expr_depth={}; {}→{}", + lowered.name_probes, + temps, + count_role(&lowered.binding_names, "mod_lhs"), + count_role(&lowered.binding_names, "mod_rhs"), + count_role(&lowered.binding_names, "value"), + lowered.logical_slots, + run.frame_slots, + depth, + lowered.logical_slots, + run.frame_slots + ); + assert!( + depth < 32, + "short remainder sample expr depth {depth} is not bounded" + ); + assert_eq!( + lowered.name_probes, temps as u64, + "name probes rescanned occupied ordinals from 0" + ); assert!( lowered .binding_names @@ -333,8 +360,8 @@ fn configured_oracle_matches_the_same_sources() { println!( "oracle differential execute={execute} signed-zero={signed_zero} nonfinite={nonfinite} empty={empty} not-float={not_float} compile-unsupported={unsupported} syntax-reject={syntax_reject}" ); - assert_eq!(execute, 35); - assert_eq!(signed_zero, 4); + assert_eq!(execute, 38); + assert_eq!(signed_zero, 5); assert_eq!(nonfinite, 5); assert_eq!(empty, 1); assert_eq!(not_float, 3); @@ -342,6 +369,225 @@ fn configured_oracle_matches_the_same_sources() { assert_eq!(syntax_reject, 3); } +#[test] +fn flat_remainder_chain_probes_once_per_temp_and_matches_oracle() { + let short = measure_source(&sequential_mod_source(12)); + assert_eq!( + short.logical_slots, 36, + "12-remainder control logical slots" + ); + assert_eq!(short.frame_slots, 3, "12-remainder control frame slots"); + println!( + "control 36→3 name_probes={} temps={} logical_slots={} frame_slots={}", + short.name_probes, short.temps, short.logical_slots, short.frame_slots + ); + + let nested = measure_source("return 7%(10%4)\n"); + assert_eq!(nested.stack_bits, Some(1.0f64.to_bits()), "nested 7%(10%4)"); + println!( + "nested name_probes={} temps={} mod_lhs={} mod_rhs={} value={} logical_slots={} frame_slots={} expr_depth={}", + nested.name_probes, + nested.temps, + nested.mod_lhs, + nested.mod_rhs, + nested.value_temps, + nested.logical_slots, + nested.frame_slots, + nested.expr_depth + ); + + let chain_a = measure_source(&flat_mod_chain(100, 7, 128)); + let chain_b = measure_source(&flat_mod_chain(101, 7, 128)); + println!( + "flat chain mods=128 name_probes={} temps={} mod_lhs={} mod_rhs={} value={} logical_slots={} frame_slots={} expr_depth={} bits_a={:?} bits_b={:?}", + chain_a.name_probes, + chain_a.temps, + chain_a.mod_lhs, + chain_a.mod_rhs, + chain_a.value_temps, + chain_a.logical_slots, + chain_a.frame_slots, + chain_a.expr_depth, + chain_a.stack_bits, + chain_b.stack_bits + ); + assert!( + chain_a.temps >= 128, + "flat chain did not lower 128 remainders, temps={}", + chain_a.temps + ); + assert_ne!( + chain_a.stack_bits, chain_b.stack_bits, + "two seeds of a 128-remainder chain collapsed" + ); + assert_ne!(chain_a.stack_bits, Some(0), "seed 100 collapsed to +0"); + assert_ne!(chain_b.stack_bits, Some(0), "seed 101 collapsed to +0"); + assert!( + chain_a.expr_depth < 32, + "flat chain expr depth {} grew with the source spine", + chain_a.expr_depth + ); + + let cycle_128 = measure_source(&cycling_rebind(128)); + let cycle_127 = measure_source(&cycling_rebind(127)); + assert_ne!( + cycle_128.stack_bits, cycle_127.stack_bits, + "dropping one rebind step left the result unchanged" + ); + assert_ne!( + cycle_128.stack_bits, + Some(0), + "cycling chain collapsed to +0" + ); + println!( + "cycling rebind steps=128 name_probes={} temps={} logical_slots={} frame_slots={} expr_depth={} bits_128={:?} bits_127={:?}", + cycle_128.name_probes, + cycle_128.temps, + cycle_128.logical_slots, + cycle_128.frame_slots, + cycle_128.expr_depth, + cycle_128.stack_bits, + cycle_127.stack_bits + ); + + if let Ok(path) = std::env::var("LUAJIT_ORACLE") { + assert_oracle_baseline(&path); + compare_oracle(&path, &flat_mod_chain(100, 7, 128), "flat-100"); + compare_oracle(&path, &flat_mod_chain(101, 7, 128), "flat-101"); + compare_oracle(&path, &cycling_rebind(128), "cycle-128"); + compare_oracle(&path, &cycling_rebind(127), "cycle-127"); + compare_oracle(&path, "return 7%(10%4)\n", "nested"); + println!("chain oracle compared=5"); + } else { + println!( + "chain oracle differential not run: LUAJIT_ORACLE unset; compared=0; not a differential GREEN" + ); + } + + assert_one_probe_per_temp(&short, "12-remainder control"); + assert_one_probe_per_temp(&nested, "nested"); + assert_one_probe_per_temp(&chain_a, "flat-100"); + assert_one_probe_per_temp(&chain_b, "flat-101"); + assert_one_probe_per_temp(&cycle_128, "cycle-128"); + assert_one_probe_per_temp(&cycle_127, "cycle-127"); +} + +struct Measured { + name_probes: u64, + temps: usize, + mod_lhs: usize, + mod_rhs: usize, + value_temps: usize, + logical_slots: usize, + frame_slots: usize, + expr_depth: usize, + stack_bits: Option, +} + +fn measure_source(source: &str) -> Measured { + let lowered = lower_source(source).unwrap_or_else(|error| { + panic!("lower failed: {error}"); + }); + let run = run_plugin(source).unwrap_or_else(|failure| { + panic!( + "run failed at {} logical_slots={}: {}", + failure.layer, lowered.logical_slots, failure.detail + ); + }); + let stack_bits = match run.stack.as_slice() { + [Value::Float(number)] => Some(number.to_bits()), + other => panic!("expected one binary64 result, stack={other:?}"), + }; + Measured { + name_probes: lowered.name_probes, + temps: count_prefix(&lowered.binding_names, "$lua.number."), + mod_lhs: count_role(&lowered.binding_names, "mod_lhs"), + mod_rhs: count_role(&lowered.binding_names, "mod_rhs"), + value_temps: count_role(&lowered.binding_names, "value"), + logical_slots: lowered.logical_slots, + frame_slots: run.frame_slots, + expr_depth: expr_depth_of(&lowered.ir.stmts), + stack_bits, + } +} + +fn assert_one_probe_per_temp(measured: &Measured, label: &str) { + assert_eq!( + measured.name_probes, measured.temps as u64, + "{label} name probes rescanned occupied ordinals from 0: probes={} temps={} logical_slots={} frame_slots={}", + measured.name_probes, measured.temps, measured.logical_slots, measured.frame_slots + ); +} + +fn compare_oracle(path: &str, source: &str, label: &str) { + let ours = run_plugin(source).unwrap_or_else(|failure| { + panic!("{label} rust {}: {}", failure.layer, failure.detail); + }); + let oracle = oracle_execute(path, source); + assert!(oracle.accepted, "{label} LuaJIT rejected the source"); + assert_eq!(oracle.values.len(), ours.stack.len(), "{label}"); + for (index, (oracle_value, rust_value)) in + oracle.values.iter().zip(ours.stack.iter()).enumerate() + { + assert_same_number(oracle_value, rust_value, &format!("{label}[{index}]")); + } +} + +fn flat_mod_chain(seed: i64, divisor: i64, mods: usize) -> String { + let mut source = format!("return {seed}"); + for _ in 0..mods { + source.push_str(&format!(" % {divisor}")); + } + source.push('\n'); + source +} + +fn cycling_rebind(steps: usize) -> String { + let mut source = String::from("local x = 17\n"); + for _ in 0..steps { + source.push_str("local x = (x % 5) + 3\n"); + } + source.push_str("return x\n"); + source +} + +fn count_role(names: &[String], role: &str) -> usize { + count_prefix(names, &format!("$lua.number.{role}.")) +} + +fn count_prefix(names: &[String], prefix: &str) -> usize { + names.iter().filter(|name| name.starts_with(prefix)).count() +} + +fn expr_depth_of(stmts: &[vm::Stmt]) -> usize { + stmts.iter().map(stmt_depth).max().unwrap_or(0) +} + +fn stmt_depth(stmt: &vm::Stmt) -> usize { + match stmt { + vm::Stmt::Let { expr, .. } | vm::Stmt::Expr { expr, .. } => expr_depth(expr), + other => panic!("number seam emitted an unexpected statement: {other:?}"), + } +} + +fn expr_depth(expr: &vm::Expr) -> usize { + match expr { + vm::Expr::Float(_) | vm::Expr::Int(_) | vm::Expr::Var(_) => 1, + vm::Expr::Neg(inner) => 1 + expr_depth(inner), + vm::Expr::Add(lhs, rhs) + | vm::Expr::Sub(lhs, rhs) + | vm::Expr::Mul(lhs, rhs) + | vm::Expr::Div(lhs, rhs) => 1 + expr_depth(lhs).max(expr_depth(rhs)), + vm::Expr::Call(_, _, args, _, _) => 1 + args.iter().map(expr_depth).max().unwrap_or(0), + vm::Expr::Block { stmts, expr } => 1 + stmt_depth_max(stmts).max(expr_depth(expr)), + other => panic!("number seam emitted an unexpected expression: {other:?}"), + } +} + +fn stmt_depth_max(stmts: &[vm::Stmt]) -> usize { + stmts.iter().map(stmt_depth).max().unwrap_or(0) +} + #[derive(Debug)] struct Run { stack: Vec, @@ -380,6 +626,7 @@ struct OwnedLowered { ir: FrontendIr, logical_slots: usize, binding_names: Vec, + name_probes: u64, } fn lower_source(source: &str) -> Result { @@ -391,6 +638,7 @@ fn lower_source(source: &str) -> Result { Ok(OwnedLowered { logical_slots: lowered.logical_slots, binding_names: lowered.binding_names, + name_probes: lowered.name_probes, ir: lowered.ir, }) } @@ -574,6 +822,24 @@ fn execute_cases() -> Vec { Category::Finite, Expect::Bits(3.5f64.to_bits()), ), + case( + "rebind-reads-old", + "local x = 7/2\nlocal x = x + 1\nreturn x", + Category::Finite, + Expect::Bits(4.5f64.to_bits()), + ), + case( + "rebind-commits", + "local x = 7/2\nlocal x = x + 1\nlocal x = x + 1\nreturn x", + Category::Finite, + Expect::Bits(5.5f64.to_bits()), + ), + case( + "rebind-keeps-other-name", + "local x = 7/2\nlocal y = x\nlocal x = x + 1\nreturn x + y", + Category::Finite, + Expect::Bits(8.0f64.to_bits()), + ), case( "two-locals", "local a = -5\nlocal b = 3\nreturn a % b", @@ -628,6 +894,12 @@ fn execute_cases() -> Vec { Category::SignedZero, Expect::Bits((-0.0f64).to_bits()), ), + case( + "neg-neg-zero", + "return -(-0)", + Category::SignedZero, + Expect::Bits(0.0f64.to_bits()), + ), case( "div-signed-zero", "return 0/-1", From b737c98452f22d24c88d78caed16b248d8fb0484 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 21:04:13 +0800 Subject: [PATCH 015/225] fix(lua): round hex literals onto binary64 in one pass Hex floats and hex integers share a guard/sticky conversion. A wide significand is not truncated to u64 and then scaled again. Syntax rejections and LL/ULL/i stay outside that path. Private plugin only. Locked LuaJIT %a compared 51 finite, 8 signed zero, 7 non-finite, and 1 empty result. Stops are syntax 9, cdata 3, and unsupported 7. An ordinary hex float and 2^64 do not share bits. --- src/frontends/lua/number_source.rs | 265 ++++++++++++++++++++++++++-- tests/luajit_number_source_tests.rs | 252 ++++++++++++++++++++++++-- 2 files changed, 483 insertions(+), 34 deletions(-) diff --git a/src/frontends/lua/number_source.rs b/src/frontends/lua/number_source.rs index f7fa51b..6f60d9c 100644 --- a/src/frontends/lua/number_source.rs +++ b/src/frontends/lua/number_source.rs @@ -1,10 +1,11 @@ //! Narrow source seam from a parsed Lua chunk onto the binary64 number kernel. //! //! Only a grammar kind that is already binary64, or a local this walk just -//! bound from a classified value, enters the kernel. `LL`, `ULL`, imaginary -//! suffixes, and names this walk did not prove stay outside it. Chains are -//! hoisted with the kernel's temps so a flat source spine does not become an -//! unbounded Core expression. Slot reuse stays with Core. +//! bound from a classified value, enters the kernel. Hex integers and hex +//! floats share one conversion. `LL`, `ULL`, imaginary suffixes, and names +//! this walk did not prove stay outside it. Chains are hoisted with the +//! kernel's temps so a flat source spine does not become an unbounded Core +//! expression. Slot reuse stays with Core. use super::ast::{BinOp, Chunk, Expr, ExprList, LocalName, NumberKind, Span, Stmt, UnOp}; use super::number::{ClassifiedNumber, NumberLowering}; @@ -207,10 +208,9 @@ fn lower_number(raw: &str, kind: NumberKind) -> Result return Err(not_float(NumberKind::Signed64)), NumberKind::Unsigned64 => return Err(not_float(NumberKind::Unsigned64)), NumberKind::Imaginary => return Err(not_float(NumberKind::Imaginary)), - NumberKind::HexFloat => return Err(unsupported(UnsupportedReason::LiteralForm)), + NumberKind::HexFloat | NumberKind::HexInteger => parse_hex_literal(raw)?, NumberKind::Integer | NumberKind::Float => parse_decimal(raw)?, - NumberKind::HexInteger => parse_prefixed_integer(raw, 16)?, - NumberKind::Binary => parse_prefixed_integer(raw, 2)?, + NumberKind::Binary => parse_binary_literal(raw)?, }; if value.is_nan() { return Err(unsupported(UnsupportedReason::LiteralForm)); @@ -231,29 +231,23 @@ fn parse_decimal(raw: &str) -> Result { .map_err(|_| unsupported(UnsupportedReason::LiteralForm)) } -fn parse_prefixed_integer(raw: &str, radix: u32) -> Result { +fn parse_binary_literal(raw: &str) -> Result { let digits = raw .get(2..) .filter(|digits| !digits.is_empty()) .ok_or_else(|| unsupported(UnsupportedReason::LiteralForm))?; let marker = raw.as_bytes().get(1).copied().unwrap_or(0) | 0x20; - let expected = if radix == 16 { b'x' } else { b'b' }; - if raw.len() < 3 || raw.as_bytes()[0] != b'0' || marker != expected { + if raw.len() < 3 || raw.as_bytes()[0] != b'0' || marker != b'b' { return Err(unsupported(UnsupportedReason::LiteralForm)); } let mut magnitude: u64 = 0; for byte in digits.bytes() { let digit = match byte { - b'0'..=b'9' => byte - b'0', - b'a'..=b'f' => byte - b'a' + 10, - b'A'..=b'F' => byte - b'A' + 10, + b'0' | b'1' => byte - b'0', _ => return Err(unsupported(UnsupportedReason::LiteralForm)), }; - if u32::from(digit) >= radix { - return Err(unsupported(UnsupportedReason::LiteralForm)); - } let scaled = magnitude - .checked_mul(u64::from(radix)) + .checked_mul(2) .ok_or_else(|| unsupported(UnsupportedReason::LiteralForm))?; magnitude = scaled .checked_add(u64::from(digit)) @@ -262,6 +256,243 @@ fn parse_prefixed_integer(raw: &str, radix: u32) -> Result Result { + let bytes = raw.as_bytes(); + if bytes.len() < 3 || bytes[0] != b'0' || (bytes[1] | 0x20) != b'x' { + return Err(unsupported(UnsupportedReason::LiteralForm)); + } + let body = &bytes[2..]; + let exp_at = body.iter().position(|byte| (byte | 0x20) == b'p'); + let digits = match exp_at { + Some(at) => &body[..at], + None => body, + }; + let bin_exp = match exp_at { + Some(at) => parse_bin_exp(&body[at + 1..])?, + None => 0, + }; + hex_digits_to_f64(digits, bin_exp) +} + +fn parse_bin_exp(text: &[u8]) -> Result { + if text.is_empty() { + return Err(unsupported(UnsupportedReason::LiteralForm)); + } + let (negative, digits) = match text[0] { + b'+' => (false, &text[1..]), + b'-' => (true, &text[1..]), + _ => (false, text), + }; + if digits.is_empty() { + return Err(unsupported(UnsupportedReason::LiteralForm)); + } + let mut magnitude: i64 = 0; + for byte in digits { + if !byte.is_ascii_digit() { + return Err(unsupported(UnsupportedReason::LiteralForm)); + } + let digit = i64::from(byte - b'0'); + magnitude = match magnitude + .checked_mul(10) + .and_then(|value| value.checked_add(digit)) + { + Some(value) => value, + None => return Ok(if negative { i64::MIN } else { i64::MAX }), + }; + } + Ok(if negative { -magnitude } else { magnitude }) +} + +fn hex_digits_to_f64(digits: &[u8], bin_exp: i64) -> Result { + let mut saw_digit = false; + let mut seen_dot = false; + let mut integer_len = 0usize; + let mut first_nz: Option<(usize, u8)> = None; + for (index, byte) in digits.iter().copied().enumerate() { + if byte == b'.' { + if seen_dot { + return Err(unsupported(UnsupportedReason::LiteralForm)); + } + seen_dot = true; + continue; + } + let digit = hex_value(byte).ok_or_else(|| unsupported(UnsupportedReason::LiteralForm))?; + saw_digit = true; + if !seen_dot { + integer_len += 1; + } + if digit != 0 && first_nz.is_none() { + first_nz = Some((index, digit)); + } + } + if !saw_digit { + return Err(unsupported(UnsupportedReason::LiteralForm)); + } + let Some((index, digit)) = first_nz else { + return Ok(0.0); + }; + let place = match hex_place(index, integer_len) { + Place::Over => return Ok(f64::INFINITY), + Place::Under => return Ok(0.0), + Place::Exact(place) => place, + }; + let bitlen = 32 - u32::from(digit).leading_zeros(); + let msb_exp = match msb_exponent(bin_exp, place, bitlen) { + Place::Over => return Ok(f64::INFINITY), + Place::Under => return Ok(0.0), + Place::Exact(exp) => exp, + }; + if msb_exp > 1023 { + return Ok(f64::INFINITY); + } + if msb_exp < -1075 { + return Ok(0.0); + } + let (mag, sticky) = hex_window(digits, index, digit, bitlen); + Ok(round_hex_window(mag, msb_exp, sticky)) +} + +enum Place { + Exact(i64), + Over, + Under, +} + +fn hex_place(index: usize, integer_len: usize) -> Place { + if index < integer_len { + match i64::try_from(integer_len - 1 - index) { + Ok(place) => Place::Exact(place), + Err(_) => Place::Over, + } + } else { + let fraction_index = index - integer_len - 1; + match i64::try_from(fraction_index) { + Ok(place) => Place::Exact(-1 - place), + Err(_) => Place::Under, + } + } +} + +fn msb_exponent(bin_exp: i64, place: i64, bitlen: u32) -> Place { + let shift = match place.checked_mul(4) { + Some(shift) => shift, + None => return if place < 0 { Place::Under } else { Place::Over }, + }; + let placed = match bin_exp.checked_add(shift) { + Some(placed) => placed, + None => { + return if place < 0 && bin_exp < 0 { + Place::Under + } else { + Place::Over + }; + } + }; + match placed.checked_add(i64::from(bitlen - 1)) { + Some(exp) => Place::Exact(exp), + None => { + if placed < 0 { + Place::Under + } else { + Place::Over + } + } + } +} + +fn hex_window(digits: &[u8], start: usize, first: u8, bitlen: u32) -> (u64, bool) { + let mut mag = u64::from(first) << (64 - bitlen); + let mut filled = bitlen; + let mut sticky = false; + for byte in &digits[start + 1..] { + if *byte == b'.' { + continue; + } + let Some(digit) = hex_value(*byte) else { + break; + }; + if filled >= 64 { + if digit != 0 { + sticky = true; + } + continue; + } + if filled + 4 <= 64 { + mag |= u64::from(digit) << (64 - filled - 4); + filled += 4; + continue; + } + let room = 64 - filled; + mag |= u64::from(digit) >> (4 - room); + let dropped = digit & ((1u8 << (4 - room)) - 1); + if dropped != 0 { + sticky = true; + } + filled = 64; + } + (mag, sticky) +} + +fn round_hex_window(mag: u64, msb_exp: i64, sticky: bool) -> f64 { + if msb_exp >= -1022 { + let mut significand = round_right(mag, 11, sticky); + let mut exp = msb_exp; + if significand == 1u64 << 53 { + significand = 1u64 << 52; + exp += 1; + } + if exp > 1023 { + return f64::INFINITY; + } + let exp_field = u64::try_from(exp + 1023).expect("binary64 exponent"); + let fraction = significand & ((1u64 << 52) - 1); + return f64::from_bits((exp_field << 52) | fraction); + } + let shift = u32::try_from(-msb_exp - 1011).expect("subnormal shift"); + let significand = round_right(mag, shift, sticky); + if significand >= 1u64 << 52 { + f64::from_bits(1u64 << 52) + } else { + f64::from_bits(significand) + } +} + +fn round_right(mag: u64, shift: u32, sticky: bool) -> u64 { + if shift == 0 { + return mag; + } + if shift > 64 { + return 0; + } + if shift == 64 { + let guard = mag >> 63; + let rest = mag & ((1u64 << 63) - 1); + let round_up = guard == 1 && (rest != 0 || sticky); + return u64::from(round_up); + } + let kept = mag >> shift; + let guard = (mag >> (shift - 1)) & 1; + let rest_mask = (1u64 << (shift - 1)) - 1; + let rest = mag & rest_mask; + let round_up = guard == 1 && (rest != 0 || sticky || (kept & 1) == 1); + if round_up { kept + 1 } else { kept } +} + +fn hex_value(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + fn lookup_proven(name: &[u8], env: &[ProvenLocal]) -> Result { env.iter() .rev() diff --git a/tests/luajit_number_source_tests.rs b/tests/luajit_number_source_tests.rs index edbc726..f397b8b 100644 --- a/tests/luajit_number_source_tests.rs +++ b/tests/luajit_number_source_tests.rs @@ -116,9 +116,12 @@ fn hex_float_decoder_keeps_nonzero_subnormal_bits() { #[test] fn proven_binary64_sources_run_through_the_plugin() { let cases = execute_cases(); + assert_hex_expectations_differ(&cases); let mut ran = 0usize; + let mut failed = Vec::new(); for case in &cases { let outcome = run_plugin(case.source); + let mut failed_this = false; match (&case.expect, outcome) { (Expect::Empty, Ok(run)) => { assert!( @@ -131,18 +134,44 @@ fn proven_binary64_sources_run_through_the_plugin() { (Expect::Bits(bits), Ok(run)) => { assert_eq!(run.stack.len(), 1, "{}", case.name); assert_bits(&run.stack[0], *bits, case.name); + if case.name.starts_with("hex-") { + println!("hex {} bits={bits:#018x}", case.name); + } } (Expect::Class(class), Ok(run)) => { assert_eq!(run.stack.len(), 1, "{}", case.name); assert_class(&run.stack[0], class, case.name); + if case.name.starts_with("hex-") { + println!("hex {} class={class}", case.name); + } + } + (_, Err(failure)) => { + let note = if failure.layer == "syntax" { + "; syntax rejection is not a lowering RED" + } else { + "" + }; + failed.push(format!( + "{} at {}: {} expect={}{note}", + case.name, + failure.layer, + failure.detail, + expect_label(&case.expect) + )); + failed_this = true; } - (_, Err(failure)) => panic!( - "{} failed at {}: {}", - case.name, failure.layer, failure.detail - ), } - ran += 1; + if !failed_this { + ran += 1; + } } + assert!( + failed.is_empty(), + "execute failures ({} of {}):\n{}", + failed.len(), + cases.len(), + failed.join("\n") + ); assert_eq!(ran, cases.len()); println!("execute cases={ran}"); } @@ -172,13 +201,25 @@ fn legal_uncovered_sources_are_not_syntax_rejections() { } } } + let syntax_names: Vec<_> = cases + .iter() + .filter(|case| matches!(case.layer, RejectLayer::Syntax)) + .map(|case| case.name) + .collect(); + let not_float_names: Vec<_> = cases + .iter() + .filter(|case| matches!(case.layer, RejectLayer::NotFloat(_))) + .map(|case| case.name) + .collect(); println!( "negative cases={} syntax={syntax} classify-not-float={not_float} compile-unsupported={unsupported}", cases.len() ); - assert_eq!(syntax, 3); + println!("syntax-reject names={syntax_names:?}"); + println!("not-float names={not_float_names:?}"); + assert_eq!(syntax, 9); assert_eq!(not_float, 3); - assert_eq!(unsupported, 8); + assert_eq!(unsupported, 7); } fn reject_layer(source: &str) -> RejectLayer { @@ -360,13 +401,13 @@ fn configured_oracle_matches_the_same_sources() { println!( "oracle differential execute={execute} signed-zero={signed_zero} nonfinite={nonfinite} empty={empty} not-float={not_float} compile-unsupported={unsupported} syntax-reject={syntax_reject}" ); - assert_eq!(execute, 38); - assert_eq!(signed_zero, 5); - assert_eq!(nonfinite, 5); + assert_eq!(execute, 51); + assert_eq!(signed_zero, 8); + assert_eq!(nonfinite, 7); assert_eq!(empty, 1); assert_eq!(not_float, 3); - assert_eq!(unsupported, 8); - assert_eq!(syntax_reject, 3); + assert_eq!(unsupported, 7); + assert_eq!(syntax_reject, 9); } #[test] @@ -996,6 +1037,116 @@ fn execute_cases() -> Vec { Category::Finite, Expect::Bits(0x40f8_6a00_0000_0000), ), + // Ordinary hex float and the wide hex integer are different literal forms. + // Expected bits come from the pinned LuaJIT `%a` oracle, not this parser. + case( + "hex-float", + "return 0x1.8p1", + Category::Finite, + Expect::Bits(0x4008_0000_0000_0000), + ), + case( + "hex-upper-omit-int", + "return 0X.8P+2", + Category::Finite, + Expect::Bits(0x4000_0000_0000_0000), + ), + case( + "hex-omit-exp", + "return 0x1.8", + Category::Finite, + Expect::Bits(0x3ff8_0000_0000_0000), + ), + case( + "hex-min-subnormal", + "return 0x1p-1074", + Category::Finite, + Expect::Bits(0x0000_0000_0000_0001), + ), + case( + "hex-above-half-ulp", + "return 0x1.0000000000000001p-1075", + Category::Finite, + Expect::Bits(0x0000_0000_0000_0001), + ), + case( + "hex-max-subnormal", + "return 0x0.fffffffffffffp-1022", + Category::Finite, + Expect::Bits(0x000f_ffff_ffff_ffff), + ), + case( + "hex-subnormal-to-normal", + "return 0x0.fffffffffffff8p-1022", + Category::Finite, + Expect::Bits(0x0010_0000_0000_0000), + ), + case( + "hex-tie-down", + "return 0x1.00000000000008p0", + Category::Finite, + Expect::Bits(0x3ff0_0000_0000_0000), + ), + case( + "hex-tie-sticky", + "return 0x1.000000000000080001p0", + Category::Finite, + Expect::Bits(0x3ff0_0000_0000_0001), + ), + case( + "hex-tie-up", + "return 0x1.00000000000018p0", + Category::Finite, + Expect::Bits(0x3ff0_0000_0000_0002), + ), + case( + "hex-tie-zero-tail", + "return 0x1.000000000000080000p0", + Category::Finite, + Expect::Bits(0x3ff0_0000_0000_0000), + ), + case( + "hex-max-finite", + "return 0x1.fffffffffffffp1023", + Category::Finite, + Expect::Bits(0x7fef_ffff_ffff_ffff), + ), + case( + "hex-wide", + "return 0x10000000000000000", + Category::Finite, + Expect::Bits(0x43f0_0000_0000_0000), + ), + case( + "hex-half-ulp-pos-zero", + "return 0x1p-1075", + Category::SignedZero, + Expect::Bits(0.0f64.to_bits()), + ), + case( + "hex-half-ulp-neg-zero", + "return -0x1p-1075", + Category::SignedZero, + Expect::Bits((-0.0f64).to_bits()), + ), + case( + "hex-zero-large-exp", + "return 0x0.000p1048575", + Category::SignedZero, + Expect::Bits(0.0f64.to_bits()), + ), + case( + "hex-overflow", + "return 0x1.fffffffffffff8p1023", + Category::NonFinite, + Expect::Class("inf"), + ), + case( + "hex-large-exp", + "return 0x1.000p1048575", + Category::NonFinite, + Expect::Class("inf"), + ), ] } @@ -1013,6 +1164,47 @@ fn case( } } +fn assert_hex_expectations_differ(cases: &[ExecuteCase]) { + let float = cases + .iter() + .find(|case| case.name == "hex-float") + .expect("ordinary hex float case"); + let wide = cases + .iter() + .find(|case| case.name == "hex-wide") + .expect("wide hex integer case"); + match (&float.expect, &wide.expect) { + (Expect::Bits(float_bits), Expect::Bits(wide_bits)) => { + assert_ne!( + float_bits, wide_bits, + "ordinary hex float and wide hex integer share an expected value" + ); + } + _ => panic!("hex-float and hex-wide must be finite bit patterns"), + } + let mut seen = Vec::new(); + for case in cases.iter().filter(|case| case.name.starts_with("hex-")) { + if let Expect::Bits(bits) = case.expect + && !seen.contains(&bits) + { + seen.push(bits); + } + } + assert!( + seen.len() >= 10, + "hex finite expectations collapsed to {} values", + seen.len() + ); +} + +fn expect_label(expect: &Expect) -> String { + match expect { + Expect::Bits(bits) => format!("bits={bits:#018x}"), + Expect::Class(class) => format!("class={class}"), + Expect::Empty => "empty".to_string(), + } +} + fn negative_cases() -> Vec { vec![ NegativeCase { @@ -1030,6 +1222,37 @@ fn negative_cases() -> Vec { source: "return 1 // 2", layer: RejectLayer::Syntax, }, + // Huge text exponents and a 65-bit binary significand never reach lowering. + NegativeCase { + name: "hex-exp-huge", + source: "return 0x1p9999999", + layer: RejectLayer::Syntax, + }, + NegativeCase { + name: "hex-exp-huge-zero", + source: "return 0x0p9999999", + layer: RejectLayer::Syntax, + }, + NegativeCase { + name: "hex-exp-huge-neg", + source: "return 0x1p-9999999", + layer: RejectLayer::Syntax, + }, + NegativeCase { + name: "binary-past-64", + source: "return 0b10000000000000000000000000000000000000000000000000000000000000000", + layer: RejectLayer::Syntax, + }, + NegativeCase { + name: "hex-exp-truncated", + source: "return 0x1p+", + layer: RejectLayer::Syntax, + }, + NegativeCase { + name: "hex-dot-only", + source: "return 0x.p1", + layer: RejectLayer::Syntax, + }, NegativeCase { name: "signed64", source: "return 1LL", @@ -1060,11 +1283,6 @@ fn negative_cases() -> Vec { source: "return 1 + \"2\"", layer: RejectLayer::Unsupported(number_source::UnsupportedReason::Expression), }, - NegativeCase { - name: "hex-float", - source: "return 0x1.8p1", - layer: RejectLayer::Unsupported(number_source::UnsupportedReason::LiteralForm), - }, NegativeCase { name: "assign", source: "local x = 1\nx = 2\nreturn x", From 9d1dd2f55280500f09549e0baa7b920f90353a13 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 21:44:41 +0800 Subject: [PATCH 016/225] feat(lua): lower locked numeric bitwise operators privately --- src/frontends/lua/number.rs | 112 +++++++++++++++- src/frontends/lua/number_source.rs | 80 ++++++++---- tests/luajit_number/bitwise.rs | 86 +++++++++++++ tests/luajit_number_semantics_tests.rs | 52 +++++++- tests/luajit_number_source_tests.rs | 170 ++++++++++++++++++++++++- 5 files changed, 463 insertions(+), 37 deletions(-) create mode 100644 tests/luajit_number/bitwise.rs diff --git a/src/frontends/lua/number.rs b/src/frontends/lua/number.rs index bd9e7da..7f6404b 100644 --- a/src/frontends/lua/number.rs +++ b/src/frontends/lua/number.rs @@ -24,7 +24,59 @@ //! temp is a typed reference returned by the operation that just emitted the //! binding. There is no constructor from an arbitrary `Expr` or `LocalSlot`. -use vm::{BuiltinFunction, Expr, LocalIrBuilder, LocalSlot, ParseError, Stmt}; +use vm::compiler::HostCallResolver; +use vm::{BuiltinFunction, Expr, LocalIrBuilder, LocalSlot, ParseError, Stmt, TypeSchema}; + +pub(crate) const BIT_NOT: &str = "lua_number::bit_not"; + +#[derive(Clone, Copy)] +pub(crate) enum BitwiseBinary { + And, + Or, + Xor, + Shl, + Shr, + Sar, +} + +impl BitwiseBinary { + pub(crate) fn name(self) -> &'static str { + match self { + Self::And => "lua_number::bit_and", + Self::Or => "lua_number::bit_or", + Self::Xor => "lua_number::bit_xor", + Self::Shl => "lua_number::bit_shl", + Self::Shr => "lua_number::bit_shr", + Self::Sar => "lua_number::bit_sar", + } + } + + pub(crate) fn evaluate(self, left: f64, right: f64) -> f64 { + let left = tobit(left); + let right = tobit(right); + // Rust's wrapping shifts mask the count to the low five bits for i32/u32. + let result = match self { + Self::And => left & right, + Self::Or => left | right, + Self::Xor => left ^ right, + Self::Shl => left.wrapping_shl(right as u32), + Self::Shr => (left as u32).wrapping_shr(right as u32) as i32, + Self::Sar => left.wrapping_shr(right as u32), + }; + f64::from(result) + } +} + +pub(crate) fn bit_not(value: f64) -> f64 { + f64::from(!tobit(value)) +} + +/// The pinned LuaJIT x64 `vm_tobit` adds 2^52 + 2^51 in binary64, then +/// reads the low 32 bits of the sum. Large values observe the rounding of +/// the addition itself, so rounding the input and reducing modulo 2^32 differs. +fn tobit(value: f64) -> i32 { + (value + 6_755_399_441_055_744.0).to_bits() as i32 +} /// A Lua number built only from a binary64 literal or from an operation on one. #[derive(Clone, Debug)] @@ -148,6 +200,64 @@ impl<'a> NumberLowering<'a> { self.name_probes } + pub(crate) fn bitwise_not( + &mut self, + resolver: &HostCallResolver<'_>, + operand: ClassifiedNumber, + ) -> Result { + self.bit_call(resolver, BIT_NOT, [operand]) + } + + pub(crate) fn bitwise_binary( + &mut self, + resolver: &HostCallResolver<'_>, + op: BitwiseBinary, + lhs: ClassifiedNumber, + rhs: ClassifiedNumber, + ) -> Result { + self.bit_call(resolver, op.name(), [lhs, rhs]) + } + + fn bit_call( + &mut self, + resolver: &HostCallResolver<'_>, + name: &str, + operands: [ClassifiedNumber; N], + ) -> Result { + let signature = [const { TypeSchema::Float }; N]; + let resolved = resolver + .resolve(name, &signature) + .map_err(|error| ParseError::new(error.to_string()))?; + if resolved.return_type != TypeSchema::Float + || !resolved + .params + .iter() + .map(|param| ¶m.schema) + .eq(&signature) + { + return Err(ParseError::new(format!( + "invalid Lua bitwise signature for {name}" + ))); + } + self.builder.declare_function(name, Some(N as u8))?; + let index = self + .builder + .function_index(name) + .expect("declared bitwise operation"); + Ok(ClassifiedNumber { + expr: Expr::Call( + index, + Vec::new(), + operands + .into_iter() + .map(ClassifiedNumber::into_expr) + .collect(), + Some(Box::new(resolved)), + None, + ), + }) + } + /// Lua `%` on binary64: `lhs - floor(lhs / rhs) * rhs`. /// /// Each operand is bound once before the formula, so a side effect in an diff --git a/src/frontends/lua/number_source.rs b/src/frontends/lua/number_source.rs index 6f60d9c..00f10e8 100644 --- a/src/frontends/lua/number_source.rs +++ b/src/frontends/lua/number_source.rs @@ -5,11 +5,13 @@ //! floats share one conversion. `LL`, `ULL`, imaginary suffixes, and names //! this walk did not prove stay outside it. Chains are hoisted with the //! kernel's temps so a flat source spine does not become an unbounded Core -//! expression. Slot reuse stays with Core. +//! expression. Slot reuse stays with Core. Bitwise calls use the private +//! numeric imports resolved by the caller. use super::ast::{BinOp, Chunk, Expr, ExprList, LocalName, NumberKind, Span, Stmt, UnOp}; -use super::number::{ClassifiedNumber, NumberLowering}; +use super::number::{BitwiseBinary, ClassifiedNumber, NumberLowering}; use super::resolve::Resolution; +use vm::compiler::HostCallResolver; use vm::{FrontendIr, LocalIrBuilder, ParseError, Stmt as CoreStmt}; pub(crate) struct LoweredNumberChunk { @@ -45,10 +47,16 @@ struct ProvenLocal { value: ClassifiedNumber, } +struct NumberSource<'a> { + locals: Vec, + resolver: HostCallResolver<'a>, +} + pub(crate) fn lower_proven_chunk( source: &str, chunk: &Chunk, resolution: &Resolution, + resolver: HostCallResolver<'_>, ) -> Result { if let Some(error) = resolution.errors.first() { return Err(NumberSourceError::Syntax { @@ -59,7 +67,10 @@ pub(crate) fn lower_proven_chunk( let mut stmts = Vec::new(); let name_probes = { let mut lowering = NumberLowering::new(&mut builder); - let mut env = Vec::new(); + let mut env = NumberSource { + locals: Vec::new(), + resolver, + }; for stmt in &chunk.body.stmts { lower_stmt(source, stmt, &mut lowering, &mut stmts, &mut env)?; } @@ -85,7 +96,7 @@ fn lower_stmt( stmt: &Stmt, lowering: &mut NumberLowering<'_>, stmts: &mut Vec, - env: &mut Vec, + env: &mut NumberSource<'_>, ) -> Result<(), NumberSourceError> { match stmt { Stmt::Empty { .. } => Ok(()), @@ -114,7 +125,7 @@ fn lower_local( values: &ExprList, lowering: &mut NumberLowering<'_>, stmts: &mut Vec, - env: &mut Vec, + env: &mut NumberSource<'_>, ) -> Result<(), NumberSourceError> { if names.len() != 1 || values.exprs.len() != 1 { return Err(unsupported(UnsupportedReason::NotSingle)); @@ -126,7 +137,7 @@ fn lower_local( let bound = lowering .bind_named(text, lowered, line_of(source, span), stmts) .map_err(kernel_error)?; - env.push(ProvenLocal { + env.locals.push(ProvenLocal { name: name.bytes.clone(), value: bound, }); @@ -138,28 +149,28 @@ fn lower_expr( expr: &Expr, lowering: &mut NumberLowering<'_>, stmts: &mut Vec, - env: &[ProvenLocal], + env: &NumberSource<'_>, ) -> Result { match expr { Expr::Number { raw, kind, .. } => lower_number(raw, *kind), - Expr::Name { name, .. } => lookup_proven(name.bytes.as_slice(), env), + Expr::Name { name, .. } => lookup_proven(name.bytes.as_slice(), &env.locals), Expr::Paren { inner, .. } => lower_expr(source, inner, lowering, stmts, env), Expr::Unary { op, expr, .. } => lower_unary(*op, expr, source, lowering, stmts, env), Expr::Binary { op, left, right, .. } => { let lhs = lower_expr(source, left, lowering, stmts, env)?; + // Finish the left value before emitting any right operand temps. + let lhs = lowering.materialize(lhs, stmts).map_err(kernel_error)?; let rhs = lower_expr(source, right, lowering, stmts, env)?; - apply(*op, lhs, rhs, lowering, stmts) + apply(*op, lhs, rhs, lowering, stmts, &env.resolver) } Expr::BinaryChain { base, steps, .. } => { let mut acc = lower_expr(source, base, lowering, stmts, env)?; - for (index, step) in steps.iter().enumerate() { + for step in steps { + acc = lowering.materialize(acc, stmts).map_err(kernel_error)?; let rhs = lower_expr(source, &step.expr, lowering, stmts, env)?; - acc = apply(step.op, acc, rhs, lowering, stmts)?; - if index + 1 != steps.len() { - acc = lowering.materialize(acc, stmts).map_err(kernel_error)?; - } + acc = apply(step.op, acc, rhs, lowering, stmts, &env.resolver)?; } Ok(acc) } @@ -173,14 +184,20 @@ fn lower_unary( source: &str, lowering: &mut NumberLowering<'_>, stmts: &mut Vec, - env: &[ProvenLocal], + env: &NumberSource<'_>, ) -> Result { - if op != UnOp::Neg { + if !matches!(op, UnOp::Neg | UnOp::BNot) { return Err(unsupported(UnsupportedReason::Operator)); } let inner = lower_expr(source, expr, lowering, stmts, env)?; let inner = lowering.materialize(inner, stmts).map_err(kernel_error)?; - Ok(inner.neg()) + if op == UnOp::Neg { + Ok(inner.neg()) + } else { + lowering + .bitwise_not(&env.resolver, inner) + .map_err(kernel_error) + } } fn apply( @@ -189,18 +206,27 @@ fn apply( rhs: ClassifiedNumber, lowering: &mut NumberLowering<'_>, stmts: &mut Vec, + resolver: &HostCallResolver<'_>, ) -> Result { - let lhs = lowering.materialize(lhs, stmts).map_err(kernel_error)?; let rhs = lowering.materialize(rhs, stmts).map_err(kernel_error)?; - match op { - BinOp::Add => Ok(lhs.add(rhs)), - BinOp::Sub => Ok(lhs.sub(rhs)), - BinOp::Mul => Ok(lhs.mul(rhs)), - BinOp::Div => Ok(lhs.div(rhs)), - BinOp::Pow => Ok(lhs.pow(rhs)), - BinOp::Mod => lowering.floor_mod(lhs, rhs).map_err(kernel_error), - _ => Err(unsupported(UnsupportedReason::Operator)), - } + let bitwise = match op { + BinOp::Add => return Ok(lhs.add(rhs)), + BinOp::Sub => return Ok(lhs.sub(rhs)), + BinOp::Mul => return Ok(lhs.mul(rhs)), + BinOp::Div => return Ok(lhs.div(rhs)), + BinOp::Pow => return Ok(lhs.pow(rhs)), + BinOp::Mod => return lowering.floor_mod(lhs, rhs).map_err(kernel_error), + BinOp::Band => BitwiseBinary::And, + BinOp::Bor => BitwiseBinary::Or, + BinOp::BXor => BitwiseBinary::Xor, + BinOp::Shl => BitwiseBinary::Shl, + BinOp::Shr => BitwiseBinary::Shr, + BinOp::Sar => BitwiseBinary::Sar, + _ => return Err(unsupported(UnsupportedReason::Operator)), + }; + lowering + .bitwise_binary(resolver, bitwise, lhs, rhs) + .map_err(kernel_error) } fn lower_number(raw: &str, kind: NumberKind) -> Result { diff --git a/tests/luajit_number/bitwise.rs b/tests/luajit_number/bitwise.rs new file mode 100644 index 0000000..c61444a --- /dev/null +++ b/tests/luajit_number/bitwise.rs @@ -0,0 +1,86 @@ +//! Test-only catalog and exact bindings for the private Lua number operations. + +use super::number::{self, BitwiseBinary}; +use std::sync::{Arc, OnceLock}; +use vm::{ + CallOutcome, CallReturn, HostApiBuilder, HostApiCatalog, HostFunctionRegistry, + HostFunctionSchema, HostImportSchema, HostOwnedFunction, HostParamSchema, HostTypeSchema, + OwnedHostCall, Value, Vm, VmError, +}; + +#[derive(Clone, Copy)] +enum BitwiseHost { + Not, + Binary(BitwiseBinary), +} + +const OPERATIONS: [BitwiseHost; 7] = [ + BitwiseHost::Not, + BitwiseHost::Binary(BitwiseBinary::And), + BitwiseHost::Binary(BitwiseBinary::Or), + BitwiseHost::Binary(BitwiseBinary::Xor), + BitwiseHost::Binary(BitwiseBinary::Shl), + BitwiseHost::Binary(BitwiseBinary::Shr), + BitwiseHost::Binary(BitwiseBinary::Sar), +]; + +impl BitwiseHost { + fn name(self) -> &'static str { + match self { + Self::Not => number::BIT_NOT, + Self::Binary(op) => op.name(), + } + } +} + +impl HostOwnedFunction for BitwiseHost { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let result = match (*self, call.args()) { + (Self::Not, [Value::Float(value)]) => number::bit_not(*value), + (Self::Binary(op), [Value::Float(left), Value::Float(right)]) => { + op.evaluate(*left, *right) + } + _ => return Err(VmError::HostError("expected classified Lua numbers".into())), + }; + Ok(CallOutcome::Return(CallReturn::one(Value::Float(result)))) + } +} + +pub(super) fn catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = HostApiBuilder::new(); + for op in OPERATIONS { + let names: &[&str] = match op { + BitwiseHost::Not => &["value"], + BitwiseHost::Binary(_) => &["left", "right"], + }; + builder.function(HostFunctionSchema::with_return( + op.name(), + names + .iter() + .map(|name| HostParamSchema::value(*name, HostTypeSchema::Float)) + .collect(), + HostTypeSchema::Float, + )); + } + Arc::new(builder.build().expect("Lua bitwise catalog")) + }) +} + +pub(super) fn bind(vm: &mut Vm) -> Result<(), VmError> { + let catalog = catalog(); + let mut registry = HostFunctionRegistry::empty(); + for op in OPERATIONS { + let name = op.name(); + let function = catalog.function(name).expect("Lua bitwise schema"); + registry.register_exact_owned( + name, + function.params.len() as u8, + HostImportSchema::from_function(catalog, function), + move |_| Box::new(op), + )?; + registry.authorize_registered_builtin_import(name); + } + registry.bind_vm_cached(vm) +} diff --git a/tests/luajit_number_semantics_tests.rs b/tests/luajit_number_semantics_tests.rs index f15c5be..11340a4 100644 --- a/tests/luajit_number_semantics_tests.rs +++ b/tests/luajit_number_semantics_tests.rs @@ -4,10 +4,13 @@ //! expected bits were observed on locked LuaJIT 96f7b297326e9fd454b7186c6858b2773f94a0dc //! with `-joff`. NaN is compared by category only. +#[path = "luajit_number/bitwise.rs"] +mod bitwise; #[path = "../src/frontends/lua/number.rs"] mod number; -use number::{ClassifiedNumber, NumberLowering}; +use number::{BitwiseBinary, ClassifiedNumber, NumberLowering}; +use vm::compiler::HostCallResolver; use vm::{AssignmentKind, Compiler, Expr, LocalIrBuilder, LocalSlot, Stmt, Value, Vm}; const PROTOCOL_06: [&str; 4] = ["3.5", "1", "-1", "-2.5"]; @@ -193,6 +196,50 @@ fn operands_are_evaluated_once_left_then_right() { assert_unary_eval_once(); } +#[test] +fn bitwise_operands_are_evaluated_once_left_then_right() { + let resolver = HostCallResolver::new(bitwise::catalog()); + for (op, lhs, rhs, result) in [ + (BitwiseBinary::And, 6.0, 3.0, "2"), + (BitwiseBinary::Or, 4.0, 3.0, "7"), + (BitwiseBinary::Xor, 6.0, 3.0, "5"), + (BitwiseBinary::Shl, 1.0, 31.0, "-2147483648"), + (BitwiseBinary::Shr, -1.0, 1.0, "2147483647"), + (BitwiseBinary::Sar, -4.0, 1.0, "-2"), + ] { + assert_binary_eval_once( + op.name(), + lhs, + rhs, + result, + result.parse::().unwrap().to_bits(), + |lowering, left, right| { + lowering + .bitwise_binary(&resolver, op, left, right) + .expect("lower bitwise operation") + }, + ); + } + + let mut builder = LocalIrBuilder::new(); + let sequence = builder.alloc_local_named("sequence").expect("sequence"); + let mark = builder.alloc_local_named("mark").expect("mark"); + let value = NumberLowering::new(&mut builder) + .bitwise_not(&resolver, observed_count(sequence, mark, 0.0)) + .expect("lower complement"); + let ran = run( + builder, + vec![ + let_int(sequence, 0), + let_int(mark, 0), + expr_stmt(value.into_expr()), + ], + ); + assert_eq!(local_int(&ran, sequence), 1); + assert_eq!(local_int(&ran, mark), 1); + assert_protocol_number(&ran.stack[0], "-1", (-1.0f64).to_bits()); +} + #[test] fn remainder_temps_keep_a_guest_local_and_a_nested_rhs() { // Both examples share one builder and one Core compile/run. @@ -414,7 +461,7 @@ fn assert_binary_eval_once( rhs: f64, text: &str, bits: u64, - op: fn(&mut NumberLowering<'_>, ClassifiedNumber, ClassifiedNumber) -> ClassifiedNumber, + op: impl FnOnce(&mut NumberLowering<'_>, ClassifiedNumber, ClassifiedNumber) -> ClassifiedNumber, ) { let mut builder = LocalIrBuilder::new(); let sequence = builder.alloc_local_named("sequence").expect("sequence"); @@ -508,6 +555,7 @@ fn run_stmts(local_count: usize, stmts: Vec) -> Ran { .compile_program(&stmts) .unwrap_or_else(|error| panic!("compile failed: {error}")); let mut vm = Vm::new(program); + bitwise::bind(&mut vm).expect("bind bitwise test imports"); vm.run() .unwrap_or_else(|error| panic!("run failed: {error}")); Ran { diff --git a/tests/luajit_number_source_tests.rs b/tests/luajit_number_source_tests.rs index f397b8b..b62373f 100644 --- a/tests/luajit_number_source_tests.rs +++ b/tests/luajit_number_source_tests.rs @@ -1,8 +1,8 @@ //! Standard Lua numeric fragments through the source seam. //! -//! The trial plugin lives here. It is not a product entry and it does not -//! register hosts. Each executed sample is real Lua source, lowered by the -//! seam, then compiled with `SourcePlugin` and run on the VM. +//! The trial plugin lives here. Each executed sample is real Lua source, +//! lowered by the private seam, compiled with `SourcePlugin`, and run on the VM. +//! The bitwise imports are bound only by the test harness. // This test compiles the production AST through a path module. Four helpers // (`Name::is`, `ExprList::tail_multi`, `AssignTarget::span`/`has_nav`, @@ -11,6 +11,8 @@ #[allow(dead_code)] #[path = "../src/frontends/lua/ast.rs"] mod ast; +#[path = "luajit_number/bitwise.rs"] +mod bitwise; #[path = "../src/frontends/lua/lexer.rs"] mod lexer; #[path = "../src/frontends/lua/number.rs"] @@ -24,8 +26,10 @@ mod resolve; use std::io::Write; use std::process::{Command, Stdio}; +use std::sync::Arc; use number_source::NumberSourceError; +use vm::compiler::HostCallResolver; use vm::{ CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, ParseError, SourceFlavor, SourcePlugin, Value, Vm, VmStatus, @@ -176,6 +180,142 @@ fn proven_binary64_sources_run_through_the_plugin() { println!("execute cases={ran}"); } +#[test] +fn numeric_bitwise_sources_return_binary64() { + for &(name, source, expected) in bitwise_cases() { + let run = run_plugin(source) + .unwrap_or_else(|failure| panic!("{name} at {}: {}", failure.layer, failure.detail)); + assert_eq!(run.stack.len(), 1, "{name}"); + assert_bits(&run.stack[0], expected.to_bits(), name); + } +} + +fn bitwise_cases() -> &'static [(&'static str, &'static str, f64)] { + &[ + ("and", "return 6 & 3", 2.0), + ("or", "return 4 | 3", 7.0), + ("xor", "return 6 ~ 3", 5.0), + ("not", "return ~0", -1.0), + ("signed-bit", "return 1 << 31", -2147483648.0), + ("wrapped-count", "return 1 << 32", 1.0), + ("negative-count", "return 1 << -1", -2147483648.0), + ("logical-right", "return -1 >> 1", 2147483647.0), + ("logical-result-signed", "return -1 >> 32", -1.0), + ("arithmetic-right", "return -4 ~>> 1", -2.0), + ("fractional-count", "return 1 << 1.5", 4.0), + ("nan-count", "local count = 0/0; return 3 << count", 3.0), + ("tie-down", "return 2.5 & 3", 2.0), + ("tie-up", "return 1.5 & 3", 2.0), + ("negative-tie", "return -1.5 | 0", -2.0), + ("wrap-32", "return 4294967296 | 1", 1.0), + ("negative-zero", "local n = -0; return n | 0", 0.0), + ("nan", "local n = 0/0; return n | 1", 1.0), + ("infinity", "local n = 1/0; return n | 7", 7.0), + ("negative-infinity", "local n = -1/0; return n | 7", 7.0), + ("large-precision", "return 9007199254740992 | 0", 0.0), + ("positive-bias", "return 9007199254740994 | 0", 1.0), + ("negative-bias", "return -9007199254740990 | 0", -8.0), + ( + "evaluated-large-operands", + "local a = 2^53 + 2; local b = -2^53 + 2; return (a | 0) * 10 + (b | 0)", + 2.0, + ), + ( + "locals-and-arithmetic", + "local left = 7/2; local right = 2+1; return (left & right) / 2", + 0.0, + ), + ( + "bit-result-binding", + "local n = ~(-4 ~>> 1); return n / 2", + 0.5, + ), + ("left-associative-shift", "return 4 << 1 >> 2", 2.0), + ("arithmetic-precedence", "return 1 + 2 << 1 + 1", 12.0), + ] +} + +#[test] +fn bitwise_source_rejections_keep_their_layers() { + use number_source::UnsupportedReason; + + for (source, layer) in [ + ("return (-4) >>> 1", RejectLayer::Syntax), + ( + "return 1LL | 0", + RejectLayer::NotFloat(ast::NumberKind::Signed64), + ), + ( + r#"return "3" & 1"#, + RejectLayer::Unsupported(UnsupportedReason::Expression), + ), + ( + "return true | 0", + RejectLayer::Unsupported(UnsupportedReason::Expression), + ), + ( + "return 1 & nil", + RejectLayer::Unsupported(UnsupportedReason::Expression), + ), + ( + "return ~{}", + RejectLayer::Unsupported(UnsupportedReason::Expression), + ), + ( + "return 1 << count", + RejectLayer::Unsupported(UnsupportedReason::UnprovenName), + ), + ] { + assert_eq!(reject_layer(source), layer, "{source}"); + assert!(run_plugin(source).is_err(), "{source}"); + } +} + +#[test] +fn configured_bitwise_oracle_matches_numeric_sources() { + let Ok(path) = std::env::var("LUAJIT_ORACLE") else { + println!("bitwise oracle not configured; compared=0"); + return; + }; + assert_oracle_baseline(&path); + let architecture = spawn_oracle( + &path, + &[ + "-E", + "-joff", + "-e", + "assert(jit.arch == 'x64' and not jit.status())", + ], + None, + ); + require_success(&path, &architecture, "x64 bitwise oracle"); + for &(name, source, _) in bitwise_cases() { + compare_oracle(&path, source, name); + } + assert!(!oracle_load(&path, "return (-4) >>> 1")); + let output = spawn_oracle( + &path, + &[ + "-E", + "-joff", + "-e", + r#" +local chunk = assert(load(io.read('*a'), '@bitwise-string', 't')) +local ok, err = pcall(chunk) +assert(not ok and type(err) == 'string' and err:find('a string value', 1, true)) +io.write('runtime-error:string\n') +"#, + ], + Some(br#"return "3" & 1"#), + ); + require_success(&path, &output, "string runtime-error oracle"); + assert_eq!(output.stdout, b"runtime-error:string\n"); + println!( + "bitwise oracle compared={} syntax-reject=1 runtime-error=1", + bitwise_cases().len() + ); +} + #[test] fn legal_uncovered_sources_are_not_syntax_rejections() { let cases = negative_cases(); @@ -227,7 +367,12 @@ fn reject_layer(source: &str) -> RejectLayer { Err(_) => RejectLayer::Syntax, Ok(chunk) => { let resolution = resolve::resolve(&chunk); - match number_source::lower_proven_chunk(source, &chunk, &resolution) { + match number_source::lower_proven_chunk( + source, + &chunk, + &resolution, + HostCallResolver::new(bitwise::catalog()), + ) { Err(NumberSourceError::Syntax { .. }) => RejectLayer::Syntax, Err(NumberSourceError::NotFloat { kind }) => RejectLayer::NotFloat(kind), Err(NumberSourceError::CompileUnsupported { reason }) => { @@ -674,8 +819,13 @@ fn lower_source(source: &str) -> Result { let chunk = parser::parse_chunk(source.as_bytes()) .map_err(|error| ParseError::new(format!("lua number syntax: {}", error.message)))?; let resolution = resolve::resolve(&chunk); - let lowered = - number_source::lower_proven_chunk(source, &chunk, &resolution).map_err(source_error)?; + let lowered = number_source::lower_proven_chunk( + source, + &chunk, + &resolution, + HostCallResolver::new(bitwise::catalog()), + ) + .map_err(source_error)?; Ok(OwnedLowered { logical_slots: lowered.logical_slots, binding_names: lowered.binding_names, @@ -702,7 +852,9 @@ fn run_plugin(source: &str) -> Result { let compiled = vm::compile_source_with_flavor_and_options( source, SourceFlavor::Lua, - CompileSourceFileOptions::new().with_source_plugin(&NUMERIC_PLUGIN), + CompileSourceFileOptions::new() + .with_source_plugin(&NUMERIC_PLUGIN) + .with_host_api_catalog(Arc::clone(bitwise::catalog())), ); let compiled = match compiled { Ok(compiled) => compiled, @@ -710,6 +862,10 @@ fn run_plugin(source: &str) -> Result { }; let frame_slots = compiled.program.local_count; let mut vm = Vm::new(compiled.program); + bitwise::bind(&mut vm).map_err(|error| LayerFailure { + layer: "bind", + detail: error.to_string(), + })?; match vm.run() { Err(error) => Err(LayerFailure { layer: "run", From f2e3a797d9b66bcf0b243c2e9f28819840ec9b7f Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 22:13:08 +0800 Subject: [PATCH 017/225] feat(lua): lower chunk repeat until break and continue on the fixed core --- src/frontends/lua/control.rs | 72 ++- tests/compiler/compiler_lua_control_tests.rs | 481 +++++++++++++++++++ 2 files changed, 545 insertions(+), 8 deletions(-) diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs index 3dce898..cb4dcdf 100644 --- a/src/frontends/lua/control.rs +++ b/src/frontends/lua/control.rs @@ -5,16 +5,22 @@ //! not a file entry and not a fallback to the line lowerer. //! //! A chunk with no goto and no early return is emitted as ordinary -//! statements, including a source `while`. Any goto, or a return that is not -//! the chunk tail, becomes a private integer state loop. Each basic block is -//! one state. A transfer assigns that state and `Continue`s the dispatch +//! statements, including a source `while` or `repeat`. Any goto, or a return +//! that is not the chunk tail, becomes a private integer state loop. Each basic +//! block is one state. A transfer assigns that state and `Continue`s the dispatch //! loop, so it is emitted only in the dispatch arm, never inside a nested //! source loop. `break` and `continue` inside a source loop stay Core -//! statements of that loop. User values are binary64 or bool. The state id -//! is a private Core int and is not a Lua number. In this numeric/bool slice -//! only `false` is falsy: `0` and every other number are truthy. `if`, -//! `elseif`, `while`, and `not` / `!` pass the operand through `core_truthy` -//! before a Core branch or `Not`. The operand expression is placed once. +//! statements of that loop. A source `repeat` is one Core `for`, not a copied +//! body. Its private bool starts true, so the body runs before `until`. The +//! `for` post stores whether another round is required. Fallthrough and +//! `continue` both reach that post; `break` skips it and leaves this `for`, +//! not an outer dispatch loop. `until` is placed once and can read the +//! same-round body locals. In this numeric/bool slice only `false` is falsy: +//! `0` and every other number are truthy, so `until 0` stops after one body. +//! `if`, `elseif`, `while`, and `not` / `!` pass the operand through +//! `core_truthy` before a Core branch or `Not`. `until` does the same, once, +//! in the `for` post. The operand expression is placed once. The state id is +//! a private Core int and is not a Lua number. use super::ast::{self, BinOp, Block, Chunk, Expr, Name, NumberKind, Span, Stmt, UnOp}; use super::lexer; @@ -54,6 +60,7 @@ struct Lower<'a> { state: Option, result: Option, label_state: Vec>, + repeat_flags: u32, } struct BlockBuf { @@ -106,6 +113,7 @@ impl<'a> Lower<'a> { state: None, result: None, label_state, + repeat_flags: 0, } } @@ -223,6 +231,9 @@ impl<'a> Lower<'a> { span, } => self.if_item(arms, else_body.as_ref(), *span), Stmt::While { cond, body, span } => Ok(Item::Core(self.while_stmt(cond, body, *span)?)), + Stmt::Repeat { body, until, span } => { + Ok(Item::Core(self.repeat_stmt(body, until, *span)?)) + } Stmt::Break { span } | Stmt::Continue { span } => { Err(self.fail(*span, "break or continue outside a source loop")) } @@ -353,6 +364,44 @@ impl<'a> Lower<'a> { }) } + fn repeat_stmt( + &mut self, + body: &Block, + until: &Expr, + span: Span, + ) -> Result { + if contains_transfer(body) || contains_label(body) { + return Err(self.fail( + span, + "goto, label, or return inside a loop is not in this slice", + )); + } + let (body_stmts, value) = self.straight(&body.stmts, true)?; + if value.is_some() { + return Err(self.fail(span, "return inside a loop is not in this slice")); + } + let line = self.line(span); + let again = self.alloc_repeat_flag()?; + let until_value = self.expr(until)?; + // Core `while` tests its condition before the body and sends + // `continue` there, so `until` cannot live in that condition: it + // would run before the body locals exist, and a Core `continue` + // would skip it. A `for` post is reached only after the body or a + // `continue`, and a `break` in the body skips the post. The private + // flag is a Core bool, not a Lua value. + Ok(CoreStmt::For { + init: Box::new(let_expr(again, CoreExpr::Bool(true), line)), + condition: CoreExpr::Var(again), + post: Box::new(set_slot( + again, + CoreExpr::Not(Box::new(core_truthy(until_value))), + line, + )), + body: body_stmts, + line, + }) + } + fn straight( &mut self, stmts: &[Stmt], @@ -422,6 +471,7 @@ impl<'a> Lower<'a> { span, } => self.if_core(arms, else_body.as_ref(), *span, in_loop), Stmt::While { cond, body, span } => self.while_stmt(cond, body, *span), + Stmt::Repeat { body, until, span } => self.repeat_stmt(body, until, *span), Stmt::Break { span } if in_loop => Ok(CoreStmt::Break { line: self.line(*span), }), @@ -683,6 +733,12 @@ impl<'a> Lower<'a> { self.builder.alloc_local_named(name) } + fn alloc_repeat_flag(&mut self) -> Result { + let name = format!("$lua_repeat_again_{}", self.repeat_flags); + self.repeat_flags += 1; + self.alloc_private(&name) + } + fn goto_target(&self, span: Span) -> Result { let goto = self .resolution diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index eb63c69..1199614 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -613,6 +613,87 @@ fn assert_private_slots(ir: &FrontendIr, guest_names: &[&str]) { assert_eq!(unique.len(), user.len(), "user slots alias: {user:?}"); } +fn repeat_flag_bindings(ir: &FrontendIr) -> Vec<(&str, LocalSlot)> { + ir.local_bindings + .iter() + .filter(|(name, _)| name.starts_with("$lua_repeat_again_")) + .map(|(name, slot)| (name.as_str(), *slot)) + .collect() +} + +fn assert_repeat_fors(ir: &FrontendIr, expected: usize) { + let flags = repeat_flag_bindings(ir); + assert_eq!( + flags.len(), + expected, + "one private flag per repeat, bindings={flags:?}" + ); + for (name, _) in &flags { + assert!(!is_lua_ident(name), "{name} is a guest identifier"); + } + let mut slots: Vec = flags.iter().map(|(_, slot)| *slot).collect(); + slots.sort_unstable(); + slots.dedup(); + assert_eq!(slots.len(), expected, "repeat flags alias: {flags:?}"); + let mut seen = 0; + walk_stmts(&ir.stmts, &mut |stmt| { + if let Stmt::For { + init, + condition, + post, + .. + } = stmt + { + seen += 1; + let Stmt::Let { + index, + expr: init_expr, + .. + } = init.as_ref() + else { + panic!("repeat init is not one flag let: {init:?}"); + }; + assert!( + matches!(init_expr, Expr::Bool(true)), + "repeat flag must start true so the body runs before until: {init_expr:?}" + ); + assert!( + flags.iter().any(|(_, slot)| slot == index), + "repeat flag {index:?} is not a private repeat slot: {flags:?}" + ); + assert!( + matches!(condition, Expr::Var(slot) if slot == index), + "repeat condition must be the flag, not a second until: {condition:?}" + ); + let Stmt::Assign { + index: assigned, + expr: post_expr, + .. + } = post.as_ref() + else { + panic!("repeat post is not the until store: {post:?}"); + }; + assert_eq!(assigned, index, "until must update the same repeat flag"); + assert!( + matches!( + post_expr, + Expr::Not(outer) + if matches!( + outer.as_ref(), + Expr::Not(inner) + if matches!( + inner.as_ref(), + Expr::Eq(_, rhs) if matches!(rhs.as_ref(), Expr::Bool(false)) + ) + ) + ), + "until must be stored once as not core_truthy: {post_expr:?}" + ); + } + }); + assert_eq!(seen, expected, "each repeat is one for, not a copied body"); +} + #[test] fn backward_goto_stops_after_three_trips() { // One trip is 11, two is 22, four is 44. An open loop exhausts fuel. @@ -1120,3 +1201,403 @@ fn oracle_harness_runs_the_fixture_once_under_joff() { assert_eq!(business_once.value, business_twice.value); assert_eq!(business_once.value, TRUTH_EXPECTED); } + +// 921: outer scoped stays 9, two rounds, continue skips the second observed write. +// The low digits are the scoped combination 21. 911 means until read the outer +// scoped. 922 means continue fell through. 221 means the inner scoped leaked. +// Fuel exhaustion means until was skipped or stayed false after round two. +const REPEAT_SHADOW_LOOP: &str = "\ +repeat\n\ + n = n + 1\n\ + local scoped = n\n\ + if n == 2 then\n\ + continue\n\ + end\n\ + observed = observed + 1\n\ +until scoped > 1\n\ +"; + +fn repeat_shadow_direct() -> String { + [ + "local n = 0\n", + "local observed = 0\n", + "local scoped = 9\n", + REPEAT_SHADOW_LOOP, + "return scoped * 100 + n * 10 + observed\n", + ] + .concat() +} + +fn repeat_shadow_dispatch() -> String { + [ + "local skipped = 0\n", + "local n = 0\n", + "local observed = 0\n", + "local scoped = 9\n", + "goto enter\n", + "skipped = 1\n", + "::enter::\n", + REPEAT_SHADOW_LOOP, + "return skipped * 1000 + scoped * 100 + n * 10 + observed\n", + ] + .concat() +} + +const REPEAT_COMBINATION: &str = "\ +local n = 0\n\ +local observed = 0\n\ +repeat\n\ + n = n + 1\n\ + local scoped = n\n\ + if n == 2 then\n\ + continue\n\ + end\n\ + observed = observed + 1\n\ +until scoped > 1\n\ +return n * 10 + observed\n\ +"; + +const REPEAT_UNTIL_ZERO: &str = "\ +local n = 0\n\ +repeat\n\ + n = n + 1\n\ +until 0\n\ +return n\n\ +"; + +const REPEAT_BREAK_FALSE: &str = "\ +local n = 0\n\ +local after = 0\n\ +repeat\n\ + n = n + 1\n\ + if true then\n\ + break\n\ + end\n\ + n = n + 50\n\ +until false\n\ +after = 1\n\ +return n * 10 + after\n\ +"; + +const REPEAT_BREAK_FALSE_DISPATCH: &str = "\ +local skipped = 0\n\ +local n = 0\n\ +local after = 0\n\ +goto enter\n\ +skipped = 1\n\ +::enter::\n\ +repeat\n\ + n = n + 1\n\ + if true then\n\ + break\n\ + end\n\ + n = n + 50\n\ +until false\n\ +after = 1\n\ +return skipped * 100 + n * 10 + after\n\ +"; + +const NESTED_REPEAT_BREAK_ELEVEN: &str = "\ +local n = 0\n\ +local inner = 0\n\ +repeat\n\ + n = n + 1\n\ + repeat\n\ + inner = inner + 1\n\ + break\n\ + until false\n\ +until n > 0\n\ +return n * 10 + inner\n\ +"; + +const NESTED_REPEAT_BREAK: &str = "\ +local outer = 0\n\ +local inner = 0\n\ +local after_inner = 0\n\ +local after = 0\n\ +repeat\n\ + outer = outer + 1\n\ + repeat\n\ + inner = inner + 1\n\ + break\n\ + until false\n\ + after_inner = 1\n\ + break\n\ +until false\n\ +after = 1\n\ +return outer * 1000 + inner * 100 + after_inner * 10 + after\n\ +"; + +const NESTED_REPEAT_BREAK_DISPATCH: &str = "\ +local skipped = 0\n\ +goto enter\n\ +skipped = 1\n\ +::enter::\n\ +local outer = 0\n\ +local inner = 0\n\ +local after_inner = 0\n\ +local after = 0\n\ +repeat\n\ + outer = outer + 1\n\ + repeat\n\ + inner = inner + 1\n\ + break\n\ + until false\n\ + after_inner = 1\n\ + break\n\ +until false\n\ +after = 1\n\ +return skipped * 10000 + outer * 1000 + inner * 100 + after_inner * 10 + after\n\ +"; + +const REPEAT_CONTINUE_PAIR: &str = "\ +local a = 0\n\ +local atails = 0\n\ +repeat\n\ + a = a + 1\n\ + if a == 2 then\n\ + continue\n\ + end\n\ + atails = atails + 1\n\ +until a > 1\n\ +local b = 0\n\ +local btails = 0\n\ +repeat\n\ + b = b + 1\n\ + if b == 1 then\n\ + continue\n\ + end\n\ + btails = btails + 1\n\ +until b > 2\n\ +return a * 1000 + atails * 100 + b * 10 + btails\n\ +"; + +const REPEAT_CONTINUE_PAIR_DISPATCH: &str = "\ +local skipped = 0\n\ +goto enter\n\ +skipped = 1\n\ +::enter::\n\ +local a = 0\n\ +local atails = 0\n\ +repeat\n\ + a = a + 1\n\ + if a == 2 then\n\ + continue\n\ + end\n\ + atails = atails + 1\n\ +until a > 1\n\ +local b = 0\n\ +local btails = 0\n\ +repeat\n\ + b = b + 1\n\ + if b == 1 then\n\ + continue\n\ + end\n\ + btails = btails + 1\n\ +until b > 2\n\ +return skipped * 10000 + a * 1000 + atails * 100 + b * 10 + btails\n\ +"; + +const NESTED_WHILE_IN_REPEAT: &str = "\ +local outer = 0\n\ +local inner = 0\n\ +local inner_tails = 0\n\ +local outer_tails = 0\n\ +local after = 0\n\ +repeat\n\ + outer = outer + 1\n\ + while inner < 2 do\n\ + inner = inner + 1\n\ + if inner == 1 then\n\ + continue\n\ + end\n\ + inner_tails = inner_tails + 1\n\ + end\n\ + if outer == 1 then\n\ + continue\n\ + end\n\ + outer_tails = outer_tails + 1\n\ +until outer > 1\n\ +after = 1\n\ +return after * 10000 + outer * 1000 + inner * 100 + inner_tails * 10 + outer_tails\n\ +"; + +const REPEAT_IN_WHILE: &str = "\ +local w = 0\n\ +local r = 0\n\ +local rtail = 0\n\ +while w < 1 do\n\ + w = w + 1\n\ + repeat\n\ + r = r + 1\n\ + if r == 1 then\n\ + continue\n\ + end\n\ + rtail = rtail + 1\n\ + until r > 1\n\ +end\n\ +return w * 100 + r * 10 + rtail\n\ +"; + +const REPEAT_SKIP_LOCAL: &str = "\ +repeat if true then continue end; local skipped = 1 until skipped == 1; return 0\n\ +"; + +#[test] +fn direct_repeat_until_reads_the_round_local_and_continue_skips_the_tail() { + let source = repeat_shadow_direct(); + let path = write_fixture("repeat_shadow", &source); + assert!(path.extension().is_some_and(|ext| ext == "lua")); + expect_number("repeat_shadow", &source, 921.0); + expect_number("repeat_combination", REPEAT_COMBINATION, 21.0); + let ir = lowered(&source); + assert!(slot_named(&ir, "$lua_dispatch_state").is_none()); + assert_eq!(source_while_count(&ir.stmts, None), 0); + assert_repeat_fors(&ir, 1); + assert_private_slots(&ir, &["n", "observed", "scoped"]); +} + +#[test] +fn same_repeat_block_runs_direct_and_after_an_outer_goto() { + let direct_source = repeat_shadow_direct(); + let dispatch_source = repeat_shadow_dispatch(); + assert!( + direct_source.contains(REPEAT_SHADOW_LOOP) && dispatch_source.contains(REPEAT_SHADOW_LOOP) + ); + expect_number("repeat_shadow_direct", &direct_source, 921.0); + expect_number("repeat_shadow_dispatch", &dispatch_source, 921.0); + let direct = lowered(&direct_source); + let dispatch = lowered(&dispatch_source); + assert!(slot_named(&direct, "$lua_dispatch_state").is_none()); + assert_repeat_fors(&direct, 1); + let state = slot_named(&dispatch, "$lua_dispatch_state").expect("dispatch state"); + assert!(!is_lua_ident("$lua_dispatch_state")); + assert_eq!(dispatch_while_count(&dispatch.stmts, state), 1); + assert_eq!(source_while_count(&dispatch.stmts, Some(state)), 0); + assert_repeat_fors(&dispatch, 1); + assert_private_slots(&dispatch, &["skipped", "n", "observed", "scoped", "enter"]); +} + +#[test] +fn until_zero_is_truthy_and_the_body_runs_once() { + expect_number("repeat_until_zero", REPEAT_UNTIL_ZERO, 1.0); + let ir = lowered(REPEAT_UNTIL_ZERO); + assert_repeat_fors(&ir, 1); + assert!(slot_named(&ir, "$lua_dispatch_state").is_none()); +} + +#[test] +fn repeat_break_skips_a_false_until_and_stays_inside_dispatch() { + // 11: one body, break, then the statement after the repeat. 10 means the + // break also skipped that statement. 61 means break did not fire. A + // dispatch break that leaves the state loop does not reach `after`. + expect_number("repeat_break_false", REPEAT_BREAK_FALSE, 11.0); + expect_number( + "repeat_break_false_dispatch", + REPEAT_BREAK_FALSE_DISPATCH, + 11.0, + ); + let direct = lowered(REPEAT_BREAK_FALSE); + let dispatch = lowered(REPEAT_BREAK_FALSE_DISPATCH); + assert_repeat_fors(&direct, 1); + assert_repeat_fors(&dispatch, 1); + let state = slot_named(&dispatch, "$lua_dispatch_state").expect("dispatch state"); + assert_eq!(dispatch_while_count(&dispatch.stmts, state), 1); +} + +#[test] +fn nested_repeat_break_stays_in_the_inner_loop() { + // 11: inner break then outer until. 1111: inner break still runs + // after_inner, then the outer break still runs after. 1101 means the + // inner break left the outer repeat. 1110 means the outer break left a + // dispatcher before `after`. + expect_number( + "nested_repeat_break_eleven", + NESTED_REPEAT_BREAK_ELEVEN, + 11.0, + ); + expect_number("nested_repeat_break", NESTED_REPEAT_BREAK, 1111.0); + expect_number( + "nested_repeat_break_dispatch", + NESTED_REPEAT_BREAK_DISPATCH, + 1111.0, + ); + let direct = lowered(NESTED_REPEAT_BREAK); + let dispatch = lowered(NESTED_REPEAT_BREAK_DISPATCH); + assert_repeat_fors(&direct, 2); + assert_repeat_fors(&dispatch, 2); + assert_eq!(source_while_count(&direct.stmts, None), 0); + let state = slot_named(&dispatch, "$lua_dispatch_state").expect("dispatch state"); + assert_eq!(dispatch_while_count(&dispatch.stmts, state), 1); + assert_eq!(source_while_count(&dispatch.stmts, Some(state)), 0); +} + +#[test] +fn repeat_continue_reaches_until_instead_of_skipping_or_exiting() { + // 2132: continue on a true until stops, continue on a false until loops. + // 3232 means continue skipped until and took an extra round. 2110 means + // continue exited before a false until. Dispatch adds no ten-thousands + // digit when the outer goto is taken. + expect_number("repeat_continue_pair", REPEAT_CONTINUE_PAIR, 2132.0); + expect_number( + "repeat_continue_pair_dispatch", + REPEAT_CONTINUE_PAIR_DISPATCH, + 2132.0, + ); + let direct = lowered(REPEAT_CONTINUE_PAIR); + let dispatch = lowered(REPEAT_CONTINUE_PAIR_DISPATCH); + assert_repeat_fors(&direct, 2); + assert_repeat_fors(&dispatch, 2); + assert!(slot_named(&direct, "$lua_dispatch_state").is_none()); + let state = slot_named(&dispatch, "$lua_dispatch_state").expect("dispatch state"); + assert_eq!(dispatch_while_count(&dispatch.stmts, state), 1); +} + +#[test] +fn nested_while_and_repeat_keep_transfers_on_the_nearest_loop() { + // 12211: inner while continue does not consume the outer repeat continue. + // 121: repeat continue inside while does not restart the while. + expect_number("nested_while_in_repeat", NESTED_WHILE_IN_REPEAT, 12211.0); + expect_number("repeat_in_while", REPEAT_IN_WHILE, 121.0); + let outer = lowered(NESTED_WHILE_IN_REPEAT); + let inner = lowered(REPEAT_IN_WHILE); + assert!(slot_named(&outer, "$lua_dispatch_state").is_none()); + assert!(slot_named(&inner, "$lua_dispatch_state").is_none()); + assert_repeat_fors(&outer, 1); + assert_repeat_fors(&inner, 1); + assert_eq!(source_while_count(&outer.stmts, None), 1); + assert_eq!(source_while_count(&inner.stmts, None), 1); +} + +#[test] +fn repeat_continue_past_a_local_is_rejected_at_load() { + let error = control::lower_source(REPEAT_SKIP_LOCAL).expect_err("resolver rejection"); + let text = error.to_string(); + assert!( + text.contains("jump into the scope of local skipped"), + "{text}" + ); + let path = write_fixture("repeat_skip_local", REPEAT_SKIP_LOCAL); + let compiled = compile_source_file_with_options(&path, candidate_options()); + assert!( + compiled.is_err(), + "continue past a local must not produce a program" + ); + let Ok(oracle) = std::env::var("LUAJIT_ORACLE") else { + eprintln!("LUAJIT_ORACLE is unset; repeat skip-local is not a differential result"); + return; + }; + let output = oracle_load_rejection(&oracle, &path); + let stderr = String::from_utf8_lossy(&output.stderr); + let code = output.status.code(); + assert_eq!( + code, + Some(2), + "text-mode load rejection is exit 2; a process failure has a different status={} stderr={stderr}", + output.status + ); + assert!( + stderr.contains("LOAD_REJECT"), + "load rejection marker missing; this is not a full-text match: {stderr}" + ); +} From 3fdbb1d60d7823a4eb71820cad146ce2d47f7571 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 23:26:56 +0800 Subject: [PATCH 018/225] fix(test): isolate frozen corpus scratch from diagnostic probes prepare_runnable_corpus deleted the shared scratch parent while a diagnostic probe was being written. Stage each corpus call in a newly created child and leave the diagnostics directory in place. --- tests/frozen_core_consumer.rs | 54 +++++++++++++++++++++++++++++++++-- 1 file changed, 52 insertions(+), 2 deletions(-) diff --git a/tests/frozen_core_consumer.rs b/tests/frozen_core_consumer.rs index 7a76fda..075028b 100644 --- a/tests/frozen_core_consumer.rs +++ b/tests/frozen_core_consumer.rs @@ -28,6 +28,22 @@ fn scratch_root() -> PathBuf { root.join("compat-frontends-corpus") } +fn exclusive_subroot(owner: &str) -> PathBuf { + let parent = scratch_root().join(owner); + fs::create_dir_all(&parent).expect("owned scratch parent"); + let mut index = 0u32; + loop { + let root = parent.join(index.to_string()); + match fs::create_dir(&root) { + Ok(()) => return root, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + index = index.checked_add(1).expect("owned scratch index"); + } + Err(error) => panic!("create owned scratch {owner}: {error}"), + } + } +} + fn rustscript_lock_source() -> String { format!("git+{RUSTSCRIPT_GIT}?rev={FROZEN_RUSTSCRIPT_REV}#{FROZEN_RUSTSCRIPT_REV}") } @@ -90,8 +106,8 @@ fn lock_package_source(block: &str) -> Option<&str> { } fn prepare_runnable_corpus() -> PathBuf { - let root = scratch_root(); - let _ = fs::remove_dir_all(&root); + // New child only. Do not remove the shared parent: diagnostic probes live beside it. + let root = exclusive_subroot("corpus"); let examples_dir = root.join("compat").join("examples"); fs::create_dir_all(&examples_dir).expect("corpus examples directory"); let stdlib = root @@ -362,6 +378,40 @@ fn lua_map_array_and_callable_semantics_survive_the_frozen_core() { assert_eq!(vm.stack(), &[Value::Int(10)]); } +#[test] +fn corpus_staging_preserves_diagnostic_probe_files() { + let diagnostics = scratch_root().join("diagnostics"); + fs::create_dir_all(&diagnostics).expect("diagnostics directory"); + let kept = diagnostics.join("kept.txt"); + fs::write(&kept, "diagnostic-owner\n").expect("write diagnostic marker"); + + let examples = prepare_runnable_corpus(); + + let python = diagnostics.join("probe.py"); + fs::write(&python, "print(1)\n").expect("write unsupported source"); + assert_eq!( + fs::read_to_string(&kept).expect("diagnostic marker survives corpus staging"), + "diagnostic-owner\n", + "corpus staging must keep the diagnostic owner directory" + ); + assert_eq!( + fs::read_to_string(&python).expect("diagnostic probe survives corpus staging"), + "print(1)\n" + ); + assert!( + examples.join("example.lua").is_file(), + "staged corpus must survive the diagnostic probe write" + ); + assert!( + !examples.starts_with(&diagnostics), + "corpus staging must not live inside the diagnostic owner" + ); + assert!( + !diagnostics.starts_with(&examples), + "diagnostic probes must not live inside the staged corpus" + ); +} + #[test] fn unsupported_language_and_invalid_sources_produce_portable_diagnostics() { let tmp = scratch_root().join("diagnostics"); From 8d41159503755b45274b07c77128917963eb40cd Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 05:32:57 +0800 Subject: [PATCH 019/225] feat(lua): add private table heap and explicit roots Keep the heap unwired from the Lua entry. Guest values are typed resource tokens, not GC roots and not bare integers. --- src/frontends/lua/heap.rs | 86 ++++ src/frontends/lua/heap/handle.rs | 53 +++ src/frontends/lua/heap/resource.rs | 44 ++ src/frontends/lua/heap/table.rs | 516 ++++++++++++++++++++++ tests/luajit_heap_runtime/mod.rs | 680 +++++++++++++++++++++++++++++ tests/luajit_heap_runtime_tests.rs | 220 ++++++++++ 6 files changed, 1599 insertions(+) create mode 100644 src/frontends/lua/heap.rs create mode 100644 src/frontends/lua/heap/handle.rs create mode 100644 src/frontends/lua/heap/resource.rs create mode 100644 src/frontends/lua/heap/table.rs create mode 100644 tests/luajit_heap_runtime/mod.rs create mode 100644 tests/luajit_heap_runtime_tests.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs new file mode 100644 index 0000000..d6ce831 --- /dev/null +++ b/src/frontends/lua/heap.rs @@ -0,0 +1,86 @@ +//! Private Lua table heap and explicit root frames. +//! +//! Not wired into `lua/mod.rs`, `lib.rs`, or the `.lua` entry. Tests compile +//! this file through `#[path]`. A future production wiring is a separate scope. +//! +//! Table nodes, reference edges, explicit root frames, and the mark/sweep scan +//! live in one `LuaHeap` stored in the current `ExecutionScope`. A published +//! guest value is a typed `resource` token in that same scope's +//! resource table. The token is not a second heap and is not a GC root: only +//! an explicit root frame keeps a node alive across `collect`. +//! +//! Borrowed from the ES5 heap at `3e348a010bc8d84baa5b7d1169a5f50aeb4e46ec` +//! `src/javascript/heap.rs`: slot plus generation handles, explicit root +//! frames, and non-moving mark/sweep. Not borrowed: numeric guest backing, +//! JavaScript classifications, swc, or guest IR. +//! +//! Later integration, not this kernel: LuaJIT `ordered.lua` plus the reverse +//! and skip-collection controls in +//! `/mnt/workspace/rustscript-lua/evidence/lua52-gc-arg-order/qualification.md`. +//! When `.lua` is connected, that stage consumes the sample. A collection +//! witness must be a helper that only returns a boolean; do not inline-read a +//! weak referent from the caller. This milestone has no weak references. + +#[path = "heap/handle.rs"] +mod handle; +#[path = "heap/resource.rs"] +mod resource; +#[path = "heap/table.rs"] +mod table; + +pub use handle::{HandleKind, TableRef}; +pub use resource::LuaTableResource; +pub use table::{CollectReport, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId}; + +use vm::resource::handle::DEFAULT_MAX_RESOURCES; +use vm::{HostContext, Value}; + +/// Installs the scope heap before the first use. A second install is refused +/// so a test cannot silently replace a live heap. +pub fn install(host: &mut HostContext, limits: HeapLimits) -> Result<(), HeapError> { + if host.scope_state::().is_some() { + return Err(HeapError::AlreadyInstalled); + } + host.scope_state_or_insert_with(|| LuaHeap::new(limits)) + .map_err(HeapError::from_scope)?; + Ok(()) +} + +/// Allocates a table and publishes its typed resource token. +/// +/// The resource table is checked before the node is reserved. A refused +/// publish therefore does not add a live node or a slot. If insertion fails +/// after a reserve, the node is rolled back before the error returns. +pub fn publish(host: &mut HostContext) -> Result { + if host.resource_count() >= DEFAULT_MAX_RESOURCES { + return Err(HeapError::PublishRejected); + } + let table = with_heap(host, LuaHeap::alloc)?; + let pushed = host.push_resource(LuaTableResource::new(table)); + let resource = match pushed { + Ok(resource) => resource, + Err(error) => { + let _ = with_heap(host, |heap| heap.rollback(table)); + return Err(HeapError::from_scope(error)); + } + }; + let raw = i64::try_from(resource.handle().raw()).map_err(|_| HeapError::CarrierOutOfRange)?; + Ok(Value::Int(raw)) +} + +/// Runs `body` against the scope heap, creating it with production limits if +/// this scope has not been installed yet. +pub fn with_heap( + host: &mut HostContext, + body: impl FnOnce(&mut LuaHeap) -> Result, +) -> Result { + let heap = host + .scope_state_or_insert_with(|| LuaHeap::new(HeapLimits::production())) + .map_err(HeapError::from_scope)?; + body(heap) +} + +/// Reads occupancy counters from the scope heap. +pub fn stats(host: &mut HostContext) -> Result { + with_heap(host, |heap| Ok(heap.stats())) +} diff --git a/src/frontends/lua/heap/handle.rs b/src/frontends/lua/heap/handle.rs new file mode 100644 index 0000000..cc54f2b --- /dev/null +++ b/src/frontends/lua/heap/handle.rs @@ -0,0 +1,53 @@ +//! Private table handle. It is not a VM `Value` and has no bare-integer ABI. + +/// Kind carried by a private handle. This milestone only allocates tables; +/// every operation still rejects a different kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HandleKind { + /// A table node. + Table, +} + +/// Domain-checked reference to one table node. +/// +/// `domain` ties the handle to the heap that allocated it. `slot` and +/// `generation` are checked against that heap on every use. A copied handle +/// is an alias only when those fields still match a live node. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TableRef { + domain: u64, + slot: u32, + generation: u32, + kind: HandleKind, +} + +impl TableRef { + pub(super) fn table(domain: u64, slot: u32, generation: u32) -> Self { + Self { + domain, + slot, + generation, + kind: HandleKind::Table, + } + } + + /// Heap domain that allocated this handle. + pub fn domain(self) -> u64 { + self.domain + } + + /// Stable slot index. Collection does not move it. + pub fn slot(self) -> u32 { + self.slot + } + + /// Generation observed when the handle was issued. + pub fn generation(self) -> u32 { + self.generation + } + + /// Handle kind. Table operations reject any other kind. + pub fn kind(self) -> HandleKind { + self.kind + } +} diff --git a/src/frontends/lua/heap/resource.rs b/src/frontends/lua/heap/resource.rs new file mode 100644 index 0000000..aeb3a85 --- /dev/null +++ b/src/frontends/lua/heap/resource.rs @@ -0,0 +1,44 @@ +//! Typed resource token for a private table handle. +//! +//! The token crosses the host boundary as `resource`. Its physical +//! VM carrier is the existing resource handle, validated by arena, type, and +//! key. It does not store table fields and is not a GC root. + +use vm::resource::HostResource; +use vm::host_extension::HostResourceType; +use vm::ResourceTypeKey; + +use super::handle::TableRef; + +/// Public object capability for one private table node. +#[derive(Debug)] +pub struct LuaTableResource { + table: TableRef, +} + +impl LuaTableResource { + pub(super) fn new(table: TableRef) -> Self { + Self { table } + } + + /// The private handle stored in this token. + pub fn table(&self) -> TableRef { + self.table + } + + /// Catalog key used by `typed_resource_with_key`. + pub fn key() -> ResourceTypeKey { + ResourceTypeKey::new(Self::KEY).expect("lua.table is a valid resource key") + } +} + +impl HostResource for LuaTableResource { + fn resource_type_key() -> Option { + Some(Self::key()) + } +} + +impl HostResourceType for LuaTableResource { + const KEY: &'static str = "lua.table"; + const DESCRIPTION: &'static str = "Lua table"; +} diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs new file mode 100644 index 0000000..7f4ded8 --- /dev/null +++ b/src/frontends/lua/heap/table.rs @@ -0,0 +1,516 @@ +//! Non-moving mark/sweep table storage, explicit root frames, and hard caps. + +use std::fmt; +use std::sync::atomic::{AtomicU64, Ordering}; + +use vm::HostContextError; + +use super::handle::{HandleKind, TableRef}; + +static NEXT_DOMAIN: AtomicU64 = AtomicU64::new(1); + +/// Hard caps. Edges and root slots are counted separately so fields cannot +/// grow past the edge cap by avoiding the node cap. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct HeapLimits { + /// Slot-vector length, including free and retired slots. + pub nodes: u32, + /// Simultaneous explicit root slots. + pub roots: u32, + /// Live reference-edge records. + pub edges: u32, + /// Highest generation a slot may hold. The next release retires it. + pub max_generation: u32, +} + +impl HeapLimits { + /// Defaults for an unwired production heap. Tests pass tighter limits. + pub const fn production() -> Self { + Self { + nodes: 4096, + roots: 256, + edges: 8192, + max_generation: u32::MAX, + } + } +} + +/// Why a heap operation was refused. Refusal does not mutate live occupancy +/// except `rollback`, which releases a node the caller already reserved. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HeapError { + /// Node slot storage is at its cap. + NodeCapacity, + /// Root slot storage is at its cap. + RootCapacity, + /// Edge storage is at its cap. + EdgeCapacity, + /// The slot cannot be reused without wrapping generation through zero. + GenerationExhausted, + /// The handle's slot or generation is not a live node in this heap. + StaleHandle, + /// The handle was allocated by a different heap domain. + WrongDomain, + /// The handle kind is not a table. + WrongKind, + /// `write_root` ran with no open frame. + NoRootFrame, + /// The frame id is not the current top frame, or its index is out of range. + StaleFrame, + /// The scope resource table cannot take another token. + PublishRejected, + /// The resource handle does not fit in a positive VM integer. + CarrierOutOfRange, + /// This scope already has a heap. + AlreadyInstalled, + /// Execution-scope or resource-table failure. The node was rolled back + /// when the failure happened after a reserve. + Scope(String), +} + +impl HeapError { + pub(super) fn from_scope(error: HostContextError) -> Self { + Self::Scope(error.to_string()) + } +} + +impl fmt::Display for HeapError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NodeCapacity => write!(formatter, "lua heap node capacity"), + Self::RootCapacity => write!(formatter, "lua heap root capacity"), + Self::EdgeCapacity => write!(formatter, "lua heap edge capacity"), + Self::GenerationExhausted => write!(formatter, "lua heap generation exhausted"), + Self::StaleHandle => write!(formatter, "stale lua table handle"), + Self::WrongDomain => write!(formatter, "lua table handle is from another heap"), + Self::WrongKind => write!(formatter, "lua handle is not a table"), + Self::NoRootFrame => write!(formatter, "no lua root frame"), + Self::StaleFrame => write!(formatter, "stale lua root frame"), + Self::PublishRejected => write!(formatter, "lua table publish rejected"), + Self::CarrierOutOfRange => write!(formatter, "lua resource carrier out of range"), + Self::AlreadyInstalled => write!(formatter, "lua heap already installed"), + Self::Scope(message) => write!(formatter, "lua heap scope error: {message}"), + } + } +} + +/// Occupancy and high-water storage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct HeapStats { + /// Nodes reachable as live slots. + pub live_nodes: u32, + /// Root slots currently holding a handle. + pub live_roots: u32, + /// Reference edges currently stored. + pub live_edges: u32, + /// Slot vector length. Free and retired slots still occupy it. + pub node_slots: u32, + /// Root vector length. + pub root_slots: u32, + /// Edge vector length. + pub edge_slots: u32, + /// Completed collections. + pub collections: u32, + /// Nodes marked by the latest collection. + pub last_marked: u32, + /// High-water slot storage. + pub peak_nodes: u32, + /// High-water root storage. + pub peak_roots: u32, + /// High-water edge storage. + pub peak_edges: u32, +} + +/// Result of one collection. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CollectReport { + /// Live nodes after the sweep. + pub live_nodes: u32, + /// Nodes marked from explicit roots, including nodes reached by edges. + pub marked_nodes: u32, + /// Root slots still holding a live handle. + pub live_roots: u32, +} + +/// Identity of one explicit root frame. Frames are a stack. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RootFrameId { + index: u32, + generation: u32, +} + +#[derive(Clone, Copy, Debug)] +enum SlotState { + Free, + Live { marked: bool }, + Retired, +} + +struct Slot { + generation: u32, + state: SlotState, +} + +struct Edge { + from: u32, + key: u32, + to_slot: u32, + to_generation: u32, +} + +struct Frame { + index: u32, + generation: u32, + start: u32, + width: u32, +} + +/// One scope's table nodes, edges, roots, and scan state. +pub struct LuaHeap { + domain: u64, + limits: HeapLimits, + slots: Vec, + free_list: Vec, + edges: Vec, + roots: Vec>, + frames: Vec, + next_frame_generation: u32, + collections: u32, + last_marked: u32, + peak_nodes: u32, + peak_roots: u32, + peak_edges: u32, +} + +impl LuaHeap { + /// Creates an empty heap. Slot zero is ordinary storage; handles start at + /// generation 1 so generation 0 never denotes a live node. + pub fn new(limits: HeapLimits) -> Self { + Self { + domain: NEXT_DOMAIN.fetch_add(1, Ordering::Relaxed), + limits, + slots: Vec::new(), + free_list: Vec::new(), + edges: Vec::new(), + roots: Vec::new(), + frames: Vec::new(), + next_frame_generation: 1, + collections: 0, + last_marked: 0, + peak_nodes: 0, + peak_roots: 0, + peak_edges: 0, + } + } + + /// Reserves a live, unrooted table. Failure leaves occupancy unchanged. + pub fn alloc(&mut self) -> Result { + if let Some(index) = self.free_list.pop() { + let slot = &mut self.slots[index as usize]; + if !matches!(slot.state, SlotState::Free) { + return Err(HeapError::StaleHandle); + } + slot.state = SlotState::Live { marked: false }; + return Ok(TableRef::table(self.domain, index, slot.generation)); + } + if self.slots.len() >= self.limits.nodes as usize { + return Err(HeapError::NodeCapacity); + } + if self.limits.max_generation == 0 { + return Err(HeapError::GenerationExhausted); + } + let index = u32::try_from(self.slots.len()).map_err(|_| HeapError::NodeCapacity)?; + self.slots.push(Slot { + generation: 1, + state: SlotState::Live { marked: false }, + }); + self.note_node_peak(); + Ok(TableRef::table(self.domain, index, 1)) + } + + /// Releases a reserved node. A stale or foreign handle is refused and the + /// heap is left unchanged. The slot stays in the vector so its generation + /// cannot be reissued as 1. + pub fn rollback(&mut self, handle: TableRef) -> Result<(), HeapError> { + self.require_live(handle)?; + self.clear_roots_to(handle); + self.remove_edges_touching(handle.slot()); + self.release_slot(handle.slot()); + Ok(()) + } + + /// Writes a reference edge. An existing key is overwritten and does not + /// consume another edge slot. A new key at the cap fails without insert. + pub fn set_edge(&mut self, from: TableRef, key: u32, to: TableRef) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_live(to)?; + if let Some(edge) = self + .edges + .iter_mut() + .find(|edge| edge.from == from.slot() && edge.key == key) + { + edge.to_slot = to.slot(); + edge.to_generation = to.generation(); + return Ok(()); + } + if self.edges.len() >= self.limits.edges as usize { + return Err(HeapError::EdgeCapacity); + } + self.edges.push(Edge { + from: from.slot(), + key, + to_slot: to.slot(), + to_generation: to.generation(), + }); + self.note_edge_peak(); + Ok(()) + } + + /// Reads a reference edge through either alias of `from`. + pub fn edge(&self, from: TableRef, key: u32) -> Result, HeapError> { + self.require_live(from)?; + Ok(self.edges.iter().find_map(|edge| { + if edge.from == from.slot() && edge.key == key { + Some(TableRef::table(self.domain, edge.to_slot, edge.to_generation)) + } else { + None + } + })) + } + + /// Opens a root frame of `width` slots. Failure does not grow root storage. + pub fn enter_roots(&mut self, width: u32) -> Result { + if width == 0 || self.next_frame_generation == 0 { + return Err(HeapError::StaleFrame); + } + let start = u32::try_from(self.roots.len()).map_err(|_| HeapError::RootCapacity)?; + let end = start.checked_add(width).ok_or(HeapError::RootCapacity)?; + if end > self.limits.roots { + return Err(HeapError::RootCapacity); + } + self.roots.resize(end as usize, None); + let generation = self.next_frame_generation; + self.next_frame_generation = self.next_frame_generation.saturating_add(1); + let index = u32::try_from(self.frames.len()).map_err(|_| HeapError::RootCapacity)?; + self.frames.push(Frame { + index, + generation, + start, + width, + }); + self.note_root_peak(); + Ok(RootFrameId { index, generation }) + } + + /// The open top frame, if any. + pub fn current_frame(&self) -> Option { + self.frames.last().map(|frame| RootFrameId { + index: frame.index, + generation: frame.generation, + }) + } + + /// Stores `handle` in an open frame. The frame does not have to be the + /// top frame; a stale id is refused. + pub fn write_root( + &mut self, + frame: RootFrameId, + slot: u32, + handle: TableRef, + ) -> Result<(), HeapError> { + self.require_live(handle)?; + let found = self.frame(frame)?; + if slot >= found.width { + return Err(HeapError::StaleFrame); + } + let index = found.start as usize + slot as usize; + self.roots[index] = Some(handle); + Ok(()) + } + + /// Drops the top frame. A frame that is not top is refused. + pub fn leave_roots(&mut self, frame: RootFrameId) -> Result<(), HeapError> { + let top = self.frames.last().ok_or(HeapError::NoRootFrame)?; + if top.index != frame.index || top.generation != frame.generation { + return Err(HeapError::StaleFrame); + } + let start = top.start as usize; + self.roots.truncate(start); + self.frames.pop(); + Ok(()) + } + + /// Non-moving mark from explicit roots, then sweep unmarked nodes. + /// Freed slots are reused with a bumped generation. A slot whose next + /// generation would pass `max_generation` is retired instead. + pub fn collect(&mut self) -> CollectReport { + for slot in &mut self.slots { + if let SlotState::Live { marked } = &mut slot.state { + *marked = false; + } + } + let mut work = Vec::new(); + let rooted: Vec = self.roots.iter().copied().flatten().collect(); + for handle in rooted { + if self.alive(handle) { + self.mark_slot(handle.slot(), &mut work); + } + } + while let Some(slot) = work.pop() { + let targets: Vec<(u32, u32)> = self + .edges + .iter() + .filter(|edge| edge.from == slot) + .map(|edge| (edge.to_slot, edge.to_generation)) + .collect(); + for (to_slot, to_generation) in targets { + if self.slot_live(to_slot, to_generation) { + self.mark_slot(to_slot, &mut work); + } + } + } + let swept: Vec = self + .slots + .iter() + .enumerate() + .filter_map(|(index, slot)| match slot.state { + SlotState::Live { marked: false } => Some(index as u32), + _ => None, + }) + .collect(); + let marked_nodes = self + .slots + .iter() + .filter(|slot| matches!(slot.state, SlotState::Live { marked: true })) + .count() as u32; + for index in swept { + self.remove_edges_touching(index); + self.release_slot(index); + } + self.clear_dead_roots(); + self.collections = self.collections.saturating_add(1); + self.last_marked = marked_nodes; + CollectReport { + live_nodes: self.live_nodes(), + marked_nodes, + live_roots: self.live_roots(), + } + } + + /// Reports whether `handle` names a live table in this heap. + pub fn alive(&self, handle: TableRef) -> bool { + self.require_live(handle).is_ok() + } + + /// Current occupancy. Peaks count storage, not only live objects. + pub fn stats(&self) -> HeapStats { + HeapStats { + live_nodes: self.live_nodes(), + live_roots: self.live_roots(), + live_edges: self.edges.len() as u32, + node_slots: self.slots.len() as u32, + root_slots: self.roots.len() as u32, + edge_slots: self.edges.len() as u32, + collections: self.collections, + last_marked: self.last_marked, + peak_nodes: self.peak_nodes, + peak_roots: self.peak_roots, + peak_edges: self.peak_edges, + } + } + + fn require_live(&self, handle: TableRef) -> Result<(), HeapError> { + if handle.domain() != self.domain { + return Err(HeapError::WrongDomain); + } + if handle.kind() != HandleKind::Table { + return Err(HeapError::WrongKind); + } + if self.slot_live(handle.slot(), handle.generation()) { + Ok(()) + } else { + Err(HeapError::StaleHandle) + } + } + + fn slot_live(&self, index: u32, generation: u32) -> bool { + self.slots.get(index as usize).is_some_and(|slot| { + slot.generation == generation && matches!(slot.state, SlotState::Live { .. }) + }) + } + + fn mark_slot(&mut self, index: u32, work: &mut Vec) { + if let SlotState::Live { marked } = &mut self.slots[index as usize].state { + if !*marked { + *marked = true; + work.push(index); + } + } + } + + fn release_slot(&mut self, index: u32) { + let slot = &mut self.slots[index as usize]; + if slot.generation >= self.limits.max_generation { + slot.state = SlotState::Retired; + return; + } + slot.generation = slot.generation.saturating_add(1); + slot.state = SlotState::Free; + self.free_list.push(index); + } + + fn remove_edges_touching(&mut self, slot: u32) { + self.edges + .retain(|edge| edge.from != slot && edge.to_slot != slot); + } + + fn clear_roots_to(&mut self, handle: TableRef) { + for root in &mut self.roots { + if *root == Some(handle) { + *root = None; + } + } + } + + fn clear_dead_roots(&mut self) { + let len = self.roots.len(); + for index in 0..len { + let Some(handle) = self.roots[index] else { + continue; + }; + if !self.alive(handle) { + self.roots[index] = None; + } + } + } + + fn frame(&self, id: RootFrameId) -> Result<&Frame, HeapError> { + self.frames + .iter() + .find(|frame| frame.index == id.index && frame.generation == id.generation) + .ok_or(HeapError::StaleFrame) + } + + fn live_nodes(&self) -> u32 { + self.slots + .iter() + .filter(|slot| matches!(slot.state, SlotState::Live { .. })) + .count() as u32 + } + + fn live_roots(&self) -> u32 { + self.roots.iter().filter(|root| root.is_some()).count() as u32 + } + + fn note_node_peak(&mut self) { + self.peak_nodes = self.peak_nodes.max(self.slots.len() as u32); + } + + fn note_root_peak(&mut self) { + self.peak_roots = self.peak_roots.max(self.roots.len() as u32); + } + + fn note_edge_peak(&mut self) { + self.peak_edges = self.peak_edges.max(self.edges.len() as u32); + } +} diff --git a/tests/luajit_heap_runtime/mod.rs b/tests/luajit_heap_runtime/mod.rs new file mode 100644 index 0000000..f457447 --- /dev/null +++ b/tests/luajit_heap_runtime/mod.rs @@ -0,0 +1,680 @@ +//! Test-owned SourcePlugin and typed host adapters. +//! +//! This is not a production plugin and is not wired to the `.lua` entry. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use vm::compiler::ir::{ResolvedHostCall, ResolvedHostParam}; +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, Expr, FrontendImportSyntax, FrontendIr, + HostApiBuilder, HostApiCatalog, HostFunctionRegistry, HostFunctionSchema, HostImportSchema, + HostOwnedFunction, HostParamPassing, HostParamSchema, HostStructField, + HostStructSchema, HostTypeSchema, LocalIrBuilder, LocalSlot, OwnedHostCall, ParseError, + ResourceTypeKey, ResourceTypeSchema, SourceFlavor, SourcePlugin, Stmt, TypeSchema, Value, + VmError, VmStatus, +}; + +use super::heap::{self, HeapLimits, LuaTableResource, TableRef}; + +static BODY_ENTRIES: AtomicU64 = AtomicU64::new(0); +static ALIVE_ENTRIES: AtomicU64 = AtomicU64::new(0); +static FORGED_SLOT: AtomicU64 = AtomicU64::new(0); +static FORGED_GENERATION: AtomicU64 = AtomicU64::new(0); + +pub fn body_entries() -> u64 { + BODY_ENTRIES.load(Ordering::SeqCst) +} + +pub fn alive_entries() -> u64 { + ALIVE_ENTRIES.load(Ordering::SeqCst) +} + +#[derive(Clone, Copy, Debug)] +pub enum Probe { + Transfer, + Publish, + Alias, + RejectInt, + RejectForeign { raw: i64 }, + Expired, + NamedCarrier, + NestedRooted, + NestedUnrooted, +} + +#[derive(Clone, Debug)] +pub struct ProbeResult { + pub stack: Vec, + pub body_entries: u64, + pub published_raw: Option, + pub forged_slot: Option, + pub forged_generation: Option, +} + +pub struct PublishStats { + pub before_live: u32, + pub after_live: u32, + pub before_slots: u32, + pub after_slots: u32, + pub publish_failed: bool, +} + +struct ProbePlugin; + +impl SourcePlugin for ProbePlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &["lua"] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + build_ir(source.trim()) + } +} + +pub fn run_probe(probe: Probe) -> Result { + let catalog = catalog(); + let source = probe_source(probe); + let compiled = vm::compile_source_with_flavor_and_options( + &source, + SourceFlavor::Lua, + CompileSourceFileOptions::new() + .with_source_plugin(&ProbePlugin) + .with_host_api_catalog(std::sync::Arc::new(catalog.clone())), + ) + .map_err(|error| error.to_string())?; + let mut registry = HostFunctionRegistry::empty(); + register_hosts(&mut registry, &catalog).map_err(|error| error.to_string())?; + let mut vm = compiled.into_vm().map_err(|error| error.to_string())?; + registry + .bind_vm_cached(&mut vm) + .map_err(|error| error.to_string())?; + let before = body_entries(); + let status = vm.run().map_err(|error| error.to_string())?; + if status != VmStatus::Halted { + return Err(format!("probe did not halt: {status:?}")); + } + let stack = vm.stack().to_vec(); + let published_raw = stack.iter().find_map(|value| match value { + Value::Int(raw) if *raw > 1 => Some(*raw), + _ => None, + }); + Ok(ProbeResult { + stack, + body_entries: body_entries().saturating_sub(before), + published_raw, + forged_slot: non_zero(FORGED_SLOT.load(Ordering::SeqCst)), + forged_generation: non_zero(FORGED_GENERATION.load(Ordering::SeqCst)), + }) +} + +pub fn fill_resource_table_then_fail_publish() -> PublishStats { + let catalog = catalog(); + let compiled = vm::compile_source_with_flavor_and_options( + "idle", + SourceFlavor::Lua, + CompileSourceFileOptions::new().with_source_plugin(&ProbePlugin), + ) + .expect("idle program"); + let mut vm = compiled.into_vm().expect("vm"); + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 2048, + roots: 4, + edges: 4, + max_generation: 8, + }, + ) + .expect("install"); + for _ in 0..vm::resource::handle::DEFAULT_MAX_RESOURCES { + heap::publish(&mut host).expect("fill resource table"); + } + let before = heap::stats(&mut host).expect("stats"); + let failed = heap::publish(&mut host).is_err(); + let after = heap::stats(&mut host).expect("stats after"); + let _ = catalog; + PublishStats { + before_live: before.live_nodes, + after_live: after.live_nodes, + before_slots: before.node_slots, + after_slots: after.node_slots, + publish_failed: failed, + } +} + +fn non_zero(value: u64) -> Option { + (value != 0).then_some(value) +} + +fn probe_source(probe: Probe) -> String { + match probe { + Probe::Transfer => "transfer".to_string(), + Probe::Publish => "publish".to_string(), + Probe::Alias => "alias".to_string(), + Probe::RejectInt => "reject-int".to_string(), + Probe::RejectForeign { raw } => format!("reject-foreign:{raw}"), + Probe::Expired => "expired".to_string(), + Probe::NamedCarrier => "named".to_string(), + Probe::NestedRooted => "nested-rooted".to_string(), + Probe::NestedUnrooted => "nested-unrooted".to_string(), + } +} + +fn catalog() -> HostApiCatalog { + let key = LuaTableResource::key(); + let named = named_schema(); + let mut builder = HostApiBuilder::new(); + builder.resource(ResourceTypeSchema::new(key.clone(), "Lua table")); + builder.named_struct(named.clone()); + builder.function(func( + "lua_heap_publish", + vec![], + HostTypeSchema::Resource(key.clone()), + )); + builder.function(func( + "lua_heap_alive", + vec![borrow("table", &key)], + HostTypeSchema::Int, + )); + builder.function(func( + "lua_heap_observe", + vec![ + borrow("table", &key), + HostParamSchema::value("marker", HostTypeSchema::Int), + ], + HostTypeSchema::Int, + )); + builder.function(func( + "lua_heap_set_edge", + vec![ + borrow("from", &key), + HostParamSchema::value("key", HostTypeSchema::Int), + borrow("to", &key), + ], + HostTypeSchema::Int, + )); + builder.function(func( + "lua_heap_edge_is", + vec![ + borrow("from", &key), + HostParamSchema::value("key", HostTypeSchema::Int), + borrow("to", &key), + ], + HostTypeSchema::Int, + )); + builder.function(func( + "lua_heap_enter", + vec![HostParamSchema::value("width", HostTypeSchema::Int)], + HostTypeSchema::Int, + )); + builder.function(func( + "lua_heap_root", + vec![ + HostParamSchema::value("slot", HostTypeSchema::Int), + borrow("table", &key), + ], + HostTypeSchema::Resource(key.clone()), + )); + builder.function(func( + "lua_heap_collect", + vec![], + HostTypeSchema::Int, + )); + builder.function(func( + "lua_heap_close", + vec![HostParamSchema::with_passing( + "table", + HostTypeSchema::Resource(key), + HostParamPassing::TakeOwned, + )], + HostTypeSchema::Int, + )); + builder.function(func( + "lua_heap_forge_named", + vec![], + named.as_type(), + )); + builder.function(func( + "lua_heap_accept_named", + vec![HostParamSchema::value("record", named.as_type())], + HostTypeSchema::Int, + )); + builder.build().expect("catalog") +} + +fn named_schema() -> HostStructSchema { + HostStructSchema::new( + "lua_heap_private_carrier", + vec![ + HostStructField::new("slot", HostTypeSchema::Int), + HostStructField::new("generation", HostTypeSchema::Int), + ], + ) +} + +fn borrow(name: &str, key: &ResourceTypeKey) -> HostParamSchema { + HostParamSchema::with_passing( + name, + HostTypeSchema::Resource(key.clone()), + HostParamPassing::Borrow, + ) +} + +fn func(name: &str, params: Vec, ret: HostTypeSchema) -> HostFunctionSchema { + HostFunctionSchema::with_return(name, params, ret) +} + +fn register_hosts(registry: &mut HostFunctionRegistry, catalog: &HostApiCatalog) -> Result<(), VmError> { + register(registry, catalog, "lua_heap_publish", 0, |_| Box::new(Publish))?; + register(registry, catalog, "lua_heap_alive", 1, |_| Box::new(Alive))?; + register(registry, catalog, "lua_heap_observe", 2, |_| Box::new(Observe))?; + register(registry, catalog, "lua_heap_set_edge", 3, |_| Box::new(SetEdge))?; + register(registry, catalog, "lua_heap_edge_is", 3, |_| Box::new(EdgeIs))?; + register(registry, catalog, "lua_heap_enter", 1, |_| Box::new(Enter))?; + register(registry, catalog, "lua_heap_root", 2, |_| Box::new(Root))?; + register(registry, catalog, "lua_heap_collect", 0, |_| Box::new(Collect))?; + register(registry, catalog, "lua_heap_close", 1, |_| Box::new(Close))?; + register(registry, catalog, "lua_heap_forge_named", 0, |_| Box::new(ForgeNamed))?; + register(registry, catalog, "lua_heap_accept_named", 1, |_| Box::new(AcceptNamed))?; + Ok(()) +} + +fn register( + registry: &mut HostFunctionRegistry, + catalog: &HostApiCatalog, + name: &str, + arity: u8, + factory: impl Fn(vm::OwnedHostContext<'_>) -> Box + Send + Sync + 'static, +) -> Result<(), VmError> { + let function = catalog.function(name).expect("catalog function"); + let schema = HostImportSchema::from_function(catalog, function); + registry.register_exact_owned(name, arity, schema, factory)?; + Ok(()) +} + +struct Publish; +struct Alive; +struct Observe; +struct SetEdge; +struct EdgeIs; +struct Enter; +struct Root; +struct Collect; +struct Close; +struct ForgeNamed; +struct AcceptNamed; + +impl HostOwnedFunction for Publish { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let mut host = call.vm().host_context(); + let value = heap::publish(&mut host).map_err(host_error)?; + Ok(CallOutcome::Return(CallReturn::one(value))) + } +} + +impl HostOwnedFunction for Alive { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + note_alive(); + let table = recover(call, 0)?; + let mut host = call.vm().host_context(); + let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).map_err(host_error)?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from(alive))))) + } +} + +impl HostOwnedFunction for Observe { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + note_alive(); + let table = recover(call, 0)?; + let _marker = int_arg(&call, 1)?; + let mut host = call.vm().host_context(); + let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).map_err(host_error)?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from( + alive, + ))))) + } +} + +impl HostOwnedFunction for SetEdge { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let from = recover(call, 0)?; + let key = int_arg(&call, 1)?; + let to = recover(call, 2)?; + let mut host = call.vm().host_context(); + heap::with_heap(&mut host, |heap| heap.set_edge(from, key, to)).map_err(host_error)?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int(1)))) + } +} + +impl HostOwnedFunction for EdgeIs { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let from = recover(call, 0)?; + let key = int_arg(&call, 1)?; + let to = recover(call, 2)?; + let mut host = call.vm().host_context(); + let same = heap::with_heap(&mut host, |heap| Ok(heap.edge(from, key) == Ok(Some(to)))) + .map_err(host_error)?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from(same))))) + } +} + +impl HostOwnedFunction for Enter { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let width = int_arg(&call, 0)?; + let mut host = call.vm().host_context(); + heap::with_heap(&mut host, |heap| heap.enter_roots(width)).map_err(host_error)?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int(1)))) + } +} + +impl HostOwnedFunction for Root { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let slot = int_arg(&call, 0)?; + let table = recover(call, 1)?; + let returned = call.args()[1].clone(); + let mut host = call.vm().host_context(); + heap::with_heap(&mut host, |heap| { + let frame = heap.current_frame().ok_or(heap::HeapError::NoRootFrame)?; + heap.write_root(frame, slot, table) + }) + .map_err(host_error)?; + Ok(CallOutcome::Return(CallReturn::one(returned))) + } +} + +impl HostOwnedFunction for Collect { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let mut host = call.vm().host_context(); + let marked = heap::with_heap(&mut host, |heap| Ok(heap.collect())).map_err(host_error)?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int( + i64::from(marked.live_nodes), + )))) + } +} + +impl HostOwnedFunction for Close { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let _taken = call.take_arg(0)?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int(1)))) + } +} + +impl HostOwnedFunction for ForgeNamed { + fn call(&mut self, _call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let mut map = vm::bytecode::VmMap::new(); + map.insert(Value::string("slot"), Value::Int(7)); + map.insert(Value::string("generation"), Value::Int(9)); + Ok(CallOutcome::Return(CallReturn::one(Value::Map( + std::sync::Arc::new(map), + )))) + } +} + +impl HostOwnedFunction for AcceptNamed { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + note_body(); + let Value::Map(map) = &call.args()[0] else { + return Err(VmError::HostError("named carrier was not a map".to_string())); + }; + let slot = map_int(map, "slot")?; + let generation = map_int(map, "generation")?; + FORGED_SLOT.store(slot as u64, Ordering::SeqCst); + FORGED_GENERATION.store(generation as u64, Ordering::SeqCst); + Ok(CallOutcome::Return(CallReturn::one(Value::Int(1)))) + } +} + +fn map_int(map: &vm::bytecode::VmMap, key: &str) -> Result { + match map.get(&Value::string(key)) { + Some(Value::Int(value)) => Ok(*value), + _ => Err(VmError::HostError(format!("missing named field {key}"))), + } +} + +fn recover(call: &mut OwnedHostCall<'_>, index: usize) -> Result { + let value = call.args().get(index).cloned().ok_or_else(|| { + VmError::HostError(format!("missing argument {index}")) + })?; + let Value::Int(raw) = value else { + return Err(VmError::HostError( + "table carrier is not a resource handle".to_string(), + )); + }; + let raw = u64::try_from(raw).map_err(|_| { + VmError::HostError("table carrier is not a positive resource handle".to_string()) + })?; + let handle = vm::ResourceHandle::from_raw(raw) + .map_err(|error| VmError::HostError(error.to_string()))?; + let host = call.vm().host_context(); + let token = host + .typed_resource_with_key::(handle, &LuaTableResource::key()) + .map_err(host_error)?; + Ok(host.resource(&token).map_err(host_error)?.get().table()) +} + +fn int_arg(call: &OwnedHostCall<'_>, index: usize) -> Result { + match call.args().get(index) { + Some(Value::Int(value)) if *value >= 0 && *value <= i64::from(u32::MAX) => { + Ok(*value as u32) + } + _ => Err(VmError::HostError(format!("argument {index} is not a field index"))), + } +} + +fn note_body() { + BODY_ENTRIES.fetch_add(1, Ordering::SeqCst); +} + +fn note_alive() { + ALIVE_ENTRIES.fetch_add(1, Ordering::SeqCst); +} + +fn host_error(error: impl ToString) -> VmError { + VmError::HostError(error.to_string()) +} + +fn build_ir(source: &str) -> Result { + if source == "idle" { + return Ok(LocalIrBuilder::new().finish(Vec::new())); + } + let catalog = catalog(); + let mut builder = LocalIrBuilder::new(); + let mut next_index = 0u16; + let mut indices = std::collections::HashMap::new(); + for (name, arity) in hosts_for(source) { + builder.declare_function(name, Some(*arity))?; + indices.insert(*name, next_index); + next_index += 1; + } + let call = |name: &str, args: Vec| { + let index = indices[name]; + Expr::Call( + index, + Vec::new(), + args, + Some(Box::new(resolution(&catalog, name))), + None, + ) + }; + let local = |builder: &mut LocalIrBuilder, name: &str| builder.alloc_local_named(name); + let bind = |slot: LocalSlot, expr: Expr| Stmt::Let { + index: slot, + declared_schema: None, + expr, + line: 1, + }; + let mut stmts = Vec::new(); + match source { + "publish" => stmts.push(Stmt::Expr { + expr: call("lua_heap_publish", Vec::new()), + line: 1, + }), + "transfer" => { + let table = local(&mut builder, "table")?; + stmts.push(bind(table, call("lua_heap_publish", Vec::new()))); + stmts.push(Stmt::Expr { + expr: call("lua_heap_alive", vec![Expr::Var(table)]), + line: 1, + }); + } + "alias" => { + let left = local(&mut builder, "left")?; + let right = local(&mut builder, "right")?; + let wrote = local(&mut builder, "wrote")?; + stmts.push(bind(left, call("lua_heap_publish", Vec::new()))); + stmts.push(bind(right, call("lua_heap_publish", Vec::new()))); + stmts.push(bind( + wrote, + call( + "lua_heap_set_edge", + vec![Expr::Var(left), Expr::Int(1), Expr::Var(right)], + ), + )); + stmts.push(Stmt::Expr { + expr: call( + "lua_heap_edge_is", + vec![Expr::Var(left), Expr::Int(1), Expr::Var(right)], + ), + line: 1, + }); + } + "reject-int" => stmts.push(Stmt::Expr { + expr: call("lua_heap_alive", vec![Expr::Int(1)]), + line: 1, + }), + source if source.starts_with("reject-foreign:") => { + let raw = source["reject-foreign:".len()..] + .parse::() + .map_err(|_| ParseError::new("foreign handle literal"))?; + stmts.push(Stmt::Expr { + expr: call("lua_heap_alive", vec![Expr::Int(raw)]), + line: 1, + }); + } + "expired" => { + let table = local(&mut builder, "table")?; + let closed = local(&mut builder, "closed")?; + stmts.push(bind(table, call("lua_heap_publish", Vec::new()))); + stmts.push(bind(closed, call("lua_heap_close", vec![Expr::Var(table)]))); + stmts.push(Stmt::Expr { + expr: call("lua_heap_alive", vec![Expr::Var(table)]), + line: 1, + }); + } + "named" => { + FORGED_SLOT.store(0, Ordering::SeqCst); + FORGED_GENERATION.store(0, Ordering::SeqCst); + let record = local(&mut builder, "record")?; + stmts.push(bind(record, call("lua_heap_forge_named", Vec::new()))); + stmts.push(Stmt::Expr { + expr: call("lua_heap_accept_named", vec![Expr::Var(record)]), + line: 1, + }); + } + "nested-rooted" | "nested-unrooted" => { + let entered = local(&mut builder, "entered")?; + let table = local(&mut builder, "table")?; + stmts.push(bind(entered, call("lua_heap_enter", vec![Expr::Int(1)]))); + stmts.push(bind(table, call("lua_heap_publish", Vec::new()))); + let first = if source == "nested-rooted" { + call("lua_heap_root", vec![Expr::Int(0), Expr::Var(table)]) + } else { + Expr::Var(table) + }; + stmts.push(Stmt::Expr { + expr: call( + "lua_heap_observe", + vec![first, call("lua_heap_collect", Vec::new())], + ), + line: 1, + }); + } + _ => return Err(ParseError::new(format!("unknown heap probe {source}"))), + } + Ok(builder.finish(stmts)) +} + +fn hosts_for(source: &str) -> &'static [(&'static str, u8)] { + match source { + "publish" => &[("lua_heap_publish", 0)], + "transfer" => &[("lua_heap_publish", 0), ("lua_heap_alive", 1)], + "alias" => &[ + ("lua_heap_publish", 0), + ("lua_heap_set_edge", 3), + ("lua_heap_edge_is", 3), + ], + "reject-int" => &[("lua_heap_alive", 1)], + source if source.starts_with("reject-foreign:") => &[("lua_heap_alive", 1)], + "expired" => &[ + ("lua_heap_publish", 0), + ("lua_heap_close", 1), + ("lua_heap_alive", 1), + ], + "named" => &[ + ("lua_heap_forge_named", 0), + ("lua_heap_accept_named", 1), + ], + "nested-rooted" => &[ + ("lua_heap_enter", 1), + ("lua_heap_publish", 0), + ("lua_heap_root", 2), + ("lua_heap_observe", 2), + ("lua_heap_collect", 0), + ], + "nested-unrooted" => &[ + ("lua_heap_enter", 1), + ("lua_heap_publish", 0), + ("lua_heap_observe", 2), + ("lua_heap_collect", 0), + ], + _ => &[], + } +} + +fn resolution(catalog: &HostApiCatalog, name: &str) -> ResolvedHostCall { + let function = catalog.function(name).expect("function"); + ResolvedHostCall { + name: function.name.clone(), + params: function + .params + .iter() + .map(|param| ResolvedHostParam { + name: param.name.clone(), + schema: type_schema(¶m.ty), + }) + .collect(), + return_type: type_schema(&function.return_type), + passing: function.params.iter().map(|param| param.passing).collect(), + fingerprint: catalog.fingerprint(), + host_params: function.params.iter().map(|param| param.ty.clone()).collect(), + host_return_type: function.return_type.clone(), + } +} + +fn type_schema(schema: &HostTypeSchema) -> TypeSchema { + match schema { + HostTypeSchema::Int => TypeSchema::Int, + HostTypeSchema::Resource(key) => TypeSchema::Resource(key.clone()), + HostTypeSchema::Named { name, .. } => TypeSchema::Named(name.clone(), Vec::new()), + _ => TypeSchema::Unknown, + } +} diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs new file mode 100644 index 0000000..0d826bf --- /dev/null +++ b/tests/luajit_heap_runtime_tests.rs @@ -0,0 +1,220 @@ +//! Acceptance for the unwired Lua private table heap. +//! +//! The production files are compiled through `#[path]` and are not registered +//! from `lua/mod.rs`, `lib.rs`, or the `.lua` entry. Weak tables and the +//! LuaJIT `ordered.lua` sample stay in the later integration stage. + +#[path = "../src/frontends/lua/heap.rs"] +mod heap; + +#[path = "luajit_heap_runtime/mod.rs"] +mod support; + +use heap::{CollectReport, HandleKind, HeapLimits, LuaHeap, RootFrameId}; +use support::{Probe, alive_entries, body_entries, run_probe}; +use vm::Value; + +fn tight_limits() -> HeapLimits { + HeapLimits { + nodes: 4, + roots: 2, + edges: 2, + max_generation: 4, + } +} + +#[test] +fn alias_write_collect_reuse_and_hard_caps_stay_inside_one_heap() { + let mut heap = LuaHeap::new(tight_limits()); + let left = heap.alloc().expect("first table"); + assert_eq!(left.kind(), HandleKind::Table); + let right = heap.alloc().expect("second table"); + let alias = left; + heap.set_edge(left, 1, right).expect("edge"); + assert_eq!(heap.edge(alias, 1).expect("read alias"), Some(right)); + assert!(heap.alive(left) && heap.alive(right)); + + let unrooted = heap.collect(); + assert_eq!(unrooted.live_nodes, 0, "an edge is not a root"); + assert!(!heap.alive(left)); + assert!(!heap.alive(right)); + assert!(heap.edge(left, 1).is_err(), "a stale source is not a readable edge"); + + let reused = heap.alloc().expect("reuse freed slot"); + assert_eq!(reused.slot(), right.slot()); + assert_ne!(reused.generation(), right.generation()); + assert!(!heap.alive(right), "stale generation stays dead"); + assert_eq!(heap.stats().node_slots, 2, "reuse must not grow slot storage"); + + let dropped = heap.alloc().expect("second reuse"); + let frame: RootFrameId = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, reused).expect("root reused"); + heap.set_edge(reused, 1, dropped).expect("reachable edge"); + let kept: CollectReport = heap.collect(); + assert_eq!(kept.live_nodes, 2, "a rooted source keeps its target"); + assert!(heap.alive(reused)); + assert!(heap.alive(dropped)); + + heap.leave_roots(frame).expect("leave"); + let after_leave = heap.collect(); + assert_eq!(after_leave.live_nodes, 0); + assert_eq!(heap.stats().live_roots, 0); +} + +#[test] +fn failed_alloc_and_rollback_do_not_grow_live_storage() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 1, + roots: 1, + edges: 1, + max_generation: 2, + }); + let first = heap.alloc().expect("only slot"); + let before = heap.stats(); + assert!(heap.alloc().is_err(), "node cap"); + assert_eq!(heap.stats(), before); + + heap.rollback(first).expect("rollback unpublished"); + assert!(!heap.alive(first)); + assert_eq!(heap.stats().live_nodes, 0); + assert_eq!( + heap.stats().node_slots, 1, + "the slot stays for reuse, but it is not a live node" + ); + let again = heap.alloc().expect("reuse after rollback"); + assert_ne!(again.generation(), first.generation()); + assert!(!heap.alive(first)); + assert!(heap.set_edge(again, 1, again).is_ok()); + let edges = heap.stats().edge_slots; + assert!(heap.set_edge(again, 2, again).is_err(), "edge cap"); + assert_eq!(heap.stats().live_edges, 1); + assert_eq!(heap.stats().edge_slots, edges); + + let root = heap.enter_roots(1).expect("one root"); + assert!(heap.enter_roots(1).is_err(), "root cap"); + assert_eq!(heap.stats().root_slots, 1); + heap.leave_roots(root).expect("leave"); +} + +#[test] +fn generation_exhaustion_retires_the_slot_instead_of_wrapping() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 1, + roots: 1, + edges: 1, + max_generation: 1, + }); + let once = heap.alloc().expect("generation 1"); + heap.rollback(once).expect("free"); + assert!(heap.alloc().is_err(), "retired slot is not reused"); + assert!(!heap.alive(once)); + assert_eq!(heap.stats().live_nodes, 0); + assert_eq!(heap.stats().node_slots, 1, "retired storage remains, but is not live"); +} + +#[test] +fn cyclic_create_and_collect_tracks_live_nodes_and_roots() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 8, + roots: 4, + edges: 8, + max_generation: 8, + }); + for round in 0..3 { + let frame = heap.enter_roots(1).expect("frame"); + let kept = heap.alloc().expect("kept"); + let linked = heap.alloc().expect("linked"); + heap.set_edge(kept, 1, linked).expect("forward"); + heap.set_edge(linked, 1, kept).expect("back edge"); + heap.write_root(frame, 0, kept).expect("root"); + let orphan = heap.alloc().expect("orphan"); + let orphan_link = heap.alloc().expect("orphan link"); + heap.set_edge(orphan, 1, orphan_link).expect("orphan forward"); + heap.set_edge(orphan_link, 1, orphan).expect("orphan back"); + let marked = heap.collect(); + assert_eq!( + marked.live_nodes, 2, + "round {round}: rooted cycle stays, orphan cycle is collected" + ); + assert_eq!(heap.stats().live_roots, 1); + assert!(heap.alive(kept) && heap.alive(linked)); + assert!(!heap.alive(orphan) && !heap.alive(orphan_link)); + heap.leave_roots(frame).expect("leave"); + assert_eq!(heap.collect().live_nodes, 0); + assert_eq!(heap.stats().live_roots, 0); + } + assert_eq!(heap.stats().node_slots, 4, "later rounds reuse the first four slots"); + assert!(heap.stats().peak_roots <= 4); +} + +#[test] +fn a_handle_from_another_heap_is_rejected() { + let mut left = LuaHeap::new(tight_limits()); + let mut right = LuaHeap::new(tight_limits()); + let handle = left.alloc().expect("left table"); + assert!(!right.alive(handle)); + assert!(right.set_edge(handle, 1, handle).is_err()); +} + +#[test] +fn typed_resource_boundary_rejects_int_foreign_and_expired_values() { + let transfer = run_probe(Probe::Transfer).expect("transfer"); + assert_eq!(transfer.stack, vec![Value::Int(1)]); + assert!(transfer.body_entries > 0, "typed host body ran for a published table"); + + let alias = run_probe(Probe::Alias).expect("alias"); + assert_eq!(alias.stack, vec![Value::Int(1)], "same table write is visible through the other handle"); + + let before_int = body_entries(); + let rejected_int = run_probe(Probe::RejectInt); + assert!(rejected_int.is_err(), "ordinary int is not a table: {rejected_int:?}"); + assert_eq!(body_entries(), before_int, "int rejection happens before the host body"); + + let published = run_probe(Probe::Publish).expect("publish handle"); + assert_eq!(published.published_raw, published.stack.first().and_then(|value| match value { + Value::Int(raw) => Some(*raw), + _ => None, + })); + let raw = match published.stack.as_slice() { + [Value::Int(raw)] => *raw, + other => panic!("publish did not return one handle: {other:?}"), + }; + let before_foreign = alive_entries(); + let foreign = run_probe(Probe::RejectForeign { raw }); + assert!(foreign.is_err(), "cross-vm handle is rejected: {foreign:?}"); + assert_eq!(alive_entries(), before_foreign, "foreign rejection is before the host body"); + + let before_expired = alive_entries(); + let expired = run_probe(Probe::Expired); + assert!(expired.is_err(), "expired handle is rejected: {expired:?}"); + assert_eq!( + alive_entries(), + before_expired, + "close runs; the later alive call must not" + ); + + let named = run_probe(Probe::NamedCarrier).expect("named carrier"); + assert_eq!(named.stack, vec![Value::Int(1)]); + assert_eq!(named.forged_slot, Some(7)); + assert_eq!(named.forged_generation, Some(9)); + assert!( + rejected_int.is_err() && named.stack == vec![Value::Int(1)], + "a named record of copyable ints is not provenance; typed resource is the carrier" + ); +} + +#[test] +fn nested_argument_root_keeps_the_first_argument_across_collect() { + let rooted = run_probe(Probe::NestedRooted).expect("rooted nest"); + assert_eq!(rooted.stack, vec![Value::Int(1)]); + let unrooted = run_probe(Probe::NestedUnrooted).expect("unrooted nest"); + assert_eq!(unrooted.stack, vec![Value::Int(0)]); +} + +#[test] +fn publish_failure_against_the_resource_table_rolls_back_the_node() { + let stats = support::fill_resource_table_then_fail_publish(); + assert_eq!(stats.before_live, stats.after_live); + assert_eq!(stats.before_slots, stats.after_slots); + assert!(stats.publish_failed); +} From 3cb9e7c7504cf4bad2a22a709d4cfcc961e7d0e6 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 06:20:23 +0800 Subject: [PATCH 020/225] fix(lua): roll back refused publishes and retire collected tokens A full resource table now refuses push_resource after the Lua slot is reserved, then rolls that slot back so existing roots stay and the same slot is reused at the next generation. Host collect closes the exact typed tokens of swept tables through the scope close contract and returns their quota in the same VM. Tokens stay on the heap and are not GC roots. --- src/frontends/lua/heap.rs | 67 +++++-- src/frontends/lua/heap/table.rs | 103 +++++++--- tests/luajit_heap_runtime/mod.rs | 193 +++++++++++-------- tests/luajit_heap_runtime_tests.rs | 295 ++++++++++++++++++++++++++--- 4 files changed, 505 insertions(+), 153 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index d6ce831..1100cd8 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -7,7 +7,9 @@ //! live in one `LuaHeap` stored in the current `ExecutionScope`. A published //! guest value is a typed `resource` token in that same scope's //! resource table. The token is not a second heap and is not a GC root: only -//! an explicit root frame keeps a node alive across `collect`. +//! an explicit root frame keeps a node alive across `collect`. Collection +//! closes each swept node's token through the scope close contract and returns +//! that quota before the node is released. //! //! Borrowed from the ES5 heap at `3e348a010bc8d84baa5b7d1169a5f50aeb4e46ec` //! `src/javascript/heap.rs`: slot plus generation handles, explicit root @@ -32,7 +34,6 @@ pub use handle::{HandleKind, TableRef}; pub use resource::LuaTableResource; pub use table::{CollectReport, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId}; -use vm::resource::handle::DEFAULT_MAX_RESOURCES; use vm::{HostContext, Value}; /// Installs the scope heap before the first use. A second install is refused @@ -48,23 +49,41 @@ pub fn install(host: &mut HostContext, limits: HeapLimits) -> Result<(), HeapErr /// Allocates a table and publishes its typed resource token. /// -/// The resource table is checked before the node is reserved. A refused -/// publish therefore does not add a live node or a slot. If insertion fails -/// after a reserve, the node is rolled back before the error returns. +/// The node is reserved before `HostContext::push_resource`. A full resource +/// table refuses that insert after the reservation. The reserved node is then +/// rolled back, so live occupancy and existing roots return to their previous +/// state and the slot can be reused at the next generation. pub fn publish(host: &mut HostContext) -> Result { - if host.resource_count() >= DEFAULT_MAX_RESOURCES { - return Err(HeapError::PublishRejected); - } let table = with_heap(host, LuaHeap::alloc)?; - let pushed = host.push_resource(LuaTableResource::new(table)); - let resource = match pushed { + let resource = match host.push_resource(LuaTableResource::new(table)) { Ok(resource) => resource, Err(error) => { - let _ = with_heap(host, |heap| heap.rollback(table)); + with_heap(host, |heap| heap.rollback(table))?; return Err(HeapError::from_scope(error)); } }; - let raw = i64::try_from(resource.handle().raw()).map_err(|_| HeapError::CarrierOutOfRange)?; + let raw_u64 = resource.handle().raw(); + if let Err(error) = with_heap(host, |heap| heap.bind_token(table, raw_u64)) { + host.close_resource::( + resource.handle(), + vm::ResourceCloseReason::Requested, + ) + .map_err(HeapError::from_scope)?; + with_heap(host, |heap| heap.rollback(table))?; + return Err(error); + } + let raw = match i64::try_from(raw_u64) { + Ok(raw) => raw, + Err(_) => { + host.close_resource::( + resource.handle(), + vm::ResourceCloseReason::Requested, + ) + .map_err(HeapError::from_scope)?; + with_heap(host, |heap| heap.rollback(table))?; + return Err(HeapError::CarrierOutOfRange); + } + }; Ok(Value::Int(raw)) } @@ -80,6 +99,30 @@ pub fn with_heap( body(heap) } +/// Host-side collection. Unreachable tables lose their typed tokens through +/// `HostContext::close_resource` before the heap sweep, so the scope quota +/// comes back in this same VM. Stored handles are not roots. +pub fn collect(host: &mut HostContext) -> Result { + let doomed = with_heap(host, |heap| Ok(heap.unmarked_tokens()))?; + for raw in doomed { + let handle = + vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let progress = host + .close_resource::(handle, vm::ResourceCloseReason::Requested) + .map_err(HeapError::from_scope)?; + if progress != vm::resource::CloseProgress::Ready { + return Err(HeapError::Scope( + "lua table close did not finish synchronously".to_string(), + )); + } + with_heap(host, |heap| { + heap.clear_token(raw); + Ok(()) + })?; + } + with_heap(host, |heap| Ok(heap.collect())) +} + /// Reads occupancy counters from the scope heap. pub fn stats(host: &mut HostContext) -> Result { with_heap(host, |heap| Ok(heap.stats())) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 7f4ded8..9a211ff 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -57,14 +57,12 @@ pub enum HeapError { NoRootFrame, /// The frame id is not the current top frame, or its index is out of range. StaleFrame, - /// The scope resource table cannot take another token. - PublishRejected, /// The resource handle does not fit in a positive VM integer. CarrierOutOfRange, /// This scope already has a heap. AlreadyInstalled, - /// Execution-scope or resource-table failure. The node was rolled back - /// when the failure happened after a reserve. + /// Execution-scope or resource-table failure. `publish` rolls the reserved + /// node back before returning this error. Scope(String), } @@ -86,7 +84,6 @@ impl fmt::Display for HeapError { Self::WrongKind => write!(formatter, "lua handle is not a table"), Self::NoRootFrame => write!(formatter, "no lua root frame"), Self::StaleFrame => write!(formatter, "stale lua root frame"), - Self::PublishRejected => write!(formatter, "lua table publish rejected"), Self::CarrierOutOfRange => write!(formatter, "lua resource carrier out of range"), Self::AlreadyInstalled => write!(formatter, "lua heap already installed"), Self::Scope(message) => write!(formatter, "lua heap scope error: {message}"), @@ -149,6 +146,9 @@ enum SlotState { struct Slot { generation: u32, state: SlotState, + /// Raw resource handle for this node. Ownership metadata only: the mark + /// phase does not read it, so the token is not a GC root. + token: Option, } struct Edge { @@ -211,6 +211,7 @@ impl LuaHeap { return Err(HeapError::StaleHandle); } slot.state = SlotState::Live { marked: false }; + slot.token = None; return Ok(TableRef::table(self.domain, index, slot.generation)); } if self.slots.len() >= self.limits.nodes as usize { @@ -223,6 +224,7 @@ impl LuaHeap { self.slots.push(Slot { generation: 1, state: SlotState::Live { marked: false }, + token: None, }); self.note_node_peak(); Ok(TableRef::table(self.domain, index, 1)) @@ -340,35 +342,46 @@ impl LuaHeap { Ok(()) } + /// Records the typed token that owns `table`. The handle is not installed + /// as a root. + pub fn bind_token(&mut self, table: TableRef, raw: u64) -> Result<(), HeapError> { + self.require_live(table)?; + let slot = &mut self.slots[table.slot() as usize]; + if slot.token.is_some() { + return Err(HeapError::StaleHandle); + } + slot.token = Some(raw); + Ok(()) + } + + /// Drops the stored handle after the resource table has closed it. The + /// node stays until sweep. + pub fn clear_token(&mut self, raw: u64) { + for slot in &mut self.slots { + if slot.token == Some(raw) { + slot.token = None; + } + } + } + + /// Tokens of live nodes the current mark does not reach. Runs the same + /// mark as `collect` and does not release slots. + pub fn unmarked_tokens(&mut self) -> Vec { + self.mark_reachable(); + self.slots + .iter() + .filter_map(|slot| match slot.state { + SlotState::Live { marked: false } => slot.token, + _ => None, + }) + .collect() + } + /// Non-moving mark from explicit roots, then sweep unmarked nodes. /// Freed slots are reused with a bumped generation. A slot whose next /// generation would pass `max_generation` is retired instead. pub fn collect(&mut self) -> CollectReport { - for slot in &mut self.slots { - if let SlotState::Live { marked } = &mut slot.state { - *marked = false; - } - } - let mut work = Vec::new(); - let rooted: Vec = self.roots.iter().copied().flatten().collect(); - for handle in rooted { - if self.alive(handle) { - self.mark_slot(handle.slot(), &mut work); - } - } - while let Some(slot) = work.pop() { - let targets: Vec<(u32, u32)> = self - .edges - .iter() - .filter(|edge| edge.from == slot) - .map(|edge| (edge.to_slot, edge.to_generation)) - .collect(); - for (to_slot, to_generation) in targets { - if self.slot_live(to_slot, to_generation) { - self.mark_slot(to_slot, &mut work); - } - } - } + self.mark_reachable(); let swept: Vec = self .slots .iter() @@ -439,6 +452,34 @@ impl LuaHeap { }) } + fn mark_reachable(&mut self) { + for slot in &mut self.slots { + if let SlotState::Live { marked } = &mut slot.state { + *marked = false; + } + } + let mut work = Vec::new(); + let rooted: Vec = self.roots.iter().copied().flatten().collect(); + for handle in rooted { + if self.alive(handle) { + self.mark_slot(handle.slot(), &mut work); + } + } + while let Some(slot) = work.pop() { + let targets: Vec<(u32, u32)> = self + .edges + .iter() + .filter(|edge| edge.from == slot) + .map(|edge| (edge.to_slot, edge.to_generation)) + .collect(); + for (to_slot, to_generation) in targets { + if self.slot_live(to_slot, to_generation) { + self.mark_slot(to_slot, &mut work); + } + } + } + } + fn mark_slot(&mut self, index: u32, work: &mut Vec) { if let SlotState::Live { marked } = &mut self.slots[index as usize].state { if !*marked { @@ -452,10 +493,12 @@ impl LuaHeap { let slot = &mut self.slots[index as usize]; if slot.generation >= self.limits.max_generation { slot.state = SlotState::Retired; + slot.token = None; return; } slot.generation = slot.generation.saturating_add(1); slot.state = SlotState::Free; + slot.token = None; self.free_list.push(index); } diff --git a/tests/luajit_heap_runtime/mod.rs b/tests/luajit_heap_runtime/mod.rs index f457447..a9ad422 100644 --- a/tests/luajit_heap_runtime/mod.rs +++ b/tests/luajit_heap_runtime/mod.rs @@ -2,8 +2,6 @@ //! //! This is not a production plugin and is not wired to the `.lua` entry. -use std::sync::atomic::{AtomicU64, Ordering}; - use vm::compiler::ir::{ResolvedHostCall, ResolvedHostParam}; use vm::{ CallOutcome, CallReturn, CompileSourceFileOptions, Expr, FrontendImportSyntax, FrontendIr, @@ -14,19 +12,31 @@ use vm::{ VmError, VmStatus, }; -use super::heap::{self, HeapLimits, LuaTableResource, TableRef}; +use super::heap::{self, LuaTableResource, TableRef}; +use vm::HostContext; -static BODY_ENTRIES: AtomicU64 = AtomicU64::new(0); -static ALIVE_ENTRIES: AtomicU64 = AtomicU64::new(0); -static FORGED_SLOT: AtomicU64 = AtomicU64::new(0); -static FORGED_GENERATION: AtomicU64 = AtomicU64::new(0); +/// Per-VM probe counters. They live in the execution scope so parallel tests +/// do not share a process-global tally. +#[derive(Clone, Copy, Debug, Default)] +struct ProbeCounters { + body: u64, + alive: u64, + forged_slot: u64, + forged_generation: u64, +} -pub fn body_entries() -> u64 { - BODY_ENTRIES.load(Ordering::SeqCst) +/// A probe that did not produce a halted stack. Counts belong to that VM only. +#[derive(Debug)] +pub struct ProbeError { + pub message: String, + pub body_entries: u64, + pub alive_entries: u64, } -pub fn alive_entries() -> u64 { - ALIVE_ENTRIES.load(Ordering::SeqCst) +impl std::fmt::Display for ProbeError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(&self.message) + } } #[derive(Clone, Copy, Debug)] @@ -46,19 +56,12 @@ pub enum Probe { pub struct ProbeResult { pub stack: Vec, pub body_entries: u64, + pub alive_entries: u64, pub published_raw: Option, pub forged_slot: Option, pub forged_generation: Option, } -pub struct PublishStats { - pub before_live: u32, - pub after_live: u32, - pub before_slots: u32, - pub after_slots: u32, - pub publish_failed: bool, -} - struct ProbePlugin; impl SourcePlugin for ProbePlugin { @@ -79,7 +82,7 @@ impl SourcePlugin for ProbePlugin { } } -pub fn run_probe(probe: Probe) -> Result { +pub fn run_probe(probe: Probe) -> Result { let catalog = catalog(); let source = probe_source(probe); let compiled = vm::compile_source_with_flavor_and_options( @@ -89,17 +92,28 @@ pub fn run_probe(probe: Probe) -> Result { .with_source_plugin(&ProbePlugin) .with_host_api_catalog(std::sync::Arc::new(catalog.clone())), ) - .map_err(|error| error.to_string())?; + .map_err(|error| probe_error(error.to_string()))?; let mut registry = HostFunctionRegistry::empty(); - register_hosts(&mut registry, &catalog).map_err(|error| error.to_string())?; - let mut vm = compiled.into_vm().map_err(|error| error.to_string())?; + register_hosts(&mut registry, &catalog).map_err(|error| probe_error(error.to_string()))?; + let mut vm = compiled + .into_vm() + .map_err(|error| probe_error(error.to_string()))?; registry .bind_vm_cached(&mut vm) - .map_err(|error| error.to_string())?; - let before = body_entries(); - let status = vm.run().map_err(|error| error.to_string())?; + .map_err(|error| probe_error(error.to_string()))?; + let status = vm.run(); + let counters = read_counters(&mut vm); + let status = status.map_err(|error| ProbeError { + message: error.to_string(), + body_entries: counters.body, + alive_entries: counters.alive, + })?; if status != VmStatus::Halted { - return Err(format!("probe did not halt: {status:?}")); + return Err(ProbeError { + message: format!("probe did not halt: {status:?}"), + body_entries: counters.body, + alive_entries: counters.alive, + }); } let stack = vm.stack().to_vec(); let published_raw = stack.iter().find_map(|value| match value { @@ -108,15 +122,15 @@ pub fn run_probe(probe: Probe) -> Result { }); Ok(ProbeResult { stack, - body_entries: body_entries().saturating_sub(before), + body_entries: counters.body, + alive_entries: counters.alive, published_raw, - forged_slot: non_zero(FORGED_SLOT.load(Ordering::SeqCst)), - forged_generation: non_zero(FORGED_GENERATION.load(Ordering::SeqCst)), + forged_slot: non_zero(counters.forged_slot), + forged_generation: non_zero(counters.forged_generation), }) } -pub fn fill_resource_table_then_fail_publish() -> PublishStats { - let catalog = catalog(); +pub fn with_idle_vm(body: impl FnOnce(&mut vm::Vm) -> T) -> T { let compiled = vm::compile_source_with_flavor_and_options( "idle", SourceFlavor::Lua, @@ -124,30 +138,21 @@ pub fn fill_resource_table_then_fail_publish() -> PublishStats { ) .expect("idle program"); let mut vm = compiled.into_vm().expect("vm"); - let mut host = vm.host_context(); - heap::install( - &mut host, - HeapLimits { - nodes: 2048, - roots: 4, - edges: 4, - max_generation: 8, - }, - ) - .expect("install"); - for _ in 0..vm::resource::handle::DEFAULT_MAX_RESOURCES { - heap::publish(&mut host).expect("fill resource table"); - } - let before = heap::stats(&mut host).expect("stats"); - let failed = heap::publish(&mut host).is_err(); - let after = heap::stats(&mut host).expect("stats after"); - let _ = catalog; - PublishStats { - before_live: before.live_nodes, - after_live: after.live_nodes, - before_slots: before.node_slots, - after_slots: after.node_slots, - publish_failed: failed, + body(&mut vm) +} + +fn read_counters(vm: &mut vm::Vm) -> ProbeCounters { + vm.host_context() + .scope_state::() + .copied() + .unwrap_or_default() +} + +fn probe_error(message: String) -> ProbeError { + ProbeError { + message, + body_entries: 0, + alive_entries: 0, } } @@ -315,8 +320,8 @@ struct AcceptNamed; impl HostOwnedFunction for Publish { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); let mut host = call.vm().host_context(); + note_body(&mut host); let value = heap::publish(&mut host).map_err(host_error)?; Ok(CallOutcome::Return(CallReturn::one(value))) } @@ -324,8 +329,10 @@ impl HostOwnedFunction for Publish { impl HostOwnedFunction for Alive { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); - note_alive(); + let mut host = call.vm().host_context(); + note_body(&mut host); + note_alive(&mut host); + drop(host); let table = recover(call, 0)?; let mut host = call.vm().host_context(); let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).map_err(host_error)?; @@ -335,8 +342,10 @@ impl HostOwnedFunction for Alive { impl HostOwnedFunction for Observe { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); - note_alive(); + let mut host = call.vm().host_context(); + note_body(&mut host); + note_alive(&mut host); + drop(host); let table = recover(call, 0)?; let _marker = int_arg(&call, 1)?; let mut host = call.vm().host_context(); @@ -349,7 +358,9 @@ impl HostOwnedFunction for Observe { impl HostOwnedFunction for SetEdge { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); + let mut host = call.vm().host_context(); + note_body(&mut host); + drop(host); let from = recover(call, 0)?; let key = int_arg(&call, 1)?; let to = recover(call, 2)?; @@ -361,7 +372,9 @@ impl HostOwnedFunction for SetEdge { impl HostOwnedFunction for EdgeIs { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); + let mut host = call.vm().host_context(); + note_body(&mut host); + drop(host); let from = recover(call, 0)?; let key = int_arg(&call, 1)?; let to = recover(call, 2)?; @@ -374,9 +387,9 @@ impl HostOwnedFunction for EdgeIs { impl HostOwnedFunction for Enter { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); let width = int_arg(&call, 0)?; let mut host = call.vm().host_context(); + note_body(&mut host); heap::with_heap(&mut host, |heap| heap.enter_roots(width)).map_err(host_error)?; Ok(CallOutcome::Return(CallReturn::one(Value::Int(1)))) } @@ -384,7 +397,9 @@ impl HostOwnedFunction for Enter { impl HostOwnedFunction for Root { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); + let mut host = call.vm().host_context(); + note_body(&mut host); + drop(host); let slot = int_arg(&call, 0)?; let table = recover(call, 1)?; let returned = call.args()[1].clone(); @@ -400,9 +415,9 @@ impl HostOwnedFunction for Root { impl HostOwnedFunction for Collect { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); let mut host = call.vm().host_context(); - let marked = heap::with_heap(&mut host, |heap| Ok(heap.collect())).map_err(host_error)?; + note_body(&mut host); + let marked = heap::collect(&mut host).map_err(host_error)?; Ok(CallOutcome::Return(CallReturn::one(Value::Int( i64::from(marked.live_nodes), )))) @@ -411,15 +426,18 @@ impl HostOwnedFunction for Collect { impl HostOwnedFunction for Close { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); + let mut host = call.vm().host_context(); + note_body(&mut host); + drop(host); let _taken = call.take_arg(0)?; Ok(CallOutcome::Return(CallReturn::one(Value::Int(1)))) } } impl HostOwnedFunction for ForgeNamed { - fn call(&mut self, _call: &mut OwnedHostCall<'_>) -> Result { - note_body(); + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let mut host = call.vm().host_context(); + note_body(&mut host); let mut map = vm::bytecode::VmMap::new(); map.insert(Value::string("slot"), Value::Int(7)); map.insert(Value::string("generation"), Value::Int(9)); @@ -431,14 +449,19 @@ impl HostOwnedFunction for ForgeNamed { impl HostOwnedFunction for AcceptNamed { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - note_body(); - let Value::Map(map) = &call.args()[0] else { - return Err(VmError::HostError("named carrier was not a map".to_string())); + let (slot, generation) = { + let Value::Map(map) = &call.args()[0] else { + return Err(VmError::HostError("named carrier was not a map".to_string())); + }; + (map_int(map, "slot")?, map_int(map, "generation")?) }; - let slot = map_int(map, "slot")?; - let generation = map_int(map, "generation")?; - FORGED_SLOT.store(slot as u64, Ordering::SeqCst); - FORGED_GENERATION.store(generation as u64, Ordering::SeqCst); + let mut host = call.vm().host_context(); + note_body(&mut host); + let counters = host + .scope_state_or_insert_with(ProbeCounters::default) + .map_err(host_error)?; + counters.forged_slot = slot as u64; + counters.forged_generation = generation as u64; Ok(CallOutcome::Return(CallReturn::one(Value::Int(1)))) } } @@ -480,12 +503,18 @@ fn int_arg(call: &OwnedHostCall<'_>, index: usize) -> Result { } } -fn note_body() { - BODY_ENTRIES.fetch_add(1, Ordering::SeqCst); +fn note_body(host: &mut HostContext<'_>) { + let counters = host + .scope_state_or_insert_with(ProbeCounters::default) + .expect("probe counter scope"); + counters.body = counters.body.saturating_add(1); } -fn note_alive() { - ALIVE_ENTRIES.fetch_add(1, Ordering::SeqCst); +fn note_alive(host: &mut HostContext<'_>) { + let counters = host + .scope_state_or_insert_with(ProbeCounters::default) + .expect("probe counter scope"); + counters.alive = counters.alive.saturating_add(1); } fn host_error(error: impl ToString) -> VmError { @@ -581,8 +610,6 @@ fn build_ir(source: &str) -> Result { }); } "named" => { - FORGED_SLOT.store(0, Ordering::SeqCst); - FORGED_GENERATION.store(0, Ordering::SeqCst); let record = local(&mut builder, "record")?; stmts.push(bind(record, call("lua_heap_forge_named", Vec::new()))); stmts.push(Stmt::Expr { diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index 0d826bf..a0afb75 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -10,9 +10,9 @@ mod heap; #[path = "luajit_heap_runtime/mod.rs"] mod support; -use heap::{CollectReport, HandleKind, HeapLimits, LuaHeap, RootFrameId}; -use support::{Probe, alive_entries, body_entries, run_probe}; -use vm::Value; +use heap::{CollectReport, HandleKind, HeapLimits, LuaHeap, LuaTableResource, RootFrameId, TableRef}; +use support::{Probe, run_probe, with_idle_vm}; +use vm::{HostContext, ResourceHandle, Value}; fn tight_limits() -> HeapLimits { HeapLimits { @@ -161,14 +161,17 @@ fn typed_resource_boundary_rejects_int_foreign_and_expired_values() { let transfer = run_probe(Probe::Transfer).expect("transfer"); assert_eq!(transfer.stack, vec![Value::Int(1)]); assert!(transfer.body_entries > 0, "typed host body ran for a published table"); + assert!(transfer.alive_entries > 0, "alive ran inside the same VM"); let alias = run_probe(Probe::Alias).expect("alias"); assert_eq!(alias.stack, vec![Value::Int(1)], "same table write is visible through the other handle"); - let before_int = body_entries(); - let rejected_int = run_probe(Probe::RejectInt); - assert!(rejected_int.is_err(), "ordinary int is not a table: {rejected_int:?}"); - assert_eq!(body_entries(), before_int, "int rejection happens before the host body"); + let before_int = run_probe(Probe::RejectInt).expect_err("ordinary int is not a table"); + assert_eq!( + before_int.body_entries, 0, + "int rejection happens before the host body" + ); + assert_eq!(before_int.alive_entries, 0); let published = run_probe(Probe::Publish).expect("publish handle"); assert_eq!(published.published_raw, published.stack.first().and_then(|value| match value { @@ -179,17 +182,13 @@ fn typed_resource_boundary_rejects_int_foreign_and_expired_values() { [Value::Int(raw)] => *raw, other => panic!("publish did not return one handle: {other:?}"), }; - let before_foreign = alive_entries(); - let foreign = run_probe(Probe::RejectForeign { raw }); - assert!(foreign.is_err(), "cross-vm handle is rejected: {foreign:?}"); - assert_eq!(alive_entries(), before_foreign, "foreign rejection is before the host body"); - - let before_expired = alive_entries(); - let expired = run_probe(Probe::Expired); - assert!(expired.is_err(), "expired handle is rejected: {expired:?}"); + let foreign = run_probe(Probe::RejectForeign { raw }).expect_err("cross-vm handle is rejected"); + assert_eq!(foreign.body_entries, 0, "foreign rejection is before the host body"); + assert_eq!(foreign.alive_entries, 0); + + let expired = run_probe(Probe::Expired).expect_err("expired handle is rejected"); assert_eq!( - alive_entries(), - before_expired, + expired.alive_entries, 0, "close runs; the later alive call must not" ); @@ -197,24 +196,264 @@ fn typed_resource_boundary_rejects_int_foreign_and_expired_values() { assert_eq!(named.stack, vec![Value::Int(1)]); assert_eq!(named.forged_slot, Some(7)); assert_eq!(named.forged_generation, Some(9)); - assert!( - rejected_int.is_err() && named.stack == vec![Value::Int(1)], - "a named record of copyable ints is not provenance; typed resource is the carrier" - ); + // A named record of copyable ints is not the table carrier. Rejecting one + // ordinary int does not show that every Lua number, or an unrelated auth + // token, is isolated from table tokens. } #[test] fn nested_argument_root_keeps_the_first_argument_across_collect() { let rooted = run_probe(Probe::NestedRooted).expect("rooted nest"); assert_eq!(rooted.stack, vec![Value::Int(1)]); - let unrooted = run_probe(Probe::NestedUnrooted).expect("unrooted nest"); - assert_eq!(unrooted.stack, vec![Value::Int(0)]); + let unrooted = run_probe(Probe::NestedUnrooted).expect_err("collected token is retired"); + assert!( + unrooted.message.contains("resource_already_closed"), + "an unrooted table's token must be invalid after collect: {unrooted}" + ); + assert_eq!( + unrooted.body_entries, 3, + "enter, publish, and collect ran; the later observe must not" + ); + assert_eq!(unrooted.alive_entries, 0); +} + +#[test] +fn full_resource_table_publish_occupies_a_slot_then_rolls_it_back() { + with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 2048, + roots: 4, + edges: 4, + max_generation: 8, + }, + ) + .expect("install"); + let rooted_raw = publish_raw(&mut host); + let rooted = table_ref(&host, rooted_raw); + let frame = heap::with_heap(&mut host, |heap| heap.enter_roots(1)).expect("frame"); + heap::with_heap(&mut host, |heap| heap.write_root(frame, 0, rooted)).expect("root"); + let spare_raw = publish_raw(&mut host); + let spare = resource_handle(spare_raw); + while host.resource_count() < vm::resource::handle::DEFAULT_MAX_RESOURCES { + let _filled = publish_raw(&mut host); + } + assert_eq!( + host.resource_count(), + vm::resource::handle::DEFAULT_MAX_RESOURCES + ); + + let before = heap::stats(&mut host).expect("stats"); + let failed = heap::publish(&mut host); + let after = heap::stats(&mut host).expect("stats after"); + let error = failed.expect_err("a full resource table must refuse the next publish"); + assert_eq!( + after.node_slots, + before.node_slots + 1, + "refused publish must occupy a lua slot before push_resource returns; error={error}" + ); + assert_eq!( + after.live_nodes, + before.live_nodes, + "rollback must release the occupied slot; error={error}" + ); + assert_eq!(after.live_roots, before.live_roots, "existing roots must stay"); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("rooted check"), + "the existing root stays live" + ); + assert_eq!( + host.resource_count(), + vm::resource::handle::DEFAULT_MAX_RESOURCES + ); + match &error { + heap::HeapError::Scope(message) if message.contains("resource_limit_exceeded") => {} + other => panic!("refusal must be the real push_resource limit, got {other:?}"), + } + + let progress = host + .close_resource::(spare, vm::ResourceCloseReason::Requested) + .expect("close one token to free a resource slot"); + assert_eq!(progress, vm::resource::CloseProgress::Ready); + let reused_raw = publish_raw(&mut host); + let reused = table_ref(&host, reused_raw); + assert_eq!( + reused.slot(), + before.node_slots, + "the slot occupied by the refused publish is reused" + ); + assert_eq!( + reused.generation(), + 2, + "rollback must bump the generation before reuse" + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(reused))).expect("reused check")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("root remains")); + }); +} + +fn publish_raw(host: &mut HostContext<'_>) -> i64 { + match heap::publish(host).expect("publish") { + Value::Int(raw) => raw, + other => panic!("publish did not return a handle: {other:?}"), + } +} + +fn resource_handle(raw: i64) -> ResourceHandle { + ResourceHandle::from_raw(u64::try_from(raw).expect("positive handle")).expect("handle") +} + +fn table_ref(host: &HostContext<'_>, raw: i64) -> TableRef { + let handle = resource_handle(raw); + let token = host + .typed_resource_with_key::(handle, &LuaTableResource::key()) + .expect("typed token"); + host.resource(&token).expect("live token").get().table() } +/// A host resource that is not a Lua table. Collection must not close it. +struct UnrelatedHostResource; + +impl vm::resource::HostResource for UnrelatedHostResource {} + #[test] -fn publish_failure_against_the_resource_table_rolls_back_the_node() { - let stats = support::fill_resource_table_then_fail_publish(); - assert_eq!(stats.before_live, stats.after_live); - assert_eq!(stats.before_slots, stats.after_slots); - assert!(stats.publish_failed); +fn collect_returns_token_quota_and_republish_exceeds_the_core_limit() { + with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 64, + roots: 4, + edges: 4, + max_generation: 64, + }, + ) + .expect("install"); + let unrelated = host + .push_resource(UnrelatedHostResource) + .expect("unrelated host resource"); + let rooted_raw = publish_raw(&mut host); + let rooted = table_ref(&host, rooted_raw); + let frame = heap::with_heap(&mut host, |heap| heap.enter_roots(1)).expect("frame"); + heap::with_heap(&mut host, |heap| heap.write_root(frame, 0, rooted)).expect("root"); + + let mut published = 1usize; + let mut last_doomed = 0i64; + let batch = 32usize; + while published <= vm::resource::handle::DEFAULT_MAX_RESOURCES { + for _ in 0..batch { + last_doomed = publish_raw(&mut host); + published = published.saturating_add(1); + } + let before_nodes = heap::stats(&mut host).expect("before nodes").live_nodes; + let before_tokens = host.resource_count(); + let report = heap::collect(&mut host).expect("collect"); + let after = heap::stats(&mut host).expect("after nodes"); + assert!( + before_nodes > after.live_nodes, + "collect must sweep unrooted tables in this same VM" + ); + assert_eq!(after.live_nodes, 1, "the rooted table stays"); + assert_eq!(report.live_nodes, 1); + assert_eq!( + host.resource_count(), + 2, + "swept tokens must retire and return quota; before_tokens={before_tokens}" + ); + assert!( + before_tokens > host.resource_count(), + "live tokens must drop with the swept tables" + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("rooted node"), + "the rooted node stays live" + ); + let rooted_token = resource_handle(rooted_raw); + assert!( + host.typed_resource_with_key::( + rooted_token, + &LuaTableResource::key(), + ) + .is_ok(), + "the rooted token stays valid" + ); + let doomed = resource_handle(last_doomed); + assert!( + host.typed_resource_with_key::(doomed, &LuaTableResource::key()) + .is_err(), + "a collected token must be invalid without leaving the VM" + ); + assert!( + host.resource(&unrelated).is_ok(), + "an unrelated host resource is not a collected table" + ); + } + assert!( + published > vm::resource::handle::DEFAULT_MAX_RESOURCES, + "cumulative publish, collect, and republish must pass the core limit" + ); + let _again = publish_raw(&mut host); + }); +} + +#[test] +fn reset_for_reuse_rejects_old_handles_and_starts_an_empty_heap() { + with_idle_vm(|vm| { + let raw = { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 8, + roots: 2, + edges: 2, + max_generation: 4, + }, + ) + .expect("install"); + let raw = publish_raw(&mut host); + let table = table_ref(&host, raw); + let frame = heap::with_heap(&mut host, |heap| heap.enter_roots(1)).expect("frame"); + heap::with_heap(&mut host, |heap| heap.write_root(frame, 0, table)).expect("root"); + let before = heap::stats(&mut host).expect("before reset"); + assert!(before.live_nodes > 0); + assert!(before.live_roots > 0); + raw + }; + vm.reset_for_reuse().expect("start reset"); + let waker = std::task::Waker::noop(); + let mut context = std::task::Context::from_waker(&waker); + match vm.poll_reset_for_reuse(&mut context) { + std::task::Poll::Ready(Ok(())) => {} + other => panic!("reset did not finish: {other:?}"), + } + let mut host = vm.host_context(); + let rejected = host.typed_resource_with_key::( + resource_handle(raw), + &LuaTableResource::key(), + ); + assert!(rejected.is_err(), "old handle must be rejected: {rejected:?}"); + assert!( + host.scope_state::().is_none(), + "the replacement scope starts without a heap" + ); + assert_eq!(host.resource_count(), 0, "the new scope has no leftover tokens"); + heap::install( + &mut host, + HeapLimits { + nodes: 8, + roots: 2, + edges: 2, + max_generation: 4, + }, + ) + .expect("reinstall"); + let empty = heap::stats(&mut host).expect("empty heap"); + assert_eq!(empty.live_nodes, 0); + assert_eq!(empty.live_roots, 0); + let _again = publish_raw(&mut host); + }); } From 3e121145ad0c13d74bd4647139ed6ceeffceed86 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 06:44:57 +0800 Subject: [PATCH 021/225] fix(lua): keep sweeping after a retired table token A stored lua.table token already removed by close or take aborted collection and stayed in the node. For that stored token only, treat ResourceAlreadyClosed and ResourceStale as retired and continue the sweep. --- src/frontends/lua/heap.rs | 63 +++++++--- src/frontends/lua/heap/table.rs | 5 + tests/luajit_heap_runtime_tests.rs | 190 +++++++++++++++++++++++++++++ 3 files changed, 244 insertions(+), 14 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 1100cd8..72a9a56 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -102,27 +102,62 @@ pub fn with_heap( /// Host-side collection. Unreachable tables lose their typed tokens through /// `HostContext::close_resource` before the heap sweep, so the scope quota /// comes back in this same VM. Stored handles are not roots. +/// +/// A token this heap still stores may already have been removed by +/// `close_resource`, `take_resource`, or a TakeOwned host parameter. For that +/// stored token only, `ResourceAlreadyClosed` (slot not reused) and +/// `ResourceStale` (slot reused) are retired: the token is cleared and the +/// sweep continues. The successor in a reused slot is not closed. Any other +/// structured error, including a wrong table or a type mismatch, stops the +/// sweep. Tokens already cleared stay cleared, so a later collection retries +/// only the unprocessed suffix. pub fn collect(host: &mut HostContext) -> Result { let doomed = with_heap(host, |heap| Ok(heap.unmarked_tokens()))?; for raw in doomed { - let handle = - vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; - let progress = host - .close_resource::(handle, vm::ResourceCloseReason::Requested) - .map_err(HeapError::from_scope)?; - if progress != vm::resource::CloseProgress::Ready { - return Err(HeapError::Scope( - "lua table close did not finish synchronously".to_string(), - )); - } - with_heap(host, |heap| { - heap.clear_token(raw); - Ok(()) - })?; + retire_doomed_token(host, raw)?; } with_heap(host, |heap| Ok(heap.collect())) } +fn retire_doomed_token(host: &mut HostContext, raw: u64) -> Result<(), HeapError> { + let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + match host.close_resource::(handle, vm::ResourceCloseReason::Requested) { + Ok(progress) => { + // `LuaTableResource` uses the default synchronous close, which + // returns Ready. Core can also report AlreadyClosed for a Closing + // slot, but this concrete type has no path that returns Pending. + if progress != vm::resource::CloseProgress::Ready { + return Err(HeapError::Scope( + "lua table close did not finish synchronously".to_string(), + )); + } + } + Err(error) => { + let stored = with_heap(host, |heap| Ok(heap.stores_token(raw)))?; + if !(stored && retired_lua_token(&error)) { + return Err(HeapError::from_scope(error)); + } + } + } + with_heap(host, |heap| { + heap.clear_token(raw); + Ok(()) + }) +} + +fn retired_lua_token(error: &vm::HostContextError) -> bool { + match error.kind() { + vm::HostContextErrorKind::Scope(vm::execution_scope::ExecutionScopeError::Resource( + resource, + )) => matches!( + resource.code(), + vm::resource::ResourceErrorCode::ResourceAlreadyClosed + | vm::resource::ResourceErrorCode::ResourceStale + ), + _ => false, + } +} + /// Reads occupancy counters from the scope heap. pub fn stats(host: &mut HostContext) -> Result { with_heap(host, |heap| Ok(heap.stats())) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 9a211ff..ac4445e 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -354,6 +354,11 @@ impl LuaHeap { Ok(()) } + /// Whether `raw` is the token currently stored on a node in this heap. + pub(super) fn stores_token(&self, raw: u64) -> bool { + self.slots.iter().any(|slot| slot.token == Some(raw)) + } + /// Drops the stored handle after the resource table has closed it. The /// node stays until sweep. pub fn clear_token(&mut self, raw: u64) { diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index a0afb75..a5191b6 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -294,6 +294,196 @@ fn full_resource_table_publish_occupies_a_slot_then_rolls_it_back() { }); } +fn scope_resource_code(error: &vm::HostContextError) -> vm::resource::ResourceErrorCode { + match error.kind() { + vm::HostContextErrorKind::Scope(vm::execution_scope::ExecutionScopeError::Resource( + resource, + )) => resource.code(), + other => panic!("close did not return a scope resource error: {other:?}"), + } +} + +fn root_table(host: &mut HostContext<'_>, table: TableRef) { + let frame = heap::with_heap(host, |heap| heap.enter_roots(1)).expect("root frame"); + heap::with_heap(host, |heap| heap.write_root(frame, 0, table)).expect("root"); +} + +fn sweep_limits() -> HeapLimits { + HeapLimits { + nodes: 16, + roots: 4, + edges: 4, + max_generation: 16, + } +} + +/// External `close_resource` retires the core token while the lua node still +/// stores it. The slot is not reused, so a later close reports +/// `ResourceAlreadyClosed`. Collection must still sweep that node and another +/// ordinary unreachable table, then accept a second collection in the same VM. +#[test] +fn collect_finishes_when_an_unreused_token_is_already_closed() { + with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, sweep_limits()).expect("install"); + let unrelated = host + .push_resource(UnrelatedHostResource) + .expect("unrelated host resource"); + let rooted_raw = publish_raw(&mut host); + let rooted = table_ref(&host, rooted_raw); + root_table(&mut host, rooted); + let retired_raw = publish_raw(&mut host); + let retired = table_ref(&host, retired_raw); + let retired_handle = resource_handle(retired_raw); + let other_raw = publish_raw(&mut host); + let other_handle = resource_handle(other_raw); + + let progress = host + .close_resource::( + retired_handle, + vm::ResourceCloseReason::Requested, + ) + .expect("external close"); + assert_eq!(progress, vm::resource::CloseProgress::Ready); + let observed = host + .close_resource::( + retired_handle, + vm::ResourceCloseReason::Requested, + ) + .expect_err("slot was not reused"); + assert_eq!( + scope_resource_code(&observed), + vm::resource::ResourceErrorCode::ResourceAlreadyClosed + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(retired))).expect("retired node"), + "the lua node still stores the closed token" + ); + assert_eq!(host.resource_count(), 3, "close already returned one quota unit"); + assert_eq!(heap::stats(&mut host).expect("before").live_nodes, 3); + + let report = heap::collect(&mut host) + .expect("an already-closed stored token must not stop collection"); + assert_eq!(report.live_nodes, 1); + assert_eq!(host.resource_count(), 2, "only the other doomed token is closed"); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("rooted")); + assert!( + host.typed_resource_with_key::( + resource_handle(rooted_raw), + &LuaTableResource::key(), + ) + .is_ok(), + "the rooted token stays valid" + ); + assert!( + host.typed_resource_with_key::(other_handle, &LuaTableResource::key()) + .is_err(), + "the other unreachable table is collected" + ); + assert!(host.resource(&unrelated).is_ok(), "unrelated resource stays"); + assert!( + host.scope_state::().is_some(), + "collection must not replace the scope with reset" + ); + + let again = heap::collect(&mut host).expect("a later collection must also finish"); + assert_eq!(again.live_nodes, 1); + assert_eq!(host.resource_count(), 2, "the second collection must not release quota again"); + assert_eq!(heap::stats(&mut host).expect("after").collections, 2); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("root remains")); + assert!(host.resource(&unrelated).is_ok(), "unrelated resource remains"); + }); +} + +/// `take_resource` vacates the core slot. The next publish reuses that slot, so +/// the stored token is `ResourceStale`. The successor in that slot must stay +/// usable, and another unreachable table must still be collected. +#[test] +fn collect_finishes_when_a_reused_token_is_stale() { + with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, sweep_limits()).expect("install"); + let unrelated = host + .push_resource(UnrelatedHostResource) + .expect("unrelated host resource"); + let rooted_raw = publish_raw(&mut host); + let rooted = table_ref(&host, rooted_raw); + root_table(&mut host, rooted); + let other_raw = publish_raw(&mut host); + let other_handle = resource_handle(other_raw); + let retired_raw = publish_raw(&mut host); + let retired = table_ref(&host, retired_raw); + let retired_handle = resource_handle(retired_raw); + + let _taken = host + .take_resource::(retired_handle) + .expect("take the stored token"); + let successor_raw = publish_raw(&mut host); + let successor_handle = resource_handle(successor_raw); + let successor = table_ref(&host, successor_raw); + root_table(&mut host, successor); + assert_eq!( + retired_handle.slot_index().expect("retired slot"), + successor_handle.slot_index().expect("successor slot"), + "the successor must occupy the same core slot" + ); + assert_ne!(retired_handle.generation(), successor_handle.generation()); + let observed = host + .close_resource::( + retired_handle, + vm::ResourceCloseReason::Requested, + ) + .expect_err("reused slot"); + assert_eq!( + scope_resource_code(&observed), + vm::resource::ResourceErrorCode::ResourceStale + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(retired))).expect("retired node"), + "the lua node still stores the stale token" + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(successor))).expect("successor node") + ); + assert_eq!(host.resource_count(), 4); + assert_eq!(heap::stats(&mut host).expect("before").live_nodes, 4); + + let report = heap::collect(&mut host) + .expect("a stale stored token must not stop collection"); + assert_eq!(report.live_nodes, 2, "rooted table and successor stay"); + assert_eq!( + host.resource_count(), + 3, + "only the other doomed token is closed; the successor keeps its quota" + ); + assert_eq!( + table_ref(&host, successor_raw).slot(), + successor.slot(), + "the successor token is still the live occupant of the reused slot" + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(successor))).expect("successor")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("rooted")); + assert!( + host.typed_resource_with_key::(other_handle, &LuaTableResource::key()) + .is_err(), + "the other unreachable table is collected" + ); + assert!(host.resource(&unrelated).is_ok(), "unrelated resource stays"); + assert!( + host.scope_state::().is_some(), + "collection must not replace the scope with reset" + ); + + let again = heap::collect(&mut host).expect("a later collection must also finish"); + assert_eq!(again.live_nodes, 2); + assert_eq!(host.resource_count(), 3, "the second collection must not release quota again"); + assert_eq!(heap::stats(&mut host).expect("after").collections, 2); + assert_eq!(table_ref(&host, successor_raw).generation(), successor.generation()); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("root remains")); + assert!(host.resource(&unrelated).is_ok(), "unrelated resource remains"); + }); +} + fn publish_raw(host: &mut HostContext<'_>) -> i64 { match heap::publish(host).expect("publish") { Value::Int(raw) => raw, From e52a2bc3813cdd04428972d979ba5bff5d68a156 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 08:00:02 +0800 Subject: [PATCH 022/225] fix(lua): collect the private heap in one linear pass Mark once from explicit roots, walk a temporary outgoing index, and filter the edge vector once. Host close checks the slot captured at mark time, so a retired token does not scan every slot or close a successor. --- src/frontends/lua/heap.rs | 71 ++- src/frontends/lua/heap/resource.rs | 4 +- src/frontends/lua/heap/table.rs | 183 ++++++- tests/luajit_heap_runtime/mod.rs | 97 ++-- tests/luajit_heap_runtime_tests.rs | 802 +++++++++++++++++++++++++++-- 5 files changed, 1016 insertions(+), 141 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 72a9a56..8b607aa 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -32,7 +32,7 @@ mod table; pub use handle::{HandleKind, TableRef}; pub use resource::LuaTableResource; -pub use table::{CollectReport, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId}; +pub use table::{CollectReport, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId, ScanMeter}; use vm::{HostContext, Value}; @@ -99,50 +99,62 @@ pub fn with_heap( body(heap) } -/// Host-side collection. Unreachable tables lose their typed tokens through -/// `HostContext::close_resource` before the heap sweep, so the scope quota -/// comes back in this same VM. Stored handles are not roots. +/// Host-side collection. One mark lists unreachable tokens. Each token is +/// closed through `HostContext::close_resource` before the heap sweep, so the +/// scope quota comes back in this same VM. Stored handles are not roots. /// -/// A token this heap still stores may already have been removed by -/// `close_resource`, `take_resource`, or a TakeOwned host parameter. For that -/// stored token only, `ResourceAlreadyClosed` (slot not reused) and -/// `ResourceStale` (slot reused) are retired: the token is cleared and the -/// sweep continues. The successor in a reused slot is not closed. Any other -/// structured error, including a wrong table or a type mismatch, stops the -/// sweep. Tokens already cleared stay cleared, so a later collection retries -/// only the unprocessed suffix. +/// Close checks the slot and generation captured at mark time. It does not +/// search the slot vector. For that exact stored token only, +/// `ResourceAlreadyClosed` (slot not reused) and `ResourceStale` (slot reused) +/// are retired: the identified slot is cleared and the sweep continues. A +/// successor in a reused core slot is not closed, and a different lua slot is +/// not cleared. Any other structured error, including a wrong table or a type +/// mismatch, stops the sweep. Tokens already cleared stay cleared. The sweep +/// does not run, so a later collection marks again and retries the remainder. +/// +/// `LuaTableResource` uses the default synchronous close, which returns Ready. +/// A Pending result is an error. This type has no path that starts an +/// asynchronous close, and this collector does not add one. pub fn collect(host: &mut HostContext) -> Result { - let doomed = with_heap(host, |heap| Ok(heap.unmarked_tokens()))?; - for raw in doomed { - retire_doomed_token(host, raw)?; + let doomed = with_heap(host, |heap| Ok(heap.mark_and_doomed_tokens()))?; + for token in doomed { + retire_doomed_token(host, token)?; } - with_heap(host, |heap| Ok(heap.collect())) + with_heap(host, |heap| Ok(heap.sweep_marked())) } -fn retire_doomed_token(host: &mut HostContext, raw: u64) -> Result<(), HeapError> { - let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; +fn retire_doomed_token(host: &mut HostContext, token: table::DoomedToken) -> Result<(), HeapError> { + let handle = + vm::ResourceHandle::from_raw(token.raw).map_err(|_| HeapError::CarrierOutOfRange)?; + with_heap(host, |heap| { + heap.note_token_close(); + Ok(()) + })?; match host.close_resource::(handle, vm::ResourceCloseReason::Requested) { Ok(progress) => { - // `LuaTableResource` uses the default synchronous close, which - // returns Ready. Core can also report AlreadyClosed for a Closing - // slot, but this concrete type has no path that returns Pending. if progress != vm::resource::CloseProgress::Ready { return Err(HeapError::Scope( "lua table close did not finish synchronously".to_string(), )); } + with_heap(host, |heap| { + let _cleared = heap.clear_exact_token(token); + Ok(()) + })?; + Ok(()) } Err(error) => { - let stored = with_heap(host, |heap| Ok(heap.stores_token(raw)))?; - if !(stored && retired_lua_token(&error)) { + if !retired_lua_token(&error) { return Err(HeapError::from_scope(error)); } + let cleared = with_heap(host, |heap| Ok(heap.clear_exact_token(token)))?; + if cleared { + Ok(()) + } else { + Err(HeapError::from_scope(error)) + } } } - with_heap(host, |heap| { - heap.clear_token(raw); - Ok(()) - }) } fn retired_lua_token(error: &vm::HostContextError) -> bool { @@ -162,3 +174,8 @@ fn retired_lua_token(error: &vm::HostContextError) -> bool { pub fn stats(host: &mut HostContext) -> Result { with_heap(host, |heap| Ok(heap.stats())) } + +/// Reads and clears the scan counts from the scope heap. This does not collect. +pub fn take_scan_meter(host: &mut HostContext) -> Result { + with_heap(host, |heap| Ok(heap.take_scan_meter())) +} diff --git a/src/frontends/lua/heap/resource.rs b/src/frontends/lua/heap/resource.rs index aeb3a85..b5a52c3 100644 --- a/src/frontends/lua/heap/resource.rs +++ b/src/frontends/lua/heap/resource.rs @@ -4,9 +4,9 @@ //! VM carrier is the existing resource handle, validated by arena, type, and //! key. It does not store table fields and is not a GC root. -use vm::resource::HostResource; -use vm::host_extension::HostResourceType; use vm::ResourceTypeKey; +use vm::host_extension::HostResourceType; +use vm::resource::HostResource; use super::handle::TableRef; diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index ac4445e..9a99d5c 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -165,6 +165,39 @@ struct Frame { width: u32, } +/// Counts the loops one collect actually ran. +/// +/// Production keeps these counters. Each add sits on an edge or slot the +/// collector already visits. They are not a second graph, and reading them +/// does not sweep or close tokens. Host collection still closes tokens before +/// sweep; there is no public sweep that skips that close. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ScanMeter { + pub mark_passes: u64, + pub index_edge_checks: u64, + pub index_slot_checks: u64, + pub outgoing_edge_checks: u64, + pub sweep_edge_checks: u64, + pub token_slot_checks: u64, + pub token_closes: u64, +} + +/// A stored token identified while marking. Close checks this slot and +/// generation directly; it does not search the slot vector. +#[derive(Clone, Copy, Debug)] +pub(super) struct DoomedToken { + pub(super) raw: u64, + pub(super) slot: u32, + pub(super) generation: u32, +} + +/// Temporary outgoing-edge index for one mark. Dropped when mark returns. +/// Not stored on the heap, so it is not a second persistent graph. +struct OutgoingIndex { + offsets: Vec, + targets: Vec<(u32, u32)>, +} + /// One scope's table nodes, edges, roots, and scan state. pub struct LuaHeap { domain: u64, @@ -180,6 +213,7 @@ pub struct LuaHeap { peak_nodes: u32, peak_roots: u32, peak_edges: u32, + scan: ScanMeter, } impl LuaHeap { @@ -200,9 +234,17 @@ impl LuaHeap { peak_nodes: 0, peak_roots: 0, peak_edges: 0, + scan: ScanMeter::default(), } } + /// Returns the counts since the previous take and clears them. + pub fn take_scan_meter(&mut self) -> ScanMeter { + let meter = self.scan; + self.scan = ScanMeter::default(); + meter + } + /// Reserves a live, unrooted table. Failure leaves occupancy unchanged. pub fn alloc(&mut self) -> Result { if let Some(index) = self.free_list.pop() { @@ -273,7 +315,11 @@ impl LuaHeap { self.require_live(from)?; Ok(self.edges.iter().find_map(|edge| { if edge.from == from.slot() && edge.key == key { - Some(TableRef::table(self.domain, edge.to_slot, edge.to_generation)) + Some(TableRef::table( + self.domain, + edge.to_slot, + edge.to_generation, + )) } else { None } @@ -354,39 +400,69 @@ impl LuaHeap { Ok(()) } - /// Whether `raw` is the token currently stored on a node in this heap. - pub(super) fn stores_token(&self, raw: u64) -> bool { - self.slots.iter().any(|slot| slot.token == Some(raw)) + /// Clears the token stored on `table` without searching other slots. + /// Does not close a host resource and does not sweep. Collection uses + /// [`Self::clear_exact_token`] instead. + pub fn unbind_token(&mut self, table: TableRef) -> Result<(), HeapError> { + self.require_live(table)?; + self.slots[table.slot() as usize].token = None; + Ok(()) } - /// Drops the stored handle after the resource table has closed it. The - /// node stays until sweep. - pub fn clear_token(&mut self, raw: u64) { - for slot in &mut self.slots { - if slot.token == Some(raw) { - slot.token = None; - } + /// Records one close attempt. The attempt is counted even when close + /// returns an error, so a later retry can be metered on its own. + pub(super) fn note_token_close(&mut self) { + self.scan.token_closes += 1; + } + + /// Clears `token` only when that exact slot and generation still store it. + /// A reused slot, including a successor, is left alone. + pub(super) fn clear_exact_token(&mut self, token: DoomedToken) -> bool { + self.scan.token_slot_checks += 1; + let matches = self.slots.get(token.slot as usize).is_some_and(|slot| { + slot.generation == token.generation && slot.token == Some(token.raw) + }); + if !matches { + return false; } + self.scan.token_slot_checks += 1; + self.slots[token.slot as usize].token = None; + true } - /// Tokens of live nodes the current mark does not reach. Runs the same - /// mark as `collect` and does not release slots. - pub fn unmarked_tokens(&mut self) -> Vec { + /// Marks once and returns unreachable stored tokens with their slots. + /// Does not release nodes. The caller closes those tokens, then + /// [`Self::sweep_marked`] uses this same mark. + pub(super) fn mark_and_doomed_tokens(&mut self) -> Vec { self.mark_reachable(); self.slots .iter() - .filter_map(|slot| match slot.state { - SlotState::Live { marked: false } => slot.token, + .enumerate() + .filter_map(|(index, slot)| match slot.state { + SlotState::Live { marked: false } => slot.token.map(|raw| DoomedToken { + raw, + slot: index as u32, + generation: slot.generation, + }), _ => None, }) .collect() } - /// Non-moving mark from explicit roots, then sweep unmarked nodes. + /// Non-moving mark from explicit roots, then one sweep of unmarked nodes. /// Freed slots are reused with a bumped generation. A slot whose next /// generation would pass `max_generation` is retired instead. + /// + /// This is the pure-heap collector. A host heap must use `heap::collect`, + /// which closes tokens before [`Self::sweep_marked`]. Calling this on a + /// host heap would skip that close. pub fn collect(&mut self) -> CollectReport { self.mark_reachable(); + self.sweep_marked() + } + + /// Releases nodes the current mark did not reach. Does not mark again. + pub(super) fn sweep_marked(&mut self) -> CollectReport { let swept: Vec = self .slots .iter() @@ -401,9 +477,11 @@ impl LuaHeap { .iter() .filter(|slot| matches!(slot.state, SlotState::Live { marked: true })) .count() as u32; - for index in swept { - self.remove_edges_touching(index); - self.release_slot(index); + if !swept.is_empty() { + self.sweep_edges_once(); + for index in swept { + self.release_slot(index); + } } self.clear_dead_roots(); self.collections = self.collections.saturating_add(1); @@ -458,11 +536,13 @@ impl LuaHeap { } fn mark_reachable(&mut self) { + self.scan.mark_passes += 1; for slot in &mut self.slots { if let SlotState::Live { marked } = &mut slot.state { *marked = false; } } + let index = self.build_outgoing_index(); let mut work = Vec::new(); let rooted: Vec = self.roots.iter().copied().flatten().collect(); for handle in rooted { @@ -471,13 +551,10 @@ impl LuaHeap { } } while let Some(slot) = work.pop() { - let targets: Vec<(u32, u32)> = self - .edges - .iter() - .filter(|edge| edge.from == slot) - .map(|edge| (edge.to_slot, edge.to_generation)) - .collect(); - for (to_slot, to_generation) in targets { + let start = index.offsets[slot as usize] as usize; + let end = index.offsets[slot as usize + 1] as usize; + self.scan.outgoing_edge_checks += (end - start) as u64; + for &(to_slot, to_generation) in &index.targets[start..end] { if self.slot_live(to_slot, to_generation) { self.mark_slot(to_slot, &mut work); } @@ -485,6 +562,58 @@ impl LuaHeap { } } + /// Two passes over the stored edge vector, plus one pass over slots to + /// turn counts into offsets. The index is dropped at the end of mark. + fn build_outgoing_index(&mut self) -> OutgoingIndex { + let slot_count = self.slots.len(); + let edge_count = self.edges.len(); + self.scan.index_edge_checks += edge_count as u64; + let mut counts = vec![0u32; slot_count]; + for edge in &self.edges { + if let Some(count) = counts.get_mut(edge.from as usize) { + *count = count.saturating_add(1); + } + } + self.scan.index_slot_checks += slot_count as u64; + let mut offsets = Vec::with_capacity(slot_count + 1); + offsets.push(0); + let mut running = 0u32; + for count in &counts { + running = running.saturating_add(*count); + offsets.push(running); + } + self.scan.index_edge_checks += edge_count as u64; + let mut cursor = offsets.clone(); + let mut targets = vec![(0u32, 0u32); running as usize]; + for edge in &self.edges { + let from = edge.from as usize; + if from >= slot_count { + continue; + } + let at = cursor[from] as usize; + if at < targets.len() { + targets[at] = (edge.to_slot, edge.to_generation); + cursor[from] = cursor[from].saturating_add(1); + } + } + OutgoingIndex { offsets, targets } + } + + /// One filter of the edge vector. Skipped when every live node is marked, + /// so an all-live collect does not walk edges again. + fn sweep_edges_once(&mut self) { + let marked: Vec = self + .slots + .iter() + .map(|slot| matches!(slot.state, SlotState::Live { marked: true })) + .collect(); + self.scan.sweep_edge_checks += self.edges.len() as u64; + self.edges.retain(|edge| { + marked.get(edge.from as usize).copied().unwrap_or(false) + && marked.get(edge.to_slot as usize).copied().unwrap_or(false) + }); + } + fn mark_slot(&mut self, index: u32, work: &mut Vec) { if let SlotState::Live { marked } = &mut self.slots[index as usize].state { if !*marked { diff --git a/tests/luajit_heap_runtime/mod.rs b/tests/luajit_heap_runtime/mod.rs index a9ad422..1d4781a 100644 --- a/tests/luajit_heap_runtime/mod.rs +++ b/tests/luajit_heap_runtime/mod.rs @@ -6,10 +6,9 @@ use vm::compiler::ir::{ResolvedHostCall, ResolvedHostParam}; use vm::{ CallOutcome, CallReturn, CompileSourceFileOptions, Expr, FrontendImportSyntax, FrontendIr, HostApiBuilder, HostApiCatalog, HostFunctionRegistry, HostFunctionSchema, HostImportSchema, - HostOwnedFunction, HostParamPassing, HostParamSchema, HostStructField, - HostStructSchema, HostTypeSchema, LocalIrBuilder, LocalSlot, OwnedHostCall, ParseError, - ResourceTypeKey, ResourceTypeSchema, SourceFlavor, SourcePlugin, Stmt, TypeSchema, Value, - VmError, VmStatus, + HostOwnedFunction, HostParamPassing, HostParamSchema, HostStructField, HostStructSchema, + HostTypeSchema, LocalIrBuilder, LocalSlot, OwnedHostCall, ParseError, ResourceTypeKey, + ResourceTypeSchema, SourceFlavor, SourcePlugin, Stmt, TypeSchema, Value, VmError, VmStatus, }; use super::heap::{self, LuaTableResource, TableRef}; @@ -229,11 +228,7 @@ fn catalog() -> HostApiCatalog { ], HostTypeSchema::Resource(key.clone()), )); - builder.function(func( - "lua_heap_collect", - vec![], - HostTypeSchema::Int, - )); + builder.function(func("lua_heap_collect", vec![], HostTypeSchema::Int)); builder.function(func( "lua_heap_close", vec![HostParamSchema::with_passing( @@ -243,11 +238,7 @@ fn catalog() -> HostApiCatalog { )], HostTypeSchema::Int, )); - builder.function(func( - "lua_heap_forge_named", - vec![], - named.as_type(), - )); + builder.function(func("lua_heap_forge_named", vec![], named.as_type())); builder.function(func( "lua_heap_accept_named", vec![HostParamSchema::value("record", named.as_type())], @@ -278,18 +269,35 @@ fn func(name: &str, params: Vec, ret: HostTypeSchema) -> HostFu HostFunctionSchema::with_return(name, params, ret) } -fn register_hosts(registry: &mut HostFunctionRegistry, catalog: &HostApiCatalog) -> Result<(), VmError> { - register(registry, catalog, "lua_heap_publish", 0, |_| Box::new(Publish))?; +fn register_hosts( + registry: &mut HostFunctionRegistry, + catalog: &HostApiCatalog, +) -> Result<(), VmError> { + register(registry, catalog, "lua_heap_publish", 0, |_| { + Box::new(Publish) + })?; register(registry, catalog, "lua_heap_alive", 1, |_| Box::new(Alive))?; - register(registry, catalog, "lua_heap_observe", 2, |_| Box::new(Observe))?; - register(registry, catalog, "lua_heap_set_edge", 3, |_| Box::new(SetEdge))?; - register(registry, catalog, "lua_heap_edge_is", 3, |_| Box::new(EdgeIs))?; + register(registry, catalog, "lua_heap_observe", 2, |_| { + Box::new(Observe) + })?; + register(registry, catalog, "lua_heap_set_edge", 3, |_| { + Box::new(SetEdge) + })?; + register(registry, catalog, "lua_heap_edge_is", 3, |_| { + Box::new(EdgeIs) + })?; register(registry, catalog, "lua_heap_enter", 1, |_| Box::new(Enter))?; register(registry, catalog, "lua_heap_root", 2, |_| Box::new(Root))?; - register(registry, catalog, "lua_heap_collect", 0, |_| Box::new(Collect))?; + register(registry, catalog, "lua_heap_collect", 0, |_| { + Box::new(Collect) + })?; register(registry, catalog, "lua_heap_close", 1, |_| Box::new(Close))?; - register(registry, catalog, "lua_heap_forge_named", 0, |_| Box::new(ForgeNamed))?; - register(registry, catalog, "lua_heap_accept_named", 1, |_| Box::new(AcceptNamed))?; + register(registry, catalog, "lua_heap_forge_named", 0, |_| { + Box::new(ForgeNamed) + })?; + register(registry, catalog, "lua_heap_accept_named", 1, |_| { + Box::new(AcceptNamed) + })?; Ok(()) } @@ -336,7 +344,9 @@ impl HostOwnedFunction for Alive { let table = recover(call, 0)?; let mut host = call.vm().host_context(); let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).map_err(host_error)?; - Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from(alive))))) + Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from( + alive, + ))))) } } @@ -381,7 +391,9 @@ impl HostOwnedFunction for EdgeIs { let mut host = call.vm().host_context(); let same = heap::with_heap(&mut host, |heap| Ok(heap.edge(from, key) == Ok(Some(to)))) .map_err(host_error)?; - Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from(same))))) + Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from( + same, + ))))) } } @@ -418,9 +430,9 @@ impl HostOwnedFunction for Collect { let mut host = call.vm().host_context(); note_body(&mut host); let marked = heap::collect(&mut host).map_err(host_error)?; - Ok(CallOutcome::Return(CallReturn::one(Value::Int( - i64::from(marked.live_nodes), - )))) + Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from( + marked.live_nodes, + ))))) } } @@ -451,7 +463,9 @@ impl HostOwnedFunction for AcceptNamed { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { let (slot, generation) = { let Value::Map(map) = &call.args()[0] else { - return Err(VmError::HostError("named carrier was not a map".to_string())); + return Err(VmError::HostError( + "named carrier was not a map".to_string(), + )); }; (map_int(map, "slot")?, map_int(map, "generation")?) }; @@ -474,9 +488,11 @@ fn map_int(map: &vm::bytecode::VmMap, key: &str) -> Result { } fn recover(call: &mut OwnedHostCall<'_>, index: usize) -> Result { - let value = call.args().get(index).cloned().ok_or_else(|| { - VmError::HostError(format!("missing argument {index}")) - })?; + let value = call + .args() + .get(index) + .cloned() + .ok_or_else(|| VmError::HostError(format!("missing argument {index}")))?; let Value::Int(raw) = value else { return Err(VmError::HostError( "table carrier is not a resource handle".to_string(), @@ -485,8 +501,8 @@ fn recover(call: &mut OwnedHostCall<'_>, index: usize) -> Result(handle, &LuaTableResource::key()) @@ -499,7 +515,9 @@ fn int_arg(call: &OwnedHostCall<'_>, index: usize) -> Result { Some(Value::Int(value)) if *value >= 0 && *value <= i64::from(u32::MAX) => { Ok(*value as u32) } - _ => Err(VmError::HostError(format!("argument {index} is not a field index"))), + _ => Err(VmError::HostError(format!( + "argument {index} is not a field index" + ))), } } @@ -656,10 +674,7 @@ fn hosts_for(source: &str) -> &'static [(&'static str, u8)] { ("lua_heap_close", 1), ("lua_heap_alive", 1), ], - "named" => &[ - ("lua_heap_forge_named", 0), - ("lua_heap_accept_named", 1), - ], + "named" => &[("lua_heap_forge_named", 0), ("lua_heap_accept_named", 1)], "nested-rooted" => &[ ("lua_heap_enter", 1), ("lua_heap_publish", 0), @@ -692,7 +707,11 @@ fn resolution(catalog: &HostApiCatalog, name: &str) -> ResolvedHostCall { return_type: type_schema(&function.return_type), passing: function.params.iter().map(|param| param.passing).collect(), fingerprint: catalog.fingerprint(), - host_params: function.params.iter().map(|param| param.ty.clone()).collect(), + host_params: function + .params + .iter() + .map(|param| param.ty.clone()) + .collect(), host_return_type: function.return_type.clone(), } } diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index a5191b6..79f22dd 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -10,7 +10,9 @@ mod heap; #[path = "luajit_heap_runtime/mod.rs"] mod support; -use heap::{CollectReport, HandleKind, HeapLimits, LuaHeap, LuaTableResource, RootFrameId, TableRef}; +use heap::{ + CollectReport, HandleKind, HeapLimits, LuaHeap, LuaTableResource, RootFrameId, TableRef, +}; use support::{Probe, run_probe, with_idle_vm}; use vm::{HostContext, ResourceHandle, Value}; @@ -38,13 +40,20 @@ fn alias_write_collect_reuse_and_hard_caps_stay_inside_one_heap() { assert_eq!(unrooted.live_nodes, 0, "an edge is not a root"); assert!(!heap.alive(left)); assert!(!heap.alive(right)); - assert!(heap.edge(left, 1).is_err(), "a stale source is not a readable edge"); + assert!( + heap.edge(left, 1).is_err(), + "a stale source is not a readable edge" + ); let reused = heap.alloc().expect("reuse freed slot"); assert_eq!(reused.slot(), right.slot()); assert_ne!(reused.generation(), right.generation()); assert!(!heap.alive(right), "stale generation stays dead"); - assert_eq!(heap.stats().node_slots, 2, "reuse must not grow slot storage"); + assert_eq!( + heap.stats().node_slots, + 2, + "reuse must not grow slot storage" + ); let dropped = heap.alloc().expect("second reuse"); let frame: RootFrameId = heap.enter_roots(1).expect("frame"); @@ -78,7 +87,8 @@ fn failed_alloc_and_rollback_do_not_grow_live_storage() { assert!(!heap.alive(first)); assert_eq!(heap.stats().live_nodes, 0); assert_eq!( - heap.stats().node_slots, 1, + heap.stats().node_slots, + 1, "the slot stays for reuse, but it is not a live node" ); let again = heap.alloc().expect("reuse after rollback"); @@ -109,7 +119,11 @@ fn generation_exhaustion_retires_the_slot_instead_of_wrapping() { assert!(heap.alloc().is_err(), "retired slot is not reused"); assert!(!heap.alive(once)); assert_eq!(heap.stats().live_nodes, 0); - assert_eq!(heap.stats().node_slots, 1, "retired storage remains, but is not live"); + assert_eq!( + heap.stats().node_slots, + 1, + "retired storage remains, but is not live" + ); } #[test] @@ -129,7 +143,8 @@ fn cyclic_create_and_collect_tracks_live_nodes_and_roots() { heap.write_root(frame, 0, kept).expect("root"); let orphan = heap.alloc().expect("orphan"); let orphan_link = heap.alloc().expect("orphan link"); - heap.set_edge(orphan, 1, orphan_link).expect("orphan forward"); + heap.set_edge(orphan, 1, orphan_link) + .expect("orphan forward"); heap.set_edge(orphan_link, 1, orphan).expect("orphan back"); let marked = heap.collect(); assert_eq!( @@ -143,7 +158,11 @@ fn cyclic_create_and_collect_tracks_live_nodes_and_roots() { assert_eq!(heap.collect().live_nodes, 0); assert_eq!(heap.stats().live_roots, 0); } - assert_eq!(heap.stats().node_slots, 4, "later rounds reuse the first four slots"); + assert_eq!( + heap.stats().node_slots, + 4, + "later rounds reuse the first four slots" + ); assert!(heap.stats().peak_roots <= 4); } @@ -160,11 +179,18 @@ fn a_handle_from_another_heap_is_rejected() { fn typed_resource_boundary_rejects_int_foreign_and_expired_values() { let transfer = run_probe(Probe::Transfer).expect("transfer"); assert_eq!(transfer.stack, vec![Value::Int(1)]); - assert!(transfer.body_entries > 0, "typed host body ran for a published table"); + assert!( + transfer.body_entries > 0, + "typed host body ran for a published table" + ); assert!(transfer.alive_entries > 0, "alive ran inside the same VM"); let alias = run_probe(Probe::Alias).expect("alias"); - assert_eq!(alias.stack, vec![Value::Int(1)], "same table write is visible through the other handle"); + assert_eq!( + alias.stack, + vec![Value::Int(1)], + "same table write is visible through the other handle" + ); let before_int = run_probe(Probe::RejectInt).expect_err("ordinary int is not a table"); assert_eq!( @@ -174,16 +200,22 @@ fn typed_resource_boundary_rejects_int_foreign_and_expired_values() { assert_eq!(before_int.alive_entries, 0); let published = run_probe(Probe::Publish).expect("publish handle"); - assert_eq!(published.published_raw, published.stack.first().and_then(|value| match value { - Value::Int(raw) => Some(*raw), - _ => None, - })); + assert_eq!( + published.published_raw, + published.stack.first().and_then(|value| match value { + Value::Int(raw) => Some(*raw), + _ => None, + }) + ); let raw = match published.stack.as_slice() { [Value::Int(raw)] => *raw, other => panic!("publish did not return one handle: {other:?}"), }; let foreign = run_probe(Probe::RejectForeign { raw }).expect_err("cross-vm handle is rejected"); - assert_eq!(foreign.body_entries, 0, "foreign rejection is before the host body"); + assert_eq!( + foreign.body_entries, 0, + "foreign rejection is before the host body" + ); assert_eq!(foreign.alive_entries, 0); let expired = run_probe(Probe::Expired).expect_err("expired handle is rejected"); @@ -255,11 +287,13 @@ fn full_resource_table_publish_occupies_a_slot_then_rolls_it_back() { "refused publish must occupy a lua slot before push_resource returns; error={error}" ); assert_eq!( - after.live_nodes, - before.live_nodes, + after.live_nodes, before.live_nodes, "rollback must release the occupied slot; error={error}" ); - assert_eq!(after.live_roots, before.live_roots, "existing roots must stay"); + assert_eq!( + after.live_roots, before.live_roots, + "existing roots must stay" + ); assert!( heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("rooted check"), "the existing root stays live" @@ -339,17 +373,11 @@ fn collect_finishes_when_an_unreused_token_is_already_closed() { let other_handle = resource_handle(other_raw); let progress = host - .close_resource::( - retired_handle, - vm::ResourceCloseReason::Requested, - ) + .close_resource::(retired_handle, vm::ResourceCloseReason::Requested) .expect("external close"); assert_eq!(progress, vm::resource::CloseProgress::Ready); let observed = host - .close_resource::( - retired_handle, - vm::ResourceCloseReason::Requested, - ) + .close_resource::(retired_handle, vm::ResourceCloseReason::Requested) .expect_err("slot was not reused"); assert_eq!( scope_resource_code(&observed), @@ -359,13 +387,21 @@ fn collect_finishes_when_an_unreused_token_is_already_closed() { heap::with_heap(&mut host, |heap| Ok(heap.alive(retired))).expect("retired node"), "the lua node still stores the closed token" ); - assert_eq!(host.resource_count(), 3, "close already returned one quota unit"); + assert_eq!( + host.resource_count(), + 3, + "close already returned one quota unit" + ); assert_eq!(heap::stats(&mut host).expect("before").live_nodes, 3); let report = heap::collect(&mut host) .expect("an already-closed stored token must not stop collection"); assert_eq!(report.live_nodes, 1); - assert_eq!(host.resource_count(), 2, "only the other doomed token is closed"); + assert_eq!( + host.resource_count(), + 2, + "only the other doomed token is closed" + ); assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("rooted")); assert!( host.typed_resource_with_key::( @@ -376,11 +412,17 @@ fn collect_finishes_when_an_unreused_token_is_already_closed() { "the rooted token stays valid" ); assert!( - host.typed_resource_with_key::(other_handle, &LuaTableResource::key()) - .is_err(), + host.typed_resource_with_key::( + other_handle, + &LuaTableResource::key() + ) + .is_err(), "the other unreachable table is collected" ); - assert!(host.resource(&unrelated).is_ok(), "unrelated resource stays"); + assert!( + host.resource(&unrelated).is_ok(), + "unrelated resource stays" + ); assert!( host.scope_state::().is_some(), "collection must not replace the scope with reset" @@ -388,10 +430,17 @@ fn collect_finishes_when_an_unreused_token_is_already_closed() { let again = heap::collect(&mut host).expect("a later collection must also finish"); assert_eq!(again.live_nodes, 1); - assert_eq!(host.resource_count(), 2, "the second collection must not release quota again"); + assert_eq!( + host.resource_count(), + 2, + "the second collection must not release quota again" + ); assert_eq!(heap::stats(&mut host).expect("after").collections, 2); assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("root remains")); - assert!(host.resource(&unrelated).is_ok(), "unrelated resource remains"); + assert!( + host.resource(&unrelated).is_ok(), + "unrelated resource remains" + ); }); } @@ -429,10 +478,7 @@ fn collect_finishes_when_a_reused_token_is_stale() { ); assert_ne!(retired_handle.generation(), successor_handle.generation()); let observed = host - .close_resource::( - retired_handle, - vm::ResourceCloseReason::Requested, - ) + .close_resource::(retired_handle, vm::ResourceCloseReason::Requested) .expect_err("reused slot"); assert_eq!( scope_resource_code(&observed), @@ -448,8 +494,8 @@ fn collect_finishes_when_a_reused_token_is_stale() { assert_eq!(host.resource_count(), 4); assert_eq!(heap::stats(&mut host).expect("before").live_nodes, 4); - let report = heap::collect(&mut host) - .expect("a stale stored token must not stop collection"); + let report = + heap::collect(&mut host).expect("a stale stored token must not stop collection"); assert_eq!(report.live_nodes, 2, "rooted table and successor stay"); assert_eq!( host.resource_count(), @@ -464,11 +510,17 @@ fn collect_finishes_when_a_reused_token_is_stale() { assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(successor))).expect("successor")); assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("rooted")); assert!( - host.typed_resource_with_key::(other_handle, &LuaTableResource::key()) - .is_err(), + host.typed_resource_with_key::( + other_handle, + &LuaTableResource::key() + ) + .is_err(), "the other unreachable table is collected" ); - assert!(host.resource(&unrelated).is_ok(), "unrelated resource stays"); + assert!( + host.resource(&unrelated).is_ok(), + "unrelated resource stays" + ); assert!( host.scope_state::().is_some(), "collection must not replace the scope with reset" @@ -476,11 +528,21 @@ fn collect_finishes_when_a_reused_token_is_stale() { let again = heap::collect(&mut host).expect("a later collection must also finish"); assert_eq!(again.live_nodes, 2); - assert_eq!(host.resource_count(), 3, "the second collection must not release quota again"); + assert_eq!( + host.resource_count(), + 3, + "the second collection must not release quota again" + ); assert_eq!(heap::stats(&mut host).expect("after").collections, 2); - assert_eq!(table_ref(&host, successor_raw).generation(), successor.generation()); + assert_eq!( + table_ref(&host, successor_raw).generation(), + successor.generation() + ); assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("root remains")); - assert!(host.resource(&unrelated).is_ok(), "unrelated resource remains"); + assert!( + host.resource(&unrelated).is_ok(), + "unrelated resource remains" + ); }); } @@ -625,12 +687,19 @@ fn reset_for_reuse_rejects_old_handles_and_starts_an_empty_heap() { resource_handle(raw), &LuaTableResource::key(), ); - assert!(rejected.is_err(), "old handle must be rejected: {rejected:?}"); + assert!( + rejected.is_err(), + "old handle must be rejected: {rejected:?}" + ); assert!( host.scope_state::().is_none(), "the replacement scope starts without a heap" ); - assert_eq!(host.resource_count(), 0, "the new scope has no leftover tokens"); + assert_eq!( + host.resource_count(), + 0, + "the new scope has no leftover tokens" + ); heap::install( &mut host, HeapLimits { @@ -647,3 +716,644 @@ fn reset_for_reuse_rejects_old_handles_and_starts_an_empty_heap() { let _again = publish_raw(&mut host); }); } + +struct ScanShape { + name: &'static str, + nodes: u32, + roots: u32, + edges: u32, + reachable: u32, + edges_in_live: bool, +} + +fn scan_shape( + name: &'static str, + nodes: u32, + roots: u32, + edges: u32, + reachable: u32, + edges_in_live: bool, +) -> ScanShape { + ScanShape { + name, + nodes, + roots, + edges, + reachable, + edges_in_live, + } +} + +fn plan_scan_edges(shape: &ScanShape) -> Vec<(u32, u32, u32)> { + let mut next_key = vec![1u32; shape.nodes as usize]; + let mut edges = Vec::with_capacity(shape.edges as usize); + if shape.edges_in_live { + let spanning = shape.reachable - shape.roots; + assert!( + shape.edges >= spanning, + "{} needs {spanning} spanning edges", + shape.name + ); + for index in shape.roots..shape.reachable { + let from = index - 1; + let key = next_key[from as usize]; + next_key[from as usize] = key + 1; + edges.push((from, key, index)); + } + let mut round = 0u32; + while edges.len() < shape.edges as usize { + let from = round % shape.reachable; + let to = (round + 1) % shape.reachable; + let key = next_key[from as usize]; + next_key[from as usize] = key + 1; + edges.push((from, key, to)); + round += 1; + assert!( + round <= shape.edges + shape.reachable + 4, + "{} live plan stalled", + shape.name + ); + } + } else { + let dead = shape.nodes - shape.reachable; + assert!(dead > 0, "{} dead-home needs a dead node", shape.name); + let mut round = 0u32; + while edges.len() < shape.edges as usize { + let from = shape.reachable + (round % dead); + let to = shape.reachable + ((round + 1) % dead); + let key = next_key[from as usize]; + next_key[from as usize] = key + 1; + edges.push((from, key, to)); + round += 1; + assert!( + round <= shape.edges + dead + 4, + "{} dead plan stalled", + shape.name + ); + } + } + assert_eq!( + edges.len(), + shape.edges as usize, + "{} edge plan", + shape.name + ); + edges +} + +fn reachable_outgoing(shape: &ScanShape, plan: &[(u32, u32, u32)]) -> u64 { + plan.iter() + .filter(|(from, _, _)| *from < shape.reachable) + .count() as u64 +} + +/// The meter is the observation. Graph size is only the budget, not a stand-in +/// for the counts. +fn assert_linear_meter( + label: &str, + meter: &heap::ScanMeter, + slots: u64, + edges: u64, + outgoing: u64, + dead: u64, + doomed_tokens: u64, +) { + assert_eq!( + meter.mark_passes, + 1, + "{label} marks once (outgoing={} budget={outgoing} sweep={} token_slots={} closes={} index_edges={})", + meter.outgoing_edge_checks, + meter.sweep_edge_checks, + meter.token_slot_checks, + meter.token_closes, + meter.index_edge_checks + ); + assert_eq!( + meter.outgoing_edge_checks, outgoing, + "{label} outgoing checks must be the visited edges; a full walk of reachable*edges exceeds this budget of {outgoing} (mark_passes={} sweep={} token_slots={})", + meter.mark_passes, meter.sweep_edge_checks, meter.token_slot_checks + ); + assert_eq!( + meter.index_edge_checks, + edges.saturating_mul(2), + "{label} index build examines each stored edge twice" + ); + assert_eq!( + meter.index_slot_checks, slots, + "{label} index build examines each slot once" + ); + let sweep_budget = if dead == 0 { 0 } else { edges }; + assert_eq!( + meter.sweep_edge_checks, sweep_budget, + "{label} sweep filters the edge vector once" + ); + assert_eq!(meter.token_closes, doomed_tokens, "{label} closes"); + assert!( + meter.token_slot_checks <= doomed_tokens.saturating_mul(3), + "{label} token slot checks {} are not direct lookups for {doomed_tokens} tokens (slots={slots})", + meter.token_slot_checks + ); +} + +fn assert_pure_kept( + heap: &LuaHeap, + nodes: &[TableRef], + shape: &ScanShape, + plan: &[(u32, u32, u32)], +) { + assert_eq!( + heap.stats().live_nodes, + shape.reachable, + "{} live nodes", + shape.name + ); + assert_eq!( + heap.stats().live_roots, + shape.roots, + "{} live roots", + shape.name + ); + for index in 0..shape.reachable { + assert!( + heap.alive(nodes[index as usize]), + "{} root region stays", + shape.name + ); + } + for index in shape.reachable..shape.nodes { + assert!( + !heap.alive(nodes[index as usize]), + "{} dead region is collected", + shape.name + ); + } + if let Some((from, key, to)) = plan.iter().find(|(from, _, _)| *from < shape.reachable) { + assert_eq!( + heap.edge(nodes[*from as usize], *key).expect("kept edge"), + Some(nodes[*to as usize]), + "{} kept edge", + shape.name + ); + } +} + +fn collect_pure_shape(shape: &ScanShape) { + let mut heap = LuaHeap::new(HeapLimits::production()); + let mut nodes = Vec::with_capacity(shape.nodes as usize); + for _ in 0..shape.nodes { + nodes.push( + heap.alloc() + .unwrap_or_else(|error| panic!("{} alloc: {error}", shape.name)), + ); + } + let frame = heap + .enter_roots(shape.roots) + .unwrap_or_else(|error| panic!("{} roots: {error}", shape.name)); + for index in 0..shape.roots { + heap.write_root(frame, index, nodes[index as usize]) + .unwrap_or_else(|error| panic!("{} root: {error}", shape.name)); + } + let plan = plan_scan_edges(shape); + for (from, key, to) in &plan { + heap.set_edge(nodes[*from as usize], *key, nodes[*to as usize]) + .unwrap_or_else(|error| panic!("{} edge: {error}", shape.name)); + } + let before = heap.stats(); + let started = std::time::Instant::now(); + let report = heap.collect(); + if std::env::var_os("LUA_HEAP_TIME_COLLECT").is_some() { + eprintln!("time {} nanos={}", shape.name, started.elapsed().as_nanos()); + } + let meter = heap.take_scan_meter(); + eprintln!( + "meter {} mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={}", + shape.name, + meter.mark_passes, + meter.index_edge_checks, + meter.index_slot_checks, + meter.outgoing_edge_checks, + meter.sweep_edge_checks, + meter.token_slot_checks, + meter.token_closes + ); + assert_eq!(report.live_nodes, shape.reachable, "{}", shape.name); + assert_eq!(report.marked_nodes, shape.reachable, "{}", shape.name); + assert_pure_kept(&heap, &nodes, shape, &plan); + assert_linear_meter( + shape.name, + &meter, + u64::from(before.node_slots), + u64::from(before.live_edges), + reachable_outgoing(shape, &plan), + u64::from(shape.nodes - shape.reachable), + 0, + ); +} + +fn collect_host_shape(shape: &ScanShape, share_resource: bool) { + let token_cap = vm::resource::handle::DEFAULT_MAX_RESOURCES; + let published = if share_resource { + shape.nodes as usize + 1 + } else { + shape.nodes as usize + }; + assert!( + published <= token_cap, + "{} uses {published} resources, cap is {token_cap}", + shape.name + ); + with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, HeapLimits::production()).expect("install"); + let unrelated = if share_resource { + Some( + host.push_resource(UnrelatedHostResource) + .expect("shared resource"), + ) + } else { + None + }; + let mut nodes = Vec::with_capacity(shape.nodes as usize); + let mut raws = Vec::with_capacity(shape.nodes as usize); + for _ in 0..shape.nodes { + let raw = publish_raw(&mut host); + nodes.push(table_ref(&host, raw)); + raws.push(raw); + } + let frame = heap::with_heap(&mut host, |heap| heap.enter_roots(shape.roots)) + .unwrap_or_else(|error| panic!("{} roots: {error}", shape.name)); + for index in 0..shape.roots { + let handle = nodes[index as usize]; + heap::with_heap(&mut host, |heap| heap.write_root(frame, index, handle)) + .unwrap_or_else(|error| panic!("{} root: {error}", shape.name)); + } + let plan = plan_scan_edges(shape); + for (from, key, to) in &plan { + let source = nodes[*from as usize]; + let target = nodes[*to as usize]; + heap::with_heap(&mut host, |heap| heap.set_edge(source, *key, target)) + .unwrap_or_else(|error| panic!("{} edge: {error}", shape.name)); + } + let before = heap::stats(&mut host).expect("before"); + let resources_before = host.resource_count(); + let started = std::time::Instant::now(); + let report = heap::collect(&mut host) + .unwrap_or_else(|error| panic!("{} collect: {error}", shape.name)); + if std::env::var_os("LUA_HEAP_TIME_COLLECT").is_some() { + eprintln!("time {} nanos={}", shape.name, started.elapsed().as_nanos()); + } + let resources_after = host.resource_count(); + let meter = heap::take_scan_meter(&mut host).expect("meter"); + eprintln!( + "meter {} mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={}", + shape.name, + meter.mark_passes, + meter.index_edge_checks, + meter.index_slot_checks, + meter.outgoing_edge_checks, + meter.sweep_edge_checks, + meter.token_slot_checks, + meter.token_closes + ); + let shared = usize::from(share_resource); + assert_eq!(report.live_nodes, shape.reachable, "{}", shape.name); + assert_eq!(report.marked_nodes, shape.reachable, "{}", shape.name); + assert_eq!( + resources_after, + shape.reachable as usize + shared, + "{} quota", + shape.name + ); + if shape.reachable < shape.nodes { + assert!( + resources_before > resources_after, + "{} tokens drop", + shape.name + ); + } else { + assert_eq!( + resources_before, resources_after, + "{} keeps every token", + shape.name + ); + } + for index in 0..shape.reachable { + assert!( + host.typed_resource_with_key::( + resource_handle(raws[index as usize]), + &LuaTableResource::key(), + ) + .is_ok(), + "{} rooted token stays", + shape.name + ); + } + if shape.nodes > shape.reachable { + let doomed = resource_handle(raws[shape.reachable as usize]); + assert!( + host.typed_resource_with_key::(doomed, &LuaTableResource::key()) + .is_err(), + "{} collected token is invalid", + shape.name + ); + } + if let Some(unrelated) = unrelated { + assert!( + host.resource(&unrelated).is_ok(), + "{} shared resource stays", + shape.name + ); + } + heap::with_heap(&mut host, |heap| { + assert_pure_kept(heap, &nodes, shape, &plan); + Ok(()) + }) + .expect("kept"); + assert_linear_meter( + shape.name, + &meter, + u64::from(before.node_slots), + u64::from(before.live_edges), + reachable_outgoing(shape, &plan), + u64::from(shape.nodes - shape.reachable), + u64::from(shape.nodes - shape.reachable), + ); + }); +} + +#[test] +fn collect_scan_small_graph_stays_inside_one_linear_pass() { + let pure = scan_shape("small-survival", 8, 2, 12, 4, true); + collect_pure_shape(&pure); + let host = scan_shape("small-host-death", 8, 1, 12, 2, true); + collect_host_shape(&host, true); +} + +#[test] +fn collect_scan_pure_limit_graphs_stay_linear() { + let limits = HeapLimits::production(); + collect_pure_shape(&scan_shape( + "limit-survival-all", + limits.nodes, + limits.roots, + limits.edges, + limits.nodes, + true, + )); + collect_pure_shape(&scan_shape( + "limit-death-live-edges", + limits.nodes, + 1, + limits.edges, + 16, + true, + )); + collect_pure_shape(&scan_shape( + "limit-death-dead-edges", + limits.nodes, + 1, + limits.edges, + 1, + false, + )); +} + +#[test] +fn collect_scan_host_limit_graphs_stay_linear() { + let token_cap = u32::try_from(vm::resource::handle::DEFAULT_MAX_RESOURCES).expect("cap"); + let edges = HeapLimits::production().edges; + collect_host_shape( + &scan_shape( + "token-cap-survival-all", + token_cap, + 256, + edges, + token_cap, + true, + ), + false, + ); + collect_host_shape( + &scan_shape("token-cap-death-live-edges", token_cap, 1, edges, 4, true), + false, + ); + collect_host_shape( + &scan_shape( + "token-cap-shared-death-dead-edges", + token_cap - 1, + 1, + edges, + 1, + false, + ), + true, + ); +} + +/// AlreadyClosed and Stale still retire only this heap's exact token. The +/// lookup is the identified slot, not a scan of every slot. +#[test] +fn collect_scan_retired_tokens_check_the_identified_slot() { + with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, sweep_limits()).expect("install"); + let unrelated = host + .push_resource(UnrelatedHostResource) + .expect("unrelated"); + let rooted_raw = publish_raw(&mut host); + let rooted = table_ref(&host, rooted_raw); + root_table(&mut host, rooted); + let mut filler = Vec::new(); + for _ in 0..6 { + filler.push(publish_raw(&mut host)); + } + let closed_raw = filler[0]; + let closed = table_ref(&host, closed_raw); + let closed_handle = resource_handle(closed_raw); + host.close_resource::(closed_handle, vm::ResourceCloseReason::Requested) + .expect("external close"); + let stale_raw = filler[1]; + let stale = table_ref(&host, stale_raw); + let stale_handle = resource_handle(stale_raw); + let _taken = host + .take_resource::(stale_handle) + .expect("take"); + let successor_raw = publish_raw(&mut host); + let successor = table_ref(&host, successor_raw); + root_table(&mut host, successor); + assert_eq!( + stale_handle.slot_index().expect("stale slot"), + resource_handle(successor_raw) + .slot_index() + .expect("successor slot") + ); + + let before_slots = heap::stats(&mut host).expect("slots").node_slots; + let report = heap::collect(&mut host).expect("retired tokens do not stop collection"); + let meter = heap::take_scan_meter(&mut host).expect("meter"); + eprintln!( + "meter retired-slot mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={} slots={}", + meter.mark_passes, + meter.index_edge_checks, + meter.index_slot_checks, + meter.outgoing_edge_checks, + meter.sweep_edge_checks, + meter.token_slot_checks, + meter.token_closes, + before_slots + ); + assert!( + before_slots > 3, + "the slot vector must be wider than a direct lookup" + ); + assert_eq!(report.live_nodes, 2, "rooted table and successor stay"); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(rooted))).expect("rooted")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(successor))).expect("successor")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(closed))).expect("closed node")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(stale))).expect("stale node")); + assert!( + host.resource(&unrelated).is_ok(), + "unrelated resource stays" + ); + assert!( + host.typed_resource_with_key::( + resource_handle(successor_raw), + &LuaTableResource::key(), + ) + .is_ok(), + "successor token stays usable" + ); + assert!( + meter.token_slot_checks <= meter.token_closes.saturating_mul(3), + "retired close checked {} slots for {} closes; a full scan of {before_slots} slots would exceed this", + meter.token_slot_checks, + meter.token_closes + ); + assert_eq!(meter.mark_passes, 1, "retired close still marks once"); + }); +} + +/// A non-retired close error leaves the swept prefix closed, does not sweep, +/// and the next collect marks again. A node rooted after the failure stays. +#[test] +fn collect_scan_failed_close_retries_after_remark() { + with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, sweep_limits()).expect("install"); + let unrelated = host + .push_resource(UnrelatedHostResource) + .expect("unrelated"); + let unrelated_raw = unrelated.handle().raw(); + let keeper_raw = publish_raw(&mut host); + let keeper = table_ref(&host, keeper_raw); + root_table(&mut host, keeper); + let prefix_raw = publish_raw(&mut host); + let prefix = table_ref(&host, prefix_raw); + let other_raw = publish_raw(&mut host); + let other = table_ref(&host, other_raw); + let doomed = heap::with_heap(&mut host, |heap| { + let node = heap.alloc()?; + heap.bind_token(node, unrelated_raw)?; + Ok(node) + }) + .expect("bind a foreign token"); + let before_nodes = heap::stats(&mut host).expect("before").live_nodes; + let before_resources = host.resource_count(); + + let error = heap::collect(&mut host).expect_err("type mismatch must propagate"); + match &error { + heap::HeapError::Scope(message) => { + assert!( + message.contains("resource_type_mismatch"), + "other close errors propagate, got {message}" + ); + } + other => panic!("expected a scope close error, got {other:?}"), + } + let failed = heap::take_scan_meter(&mut host).expect("failed meter"); + eprintln!( + "meter failed-close mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={}", + failed.mark_passes, + failed.index_edge_checks, + failed.index_slot_checks, + failed.outgoing_edge_checks, + failed.sweep_edge_checks, + failed.token_slot_checks, + failed.token_closes + ); + assert_eq!( + heap::stats(&mut host).expect("after error").live_nodes, + before_nodes + ); + assert_eq!(heap::stats(&mut host).expect("collections").collections, 0); + assert_eq!( + failed.sweep_edge_checks, 0, + "an incomplete collect does not sweep" + ); + assert_eq!(failed.mark_passes, 1); + assert!( + failed.token_slot_checks <= failed.token_closes.saturating_mul(3), + "the failed close checked {} slots for {} closes; a direct lookup stays within 3 per close", + failed.token_slot_checks, + failed.token_closes + ); + assert!( + host.resource(&unrelated).is_ok(), + "the foreign resource is not closed" + ); + assert!( + host.typed_resource_with_key::( + resource_handle(prefix_raw), + &LuaTableResource::key(), + ) + .is_err(), + "the successful prefix stays closed" + ); + assert!( + host.typed_resource_with_key::( + resource_handle(other_raw), + &LuaTableResource::key(), + ) + .is_err(), + "the second prefix token stays closed" + ); + assert_eq!(host.resource_count(), before_resources - 2); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(prefix))).expect("prefix node")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(doomed))).expect("doomed node")); + + heap::with_heap(&mut host, |heap| heap.unbind_token(doomed)) + .expect("drop the foreign token binding"); + root_table(&mut host, prefix); + let report = heap::collect(&mut host).expect("retry after the token is exact again"); + let retry = heap::take_scan_meter(&mut host).expect("retry meter"); + eprintln!( + "meter retry mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={}", + retry.mark_passes, + retry.index_edge_checks, + retry.index_slot_checks, + retry.outgoing_edge_checks, + retry.sweep_edge_checks, + retry.token_slot_checks, + retry.token_closes + ); + assert_eq!(retry.mark_passes, 1, "the retry marks again"); + assert_eq!( + report.live_nodes, 2, + "keeper and the newly rooted prefix stay" + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(keeper))).expect("keeper")); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(prefix))).expect("remarked prefix") + ); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(other))).expect("other swept")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(doomed))).expect("doomed swept")); + assert!(host.resource(&unrelated).is_ok(), "shared resource remains"); + assert!( + host.typed_resource_with_key::( + resource_handle(keeper_raw), + &LuaTableResource::key(), + ) + .is_ok() + ); + }); +} From 9f90bad6a6deccf2a9daaff2cd5f4aab352bad07 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 08:41:33 +0800 Subject: [PATCH 023/225] fix(lua): account collect slot walks and failed-close retries Record the node-slot and root-slot visits a full collect already makes, and the scratch requests those passes measure. A close failure keeps the closed prefix, leaves the suffix open, and a later collect marks again from the current roots. --- src/frontends/lua/heap.rs | 16 +- src/frontends/lua/heap/table.rs | 149 +++++++++--- tests/luajit_heap_runtime_tests.rs | 351 ++++++++++++++++++++++------- 3 files changed, 398 insertions(+), 118 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 8b607aa..9501853 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -109,8 +109,14 @@ pub fn with_heap( /// are retired: the identified slot is cleared and the sweep continues. A /// successor in a reused core slot is not closed, and a different lua slot is /// not cleared. Any other structured error, including a wrong table or a type -/// mismatch, stops the sweep. Tokens already cleared stay cleared. The sweep -/// does not run, so a later collection marks again and retries the remainder. +/// mismatch, returns immediately. Tokens already cleared stay cleared. Tokens +/// not yet closed stay open, including every token after the failing one. +/// Sweep does not run, so those nodes stay allocated and the scope quota for +/// the unclosed suffix is not returned. A later collection marks again from +/// the current roots. It does not resume after the failing token. If that +/// token is still bound, the later collection can fail again at the same +/// obstacle, and it does not close the suffix or return the prefix quota a +/// second time. Removing the obstacle is outside this collector. /// /// `LuaTableResource` uses the default synchronous close, which returns Ready. /// A Pending result is an error. This type has no path that starts an @@ -170,12 +176,14 @@ fn retired_lua_token(error: &vm::HostContextError) -> bool { } } -/// Reads occupancy counters from the scope heap. +/// Reads occupancy counters from the scope heap. This does not collect and +/// does not add scan counts. pub fn stats(host: &mut HostContext) -> Result { with_heap(host, |heap| Ok(heap.stats())) } -/// Reads and clears the scan counts from the scope heap. This does not collect. +/// Reads and clears the scan counts from the scope heap. This does not collect +/// and does not record the read as collection work. pub fn take_scan_meter(host: &mut HostContext) -> Result { with_heap(host, |heap| Ok(heap.take_scan_meter())) } diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 9a99d5c..4374e38 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -167,10 +167,32 @@ struct Frame { /// Counts the loops one collect actually ran. /// -/// Production keeps these counters. Each add sits on an edge or slot the -/// collector already visits. They are not a second graph, and reading them -/// does not sweep or close tokens. Host collection still closes tokens before -/// sweep; there is no public sweep that skips that close. +/// Production keeps these counters. Each add sits on an edge, node slot, or +/// root slot the collector already visits. They are not a second graph. +/// `stats` and `take_scan_meter` do not collect, and they do not add to these +/// counts. A test query after the take is not part of the collection that was +/// taken. +/// +/// Edge work stays in its own fields. `index_edge_checks` is the two passes +/// that build the outgoing index (2E). `outgoing_edge_checks` is the edges +/// followed from marked nodes. `sweep_edge_checks` is the one edge filter, +/// and it is zero when every live node is marked. Adding those fields is not +/// a total GC cost. +/// +/// `index_slot_checks` is the one counts-to-offsets walk over index scratch. +/// Its length is the node-slot vector. It is not a heap-node walk. Heap node +/// walks are `node_slot_visits`. Root-vector walks are `root_slot_visits`. +/// Token identity checks stay in `token_slot_checks`. +/// +/// `scratch` records element counts the collector asked Rust to initialize, +/// copy, reserve, or push. Those are measured requests. They are not allocator +/// capacity, process RSS, or a byte size. A `Vec` may reserve more than the +/// request; this meter does not observe that. The ordinary meter also does +/// not include Core's close implementation, the process allocator, or wall +/// clock time. +/// +/// Host collection still closes tokens before sweep. There is no public sweep +/// that skips that close. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ScanMeter { pub mark_passes: u64, @@ -180,6 +202,42 @@ pub struct ScanMeter { pub sweep_edge_checks: u64, pub token_slot_checks: u64, pub token_closes: u64, + /// Node-slot reads and writes during mark reset, root liveness, outgoing + /// target checks, mark updates, pending-close enumeration, sweep + /// selection, the marked bitmap, slot release, and dead-root liveness. + pub node_slot_visits: u64, + /// Root-slot reads during root enumeration and the dead-root sweep. + pub root_slot_visits: u64, + pub scratch: ScanScratch, +} + +/// Measured scratch requests for the collects since the previous take. +/// +/// Initialization is a zeroed buffer. A copy duplicates an existing buffer. +/// A reserve is the capacity passed to `Vec::with_capacity`, not the +/// allocator's allocation. A push count is elements appended, not a capacity +/// upper bound above that count. Length fields are the sizes observed after +/// the request. This is not an observation of RSS or global allocation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ScanScratch { + /// `counts` zero-initialized to the node-slot length. + pub index_counts_inited: u64, + /// Capacity requested for `offsets` (`slots + 1`). + pub index_offsets_reserved: u64, + /// Elements pushed into `offsets`. + pub index_offsets_pushed: u64, + /// Elements copied into `cursor` from `offsets`. + pub index_cursor_copied: u64, + /// `targets` zero-initialized to the running in-range edge total. + pub index_targets_inited: u64, + /// Work-stack pushes. One per newly marked node. Not a reserve. + pub work_pushed: u64, + /// Pending-close elements appended. Host mark only; pure collect is 0. + pub pending_close_pushed: u64, + /// Dead-slot indices appended during sweep selection. 0 if sweep did not run. + pub dead_slots_pushed: u64, + /// Mark bitmap zero-initialized when the edge filter runs. 0 when skipped. + pub sweep_bitmap_inited: u64, } /// A stored token identified while marking. Close checks this slot and @@ -239,6 +297,7 @@ impl LuaHeap { } /// Returns the counts since the previous take and clears them. + /// Does not collect, and does not record this read as collection work. pub fn take_scan_meter(&mut self) -> ScanMeter { let meter = self.scan; self.scan = ScanMeter::default(); @@ -435,7 +494,8 @@ impl LuaHeap { /// [`Self::sweep_marked`] uses this same mark. pub(super) fn mark_and_doomed_tokens(&mut self) -> Vec { self.mark_reachable(); - self.slots + let doomed: Vec = self + .slots .iter() .enumerate() .filter_map(|(index, slot)| match slot.state { @@ -446,7 +506,10 @@ impl LuaHeap { }), _ => None, }) - .collect() + .collect(); + self.scan.node_slot_visits += self.slots.len() as u64; + self.scan.scratch.pending_close_pushed += doomed.len() as u64; + doomed } /// Non-moving mark from explicit roots, then one sweep of unmarked nodes. @@ -462,34 +525,37 @@ impl LuaHeap { } /// Releases nodes the current mark did not reach. Does not mark again. + /// + /// Selection and the marked count share one slot pass. After that pass, + /// every unmarked live node is released, so remaining live nodes are the + /// marked count. The report uses that count instead of walking the slot + /// vector again. pub(super) fn sweep_marked(&mut self) -> CollectReport { - let swept: Vec = self - .slots - .iter() - .enumerate() - .filter_map(|(index, slot)| match slot.state { - SlotState::Live { marked: false } => Some(index as u32), - _ => None, - }) - .collect(); - let marked_nodes = self - .slots - .iter() - .filter(|slot| matches!(slot.state, SlotState::Live { marked: true })) - .count() as u32; + let mut swept = Vec::new(); + let mut marked_nodes = 0u32; + self.scan.node_slot_visits += self.slots.len() as u64; + for (index, slot) in self.slots.iter().enumerate() { + match slot.state { + SlotState::Live { marked: false } => swept.push(index as u32), + SlotState::Live { marked: true } => marked_nodes += 1, + SlotState::Free | SlotState::Retired => {} + } + } + self.scan.scratch.dead_slots_pushed += swept.len() as u64; if !swept.is_empty() { self.sweep_edges_once(); for index in swept { + self.scan.node_slot_visits += 1; self.release_slot(index); } } - self.clear_dead_roots(); + let live_roots = self.clear_dead_roots(); self.collections = self.collections.saturating_add(1); self.last_marked = marked_nodes; CollectReport { - live_nodes: self.live_nodes(), + live_nodes: marked_nodes, marked_nodes, - live_roots: self.live_roots(), + live_roots, } } @@ -499,6 +565,7 @@ impl LuaHeap { } /// Current occupancy. Peaks count storage, not only live objects. + /// Does not collect and does not add scan counts. pub fn stats(&self) -> HeapStats { HeapStats { live_nodes: self.live_nodes(), @@ -537,6 +604,7 @@ impl LuaHeap { fn mark_reachable(&mut self) { self.scan.mark_passes += 1; + self.scan.node_slot_visits += self.slots.len() as u64; for slot in &mut self.slots { if let SlotState::Live { marked } = &mut slot.state { *marked = false; @@ -544,9 +612,12 @@ impl LuaHeap { } let index = self.build_outgoing_index(); let mut work = Vec::new(); + self.scan.root_slot_visits += self.roots.len() as u64; let rooted: Vec = self.roots.iter().copied().flatten().collect(); for handle in rooted { + self.scan.node_slot_visits += 1; if self.alive(handle) { + self.scan.node_slot_visits += 1; self.mark_slot(handle.slot(), &mut work); } } @@ -555,36 +626,46 @@ impl LuaHeap { let end = index.offsets[slot as usize + 1] as usize; self.scan.outgoing_edge_checks += (end - start) as u64; for &(to_slot, to_generation) in &index.targets[start..end] { + self.scan.node_slot_visits += 1; if self.slot_live(to_slot, to_generation) { + self.scan.node_slot_visits += 1; self.mark_slot(to_slot, &mut work); } } } } - /// Two passes over the stored edge vector, plus one pass over slots to - /// turn counts into offsets. The index is dropped at the end of mark. + /// Two passes over the stored edge vector, plus one pass over the counts + /// scratch to turn those counts into offsets. `index_slot_checks` is that + /// scratch pass. Heap node walks are counted separately. The index is + /// dropped at the end of mark. fn build_outgoing_index(&mut self) -> OutgoingIndex { let slot_count = self.slots.len(); let edge_count = self.edges.len(); self.scan.index_edge_checks += edge_count as u64; let mut counts = vec![0u32; slot_count]; + self.scan.scratch.index_counts_inited += counts.len() as u64; for edge in &self.edges { if let Some(count) = counts.get_mut(edge.from as usize) { *count = count.saturating_add(1); } } self.scan.index_slot_checks += slot_count as u64; - let mut offsets = Vec::with_capacity(slot_count + 1); + let offset_request = slot_count + 1; + self.scan.scratch.index_offsets_reserved += offset_request as u64; + let mut offsets = Vec::with_capacity(offset_request); offsets.push(0); let mut running = 0u32; for count in &counts { running = running.saturating_add(*count); offsets.push(running); } + self.scan.scratch.index_offsets_pushed += offsets.len() as u64; self.scan.index_edge_checks += edge_count as u64; let mut cursor = offsets.clone(); + self.scan.scratch.index_cursor_copied += cursor.len() as u64; let mut targets = vec![(0u32, 0u32); running as usize]; + self.scan.scratch.index_targets_inited += targets.len() as u64; for edge in &self.edges { let from = edge.from as usize; if from >= slot_count { @@ -600,13 +681,16 @@ impl LuaHeap { } /// One filter of the edge vector. Skipped when every live node is marked, - /// so an all-live collect does not walk edges again. + /// so an all-live collect does not walk edges again and does not build + /// the mark bitmap. fn sweep_edges_once(&mut self) { let marked: Vec = self .slots .iter() .map(|slot| matches!(slot.state, SlotState::Live { marked: true })) .collect(); + self.scan.node_slot_visits += marked.len() as u64; + self.scan.scratch.sweep_bitmap_inited += marked.len() as u64; self.scan.sweep_edge_checks += self.edges.len() as u64; self.edges.retain(|edge| { marked.get(edge.from as usize).copied().unwrap_or(false) @@ -619,6 +703,7 @@ impl LuaHeap { if !*marked { *marked = true; work.push(index); + self.scan.scratch.work_pushed += 1; } } } @@ -649,16 +734,22 @@ impl LuaHeap { } } - fn clear_dead_roots(&mut self) { + fn clear_dead_roots(&mut self) -> u32 { + let mut live = 0u32; let len = self.roots.len(); + self.scan.root_slot_visits += len as u64; for index in 0..len { let Some(handle) = self.roots[index] else { continue; }; - if !self.alive(handle) { + self.scan.node_slot_visits += 1; + if self.alive(handle) { + live += 1; + } else { self.roots[index] = None; } } + live } fn frame(&self, id: RootFrameId) -> Result<&Frame, HeapError> { diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index 79f22dd..4a0bacf 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -808,25 +808,33 @@ fn reachable_outgoing(shape: &ScanShape, plan: &[(u32, u32, u32)]) -> u64 { } /// The meter is the observation. Graph size is only the budget, not a stand-in -/// for the counts. +/// for the counts. Edge fields stay separate from node, root, and scratch +/// requests. Scratch lengths are measured requests, not allocator capacity, +/// RSS, Core close work, or wall time. fn assert_linear_meter( label: &str, meter: &heap::ScanMeter, slots: u64, + roots: u64, + occupied_roots: u64, edges: u64, outgoing: u64, dead: u64, + marked: u64, doomed_tokens: u64, + enumerates_doomed: bool, ) { assert_eq!( meter.mark_passes, 1, - "{label} marks once (outgoing={} budget={outgoing} sweep={} token_slots={} closes={} index_edges={})", + "{label} marks once (outgoing={} budget={outgoing} sweep={} token_slots={} closes={} index_edges={} node_slots={} root_slots={})", meter.outgoing_edge_checks, meter.sweep_edge_checks, meter.token_slot_checks, meter.token_closes, - meter.index_edge_checks + meter.index_edge_checks, + meter.node_slot_visits, + meter.root_slot_visits ); assert_eq!( meter.outgoing_edge_checks, outgoing, @@ -840,7 +848,7 @@ fn assert_linear_meter( ); assert_eq!( meter.index_slot_checks, slots, - "{label} index build examines each slot once" + "{label} index build examines the counts scratch once" ); let sweep_budget = if dead == 0 { 0 } else { edges }; assert_eq!( @@ -848,10 +856,91 @@ fn assert_linear_meter( "{label} sweep filters the edge vector once" ); assert_eq!(meter.token_closes, doomed_tokens, "{label} closes"); - assert!( - meter.token_slot_checks <= doomed_tokens.saturating_mul(3), - "{label} token slot checks {} are not direct lookups for {doomed_tokens} tokens (slots={slots})", - meter.token_slot_checks + assert_eq!( + meter.token_slot_checks, + doomed_tokens.saturating_mul(2), + "{label} token slot checks are two per close" + ); + // These graphs store only live targets, so each outgoing edge reads the + // target slot and then updates it. Occupied roots are live at mark time. + let mut node_visits = slots + occupied_roots.saturating_mul(2) + outgoing.saturating_mul(2); + if enumerates_doomed { + node_visits += slots; + } + node_visits += slots; + if dead > 0 { + node_visits += slots + dead; + } + node_visits += occupied_roots; + assert_eq!( + meter.node_slot_visits, node_visits, + "{label} node slot visits" + ); + assert_eq!( + meter.root_slot_visits, + roots.saturating_mul(2), + "{label} root slot visits" + ); + let scratch = &meter.scratch; + assert_eq!( + scratch.index_counts_inited, slots, + "{label} counts init is the measured request, not allocator capacity" + ); + assert_eq!( + scratch.index_offsets_reserved, + slots + 1, + "{label} offsets reserve" + ); + assert_eq!( + scratch.index_offsets_pushed, + slots + 1, + "{label} offsets pushed" + ); + assert_eq!( + scratch.index_cursor_copied, + slots + 1, + "{label} cursor copy" + ); + assert_eq!( + scratch.index_targets_inited, edges, + "{label} targets init is the measured in-range edge total" + ); + assert_eq!(scratch.work_pushed, marked, "{label} work pushes"); + let pending = if enumerates_doomed { doomed_tokens } else { 0 }; + assert_eq!( + scratch.pending_close_pushed, pending, + "{label} pending close" + ); + assert_eq!(scratch.dead_slots_pushed, dead, "{label} dead slots"); + let bitmap = if dead == 0 { 0 } else { slots }; + assert_eq!( + scratch.sweep_bitmap_inited, bitmap, + "{label} bitmap init is skipped when nothing is dead" + ); +} + +fn eprintln_meter(label: &str, meter: &heap::ScanMeter) { + let scratch = &meter.scratch; + eprintln!( + "meter {label} mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={} node_slots={} root_slots={} counts={} offsets_res={} offsets_pushed={} cursor={} targets={} work={} pending={} dead={} bitmap={}", + meter.mark_passes, + meter.index_edge_checks, + meter.index_slot_checks, + meter.outgoing_edge_checks, + meter.sweep_edge_checks, + meter.token_slot_checks, + meter.token_closes, + meter.node_slot_visits, + meter.root_slot_visits, + scratch.index_counts_inited, + scratch.index_offsets_reserved, + scratch.index_offsets_pushed, + scratch.index_cursor_copied, + scratch.index_targets_inited, + scratch.work_pushed, + scratch.pending_close_pushed, + scratch.dead_slots_pushed, + scratch.sweep_bitmap_inited ); } @@ -925,17 +1014,7 @@ fn collect_pure_shape(shape: &ScanShape) { eprintln!("time {} nanos={}", shape.name, started.elapsed().as_nanos()); } let meter = heap.take_scan_meter(); - eprintln!( - "meter {} mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={}", - shape.name, - meter.mark_passes, - meter.index_edge_checks, - meter.index_slot_checks, - meter.outgoing_edge_checks, - meter.sweep_edge_checks, - meter.token_slot_checks, - meter.token_closes - ); + eprintln_meter(shape.name, &meter); assert_eq!(report.live_nodes, shape.reachable, "{}", shape.name); assert_eq!(report.marked_nodes, shape.reachable, "{}", shape.name); assert_pure_kept(&heap, &nodes, shape, &plan); @@ -943,10 +1022,14 @@ fn collect_pure_shape(shape: &ScanShape) { shape.name, &meter, u64::from(before.node_slots), + u64::from(before.root_slots), + u64::from(before.live_roots), u64::from(before.live_edges), reachable_outgoing(shape, &plan), u64::from(shape.nodes - shape.reachable), + u64::from(shape.reachable), 0, + false, ); } @@ -1004,17 +1087,7 @@ fn collect_host_shape(shape: &ScanShape, share_resource: bool) { } let resources_after = host.resource_count(); let meter = heap::take_scan_meter(&mut host).expect("meter"); - eprintln!( - "meter {} mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={}", - shape.name, - meter.mark_passes, - meter.index_edge_checks, - meter.index_slot_checks, - meter.outgoing_edge_checks, - meter.sweep_edge_checks, - meter.token_slot_checks, - meter.token_closes - ); + eprintln_meter(shape.name, &meter); let shared = usize::from(share_resource); assert_eq!(report.live_nodes, shape.reachable, "{}", shape.name); assert_eq!(report.marked_nodes, shape.reachable, "{}", shape.name); @@ -1073,14 +1146,25 @@ fn collect_host_shape(shape: &ScanShape, share_resource: bool) { shape.name, &meter, u64::from(before.node_slots), + u64::from(before.root_slots), + u64::from(before.live_roots), u64::from(before.live_edges), reachable_outgoing(shape, &plan), u64::from(shape.nodes - shape.reachable), + u64::from(shape.reachable), u64::from(shape.nodes - shape.reachable), + true, ); }); } +/// One small pure collect accounts node slots, root slots, and scratch +/// requests separately from the index's one scratch pass. +#[test] +fn collect_meter_accounts_node_root_and_scratch_work() { + collect_pure_shape(&scan_shape("account-small", 4, 1, 1, 2, true)); +} + #[test] fn collect_scan_small_graph_stays_inside_one_linear_pass() { let pure = scan_shape("small-survival", 8, 2, 12, 4, true); @@ -1188,20 +1272,12 @@ fn collect_scan_retired_tokens_check_the_identified_slot() { .expect("successor slot") ); - let before_slots = heap::stats(&mut host).expect("slots").node_slots; + let before = heap::stats(&mut host).expect("slots"); + let before_slots = before.node_slots; let report = heap::collect(&mut host).expect("retired tokens do not stop collection"); let meter = heap::take_scan_meter(&mut host).expect("meter"); - eprintln!( - "meter retired-slot mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={} slots={}", - meter.mark_passes, - meter.index_edge_checks, - meter.index_slot_checks, - meter.outgoing_edge_checks, - meter.sweep_edge_checks, - meter.token_slot_checks, - meter.token_closes, - before_slots - ); + eprintln_meter("retired-slot", &meter); + eprintln!("meter retired-slot slots={before_slots}"); assert!( before_slots > 3, "the slot vector must be wider than a direct lookup" @@ -1223,18 +1299,32 @@ fn collect_scan_retired_tokens_check_the_identified_slot() { .is_ok(), "successor token stays usable" ); - assert!( - meter.token_slot_checks <= meter.token_closes.saturating_mul(3), - "retired close checked {} slots for {} closes; a full scan of {before_slots} slots would exceed this", + assert_eq!( meter.token_slot_checks, - meter.token_closes + meter.token_closes.saturating_mul(2), + "retired close checks the identified slot twice per close" ); assert_eq!(meter.mark_passes, 1, "retired close still marks once"); + assert_linear_meter( + "retired-slot", + &meter, + u64::from(before.node_slots), + u64::from(before.root_slots), + u64::from(before.live_roots), + 0, + 0, + u64::from(before.live_nodes - report.live_nodes), + u64::from(report.marked_nodes), + u64::from(meter.token_closes), + true, + ); }); } -/// A non-retired close error leaves the swept prefix closed, does not sweep, -/// and the next collect marks again. A node rooted after the failure stays. +/// A non-retired close error keeps the closed prefix, leaves the later token +/// open, and does not sweep. Another collect marks from the current roots and +/// fails again while the foreign token remains. Unbinding that token is a +/// test fixture, not a recovery path in the collector. #[test] fn collect_scan_failed_close_retries_after_remark() { with_idle_vm(|vm| { @@ -1257,30 +1347,15 @@ fn collect_scan_failed_close_retries_after_remark() { Ok(node) }) .expect("bind a foreign token"); + let suffix_raw = publish_raw(&mut host); + let suffix = table_ref(&host, suffix_raw); let before_nodes = heap::stats(&mut host).expect("before").live_nodes; let before_resources = host.resource_count(); let error = heap::collect(&mut host).expect_err("type mismatch must propagate"); - match &error { - heap::HeapError::Scope(message) => { - assert!( - message.contains("resource_type_mismatch"), - "other close errors propagate, got {message}" - ); - } - other => panic!("expected a scope close error, got {other:?}"), - } + assert_type_mismatch(&error); let failed = heap::take_scan_meter(&mut host).expect("failed meter"); - eprintln!( - "meter failed-close mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={}", - failed.mark_passes, - failed.index_edge_checks, - failed.index_slot_checks, - failed.outgoing_edge_checks, - failed.sweep_edge_checks, - failed.token_slot_checks, - failed.token_closes - ); + eprintln_meter("failed-close", &failed); assert_eq!( heap::stats(&mut host).expect("after error").live_nodes, before_nodes @@ -1291,12 +1366,25 @@ fn collect_scan_failed_close_retries_after_remark() { "an incomplete collect does not sweep" ); assert_eq!(failed.mark_passes, 1); - assert!( - failed.token_slot_checks <= failed.token_closes.saturating_mul(3), - "the failed close checked {} slots for {} closes; a direct lookup stays within 3 per close", - failed.token_slot_checks, - failed.token_closes + assert_eq!( + failed.token_closes, 3, + "prefix, other, and the foreign attempt" + ); + assert_eq!( + failed.token_slot_checks, 4, + "the two successful closes check twice; the failing close does not" ); + assert_eq!( + failed.node_slot_visits, 12, + "reset, root checks, and doomed enum" + ); + assert_eq!( + failed.root_slot_visits, 1, + "mark enumerates roots; sweep does not" + ); + assert_eq!(failed.scratch.pending_close_pushed, 4); + assert_eq!(failed.scratch.dead_slots_pushed, 0); + assert_eq!(failed.scratch.sweep_bitmap_inited, 0); assert!( host.resource(&unrelated).is_ok(), "the foreign resource is not closed" @@ -1317,26 +1405,97 @@ fn collect_scan_failed_close_retries_after_remark() { .is_err(), "the second prefix token stays closed" ); - assert_eq!(host.resource_count(), before_resources - 2); + assert!( + host.typed_resource_with_key::( + resource_handle(suffix_raw), + &LuaTableResource::key(), + ) + .is_ok(), + "the suffix after the failing token stays open" + ); + let resources_after_failure = host.resource_count(); + assert_eq!(resources_after_failure, before_resources - 2); assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(prefix))).expect("prefix node")); assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(doomed))).expect("doomed node")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(suffix))).expect("suffix node")); + let again = heap::collect(&mut host).expect_err("the same obstacle fails again"); + assert_type_mismatch(&again); + let again_meter = heap::take_scan_meter(&mut host).expect("second failure meter"); + eprintln_meter("failed-close-again", &again_meter); + assert_eq!( + again_meter.mark_passes, 1, + "the later collect marks from the current roots" + ); + assert_eq!( + again_meter.sweep_edge_checks, 0, + "the later collect still does not sweep" + ); + assert_eq!( + again_meter.token_closes, 1, + "only the foreign token is attempted" + ); + assert_eq!( + again_meter.token_slot_checks, 0, + "the failing close does not check a slot or advance the suffix" + ); + assert_eq!( + again_meter.node_slot_visits, 12, + "the later mark walks the same node slots and does not sweep" + ); + assert_eq!( + again_meter.root_slot_visits, 1, + "the later mark reads the current roots and does not sweep them" + ); + assert_eq!( + again_meter.scratch.pending_close_pushed, 2, + "foreign token and suffix" + ); + assert_eq!(again_meter.scratch.dead_slots_pushed, 0); + assert_eq!( + host.resource_count(), + resources_after_failure, + "the closed prefix quota is not returned again" + ); + assert_eq!( + heap::stats(&mut host).expect("still unswept").collections, + 0 + ); + assert!( + host.typed_resource_with_key::( + resource_handle(suffix_raw), + &LuaTableResource::key(), + ) + .is_ok(), + "the unprocessed suffix stays open" + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(suffix))).expect("suffix stays")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(other))).expect("other stays")); + assert!( + host.resource(&unrelated).is_ok(), + "the foreign resource stays open" + ); + + // Test fixture only. The collector does not unbind an obstacle or + // resume a remainder. This removes the foreign binding so the next + // collect can finish; it is not a production recovery path. heap::with_heap(&mut host, |heap| heap.unbind_token(doomed)) - .expect("drop the foreign token binding"); + .expect("fixture drops the foreign token binding"); root_table(&mut host, prefix); - let report = heap::collect(&mut host).expect("retry after the token is exact again"); - let retry = heap::take_scan_meter(&mut host).expect("retry meter"); - eprintln!( - "meter retry mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={}", - retry.mark_passes, - retry.index_edge_checks, - retry.index_slot_checks, - retry.outgoing_edge_checks, - retry.sweep_edge_checks, + let report = heap::collect(&mut host) + .expect("collect finishes after the fixture removes the foreign binding"); + let retry = heap::take_scan_meter(&mut host).expect("fixture meter"); + eprintln_meter("fixture-after-unbind", &retry); + assert_eq!(retry.mark_passes, 1, "the fixture collect marks again"); + assert_eq!( + retry.token_closes, 1, + "only the still-open suffix is closed" + ); + assert_eq!( retry.token_slot_checks, - retry.token_closes + retry.token_closes.saturating_mul(2), + "the suffix close checks its slot twice" ); - assert_eq!(retry.mark_passes, 1, "the retry marks again"); assert_eq!( report.live_nodes, 2, "keeper and the newly rooted prefix stay" @@ -1347,6 +1506,16 @@ fn collect_scan_failed_close_retries_after_remark() { ); assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(other))).expect("other swept")); assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(doomed))).expect("doomed swept")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(suffix))).expect("suffix swept")); + assert!( + host.typed_resource_with_key::( + resource_handle(suffix_raw), + &LuaTableResource::key(), + ) + .is_err(), + "the suffix closes only after the fixture removes the obstacle" + ); + assert_eq!(host.resource_count(), resources_after_failure - 1); assert!(host.resource(&unrelated).is_ok(), "shared resource remains"); assert!( host.typed_resource_with_key::( @@ -1357,3 +1526,15 @@ fn collect_scan_failed_close_retries_after_remark() { ); }); } + +fn assert_type_mismatch(error: &heap::HeapError) { + match error { + heap::HeapError::Scope(message) => { + assert!( + message.contains("resource_type_mismatch"), + "other close errors propagate, got {message}" + ); + } + other => panic!("expected a scope close error, got {other:?}"), + } +} From a194df15250e8a91fc1f159f49d2def51b3a536b Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 15:09:45 +0800 Subject: [PATCH 024/225] test(lua): exercise table and number isolation on fixed Core --- src/frontends/lua/heap.rs | 6 +- src/frontends/lua/heap/handle.rs | 2 +- src/frontends/lua/heap/table.rs | 7 + tests/luajit_heap_runtime/candidate.rs | 395 ++++++++++++++++++ .../value_boundary_tests.rs | 214 ++++++++++ tests/luajit_heap_runtime_tests.rs | 2 + 6 files changed, 624 insertions(+), 2 deletions(-) create mode 100644 tests/luajit_heap_runtime/candidate.rs create mode 100644 tests/luajit_heap_runtime/value_boundary_tests.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 9501853..498b51a 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -54,6 +54,10 @@ pub fn install(host: &mut HostContext, limits: HeapLimits) -> Result<(), HeapErr /// rolled back, so live occupancy and existing roots return to their previous /// state and the slot can be reused at the next generation. pub fn publish(host: &mut HostContext) -> Result { + publish_table(host).map(|(_, raw)| Value::Int(raw)) +} + +pub(super) fn publish_table(host: &mut HostContext) -> Result<(TableRef, i64), HeapError> { let table = with_heap(host, LuaHeap::alloc)?; let resource = match host.push_resource(LuaTableResource::new(table)) { Ok(resource) => resource, @@ -84,7 +88,7 @@ pub fn publish(host: &mut HostContext) -> Result { return Err(HeapError::CarrierOutOfRange); } }; - Ok(Value::Int(raw)) + Ok((table, raw)) } /// Runs `body` against the scope heap, creating it with production limits if diff --git a/src/frontends/lua/heap/handle.rs b/src/frontends/lua/heap/handle.rs index cc54f2b..bff634c 100644 --- a/src/frontends/lua/heap/handle.rs +++ b/src/frontends/lua/heap/handle.rs @@ -22,7 +22,7 @@ pub struct TableRef { } impl TableRef { - pub(super) fn table(domain: u64, slot: u32, generation: u32) -> Self { + pub(crate) fn table(domain: u64, slot: u32, generation: u32) -> Self { Self { domain, slot, diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 4374e38..b521888 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -459,6 +459,13 @@ impl LuaHeap { Ok(()) } + pub(crate) fn published_token(&self, table: TableRef) -> Result { + self.require_live(table)?; + self.slots[table.slot() as usize] + .token + .ok_or(HeapError::StaleHandle) + } + /// Clears the token stored on `table` without searching other slots. /// Does not close a host resource and does not sweep. Collection uses /// [`Self::clear_exact_token`] instead. diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs new file mode 100644 index 0000000..1481012 --- /dev/null +++ b/tests/luajit_heap_runtime/candidate.rs @@ -0,0 +1,395 @@ +//! Executable slice of the AST lowering. The production file entry does not +//! select it until the supported execution and root-transfer gates pass. + +use std::collections::HashMap; +use vm::compiler::ir::{ResolvedHostCall, ResolvedHostParam}; +use vm::{ + CallOutcome, CallReturn, Expr, FrontendIr, HostApiBuilder, HostApiCatalog, + HostFunctionRegistry, HostFunctionSchema, HostImportSchema, HostOwnedFunction, HostParamSchema, + HostTypeSchema, LocalIrBuilder, LocalSlot, OwnedHostCall, ParseError, Stmt, TypeSchema, Value, + VmError, +}; + +use super::{ast, heap, parser, resolve}; + +const NEW_TABLE: &str = "lua_internal::new_table"; +const TYPE: &str = "lua_internal::type_of"; +const ADD: &str = "lua_internal::add"; +const RETURN_SCALAR: &str = "lua_internal::return_scalar"; + +const TABLE_ARG: &str = "lua_internal::table_arg"; +const NUMBER_ARG: &str = "lua_internal::number_arg"; + +pub(super) fn install_schemas(builder: &mut HostApiBuilder) { + let key = heap::LuaTableResource::key(); + builder.resource(vm::ResourceTypeSchema::new(key.clone(), "Lua table")); + builder.function(HostFunctionSchema::with_return( + NEW_TABLE, + vec![], + HostTypeSchema::Unknown, + )); + builder.function(HostFunctionSchema::with_return( + TYPE, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::String, + )); + builder.function(HostFunctionSchema::with_return( + ADD, + vec![ + HostParamSchema::value("left", HostTypeSchema::Unknown), + HostParamSchema::value("right", HostTypeSchema::Unknown), + ], + HostTypeSchema::Float, + )); + builder.function(HostFunctionSchema::with_return( + RETURN_SCALAR, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::Unknown, + )); + for (name, result) in [ + (TABLE_ARG, HostTypeSchema::Resource(key)), + (NUMBER_ARG, HostTypeSchema::Float), + ] { + builder.function(HostFunctionSchema::with_return( + name, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + result, + )); + } +} + +pub(super) fn register( + registry: &mut HostFunctionRegistry, + catalog: &HostApiCatalog, +) -> Result<(), VmError> { + for op in [ + Op::NewTable, + Op::Type, + Op::Add, + Op::ReturnScalar, + Op::TableArg, + Op::NumberArg, + ] { + let name = match op { + Op::NewTable => NEW_TABLE, + Op::Type => TYPE, + Op::Add => ADD, + Op::ReturnScalar => RETURN_SCALAR, + Op::TableArg => TABLE_ARG, + Op::NumberArg => NUMBER_ARG, + }; + let function = catalog.function(name).expect("private Lua operation"); + let schema = HostImportSchema::from_function(catalog, function); + registry.register_exact_owned(name, function.params.len() as u8, schema, move |_| { + Box::new(op) + })?; + } + Ok(()) +} + +#[derive(Clone, Copy)] +enum Op { + NewTable, + Type, + Add, + ReturnScalar, + TableArg, + NumberArg, +} + +impl HostOwnedFunction for Op { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let value = match self { + Self::NewTable => { + let (table, _) = heap::publish_table(&mut call.vm().host_context()) + .map_err(|error| VmError::HostError(error.to_string()))?; + // This array is a private VM carrier, not a Lua array or a + // host resource token. Only Lua table construction produces it. + Value::array(vec![ + Value::Int(table.domain().cast_signed()), + Value::Int(i64::from(table.slot())), + Value::Int(i64::from(table.generation())), + ]) + } + Self::Type => match call.args() { + [Value::Float(_)] => Value::string("number"), + [Value::Array(_)] => Value::string("table"), + [Value::Bool(_)] => Value::string("boolean"), + [Value::String(_)] => Value::string("string"), + _ => return Err(VmError::HostError("invalid private Lua value".to_string())), + }, + Self::Add => match call.args() { + [Value::Float(left), Value::Float(right)] => Value::Float(left + right), + [Value::Array(_), _] | [_, Value::Array(_)] => { + return Err(VmError::HostError( + "attempt to perform arithmetic on a table value".to_string(), + )); + } + _ => { + return Err(VmError::HostError( + "unsupported Lua arithmetic operand".to_string(), + )); + } + }, + Self::ReturnScalar => match call.args() { + [value @ (Value::Float(_) | Value::String(_) | Value::Bool(_))] => value.clone(), + _ => { + return Err(VmError::HostError( + "Lua result needs a typed adapter".to_string(), + )); + } + }, + Self::TableArg => { + let table = match call.args() { + [Value::Array(fields)] => decode_table(fields), + _ => None, + } + .ok_or_else(|| VmError::HostError("expected Lua table".to_string()))?; + let raw = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.published_token(table) + }) + .map_err(|error| VmError::HostError(error.to_string()))?; + Value::Int( + i64::try_from(raw) + .map_err(|_| VmError::HostError("table token out of range".to_string()))?, + ) + } + Self::NumberArg => match call.args() { + [Value::Float(number)] => Value::Float(*number), + _ => return Err(VmError::HostError("expected Lua number".to_string())), + }, + }; + Ok(CallOutcome::Return(CallReturn::one(value))) + } +} + +fn decode_table(fields: &[Value]) -> Option { + let [Value::Int(domain), Value::Int(slot), Value::Int(generation)] = fields else { + return None; + }; + Some(heap::TableRef::table( + domain.cast_unsigned(), + (*slot).try_into().ok()?, + (*generation).try_into().ok()?, + )) +} + +pub(super) fn lower(source: &str, catalog: &HostApiCatalog) -> Result { + let chunk = parser::parse_chunk(source.as_bytes()) + .map_err(|error| ParseError::at_line(error.line as usize, error.message))?; + let mut lower = Lower { + source, + catalog, + builder: LocalIrBuilder::new(), + locals: HashMap::new(), + stmts: Vec::new(), + }; + if let Some(error) = resolve::resolve(&chunk).errors.first() { + return Err(ParseError::at_line(1, format!("{error:?}"))); + } + for stmt in &chunk.body.stmts { + match stmt { + ast::Stmt::Local { + span, + names, + values, + } if let ([name], [value]) = (names.as_slice(), values.exprs.as_slice()) => { + let expr = lower.expr(value)?; + let index = lower + .builder + .alloc_local_named(&format!("#{}", span.start))?; + lower.locals.insert(name.name.bytes.clone(), index); + lower.stmts.push(Stmt::Let { + index, + declared_schema: None, + expr, + line: lower.line(*span), + }); + } + ast::Stmt::Return { span, values } if let [value] = values.exprs.as_slice() => { + let value = lower.expr(value)?; + let expr = lower.call(RETURN_SCALAR, vec![value])?; + lower.stmts.push(Stmt::Expr { + expr, + line: lower.line(*span), + }); + } + ast::Stmt::Empty { .. } => {} + _ => return Err(ParseError::at_line(1, "Lua statement not lowered yet")), + } + } + Ok(lower.builder.finish(lower.stmts)) +} + +struct Lower<'a> { + source: &'a str, + catalog: &'a HostApiCatalog, + builder: LocalIrBuilder, + locals: HashMap, LocalSlot>, + stmts: Vec, +} + +impl Lower<'_> { + fn expr(&mut self, expr: &ast::Expr) -> Result { + match expr { + ast::Expr::Table { fields, .. } if fields.is_empty() => self.call(NEW_TABLE, vec![]), + ast::Expr::Number { raw, kind, .. } + if matches!(kind, ast::NumberKind::Integer | ast::NumberKind::Float) => + { + raw.parse() + .map(Expr::Float) + .map_err(|_| self.unsupported(expr.span())) + } + ast::Expr::Name { name, .. } => self + .locals + .get(&name.bytes) + .copied() + .map(Expr::Var) + .ok_or_else(|| self.unsupported(expr.span())), + ast::Expr::Paren { inner, .. } => self.expr(inner), + ast::Expr::BinaryChain { span, base, steps } => { + let mut left = self.expr(base)?; + for step in steps { + if step.op != ast::BinOp::Add { + return Err(self.unsupported(*span)); + } + let temp = self + .builder + .alloc_local_named(&format!("#step:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: temp, + declared_schema: None, + expr: left, + line: self.line(*span), + }); + let right = self.expr(&step.expr)?; + left = self.call(ADD, vec![Expr::Var(temp), right])?; + } + Ok(left) + } + ast::Expr::SuffixChain { base, steps, .. } + if let ast::Expr::Name { name, .. } = base.as_ref() + && !self.locals.contains_key(&name.bytes) + && let [ + ast::Suffix::Call { + args: ast::Args::List(args), + nav: false, + .. + }, + ] = steps.as_slice() => + { + if name.is("type") + && let [arg] = args.exprs.as_slice() + { + let arg = self.expr(arg)?; + return self.call(TYPE, vec![arg]); + } + let name = + std::str::from_utf8(&name.bytes).map_err(|_| self.unsupported(expr.span()))?; + self.host_call(&format!("lua_host::{name}"), &args.exprs, expr.span()) + } + _ => Err(self.unsupported(expr.span())), + } + } + + fn host_call( + &mut self, + name: &str, + args: &[ast::Expr], + span: ast::Span, + ) -> Result { + let Some(function) = self.catalog.function(name) else { + return Err(self.unsupported(span)); + }; + if function.params.len() != args.len() + || !matches!( + function.return_type, + HostTypeSchema::Bool | HostTypeSchema::Float | HostTypeSchema::String + ) + { + return Err(self.unsupported(span)); + } + let mut checked = Vec::new(); + for (arg, param) in args.iter().zip(&function.params) { + let adapter = match (¶m.ty, param.passing) { + (HostTypeSchema::Float, vm::HostParamPassing::Value) => NUMBER_ARG, + (HostTypeSchema::Resource(key), vm::HostParamPassing::Borrow) + if *key == heap::LuaTableResource::key() => + { + TABLE_ARG + } + _ => return Err(self.unsupported(span)), + }; + let value = self.expr(arg)?; + let slot = self + .builder + .alloc_local_named(&format!("#arg:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: value, + line: self.line(span), + }); + checked.push(self.call(adapter, vec![Expr::Var(slot)])?); + } + self.call(name, checked) + } + + fn call(&mut self, name: &str, args: Vec) -> Result { + let function = self.catalog.function(name).expect("private Lua operation"); + self.builder + .declare_function(name, Some(function.params.len() as u8))?; + let index = self + .builder + .function_index(name) + .expect("declared operation"); + let resolution = ResolvedHostCall { + name: name.to_string(), + params: function + .params + .iter() + .map(|param| ResolvedHostParam { + name: param.name.clone(), + schema: schema_type(¶m.ty), + }) + .collect(), + return_type: schema_type(&function.return_type), + passing: function.params.iter().map(|param| param.passing).collect(), + fingerprint: self.catalog.fingerprint(), + host_params: function + .params + .iter() + .map(|param| param.ty.clone()) + .collect(), + host_return_type: function.return_type.clone(), + }; + Ok(Expr::Call( + index, + vec![], + args, + Some(Box::new(resolution)), + None, + )) + } + + fn line(&self, span: ast::Span) -> u32 { + 1 + self.source.as_bytes()[..span.start as usize] + .iter() + .filter(|&&byte| byte == b'\n') + .count() as u32 + } + + fn unsupported(&self, span: ast::Span) -> ParseError { + ParseError::at_line(self.line(span) as usize, "Lua expression not lowered yet") + } +} + +fn schema_type(schema: &HostTypeSchema) -> TypeSchema { + match schema { + HostTypeSchema::String => TypeSchema::String, + HostTypeSchema::Float => TypeSchema::Float, + HostTypeSchema::Bool => TypeSchema::Bool, + HostTypeSchema::Resource(key) => TypeSchema::Resource(key.clone()), + _ => TypeSchema::Unknown, + } +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs new file mode 100644 index 0000000..cb2427e --- /dev/null +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -0,0 +1,214 @@ +// Exercise candidate lowering with Core without registering a second entry. +#[path = "../../src/frontends/lua/ast.rs"] +#[allow(dead_code)] +mod ast; +mod candidate; +#[path = "../../src/frontends/lua/lexer.rs"] +#[allow(dead_code)] +mod lexer; +#[path = "../../src/frontends/lua/parser.rs"] +mod parser; +#[path = "../../src/frontends/lua/resolve.rs"] +mod resolve; + +use super::heap; +use std::sync::{Arc, OnceLock}; +use vm::{ + CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, ParseError, + SourceFlavor, SourcePlugin, Value, VmStatus, +}; + +struct CandidatePlugin; + +impl SourcePlugin for CandidatePlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, catalog()) + } +} + +fn candidate(source: &str) -> vm::Vm { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&CandidatePlugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .expect("compile Lua text") + .into_vm() + .expect("create VM"); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register_witnesses(&mut registry, &catalog); + registry + .bind_vm_cached(&mut vm) + .expect("bind candidate runtime"); + vm +} + +#[test] +fn lua_candidate_type_preserves_table_category_after_local_copy() { + let mut vm = candidate("local t = {}; local alias = t; return type(alias)"); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("table")]); +} + +#[test] +fn lua_candidate_type_preserves_number_category_after_local_copy() { + let mut vm = candidate("local n = 42; local alias = n; return type(alias)"); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("number")]); +} + +#[test] +fn lua_candidate_addition_returns_a_number() { + let mut vm = candidate("local n = 40; return n + 1 + 1"); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Float(42.0)]); +} + +#[test] +fn lua_candidate_addition_rejects_table_at_runtime() { + let mut vm = candidate("local t = {}; local alias = t; return alias + 1"); + assert!(matches!(vm.run(), Err(vm::VmError::HostError(message)) + if message == "attempt to perform arithmetic on a table value")); +} + +#[test] +fn lua_candidate_typed_host_observes_table_identity() { + for (source, same) in [ + ( + "local t = {}; local alias = t; return same_table(t, alias)", + true, + ), + ("return same_table({}, {})", false), + ] { + let mut vm = candidate(source); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Bool(same)]); + assert_eq!(entries(&mut vm).tables, 1); + } +} + +#[test] +fn lua_candidate_host_guards_both_value_categories() { + for (source, expected) in [ + ("return same_table(1, {})", "expected Lua table"), + ("return observe_number({})", "expected Lua number"), + ] { + let mut vm = candidate(source); + assert!(matches!(vm.run(), Err(vm::VmError::HostError(message)) if message == expected)); + assert_eq!(entries(&mut vm), Entries::default()); + } + + let mut vm = candidate("return observe_number(42)"); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Float(42.0)]); + assert_eq!(entries(&mut vm).numbers, 1); +} + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct Entries { + tables: usize, + numbers: usize, +} + +fn entries(vm: &mut vm::Vm) -> Entries { + vm.host_context() + .scope_state::() + .cloned() + .unwrap_or_default() +} + +fn catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + use vm::{HostFunctionSchema, HostParamPassing, HostParamSchema, HostTypeSchema}; + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(HostFunctionSchema::with_return( + "lua_host::same_table", + vec![ + HostParamSchema::with_passing("left", table.clone(), HostParamPassing::Borrow), + HostParamSchema::with_passing("right", table, HostParamPassing::Borrow), + ], + HostTypeSchema::Bool, + )); + builder.function(HostFunctionSchema::with_return( + "lua_host::observe_number", + vec![HostParamSchema::value("number", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); + Arc::new(builder.build().unwrap()) + }) +} + +fn register_witnesses(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + for (name, op) in [ + ("lua_host::same_table", Witness::Tables), + ("lua_host::observe_number", Witness::Number), + ] { + let function = catalog.function(name).unwrap(); + registry + .register_exact_owned( + name, + function.params.len() as u8, + vm::HostImportSchema::from_function(catalog, function), + move |_| Box::new(op), + ) + .unwrap(); + } +} + +#[derive(Clone, Copy)] +enum Witness { + Tables, + Number, +} + +impl vm::HostOwnedFunction for Witness { + fn call(&mut self, call: &mut vm::OwnedHostCall<'_>) -> Result { + let args = call.args().to_vec(); + let mut host = call.vm().host_context(); + let counters = host.scope_state_or_insert_with(Entries::default).unwrap(); + let value = match self { + Self::Tables => { + counters.tables += 1; + let [left, right] = args.as_slice() else { + panic!("table arity") + }; + let key = heap::LuaTableResource::key(); + let get = |value: &Value| { + let Value::Int(raw) = value else { + panic!("expected Core resource carrier") + }; + let handle = + vm::ResourceHandle::from_raw(u64::try_from(*raw).unwrap()).unwrap(); + host.borrow_resource_with_key::(handle, &key) + .unwrap() + .table() + }; + Value::Bool(get(left) == get(right)) + } + Self::Number => { + counters.numbers += 1; + let [Value::Float(number)] = args.as_slice() else { + panic!("expected float argument") + }; + Value::Float(*number) + } + }; + Ok(vm::CallOutcome::Return(vm::CallReturn::one(value))) + } +} diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index 4a0bacf..a65999d 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -9,6 +9,8 @@ mod heap; #[path = "luajit_heap_runtime/mod.rs"] mod support; +#[path = "luajit_heap_runtime/value_boundary_tests.rs"] +mod value_boundary_tests; use heap::{ CollectReport, HandleKind, HeapLimits, LuaHeap, LuaTableResource, RootFrameId, TableRef, From 5360b8faf3b196a6cec220a5d228288ed8720f52 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 15:17:00 +0800 Subject: [PATCH 025/225] test(lua): verify collection during later argument evaluation --- tests/luajit_heap_runtime/candidate.rs | 141 ++++++++++++++++++ .../value_boundary_tests.rs | 84 +++++++++++ 2 files changed, 225 insertions(+) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 1481012..e0a82c6 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -19,8 +19,18 @@ const RETURN_SCALAR: &str = "lua_internal::return_scalar"; const TABLE_ARG: &str = "lua_internal::table_arg"; const NUMBER_ARG: &str = "lua_internal::number_arg"; +const GATHER_ROOT: &str = "lua_internal::gather_root"; +const COLLECT: &str = "lua_internal::collect"; pub(super) fn install_schemas(builder: &mut HostApiBuilder) { + builder.function(HostFunctionSchema::with_return( + GATHER_ROOT, + vec![ + HostParamSchema::value("roots", HostTypeSchema::Unknown), + HostParamSchema::value("value", HostTypeSchema::Unknown), + ], + HostTypeSchema::Unknown, + )); let key = heap::LuaTableResource::key(); builder.resource(vm::ResourceTypeSchema::new(key.clone(), "Lua table")); builder.function(HostFunctionSchema::with_return( @@ -49,6 +59,7 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { for (name, result) in [ (TABLE_ARG, HostTypeSchema::Resource(key)), (NUMBER_ARG, HostTypeSchema::Float), + (COLLECT, HostTypeSchema::Float), ] { builder.function(HostFunctionSchema::with_return( name, @@ -69,6 +80,8 @@ pub(super) fn register( Op::ReturnScalar, Op::TableArg, Op::NumberArg, + Op::GatherRoot, + Op::Collect, ] { let name = match op { Op::NewTable => NEW_TABLE, @@ -77,6 +90,8 @@ pub(super) fn register( Op::ReturnScalar => RETURN_SCALAR, Op::TableArg => TABLE_ARG, Op::NumberArg => NUMBER_ARG, + Op::GatherRoot => GATHER_ROOT, + Op::Collect => COLLECT, }; let function = catalog.function(name).expect("private Lua operation"); let schema = HostImportSchema::from_function(catalog, function); @@ -95,6 +110,8 @@ enum Op { ReturnScalar, TableArg, NumberArg, + GatherRoot, + Collect, } impl HostOwnedFunction for Op { @@ -158,11 +175,93 @@ impl HostOwnedFunction for Op { [Value::Float(number)] => Value::Float(*number), _ => return Err(VmError::HostError("expected Lua number".to_string())), }, + Self::GatherRoot => { + let table = match call.args() { + [_, value @ Value::Array(_)] => Some(value.clone()), + [_, Value::Float(_) | Value::Bool(_) | Value::String(_)] => None, + _ => { + return Err(VmError::HostError( + "invalid private Lua root candidate".to_string(), + )); + } + }; + let root_list = call.take_arg(0)?; + let mut roots = match root_list { + Value::Null => { + return Ok(CallOutcome::Return(CallReturn::one(Value::array( + table.into_iter().collect(), + )))); + } + Value::Array(roots) => roots, + _ => { + return Err(VmError::HostError( + "invalid private Lua root list".to_string(), + )); + } + }; + if let Some(table) = table { + std::sync::Arc::make_mut(&mut roots).push(table); + } + Value::Array(roots) + } + Self::Collect => { + let roots = match call.args() { + [Value::Null] => &[][..], + [Value::Array(roots)] => roots.as_slice(), + _ => { + return Err(VmError::HostError( + "invalid private Lua root list".to_string(), + )); + } + }; + let roots = roots + .iter() + .map(|root| match root { + Value::Array(fields) => decode_table(fields), + _ => None, + }) + .collect::>>() + .ok_or_else(|| { + VmError::HostError("invalid private Lua table root".to_string()) + })?; + collect_at_safepoint(&mut call.vm().host_context(), &roots)?; + Value::Float(0.0) + } }; Ok(CallOutcome::Return(CallReturn::one(value))) } } +fn collect_at_safepoint( + host: &mut vm::HostContext<'_>, + roots: &[heap::TableRef], +) -> Result<(), VmError> { + let frame = heap::with_heap(host, |heap| { + if roots.is_empty() { + return Ok(None); + } + let frame = heap + .enter_roots(u32::try_from(roots.len()).map_err(|_| heap::HeapError::RootCapacity)?)?; + for (index, root) in roots.iter().enumerate() { + if let Err(error) = heap.write_root(frame, index as u32, *root) { + heap.leave_roots(frame)?; + return Err(error); + } + } + Ok(Some(frame)) + }) + .map_err(heap_error)?; + let collect = heap::collect(host); + if let Some(frame) = frame { + heap::with_heap(host, |heap| heap.leave_roots(frame)).map_err(heap_error)?; + } + collect.map(|_| ()).map_err(heap_error) +} + +fn heap_error(error: heap::HeapError) -> VmError { + VmError::HostError(error.to_string()) +} + fn decode_table(fields: &[Value]) -> Option { let [Value::Int(domain), Value::Int(slot), Value::Int(generation)] = fields else { return None; @@ -182,6 +281,8 @@ pub(super) fn lower(source: &str, catalog: &HostApiCatalog) -> Result Result { catalog: &'a HostApiCatalog, builder: LocalIrBuilder, locals: HashMap, LocalSlot>, + live_locals: Vec, + active_temps: Vec, stmts: Vec, } @@ -262,7 +366,9 @@ impl Lower<'_> { expr: left, line: self.line(*span), }); + self.active_temps.push(temp); let right = self.expr(&step.expr)?; + self.active_temps.pop(); left = self.call(ADD, vec![Expr::Var(temp), right])?; } Ok(left) @@ -284,6 +390,12 @@ impl Lower<'_> { let arg = self.expr(arg)?; return self.call(TYPE, vec![arg]); } + if name.is("collectgarbage") + && let [ast::Expr::String { bytes, .. }] = args.exprs.as_slice() + && bytes == b"collect" + { + return self.collect_expr(expr.span()); + } let name = std::str::from_utf8(&name.bytes).map_err(|_| self.unsupported(expr.span()))?; self.host_call(&format!("lua_host::{name}"), &args.exprs, expr.span()) @@ -310,6 +422,7 @@ impl Lower<'_> { return Err(self.unsupported(span)); } let mut checked = Vec::new(); + let temp_base = self.active_temps.len(); for (arg, param) in args.iter().zip(&function.params) { let adapter = match (¶m.ty, param.passing) { (HostTypeSchema::Float, vm::HostParamPassing::Value) => NUMBER_ARG, @@ -330,11 +443,39 @@ impl Lower<'_> { expr: value, line: self.line(span), }); + self.active_temps.push(slot); checked.push(self.call(adapter, vec![Expr::Var(slot)])?); } + self.active_temps.truncate(temp_base); self.call(name, checked) } + fn collect_expr(&mut self, span: ast::Span) -> Result { + // All supported collects are explicit safepoints. Completed arguments + // live in compat-emitted temporaries, not in an implicit Core stack scan. + let live: Vec<_> = self + .live_locals + .iter() + .chain(&self.active_temps) + .copied() + .collect(); + let mut roots = Expr::Null; + for slot in live { + let packed = self.call(GATHER_ROOT, vec![roots, Expr::Var(slot)])?; + let next = self + .builder + .alloc_local_named(&format!("#roots:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: next, + declared_schema: None, + expr: packed, + line: self.line(span), + }); + roots = Expr::MoveVar(next); + } + self.call(COLLECT, vec![roots]) + } + fn call(&mut self, name: &str, args: Vec) -> Result { let function = self.catalog.function(name).expect("private Lua operation"); self.builder diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index cb2427e..c8ebe4c 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -150,6 +150,27 @@ fn catalog() -> &'static Arc { vec![HostParamSchema::value("number", HostTypeSchema::Float)], HostTypeSchema::Float, )); + for (name, reverse) in [ + ("lua_host::observe_table", false), + ("lua_host::observe_table_after", true), + ] { + let table = HostParamSchema::with_passing( + "table", + HostTypeSchema::Resource(heap::LuaTableResource::key()), + HostParamPassing::Borrow, + ); + let number = HostParamSchema::value("number", HostTypeSchema::Float); + let params = if reverse { + vec![number, table] + } else { + vec![table, number] + }; + builder.function(HostFunctionSchema::with_return( + name, + params, + HostTypeSchema::Bool, + )); + } Arc::new(builder.build().unwrap()) }) } @@ -158,6 +179,8 @@ fn register_witnesses(registry: &mut HostFunctionRegistry, catalog: &vm::HostApi for (name, op) in [ ("lua_host::same_table", Witness::Tables), ("lua_host::observe_number", Witness::Number), + ("lua_host::observe_table", Witness::TableAndNumber(0)), + ("lua_host::observe_table_after", Witness::TableAndNumber(1)), ] { let function = catalog.function(name).unwrap(); registry @@ -175,6 +198,7 @@ fn register_witnesses(registry: &mut HostFunctionRegistry, catalog: &vm::HostApi enum Witness { Tables, Number, + TableAndNumber(usize), } impl vm::HostOwnedFunction for Witness { @@ -201,6 +225,21 @@ impl vm::HostOwnedFunction for Witness { }; Value::Bool(get(left) == get(right)) } + Self::TableAndNumber(index) => { + counters.tables += 1; + let Value::Int(raw) = args[*index] else { + panic!("expected Core resource carrier") + }; + let handle = vm::ResourceHandle::from_raw(u64::try_from(raw).unwrap()).unwrap(); + let key = heap::LuaTableResource::key(); + let table = host + .borrow_resource_with_key::(handle, &key) + .unwrap() + .table(); + let live = heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).unwrap(); + assert_eq!(args[1 - *index], Value::Float(0.0)); + Value::Bool(live) + } Self::Number => { counters.numbers += 1; let [Value::Float(number)] = args.as_slice() else { @@ -212,3 +251,48 @@ impl vm::HostOwnedFunction for Witness { Ok(vm::CallOutcome::Return(vm::CallReturn::one(value))) } } + +#[test] +fn lua_candidate_collect_preserves_an_already_evaluated_host_argument() { + for (source, collections, marked, live, dead) in [ + ( + r#"local discarded = type({}); return observe_table({}, collectgarbage("collect"))"#, + 1, + 1, + 1, + 1, + ), + ( + r#"local discarded = type({}); return observe_table_after(collectgarbage("collect"), {})"#, + 1, + 0, + 1, + 1, + ), + ( + r#"local discarded = type({}); return observe_table({}, 0)"#, + 0, + 0, + 2, + 0, + ), + ] { + let mut vm = candidate(source); + assert_eq!(vm.run().unwrap(), VmStatus::Halted, "{source}"); + assert_eq!(vm.stack(), &[Value::Bool(true)], "{source}"); + assert_eq!(entries(&mut vm).tables, 1); + let (stats, meter) = heap::with_heap(&mut vm.host_context(), |heap| { + Ok((heap.stats(), heap.take_scan_meter())) + }) + .unwrap(); + assert_eq!(stats.collections, collections, "{source}"); + assert_eq!(stats.last_marked, marked, "{source}"); + assert_eq!(stats.live_nodes, live, "{source}"); + assert_eq!(stats.live_roots, 0, "{source}"); + assert_eq!(meter.scratch.dead_slots_pushed, dead, "{source}"); + println!( + "{source}: collections={} marked={} live={} swept={}", + stats.collections, stats.last_marked, stats.live_nodes, meter.scratch.dead_slots_pushed, + ); + } +} From d90991a1a6c80a611282022eb1cbf515e9ecdeff Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 18:59:00 +0800 Subject: [PATCH 026/225] fix(lua): require an issued carrier for table values --- src/frontends/lua/heap.rs | 37 ++- src/frontends/lua/heap/handle.rs | 7 +- src/frontends/lua/heap/table.rs | 97 ++++++- tests/luajit_heap_runtime/candidate.rs | 198 ++++++++++----- .../value_boundary_tests.rs | 238 ++++++++++++++++++ 5 files changed, 508 insertions(+), 69 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 498b51a..9b3a15b 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -13,15 +13,24 @@ //! //! Borrowed from the ES5 heap at `3e348a010bc8d84baa5b7d1169a5f50aeb4e46ec` //! `src/javascript/heap.rs`: slot plus generation handles, explicit root -//! frames, and non-moving mark/sweep. Not borrowed: numeric guest backing, +//! frames, and non-moving mark/sweep. The guest table check uses the issued +//! VM array identity instead of numeric guest backing. Not borrowed: //! JavaScript classifications, swc, or guest IR. //! +//! A guest table is the VM array issued for one live slot. The slot stores a +//! weak pointer to that array and checks the pointer, the slot, and the +//! generation together. The weak pointer is not a GC root and does not keep +//! the array alive. An ordinary array with the same fields is not a table. +//! This check is the experimental guest boundary for this slice. It is not a +//! measured production collection scheme. +//! //! Later integration, not this kernel: LuaJIT `ordered.lua` plus the reverse //! and skip-collection controls in //! `/mnt/workspace/rustscript-lua/evidence/lua52-gc-arg-order/qualification.md`. //! When `.lua` is connected, that stage consumes the sample. A collection //! witness must be a helper that only returns a boolean; do not inline-read a -//! weak referent from the caller. This milestone has no weak references. +//! weak referent from the caller. This milestone has no Lua weak tables +//! (`__mode`). #[path = "heap/handle.rs"] mod handle; @@ -32,7 +41,9 @@ mod table; pub use handle::{HandleKind, TableRef}; pub use resource::LuaTableResource; -pub use table::{CollectReport, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId, ScanMeter}; +pub use table::{ + CollectReport, GuestClass, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId, ScanMeter, +}; use vm::{HostContext, Value}; @@ -57,6 +68,26 @@ pub fn publish(host: &mut HostContext) -> Result { publish_table(host).map(|(_, raw)| Value::Int(raw)) } +/// Allocates a table, publishes its token, and issues the guest array. +/// +/// The returned array is the only guest table value for that slot. The token +/// stays on the existing host boundary and is not the guest identity. +pub fn publish_guest(host: &mut HostContext) -> Result { + let (table, raw) = publish_table(host)?; + match with_heap(host, |heap| heap.issue_carrier(table)) { + Ok(value) => Ok(value), + Err(error) => { + let raw = u64::try_from(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let handle = + vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + host.close_resource::(handle, vm::ResourceCloseReason::Requested) + .map_err(HeapError::from_scope)?; + with_heap(host, |heap| heap.rollback(table))?; + Err(error) + } + } +} + pub(super) fn publish_table(host: &mut HostContext) -> Result<(TableRef, i64), HeapError> { let table = with_heap(host, LuaHeap::alloc)?; let resource = match host.push_resource(LuaTableResource::new(table)) { diff --git a/src/frontends/lua/heap/handle.rs b/src/frontends/lua/heap/handle.rs index bff634c..539dda8 100644 --- a/src/frontends/lua/heap/handle.rs +++ b/src/frontends/lua/heap/handle.rs @@ -12,7 +12,8 @@ pub enum HandleKind { /// /// `domain` ties the handle to the heap that allocated it. `slot` and /// `generation` are checked against that heap on every use. A copied handle -/// is an alias only when those fields still match a live node. +/// is an alias only when those fields still match a live node. Guest values +/// are not built from these fields. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TableRef { domain: u64, @@ -22,7 +23,9 @@ pub struct TableRef { } impl TableRef { - pub(crate) fn table(domain: u64, slot: u32, generation: u32) -> Self { + /// Field construction stays inside the heap. A guest `Value` is not a + /// `TableRef` and cannot be assembled from these fields. + pub(super) fn table(domain: u64, slot: u32, generation: u32) -> Self { Self { domain, slot, diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index b521888..fe9be6c 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2,8 +2,9 @@ use std::fmt; use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Weak}; -use vm::HostContextError; +use vm::{HostContextError, Value}; use super::handle::{HandleKind, TableRef}; @@ -149,6 +150,10 @@ struct Slot { /// Raw resource handle for this node. Ownership metadata only: the mark /// phase does not read it, so the token is not a GC root. token: Option, + /// Weak identity of the VM array issued for this generation. Not a GC + /// root and not a strong reference: dropping the guest value drops the + /// array even while this slot is live. + carrier: Weak>, } struct Edge { @@ -256,6 +261,25 @@ struct OutgoingIndex { targets: Vec<(u32, u32)>, } +/// Category of one guest value on this heap. +/// +/// `Table` is only the array issued for a live slot. A structurally equal +/// array, a raw resource token, and a value issued by another heap are +/// `Unissued`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GuestClass { + /// Lua number. + Number, + /// Lua boolean. + Boolean, + /// Lua string. + String, + /// Issued table on this heap. + Table(TableRef), + /// Not an issued Lua value on this heap. + Unissued, +} + /// One scope's table nodes, edges, roots, and scan state. pub struct LuaHeap { domain: u64, @@ -313,6 +337,7 @@ impl LuaHeap { } slot.state = SlotState::Live { marked: false }; slot.token = None; + slot.carrier = Weak::new(); return Ok(TableRef::table(self.domain, index, slot.generation)); } if self.slots.len() >= self.limits.nodes as usize { @@ -326,6 +351,7 @@ impl LuaHeap { generation: 1, state: SlotState::Live { marked: false }, token: None, + carrier: Weak::new(), }); self.note_node_peak(); Ok(TableRef::table(self.domain, index, 1)) @@ -342,6 +368,71 @@ impl LuaHeap { Ok(()) } + /// Issues the guest array for a live table. + /// + /// The slot stores only a weak pointer to that array. The pointer is not + /// a root and does not keep the array alive. A second issue while the + /// first array is still alive is refused, so assignment and `Value` clone + /// keep one identity. + pub fn issue_carrier(&mut self, table: TableRef) -> Result { + self.require_live(table)?; + let index = table.slot() as usize; + if self.slots[index].carrier.upgrade().is_some() { + return Err(HeapError::StaleHandle); + } + let value = Value::array(vec![ + Value::Int(i64::from(table.slot())), + Value::Int(i64::from(table.generation())), + ]); + let carrier = match &value { + Value::Array(issued) => Arc::downgrade(issued), + _ => unreachable!("Value::array returns an array"), + }; + self.slots[index].carrier = carrier; + Ok(value) + } + + /// Classifies a guest value against this heap. + /// + /// A table result requires the live slot, the issued generation, and the + /// same VM array. Field equality is not enough. An integer resource token + /// is not consulted. This is one slot index, one generation compare, one + /// weak upgrade, and one pointer compare. It does not add a root and does + /// not increment scan counts. It is the experimental guest check for this + /// slice, not a measured production collection scheme. + pub fn guest_class(&self, value: &Value) -> GuestClass { + match value { + Value::Float(_) => GuestClass::Number, + Value::Bool(_) => GuestClass::Boolean, + Value::String(_) => GuestClass::String, + Value::Array(issued) => self + .issued_table(issued) + .map(GuestClass::Table) + .unwrap_or(GuestClass::Unissued), + _ => GuestClass::Unissued, + } + } + + fn issued_table(&self, issued: &Arc>) -> Option { + let [Value::Int(slot), Value::Int(generation)] = issued.as_slice() else { + return None; + }; + let slot = u32::try_from(*slot).ok()?; + let generation = u32::try_from(*generation).ok()?; + let stored = self.slots.get(slot as usize)?; + if stored.generation != generation { + return None; + } + if !matches!(stored.state, SlotState::Live { .. }) { + return None; + } + let current = stored.carrier.upgrade()?; + if !Arc::ptr_eq(¤t, issued) { + return None; + } + Some(TableRef::table(self.domain, slot, generation)) + } + /// Writes a reference edge. An existing key is overwritten and does not /// consume another edge slot. A new key at the cap fails without insert. pub fn set_edge(&mut self, from: TableRef, key: u32, to: TableRef) -> Result<(), HeapError> { @@ -717,14 +808,14 @@ impl LuaHeap { fn release_slot(&mut self, index: u32) { let slot = &mut self.slots[index as usize]; + slot.token = None; + slot.carrier = Weak::new(); if slot.generation >= self.limits.max_generation { slot.state = SlotState::Retired; - slot.token = None; return; } slot.generation = slot.generation.saturating_add(1); slot.state = SlotState::Free; - slot.token = None; self.free_list.push(index); } diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index e0a82c6..68866ea 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -21,6 +21,10 @@ const TABLE_ARG: &str = "lua_internal::table_arg"; const NUMBER_ARG: &str = "lua_internal::number_arg"; const GATHER_ROOT: &str = "lua_internal::gather_root"; const COLLECT: &str = "lua_internal::collect"; +// Test-only witnesses. They place an ordinary VM array on the source path. +// They are not Lua syntax and are not registered on the production entry. +const COPY_FIELDS: &str = "lua_internal::copy_fields"; +const EXTERNAL_SHAPE: &str = "lua_internal::external_shape"; pub(super) fn install_schemas(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( @@ -38,6 +42,16 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { vec![], HostTypeSchema::Unknown, )); + builder.function(HostFunctionSchema::with_return( + COPY_FIELDS, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::Unknown, + )); + builder.function(HostFunctionSchema::with_return( + EXTERNAL_SHAPE, + vec![], + HostTypeSchema::Unknown, + )); builder.function(HostFunctionSchema::with_return( TYPE, vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], @@ -82,6 +96,8 @@ pub(super) fn register( Op::NumberArg, Op::GatherRoot, Op::Collect, + Op::CopyFields, + Op::ExternalShape, ] { let name = match op { Op::NewTable => NEW_TABLE, @@ -92,6 +108,8 @@ pub(super) fn register( Op::NumberArg => NUMBER_ARG, Op::GatherRoot => GATHER_ROOT, Op::Collect => COLLECT, + Op::CopyFields => COPY_FIELDS, + Op::ExternalShape => EXTERNAL_SHAPE, }; let function = catalog.function(name).expect("private Lua operation"); let schema = HostImportSchema::from_function(catalog, function); @@ -112,42 +130,64 @@ enum Op { NumberArg, GatherRoot, Collect, + CopyFields, + ExternalShape, } impl HostOwnedFunction for Op { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { let value = match self { - Self::NewTable => { - let (table, _) = heap::publish_table(&mut call.vm().host_context()) - .map_err(|error| VmError::HostError(error.to_string()))?; - // This array is a private VM carrier, not a Lua array or a - // host resource token. Only Lua table construction produces it. - Value::array(vec![ - Value::Int(table.domain().cast_signed()), - Value::Int(i64::from(table.slot())), - Value::Int(i64::from(table.generation())), - ]) + Self::NewTable => heap::publish_guest(&mut call.vm().host_context()) + .map_err(|error| VmError::HostError(error.to_string()))?, + Self::Type => { + let value = match call.args() { + [value] => value.clone(), + _ => { + return Err(VmError::HostError("invalid private Lua value".to_string())); + } + }; + let name = match classify(&mut call.vm().host_context(), &value)? { + heap::GuestClass::Table(_) => "table", + heap::GuestClass::Number => "number", + heap::GuestClass::Boolean => "boolean", + heap::GuestClass::String => "string", + heap::GuestClass::Unissued => { + return Err(VmError::HostError("invalid private Lua value".to_string())); + } + }; + Value::string(name) } - Self::Type => match call.args() { - [Value::Float(_)] => Value::string("number"), - [Value::Array(_)] => Value::string("table"), - [Value::Bool(_)] => Value::string("boolean"), - [Value::String(_)] => Value::string("string"), - _ => return Err(VmError::HostError("invalid private Lua value".to_string())), - }, - Self::Add => match call.args() { - [Value::Float(left), Value::Float(right)] => Value::Float(left + right), - [Value::Array(_), _] | [_, Value::Array(_)] => { - return Err(VmError::HostError( - "attempt to perform arithmetic on a table value".to_string(), - )); - } - _ => { - return Err(VmError::HostError( - "unsupported Lua arithmetic operand".to_string(), - )); + Self::Add => { + let (left, right) = match call.args() { + [left, right] => (left.clone(), right.clone()), + _ => { + return Err(VmError::HostError( + "unsupported Lua arithmetic operand".to_string(), + )); + } + }; + let left_class = classify(&mut call.vm().host_context(), &left)?; + let right_class = classify(&mut call.vm().host_context(), &right)?; + match (left_class, right_class, left, right) { + ( + heap::GuestClass::Number, + heap::GuestClass::Number, + Value::Float(left), + Value::Float(right), + ) => Value::Float(left + right), + (heap::GuestClass::Table(_), _, _, _) + | (_, heap::GuestClass::Table(_), _, _) => { + return Err(VmError::HostError( + "attempt to perform arithmetic on a table value".to_string(), + )); + } + _ => { + return Err(VmError::HostError( + "unsupported Lua arithmetic operand".to_string(), + )); + } } - }, + } Self::ReturnScalar => match call.args() { [value @ (Value::Float(_) | Value::String(_) | Value::Bool(_))] => value.clone(), _ => { @@ -157,11 +197,16 @@ impl HostOwnedFunction for Op { } }, Self::TableArg => { - let table = match call.args() { - [Value::Array(fields)] => decode_table(fields), - _ => None, - } - .ok_or_else(|| VmError::HostError("expected Lua table".to_string()))?; + let value = match call.args() { + [value] => value.clone(), + _ => { + return Err(VmError::HostError("expected Lua table".to_string())); + } + }; + let table = match classify(&mut call.vm().host_context(), &value)? { + heap::GuestClass::Table(table) => table, + _ => return Err(VmError::HostError("expected Lua table".to_string())), + }; let raw = heap::with_heap(&mut call.vm().host_context(), |heap| { heap.published_token(table) }) @@ -176,20 +221,30 @@ impl HostOwnedFunction for Op { _ => return Err(VmError::HostError("expected Lua number".to_string())), }, Self::GatherRoot => { - let table = match call.args() { - [_, value @ Value::Array(_)] => Some(value.clone()), - [_, Value::Float(_) | Value::Bool(_) | Value::String(_)] => None, + let value = match call.args() { + [_, value] => value.clone(), _ => { return Err(VmError::HostError( "invalid private Lua root candidate".to_string(), )); } }; + let included = match classify(&mut call.vm().host_context(), &value)? { + heap::GuestClass::Table(_) => Some(value), + heap::GuestClass::Number + | heap::GuestClass::Boolean + | heap::GuestClass::String => None, + heap::GuestClass::Unissued => { + return Err(VmError::HostError( + "invalid private Lua root candidate".to_string(), + )); + } + }; let root_list = call.take_arg(0)?; let mut roots = match root_list { Value::Null => { return Ok(CallOutcome::Return(CallReturn::one(Value::array( - table.into_iter().collect(), + included.into_iter().collect(), )))); } Value::Array(roots) => roots, @@ -199,34 +254,44 @@ impl HostOwnedFunction for Op { )); } }; - if let Some(table) = table { + if let Some(table) = included { std::sync::Arc::make_mut(&mut roots).push(table); } Value::Array(roots) } Self::Collect => { let roots = match call.args() { - [Value::Null] => &[][..], - [Value::Array(roots)] => roots.as_slice(), + [Value::Null] => Vec::new(), + [Value::Array(roots)] => roots.iter().cloned().collect(), _ => { return Err(VmError::HostError( "invalid private Lua root list".to_string(), )); } }; - let roots = roots - .iter() - .map(|root| match root { - Value::Array(fields) => decode_table(fields), - _ => None, - }) - .collect::>>() - .ok_or_else(|| { - VmError::HostError("invalid private Lua table root".to_string()) - })?; - collect_at_safepoint(&mut call.vm().host_context(), &roots)?; + let mut tables = Vec::with_capacity(roots.len()); + for root in &roots { + match classify(&mut call.vm().host_context(), root)? { + heap::GuestClass::Table(table) => tables.push(table), + _ => { + return Err(VmError::HostError( + "invalid private Lua table root".to_string(), + )); + } + } + } + collect_at_safepoint(&mut call.vm().host_context(), &tables)?; Value::Float(0.0) } + Self::CopyFields => match call.args() { + [Value::Array(fields)] => Value::array(fields.iter().cloned().collect()), + _ => { + return Err(VmError::HostError( + "copy_fields witness expects an array carrier".to_string(), + )); + } + }, + Self::ExternalShape => Value::array(vec![Value::Int(0), Value::Int(1)]), }; Ok(CallOutcome::Return(CallReturn::one(value))) } @@ -262,15 +327,8 @@ fn heap_error(error: heap::HeapError) -> VmError { VmError::HostError(error.to_string()) } -fn decode_table(fields: &[Value]) -> Option { - let [Value::Int(domain), Value::Int(slot), Value::Int(generation)] = fields else { - return None; - }; - Some(heap::TableRef::table( - domain.cast_unsigned(), - (*slot).try_into().ok()?, - (*generation).try_into().ok()?, - )) +fn classify(host: &mut vm::HostContext<'_>, value: &Value) -> Result { + heap::with_heap(host, |heap| Ok(heap.guest_class(value))).map_err(heap_error) } pub(super) fn lower(source: &str, catalog: &HostApiCatalog) -> Result { @@ -396,6 +454,24 @@ impl Lower<'_> { { return self.collect_expr(expr.span()); } + if name.is("copy_fields") + && let [arg] = args.exprs.as_slice() + { + let value = self.expr(arg)?; + let slot = self + .builder + .alloc_local_named(&format!("#copy:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: value, + line: self.line(expr.span()), + }); + return self.call(COPY_FIELDS, vec![Expr::Var(slot)]); + } + if name.is("external_shape") && args.exprs.is_empty() { + return self.call(EXTERNAL_SHAPE, vec![]); + } let name = std::str::from_utf8(&name.bytes).map_err(|_| self.unsupported(expr.span()))?; self.host_call(&format!("lua_host::{name}"), &args.exprs, expr.span()) diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index c8ebe4c..91b11d3 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -12,6 +12,7 @@ mod parser; mod resolve; use super::heap; +use super::support; use std::sync::{Arc, OnceLock}; use vm::{ CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, ParseError, @@ -296,3 +297,240 @@ fn lua_candidate_collect_preserves_an_already_evaluated_host_argument() { ); } } + +#[test] +fn lua_candidate_type_rejects_an_ordinary_external_array() { + let mut vm = candidate("return type(external_shape())"); + let error = vm + .run() + .expect_err("an ordinary array is not an issued table"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "invalid private Lua value"), + "{error}" + ); +} + +#[test] +fn lua_candidate_type_rejects_a_structural_copy_of_an_issued_table() { + let mut vm = candidate("local t = {}; return type(copy_fields(t))"); + let error = vm.run().expect_err("copied fields are not an issued table"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "invalid private Lua value"), + "{error}" + ); +} + +#[test] +fn lua_candidate_addition_rejects_a_structural_copy_as_a_non_table() { + let mut vm = candidate("local t = {}; return copy_fields(t) + 1"); + let error = vm + .run() + .expect_err("a structural copy is not a table operand"); + assert!( + matches!(error, vm::VmError::HostError(ref message) + if message == "unsupported Lua arithmetic operand"), + "{error}" + ); +} + +#[test] +fn lua_candidate_adapter_rejects_a_structural_copy_after_the_second_argument() { + // Argument Lets run before the outer call. The table adapter is a + // subexpression of that call, so the second `{}` allocates before the + // first argument is rejected. This is the source order, not a handwritten + // call schedule. + let mut vm = candidate("return same_table(copy_fields({}), {})"); + let error = vm + .run() + .expect_err("a structural copy must not enter the typed host"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "expected Lua table"), + "{error}" + ); + assert_eq!(entries(&mut vm).tables, 0, "typed host body did not run"); + assert_eq!( + live_nodes(&mut vm), + 2, + "the second argument allocated before the first argument was rejected" + ); +} + +#[test] +fn lua_candidate_collect_refuses_a_structural_copy_as_a_root() { + let mut vm = candidate("local shape = copy_fields({}); return collectgarbage(\"collect\")"); + let error = vm.run().expect_err("a structural copy is not a table root"); + assert!( + matches!(error, vm::VmError::HostError(ref message) + if message == "invalid private Lua root candidate"), + "{error}" + ); +} + +#[test] +fn lua_candidate_alias_remains_the_issued_table_across_collection() { + let source = + "local t = {}; local alias = t; return observe_table(alias, collectgarbage(\"collect\"))"; + let mut vm = candidate(source); + assert_eq!(vm.run().unwrap(), VmStatus::Halted, "{source}"); + assert_eq!(vm.stack(), &[Value::Bool(true)]); + assert_eq!(entries(&mut vm).tables, 1); + let stats = heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.stats())).unwrap(); + assert_eq!(stats.collections, 1); + assert_eq!(stats.live_nodes, 1); + assert_eq!(stats.live_roots, 0); +} + +fn live_nodes(vm: &mut vm::Vm) -> u32 { + heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.stats().live_nodes)).unwrap() +} + +fn class_of(vm: &mut vm::Vm, value: &Value) -> heap::GuestClass { + heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.guest_class(value))).unwrap() +} + +#[test] +fn issued_carrier_keeps_identity_without_adding_a_root() { + // Test-only fixture. It calls the heap directly and is not a second entry. + support::with_idle_vm(|vm| { + let carrier = heap::publish_guest(&mut vm.host_context()).unwrap(); + assert_eq!( + heap::take_scan_meter(&mut vm.host_context()).unwrap(), + heap::ScanMeter::default(), + "issuing a carrier is not collection work" + ); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_roots, 0); + assert_eq!(vm.host_context().resource_count(), 1); + let class = class_of(vm, &carrier); + assert!(matches!(class, heap::GuestClass::Table(_))); + assert_eq!( + heap::take_scan_meter(&mut vm.host_context()).unwrap(), + heap::ScanMeter::default(), + "classification is not collection work" + ); + let alias = carrier.clone(); + assert_eq!(class_of(vm, &carrier), class_of(vm, &alias)); + let Value::Array(fields) = &carrier else { + panic!("issued carrier is an array"); + }; + let copy = Value::array(fields.iter().cloned().collect()); + assert_eq!(carrier, copy, "the copy has the same fields"); + assert_eq!(class_of(vm, ©), heap::GuestClass::Unissued); + let heap::GuestClass::Table(table) = class else { + panic!("issued carrier"); + }; + let token = + heap::with_heap(&mut vm.host_context(), |heap| heap.published_token(table)).unwrap(); + assert_eq!( + class_of(vm, &Value::Int(i64::try_from(token).unwrap())), + heap::GuestClass::Unissued, + "a raw resource token is not a table" + ); + assert_eq!( + class_of(vm, &Value::Float(token as f64)), + heap::GuestClass::Number + ); + let map = Value::map(vec![(Value::string("slot"), Value::Int(0))]); + assert_eq!(class_of(vm, &map), heap::GuestClass::Unissued); + let Value::Array(issued) = &carrier else { + panic!("issued carrier is an array"); + }; + let weak = Arc::downgrade(issued); + drop(carrier); + drop(alias); + assert!( + weak.upgrade().is_none(), + "the slot weak pointer must not keep the array alive" + ); + }); +} + +#[test] +fn collection_retires_an_unrooted_carrier() { + support::with_idle_vm(|vm| { + let carrier = heap::publish_guest(&mut vm.host_context()).unwrap(); + assert!(matches!(class_of(vm, &carrier), heap::GuestClass::Table(_))); + heap::collect(&mut vm.host_context()).unwrap(); + assert_eq!(class_of(vm, &carrier), heap::GuestClass::Unissued); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_nodes, 0); + }); +} + +#[test] +fn reused_slot_does_not_accept_the_previous_carrier() { + support::with_idle_vm(|vm| { + let first_value = heap::publish_guest(&mut vm.host_context()).unwrap(); + let heap::GuestClass::Table(first) = class_of(vm, &first_value) else { + panic!("issued table"); + }; + heap::collect(&mut vm.host_context()).unwrap(); + let second_value = heap::publish_guest(&mut vm.host_context()).unwrap(); + let heap::GuestClass::Table(second) = class_of(vm, &second_value) else { + panic!("reissued table"); + }; + assert_eq!(second.slot(), first.slot()); + assert_ne!(second.generation(), first.generation()); + assert_eq!(class_of(vm, &first_value), heap::GuestClass::Unissued); + }); +} + +#[test] +fn retired_generation_does_not_keep_the_carrier() { + support::with_idle_vm(|vm| { + heap::install( + &mut vm.host_context(), + heap::HeapLimits { + nodes: 4, + roots: 1, + edges: 1, + max_generation: 1, + }, + ) + .unwrap(); + let carrier = heap::publish_guest(&mut vm.host_context()).unwrap(); + assert!(matches!(class_of(vm, &carrier), heap::GuestClass::Table(_))); + heap::collect(&mut vm.host_context()).unwrap(); + assert_eq!(class_of(vm, &carrier), heap::GuestClass::Unissued); + }); +} + +#[test] +fn another_vm_rejects_a_structurally_equal_carrier() { + support::with_idle_vm(|left| { + let from_left = heap::publish_guest(&mut left.host_context()).unwrap(); + support::with_idle_vm(|right| { + let from_right = heap::publish_guest(&mut right.host_context()).unwrap(); + assert_eq!( + from_left, from_right, + "equal fields are not a heap identity" + ); + assert_eq!(class_of(right, &from_left), heap::GuestClass::Unissued); + assert!(matches!( + class_of(right, &from_right), + heap::GuestClass::Table(_) + )); + }); + assert!(matches!( + class_of(left, &from_left), + heap::GuestClass::Table(_) + )); + }); +} + +#[test] +fn reset_drops_the_old_carrier_even_when_fields_match_again() { + support::with_idle_vm(|vm| { + let old = heap::publish_guest(&mut vm.host_context()).unwrap(); + vm.reset_for_reuse().unwrap(); + let waker = std::task::Waker::noop(); + let mut context = std::task::Context::from_waker(waker); + match vm.poll_reset_for_reuse(&mut context) { + std::task::Poll::Ready(Ok(())) => {} + other => panic!("reset did not finish: {other:?}"), + } + assert!(vm.host_context().scope_state::().is_none()); + let fresh = heap::publish_guest(&mut vm.host_context()).unwrap(); + assert_eq!(old, fresh, "reissue after reset has no random domain"); + assert_eq!(class_of(vm, &old), heap::GuestClass::Unissued); + assert!(matches!(class_of(vm, &fresh), heap::GuestClass::Table(_))); + }); +} From f8f6f39b42ce2b5d0eba615188bf60fe01fe7ae8 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 19:19:44 +0800 Subject: [PATCH 027/225] fix(lua): clear strict clippy on heap runtime tests End non-Drop host borrows with a block, pass the existing call reference, enumerate host indexes, and group meter expectations. Assertions, collection order, and argument evaluation stay the same. --- tests/luajit_heap_runtime/candidate.rs | 15 +++-- tests/luajit_heap_runtime/mod.rs | 61 ++++++++++-------- tests/luajit_heap_runtime_tests.rs | 89 +++++++++++++++----------- 3 files changed, 94 insertions(+), 71 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 68866ea..0a495d5 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -395,13 +395,14 @@ impl Lower<'_> { fn expr(&mut self, expr: &ast::Expr) -> Result { match expr { ast::Expr::Table { fields, .. } if fields.is_empty() => self.call(NEW_TABLE, vec![]), - ast::Expr::Number { raw, kind, .. } - if matches!(kind, ast::NumberKind::Integer | ast::NumberKind::Float) => - { - raw.parse() - .map(Expr::Float) - .map_err(|_| self.unsupported(expr.span())) - } + ast::Expr::Number { + raw, + kind: ast::NumberKind::Integer | ast::NumberKind::Float, + .. + } => raw + .parse() + .map(Expr::Float) + .map_err(|_| self.unsupported(expr.span())), ast::Expr::Name { name, .. } => self .locals .get(&name.bytes) diff --git a/tests/luajit_heap_runtime/mod.rs b/tests/luajit_heap_runtime/mod.rs index 1d4781a..627d9ec 100644 --- a/tests/luajit_heap_runtime/mod.rs +++ b/tests/luajit_heap_runtime/mod.rs @@ -337,10 +337,11 @@ impl HostOwnedFunction for Publish { impl HostOwnedFunction for Alive { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - let mut host = call.vm().host_context(); - note_body(&mut host); - note_alive(&mut host); - drop(host); + { + let mut host = call.vm().host_context(); + note_body(&mut host); + note_alive(&mut host); + } let table = recover(call, 0)?; let mut host = call.vm().host_context(); let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).map_err(host_error)?; @@ -352,12 +353,13 @@ impl HostOwnedFunction for Alive { impl HostOwnedFunction for Observe { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - let mut host = call.vm().host_context(); - note_body(&mut host); - note_alive(&mut host); - drop(host); + { + let mut host = call.vm().host_context(); + note_body(&mut host); + note_alive(&mut host); + } let table = recover(call, 0)?; - let _marker = int_arg(&call, 1)?; + let _marker = int_arg(call, 1)?; let mut host = call.vm().host_context(); let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).map_err(host_error)?; Ok(CallOutcome::Return(CallReturn::one(Value::Int(i64::from( @@ -368,11 +370,12 @@ impl HostOwnedFunction for Observe { impl HostOwnedFunction for SetEdge { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - let mut host = call.vm().host_context(); - note_body(&mut host); - drop(host); + { + let mut host = call.vm().host_context(); + note_body(&mut host); + } let from = recover(call, 0)?; - let key = int_arg(&call, 1)?; + let key = int_arg(call, 1)?; let to = recover(call, 2)?; let mut host = call.vm().host_context(); heap::with_heap(&mut host, |heap| heap.set_edge(from, key, to)).map_err(host_error)?; @@ -382,11 +385,12 @@ impl HostOwnedFunction for SetEdge { impl HostOwnedFunction for EdgeIs { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - let mut host = call.vm().host_context(); - note_body(&mut host); - drop(host); + { + let mut host = call.vm().host_context(); + note_body(&mut host); + } let from = recover(call, 0)?; - let key = int_arg(&call, 1)?; + let key = int_arg(call, 1)?; let to = recover(call, 2)?; let mut host = call.vm().host_context(); let same = heap::with_heap(&mut host, |heap| Ok(heap.edge(from, key) == Ok(Some(to)))) @@ -399,7 +403,7 @@ impl HostOwnedFunction for EdgeIs { impl HostOwnedFunction for Enter { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - let width = int_arg(&call, 0)?; + let width = int_arg(call, 0)?; let mut host = call.vm().host_context(); note_body(&mut host); heap::with_heap(&mut host, |heap| heap.enter_roots(width)).map_err(host_error)?; @@ -409,10 +413,11 @@ impl HostOwnedFunction for Enter { impl HostOwnedFunction for Root { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - let mut host = call.vm().host_context(); - note_body(&mut host); - drop(host); - let slot = int_arg(&call, 0)?; + { + let mut host = call.vm().host_context(); + note_body(&mut host); + } + let slot = int_arg(call, 0)?; let table = recover(call, 1)?; let returned = call.args()[1].clone(); let mut host = call.vm().host_context(); @@ -438,9 +443,10 @@ impl HostOwnedFunction for Collect { impl HostOwnedFunction for Close { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { - let mut host = call.vm().host_context(); - note_body(&mut host); - drop(host); + { + let mut host = call.vm().host_context(); + note_body(&mut host); + } let _taken = call.take_arg(0)?; Ok(CallOutcome::Return(CallReturn::one(Value::Int(1)))) } @@ -545,12 +551,11 @@ fn build_ir(source: &str) -> Result { } let catalog = catalog(); let mut builder = LocalIrBuilder::new(); - let mut next_index = 0u16; let mut indices = std::collections::HashMap::new(); - for (name, arity) in hosts_for(source) { + for (offset, (name, arity)) in hosts_for(source).iter().enumerate() { + let next_index = offset as u16; builder.declare_function(name, Some(*arity))?; indices.insert(*name, next_index); - next_index += 1; } let call = |name: &str, args: Vec| { let index = indices[name]; diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index a65999d..8aa1cd5 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -679,7 +679,7 @@ fn reset_for_reuse_rejects_old_handles_and_starts_an_empty_heap() { }; vm.reset_for_reuse().expect("start reset"); let waker = std::task::Waker::noop(); - let mut context = std::task::Context::from_waker(&waker); + let mut context = std::task::Context::from_waker(waker); match vm.poll_reset_for_reuse(&mut context) { std::task::Poll::Ready(Ok(())) => {} other => panic!("reset did not finish: {other:?}"), @@ -809,13 +809,7 @@ fn reachable_outgoing(shape: &ScanShape, plan: &[(u32, u32, u32)]) -> u64 { .count() as u64 } -/// The meter is the observation. Graph size is only the budget, not a stand-in -/// for the counts. Edge fields stay separate from node, root, and scratch -/// requests. Scratch lengths are measured requests, not allocator capacity, -/// RSS, Core close work, or wall time. -fn assert_linear_meter( - label: &str, - meter: &heap::ScanMeter, +struct LinearMeterExpect { slots: u64, roots: u64, occupied_roots: u64, @@ -825,7 +819,24 @@ fn assert_linear_meter( marked: u64, doomed_tokens: u64, enumerates_doomed: bool, -) { +} + +/// The meter is the observation. Graph size is only the budget, not a stand-in +/// for the counts. Edge fields stay separate from node, root, and scratch +/// requests. Scratch lengths are measured requests, not allocator capacity, +/// RSS, Core close work, or wall time. +fn assert_linear_meter(label: &str, meter: &heap::ScanMeter, expect: LinearMeterExpect) { + let LinearMeterExpect { + slots, + roots, + occupied_roots, + edges, + outgoing, + dead, + marked, + doomed_tokens, + enumerates_doomed, + } = expect; assert_eq!( meter.mark_passes, 1, @@ -1023,15 +1034,17 @@ fn collect_pure_shape(shape: &ScanShape) { assert_linear_meter( shape.name, &meter, - u64::from(before.node_slots), - u64::from(before.root_slots), - u64::from(before.live_roots), - u64::from(before.live_edges), - reachable_outgoing(shape, &plan), - u64::from(shape.nodes - shape.reachable), - u64::from(shape.reachable), - 0, - false, + LinearMeterExpect { + slots: u64::from(before.node_slots), + roots: u64::from(before.root_slots), + occupied_roots: u64::from(before.live_roots), + edges: u64::from(before.live_edges), + outgoing: reachable_outgoing(shape, &plan), + dead: u64::from(shape.nodes - shape.reachable), + marked: u64::from(shape.reachable), + doomed_tokens: 0, + enumerates_doomed: false, + }, ); } @@ -1147,15 +1160,17 @@ fn collect_host_shape(shape: &ScanShape, share_resource: bool) { assert_linear_meter( shape.name, &meter, - u64::from(before.node_slots), - u64::from(before.root_slots), - u64::from(before.live_roots), - u64::from(before.live_edges), - reachable_outgoing(shape, &plan), - u64::from(shape.nodes - shape.reachable), - u64::from(shape.reachable), - u64::from(shape.nodes - shape.reachable), - true, + LinearMeterExpect { + slots: u64::from(before.node_slots), + roots: u64::from(before.root_slots), + occupied_roots: u64::from(before.live_roots), + edges: u64::from(before.live_edges), + outgoing: reachable_outgoing(shape, &plan), + dead: u64::from(shape.nodes - shape.reachable), + marked: u64::from(shape.reachable), + doomed_tokens: u64::from(shape.nodes - shape.reachable), + enumerates_doomed: true, + }, ); }); } @@ -1310,15 +1325,17 @@ fn collect_scan_retired_tokens_check_the_identified_slot() { assert_linear_meter( "retired-slot", &meter, - u64::from(before.node_slots), - u64::from(before.root_slots), - u64::from(before.live_roots), - 0, - 0, - u64::from(before.live_nodes - report.live_nodes), - u64::from(report.marked_nodes), - u64::from(meter.token_closes), - true, + LinearMeterExpect { + slots: u64::from(before.node_slots), + roots: u64::from(before.root_slots), + occupied_roots: u64::from(before.live_roots), + edges: 0, + outgoing: 0, + dead: u64::from(before.live_nodes - report.live_nodes), + marked: u64::from(report.marked_nodes), + doomed_tokens: meter.token_closes, + enumerates_doomed: true, + }, ); }); } From 9bb5d7b0db160f9d41c5758c9be94351bf9a0d70 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 19:29:54 +0800 Subject: [PATCH 028/225] fix(lua): collapse the mark_slot live check Combine the live-slot match and the unmarked test into one let-chain. An unmarked live slot is still marked, queued, and counted once. --- src/frontends/lua/heap/table.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index fe9be6c..208a03f 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -797,12 +797,12 @@ impl LuaHeap { } fn mark_slot(&mut self, index: u32, work: &mut Vec) { - if let SlotState::Live { marked } = &mut self.slots[index as usize].state { - if !*marked { - *marked = true; - work.push(index); - self.scan.scratch.work_pushed += 1; - } + if let SlotState::Live { marked } = &mut self.slots[index as usize].state + && !*marked + { + *marked = true; + work.push(index); + self.scan.scratch.work_pushed += 1; } } From 272c99ee4e8c6585ea1937cb2e9bb2f5104b41f1 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 20:16:38 +0800 Subject: [PATCH 029/225] test(lua): prove synchronous returns on a real frame Lower an uncaptured local function through Core CallScript and Ret. The nested return is still one value: a private ordered array. The candidate publishes the caller root, then leaves the callee frame. --- tests/luajit_heap_runtime/candidate.rs | 835 +++++++++++++++++- tests/luajit_heap_runtime/return_frame.rs | 323 +++++++ .../value_boundary_tests.rs | 3 +- 3 files changed, 1123 insertions(+), 38 deletions(-) create mode 100644 tests/luajit_heap_runtime/return_frame.rs diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 0a495d5..7ef5b5f 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1,10 +1,10 @@ //! Executable slice of the AST lowering. The production file entry does not //! select it until the supported execution and root-transfer gates pass. -use std::collections::HashMap; -use vm::compiler::ir::{ResolvedHostCall, ResolvedHostParam}; +use std::collections::{HashMap, HashSet}; +use vm::compiler::ir::{FunctionImpl, ResolvedHostCall, ResolvedHostParam}; use vm::{ - CallOutcome, CallReturn, Expr, FrontendIr, HostApiBuilder, HostApiCatalog, + AssignmentKind, CallOutcome, CallReturn, Expr, FrontendIr, HostApiBuilder, HostApiCatalog, HostFunctionRegistry, HostFunctionSchema, HostImportSchema, HostOwnedFunction, HostParamSchema, HostTypeSchema, LocalIrBuilder, LocalSlot, OwnedHostCall, ParseError, Stmt, TypeSchema, Value, VmError, @@ -20,7 +20,13 @@ const RETURN_SCALAR: &str = "lua_internal::return_scalar"; const TABLE_ARG: &str = "lua_internal::table_arg"; const NUMBER_ARG: &str = "lua_internal::number_arg"; const GATHER_ROOT: &str = "lua_internal::gather_root"; -const COLLECT: &str = "lua_internal::collect"; +pub(super) const COLLECT: &str = "lua_internal::collect"; +const ENTER_RESULT: &str = "lua_internal::enter_result_frame"; +const ENTER_CALLEE: &str = "lua_internal::enter_callee_frame"; +const ROOT_ISSUED: &str = "lua_internal::root_issued"; +const SET_EDGE: &str = "lua_internal::set_edge"; +pub(super) const FINISH_RETURN: &str = "lua_internal::finish_return"; +const RELEASE_RESULT: &str = "lua_internal::release_result"; // Test-only witnesses. They place an ordinary VM array on the source path. // They are not Lua syntax and are not registered on the production entry. const COPY_FIELDS: &str = "lua_internal::copy_fields"; @@ -81,6 +87,23 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { result, )); } + for (name, params) in [ + (ENTER_RESULT, vec![]), + (ENTER_CALLEE, vec!["width"]), + (ROOT_ISSUED, vec!["value", "slot", "role"]), + (SET_EDGE, vec!["from", "key", "to"]), + (FINISH_RETURN, vec!["values", "publish"]), + (RELEASE_RESULT, vec![]), + ] { + builder.function(HostFunctionSchema::with_return( + name, + params + .into_iter() + .map(|param| HostParamSchema::value(param, HostTypeSchema::Unknown)) + .collect(), + HostTypeSchema::Float, + )); + } } pub(super) fn register( @@ -96,6 +119,12 @@ pub(super) fn register( Op::NumberArg, Op::GatherRoot, Op::Collect, + Op::EnterResult, + Op::EnterCallee, + Op::RootIssued, + Op::SetEdge, + Op::FinishReturn, + Op::ReleaseResult, Op::CopyFields, Op::ExternalShape, ] { @@ -108,6 +137,12 @@ pub(super) fn register( Op::NumberArg => NUMBER_ARG, Op::GatherRoot => GATHER_ROOT, Op::Collect => COLLECT, + Op::EnterResult => ENTER_RESULT, + Op::EnterCallee => ENTER_CALLEE, + Op::RootIssued => ROOT_ISSUED, + Op::SetEdge => SET_EDGE, + Op::FinishReturn => FINISH_RETURN, + Op::ReleaseResult => RELEASE_RESULT, Op::CopyFields => COPY_FIELDS, Op::ExternalShape => EXTERNAL_SHAPE, }; @@ -130,6 +165,12 @@ enum Op { NumberArg, GatherRoot, Collect, + EnterResult, + EnterCallee, + RootIssued, + SetEdge, + FinishReturn, + ReleaseResult, CopyFields, ExternalShape, } @@ -283,6 +324,12 @@ impl HostOwnedFunction for Op { collect_at_safepoint(&mut call.vm().host_context(), &tables)?; Value::Float(0.0) } + Self::EnterResult => enter_result(call)?, + Self::EnterCallee => enter_callee(call)?, + Self::RootIssued => root_issued(call)?, + Self::SetEdge => set_edge(call)?, + Self::FinishReturn => finish_return(call)?, + Self::ReleaseResult => release_result(call)?, Self::CopyFields => match call.args() { [Value::Array(fields)] => Value::array(fields.iter().cloned().collect()), _ => { @@ -297,6 +344,294 @@ impl HostOwnedFunction for Op { } } +fn host_fault(message: &str) -> VmError { + VmError::HostError(message.to_string()) +} + +fn with_witness( + vm: &mut vm::Vm, + body: impl FnOnce(&mut ReturnWitness) -> T, +) -> Result { + let mut host = vm.host_context(); + let witness = host + .scope_state_or_insert_with(ReturnWitness::default) + .map_err(|error| VmError::HostError(error.to_string()))?; + Ok(body(witness)) +} + +fn float_u32(value: &Value) -> Result { + let Value::Float(number) = value else { + return Err(host_fault("expected a compile-time Lua integer")); + }; + if !number.is_finite() || *number < 0.0 || number.fract() != 0.0 { + return Err(host_fault("expected a compile-time Lua integer")); + } + u32::try_from(*number as u64).map_err(|_| host_fault("integer out of range")) +} + +fn carrier_ptr(value: &Value) -> Option { + match value { + Value::Array(issued) => Some(std::sync::Arc::as_ptr(issued) as usize), + _ => None, + } +} + +fn read_edge( + heap: &heap::LuaHeap, + table: Option, + key: Option, +) -> Option { + match (table, key) { + (Some(table), Some(key)) => heap.edge(table, key).ok().flatten(), + _ => None, + } +} + +fn enter_result(call: &mut OwnedHostCall<'_>) -> Result { + let frame = heap::with_heap(&mut call.vm().host_context(), |heap| heap.enter_roots(1)) + .map_err(heap_error)?; + let depth = call.vm().call_depth(); + with_witness(call.vm(), |witness| { + witness.caller_frame = Some(frame); + witness.caller_depth = Some(depth); + })?; + Ok(Value::Float(0.0)) +} + +fn enter_callee(call: &mut OwnedHostCall<'_>) -> Result { + let width = match call.args() { + [value] => float_u32(value)?, + _ => return Err(host_fault("invalid callee frame width")), + }; + let frame = if width == 0 { + None + } else { + Some( + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.enter_roots(width) + }) + .map_err(heap_error)?, + ) + }; + let depth = call.vm().call_depth(); + with_witness(call.vm(), |witness| { + witness.callee_depth = Some(depth); + witness.callee_frame = frame; + })?; + Ok(Value::Float(0.0)) +} + +fn root_issued(call: &mut OwnedHostCall<'_>) -> Result { + let (value, slot, role) = match call.args() { + [value, slot, role] => (value.clone(), float_u32(slot)?, float_u32(role)?), + _ => return Err(host_fault("invalid issued-table root")), + }; + let table = match classify(&mut call.vm().host_context(), &value)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("issued root is not a table")), + }; + let frame = with_witness(call.vm(), |witness| { + let frame = witness.callee_frame?; + if role == 0 { + witness.returned = Some(table); + witness.returned_carrier = carrier_ptr(&value); + } else if witness.discarded.is_none() { + witness.discarded = Some(table); + } + Some(frame) + })? + .ok_or_else(|| host_fault("no callee root frame"))?; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.write_root(frame, slot, table) + }) + .map_err(heap_error)?; + Ok(Value::Float(0.0)) +} + +fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { + let (from, key, to) = match call.args() { + [from, key, to] => (from.clone(), float_u32(key)?, to.clone()), + _ => return Err(host_fault("invalid table edge")), + }; + let from = match classify(&mut call.vm().host_context(), &from)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("edge source is not a table")), + }; + let to = match classify(&mut call.vm().host_context(), &to)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("edge target is not a table")), + }; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.set_edge(from, key, to) + }) + .map_err(heap_error)?; + with_witness(call.vm(), |witness| { + if witness.field_key.is_none() { + witness.field_key = Some(key); + } + })?; + Ok(Value::Float(0.0)) +} + +fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { + let (values, publish) = match call.args() { + [Value::Array(values), Value::Float(flag)] => (values.clone(), *flag != 0.0), + _ => return Err(host_fault("Lua return transport is not one array")), + }; + let depth = call.vm().call_depth(); + let mut elements = Vec::with_capacity(values.len()); + let mut returned_value = None; + for value in values.iter() { + elements.push(return_element(call, value, &mut returned_value)?); + } + let (returned, discarded, key, caller_frame, callee_frame) = + with_witness(call.vm(), |witness| { + ( + witness.returned, + witness.discarded, + witness.field_key, + witness.caller_frame, + witness.callee_frame, + ) + })?; + let (returned_edge, discarded_edge) = heap::with_heap(&mut call.vm().host_context(), |heap| { + Ok(( + read_edge(heap, returned, key), + read_edge(heap, discarded, key), + )) + }) + .map_err(heap_error)?; + let mut published = false; + if publish && let (Some(frame), Some(table)) = (caller_frame, returned_value) { + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.write_root(frame, 0, table) + }) + .map_err(heap_error)?; + published = true; + } + let mut callee_left = false; + if let Some(frame) = callee_frame { + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(frame) + }) + .map_err(heap_error)?; + callee_left = true; + } + let top_is_caller = heap::with_heap(&mut call.vm().host_context(), |heap| { + Ok(caller_frame.is_some() && heap.current_frame() == caller_frame) + }) + .map_err(heap_error)?; + with_witness(call.vm(), |witness| { + witness.elements = elements; + witness.published_root = published; + witness.callee_left = callee_left; + witness.top_is_caller_after_handoff = top_is_caller; + witness.handoff_depth = Some(depth); + witness.returned_edge_at_handoff = returned_edge; + witness.discarded_edge_at_handoff = discarded_edge; + })?; + Ok(Value::Float(values.len() as f64)) +} + +fn return_element( + call: &mut OwnedHostCall<'_>, + value: &Value, + returned_value: &mut Option, +) -> Result { + match value { + Value::Null => Ok(ReturnedElement::Nil), + Value::Float(number) => Ok(ReturnedElement::Number(*number)), + other => { + let table = match classify(&mut call.vm().host_context(), other)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("return element is not a pass-through value")), + }; + let (same_ref, same_carrier) = with_witness(call.vm(), |witness| { + let same_ref = witness.returned == Some(table); + let same_carrier = matches!( + (witness.returned_carrier, carrier_ptr(other)), + (Some(issued), Some(found)) if issued == found + ); + (same_ref, same_carrier) + })?; + if same_ref { + *returned_value = Some(table); + } + Ok(ReturnedElement::Table { + same_ref, + same_carrier, + }) + } + } +} + +fn release_result(call: &mut OwnedHostCall<'_>) -> Result { + let (returned, key, frame) = with_witness(call.vm(), |witness| { + (witness.returned, witness.field_key, witness.caller_frame) + })?; + let frame = frame.ok_or_else(|| host_fault("no caller result frame"))?; + let (alive, edge) = heap::with_heap(&mut call.vm().host_context(), |heap| { + Ok(( + returned.is_some_and(|table| heap.alive(table)), + read_edge(heap, returned, key), + )) + }) + .map_err(heap_error)?; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(frame) + }) + .map_err(heap_error)?; + let live_roots = heap::stats(&mut call.vm().host_context()) + .map_err(heap_error)? + .live_roots; + with_witness(call.vm(), |witness| { + witness.caller_frame = None; + witness.release = Some(ReleaseNote { + returned_alive: alive, + returned_edge: edge, + live_roots, + }); + })?; + Ok(Value::Float(0.0)) +} + +fn note_collect( + host: &mut vm::HostContext<'_>, + report: heap::CollectReport, +) -> Result<(), VmError> { + let Some((returned, discarded, key)) = host + .scope_state::() + .map(|witness| (witness.returned, witness.discarded, witness.field_key)) + else { + return Ok(()); + }; + let (returned_alive, discarded_alive, returned_edge) = heap::with_heap(host, |heap| { + Ok(( + returned.is_some_and(|table| heap.alive(table)), + discarded.is_some_and(|table| heap.alive(table)), + read_edge(heap, returned, key), + )) + }) + .map_err(heap_error)?; + let swept = heap::take_scan_meter(host) + .map_err(heap_error)? + .scratch + .dead_slots_pushed; + let witness = host + .scope_state_mut::() + .ok_or_else(|| host_fault("return witness disappeared"))?; + witness.collects.push(CollectNote { + live_nodes: report.live_nodes, + marked_nodes: report.marked_nodes, + live_roots: report.live_roots, + swept, + returned_alive, + discarded_alive, + returned_edge, + }); + Ok(()) +} + fn collect_at_safepoint( host: &mut vm::HostContext<'_>, roots: &[heap::TableRef], @@ -316,11 +651,12 @@ fn collect_at_safepoint( Ok(Some(frame)) }) .map_err(heap_error)?; - let collect = heap::collect(host); + let report = heap::collect(host); if let Some(frame) = frame { heap::with_heap(host, |heap| heap.leave_roots(frame)).map_err(heap_error)?; } - collect.map(|_| ()).map_err(heap_error) + let report = report.map_err(heap_error)?; + note_collect(host, report) } fn heap_error(error: heap::HeapError) -> VmError { @@ -332,6 +668,14 @@ fn classify(host: &mut vm::HostContext<'_>, value: &Value) -> Result Result { + lower_returning(source, catalog, true) +} + +pub(super) fn lower_returning( + source: &str, + catalog: &HostApiCatalog, + publish_results: bool, +) -> Result { let chunk = parser::parse_chunk(source.as_bytes()) .map_err(|error| ParseError::at_line(error.line as usize, error.message))?; let mut lower = Lower { @@ -342,43 +686,26 @@ pub(super) fn lower(source: &str, catalog: &HostApiCatalog) -> Result { - let expr = lower.expr(value)?; - let index = lower - .builder - .alloc_local_named(&format!("#{}", span.start))?; - lower.locals.insert(name.name.bytes.clone(), index); - lower.live_locals.push(index); - lower.stmts.push(Stmt::Let { - index, - declared_schema: None, - expr, - line: lower.line(*span), - }); - } - ast::Stmt::Return { span, values } if let [value] = values.exprs.as_slice() => { - let value = lower.expr(value)?; - let expr = lower.call(RETURN_SCALAR, vec![value])?; - lower.stmts.push(Stmt::Expr { - expr, - line: lower.line(*span), - }); - } - ast::Stmt::Empty { .. } => {} - _ => return Err(ParseError::at_line(1, "Lua statement not lowered yet")), - } + lower.lower_stmt(stmt)?; } - Ok(lower.builder.finish(lower.stmts)) + let mut ir = lower.builder.finish(lower.stmts); + ir.function_impls = lower.function_impls; + Ok(ir) } struct Lower<'a> { @@ -389,9 +716,326 @@ struct Lower<'a> { live_locals: Vec, active_temps: Vec, stmts: Vec, + functions: HashMap, FuncInfo>, + function_impls: HashMap, + result_bindings: HashSet>, + field_keys: HashMap, u32>, + publish_results: bool, + in_function: bool, + return_names: HashSet>, + function_returns_table: bool, + root_slot: u32, + ignored_slot: Option, +} + +#[derive(Clone, Copy)] +struct FuncInfo { + index: u16, + returns_table: bool, } impl Lower<'_> { + fn lower_stmt(&mut self, stmt: &ast::Stmt) -> Result<(), ParseError> { + match stmt { + ast::Stmt::LocalFunction { + span, name, func, .. + } => self.lower_function(name, func, *span), + ast::Stmt::Local { + span, + names, + values, + } if let ([name], [value]) = (names.as_slice(), values.exprs.as_slice()) => { + self.lower_local(*span, &name.name, value) + } + ast::Stmt::Assign { + span, + targets, + values, + } if let ([target], [value]) = (targets.as_slice(), values.exprs.as_slice()) => { + self.lower_assign(*span, target, value) + } + ast::Stmt::Call { span, call } => { + let expr = self.expr(call)?; + self.emit_ignored(expr, self.line(*span)) + } + ast::Stmt::Return { span, values } if !self.in_function && values.exprs.len() == 1 => { + let value = self.expr(&values.exprs[0])?; + let expr = self.call(RETURN_SCALAR, vec![value])?; + self.stmts.push(Stmt::Expr { + expr, + line: self.line(*span), + }); + Ok(()) + } + ast::Stmt::Empty { .. } => Ok(()), + other => Err(ParseError::at_line( + self.line(stmt_span(other)) as usize, + "Lua statement not lowered yet", + )), + } + } + + fn lower_local( + &mut self, + span: ast::Span, + name: &ast::Name, + value: &ast::Expr, + ) -> Result<(), ParseError> { + let returns_call = self.direct_function_call(value).is_some(); + let expr = self.expr(value)?; + let index = self + .builder + .alloc_local_named(&format!("#{}", span.start))?; + self.locals.insert(name.bytes.clone(), index); + if returns_call { + self.result_bindings.insert(name.bytes.clone()); + } else { + self.live_locals.push(index); + } + self.stmts.push(Stmt::Let { + index, + declared_schema: None, + expr, + line: self.line(span), + }); + if self.in_function && matches!(value, ast::Expr::Table { fields, .. } if fields.is_empty()) + { + let role = if self.return_names.contains(&name.bytes) { + self.function_returns_table = true; + 0.0 + } else { + 1.0 + }; + let slot = self.root_slot; + self.root_slot += 1; + let expr = self.call( + ROOT_ISSUED, + vec![ + Expr::Var(index), + Expr::Float(slot as f64), + Expr::Float(role), + ], + )?; + self.emit_ignored(expr, self.line(span))?; + } + Ok(()) + } + + fn lower_assign( + &mut self, + span: ast::Span, + target: &ast::AssignTarget, + value: &ast::Expr, + ) -> Result<(), ParseError> { + match (target, value) { + (ast::AssignTarget::Name(name), ast::Expr::Nil { .. }) + if self.result_bindings.contains(&name.bytes) => + { + let expr = self.call(RELEASE_RESULT, vec![])?; + self.emit_ignored(expr, self.line(span)) + } + ( + ast::AssignTarget::Field { + table, + name, + nav: false, + .. + }, + _, + ) if self.in_function => { + let key = self.field_key(&name.bytes); + let from = self.expr(table)?; + let to = self.expr(value)?; + let expr = self.call(SET_EDGE, vec![from, Expr::Float(key as f64), to])?; + self.emit_ignored(expr, self.line(span)) + } + _ => Err(self.unsupported(span)), + } + } + + fn lower_function( + &mut self, + name: &ast::Name, + func: &ast::FuncBody, + span: ast::Span, + ) -> Result<(), ParseError> { + if !func.params.is_empty() || func.vararg || func.self_param { + return Err(self.unsupported(span)); + } + let function_name = std::str::from_utf8(&name.bytes).map_err(|_| self.unsupported(span))?; + self.builder.declare_function(function_name, Some(0))?; + let index = self + .builder + .function_index(function_name) + .expect("declared Lua function"); + let (prefix, returns) = split_return(&func.body.stmts).map_err(|span| { + ParseError::at_line(self.line(span) as usize, "Lua return must end the block") + })?; + let width = rooted_table_count(prefix); + let saved_locals = std::mem::take(&mut self.locals); + let saved_live = std::mem::take(&mut self.live_locals); + let saved_temps = std::mem::take(&mut self.active_temps); + let saved_stmts = std::mem::take(&mut self.stmts); + let saved_results = std::mem::take(&mut self.result_bindings); + let saved_return_names = std::mem::replace( + &mut self.return_names, + returns + .iter() + .filter_map(|expr| match expr { + ast::Expr::Name { name, .. } => Some(name.bytes.clone()), + _ => None, + }) + .collect(), + ); + let saved_returns_table = self.function_returns_table; + let saved_root_slot = self.root_slot; + let saved_ignored = self.ignored_slot; + let saved_in_function = self.in_function; + self.function_returns_table = false; + self.root_slot = 0; + self.ignored_slot = None; + self.in_function = true; + let enter = self.call(ENTER_CALLEE, vec![Expr::Float(width as f64)])?; + self.emit_ignored(enter, self.line(span))?; + for stmt in prefix { + self.lower_stmt(stmt)?; + } + if self.root_slot != width { + return Err(self.unsupported(span)); + } + let body_expr = self.pack_return(returns)?; + let body_stmts = std::mem::take(&mut self.stmts); + let returns_table = self.function_returns_table; + self.locals = saved_locals; + self.live_locals = saved_live; + self.active_temps = saved_temps; + self.stmts = saved_stmts; + self.result_bindings = saved_results; + self.return_names = saved_return_names; + self.function_returns_table = saved_returns_table; + self.root_slot = saved_root_slot; + self.ignored_slot = saved_ignored; + self.in_function = saved_in_function; + self.function_impls.insert( + index, + FunctionImpl { + param_slots: Vec::new(), + capture_copies: Vec::new(), + body_stmts, + body_expr, + body_expr_line: self.line(span), + }, + ); + self.functions.insert( + name.bytes.clone(), + FuncInfo { + index, + returns_table, + }, + ); + Ok(()) + } + + fn pack_return(&mut self, values: &[ast::Expr]) -> Result { + let mut packed = Vec::with_capacity(values.len()); + for value in values { + packed.push(self.return_value(value)?); + } + Ok(pack_array(packed)) + } + + fn return_value(&mut self, expr: &ast::Expr) -> Result { + match expr { + ast::Expr::Nil { .. } => Ok(Expr::Null), + ast::Expr::Number { + raw, + kind: ast::NumberKind::Integer | ast::NumberKind::Float, + .. + } => raw + .parse() + .map(Expr::Float) + .map_err(|_| self.unsupported(expr.span())), + ast::Expr::Name { name, .. } => self + .locals + .get(&name.bytes) + .copied() + .map(Expr::Var) + .ok_or_else(|| self.unsupported(expr.span())), + other => Err(self.unsupported(other.span())), + } + } + + fn direct_function_call<'a>(&self, expr: &'a ast::Expr) -> Option<&'a ast::Name> { + match expr { + ast::Expr::SuffixChain { base, steps, .. } + if let ast::Expr::Name { name, .. } = base.as_ref() + && let [ + ast::Suffix::Call { + args: ast::Args::List(args), + nav: false, + .. + }, + ] = steps.as_slice() + && args.exprs.is_empty() + && self.functions.contains_key(&name.bytes) => + { + Some(name) + } + _ => None, + } + } + + fn finish_call(&mut self, name: &[u8], span: ast::Span) -> Result { + let info = self + .functions + .get(name) + .copied() + .ok_or_else(|| self.unsupported(span))?; + if info.returns_table { + let enter = self.call(ENTER_RESULT, vec![])?; + self.emit_ignored(enter, self.line(span))?; + } + let call = Expr::Call(info.index, vec![], vec![], None, None); + let publish = if self.publish_results && info.returns_table { + 1.0 + } else { + 0.0 + }; + self.call(FINISH_RETURN, vec![call, Expr::Float(publish)]) + } + + fn field_key(&mut self, name: &[u8]) -> u32 { + if let Some(key) = self.field_keys.get(name).copied() { + return key; + } + let key = u32::try_from(self.field_keys.len() + 1).expect("field key"); + self.field_keys.insert(name.to_vec(), key); + key + } + + fn emit_ignored(&mut self, expr: Expr, line: u32) -> Result<(), ParseError> { + if let Some(index) = self.ignored_slot { + self.stmts.push(Stmt::Assign { + kind: AssignmentKind::Set, + index, + expr, + line, + }); + return Ok(()); + } + let index = self + .builder + .alloc_local_named(&format!("#ignored:{}", self.stmts.len()))?; + self.ignored_slot = Some(index); + self.stmts.push(Stmt::Let { + index, + declared_schema: None, + expr, + line, + }); + Ok(()) + } + fn expr(&mut self, expr: &ast::Expr) -> Result { match expr { ast::Expr::Table { fields, .. } if fields.is_empty() => self.call(NEW_TABLE, vec![]), @@ -443,6 +1087,12 @@ impl Lower<'_> { }, ] = steps.as_slice() => { + if self.functions.contains_key(&name.bytes) { + if !args.exprs.is_empty() { + return Err(self.unsupported(expr.span())); + } + return self.finish_call(&name.bytes, expr.span()); + } if name.is("type") && let [arg] = args.exprs.as_slice() { @@ -602,6 +1252,117 @@ impl Lower<'_> { } } +fn stmt_span(stmt: &ast::Stmt) -> ast::Span { + match stmt { + ast::Stmt::Empty { span } + | ast::Stmt::Do { span, .. } + | ast::Stmt::While { span, .. } + | ast::Stmt::Repeat { span, .. } + | ast::Stmt::If { span, .. } + | ast::Stmt::NumericFor { span, .. } + | ast::Stmt::GenericFor { span, .. } + | ast::Stmt::Local { span, .. } + | ast::Stmt::LocalFunction { span, .. } + | ast::Stmt::Function { span, .. } + | ast::Stmt::Assign { span, .. } + | ast::Stmt::CompoundAssign { span, .. } + | ast::Stmt::Call { span, .. } + | ast::Stmt::Label { span, .. } + | ast::Stmt::Goto { span, .. } + | ast::Stmt::Break { span } + | ast::Stmt::Continue { span } + | ast::Stmt::Return { span, .. } => *span, + } +} + +fn split_return(stmts: &[ast::Stmt]) -> Result<(&[ast::Stmt], &[ast::Expr]), ast::Span> { + let Some((last, prefix)) = stmts.split_last() else { + return Ok((stmts, &[])); + }; + match last { + ast::Stmt::Return { values, .. } => Ok((prefix, &values.exprs)), + other + if stmts + .iter() + .any(|stmt| matches!(stmt, ast::Stmt::Return { .. })) => + { + Err(stmt_span(other)) + } + _ => Ok((stmts, &[])), + } +} + +fn rooted_table_count(stmts: &[ast::Stmt]) -> u32 { + stmts + .iter() + .filter(|stmt| { + matches!( + stmt, + ast::Stmt::Local { values, .. } + if matches!( + values.exprs.as_slice(), + [ast::Expr::Table { fields, .. }] if fields.is_empty() + ) + ) + }) + .count() as u32 +} + +fn pack_array(values: Vec) -> Expr { + let new_array = vm::BuiltinFunction::ArrayNew.call_index(); + let push = vm::BuiltinFunction::ArrayPush.call_index(); + values.into_iter().fold( + Expr::Call(new_array, vec![], vec![], None, None), + |array, value| Expr::Call(push, vec![], vec![array, value], None, None), + ) +} + +#[derive(Clone, Debug, Default)] +pub(super) struct ReturnWitness { + pub callee_depth: Option, + pub caller_depth: Option, + pub handoff_depth: Option, + pub returned: Option, + pub discarded: Option, + pub returned_carrier: Option, + pub field_key: Option, + pub returned_edge_at_handoff: Option, + pub discarded_edge_at_handoff: Option, + pub elements: Vec, + pub published_root: bool, + pub callee_left: bool, + pub top_is_caller_after_handoff: bool, + pub collects: Vec, + pub release: Option, + caller_frame: Option, + callee_frame: Option, +} + +#[derive(Clone, Debug)] +pub(super) enum ReturnedElement { + Nil, + Number(f64), + Table { same_ref: bool, same_carrier: bool }, +} + +#[derive(Clone, Debug)] +pub(super) struct CollectNote { + pub live_nodes: u32, + pub marked_nodes: u32, + pub live_roots: u32, + pub swept: u64, + pub returned_alive: bool, + pub discarded_alive: bool, + pub returned_edge: Option, +} + +#[derive(Clone, Debug)] +pub(super) struct ReleaseNote { + pub returned_alive: bool, + pub returned_edge: Option, + pub live_roots: u32, +} + fn schema_type(schema: &HostTypeSchema) -> TypeSchema { match schema { HostTypeSchema::String => TypeSchema::String, diff --git a/tests/luajit_heap_runtime/return_frame.rs b/tests/luajit_heap_runtime/return_frame.rs new file mode 100644 index 0000000..529b1b6 --- /dev/null +++ b/tests/luajit_heap_runtime/return_frame.rs @@ -0,0 +1,323 @@ +//! Real uncaptured Lua calls and the explicit return-root handoff. +//! +//! The sources are legal Lua. Observation stays in the candidate witness: +//! Core's nested `Ret` still carries one value, and that value is the private +//! ordered result array. `self` is an ordinary field name. + +use super::candidate::{self, ReturnWitness, ReturnedElement}; +use super::catalog; +use std::sync::Arc; +use vm::{ + CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, OpCode, + ParseError, Program, SourceFlavor, SourcePlugin, Value, VmStatus, +}; + +struct PublishingReturn; +struct UnpublishedReturn; + +impl SourcePlugin for PublishingReturn { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower_returning(source, catalog(), true) + } +} + +impl SourcePlugin for UnpublishedReturn { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower_returning(source, catalog(), false) + } +} + +fn run(source: &str, publish_results: bool) -> vm::Vm { + let catalog = Arc::clone(catalog()); + let options = if publish_results { + CompileSourceFileOptions::new().with_source_plugin(&PublishingReturn) + } else { + CompileSourceFileOptions::new().with_source_plugin(&UnpublishedReturn) + } + .with_host_api_catalog(Arc::clone(&catalog)); + let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .expect("compile Lua text") + .into_vm() + .expect("create VM"); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + registry + .bind_vm_cached(&mut vm) + .expect("bind candidate runtime"); + vm +} + +fn witness(vm: &mut vm::Vm) -> ReturnWitness { + vm.host_context() + .scope_state::() + .cloned() + .expect("return witness") +} + +const ZERO: &str = "\ +local function none() + return +end +local n = none() +return n +"; + +const ONE_NIL: &str = "\ +local function one() + return nil +end +local n = one() +return n +"; + +const TABLE_RETURN: &str = "\ +local function make() + local returned = {} + local discarded = {} + local alias = returned + alias.self = returned + local other = discarded + other.self = discarded + return returned, nil, 9 +end +local kept = make() +collectgarbage(\"collect\") +kept = nil +collectgarbage(\"collect\") +"; + +#[test] +fn zero_return_uses_a_real_frame_and_exact_arity() { + let mut vm = run(ZERO, true); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Float(0.0)]); + let witness = witness(&mut vm); + assert!(witness.elements.is_empty()); + assert_retired_call(&witness); + assert!(!witness.published_root); + assert!(witness.collects.is_empty()); + assert_real_return_window(vm.program()); +} + +#[test] +fn one_nil_keeps_exact_arity_and_nil_position() { + let mut vm = run(ONE_NIL, true); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Float(1.0)]); + let witness = witness(&mut vm); + assert!(matches!( + witness.elements.as_slice(), + [ReturnedElement::Nil] + )); + assert_retired_call(&witness); + assert_real_return_window(vm.program()); +} + +#[test] +fn table_nil_number_handoff_keeps_the_returned_object_only() { + let mut vm = run(TABLE_RETURN, true); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + let witness = witness(&mut vm); + assert_eq!(witness.elements.len(), 3); + match witness.elements.as_slice() { + [ + ReturnedElement::Table { + same_ref: true, + same_carrier: true, + }, + ReturnedElement::Nil, + ReturnedElement::Number(number), + ] => assert_eq!(*number, 9.0), + other => panic!("unexpected return elements: {other:?}"), + } + let returned = witness.returned.expect("issued returned table"); + let discarded = witness.discarded.expect("issued discarded table"); + assert_ne!(returned, discarded); + assert_eq!(witness.returned_edge_at_handoff, Some(returned)); + assert_eq!(witness.discarded_edge_at_handoff, Some(discarded)); + assert!(witness.published_root); + assert!(witness.callee_left); + assert!(witness.top_is_caller_after_handoff); + assert_retired_call(&witness); + let first = &witness.collects[0]; + assert!(first.returned_alive); + assert_eq!(first.returned_edge, Some(returned)); + assert!(!first.discarded_alive); + assert_eq!(first.marked_nodes, 1); + assert_eq!(first.live_roots, 1); + assert_eq!(first.live_nodes, 1); + assert_eq!(first.swept, 1); + let release = witness.release.expect("caller dropped the result root"); + assert!(release.returned_alive); + assert_eq!(release.returned_edge, Some(returned)); + assert_eq!(release.live_roots, 0); + let second = &witness.collects[1]; + assert!(!second.returned_alive); + assert!(second.returned_edge.is_none()); + assert!(!second.discarded_alive); + assert_eq!(second.marked_nodes, 0); + assert_eq!(second.live_roots, 0); + assert_eq!(second.live_nodes, 0); + assert_eq!(second.swept, 1); + assert_real_return_window(vm.program()); +} + +#[test] +fn omitting_only_the_result_root_drops_the_returned_table_on_first_collect() { + let mut vm = run(TABLE_RETURN, false); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + let witness = witness(&mut vm); + assert!(!witness.published_root); + assert!(witness.callee_left); + assert_retired_call(&witness); + let first = &witness.collects[0]; + assert!(!first.returned_alive, "the returned table is unusable"); + assert!(first.returned_edge.is_none()); + assert!(!first.discarded_alive); + assert_eq!(first.marked_nodes, 0); + assert_eq!(first.live_roots, 0); + assert_eq!(first.swept, 2); + assert_real_return_window(vm.program()); +} + +fn assert_retired_call(witness: &ReturnWitness) { + let callee = witness.callee_depth.expect("callee depth"); + let handoff = witness.handoff_depth.expect("depth after return"); + assert_eq!( + callee, + handoff + 1, + "the callee frame retired before publish" + ); +} + +fn assert_real_return_window(program: &Program) { + let finish = import_index(program, candidate::FINISH_RETURN); + let mut call_ip = None; + let mut prototype = None; + let mut ip = 0; + while ip < program.code.len() { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == OpCode::CallScript && call_ip.is_none() { + call_ip = Some(ip); + prototype = Some(u32::from_le_bytes( + program.code[ip + 1..ip + 5].try_into().expect("prototype"), + )); + assert_eq!(program.code[ip + 5], 0, "no captured arguments"); + } + ip += 1 + op.operand_len(); + } + let call_ip = call_ip.expect("CallScript"); + let function = &program.script_functions[prototype.expect("prototype") as usize]; + assert!(function.end_ip > function.entry_ip); + assert!( + call_ip < function.entry_ip as usize || call_ip >= function.end_ip as usize, + "the call site is outside the callee, so the frame was not inlined away" + ); + assert!( + region_has(program, function.entry_ip, function.end_ip, OpCode::Ret), + "the callee still retires with Ret" + ); + if let Some(collect) = program + .imports + .iter() + .position(|import| import.name == candidate::COLLECT) + { + let collect = u16::try_from(collect).expect("import index"); + assert!( + !region_calls(program, function.entry_ip, function.end_ip, collect), + "the callee does not collect before returning" + ); + } + let finish_ip = next_call(program, call_ip, finish); + assert_no_calls_between(program, call_ip, finish_ip); +} + +fn import_index(program: &Program, name: &str) -> u16 { + program + .imports + .iter() + .position(|import| import.name == name) + .expect(name) + .try_into() + .expect("import index") +} + +fn region_has(program: &Program, start: u32, end: u32, want: OpCode) -> bool { + let mut ip = start as usize; + let end = end as usize; + while ip < end { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == want { + return true; + } + ip += 1 + op.operand_len(); + } + false +} + +fn region_calls(program: &Program, start: u32, end: u32, import: u16) -> bool { + let mut ip = start as usize; + let end = end as usize; + while ip < end { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == OpCode::Call && call_index(program, ip) == import { + return true; + } + ip += 1 + op.operand_len(); + } + false +} + +fn next_call(program: &Program, call_script: usize, import: u16) -> usize { + let op = OpCode::try_from(program.code[call_script]).expect("opcode"); + let mut ip = call_script + 1 + op.operand_len(); + while ip < program.code.len() { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == OpCode::Call && call_index(program, ip) == import { + return ip; + } + ip += 1 + op.operand_len(); + } + panic!("finish_return does not follow the generated call"); +} + +fn assert_no_calls_between(program: &Program, call_script: usize, finish: usize) { + let op = OpCode::try_from(program.code[call_script]).expect("opcode"); + let mut ip = call_script + 1 + op.operand_len(); + while ip < finish { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + assert!( + !matches!(op, OpCode::Call | OpCode::CallValue | OpCode::CallScript), + "collect or a guest callback sits between the call and publish at {ip}" + ); + ip += 1 + op.operand_len(); + } +} + +fn call_index(program: &Program, ip: usize) -> u16 { + u16::from_le_bytes(program.code[ip + 1..ip + 3].try_into().expect("call index")) +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 91b11d3..15d3a07 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -10,6 +10,7 @@ mod lexer; mod parser; #[path = "../../src/frontends/lua/resolve.rs"] mod resolve; +mod return_frame; use super::heap; use super::support; @@ -131,7 +132,7 @@ fn entries(vm: &mut vm::Vm) -> Entries { .unwrap_or_default() } -fn catalog() -> &'static Arc { +pub(super) fn catalog() -> &'static Arc { static CATALOG: OnceLock> = OnceLock::new(); CATALOG.get_or_init(|| { use vm::{HostFunctionSchema, HostParamPassing, HostParamSchema, HostTypeSchema}; From ab839aecfe732c1a1fb9fd989883daf55daebe89 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 21:41:17 +0800 Subject: [PATCH 030/225] fix(lua): bind caller locals to synchronous return roots The ordered array stays a private transport. The caller reads each known slot into a local, and nil assignment writes nil. A result frame is released only when that local owns one. Core Ret and the callee Lua frame stay separate: publish happens while the Lua frame is still current, then retire leaves it. --- src/frontends/lua/heap/table.rs | 22 + tests/luajit_heap_runtime/candidate.rs | 595 ++++++++++++++---- tests/luajit_heap_runtime/return_frame.rs | 370 ++++++++++- .../value_boundary_tests.rs | 17 +- 4 files changed, 863 insertions(+), 141 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 208a03f..f719ec2 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -137,6 +137,18 @@ pub struct RootFrameId { generation: u32, } +impl RootFrameId { + /// Parts a private IR argument can carry without the witness owning the frame. + pub fn parts(self) -> (u32, u32) { + (self.index, self.generation) + } + + /// Rebuilds a frame id from those IR parts. A stale pair fails at use. + pub fn from_parts(index: u32, generation: u32) -> Self { + Self { index, generation } + } +} + #[derive(Clone, Copy, Debug)] enum SlotState { Free, @@ -476,6 +488,16 @@ impl LuaHeap { })) } + /// Upgrades the slot's weak carrier for a field read. The upgrade is not a root. + pub fn issued_value(&self, table: TableRef) -> Result { + self.require_live(table)?; + let carrier = self.slots[table.slot() as usize] + .carrier + .upgrade() + .ok_or(HeapError::StaleHandle)?; + Ok(Value::Array(carrier)) + } + /// Opens a root frame of `width` slots. Failure does not grow root storage. pub fn enter_roots(&mut self, width: u32) -> Result { if width == 0 || self.next_frame_generation == 0 { diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 7ef5b5f..c907f8d 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -19,13 +19,17 @@ const RETURN_SCALAR: &str = "lua_internal::return_scalar"; const TABLE_ARG: &str = "lua_internal::table_arg"; const NUMBER_ARG: &str = "lua_internal::number_arg"; +const BOOL_ARG: &str = "lua_internal::bool_arg"; +const STRING_ARG: &str = "lua_internal::string_arg"; const GATHER_ROOT: &str = "lua_internal::gather_root"; pub(super) const COLLECT: &str = "lua_internal::collect"; const ENTER_RESULT: &str = "lua_internal::enter_result_frame"; const ENTER_CALLEE: &str = "lua_internal::enter_callee_frame"; const ROOT_ISSUED: &str = "lua_internal::root_issued"; const SET_EDGE: &str = "lua_internal::set_edge"; +const GET_EDGE: &str = "lua_internal::get_edge"; pub(super) const FINISH_RETURN: &str = "lua_internal::finish_return"; +pub(super) const RETIRE_CALLEE: &str = "lua_internal::retire_callee"; const RELEASE_RESULT: &str = "lua_internal::release_result"; // Test-only witnesses. They place an ordinary VM array on the source path. // They are not Lua syntax and are not registered on the production entry. @@ -79,6 +83,8 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { for (name, result) in [ (TABLE_ARG, HostTypeSchema::Resource(key)), (NUMBER_ARG, HostTypeSchema::Float), + (BOOL_ARG, HostTypeSchema::Bool), + (STRING_ARG, HostTypeSchema::String), (COLLECT, HostTypeSchema::Float), ] { builder.function(HostFunctionSchema::with_return( @@ -87,13 +93,23 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { result, )); } - for (name, params) in [ - (ENTER_RESULT, vec![]), - (ENTER_CALLEE, vec!["width"]), - (ROOT_ISSUED, vec!["value", "slot", "role"]), - (SET_EDGE, vec!["from", "key", "to"]), - (FINISH_RETURN, vec!["values", "publish"]), - (RELEASE_RESULT, vec![]), + for (name, params, result) in [ + (ENTER_RESULT, vec![], HostTypeSchema::Unknown), + (ENTER_CALLEE, vec!["width"], HostTypeSchema::Float), + ( + ROOT_ISSUED, + vec!["value", "slot", "role"], + HostTypeSchema::Float, + ), + (SET_EDGE, vec!["from", "key", "to"], HostTypeSchema::Float), + (GET_EDGE, vec!["table", "key"], HostTypeSchema::Unknown), + ( + FINISH_RETURN, + vec!["values", "frame", "publish", "index", "callee"], + HostTypeSchema::Unknown, + ), + (RETIRE_CALLEE, vec!["flag", "frame"], HostTypeSchema::Float), + (RELEASE_RESULT, vec!["frame"], HostTypeSchema::Float), ] { builder.function(HostFunctionSchema::with_return( name, @@ -101,7 +117,7 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { .into_iter() .map(|param| HostParamSchema::value(param, HostTypeSchema::Unknown)) .collect(), - HostTypeSchema::Float, + result, )); } } @@ -117,13 +133,17 @@ pub(super) fn register( Op::ReturnScalar, Op::TableArg, Op::NumberArg, + Op::BoolArg, + Op::StringArg, Op::GatherRoot, Op::Collect, Op::EnterResult, Op::EnterCallee, Op::RootIssued, Op::SetEdge, + Op::GetEdge, Op::FinishReturn, + Op::RetireCallee, Op::ReleaseResult, Op::CopyFields, Op::ExternalShape, @@ -135,13 +155,17 @@ pub(super) fn register( Op::ReturnScalar => RETURN_SCALAR, Op::TableArg => TABLE_ARG, Op::NumberArg => NUMBER_ARG, + Op::BoolArg => BOOL_ARG, + Op::StringArg => STRING_ARG, Op::GatherRoot => GATHER_ROOT, Op::Collect => COLLECT, Op::EnterResult => ENTER_RESULT, Op::EnterCallee => ENTER_CALLEE, Op::RootIssued => ROOT_ISSUED, Op::SetEdge => SET_EDGE, + Op::GetEdge => GET_EDGE, Op::FinishReturn => FINISH_RETURN, + Op::RetireCallee => RETIRE_CALLEE, Op::ReleaseResult => RELEASE_RESULT, Op::CopyFields => COPY_FIELDS, Op::ExternalShape => EXTERNAL_SHAPE, @@ -163,13 +187,17 @@ enum Op { ReturnScalar, TableArg, NumberArg, + BoolArg, + StringArg, GatherRoot, Collect, EnterResult, EnterCallee, RootIssued, SetEdge, + GetEdge, FinishReturn, + RetireCallee, ReleaseResult, CopyFields, ExternalShape, @@ -187,6 +215,9 @@ impl HostOwnedFunction for Op { return Err(VmError::HostError("invalid private Lua value".to_string())); } }; + if matches!(value, Value::Null) { + return Ok(CallOutcome::Return(CallReturn::one(Value::string("nil")))); + } let name = match classify(&mut call.vm().host_context(), &value)? { heap::GuestClass::Table(_) => "table", heap::GuestClass::Number => "number", @@ -230,7 +261,9 @@ impl HostOwnedFunction for Op { } } Self::ReturnScalar => match call.args() { - [value @ (Value::Float(_) | Value::String(_) | Value::Bool(_))] => value.clone(), + [value @ (Value::Float(_) | Value::String(_) | Value::Bool(_) | Value::Null)] => { + value.clone() + } _ => { return Err(VmError::HostError( "Lua result needs a typed adapter".to_string(), @@ -261,6 +294,14 @@ impl HostOwnedFunction for Op { [Value::Float(number)] => Value::Float(*number), _ => return Err(VmError::HostError("expected Lua number".to_string())), }, + Self::BoolArg => match call.args() { + [Value::Bool(value)] => Value::Bool(*value), + _ => return Err(VmError::HostError("expected Lua boolean".to_string())), + }, + Self::StringArg => match call.args() { + [Value::String(value)] => Value::string(value.as_str()), + _ => return Err(VmError::HostError("expected Lua string".to_string())), + }, Self::GatherRoot => { let value = match call.args() { [_, value] => value.clone(), @@ -328,7 +369,9 @@ impl HostOwnedFunction for Op { Self::EnterCallee => enter_callee(call)?, Self::RootIssued => root_issued(call)?, Self::SetEdge => set_edge(call)?, + Self::GetEdge => get_edge(call)?, Self::FinishReturn => finish_return(call)?, + Self::RetireCallee => retire_callee(call)?, Self::ReleaseResult => release_result(call)?, Self::CopyFields => match call.args() { [Value::Array(fields)] => Value::array(fields.iter().cloned().collect()), @@ -380,11 +423,43 @@ fn read_edge( heap: &heap::LuaHeap, table: Option, key: Option, -) -> Option { - match (table, key) { - (Some(table), Some(key)) => heap.edge(table, key).ok().flatten(), - _ => None, +) -> Result { + let (Some(table), Some(key)) = (table, key) else { + return Ok(EdgeView::Absent); + }; + match heap.edge(table, key) { + Ok(Some(target)) => Ok(EdgeView::Live(target)), + Ok(None) => Ok(EdgeView::Absent), + Err(heap::HeapError::StaleHandle) => Ok(EdgeView::Stale), + Err(error) => Err(error), + } +} + +fn decode_frame(call: &mut OwnedHostCall<'_>, token: &Value) -> Result { + if matches!( + classify(&mut call.vm().host_context(), token)?, + heap::GuestClass::Table(_) + ) { + return Err(host_fault("caller frame token is not a private array")); } + let Value::Array(parts) = token else { + return Err(host_fault("caller frame token is not a private array")); + }; + let [Value::Float(index), Value::Float(generation)] = parts.as_slice() else { + return Err(host_fault("caller frame token is not a private array")); + }; + Ok(heap::RootFrameId::from_parts( + float_u32(&Value::Float(*index))?, + float_u32(&Value::Float(*generation))?, + )) +} + +fn frame_token(frame: heap::RootFrameId) -> Value { + let (index, generation) = frame.parts(); + Value::array(vec![ + Value::Float(index as f64), + Value::Float(generation as f64), + ]) } fn enter_result(call: &mut OwnedHostCall<'_>) -> Result { @@ -392,10 +467,9 @@ fn enter_result(call: &mut OwnedHostCall<'_>) -> Result { .map_err(heap_error)?; let depth = call.vm().call_depth(); with_witness(call.vm(), |witness| { - witness.caller_frame = Some(frame); witness.caller_depth = Some(depth); })?; - Ok(Value::Float(0.0)) + Ok(frame_token(frame)) } fn enter_callee(call: &mut OwnedHostCall<'_>) -> Result { @@ -403,20 +477,15 @@ fn enter_callee(call: &mut OwnedHostCall<'_>) -> Result { [value] => float_u32(value)?, _ => return Err(host_fault("invalid callee frame width")), }; - let frame = if width == 0 { - None - } else { - Some( - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.enter_roots(width) - }) - .map_err(heap_error)?, - ) - }; + if width > 0 { + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.enter_roots(width) + }) + .map_err(heap_error)?; + } let depth = call.vm().call_depth(); with_witness(call.vm(), |witness| { witness.callee_depth = Some(depth); - witness.callee_frame = frame; })?; Ok(Value::Float(0.0)) } @@ -430,21 +499,22 @@ fn root_issued(call: &mut OwnedHostCall<'_>) -> Result { heap::GuestClass::Table(table) => table, _ => return Err(host_fault("issued root is not a table")), }; - let frame = with_witness(call.vm(), |witness| { - let frame = witness.callee_frame?; + let frame = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.current_frame().ok_or(heap::HeapError::StaleFrame) + }) + .map_err(heap_error)?; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.write_root(frame, slot, table) + }) + .map_err(heap_error)?; + with_witness(call.vm(), |witness| { if role == 0 { witness.returned = Some(table); witness.returned_carrier = carrier_ptr(&value); } else if witness.discarded.is_none() { witness.discarded = Some(table); } - Some(frame) - })? - .ok_or_else(|| host_fault("no callee root frame"))?; - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.write_root(frame, slot, table) - }) - .map_err(heap_error)?; + })?; Ok(Value::Float(0.0)) } @@ -474,70 +544,98 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { } fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { - let (values, publish) = match call.args() { - [Value::Array(values), Value::Float(flag)] => (values.clone(), *flag != 0.0), + let (values, frame_token, publish, table_at, callee_flag) = match call.args() { + [ + Value::Array(values), + frame, + Value::Float(publish), + index, + Value::Float(flag), + ] => ( + values.clone(), + frame.clone(), + *publish != 0.0, + float_u32(index)?, + *flag != 0.0, + ), _ => return Err(host_fault("Lua return transport is not one array")), }; + let transport = Value::Array(values.clone()); + if matches!( + classify(&mut call.vm().host_context(), &transport)?, + heap::GuestClass::Table(_) + ) { + return Err(host_fault( + "Lua return transport must stay an unissued array", + )); + } + // Core has already executed Ret. The callee Lua root frame, if any, is still current. let depth = call.vm().call_depth(); let mut elements = Vec::with_capacity(values.len()); - let mut returned_value = None; for value in values.iter() { - elements.push(return_element(call, value, &mut returned_value)?); + elements.push(return_element(call, value)?); } - let (returned, discarded, key, caller_frame, callee_frame) = - with_witness(call.vm(), |witness| { - ( - witness.returned, - witness.discarded, - witness.field_key, - witness.caller_frame, - witness.callee_frame, - ) - })?; - let (returned_edge, discarded_edge) = heap::with_heap(&mut call.vm().host_context(), |heap| { - Ok(( - read_edge(heap, returned, key), - read_edge(heap, discarded, key), - )) - }) - .map_err(heap_error)?; - let mut published = false; - if publish && let (Some(frame), Some(table)) = (caller_frame, returned_value) { + if publish { + let element = values + .get(table_at as usize) + .ok_or_else(|| host_fault("published return is not an issued table"))?; + let table = match classify(&mut call.vm().host_context(), element)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("published return is not an issued table")), + }; + let frame = decode_frame(call, &frame_token)?; + // Publish the caller root before any later retire removes the callee frame. heap::with_heap(&mut call.vm().host_context(), |heap| { heap.write_root(frame, 0, table) }) .map_err(heap_error)?; - published = true; } - let mut callee_left = false; - if let Some(frame) = callee_frame { + let lua_frame_alive = if callee_flag { heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.leave_roots(frame) + Ok(heap.current_frame().is_some()) }) - .map_err(heap_error)?; - callee_left = true; - } - let top_is_caller = heap::with_heap(&mut call.vm().host_context(), |heap| { - Ok(caller_frame.is_some() && heap.current_frame() == caller_frame) + .map_err(heap_error)? + } else { + false + }; + let (returned, discarded, key, callee_depth) = with_witness(call.vm(), |witness| { + ( + witness.returned, + witness.discarded, + witness.field_key, + witness.callee_depth, + ) + })?; + let (returned_edge, discarded_edge) = heap::with_heap(&mut call.vm().host_context(), |heap| { + Ok(( + read_edge(heap, returned, key)?, + read_edge(heap, discarded, key)?, + )) }) .map_err(heap_error)?; with_witness(call.vm(), |witness| { - witness.elements = elements; - witness.published_root = published; - witness.callee_left = callee_left; - witness.top_is_caller_after_handoff = top_is_caller; + witness.elements = elements.clone(); + witness.published_root = publish; witness.handoff_depth = Some(depth); + witness.lua_frame_alive_at_publish = lua_frame_alive; witness.returned_edge_at_handoff = returned_edge; witness.discarded_edge_at_handoff = discarded_edge; + witness.handoffs.push(Handoff { + elements, + published_root: publish, + callee_left: false, + top_is_caller_after_handoff: false, + lua_frame_alive_at_publish: lua_frame_alive, + handoff_depth: Some(depth), + callee_depth, + returned_edge, + discarded_edge, + }); })?; - Ok(Value::Float(values.len() as f64)) + Ok(transport) } -fn return_element( - call: &mut OwnedHostCall<'_>, - value: &Value, - returned_value: &mut Option, -) -> Result { +fn return_element(call: &mut OwnedHostCall<'_>, value: &Value) -> Result { match value { Value::Null => Ok(ReturnedElement::Nil), Value::Float(number) => Ok(ReturnedElement::Number(*number)), @@ -554,9 +652,6 @@ fn return_element( ); (same_ref, same_carrier) })?; - if same_ref { - *returned_value = Some(table); - } Ok(ReturnedElement::Table { same_ref, same_carrier, @@ -565,15 +660,77 @@ fn return_element( } } -fn release_result(call: &mut OwnedHostCall<'_>) -> Result { - let (returned, key, frame) = with_witness(call.vm(), |witness| { - (witness.returned, witness.field_key, witness.caller_frame) +fn retire_callee(call: &mut OwnedHostCall<'_>) -> Result { + let (flag, frame_token) = match call.args() { + [Value::Float(flag), frame] => (*flag != 0.0, frame.clone()), + _ => return Err(host_fault("invalid callee retire")), + }; + let caller = if matches!(frame_token, Value::Null) { + None + } else { + Some(decode_frame(call, &frame_token)?) + }; + let mut left = false; + if flag { + let callee = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.current_frame().ok_or(heap::HeapError::StaleFrame) + }) + .map_err(heap_error)?; + if caller == Some(callee) { + return Err(host_fault("would retire the caller result frame")); + } + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(callee) + }) + .map_err(heap_error)?; + left = true; + } + let top_is_caller = heap::with_heap(&mut call.vm().host_context(), |heap| { + Ok(caller.is_some() && heap.current_frame() == caller) + }) + .map_err(heap_error)?; + with_witness(call.vm(), |witness| { + witness.callee_left = left; + witness.top_is_caller_after_handoff = top_is_caller; + if let Some(last) = witness.handoffs.last_mut() { + last.callee_left = left; + last.top_is_caller_after_handoff = top_is_caller; + } })?; - let frame = frame.ok_or_else(|| host_fault("no caller result frame"))?; + Ok(Value::Float(0.0)) +} + +fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { + let (from, key) = match call.args() { + [from, key] => (from.clone(), float_u32(key)?), + _ => return Err(host_fault("invalid field read")), + }; + let table = match classify(&mut call.vm().host_context(), &from)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("field source is not a table")), + }; + let target = heap::with_heap(&mut call.vm().host_context(), |heap| heap.edge(table, key)) + .map_err(heap_error)?; + let Some(target) = target else { + return Ok(Value::Null); + }; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.issued_value(target) + }) + .map_err(heap_error) +} + +fn release_result(call: &mut OwnedHostCall<'_>) -> Result { + let frame_token = match call.args() { + [frame] => frame.clone(), + _ => return Err(host_fault("invalid result release")), + }; + let frame = decode_frame(call, &frame_token)?; + let (returned, key) = with_witness(call.vm(), |witness| (witness.returned, witness.field_key))?; let (alive, edge) = heap::with_heap(&mut call.vm().host_context(), |heap| { Ok(( returned.is_some_and(|table| heap.alive(table)), - read_edge(heap, returned, key), + read_edge(heap, returned, key)?, )) }) .map_err(heap_error)?; @@ -585,7 +742,6 @@ fn release_result(call: &mut OwnedHostCall<'_>) -> Result { .map_err(heap_error)? .live_roots; with_witness(call.vm(), |witness| { - witness.caller_frame = None; witness.release = Some(ReleaseNote { returned_alive: alive, returned_edge: edge, @@ -609,7 +765,7 @@ fn note_collect( Ok(( returned.is_some_and(|table| heap.alive(table)), discarded.is_some_and(|table| heap.alive(table)), - read_edge(heap, returned, key), + read_edge(heap, returned, key)?, )) }) .map_err(heap_error)?; @@ -688,12 +844,12 @@ pub(super) fn lower_returning( stmts: Vec::new(), functions: HashMap::new(), function_impls: HashMap::new(), - result_bindings: HashSet::new(), + result_frames: HashMap::new(), + table_locals: HashSet::new(), field_keys: HashMap::new(), publish_results, in_function: false, return_names: HashSet::new(), - function_returns_table: false, root_slot: 0, ignored_slot: None, }; @@ -718,12 +874,12 @@ struct Lower<'a> { stmts: Vec, functions: HashMap, FuncInfo>, function_impls: HashMap, - result_bindings: HashSet>, + result_frames: HashMap, LocalSlot>, + table_locals: HashSet>, field_keys: HashMap, u32>, publish_results: bool, in_function: bool, return_names: HashSet>, - function_returns_table: bool, root_slot: u32, ignored_slot: Option, } @@ -731,7 +887,9 @@ struct Lower<'a> { #[derive(Clone, Copy)] struct FuncInfo { index: u16, - returns_table: bool, + callee_width: u32, + table_at: Option, + return_count: u32, } impl Lower<'_> { @@ -740,6 +898,15 @@ impl Lower<'_> { ast::Stmt::LocalFunction { span, name, func, .. } => self.lower_function(name, func, *span), + ast::Stmt::Local { + span, + names, + values, + } if values.exprs.len() == 1 + && self.direct_function_call(&values.exprs[0]).is_some() => + { + self.lower_call_local(*span, names, &values.exprs[0]) + } ast::Stmt::Local { span, names, @@ -781,17 +948,12 @@ impl Lower<'_> { name: &ast::Name, value: &ast::Expr, ) -> Result<(), ParseError> { - let returns_call = self.direct_function_call(value).is_some(); let expr = self.expr(value)?; let index = self .builder .alloc_local_named(&format!("#{}", span.start))?; self.locals.insert(name.bytes.clone(), index); - if returns_call { - self.result_bindings.insert(name.bytes.clone()); - } else { - self.live_locals.push(index); - } + self.live_locals.push(index); self.stmts.push(Stmt::Let { index, declared_schema: None, @@ -800,8 +962,8 @@ impl Lower<'_> { }); if self.in_function && matches!(value, ast::Expr::Table { fields, .. } if fields.is_empty()) { + self.table_locals.insert(name.bytes.clone()); let role = if self.return_names.contains(&name.bytes) { - self.function_returns_table = true; 0.0 } else { 1.0 @@ -828,11 +990,24 @@ impl Lower<'_> { value: &ast::Expr, ) -> Result<(), ParseError> { match (target, value) { - (ast::AssignTarget::Name(name), ast::Expr::Nil { .. }) - if self.result_bindings.contains(&name.bytes) => - { - let expr = self.call(RELEASE_RESULT, vec![])?; - self.emit_ignored(expr, self.line(span)) + (ast::AssignTarget::Name(name), ast::Expr::Nil { .. }) => { + let slot = self + .locals + .get(&name.bytes) + .copied() + .ok_or_else(|| self.unsupported(span))?; + self.stmts.push(Stmt::Assign { + kind: AssignmentKind::Set, + index: slot, + expr: Expr::Null, + line: self.line(span), + }); + self.live_locals.retain(|local| *local != slot); + if let Some(frame) = self.result_frames.remove(&name.bytes) { + let release = self.call(RELEASE_RESULT, vec![Expr::Var(frame)])?; + self.emit_ignored(release, self.line(span))?; + } + Ok(()) } ( ast::AssignTarget::Field { @@ -876,7 +1051,8 @@ impl Lower<'_> { let saved_live = std::mem::take(&mut self.live_locals); let saved_temps = std::mem::take(&mut self.active_temps); let saved_stmts = std::mem::take(&mut self.stmts); - let saved_results = std::mem::take(&mut self.result_bindings); + let saved_results = std::mem::take(&mut self.result_frames); + let saved_tables = std::mem::take(&mut self.table_locals); let saved_return_names = std::mem::replace( &mut self.return_names, returns @@ -887,11 +1063,9 @@ impl Lower<'_> { }) .collect(), ); - let saved_returns_table = self.function_returns_table; let saved_root_slot = self.root_slot; let saved_ignored = self.ignored_slot; let saved_in_function = self.in_function; - self.function_returns_table = false; self.root_slot = 0; self.ignored_slot = None; self.in_function = true; @@ -905,14 +1079,27 @@ impl Lower<'_> { } let body_expr = self.pack_return(returns)?; let body_stmts = std::mem::take(&mut self.stmts); - let returns_table = self.function_returns_table; + let table_positions: Vec = returns + .iter() + .enumerate() + .filter_map(|(index, expr)| match expr { + ast::Expr::Name { name, .. } if self.table_locals.contains(&name.bytes) => { + Some(index as u32) + } + _ => None, + }) + .collect(); + if table_positions.len() > 1 { + return Err(self.unsupported(span)); + } + let table_at = table_positions.first().copied(); self.locals = saved_locals; self.live_locals = saved_live; self.active_temps = saved_temps; self.stmts = saved_stmts; - self.result_bindings = saved_results; + self.result_frames = saved_results; + self.table_locals = saved_tables; self.return_names = saved_return_names; - self.function_returns_table = saved_returns_table; self.root_slot = saved_root_slot; self.ignored_slot = saved_ignored; self.in_function = saved_in_function; @@ -930,7 +1117,9 @@ impl Lower<'_> { name.bytes.clone(), FuncInfo { index, - returns_table, + callee_width: width, + table_at, + return_count: u32::try_from(returns.len()).expect("return count"), }, ); Ok(()) @@ -985,23 +1174,132 @@ impl Lower<'_> { } } - fn finish_call(&mut self, name: &[u8], span: ast::Span) -> Result { + fn lower_call_local( + &mut self, + span: ast::Span, + names: &[ast::LocalName], + call: &ast::Expr, + ) -> Result<(), ParseError> { + let callee = self + .direct_function_call(call) + .ok_or_else(|| self.unsupported(span))?; let info = self .functions - .get(name) + .get(&callee.bytes) .copied() .ok_or_else(|| self.unsupported(span))?; - if info.returns_table { - let enter = self.call(ENTER_RESULT, vec![])?; - self.emit_ignored(enter, self.line(span))?; + let line = self.line(span); + let mut slots = Vec::with_capacity(names.len()); + for (offset, name) in names.iter().enumerate() { + let index = self + .builder + .alloc_local_named(&format!("#{}:{offset}", span.start))?; + self.locals.insert(name.name.bytes.clone(), index); + slots.push((name.name.bytes.clone(), index)); } - let call = Expr::Call(info.index, vec![], vec![], None, None); - let publish = if self.publish_results && info.returns_table { + let frame_slot = if info.table_at.is_some() { + let slot = self + .builder + .alloc_local_named(&format!("#frame:{}", span.start))?; + let enter = self.call(ENTER_RESULT, vec![])?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: enter, + line, + }); + Some(slot) + } else { + None + }; + let transport = self + .builder + .alloc_local_named(&format!("#ret:{}", span.start))?; + let call_expr = Expr::Call(info.index, vec![], vec![], None, None); + let publish = if self.publish_results && info.table_at.is_some() { 1.0 } else { 0.0 }; - self.call(FINISH_RETURN, vec![call, Expr::Float(publish)]) + let frame_expr = frame_slot.map(Expr::Var).unwrap_or(Expr::Null); + // The script call is the transport argument. Core Ret runs inside that + // call. finish_return then publishes, while the callee Lua frame is still current. + let finish = self.call( + FINISH_RETURN, + vec![ + call_expr, + frame_expr.clone(), + Expr::Float(publish), + Expr::Float(info.table_at.unwrap_or(0) as f64), + Expr::Float(if info.callee_width > 0 { 1.0 } else { 0.0 }), + ], + )?; + self.stmts.push(Stmt::Let { + index: transport, + declared_schema: None, + expr: finish, + line, + }); + let get = vm::BuiltinFunction::Get.call_index(); + for (index, (_, slot)) in slots.iter().enumerate() { + let expr = if (index as u32) < info.return_count { + Expr::Call( + get, + vec![], + vec![Expr::Var(transport), Expr::Int(index as i64)], + None, + None, + ) + } else { + Expr::Null + }; + self.stmts.push(Stmt::Let { + index: *slot, + declared_schema: None, + expr, + line, + }); + } + if let (Some(at), Some(frame)) = (info.table_at, frame_slot) + && let Some((name, _)) = slots.get(at as usize) + { + self.result_frames.insert(name.clone(), frame); + } + let retire = self.call( + RETIRE_CALLEE, + vec![ + Expr::Float(if info.callee_width > 0 { 1.0 } else { 0.0 }), + frame_expr, + ], + )?; + self.emit_ignored(retire, line)?; + if slots.is_empty() + && let Some(frame) = frame_slot + { + let release = self.call(RELEASE_RESULT, vec![Expr::Var(frame)])?; + self.emit_ignored(release, line)?; + } + Ok(()) + } + + fn field_read( + &mut self, + base: &ast::Expr, + key_name: &[u8], + span: ast::Span, + ) -> Result { + let table = self.expr(base)?; + let slot = self + .builder + .alloc_local_named(&format!("#field:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: table, + line: self.line(span), + }); + let key = self.field_key(key_name); + self.call(GET_EDGE, vec![Expr::Var(slot), Expr::Float(key as f64)]) } fn field_key(&mut self, name: &[u8]) -> u32 { @@ -1076,6 +1374,25 @@ impl Lower<'_> { } Ok(left) } + ast::Expr::SuffixChain { steps, span, .. } + if steps + .iter() + .any(|step| matches!(step, ast::Suffix::Index { .. })) => + { + Err(ParseError::at_line( + self.line(*span) as usize, + "numeric table keys are not in this field-key subset", + )) + } + ast::Expr::SuffixChain { base, steps, span } + if let [ + ast::Suffix::Field { + name, nav: false, .. + }, + ] = steps.as_slice() => + { + self.field_read(base, &name.bytes, *span) + } ast::Expr::SuffixChain { base, steps, .. } if let ast::Expr::Name { name, .. } = base.as_ref() && !self.locals.contains_key(&name.bytes) @@ -1091,7 +1408,8 @@ impl Lower<'_> { if !args.exprs.is_empty() { return Err(self.unsupported(expr.span())); } - return self.finish_call(&name.bytes, expr.span()); + self.lower_call_local(expr.span(), &[], expr)?; + return Ok(Expr::Null); } if name.is("type") && let [arg] = args.exprs.as_slice() @@ -1153,6 +1471,8 @@ impl Lower<'_> { for (arg, param) in args.iter().zip(&function.params) { let adapter = match (¶m.ty, param.passing) { (HostTypeSchema::Float, vm::HostParamPassing::Value) => NUMBER_ARG, + (HostTypeSchema::Bool, vm::HostParamPassing::Value) => BOOL_ARG, + (HostTypeSchema::String, vm::HostParamPassing::Value) => STRING_ARG, (HostTypeSchema::Resource(key), vm::HostParamPassing::Borrow) if *key == heap::LuaTableResource::key() => { @@ -1326,16 +1646,39 @@ pub(super) struct ReturnWitness { pub discarded: Option, pub returned_carrier: Option, pub field_key: Option, - pub returned_edge_at_handoff: Option, - pub discarded_edge_at_handoff: Option, + pub returned_edge_at_handoff: EdgeView, + pub discarded_edge_at_handoff: EdgeView, pub elements: Vec, pub published_root: bool, pub callee_left: bool, pub top_is_caller_after_handoff: bool, + /// True when the callee Lua frame was still current after the caller root was written. + /// Core's `Ret` has already run; this is not the same fact. + pub lua_frame_alive_at_publish: bool, pub collects: Vec, pub release: Option, - caller_frame: Option, - callee_frame: Option, + pub handoffs: Vec, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum EdgeView { + #[default] + Absent, + Live(heap::TableRef), + Stale, +} + +#[derive(Clone, Debug)] +pub(super) struct Handoff { + pub elements: Vec, + pub published_root: bool, + pub callee_left: bool, + pub top_is_caller_after_handoff: bool, + pub lua_frame_alive_at_publish: bool, + pub handoff_depth: Option, + pub callee_depth: Option, + pub returned_edge: EdgeView, + pub discarded_edge: EdgeView, } #[derive(Clone, Debug)] @@ -1353,13 +1696,13 @@ pub(super) struct CollectNote { pub swept: u64, pub returned_alive: bool, pub discarded_alive: bool, - pub returned_edge: Option, + pub returned_edge: EdgeView, } #[derive(Clone, Debug)] pub(super) struct ReleaseNote { pub returned_alive: bool, - pub returned_edge: Option, + pub returned_edge: EdgeView, pub live_roots: u32, } diff --git a/tests/luajit_heap_runtime/return_frame.rs b/tests/luajit_heap_runtime/return_frame.rs index 529b1b6..ca8311d 100644 --- a/tests/luajit_heap_runtime/return_frame.rs +++ b/tests/luajit_heap_runtime/return_frame.rs @@ -1,17 +1,77 @@ //! Real uncaptured Lua calls and the explicit return-root handoff. //! -//! The sources are legal Lua. Observation stays in the candidate witness: -//! Core's nested `Ret` still carries one value, and that value is the private -//! ordered result array. `self` is an ordinary field name. +//! The sources are legal Lua. The callee's `Ret` still carries one value, the +//! private ordered result array. The caller binds that array into locals and +//! reads those locals. `self` is an ordinary field name. Numeric keys are refused. -use super::candidate::{self, ReturnWitness, ReturnedElement}; -use super::catalog; +use super::candidate::{self, EdgeView, ReturnWitness, ReturnedElement}; +use super::{catalog, heap, register_witnesses}; use std::sync::Arc; use vm::{ CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, OpCode, ParseError, Program, SourceFlavor, SourcePlugin, Value, VmStatus, }; +#[derive(Clone, Debug, PartialEq)] +struct CallerReads { + field_same: bool, + gap: String, + missing: String, + single: String, + total: f64, + cleared: String, +} + +fn register_caller_reads(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + let function = catalog + .function("lua_host::caller_reads") + .expect("caller reads schema"); + registry + .register_exact_owned( + "lua_host::caller_reads", + function.params.len() as u8, + vm::HostImportSchema::from_function(catalog, function), + |_| Box::new(CallerReadsHost), + ) + .expect("register caller reads"); +} + +struct CallerReadsHost; + +impl vm::HostOwnedFunction for CallerReadsHost { + fn call(&mut self, call: &mut vm::OwnedHostCall<'_>) -> Result { + let [ + Value::Bool(field_same), + Value::String(gap), + Value::String(missing), + Value::String(single), + Value::Float(total), + Value::String(cleared), + ] = call.args() + else { + return Err(vm::VmError::HostError( + "caller reads need the Lua local observations".to_string(), + )); + }; + let cleared = cleared.to_string(); + let reads = CallerReads { + field_same: *field_same, + gap: gap.to_string(), + missing: missing.to_string(), + single: single.to_string(), + total: *total, + cleared: cleared.clone(), + }; + call.vm() + .host_context() + .scope_state_or_insert_with(|| reads) + .map_err(|error| vm::VmError::HostError(error.to_string()))?; + Ok(vm::CallOutcome::Return(vm::CallReturn::one(Value::string( + &cleared, + )))) + } +} + struct PublishingReturn; struct UnpublishedReturn; @@ -65,9 +125,16 @@ fn run(source: &str, publish_results: bool) -> vm::Vm { .expect("create VM"); let mut registry = HostFunctionRegistry::empty(); candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register_witnesses(&mut registry, &catalog); + register_caller_reads(&mut registry, &catalog); registry .bind_vm_cached(&mut vm) .expect("bind candidate runtime"); + vm.set_jit_config(vm::JitConfig { + enabled: false, + hot_loop_threshold: 0, + max_trace_len: 0, + }); vm } @@ -110,11 +177,100 @@ kept = nil collectgarbage(\"collect\") "; +const SEQUENTIAL: &str = "\ +local function make() + local returned = {} + return returned +end +local function zero() + return +end +local kept = make() +local missing = zero() +return type(missing) +"; + +const NONE_THEN_NIL: &str = "\ +local function none() + return +end +local n = none() +n = nil +return type(n) +"; + +const ORDINARY_NIL: &str = "\ +local n = 1 +n = nil +return type(n) +"; + +const CONSUME: &str = "\ +local function make() + local returned = {} + local discarded = {} + local alias = returned + alias.self = returned + local other = discarded + other.self = discarded + return returned, nil, 9 +end +local function zero() + return +end +local function one() + return nil +end +local kept, gap, value = make() +local missing = zero() +local single = one() +local field_ok = same_table(kept, kept.self) +local gap_kind = type(gap) +local missing_kind = type(missing) +local single_kind = type(single) +local total = value + 1 +collectgarbage(\"collect\") +kept = nil +local cleared = type(kept) +collectgarbage(\"collect\") +return caller_reads(field_ok, gap_kind, missing_kind, single_kind, total, cleared) +"; + +const VALUE_ORACLE: &str = "\ +local function make() + local returned = {} + returned.self = returned + return returned, nil, 9 +end +local function zero() + return +end +local function one() + return nil +end +local kept, gap, value = make() +local missing = zero() +local single = one() +local total = value + 1 +local field_same = kept.self == kept +kept = nil +io.write(tostring(field_same), \" \", tostring(gap == nil), \" \", tostring(missing == nil), \" \", tostring(single == nil), \" \", tostring(total), \" \", tostring(kept == nil), \"\\n\") +local n = 1 +n = nil +io.write(tostring(n == nil), \"\\n\") +local function none() + return +end +local m = none() +m = nil +io.write(tostring(m == nil), \"\\n\") +"; + #[test] fn zero_return_uses_a_real_frame_and_exact_arity() { let mut vm = run(ZERO, true); assert_eq!(vm.run().unwrap(), VmStatus::Halted); - assert_eq!(vm.stack(), &[Value::Float(0.0)]); + assert_eq!(vm.stack(), &[Value::Null]); let witness = witness(&mut vm); assert!(witness.elements.is_empty()); assert_retired_call(&witness); @@ -127,7 +283,7 @@ fn zero_return_uses_a_real_frame_and_exact_arity() { fn one_nil_keeps_exact_arity_and_nil_position() { let mut vm = run(ONE_NIL, true); assert_eq!(vm.run().unwrap(), VmStatus::Halted); - assert_eq!(vm.stack(), &[Value::Float(1.0)]); + assert_eq!(vm.stack(), &[Value::Null]); let witness = witness(&mut vm); assert!(matches!( witness.elements.as_slice(), @@ -157,15 +313,19 @@ fn table_nil_number_handoff_keeps_the_returned_object_only() { let returned = witness.returned.expect("issued returned table"); let discarded = witness.discarded.expect("issued discarded table"); assert_ne!(returned, discarded); - assert_eq!(witness.returned_edge_at_handoff, Some(returned)); - assert_eq!(witness.discarded_edge_at_handoff, Some(discarded)); + assert_eq!(witness.returned_edge_at_handoff, EdgeView::Live(returned)); + assert_eq!(witness.discarded_edge_at_handoff, EdgeView::Live(discarded)); assert!(witness.published_root); assert!(witness.callee_left); assert!(witness.top_is_caller_after_handoff); + assert!( + witness.lua_frame_alive_at_publish, + "Core has already Ret; the callee Lua frame is a separate fact" + ); assert_retired_call(&witness); let first = &witness.collects[0]; assert!(first.returned_alive); - assert_eq!(first.returned_edge, Some(returned)); + assert_eq!(first.returned_edge, EdgeView::Live(returned)); assert!(!first.discarded_alive); assert_eq!(first.marked_nodes, 1); assert_eq!(first.live_roots, 1); @@ -173,11 +333,12 @@ fn table_nil_number_handoff_keeps_the_returned_object_only() { assert_eq!(first.swept, 1); let release = witness.release.expect("caller dropped the result root"); assert!(release.returned_alive); - assert_eq!(release.returned_edge, Some(returned)); + assert_eq!(release.returned_edge, EdgeView::Live(returned)); assert_eq!(release.live_roots, 0); let second = &witness.collects[1]; assert!(!second.returned_alive); - assert!(second.returned_edge.is_none()); + assert_eq!(second.returned_edge, EdgeView::Stale); + assert_stale_edge(&mut vm, returned, witness.field_key); assert!(!second.discarded_alive); assert_eq!(second.marked_nodes, 0); assert_eq!(second.live_roots, 0); @@ -196,7 +357,12 @@ fn omitting_only_the_result_root_drops_the_returned_table_on_first_collect() { assert_retired_call(&witness); let first = &witness.collects[0]; assert!(!first.returned_alive, "the returned table is unusable"); - assert!(first.returned_edge.is_none()); + assert_eq!(first.returned_edge, EdgeView::Stale); + assert_stale_edge( + &mut vm, + witness.returned.expect("issued returned table"), + witness.field_key, + ); assert!(!first.discarded_alive); assert_eq!(first.marked_nodes, 0); assert_eq!(first.live_roots, 0); @@ -204,6 +370,157 @@ fn omitting_only_the_result_root_drops_the_returned_table_on_first_collect() { assert_real_return_window(vm.program()); } +#[test] +fn sequential_calls_do_not_reuse_the_previous_guest_result() { + let mut vm = run(SEQUENTIAL, true); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let witness = witness(&mut vm); + assert_eq!(witness.handoffs.len(), 2); + assert!(matches!( + witness.handoffs[0].elements.as_slice(), + [ReturnedElement::Table { + same_ref: true, + same_carrier: true, + }] + )); + assert!(witness.handoffs[1].elements.is_empty()); + assert_eq!( + witness.handoffs[0].callee_depth, witness.handoffs[1].callee_depth, + "sibling calls share depth; they must not share the result array" + ); + assert!(witness.handoffs[0].handoff_depth.is_some()); + assert_eq!( + witness.handoffs[0].handoff_depth, + witness.handoffs[1].handoff_depth + ); + assert_eq!(witness.handoffs[0].returned_edge, EdgeView::Absent); + assert_eq!(witness.handoffs[1].discarded_edge, EdgeView::Absent); +} + +#[test] +fn nil_assignment_after_empty_return_writes_nil() { + let mut vm = run(NONE_THEN_NIL, true); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); +} + +#[test] +fn ordinary_nil_assignment_writes_nil() { + let mut vm = run(ORDINARY_NIL, true); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); +} + +#[test] +fn caller_reads_table_nil_and_number_then_clears_the_local() { + assert_value_oracle(); + let mut vm = run(CONSUME, true); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let reads = vm + .host_context() + .scope_state::() + .cloned() + .expect("Lua caller reads"); + assert_eq!( + reads, + CallerReads { + field_same: true, + gap: "nil".to_string(), + missing: "nil".to_string(), + single: "nil".to_string(), + total: 10.0, + cleared: "nil".to_string(), + } + ); + let witness = witness(&mut vm); + assert_eq!(witness.handoffs.len(), 3); + assert!(matches!( + witness.handoffs[0].elements.as_slice(), + [ + ReturnedElement::Table { + same_ref: true, + same_carrier: true, + }, + ReturnedElement::Nil, + ReturnedElement::Number(9.0), + ] + )); + assert!(witness.handoffs[0].published_root); + assert!(witness.handoffs[0].lua_frame_alive_at_publish); + assert!(witness.handoffs[0].callee_left); + assert!(witness.handoffs[1].elements.is_empty()); + assert!(!witness.handoffs[1].published_root); + assert!(matches!( + witness.handoffs[2].elements.as_slice(), + [ReturnedElement::Nil] + )); + let returned = witness.returned.expect("issued returned table"); + let first = &witness.collects[0]; + assert!(first.returned_alive); + assert!(!first.discarded_alive); + assert_eq!(first.swept, 1); + let second = &witness.collects[1]; + assert!(!second.returned_alive); + assert_eq!(second.returned_edge, EdgeView::Stale); + assert_stale_edge(&mut vm, returned, witness.field_key); +} + +#[test] +fn unpublished_consume_source_still_reclaims_on_first_collect() { + let mut vm = run(CONSUME, false); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + let witness = witness(&mut vm); + assert!(!witness.published_root); + let first = &witness.collects[0]; + assert!(!first.returned_alive); + assert!(!first.discarded_alive); + assert_eq!(first.swept, 2); + assert_eq!(vm.stack(), &[Value::string("nil")]); + assert!(!witness.handoffs[0].published_root); + assert!(witness.handoffs[0].lua_frame_alive_at_publish); + assert_eq!(first.returned_edge, EdgeView::Stale); +} + +fn assert_value_oracle() { + let Ok(oracle) = std::env::var("LUAJIT_ORACLE") else { + return; + }; + let dir = std::env::var("TMPDIR").expect("TMPDIR"); + let path = format!("{dir}/caller-value-oracle.lua"); + std::fs::write(&path, VALUE_ORACLE).expect("write oracle source"); + let output = std::process::Command::new(oracle) + .arg(&path) + .output() + .expect("run LuaJIT"); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!( + String::from_utf8(output.stdout).expect("oracle stdout"), + "true true true true 10 true\ntrue\ntrue\n" + ); +} + +#[test] +fn numeric_table_keys_are_refused() { + let error = candidate::lower_returning("local t = {}; local n = t[1]\n", catalog(), true) + .expect_err("numeric keys stay outside this field-key subset"); + assert!(error.to_string().contains("numeric table keys"), "{error}"); +} + +fn assert_stale_edge(vm: &mut vm::Vm, table: heap::TableRef, key: Option) { + let key = key.expect("field key"); + let edge = heap::with_heap(&mut vm.host_context(), |heap| heap.edge(table, key)); + assert!( + matches!(edge, Err(heap::HeapError::StaleHandle)), + "stale edge must stay structured, got {edge:?}" + ); +} + fn assert_retired_call(witness: &ReturnWitness) { let callee = witness.callee_depth.expect("callee depth"); let handoff = witness.handoff_depth.expect("depth after return"); @@ -231,7 +548,18 @@ fn assert_real_return_window(program: &Program) { ip += 1 + op.operand_len(); } let call_ip = call_ip.expect("CallScript"); - let function = &program.script_functions[prototype.expect("prototype") as usize]; + let prototype_id = prototype.expect("prototype"); + let prototype = program + .callable_prototypes + .get(prototype_id as usize) + .expect("callable prototype"); + let vm::CallableTarget::ScriptFunction(index) = prototype.target else { + panic!("CallScript target {prototype_id} is not a script function"); + }; + let function = program + .script_functions + .get(index as usize) + .expect("script function"); assert!(function.end_ip > function.entry_ip); assert!( call_ip < function.entry_ip as usize || call_ip >= function.end_ip as usize, @@ -254,6 +582,20 @@ fn assert_real_return_window(program: &Program) { } let finish_ip = next_call(program, call_ip, finish); assert_no_calls_between(program, call_ip, finish_ip); + let retire = import_index(program, candidate::RETIRE_CALLEE); + let retire_ip = next_call(program, finish_ip, retire); + assert!(retire_ip > finish_ip, "retire follows publish"); + if let Some(collect) = program + .imports + .iter() + .position(|import| import.name == candidate::COLLECT) + { + let collect = u16::try_from(collect).expect("import index"); + assert!( + !region_calls(program, finish_ip as u32, retire_ip as u32, collect), + "collect does not sit between publish and retire" + ); + } } fn import_index(program: &Program, name: &str) -> u16 { diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 15d3a07..72f5b90 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -152,6 +152,18 @@ pub(super) fn catalog() -> &'static Arc { vec![HostParamSchema::value("number", HostTypeSchema::Float)], HostTypeSchema::Float, )); + builder.function(HostFunctionSchema::with_return( + "lua_host::caller_reads", + vec![ + HostParamSchema::value("field_same", HostTypeSchema::Bool), + HostParamSchema::value("gap", HostTypeSchema::String), + HostParamSchema::value("missing", HostTypeSchema::String), + HostParamSchema::value("single", HostTypeSchema::String), + HostParamSchema::value("total", HostTypeSchema::Float), + HostParamSchema::value("cleared", HostTypeSchema::String), + ], + HostTypeSchema::String, + )); for (name, reverse) in [ ("lua_host::observe_table", false), ("lua_host::observe_table_after", true), @@ -177,7 +189,10 @@ pub(super) fn catalog() -> &'static Arc { }) } -fn register_witnesses(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { +pub(super) fn register_witnesses( + registry: &mut HostFunctionRegistry, + catalog: &vm::HostApiCatalog, +) { for (name, op) in [ ("lua_host::same_table", Witness::Tables), ("lua_host::observe_number", Witness::Number), From 07ee47a5c1815e1b06d30e716f0a811eafda9b65 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 22:53:37 +0800 Subject: [PATCH 031/225] fix(lua): root each consumed return binding in one caller frame A direct constructor name was the only published root, and each call owned a result frame that had to leave in stack order. An alias, a second consumed position, or an earlier sibling binding was therefore either unrooted or released with the wrong frame. The chunk now opens one caller frame sized to its receiving bindings. finish_return classifies each consumed value and writes only issued tables into that binding's slot. Nil clears that slot and leaves the frame, so leave_roots stays top-only for the callee frame. --- src/frontends/lua/heap/table.rs | 14 + tests/luajit_heap_runtime/candidate.rs | 230 ++++--- tests/luajit_heap_runtime/return_frame.rs | 568 ++++++++++++++++++ .../value_boundary_tests.rs | 32 + 4 files changed, 771 insertions(+), 73 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index f719ec2..f767102 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -548,6 +548,20 @@ impl LuaHeap { Ok(()) } + /// Clears one slot of an open frame. The frame does not have to be the + /// top frame. Other slots, including another slot holding the same table, + /// stay. A stale id or an out-of-range slot is refused. An empty slot + /// stays empty. + pub fn clear_root(&mut self, frame: RootFrameId, slot: u32) -> Result<(), HeapError> { + let found = self.frame(frame)?; + if slot >= found.width { + return Err(HeapError::StaleFrame); + } + let index = found.start as usize + slot as usize; + self.roots[index] = None; + Ok(()) + } + /// Drops the top frame. A frame that is not top is refused. pub fn leave_roots(&mut self, frame: RootFrameId) -> Result<(), HeapError> { let top = self.frames.last().ok_or(HeapError::NoRootFrame)?; diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index c907f8d..ac14b6b 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -94,7 +94,7 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { )); } for (name, params, result) in [ - (ENTER_RESULT, vec![], HostTypeSchema::Unknown), + (ENTER_RESULT, vec!["width"], HostTypeSchema::Unknown), (ENTER_CALLEE, vec!["width"], HostTypeSchema::Float), ( ROOT_ISSUED, @@ -105,11 +105,11 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { (GET_EDGE, vec!["table", "key"], HostTypeSchema::Unknown), ( FINISH_RETURN, - vec!["values", "frame", "publish", "index", "callee"], + vec!["values", "frame", "publish", "slots", "callee"], HostTypeSchema::Unknown, ), (RETIRE_CALLEE, vec!["flag", "frame"], HostTypeSchema::Float), - (RELEASE_RESULT, vec!["frame"], HostTypeSchema::Float), + (RELEASE_RESULT, vec!["frame", "slot"], HostTypeSchema::Float), ] { builder.function(HostFunctionSchema::with_return( name, @@ -463,8 +463,14 @@ fn frame_token(frame: heap::RootFrameId) -> Value { } fn enter_result(call: &mut OwnedHostCall<'_>) -> Result { - let frame = heap::with_heap(&mut call.vm().host_context(), |heap| heap.enter_roots(1)) - .map_err(heap_error)?; + let width = match call.args() { + [value] => float_u32(value)?, + _ => return Err(host_fault("invalid caller frame width")), + }; + let frame = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.enter_roots(width) + }) + .map_err(heap_error)?; let depth = call.vm().call_depth(); with_witness(call.vm(), |witness| { witness.caller_depth = Some(depth); @@ -544,22 +550,27 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { } fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { - let (values, frame_token, publish, table_at, callee_flag) = match call.args() { + let (values, frame_token, publish, slots, callee_flag) = match call.args() { [ Value::Array(values), frame, Value::Float(publish), - index, + slots, Value::Float(flag), ] => ( values.clone(), frame.clone(), *publish != 0.0, - float_u32(index)?, + slots.clone(), *flag != 0.0, ), _ => return Err(host_fault("Lua return transport is not one array")), }; + let root_slots = match &slots { + Value::Array(items) => items.as_slice().to_vec(), + Value::Null => Vec::new(), + _ => return Err(host_fault("caller root slots are not a private array")), + }; let transport = Value::Array(values.clone()); if matches!( classify(&mut call.vm().host_context(), &transport)?, @@ -575,21 +586,9 @@ fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { for value in values.iter() { elements.push(return_element(call, value)?); } - if publish { - let element = values - .get(table_at as usize) - .ok_or_else(|| host_fault("published return is not an issued table"))?; - let table = match classify(&mut call.vm().host_context(), element)? { - heap::GuestClass::Table(table) => table, - _ => return Err(host_fault("published return is not an issued table")), - }; - let frame = decode_frame(call, &frame_token)?; - // Publish the caller root before any later retire removes the callee frame. - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.write_root(frame, 0, table) - }) - .map_err(heap_error)?; - } + // Classify each consumed position. Nil, scalars, and the transport array + // do not become roots. The callee source name is not consulted. + let wrote = publish_consumed_tables(call, &values, &frame_token, publish, &root_slots)?; let lua_frame_alive = if callee_flag { heap::with_heap(&mut call.vm().host_context(), |heap| { Ok(heap.current_frame().is_some()) @@ -615,14 +614,14 @@ fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { .map_err(heap_error)?; with_witness(call.vm(), |witness| { witness.elements = elements.clone(); - witness.published_root = publish; + witness.published_root = wrote; witness.handoff_depth = Some(depth); witness.lua_frame_alive_at_publish = lua_frame_alive; witness.returned_edge_at_handoff = returned_edge; witness.discarded_edge_at_handoff = discarded_edge; witness.handoffs.push(Handoff { elements, - published_root: publish, + published_root: wrote, callee_left: false, top_is_caller_after_handoff: false, lua_frame_alive_at_publish: lua_frame_alive, @@ -635,6 +634,43 @@ fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { Ok(transport) } +fn publish_consumed_tables( + call: &mut OwnedHostCall<'_>, + values: &[Value], + frame_token: &Value, + publish: bool, + root_slots: &[Value], +) -> Result { + if !publish { + return Ok(false); + } + if matches!(frame_token, Value::Null) { + if root_slots.is_empty() { + return Ok(false); + } + return Err(host_fault("missing caller root frame")); + } + let frame = decode_frame(call, frame_token)?; + let mut wrote = false; + for (index, slot_value) in root_slots.iter().enumerate() { + let Some(element) = values.get(index) else { + continue; + }; + let heap::GuestClass::Table(table) = classify(&mut call.vm().host_context(), element)? + else { + continue; + }; + let slot = float_u32(slot_value)?; + // Publish before any later retire removes the callee frame. + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.write_root(frame, slot, table) + }) + .map_err(heap_error)?; + wrote = true; + } + Ok(wrote) +} + fn return_element(call: &mut OwnedHostCall<'_>, value: &Value) -> Result { match value { Value::Null => Ok(ReturnedElement::Nil), @@ -721,8 +757,8 @@ fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { } fn release_result(call: &mut OwnedHostCall<'_>) -> Result { - let frame_token = match call.args() { - [frame] => frame.clone(), + let (frame_token, slot) = match call.args() { + [frame, slot] => (frame.clone(), float_u32(slot)?), _ => return Err(host_fault("invalid result release")), }; let frame = decode_frame(call, &frame_token)?; @@ -735,7 +771,7 @@ fn release_result(call: &mut OwnedHostCall<'_>) -> Result { }) .map_err(heap_error)?; heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.leave_roots(frame) + heap.clear_root(frame, slot) }) .map_err(heap_error)?; let live_roots = heap::stats(&mut call.vm().host_context()) @@ -844,7 +880,10 @@ pub(super) fn lower_returning( stmts: Vec::new(), functions: HashMap::new(), function_impls: HashMap::new(), - result_frames: HashMap::new(), + caller_frame: None, + receiver_roots: HashMap::new(), + next_receiver_slot: 0, + receiver_width: chunk_receiver_width(&chunk.body.stmts), table_locals: HashSet::new(), field_keys: HashMap::new(), publish_results, @@ -853,6 +892,17 @@ pub(super) fn lower_returning( root_slot: 0, ignored_slot: None, }; + if lower.receiver_width > 0 { + let slot = lower.builder.alloc_local_named("#caller-frame")?; + let enter = lower.call(ENTER_RESULT, vec![Expr::Float(lower.receiver_width as f64)])?; + lower.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: enter, + line: 1, + }); + lower.caller_frame = Some(slot); + } if let Some(error) = resolve::resolve(&chunk).errors.first() { return Err(ParseError::at_line(1, format!("{error:?}"))); } @@ -874,7 +924,10 @@ struct Lower<'a> { stmts: Vec, functions: HashMap, FuncInfo>, function_impls: HashMap, - result_frames: HashMap, LocalSlot>, + caller_frame: Option, + receiver_roots: HashMap, u32>, + next_receiver_slot: u32, + receiver_width: u32, table_locals: HashSet>, field_keys: HashMap, u32>, publish_results: bool, @@ -888,7 +941,6 @@ struct Lower<'a> { struct FuncInfo { index: u16, callee_width: u32, - table_at: Option, return_count: u32, } @@ -1003,8 +1055,12 @@ impl Lower<'_> { line: self.line(span), }); self.live_locals.retain(|local| *local != slot); - if let Some(frame) = self.result_frames.remove(&name.bytes) { - let release = self.call(RELEASE_RESULT, vec![Expr::Var(frame)])?; + if let Some(root_slot) = self.receiver_roots.remove(&name.bytes) { + let frame = self.caller_frame.ok_or_else(|| self.unsupported(span))?; + let release = self.call( + RELEASE_RESULT, + vec![Expr::Var(frame), Expr::Float(root_slot as f64)], + )?; self.emit_ignored(release, self.line(span))?; } Ok(()) @@ -1051,7 +1107,10 @@ impl Lower<'_> { let saved_live = std::mem::take(&mut self.live_locals); let saved_temps = std::mem::take(&mut self.active_temps); let saved_stmts = std::mem::take(&mut self.stmts); - let saved_results = std::mem::take(&mut self.result_frames); + let saved_roots = std::mem::take(&mut self.receiver_roots); + let saved_frame = self.caller_frame.take(); + let saved_next = self.next_receiver_slot; + self.next_receiver_slot = 0; let saved_tables = std::mem::take(&mut self.table_locals); let saved_return_names = std::mem::replace( &mut self.return_names, @@ -1092,12 +1151,13 @@ impl Lower<'_> { if table_positions.len() > 1 { return Err(self.unsupported(span)); } - let table_at = table_positions.first().copied(); self.locals = saved_locals; self.live_locals = saved_live; self.active_temps = saved_temps; self.stmts = saved_stmts; - self.result_frames = saved_results; + self.receiver_roots = saved_roots; + self.caller_frame = saved_frame; + self.next_receiver_slot = saved_next; self.table_locals = saved_tables; self.return_names = saved_return_names; self.root_slot = saved_root_slot; @@ -1118,7 +1178,6 @@ impl Lower<'_> { FuncInfo { index, callee_width: width, - table_at, return_count: u32::try_from(returns.len()).expect("return count"), }, ); @@ -1180,6 +1239,9 @@ impl Lower<'_> { names: &[ast::LocalName], call: &ast::Expr, ) -> Result<(), ParseError> { + if self.in_function { + return Err(self.unsupported(span)); + } let callee = self .direct_function_call(call) .ok_or_else(|| self.unsupported(span))?; @@ -1190,47 +1252,49 @@ impl Lower<'_> { .ok_or_else(|| self.unsupported(span))?; let line = self.line(span); let mut slots = Vec::with_capacity(names.len()); + let mut root_slots = Vec::with_capacity(names.len()); for (offset, name) in names.iter().enumerate() { let index = self .builder .alloc_local_named(&format!("#{}:{offset}", span.start))?; self.locals.insert(name.name.bytes.clone(), index); - slots.push((name.name.bytes.clone(), index)); + if self.next_receiver_slot >= self.receiver_width { + return Err(self.unsupported(span)); + } + let root_slot = self.next_receiver_slot; + self.next_receiver_slot += 1; + self.receiver_roots + .insert(name.name.bytes.clone(), root_slot); + slots.push(index); + root_slots.push(Expr::Float(root_slot as f64)); } - let frame_slot = if info.table_at.is_some() { - let slot = self - .builder - .alloc_local_named(&format!("#frame:{}", span.start))?; - let enter = self.call(ENTER_RESULT, vec![])?; - self.stmts.push(Stmt::Let { - index: slot, - declared_schema: None, - expr: enter, - line, - }); - Some(slot) - } else { - None - }; + // The slot list is a previous statement, so its array calls cannot + // sit between Core Ret and the publish that follows it. + let slots_local = self + .builder + .alloc_local_named(&format!("#slots:{}", span.start))?; + self.stmts.push(Stmt::Let { + index: slots_local, + declared_schema: None, + expr: pack_array(root_slots), + line, + }); let transport = self .builder .alloc_local_named(&format!("#ret:{}", span.start))?; let call_expr = Expr::Call(info.index, vec![], vec![], None, None); - let publish = if self.publish_results && info.table_at.is_some() { - 1.0 - } else { - 0.0 - }; - let frame_expr = frame_slot.map(Expr::Var).unwrap_or(Expr::Null); + let publish = if self.publish_results { 1.0 } else { 0.0 }; + let frame_expr = self.caller_frame.map(Expr::Var).unwrap_or(Expr::Null); // The script call is the transport argument. Core Ret runs inside that - // call. finish_return then publishes, while the callee Lua frame is still current. + // call. finish_return then publishes into this chunk's one caller + // frame, while the callee Lua frame is still current. let finish = self.call( FINISH_RETURN, vec![ call_expr, frame_expr.clone(), Expr::Float(publish), - Expr::Float(info.table_at.unwrap_or(0) as f64), + Expr::Var(slots_local), Expr::Float(if info.callee_width > 0 { 1.0 } else { 0.0 }), ], )?; @@ -1241,7 +1305,7 @@ impl Lower<'_> { line, }); let get = vm::BuiltinFunction::Get.call_index(); - for (index, (_, slot)) in slots.iter().enumerate() { + for (index, slot) in slots.iter().enumerate() { let expr = if (index as u32) < info.return_count { Expr::Call( get, @@ -1260,11 +1324,6 @@ impl Lower<'_> { line, }); } - if let (Some(at), Some(frame)) = (info.table_at, frame_slot) - && let Some((name, _)) = slots.get(at as usize) - { - self.result_frames.insert(name.clone(), frame); - } let retire = self.call( RETIRE_CALLEE, vec![ @@ -1273,12 +1332,6 @@ impl Lower<'_> { ], )?; self.emit_ignored(retire, line)?; - if slots.is_empty() - && let Some(frame) = frame_slot - { - let release = self.call(RELEASE_RESULT, vec![Expr::Var(frame)])?; - self.emit_ignored(release, line)?; - } Ok(()) } @@ -1628,6 +1681,37 @@ fn rooted_table_count(stmts: &[ast::Stmt]) -> u32 { .count() as u32 } +fn chunk_receiver_width(stmts: &[ast::Stmt]) -> u32 { + stmts.iter().fold(0u32, |count, stmt| { + let ast::Stmt::Local { names, values, .. } = stmt else { + return count; + }; + let [call] = values.exprs.as_slice() else { + return count; + }; + if !syntactic_direct_call(call) { + return count; + } + count.saturating_add(u32::try_from(names.len()).unwrap_or(u32::MAX)) + }) +} + +fn syntactic_direct_call(expr: &ast::Expr) -> bool { + matches!( + expr, + ast::Expr::SuffixChain { base, steps, .. } + if matches!(base.as_ref(), ast::Expr::Name { .. }) + && matches!( + steps.as_slice(), + [ast::Suffix::Call { + args: ast::Args::List(args), + nav: false, + .. + }] if args.exprs.is_empty() + ) + ) +} + fn pack_array(values: Vec) -> Expr { let new_array = vm::BuiltinFunction::ArrayNew.call_index(); let push = vm::BuiltinFunction::ArrayPush.call_index(); diff --git a/tests/luajit_heap_runtime/return_frame.rs b/tests/luajit_heap_runtime/return_frame.rs index ca8311d..14a61c9 100644 --- a/tests/luajit_heap_runtime/return_frame.rs +++ b/tests/luajit_heap_runtime/return_frame.rs @@ -72,6 +72,183 @@ impl vm::HostOwnedFunction for CallerReadsHost { } } +#[derive(Clone, Copy)] +enum BindingObs { + Record, + Bool, + Text, + Stage, + Snap, +} + +fn register_binding_obs(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + for (name, op) in [ + ("lua_host::record_binding", BindingObs::Record), + ("lua_host::note_bool", BindingObs::Bool), + ("lua_host::note_text", BindingObs::Text), + ("lua_host::note_stage", BindingObs::Stage), + ("lua_host::snapshot_bindings", BindingObs::Snap), + ] { + let function = catalog.function(name).expect(name); + registry + .register_exact_owned( + name, + function.params.len() as u8, + vm::HostImportSchema::from_function(catalog, function), + move |_| Box::new(op), + ) + .expect(name); + } +} + +#[derive(Clone, Debug, Default)] +struct ObsLog { + stage: f64, + bools: Vec<(f64, bool)>, + texts: Vec<(f64, String)>, + bindings: Vec<(f64, heap::TableRef)>, + snaps: Vec, +} + +#[derive(Clone, Debug)] +struct BindingSnap { + tag: f64, + live_nodes: u32, + live_roots: u32, + collections: u32, + alive: Vec<(f64, bool)>, +} + +impl vm::HostOwnedFunction for BindingObs { + fn call(&mut self, call: &mut vm::OwnedHostCall<'_>) -> Result { + let args = call.args().to_vec(); + let mut host = call.vm().host_context(); + let result = match self { + Self::Record => { + let [Value::Float(tag), token] = args.as_slice() else { + return Err(obs_fault("record_binding needs a tag and a table")); + }; + let table = borrowed_table(&mut host, token)?; + let tag = *tag; + host.scope_state_or_insert_with(ObsLog::default) + .map_err(|error| vm::VmError::HostError(error.to_string()))? + .bindings + .push((tag, table)); + Value::Bool(true) + } + Self::Bool => { + let [Value::Float(tag), Value::Bool(value)] = args.as_slice() else { + return Err(obs_fault("note_bool needs a tag and a boolean")); + }; + let noted = (*tag, *value); + host.scope_state_or_insert_with(ObsLog::default) + .map_err(|error| vm::VmError::HostError(error.to_string()))? + .bools + .push(noted); + Value::Bool(true) + } + Self::Text => { + let [Value::Float(tag), Value::String(value)] = args.as_slice() else { + return Err(obs_fault("note_text needs a tag and a string")); + }; + let noted = (*tag, value.to_string()); + host.scope_state_or_insert_with(ObsLog::default) + .map_err(|error| vm::VmError::HostError(error.to_string()))? + .texts + .push(noted); + Value::Bool(true) + } + Self::Stage => { + let [Value::Float(tag)] = args.as_slice() else { + return Err(obs_fault("note_stage needs a tag")); + }; + let tag = *tag; + host.scope_state_or_insert_with(ObsLog::default) + .map_err(|error| vm::VmError::HostError(error.to_string()))? + .stage = tag; + Value::Bool(true) + } + Self::Snap => { + let [Value::Float(tag)] = args.as_slice() else { + return Err(obs_fault("snapshot_bindings needs a tag")); + }; + let tag = *tag; + let recorded = host + .scope_state::() + .map(|log| log.bindings.clone()) + .unwrap_or_default(); + let (alive, live_nodes, live_roots, collections) = + heap::with_heap(&mut host, |heap| { + Ok(( + recorded + .iter() + .map(|(binding, table)| (*binding, heap.alive(*table))) + .collect::>(), + heap.stats().live_nodes, + heap.stats().live_roots, + heap.stats().collections, + )) + }) + .map_err(|error| vm::VmError::HostError(error.to_string()))?; + host.scope_state_or_insert_with(ObsLog::default) + .map_err(|error| vm::VmError::HostError(error.to_string()))? + .snaps + .push(BindingSnap { + tag, + live_nodes, + live_roots, + collections, + alive, + }); + Value::Bool(true) + } + }; + Ok(vm::CallOutcome::Return(vm::CallReturn::one(result))) + } +} + +fn borrowed_table( + host: &mut vm::HostContext<'_>, + value: &Value, +) -> Result { + let Value::Int(raw) = value else { + return Err(obs_fault("expected Lua table")); + }; + let raw = u64::try_from(*raw).map_err(|_| obs_fault("expected Lua table"))?; + let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| obs_fault("expected Lua table"))?; + let key = heap::LuaTableResource::key(); + host.borrow_resource_with_key::(handle, &key) + .map(|resource| resource.table()) + .map_err(|error| vm::VmError::HostError(error.to_string())) +} + +fn obs_fault(message: &str) -> vm::VmError { + vm::VmError::HostError(message.to_string()) +} + +fn obs_log(vm: &mut vm::Vm) -> ObsLog { + vm.host_context() + .scope_state::() + .cloned() + .unwrap_or_default() +} + +fn require_halted(vm: &mut vm::Vm) { + match vm.run() { + Ok(VmStatus::Halted) => {} + Ok(other) => panic!( + "status {other:?} after stage {}; log={:?}", + obs_log(vm).stage, + obs_log(vm) + ), + Err(error) => panic!( + "run failed after stage {}: {error}; log={:?}", + obs_log(vm).stage, + obs_log(vm) + ), + } +} + struct PublishingReturn; struct UnpublishedReturn; @@ -127,6 +304,7 @@ fn run(source: &str, publish_results: bool) -> vm::Vm { candidate::register(&mut registry, &catalog).expect("register candidate runtime"); register_witnesses(&mut registry, &catalog); register_caller_reads(&mut registry, &catalog); + register_binding_obs(&mut registry, &catalog); registry .bind_vm_cached(&mut vm) .expect("bind candidate runtime"); @@ -483,6 +661,396 @@ fn unpublished_consume_source_still_reclaims_on_first_collect() { assert_eq!(first.returned_edge, EdgeView::Stale); } +const ALIAS_RETURN: &str = r#" +local function make() + local returned = {} + local discarded = {} + local alias = returned + alias.self = returned + discarded.self = discarded + return alias +end +local kept = make() +record_binding(1, kept) +note_bool(2, same_table(kept, kept.self)) +note_stage(10) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +note_bool(3, same_table(kept, kept.self)) +record_binding(4, kept) +kept = nil +note_text(5, type(kept)) +collectgarbage("collect") +snapshot_bindings(50) +"#; + +const ALIAS_PAIR: &str = r#" +local function make() + local returned = {} + local discarded = {} + local alias = returned + alias.self = returned + discarded.self = discarded + return alias, nil, alias +end +local first, gap, last = make() +record_binding(1, first) +record_binding(2, last) +note_bool(3, same_table(first, last)) +note_text(4, type(gap)) +note_bool(5, same_table(first, first.self)) +note_stage(10) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +note_bool(6, same_table(first, first.self)) +note_bool(7, same_table(last, last.self)) +first = nil +collectgarbage("collect") +snapshot_bindings(31) +note_stage(31) +note_bool(8, same_table(last, last.self)) +record_binding(9, last) +last = nil +note_text(11, type(last)) +collectgarbage("collect") +snapshot_bindings(50) +"#; + +const MIXED_CLEAR_FIRST: &str = r#" +local function make() + local returned = {} + local discarded = {} + local alias = returned + alias.self = returned + discarded.self = discarded + return returned, nil, alias +end +local first, gap, last = make() +record_binding(1, first) +record_binding(2, last) +note_bool(3, same_table(first, last)) +note_text(4, type(gap)) +note_bool(5, same_table(first, first.self)) +note_stage(10) +first = nil +note_stage(20) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +note_bool(8, same_table(last, last.self)) +record_binding(9, last) +last = nil +note_text(11, type(last)) +collectgarbage("collect") +snapshot_bindings(50) +"#; + +const MIXED_CLEAR_LAST: &str = r#" +local function make() + local returned = {} + local discarded = {} + local alias = returned + alias.self = returned + discarded.self = discarded + return returned, nil, alias +end +local first, gap, last = make() +record_binding(1, first) +record_binding(2, last) +note_bool(3, same_table(first, last)) +note_text(4, type(gap)) +note_bool(5, same_table(last, last.self)) +snapshot_bindings(11) +note_stage(10) +last = nil +note_stage(20) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +note_bool(8, same_table(first, first.self)) +record_binding(9, first) +first = nil +note_text(11, type(first)) +collectgarbage("collect") +snapshot_bindings(50) +"#; + +const SIBLING_CALLS: &str = r#" +local function make() + local returned = {} + local discarded = {} + returned.self = returned + discarded.self = discarded + return returned +end +local a = make() +local b = make() +record_binding(1, a) +record_binding(2, b) +note_bool(3, same_table(a, b)) +note_bool(4, same_table(a, a.self)) +note_bool(5, same_table(b, b.self)) +note_stage(10) +a = nil +note_stage(20) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +note_bool(6, same_table(b, b.self)) +record_binding(7, b) +b = nil +note_text(8, type(b)) +collectgarbage("collect") +snapshot_bindings(50) +"#; + +#[test] +fn alias_return_keeps_the_caller_binding_until_that_local_is_cleared() { + let (mut vm, log) = run_obs(ALIAS_RETURN, true); + let witness = witness(&mut vm); + assert!( + witness.returned.is_none(), + "the alias is not selected from the constructor name" + ); + assert!(witness.handoffs[0].published_root); + assert!(witness.handoffs[0].lua_frame_alive_at_publish); + assert!(witness.callee_left); + assert!(bool_at(&log, 2.0), "setup field read"); + let kept = binding_at(&log, 1.0); + let after = binding_at(&log, 4.0); + assert_eq!( + kept, after, + "the guest binding is the same table after collect" + ); + let first = snap_at(&log, 30.0); + assert!(alive_at(first, 1.0), "caller binding keeps the alias"); + assert_eq!(first.live_nodes, 1, "the unreturned cycle is collected"); + assert_eq!(first.live_roots, 1); + assert_eq!(first.collections, 1); + assert!(bool_at(&log, 3.0), "field read after collect"); + assert_eq!(text_at(&log, 5.0), "nil"); + let cleared = snap_at(&log, 50.0); + assert!(!alive_at(cleared, 1.0)); + assert_eq!(cleared.live_nodes, 0); + assert_eq!(cleared.live_roots, 0); + assert_eq!(cleared.collections, 2); + assert_real_return_window(vm.program()); +} + +#[test] +fn alias_pair_keeps_either_binding_until_the_last_one_is_cleared() { + let (vm, log) = run_obs(ALIAS_PAIR, true); + assert!(bool_at(&log, 3.0), "both positions are the same table"); + assert_eq!(text_at(&log, 4.0), "nil"); + assert!(bool_at(&log, 5.0)); + let first_id = binding_at(&log, 1.0); + let last_id = binding_at(&log, 2.0); + assert_eq!(first_id, last_id); + let both = snap_at(&log, 30.0); + assert!(alive_at(both, 1.0) && alive_at(both, 2.0)); + assert_eq!(both.live_nodes, 1); + assert_eq!( + both.live_roots, 2, + "each consumed position has its own slot" + ); + assert!(bool_at(&log, 6.0) && bool_at(&log, 7.0)); + let one_left = snap_at(&log, 31.0); + assert!(alive_at(one_left, 1.0)); + assert_eq!(one_left.live_roots, 1); + assert_eq!(one_left.live_nodes, 1); + assert!( + bool_at(&log, 8.0), + "the remaining local still reads the field" + ); + assert_eq!(binding_at(&log, 9.0), last_id); + assert_eq!(text_at(&log, 11.0), "nil"); + let gone = snap_at(&log, 50.0); + assert!(!alive_at(gone, 1.0)); + assert_eq!(gone.live_nodes, 0); + assert_eq!(gone.live_roots, 0); + assert_real_return_window(vm.program()); +} + +#[test] +fn mixed_return_keeps_the_alias_when_the_constructor_binding_is_cleared() { + let (vm, log) = run_obs(MIXED_CLEAR_FIRST, true); + assert!(bool_at(&log, 3.0)); + assert_eq!(text_at(&log, 4.0), "nil"); + assert!(bool_at(&log, 5.0)); + let shared = binding_at(&log, 1.0); + assert_eq!(shared, binding_at(&log, 2.0)); + let after_first = snap_at(&log, 30.0); + assert!( + alive_at(after_first, 2.0), + "clearing the first local must not drop the alias" + ); + assert_eq!(after_first.live_roots, 1); + assert_eq!(after_first.live_nodes, 1); + assert!(bool_at(&log, 8.0)); + assert_eq!(binding_at(&log, 9.0), shared); + assert_eq!(text_at(&log, 11.0), "nil"); + let gone = snap_at(&log, 50.0); + assert!(!alive_at(gone, 1.0)); + assert_eq!(gone.live_nodes, 0); + assert_eq!(gone.live_roots, 0); + assert_real_return_window(vm.program()); +} + +#[test] +fn mixed_return_keeps_the_constructor_binding_when_the_alias_is_cleared() { + let (vm, log) = run_obs(MIXED_CLEAR_LAST, true); + assert!(bool_at(&log, 3.0)); + assert_eq!(text_at(&log, 4.0), "nil"); + let shared = binding_at(&log, 1.0); + assert_eq!(shared, binding_at(&log, 2.0)); + let before = snap_at(&log, 11.0); + assert_eq!( + before.live_roots, 2, + "the alias position is rooted before either clear" + ); + assert!(alive_at(before, 1.0) && alive_at(before, 2.0)); + let after_last = snap_at(&log, 30.0); + assert!(alive_at(after_last, 1.0)); + assert_eq!(after_last.live_roots, 1); + assert_eq!(after_last.live_nodes, 1); + assert!(bool_at(&log, 8.0)); + assert_eq!(binding_at(&log, 9.0), shared); + assert_eq!(text_at(&log, 11.0), "nil"); + let gone = snap_at(&log, 50.0); + assert!(!alive_at(gone, 1.0)); + assert_eq!(gone.live_nodes, 0); + assert_eq!(gone.live_roots, 0); + assert_real_return_window(vm.program()); +} + +#[test] +fn earlier_sibling_call_can_be_cleared_without_collecting_the_later_table() { + let (mut vm, log) = run_obs(SIBLING_CALLS, true); + let a = binding_at(&log, 1.0); + let b = binding_at(&log, 2.0); + assert_ne!( + a, b, + "two calls of the same function allocate different tables" + ); + assert!(!bool_at(&log, 3.0)); + assert!(bool_at(&log, 4.0) && bool_at(&log, 5.0)); + let witness = witness(&mut vm); + assert_eq!(witness.handoffs.len(), 2); + assert!(witness.handoffs[0].published_root && witness.handoffs[1].published_root); + assert_eq!( + witness.returned, + Some(b), + "the witness field is only the last call; the guest binding selects a" + ); + let after_a = snap_at(&log, 30.0); + assert!(!alive_at(after_a, 1.0), "clearing a collects only a"); + assert!(alive_at(after_a, 2.0)); + assert_eq!(after_a.live_nodes, 1); + assert_eq!(after_a.live_roots, 1); + assert!(bool_at(&log, 6.0), "b is still readable"); + assert_eq!(binding_at(&log, 7.0), b, "b did not become a"); + assert_ne!(binding_at(&log, 7.0), a); + assert_eq!(text_at(&log, 8.0), "nil"); + let gone = snap_at(&log, 50.0); + assert!(!alive_at(gone, 1.0) && !alive_at(gone, 2.0)); + assert_eq!(gone.live_nodes, 0); + assert_eq!(gone.live_roots, 0); + assert_eq!(gone.collections, 2); + assert_real_return_window(vm.program()); +} + +const UNPUBLISHED_ALIAS: &str = r#" +local function make() + local returned = {} + local discarded = {} + local alias = returned + alias.self = returned + discarded.self = discarded + return alias +end +local kept = make() +record_binding(1, kept) +note_bool(2, same_table(kept, kept.self)) +note_stage(10) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +"#; + +#[test] +fn unpublished_alias_return_is_collected_while_the_caller_binding_remains() { + let (mut vm, log) = run_obs(UNPUBLISHED_ALIAS, false); + let witness = witness(&mut vm); + assert!(!witness.published_root); + assert!(!witness.handoffs[0].published_root); + assert!(witness.handoffs[0].lua_frame_alive_at_publish); + assert!(witness.callee_left); + let kept = binding_at(&log, 1.0); + let after = snap_at(&log, 30.0); + assert!( + !alive_at(after, 1.0), + "skipping publish must not leave another root" + ); + assert!(!heap_alive(&mut vm, kept)); + assert_eq!(after.live_nodes, 0); + assert_eq!(after.live_roots, 0); + assert_eq!(after.collections, 1); + assert_real_return_window(vm.program()); +} + +fn run_obs(source: &str, publish: bool) -> (vm::Vm, ObsLog) { + let mut vm = run(source, publish); + require_halted(&mut vm); + let log = obs_log(&mut vm); + (vm, log) +} + +fn bool_at(log: &ObsLog, tag: f64) -> bool { + log.bools + .iter() + .find(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing bool {tag} in {log:?}")) + .1 +} + +fn text_at(log: &ObsLog, tag: f64) -> String { + log.texts + .iter() + .find(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing text {tag} in {log:?}")) + .1 + .clone() +} + +fn binding_at(log: &ObsLog, tag: f64) -> heap::TableRef { + log.bindings + .iter() + .find(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing binding {tag} in {log:?}")) + .1 +} + +fn snap_at(log: &ObsLog, tag: f64) -> &BindingSnap { + log.snaps + .iter() + .find(|snap| snap.tag == tag) + .unwrap_or_else(|| panic!("missing snap {tag} in {log:?}")) +} + +fn alive_at(snap: &BindingSnap, tag: f64) -> bool { + snap.alive + .iter() + .find(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing alive {tag} in {snap:?}")) + .1 +} + +fn heap_alive(vm: &mut vm::Vm, table: heap::TableRef) -> bool { + heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.alive(table))).expect("heap") +} + fn assert_value_oracle() { let Ok(oracle) = std::env::var("LUAJIT_ORACLE") else { return; diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 72f5b90..7140a55 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -164,6 +164,38 @@ pub(super) fn catalog() -> &'static Arc { ], HostTypeSchema::String, )); + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(HostFunctionSchema::with_return( + "lua_host::record_binding", + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::with_passing("table", table, HostParamPassing::Borrow), + ], + HostTypeSchema::Bool, + )); + builder.function(HostFunctionSchema::with_return( + "lua_host::note_bool", + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("value", HostTypeSchema::Bool), + ], + HostTypeSchema::Bool, + )); + builder.function(HostFunctionSchema::with_return( + "lua_host::note_text", + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("value", HostTypeSchema::String), + ], + HostTypeSchema::Bool, + )); + for name in ["lua_host::note_stage", "lua_host::snapshot_bindings"] { + builder.function(HostFunctionSchema::with_return( + name, + vec![HostParamSchema::value("tag", HostTypeSchema::Float)], + HostTypeSchema::Bool, + )); + } for (name, reverse) in [ ("lua_host::observe_table", false), ("lua_host::observe_table_after", true), From 6f510fbf8e3d914accbd928929134ff8ad1a195d Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 00:23:01 +0800 Subject: [PATCH 032/225] fix(test): claim an exclusive root for each staged example staged_example_path reused one directory per file name, so concurrent JavaScript tests rewrote the same example and frozen strings.rss. Each call now claims a directory with the process id, an in-process ticket, and atomic mkdir, and keeps the compat/examples layout. --- tests/common/mod.rs | 27 ++++++- tests/compiler/compiler_javascript_tests.rs | 82 +++++++++++++++++++++ 2 files changed, 105 insertions(+), 4 deletions(-) diff --git a/tests/common/mod.rs b/tests/common/mod.rs index e4908bc..233552c 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -2,6 +2,7 @@ use std::fs; use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; pub use vm::{ Assembler, BytecodeBuilder, CallOutcome, CompileSourceFileOptions, Compiler, Expr, @@ -173,12 +174,30 @@ fn unwrap_source_error(err: vm::SourcePathError, case: &str) -> vm::SourceError const FROZEN_STRINGS_RSS: &str = include_str!("../fixtures/frozen_stdlib/strings.rss"); -pub fn staged_example_path(file_name: &str) -> PathBuf { - let root = std::env::var_os("CARGO_TARGET_DIR") +fn claim_staged_example_root() -> PathBuf { + let parent = std::env::var_os("CARGO_TARGET_DIR") .map(PathBuf::from) .unwrap_or_else(std::env::temp_dir) - .join("compat-frontends-staged-examples") - .join(file_name); + .join("compat-frontends-staged-examples"); + fs::create_dir_all(&parent).expect("staged examples parent"); + // pid separates processes and the counter separates threads. create_dir is + // the claim: an existing name is skipped, not reused. Do not scan a shared + // index from zero, and do not use time as the only name. + static NEXT: AtomicU64 = AtomicU64::new(0); + let pid = std::process::id(); + loop { + let ticket = NEXT.fetch_add(1, Ordering::Relaxed); + let root = parent.join(format!("{pid}-{ticket}")); + match fs::create_dir(&root) { + Ok(()) => return root, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("claim staged example root: {error}"), + } + } +} + +pub fn staged_example_path(file_name: &str) -> PathBuf { + let root = claim_staged_example_root(); let examples_dir = root.join("compat").join("examples"); let stdlib = root .join("rustscript") diff --git a/tests/compiler/compiler_javascript_tests.rs b/tests/compiler/compiler_javascript_tests.rs index b3e0cf3..68dc27f 100644 --- a/tests/compiler/compiler_javascript_tests.rs +++ b/tests/compiler/compiler_javascript_tests.rs @@ -616,6 +616,88 @@ fn compile_source_file_js_complex_replay_break_line_resolves_non_executable_line ); } +#[test] +fn staged_same_example_second_copy_does_not_overwrite_first_root() { + fn frozen_beside(example: &std::path::Path) -> std::path::PathBuf { + let examples = example.parent().expect("staged example parent"); + assert_eq!( + examples.file_name().and_then(|name| name.to_str()), + Some("examples"), + "staged example must stay under compat/examples" + ); + let compat = examples.parent().expect("compat parent"); + assert_eq!( + compat.file_name().and_then(|name| name.to_str()), + Some("compat"), + "staged example must stay under compat/examples" + ); + let root = compat.parent().expect("staging root"); + root.join("rustscript") + .join("stdlib") + .join("rss") + .join("strings.rss") + } + + let file_name = "example_complex.js"; + let manifest = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let fixture = manifest.join("examples").join(file_name); + let fixture_bytes = fs::read(&fixture).expect("read example fixture"); + let frozen_fixture = fs::read(manifest.join("tests/fixtures/frozen_stdlib/strings.rss")) + .expect("read frozen strings fixture"); + + let first = staged_example_path(file_name); + let first_frozen = frozen_beside(&first); + assert_ne!( + first, fixture, + "observation must stay on the staged path, not the repository fixture" + ); + assert_eq!( + fs::read(&first).expect("read first staged example"), + fixture_bytes, + "first staging must copy the complete example before observation" + ); + assert_eq!( + fs::read(&first_frozen).expect("read first frozen stdlib"), + frozen_fixture, + "first staging must write the complete frozen stdlib" + ); + + let marker = b"staged-example-isolation-marker\n"; + assert_ne!(marker.as_slice(), fixture_bytes.as_slice()); + fs::write(&first, marker).expect("mark only the confirmed staged example"); + + let second = staged_example_path(file_name); + let second_frozen = frozen_beside(&second); + assert_eq!( + fs::read(&first).expect("read marked example after second staging"), + marker, + "second staging overwrote the first staged example" + ); + assert_ne!( + first_frozen, second_frozen, + "second staging reused the first frozen strings.rss" + ); + assert_eq!( + fs::read(&first_frozen).expect("read first frozen stdlib after second staging"), + frozen_fixture, + "second staging overwrote or truncated the first frozen stdlib" + ); + assert_eq!( + fs::read(&second).expect("read second staged example"), + fixture_bytes, + "second staging must equal the complete example fixture" + ); + assert_eq!( + fs::read(&second_frozen).expect("read second frozen stdlib"), + frozen_fixture, + "second staging must equal the complete frozen fixture" + ); + assert_eq!( + fs::read(&fixture).expect("repository fixture must stay unchanged"), + fixture_bytes + ); +} + #[test] fn javascript_module_declarations_are_ignored() { let case = RuntimeCase { From 086619d730e75397268df14cea4288a94ff273e7 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 00:40:50 +0800 Subject: [PATCH 033/225] fix(test): isolate each frozen diagnostic probe Two diagnostics staged probe.py in one shared scratch directory, so the second same-name write replaced the first marker. Claim a child of diagnostics through exclusive_subroot for every staging. --- tests/frozen_core_consumer.rs | 58 ++++++++++++++++++++++++++++++++--- 1 file changed, 54 insertions(+), 4 deletions(-) diff --git a/tests/frozen_core_consumer.rs b/tests/frozen_core_consumer.rs index 075028b..222ff15 100644 --- a/tests/frozen_core_consumer.rs +++ b/tests/frozen_core_consumer.rs @@ -44,6 +44,10 @@ fn exclusive_subroot(owner: &str) -> PathBuf { } } +fn diagnostic_scratch() -> PathBuf { + exclusive_subroot("diagnostics") +} + fn rustscript_lock_source() -> String { format!("git+{RUSTSCRIPT_GIT}?rev={FROZEN_RUSTSCRIPT_REV}#{FROZEN_RUSTSCRIPT_REV}") } @@ -378,10 +382,57 @@ fn lua_map_array_and_callable_semantics_survive_the_frozen_core() { assert_eq!(vm.stack(), &[Value::Int(10)]); } +#[test] +fn second_diagnostic_probe_does_not_overwrite_the_first() { + let first_marker = "print(1)\n"; + let second_marker = "print(2)\n"; + assert_ne!(first_marker, second_marker); + + let first = diagnostic_scratch(); + let first_probe = first.join("probe.py"); + fs::write(&first_probe, first_marker).expect("write first diagnostic probe"); + assert_eq!( + fs::read_to_string(&first_probe).expect("read first diagnostic probe"), + first_marker, + "first staging must write the complete probe before the second write" + ); + + let second = diagnostic_scratch(); + let second_probe = second.join("probe.py"); + fs::write(&second_probe, second_marker).expect("write second diagnostic probe"); + + assert_eq!( + fs::read_to_string(&first_probe).expect("read first diagnostic probe after second write"), + first_marker, + "second same-name write overwrote {}; second path is {}", + first_probe.display(), + second_probe.display() + ); + assert_ne!( + first_probe, second_probe, + "second diagnostic staging reused the first probe path" + ); + assert_eq!( + fs::read_to_string(&second_probe).expect("read second diagnostic probe"), + second_marker, + "second diagnostic probe must keep its own marker" + ); + let diagnostics_parent = scratch_root().join("diagnostics"); + assert!( + first.starts_with(&diagnostics_parent), + "first diagnostic root must stay under scratch_root()/diagnostics: {}", + first.display() + ); + assert!( + second.starts_with(&diagnostics_parent), + "second diagnostic root must stay under scratch_root()/diagnostics: {}", + second.display() + ); +} + #[test] fn corpus_staging_preserves_diagnostic_probe_files() { - let diagnostics = scratch_root().join("diagnostics"); - fs::create_dir_all(&diagnostics).expect("diagnostics directory"); + let diagnostics = diagnostic_scratch(); let kept = diagnostics.join("kept.txt"); fs::write(&kept, "diagnostic-owner\n").expect("write diagnostic marker"); @@ -414,8 +465,7 @@ fn corpus_staging_preserves_diagnostic_probe_files() { #[test] fn unsupported_language_and_invalid_sources_produce_portable_diagnostics() { - let tmp = scratch_root().join("diagnostics"); - fs::create_dir_all(&tmp).expect("diagnostics directory"); + let tmp = diagnostic_scratch(); let python = tmp.join("probe.py"); fs::write(&python, "print(1)\n").expect("write unsupported source"); let error = expect_err( From cfb9bfca3d3f641313c4465ee7cf3dec017871ec Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 23:53:34 +0800 Subject: [PATCH 034/225] fix(lua): release a return root only for the binding just cleared A same-name shadow replaces the local mapping but not the published result slot. Nil now releases the root recorded for the slot just resolved, so the earlier table stays until this frame retires. --- tests/luajit_heap_runtime/candidate.rs | 9 +- tests/luajit_heap_runtime/return_frame.rs | 266 ++++++++++++++++++++++ 2 files changed, 271 insertions(+), 4 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index ac14b6b..3d23276 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -925,7 +925,7 @@ struct Lower<'a> { functions: HashMap, FuncInfo>, function_impls: HashMap, caller_frame: Option, - receiver_roots: HashMap, u32>, + receiver_roots: HashMap, next_receiver_slot: u32, receiver_width: u32, table_locals: HashSet>, @@ -1055,7 +1055,8 @@ impl Lower<'_> { line: self.line(span), }); self.live_locals.retain(|local| *local != slot); - if let Some(root_slot) = self.receiver_roots.remove(&name.bytes) { + // The name may now denote a shadow. Release the root of this slot only. + if let Some(root_slot) = self.receiver_roots.remove(&slot) { let frame = self.caller_frame.ok_or_else(|| self.unsupported(span))?; let release = self.call( RELEASE_RESULT, @@ -1263,8 +1264,8 @@ impl Lower<'_> { } let root_slot = self.next_receiver_slot; self.next_receiver_slot += 1; - self.receiver_roots - .insert(name.name.bytes.clone(), root_slot); + // Keep the published slot with this binding, not with the spelling. + self.receiver_roots.insert(index, root_slot); slots.push(index); root_slots.push(Expr::Float(root_slot as f64)); } diff --git a/tests/luajit_heap_runtime/return_frame.rs b/tests/luajit_heap_runtime/return_frame.rs index 14a61c9..6578ec0 100644 --- a/tests/luajit_heap_runtime/return_frame.rs +++ b/tests/luajit_heap_runtime/return_frame.rs @@ -979,6 +979,272 @@ snapshot_bindings(30) note_stage(30) "#; +const SCALAR_SHADOW: &str = r#" +local function make() + local returned = {} + returned.self = returned + return returned +end +local a = make() +record_binding(1, a) +note_bool(2, same_table(a, a.self)) +local a = 0 +note_text(3, type(a)) +a = nil +note_text(4, type(a)) +note_stage(20) +snapshot_bindings(20) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +"#; + +const CLEAR_BEFORE_SHADOW: &str = r#" +local function make() + local returned = {} + returned.self = returned + return returned +end +local a = make() +record_binding(1, a) +note_bool(2, same_table(a, a.self)) +snapshot_bindings(11) +a = nil +note_text(3, type(a)) +local a = 0 +note_text(4, type(a)) +note_stage(20) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +"#; + +const TABLE_SHADOW: &str = r#" +local function make() + local returned = {} + returned.self = returned + return returned +end +local a = make() +record_binding(1, a) +note_bool(2, same_table(a, a.self)) +local a = {} +record_binding(3, a) +note_text(4, type(a)) +a = nil +note_text(5, type(a)) +note_stage(20) +snapshot_bindings(20) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +"#; + +const TABLE_RESULT_SHADOW: &str = r#" +local function make() + local returned = {} + returned.self = returned + return returned +end +local function other() + local returned = {} + returned.self = returned + return returned +end +local a = make() +record_binding(1, a) +note_bool(2, same_table(a, a.self)) +local a = other() +record_binding(3, a) +note_bool(6, same_table(a, a.self)) +note_text(4, type(a)) +snapshot_bindings(15) +a = nil +note_text(5, type(a)) +note_stage(20) +snapshot_bindings(20) +collectgarbage("collect") +snapshot_bindings(30) +note_stage(30) +"#; + +#[test] +fn scalar_shadow_nil_keeps_the_earlier_table() { + let (mut vm, log) = run_obs(SCALAR_SHADOW, true); + let witness = witness(&mut vm); + let old = binding_at(&log, 1.0); + assert_eq!( + witness.returned, + Some(old), + "the recorded binding is the issued table" + ); + assert!(bool_at(&log, 2.0), "the earlier table was readable"); + assert_eq!(text_at(&log, 3.0), "number", "the new binding is a scalar"); + assert_eq!( + text_at(&log, 4.0), + "nil", + "nil assignment wrote nil into the new scalar" + ); + let before = snap_at(&log, 20.0); + assert!( + alive_at(before, 1.0), + "the earlier table must still be allocated before collect: {before:?}" + ); + let after = snap_at(&log, 30.0); + let collect = witness.collects.first(); + assert!( + alive_at(after, 1.0) + && after.live_roots == 1 + && collect.is_some_and(|note| { + note.returned_alive + && note.live_roots == 1 + && note.swept == 0 + && note.live_nodes == 1 + }), + "shadow nil reclaimed the earlier table; id={old:?} before_roots={} after={after:?} collect={:?} release={:?}", + before.live_roots, + witness.collects, + witness.release + ); + assert_eq!( + before.live_roots, 1, + "the published slot stays until this frame retires" + ); + assert!( + witness.release.is_none(), + "clearing the new scalar must not release the earlier root" + ); + assert_eq!(after.collections, 1); + assert_real_return_window(vm.program()); +} + +#[test] +fn explicit_clear_before_shadow_reclaims_the_earlier_table() { + let (mut vm, log) = run_obs(CLEAR_BEFORE_SHADOW, true); + let witness = witness(&mut vm); + let old = binding_at(&log, 1.0); + assert_eq!(witness.returned, Some(old)); + assert!(bool_at(&log, 2.0)); + let rooted = snap_at(&log, 11.0); + assert!(alive_at(rooted, 1.0)); + assert_eq!(rooted.live_roots, 1); + assert_eq!( + text_at(&log, 3.0), + "nil", + "the original binding was cleared" + ); + assert_eq!(text_at(&log, 4.0), "number"); + let after = snap_at(&log, 30.0); + assert!( + !alive_at(after, 1.0), + "explicit clear must reclaim on collect" + ); + assert_eq!(after.live_roots, 0); + assert_eq!(after.collections, 1); + let collect = &witness.collects[0]; + assert!(!collect.returned_alive); + assert_eq!(collect.live_roots, 0); + assert_eq!(collect.swept, 1); + assert_eq!(collect.live_nodes, 0); + assert!( + witness.release.is_some(), + "the original slot still releases" + ); + assert_real_return_window(vm.program()); +} + +#[test] +fn table_shadow_nil_keeps_the_earlier_table() { + let (mut vm, log) = run_obs(TABLE_SHADOW, true); + let witness = witness(&mut vm); + let old = binding_at(&log, 1.0); + let fresh = binding_at(&log, 3.0); + assert_ne!(old, fresh, "the shadow table is a different object"); + assert_eq!(witness.returned, Some(old)); + assert!(bool_at(&log, 2.0)); + assert_eq!(text_at(&log, 4.0), "table", "the new binding is a table"); + assert_eq!( + text_at(&log, 5.0), + "nil", + "nil assignment wrote nil into the new table" + ); + let before = snap_at(&log, 20.0); + assert!( + alive_at(before, 1.0), + "the earlier table must still be allocated before collect: {before:?}" + ); + let after = snap_at(&log, 30.0); + let collect = witness.collects.first(); + assert!( + alive_at(after, 1.0) + && after.live_roots == 1 + && collect.is_some_and(|note| { + note.returned_alive && note.live_roots == 1 && note.live_nodes == 1 + }), + "table shadow nil reclaimed the earlier table; old={old:?} fresh={fresh:?} before_roots={} after={after:?} collect={:?} release={:?}", + before.live_roots, + witness.collects, + witness.release + ); + assert!( + !alive_at(after, 3.0), + "the shadowed constructor must not gain an extra root" + ); + assert_eq!( + before.live_roots, 1, + "shadow does not add a root for the earlier binding" + ); + assert!(witness.release.is_none()); + assert_eq!(after.collections, 1); + assert_eq!(collect.expect("collect").swept, 1); + assert_real_return_window(vm.program()); +} + +#[test] +fn table_result_shadow_keeps_the_earlier_table_and_drops_the_new_one() { + let (mut vm, log) = run_obs(TABLE_RESULT_SHADOW, true); + let witness = witness(&mut vm); + let old = binding_at(&log, 1.0); + let fresh = binding_at(&log, 3.0); + assert_ne!(old, fresh); + assert!(bool_at(&log, 2.0) && bool_at(&log, 6.0)); + assert_eq!(text_at(&log, 4.0), "table"); + assert_eq!(text_at(&log, 5.0), "nil"); + assert_eq!(witness.handoffs.len(), 2); + assert!(witness.handoffs[0].published_root && witness.handoffs[1].published_root); + let both = snap_at(&log, 15.0); + assert!(alive_at(both, 1.0) && alive_at(both, 3.0)); + assert_eq!(both.live_roots, 2, "each call result keeps its own slot"); + let before = snap_at(&log, 20.0); + assert!( + alive_at(before, 1.0), + "nil must not drop the earlier table before collect: {before:?}" + ); + let after = snap_at(&log, 30.0); + assert!( + alive_at(after, 1.0), + "nil on the new result must not reclaim the earlier table; after={after:?} collect={:?}", + witness.collects + ); + assert!( + !alive_at(after, 3.0), + "the new result root is the one released" + ); + assert_eq!(after.live_roots, 1); + assert_eq!(after.collections, 1); + assert_eq!(binding_at(&log, 1.0), old); + assert_eq!(binding_at(&log, 3.0), fresh); + let collect = &witness.collects[0]; + assert!( + !collect.returned_alive, + "the witness field is the later call" + ); + assert_eq!(collect.swept, 1); + assert_eq!(collect.live_roots, 1); + assert_eq!(collect.live_nodes, 1); + assert_real_return_window(vm.program()); +} + #[test] fn unpublished_alias_return_is_collected_while_the_caller_binding_remains() { let (mut vm, log) = run_obs(UNPUBLISHED_ALIAS, false); From 1bc0af71082d557cc898ec3a3a1f646e6a946880 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 00:30:21 +0800 Subject: [PATCH 035/225] fix(lua): retire the chunk caller frame on normal completion The private test lowerer opened a caller root frame and left it after fallthrough and a scalar or nil return. Leave that frame after the return expression has run, using the existing frame token and leave_roots. A chunk with no receiver slots still opens no frame. --- tests/luajit_heap_runtime/candidate.rs | 26 +++ tests/luajit_heap_runtime/return_frame.rs | 208 ++++++++++++++++++++++ 2 files changed, 234 insertions(+) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 3d23276..a334da3 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -30,6 +30,7 @@ const SET_EDGE: &str = "lua_internal::set_edge"; const GET_EDGE: &str = "lua_internal::get_edge"; pub(super) const FINISH_RETURN: &str = "lua_internal::finish_return"; pub(super) const RETIRE_CALLEE: &str = "lua_internal::retire_callee"; +const RETIRE_CHUNK: &str = "lua_internal::retire_chunk"; const RELEASE_RESULT: &str = "lua_internal::release_result"; // Test-only witnesses. They place an ordinary VM array on the source path. // They are not Lua syntax and are not registered on the production entry. @@ -109,6 +110,7 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { HostTypeSchema::Unknown, ), (RETIRE_CALLEE, vec!["flag", "frame"], HostTypeSchema::Float), + (RETIRE_CHUNK, vec!["frame"], HostTypeSchema::Float), (RELEASE_RESULT, vec!["frame", "slot"], HostTypeSchema::Float), ] { builder.function(HostFunctionSchema::with_return( @@ -144,6 +146,7 @@ pub(super) fn register( Op::GetEdge, Op::FinishReturn, Op::RetireCallee, + Op::RetireChunk, Op::ReleaseResult, Op::CopyFields, Op::ExternalShape, @@ -166,6 +169,7 @@ pub(super) fn register( Op::GetEdge => GET_EDGE, Op::FinishReturn => FINISH_RETURN, Op::RetireCallee => RETIRE_CALLEE, + Op::RetireChunk => RETIRE_CHUNK, Op::ReleaseResult => RELEASE_RESULT, Op::CopyFields => COPY_FIELDS, Op::ExternalShape => EXTERNAL_SHAPE, @@ -198,6 +202,7 @@ enum Op { GetEdge, FinishReturn, RetireCallee, + RetireChunk, ReleaseResult, CopyFields, ExternalShape, @@ -372,6 +377,7 @@ impl HostOwnedFunction for Op { Self::GetEdge => get_edge(call)?, Self::FinishReturn => finish_return(call)?, Self::RetireCallee => retire_callee(call)?, + Self::RetireChunk => retire_chunk(call)?, Self::ReleaseResult => release_result(call)?, Self::CopyFields => match call.args() { [Value::Array(fields)] => Value::array(fields.iter().cloned().collect()), @@ -736,6 +742,19 @@ fn retire_callee(call: &mut OwnedHostCall<'_>) -> Result { Ok(Value::Float(0.0)) } +fn retire_chunk(call: &mut OwnedHostCall<'_>) -> Result { + let frame_token = match call.args() { + [frame] => frame.clone(), + _ => return Err(host_fault("invalid chunk retire")), + }; + let frame = decode_frame(call, &frame_token)?; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(frame) + }) + .map_err(heap_error)?; + Ok(Value::Float(0.0)) +} + fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { let (from, key) = match call.args() { [from, key] => (from.clone(), float_u32(key)?), @@ -909,6 +928,13 @@ pub(super) fn lower_returning( for stmt in &chunk.body.stmts { lower.lower_stmt(stmt)?; } + // Statements, including an explicit scalar return, have already run. + // A chunk with no receiver slots never opened this frame, so it does not + // leave one. Fallthrough has no result expression here. + if let Some(frame) = lower.caller_frame { + let retire = lower.call(RETIRE_CHUNK, vec![Expr::Var(frame)])?; + lower.emit_ignored(retire, 1)?; + } let mut ir = lower.builder.finish(lower.stmts); ir.function_impls = lower.function_impls; Ok(ir) diff --git a/tests/luajit_heap_runtime/return_frame.rs b/tests/luajit_heap_runtime/return_frame.rs index 6578ec0..5d831c4 100644 --- a/tests/luajit_heap_runtime/return_frame.rs +++ b/tests/luajit_heap_runtime/return_frame.rs @@ -1497,3 +1497,211 @@ fn assert_no_calls_between(program: &Program, call_script: usize, finish: usize) fn call_index(program: &Program, ip: usize) -> u16 { u16::from_le_bytes(program.code[ip + 1..ip + 3].try_into().expect("call index")) } + +/// Chunk completion must drop only this chunk's caller frame. +/// +/// The outer table is rooted on the native heap before the chunk starts. It +/// is not a Lua local of this chunk. LuaJIT's 260-activation run is a separate +/// upstream observation and is not this compat result. +struct ChunkExit { + vm: vm::Vm, + outer_frame: heap::RootFrameId, + outer_table: heap::TableRef, + chunk_table: heap::TableRef, + baseline: heap::HeapStats, + baseline_resources: usize, +} + +fn run_chunk_over_outer_root(source: &str) -> ChunkExit { + let mut vm = run(source, true); + let outer_frame = heap::with_heap(&mut vm.host_context(), |heap| heap.enter_roots(1)) + .expect("native heap accepts an outer frame before the chunk"); + let carrier = heap::publish_guest(&mut vm.host_context()).expect("outer table"); + let outer_table = heap::with_heap(&mut vm.host_context(), |heap| { + let heap::GuestClass::Table(table) = heap.guest_class(&carrier) else { + return Err(heap::HeapError::WrongKind); + }; + heap.write_root(outer_frame, 0, table)?; + Ok(table) + }) + .expect("write the outer root"); + let baseline = heap::stats(&mut vm.host_context()).expect("entry baseline"); + let baseline_resources = vm.host_context().resource_count(); + assert_eq!( + baseline.root_slots, 1, + "setup: outer frame occupies one root slot" + ); + assert_eq!( + baseline.live_roots, 1, + "setup: outer table is the only live root" + ); + assert_eq!( + baseline.live_nodes, 1, + "setup: outer table occupies one node" + ); + assert_eq!( + baseline_resources, 1, + "setup: outer table holds one resource" + ); + assert_eq!(vm.run().expect("run chunk"), VmStatus::Halted); + let chunk_table = witness(&mut vm) + .returned + .expect("the chunk received a returned table"); + assert_ne!( + chunk_table, outer_table, + "setup: the chunk table is not the outer table" + ); + ChunkExit { + vm, + outer_frame, + outer_table, + chunk_table, + baseline, + baseline_resources, + } +} + +fn assert_only_chunk_frame_retired(exit: &mut ChunkExit) { + let before = heap::stats(&mut exit.vm.host_context()).expect("stats before extra collect"); + assert_eq!( + before.root_slots, exit.baseline.root_slots, + "chunk frame must return root storage to the entry baseline" + ); + assert_eq!( + before.live_roots, exit.baseline.live_roots, + "the chunk's live root must be gone before the extra collect" + ); + assert!( + heap_alive(&mut exit.vm, exit.chunk_table), + "the unrooted self-cycle still occupies a node before the extra collect" + ); + assert_eq!( + before.live_nodes, + exit.baseline.live_nodes + 1, + "the self-cycle node stays until an explicit collect" + ); + assert!( + heap_alive(&mut exit.vm, exit.outer_table), + "the outer root must survive chunk completion" + ); + let current = heap::with_heap(&mut exit.vm.host_context(), |heap| Ok(heap.current_frame())) + .expect("current frame"); + assert_eq!( + current, + Some(exit.outer_frame), + "completion leaves only this chunk frame" + ); + assert_eq!( + exit.vm.host_context().resource_count(), + exit.baseline_resources + 1, + "the self-cycle token stays until collect" + ); + // Same VM, no reset and no host clear of the remaining root. + let report = heap::collect(&mut exit.vm.host_context()).expect("same-scope collect"); + assert!( + !heap_alive(&mut exit.vm, exit.chunk_table), + "collect reclaims the self-cycle after the frame is gone" + ); + assert!( + heap_alive(&mut exit.vm, exit.outer_table), + "collect must not reclaim the outer root" + ); + assert_eq!(report.live_nodes, exit.baseline.live_nodes); + assert_eq!(report.live_roots, exit.baseline.live_roots); + assert_eq!( + exit.vm.host_context().resource_count(), + exit.baseline_resources, + "collect returns the self-cycle resource" + ); + let after = heap::stats(&mut exit.vm.host_context()).expect("stats after collect"); + assert_eq!(after.root_slots, exit.baseline.root_slots); + let current = heap::with_heap(&mut exit.vm.host_context(), |heap| Ok(heap.current_frame())) + .expect("frame after collect"); + assert_eq!(current, Some(exit.outer_frame)); +} + +#[test] +fn fallthrough_returns_root_slots_and_leaves_the_self_cycle_until_collect() { + let source = r#" +local function make() + local obj = {} + obj.self = obj + return obj +end +local kept = make() +"#; + let mut exit = run_chunk_over_outer_root(source); + assert_eq!( + exit.vm.stack(), + &[] as &[Value], + "fallthrough adds no result" + ); + assert_only_chunk_frame_retired(&mut exit); +} + +#[test] +fn nil_return_keeps_the_scalar_stack_and_returns_root_slots() { + let source = r#" +local function make() + local obj = {} + obj.self = obj + return obj +end +local function one() + return nil +end +local kept = make() +local n = one() +return n +"#; + let mut exit = run_chunk_over_outer_root(source); + assert_eq!(exit.vm.stack(), &[Value::Null]); + assert_only_chunk_frame_retired(&mut exit); +} + +#[test] +fn type_return_reads_the_rooted_table_before_the_frame_leaves() { + let source = r#" +local function make() + local obj = {} + obj.self = obj + return obj +end +local kept = make() +return type(kept) +"#; + let mut exit = run_chunk_over_outer_root(source); + assert_eq!(exit.vm.stack(), &[Value::string("table")]); + assert_only_chunk_frame_retired(&mut exit); +} + +#[test] +fn collect_return_sees_the_frame_root_then_the_frame_leaves() { + let source = r#" +local function make() + local obj = {} + obj.self = obj + return obj +end +local kept = make() +return collectgarbage("collect") +"#; + let mut exit = run_chunk_over_outer_root(source); + assert_eq!(exit.vm.stack(), &[Value::Float(0.0)]); + let witness = witness(&mut exit.vm); + let during = witness + .collects + .first() + .expect("the return expression collected while the chunk frame was still current"); + assert!( + during.returned_alive, + "collect inside the return must still see the chunk root: {during:?}" + ); + assert_eq!( + during.live_roots, + exit.baseline.live_roots + 1, + "the last collection runs before the chunk frame leaves" + ); + assert_eq!(during.live_nodes, exit.baseline.live_nodes + 1); + assert_only_chunk_frame_retired(&mut exit); +} From 4a16e777253a7a28658cf8e73ad9754fc47ad674 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sat, 21 Nov 2026 23:26:13 +0800 Subject: [PATCH 036/225] feat(lua): lower chunk numeric for on the fixed core Save start, limit, and step once, then drive one Core for with a private binary64 counter. The test predicate uses the step sign bit and an ordered closed interval, so +0, -0, and NaN stay distinct. --- src/frontends/lua/control.rs | 239 ++++- tests/compiler/compiler_lua_control_tests.rs | 908 ++++++++++++++++++- 2 files changed, 1136 insertions(+), 11 deletions(-) diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs index cb4dcdf..b2248bf 100644 --- a/src/frontends/lua/control.rs +++ b/src/frontends/lua/control.rs @@ -21,28 +21,51 @@ //! `core_truthy` before a Core branch or `Not`. `until` does the same, once, //! in the `for` post. The operand expression is placed once. The state id is //! a private Core int and is not a Lua number. - +//! +//! A numeric `for` is also one Core `for`, in the same dispatch arm as the +//! surrounding chunk. Its three header expressions are assigned once, left to +//! right, into private float slots. The default step is `+1`. Those slots are +//! declared at the chunk root so a nested loop can assign them again without +//! a second `let`. The visible index is a different slot, copied from the +//! hidden counter at the start of each iteration, so a write to the Lua local +//! does not move the counter and a same-name header reference still sees the +//! outer binding. Core has no sign-bit opcode, so the condition is one call of +//! `lua_control::numeric_for_holds`. The test catalog owns that predicate: +//! direction is the step's sign bit, and the closed interval uses ordered +//! comparisons. `continue` reaches the post, which adds the saved step to the +//! hidden counter. `break` skips that post and leaves this `for`. +//! use super::ast::{self, BinOp, Block, Chunk, Expr, Name, NumberKind, Span, Stmt, UnOp}; use super::lexer; use super::parser; use super::resolve::{self, Resolution, ResolveError}; +use vm::compiler::HostCallResolver; use vm::{ AssignmentKind, Expr as CoreExpr, FrontendIr, LocalIrBuilder, LocalSlot, ParseError, - Stmt as CoreStmt, + Stmt as CoreStmt, TypeSchema, }; const STATE_SLOT: &str = "$lua_dispatch_state"; const RESULT_SLOT: &str = "$lua_return_value"; const EXIT_STATE: i64 = 0; +pub(super) const NUMERIC_FOR_HOLDS: &str = "lua_control::numeric_for_holds"; + pub(super) fn lower_source(source: &str) -> Result { + lower_source_with(source, None) +} + +pub(super) fn lower_source_with( + source: &str, + holds: Option<&HostCallResolver<'_>>, +) -> Result { let chunk = parser::parse_chunk(source.as_bytes()).map_err(syntax_error)?; let resolution = resolve::resolve(&chunk); if let Some(error) = resolution.errors.first() { let line = line_of(source, error_span(error)); return Err(ParseError::at_line(line, static_message(error))); } - let mut lower = Lower::new(source, &resolution); + let mut lower = Lower::new(source, &resolution, holds); let stmts = if needs_dispatch(&chunk) { lower.lower_dispatch(&chunk)? } else { @@ -61,6 +84,10 @@ struct Lower<'a> { result: Option, label_state: Vec>, repeat_flags: u32, + nfor_ordinal: u32, + nfor_slots: Vec, + for_indexes: Vec, + holds: Option<&'a HostCallResolver<'a>>, } struct BlockBuf { @@ -101,7 +128,11 @@ enum Exit { } impl<'a> Lower<'a> { - fn new(source: &'a str, resolution: &'a Resolution) -> Self { + fn new( + source: &'a str, + resolution: &'a Resolution, + holds: Option<&'a HostCallResolver<'a>>, + ) -> Self { let slots = vec![None; resolution.bindings.len()]; let label_state = vec![None; resolution.labels.len()]; Self { @@ -114,6 +145,10 @@ impl<'a> Lower<'a> { result: None, label_state, repeat_flags: 0, + nfor_ordinal: 0, + nfor_slots: Vec::new(), + for_indexes: Vec::new(), + holds, } } @@ -122,7 +157,19 @@ impl<'a> Lower<'a> { if let Some(expr) = value { stmts.push(CoreStmt::Expr { expr, line: 1 }); } - Ok(stmts) + Ok(self.hoist_numeric_for(stmts)) + } + + fn hoist_numeric_for(&self, stmts: Vec) -> Vec { + let mut root = Vec::new(); + for slot in &self.nfor_slots { + root.push(let_float(*slot, CoreExpr::Float(0.0), 1)); + } + for slot in &self.for_indexes { + root.push(let_float(*slot, CoreExpr::Float(0.0), 1)); + } + root.extend(stmts); + root } fn lower_dispatch(&mut self, chunk: &Chunk) -> Result, ParseError> { @@ -159,6 +206,9 @@ impl<'a> Lower<'a> { for slot in self.slots.iter().flatten().copied() { root.push(let_expr(slot, CoreExpr::Null, 1)); } + for slot in &self.nfor_slots { + root.push(let_float(*slot, CoreExpr::Float(0.0), 1)); + } root.push(let_expr(state, CoreExpr::Int(1), 1)); if let Some(result) = self.result { root.push(let_expr(result, CoreExpr::Null, 1)); @@ -206,6 +256,20 @@ impl<'a> Lower<'a> { line: self.line(*span), }); } + Stmt::NumericFor { + name, + start, + limit, + step, + body, + span, + } => { + for stmt in + self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)? + { + blocks.current.push(Item::Core(stmt)); + } + } other => blocks.current.push(self.arm_item(other)?), } } @@ -266,6 +330,22 @@ impl<'a> Lower<'a> { items.extend(self.branch_items(&body.stmts)?); continue; } + if let Stmt::NumericFor { + name, + start, + limit, + step, + body, + span, + } = stmt + { + for core in + self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)? + { + items.push(Item::Core(core)); + } + continue; + } items.push(self.arm_item(stmt)?); } Ok(items) @@ -402,6 +482,109 @@ impl<'a> Lower<'a> { }) } + fn numeric_for_stmts( + &mut self, + name: &Name, + start: &Expr, + limit: &Expr, + step: Option<&Expr>, + body: &Block, + span: Span, + ) -> Result, ParseError> { + if contains_transfer(body) || contains_label(body) { + return Err(self.fail( + span, + "goto, label, or return inside a loop is not in this slice", + )); + } + let (body_stmts, value) = self.straight(&body.stmts, true)?; + if value.is_some() { + return Err(self.fail(span, "return inside a loop is not in this slice")); + } + let line = self.line(span); + let visible = self.slot(self.binding_for_index(name, body)?)?; + if !self.dispatching { + self.for_indexes.push(visible); + } + let hidden = self.alloc_nfor("index")?; + let limit_slot = self.alloc_nfor("limit")?; + let step_slot = self.alloc_nfor("step")?; + // `expr` builds IR. The assigns below are the only runtime evaluation, + // left to right, once per time this loop statement is reached. + let start_expr = self.expr(start)?; + let limit_expr = self.expr(limit)?; + let step_expr = match step { + Some(expr) => self.expr(expr)?, + None => CoreExpr::Float(1.0), + }; + let mut loop_body = vec![set_slot(visible, CoreExpr::Var(hidden), line)]; + loop_body.extend(body_stmts); + Ok(vec![ + set_slot(hidden, start_expr, line), + set_slot(limit_slot, limit_expr, line), + set_slot(step_slot, step_expr, line), + CoreStmt::For { + init: Box::new(CoreStmt::Noop { line }), + condition: self.holds_call(hidden, limit_slot, step_slot, span)?, + post: Box::new(set_slot( + hidden, + CoreExpr::Add( + Box::new(CoreExpr::Var(hidden)), + Box::new(CoreExpr::Var(step_slot)), + ), + line, + )), + body: loop_body, + line, + }, + ]) + } + + fn holds_call( + &mut self, + index: LocalSlot, + limit: LocalSlot, + step: LocalSlot, + span: Span, + ) -> Result { + let Some(resolver) = self.holds else { + return Err(self.fail(span, "numeric for predicate is not bound")); + }; + let signature = [TypeSchema::Float, TypeSchema::Float, TypeSchema::Float]; + let resolved = resolver + .resolve(NUMERIC_FOR_HOLDS, &signature) + .map_err(|error| self.fail(span, format!("numeric for predicate: {error}")))?; + if resolved.return_type != TypeSchema::Bool + || resolved.params.len() != signature.len() + || resolved + .params + .iter() + .any(|param| param.schema != TypeSchema::Float) + { + return Err(self.fail( + span, + "numeric for predicate signature is not three floats to bool", + )); + } + self.builder + .declare_function(NUMERIC_FOR_HOLDS, Some(signature.len() as u8))?; + let index_fn = self + .builder + .function_index(NUMERIC_FOR_HOLDS) + .ok_or_else(|| self.fail(span, "numeric for predicate was not declared"))?; + Ok(CoreExpr::Call( + index_fn, + Vec::new(), + vec![ + CoreExpr::Var(index), + CoreExpr::Var(limit), + CoreExpr::Var(step), + ], + Some(Box::new(resolved)), + None, + )) + } + fn straight( &mut self, stmts: &[Stmt], @@ -447,6 +630,23 @@ impl<'a> Lower<'a> { Stmt::Goto { span, .. } | Stmt::Label { span, .. } => { return Err(self.fail(*span, "goto or label in a direct statement")); } + Stmt::NumericFor { + name, + start, + limit, + step, + body, + span, + } => { + out.extend(self.numeric_for_stmts( + name, + start, + limit, + step.as_ref(), + body, + *span, + )?); + } other => out.push(self.straight_stmt(other, in_loop)?), } } @@ -698,6 +898,18 @@ impl<'a> Lower<'a> { .ok_or_else(|| self.fail(name.span, "local has no resolver binding")) } + fn binding_for_index(&self, name: &Name, body: &Block) -> Result { + self.resolution + .bindings + .iter() + .position(|binding| { + binding.function_id == 0 + && binding.name == name.bytes + && binding.visible_from == body.span.start + }) + .ok_or_else(|| self.fail(name.span, "numeric for index has no resolver binding")) + } + fn binding_at(&self, name: &[u8], span: Span) -> Result { let mut best: Option<(usize, u32)> = None; for (index, binding) in self.resolution.bindings.iter().enumerate() { @@ -739,6 +951,14 @@ impl<'a> Lower<'a> { self.alloc_private(&name) } + fn alloc_nfor(&mut self, role: &str) -> Result { + let name = format!("$lua_nfor_{role}_{}", self.nfor_ordinal); + self.nfor_ordinal += 1; + let slot = self.alloc_private(&name)?; + self.nfor_slots.push(slot); + Ok(slot) + } + fn goto_target(&self, span: Span) -> Result { let goto = self .resolution @@ -844,6 +1064,15 @@ fn let_expr(slot: LocalSlot, expr: CoreExpr, line: u32) -> CoreStmt { } } +fn let_float(slot: LocalSlot, expr: CoreExpr, line: u32) -> CoreStmt { + CoreStmt::Let { + index: slot, + declared_schema: Some(TypeSchema::Float), + expr, + line, + } +} + fn set_slot(slot: LocalSlot, expr: CoreExpr, line: u32) -> CoreStmt { CoreStmt::Assign { kind: AssignmentKind::Set, diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index 1199614..2e88353 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -31,10 +31,14 @@ mod resolve; use std::fs; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; +use std::sync::{Arc, OnceLock}; +use vm::compiler::HostCallResolver; use vm::{ - Expr, FrontendImportSyntax, FrontendIr, JitConfig, LocalSlot, ParseError, SourceFlavor, - SourcePlugin, Stmt, Value, VmStatus, + CallOutcome, CallReturn, CompileSourceFileOptions, Expr, FrontendImportSyntax, FrontendIr, + HostApiBuilder, HostApiCatalog, HostFunctionRegistry, HostFunctionSchema, HostImportSchema, + HostOwnedFunction, HostParamSchema, HostTypeSchema, JitConfig, LocalSlot, OwnedHostCall, + ParseError, SourceFlavor, SourcePlugin, Stmt, Value, Vm, VmError, VmStatus, }; const FUEL_BUDGET: u64 = 8_192; @@ -71,7 +75,8 @@ impl SourcePlugin for ControlLuaPlugin { } fn parse_source(&self, source: &str) -> Result { - control::lower_source(source) + let resolver = HostCallResolver::new(holds_catalog()); + control::lower_source_with(source, Some(&resolver)) } fn parse_module_imports( @@ -87,6 +92,68 @@ fn candidate_options() -> CompileSourceFileOptions { CompileSourceFileOptions::new().with_source_plugin(&CONTROL_LUA_PLUGIN) } +fn numeric_options() -> CompileSourceFileOptions { + candidate_options().with_host_api_catalog(Arc::clone(holds_catalog())) +} + +struct NumericForHolds; + +impl HostOwnedFunction for NumericForHolds { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let [Value::Float(index), Value::Float(limit), Value::Float(step)] = call.args() else { + return Err(VmError::HostError( + "lua_control::numeric_for_holds requires three floats".into(), + )); + }; + // `>=` / `<=` are ordered: NaN makes both false. That is not + // `!(index < limit)`, which would be true for NaN. Sign comes from + // the step bit, so +0 and -0 stay distinct. + let holds = if step.is_sign_negative() { + *index >= *limit + } else { + *index <= *limit + }; + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(holds)))) + } +} + +fn holds_schema() -> HostFunctionSchema { + HostFunctionSchema::with_return( + control::NUMERIC_FOR_HOLDS, + vec![ + HostParamSchema::value("index", HostTypeSchema::Float), + HostParamSchema::value("limit", HostTypeSchema::Float), + HostParamSchema::value("step", HostTypeSchema::Float), + ], + HostTypeSchema::Bool, + ) +} + +fn holds_catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = HostApiBuilder::new(); + builder.function(holds_schema()); + Arc::new(builder.build().expect("numeric for predicate catalog")) + }) +} + +fn bind_numeric_for_holds(vm: &mut Vm) -> Result<(), VmError> { + let catalog = holds_catalog(); + let mut registry = HostFunctionRegistry::empty(); + let function = catalog + .function(control::NUMERIC_FOR_HOLDS) + .expect("numeric for predicate schema"); + registry.register_exact_owned( + control::NUMERIC_FOR_HOLDS, + function.params.len() as u8, + HostImportSchema::from_function(catalog, function), + move |_| Box::new(NumericForHolds), + )?; + registry.authorize_registered_builtin_import(control::NUMERIC_FOR_HOLDS); + registry.bind_vm_cached(vm) +} + fn write_fixture(label: &str, source: &str) -> PathBuf { let root = namespace_case_root(&format!("lua_control_{label}")); let path = root.join("chunk.lua"); @@ -95,8 +162,21 @@ fn write_fixture(label: &str, source: &str) -> PathBuf { } fn run_fixture(label: &str, source: &str) -> (Vec, u64) { + run_compiled(label, source, false) +} + +fn run_numeric(label: &str, source: &str) -> (Vec, u64) { + run_compiled(label, source, true) +} + +fn run_compiled(label: &str, source: &str, numeric_for: bool) -> (Vec, u64) { let path = write_fixture(label, source); - let compiled = compile_source_file_with_options(&path, candidate_options()) + let options = if numeric_for { + numeric_options() + } else { + candidate_options() + }; + let compiled = compile_source_file_with_options(&path, options) .unwrap_or_else(|error| panic!("{label}: compile failed: {error}")); let mut vm = Vm::new_with_jit_config( compiled.program, @@ -106,6 +186,10 @@ fn run_fixture(label: &str, source: &str) -> (Vec, u64) { max_trace_len: 256, }, ); + if numeric_for { + bind_numeric_for_holds(&mut vm) + .unwrap_or_else(|error| panic!("{label}: bind numeric for predicate: {error}")); + } vm.set_fuel_check_interval(FUEL_CHECK_INTERVAL) .unwrap_or_else(|error| panic!("{label}: fuel interval: {error}")); vm.set_fuel(FUEL_BUDGET); @@ -126,6 +210,27 @@ fn run_fixture(label: &str, source: &str) -> (Vec, u64) { (stack, consumed) } +fn expect_numeric(label: &str, source: &str, expected: f64) { + let (stack, consumed) = run_numeric(label, source); + assert_eq!( + stack, + vec![Value::Float(expected)], + "{label}: numeric for mismatch; fuel records a budget exhaustion separately from this value" + ); + assert!(consumed > 0, "{label}: recorded no fuel"); + assert!( + consumed < FUEL_BUDGET, + "{label}: exhausted the fuel budget, so this is not a numeric-for result" + ); + if let Ok(oracle) = std::env::var("LUAJIT_ORACLE") { + let observed = oracle_return(&oracle, &write_fixture(label, source)); + assert_eq!( + observed, expected, + "{label}: LuaJIT returned {observed}, candidate returned {expected}" + ); + } +} + fn expect_number(label: &str, source: &str, expected: f64) { let (stack, consumed) = run_fixture(label, source); assert_eq!( @@ -498,6 +603,12 @@ fn lowered(source: &str) -> FrontendIr { control::lower_source(source).unwrap_or_else(|error| panic!("lower failed: {error}")) } +fn lowered_numeric(source: &str) -> FrontendIr { + let resolver = HostCallResolver::new(holds_catalog()); + control::lower_source_with(source, Some(&resolver)) + .unwrap_or_else(|error| panic!("lower failed: {error}")) +} + fn slot_named(ir: &FrontendIr, name: &str) -> Option { ir.local_bindings .iter() @@ -644,15 +755,18 @@ fn assert_repeat_fors(ir: &FrontendIr, expected: usize) { .. } = stmt { - seen += 1; let Stmt::Let { index, expr: init_expr, .. } = init.as_ref() else { - panic!("repeat init is not one flag let: {init:?}"); + return; }; + if !flags.iter().any(|(_, slot)| slot == index) { + return; + } + seen += 1; assert!( matches!(init_expr, Expr::Bool(true)), "repeat flag must start true so the body runs before until: {init_expr:?}" @@ -1569,6 +1683,788 @@ fn nested_while_and_repeat_keep_transfers_on_the_nearest_loop() { assert_eq!(source_while_count(&inner.stmts, None), 1); } +const NUMERIC_FOR_UP_AND_EMPTY: &str = "\ +local sum = 0 +for i = 1, 3 do + sum = sum * 10 + i +end +for i = 3, 1 do + sum = -1 +end +return sum +"; + +#[test] +fn numeric_for_counts_up_and_skips_an_empty_range() { + // 123 is 1 then 2 then 3. The descending header with the default step + // must not enter, so a wrong direction or a copied body cannot yield 123. + expect_numeric("numeric_for_up_empty", NUMERIC_FOR_UP_AND_EMPTY, 123.0); + let ir = lowered_numeric(NUMERIC_FOR_UP_AND_EMPTY); + assert_eq!(numeric_for_count(&ir), 2); + assert_eq!(default_step_assigns(&ir), 2); +} + +const NUMERIC_FOR_DOWN: &str = "\ +local sum = 0 +for i = 3, 1, -1 do + sum = sum * 10 + i +end +return sum +"; + +const NUMERIC_FOR_FRACTION: &str = "\ +local code = 0 +for i = 0.5, 1.5, 0.5 do + code = code * 10 + i * 2 +end +return code +"; + +const NUMERIC_FOR_HEADER: &str = "\ +local i = 7 +local limit = 1 +local step = -2 +local packed = 0 +local effects = 0 +local n = 0 +for i = i, limit, step do + n = n + 1 + packed = packed * 10 + i + if n == 2 then + continue + end + i = 99 + limit = 100 + step = 100 + effects = effects + 1 +end +return i * 1000000 + packed * 10 + effects +"; + +const NUMERIC_FOR_HEADER_DISPATCH: &str = "\ +local skipped = 0 +goto enter +skipped = 1 +::enter:: +local i = 7 +local limit = 1 +local step = -2 +local packed = 0 +local effects = 0 +local n = 0 +for i = i, limit, step do + n = n + 1 + packed = packed * 10 + i + if n == 2 then + continue + end + i = 99 + limit = 100 + step = 100 + effects = effects + 1 +end +return skipped * 10000000 + i * 1000000 + packed * 10 + effects +"; + +const NUMERIC_FOR_NESTED: &str = "\ +local outer = 0 +local inner = 0 +local after = 0 +for i = 1, 3 do + outer = outer + 1 + for j = 1, 3 do + inner = inner + 1 + if j == 2 then + break + end + end + if i == 2 then + continue + end + after = after + 1 +end +return outer * 100 + inner * 10 + after +"; + +const NUMERIC_FOR_NESTED_DISPATCH: &str = "\ +local skipped = 0 +goto enter +skipped = 1 +::enter:: +local outer = 0 +local inner = 0 +local after = 0 +for i = 1, 3 do + outer = outer + 1 + for j = 1, 3 do + inner = inner + 1 + if j == 2 then + break + end + end + if i == 2 then + continue + end + after = after + 1 +end +return skipped * 1000 + outer * 100 + inner * 10 + after +"; + +const NUMERIC_FOR_FLOATS: &str = "\ +local huge = 1e308 * 10 +local nnan = huge - huge +local pnan = -nnan +local neg0 = -0 +local pos0 = 0 +local code = 0 +local n = 0 +local ok = 1 +n = 0 +ok = 1 +for i = 1.5, 2.5, pos0 do + n = n + 1 + if i ~= 1.5 then + ok = 0 + end + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 1.5, 2.5, neg0 do + n = n + 1 + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 2.5, 1.5, pos0 do + n = n + 1 + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 2.5, 1.5, neg0 do + n = n + 1 + if i ~= 2.5 then + ok = 0 + end + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 1.5, 2.5, pnan do + n = n + 1 + if n == 1 then + if i ~= 1.5 then + ok = 0 + end + end + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 1.5, 2.5, nnan do + n = n + 1 + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 2.5, 1.5, pnan do + n = n + 1 + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 2.5, 1.5, nnan do + n = n + 1 + if n == 1 then + if i ~= 2.5 then + ok = 0 + end + end + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = nnan, 2.5, 1 do + n = n + 1 + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 1.5, nnan, 1 do + n = n + 1 + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 9007199254740992, 9007199254740996, 1 do + n = n + 1 + if i ~= 9007199254740992 then + ok = 0 + end + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +n = 0 +ok = 1 +for i = 1, huge, huge do + n = n + 1 + if n == 1 then + if i ~= 1 then + ok = 0 + end + end + if n > 1 then + if i ~= i then + ok = 0 + end + if not (i > 1e308) then + ok = 0 + end + end + if n == 3 then + break + end +end +if ok == 0 then + n = 9 +end +code = code * 10 + n +return code +"; + +const NUMERIC_FOR_ONCE: &str = "\ +local a = 1 +local b = 4 +local c = 1 +local sum = 0 +for i = a + 1, b, c do + sum = sum + i +end +return sum +"; + +const NUMERIC_FOR_ONCE_DISPATCH: &str = "\ +local skipped = 0 +goto enter +skipped = 1 +::enter:: +local a = 1 +local b = 4 +local c = 1 +local sum = 0 +for i = a + 1, b, c do + sum = sum + i +end +return skipped * 10 + sum +"; + +const NUMERIC_FOR_BAD_STEP: &str = "\ +local bad = false +local seen = 0 +for i = 1, 2, bad do + seen = 1 +end +return seen +"; + +const NUMERIC_FOR_BAD_START: &str = "\ +local bad = false +local seen = 0 +for i = bad, 2, 1 do + seen = 1 +end +return seen +"; + +const NUMERIC_FOR_GENERIC: &str = "\ +for i in 1 do +end +return 0 +"; + +#[test] +fn numeric_for_counts_down_and_uses_a_fractional_step() { + expect_numeric("numeric_for_down", NUMERIC_FOR_DOWN, 321.0); + expect_numeric("numeric_for_fraction", NUMERIC_FOR_FRACTION, 123.0); +} + +#[test] +fn numeric_for_header_is_a_snapshot_and_continue_still_updates() { + // 7075313: outer i stays 7, visits are 7,5,3,1, and the second visit + // continues past the writes. A live limit or step would not pack 7531. + expect_numeric("numeric_for_header", NUMERIC_FOR_HEADER, 7_075_313.0); + expect_numeric( + "numeric_for_header_dispatch", + NUMERIC_FOR_HEADER_DISPATCH, + 7_075_313.0, + ); +} + +#[test] +fn numeric_for_break_and_continue_stay_on_the_source_loop() { + // 362: three outer trips, two inner trips each, and the middle continue + // skips one tail. An inner break that left the outer loop cannot pack 362. + expect_numeric("numeric_for_nested", NUMERIC_FOR_NESTED, 362.0); + expect_numeric( + "numeric_for_nested_dispatch", + NUMERIC_FOR_NESTED_DISPATCH, + 362.0, + ); + let direct = lowered_numeric(NUMERIC_FOR_NESTED); + let dispatch = lowered_numeric(NUMERIC_FOR_NESTED_DISPATCH); + assert!(slot_named(&direct, "$lua_dispatch_state").is_none()); + assert_eq!( + numeric_for_count(&direct), + 2, + "nested source is two fors, not a copied body" + ); + assert_eq!( + numeric_for_count(&dispatch), + 2, + "dispatch must not copy the numeric-for body" + ); + let state = slot_named(&dispatch, "$lua_dispatch_state").expect("dispatch state"); + assert_eq!(dispatch_while_count(&dispatch.stmts, state), 1); + assert_eq!(break_count(&direct), 1); + // Dispatch keeps one unknown-state sentinel break outside the numeric fors. + assert_eq!(break_count(&dispatch), 2); + assert_eq!(breaks_inside_numeric_for(&direct), 1); + assert_eq!(breaks_inside_numeric_for(&dispatch), 1); +} + +#[test] +fn numeric_for_float_boundaries_match_the_locked_sign_bit() { + // Digits, each capped by a source break so a stuck back edge is a wrong + // digit rather than an exhausted fuel budget: + // +0 up 3, -0 up 0, +0 down 0, -0 down 3, + // +NaN up 1, -NaN up 0, +NaN down 0, -NaN down 1, + // NaN start 0, NaN limit 0, 2^53 step 3, inf step 3. + expect_numeric("numeric_for_floats", NUMERIC_FOR_FLOATS, 300_310_010_033.0); +} + +#[test] +fn numeric_for_header_expression_is_materialized_once() { + expect_numeric("numeric_for_once", NUMERIC_FOR_ONCE, 9.0); + expect_numeric("numeric_for_once_dispatch", NUMERIC_FOR_ONCE_DISPATCH, 9.0); + assert_header_once("direct", &lowered_numeric(NUMERIC_FOR_ONCE)); + assert_header_once("dispatch", &lowered_numeric(NUMERIC_FOR_ONCE_DISPATCH)); + let dispatch = lowered_numeric(NUMERIC_FOR_ONCE_DISPATCH); + let state = slot_named(&dispatch, "$lua_dispatch_state").expect("dispatch state"); + assert_eq!(dispatch_while_count(&dispatch.stmts, state), 1); + assert_eq!(numeric_for_count(&dispatch), 1); +} + +#[test] +fn numeric_for_rejects_a_non_float_header_instead_of_an_empty_loop() { + assert_numeric_header_rejected("numeric_for_bad_step", NUMERIC_FOR_BAD_STEP); + assert_numeric_header_rejected("numeric_for_bad_start", NUMERIC_FOR_BAD_START); +} + +#[test] +fn generic_for_stays_outside_this_slice() { + let error = lowered_numeric_err(NUMERIC_FOR_GENERIC); + assert!( + error.contains("statement is not in this chunk control slice"), + "{error}" + ); +} + +fn lowered_numeric_err(source: &str) -> String { + let resolver = HostCallResolver::new(holds_catalog()); + control::lower_source_with(source, Some(&resolver)) + .expect_err("generic for must not lower") + .to_string() +} + +fn slots_with_prefix(ir: &FrontendIr, prefix: &str) -> Vec { + ir.local_bindings + .iter() + .filter(|(name, _)| name.starts_with(prefix)) + .map(|(name, slot)| { + assert!(!is_lua_ident(name), "{name} is a guest identifier"); + *slot + }) + .collect() +} + +fn default_step_assigns(ir: &FrontendIr) -> usize { + let steps = slots_with_prefix(ir, "$lua_nfor_step_"); + let mut seen = 0; + walk_stmts(&ir.stmts, &mut |stmt| { + if let Stmt::Assign { index, expr, .. } = stmt + && steps.contains(index) + && matches!(expr, Expr::Float(value) if *value == 1.0) + { + seen += 1; + } + }); + seen +} + +fn numeric_for_count(ir: &FrontendIr) -> usize { + let mut seen = 0; + walk_stmts(&ir.stmts, &mut |stmt| { + if let Stmt::For { init, .. } = stmt + && matches!(init.as_ref(), Stmt::Noop { .. }) + { + seen += 1; + } + }); + seen +} + +fn break_count(ir: &FrontendIr) -> usize { + break_count_stmts(&ir.stmts) +} + +fn breaks_inside_numeric_for(ir: &FrontendIr) -> usize { + fn walk(stmts: &[Stmt], inside: bool) -> usize { + let mut seen = 0; + for stmt in stmts { + match stmt { + Stmt::Break { .. } if inside => seen += 1, + Stmt::For { + init, post, body, .. + } => { + let numeric = matches!(init.as_ref(), Stmt::Noop { .. }); + seen += walk(std::slice::from_ref(init.as_ref()), inside); + seen += walk(std::slice::from_ref(post.as_ref()), inside); + seen += walk(body, inside || numeric); + } + Stmt::While { body, .. } => seen += walk(body, inside), + Stmt::IfElse { + then_branch, + else_branch, + .. + } => { + seen += walk(then_branch, inside); + seen += walk(else_branch, inside); + } + _ => {} + } + } + seen + } + walk(&ir.stmts, false) +} + +fn break_count_stmts(stmts: &[Stmt]) -> usize { + let mut seen = 0; + walk_stmts(stmts, &mut |stmt| { + if matches!(stmt, Stmt::Break { .. }) { + seen += 1; + } + }); + seen +} + +fn assert_header_once(label: &str, ir: &FrontendIr) { + let indexes = slots_with_prefix(ir, "$lua_nfor_index_"); + let limits = slots_with_prefix(ir, "$lua_nfor_limit_"); + let steps = slots_with_prefix(ir, "$lua_nfor_step_"); + assert_eq!(indexes.len(), 1, "{label}: one hidden counter"); + assert_eq!(limits.len(), 1, "{label}: one cached limit"); + assert_eq!(steps.len(), 1, "{label}: one cached step"); + let index = indexes[0]; + let limit = limits[0]; + let step = steps[0]; + let start = header_start_slot(ir, index).unwrap_or_else(|| { + panic!( + "{label}: hidden counter is not assigned from a + 1; bindings={:?}", + ir.local_bindings + ) + }); + let mut start_adds = 0; + let mut condition_calls = 0; + let mut post_adds = 0; + walk_stmts(&ir.stmts, &mut |stmt| { + if let Stmt::Assign { + index: slot, expr, .. + } = stmt + && *slot == index + && is_start_add(expr, start) + { + start_adds += 1; + } + if let Stmt::For { + condition, post, .. + } = stmt + { + if is_holds_call(condition, index, limit, step) { + condition_calls += 1; + } + if let Stmt::Assign { + index: slot, expr, .. + } = post.as_ref() + && *slot == index + && is_slot_add(expr, index, step) + { + post_adds += 1; + } + } + }); + assert_eq!(start_adds, 1, "{label}: header start must be assigned once"); + assert_eq!( + condition_calls, 1, + "{label}: one predicate call, not a copied loop" + ); + assert_eq!( + post_adds, 1, + "{label}: post adds the saved step, not the source step" + ); + assert!( + !for_interior_has_start_add(&ir.stmts, start), + "{label}: start expression leaked into the condition, post, or body" + ); + assert_eq!( + ir.functions.len(), + 1, + "{label}: one predicate declaration, functions={:?}", + ir.functions + ); + assert_eq!(ir.functions[0].name, control::NUMERIC_FOR_HOLDS); +} + +fn header_start_slot(ir: &FrontendIr, index: LocalSlot) -> Option { + let mut found = None; + walk_stmts(&ir.stmts, &mut |stmt| { + if let Stmt::Assign { + index: slot, + expr: Expr::Add(lhs, rhs), + .. + } = stmt + && *slot == index + && matches!(rhs.as_ref(), Expr::Float(value) if *value == 1.0) + && let Expr::Var(start) = lhs.as_ref() + { + found = Some(*start); + } + }); + found +} + +fn is_start_add(expr: &Expr, start: LocalSlot) -> bool { + matches!( + expr, + Expr::Add(lhs, rhs) + if matches!(lhs.as_ref(), Expr::Var(slot) if *slot == start) + && matches!(rhs.as_ref(), Expr::Float(value) if *value == 1.0) + ) +} + +fn is_slot_add(expr: &Expr, left: LocalSlot, right: LocalSlot) -> bool { + matches!( + expr, + Expr::Add(lhs, rhs) + if matches!(lhs.as_ref(), Expr::Var(slot) if *slot == left) + && matches!(rhs.as_ref(), Expr::Var(slot) if *slot == right) + ) +} + +fn is_holds_call(expr: &Expr, index: LocalSlot, limit: LocalSlot, step: LocalSlot) -> bool { + matches!( + expr, + Expr::Call(_, _, args, Some(_), None) + if matches!( + args.as_slice(), + [ + Expr::Var(got_index), + Expr::Var(got_limit), + Expr::Var(got_step), + ] if *got_index == index && *got_limit == limit && *got_step == step + ) + ) +} + +fn for_interior_has_start_add(stmts: &[Stmt], start: LocalSlot) -> bool { + let mut found = false; + walk_stmts(stmts, &mut |stmt| { + if let Stmt::For { + condition, + post, + body, + .. + } = stmt + { + found |= expr_contains_start_add(condition, start); + found |= stmt_contains_start_add(post, start); + found |= stmts_contain_start_add(body, start); + } + }); + found +} + +fn stmts_contain_start_add(stmts: &[Stmt], start: LocalSlot) -> bool { + stmts.iter().any(|stmt| match stmt { + Stmt::Assign { expr, .. } | Stmt::Let { expr, .. } => expr_contains_start_add(expr, start), + Stmt::For { + condition, + post, + body, + .. + } => { + expr_contains_start_add(condition, start) + || stmt_contains_start_add(post, start) + || stmts_contain_start_add(body, start) + } + Stmt::IfElse { + condition, + then_branch, + else_branch, + .. + } => { + expr_contains_start_add(condition, start) + || stmts_contain_start_add(then_branch, start) + || stmts_contain_start_add(else_branch, start) + } + Stmt::While { + condition, body, .. + } => expr_contains_start_add(condition, start) || stmts_contain_start_add(body, start), + _ => false, + }) +} + +fn stmt_contains_start_add(stmt: &Stmt, start: LocalSlot) -> bool { + match stmt { + Stmt::Assign { expr, .. } | Stmt::Let { expr, .. } => expr_contains_start_add(expr, start), + _ => false, + } +} + +fn expr_contains_start_add(expr: &Expr, start: LocalSlot) -> bool { + if is_start_add(expr, start) { + return true; + } + match expr { + Expr::Add(lhs, rhs) + | Expr::Sub(lhs, rhs) + | Expr::Mul(lhs, rhs) + | Expr::Div(lhs, rhs) + | Expr::Eq(lhs, rhs) + | Expr::Gt(lhs, rhs) => { + expr_contains_start_add(lhs, start) || expr_contains_start_add(rhs, start) + } + Expr::Not(inner) => expr_contains_start_add(inner, start), + Expr::Call(_, _, args, _, _) => args.iter().any(|arg| expr_contains_start_add(arg, start)), + _ => false, + } +} + +fn assert_numeric_header_rejected(label: &str, source: &str) { + let path = write_fixture(label, source); + let compiled = compile_source_file_with_options(&path, numeric_options()); + let compiled = match compiled { + Err(error) => { + let text = error.to_string(); + assert!( + !text.contains("not in this chunk control slice"), + "{label}: non-float header was rejected as unsupported syntax: {text}" + ); + assert!( + text.to_ascii_lowercase().contains("float") + || text.to_ascii_lowercase().contains("type"), + "{label}: non-float header must fail closed, not as an empty loop: {text}" + ); + return; + } + Ok(compiled) => compiled, + }; + let mut vm = Vm::new_with_jit_config( + compiled.program, + JitConfig { + enabled: false, + hot_loop_threshold: 8, + max_trace_len: 256, + }, + ); + bind_numeric_for_holds(&mut vm) + .unwrap_or_else(|error| panic!("{label}: bind numeric for predicate: {error}")); + vm.set_fuel_check_interval(FUEL_CHECK_INTERVAL) + .unwrap_or_else(|error| panic!("{label}: fuel interval: {error}")); + vm.set_fuel(FUEL_BUDGET); + match vm.run() { + Ok(status) => panic!( + "{label}: non-float header halted ({status:?}) with stack {:?}; an empty loop would be 0", + vm.stack() + ), + Err(error) => { + let text = error.to_string(); + assert!( + text.to_ascii_lowercase().contains("float") + || text.to_ascii_lowercase().contains("type") + || text.contains("HostError"), + "{label}: expected a float header failure, got {text}" + ); + } + } +} + #[test] fn repeat_continue_past_a_local_is_rejected_at_load() { let error = control::lower_source(REPEAT_SKIP_LOCAL).expect_err("resolver rejection"); From 0f789540bc43691d8db9490cf659677c5ad4e4f1 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 00:41:52 +0800 Subject: [PATCH 037/225] test(lua): cover numeric for inside a transferred if arm Direct control stays off dispatch and returns 71231. The same loop inside the if that transfers returns 1230, without copying the body. Pure repeat call sites count every for in the existing walk. --- tests/compiler/compiler_lua_control_tests.rs | 157 +++++++++++++++++++ 1 file changed, 157 insertions(+) diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index 2e88353..5d15055 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -747,6 +747,7 @@ fn assert_repeat_fors(ir: &FrontendIr, expected: usize) { slots.dedup(); assert_eq!(slots.len(), expected, "repeat flags alias: {flags:?}"); let mut seen = 0; + let mut total_fors = 0; walk_stmts(&ir.stmts, &mut |stmt| { if let Stmt::For { init, @@ -755,6 +756,7 @@ fn assert_repeat_fors(ir: &FrontendIr, expected: usize) { .. } = stmt { + total_fors += 1; let Stmt::Let { index, expr: init_expr, @@ -806,6 +808,12 @@ fn assert_repeat_fors(ir: &FrontendIr, expected: usize) { } }); assert_eq!(seen, expected, "each repeat is one for, not a copied body"); + // These call sites are pure repeat shapes. The same walk counts every + // For, including one whose init is not the private flag. + assert_eq!( + total_fors, expected, + "pure repeat shape must count every for; flag matching alone misses a non-flag for, flags={flags:?}" + ); } #[test] @@ -2024,6 +2032,44 @@ end return skipped * 10 + sum "; +const NUMERIC_FOR_ARM_LOOP: &str = "\ + for i = base + 1, 3 do + sum = sum * 10 + i + end +"; + +const NUMERIC_FOR_ARM_DIRECT: &str = "\ +local base = 0 +local mark = 0 +local sum = 0 +local tail = 0 +if true then + for i = base + 1, 3 do + sum = sum * 10 + i + end + mark = 7 +end +tail = 1 +return mark * 10000 + sum * 10 + tail +"; + +const NUMERIC_FOR_ARM_JUMP: &str = "\ +local base = 0 +local mark = 0 +local sum = 0 +local tail = 0 +if true then + for i = base + 1, 3 do + sum = sum * 10 + i + end + goto leave + mark = 7 +end +tail = 1 +::leave:: +return mark * 10000 + sum * 10 + tail +"; + const NUMERIC_FOR_BAD_STEP: &str = "\ local bad = false local seen = 0 @@ -2120,6 +2166,42 @@ fn numeric_for_header_expression_is_materialized_once() { assert_eq!(numeric_for_count(&dispatch), 1); } +#[test] +fn numeric_for_in_a_transferred_if_arm_skips_the_following_write() { + // 71231 is the un-jumped arm: the loop packs 123, then the arm stores 7 + // and the statement after the if stores 1. 1230 is the same loop with the + // goto after it skipping both writes. 0 means the loop was dropped. + assert!( + NUMERIC_FOR_ARM_DIRECT.contains(NUMERIC_FOR_ARM_LOOP) + && NUMERIC_FOR_ARM_JUMP.contains(NUMERIC_FOR_ARM_LOOP), + "direct and jumped sources must share the numeric loop text" + ); + expect_numeric("numeric_for_arm_direct", NUMERIC_FOR_ARM_DIRECT, 71_231.0); + expect_numeric("numeric_for_arm_jump", NUMERIC_FOR_ARM_JUMP, 1_230.0); + let direct = lowered_numeric(NUMERIC_FOR_ARM_DIRECT); + let jumped = lowered_numeric(NUMERIC_FOR_ARM_JUMP); + assert!( + slot_named(&direct, "$lua_dispatch_state").is_none(), + "direct control must stay off the dispatch path" + ); + assert_eq!( + numeric_for_count(&direct), + 1, + "direct arm copied the numeric for" + ); + assert_eq!( + numeric_for_count(&jumped), + 1, + "transferred arm copied the numeric for" + ); + let state = slot_named(&jumped, "$lua_dispatch_state").expect("dispatch state"); + assert_eq!(dispatch_while_count(&jumped.stmts, state), 1); + assert!( + numeric_for_sits_in_transferring_if_arm(&jumped.stmts, state), + "numeric for is not in the if arm that transfers" + ); +} + #[test] fn numeric_for_rejects_a_non_float_header_instead_of_an_empty_loop() { assert_numeric_header_rejected("numeric_for_bad_step", NUMERIC_FOR_BAD_STEP); @@ -2179,6 +2261,81 @@ fn numeric_for_count(ir: &FrontendIr) -> usize { seen } +fn numeric_for_sits_in_transferring_if_arm(stmts: &[Stmt], state: LocalSlot) -> bool { + fn is_true_condition(condition: &Expr) -> bool { + matches!( + condition, + Expr::Not(outer) + if matches!( + outer.as_ref(), + Expr::Eq(lhs, rhs) + if matches!(lhs.as_ref(), Expr::Bool(true)) + && matches!(rhs.as_ref(), Expr::Bool(false)) + ) + ) + } + + fn is_numeric_for(stmt: &Stmt) -> bool { + matches!( + stmt, + Stmt::For { init, .. } if matches!(init.as_ref(), Stmt::Noop { .. }) + ) + } + + fn transfers_after_for(arm: &[Stmt], state: LocalSlot) -> bool { + let Some(at) = arm.iter().position(is_numeric_for) else { + return false; + }; + // The goto is the state store and Continue immediately after the for. + // A later unreachable store is not part of this shape. + matches!( + arm.get(at + 1), + Some(Stmt::Assign { + index, + expr: Expr::Int(target), + .. + }) if *index == state && *target != 0 + ) && matches!(arm.get(at + 2), Some(Stmt::Continue { .. })) + } + + fn walk(stmts: &[Stmt], state: LocalSlot, in_dispatch: bool) -> bool { + for stmt in stmts { + match stmt { + Stmt::While { + condition, body, .. + } => { + let nested = in_dispatch || is_dispatch_state_while(condition, state); + if walk(body, state, nested) { + return true; + } + } + Stmt::IfElse { + condition, + then_branch, + else_branch, + .. + } => { + if in_dispatch + && is_true_condition(condition) + && transfers_after_for(then_branch, state) + { + return true; + } + if walk(then_branch, state, in_dispatch) + || walk(else_branch, state, in_dispatch) + { + return true; + } + } + _ => {} + } + } + false + } + + walk(stmts, state, false) +} + fn break_count(ir: &FrontendIr) -> usize { break_count_stmts(&ir.stmts) } From e8e9546c525893a7f720f6832633c6a8a42247b0 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 01:32:05 +0800 Subject: [PATCH 038/225] feat(lua): return from chunk while, repeat, and numeric for A private scalar chunk can return one existing expression from those loops. The return stores the dispatch result once, sets the exit state, and breaks the source loop so its post does not run. Each returning loop then breaks an enclosing source loop, or continues the existing dispatch loop, so a later transfer cannot replace the result. --- src/frontends/lua/control.rs | 201 +++++++++++---- tests/compiler/compiler_lua_control_tests.rs | 253 +++++++++++++++++++ 2 files changed, 398 insertions(+), 56 deletions(-) diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs index b2248bf..6a26e9f 100644 --- a/src/frontends/lua/control.rs +++ b/src/frontends/lua/control.rs @@ -8,10 +8,17 @@ //! statements, including a source `while` or `repeat`. Any goto, or a return //! that is not the chunk tail, becomes a private integer state loop. Each basic //! block is one state. A transfer assigns that state and `Continue`s the dispatch -//! loop, so it is emitted only in the dispatch arm, never inside a nested -//! source loop. `break` and `continue` inside a source loop stay Core -//! statements of that loop. A source `repeat` is one Core `for`, not a copied -//! body. Its private bool starts true, so the body runs before `until`. The +//! loop, so that Continue is emitted only in the dispatch arm, never inside a +//! nested source loop. `break` and `continue` inside a source loop stay Core +//! statements of that loop. A `return` in `while`, `repeat`, or numeric `for` +//! writes the one result, stores the exit state, and `Break`s that source loop +//! so its post does not run. After every loop that can return, an exit-state +//! guard `Break`s an enclosing source loop, or `Continue`s the dispatch loop +//! once the source loop is already in the dispatch arm. A later arm transfer +//! therefore cannot overwrite the exit state. A loop that cannot return is +//! unchanged. `goto` and labels inside a loop are not in this slice. A source +//! `repeat` is one Core `for`, not a copied body. Its private bool starts +//! true, so the body runs before `until`. The //! `for` post stores whether another round is required. Fallthrough and //! `continue` both reach that post; `break` skips it and leaves this `for`, //! not an outer dispatch loop. `until` is placed once and can read the @@ -174,6 +181,15 @@ impl<'a> Lower<'a> { fn lower_dispatch(&mut self, chunk: &Chunk) -> Result, ParseError> { self.dispatching = true; + // A loop return assigns these slots while its body is lowered. Allocate + // them before walking so that assign can name the same slots the root + // `let` declares below. The `let` still dominates every arm. + let state = self.alloc_private(STATE_SLOT)?; + self.state = Some(state); + if contains_return_block(&chunk.body) { + let result = self.alloc_private(RESULT_SLOT)?; + self.result = Some(result); + } let mut blocks = BlockBuf::new(); self.walk_list(&chunk.body.stmts, &mut blocks)?; blocks.finish(); @@ -185,12 +201,6 @@ impl<'a> Lower<'a> { self.label_state[label] = Some(self.state_id_of(index)); } } - let state = self.alloc_private(STATE_SLOT)?; - self.state = Some(state); - if contains_return_block(&chunk.body) { - let result = self.alloc_private(RESULT_SLOT)?; - self.result = Some(result); - } let mut arms = Vec::with_capacity(blocks.finished.len()); for (index, block) in blocks.finished.iter().enumerate() { let state_id = index as i64 + 1; @@ -256,6 +266,16 @@ impl<'a> Lower<'a> { line: self.line(*span), }); } + Stmt::While { cond, body, span } => { + for stmt in self.while_stmt(cond, body, *span, false)? { + blocks.current.push(Item::Core(stmt)); + } + } + Stmt::Repeat { body, until, span } => { + for stmt in self.repeat_stmt(body, until, *span, false)? { + blocks.current.push(Item::Core(stmt)); + } + } Stmt::NumericFor { name, start, @@ -264,9 +284,9 @@ impl<'a> Lower<'a> { body, span, } => { - for stmt in - self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)? - { + let stmts = + self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)?; + for stmt in self.with_return_guard(stmts, body, self.line(*span), false)? { blocks.current.push(Item::Core(stmt)); } } @@ -294,10 +314,6 @@ impl<'a> Lower<'a> { else_body, span, } => self.if_item(arms, else_body.as_ref(), *span), - Stmt::While { cond, body, span } => Ok(Item::Core(self.while_stmt(cond, body, *span)?)), - Stmt::Repeat { body, until, span } => { - Ok(Item::Core(self.repeat_stmt(body, until, *span)?)) - } Stmt::Break { span } | Stmt::Continue { span } => { Err(self.fail(*span, "break or continue outside a source loop")) } @@ -330,6 +346,18 @@ impl<'a> Lower<'a> { items.extend(self.branch_items(&body.stmts)?); continue; } + if let Stmt::While { cond, body, span } = stmt { + for core in self.while_stmt(cond, body, *span, false)? { + items.push(Item::Core(core)); + } + continue; + } + if let Stmt::Repeat { body, until, span } = stmt { + for core in self.repeat_stmt(body, until, *span, false)? { + items.push(Item::Core(core)); + } + continue; + } if let Stmt::NumericFor { name, start, @@ -339,9 +367,9 @@ impl<'a> Lower<'a> { span, } = stmt { - for core in - self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)? - { + let cores = + self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)?; + for core in self.with_return_guard(cores, body, self.line(*span), false)? { items.push(Item::Core(core)); } continue; @@ -426,22 +454,20 @@ impl<'a> Lower<'a> { cond: &Expr, body: &Block, span: Span, - ) -> Result { - if contains_transfer(body) || contains_label(body) { - return Err(self.fail( - span, - "goto, label, or return inside a loop is not in this slice", - )); - } + enclosing_loop: bool, + ) -> Result, ParseError> { + self.reject_loop_transfer(body, span)?; let (body_stmts, value) = self.straight(&body.stmts, true)?; if value.is_some() { return Err(self.fail(span, "return inside a loop is not in this slice")); } - Ok(CoreStmt::While { + let line = self.line(span); + let stmt = CoreStmt::While { condition: core_truthy(self.expr(cond)?), body: body_stmts, - line: self.line(span), - }) + line, + }; + self.with_return_guard(vec![stmt], body, line, enclosing_loop) } fn repeat_stmt( @@ -449,13 +475,9 @@ impl<'a> Lower<'a> { body: &Block, until: &Expr, span: Span, - ) -> Result { - if contains_transfer(body) || contains_label(body) { - return Err(self.fail( - span, - "goto, label, or return inside a loop is not in this slice", - )); - } + enclosing_loop: bool, + ) -> Result, ParseError> { + self.reject_loop_transfer(body, span)?; let (body_stmts, value) = self.straight(&body.stmts, true)?; if value.is_some() { return Err(self.fail(span, "return inside a loop is not in this slice")); @@ -469,7 +491,7 @@ impl<'a> Lower<'a> { // would skip it. A `for` post is reached only after the body or a // `continue`, and a `break` in the body skips the post. The private // flag is a Core bool, not a Lua value. - Ok(CoreStmt::For { + let stmt = CoreStmt::For { init: Box::new(let_expr(again, CoreExpr::Bool(true), line)), condition: CoreExpr::Var(again), post: Box::new(set_slot( @@ -479,7 +501,8 @@ impl<'a> Lower<'a> { )), body: body_stmts, line, - }) + }; + self.with_return_guard(vec![stmt], body, line, enclosing_loop) } fn numeric_for_stmts( @@ -491,12 +514,7 @@ impl<'a> Lower<'a> { body: &Block, span: Span, ) -> Result, ParseError> { - if contains_transfer(body) || contains_label(body) { - return Err(self.fail( - span, - "goto, label, or return inside a loop is not in this slice", - )); - } + self.reject_loop_transfer(body, span)?; let (body_stmts, value) = self.straight(&body.stmts, true)?; if value.is_some() { return Err(self.fail(span, "return inside a loop is not in this slice")); @@ -519,7 +537,7 @@ impl<'a> Lower<'a> { }; let mut loop_body = vec![set_slot(visible, CoreExpr::Var(hidden), line)]; loop_body.extend(body_stmts); - Ok(vec![ + let stmts = vec![ set_slot(hidden, start_expr, line), set_slot(limit_slot, limit_expr, line), set_slot(step_slot, step_expr, line), @@ -537,6 +555,74 @@ impl<'a> Lower<'a> { body: loop_body, line, }, + ]; + Ok(stmts) + } + + fn reject_loop_transfer(&self, body: &Block, span: Span) -> Result<(), ParseError> { + if contains_goto(body) || contains_label(body) { + return Err(self.fail(span, "goto or label inside a loop is not in this slice")); + } + Ok(()) + } + + fn with_return_guard( + &self, + mut stmts: Vec, + body: &Block, + line: u32, + enclosing_loop: bool, + ) -> Result, ParseError> { + if contains_return_block(body) { + stmts.push(self.exit_propagation(line, enclosing_loop)?); + } + Ok(stmts) + } + + fn exit_propagation(&self, line: u32, enclosing_loop: bool) -> Result { + let Some(state) = self.state else { + return Err(self.fail_line(line, "return leaves a loop without a dispatch state")); + }; + // Break leaves the enclosing source loop and skips its post. Continue + // is only legal in the dispatch arm: it is the same exit a chunk + // return already uses, and it runs before a later transfer can store + // another state. + let leave = if enclosing_loop { + CoreStmt::Break { line } + } else { + CoreStmt::Continue { line } + }; + Ok(CoreStmt::IfElse { + condition: CoreExpr::Eq( + Box::new(CoreExpr::Var(state)), + Box::new(CoreExpr::Int(EXIT_STATE)), + ), + then_branch: vec![leave], + else_branch: Vec::new(), + line, + }) + } + + fn loop_return( + &mut self, + values: &ast::ExprList, + span: Span, + ) -> Result, ParseError> { + let expr = self.one_value(values, span)?; + let line = self.line(span); + let Some(result) = self.result else { + return Err(self.fail(span, "return without a result slot")); + }; + let Some(state) = self.state else { + return Err(self.fail(span, "return leaves a loop without a dispatch state")); + }; + // Continue would resume this source loop and run its post. Break + // skips that post. The expression is the assign operand, so it runs + // once, before the exit state is stored. + Ok(vec![ + set_slot(result, expr, line), + set_slot(state, CoreExpr::Int(EXIT_STATE), line), + CoreStmt::Break { line }, ]) } @@ -596,6 +682,10 @@ impl<'a> Lower<'a> { match stmt { Stmt::Empty { .. } => {} Stmt::Return { values, span } => { + if in_loop && self.dispatching { + out.extend(self.loop_return(values, *span)?); + return Ok((out, None)); + } if !last || in_loop { return Err(self.fail(*span, "early return needs dispatch")); } @@ -630,6 +720,12 @@ impl<'a> Lower<'a> { Stmt::Goto { span, .. } | Stmt::Label { span, .. } => { return Err(self.fail(*span, "goto or label in a direct statement")); } + Stmt::While { cond, body, span } => { + out.extend(self.while_stmt(cond, body, *span, in_loop)?); + } + Stmt::Repeat { body, until, span } => { + out.extend(self.repeat_stmt(body, until, *span, in_loop)?); + } Stmt::NumericFor { name, start, @@ -638,14 +734,9 @@ impl<'a> Lower<'a> { body, span, } => { - out.extend(self.numeric_for_stmts( - name, - start, - limit, - step.as_ref(), - body, - *span, - )?); + let stmts = + self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)?; + out.extend(self.with_return_guard(stmts, body, self.line(*span), in_loop)?); } other => out.push(self.straight_stmt(other, in_loop)?), } @@ -670,8 +761,6 @@ impl<'a> Lower<'a> { else_body, span, } => self.if_core(arms, else_body.as_ref(), *span, in_loop), - Stmt::While { cond, body, span } => self.while_stmt(cond, body, *span), - Stmt::Repeat { body, until, span } => self.repeat_stmt(body, until, *span), Stmt::Break { span } if in_loop => Ok(CoreStmt::Break { line: self.line(*span), }), diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index 5d15055..bf2076a 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -2654,3 +2654,256 @@ fn repeat_continue_past_a_local_is_rejected_at_load() { "load rejection marker missing; this is not a full-text match: {stderr}" ); } + +fn private_binding_count(ir: &FrontendIr, name: &str) -> usize { + ir.local_bindings + .iter() + .filter(|(binding, _)| binding == name) + .count() +} + +fn assert_one_dispatch_and_result(ir: &FrontendIr) -> LocalSlot { + assert_eq!( + private_binding_count(ir, "$lua_dispatch_state"), + 1, + "dispatch state was duplicated: {:?}", + ir.local_bindings + ); + assert_eq!( + private_binding_count(ir, "$lua_return_value"), + 1, + "return result was duplicated: {:?}", + ir.local_bindings + ); + let state = slot_named(ir, "$lua_dispatch_state").expect("dispatch state"); + assert_eq!( + dispatch_while_count(&ir.stmts, state), + 1, + "source return must reuse the one dispatch loop" + ); + state +} + +// 12 is the taken return n + 10. 4 is the finished loop's tail return. +// 2 would mean the add was dropped. An open back-edge cannot hide in 12: +// the condition stops at 4. +const WHILE_RETURN_HIT: &str = "\ +local n = 0 +while n < 4 do + n = n + 1 + if n == 2 then + return n + 10 + end +end +return n +"; + +const WHILE_RETURN_MISS: &str = "\ +local n = 0 +while n < 4 do + n = n + 1 + if n == 9 then + return n + 10 + end +end +return n +"; + +#[test] +fn while_return_leaves_the_chunk_and_a_false_condition_continues() { + expect_number("while_return_hit", WHILE_RETURN_HIT, 12.0); + expect_number("while_return_miss", WHILE_RETURN_MISS, 4.0); + let hit = lowered(WHILE_RETURN_HIT); + let state = assert_one_dispatch_and_result(&hit); + assert_eq!( + source_while_count(&hit.stmts, Some(state)), + 1, + "while return copied the source loop" + ); + let miss = lowered(WHILE_RETURN_MISS); + let miss_state = assert_one_dispatch_and_result(&miss); + assert_eq!(source_while_count(&miss.stmts, Some(miss_state)), 1); +} + +// 21 is n + 20 on the first body. 1 is the tail return after leaving the +// repeat without using that expression. until false repeats forever if the +// return continues this loop; fuel exhaustion is that back-edge, not a value. +// 7 is two finished trips plus the tail add, with the return condition false. +const REPEAT_RETURN_HIT: &str = "\ +local n = 0 +repeat + n = n + 1 + if n == 1 then + return n + 20 + end +until false +return n +"; + +const REPEAT_RETURN_MISS: &str = "\ +local n = 0 +repeat + n = n + 1 + if n == 9 then + return n + 20 + end +until n == 2 +return n + 5 +"; + +#[test] +fn repeat_return_leaves_before_until_false_and_a_finished_repeat_continues() { + expect_number("repeat_return_hit", REPEAT_RETURN_HIT, 21.0); + expect_number("repeat_return_miss", REPEAT_RETURN_MISS, 7.0); + let hit = lowered(REPEAT_RETURN_HIT); + assert_one_dispatch_and_result(&hit); + assert_repeat_fors(&hit, 1); + let miss = lowered(REPEAT_RETURN_MISS); + assert_one_dispatch_and_result(&miss); + assert_repeat_fors(&miss, 1); +} + +// 33 is s + 30 after i = 1 then i = 2 (s = 3). 10 is the finished 1+2+3+4. +// 3 would drop the add. A step after the return would reach the tail 10. +const NUMERIC_FOR_RETURN_HIT: &str = "\ +local s = 0 +for i = 1, 4 do + s = s + i + if i == 2 then + return s + 30 + end +end +return s +"; + +const NUMERIC_FOR_RETURN_MISS: &str = "\ +local s = 0 +for i = 1, 4 do + s = s + i + if i == 9 then + return s + 30 + end +end +return s +"; + +#[test] +fn numeric_for_return_leaves_before_the_step_and_a_finished_for_continues() { + expect_numeric("numeric_for_return_hit", NUMERIC_FOR_RETURN_HIT, 33.0); + expect_numeric("numeric_for_return_miss", NUMERIC_FOR_RETURN_MISS, 10.0); + let hit = lowered_numeric(NUMERIC_FOR_RETURN_HIT); + assert_one_dispatch_and_result(&hit); + assert_eq!( + numeric_for_count(&hit), + 1, + "numeric for return copied the source loop" + ); + let miss = lowered_numeric(NUMERIC_FOR_RETURN_MISS); + assert_one_dispatch_and_result(&miss); + assert_eq!(numeric_for_count(&miss), 1); +} + +// 42 is wave + i + 40 on the first numeric trip (1 + 1 + 40). +// 1 is the chunk tail if the while exits before its own trailing add. +// 51 is that trailing add plus the chunk tail, so the repeat body after the +// for ran. until false exhausts fuel if the numeric return only breaks the +// inner for and the repeat back-edge still runs. +const NESTED_LOOP_RETURN: &str = "\ +local wave = 0 +while wave < 3 do + wave = wave + 1 + repeat + for i = 1, 2 do + if wave == 1 then + if i == 1 then + return wave + i + 40 + end + end + end + until false + wave = wave + 50 +end +return wave +"; + +#[test] +fn inner_return_skips_outer_loop_body_and_chunk_tail() { + expect_numeric("nested_loop_return", NESTED_LOOP_RETURN, 42.0); + let ir = lowered_numeric(NESTED_LOOP_RETURN); + let state = assert_one_dispatch_and_result(&ir); + assert_eq!( + source_while_count(&ir.stmts, Some(state)), + 1, + "nested return copied the while" + ); + assert_eq!( + repeat_flag_bindings(&ir).len(), + 1, + "nested return copied the repeat" + ); + assert_eq!( + numeric_for_count(&ir), + 1, + "nested return copied the numeric for" + ); +} + +// 61 is the loop return n + 60. 141 is n + 40 then goto done then n + 100, +// which is the following write replacing the return. 108 is the else goto. +// 143 is the same arm with the return condition false: the while finishes, +// the following write runs, and the external goto still reaches done. +const LOOP_RETURN_GOTO_HIT: &str = "\ +local pick = 1 +local n = 0 +if pick == 1 then + while n < 3 do + n = n + 1 + if n == 1 then + return n + 60 + end + end + n = n + 40 + goto done +else + n = 8 + goto done +end +::done:: +return n + 100 +"; + +const LOOP_RETURN_GOTO_MISS: &str = "\ +local pick = 1 +local n = 0 +if pick == 1 then + while n < 3 do + n = n + 1 + if n == 9 then + return n + 60 + end + end + n = n + 40 + goto done +else + n = 8 + goto done +end +::done:: +return n + 100 +"; + +#[test] +fn return_inside_dispatch_if_arm_is_not_replaced_by_the_following_goto() { + expect_number("loop_return_goto_hit", LOOP_RETURN_GOTO_HIT, 61.0); + expect_number("loop_return_goto_miss", LOOP_RETURN_GOTO_MISS, 143.0); + let hit = lowered(LOOP_RETURN_GOTO_HIT); + let state = assert_one_dispatch_and_result(&hit); + assert_eq!( + source_while_count(&hit.stmts, Some(state)), + 1, + "goto arm copied the while" + ); + let miss = lowered(LOOP_RETURN_GOTO_MISS); + let miss_state = assert_one_dispatch_and_result(&miss); + assert_eq!(source_while_count(&miss.stmts, Some(miss_state)), 1); +} From 48394c3922739109511c81b4de7df812299bc9c0 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 01:28:46 +0800 Subject: [PATCH 039/225] test(lua): reuse one root slot across 260 callable activations Wrap one already-lowered chunk as a test script callable. The same VM and scope call it 260 times; normal completion returns the caller frame to the entry root baseline. --- tests/luajit_heap_runtime/candidate.rs | 153 +++++++++- tests/luajit_heap_runtime/return_frame.rs | 328 ++++++++++++++++++++++ 2 files changed, 468 insertions(+), 13 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index a334da3..1f0f755 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -2,7 +2,7 @@ //! select it until the supported execution and root-transfer gates pass. use std::collections::{HashMap, HashSet}; -use vm::compiler::ir::{FunctionImpl, ResolvedHostCall, ResolvedHostParam}; +use vm::compiler::ir::{FunctionDecl, FunctionImpl, ResolvedHostCall, ResolvedHostParam}; use vm::{ AssignmentKind, CallOutcome, CallReturn, Expr, FrontendIr, HostApiBuilder, HostApiCatalog, HostFunctionRegistry, HostFunctionSchema, HostImportSchema, HostOwnedFunction, HostParamSchema, @@ -30,7 +30,12 @@ const SET_EDGE: &str = "lua_internal::set_edge"; const GET_EDGE: &str = "lua_internal::get_edge"; pub(super) const FINISH_RETURN: &str = "lua_internal::finish_return"; pub(super) const RETIRE_CALLEE: &str = "lua_internal::retire_callee"; -const RETIRE_CHUNK: &str = "lua_internal::retire_chunk"; +pub(super) const RETIRE_CHUNK: &str = "lua_internal::retire_chunk"; +/// Name of the test-only script callable that wraps one already-lowered chunk. +/// +/// The inner Lua function stays unexported. Exporting that callee directly would +/// skip the caller's `FINISH_RETURN` / `RETIRE_CALLEE` window. +pub(super) const EXPORTED_CHUNK: &str = "lua_chunk_entry"; const RELEASE_RESULT: &str = "lua_internal::release_result"; // Test-only witnesses. They place an ordinary VM array on the source path. // They are not Lua syntax and are not registered on the production entry. @@ -520,6 +525,7 @@ fn root_issued(call: &mut OwnedHostCall<'_>) -> Result { }) .map_err(heap_error)?; with_witness(call.vm(), |witness| { + witness.issued.push(table); if role == 0 { witness.returned = Some(table); witness.returned_carrier = carrier_ptr(&value); @@ -810,20 +816,28 @@ fn note_collect( host: &mut vm::HostContext<'_>, report: heap::CollectReport, ) -> Result<(), VmError> { - let Some((returned, discarded, key)) = host - .scope_state::() - .map(|witness| (witness.returned, witness.discarded, witness.field_key)) + let Some((returned, discarded, key, latest)) = + host.scope_state::().map(|witness| { + ( + witness.returned, + witness.discarded, + witness.field_key, + witness.issued.last().copied(), + ) + }) else { return Ok(()); }; - let (returned_alive, discarded_alive, returned_edge) = heap::with_heap(host, |heap| { - Ok(( - returned.is_some_and(|table| heap.alive(table)), - discarded.is_some_and(|table| heap.alive(table)), - read_edge(heap, returned, key)?, - )) - }) - .map_err(heap_error)?; + let (returned_alive, discarded_alive, returned_edge, latest_alive) = + heap::with_heap(host, |heap| { + Ok(( + returned.is_some_and(|table| heap.alive(table)), + discarded.is_some_and(|table| heap.alive(table)), + read_edge(heap, returned, key)?, + latest.is_some_and(|table| heap.alive(table)), + )) + }) + .map_err(heap_error)?; let swept = heap::take_scan_meter(host) .map_err(heap_error)? .scratch @@ -840,6 +854,7 @@ fn note_collect( discarded_alive, returned_edge, }); + witness.issued_alive_at_collect.push(latest_alive); Ok(()) } @@ -940,6 +955,114 @@ pub(super) fn lower_returning( Ok(ir) } +/// Wrap one real, already-lowered chunk as an exported script callable. +/// +/// The body is the chunk's own statements, including the Lua callee call and +/// the normal `RETIRE_CHUNK` completion. The wrapper only connects the +/// compiler's export slot. It does not emit a second root lifecycle. +pub(super) fn lower_exported_chunk( + source: &str, + catalog: &HostApiCatalog, + publish_results: bool, +) -> Result { + let mut ir = lower_returning(source, catalog, publish_results)?; + let body_expr = connect_scalar_return(&mut ir)?; + let index = u16::try_from(ir.functions.len()) + .map_err(|_| ParseError::at_line(1, "exported chunk exceeds the function index space"))?; + if ir.functions.iter().any(|func| func.index == index) + || ir.function_impls.contains_key(&index) + || ir.functions.iter().any(|func| func.name == EXPORTED_CHUNK) + { + return Err(ParseError::at_line( + 1, + "exported chunk collides with an existing function", + )); + } + ir.functions.push(FunctionDecl { + name: EXPORTED_CHUNK.to_string(), + arity: 0, + index, + args: Vec::new(), + arg_schemas: Vec::new(), + return_schema: None, + type_params: Vec::new(), + exported: true, + return_type: vm::ValueType::Unknown, + symbol: None, + }); + ir.function_sources.insert(index, source.to_string()); + ir.function_impls.insert( + index, + FunctionImpl { + param_slots: Vec::new(), + capture_copies: Vec::new(), + body_stmts: std::mem::take(&mut ir.stmts), + body_expr, + body_expr_line: 1, + }, + ); + Ok(ir) +} + +/// Keep the chunk's scalar return in a local so the script `Ret` can load it +/// after `RETIRE_CHUNK`. A chunk with no return stays a null fallthrough. +fn connect_scalar_return(ir: &mut FrontendIr) -> Result { + let Some(return_index) = ir + .functions + .iter() + .find(|func| func.name == RETURN_SCALAR) + .map(|func| func.index) + else { + return Ok(Expr::Null); + }; + let mut found = None; + for (index, stmt) in ir.stmts.iter().enumerate() { + let Stmt::Expr { expr, .. } = stmt else { + continue; + }; + let Expr::Call(call_index, ..) = expr else { + continue; + }; + if *call_index != return_index { + continue; + } + if found.is_some() { + return Err(ParseError::at_line( + 1, + "exported chunk has more than one scalar return", + )); + } + found = Some(index); + } + let Some(stmt_index) = found else { + return Err(ParseError::at_line( + 1, + "scalar return host is declared but the chunk has no return statement", + )); + }; + let slot = u16::try_from(ir.locals).map_err(|_| { + ParseError::at_line(1, "exported scalar slot exceeds the local index space") + })?; + ir.locals += 1; + ir.local_bindings.push(("#export-scalar".to_string(), slot)); + let Stmt::Expr { expr, line } = ir.stmts.remove(stmt_index) else { + return Err(ParseError::at_line( + 1, + "scalar return statement disappeared", + )); + }; + ir.stmts.insert( + stmt_index, + Stmt::Let { + index: slot, + declared_schema: None, + expr, + line, + }, + ); + Ok(Expr::Var(slot)) +} + struct Lower<'a> { source: &'a str, catalog: &'a HostApiCatalog, @@ -1769,6 +1892,10 @@ pub(super) struct ReturnWitness { pub collects: Vec, pub release: Option, pub handoffs: Vec, + /// Every table rooted by `root_issued`, in activation order. + pub issued: Vec, + /// Whether the latest issued table was still alive at each guest collect. + pub issued_alive_at_collect: Vec, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] diff --git a/tests/luajit_heap_runtime/return_frame.rs b/tests/luajit_heap_runtime/return_frame.rs index 5d831c4..6c2e9aa 100644 --- a/tests/luajit_heap_runtime/return_frame.rs +++ b/tests/luajit_heap_runtime/return_frame.rs @@ -288,6 +288,26 @@ impl SourcePlugin for UnpublishedReturn { } } +struct ExportedChunk; + +impl SourcePlugin for ExportedChunk { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower_exported_chunk(source, catalog(), true) + } +} + fn run(source: &str, publish_results: bool) -> vm::Vm { let catalog = Arc::clone(catalog()); let options = if publish_results { @@ -1705,3 +1725,311 @@ return collectgarbage("collect") assert_eq!(during.live_nodes, exit.baseline.live_nodes + 1); assert_only_chunk_frame_retired(&mut exit); } + +const REPEATED_CALLS: usize = 260; + +const REPEATED_SOURCE: &str = r#" +local function make() + local obj = {} + obj.self = obj + collectgarbage("collect") + return 7 +end +local n = make() +return n +"#; + +fn bind_exported(source: &str) -> vm::Vm { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&ExportedChunk) + .with_host_api_catalog(Arc::clone(&catalog)); + let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .expect("compile exported chunk") + .into_vm() + .expect("create VM"); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register_witnesses(&mut registry, &catalog); + register_caller_reads(&mut registry, &catalog); + register_binding_obs(&mut registry, &catalog); + registry + .bind_vm_cached(&mut vm) + .expect("bind candidate runtime"); + vm.set_jit_config(vm::JitConfig { + enabled: false, + hot_loop_threshold: 0, + max_trace_len: 0, + }); + vm +} + +fn assert_exported_script_entry(vm: &vm::Vm) { + let program = vm.program(); + assert!( + program + .exported_callables + .iter() + .all(|item| item.name != "make"), + "the Lua callee stays unexported so its caller still runs FINISH_RETURN" + ); + let export = program + .exported_callables + .iter() + .find(|item| item.name == candidate::EXPORTED_CHUNK) + .expect("compiled script export"); + assert_eq!( + program + .exported_callables + .iter() + .filter(|item| item.name == candidate::EXPORTED_CHUNK) + .count(), + 1 + ); + let binding = program + .root_callable_bindings + .iter() + .find(|item| item.local_slot == export.local_slot) + .expect("export occupies one root callable slot"); + let prototype = program + .callable_prototypes + .get(binding.prototype_id as usize) + .expect("export prototype"); + let vm::CallableTarget::ScriptFunction(index) = prototype.target else { + panic!( + "export target is not a script function: {:?}", + prototype.target + ); + }; + let function = program + .script_functions + .get(index as usize) + .expect("export script function"); + assert!( + function.end_ip > function.entry_ip, + "export region is not empty" + ); + assert!( + region_has(program, function.entry_ip, function.end_ip, OpCode::Ret), + "the exported chunk retires with Ret" + ); + let retire = import_index(program, candidate::RETIRE_CHUNK); + assert!( + region_calls(program, function.entry_ip, function.end_ip, retire), + "the exported chunk still emits this activation's RETIRE_CHUNK" + ); + let finish = import_index(program, candidate::FINISH_RETURN); + assert!( + region_calls(program, function.entry_ip, function.end_ip, finish), + "the exported chunk still runs FINISH_RETURN" + ); + let callee_retire = import_index(program, candidate::RETIRE_CALLEE); + assert!( + region_calls(program, function.entry_ip, function.end_ip, callee_retire), + "the exported chunk still retires the Lua callee" + ); + let mut callee = None; + let mut ip = function.entry_ip as usize; + let end = function.end_ip as usize; + while ip < end { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == OpCode::CallScript { + let prototype_id = + u32::from_le_bytes(program.code[ip + 1..ip + 5].try_into().expect("prototype")); + let target = program + .callable_prototypes + .get(prototype_id as usize) + .expect("callee prototype"); + let vm::CallableTarget::ScriptFunction(callee_index) = target.target else { + panic!("CallScript inside the export is not a script function"); + }; + assert_ne!(callee_index, index, "the export must not call itself"); + let callee_fn = program + .script_functions + .get(callee_index as usize) + .expect("Lua callee"); + assert!( + ip < callee_fn.entry_ip as usize || ip >= callee_fn.end_ip as usize, + "the call site is outside the callee" + ); + assert!( + region_has(program, callee_fn.entry_ip, callee_fn.end_ip, OpCode::Ret), + "the Lua callee still retires with Ret" + ); + let collect = import_index(program, candidate::COLLECT); + assert!( + region_calls(program, callee_fn.entry_ip, callee_fn.end_ip, collect), + "the activation collects while the callee frame is still current" + ); + callee = Some(callee_index); + break; + } + ip += 1 + op.operand_len(); + } + assert!( + callee.is_some(), + "the export body has no real Lua callee call" + ); +} + +/// Same VM and same outer scope, 260 normal completions of one exported chunk. +/// +/// LuaJIT's separate 260-activation oracle is not this compat result. Rust +/// starts the real callable, observes, and collects in this scope. It does not +/// reset the VM, drop the scope, or call `leave_roots` for the activation frame. +#[test] +fn exported_chunk_reuses_one_root_slot_across_260_calls() { + let mut vm = bind_exported(REPEATED_SOURCE); + assert_exported_script_entry(&vm); + let outer_frame = heap::with_heap(&mut vm.host_context(), |heap| heap.enter_roots(1)) + .expect("native heap accepts an outer frame"); + let carrier = heap::publish_guest(&mut vm.host_context()).expect("outer table"); + let outer_table = heap::with_heap(&mut vm.host_context(), |heap| { + let heap::GuestClass::Table(table) = heap.guest_class(&carrier) else { + return Err(heap::HeapError::WrongKind); + }; + heap.write_root(outer_frame, 0, table)?; + Ok(table) + }) + .expect("write the outer root"); + assert_eq!(vm.run().expect("empty root halts"), VmStatus::Halted); + let baseline = heap::stats(&mut vm.host_context()).expect("entry baseline"); + let baseline_resources = vm.host_context().resource_count(); + assert_eq!(baseline.root_slots, 1, "setup: one outer root slot"); + assert_eq!(baseline.live_roots, 1, "setup: one live outer root"); + assert_eq!(baseline.live_nodes, 1, "setup: one outer node"); + assert_eq!(baseline_resources, 1, "setup: one outer resource"); + assert_eq!(vm.call_depth(), 0, "setup: root frame has halted"); + let host_calls_before = vm.interpreter_metrics_snapshot().generic_builtin_call_count; + let mut retained = None; + for round in 0..REPEATED_CALLS { + let callable = vm + .resolve_exported_callable(candidate::EXPORTED_CHUNK) + .unwrap_or_else(|error| panic!("round {round}: export binding missing: {error}")); + assert!( + matches!(callable, Value::Callable(_)), + "round {round}: export is not a callable" + ); + let value = vm + .invoke_callable(callable, &[]) + .unwrap_or_else(|error| panic!("round {round}: callable failed: {error}")); + assert_eq!(value, Value::Float(7.0), "round {round}: scalar handoff"); + assert_eq!(vm.call_depth(), 0, "round {round}: no leftover Core frame"); + let seen = witness(&mut vm); + assert_eq!(seen.issued.len(), round + 1, "round {round}: one new table"); + assert_eq!( + seen.collects.len(), + round + 1, + "round {round}: one in-activation collect" + ); + assert_eq!( + seen.issued_alive_at_collect.len(), + round + 1, + "round {round}: collect observed the new table" + ); + assert!( + seen.issued_alive_at_collect[round], + "round {round}: collect inside the activation must still see the table" + ); + let table = seen.issued[round]; + assert!( + seen.issued[..round].iter().all(|prior| *prior != table), + "round {round}: table handle is not reused before collect" + ); + let key = seen.field_key.expect("self field"); + let edge = heap::with_heap(&mut vm.host_context(), |heap| heap.edge(table, key)) + .expect("self edge"); + assert_eq!(edge, Some(table), "round {round}: self-loop is live"); + let stats = heap::stats(&mut vm.host_context()).expect("stats after return"); + assert_eq!( + stats.root_slots, baseline.root_slots, + "round {round}: root slots must return to the entry baseline" + ); + assert_eq!( + stats.live_roots, baseline.live_roots, + "round {round}: live roots must return to the entry baseline" + ); + assert_eq!( + stats.live_nodes, + baseline.live_nodes + 1, + "round {round}: the unrooted self-cycle still occupies a node" + ); + assert!( + heap_alive(&mut vm, table), + "round {round}: completion must not collect the table immediately" + ); + assert!( + heap_alive(&mut vm, outer_table), + "round {round}: outer root stays live" + ); + let current = heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.current_frame())) + .expect("current frame"); + assert_eq!( + current, + Some(outer_frame), + "round {round}: only the outer frame remains" + ); + assert_eq!( + vm.host_context().resource_count(), + baseline_resources + 1, + "round {round}: the table resource stays until collect" + ); + let omit_post_return_collect = round + 1 == REPEATED_CALLS; + if omit_post_return_collect { + retained = Some(table); + continue; + } + heap::collect(&mut vm.host_context()).expect("same-scope collect"); + assert!( + !heap_alive(&mut vm, table), + "round {round}: explicit collect reclaims the table" + ); + assert!( + heap_alive(&mut vm, outer_table), + "round {round}: collect keeps the outer root" + ); + let after = heap::stats(&mut vm.host_context()).expect("stats after collect"); + assert_eq!(after.root_slots, baseline.root_slots); + assert_eq!(after.live_roots, baseline.live_roots); + assert_eq!(after.live_nodes, baseline.live_nodes); + assert_eq!(vm.host_context().resource_count(), baseline_resources); + } + let retained = retained.expect("one round omitted the post-return collect"); + assert!( + heap_alive(&mut vm, retained), + "omitting the post-return collect leaves the self-cycle observable" + ); + assert_eq!( + vm.host_context().resource_count(), + baseline_resources + 1, + "omitting the post-return collect leaves the host resource" + ); + heap::collect(&mut vm.host_context()).expect("final same-scope collect"); + assert!(!heap_alive(&mut vm, retained)); + assert!(heap_alive(&mut vm, outer_table)); + let after = heap::stats(&mut vm.host_context()).expect("stats after final collect"); + assert_eq!(after.root_slots, baseline.root_slots); + assert_eq!(after.live_roots, baseline.live_roots); + assert_eq!(after.live_nodes, baseline.live_nodes); + assert_eq!(vm.host_context().resource_count(), baseline_resources); + let current = heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.current_frame())) + .expect("frame after final collect"); + assert_eq!(current, Some(outer_frame)); + let host_calls = vm + .interpreter_metrics_snapshot() + .generic_builtin_call_count + .saturating_sub(host_calls_before); + assert!( + host_calls >= REPEATED_CALLS as u64, + "interpreter host calls {host_calls} did not cover {REPEATED_CALLS} rounds" + ); + assert_eq!( + host_calls % REPEATED_CALLS as u64, + 0, + "host calls {host_calls} are not uniform across {REPEATED_CALLS} rounds" + ); + eprintln!( + "callable-repeated-retirement rounds={REPEATED_CALLS} host_calls={host_calls} per_round={}", + host_calls / REPEATED_CALLS as u64 + ); +} From babb91ccecd1f06e33b6b22a430572892273091f Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 01:52:35 +0800 Subject: [PATCH 040/225] fix(lua): retain issued table carriers until sweep --- src/frontends/lua/heap/table.rs | 44 ++++---- .../value_boundary_tests.rs | 102 +++++++++++++++++- 2 files changed, 118 insertions(+), 28 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index f767102..f23fd99 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -1,8 +1,8 @@ //! Non-moving mark/sweep table storage, explicit root frames, and hard caps. use std::fmt; +use std::sync::Arc; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Weak}; use vm::{HostContextError, Value}; @@ -162,10 +162,10 @@ struct Slot { /// Raw resource handle for this node. Ownership metadata only: the mark /// phase does not read it, so the token is not a GC root. token: Option, - /// Weak identity of the VM array issued for this generation. Not a GC - /// root and not a strong reference: dropping the guest value drops the - /// array even while this slot is live. - carrier: Weak>, + /// Canonical VM array for this generation, if issued. The slot owns the + /// array so a field can read it back while the node is live. It contains + /// identity only, not object edges, and does not participate in marking. + carrier: Option>>, } struct Edge { @@ -349,7 +349,7 @@ impl LuaHeap { } slot.state = SlotState::Live { marked: false }; slot.token = None; - slot.carrier = Weak::new(); + slot.carrier = None; return Ok(TableRef::table(self.domain, index, slot.generation)); } if self.slots.len() >= self.limits.nodes as usize { @@ -363,7 +363,7 @@ impl LuaHeap { generation: 1, state: SlotState::Live { marked: false }, token: None, - carrier: Weak::new(), + carrier: None, }); self.note_node_peak(); Ok(TableRef::table(self.domain, index, 1)) @@ -382,14 +382,12 @@ impl LuaHeap { /// Issues the guest array for a live table. /// - /// The slot stores only a weak pointer to that array. The pointer is not - /// a root and does not keep the array alive. A second issue while the - /// first array is still alive is refused, so assignment and `Value` clone - /// keep one identity. + /// The slot keeps one array until release. A second issue for that live + /// generation is refused, so assignment and field reads keep one identity. pub fn issue_carrier(&mut self, table: TableRef) -> Result { self.require_live(table)?; let index = table.slot() as usize; - if self.slots[index].carrier.upgrade().is_some() { + if self.slots[index].carrier.is_some() { return Err(HeapError::StaleHandle); } let value = Value::array(vec![ @@ -397,10 +395,10 @@ impl LuaHeap { Value::Int(i64::from(table.generation())), ]); let carrier = match &value { - Value::Array(issued) => Arc::downgrade(issued), + Value::Array(issued) => Arc::clone(issued), _ => unreachable!("Value::array returns an array"), }; - self.slots[index].carrier = carrier; + self.slots[index].carrier = Some(carrier); Ok(value) } @@ -408,10 +406,8 @@ impl LuaHeap { /// /// A table result requires the live slot, the issued generation, and the /// same VM array. Field equality is not enough. An integer resource token - /// is not consulted. This is one slot index, one generation compare, one - /// weak upgrade, and one pointer compare. It does not add a root and does - /// not increment scan counts. It is the experimental guest check for this - /// slice, not a measured production collection scheme. + /// is not consulted. The slot lookup, generation check, and pointer + /// comparison do not add a root or increment scan counts. pub fn guest_class(&self, value: &Value) -> GuestClass { match value { Value::Float(_) => GuestClass::Number, @@ -438,8 +434,8 @@ impl LuaHeap { if !matches!(stored.state, SlotState::Live { .. }) { return None; } - let current = stored.carrier.upgrade()?; - if !Arc::ptr_eq(¤t, issued) { + let current = stored.carrier.as_ref()?; + if !Arc::ptr_eq(current, issued) { return None; } Some(TableRef::table(self.domain, slot, generation)) @@ -488,14 +484,14 @@ impl LuaHeap { })) } - /// Upgrades the slot's weak carrier for a field read. The upgrade is not a root. + /// Clones the slot's issued carrier for a field read. This does not add a root. pub fn issued_value(&self, table: TableRef) -> Result { self.require_live(table)?; let carrier = self.slots[table.slot() as usize] .carrier - .upgrade() + .as_ref() .ok_or(HeapError::StaleHandle)?; - Ok(Value::Array(carrier)) + Ok(Value::Array(Arc::clone(carrier))) } /// Opens a root frame of `width` slots. Failure does not grow root storage. @@ -845,7 +841,7 @@ impl LuaHeap { fn release_slot(&mut self, index: u32) { let slot = &mut self.slots[index as usize]; slot.token = None; - slot.carrier = Weak::new(); + slot.carrier = None; if slot.generation >= self.limits.max_generation { slot.state = SlotState::Retired; return; diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 7140a55..48bfd04 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -125,6 +125,13 @@ struct Entries { numbers: usize, } +// Identity metadata only: recording a borrowed table does not keep its carrier alive. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct ObservedTable { + table: heap::TableRef, + token: vm::ResourceHandle, +} + fn entries(vm: &mut vm::Vm) -> Entries { vm.host_context() .scope_state::() @@ -286,6 +293,12 @@ impl vm::HostOwnedFunction for Witness { .unwrap() .table(); let live = heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).unwrap(); + host.scope_state_or_insert_with(Vec::::new) + .unwrap() + .push(ObservedTable { + table, + token: handle, + }); assert_eq!(args[1 - *index], Value::Float(0.0)); Value::Bool(live) } @@ -428,6 +441,76 @@ fn lua_candidate_alias_remains_the_issued_table_across_collection() { assert_eq!(stats.live_roots, 0); } +#[test] +fn lua_candidate_reads_original_table_kept_only_by_a_strong_field() { + let source = r#" +local function make() + local owner = {} + local child = {} + observe_table(child, 0) + owner.field = child + child = nil + return owner +end +local owner = make() +local unrelated = {} +local discarded = type({}) +collectgarbage("collect") +local read_ok = observe_table(owner.field, 0) +owner = nil +collectgarbage("collect") +observe_table(unrelated, 0) +return read_ok +"#; + let mut vm = candidate(source); + let status = vm.run(); + let mut host = vm.host_context(); + let witness = host.scope_state::().unwrap(); + let tables = host.scope_state::>().unwrap(); + let original = tables[0]; + assert!(witness.callee_left); + assert_eq!(witness.discarded, Some(original.table)); + let first = &witness.collects[0]; + assert_eq!( + first.returned_edge, + candidate::EdgeView::Live(original.table) + ); + assert!(first.returned_alive && first.discarded_alive); + assert_eq!( + (first.marked_nodes, first.live_nodes, first.swept), + (3, 3, 1) + ); + assert_eq!( + status.expect("read the field after a real collection"), + VmStatus::Halted + ); + assert_eq!(tables.len(), 3); + assert_eq!( + tables[1], original, + "the same slot, generation and Core token" + ); + + assert_eq!(witness.collects.len(), 2); + let second = &witness.collects[1]; + assert!(!second.returned_alive && !second.discarded_alive); + assert_eq!( + (second.marked_nodes, second.live_nodes, second.swept), + (1, 1, 2) + ); + assert_eq!(host.resource_count(), 1); + let key = heap::LuaTableResource::key(); + assert!( + host.borrow_resource_with_key::(original.token, &key) + .is_err() + ); + assert!( + host.borrow_resource_with_key::(tables[2].token, &key) + .is_ok() + ); + assert_eq!(heap::stats(&mut host).unwrap().live_roots, 0); + assert_eq!(vm.stack(), &[Value::Bool(true)]); +} + fn live_nodes(vm: &mut vm::Vm) -> u32 { heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.stats().live_nodes)).unwrap() } @@ -485,10 +568,21 @@ fn issued_carrier_keeps_identity_without_adding_a_root() { let weak = Arc::downgrade(issued); drop(carrier); drop(alias); - assert!( - weak.upgrade().is_none(), - "the slot weak pointer must not keep the array alive" - ); + { + let original = weak.upgrade().expect("the live slot owns the issued array"); + let read = heap::with_heap(&mut vm.host_context(), |heap| heap.issued_value(table)) + .expect("read the original carrier"); + let Value::Array(read) = read else { + panic!("issued carrier is an array"); + }; + assert!(Arc::ptr_eq(&original, &read)); + } + let report = heap::collect(&mut vm.host_context()).unwrap(); + assert_eq!(report.marked_nodes, 0); + assert_eq!(report.live_nodes, 0); + assert_eq!(report.live_roots, 0); + assert_eq!(vm.host_context().resource_count(), 0); + assert!(weak.upgrade().is_none(), "sweeping drops the slot's array"); }); } From 3cf856a8ea7295339fc4e4499960b89ab6683985 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 03:02:08 +0800 Subject: [PATCH 041/225] feat(lua): leave a structured loop by goto to an outside label A goto in while, repeat, or numeric for may target a resolver-accepted label outside every source loop. The loop stores that label index as a negative state and Breaks, so its tail and post do not run. Enclosing loops propagate the non-positive state. The one dispatch loop rewrites it through the finished label map. Positive arm ids stay positive, and 0 remains the chunk return. A label or goto that stays inside a loop is still rejected. --- src/frontends/lua/control.rs | 212 ++++++++++++- tests/compiler/compiler_lua_control_tests.rs | 301 +++++++++++++++++++ 2 files changed, 499 insertions(+), 14 deletions(-) diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs index 6a26e9f..dfb49d8 100644 --- a/src/frontends/lua/control.rs +++ b/src/frontends/lua/control.rs @@ -12,11 +12,23 @@ //! nested source loop. `break` and `continue` inside a source loop stay Core //! statements of that loop. A `return` in `while`, `repeat`, or numeric `for` //! writes the one result, stores the exit state, and `Break`s that source loop -//! so its post does not run. After every loop that can return, an exit-state -//! guard `Break`s an enclosing source loop, or `Continue`s the dispatch loop -//! once the source loop is already in the dispatch arm. A later arm transfer -//! therefore cannot overwrite the exit state. A loop that cannot return is -//! unchanged. `goto` and labels inside a loop are not in this slice. A source +//! so its post does not run. After every loop that can return or jump outward, +//! an exit-state guard `Break`s an enclosing source loop, or `Continue`s the +//! dispatch loop once the source loop is already in the dispatch arm. A later +//! arm transfer therefore cannot overwrite the exit state. A loop that cannot +//! return and has no outward goto is unchanged. A `goto` in `while`, `repeat`, +//! or numeric `for` may target a label the resolver has already accepted outside +//! source loop. That goto stores a negative state — the resolver label index, +//! not an arm id — and `Break`s, so this loop's tail and post do not run. +//! Enclosing source loops see the same non-positive state and `Break` too. +//! After the outermost source loop, the one dispatch loop maps that negative +//! value through the finished label table and continues to the existing arm. +//! Positive arm ids stay positive, and `0` remains the chunk return. The +//! negative carrier is required because the loop body is lowered before arm +//! ids exist. Storing the positive id inside the loop would compare equal to +//! the current arm when the label is that arm's own entry, and the statements +//! after the loop would overwrite the jump. A label inside a loop, or a goto +//! whose target is still inside a loop, is not in this slice. A source //! `repeat` is one Core `for`, not a copied body. Its private bool starts //! true, so the body runs before `until`. The //! `for` post stores whether another round is required. Fallthrough and @@ -72,7 +84,12 @@ pub(super) fn lower_source_with( let line = line_of(source, error_span(error)); return Err(ParseError::at_line(line, static_message(error))); } - let mut lower = Lower::new(source, &resolution, holds); + let mut lower = Lower::new( + source, + &resolution, + holds, + labels_inside_loops(&chunk, &resolution), + ); let stmts = if needs_dispatch(&chunk) { lower.lower_dispatch(&chunk)? } else { @@ -95,6 +112,8 @@ struct Lower<'a> { nfor_slots: Vec, for_indexes: Vec, holds: Option<&'a HostCallResolver<'a>>, + labels_in_loops: Vec, + pending_labels: Vec, } struct BlockBuf { @@ -139,6 +158,7 @@ impl<'a> Lower<'a> { source: &'a str, resolution: &'a Resolution, holds: Option<&'a HostCallResolver<'a>>, + labels_in_loops: Vec, ) -> Self { let slots = vec![None; resolution.bindings.len()]; let label_state = vec![None; resolution.labels.len()]; @@ -156,6 +176,8 @@ impl<'a> Lower<'a> { nfor_slots: Vec::new(), for_indexes: Vec::new(), holds, + labels_in_loops, + pending_labels: Vec::new(), } } @@ -209,6 +231,14 @@ impl<'a> Lower<'a> { arms.push((state_id, body)); } let chain = dispatch_chain(state, arms); + // An outward goto carries a negative label index until this point. + // Arm ids exist only after the walk, so the rewrite stays here, on + // the one dispatch loop, and only when a loop goto needs it. + let mut dispatch_body = Vec::new(); + if !self.pending_labels.is_empty() { + dispatch_body.push(self.resolve_pending_labels(state)?); + } + dispatch_body.push(chain); // Core requires a `let` on every path before an assign. The arms do // not dominate each other, so user slots are declared here. The // source initializer still runs at the declaration, as an assign. @@ -228,7 +258,7 @@ impl<'a> Lower<'a> { Box::new(CoreExpr::Var(state)), Box::new(CoreExpr::Int(EXIT_STATE)), ))), - body: vec![chain], + body: dispatch_body, line: 1, }); if let Some(result) = self.result { @@ -560,7 +590,7 @@ impl<'a> Lower<'a> { } fn reject_loop_transfer(&self, body: &Block, span: Span) -> Result<(), ParseError> { - if contains_goto(body) || contains_label(body) { + if contains_label(body) || self.block_has_goto(body, false) { return Err(self.fail(span, "goto or label inside a loop is not in this slice")); } Ok(()) @@ -573,7 +603,7 @@ impl<'a> Lower<'a> { line: u32, enclosing_loop: bool, ) -> Result, ParseError> { - if contains_return_block(body) { + if contains_return_block(body) || self.block_has_goto(body, true) { stmts.push(self.exit_propagation(line, enclosing_loop)?); } Ok(stmts) @@ -592,11 +622,15 @@ impl<'a> Lower<'a> { } else { CoreStmt::Continue { line } }; + // 0 is a chunk return. A negative value is an outward goto whose arm + // id is applied only when this state leaves the last source loop. + // Both must leave before a later store in this arm replaces them. + let pending_exit = CoreExpr::Not(Box::new(CoreExpr::Gt( + Box::new(CoreExpr::Var(state)), + Box::new(CoreExpr::Int(0)), + ))); Ok(CoreStmt::IfElse { - condition: CoreExpr::Eq( - Box::new(CoreExpr::Var(state)), - Box::new(CoreExpr::Int(EXIT_STATE)), - ), + condition: pending_exit, then_branch: vec![leave], else_branch: Vec::new(), line, @@ -626,6 +660,104 @@ impl<'a> Lower<'a> { ]) } + fn loop_goto(&mut self, span: Span) -> Result, ParseError> { + let label = self.goto_target(span)?; + if self.label_in_loop(label) { + return Err(self.fail(span, "goto or label inside a loop is not in this slice")); + } + let Some(state) = self.state else { + return Err(self.fail(span, "goto leaves a loop without a dispatch state")); + }; + // The arm id does not exist yet. The negative value is the resolver + // label index, never 0 and never a positive arm id. Break skips this + // loop's tail and post; the dispatch loop applies the finished map. + let pending = self.pending_label_state(label, span)?; + let line = self.line(span); + self.pending_labels.push(label); + Ok(vec![ + set_slot(state, CoreExpr::Int(pending), line), + CoreStmt::Break { line }, + ]) + } + + fn pending_label_state(&self, label: usize, span: Span) -> Result { + let index = i64::try_from(label) + .ok() + .and_then(|index| index.checked_add(1)) + .and_then(i64::checked_neg); + index.ok_or_else(|| self.fail(span, "loop goto label index does not fit in a state")) + } + + fn label_in_loop(&self, label: usize) -> bool { + self.labels_in_loops.get(label).copied().unwrap_or(true) + } + + fn block_has_goto(&self, block: &Block, outward: bool) -> bool { + block + .stmts + .iter() + .any(|stmt| self.stmt_has_goto(stmt, outward)) + } + + fn stmt_has_goto(&self, stmt: &Stmt, outward: bool) -> bool { + match stmt { + Stmt::Goto { span, .. } => self.goto_is_outward(*span) == outward, + Stmt::Do { body, .. } + | Stmt::While { body, .. } + | Stmt::Repeat { body, .. } + | Stmt::NumericFor { body, .. } + | Stmt::GenericFor { body, .. } => self.block_has_goto(body, outward), + Stmt::If { + arms, else_body, .. + } => { + arms.iter() + .any(|arm| self.block_has_goto(&arm.body, outward)) + || else_body + .as_ref() + .is_some_and(|body| self.block_has_goto(body, outward)) + } + _ => false, + } + } + + fn goto_is_outward(&self, span: Span) -> bool { + self.goto_target(span) + .ok() + .is_some_and(|label| !self.label_in_loop(label)) + } + + fn resolve_pending_labels(&self, state: LocalSlot) -> Result { + let mut labels = self.pending_labels.clone(); + labels.sort_unstable(); + labels.dedup(); + let mut else_branch = Vec::new(); + for label in labels.into_iter().rev() { + let arm = self.label_state_id(label)?; + let span = self + .resolution + .labels + .get(label) + .map(|item| item.span) + .unwrap_or(Span::new(0, 0)); + let pending = self.pending_label_state(label, span)?; + else_branch = vec![CoreStmt::IfElse { + condition: CoreExpr::Eq( + Box::new(CoreExpr::Var(state)), + Box::new(CoreExpr::Int(pending)), + ), + then_branch: vec![set_slot(state, CoreExpr::Int(arm), 1)], + else_branch, + line: 1, + }]; + } + Ok(CoreStmt::IfElse { + condition: CoreExpr::Lt(Box::new(CoreExpr::Var(state)), Box::new(CoreExpr::Int(0))), + then_branch: else_branch, + else_branch: Vec::new(), + line: 1, + }) + } + fn holds_call( &mut self, index: LocalSlot, @@ -717,7 +849,14 @@ impl<'a> Lower<'a> { line: self.line(*span), }); } - Stmt::Goto { span, .. } | Stmt::Label { span, .. } => { + Stmt::Goto { span, .. } => { + if !in_loop { + return Err(self.fail(*span, "goto or label in a direct statement")); + } + out.extend(self.loop_goto(*span)?); + return Ok((out, None)); + } + Stmt::Label { span, .. } => { return Err(self.fail(*span, "goto or label in a direct statement")); } Stmt::While { cond, body, span } => { @@ -1259,6 +1398,51 @@ fn contains_label(block: &Block) -> bool { block.stmts.iter().any(stmt_contains_label) } +fn labels_inside_loops(chunk: &Chunk, resolution: &Resolution) -> Vec { + let mut inside = vec![false; resolution.labels.len()]; + mark_labels_in_loops(&chunk.body, false, resolution, &mut inside); + inside +} + +fn mark_labels_in_loops( + block: &Block, + in_loop: bool, + resolution: &Resolution, + inside: &mut [bool], +) { + for stmt in &block.stmts { + match stmt { + Stmt::Label { name, .. } if in_loop => { + if let Some(index) = resolution + .labels + .iter() + .position(|label| label.span == name.span) + { + inside[index] = true; + } + } + Stmt::Do { body, .. } => mark_labels_in_loops(body, in_loop, resolution, inside), + Stmt::While { body, .. } | Stmt::Repeat { body, .. } => { + mark_labels_in_loops(body, true, resolution, inside); + } + Stmt::NumericFor { body, .. } | Stmt::GenericFor { body, .. } => { + mark_labels_in_loops(body, true, resolution, inside); + } + Stmt::If { + arms, else_body, .. + } => { + for arm in arms { + mark_labels_in_loops(&arm.body, in_loop, resolution, inside); + } + if let Some(body) = else_body { + mark_labels_in_loops(body, in_loop, resolution, inside); + } + } + _ => {} + } + } +} + fn stmt_contains_label(stmt: &Stmt) -> bool { match stmt { Stmt::Label { .. } => true, diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index bf2076a..cc11c9b 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -2907,3 +2907,304 @@ fn return_inside_dispatch_if_arm_is_not_replaced_by_the_following_goto() { let miss_state = assert_one_dispatch_and_result(&miss); assert_eq!(source_while_count(&miss.stmts, Some(miss_state)), 1); } + +// 2100 is n=2, body=1, and neither the arm tail nor the wrong label. +// 2110 would be the tail after the while. 2101 would land on ::wrong::. +// 4411 is the miss: four bodies, the tail, and the wrong label on the way +// to ::right::. Skipping that tail is 4401. +const WHILE_OUTWARD_GOTO_HIT: &str = "\ +local n = 0 +local body = 0 +local tail = 0 +local wrong = 0 +while n < 4 do + n = n + 1 + do + if n == 2 then + goto right + end + end + body = body + 1 +end +tail = 1 +::wrong:: +wrong = 1 +::right:: +return n * 1000 + body * 100 + tail * 10 + wrong +"; + +const WHILE_OUTWARD_GOTO_MISS: &str = "\ +local n = 0 +local body = 0 +local tail = 0 +local wrong = 0 +while n < 4 do + n = n + 1 + do + if n == 9 then + goto right + end + end + body = body + 1 +end +tail = 1 +::wrong:: +wrong = 1 +::right:: +return n * 1000 + body * 100 + tail * 10 + wrong +"; + +#[test] +fn loop_outward_goto_while_hits_and_a_miss_falls_through() { + expect_number("while_outward_goto_hit", WHILE_OUTWARD_GOTO_HIT, 2100.0); + expect_number("while_outward_goto_miss", WHILE_OUTWARD_GOTO_MISS, 4411.0); + let hit = lowered(WHILE_OUTWARD_GOTO_HIT); + let state = assert_one_dispatch_and_result(&hit); + assert_eq!( + source_while_count(&hit.stmts, Some(state)), + 1, + "outward goto copied the while" + ); + assert_eq!(dispatch_while_count(&hit.stmts, state), 1); + let miss = lowered(WHILE_OUTWARD_GOTO_MISS); + let miss_state = assert_one_dispatch_and_result(&miss); + assert_eq!(source_while_count(&miss.stmts, Some(miss_state)), 1); +} + +// 10 is the first body, with until false and the arm tail both skipped. +// until false would exhaust fuel if the post ran. 11 is the arm tail. +// 21 is two finished trips and the tail; leaving after one trip is 11 or 10. +const REPEAT_OUTWARD_GOTO_HIT: &str = "\ +local n = 0 +local tail = 0 +repeat + n = n + 1 + if n == 1 then + goto out + end + n = n + 100 +until false +tail = 1 +::out:: +return n * 10 + tail +"; + +const REPEAT_OUTWARD_GOTO_MISS: &str = "\ +local n = 0 +local tail = 0 +repeat + n = n + 1 + if n == 9 then + goto out + end +until n == 2 +tail = 1 +::out:: +return n * 10 + tail +"; + +#[test] +fn loop_outward_goto_repeat_skips_until_and_a_miss_stops_on_until() { + expect_number("repeat_outward_goto_hit", REPEAT_OUTWARD_GOTO_HIT, 10.0); + expect_number("repeat_outward_goto_miss", REPEAT_OUTWARD_GOTO_MISS, 21.0); + let hit = lowered(REPEAT_OUTWARD_GOTO_HIT); + assert_one_dispatch_and_result(&hit); + assert_repeat_fors(&hit, 1); + let miss = lowered(REPEAT_OUTWARD_GOTO_MISS); + assert_one_dispatch_and_result(&miss); + assert_repeat_fors(&miss, 1); +} + +// 10 is s=1 and the arm tail skipped. 11 is that tail. 101 is 1+2+3+4 and +// the tail. The hidden step is not a guest write, so 10 does not show +// whether the post ran before the for was left. The body Break is that +// evidence: Continue would run the post and then the next body. +const NUMERIC_OUTWARD_GOTO_HIT: &str = "\ +local s = 0 +local tail = 0 +for i = 1, 4 do + s = s + i + if i == 1 then + goto out + end + s = s + 100 +end +tail = 1 +::out:: +return s * 10 + tail +"; + +const NUMERIC_OUTWARD_GOTO_MISS: &str = "\ +local s = 0 +local tail = 0 +for i = 1, 4 do + s = s + i + if i == 9 then + goto out + end +end +tail = 1 +::out:: +return s * 10 + tail +"; + +#[test] +fn loop_outward_goto_numeric_for_skips_the_step_and_a_miss_sums() { + expect_numeric("numeric_outward_goto_hit", NUMERIC_OUTWARD_GOTO_HIT, 10.0); + expect_numeric( + "numeric_outward_goto_miss", + NUMERIC_OUTWARD_GOTO_MISS, + 101.0, + ); + let hit = lowered_numeric(NUMERIC_OUTWARD_GOTO_HIT); + assert_one_dispatch_and_result(&hit); + assert_eq!( + numeric_for_count(&hit), + 1, + "outward goto copied the numeric for" + ); + assert_numeric_goto_breaks_before_post(&hit); + let miss = lowered_numeric(NUMERIC_OUTWARD_GOTO_MISS); + assert_one_dispatch_and_result(&miss); + assert_eq!(numeric_for_count(&miss), 1); +} + +fn assert_numeric_goto_breaks_before_post(ir: &FrontendIr) { + let mut fors = 0; + let mut breaks_in_body = 0; + let mut continues_in_body = 0; + let mut post_adds = 0; + walk_stmts(&ir.stmts, &mut |stmt| { + let Stmt::For { + init, post, body, .. + } = stmt + else { + return; + }; + if !matches!(init.as_ref(), Stmt::Noop { .. }) { + return; + } + fors += 1; + if matches!( + post.as_ref(), + Stmt::Assign { expr, .. } if matches!(expr, Expr::Add(_, _)) + ) { + post_adds += 1; + } + fn walk_body(stmts: &[Stmt], breaks: &mut usize, continues: &mut usize) { + for stmt in stmts { + match stmt { + Stmt::Break { .. } => *breaks += 1, + Stmt::Continue { .. } => *continues += 1, + Stmt::IfElse { + then_branch, + else_branch, + .. + } => { + walk_body(then_branch, breaks, continues); + walk_body(else_branch, breaks, continues); + } + Stmt::While { body, .. } => walk_body(body, breaks, continues), + Stmt::For { body, .. } => walk_body(body, breaks, continues), + _ => {} + } + } + } + walk_body(body, &mut breaks_in_body, &mut continues_in_body); + }); + assert_eq!(fors, 1, "numeric for was copied or missing"); + assert_eq!( + post_adds, 1, + "the step post must stay on the for, not move onto the goto path" + ); + assert_eq!( + breaks_in_body, 1, + "outward goto must Break this for so its post does not run" + ); + assert_eq!( + continues_in_body, 0, + "Continue inside the numeric for would run the step post" + ); +} + +// 1 is the first numeric body. 101 adds the inner tail, 1101 the repeat +// tail, 11101 the while tail, 111101 the arm statement after the while. +// until false exhausts fuel if an inner exit still runs the repeat post. +const NESTED_OUTWARD_GOTO: &str = "\ +local acc = 0 +local outer = 0 +while outer < 3 do + outer = outer + 1 + repeat + for i = 1, 3 do + acc = acc + 1 + do + if outer == 1 then + if i == 1 then + goto out + end + end + end + acc = acc + 100 + end + acc = acc + 1000 + until false + acc = acc + 10000 +end +acc = acc + 100000 +::out:: +return acc +"; + +#[test] +fn loop_outward_goto_nested_skips_every_enclosing_tail() { + expect_numeric("nested_outward_goto", NESTED_OUTWARD_GOTO, 1.0); + let ir = lowered_numeric(NESTED_OUTWARD_GOTO); + let state = assert_one_dispatch_and_result(&ir); + assert_eq!( + source_while_count(&ir.stmts, Some(state)), + 1, + "nested outward goto copied the while" + ); + assert_eq!( + repeat_flag_bindings(&ir).len(), + 1, + "nested outward goto copied the repeat" + ); + assert_eq!( + numeric_for_count(&ir), + 1, + "nested outward goto copied the numeric for" + ); + assert_eq!(dispatch_while_count(&ir.stmts, state), 1); +} + +// 21 is one re-entry of the arm that owns the while, then the trailing +// write. 11 is a same-arm comparison that breaks the while and lets that +// write run without re-entering. 20 re-enters but then skips the write. +const SAME_ARM_BACKWARD_GOTO: &str = "\ +local n = 0 +local seen = 0 +local after = 0 +::again:: +seen = seen + 1 +while n < 1 do + n = n + 1 + goto again +end +after = 1 +return seen * 10 + after +"; + +#[test] +fn loop_outward_goto_same_arm_backward_reenters() { + expect_number("same_arm_backward_goto", SAME_ARM_BACKWARD_GOTO, 21.0); + let ir = lowered(SAME_ARM_BACKWARD_GOTO); + let state = assert_one_dispatch_and_result(&ir); + assert_eq!( + source_while_count(&ir.stmts, Some(state)), + 1, + "same-arm goto copied the while" + ); + assert_eq!(dispatch_while_count(&ir.stmts, state), 1); +} From ece3aea78330fb0550f4733cbb713f4b4e724218 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 02:39:09 +0800 Subject: [PATCH 042/225] feat(lua): follow a strong metatable edge during collection --- src/frontends/lua/heap/table.rs | 74 +++++++ tests/luajit_heap_runtime/candidate.rs | 91 +++++++- .../value_boundary_tests.rs | 205 ++++++++++++++++++ 3 files changed, 365 insertions(+), 5 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index f23fd99..7a87761 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -166,6 +166,8 @@ struct Slot { /// array so a field can read it back while the node is live. It contains /// identity only, not object edges, and does not participate in marking. carrier: Option>>, + /// Optional metatable. Not a field key and not an `edges` record. + metatable: Option<(u32, u32)>, } struct Edge { @@ -196,6 +198,11 @@ struct Frame { /// and it is zero when every live node is marked. Adding those fields is not /// a total GC cost. /// +/// A metatable is not in that edge vector. `metatable_edge_checks` counts +/// stored metatable refs followed from marked nodes. A collect with none +/// stored does not read those slots, so the three field-edge counters stay +/// the same as a heap that never had a metatable. +/// /// `index_slot_checks` is the one counts-to-offsets walk over index scratch. /// Its length is the node-slot vector. It is not a heap-node walk. Heap node /// walks are `node_slot_visits`. Root-vector walks are `root_slot_visits`. @@ -217,6 +224,14 @@ pub struct ScanMeter { pub index_slot_checks: u64, pub outgoing_edge_checks: u64, pub sweep_edge_checks: u64, + /// Stored metatable references followed from a marked node. + /// + /// A metatable is an optional per-slot reference, not a field-edge record + /// and not an integer key. It is not included in `index_edge_checks`, + /// `outgoing_edge_checks`, or `sweep_edge_checks`. A heap with no stored + /// metatable reference does not read this path, so those collects add zero + /// and leave the field-edge counts unchanged. + pub metatable_edge_checks: u64, pub token_slot_checks: u64, pub token_closes: u64, /// Node-slot reads and writes during mark reset, root liveness, outgoing @@ -299,6 +314,8 @@ pub struct LuaHeap { slots: Vec, free_list: Vec, edges: Vec, + /// Stored metatable refs. Zero means mark does not read metatable slots. + metatable_edges: u32, roots: Vec>, frames: Vec, next_frame_generation: u32, @@ -320,6 +337,7 @@ impl LuaHeap { slots: Vec::new(), free_list: Vec::new(), edges: Vec::new(), + metatable_edges: 0, roots: Vec::new(), frames: Vec::new(), next_frame_generation: 1, @@ -350,6 +368,7 @@ impl LuaHeap { slot.state = SlotState::Live { marked: false }; slot.token = None; slot.carrier = None; + slot.metatable = None; return Ok(TableRef::table(self.domain, index, slot.generation)); } if self.slots.len() >= self.limits.nodes as usize { @@ -364,6 +383,7 @@ impl LuaHeap { state: SlotState::Live { marked: false }, token: None, carrier: None, + metatable: None, }); self.note_node_peak(); Ok(TableRef::table(self.domain, index, 1)) @@ -484,6 +504,39 @@ impl LuaHeap { })) } + /// Sets or clears the metatable ref. A table target is not encoded as a + /// field key. Replacing one ref does not allocate another record. This + /// does not reject a cycle. + pub fn set_metatable( + &mut self, + owner: TableRef, + mt: Option, + ) -> Result<(), HeapError> { + self.require_live(owner)?; + if let Some(target) = mt { + self.require_live(target)?; + } + let had = self.slots[owner.slot() as usize].metatable.is_some(); + let next = mt.map(|target| (target.slot(), target.generation())); + if had != next.is_some() { + if next.is_some() { + self.metatable_edges = self.metatable_edges.saturating_add(1); + } else { + self.metatable_edges = self.metatable_edges.saturating_sub(1); + } + } + self.slots[owner.slot() as usize].metatable = next; + Ok(()) + } + + /// Reads the stored metatable ref. The caller loads the canonical carrier. + pub fn metatable(&self, owner: TableRef) -> Result, HeapError> { + self.require_live(owner)?; + Ok(self.slots[owner.slot() as usize] + .metatable + .map(|(slot, generation)| TableRef::table(self.domain, slot, generation))) + } + /// Clones the slot's issued carrier for a field read. This does not add a root. pub fn issued_value(&self, table: TableRef) -> Result { self.require_live(table)?; @@ -751,6 +804,7 @@ impl LuaHeap { self.mark_slot(handle.slot(), &mut work); } } + let follow_metatables = self.metatable_edges > 0; while let Some(slot) = work.pop() { let start = index.offsets[slot as usize] as usize; let end = index.offsets[slot as usize + 1] as usize; @@ -762,6 +816,23 @@ impl LuaHeap { self.mark_slot(to_slot, &mut work); } } + if follow_metatables { + self.follow_metatable(slot, &mut work); + } + } + } + + /// Follows one stored metatable ref. Absent refs are not edges and are + /// not counted. The caller skips this entirely when no ref is stored. + fn follow_metatable(&mut self, slot: u32, work: &mut Vec) { + let Some((to_slot, to_generation)) = self.slots[slot as usize].metatable else { + return; + }; + self.scan.metatable_edge_checks += 1; + self.scan.node_slot_visits += 1; + if self.slot_live(to_slot, to_generation) { + self.scan.node_slot_visits += 1; + self.mark_slot(to_slot, work); } } @@ -839,6 +910,9 @@ impl LuaHeap { } fn release_slot(&mut self, index: u32) { + if self.slots[index as usize].metatable.take().is_some() { + self.metatable_edges = self.metatable_edges.saturating_sub(1); + } let slot = &mut self.slots[index as usize]; slot.token = None; slot.carrier = None; diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 1f0f755..470e8aa 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -28,6 +28,8 @@ const ENTER_CALLEE: &str = "lua_internal::enter_callee_frame"; const ROOT_ISSUED: &str = "lua_internal::root_issued"; const SET_EDGE: &str = "lua_internal::set_edge"; const GET_EDGE: &str = "lua_internal::get_edge"; +const SET_METATABLE: &str = "lua_internal::set_metatable"; +const GET_METATABLE: &str = "lua_internal::get_metatable"; pub(super) const FINISH_RETURN: &str = "lua_internal::finish_return"; pub(super) const RETIRE_CALLEE: &str = "lua_internal::retire_callee"; pub(super) const RETIRE_CHUNK: &str = "lua_internal::retire_chunk"; @@ -109,6 +111,12 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { ), (SET_EDGE, vec!["from", "key", "to"], HostTypeSchema::Float), (GET_EDGE, vec!["table", "key"], HostTypeSchema::Unknown), + ( + SET_METATABLE, + vec!["owner", "metatable"], + HostTypeSchema::Float, + ), + (GET_METATABLE, vec!["owner"], HostTypeSchema::Unknown), ( FINISH_RETURN, vec!["values", "frame", "publish", "slots", "callee"], @@ -149,6 +157,8 @@ pub(super) fn register( Op::RootIssued, Op::SetEdge, Op::GetEdge, + Op::SetMetatable, + Op::GetMetatable, Op::FinishReturn, Op::RetireCallee, Op::RetireChunk, @@ -172,6 +182,8 @@ pub(super) fn register( Op::RootIssued => ROOT_ISSUED, Op::SetEdge => SET_EDGE, Op::GetEdge => GET_EDGE, + Op::SetMetatable => SET_METATABLE, + Op::GetMetatable => GET_METATABLE, Op::FinishReturn => FINISH_RETURN, Op::RetireCallee => RETIRE_CALLEE, Op::RetireChunk => RETIRE_CHUNK, @@ -205,6 +217,8 @@ enum Op { RootIssued, SetEdge, GetEdge, + SetMetatable, + GetMetatable, FinishReturn, RetireCallee, RetireChunk, @@ -380,6 +394,8 @@ impl HostOwnedFunction for Op { Self::RootIssued => root_issued(call)?, Self::SetEdge => set_edge(call)?, Self::GetEdge => get_edge(call)?, + Self::SetMetatable => set_metatable(call)?, + Self::GetMetatable => get_metatable(call)?, Self::FinishReturn => finish_return(call)?, Self::RetireCallee => retire_callee(call)?, Self::RetireChunk => retire_chunk(call)?, @@ -781,6 +797,49 @@ fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { .map_err(heap_error) } +fn set_metatable(call: &mut OwnedHostCall<'_>) -> Result { + let (owner, mt) = match call.args() { + [owner, mt] => (owner.clone(), mt.clone()), + _ => return Err(host_fault("invalid metatable assignment")), + }; + let owner = match classify(&mut call.vm().host_context(), &owner)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("metatable owner is not a table")), + }; + let mt = match &mt { + Value::Null => None, + other => match classify(&mut call.vm().host_context(), other)? { + heap::GuestClass::Table(table) => Some(table), + _ => return Err(host_fault("metatable target is not a table")), + }, + }; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.set_metatable(owner, mt) + }) + .map_err(heap_error)?; + Ok(Value::Float(0.0)) +} + +fn get_metatable(call: &mut OwnedHostCall<'_>) -> Result { + let owner = match call.args() { + [owner] => owner.clone(), + _ => return Err(host_fault("invalid metatable read")), + }; + let owner = match classify(&mut call.vm().host_context(), &owner)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("metatable owner is not a table")), + }; + let target = heap::with_heap(&mut call.vm().host_context(), |heap| heap.metatable(owner)) + .map_err(heap_error)?; + let Some(target) = target else { + return Ok(Value::Null); + }; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.issued_value(target) + }) + .map_err(heap_error) +} + fn release_result(call: &mut OwnedHostCall<'_>) -> Result { let (frame_token, slot) = match call.args() { [frame, slot] => (frame.clone(), float_u32(slot)?), @@ -838,10 +897,7 @@ fn note_collect( )) }) .map_err(heap_error)?; - let swept = heap::take_scan_meter(host) - .map_err(heap_error)? - .scratch - .dead_slots_pushed; + let meter = heap::take_scan_meter(host).map_err(heap_error)?; let witness = host .scope_state_mut::() .ok_or_else(|| host_fault("return witness disappeared"))?; @@ -849,10 +905,14 @@ fn note_collect( live_nodes: report.live_nodes, marked_nodes: report.marked_nodes, live_roots: report.live_roots, - swept, + swept: meter.scratch.dead_slots_pushed, returned_alive, discarded_alive, returned_edge, + metatable_edge_checks: meter.metatable_edge_checks, + index_edge_checks: meter.index_edge_checks, + outgoing_edge_checks: meter.outgoing_edge_checks, + sweep_edge_checks: meter.sweep_edge_checks, }); witness.issued_alive_at_collect.push(latest_alive); Ok(()) @@ -1641,6 +1701,22 @@ impl Lower<'_> { }); return self.call(COPY_FIELDS, vec![Expr::Var(slot)]); } + if name.is("setmetatable") + && let [owner, mt] = args.exprs.as_slice() + { + let owner = self.expr(owner)?; + let mt = match mt { + ast::Expr::Nil { .. } => Expr::Null, + other => self.expr(other)?, + }; + return self.call(SET_METATABLE, vec![owner, mt]); + } + if name.is("getmetatable") + && let [owner] = args.exprs.as_slice() + { + let owner = self.expr(owner)?; + return self.call(GET_METATABLE, vec![owner]); + } if name.is("external_shape") && args.exprs.is_empty() { return self.call(EXTERNAL_SHAPE, vec![]); } @@ -1935,6 +2011,11 @@ pub(super) struct CollectNote { pub returned_alive: bool, pub discarded_alive: bool, pub returned_edge: EdgeView, + /// Metatable references followed from marked nodes. Not a field-edge count. + pub metatable_edge_checks: u64, + pub index_edge_checks: u64, + pub outgoing_edge_checks: u64, + pub sweep_edge_checks: u64, } #[derive(Clone, Debug)] diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 48bfd04..4fac3f3 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -676,3 +676,208 @@ fn reset_drops_the_old_carrier_even_when_fields_match_again() { assert!(matches!(class_of(vm, &fresh), heap::GuestClass::Table(_))); }); } + +// IR and scope for the metatable graph. `make` publishes only `owner` into the +// caller root frame, then retire drops the callee frame. `mt` and `payload` +// were assigned nil in that frame, so they are not chunk live locals. `orphan` +// drops its frame before the chunk collect, so the self-cycle has no root. +// `collectgarbage` gathers `live_locals` and `active_temps` only. The read-back +// names are removed from `live_locals` by `= nil` before detach and the second +// collect. `host_call` argument slots and `field_read`'s base slot are not +// added to those lists, so they are not safepoint roots. `observe_table` +// stores a `TableRef` and a Core token, not a VM `Value`. `read_mt.__index` is +// the existing physical field read, not `__index` dispatch. +fn strong_metatable_source(second_collect: bool) -> String { + let tail = if second_collect { + "collectgarbage(\"collect\")\nlocal unrelated_ok = observe_table(unrelated, 0)\nreturn mt_same\n" + } else { + "return type(getmetatable(owner))\n" + }; + let source = r#" +local function orphan() + local cycle = {} + observe_table(cycle, 0) + cycle.self = cycle + cycle = nil +end +orphan() +local function make() + local owner = {} + local mt = {} + local payload = {} + observe_table(mt, 0) + observe_table(payload, 0) + mt.__index = payload + setmetatable(owner, mt) + mt = nil + payload = nil + return owner +end +local owner = make() +local unrelated = {} +collectgarbage("collect") +local read_mt = getmetatable(owner) +local mt_same = observe_table(read_mt, 0) +local read_payload = read_mt.__index +local payload_same = observe_table(read_payload, 0) +read_mt = nil +read_payload = nil +setmetatable(owner, nil) +"#; + format!("{source}{tail}") +} + +fn first_collect_matrix(note: &candidate::CollectNote) -> (u64, u64, u64, u64, u32, u32, u64) { + ( + note.metatable_edge_checks, + note.index_edge_checks, + note.outgoing_edge_checks, + note.sweep_edge_checks, + note.marked_nodes, + note.live_nodes, + note.swept, + ) +} + +#[test] +fn lua_candidate_reads_metatable_identity_after_collect_then_reclaims_on_detach() { + let source = strong_metatable_source(true); + let mut vm = candidate(&source); + let status = vm.run(); + let stack = vm.stack().to_vec(); + let mut host = vm.host_context(); + let witness = host.scope_state::().unwrap(); + let tables = host.scope_state::>().unwrap(); + assert!( + witness.callee_left, + "make returned through the real callee frame" + ); + assert_eq!( + witness.discarded, + Some(tables[0].table), + "the self-cycle was witnessed" + ); + assert!(!witness.collects.is_empty(), "collection did not run"); + let first = &witness.collects[0]; + assert!(!first.discarded_alive && first.returned_alive); + assert_eq!(first.returned_edge, candidate::EdgeView::Absent); + // Field edges are cycle.self and mt.__index. The metatable ref is not one + // of them: index is 2 passes x 2 field edges, outgoing follows only the + // marked mt field, sweep filters both because the cycle died. The + // metatable follow is the separate 1. + assert_eq!( + first_collect_matrix(first), + (1, 4, 1, 2, 4, 4, 1), + "metatable follow must stay out of the field-edge counters" + ); + assert_eq!( + status.expect("read the metatable after a real collection"), + VmStatus::Halted + ); + assert_eq!(tables.len(), 6); + let cycle = tables[0]; + let mt = tables[1]; + let payload = tables[2]; + assert_eq!( + tables[3], mt, + "getmetatable returns the same slot, generation and token" + ); + assert_eq!( + tables[4], payload, + "the payload identity is the physical __index field" + ); + assert_eq!(stack, [Value::Bool(true)]); + + assert_eq!(witness.collects.len(), 2); + let second = &witness.collects[1]; + assert!( + second.returned_alive, + "owner stays rooted across the reclaim collect" + ); + assert_eq!(second.returned_edge, candidate::EdgeView::Absent); + // Detach removed the only metatable ref. One field edge remains, and the + // marked nodes do not own it, so outgoing is 0 and the metatable counter + // is 0. Sweep still filters that field edge. + assert_eq!( + first_collect_matrix(second), + (0, 2, 0, 1, 2, 2, 2), + "detach does not add a field edge, and the second collect reclaims both targets" + ); + let key = heap::LuaTableResource::key(); + assert!( + host.borrow_resource_with_key::(cycle.token, &key) + .is_err() + ); + assert!( + host.borrow_resource_with_key::(mt.token, &key) + .is_err() + ); + assert!( + host.borrow_resource_with_key::(payload.token, &key) + .is_err() + ); + assert!( + host.borrow_resource_with_key::(tables[5].token, &key) + .is_ok() + ); + assert_eq!(host.resource_count(), 2); + assert_eq!(heap::stats(&mut host).unwrap().live_roots, 0); +} + +#[test] +fn lua_candidate_omitting_the_collect_after_detach_keeps_the_metatable_target() { + let source = strong_metatable_source(false); + let mut vm = candidate(&source); + let status = vm.run(); + let stack = vm.stack().to_vec(); + let mut host = vm.host_context(); + let witness = host.scope_state::().unwrap(); + let tables = host.scope_state::>().unwrap(); + assert_eq!( + witness.collects.len(), + 1, + "the omitted collect must not run" + ); + let first = &witness.collects[0]; + assert_eq!( + first_collect_matrix(first), + (1, 4, 1, 2, 4, 4, 1), + "the kept graph is the same one the reclaim test collects a second time" + ); + assert_eq!( + status.expect("detach without a second collection"), + VmStatus::Halted + ); + assert_eq!(stack, [Value::string("nil")]); + assert_eq!(tables.len(), 5); + let cycle = tables[0]; + let mt = tables[1]; + let payload = tables[2]; + assert_eq!(tables[3], mt); + assert_eq!(tables[4], payload); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(mt.table))).unwrap(), + "removing the edge does not release the metatable node" + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(payload.table))).unwrap(), + "removing the edge does not release the payload node" + ); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(cycle.table))).unwrap()); + let key = heap::LuaTableResource::key(); + assert!( + host.borrow_resource_with_key::(mt.token, &key) + .is_ok() + ); + assert!( + host.borrow_resource_with_key::(payload.token, &key) + .is_ok() + ); + assert!( + host.borrow_resource_with_key::(cycle.token, &key) + .is_err() + ); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, 1); + assert_eq!(stats.live_nodes, 4); +} From 9ed5562609323ad6019b1e9911b8a2f5a4a3401b Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 04:00:44 +0800 Subject: [PATCH 043/225] test(lua): execute combined outward gotos beside return and chunk goto One scalar chunk selects each outward target, a repeated target, a cross-arm backward jump, an in-loop return, and a chunk goto. An in-loop label remains outside the private slice. --- tests/compiler/compiler_lua_control_tests.rs | 174 +++++++++++++++++++ 1 file changed, 174 insertions(+) diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index cc11c9b..65bdd52 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -3208,3 +3208,177 @@ fn loop_outward_goto_same_arm_backward_reenters() { ); assert_eq!(dispatch_while_count(&ir.stmts, state), 1); } + +// One chunk, selected by pick. Observation is the chunk return, not IR shape. +// 1000 is the back arm's chunk goto to done: trace 1, no loop, no tail. +// 101010 is the first goto left: one body, the left mark, tail skipped. +// 201010 is the other outward target, right, with that mark instead of left. +// 103010 is the second source goto to left; the +2 is that source's own write. +// 2010 is the cross-arm jump back to ::back::. The second visit sees trace 2 +// and leaves by the chunk goto there. One visit is 1010. Running the mid tail +// or falling into left is 102011 or 101011. +// 61 is the loop return. A later goto replacing it is a packed value, not 61. +// 21021 is that return missed: two body writes, the tail, then the chunk goto +// skips left and right. Falling into left is 121021. +fn outward_combination(pick: i64) -> String { + format!( + "\ +local pick = {pick} +local n = 0 +local trace = 0 +local tail = 0 +::back:: +trace = trace + 1 +if trace == 2 then + goto done +end +if pick == 1 then + goto done +end +goto mid +::mid:: +if pick == 2 then + while n < 4 do + n = n + 1 + if n == 1 then + goto left + end + trace = trace + 10 + end + tail = tail + 1 +end +if pick == 4 then + while n < 4 do + n = n + 1 + if n == 1 then + trace = trace + 2 + goto left + end + trace = trace + 10 + end + tail = tail + 1 +end +if pick == 3 then + while n < 4 do + n = n + 1 + if n == 1 then + goto right + end + trace = trace + 10 + end + tail = tail + 1 +end +if pick == 5 then + while n < 1 do + n = n + 1 + if n == 1 then + goto back + end + trace = trace + 10 + end + tail = tail + 1 +end +if pick == 6 then + while n < 4 do + n = n + 1 + if n == 1 then + return n + 60 + end + trace = trace + 10 + end + tail = tail + 1 + goto done +end +if pick == 7 then + while n < 2 do + n = n + 1 + if n == 9 then + return n + 60 + end + trace = trace + 10 + end + tail = tail + 1 + goto done +end +::left:: +trace = trace + 100 +goto done +::right:: +trace = trace + 200 +::done:: +return trace * 1000 + n * 10 + tail +" + ) +} + +#[test] +fn loop_outward_combination_selects_each_scalar_path() { + expect_number("outward_combo_chunk_goto", &outward_combination(1), 1000.0); + expect_number("outward_combo_left", &outward_combination(2), 101010.0); + expect_number("outward_combo_right", &outward_combination(3), 201010.0); + expect_number( + "outward_combo_left_again", + &outward_combination(4), + 103010.0, + ); + expect_number("outward_combo_back", &outward_combination(5), 2010.0); + expect_number("outward_combo_return", &outward_combination(6), 61.0); + expect_number( + "outward_combo_return_miss", + &outward_combination(7), + 21021.0, + ); +} + +// Legal LuaJIT: the label and its goto share the loop block and enter no +// local. The private slice still refuses an in-loop label. This records that +// current boundary. jump_into_local_is_a_static_rejection already covers the +// resolver's refusal to enter a local, so this test does not repeat it. +const IN_LOOP_LABEL: &str = "\ +local n = 0 +while n < 2 do + n = n + 1 + if n == 1 then + goto inside + end + ::inside:: + n = n + 10 +end +return n +"; + +#[test] +fn in_loop_label_fails_closed_outside_the_private_slice() { + let chunk = parser::parse_chunk(IN_LOOP_LABEL.as_bytes()).expect("parse in-loop label"); + let resolution = resolve::resolve(&chunk); + assert!( + resolution.errors.is_empty(), + "an in-loop label that enters no local is legal: {:?}", + resolution.errors + ); + let error = control::lower_source(IN_LOOP_LABEL).expect_err("private slice"); + let text = error.to_string(); + assert!( + text.contains("not in this slice"), + "in-loop label must fail closed at the private slice, not as another class: {text}" + ); + assert!( + !text.contains("jump into the scope of local"), + "this source does not enter a local: {text}" + ); + let path = write_fixture("in_loop_label", IN_LOOP_LABEL); + let compiled = compile_source_file_with_options(&path, candidate_options()); + assert!( + compiled.is_err(), + "in-loop label must not produce a program" + ); + let Ok(oracle) = std::env::var("LUAJIT_ORACLE") else { + eprintln!("LUAJIT_ORACLE is unset; in-loop label acceptance is not a differential result"); + return; + }; + let observed = oracle_return(&oracle, &path); + assert_eq!( + observed, 11.0, + "LuaJIT accepts the in-loop label; candidate refusal is the private slice" + ); +} From 6b8c984cef4d647791f832286c19ed6b4539594c Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 04:52:14 +0800 Subject: [PATCH 044/225] feat(lua): lower same-loop gotos within Core iterations --- src/frontends/lua/control.rs | 454 +++++++++++-------- tests/compiler/compiler_lua_control_tests.rs | 177 ++++++-- 2 files changed, 398 insertions(+), 233 deletions(-) diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs index dfb49d8..0cdbcac 100644 --- a/src/frontends/lua/control.rs +++ b/src/frontends/lua/control.rs @@ -5,18 +5,18 @@ //! not a file entry and not a fallback to the line lowerer. //! //! A chunk with no goto and no early return is emitted as ordinary -//! statements, including a source `while` or `repeat`. Any goto, or a return -//! that is not the chunk tail, becomes a private integer state loop. Each basic -//! block is one state. A transfer assigns that state and `Continue`s the dispatch -//! loop, so that Continue is emitted only in the dispatch arm, never inside a -//! nested source loop. `break` and `continue` inside a source loop stay Core -//! statements of that loop. A `return` in `while`, `repeat`, or numeric `for` -//! writes the one result, stores the exit state, and `Break`s that source loop -//! so its post does not run. After every loop that can return or jump outward, -//! an exit-state guard `Break`s an enclosing source loop, or `Continue`s the +//! statements, including a source `while` or `repeat`. Gotos and early returns +//! use private integer state to dispatch basic blocks. A same-loop goto uses a +//! separate dispatcher for the current iteration, reset at the start of each +//! iteration. The source condition and post stay outside that dispatcher. +//! A source `continue` ends the iteration dispatcher normally, reaching the +//! post or next condition; `break` also leaves the source loop. Loops without +//! same-loop gotos need no iteration dispatcher. +//! A `return` in `while`, `repeat`, or numeric `for` writes the one result, +//! stores the exit state, and `Break`s the nearest Core loop. Exit-state guards +//! then `Break` through enclosing loops so their posts do not run, or `Continue` the //! dispatch loop once the source loop is already in the dispatch arm. A later -//! arm transfer therefore cannot overwrite the exit state. A loop that cannot -//! return and has no outward goto is unchanged. A `goto` in `while`, `repeat`, +//! arm transfer therefore cannot overwrite the exit state. A `goto` in `while`, `repeat`, //! or numeric `for` may target a label the resolver has already accepted outside //! source loop. That goto stores a negative state — the resolver label index, //! not an arm id — and `Break`s, so this loop's tail and post do not run. @@ -27,11 +27,11 @@ //! negative carrier is required because the loop body is lowered before arm //! ids exist. Storing the positive id inside the loop would compare equal to //! the current arm when the label is that arm's own entry, and the statements -//! after the loop would overwrite the jump. A label inside a loop, or a goto -//! whose target is still inside a loop, is not in this slice. A source -//! `repeat` is one Core `for`, not a copied body. Its private bool starts -//! true, so the body runs before `until`. The -//! `for` post stores whether another round is required. Fallthrough and +//! after the loop would overwrite the jump. A goto targeting a different +//! source loop, or a target label inside an `if` branch of the same region, +//! remains outside this slice. A source `repeat` is one Core `for`, not a +//! copied body. Its private bool starts true, so the body runs before `until`. +//! The `for` post stores whether another round is required. Fallthrough and //! `continue` both reach that post; `break` skips it and leaves this `for`, //! not an outer dispatch loop. `until` is placed once and can read the //! same-round body locals. In this numeric/bool slice only `false` is falsy: @@ -67,6 +67,7 @@ use vm::{ const STATE_SLOT: &str = "$lua_dispatch_state"; const RESULT_SLOT: &str = "$lua_return_value"; const EXIT_STATE: i64 = 0; +const ITERATION_BREAK: i64 = -1; pub(super) const NUMERIC_FOR_HOLDS: &str = "lua_control::numeric_for_holds"; @@ -88,7 +89,7 @@ pub(super) fn lower_source_with( source, &resolution, holds, - labels_inside_loops(&chunk, &resolution), + label_loop_owners(&chunk, &resolution), ); let stmts = if needs_dispatch(&chunk) { lower.lower_dispatch(&chunk)? @@ -112,10 +113,16 @@ struct Lower<'a> { nfor_slots: Vec, for_indexes: Vec, holds: Option<&'a HostCallResolver<'a>>, - labels_in_loops: Vec, + label_loops: Vec>, pending_labels: Vec, } +#[derive(Clone, Copy)] +struct Iteration { + owner: Span, + state: LocalSlot, +} + struct BlockBuf { finished: Vec, current: Vec, @@ -158,7 +165,7 @@ impl<'a> Lower<'a> { source: &'a str, resolution: &'a Resolution, holds: Option<&'a HostCallResolver<'a>>, - labels_in_loops: Vec, + label_loops: Vec>, ) -> Self { let slots = vec![None; resolution.bindings.len()]; let label_state = vec![None; resolution.labels.len()]; @@ -176,7 +183,7 @@ impl<'a> Lower<'a> { nfor_slots: Vec::new(), for_indexes: Vec::new(), holds, - labels_in_loops, + label_loops, pending_labels: Vec::new(), } } @@ -213,24 +220,8 @@ impl<'a> Lower<'a> { self.result = Some(result); } let mut blocks = BlockBuf::new(); - self.walk_list(&chunk.body.stmts, &mut blocks)?; - blocks.finish(); - if blocks.finished.is_empty() { - return Err(self.fail_line(1, "empty dispatch chunk")); - } - for (index, block) in blocks.finished.iter().enumerate() { - if let Some(label) = block.label { - self.label_state[label] = Some(self.state_id_of(index)); - } - } - let mut arms = Vec::with_capacity(blocks.finished.len()); - for (index, block) in blocks.finished.iter().enumerate() { - let state_id = index as i64 + 1; - let mut body = self.emit_items(&block.items)?; - body.extend(self.emit_exit(&block.exit, index, blocks.finished.len())?); - arms.push((state_id, body)); - } - let chain = dispatch_chain(state, arms); + self.walk_list(&chunk.body.stmts, &mut blocks, None)?; + let chain = self.emit_dispatch(blocks, state)?; // An outward goto carries a negative label index until this point. // Arm ids exist only after the walk, so the rewrite stays here, on // the one dispatch loop, and only when a loop goto needs it. @@ -253,14 +244,7 @@ impl<'a> Lower<'a> { if let Some(result) = self.result { root.push(let_expr(result, CoreExpr::Null, 1)); } - root.push(CoreStmt::While { - condition: CoreExpr::Not(Box::new(CoreExpr::Eq( - Box::new(CoreExpr::Var(state)), - Box::new(CoreExpr::Int(EXIT_STATE)), - ))), - body: dispatch_body, - line: 1, - }); + root.push(dispatch_loop(state, dispatch_body, 1)); if let Some(result) = self.result { root.push(CoreStmt::Expr { expr: CoreExpr::Var(result), @@ -274,38 +258,60 @@ impl<'a> Lower<'a> { i64::try_from(block_index).expect("block index") + 1 } - fn walk_list(&mut self, stmts: &[Stmt], blocks: &mut BlockBuf) -> Result<(), ParseError> { + fn walk_list( + &mut self, + stmts: &[Stmt], + blocks: &mut BlockBuf, + iteration: Option, + ) -> Result<(), ParseError> { for stmt in stmts { match stmt { Stmt::Empty { .. } => {} - Stmt::Do { body, .. } => self.walk_list(&body.stmts, blocks)?, + Stmt::Do { body, .. } => self.walk_list(&body.stmts, blocks, iteration)?, Stmt::Label { name, .. } => { let index = self.label_index(name)?; blocks.split_label(index); } Stmt::Goto { span, .. } => { let label = self.goto_target(*span)?; - blocks.flush(Exit::Goto { - label, - line: self.line(*span), - }); + if self.label_loops[label] == iteration.map(|iteration| iteration.owner) { + blocks.flush(Exit::Goto { + label, + line: self.line(*span), + }); + } else { + self.append_items(stmt, &mut blocks.current, iteration)?; + } } - Stmt::Return { values, span } => { + Stmt::Return { values, span } if iteration.is_none() => { blocks.flush(Exit::Return { expr: self.one_value(values, *span)?, line: self.line(*span), }); } - Stmt::While { cond, body, span } => { - for stmt in self.while_stmt(cond, body, *span, false)? { - blocks.current.push(Item::Core(stmt)); - } - } - Stmt::Repeat { body, until, span } => { - for stmt in self.repeat_stmt(body, until, *span, false)? { - blocks.current.push(Item::Core(stmt)); - } - } + other => self.append_items(other, &mut blocks.current, iteration)?, + } + } + Ok(()) + } + + fn append_items( + &mut self, + stmt: &Stmt, + items: &mut Vec, + iteration: Option, + ) -> Result<(), ParseError> { + // Inside an iteration dispatcher, a nested source loop's exit guard + // breaks that dispatcher before the outer source loop can unwind. + let enclosing_loop = iteration.is_some(); + let cores = match (stmt, iteration) { + (Stmt::While { cond, body, span }, _) => { + self.while_stmt(cond, body, *span, enclosing_loop)? + } + (Stmt::Repeat { body, until, span }, _) => { + self.repeat_stmt(body, until, *span, enclosing_loop)? + } + ( Stmt::NumericFor { name, start, @@ -313,20 +319,47 @@ impl<'a> Lower<'a> { step, body, span, - } => { - let stmts = - self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)?; - for stmt in self.with_return_guard(stmts, body, self.line(*span), false)? { - blocks.current.push(Item::Core(stmt)); - } + }, + _, + ) => { + let cores = + self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)?; + self.with_return_guard(cores, body, self.line(*span), enclosing_loop)? + } + (Stmt::Break { span } | Stmt::Continue { span }, Some(iteration)) => { + let line = self.line(*span); + let target = if matches!(stmt, Stmt::Break { .. }) { + ITERATION_BREAK + } else { + EXIT_STATE + }; + vec![ + set_slot(iteration.state, CoreExpr::Int(target), line), + CoreStmt::Break { line }, + ] + } + (Stmt::Goto { span, .. }, Some(iteration)) => { + let label = self.goto_target(*span)?; + if self.label_loops[label] == Some(iteration.owner) { + items.push(Item::Goto { + label, + line: self.line(*span), + }); + return Ok(()); } - other => blocks.current.push(self.arm_item(other)?), + self.loop_goto(label, *span)? } - } + (Stmt::Return { values, span }, Some(_)) => self.loop_return(values, *span)?, + (other, iteration) => { + items.push(self.arm_item(other, iteration)?); + return Ok(()); + } + }; + items.extend(cores.into_iter().map(Item::Core)); Ok(()) } - fn arm_item(&mut self, stmt: &Stmt) -> Result { + fn arm_item(&mut self, stmt: &Stmt, iteration: Option) -> Result { match stmt { Stmt::Empty { .. } => Ok(Item::Core(CoreStmt::Noop { line: 1 })), Stmt::Local { @@ -343,7 +376,7 @@ impl<'a> Lower<'a> { arms, else_body, span, - } => self.if_item(arms, else_body.as_ref(), *span), + } => self.if_item(arms, else_body.as_ref(), *span, iteration), Stmt::Break { span } | Stmt::Continue { span } => { Err(self.fail(*span, "break or continue outside a source loop")) } @@ -366,45 +399,21 @@ impl<'a> Lower<'a> { } } - fn branch_items(&mut self, stmts: &[Stmt]) -> Result, ParseError> { + fn branch_items( + &mut self, + stmts: &[Stmt], + iteration: Option, + ) -> Result, ParseError> { let mut items = Vec::new(); for stmt in stmts { if matches!(stmt, Stmt::Empty { .. }) { continue; } if let Stmt::Do { body, .. } = stmt { - items.extend(self.branch_items(&body.stmts)?); - continue; + items.extend(self.branch_items(&body.stmts, iteration)?); + } else { + self.append_items(stmt, &mut items, iteration)?; } - if let Stmt::While { cond, body, span } = stmt { - for core in self.while_stmt(cond, body, *span, false)? { - items.push(Item::Core(core)); - } - continue; - } - if let Stmt::Repeat { body, until, span } = stmt { - for core in self.repeat_stmt(body, until, *span, false)? { - items.push(Item::Core(core)); - } - continue; - } - if let Stmt::NumericFor { - name, - start, - limit, - step, - body, - span, - } = stmt - { - let cores = - self.numeric_for_stmts(name, start, limit, step.as_ref(), body, *span)?; - for core in self.with_return_guard(cores, body, self.line(*span), false)? { - items.push(Item::Core(core)); - } - continue; - } - items.push(self.arm_item(stmt)?); } Ok(items) } @@ -414,6 +423,7 @@ impl<'a> Lower<'a> { arms: &[ast::IfArm], else_body: Option<&Block>, span: Span, + iteration: Option, ) -> Result { if arms.is_empty() { return Err(self.fail(span, "if has no arm")); @@ -421,16 +431,16 @@ impl<'a> Lower<'a> { if if_has_label(arms, else_body) { return Err(self.fail(span, "a label inside if is not in this slice")); } - if !if_has_transfer(arms, else_body) { + if iteration.is_none() && !if_has_transfer(arms, else_body) { return Ok(Item::Core(self.if_core(arms, else_body, span, false)?)); } let line = self.line(span); let mut else_body_items = match else_body { - Some(body) => self.branch_items(&body.stmts)?, + Some(body) => self.branch_items(&body.stmts, iteration)?, None => Vec::new(), }; for arm in arms.iter().rev() { - let then_body = self.branch_items(&arm.body.stmts)?; + let then_body = self.branch_items(&arm.body.stmts, iteration)?; let cond = core_truthy(self.expr(&arm.cond)?); else_body_items = vec![Item::If { cond, @@ -486,11 +496,7 @@ impl<'a> Lower<'a> { span: Span, enclosing_loop: bool, ) -> Result, ParseError> { - self.reject_loop_transfer(body, span)?; - let (body_stmts, value) = self.straight(&body.stmts, true)?; - if value.is_some() { - return Err(self.fail(span, "return inside a loop is not in this slice")); - } + let body_stmts = self.loop_body(body, span)?; let line = self.line(span); let stmt = CoreStmt::While { condition: core_truthy(self.expr(cond)?), @@ -507,11 +513,7 @@ impl<'a> Lower<'a> { span: Span, enclosing_loop: bool, ) -> Result, ParseError> { - self.reject_loop_transfer(body, span)?; - let (body_stmts, value) = self.straight(&body.stmts, true)?; - if value.is_some() { - return Err(self.fail(span, "return inside a loop is not in this slice")); - } + let body_stmts = self.loop_body(body, span)?; let line = self.line(span); let again = self.alloc_repeat_flag()?; let until_value = self.expr(until)?; @@ -544,11 +546,7 @@ impl<'a> Lower<'a> { body: &Block, span: Span, ) -> Result, ParseError> { - self.reject_loop_transfer(body, span)?; - let (body_stmts, value) = self.straight(&body.stmts, true)?; - if value.is_some() { - return Err(self.fail(span, "return inside a loop is not in this slice")); - } + let body_stmts = self.loop_body(body, span)?; let line = self.line(span); let visible = self.slot(self.binding_for_index(name, body)?)?; if !self.dispatching { @@ -589,11 +587,40 @@ impl<'a> Lower<'a> { Ok(stmts) } - fn reject_loop_transfer(&self, body: &Block, span: Span) -> Result<(), ParseError> { - if contains_label(body) || self.block_has_goto(body, false) { - return Err(self.fail(span, "goto or label inside a loop is not in this slice")); + fn loop_body(&mut self, body: &Block, owner: Span) -> Result, ParseError> { + if !self.block_has_goto(body, Some(owner)) { + let (stmts, value) = self.straight(&body.stmts, true)?; + debug_assert!(value.is_none()); + return Ok(stmts); } - Ok(()) + let line = self.line(owner); + let state = self.alloc_private(&format!("$lua_iteration_state_{}", owner.start))?; + let mut blocks = BlockBuf::new(); + self.walk_list(&body.stmts, &mut blocks, Some(Iteration { owner, state }))?; + let chain = self.emit_dispatch(blocks, state)?; + let mut stmts = vec![ + let_expr(state, CoreExpr::Int(1), line), + dispatch_loop(state, vec![chain], line), + CoreStmt::IfElse { + condition: CoreExpr::Eq( + Box::new(CoreExpr::Var(state)), + Box::new(CoreExpr::Int(ITERATION_BREAK)), + ), + then_branch: vec![CoreStmt::Break { line }], + else_branch: Vec::new(), + line, + }, + ]; + // A return or outward goto may have left the dispatcher directly, or + // via a nested loop's guard. Leave the source loop before its post. + if self.loop_can_exit_chunk_arm(body) { + stmts.push(self.exit_propagation(line, true)?); + } + Ok(stmts) + } + + fn loop_can_exit_chunk_arm(&self, body: &Block) -> bool { + contains_return_block(body) || self.block_has_goto(body, None) } fn with_return_guard( @@ -603,7 +630,7 @@ impl<'a> Lower<'a> { line: u32, enclosing_loop: bool, ) -> Result, ParseError> { - if contains_return_block(body) || self.block_has_goto(body, true) { + if self.loop_can_exit_chunk_arm(body) { stmts.push(self.exit_propagation(line, enclosing_loop)?); } Ok(stmts) @@ -613,10 +640,9 @@ impl<'a> Lower<'a> { let Some(state) = self.state else { return Err(self.fail_line(line, "return leaves a loop without a dispatch state")); }; - // Break leaves the enclosing source loop and skips its post. Continue - // is only legal in the dispatch arm: it is the same exit a chunk - // return already uses, and it runs before a later transfer can store - // another state. + // Break leaves the nearest source loop or iteration dispatcher. + // In a chunk dispatch arm, Continue takes the pending transfer before + // a later store can overwrite it. let leave = if enclosing_loop { CoreStmt::Break { line } } else { @@ -650,9 +676,8 @@ impl<'a> Lower<'a> { let Some(state) = self.state else { return Err(self.fail(span, "return leaves a loop without a dispatch state")); }; - // Continue would resume this source loop and run its post. Break - // skips that post. The expression is the assign operand, so it runs - // once, before the exit state is stored. + // Exit the nearest Core loop; the guards skip each source loop's post. + // Evaluate the result once, before recording the pending return. Ok(vec![ set_slot(result, expr, line), set_slot(state, CoreExpr::Int(EXIT_STATE), line), @@ -660,10 +685,12 @@ impl<'a> Lower<'a> { ]) } - fn loop_goto(&mut self, span: Span) -> Result, ParseError> { - let label = self.goto_target(span)?; - if self.label_in_loop(label) { - return Err(self.fail(span, "goto or label inside a loop is not in this slice")); + fn loop_goto(&mut self, label: usize, span: Span) -> Result, ParseError> { + if self.label_loops[label].is_some() { + return Err(self.fail( + span, + "goto targeting a different source loop is not in this slice", + )); } let Some(state) = self.state else { return Err(self.fail(span, "goto leaves a loop without a dispatch state")); @@ -688,44 +715,35 @@ impl<'a> Lower<'a> { index.ok_or_else(|| self.fail(span, "loop goto label index does not fit in a state")) } - fn label_in_loop(&self, label: usize) -> bool { - self.labels_in_loops.get(label).copied().unwrap_or(true) - } - - fn block_has_goto(&self, block: &Block, outward: bool) -> bool { + fn block_has_goto(&self, block: &Block, owner: Option) -> bool { block .stmts .iter() - .any(|stmt| self.stmt_has_goto(stmt, outward)) + .any(|stmt| self.stmt_has_goto(stmt, owner)) } - fn stmt_has_goto(&self, stmt: &Stmt, outward: bool) -> bool { + fn stmt_has_goto(&self, stmt: &Stmt, owner: Option) -> bool { match stmt { - Stmt::Goto { span, .. } => self.goto_is_outward(*span) == outward, + Stmt::Goto { span, .. } => self + .goto_target(*span) + .is_ok_and(|label| self.label_loops[label] == owner), Stmt::Do { body, .. } | Stmt::While { body, .. } | Stmt::Repeat { body, .. } | Stmt::NumericFor { body, .. } - | Stmt::GenericFor { body, .. } => self.block_has_goto(body, outward), + | Stmt::GenericFor { body, .. } => self.block_has_goto(body, owner), Stmt::If { arms, else_body, .. } => { - arms.iter() - .any(|arm| self.block_has_goto(&arm.body, outward)) + arms.iter().any(|arm| self.block_has_goto(&arm.body, owner)) || else_body .as_ref() - .is_some_and(|body| self.block_has_goto(body, outward)) + .is_some_and(|body| self.block_has_goto(body, owner)) } _ => false, } } - fn goto_is_outward(&self, span: Span) -> bool { - self.goto_target(span) - .ok() - .is_some_and(|label| !self.label_in_loop(label)) - } - fn resolve_pending_labels(&self, state: LocalSlot) -> Result { let mut labels = self.pending_labels.clone(); labels.sort_unstable(); @@ -853,9 +871,11 @@ impl<'a> Lower<'a> { if !in_loop { return Err(self.fail(*span, "goto or label in a direct statement")); } - out.extend(self.loop_goto(*span)?); + let label = self.goto_target(*span)?; + out.extend(self.loop_goto(label, *span)?); return Ok((out, None)); } + Stmt::Label { .. } if in_loop => {} Stmt::Label { span, .. } => { return Err(self.fail(*span, "goto or label in a direct statement")); } @@ -1036,15 +1056,35 @@ impl<'a> Lower<'a> { Ok(CoreExpr::Float(value)) } - fn emit_items(&self, items: &[Item]) -> Result, ParseError> { + fn emit_dispatch( + &mut self, + mut blocks: BlockBuf, + state: LocalSlot, + ) -> Result { + blocks.finish(); + for (index, block) in blocks.finished.iter().enumerate() { + if let Some(label) = block.label { + self.label_state[label] = Some(self.state_id_of(index)); + } + } + let mut arms = Vec::with_capacity(blocks.finished.len()); + for (index, block) in blocks.finished.iter().enumerate() { + let mut body = self.emit_items(&block.items, state)?; + body.extend(self.emit_exit(&block.exit, index, blocks.finished.len(), state)?); + arms.push((self.state_id_of(index), body)); + } + Ok(dispatch_chain(state, arms)) + } + + fn emit_items(&self, items: &[Item], state: LocalSlot) -> Result, ParseError> { let mut out = Vec::new(); for item in items { - out.extend(self.emit_item(item)?); + out.extend(self.emit_item(item, state)?); } Ok(out) } - fn emit_item(&self, item: &Item) -> Result, ParseError> { + fn emit_item(&self, item: &Item, state: LocalSlot) -> Result, ParseError> { match item { Item::Core(stmt) => Ok(vec![stmt.clone()]), Item::If { @@ -1054,12 +1094,12 @@ impl<'a> Lower<'a> { line, } => Ok(vec![CoreStmt::IfElse { condition: cond.clone(), - then_branch: self.emit_items(then_body)?, - else_branch: self.emit_items(else_body)?, + then_branch: self.emit_items(then_body, state)?, + else_branch: self.emit_items(else_body, state)?, line: *line, }]), - Item::Goto { label, line } => Ok(self.transfer(self.label_state_id(*label)?, *line)), - Item::Return { expr, line } => Ok(self.return_transfer(expr.clone(), *line)?), + Item::Goto { label, line } => Ok(transfer(state, self.label_state_id(*label)?, *line)), + Item::Return { expr, line } => self.return_transfer(state, expr.clone(), *line), } } @@ -1068,6 +1108,7 @@ impl<'a> Lower<'a> { exit: &Exit, index: usize, len: usize, + state: LocalSlot, ) -> Result, ParseError> { match exit { Exit::Fallthrough => { @@ -1076,28 +1117,25 @@ impl<'a> Lower<'a> { } else { EXIT_STATE }; - Ok(self.transfer(next, 1)) + Ok(transfer(state, next, 1)) } - Exit::Goto { label, line } => Ok(self.transfer(self.label_state_id(*label)?, *line)), - Exit::Return { expr, line } => self.return_transfer(expr.clone(), *line), - Exit::Stop => Ok(self.transfer(EXIT_STATE, 1)), + Exit::Goto { label, line } => Ok(transfer(state, self.label_state_id(*label)?, *line)), + Exit::Return { expr, line } => self.return_transfer(state, expr.clone(), *line), + Exit::Stop => Ok(transfer(state, EXIT_STATE, 1)), } } - fn transfer(&self, target: i64, line: u32) -> Vec { - let state = self.state.expect("dispatch state"); - vec![ - set_slot(state, CoreExpr::Int(target), line), - CoreStmt::Continue { line }, - ] - } - - fn return_transfer(&self, expr: CoreExpr, line: u32) -> Result, ParseError> { + fn return_transfer( + &self, + state: LocalSlot, + expr: CoreExpr, + line: u32, + ) -> Result, ParseError> { let Some(result) = self.result else { return Err(self.fail_line(line, "return without a result slot")); }; let mut stmts = vec![set_slot(result, expr, line)]; - stmts.extend(self.transfer(EXIT_STATE, line)); + stmts.extend(transfer(state, EXIT_STATE, line)); Ok(stmts) } @@ -1256,6 +1294,24 @@ impl BlockBuf { } } +fn transfer(state: LocalSlot, target: i64, line: u32) -> Vec { + vec![ + set_slot(state, CoreExpr::Int(target), line), + CoreStmt::Continue { line }, + ] +} + +fn dispatch_loop(state: LocalSlot, body: Vec, line: u32) -> CoreStmt { + CoreStmt::While { + condition: CoreExpr::Not(Box::new(CoreExpr::Eq( + Box::new(CoreExpr::Var(state)), + Box::new(CoreExpr::Int(EXIT_STATE)), + ))), + body, + line, + } +} + fn dispatch_chain(state: LocalSlot, arms: Vec<(i64, Vec)>) -> CoreStmt { let mut pending = vec![CoreStmt::Break { line: 1 }]; for (state_id, body) in arms.into_iter().rev() { @@ -1398,44 +1454,44 @@ fn contains_label(block: &Block) -> bool { block.stmts.iter().any(stmt_contains_label) } -fn labels_inside_loops(chunk: &Chunk, resolution: &Resolution) -> Vec { - let mut inside = vec![false; resolution.labels.len()]; - mark_labels_in_loops(&chunk.body, false, resolution, &mut inside); - inside +fn label_loop_owners(chunk: &Chunk, resolution: &Resolution) -> Vec> { + let mut owners = vec![None; resolution.labels.len()]; + mark_label_owners(&chunk.body, None, resolution, &mut owners); + owners } -fn mark_labels_in_loops( +fn mark_label_owners( block: &Block, - in_loop: bool, + owner: Option, resolution: &Resolution, - inside: &mut [bool], + owners: &mut [Option], ) { for stmt in &block.stmts { match stmt { - Stmt::Label { name, .. } if in_loop => { + Stmt::Label { name, .. } if owner.is_some() => { if let Some(index) = resolution .labels .iter() .position(|label| label.span == name.span) { - inside[index] = true; + owners[index] = owner; } } - Stmt::Do { body, .. } => mark_labels_in_loops(body, in_loop, resolution, inside), - Stmt::While { body, .. } | Stmt::Repeat { body, .. } => { - mark_labels_in_loops(body, true, resolution, inside); - } - Stmt::NumericFor { body, .. } | Stmt::GenericFor { body, .. } => { - mark_labels_in_loops(body, true, resolution, inside); + Stmt::Do { body, .. } => mark_label_owners(body, owner, resolution, owners), + Stmt::While { body, span, .. } + | Stmt::Repeat { body, span, .. } + | Stmt::NumericFor { body, span, .. } + | Stmt::GenericFor { body, span, .. } => { + mark_label_owners(body, Some(*span), resolution, owners); } Stmt::If { arms, else_body, .. } => { for arm in arms { - mark_labels_in_loops(&arm.body, in_loop, resolution, inside); + mark_label_owners(&arm.body, owner, resolution, owners); } if let Some(body) = else_body { - mark_labels_in_loops(body, in_loop, resolution, inside); + mark_label_owners(body, owner, resolution, owners); } } _ => {} @@ -1446,16 +1502,14 @@ fn mark_labels_in_loops( fn stmt_contains_label(stmt: &Stmt) -> bool { match stmt { Stmt::Label { .. } => true, - Stmt::Do { body, .. } | Stmt::While { body, .. } | Stmt::Repeat { body, .. } => { - contains_label(body) - } + Stmt::Do { body, .. } => contains_label(body), Stmt::If { arms, else_body, .. } => { arms.iter().any(|arm| contains_label(&arm.body)) || else_body.as_ref().is_some_and(contains_label) } - Stmt::NumericFor { body, .. } | Stmt::GenericFor { body, .. } => contains_label(body), + // Nested loops own their labels and lower them in their own regions. _ => false, } } diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index 65bdd52..38076f4 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -331,6 +331,11 @@ fn oracle_return(oracle: &str, path: &Path) -> f64 { assert!(run.lines > 0, "line hook saw no fixture execution"); assert_eq!(run.argc, 0, "fixture path was passed as a script argument"); assert_eq!(run.arg0, "nil", "fixture path leaked into arg[0]"); + eprintln!( + "LUA_CONTROL oracle fixture={} jit=off value={}", + path.display(), + run.value + ); run.value } @@ -3330,10 +3335,6 @@ fn loop_outward_combination_selects_each_scalar_path() { ); } -// Legal LuaJIT: the label and its goto share the loop block and enter no -// local. The private slice still refuses an in-loop label. This records that -// current boundary. jump_into_local_is_a_static_rejection already covers the -// resolver's refusal to enter a local, so this test does not repeat it. const IN_LOOP_LABEL: &str = "\ local n = 0 while n < 2 do @@ -3348,37 +3349,147 @@ return n "; #[test] -fn in_loop_label_fails_closed_outside_the_private_slice() { - let chunk = parser::parse_chunk(IN_LOOP_LABEL.as_bytes()).expect("parse in-loop label"); - let resolution = resolve::resolve(&chunk); - assert!( - resolution.errors.is_empty(), - "an in-loop label that enters no local is legal: {:?}", - resolution.errors - ); - let error = control::lower_source(IN_LOOP_LABEL).expect_err("private slice"); - let text = error.to_string(); - assert!( - text.contains("not in this slice"), - "in-loop label must fail closed at the private slice, not as another class: {text}" +fn in_loop_label_runs_in_the_private_slice() { + expect_number("in_loop_label", IN_LOOP_LABEL, 11.0); +} + +#[test] +fn in_loop_label_while_backedge_stays_in_the_current_iteration() { + expect_number( + "while_iteration_backedge", + "\ +local n = 0 +local visits = 0 +while n < 2 do + visits = visits + 1 + do + ::again:: + n = n + 1 + if n == 1 then continue end + if n == 2 then goto again end + n = n + 10 + end +end +return visits * 100 + n +", + 213.0, ); - assert!( - !text.contains("jump into the scope of local"), - "this source does not enter a local: {text}" +} + +#[test] +fn in_loop_label_repeat_keeps_until_on_the_source_loop() { + // Route 1 must stop on continue. Route 2 must reach n == 3 before + // testing `stop`. Route 3 must break even though `stop` is false. + for (route, expected) in [(1, 101.0), (2, 203.0), (3, 203.0)] { + expect_number( + &format!("repeat_iteration_post_{route}"), + &format!( + "\ +local route = {route} +local rounds = 0 +local n = 0 +repeat + rounds = rounds + 1 + local stop = route == 1 + ::again:: + n = n + 1 + if n == 1 then continue end + if n == 2 then + stop = route == 2 + goto again + end + if route == 3 then break end + if n > 3 then break end +until stop +return rounds * 100 + n +", + ), + expected, + ); + } +} + +#[test] +fn in_loop_label_numeric_for_goto_keeps_visible_index_until_post() { + expect_numeric( + "numeric_iteration_index", + "\ +local trace = 0 +for i = 1, 5 do + if i == 1 then continue end + if i == 4 then break end + trace = trace * 10 + i + i = i + 10 + do goto mark end + trace = 999 + ::mark:: + trace = trace * 100 + i +end +return trace +", + 212313.0, ); - let path = write_fixture("in_loop_label", IN_LOOP_LABEL); - let compiled = compile_source_file_with_options(&path, candidate_options()); +} + +#[test] +fn in_loop_label_coexists_with_nested_loop_controls_and_chunk_exits() { + for (route, expected) in [(1, 102.0), (2, 202.0), (3, 302.0), (4, 102.0)] { + expect_number( + &format!("iteration_and_chunk_exit_{route}"), + &format!( + "\ +local n = 0 +local route = {route} +goto start +n = 999 +::start:: +repeat + goto body + n = 999 + ::body:: + while true do + n = n + 1 + if n == 1 then continue end + if route == 1 then goto done end + if route == 2 then return 200 + n end + break + end + if route == 4 then goto done end + return 300 + n +until true +do return 999 end +::done:: +return 100 + n +" + ), + expected, + ); + } +} + +#[test] +fn in_loop_label_does_not_allow_jumping_into_a_local() { + let source = "\ +while true do + goto inside + local hidden = 42 + ::inside:: + return hidden +end +"; + let path = write_fixture("loop_jump_into_local", source); + let error = compile_source_file_with_options(&path, candidate_options()) + .err() + .expect("a goto cannot enter a local binding"); assert!( - compiled.is_err(), - "in-loop label must not produce a program" - ); - let Ok(oracle) = std::env::var("LUAJIT_ORACLE") else { - eprintln!("LUAJIT_ORACLE is unset; in-loop label acceptance is not a differential result"); - return; - }; - let observed = oracle_return(&oracle, &path); - assert_eq!( - observed, 11.0, - "LuaJIT accepts the in-loop label; candidate refusal is the private slice" + error + .to_string() + .contains("jump into the scope of local hidden"), + "{error}" ); + if let Ok(oracle) = std::env::var("LUAJIT_ORACLE") { + let output = oracle_load_rejection(&oracle, &path); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("LOAD_REJECT")); + } } From 0dc995e8c8c2b9a5c05beb0647c1af013a5a8a5d Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 04:32:58 +0800 Subject: [PATCH 045/225] feat(lua): trace strong table object keys --- src/frontends/lua/heap/table.rs | 117 +++++++-- tests/luajit_heap_runtime/candidate.rs | 180 +++++++++++--- .../value_boundary_tests.rs | 232 ++++++++++++++++++ 3 files changed, 481 insertions(+), 48 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 7a87761..d5f7a03 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -170,13 +170,31 @@ struct Slot { metatable: Option<(u32, u32)>, } +#[derive(Clone, Copy)] struct Edge { from: u32, - key: u32, + /// Field ids and object identities share this record. An object key is the + /// live slot and generation, not a guest number and not a second edge table. + key: EdgeKey, to_slot: u32, to_generation: u32, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum EdgeKey { + Field(u32), + Object { slot: u32, generation: u32 }, +} + +impl EdgeKey { + fn object(key: TableRef) -> Self { + Self::Object { + slot: key.slot(), + generation: key.generation(), + } + } +} + struct Frame { index: u32, generation: u32, @@ -193,8 +211,10 @@ struct Frame { /// taken. /// /// Edge work stays in its own fields. `index_edge_checks` is the two passes -/// that build the outgoing index (2E). `outgoing_edge_checks` is the edges -/// followed from marked nodes. `sweep_edge_checks` is the one edge filter, +/// that build the outgoing index (2E). `outgoing_edge_checks` counts records +/// followed from marked nodes. An object record has one key and one value +/// target; each target contributes separately to `node_slot_visits`. +/// `sweep_edge_checks` is the one edge filter, /// and it is zero when every live node is marked. Adding those fields is not /// a total GC cost. /// @@ -260,7 +280,7 @@ pub struct ScanScratch { pub index_offsets_pushed: u64, /// Elements copied into `cursor` from `offsets`. pub index_cursor_copied: u64, - /// `targets` zero-initialized to the running in-range edge total. + /// Outgoing index entries zero-initialized to the in-range edge total. pub index_targets_inited: u64, /// Work-stack pushes. One per newly marked node. Not a reserve. pub work_pushed: u64, @@ -285,7 +305,7 @@ pub(super) struct DoomedToken { /// Not stored on the heap, so it is not a second persistent graph. struct OutgoingIndex { offsets: Vec, - targets: Vec<(u32, u32)>, + entries: Vec, } /// Category of one guest value on this heap. @@ -464,6 +484,35 @@ impl LuaHeap { /// Writes a reference edge. An existing key is overwritten and does not /// consume another edge slot. A new key at the cap fails without insert. pub fn set_edge(&mut self, from: TableRef, key: u32, to: TableRef) -> Result<(), HeapError> { + self.write_edge(from, EdgeKey::Field(key), to) + } + + /// Writes one object-key edge in the same record and quota as a field edge. + /// + /// The key is the live slot and generation. A structurally equal carrier is + /// not a key: the caller classifies the issued array before this call. + pub fn set_object_edge( + &mut self, + from: TableRef, + key: TableRef, + to: TableRef, + ) -> Result<(), HeapError> { + self.require_live(key)?; + self.write_edge(from, EdgeKey::object(key), to) + } + + /// Removes one object-key record. Another key, including a later generation + /// of the same slot, is a different identity and stays. + pub fn clear_object_edge(&mut self, from: TableRef, key: TableRef) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_live(key)?; + let key = EdgeKey::object(key); + self.edges + .retain(|edge| edge.from != from.slot() || edge.key != key); + Ok(()) + } + + fn write_edge(&mut self, from: TableRef, key: EdgeKey, to: TableRef) -> Result<(), HeapError> { self.require_live(from)?; self.require_live(to)?; if let Some(edge) = self @@ -490,6 +539,20 @@ impl LuaHeap { /// Reads a reference edge through either alias of `from`. pub fn edge(&self, from: TableRef, key: u32) -> Result, HeapError> { + self.read_edge(from, EdgeKey::Field(key)) + } + + /// Reads an object-key edge. The key generation must still be that live slot. + pub fn object_edge( + &self, + from: TableRef, + key: TableRef, + ) -> Result, HeapError> { + self.require_live(key)?; + self.read_edge(from, EdgeKey::object(key)) + } + + fn read_edge(&self, from: TableRef, key: EdgeKey) -> Result, HeapError> { self.require_live(from)?; Ok(self.edges.iter().find_map(|edge| { if edge.from == from.slot() && edge.key == key { @@ -809,12 +872,12 @@ impl LuaHeap { let start = index.offsets[slot as usize] as usize; let end = index.offsets[slot as usize + 1] as usize; self.scan.outgoing_edge_checks += (end - start) as u64; - for &(to_slot, to_generation) in &index.targets[start..end] { - self.scan.node_slot_visits += 1; - if self.slot_live(to_slot, to_generation) { - self.scan.node_slot_visits += 1; - self.mark_slot(to_slot, &mut work); + for &entry in &index.entries[start..end] { + let edge = self.edges[entry as usize]; + if let EdgeKey::Object { slot, generation } = edge.key { + self.follow_target(slot, generation, &mut work); } + self.follow_target(edge.to_slot, edge.to_generation, &mut work); } if follow_metatables { self.follow_metatable(slot, &mut work); @@ -829,6 +892,10 @@ impl LuaHeap { return; }; self.scan.metatable_edge_checks += 1; + self.follow_target(to_slot, to_generation, work); + } + + fn follow_target(&mut self, to_slot: u32, to_generation: u32, work: &mut Vec) { self.scan.node_slot_visits += 1; if self.slot_live(to_slot, to_generation) { self.scan.node_slot_visits += 1; @@ -865,20 +932,20 @@ impl LuaHeap { self.scan.index_edge_checks += edge_count as u64; let mut cursor = offsets.clone(); self.scan.scratch.index_cursor_copied += cursor.len() as u64; - let mut targets = vec![(0u32, 0u32); running as usize]; - self.scan.scratch.index_targets_inited += targets.len() as u64; - for edge in &self.edges { + let mut entries = vec![0u32; running as usize]; + self.scan.scratch.index_targets_inited += entries.len() as u64; + for (entry, edge) in self.edges.iter().enumerate() { let from = edge.from as usize; if from >= slot_count { continue; } let at = cursor[from] as usize; - if at < targets.len() { - targets[at] = (edge.to_slot, edge.to_generation); + if at < entries.len() { + entries[at] = entry as u32; cursor[from] = cursor[from].saturating_add(1); } } - OutgoingIndex { offsets, targets } + OutgoingIndex { offsets, entries } } /// One filter of the edge vector. Skipped when every live node is marked, @@ -893,9 +960,14 @@ impl LuaHeap { self.scan.node_slot_visits += marked.len() as u64; self.scan.scratch.sweep_bitmap_inited += marked.len() as u64; self.scan.sweep_edge_checks += self.edges.len() as u64; + let is_marked = |slot: u32| marked.get(slot as usize).copied().unwrap_or(false); self.edges.retain(|edge| { - marked.get(edge.from as usize).copied().unwrap_or(false) - && marked.get(edge.to_slot as usize).copied().unwrap_or(false) + is_marked(edge.from) + && is_marked(edge.to_slot) + && match edge.key { + EdgeKey::Field(_) => true, + EdgeKey::Object { slot, .. } => is_marked(slot), + } }); } @@ -926,8 +998,9 @@ impl LuaHeap { } fn remove_edges_touching(&mut self, slot: u32) { - self.edges - .retain(|edge| edge.from != slot && edge.to_slot != slot); + self.edges.retain(|edge| { + edge.from != slot && edge.to_slot != slot && !edge_key_is_slot(edge.key, slot) + }); } fn clear_roots_to(&mut self, handle: TableRef) { @@ -986,3 +1059,7 @@ impl LuaHeap { self.peak_edges = self.peak_edges.max(self.edges.len() as u32); } } + +fn edge_key_is_slot(key: EdgeKey, slot: u32) -> bool { + matches!(key, EdgeKey::Object { slot: key_slot, .. } if key_slot == slot) +} diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 470e8aa..3bbd397 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -553,27 +553,55 @@ fn root_issued(call: &mut OwnedHostCall<'_>) -> Result { } fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { - let (from, key, to) = match call.args() { - [from, key, to] => (from.clone(), float_u32(key)?, to.clone()), + let (from, key_value, to_value) = match call.args() { + [from, key, to] => (from.clone(), key.clone(), to.clone()), _ => return Err(host_fault("invalid table edge")), }; let from = match classify(&mut call.vm().host_context(), &from)? { heap::GuestClass::Table(table) => table, _ => return Err(host_fault("edge source is not a table")), }; - let to = match classify(&mut call.vm().host_context(), &to)? { - heap::GuestClass::Table(table) => table, - _ => return Err(host_fault("edge target is not a table")), - }; - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.set_edge(from, key, to) - }) - .map_err(heap_error)?; - with_witness(call.vm(), |witness| { - if witness.field_key.is_none() { - witness.field_key = Some(key); + match key_value { + Value::Int(key) => { + // Only the private dot lowering emits an Int field id. + let key = u32::try_from(key).map_err(|_| host_fault("invalid field id"))?; + let to = match classify(&mut call.vm().host_context(), &to_value)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("edge target is not a table")), + }; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.set_edge(from, key, to) + }) + .map_err(heap_error)?; + with_witness(call.vm(), |witness| { + if witness.field_key.is_none() { + witness.field_key = Some(key); + } + })?; } - })?; + other => { + let heap::GuestClass::Table(key) = classify(&mut call.vm().host_context(), &other)? + else { + return Err(host_fault("edge key is not a table")); + }; + if matches!(to_value, Value::Null) { + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.clear_object_edge(from, key) + }) + .map_err(heap_error)?; + } else { + let heap::GuestClass::Table(to) = + classify(&mut call.vm().host_context(), &to_value)? + else { + return Err(host_fault("edge target is not a table")); + }; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.set_object_edge(from, key, to) + }) + .map_err(heap_error)?; + } + } + } Ok(Value::Float(0.0)) } @@ -778,16 +806,25 @@ fn retire_chunk(call: &mut OwnedHostCall<'_>) -> Result { } fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { - let (from, key) = match call.args() { - [from, key] => (from.clone(), float_u32(key)?), + let (from, key_value) = match call.args() { + [from, key] => (from.clone(), key.clone()), _ => return Err(host_fault("invalid field read")), }; let table = match classify(&mut call.vm().host_context(), &from)? { heap::GuestClass::Table(table) => table, _ => return Err(host_fault("field source is not a table")), }; - let target = heap::with_heap(&mut call.vm().host_context(), |heap| heap.edge(table, key)) - .map_err(heap_error)?; + let mut host = call.vm().host_context(); + let target = if let Value::Int(key) = key_value { + let key = u32::try_from(key).map_err(|_| host_fault("invalid field id"))?; + heap::with_heap(&mut host, |heap| heap.edge(table, key)) + } else { + let heap::GuestClass::Table(key) = classify(&mut host, &key_value)? else { + return Err(host_fault("edge key is not a table")); + }; + heap::with_heap(&mut host, |heap| heap.object_edge(table, key)) + } + .map_err(heap_error)?; let Some(target) = target else { return Ok(Value::Null); }; @@ -1287,13 +1324,93 @@ impl Lower<'_> { let key = self.field_key(&name.bytes); let from = self.expr(table)?; let to = self.expr(value)?; - let expr = self.call(SET_EDGE, vec![from, Expr::Float(key as f64), to])?; + let expr = self.call(SET_EDGE, vec![from, Expr::Int(i64::from(key)), to])?; self.emit_ignored(expr, self.line(span)) } + ( + ast::AssignTarget::Index { + table, + key, + nav: false, + .. + }, + _, + ) => self.lower_index_assign(span, table, key, value), _ => Err(self.unsupported(span)), } } + /// Evaluate the receiver and key before the RHS and keep their temporary + /// slots visible to explicit collection during later operand evaluation. + fn lower_index_assign( + &mut self, + span: ast::Span, + table: &ast::Expr, + key: &ast::Expr, + value: &ast::Expr, + ) -> Result<(), ParseError> { + let temp_base = self.active_temps.len(); + let (from, key_slot) = self.index_operands(table, key, span)?; + let to = match value { + ast::Expr::Nil { .. } => Expr::Null, + other => self.expr(other)?, + }; + self.active_temps.truncate(temp_base); + let expr = self.call(SET_EDGE, vec![Expr::Var(from), Expr::Var(key_slot), to])?; + self.emit_ignored(expr, self.line(span)) + } + + fn index_read( + &mut self, + base: &ast::Expr, + key: &ast::Expr, + span: ast::Span, + ) -> Result { + let temp_base = self.active_temps.len(); + let (table, key_slot) = self.index_operands(base, key, span)?; + self.active_temps.truncate(temp_base); + self.call(GET_EDGE, vec![Expr::Var(table), Expr::Var(key_slot)]) + } + + fn index_operands( + &mut self, + base: &ast::Expr, + key: &ast::Expr, + span: ast::Span, + ) -> Result<(LocalSlot, LocalSlot), ParseError> { + if index_key_is_number(key) { + return Err(ParseError::at_line( + self.line(span) as usize, + "numeric table keys are not in this field-key subset", + )); + } + if !matches!(key, ast::Expr::Name { .. } | ast::Expr::Paren { .. }) { + return Err(self.unsupported(key.span())); + } + let table = self.expr(base)?; + let table = self.index_operand_slot(table, span)?; + let key = self.expr(key)?; + let key = self.index_operand_slot(key, span)?; + Ok((table, key)) + } + + fn index_operand_slot(&mut self, expr: Expr, span: ast::Span) -> Result { + if let Expr::Var(slot) = expr { + return Ok(slot); + } + let slot = self + .builder + .alloc_local_named(&format!("#index:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr, + line: self.line(span), + }); + self.active_temps.push(slot); + Ok(slot) + } + fn lower_function( &mut self, name: &ast::Name, @@ -1562,7 +1679,7 @@ impl Lower<'_> { line: self.line(span), }); let key = self.field_key(key_name); - self.call(GET_EDGE, vec![Expr::Var(slot), Expr::Float(key as f64)]) + self.call(GET_EDGE, vec![Expr::Var(slot), Expr::Int(i64::from(key))]) } fn field_key(&mut self, name: &[u8]) -> u32 { @@ -1637,15 +1754,14 @@ impl Lower<'_> { } Ok(left) } - ast::Expr::SuffixChain { steps, span, .. } - if steps - .iter() - .any(|step| matches!(step, ast::Suffix::Index { .. })) => + ast::Expr::SuffixChain { base, steps, span } + if let [ + ast::Suffix::Index { + key, nav: false, .. + }, + ] = steps.as_slice() => { - Err(ParseError::at_line( - self.line(*span) as usize, - "numeric table keys are not in this field-key subset", - )) + self.index_read(base, key, *span) } ast::Expr::SuffixChain { base, steps, span } if let [ @@ -1922,6 +2038,14 @@ fn chunk_receiver_width(stmts: &[ast::Stmt]) -> u32 { }) } +fn index_key_is_number(key: &ast::Expr) -> bool { + match key { + ast::Expr::Number { .. } => true, + ast::Expr::Paren { inner, .. } => index_key_is_number(inner), + _ => false, + } +} + fn syntactic_direct_call(expr: &ast::Expr) -> bool { matches!( expr, diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 4fac3f3..d810ffb 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -881,3 +881,235 @@ fn lua_candidate_omitting_the_collect_after_detach_keeps_the_metatable_target() assert_eq!(stats.collections, 1); assert_eq!(stats.live_nodes, 4); } + +/// `owner[key] = value`, a real bracket read, and `owner[key] = nil`. +/// The key is a live table identity, not a field name or a guest number. +#[test] +fn lua_candidate_assigns_reads_and_clears_a_table_object_key() { + let source = r#" +local owner = {} +local alias_owner = owner +local key = {} +local alias_key = key +local other_key = {} +local value = {} +local replacement = {} +observe_table(value, 0) +observe_table(replacement, 0) +owner[key] = value +alias_owner[other_key] = nil +observe_table(alias_owner[alias_key], 0) +owner[other_key] = value +alias_owner[alias_key] = replacement +observe_table(owner[key], 0) +alias_owner[alias_key] = nil +observe_table(owner[other_key], 0) +return type(owner[alias_key]) +"#; + let mut vm = candidate(source); + assert_eq!( + vm.run().expect("assign, read, and nil a table object key"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let tables = vm + .host_context() + .scope_state::>() + .unwrap() + .clone(); + let [value, replacement, via_alias, overwritten, other] = tables.as_slice() else { + panic!("expected five observed tables"); + }; + assert_eq!(via_alias, value, "aliases address the same entry"); + assert_eq!(overwritten, replacement, "an overwrite replaces the value"); + assert_eq!(other, value, "deletion leaves the distinct key alone"); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); +} + +#[test] +fn lua_candidate_bracket_numbers_do_not_alias_private_field_ids() { + let source = r#" +local function make() + local owner = {} + local value = {} + owner.field = value + return owner +end +local owner = make() +local number = 1 +return type(owner[number]) +"#; + let mut vm = candidate(source); + assert!(matches!(vm.run(), Err(vm::VmError::HostError(message)) + if message == "edge key is not a table")); +} + +#[test] +fn lua_candidate_collect_marks_object_key_and_value_from_owner_alone() { + let source = r#" +local function make() + local owner = {} + local key = {} + local value = {} + local child = {} + local orphan = {} + key.child = child + value.self = value + orphan.self = orphan + owner[key] = value + observe_table(owner, 0) + observe_table(key, 0) + observe_table(value, 0) + observe_table(child, 0) + observe_table(orphan, 0) + return owner +end +local owner = make() +collectgarbage("collect") +return type(owner) +"#; + let mut vm = candidate(source); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("table")]); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let [owner, key, value, child, orphan] = tables.as_slice() else { + panic!("expected five observed tables"); + }; + let resource_key = heap::LuaTableResource::key(); + for table in [owner, key, value, child] { + assert!( + host.borrow_resource_with_key::(table.token, &resource_key) + .is_ok(), + "only the owner root should keep {table:?} alive" + ); + } + assert!( + host.borrow_resource_with_key::(orphan.token, &resource_key) + .is_err() + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.object_edge(owner.table, key.table)).unwrap(), + Some(value.table) + ); + let witness = host.scope_state::().unwrap(); + let [first] = witness.collects.as_slice() else { + panic!("expected one completed collection"); + }; + assert_eq!(first_collect_matrix(first), (0, 8, 3, 4, 4, 4, 1)); + assert_eq!(host.resource_count(), 4); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.live_edges, 3); + assert_eq!(stats.live_roots, 0); +} + +#[test] +fn lua_candidate_collection_keeps_pending_index_receiver_and_key() { + let source = r#" +local orphan = {} +observe_table(orphan, 0) +orphan = nil +({})[({})] = collectgarbage("collect") +"#; + let mut vm = candidate(source); + // The collector returns a number. Reaching the value error proves both + // already evaluated table operands survived validation. + assert!(matches!(vm.run(), Err(vm::VmError::HostError(message)) + if message == "edge target is not a table")); + let mut host = vm.host_context(); + let orphan = host.scope_state::>().unwrap()[0]; + assert!( + host.borrow_resource_with_key::( + orphan.token, + &heap::LuaTableResource::key() + ) + .is_err() + ); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!( + (stats.collections, stats.live_nodes, stats.live_edges), + (1, 2, 0) + ); +} + +#[test] +fn lua_candidate_nil_deletion_reclaims_key_and_value_only_on_next_collect() { + let source = r#" +local function payload() + local value = {} + local orphan = {} + value.self = value + orphan.self = orphan + observe_table(value, 0) + observe_table(orphan, 0) + return value +end +local owner = {} +local key = {} +observe_table(owner, 0) +observe_table(key, 0) +local value = payload() +owner[key] = value +value = nil +collectgarbage("collect") +local read = owner[key] +observe_table(read, 0) +owner[key] = nil +local missing = type(owner[key]) +read = nil +key = nil +"#; + // The key is needed for guest indexing and is explicitly released + // before the second collect. The value has no direct root at the first. + for second_collect in [false, true] { + let collect = if second_collect { + "collectgarbage(\"collect\")\n" + } else { + "" + }; + let mut vm = candidate(&format!("{source}{collect}return missing\n")); + assert_eq!(vm.run().unwrap(), VmStatus::Halted, "{second_collect}"); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let [owner, key, value, orphan, via_owner] = tables.as_slice() else { + panic!("expected five observed tables"); + }; + assert_eq!(via_owner, value, "the edge retained the issued VM carrier"); + let witness = host.scope_state::().unwrap(); + assert_eq!(witness.collects.len(), if second_collect { 2 } else { 1 }); + assert_eq!( + first_collect_matrix(&witness.collects[0]), + (0, 6, 2, 3, 3, 3, 1) + ); + if second_collect { + assert_eq!( + first_collect_matrix(&witness.collects[1]), + (0, 2, 0, 1, 1, 1, 2) + ); + } + let resource_key = heap::LuaTableResource::key(); + for (table, alive) in [ + (owner, true), + (key, !second_collect), + (value, !second_collect), + (orphan, false), + ] { + assert_eq!( + host.borrow_resource_with_key::(table.token, &resource_key) + .is_ok(), + alive, + "resource lifetime after deletion for {table:?}" + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(table.table))).unwrap(), + alive, + "heap lifetime after deletion for {table:?}" + ); + } + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.live_edges, u32::from(!second_collect)); + assert_eq!(stats.live_roots, 0); + assert_eq!(host.resource_count(), if second_collect { 1 } else { 3 }); + } +} From cc50dccb07657287752583f2a5c9ce535d5db280 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 05:04:54 +0800 Subject: [PATCH 046/225] feat(lua): collect weak private table entries (cherry picked from commit c39ef50d28bded0b05819b8ae3d94a19b5d059a5) --- src/frontends/lua/heap/table.rs | 234 ++++++++++++--- tests/luajit_heap_runtime/candidate.rs | 64 +++-- .../value_boundary_tests.rs | 268 ++++++++++++++++++ 3 files changed, 498 insertions(+), 68 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index d5f7a03..ef936ca 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -18,7 +18,7 @@ pub struct HeapLimits { pub nodes: u32, /// Simultaneous explicit root slots. pub roots: u32, - /// Live reference-edge records. + /// Live table-entry records, including a scalar `__mode` field. pub edges: u32, /// Highest generation a slot may hold. The next release retires it. pub max_generation: u32, @@ -99,7 +99,7 @@ pub struct HeapStats { pub live_nodes: u32, /// Root slots currently holding a handle. pub live_roots: u32, - /// Reference edges currently stored. + /// Table-entry records currently stored. pub live_edges: u32, /// Slot vector length. Free and retired slots still occupy it. pub node_slots: u32, @@ -170,14 +170,26 @@ struct Slot { metatable: Option<(u32, u32)>, } -#[derive(Clone, Copy)] struct Edge { from: u32, /// Field ids and object identities share this record. An object key is the /// live slot and generation, not a guest number and not a second edge table. key: EdgeKey, - to_slot: u32, - to_generation: u32, + value: EdgeValue, +} + +enum EdgeValue { + Table { slot: u32, generation: u32 }, + ModeScalar(Value), +} + +impl EdgeValue { + fn table(&self) -> Option<(u32, u32)> { + match self { + Self::Table { slot, generation } => Some((*slot, *generation)), + Self::ModeScalar(_) => None, + } + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -212,8 +224,8 @@ struct Frame { /// /// Edge work stays in its own fields. `index_edge_checks` is the two passes /// that build the outgoing index (2E). `outgoing_edge_checks` counts records -/// followed from marked nodes. An object record has one key and one value -/// target; each target contributes separately to `node_slot_visits`. +/// inspected from marked nodes. Each followed object target contributes +/// separately to `node_slot_visits`; skipped weak targets do not. /// `sweep_edge_checks` is the one edge filter, /// and it is zero when every live node is marked. Adding those fields is not /// a total GC cost. @@ -252,6 +264,10 @@ pub struct ScanMeter { /// metatable reference does not read this path, so those collects add zero /// and leave the field-edge counts unchanged. pub metatable_edge_checks: u64, + /// Bytes examined while parsing direct string modes (including a NUL terminator if present). + pub weak_mode_bytes: u64, + /// Mode lookups by live metatable slot when a weak mode was indexed. + pub weak_mode_lookups: u64, pub token_slot_checks: u64, pub token_closes: u64, /// Node-slot reads and writes during mark reset, root liveness, outgoing @@ -282,6 +298,8 @@ pub struct ScanScratch { pub index_cursor_copied: u64, /// Outgoing index entries zero-initialized to the in-range edge total. pub index_targets_inited: u64, + /// Slot-indexed modes zero-initialized on the first weak mode in the index. + pub weak_modes_inited: u64, /// Work-stack pushes. One per newly marked node. Not a reserve. pub work_pushed: u64, /// Pending-close elements appended. Host mark only; pure collect is 0. @@ -306,6 +324,29 @@ pub(super) struct DoomedToken { struct OutgoingIndex { offsets: Vec, entries: Vec, + weak_modes: Option>, +} + +#[derive(Clone, Copy, Default)] +struct WeakMode { + keys: bool, + values: bool, +} + +impl WeakMode { + fn parse(mode: &str, bytes: &mut u64) -> Self { + let mut weak = Self::default(); + for byte in mode.bytes() { + *bytes += 1; + match byte { + b'k' => weak.keys = true, + b'v' => weak.values = true, + 0 => break, // LuaJIT scans the NUL-terminated mode string. + _ => {} + } + } + weak + } } /// Category of one guest value on this heap. @@ -348,6 +389,9 @@ pub struct LuaHeap { } impl LuaHeap { + /// Reserved direct field id for `__mode`; ordinary field ids start at 1. + pub const MODE_FIELD: u32 = 0; + /// Creates an empty heap. Slot zero is ordinary storage; handles start at /// generation 1 so generation 0 never denotes a live node. pub fn new(limits: HeapLimits) -> Self { @@ -484,7 +528,24 @@ impl LuaHeap { /// Writes a reference edge. An existing key is overwritten and does not /// consume another edge slot. A new key at the cap fails without insert. pub fn set_edge(&mut self, from: TableRef, key: u32, to: TableRef) -> Result<(), HeapError> { - self.write_edge(from, EdgeKey::Field(key), to) + self.write_table_edge(from, EdgeKey::Field(key), to) + } + + /// Writes the non-reference scalar forms of the direct `__mode` field. + /// Nil deletes the record; other scalar values occupy the same edge quota. + pub fn set_mode_scalar(&mut self, from: TableRef, value: Value) -> Result<(), HeapError> { + debug_assert!(matches!( + value, + Value::Null | Value::String(_) | Value::Float(_) | Value::Bool(_) + )); + self.require_live(from)?; + let key = EdgeKey::Field(Self::MODE_FIELD); + if matches!(value, Value::Null) { + self.clear_edge(from, key); + Ok(()) + } else { + self.write_edge(from, key, EdgeValue::ModeScalar(value)) + } } /// Writes one object-key edge in the same record and quota as a field edge. @@ -498,7 +559,7 @@ impl LuaHeap { to: TableRef, ) -> Result<(), HeapError> { self.require_live(key)?; - self.write_edge(from, EdgeKey::object(key), to) + self.write_table_edge(from, EdgeKey::object(key), to) } /// Removes one object-key record. Another key, including a later generation @@ -506,22 +567,45 @@ impl LuaHeap { pub fn clear_object_edge(&mut self, from: TableRef, key: TableRef) -> Result<(), HeapError> { self.require_live(from)?; self.require_live(key)?; - let key = EdgeKey::object(key); + self.clear_edge(from, EdgeKey::object(key)); + Ok(()) + } + + fn clear_edge(&mut self, from: TableRef, key: EdgeKey) { self.edges .retain(|edge| edge.from != from.slot() || edge.key != key); - Ok(()) } - fn write_edge(&mut self, from: TableRef, key: EdgeKey, to: TableRef) -> Result<(), HeapError> { + fn write_table_edge( + &mut self, + from: TableRef, + key: EdgeKey, + to: TableRef, + ) -> Result<(), HeapError> { self.require_live(from)?; self.require_live(to)?; + self.write_edge( + from, + key, + EdgeValue::Table { + slot: to.slot(), + generation: to.generation(), + }, + ) + } + + fn write_edge( + &mut self, + from: TableRef, + key: EdgeKey, + value: EdgeValue, + ) -> Result<(), HeapError> { if let Some(edge) = self .edges .iter_mut() .find(|edge| edge.from == from.slot() && edge.key == key) { - edge.to_slot = to.slot(); - edge.to_generation = to.generation(); + edge.value = value; return Ok(()); } if self.edges.len() >= self.limits.edges as usize { @@ -530,16 +614,26 @@ impl LuaHeap { self.edges.push(Edge { from: from.slot(), key, - to_slot: to.slot(), - to_generation: to.generation(), + value, }); self.note_edge_peak(); Ok(()) } - /// Reads a reference edge through either alias of `from`. + /// Reads the table target of a direct field through either alias of `from`. pub fn edge(&self, from: TableRef, key: u32) -> Result, HeapError> { - self.read_edge(from, EdgeKey::Field(key)) + self.read_table_edge(from, EdgeKey::Field(key)) + } + + /// Reads a direct field as the guest value without metatable dispatch. + pub fn field_value(&self, from: TableRef, key: u32) -> Result { + match self.read_edge(from, EdgeKey::Field(key))? { + Some(EdgeValue::Table { slot, generation }) => { + self.issued_value(TableRef::table(self.domain, *slot, *generation)) + } + Some(EdgeValue::ModeScalar(value)) => Ok(value.clone()), + None => Ok(Value::Null), + } } /// Reads an object-key edge. The key generation must still be that live slot. @@ -549,22 +643,23 @@ impl LuaHeap { key: TableRef, ) -> Result, HeapError> { self.require_live(key)?; - self.read_edge(from, EdgeKey::object(key)) + self.read_table_edge(from, EdgeKey::object(key)) + } + + fn read_table_edge(&self, from: TableRef, key: EdgeKey) -> Result, HeapError> { + Ok(self + .read_edge(from, key)? + .and_then(EdgeValue::table) + .map(|(slot, generation)| TableRef::table(self.domain, slot, generation))) } - fn read_edge(&self, from: TableRef, key: EdgeKey) -> Result, HeapError> { + fn read_edge(&self, from: TableRef, key: EdgeKey) -> Result, HeapError> { self.require_live(from)?; - Ok(self.edges.iter().find_map(|edge| { - if edge.from == from.slot() && edge.key == key { - Some(TableRef::table( - self.domain, - edge.to_slot, - edge.to_generation, - )) - } else { - None - } - })) + Ok(self + .edges + .iter() + .find(|edge| edge.from == from.slot() && edge.key == key) + .map(|edge| &edge.value)) } /// Sets or clears the metatable ref. A table target is not encoded as a @@ -869,38 +964,61 @@ impl LuaHeap { } let follow_metatables = self.metatable_edges > 0; while let Some(slot) = work.pop() { + let mode = if follow_metatables { + self.follow_metatable(slot, &index, &mut work) + } else { + WeakMode::default() + }; let start = index.offsets[slot as usize] as usize; let end = index.offsets[slot as usize + 1] as usize; self.scan.outgoing_edge_checks += (end - start) as u64; for &entry in &index.entries[start..end] { - let edge = self.edges[entry as usize]; - if let EdgeKey::Object { slot, generation } = edge.key { + let edge = &self.edges[entry as usize]; + let (key, value) = (edge.key, edge.value.table()); + if !mode.keys + && let EdgeKey::Object { slot, generation } = key + { + self.follow_target(slot, generation, &mut work); + } + // LuaJIT traces k-mode values even when their keys are unmarked. + if !mode.values + && let Some((slot, generation)) = value + { self.follow_target(slot, generation, &mut work); } - self.follow_target(edge.to_slot, edge.to_generation, &mut work); - } - if follow_metatables { - self.follow_metatable(slot, &mut work); } } } /// Follows one stored metatable ref. Absent refs are not edges and are /// not counted. The caller skips this entirely when no ref is stored. - fn follow_metatable(&mut self, slot: u32, work: &mut Vec) { + fn follow_metatable( + &mut self, + slot: u32, + index: &OutgoingIndex, + work: &mut Vec, + ) -> WeakMode { let Some((to_slot, to_generation)) = self.slots[slot as usize].metatable else { - return; + return WeakMode::default(); }; self.scan.metatable_edge_checks += 1; - self.follow_target(to_slot, to_generation, work); + if self.follow_target(to_slot, to_generation, work) + && let Some(modes) = &index.weak_modes + { + self.scan.weak_mode_lookups += 1; + return modes[to_slot as usize]; + } + WeakMode::default() } - fn follow_target(&mut self, to_slot: u32, to_generation: u32, work: &mut Vec) { + fn follow_target(&mut self, to_slot: u32, to_generation: u32, work: &mut Vec) -> bool { self.scan.node_slot_visits += 1; - if self.slot_live(to_slot, to_generation) { - self.scan.node_slot_visits += 1; - self.mark_slot(to_slot, work); + if !self.slot_live(to_slot, to_generation) { + return false; } + self.scan.node_slot_visits += 1; + self.mark_slot(to_slot, work); + true } /// Two passes over the stored edge vector, plus one pass over the counts @@ -934,6 +1052,7 @@ impl LuaHeap { self.scan.scratch.index_cursor_copied += cursor.len() as u64; let mut entries = vec![0u32; running as usize]; self.scan.scratch.index_targets_inited += entries.len() as u64; + let mut weak_modes = None; for (entry, edge) in self.edges.iter().enumerate() { let from = edge.from as usize; if from >= slot_count { @@ -944,8 +1063,25 @@ impl LuaHeap { entries[at] = entry as u32; cursor[from] = cursor[from].saturating_add(1); } + if self.metatable_edges > 0 + && edge.key == EdgeKey::Field(Self::MODE_FIELD) + && let EdgeValue::ModeScalar(Value::String(mode)) = &edge.value + { + let mode = WeakMode::parse(mode, &mut self.scan.weak_mode_bytes); + if mode.keys || mode.values { + let modes = weak_modes.get_or_insert_with(|| { + self.scan.scratch.weak_modes_inited += slot_count as u64; + vec![WeakMode::default(); slot_count] + }); + modes[from] = mode; + } + } + } + OutgoingIndex { + offsets, + entries, + weak_modes, } - OutgoingIndex { offsets, entries } } /// One filter of the edge vector. Skipped when every live node is marked, @@ -961,9 +1097,11 @@ impl LuaHeap { self.scan.scratch.sweep_bitmap_inited += marked.len() as u64; self.scan.sweep_edge_checks += self.edges.len() as u64; let is_marked = |slot: u32| marked.get(slot as usize).copied().unwrap_or(false); + // Strong endpoints of a marked owner were already marked. For weak + // edges, either dead object endpoint invalidates the whole entry. self.edges.retain(|edge| { is_marked(edge.from) - && is_marked(edge.to_slot) + && edge.value.table().is_none_or(|(slot, _)| is_marked(slot)) && match edge.key { EdgeKey::Field(_) => true, EdgeKey::Object { slot, .. } => is_marked(slot), @@ -999,7 +1137,9 @@ impl LuaHeap { fn remove_edges_touching(&mut self, slot: u32) { self.edges.retain(|edge| { - edge.from != slot && edge.to_slot != slot && !edge_key_is_slot(edge.key, slot) + edge.from != slot + && edge.value.table().is_none_or(|(target, _)| target != slot) + && !edge_key_is_slot(edge.key, slot) }); } diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 3bbd397..392ed11 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -565,13 +565,25 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { Value::Int(key) => { // Only the private dot lowering emits an Int field id. let key = u32::try_from(key).map_err(|_| host_fault("invalid field id"))?; - let to = match classify(&mut call.vm().host_context(), &to_value)? { - heap::GuestClass::Table(table) => table, + let mut host = call.vm().host_context(); + match classify(&mut host, &to_value)? { + heap::GuestClass::Table(to) => { + heap::with_heap(&mut host, |heap| heap.set_edge(from, key, to)) + } + class + if key == heap::LuaHeap::MODE_FIELD + && (matches!(to_value, Value::Null) + || matches!( + class, + heap::GuestClass::String + | heap::GuestClass::Number + | heap::GuestClass::Boolean + )) => + { + heap::with_heap(&mut host, |heap| heap.set_mode_scalar(from, to_value)) + } _ => return Err(host_fault("edge target is not a table")), - }; - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.set_edge(from, key, to) - }) + } .map_err(heap_error)?; with_witness(call.vm(), |witness| { if witness.field_key.is_none() { @@ -815,21 +827,16 @@ fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { _ => return Err(host_fault("field source is not a table")), }; let mut host = call.vm().host_context(); - let target = if let Value::Int(key) = key_value { + if let Value::Int(key) = key_value { let key = u32::try_from(key).map_err(|_| host_fault("invalid field id"))?; - heap::with_heap(&mut host, |heap| heap.edge(table, key)) - } else { - let heap::GuestClass::Table(key) = classify(&mut host, &key_value)? else { - return Err(host_fault("edge key is not a table")); - }; - heap::with_heap(&mut host, |heap| heap.object_edge(table, key)) + return heap::with_heap(&mut host, |heap| heap.field_value(table, key)).map_err(heap_error); } - .map_err(heap_error)?; - let Some(target) = target else { - return Ok(Value::Null); + let heap::GuestClass::Table(key) = classify(&mut host, &key_value)? else { + return Err(host_fault("edge key is not a table")); }; - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.issued_value(target) + heap::with_heap(&mut host, |heap| match heap.object_edge(table, key)? { + Some(target) => heap.issued_value(target), + None => Ok(Value::Null), }) .map_err(heap_error) } @@ -1320,11 +1327,20 @@ impl Lower<'_> { .. }, _, - ) if self.in_function => { + ) => { let key = self.field_key(&name.bytes); + let temp_base = self.active_temps.len(); let from = self.expr(table)?; - let to = self.expr(value)?; - let expr = self.call(SET_EDGE, vec![from, Expr::Int(i64::from(key)), to])?; + let from = self.index_operand_slot(from, span)?; + let to = match value { + ast::Expr::Nil { .. } => Expr::Null, + other => self.expr(other)?, + }; + self.active_temps.truncate(temp_base); + let expr = self.call( + SET_EDGE, + vec![Expr::Var(from), Expr::Int(i64::from(key)), to], + )?; self.emit_ignored(expr, self.line(span)) } ( @@ -1683,6 +1699,9 @@ impl Lower<'_> { } fn field_key(&mut self, name: &[u8]) -> u32 { + if name == b"__mode" { + return heap::LuaHeap::MODE_FIELD; + } if let Some(key) = self.field_keys.get(name).copied() { return key; } @@ -1717,6 +1736,9 @@ impl Lower<'_> { fn expr(&mut self, expr: &ast::Expr) -> Result { match expr { ast::Expr::Table { fields, .. } if fields.is_empty() => self.call(NEW_TABLE, vec![]), + ast::Expr::String { bytes, .. } => String::from_utf8(bytes.clone()) + .map(Expr::String) + .map_err(|_| self.unsupported(expr.span())), ast::Expr::Number { raw, kind: ast::NumberKind::Integer | ast::NumberKind::Float, diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index d810ffb..7852b57 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -882,6 +882,274 @@ fn lua_candidate_omitting_the_collect_after_detach_keeps_the_metatable_target() assert_eq!(stats.live_nodes, 4); } +fn assert_weak_probe(source: &str, result: &str, live: &[bool], edges: u32, collections: u32) { + let mut vm = candidate(source); + assert_eq!( + vm.run().expect("execute weak-table probe"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string(result)]); + let mut host = vm.host_context(); + let observed = host.scope_state::>().unwrap().clone(); + assert_eq!(observed.len(), live.len()); + let resource_key = heap::LuaTableResource::key(); + for (index, (table, &expected)) in observed.iter().zip(live).enumerate() { + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(table.table))).unwrap(), + expected, + "table {index} heap liveness" + ); + assert_eq!( + host.borrow_resource_with_key::(table.token, &resource_key) + .is_ok(), + expected, + "table {index} token liveness" + ); + } + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.live_edges, edges, "stored entries after collection"); + assert_eq!(stats.collections, collections); +} + +#[test] +fn lua_candidate_weak_values_clear_entries_but_trace_keys() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local key = {} +local extra_key = {} +local cycle = {} +cycle.self = cycle +local other = {} +local rooted = {} +owner[key] = cycle +owner[extra_key] = other +owner.keep = rooted +observe_table(mt, 0) +observe_table(key, 0) +observe_table(extra_key, 0) +observe_table(cycle, 0) +observe_table(other, 0) +observe_table(rooted, 0) +mt = nil +extra_key = nil +cycle = nil +other = nil +collectgarbage("collect") +observe_table(owner.keep, 0) +return type(owner[key]) +"#; + assert_weak_probe( + source, + "nil", + &[true, true, true, false, false, true, true], + 2, + 1, + ); + let control = source.replace("collectgarbage(\"collect\")", ""); + assert_weak_probe(&control, "table", &[true; 7], 5, 0); +} + +#[test] +fn lua_candidate_weak_keys_trace_values_with_or_without_a_back_reference() { + let source = r#" +local mt = {} +mt.__mode = "k" +local owner = {} +setmetatable(owner, mt) +local dead_key = {} +local traced_value = {} +local back_key = {} +local back_value = {} +local rooted_key = {} +local rooted_value = {} +owner[dead_key] = traced_value +owner[back_key] = back_value +back_value.back = back_key +owner[rooted_key] = rooted_value +observe_table(dead_key, 0) +observe_table(traced_value, 0) +observe_table(back_key, 0) +observe_table(back_value, 0) +observe_table(rooted_key, 0) +observe_table(rooted_value, 0) +dead_key = nil +traced_value = nil +back_key = nil +back_value = nil +collectgarbage("collect") +return type(owner[rooted_key]) +"#; + assert_weak_probe( + source, + "table", + &[false, true, true, true, true, true], + 4, + 1, + ); + let both = source.replace(r#""k""#, r#""kv""#); + assert_weak_probe( + &both, + "table", + &[false, false, false, false, true, true], + 2, + 1, + ); + let control = both.replace(r#"collectgarbage("collect")"#, ""); + assert_weak_probe(&control, "table", &[true; 6], 5, 0); +} + +#[test] +fn lua_candidate_shared_metatable_uses_only_its_current_direct_mode() { + let source = r#" +local inherited = {} +inherited.__mode = "v" +local proxy = {} +proxy.__index = inherited +local mt = {} +setmetatable(mt, proxy) +local one = {} +local two = {} +setmetatable(one, mt) +setmetatable(two, mt) +local key = {} +local first = {} +local second = {} +local orphan = {} +one[key] = first +two[key] = second +observe_table(first, 0) +observe_table(second, 0) +observe_table(orphan, 0) +first = nil +second = nil +orphan = nil +collectgarbage("collect") +observe_table(one[key], 0) +observe_table(two[key], 0) +@change@ +@collect@ +return type(one[key]) +"#; + for (change, collect, result, live, edges) in [ + ( + r#"mt.__mode = "v""#, + true, + "nil", + [false, false, false, false, false], + 3, + ), + ( + r#"mt.__mode = "v""#, + false, + "table", + [true, true, false, true, true], + 5, + ), + ( + "setmetatable(one, inherited)", + true, + "nil", + [false, true, false, false, true], + 3, + ), + ( + "mt.__mode = 118", + true, + "table", + [true, true, false, true, true], + 5, + ), + ( + "mt.__mode = inherited", + true, + "table", + [true, true, false, true, true], + 5, + ), + ] { + let source = source.replace("@change@", change).replace( + "@collect@", + if collect { + r#"collectgarbage("collect")"# + } else { + "" + }, + ); + assert_weak_probe(&source, result, &live, edges, 1 + u32::from(collect)); + } +} + +#[test] +fn lua_candidate_deleting_shared_mode_restores_strong_edges() { + let source = r#" +local mt = {} +mt.__mode = "v" +setmetatable(mt, mt) +local one = {} +local two = {} +setmetatable(one, mt) +setmetatable(two, mt) +local key = {} +local first = {} +local second = {} +one[key] = first +two[key] = second +observe_table(first, 0) +observe_table(second, 0) +collectgarbage("collect") +@change@ +first = nil +second = nil +collectgarbage("collect") +return type(one[key]) +"#; + let read_mode = source + .replace("@change@", "") + .replace("type(one[key])", "mt.__mode"); + assert_weak_probe(&read_mode, "v", &[false, false], 1, 2); + let removed = source.replace("@change@", "mt.__mode = nil"); + assert_weak_probe(&removed, "table", &[true, true], 2, 2); + let unchanged = source.replace("@change@", ""); + assert_weak_probe(&unchanged, "nil", &[false, false], 1, 2); +} + +#[test] +fn shared_weak_mode_is_parsed_once_per_collection() { + let mut heap = heap::LuaHeap::new(heap::HeapLimits::production()); + let mt = heap.alloc().unwrap(); + let value = heap.alloc().unwrap(); + let mode = "x".repeat(1024) + "v"; + heap.set_mode_scalar(mt, Value::string(&mode)).unwrap(); + let count = 16; + let frame = heap.enter_roots(count).unwrap(); + for slot in 0..count { + let owner = heap.alloc().unwrap(); + heap.set_metatable(owner, Some(mt)).unwrap(); + heap.set_edge(owner, 1, value).unwrap(); + heap.write_root(frame, slot, owner).unwrap(); + } + + assert_eq!(heap.collect().marked_nodes, count + 1); + let meter = heap.take_scan_meter(); + assert_eq!(meter.weak_mode_bytes, mode.len() as u64); + assert_eq!(meter.weak_mode_lookups, u64::from(count)); + assert_eq!(meter.scratch.weak_modes_inited, u64::from(count + 2)); + assert_eq!(meter.outgoing_edge_checks, u64::from(count + 1)); + assert_eq!(meter.sweep_edge_checks, u64::from(count + 1)); + assert_eq!(heap.stats().live_edges, 1); + + heap.set_mode_scalar(mt, Value::Null).unwrap(); + assert_eq!(heap.collect().marked_nodes, count + 1); + let meter = heap.take_scan_meter(); + assert_eq!(meter.weak_mode_bytes, 0); + assert_eq!(meter.weak_mode_lookups, 0); + assert_eq!(meter.scratch.weak_modes_inited, 0); + assert_eq!(meter.sweep_edge_checks, 0); +} + /// `owner[key] = value`, a real bracket read, and `owner[key] = nil`. /// The key is a live table identity, not a field name or a guest number. #[test] From da43559f0e1ff57ec007425bc85c800850762d18 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 05:26:26 +0800 Subject: [PATCH 047/225] test(lua): cover weak field release and cleared entries (cherry picked from commit b90b8cef8479ed84c06ae2053c48b3bd5e938599) --- .../value_boundary_tests.rs | 74 ++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 7852b57..c981596 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -882,7 +882,13 @@ fn lua_candidate_omitting_the_collect_after_detach_keeps_the_metatable_target() assert_eq!(stats.live_nodes, 4); } -fn assert_weak_probe(source: &str, result: &str, live: &[bool], edges: u32, collections: u32) { +fn assert_weak_probe( + source: &str, + result: &str, + live: &[bool], + edges: u32, + collections: u32, +) -> Vec { let mut vm = candidate(source); assert_eq!( vm.run().expect("execute weak-table probe"), @@ -909,6 +915,7 @@ fn assert_weak_probe(source: &str, result: &str, live: &[bool], edges: u32, coll let stats = heap::stats(&mut host).unwrap(); assert_eq!(stats.live_edges, edges, "stored entries after collection"); assert_eq!(stats.collections, collections); + observed } #[test] @@ -952,6 +959,32 @@ return type(owner[key]) assert_weak_probe(&control, "table", &[true; 7], 5, 0); } +#[test] +fn lua_candidate_weak_value_in_a_dot_field_is_released() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local value = {} +owner.keep = value +observe_table(value, 0) +value = nil +collectgarbage("collect") +return type(owner.keep) +"#; + assert_weak_probe(source, "nil", &[false], 1, 1); + + let control = source.replace(r#"collectgarbage("collect")"#, ""); + assert_weak_probe(&control, "table", &[true], 2, 0); + let readback = control.replace( + "return type(owner.keep)", + "observe_table(owner.keep, 0)\nreturn type(owner.keep)", + ); + let observed = assert_weak_probe(&readback, "table", &[true, true], 2, 0); + assert_eq!(observed[0], observed[1], "original weak field referent"); +} + #[test] fn lua_candidate_weak_keys_trace_values_with_or_without_a_back_reference() { let source = r#" @@ -1116,6 +1149,45 @@ return type(one[key]) assert_weak_probe(&unchanged, "nil", &[false, false], 1, 2); } +#[test] +fn lua_candidate_deleting_shared_mode_does_not_restore_a_cleared_entry() { + let setup = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +local peer = {} +setmetatable(owner, mt) +setmetatable(peer, mt) +local key = {} +local value = {} +local kept = {} +owner[key] = value +peer[key] = kept +observe_table(value, 0) +observe_table(kept, 0) +value = nil +"#; + let collect = r#"collectgarbage("collect")"#; + let read = "return type(owner[key])"; + let first = format!("{setup}{collect}\nobserve_table(kept, 0)\n{read}"); + assert_weak_probe(&first, "nil", &[false, true, true], 2, 1); + + // The peer stays rooted through the first collection, then relies on its now strong entry. + let change = r#" +mt.__mode = nil +kept = nil +collectgarbage("collect") +observe_table(peer[key], 0) +"#; + let source = format!("{setup}{collect}{change}{read}"); + let observed = assert_weak_probe(&source, "nil", &[false, true, true], 1, 2); + assert_eq!(observed[1], observed[2], "original peer referent"); + + let control = format!("{setup}{change}{read}"); + let observed = assert_weak_probe(&control, "table", &[true, true, true], 2, 1); + assert_eq!(observed[1], observed[2], "original peer referent"); +} + #[test] fn shared_weak_mode_is_parsed_once_per_collection() { let mut heap = heap::LuaHeap::new(heap::HeapLimits::production()); From d4bf0c6c9d9a19c410ae893ab1e7b4d482891b59 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 06:25:08 +0800 Subject: [PATCH 048/225] feat(lua): retire chunk do roots on normal exit A top-level do block keeps shadowed outer slots in the existing safepoint list and drops only the bindings that scope declares. Leaving the block restores the outer name without putting a nil-cleared slot back. --- tests/luajit_heap_runtime/candidate.rs | 111 +++++++++- .../value_boundary_tests.rs | 189 ++++++++++++++++++ 2 files changed, 295 insertions(+), 5 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 392ed11..185d2f7 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1008,6 +1008,10 @@ pub(super) fn lower_returning( ) -> Result { let chunk = parser::parse_chunk(source.as_bytes()) .map_err(|error| ParseError::at_line(error.line as usize, error.message))?; + let resolution = resolve::resolve(&chunk); + if let Some(error) = resolution.errors.first() { + return Err(ParseError::at_line(1, format!("{error:?}"))); + } let mut lower = Lower { source, catalog, @@ -1029,6 +1033,8 @@ pub(super) fn lower_returning( return_names: HashSet::new(), root_slot: 0, ignored_slot: None, + resolution: &resolution, + binding_slots: vec![None; resolution.bindings.len()], }; if lower.receiver_width > 0 { let slot = lower.builder.alloc_local_named("#caller-frame")?; @@ -1041,9 +1047,6 @@ pub(super) fn lower_returning( }); lower.caller_frame = Some(slot); } - if let Some(error) = resolve::resolve(&chunk).errors.first() { - return Err(ParseError::at_line(1, format!("{error:?}"))); - } for stmt in &chunk.body.stmts { lower.lower_stmt(stmt)?; } @@ -1188,6 +1191,8 @@ struct Lower<'a> { return_names: HashSet>, root_slot: u32, ignored_slot: Option, + resolution: &'a resolve::Resolution, + binding_slots: Vec>, } #[derive(Clone, Copy)] @@ -1240,6 +1245,7 @@ impl Lower<'_> { Ok(()) } ast::Stmt::Empty { .. } => Ok(()), + ast::Stmt::Do { span, body } if !self.in_function => self.lower_do(*span, body), other => Err(ParseError::at_line( self.line(stmt_span(other)) as usize, "Lua statement not lowered yet", @@ -1247,6 +1253,101 @@ impl Lower<'_> { } } + /// Normal exit of one chunk `do`. Slots declared in this block leave + /// `live_locals`. Same-name outer slots stay where they are, including a + /// slot already removed by `= nil`. A function body is not this path. + fn lower_do(&mut self, span: ast::Span, body: &ast::Block) -> Result<(), ParseError> { + for stmt in &body.stmts { + self.lower_stmt(stmt)?; + } + self.retire_block(span, body) + } + + fn retire_block(&mut self, span: ast::Span, body: &ast::Block) -> Result<(), ParseError> { + let Some(scope_id) = self.block_scope(span, body) else { + return Ok(()); + }; + let ended: Vec = self + .resolution + .bindings + .iter() + .enumerate() + .filter(|(_, binding)| binding.function_id == 0 && binding.scope_id == scope_id) + .map(|(index, _)| index) + .collect(); + for index in ended { + let Some(slot) = self.binding_slots[index] else { + continue; + }; + self.live_locals.retain(|local| *local != slot); + let name = self.resolution.bindings[index].name.clone(); + if self.locals.get(&name).copied() == Some(slot) { + if let Some(outer) = self.visible_slot(&name, span.end) { + self.locals.insert(name, outer); + } else { + self.locals.remove(&name); + } + } + } + Ok(()) + } + + /// Scope of the locals this `do` itself declares. Nested blocks have a + /// different `visible_to`, and the chunk scope can share this statement's + /// end byte when the block is last. + fn block_scope(&self, span: ast::Span, body: &ast::Block) -> Option { + self.resolution.bindings.iter().find_map(|binding| { + let inside = binding.span.start >= body.span.start && binding.span.end <= body.span.end; + if binding.function_id == 0 && inside && binding.visible_to == span.end { + Some(binding.scope_id) + } else { + None + } + }) + } + + fn visible_slot(&self, name: &[u8], at: u32) -> Option { + let mut best: Option<(usize, u32)> = None; + for (index, binding) in self.resolution.bindings.iter().enumerate() { + if binding.function_id != 0 || binding.name != name { + continue; + } + if at < binding.visible_from || at >= binding.visible_to { + continue; + } + if best.is_none_or(|(_, from)| binding.visible_from >= from) { + best = Some((index, binding.visible_from)); + } + } + best.and_then(|(index, _)| self.binding_slots[index]) + } + + fn remember_binding( + &mut self, + span: ast::Span, + name: &ast::Name, + slot: LocalSlot, + ) -> Result<(), ParseError> { + if !self.in_function { + let index = self.chunk_binding(name, span)?; + self.binding_slots[index] = Some(slot); + } + self.locals.insert(name.bytes.clone(), slot); + Ok(()) + } + + fn chunk_binding(&self, name: &ast::Name, span: ast::Span) -> Result { + self.resolution + .bindings + .iter() + .position(|binding| { + binding.function_id == 0 + && binding.name == name.bytes + && binding.visible_from == span.end + }) + .ok_or_else(|| self.unsupported(span)) + } + fn lower_local( &mut self, span: ast::Span, @@ -1257,7 +1358,7 @@ impl Lower<'_> { let index = self .builder .alloc_local_named(&format!("#{}", span.start))?; - self.locals.insert(name.bytes.clone(), index); + self.remember_binding(span, name, index)?; self.live_locals.push(index); self.stmts.push(Stmt::Let { index, @@ -1600,7 +1701,7 @@ impl Lower<'_> { let index = self .builder .alloc_local_named(&format!("#{}:{offset}", span.start))?; - self.locals.insert(name.name.bytes.clone(), index); + self.remember_binding(span, &name.name, index)?; if self.next_receiver_slot >= self.receiver_width { return Err(self.unsupported(span)); } diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index c981596..f4a7c44 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -1453,3 +1453,192 @@ key = nil assert_eq!(host.resource_count(), if second_collect { 1 } else { 3 }); } } + +fn assert_table_lifetime(host: &mut vm::HostContext<'_>, table: ObservedTable, alive: bool) { + let resource_key = heap::LuaTableResource::key(); + assert_eq!( + heap::with_heap(host, |heap| Ok(heap.alive(table.table))).unwrap(), + alive, + "heap node {table:?}" + ); + assert_eq!( + host.borrow_resource_with_key::(table.token, &resource_key) + .is_ok(), + alive, + "resource token {table:?}" + ); +} + +// Chunk `do` normal exit. The inner `value` is a different binding from the +// outer one. An explicit collect inside the block must keep both, because the +// outer binding is still in its lifetime while shadowed. Leaving the block +// removes only the inner slot from the safepoint roots. It does not assign nil +// and does not roll the root list back. The weak `drop` entry therefore dies +// only on the next explicit collect; omitting that collect leaves the same table. +#[test] +fn lua_candidate_chunk_do_normal_exit_releases_shadow() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local value = {} +owner.keep = value +observe_table(value, 0) +do + local value = {} + owner.drop = value + observe_table(value, 0) + collectgarbage("collect") + observe_table(owner.keep, 0) + observe_table(owner.drop, 0) +end +@after@ +"#; + let collect_after = "\ +collectgarbage(\"collect\") +observe_table(value, 0) +observe_table(owner.keep, 0) +return type(owner.drop) +"; + let omit_after = "\ +observe_table(value, 0) +observe_table(owner.keep, 0) +observe_table(owner.drop, 0) +return type(owner.drop) +"; + for (after, result, collections, live_nodes, live_edges, resources) in [ + (collect_after, "nil", 2, 3, 2, 3), + (omit_after, "table", 1, 4, 3, 4), + ] { + let mut vm = candidate(&source.replace("@after@", after)); + assert_eq!(vm.run().expect("run chunk do"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string(result)], "{result}"); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let outer = tables[0]; + let inner = tables[1]; + let keep_inside = tables[2]; + let drop_inside = tables[3]; + let outer_after = tables[4]; + let keep_after = tables[5]; + assert_eq!( + keep_inside, outer, + "in-block collect keeps the outer object" + ); + assert_eq!( + drop_inside, inner, + "in-block collect keeps the inner object" + ); + assert_eq!(outer_after, outer, "the restored name is the outer object"); + assert_eq!(keep_after, outer, "owner.keep is the outer object"); + let drop_alive = result == "table"; + if drop_alive { + assert_eq!(tables[6], inner, "omitted collect leaves the inner object"); + } + for (table, alive) in [ + (outer, true), + (inner, drop_alive), + (keep_inside, true), + (drop_inside, drop_alive), + (outer_after, true), + (keep_after, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + if drop_alive { + assert_table_lifetime(&mut host, tables[6], true); + } + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, collections, "{result}"); + assert_eq!(stats.live_nodes, live_nodes, "{result}"); + assert_eq!(stats.live_edges, live_edges, "{result}"); + assert_eq!(stats.live_roots, 0, "{result}"); + assert_eq!(host.resource_count(), resources, "{result}"); + } +} + +// Nested normal exit retires only that block's slot. Clearing a non-shadowed +// outer local stays cleared: leaving the block must not put that slot back. +#[test] +fn lua_candidate_chunk_do_normal_exit_keeps_cleared_outer_dead() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local value = {} +local cleared = {} +owner.keep = value +owner.cleared = cleared +observe_table(value, 0) +observe_table(cleared, 0) +do + cleared = nil + local mid = {} + owner.mid = mid + observe_table(mid, 0) + do + local value = {} + owner.drop = value + observe_table(value, 0) + end + collectgarbage("collect") + observe_table(owner.keep, 0) + observe_table(owner.mid, 0) +end +collectgarbage("collect") +observe_table(value, 0) +observe_table(owner.keep, 0) +return type(owner.mid) +"#; + let mut vm = candidate(source); + assert_eq!(vm.run().expect("run nested chunk do"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let [ + outer, + cleared, + mid, + inner, + keep_inside, + mid_inside, + outer_after, + keep_after, + ] = tables.as_slice() + else { + panic!("expected eight observed tables, got {}", tables.len()); + }; + assert_eq!( + *keep_inside, *outer, + "shadowed outer stays live inside the block" + ); + assert_eq!(*mid_inside, *mid, "the mid binding is still in scope"); + assert_eq!(*outer_after, *outer); + assert_eq!(*keep_after, *outer); + for (table, alive) in [ + (*outer, true), + (*cleared, false), + (*mid, false), + (*inner, false), + (*keep_inside, true), + (*mid_inside, false), + (*outer_after, true), + (*keep_after, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + let stats = heap::stats(&mut host).unwrap(); + // First collect drops cleared and the nested value. Second collect drops mid. + assert_eq!( + ( + stats.collections, + stats.live_nodes, + stats.live_edges, + stats.live_roots + ), + (2, 3, 2, 0) + ); + assert_eq!(host.resource_count(), 3); +} From cedc659f788ad19b5554656a59a90a94b0fea1a5 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 07:06:23 +0800 Subject: [PATCH 049/225] fix(lua): release chunk do multi-return roots when the binding ends Reserve receiver slots declared inside a chunk do, and clear the published caller-frame root when that local slot expires or is assigned nil. An already-cleared slot is left alone. Outer slots and nested timing stay on the same release path. --- tests/luajit_heap_runtime/candidate.rs | 59 +++- .../value_boundary_tests.rs | 329 ++++++++++++++++++ 2 files changed, 370 insertions(+), 18 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 185d2f7..743570d 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1280,6 +1280,7 @@ impl Lower<'_> { continue; }; self.live_locals.retain(|local| *local != slot); + self.release_receiver_root(span, slot)?; let name = self.resolution.bindings[index].name.clone(); if self.locals.get(&name).copied() == Some(slot) { if let Some(outer) = self.visible_slot(&name, span.end) { @@ -1292,6 +1293,26 @@ impl Lower<'_> { Ok(()) } + /// Drops one published caller-frame root when its local slot leaves scope + /// or is assigned nil. A slot already cleared is absent from the map and + /// is left alone. This is the caller frame recorded for the chunk, not + /// the frame that is current while a callee runs. + fn release_receiver_root( + &mut self, + span: ast::Span, + slot: LocalSlot, + ) -> Result<(), ParseError> { + let Some(root_slot) = self.receiver_roots.remove(&slot) else { + return Ok(()); + }; + let frame = self.caller_frame.ok_or_else(|| self.unsupported(span))?; + let release = self.call( + RELEASE_RESULT, + vec![Expr::Var(frame), Expr::Float(root_slot as f64)], + )?; + self.emit_ignored(release, self.line(span)) + } + /// Scope of the locals this `do` itself declares. Nested blocks have a /// different `visible_to`, and the chunk scope can share this statement's /// end byte when the block is last. @@ -1410,14 +1431,7 @@ impl Lower<'_> { }); self.live_locals.retain(|local| *local != slot); // The name may now denote a shadow. Release the root of this slot only. - if let Some(root_slot) = self.receiver_roots.remove(&slot) { - let frame = self.caller_frame.ok_or_else(|| self.unsupported(span))?; - let release = self.call( - RELEASE_RESULT, - vec![Expr::Var(frame), Expr::Float(root_slot as f64)], - )?; - self.emit_ignored(release, self.line(span))?; - } + self.release_receiver_root(span, slot)?; Ok(()) } ( @@ -2148,19 +2162,28 @@ fn rooted_table_count(stmts: &[ast::Stmt]) -> u32 { fn chunk_receiver_width(stmts: &[ast::Stmt]) -> u32 { stmts.iter().fold(0u32, |count, stmt| { - let ast::Stmt::Local { names, values, .. } = stmt else { - return count; - }; - let [call] = values.exprs.as_slice() else { - return count; - }; - if !syntactic_direct_call(call) { - return count; - } - count.saturating_add(u32::try_from(names.len()).unwrap_or(u32::MAX)) + count.saturating_add(statement_receiver_width(stmt)) }) } +/// Direct multi-return receivers, including those declared in a chunk `do`. +/// A function body is a different frame and is not counted here. +fn statement_receiver_width(stmt: &ast::Stmt) -> u32 { + match stmt { + ast::Stmt::Local { names, values, .. } => { + let [call] = values.exprs.as_slice() else { + return 0; + }; + if !syntactic_direct_call(call) { + return 0; + } + u32::try_from(names.len()).unwrap_or(u32::MAX) + } + ast::Stmt::Do { body, .. } => chunk_receiver_width(&body.stmts), + _ => 0, + } +} + fn index_key_is_number(key: &ast::Expr) -> bool { match key { ast::Expr::Number { .. } => true, diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index f4a7c44..e8b9923 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -1642,3 +1642,332 @@ return type(owner.mid) ); assert_eq!(host.resource_count(), 3); } + +// Chunk `do` receives two tables from one synchronous call. The caller frame +// roots stay live through an explicit collect inside the block, so both weak +// entries keep the same identity. Leaving the block drops those two slots. +// The next collect clears the entries and closes their nodes and tokens. +// Omitting that collect leaves both entries. The outer call result is a +// different slot and stays. This is not a function body and not a goto. +#[test] +fn lua_candidate_chunk_do_releases_multi_return_roots() { + let source = r#" +local function pair() + local left = {} + local right = {} + local a = left + local b = right + return a, b +end +local function hold() + local kept = {} + local alias = kept + return alias +end +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local kept = hold() +owner.keep = kept +observe_table(kept, 0) +do + local left, right = pair() + owner.left = left + owner.right = right + observe_table(left, 0) + observe_table(right, 0) + collectgarbage("collect") + observe_table(owner.left, 0) + observe_table(owner.right, 0) + observe_table(owner.keep, 0) +end +@after@ +"#; + let collect_after = "\ +collectgarbage(\"collect\") +observe_table(kept, 0) +observe_table(owner.keep, 0) +return type(owner.@field@) +"; + let omit_after = "\ +observe_table(owner.left, 0) +observe_table(owner.right, 0) +observe_table(kept, 0) +observe_table(owner.keep, 0) +return type(owner.@field@) +"; + for (after, result, collections, live_nodes, live_edges, resources) in [ + (collect_after, "nil", 2u32, 3u32, 2u32, 3usize), + (omit_after, "table", 1, 5, 4, 5), + ] { + for field in ["left", "right"] { + let mut vm = candidate(&source.replace("@after@", &after.replace("@field@", field))); + assert_eq!( + vm.run().expect("run do multi-return"), + VmStatus::Halted, + "{result} {field}" + ); + assert_eq!(vm.stack(), &[Value::string(result)], "{result} {field}"); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let kept = tables[0]; + let left = tables[1]; + let right = tables[2]; + let left_inside = tables[3]; + let right_inside = tables[4]; + let keep_inside = tables[5]; + assert_eq!(left_inside, left, "in-block collect keeps the left result"); + assert_eq!( + right_inside, right, + "in-block collect keeps the right result" + ); + assert_eq!(keep_inside, kept, "in-block collect keeps the outer result"); + let drop_alive = result == "table"; + let (kept_after, keep_after) = if drop_alive { + assert_eq!(tables[6], left, "omitted collect leaves the left entry"); + assert_eq!(tables[7], right, "omitted collect leaves the right entry"); + (tables[8], tables[9]) + } else { + (tables[6], tables[7]) + }; + assert_eq!(kept_after, kept, "the outer local is the held result"); + assert_eq!(keep_after, kept, "owner.keep is the outer call result"); + for (table, alive) in [ + (kept, true), + (left, drop_alive), + (right, drop_alive), + (left_inside, drop_alive), + (right_inside, drop_alive), + (keep_inside, true), + (kept_after, true), + (keep_after, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + if drop_alive { + assert_table_lifetime(&mut host, tables[6], true); + assert_table_lifetime(&mut host, tables[7], true); + } + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, collections, "{result} {field}"); + assert_eq!(stats.live_nodes, live_nodes, "{result} {field}"); + assert_eq!(stats.live_edges, live_edges, "{result} {field}"); + assert_eq!(stats.live_roots, 0, "{result} {field}"); + assert_eq!(host.resource_count(), resources, "{result} {field}"); + } + } +} + +// Nested chunk `do` retires only that block's caller slots. An explicit nil +// inside the inner block has already cleared that slot; the sibling result +// stays until the inner block ends. The enclosing block's call results stay +// until that block ends. The outer call result stays through both exits. +#[test] +fn lua_candidate_chunk_do_releases_nested_multi_return_roots() { + let setup = r#" +local function pair() + local left = {} + local right = {} + local a = left + local b = right + return a, b +end +local function hold() + local kept = {} + local alias = kept + return alias +end +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local kept = hold() +owner.keep = kept +observe_table(kept, 0) +do + local mid_left, mid_right = pair() + owner.mid_left = mid_left + owner.mid_right = mid_right + observe_table(mid_left, 0) + observe_table(mid_right, 0) + do + local left, right = pair() + owner.left = left + owner.right = right + observe_table(left, 0) + observe_table(right, 0) + left = nil + collectgarbage("collect") + observe_table(owner.right, 0) +"#; + let nil_inside = r#" + observe_table(owner.mid_left, 0) + observe_table(owner.mid_right, 0) + observe_table(owner.keep, 0) + return type(owner.left) + end +end +"#; + let after_inner = r#" + end + collectgarbage("collect") + observe_table(owner.mid_left, 0) + observe_table(owner.mid_right, 0) + observe_table(owner.keep, 0) + return type(owner.@field@) +end +"#; + let after_mid = r#" + end + collectgarbage("collect") + observe_table(owner.mid_left, 0) + observe_table(owner.mid_right, 0) + observe_table(owner.keep, 0) +end +collectgarbage("collect") +observe_table(kept, 0) +observe_table(owner.keep, 0) +return type(owner.@field@) +"#; + let nil_source = format!("{setup}{nil_inside}"); + let mut vm = candidate(&nil_source); + assert_eq!(vm.run().expect("run nil inside do"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let [ + kept, + mid_left, + mid_right, + left, + right, + right_inside, + mid_left_inside, + mid_right_inside, + keep_inside, + ] = tables.as_slice() + else { + panic!("expected nine observed tables, got {}", tables.len()); + }; + assert_eq!( + *right_inside, *right, + "nil of left does not drop the sibling" + ); + assert_eq!(*mid_left_inside, *mid_left); + assert_eq!(*mid_right_inside, *mid_right); + assert_eq!(*keep_inside, *kept); + for (table, alive) in [ + (*kept, true), + (*mid_left, true), + (*mid_right, true), + (*left, false), + (*right, true), + (*right_inside, true), + (*mid_left_inside, true), + (*mid_right_inside, true), + (*keep_inside, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + + for field in ["left", "right"] { + let mut vm = candidate(&format!("{setup}{}", after_inner.replace("@field@", field))); + assert_eq!( + vm.run().expect("run after inner do"), + VmStatus::Halted, + "{field}" + ); + assert_eq!(vm.stack(), &[Value::string("nil")], "{field}"); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let [ + kept, + mid_left, + mid_right, + left, + right, + right_inside, + mid_left_after, + mid_right_after, + keep_after, + ] = tables.as_slice() + else { + panic!("expected nine observed tables, got {}", tables.len()); + }; + assert_eq!( + *right_inside, *right, + "sibling stays through the in-block collect" + ); + assert_eq!( + *mid_left_after, *mid_left, + "enclosing result stays after inner exit" + ); + assert_eq!(*mid_right_after, *mid_right); + assert_eq!(*keep_after, *kept); + for (table, alive) in [ + (*kept, true), + (*mid_left, true), + (*mid_right, true), + (*left, false), + (*right, false), + (*right_inside, false), + (*mid_left_after, true), + (*mid_right_after, true), + (*keep_after, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + } + + for field in ["mid_left", "mid_right"] { + let mut vm = candidate(&format!("{setup}{}", after_mid.replace("@field@", field))); + assert_eq!( + vm.run().expect("run after mid do"), + VmStatus::Halted, + "{field}" + ); + assert_eq!(vm.stack(), &[Value::string("nil")], "{field}"); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let kept = tables[0]; + let mid_left = tables[1]; + let mid_right = tables[2]; + let left = tables[3]; + let right = tables[4]; + let mid_left_inside = tables[6]; + let keep_inside = tables[8]; + let kept_after = tables[9]; + let keep_after = tables[10]; + assert_eq!( + mid_left_inside, mid_left, + "mid stays until its own block ends" + ); + assert_eq!(keep_inside, kept); + assert_eq!(kept_after, kept); + assert_eq!( + keep_after, kept, + "outer call result stays after both blocks" + ); + for (table, alive) in [ + (kept, true), + (mid_left, false), + (mid_right, false), + (left, false), + (right, false), + (mid_left_inside, false), + (keep_inside, true), + (kept_after, true), + (keep_after, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + let stats = heap::stats(&mut host).unwrap(); + assert_eq!( + (stats.collections, stats.live_nodes, stats.live_roots), + (3, 3, 0), + "{field}" + ); + assert_eq!(host.resource_count(), 3, "{field}"); + } +} From 1706ec244caea18a579c29e573e7c0da820389e4 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 07:39:14 +0800 Subject: [PATCH 050/225] fix(lua): release both receivers of a repeated chunk do local Match each chunk local to its resolver binding by the name token span. Repeated names in one statement share visible_from, so the first binding was overwritten and the shadowed receiver root stayed after the block. --- tests/luajit_heap_runtime/candidate.rs | 3 + .../value_boundary_tests.rs | 127 ++++++++++++++++++ 2 files changed, 130 insertions(+) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 743570d..807fb25 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1358,12 +1358,15 @@ impl Lower<'_> { } fn chunk_binding(&self, name: &ast::Name, span: ast::Span) -> Result { + // Repeated names in one statement share visible_from. The resolver + // stores each name token as Binding.span, which is the declaration. self.resolution .bindings .iter() .position(|binding| { binding.function_id == 0 && binding.name == name.bytes + && binding.span == name.span && binding.visible_from == span.end }) .ok_or_else(|| self.unsupported(span)) diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index e8b9923..afe3420 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -1971,3 +1971,130 @@ return type(owner.@field@) assert_eq!(host.resource_count(), 3, "{field}"); } } + +// Chunk `do` receives two tables from one call into one repeated local name. +// Resolver records each name token as its own binding: both share +// `visible_from` at the statement end, and `Binding.span` is that token's +// span. The visible name is the second receiver. An explicit collect inside +// the block keeps both caller-frame roots. Leaving the block drops both +// roots; the next explicit collect closes both nodes and Core tokens. The +// outer local of the same name is visible again. Omitting the post-block +// collect leaves both receivers, so a dead witness is not a missing +// allocation. `observe_table` inside `pair` records issuance and does not +// retain a VM Value. This candidate does not capture the chunk weak table. +// It is not a goto, a production `.lua` entry, a closure, or JIT/AOT. +#[test] +fn lua_candidate_chunk_do_releases_duplicate_receiver_roots() { + let source = r#" +local function pair() + local left = {} + local right = {} + observe_table(left, 0) + observe_table(right, 0) + local a = left + local b = right + return a, b +end +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local x = {} +owner.keep = x +observe_table(x, 0) +do + local x, x = pair() + owner.seen = x + observe_table(x, 0) + collectgarbage("collect") + observe_table(owner.seen, 0) + observe_table(owner.keep, 0) +end +@after@ +"#; + let collect_after = "\ +collectgarbage(\"collect\") +observe_table(x, 0) +observe_table(owner.keep, 0) +return type(owner.seen) +"; + let omit_after = "\ +observe_table(owner.seen, 0) +observe_table(x, 0) +observe_table(owner.keep, 0) +return type(owner.seen) +"; + for (after, result, collections, live_nodes, live_edges, resources) in [ + (omit_after, "table", 1u32, 5u32, 3u32, 5usize), + (collect_after, "nil", 2, 3, 2, 3), + ] { + let mut vm = candidate(&source.replace("@after@", after)); + assert_eq!( + vm.run().expect("run duplicate receivers"), + VmStatus::Halted, + "{result}" + ); + assert_eq!(vm.stack(), &[Value::string(result)], "{result}"); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + // pair runs inside the block, so its issuance witnesses follow the + // outer observation recorded before the call. + let outer = tables[0]; + let left = tables[1]; + let right = tables[2]; + let visible = tables[3]; + let seen_inside = tables[4]; + let keep_inside = tables[5]; + assert_ne!(left, right, "pair returns two tables"); + assert_eq!(visible, right, "the visible name is the second receiver"); + assert_ne!( + visible, left, + "the shadowed receiver is not the visible name" + ); + assert_eq!( + seen_inside, right, + "in-block collect keeps the visible receiver" + ); + assert_eq!( + keep_inside, outer, + "in-block collect keeps the outer object" + ); + let drop_alive = result == "table"; + let (seen_after, restored, keep_after) = if drop_alive { + assert_eq!( + tables[6], right, + "omitted collect leaves the visible receiver" + ); + (tables[6], tables[7], tables[8]) + } else { + (right, tables[6], tables[7]) + }; + assert_eq!(restored, outer, "the restored name is the outer object"); + assert_ne!(restored, right, "block exit does not keep the inner name"); + assert_eq!(keep_after, outer, "owner.keep is the outer object"); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(left.table))).unwrap(), + drop_alive, + "shadowed receiver after the block; result={result}" + ); + for (table, alive) in [ + (left, drop_alive), + (right, drop_alive), + (outer, true), + (visible, drop_alive), + (seen_inside, drop_alive), + (keep_inside, true), + (seen_after, drop_alive), + (restored, true), + (keep_after, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, collections, "{result}"); + assert_eq!(stats.live_nodes, live_nodes, "{result}"); + assert_eq!(stats.live_edges, live_edges, "{result}"); + assert_eq!(stats.live_roots, 0, "{result}"); + assert_eq!(host.resource_count(), resources, "{result}"); + } +} From 80bb1cfb71851c27f263cd89159622e8337ef061 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 05:59:48 +0800 Subject: [PATCH 051/225] feat(lua): keep ordinary string fields through weak collection Store a UTF-8 string in the same edge record as a table value. Weak v/kv collection still drops an unrooted table on that owner and does not clear the string. Field 0 remains the only key read as __mode. --- src/frontends/lua/heap/table.rs | 52 +++++--- tests/luajit_heap_runtime/candidate.rs | 13 +- .../value_boundary_tests.rs | 116 ++++++++++++++++++ 3 files changed, 159 insertions(+), 22 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index ef936ca..64ed7be 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -18,7 +18,7 @@ pub struct HeapLimits { pub nodes: u32, /// Simultaneous explicit root slots. pub roots: u32, - /// Live table-entry records, including a scalar `__mode` field. + /// Live table-entry records, including one scalar field value. pub edges: u32, /// Highest generation a slot may hold. The next release retires it. pub max_generation: u32, @@ -179,15 +179,20 @@ struct Edge { } enum EdgeValue { - Table { slot: u32, generation: u32 }, - ModeScalar(Value), + Table { + slot: u32, + generation: u32, + }, + /// One guest scalar in the same record as a table target. Field 0 is the + /// only key whose string is read as `__mode`. + Scalar(Value), } impl EdgeValue { fn table(&self) -> Option<(u32, u32)> { match self { Self::Table { slot, generation } => Some((*slot, *generation)), - Self::ModeScalar(_) => None, + Self::Scalar(_) => None, } } } @@ -531,23 +536,40 @@ impl LuaHeap { self.write_table_edge(from, EdgeKey::Field(key), to) } - /// Writes the non-reference scalar forms of the direct `__mode` field. - /// Nil deletes the record; other scalar values occupy the same edge quota. - pub fn set_mode_scalar(&mut self, from: TableRef, value: Value) -> Result<(), HeapError> { - debug_assert!(matches!( - value, - Value::Null | Value::String(_) | Value::Float(_) | Value::Bool(_) - )); + /// Writes a scalar into the same record and quota as a table edge. + /// + /// Nil deletes that record. A string may occupy any direct field. A number + /// or boolean remains a field 0 value; only that key's string is `__mode`. + pub fn set_field_scalar( + &mut self, + from: TableRef, + key: u32, + value: Value, + ) -> Result<(), HeapError> { + debug_assert!( + matches!(value, Value::Null | Value::String(_)) + || (key == Self::MODE_FIELD && matches!(value, Value::Float(_) | Value::Bool(_))) + ); self.require_live(from)?; - let key = EdgeKey::Field(Self::MODE_FIELD); + let key = EdgeKey::Field(key); if matches!(value, Value::Null) { self.clear_edge(from, key); Ok(()) } else { - self.write_edge(from, key, EdgeValue::ModeScalar(value)) + self.write_edge(from, key, EdgeValue::Scalar(value)) } } + /// Writes the non-reference forms of the direct `__mode` field. + /// Nil deletes the record; other scalar values occupy the same edge quota. + pub fn set_mode_scalar(&mut self, from: TableRef, value: Value) -> Result<(), HeapError> { + debug_assert!(matches!( + value, + Value::Null | Value::String(_) | Value::Float(_) | Value::Bool(_) + )); + self.set_field_scalar(from, Self::MODE_FIELD, value) + } + /// Writes one object-key edge in the same record and quota as a field edge. /// /// The key is the live slot and generation. A structurally equal carrier is @@ -631,7 +653,7 @@ impl LuaHeap { Some(EdgeValue::Table { slot, generation }) => { self.issued_value(TableRef::table(self.domain, *slot, *generation)) } - Some(EdgeValue::ModeScalar(value)) => Ok(value.clone()), + Some(EdgeValue::Scalar(value)) => Ok(value.clone()), None => Ok(Value::Null), } } @@ -1065,7 +1087,7 @@ impl LuaHeap { } if self.metatable_edges > 0 && edge.key == EdgeKey::Field(Self::MODE_FIELD) - && let EdgeValue::ModeScalar(Value::String(mode)) = &edge.value + && let EdgeValue::Scalar(Value::String(mode)) = &edge.value { let mode = WeakMode::parse(mode, &mut self.scan.weak_mode_bytes); if mode.keys || mode.values { diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 807fb25..d716501 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -571,16 +571,15 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { heap::with_heap(&mut host, |heap| heap.set_edge(from, key, to)) } class - if key == heap::LuaHeap::MODE_FIELD - && (matches!(to_value, Value::Null) - || matches!( + if matches!(class, heap::GuestClass::String) + || matches!(to_value, Value::Null) + || (key == heap::LuaHeap::MODE_FIELD + && matches!( class, - heap::GuestClass::String - | heap::GuestClass::Number - | heap::GuestClass::Boolean + heap::GuestClass::Number | heap::GuestClass::Boolean )) => { - heap::with_heap(&mut host, |heap| heap.set_mode_scalar(from, to_value)) + heap::with_heap(&mut host, |heap| heap.set_field_scalar(from, key, to_value)) } _ => return Err(host_fault("edge target is not a table")), } diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index afe3420..0daafa8 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -985,6 +985,122 @@ return type(owner.keep) assert_eq!(observed[0], observed[1], "original weak field referent"); } +/// Ordinary dot fields store one UTF-8 string in the same edge record as a table. +/// +/// The candidate lowerer has no concatenation, so the string is a literal placed +/// in a local and then cleared. That is the runnable stand-in for a dynamic +/// string that must not remain a local root. Field 0 stays the only `__mode` key. +#[test] +fn lua_candidate_weak_collection_keeps_an_ordinary_utf8_string_field() { + let kept = "kv-caf\u{e9}-42"; + let source = format!( + r#" +local mt = {{}} +mt.__mode = "@mode@" +local owner = {{}} +setmetatable(owner, mt) +local kept = "{kept}" +local drop = {{}} +owner.keep = kept +owner.drop = drop +observe_table(drop, 0) +kept = nil +drop = nil +collectgarbage("collect") +return owner.keep +"# + ); + for mode in ["v", "kv"] { + let source = source.replace("@mode@", mode); + assert_weak_probe(&source, kept, &[false], 2, 1); + } + let control = source + .replace("@mode@", "v") + .replace(r#"collectgarbage("collect")"#, ""); + assert_weak_probe(&control, kept, &[true], 3, 0); + + let ordinary_mode_text = r#" +local mt = {} +mt.note = "kv" +local owner = {} +setmetatable(owner, mt) +local drop = {} +owner.drop = drop +observe_table(drop, 0) +drop = nil +collectgarbage("collect") +return type(owner.drop) +"#; + assert_weak_probe(ordinary_mode_text, "table", &[true], 2, 1); + + let mode_stays_field_zero = format!( + r#" +local mt = {{}} +mt.__mode = "v" +mt.note = "k" +local owner = {{}} +setmetatable(owner, mt) +local kept = "{kept}" +local drop = {{}} +owner.keep = kept +owner.drop = drop +observe_table(drop, 0) +kept = nil +drop = nil +collectgarbage("collect") +return owner.keep +"# + ); + assert_weak_probe(&mode_stays_field_zero, kept, &[false], 3, 1); + + let deleted = format!( + r#" +local owner = {{}} +owner.keep = "{kept}" +owner.keep = nil +return type(owner.keep) +"# + ); + let mut vm = candidate(&deleted); + assert_eq!( + vm.run().expect("delete an ordinary string field"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let stats = heap::stats(&mut vm.host_context()).unwrap(); + assert_eq!(stats.live_edges, 0, "nil removes the string record"); + assert_eq!(stats.collections, 0); + + let string_over_table = format!( + r#" +local owner = {{}} +local drop = {{}} +owner.keep = drop +owner.keep = "{kept}" +observe_table(drop, 0) +return owner.keep +"# + ); + assert_weak_probe(&string_over_table, kept, &[true], 1, 0); + + let table_over_string = format!( + r#" +local owner = {{}} +local drop = {{}} +owner.keep = "{kept}" +owner.keep = drop +observe_table(drop, 0) +observe_table(owner.keep, 0) +return type(owner.keep) +"# + ); + let overwritten = assert_weak_probe(&table_over_string, "table", &[true, true], 1, 0); + assert_eq!( + overwritten[0], overwritten[1], + "table replaces the string record" + ); +} + #[test] fn lua_candidate_weak_keys_trace_values_with_or_without_a_back_reference() { let source = r#" From f9e2f65204dada83dabaa6edbbc627a47ec31cad Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 06:31:31 +0800 Subject: [PATCH 052/225] feat(lua): keep object-key strings through weak collection Store a string under an object key in the existing edge record. Weak k/kv still drop an unrooted key; v keeps it, and the string is never issued as a table token. --- src/frontends/lua/heap/table.rs | 42 +++- tests/luajit_heap_runtime/candidate.rs | 25 ++- .../value_boundary_tests.rs | 195 ++++++++++++++++++ 3 files changed, 242 insertions(+), 20 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 64ed7be..27b73b8 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -584,6 +584,22 @@ impl LuaHeap { self.write_table_edge(from, EdgeKey::object(key), to) } + /// Writes one string under an object key, in the same record and quota. + /// + /// Nil removal stays on [`Self::clear_object_edge`]. The string is not + /// issued as a table token and is not a second edge table. + pub fn set_object_scalar( + &mut self, + from: TableRef, + key: TableRef, + value: Value, + ) -> Result<(), HeapError> { + debug_assert!(matches!(value, Value::String(_))); + self.require_live(from)?; + self.require_live(key)?; + self.write_edge(from, EdgeKey::object(key), EdgeValue::Scalar(value)) + } + /// Removes one object-key record. Another key, including a later generation /// of the same slot, is a different identity and stays. pub fn clear_object_edge(&mut self, from: TableRef, key: TableRef) -> Result<(), HeapError> { @@ -649,13 +665,7 @@ impl LuaHeap { /// Reads a direct field as the guest value without metatable dispatch. pub fn field_value(&self, from: TableRef, key: u32) -> Result { - match self.read_edge(from, EdgeKey::Field(key))? { - Some(EdgeValue::Table { slot, generation }) => { - self.issued_value(TableRef::table(self.domain, *slot, *generation)) - } - Some(EdgeValue::Scalar(value)) => Ok(value.clone()), - None => Ok(Value::Null), - } + self.stored_value(from, EdgeKey::Field(key)) } /// Reads an object-key edge. The key generation must still be that live slot. @@ -668,6 +678,24 @@ impl LuaHeap { self.read_table_edge(from, EdgeKey::object(key)) } + /// Reads an object-key edge as the guest value. + /// + /// A stored string is that string. It is not decoded as a table token. + pub fn object_value(&self, from: TableRef, key: TableRef) -> Result { + self.require_live(key)?; + self.stored_value(from, EdgeKey::object(key)) + } + + fn stored_value(&self, from: TableRef, key: EdgeKey) -> Result { + match self.read_edge(from, key)? { + Some(EdgeValue::Table { slot, generation }) => { + self.issued_value(TableRef::table(self.domain, *slot, *generation)) + } + Some(EdgeValue::Scalar(value)) => Ok(value.clone()), + None => Ok(Value::Null), + } + } + fn read_table_edge(&self, from: TableRef, key: EdgeKey) -> Result, HeapError> { Ok(self .read_edge(from, key)? diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index d716501..656e85d 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -601,14 +601,17 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { }) .map_err(heap_error)?; } else { - let heap::GuestClass::Table(to) = - classify(&mut call.vm().host_context(), &to_value)? - else { - return Err(host_fault("edge target is not a table")); - }; - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.set_object_edge(from, key, to) - }) + let mut host = call.vm().host_context(); + let class = classify(&mut host, &to_value)?; + match class { + heap::GuestClass::Table(to) => { + heap::with_heap(&mut host, |heap| heap.set_object_edge(from, key, to)) + } + heap::GuestClass::String => heap::with_heap(&mut host, |heap| { + heap.set_object_scalar(from, key, to_value) + }), + _ => return Err(host_fault("edge target is not a table")), + } .map_err(heap_error)?; } } @@ -833,11 +836,7 @@ fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { let heap::GuestClass::Table(key) = classify(&mut host, &key_value)? else { return Err(host_fault("edge key is not a table")); }; - heap::with_heap(&mut host, |heap| match heap.object_edge(table, key)? { - Some(target) => heap.issued_value(target), - None => Ok(Value::Null), - }) - .map_err(heap_error) + heap::with_heap(&mut host, |heap| heap.object_value(table, key)).map_err(heap_error) } fn set_metatable(call: &mut OwnedHostCall<'_>) -> Result { diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 0daafa8..61acc44 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -1382,6 +1382,201 @@ return type(owner[alias_key]) assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); } +/// Object-key strings share the table edge record. They are not table tokens. +/// +/// Upstream LuaJIT `96f7b297` with `-joff` and Lua 5.2 compat, after the helper +/// returns and an explicit collect: `rawget(owner, kept_key)` is `stored-42` in +/// `k`/`v`/`kv`; `rawget(watch, "drop")` is nil and `owner` has 1 entry in `k` +/// and `kv`, and is a table with 2 entries in `v`. Omitting collect leaves the +/// drop key as a table and 2 owner entries in all three modes. +/// +/// Candidate adaptations, same literals: index reads stand in for `rawget` +/// because this lowerer has no metamethods; `live_edges` stands in for the +/// owner entry count (two `__mode` fields, `kept_key.owner`, `kept_key.watch`, +/// and the kept string are the five records that remain when the drop entry +/// and `watch.drop` are cleared); `collectgarbage("stop")` is omitted because +/// collection runs only at the explicit call. The candidate cannot capture +/// upvalues or return three tables, so `seed` returns `kept_key` and that key +/// holds `owner` and the weak-value watch by strong fields. Concatenation is +/// not lowered here; the string local is cleared so it is not a root. +#[test] +fn lua_candidate_weak_object_keys_retain_string_values() { + let source = r#" +local function seed() + local mt = {} + mt.__mode = "@mode@" + local owner = {} + setmetatable(owner, mt) + local kept_key = {} + local drop = {} + local watch_mt = {} + watch_mt.__mode = "v" + local watch = {} + setmetatable(watch, watch_mt) + local kept = "stored-42" + owner[kept_key] = kept + kept = nil + local stored = "drop-7" + owner[drop] = stored + stored = nil + watch.drop = drop + kept_key.owner = owner + kept_key.watch = watch + observe_table(drop, 0) + return kept_key +end +local kept_key = seed() +@collect@ +local owner = kept_key.owner +local watch = kept_key.watch +@return@ +"#; + let collect = "collectgarbage(\"collect\")\n"; + for mode in ["k", "v", "kv"] { + for (do_collect, drop_result, drop_alive, edges, collections) in [ + ( + true, + if mode == "v" { "table" } else { "nil" }, + mode == "v", + if mode == "v" { 7 } else { 5 }, + 1, + ), + (false, "table", true, 7, 0), + ] { + let body = source + .replace("@mode@", mode) + .replace("@collect@", if do_collect { collect } else { "" }); + assert_object_string( + &body.replace("@return@", "return owner[kept_key]\n"), + "stored-42", + drop_alive, + edges, + collections, + ); + assert_object_string( + &body.replace("@return@", "return type(watch.drop)\n"), + drop_result, + drop_alive, + edges, + collections, + ); + } + } +} + +/// One object key reuses one edge for a table, a string, and nil. +/// +/// A later generation of the same slot must not read the cleared string. +/// `live_edges` is the shared quota: overwrite does not add a record, nil +/// releases it, and a second key consumes a second record. +#[test] +fn lua_candidate_object_key_string_reuses_one_edge_record() { + let overwrite = r#" +local owner = {} +local key = {} +local other = {} +local value = {} +observe_table(value, 0) +owner[key] = "stored-42" +owner[other] = value +owner[key] = value +observe_table(owner[key], 0) +owner[key] = "stored-42" +owner[other] = nil +return owner[key] +"#; + let mut vm = candidate(overwrite); + assert_eq!( + vm.run() + .expect("overwrite an object key between table and string"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("stored-42")]); + let tables = vm + .host_context() + .scope_state::>() + .unwrap() + .clone(); + let [value, via_key] = tables.as_slice() else { + panic!("expected the table value and its readback"); + }; + assert_eq!(via_key, value, "string to table keeps the issued identity"); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); + + let reused = r#" +local owner = {} +local key = {} +observe_table(key, 0) +owner[key] = "stored-42" +owner[key] = nil +key = nil +collectgarbage("collect") +local reused = {} +observe_table(reused, 0) +return type(owner[reused]) +"#; + let mut vm = candidate(reused); + assert_eq!( + vm.run() + .expect("a reused object-key slot does not revive the string"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let [key, reused] = tables.as_slice() else { + panic!("expected the old key and the reused slot"); + }; + assert_eq!(reused.table.domain(), key.table.domain()); + assert_eq!(reused.table.kind(), key.table.kind()); + assert_eq!(reused.table.slot(), key.table.slot()); + assert_ne!(reused.table.generation(), key.table.generation()); + let resource_key = heap::LuaTableResource::key(); + assert!( + host.borrow_resource_with_key::(key.token, &resource_key) + .is_err() + ); + assert!( + host.borrow_resource_with_key::(reused.token, &resource_key) + .is_ok() + ); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.live_edges, 0); + assert_eq!(stats.collections, 1); +} + +fn assert_object_string( + source: &str, + result: &str, + drop_alive: bool, + edges: u32, + collections: u32, +) { + let mut vm = candidate(source); + assert_eq!(vm.run().expect("object-key string"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string(result)]); + let mut host = vm.host_context(); + let observed = host.scope_state::>().unwrap().clone(); + let [drop] = observed.as_slice() else { + panic!("expected the dropped object key"); + }; + let resource_key = heap::LuaTableResource::key(); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(drop.table))).unwrap(), + drop_alive, + "dropped key heap node" + ); + assert_eq!( + host.borrow_resource_with_key::(drop.token, &resource_key) + .is_ok(), + drop_alive, + "dropped key Core token" + ); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.live_edges, edges, "stored entries after collection"); + assert_eq!(stats.collections, collections); +} + #[test] fn lua_candidate_bracket_numbers_do_not_alias_private_field_ids() { let source = r#" From 9aa11b09d8a1f3e0a2a13e5a5adc26a1c72c6179 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 07:44:59 +0800 Subject: [PATCH 053/225] feat(lua): share one edge for dot and string keys Dot fields, bracket string literals, and dynamic UTF-8 keys write the same edge record. __mode stays the reserved field, including when it is written through a string local. Other text, including interior NUL, is compared in full and is not a collectable key. --- src/frontends/lua/heap/table.rs | 130 +++++-- tests/luajit_heap_runtime/candidate.rs | 76 ++-- tests/luajit_heap_runtime/return_frame.rs | 6 +- .../value_boundary_tests.rs | 327 ++++++++++++++++++ 4 files changed, 468 insertions(+), 71 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 27b73b8..12e5fcc 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -172,8 +172,9 @@ struct Slot { struct Edge { from: u32, - /// Field ids and object identities share this record. An object key is the - /// live slot and generation, not a guest number and not a second edge table. + /// Field ids, object identities, and full string text share this record. + /// An object key is the live slot and generation. A string key is the + /// complete UTF-8 text, not a guest number and not a second edge table. key: EdgeKey, value: EdgeValue, } @@ -197,10 +198,15 @@ impl EdgeValue { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] enum EdgeKey { Field(u32), - Object { slot: u32, generation: u32 }, + Object { + slot: u32, + generation: u32, + }, + /// Complete UTF-8 text, including interior NUL. Not a collectable table. + Utf8(String), } impl EdgeKey { @@ -210,6 +216,16 @@ impl EdgeKey { generation: key.generation(), } } + + /// One constructor for a Lua name. `__mode` is the reserved field id. + /// Every other name keeps its full text. + fn named(name: &str) -> Self { + if name == "__mode" { + Self::Field(LuaHeap::MODE_FIELD) + } else { + Self::Utf8(name.to_owned()) + } + } } struct Frame { @@ -553,13 +569,56 @@ impl LuaHeap { self.require_live(from)?; let key = EdgeKey::Field(key); if matches!(value, Value::Null) { - self.clear_edge(from, key); + self.clear_edge(from, &key); Ok(()) } else { self.write_edge(from, key, EdgeValue::Scalar(value)) } } + /// Writes a table under a Lua string key. + /// + /// `__mode` is the reserved field. Any other text is compared in full, + /// including interior NUL. The same text overwrites one record. + pub fn set_named_edge( + &mut self, + from: TableRef, + name: &str, + to: TableRef, + ) -> Result<(), HeapError> { + self.write_table_edge(from, EdgeKey::named(name), to) + } + + /// Writes a scalar under a Lua string key, or deletes that record on nil. + /// + /// A number or boolean is accepted only for the reserved mode field. The + /// direct numeric field API stays available for heap tests. + pub fn set_named_scalar( + &mut self, + from: TableRef, + name: &str, + value: Value, + ) -> Result<(), HeapError> { + let key = EdgeKey::named(name); + let mode = matches!(key, EdgeKey::Field(Self::MODE_FIELD)); + debug_assert!( + matches!(value, Value::Null | Value::String(_)) + || (mode && matches!(value, Value::Float(_) | Value::Bool(_))) + ); + self.require_live(from)?; + if matches!(value, Value::Null) { + self.clear_edge(from, &key); + Ok(()) + } else { + self.write_edge(from, key, EdgeValue::Scalar(value)) + } + } + + /// True when the name constructor selects the reserved mode field. + pub fn names_mode_field(name: &str) -> bool { + matches!(EdgeKey::named(name), EdgeKey::Field(Self::MODE_FIELD)) + } + /// Writes the non-reference forms of the direct `__mode` field. /// Nil deletes the record; other scalar values occupy the same edge quota. pub fn set_mode_scalar(&mut self, from: TableRef, value: Value) -> Result<(), HeapError> { @@ -605,13 +664,14 @@ impl LuaHeap { pub fn clear_object_edge(&mut self, from: TableRef, key: TableRef) -> Result<(), HeapError> { self.require_live(from)?; self.require_live(key)?; - self.clear_edge(from, EdgeKey::object(key)); + let key = EdgeKey::object(key); + self.clear_edge(from, &key); Ok(()) } - fn clear_edge(&mut self, from: TableRef, key: EdgeKey) { + fn clear_edge(&mut self, from: TableRef, key: &EdgeKey) { self.edges - .retain(|edge| edge.from != from.slot() || edge.key != key); + .retain(|edge| edge.from != from.slot() || &edge.key != key); } fn write_table_edge( @@ -660,12 +720,20 @@ impl LuaHeap { /// Reads the table target of a direct field through either alias of `from`. pub fn edge(&self, from: TableRef, key: u32) -> Result, HeapError> { - self.read_table_edge(from, EdgeKey::Field(key)) + let key = EdgeKey::Field(key); + self.read_table_edge(from, &key) + } + + /// Reads a Lua string key as a table target. `__mode` is the reserved field. + pub fn named_edge(&self, from: TableRef, name: &str) -> Result, HeapError> { + let key = EdgeKey::named(name); + self.read_table_edge(from, &key) } - /// Reads a direct field as the guest value without metatable dispatch. - pub fn field_value(&self, from: TableRef, key: u32) -> Result { - self.stored_value(from, EdgeKey::Field(key)) + /// Reads a Lua string key as the stored guest value, or nil when absent. + pub fn named_value(&self, from: TableRef, name: &str) -> Result { + let key = EdgeKey::named(name); + self.stored_value(from, &key) } /// Reads an object-key edge. The key generation must still be that live slot. @@ -675,7 +743,8 @@ impl LuaHeap { key: TableRef, ) -> Result, HeapError> { self.require_live(key)?; - self.read_table_edge(from, EdgeKey::object(key)) + let key = EdgeKey::object(key); + self.read_table_edge(from, &key) } /// Reads an object-key edge as the guest value. @@ -683,10 +752,11 @@ impl LuaHeap { /// A stored string is that string. It is not decoded as a table token. pub fn object_value(&self, from: TableRef, key: TableRef) -> Result { self.require_live(key)?; - self.stored_value(from, EdgeKey::object(key)) + let key = EdgeKey::object(key); + self.stored_value(from, &key) } - fn stored_value(&self, from: TableRef, key: EdgeKey) -> Result { + fn stored_value(&self, from: TableRef, key: &EdgeKey) -> Result { match self.read_edge(from, key)? { Some(EdgeValue::Table { slot, generation }) => { self.issued_value(TableRef::table(self.domain, *slot, *generation)) @@ -696,19 +766,23 @@ impl LuaHeap { } } - fn read_table_edge(&self, from: TableRef, key: EdgeKey) -> Result, HeapError> { + fn read_table_edge( + &self, + from: TableRef, + key: &EdgeKey, + ) -> Result, HeapError> { Ok(self .read_edge(from, key)? .and_then(EdgeValue::table) .map(|(slot, generation)| TableRef::table(self.domain, slot, generation))) } - fn read_edge(&self, from: TableRef, key: EdgeKey) -> Result, HeapError> { + fn read_edge(&self, from: TableRef, key: &EdgeKey) -> Result, HeapError> { self.require_live(from)?; Ok(self .edges .iter() - .find(|edge| edge.from == from.slot() && edge.key == key) + .find(|edge| edge.from == from.slot() && &edge.key == key) .map(|edge| &edge.value)) } @@ -1024,9 +1098,13 @@ impl LuaHeap { self.scan.outgoing_edge_checks += (end - start) as u64; for &entry in &index.entries[start..end] { let edge = &self.edges[entry as usize]; - let (key, value) = (edge.key, edge.value.table()); + let object_key = match &edge.key { + EdgeKey::Object { slot, generation } => Some((*slot, *generation)), + EdgeKey::Field(_) | EdgeKey::Utf8(_) => None, + }; + let value = edge.value.table(); if !mode.keys - && let EdgeKey::Object { slot, generation } = key + && let Some((slot, generation)) = object_key { self.follow_target(slot, generation, &mut work); } @@ -1152,9 +1230,9 @@ impl LuaHeap { self.edges.retain(|edge| { is_marked(edge.from) && edge.value.table().is_none_or(|(slot, _)| is_marked(slot)) - && match edge.key { - EdgeKey::Field(_) => true, - EdgeKey::Object { slot, .. } => is_marked(slot), + && match &edge.key { + EdgeKey::Field(_) | EdgeKey::Utf8(_) => true, + EdgeKey::Object { slot, .. } => is_marked(*slot), } }); } @@ -1189,7 +1267,7 @@ impl LuaHeap { self.edges.retain(|edge| { edge.from != slot && edge.value.table().is_none_or(|(target, _)| target != slot) - && !edge_key_is_slot(edge.key, slot) + && !edge_key_is_slot(&edge.key, slot) }); } @@ -1250,6 +1328,6 @@ impl LuaHeap { } } -fn edge_key_is_slot(key: EdgeKey, slot: u32) -> bool { - matches!(key, EdgeKey::Object { slot: key_slot, .. } if key_slot == slot) +fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { + matches!(key, EdgeKey::Object { slot: key_slot, .. } if *key_slot == slot) } diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 656e85d..df4b85f 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -449,12 +449,12 @@ fn carrier_ptr(value: &Value) -> Option { fn read_edge( heap: &heap::LuaHeap, table: Option, - key: Option, + key: Option<&str>, ) -> Result { let (Some(table), Some(key)) = (table, key) else { return Ok(EdgeView::Absent); }; - match heap.edge(table, key) { + match heap.named_edge(table, key) { Ok(Some(target)) => Ok(EdgeView::Live(target)), Ok(None) => Ok(EdgeView::Absent), Err(heap::HeapError::StaleHandle) => Ok(EdgeView::Stale), @@ -562,31 +562,31 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { _ => return Err(host_fault("edge source is not a table")), }; match key_value { - Value::Int(key) => { - // Only the private dot lowering emits an Int field id. - let key = u32::try_from(key).map_err(|_| host_fault("invalid field id"))?; + Value::String(name) => { let mut host = call.vm().host_context(); match classify(&mut host, &to_value)? { heap::GuestClass::Table(to) => { - heap::with_heap(&mut host, |heap| heap.set_edge(from, key, to)) + heap::with_heap(&mut host, |heap| heap.set_named_edge(from, &name, to)) } class if matches!(class, heap::GuestClass::String) || matches!(to_value, Value::Null) - || (key == heap::LuaHeap::MODE_FIELD + || (heap::LuaHeap::names_mode_field(&name) && matches!( class, heap::GuestClass::Number | heap::GuestClass::Boolean )) => { - heap::with_heap(&mut host, |heap| heap.set_field_scalar(from, key, to_value)) + heap::with_heap(&mut host, |heap| { + heap.set_named_scalar(from, &name, to_value) + }) } _ => return Err(host_fault("edge target is not a table")), } .map_err(heap_error)?; with_witness(call.vm(), |witness| { if witness.field_key.is_none() { - witness.field_key = Some(key); + witness.field_key = Some(name.to_string()); } })?; } @@ -671,14 +671,14 @@ fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { ( witness.returned, witness.discarded, - witness.field_key, + witness.field_key.clone(), witness.callee_depth, ) })?; let (returned_edge, discarded_edge) = heap::with_heap(&mut call.vm().host_context(), |heap| { Ok(( - read_edge(heap, returned, key)?, - read_edge(heap, discarded, key)?, + read_edge(heap, returned, key.as_deref())?, + read_edge(heap, discarded, key.as_deref())?, )) }) .map_err(heap_error)?; @@ -829,9 +829,9 @@ fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { _ => return Err(host_fault("field source is not a table")), }; let mut host = call.vm().host_context(); - if let Value::Int(key) = key_value { - let key = u32::try_from(key).map_err(|_| host_fault("invalid field id"))?; - return heap::with_heap(&mut host, |heap| heap.field_value(table, key)).map_err(heap_error); + if let Value::String(name) = key_value { + return heap::with_heap(&mut host, |heap| heap.named_value(table, &name)) + .map_err(heap_error); } let heap::GuestClass::Table(key) = classify(&mut host, &key_value)? else { return Err(host_fault("edge key is not a table")); @@ -888,11 +888,13 @@ fn release_result(call: &mut OwnedHostCall<'_>) -> Result { _ => return Err(host_fault("invalid result release")), }; let frame = decode_frame(call, &frame_token)?; - let (returned, key) = with_witness(call.vm(), |witness| (witness.returned, witness.field_key))?; + let (returned, key) = with_witness(call.vm(), |witness| { + (witness.returned, witness.field_key.clone()) + })?; let (alive, edge) = heap::with_heap(&mut call.vm().host_context(), |heap| { Ok(( returned.is_some_and(|table| heap.alive(table)), - read_edge(heap, returned, key)?, + read_edge(heap, returned, key.as_deref())?, )) }) .map_err(heap_error)?; @@ -922,7 +924,7 @@ fn note_collect( ( witness.returned, witness.discarded, - witness.field_key, + witness.field_key.clone(), witness.issued.last().copied(), ) }) @@ -934,7 +936,7 @@ fn note_collect( Ok(( returned.is_some_and(|table| heap.alive(table)), discarded.is_some_and(|table| heap.alive(table)), - read_edge(heap, returned, key)?, + read_edge(heap, returned, key.as_deref())?, latest.is_some_and(|table| heap.alive(table)), )) }) @@ -1025,7 +1027,6 @@ pub(super) fn lower_returning( next_receiver_slot: 0, receiver_width: chunk_receiver_width(&chunk.body.stmts), table_locals: HashSet::new(), - field_keys: HashMap::new(), publish_results, in_function: false, return_names: HashSet::new(), @@ -1183,7 +1184,6 @@ struct Lower<'a> { next_receiver_slot: u32, receiver_width: u32, table_locals: HashSet>, - field_keys: HashMap, u32>, publish_results: bool, in_function: bool, return_names: HashSet>, @@ -1444,7 +1444,7 @@ impl Lower<'_> { }, _, ) => { - let key = self.field_key(&name.bytes); + let key = utf8_field(&name.bytes).map_err(|_| self.unsupported(span))?; let temp_base = self.active_temps.len(); let from = self.expr(table)?; let from = self.index_operand_slot(from, span)?; @@ -1453,10 +1453,7 @@ impl Lower<'_> { other => self.expr(other)?, }; self.active_temps.truncate(temp_base); - let expr = self.call( - SET_EDGE, - vec![Expr::Var(from), Expr::Int(i64::from(key)), to], - )?; + let expr = self.call(SET_EDGE, vec![Expr::Var(from), Expr::String(key), to])?; self.emit_ignored(expr, self.line(span)) } ( @@ -1516,7 +1513,10 @@ impl Lower<'_> { "numeric table keys are not in this field-key subset", )); } - if !matches!(key, ast::Expr::Name { .. } | ast::Expr::Paren { .. }) { + if !matches!( + key, + ast::Expr::Name { .. } | ast::Expr::Paren { .. } | ast::Expr::String { .. } + ) { return Err(self.unsupported(key.span())); } let table = self.expr(base)?; @@ -1810,20 +1810,8 @@ impl Lower<'_> { expr: table, line: self.line(span), }); - let key = self.field_key(key_name); - self.call(GET_EDGE, vec![Expr::Var(slot), Expr::Int(i64::from(key))]) - } - - fn field_key(&mut self, name: &[u8]) -> u32 { - if name == b"__mode" { - return heap::LuaHeap::MODE_FIELD; - } - if let Some(key) = self.field_keys.get(name).copied() { - return key; - } - let key = u32::try_from(self.field_keys.len() + 1).expect("field key"); - self.field_keys.insert(name.to_vec(), key); - key + let key = utf8_field(key_name).map_err(|_| self.unsupported(span))?; + self.call(GET_EDGE, vec![Expr::Var(slot), Expr::String(key)]) } fn emit_ignored(&mut self, expr: Expr, line: u32) -> Result<(), ParseError> { @@ -2185,6 +2173,10 @@ fn statement_receiver_width(stmt: &ast::Stmt) -> u32 { } } +fn utf8_field(name: &[u8]) -> Result { + String::from_utf8(name.to_vec()).map_err(|_| ()) +} + fn index_key_is_number(key: &ast::Expr) -> bool { match key { ast::Expr::Number { .. } => true, @@ -2226,7 +2218,7 @@ pub(super) struct ReturnWitness { pub returned: Option, pub discarded: Option, pub returned_carrier: Option, - pub field_key: Option, + pub field_key: Option, pub returned_edge_at_handoff: EdgeView, pub discarded_edge_at_handoff: EdgeView, pub elements: Vec, diff --git a/tests/luajit_heap_runtime/return_frame.rs b/tests/luajit_heap_runtime/return_frame.rs index 6c2e9aa..bdda61d 100644 --- a/tests/luajit_heap_runtime/return_frame.rs +++ b/tests/luajit_heap_runtime/return_frame.rs @@ -1366,9 +1366,9 @@ fn numeric_table_keys_are_refused() { assert!(error.to_string().contains("numeric table keys"), "{error}"); } -fn assert_stale_edge(vm: &mut vm::Vm, table: heap::TableRef, key: Option) { +fn assert_stale_edge(vm: &mut vm::Vm, table: heap::TableRef, key: Option) { let key = key.expect("field key"); - let edge = heap::with_heap(&mut vm.host_context(), |heap| heap.edge(table, key)); + let edge = heap::with_heap(&mut vm.host_context(), |heap| heap.named_edge(table, &key)); assert!( matches!(edge, Err(heap::HeapError::StaleHandle)), "stale edge must stay structured, got {edge:?}" @@ -1937,7 +1937,7 @@ fn exported_chunk_reuses_one_root_slot_across_260_calls() { "round {round}: table handle is not reused before collect" ); let key = seen.field_key.expect("self field"); - let edge = heap::with_heap(&mut vm.host_context(), |heap| heap.edge(table, key)) + let edge = heap::with_heap(&mut vm.host_context(), |heap| heap.named_edge(table, &key)) .expect("self edge"); assert_eq!(edge, Some(table), "round {round}: self-loop is live"); let stats = heap::stats(&mut vm.host_context()).expect("stats after return"); diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 61acc44..b570d03 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -2409,3 +2409,330 @@ return type(owner.seen) assert_eq!(host.resource_count(), resources, "{result}"); } } + +fn assert_halted_string(source: &str, result: &str, edges: u32) { + let mut vm = candidate(source); + assert_eq!(vm.run().expect("string-key program"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string(result)]); + let stats = heap::stats(&mut vm.host_context()).unwrap(); + assert_eq!(stats.live_edges, edges, "stored entries"); + assert_eq!(stats.collections, 0); +} + +/// `t.name`, `t["name"]`, and `t[k]` are one record and one edge quota. +#[test] +fn lua_candidate_string_key_spellings_share_one_record() { + let shared = r#" +local owner = {} +local value = {} +owner.name = value +local bracket = owner["name"] +local k = "name" +local dynamic = owner[k] +observe_table(value, 0) +observe_table(bracket, 0) +observe_table(dynamic, 0) +return type(owner.name) +"#; + let mut vm = candidate(shared); + assert_eq!(vm.run().expect("shared string key"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("table")]); + let observed = vm + .host_context() + .scope_state::>() + .unwrap() + .clone(); + assert_eq!(observed.len(), 3); + assert_eq!( + observed[0], observed[1], + "bracket literal reads the dot record" + ); + assert_eq!( + observed[0], observed[2], + "dynamic string reads the dot record" + ); + let stats = heap::stats(&mut vm.host_context()).unwrap(); + assert_eq!(stats.live_edges, 1, "three spellings share one edge"); + assert_eq!(stats.collections, 0); + + assert_halted_string( + r#" +local owner = {} +local value = {} +owner["name"] = value +local k = "name" +owner[k] = value +owner.name = value +return type(owner["name"]) +"#, + "table", + 1, + ); + assert_halted_string( + r#" +local owner = {} +local k = "name" +owner.name = {} +owner[k] = nil +return type(owner["name"]) +"#, + "nil", + 0, + ); + assert_halted_string( + r#" +local owner = {} +owner["name"] = {} +owner.name = nil +local k = "name" +return type(owner[k]) +"#, + "nil", + 0, + ); + assert_halted_string( + r#" +local owner = {} +local key = {} +local value = {} +owner[key] = value +owner.name = value +owner["other"] = value +return type(owner.name) +"#, + "table", + 3, + ); +} + +/// A string local used as a key is the same record as the dot field. +#[test] +fn lua_candidate_string_key_dynamic_read_uses_the_same_record() { + assert_halted_string( + r#" +local owner = {} +local value = {} +owner.name = value +local k = "name" +return type(owner[k]) +"#, + "table", + 1, + ); + assert_halted_string( + r#" +local owner = {} +local k = "name" +owner[k] = {} +return type(owner.name) +"#, + "table", + 1, + ); + assert_halted_string( + r#" +local owner = {} +local k = "name" +owner.name = {} +owner[k] = nil +return type(owner.name) +"#, + "nil", + 0, + ); +} + +/// Full UTF-8 text is the key. A NUL does not end the key or collapse a prefix. +#[test] +fn lua_candidate_string_key_full_bytes_stay_distinct() { + let accent = "caf\u{e9}"; + assert_halted_string( + &format!( + r#" +local owner = {{}} +local accent = "{accent}" +owner[accent] = "accented" +owner["{accent}"] = "accented" +owner.cafe = "plain" +return owner["{accent}"] +"# + ), + "accented", + 2, + ); + assert_halted_string( + r#" +local owner = {} +owner.cafe = "plain" +return owner.cafe +"#, + "plain", + 1, + ); + assert_halted_string( + r#" +local owner = {} +local prefix = "ab\0" +owner[prefix] = "cut" +owner["ab"] = "short" +owner["ab\0c"] = "full" +return owner[prefix] +"#, + "cut", + 3, + ); + assert_halted_string( + r#" +local owner = {} +local prefix = "ab\0" +owner[prefix] = "cut" +owner["ab"] = "short" +owner["ab\0c"] = "full" +return owner["ab"] +"#, + "short", + 3, + ); + assert_halted_string( + r#" +local owner = {} +local prefix = "ab\0" +owner[prefix] = "cut" +owner["ab"] = "short" +owner["ab\0c"] = "full" +return owner["ab\0c"] +"#, + "full", + 3, + ); + assert_halted_string( + r#" +local owner = {} +local prefix = "ab\0" +owner[prefix] = "cut" +owner["ab"] = "short" +owner["ab\0c"] = "full" +return type(owner["ab\0d"]) +"#, + "nil", + 3, + ); +} + +/// `mt.__mode` and `mt[k]` with `k == "__mode"` are one scanned record. +/// A longer key that only starts with `__mode` is not a mode. +#[test] +fn lua_candidate_string_key_mode_enters_the_weak_scan() { + let collect = r#" +local mt = {} +local k = "__mode" +mt[k] = "v" +local owner = {} +setmetatable(owner, mt) +local drop = {} +local rooted = {} +local name = "name" +owner[name] = drop +observe_table(drop, 0) +observe_table(rooted, 0) +drop = nil +name = nil +collectgarbage("collect") +return type(owner.name) +"#; + assert_weak_probe(collect, "nil", &[false, true], 1, 1); + let omitted = collect.replace(r#"collectgarbage("collect")"#, ""); + assert_weak_probe(&omitted, "table", &[true, true], 2, 0); + + let keep_value = collect.replace("mt[k] = \"v\"", "mt[k] = \"k\""); + assert_weak_probe(&keep_value, "table", &[true, true], 2, 1); + let clear_value = collect.replace("mt[k] = \"v\"", "mt[k] = \"kv\""); + assert_weak_probe(&clear_value, "nil", &[false, true], 1, 1); + + let note = r#" +local mt = {} +local k = "note" +mt[k] = "v" +local owner = {} +setmetatable(owner, mt) +local drop = {} +owner.name = drop +observe_table(drop, 0) +drop = nil +collectgarbage("collect") +return type(owner.name) +"#; + assert_weak_probe(note, "table", &[true], 2, 1); + + let prefix = r#" +local mt = {} +local k = "__mode\0x" +mt[k] = "v" +local owner = {} +setmetatable(owner, mt) +local drop = {} +owner.name = drop +observe_table(drop, 0) +drop = nil +collectgarbage("collect") +return type(owner.name) +"#; + assert_weak_probe(prefix, "table", &[true], 2, 1); + + let overwritten = r#" +local mt = {} +mt.__mode = "x" +local k = "__mode" +mt[k] = "v" +local owner = {} +setmetatable(owner, mt) +local drop = {} +local rooted = {} +owner.name = drop +observe_table(drop, 0) +observe_table(rooted, 0) +drop = nil +collectgarbage("collect") +return type(owner.name) +"#; + assert_weak_probe(overwritten, "nil", &[false, true], 1, 1); + let overwritten_omitted = overwritten.replace(r#"collectgarbage("collect")"#, ""); + assert_weak_probe(&overwritten_omitted, "table", &[true, true], 2, 0); + + let restored = r#" +local mt = {} +local k = "__mode" +mt[k] = "v" +mt.__mode = "x" +local owner = {} +setmetatable(owner, mt) +local drop = {} +owner.name = drop +observe_table(drop, 0) +drop = nil +collectgarbage("collect") +return type(owner["name"]) +"#; + assert_weak_probe(restored, "table", &[true], 2, 1); + assert_halted_string( + r#" +local mt = {} +mt.__mode = "v" +local k = "__mode" +mt[k] = "kv" +return mt.__mode +"#, + "kv", + 1, + ); + assert_halted_string( + r#" +local mt = {} +local k = "__mode" +mt[k] = "v" +return mt["__mode"] +"#, + "v", + 1, + ); +} From 41fad46815f9d70cc457f542924b337058db42c9 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 08:12:27 +0800 Subject: [PATCH 054/225] fix(lua): compare string-key lookups without constructing a key named_edge and named_value no longer build EdgeKey::named. The shared edge scan compares the borrowed name with the stored key. __mode still selects the reserved field. Writes still store an owned string. --- src/frontends/lua/heap/table.rs | 63 ++++++++++++++++++++++++--------- 1 file changed, 47 insertions(+), 16 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 12e5fcc..6b58c71 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -217,15 +217,33 @@ impl EdgeKey { } } - /// One constructor for a Lua name. `__mode` is the reserved field id. - /// Every other name keeps its full text. + /// One constructor for a stored Lua name. `__mode` is the reserved field + /// id. Every other name keeps its full text. A lookup does not call this. fn named(name: &str) -> Self { - if name == "__mode" { + if Self::is_mode_name(name) { Self::Field(LuaHeap::MODE_FIELD) } else { Self::Utf8(name.to_owned()) } } + + /// The reserved mode name. Field id 0 is that key; a longer text is not. + fn is_mode_name(name: &str) -> bool { + name == "__mode" + } + + /// Compares a borrowed lookup name with this stored key. + /// + /// `__mode` matches the reserved field. Every other name matches stored + /// UTF-8 of the same length, including an interior NUL. An object key + /// does not match a name. This does not construct a key. + fn matches_name(&self, name: &str) -> bool { + if Self::is_mode_name(name) { + matches!(self, Self::Field(field) if *field == LuaHeap::MODE_FIELD) + } else { + matches!(self, Self::Utf8(stored) if stored == name) + } + } } struct Frame { @@ -721,19 +739,22 @@ impl LuaHeap { /// Reads the table target of a direct field through either alias of `from`. pub fn edge(&self, from: TableRef, key: u32) -> Result, HeapError> { let key = EdgeKey::Field(key); - self.read_table_edge(from, &key) + self.read_table_edge(from, |stored| stored == &key) } /// Reads a Lua string key as a table target. `__mode` is the reserved field. + /// + /// The name is borrowed for the comparison. This does not construct a key. pub fn named_edge(&self, from: TableRef, name: &str) -> Result, HeapError> { - let key = EdgeKey::named(name); - self.read_table_edge(from, &key) + self.read_table_edge(from, |stored| stored.matches_name(name)) } /// Reads a Lua string key as the stored guest value, or nil when absent. + /// + /// The name is borrowed for the comparison. This does not construct a key. + /// A cloned string in the returned value is the stored scalar, not the lookup. pub fn named_value(&self, from: TableRef, name: &str) -> Result { - let key = EdgeKey::named(name); - self.stored_value(from, &key) + self.stored_value(from, |stored| stored.matches_name(name)) } /// Reads an object-key edge. The key generation must still be that live slot. @@ -744,7 +765,7 @@ impl LuaHeap { ) -> Result, HeapError> { self.require_live(key)?; let key = EdgeKey::object(key); - self.read_table_edge(from, &key) + self.read_table_edge(from, |stored| stored == &key) } /// Reads an object-key edge as the guest value. @@ -753,11 +774,15 @@ impl LuaHeap { pub fn object_value(&self, from: TableRef, key: TableRef) -> Result { self.require_live(key)?; let key = EdgeKey::object(key); - self.stored_value(from, &key) + self.stored_value(from, |stored| stored == &key) } - fn stored_value(&self, from: TableRef, key: &EdgeKey) -> Result { - match self.read_edge(from, key)? { + fn stored_value( + &self, + from: TableRef, + matches_key: impl Fn(&EdgeKey) -> bool, + ) -> Result { + match self.read_edge(from, matches_key)? { Some(EdgeValue::Table { slot, generation }) => { self.issued_value(TableRef::table(self.domain, *slot, *generation)) } @@ -769,20 +794,26 @@ impl LuaHeap { fn read_table_edge( &self, from: TableRef, - key: &EdgeKey, + matches_key: impl Fn(&EdgeKey) -> bool, ) -> Result, HeapError> { Ok(self - .read_edge(from, key)? + .read_edge(from, matches_key)? .and_then(EdgeValue::table) .map(|(slot, generation)| TableRef::table(self.domain, slot, generation))) } - fn read_edge(&self, from: TableRef, key: &EdgeKey) -> Result, HeapError> { + /// One scan of the heap edge vector. `from` is checked before any key test. + /// The predicate selects the stored key. This does not build another table. + fn read_edge( + &self, + from: TableRef, + matches_key: impl Fn(&EdgeKey) -> bool, + ) -> Result, HeapError> { self.require_live(from)?; Ok(self .edges .iter() - .find(|edge| edge.from == from.slot() && &edge.key == key) + .find(|edge| edge.from == from.slot() && matches_key(&edge.key)) .map(|edge| &edge.value)) } From 2f45350f8a1804b207ef2ca076175e5a537de66d Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 09:10:05 +0800 Subject: [PATCH 055/225] feat(lua): retire chunk do roots on a trailing goto A same-block forward goto to the do end label skips the suffix and reuses retire_block, so executed bindings drop their caller-frame roots. The string-key union keeps that cut. One witness writes the weak value through a dynamic text index and reads it back with a dot and a literal bracket. Block exit still releases the same-name receiver. --- tests/luajit_heap_runtime/candidate.rs | 72 ++++- .../value_boundary_tests.rs | 262 ++++++++++++++++++ 2 files changed, 333 insertions(+), 1 deletion(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index df4b85f..d58a801 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1254,13 +1254,83 @@ impl Lower<'_> { /// Normal exit of one chunk `do`. Slots declared in this block leave /// `live_locals`. Same-name outer slots stay where they are, including a /// slot already removed by `= nil`. A function body is not this path. + /// + /// A resolver-proven `goto` to this block's trailing end label does not + /// emit the suffix. `retire_block` is still the exit, so executed bindings + /// drop their roots. This is not the `control.rs` state dispatcher, and + /// the target comes from the resolved label index rather than a bare name. fn lower_do(&mut self, span: ast::Span, body: &ast::Block) -> Result<(), ParseError> { - for stmt in &body.stmts { + let statements = match self.tail_goto_cut(span, body)? { + Some(cut) => &body.stmts[..cut], + None => body.stmts.as_slice(), + }; + for stmt in statements { self.lower_stmt(stmt)?; } self.retire_block(span, body) } + /// Index of the one direct `goto` whose resolved target is this block's + /// trailing end label. `None` keeps the straight path. A different goto + /// stays unsupported instead of falling through the suffix. + fn tail_goto_cut( + &self, + span: ast::Span, + body: &ast::Block, + ) -> Result, ParseError> { + let mut found = None; + for (index, stmt) in body.stmts.iter().enumerate() { + let ast::Stmt::Goto { + span: goto_span, .. + } = stmt + else { + continue; + }; + if found.is_some() { + return Err(self.statement_unsupported(*goto_span)); + } + found = Some((index, *goto_span)); + } + let Some((index, goto_span)) = found else { + return Ok(None); + }; + let Some(ast::Stmt::Label { name, .. }) = body.stmts.last() else { + return Err(self.statement_unsupported(goto_span)); + }; + if index + 1 >= body.stmts.len() { + return Err(self.statement_unsupported(goto_span)); + } + let jump = self + .resolution + .gotos + .iter() + .find(|jump| jump.span == goto_span && jump.function_id == 0); + let Some(jump) = jump else { + return Err(self.statement_unsupported(goto_span)); + }; + let Some(target) = jump.target else { + return Err(self.statement_unsupported(goto_span)); + }; + let Some(label) = self.resolution.labels.get(target) else { + return Err(self.statement_unsupported(goto_span)); + }; + let same_end = label.trailing && label.function_id == 0 && label.span == name.span; + if !same_end { + return Err(self.statement_unsupported(goto_span)); + } + if self + .block_scope(span, body) + .is_some_and(|scope_id| scope_id != label.scope_id) + { + return Err(self.statement_unsupported(goto_span)); + } + Ok(Some(index)) + } + + fn statement_unsupported(&self, span: ast::Span) -> ParseError { + ParseError::at_line(self.line(span) as usize, "Lua statement not lowered yet") + } + fn retire_block(&mut self, span: ast::Span, body: &ast::Block) -> Result<(), ParseError> { let Some(scope_id) = self.block_scope(span, body) else { return Ok(()); diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index b570d03..30096e9 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -2736,3 +2736,265 @@ return mt["__mode"] 1, ); } + +// Chunk `do` jumps to its own trailing end label. The resolver target is that +// label, not a same-named label in another block. Statements after the goto +// are not lowered, so `marker.ran = x` does not publish a strong edge. Both +// receivers from `pair` stay live through the in-block collect, including the +// shadowed first slot. Leaving the block retires those executed bindings. +// The next collect closes both nodes and Core tokens. Omitting it leaves +// them. The outer `x` is a different binding and stays. An adjacent label +// would not show this: the skipped field write is what the jump must avoid. +#[test] +fn lua_candidate_chunk_do_tail_goto_releases_executed_roots() { + let source = r#" +local function pair() + local left = {} + local right = {} + observe_table(left, 0) + observe_table(right, 0) + local a = left + local b = right + return a, b +end +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local marker = {} +local x = {} +owner.keep = x +observe_table(x, 0) +observe_table(marker, 0) +do + local x, x = pair() + owner.seen = x + observe_table(x, 0) + collectgarbage("collect") + observe_table(owner.seen, 0) + observe_table(owner.keep, 0) + goto tail + marker.ran = x + ::tail:: +end +@after@ +"#; + let collect_after = "\ +collectgarbage(\"collect\") +observe_table(x, 0) +observe_table(owner.keep, 0) +observe_table(marker, 0) +return type(owner.seen) +"; + let omit_after = "\ +observe_table(owner.seen, 0) +observe_table(x, 0) +observe_table(owner.keep, 0) +observe_table(marker, 0) +return type(owner.seen) +"; + // marker is an extra rooted table and adds no edge when the jump skips + // `marker.ran = x`. The duplicate-receiver counts are otherwise unchanged. + for (after, result, collections, live_nodes, live_edges, resources) in [ + (omit_after, "table", 1u32, 6u32, 3u32, 6usize), + (collect_after, "nil", 2, 4, 2, 4), + ] { + let mut vm = candidate(&source.replace("@after@", after)); + assert_eq!( + vm.run().expect("run tail goto"), + VmStatus::Halted, + "{result}" + ); + assert_eq!(vm.stack(), &[Value::string(result)], "{result}"); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let outer = tables[0]; + let marker = tables[1]; + let left = tables[2]; + let right = tables[3]; + let visible = tables[4]; + let seen_inside = tables[5]; + let keep_inside = tables[6]; + assert_ne!(left, right, "pair returns two tables"); + assert_ne!(marker, outer, "marker is not the outer local"); + assert_eq!(visible, right, "the visible name is the second receiver"); + assert_ne!( + visible, left, + "the shadowed receiver is not the visible name" + ); + assert_eq!( + seen_inside, right, + "in-block collect keeps the visible receiver" + ); + assert_eq!( + keep_inside, outer, + "in-block collect keeps the outer object" + ); + let drop_alive = result == "table"; + let (seen_after, restored, keep_after, marker_after) = if drop_alive { + assert_eq!( + tables[7], right, + "omitted collect leaves the visible receiver" + ); + (tables[7], tables[8], tables[9], tables[10]) + } else { + (right, tables[7], tables[8], tables[9]) + }; + assert_eq!(restored, outer, "the restored name is the outer object"); + assert_ne!(restored, right, "block exit does not keep the inner name"); + assert_eq!(keep_after, outer, "owner.keep is the outer object"); + assert_eq!(marker_after, marker, "the jump does not replace marker"); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(left.table))).unwrap(), + drop_alive, + "shadowed receiver after the block; result={result}" + ); + for (table, alive) in [ + (left, drop_alive), + (right, drop_alive), + (outer, true), + (marker, true), + (visible, drop_alive), + (seen_inside, drop_alive), + (keep_inside, true), + (seen_after, drop_alive), + (restored, true), + (keep_after, true), + (marker_after, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, collections, "{result}"); + assert_eq!(stats.live_nodes, live_nodes, "{result}"); + assert_eq!(stats.live_edges, live_edges, "{result}"); + assert_eq!(stats.live_roots, 0, "{result}"); + assert_eq!(host.resource_count(), resources, "{result}"); + } +} + +// Same trailing-label cut as the replayed goto. The weak write is +// `owner[k]` with a text local. Leaving the block still drops both +// same-name receiver roots. `owner.seen` and `owner["seen"]` read that +// one record. Collecting after the block retires the receiver token; +// omitting that collect leaves the same table. `marker.ran = x` remains +// after the goto, so a missed cut would keep the receiver. +#[test] +fn lua_candidate_chunk_do_tail_goto_string_key_releases_receiver() { + let source = r#" +local function pair() + local left = {} + local right = {} + observe_table(left, 0) + observe_table(right, 0) + local a = left + local b = right + return a, b +end +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +observe_table(owner, 0) +local marker = {} +local x = {} +owner.keep = x +observe_table(x, 0) +do + local x, x = pair() + local k = "seen" + owner[k] = x + collectgarbage("collect") + goto tail + marker.ran = x + ::tail:: +end +@after@ +"#; + let reads = ["owner.seen", r#"owner["seen"]"#]; + for collect in [false, true] { + for read in reads { + let after = if collect { + format!( + "collectgarbage(\"collect\")\n\ + return type({read})\n" + ) + } else { + format!( + "observe_table(owner.seen, 0)\n\ + observe_table(owner[\"seen\"], 0)\n\ + return type({read})\n" + ) + }; + let label = format!("collect={collect} read={read}"); + let mut vm = candidate(&source.replace("@after@", &after)); + assert_eq!( + vm.run().expect("run tail goto string key"), + VmStatus::Halted, + "{label}" + ); + let result = if collect { "nil" } else { "table" }; + assert_eq!(vm.stack(), &[Value::string(result)], "{label}"); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + let owner = tables[0]; + let outer = tables[1]; + let left = tables[2]; + let right = tables[3]; + assert_ne!(left, right, "pair returns two tables; {label}"); + assert_ne!(owner, outer, "owner is not the kept object; {label}"); + if !collect { + let dot = tables[4]; + let bracket = tables[5]; + assert_eq!( + dot, bracket, + "dot and literal bracket read the dynamic key; {label}" + ); + assert_eq!(dot, right, "that key is the visible receiver; {label}"); + assert_ne!( + dot, left, + "the shadowed receiver is not the stored value; {label}" + ); + } + let (seen, keep) = heap::with_heap(&mut host, |heap| { + Ok(( + heap.named_edge(owner.table, "seen")?, + heap.named_edge(owner.table, "keep")?, + )) + }) + .unwrap(); + assert_eq!( + keep, + Some(outer.table), + "owner.keep stays the outer object; {label}" + ); + if collect { + assert_eq!(seen, None, "the weak text key is cleared; {label}"); + } else { + assert_eq!( + seen, + Some(right.table), + "the dynamic write and both reads are one key; {label}" + ); + } + for (table, alive) in [ + (left, !collect), + (right, !collect), + (owner, true), + (outer, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, if collect { 2 } else { 1 }, "{label}"); + assert_eq!(stats.live_nodes, if collect { 4 } else { 6 }, "{label}"); + assert_eq!(stats.live_edges, if collect { 2 } else { 3 }, "{label}"); + assert_eq!(stats.live_roots, 0, "{label}"); + assert_eq!( + host.resource_count(), + if collect { 4 } else { 6 }, + "{label}" + ); + } + } +} From d1d5659243ded492c9a6e441103d6059c70b3ade Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 09:00:05 +0800 Subject: [PATCH 056/225] feat(lua): retire chunk do roots across a trailing label set A direct goto may land on any resolved label in that do's trailing set, including one followed by another label or an empty statement. The suffix stays omitted and retire_block still drops executed roots. --- tests/luajit_heap_runtime/candidate.rs | 46 ++- .../value_boundary_tests.rs | 309 +++++++++++++++++- 2 files changed, 322 insertions(+), 33 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index d58a801..5295929 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1255,12 +1255,14 @@ impl Lower<'_> { /// `live_locals`. Same-name outer slots stay where they are, including a /// slot already removed by `= nil`. A function body is not this path. /// - /// A resolver-proven `goto` to this block's trailing end label does not - /// emit the suffix. `retire_block` is still the exit, so executed bindings - /// drop their roots. This is not the `control.rs` state dispatcher, and - /// the target comes from the resolved label index rather than a bare name. + /// A resolver-proven `goto` whose target is in this block's trailing label + /// set does not emit the suffix. The set is every direct label the + /// resolver marked `trailing`: only labels and empty statements follow it. + /// The target index is matched to a direct child by that label's span, not + /// by name. `retire_block` is still the exit, so executed bindings drop + /// their roots. This is not the `control.rs` state dispatcher. fn lower_do(&mut self, span: ast::Span, body: &ast::Block) -> Result<(), ParseError> { - let statements = match self.tail_goto_cut(span, body)? { + let statements = match self.tail_goto_cut(body)? { Some(cut) => &body.stmts[..cut], None => body.stmts.as_slice(), }; @@ -1270,14 +1272,14 @@ impl Lower<'_> { self.retire_block(span, body) } - /// Index of the one direct `goto` whose resolved target is this block's - /// trailing end label. `None` keeps the straight path. A different goto + /// Index of the one direct `goto` whose resolved target is in this block's + /// trailing label set. `None` keeps the straight path. The resolver index + /// is matched to a direct child by label span, not by name, so a + /// same-named label in another block is not this target. A non-trailing + /// label in this block stays unsupported. `scope_id` is not a second + /// check: that direct-child span is already this block. A different goto /// stays unsupported instead of falling through the suffix. - fn tail_goto_cut( - &self, - span: ast::Span, - body: &ast::Block, - ) -> Result, ParseError> { + fn tail_goto_cut(&self, body: &ast::Block) -> Result, ParseError> { let mut found = None; for (index, stmt) in body.stmts.iter().enumerate() { let ast::Stmt::Goto { @@ -1294,12 +1296,6 @@ impl Lower<'_> { let Some((index, goto_span)) = found else { return Ok(None); }; - let Some(ast::Stmt::Label { name, .. }) = body.stmts.last() else { - return Err(self.statement_unsupported(goto_span)); - }; - if index + 1 >= body.stmts.len() { - return Err(self.statement_unsupported(goto_span)); - } let jump = self .resolution .gotos @@ -1314,14 +1310,12 @@ impl Lower<'_> { let Some(label) = self.resolution.labels.get(target) else { return Err(self.statement_unsupported(goto_span)); }; - let same_end = label.trailing && label.function_id == 0 && label.span == name.span; - if !same_end { - return Err(self.statement_unsupported(goto_span)); - } - if self - .block_scope(span, body) - .is_some_and(|scope_id| scope_id != label.scope_id) - { + let in_trailing_set = label.trailing + && label.function_id == 0 + && body.stmts.iter().any( + |stmt| matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span), + ); + if !in_trailing_set { return Err(self.statement_unsupported(goto_span)); } Ok(Some(index)) diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 30096e9..c14d8c6 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -41,21 +41,24 @@ impl SourcePlugin for CandidatePlugin { } fn candidate(source: &str) -> vm::Vm { + try_candidate(source).expect("compile Lua text") +} + +fn try_candidate(source: &str) -> Result { let catalog = Arc::clone(catalog()); let options = CompileSourceFileOptions::new() .with_source_plugin(&CandidatePlugin) .with_host_api_catalog(Arc::clone(&catalog)); - let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) - .expect("compile Lua text") - .into_vm() - .expect("create VM"); + let program = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .map_err(|error| format!("{error:?}"))?; + let mut vm = program.into_vm().map_err(|error| format!("{error:?}"))?; let mut registry = HostFunctionRegistry::empty(); - candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + candidate::register(&mut registry, &catalog).map_err(|error| format!("{error:?}"))?; register_witnesses(&mut registry, &catalog); registry .bind_vm_cached(&mut vm) - .expect("bind candidate runtime"); - vm + .map_err(|error| format!("{error:?}"))?; + Ok(vm) } #[test] @@ -2998,3 +3001,295 @@ end } } } + +/// `::tail::` followed by another label and `;`, and `::tail::` followed only +/// by `;`, are both in the block's trailing set. The goto is real: the local +/// after it would publish a receiver and run `fresh`, whose RHS observes two +/// tables and writes `box.kept`. An adjacent label does not skip that local; +/// the locked `-joff` fall arm does run it. This candidate only has the goto +/// arm. `omit` leaves the prefix receivers allocated, so a skipped root cannot +/// hide in the sweep. +#[test] +fn lua_candidate_chunk_do_trailing_label_set_skips_receiver_local() { + for (shape, suffix) in [ + ("label-and-empty", " ::tail::\n ::other::\n ;\n"), + ("empty-only", " ::tail::\n ;\n"), + ] { + assert_trailing_label_set_skips_receiver(shape, suffix); + } +} + +fn assert_trailing_label_set_skips_receiver(shape: &str, suffix: &str) { + let source = r#" +local function fresh() + local made = {} + local box = {} + box.kept = made + observe_table(made, 0) + observe_table(box, 0) + local out = made + return out +end +local function pair() + local left = {} + local right = {} + observe_table(left, 0) + observe_table(right, 0) + local a = left + local b = right + return a, b +end +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local marker = {} +local x = {} +owner.keep = x +observe_table(x, 0) +observe_table(marker, 0) +do + local x, x = pair() + owner.seen = x + observe_table(x, 0) + collectgarbage("collect") + observe_table(owner.seen, 0) + observe_table(owner.keep, 0) + goto tail + local x = fresh() + marker.ran = x +@suffix@end +@after@ +"# + .replace("@suffix@", suffix); + let collect_after = "\ +collectgarbage(\"collect\") +observe_table(x, 0) +observe_table(owner.keep, 0) +observe_table(marker, 0) +return type(owner.seen) +"; + let omit_after = "\ +observe_table(owner.seen, 0) +observe_table(x, 0) +observe_table(owner.keep, 0) +observe_table(marker, 0) +return type(owner.seen) +"; + for (after, result, collections, live_nodes, live_edges, resources, observations) in [ + (omit_after, "table", 1u32, 6u32, 3u32, 6usize, 11usize), + (collect_after, "nil", 2, 4, 2, 4, 10), + ] { + let mut vm = candidate(&source.replace("@after@", after)); + assert_eq!( + vm.run().expect("run trailing label set"), + VmStatus::Halted, + "{shape}/{result}" + ); + assert_eq!(vm.stack(), &[Value::string(result)], "{shape}/{result}"); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + assert_eq!( + tables.len(), + observations, + "{shape}/{result}: fresh() must not publish made or box" + ); + let outer = tables[0]; + let marker = tables[1]; + let left = tables[2]; + let right = tables[3]; + let visible = tables[4]; + let seen_inside = tables[5]; + let keep_inside = tables[6]; + assert_ne!(left, right, "{shape}/{result}"); + assert_ne!(marker, outer, "{shape}/{result}"); + assert_eq!(visible, right, "{shape}/{result}"); + assert_eq!(seen_inside, right, "{shape}/{result}"); + assert_eq!(keep_inside, outer, "{shape}/{result}"); + let drop_alive = result == "table"; + let (seen_after, restored, keep_after, marker_after) = if drop_alive { + (tables[7], tables[8], tables[9], tables[10]) + } else { + (right, tables[7], tables[8], tables[9]) + }; + assert_eq!(restored, outer, "{shape}/{result}: restored name is outer"); + assert_ne!(restored, right, "{shape}/{result}"); + assert_eq!(keep_after, outer, "{shape}/{result}"); + assert_eq!( + marker_after, marker, + "{shape}/{result}: marker.ran was not written" + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(left.table))).unwrap(), + drop_alive, + "{shape}/{result}" + ); + for (table, alive) in [ + (left, drop_alive), + (right, drop_alive), + (outer, true), + (marker, true), + (visible, drop_alive), + (seen_inside, drop_alive), + (keep_inside, true), + (seen_after, drop_alive), + (restored, true), + (keep_after, true), + (marker_after, true), + ] { + assert_table_lifetime(&mut host, table, alive); + } + let stats = heap::stats(&mut host).unwrap(); + let label = format!("{shape}/{result}"); + assert_eq!(stats.collections, collections, "{label}"); + assert_eq!(stats.live_nodes, live_nodes, "{label}"); + assert_eq!(stats.live_edges, live_edges, "{label}"); + assert_eq!(stats.live_roots, 0, "{label}"); + assert_eq!(host.resource_count(), resources, "{label}"); + } +} + +/// Same label text in two blocks. Each goto uses its own resolved target, so +/// the statement between the blocks still runs and neither `fresh` runs. +#[test] +fn lua_candidate_chunk_do_trailing_label_set_keeps_outer_statement() { + let source = r#" +local function fresh() + local made = {} + observe_table(made, 0) + local out = made + return out +end +local live = {} +observe_table(live, 0) +do + goto tail + local x = fresh() + ::tail:: + ::other:: + ; +end +observe_table(live, 0) +do + goto tail + local x = fresh() + ::tail:: + ; +end +observe_table(live, 0) +return type(live) +"#; + let mut vm = candidate(source); + assert_eq!( + vm.run().expect("run same-name trailing labels"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("table")]); + let host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + assert_eq!( + tables.len(), + 3, + "fresh must not publish, and the outer local must" + ); + assert_eq!(tables[0], tables[1]); + assert_eq!(tables[1], tables[2]); +} + +/// A non-trailing target is outside this cut. Accepting it and dropping the +/// local after that label would be a mis-cut. Rejection is not pinned. +#[test] +fn lua_candidate_trailing_label_set_does_not_cut_reachable_non_tail() { + let source = r#" +local live = {} +observe_table(live, 0) +do + goto mid + ::mid:: + local after = {} + observe_table(after, 0) + ::tail:: + ; +end +observe_table(live, 0) +return type(live) +"#; + let Ok(mut vm) = try_candidate(source) else { + return; + }; + assert_eq!(vm.run().expect("run non-tail"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("table")]); + let host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + assert!( + tables.len() >= 3, + "the local after the non-trailing label must still be lowered" + ); + assert_eq!(tables[0], tables[2]); + assert_ne!(tables[1], tables[0]); +} + +/// Resolver identity the cut uses. This does not pin a lowerer error. +#[test] +fn trailing_label_set_keeps_resolved_identity() { + let set = parser::parse_chunk( + b"do\n goto tail\n local x = 1\n ::tail::\n ::other::\n ;\nend\ndo\n goto tail\n local x = 1\n ::tail::\n ;\nend\n", + ) + .expect("parse trailing set"); + let resolution = resolve::resolve(&set); + assert!(resolution.errors.is_empty(), "{:?}", resolution.errors); + let first = resolution.gotos[0].target.expect("first tail"); + let second = resolution.gotos[1].target.expect("second tail"); + assert_ne!( + first, second, + "same name in another block is a different label" + ); + assert_eq!(resolution.labels[first].name, b"tail"); + assert_eq!(resolution.labels[second].name, b"tail"); + assert!(resolution.labels[first].trailing); + assert!(resolution.labels[second].trailing); + let other = resolution + .labels + .iter() + .find(|label| label.name == b"other") + .expect("other"); + assert!(other.trailing); + assert_ne!(other.span, resolution.labels[first].span); + + let nontail = parser::parse_chunk( + b"do\n goto mid\n ::mid::\n local after = 1\n ::tail::\n ;\nend\n", + ) + .expect("parse non-tail"); + let resolution = resolve::resolve(&nontail); + assert!(resolution.errors.is_empty(), "{:?}", resolution.errors); + let mid = resolution.gotos[0].target.expect("mid"); + assert_eq!(resolution.labels[mid].name, b"mid"); + assert!(!resolution.labels[mid].trailing); + + let cross = parser::parse_chunk( + b"do\n do\n goto tail\n local skipped = 1\n end\n local between = 1\n ::tail::\n ;\nend\n", + ) + .expect("parse cross-block"); + let resolution = resolve::resolve(&cross); + assert!(resolution.errors.is_empty(), "{:?}", resolution.errors); + let target = resolution.gotos[0].target.expect("outer tail"); + let label = &resolution.labels[target]; + assert!(label.trailing); + assert_eq!(label.name, b"tail"); + let ast::Stmt::Do { body: outer, .. } = &cross.body.stmts[0] else { + panic!("outer do"); + }; + let ast::Stmt::Do { body: inner, .. } = &outer.stmts[0] else { + panic!("inner do"); + }; + assert!( + inner.stmts.iter().all(|stmt| { + !matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span) + }) + ); + assert!( + outer.stmts.iter().any(|stmt| { + matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span) + }) + ); +} From 816cdb3221371675d37ccc852172e843987bae18 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 09:20:12 +0800 Subject: [PATCH 057/225] test(lua): jump to the second trailing label and drop the empty control The non-tail VM test returned on compilation refusal and asserted nothing. Resolver coverage already records that label. The receiver case now also jumps to the second trailing label, with two empty statements after the set. --- .../value_boundary_tests.rs | 86 +++++++------------ 1 file changed, 29 insertions(+), 57 deletions(-) diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index c14d8c6..d215b2f 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -41,24 +41,21 @@ impl SourcePlugin for CandidatePlugin { } fn candidate(source: &str) -> vm::Vm { - try_candidate(source).expect("compile Lua text") -} - -fn try_candidate(source: &str) -> Result { let catalog = Arc::clone(catalog()); let options = CompileSourceFileOptions::new() .with_source_plugin(&CandidatePlugin) .with_host_api_catalog(Arc::clone(&catalog)); - let program = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) - .map_err(|error| format!("{error:?}"))?; - let mut vm = program.into_vm().map_err(|error| format!("{error:?}"))?; + let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .expect("compile Lua text") + .into_vm() + .expect("create VM"); let mut registry = HostFunctionRegistry::empty(); - candidate::register(&mut registry, &catalog).map_err(|error| format!("{error:?}"))?; + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); register_witnesses(&mut registry, &catalog); registry .bind_vm_cached(&mut vm) - .map_err(|error| format!("{error:?}"))?; - Ok(vm) + .expect("bind candidate runtime"); + vm } #[test] @@ -3002,24 +2999,30 @@ end } } -/// `::tail::` followed by another label and `;`, and `::tail::` followed only -/// by `;`, are both in the block's trailing set. The goto is real: the local +/// Three tails share this goto arm. `::tail::` then `::other::` then `;`, +/// `::tail::` then only `;`, and a jump to that second label followed by two +/// `;`, are all in the block's trailing set. The goto is real: the local /// after it would publish a receiver and run `fresh`, whose RHS observes two -/// tables and writes `box.kept`. An adjacent label does not skip that local; -/// the locked `-joff` fall arm does run it. This candidate only has the goto -/// arm. `omit` leaves the prefix receivers allocated, so a skipped root cannot -/// hide in the sweep. +/// tables and writes `box.kept`. An adjacent label or a second `;` does not +/// itself skip that local; the locked `-joff` fall arm does run it. This +/// candidate only has the goto arm. `omit` leaves the prefix receivers +/// allocated, so a skipped root cannot hide in the sweep. #[test] fn lua_candidate_chunk_do_trailing_label_set_skips_receiver_local() { - for (shape, suffix) in [ - ("label-and-empty", " ::tail::\n ::other::\n ;\n"), - ("empty-only", " ::tail::\n ;\n"), + for (shape, target, suffix) in [ + ("label-and-empty", "tail", " ::tail::\n ::other::\n ;\n"), + ("empty-only", "tail", " ::tail::\n ;\n"), + ( + "second-label", + "other", + " ::tail::\n ::other::\n ;\n ;\n", + ), ] { - assert_trailing_label_set_skips_receiver(shape, suffix); + assert_trailing_label_set_skips_receiver(shape, target, suffix); } } -fn assert_trailing_label_set_skips_receiver(shape: &str, suffix: &str) { +fn assert_trailing_label_set_skips_receiver(shape: &str, target: &str, suffix: &str) { let source = r#" local function fresh() local made = {} @@ -3055,12 +3058,13 @@ do collectgarbage("collect") observe_table(owner.seen, 0) observe_table(owner.keep, 0) - goto tail + goto @jump@ local x = fresh() marker.ran = x @suffix@end @after@ "# + .replace("@jump@", target) .replace("@suffix@", suffix); let collect_after = "\ collectgarbage(\"collect\") @@ -3149,8 +3153,9 @@ return type(owner.seen) } } -/// Same label text in two blocks. Each goto uses its own resolved target, so -/// the statement between the blocks still runs and neither `fresh` runs. +/// Two same-name source blocks. The statement between them still runs, and +/// neither `fresh` runs. Matching a target by span rather than by name is a +/// resolver structural assertion; this VM case does not show that. #[test] fn lua_candidate_chunk_do_trailing_label_set_keeps_outer_statement() { let source = r#" @@ -3196,39 +3201,6 @@ return type(live) assert_eq!(tables[1], tables[2]); } -/// A non-trailing target is outside this cut. Accepting it and dropping the -/// local after that label would be a mis-cut. Rejection is not pinned. -#[test] -fn lua_candidate_trailing_label_set_does_not_cut_reachable_non_tail() { - let source = r#" -local live = {} -observe_table(live, 0) -do - goto mid - ::mid:: - local after = {} - observe_table(after, 0) - ::tail:: - ; -end -observe_table(live, 0) -return type(live) -"#; - let Ok(mut vm) = try_candidate(source) else { - return; - }; - assert_eq!(vm.run().expect("run non-tail"), VmStatus::Halted); - assert_eq!(vm.stack(), &[Value::string("table")]); - let host = vm.host_context(); - let tables = host.scope_state::>().unwrap().clone(); - assert!( - tables.len() >= 3, - "the local after the non-trailing label must still be lowered" - ); - assert_eq!(tables[0], tables[2]); - assert_ne!(tables[1], tables[0]); -} - /// Resolver identity the cut uses. This does not pin a lowerer error. #[test] fn trailing_label_set_keeps_resolved_identity() { From 79d5b9d95dcbbd0cc46209c70fb37f1ec1bb137c Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 10:22:12 +0800 Subject: [PATCH 058/225] feat(lua): store numeric keys on the same edge record A bracket number is canonical binary64 on the existing edge, not a field id and not a collectable node. Positive and negative zero share one record. A NaN read is nil; a NaN write reports the LuaJIT error and does not delete. --- src/frontends/lua/heap/table.rs | 79 +++- tests/luajit_heap_runtime/candidate.rs | 50 ++- tests/luajit_heap_runtime/return_frame.rs | 11 +- .../value_boundary_tests.rs | 419 +++++++++++++++++- 4 files changed, 531 insertions(+), 28 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 6b58c71..639af2c 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -60,6 +60,8 @@ pub enum HeapError { StaleFrame, /// The resource handle does not fit in a positive VM integer. CarrierOutOfRange, + /// A NaN is not a table key. LuaJIT reports this on write; a read is nil. + NanIndex, /// This scope already has a heap. AlreadyInstalled, /// Execution-scope or resource-table failure. `publish` rolls the reserved @@ -86,6 +88,7 @@ impl fmt::Display for HeapError { Self::NoRootFrame => write!(formatter, "no lua root frame"), Self::StaleFrame => write!(formatter, "stale lua root frame"), Self::CarrierOutOfRange => write!(formatter, "lua resource carrier out of range"), + Self::NanIndex => write!(formatter, "table index is NaN"), Self::AlreadyInstalled => write!(formatter, "lua heap already installed"), Self::Scope(message) => write!(formatter, "lua heap scope error: {message}"), } @@ -172,9 +175,10 @@ struct Slot { struct Edge { from: u32, - /// Field ids, object identities, and full string text share this record. - /// An object key is the live slot and generation. A string key is the - /// complete UTF-8 text, not a guest number and not a second edge table. + /// Field ids, object identities, string text, and binary64 numbers share + /// this record. An object key is the live slot and generation. A string + /// key is the complete UTF-8 text. A number key is canonical binary64 + /// bits, not a field id and not a collectable node. key: EdgeKey, value: EdgeValue, } @@ -207,6 +211,9 @@ enum EdgeKey { }, /// Complete UTF-8 text, including interior NUL. Not a collectable table. Utf8(String), + /// Canonical binary64 bits. Positive and negative zero share the zero + /// bits. A NaN is never stored. This is not a field id and not a node. + Number(u64), } impl EdgeKey { @@ -232,6 +239,14 @@ impl EdgeKey { name == "__mode" } + /// One constructor for a numeric key. `+0` and `-0` share the zero bits. + /// The caller refuses NaN before this runs. + fn number(number: f64) -> Self { + debug_assert!(!number.is_nan()); + let bits = if number == 0.0 { 0 } else { number.to_bits() }; + Self::Number(bits) + } + /// Compares a borrowed lookup name with this stored key. /// /// `__mode` matches the reserved field. Every other name matches stored @@ -687,6 +702,60 @@ impl LuaHeap { Ok(()) } + /// Writes one table under a binary64 key, in the same record as a field. + /// + /// NaN is refused before any lookup or insert. An integer resource carrier + /// is not a number key; callers pass `f64` only for `Value::Float`. + pub fn set_number_edge( + &mut self, + from: TableRef, + key: f64, + to: TableRef, + ) -> Result<(), HeapError> { + let key = Self::number_key(key)?; + self.write_table_edge(from, key, to) + } + + /// Writes one string under a binary64 key. Nil removal stays on + /// [`Self::clear_number_edge`]. + pub fn set_number_scalar( + &mut self, + from: TableRef, + key: f64, + value: Value, + ) -> Result<(), HeapError> { + debug_assert!(matches!(value, Value::String(_))); + let key = Self::number_key(key)?; + self.require_live(from)?; + self.write_edge(from, key, EdgeValue::Scalar(value)) + } + + /// Removes one binary64 record. A NaN write is an error and does not delete. + pub fn clear_number_edge(&mut self, from: TableRef, key: f64) -> Result<(), HeapError> { + let key = Self::number_key(key)?; + self.require_live(from)?; + self.clear_edge(from, &key); + Ok(()) + } + + /// Reads a binary64 key. NaN reads nil after the table is confirmed live. + /// `+0` and `-0` select the same record. + pub fn number_value(&self, from: TableRef, key: f64) -> Result { + self.require_live(from)?; + if key.is_nan() { + return Ok(Value::Null); + } + let key = EdgeKey::number(key); + self.stored_value(from, |stored| stored == &key) + } + + fn number_key(key: f64) -> Result { + if key.is_nan() { + return Err(HeapError::NanIndex); + } + Ok(EdgeKey::number(key)) + } + fn clear_edge(&mut self, from: TableRef, key: &EdgeKey) { self.edges .retain(|edge| edge.from != from.slot() || &edge.key != key); @@ -1131,7 +1200,7 @@ impl LuaHeap { let edge = &self.edges[entry as usize]; let object_key = match &edge.key { EdgeKey::Object { slot, generation } => Some((*slot, *generation)), - EdgeKey::Field(_) | EdgeKey::Utf8(_) => None, + EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => None, }; let value = edge.value.table(); if !mode.keys @@ -1262,7 +1331,7 @@ impl LuaHeap { is_marked(edge.from) && edge.value.table().is_none_or(|(slot, _)| is_marked(slot)) && match &edge.key { - EdgeKey::Field(_) | EdgeKey::Utf8(_) => true, + EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, EdgeKey::Object { slot, .. } => is_marked(*slot), } }); diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 5295929..25dbba5 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -552,6 +552,31 @@ fn root_issued(call: &mut OwnedHostCall<'_>) -> Result { Ok(Value::Float(0.0)) } +fn write_number_edge( + call: &mut OwnedHostCall<'_>, + from: heap::TableRef, + key: f64, + to_value: &Value, +) -> Result<(), VmError> { + if matches!(to_value, Value::Null) { + return heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.clear_number_edge(from, key) + }) + .map_err(heap_error); + } + let mut host = call.vm().host_context(); + match classify(&mut host, to_value)? { + heap::GuestClass::Table(to) => { + heap::with_heap(&mut host, |heap| heap.set_number_edge(from, key, to)) + } + heap::GuestClass::String => heap::with_heap(&mut host, |heap| { + heap.set_number_scalar(from, key, to_value.clone()) + }), + _ => return Err(host_fault("edge target is not a table")), + } + .map_err(heap_error) +} + fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { let (from, key_value, to_value) = match call.args() { [from, key, to] => (from.clone(), key.clone(), to.clone()), @@ -590,6 +615,8 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { } })?; } + // Binary64 only. An integer resource carrier is not a number key. + Value::Float(number) => write_number_edge(call, from, number, &to_value)?, other => { let heap::GuestClass::Table(key) = classify(&mut call.vm().host_context(), &other)? else { @@ -833,6 +860,10 @@ fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { return heap::with_heap(&mut host, |heap| heap.named_value(table, &name)) .map_err(heap_error); } + if let Value::Float(number) = key_value { + return heap::with_heap(&mut host, |heap| heap.number_value(table, number)) + .map_err(heap_error); + } let heap::GuestClass::Table(key) = classify(&mut host, &key_value)? else { return Err(host_fault("edge key is not a table")); }; @@ -1571,15 +1602,12 @@ impl Lower<'_> { key: &ast::Expr, span: ast::Span, ) -> Result<(LocalSlot, LocalSlot), ParseError> { - if index_key_is_number(key) { - return Err(ParseError::at_line( - self.line(span) as usize, - "numeric table keys are not in this field-key subset", - )); - } if !matches!( key, - ast::Expr::Name { .. } | ast::Expr::Paren { .. } | ast::Expr::String { .. } + ast::Expr::Name { .. } + | ast::Expr::Paren { .. } + | ast::Expr::String { .. } + | ast::Expr::Number { .. } ) { return Err(self.unsupported(key.span())); } @@ -2241,14 +2269,6 @@ fn utf8_field(name: &[u8]) -> Result { String::from_utf8(name.to_vec()).map_err(|_| ()) } -fn index_key_is_number(key: &ast::Expr) -> bool { - match key { - ast::Expr::Number { .. } => true, - ast::Expr::Paren { inner, .. } => index_key_is_number(inner), - _ => false, - } -} - fn syntactic_direct_call(expr: &ast::Expr) -> bool { matches!( expr, diff --git a/tests/luajit_heap_runtime/return_frame.rs b/tests/luajit_heap_runtime/return_frame.rs index bdda61d..38304fa 100644 --- a/tests/luajit_heap_runtime/return_frame.rs +++ b/tests/luajit_heap_runtime/return_frame.rs @@ -2,7 +2,8 @@ //! //! The sources are legal Lua. The callee's `Ret` still carries one value, the //! private ordered result array. The caller binds that array into locals and -//! reads those locals. `self` is an ordinary field name. Numeric keys are refused. +//! reads those locals. `self` is an ordinary field name. A numeric key is a +//! binary64 edge, not a private field id. An absent `t[1]` reads nil. use super::candidate::{self, EdgeView, ReturnWitness, ReturnedElement}; use super::{catalog, heap, register_witnesses}; @@ -1360,10 +1361,10 @@ fn assert_value_oracle() { } #[test] -fn numeric_table_keys_are_refused() { - let error = candidate::lower_returning("local t = {}; local n = t[1]\n", catalog(), true) - .expect_err("numeric keys stay outside this field-key subset"); - assert!(error.to_string().contains("numeric table keys"), "{error}"); +fn numeric_table_key_read_returns_nil_when_absent() { + let mut vm = run("local t = {}; local n = t[1]; return type(n)\n", true); + assert_eq!(vm.run().expect("absent numeric key"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); } fn assert_stale_edge(vm: &mut vm::Vm, table: heap::TableRef, key: Option) { diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index d215b2f..ea8d858 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -159,6 +159,20 @@ pub(super) fn catalog() -> &'static Arc { vec![HostParamSchema::value("number", HostTypeSchema::Float)], HostTypeSchema::Float, )); + builder.function(HostFunctionSchema::with_return( + "lua_host::float_bits", + vec![HostParamSchema::value("tag", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(HostFunctionSchema::with_return( + "lua_host::plant_private_field", + vec![ + HostParamSchema::with_passing("owner", table.clone(), HostParamPassing::Borrow), + HostParamSchema::with_passing("value", table, HostParamPassing::Borrow), + ], + HostTypeSchema::Bool, + )); builder.function(HostFunctionSchema::with_return( "lua_host::caller_reads", vec![ @@ -237,6 +251,8 @@ pub(super) fn register_witnesses( ("lua_host::observe_number", Witness::Number), ("lua_host::observe_table", Witness::TableAndNumber(0)), ("lua_host::observe_table_after", Witness::TableAndNumber(1)), + ("lua_host::float_bits", Witness::FloatBits), + ("lua_host::plant_private_field", Witness::PlantField), ] { let function = catalog.function(name).unwrap(); registry @@ -255,6 +271,8 @@ enum Witness { Tables, Number, TableAndNumber(usize), + FloatBits, + PlantField, } impl vm::HostOwnedFunction for Witness { @@ -309,11 +327,50 @@ impl vm::HostOwnedFunction for Witness { }; Value::Float(*number) } + Self::FloatBits => { + let [Value::Float(tag)] = args.as_slice() else { + panic!("expected float tag") + }; + Value::Float(special_float(*tag)) + } + Self::PlantField => { + let [owner, planted] = args.as_slice() else { + panic!("plant arity") + }; + let key = heap::LuaTableResource::key(); + let table_of = |value: &Value| { + let Value::Int(raw) = value else { + panic!("expected Core resource carrier") + }; + let handle = + vm::ResourceHandle::from_raw(u64::try_from(*raw).unwrap()).unwrap(); + host.borrow_resource_with_key::(handle, &key) + .unwrap() + .table() + }; + let owner = table_of(owner); + let planted = table_of(planted); + heap::with_heap(&mut host, |heap| heap.set_edge(owner, 1, planted)) + .expect("plant private field 1"); + Value::Bool(true) + } }; Ok(vm::CallOutcome::Return(vm::CallReturn::one(value))) } } +fn special_float(tag: f64) -> f64 { + // Candidate source cannot spell these. The tags are ordinary numbers. + // The returned binary64 values are the typed inputs. + match tag { + 1.0 => f64::from_bits(0x8000_0000_0000_0000), + 2.0 => f64::NAN, + 3.0 => f64::INFINITY, + 4.0 => f64::NEG_INFINITY, + _ => panic!("unknown float tag {tag}"), + } +} + #[test] fn lua_candidate_collect_preserves_an_already_evaluated_host_argument() { for (source, collections, marked, live, dead) in [ @@ -1579,7 +1636,7 @@ fn assert_object_string( #[test] fn lua_candidate_bracket_numbers_do_not_alias_private_field_ids() { - let source = r#" + let dynamic = r#" local function make() local owner = {} local value = {} @@ -1589,10 +1646,366 @@ end local owner = make() local number = 1 return type(owner[number]) +"#; + let mut vm = candidate(dynamic); + assert_eq!(vm.run().expect("dynamic numeric read"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + + let read = r#" +local owner = {} +local planted = {} +local named = {} +plant_private_field(owner, planted) +owner.field = named +owner["1"] = "text" +observe_table(owner, 0) +observe_table(planted, 0) +observe_table(named, 0) +return type(owner[1]) +"#; + let mut vm = candidate(read); + assert_eq!( + vm.run().expect("numeric read beside field 1"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("nil")]); + assert_private_field_untouched(&mut vm, 3); + + let written = r#" +local owner = {} +local planted = {} +local named = {} +plant_private_field(owner, planted) +owner.field = named +owner["1"] = "text" +owner[1] = "num" +owner[1.0] = "num" +observe_table(owner, 0) +observe_table(planted, 0) +observe_table(named, 0) +return owner[1] +"#; + let mut vm = candidate(written); + assert_eq!(vm.run().expect("numeric write"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("num")]); + assert_private_field_untouched(&mut vm, 4); + let owner = observed_tables(&mut vm)[0]; + let text = heap::with_heap(&mut vm.host_context(), |heap| { + heap.named_value(owner.table, "1") + }) + .unwrap(); + assert_eq!(text, Value::string("text")); +} + +fn assert_private_field_untouched(vm: &mut vm::Vm, edges: u32) { + let tables = observed_tables(vm); + let [owner, planted, named] = tables.as_slice() else { + panic!("expected owner, planted field, and named field"); + }; + let field = heap::with_heap(&mut vm.host_context(), |heap| heap.edge(owner.table, 1)).unwrap(); + assert_eq!( + field, + Some(planted.table), + "field id 1 stays the planted table" + ); + let by_name = heap::with_heap(&mut vm.host_context(), |heap| { + heap.named_edge(owner.table, "field") + }) + .unwrap(); + assert_eq!(by_name, Some(named.table)); + assert_eq!( + heap::stats(&mut vm.host_context()).unwrap().live_edges, + edges + ); +} + +fn observed_tables(vm: &mut vm::Vm) -> Vec { + vm.host_context() + .scope_state::>() + .unwrap() + .clone() +} + +#[test] +fn lua_candidate_numeric_key_reuses_one_record() { + let overwrite = r#" +local owner = {} +local value = {} +owner[1] = "first" +local k = 1.0 +owner[k] = value +observe_table(value, 0) +observe_table(owner[1], 0) +owner[1] = "second" +return owner[1.0] +"#; + let mut vm = candidate(overwrite); + assert_eq!( + vm.run().expect("overwrite one numeric record"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("second")]); + let tables = observed_tables(&mut vm); + assert_eq!( + tables[0], tables[1], + "literal and dynamic read the same table" + ); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); + + let missing = "local owner = {}\nowner[2] = nil\nreturn type(owner[2])\n"; + let mut vm = candidate(missing); + assert_eq!( + vm.run().expect("nil write to a missing numeric key"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("nil")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 0); + + let deleted = r#" +local owner = {} +local value = {} +value.self = value +observe_table(value, 0) +owner[1] = value +value = nil +owner[1] = nil +return type(owner[1]) +"#; + for collect in [false, true] { + let source = if collect { + deleted.replace( + "return type(owner[1])", + "collectgarbage(\"collect\")\nreturn type(owner[1])", + ) + } else { + deleted.to_string() + }; + let mut vm = candidate(&source); + assert_eq!(vm.run().expect("nil delete"), VmStatus::Halted, "{collect}"); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let value = observed_tables(&mut vm)[0]; + let alive = + heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.alive(value.table))).unwrap(); + let token_alive = vm + .host_context() + .borrow_resource_with_key::( + value.token, + &heap::LuaTableResource::key(), + ) + .is_ok(); + assert_eq!(alive, !collect, "heap node after nil delete"); + assert_eq!(token_alive, !collect, "token after nil delete"); + let stats = heap::stats(&mut vm.host_context()).unwrap(); + // The numeric record is gone. The value's own self edge remains until + // the explicit collection that reclaims the unrooted node. + assert_eq!(stats.live_edges, u32::from(!collect)); + assert_eq!(stats.collections, u32::from(collect)); + } +} + +#[test] +fn lua_candidate_numeric_fraction_does_not_alias_one_or_field_id() { + let source = r#" +local owner = {} +local planted = {} +plant_private_field(owner, planted) +owner[1.5] = "half" +local k = 1.5 +observe_table(owner, 0) +observe_table(planted, 0) +return owner[k] "#; let mut vm = candidate(source); - assert!(matches!(vm.run(), Err(vm::VmError::HostError(message)) - if message == "edge key is not a table")); + assert_eq!(vm.run().expect("fraction key"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("half")]); + let tables = observed_tables(&mut vm); + let field = + heap::with_heap(&mut vm.host_context(), |heap| heap.edge(tables[0].table, 1)).unwrap(); + assert_eq!(field, Some(tables[1].table)); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 2); + + let other = source.replace("return owner[k]", "return type(owner[1])"); + let mut vm = candidate(&other); + assert_eq!( + vm.run().expect("integer key stays absent"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let text = source.replace("return owner[k]", "return type(owner[\"1.5\"])"); + let mut vm = candidate(&text); + assert_eq!(vm.run().expect("text key stays absent"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); +} + +#[test] +fn lua_candidate_numeric_zero_does_not_alias_mode_field() { + let mode = r#" +local mt = {} +mt.__mode = "v" +mt[0] = "zero" +return mt.__mode +"#; + let mut vm = candidate(mode); + assert_eq!(vm.run().expect("mode field"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("v")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 2); + + let zero = mode.replace("return mt.__mode", "return mt[0]"); + let mut vm = candidate(&zero); + assert_eq!(vm.run().expect("numeric zero"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("zero")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 2); +} + +#[test] +fn lua_candidate_weak_numeric_value_clears_only_after_collect() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local value = {} +value.self = value +local orphan = {} +orphan.self = orphan +owner[1] = value +observe_table(orphan, 0) +observe_table(value, 0) +orphan = nil +@collect@ +return type(owner[1]) +"#; + let omitted = source.replace("@collect@\n", ""); + assert_weak_probe(&omitted, "table", &[true, true], 4, 0); + + let rooted = source.replace("@collect@", "collectgarbage(\"collect\")"); + assert_weak_probe(&rooted, "table", &[false, true], 3, 1); + + let released = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local value = {} +value.self = value +owner[1] = value +observe_table(value, 0) +value = nil +@collect@ +return type(owner[1]) +"#; + assert_weak_probe(&released.replace("@collect@\n", ""), "table", &[true], 3, 0); + assert_weak_probe( + &released.replace("@collect@", "collectgarbage(\"collect\")"), + "nil", + &[false], + 1, + 1, + ); +} + +#[test] +fn lua_candidate_signed_zero_number_keys_share_one_record() { + let through_zero = r#" +local neg = float_bits(1) +local owner = {} +owner[neg] = "neg" +return owner[0] +"#; + let mut vm = candidate(through_zero); + assert_eq!(vm.run().expect("read +0 after -0 write"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("neg")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); + + let through_neg = r#" +local neg = float_bits(1) +local owner = {} +owner[0] = "pos" +return owner[neg] +"#; + let mut vm = candidate(through_neg); + assert_eq!(vm.run().expect("read -0 after +0 write"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("pos")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); + + let overwrite = r#" +local neg = float_bits(1) +local owner = {} +owner[0] = "pos" +owner[neg] = "neg" +return owner[0] +"#; + let mut vm = candidate(overwrite); + assert_eq!(vm.run().expect("signed zero overwrite"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("neg")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); +} + +#[test] +fn lua_candidate_infinities_are_distinct_number_keys() { + let source = r#" +local pos = float_bits(3) +local neg = float_bits(4) +local owner = {} +owner[pos] = "pos" +owner[neg] = "neg" +return owner[@which@] +"#; + for (which, expected) in [("pos", "pos"), ("neg", "neg")] { + let mut vm = candidate(&source.replace("@which@", which)); + assert_eq!(vm.run().expect(which), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string(expected)]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 2); + } +} + +#[test] +fn lua_candidate_nan_number_key_read_is_nil() { + let source = r#" +local owner = {} +owner[1] = "keep" +local k = float_bits(2) +return type(owner[k]) +"#; + let mut vm = candidate(source); + assert_eq!(vm.run().expect("NaN key read"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); +} + +#[test] +fn lua_candidate_nan_number_key_string_write_is_refused() { + let source = r#" +local owner = {} +owner[1] = "keep" +local k = float_bits(2) +observe_table(owner, 0) +owner[k] = "nope" +"#; + assert_nan_index(source); +} + +#[test] +fn lua_candidate_nan_number_key_nil_write_is_refused() { + let source = r#" +local owner = {} +owner[1] = "keep" +local k = float_bits(2) +observe_table(owner, 0) +owner[k] = nil +"#; + assert_nan_index(source); +} + +fn assert_nan_index(source: &str) { + let mut vm = candidate(source); + let error = vm.run().expect_err("NaN key write"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "table index is NaN"), + "{error}" + ); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().collections, 0); } #[test] From b2e86e5de066e6033b8b707efb3211f7f5ebcb96 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 10:59:30 +0800 Subject: [PATCH 059/225] feat(lua): read rawget through the existing edge path An unbound rawget(table, key) uses the same GET_EDGE read as a bracket. A nil or boolean key is a miss after the table check. Unissued, foreign, and stale carriers stay errors. No metamethod and no boolean write. --- tests/luajit_heap_runtime/candidate.rs | 12 + .../value_boundary_tests.rs | 321 +++++++++++++++++- 2 files changed, 331 insertions(+), 2 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 25dbba5..b8ba19d 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -855,6 +855,11 @@ fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { heap::GuestClass::Table(table) => table, _ => return Err(host_fault("field source is not a table")), }; + // Nil and boolean keys are misses. Boolean keys are not written. Unissued + // integers, foreign handles, and stale carriers stay on the error path. + if matches!(key_value, Value::Null | Value::Bool(_)) { + return Ok(Value::Null); + } let mut host = call.vm().host_context(); if let Value::String(name) = key_value { return heap::with_heap(&mut host, |heap| heap.named_value(table, &name)) @@ -2051,6 +2056,13 @@ impl Lower<'_> { let owner = self.expr(owner)?; return self.call(GET_METATABLE, vec![owner]); } + if name.is("rawget") { + // Exact two arguments. Same GET_EDGE path as t[k]. No metamethod. + let [table, key] = args.exprs.as_slice() else { + return Err(self.unsupported(expr.span())); + }; + return self.index_read(table, key, expr.span()); + } if name.is("external_shape") && args.exprs.is_empty() { return self.call(EXTERNAL_SHAPE, vec![]); } diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index ea8d858..50c703b 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -360,8 +360,9 @@ impl vm::HostOwnedFunction for Witness { } fn special_float(tag: f64) -> f64 { - // Candidate source cannot spell these. The tags are ordinary numbers. - // The returned binary64 values are the typed inputs. + // `1e400` is +Inf in this lowerer. `-0`, NaN, and `-Inf` still enter + // through these tags. The tags themselves are ordinary numbers. The + // returned binary64 values are the typed inputs. match tag { 1.0 => f64::from_bits(0x8000_0000_0000_0000), 2.0 => f64::NAN, @@ -3678,3 +3679,319 @@ fn trailing_label_set_keeps_resolved_identity() { }) ); } + +/// `rawget(weak, 1)` reads the numeric weak value without a caller binding. +/// +/// The helper records the value, stores it only under `weak[1]`, and returns +/// the weak table. Omit keeps that same object. Collect returns one nil and +/// retires the original token and heap node. The string key `"1"` is a +/// different entry. +#[test] +fn lua_candidate_rawget_reads_a_weak_numeric_value_until_collect() { + let source = r#" +local function seed() + local mt = {} + mt.__mode = "v" + local weak = {} + setmetatable(weak, mt) + local value = {} + value.self = value + weak[1] = value + observe_table(value, 0) + return weak +end +local weak = seed() +observe_table(rawget(weak, 1), 0) +@collect@ +return type(rawget(weak, 1)) +"#; + let omitted = source.replace("@collect@\n", ""); + let observed = assert_weak_probe(&omitted, "table", &[true, true], 3, 0); + assert_eq!( + observed[0], observed[1], + "rawget returns the helper's original object" + ); + + let collected = source.replace("@collect@", "collectgarbage(\"collect\")"); + let observed = assert_weak_probe(&collected, "nil", &[false, false], 1, 1); + assert_eq!( + observed[0], observed[1], + "the retired token is the object rawget returned" + ); + + let text_key = omitted.replace( + "return type(rawget(weak, 1))", + "return type(rawget(weak, \"1\"))", + ); + let observed = assert_weak_probe(&text_key, "nil", &[true, true], 3, 0); + assert_eq!(observed[0], observed[1], "the numeric entry stays readable"); +} + +/// A nil key is one miss after the table is accepted. The numeric entry stays. +#[test] +fn lua_candidate_rawget_nil_key_reads_one_nil() { + let source = r#" +local owner = {} +owner[1] = "kept" +local k = 1 +k = nil +return rawget(owner, k) +"#; + let mut vm = candidate(source); + assert_eq!(vm.run().expect("nil key readback"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Null]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); + + let kept = source.replace("return rawget(owner, k)", "return owner[1]"); + let mut vm = candidate(&kept); + assert_eq!( + vm.run().expect("entry survives a nil key"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("kept")]); +} + +/// A boolean cannot be written as a key. When one reaches `rawget`, it misses. +#[test] +fn lua_candidate_rawget_bool_key_is_a_miss() { + let source = r#" +local a = {} +local owner = {} +owner[1] = "kept" +local k = same_table(a, a) +return rawget(owner, k) +"#; + let mut vm = candidate(source); + assert_eq!(vm.run().expect("bool key readback"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Null]); + + let kept = source.replace("return rawget(owner, k)", "return owner[1]"); + let mut vm = candidate(&kept); + assert_eq!( + vm.run().expect("bool key does not delete"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("kept")]); +} + +/// A nil table is rejected before a nil key can become a miss. +#[test] +fn lua_candidate_rawget_rejects_a_nil_table_before_the_key() { + let source = r#" +local owner = 1 +owner = nil +local k = 1 +k = nil +return rawget(owner, k) +"#; + let mut vm = candidate(source); + let error = vm.run().expect_err("nil table"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "field source is not a table"), + "{error}" + ); +} + +/// An unissued array is not a nil miss, as a table or as a key. +#[test] +fn lua_candidate_rawget_keeps_unissued_values_as_errors() { + let table = "return rawget(external_shape(), 1)"; + let mut vm = candidate(table); + let error = vm.run().expect_err("unissued table"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "field source is not a table"), + "{error}" + ); + + let key = r#" +local owner = {} +owner[1] = "kept" +local bad = external_shape() +return rawget(owner, bad) +"#; + let mut vm = candidate(key); + let error = vm.run().expect_err("unissued key"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "edge key is not a table"), + "{error}" + ); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); + + let copy = r#" +local owner = {} +owner[1] = "kept" +local bad = copy_fields(owner) +return rawget(owner, bad) +"#; + let mut vm = candidate(copy); + let error = vm.run().expect_err("structural copy key"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "edge key is not a table"), + "{error}" + ); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); +} + +/// Boolean keys stay unwritable. `rawget` does not add a write path. +#[test] +fn lua_candidate_bool_key_write_stays_refused() { + let source = r#" +local a = {} +local owner = {} +owner[1] = "kept" +local k = same_table(a, a) +observe_table(owner, 0) +owner[k] = "no" +"#; + let mut vm = candidate(source); + let error = vm.run().expect_err("bool key write"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "edge key is not a table"), + "{error}" + ); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); +} + +/// The fresh table is rooted while the key expression collects. +/// +/// The key is parenthesized because index keys already accept that form. +/// A table constructor is not an index key, so the reversed case uses a name. +/// Collect in the first argument does not root a table that has not been +/// evaluated, and that number is still not a table. +#[test] +fn lua_candidate_rawget_roots_a_fresh_table_while_the_key_collects() { + let source = r#" +local orphan = {} +orphan.self = orphan +observe_table(orphan, 0) +orphan = nil +return type(rawget({}, (collectgarbage("collect")))) +"#; + let mut vm = candidate(source); + assert_eq!(vm.run().expect("collect inside the key"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let observed = observed_tables(&mut vm); + assert_eq!(observed.len(), 1); + assert!( + !heap::with_heap(&mut vm.host_context(), |heap| { + Ok(heap.alive(observed[0].table)) + }) + .unwrap() + ); + let stats = heap::stats(&mut vm.host_context()).unwrap(); + assert_eq!(stats.collections, 1); + assert_eq!( + stats.live_nodes, 1, + "the fresh table survived the key collect" + ); + assert_eq!(stats.live_edges, 0); + + let omitted = source.replace("(collectgarbage(\"collect\"))", "0"); + let mut vm = candidate(&omitted); + assert_eq!(vm.run().expect("omit key collect"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let observed = observed_tables(&mut vm); + assert!( + heap::with_heap(&mut vm.host_context(), |heap| { + Ok(heap.alive(observed[0].table)) + }) + .unwrap() + ); + let stats = heap::stats(&mut vm.host_context()).unwrap(); + assert_eq!(stats.collections, 0); + assert_eq!(stats.live_nodes, 2); + + let reversed = r#" +local orphan = {} +orphan.self = orphan +observe_table(orphan, 0) +orphan = nil +local key = {} +return type(rawget((collectgarbage("collect")), key)) +"#; + let mut vm = candidate(reversed); + let error = vm.run().expect_err("collect before the table exists"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message == "field source is not a table"), + "{error}" + ); + let observed = observed_tables(&mut vm); + assert!( + !heap::with_heap(&mut vm.host_context(), |heap| { + Ok(heap.alive(observed[0].table)) + }) + .unwrap() + ); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().collections, 1); +} + +/// A block-local `rawget` does not replace the unbound call after the block. +#[test] +fn lua_candidate_rawget_after_a_block_shadow_is_the_builtin() { + let source = r#" +do + local rawget = 1 +end +local owner = {} +owner[1] = "kept" +return rawget(owner, 1) +"#; + let mut vm = candidate(source); + assert_eq!(vm.run().expect("builtin after the block"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("kept")]); +} + +#[test] +fn lua_candidate_local_rawget_is_not_the_builtin() { + let function = r#" +local function rawget() + return 7 +end +local n = rawget() +return n +"#; + let mut vm = candidate(function); + assert_eq!(vm.run().expect("local function"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::Float(7.0)]); + + for source in [ + "local rawget = 1\nreturn rawget({}, 1)\n", + "local function rawget()\n return 7\nend\nreturn rawget({}, 1)\n", + "return rawget({})\n", + "return rawget({}, 1, 2)\n", + ] { + let error = candidate::lower(source, catalog()).expect_err(source); + let text = error.to_string(); + assert!( + text.contains("not lowered"), + "{source} lowered or failed differently: {text}" + ); + } +} + +/// `1e400` is +Inf in this lowerer. It shares the injected +Inf key. +/// `-0` and NaN still need `float_bits`. +#[test] +fn lua_candidate_literal_overflow_shares_positive_infinity_key() { + let from_literal = r#" +local inf = float_bits(3) +local owner = {} +owner[1e400] = "literal" +return owner[inf] +"#; + let mut vm = candidate(from_literal); + assert_eq!(vm.run().expect("read injected +Inf"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("literal")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); + + let from_bits = r#" +local inf = float_bits(3) +local owner = {} +owner[inf] = "bits" +return rawget(owner, 1e400) +"#; + let mut vm = candidate(from_bits); + assert_eq!(vm.run().expect("read literal +Inf"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("bits")]); + assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); +} From d5c7606a752492299f6315439e9207e3e4b43666 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 15:41:09 +0800 Subject: [PATCH 060/225] test(lua): drop the frozen bool-key write refusal Boolean key writes are legal Lua. This slice does not implement them, so that refusal is not a regression. The read miss, the nil stack, and the weak identity checks stay. The collector marked one node for the fresh table already created as rawget's first argument. --- .../value_boundary_tests.rs | 86 ++++++++++--------- 1 file changed, 47 insertions(+), 39 deletions(-) diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 50c703b..c4512ee 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -3683,9 +3683,11 @@ fn trailing_label_set_keeps_resolved_identity() { /// `rawget(weak, 1)` reads the numeric weak value without a caller binding. /// /// The helper records the value, stores it only under `weak[1]`, and returns -/// the weak table. Omit keeps that same object. Collect returns one nil and -/// retires the original token and heap node. The string key `"1"` is a -/// different entry. +/// the weak table. Omit keeps that same object. `type(rawget(...))` observes +/// only the first value, so collect yields the string `"nil"`. The original +/// token and heap node are retired. One nil on the VM stack is the separate +/// `return rawget(owner, k)` case. The string key `"1"` is another entry; +/// its type wrapper also sees only the first value. #[test] fn lua_candidate_rawget_reads_a_weak_numeric_value_until_collect() { let source = r#" @@ -3724,7 +3726,10 @@ return type(rawget(weak, 1)) "return type(rawget(weak, \"1\"))", ); let observed = assert_weak_probe(&text_key, "nil", &[true, true], 3, 0); - assert_eq!(observed[0], observed[1], "the numeric entry stays readable"); + assert_eq!( + observed[0], observed[1], + "numeric observations match; type() on \"1\" only saw the first value" + ); } /// A nil key is one miss after the table is accepted. The numeric entry stays. @@ -3751,7 +3756,7 @@ return rawget(owner, k) assert_eq!(vm.stack(), &[Value::string("kept")]); } -/// A boolean cannot be written as a key. When one reaches `rawget`, it misses. +/// When a boolean reaches `rawget`, the read misses. The numeric entry stays. #[test] fn lua_candidate_rawget_bool_key_is_a_miss() { let source = r#" @@ -3832,32 +3837,18 @@ return rawget(owner, bad) assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); } -/// Boolean keys stay unwritable. `rawget` does not add a write path. -#[test] -fn lua_candidate_bool_key_write_stays_refused() { - let source = r#" -local a = {} -local owner = {} -owner[1] = "kept" -local k = same_table(a, a) -observe_table(owner, 0) -owner[k] = "no" -"#; - let mut vm = candidate(source); - let error = vm.run().expect_err("bool key write"); - assert!( - matches!(error, vm::VmError::HostError(ref message) if message == "edge key is not a table"), - "{error}" - ); - assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); -} - /// The fresh table is rooted while the key expression collects. /// /// The key is parenthesized because index keys already accept that form. /// A table constructor is not an index key, so the reversed case uses a name. /// Collect in the first argument does not root a table that has not been /// evaluated, and that number is still not a table. +/// +/// `last_marked` is that collect's marked-node count. The orphan is retired, +/// so the marked node is the fresh table the first argument already created. +/// A second run records that table before the call and checks the same handle +/// is still alive. Its local also roots it; argument-temp rooting stays on +/// the first run. #[test] fn lua_candidate_rawget_roots_a_fresh_table_while_the_key_collects() { let source = r#" @@ -3880,12 +3871,41 @@ return type(rawget({}, (collectgarbage("collect")))) ); let stats = heap::stats(&mut vm.host_context()).unwrap(); assert_eq!(stats.collections, 1); + assert_eq!( + stats.last_marked, 1, + "the collector marked the fresh table already created as the first argument" + ); assert_eq!( stats.live_nodes, 1, "the fresh table survived the key collect" ); assert_eq!(stats.live_edges, 0); + let named = r#" +local fresh = {} +observe_table(fresh, 0) +return type(rawget(fresh, (collectgarbage("collect")))) +"#; + let mut vm = candidate(named); + assert_eq!( + vm.run().expect("record the fresh table before collect"), + VmStatus::Halted + ); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let observed = observed_tables(&mut vm); + assert_eq!(observed.len(), 1); + assert!( + heap::with_heap(&mut vm.host_context(), |heap| { + Ok(heap.alive(observed[0].table)) + }) + .unwrap(), + "the table recorded before the key collect is still alive" + ); + let stats = heap::stats(&mut vm.host_context()).unwrap(); + assert_eq!(stats.collections, 1); + assert_eq!(stats.last_marked, 1); + assert_eq!(stats.live_nodes, 1); + let omitted = source.replace("(collectgarbage(\"collect\"))", "0"); let mut vm = candidate(&omitted); assert_eq!(vm.run().expect("omit key collect"), VmStatus::Halted); @@ -3941,6 +3961,8 @@ return rawget(owner, 1) assert_eq!(vm.stack(), &[Value::string("kept")]); } +/// A local function named `rawget` returns 7. Legal call shapes this subset +/// does not lower are not frozen as refusals. #[test] fn lua_candidate_local_rawget_is_not_the_builtin() { let function = r#" @@ -3953,20 +3975,6 @@ return n let mut vm = candidate(function); assert_eq!(vm.run().expect("local function"), VmStatus::Halted); assert_eq!(vm.stack(), &[Value::Float(7.0)]); - - for source in [ - "local rawget = 1\nreturn rawget({}, 1)\n", - "local function rawget()\n return 7\nend\nreturn rawget({}, 1)\n", - "return rawget({})\n", - "return rawget({}, 1, 2)\n", - ] { - let error = candidate::lower(source, catalog()).expect_err(source); - let text = error.to_string(); - assert!( - text.contains("not lowered"), - "{source} lowered or failed differently: {text}" - ); - } } /// `1e400` is +Inf in this lowerer. It shares the injected +Inf key. From ee68c0380eb88406f79c6ce5afb1ced4b5f0be74 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 16:19:12 +0800 Subject: [PATCH 061/225] feat(lua): trace closures and cells on the weak-table graph Closure, cell, and table nodes share one slot vector, edge index, root storage, and sweep. Internal closure and cell links stay strong. Only a table entry follows that table's weak mode. A private field id is not a Lua number, and a cell is not issued as a table value. --- src/frontends/lua/heap.rs | 12 +- src/frontends/lua/heap/handle.rs | 96 +- src/frontends/lua/heap/table.rs | 472 +++++- tests/luajit_heap_runtime/closure_graph.rs | 1267 +++++++++++++++++ .../value_boundary_tests.rs | 2 + 5 files changed, 1793 insertions(+), 56 deletions(-) create mode 100644 tests/luajit_heap_runtime/closure_graph.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 9b3a15b..253ba1a 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -24,6 +24,13 @@ //! This check is the experimental guest boundary for this slice. It is not a //! measured production collection scheme. //! +//! Closure and upvalue nodes use the same slots, edges, roots, meter, and +//! sweep. A root slot holds a table or a closure. A table field can point at +//! a closure, a closure at one shared upvalue, and that upvalue at its current +//! table or closure. A missing current edge is nil. Two closures can point at +//! the same upvalue. Those nodes have no guest carrier and no Core resource +//! token. They are not callable values. +//! //! Later integration, not this kernel: LuaJIT `ordered.lua` plus the reverse //! and skip-collection controls in //! `/mnt/workspace/rustscript-lua/evidence/lua52-gc-arg-order/qualification.md`. @@ -39,10 +46,11 @@ mod resource; #[path = "heap/table.rs"] mod table; -pub use handle::{HandleKind, TableRef}; +pub use handle::{ClosureRef, HandleKind, TableRef, UpvalueRef}; pub use resource::LuaTableResource; pub use table::{ - CollectReport, GuestClass, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId, ScanMeter, + CellValue, CollectReport, GuestClass, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId, + ScanMeter, }; use vm::{HostContext, Value}; diff --git a/src/frontends/lua/heap/handle.rs b/src/frontends/lua/heap/handle.rs index 539dda8..dabd534 100644 --- a/src/frontends/lua/heap/handle.rs +++ b/src/frontends/lua/heap/handle.rs @@ -1,11 +1,16 @@ -//! Private table handle. It is not a VM `Value` and has no bare-integer ABI. +//! Private handles. They are not VM values and have no bare-integer ABI. -/// Kind carried by a private handle. This milestone only allocates tables; -/// every operation still rejects a different kind. +/// Kind carried by a private handle. Table, closure, and upvalue nodes share +/// one heap. An operation rejects a live node of a different kind. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HandleKind { /// A table node. Table, + /// A closure node. It is not a callable value. + Closure, + /// A shared upvalue node. Its current edge holds a table, a closure, or is + /// absent (nil). It has no open or closed flag. + Upvalue, } /// Domain-checked reference to one table node. @@ -54,3 +59,88 @@ impl TableRef { self.kind } } + +/// Domain-checked reference to one closure node. +/// +/// Construction stays inside the heap. A guest `Value` is not a `ClosureRef`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ClosureRef { + domain: u64, + slot: u32, + generation: u32, + kind: HandleKind, +} + +impl ClosureRef { + pub(super) fn closure(domain: u64, slot: u32, generation: u32) -> Self { + Self { + domain, + slot, + generation, + kind: HandleKind::Closure, + } + } + + /// Heap domain that allocated this handle. + pub fn domain(self) -> u64 { + self.domain + } + + /// Stable slot index. Collection does not move it. + pub fn slot(self) -> u32 { + self.slot + } + + /// Generation observed when the handle was issued. + pub fn generation(self) -> u32 { + self.generation + } + + /// Handle kind. Closure operations reject any other kind. + pub fn kind(self) -> HandleKind { + self.kind + } +} + +/// Domain-checked reference to one shared upvalue node. +/// +/// Construction stays inside the heap. The node has no open or closed flag. +/// Its current edge is a table, a closure, or missing (nil). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UpvalueRef { + domain: u64, + slot: u32, + generation: u32, + kind: HandleKind, +} + +impl UpvalueRef { + pub(super) fn upvalue(domain: u64, slot: u32, generation: u32) -> Self { + Self { + domain, + slot, + generation, + kind: HandleKind::Upvalue, + } + } + + /// Heap domain that allocated this handle. + pub fn domain(self) -> u64 { + self.domain + } + + /// Stable slot index. Collection does not move it. + pub fn slot(self) -> u32 { + self.slot + } + + /// Generation observed when the handle was issued. + pub fn generation(self) -> u32 { + self.generation + } + + /// Handle kind. Upvalue operations reject any other kind. + pub fn kind(self) -> HandleKind { + self.kind + } +} diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 639af2c..82b9e12 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -1,4 +1,8 @@ -//! Non-moving mark/sweep table storage, explicit root frames, and hard caps. +//! Non-moving mark/sweep storage for tables, closures, and shared cells. +//! +//! Closure and cell nodes use the same slots, edges, roots, and sweep as +//! tables. A private field id is not a Lua number. Internal links are strong. +//! Only a table entry follows that table's weak mode. use std::fmt; use std::sync::Arc; @@ -6,10 +10,17 @@ use std::sync::atomic::{AtomicU64, Ordering}; use vm::{HostContextError, Value}; -use super::handle::{HandleKind, TableRef}; +use super::handle::{ClosureRef, HandleKind, TableRef, UpvalueRef}; static NEXT_DOMAIN: AtomicU64 = AtomicU64::new(1); +/// Closure-to-cell field. It is keyed only on a closure node. Field id 0 on a +/// table remains `__mode`. This id is not a Lua number. +const UPVALUE_EDGE: u32 = 0; +/// Cell current-value field. It is keyed only on an upvalue node. A missing +/// edge is nil. This id is not a Lua number. +const CURRENT_EDGE: u32 = 0; + /// Hard caps. Edges and root slots are counted separately so fields cannot /// grow past the edge cap by avoiding the node cap. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -161,6 +172,7 @@ enum SlotState { struct Slot { generation: u32, + kind: HandleKind, state: SlotState, /// Raw resource handle for this node. Ownership metadata only: the mark /// phase does not read it, so the token is not a GC root. @@ -188,20 +200,61 @@ enum EdgeValue { slot: u32, generation: u32, }, + /// A closure target in the same edge record. Not a guest table value. + Closure { + slot: u32, + generation: u32, + }, + /// A cell target in the same edge record. Not a guest table value. + Upvalue { + slot: u32, + generation: u32, + }, /// One guest scalar in the same record as a table target. Field 0 is the /// only key whose string is read as `__mode`. Scalar(Value), } impl EdgeValue { - fn table(&self) -> Option<(u32, u32)> { + fn object_slot(&self) -> Option { match self { - Self::Table { slot, generation } => Some((*slot, *generation)), + Self::Table { slot, .. } | Self::Closure { slot, .. } | Self::Upvalue { slot, .. } => { + Some(*slot) + } Self::Scalar(_) => None, } } } +/// Value stored in a shared cell's current edge. +/// +/// A missing edge is nil and is not a variant. `None` from [`LuaHeap::read_cell`] +/// is that nil. An error is an invalid handle, not nil. A cell is not issued +/// as a table value. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CellValue { + /// The cell currently holds a table. + Table(TableRef), + /// The cell currently holds a closure. + Closure(ClosureRef), +} + +/// One explicit root. Table and closure roots share the root vector. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Rooted { + Table(TableRef), + Closure(ClosureRef), +} + +impl Rooted { + fn slot(self) -> u32 { + match self { + Self::Table(handle) => handle.slot(), + Self::Closure(handle) => handle.slot(), + } + } +} + #[derive(Clone, Debug, PartialEq, Eq)] enum EdgeKey { Field(u32), @@ -431,7 +484,7 @@ pub struct LuaHeap { edges: Vec, /// Stored metatable refs. Zero means mark does not read metatable slots. metatable_edges: u32, - roots: Vec>, + roots: Vec>, frames: Vec, next_frame_generation: u32, collections: u32, @@ -478,16 +531,36 @@ impl LuaHeap { /// Reserves a live, unrooted table. Failure leaves occupancy unchanged. pub fn alloc(&mut self) -> Result { + let (index, generation) = self.alloc_slot(HandleKind::Table)?; + Ok(TableRef::table(self.domain, index, generation)) + } + + /// Reserves a live, unrooted closure. It uses the same node cap as a table. + /// It has no guest carrier and no resource token. + pub fn alloc_closure(&mut self) -> Result { + let (index, generation) = self.alloc_slot(HandleKind::Closure)?; + Ok(ClosureRef::closure(self.domain, index, generation)) + } + + /// Reserves a live, unrooted cell. It uses the same node cap as a table. + /// It has no guest carrier and no resource token. + pub fn alloc_upvalue(&mut self) -> Result { + let (index, generation) = self.alloc_slot(HandleKind::Upvalue)?; + Ok(UpvalueRef::upvalue(self.domain, index, generation)) + } + + fn alloc_slot(&mut self, kind: HandleKind) -> Result<(u32, u32), HeapError> { if let Some(index) = self.free_list.pop() { let slot = &mut self.slots[index as usize]; if !matches!(slot.state, SlotState::Free) { return Err(HeapError::StaleHandle); } + slot.kind = kind; slot.state = SlotState::Live { marked: false }; slot.token = None; slot.carrier = None; slot.metatable = None; - return Ok(TableRef::table(self.domain, index, slot.generation)); + return Ok((index, slot.generation)); } if self.slots.len() >= self.limits.nodes as usize { return Err(HeapError::NodeCapacity); @@ -498,13 +571,14 @@ impl LuaHeap { let index = u32::try_from(self.slots.len()).map_err(|_| HeapError::NodeCapacity)?; self.slots.push(Slot { generation: 1, + kind, state: SlotState::Live { marked: false }, token: None, carrier: None, metatable: None, }); self.note_node_peak(); - Ok(TableRef::table(self.domain, index, 1)) + Ok((index, 1)) } /// Releases a reserved node. A stale or foreign handle is refused and the @@ -585,6 +659,156 @@ impl LuaHeap { self.write_table_edge(from, EdgeKey::Field(key), to) } + /// Points a table field at a closure. The field id is not a Lua number. + pub fn set_closure_edge( + &mut self, + from: TableRef, + key: u32, + closure: ClosureRef, + ) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_closure(closure)?; + self.write_from( + from.slot(), + EdgeKey::Field(key), + EdgeValue::Closure { + slot: closure.slot(), + generation: closure.generation(), + }, + ) + } + + /// Points a closure at one shared cell. This is not an open-capture list. + pub fn set_upvalue_edge( + &mut self, + closure: ClosureRef, + cell: UpvalueRef, + ) -> Result<(), HeapError> { + self.require_closure(closure)?; + self.require_upvalue(cell)?; + self.write_from( + closure.slot(), + EdgeKey::Field(UPVALUE_EDGE), + EdgeValue::Upvalue { + slot: cell.slot(), + generation: cell.generation(), + }, + ) + } + + /// Replaces the table currently stored in a shared cell. + /// + /// An existing current edge is overwritten. This does not insert a second + /// record. A closure target uses [`Self::write_closure_upvalue`]. + pub fn write_upvalue(&mut self, cell: UpvalueRef, table: TableRef) -> Result<(), HeapError> { + self.require_upvalue(cell)?; + self.require_live(table)?; + self.write_from( + cell.slot(), + EdgeKey::Field(CURRENT_EDGE), + EdgeValue::Table { + slot: table.slot(), + generation: table.generation(), + }, + ) + } + + /// Replaces the current edge with a closure. Same record as a table write. + pub fn write_closure_upvalue( + &mut self, + cell: UpvalueRef, + closure: ClosureRef, + ) -> Result<(), HeapError> { + self.require_upvalue(cell)?; + self.require_closure(closure)?; + self.write_from( + cell.slot(), + EdgeKey::Field(CURRENT_EDGE), + EdgeValue::Closure { + slot: closure.slot(), + generation: closure.generation(), + }, + ) + } + + /// Removes the current edge. Nil is the missing edge, not a stored record. + pub fn clear_upvalue(&mut self, cell: UpvalueRef) -> Result<(), HeapError> { + self.require_upvalue(cell)?; + let key = EdgeKey::Field(CURRENT_EDGE); + self.edges + .retain(|edge| edge.from != cell.slot() || edge.key != key); + Ok(()) + } + + /// Reads the current edge through a closure. + /// + /// `Ok(None)` is nil. `Err` means the closure, its cell, or the stored + /// target is an invalid handle. A missing edge is not an invalid handle. + /// This does not call the closure. + pub fn read_cell(&self, closure: ClosureRef) -> Result, HeapError> { + let cell = self.upvalue_of(closure)?; + let Some(value) = self.stored_from(cell.slot(), &EdgeKey::Field(CURRENT_EDGE)) else { + return Ok(None); + }; + match value { + EdgeValue::Table { slot, generation } => { + let table = TableRef::table(self.domain, *slot, *generation); + self.require_live(table)?; + Ok(Some(CellValue::Table(table))) + } + EdgeValue::Closure { slot, generation } => { + let found = ClosureRef::closure(self.domain, *slot, *generation); + self.require_closure(found)?; + Ok(Some(CellValue::Closure(found))) + } + EdgeValue::Upvalue { .. } | EdgeValue::Scalar(_) => Err(HeapError::WrongKind), + } + } + + /// Reads the table currently stored through a closure's cell. + /// + /// A closure target is `WrongKind`. A missing edge has no table, so this + /// table adapter returns `StaleHandle`. [`Self::read_cell`] returns `None` + /// for that nil. + pub fn read_upvalue(&self, closure: ClosureRef) -> Result { + match self.read_cell(closure)? { + Some(CellValue::Table(table)) => Ok(table), + Some(CellValue::Closure(_)) => Err(HeapError::WrongKind), + None => Err(HeapError::StaleHandle), + } + } + + /// The cell a closure points at. Two closures can return the same cell. + pub fn upvalue_of(&self, closure: ClosureRef) -> Result { + self.require_closure(closure)?; + let Some(value) = self.stored_from(closure.slot(), &EdgeKey::Field(UPVALUE_EDGE)) else { + return Err(HeapError::StaleHandle); + }; + let EdgeValue::Upvalue { slot, generation } = value else { + return Err(HeapError::WrongKind); + }; + let cell = UpvalueRef::upvalue(self.domain, *slot, *generation); + self.require_upvalue(cell)?; + Ok(cell) + } + + /// Reads a table field that points at a closure. + /// + /// A missing field is `StaleHandle`. A table or scalar at that field is + /// `WrongKind`. The field id is not read as a Lua number. + pub fn closure_edge(&self, from: TableRef, key: u32) -> Result { + self.require_live(from)?; + let Some(value) = self.stored_from(from.slot(), &EdgeKey::Field(key)) else { + return Err(HeapError::StaleHandle); + }; + let EdgeValue::Closure { slot, generation } = value else { + return Err(HeapError::WrongKind); + }; + let closure = ClosureRef::closure(self.domain, *slot, *generation); + self.require_closure(closure)?; + Ok(closure) + } + /// Writes a scalar into the same record and quota as a table edge. /// /// Nil deletes that record. A string may occupy any direct field. A number @@ -784,11 +1008,20 @@ impl LuaHeap { from: TableRef, key: EdgeKey, value: EdgeValue, + ) -> Result<(), HeapError> { + self.write_from(from.slot(), key, value) + } + + fn write_from( + &mut self, + from_slot: u32, + key: EdgeKey, + value: EdgeValue, ) -> Result<(), HeapError> { if let Some(edge) = self .edges .iter_mut() - .find(|edge| edge.from == from.slot() && edge.key == key) + .find(|edge| edge.from == from_slot && edge.key == key) { edge.value = value; return Ok(()); @@ -797,7 +1030,7 @@ impl LuaHeap { return Err(HeapError::EdgeCapacity); } self.edges.push(Edge { - from: from.slot(), + from: from_slot, key, value, }); @@ -856,6 +1089,9 @@ impl LuaHeap { self.issued_value(TableRef::table(self.domain, *slot, *generation)) } Some(EdgeValue::Scalar(value)) => Ok(value.clone()), + Some(EdgeValue::Closure { .. } | EdgeValue::Upvalue { .. }) => { + Err(HeapError::WrongKind) + } None => Ok(Value::Null), } } @@ -865,10 +1101,22 @@ impl LuaHeap { from: TableRef, matches_key: impl Fn(&EdgeKey) -> bool, ) -> Result, HeapError> { - Ok(self - .read_edge(from, matches_key)? - .and_then(EdgeValue::table) - .map(|(slot, generation)| TableRef::table(self.domain, slot, generation))) + match self.read_edge(from, matches_key)? { + Some(EdgeValue::Table { slot, generation }) => { + Ok(Some(TableRef::table(self.domain, *slot, *generation))) + } + Some(EdgeValue::Scalar(_)) | None => Ok(None), + Some(EdgeValue::Closure { .. } | EdgeValue::Upvalue { .. }) => { + Err(HeapError::WrongKind) + } + } + } + + fn stored_from(&self, from_slot: u32, key: &EdgeKey) -> Option<&EdgeValue> { + self.edges + .iter() + .find(|edge| edge.from == from_slot && &edge.key == key) + .map(|edge| &edge.value) } /// One scan of the heap edge vector. `from` is checked before any key test. @@ -975,7 +1223,26 @@ impl LuaHeap { return Err(HeapError::StaleFrame); } let index = found.start as usize + slot as usize; - self.roots[index] = Some(handle); + self.roots[index] = Some(Rooted::Table(handle)); + Ok(()) + } + + /// Stores a closure in an open frame. Same vector and quota as a table root. + /// + /// A stale, foreign, or wrong-kind handle is refused before the slot changes. + pub fn write_closure_root( + &mut self, + frame: RootFrameId, + slot: u32, + handle: ClosureRef, + ) -> Result<(), HeapError> { + self.require_closure(handle)?; + let found = self.frame(frame)?; + if slot >= found.width { + return Err(HeapError::StaleFrame); + } + let index = found.start as usize + slot as usize; + self.roots[index] = Some(Rooted::Closure(handle)); Ok(()) } @@ -1129,6 +1396,16 @@ impl LuaHeap { self.require_live(handle).is_ok() } + /// Reports whether `handle` names a live closure in this heap. + pub fn closure_alive(&self, handle: ClosureRef) -> bool { + self.require_closure(handle).is_ok() + } + + /// Reports whether `handle` names a live upvalue in this heap. + pub fn upvalue_alive(&self, handle: UpvalueRef) -> bool { + self.require_upvalue(handle).is_ok() + } + /// Current occupancy. Peaks count storage, not only live objects. /// Does not collect and does not add scan counts. pub fn stats(&self) -> HeapStats { @@ -1148,22 +1425,62 @@ impl LuaHeap { } fn require_live(&self, handle: TableRef) -> Result<(), HeapError> { - if handle.domain() != self.domain { + self.require_kind( + handle.domain(), + handle.slot(), + handle.generation(), + HandleKind::Table, + ) + } + + fn require_closure(&self, handle: ClosureRef) -> Result<(), HeapError> { + self.require_kind( + handle.domain(), + handle.slot(), + handle.generation(), + HandleKind::Closure, + ) + } + + fn require_upvalue(&self, handle: UpvalueRef) -> Result<(), HeapError> { + self.require_kind( + handle.domain(), + handle.slot(), + handle.generation(), + HandleKind::Upvalue, + ) + } + + fn require_kind( + &self, + domain: u64, + slot: u32, + generation: u32, + kind: HandleKind, + ) -> Result<(), HeapError> { + if domain != self.domain { return Err(HeapError::WrongDomain); } - if handle.kind() != HandleKind::Table { - return Err(HeapError::WrongKind); + if self.slot_matches(slot, generation, kind) { + return Ok(()); } - if self.slot_live(handle.slot(), handle.generation()) { - Ok(()) + let live_other_kind = self.slots.get(slot as usize).is_some_and(|stored| { + stored.generation == generation + && stored.kind != kind + && matches!(stored.state, SlotState::Live { .. }) + }); + if live_other_kind { + Err(HeapError::WrongKind) } else { Err(HeapError::StaleHandle) } } - fn slot_live(&self, index: u32, generation: u32) -> bool { + fn slot_matches(&self, index: u32, generation: u32, kind: HandleKind) -> bool { self.slots.get(index as usize).is_some_and(|slot| { - slot.generation == generation && matches!(slot.state, SlotState::Live { .. }) + slot.generation == generation + && slot.kind == kind + && matches!(slot.state, SlotState::Live { .. }) }) } @@ -1178,17 +1495,18 @@ impl LuaHeap { let index = self.build_outgoing_index(); let mut work = Vec::new(); self.scan.root_slot_visits += self.roots.len() as u64; - let rooted: Vec = self.roots.iter().copied().flatten().collect(); - for handle in rooted { + let rooted: Vec = self.roots.iter().copied().flatten().collect(); + for rooted in rooted { self.scan.node_slot_visits += 1; - if self.alive(handle) { + if self.rooted_alive(rooted) { self.scan.node_slot_visits += 1; - self.mark_slot(handle.slot(), &mut work); + self.mark_slot(rooted.slot(), &mut work); } } let follow_metatables = self.metatable_edges > 0; while let Some(slot) = work.pop() { - let mode = if follow_metatables { + let from_table = self.slots[slot as usize].kind == HandleKind::Table; + let mode = if from_table && follow_metatables { self.follow_metatable(slot, &index, &mut work) } else { WeakMode::default() @@ -1197,22 +1515,37 @@ impl LuaHeap { let end = index.offsets[slot as usize + 1] as usize; self.scan.outgoing_edge_checks += (end - start) as u64; for &entry in &index.entries[start..end] { - let edge = &self.edges[entry as usize]; - let object_key = match &edge.key { - EdgeKey::Object { slot, generation } => Some((*slot, *generation)), - EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => None, + let (object_key, value_target) = { + let edge = &self.edges[entry as usize]; + let object_key = match &edge.key { + EdgeKey::Object { slot, generation } => Some((*slot, *generation)), + EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => None, + }; + let value_target = match &edge.value { + EdgeValue::Table { slot, generation } => { + Some((*slot, *generation, HandleKind::Table)) + } + EdgeValue::Closure { slot, generation } => { + Some((*slot, *generation, HandleKind::Closure)) + } + EdgeValue::Upvalue { slot, generation } => { + Some((*slot, *generation, HandleKind::Upvalue)) + } + EdgeValue::Scalar(_) => None, + }; + (object_key, value_target) }; - let value = edge.value.table(); - if !mode.keys + if from_table + && !mode.keys && let Some((slot, generation)) = object_key { - self.follow_target(slot, generation, &mut work); + self.follow_target(slot, generation, HandleKind::Table, &mut work); } - // LuaJIT traces k-mode values even when their keys are unmarked. - if !mode.values - && let Some((slot, generation)) = value - { - self.follow_target(slot, generation, &mut work); + // A table entry follows that table's weak mode. A closure or + // cell link is not a table entry, so it stays strong. + let strong_value = !from_table || !mode.values; + if strong_value && let Some((slot, generation, kind)) = value_target { + self.follow_target(slot, generation, kind, &mut work); } } } @@ -1230,7 +1563,7 @@ impl LuaHeap { return WeakMode::default(); }; self.scan.metatable_edge_checks += 1; - if self.follow_target(to_slot, to_generation, work) + if self.follow_target(to_slot, to_generation, HandleKind::Table, work) && let Some(modes) = &index.weak_modes { self.scan.weak_mode_lookups += 1; @@ -1239,9 +1572,15 @@ impl LuaHeap { WeakMode::default() } - fn follow_target(&mut self, to_slot: u32, to_generation: u32, work: &mut Vec) -> bool { + fn follow_target( + &mut self, + to_slot: u32, + to_generation: u32, + kind: HandleKind, + work: &mut Vec, + ) -> bool { self.scan.node_slot_visits += 1; - if !self.slot_live(to_slot, to_generation) { + if !self.slot_matches(to_slot, to_generation, kind) { return false; } self.scan.node_slot_visits += 1; @@ -1316,20 +1655,44 @@ impl LuaHeap { /// so an all-live collect does not walk edges again and does not build /// the mark bitmap. fn sweep_edges_once(&mut self) { - let marked: Vec = self + struct SweepSlot { + marked: bool, + kind: HandleKind, + generation: u32, + } + let sweep: Vec = self .slots .iter() - .map(|slot| matches!(slot.state, SlotState::Live { marked: true })) + .map(|slot| SweepSlot { + marked: matches!(slot.state, SlotState::Live { marked: true }), + kind: slot.kind, + generation: slot.generation, + }) .collect(); - self.scan.node_slot_visits += marked.len() as u64; - self.scan.scratch.sweep_bitmap_inited += marked.len() as u64; + self.scan.node_slot_visits += sweep.len() as u64; + self.scan.scratch.sweep_bitmap_inited += sweep.len() as u64; self.scan.sweep_edge_checks += self.edges.len() as u64; - let is_marked = |slot: u32| marked.get(slot as usize).copied().unwrap_or(false); + let is_marked = |slot: u32| sweep.get(slot as usize).is_some_and(|found| found.marked); + let typed = |slot: u32, generation: u32, kind: HandleKind| { + sweep.get(slot as usize).is_some_and(|found| { + found.marked && found.kind == kind && found.generation == generation + }) + }; // Strong endpoints of a marked owner were already marked. For weak // edges, either dead object endpoint invalidates the whole entry. + // Closure and cell targets are checked in this same retain. self.edges.retain(|edge| { is_marked(edge.from) - && edge.value.table().is_none_or(|(slot, _)| is_marked(slot)) + && match &edge.value { + EdgeValue::Table { slot, .. } => is_marked(*slot), + EdgeValue::Scalar(_) => true, + EdgeValue::Closure { slot, generation } => { + typed(*slot, *generation, HandleKind::Closure) + } + EdgeValue::Upvalue { slot, generation } => { + typed(*slot, *generation, HandleKind::Upvalue) + } + } && match &edge.key { EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, EdgeKey::Object { slot, .. } => is_marked(*slot), @@ -1366,29 +1729,36 @@ impl LuaHeap { fn remove_edges_touching(&mut self, slot: u32) { self.edges.retain(|edge| { edge.from != slot - && edge.value.table().is_none_or(|(target, _)| target != slot) + && edge.value.object_slot().is_none_or(|target| target != slot) && !edge_key_is_slot(&edge.key, slot) }); } fn clear_roots_to(&mut self, handle: TableRef) { for root in &mut self.roots { - if *root == Some(handle) { + if *root == Some(Rooted::Table(handle)) { *root = None; } } } + fn rooted_alive(&self, rooted: Rooted) -> bool { + match rooted { + Rooted::Table(handle) => self.alive(handle), + Rooted::Closure(handle) => self.closure_alive(handle), + } + } + fn clear_dead_roots(&mut self) -> u32 { let mut live = 0u32; let len = self.roots.len(); self.scan.root_slot_visits += len as u64; for index in 0..len { - let Some(handle) = self.roots[index] else { + let Some(rooted) = self.roots[index] else { continue; }; self.scan.node_slot_visits += 1; - if self.alive(handle) { + if self.rooted_alive(rooted) { live += 1; } else { self.roots[index] = None; diff --git a/tests/luajit_heap_runtime/closure_graph.rs b/tests/luajit_heap_runtime/closure_graph.rs new file mode 100644 index 0000000..8c1f1cb --- /dev/null +++ b/tests/luajit_heap_runtime/closure_graph.rs @@ -0,0 +1,1267 @@ +//! Same-graph witness for a table, a closure, and a shared cell. +//! +//! This is not Lua source and does not execute a closure. Locked LuaJIT stores +//! the closure at numeric key `1` (`evidence/lua52-mixed-closure-weak-graph`). +//! The reviewed table-to-closure edge is a private field id. Field ids and +//! binary64 keys do not alias. The second table's back-edge uses the existing +//! string key `"1"`, matching that oracle. The observer stores the closure in +//! another private field, not under the oracle's string key `call`. + +use std::sync::Arc; + +use vm::{HostContext, Value}; + +use super::super::heap::{ + self, CellValue, ClosureRef, HeapError, HeapLimits, TableRef, UpvalueRef, +}; +use super::super::{publish_raw, resource_handle, table_ref}; + +/// Private field on the anchor table. Not Lua numeric key 1. +const CLOSURE_FIELD: u32 = 1; +/// Private field on the weak observer. Not the string key `call`. +const OBSERVER_CLOSURE_FIELD: u32 = 1; + +struct Mixed { + frame: heap::RootFrameId, + first: TableRef, + first_raw: i64, + first_carrier: Value, + second: TableRef, + second_raw: i64, + second_carrier: Value, + closure: ClosureRef, + cell: UpvalueRef, + observer: TableRef, + observer_raw: i64, + peer: TableRef, + peer_raw: i64, + orphan: TableRef, + orphan_raw: i64, + mode: TableRef, + mode_raw: i64, + tables_published: usize, +} + +fn mixed_limits() -> HeapLimits { + HeapLimits { + nodes: 8, + roots: 3, + edges: 11, + max_generation: 8, + } +} + +fn carrier_ptr(value: &Value) -> *const Vec { + match value { + Value::Array(array) => Arc::as_ptr(array), + other => panic!("issued table is not an array: {other:?}"), + } +} + +fn token_open(host: &HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + resource_handle(raw), + &heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn issue(host: &mut HostContext<'_>, table: TableRef) -> Value { + heap::with_heap(host, |heap| heap.issue_carrier(table)).expect("issue table carrier") +} + +fn read_capture(host: &mut HostContext<'_>, closure: ClosureRef) -> Value { + let table = heap::with_heap(host, |heap| match heap.read_cell(closure)? { + Some(CellValue::Table(table)) => Ok(table), + Some(CellValue::Closure(_)) => panic!("capture is not a closure"), + None => panic!("capture is nil"), + }) + .expect("read the cell through the closure"); + heap::with_heap(host, |heap| heap.issued_value(table)).expect("issued captured table") +} + +/// First table is the cycle's only explicit root. Observer and peer have their +/// own roots. The cell is not published and has no token. +fn seed(host: &mut HostContext<'_>) -> Mixed { + heap::install(host, mixed_limits()).expect("install"); + let before_tokens = host.resource_count(); + let first_raw = publish_raw(host); + let first = table_ref(host, first_raw); + let second_raw = publish_raw(host); + let second = table_ref(host, second_raw); + let observer_raw = publish_raw(host); + let observer = table_ref(host, observer_raw); + let peer_raw = publish_raw(host); + let peer = table_ref(host, peer_raw); + let orphan_raw = publish_raw(host); + let orphan = table_ref(host, orphan_raw); + let mode_raw = publish_raw(host); + let mode = table_ref(host, mode_raw); + let tables_published = 6; + assert_eq!( + host.resource_count() - before_tokens, + tables_published, + "six table tokens" + ); + + let (closure, cell) = heap::with_heap(host, |heap| { + let closure = heap.alloc_closure()?; + let cell = heap.alloc_upvalue()?; + Ok((closure, cell)) + }) + .expect("closure and cell"); + assert_eq!( + host.resource_count() - before_tokens, + tables_published, + "a cell has no token; do not publish one" + ); + assert_eq!(closure.kind(), heap::HandleKind::Closure); + assert_eq!(cell.kind(), heap::HandleKind::Upvalue); + + let frame = heap::with_heap(host, |heap| heap.enter_roots(3)).expect("three roots"); + heap::with_heap(host, |heap| heap.write_root(frame, 0, first)).expect("anchor"); + heap::with_heap(host, |heap| heap.write_root(frame, 1, observer)).expect("observer root"); + heap::with_heap(host, |heap| heap.write_root(frame, 2, peer)).expect("peer root"); + + heap::with_heap(host, |heap| { + heap.set_closure_edge(first, CLOSURE_FIELD, closure)?; + heap.set_upvalue_edge(closure, cell)?; + heap.write_upvalue(cell, second)?; + heap.set_named_edge(second, "1", first)?; + heap.set_mode_scalar(mode, Value::string("v"))?; + heap.set_metatable(observer, Some(mode))?; + heap.set_number_edge(observer, 1.0, first)?; + heap.set_named_edge(observer, "1", second)?; + heap.set_closure_edge(observer, OBSERVER_CLOSURE_FIELD, closure)?; + heap.set_named_edge(observer, "orphan", orphan)?; + heap.set_named_edge(observer, "peer", peer)?; + heap.set_named_edge(orphan, "self", orphan)?; + Ok(()) + }) + .expect("link the mixed cycle and the weak observer"); + + let first_carrier = issue(host, first); + let second_carrier = issue(host, second); + assert_eq!( + carrier_ptr(&read_capture(host, closure)), + carrier_ptr(&second_carrier), + "capture readback uses read_cell, not a Lua call" + ); + assert!( + matches!( + heap::with_heap(host, |heap| heap.number_value(first, 1.0)).expect("number key"), + Value::Null + ), + "private field {CLOSURE_FIELD} is not Lua numeric key 1" + ); + assert_eq!( + heap::with_heap(host, |heap| heap.closure_edge(first, CLOSURE_FIELD)).expect("field"), + closure + ); + assert!( + heap::with_heap(host, |heap| heap.named_edge(observer, "call")) + .expect("call key") + .is_none(), + "observer closure is a private field, not string key call" + ); + + Mixed { + frame, + first, + first_raw, + first_carrier, + second, + second_raw, + second_carrier, + closure, + cell, + observer, + observer_raw, + peer, + peer_raw, + orphan, + orphan_raw, + mode, + mode_raw, + tables_published, + } +} + +fn edge_present(host: &mut HostContext<'_>, from: TableRef, name: &str, to: TableRef) -> bool { + heap::with_heap(host, |heap| heap.named_edge(from, name)) + .expect("named edge") + .is_some_and(|found| found == to) +} + +fn number_present(host: &mut HostContext<'_>, from: TableRef, key: f64, to: TableRef) -> bool { + let observed = + heap::with_heap(host, |heap| heap.number_value(from, key)).expect("number value"); + let Value::Array(observed) = observed else { + return false; + }; + let Ok(Value::Array(expected)) = heap::with_heap(host, |heap| heap.issued_value(to)) else { + return false; + }; + Arc::ptr_eq(&observed, &expected) +} + +fn closure_entry_present(host: &mut HostContext<'_>, graph: &Mixed) -> bool { + heap::with_heap(host, |heap| { + heap.closure_edge(graph.observer, OBSERVER_CLOSURE_FIELD) + }) + .ok() + .is_some_and(|found| found == graph.closure) +} + +fn observer_count(host: &mut HostContext<'_>, graph: &Mixed) -> u32 { + let mut count = 0; + if number_present(host, graph.observer, 1.0, graph.first) { + count += 1; + } + if edge_present(host, graph.observer, "1", graph.second) { + count += 1; + } + if closure_entry_present(host, graph) { + count += 1; + } + if edge_present(host, graph.observer, "orphan", graph.orphan) { + count += 1; + } + if edge_present(host, graph.observer, "peer", graph.peer) { + count += 1; + } + count +} + +fn cycle_alive(host: &mut HostContext<'_>, graph: &Mixed) -> bool { + heap::with_heap(host, |heap| { + Ok(heap.alive(graph.first) + && heap.closure_alive(graph.closure) + && heap.upvalue_alive(graph.cell) + && heap.alive(graph.second)) + }) + .expect("cycle handles") +} + +fn assert_capture_identity(host: &mut HostContext<'_>, graph: &Mixed) { + assert_eq!( + carrier_ptr(&read_capture(host, graph.closure)), + carrier_ptr(&graph.second_carrier) + ); + assert_eq!( + heap::with_heap(host, |heap| heap.read_cell(graph.closure)).expect("cell"), + Some(CellValue::Table(graph.second)) + ); +} + +fn assert_retired_cycle(host: &mut HostContext<'_>, graph: &Mixed) { + assert!(!cycle_alive(host, graph)); + assert!(!token_open(host, graph.first_raw)); + assert!(!token_open(host, graph.second_raw)); + assert!(!token_open(host, graph.orphan_raw)); + assert!(token_open(host, graph.peer_raw)); + assert!(token_open(host, graph.observer_raw)); + assert!(token_open(host, graph.mode_raw)); + assert!(heap::with_heap(host, |heap| Ok(heap.alive(graph.mode))).expect("mode table")); + assert_eq!( + observer_count(host, graph), + 1, + "only the peer weak entry remains" + ); + assert_eq!( + heap::with_heap(host, |heap| heap.read_cell(graph.closure)).expect_err("expired"), + heap::HeapError::StaleHandle + ); + assert_eq!( + heap::with_heap(host, |heap| Ok(heap.guest_class(&graph.first_carrier))).expect("class"), + heap::GuestClass::Unissued + ); +} + +fn collect(host: &mut HostContext<'_>) { + heap::collect(host).expect("collect"); +} + +#[test] +fn mixed_graph_full_keeps_identities_then_retires_the_cycle() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = seed(&mut host); + assert!(cycle_alive(&mut host, &graph)); + assert!(token_open(&host, graph.orphan_raw)); + assert_eq!(observer_count(&mut host, &graph), 5); + collect(&mut host); + assert!(cycle_alive(&mut host, &graph)); + assert_capture_identity(&mut host, &graph); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.orphan))).expect("orphan")); + assert!(!token_open(&host, graph.orphan_raw), "orphan token retired"); + assert!( + !edge_present(&mut host, graph.observer, "orphan", graph.orphan), + "weak orphan entry cleared" + ); + assert_eq!(observer_count(&mut host, &graph), 4); + assert!(token_open(&host, graph.first_raw)); + assert!(token_open(&host, graph.second_raw)); + heap::with_heap(&mut host, |heap| heap.clear_root(graph.frame, 0)).expect("drop anchor"); + collect(&mut host); + assert_retired_cycle(&mut host, &graph); + assert_eq!( + host.resource_count(), + 3, + "observer, peer, and mode tokens; the cell was never issued" + ); + let _ = graph.tables_published; + }); +} + +#[test] +fn mixed_graph_omit_first_keeps_the_orphan_until_the_final_collect() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = seed(&mut host); + assert!(cycle_alive(&mut host, &graph)); + assert!(token_open(&host, graph.orphan_raw)); + assert_eq!(observer_count(&mut host, &graph), 5); + heap::with_heap(&mut host, |heap| heap.clear_root(graph.frame, 0)).expect("drop anchor"); + collect(&mut host); + assert_retired_cycle(&mut host, &graph); + }); +} + +#[test] +fn mixed_graph_omit_final_leaves_the_cycle_after_the_anchor_is_cleared() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = seed(&mut host); + collect(&mut host); + assert!(!token_open(&host, graph.orphan_raw)); + assert_eq!(observer_count(&mut host, &graph), 4); + heap::with_heap(&mut host, |heap| heap.clear_root(graph.frame, 0)).expect("drop anchor"); + assert!(cycle_alive(&mut host, &graph)); + assert_capture_identity(&mut host, &graph); + assert!(token_open(&host, graph.first_raw)); + assert!(token_open(&host, graph.second_raw)); + assert_eq!(observer_count(&mut host, &graph), 4); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + }); +} + +#[test] +fn mixed_graph_cut_drops_closure_cell_and_captured_table() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = seed(&mut host); + heap::with_heap(&mut host, |heap| { + heap.set_field_scalar(graph.first, CLOSURE_FIELD, Value::Null) + }) + .expect("cut the private field, not numeric key 1"); + assert!(matches!( + heap::with_heap(&mut host, |heap| heap.number_value(graph.first, 1.0)) + .expect("number key"), + Value::Null + )); + collect(&mut host); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.first))).expect("first")); + assert!(token_open(&host, graph.first_raw)); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(graph.closure))) + .expect("closure") + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(graph.cell))).expect("cell") + ); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.second))).expect("second")); + assert!(!token_open(&host, graph.second_raw)); + assert!(!token_open(&host, graph.orphan_raw)); + assert!(token_open(&host, graph.peer_raw)); + assert_eq!( + observer_count(&mut host, &graph), + 2, + "anchored table and peer" + ); + assert!(!closure_entry_present(&mut host, &graph)); + heap::with_heap(&mut host, |heap| heap.clear_root(graph.frame, 0)).expect("drop anchor"); + collect(&mut host); + assert_retired_cycle(&mut host, &graph); + }); +} + +const LEFT_KEY: u32 = 1; +const RIGHT_KEY: u32 = 2; +const BACK_KEY: u32 = 1; + +struct Graph { + frame: heap::RootFrameId, + root: TableRef, + root_raw: i64, + root_carrier: Value, + left: ClosureRef, + right: ClosureRef, + cell: UpvalueRef, + original: TableRef, + original_raw: i64, + original_carrier: Value, + replacement: TableRef, + replacement_raw: i64, + replacement_carrier: Value, + independent: TableRef, + independent_raw: i64, + independent_carrier: Value, +} + +fn graph_limits() -> HeapLimits { + HeapLimits { + nodes: 8, + roots: 2, + edges: 8, + max_generation: 8, + } +} +fn read_carrier(host: &mut HostContext<'_>, closure: ClosureRef) -> Value { + let table = heap::with_heap(host, |heap| heap.read_upvalue(closure)).expect("read shared cell"); + heap::with_heap(host, |heap| heap.issued_value(table)).expect("issued current table") +} + +/// One root table holds two closures over one cell. A write through that cell +/// is visible from the other closure. No collection runs here. +fn link_shared_cell(host: &mut HostContext<'_>) -> Graph { + heap::install(host, graph_limits()).expect("install"); + let root_raw = publish_raw(host); + let root = table_ref(host, root_raw); + let independent_raw = publish_raw(host); + let independent = table_ref(host, independent_raw); + let frame = heap::with_heap(host, |heap| heap.enter_roots(2)).expect("two root slots"); + heap::with_heap(host, |heap| heap.write_root(frame, 0, root)).expect("root the cycle owner"); + heap::with_heap(host, |heap| heap.write_root(frame, 1, independent)).expect("independent root"); + + let (left, right, cell) = heap::with_heap(host, |heap| { + let left = heap.alloc_closure()?; + let right = heap.alloc_closure()?; + let cell = heap.alloc_upvalue()?; + heap.set_closure_edge(root, LEFT_KEY, left)?; + heap.set_closure_edge(root, RIGHT_KEY, right)?; + heap.set_upvalue_edge(left, cell)?; + heap.set_upvalue_edge(right, cell)?; + Ok((left, right, cell)) + }) + .expect("two closures, one upvalue"); + + let original_raw = publish_raw(host); + let original = table_ref(host, original_raw); + heap::with_heap(host, |heap| heap.write_upvalue(cell, original)) + .expect("capture the original table"); + let root_carrier = issue(host, root); + let original_carrier = issue(host, original); + let independent_carrier = issue(host, independent); + + let through_left = read_carrier(host, left); + let through_right = read_carrier(host, right); + assert_eq!( + carrier_ptr(&through_left), + carrier_ptr(&original_carrier), + "the left closure reads the original table carrier" + ); + assert_eq!( + carrier_ptr(&through_right), + carrier_ptr(&original_carrier), + "the right closure reads the same carrier" + ); + assert_eq!( + heap::with_heap(host, |heap| heap.upvalue_of(left)).expect("left cell"), + cell, + "both closures name one upvalue" + ); + assert_eq!( + heap::with_heap(host, |heap| heap.upvalue_of(right)).expect("right cell"), + cell + ); + + let replacement_raw = publish_raw(host); + let replacement = table_ref(host, replacement_raw); + let replacement_carrier = issue(host, replacement); + heap::with_heap(host, |heap| heap.write_upvalue(cell, replacement)) + .expect("replace the current table"); + let seen = read_carrier(host, right); + assert_eq!( + carrier_ptr(&seen), + carrier_ptr(&replacement_carrier), + "a write is visible through the other closure" + ); + assert_ne!( + carrier_ptr(&seen), + carrier_ptr(&original_carrier), + "the other closure no longer reads the original carrier" + ); + let stats = heap::stats(host).expect("stats after the write"); + assert_eq!( + stats.live_nodes, 7, + "four tables, two closures, one upvalue" + ); + assert_eq!( + stats.live_edges, 5, + "two fields, two closure links, one current value" + ); + assert_eq!(stats.node_slots, 7); + assert_eq!(stats.edge_slots, 5); + + Graph { + frame, + root, + root_raw, + root_carrier, + left, + right, + cell, + original, + original_raw, + original_carrier, + replacement, + replacement_raw, + replacement_carrier, + independent, + independent_raw, + independent_carrier, + } +} + +fn release_replaced_table(host: &mut HostContext<'_>, graph: &Graph) { + let before = heap::stats(host).expect("before replaced-table collect"); + let before_tokens = host.resource_count(); + let report = heap::collect(host).expect("collect the replaced table"); + let meter = heap::take_scan_meter(host).expect("meter"); + assert_eq!(meter.mark_passes, 1, "the existing collector marks once"); + assert_eq!( + meter.outgoing_edge_checks, 5, + "mark follows the closure and upvalue edges; got {}", + meter.outgoing_edge_checks + ); + assert_eq!(report.live_nodes, 6, "the replaced table is the only sweep"); + assert_eq!(before.live_nodes - report.live_nodes, 1); + assert!(!heap::with_heap(host, |heap| Ok(heap.alive(graph.original))).expect("original")); + assert!( + !token_open(host, graph.original_raw), + "the replaced table token is closed" + ); + assert_eq!( + heap::with_heap(host, |heap| Ok(heap.guest_class(&graph.original_carrier))).expect("class"), + heap::GuestClass::Unissued, + "holding the carrier must not keep the swept table" + ); + let current = read_carrier(host, graph.left); + assert_eq!( + carrier_ptr(¤t), + carrier_ptr(&graph.replacement_carrier), + "mark missed the capture: the rooted cell's current table was swept" + ); + assert!(token_open(host, graph.replacement_raw)); + assert!(token_open(host, graph.root_raw)); + assert!(token_open(host, graph.independent_raw)); + assert_eq!(host.resource_count(), before_tokens - 1); +} + +fn close_cycle(host: &mut HostContext<'_>, graph: &Graph) { + heap::with_heap(host, |heap| { + heap.set_edge(graph.replacement, BACK_KEY, graph.root) + }) + .expect("current table points back at the root"); + assert_eq!( + heap::with_heap(host, |heap| heap.edge(graph.replacement, BACK_KEY)).expect("back edge"), + Some(graph.root) + ); + assert_eq!( + heap::with_heap(host, |heap| heap.edge(graph.root, LEFT_KEY)).expect_err("closure field"), + HeapError::WrongKind, + "a table-edge read must not turn a closure into a table" + ); + heap::with_heap(host, |heap| heap.clear_root(graph.frame, 0)) + .expect("drop the only external root"); +} + +#[test] +fn closure_upvalue_quota_rejects_another_node_or_edge_and_reuses_kind_checks() { + let mut heap = heap::LuaHeap::new(HeapLimits { + nodes: 3, + roots: 1, + edges: 2, + max_generation: 4, + }); + let table = heap.alloc().expect("table"); + let closure = heap.alloc_closure().expect("closure"); + let cell = heap.alloc_upvalue().expect("upvalue"); + let before = heap.stats(); + assert!( + heap.alloc_closure().is_err(), + "node cap counts closure nodes" + ); + assert_eq!( + heap.stats(), + before, + "a refused closure alloc does not grow storage" + ); + + heap.set_closure_edge(table, LEFT_KEY, closure) + .expect("field"); + heap.set_upvalue_edge(closure, cell).expect("cell"); + let edges = heap.stats(); + let captured = heap.alloc().expect_err("node cap still includes the table"); + assert!(matches!(captured, HeapError::NodeCapacity)); + assert_eq!( + heap.write_upvalue(cell, table), + Err(HeapError::EdgeCapacity), + "edge cap counts the closure and upvalue links" + ); + assert_eq!(heap.stats().live_edges, edges.live_edges); + assert_eq!(heap.stats().edge_slots, edges.edge_slots); + + let mut other = heap::LuaHeap::new(HeapLimits { + nodes: 4, + roots: 1, + edges: 4, + max_generation: 4, + }); + let foreign = other.alloc_closure().expect("foreign closure"); + assert_eq!( + heap.set_upvalue_edge(foreign, cell), + Err(HeapError::WrongDomain) + ); + assert_eq!( + heap.edge(table, LEFT_KEY), + Err(HeapError::WrongKind), + "the stored closure edge is not a table edge" + ); + let foreign_table = other.alloc().expect("foreign table"); + assert_eq!( + other.closure_edge(foreign_table, LEFT_KEY), + Err(HeapError::StaleHandle) + ); + + let stale_closure = closure; + let stale_cell = cell; + assert_eq!(heap.collect().live_nodes, 0); + assert_eq!( + heap.read_upvalue(stale_closure), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.write_upvalue(stale_cell, table), + Err(HeapError::StaleHandle) + ); + assert!(!heap.alive(table)); +} + +#[test] +fn closure_upvalue_two_closures_share_a_cell_and_a_write_replaces_it() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = link_shared_cell(&mut host); + assert_eq!(graph.left.kind(), heap::HandleKind::Closure); + assert_eq!(graph.right.kind(), heap::HandleKind::Closure); + assert_eq!(graph.cell.kind(), heap::HandleKind::Upvalue); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(graph.cell))).expect("cell") + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(graph.left)).expect("left"), + graph.replacement + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(graph.right)).expect("right"), + graph.replacement + ); + }); +} + +#[test] +fn closure_upvalue_explicit_collect_releases_only_the_replaced_table() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = link_shared_cell(&mut host); + release_replaced_table(&mut host, &graph); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.root))).expect("root")); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(graph.left))).expect("left") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(graph.right))).expect("right") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(graph.cell))).expect("cell") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.independent))) + .expect("independent") + ); + }); +} + +#[test] +fn closure_upvalue_collect_reclaims_the_mixed_cycle_and_closes_tokens() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = link_shared_cell(&mut host); + release_replaced_table(&mut host, &graph); + close_cycle(&mut host, &graph); + let before_tokens = host.resource_count(); + assert_eq!( + before_tokens, 3, + "root, replacement, and independent tokens" + ); + assert_eq!(heap::stats(&mut host).expect("linked").live_edges, 6); + assert!(token_open(&host, graph.root_raw)); + assert!(token_open(&host, graph.replacement_raw)); + + let report = heap::collect(&mut host).expect("collect the unreachable cycle"); + assert_eq!(report.live_nodes, 1, "only the independent root remains"); + assert_eq!(report.live_roots, 1); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.root))).expect("root")); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(graph.left))).expect("left") + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(graph.right))).expect("right") + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(graph.cell))).expect("cell") + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.replacement))).expect("current") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.independent))) + .expect("independent") + ); + assert!( + !token_open(&host, graph.root_raw), + "cycle table token closed" + ); + assert!( + !token_open(&host, graph.replacement_raw), + "current table token closed" + ); + assert!(token_open(&host, graph.independent_raw)); + assert_eq!(host.resource_count(), 1); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&graph.root_carrier))) + .expect("class"), + heap::GuestClass::Unissued + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok( + heap.guest_class(&graph.independent_carrier) + )) + .expect("independent class"), + heap::GuestClass::Table(graph.independent) + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(graph.left)) + .expect_err("expired closure"), + HeapError::StaleHandle + ); + }); +} + +#[test] +fn closure_upvalue_omitting_the_final_collect_leaves_the_mixed_cycle() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = link_shared_cell(&mut host); + release_replaced_table(&mut host, &graph); + close_cycle(&mut host, &graph); + let stats = heap::stats(&mut host).expect("before the omitted collect"); + assert_eq!(stats.live_nodes, 6); + assert_eq!(stats.collections, 1, "only the replaced-table collect ran"); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.root))).expect("root")); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(graph.left))).expect("left") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(graph.right))).expect("right") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(graph.cell))).expect("cell") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.replacement))).expect("current") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.independent))) + .expect("independent") + ); + assert!(token_open(&host, graph.root_raw)); + assert!(token_open(&host, graph.replacement_raw)); + assert!(token_open(&host, graph.independent_raw)); + assert_eq!(host.resource_count(), 3); + assert_eq!( + carrier_ptr(&read_carrier(&mut host, graph.right)), + carrier_ptr(&graph.replacement_carrier) + ); + }); +} + +/// Direct closure root and a rebindable cell. This is object topology only: +/// not a recursive call, and not a guest closure carrier. +struct RecursiveCell { + frame: heap::RootFrameId, + original: ClosureRef, + observer: ClosureRef, + cell: UpvalueRef, + replacement: ClosureRef, + independent: TableRef, + independent_raw: i64, + independent_carrier: Value, + doomed_raw: i64, + doomed_carrier: Value, + independent_closure: ClosureRef, + proof_roots: u64, +} + +fn recursive_limits() -> HeapLimits { + HeapLimits { + nodes: 7, + roots: 4, + edges: 3, + max_generation: 8, + } +} + +fn read_cell( + host: &mut HostContext<'_>, + closure: ClosureRef, +) -> Result, HeapError> { + heap::with_heap(host, |heap| heap.read_cell(closure)) +} + +fn bind_recursive_cell(host: &mut HostContext<'_>) -> RecursiveCell { + heap::install(host, recursive_limits()).expect("install"); + let independent_raw = publish_raw(host); + let independent = table_ref(host, independent_raw); + let doomed_raw = publish_raw(host); + let doomed = table_ref(host, doomed_raw); + assert_eq!( + host.resource_count(), + 2, + "two table tokens, no closure token" + ); + + let (original, observer, cell, independent_closure) = heap::with_heap(host, |heap| { + let original = heap.alloc_closure()?; + let observer = heap.alloc_closure()?; + let independent_closure = heap.alloc_closure()?; + let cell = heap.alloc_upvalue()?; + Ok((original, observer, cell, independent_closure)) + }) + .expect("closures and one shared cell"); + let frame = heap::with_heap(host, |heap| heap.enter_roots(4)).expect("shared root quota"); + heap::with_heap(host, |heap| heap.write_closure_root(frame, 0, original)) + .expect("caller holds the original closure directly"); + heap::with_heap(host, |heap| heap.write_closure_root(frame, 1, observer)) + .expect("observer root"); + heap::with_heap(host, |heap| heap.write_root(frame, 2, independent)) + .expect("independent table"); + heap::with_heap(host, |heap| { + heap.write_closure_root(frame, 3, independent_closure) + }) + .expect("independent closure"); + assert_eq!( + heap::with_heap(host, |heap| heap.enter_roots(1)).expect_err("root cap"), + HeapError::RootCapacity, + "a closure root spends the same root quota as a table root" + ); + assert_eq!(heap::stats(host).expect("roots").root_slots, 4); + assert_eq!(heap::stats(host).expect("roots").live_roots, 4); + + heap::with_heap(host, |heap| { + heap.set_upvalue_edge(original, cell)?; + heap.set_upvalue_edge(observer, cell)?; + heap.write_upvalue(cell, doomed)?; + Ok(()) + }) + .expect("two closures, one cell, current table"); + let edges = heap::stats(host).expect("at edge cap"); + assert_eq!(edges.edge_slots, 3); + assert_eq!( + heap::with_heap(host, |heap| heap.set_closure_edge(independent, 1, original)) + .expect_err("no spare edge"), + HeapError::EdgeCapacity + ); + assert_eq!(heap::stats(host).expect("refused edge").edge_slots, 3); + + heap::with_heap(host, |heap| heap.write_closure_upvalue(cell, original)) + .expect("replace the table with the original closure"); + assert_eq!( + heap::stats(host).expect("overwrite").edge_slots, + 3, + "rebinding the current edge must not add a record" + ); + let alias = original; + assert_eq!( + read_cell(host, alias).expect("alias"), + Some(CellValue::Closure(original)) + ); + assert_eq!( + read_cell(host, observer).expect("observer"), + Some(CellValue::Closure(original)) + ); + assert_eq!( + heap::with_heap(host, |heap| heap.read_upvalue(original)).expect_err("table adapter"), + HeapError::WrongKind, + "a closure in the cell is not a table" + ); + assert_eq!( + read_cell(host, original).expect("kind error must not clear the cell"), + Some(CellValue::Closure(original)) + ); + + let doomed_carrier = issue(host, doomed); + let independent_carrier = issue(host, independent); + let retired = heap::collect(host).expect("retire the replaced table"); + assert_eq!( + retired.live_nodes, 5, + "the unrooted table is the only sweep" + ); + assert!( + !token_open(host, doomed_raw), + "the replaced table token is closed" + ); + assert!(token_open(host, independent_raw)); + assert_eq!(host.resource_count(), 1); + assert_eq!( + heap::with_heap(host, |heap| Ok(heap.guest_class(&doomed_carrier))).expect("class"), + heap::GuestClass::Unissued, + "holding the carrier must not keep the swept table" + ); + assert!(heap::with_heap(host, |heap| Ok(heap.closure_alive(original))).expect("original")); + + let replacement = heap::with_heap(host, |heap| heap.alloc_closure()).expect("replacement"); + heap::with_heap(host, |heap| heap.write_closure_upvalue(cell, replacement)) + .expect("rebind the shared cell"); + assert_eq!(heap::stats(host).expect("second overwrite").edge_slots, 3); + assert_eq!( + read_cell(host, alias).expect("alias sees the rebind"), + Some(CellValue::Closure(replacement)) + ); + assert_eq!( + read_cell(host, observer).expect("observer sees the rebind"), + Some(CellValue::Closure(replacement)) + ); + + let _ = heap::take_scan_meter(host).expect("clear the previous meter"); + let proof = heap::collect(host).expect("closure root keeps the old closure"); + let meter = heap::take_scan_meter(host).expect("root scan meter"); + assert_eq!(proof.live_nodes, 6); + assert_eq!( + proof.live_roots, 4, + "a live closure root is not cleared as a dead table" + ); + assert!( + heap::with_heap(host, |heap| Ok(heap.closure_alive(original))).expect("old closure"), + "the old closure stays while its direct root is held" + ); + assert!( + heap::with_heap(host, |heap| Ok(heap.closure_alive(replacement))).expect("replacement") + ); + assert_eq!( + meter.root_slot_visits, 8, + "mark and the dead-root sweep each visit the four shared root slots" + ); + assert_eq!(meter.outgoing_edge_checks, 3); + + heap::with_heap(host, |heap| heap.clear_upvalue(cell)).expect("nil the cell"); + assert_eq!( + heap::stats(host).expect("nil drops the record").edge_slots, + 2, + "nil removes the current edge and does not store a nil record" + ); + assert_eq!(read_cell(host, alias).expect("nil"), None); + assert_eq!( + read_cell(host, observer).expect("nil through the other observer"), + None + ); + let released = heap::collect(host).expect("nil releases the unrooted replacement"); + assert_eq!(released.live_nodes, 5); + assert!(!heap::with_heap(host, |heap| Ok(heap.closure_alive(replacement))).expect("released")); + assert!(heap::with_heap(host, |heap| Ok(heap.closure_alive(original))).expect("still rooted")); + assert_eq!( + read_cell(host, original).expect("nil is not an invalid handle"), + None + ); + + heap::with_heap(host, |heap| heap.write_closure_upvalue(cell, original)) + .expect("restore the self-cycle"); + assert_eq!(heap::stats(host).expect("restored").edge_slots, 3); + assert_eq!( + read_cell(host, alias).expect("restored alias"), + Some(CellValue::Closure(original)) + ); + assert_eq!( + read_cell(host, observer).expect("restored observer"), + Some(CellValue::Closure(original)) + ); + + RecursiveCell { + frame, + original, + observer, + cell, + replacement, + independent, + independent_raw, + independent_carrier, + doomed_raw, + doomed_carrier, + independent_closure, + proof_roots: meter.root_slot_visits, + } +} + +fn drop_cycle_roots(host: &mut HostContext<'_>, cycle: &RecursiveCell) { + heap::with_heap(host, |heap| heap.clear_root(cycle.frame, 0)).expect("drop original root"); + heap::with_heap(host, |heap| heap.clear_root(cycle.frame, 1)).expect("drop observer root"); +} + +#[test] +fn closure_root_shares_root_quota_and_cleanup_with_table_roots() { + let mut heap = heap::LuaHeap::new(HeapLimits { + nodes: 4, + roots: 2, + edges: 1, + max_generation: 4, + }); + let table = heap.alloc().expect("table"); + let closure = heap.alloc_closure().expect("closure"); + let frame = heap.enter_roots(2).expect("two shared slots"); + heap.write_root(frame, 0, table).expect("table root"); + heap.write_closure_root(frame, 1, closure) + .expect("closure root"); + assert_eq!(heap.enter_roots(1), Err(HeapError::RootCapacity)); + assert_eq!(heap.stats().root_slots, 2); + assert_eq!(heap.stats().live_roots, 2); + + heap.clear_root(frame, 1).expect("clear the closure root"); + assert_eq!(heap.stats().live_roots, 1); + let swept = heap.collect(); + assert_eq!(swept.live_nodes, 1, "the unrooted closure is swept"); + assert!(heap.alive(table)); + assert!(!heap.closure_alive(closure)); + assert_eq!(swept.live_roots, 1); + + heap.leave_roots(frame).expect("drop the table root too"); + assert_eq!(heap.stats().root_slots, 0); + assert_eq!(heap.stats().live_roots, 0); + let again = heap + .enter_roots(2) + .expect("quota returns to the same vector"); + let fresh = heap.alloc_closure().expect("reuse the swept slot"); + heap.write_closure_root(again, 0, fresh) + .expect("closure in a freed slot"); + heap.write_root(again, 1, table) + .expect("table in the other slot"); + assert_eq!(heap.stats().live_roots, 2); + assert_eq!(heap.collect().live_nodes, 2); +} + +#[test] +fn closure_root_and_cell_reject_foreign_and_retired_without_clobber() { + let mut heap = heap::LuaHeap::new(HeapLimits { + nodes: 4, + roots: 2, + edges: 2, + max_generation: 4, + }); + let local = heap.alloc_closure().expect("local"); + let cell = heap.alloc_upvalue().expect("cell"); + heap.set_upvalue_edge(local, cell).expect("link"); + heap.write_closure_upvalue(cell, local).expect("self-cycle"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_closure_root(frame, 0, local).expect("root"); + assert_eq!( + heap.read_upvalue(local), + Err(HeapError::WrongKind), + "the table read must not turn the closure into a table" + ); + assert_eq!( + heap.read_cell(local).expect("typed read"), + Some(CellValue::Closure(local)) + ); + + let mut other = heap::LuaHeap::new(HeapLimits { + nodes: 2, + roots: 1, + edges: 1, + max_generation: 4, + }); + let foreign = other.alloc_closure().expect("foreign"); + let foreign_cell = other.alloc_upvalue().expect("foreign cell"); + assert_eq!( + heap.write_closure_root(frame, 0, foreign), + Err(HeapError::WrongDomain) + ); + assert_eq!( + heap.write_closure_upvalue(cell, foreign), + Err(HeapError::WrongDomain) + ); + assert_eq!( + heap.clear_upvalue(foreign_cell), + Err(HeapError::WrongDomain) + ); + assert_eq!( + heap.read_cell(local).expect("unchanged cell"), + Some(CellValue::Closure(local)) + ); + assert_eq!(heap.stats().live_roots, 1); + assert_eq!(heap.stats().live_edges, 2); + assert_eq!(heap.collect().live_nodes, 2); + assert!(heap.closure_alive(local)); + + let retired = heap.alloc_closure().expect("soon retired"); + assert_eq!(heap.collect().live_nodes, 2); + assert!(!heap.closure_alive(retired)); + assert_eq!( + heap.write_closure_root(frame, 0, retired), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.write_closure_upvalue(cell, retired), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.read_cell(local) + .expect("retired write must not replace the cell"), + Some(CellValue::Closure(local)) + ); + assert_eq!(heap.stats().live_roots, 1); + assert!(heap.closure_alive(local)); + + heap.clear_root(frame, 0).expect("drop"); + assert_eq!(heap.collect().live_nodes, 0); + let empty = heap.enter_roots(1).expect("empty frame"); + assert_eq!( + heap.write_closure_root(empty, 0, local), + Err(HeapError::StaleHandle) + ); + assert_eq!(heap.clear_upvalue(cell), Err(HeapError::StaleHandle)); + assert_eq!(heap.read_cell(local), Err(HeapError::StaleHandle)); + assert_ne!( + heap.read_cell(local), + Ok(None), + "a retired closure is an invalid handle, not nil" + ); + assert_eq!(heap.stats().live_roots, 0); + assert_eq!(heap.stats().live_edges, 0); +} + +#[test] +fn closure_root_recursive_cell_rebind_is_visible_and_collect_reclaims_the_cycle() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let cycle = bind_recursive_cell(&mut host); + assert_eq!( + cycle.proof_roots, 8, + "the closure-root collect metered the root scan" + ); + drop_cycle_roots(&mut host, &cycle); + let before = heap::stats(&mut host).expect("before the cycle collect"); + assert_eq!(before.live_nodes, 5); + assert!(token_open(&host, cycle.independent_raw)); + assert!(!token_open(&host, cycle.doomed_raw)); + + let report = heap::collect(&mut host).expect("collect the unrooted cycle"); + assert_eq!(report.live_nodes, 2, "independent table and closure remain"); + assert_eq!(report.live_roots, 2); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(cycle.original))) + .expect("original") + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(cycle.observer))) + .expect("observer") + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(cycle.cell))).expect("cell") + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(cycle.replacement))) + .expect("replacement") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(cycle.independent))).expect("table") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok( + heap.closure_alive(cycle.independent_closure) + )) + .expect("independent closure") + ); + assert!(token_open(&host, cycle.independent_raw)); + assert!(!token_open(&host, cycle.doomed_raw)); + assert_eq!(host.resource_count(), 1); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok( + heap.guest_class(&cycle.independent_carrier) + )) + .expect("independent class"), + heap::GuestClass::Table(cycle.independent) + ); + assert_eq!( + heap::with_heap( + &mut host, + |heap| Ok(heap.guest_class(&cycle.doomed_carrier)) + ) + .expect("doomed class"), + heap::GuestClass::Unissued + ); + assert_eq!( + read_cell(&mut host, cycle.original).expect_err("retired closure"), + HeapError::StaleHandle + ); + }); +} + +#[test] +fn closure_root_recursive_cell_omitting_the_final_collect_leaves_the_cycle() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let cycle = bind_recursive_cell(&mut host); + drop_cycle_roots(&mut host, &cycle); + let stats = heap::stats(&mut host).expect("omitted collect"); + assert_eq!(stats.live_nodes, 5); + assert_eq!( + stats.collections, 3, + "only the earlier release collects ran" + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(cycle.original))) + .expect("original") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(cycle.observer))) + .expect("observer") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(cycle.cell))).expect("cell") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(cycle.independent))).expect("table") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok( + heap.closure_alive(cycle.independent_closure) + )) + .expect("independent closure") + ); + assert_eq!( + read_cell(&mut host, cycle.observer).expect("still linked"), + Some(CellValue::Closure(cycle.original)) + ); + assert!(token_open(&host, cycle.independent_raw)); + assert!(!token_open(&host, cycle.doomed_raw)); + assert_eq!(host.resource_count(), 1); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok( + heap.guest_class(&cycle.independent_carrier) + )) + .expect("independent class"), + heap::GuestClass::Table(cycle.independent) + ); + }); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index c4512ee..5594f44 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -3,6 +3,8 @@ #[allow(dead_code)] mod ast; mod candidate; +#[path = "closure_graph.rs"] +mod closure_graph; #[path = "../../src/frontends/lua/lexer.rs"] #[allow(dead_code)] mod lexer; From 139f89638ef6a968a013bc3e23dd5de56dec42e7 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 15:52:50 +0800 Subject: [PATCH 062/225] feat(lua): keep a chunk do root through one forward goto A resolver-proven jump to a later direct label in the same block keeps one retained segment. The skipped statements are not lowered, the statements after the label are, and retire_block is still the only exit. --- tests/luajit_heap_runtime/candidate.rs | 147 ++++++++++--- .../value_boundary_tests.rs | 201 ++++++++++++++++++ 2 files changed, 321 insertions(+), 27 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index b8ba19d..01b0642 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1291,31 +1291,60 @@ impl Lower<'_> { /// `live_locals`. Same-name outer slots stay where they are, including a /// slot already removed by `= nil`. A function body is not this path. /// - /// A resolver-proven `goto` whose target is in this block's trailing label - /// set does not emit the suffix. The set is every direct label the - /// resolver marked `trailing`: only labels and empty statements follow it. - /// The target index is matched to a direct child by that label's span, not - /// by name. `retire_block` is still the exit, so executed bindings drop - /// their roots. This is not the `control.rs` state dispatcher. + /// The lowered list is one retained segment. `retire_block` still runs + /// once, at this statement's end, not at the label. This is not the + /// `control.rs` state dispatcher. fn lower_do(&mut self, span: ast::Span, body: &ast::Block) -> Result<(), ParseError> { - let statements = match self.tail_goto_cut(body)? { - Some(cut) => &body.stmts[..cut], - None => body.stmts.as_slice(), - }; - for stmt in statements { + for stmt in self.retained_statements(span, body)? { self.lower_stmt(stmt)?; } self.retire_block(span, body) } - /// Index of the one direct `goto` whose resolved target is in this block's - /// trailing label set. `None` keeps the straight path. The resolver index - /// is matched to a direct child by label span, not by name, so a - /// same-named label in another block is not this target. A non-trailing - /// label in this block stays unsupported. `scope_id` is not a second - /// check: that direct-child span is already this block. A different goto - /// stays unsupported instead of falling through the suffix. - fn tail_goto_cut(&self, body: &ast::Block) -> Result, ParseError> { + /// Statements this chunk `do` lowers, in source order. Labels are not + /// runtime statements. Empty statements stay, including a trailing `;`. + /// + /// With no direct `goto`, that is the whole block. One direct unconditional + /// `goto` whose resolver target is a later direct child keeps the prefix + /// and the statements after that label, and drops the jump plus the + /// statements between them. A trailing label is the same shape: only + /// labels and empty statements follow it, so the kept tail is those + /// semicolons. The target id is matched by label span, not by name. + fn retained_statements<'b>( + &self, + span: ast::Span, + body: &'b ast::Block, + ) -> Result, ParseError> { + let skip = self.forward_goto_skip(span, body)?; + let mut kept = Vec::new(); + for (index, stmt) in body.stmts.iter().enumerate() { + if matches!(stmt, ast::Stmt::Label { .. }) { + continue; + } + if let Some((goto_index, label_index)) = skip + && index >= goto_index + && index < label_index + { + continue; + } + kept.push(stmt); + } + Ok(kept) + } + + /// Bounds of the one direct forward `goto` this block can structure. + /// `None` is the straight path. The resolver target must be a direct child + /// later in this block. Its scope must be this block's scope when the + /// block has locals, and must not be a nested block's scope. Another goto + /// whose target lies in the skipped span is excluded: that shape needs a + /// graph, and this path does not invent one. A second direct goto, a + /// backward jump, or a target in another block stays unsupported instead + /// of falling through the skipped statements. + fn forward_goto_skip( + &self, + span: ast::Span, + body: &ast::Block, + ) -> Result, ParseError> { let mut found = None; for (index, stmt) in body.stmts.iter().enumerate() { let ast::Stmt::Goto { @@ -1329,7 +1358,7 @@ impl Lower<'_> { } found = Some((index, *goto_span)); } - let Some((index, goto_span)) = found else { + let Some((goto_index, goto_span)) = found else { return Ok(None); }; let jump = self @@ -1346,15 +1375,79 @@ impl Lower<'_> { let Some(label) = self.resolution.labels.get(target) else { return Err(self.statement_unsupported(goto_span)); }; - let in_trailing_set = label.trailing - && label.function_id == 0 - && body.stmts.iter().any( - |stmt| matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span), - ); - if !in_trailing_set { + if label.function_id != 0 || !self.label_names_this_block(span, body, label) { + return Err(self.statement_unsupported(goto_span)); + } + let Some(label_index) = body.stmts.iter().position( + |stmt| matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span), + ) else { + return Err(self.statement_unsupported(goto_span)); + }; + if label_index <= goto_index + || self.outside_goto_enters_skip(body, goto_index, label_index, goto_span) + { return Err(self.statement_unsupported(goto_span)); } - Ok(Some(index)) + Ok(Some((goto_index, label_index))) + } + + /// Direct-child span already places the label in this block. When the + /// block has locals, their `scope_id` must be the label's scope. A nested + /// block's binding uses another scope and must not share this name. + fn label_names_this_block( + &self, + span: ast::Span, + body: &ast::Block, + label: &resolve::LabelBinding, + ) -> bool { + for binding in &self.resolution.bindings { + if binding.function_id != 0 { + continue; + } + let inside = binding.span.start >= body.span.start && binding.span.end <= body.span.end; + if !inside { + continue; + } + if binding.visible_to == span.end { + if binding.scope_id != label.scope_id { + return false; + } + } else if binding.scope_id == label.scope_id { + return false; + } + } + true + } + + /// True when some other goto targets a label inside the skipped statements. + /// The structuring goto itself lands on the label after that span. + fn outside_goto_enters_skip( + &self, + body: &ast::Block, + goto_index: usize, + label_index: usize, + goto_span: ast::Span, + ) -> bool { + let skipped = &body.stmts[goto_index + 1..label_index]; + let Some(first) = skipped.first() else { + return false; + }; + let start = stmt_span(first).start; + let end = stmt_span(skipped.last().expect("skipped statement")).end; + self.resolution.gotos.iter().any(|jump| { + if jump.span == goto_span { + return false; + } + let Some(target) = jump.target else { + return true; + }; + let Some(label) = self.resolution.labels.get(target) else { + return true; + }; + let outside = jump.span.end <= start || jump.span.start >= end; + let inside = label.span.start >= start && label.span.end <= end; + outside && inside + }) } fn statement_unsupported(&self, span: ast::Span) -> ParseError { diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 5594f44..e3e01c3 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -4005,3 +4005,204 @@ return rawget(owner, 1e400) assert_eq!(vm.stack(), &[Value::string("bits")]); assert_eq!(heap::stats(&mut vm.host_context()).unwrap().live_edges, 1); } + +// Chunk `do` jumps forward to its own non-trailing label. The label is not in +// the trailing set: `collectgarbage` follows it. The goto is the block's only +// direct jump, so the statements between it and that label are not lowered. +// `marker.skipped = {}` therefore publishes no node. The statements after the +// label do run, and the in-block collect happens while `t` is still that +// block's root. Leaving the block is the one `retire_block`. The next collect +// clears the weak value and retires the original token. Omitting it leaves +// the same token. Omitting the goto runs the skipped write. A nested block +// with the same label name is a different span. A jump over a same-block +// local is a resolver error, not a lowered path. This does not pin an +// unimplemented goto's diagnostic text. +#[test] +fn lua_candidate_chunk_do_forward_goto_keeps_root_until_block_exit() { + let nested = parser::parse_chunk( + b"do\n goto resume\n do\n ::resume::\n end\n marker.skipped = {}\n ::resume::\n collectgarbage(\"collect\")\nend\n", + ) + .expect("parse nested same name"); + let resolution = resolve::resolve(&nested); + assert!( + resolution.errors.is_empty(), + "a nested same name is not this block's label: {:?}", + resolution.errors + ); + let target = resolution.gotos[0].target.expect("outer resume"); + let label = &resolution.labels[target]; + assert_eq!(label.name, b"resume"); + assert!(!label.trailing, "collectgarbage follows the label"); + let ast::Stmt::Do { body, .. } = &nested.body.stmts[0] else { + panic!("outer do"); + }; + let ast::Stmt::Do { body: inner, .. } = &body.stmts[1] else { + panic!("nested do"); + }; + assert!( + inner.stmts.iter().all(|stmt| { + !matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span) + }), + "the nested name is a different label" + ); + assert!( + body.stmts.iter().any(|stmt| { + matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span) + }), + "the resolved target is a direct child" + ); + + let into_local = parser::parse_chunk( + b"do\n goto resume\n local hidden = {}\n ::resume::\n local after = 1\nend\n", + ) + .expect("parse jump into local"); + let resolution = resolve::resolve(&into_local); + assert!( + matches!( + resolution.errors.first(), + Some(resolve::ResolveError::JumpIntoLocal { local_name, .. }) + if local_name == b"hidden" + ), + "a non-trailing label cannot enter a same-block local: {:?}", + resolution.errors + ); + + let source = r#" +local mt = {} +mt.__mode = "v" +local weak = {} +setmetatable(weak, mt) +local marker = {} +observe_table(weak, 0) +observe_table(marker, 0) +do + local t = {} + t.self = t + weak.seen = t + observe_table(t, 0) +@jump@ + marker.skipped = {} + ::resume:: + observe_table(t, 0) + observe_table(weak.seen, 0) + collectgarbage("collect") + observe_table(t, 0) + observe_table(weak.seen, 0) +end +@after@ +"#; + let collect_after = "\ +collectgarbage(\"collect\") +observe_table(weak, 0) +observe_table(marker, 0) +return type(weak.seen) +"; + let omit_after = "\ +observe_table(weak.seen, 0) +observe_table(weak, 0) +observe_table(marker, 0) +return type(weak.seen) +"; + let fall_after = "\ +collectgarbage(\"collect\") +observe_table(marker.skipped, 0) +observe_table(weak, 0) +observe_table(marker, 0) +return type(weak.seen) +"; + for (jump, after, result, collections, live_nodes, live_edges, resources, observations) in [ + ( + " goto resume\n", + omit_after, + "table", + 1u32, + 4u32, + 3u32, + 4usize, + 10usize, + ), + (" goto resume\n", collect_after, "nil", 2, 3, 1, 3, 9), + ("", fall_after, "nil", 2, 4, 2, 4, 10), + ] { + let mut vm = candidate(&source.replace("@jump@", jump).replace("@after@", after)); + assert_eq!( + vm.run().expect("run forward goto"), + VmStatus::Halted, + "{result}/{collections}" + ); + assert_eq!( + vm.stack(), + &[Value::string(result)], + "{result}/{collections}" + ); + let mut host = vm.host_context(); + let tables = host.scope_state::>().unwrap().clone(); + assert_eq!( + tables.len(), + observations, + "{result}/{collections}: skipped write must not add an observation on the goto arms" + ); + let weak = tables[0]; + let marker = tables[1]; + let created = tables[2]; + let after_label = tables[3]; + let seen_before = tables[4]; + let after_collect = tables[5]; + let seen_after = tables[6]; + assert_ne!(weak, marker, "{result}/{collections}"); + assert_ne!(created, weak, "{result}/{collections}"); + assert_ne!(created, marker, "{result}/{collections}"); + assert_eq!( + after_label, created, + "{result}/{collections}: the label's following read is t" + ); + assert_eq!( + seen_before, created, + "{result}/{collections}: weak.seen before the in-block collect is t" + ); + assert_eq!( + after_collect, created, + "{result}/{collections}: in-block collect keeps the same token" + ); + assert_eq!( + seen_after, created, + "{result}/{collections}: the weak read after that collect is still t" + ); + let dropped = result == "nil"; + if jump.is_empty() { + let skipped = tables[7]; + let weak_after = tables[8]; + let marker_after = tables[9]; + assert_ne!(skipped, created, "the skipped write publishes a new table"); + assert_ne!(skipped, marker, "marker.skipped is not marker"); + assert_ne!(skipped, weak, "marker.skipped is not weak"); + assert_eq!(weak_after, weak); + assert_eq!(marker_after, marker); + assert_table_lifetime(&mut host, skipped, true); + } else { + let (weak_after, marker_after) = if dropped { + (tables[7], tables[8]) + } else { + let seen_outside = tables[7]; + assert_eq!( + seen_outside, created, + "omitted collect leaves the same token in weak.seen" + ); + assert_table_lifetime(&mut host, seen_outside, true); + (tables[8], tables[9]) + }; + assert_eq!(weak_after, weak, "{result}"); + assert_eq!(marker_after, marker, "{result}"); + } + assert_table_lifetime(&mut host, created, !dropped); + assert_table_lifetime(&mut host, weak, true); + assert_table_lifetime(&mut host, marker, true); + let stats = heap::stats(&mut host).unwrap(); + let label = format!("{result}/{collections}"); + assert_eq!(stats.collections, collections, "{label}"); + assert_eq!(stats.live_nodes, live_nodes, "{label}"); + assert_eq!(stats.live_edges, live_edges, "{label}"); + assert_eq!(stats.live_roots, 0, "{label}"); + assert_eq!(host.resource_count(), resources, "{label}"); + } +} From b1fee3f2b6413334b533064a913ed47d52f4bf86 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 16:19:30 +0800 Subject: [PATCH 063/225] refactor(lua): drop the redundant chunk do label scope scan The direct-child label span already places the target in this block. Scanning bindings by visible_to and scope_id does not accept or reject any shape that span match does not already decide. The resolver id, function_id, forward bound, skipped-span guard, and one retire_block stay. --- tests/luajit_heap_runtime/candidate.rs | 54 +++++--------------------- 1 file changed, 10 insertions(+), 44 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 01b0642..3fa54a2 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1295,7 +1295,7 @@ impl Lower<'_> { /// once, at this statement's end, not at the label. This is not the /// `control.rs` state dispatcher. fn lower_do(&mut self, span: ast::Span, body: &ast::Block) -> Result<(), ParseError> { - for stmt in self.retained_statements(span, body)? { + for stmt in self.retained_statements(body)? { self.lower_stmt(stmt)?; } self.retire_block(span, body) @@ -1312,10 +1312,9 @@ impl Lower<'_> { /// semicolons. The target id is matched by label span, not by name. fn retained_statements<'b>( &self, - span: ast::Span, body: &'b ast::Block, ) -> Result, ParseError> { - let skip = self.forward_goto_skip(span, body)?; + let skip = self.forward_goto_skip(body)?; let mut kept = Vec::new(); for (index, stmt) in body.stmts.iter().enumerate() { if matches!(stmt, ast::Stmt::Label { .. }) { @@ -1333,18 +1332,13 @@ impl Lower<'_> { } /// Bounds of the one direct forward `goto` this block can structure. - /// `None` is the straight path. The resolver target must be a direct child - /// later in this block. Its scope must be this block's scope when the - /// block has locals, and must not be a nested block's scope. Another goto - /// whose target lies in the skipped span is excluded: that shape needs a - /// graph, and this path does not invent one. A second direct goto, a - /// backward jump, or a target in another block stays unsupported instead - /// of falling through the skipped statements. - fn forward_goto_skip( - &self, - span: ast::Span, - body: &ast::Block, - ) -> Result, ParseError> { + /// `None` is the straight path. The resolver target must be a later + /// direct child of this block. Another goto whose target lies in the + /// skipped span is excluded: that shape needs a graph, and this path + /// does not invent one. A second direct goto, a backward jump, or a + /// target in another block stays unsupported instead of falling through + /// the skipped statements. + fn forward_goto_skip(&self, body: &ast::Block) -> Result, ParseError> { let mut found = None; for (index, stmt) in body.stmts.iter().enumerate() { let ast::Stmt::Goto { @@ -1375,7 +1369,7 @@ impl Lower<'_> { let Some(label) = self.resolution.labels.get(target) else { return Err(self.statement_unsupported(goto_span)); }; - if label.function_id != 0 || !self.label_names_this_block(span, body, label) { + if label.function_id != 0 { return Err(self.statement_unsupported(goto_span)); } let Some(label_index) = body.stmts.iter().position( @@ -1391,34 +1385,6 @@ impl Lower<'_> { Ok(Some((goto_index, label_index))) } - /// Direct-child span already places the label in this block. When the - /// block has locals, their `scope_id` must be the label's scope. A nested - /// block's binding uses another scope and must not share this name. - fn label_names_this_block( - &self, - span: ast::Span, - body: &ast::Block, - label: &resolve::LabelBinding, - ) -> bool { - for binding in &self.resolution.bindings { - if binding.function_id != 0 { - continue; - } - let inside = binding.span.start >= body.span.start && binding.span.end <= body.span.end; - if !inside { - continue; - } - if binding.visible_to == span.end { - if binding.scope_id != label.scope_id { - return false; - } - } else if binding.scope_id == label.scope_id { - return false; - } - } - true - } - /// True when some other goto targets a label inside the skipped statements. /// The structuring goto itself lands on the label after that span. fn outside_goto_enters_skip( From d1cd2c36ee78f6253ccfa4e14a43d09f34aab638 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 17:03:51 +0800 Subject: [PATCH 064/225] feat(lua): root an open upvalue from the active frame A cell uses the same frame slots and collector as tables and closures. Clearing that slot does not copy or clear the cell's current value. --- src/frontends/lua/heap.rs | 6 +- src/frontends/lua/heap/table.rs | 44 +- tests/luajit_heap_runtime/closure_graph.rs | 445 +++++++++++++++++++++ 3 files changed, 481 insertions(+), 14 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 253ba1a..d1700e8 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -25,7 +25,7 @@ //! measured production collection scheme. //! //! Closure and upvalue nodes use the same slots, edges, roots, meter, and -//! sweep. A root slot holds a table or a closure. A table field can point at +//! sweep. A root slot holds a table, a closure, or an upvalue. A table field can point at //! a closure, a closure at one shared upvalue, and that upvalue at its current //! table or closure. A missing current edge is nil. Two closures can point at //! the same upvalue. Those nodes have no guest carrier and no Core resource @@ -36,8 +36,8 @@ //! `/mnt/workspace/rustscript-lua/evidence/lua52-gc-arg-order/qualification.md`. //! When `.lua` is connected, that stage consumes the sample. A collection //! witness must be a helper that only returns a boolean; do not inline-read a -//! weak referent from the caller. This milestone has no Lua weak tables -//! (`__mode`). +//! weak referent from the caller. Only a table entry follows `__mode`. A +//! frame root is not a weak edge. #[path = "heap/handle.rs"] mod handle; diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 82b9e12..e7a4302 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -239,11 +239,12 @@ pub enum CellValue { Closure(ClosureRef), } -/// One explicit root. Table and closure roots share the root vector. +/// One explicit root. Table, closure, and upvalue roots share the root vector. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Rooted { Table(TableRef), Closure(ClosureRef), + Upvalue(UpvalueRef), } impl Rooted { @@ -251,6 +252,7 @@ impl Rooted { match self { Self::Table(handle) => handle.slot(), Self::Closure(handle) => handle.slot(), + Self::Upvalue(handle) => handle.slot(), } } } @@ -1209,8 +1211,9 @@ impl LuaHeap { }) } - /// Stores `handle` in an open frame. The frame does not have to be the - /// top frame; a stale id is refused. + /// Stores `handle` in an open frame. A closure uses [`Self::write_closure_root`]. + /// An upvalue uses [`Self::write_upvalue_root`]. The frame does not have to + /// be the top frame; a stale id is refused. pub fn write_root( &mut self, frame: RootFrameId, @@ -1218,13 +1221,7 @@ impl LuaHeap { handle: TableRef, ) -> Result<(), HeapError> { self.require_live(handle)?; - let found = self.frame(frame)?; - if slot >= found.width { - return Err(HeapError::StaleFrame); - } - let index = found.start as usize + slot as usize; - self.roots[index] = Some(Rooted::Table(handle)); - Ok(()) + self.store_root(frame, slot, Rooted::Table(handle)) } /// Stores a closure in an open frame. Same vector and quota as a table root. @@ -1237,12 +1234,36 @@ impl LuaHeap { handle: ClosureRef, ) -> Result<(), HeapError> { self.require_closure(handle)?; + self.store_root(frame, slot, Rooted::Closure(handle)) + } + + /// Stores an upvalue in an open frame. Same vector, quota, and collector + /// as a table or closure root. + /// + /// The slot roots the cell. It does not copy or clear the current edge. + /// A stale, foreign, or wrong-kind handle is refused before the slot changes. + pub fn write_upvalue_root( + &mut self, + frame: RootFrameId, + slot: u32, + handle: UpvalueRef, + ) -> Result<(), HeapError> { + self.require_upvalue(handle)?; + self.store_root(frame, slot, Rooted::Upvalue(handle)) + } + + fn store_root( + &mut self, + frame: RootFrameId, + slot: u32, + rooted: Rooted, + ) -> Result<(), HeapError> { let found = self.frame(frame)?; if slot >= found.width { return Err(HeapError::StaleFrame); } let index = found.start as usize + slot as usize; - self.roots[index] = Some(Rooted::Closure(handle)); + self.roots[index] = Some(rooted); Ok(()) } @@ -1746,6 +1767,7 @@ impl LuaHeap { match rooted { Rooted::Table(handle) => self.alive(handle), Rooted::Closure(handle) => self.closure_alive(handle), + Rooted::Upvalue(handle) => self.upvalue_alive(handle), } } diff --git a/tests/luajit_heap_runtime/closure_graph.rs b/tests/luajit_heap_runtime/closure_graph.rs index 8c1f1cb..d595422 100644 --- a/tests/luajit_heap_runtime/closure_graph.rs +++ b/tests/luajit_heap_runtime/closure_graph.rs @@ -1265,3 +1265,448 @@ fn closure_root_recursive_cell_omitting_the_final_collect_leaves_the_cycle() { ); }); } + +/// One frame slot roots the open cell. The captured table has no root of its own. +struct OpenCell { + frame: heap::RootFrameId, + cell: UpvalueRef, + original: TableRef, + original_raw: i64, + original_carrier: Value, + sibling: TableRef, + sibling_raw: i64, +} + +fn open_cell_limits() -> HeapLimits { + HeapLimits { + nodes: 4, + roots: 1, + edges: 2, + max_generation: 4, + } +} + +fn root_open_cell(host: &mut HostContext<'_>) -> OpenCell { + heap::install(host, open_cell_limits()).expect("install"); + let original_raw = publish_raw(host); + let original = table_ref(host, original_raw); + let sibling_raw = publish_raw(host); + let sibling = table_ref(host, sibling_raw); + let cell = heap::with_heap(host, |heap| heap.alloc_upvalue()).expect("cell"); + heap::with_heap(host, |heap| heap.write_upvalue(cell, original)).expect("capture"); + let frame = heap::with_heap(host, |heap| heap.enter_roots(1)).expect("one slot"); + heap::with_heap(host, |heap| heap.write_upvalue_root(frame, 0, cell)) + .expect("the frame slot roots the cell"); + assert_eq!( + heap::with_heap(host, |heap| heap.enter_roots(1)).expect_err("shared quota"), + HeapError::RootCapacity, + "an upvalue root spends the same root quota as a table root" + ); + let stats = heap::stats(host).expect("rooted cell"); + assert_eq!(stats.live_roots, 1, "the cell is the only root"); + assert_eq!( + stats.root_slots, 1, + "the table has no independent root slot" + ); + assert_eq!( + stats.live_edges, 1, + "the current edge is the only stored value" + ); + assert_eq!(stats.live_nodes, 3, "two tables and one cell"); + let original_carrier = issue(host, original); + OpenCell { + frame, + cell, + original, + original_raw, + original_carrier, + sibling, + sibling_raw, + } +} + +fn collect_open_sibling(host: &mut HostContext<'_>, open: &OpenCell) { + let _ = heap::take_scan_meter(host).expect("clear setup meter"); + let report = heap::collect(host).expect("collect the unrooted sibling"); + let meter = heap::take_scan_meter(host).expect("same collector"); + assert_eq!(meter.mark_passes, 1); + assert_eq!( + meter.outgoing_edge_checks, 1, + "mark follows the current edge from the rooted cell" + ); + assert_eq!( + meter.root_slot_visits, 2, + "mark and the dead-root sweep each visit the one frame slot" + ); + assert_eq!( + meter.token_closes, 1, + "the sibling token is closed by this collect" + ); + assert_eq!(report.live_nodes, 2, "the cell and its current table stay"); + assert_eq!(report.live_roots, 1); + assert!(heap::with_heap(host, |heap| Ok(heap.upvalue_alive(open.cell))).expect("cell")); + assert!(heap::with_heap(host, |heap| Ok(heap.alive(open.original))).expect("table")); + assert!(!heap::with_heap(host, |heap| Ok(heap.alive(open.sibling))).expect("sibling")); + assert!(token_open(host, open.original_raw)); + assert!(!token_open(host, open.sibling_raw)); + assert_eq!(host.resource_count(), 1); + assert_eq!( + heap::with_heap(host, |heap| Ok(heap.guest_class(&open.original_carrier))).expect("class"), + heap::GuestClass::Table(open.original) + ); +} + +/// The active frame's one slot keeps the captured table. No table root is stored. +/// After that collect, clearing the slot lets the unescaped cell and table die. +#[test] +fn frame_owned_cell_keeps_the_table_then_clear_and_collect_reclaims_it() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let open = root_open_cell(&mut host); + collect_open_sibling(&mut host, &open); + + let reader = heap::with_heap(&mut host, |heap| heap.alloc_closure()).expect("reader"); + assert_eq!( + reader.slot(), + open.sibling.slot(), + "the swept sibling slot is reused" + ); + assert_ne!(reader.generation(), open.sibling.generation()); + heap::with_heap(&mut host, |heap| heap.set_upvalue_edge(reader, open.cell)) + .expect("read through the surviving cell"); + let seen = read_carrier(&mut host, reader); + assert_eq!( + carrier_ptr(&seen), + carrier_ptr(&open.original_carrier), + "clearing is not required for the current edge to stay the original table" + ); + + heap::with_heap(&mut host, |heap| heap.clear_root(open.frame, 0)).expect("block exit"); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())).expect("frame"), + Some(open.frame), + "clearing the slot does not retire the frame" + ); + assert_eq!(heap::stats(&mut host).expect("cleared").live_roots, 0); + assert_eq!(heap::stats(&mut host).expect("cleared").root_slots, 1); + let still = read_carrier(&mut host, reader); + assert_eq!( + carrier_ptr(&still), + carrier_ptr(&open.original_carrier), + "clearing the root must not copy or clear the current value" + ); + + let report = heap::collect(&mut host).expect("collect the unescaped cell"); + assert_eq!(report.live_nodes, 0); + assert_eq!(report.live_roots, 0); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(open.cell))).expect("cell") + ); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(open.original))).expect("table")); + assert!(!token_open(&host, open.original_raw)); + assert_eq!(host.resource_count(), 0); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok( + heap.guest_class(&open.original_carrier) + )) + .expect("class"), + heap::GuestClass::Unissued + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_cell(reader)).expect_err("swept reader"), + HeapError::StaleHandle + ); + }); +} + +/// Clearing the frame slot does not destroy the cell. The paired collect does. +#[test] +fn frame_owned_cell_clear_without_collect_keeps_the_table() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let open = root_open_cell(&mut host); + collect_open_sibling(&mut host, &open); + heap::with_heap(&mut host, |heap| heap.clear_root(open.frame, 0)).expect("block exit"); + let stats = heap::stats(&mut host).expect("omitted collect"); + assert_eq!(stats.collections, 1, "only the sibling collect ran"); + assert_eq!(stats.live_nodes, 2); + assert_eq!(stats.live_roots, 0); + assert_eq!(stats.root_slots, 1, "the frame is still active"); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(open.cell))).expect("cell") + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(open.original))).expect("table")); + assert!(token_open(&host, open.original_raw)); + assert!(!token_open(&host, open.sibling_raw)); + assert_eq!(host.resource_count(), 1); + let reader = heap::with_heap(&mut host, |heap| heap.alloc_closure()).expect("reader"); + heap::with_heap(&mut host, |heap| heap.set_upvalue_edge(reader, open.cell)).expect("link"); + let seen = read_carrier(&mut host, reader); + assert_eq!( + carrier_ptr(&seen), + carrier_ptr(&open.original_carrier), + "root cleanup must not copy or clear the current value" + ); + }); +} + +fn shared_slot_limits() -> HeapLimits { + HeapLimits { + nodes: 8, + roots: 3, + edges: 4, + max_generation: 8, + } +} + +/// Two closures share the old cell. Block exit clears only that root slot. +/// The same slot then roots a new cell. The old closures still read the old value. +#[test] +fn escaped_closures_keep_the_old_cell_after_the_frame_slot_is_reused() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, shared_slot_limits()).expect("install"); + let original_raw = publish_raw(&mut host); + let original = table_ref(&host, original_raw); + let orphan_raw = publish_raw(&mut host); + let orphan = table_ref(&host, orphan_raw); + let (left, right, old_cell) = heap::with_heap(&mut host, |heap| { + let left = heap.alloc_closure()?; + let right = heap.alloc_closure()?; + let old_cell = heap.alloc_upvalue()?; + heap.set_upvalue_edge(left, old_cell)?; + heap.set_upvalue_edge(right, old_cell)?; + heap.write_upvalue(old_cell, original)?; + Ok((left, right, old_cell)) + }) + .expect("two closures, one cell"); + let frame = heap::with_heap(&mut host, |heap| heap.enter_roots(3)).expect("outer frame"); + heap::with_heap(&mut host, |heap| { + heap.write_upvalue_root(frame, 0, old_cell) + }) + .expect("open cell root"); + heap::with_heap(&mut host, |heap| heap.write_closure_root(frame, 1, left)) + .expect("left escape root"); + heap::with_heap(&mut host, |heap| heap.write_closure_root(frame, 2, right)) + .expect("right escape root"); + let original_carrier = issue(&mut host, original); + + let _ = heap::take_scan_meter(&mut host).expect("clear setup meter"); + let first = heap::collect(&mut host).expect("collect the orphan"); + let first_meter = heap::take_scan_meter(&mut host).expect("first meter"); + assert_eq!(first_meter.mark_passes, 1); + assert_eq!(first_meter.outgoing_edge_checks, 3); + assert_eq!(first_meter.root_slot_visits, 6); + assert_eq!(first_meter.token_closes, 1); + assert_eq!(first.live_nodes, 4); + assert!(!token_open(&host, orphan_raw)); + assert!(token_open(&host, original_raw)); + assert_eq!( + carrier_ptr(&read_carrier(&mut host, left)), + carrier_ptr(&original_carrier) + ); + assert_eq!( + carrier_ptr(&read_carrier(&mut host, right)), + carrier_ptr(&original_carrier) + ); + + heap::with_heap(&mut host, |heap| heap.clear_root(frame, 0)).expect("block exit"); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())).expect("outer frame"), + Some(frame), + "block exit clears one slot and leaves the outer frame active" + ); + assert_eq!(heap::stats(&mut host).expect("after exit").live_roots, 2); + assert_eq!(heap::stats(&mut host).expect("after exit").root_slots, 3); + assert_eq!( + carrier_ptr(&read_carrier(&mut host, left)), + carrier_ptr(&original_carrier), + "clearing the open root must not copy or clear the old value" + ); + + let new_cell = heap::with_heap(&mut host, |heap| heap.alloc_upvalue()).expect("new cell"); + assert_eq!( + new_cell.slot(), + orphan.slot(), + "the swept orphan slot is reused" + ); + assert_ne!(new_cell.generation(), orphan.generation()); + heap::with_heap(&mut host, |heap| { + heap.write_upvalue_root(frame, 0, new_cell) + }) + .expect("reuse the same frame slot"); + assert_eq!(heap::stats(&mut host).expect("reused").live_roots, 3); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(left)).expect("left still old"), + old_cell + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(right)).expect("right still old"), + old_cell + ); + + let fresh_raw = publish_raw(&mut host); + let fresh = table_ref(&host, fresh_raw); + heap::with_heap(&mut host, |heap| heap.write_upvalue(new_cell, fresh)) + .expect("first new value"); + let fresh_carrier = issue(&mut host, fresh); + let replacement_raw = publish_raw(&mut host); + let replacement = table_ref(&host, replacement_raw); + heap::with_heap(&mut host, |heap| heap.write_upvalue(new_cell, replacement)) + .expect("change the new cell"); + let replacement_carrier = issue(&mut host, replacement); + assert_eq!(heap::stats(&mut host).expect("overwrite").edge_slots, 4); + assert_eq!( + carrier_ptr(&read_carrier(&mut host, right)), + carrier_ptr(&original_carrier), + "the old closure still reads the original table" + ); + assert_ne!( + carrier_ptr(&read_carrier(&mut host, left)), + carrier_ptr(&replacement_carrier) + ); + assert_ne!( + carrier_ptr(&read_carrier(&mut host, left)), + carrier_ptr(&fresh_carrier) + ); + + let middle = heap::collect(&mut host).expect("survival follows existing roots"); + let middle_meter = heap::take_scan_meter(&mut host).expect("middle meter"); + assert_eq!(middle_meter.mark_passes, 1); + assert_eq!(middle_meter.outgoing_edge_checks, 4); + assert_eq!(middle_meter.root_slot_visits, 6); + assert_eq!(middle_meter.token_closes, 1); + assert_eq!(middle.live_nodes, 6); + assert_eq!(middle.live_roots, 3); + assert!( + !token_open(&host, fresh_raw), + "the replaced new value is collected" + ); + assert!(token_open(&host, original_raw)); + assert!(token_open(&host, replacement_raw)); + assert_eq!(host.resource_count(), 2); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(old_cell))).expect("old cell") + ); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(new_cell))).expect("new cell") + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&fresh_carrier))).expect("fresh"), + heap::GuestClass::Unissued + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&replacement_carrier))) + .expect("replacement"), + heap::GuestClass::Table(replacement) + ); + + heap::with_heap(&mut host, |heap| heap.clear_root(frame, 1)).expect("drop left root"); + heap::with_heap(&mut host, |heap| heap.clear_root(frame, 2)).expect("drop right root"); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())).expect("still outer"), + Some(frame) + ); + assert_eq!(heap::stats(&mut host).expect("roots dropped").live_roots, 1); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(old_cell))) + .expect("clear does not destroy") + ); + assert_eq!( + carrier_ptr(&read_carrier(&mut host, left)), + carrier_ptr(&original_carrier), + "dropping the closure roots must not rewrite the old cell" + ); + + let final_report = heap::collect(&mut host).expect("collect the old path"); + let final_meter = heap::take_scan_meter(&mut host).expect("final meter"); + assert_eq!(final_meter.mark_passes, 1); + assert_eq!(final_meter.outgoing_edge_checks, 1); + assert_eq!(final_meter.token_closes, 1); + assert_eq!( + final_report.live_nodes, 2, + "the new cell and its table stay" + ); + assert_eq!(final_report.live_roots, 1); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(old_cell))).expect("old")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(left))).expect("left")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(right))).expect("right")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(original))).expect("old table")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(new_cell))).expect("new")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(replacement))).expect("new table")); + assert!( + !token_open(&host, original_raw), + "the old table token is retired" + ); + assert!(token_open(&host, replacement_raw)); + assert_eq!(host.resource_count(), 1); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&original_carrier))) + .expect("old class"), + heap::GuestClass::Unissued + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&replacement_carrier))) + .expect("new class"), + heap::GuestClass::Table(replacement) + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(left)).expect_err("old path"), + HeapError::StaleHandle + ); + }); +} + +/// A foreign or retired cell is refused by the existing handle check. +/// The occupied frame slot stays on the live cell. +#[test] +fn upvalue_root_rejects_foreign_and_stale_without_clobber() { + let mut heap = heap::LuaHeap::new(HeapLimits { + nodes: 4, + roots: 1, + edges: 1, + max_generation: 4, + }); + let table = heap.alloc().expect("table"); + let cell = heap.alloc_upvalue().expect("cell"); + heap.write_upvalue(cell, table).expect("capture"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_upvalue_root(frame, 0, cell).expect("root"); + + let mut other = heap::LuaHeap::new(HeapLimits { + nodes: 1, + roots: 1, + edges: 1, + max_generation: 4, + }); + let foreign = other.alloc_upvalue().expect("foreign"); + assert_eq!( + heap.write_upvalue_root(frame, 0, foreign), + Err(HeapError::WrongDomain) + ); + assert_eq!(heap.stats().live_roots, 1); + assert_eq!( + heap.collect().live_nodes, + 2, + "the foreign write did not replace the slot" + ); + assert!(heap.upvalue_alive(cell)); + assert!(heap.alive(table)); + + let stale = heap.alloc_upvalue().expect("soon stale"); + assert_eq!(heap.collect().live_nodes, 2, "the unrooted cell is swept"); + assert!(!heap.upvalue_alive(stale)); + assert_eq!( + heap.write_upvalue_root(frame, 0, stale), + Err(HeapError::StaleHandle) + ); + assert_eq!(heap.stats().live_roots, 1); + assert_eq!(heap.stats().live_edges, 1); + assert_eq!( + heap.collect().live_nodes, + 2, + "the stale write did not clear the slot" + ); + assert!(heap.upvalue_alive(cell)); + assert!(heap.alive(table)); +} From 68cb74c8342f0434f1d7ee018ed34c4cdf38c709 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 17:37:40 +0800 Subject: [PATCH 065/225] feat(lua): keep closure identity keys on the object-key record A private table can use a closure as an identity key without a second edge table or a second mark pass. The object key stores slot, generation, and kind, so mark follows the stored kind instead of treating every object key as a table. Weak k, v, and kv still use the existing entry policy. --- src/frontends/lua/heap.rs | 7 +- src/frontends/lua/heap/table.rs | 98 +++- tests/luajit_heap_runtime/closure_graph.rs | 522 +++++++++++++++++++++ 3 files changed, 616 insertions(+), 11 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index d1700e8..8294283 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -28,8 +28,11 @@ //! sweep. A root slot holds a table, a closure, or an upvalue. A table field can point at //! a closure, a closure at one shared upvalue, and that upvalue at its current //! table or closure. A missing current edge is nil. Two closures can point at -//! the same upvalue. Those nodes have no guest carrier and no Core resource -//! token. They are not callable values. +//! the same upvalue. A table entry key can be a table or a closure. Both use +//! the same object-key record: slot, generation, and kind. Mark and sweep walk +//! that record in the existing pass. A closure key is not a field id and is +//! not a guest value. Closure and upvalue nodes have no guest carrier and no +//! Core resource token. They are not callable values. //! //! Later integration, not this kernel: LuaJIT `ordered.lua` plus the reverse //! and skip-collection controls in diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index e7a4302..5c9018c 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2,7 +2,9 @@ //! //! Closure and cell nodes use the same slots, edges, roots, and sweep as //! tables. A private field id is not a Lua number. Internal links are strong. -//! Only a table entry follows that table's weak mode. +//! Only a table entry follows that table's weak mode. An object key stores +//! the slot, generation, and kind. A closure key is that record with closure +//! kind. It is not a private field id and not a second edge table. use std::fmt; use std::sync::Arc; @@ -188,8 +190,8 @@ struct Slot { struct Edge { from: u32, /// Field ids, object identities, string text, and binary64 numbers share - /// this record. An object key is the live slot and generation. A string - /// key is the complete UTF-8 text. A number key is canonical binary64 + /// this record. An object key is the live slot, generation, and kind. A + /// string key is the complete UTF-8 text. A number key is canonical binary64 /// bits, not a field id and not a collectable node. key: EdgeKey, value: EdgeValue, @@ -263,6 +265,7 @@ enum EdgeKey { Object { slot: u32, generation: u32, + kind: HandleKind, }, /// Complete UTF-8 text, including interior NUL. Not a collectable table. Utf8(String), @@ -273,9 +276,19 @@ enum EdgeKey { impl EdgeKey { fn object(key: TableRef) -> Self { + Self::identity(key.slot(), key.generation(), key.kind()) + } + + fn closure_key(key: ClosureRef) -> Self { + Self::identity(key.slot(), key.generation(), key.kind()) + } + + /// One object-key record. Table and closure keys differ by `kind`. + fn identity(slot: u32, generation: u32, kind: HandleKind) -> Self { Self::Object { - slot: key.slot(), - generation: key.generation(), + slot, + generation, + kind, } } @@ -928,6 +941,68 @@ impl LuaHeap { Ok(()) } + /// Writes one table under a closure identity key. + /// + /// Same record and quota as a table object key. The key is the closure + /// slot, generation, and kind. A private field id is not this key. Handle + /// checks run before any stored entry is replaced. + pub fn set_closure_key_edge( + &mut self, + from: TableRef, + key: ClosureRef, + to: TableRef, + ) -> Result<(), HeapError> { + self.require_closure(key)?; + self.write_table_edge(from, EdgeKey::closure_key(key), to) + } + + /// Writes one string under a closure identity key, in the same record. + /// + /// Nil removal stays on [`Self::clear_closure_key`]. A refused handle does + /// not replace an existing entry. + pub fn set_closure_key_scalar( + &mut self, + from: TableRef, + key: ClosureRef, + value: Value, + ) -> Result<(), HeapError> { + debug_assert!(matches!(value, Value::String(_))); + self.require_live(from)?; + self.require_closure(key)?; + self.write_edge(from, EdgeKey::closure_key(key), EdgeValue::Scalar(value)) + } + + /// Removes one closure-key record. Another closure, including one that + /// shares this key's cell, is a different identity and stays. + pub fn clear_closure_key(&mut self, from: TableRef, key: ClosureRef) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_closure(key)?; + let key = EdgeKey::closure_key(key); + self.clear_edge(from, &key); + Ok(()) + } + + /// Reads a closure-key edge. The key domain, kind, and generation must + /// still name that live closure. + pub fn closure_key_edge( + &self, + from: TableRef, + key: ClosureRef, + ) -> Result, HeapError> { + self.require_closure(key)?; + let key = EdgeKey::closure_key(key); + self.read_table_edge(from, |stored| stored == &key) + } + + /// Reads a closure-key edge as the guest value. + /// + /// A stored string is that string. A stored table is its issued carrier. + pub fn closure_key_value(&self, from: TableRef, key: ClosureRef) -> Result { + self.require_closure(key)?; + let key = EdgeKey::closure_key(key); + self.stored_value(from, |stored| stored == &key) + } + /// Writes one table under a binary64 key, in the same record as a field. /// /// NaN is refused before any lookup or insert. An integer resource carrier @@ -1539,7 +1614,11 @@ impl LuaHeap { let (object_key, value_target) = { let edge = &self.edges[entry as usize]; let object_key = match &edge.key { - EdgeKey::Object { slot, generation } => Some((*slot, *generation)), + EdgeKey::Object { + slot, + generation, + kind, + } => Some((*slot, *generation, *kind)), EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => None, }; let value_target = match &edge.value { @@ -1558,9 +1637,9 @@ impl LuaHeap { }; if from_table && !mode.keys - && let Some((slot, generation)) = object_key + && let Some((slot, generation, kind)) = object_key { - self.follow_target(slot, generation, HandleKind::Table, &mut work); + self.follow_target(slot, generation, kind, &mut work); } // A table entry follows that table's weak mode. A closure or // cell link is not a table entry, so it stays strong. @@ -1701,7 +1780,8 @@ impl LuaHeap { }; // Strong endpoints of a marked owner were already marked. For weak // edges, either dead object endpoint invalidates the whole entry. - // Closure and cell targets are checked in this same retain. + // Closure and cell targets, and object keys of either stored kind, + // are checked in this same retain. self.edges.retain(|edge| { is_marked(edge.from) && match &edge.value { diff --git a/tests/luajit_heap_runtime/closure_graph.rs b/tests/luajit_heap_runtime/closure_graph.rs index d595422..84543e4 100644 --- a/tests/luajit_heap_runtime/closure_graph.rs +++ b/tests/luajit_heap_runtime/closure_graph.rs @@ -1710,3 +1710,525 @@ fn upvalue_root_rejects_foreign_and_stale_without_clobber() { assert!(heap.upvalue_alive(cell)); assert!(heap.alive(table)); } + +/// Private field on a value table that points back at its closure key. +/// +/// Locked LuaJIT `96f7b297` with `-joff` and Lua 5.2 compat stores that +/// back-edge as `{ key = key }` (`evidence/lua52-gc-weak-closure-modes`). +/// This heap has no Lua source closure key. The value uses the existing +/// private field, which is not a closure identity and not numeric key 1. +const CLOSURE_KEY_BACKREF_FIELD: u32 = 1; + +fn closure_key_limits() -> HeapLimits { + HeapLimits { + nodes: 12, + roots: 4, + edges: 12, + max_generation: 8, + } +} + +struct ClosureKeyGraph { + owner: TableRef, + survivor: TableRef, + survivor_raw: i64, + watch: TableRef, + orphan: TableRef, + orphan_raw: i64, + value: TableRef, + value_raw: i64, + isolated: ClosureRef, + linked: ClosureRef, + baseline_tokens: usize, +} + +fn seed_closure_keys(host: &mut HostContext<'_>, mode: &str) -> ClosureKeyGraph { + heap::install(host, closure_key_limits()).expect("install"); + let baseline_tokens = host.resource_count(); + let owner_raw = publish_raw(host); + let owner = table_ref(host, owner_raw); + let mode_raw = publish_raw(host); + let mode_table = table_ref(host, mode_raw); + let survivor_raw = publish_raw(host); + let survivor = table_ref(host, survivor_raw); + let watch_raw = publish_raw(host); + let watch = table_ref(host, watch_raw); + let watch_mode_raw = publish_raw(host); + let watch_mode = table_ref(host, watch_mode_raw); + let orphan_raw = publish_raw(host); + let orphan = table_ref(host, orphan_raw); + let value_raw = publish_raw(host); + let value = table_ref(host, value_raw); + assert_eq!(host.resource_count() - baseline_tokens, 7); + + let (isolated, linked) = heap::with_heap(host, |heap| { + let isolated = heap.alloc_closure()?; + let linked = heap.alloc_closure()?; + Ok((isolated, linked)) + }) + .expect("two closure keys"); + assert_eq!( + host.resource_count() - baseline_tokens, + 7, + "a closure key has no resource token" + ); + assert_eq!(isolated.kind(), heap::HandleKind::Closure); + assert_eq!(linked.kind(), heap::HandleKind::Closure); + assert_eq!(isolated.domain(), owner.domain()); + assert_ne!(isolated, linked); + + let frame = heap::with_heap(host, |heap| heap.enter_roots(3)).expect("roots"); + heap::with_heap(host, |heap| { + heap.write_root(frame, 0, owner)?; + heap.write_root(frame, 1, survivor)?; + heap.write_root(frame, 2, watch)?; + heap.set_mode_scalar(mode_table, Value::string(mode))?; + heap.set_metatable(owner, Some(mode_table))?; + heap.set_mode_scalar(watch_mode, Value::string("v"))?; + heap.set_metatable(watch, Some(watch_mode))?; + heap.set_closure_key_scalar(owner, isolated, Value::string("key-only"))?; + heap.set_closure_key_edge(owner, linked, value)?; + heap.set_closure_edge(value, CLOSURE_KEY_BACKREF_FIELD, linked)?; + heap.set_named_edge(watch, "orphan", orphan)?; + heap.set_named_edge(orphan, "self", orphan)?; + heap.set_named_scalar(survivor, "mark", Value::string("alive"))?; + Ok(()) + }) + .expect("publish closure keys"); + + assert_eq!( + heap::with_heap(host, |heap| heap + .closure_edge(value, CLOSURE_KEY_BACKREF_FIELD)) + .expect("private back-edge"), + linked + ); + assert_eq!( + heap::with_heap(host, |heap| heap.closure_key_edge(value, linked)).expect("not a key"), + None, + "the value holds the closure in a private field, not as a closure key" + ); + assert!( + heap::with_heap(host, |heap| heap.edge(owner, isolated.slot())) + .expect("field read") + .is_none(), + "a closure key is not the field id of its slot" + ); + + ClosureKeyGraph { + owner, + survivor, + survivor_raw, + watch, + orphan, + orphan_raw, + value, + value_raw, + isolated, + linked, + baseline_tokens, + } +} + +fn closure_key_string( + host: &mut HostContext<'_>, + graph: &ClosureKeyGraph, +) -> Result { + heap::with_heap(host, |heap| { + heap.closure_key_value(graph.owner, graph.isolated) + }) +} + +fn linked_key_table( + host: &mut HostContext<'_>, + graph: &ClosureKeyGraph, +) -> Result, HeapError> { + heap::with_heap(host, |heap| { + heap.closure_key_edge(graph.owner, graph.linked) + }) +} + +#[derive(Clone, Copy)] +struct ClosureKeyExpect { + isolated_string: bool, + isolated_alive: bool, + linked_table: bool, + linked_alive: bool, + value_alive: bool, + orphan_alive: bool, + live_nodes: u32, + live_edges: u32, + tokens: usize, +} + +fn assert_closure_key_graph( + host: &mut HostContext<'_>, + graph: &ClosureKeyGraph, + expect: ClosureKeyExpect, + label: &str, +) { + let string = closure_key_string(host, graph); + if expect.isolated_alive { + assert_eq!( + string.expect(label), + Value::string("key-only"), + "{label}: isolated closure key string" + ); + assert!( + heap::with_heap(host, |heap| Ok(heap.closure_alive(graph.isolated))).expect(label), + "{label}: isolated closure stays" + ); + } else { + assert_eq!(string, Err(HeapError::StaleHandle), "{label}: isolated key"); + assert!( + !heap::with_heap(host, |heap| Ok(heap.closure_alive(graph.isolated))).expect(label), + "{label}: isolated closure reclaimed" + ); + } + assert_eq!( + expect.isolated_string, expect.isolated_alive, + "{label}: a dead closure key cannot keep its string entry" + ); + + let linked = linked_key_table(host, graph); + if expect.linked_alive { + assert_eq!( + linked.expect(label), + expect.linked_table.then_some(graph.value), + "{label}: linked entry" + ); + assert!( + heap::with_heap(host, |heap| Ok(heap.closure_alive(graph.linked))).expect(label), + "{label}: linked closure" + ); + } else { + assert_eq!(linked, Err(HeapError::StaleHandle), "{label}: linked key"); + assert!(!heap::with_heap(host, |heap| Ok(heap.closure_alive(graph.linked))).expect(label)); + assert!(!expect.linked_table, "{label}: a dead key has no entry"); + } + + assert_eq!( + heap::with_heap(host, |heap| Ok(heap.alive(graph.value))).expect(label), + expect.value_alive, + "{label}: value table" + ); + assert_eq!( + token_open(host, graph.value_raw), + expect.value_alive, + "{label}: value token" + ); + assert_eq!( + heap::with_heap(host, |heap| heap.named_edge(graph.watch, "orphan")).expect(label), + expect.orphan_alive.then_some(graph.orphan), + "{label}: weak orphan entry" + ); + assert_eq!( + heap::with_heap(host, |heap| Ok(heap.alive(graph.orphan))).expect(label), + expect.orphan_alive, + "{label}: orphan node" + ); + assert_eq!( + token_open(host, graph.orphan_raw), + expect.orphan_alive, + "{label}: orphan token" + ); + assert!( + heap::with_heap(host, |heap| Ok(heap.alive(graph.survivor))).expect(label), + "{label}: survival control" + ); + assert!( + token_open(host, graph.survivor_raw), + "{label}: survivor token" + ); + assert_eq!( + heap::with_heap(host, |heap| heap.named_value(graph.survivor, "mark")).expect(label), + Value::string("alive"), + "{label}: survivor mark" + ); + + let stats = heap::stats(host).expect(label); + assert_eq!(stats.live_nodes, expect.live_nodes, "{label}: nodes"); + assert_eq!(stats.live_edges, expect.live_edges, "{label}: edges"); + assert_eq!(stats.live_roots, 3, "{label}: roots"); + assert_eq!( + host.resource_count() - graph.baseline_tokens, + expect.tokens, + "{label}: open table tokens" + ); +} + +/// Closure identity keys on one heap, for `k` / `v` / `kv`, with and without +/// collection. +/// +/// The oracle removes an isolated closure key in `k` and `kv`, keeps it in +/// `v`, and keeps a strong value's back-edge only in `k`. `v` marks that key +/// while dropping the weak value, so the first collect must not be read as +/// reclaiming the key. The next collect reclaims it. The rooted survivor and +/// the weak orphan separate that from a collect that did not run. +#[test] +fn closure_key_weak_modes_keep_or_drop_entries_and_reclaim_on_the_next_pass() { + let seeded = ClosureKeyExpect { + isolated_string: true, + isolated_alive: true, + linked_table: true, + linked_alive: true, + value_alive: true, + orphan_alive: true, + live_nodes: 9, + live_edges: 8, + tokens: 7, + }; + for mode in ["k", "v", "kv"] { + for collect in [false, true] { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = seed_closure_keys(&mut host, mode); + assert_closure_key_graph(&mut host, &graph, seeded, "before"); + if !collect { + assert_closure_key_graph(&mut host, &graph, seeded, "omit"); + assert_eq!(heap::stats(&mut host).expect("omit").collections, 0); + return; + } + + let report = heap::collect(&mut host).expect("collect"); + let meter = heap::take_scan_meter(&mut host).expect("one pass"); + assert_eq!(meter.mark_passes, 1, "{mode}: one mark pass"); + assert_eq!(report.live_roots, 3, "{mode}: roots stay"); + let after = match mode { + "k" => ClosureKeyExpect { + isolated_string: false, + isolated_alive: false, + linked_table: true, + linked_alive: true, + value_alive: true, + orphan_alive: false, + live_nodes: 7, + live_edges: 5, + tokens: 6, + }, + "v" => ClosureKeyExpect { + isolated_string: true, + isolated_alive: true, + linked_table: false, + linked_alive: true, + value_alive: false, + orphan_alive: false, + live_nodes: 7, + live_edges: 4, + tokens: 5, + }, + "kv" => ClosureKeyExpect { + isolated_string: false, + isolated_alive: false, + linked_table: false, + linked_alive: false, + value_alive: false, + orphan_alive: false, + live_nodes: 5, + live_edges: 3, + tokens: 5, + }, + _ => unreachable!("mode is k, v, or kv"), + }; + assert_closure_key_graph(&mut host, &graph, after, mode); + if mode != "v" { + return; + } + + let again = heap::collect(&mut host).expect("second collect"); + let second = heap::take_scan_meter(&mut host).expect("second pass"); + assert_eq!(second.mark_passes, 1, "the next collect is still one pass"); + assert_eq!( + again.live_nodes, 6, + "the unreferenced closure key is reclaimed" + ); + assert_closure_key_graph( + &mut host, + &graph, + ClosureKeyExpect { + isolated_string: true, + isolated_alive: true, + linked_table: false, + linked_alive: false, + value_alive: false, + orphan_alive: false, + live_nodes: 6, + live_edges: 4, + tokens: 5, + }, + "v next", + ); + }); + } + } +} + +/// Two closures can share one cell and still be different table keys. +/// Deleting one entry leaves the other. A stale, foreign, or full-edge write +/// is refused before it replaces a stored entry. +#[test] +fn closure_keys_sharing_a_cell_stay_distinct_and_refused_writes_keep_entries() { + let mut heap = heap::LuaHeap::new(HeapLimits { + nodes: 10, + roots: 1, + edges: 4, + max_generation: 4, + }); + let owner = heap.alloc().expect("owner"); + let table_value = heap.alloc().expect("table value"); + let cell = heap.alloc_upvalue().expect("cell"); + let left = heap.alloc_closure().expect("left"); + let right = heap.alloc_closure().expect("right"); + heap.set_upvalue_edge(left, cell).expect("left cell"); + heap.set_upvalue_edge(right, cell).expect("right cell"); + assert_eq!(heap.upvalue_of(left).expect("left"), cell); + assert_eq!(heap.upvalue_of(right).expect("right"), cell); + assert_ne!(left, right); + assert_ne!(left.slot(), right.slot()); + assert_eq!(left.domain(), right.domain()); + assert_eq!(left.kind(), heap::HandleKind::Closure); + + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, owner).expect("root"); + heap.set_closure_key_scalar(owner, left, Value::string("left")) + .expect("left string"); + heap.set_closure_key_edge(owner, right, table_value) + .expect("right table"); + heap.issue_carrier(table_value) + .expect("issue the table value"); + assert_eq!( + heap.closure_key_value(owner, left).expect("read left"), + Value::string("left") + ); + assert_eq!( + heap.closure_key_edge(owner, right).expect("read right"), + Some(table_value) + ); + assert_eq!( + heap.closure_key_value(owner, right).expect("issued read"), + heap.issued_value(table_value).expect("carrier") + ); + assert_eq!( + heap.closure_key_edge(owner, left) + .expect("scalar is not a table"), + None + ); + assert_eq!(heap.stats().live_edges, 4); + + let table_key = heap.alloc().expect("table key"); + assert_eq!( + heap.object_value(owner, table_key).expect("table key"), + Value::Null, + "a table key does not select a closure key" + ); + assert_eq!( + heap.edge(owner, left.slot()).expect("field id"), + None, + "the closure slot is not a field key" + ); + + let extra = heap.alloc_closure().expect("extra"); + let before = heap.stats(); + assert_eq!( + heap.set_closure_key_scalar(owner, extra, Value::string("extra")), + Err(HeapError::EdgeCapacity) + ); + assert_eq!(heap.stats().live_edges, before.live_edges); + assert_eq!(heap.stats().edge_slots, before.edge_slots); + assert_eq!( + heap.closure_key_value(owner, left) + .expect("capacity left the string"), + Value::string("left") + ); + assert_eq!( + heap.closure_key_edge(owner, right) + .expect("capacity left the table"), + Some(table_value) + ); + + heap.clear_closure_key(owner, left).expect("delete left"); + assert_eq!( + heap.closure_key_value(owner, left).expect("deleted"), + Value::Null + ); + assert_eq!( + heap.closure_key_edge(owner, right).expect("right stays"), + Some(table_value) + ); + assert!(heap.closure_alive(left)); + assert!(heap.closure_alive(right)); + assert_eq!(heap.upvalue_of(left).expect("cell stays"), cell); + assert_eq!(heap.upvalue_of(right).expect("shared cell"), cell); + heap.set_closure_key_scalar(owner, left, Value::string("left")) + .expect("restore left"); + + let doomed = heap.alloc().expect("doomed table"); + let soon = heap.alloc_closure().expect("soon stale"); + let soon_slot = soon.slot(); + let soon_generation = soon.generation(); + assert_eq!(heap.collect().live_nodes, 5, "unkeyed nodes are swept"); + assert!(!heap.alive(doomed)); + assert!(!heap.closure_alive(soon)); + assert!(!heap.closure_alive(extra)); + assert!(!heap.alive(table_key)); + let reused = heap.alloc_closure().expect("reuse"); + assert_eq!(reused.slot(), soon_slot); + assert_ne!(reused.generation(), soon_generation); + assert_eq!(reused.kind(), heap::HandleKind::Closure); + assert_eq!( + heap.set_closure_key_edge(owner, right, doomed), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.set_closure_key_scalar(owner, soon, Value::string("stale")), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.closure_key_value(owner, left) + .expect("stale write kept left"), + Value::string("left") + ); + assert_eq!( + heap.closure_key_edge(owner, right) + .expect("stale write kept right"), + Some(table_value) + ); + + let mut other = heap::LuaHeap::new(HeapLimits { + nodes: 2, + roots: 1, + edges: 1, + max_generation: 4, + }); + let foreign = other.alloc_closure().expect("foreign"); + assert_ne!(foreign.domain(), owner.domain()); + assert_eq!(foreign.kind(), heap::HandleKind::Closure); + let foreign_table = other.alloc().expect("foreign table"); + assert_eq!( + heap.set_closure_key_scalar(owner, foreign, Value::string("foreign")), + Err(HeapError::WrongDomain) + ); + assert_eq!( + heap.set_closure_key_edge(owner, right, foreign_table), + Err(HeapError::WrongDomain) + ); + assert_eq!( + heap.clear_closure_key(owner, foreign), + Err(HeapError::WrongDomain) + ); + assert_eq!( + heap.closure_key_value(owner, foreign), + Err(HeapError::WrongDomain) + ); + assert_eq!(heap.stats().live_edges, 4); + assert_eq!( + heap.closure_key_value(owner, left) + .expect("foreign write kept left"), + Value::string("left") + ); + assert_eq!( + heap.closure_key_edge(owner, right) + .expect("foreign write kept right"), + Some(table_value) + ); + assert_eq!(heap.collect().live_nodes, 5); +} From 858901c931f0a38b9a657c4f58491ad3090dad43 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 18:17:18 +0800 Subject: [PATCH 066/225] feat(lua): retire the inner do root on one outward goto (cherry picked from commit 3fbe3486e3baf4600a1a0d7a2880c4860adcddc5) --- tests/luajit_heap_runtime/candidate.rs | 125 ++++++- .../value_boundary_tests.rs | 316 ++++++++++++++++++ 2 files changed, 436 insertions(+), 5 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 3fa54a2..be6fdf9 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1279,7 +1279,7 @@ impl Lower<'_> { Ok(()) } ast::Stmt::Empty { .. } => Ok(()), - ast::Stmt::Do { span, body } if !self.in_function => self.lower_do(*span, body), + ast::Stmt::Do { span, body } if !self.in_function => self.lower_do(*span, body, None), other => Err(ParseError::at_line( self.line(stmt_span(other)) as usize, "Lua statement not lowered yet", @@ -1291,16 +1291,131 @@ impl Lower<'_> { /// `live_locals`. Same-name outer slots stay where they are, including a /// slot already removed by `= nil`. A function body is not this path. /// - /// The lowered list is one retained segment. `retire_block` still runs - /// once, at this statement's end, not at the label. This is not the - /// `control.rs` state dispatcher. - fn lower_do(&mut self, span: ast::Span, body: &ast::Block) -> Result<(), ParseError> { + /// A same-block forward `goto` still uses `retained_statements`. One direct + /// child `do` may instead carry `pending`: the resolver target span of its + /// single unconditional `goto`, already known to be a later direct label + /// of this block. That child lowers its prefix and `retire_block` drops + /// only its slots. This walk then continues after the label. `retire_block` + /// still runs once, at this statement's end, not at the label. + fn lower_do( + &mut self, + span: ast::Span, + body: &ast::Block, + pending: Option, + ) -> Result<(), ParseError> { + if let Some(label_span) = pending { + let goto_index = self + .goto_targeting(body, label_span) + .ok_or_else(|| self.statement_unsupported(span))?; + for stmt in &body.stmts[..goto_index] { + if !matches!(stmt, ast::Stmt::Label { .. }) { + self.lower_stmt(stmt)?; + } + } + return self.retire_block(span, body); + } + // A same-block skip owns this block. Do not also structure a nested + // jump; `forward_goto_skip` already drops or keeps that child. + if self.forward_goto_skip(body)?.is_none() + && let Some((child_index, label_index, label_span)) = self.outward_forward_goto(body)? + { + for (index, stmt) in body.stmts.iter().enumerate() { + if matches!(stmt, ast::Stmt::Label { .. }) { + continue; + } + if index == child_index { + let ast::Stmt::Do { + span: child_span, + body: child_body, + } = stmt + else { + return Err(self.statement_unsupported(stmt_span(stmt))); + }; + self.lower_do(*child_span, child_body, Some(label_span))?; + continue; + } + if index > child_index && index < label_index { + continue; + } + self.lower_stmt(stmt)?; + } + return self.retire_block(span, body); + } for stmt in self.retained_statements(body)? { self.lower_stmt(stmt)?; } self.retire_block(span, body) } + /// Direct child `do` whose one direct `goto` resolves to a later direct + /// label of `body`. The label is `GotoUse::target`'s span, not a name + /// match. A backward target or a second such child is unsupported. A + /// target outside this block is left for that child to reject. + fn outward_forward_goto( + &self, + body: &ast::Block, + ) -> Result, ParseError> { + let mut found = None; + for (index, stmt) in body.stmts.iter().enumerate() { + let ast::Stmt::Do { body: child, .. } = stmt else { + continue; + }; + let mut goto_span = None; + for child_stmt in &child.stmts { + let ast::Stmt::Goto { span, .. } = child_stmt else { + continue; + }; + if goto_span.is_some() { + goto_span = None; + break; + } + goto_span = Some(*span); + } + let Some(goto_span) = goto_span else { + continue; + }; + let Some(label) = self.chunk_target_label(goto_span) else { + continue; + }; + let Some(label_index) = body.stmts.iter().position( + |stmt| matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span), + ) else { + continue; + }; + if label_index <= index || found.is_some() { + return Err(self.statement_unsupported(goto_span)); + } + found = Some((index, label_index, label.span)); + } + Ok(found) + } + + /// Index of the one direct `goto` whose resolver target span is `label_span`. + fn goto_targeting(&self, body: &ast::Block, label_span: ast::Span) -> Option { + let mut found = None; + for (index, stmt) in body.stmts.iter().enumerate() { + let ast::Stmt::Goto { span, .. } = stmt else { + continue; + }; + let label = self.chunk_target_label(*span)?; + if label.span != label_span || found.is_some() { + return None; + } + found = Some(index); + } + found + } + + fn chunk_target_label(&self, goto_span: ast::Span) -> Option<&resolve::LabelBinding> { + let jump = self + .resolution + .gotos + .iter() + .find(|jump| jump.span == goto_span && jump.function_id == 0)?; + let label = self.resolution.labels.get(jump.target?)?; + (label.function_id == 0).then_some(label) + } + /// Statements this chunk `do` lowers, in source order. Labels are not /// runtime statements. Empty statements stay, including a trailing `;`. /// diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index e3e01c3..9fd5c0d 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -4206,3 +4206,319 @@ return type(weak.seen) assert_eq!(host.resource_count(), resources, "{label}"); } } + +// One unconditional goto in a direct inner chunk `do` targets the direct outer +// `do`'s later label. Resolve picks that label id; the earlier sibling +// `::resume::` has the same name and a different span. The inner `retire_block` +// drops only the inner slot. The outer slot stays until the outer block exits. +// An inner collect keeps both. A collect at the outer label reclaims only the +// inner object. Omitting that collect leaves it. An exit collect then reclaims +// the outer object. Omitting the goto runs both skipped writes. Observation is +// the existing `observe_table` / `type` / heap stats path, not a second API. +#[test] +fn lua_candidate_chunk_inner_do_goto_outer_label_retires_inner_root() { + let source = r#" +local mt = {} +mt.__mode = "v" +local weak = {} +setmetatable(weak, mt) +local marker = {} +observe_table(weak, 0) +observe_table(marker, 0) +do + do + ::resume:: + end + local a = {} + a.self = a + weak.a = a + observe_table(a, 0) + do + local b = {} + b.self = b + weak.b = b + observe_table(b, 0) + collectgarbage("collect") + observe_table(a, 0) + observe_table(weak.a, 0) + observe_table(b, 0) + observe_table(weak.b, 0) +@jump@ + marker.inner = {} + end + marker.outer = {} + ::resume:: + observe_table(a, 0) + observe_table(weak.a, 0) + observe_table(weak.b, 0) +@label@ +end +@after@ +"#; + let jump = " goto resume\n"; + let label_collect = "\ + collectgarbage(\"collect\") + observe_table(a, 0) + observe_table(weak.a, 0) +"; + let no_label_collect = ""; + let after_label_only = "\ +observe_table(weak.a, 0) +observe_table(weak, 0) +observe_table(marker, 0) +return type(weak.b) +"; + let after_exit_collect = "\ +collectgarbage(\"collect\") +observe_table(weak, 0) +observe_table(marker, 0) +return type(weak.a) +"; + let after_omit = "\ +observe_table(weak.b, 0) +observe_table(weak.a, 0) +observe_table(weak, 0) +observe_table(marker, 0) +return type(weak.b) +"; + let label_fall = "\ + collectgarbage(\"collect\") + observe_table(a, 0) + observe_table(weak.a, 0) + observe_table(marker.inner, 0) + observe_table(marker.outer, 0) +"; + let after_fall = "\ +collectgarbage(\"collect\") +observe_table(marker.inner, 0) +observe_table(marker.outer, 0) +observe_table(weak, 0) +observe_table(marker, 0) +return type(weak.a) +"; + + let jumped = source + .replace("@jump@", jump) + .replace("@label@", label_collect) + .replace("@after@", after_label_only); + let parsed = parser::parse_chunk(jumped.as_bytes()).expect("parse outward goto"); + let resolution = resolve::resolve(&parsed); + assert!( + resolution.errors.is_empty(), + "resolve names the outer label: {:?}", + resolution.errors + ); + assert_eq!(resolution.gotos.len(), 1, "one unconditional goto"); + let target = resolution.gotos[0].target.expect("resolved target id"); + let label = &resolution.labels[target]; + assert_eq!(label.name, b"resume"); + let same_name: Vec<_> = resolution + .labels + .iter() + .filter(|item| item.name == b"resume") + .collect(); + assert_eq!(same_name.len(), 2, "sibling and outer share the name"); + assert!( + same_name.iter().any(|item| item.span != label.span), + "the other resume is not the resolved target" + ); + let outer = parsed + .body + .stmts + .iter() + .find_map(|stmt| { + let ast::Stmt::Do { body, .. } = stmt else { + return None; + }; + body.stmts + .iter() + .any( + |stmt| matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span), + ) + .then_some(body) + }) + .expect("outer do owns the resolved label"); + let sibling = outer + .stmts + .iter() + .find_map(|stmt| { + let ast::Stmt::Do { body, .. } = stmt else { + return None; + }; + body.stmts.iter().find_map(|stmt| { + let ast::Stmt::Label { name, .. } = stmt else { + return None; + }; + (name.bytes == b"resume").then_some(name.span) + }) + }) + .expect("sibling resume"); + assert_ne!(sibling, label.span, "resolve did not pick the sibling span"); + let inner = outer + .stmts + .iter() + .find_map(|stmt| { + let ast::Stmt::Do { body, .. } = stmt else { + return None; + }; + body.stmts + .iter() + .any(|stmt| matches!(stmt, ast::Stmt::Goto { .. })) + .then_some(body) + }) + .expect("inner do owns the goto"); + assert!( + inner.stmts.iter().all(|stmt| { + !matches!(stmt, ast::Stmt::Label { name, .. } if name.span == label.span) + }), + "the resolved label is not an inner direct child" + ); + + let run = |jump_text: &str, label_text: &str, after_text: &str, result: &str| { + let program = source + .replace("@jump@", jump_text) + .replace("@label@", label_text) + .replace("@after@", after_text); + let mut vm = candidate(&program); + assert_eq!( + vm.run().expect("run outward goto"), + VmStatus::Halted, + "{result}" + ); + assert_eq!(vm.stack(), &[Value::string(result)], "{result}"); + vm + }; + + let mut vm = run(jump, label_collect, after_label_only, "nil"); + let tables = observed_tables(&mut vm); + assert_eq!(tables.len(), 16, "label collect, no exit collect"); + let weak = tables[0]; + let marker = tables[1]; + let created_a = tables[2]; + let created_b = tables[3]; + assert_ne!(created_a, created_b); + assert_ne!(created_a, weak); + assert_ne!(created_b, marker); + assert_eq!(tables[4], created_a, "inner collect keeps a"); + assert_eq!(tables[5], created_a, "weak.a inside is a"); + assert_eq!(tables[6], created_b, "inner collect keeps b"); + assert_eq!(tables[7], created_b, "weak.b inside is b"); + assert_eq!(tables[8], created_a, "a is still rooted at the outer label"); + assert_eq!(tables[9], created_a, "weak.a before the label collect is a"); + assert_eq!(tables[10], created_b, "the jump has not collected b"); + assert_eq!(tables[11], created_a, "label collect keeps a"); + assert_eq!(tables[12], created_a, "weak.a after the label collect is a"); + assert_eq!( + tables[13], created_a, + "leaving the outer block does not collect a" + ); + assert_eq!(tables[14], weak); + assert_eq!(tables[15], marker); + let mut host = vm.host_context(); + assert_table_lifetime(&mut host, created_b, false); + assert_table_lifetime(&mut host, created_a, true); + assert_table_lifetime(&mut host, weak, true); + assert_table_lifetime(&mut host, marker, true); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, 2); + assert_eq!(stats.live_nodes, 4); + assert_eq!(stats.live_edges, 3); + assert_eq!(stats.live_roots, 0); + assert_eq!(stats.last_marked, 4, "label collect marks a and not b"); + assert_eq!( + stats.peak_roots, 5, + "inner collect rooted both block locals" + ); + assert_eq!(host.resource_count(), 4); + + let mut vm = run(jump, label_collect, after_exit_collect, "nil"); + let tables = observed_tables(&mut vm); + assert_eq!(tables.len(), 15, "label collect and exit collect"); + let created_a = tables[2]; + let created_b = tables[3]; + assert_eq!( + tables[10], created_b, + "b is alive at the label before collect" + ); + assert_eq!(tables[11], created_a, "label collect keeps a"); + assert_eq!(tables[12], created_a); + assert_eq!(tables[13], tables[0]); + assert_eq!(tables[14], tables[1]); + let mut host = vm.host_context(); + assert_table_lifetime(&mut host, created_b, false); + assert_table_lifetime(&mut host, created_a, false); + assert_table_lifetime(&mut host, tables[0], true); + assert_table_lifetime(&mut host, tables[1], true); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, 3); + assert_eq!(stats.live_nodes, 3); + assert_eq!(stats.live_edges, 1); + assert_eq!(stats.live_roots, 0); + assert_eq!(stats.last_marked, 3); + assert_eq!(host.resource_count(), 3); + + let mut vm = run(jump, no_label_collect, after_omit, "table"); + let tables = observed_tables(&mut vm); + assert_eq!(tables.len(), 15, "omit label collect"); + let created_a = tables[2]; + let created_b = tables[3]; + assert_eq!(tables[8], created_a); + assert_eq!(tables[9], created_a); + assert_eq!(tables[10], created_b, "weak.b at the label is still b"); + assert_eq!(tables[11], created_b, "no collect after the jump leaves b"); + assert_eq!(tables[12], created_a, "no exit collect leaves a"); + assert_eq!(tables[13], tables[0]); + assert_eq!(tables[14], tables[1]); + let mut host = vm.host_context(); + assert_table_lifetime(&mut host, created_b, true); + assert_table_lifetime(&mut host, created_a, true); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, 1); + assert_eq!(stats.live_nodes, 5); + assert_eq!(stats.live_edges, 5); + assert_eq!(stats.live_roots, 0); + assert_eq!(stats.last_marked, 5); + assert_eq!(host.resource_count(), 5); + + let mut vm = run("", label_fall, after_fall, "nil"); + let tables = observed_tables(&mut vm); + assert_eq!(tables.len(), 19, "fallthrough runs both skipped writes"); + let created_a = tables[2]; + let created_b = tables[3]; + assert_eq!(tables[4], created_a, "inner collect keeps a"); + assert_eq!(tables[6], created_b, "inner collect keeps b"); + assert_eq!(tables[8], created_a, "fallthrough still reaches a"); + assert_eq!( + tables[10], created_b, + "b is alive at the label before collect" + ); + assert_eq!(tables[11], created_a, "label collect keeps a"); + let inner_write = tables[13]; + let outer_write = tables[14]; + assert_ne!(inner_write, created_a); + assert_ne!(inner_write, created_b); + assert_ne!(outer_write, inner_write); + assert_ne!(outer_write, tables[1], "marker.outer is not marker"); + assert_eq!( + tables[15], inner_write, + "exit collect keeps the strong inner write" + ); + assert_eq!( + tables[16], outer_write, + "exit collect keeps the strong outer write" + ); + assert_eq!(tables[17], tables[0]); + assert_eq!(tables[18], tables[1]); + let mut host = vm.host_context(); + assert_table_lifetime(&mut host, created_b, false); + assert_table_lifetime(&mut host, created_a, false); + assert_table_lifetime(&mut host, inner_write, true); + assert_table_lifetime(&mut host, outer_write, true); + let stats = heap::stats(&mut host).unwrap(); + assert_eq!(stats.collections, 3); + assert_eq!(stats.live_nodes, 5); + assert_eq!(stats.live_edges, 3); + assert_eq!(stats.live_roots, 0); + assert_eq!(stats.last_marked, 5); + assert_eq!(host.resource_count(), 5); +} From c8977a41b0e7a202598596b1915c783a7b38a550 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 18:28:55 +0800 Subject: [PATCH 067/225] test(lua): keep an issued envelope local until the block exits The host only links the existing closure, cell, and table edges. Source collectgarbage gathers the local while it is live and drops it when the block exits. Omitting the second collect leaves the chain allocated after the safepoint frame is already closed. (cherry picked from commit fd96b4ac3b393a53454bc73670df931a22c356d0) --- .../envelope_local_root.rs | 464 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 2 files changed, 466 insertions(+) create mode 100644 tests/luajit_heap_runtime/envelope_local_root.rs diff --git a/tests/luajit_heap_runtime/envelope_local_root.rs b/tests/luajit_heap_runtime/envelope_local_root.rs new file mode 100644 index 0000000..fe81642 --- /dev/null +++ b/tests/luajit_heap_runtime/envelope_local_root.rs @@ -0,0 +1,464 @@ +//! Issued envelope in a chunk-local slot, reached through source collect. +//! +//! The host only connects the existing private closure, cell, and table edges. +//! It does not publish a heap root and does not collect. `collectgarbage` is +//! the candidate `collect_expr` / `GATHER_ROOT` / `collect_at_safepoint` path. +//! This does not add a production closure type, and it does not claim source +//! closures, dispatch, proxy lookup, or a full safepoint scan. + +use std::sync::Arc; + +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + HostFunctionRegistry, HostImportSchema, HostOwnedFunction, HostParamPassing, HostParamSchema, + HostTypeSchema, OwnedHostCall, ParseError, SourceFlavor, SourcePlugin, Value, VmError, + VmStatus, +}; + +use super::candidate::{self, CollectNote, ReturnWitness}; +use super::heap::{self, ClosureRef, TableRef, UpvalueRef}; +use super::{ObservedTable, Witness}; + +/// Private field id. Not a Lua number key and not a string field. +const CLOSURE_FIELD: u32 = 1; +const LINK: &str = "lua_host::link_envelope"; +const OBSERVE: &str = "lua_host::observe_table"; + +/// Description handles only. Pointers are addresses, not retained carriers. +#[derive(Clone, Copy, Debug)] +struct LinkNote { + envelope: TableRef, + envelope_ptr: usize, + envelope_slot: u32, + envelope_generation: u32, + closure: ClosureRef, + closure_slot: u32, + closure_generation: u32, + cell: UpvalueRef, + cell_slot: u32, + cell_generation: u32, + target: TableRef, + target_ptr: usize, + target_slot: u32, + target_generation: u32, + roots_at_link: u32, + collections_at_link: u32, +} + +struct LinkEnvelope; + +impl HostOwnedFunction for LinkEnvelope { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let [Value::Int(raw)] = call.args() else { + return Err(host_fault("link_envelope needs the issued envelope")); + }; + let raw = u64::try_from(*raw).map_err(|_| host_fault("envelope token out of range"))?; + let token = vm::ResourceHandle::from_raw(raw) + .map_err(|_| host_fault("envelope token is not a resource handle"))?; + let mut host = call.vm().host_context(); + if host.scope_state::().is_some() { + return Err(host_fault("envelope graph was linked twice")); + } + let key = heap::LuaTableResource::key(); + let envelope = host + .borrow_resource_with_key::(token, &key) + .map_err(|error| host_fault(&error.to_string()))? + .table(); + let before = heap::stats(&mut host).map_err(heap_fault)?; + if before.live_roots != 0 { + return Err(host_fault("link saw a heap root it did not publish")); + } + let note = heap::with_heap(&mut host, |heap| { + let closure = heap.alloc_closure()?; + let cell = heap.alloc_upvalue()?; + let target = heap.alloc()?; + let target_issued = heap.issue_carrier(target)?; + heap.set_closure_edge(envelope, CLOSURE_FIELD, closure)?; + heap.set_upvalue_edge(closure, cell)?; + heap.write_upvalue(cell, target)?; + let envelope_issued = heap.issued_value(envelope)?; + Ok(LinkNote { + envelope, + envelope_ptr: carrier_ptr(&envelope_issued), + envelope_slot: envelope.slot(), + envelope_generation: envelope.generation(), + closure, + closure_slot: closure.slot(), + closure_generation: closure.generation(), + cell, + cell_slot: cell.slot(), + cell_generation: cell.generation(), + target, + target_ptr: carrier_ptr(&target_issued), + target_slot: target.slot(), + target_generation: target.generation(), + roots_at_link: before.live_roots, + collections_at_link: before.collections, + }) + }) + .map_err(heap_fault)?; + let after = heap::stats(&mut host).map_err(heap_fault)?; + if after.live_roots != before.live_roots { + return Err(host_fault("link published a heap root")); + } + if after.collections != before.collections { + return Err(host_fault("link collected")); + } + host.scope_state_or_insert_with(|| note) + .map_err(|error| host_fault(&error.to_string()))?; + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))) + } +} + +fn host_fault(message: &str) -> VmError { + VmError::HostError(message.to_string()) +} + +fn heap_fault(error: heap::HeapError) -> VmError { + VmError::HostError(error.to_string()) +} + +fn carrier_ptr(value: &Value) -> usize { + let Value::Array(issued) = value else { + panic!("issued carrier was not an array"); + }; + Arc::as_ptr(issued) as usize +} + +fn catalog() -> &'static Arc { + static CATALOG: std::sync::OnceLock> = std::sync::OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(vm::HostFunctionSchema::with_return( + OBSERVE, + vec![ + HostParamSchema::with_passing("table", table, HostParamPassing::Borrow), + HostParamSchema::value("number", HostTypeSchema::Float), + ], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + LINK, + vec![HostParamSchema::with_passing( + "envelope", + HostTypeSchema::Resource(heap::LuaTableResource::key()), + HostParamPassing::Borrow, + )], + HostTypeSchema::Bool, + )); + Arc::new(builder.build().expect("envelope local-root catalog")) + }) +} + +struct EnvelopePlugin; + +impl SourcePlugin for EnvelopePlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, catalog()) + } +} + +fn run(source: &str) -> vm::Vm { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&EnvelopePlugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .expect("compile envelope local-root source") + .into_vm() + .expect("create VM"); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry + .bind_vm_cached(&mut vm) + .expect("bind envelope local-root runtime"); + vm +} + +fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + let observe = catalog.function(OBSERVE).expect("observe schema"); + registry + .register_exact_owned( + OBSERVE, + observe.params.len() as u8, + HostImportSchema::from_function(catalog, observe), + |_| Box::new(Witness::TableAndNumber(0)), + ) + .expect("register observe_table"); + let link = catalog.function(LINK).expect("link schema"); + registry + .register_exact_owned( + LINK, + link.params.len() as u8, + HostImportSchema::from_function(catalog, link), + |_| Box::new(LinkEnvelope), + ) + .expect("register link_envelope"); +} + +const SOURCE: &str = r#" +local mt = {} +mt.__mode = "v" +local watch = {} +setmetatable(watch, mt) +observe_table(watch, 0) +do + local envelope = {} + watch.env = envelope + link_envelope(envelope) + local orphan = {} + watch.orphan = orphan + observe_table(orphan, 0) + orphan = nil + collectgarbage("collect") +end +@after@ +"#; + +const COLLECT_AFTER: &str = "\ +collectgarbage(\"collect\") +return type(watch.env) +"; + +const OMIT_AFTER: &str = "\ +return type(watch.env) +"; + +#[test] +fn lua_candidate_local_envelope_roots_the_closure_graph_until_scope_exit() { + // The second arm omits only the post-exit collect. Scope exit has already + // dropped the local from the next gather list; that is not collection. + let mut collect_twice = run_arm(COLLECT_AFTER, "nil"); + assert_collected(&mut collect_twice); + let mut omit_second = run_arm(OMIT_AFTER, "table"); + assert_unrooted_but_live(&mut omit_second); +} + +struct Arm { + vm: vm::Vm, + note: LinkNote, + watch: ObservedTable, + orphan: ObservedTable, + collects: Vec, +} + +fn run_arm(after: &str, weak_env: &str) -> Arm { + let source = SOURCE.replace("@after@", after); + let mut vm = run(&source); + assert_eq!( + vm.run().expect("run issued envelope local"), + VmStatus::Halted, + "{weak_env}" + ); + assert_eq!(vm.stack(), &[Value::string(weak_env)], "{weak_env}"); + let (note, watch, orphan, collects) = { + let host = vm.host_context(); + let note = host.scope_state::().copied().expect("link note"); + assert_eq!(note.roots_at_link, 0, "the host did not publish a root"); + assert_eq!(note.collections_at_link, 0, "the host did not collect"); + let observed = host + .scope_state::>() + .expect("weak observations") + .clone(); + assert_eq!(observed.len(), 2, "watch and the independent orphan"); + let collects = host + .scope_state::() + .expect("source collects") + .collects + .clone(); + (note, observed[0], observed[1], collects) + }; + Arm { + vm, + note, + watch, + orphan, + collects, + } +} + +fn assert_collected(arm: &mut Arm) { + assert_eq!( + arm.collects.len(), + 2, + "in-block collect, then post-exit collect" + ); + let inside = &arm.collects[0]; + let after = &arm.collects[1]; + assert_eq!(inside.swept, 1, "the in-block collect reclaims the orphan"); + assert_eq!( + inside.live_nodes, 6, + "envelope, closure, cell, and table stay" + ); + assert_eq!( + inside.live_roots, 3, + "safepoint roots are the mode table, the watch, and the envelope" + ); + assert_eq!(after.swept, 4, "post-exit collect reclaims the whole chain"); + assert_eq!( + after.live_nodes, 2, + "only the mode table and the watch remain" + ); + assert_eq!( + after.live_roots, 2, + "the exited envelope is not published on the second gather" + ); + assert!(after.live_roots < inside.live_roots); + let mut host = arm.vm.host_context(); + assert!( + !alive(&mut host, arm.orphan.table), + "orphan identity is dead" + ); + assert!(alive(&mut host, arm.watch.table), "watch stays rooted"); + assert_eq!( + named(&mut host, arm.watch.table, "orphan"), + None, + "the orphan weak entry is gone" + ); + assert_eq!( + named(&mut host, arm.watch.table, "env"), + None, + "the envelope weak entry is gone" + ); + assert_chain_dead(&mut host, &arm.note); + let stats = heap::stats(&mut host).expect("stats"); + assert_eq!(stats.live_nodes, 2); + assert_eq!(stats.live_roots, 0, "the safepoint frame was left"); + assert_eq!( + stats.root_slots, 0, + "no root slot remains after leave_roots" + ); + assert_eq!(stats.collections, 2); +} + +fn assert_unrooted_but_live(arm: &mut Arm) { + assert_eq!( + arm.collects.len(), + 1, + "the post-exit collect is absent from source" + ); + let inside = &arm.collects[0]; + assert_eq!( + inside.swept, 1, + "the in-block collect still reclaims the orphan" + ); + assert_eq!(inside.live_nodes, 6); + assert_eq!(inside.live_roots, 3); + let mut host = arm.vm.host_context(); + assert!(!alive(&mut host, arm.orphan.table)); + assert_eq!(named(&mut host, arm.watch.table, "orphan"), None); + assert_eq!( + named(&mut host, arm.watch.table, "env"), + Some(arm.note.envelope), + "the weak entry still names the original envelope" + ); + assert_chain_live(&mut host, &arm.note); + let stats = heap::stats(&mut host).expect("stats"); + assert_eq!( + stats.live_nodes, 6, + "leaving the block did not sweep the chain" + ); + assert_eq!( + stats.live_roots, 0, + "the in-block safepoint root is already closed; that is not collection" + ); + assert_eq!(stats.root_slots, 0); + assert_eq!(stats.collections, 1); +} + +fn assert_chain_live(host: &mut vm::HostContext<'_>, note: &LinkNote) { + assert!(alive(host, note.envelope)); + assert!(closure_alive(host, note.closure)); + assert!(cell_alive(host, note.cell)); + assert!(alive(host, note.target)); + assert_eq!(issued_ptr(host, note.envelope), Some(note.envelope_ptr)); + assert_eq!(issued_ptr(host, note.target), Some(note.target_ptr)); + assert_eq!(note.envelope.slot(), note.envelope_slot); + assert_eq!(note.envelope.generation(), note.envelope_generation); + assert_eq!(note.target.slot(), note.target_slot); + assert_eq!(note.target.generation(), note.target_generation); + let (closure, cell, current) = heap::with_heap(host, |heap| { + let closure = heap.closure_edge(note.envelope, CLOSURE_FIELD)?; + let cell = heap.upvalue_of(closure)?; + let current = heap.read_upvalue(closure)?; + Ok((closure, cell, current)) + }) + .expect("live closure graph"); + assert_eq!(closure, note.closure); + assert_eq!(closure.slot(), note.closure_slot); + assert_eq!(closure.generation(), note.closure_generation); + assert_eq!(cell, note.cell); + assert_eq!(cell.slot(), note.cell_slot); + assert_eq!(cell.generation(), note.cell_generation); + assert_eq!(current, note.target); +} + +fn assert_chain_dead(host: &mut vm::HostContext<'_>, note: &LinkNote) { + assert!(!alive(host, note.envelope)); + assert!(!closure_alive(host, note.closure)); + assert!(!cell_alive(host, note.cell)); + assert!(!alive(host, note.target)); + assert_eq!( + issued_ptr(host, note.envelope), + None, + "envelope issuance is stale" + ); + assert_eq!( + issued_ptr(host, note.target), + None, + "cell table issuance is stale" + ); + let stale = heap::with_heap(host, |heap| { + Ok(( + heap.closure_edge(note.envelope, CLOSURE_FIELD).is_err(), + heap.upvalue_of(note.closure).is_err(), + heap.read_upvalue(note.closure).is_err(), + )) + }) + .expect("stale queries"); + assert!( + stale.0 && stale.1 && stale.2, + "recorded identities no longer resolve" + ); +} + +fn alive(host: &mut vm::HostContext<'_>, table: TableRef) -> bool { + heap::with_heap(host, |heap| Ok(heap.alive(table))).expect("alive") +} + +fn closure_alive(host: &mut vm::HostContext<'_>, closure: ClosureRef) -> bool { + heap::with_heap(host, |heap| Ok(heap.closure_alive(closure))).expect("closure") +} + +fn cell_alive(host: &mut vm::HostContext<'_>, cell: UpvalueRef) -> bool { + heap::with_heap(host, |heap| Ok(heap.upvalue_alive(cell))).expect("cell") +} + +fn named(host: &mut vm::HostContext<'_>, table: TableRef, key: &str) -> Option { + heap::with_heap(host, |heap| heap.named_edge(table, key)).expect("named edge") +} + +fn issued_ptr(host: &mut vm::HostContext<'_>, table: TableRef) -> Option { + heap::with_heap(host, |heap| { + Ok(heap + .issued_value(table) + .ok() + .map(|value| carrier_ptr(&value))) + }) + .expect("issued identity") +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 9fd5c0d..cad63af 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -5,6 +5,8 @@ mod ast; mod candidate; #[path = "closure_graph.rs"] mod closure_graph; +#[path = "envelope_local_root.rs"] +mod envelope_local_root; #[path = "../../src/frontends/lua/lexer.rs"] #[allow(dead_code)] mod lexer; From 64534570399574eda48ed900fd54e769ad931256 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 19:58:31 +0800 Subject: [PATCH 068/225] feat(lua): lower one shared source closure cell onto table roots Source getter and setter close over the same lexical binding. CallValue runs both calls. A live callable publishes the envelope it copy-captured into the existing TableRef root list; collect_at_safepoint still receives only table roots. --- src/frontends/lua/resolve.rs | 36 +- tests/luajit_heap_runtime/candidate.rs | 518 +++++++++++++++++- tests/luajit_heap_runtime/source_closure.rs | 482 ++++++++++++++++ .../value_boundary_tests.rs | 2 + 4 files changed, 1017 insertions(+), 21 deletions(-) create mode 100644 tests/luajit_heap_runtime/source_closure.rs diff --git a/src/frontends/lua/resolve.rs b/src/frontends/lua/resolve.rs index 40272c1..b101b93 100644 --- a/src/frontends/lua/resolve.rs +++ b/src/frontends/lua/resolve.rs @@ -13,6 +13,9 @@ pub struct Resolution { pub labels: Vec, pub gotos: Vec, pub imports: Vec, + /// Name reads and assignments, recorded from the resolver's own scope stack. + /// A use whose function differs from the binding's function is a capture. + pub uses: Vec, pub errors: Vec, } @@ -37,6 +40,13 @@ pub struct Binding { pub const_binding: bool, } +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NameUse { + pub span: Span, + pub binding: Option, + pub function_id: u32, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct LabelBinding { pub name: Vec, @@ -151,6 +161,7 @@ pub fn resolve(chunk: &Chunk) -> Resolution { labels: Vec::new(), gotos: Vec::new(), imports: Vec::new(), + uses: Vec::new(), errors: Vec::new(), }, funcs: Vec::new(), @@ -324,7 +335,25 @@ impl Cx { .any(|local| local.name == name && local.const_binding) } + fn lookup_binding(&self, name: &[u8]) -> Option { + self.locals + .iter() + .rev() + .find(|local| local.name == name) + .map(|local| local.binding_index) + } + + fn note_name(&mut self, name: &Name) { + let function_id = self.funcs.last().expect("function").id; + self.resolution.uses.push(NameUse { + span: name.span, + binding: self.lookup_binding(&name.bytes), + function_id, + }); + } + fn assign_name(&mut self, name: &Name) { + self.note_name(name); if self.lookup_const(&name.bytes) { self.resolution.errors.push(ResolveError::AssignConst { span: name.span, @@ -663,11 +692,8 @@ impl Cx { fn walk_expr(&mut self, expr: &Expr) { match expr { - Expr::Nil { .. } - | Expr::Bool { .. } - | Expr::Number { .. } - | Expr::String { .. } - | Expr::Name { .. } => {} + Expr::Nil { .. } | Expr::Bool { .. } | Expr::Number { .. } | Expr::String { .. } => {} + Expr::Name { name, .. } => self.note_name(name), Expr::Vararg { span } => { if !self.funcs.last().is_some_and(|func| func.vararg) { self.resolution diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index be6fdf9..791076d 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -23,6 +23,11 @@ const BOOL_ARG: &str = "lua_internal::bool_arg"; const STRING_ARG: &str = "lua_internal::string_arg"; const GATHER_ROOT: &str = "lua_internal::gather_root"; pub(super) const COLLECT: &str = "lua_internal::collect"; +const OPEN_CELL: &str = "lua_internal::open_cell"; +const READ_CELL: &str = "lua_internal::read_cell"; +const WRITE_CELL: &str = "lua_internal::write_cell"; +const TRACK_CLOSURE: &str = "lua_internal::track_closure"; +const RETIRE_CLOSURE: &str = "lua_internal::retire_closure"; const ENTER_RESULT: &str = "lua_internal::enter_result_frame"; const ENTER_CALLEE: &str = "lua_internal::enter_callee_frame"; const ROOT_ISSUED: &str = "lua_internal::root_issued"; @@ -125,6 +130,15 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { (RETIRE_CALLEE, vec!["flag", "frame"], HostTypeSchema::Float), (RETIRE_CHUNK, vec!["frame"], HostTypeSchema::Float), (RELEASE_RESULT, vec!["frame", "slot"], HostTypeSchema::Float), + (OPEN_CELL, vec!["table"], HostTypeSchema::Unknown), + (READ_CELL, vec!["envelope"], HostTypeSchema::Unknown), + (WRITE_CELL, vec!["envelope", "table"], HostTypeSchema::Float), + ( + TRACK_CLOSURE, + vec!["closure", "envelope"], + HostTypeSchema::Float, + ), + (RETIRE_CLOSURE, vec!["closure"], HostTypeSchema::Float), ] { builder.function(HostFunctionSchema::with_return( name, @@ -165,6 +179,11 @@ pub(super) fn register( Op::ReleaseResult, Op::CopyFields, Op::ExternalShape, + Op::OpenCell, + Op::ReadCell, + Op::WriteCell, + Op::TrackClosure, + Op::RetireClosure, ] { let name = match op { Op::NewTable => NEW_TABLE, @@ -190,6 +209,11 @@ pub(super) fn register( Op::ReleaseResult => RELEASE_RESULT, Op::CopyFields => COPY_FIELDS, Op::ExternalShape => EXTERNAL_SHAPE, + Op::OpenCell => OPEN_CELL, + Op::ReadCell => READ_CELL, + Op::WriteCell => WRITE_CELL, + Op::TrackClosure => TRACK_CLOSURE, + Op::RetireClosure => RETIRE_CLOSURE, }; let function = catalog.function(name).expect("private Lua operation"); let schema = HostImportSchema::from_function(catalog, function); @@ -225,6 +249,11 @@ enum Op { ReleaseResult, CopyFields, ExternalShape, + OpenCell, + ReadCell, + WriteCell, + TrackClosure, + RetireClosure, } impl HostOwnedFunction for Op { @@ -341,9 +370,7 @@ impl HostOwnedFunction for Op { | heap::GuestClass::Boolean | heap::GuestClass::String => None, heap::GuestClass::Unissued => { - return Err(VmError::HostError( - "invalid private Lua root candidate".to_string(), - )); + published_capture(&mut call.vm().host_context(), &value)? } }; let root_list = call.take_arg(0)?; @@ -409,6 +436,11 @@ impl HostOwnedFunction for Op { } }, Self::ExternalShape => Value::array(vec![Value::Int(0), Value::Int(1)]), + Self::OpenCell => open_cell(call)?, + Self::ReadCell => read_cell(call)?, + Self::WriteCell => write_cell(call)?, + Self::TrackClosure => track_closure(call)?, + Self::RetireClosure => retire_closure(call)?, }; Ok(CallOutcome::Return(CallReturn::one(value))) } @@ -998,6 +1030,273 @@ fn note_collect( Ok(()) } +/// A callable is not a [`heap::TableRef`]. Gather publishes the issued envelope +/// the closure copy-captured, so `collect_at_safepoint` still receives only +/// table roots. Retiring the callable drops that publication. +fn published_capture( + host: &mut vm::HostContext<'_>, + value: &Value, +) -> Result, VmError> { + let Value::Callable(callable) = value else { + return Err(host_fault("invalid private Lua root candidate")); + }; + let ptr = std::sync::Arc::as_ptr(callable) as usize; + let envelope = host.scope_state::().and_then(|graph| { + graph + .published + .iter() + .find(|(found, _)| *found == ptr) + .map(|(_, envelope)| *envelope) + }); + let Some(envelope) = envelope else { + return Err(host_fault("invalid private Lua root candidate")); + }; + heap::with_heap(host, |heap| heap.issued_value(envelope)) + .map_err(heap_error) + .map(Some) +} + +#[derive(Clone, Copy, Debug)] +pub(super) struct CaptureNote { + pub envelope: heap::TableRef, + pub closure: heap::ClosureRef, + pub cell: heap::UpvalueRef, + pub callable: usize, +} + +struct CaptureGraph { + cells: Vec<(heap::TableRef, heap::UpvalueRef)>, + published: Vec<(usize, heap::TableRef)>, + notes: Vec, + reads: u32, + writes: u32, +} + +fn with_capture( + host: &mut vm::HostContext<'_>, + body: impl FnOnce(&mut CaptureGraph) -> T, +) -> Result { + let graph = host + .scope_state_or_insert_with(|| CaptureGraph { + cells: Vec::new(), + published: Vec::new(), + notes: Vec::new(), + reads: 0, + writes: 0, + }) + .map_err(|error| host_fault(&error.to_string()))?; + Ok(body(graph)) +} + +fn root_count(host: &mut vm::HostContext<'_>) -> Result { + heap::stats(host) + .map(|stats| stats.live_roots) + .map_err(heap_error) +} + +fn refuse_root_change( + before: u32, + host: &mut vm::HostContext<'_>, + what: &str, +) -> Result<(), VmError> { + let after = root_count(host)?; + if after != before { + return Err(host_fault(what)); + } + Ok(()) +} + +fn issued_table(host: &mut vm::HostContext<'_>, value: &Value) -> Result { + match classify(host, value)? { + heap::GuestClass::Table(table) => Ok(table), + _ => Err(host_fault("Lua cell operand is not an issued table")), + } +} + +fn open_cell(call: &mut OwnedHostCall<'_>) -> Result { + let table = match call.args() { + [table] => table.clone(), + _ => return Err(host_fault("open_cell needs the initial table")), + }; + let initial = issued_table(&mut call.vm().host_context(), &table)?; + let before = root_count(&mut call.vm().host_context())?; + let issued = heap::with_heap(&mut call.vm().host_context(), |heap| { + let envelope = heap.alloc()?; + let carrier = heap.issue_carrier(envelope)?; + let cell = heap.alloc_upvalue()?; + heap.write_upvalue(cell, initial)?; + Ok((carrier, envelope, cell)) + }) + .map_err(heap_error)?; + let (carrier, envelope, cell) = issued; + with_capture(&mut call.vm().host_context(), |graph| { + graph.cells.push((envelope, cell)); + })?; + refuse_root_change( + before, + &mut call.vm().host_context(), + "open_cell published a heap root", + )?; + Ok(carrier) +} + +fn cell_of( + host: &mut vm::HostContext<'_>, + envelope: heap::TableRef, +) -> Result { + with_capture(host, |graph| { + graph + .cells + .iter() + .find(|(found, _)| *found == envelope) + .map(|(_, cell)| *cell) + })? + .ok_or_else(|| host_fault("envelope has no shared cell")) +} + +fn read_cell(call: &mut OwnedHostCall<'_>) -> Result { + let envelope = match call.args() { + [envelope] => envelope.clone(), + _ => return Err(host_fault("read_cell needs the captured envelope")), + }; + let envelope = issued_table(&mut call.vm().host_context(), &envelope)?; + let cell = cell_of(&mut call.vm().host_context(), envelope)?; + let closure = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.closure_edge(envelope, 1) + }) + .map_err(heap_error)?; + let same = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.upvalue_of(closure) + }) + .map_err(heap_error)?; + if same != cell { + return Err(host_fault("closure edge does not share the opened cell")); + } + with_capture(&mut call.vm().host_context(), |graph| graph.reads += 1)?; + let table = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.read_upvalue(closure) + }) + .map_err(heap_error)?; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.issued_value(table) + }) + .map_err(heap_error) +} + +fn write_cell(call: &mut OwnedHostCall<'_>) -> Result { + let (envelope, next) = match call.args() { + [envelope, next] => (envelope.clone(), next.clone()), + _ => { + return Err(host_fault( + "write_cell needs the envelope and the next table", + )); + } + }; + let envelope = issued_table(&mut call.vm().host_context(), &envelope)?; + let next = issued_table(&mut call.vm().host_context(), &next)?; + let cell = cell_of(&mut call.vm().host_context(), envelope)?; + let before = root_count(&mut call.vm().host_context())?; + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.write_upvalue(cell, next) + }) + .map_err(heap_error)?; + with_capture(&mut call.vm().host_context(), |graph| graph.writes += 1)?; + refuse_root_change( + before, + &mut call.vm().host_context(), + "write_cell published a heap root", + )?; + Ok(Value::Float(0.0)) +} + +fn track_closure(call: &mut OwnedHostCall<'_>) -> Result { + let (closure, envelope) = match call.args() { + [closure, envelope] => (closure.clone(), envelope.clone()), + _ => { + return Err(host_fault( + "track_closure needs the callable and its envelope", + )); + } + }; + let Value::Callable(callable) = &closure else { + return Err(host_fault("tracked closure is not a callable")); + }; + let ptr = std::sync::Arc::as_ptr(callable) as usize; + let envelope = issued_table(&mut call.vm().host_context(), &envelope)?; + let cell = cell_of(&mut call.vm().host_context(), envelope)?; + let before = root_count(&mut call.vm().host_context())?; + let field = with_capture(&mut call.vm().host_context(), |graph| { + 1 + graph + .notes + .iter() + .filter(|note| note.envelope == envelope) + .count() as u32 + })?; + let node = heap::with_heap(&mut call.vm().host_context(), |heap| { + let node = heap.alloc_closure()?; + heap.set_upvalue_edge(node, cell)?; + heap.set_closure_edge(envelope, field, node)?; + Ok(node) + }) + .map_err(heap_error)?; + with_capture(&mut call.vm().host_context(), |graph| { + graph.published.push((ptr, envelope)); + graph.notes.push(CaptureNote { + envelope, + closure: node, + cell, + callable: ptr, + }); + })?; + refuse_root_change( + before, + &mut call.vm().host_context(), + "track_closure published a heap root", + )?; + Ok(Value::Float(0.0)) +} + +fn retire_closure(call: &mut OwnedHostCall<'_>) -> Result { + let closure = match call.args() { + [closure] => closure.clone(), + _ => return Err(host_fault("retire_closure needs the callable")), + }; + let Some(ptr) = callable_ptr(&closure) else { + return Ok(Value::Float(0.0)); + }; + let before = root_count(&mut call.vm().host_context())?; + let _ = with_capture(&mut call.vm().host_context(), |graph| { + graph.published.retain(|(found, _)| *found != ptr); + }); + refuse_root_change( + before, + &mut call.vm().host_context(), + "retire_closure published a heap root", + )?; + Ok(Value::Float(0.0)) +} + +fn callable_ptr(value: &Value) -> Option { + match value { + Value::Callable(callable) => Some(std::sync::Arc::as_ptr(callable) as usize), + _ => None, + } +} + +pub(super) fn capture_notes(vm: &mut vm::Vm) -> Vec { + vm.host_context() + .scope_state::() + .map(|graph| graph.notes.clone()) + .unwrap_or_default() +} + +pub(super) fn capture_counts(vm: &mut vm::Vm) -> (u32, u32) { + vm.host_context() + .scope_state::() + .map(|graph| (graph.reads, graph.writes)) + .unwrap_or((0, 0)) +} + fn collect_at_safepoint( host: &mut vm::HostContext<'_>, roots: &[heap::TableRef], @@ -1070,6 +1369,8 @@ pub(super) fn lower_returning( ignored_slot: None, resolution: &resolution, binding_slots: vec![None; resolution.bindings.len()], + capture_envelopes: HashMap::new(), + closure_slots: HashSet::new(), }; if lower.receiver_width > 0 { let slot = lower.builder.alloc_local_named("#caller-frame")?; @@ -1227,6 +1528,8 @@ struct Lower<'a> { ignored_slot: Option, resolution: &'a resolve::Resolution, binding_slots: Vec>, + capture_envelopes: HashMap, + closure_slots: HashSet, } #[derive(Clone, Copy)] @@ -1655,7 +1958,10 @@ impl Lower<'_> { .builder .alloc_local_named(&format!("#{}", span.start))?; self.remember_binding(span, name, index)?; - self.live_locals.push(index); + let nil_init = matches!(value, ast::Expr::Nil { .. }); + if !nil_init { + self.live_locals.push(index); + } self.stmts.push(Stmt::Let { index, declared_schema: None, @@ -1682,9 +1988,162 @@ impl Lower<'_> { )?; self.emit_ignored(expr, self.line(span))?; } + if !nil_init { + self.open_captured_cell(span, name, index)?; + } + Ok(()) + } + + fn open_captured_cell( + &mut self, + span: ast::Span, + name: &ast::Name, + slot: LocalSlot, + ) -> Result<(), ParseError> { + let Ok(binding) = self.chunk_binding(name, span) else { + return Ok(()); + }; + if !self.binding_is_captured(binding) { + return Ok(()); + } + let envelope = self.builder.alloc_local_named("#envelope")?; + let expr = self.call(OPEN_CELL, vec![Expr::Var(slot)])?; + self.stmts.push(Stmt::Let { + index: envelope, + declared_schema: None, + expr, + line: self.line(span), + }); + self.capture_envelopes.insert(binding, envelope); + Ok(()) + } + + fn binding_is_captured(&self, binding: usize) -> bool { + let owner = self.resolution.bindings[binding].function_id; + self.resolution + .uses + .iter() + .any(|use_site| use_site.binding == Some(binding) && use_site.function_id != owner) + } + + fn captures_in(&self, span: ast::Span) -> Vec { + let mut found = Vec::new(); + for use_site in &self.resolution.uses { + if use_site.span.start < span.start || use_site.span.end > span.end { + continue; + } + let Some(binding) = use_site.binding else { + continue; + }; + if self.resolution.bindings[binding].function_id == use_site.function_id { + continue; + } + if !found.contains(&binding) { + found.push(binding); + } + } + found + } + + fn lower_closure_assign( + &mut self, + span: ast::Span, + name: &ast::Name, + func: &ast::FuncBody, + ) -> Result<(), ParseError> { + if !func.params.is_empty() || func.vararg || func.self_param { + return Err(self.unsupported(func.span)); + } + let captures = self.captures_in(func.span); + let [binding] = captures.as_slice() else { + return Err(self.unsupported(func.span)); + }; + let envelope = self + .capture_envelopes + .get(binding) + .copied() + .ok_or_else(|| self.unsupported(func.span))?; + let slot = self + .locals + .get(&name.bytes) + .copied() + .ok_or_else(|| self.unsupported(span))?; + let captured = self.builder.alloc_local_named("#capture")?; + let body = self.closure_body(func, *binding, captured)?; + self.stmts.push(Stmt::Assign { + kind: AssignmentKind::Set, + index: slot, + expr: Expr::Closure(vm::ClosureExpr { + param_slots: Vec::new(), + capture_copies: vec![(envelope, captured)], + body: Box::new(body), + }), + line: self.line(span), + }); + let track = self.call(TRACK_CLOSURE, vec![Expr::Var(slot), Expr::Var(envelope)])?; + self.emit_ignored(track, self.line(span))?; + if !self.live_locals.contains(&slot) { + self.live_locals.push(slot); + } + self.closure_slots.insert(slot); Ok(()) } + fn closure_body( + &mut self, + func: &ast::FuncBody, + binding: usize, + captured: LocalSlot, + ) -> Result { + match func.body.stmts.as_slice() { + [ast::Stmt::Return { values, .. }] + if values.exprs.len() == 1 && self.use_is_binding(&values.exprs[0], binding) => + { + self.call(READ_CELL, vec![Expr::Var(captured)]) + } + [ + ast::Stmt::Assign { + targets, + values, + span, + }, + ] if targets.len() == 1 + && values.exprs.len() == 1 + && self.target_is_binding(&targets[0], binding) + && matches!( + values.exprs[0], + ast::Expr::Table { ref fields, .. } if fields.is_empty() + ) => + { + let next = self.call(NEW_TABLE, vec![])?; + self.call(WRITE_CELL, vec![Expr::Var(captured), next]) + .map_err(|_| self.unsupported(*span)) + } + [other, ..] => Err(self.unsupported(stmt_span(other))), + [] => Err(self.unsupported(func.span)), + } + } + + fn use_is_binding(&self, expr: &ast::Expr, binding: usize) -> bool { + let ast::Expr::Name { name, .. } = expr else { + return false; + }; + self.resolution + .uses + .iter() + .any(|use_site| use_site.span == name.span && use_site.binding == Some(binding)) + } + + fn target_is_binding(&self, target: &ast::AssignTarget, binding: usize) -> bool { + let ast::AssignTarget::Name(name) = target else { + return false; + }; + self.resolution + .uses + .iter() + .any(|use_site| use_site.span == name.span && use_site.binding == Some(binding)) + } + fn lower_assign( &mut self, span: ast::Span, @@ -1698,6 +2157,11 @@ impl Lower<'_> { .get(&name.bytes) .copied() .ok_or_else(|| self.unsupported(span))?; + if self.closure_slots.contains(&slot) { + let retire = self.call(RETIRE_CLOSURE, vec![Expr::Var(slot)])?; + self.emit_ignored(retire, self.line(span))?; + self.closure_slots.remove(&slot); + } self.stmts.push(Stmt::Assign { kind: AssignmentKind::Set, index: slot, @@ -1739,6 +2203,9 @@ impl Lower<'_> { }, _, ) => self.lower_index_assign(span, table, key, value), + (ast::AssignTarget::Name(name), ast::Expr::Function { body, .. }) => { + self.lower_closure_assign(span, name, body) + } _ => Err(self.unsupported(span)), } } @@ -2128,6 +2595,7 @@ impl Lower<'_> { .copied() .map(Expr::Var) .ok_or_else(|| self.unsupported(expr.span())), + ast::Expr::Nil { .. } => Ok(Expr::Null), ast::Expr::Paren { inner, .. } => self.expr(inner), ast::Expr::BinaryChain { span, base, steps } => { let mut left = self.expr(base)?; @@ -2169,6 +2637,20 @@ impl Lower<'_> { { self.field_read(base, &name.bytes, *span) } + ast::Expr::SuffixChain { base, steps, .. } + if let ast::Expr::Name { name, .. } = base.as_ref() + && let Some(slot) = self.locals.get(&name.bytes).copied() + && let [ + ast::Suffix::Call { + args: ast::Args::List(args), + nav: false, + .. + }, + ] = steps.as_slice() + && args.exprs.is_empty() => + { + Ok(Expr::LocalCall(slot, Vec::new(), Vec::new(), None)) + } ast::Expr::SuffixChain { base, steps, .. } if let ast::Expr::Name { name, .. } = base.as_ref() && !self.locals.contains_key(&name.bytes) @@ -2268,17 +2750,6 @@ impl Lower<'_> { let mut checked = Vec::new(); let temp_base = self.active_temps.len(); for (arg, param) in args.iter().zip(&function.params) { - let adapter = match (¶m.ty, param.passing) { - (HostTypeSchema::Float, vm::HostParamPassing::Value) => NUMBER_ARG, - (HostTypeSchema::Bool, vm::HostParamPassing::Value) => BOOL_ARG, - (HostTypeSchema::String, vm::HostParamPassing::Value) => STRING_ARG, - (HostTypeSchema::Resource(key), vm::HostParamPassing::Borrow) - if *key == heap::LuaTableResource::key() => - { - TABLE_ARG - } - _ => return Err(self.unsupported(span)), - }; let value = self.expr(arg)?; let slot = self .builder @@ -2290,7 +2761,22 @@ impl Lower<'_> { line: self.line(span), }); self.active_temps.push(slot); - checked.push(self.call(adapter, vec![Expr::Var(slot)])?); + let forwarded = match (¶m.ty, param.passing) { + (HostTypeSchema::Float, vm::HostParamPassing::Value) => NUMBER_ARG, + (HostTypeSchema::Bool, vm::HostParamPassing::Value) => BOOL_ARG, + (HostTypeSchema::String, vm::HostParamPassing::Value) => STRING_ARG, + (HostTypeSchema::Resource(key), vm::HostParamPassing::Borrow) + if *key == heap::LuaTableResource::key() => + { + TABLE_ARG + } + (HostTypeSchema::Unknown, vm::HostParamPassing::Value) => { + checked.push(Expr::Var(slot)); + continue; + } + _ => return Err(self.unsupported(span)), + }; + checked.push(self.call(forwarded, vec![Expr::Var(slot)])?); } self.active_temps.truncate(temp_base); self.call(name, checked) diff --git a/tests/luajit_heap_runtime/source_closure.rs b/tests/luajit_heap_runtime/source_closure.rs new file mode 100644 index 0000000..af1045e --- /dev/null +++ b/tests/luajit_heap_runtime/source_closure.rs @@ -0,0 +1,482 @@ +//! Lua source creates one shared cell, calls both closures, and collects it. +//! +//! `collect_at_safepoint` still receives only [`heap::TableRef`] roots. A live +//! callable is not itself a root: gather publishes the issued envelope that +//! the closure copy-captured. The heap upvalue, not a Core borrow cell, is the +//! mutable capture. Host observers record handles and booleans; they do not +//! root, collect, call the closures, or write the cell. + +use std::sync::{Arc, OnceLock}; + +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + HostFunctionRegistry, HostFunctionSchema, HostImportSchema, HostOwnedFunction, + HostParamPassing, HostParamSchema, HostTypeSchema, OpCode, OwnedHostCall, ParseError, + SourceFlavor, SourcePlugin, Value, VmError, VmStatus, +}; + +use super::candidate::{self, CaptureNote}; +use super::heap::{self, TableRef}; + +const OBSERVE: &str = "lua_host::observe_table"; +const NOTE_FN: &str = "lua_host::note_fn"; +const NOTE_PHASE: &str = "lua_host::note_phase"; + +const SOURCE: &str = r#" +local mt = {} +mt.__mode = "v" +local weak = {} +setmetatable(weak, mt) +observe_table(weak, 0) +do + local get = nil + local set = nil + do + local held = {} + weak.old = held + observe_table(held, 1) + get = function() + return held + end + set = function() + held = {} + end + end + note_fn(get) + note_fn(set) + local orphan = {} + weak.orphan = orphan + observe_table(orphan, 2) + orphan = nil + collectgarbage("collect") + note_phase(weak, 1) + local first = get() + observe_table(first, 3) + first = nil + set() + @replace@ + note_phase(weak, 2) + local second = get() + weak.next = second + observe_table(second, 4) + second = nil + get = nil + set = nil +end +@drop@ +note_phase(weak, 3) +"#; + +#[derive(Clone, Copy, Debug)] +struct Phase { + id: u32, + old: bool, + orphan: bool, + next: bool, + held_alive: bool, + orphan_alive: bool, +} + +#[derive(Clone, Debug, Default)] +struct Obs { + tables: Vec<(u32, TableRef)>, + callables: Vec, + phases: Vec, +} + +struct ObserveTable; +struct NoteFn; +struct NotePhase; + +fn catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(HostFunctionSchema::with_return( + OBSERVE, + vec![ + HostParamSchema::with_passing("table", table.clone(), HostParamPassing::Borrow), + HostParamSchema::value("tag", HostTypeSchema::Float), + ], + HostTypeSchema::Float, + )); + builder.function(HostFunctionSchema::with_return( + NOTE_FN, + vec![HostParamSchema::value("closure", HostTypeSchema::Unknown)], + HostTypeSchema::Float, + )); + builder.function(HostFunctionSchema::with_return( + NOTE_PHASE, + vec![ + HostParamSchema::with_passing("weak", table, HostParamPassing::Borrow), + HostParamSchema::value("id", HostTypeSchema::Float), + ], + HostTypeSchema::Float, + )); + Arc::new(builder.build().expect("shared-closure catalog")) + }) +} + +struct Plugin; + +impl SourcePlugin for Plugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, catalog()) + } +} + +fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + for name in [OBSERVE, NOTE_FN, NOTE_PHASE] { + let function = catalog.function(name).expect("observer schema"); + registry + .register_exact_owned( + name, + function.params.len() as u8, + HostImportSchema::from_function(catalog, function), + move |_| ctor_box(name), + ) + .expect("register observer"); + } +} + +fn ctor_box(name: &str) -> Box { + match name { + OBSERVE => Box::new(ObserveTable), + NOTE_FN => Box::new(NoteFn), + NOTE_PHASE => Box::new(NotePhase), + _ => unreachable!("observer name"), + } +} + +fn host_fault(message: &str) -> VmError { + VmError::HostError(message.to_string()) +} + +fn borrowed_table(call: &mut OwnedHostCall<'_>, index: usize) -> Result { + let Value::Int(raw) = call.args().get(index).cloned().unwrap_or(Value::Null) else { + return Err(host_fault("observer table is not a resource handle")); + }; + let raw = u64::try_from(raw).map_err(|_| host_fault("observer token out of range"))?; + let token = vm::ResourceHandle::from_raw(raw).map_err(|_| host_fault("observer token"))?; + let host = call.vm().host_context(); + let key = heap::LuaTableResource::key(); + host.borrow_resource_with_key::(token, &key) + .map(|resource| resource.table()) + .map_err(|error| host_fault(&error.to_string())) +} + +fn tag_of(call: &OwnedHostCall<'_>, index: usize) -> Result { + match call.args().get(index) { + Some(Value::Float(number)) if number.fract() == 0.0 && *number >= 0.0 => Ok(*number as u32), + _ => Err(host_fault("observer tag is not a number")), + } +} + +fn obs<'a>(host: &'a mut vm::HostContext<'a>) -> Result<&'a mut Obs, VmError> { + host.scope_state_or_insert_with(Obs::default) + .map_err(|error| host_fault(&error.to_string())) +} + +impl HostOwnedFunction for ObserveTable { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let table = borrowed_table(call, 0)?; + let tag = tag_of(call, 1)?; + let before = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + obs(&mut call.vm().host_context())? + .tables + .push((tag, table)); + let after = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + if after.live_roots != before.live_roots || after.collections != before.collections { + return Err(host_fault("observe_table rooted or collected")); + } + Ok(CallOutcome::Return(CallReturn::one(Value::Float(0.0)))) + } +} + +impl HostOwnedFunction for NoteFn { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let ptr = match call.args() { + [Value::Callable(callable)] => Arc::as_ptr(callable) as usize, + _ => return Err(host_fault("note_fn expected the source closure")), + }; + let before = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + obs(&mut call.vm().host_context())?.callables.push(ptr); + let after = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + if after.live_roots != before.live_roots || after.collections != before.collections { + return Err(host_fault("note_fn rooted or collected")); + } + Ok(CallOutcome::Return(CallReturn::one(Value::Float(0.0)))) + } +} + +impl HostOwnedFunction for NotePhase { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let weak = borrowed_table(call, 0)?; + let id = tag_of(call, 1)?; + let before = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + let (held, orphan_ref) = { + let mut host = call.vm().host_context(); + let tables = obs(&mut host)?.tables.clone(); + ( + tables + .iter() + .find(|(tag, _)| *tag == 1) + .map(|(_, table)| *table), + tables + .iter() + .find(|(tag, _)| *tag == 2) + .map(|(_, table)| *table), + ) + }; + let (old, orphan, next, held_alive, orphan_alive) = { + let mut host = call.vm().host_context(); + heap::with_heap(&mut host, |heap| { + Ok(( + heap.named_edge(weak, "old")?.is_some(), + heap.named_edge(weak, "orphan")?.is_some(), + heap.named_edge(weak, "next")?.is_some(), + held.is_some_and(|table| heap.alive(table)), + orphan_ref.is_some_and(|table| heap.alive(table)), + )) + }) + .map_err(|error| host_fault(&error.to_string()))? + }; + obs(&mut call.vm().host_context())?.phases.push(Phase { + id, + old, + orphan, + next, + held_alive, + orphan_alive, + }); + let after = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + if after.live_roots != before.live_roots || after.collections != before.collections { + return Err(host_fault("note_phase rooted or collected")); + } + Ok(CallOutcome::Return(CallReturn::one(Value::Float(0.0)))) + } +} + +struct Arm { + vm: vm::Vm, + notes: Vec, + reads: u32, + writes: u32, + obs: Obs, + call_values: usize, + call_scripts: usize, +} + +fn source(replace: bool, drop: bool) -> String { + SOURCE + .replace( + "@replace@", + if replace { + "collectgarbage(\"collect\")" + } else { + "" + }, + ) + .replace( + "@drop@", + if drop { + "collectgarbage(\"collect\")" + } else { + "" + }, + ) +} + +fn run_arm(replace: bool, drop: bool) -> Arm { + let source = source(replace, drop); + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = vm::compile_source_with_flavor_and_options(&source, SourceFlavor::Lua, options) + .unwrap_or_else(|error| panic!("lower/compile rejected the source: {error}")); + let mut vm = prepared.into_vm().expect("create VM"); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind runtime"); + let (call_values, call_scripts) = opcode_counts(vm.program()); + assert_eq!( + vm.run().expect("run source closures"), + VmStatus::Halted, + "replace={replace} drop={drop}" + ); + let notes = candidate::capture_notes(&mut vm); + let (reads, writes) = candidate::capture_counts(&mut vm); + let obs = vm + .host_context() + .scope_state::() + .cloned() + .unwrap_or_default(); + Arm { + vm, + notes, + reads, + writes, + obs, + call_values, + call_scripts, + } +} + +fn opcode_counts(program: &vm::Program) -> (usize, usize) { + let mut ip = 0; + let mut call_values = 0; + let mut call_scripts = 0; + while ip < program.code.len() { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + match op { + OpCode::CallValue => call_values += 1, + OpCode::CallScript => call_scripts += 1, + _ => {} + } + ip += 1 + op.operand_len(); + } + (call_values, call_scripts) +} + +fn tagged(obs: &Obs, tag: u32) -> TableRef { + obs.tables + .iter() + .find(|(found, _)| *found == tag) + .map(|(_, table)| *table) + .unwrap_or_else(|| panic!("missing observation {tag}")) +} + +fn phase(obs: &Obs, id: u32) -> Phase { + obs.phases + .iter() + .copied() + .find(|phase| phase.id == id) + .unwrap_or_else(|| panic!("missing phase {id}")) +} + +fn alive(vm: &mut vm::Vm, table: TableRef) -> bool { + heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.alive(table))).expect("alive") +} + +fn closure_alive(vm: &mut vm::Vm, note: &CaptureNote) -> bool { + heap::with_heap(&mut vm.host_context(), |heap| { + Ok(heap.closure_alive(note.closure) && heap.upvalue_alive(note.cell)) + }) + .expect("closure") +} + +fn assert_shared_calls(arm: &Arm) { + assert_eq!( + arm.call_scripts, 0, + "static CallScript must not implement the calls" + ); + assert_eq!( + arm.call_values, 3, + "getter twice and setter once must be CallValue" + ); + assert_eq!(arm.reads, 2, "the source getter ran twice"); + assert_eq!(arm.writes, 1, "the source setter wrote the cell"); + assert_eq!(arm.notes.len(), 2, "two source closures"); + assert_eq!(arm.notes[0].cell, arm.notes[1].cell, "one shared cell"); + assert_eq!( + arm.notes[0].envelope, arm.notes[1].envelope, + "one captured envelope" + ); + assert_eq!( + arm.obs.callables, + vec![arm.notes[0].callable, arm.notes[1].callable] + ); + assert_ne!(arm.notes[0].closure, arm.notes[1].closure); + assert_eq!( + tagged(&arm.obs, 1), + tagged(&arm.obs, 3), + "getter returned the original table" + ); + assert_ne!( + tagged(&arm.obs, 3), + tagged(&arm.obs, 4), + "setter replaced the cell table" + ); + let first = phase(&arm.obs, 1); + assert!( + !first.orphan && !first.orphan_alive, + "first collect swept the orphan" + ); + assert!( + first.old && first.held_alive, + "closure kept the original table" + ); +} + +#[test] +fn source_closures_share_one_cell_across_block_exit_and_collect() { + let mut both = run_arm(true, true); + assert_shared_calls(&both); + let replaced = phase(&both.obs, 2); + assert!( + !replaced.old && !replaced.held_alive, + "replace collect released the old table" + ); + let done = phase(&both.obs, 3); + assert!(!done.next, "drop collect cleared the new weak entry"); + assert!(!alive(&mut both.vm, tagged(&both.obs, 4))); + assert!( + both.notes + .iter() + .all(|note| !closure_alive(&mut both.vm, note)) + ); + + let mut keep_old = run_arm(false, true); + assert_shared_calls(&keep_old); + let still = phase(&keep_old.obs, 2); + assert!( + still.old && still.held_alive, + "omitted replace collect left the old table" + ); + let dropped = phase(&keep_old.obs, 3); + assert!(!dropped.next); + assert!(!alive(&mut keep_old.vm, tagged(&keep_old.obs, 4))); + assert!( + keep_old + .notes + .iter() + .all(|note| !closure_alive(&mut keep_old.vm, note)) + ); + + let mut keep_graph = run_arm(true, false); + assert_shared_calls(&keep_graph); + let replaced = phase(&keep_graph.obs, 2); + assert!(!replaced.old && !replaced.held_alive); + let kept = phase(&keep_graph.obs, 3); + assert!(kept.next, "omitted drop collect left the new table"); + assert!(alive(&mut keep_graph.vm, tagged(&keep_graph.obs, 4))); + assert!( + keep_graph + .notes + .iter() + .all(|note| closure_alive(&mut keep_graph.vm, note)) + ); + assert!(!alive(&mut keep_graph.vm, tagged(&keep_graph.obs, 1))); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index cad63af..0043a95 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -15,6 +15,8 @@ mod parser; #[path = "../../src/frontends/lua/resolve.rs"] mod resolve; mod return_frame; +#[path = "source_closure.rs"] +mod source_closure; use super::heap; use super::support; From c843c6b1309b49d722702727efb495c4414f4d83 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 21:01:11 +0800 Subject: [PATCH 069/225] fix(lua): share one cell between the outer binding and each closure Outer reads and writes follow the binding anchor's cell edge. Each closure keeps its own envelope, so a surviving sibling no longer roots a replaced callable, and the cell dies with its last root. --- src/frontends/lua/heap/table.rs | 54 +++ tests/luajit_heap_runtime/candidate.rs | 356 ++++++++------- tests/luajit_heap_runtime/source_closure.rs | 463 +++++++++++++++++++- 3 files changed, 709 insertions(+), 164 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 5c9018c..c94ada0 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -22,6 +22,9 @@ const UPVALUE_EDGE: u32 = 0; /// Cell current-value field. It is keyed only on an upvalue node. A missing /// edge is nil. This id is not a Lua number. const CURRENT_EDGE: u32 = 0; +/// Table-to-cell field. Not `__mode`, and not the per-closure field that +/// points at that closure's own node. This id is not a Lua number. +const CELL_EDGE: u32 = 2; /// Hard caps. Edges and root slots are counted separately so fields cannot /// grow past the edge cap by avoiding the node cap. @@ -824,6 +827,57 @@ impl LuaHeap { Ok(closure) } + /// Points a table at the one cell that binding uses. + /// + /// The field is private. It is not a Lua key, so next/raw enumeration does + /// not see it. A non-weak table follows the edge strongly through the + /// existing mark; this does not add a scan rule. + pub fn set_cell_edge(&mut self, from: TableRef, cell: UpvalueRef) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_upvalue(cell)?; + self.write_from( + from.slot(), + EdgeKey::Field(CELL_EDGE), + EdgeValue::Upvalue { + slot: cell.slot(), + generation: cell.generation(), + }, + ) + } + + /// The cell a table publishes. A missing edge is `StaleHandle`. + pub fn cell_edge(&self, from: TableRef) -> Result { + self.require_live(from)?; + let Some(value) = self.stored_from(from.slot(), &EdgeKey::Field(CELL_EDGE)) else { + return Err(HeapError::StaleHandle); + }; + let EdgeValue::Upvalue { slot, generation } = value else { + return Err(HeapError::WrongKind); + }; + let cell = UpvalueRef::upvalue(self.domain, *slot, *generation); + self.require_upvalue(cell)?; + Ok(cell) + } + + /// The table currently stored in a cell. + /// + /// `Ok(None)` is a missing current edge, which is nil. This does not go + /// through a closure. + pub fn current_table(&self, cell: UpvalueRef) -> Result, HeapError> { + self.require_upvalue(cell)?; + let Some(value) = self.stored_from(cell.slot(), &EdgeKey::Field(CURRENT_EDGE)) else { + return Ok(None); + }; + match value { + EdgeValue::Table { slot, generation } => { + let table = TableRef::table(self.domain, *slot, *generation); + self.require_live(table)?; + Ok(Some(table)) + } + _ => Err(HeapError::WrongKind), + } + } + /// Writes a scalar into the same record and quota as a table edge. /// /// Nil deletes that record. A string may occupy any direct field. A number diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 791076d..7a9283d 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -27,7 +27,6 @@ const OPEN_CELL: &str = "lua_internal::open_cell"; const READ_CELL: &str = "lua_internal::read_cell"; const WRITE_CELL: &str = "lua_internal::write_cell"; const TRACK_CLOSURE: &str = "lua_internal::track_closure"; -const RETIRE_CLOSURE: &str = "lua_internal::retire_closure"; const ENTER_RESULT: &str = "lua_internal::enter_result_frame"; const ENTER_CALLEE: &str = "lua_internal::enter_callee_frame"; const ROOT_ISSUED: &str = "lua_internal::root_issued"; @@ -135,10 +134,9 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { (WRITE_CELL, vec!["envelope", "table"], HostTypeSchema::Float), ( TRACK_CLOSURE, - vec!["closure", "envelope"], + vec!["closure", "anchor", "envelope"], HostTypeSchema::Float, ), - (RETIRE_CLOSURE, vec!["closure"], HostTypeSchema::Float), ] { builder.function(HostFunctionSchema::with_return( name, @@ -183,7 +181,6 @@ pub(super) fn register( Op::ReadCell, Op::WriteCell, Op::TrackClosure, - Op::RetireClosure, ] { let name = match op { Op::NewTable => NEW_TABLE, @@ -213,7 +210,6 @@ pub(super) fn register( Op::ReadCell => READ_CELL, Op::WriteCell => WRITE_CELL, Op::TrackClosure => TRACK_CLOSURE, - Op::RetireClosure => RETIRE_CLOSURE, }; let function = catalog.function(name).expect("private Lua operation"); let schema = HostImportSchema::from_function(catalog, function); @@ -253,7 +249,6 @@ enum Op { ReadCell, WriteCell, TrackClosure, - RetireClosure, } impl HostOwnedFunction for Op { @@ -370,7 +365,15 @@ impl HostOwnedFunction for Op { | heap::GuestClass::Boolean | heap::GuestClass::String => None, heap::GuestClass::Unissued => { - published_capture(&mut call.vm().host_context(), &value)? + // A callable is not a table root. Its shadow envelope, + // when still assigned, is the issued table gather sees. + if matches!(value, Value::Callable(_)) { + None + } else { + return Err(VmError::HostError( + "invalid private Lua root candidate".to_string(), + )); + } } }; let root_list = call.take_arg(0)?; @@ -440,7 +443,6 @@ impl HostOwnedFunction for Op { Self::ReadCell => read_cell(call)?, Self::WriteCell => write_cell(call)?, Self::TrackClosure => track_closure(call)?, - Self::RetireClosure => retire_closure(call)?, }; Ok(CallOutcome::Return(CallReturn::one(value))) } @@ -1030,32 +1032,6 @@ fn note_collect( Ok(()) } -/// A callable is not a [`heap::TableRef`]. Gather publishes the issued envelope -/// the closure copy-captured, so `collect_at_safepoint` still receives only -/// table roots. Retiring the callable drops that publication. -fn published_capture( - host: &mut vm::HostContext<'_>, - value: &Value, -) -> Result, VmError> { - let Value::Callable(callable) = value else { - return Err(host_fault("invalid private Lua root candidate")); - }; - let ptr = std::sync::Arc::as_ptr(callable) as usize; - let envelope = host.scope_state::().and_then(|graph| { - graph - .published - .iter() - .find(|(found, _)| *found == ptr) - .map(|(_, envelope)| *envelope) - }); - let Some(envelope) = envelope else { - return Err(host_fault("invalid private Lua root candidate")); - }; - heap::with_heap(host, |heap| heap.issued_value(envelope)) - .map_err(heap_error) - .map(Some) -} - #[derive(Clone, Copy, Debug)] pub(super) struct CaptureNote { pub envelope: heap::TableRef, @@ -1065,8 +1041,6 @@ pub(super) struct CaptureNote { } struct CaptureGraph { - cells: Vec<(heap::TableRef, heap::UpvalueRef)>, - published: Vec<(usize, heap::TableRef)>, notes: Vec, reads: u32, writes: u32, @@ -1078,8 +1052,6 @@ fn with_capture( ) -> Result { let graph = host .scope_state_or_insert_with(|| CaptureGraph { - cells: Vec::new(), - published: Vec::new(), notes: Vec::new(), reads: 0, writes: 0, @@ -1120,18 +1092,15 @@ fn open_cell(call: &mut OwnedHostCall<'_>) -> Result { }; let initial = issued_table(&mut call.vm().host_context(), &table)?; let before = root_count(&mut call.vm().host_context())?; - let issued = heap::with_heap(&mut call.vm().host_context(), |heap| { - let envelope = heap.alloc()?; - let carrier = heap.issue_carrier(envelope)?; + let carrier = heap::with_heap(&mut call.vm().host_context(), |heap| { + let anchor = heap.alloc()?; + let carrier = heap.issue_carrier(anchor)?; let cell = heap.alloc_upvalue()?; heap.write_upvalue(cell, initial)?; - Ok((carrier, envelope, cell)) + heap.set_cell_edge(anchor, cell)?; + Ok(carrier) }) .map_err(heap_error)?; - let (carrier, envelope, cell) = issued; - with_capture(&mut call.vm().host_context(), |graph| { - graph.cells.push((envelope, cell)); - })?; refuse_root_change( before, &mut call.vm().host_context(), @@ -1140,64 +1109,48 @@ fn open_cell(call: &mut OwnedHostCall<'_>) -> Result { Ok(carrier) } -fn cell_of( - host: &mut vm::HostContext<'_>, - envelope: heap::TableRef, -) -> Result { - with_capture(host, |graph| { - graph - .cells - .iter() - .find(|(found, _)| *found == envelope) - .map(|(_, cell)| *cell) - })? - .ok_or_else(|| host_fault("envelope has no shared cell")) -} - fn read_cell(call: &mut OwnedHostCall<'_>) -> Result { - let envelope = match call.args() { - [envelope] => envelope.clone(), - _ => return Err(host_fault("read_cell needs the captured envelope")), + let table = match call.args() { + [table] => table.clone(), + _ => return Err(host_fault("read_cell needs the cell table")), }; - let envelope = issued_table(&mut call.vm().host_context(), &envelope)?; - let cell = cell_of(&mut call.vm().host_context(), envelope)?; - let closure = heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.closure_edge(envelope, 1) - }) - .map_err(heap_error)?; - let same = heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.upvalue_of(closure) - }) - .map_err(heap_error)?; - if same != cell { - return Err(host_fault("closure edge does not share the opened cell")); - } + let table = issued_table(&mut call.vm().host_context(), &table)?; with_capture(&mut call.vm().host_context(), |graph| graph.reads += 1)?; - let table = heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.read_upvalue(closure) + let current = heap::with_heap(&mut call.vm().host_context(), |heap| { + let cell = heap.cell_edge(table)?; + heap.current_table(cell) }) .map_err(heap_error)?; - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.issued_value(table) - }) - .map_err(heap_error) + match current { + Some(table) => heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.issued_value(table) + }) + .map_err(heap_error), + None => Ok(Value::Null), + } } fn write_cell(call: &mut OwnedHostCall<'_>) -> Result { - let (envelope, next) = match call.args() { - [envelope, next] => (envelope.clone(), next.clone()), + let (table, next) = match call.args() { + [table, next] => (table.clone(), next.clone()), _ => { return Err(host_fault( - "write_cell needs the envelope and the next table", + "write_cell needs the cell table and the next value", )); } }; - let envelope = issued_table(&mut call.vm().host_context(), &envelope)?; - let next = issued_table(&mut call.vm().host_context(), &next)?; - let cell = cell_of(&mut call.vm().host_context(), envelope)?; + let table = issued_table(&mut call.vm().host_context(), &table)?; + let next_table = match &next { + Value::Null => None, + other => Some(issued_table(&mut call.vm().host_context(), other)?), + }; let before = root_count(&mut call.vm().host_context())?; heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.write_upvalue(cell, next) + let cell = heap.cell_edge(table)?; + match next_table { + None => heap.clear_upvalue(cell), + Some(next) => heap.write_upvalue(cell, next), + } }) .map_err(heap_error)?; with_capture(&mut call.vm().host_context(), |graph| graph.writes += 1)?; @@ -1210,11 +1163,11 @@ fn write_cell(call: &mut OwnedHostCall<'_>) -> Result { } fn track_closure(call: &mut OwnedHostCall<'_>) -> Result { - let (closure, envelope) = match call.args() { - [closure, envelope] => (closure.clone(), envelope.clone()), + let (closure, anchor, envelope) = match call.args() { + [closure, anchor, envelope] => (closure.clone(), anchor.clone(), envelope.clone()), _ => { return Err(host_fault( - "track_closure needs the callable and its envelope", + "track_closure needs the callable, its anchor, and its envelope", )); } }; @@ -1222,31 +1175,25 @@ fn track_closure(call: &mut OwnedHostCall<'_>) -> Result { return Err(host_fault("tracked closure is not a callable")); }; let ptr = std::sync::Arc::as_ptr(callable) as usize; + let anchor = issued_table(&mut call.vm().host_context(), &anchor)?; let envelope = issued_table(&mut call.vm().host_context(), &envelope)?; - let cell = cell_of(&mut call.vm().host_context(), envelope)?; let before = root_count(&mut call.vm().host_context())?; - let field = with_capture(&mut call.vm().host_context(), |graph| { - 1 + graph - .notes - .iter() - .filter(|note| note.envelope == envelope) - .count() as u32 - })?; - let node = heap::with_heap(&mut call.vm().host_context(), |heap| { + let note = heap::with_heap(&mut call.vm().host_context(), |heap| { + let cell = heap.cell_edge(anchor)?; let node = heap.alloc_closure()?; heap.set_upvalue_edge(node, cell)?; - heap.set_closure_edge(envelope, field, node)?; - Ok(node) - }) - .map_err(heap_error)?; - with_capture(&mut call.vm().host_context(), |graph| { - graph.published.push((ptr, envelope)); - graph.notes.push(CaptureNote { + heap.set_cell_edge(envelope, cell)?; + heap.set_closure_edge(envelope, 1, node)?; + Ok(CaptureNote { envelope, closure: node, cell, callable: ptr, - }); + }) + }) + .map_err(heap_error)?; + with_capture(&mut call.vm().host_context(), |graph| { + graph.notes.push(note); })?; refuse_root_change( before, @@ -1256,33 +1203,6 @@ fn track_closure(call: &mut OwnedHostCall<'_>) -> Result { Ok(Value::Float(0.0)) } -fn retire_closure(call: &mut OwnedHostCall<'_>) -> Result { - let closure = match call.args() { - [closure] => closure.clone(), - _ => return Err(host_fault("retire_closure needs the callable")), - }; - let Some(ptr) = callable_ptr(&closure) else { - return Ok(Value::Float(0.0)); - }; - let before = root_count(&mut call.vm().host_context())?; - let _ = with_capture(&mut call.vm().host_context(), |graph| { - graph.published.retain(|(found, _)| *found != ptr); - }); - refuse_root_change( - before, - &mut call.vm().host_context(), - "retire_closure published a heap root", - )?; - Ok(Value::Float(0.0)) -} - -fn callable_ptr(value: &Value) -> Option { - match value { - Value::Callable(callable) => Some(std::sync::Arc::as_ptr(callable) as usize), - _ => None, - } -} - pub(super) fn capture_notes(vm: &mut vm::Vm) -> Vec { vm.host_context() .scope_state::() @@ -1370,7 +1290,7 @@ pub(super) fn lower_returning( resolution: &resolution, binding_slots: vec![None; resolution.bindings.len()], capture_envelopes: HashMap::new(), - closure_slots: HashSet::new(), + shadows: HashMap::new(), }; if lower.receiver_width > 0 { let slot = lower.builder.alloc_local_named("#caller-frame")?; @@ -1529,7 +1449,8 @@ struct Lower<'a> { resolution: &'a resolve::Resolution, binding_slots: Vec>, capture_envelopes: HashMap, - closure_slots: HashSet, + /// Callable slot to the issued envelope that roots that callable's cell. + shadows: HashMap, } #[derive(Clone, Copy)] @@ -1855,6 +1776,12 @@ impl Lower<'_> { continue; }; self.live_locals.retain(|local| *local != slot); + if let Some(anchor) = self.capture_envelopes.remove(&index) { + self.live_locals.retain(|local| *local != anchor); + } + if let Some(shadow) = self.shadows.remove(&slot) { + self.live_locals.retain(|local| *local != shadow); + } self.release_receiver_root(span, slot)?; let name = self.resolution.bindings[index].name.clone(); if self.locals.get(&name).copied() == Some(slot) { @@ -1959,7 +1886,8 @@ impl Lower<'_> { .alloc_local_named(&format!("#{}", span.start))?; self.remember_binding(span, name, index)?; let nil_init = matches!(value, ast::Expr::Nil { .. }); - if !nil_init { + let shadowed = self.copy_shadow(span, index, value)?; + if !nil_init && !shadowed { self.live_locals.push(index); } self.stmts.push(Stmt::Let { @@ -2006,18 +1934,57 @@ impl Lower<'_> { if !self.binding_is_captured(binding) { return Ok(()); } - let envelope = self.builder.alloc_local_named("#envelope")?; + let anchor = self + .builder + .alloc_local_named(&format!("#cell:{binding}"))?; let expr = self.call(OPEN_CELL, vec![Expr::Var(slot)])?; self.stmts.push(Stmt::Let { - index: envelope, + index: anchor, declared_schema: None, expr, line: self.line(span), }); - self.capture_envelopes.insert(binding, envelope); + self.capture_envelopes.insert(binding, anchor); + self.live_locals.push(anchor); + self.live_locals.retain(|local| *local != slot); + self.stmts.push(Stmt::Assign { + kind: AssignmentKind::Set, + index: slot, + expr: Expr::Null, + line: self.line(span), + }); Ok(()) } + fn copy_shadow( + &mut self, + span: ast::Span, + dest: LocalSlot, + value: &ast::Expr, + ) -> Result { + let ast::Expr::Name { name, .. } = value else { + return Ok(false); + }; + let Some(source) = self.locals.get(&name.bytes).copied() else { + return Ok(false); + }; + let Some(shadow) = self.shadows.get(&source).copied() else { + return Ok(false); + }; + let copied = self + .builder + .alloc_local_named(&format!("#shadow:{dest:?}"))?; + self.stmts.push(Stmt::Let { + index: copied, + declared_schema: None, + expr: Expr::Var(shadow), + line: self.line(span), + }); + self.shadows.insert(dest, copied); + self.live_locals.push(copied); + Ok(true) + } + fn binding_is_captured(&self, binding: usize) -> bool { let owner = self.resolution.bindings[binding].function_id; self.resolution @@ -2058,7 +2025,7 @@ impl Lower<'_> { let [binding] = captures.as_slice() else { return Err(self.unsupported(func.span)); }; - let envelope = self + let anchor = self .capture_envelopes .get(binding) .copied() @@ -2068,27 +2035,55 @@ impl Lower<'_> { .get(&name.bytes) .copied() .ok_or_else(|| self.unsupported(span))?; - let captured = self.builder.alloc_local_named("#capture")?; + let shadow = self.fresh_shadow(span, slot)?; + let captured = self + .builder + .alloc_local_named(&format!("#capture:{}", func.span.start))?; let body = self.closure_body(func, *binding, captured)?; self.stmts.push(Stmt::Assign { kind: AssignmentKind::Set, index: slot, expr: Expr::Closure(vm::ClosureExpr { param_slots: Vec::new(), - capture_copies: vec![(envelope, captured)], + capture_copies: vec![(shadow, captured)], body: Box::new(body), }), line: self.line(span), }); - let track = self.call(TRACK_CLOSURE, vec![Expr::Var(slot), Expr::Var(envelope)])?; + let track = self.call( + TRACK_CLOSURE, + vec![Expr::Var(slot), Expr::Var(anchor), Expr::Var(shadow)], + )?; self.emit_ignored(track, self.line(span))?; - if !self.live_locals.contains(&slot) { - self.live_locals.push(slot); - } - self.closure_slots.insert(slot); + self.live_locals.retain(|local| *local != slot); Ok(()) } + fn fresh_shadow(&mut self, span: ast::Span, slot: LocalSlot) -> Result { + let fresh = self.call(NEW_TABLE, vec![])?; + if let Some(shadow) = self.shadows.get(&slot).copied() { + self.stmts.push(Stmt::Assign { + kind: AssignmentKind::Set, + index: shadow, + expr: fresh, + line: self.line(span), + }); + return Ok(shadow); + } + let shadow = self + .builder + .alloc_local_named(&format!("#shadow:{slot:?}"))?; + self.stmts.push(Stmt::Let { + index: shadow, + declared_schema: None, + expr: fresh, + line: self.line(span), + }); + self.shadows.insert(slot, shadow); + self.live_locals.push(shadow); + Ok(shadow) + } + fn closure_body( &mut self, func: &ast::FuncBody, @@ -2144,6 +2139,15 @@ impl Lower<'_> { .any(|use_site| use_site.span == name.span && use_site.binding == Some(binding)) } + fn anchor_of_name(&self, name: &ast::Name) -> Option { + let binding = self + .resolution + .uses + .iter() + .find_map(|use_site| (use_site.span == name.span).then_some(use_site.binding)?)?; + self.capture_envelopes.get(&binding).copied() + } + fn lower_assign( &mut self, span: ast::Span, @@ -2157,10 +2161,18 @@ impl Lower<'_> { .get(&name.bytes) .copied() .ok_or_else(|| self.unsupported(span))?; - if self.closure_slots.contains(&slot) { - let retire = self.call(RETIRE_CLOSURE, vec![Expr::Var(slot)])?; - self.emit_ignored(retire, self.line(span))?; - self.closure_slots.remove(&slot); + if let Some(anchor) = self.anchor_of_name(name) { + let cleared = self.call(WRITE_CELL, vec![Expr::Var(anchor), Expr::Null])?; + self.emit_ignored(cleared, self.line(span))?; + } + if let Some(shadow) = self.shadows.remove(&slot) { + self.live_locals.retain(|local| *local != shadow); + self.stmts.push(Stmt::Assign { + kind: AssignmentKind::Set, + index: shadow, + expr: Expr::Null, + line: self.line(span), + }); } self.stmts.push(Stmt::Assign { kind: AssignmentKind::Set, @@ -2173,6 +2185,26 @@ impl Lower<'_> { self.release_receiver_root(span, slot)?; Ok(()) } + (ast::AssignTarget::Name(name), ast::Expr::Table { fields, .. }) + if fields.is_empty() => + { + let anchor = self + .anchor_of_name(name) + .ok_or_else(|| self.unsupported(span))?; + let next = self.call(NEW_TABLE, vec![])?; + let written = self.call(WRITE_CELL, vec![Expr::Var(anchor), next])?; + self.emit_ignored(written, self.line(span))?; + if let Some(slot) = self.locals.get(&name.bytes).copied() { + self.live_locals.retain(|local| *local != slot); + self.stmts.push(Stmt::Assign { + kind: AssignmentKind::Set, + index: slot, + expr: Expr::Null, + line: self.line(span), + }); + } + Ok(()) + } ( ast::AssignTarget::Field { table, @@ -2589,12 +2621,16 @@ impl Lower<'_> { .parse() .map(Expr::Float) .map_err(|_| self.unsupported(expr.span())), - ast::Expr::Name { name, .. } => self - .locals - .get(&name.bytes) - .copied() - .map(Expr::Var) - .ok_or_else(|| self.unsupported(expr.span())), + ast::Expr::Name { name, .. } => { + if let Some(anchor) = self.anchor_of_name(name) { + return self.call(READ_CELL, vec![Expr::Var(anchor)]); + } + self.locals + .get(&name.bytes) + .copied() + .map(Expr::Var) + .ok_or_else(|| self.unsupported(expr.span())) + } ast::Expr::Nil { .. } => Ok(Expr::Null), ast::Expr::Paren { inner, .. } => self.expr(inner), ast::Expr::BinaryChain { span, base, steps } => { diff --git a/tests/luajit_heap_runtime/source_closure.rs b/tests/luajit_heap_runtime/source_closure.rs index af1045e..6f4d81f 100644 --- a/tests/luajit_heap_runtime/source_closure.rs +++ b/tests/luajit_heap_runtime/source_closure.rs @@ -21,6 +21,8 @@ use super::heap::{self, TableRef}; const OBSERVE: &str = "lua_host::observe_table"; const NOTE_FN: &str = "lua_host::note_fn"; const NOTE_PHASE: &str = "lua_host::note_phase"; +const NOTE_NIL: &str = "lua_host::note_nil"; +const NOTE_GRAPH: &str = "lua_host::note_graph"; const SOURCE: &str = r#" local mt = {} @@ -77,16 +79,30 @@ struct Phase { orphan_alive: bool, } +/// Read-only closure and cell snapshot. Not a root and not a publication. +#[derive(Clone, Debug)] +struct GraphNote { + id: u32, + closure_alive: Vec, + cell_alive: Vec, + /// `true` when that note's closure can still read a table from its cell. + cell_has_table: Vec, +} + #[derive(Clone, Debug, Default)] struct Obs { tables: Vec<(u32, TableRef)>, callables: Vec, phases: Vec, + nils: Vec, + graphs: Vec, } struct ObserveTable; struct NoteFn; struct NotePhase; +struct NoteNil; +struct NoteGraph; fn catalog() -> &'static Arc { static CATALOG: OnceLock> = OnceLock::new(); @@ -115,6 +131,16 @@ fn catalog() -> &'static Arc { ], HostTypeSchema::Float, )); + builder.function(HostFunctionSchema::with_return( + NOTE_NIL, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::Float, + )); + builder.function(HostFunctionSchema::with_return( + NOTE_GRAPH, + vec![HostParamSchema::value("id", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); Arc::new(builder.build().expect("shared-closure catalog")) }) } @@ -140,7 +166,7 @@ impl SourcePlugin for Plugin { } fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { - for name in [OBSERVE, NOTE_FN, NOTE_PHASE] { + for name in [OBSERVE, NOTE_FN, NOTE_PHASE, NOTE_NIL, NOTE_GRAPH] { let function = catalog.function(name).expect("observer schema"); registry .register_exact_owned( @@ -158,6 +184,8 @@ fn ctor_box(name: &str) -> Box { OBSERVE => Box::new(ObserveTable), NOTE_FN => Box::new(NoteFn), NOTE_PHASE => Box::new(NotePhase), + NOTE_NIL => Box::new(NoteNil), + NOTE_GRAPH => Box::new(NoteGraph), _ => unreachable!("observer name"), } } @@ -277,6 +305,67 @@ impl HostOwnedFunction for NotePhase { } } +impl HostOwnedFunction for NoteNil { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let is_nil = matches!(call.args(), [Value::Null]); + let before = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + obs(&mut call.vm().host_context())?.nils.push(is_nil); + let after = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + if after.live_roots != before.live_roots || after.collections != before.collections { + return Err(host_fault("note_nil rooted or collected")); + } + Ok(CallOutcome::Return(CallReturn::one(Value::Float(0.0)))) + } +} + +impl HostOwnedFunction for NoteGraph { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let id = tag_of(call, 0)?; + let before = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + let notes = candidate::capture_notes(call.vm()); + let (closure_alive, cell_alive, cell_has_table) = { + let mut host = call.vm().host_context(); + heap::with_heap(&mut host, |heap| { + let mut closures = Vec::with_capacity(notes.len()); + let mut cells = Vec::with_capacity(notes.len()); + let mut values = Vec::with_capacity(notes.len()); + for note in ¬es { + let closure_live = heap.closure_alive(note.closure); + let cell_live = heap.upvalue_alive(note.cell); + let has_table = if closure_live { + matches!( + heap.read_cell(note.closure)?, + Some(heap::CellValue::Table(_)) + ) + } else { + false + }; + closures.push(closure_live); + cells.push(cell_live); + values.push(has_table); + } + Ok((closures, cells, values)) + }) + .map_err(|error| host_fault(&error.to_string()))? + }; + obs(&mut call.vm().host_context())?.graphs.push(GraphNote { + id, + closure_alive, + cell_alive, + cell_has_table, + }); + let after = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + if after.live_roots != before.live_roots || after.collections != before.collections { + return Err(host_fault("note_graph rooted or collected")); + } + Ok(CallOutcome::Return(CallReturn::one(Value::Float(0.0)))) + } +} + struct Arm { vm: vm::Vm, notes: Vec, @@ -396,13 +485,13 @@ fn assert_shared_calls(arm: &Arm) { arm.call_values, 3, "getter twice and setter once must be CallValue" ); - assert_eq!(arm.reads, 2, "the source getter ran twice"); + assert_eq!(arm.reads, 4, "two outer reads and two getter calls"); assert_eq!(arm.writes, 1, "the source setter wrote the cell"); assert_eq!(arm.notes.len(), 2, "two source closures"); assert_eq!(arm.notes[0].cell, arm.notes[1].cell, "one shared cell"); - assert_eq!( + assert_ne!( arm.notes[0].envelope, arm.notes[1].envelope, - "one captured envelope" + "each closure has its own envelope" ); assert_eq!( arm.obs.callables, @@ -480,3 +569,369 @@ fn source_closures_share_one_cell_across_block_exit_and_collect() { ); assert!(!alive(&mut keep_graph.vm, tagged(&keep_graph.obs, 1))); } + +fn run_chunk(source: &str) -> Arm { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .unwrap_or_else(|error| panic!("lower/compile rejected the source: {error}")); + let mut vm = prepared.into_vm().expect("create VM"); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind runtime"); + let (call_values, call_scripts) = opcode_counts(vm.program()); + assert_eq!( + vm.run().expect("vm rejected the chunk"), + VmStatus::Halted, + "chunk did not halt" + ); + let notes = candidate::capture_notes(&mut vm); + let (reads, writes) = candidate::capture_counts(&mut vm); + let obs = vm + .host_context() + .scope_state::() + .cloned() + .unwrap_or_default(); + Arm { + vm, + notes, + reads, + writes, + obs, + call_values, + call_scripts, + } +} + +fn graph(obs: &Obs, id: u32) -> GraphNote { + obs.graphs + .iter() + .find(|note| note.id == id) + .cloned() + .unwrap_or_else(|| panic!("missing graph {id}")) +} + +fn assert_call_value(arm: &Arm) { + assert_eq!( + arm.call_scripts, 0, + "CallScript must not implement the call" + ); + assert!(arm.call_values > 0, "missing CallValue"); +} + +const WEAK_HEAD: &str = "\ +local mt = {}\n\ +mt.__mode = \"v\"\n\ +local weak = {}\n\ +setmetatable(weak, mt)\n\ +observe_table(weak, 0)\n"; + +#[test] +fn outer_read_sees_the_table_written_by_the_closure() { + let source = format!( + "{WEAK_HEAD}\ +do\n\ + local held = {{}}\n\ + observe_table(held, 1)\n\ + local get = nil\n\ + local set = nil\n\ + get = function()\n\ + return held\n\ + end\n\ + set = function()\n\ + held = {{}}\n\ + end\n\ + set()\n\ + local seen = held\n\ + observe_table(seen, 2)\n\ + local again = get()\n\ + observe_table(again, 3)\n\ +end\n" + ); + let arm = run_chunk(&source); + assert_call_value(&arm); + assert_eq!(arm.notes.len(), 2, "getter and setter"); + assert_eq!(arm.notes[0].cell, arm.notes[1].cell, "one shared cell"); + assert_ne!( + tagged(&arm.obs, 1), + tagged(&arm.obs, 2), + "outer read after set() still saw the original slot" + ); + assert_eq!( + tagged(&arm.obs, 2), + tagged(&arm.obs, 3), + "getter and outer read diverged" + ); +} + +#[test] +fn replaced_table_leaves_the_shared_cell_and_can_be_collected() { + let source = format!( + "{WEAK_HEAD}\ +do\n\ + local held = {{}}\n\ + weak.old = held\n\ + observe_table(held, 1)\n\ + local set = nil\n\ + set = function()\n\ + held = {{}}\n\ + end\n\ + set()\n\ + local orphan = {{}}\n\ + weak.orphan = orphan\n\ + orphan = nil\n\ + collectgarbage(\"collect\")\n\ + note_phase(weak, 1)\n\ +end\n" + ); + let arm = run_chunk(&source); + assert_call_value(&arm); + let swept = phase(&arm.obs, 1); + assert!(!swept.orphan && !swept.orphan_alive, "collect did not run"); + assert!( + !swept.old && !swept.held_alive, + "old table stayed reachable after set() replaced the cell" + ); +} + +#[test] +fn outer_nil_clears_the_shared_cell_seen_by_the_getter() { + let source = "\ +do\n\ + local held = {}\n\ + observe_table(held, 1)\n\ + local get = nil\n\ + get = function()\n\ + return held\n\ + end\n\ + held = nil\n\ + local gone = get()\n\ + note_nil(gone)\n\ + note_graph(1)\n\ +end\n"; + let arm = run_chunk(source); + assert_call_value(&arm); + assert_eq!(arm.obs.nils.first().copied(), Some(true)); + let snap = graph(&arm.obs, 1); + assert!( + snap.closure_alive.first().copied().unwrap_or(false), + "getter closure was collected while it was still callable" + ); + assert!( + !snap.cell_has_table.first().copied().unwrap_or(true), + "getter still read a table after the outer nil write" + ); +} + +#[test] +fn outer_table_write_uses_the_same_binding_cell() { + let source = "\ +do\n\ + local held = {}\n\ + observe_table(held, 1)\n\ + local get = nil\n\ + get = function()\n\ + return held\n\ + end\n\ + held = {}\n\ + local seen = held\n\ + observe_table(seen, 2)\n\ + local got = get()\n\ + observe_table(got, 3)\n\ +end\n"; + let arm = run_chunk(source); + assert_call_value(&arm); + assert_eq!(arm.notes.len(), 1); + assert_ne!(tagged(&arm.obs, 1), tagged(&arm.obs, 2)); + assert_eq!(tagged(&arm.obs, 2), tagged(&arm.obs, 3)); +} + +#[test] +fn alias_calls_the_original_closure_after_nil_slot_and_collect() { + let source = format!( + "{WEAK_HEAD}\ +do\n\ + local held = {{}}\n\ + observe_table(held, 1)\n\ + local get = nil\n\ + get = function()\n\ + return held\n\ + end\n\ + note_fn(get)\n\ + local alias = get\n\ + note_fn(alias)\n\ + get = nil\n\ + local orphan = {{}}\n\ + weak.orphan = orphan\n\ + orphan = nil\n\ + collectgarbage(\"collect\")\n\ + note_phase(weak, 1)\n\ + local seen = alias()\n\ + observe_table(seen, 2)\n\ + note_graph(1)\n\ +end\n" + ); + let mut arm = run_chunk(&source); + assert_call_value(&arm); + assert_eq!(arm.obs.callables.len(), 2); + assert_eq!( + arm.obs.callables[0], arm.obs.callables[1], + "alias was not the original callable" + ); + let swept = phase(&arm.obs, 1); + assert!(!swept.orphan && !swept.orphan_alive, "collect did not run"); + assert_eq!( + tagged(&arm.obs, 1), + tagged(&arm.obs, 2), + "alias() did not return the original table" + ); + let snap = graph(&arm.obs, 1); + assert!( + snap.closure_alive.first().copied().unwrap_or(false), + "nil on the original slot collected the aliased closure" + ); + assert!(alive(&mut arm.vm, tagged(&arm.obs, 1))); +} + +#[test] +fn overwrite_sweeps_the_old_callable_while_its_sibling_keeps_the_cell() { + let source = format!( + "{WEAK_HEAD}\ +do\n\ + local held = {{}}\n\ + local get = nil\n\ + local set = nil\n\ + get = function()\n\ + return held\n\ + end\n\ + set = function()\n\ + held = {{}}\n\ + end\n\ + note_fn(get)\n\ + note_fn(set)\n\ + get = function()\n\ + return held\n\ + end\n\ + note_fn(get)\n\ + local orphan = {{}}\n\ + weak.orphan = orphan\n\ + orphan = nil\n\ + collectgarbage(\"collect\")\n\ + note_graph(1)\n\ +end\n" + ); + let arm = run_chunk(&source); + assert_eq!(arm.notes.len(), 3, "old getter, setter, replacement getter"); + assert_eq!(arm.notes[0].cell, arm.notes[1].cell); + assert_eq!(arm.notes[1].cell, arm.notes[2].cell); + let snap = graph(&arm.obs, 1); + assert_eq!(snap.closure_alive.len(), 3); + assert!( + !snap.closure_alive[0], + "overwrite left the old getter reachable through the sibling envelope" + ); + assert!(snap.closure_alive[1], "sibling setter was collected"); + assert!(snap.closure_alive[2], "replacement getter was collected"); + assert!(snap.cell_alive[1], "sibling lost the shared cell"); +} + +#[test] +fn block_exit_sweeps_a_closure_that_has_no_remaining_root() { + let source = format!( + "{WEAK_HEAD}\ +do\n\ + local held = {{}}\n\ + local get = nil\n\ + get = function()\n\ + return held\n\ + end\n\ + note_fn(get)\n\ +end\n\ +local orphan = {{}}\n\ +weak.orphan = orphan\n\ +orphan = nil\n\ +collectgarbage(\"collect\")\n\ +note_phase(weak, 1)\n\ +note_graph(1)\n" + ); + let arm = run_chunk(&source); + let swept = phase(&arm.obs, 1); + assert!(!swept.orphan && !swept.orphan_alive, "collect did not run"); + let snap = graph(&arm.obs, 1); + assert!( + snap.closure_alive.first().copied() == Some(false), + "block exit left the closure rooted" + ); + assert!( + snap.cell_alive.first().copied() == Some(false), + "block exit left the cell rooted" + ); +} + +#[test] +fn open_binding_keeps_the_cell_after_every_callable_is_cleared() { + let source = format!( + "{WEAK_HEAD}\ +do\n\ + local held = {{}}\n\ + weak.old = held\n\ + observe_table(held, 1)\n\ + local get = nil\n\ + local set = nil\n\ + get = function()\n\ + return held\n\ + end\n\ + set = function()\n\ + held = {{}}\n\ + end\n\ + set()\n\ + get = nil\n\ + set = nil\n\ + local seen = held\n\ + observe_table(seen, 3)\n\ + weak.next = seen\n\ + local orphan = {{}}\n\ + observe_table(orphan, 2)\n\ + weak.orphan = orphan\n\ + orphan = nil\n\ + collectgarbage(\"collect\")\n\ + note_phase(weak, 1)\n\ + note_graph(1)\n\ +end\n\ +collectgarbage(\"collect\")\n\ +note_phase(weak, 2)\n\ +note_graph(2)\n" + ); + let mut arm = run_chunk(&source); + assert_call_value(&arm); + assert_ne!( + tagged(&arm.obs, 1), + tagged(&arm.obs, 3), + "outer read after set() did not see the cell" + ); + let inside = phase(&arm.obs, 1); + assert!( + !inside.orphan && !inside.orphan_alive, + "collect did not run" + ); + assert!( + !inside.old && !inside.held_alive, + "original table stayed rooted after the cell moved on" + ); + assert!(inside.next, "binding dropped the replacement table"); + let snap = graph(&arm.obs, 1); + assert!( + snap.closure_alive.iter().all(|alive| !alive), + "withdrawn callables stayed rooted" + ); + assert!( + snap.cell_alive.iter().any(|alive| *alive), + "open binding did not root the cell after every callable left" + ); + let after = phase(&arm.obs, 2); + assert!(!after.next, "block exit left the replacement table rooted"); + assert!(!alive(&mut arm.vm, tagged(&arm.obs, 3))); +} From 20a5be21cc797f8874c2d8afc894a298c9a92d6b Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 21:25:57 +0800 Subject: [PATCH 070/225] fix(lua): reject closure writes to shared upvalue cells --- tests/luajit_heap_runtime/candidate.rs | 4 ++ tests/luajit_heap_runtime/source_closure.rs | 46 +++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 7a9283d..afd0eff 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -2018,6 +2018,10 @@ impl Lower<'_> { name: &ast::Name, func: &ast::FuncBody, ) -> Result<(), ParseError> { + // Reads of this binding use the shared cell, which cannot hold a callable. + if self.anchor_of_name(name).is_some() { + return Err(self.unsupported(span)); + } if !func.params.is_empty() || func.vararg || func.self_param { return Err(self.unsupported(func.span)); } diff --git a/tests/luajit_heap_runtime/source_closure.rs b/tests/luajit_heap_runtime/source_closure.rs index 6f4d81f..f7f5f09 100644 --- a/tests/luajit_heap_runtime/source_closure.rs +++ b/tests/luajit_heap_runtime/source_closure.rs @@ -622,6 +622,52 @@ fn assert_call_value(arm: &Arm) { assert!(arm.call_values > 0, "missing CallValue"); } +fn assert_shared_upvalue_closure_assignment_unsupported(source: &str, line: usize) { + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(Arc::clone(catalog())); + let error = match vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + { + Ok(_) => { + panic!("candidate accepted a closure assignment to a shared upvalue at line {line}") + } + Err(vm::SourcePathError::SourceWithMap { + error: vm::SourceError::Parse(error), + .. + }) => error, + Err(other) => panic!("expected a candidate lowering diagnostic, got {other}"), + }; + assert_eq!(error.line, line, "{error}"); + assert!(error.message.contains("not lowered yet"), "{error}"); +} + +#[test] +fn shared_upvalue_closure_assignment_rejects_self_capture() { + let source = r#"do + local a = {} + a = function() return a end + local x = a + note_fn(x) +end +"#; + assert_shared_upvalue_closure_assignment_unsupported(source, 3); +} + +#[test] +fn shared_upvalue_closure_assignment_rejects_target_captured_by_another_closure() { + let source = r#"do + local a = {} + local held = {} + local get = nil + get = function() return a end + a = function() return held end + local x = a + note_fn(x) +end +"#; + assert_shared_upvalue_closure_assignment_unsupported(source, 6); +} + const WEAK_HEAD: &str = "\ local mt = {}\n\ mt.__mode = \"v\"\n\ From 0850c4ea6c0810c1c104b559abf33adb916d1994 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 20:21:09 +0800 Subject: [PATCH 071/225] feat(lua): walk surviving weak-table entries with next Source next walks the same edge vector weak sweep retains. A live entry returns the key and value through the existing array transport; the end returns one nil. A missing or non-guest cursor is an error, not a silent end. --- src/frontends/lua/heap/table.rs | 139 +++++++++ tests/luajit_heap_runtime/candidate.rs | 270 ++++++++++++++++++ .../value_boundary_tests.rs | 244 ++++++++++++++++ 3 files changed, 653 insertions(+) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index c94ada0..71c9194 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -78,6 +78,10 @@ pub enum HeapError { CarrierOutOfRange, /// A NaN is not a table key. LuaJIT reports this on write; a read is nil. NanIndex, + /// `next` was given a key that is not stored. This is not the end. + NextCursorMissing, + /// A cursor or stored entry has no guest key. This is not the end. + NextUnsupported, /// This scope already has a heap. AlreadyInstalled, /// Execution-scope or resource-table failure. `publish` rolls the reserved @@ -105,6 +109,8 @@ impl fmt::Display for HeapError { Self::StaleFrame => write!(formatter, "stale lua root frame"), Self::CarrierOutOfRange => write!(formatter, "lua resource carrier out of range"), Self::NanIndex => write!(formatter, "table index is NaN"), + Self::NextCursorMissing => write!(formatter, "invalid key to next"), + Self::NextUnsupported => write!(formatter, "next key is not a guest key"), Self::AlreadyInstalled => write!(formatter, "lua heap already installed"), Self::Scope(message) => write!(formatter, "lua heap scope error: {message}"), } @@ -332,6 +338,40 @@ impl EdgeKey { } } +/// Cursor for [`LuaHeap::next_guest`]. `None` at the call site means start. +enum NextCursor<'a> { + Name(&'a str), + Number(u64), + Object { + slot: u32, + generation: u32, + kind: HandleKind, + }, +} + +impl NextCursor<'_> { + fn matches(&self, key: &EdgeKey) -> bool { + match self { + Self::Name(name) => key.matches_name(name), + Self::Number(bits) => matches!(key, EdgeKey::Number(stored) if stored == bits), + Self::Object { + slot, + generation, + kind, + } => matches!( + key, + EdgeKey::Object { + slot: stored_slot, + generation: stored_generation, + kind: stored_kind, + } if stored_slot == slot + && stored_generation == generation + && stored_kind == kind + ), + } + } +} + struct Frame { index: u32, generation: u32, @@ -1190,6 +1230,105 @@ impl LuaHeap { self.stored_value(from, |stored| stored.matches_name(name)) } + /// Next raw entry of `table` after `cursor`, in stored edge order. + /// + /// `Value::Null` starts at the first edge. `None` is the end: one nil, not + /// an empty pair. A missing cursor and a non-guest key are errors, not the + /// end and not a restart. This walks `edges`, the same vector weak sweep + /// retains. It does not allocate another table and does not read a + /// metamethod. + pub fn next_guest( + &self, + table: TableRef, + cursor: &Value, + ) -> Result, HeapError> { + self.require_live(table)?; + let slot = table.slot(); + match cursor { + Value::Null => self.next_after(slot, None), + Value::Bool(_) => Err(HeapError::NextUnsupported), + Value::String(name) => self.next_after(slot, Some(NextCursor::Name(name.as_str()))), + Value::Float(number) => { + if number.is_nan() { + return Err(HeapError::NanIndex); + } + let bits = if *number == 0.0 { 0 } else { number.to_bits() }; + self.next_after(slot, Some(NextCursor::Number(bits))) + } + other => match self.guest_class(other) { + GuestClass::Table(key) => { + self.require_live(key)?; + self.next_after( + slot, + Some(NextCursor::Object { + slot: key.slot(), + generation: key.generation(), + kind: key.kind(), + }), + ) + } + _ => Err(HeapError::NextUnsupported), + }, + } + } + + fn next_after( + &self, + slot: u32, + cursor: Option>, + ) -> Result, HeapError> { + let mut passed = cursor.is_none(); + for edge in &self.edges { + if edge.from != slot { + continue; + } + if !passed { + if cursor + .as_ref() + .is_some_and(|cursor| cursor.matches(&edge.key)) + { + passed = true; + } + continue; + } + return Ok(Some(( + self.guest_key(&edge.key)?, + self.guest_edge_value(&edge.value)?, + ))); + } + if !passed { + return Err(HeapError::NextCursorMissing); + } + Ok(None) + } + + fn guest_key(&self, key: &EdgeKey) -> Result { + match key { + EdgeKey::Field(field) if *field == Self::MODE_FIELD => Ok(Value::string("__mode")), + EdgeKey::Field(_) => Err(HeapError::NextUnsupported), + EdgeKey::Utf8(text) => Ok(Value::string(text)), + EdgeKey::Number(bits) => Ok(Value::Float(f64::from_bits(*bits))), + EdgeKey::Object { + slot, + generation, + kind: HandleKind::Table, + } => self.issued_value(TableRef::table(self.domain, *slot, *generation)), + EdgeKey::Object { .. } => Err(HeapError::NextUnsupported), + } + } + + fn guest_edge_value(&self, value: &EdgeValue) -> Result { + match value { + EdgeValue::Scalar(value) => Ok(value.clone()), + EdgeValue::Table { slot, generation } => { + self.issued_value(TableRef::table(self.domain, *slot, *generation)) + } + EdgeValue::Closure { .. } | EdgeValue::Upvalue { .. } => { + Err(HeapError::NextUnsupported) + } + } + } + /// Reads an object-key edge. The key generation must still be that live slot. pub fn object_edge( &self, diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index afd0eff..75d4c5f 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -32,6 +32,8 @@ const ENTER_CALLEE: &str = "lua_internal::enter_callee_frame"; const ROOT_ISSUED: &str = "lua_internal::root_issued"; const SET_EDGE: &str = "lua_internal::set_edge"; const GET_EDGE: &str = "lua_internal::get_edge"; +const NEXT: &str = "lua_internal::next"; +const NOTE_NEXT_COUNT: &str = "lua_internal::note_next_count"; const SET_METATABLE: &str = "lua_internal::set_metatable"; const GET_METATABLE: &str = "lua_internal::get_metatable"; pub(super) const FINISH_RETURN: &str = "lua_internal::finish_return"; @@ -48,6 +50,22 @@ const RELEASE_RESULT: &str = "lua_internal::release_result"; const COPY_FIELDS: &str = "lua_internal::copy_fields"; const EXTERNAL_SHAPE: &str = "lua_internal::external_shape"; +/// Lengths the IR consumer read from `next`'s return transport with Core `len`. +/// +/// Source has no `select`. These lengths are not a source multi-return count +/// and are not the host array length recorded by `next` itself. +#[derive(Clone, Debug, Default)] +pub(super) struct NextCounts { + pub consumed: Vec, +} + +pub(super) fn next_counts(vm: &mut vm::Vm) -> Vec { + vm.host_context() + .scope_state::() + .map(|counts| counts.consumed.clone()) + .unwrap_or_default() +} + pub(super) fn install_schemas(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( GATHER_ROOT, @@ -115,6 +133,8 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { ), (SET_EDGE, vec!["from", "key", "to"], HostTypeSchema::Float), (GET_EDGE, vec!["table", "key"], HostTypeSchema::Unknown), + (NEXT, vec!["table", "cursor"], HostTypeSchema::Unknown), + (NOTE_NEXT_COUNT, vec!["count"], HostTypeSchema::Float), ( SET_METATABLE, vec!["owner", "metatable"], @@ -169,6 +189,8 @@ pub(super) fn register( Op::RootIssued, Op::SetEdge, Op::GetEdge, + Op::Next, + Op::NoteNextCount, Op::SetMetatable, Op::GetMetatable, Op::FinishReturn, @@ -198,6 +220,8 @@ pub(super) fn register( Op::RootIssued => ROOT_ISSUED, Op::SetEdge => SET_EDGE, Op::GetEdge => GET_EDGE, + Op::Next => NEXT, + Op::NoteNextCount => NOTE_NEXT_COUNT, Op::SetMetatable => SET_METATABLE, Op::GetMetatable => GET_METATABLE, Op::FinishReturn => FINISH_RETURN, @@ -237,6 +261,8 @@ enum Op { RootIssued, SetEdge, GetEdge, + Next, + NoteNextCount, SetMetatable, GetMetatable, FinishReturn, @@ -424,6 +450,8 @@ impl HostOwnedFunction for Op { Self::RootIssued => root_issued(call)?, Self::SetEdge => set_edge(call)?, Self::GetEdge => get_edge(call)?, + Self::Next => next_entry(call)?, + Self::NoteNextCount => note_next_count(call)?, Self::SetMetatable => set_metatable(call)?, Self::GetMetatable => get_metatable(call)?, Self::FinishReturn => finish_return(call)?, @@ -909,6 +937,45 @@ fn get_edge(call: &mut OwnedHostCall<'_>) -> Result { heap::with_heap(&mut host, |heap| heap.object_value(table, key)).map_err(heap_error) } +fn next_entry(call: &mut OwnedHostCall<'_>) -> Result { + let (table_value, cursor) = match call.args() { + [table, cursor] => (table.clone(), cursor.clone()), + _ => return Err(host_fault("invalid next")), + }; + let table = match classify(&mut call.vm().host_context(), &table_value)? { + heap::GuestClass::Table(table) => table, + _ => return Err(host_fault("next target is not a table")), + }; + let step = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.next_guest(table, &cursor) + }) + .map_err(heap_error)?; + // The array is the same unissued return transport a multi-local already + // consumes with Get. It is not a second protocol and not a Lua table. + // End is one nil. An entry is the key and the value. + let values = match step { + None => vec![Value::Null], + Some((key, value)) => vec![key, value], + }; + Ok(Value::array(values)) +} + +fn note_next_count(call: &mut OwnedHostCall<'_>) -> Result { + let count = match call.args() { + [Value::Int(count)] => { + u32::try_from(*count).map_err(|_| host_fault("next result count"))? + } + _ => return Err(host_fault("next result count")), + }; + call.vm() + .host_context() + .scope_state_or_insert_with(NextCounts::default) + .map_err(|error| VmError::HostError(error.to_string()))? + .consumed + .push(count); + Ok(Value::Float(0.0)) +} + fn set_metatable(call: &mut OwnedHostCall<'_>) -> Result { let (owner, mt) = match call.args() { [owner, mt] => (owner.clone(), mt.clone()), @@ -1475,6 +1542,13 @@ impl Lower<'_> { { self.lower_call_local(*span, names, &values.exprs[0]) } + ast::Stmt::Local { + span, + names, + values, + } if values.exprs.len() == 1 && self.is_next_call(&values.exprs[0]) => { + self.lower_next_local(*span, names, &values.exprs[0]) + } ast::Stmt::Local { span, names, @@ -1874,6 +1948,199 @@ impl Lower<'_> { .ok_or_else(|| self.unsupported(span)) } + fn is_next_call(&self, expr: &ast::Expr) -> bool { + let ast::Expr::SuffixChain { base, steps, .. } = expr else { + return false; + }; + let ast::Expr::Name { name, .. } = base.as_ref() else { + return false; + }; + if !name.is("next") || self.functions.contains_key(&name.bytes) { + return false; + } + matches!( + steps.as_slice(), + [ast::Suffix::Call { + args: ast::Args::List(_), + nav: false, + .. + }] + ) + } + + /// `local k, v = next(...)` binds through the existing array transport. + /// + /// Chunk `return next(...)` stays one value: the chunk return path only + /// carries a scalar. A single-value expression uses the first result. + fn lower_next_local( + &mut self, + span: ast::Span, + names: &[ast::LocalName], + call: &ast::Expr, + ) -> Result<(), ParseError> { + let line = self.line(span); + let transport = self.next_transport(call, span)?; + let mut slots = Vec::with_capacity(names.len()); + for (offset, name) in names.iter().enumerate() { + let index = self + .builder + .alloc_local_named(&format!("#{offset}:{}", span.start))?; + self.remember_binding(span, &name.name, index)?; + self.live_locals.push(index); + slots.push(index); + } + self.bind_transport(transport, &slots, line) + } + + fn next_expr(&mut self, args: &ast::ExprList, span: ast::Span) -> Result { + let transport = self.next_transport_exprs(&args.exprs, span)?; + let get = vm::BuiltinFunction::Get.call_index(); + Ok(Expr::Call( + get, + vec![], + vec![Expr::Var(transport), Expr::Int(0)], + None, + None, + )) + } + + fn next_transport( + &mut self, + call: &ast::Expr, + span: ast::Span, + ) -> Result { + let ast::Expr::SuffixChain { steps, .. } = call else { + return Err(self.unsupported(span)); + }; + let [ + ast::Suffix::Call { + args: ast::Args::List(list), + .. + }, + ] = steps.as_slice() + else { + return Err(self.unsupported(span)); + }; + self.next_transport_exprs(&list.exprs, span) + } + + fn next_transport_exprs( + &mut self, + args: &[ast::Expr], + span: ast::Span, + ) -> Result { + let (table, cursor) = match args { + [table] => (table, None), + [table, cursor] => (table, Some(cursor)), + _ => return Err(self.unsupported(span)), + }; + let table = self.expr(table)?; + let table = self.operand_slot(table, span)?; + let cursor = match cursor { + Some(ast::Expr::Nil { .. }) => Expr::Null, + Some(cursor) => self.expr(cursor)?, + None => Expr::Null, + }; + let cursor = self.operand_slot(cursor, span)?; + let line = self.line(span); + let transport = self + .builder + .alloc_local_named(&format!("#next:{}", span.start))?; + let call = self.call(NEXT, vec![Expr::Var(table), Expr::Var(cursor)])?; + self.stmts.push(Stmt::Let { + index: transport, + declared_schema: None, + expr: call, + line, + }); + self.note_next_len(transport, line)?; + Ok(transport) + } + + /// Records Core `len` of the return transport. `next` itself does not + /// write this count. + fn note_next_len(&mut self, transport: LocalSlot, line: u32) -> Result<(), ParseError> { + let len = vm::BuiltinFunction::Len.call_index(); + let count = self + .builder + .alloc_local_named(&format!("#next-len:{line}"))?; + self.stmts.push(Stmt::Let { + index: count, + declared_schema: None, + expr: Expr::Call(len, vec![], vec![Expr::Var(transport)], None, None), + line, + }); + let note = self.call(NOTE_NEXT_COUNT, vec![Expr::Var(count)])?; + self.emit_ignored(note, line) + } + + fn bind_transport( + &mut self, + transport: LocalSlot, + slots: &[LocalSlot], + line: u32, + ) -> Result<(), ParseError> { + let has = vm::BuiltinFunction::Has.call_index(); + let get = vm::BuiltinFunction::Get.call_index(); + for (index, slot) in slots.iter().enumerate() { + self.stmts.push(Stmt::Let { + index: *slot, + declared_schema: None, + expr: Expr::Null, + line, + }); + let present = self + .builder + .alloc_local_named(&format!("#next-has:{line}:{index}"))?; + self.stmts.push(Stmt::Let { + index: present, + declared_schema: None, + expr: Expr::Call( + has, + vec![], + vec![Expr::Var(transport), Expr::Int(index as i64)], + None, + None, + ), + line, + }); + self.stmts.push(Stmt::IfElse { + condition: Expr::Var(present), + then_branch: vec![Stmt::Assign { + kind: AssignmentKind::Set, + index: *slot, + expr: Expr::Call( + get, + vec![], + vec![Expr::Var(transport), Expr::Int(index as i64)], + None, + None, + ), + line, + }], + else_branch: vec![], + line, + }); + } + Ok(()) + } + + fn operand_slot(&mut self, expr: Expr, span: ast::Span) -> Result { + if let Expr::Var(slot) = expr { + return Ok(slot); + } + let slot = self + .builder + .alloc_local_named(&format!("#next-arg:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr, + line: self.line(span), + }); + Ok(slot) + } + fn lower_local( &mut self, span: ast::Span, @@ -2752,6 +3019,9 @@ impl Lower<'_> { let owner = self.expr(owner)?; return self.call(GET_METATABLE, vec![owner]); } + if name.is("next") && !self.functions.contains_key(&name.bytes) { + return self.next_expr(args, expr.span()); + } if name.is("rawget") { // Exact two arguments. Same GET_EDGE path as t[k]. No metamethod. let [table, key] = args.exprs.as_slice() else { diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 0043a95..bbb106f 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -4526,3 +4526,247 @@ return type(weak.a) assert_eq!(stats.last_marked, 5); assert_eq!(host.resource_count(), 5); } + +/// Source bindings are the locals and `return type(...)`. `next_counts` is the +/// IR consumer's Core `len` of the existing return transport. Source has no +/// `select`, so that vector is not a source multi-return count. +#[test] +fn lua_candidate_next_and_rawget_agree_after_weak_collect() { + let prefix = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local key = {} +local cycle = {} +cycle.self = cycle +local rooted = {} +owner[key] = cycle +owner[1] = rooted +observe_table(key, 0) +observe_table(cycle, 0) +observe_table(rooted, 0) +local k1, v1 = next(owner, nil) +local k2, v2 = next(owner, k1) +local k3, v3 = next(owner, k2) +observe_table(v1, 0) +observe_table(v2, 0) +observe_table(rawget(owner, k1), 0) +observe_table(rawget(owner, k2), 0) +observe_table(rawget(owner, 1), 0) +k1 = nil +v1 = nil +k2 = nil +v2 = nil +k3 = nil +v3 = nil +cycle = nil +collectgarbage("collect") +local gone = rawget(owner, key) +local a, b = next(owner) +local c, d = next(owner, a) +observe_table(b, 0) +observe_table(rawget(owner, 1), 0) +observe_table(rawget(owner, a), 0) +"#; + let gone = run_next(&format!("{prefix}return type(gone)\n")); + assert_eq!(gone.stack, &[Value::string("nil")]); + assert_eq!(gone.counts, vec![2, 2, 1, 2, 1]); + assert_weak_next_identities(&gone.tables); + let end = run_next(&format!("{prefix}return type(c)\n")); + assert_eq!(end.stack, &[Value::string("nil")]); + assert_eq!(end.counts, vec![2, 2, 1, 2, 1]); + assert_weak_next_identities(&end.tables); + let padded = run_next(&format!("{prefix}return type(d)\n")); + assert_eq!(padded.stack, &[Value::string("nil")]); + assert_eq!(padded.counts, vec![2, 2, 1, 2, 1]); + assert_weak_next_identities(&padded.tables); +} + +fn assert_weak_next_identities(seen: &[ObservedTable]) { + let key = seen[0].table; + let cycle = seen[1].table; + let rooted = seen[2].table; + let before = [seen[3].table, seen[4].table]; + assert!(before.contains(&cycle) && before.contains(&rooted)); + assert_ne!(cycle, rooted); + assert_eq!( + seen[3].table, seen[5].table, + "rawget agrees with the first value" + ); + assert_eq!( + seen[4].table, seen[6].table, + "rawget agrees with the second value" + ); + assert_eq!(seen[7].table, rooted); + assert_eq!( + seen[8].table, rooted, + "next after collect returns the strong root" + ); + assert_eq!(seen[9].table, rooted); + assert_eq!(seen[10].table, rooted); + assert_ne!(seen[8].table, cycle); + assert_ne!(seen[8].table, key); +} + +#[test] +fn lua_candidate_next_on_empty_or_cleared_returns_one_nil() { + let empty_key = run_next("local k, v = next({})\nreturn type(k)\n"); + assert_eq!(empty_key.stack, &[Value::string("nil")]); + assert_eq!(empty_key.counts, vec![1]); + let empty_pad = run_next("local k, v = next({})\nreturn type(v)\n"); + assert_eq!(empty_pad.stack, &[Value::string("nil")]); + assert_eq!(empty_pad.counts, vec![1]); + + // The cycle lives only inside `seed`. This lowerer does not capture + // upvalues, so the function returns the weak table the same way the + // existing rawget probe does. + let cleared = r#" +local function seed() + local mt = {} + mt.__mode = "v" + local owner = {} + setmetatable(owner, mt) + local cycle = {} + cycle.self = cycle + owner[1] = cycle + return owner +end +local owner = seed() +collectgarbage("collect") +local k, v = next(owner, nil) +"#; + let key = run_next(&format!("{cleared}return type(k)\n")); + assert_eq!(key.stack, &[Value::string("nil")]); + assert_eq!(key.counts, vec![1]); + let pad = run_next(&format!("{cleared}return type(v)\n")); + assert_eq!(pad.stack, &[Value::string("nil")]); + assert_eq!(pad.counts, vec![1]); + let raw = run_next(&format!("{cleared}return type(rawget(owner, 1))\n")); + assert_eq!(raw.stack, &[Value::string("nil")]); + assert_eq!(raw.counts, vec![1]); +} + +#[test] +fn lua_candidate_next_returns_mode_name_not_a_field_id() { + let source = r#" +local mt = {} +mt.__mode = "v" +local k, v = next(mt) +local n = next(mt, k) +"#; + let key = run_next(&format!("{source}return k\n")); + assert_eq!(key.stack, &[Value::string("__mode")]); + assert_eq!(key.counts, vec![2, 1]); + let value = run_next(&format!("{source}return v\n")); + assert_eq!(value.stack, &[Value::string("v")]); + assert_eq!(value.counts, vec![2, 1]); + let end = run_next(&format!("{source}return type(n)\n")); + assert_eq!(end.stack, &[Value::string("nil")]); + assert_eq!(end.counts, vec![2, 1]); +} + +#[test] +fn lua_candidate_next_returns_a_string_key_and_stops() { + let source = r#" +local owner = {} +owner.keep = "yes" +local k, v = next(owner) +local n = next(owner, k) +"#; + let key = run_next(&format!("{source}return k\n")); + assert_eq!(key.stack, &[Value::string("keep")]); + assert_eq!(key.counts, vec![2, 1]); + let value = run_next(&format!("{source}return v\n")); + assert_eq!(value.stack, &[Value::string("yes")]); + assert_eq!(value.counts, vec![2, 1]); + let end = run_next(&format!("{source}return type(n)\n")); + assert_eq!(end.stack, &[Value::string("nil")]); + assert_eq!(end.counts, vec![2, 1]); +} + +#[test] +fn lua_candidate_next_object_key_keeps_issued_identity() { + let source = r#" +local owner = {} +local key = {} +local value = {} +owner[key] = value +observe_table(key, 0) +observe_table(value, 0) +local k, v = next(owner) +observe_table(k, 0) +observe_table(v, 0) +observe_table(rawget(owner, k), 0) +local n = next(owner, k) +return type(n) +"#; + let run = run_next(source); + assert_eq!(run.stack, &[Value::string("nil")]); + assert_eq!(run.counts, vec![2, 1]); + assert_eq!(run.tables[2].table, run.tables[0].table); + assert_eq!(run.tables[3].table, run.tables[1].table); + assert_eq!(run.tables[4].table, run.tables[1].table); +} + +#[test] +fn lua_candidate_next_single_value_takes_the_first_result() { + let source = r#" +local owner = {} +local value = {} +owner[1] = value +local k = next(owner) +return type(k) +"#; + let run = run_next(source); + assert_eq!(run.stack, &[Value::string("number")]); + assert_eq!(run.counts, vec![2]); + let omitted = run_next("return type(next({}))\n"); + assert_eq!(omitted.stack, &[Value::string("nil")]); + assert_eq!(omitted.counts, vec![1]); +} + +#[test] +fn lua_candidate_next_refuses_a_private_field_id() { + let source = r#" +local owner = {} +owner.keep = "yes" +local planted = {} +plant_private_field(owner, planted) +local k, v = next(owner) +local n = next(owner, k) +return k +"#; + let mut vm = candidate(source); + let error = vm.run().expect_err("private field is not a guest key"); + assert!( + matches!(error, vm::VmError::HostError(ref message) if message.contains("guest key")), + "{error}" + ); + assert_ne!( + candidate::next_counts(&mut vm), + vec![1], + "an unsupported entry is not the end of iteration" + ); +} + +struct NextRun { + stack: Vec, + tables: Vec, + counts: Vec, +} + +fn run_next(source: &str) -> NextRun { + let mut vm = candidate(source); + let status = vm.run().expect("run next"); + assert_eq!(status, VmStatus::Halted); + NextRun { + stack: vm.stack().to_vec(), + tables: vm + .host_context() + .scope_state::>() + .cloned() + .unwrap_or_default(), + counts: candidate::next_counts(&mut vm), + } +} From 5942f89ef9aef5c529e764748f00fd3180f61817 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 20:58:45 +0800 Subject: [PATCH 072/225] fix(lua): refuse tail next and root the next receiver Chunk export cannot publish two values, so an unparenthesized tail next stays on the existing unsupported path. Parentheses and a non-last argument still take one value. A local named next no longer calls the builtin, while local next, v = next(t) still sees it. The receiver temp is rooted only while the cursor expression runs. A missing or cleared cursor is invalid key to next. next walks the owner's edges; that walk is the scan cost. --- tests/luajit_heap_runtime/candidate.rs | 62 +++- .../value_boundary_tests.rs | 271 +++++++++++++++++- 2 files changed, 320 insertions(+), 13 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 75d4c5f..32d0176 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1568,6 +1568,13 @@ impl Lower<'_> { self.emit_ignored(expr, self.line(*span)) } ast::Stmt::Return { span, values } if !self.in_function && values.exprs.len() == 1 => { + // One public chunk return. `CallReturn::Many` is not a + // non-yielding host result, so an unparenthesized tail `next` + // is the existing unsupported path rather than a second + // protocol. `return (next(t))` still exports the first value. + if self.is_next_call(&values.exprs[0]) { + return Err(self.unsupported(*span)); + } let value = self.expr(&values.exprs[0])?; let expr = self.call(RETURN_SCALAR, vec![value])?; self.stmts.push(Stmt::Expr { @@ -1948,6 +1955,12 @@ impl Lower<'_> { .ok_or_else(|| self.unsupported(span)) } + fn builtin_next(&self, name: &ast::Name) -> bool { + name.is("next") + && !self.functions.contains_key(&name.bytes) + && !self.locals.contains_key(&name.bytes) + } + fn is_next_call(&self, expr: &ast::Expr) -> bool { let ast::Expr::SuffixChain { base, steps, .. } = expr else { return false; @@ -1955,7 +1968,7 @@ impl Lower<'_> { let ast::Expr::Name { name, .. } = base.as_ref() else { return false; }; - if !name.is("next") || self.functions.contains_key(&name.bytes) { + if !self.builtin_next(name) { return false; } matches!( @@ -1968,10 +1981,24 @@ impl Lower<'_> { ) } + /// Last-argument adjustment is not implemented. Parentheses and a + /// non-last argument still take one value through `expr`. + fn reject_tail_next(&self, arg: &ast::Expr, span: ast::Span) -> Result<(), ParseError> { + if self.is_next_call(arg) { + Err(self.unsupported(span)) + } else { + Ok(()) + } + } + /// `local k, v = next(...)` binds through the existing array transport. + /// The RHS is lowered before the new names are bound, so + /// `local next, v = next(t)` still sees the builtin. /// - /// Chunk `return next(...)` stays one value: the chunk return path only - /// carries a scalar. A single-value expression uses the first result. + /// Chunk `return next(...)` is not this path. A missing or cleared cursor + /// is `invalid key to next`, not a restart. `next` walks the owner's + /// edges; that walk is the scan cost. Continuation from a cleared cursor + /// is not implemented. fn lower_next_local( &mut self, span: ast::Span, @@ -2029,13 +2056,20 @@ impl Lower<'_> { args: &[ast::Expr], span: ast::Span, ) -> Result { + // A fresh receiver is a temp root only while the cursor expression + // runs. It is released with the call, so a later collect can reclaim + // it. A missing or cleared cursor still errors; this walk is the scan. + if args.last().is_some_and(|arg| self.is_next_call(arg)) { + return Err(self.unsupported(span)); + } let (table, cursor) = match args { [table] => (table, None), [table, cursor] => (table, Some(cursor)), _ => return Err(self.unsupported(span)), }; + let temp_base = self.active_temps.len(); let table = self.expr(table)?; - let table = self.operand_slot(table, span)?; + let table = self.rooted_operand(table, span)?; let cursor = match cursor { Some(ast::Expr::Nil { .. }) => Expr::Null, Some(cursor) => self.expr(cursor)?, @@ -2054,6 +2088,7 @@ impl Lower<'_> { line, }); self.note_next_len(transport, line)?; + self.active_temps.truncate(temp_base); Ok(transport) } @@ -2125,6 +2160,15 @@ impl Lower<'_> { Ok(()) } + fn rooted_operand(&mut self, expr: Expr, span: ast::Span) -> Result { + if let Expr::Var(slot) = expr { + return Ok(slot); + } + let slot = self.operand_slot(expr, span)?; + self.active_temps.push(slot); + Ok(slot) + } + fn operand_slot(&mut self, expr: Expr, span: ast::Span) -> Result { if let Expr::Var(slot) = expr { return Ok(slot); @@ -2979,6 +3023,7 @@ impl Lower<'_> { if name.is("type") && let [arg] = args.exprs.as_slice() { + self.reject_tail_next(arg, expr.span())?; let arg = self.expr(arg)?; return self.call(TYPE, vec![arg]); } @@ -2991,6 +3036,7 @@ impl Lower<'_> { if name.is("copy_fields") && let [arg] = args.exprs.as_slice() { + self.reject_tail_next(arg, expr.span())?; let value = self.expr(arg)?; let slot = self .builder @@ -3006,6 +3052,7 @@ impl Lower<'_> { if name.is("setmetatable") && let [owner, mt] = args.exprs.as_slice() { + self.reject_tail_next(mt, expr.span())?; let owner = self.expr(owner)?; let mt = match mt { ast::Expr::Nil { .. } => Expr::Null, @@ -3016,10 +3063,11 @@ impl Lower<'_> { if name.is("getmetatable") && let [owner] = args.exprs.as_slice() { + self.reject_tail_next(owner, expr.span())?; let owner = self.expr(owner)?; return self.call(GET_METATABLE, vec![owner]); } - if name.is("next") && !self.functions.contains_key(&name.bytes) { + if self.builtin_next(name) { return self.next_expr(args, expr.span()); } if name.is("rawget") { @@ -3027,6 +3075,7 @@ impl Lower<'_> { let [table, key] = args.exprs.as_slice() else { return Err(self.unsupported(expr.span())); }; + self.reject_tail_next(key, expr.span())?; return self.index_read(table, key, expr.span()); } if name.is("external_shape") && args.exprs.is_empty() { @@ -3057,6 +3106,9 @@ impl Lower<'_> { { return Err(self.unsupported(span)); } + if args.last().is_some_and(|arg| self.is_next_call(arg)) { + return Err(self.unsupported(span)); + } let mut checked = Vec::new(); let temp_base = self.active_temps.len(); for (arg, param) in args.iter().zip(&function.params) { diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index bbb106f..c2f8403 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -47,21 +47,25 @@ impl SourcePlugin for CandidatePlugin { } fn candidate(source: &str) -> vm::Vm { + try_candidate(source).expect("compile Lua text") +} + +fn try_candidate(source: &str) -> Result { let catalog = Arc::clone(catalog()); let options = CompileSourceFileOptions::new() .with_source_plugin(&CandidatePlugin) .with_host_api_catalog(Arc::clone(&catalog)); let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) - .expect("compile Lua text") + .map_err(|error| error.to_string())? .into_vm() - .expect("create VM"); + .map_err(|error| error.to_string())?; let mut registry = HostFunctionRegistry::empty(); - candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + candidate::register(&mut registry, &catalog).map_err(|error| error.to_string())?; register_witnesses(&mut registry, &catalog); registry .bind_vm_cached(&mut vm) - .expect("bind candidate runtime"); - vm + .map_err(|error| error.to_string())?; + Ok(vm) } #[test] @@ -4721,9 +4725,7 @@ return type(k) let run = run_next(source); assert_eq!(run.stack, &[Value::string("number")]); assert_eq!(run.counts, vec![2]); - let omitted = run_next("return type(next({}))\n"); - assert_eq!(omitted.stack, &[Value::string("nil")]); - assert_eq!(omitted.counts, vec![1]); + assert_not_lowered("return type(next({}))\n"); } #[test] @@ -4770,3 +4772,256 @@ fn run_next(source: &str) -> NextRun { counts: candidate::next_counts(&mut vm), } } + +fn not_lowered(source: &str) -> String { + match try_candidate(source) { + Ok(_) => String::new(), + Err(error) => error, + } +} + +fn assert_not_lowered(source: &str) { + let diagnostic = not_lowered(source); + assert!( + diagnostic.contains("not lowered yet"), + "expected the existing unsupported path, got {diagnostic:?}\n{source}" + ); +} + +/// Chunk export is one `RETURN_SCALAR`. The pinned Core rejects +/// `CallReturn::Many` from that non-yielding host, so the array transport +/// cannot become two public returns without a second protocol. An +/// unparenthesized tail `next` stays on the existing unsupported path. +/// `return (next(t))` still exports the first value. A cursor that is not a +/// live entry, including one whose entry was cleared, is `invalid key to +/// next`, not a restart. `next` walks the owner's edge vector; that walk is +/// the scan cost of this candidate. +#[test] +fn lua_candidate_review_tail_next_is_not_lowered() { + let sources = [ + "\ +local owner = {} +owner.keep = \"yes\" +return next(owner) +", + "\ +local owner = {} +owner.keep = \"yes\" +return type(next(owner)) +", + "\ +local owner = {} +owner.keep = \"yes\" +return type(rawget(owner, next(owner))) +", + "\ +local owner = {} +owner.keep = \"yes\" +local other = {} +other.keep = \"yes\" +local k, v = next(owner, next(other)) +return type(k) +", + "\ +local owner = {} +owner.keep = \"yes\" +return observe_number(next(owner)) +", + "\ +local owner = {} +owner.keep = \"yes\" +local mt = {} +return type(setmetatable(owner, next(owner))) +", + "\ +local owner = {} +owner.keep = \"yes\" +return type(getmetatable(next(owner))) +", + "\ +local owner = {} +owner.keep = \"yes\" +return type(copy_fields(next(owner))) +", + ]; + for source in sources { + assert_not_lowered(source); + } +} + +#[test] +fn lua_candidate_review_parenthesized_next_exports_one() { + let run = run_next( + "\ +local owner = {} +owner.keep = \"yes\" +return (next(owner)) +", + ); + assert_eq!(run.stack, vec![Value::string("keep")]); + assert_eq!(run.counts, vec![2], "transport still carries the pair"); +} + +#[test] +fn lua_candidate_review_adjusted_next_stays_one_value() { + let non_last = run_next( + "\ +local owner = {} +local key = {} +key.self = key +owner[key] = key +return type(rawget(next(owner), \"self\")) +", + ); + assert_eq!(non_last.stack, vec![Value::string("table")]); + + let parenthesized_arg = run_next( + "\ +local owner = {} +owner.keep = \"yes\" +return type(rawget(owner, (next(owner)))) +", + ); + assert_eq!(parenthesized_arg.stack, vec![Value::string("string")]); + assert_eq!(parenthesized_arg.counts, vec![2]); +} + +#[test] +fn lua_candidate_review_shadowed_next_is_not_builtin() { + let sources = [ + "\ +local next = 1 +local owner = {} +owner.keep = \"yes\" +local k, v = next(owner) +return k +", + "\ +local next = 1 +local owner = {} +owner.keep = \"yes\" +local k = next(owner) +return type(k) +", + "\ +local next = 1 +local owner = {} +owner.keep = \"yes\" +return type(next(owner)) +", + ]; + for source in sources { + assert_not_lowered(source); + } +} + +#[test] +fn lua_candidate_review_next_rhs_sees_builtin() { + let run = run_next( + "\ +local owner = {} +owner.keep = \"yes\" +local next, v = next(owner) +return next +", + ); + assert_eq!(run.stack, vec![Value::string("keep")]); + assert_eq!(run.counts, vec![2]); +} + +#[test] +fn lua_candidate_review_next_after_do_is_builtin() { + let run = run_next( + "\ +local owner = {} +owner.keep = \"yes\" +do + local next = 1 +end +local k, v = next(owner) +return k +", + ); + assert_eq!(run.stack, vec![Value::string("keep")]); + assert_eq!(run.counts, vec![2]); +} + +#[test] +fn lua_candidate_review_receiver_temp_survives_cursor_collect() { + let source = "\ +local orphan = {} +orphan.self = orphan +observe_table(orphan, 0) +orphan = nil +local k, v = next({}, collectgarbage(\"collect\")) +return type(k) +"; + let (mut vm, status) = { + let mut vm = candidate(source); + let status = vm.run(); + (vm, status) + }; + let error = status.expect_err("0 is not a key of the empty receiver"); + match &error { + vm::VmError::HostError(message) => { + assert!( + message.contains("invalid key to next"), + "a live receiver with a missing cursor is not a stale handle: {message}" + ); + assert!( + !message.contains("stale"), + "stale receiver is a different failure from an invalid cursor: {message}" + ); + } + other => panic!("expected a host error, got {other}"), + } + let tables = observed_tables(&mut vm); + assert_eq!(tables.len(), 1, "the independent orphan was observed"); + assert_table_lifetime(&mut vm.host_context(), tables[0], false); +} + +#[test] +fn lua_candidate_review_zero_cursor_is_invalid_key() { + let mut vm = candidate( + "\ +local k, v = next({}, 0) +return type(k) +", + ); + let error = vm.run().expect_err("0 is not a key of {}"); + match error { + vm::VmError::HostError(message) => { + assert!( + message.contains("invalid key to next"), + "missing cursor without a collect is still invalid, got {message}" + ); + } + other => panic!("expected a host error, got {other}"), + } +} + +#[test] +fn lua_candidate_review_receiver_temp_released_after_next() { + let mut vm = candidate( + "\ +local marker = {} +observe_table(marker, 0) +local k, v = next({}) +marker = nil +k = nil +v = nil +collectgarbage(\"collect\") +return type(k) +", + ); + assert_eq!(vm.run().expect("collect after next"), VmStatus::Halted); + assert_eq!(vm.stack(), &[Value::string("nil")]); + let tables = observed_tables(&mut vm); + assert_eq!(tables.len(), 1); + assert_table_lifetime(&mut vm.host_context(), tables[0], false); + let stats = heap::stats(&mut vm.host_context()).expect("heap stats"); + assert_eq!( + stats.live_nodes, 0, + "the consumed receiver temp must not remain a root" + ); +} From ee1e054c3ded20907ccc9ab24f791498c2e1db32 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 20:25:32 +0800 Subject: [PATCH 073/225] feat(lua): reject LuaJIT local and upvalue limits in resolve Charge 200 active locals and 60 distinct upvalues at the existing nearest binding lookup. Hidden for slots and implicit self count; const captures count; globals, literals, and varargs do not. Binding identity and goto active locals stay unchanged. --- src/frontends/lua/resolve.rs | 137 +++- .../compiler/compiler_luajit_oracle_tests.rs | 654 +++++++++++++++++- 2 files changed, 777 insertions(+), 14 deletions(-) diff --git a/src/frontends/lua/resolve.rs b/src/frontends/lua/resolve.rs index b101b93..4467326 100644 --- a/src/frontends/lua/resolve.rs +++ b/src/frontends/lua/resolve.rs @@ -4,9 +4,19 @@ //! block, a trailing label sits at the block's starting local count, and a //! forward jump into a local's scope is an error. Const bindings cannot be //! redeclared or assigned, including from a nested function. +//! +//! Active local slots and distinct upvalues follow pinned LuaJIT `load`. The +//! counts are recorded on `Resolution::limits` and do not change binding +//! identity, goto slots, or `ResolveError`. use super::ast::*; +/// LuaJIT `LJ_MAX_LOCVAR` / `LJ_MAX_UPVAL` (`lj_def.h`). +const MAX_LOCAL_SLOTS: u32 = 200; +const MAX_UPVALUES: u32 = 60; +/// Numeric and generic `for` reserve index, limit, and step before the names. +const FOR_HIDDEN_SLOTS: u32 = 3; + #[derive(Clone, Debug, PartialEq, Eq)] pub struct Resolution { pub bindings: Vec, @@ -17,6 +27,11 @@ pub struct Resolution { /// A use whose function differs from the binding's function is a capture. pub uses: Vec, pub errors: Vec, + /// First overflows of the pinned local-slot and upvalue caps. + /// + /// Production lowering still reads `errors` only. This field is the + /// source-level check; it is not a LuaPlugin switch. + pub limits: Vec, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -106,6 +121,22 @@ pub enum ResolveError { }, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LexicalLimitKind { + Locals, + Upvalues, +} + +/// One static overflow. `count` is the first slot past the pinned cap. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LexicalLimit { + pub kind: LexicalLimitKind, + pub span: Span, + /// One-based count of the slot that did not fit (`limit + 1` on the first miss). + pub count: u32, + pub limit: u32, +} + struct LocalSlot { name: Vec, const_binding: bool, @@ -136,6 +167,7 @@ struct JumpRec { struct ScopeFrame { id: u32, start_local: usize, + hidden_base: u32, labels: Vec, jumps: Vec, } @@ -144,6 +176,10 @@ struct FuncFrame { id: u32, vararg: bool, scope_base: usize, + /// Slots reserved for `for` headers. Not guest bindings and not goto slots. + hidden: u32, + /// Binding indexes already closed over by this active function. + upvalues: Vec, } struct Cx { @@ -163,6 +199,7 @@ pub fn resolve(chunk: &Chunk) -> Resolution { imports: Vec::new(), uses: Vec::new(), errors: Vec::new(), + limits: Vec::new(), }, funcs: Vec::new(), scopes: Vec::new(), @@ -183,6 +220,8 @@ impl Cx { id, vararg, scope_base: self.scopes.len(), + hidden: 0, + upvalues: Vec::new(), }); self.enter_scope(); } @@ -190,9 +229,11 @@ impl Cx { fn enter_scope(&mut self) { let id = self.next_scope; self.next_scope += 1; + let hidden_base = self.funcs.last().map(|func| func.hidden).unwrap_or(0); self.scopes.push(ScopeFrame { id, start_local: self.locals.len(), + hidden_base, labels: Vec::new(), jumps: Vec::new(), }); @@ -230,6 +271,9 @@ impl Cx { } fn close_scope(&mut self, scope: ScopeFrame, end: u32, is_loop: bool) { + if let Some(func) = self.funcs.last_mut() { + func.hidden = scope.hidden_base; + } for local in self.locals.iter().skip(scope.start_local) { self.resolution.bindings[local.binding_index].visible_to = end; } @@ -296,6 +340,7 @@ impl Cx { visible_from: u32, pending_consts: &[Vec], ) { + self.charge_local(name.span); let active_const = self .locals .iter() @@ -335,6 +380,84 @@ impl Cx { .any(|local| local.name == name && local.const_binding) } + fn function_local_base(&self) -> usize { + let scope_base = self.funcs.last().expect("function").scope_base; + self.scopes[scope_base].start_local + } + + fn active_slots(&self) -> u32 { + let guest = self.locals.len().saturating_sub(self.function_local_base()); + let hidden = self.funcs.last().map(|func| func.hidden).unwrap_or(0); + u32::try_from(guest) + .unwrap_or(u32::MAX) + .saturating_add(hidden) + } + + fn push_limit(&mut self, kind: LexicalLimitKind, span: Span, count: u32, limit: u32) { + self.resolution.limits.push(LexicalLimit { + kind, + span, + count, + limit, + }); + } + + fn charge_local(&mut self, span: Span) { + let active = self.active_slots(); + if active >= MAX_LOCAL_SLOTS { + self.push_limit(LexicalLimitKind::Locals, span, active + 1, MAX_LOCAL_SLOTS); + } + } + + fn note_hidden_slots(&mut self, extra: u32, span: Span) { + let active = self.active_slots(); + for offset in 0..extra { + let slot = active.saturating_add(offset); + if slot >= MAX_LOCAL_SLOTS { + self.push_limit(LexicalLimitKind::Locals, span, slot + 1, MAX_LOCAL_SLOTS); + return; + } + } + } + + fn activate_hidden(&mut self, extra: u32) { + if let Some(func) = self.funcs.last_mut() { + func.hidden = func.hidden.saturating_add(extra); + } + } + + /// Relay a capture along the active function stack. Identity is the binding + /// index, not nesting depth, so sibling functions share one parent slot. + fn account_upvalue(&mut self, span: Span, binding: Option, function_id: u32) { + let Some(binding_index) = binding else { + return; + }; + let owner = self.resolution.bindings[binding_index].function_id; + if owner == function_id { + return; + } + let Some(start) = self.funcs.iter().rposition(|func| func.id == function_id) else { + return; + }; + let Some(owner_at) = self.funcs.iter().rposition(|func| func.id == owner) else { + return; + }; + if owner_at >= start { + return; + } + for index in (owner_at + 1..=start).rev() { + if self.funcs[index].upvalues.contains(&binding_index) { + return; + } + let count = u32::try_from(self.funcs[index].upvalues.len()).unwrap_or(u32::MAX); + if count >= MAX_UPVALUES { + self.push_limit(LexicalLimitKind::Upvalues, span, count + 1, MAX_UPVALUES); + return; + } + self.funcs[index].upvalues.push(binding_index); + } + } + fn lookup_binding(&self, name: &[u8]) -> Option { self.locals .iter() @@ -343,11 +466,16 @@ impl Cx { .map(|local| local.binding_index) } + /// Shared name-access point. The closure candidate records `NameUse` from + /// this same nearest-binding lookup. Keep capture charging here so + /// integration does not grow a second walk. fn note_name(&mut self, name: &Name) { let function_id = self.funcs.last().expect("function").id; + let binding = self.lookup_binding(&name.bytes); + self.account_upvalue(name.span, binding, function_id); self.resolution.uses.push(NameUse { span: name.span, - binding: self.lookup_binding(&name.bytes), + binding, function_id, }); } @@ -537,12 +665,14 @@ impl Cx { span, .. } => { + self.note_hidden_slots(FOR_HIDDEN_SLOTS, name.span); self.walk_expr(start); self.walk_expr(limit); if let Some(step) = step { self.walk_expr(step); } self.enter_scope(); + self.activate_hidden(FOR_HIDDEN_SLOTS); self.add_binding(name, BindingKind::ForIndex, false, body.span.start, &[]); self.walk_block(body, true, true); self.leave_loop(span.end); @@ -554,8 +684,11 @@ impl Cx { span, .. } => { + let anchor = names.first().map(|name| name.span).unwrap_or(*span); + self.note_hidden_slots(FOR_HIDDEN_SLOTS, anchor); self.walk_expr_list(iters); self.enter_scope(); + self.activate_hidden(FOR_HIDDEN_SLOTS); for name in names { self.add_binding(name, BindingKind::ForIndex, false, body.span.start, &[]); } @@ -603,6 +736,8 @@ impl Cx { Stmt::Function { name, body, .. } => { if name.method.is_none() && name.segments.len() == 1 { self.assign_name(&name.segments[0]); + } else if let Some(base) = name.segments.first() { + self.note_name(base); } self.walk_func(body, name.method.is_some()); } diff --git a/tests/compiler/compiler_luajit_oracle_tests.rs b/tests/compiler/compiler_luajit_oracle_tests.rs index e3a6979..82a6d21 100644 --- a/tests/compiler/compiler_luajit_oracle_tests.rs +++ b/tests/compiler/compiler_luajit_oracle_tests.rs @@ -47,21 +47,30 @@ fn configured_oracle() -> Option { fn syntax_ok(source: &[u8]) -> bool { match parser::parse_chunk(source) { - Ok(chunk) => resolve::resolve(&chunk).errors.is_empty(), + Ok(chunk) => { + let resolution = resolve::resolve(&chunk); + resolution.errors.is_empty() && resolution.limits.is_empty() + } Err(_) => false, } } fn spawn_oracle(path: &str, args: &[&str], stdin_bytes: Option<&[u8]>) -> std::process::Output { let mut cmd = Command::new(path); - cmd.args(args) - .stdin(if stdin_bytes.is_some() { - Stdio::piped() - } else { - Stdio::null() - }) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); + // Pin is -joff. Drop Lua startup files so load() sees only the driver. + cmd.arg("-joff").args(args); + for (key, _) in std::env::vars() { + if key.starts_with("LUA") { + cmd.env_remove(&key); + } + } + cmd.stdin(if stdin_bytes.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); #[cfg(target_os = "linux")] unsafe { use std::os::unix::process::CommandExt; @@ -642,14 +651,24 @@ fn differential_matches_locked_luajit() { )); } } - for (name, source, _) in boundary_samples() { + let lexical = lexical_limit_samples(); + let lexical_count = lexical.len() as u32; + let mut lexical_accept = 0u32; + let mut lexical_reject = 0u32; + let mut compare = |name: &str, source: &[u8], lexical_sample: bool| { compared += 1; - let ours = syntax_ok(&source); - let theirs = oracle_accepts(&path, &source); + let ours = syntax_ok(source); + let theirs = oracle_accepts(&path, source); if theirs { accept += 1; + if lexical_sample { + lexical_accept += 1; + } } else { reject += 1; + if lexical_sample { + lexical_reject += 1; + } } if ours != theirs { mismatches.push(format!( @@ -658,9 +677,15 @@ fn differential_matches_locked_luajit() { if theirs { "ACCEPT" } else { "REJECT" } )); } + }; + for (name, source, _) in boundary_samples() { + compare(&name, &source, false); + } + for (name, source, _) in lexical { + compare(&name, &source, true); } eprintln!( - "oracle differential cases={compared} accept={accept} reject={reject} scope=load(..., \"t\") source={ORACLE_SHA}" + "oracle differential cases={compared} accept={accept} reject={reject} lexical={lexical_count} lexical_accept={lexical_accept} lexical_reject={lexical_reject} scope=load(..., \"t\") source={ORACLE_SHA}" ); assert!( mismatches.is_empty(), @@ -1337,3 +1362,606 @@ fn long_flat_chains_finish_on_the_default_test_thread() { ); } } + +fn numbered(prefix: &str, count: usize) -> String { + (1..=count) + .map(|index| format!("{prefix}{index}")) + .collect::>() + .join(", ") +} + +fn local_decl(prefix: &str, count: usize) -> String { + format!("local {}", numbered(prefix, count)) +} + +fn line_locals(prefix: &str, count: usize) -> String { + (1..=count) + .map(|index| format!("local {prefix}{index} = {index}")) + .collect::>() + .join("\n") +} + +fn capture_return(count: usize) -> String { + let names = numbered("u", count); + format!( + "{}\nlocal function f()\nreturn {names}\nend\n", + line_locals("u", count) + ) +} + +fn capture_assign(count: usize) -> String { + let writes = (1..=count) + .map(|index| format!("u{index} = u{index}")) + .collect::>() + .join("\n"); + format!( + "{}\nlocal function f()\n{writes}\nreturn {}\nend\n", + line_locals("u", count), + numbered("u", count) + ) +} + +fn const_capture(count: usize) -> String { + let decls = (1..=count) + .map(|index| format!("const c{index} = {index}")) + .collect::>() + .join("\n"); + format!( + "{decls}\nlocal function f()\nreturn {}\nend\n", + numbered("c", count) + ) +} + +fn released_blocks(count: usize) -> String { + (1..=count) + .map(|index| format!("do local x{index} = 1 end\n")) + .collect() +} + +/// Accept/reject matrix measured with pinned LuaJIT `load(..., "t")` at +/// 96f7b297, `-joff`. 200 active locals and 60 distinct upvalues are the +/// last accepted counts. Hidden `for` slots and implicit `self` are included. +/// `...` is not a local slot. A `const` binding is an upvalue when captured. +/// Literal constants and globals are not. +fn lexical_limit_samples() -> Vec<(String, Vec, bool)> { + let mut samples = Vec::new(); + let mut add = |name: &str, source: String, accept: bool| { + samples.push((name.to_string(), source.into_bytes(), accept)); + }; + + add("locals_200", local_decl("v", 200), true); + add("locals_201", local_decl("v", 201), false); + add( + "params_200", + format!("function f({})\nend\n", numbered("p", 200)), + true, + ); + add( + "params_201", + format!("function f({})\nend\n", numbered("p", 201)), + false, + ); + add( + "params_200_local", + format!("function f({})\nlocal extra = 1\nend\n", numbered("p", 200)), + false, + ); + add( + "params_199_local", + format!("function f({})\nlocal extra = 1\nend\n", numbered("p", 199)), + true, + ); + add( + "params_200_dots", + format!("function f({}, ...)\nend\n", numbered("p", 200)), + true, + ); + add( + "method_199", + format!("function t:m({})\nend\n", numbered("p", 199)), + true, + ); + add( + "method_200", + format!("function t:m({})\nend\n", numbered("p", 200)), + false, + ); + add( + "method_198_local", + format!( + "function t:m({})\nlocal extra = 1\nend\n", + numbered("p", 198) + ), + true, + ); + add( + "method_199_local", + format!( + "function t:m({})\nlocal extra = 1\nend\n", + numbered("p", 199) + ), + false, + ); + add("release_202", released_blocks(202), true); + add( + "nfor_196", + format!("{}\nfor i = 1, 2 do end\n", local_decl("v", 196)), + true, + ); + add( + "nfor_197", + format!("{}\nfor overflow = 1, 2 do end\n", local_decl("v", 197)), + false, + ); + add( + "gfor1_196", + format!("{}\nfor i in pairs do end\n", local_decl("v", 196)), + true, + ); + add( + "gfor1_197", + format!("{}\nfor overflow in pairs do end\n", local_decl("v", 197)), + false, + ); + add( + "gfor2_195", + format!("{}\nfor i, j in pairs do end\n", local_decl("v", 195)), + true, + ); + add( + "gfor2_196", + format!( + "{}\nfor i, overflow in pairs do end\n", + local_decl("v", 196) + ), + false, + ); + add( + "dup_198", + format!("{}\nlocal same, same = 1\n", local_decl("v", 198)), + true, + ); + add( + "dup_199", + format!("{}\nlocal same, overflow = 1\n", local_decl("v", 199)), + false, + ); + add( + "nfor_196_then", + format!( + "{}\nfor i = 1, 2 do end\nlocal extra = 1\n", + local_decl("v", 196) + ), + true, + ); + add( + "do_200_then", + format!("do {} end\nlocal extra = 1\n", local_decl("v", 200)), + true, + ); + add( + "inner_200_parent_199", + format!( + "local function f()\n{}\nend\n{}\n", + local_decl("a", 200), + local_decl("b", 199) + ), + true, + ); + add( + "inner_200_parent_200", + format!( + "local function f()\n{}\nend\n{}\n", + local_decl("a", 200), + local_decl("b", 200) + ), + false, + ); + add( + "wrapped_inner_200", + format!( + "do local function f()\n{}\nend end\n{}\n", + local_decl("a", 200), + local_decl("b", 200) + ), + true, + ); + add("up_60", capture_return(60), true); + add("up_61", capture_return(61), false); + add("up_60_rw", capture_assign(60), true); + add("up_61_rw", capture_assign(61), false); + add( + "globals_79", + format!("local function f()\nreturn {}\nend\n", numbered("g", 79)), + true, + ); + add( + "literals_beside_60", + format!( + "{}\nlocal function g()\nreturn 1, 2, 'abc'\nend\n", + capture_return(60) + ), + true, + ); + add("const_60", const_capture(60), true); + add("const_61", const_capture(61), false); + add("forward_60", forward_mid(60, false), true); + add("forward_60_plus", forward_mid(60, true), false); + add("shared_60", shared_mid(60, false), true); + add("shared_60_plus", shared_mid(60, true), false); + add("func_base_60", func_base(60, false), true); + add("func_base_61", func_base(61, false), false); + add("method_base_61", func_base(61, true), false); + add("short_60", short_capture(60), true); + add("short_61", short_capture(61), false); + add("bounds_60", for_bounds_capture(60), true); + add("body_60", for_body_capture(60), false); + add("init_60", initializer_capture(60), true); + add("rec_59", recursive_capture(59), true); + add("rec_60", recursive_capture(60), false); + add( + "shadow_60", + format!( + "{}\nlocal function mid()\n{}\nlocal function inner()\nreturn {}\nend\nend\n", + line_locals("u", 60), + local_decl("u", 60), + numbered("u", 60) + ), + true, + ); + samples +} + +fn forward_mid(count: usize, extra: bool) -> String { + let names = numbered("u", count); + let tail = if extra { "\nreturn x\n" } else { "\n" }; + let marker = if extra { "\nlocal x = 9\n" } else { "\n" }; + format!( + "{}\n{marker}local function mid()\nlocal function inner()\nreturn {names}\nend{tail}end\n", + line_locals("u", count) + ) +} + +fn shared_mid(count: usize, extra: bool) -> String { + let names = numbered("u", count); + let tail = if extra { "\nreturn x\n" } else { "\n" }; + let marker = if extra { "\nlocal x = 9\n" } else { "\n" }; + format!( + "{}\n{marker}local function mid()\nlocal function a()\nreturn {names}\nend\nlocal function b()\nreturn {names}\nend{tail}end\n", + line_locals("u", count) + ) +} + +fn func_base(count: usize, method: bool) -> String { + let sep = if method { ":" } else { "." }; + let calls = (1..=count) + .map(|index| format!("function a{index}{sep}b() end")) + .collect::>() + .join("\n"); + format!( + "{}\nlocal function mid()\n{calls}\nend\n", + (1..=count) + .map(|index| format!("local a{index} = {{}}")) + .collect::>() + .join("\n") + ) +} + +fn short_capture(count: usize) -> String { + let bodies = (1..=count) + .map(|index| format!("local f{index} = |x| -> u{index}")) + .collect::>() + .join("\n"); + format!( + "{}\nlocal function mid()\n{bodies}\nend\n", + line_locals("u", count) + ) +} + +fn for_bounds_capture(count: usize) -> String { + format!( + "{}\nfor i = (function() return {}, i end)(), 2 do end\n", + line_locals("u", count), + numbered("u", count) + ) +} + +fn for_body_capture(count: usize) -> String { + format!( + "{}\nfor i = 1, 2 do local function f() return {}, i end end\n", + line_locals("u", count), + numbered("u", count) + ) +} + +fn initializer_capture(count: usize) -> String { + format!( + "{}\nlocal fresh = (function() return {}, fresh end)()\n", + line_locals("u", count), + numbered("u", count) + ) +} + +fn recursive_capture(count: usize) -> String { + format!( + "{}\nlocal function f()\nreturn {}, f\nend\n", + line_locals("u", count), + numbered("u", count) + ) +} + +#[test] +fn lexical_limits_follow_pinned_load() { + let mut failed = Vec::new(); + for (name, source, accept) in lexical_limit_samples() { + let got = syntax_ok(&source); + if got != accept { + failed.push(format!( + "{name}: parse_chunk+resolve {} expected {}", + if got { "ACCEPT" } else { "REJECT" }, + if accept { "ACCEPT" } else { "REJECT" } + )); + } + } + assert!( + failed.is_empty(), + "lexical limits disagree with pinned load(..., \"t\"):\n{}", + failed.join("\n") + ); +} + +fn sample_source(name: &str) -> Vec { + lexical_limit_samples() + .into_iter() + .find(|(sample, _, _)| sample == name) + .map(|(_, source, _)| source) + .unwrap_or_else(|| panic!("missing sample {name}")) +} + +fn is_ident_byte(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' +} + +fn ident_spans(source: &[u8], ident: &str) -> Vec { + let needle = ident.as_bytes(); + let mut spans = Vec::new(); + let mut offset = 0; + while offset + needle.len() <= source.len() { + let Some(found) = source[offset..] + .windows(needle.len()) + .position(|window| window == needle) + else { + break; + }; + let start = offset + found; + let end = start + needle.len(); + let before_ok = start == 0 || !is_ident_byte(source[start - 1]); + let after_ok = end == source.len() || !is_ident_byte(source[end]); + if before_ok && after_ok { + spans.push(ast::Span { + start: start as u32, + end: end as u32, + }); + } + offset = start + 1; + } + spans +} + +fn resolved(source: &[u8]) -> resolve::Resolution { + let chunk = parser::parse_chunk(source).unwrap_or_else(|err| panic!("parse failed: {err:?}")); + resolve::resolve(&chunk) +} + +fn assert_first_limit( + name: &str, + source: &[u8], + kind: resolve::LexicalLimitKind, + count: u32, + span: ast::Span, +) { + let resolution = resolved(source); + assert!( + resolution.errors.is_empty(), + "{name} mixed a syntax error into the limit: {:?}", + resolution.errors + ); + let limit = resolution + .limits + .first() + .unwrap_or_else(|| panic!("{name} accepted a pinned overflow")); + assert_eq!(limit.kind, kind, "{name} kind"); + assert_eq!(limit.count, count, "{name} first overflow count"); + assert_eq!( + limit.limit, + if kind == resolve::LexicalLimitKind::Locals { + 200 + } else { + 60 + } + ); + assert_eq!(limit.span, span, "{name} span"); +} + +#[test] +fn lexical_limit_reports_first_overflow() { + let locals = sample_source("locals_201"); + assert_first_limit( + "locals_201", + &locals, + resolve::LexicalLimitKind::Locals, + 201, + ident_spans(&locals, "v201")[0], + ); + + let params = sample_source("params_200_local"); + assert_first_limit( + "params_200_local", + ¶ms, + resolve::LexicalLimitKind::Locals, + 201, + ident_spans(¶ms, "extra")[0], + ); + + let method = sample_source("method_200"); + assert_first_limit( + "method_200", + &method, + resolve::LexicalLimitKind::Locals, + 201, + ident_spans(&method, "p200")[0], + ); + + let numeric = sample_source("nfor_197"); + assert_first_limit( + "nfor_197", + &numeric, + resolve::LexicalLimitKind::Locals, + 201, + ident_spans(&numeric, "overflow")[0], + ); + + let hidden = format!("{}\nfor overflow = 1, 2 do end\n", local_decl("v", 198)); + let hidden_bytes = hidden.as_bytes(); + assert_first_limit( + "nfor_hidden_198", + hidden_bytes, + resolve::LexicalLimitKind::Locals, + 201, + ident_spans(hidden_bytes, "overflow")[0], + ); + let hidden_resolution = resolved(hidden_bytes); + assert_eq!( + hidden_resolution + .bindings + .iter() + .filter(|binding| binding.kind == resolve::BindingKind::ForIndex) + .count(), + 1, + "hidden for slots must not become guest bindings" + ); + + let generic = sample_source("gfor2_196"); + assert_first_limit( + "gfor2_196", + &generic, + resolve::LexicalLimitKind::Locals, + 201, + ident_spans(&generic, "overflow")[0], + ); + + let duplicate = sample_source("dup_199"); + assert_first_limit( + "dup_199", + &duplicate, + resolve::LexicalLimitKind::Locals, + 201, + ident_spans(&duplicate, "overflow")[0], + ); + let same = sample_source("dup_198"); + let same_resolution = resolved(&same); + assert!(same_resolution.limits.is_empty()); + assert_eq!( + same_resolution + .bindings + .iter() + .filter(|binding| binding.name == b"same") + .count(), + 2, + "repeated names still take two slots" + ); + + let upvalues = sample_source("up_61"); + let up_spans = ident_spans(&upvalues, "u61"); + assert_first_limit( + "up_61", + &upvalues, + resolve::LexicalLimitKind::Upvalues, + 61, + *up_spans.last().expect("u61 use"), + ); + + let constants = sample_source("const_61"); + assert_first_limit( + "const_61", + &constants, + resolve::LexicalLimitKind::Upvalues, + 61, + *ident_spans(&constants, "c61").last().expect("c61 use"), + ); + + let forwarded = sample_source("forward_60_plus"); + assert_first_limit( + "forward_60_plus", + &forwarded, + resolve::LexicalLimitKind::Upvalues, + 61, + *ident_spans(&forwarded, "x").last().expect("x use"), + ); + + let shared = sample_source("shared_60_plus"); + assert_first_limit( + "shared_60_plus", + &shared, + resolve::LexicalLimitKind::Upvalues, + 61, + *ident_spans(&shared, "x").last().expect("x use"), + ); + + let base = sample_source("func_base_61"); + assert_first_limit( + "func_base_61", + &base, + resolve::LexicalLimitKind::Upvalues, + 61, + *ident_spans(&base, "a61").last().expect("a61 use"), + ); + + let method_base = sample_source("method_base_61"); + assert_first_limit( + "method_base_61", + &method_base, + resolve::LexicalLimitKind::Upvalues, + 61, + *ident_spans(&method_base, "a61").last().expect("a61 use"), + ); + + let short = sample_source("short_61"); + assert_first_limit( + "short_61", + &short, + resolve::LexicalLimitKind::Upvalues, + 61, + *ident_spans(&short, "u61").last().expect("u61 use"), + ); + + let body = sample_source("body_60"); + assert_first_limit( + "body_60", + &body, + resolve::LexicalLimitKind::Upvalues, + 61, + *ident_spans(&body, "i").last().expect("loop variable use"), + ); + + let recursive = sample_source("rec_60"); + assert_first_limit( + "rec_60", + &recursive, + resolve::LexicalLimitKind::Upvalues, + 61, + *ident_spans(&recursive, "f") + .last() + .expect("function name use"), + ); + + let goto_source = b"local a = 1\nfor i = 1, 2 do\ngoto L\n::L::\nend\n"; + let goto_resolution = resolved(goto_source); + assert!(goto_resolution.errors.is_empty()); + assert!(goto_resolution.limits.is_empty()); + assert_eq!(goto_resolution.bindings.len(), 2); + assert_eq!( + goto_resolution.gotos[0].active_locals, 2, + "hidden for slots must not change goto active locals" + ); +} From fe731a57f719db779468ceb630701c3b86e53cb9 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 20:54:21 +0800 Subject: [PATCH 074/225] docs(lua): state the private lexical-limit vector contract Non-empty Resolution::limits means the chunk is over a cap. first() is the frontend walk entry for one diagnostic. Later entries may repeat, and the order is not LuaJIT's first error. note_name documents the current lookup. function a.b and function a:m receivers stay charged before walk_func. --- src/frontends/lua/resolve.rs | 25 +++++++++++++------ .../compiler/compiler_luajit_oracle_tests.rs | 2 ++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/frontends/lua/resolve.rs b/src/frontends/lua/resolve.rs index 4467326..1cdd32d 100644 --- a/src/frontends/lua/resolve.rs +++ b/src/frontends/lua/resolve.rs @@ -5,9 +5,10 @@ //! forward jump into a local's scope is an error. Const bindings cannot be //! redeclared or assigned, including from a nested function. //! -//! Active local slots and distinct upvalues follow pinned LuaJIT `load`. The -//! counts are recorded on `Resolution::limits` and do not change binding -//! identity, goto slots, or `ResolveError`. +//! Active local slots and distinct upvalues follow pinned LuaJIT `load` for +//! accept and reject. Overflows are appended to `Resolution::limits` in +//! frontend walk order. That order is not LuaJIT's first error. The counts +//! do not change binding identity, goto slots, or `ResolveError`. use super::ast::*; @@ -27,7 +28,14 @@ pub struct Resolution { /// A use whose function differs from the binding's function is a capture. pub uses: Vec, pub errors: Vec, - /// First overflows of the pinned local-slot and upvalue caps. + /// Appended overflows of the pinned local-slot and upvalue caps. + /// + /// Non-empty means the chunk is over a cap. `first()` is the entry for + /// one diagnostic, in frontend walk order. Later entries may repeat the + /// same miss: a `for` can overflow on a hidden slot and again on a + /// visible index. This is not LuaJIT's first error. LuaJIT can report a + /// local before it initializes that local's RHS. Diagnostics that are + /// not wired yet do not deduplicate this vector or add state. /// /// Production lowering still reads `errors` only. This field is the /// source-level check; it is not a LuaPlugin switch. @@ -466,9 +474,11 @@ impl Cx { .map(|local| local.binding_index) } - /// Shared name-access point. The closure candidate records `NameUse` from - /// this same nearest-binding lookup. Keep capture charging here so - /// integration does not grow a second walk. + /// Look up the nearest binding and charge a distinct outer upvalue. + /// + /// `function a.b` and `function a:m` bill the receiver through this + /// lookup before `walk_func`. A later integration line reuses the same + /// lookup instead of walking the name again. fn note_name(&mut self, name: &Name) { let function_id = self.funcs.last().expect("function").id; let binding = self.lookup_binding(&name.bytes); @@ -737,6 +747,7 @@ impl Cx { if name.method.is_none() && name.segments.len() == 1 { self.assign_name(&name.segments[0]); } else if let Some(base) = name.segments.first() { + // First segment of `function a.b` / `function a:m`, before the body. self.note_name(base); } self.walk_func(body, name.method.is_some()); diff --git a/tests/compiler/compiler_luajit_oracle_tests.rs b/tests/compiler/compiler_luajit_oracle_tests.rs index 82a6d21..7e4b611 100644 --- a/tests/compiler/compiler_luajit_oracle_tests.rs +++ b/tests/compiler/compiler_luajit_oracle_tests.rs @@ -1753,6 +1753,8 @@ fn resolved(source: &[u8]) -> resolve::Resolution { resolve::resolve(&chunk) } +/// `limits.first()` is the frontend walk entry for one diagnostic. +/// Later entries may repeat. This is not LuaJIT's first error. fn assert_first_limit( name: &str, source: &[u8], From b0689b3e489b55f07ef82f784cc1102a4eebf504 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 21:50:58 +0800 Subject: [PATCH 075/225] fix(lua): enforce lexical limits at control candidate entry --- src/frontends/lua/control.rs | 15 +++- src/frontends/lua/resolve.rs | 7 +- tests/compiler/compiler_lua_control_tests.rs | 86 ++++++++++++++++++++ 3 files changed, 103 insertions(+), 5 deletions(-) diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs index 0cdbcac..037c825 100644 --- a/src/frontends/lua/control.rs +++ b/src/frontends/lua/control.rs @@ -57,7 +57,7 @@ use super::ast::{self, BinOp, Block, Chunk, Expr, Name, NumberKind, Span, Stmt, UnOp}; use super::lexer; use super::parser; -use super::resolve::{self, Resolution, ResolveError}; +use super::resolve::{self, LexicalLimitKind, Resolution, ResolveError}; use vm::compiler::HostCallResolver; use vm::{ AssignmentKind, Expr as CoreExpr, FrontendIr, LocalIrBuilder, LocalSlot, ParseError, @@ -85,6 +85,19 @@ pub(super) fn lower_source_with( let line = line_of(source, error_span(error)); return Err(ParseError::at_line(line, static_message(error))); } + if let Some(limit) = resolution.limits.first() { + let kind = match limit.kind { + LexicalLimitKind::Locals => "active local slots", + LexicalLimitKind::Upvalues => "distinct upvalues", + }; + return Err(ParseError::at_line( + line_of(source, limit.span), + format!( + "Lua lexical limit exceeded: {kind} ({} > {})", + limit.count, limit.limit + ), + )); + } let mut lower = Lower::new( source, &resolution, diff --git a/src/frontends/lua/resolve.rs b/src/frontends/lua/resolve.rs index 1cdd32d..88b5a06 100644 --- a/src/frontends/lua/resolve.rs +++ b/src/frontends/lua/resolve.rs @@ -34,11 +34,10 @@ pub struct Resolution { /// one diagnostic, in frontend walk order. Later entries may repeat the /// same miss: a `for` can overflow on a hidden slot and again on a /// visible index. This is not LuaJIT's first error. LuaJIT can report a - /// local before it initializes that local's RHS. Diagnostics that are - /// not wired yet do not deduplicate this vector or add state. + /// local before it initializes that local's RHS. /// - /// Production lowering still reads `errors` only. This field is the - /// source-level check; it is not a LuaPlugin switch. + /// The control candidate checks this after `errors` and before lowering. + /// This does not change the production LuaPlugin entry. pub limits: Vec, } diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index 38076f4..0994ec2 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -968,6 +968,92 @@ fn jump_into_local_is_a_static_rejection() { ); } +fn numbered_locals(count: usize) -> String { + (1..=count) + .map(|index| format!("local v{index} = {index}\n")) + .collect() +} + +fn expect_lexical_rejection( + label: &str, + source: &str, + line: usize, + message: &str, + oracle_kind: &str, +) { + let path = write_fixture(label, source); + eprintln!("LUA_CONTROL lexical fixture={}", path.display()); + if let Ok(oracle) = std::env::var("LUAJIT_ORACLE") { + let output = oracle_load_rejection(&oracle, &path); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{label}: {stderr}"); + assert_eq!(output.stdout, b"jit=off\n", "{label}: oracle stdout"); + assert_eq!(stderr.lines().next(), Some("LOAD_REJECT")); + assert!(stderr.contains(oracle_kind), "{label}: {stderr}"); + eprintln!("LUA_CONTROL oracle {label} exit=2 {stderr}"); + } + + let error = compile_source_file_with_options(&path, candidate_options()) + .err() + .unwrap_or_else(|| panic!("{label}: lexical overflow produced a program")); + let vm::SourcePathError::SourceWithMap { + error: vm::compiler::SourceError::Parse(error), + sources, + } = error + else { + panic!("{label}: expected a frontend parse error, got {error}"); + }; + assert!(error.message.contains(message), "{label}: {error}"); + assert_eq!(error.line, line, "{label}: {error}"); + let span = error.span.expect("file compile attaches a diagnostic span"); + assert_eq!(sources.file_name(span.source_id), path.to_str()); + assert_eq!(sources.span_text(span), source.lines().nth(line - 1)); + eprintln!("LUA_CONTROL candidate {label} line={line} {error}"); +} + +#[test] +fn lexical_admission_checks_active_local_boundary() { + expect_number( + "active_locals_200", + &format!("{}return v200\n", numbered_locals(200)), + 200.0, + ); + expect_lexical_rejection( + "active_locals_201", + &format!("{}return v201\n", numbered_locals(201)), + 201, + "active local slots (201 > 200)", + "local variables", + ); +} + +#[test] +fn lexical_admission_checks_upvalues_before_lowering() { + let source = |count| { + let captures = (1..=count) + .map(|index| format!("v{index}")) + .collect::>() + .join(", "); + format!( + "{}local function collect_values()\n return {captures}\nend\nreturn 7\n", + numbered_locals(count) + ) + }; + // The admitted control subset does not lower the function. Pinned LuaJIT + // checks the legal 60-capture source with the function left uncalled. + if let Ok(oracle) = std::env::var("LUAJIT_ORACLE") { + let path = write_fixture("distinct_upvalues_60", &source(60)); + assert_eq!(oracle_return(&oracle, &path), 7.0); + } + expect_lexical_rejection( + "distinct_upvalues_61", + &source(61), + 63, + "distinct upvalues (61 > 60)", + "upvalues", + ); +} + #[test] fn oracle_control_config_matches_locked_52_build() { let Ok(path) = std::env::var("LUAJIT_ORACLE") else { From 4a953553f94ba4a65338f881c98b637f5290695b Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 21:57:59 +0800 Subject: [PATCH 076/225] fix(lua): report physical lines for static RSS links --- src/frontends/lua/imports.rs | 32 +++++++++--- src/frontends/lua/lexer.rs | 18 ++++--- .../compiler_lua_static_import_tests.rs | 52 +++++++++++++++++++ 3 files changed, 87 insertions(+), 15 deletions(-) diff --git a/src/frontends/lua/imports.rs b/src/frontends/lua/imports.rs index d05f673..be68a3e 100644 --- a/src/frontends/lua/imports.rs +++ b/src/frontends/lua/imports.rs @@ -13,9 +13,14 @@ use vm::{ImportClause, ModuleImport, NamedImport, ParseError, SourceError, Sourc pub(super) fn static_module_imports(source: &str) -> Result, SourcePathError> { let chunk = parser::parse_chunk(source.as_bytes()).map_err(syntax_to_path_error)?; let mut imports = Vec::new(); + let mut lines = PhysicalLines { + source: source.as_bytes(), + offset: 0, + line: 1, + }; let mut require_shadowed = false; for stmt in &chunk.body.stmts { - if !require_shadowed && let Some(import) = local_static_link(source, stmt) { + if !require_shadowed && let Some(import) = local_static_link(stmt, &mut lines) { imports.push(import); } if binds_require(stmt) { @@ -32,7 +37,7 @@ fn syntax_to_path_error(err: lexer::SyntaxError) -> SourcePathError { ))) } -fn local_static_link(source: &str, stmt: &Stmt) -> Option { +fn local_static_link(stmt: &Stmt, lines: &mut PhysicalLines<'_>) -> Option { let Stmt::Local { names, values, .. } = stmt else { return None; }; @@ -55,7 +60,7 @@ fn local_static_link(source: &str, stmt: &Stmt) -> Option { }; Some(ModuleImport { spec: link.spec, - line: line_at(source, link.name_start), + line: lines.line_at(link.name_start), clause, }) } @@ -148,8 +153,21 @@ fn utf8_bytes(bytes: &[u8]) -> Option { String::from_utf8(bytes.to_vec()).ok() } -fn line_at(source: &str, offset: u32) -> usize { - let end = usize::try_from(offset).unwrap_or(source.len()); - let prefix = source.get(..end.min(source.len())).unwrap_or(""); - prefix.bytes().filter(|byte| *byte == b'\n').count() + 1 +// Links arrive in source order. Count raw bytes once, independently of Lua +// line directives that remap the lexer token lines used for diagnostics. +struct PhysicalLines<'a> { + source: &'a [u8], + offset: usize, + line: usize, +} + +impl PhysicalLines<'_> { + fn line_at(&mut self, name_start: u32) -> usize { + while self.offset < name_start as usize { + let width = lexer::newline_width(&self.source[self.offset..]); + self.line += usize::from(width != 0); + self.offset += width.max(1); + } + self.line + } } diff --git a/src/frontends/lua/lexer.rs b/src/frontends/lua/lexer.rs index d9210e6..a7d46d7 100644 --- a/src/frontends/lua/lexer.rs +++ b/src/frontends/lua/lexer.rs @@ -144,6 +144,15 @@ pub fn lex(source: &[u8]) -> Result { }) } +/// Width of a Lua newline at the start of the byte slice, or zero. +pub(super) fn newline_width(source: &[u8]) -> usize { + match source { + [b'\r', b'\n', ..] | [b'\n', b'\r', ..] => 2, + [b'\r' | b'\n', ..] => 1, + _ => 0, + } +} + impl<'a> Scan<'a> { fn cur(&self) -> Option { self.src.get(self.pos).copied() @@ -187,14 +196,7 @@ impl<'a> Scan<'a> { } fn finish_newline(&mut self) { - let old = self.cur(); - self.advance(); - if let Some(next) = self.cur() - && Self::is_eol(next) - && Some(next) != old - { - self.advance(); - } + self.pos += newline_width(&self.src[self.pos..]); self.line = self.line.saturating_add(1); } diff --git a/tests/compiler/compiler_lua_static_import_tests.rs b/tests/compiler/compiler_lua_static_import_tests.rs index c29c4a2..4e82a0c 100644 --- a/tests/compiler/compiler_lua_static_import_tests.rs +++ b/tests/compiler/compiler_lua_static_import_tests.rs @@ -414,6 +414,30 @@ fn static_link_keeps_multiline_require_line() { assert_namespace(&imports[0], "./present.rss", "m", 2); } +#[test] +fn static_link_reports_physical_require_lines() { + for (eol, expected) in [ + ("\n", 2), + ("\r", 2), + ("\r\n", 2), + ("\n\r", 2), + ("\r\r", 3), + ("\n\n", 3), + ] { + let source = format!("-- header{eol}local imported = require(\"./missing.rss\")"); + let imports = static_imports(&source); + assert_eq!(imports.len(), 1, "EOL {eol:?}"); + assert_eq!(imports[0].line, expected, "EOL {eol:?}"); + assert_namespace(&imports[0], "./missing.rss", "imported", expected); + } + + let source = "-- header\r\n# 90 \"virtual.lua\"\n\rlocal first =\rrequire(\"./one.rss\")\r\rlocal second = require(\"./two.rss\").tag"; + let imports = static_imports(source); + assert_eq!(imports.len(), 2); + assert_namespace(&imports[0], "./one.rss", "first", 4); + assert_named(&imports[1], "./two.rss", "tag", "second", 6); +} + #[test] fn static_link_keeps_named_member_clause() { let source = "local tag = require(\"./left.rss\").tag\n"; @@ -468,6 +492,34 @@ fn named_missing_export_is_invalid_import_syntax() { } } +#[test] +fn named_missing_export_reports_physical_require_line() { + let root = owned_root("missing_export_physical_line"); + write_present(&root); + let source = "-- header\r\n\rlocal missing = require(\"./present.rss\").gone\n\r"; + let main_path = write_source(&root, "main.lua", source); + let err = expect_load_error(compile_candidate(&main_path), "missing export"); + match err { + SourcePathError::InvalidImportSyntax { + line, + message, + path, + } => { + assert_eq!(line, 3); + assert_eq!(path, main_path.canonicalize().expect("real Lua path")); + assert_eq!( + message, + "module './present.rss' has no public function 'gone'" + ); + } + other => panic!("expected InvalidImportSyntax from Core's export check, got {other:?}"), + } + + let imports = static_imports(source); + assert_eq!(imports.len(), 1); + assert_named(&imports[0], "./present.rss", "gone", "missing", 3); +} + #[test] fn alias_call_stops_in_the_old_lowerer() { let source = "local different = require(\"./present.rss\").tag\ndifferent()\n"; From 874c3dc4aa736b2d3c984fb12994c85dce3a8fa7 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 18:35:46 +0800 Subject: [PATCH 077/225] feat(lua): store bool and binary64 on the shared upvalue edge (cherry picked from commit 2787f2f9ab5d5b59b9b7a60d4c99e84907d5b5e6) --- src/frontends/lua/heap.rs | 2 +- src/frontends/lua/heap/table.rs | 49 +++- tests/luajit_heap_runtime/closure_graph.rs | 280 +++++++++++++++++++++ 3 files changed, 321 insertions(+), 10 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 8294283..2f67339 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -27,7 +27,7 @@ //! Closure and upvalue nodes use the same slots, edges, roots, meter, and //! sweep. A root slot holds a table, a closure, or an upvalue. A table field can point at //! a closure, a closure at one shared upvalue, and that upvalue at its current -//! table or closure. A missing current edge is nil. Two closures can point at +//! table, closure, boolean, or binary64. A missing current edge is nil. Two closures can point at //! the same upvalue. A table entry key can be a table or a closure. Both use //! the same object-key record: slot, generation, and kind. Mark and sweep walk //! that record in the existing pass. A closure key is not a field id and is diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 71c9194..fbc148d 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -221,8 +221,9 @@ enum EdgeValue { slot: u32, generation: u32, }, - /// One guest scalar in the same record as a table target. Field 0 is the - /// only key whose string is read as `__mode`. + /// One guest scalar in the same record as a table target. Field 0 on a + /// table is the only key whose string is read as `__mode`. A cell current + /// edge may hold a boolean or binary64; that value is not a key. Scalar(Value), } @@ -241,13 +242,16 @@ impl EdgeValue { /// /// A missing edge is nil and is not a variant. `None` from [`LuaHeap::read_cell`] /// is that nil. An error is an invalid handle, not nil. A cell is not issued -/// as a table value. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// as a table value. A scalar carries the stored [`Value`]. [`Value`] is not +/// `Copy` or `Eq`, so this enum is not either. +#[derive(Clone, Debug, PartialEq)] pub enum CellValue { /// The cell currently holds a table. Table(TableRef), /// The cell currently holds a closure. Closure(ClosureRef), + /// The cell currently holds a boolean or binary64. Not a table key. + Scalar(Value), } /// One explicit root. Table, closure, and upvalue roots share the root vector. @@ -757,7 +761,8 @@ impl LuaHeap { /// Replaces the table currently stored in a shared cell. /// /// An existing current edge is overwritten. This does not insert a second - /// record. A closure target uses [`Self::write_closure_upvalue`]. + /// record. A closure target uses [`Self::write_closure_upvalue`]. A + /// boolean or binary64 uses [`Self::write_scalar_upvalue`]. pub fn write_upvalue(&mut self, cell: UpvalueRef, table: TableRef) -> Result<(), HeapError> { self.require_upvalue(cell)?; self.require_live(table)?; @@ -789,6 +794,29 @@ impl LuaHeap { ) } + /// Replaces the current edge with a boolean or binary64 scalar. + /// + /// Same record as [`Self::write_upvalue`]. An existing edge is overwritten. + /// Nil is not stored here; [`Self::clear_upvalue`] deletes that record. + /// Any other guest value is refused at entry and leaves the stored edge + /// unchanged. The number is stored as given: signed zero is not + /// canonicalized, and NaN is not treated as a table key. + pub fn write_scalar_upvalue( + &mut self, + cell: UpvalueRef, + value: Value, + ) -> Result<(), HeapError> { + if !matches!(value, Value::Bool(_) | Value::Float(_)) { + return Err(HeapError::WrongKind); + } + self.require_upvalue(cell)?; + self.write_from( + cell.slot(), + EdgeKey::Field(CURRENT_EDGE), + EdgeValue::Scalar(value), + ) + } + /// Removes the current edge. Nil is the missing edge, not a stored record. pub fn clear_upvalue(&mut self, cell: UpvalueRef) -> Result<(), HeapError> { self.require_upvalue(cell)?; @@ -819,19 +847,22 @@ impl LuaHeap { self.require_closure(found)?; Ok(Some(CellValue::Closure(found))) } + EdgeValue::Scalar(value @ (Value::Bool(_) | Value::Float(_))) => { + Ok(Some(CellValue::Scalar(value.clone()))) + } EdgeValue::Upvalue { .. } | EdgeValue::Scalar(_) => Err(HeapError::WrongKind), } } /// Reads the table currently stored through a closure's cell. /// - /// A closure target is `WrongKind`. A missing edge has no table, so this - /// table adapter returns `StaleHandle`. [`Self::read_cell`] returns `None` - /// for that nil. + /// A closure or scalar target is `WrongKind`. A missing edge has no table, + /// so this table adapter returns `StaleHandle`. [`Self::read_cell`] returns + /// `None` for that nil. pub fn read_upvalue(&self, closure: ClosureRef) -> Result { match self.read_cell(closure)? { Some(CellValue::Table(table)) => Ok(table), - Some(CellValue::Closure(_)) => Err(HeapError::WrongKind), + Some(CellValue::Closure(_) | CellValue::Scalar(_)) => Err(HeapError::WrongKind), None => Err(HeapError::StaleHandle), } } diff --git a/tests/luajit_heap_runtime/closure_graph.rs b/tests/luajit_heap_runtime/closure_graph.rs index 84543e4..69ce697 100644 --- a/tests/luajit_heap_runtime/closure_graph.rs +++ b/tests/luajit_heap_runtime/closure_graph.rs @@ -74,6 +74,7 @@ fn read_capture(host: &mut HostContext<'_>, closure: ClosureRef) -> Value { let table = heap::with_heap(host, |heap| match heap.read_cell(closure)? { Some(CellValue::Table(table)) => Ok(table), Some(CellValue::Closure(_)) => panic!("capture is not a closure"), + Some(CellValue::Scalar(_)) => panic!("capture is not a table"), None => panic!("capture is nil"), }) .expect("read the cell through the closure"); @@ -2232,3 +2233,282 @@ fn closure_keys_sharing_a_cell_stay_distinct_and_refused_writes_keep_entries() { ); assert_eq!(heap.collect().live_nodes, 5); } + +fn shared_current( + host: &mut HostContext<'_>, + left: ClosureRef, + right: ClosureRef, +) -> Option { + let through_left = heap::with_heap(host, |heap| heap.read_cell(left)).expect("left cell"); + let through_right = heap::with_heap(host, |heap| heap.read_cell(right)).expect("right cell"); + assert!( + same_recorded_cell(&through_left, &through_right), + "both closures read the same current edge: {through_left:?} vs {through_right:?}" + ); + through_left +} + +fn same_recorded_cell(left: &Option, right: &Option) -> bool { + match (left, right) { + ( + Some(CellValue::Scalar(Value::Float(left))), + Some(CellValue::Scalar(Value::Float(right))), + ) => left.to_bits() == right.to_bits(), + _ => left == right, + } +} + +/// Two closures share one cell. `false` replaces that cell's only object edge +/// in the same record. The old self-cycle stays live until the next collect. +#[test] +fn shared_upvalue_scalar_replaces_object_edge_and_collect_reclaims_only_that_cycle() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 6, + roots: 2, + edges: 6, + max_generation: 8, + }, + ) + .expect("install"); + let root_raw = publish_raw(&mut host); + let root = table_ref(&host, root_raw); + let independent_raw = publish_raw(&mut host); + let independent = table_ref(&host, independent_raw); + let frame = heap::with_heap(&mut host, |heap| heap.enter_roots(2)).expect("two roots"); + heap::with_heap(&mut host, |heap| heap.write_root(frame, 0, root)).expect("root the owner"); + heap::with_heap(&mut host, |heap| heap.write_root(frame, 1, independent)) + .expect("root the survivor"); + + let (left, right, cell) = heap::with_heap(&mut host, |heap| { + let left = heap.alloc_closure()?; + let right = heap.alloc_closure()?; + let cell = heap.alloc_upvalue()?; + heap.set_closure_edge(root, LEFT_KEY, left)?; + heap.set_closure_edge(root, RIGHT_KEY, right)?; + heap.set_upvalue_edge(left, cell)?; + heap.set_upvalue_edge(right, cell)?; + Ok((left, right, cell)) + }) + .expect("two closures, one cell"); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(left)).expect("left cell"), + cell + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(right)).expect("right cell"), + cell, + "both closures name one upvalue" + ); + + let original_raw = publish_raw(&mut host); + let original = table_ref(&host, original_raw); + heap::with_heap(&mut host, |heap| heap.write_upvalue(cell, original)) + .expect("capture the table"); + heap::with_heap(&mut host, |heap| { + heap.set_edge(original, BACK_KEY, original) + }) + .expect("self-cycle"); + let original_carrier = issue(&mut host, original); + let independent_carrier = issue(&mut host, independent); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(left)).expect("left object"), + original + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(right)).expect("right object"), + original, + "the live root keeps the shared object readable" + ); + let linked = heap::stats(&mut host).expect("linked"); + assert_eq!(linked.live_nodes, 6, "three tables, two closures, one cell"); + assert_eq!( + linked.live_edges, 6, + "two fields, two closure links, one current edge, one self-edge" + ); + assert_eq!( + linked.edge_slots, 6, + "the edge cap is the current record count" + ); + + heap::with_heap(&mut host, |heap| { + heap.write_scalar_upvalue(cell, Value::Bool(false)) + }) + .expect("replace the object edge with false"); + assert_eq!( + heap::stats(&mut host).expect("overwrite").live_edges, + linked.live_edges, + "a scalar overwrite does not add an edge" + ); + assert_eq!( + heap::stats(&mut host).expect("slots").edge_slots, + linked.edge_slots + ); + assert_eq!( + shared_current(&mut host, left, right), + Some(CellValue::Scalar(Value::Bool(false))) + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(left)).expect_err("not a table"), + HeapError::WrongKind + ); + + // Uncollected control. The old cycle is still live before a real collect. + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(original))).expect("still live")); + assert!( + token_open(&host, original_raw), + "token stays open without collect" + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&original_carrier))) + .expect("class"), + heap::GuestClass::Table(original) + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.edge(original, BACK_KEY)).expect("self-edge"), + Some(original) + ); + + let before_tokens = host.resource_count(); + assert_eq!(before_tokens, 3, "root, survivor, and the captured table"); + let report = heap::collect(&mut host).expect("collect the replaced cycle"); + let meter = heap::take_scan_meter(&mut host).expect("meter"); + assert_eq!(meter.mark_passes, 1, "the existing collector marks once"); + assert_eq!( + meter.outgoing_edge_checks, 5, + "mark walks the rooted edges and does not follow the scalar" + ); + assert_eq!( + meter.index_edge_checks, + u64::from(linked.live_edges) * 2, + "index walks the same edge vector twice" + ); + assert_eq!(report.live_nodes, 5, "only the self-cycle table is swept"); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(original))).expect("swept")); + assert!( + !token_open(&host, original_raw), + "the captured table token is closed" + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&original_carrier))) + .expect("class"), + heap::GuestClass::Unissued + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(root))).expect("root")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(left))).expect("left")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(right))).expect("right")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(cell))).expect("cell")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(independent))).expect("survivor")); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(left)).expect("left still shared"), + cell + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(right)).expect("right still shared"), + cell + ); + assert!(token_open(&host, root_raw)); + assert!(token_open(&host, independent_raw)); + assert_eq!(host.resource_count(), before_tokens - 1); + assert_eq!( + heap::stats(&mut host).expect("after sweep").live_edges, + linked.live_edges - 1, + "sweep drops the self-edge and keeps the current scalar record" + ); + assert_eq!( + shared_current(&mut host, left, right), + Some(CellValue::Scalar(Value::Bool(false))) + ); + + let neg_zero = -0.0_f64; + heap::with_heap(&mut host, |heap| { + heap.write_scalar_upvalue(cell, Value::Float(neg_zero)) + }) + .expect("store -0"); + match shared_current(&mut host, left, right) { + Some(CellValue::Scalar(Value::Float(stored))) => { + assert_eq!( + stored.to_bits(), + neg_zero.to_bits(), + "signed zero is stored as given" + ); + assert_ne!(stored.to_bits(), 0.0_f64.to_bits()); + assert_eq!(1.0 / stored, f64::NEG_INFINITY); + } + other => panic!("expected -0, got {other:?}"), + } + assert_eq!( + heap::stats(&mut host).expect("-0 edges").live_edges, + linked.live_edges - 1 + ); + + let nan_bits = 0x7ff8_0000_0000_0001_u64; + let nan = f64::from_bits(nan_bits); + heap::with_heap(&mut host, |heap| { + heap.write_scalar_upvalue(cell, Value::Float(nan)) + }) + .expect("store NaN"); + match shared_current(&mut host, left, right) { + Some(CellValue::Scalar(Value::Float(stored))) => { + assert_eq!(stored.to_bits(), nan_bits, "NaN bits are not rewritten"); + assert!(stored.is_nan()); + } + other => panic!("expected NaN, got {other:?}"), + } + assert_eq!( + heap::stats(&mut host).expect("NaN edges").live_edges, + linked.live_edges - 1 + ); + + heap::with_heap(&mut host, |heap| heap.clear_upvalue(cell)).expect("nil"); + assert_eq!(shared_current(&mut host, left, right), None); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(left)).expect_err("nil"), + HeapError::StaleHandle + ); + assert_eq!( + heap::stats(&mut host).expect("cleared").live_edges, + linked.live_edges - 2, + "nil deletes the current record" + ); + + heap::with_heap(&mut host, |heap| heap.write_upvalue(cell, independent)) + .expect("write the object back onto the same edge"); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(left)).expect("left object"), + independent + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(right)).expect("right object"), + independent + ); + let kept = shared_current(&mut host, left, right); + let edges_kept = heap::stats(&mut host).expect("restored").live_edges; + assert_eq!(edges_kept, linked.live_edges - 1); + for value in [ + Value::Null, + Value::Int(1), + Value::string("no"), + independent_carrier, + ] { + assert_eq!( + heap::with_heap(&mut host, |heap| heap.write_scalar_upvalue(cell, value)) + .expect_err("unsupported value"), + HeapError::WrongKind + ); + } + assert_eq!(shared_current(&mut host, left, right), kept); + assert_eq!( + heap::stats(&mut host).expect("refusal").live_edges, + edges_kept, + "a refused write does not add or delete an edge" + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.read_upvalue(right)).expect("not clobbered"), + independent + ); + }); +} From c4a4f9a2cabf8699baea7b11beed032ef449667d Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 18:58:39 +0800 Subject: [PATCH 078/225] feat(lua): store string and bytes on the shared upvalue edge Keep both carriers on the existing scalar current edge. Nil still clears that record, and other guest values are still refused before any write. (cherry picked from commit 7cf5b0f6c7806f71c7b603ec8cf2e7abb9760645) --- src/frontends/lua/heap/handle.rs | 8 +- src/frontends/lua/heap/table.rs | 25 ++- tests/luajit_heap_runtime/closure_graph.rs | 203 ++++++++++++++++++++- 3 files changed, 218 insertions(+), 18 deletions(-) diff --git a/src/frontends/lua/heap/handle.rs b/src/frontends/lua/heap/handle.rs index dabd534..46a9e93 100644 --- a/src/frontends/lua/heap/handle.rs +++ b/src/frontends/lua/heap/handle.rs @@ -8,8 +8,9 @@ pub enum HandleKind { Table, /// A closure node. It is not a callable value. Closure, - /// A shared upvalue node. Its current edge holds a table, a closure, or is - /// absent (nil). It has no open or closed flag. + /// A shared upvalue node. Its current edge holds a table, a closure, or a + /// scalar (boolean, binary64, string, or bytes), or is absent (nil). It has + /// no open or closed flag. Upvalue, } @@ -105,7 +106,8 @@ impl ClosureRef { /// Domain-checked reference to one shared upvalue node. /// /// Construction stays inside the heap. The node has no open or closed flag. -/// Its current edge is a table, a closure, or missing (nil). +/// Its current edge is a table, a closure, a scalar (boolean, binary64, string, +/// or bytes), or missing (nil). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct UpvalueRef { domain: u64, diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index fbc148d..6d28060 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -223,7 +223,8 @@ enum EdgeValue { }, /// One guest scalar in the same record as a table target. Field 0 on a /// table is the only key whose string is read as `__mode`. A cell current - /// edge may hold a boolean or binary64; that value is not a key. + /// edge may hold a boolean, binary64, string, or bytes; that value is not + /// a key. Scalar(Value), } @@ -250,7 +251,8 @@ pub enum CellValue { Table(TableRef), /// The cell currently holds a closure. Closure(ClosureRef), - /// The cell currently holds a boolean or binary64. Not a table key. + /// The cell currently holds a boolean, binary64, string, or bytes. Not a + /// table key. Scalar(Value), } @@ -762,7 +764,8 @@ impl LuaHeap { /// /// An existing current edge is overwritten. This does not insert a second /// record. A closure target uses [`Self::write_closure_upvalue`]. A - /// boolean or binary64 uses [`Self::write_scalar_upvalue`]. + /// boolean, binary64, string, or bytes value uses + /// [`Self::write_scalar_upvalue`]. pub fn write_upvalue(&mut self, cell: UpvalueRef, table: TableRef) -> Result<(), HeapError> { self.require_upvalue(cell)?; self.require_live(table)?; @@ -794,19 +797,23 @@ impl LuaHeap { ) } - /// Replaces the current edge with a boolean or binary64 scalar. + /// Replaces the current edge with a boolean, binary64, string, or bytes scalar. /// /// Same record as [`Self::write_upvalue`]. An existing edge is overwritten. /// Nil is not stored here; [`Self::clear_upvalue`] deletes that record. /// Any other guest value is refused at entry and leaves the stored edge /// unchanged. The number is stored as given: signed zero is not - /// canonicalized, and NaN is not treated as a table key. + /// canonicalized, and NaN is not treated as a table key. A string or bytes + /// value is stored as given. The two carriers are not converted or compared. pub fn write_scalar_upvalue( &mut self, cell: UpvalueRef, value: Value, ) -> Result<(), HeapError> { - if !matches!(value, Value::Bool(_) | Value::Float(_)) { + if !matches!( + value, + Value::Bool(_) | Value::Float(_) | Value::String(_) | Value::Bytes(_) + ) { return Err(HeapError::WrongKind); } self.require_upvalue(cell)?; @@ -847,9 +854,9 @@ impl LuaHeap { self.require_closure(found)?; Ok(Some(CellValue::Closure(found))) } - EdgeValue::Scalar(value @ (Value::Bool(_) | Value::Float(_))) => { - Ok(Some(CellValue::Scalar(value.clone()))) - } + EdgeValue::Scalar( + value @ (Value::Bool(_) | Value::Float(_) | Value::String(_) | Value::Bytes(_)), + ) => Ok(Some(CellValue::Scalar(value.clone()))), EdgeValue::Upvalue { .. } | EdgeValue::Scalar(_) => Err(HeapError::WrongKind), } } diff --git a/tests/luajit_heap_runtime/closure_graph.rs b/tests/luajit_heap_runtime/closure_graph.rs index 69ce697..25d45a0 100644 --- a/tests/luajit_heap_runtime/closure_graph.rs +++ b/tests/luajit_heap_runtime/closure_graph.rs @@ -2488,12 +2488,7 @@ fn shared_upvalue_scalar_replaces_object_edge_and_collect_reclaims_only_that_cyc let kept = shared_current(&mut host, left, right); let edges_kept = heap::stats(&mut host).expect("restored").live_edges; assert_eq!(edges_kept, linked.live_edges - 1); - for value in [ - Value::Null, - Value::Int(1), - Value::string("no"), - independent_carrier, - ] { + for value in [Value::Null, Value::Int(1), independent_carrier] { assert_eq!( heap::with_heap(&mut host, |heap| heap.write_scalar_upvalue(cell, value)) .expect_err("unsupported value"), @@ -2512,3 +2507,199 @@ fn shared_upvalue_scalar_replaces_object_edge_and_collect_reclaims_only_that_cyc ); }); } + +/// Two closures read one cell. UTF-8 text with an interior NUL and bytes with +/// NUL plus 0xFF stay on that cell's only current edge. Replacing a self-cycle +/// with the text leaves the cycle live until an explicit collect. +#[test] +fn shared_upvalue_text_and_bytes_keep_one_edge_and_collect_the_replaced_cycle() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 6, + roots: 1, + edges: 6, + max_generation: 8, + }, + ) + .expect("install"); + let root_raw = publish_raw(&mut host); + let root = table_ref(&host, root_raw); + let frame = heap::with_heap(&mut host, |heap| heap.enter_roots(1)).expect("one root"); + heap::with_heap(&mut host, |heap| heap.write_root(frame, 0, root)).expect("root the owner"); + + let (left, right, cell) = heap::with_heap(&mut host, |heap| { + let left = heap.alloc_closure()?; + let right = heap.alloc_closure()?; + let cell = heap.alloc_upvalue()?; + heap.set_closure_edge(root, LEFT_KEY, left)?; + heap.set_closure_edge(root, RIGHT_KEY, right)?; + heap.set_upvalue_edge(left, cell)?; + heap.set_upvalue_edge(right, cell)?; + Ok((left, right, cell)) + }) + .expect("two closures, one cell"); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(left)).expect("left cell"), + heap::with_heap(&mut host, |heap| heap.upvalue_of(right)).expect("right cell"), + "both closures name one upvalue" + ); + + let original_raw = publish_raw(&mut host); + let original = table_ref(&host, original_raw); + heap::with_heap(&mut host, |heap| heap.write_upvalue(cell, original)).expect("capture"); + heap::with_heap(&mut host, |heap| { + heap.set_edge(original, BACK_KEY, original) + }) + .expect("self-cycle"); + let linked = heap::stats(&mut host).expect("linked"); + assert_eq!(linked.live_nodes, 5, "two tables, two closures, one cell"); + assert_eq!( + linked.live_edges, 6, + "fields, closure links, current edge, self-edge" + ); + + let utf8 = [0x61_u8, 0x00, 0xC3, 0xA9]; + let text = Value::string(String::from_utf8(utf8.to_vec()).expect("utf-8")); + let text_arc = match &text { + Value::String(inner) => Arc::clone(inner), + other => panic!("text carrier is not a string: {other:?}"), + }; + heap::with_heap(&mut host, |heap| heap.write_scalar_upvalue(cell, text)) + .expect("store utf-8 text on the current edge"); + assert_eq!( + heap::stats(&mut host).expect("text overwrite").live_edges, + linked.live_edges, + "text replaces the object edge and does not add one" + ); + assert_shared_text(&mut host, left, right, &utf8, &text_arc); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(original))).expect("still live"), + "the replaced self-cycle stays live before collect" + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.edge(original, BACK_KEY)).expect("self-edge"), + Some(original) + ); + assert!( + token_open(&host, original_raw), + "token stays open without collect" + ); + + heap::collect(&mut host).expect("collect the replaced cycle"); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.alive(original))).expect("swept"), + "explicit collect drops the unreachable self-cycle" + ); + assert!( + !token_open(&host, original_raw), + "the captured table token is closed" + ); + assert!(token_open(&host, root_raw)); + assert_eq!( + heap::stats(&mut host).expect("after sweep").live_edges, + linked.live_edges - 1, + "sweep drops the self-edge and keeps the current text record" + ); + assert_shared_text(&mut host, left, right, &utf8, &text_arc); + + let raw = vec![0x00_u8, 0xFF, 0x5A]; + assert!( + std::str::from_utf8(&raw).is_err(), + "the byte carrier is not UTF-8" + ); + let bytes = Value::bytes(raw.to_vec()); + let bytes_arc = match &bytes { + Value::Bytes(inner) => Arc::clone(inner), + other => panic!("byte carrier is not bytes: {other:?}"), + }; + let after_sweep = heap::stats(&mut host).expect("before bytes").live_edges; + heap::with_heap(&mut host, |heap| heap.write_scalar_upvalue(cell, bytes)) + .expect("store bytes on the same edge"); + assert_eq!( + heap::stats(&mut host).expect("bytes overwrite").live_edges, + after_sweep, + "bytes replace the text record and do not add an edge" + ); + assert_shared_bytes(&mut host, left, right, &raw, &bytes_arc); + + let next = [0x62_u8, 0x00, 0x63]; + let replacement = Value::string(String::from_utf8(next.to_vec()).expect("utf-8")); + let replacement_arc = match &replacement { + Value::String(inner) => Arc::clone(inner), + other => panic!("replacement carrier is not a string: {other:?}"), + }; + heap::with_heap(&mut host, |heap| { + heap.write_scalar_upvalue(cell, replacement) + }) + .expect("replace bytes with another string"); + assert_eq!( + heap::stats(&mut host).expect("second text").live_edges, + after_sweep, + "another string overwrites the same record" + ); + assert_shared_text(&mut host, left, right, &next, &replacement_arc); + assert!( + !Arc::ptr_eq(&replacement_arc, &text_arc), + "the replacement is a different string carrier" + ); + + heap::with_heap(&mut host, |heap| heap.clear_upvalue(cell)).expect("nil"); + assert_eq!(shared_current(&mut host, left, right), None); + assert_eq!( + heap::stats(&mut host).expect("cleared").live_edges, + after_sweep - 1, + "nil deletes the current record" + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(left)).expect("left still shared"), + cell + ); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.upvalue_of(right)).expect("right still shared"), + cell + ); + }); +} + +fn assert_shared_text( + host: &mut HostContext<'_>, + left: ClosureRef, + right: ClosureRef, + bytes: &[u8], + stored: &Arc, +) { + match shared_current(host, left, right) { + Some(CellValue::Scalar(Value::String(text))) => { + assert!( + Arc::ptr_eq(&text, stored), + "the string carrier is stored as given" + ); + assert_eq!(text.as_bytes(), bytes, "every text byte is preserved"); + assert!(bytes.contains(&0), "the fixture contains an interior NUL"); + } + other => panic!("expected a string scalar, got {other:?}"), + } +} + +fn assert_shared_bytes( + host: &mut HostContext<'_>, + left: ClosureRef, + right: ClosureRef, + bytes: &[u8], + stored: &Arc>, +) { + match shared_current(host, left, right) { + Some(CellValue::Scalar(Value::Bytes(raw))) => { + assert!( + Arc::ptr_eq(&raw, stored), + "the bytes carrier is stored as given" + ); + assert_eq!(raw.as_slice(), bytes, "every byte is preserved"); + assert!(bytes.contains(&0) && bytes.contains(&0xFF)); + } + other => panic!("expected a bytes scalar, got {other:?}"), + } +} From 3f8e959bbc5131a09183e29207b38b10ae33d585 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 19:31:35 +0800 Subject: [PATCH 079/225] fix(lua): parse weak mode only from a table owner Field 0 is also an upvalue current edge. A string stored there is not a mode name, so the index does not scan it or allocate mode slots. --- src/frontends/lua/heap.rs | 2 +- src/frontends/lua/heap/table.rs | 1 + tests/luajit_heap_runtime/closure_graph.rs | 133 +++++++++++++++++++++ 3 files changed, 135 insertions(+), 1 deletion(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 2f67339..6dab26d 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -27,7 +27,7 @@ //! Closure and upvalue nodes use the same slots, edges, roots, meter, and //! sweep. A root slot holds a table, a closure, or an upvalue. A table field can point at //! a closure, a closure at one shared upvalue, and that upvalue at its current -//! table, closure, boolean, or binary64. A missing current edge is nil. Two closures can point at +//! table, closure, boolean, binary64, string, or bytes. A missing current edge is nil. Two closures can point at //! the same upvalue. A table entry key can be a table or a closure. Both use //! the same object-key record: slot, generation, and kind. Mark and sweep walk //! that record in the existing pass. A closure key is not a field id and is diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 6d28060..6daf969 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -1963,6 +1963,7 @@ impl LuaHeap { } if self.metatable_edges > 0 && edge.key == EdgeKey::Field(Self::MODE_FIELD) + && self.slots[from].kind == HandleKind::Table && let EdgeValue::Scalar(Value::String(mode)) = &edge.value { let mode = WeakMode::parse(mode, &mut self.scan.weak_mode_bytes); diff --git a/tests/luajit_heap_runtime/closure_graph.rs b/tests/luajit_heap_runtime/closure_graph.rs index 25d45a0..768ddce 100644 --- a/tests/luajit_heap_runtime/closure_graph.rs +++ b/tests/luajit_heap_runtime/closure_graph.rs @@ -2664,6 +2664,139 @@ fn shared_upvalue_text_and_bytes_keep_one_edge_and_collect_the_replaced_cycle() }); } +/// A strong metatable edge does not turn a shared cell's UTF-8 text into +/// `__mode`. Field 0 is also that cell's current edge. The text is longer than +/// a mode name, contains `k` and `v` before an interior NUL, and stays on the +/// cell. A later table mode string is the only parsed name. An independent +/// weak value is what the second collection removes. +#[test] +fn shared_upvalue_text_is_not_parsed_as_a_weak_mode() { + super::super::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 7, + roots: 2, + edges: 7, + max_generation: 8, + }, + ) + .expect("install"); + let anchor_raw = publish_raw(&mut host); + let anchor = table_ref(&host, anchor_raw); + let owner_raw = publish_raw(&mut host); + let owner = table_ref(&host, owner_raw); + let mode_raw = publish_raw(&mut host); + let mode_table = table_ref(&host, mode_raw); + let referent_raw = publish_raw(&mut host); + let referent = table_ref(&host, referent_raw); + let frame = heap::with_heap(&mut host, |heap| heap.enter_roots(2)).expect("two roots"); + heap::with_heap(&mut host, |heap| heap.write_root(frame, 0, anchor)).expect("root"); + heap::with_heap(&mut host, |heap| heap.write_root(frame, 1, owner)).expect("weak owner"); + + let (left, right, cell) = heap::with_heap(&mut host, |heap| { + let left = heap.alloc_closure()?; + let right = heap.alloc_closure()?; + let cell = heap.alloc_upvalue()?; + heap.set_closure_edge(anchor, LEFT_KEY, left)?; + heap.set_closure_edge(anchor, RIGHT_KEY, right)?; + heap.set_upvalue_edge(left, cell)?; + heap.set_upvalue_edge(right, cell)?; + heap.set_metatable(owner, Some(mode_table))?; + heap.set_edge(owner, 1, referent)?; + Ok((left, right, cell)) + }) + .expect("shared cell and strong metatable"); + + let mut raw = "é".repeat(24).into_bytes(); + raw.extend_from_slice(b"kv\0"); + raw.extend_from_slice("é".as_bytes()); + assert!(raw.len() > 32, "the cell text is longer than a mode name"); + let nul = raw + .iter() + .position(|byte| *byte == 0) + .expect("interior NUL"); + assert!( + raw[..nul].windows(2).any(|pair| pair == b"kv"), + "k and v precede the NUL a mode scan would stop on" + ); + let text = Value::string(String::from_utf8(raw.clone()).expect("utf-8")); + let text_arc = match &text { + Value::String(inner) => Arc::clone(inner), + other => panic!("text carrier is not a string: {other:?}"), + }; + heap::with_heap(&mut host, |heap| heap.write_scalar_upvalue(cell, text)) + .expect("store utf-8 text on the shared cell"); + assert_shared_text(&mut host, left, right, &raw, &text_arc); + + let _ = heap::take_scan_meter(&mut host).expect("clear setup meter"); + heap::collect(&mut host).expect("strong metatable collect"); + let strong = heap::take_scan_meter(&mut host).expect("strong meter"); + assert_eq!( + strong.weak_mode_bytes, 0, + "a cell string is not scanned as a mode name" + ); + assert_eq!( + strong.scratch.weak_modes_inited, 0, + "a cell string does not allocate weak-mode slots" + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(anchor))).expect("root")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(cell))).expect("cell")); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(referent))).expect("strong value"), + "a strong metatable does not collect the independent value" + ); + assert!(token_open(&host, referent_raw)); + assert_shared_text(&mut host, left, right, &raw, &text_arc); + + let mode = "v"; + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(mode_table, Value::string(mode)) + }) + .expect("set the table mode"); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(referent))).expect("before collect"), + "the weak value stays until an explicit collect" + ); + let before_weak = heap::stats(&mut host).expect("before weak collect"); + heap::collect(&mut host).expect("weak value collect"); + let weak = heap::take_scan_meter(&mut host).expect("weak meter"); + assert_eq!( + weak.weak_mode_bytes, + mode.len() as u64, + "the scan counts only the table mode name" + ); + assert!( + (raw.len() as u64) > weak.weak_mode_bytes, + "the cell text is not part of the mode count" + ); + assert_eq!( + weak.scratch.weak_modes_inited, + u64::from(before_weak.node_slots), + "the real mode allocates one entry per node slot" + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.alive(referent))).expect("swept"), + "the independent weak value is collected" + ); + assert!( + !token_open(&host, referent_raw), + "the weak value token is closed" + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(anchor))).expect("root kept")); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.upvalue_alive(cell))).expect("cell kept") + ); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(left))).expect("left")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.closure_alive(right))).expect("right")); + assert!(token_open(&host, anchor_raw)); + assert!(token_open(&host, owner_raw)); + assert!(token_open(&host, mode_raw)); + assert_shared_text(&mut host, left, right, &raw, &text_arc); + }); +} + fn assert_shared_text( host: &mut HostContext<'_>, left: ClosureRef, From 0866d02cd210f12361bb3fa3ecd5a219c69f579b Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 23:27:25 +0800 Subject: [PATCH 080/225] feat(lua): call a top-level named static link Match the import declaration span to its resolver binding and lower a direct zero-argument call as an implicit extern. A same-spelling inner binding stays a local. An extra RHS or a shadowed require is not a link. Map require offsets with one PhysicalLines cursor and lexer::newline_width. Do not recount LF only. --- src/frontends/lua/control.rs | 102 ++++++++++++- src/frontends/lua/imports.rs | 71 ++++++--- tests/compiler/compiler_lua_control_tests.rs | 143 ++++++++++++++++++- 3 files changed, 293 insertions(+), 23 deletions(-) diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs index 037c825..566e20d 100644 --- a/src/frontends/lua/control.rs +++ b/src/frontends/lua/control.rs @@ -54,7 +54,13 @@ //! comparisons. `continue` reaches the post, which adds the saved step to the //! hidden counter. `break` skips that post and leaves this `for`. //! +//! A top-level named static link is not a local value. The declaration span +//! selects the resolver binding; a direct zero-argument call of that binding +//! is an implicit extern. Another binding with the same spelling stays a +//! local. A non-call use or a rebinding is refused. +//! use super::ast::{self, BinOp, Block, Chunk, Expr, Name, NumberKind, Span, Stmt, UnOp}; +use super::imports::{self, ClassifiedLink}; use super::lexer; use super::parser; use super::resolve::{self, LexicalLimitKind, Resolution, ResolveError}; @@ -98,18 +104,22 @@ pub(super) fn lower_source_with( ), )); } + let links = imports::top_level_links(&chunk); let mut lower = Lower::new( source, &resolution, holds, label_loop_owners(&chunk, &resolution), + links, ); let stmts = if needs_dispatch(&chunk) { lower.lower_dispatch(&chunk)? } else { lower.lower_direct(&chunk)? }; - Ok(lower.builder.finish(stmts)) + let mut ir = lower.builder.finish(stmts); + ir.implicit_extern_names = lower.externs; + Ok(ir) } struct Lower<'a> { @@ -128,6 +138,8 @@ struct Lower<'a> { holds: Option<&'a HostCallResolver<'a>>, label_loops: Vec>, pending_labels: Vec, + link_by_binding: Vec>, + externs: Vec, } #[derive(Clone, Copy)] @@ -179,9 +191,24 @@ impl<'a> Lower<'a> { resolution: &'a Resolution, holds: Option<&'a HostCallResolver<'a>>, label_loops: Vec>, + links: Vec, ) -> Self { let slots = vec![None; resolution.bindings.len()]; let label_state = vec![None; resolution.labels.len()]; + let mut link_by_binding = vec![None; resolution.bindings.len()]; + for link in links { + if link.member.is_none() { + continue; + } + let Some(index) = resolution + .bindings + .iter() + .position(|binding| binding.function_id == 0 && binding.span == link.decl_span) + else { + continue; + }; + link_by_binding[index] = Some(link.alias); + } Self { source, resolution, @@ -198,6 +225,8 @@ impl<'a> Lower<'a> { holds, label_loops, pending_labels: Vec::new(), + link_by_binding, + externs: Vec::new(), } } @@ -958,6 +987,12 @@ impl<'a> Lower<'a> { if names[0].const_binding { return Err(self.fail(span, "const locals are not in this slice")); } + if let Some(alias) = self.link_alias_for_decl(&names[0].name).map(str::to_string) { + self.declare_link(&alias, names[0].name.span)?; + return Ok(CoreStmt::Noop { + line: self.line(span), + }); + } let init = self.expr(&values.exprs[0])?; let index = self.binding_for_local(&names[0].name, span)?; let slot = self.slot(index)?; @@ -983,6 +1018,9 @@ impl<'a> Lower<'a> { }; let expr = self.expr(&values.exprs[0])?; let index = self.binding_at(&name.bytes, name.span)?; + if self.link_alias(index).is_some() { + return Err(self.fail(span, "static link cannot be rebound in this slice")); + } let slot = self.slot(index)?; Ok(set_slot(slot, expr, self.line(span))) } @@ -1000,6 +1038,11 @@ impl<'a> Lower<'a> { Expr::Number { raw, kind, span } => self.number(raw, *kind, *span), Expr::Name { name, .. } => { let index = self.binding_at(&name.bytes, name.span)?; + if self.link_alias(index).is_some() { + return Err( + self.fail(name.span, "static link is only a direct call in this slice") + ); + } let slot = self.slot(index)?; Ok(CoreExpr::Var(slot)) } @@ -1030,10 +1073,67 @@ impl<'a> Lower<'a> { } Ok(acc) } + Expr::SuffixChain { base, steps, span } => self.direct_link_call(base, steps, *span), other => Err(self.fail(expr_span(other), "expression is not in this slice")), } } + fn direct_link_call( + &mut self, + base: &Expr, + steps: &[ast::Suffix], + span: Span, + ) -> Result { + let Expr::Name { name, .. } = base else { + return Err(self.fail(span, "expression is not in this slice")); + }; + let [ + ast::Suffix::Call { + args: ast::Args::List(list), + nav: false, + .. + }, + ] = steps + else { + return Err(self.fail(span, "expression is not in this slice")); + }; + if !list.exprs.is_empty() { + return Err(self.fail(span, "expression is not in this slice")); + } + let index = self.binding_at(&name.bytes, name.span)?; + let Some(alias) = self.link_alias(index).map(str::to_string) else { + return Err(self.fail(span, "expression is not in this slice")); + }; + let func = self.declare_link(&alias, name.span)?; + Ok(CoreExpr::Call(func, Vec::new(), Vec::new(), None, None)) + } + + fn link_alias(&self, index: usize) -> Option<&str> { + self.link_by_binding.get(index)?.as_deref() + } + + fn link_alias_for_decl(&self, name: &Name) -> Option<&str> { + let index = self + .resolution + .bindings + .iter() + .position(|binding| binding.function_id == 0 && binding.span == name.span)?; + self.link_alias(index) + } + + fn declare_link(&mut self, alias: &str, span: Span) -> Result { + if let Some(index) = self.builder.function_index(alias) { + return Ok(index); + } + self.builder + .declare_function(alias, Some(0)) + .map_err(|error| self.fail(span, error.message))?; + self.externs.push(alias.to_string()); + self.builder + .function_index(alias) + .ok_or_else(|| self.fail(span, "static link was not declared")) + } + fn bin( &self, op: BinOp, diff --git a/src/frontends/lua/imports.rs b/src/frontends/lua/imports.rs index be68a3e..9398a06 100644 --- a/src/frontends/lua/imports.rs +++ b/src/frontends/lua/imports.rs @@ -3,31 +3,51 @@ //! Production `LuaPlugin` still uses the line scanner. This walk uses the //! parsed chunk so a string, comment, uncalled function, shadow, or ordinary //! call cannot enter the module graph. A named link binds the declared local -//! alias. Path mapping stays in Core, including an extensionless relative spec. +//! alias. One initializer is the whole shape: an extra RHS is not a link and +//! is not dropped. Path mapping stays in Core, including an extensionless +//! relative spec. -use super::ast::{Args, AssignTarget, Expr, Stmt, Suffix}; +use super::ast::{Args, AssignTarget, Expr, Span, Stmt, Suffix}; use super::lexer; use super::parser; use vm::{ImportClause, ModuleImport, NamedImport, ParseError, SourceError, SourcePathError}; -pub(super) fn static_module_imports(source: &str) -> Result, SourcePathError> { - let chunk = parser::parse_chunk(source.as_bytes()).map_err(syntax_to_path_error)?; - let mut imports = Vec::new(); - let mut lines = PhysicalLines { - source: source.as_bytes(), - offset: 0, - line: 1, - }; +pub(super) struct ClassifiedLink { + // The control lowerer matches this declaration span to a resolver binding. + // A second include of this file only scans imports and does not read it. + #[allow(dead_code)] + pub decl_span: Span, + pub alias: String, + pub spec: String, + pub member: Option, + name_start: u32, +} + +pub(super) fn top_level_links(chunk: &super::ast::Chunk) -> Vec { + let mut links = Vec::new(); let mut require_shadowed = false; for stmt in &chunk.body.stmts { - if !require_shadowed && let Some(import) = local_static_link(stmt, &mut lines) { - imports.push(import); + if !require_shadowed && let Some(link) = classify_local(stmt) { + links.push(link); } if binds_require(stmt) { require_shadowed = true; } } - Ok(imports) + links +} + +pub(super) fn static_module_imports(source: &str) -> Result, SourcePathError> { + let chunk = parser::parse_chunk(source.as_bytes()).map_err(syntax_to_path_error)?; + let mut lines = PhysicalLines { + source: source.as_bytes(), + offset: 0, + line: 1, + }; + Ok(top_level_links(&chunk) + .into_iter() + .map(|link| module_import(&mut lines, link)) + .collect()) } fn syntax_to_path_error(err: lexer::SyntaxError) -> SourcePathError { @@ -37,32 +57,43 @@ fn syntax_to_path_error(err: lexer::SyntaxError) -> SourcePathError { ))) } -fn local_static_link(stmt: &Stmt, lines: &mut PhysicalLines<'_>) -> Option { +fn classify_local(stmt: &Stmt) -> Option { let Stmt::Local { names, values, .. } = stmt else { return None; }; let [local_name] = names.as_slice() else { return None; }; - let [value, ..] = values.exprs.as_slice() else { + // One value only. `local alias = require(...).tag, side_effect()` is not + // a link, so the extra call is not removed from the statement. + let [value] = values.exprs.as_slice() else { return None; }; let link = require_link(value)?; - let alias = utf8_bytes(&local_name.name.bytes)?; + Some(ClassifiedLink { + decl_span: local_name.name.span, + alias: utf8_bytes(&local_name.name.bytes)?, + spec: link.spec, + member: link.member, + name_start: link.name_start, + }) +} + +fn module_import(lines: &mut PhysicalLines<'_>, link: ClassifiedLink) -> ModuleImport { let clause = match link.member { - None => ImportClause::Namespace(alias), + None => ImportClause::Namespace(link.alias), Some(member) => ImportClause::Named(vec![NamedImport { // Core binds this local name. The export stays in `imported`, // matching the line scanner's declared-name split. imported: member, - local: alias, + local: link.alias, }]), }; - Some(ModuleImport { + ModuleImport { spec: link.spec, line: lines.line_at(link.name_start), clause, - }) + } } struct RequireLink { diff --git a/tests/compiler/compiler_lua_control_tests.rs b/tests/compiler/compiler_lua_control_tests.rs index 0994ec2..aa177f9 100644 --- a/tests/compiler/compiler_lua_control_tests.rs +++ b/tests/compiler/compiler_lua_control_tests.rs @@ -18,6 +18,8 @@ use common::*; mod ast; #[path = "../../src/frontends/lua/control.rs"] mod control; +#[path = "../../src/frontends/lua/imports.rs"] +mod imports; #[allow(dead_code)] #[path = "../../src/frontends/lua/lexer.rs"] mod lexer; @@ -81,10 +83,10 @@ impl SourcePlugin for ControlLuaPlugin { fn parse_module_imports( &self, - _source: &str, + source: &str, _path: &Path, ) -> Result, vm::SourcePathError> { - Ok(Vec::new()) + imports::static_module_imports(source) } } @@ -3579,3 +3581,140 @@ end assert!(String::from_utf8_lossy(&output.stderr).contains("LOAD_REJECT")); } } + +const NAMED_LINK_CALL: &str = + "local different = require(\"./present.rss\").tag\nreturn different()\n"; + +fn write_named_link(label: &str, source: &str) -> PathBuf { + let root = namespace_case_root(&format!("lua_control_{label}")); + fs::write(root.join("present.rss"), "pub fn tag() { 41 }\n").expect("present module"); + let path = root.join("main.lua"); + fs::write(&path, source).unwrap_or_else(|error| panic!("{label}: write main.lua: {error}")); + path +} + +fn run_named_link(label: &str, source: &str) -> Vec { + let path = write_named_link(label, source); + let compiled = + compile_source_file_with_options(&path, candidate_options()).unwrap_or_else(|error| { + panic!("{label}: named static link call was not connected: {error}") + }); + let mut vm = Vm::new_with_jit_config( + compiled.program, + JitConfig { + enabled: false, + hot_loop_threshold: 8, + max_trace_len: 256, + }, + ); + vm.set_fuel_check_interval(FUEL_CHECK_INTERVAL) + .unwrap_or_else(|error| panic!("{label}: fuel interval: {error}")); + vm.set_fuel(FUEL_BUDGET); + let status = vm + .run() + .unwrap_or_else(|error| panic!("{label}: vm run failed: {error}")); + assert_eq!(status, VmStatus::Halted, "{label}: status"); + let stack = vm.stack().to_vec(); + eprintln!("LUA_CONTROL label={label} named_link_stack={stack:?}"); + stack +} + +#[test] +fn named_static_link_call_returns_rss_export() { + // LuaJIT does not run RSS. This path is the control plugin, the AST import + // scan, Core's file graph, and Vm::run. + let stack = run_named_link("named_link_call", NAMED_LINK_CALL); + assert_eq!( + stack, + vec![Value::Int(41)], + "named static link call must return the RSS export" + ); +} + +#[test] +fn named_static_link_ignores_shadowed_spelling() { + let source = "\ +local different = require(\"./present.rss\").tag +do + local different = 7 + different = different + 1 +end +return different() +"; + let stack = run_named_link("named_link_shadow", source); + assert_eq!(stack, vec![Value::Int(41)]); +} + +#[test] +fn inner_same_spelling_call_is_not_the_static_link() { + let source = "\ +local different = require(\"./present.rss\").tag +do + local different = 7 + return different() +end +"; + expect_link_refusal( + "named_link_inner_call", + source, + "expression is not in this slice", + ); +} + +#[test] +fn static_link_value_and_rebinding_are_refused() { + expect_link_refusal( + "named_link_value", + "local different = require(\"./present.rss\").tag\nreturn different\n", + "static link is only a direct call in this slice", + ); + expect_link_refusal( + "named_link_rebind", + "local different = require(\"./present.rss\").tag\ndifferent = 7\nreturn different()\n", + "static link cannot be rebound in this slice", + ); +} + +#[test] +fn extra_rhs_and_shadowed_require_are_not_static_links() { + let extra = + "local different = require(\"./present.rss\").tag, side_effect()\nreturn different()\n"; + assert!( + imports::static_module_imports(extra) + .expect("scan extra rhs") + .is_empty() + ); + expect_link_refusal( + "named_link_extra_rhs", + extra, + "this slice lowers one local and one initializer", + ); + let shadowed = "\ +local require = 1 +local different = require(\"./present.rss\").tag +return different() +"; + assert!( + imports::static_module_imports(shadowed) + .expect("scan shadowed require") + .is_empty() + ); + expect_link_refusal( + "named_link_shadowed_require", + shadowed, + "expression is not in this slice", + ); +} + +fn expect_link_refusal(label: &str, source: &str, message: &str) { + let path = write_named_link(label, source); + let error = match compile_source_file_with_options(&path, candidate_options()) { + Err(error) => error, + Ok(_) => panic!("{label}: boundary must not run the RSS export"), + }; + let text = error.to_string(); + assert!( + text.contains(message), + "{label}: expected {message}, got {text}" + ); +} From 96d8a0b1e00173cd010a1a94d03f773afb7009b2 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 22:46:49 +0800 Subject: [PATCH 081/225] fix(lua): continue next from a weak-cleared key Sweep used to drop the whole edge when a weak value died, so next could not match the old key. The same record now keeps that key with no value. rawget is nil, a fresh next skips it, and next from the old key returns the next live entry or one nil at the end. --- src/frontends/lua/heap/table.rs | 135 ++++- tests/luajit_heap_runtime/candidate.rs | 8 +- .../value_boundary_tests.rs | 470 +++++++++++++++++- 3 files changed, 592 insertions(+), 21 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 6daf969..34c3493 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -124,13 +124,15 @@ pub struct HeapStats { pub live_nodes: u32, /// Root slots currently holding a handle. pub live_roots: u32, - /// Table-entry records currently stored. + /// Table-entry records that still hold a value. A weak-cleared cursor is + /// stored, but it is not a live entry. pub live_edges: u32, /// Slot vector length. Free and retired slots still occupy it. pub node_slots: u32, /// Root vector length. pub root_slots: u32, - /// Edge vector length. + /// Edge vector length, including weak-cleared cursors that no longer hold a + /// value. Quota uses this storage, not `live_edges`. pub edge_slots: u32, /// Completed collections. pub collections: u32, @@ -237,6 +239,12 @@ impl EdgeValue { Self::Scalar(_) => None, } } + + /// A weak-cleared entry left in place so `next` can continue from that key. + /// Nil is not otherwise stored: an explicit removal deletes the record. + fn is_cursor_gap(&self) -> bool { + matches!(self, Self::Scalar(Value::Null)) + } } /// Value stored in a shared cell's current edge. @@ -1235,7 +1243,7 @@ impl LuaHeap { edge.value = value; return Ok(()); } - if self.edges.len() >= self.limits.edges as usize { + if self.edges.len() >= self.limits.edges as usize && !self.reclaim_cursor_gap() { return Err(HeapError::EdgeCapacity); } self.edges.push(Edge { @@ -1247,6 +1255,20 @@ impl LuaHeap { Ok(()) } + /// Drops one valueless cursor so a real edge can use that storage. + /// Lua does not keep an old cursor valid across this structural change. + fn reclaim_cursor_gap(&mut self) -> bool { + let Some(index) = self + .edges + .iter() + .position(|edge| edge.value.is_cursor_gap()) + else { + return false; + }; + self.edges.remove(index); + true + } + /// Reads the table target of a direct field through either alias of `from`. pub fn edge(&self, from: TableRef, key: u32) -> Result, HeapError> { let key = EdgeKey::Field(key); @@ -1270,11 +1292,16 @@ impl LuaHeap { /// Next raw entry of `table` after `cursor`, in stored edge order. /// - /// `Value::Null` starts at the first edge. `None` is the end: one nil, not - /// an empty pair. A missing cursor and a non-guest key are errors, not the - /// end and not a restart. This walks `edges`, the same vector weak sweep - /// retains. It does not allocate another table and does not read a - /// metamethod. + /// `Value::Null` starts at the first valued edge. `None` is the end: one + /// nil, not an empty pair. A weak-cleared entry keeps its key in that order + /// with no value, so `rawget` is nil, a fresh `next` skips it, and `next` + /// with that key continues at the next valued entry or one nil at the end. + /// A missing key and a non-guest key are errors, not the end and not a + /// restart. An explicit removal drops the key. A later write of the same + /// key reuses the record. Inserting a different key may drop an old cursor + /// when edge storage is full; Lua does not keep cursors across that change. + /// This walks `edges`. It does not allocate another table and does not read + /// a metamethod. pub fn next_guest( &self, table: TableRef, @@ -1329,6 +1356,9 @@ impl LuaHeap { } continue; } + if edge.value.is_cursor_gap() { + continue; + } return Ok(Some(( self.guest_key(&edge.key)?, self.guest_edge_value(&edge.value)?, @@ -1739,7 +1769,11 @@ impl LuaHeap { HeapStats { live_nodes: self.live_nodes(), live_roots: self.live_roots(), - live_edges: self.edges.len() as u32, + live_edges: self + .edges + .iter() + .filter(|edge| !edge.value.is_cursor_gap()) + .count() as u32, node_slots: self.slots.len() as u32, root_slots: self.roots.len() as u32, edge_slots: self.edges.len() as u32, @@ -1842,6 +1876,10 @@ impl LuaHeap { let end = index.offsets[slot as usize + 1] as usize; self.scan.outgoing_edge_checks += (end - start) as u64; for &entry in &index.entries[start..end] { + let gap = self.edges[entry as usize].value.is_cursor_gap(); + if gap { + continue; + } let (object_key, value_target) = { let edge = &self.edges[entry as usize]; let object_key = match &edge.key { @@ -1930,6 +1968,9 @@ impl LuaHeap { let mut counts = vec![0u32; slot_count]; self.scan.scratch.index_counts_inited += counts.len() as u64; for edge in &self.edges { + if edge.value.is_cursor_gap() { + continue; + } if let Some(count) = counts.get_mut(edge.from as usize) { *count = count.saturating_add(1); } @@ -1952,6 +1993,9 @@ impl LuaHeap { self.scan.scratch.index_targets_inited += entries.len() as u64; let mut weak_modes = None; for (entry, edge) in self.edges.iter().enumerate() { + if edge.value.is_cursor_gap() { + continue; + } let from = edge.from as usize; if from >= slot_count { continue; @@ -2010,10 +2054,70 @@ impl LuaHeap { found.marked && found.kind == kind && found.generation == generation }) }; - // Strong endpoints of a marked owner were already marked. For weak - // edges, either dead object endpoint invalidates the whole entry. - // Closure and cell targets, and object keys of either stored kind, - // are checked in this same retain. + let weak_values: Vec = sweep + .iter() + .enumerate() + .map(|(index, found)| { + if !found.marked || found.kind != HandleKind::Table { + return false; + } + let Some((mt_slot, mt_generation)) = self.slots[index].metatable else { + return false; + }; + let Some(mt) = sweep.get(mt_slot as usize) else { + return false; + }; + if !mt.marked || mt.kind != HandleKind::Table || mt.generation != mt_generation { + return false; + } + self.edges.iter().any(|edge| { + if edge.from != mt_slot || edge.key != EdgeKey::Field(Self::MODE_FIELD) { + return false; + } + let EdgeValue::Scalar(Value::String(mode)) = &edge.value else { + return false; + }; + let mut ignored = 0u64; + WeakMode::parse(mode, &mut ignored).values + }) + }) + .collect(); + let guest_cursor = |key: &EdgeKey| match key { + EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, + EdgeKey::Field(_) => false, + EdgeKey::Object { + slot, + generation, + kind: HandleKind::Table, + } => typed(*slot, *generation, HandleKind::Table), + EdgeKey::Object { .. } => false, + }; + // A weak-value clear leaves the key in place with no value. The record + // is the cursor. It is not a second index. A dead key, a private field, + // or a strong edge is still removed. + for edge in &mut self.edges { + let owner = edge.from as usize; + if !is_marked(edge.from) || !weak_values.get(owner).copied().unwrap_or(false) { + continue; + } + let value_dead = match &edge.value { + EdgeValue::Scalar(_) => false, + EdgeValue::Table { slot, .. } => !is_marked(*slot), + EdgeValue::Closure { slot, generation } => { + !typed(*slot, *generation, HandleKind::Closure) + } + EdgeValue::Upvalue { slot, generation } => { + !typed(*slot, *generation, HandleKind::Upvalue) + } + }; + if !value_dead || !guest_cursor(&edge.key) { + continue; + } + edge.value = EdgeValue::Scalar(Value::Null); + } + // Strong endpoints of a marked owner were already marked. A valueless + // cursor stays when its key is still usable. Closure and cell targets, + // and object keys of either stored kind, are checked in this same retain. self.edges.retain(|edge| { is_marked(edge.from) && match &edge.value { @@ -2028,6 +2132,11 @@ impl LuaHeap { } && match &edge.key { EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, + EdgeKey::Object { + slot, + generation, + kind, + } if edge.value.is_cursor_gap() => typed(*slot, *generation, *kind), EdgeKey::Object { slot, .. } => is_marked(*slot), } }); diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 32d0176..fb6ef13 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1995,10 +1995,10 @@ impl Lower<'_> { /// The RHS is lowered before the new names are bound, so /// `local next, v = next(t)` still sees the builtin. /// - /// Chunk `return next(...)` is not this path. A missing or cleared cursor - /// is `invalid key to next`, not a restart. `next` walks the owner's - /// edges; that walk is the scan cost. Continuation from a cleared cursor - /// is not implemented. + /// Chunk `return next(...)` is not this path. A missing cursor is + /// `invalid key to next`, not a restart. A weak-cleared cursor is still + /// stored, so `next` continues from it. `next` walks the owner's edges; + /// that walk is the scan cost. fn lower_next_local( &mut self, span: ast::Span, diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index c2f8403..c31600c 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -4613,6 +4613,467 @@ fn assert_weak_next_identities(seen: &[ObservedTable]) { assert_ne!(seen[8].table, key); } +/// Weak-cleared cursor continuation. The candidate walk order is insertion +/// order, so each source plants one key kind first. LuaJIT hash order is not +/// assumed here; the locked oracle discovers it. This lowerer has no `if`, so +/// the two shapes stay separate sources rather than one runtime branch. +#[test] +fn lua_candidate_next_continues_from_a_cleared_weak_cursor() { + let text_cursor = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local dead = {} +dead.self = dead +local kept = {} +local key = {} +owner.gone = dead +owner[key] = kept +observe_table(dead, 0) +observe_table(kept, 0) +observe_table(key, 0) +local cursor, first = next(owner, nil) +observe_table(first, 0) +first = nil +dead = nil +collectgarbage("collect") +local raw = rawget(owner, cursor) +local fresh_key, fresh_value = next(owner, nil) +local cont_key, cont_value = next(owner, cursor) +observe_table(fresh_key, 0) +observe_table(fresh_value, 0) +observe_table(cont_key, 0) +observe_table(cont_value, 0) +observe_table(rawget(owner, cont_key), 0) +"#; + let cleared = run_next(&format!("{text_cursor}return type(raw)\n")); + assert_eq!(cleared.stack, &[Value::string("nil")]); + assert_eq!(cleared.counts, vec![2, 2, 2]); + assert_cleared_text_cursor(&cleared.tables); + let cursor_kind = run_next(&format!("{text_cursor}return type(cursor)\n")); + assert_eq!(cursor_kind.stack, &[Value::string("string")]); + assert_eq!(cursor_kind.counts, vec![2, 2, 2]); + + let table_cursor = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local dead = {} +dead.self = dead +local kept = {} +local key = {} +owner[key] = dead +owner.keep = kept +observe_table(dead, 0) +observe_table(kept, 0) +observe_table(key, 0) +local cursor, first = next(owner, nil) +observe_table(cursor, 0) +observe_table(first, 0) +first = nil +dead = nil +collectgarbage("collect") +local raw = rawget(owner, cursor) +local fresh_key, fresh_value = next(owner, nil) +local cont_key, cont_value = next(owner, cursor) +observe_table(fresh_value, 0) +observe_table(cont_value, 0) +"#; + let table_cleared = run_next(&format!("{table_cursor}return type(raw)\n")); + assert_eq!(table_cleared.stack, &[Value::string("nil")]); + assert_eq!(table_cleared.counts, vec![2, 2, 2]); + assert_cleared_table_cursor(&table_cleared.tables); + let successor = run_next(&format!("{table_cursor}return fresh_key\n")); + assert_eq!(successor.stack, &[Value::string("keep")]); + assert_eq!(successor.counts, vec![2, 2, 2]); + let successor_again = run_next(&format!("{table_cursor}return cont_key\n")); + assert_eq!(successor_again.stack, &[Value::string("keep")]); + assert_eq!(successor_again.counts, vec![2, 2, 2]); +} + +fn assert_cleared_text_cursor(seen: &[ObservedTable]) { + let dead = seen[0].table; + let kept = seen[1].table; + let key = seen[2].table; + assert_eq!(seen[3].table, dead, "first next value is the dying entry"); + assert_eq!(seen[4].table, key, "fresh next skips the cleared text key"); + assert_eq!(seen[5].table, kept); + assert_eq!( + seen[6].table, key, + "continuation returns the same successor" + ); + assert_eq!(seen[7].table, kept); + assert_eq!(seen[8].table, kept, "rawget agrees with the successor"); + assert_ne!(seen[4].table, dead); +} + +fn assert_cleared_table_cursor(seen: &[ObservedTable]) { + let dead = seen[0].table; + let kept = seen[1].table; + let key = seen[2].table; + assert_eq!(seen[3].table, key, "first next key is the rooted table key"); + assert_eq!(seen[4].table, dead); + assert_eq!( + seen[5].table, kept, + "fresh next skips the cleared table key" + ); + assert_eq!( + seen[6].table, kept, + "continuation returns the same successor" + ); + assert_ne!(seen[5].table, dead); +} + +/// No collection: the same cursor still returns the following live pair. +/// This is the control for the cleared-cursor fixture, not a second protocol. +#[test] +fn lua_candidate_next_without_collect_keeps_the_following_pair() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local dead = {} +local kept = {} +local key = {} +owner.gone = dead +owner[key] = kept +observe_table(dead, 0) +observe_table(kept, 0) +observe_table(key, 0) +local cursor, first = next(owner, nil) +local cont_key, cont_value = next(owner, cursor) +observe_table(first, 0) +observe_table(cont_key, 0) +observe_table(cont_value, 0) +observe_table(rawget(owner, cursor), 0) +"#; + let run = run_next(&format!("{source}return type(cursor)\n")); + assert_eq!(run.stack, &[Value::string("string")]); + assert_eq!(run.counts, vec![2, 2]); + let dead = run.tables[0].table; + let kept = run.tables[1].table; + let key = run.tables[2].table; + assert_eq!(run.tables[3].table, dead); + assert_eq!(run.tables[4].table, key); + assert_eq!(run.tables[5].table, kept); + assert_eq!(run.tables[6].table, dead, "rawget still sees the value"); +} + +/// A key that was never stored is an error. It must not restart at the first entry. +#[test] +fn lua_candidate_next_missing_key_is_not_a_restart() { + let table_key = "\ +local owner = {} +owner.keep = \"yes\" +local missing = {} +local k, v = next(owner, missing) +return k +"; + assert_invalid_next_key(table_key); + let text_key = "\ +local owner = {} +owner.keep = \"yes\" +local k, v = next(owner, \"missing\") +return k +"; + assert_invalid_next_key(text_key); +} + +fn assert_invalid_next_key(source: &str) { + let mut vm = candidate(source); + let error = vm.run().expect_err("a missing key is not a fresh next"); + match error { + vm::VmError::HostError(message) => { + assert!( + message.contains("invalid key to next"), + "missing key must not restart, got {message}" + ); + } + other => panic!("expected a host error, got {other}"), + } +} + +/// The cleared key is the last stored entry. Continuation is one nil, not a restart. +#[test] +fn lua_candidate_next_cleared_tail_is_one_nil() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local dead = {} +dead.self = dead +local kept = {} +local key = {} +owner[key] = kept +owner.gone = dead +observe_table(kept, 0) +observe_table(dead, 0) +local head, head_value = next(owner, nil) +local tail, tail_value = next(owner, head) +observe_table(head_value, 0) +observe_table(tail_value, 0) +tail_value = nil +dead = nil +collectgarbage("collect") +local cont, cont_value = next(owner, tail) +local fresh, fresh_value = next(owner, nil) +observe_table(fresh_value, 0) +observe_table(rawget(owner, head), 0) +"#; + let run = run_next(&format!("{source}return type(cont)\n")); + assert_eq!(run.stack, &[Value::string("nil")]); + assert_eq!(run.counts, vec![2, 2, 1, 2]); + let kept = run.tables[0].table; + let dead = run.tables[1].table; + assert_eq!(run.tables[2].table, kept); + assert_eq!(run.tables[3].table, dead); + assert_eq!( + run.tables[4].table, kept, + "fresh next still returns the head value" + ); + assert_eq!(run.tables[5].table, kept, "rawget of the live head agrees"); +} + +/// No new write. A rooted cursor still continues after a second collect. +#[test] +fn lua_candidate_next_cleared_cursor_survives_a_second_collect() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local dead = {} +dead.self = dead +local kept = {} +local key = {} +owner.gone = dead +owner[key] = kept +observe_table(kept, 0) +observe_table(key, 0) +local cursor, first = next(owner, nil) +first = nil +dead = nil +collectgarbage("collect") +collectgarbage("collect") +local raw = rawget(owner, cursor) +local cont_key, cont_value = next(owner, cursor) +observe_table(cont_key, 0) +observe_table(cont_value, 0) +"#; + let run = run_next(&format!("{source}return type(raw)\n")); + assert_eq!(run.stack, &[Value::string("nil")]); + assert_eq!(run.counts, vec![2, 2]); + let kept = run.tables[0].table; + let key = run.tables[1].table; + assert_eq!(run.tables[2].table, key); + assert_eq!(run.tables[3].table, kept); +} + +/// Writing the same key again fills the cleared record. Continuation still +/// reaches the original successor, so the write did not append a new edge. +#[test] +fn lua_candidate_next_reinsert_reuses_the_cleared_position() { + let source = r#" +local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local dead = {} +dead.self = dead +local kept = {} +local key = {} +owner.gone = dead +owner[key] = kept +observe_table(kept, 0) +observe_table(key, 0) +local cursor, first = next(owner, nil) +first = nil +dead = nil +collectgarbage("collect") +local restored = {} +owner.gone = restored +observe_table(restored, 0) +local cont_key, cont_value = next(owner, cursor) +observe_table(cont_key, 0) +observe_table(cont_value, 0) +observe_table(rawget(owner, cursor), 0) +"#; + let run = run_next(&format!("{source}return type(rawget(owner, cursor))\n")); + assert_eq!(run.stack, &[Value::string("table")]); + assert_eq!(run.counts, vec![2, 2]); + let kept = run.tables[0].table; + let key = run.tables[1].table; + let restored = run.tables[2].table; + assert_eq!( + run.tables[3].table, key, + "same-key write stays before the successor" + ); + assert_eq!(run.tables[4].table, kept); + assert_eq!(run.tables[5].table, restored); +} + +/// Quota, mark, and an explicit removal are not expressible as candidate +/// control flow. This heap fixture uses the same edge record and `next_guest`. +#[test] +fn weak_cleared_cursor_stays_in_the_edge_record() { + let limits = heap::HeapLimits { + nodes: 24, + roots: 8, + edges: 4, + max_generation: 16, + }; + let mut heap = heap::LuaHeap::new(limits); + let mt = heap.alloc().unwrap(); + let owner = heap.alloc().unwrap(); + let kept = heap.alloc().unwrap(); + let key = heap.alloc().unwrap(); + heap.set_mode_scalar(mt, Value::string("v")).unwrap(); + heap.set_metatable(owner, Some(mt)).unwrap(); + let frame = heap.enter_roots(3).unwrap(); + heap.write_root(frame, 0, owner).unwrap(); + heap.write_root(frame, 1, mt).unwrap(); + heap.write_root(frame, 2, kept).unwrap(); + + let dead = heap.alloc().unwrap(); + heap.set_object_edge(owner, key, dead).unwrap(); + heap.set_named_edge(owner, "keep", kept).unwrap(); + heap.issue_carrier(kept).unwrap(); + heap.collect(); + assert_eq!(heap.object_value(owner, key).unwrap(), Value::Null); + assert_eq!(heap.stats().live_edges, 2, "mode and the live entry"); + assert_eq!( + heap.stats().edge_slots, + 3, + "the cleared key still occupies storage" + ); + let key_value = heap.issue_carrier(key).unwrap(); + let continued = heap.next_guest(owner, &key_value).unwrap().unwrap(); + assert_eq!(continued.0, Value::string("keep")); + assert_eq!(continued.1, heap.issued_value(kept).unwrap()); + let fresh = heap.next_guest(owner, &Value::Null).unwrap().unwrap(); + assert_eq!(fresh.0, Value::string("keep")); + + heap.collect(); + assert!( + !heap.alive(key), + "a cleared object key is not marked on the next collect" + ); + let stale = heap.next_guest(owner, &key_value); + assert!( + stale.is_err(), + "a dead object is not a cursor and not a restart" + ); + let still = heap.next_guest(owner, &Value::Null).unwrap().unwrap(); + assert_eq!(still.0, Value::string("keep")); + + heap.set_named_scalar(owner, "keep", Value::Null).unwrap(); + assert_eq!( + heap.next_guest(owner, &Value::string("keep")).unwrap_err(), + heap::HeapError::NextCursorMissing, + "an explicit removal drops the cursor" + ); + assert!(heap.next_guest(owner, &Value::Null).unwrap().is_none()); +} + +#[test] +fn weak_cleared_cursors_yield_storage_under_insert_pressure() { + let limits = heap::HeapLimits { + nodes: 24, + roots: 8, + edges: 3, + max_generation: 16, + }; + let mut heap = heap::LuaHeap::new(limits); + let mt = heap.alloc().unwrap(); + let owner = heap.alloc().unwrap(); + let kept = heap.alloc().unwrap(); + let key = heap.alloc().unwrap(); + heap.set_mode_scalar(mt, Value::string("v")).unwrap(); + heap.set_metatable(owner, Some(mt)).unwrap(); + let first = heap.alloc().unwrap(); + let second = heap.alloc().unwrap(); + heap.set_named_edge(owner, "a", first).unwrap(); + heap.set_named_edge(owner, "b", second).unwrap(); + heap.issue_carrier(kept).unwrap(); + heap.issue_carrier(key).unwrap(); + let frame = heap.enter_roots(4).unwrap(); + heap.write_root(frame, 0, owner).unwrap(); + heap.write_root(frame, 1, mt).unwrap(); + heap.write_root(frame, 2, kept).unwrap(); + heap.write_root(frame, 3, key).unwrap(); + heap.collect(); + assert_eq!(heap.stats().edge_slots, 3); + assert_eq!(heap.stats().live_edges, 1); + heap.set_object_edge(owner, key, kept).unwrap(); + assert_eq!( + heap.stats().edge_slots, + 3, + "the new edge reused a cleared cursor" + ); + assert_eq!(heap.stats().live_edges, 2); + let lost_a = heap.next_guest(owner, &Value::string("a")); + let lost_b = heap.next_guest(owner, &Value::string("b")); + assert!( + lost_a.is_err() || lost_b.is_err(), + "pressure drops an old cursor instead of refusing the real edge" + ); + let survivor = heap.next_guest(owner, &Value::Null).unwrap().unwrap(); + assert_eq!(survivor.1, heap.issued_value(kept).unwrap()); + + let mut occupied = heap.stats().edge_slots; + for step in 0..6 { + let extra = heap.alloc().unwrap(); + let name = format!("n{step}"); + heap.set_named_edge(owner, &name, extra).unwrap(); + heap.collect(); + occupied = heap.stats().edge_slots; + assert!(occupied <= 3, "repeated clears stay inside the edge cap"); + } + assert_eq!(occupied, 3); +} + +#[test] +fn private_field_clear_does_not_leave_a_next_cursor() { + let mut heap = heap::LuaHeap::new(heap::HeapLimits { + nodes: 8, + roots: 4, + edges: 4, + max_generation: 4, + }); + let mt = heap.alloc().unwrap(); + let owner = heap.alloc().unwrap(); + let kept = heap.alloc().unwrap(); + let dead = heap.alloc().unwrap(); + heap.set_mode_scalar(mt, Value::string("v")).unwrap(); + heap.set_metatable(owner, Some(mt)).unwrap(); + heap.set_edge(owner, 1, dead).unwrap(); + heap.set_named_edge(owner, "keep", kept).unwrap(); + heap.issue_carrier(kept).unwrap(); + let frame = heap.enter_roots(3).unwrap(); + heap.write_root(frame, 0, owner).unwrap(); + heap.write_root(frame, 1, mt).unwrap(); + heap.write_root(frame, 2, kept).unwrap(); + heap.collect(); + assert_eq!(heap.edge(owner, 1).unwrap(), None); + assert_eq!(heap.stats().live_edges, 2); + assert_eq!( + heap.stats().edge_slots, + 2, + "a private field is removed, not a cursor" + ); + let fresh = heap.next_guest(owner, &Value::Null).unwrap().unwrap(); + assert_eq!(fresh.0, Value::string("keep")); + assert_eq!( + heap.next_guest(owner, &Value::string("missing")) + .unwrap_err(), + heap::HeapError::NextCursorMissing + ); +} + #[test] fn lua_candidate_next_on_empty_or_cleared_returns_one_nil() { let empty_key = run_next("local k, v = next({})\nreturn type(k)\n"); @@ -4792,10 +5253,11 @@ fn assert_not_lowered(source: &str) { /// `CallReturn::Many` from that non-yielding host, so the array transport /// cannot become two public returns without a second protocol. An /// unparenthesized tail `next` stays on the existing unsupported path. -/// `return (next(t))` still exports the first value. A cursor that is not a -/// live entry, including one whose entry was cleared, is `invalid key to -/// next`, not a restart. `next` walks the owner's edge vector; that walk is -/// the scan cost of this candidate. +/// `return (next(t))` still exports the first value. A key that was never +/// stored, or that an explicit removal dropped, is `invalid key to next`, +/// not a restart. A weak-cleared key stays in the edge vector and continues. +/// `next` walks the owner's edge vector; that walk is the scan cost of this +/// candidate. #[test] fn lua_candidate_review_tail_next_is_not_lowered() { let sources = [ From 5d3668979d602ad9752d86d20230dedf6e8d94b0 Mon Sep 17 00:00:00 2001 From: fffonion Date: Sun, 22 Nov 2026 23:57:42 +0800 Subject: [PATCH 082/225] fix(lua): reuse marked weak modes in sweep Shared metatables no longer rescan every edge to reparse __mode. One retain updates a cleared cursor and drops a dead edge, and the meter counts that storage pass once. --- src/frontends/lua/heap.rs | 17 ++- src/frontends/lua/heap/table.rs | 154 +++++++++++--------- tests/luajit_heap_runtime_tests.rs | 223 +++++++++++++++++++++++++++++ 3 files changed, 318 insertions(+), 76 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 6dab26d..8d5ea76 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -145,11 +145,14 @@ pub fn with_heap( body(heap) } -/// Host-side collection. One mark lists unreachable tokens. Each token is -/// closed through `HostContext::close_resource` before the heap sweep, so the -/// scope quota comes back in this same VM. Stored handles are not roots. +/// Host-side collection. One mark lists unreachable tokens and keeps the +/// parsed weak modes for sweep. Each token is closed through +/// `HostContext::close_resource` before the heap sweep, so the scope quota +/// comes back in this same VM. Stored handles are not roots. /// -/// Close checks the slot and generation captured at mark time. It does not +/// A close error returns before sweep. That snapshot is dropped with the +/// mark result, and the next collect marks again. Close checks the slot and +/// generation captured at mark time. It does not /// search the slot vector. For that exact stored token only, /// `ResourceAlreadyClosed` (slot not reused) and `ResourceStale` (slot reused) /// are retired: the identified slot is cleared and the sweep continues. A @@ -168,11 +171,11 @@ pub fn with_heap( /// A Pending result is an error. This type has no path that starts an /// asynchronous close, and this collector does not add one. pub fn collect(host: &mut HostContext) -> Result { - let doomed = with_heap(host, |heap| Ok(heap.mark_and_doomed_tokens()))?; - for token in doomed { + let marked = with_heap(host, |heap| Ok(heap.mark_and_doomed_tokens()))?; + for token in marked.tokens { retire_doomed_token(host, token)?; } - with_heap(host, |heap| Ok(heap.sweep_marked())) + with_heap(host, |heap| Ok(heap.sweep_marked(marked.modes))) } fn retire_doomed_token(host: &mut HostContext, token: table::DoomedToken) -> Result<(), HeapError> { diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 34c3493..9cceec0 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -405,9 +405,10 @@ struct Frame { /// that build the outgoing index (2E). `outgoing_edge_checks` counts records /// inspected from marked nodes. Each followed object target contributes /// separately to `node_slot_visits`; skipped weak targets do not. -/// `sweep_edge_checks` is the one edge filter, -/// and it is zero when every live node is marked. Adding those fields is not -/// a total GC cost. +/// `sweep_edge_checks` is that one retain of stored records. It is zero when +/// every live node is marked. Sweep reads modes parsed during mark and does +/// not scan edges again to find `__mode`. Adding those fields is not a total +/// GC cost. /// /// A metatable is not in that edge vector. `metatable_edge_checks` counts /// stored metatable refs followed from marked nodes. A collect with none @@ -498,14 +499,28 @@ pub(super) struct DoomedToken { pub(super) generation: u32, } -/// Temporary outgoing-edge index for one mark. Dropped when mark returns. -/// Not stored on the heap, so it is not a second persistent graph. +/// Temporary outgoing-edge index for one mark. Offsets and entries drop when +/// mark returns. Parsed weak modes move to sweep for that same collect and +/// are not stored on the heap. struct OutgoingIndex { offsets: Vec, entries: Vec, weak_modes: Option>, } +/// Weak modes parsed while building the outgoing index. Sweep borrows this +/// for the same collect, then drops it. A close error before sweep drops it +/// with the mark result, so the next collect parses again. +pub(super) struct MarkSnapshot { + modes: Option>, +} + +/// Doomed host tokens, plus the modes sweep needs after those tokens close. +pub(super) struct DoomedMark { + pub(super) tokens: Vec, + pub(super) modes: MarkSnapshot, +} + #[derive(Clone, Copy, Default)] struct WeakMode { keys: bool, @@ -1678,12 +1693,14 @@ impl LuaHeap { true } - /// Marks once and returns unreachable stored tokens with their slots. - /// Does not release nodes. The caller closes those tokens, then - /// [`Self::sweep_marked`] uses this same mark. - pub(super) fn mark_and_doomed_tokens(&mut self) -> Vec { - self.mark_reachable(); - let doomed: Vec = self + /// Marks once and returns unreachable stored tokens with their slots, + /// plus the weak modes sweep needs after those tokens close. Does not + /// release nodes. A close error drops the modes with this result; the + /// next collect marks and parses again. [`Self::sweep_marked`] uses this + /// same mark and does not build another mode index. + pub(super) fn mark_and_doomed_tokens(&mut self) -> DoomedMark { + let modes = self.mark_reachable(); + let tokens: Vec = self .slots .iter() .enumerate() @@ -1697,8 +1714,8 @@ impl LuaHeap { }) .collect(); self.scan.node_slot_visits += self.slots.len() as u64; - self.scan.scratch.pending_close_pushed += doomed.len() as u64; - doomed + self.scan.scratch.pending_close_pushed += tokens.len() as u64; + DoomedMark { tokens, modes } } /// Non-moving mark from explicit roots, then one sweep of unmarked nodes. @@ -1709,8 +1726,8 @@ impl LuaHeap { /// which closes tokens before [`Self::sweep_marked`]. Calling this on a /// host heap would skip that close. pub fn collect(&mut self) -> CollectReport { - self.mark_reachable(); - self.sweep_marked() + let modes = self.mark_reachable(); + self.sweep_marked(modes) } /// Releases nodes the current mark did not reach. Does not mark again. @@ -1719,7 +1736,7 @@ impl LuaHeap { /// every unmarked live node is released, so remaining live nodes are the /// marked count. The report uses that count instead of walking the slot /// vector again. - pub(super) fn sweep_marked(&mut self) -> CollectReport { + pub(super) fn sweep_marked(&mut self, modes: MarkSnapshot) -> CollectReport { let mut swept = Vec::new(); let mut marked_nodes = 0u32; self.scan.node_slot_visits += self.slots.len() as u64; @@ -1732,7 +1749,7 @@ impl LuaHeap { } self.scan.scratch.dead_slots_pushed += swept.len() as u64; if !swept.is_empty() { - self.sweep_edges_once(); + self.sweep_edges_once(&modes); for index in swept { self.scan.node_slot_visits += 1; self.release_slot(index); @@ -1845,7 +1862,7 @@ impl LuaHeap { }) } - fn mark_reachable(&mut self) { + fn mark_reachable(&mut self) -> MarkSnapshot { self.scan.mark_passes += 1; self.scan.node_slot_visits += self.slots.len() as u64; for slot in &mut self.slots { @@ -1918,6 +1935,9 @@ impl LuaHeap { } } } + MarkSnapshot { + modes: index.weak_modes, + } } /// Follows one stored metatable ref. Absent refs are not edges and are @@ -2027,10 +2047,11 @@ impl LuaHeap { } } - /// One filter of the edge vector. Skipped when every live node is marked, - /// so an all-live collect does not walk edges again and does not build - /// the mark bitmap. - fn sweep_edges_once(&mut self) { + /// One retain of stored edge records. Skipped when every live node is + /// marked, so an all-live collect does not walk edges and does not build + /// the mark bitmap. Weak-value flags come from `modes`, already parsed + /// during mark. This does not scan edges to find `__mode`. + fn sweep_edges_once(&mut self, modes: &MarkSnapshot) { struct SweepSlot { marked: bool, kind: HandleKind, @@ -2047,6 +2068,8 @@ impl LuaHeap { .collect(); self.scan.node_slot_visits += sweep.len() as u64; self.scan.scratch.sweep_bitmap_inited += sweep.len() as u64; + // Storage records this retain will visit. A later removal does not + // add a second counted pass. self.scan.sweep_edge_checks += self.edges.len() as u64; let is_marked = |slot: u32| sweep.get(slot as usize).is_some_and(|found| found.marked); let typed = |slot: u32, generation: u32, kind: HandleKind| { @@ -2054,34 +2077,33 @@ impl LuaHeap { found.marked && found.kind == kind && found.generation == generation }) }; - let weak_values: Vec = sweep - .iter() - .enumerate() - .map(|(index, found)| { - if !found.marked || found.kind != HandleKind::Table { - return false; - } - let Some((mt_slot, mt_generation)) = self.slots[index].metatable else { - return false; - }; - let Some(mt) = sweep.get(mt_slot as usize) else { - return false; - }; - if !mt.marked || mt.kind != HandleKind::Table || mt.generation != mt_generation { - return false; - } - self.edges.iter().any(|edge| { - if edge.from != mt_slot || edge.key != EdgeKey::Field(Self::MODE_FIELD) { + let weak_values = match modes.modes.as_ref() { + // No stored weak mode: every owner is strong. Do not read + // metatable slots or edges to rediscover that. + None => Vec::new(), + Some(stored) => sweep + .iter() + .enumerate() + .map(|(index, found)| { + if !found.marked || found.kind != HandleKind::Table { return false; } - let EdgeValue::Scalar(Value::String(mode)) = &edge.value else { + let Some((mt_slot, mt_generation)) = self.slots[index].metatable else { return false; }; - let mut ignored = 0u64; - WeakMode::parse(mode, &mut ignored).values + let Some(mt) = sweep.get(mt_slot as usize) else { + return false; + }; + if !mt.marked || mt.kind != HandleKind::Table || mt.generation != mt_generation + { + return false; + } + // Mark already counted this lookup. Reading the stored + // flag is not another parse and is not an edge scan. + stored.get(mt_slot as usize).is_some_and(|mode| mode.values) }) - }) - .collect(); + .collect(), + }; let guest_cursor = |key: &EdgeKey| match key { EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, EdgeKey::Field(_) => false, @@ -2092,33 +2114,27 @@ impl LuaHeap { } => typed(*slot, *generation, HandleKind::Table), EdgeKey::Object { .. } => false, }; - // A weak-value clear leaves the key in place with no value. The record - // is the cursor. It is not a second index. A dead key, a private field, - // or a strong edge is still removed. - for edge in &mut self.edges { + // One pass updates a cleared cursor and drops a dead edge. A + // weak-value clear leaves the key in place with no value. That record + // is the cursor, not a second index. A dead key, a private field, or + // a strong edge is still removed. + self.edges.retain_mut(|edge| { let owner = edge.from as usize; - if !is_marked(edge.from) || !weak_values.get(owner).copied().unwrap_or(false) { - continue; - } - let value_dead = match &edge.value { - EdgeValue::Scalar(_) => false, - EdgeValue::Table { slot, .. } => !is_marked(*slot), - EdgeValue::Closure { slot, generation } => { - !typed(*slot, *generation, HandleKind::Closure) - } - EdgeValue::Upvalue { slot, generation } => { - !typed(*slot, *generation, HandleKind::Upvalue) + if is_marked(edge.from) && weak_values.get(owner).copied().unwrap_or(false) { + let value_dead = match &edge.value { + EdgeValue::Scalar(_) => false, + EdgeValue::Table { slot, .. } => !is_marked(*slot), + EdgeValue::Closure { slot, generation } => { + !typed(*slot, *generation, HandleKind::Closure) + } + EdgeValue::Upvalue { slot, generation } => { + !typed(*slot, *generation, HandleKind::Upvalue) + } + }; + if value_dead && guest_cursor(&edge.key) { + edge.value = EdgeValue::Scalar(Value::Null); } - }; - if !value_dead || !guest_cursor(&edge.key) { - continue; } - edge.value = EdgeValue::Scalar(Value::Null); - } - // Strong endpoints of a marked owner were already marked. A valueless - // cursor stays when its key is still usable. Closure and cell targets, - // and object keys of either stored kind, are checked in this same retain. - self.edges.retain(|edge| { is_marked(edge.from) && match &edge.value { EdgeValue::Table { slot, .. } => is_marked(*slot), diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index 8aa1cd5..d70f778 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -1557,3 +1557,226 @@ fn assert_type_mismatch(error: &heap::HeapError) { other => panic!("expected a scope close error, got {other:?}"), } } + +#[test] +fn shared_metatable_sweep_reuses_marked_modes() { + let mode = "xxv"; + let narrow = collect_shared_mode(4, 16, mode); + let more_owners = collect_shared_mode(16, 16, mode); + let more_edges = collect_shared_mode(4, 64, mode); + let strong = collect_shared_mode(16, 16, "s"); + + assert_eq!(narrow.bytes, mode.len() as u64, "mark parses the mode once"); + assert_eq!(more_owners.bytes, narrow.bytes); + assert_eq!(more_edges.bytes, narrow.bytes); + assert_eq!(strong.bytes, 1, "a non-weak mode is still parsed once"); + + assert_eq!(narrow.lookups, u64::from(narrow.owners)); + assert_eq!( + more_owners.lookups / narrow.lookups, + u64::from(more_owners.owners / narrow.owners), + "lookups grow with owners, not with owners times edges" + ); + assert_eq!(more_edges.lookups, narrow.lookups); + assert_eq!(strong.lookups, 0); + assert_eq!(strong.modes_inited, 0); + + assert_eq!(narrow.sweep, u64::from(narrow.edges)); + assert_eq!( + more_owners.sweep, narrow.sweep, + "extra owners do not add an edge sweep" + ); + assert_eq!( + more_edges.sweep / narrow.sweep, + u64::from(more_edges.edges / narrow.edges) + ); + assert_eq!(strong.sweep, u64::from(strong.edges)); + assert_eq!(narrow.index, narrow.sweep * 2); + assert_eq!(more_owners.index, narrow.index); + assert_eq!( + more_edges.index / narrow.index, + more_edges.sweep / narrow.sweep + ); + assert_eq!(narrow.outgoing, narrow.sweep); + assert_eq!(more_owners.outgoing, narrow.outgoing); + assert_eq!(more_edges.outgoing, more_edges.sweep); + + assert_eq!(narrow.modes_inited, u64::from(narrow.nodes)); + assert_eq!(more_edges.modes_inited, narrow.modes_inited); + assert!(more_owners.modes_inited > narrow.modes_inited); + + assert_cleared_cursor_reuses_the_dead_slot(); + assert_host_collect_keeps_the_marked_mode(); +} + +struct ModeSweep { + owners: u32, + edges: u32, + bytes: u64, + lookups: u64, + sweep: u64, + index: u64, + outgoing: u64, + modes_inited: u64, + nodes: u32, +} + +/// One shared metatable, `owners` marked tables, `edges` stored records, and +/// one dead node so sweep runs. Padding fields are written first, so the mode +/// string is the last edge. +fn collect_shared_mode(owners: u32, edges: u32, mode: &str) -> ModeSweep { + let mut heap = LuaHeap::new(HeapLimits { + nodes: owners + 2, + roots: owners + 1, + edges, + max_generation: 8, + }); + let mt = heap.alloc().unwrap(); + let mut owner_refs = Vec::new(); + for _ in 0..owners { + owner_refs.push(heap.alloc().unwrap()); + } + let _dead = heap.alloc().unwrap(); + let frame = heap.enter_roots(owners + 1).unwrap(); + heap.write_root(frame, 0, mt).unwrap(); + for (index, owner) in owner_refs.iter().enumerate() { + heap.write_root(frame, index as u32 + 1, *owner).unwrap(); + heap.set_metatable(*owner, Some(mt)).unwrap(); + } + for field in 1..edges { + heap.set_field_scalar(mt, field, Value::string("pad")) + .unwrap(); + } + heap.set_mode_scalar(mt, Value::string(mode)).unwrap(); + assert_eq!( + heap.stats().edge_slots, + edges, + "mode is the last stored edge" + ); + heap.collect(); + let meter = heap.take_scan_meter(); + ModeSweep { + owners, + edges, + bytes: meter.weak_mode_bytes, + lookups: meter.weak_mode_lookups, + sweep: meter.sweep_edge_checks, + index: meter.index_edge_checks, + outgoing: meter.outgoing_edge_checks, + modes_inited: meter.scratch.weak_modes_inited, + nodes: heap.stats().node_slots, + } +} + +fn assert_cleared_cursor_reuses_the_dead_slot() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 8, + roots: 4, + edges: 4, + max_generation: 8, + }); + let mt = heap.alloc().unwrap(); + let owner = heap.alloc().unwrap(); + let key = heap.alloc().unwrap(); + let kept = heap.alloc().unwrap(); + let dead = heap.alloc().unwrap(); + let frame = heap.enter_roots(4).unwrap(); + heap.write_root(frame, 0, mt).unwrap(); + heap.write_root(frame, 1, owner).unwrap(); + heap.write_root(frame, 2, key).unwrap(); + heap.write_root(frame, 3, kept).unwrap(); + heap.set_metatable(owner, Some(mt)).unwrap(); + heap.set_object_edge(owner, key, dead).unwrap(); + heap.set_named_edge(owner, "keep", kept).unwrap(); + heap.set_mode_scalar(mt, Value::string("v")).unwrap(); + heap.issue_carrier(kept).unwrap(); + assert_eq!(heap.stats().edge_slots, 3); + assert_eq!(heap.stats().live_edges, 3); + + heap.collect(); + let meter = heap.take_scan_meter(); + assert_eq!(meter.weak_mode_bytes, 1); + assert_eq!(meter.weak_mode_lookups, 1); + assert_eq!( + meter.sweep_edge_checks, 3, + "one pass over the stored records" + ); + assert_eq!(meter.index_edge_checks, 6); + assert_eq!(heap.object_value(owner, key).unwrap(), Value::Null); + assert_eq!( + heap.stats().edge_slots, + 3, + "the cleared key still occupies storage" + ); + assert_eq!(heap.stats().live_edges, 2, "mode and the live entry"); + assert!(!heap.alive(dead)); + + let reused = heap.alloc().unwrap(); + assert_eq!(reused.slot(), dead.slot()); + assert_ne!(reused.generation(), dead.generation()); + assert!(heap.alive(reused)); + assert!(!heap.alive(dead)); + + let key_value = heap.issue_carrier(key).unwrap(); + let continued = heap.next_guest(owner, &key_value).unwrap().unwrap(); + assert_eq!(continued.0, Value::string("keep")); + assert_eq!(continued.1, heap.issued_value(kept).unwrap()); +} + +fn assert_host_collect_keeps_the_marked_mode() { + with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 8, + roots: 4, + edges: 4, + max_generation: 8, + }, + ) + .expect("install"); + let mt_raw = publish_raw(&mut host); + let owner_raw = publish_raw(&mut host); + let key_raw = publish_raw(&mut host); + let kept_raw = publish_raw(&mut host); + let dead_raw = publish_raw(&mut host); + let mt = table_ref(&host, mt_raw); + let owner = table_ref(&host, owner_raw); + let key = table_ref(&host, key_raw); + let kept = table_ref(&host, kept_raw); + let dead = table_ref(&host, dead_raw); + heap::with_heap(&mut host, |heap| { + let frame = heap.enter_roots(4)?; + heap.write_root(frame, 0, mt)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, key)?; + heap.write_root(frame, 3, kept)?; + heap.set_metatable(owner, Some(mt))?; + heap.set_object_edge(owner, key, dead)?; + heap.set_named_edge(owner, "keep", kept)?; + heap.set_mode_scalar(mt, Value::string("v"))?; + Ok(()) + }) + .expect("shape"); + + heap::collect(&mut host).expect("host collect"); + let reused_raw = publish_raw(&mut host); + let reused = table_ref(&host, reused_raw); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.object_value(owner, key)?, Value::Null); + assert_eq!(heap.named_edge(owner, "keep")?, Some(kept)); + assert!(!heap.alive(dead)); + assert_eq!(reused.slot(), dead.slot()); + assert_ne!(reused.generation(), dead.generation()); + let meter = heap.take_scan_meter(); + assert_eq!(meter.weak_mode_bytes, 1); + assert_eq!(meter.weak_mode_lookups, 1); + assert_eq!(meter.sweep_edge_checks, 3); + assert_eq!(heap.stats().edge_slots, 3); + assert_eq!(heap.stats().live_edges, 2); + Ok(()) + }) + .expect("host sweep used the marked mode"); + }); +} From 8548f2310b5d220ee6962afe89a1e7b1f56aaca9 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 00:27:45 +0800 Subject: [PATCH 083/225] feat(lua): lower shared upvalue scalar reads and writes Zero-arg closures store bool, binary64, UTF-8 including NUL, and non-UTF-8 bytes on the existing cell edge. Replacing a self-cycle with false lets the real collector reclaim it. Nil still clears that edge. --- src/frontends/lua/heap/table.rs | 60 ++-- tests/luajit_heap_runtime/candidate.rs | 145 ++++++++- tests/luajit_heap_runtime/source_closure.rs | 343 +++++++++++++++++++- 3 files changed, 502 insertions(+), 46 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 9cceec0..4c12d7e 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -860,28 +860,11 @@ impl LuaHeap { /// /// `Ok(None)` is nil. `Err` means the closure, its cell, or the stored /// target is an invalid handle. A missing edge is not an invalid handle. - /// This does not call the closure. + /// This does not call the closure. The edge itself is decoded by + /// [`Self::current_edge`]. pub fn read_cell(&self, closure: ClosureRef) -> Result, HeapError> { let cell = self.upvalue_of(closure)?; - let Some(value) = self.stored_from(cell.slot(), &EdgeKey::Field(CURRENT_EDGE)) else { - return Ok(None); - }; - match value { - EdgeValue::Table { slot, generation } => { - let table = TableRef::table(self.domain, *slot, *generation); - self.require_live(table)?; - Ok(Some(CellValue::Table(table))) - } - EdgeValue::Closure { slot, generation } => { - let found = ClosureRef::closure(self.domain, *slot, *generation); - self.require_closure(found)?; - Ok(Some(CellValue::Closure(found))) - } - EdgeValue::Scalar( - value @ (Value::Bool(_) | Value::Float(_) | Value::String(_) | Value::Bytes(_)), - ) => Ok(Some(CellValue::Scalar(value.clone()))), - EdgeValue::Upvalue { .. } | EdgeValue::Scalar(_) => Err(HeapError::WrongKind), - } + self.current_edge(cell) } /// Reads the table currently stored through a closure's cell. @@ -890,9 +873,9 @@ impl LuaHeap { /// so this table adapter returns `StaleHandle`. [`Self::read_cell`] returns /// `None` for that nil. pub fn read_upvalue(&self, closure: ClosureRef) -> Result { - match self.read_cell(closure)? { - Some(CellValue::Table(table)) => Ok(table), - Some(CellValue::Closure(_) | CellValue::Scalar(_)) => Err(HeapError::WrongKind), + let cell = self.upvalue_of(closure)?; + match self.current_table(cell)? { + Some(table) => Ok(table), None => Err(HeapError::StaleHandle), } } @@ -963,8 +946,25 @@ impl LuaHeap { /// The table currently stored in a cell. /// /// `Ok(None)` is a missing current edge, which is nil. This does not go - /// through a closure. + /// through a closure. A scalar or closure edge is `WrongKind`, not a table + /// and not nil. The edge bytes are decoded only by [`Self::current_edge`]. pub fn current_table(&self, cell: UpvalueRef) -> Result, HeapError> { + match self.current_edge(cell)? { + Some(CellValue::Table(table)) => Ok(Some(table)), + None => Ok(None), + Some(_) => Err(HeapError::WrongKind), + } + } + + /// Decodes the one current edge of an upvalue. + /// + /// The caller passes an upvalue, and this checks that handle before + /// reading. A missing edge is nil. Table, boolean, binary64, string, + /// bytes, and closure stay distinct carriers. An integer or any other + /// scalar is `WrongKind` and is not turned into a number or a table. + /// This reads the existing edge record. It does not allocate a value slot + /// or a root. + pub fn current_edge(&self, cell: UpvalueRef) -> Result, HeapError> { self.require_upvalue(cell)?; let Some(value) = self.stored_from(cell.slot(), &EdgeKey::Field(CURRENT_EDGE)) else { return Ok(None); @@ -973,9 +973,17 @@ impl LuaHeap { EdgeValue::Table { slot, generation } => { let table = TableRef::table(self.domain, *slot, *generation); self.require_live(table)?; - Ok(Some(table)) + Ok(Some(CellValue::Table(table))) } - _ => Err(HeapError::WrongKind), + EdgeValue::Closure { slot, generation } => { + let found = ClosureRef::closure(self.domain, *slot, *generation); + self.require_closure(found)?; + Ok(Some(CellValue::Closure(found))) + } + EdgeValue::Scalar( + value @ (Value::Bool(_) | Value::Float(_) | Value::String(_) | Value::Bytes(_)), + ) => Ok(Some(CellValue::Scalar(value.clone()))), + EdgeValue::Upvalue { .. } | EdgeValue::Scalar(_) => Err(HeapError::WrongKind), } } diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index fb6ef13..299dd2b 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1185,14 +1185,18 @@ fn read_cell(call: &mut OwnedHostCall<'_>) -> Result { with_capture(&mut call.vm().host_context(), |graph| graph.reads += 1)?; let current = heap::with_heap(&mut call.vm().host_context(), |heap| { let cell = heap.cell_edge(table)?; - heap.current_table(cell) + heap.current_edge(cell) }) .map_err(heap_error)?; match current { - Some(table) => heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.issued_value(table) - }) - .map_err(heap_error), + Some(heap::CellValue::Table(table)) => { + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.issued_value(table) + }) + .map_err(heap_error) + } + Some(heap::CellValue::Scalar(value)) => Ok(value), + Some(heap::CellValue::Closure(_)) => Err(host_fault("Lua cell holds a closure")), None => Ok(Value::Null), } } @@ -1207,16 +1211,25 @@ fn write_cell(call: &mut OwnedHostCall<'_>) -> Result { } }; let table = issued_table(&mut call.vm().host_context(), &table)?; - let next_table = match &next { - Value::Null => None, - other => Some(issued_table(&mut call.vm().host_context(), other)?), + enum NextWrite { + Clear, + Scalar(Value), + Table(heap::TableRef), + } + let next_write = match next { + Value::Null => NextWrite::Clear, + value @ (Value::Bool(_) | Value::Float(_) | Value::String(_) | Value::Bytes(_)) => { + NextWrite::Scalar(value) + } + other => NextWrite::Table(issued_table(&mut call.vm().host_context(), &other)?), }; let before = root_count(&mut call.vm().host_context())?; heap::with_heap(&mut call.vm().host_context(), |heap| { let cell = heap.cell_edge(table)?; - match next_table { - None => heap.clear_upvalue(cell), - Some(next) => heap.write_upvalue(cell, next), + match next_write { + NextWrite::Clear => heap.clear_upvalue(cell), + NextWrite::Scalar(value) => heap.write_scalar_upvalue(cell, value), + NextWrite::Table(next) => heap.write_upvalue(cell, next), } }) .map_err(heap_error)?; @@ -2419,15 +2432,29 @@ impl Lower<'_> { }, ] if targets.len() == 1 && values.exprs.len() == 1 - && self.target_is_binding(&targets[0], binding) - && matches!( + && self.target_is_binding(&targets[0], binding) => + { + let span = *span; + if let Some(literal) = self.proven_scalar_literal(&values.exprs[0])? { + return self + .call(WRITE_CELL, vec![Expr::Var(captured), literal]) + .map_err(|_| self.unsupported(span)); + } + if matches!(values.exprs[0], ast::Expr::Nil { .. }) { + return self + .call(WRITE_CELL, vec![Expr::Var(captured), Expr::Null]) + .map_err(|_| self.unsupported(span)); + } + if matches!( values.exprs[0], ast::Expr::Table { ref fields, .. } if fields.is_empty() - ) => - { - let next = self.call(NEW_TABLE, vec![])?; - self.call(WRITE_CELL, vec![Expr::Var(captured), next]) - .map_err(|_| self.unsupported(*span)) + ) { + let next = self.call(NEW_TABLE, vec![])?; + return self + .call(WRITE_CELL, vec![Expr::Var(captured), next]) + .map_err(|_| self.unsupported(span)); + } + Err(self.unsupported(span)) } [other, ..] => Err(self.unsupported(stmt_span(other))), [] => Err(self.unsupported(func.span)), @@ -2463,12 +2490,94 @@ impl Lower<'_> { self.capture_envelopes.get(&binding).copied() } + fn proven_scalar_literal(&self, expr: &ast::Expr) -> Result, ParseError> { + match expr { + ast::Expr::Bool { value, .. } => Ok(Some(Expr::Bool(*value))), + ast::Expr::Number { raw, kind, span } => { + Ok(Some(self.proven_number(raw, *kind, *span)?)) + } + ast::Expr::Unary { + op: ast::UnOp::Neg, + expr, + span, + } => Ok(Some(self.neg_zero(expr, *span)?)), + ast::Expr::String { bytes, .. } => Ok(Some(self.string_literal(bytes))), + _ => Ok(None), + } + } + + /// Decimal integer or float only. Hex, binary, and 64-bit suffixes stay + /// outside this slice, so a raw token is not reinterpreted. + fn proven_number( + &self, + raw: &str, + kind: ast::NumberKind, + span: ast::Span, + ) -> Result { + match kind { + ast::NumberKind::Integer | ast::NumberKind::Float => raw + .parse::() + .map(Expr::Float) + .map_err(|_| self.unsupported(span)), + ast::NumberKind::HexInteger + | ast::NumberKind::HexFloat + | ast::NumberKind::Binary + | ast::NumberKind::Signed64 + | ast::NumberKind::Unsigned64 + | ast::NumberKind::Imaginary => Err(self.unsupported(span)), + } + } + + /// Only unary minus of a positive zero. The result keeps the negative-zero + /// bits. Any other negation is not this slice. + fn neg_zero(&self, expr: &ast::Expr, span: ast::Span) -> Result { + let ast::Expr::Number { raw, kind, .. } = expr else { + return Err(self.unsupported(span)); + }; + let value = match self.proven_number(raw, *kind, span)? { + Expr::Float(value) => value, + _ => return Err(self.unsupported(span)), + }; + if value != 0.0 || value.is_sign_negative() { + return Err(self.unsupported(span)); + } + Ok(Expr::Float(-0.0)) + } + + /// UTF-8, including an interior NUL, stays a string. Any other byte stays + /// bytes. The two carriers are not converted. + fn string_literal(&self, bytes: &[u8]) -> Expr { + match std::str::from_utf8(bytes) { + Ok(text) => Expr::String(text.to_string()), + Err(_) => Expr::Bytes(bytes.to_vec()), + } + } + fn lower_assign( &mut self, span: ast::Span, target: &ast::AssignTarget, value: &ast::Expr, ) -> Result<(), ParseError> { + if let ast::AssignTarget::Name(name) = target + && let Some(literal) = self.proven_scalar_literal(value)? + { + let anchor = self + .anchor_of_name(name) + .ok_or_else(|| self.unsupported(span))?; + let written = self.call(WRITE_CELL, vec![Expr::Var(anchor), literal])?; + self.emit_ignored(written, self.line(span))?; + if let Some(slot) = self.locals.get(&name.bytes).copied() { + self.live_locals.retain(|local| *local != slot); + self.stmts.push(Stmt::Assign { + kind: AssignmentKind::Set, + index: slot, + expr: Expr::Null, + line: self.line(span), + }); + } + return Ok(()); + } match (target, value) { (ast::AssignTarget::Name(name), ast::Expr::Nil { .. }) => { let slot = self diff --git a/tests/luajit_heap_runtime/source_closure.rs b/tests/luajit_heap_runtime/source_closure.rs index f7f5f09..504ea20 100644 --- a/tests/luajit_heap_runtime/source_closure.rs +++ b/tests/luajit_heap_runtime/source_closure.rs @@ -6,6 +6,8 @@ //! mutable capture. Host observers record handles and booleans; they do not //! root, collect, call the closures, or write the cell. +use std::fs; +use std::path::{Path, PathBuf}; use std::sync::{Arc, OnceLock}; use vm::{ @@ -23,6 +25,7 @@ const NOTE_FN: &str = "lua_host::note_fn"; const NOTE_PHASE: &str = "lua_host::note_phase"; const NOTE_NIL: &str = "lua_host::note_nil"; const NOTE_GRAPH: &str = "lua_host::note_graph"; +const NOTE_SCALAR: &str = "lua_host::note_scalar"; const SOURCE: &str = r#" local mt = {} @@ -77,6 +80,10 @@ struct Phase { next: bool, held_alive: bool, orphan_alive: bool, + /// Tag 1 is a table whose `self` edge points at itself. + self_cycle: bool, + /// Collections already performed when this phase was observed. + collections: u32, } /// Read-only closure and cell snapshot. Not a root and not a publication. @@ -96,6 +103,7 @@ struct Obs { phases: Vec, nils: Vec, graphs: Vec, + scalars: Vec, } struct ObserveTable; @@ -103,6 +111,7 @@ struct NoteFn; struct NotePhase; struct NoteNil; struct NoteGraph; +struct NoteScalar; fn catalog() -> &'static Arc { static CATALOG: OnceLock> = OnceLock::new(); @@ -141,6 +150,11 @@ fn catalog() -> &'static Arc { vec![HostParamSchema::value("id", HostTypeSchema::Float)], HostTypeSchema::Float, )); + builder.function(HostFunctionSchema::with_return( + NOTE_SCALAR, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::Float, + )); Arc::new(builder.build().expect("shared-closure catalog")) }) } @@ -166,7 +180,14 @@ impl SourcePlugin for Plugin { } fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { - for name in [OBSERVE, NOTE_FN, NOTE_PHASE, NOTE_NIL, NOTE_GRAPH] { + for name in [ + OBSERVE, + NOTE_FN, + NOTE_PHASE, + NOTE_NIL, + NOTE_GRAPH, + NOTE_SCALAR, + ] { let function = catalog.function(name).expect("observer schema"); registry .register_exact_owned( @@ -186,6 +207,7 @@ fn ctor_box(name: &str) -> Box { NOTE_PHASE => Box::new(NotePhase), NOTE_NIL => Box::new(NoteNil), NOTE_GRAPH => Box::new(NoteGraph), + NOTE_SCALAR => Box::new(NoteScalar), _ => unreachable!("observer name"), } } @@ -275,7 +297,7 @@ impl HostOwnedFunction for NotePhase { .map(|(_, table)| *table), ) }; - let (old, orphan, next, held_alive, orphan_alive) = { + let (old, orphan, next, held_alive, orphan_alive, self_cycle) = { let mut host = call.vm().host_context(); heap::with_heap(&mut host, |heap| { Ok(( @@ -284,6 +306,13 @@ impl HostOwnedFunction for NotePhase { heap.named_edge(weak, "next")?.is_some(), held.is_some_and(|table| heap.alive(table)), orphan_ref.is_some_and(|table| heap.alive(table)), + held.is_some_and(|table| { + heap.alive(table) + && matches!( + heap.named_edge(table, "self"), + Ok(Some(target)) if target == table + ) + }), )) }) .map_err(|error| host_fault(&error.to_string()))? @@ -295,6 +324,8 @@ impl HostOwnedFunction for NotePhase { next, held_alive, orphan_alive, + self_cycle, + collections: before.collections, }); let after = heap::stats(&mut call.vm().host_context()) .map_err(|error| host_fault(&error.to_string()))?; @@ -366,6 +397,24 @@ impl HostOwnedFunction for NoteGraph { } } +impl HostOwnedFunction for NoteScalar { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let before = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + let value = match call.args() { + [value] => value.clone(), + _ => return Err(host_fault("note_scalar arity")), + }; + obs(&mut call.vm().host_context())?.scalars.push(value); + let after = heap::stats(&mut call.vm().host_context()) + .map_err(|error| host_fault(&error.to_string()))?; + if after.live_roots != before.live_roots || after.collections != before.collections { + return Err(host_fault("note_scalar rooted or collected")); + } + Ok(CallOutcome::Return(CallReturn::one(Value::Float(0.0)))) + } +} + struct Arm { vm: vm::Vm, notes: Vec, @@ -981,3 +1030,293 @@ note_graph(2)\n" assert!(!after.next, "block exit left the replacement table rooted"); assert!(!alive(&mut arm.vm, tagged(&arm.obs, 3))); } + +fn namespace_fixture(label: &str, source: &str) -> PathBuf { + // Same directory as `namespace_case_root` in tests/common. This test crate + // does not include that module. A missing target dir must not fall back to /tmp. + let target = std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| { + panic!("CARGO_TARGET_DIR must name the slot target; refusing to write a fixture elsewhere") + }); + let root = PathBuf::from(target) + .join("compat-frontends-namespace-cases") + .join(label); + fs::create_dir_all(&root).unwrap_or_else(|error| panic!("create {}: {error}", root.display())); + let path = root.join("chunk.lua"); + fs::write(&path, source).unwrap_or_else(|error| panic!("write {}: {error}", path.display())); + path +} + +fn run_lua_file(path: &Path) -> Arm { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = vm::compile_source_file_with_options(path, options) + .unwrap_or_else(|error| panic!("lower/compile rejected {}: {error}", path.display())); + let mut vm = prepared.into_vm().expect("create VM"); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind runtime"); + let (call_values, call_scripts) = opcode_counts(vm.program()); + assert_eq!( + vm.run().expect("run lua file"), + VmStatus::Halted, + "{}", + path.display() + ); + let notes = candidate::capture_notes(&mut vm); + let (reads, writes) = candidate::capture_counts(&mut vm); + let obs = vm + .host_context() + .scope_state::() + .cloned() + .unwrap_or_default(); + Arm { + vm, + notes, + reads, + writes, + obs, + call_values, + call_scripts, + } +} + +fn assert_scalar(actual: &Value, expected: &Value) { + match (actual, expected) { + (Value::Float(got), Value::Float(want)) => assert_eq!( + got.to_bits(), + want.to_bits(), + "float bits differ: got {got:?}, want {want:?}" + ), + (Value::String(got), Value::String(want)) => { + assert_eq!(got.as_str(), want.as_str(), "string bytes differ") + } + (Value::Bytes(got), Value::Bytes(want)) => { + assert_eq!(got.as_slice(), want.as_slice(), "byte string differs") + } + (got, want) => assert_eq!(got, want, "scalar carrier mismatch"), + } +} + +#[test] +fn source_file_shared_scalar_upvalue_collects_replaced_cycle() { + let path = namespace_fixture( + "lua52_source_shared_scalars", + r#" +local mt = {} +mt.__mode = "v" +local weak = {} +setmetatable(weak, mt) +observe_table(weak, 0) +do + local get = nil + local set_false = nil + local set_neg = nil + local set_text = nil + local set_bytes = nil + local set_nil = nil + do + local held = {} + held.self = held + weak.old = held + observe_table(held, 1) + get = function() + return held + end + set_false = function() + held = false + end + set_neg = function() + held = -0.0 + end + set_text = function() + held = "text\0tail" + end + set_bytes = function() + held = "\255\0tail" + end + set_nil = function() + held = nil + end + end + note_fn(get) + note_fn(set_false) + note_fn(set_neg) + note_fn(set_text) + note_fn(set_bytes) + note_fn(set_nil) + local orphan = {} + weak.orphan = orphan + observe_table(orphan, 2) + orphan = nil + collectgarbage("collect") + note_phase(weak, 1) + local seen = get() + observe_table(seen, 3) + seen = nil + set_false() + collectgarbage("collect") + note_phase(weak, 2) + note_graph(1) + local got_false = get() + note_scalar(got_false) + got_false = nil + set_neg() + local got_neg = get() + note_scalar(got_neg) + got_neg = nil + set_text() + local got_text = get() + note_scalar(got_text) + got_text = nil + set_bytes() + local got_bytes = get() + note_scalar(got_bytes) + got_bytes = nil + set_nil() + local got_nil = get() + note_scalar(got_nil) + got_nil = nil + get = nil + set_false = nil + set_neg = nil + set_text = nil + set_bytes = nil + set_nil = nil +end +"#, + ); + let mut arm = run_lua_file(&path); + assert_eq!( + arm.call_scripts, 0, + "static CallScript must not implement the calls" + ); + assert!( + arm.call_values > 0, + "the file did not execute through CallValue" + ); + assert_eq!(arm.notes.len(), 6, "six closures share the cell"); + let cell = arm.notes[0].cell; + assert!( + arm.notes.iter().all(|note| note.cell == cell), + "closures did not share one cell" + ); + assert_eq!(arm.reads, 10, "shared reads did not go through the cell"); + assert_eq!(arm.writes, 5, "scalar writes did not go through the cell"); + assert_eq!( + tagged(&arm.obs, 1), + tagged(&arm.obs, 3), + "getter did not keep the original self-cycle after the local block" + ); + let kept = phase(&arm.obs, 1); + assert!(kept.self_cycle, "held table was not a self-cycle"); + assert!( + kept.old && kept.held_alive, + "getter did not keep the cycle alive" + ); + assert!( + !kept.orphan && !kept.orphan_alive, + "first collect did not run" + ); + assert!(kept.collections >= 1, "first collect was not recorded"); + let cleared = phase(&arm.obs, 2); + assert!( + cleared.collections > kept.collections, + "second collect did not run" + ); + assert!(!cleared.old, "weak value still named the replaced cycle"); + assert!( + !cleared.held_alive, + "self-cycle stayed alive after the cell moved to false" + ); + let snap = graph(&arm.obs, 1); + assert!( + snap.closure_alive.iter().all(|alive| *alive), + "getter died before it could observe false" + ); + assert!( + snap.cell_has_table.iter().all(|has| !has), + "cell still held a table after the false write" + ); + assert_eq!( + arm.obs.scalars.len(), + 5, + "getter did not return every replacement" + ); + assert_scalar(&arm.obs.scalars[0], &Value::Bool(false)); + assert_scalar(&arm.obs.scalars[1], &Value::Float(-0.0)); + assert_scalar(&arm.obs.scalars[2], &Value::string("text\0tail")); + assert_scalar( + &arm.obs.scalars[3], + &Value::bytes([0xff, 0, b't', b'a', b'i', b'l']), + ); + assert_scalar(&arm.obs.scalars[4], &Value::Null); + assert!( + !alive(&mut arm.vm, tagged(&arm.obs, 1)), + "replaced self-cycle was still reachable after the run" + ); +} + +#[test] +fn source_file_scalar_write_follows_binding_not_name() { + let path = namespace_fixture( + "lua52_source_shared_scalar_shadow", + r#" +do + local held = {} + observe_table(held, 1) + local get = nil + get = function() + return held + end + do + local held = {} + observe_table(held, 2) + local inner_get = nil + local inner_set = nil + inner_get = function() + return held + end + inner_set = function() + held = false + end + inner_set() + local inner_seen = inner_get() + note_scalar(inner_seen) + local outer_seen = get() + observe_table(outer_seen, 3) + note_fn(inner_get) + note_fn(inner_set) + inner_get = nil + inner_set = nil + end + note_fn(get) + get = nil +end +"#, + ); + let arm = run_lua_file(&path); + assert_eq!( + arm.notes.len(), + 3, + "outer getter, inner getter, inner setter" + ); + assert_eq!( + arm.notes[1].cell, arm.notes[2].cell, + "inner closures did not share the inner binding" + ); + assert_ne!( + arm.notes[0].cell, arm.notes[1].cell, + "same name collapsed two bindings onto one cell" + ); + assert_eq!(arm.obs.scalars.len(), 1); + assert_scalar(&arm.obs.scalars[0], &Value::Bool(false)); + assert_eq!( + tagged(&arm.obs, 1), + tagged(&arm.obs, 3), + "outer binding changed when the inner name was written" + ); + assert_ne!(tagged(&arm.obs, 1), tagged(&arm.obs, 2)); +} From 1e0a95c55ff5a3ffcf88b592db699fe60deea7e7 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 00:55:03 +0800 Subject: [PATCH 084/225] test(lua): claim source-file fixtures in exclusive temp directories Ordinary Cargo does not set CARGO_TARGET_DIR, and a fixed label under the slot target is one path shared by concurrent libtest processes. Claim each real .lua input with create_dir under the process temp root. --- tests/luajit_heap_runtime/source_closure.rs | 29 ++++++++++++++------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/tests/luajit_heap_runtime/source_closure.rs b/tests/luajit_heap_runtime/source_closure.rs index 504ea20..34958ba 100644 --- a/tests/luajit_heap_runtime/source_closure.rs +++ b/tests/luajit_heap_runtime/source_closure.rs @@ -8,6 +8,7 @@ use std::fs; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, OnceLock}; use vm::{ @@ -1032,15 +1033,25 @@ note_graph(2)\n" } fn namespace_fixture(label: &str, source: &str) -> PathBuf { - // Same directory as `namespace_case_root` in tests/common. This test crate - // does not include that module. A missing target dir must not fall back to /tmp. - let target = std::env::var("CARGO_TARGET_DIR").unwrap_or_else(|_| { - panic!("CARGO_TARGET_DIR must name the slot target; refusing to write a fixture elsewhere") - }); - let root = PathBuf::from(target) - .join("compat-frontends-namespace-cases") - .join(label); - fs::create_dir_all(&root).unwrap_or_else(|error| panic!("create {}: {error}", root.display())); + // Ordinary Cargo leaves CARGO_TARGET_DIR unset. A fixed label under the + // slot target is also one path, so concurrent libtest processes truncate + // it with fs::write. Claim a fresh directory under the process temp root. + let parent = std::env::temp_dir().join("compat-frontends-lua-source-fixtures"); + fs::create_dir_all(&parent) + .unwrap_or_else(|error| panic!("create {}: {error}", parent.display())); + // pid separates processes and the counter separates claims in one process. + // create_dir is the claim: an existing name is skipped, not reused. + static NEXT: AtomicU64 = AtomicU64::new(0); + let pid = std::process::id(); + let root = loop { + let ticket = NEXT.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!("{label}-{pid}-{ticket}")); + match fs::create_dir(&candidate) { + Ok(()) => break candidate, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("claim {}: {error}", candidate.display()), + } + }; let path = root.join("chunk.lua"); fs::write(&path, source).unwrap_or_else(|error| panic!("write {}: {error}", path.display())); path From a618802a2934dcaa45647554cb48ad570e6ab873 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 02:14:38 +0800 Subject: [PATCH 085/225] feat(lua): lower string byte length for rawlen and # Unbound rawlen and # share one private byte-length operation. Core len is not used: it counts Rust chars, returns an int, and accepts arrays. Table length, __len, and pcall stay outside this slice. --- tests/luajit_heap_runtime/candidate.rs | 78 ++++ .../luajit_heap_runtime/string_byte_length.rs | 440 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 3 files changed, 520 insertions(+) create mode 100644 tests/luajit_heap_runtime/string_byte_length.rs diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 299dd2b..0dce558 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -15,6 +15,7 @@ use super::{ast, heap, parser, resolve}; const NEW_TABLE: &str = "lua_internal::new_table"; const TYPE: &str = "lua_internal::type_of"; const ADD: &str = "lua_internal::add"; +pub(super) const STRING_BYTE_LEN: &str = "lua_internal::string_byte_len"; const RETURN_SCALAR: &str = "lua_internal::return_scalar"; const TABLE_ARG: &str = "lua_internal::table_arg"; @@ -105,6 +106,11 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { ], HostTypeSchema::Float, )); + builder.function(HostFunctionSchema::with_return( + STRING_BYTE_LEN, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::Float, + )); builder.function(HostFunctionSchema::with_return( RETURN_SCALAR, vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], @@ -177,6 +183,7 @@ pub(super) fn register( Op::NewTable, Op::Type, Op::Add, + Op::StringByteLen, Op::ReturnScalar, Op::TableArg, Op::NumberArg, @@ -208,6 +215,7 @@ pub(super) fn register( Op::NewTable => NEW_TABLE, Op::Type => TYPE, Op::Add => ADD, + Op::StringByteLen => STRING_BYTE_LEN, Op::ReturnScalar => RETURN_SCALAR, Op::TableArg => TABLE_ARG, Op::NumberArg => NUMBER_ARG, @@ -249,6 +257,7 @@ enum Op { NewTable, Type, Add, + StringByteLen, ReturnScalar, TableArg, NumberArg, @@ -334,6 +343,7 @@ impl HostOwnedFunction for Op { } } } + Self::StringByteLen => string_byte_len(call)?, Self::ReturnScalar => match call.args() { [value @ (Value::Float(_) | Value::String(_) | Value::Bool(_) | Value::Null)] => { value.clone() @@ -476,6 +486,31 @@ impl HostOwnedFunction for Op { } } +/// Byte length of a Lua string. +/// +/// Core `len` is not this operation: it counts Rust `char`s for +/// `Value::String`, returns `Value::Int`, and also accepts arrays and maps. +fn string_byte_len(call: &OwnedHostCall<'_>) -> Result { + let len = match call.args() { + [Value::String(text)] => text.len(), + [Value::Bytes(bytes)] => bytes.len(), + _ => { + return Err(VmError::HostError( + "Lua length operand is not a string".to_string(), + )); + } + }; + Ok(Value::Float(len as f64)) +} + +fn skip_parens(expr: &ast::Expr) -> &ast::Expr { + let mut expr = expr; + while let ast::Expr::Paren { inner, .. } = expr { + expr = inner; + } + expr +} + fn host_fault(message: &str) -> VmError { VmError::HostError(message.to_string()) } @@ -1968,6 +2003,36 @@ impl Lower<'_> { .ok_or_else(|| self.unsupported(span)) } + fn name_is_bound(&self, name: &ast::Name) -> bool { + self.resolution + .uses + .iter() + .any(|use_site| use_site.span == name.span && use_site.binding.is_some()) + } + + fn length_expr(&mut self, operand: &ast::Expr, span: ast::Span) -> Result { + let operand = skip_parens(operand); + self.reject_tail_next(operand, span)?; + let value = self.length_operand(operand)?; + let slot = self + .builder + .alloc_local_named(&format!("len:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: value, + line: self.line(span), + }); + self.call(STRING_BYTE_LEN, vec![Expr::Var(slot)]) + } + + fn length_operand(&mut self, expr: &ast::Expr) -> Result { + match skip_parens(expr) { + ast::Expr::String { bytes, .. } => Ok(self.string_literal(bytes)), + other => self.expr(other), + } + } + fn builtin_next(&self, name: &ast::Name) -> bool { name.is("next") && !self.functions.contains_key(&name.bytes) @@ -3129,6 +3194,14 @@ impl Lower<'_> { self.lower_call_local(expr.span(), &[], expr)?; return Ok(Expr::Null); } + if name.is("rawlen") + && let [arg] = args.exprs.as_slice() + { + if self.name_is_bound(name) { + return Err(self.unsupported(expr.span())); + } + return self.length_expr(arg, expr.span()); + } if name.is("type") && let [arg] = args.exprs.as_slice() { @@ -3194,6 +3267,11 @@ impl Lower<'_> { std::str::from_utf8(&name.bytes).map_err(|_| self.unsupported(expr.span()))?; self.host_call(&format!("lua_host::{name}"), &args.exprs, expr.span()) } + ast::Expr::Unary { + op: ast::UnOp::Len, + expr: operand, + .. + } => self.length_expr(operand, expr.span()), _ => Err(self.unsupported(expr.span())), } } diff --git a/tests/luajit_heap_runtime/string_byte_length.rs b/tests/luajit_heap_runtime/string_byte_length.rs new file mode 100644 index 0000000..63137ad --- /dev/null +++ b/tests/luajit_heap_runtime/string_byte_length.rs @@ -0,0 +1,440 @@ +//! String byte length for the Lua 5.2 candidate. +//! +//! `#` and unbound `rawlen` share one private length operation. These tests +//! feed real `.lua` files through the candidate source plugin, Core, and the +//! interpreter. Table length, `__len`, and `pcall` stay out of this slice. +//! A sibling module keeps those fixtures out of the closure-graph tests. + +use std::fs; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; + +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + HostFunctionRegistry, HostFunctionSchema, HostImportSchema, HostOwnedFunction, HostParamSchema, + HostTypeSchema, OwnedHostCall, ParseError, SourceFlavor, SourcePlugin, Value, VmError, + VmStatus, +}; + +use super::candidate; + +const NOTE: &str = "lua_host::note"; +const NEXT_TEXT: &str = "lua_host::next_text"; + +const LENGTHS: &str = r#"note(#"") +note(rawlen("")) +note(#"abc") +note(rawlen("abc")) +note(#"\195\169\0z") +note(rawlen("\195\169\0z")) +note(#"\255\0a") +note(rawlen("\255\0a")) +local ascii = "abc" +note(#ascii) +note(rawlen(ascii)) +local get = nil +local set = nil +do + local held = {} + get = function() + return held + end + set = function() + held = "\255\0a" + end +end +set() +local dynamic = get() +note(#dynamic) +note(rawlen(dynamic)) +return rawlen("abc") +"#; + +const TYPE_HASH: &str = "return type(#\"\\195\\169\\0z\")\n"; +const TYPE_RAWLEN: &str = "return type(rawlen(\"\\255\\0a\"))\n"; + +const ONCE: &str = "note(#(next_text()))\nreturn rawlen(next_text())\n"; + +const GETTER_RAWLEN: &str = r#"local get = nil +local set = nil +do + local held = {} + get = function() + return held + end + set = function() + held = "ab" + end +end +set() +return rawlen(get()) +"#; + +const GETTER_HASH: &str = r#"local get = nil +local set = nil +do + local held = {} + get = function() + return held + end + set = function() + held = "abcd" + end +end +set() +return #get() +"#; + +const SHADOW_LOCAL: &str = r#"local rawlen = nil +local set = nil +do + local held = {} + rawlen = function() + return held + end + set = function() + held = "shadow" + end +end +set() +local seen = rawlen() +return #seen +"#; + +const SHADOW_FUNCTION: &str = r#"local function rawlen() + local n = 7 + return n +end +local seen = rawlen() +return seen +"#; + +const SHADOW_FUNCTION_STRING: &str = r#"local function rawlen() + local held = "script" + return held +end +local seen = rawlen() +return #seen +"#; + +const BOUND_LOCAL_CALL: &str = "local rawlen = \"bound\"\nreturn rawlen(\"abc\")\n"; +const BOUND_FUNCTION_CALL: &str = r#"local function rawlen() + local held = "nope" + return held +end +return rawlen("abc") +"#; +const RAWLEN_STRING_CALL: &str = "return rawlen\"abc\"\n"; +const RAWLEN_NO_ARG: &str = "return rawlen()\n"; + +const NUMBER_OPERAND: &str = "local n = 42\nreturn rawlen(n)\n"; +const NIL_OPERAND: &str = "local n = nil\nreturn #n\n"; +const TABLE_OPERAND: &str = "return rawlen({})\n"; + +#[derive(Clone, Debug, Default)] +struct NotedLengths { + values: Vec, +} + +#[derive(Clone, Debug, Default)] +struct TextFeed { + texts: Vec, + calls: u32, +} + +struct NoteHost; +struct NextTextHost; +struct LengthPlugin; + +#[derive(Debug)] +struct Witness { + stack: Vec, + notes: Vec, + calls: u32, + reads: u32, + imports: Vec, + path: PathBuf, +} + +fn catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + builder.function(HostFunctionSchema::with_return( + NOTE, + vec![HostParamSchema::value("value", HostTypeSchema::Float)], + HostTypeSchema::Bool, + )); + builder.function(HostFunctionSchema::with_return( + NEXT_TEXT, + vec![], + HostTypeSchema::String, + )); + Arc::new(builder.build().expect("string byte length catalog")) + }) +} + +impl HostOwnedFunction for NoteHost { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let value = match call.args() { + [Value::Float(number)] => *number, + _ => { + return Err(VmError::HostError( + "length note expected a Lua number".to_string(), + )); + } + }; + let mut host = call.vm().host_context(); + host.scope_state_or_insert_with(NotedLengths::default) + .map_err(|error| VmError::HostError(error.to_string()))? + .values + .push(value); + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))) + } +} + +impl HostOwnedFunction for NextTextHost { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let mut host = call.vm().host_context(); + let feed = host + .scope_state_or_insert_with(TextFeed::default) + .map_err(|error| VmError::HostError(error.to_string()))?; + let index = feed.calls as usize; + feed.calls = feed.calls.saturating_add(1); + let Some(text) = feed.texts.get(index).cloned() else { + return Err(VmError::HostError("text feed exhausted".to_string())); + }; + Ok(CallOutcome::Return(CallReturn::one(Value::string(text)))) + } +} + +impl SourcePlugin for LengthPlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, catalog()) + } +} + +fn register_hosts(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + for name in [NOTE, NEXT_TEXT] { + let function = catalog.function(name).expect("length witness schema"); + registry + .register_exact_owned( + name, + function.params.len() as u8, + HostImportSchema::from_function(catalog, function), + move |_| match name { + NOTE => Box::new(NoteHost), + NEXT_TEXT => Box::new(NextTextHost), + _ => unreachable!("length witness name"), + }, + ) + .expect("register length witness"); + } +} + +fn claim_file(source: &str) -> PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(1); + let parent = std::env::temp_dir().join("compat-frontends-lua-source-fixtures"); + fs::create_dir_all(&parent).expect("fixture parent"); + let pid = std::process::id(); + let root = loop { + let ticket = NEXT.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!("string-byte-length-{pid}-{ticket}")); + match fs::create_dir(&candidate) { + Ok(()) => break candidate, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("claim {}: {error}", candidate.display()), + } + }; + let path = root.join("chunk.lua"); + fs::write(&path, source).unwrap_or_else(|error| panic!("write {}: {error}", path.display())); + path +} + +fn run_file(source: &str, texts: &[&str]) -> Result { + let path = claim_file(source); + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&LengthPlugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = + vm::compile_source_file_with_options(&path, options).map_err(|error| error.to_string())?; + let mut vm = prepared.into_vm().map_err(|error| error.to_string())?; + if !texts.is_empty() { + vm.host_context() + .scope_state_or_insert_with(|| TextFeed { + texts: texts.iter().map(|text| (*text).to_string()).collect(), + calls: 0, + }) + .map_err(|error| error.to_string())?; + } + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).map_err(|error| error.to_string())?; + register_hosts(&mut registry, &catalog); + registry + .bind_vm_cached(&mut vm) + .map_err(|error| error.to_string())?; + let status = vm.run().map_err(|error| error.to_string())?; + if status != VmStatus::Halted { + return Err(format!("status {status:?}")); + } + let (reads, _) = candidate::capture_counts(&mut vm); + let notes = vm + .host_context() + .scope_state::() + .map(|noted| noted.values.clone()) + .unwrap_or_default(); + let calls = vm + .host_context() + .scope_state::() + .map(|feed| feed.calls) + .unwrap_or(0); + let stack = vm.stack().to_vec(); + let imports = vm + .program() + .imports + .iter() + .map(|import| import.name.clone()) + .collect(); + eprintln!( + "STRING_BYTE_LENGTH path={} notes={notes:?} stack={stack:?} calls={calls} reads={reads}", + path.display() + ); + Ok(Witness { + stack, + notes, + calls, + reads, + imports, + path, + }) +} + +fn assert_floats(actual: &[f64], expected: &[f64], label: &str) { + assert_eq!( + actual.len(), + expected.len(), + "{label}: count actual={actual:?} expected={expected:?}" + ); + for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() { + assert_eq!( + actual.to_bits(), + expected.to_bits(), + "{label}: [{index}] actual={actual:?} expected={expected:?}" + ); + } +} + +fn assert_rejected(source: &str, needle: &str) { + let error = run_file(source, &[]).expect_err(needle); + assert!(error.contains(needle), "missing {needle:?} in {error}"); +} + +#[test] +fn string_byte_lengths_match_runtime_witness() { + let run = run_file(LENGTHS, &[]).expect("length fixture"); + assert!( + run.imports + .iter() + .any(|name| name == candidate::STRING_BYTE_LEN), + "length must be a runtime call, not a folded constant: {:?} {}", + run.imports, + run.path.display() + ); + assert_floats( + &run.notes, + &[0.0, 0.0, 3.0, 3.0, 4.0, 4.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0], + "ordered byte lengths", + ); + assert_eq!(run.stack, vec![Value::Float(3.0)], "chunk return"); + assert_eq!(run.reads, 1, "dynamic getter read once"); + + let hash_type = run_file(TYPE_HASH, &[]).expect("type of hash"); + assert_eq!(hash_type.stack, vec![Value::string("number")]); + let rawlen_type = run_file(TYPE_RAWLEN, &[]).expect("type of rawlen"); + assert_eq!(rawlen_type.stack, vec![Value::string("number")]); +} + +#[test] +fn string_byte_length_evaluates_operand_once() { + let first = ["ab", "wxyz", "x", "abcdef"]; + let once = run_file(ONCE, &first).expect("once, first input"); + assert_floats(&once.notes, &[2.0], "hash uses the first text"); + assert_eq!( + once.stack, + vec![Value::Float(4.0)], + "rawlen uses the second text" + ); + assert_eq!(once.calls, 2, "one evaluation per operator"); + + let swapped = ["wxyz", "ab", "abcdef", "x"]; + let other = run_file(ONCE, &swapped).expect("once, swapped input"); + assert_floats(&other.notes, &[4.0], "swapped hash"); + assert_eq!(other.stack, vec![Value::Float(2.0)], "swapped rawlen"); + assert_eq!(other.calls, 2, "swapped input is still one evaluation each"); + + let getter = run_file(GETTER_RAWLEN, &[]).expect("getter rawlen"); + assert_eq!(getter.stack, vec![Value::Float(2.0)]); + assert_eq!(getter.reads, 1, "rawlen(get()) reads the cell once"); + let hashed = run_file(GETTER_HASH, &[]).expect("getter hash"); + assert_eq!(hashed.stack, vec![Value::Float(4.0)]); + assert_eq!(hashed.reads, 1, "#get() reads the cell once"); +} + +#[test] +fn shadowed_rawlen_is_a_normal_call() { + let local_fn = run_file(SHADOW_LOCAL, &[]).expect("local rawlen"); + assert_eq!(local_fn.stack, vec![Value::Float(6.0)]); + assert_eq!(local_fn.reads, 1, "local rawlen() reads its cell"); + assert!( + local_fn + .imports + .iter() + .any(|name| name == candidate::STRING_BYTE_LEN), + "#seen must call the length operation" + ); + + let script = run_file(SHADOW_FUNCTION, &[]).expect("script rawlen"); + assert_eq!(script.stack, vec![Value::Float(7.0)]); + assert!( + !script + .imports + .iter() + .any(|name| name == candidate::STRING_BYTE_LEN), + "a script function named rawlen is not the length operation" + ); + let error = run_file(SHADOW_FUNCTION_STRING, &[]).expect_err("string return"); + assert!( + error.contains("return element is not a pass-through value"), + "unsupported string return keeps its diagnostic, not a length: {error}" + ); +} + +#[test] +fn bound_rawlen_keeps_unsupported_diagnostic() { + assert_rejected(BOUND_LOCAL_CALL, "not lowered yet"); + assert_rejected(BOUND_FUNCTION_CALL, "not lowered yet"); + assert_rejected(RAWLEN_STRING_CALL, "not lowered yet"); + assert_rejected(RAWLEN_NO_ARG, "not lowered yet"); +} + +#[test] +fn non_string_length_is_rejected() { + assert_rejected(NUMBER_OPERAND, "Lua length operand is not a string"); + assert_rejected(NIL_OPERAND, "Lua length operand is not a string"); + assert_rejected(TABLE_OPERAND, "Lua length operand is not a string"); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index c31600c..805b52f 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -17,6 +17,8 @@ mod resolve; mod return_frame; #[path = "source_closure.rs"] mod source_closure; +#[path = "string_byte_length.rs"] +mod string_byte_length; use super::heap; use super::support; From a27fa4f461f950fda875593edec599c0717d0fbd Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 02:07:16 +0800 Subject: [PATCH 086/225] feat(lua): read collectgarbage("count") as logical KiB Count this private heap's slot and edge records plus the stored length of string and byte payloads. The read does not collect or scan. --- src/frontends/lua/heap/table.rs | 129 +++++++++- tests/luajit_heap_runtime/candidate.rs | 27 +- .../value_boundary_tests.rs | 232 ++++++++++++++++++ tests/luajit_heap_runtime_tests.rs | 137 ++++++++++- 4 files changed, 509 insertions(+), 16 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 4c12d7e..9629f6e 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -198,6 +198,35 @@ struct Slot { metatable: Option<(u32, u32)>, } +/// Bytes of a string or byte payload stored in a heap record. Capacity is not +/// part of the logical extent: only the stored length is. `usize` fits in +/// `u64` on every Rust target, so the conversion is exact. +fn stored_len(len: usize) -> u64 { + len as u64 +} + +fn key_payload(key: &EdgeKey) -> u64 { + match key { + EdgeKey::Utf8(text) => stored_len(text.len()), + EdgeKey::Field(_) | EdgeKey::Object { .. } | EdgeKey::Number(_) => 0, + } +} + +fn value_payload(value: &EdgeValue) -> u64 { + match value { + EdgeValue::Scalar(Value::String(text)) => stored_len(text.len()), + EdgeValue::Scalar(Value::Bytes(bytes)) => stored_len(bytes.len()), + EdgeValue::Scalar(_) + | EdgeValue::Table { .. } + | EdgeValue::Closure { .. } + | EdgeValue::Upvalue { .. } => 0, + } +} + +fn edge_payload(edge: &Edge) -> u64 { + key_payload(&edge.key) + value_payload(&edge.value) +} + struct Edge { from: u32, /// Field ids, object identities, string text, and binary64 numbers share @@ -580,6 +609,9 @@ pub struct LuaHeap { peak_roots: u32, peak_edges: u32, scan: ScanMeter, + /// String and byte lengths stored in edge records. Not Vec capacity, not + /// Core locals, and not a second scan of `edges`. + payload_bytes: u64, } impl LuaHeap { @@ -605,6 +637,7 @@ impl LuaHeap { peak_roots: 0, peak_edges: 0, scan: ScanMeter::default(), + payload_bytes: 0, } } @@ -851,8 +884,15 @@ impl LuaHeap { pub fn clear_upvalue(&mut self, cell: UpvalueRef) -> Result<(), HeapError> { self.require_upvalue(cell)?; let key = EdgeKey::Field(CURRENT_EDGE); - self.edges - .retain(|edge| edge.from != cell.slot() || edge.key != key); + let mut released = 0u64; + self.edges.retain(|edge| { + let drop = edge.from == cell.slot() && edge.key == key; + if drop { + released += edge_payload(edge); + } + !drop + }); + self.payload_bytes -= released; Ok(()) } @@ -1221,8 +1261,15 @@ impl LuaHeap { } fn clear_edge(&mut self, from: TableRef, key: &EdgeKey) { - self.edges - .retain(|edge| edge.from != from.slot() || &edge.key != key); + let mut released = 0u64; + self.edges.retain(|edge| { + let drop = edge.from == from.slot() && &edge.key == key; + if drop { + released += edge_payload(edge); + } + !drop + }); + self.payload_bytes -= released; } fn write_table_edge( @@ -1258,22 +1305,27 @@ impl LuaHeap { key: EdgeKey, value: EdgeValue, ) -> Result<(), HeapError> { - if let Some(edge) = self + if let Some(index) = self .edges - .iter_mut() - .find(|edge| edge.from == from_slot && edge.key == key) + .iter() + .position(|edge| edge.from == from_slot && edge.key == key) { - edge.value = value; + let removed = value_payload(&self.edges[index].value); + let added = value_payload(&value); + self.edges[index].value = value; + self.payload_bytes = self.payload_bytes - removed + added; return Ok(()); } if self.edges.len() >= self.limits.edges as usize && !self.reclaim_cursor_gap() { return Err(HeapError::EdgeCapacity); } + let added = key_payload(&key) + value_payload(&value); self.edges.push(Edge { from: from_slot, key, value, }); + self.payload_bytes += added; self.note_edge_peak(); Ok(()) } @@ -1288,7 +1340,8 @@ impl LuaHeap { else { return false; }; - self.edges.remove(index); + let edge = self.edges.remove(index); + self.payload_bytes -= edge_payload(&edge); true } @@ -1810,6 +1863,43 @@ impl LuaHeap { } } + /// Logical bytes of this private heap, as KiB. Same meter as + /// [`Self::logical_bytes`]. Does not collect and does not touch the scan meter. + pub fn logical_kib(&self) -> f64 { + self.logical_bytes() as f64 / 1024.0 + } + + /// Logical allocated bytes of this private heap. + /// + /// Charged: + /// - each slot record (`slots.len()`, including a free or retired record + /// that still occupies the vector) + /// - each edge record (`edges.len()`, including a weak-cleared cursor gap) + /// - the stored length of a string or byte payload in those edge records + /// + /// Not charged: + /// - `Vec` capacity above `len`, and string or byte capacity above `len` + /// - root frames and the free-list (a frame leave truncates roots before + /// collection, so charging them would drop the reading first) + /// - the issued carrier array (Core identity, not a string payload) + /// - Core locals, temporaries, and strings that are not stored in an edge + /// - the borrowed `next` cursor (not a heap record) + /// + /// A weak clear keeps the cursor key charged and releases only the value + /// payload. The read is the two lengths plus one counter: no scan, no + /// mark, and no change to `collections` or the scan meter. This is not a + /// LuaJIT allocator, not whole-VM bytes, and not string interning. + /// + /// The record product fits in `u64`: each vector length is capped by a + /// `u32` limit, and a record stride is far below `2^32`. The payload sum + /// is the sum of lengths this process stored; that sum cannot exceed the + /// bytes those allocations occupy. + pub fn logical_bytes(&self) -> u64 { + let nodes = (self.slots.len() as u64) * (std::mem::size_of::() as u64); + let edges = (self.edges.len() as u64) * (std::mem::size_of::() as u64); + nodes + edges + self.payload_bytes + } + fn require_live(&self, handle: TableRef) -> Result<(), HeapError> { self.require_kind( handle.domain(), @@ -2126,6 +2216,7 @@ impl LuaHeap { // weak-value clear leaves the key in place with no value. That record // is the cursor, not a second index. A dead key, a private field, or // a strong edge is still removed. + let mut released = 0u64; self.edges.retain_mut(|edge| { let owner = edge.from as usize; if is_marked(edge.from) && weak_values.get(owner).copied().unwrap_or(false) { @@ -2140,10 +2231,11 @@ impl LuaHeap { } }; if value_dead && guest_cursor(&edge.key) { + released += value_payload(&edge.value); edge.value = EdgeValue::Scalar(Value::Null); } } - is_marked(edge.from) + let keep = is_marked(edge.from) && match &edge.value { EdgeValue::Table { slot, .. } => is_marked(*slot), EdgeValue::Scalar(_) => true, @@ -2162,8 +2254,13 @@ impl LuaHeap { kind, } if edge.value.is_cursor_gap() => typed(*slot, *generation, *kind), EdgeKey::Object { slot, .. } => is_marked(*slot), - } + }; + if !keep { + released += edge_payload(edge); + } + keep }); + self.payload_bytes -= released; } fn mark_slot(&mut self, index: u32, work: &mut Vec) { @@ -2193,11 +2290,17 @@ impl LuaHeap { } fn remove_edges_touching(&mut self, slot: u32) { + let mut released = 0u64; self.edges.retain(|edge| { - edge.from != slot + let keep = edge.from != slot && edge.value.object_slot().is_none_or(|target| target != slot) - && !edge_key_is_slot(&edge.key, slot) + && !edge_key_is_slot(&edge.key, slot); + if !keep { + released += edge_payload(edge); + } + keep }); + self.payload_bytes -= released; } fn clear_roots_to(&mut self, handle: TableRef) { diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 0dce558..f1db8bb 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -24,6 +24,7 @@ const BOOL_ARG: &str = "lua_internal::bool_arg"; const STRING_ARG: &str = "lua_internal::string_arg"; const GATHER_ROOT: &str = "lua_internal::gather_root"; pub(super) const COLLECT: &str = "lua_internal::collect"; +const COUNT: &str = "lua_internal::count"; const OPEN_CELL: &str = "lua_internal::open_cell"; const READ_CELL: &str = "lua_internal::read_cell"; const WRITE_CELL: &str = "lua_internal::write_cell"; @@ -83,6 +84,11 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { vec![], HostTypeSchema::Unknown, )); + builder.function(HostFunctionSchema::with_return( + COUNT, + vec![], + HostTypeSchema::Float, + )); builder.function(HostFunctionSchema::with_return( COPY_FIELDS, vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], @@ -191,6 +197,7 @@ pub(super) fn register( Op::StringArg, Op::GatherRoot, Op::Collect, + Op::Count, Op::EnterResult, Op::EnterCallee, Op::RootIssued, @@ -223,6 +230,7 @@ pub(super) fn register( Op::StringArg => STRING_ARG, Op::GatherRoot => GATHER_ROOT, Op::Collect => COLLECT, + Op::Count => COUNT, Op::EnterResult => ENTER_RESULT, Op::EnterCallee => ENTER_CALLEE, Op::RootIssued => ROOT_ISSUED, @@ -265,6 +273,7 @@ enum Op { StringArg, GatherRoot, Collect, + Count, EnterResult, EnterCallee, RootIssued, @@ -455,6 +464,12 @@ impl HostOwnedFunction for Op { collect_at_safepoint(&mut call.vm().host_context(), &tables)?; Value::Float(0.0) } + Self::Count => { + let kib = + heap::with_heap(&mut call.vm().host_context(), |heap| Ok(heap.logical_kib())) + .map_err(|error| VmError::HostError(error.to_string()))?; + Value::Float(kib) + } Self::EnterResult => enter_result(call)?, Self::EnterCallee => enter_callee(call)?, Self::RootIssued => root_issued(call)?, @@ -3211,9 +3226,13 @@ impl Lower<'_> { } if name.is("collectgarbage") && let [ast::Expr::String { bytes, .. }] = args.exprs.as_slice() - && bytes == b"collect" { - return self.collect_expr(expr.span()); + if bytes == b"collect" { + return self.collect_expr(expr.span()); + } + if bytes == b"count" { + return self.count_expr(expr.span()); + } } if name.is("copy_fields") && let [arg] = args.exprs.as_slice() @@ -3357,6 +3376,10 @@ impl Lower<'_> { self.call(COLLECT, vec![roots]) } + fn count_expr(&mut self, _span: ast::Span) -> Result { + self.call(COUNT, vec![]) + } + fn call(&mut self, name: &str, args: Vec) -> Result { let function = self.catalog.function(name).expect("private Lua operation"); self.builder diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 805b52f..e5b2cd5 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -5489,3 +5489,235 @@ return type(k) "the consumed receiver temp must not remain a root" ); } + +fn run_lua_file(label: &str, source: &str) -> vm::Vm { + let root = std::env::var("TMPDIR").expect("count fixtures stay in the lease tmp"); + let dir = std::path::PathBuf::from(root).join("lua-count-fixtures"); + std::fs::create_dir_all(&dir).expect("lease fixture dir"); + let path = dir.join(format!("{label}-{}.lua", std::process::id())); + std::fs::write(&path, source).expect("write lua fixture"); + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&CandidatePlugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let mut vm = vm::compile_source_file_with_options(&path, options) + .unwrap_or_else(|error| panic!("{label}: compile {} failed: {error}", path.display())) + .into_vm() + .unwrap_or_else(|error| panic!("{label}: vm: {error}")); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate hosts"); + register_witnesses(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind hosts"); + vm +} + +fn halt_lua_file(label: &str, source: &str) -> vm::Vm { + let mut vm = run_lua_file(label, source); + let status = vm + .run() + .unwrap_or_else(|error| panic!("{label}: run: {error}")); + assert_eq!(status, VmStatus::Halted, "{label}"); + vm +} + +fn float_kib(vm: &vm::Vm) -> f64 { + match vm.stack() { + [Value::Float(kib)] => *kib, + other => panic!("count must return one float KiB, got {other:?}"), + } +} + +const WEAK_CYCLE: &str = "\ +local mt = {}\n\ +mt.__mode = \"v\"\n\ +local weak = {}\n\ +setmetatable(weak, mt)\n\ +local cycle = {}\n\ +cycle.self = cycle\n\ +observe_table(cycle, 0)\n\ +weak[1] = cycle\n\ +cycle = nil\n\ +"; + +fn payload_count_source(bytes: &str, drop_root: bool, collect: bool) -> String { + let mut source = format!("local holder = {{}}\nholder.payload = \"{bytes}\"\n"); + if drop_root { + source.push_str("holder = nil\n"); + } + if collect { + source.push_str("collectgarbage(\"collect\")\n"); + } + source.push_str("return collectgarbage(\"count\")\n"); + source +} + +#[test] +fn lua_file_count_reads_logical_kib_without_collecting() { + let bare = halt_lua_file("count-bare", "return collectgarbage(\"count\")\n"); + let bare_kib = float_kib(&bare); + assert!( + bare_kib.is_finite() && bare_kib >= 0.0, + "bare count is {bare_kib}" + ); + + let mut counted = halt_lua_file( + "count-keeps-cycle", + &format!( + "{WEAK_CYCLE}collectgarbage(\"count\")\ncollectgarbage(\"count\")\nreturn type(weak[1])\n" + ), + ); + assert_eq!(counted.stack(), &[Value::string("table")]); + let cycle = observed_tables(&mut counted); + assert_eq!(cycle.len(), 1); + assert_table_lifetime(&mut counted.host_context(), cycle[0], true); + let counted_stats = heap::stats(&mut counted.host_context()).expect("heap stats"); + let counted_meter = heap::take_scan_meter(&mut counted.host_context()).expect("scan meter"); + assert_eq!(counted_stats.collections, 0, "count must not collect"); + + let mut control = halt_lua_file( + "count-control-no-count", + &format!("{WEAK_CYCLE}return type(weak[1])\n"), + ); + assert_eq!( + control.stack(), + &[Value::string("table")], + "the same graph stays without count; a table result is not a skipped body" + ); + let control_cycle = observed_tables(&mut control); + assert_table_lifetime(&mut control.host_context(), control_cycle[0], true); + assert_eq!( + heap::stats(&mut control.host_context()) + .expect("control stats") + .collections, + 0 + ); + let control_meter = heap::take_scan_meter(&mut control.host_context()).expect("control meter"); + assert_eq!( + counted_meter, control_meter, + "count must not change the scan meter of the same graph" + ); + + let mut first = halt_lua_file( + "count-first", + &format!("{WEAK_CYCLE}return collectgarbage(\"count\")\n"), + ); + let second = halt_lua_file( + "count-second", + &format!("{WEAK_CYCLE}collectgarbage(\"count\")\nreturn collectgarbage(\"count\")\n"), + ); + assert_eq!( + float_kib(&first), + float_kib(&second), + "a second count of the same retained graph must not move the reading" + ); + assert_eq!( + heap::stats(&mut first.host_context()) + .expect("first stats") + .collections, + 0 + ); + + let mut collected = halt_lua_file( + "count-collect-control", + &format!("{WEAK_CYCLE}collectgarbage(\"collect\")\nreturn type(weak[1])\n"), + ); + let mut counted_then_collected = halt_lua_file( + "count-then-collect", + &format!( + "{WEAK_CYCLE}collectgarbage(\"count\")\ncollectgarbage(\"collect\")\nreturn type(weak[1])\n" + ), + ); + assert_eq!(collected.stack(), &[Value::string("nil")]); + assert_eq!(counted_then_collected.stack(), &[Value::string("nil")]); + let collected_cycle = observed_tables(&mut collected); + assert_table_lifetime(&mut collected.host_context(), collected_cycle[0], false); + let collected_note = collected + .host_context() + .scope_state::() + .expect("collect note") + .collects + .clone(); + let counted_note = counted_then_collected + .host_context() + .scope_state::() + .expect("count then collect note") + .collects + .clone(); + assert_eq!(collected_note.len(), 1, "one explicit collection"); + assert_eq!(counted_note.len(), 1, "count must not record a collection"); + assert!( + collected_note[0].swept >= 1, + "the weak-only cycle must actually reclaim a node, swept {}", + collected_note[0].swept + ); + assert_eq!( + counted_note[0].swept, collected_note[0].swept, + "count must not change how many nodes the same collection reclaims" + ); + assert_eq!( + counted_note[0].metatable_edge_checks, + collected_note[0].metatable_edge_checks + ); + assert_eq!( + counted_note[0].index_edge_checks, + collected_note[0].index_edge_checks + ); + assert_eq!( + counted_note[0].outgoing_edge_checks, + collected_note[0].outgoing_edge_checks + ); + assert_eq!( + counted_note[0].sweep_edge_checks, + collected_note[0].sweep_edge_checks + ); + + let short = "x"; + let long = "x".repeat(256); + let small = float_kib(&halt_lua_file( + "count-small-payload", + &payload_count_source(short, false, false), + )); + let large = float_kib(&halt_lua_file( + "count-large-payload", + &payload_count_source(&long, false, false), + )); + assert!( + large > small, + "a longer string stored on the table must raise logical KiB: small {small}, large {large}" + ); + + let held = float_kib(&halt_lua_file( + "count-held", + &payload_count_source(&long, false, false), + )); + let mut pending = halt_lua_file("count-pending", &payload_count_source(&long, true, false)); + let pending_kib = float_kib(&pending); + assert_eq!( + pending_kib, held, + "dropping the last root must not release the record before an explicit collection" + ); + assert_eq!( + heap::stats(&mut pending.host_context()) + .expect("pending stats") + .collections, + 0 + ); + let mut reclaimed = halt_lua_file("count-reclaimed", &payload_count_source(&long, true, true)); + let reclaimed_kib = float_kib(&reclaimed); + assert!( + reclaimed_kib < pending_kib, + "explicit collection of the unrooted payload must lower the reading: pending {pending_kib}, reclaimed {reclaimed_kib}" + ); + let reclaimed_note = reclaimed + .host_context() + .scope_state::() + .expect("reclaimed note") + .collects + .clone(); + assert_eq!(reclaimed_note.len(), 1); + assert!( + reclaimed_note[0].swept >= 1, + "the dropped payload table must be reclaimed, swept {}", + reclaimed_note[0].swept + ); +} diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index d70f778..0c360b5 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -13,7 +13,8 @@ mod support; mod value_boundary_tests; use heap::{ - CollectReport, HandleKind, HeapLimits, LuaHeap, LuaTableResource, RootFrameId, TableRef, + CollectReport, HandleKind, HeapLimits, LuaHeap, LuaTableResource, RootFrameId, ScanMeter, + TableRef, }; use support::{Probe, run_probe, with_idle_vm}; use vm::{HostContext, ResourceHandle, Value}; @@ -1780,3 +1781,137 @@ fn assert_host_collect_keeps_the_marked_mode() { .expect("host sweep used the marked mode"); }); } + +#[test] +fn logical_count_follows_replace_delete_gap_rollback_and_domain() { + let limits = HeapLimits { + nodes: 8, + roots: 4, + edges: 8, + max_generation: 8, + }; + let mut heap = LuaHeap::new(limits); + assert_eq!(heap.logical_bytes(), 0); + assert_eq!(heap.logical_kib(), 0.0); + let collections = heap.stats().collections; + assert_eq!(heap.logical_kib(), 0.0); + assert_eq!(heap.stats().collections, collections); + assert_eq!(heap.take_scan_meter(), ScanMeter::default()); + + let first = heap.alloc().expect("node"); + let node = heap.logical_bytes(); + assert!(node > 0, "a live slot record is charged"); + let second = heap.alloc().expect("second node"); + assert_eq!( + heap.logical_bytes() - node, + node, + "the next slot charges one record, not the Vec reserve" + ); + heap.rollback(second).expect("drop the second node"); + assert_eq!( + heap.logical_bytes(), + node * 2, + "a free slot record stays; rollback of an edgeless node adds no payload" + ); + + let before_edge = heap.logical_bytes(); + heap.set_edge(first, 1, first).expect("field edge"); + let edge = heap.logical_bytes() - before_edge; + assert!(edge > 0); + heap.set_field_scalar(first, 1, Value::Null) + .expect("clear field"); + assert_eq!(heap.logical_bytes(), before_edge); + + heap.set_named_scalar(first, "k", Value::string("ab")) + .expect("string field"); + let held = heap.logical_bytes(); + assert_eq!(held, before_edge + edge + 1 + 2); + heap.set_named_scalar(first, "k", Value::string("abcd")) + .expect("replace value"); + assert_eq!( + heap.logical_bytes(), + held + 2, + "replacement charges the value delta, not a second edge" + ); + heap.set_named_scalar(first, "k", Value::Null) + .expect("delete"); + assert_eq!( + heap.logical_bytes(), + before_edge, + "delete releases the key, the value, and the edge record" + ); + + let cell = heap.alloc_upvalue().expect("cell"); + let before_bytes = heap.logical_bytes(); + heap.write_scalar_upvalue(cell, Value::bytes(vec![1, 2, 3, 4])) + .expect("bytes"); + assert_eq!(heap.logical_bytes(), before_bytes + edge + 4); + heap.write_scalar_upvalue(cell, Value::bytes(vec![9])) + .expect("shorter bytes"); + assert_eq!(heap.logical_bytes(), before_bytes + edge + 1); + heap.clear_upvalue(cell).expect("clear bytes"); + assert_eq!(heap.logical_bytes(), before_bytes); + + let isolated = heap.logical_bytes(); + let mut tight = LuaHeap::new(HeapLimits { + nodes: 1, + roots: 1, + edges: 1, + max_generation: 4, + }); + let only = tight.alloc().expect("only node"); + let tight_node = tight.logical_bytes(); + tight + .set_named_scalar(only, "k", Value::string("ab")) + .expect("one edge"); + let tight_held = tight.logical_bytes(); + assert_eq!(tight_held, tight_node + edge + 1 + 2); + assert!( + tight + .set_named_scalar(only, "other", Value::string("zzzz")) + .is_err(), + "edge cap" + ); + assert_eq!( + tight.logical_bytes(), + tight_held, + "a refused write leaves no payload" + ); + tight.rollback(only).expect("rollback the charged edge"); + assert_eq!( + tight.logical_bytes(), + tight_node, + "rollback releases the edge payload and keeps the free slot record" + ); + assert_eq!( + heap.logical_bytes(), + isolated, + "the other heap's meter is a different domain" + ); + + let mt = heap.alloc().expect("metatable"); + let owner = heap.alloc().expect("weak owner"); + let dead = heap.alloc().expect("weak value"); + let frame = heap.enter_roots(2).expect("roots"); + heap.write_root(frame, 0, mt).expect("root metatable"); + heap.write_root(frame, 1, owner).expect("root owner"); + heap.set_metatable(owner, Some(mt)).expect("metatable"); + heap.set_mode_scalar(mt, Value::string("v")).expect("mode"); + heap.set_named_edge(owner, "keep", dead).expect("weak key"); + let before_collect = heap.logical_bytes(); + let collections = heap.stats().collections; + let _ = heap.logical_kib(); + assert_eq!(heap.stats().collections, collections); + heap.collect(); + assert!(!heap.alive(dead), "the weak value is reclaimed"); + assert_eq!(heap.stats().collections, collections + 1); + assert_eq!( + heap.logical_bytes(), + before_collect, + "the cursor key stays charged while the gap record remains" + ); + let gap = heap.logical_bytes(); + heap.set_named_scalar(owner, "keep", Value::Null) + .expect("drop the gap"); + assert_eq!(heap.logical_bytes(), gap - edge - 4); +} From 70bf7849ce1b963be6a8729626e5845d3e397dc4 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 02:38:07 +0800 Subject: [PATCH 087/225] fix(lua): place count fixtures in the process temp directory File tests no longer require TMPDIR. Create and write errors name the fixture directory. The logical_bytes note charges each edge its own reference payload, including a repeated charge when several edges share one Core Arc. --- src/frontends/lua/heap/table.rs | 6 +++--- tests/luajit_heap_runtime/value_boundary_tests.rs | 9 +++++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 9629f6e..042170d 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -1891,9 +1891,9 @@ impl LuaHeap { /// LuaJIT allocator, not whole-VM bytes, and not string interning. /// /// The record product fits in `u64`: each vector length is capped by a - /// `u32` limit, and a record stride is far below `2^32`. The payload sum - /// is the sum of lengths this process stored; that sum cannot exceed the - /// bytes those allocations occupy. + /// `u32` limit, and a record stride is far below `2^32`. Each edge counts + /// its own reference payload. The same Core `Arc` referenced by more than + /// one edge is charged once per edge. pub fn logical_bytes(&self) -> u64 { let nodes = (self.slots.len() as u64) * (std::mem::size_of::() as u64); let edges = (self.edges.len() as u64) * (std::mem::size_of::() as u64); diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index e5b2cd5..977d7e1 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -5491,11 +5491,12 @@ return type(k) } fn run_lua_file(label: &str, source: &str) -> vm::Vm { - let root = std::env::var("TMPDIR").expect("count fixtures stay in the lease tmp"); - let dir = std::path::PathBuf::from(root).join("lua-count-fixtures"); - std::fs::create_dir_all(&dir).expect("lease fixture dir"); + let dir = std::env::temp_dir().join("lua-count-fixtures"); + std::fs::create_dir_all(&dir) + .unwrap_or_else(|error| panic!("create {}: {error}", dir.display())); let path = dir.join(format!("{label}-{}.lua", std::process::id())); - std::fs::write(&path, source).expect("write lua fixture"); + std::fs::write(&path, source) + .unwrap_or_else(|error| panic!("write {}: {error}", path.display())); let catalog = Arc::clone(catalog()); let options = CompileSourceFileOptions::new() .with_source_plugin(&CandidatePlugin) From 941502a2f0b56cfcdd341f1b92e6f9330c678814 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 03:18:57 +0800 Subject: [PATCH 088/225] feat(lua): honor raw table __metatable setmetatable returns the same table. getmetatable exposes a non-nil raw __metatable field, and a protected table cannot be replaced or cleared. A boolean guard still stops at the heap named-scalar assert. --- tests/luajit_heap_runtime/candidate.rs | 43 +- .../table_metatable_protection.rs | 625 ++++++++++++++++++ .../value_boundary_tests.rs | 7 + 3 files changed, 665 insertions(+), 10 deletions(-) create mode 100644 tests/luajit_heap_runtime/table_metatable_protection.rs diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index f1db8bb..a1e0939 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -150,7 +150,7 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { ( SET_METATABLE, vec!["owner", "metatable"], - HostTypeSchema::Float, + HostTypeSchema::Unknown, ), (GET_METATABLE, vec!["owner"], HostTypeSchema::Unknown), ( @@ -1042,11 +1042,18 @@ fn set_metatable(call: &mut OwnedHostCall<'_>) -> Result { _ => return Err(host_fault("metatable target is not a table")), }, }; - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.set_metatable(owner, mt) + let protected = heap::with_heap(&mut call.vm().host_context(), |heap| { + raw_metatable_guard(heap, owner) }) .map_err(heap_error)?; - Ok(Value::Float(0.0)) + if protected.is_some() { + return Err(host_fault("cannot change a protected metatable")); + } + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.set_metatable(owner, mt)?; + heap.issued_value(owner) + }) + .map_err(heap_error) } fn get_metatable(call: &mut OwnedHostCall<'_>) -> Result { @@ -1058,17 +1065,33 @@ fn get_metatable(call: &mut OwnedHostCall<'_>) -> Result { heap::GuestClass::Table(table) => table, _ => return Err(host_fault("metatable owner is not a table")), }; - let target = heap::with_heap(&mut call.vm().host_context(), |heap| heap.metatable(owner)) - .map_err(heap_error)?; - let Some(target) = target else { - return Ok(Value::Null); - }; heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.issued_value(target) + if let Some(field) = raw_metatable_guard(heap, owner)? { + return Ok(field); + } + match heap.metatable(owner)? { + Some(target) => heap.issued_value(target), + None => Ok(Value::Null), + } }) .map_err(heap_error) } +fn raw_metatable_guard( + heap: &heap::LuaHeap, + owner: heap::TableRef, +) -> Result, heap::HeapError> { + let Some(mt) = heap.metatable(owner)? else { + return Ok(None); + }; + let field = heap.named_value(mt, "__metatable")?; + if matches!(field, Value::Null) { + Ok(None) + } else { + Ok(Some(field)) + } +} + fn release_result(call: &mut OwnedHostCall<'_>) -> Result { let (frame_token, slot) = match call.args() { [frame, slot] => (frame.clone(), float_u32(slot)?), diff --git a/tests/luajit_heap_runtime/table_metatable_protection.rs b/tests/luajit_heap_runtime/table_metatable_protection.rs new file mode 100644 index 0000000..f96d5c0 --- /dev/null +++ b/tests/luajit_heap_runtime/table_metatable_protection.rs @@ -0,0 +1,625 @@ +//! Protected table metatables for the Lua 5.2 candidate. +//! +//! Real `.lua` files go through the candidate source plugin, Core, and the +//! interpreter. `getmetatable` / `setmetatable` stay on the existing host +//! calls. This slice does not add `pcall`, non-table metatables, or `__index`. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use vm::{ + CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, ParseError, + SourceFlavor, SourcePlugin, Value, VmStatus, +}; + +use super::candidate; + +struct MetatablePlugin; + +impl SourcePlugin for MetatablePlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, super::catalog()) + } +} + +fn claim_file(source: &str) -> PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(1); + let parent = std::env::temp_dir().join("compat-frontends-lua-source-fixtures"); + fs::create_dir_all(&parent).expect("fixture parent"); + let pid = std::process::id(); + let root = loop { + let ticket = NEXT.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!("table-metatable-{pid}-{ticket}")); + match fs::create_dir(&candidate) { + Ok(()) => break candidate, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("claim {}: {error}", candidate.display()), + } + }; + let path = root.join("chunk.lua"); + fs::write(&path, source).unwrap_or_else(|error| panic!("write {}: {error}", path.display())); + path +} + +struct Run { + status: Result, + stack: Vec, + path: PathBuf, + vm: Option, +} + +#[derive(Clone, Copy)] +enum Note { + Text, + Bool, + RawFalse, +} + +#[derive(Default)] +struct Notes { + text: Vec<(f64, String)>, + flags: Vec<(f64, bool)>, +} + +impl vm::HostOwnedFunction for Note { + fn call(&mut self, call: &mut vm::OwnedHostCall<'_>) -> Result { + let args = call.args().to_vec(); + if matches!(self, Self::RawFalse) { + let owner = match args.as_slice() { + [owner] => owner.clone(), + _ => { + return Err(vm::VmError::HostError( + "false guard plant expected one table".to_string(), + )); + } + }; + let mut host = call.vm().host_context(); + let table = match super::heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&owner))) + .map_err(|error| vm::VmError::HostError(error.to_string()))? + { + super::heap::GuestClass::Table(table) => table, + _ => { + return Err(vm::VmError::HostError( + "false guard plant expected a table".to_string(), + )); + } + }; + super::heap::with_heap(&mut host, |heap| { + heap.set_named_scalar(table, "__metatable", Value::Bool(false)) + }) + .map_err(|error| vm::VmError::HostError(error.to_string()))?; + return Ok(vm::CallOutcome::Return(vm::CallReturn::one(Value::Bool( + true, + )))); + } + let mut host = call.vm().host_context(); + let notes = host + .scope_state_or_insert_with(Notes::default) + .map_err(|error| vm::VmError::HostError(error.to_string()))?; + match self { + Self::Text => { + let (tag, text) = match args.as_slice() { + [Value::Float(tag), Value::String(text)] => (*tag, text.as_str().to_string()), + _ => { + return Err(vm::VmError::HostError("expected Lua string".to_string())); + } + }; + notes.text.push((tag, text)); + } + Self::Bool => { + let (tag, flag) = match args.as_slice() { + [Value::Float(tag), Value::Bool(flag)] => (*tag, *flag), + _ => { + return Err(vm::VmError::HostError("expected Lua boolean".to_string())); + } + }; + notes.flags.push((tag, flag)); + } + Self::RawFalse => unreachable!("planted before notes"), + } + Ok(vm::CallOutcome::Return(vm::CallReturn::one(Value::Bool( + true, + )))) + } +} + +fn register_note( + registry: &mut HostFunctionRegistry, + catalog: &vm::HostApiCatalog, + name: &str, + note: Note, +) -> Result<(), String> { + let function = catalog + .function(name) + .ok_or_else(|| format!("missing {name}"))?; + registry + .register_exact_owned( + name, + function.params.len() as u8, + vm::HostImportSchema::from_function(catalog, function), + move |_| Box::new(note), + ) + .map(|_| ()) + .map_err(|error| error.to_string()) +} + +fn run_file(source: &str) -> Run { + let path = claim_file(source); + let catalog = Arc::clone(super::catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&MetatablePlugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = match vm::compile_source_file_with_options(&path, options) { + Ok(prepared) => prepared, + Err(error) => { + return Run { + status: Err(error.to_string()), + stack: Vec::new(), + path, + vm: None, + }; + } + }; + let mut vm = match prepared.into_vm() { + Ok(vm) => vm, + Err(error) => { + return Run { + status: Err(error.to_string()), + stack: Vec::new(), + path, + vm: None, + }; + } + }; + let mut registry = HostFunctionRegistry::empty(); + if let Err(error) = candidate::register(&mut registry, &catalog) { + return Run { + status: Err(error.to_string()), + stack: Vec::new(), + path, + vm: None, + }; + } + super::register_witnesses(&mut registry, &catalog); + for (name, note) in [ + ("lua_host::note_text", Note::Text), + ("lua_host::note_bool", Note::Bool), + ("lua_host::plant_raw_false", Note::RawFalse), + ] { + if let Err(error) = register_note(&mut registry, &catalog, name, note) { + return Run { + status: Err(error), + stack: Vec::new(), + path, + vm: None, + }; + } + } + if let Err(error) = registry.bind_vm_cached(&mut vm) { + return Run { + status: Err(error.to_string()), + stack: Vec::new(), + path, + vm: None, + }; + } + let status = vm.run().map_err(|error| error.to_string()); + let stack = vm.stack().to_vec(); + eprintln!( + "TABLE_METATABLE path={} status={status:?} stack={stack:?}", + path.display() + ); + Run { + status, + stack, + path, + vm: Some(vm), + } +} + +fn display(path: &Path) -> String { + path.display().to_string() +} + +#[test] +fn unprotected_setmetatable_returns_the_same_table() { + let typed = run_file("return type(setmetatable({}, {}))\n"); + assert!( + matches!(typed.status, Ok(VmStatus::Halted)), + "type path {} status={:?}", + display(&typed.path), + typed.status + ); + assert_eq!( + typed.stack, + vec![Value::string("table")], + "setmetatable must return a table, not a non-table sentinel: {}", + display(&typed.path) + ); + + let same = run_file( + "local t = {}\n\ + local mt = {}\n\ + return same_table(setmetatable(t, mt), t)\n", + ); + assert!( + matches!(same.status, Ok(VmStatus::Halted)), + "identity path {} status={:?}", + display(&same.path), + same.status + ); + assert_eq!( + same.stack, + vec![Value::Bool(true)], + "the call result must be the same table {}", + display(&same.path) + ); +} + +#[test] +fn string_guard_is_returned_and_blocks_replacement() { + let exposed = run_file( + "local t = {}\n\ + local mt = {}\n\ + mt.__metatable = \"sealed\"\n\ + setmetatable(t, mt)\n\ + return type(getmetatable(t))\n", + ); + assert!( + matches!(exposed.status, Ok(VmStatus::Halted)), + "exposure path {} status={:?}", + display(&exposed.path), + exposed.status + ); + assert_eq!( + exposed.stack, + vec![Value::string("string")], + "raw __metatable must be exposed instead of the real metatable: {}", + display(&exposed.path) + ); + + let noted = run_file( + "local t = {}\n\ + local mt = {}\n\ + mt.__metatable = \"sealed\"\n\ + setmetatable(t, mt)\n\ + note_text(1, getmetatable(t))\n\ + return 1\n", + ); + assert!( + matches!(noted.status, Ok(VmStatus::Halted)), + "note path {} status={:?}", + display(¬ed.path), + noted.status + ); + let text = noted + .vm + .expect("vm") + .host_context() + .scope_state::() + .map(|notes| notes.text.clone()) + .unwrap_or_default(); + assert_eq!(text, vec![(1.0, "sealed".to_string())]); + + let mut blocked = run_file( + "local owner = {}\n\ + local mt = {}\n\ + local other = {}\n\ + observe_table(owner, 0)\n\ + observe_table(mt, 0)\n\ + mt.__metatable = \"sealed\"\n\ + setmetatable(owner, mt)\n\ + setmetatable(owner, other)\n\ + return 1\n", + ); + let error = blocked + .status + .expect_err("protected setmetatable must fail"); + assert!( + error.contains("cannot change a protected metatable"), + "candidate host error, not a pcall string: {error}" + ); + let vm = blocked.vm.as_mut().expect("vm after host error"); + let observed = vm + .host_context() + .scope_state::>() + .cloned() + .unwrap_or_default(); + let owner = observed[0].table; + let original = observed[1].table; + let current = super::heap::with_heap(&mut vm.host_context(), |heap| heap.metatable(owner)) + .expect("read metatable"); + assert_eq!( + current, + Some(original), + "failed set must leave the real metatable" + ); +} + +#[test] +fn absent_metatable_is_nil_and_table_guard_keeps_identity() { + let absent = run_file("return type(getmetatable({}))\n"); + assert!( + matches!(absent.status, Ok(VmStatus::Halted)), + "{:?}", + absent.status + ); + assert_eq!(absent.stack, vec![Value::string("nil")]); + + let seen = run_file( + "local shield = {}\n\ + local mt = {}\n\ + mt.__metatable = shield\n\ + local owner = setmetatable({}, mt)\n\ + return same_table(getmetatable(owner), shield)\n", + ); + assert!( + matches!(seen.status, Ok(VmStatus::Halted)), + "{:?}", + seen.status + ); + assert_eq!( + seen.stack, + vec![Value::Bool(true)], + "table guard must be the stored table, not the real metatable" + ); + + let not_mt = run_file( + "local shield = {}\n\ + local mt = {}\n\ + mt.__metatable = shield\n\ + local owner = setmetatable({}, mt)\n\ + return same_table(getmetatable(owner), mt)\n", + ); + assert!( + matches!(not_mt.status, Ok(VmStatus::Halted)), + "{:?}", + not_mt.status + ); + assert_eq!(not_mt.stack, vec![Value::Bool(false)]); + + let mut blocked = run_file( + "local shield = {}\n\ + local mt = {}\n\ + local owner = {}\n\ + observe_table(owner, 0)\n\ + observe_table(mt, 0)\n\ + mt.__metatable = shield\n\ + setmetatable(owner, mt)\n\ + setmetatable(owner, nil)\n\ + return 1\n", + ); + let error = blocked.status.expect_err("protected clear must fail"); + assert!( + error.contains("cannot change a protected metatable"), + "{error}" + ); + let vm = blocked.vm.as_mut().expect("vm"); + let observed = vm + .host_context() + .scope_state::>() + .cloned() + .unwrap_or_default(); + let current = super::heap::with_heap(&mut vm.host_context(), |heap| { + heap.metatable(observed[0].table) + }) + .expect("read metatable"); + assert_eq!(current, Some(observed[1].table)); +} + +#[test] +fn raw_nil_guard_allows_a_later_clear() { + let cleared = run_file( + "local owner = {}\n\ + local mt = {}\n\ + mt.__metatable = \"sealed\"\n\ + setmetatable(owner, mt)\n\ + mt.__metatable = nil\n\ + return same_table(setmetatable(owner, nil), owner)\n", + ); + assert!( + matches!(cleared.status, Ok(VmStatus::Halted)), + "{:?}", + cleared.status + ); + assert_eq!(cleared.stack, vec![Value::Bool(true)]); + + let gone = run_file( + "local owner = {}\n\ + local mt = {}\n\ + mt.__metatable = \"sealed\"\n\ + setmetatable(owner, mt)\n\ + mt.__metatable = nil\n\ + setmetatable(owner, nil)\n\ + return type(getmetatable(owner))\n", + ); + assert!( + matches!(gone.status, Ok(VmStatus::Halted)), + "{:?}", + gone.status + ); + assert_eq!(gone.stack, vec![Value::string("nil")]); +} + +#[test] +fn inherited_guard_does_not_protect() { + let source = "\ +local hidden = {}\n\ +hidden.__metatable = \"inherited\"\n\ +local parent = {}\n\ +parent.__index = hidden\n\ +local mt = {}\n\ +local owner = {}\n\ +observe_table(mt, 0)\n\ +observe_table(parent, 0)\n\ +setmetatable(mt, parent)\n\ +setmetatable(owner, mt)\n\ +local replaced = {}\n\ +return same_table(getmetatable(owner), mt)\n"; + let seen = run_file(source); + assert!( + matches!(seen.status, Ok(VmStatus::Halted)), + "{:?}", + seen.status + ); + assert_eq!(seen.stack, vec![Value::Bool(true)]); + + let mut replaced = run_file( + "local hidden = {}\n\ + hidden.__metatable = \"inherited\"\n\ + local parent = {}\n\ + parent.__index = hidden\n\ + local mt = {}\n\ + local owner = {}\n\ + local other = {}\n\ + observe_table(owner, 0)\n\ + observe_table(mt, 0)\n\ + observe_table(parent, 0)\n\ + setmetatable(mt, parent)\n\ + setmetatable(owner, mt)\n\ + return same_table(setmetatable(owner, other), owner)\n", + ); + assert!( + matches!(replaced.status, Ok(VmStatus::Halted)), + "inherited __metatable must not protect: {:?}", + replaced.status + ); + assert_eq!(replaced.stack, vec![Value::Bool(true)]); + let vm = replaced.vm.as_mut().expect("vm"); + let observed = vm + .host_context() + .scope_state::>() + .cloned() + .unwrap_or_default(); + let (owner_mt, mt_parent) = super::heap::with_heap(&mut vm.host_context(), |heap| { + Ok(( + heap.metatable(observed[0].table)?, + heap.metatable(observed[1].table)?, + )) + }) + .expect("read metatables"); + assert_ne!(owner_mt, Some(observed[1].table), "replacement must stick"); + assert_eq!( + mt_parent, + Some(observed[2].table), + "the real metatable keeps its own parent metatable" + ); +} + +#[test] +fn shadowed_guard_does_not_stop_weak_value_collection() { + let source = "\ +local mt = {}\n\ +mt.__mode = \"v\"\n\ +mt.__metatable = \"shadow\"\n\ +local weak = {}\n\ +setmetatable(weak, mt)\n\ +local key = {}\n\ +local cycle = {}\n\ +cycle.self = cycle\n\ +weak[key] = cycle\n\ +observe_table(cycle, 0)\n\ +local peer = {}\n\ +peer.self = peer\n\ +observe_table(peer, 0)\n\ +cycle = nil\n\ +note_text(1, getmetatable(weak))\n\ +collectgarbage(\"collect\")\n\ +return type(weak[key])\n"; + let mut run = run_file(source); + assert!( + matches!(run.status, Ok(VmStatus::Halted)), + "{:?}", + run.status + ); + assert_eq!(run.stack, vec![Value::string("nil")]); + let vm = run.vm.as_mut().expect("vm"); + let text = vm + .host_context() + .scope_state::() + .map(|notes| notes.text.clone()) + .unwrap_or_default(); + assert_eq!(text, vec![(1.0, "shadow".to_string())]); + let observed = vm + .host_context() + .scope_state::>() + .cloned() + .unwrap_or_default(); + let stats = super::heap::stats(&mut vm.host_context()).expect("stats"); + assert!(stats.collections >= 1, "collections={}", stats.collections); + let alive = super::heap::with_heap(&mut vm.host_context(), |heap| { + Ok((heap.alive(observed[0].table), heap.alive(observed[1].table))) + }) + .expect("liveness"); + assert_eq!(alive, (false, true), "weak cycle cleared, rooted peer kept"); +} + +/// `false` is a raw guard in LuaJIT, but this heap refuses a boolean named +/// field other than `__mode`. The plant reaches that assert; the query itself +/// already treats every non-nil raw field, including false, as protection. +#[test] +fn false_guard_is_returned_and_blocks_replacement() { + let exposed = run_file( + "local owner = {}\n\ + local mt = {}\n\ + plant_raw_false(mt)\n\ + setmetatable(owner, mt)\n\ + note_bool(1, getmetatable(owner))\n\ + return type(getmetatable(owner))\n", + ); + assert!( + matches!(exposed.status, Ok(VmStatus::Halted)), + "false must be stored as a raw field before the guard can be read: {:?}", + exposed.status + ); + assert_eq!(exposed.stack, vec![Value::string("boolean")]); + let flags = exposed + .vm + .expect("vm") + .host_context() + .scope_state::() + .map(|notes| notes.flags.clone()) + .unwrap_or_default(); + assert_eq!(flags, vec![(1.0, false)]); + + let mut blocked = run_file( + "local owner = {}\n\ + local mt = {}\n\ + observe_table(owner, 0)\n\ + observe_table(mt, 0)\n\ + plant_raw_false(mt)\n\ + setmetatable(owner, mt)\n\ + setmetatable(owner, {})\n\ + return 1\n", + ); + let error = blocked.status.expect_err("false must protect"); + assert!( + error.contains("cannot change a protected metatable"), + "{error}" + ); + let vm = blocked.vm.as_mut().expect("vm"); + let observed = vm + .host_context() + .scope_state::>() + .cloned() + .unwrap_or_default(); + let current = super::heap::with_heap(&mut vm.host_context(), |heap| { + heap.metatable(observed[0].table) + }) + .expect("read metatable"); + assert_eq!(current, Some(observed[1].table)); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 977d7e1..c7492a5 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -19,6 +19,8 @@ mod return_frame; mod source_closure; #[path = "string_byte_length.rs"] mod string_byte_length; +#[path = "table_metatable_protection.rs"] +mod table_metatable_protection; use super::heap; use super::support; @@ -185,6 +187,11 @@ pub(super) fn catalog() -> &'static Arc { ], HostTypeSchema::Bool, )); + builder.function(HostFunctionSchema::with_return( + "lua_host::plant_raw_false", + vec![HostParamSchema::value("owner", HostTypeSchema::Unknown)], + HostTypeSchema::Bool, + )); builder.function(HostFunctionSchema::with_return( "lua_host::caller_reads", vec![ From 72ac433f180682d02ac574a5ea6dbeacb6a7e066 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 03:31:09 +0800 Subject: [PATCH 089/225] fix(lua): store a boolean on a raw named field LuaJIT treats false as a protected __metatable value. Field assignment now lowers a boolean literal onto the existing named scalar edge, so the raw guard is a real write rather than an injected plant. --- src/frontends/lua/heap/table.rs | 9 +- tests/luajit_heap_runtime/candidate.rs | 8 +- .../table_metatable_protection.rs | 97 +++++++++++-------- .../value_boundary_tests.rs | 5 - 4 files changed, 64 insertions(+), 55 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 042170d..c3fbbcf 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -1066,8 +1066,9 @@ impl LuaHeap { /// Writes a scalar under a Lua string key, or deletes that record on nil. /// - /// A number or boolean is accepted only for the reserved mode field. The - /// direct numeric field API stays available for heap tests. + /// A boolean may occupy any raw named field. A number remains only the + /// reserved mode field. The direct numeric field API stays available for + /// heap tests. pub fn set_named_scalar( &mut self, from: TableRef, @@ -1077,8 +1078,8 @@ impl LuaHeap { let key = EdgeKey::named(name); let mode = matches!(key, EdgeKey::Field(Self::MODE_FIELD)); debug_assert!( - matches!(value, Value::Null | Value::String(_)) - || (mode && matches!(value, Value::Float(_) | Value::Bool(_))) + matches!(value, Value::Null | Value::String(_) | Value::Bool(_)) + || (mode && matches!(value, Value::Float(_))) ); self.require_live(from)?; if matches!(value, Value::Null) { diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index a1e0939..b6cc359 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -706,13 +706,10 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { heap::with_heap(&mut host, |heap| heap.set_named_edge(from, &name, to)) } class - if matches!(class, heap::GuestClass::String) + if matches!(class, heap::GuestClass::String | heap::GuestClass::Boolean) || matches!(to_value, Value::Null) || (heap::LuaHeap::names_mode_field(&name) - && matches!( - class, - heap::GuestClass::Number | heap::GuestClass::Boolean - )) => + && matches!(class, heap::GuestClass::Number)) => { heap::with_heap(&mut host, |heap| { heap.set_named_scalar(from, &name, to_value) @@ -3140,6 +3137,7 @@ impl Lower<'_> { ast::Expr::String { bytes, .. } => String::from_utf8(bytes.clone()) .map(Expr::String) .map_err(|_| self.unsupported(expr.span())), + ast::Expr::Bool { value, .. } => Ok(Expr::Bool(*value)), ast::Expr::Number { raw, kind: ast::NumberKind::Integer | ast::NumberKind::Float, diff --git a/tests/luajit_heap_runtime/table_metatable_protection.rs b/tests/luajit_heap_runtime/table_metatable_protection.rs index f96d5c0..79059e6 100644 --- a/tests/luajit_heap_runtime/table_metatable_protection.rs +++ b/tests/luajit_heap_runtime/table_metatable_protection.rs @@ -66,7 +66,6 @@ struct Run { enum Note { Text, Bool, - RawFalse, } #[derive(Default)] @@ -78,34 +77,6 @@ struct Notes { impl vm::HostOwnedFunction for Note { fn call(&mut self, call: &mut vm::OwnedHostCall<'_>) -> Result { let args = call.args().to_vec(); - if matches!(self, Self::RawFalse) { - let owner = match args.as_slice() { - [owner] => owner.clone(), - _ => { - return Err(vm::VmError::HostError( - "false guard plant expected one table".to_string(), - )); - } - }; - let mut host = call.vm().host_context(); - let table = match super::heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&owner))) - .map_err(|error| vm::VmError::HostError(error.to_string()))? - { - super::heap::GuestClass::Table(table) => table, - _ => { - return Err(vm::VmError::HostError( - "false guard plant expected a table".to_string(), - )); - } - }; - super::heap::with_heap(&mut host, |heap| { - heap.set_named_scalar(table, "__metatable", Value::Bool(false)) - }) - .map_err(|error| vm::VmError::HostError(error.to_string()))?; - return Ok(vm::CallOutcome::Return(vm::CallReturn::one(Value::Bool( - true, - )))); - } let mut host = call.vm().host_context(); let notes = host .scope_state_or_insert_with(Notes::default) @@ -129,7 +100,6 @@ impl vm::HostOwnedFunction for Note { }; notes.flags.push((tag, flag)); } - Self::RawFalse => unreachable!("planted before notes"), } Ok(vm::CallOutcome::Return(vm::CallReturn::one(Value::Bool( true, @@ -198,7 +168,6 @@ fn run_file(source: &str) -> Run { for (name, note) in [ ("lua_host::note_text", Note::Text), ("lua_host::note_bool", Note::Bool), - ("lua_host::plant_raw_false", Note::RawFalse), ] { if let Err(error) = register_note(&mut registry, &catalog, name, note) { return Run { @@ -568,25 +537,29 @@ return type(weak[key])\n"; assert_eq!(alive, (false, true), "weak cycle cleared, rooted peer kept"); } -/// `false` is a raw guard in LuaJIT, but this heap refuses a boolean named -/// field other than `__mode`. The plant reaches that assert; the query itself -/// already treats every non-nil raw field, including false, as protection. +/// `false` is a raw guard. A real field write stores it; `getmetatable` +/// returns that boolean, and `setmetatable` cannot replace or clear the +/// owner until the raw field is nil. #[test] fn false_guard_is_returned_and_blocks_replacement() { let exposed = run_file( "local owner = {}\n\ local mt = {}\n\ - plant_raw_false(mt)\n\ + mt.__metatable = false\n\ setmetatable(owner, mt)\n\ note_bool(1, getmetatable(owner))\n\ - return type(getmetatable(owner))\n", + return getmetatable(owner)\n", ); assert!( matches!(exposed.status, Ok(VmStatus::Halted)), - "false must be stored as a raw field before the guard can be read: {:?}", + "false must be stored by field assignment before the guard can be read: {:?}", exposed.status ); - assert_eq!(exposed.stack, vec![Value::string("boolean")]); + assert_eq!( + exposed.stack, + vec![Value::Bool(false)], + "getmetatable must return the stored false, not a string or the real metatable" + ); let flags = exposed .vm .expect("vm") @@ -601,15 +574,15 @@ fn false_guard_is_returned_and_blocks_replacement() { local mt = {}\n\ observe_table(owner, 0)\n\ observe_table(mt, 0)\n\ - plant_raw_false(mt)\n\ + mt.__metatable = false\n\ setmetatable(owner, mt)\n\ setmetatable(owner, {})\n\ return 1\n", ); - let error = blocked.status.expect_err("false must protect"); + let error = blocked.status.expect_err("false must protect replacement"); assert!( error.contains("cannot change a protected metatable"), - "{error}" + "candidate host error, not a pcall string: {error}" ); let vm = blocked.vm.as_mut().expect("vm"); let observed = vm @@ -622,4 +595,46 @@ fn false_guard_is_returned_and_blocks_replacement() { }) .expect("read metatable"); assert_eq!(current, Some(observed[1].table)); + + let mut cleared = run_file( + "local owner = {}\n\ + local mt = {}\n\ + observe_table(owner, 0)\n\ + observe_table(mt, 0)\n\ + mt.__metatable = false\n\ + setmetatable(owner, mt)\n\ + setmetatable(owner, nil)\n\ + return 1\n", + ); + let error = cleared.status.expect_err("false must protect clear"); + assert!( + error.contains("cannot change a protected metatable"), + "{error}" + ); + let vm = cleared.vm.as_mut().expect("vm"); + let observed = vm + .host_context() + .scope_state::>() + .cloned() + .unwrap_or_default(); + let current = super::heap::with_heap(&mut vm.host_context(), |heap| { + heap.metatable(observed[0].table) + }) + .expect("read metatable"); + assert_eq!(current, Some(observed[1].table)); + + let released = run_file( + "local owner = {}\n\ + local mt = {}\n\ + mt.__metatable = false\n\ + setmetatable(owner, mt)\n\ + mt.__metatable = nil\n\ + return same_table(setmetatable(owner, nil), owner)\n", + ); + assert!( + matches!(released.status, Ok(VmStatus::Halted)), + "nil raw field must allow a later clear: {:?}", + released.status + ); + assert_eq!(released.stack, vec![Value::Bool(true)]); } diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index c7492a5..0d38fc7 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -187,11 +187,6 @@ pub(super) fn catalog() -> &'static Arc { ], HostTypeSchema::Bool, )); - builder.function(HostFunctionSchema::with_return( - "lua_host::plant_raw_false", - vec![HostParamSchema::value("owner", HostTypeSchema::Unknown)], - HostTypeSchema::Bool, - )); builder.function(HostFunctionSchema::with_return( "lua_host::caller_reads", vec![ From 59805c158b637361f7b9238dbe7e7f3666749e09 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 03:41:47 +0800 Subject: [PATCH 090/225] feat(lua): lower unbound rawset onto the existing edge write SET_EDGE returns the issued receiver on success. Both assignment sites still discard that value. Unbound rawset evaluates its three arguments left to right and uses the same rooted operands and write. --- tests/luajit_heap_runtime/candidate.rs | 40 +- tests/luajit_heap_runtime/rawset.rs | 636 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 3 files changed, 674 insertions(+), 4 deletions(-) create mode 100644 tests/luajit_heap_runtime/rawset.rs diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index b6cc359..e950ead 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -143,7 +143,8 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { vec!["value", "slot", "role"], HostTypeSchema::Float, ), - (SET_EDGE, vec!["from", "key", "to"], HostTypeSchema::Float), + // Success returns the issued receiver. Assignment discards it. + (SET_EDGE, vec!["from", "key", "to"], HostTypeSchema::Unknown), (GET_EDGE, vec!["table", "key"], HostTypeSchema::Unknown), (NEXT, vec!["table", "cursor"], HostTypeSchema::Unknown), (NOTE_NEXT_COUNT, vec!["count"], HostTypeSchema::Float), @@ -690,11 +691,11 @@ fn write_number_edge( } fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { - let (from, key_value, to_value) = match call.args() { + let (issued, key_value, to_value) = match call.args() { [from, key, to] => (from.clone(), key.clone(), to.clone()), _ => return Err(host_fault("invalid table edge")), }; - let from = match classify(&mut call.vm().host_context(), &from)? { + let from = match classify(&mut call.vm().host_context(), &issued)? { heap::GuestClass::Table(table) => table, _ => return Err(host_fault("edge source is not a table")), }; @@ -752,7 +753,7 @@ fn set_edge(call: &mut OwnedHostCall<'_>) -> Result { } } } - Ok(Value::Float(0.0)) + Ok(issued) } fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { @@ -2786,6 +2787,25 @@ impl Lower<'_> { self.emit_ignored(expr, self.line(span)) } + /// Same rooted operands and write as index assignment. The call result is + /// the issued receiver; a statement call discards it through `emit_ignored`. + fn rawset_expr( + &mut self, + table: &ast::Expr, + key: &ast::Expr, + value: &ast::Expr, + span: ast::Span, + ) -> Result { + let temp_base = self.active_temps.len(); + let (from, key_slot) = self.index_operands(table, key, span)?; + let to = match value { + ast::Expr::Nil { .. } => Expr::Null, + other => self.expr(other)?, + }; + self.active_temps.truncate(temp_base); + self.call(SET_EDGE, vec![Expr::Var(from), Expr::Var(key_slot), to]) + } + fn index_read( &mut self, base: &ast::Expr, @@ -3300,6 +3320,18 @@ impl Lower<'_> { self.reject_tail_next(key, expr.span())?; return self.index_read(table, key, expr.span()); } + if name.is("rawset") { + // A resolver binding is not yet in `locals` for an upvalue + // use. Do not treat that name as the builtin. + if self.name_is_bound(name) { + return Err(self.unsupported(expr.span())); + } + let [table, key, value] = args.exprs.as_slice() else { + return Err(self.unsupported(expr.span())); + }; + self.reject_tail_next(value, expr.span())?; + return self.rawset_expr(table, key, value, expr.span()); + } if name.is("external_shape") && args.exprs.is_empty() { return self.call(EXTERNAL_SHAPE, vec![]); } diff --git a/tests/luajit_heap_runtime/rawset.rs b/tests/luajit_heap_runtime/rawset.rs new file mode 100644 index 0000000..c5138c4 --- /dev/null +++ b/tests/luajit_heap_runtime/rawset.rs @@ -0,0 +1,636 @@ +//! Unbound `rawset` for the Lua 5.2 candidate. +//! +//! Real `.lua` files go through `compile_source_file_with_options`, the +//! candidate plugin, and Core. The write is the existing edge operation. +//! This slice does not add key categories, `__newindex`, `pcall`, or a +//! public host ABI. LuaJIT's `__newindex` / `pcall` receipt stays outside +//! these assertions: this candidate does not dispatch metatable writes. +//! +//! A source key `-0.0` is not an index operand here. Unary minus is only +//! lowered for a proven scalar store, so the numeric contrast uses +//! `float_bits(1)`, the candidate's existing negative zero. + +use std::fs; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use vm::{ + CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, ParseError, + SourceFlavor, SourcePlugin, Value, VmStatus, +}; + +use super::candidate; +use super::heap; + +struct Plugin; + +impl SourcePlugin for Plugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, super::catalog()) + } +} + +struct Attempt { + vm: vm::Vm, + stack: Result, String>, +} + +fn claim_file(label: &str, source: &str) -> PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(1); + let parent = std::env::temp_dir().join("compat-frontends-lua-source-fixtures"); + fs::create_dir_all(&parent) + .unwrap_or_else(|error| panic!("create {}: {error}", parent.display())); + let pid = std::process::id(); + let root = loop { + let ticket = NEXT.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!("rawset-{label}-{pid}-{ticket}")); + match fs::create_dir(&candidate) { + Ok(()) => break candidate, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("claim {}: {error}", candidate.display()), + } + }; + let path = root.join("chunk.lua"); + fs::write(&path, source).unwrap_or_else(|error| panic!("write {}: {error}", path.display())); + path +} + +fn attempt(label: &str, source: &str) -> Result { + let path = claim_file(label, source); + let catalog = std::sync::Arc::clone(super::catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(std::sync::Arc::clone(&catalog)); + let prepared = vm::compile_source_file_with_options(&path, options).map_err(|error| { + format!( + "{}: compile_source_file_with_options: {error}", + path.display() + ) + })?; + let mut vm = prepared + .into_vm() + .map_err(|error| format!("{}: vm: {error}", path.display()))?; + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog) + .map_err(|error| format!("{}: register: {error}", path.display()))?; + super::register_witnesses(&mut registry, &catalog); + registry + .bind_vm_cached(&mut vm) + .map_err(|error| format!("{}: bind: {error}", path.display()))?; + let stack = match vm.run() { + Ok(status) => { + assert_eq!(status, VmStatus::Halted, "{}", path.display()); + Ok(vm.stack().to_vec()) + } + Err(error) => Err(format!("{}: {error}", path.display())), + }; + Ok(Attempt { vm, stack }) +} + +fn run(label: &str, source: &str) -> Attempt { + let ran = attempt(label, source).unwrap_or_else(|error| panic!("{label}: {error}")); + if let Err(message) = &ran.stack { + panic!("{label}: runtime error: {message}"); + } + ran +} + +fn refuse(label: &str, source: &str) -> String { + match attempt(label, source) { + Err(message) => message, + Ok(ran) => panic!( + "{label}: lowered a refused shape, stack {:?}", + ran.vm.stack() + ), + } +} + +fn host_fault(label: &str, source: &str) -> (vm::Vm, String) { + let ran = attempt(label, source).unwrap_or_else(|error| panic!("{label}: {error}")); + let Err(message) = ran.stack else { + panic!("{label}: expected a host fault, stack {:?}", ran.vm.stack()); + }; + (ran.vm, message) +} + +fn stats(vm: &mut vm::Vm) -> heap::HeapStats { + heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.stats())).expect("heap stats") +} + +fn stack_of(ran: &Attempt) -> &[Value] { + ran.stack.as_ref().expect("halted stack") +} + +const WEAK_ORPHAN: &str = r#"local mt = {} +mt.__mode = "v" +local weak = {} +setmetatable(weak, mt) +local orphan = {} +orphan.self = orphan +weak[1] = orphan +orphan = nil +"#; + +#[test] +fn lua_file_rawset_returns_the_issued_receiver() { + let owner = run( + "receiver", + r#"local owner = {} +local value = {} +return same_table(rawset(owner, 1, value), owner) +"#, + ); + assert_eq!(stack_of(&owner), &[Value::Bool(true)]); + + let not_value = run( + "not-value", + r#"local owner = {} +local value = {} +return same_table(rawset(owner, 1, value), value) +"#, + ); + assert_eq!( + stack_of(¬_value), + &[Value::Bool(false)], + "rawset must return the receiver, not the stored value" + ); +} + +#[test] +fn lua_file_rawset_shares_storage_with_rawget_and_assignment() { + let from_rawset = run( + "string-rawget", + r#"local owner = {} +rawset(owner, "name", "yes") +return rawget(owner, "name") +"#, + ); + assert_eq!(stack_of(&from_rawset), &[Value::string("yes")]); + + let from_index = run( + "string-index", + r#"local owner = {} +rawset(owner, "name", "yes") +return owner["name"] +"#, + ); + assert_eq!(stack_of(&from_index), &[Value::string("yes")]); + + let from_field = run( + "string-field", + r#"local owner = {} +rawset(owner, "name", "yes") +return owner.name +"#, + ); + assert_eq!(stack_of(&from_field), &[Value::string("yes")]); + + let from_assign = run( + "assign-rawget", + r#"local owner = {} +owner["slot"] = "from-assign" +return rawget(owner, "slot") +"#, + ); + assert_eq!(stack_of(&from_assign), &[Value::string("from-assign")]); + + let mut split = run( + "split-keys", + r#"local owner = {} +rawset(owner, 1, "number") +rawset(owner, "1", "string") +return rawget(owner, 1) +"#, + ); + assert_eq!(stack_of(&split), &[Value::string("number")]); + assert_eq!( + stats(&mut split.vm).live_edges, + 2, + "string and number keys stay distinct" + ); + let string_key = run( + "split-string", + r#"local owner = {} +rawset(owner, 1, "number") +rawset(owner, "1", "string") +return rawget(owner, "1") +"#, + ); + assert_eq!(stack_of(&string_key), &[Value::string("string")]); +} + +#[test] +fn lua_file_rawset_keeps_object_key_identity() { + let ran = run( + "object-key", + r#"local owner = {} +local key = {} +local value = {} +local written = rawset(owner, key, value) +return same_table(rawget(written, key), value) +"#, + ); + assert_eq!(stack_of(&ran), &[Value::Bool(true)]); + let same_owner = run( + "object-owner", + r#"local owner = {} +local key = {} +local value = {} +return same_table(rawset(owner, key, value), owner) +"#, + ); + assert_eq!(stack_of(&same_owner), &[Value::Bool(true)]); +} + +#[test] +fn lua_file_rawset_updates_and_deletes_with_explicit_nil() { + let mut updated = run( + "update", + r#"local owner = {} +rawset(owner, 1, "first") +rawset(owner, 1, "second") +return rawget(owner, 1) +"#, + ); + assert_eq!(stack_of(&updated), &[Value::string("second")]); + assert_eq!( + stats(&mut updated.vm).live_edges, + 1, + "update replaces one edge" + ); + + let mut deleted = run( + "delete", + r#"local owner = {} +rawset(owner, 1, "first") +rawset(owner, 1, nil) +return rawget(owner, 1) +"#, + ); + assert_eq!(stack_of(&deleted), &[Value::Null]); + assert_eq!( + stats(&mut deleted.vm).live_edges, + 0, + "explicit nil removes the edge" + ); +} + +#[test] +fn lua_file_rawset_writes_negative_zero_into_the_zero_slot() { + let wrote = run( + "neg-zero-write", + r#"local owner = {} +rawset(owner, (float_bits(1)), "negzero") +return rawget(owner, 0) +"#, + ); + assert_eq!(stack_of(&wrote), &[Value::string("negzero")]); + + let read = run( + "neg-zero-read", + r#"local owner = {} +rawset(owner, 0, "zero") +return rawget(owner, (float_bits(1))) +"#, + ); + assert_eq!(stack_of(&read), &[Value::string("zero")]); +} + +#[test] +fn lua_file_rawset_calls_a_local_function_of_the_same_name() { + let local_fn = run( + "local-fn", + r#"local function rawset() + return 7 +end +local n = rawset() +return n +"#, + ); + assert_eq!(stack_of(&local_fn), &[Value::Float(7.0)]); + + let after_block = run( + "after-block", + r#"do + local rawset = 1 +end +local owner = {} +rawset(owner, 1, "kept") +return rawget(owner, 1) +"#, + ); + assert_eq!(stack_of(&after_block), &[Value::string("kept")]); +} + +#[test] +fn lua_file_rawset_does_not_capture_a_bound_name() { + let chunk = refuse( + "chunk-shadow", + r#"local rawset = 1 +local owner = {} +owner[1] = "kept" +rawset(owner, 1, "nope") +return owner[1] +"#, + ); + assert!( + chunk.contains("Lua expression not lowered yet"), + "a chunk local must not become builtin rawset, got {chunk}" + ); + + let inside = refuse( + "function-shadow", + r#"local rawset = 1 +local function probe() + local owner = {} + rawset(owner, 1, "nope") +end +return 1 +"#, + ); + assert!( + inside.contains("Lua expression not lowered yet"), + "an upvalue binding must not become builtin rawset, got {inside}" + ); + + let unbound = run( + "function-unbound", + r#"local function probe() + local owner = {} + rawset(owner, 1, "kept") +end +return 1 +"#, + ); + assert_eq!( + stack_of(&unbound), + &[Value::Float(1.0)], + "an unbound call inside a function is still the builtin" + ); +} + +#[test] +fn lua_file_rawset_rejects_nil_and_nan_keys_without_deleting() { + let nil_assign = host_fault( + "nil-assign", + r#"local owner = {} +owner[1] = "stay" +local k = nil +owner[k] = "nope" +"#, + ); + let (mut nil_write_vm, nil_write) = host_fault( + "nil-write", + r#"local owner = {} +owner[1] = "stay" +local k = nil +rawset(owner, k, "nope") +"#, + ); + assert!( + nil_assign.1.contains("edge key is not a table"), + "assignment nil key: {}", + nil_assign.1 + ); + assert!( + nil_write.contains("edge key is not a table"), + "rawset nil key must use the assignment error, got {nil_write}" + ); + assert_eq!(stats(&mut nil_write_vm).live_edges, 1); + + let (mut nil_delete_vm, nil_delete) = host_fault( + "nil-delete", + r#"local owner = {} +owner[1] = "stay" +local k = nil +rawset(owner, k, nil) +"#, + ); + assert!( + nil_delete.contains("edge key is not a table"), + "nil key must not take the delete path, got {nil_delete}" + ); + assert_eq!( + stats(&mut nil_delete_vm).live_edges, + 1, + "a nil key must not delete the existing edge" + ); + + let nan_assign = host_fault( + "nan-assign", + r#"local owner = {} +owner[1] = "stay" +local k = float_bits(2) +owner[k] = "nope" +"#, + ); + let (mut nan_write_vm, nan_write) = host_fault( + "nan-write", + r#"local owner = {} +owner[1] = "stay" +local k = float_bits(2) +rawset(owner, k, "nope") +"#, + ); + assert!( + nan_assign.1.contains("table index is NaN"), + "assignment NaN key: {}", + nan_assign.1 + ); + assert!( + nan_write.contains("table index is NaN"), + "rawset NaN key: {nan_write}" + ); + assert_eq!(stats(&mut nan_write_vm).live_edges, 1); + + let (mut nan_delete_vm, nan_delete) = host_fault( + "nan-delete", + r#"local owner = {} +owner[1] = "stay" +local k = float_bits(2) +rawset(owner, k, nil) +"#, + ); + assert!( + nan_delete.contains("table index is NaN"), + "NaN key must not take the delete path, got {nan_delete}" + ); + assert_eq!(stats(&mut nan_delete_vm).live_edges, 1); +} + +#[test] +fn lua_file_rawset_missing_value_is_not_a_nil_delete() { + for (label, source) in [ + ("no-args", "return rawset()\n"), + ("one-arg", "local owner = {}\nreturn rawset(owner)\n"), + ( + "two-args", + "local owner = {}\nowner[1] = \"stay\"\nreturn rawset(owner, 1)\n", + ), + ] { + let message = refuse(label, source); + assert!( + message.contains("Lua expression not lowered yet"), + "{label} must not default a missing argument to nil, got {message}" + ); + } + + let mut deleted = run( + "explicit-nil", + r#"local owner = {} +owner[1] = "stay" +rawset(owner, 1, nil) +return rawget(owner, 1) +"#, + ); + assert_eq!(stack_of(&deleted), &[Value::Null]); + assert_eq!(stats(&mut deleted.vm).live_edges, 0); +} + +#[test] +fn lua_file_rawset_collects_during_the_value_without_extra_roots() { + let mut quiet = run( + "quiet-collect", + &format!("{WEAK_ORPHAN}collectgarbage(\"collect\")\nreturn type(weak[1])\n"), + ); + assert_eq!(stack_of(&quiet), &[Value::string("nil")]); + let quiet_marked = stats(&mut quiet.vm).last_marked; + + let (mut during, message) = host_fault( + "value-collect", + &format!("{WEAK_ORPHAN}rawset({{}}, ({{}}), collectgarbage(\"collect\"))\n"), + ); + assert!( + message.contains("edge target is not a table"), + "value collect must still reach the write, got {message}" + ); + let during_stats = stats(&mut during); + assert_eq!( + during_stats.collections, 1, + "the value expression must collect" + ); + assert_eq!( + during_stats.last_marked, + quiet_marked + 2, + "only the fresh receiver and key are extra roots during the value collect" + ); +} + +#[test] +fn lua_file_rawset_does_not_check_the_table_before_later_arguments() { + let (mut skipped, skipped_message) = host_fault( + "check-without-collect", + &format!("{WEAK_ORPHAN}rawset(0, 1, \"later\")\n"), + ); + assert!( + skipped_message.contains("edge source is not a table"), + "number receiver: {skipped_message}" + ); + let skipped_nodes = stats(&mut skipped).live_nodes; + + let (mut checked, message) = host_fault( + "check-after-key", + &format!("{WEAK_ORPHAN}rawset(0, (collectgarbage(\"collect\")), \"later\")\n"), + ); + assert!( + message.contains("edge source is not a table"), + "later key side effect must still reach the table check, got {message}" + ); + let checked_stats = stats(&mut checked); + assert_eq!( + checked_stats.collections, 1, + "the key collect must run before the table check" + ); + assert_eq!( + checked_stats.live_nodes + 1, + skipped_nodes, + "the weak orphan must be swept by that key collect" + ); +} + +#[test] +fn lua_file_rawset_evaluates_key_and_value_once() { + // A table-yielding expression with its own side-effect counter is not + // expressible: a local function call used as a value lowers to nil. + // The key and value can each collect once, and the stored string shows + // the value expression's single type() result. + let mut ran = run( + "once", + r#"local owner = {} +local written = rawset(owner, (collectgarbage("collect")), type(collectgarbage("collect"))) +return rawget(written, 0) +"#, + ); + assert_eq!(stack_of(&ran), &[Value::string("number")]); + assert_eq!( + stats(&mut ran.vm).collections, + 2, + "each collect expression ran once" + ); + let identity = run( + "once-identity", + r#"local owner = {} +return same_table(rawset(owner, (collectgarbage("collect")), type(collectgarbage("collect"))), owner) +"#, + ); + assert_eq!(stack_of(&identity), &[Value::Bool(true)]); +} + +#[test] +fn lua_file_rawset_discarded_return_is_not_an_extra_root() { + let mut held = run( + "held-receiver", + &format!( + "{WEAK_ORPHAN}local key = {{}}\nlocal holder = rawset({{}}, key, \"kept\")\ncollectgarbage(\"collect\")\nreturn rawget(holder, key)\n" + ), + ); + assert_eq!(stack_of(&held), &[Value::string("kept")]); + let held_nodes = stats(&mut held.vm).live_nodes; + + let mut dropped = run( + "dropped-receiver", + &format!( + "{WEAK_ORPHAN}local key = {{}}\nrawset({{}}, key, \"kept\")\ncollectgarbage(\"collect\")\nreturn type(weak[1])\n" + ), + ); + assert_eq!( + stack_of(&dropped), + &[Value::string("nil")], + "the later collect must clear the weak orphan" + ); + assert_eq!( + stats(&mut dropped.vm).live_nodes + 1, + held_nodes, + "a statement rawset must not root the discarded receiver" + ); +} + +#[test] +fn lua_file_assignment_discarded_write_is_not_an_extra_root() { + let mut ran = run( + "assign-drop", + r#"local key = {} +({})[key] = "kept" +collectgarbage("collect") +return type(key) +"#, + ); + assert_eq!(stack_of(&ran), &[Value::string("table")]); + assert_eq!( + stats(&mut ran.vm).live_nodes, + 1, + "assignment must still discard the write result" + ); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 0d38fc7..05456fd 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -17,6 +17,8 @@ mod resolve; mod return_frame; #[path = "source_closure.rs"] mod source_closure; +#[path = "rawset.rs"] +mod rawset; #[path = "string_byte_length.rs"] mod string_byte_length; #[path = "table_metatable_protection.rs"] From 3d3d2172b75ab314035363197c5366fa381d59d8 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 03:49:21 +0800 Subject: [PATCH 091/225] style(lua): order the rawset module registration Move the rawset module registration to the rustfmt position between parser and resolve. No behavior change. --- tests/luajit_heap_runtime/value_boundary_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 05456fd..35046c6 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -12,13 +12,13 @@ mod envelope_local_root; mod lexer; #[path = "../../src/frontends/lua/parser.rs"] mod parser; +#[path = "rawset.rs"] +mod rawset; #[path = "../../src/frontends/lua/resolve.rs"] mod resolve; mod return_frame; #[path = "source_closure.rs"] mod source_closure; -#[path = "rawset.rs"] -mod rawset; #[path = "string_byte_length.rs"] mod string_byte_length; #[path = "table_metatable_protection.rs"] From a8548c88b96be56a6f397ecbf0f33017a959ed4b Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 04:18:06 +0800 Subject: [PATCH 092/225] feat(lua): walk collect edges on owner chains Replace the per-collect outgoing index with address-stable reusable edge slots. Mark follows each marked owner's chain, and logical bytes still charge occupied Edge records, including gaps. --- src/frontends/lua/heap/table.rs | 704 +++++++++++------- tests/luajit_heap_runtime/candidate.rs | 4 +- tests/luajit_heap_runtime/closure_graph.rs | 5 +- tests/luajit_heap_runtime/owner_adjacency.rs | 223 ++++++ .../value_boundary_tests.rs | 24 +- tests/luajit_heap_runtime_tests.rs | 121 +-- 6 files changed, 746 insertions(+), 335 deletions(-) create mode 100644 tests/luajit_heap_runtime/owner_adjacency.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index c3fbbcf..0282577 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -194,8 +194,16 @@ struct Slot { /// array so a field can read it back while the node is live. It contains /// identity only, not object edges, and does not participate in marking. carrier: Option>>, - /// Optional metatable. Not a field key and not an `edges` record. + /// Optional metatable. Not a field key and not an edge record. metatable: Option<(u32, u32)>, + /// Head of this owner's edge chain. `None` means no edges. A reused owner + /// starts with no chain. + edge_head: Option, + /// Tail of this owner's edge chain. New keys append here. + edge_tail: Option, + /// Direct `__mode` edge of a table, if that field is stored. Not a parsed + /// mode, and not set for field 0 on a closure or cell. + mode_edge: Option, } /// Bytes of a string or byte payload stored in a heap record. Capacity is not @@ -228,15 +236,29 @@ fn edge_payload(edge: &Edge) -> u64 { } struct Edge { - from: u32, /// Field ids, object identities, string text, and binary64 numbers share /// this record. An object key is the live slot, generation, and kind. A /// string key is the complete UTF-8 text. A number key is canonical binary64 - /// bits, not a field id and not a collectable node. + /// bits, not a field id and not a collectable node. The owner is the chain + /// that holds this record, not a field of the record. key: EdgeKey, value: EdgeValue, } +/// One address-stable edge record. `next` is the owner-chain link while +/// occupied and the free-list link while free. Deleting a record does not +/// move any other record. +struct EdgeSlot { + next: Option, + edge: Option, +} + +enum SweepAction { + Keep, + Gap, + Drop, +} + enum EdgeValue { Table { slot: u32, @@ -430,24 +452,26 @@ struct Frame { /// counts. A test query after the take is not part of the collection that was /// taken. /// -/// Edge work stays in its own fields. `index_edge_checks` is the two passes -/// that build the outgoing index (2E). `outgoing_edge_checks` counts records -/// inspected from marked nodes. Each followed object target contributes -/// separately to `node_slot_visits`; skipped weak targets do not. -/// `sweep_edge_checks` is that one retain of stored records. It is zero when -/// every live node is marked. Sweep reads modes parsed during mark and does -/// not scan edges again to find `__mode`. Adding those fields is not a total -/// GC cost. +/// Edge work stays in its own fields. Mark walks each marked owner's chain: +/// `outgoing_edge_checks` counts non-gap records on that chain, and +/// `outgoing_gap_checks` counts gaps actually visited there. Neither walk +/// builds an index. `owner_head_checks` counts owner-chain head reads during +/// mark and, when sweep runs, during the owner walk. `sweep_edge_checks` is +/// one visit of each occupied record when any live node is unmarked. It is +/// zero when every live node is marked. Sweep reads modes parsed during the +/// clear-mark slot walk and does not scan edges again to find `__mode`. +/// Adding those fields is not a total GC cost. /// -/// A metatable is not in that edge vector. `metatable_edge_checks` counts +/// A metatable is not in an owner chain. `metatable_edge_checks` counts /// stored metatable refs followed from marked nodes. A collect with none -/// stored does not read those slots, so the three field-edge counters stay -/// the same as a heap that never had a metatable. +/// stored does not read those slots, so the field-edge counters stay the +/// same as a heap that never had a metatable. /// -/// `index_slot_checks` is the one counts-to-offsets walk over index scratch. -/// Its length is the node-slot vector. It is not a heap-node walk. Heap node -/// walks are `node_slot_visits`. Root-vector walks are `root_slot_visits`. -/// Token identity checks stay in `token_slot_checks`. +/// `weak_mode_slot_checks` counts `mode_edge` pointer reads during the +/// clear-mark slot walk. `weak_mode_edge_checks` counts the edge records +/// those pointers actually open. A non-table field 0 has no mode pointer. +/// Heap node walks are `node_slot_visits`. Root-vector walks are +/// `root_slot_visits`. Token identity checks stay in `token_slot_checks`. /// /// `scratch` records element counts the collector asked Rust to initialize, /// copy, reserve, or push. Those are measured requests. They are not allocator @@ -461,20 +485,29 @@ struct Frame { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ScanMeter { pub mark_passes: u64, - pub index_edge_checks: u64, - pub index_slot_checks: u64, pub outgoing_edge_checks: u64, + /// Gaps visited while walking a marked owner's chain. Not included in + /// `outgoing_edge_checks`. + pub outgoing_gap_checks: u64, + /// Owner-chain head reads. Mark reads one per marked node. Sweep, when it + /// runs, reads one per node slot. + pub owner_head_checks: u64, pub sweep_edge_checks: u64, /// Stored metatable references followed from a marked node. /// /// A metatable is an optional per-slot reference, not a field-edge record - /// and not an integer key. It is not included in `index_edge_checks`, - /// `outgoing_edge_checks`, or `sweep_edge_checks`. A heap with no stored - /// metatable reference does not read this path, so those collects add zero - /// and leave the field-edge counts unchanged. + /// and not an integer key. It is not included in `outgoing_edge_checks` + /// or `sweep_edge_checks`. A heap with no stored metatable reference does + /// not read this path, so those collects add zero and leave the field-edge + /// counts unchanged. pub metatable_edge_checks: u64, /// Bytes examined while parsing direct string modes (including a NUL terminator if present). pub weak_mode_bytes: u64, + /// `mode_edge` pointer reads during the clear-mark slot walk. + pub weak_mode_slot_checks: u64, + /// Mode-edge records opened through those pointers. A missing pointer is + /// not an edge read. A non-table field 0 is not a mode pointer. + pub weak_mode_edge_checks: u64, /// Mode lookups by live metatable slot when a weak mode was indexed. pub weak_mode_lookups: u64, pub token_slot_checks: u64, @@ -497,17 +530,7 @@ pub struct ScanMeter { /// the request. This is not an observation of RSS or global allocation. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ScanScratch { - /// `counts` zero-initialized to the node-slot length. - pub index_counts_inited: u64, - /// Capacity requested for `offsets` (`slots + 1`). - pub index_offsets_reserved: u64, - /// Elements pushed into `offsets`. - pub index_offsets_pushed: u64, - /// Elements copied into `cursor` from `offsets`. - pub index_cursor_copied: u64, - /// Outgoing index entries zero-initialized to the in-range edge total. - pub index_targets_inited: u64, - /// Slot-indexed modes zero-initialized on the first weak mode in the index. + /// Slot-indexed modes zero-initialized on the first weak mode during mark. pub weak_modes_inited: u64, /// Work-stack pushes. One per newly marked node. Not a reserve. pub work_pushed: u64, @@ -528,18 +551,10 @@ pub(super) struct DoomedToken { pub(super) generation: u32, } -/// Temporary outgoing-edge index for one mark. Offsets and entries drop when -/// mark returns. Parsed weak modes move to sweep for that same collect and -/// are not stored on the heap. -struct OutgoingIndex { - offsets: Vec, - entries: Vec, - weak_modes: Option>, -} - -/// Weak modes parsed while building the outgoing index. Sweep borrows this -/// for the same collect, then drops it. A close error before sweep drops it -/// with the mark result, so the next collect parses again. +/// Parsed weak modes for one collect. Built during the clear-mark slot walk +/// from each table's direct `__mode` pointer, then borrowed by sweep. A close +/// error before sweep drops it with the mark result, so the next collect +/// parses again. It is not stored on the heap. pub(super) struct MarkSnapshot { modes: Option>, } @@ -597,7 +612,13 @@ pub struct LuaHeap { limits: HeapLimits, slots: Vec, free_list: Vec, - edges: Vec, + edge_slots: Vec, + /// Free-list head of unoccupied edge records. Reused before the backing grows. + edge_free_head: Option, + /// Occupied edge records, including cursor gaps and excluding free slots. + occupied_edges: u32, + /// Occupied records whose value is not a cursor gap. + live_edge_count: u32, /// Stored metatable refs. Zero means mark does not read metatable slots. metatable_edges: u32, roots: Vec>, @@ -626,7 +647,10 @@ impl LuaHeap { limits, slots: Vec::new(), free_list: Vec::new(), - edges: Vec::new(), + edge_slots: Vec::new(), + edge_free_head: None, + occupied_edges: 0, + live_edge_count: 0, metatable_edges: 0, roots: Vec::new(), frames: Vec::new(), @@ -680,6 +704,9 @@ impl LuaHeap { slot.token = None; slot.carrier = None; slot.metatable = None; + slot.edge_head = None; + slot.edge_tail = None; + slot.mode_edge = None; return Ok((index, slot.generation)); } if self.slots.len() >= self.limits.nodes as usize { @@ -696,6 +723,9 @@ impl LuaHeap { token: None, carrier: None, metatable: None, + edge_head: None, + edge_tail: None, + mode_edge: None, }); self.note_node_peak(); Ok((index, 1)) @@ -884,15 +914,7 @@ impl LuaHeap { pub fn clear_upvalue(&mut self, cell: UpvalueRef) -> Result<(), HeapError> { self.require_upvalue(cell)?; let key = EdgeKey::Field(CURRENT_EDGE); - let mut released = 0u64; - self.edges.retain(|edge| { - let drop = edge.from == cell.slot() && edge.key == key; - if drop { - released += edge_payload(edge); - } - !drop - }); - self.payload_bytes -= released; + self.unlink_key(cell.slot(), &key); Ok(()) } @@ -1262,15 +1284,7 @@ impl LuaHeap { } fn clear_edge(&mut self, from: TableRef, key: &EdgeKey) { - let mut released = 0u64; - self.edges.retain(|edge| { - let drop = edge.from == from.slot() && &edge.key == key; - if drop { - released += edge_payload(edge); - } - !drop - }); - self.payload_bytes -= released; + self.unlink_key(from.slot(), key); } fn write_table_edge( @@ -1306,44 +1320,48 @@ impl LuaHeap { key: EdgeKey, value: EdgeValue, ) -> Result<(), HeapError> { - if let Some(index) = self - .edges - .iter() - .position(|edge| edge.from == from_slot && edge.key == key) - { - let removed = value_payload(&self.edges[index].value); - let added = value_payload(&value); - self.edges[index].value = value; - self.payload_bytes = self.payload_bytes - removed + added; + if let Some(index) = self.find_key(from_slot, &key) { + self.replace_edge_value(from_slot, index, value); return Ok(()); } - if self.edges.len() >= self.limits.edges as usize && !self.reclaim_cursor_gap() { + if self.occupied_edges >= self.limits.edges && !self.reclaim_cursor_gap() { return Err(HeapError::EdgeCapacity); } let added = key_payload(&key) + value_payload(&value); - self.edges.push(Edge { - from: from_slot, - key, - value, - }); + let index = self.take_edge_slot(); + self.edge_slots[index as usize].edge = Some(Edge { key, value }); + self.append_tail(from_slot, index); self.payload_bytes += added; + self.occupied_edges += 1; + self.live_edge_count += 1; + self.note_mode_pointer(from_slot, index); self.note_edge_peak(); Ok(()) } /// Drops one valueless cursor so a real edge can use that storage. /// Lua does not keep an old cursor valid across this structural change. + /// The search is one owner-chain walk and stops at the first gap. The + /// removal uses the same unlink as an explicit delete. fn reclaim_cursor_gap(&mut self) -> bool { - let Some(index) = self - .edges - .iter() - .position(|edge| edge.value.is_cursor_gap()) - else { - return false; - }; - let edge = self.edges.remove(index); - self.payload_bytes -= edge_payload(&edge); - true + for owner in 0..self.slots.len() { + let mut prev = None; + let mut cursor = self.slots[owner].edge_head; + while let Some(index) = cursor { + let next = self.edge_slots[index as usize].next; + let gap = self.edge_slots[index as usize] + .edge + .as_ref() + .is_some_and(|edge| edge.value.is_cursor_gap()); + if gap { + self.unlink_at(owner as u32, prev, index); + return true; + } + prev = Some(index); + cursor = next; + } + } + false } /// Reads the table target of a direct field through either alias of `from`. @@ -1367,7 +1385,7 @@ impl LuaHeap { self.stored_value(from, |stored| stored.matches_name(name)) } - /// Next raw entry of `table` after `cursor`, in stored edge order. + /// Next raw entry of `table` after `cursor`, in owner-chain order. /// /// `Value::Null` starts at the first valued edge. `None` is the end: one /// nil, not an empty pair. A weak-cleared entry keeps its key in that order @@ -1375,10 +1393,12 @@ impl LuaHeap { /// with that key continues at the next valued entry or one nil at the end. /// A missing key and a non-guest key are errors, not the end and not a /// restart. An explicit removal drops the key. A later write of the same - /// key reuses the record. Inserting a different key may drop an old cursor - /// when edge storage is full; Lua does not keep cursors across that change. - /// This walks `edges`. It does not allocate another table and does not read - /// a metamethod. + /// key reuses that record in place. A new key, including a key that was + /// deleted, appends at the tail even when the record reuses a low slot. + /// Inserting a different key may drop an old cursor when edge storage is + /// full; Lua does not keep cursors across that change. This walks the + /// owner's chain. It does not allocate another table and does not read a + /// metamethod. pub fn next_guest( &self, table: TableRef, @@ -1420,10 +1440,17 @@ impl LuaHeap { cursor: Option>, ) -> Result, HeapError> { let mut passed = cursor.is_none(); - for edge in &self.edges { - if edge.from != slot { - continue; - } + let mut index = self + .slots + .get(slot as usize) + .and_then(|owner| owner.edge_head); + while let Some(current) = index { + let record = &self.edge_slots[current as usize]; + let edge = record + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + index = record.next; if !passed { if cursor .as_ref() @@ -1528,24 +1555,27 @@ impl LuaHeap { } fn stored_from(&self, from_slot: u32, key: &EdgeKey) -> Option<&EdgeValue> { - self.edges - .iter() - .find(|edge| edge.from == from_slot && &edge.key == key) + let index = self.find_key(from_slot, key)?; + self.edge_slots[index as usize] + .edge + .as_ref() .map(|edge| &edge.value) } - /// One scan of the heap edge vector. `from` is checked before any key test. - /// The predicate selects the stored key. This does not build another table. + /// One walk of the owner's chain. The predicate selects the stored key. + /// This does not build another table. fn read_edge( &self, from: TableRef, matches_key: impl Fn(&EdgeKey) -> bool, ) -> Result, HeapError> { self.require_live(from)?; - Ok(self - .edges - .iter() - .find(|edge| edge.from == from.slot() && matches_key(&edge.key)) + let Some(index) = self.find_matching(from.slot(), matches_key) else { + return Ok(None); + }; + Ok(self.edge_slots[index as usize] + .edge + .as_ref() .map(|edge| &edge.value)) } @@ -1848,14 +1878,10 @@ impl LuaHeap { HeapStats { live_nodes: self.live_nodes(), live_roots: self.live_roots(), - live_edges: self - .edges - .iter() - .filter(|edge| !edge.value.is_cursor_gap()) - .count() as u32, + live_edges: self.live_edge_count, node_slots: self.slots.len() as u32, root_slots: self.roots.len() as u32, - edge_slots: self.edges.len() as u32, + edge_slots: self.occupied_edges, collections: self.collections, last_marked: self.last_marked, peak_nodes: self.peak_nodes, @@ -1875,7 +1901,8 @@ impl LuaHeap { /// Charged: /// - each slot record (`slots.len()`, including a free or retired record /// that still occupies the vector) - /// - each edge record (`edges.len()`, including a weak-cleared cursor gap) + /// - each edge record (`occupied_edges`, including a weak-cleared cursor + /// gap and excluding a free slot and backing capacity) /// - the stored length of a string or byte payload in those edge records /// /// Not charged: @@ -1897,7 +1924,7 @@ impl LuaHeap { /// one edge is charged once per edge. pub fn logical_bytes(&self) -> u64 { let nodes = (self.slots.len() as u64) * (std::mem::size_of::() as u64); - let edges = (self.edges.len() as u64) * (std::mem::size_of::() as u64); + let edges = (u64::from(self.occupied_edges)) * (std::mem::size_of::() as u64); nodes + edges + self.payload_bytes } @@ -1964,12 +1991,22 @@ impl LuaHeap { fn mark_reachable(&mut self) -> MarkSnapshot { self.scan.mark_passes += 1; self.scan.node_slot_visits += self.slots.len() as u64; - for slot in &mut self.slots { - if let SlotState::Live { marked } = &mut slot.state { + self.scan.weak_mode_slot_checks += self.slots.len() as u64; + let parse_modes = self.metatable_edges > 0; + let mut modes = None; + for index in 0..self.slots.len() { + if let SlotState::Live { marked } = &mut self.slots[index].state { *marked = false; } + let mode_edge = self.slots[index].mode_edge; + let is_table = self.slots[index].kind == HandleKind::Table; + if parse_modes + && is_table + && let Some(edge_index) = mode_edge + { + self.record_mode(index, edge_index, &mut modes); + } } - let index = self.build_outgoing_index(); let mut work = Vec::new(); self.scan.root_slot_visits += self.roots.len() as u64; let rooted: Vec = self.roots.iter().copied().flatten().collect(); @@ -1984,20 +2021,29 @@ impl LuaHeap { while let Some(slot) = work.pop() { let from_table = self.slots[slot as usize].kind == HandleKind::Table; let mode = if from_table && follow_metatables { - self.follow_metatable(slot, &index, &mut work) + self.follow_metatable(slot, modes.as_ref(), &mut work) } else { WeakMode::default() }; - let start = index.offsets[slot as usize] as usize; - let end = index.offsets[slot as usize + 1] as usize; - self.scan.outgoing_edge_checks += (end - start) as u64; - for &entry in &index.entries[start..end] { - let gap = self.edges[entry as usize].value.is_cursor_gap(); + self.scan.owner_head_checks += 1; + let mut cursor = self.slots[slot as usize].edge_head; + while let Some(index) = cursor { + let next = self.edge_slots[index as usize].next; + let gap = self.edge_slots[index as usize] + .edge + .as_ref() + .is_some_and(|edge| edge.value.is_cursor_gap()); if gap { + self.scan.outgoing_gap_checks += 1; + cursor = next; continue; } + self.scan.outgoing_edge_checks += 1; let (object_key, value_target) = { - let edge = &self.edges[entry as usize]; + let edge = self.edge_slots[index as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); let object_key = match &edge.key { EdgeKey::Object { slot, @@ -2020,6 +2066,7 @@ impl LuaHeap { }; (object_key, value_target) }; + cursor = next; if from_table && !mode.keys && let Some((slot, generation, kind)) = object_key @@ -2034,9 +2081,7 @@ impl LuaHeap { } } } - MarkSnapshot { - modes: index.weak_modes, - } + MarkSnapshot { modes } } /// Follows one stored metatable ref. Absent refs are not edges and are @@ -2044,7 +2089,7 @@ impl LuaHeap { fn follow_metatable( &mut self, slot: u32, - index: &OutgoingIndex, + modes: Option<&Vec>, work: &mut Vec, ) -> WeakMode { let Some((to_slot, to_generation)) = self.slots[slot as usize].metatable else { @@ -2052,7 +2097,7 @@ impl LuaHeap { }; self.scan.metatable_edge_checks += 1; if self.follow_target(to_slot, to_generation, HandleKind::Table, work) - && let Some(modes) = &index.weak_modes + && let Some(modes) = modes { self.scan.weak_mode_lookups += 1; return modes[to_slot as usize]; @@ -2076,77 +2121,7 @@ impl LuaHeap { true } - /// Two passes over the stored edge vector, plus one pass over the counts - /// scratch to turn those counts into offsets. `index_slot_checks` is that - /// scratch pass. Heap node walks are counted separately. The index is - /// dropped at the end of mark. - fn build_outgoing_index(&mut self) -> OutgoingIndex { - let slot_count = self.slots.len(); - let edge_count = self.edges.len(); - self.scan.index_edge_checks += edge_count as u64; - let mut counts = vec![0u32; slot_count]; - self.scan.scratch.index_counts_inited += counts.len() as u64; - for edge in &self.edges { - if edge.value.is_cursor_gap() { - continue; - } - if let Some(count) = counts.get_mut(edge.from as usize) { - *count = count.saturating_add(1); - } - } - self.scan.index_slot_checks += slot_count as u64; - let offset_request = slot_count + 1; - self.scan.scratch.index_offsets_reserved += offset_request as u64; - let mut offsets = Vec::with_capacity(offset_request); - offsets.push(0); - let mut running = 0u32; - for count in &counts { - running = running.saturating_add(*count); - offsets.push(running); - } - self.scan.scratch.index_offsets_pushed += offsets.len() as u64; - self.scan.index_edge_checks += edge_count as u64; - let mut cursor = offsets.clone(); - self.scan.scratch.index_cursor_copied += cursor.len() as u64; - let mut entries = vec![0u32; running as usize]; - self.scan.scratch.index_targets_inited += entries.len() as u64; - let mut weak_modes = None; - for (entry, edge) in self.edges.iter().enumerate() { - if edge.value.is_cursor_gap() { - continue; - } - let from = edge.from as usize; - if from >= slot_count { - continue; - } - let at = cursor[from] as usize; - if at < entries.len() { - entries[at] = entry as u32; - cursor[from] = cursor[from].saturating_add(1); - } - if self.metatable_edges > 0 - && edge.key == EdgeKey::Field(Self::MODE_FIELD) - && self.slots[from].kind == HandleKind::Table - && let EdgeValue::Scalar(Value::String(mode)) = &edge.value - { - let mode = WeakMode::parse(mode, &mut self.scan.weak_mode_bytes); - if mode.keys || mode.values { - let modes = weak_modes.get_or_insert_with(|| { - self.scan.scratch.weak_modes_inited += slot_count as u64; - vec![WeakMode::default(); slot_count] - }); - modes[from] = mode; - } - } - } - OutgoingIndex { - offsets, - entries, - weak_modes, - } - } - - /// One retain of stored edge records. Skipped when every live node is + /// One owner-chain walk of occupied records. Skipped when every live node is /// marked, so an all-live collect does not walk edges and does not build /// the mark bitmap. Weak-value flags come from `modes`, already parsed /// during mark. This does not scan edges to find `__mode`. @@ -2167,9 +2142,6 @@ impl LuaHeap { .collect(); self.scan.node_slot_visits += sweep.len() as u64; self.scan.scratch.sweep_bitmap_inited += sweep.len() as u64; - // Storage records this retain will visit. A later removal does not - // add a second counted pass. - self.scan.sweep_edge_checks += self.edges.len() as u64; let is_marked = |slot: u32| sweep.get(slot as usize).is_some_and(|found| found.marked); let typed = |slot: u32, generation: u32, kind: HandleKind| { sweep.get(slot as usize).is_some_and(|found| { @@ -2213,55 +2185,81 @@ impl LuaHeap { } => typed(*slot, *generation, HandleKind::Table), EdgeKey::Object { .. } => false, }; - // One pass updates a cleared cursor and drops a dead edge. A - // weak-value clear leaves the key in place with no value. That record - // is the cursor, not a second index. A dead key, a private field, or - // a strong edge is still removed. - let mut released = 0u64; - self.edges.retain_mut(|edge| { - let owner = edge.from as usize; - if is_marked(edge.from) && weak_values.get(owner).copied().unwrap_or(false) { - let value_dead = match &edge.value { - EdgeValue::Scalar(_) => false, - EdgeValue::Table { slot, .. } => !is_marked(*slot), - EdgeValue::Closure { slot, generation } => { - !typed(*slot, *generation, HandleKind::Closure) - } - EdgeValue::Upvalue { slot, generation } => { - !typed(*slot, *generation, HandleKind::Upvalue) + // One pass per owner, with the predecessor kept so a removal does not + // rescan. A weak-value clear leaves the key in place with no value. + // That record is the cursor, not a second index. A dead key, a private + // field, or a strong edge is still removed. + let occupied_before = self.occupied_edges; + let mut visited = 0u64; + for owner in 0..self.slots.len() { + self.scan.owner_head_checks += 1; + let mut prev = None; + let mut cursor = self.slots[owner].edge_head; + while let Some(index) = cursor { + visited += 1; + let next = self.edge_slots[index as usize].next; + let action = { + let edge = self.edge_slots[index as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + let owner_marked = is_marked(owner as u32); + let weak = weak_values.get(owner).copied().unwrap_or(false); + let value_dead = match &edge.value { + EdgeValue::Scalar(_) => false, + EdgeValue::Table { slot, .. } => !is_marked(*slot), + EdgeValue::Closure { slot, generation } => { + !typed(*slot, *generation, HandleKind::Closure) + } + EdgeValue::Upvalue { slot, generation } => { + !typed(*slot, *generation, HandleKind::Upvalue) + } + }; + let make_gap = owner_marked && weak && value_dead && guest_cursor(&edge.key); + let value_ok = make_gap + || match &edge.value { + EdgeValue::Table { slot, .. } => is_marked(*slot), + EdgeValue::Scalar(_) => true, + EdgeValue::Closure { slot, generation } => { + typed(*slot, *generation, HandleKind::Closure) + } + EdgeValue::Upvalue { slot, generation } => { + typed(*slot, *generation, HandleKind::Upvalue) + } + }; + let key_ok = match &edge.key { + EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, + EdgeKey::Object { + slot, + generation, + kind, + } if make_gap || edge.value.is_cursor_gap() => { + typed(*slot, *generation, *kind) + } + EdgeKey::Object { slot, .. } => is_marked(*slot), + }; + let keep = owner_marked && value_ok && key_ok; + if !keep { + SweepAction::Drop + } else if make_gap && !edge.value.is_cursor_gap() { + SweepAction::Gap + } else { + SweepAction::Keep } }; - if value_dead && guest_cursor(&edge.key) { - released += value_payload(&edge.value); - edge.value = EdgeValue::Scalar(Value::Null); - } - } - let keep = is_marked(edge.from) - && match &edge.value { - EdgeValue::Table { slot, .. } => is_marked(*slot), - EdgeValue::Scalar(_) => true, - EdgeValue::Closure { slot, generation } => { - typed(*slot, *generation, HandleKind::Closure) - } - EdgeValue::Upvalue { slot, generation } => { - typed(*slot, *generation, HandleKind::Upvalue) + match action { + SweepAction::Keep => prev = Some(index), + SweepAction::Gap => { + self.rewrite_gap(index); + prev = Some(index); } + SweepAction::Drop => self.unlink_at(owner as u32, prev, index), } - && match &edge.key { - EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, - EdgeKey::Object { - slot, - generation, - kind, - } if edge.value.is_cursor_gap() => typed(*slot, *generation, *kind), - EdgeKey::Object { slot, .. } => is_marked(*slot), - }; - if !keep { - released += edge_payload(edge); + cursor = next; } - keep - }); - self.payload_bytes -= released; + } + self.scan.sweep_edge_checks += visited; + debug_assert_eq!(visited, u64::from(occupied_before)); } fn mark_slot(&mut self, index: u32, work: &mut Vec) { @@ -2275,12 +2273,20 @@ impl LuaHeap { } fn release_slot(&mut self, index: u32) { + debug_assert!( + self.slots[index as usize].edge_head.is_none() + && self.slots[index as usize].edge_tail.is_none(), + "owner chain must already be unlinked; release does not scan edges" + ); if self.slots[index as usize].metatable.take().is_some() { self.metatable_edges = self.metatable_edges.saturating_sub(1); } let slot = &mut self.slots[index as usize]; slot.token = None; slot.carrier = None; + slot.edge_head = None; + slot.edge_tail = None; + slot.mode_edge = None; if slot.generation >= self.limits.max_generation { slot.state = SlotState::Retired; return; @@ -2291,17 +2297,30 @@ impl LuaHeap { } fn remove_edges_touching(&mut self, slot: u32) { - let mut released = 0u64; - self.edges.retain(|edge| { - let keep = edge.from != slot - && edge.value.object_slot().is_none_or(|target| target != slot) - && !edge_key_is_slot(&edge.key, slot); - if !keep { - released += edge_payload(edge); + for owner in 0..self.slots.len() { + let mut prev = None; + let mut cursor = self.slots[owner].edge_head; + while let Some(index) = cursor { + let next = self.edge_slots[index as usize].next; + let incident = { + let edge = self.edge_slots[index as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + owner as u32 == slot + || edge.value.object_slot() == Some(slot) + || edge_key_is_slot(&edge.key, slot) + }; + if incident { + self.unlink_at(owner as u32, prev, index); + } else { + prev = Some(index); + } + cursor = next; } - keep - }); - self.payload_bytes -= released; + } + debug_assert!(self.slots[slot as usize].edge_head.is_none()); + debug_assert!(self.slots[slot as usize].edge_tail.is_none()); } fn clear_roots_to(&mut self, handle: TableRef) { @@ -2365,7 +2384,168 @@ impl LuaHeap { } fn note_edge_peak(&mut self) { - self.peak_edges = self.peak_edges.max(self.edges.len() as u32); + self.peak_edges = self.peak_edges.max(self.occupied_edges); + } + + fn find_key(&self, owner: u32, key: &EdgeKey) -> Option { + self.find_matching(owner, |stored| stored == key) + } + + fn find_matching(&self, owner: u32, matches_key: impl Fn(&EdgeKey) -> bool) -> Option { + let mut cursor = self.slots.get(owner as usize)?.edge_head; + while let Some(index) = cursor { + let record = &self.edge_slots[index as usize]; + if record + .edge + .as_ref() + .is_some_and(|edge| matches_key(&edge.key)) + { + return Some(index); + } + cursor = record.next; + } + None + } + + fn take_edge_slot(&mut self) -> u32 { + if let Some(index) = self.edge_free_head { + let next = self.edge_slots[index as usize].next; + self.edge_free_head = next; + self.edge_slots[index as usize].next = None; + debug_assert!(self.edge_slots[index as usize].edge.is_none()); + return index; + } + let index = u32::try_from(self.edge_slots.len()).expect("edge index fits in u32"); + self.edge_slots.push(EdgeSlot { + next: None, + edge: None, + }); + index + } + + fn append_tail(&mut self, owner: u32, index: u32) { + self.edge_slots[index as usize].next = None; + let tail = self.slots[owner as usize].edge_tail; + match tail { + Some(tail) => self.edge_slots[tail as usize].next = Some(index), + None => self.slots[owner as usize].edge_head = Some(index), + } + self.slots[owner as usize].edge_tail = Some(index); + } + + fn unlink_key(&mut self, owner: u32, key: &EdgeKey) { + let mut prev = None; + let mut cursor = self + .slots + .get(owner as usize) + .and_then(|slot| slot.edge_head); + while let Some(index) = cursor { + let next = self.edge_slots[index as usize].next; + let matched = self.edge_slots[index as usize] + .edge + .as_ref() + .is_some_and(|edge| edge.key == *key); + if matched { + self.unlink_at(owner, prev, index); + return; + } + prev = Some(index); + cursor = next; + } + } + + fn unlink_at(&mut self, owner: u32, prev: Option, index: u32) { + let next = self.edge_slots[index as usize].next; + match prev { + Some(prev) => self.edge_slots[prev as usize].next = next, + None => self.slots[owner as usize].edge_head = next, + } + if self.slots[owner as usize].edge_tail == Some(index) { + self.slots[owner as usize].edge_tail = prev; + } + if self.slots[owner as usize].mode_edge == Some(index) { + self.slots[owner as usize].mode_edge = None; + } + self.free_edge_record(index); + } + + fn free_edge_record(&mut self, index: u32) { + let edge = self.edge_slots[index as usize] + .edge + .take() + .expect("occupied edge record"); + let gap = edge.value.is_cursor_gap(); + self.payload_bytes -= edge_payload(&edge); + self.occupied_edges -= 1; + if !gap { + self.live_edge_count -= 1; + } + self.edge_slots[index as usize].next = self.edge_free_head; + self.edge_free_head = Some(index); + } + + fn replace_edge_value(&mut self, owner: u32, index: u32, value: EdgeValue) { + let edge = self.edge_slots[index as usize] + .edge + .as_mut() + .expect("occupied edge record"); + let old_gap = edge.value.is_cursor_gap(); + self.payload_bytes -= value_payload(&edge.value); + edge.value = value; + let new_gap = edge.value.is_cursor_gap(); + self.payload_bytes += value_payload(&edge.value); + match (old_gap, new_gap) { + (true, false) => self.live_edge_count += 1, + (false, true) => self.live_edge_count -= 1, + _ => {} + } + self.note_mode_pointer(owner, index); + } + + fn rewrite_gap(&mut self, index: u32) { + let edge = self.edge_slots[index as usize] + .edge + .as_mut() + .expect("occupied edge record"); + if edge.value.is_cursor_gap() { + return; + } + self.payload_bytes -= value_payload(&edge.value); + edge.value = EdgeValue::Scalar(Value::Null); + self.live_edge_count -= 1; + } + + fn note_mode_pointer(&mut self, owner: u32, index: u32) { + let is_table = self.slots[owner as usize].kind == HandleKind::Table; + let is_mode = matches!( + self.edge_slots[index as usize] + .edge + .as_ref() + .map(|edge| &edge.key), + Some(EdgeKey::Field(field)) if *field == Self::MODE_FIELD + ); + if is_table && is_mode { + self.slots[owner as usize].mode_edge = Some(index); + } + } + + fn record_mode(&mut self, owner: usize, edge_index: u32, modes: &mut Option>) { + self.scan.weak_mode_edge_checks += 1; + let Some(edge) = self.edge_slots[edge_index as usize].edge.as_ref() else { + return; + }; + let EdgeValue::Scalar(Value::String(mode)) = &edge.value else { + return; + }; + let parsed = WeakMode::parse(mode, &mut self.scan.weak_mode_bytes); + if parsed.keys || parsed.values { + let slot_count = self.slots.len(); + let cache = modes.get_or_insert_with(|| { + self.scan.scratch.weak_modes_inited += slot_count as u64; + vec![WeakMode::default(); slot_count] + }); + cache[owner] = parsed; + } } } diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index e950ead..b25d618 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1162,7 +1162,7 @@ fn note_collect( discarded_alive, returned_edge, metatable_edge_checks: meter.metatable_edge_checks, - index_edge_checks: meter.index_edge_checks, + outgoing_gap_checks: meter.outgoing_gap_checks, outgoing_edge_checks: meter.outgoing_edge_checks, sweep_edge_checks: meter.sweep_edge_checks, }); @@ -3657,7 +3657,7 @@ pub(super) struct CollectNote { pub returned_edge: EdgeView, /// Metatable references followed from marked nodes. Not a field-edge count. pub metatable_edge_checks: u64, - pub index_edge_checks: u64, + pub outgoing_gap_checks: u64, pub outgoing_edge_checks: u64, pub sweep_edge_checks: u64, } diff --git a/tests/luajit_heap_runtime/closure_graph.rs b/tests/luajit_heap_runtime/closure_graph.rs index 768ddce..beba511 100644 --- a/tests/luajit_heap_runtime/closure_graph.rs +++ b/tests/luajit_heap_runtime/closure_graph.rs @@ -2382,9 +2382,8 @@ fn shared_upvalue_scalar_replaces_object_edge_and_collect_reclaims_only_that_cyc "mark walks the rooted edges and does not follow the scalar" ); assert_eq!( - meter.index_edge_checks, - u64::from(linked.live_edges) * 2, - "index walks the same edge vector twice" + meter.outgoing_gap_checks, 0, + "no rebuilt index walks stored gaps", ); assert_eq!(report.live_nodes, 5, "only the self-cycle table is swept"); assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(original))).expect("swept")); diff --git a/tests/luajit_heap_runtime/owner_adjacency.rs b/tests/luajit_heap_runtime/owner_adjacency.rs new file mode 100644 index 0000000..ba4c03d --- /dev/null +++ b/tests/luajit_heap_runtime/owner_adjacency.rs @@ -0,0 +1,223 @@ +//! Owner-chain witnesses that the old full-vector index could not express. +//! +//! Keep/reclaim identity, shared long `__mode` parse, and logical-byte deltas +//! stay in the existing heap tests. These cover order, gap reuse, rollback, +//! and the non-table field 0 that must not become a mode pointer. + +use super::{HeapLimits, LuaHeap, TableRef}; +use vm::Value; + +fn next_keys(heap: &LuaHeap, owner: TableRef) -> Vec { + let mut keys = Vec::new(); + let mut cursor = Value::Null; + while let Some((key, _)) = heap.next_guest(owner, &cursor).expect("next") { + keys.push(key.clone()); + cursor = key; + } + keys +} + +fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { + HeapLimits { + nodes, + roots, + edges, + max_generation: 4, + } +} + +#[test] +fn fan_out_mark_walks_each_owner_edge_once() { + let edges = 2048; + let mut heap = LuaHeap::new(limits(1, 1, edges)); + let owner = heap.alloc().expect("owner"); + let frame = heap.enter_roots(1).expect("root"); + heap.write_root(frame, 0, owner).expect("root owner"); + for key in 1..=edges { + heap.set_edge(owner, key, owner).expect("fan-out edge"); + } + assert!(heap.alive(owner)); + heap.collect(); + assert!(heap.alive(owner)); + assert_eq!(heap.edge(owner, 1).expect("read"), Some(owner)); + assert_eq!(heap.edge(owner, edges).expect("read"), Some(owner)); + let meter = heap.take_scan_meter(); + assert_eq!(meter.outgoing_edge_checks, u64::from(edges)); + assert_eq!(meter.outgoing_gap_checks, 0); + assert_eq!(meter.sweep_edge_checks, 0); + assert_eq!(meter.owner_head_checks, 1); + assert_eq!(meter.weak_mode_edge_checks, 0); +} + +#[test] +fn same_key_gap_stays_in_place_and_deleted_key_appends() { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let mt = heap.alloc().expect("mt"); + let owner = heap.alloc().expect("owner"); + let kept = heap.alloc().expect("kept"); + let dead = heap.alloc().expect("dead"); + let frame = heap.enter_roots(3).expect("roots"); + heap.write_root(frame, 0, mt).expect("root mt"); + heap.write_root(frame, 1, owner).expect("root owner"); + heap.write_root(frame, 2, kept).expect("root kept"); + heap.issue_carrier(kept).expect("carrier"); + heap.set_metatable(owner, Some(mt)).expect("metatable"); + heap.set_mode_scalar(mt, Value::string("v")).expect("mode"); + heap.set_named_edge(owner, "a", dead).expect("a"); + heap.set_named_edge(owner, "b", kept).expect("b"); + let occupied = heap.stats().edge_slots; + heap.collect(); + assert!(!heap.alive(dead)); + assert_eq!(next_keys(&heap, owner), vec![Value::string("b")]); + heap.set_named_edge(owner, "a", kept).expect("rewrite gap"); + assert_eq!( + heap.stats().edge_slots, + occupied, + "the same key reuses the gap record" + ); + assert_eq!( + next_keys(&heap, owner), + vec![Value::string("a"), Value::string("b")] + ); + heap.set_named_scalar(owner, "a", Value::Null) + .expect("delete a"); + assert_eq!(heap.stats().edge_slots, occupied - 1); + heap.set_named_edge(owner, "a", kept).expect("reinsert a"); + assert_eq!(heap.stats().edge_slots, occupied); + assert_eq!( + next_keys(&heap, owner), + vec![Value::string("b"), Value::string("a")] + ); +} + +#[test] +fn cross_owner_gap_reclaim_appends_without_reordering() { + let mut heap = LuaHeap::new(limits(8, 4, 4)); + let mt = heap.alloc().expect("mt"); + let donor = heap.alloc().expect("donor"); + let survivor = heap.alloc().expect("survivor"); + let kept = heap.alloc().expect("kept"); + let dead = heap.alloc().expect("dead"); + let frame = heap.enter_roots(4).expect("roots"); + heap.write_root(frame, 0, mt).expect("root mt"); + heap.write_root(frame, 1, donor).expect("root donor"); + heap.write_root(frame, 2, survivor).expect("root survivor"); + heap.write_root(frame, 3, kept).expect("root kept"); + heap.issue_carrier(kept).expect("carrier"); + heap.set_metatable(donor, Some(mt)).expect("metatable"); + heap.set_mode_scalar(mt, Value::string("v")).expect("mode"); + heap.set_named_edge(donor, "stay", kept).expect("stay"); + heap.set_named_edge(donor, "gap", dead).expect("gap"); + heap.set_named_edge(survivor, "x", kept).expect("x"); + assert_eq!(heap.stats().edge_slots, 4); + heap.collect(); + assert!(!heap.alive(dead)); + assert_eq!( + heap.stats().edge_slots, + 4, + "the gap still occupies a record" + ); + assert_eq!(heap.stats().live_edges, 3); + heap.set_named_edge(survivor, "y", kept) + .expect("reuse the other owner's gap"); + assert_eq!( + heap.stats().edge_slots, + 4, + "the new key reused a freed record instead of growing occupied storage" + ); + assert_eq!( + next_keys(&heap, survivor), + vec![Value::string("x"), Value::string("y")] + ); + assert_eq!(next_keys(&heap, donor), vec![Value::string("stay")]); + assert!(heap.named_edge(donor, "gap").expect("read").is_none()); +} + +#[test] +fn rollback_reissue_starts_from_an_empty_chain() { + let mut heap = LuaHeap::new(limits(2, 1, 4)); + let owner = heap.alloc().expect("owner"); + let other = heap.alloc().expect("other"); + heap.issue_carrier(other).expect("carrier"); + heap.set_named_edge(owner, "old", other).expect("old edge"); + let slot = owner.slot(); + let generation = owner.generation(); + heap.rollback(owner).expect("rollback"); + assert!(!heap.alive(owner)); + let again = heap.alloc().expect("reuse"); + assert_eq!(again.slot(), slot); + assert_ne!(again.generation(), generation); + assert!( + heap.next_guest(again, &Value::Null) + .expect("next") + .is_none() + ); + heap.set_named_edge(again, "new", other).expect("new edge"); + assert_eq!(next_keys(&heap, again), vec![Value::string("new")]); + assert!(heap.named_edge(again, "old").expect("read").is_none()); + assert_eq!(heap.stats().live_edges, 1); +} + +#[test] +fn deleted_mode_and_reused_owner_do_not_keep_the_old_rule() { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let mt = heap.alloc().expect("mt"); + let owner = heap.alloc().expect("owner"); + let dead = heap.alloc().expect("dead"); + let frame = heap.enter_roots(2).expect("roots"); + heap.write_root(frame, 0, mt).expect("root mt"); + heap.write_root(frame, 1, owner).expect("root owner"); + heap.set_metatable(owner, Some(mt)).expect("metatable"); + heap.set_mode_scalar(mt, Value::string("v")).expect("mode"); + heap.set_named_edge(owner, "w", dead).expect("weak edge"); + heap.set_mode_scalar(mt, Value::Null).expect("delete mode"); + heap.collect(); + assert!(heap.alive(dead), "a deleted mode leaves the edge strong"); + let meter = heap.take_scan_meter(); + assert_eq!(meter.weak_mode_edge_checks, 0); + assert_eq!(meter.weak_mode_bytes, 0); + assert_eq!(meter.weak_mode_lookups, 0); + + let slot = owner.slot(); + heap.rollback(owner).expect("free owner"); + let reused = heap.alloc().expect("reuse owner slot"); + assert_eq!(reused.slot(), slot); + let orphan = heap.alloc().expect("orphan"); + heap.write_root(frame, 1, reused).expect("root reused"); + heap.set_named_edge(reused, "w", orphan) + .expect("strong edge"); + heap.collect(); + assert!( + heap.alive(orphan), + "the reused slot does not keep the previous weak rule" + ); + let meter = heap.take_scan_meter(); + assert_eq!(meter.weak_mode_edge_checks, 0); + assert_eq!(meter.weak_mode_bytes, 0); +} + +#[test] +fn upvalue_field_zero_is_not_parsed_as_a_mode() { + let mut heap = LuaHeap::new(limits(4, 2, 4)); + let mt = heap.alloc().expect("mt"); + let owner = heap.alloc().expect("owner"); + let cell = heap.alloc_upvalue().expect("cell"); + let frame = heap.enter_roots(2).expect("roots"); + heap.write_root(frame, 0, mt).expect("root mt"); + heap.write_root(frame, 1, owner).expect("root owner"); + heap.set_metatable(owner, Some(mt)).expect("metatable"); + let text = "v".repeat(64); + heap.write_scalar_upvalue(cell, Value::string(&text)) + .expect("field 0 scalar"); + heap.collect(); + let meter = heap.take_scan_meter(); + assert!(meter.metatable_edge_checks >= 1, "mode parsing is enabled"); + assert!( + meter.sweep_edge_checks >= 1, + "the dead upvalue record is visited by sweep" + ); + assert_eq!(meter.weak_mode_edge_checks, 0); + assert_eq!(meter.weak_mode_bytes, 0); + assert_eq!(meter.weak_mode_lookups, 0); + assert_eq!(meter.scratch.weak_modes_inited, 0); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 35046c6..a773141 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -801,10 +801,9 @@ setmetatable(owner, nil) format!("{source}{tail}") } -fn first_collect_matrix(note: &candidate::CollectNote) -> (u64, u64, u64, u64, u32, u32, u64) { +fn first_collect_matrix(note: &candidate::CollectNote) -> (u64, u64, u64, u32, u32, u64) { ( note.metatable_edge_checks, - note.index_edge_checks, note.outgoing_edge_checks, note.sweep_edge_checks, note.marked_nodes, @@ -836,12 +835,11 @@ fn lua_candidate_reads_metatable_identity_after_collect_then_reclaims_on_detach( assert!(!first.discarded_alive && first.returned_alive); assert_eq!(first.returned_edge, candidate::EdgeView::Absent); // Field edges are cycle.self and mt.__index. The metatable ref is not one - // of them: index is 2 passes x 2 field edges, outgoing follows only the - // marked mt field, sweep filters both because the cycle died. The - // metatable follow is the separate 1. + // of them: outgoing follows only the marked mt field, sweep filters both + // because the cycle died. The metatable follow is the separate 1. assert_eq!( first_collect_matrix(first), - (1, 4, 1, 2, 4, 4, 1), + (1, 1, 2, 4, 4, 1), "metatable follow must stay out of the field-edge counters" ); assert_eq!( @@ -874,7 +872,7 @@ fn lua_candidate_reads_metatable_identity_after_collect_then_reclaims_on_detach( // is 0. Sweep still filters that field edge. assert_eq!( first_collect_matrix(second), - (0, 2, 0, 1, 2, 2, 2), + (0, 0, 1, 2, 2, 2), "detach does not add a field edge, and the second collect reclaims both targets" ); let key = heap::LuaTableResource::key(); @@ -915,7 +913,7 @@ fn lua_candidate_omitting_the_collect_after_detach_keeps_the_metatable_target() let first = &witness.collects[0]; assert_eq!( first_collect_matrix(first), - (1, 4, 1, 2, 4, 4, 1), + (1, 1, 2, 4, 4, 1), "the kept graph is the same one the reclaim test collects a second time" ); assert_eq!( @@ -2077,7 +2075,7 @@ return type(owner) let [first] = witness.collects.as_slice() else { panic!("expected one completed collection"); }; - assert_eq!(first_collect_matrix(first), (0, 8, 3, 4, 4, 4, 1)); + assert_eq!(first_collect_matrix(first), (0, 3, 4, 4, 4, 1)); assert_eq!(host.resource_count(), 4); let stats = heap::stats(&mut host).unwrap(); assert_eq!(stats.live_edges, 3); @@ -2161,12 +2159,12 @@ key = nil assert_eq!(witness.collects.len(), if second_collect { 2 } else { 1 }); assert_eq!( first_collect_matrix(&witness.collects[0]), - (0, 6, 2, 3, 3, 3, 1) + (0, 2, 3, 3, 3, 1) ); if second_collect { assert_eq!( first_collect_matrix(&witness.collects[1]), - (0, 2, 0, 1, 1, 1, 2) + (0, 0, 1, 1, 1, 2) ); } let resource_key = heap::LuaTableResource::key(); @@ -5664,8 +5662,8 @@ fn lua_file_count_reads_logical_kib_without_collecting() { collected_note[0].metatable_edge_checks ); assert_eq!( - counted_note[0].index_edge_checks, - collected_note[0].index_edge_checks + counted_note[0].outgoing_gap_checks, + collected_note[0].outgoing_gap_checks ); assert_eq!( counted_note[0].outgoing_edge_checks, diff --git a/tests/luajit_heap_runtime_tests.rs b/tests/luajit_heap_runtime_tests.rs index 0c360b5..2876692 100644 --- a/tests/luajit_heap_runtime_tests.rs +++ b/tests/luajit_heap_runtime_tests.rs @@ -7,6 +7,8 @@ #[path = "../src/frontends/lua/heap.rs"] mod heap; +#[path = "luajit_heap_runtime/owner_adjacency.rs"] +mod owner_adjacency; #[path = "luajit_heap_runtime/mod.rs"] mod support; #[path = "luajit_heap_runtime/value_boundary_tests.rs"] @@ -841,12 +843,12 @@ fn assert_linear_meter(label: &str, meter: &heap::ScanMeter, expect: LinearMeter assert_eq!( meter.mark_passes, 1, - "{label} marks once (outgoing={} budget={outgoing} sweep={} token_slots={} closes={} index_edges={} node_slots={} root_slots={})", + "{label} marks once (outgoing={} budget={outgoing} sweep={} token_slots={} closes={} gaps={} node_slots={} root_slots={})", meter.outgoing_edge_checks, meter.sweep_edge_checks, meter.token_slot_checks, meter.token_closes, - meter.index_edge_checks, + meter.outgoing_gap_checks, meter.node_slot_visits, meter.root_slot_visits ); @@ -856,14 +858,13 @@ fn assert_linear_meter(label: &str, meter: &heap::ScanMeter, expect: LinearMeter meter.mark_passes, meter.sweep_edge_checks, meter.token_slot_checks ); assert_eq!( - meter.index_edge_checks, - edges.saturating_mul(2), - "{label} index build examines each stored edge twice" - ); - assert_eq!( - meter.index_slot_checks, slots, - "{label} index build examines the counts scratch once" + meter.outgoing_gap_checks, 0, + "{label} no cursor gaps at mark" ); + assert_eq!(meter.weak_mode_slot_checks, slots, "{label} mode pointers"); + assert_eq!(meter.weak_mode_edge_checks, 0, "{label} no mode edge"); + let owner_heads = marked + if dead == 0 { 0 } else { slots }; + assert_eq!(meter.owner_head_checks, owner_heads, "{label} owner heads"); let sweep_budget = if dead == 0 { 0 } else { edges }; assert_eq!( meter.sweep_edge_checks, sweep_budget, @@ -896,29 +897,7 @@ fn assert_linear_meter(label: &str, meter: &heap::ScanMeter, expect: LinearMeter "{label} root slot visits" ); let scratch = &meter.scratch; - assert_eq!( - scratch.index_counts_inited, slots, - "{label} counts init is the measured request, not allocator capacity" - ); - assert_eq!( - scratch.index_offsets_reserved, - slots + 1, - "{label} offsets reserve" - ); - assert_eq!( - scratch.index_offsets_pushed, - slots + 1, - "{label} offsets pushed" - ); - assert_eq!( - scratch.index_cursor_copied, - slots + 1, - "{label} cursor copy" - ); - assert_eq!( - scratch.index_targets_inited, edges, - "{label} targets init is the measured in-range edge total" - ); + assert_eq!(scratch.weak_modes_inited, 0, "{label} no weak mode cache"); assert_eq!(scratch.work_pushed, marked, "{label} work pushes"); let pending = if enumerates_doomed { doomed_tokens } else { 0 }; assert_eq!( @@ -936,21 +915,13 @@ fn assert_linear_meter(label: &str, meter: &heap::ScanMeter, expect: LinearMeter fn eprintln_meter(label: &str, meter: &heap::ScanMeter) { let scratch = &meter.scratch; eprintln!( - "meter {label} mark={} index_edges={} index_slots={} outgoing={} sweep={} token_slots={} closes={} node_slots={} root_slots={} counts={} offsets_res={} offsets_pushed={} cursor={} targets={} work={} pending={} dead={} bitmap={}", + "meter {label} mark={} gaps={} heads={} mode_slots={} mode_edges={} modes={} work={} pending={} dead={} bitmap={}", meter.mark_passes, - meter.index_edge_checks, - meter.index_slot_checks, - meter.outgoing_edge_checks, - meter.sweep_edge_checks, - meter.token_slot_checks, - meter.token_closes, - meter.node_slot_visits, - meter.root_slot_visits, - scratch.index_counts_inited, - scratch.index_offsets_reserved, - scratch.index_offsets_pushed, - scratch.index_cursor_copied, - scratch.index_targets_inited, + meter.outgoing_gap_checks, + meter.owner_head_checks, + meter.weak_mode_slot_checks, + meter.weak_mode_edge_checks, + scratch.weak_modes_inited, scratch.work_pushed, scratch.pending_close_pushed, scratch.dead_slots_pushed, @@ -1191,6 +1162,53 @@ fn collect_scan_small_graph_stays_inside_one_linear_pass() { collect_host_shape(&host, true); } +/// Dead-zone mark walks the reachable owner's empty chain. It does not examine +/// the unreachable edges. Sweep, which runs because those owners are dead, +/// visits each occupied edge once. +#[test] +fn dead_zone_mark_does_not_rebuild_an_edge_index() { + let limits = HeapLimits::production(); + let dead = scan_shape("dead-zone", limits.nodes, 1, limits.edges, 1, false); + let live = scan_shape("full-live", 16, 1, limits.edges, 16, true); + let dead_meter = collect_shape_meter(&dead); + let live_meter = collect_shape_meter(&live); + assert_eq!(dead_meter.outgoing_edge_checks, 0); + assert_eq!(dead_meter.outgoing_gap_checks, 0); + assert_eq!(dead_meter.sweep_edge_checks, u64::from(limits.edges)); + assert_eq!(dead_meter.owner_head_checks, 1 + u64::from(limits.nodes)); + assert_eq!(live_meter.outgoing_edge_checks, u64::from(limits.edges)); + assert_eq!(live_meter.sweep_edge_checks, 0); + assert_eq!(live_meter.owner_head_checks, 16); + assert!( + dead_meter.outgoing_edge_checks < live_meter.outgoing_edge_checks, + "the same edge count is visited from marked owners, not from a rebuilt index" + ); +} + +fn collect_shape_meter(shape: &ScanShape) -> ScanMeter { + let mut heap = LuaHeap::new(HeapLimits { + nodes: shape.nodes, + roots: shape.roots, + edges: shape.edges, + max_generation: 4, + }); + let mut nodes = Vec::with_capacity(shape.nodes as usize); + for _ in 0..shape.nodes { + nodes.push(heap.alloc().expect("node")); + } + let frame = heap.enter_roots(shape.roots).expect("root frame"); + for root in 0..shape.roots { + heap.write_root(frame, root, nodes[root as usize]) + .expect("root"); + } + for (from, key, to) in plan_scan_edges(shape) { + heap.set_edge(nodes[from as usize], key, nodes[to as usize]) + .expect("edge"); + } + heap.collect(); + heap.take_scan_meter() +} + #[test] fn collect_scan_pure_limit_graphs_stay_linear() { let limits = HeapLimits::production(); @@ -1592,12 +1610,6 @@ fn shared_metatable_sweep_reuses_marked_modes() { u64::from(more_edges.edges / narrow.edges) ); assert_eq!(strong.sweep, u64::from(strong.edges)); - assert_eq!(narrow.index, narrow.sweep * 2); - assert_eq!(more_owners.index, narrow.index); - assert_eq!( - more_edges.index / narrow.index, - more_edges.sweep / narrow.sweep - ); assert_eq!(narrow.outgoing, narrow.sweep); assert_eq!(more_owners.outgoing, narrow.outgoing); assert_eq!(more_edges.outgoing, more_edges.sweep); @@ -1616,7 +1628,6 @@ struct ModeSweep { bytes: u64, lookups: u64, sweep: u64, - index: u64, outgoing: u64, modes_inited: u64, nodes: u32, @@ -1662,7 +1673,6 @@ fn collect_shared_mode(owners: u32, edges: u32, mode: &str) -> ModeSweep { bytes: meter.weak_mode_bytes, lookups: meter.weak_mode_lookups, sweep: meter.sweep_edge_checks, - index: meter.index_edge_checks, outgoing: meter.outgoing_edge_checks, modes_inited: meter.scratch.weak_modes_inited, nodes: heap.stats().node_slots, @@ -1702,7 +1712,8 @@ fn assert_cleared_cursor_reuses_the_dead_slot() { meter.sweep_edge_checks, 3, "one pass over the stored records" ); - assert_eq!(meter.index_edge_checks, 6); + assert_eq!(meter.outgoing_edge_checks, 3); + assert_eq!(meter.weak_mode_edge_checks, 1); assert_eq!(heap.object_value(owner, key).unwrap(), Value::Null); assert_eq!( heap.stats().edge_slots, From ad289d4dc8ce50210cf0fa9aa18c9ad37bcdf113 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 15:08:52 +0800 Subject: [PATCH 093/225] feat(lua): pause mark on a caller budget --- src/frontends/lua/heap/table.rs | 184 +-------- src/frontends/lua/heap/table/mark.rs | 409 +++++++++++++++++++++ tests/luajit_heap_runtime/budgeted_mark.rs | 353 ++++++++++++++++++ 3 files changed, 771 insertions(+), 175 deletions(-) create mode 100644 src/frontends/lua/heap/table/mark.rs create mode 100644 tests/luajit_heap_runtime/budgeted_mark.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 0282577..0005118 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -14,6 +14,10 @@ use vm::{HostContextError, Value}; use super::handle::{ClosureRef, HandleKind, TableRef, UpvalueRef}; +#[path = "table/mark.rs"] +mod mark; +use mark::MarkSession; + static NEXT_DOMAIN: AtomicU64 = AtomicU64::new(1); /// Closure-to-cell field. It is keyed only on a closure node. Field id 0 on a @@ -571,22 +575,6 @@ struct WeakMode { values: bool, } -impl WeakMode { - fn parse(mode: &str, bytes: &mut u64) -> Self { - let mut weak = Self::default(); - for byte in mode.bytes() { - *bytes += 1; - match byte { - b'k' => weak.keys = true, - b'v' => weak.values = true, - 0 => break, // LuaJIT scans the NUL-terminated mode string. - _ => {} - } - } - weak - } -} - /// Category of one guest value on this heap. /// /// `Table` is only the array issued for a live slot. A structurally equal @@ -1989,136 +1977,7 @@ impl LuaHeap { } fn mark_reachable(&mut self) -> MarkSnapshot { - self.scan.mark_passes += 1; - self.scan.node_slot_visits += self.slots.len() as u64; - self.scan.weak_mode_slot_checks += self.slots.len() as u64; - let parse_modes = self.metatable_edges > 0; - let mut modes = None; - for index in 0..self.slots.len() { - if let SlotState::Live { marked } = &mut self.slots[index].state { - *marked = false; - } - let mode_edge = self.slots[index].mode_edge; - let is_table = self.slots[index].kind == HandleKind::Table; - if parse_modes - && is_table - && let Some(edge_index) = mode_edge - { - self.record_mode(index, edge_index, &mut modes); - } - } - let mut work = Vec::new(); - self.scan.root_slot_visits += self.roots.len() as u64; - let rooted: Vec = self.roots.iter().copied().flatten().collect(); - for rooted in rooted { - self.scan.node_slot_visits += 1; - if self.rooted_alive(rooted) { - self.scan.node_slot_visits += 1; - self.mark_slot(rooted.slot(), &mut work); - } - } - let follow_metatables = self.metatable_edges > 0; - while let Some(slot) = work.pop() { - let from_table = self.slots[slot as usize].kind == HandleKind::Table; - let mode = if from_table && follow_metatables { - self.follow_metatable(slot, modes.as_ref(), &mut work) - } else { - WeakMode::default() - }; - self.scan.owner_head_checks += 1; - let mut cursor = self.slots[slot as usize].edge_head; - while let Some(index) = cursor { - let next = self.edge_slots[index as usize].next; - let gap = self.edge_slots[index as usize] - .edge - .as_ref() - .is_some_and(|edge| edge.value.is_cursor_gap()); - if gap { - self.scan.outgoing_gap_checks += 1; - cursor = next; - continue; - } - self.scan.outgoing_edge_checks += 1; - let (object_key, value_target) = { - let edge = self.edge_slots[index as usize] - .edge - .as_ref() - .expect("owner chain holds an occupied record"); - let object_key = match &edge.key { - EdgeKey::Object { - slot, - generation, - kind, - } => Some((*slot, *generation, *kind)), - EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => None, - }; - let value_target = match &edge.value { - EdgeValue::Table { slot, generation } => { - Some((*slot, *generation, HandleKind::Table)) - } - EdgeValue::Closure { slot, generation } => { - Some((*slot, *generation, HandleKind::Closure)) - } - EdgeValue::Upvalue { slot, generation } => { - Some((*slot, *generation, HandleKind::Upvalue)) - } - EdgeValue::Scalar(_) => None, - }; - (object_key, value_target) - }; - cursor = next; - if from_table - && !mode.keys - && let Some((slot, generation, kind)) = object_key - { - self.follow_target(slot, generation, kind, &mut work); - } - // A table entry follows that table's weak mode. A closure or - // cell link is not a table entry, so it stays strong. - let strong_value = !from_table || !mode.values; - if strong_value && let Some((slot, generation, kind)) = value_target { - self.follow_target(slot, generation, kind, &mut work); - } - } - } - MarkSnapshot { modes } - } - - /// Follows one stored metatable ref. Absent refs are not edges and are - /// not counted. The caller skips this entirely when no ref is stored. - fn follow_metatable( - &mut self, - slot: u32, - modes: Option<&Vec>, - work: &mut Vec, - ) -> WeakMode { - let Some((to_slot, to_generation)) = self.slots[slot as usize].metatable else { - return WeakMode::default(); - }; - self.scan.metatable_edge_checks += 1; - if self.follow_target(to_slot, to_generation, HandleKind::Table, work) - && let Some(modes) = modes - { - self.scan.weak_mode_lookups += 1; - return modes[to_slot as usize]; - } - WeakMode::default() - } - - fn follow_target( - &mut self, - to_slot: u32, - to_generation: u32, - kind: HandleKind, - work: &mut Vec, - ) -> bool { - self.scan.node_slot_visits += 1; - if !self.slot_matches(to_slot, to_generation, kind) { - return false; - } - self.scan.node_slot_visits += 1; - self.mark_slot(to_slot, work); - true + self.drain_mark() } /// One owner-chain walk of occupied records. Skipped when every live node is @@ -2262,16 +2121,6 @@ impl LuaHeap { debug_assert_eq!(visited, u64::from(occupied_before)); } - fn mark_slot(&mut self, index: u32, work: &mut Vec) { - if let SlotState::Live { marked } = &mut self.slots[index as usize].state - && !*marked - { - *marked = true; - work.push(index); - self.scan.scratch.work_pushed += 1; - } - } - fn release_slot(&mut self, index: u32) { debug_assert!( self.slots[index as usize].edge_head.is_none() @@ -2528,27 +2377,12 @@ impl LuaHeap { self.slots[owner as usize].mode_edge = Some(index); } } - - fn record_mode(&mut self, owner: usize, edge_index: u32, modes: &mut Option>) { - self.scan.weak_mode_edge_checks += 1; - let Some(edge) = self.edge_slots[edge_index as usize].edge.as_ref() else { - return; - }; - let EdgeValue::Scalar(Value::String(mode)) = &edge.value else { - return; - }; - let parsed = WeakMode::parse(mode, &mut self.scan.weak_mode_bytes); - if parsed.keys || parsed.values { - let slot_count = self.slots.len(); - let cache = modes.get_or_insert_with(|| { - self.scan.scratch.weak_modes_inited += slot_count as u64; - vec![WeakMode::default(); slot_count] - }); - cache[owner] = parsed; - } - } } fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { matches!(key, EdgeKey::Object { slot: key_slot, .. } if *key_slot == slot) } + +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/budgeted_mark.rs"] +mod budgeted_mark; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs new file mode 100644 index 0000000..1808b4c --- /dev/null +++ b/src/frontends/lua/heap/table/mark.rs @@ -0,0 +1,409 @@ +//! Pausable mark. A session holds the heap borrow until it is dropped or swept. +//! +//! A pulse spends a caller budget on these units, each checked before it runs: +//! one slot reset, one mode-edge open, one mode-string byte (including a NUL), +//! one mode-cache initialization, one root slot, one reached owner's outgoing +//! head, or one outgoing edge or gap. Target checks and the metatable check +//! ride with the edge or the owner head. A zero budget does not read the graph. + +use super::{ + CollectReport, EdgeKey, EdgeValue, HandleKind, LuaHeap, MarkSnapshot, SlotState, WeakMode, +}; +use vm::Value; + +pub(super) struct MarkSession<'a> { + heap: &'a mut LuaHeap, + phase: MarkPhase, + gray: Vec, + modes: Option>, + index: usize, + mode_edge: Option, + mode_owner: usize, + byte_at: usize, + pending_mode: WeakMode, + init_at: usize, + owner: Option, + cursor: Option, + owner_kind: HandleKind, + owner_mode: WeakMode, +} + +enum MarkPhase { + Start, + Reset, + ModeOpen, + ModeBytes, + ModeInit, + Roots, + Gray, + Done, +} + +pub(super) struct MarkView { + pub(super) finished: bool, + pub(super) meter: super::ScanMeter, +} + +impl<'a> MarkSession<'a> { + pub(super) fn start(heap: &'a mut LuaHeap) -> Self { + Self { + heap, + phase: MarkPhase::Start, + gray: Vec::new(), + modes: None, + index: 0, + mode_edge: None, + mode_owner: 0, + byte_at: 0, + pending_mode: WeakMode::default(), + init_at: 0, + owner: None, + cursor: None, + owner_kind: HandleKind::Table, + owner_mode: WeakMode::default(), + } + } + + pub(super) fn meter(&self) -> super::ScanMeter { + self.heap.scan + } + + pub(super) fn pulse(&mut self, budget: u64) -> MarkView { + if budget == 0 || matches!(self.phase, MarkPhase::Done) { + return self.view(); + } + if matches!(self.phase, MarkPhase::Start) { + self.heap.scan.mark_passes += 1; + self.phase = MarkPhase::Reset; + } + let mut left = budget; + let mut spins = 0u32; + while left > 0 && !matches!(self.phase, MarkPhase::Done) { + if self.step() { + left -= 1; + spins = 0; + } else { + spins += 1; + debug_assert!(spins <= 4, "mark phase did not advance"); + } + } + self.view() + } + + pub(super) fn drain(&mut self) { + while !matches!(self.phase, MarkPhase::Done) { + self.pulse(64); + } + } + + pub(super) fn sweep(self) -> CollectReport { + let MarkSession { + heap, modes, phase, .. + } = self; + assert!( + matches!(phase, MarkPhase::Done), + "sweep needs a finished mark" + ); + heap.sweep_marked(MarkSnapshot { modes }) + } + + fn view(&self) -> MarkView { + MarkView { + finished: matches!(self.phase, MarkPhase::Done), + meter: self.heap.scan, + } + } + + fn step(&mut self) -> bool { + match self.phase { + MarkPhase::Start => false, + MarkPhase::Reset => self.step_reset(), + MarkPhase::ModeOpen => self.step_mode_open(), + MarkPhase::ModeBytes => self.step_mode_byte(), + MarkPhase::ModeInit => self.step_mode_init(), + MarkPhase::Roots => self.step_root(), + MarkPhase::Gray => self.step_gray(), + MarkPhase::Done => false, + } + } + + fn step_reset(&mut self) -> bool { + if self.index >= self.heap.slots.len() { + self.phase = MarkPhase::Roots; + self.index = 0; + return false; + } + let index = self.index; + if let SlotState::Live { marked } = &mut self.heap.slots[index].state { + *marked = false; + } + self.heap.scan.node_slot_visits += 1; + self.heap.scan.weak_mode_slot_checks += 1; + let mode_edge = self.heap.slots[index].mode_edge; + let is_table = self.heap.slots[index].kind == HandleKind::Table; + if self.heap.metatable_edges > 0 && is_table && mode_edge.is_some() { + self.mode_edge = mode_edge; + self.mode_owner = index; + self.byte_at = 0; + self.pending_mode = WeakMode::default(); + self.phase = MarkPhase::ModeOpen; + } else { + self.index += 1; + } + true + } + + fn step_mode_open(&mut self) -> bool { + let edge_index = self.mode_edge.expect("mode open has an edge"); + self.heap.scan.weak_mode_edge_checks += 1; + if self.mode_string_len(edge_index).is_some() { + self.phase = MarkPhase::ModeBytes; + } else { + self.advance_after_mode(); + } + true + } + + fn step_mode_byte(&mut self) -> bool { + let edge_index = self.mode_edge.expect("mode byte has an edge"); + let at = self.byte_at; + let Some(byte) = self.mode_string_byte(edge_index, at) else { + self.finish_mode_parse(); + return false; + }; + self.heap.scan.weak_mode_bytes += 1; + self.byte_at = at + 1; + match byte { + b'k' => self.pending_mode.keys = true, + b'v' => self.pending_mode.values = true, + 0 => { + self.finish_mode_parse(); + return true; + } + _ => {} + } + let len = self.mode_string_len(edge_index).unwrap_or(0); + if self.byte_at >= len { + self.finish_mode_parse(); + } + true + } + + fn finish_mode_parse(&mut self) { + let parsed = self.pending_mode; + if parsed.keys || parsed.values { + if self.modes.is_none() { + self.init_at = 0; + self.phase = MarkPhase::ModeInit; + return; + } + self.store_mode(parsed); + } + self.advance_after_mode(); + } + + fn step_mode_init(&mut self) -> bool { + let slot_count = self.heap.slots.len(); + if self.modes.is_none() { + self.modes = Some(Vec::with_capacity(slot_count)); + } + let modes = self.modes.as_mut().expect("mode init has a cache"); + modes.push(WeakMode::default()); + self.heap.scan.scratch.weak_modes_inited += 1; + self.init_at += 1; + if self.init_at == slot_count { + let parsed = self.pending_mode; + self.store_mode(parsed); + self.advance_after_mode(); + } + true + } + + fn store_mode(&mut self, parsed: WeakMode) { + let modes = self.modes.as_mut().expect("mode cache"); + modes[self.mode_owner] = parsed; + } + + fn advance_after_mode(&mut self) { + self.mode_edge = None; + self.index += 1; + self.phase = MarkPhase::Reset; + } + + fn step_root(&mut self) -> bool { + if self.index >= self.heap.roots.len() { + self.phase = MarkPhase::Gray; + return false; + } + let index = self.index; + self.index += 1; + self.heap.scan.root_slot_visits += 1; + let Some(rooted) = self.heap.roots[index] else { + return true; + }; + self.heap.scan.node_slot_visits += 1; + if self.heap.rooted_alive(rooted) { + self.heap.scan.node_slot_visits += 1; + let slot = rooted.slot(); + if self.heap.mark_new(slot) { + self.gray.push(slot); + } + } + true + } + + fn step_gray(&mut self) -> bool { + if self.owner.is_some() { + if self.cursor.is_some() { + return self.charge_edge(); + } + self.owner = None; + return false; + } + self.begin_owner() + } + + fn begin_owner(&mut self) -> bool { + let Some(slot) = self.gray.pop() else { + self.phase = MarkPhase::Done; + return false; + }; + let kind = self.heap.slots[slot as usize].kind; + let mode = if kind == HandleKind::Table && self.heap.metatable_edges > 0 { + self.owner_mode(slot) + } else { + WeakMode::default() + }; + self.heap.scan.owner_head_checks += 1; + self.cursor = self.heap.slots[slot as usize].edge_head; + self.owner = Some(slot); + self.owner_kind = kind; + self.owner_mode = mode; + true + } + + fn charge_edge(&mut self) -> bool { + let cursor = self.cursor.expect("edge unit has a cursor"); + let next = self.heap.edge_slots[cursor as usize].next; + self.cursor = next; + let gap = self.heap.edge_slots[cursor as usize] + .edge + .as_ref() + .is_some_and(|edge| edge.value.is_cursor_gap()); + if gap { + self.heap.scan.outgoing_gap_checks += 1; + return true; + } + self.heap.scan.outgoing_edge_checks += 1; + self.follow_edge_ends(cursor); + true + } + + fn follow_edge_ends(&mut self, cursor: u32) { + let (object_key, value_target) = { + let edge = self.heap.edge_slots[cursor as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + let object_key = match &edge.key { + EdgeKey::Object { + slot, + generation, + kind, + } => Some((*slot, *generation, *kind)), + EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => None, + }; + let value_target = match &edge.value { + EdgeValue::Table { slot, generation } => { + Some((*slot, *generation, HandleKind::Table)) + } + EdgeValue::Closure { slot, generation } => { + Some((*slot, *generation, HandleKind::Closure)) + } + EdgeValue::Upvalue { slot, generation } => { + Some((*slot, *generation, HandleKind::Upvalue)) + } + EdgeValue::Scalar(_) => None, + }; + (object_key, value_target) + }; + let from_table = self.owner_kind == HandleKind::Table; + if from_table + && !self.owner_mode.keys + && let Some((slot, generation, kind)) = object_key + { + let _matched = self.follow_one(slot, generation, kind); + } + // A table entry follows that table's weak mode. A closure or cell + // link is not a table entry, so it stays strong. + let strong_value = !from_table || !self.owner_mode.values; + if strong_value && let Some((slot, generation, kind)) = value_target { + let _matched = self.follow_one(slot, generation, kind); + } + } + + fn owner_mode(&mut self, slot: u32) -> WeakMode { + let Some((to_slot, to_generation)) = self.heap.slots[slot as usize].metatable else { + return WeakMode::default(); + }; + self.heap.scan.metatable_edge_checks += 1; + if self.follow_one(to_slot, to_generation, HandleKind::Table) + && let Some(modes) = self.modes.as_ref() + { + self.heap.scan.weak_mode_lookups += 1; + return modes[to_slot as usize]; + } + WeakMode::default() + } + + /// Same visits as the old target follow. True when the slot matches, even + /// if it was already marked. Only a newly marked slot joins the gray stack. + fn follow_one(&mut self, slot: u32, generation: u32, kind: HandleKind) -> bool { + self.heap.scan.node_slot_visits += 1; + if !self.heap.slot_matches(slot, generation, kind) { + return false; + } + self.heap.scan.node_slot_visits += 1; + if self.heap.mark_new(slot) { + self.gray.push(slot); + } + true + } + + fn mode_string_len(&self, edge_index: u32) -> Option { + let edge = self.heap.edge_slots[edge_index as usize].edge.as_ref()?; + match &edge.value { + EdgeValue::Scalar(Value::String(mode)) => Some(mode.len()), + _ => None, + } + } + + fn mode_string_byte(&self, edge_index: u32, at: usize) -> Option { + let edge = self.heap.edge_slots[edge_index as usize].edge.as_ref()?; + match &edge.value { + EdgeValue::Scalar(Value::String(mode)) => mode.as_bytes().get(at).copied(), + _ => None, + } + } +} + +impl LuaHeap { + pub(super) fn drain_mark(&mut self) -> MarkSnapshot { + let mut session = MarkSession::start(self); + session.drain(); + MarkSnapshot { + modes: session.modes.take(), + } + } + + fn mark_new(&mut self, index: u32) -> bool { + if let SlotState::Live { marked } = &mut self.slots[index as usize].state + && !*marked + { + *marked = true; + self.scan.scratch.work_pushed += 1; + return true; + } + false + } +} diff --git a/tests/luajit_heap_runtime/budgeted_mark.rs b/tests/luajit_heap_runtime/budgeted_mark.rs new file mode 100644 index 0000000..71f6521 --- /dev/null +++ b/tests/luajit_heap_runtime/budgeted_mark.rs @@ -0,0 +1,353 @@ +//! Pausable mark on a fixed graph. Pulses share one pass and one heap borrow. +//! +//! Each pulse is checked against the scan meter, not against a returned +//! budget number. Sweep stays behind a finished mark. + +use super::{HeapLimits, LuaHeap, MarkSession, ScanMeter}; +use vm::Value; + +fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { + HeapLimits { + nodes, + roots, + edges, + max_generation: 8, + } +} + +fn edge_work(meter: &ScanMeter) -> u64 { + meter.outgoing_edge_checks + meter.outgoing_gap_checks +} + +/// Drive `session` with `budget` until the mark finishes. Every pulse must +/// keep edge, mode-byte, and mode-cache work inside that budget. +fn pulse_until_done(session: &mut MarkSession<'_>, budget: u64, limit: u32) -> ScanMeter { + assert!(budget > 0, "a finishing drive needs a positive budget"); + let mut pulses = 0u32; + loop { + let before = session.meter(); + let view = session.pulse(budget); + let edge_delta = edge_work(&view.meter) - edge_work(&before); + let byte_delta = view.meter.weak_mode_bytes - before.weak_mode_bytes; + let init_delta = view.meter.scratch.weak_modes_inited - before.scratch.weak_modes_inited; + assert!( + edge_delta <= budget && byte_delta <= budget && init_delta <= budget, + "pulse {pulses} budget {budget} exceeded: edges {edge_delta}, bytes {byte_delta}, init {init_delta} (outgoing {} gaps {} bytes {} init {})", + view.meter.outgoing_edge_checks, + view.meter.outgoing_gap_checks, + view.meter.weak_mode_bytes, + view.meter.scratch.weak_modes_inited + ); + assert_eq!( + view.meter.sweep_edge_checks, 0, + "a mark pulse must not sweep" + ); + assert_eq!(view.meter.scratch.dead_slots_pushed, 0); + assert_eq!(view.meter.scratch.sweep_bitmap_inited, 0); + assert_eq!( + view.meter.mark_passes, 1, + "pause stays in the original pass" + ); + if view.finished { + return view.meter; + } + pulses += 1; + assert!( + pulses < limit, + "mark did not finish within {limit} pulses of budget {budget}" + ); + } +} + +#[test] +fn fan_out_pulse_keeps_edge_work_inside_budget() { + let edges = 256u32; + let mut heap = LuaHeap::new(limits(1, 1, edges)); + let owner = heap.alloc().expect("owner"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, owner).expect("root"); + for key in 1..=edges { + heap.set_edge(owner, key, owner).expect("edge"); + } + + let mut session = MarkSession::start(&mut heap); + let idle = session.pulse(0); + assert!(!idle.finished, "zero budget does not finish the mark"); + assert_eq!( + idle.meter, + ScanMeter::default(), + "zero budget does not read the graph or change mark state" + ); + + let meter = pulse_until_done(&mut session, 1, edges + 16); + assert_eq!(meter.outgoing_edge_checks, u64::from(edges)); + assert_eq!(meter.outgoing_gap_checks, 0); + assert_eq!(meter.owner_head_checks, 1); + assert_eq!(meter.mark_passes, 1); + assert_eq!(meter.scratch.work_pushed, 1, "the owner is marked once"); + drop(session); + assert!(heap.alive(owner)); + assert_eq!(heap.stats().collections, 0, "mark does not collect"); +} + +#[test] +fn fan_out_budget_three_bounds_each_pulse() { + let edges = 64u32; + let budget = 3u64; + let mut heap = LuaHeap::new(limits(1, 1, edges)); + let owner = heap.alloc().expect("owner"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, owner).expect("root"); + for key in 1..=edges { + heap.set_edge(owner, key, owner).expect("edge"); + } + let mut session = MarkSession::start(&mut heap); + let first = session.pulse(budget); + assert!( + !first.finished, + "budget {budget} must not walk the whole owner" + ); + let meter = pulse_until_done(&mut session, budget, edges + 16); + assert_eq!(meter.outgoing_edge_checks, u64::from(edges)); + assert_eq!(meter.mark_passes, 1); +} + +const VALUE_PAD: usize = 24; + +fn weak_values_mode() -> String { + let mut mode = String::from("v"); + mode.extend(std::iter::repeat_n('x', VALUE_PAD)); + mode.push('\0'); + mode.push('k'); + mode +} + +fn weak_keys_mode() -> String { + let mut mode = String::from("k"); + mode.push('\0'); + mode.push('v'); + mode +} + +fn parsed_values_bytes() -> u64 { + // 'v', the pad, and the NUL. The trailing 'k' is past the terminator. + 1 + VALUE_PAD as u64 + 1 +} + +fn parsed_keys_bytes() -> u64 { + // 'k' and the NUL. The trailing 'v' is past the terminator. + 2 +} + +#[test] +fn shared_modes_amortize_bytes_and_cache_init() { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let mt_values = heap.alloc().expect("values metatable"); + let mt_keys = heap.alloc().expect("keys metatable"); + let owner_values = heap.alloc().expect("values owner"); + let owner_keys = heap.alloc().expect("keys owner"); + let peer = heap.alloc().expect("peer"); + let weak_orphan = heap.alloc().expect("weak orphan"); + let strong_key = heap.alloc().expect("strong key"); + let strong_value = heap.alloc().expect("strong value"); + let weak_key = heap.alloc().expect("weak key"); + let nodes = 9u64; + let frame = heap.enter_roots(5).expect("frame"); + heap.write_root(frame, 0, mt_values) + .expect("root mt values"); + heap.write_root(frame, 1, mt_keys).expect("root mt keys"); + heap.write_root(frame, 2, owner_values) + .expect("root values owner"); + heap.write_root(frame, 3, owner_keys) + .expect("root keys owner"); + heap.write_root(frame, 4, peer).expect("root peer"); + heap.set_metatable(owner_values, Some(mt_values)) + .expect("values metatable"); + heap.set_metatable(owner_keys, Some(mt_keys)) + .expect("keys metatable"); + heap.set_mode_scalar(mt_values, Value::string(weak_values_mode())) + .expect("values mode"); + heap.set_mode_scalar(mt_keys, Value::string(weak_keys_mode())) + .expect("keys mode"); + heap.set_object_edge(owner_values, strong_key, peer) + .expect("strong key edge"); + heap.set_named_edge(owner_values, "orphan", weak_orphan) + .expect("weak value edge"); + heap.set_object_edge(owner_keys, weak_key, peer) + .expect("weak key edge"); + heap.set_named_edge(owner_keys, "kept", strong_value) + .expect("strong value edge"); + heap.set_edge(weak_orphan, 1, weak_orphan) + .expect("orphan cycle"); + + let mut session = MarkSession::start(&mut heap); + let meter = pulse_until_done(&mut session, 1, 256); + assert_eq!( + meter.weak_mode_bytes, + parsed_values_bytes() + parsed_keys_bytes(), + "each mode string is parsed once, and the suffix after NUL is not scanned" + ); + assert_eq!( + meter.scratch.weak_modes_inited, nodes, + "the mode cache is initialized once, not once per owner" + ); + assert_eq!(meter.weak_mode_edge_checks, 2, "one open per mode edge"); + assert_eq!( + meter.weak_mode_lookups, 2, + "shared metatables are looked up, not parsed again" + ); + assert_eq!(meter.mark_passes, 1); + let report = session.sweep(); + assert!(heap.alive(peer), "rooted peer keeps its identity"); + assert!(heap.alive(strong_key), "the suffix k was not scanned"); + assert!(heap.alive(strong_value), "the suffix v was not scanned"); + assert!(!heap.alive(weak_orphan), "a weak value orphan is reclaimed"); + assert!(!heap.alive(weak_key), "a weak key orphan is reclaimed"); + assert_eq!( + heap.object_edge(owner_values, strong_key) + .expect("kept key"), + Some(peer) + ); + assert!( + heap.named_edge(owner_values, "orphan") + .expect("cleared value") + .is_none() + ); + assert_eq!( + heap.named_edge(owner_keys, "kept").expect("kept value"), + Some(strong_value) + ); + assert_eq!( + report.live_nodes, 7, + "two weak orphans are the only dead nodes" + ); +} + +#[test] +fn plain_fan_out_sweep_keeps_the_root_and_drops_the_orphan() { + let edges = 64u32; + let mut heap = LuaHeap::new(limits(2, 1, edges + 1)); + let owner = heap.alloc().expect("owner"); + let orphan = heap.alloc().expect("orphan"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, owner).expect("root"); + for key in 1..=edges { + heap.set_edge(owner, key, owner).expect("edge"); + } + heap.set_edge(orphan, 1, orphan).expect("orphan cycle"); + let mut session = MarkSession::start(&mut heap); + let meter = pulse_until_done(&mut session, 1, edges + 16); + assert_eq!(meter.weak_mode_bytes, 0); + assert_eq!(meter.scratch.weak_modes_inited, 0); + assert_eq!(meter.outgoing_edge_checks, u64::from(edges)); + let report = session.sweep(); + assert!(heap.alive(owner)); + assert!(!heap.alive(orphan)); + assert_eq!(heap.edge(owner, 1).expect("kept edge"), Some(owner)); + assert_eq!(heap.edge(owner, edges).expect("kept tail"), Some(owner)); + assert_eq!(report.live_nodes, 1); +} + +#[test] +fn gap_pulses_visit_one_record_at_a_time() { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let mt = heap.alloc().expect("mt"); + let owner = heap.alloc().expect("owner"); + let kept = heap.alloc().expect("kept"); + let dead = [ + heap.alloc().expect("dead"), + heap.alloc().expect("dead"), + heap.alloc().expect("dead"), + heap.alloc().expect("dead"), + ]; + let frame = heap.enter_roots(3).expect("frame"); + heap.write_root(frame, 0, mt).expect("root mt"); + heap.write_root(frame, 1, owner).expect("root owner"); + heap.write_root(frame, 2, kept).expect("root kept"); + heap.set_metatable(owner, Some(mt)).expect("metatable"); + heap.set_mode_scalar(mt, Value::string("v")).expect("mode"); + for (index, target) in dead.iter().enumerate() { + heap.set_named_edge(owner, &format!("d{index}"), *target) + .expect("dead edge"); + } + heap.set_named_edge(owner, "keep", kept).expect("kept edge"); + heap.collect(); + assert!(!heap.alive(dead[0])); + let _ = heap.take_scan_meter(); + + let mut session = MarkSession::start(&mut heap); + let meter = pulse_until_done(&mut session, 1, 64); + assert_eq!( + meter.outgoing_gap_checks, 4, + "each cleared cursor is visited once" + ); + assert_eq!(meter.mark_passes, 1); + assert!( + meter.outgoing_edge_checks >= 1, + "the kept edge is still an edge" + ); + drop(session); + assert!(heap.alive(owner)); + assert!(heap.alive(kept)); +} + +#[test] +fn dropped_partial_mark_collects_the_current_roots() { + let mut heap = LuaHeap::new(limits(4, 2, 4)); + let old = heap.alloc().expect("old root"); + let child = heap.alloc().expect("child"); + let other = heap.alloc().expect("replacement root"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, old).expect("root"); + heap.set_edge(old, 1, child).expect("edge"); + + let mut session = MarkSession::start(&mut heap); + let view = session.pulse(1); + assert!(!view.finished, "one unit does not finish this graph"); + assert_eq!(view.meter.mark_passes, 1); + assert_eq!(view.meter.sweep_edge_checks, 0); + assert_eq!(view.meter.scratch.dead_slots_pushed, 0); + assert_eq!(view.meter.scratch.sweep_bitmap_inited, 0); + drop(session); + + assert!(heap.alive(old) && heap.alive(child) && heap.alive(other)); + assert_eq!(heap.stats().collections, 0); + let partial = heap.take_scan_meter(); + assert_eq!( + partial.sweep_edge_checks, 0, + "dropping a mark does not sweep" + ); + assert_eq!(partial.mark_passes, 1); + + heap.write_root(frame, 0, other).expect("current root"); + let report = heap.collect(); + assert_eq!(report.live_nodes, 1); + assert!(heap.alive(other)); + assert!(!heap.alive(old)); + assert!(!heap.alive(child)); + let again = heap.take_scan_meter(); + assert_eq!(again.mark_passes, 1, "the next collect is a fresh pass"); +} + +#[test] +fn empty_graph_finishes_and_a_discarded_pass_can_remark() { + let mut heap = LuaHeap::new(limits(4, 2, 4)); + let mut session = MarkSession::start(&mut heap); + let idle = session.pulse(0); + assert!(!idle.finished); + assert_eq!(idle.meter, ScanMeter::default()); + let done = session.pulse(1); + assert!(done.finished, "an empty graph can finish"); + assert_eq!(done.meter.mark_passes, 1); + assert_eq!(done.meter.node_slot_visits, 0); + assert_eq!(done.meter.root_slot_visits, 0); + assert_eq!(done.meter.outgoing_edge_checks, 0); + drop(session); + let first = heap.take_scan_meter(); + assert_eq!(first.mark_passes, 1); + assert_eq!(first.sweep_edge_checks, 0); + let report = heap.collect(); + assert_eq!(report.live_nodes, 0); + let second = heap.take_scan_meter(); + assert_eq!(second.mark_passes, 1, "discard then collect marks again"); +} From 9468b84e25453f90bda858f9aa0e3dbded01f7cc Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 15:05:35 +0800 Subject: [PATCH 094/225] feat(lua): read rawlen from the first raw numeric border Unbound single-argument rawlen of an issued table walks that owner's chain once and returns the contiguous prefix from 1. No key 1 is 0. A later legal border is not selected. Strings and byte strings keep the shared byte-length helper. Table # stays outside this slice. --- src/frontends/lua/heap/table.rs | 73 ++++ tests/luajit_heap_runtime/candidate.rs | 67 +++- .../luajit_heap_runtime/string_byte_length.rs | 19 +- tests/luajit_heap_runtime/table_rawlen.rs | 369 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 5 files changed, 521 insertions(+), 9 deletions(-) create mode 100644 tests/luajit_heap_runtime/table_rawlen.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 0005118..37dc551 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -623,6 +623,25 @@ pub struct LuaHeap { payload_bytes: u64, } +/// Positive finite integer key that can sit in a 1-based prefix. +/// +/// `cap` is the edge quota. A contiguous prefix cannot outgrow the owner's +/// degree, and that degree cannot exceed the quota, so a larger key cannot +/// change the border. The caller therefore does not size marks by the key. +fn sequence_index(key: &EdgeKey, cap: u32) -> Option { + let EdgeKey::Number(bits) = key else { + return None; + }; + let number = f64::from_bits(*bits); + if !number.is_finite() || number < 1.0 || number.trunc() != number { + return None; + } + if number > f64::from(cap) { + return None; + } + Some(number as u32) +} + impl LuaHeap { /// Reserved direct field id for `__mode`; ordinary field ids start at 1. pub const MODE_FIELD: u32 = 0; @@ -1264,6 +1283,60 @@ impl LuaHeap { self.stored_value(from, |stored| stored == &key) } + /// First raw sequence border of this issued table. + /// + /// One walk of the owner's chain copies positive finite integer keys into + /// a buffer. That buffer is at most the owner's degree, and the degree + /// cannot exceed the edge quota, so a huge key does not size it. Strings, + /// object keys, private fields, and cursor gaps are ignored. The walk does + /// not read a metatable, use ordinary lookup, collect, or modify the chain. + /// The length is not cached. + /// + /// A contiguous prefix returns that length. Several legal borders resolve + /// to the first border of the prefix that starts at 1. No key 1 means 0. + /// This is not a border that depends on table capacity or insert history. + pub fn raw_sequence_len(&self, table: TableRef) -> Result { + self.require_live(table)?; + Ok(f64::from(self.raw_sequence_border(table.slot()))) + } + + fn raw_sequence_border(&self, owner: u32) -> u32 { + let cap = self.limits.edges; + let mut keys = Vec::new(); + let mut cursor = self + .slots + .get(owner as usize) + .and_then(|slot| slot.edge_head); + while let Some(index) = cursor { + let record = &self.edge_slots[index as usize]; + let edge = record + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + cursor = record.next; + if edge.value.is_cursor_gap() { + continue; + } + let Some(key) = sequence_index(&edge.key, cap) else { + continue; + }; + keys.push(key); + } + keys.sort_unstable(); + let mut expect = 1u32; + for key in keys { + if key == expect { + if expect == cap { + return expect; + } + expect += 1; + } else if key > expect { + break; + } + } + expect - 1 + } + fn number_key(key: f64) -> Result { if key.is_nan() { return Err(HeapError::NanIndex); diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index b25d618..4d88259 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -16,6 +16,7 @@ const NEW_TABLE: &str = "lua_internal::new_table"; const TYPE: &str = "lua_internal::type_of"; const ADD: &str = "lua_internal::add"; pub(super) const STRING_BYTE_LEN: &str = "lua_internal::string_byte_len"; +const RAW_LEN: &str = "lua_internal::raw_len"; const RETURN_SCALAR: &str = "lua_internal::return_scalar"; const TABLE_ARG: &str = "lua_internal::table_arg"; @@ -117,6 +118,11 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], HostTypeSchema::Float, )); + builder.function(HostFunctionSchema::with_return( + RAW_LEN, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::Float, + )); builder.function(HostFunctionSchema::with_return( RETURN_SCALAR, vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], @@ -191,6 +197,7 @@ pub(super) fn register( Op::Type, Op::Add, Op::StringByteLen, + Op::RawLen, Op::ReturnScalar, Op::TableArg, Op::NumberArg, @@ -224,6 +231,7 @@ pub(super) fn register( Op::Type => TYPE, Op::Add => ADD, Op::StringByteLen => STRING_BYTE_LEN, + Op::RawLen => RAW_LEN, Op::ReturnScalar => RETURN_SCALAR, Op::TableArg => TABLE_ARG, Op::NumberArg => NUMBER_ARG, @@ -267,6 +275,7 @@ enum Op { Type, Add, StringByteLen, + RawLen, ReturnScalar, TableArg, NumberArg, @@ -354,6 +363,7 @@ impl HostOwnedFunction for Op { } } Self::StringByteLen => string_byte_len(call)?, + Self::RawLen => raw_len(call)?, Self::ReturnScalar => match call.args() { [value @ (Value::Float(_) | Value::String(_) | Value::Bool(_) | Value::Null)] => { value.clone() @@ -502,14 +512,22 @@ impl HostOwnedFunction for Op { } } -/// Byte length of a Lua string. +/// Byte length of a Lua string or binary string. /// /// Core `len` is not this operation: it counts Rust `char`s for /// `Value::String`, returns `Value::Int`, and also accepts arrays and maps. +fn byte_len_of(value: &Value) -> Option { + match value { + Value::String(text) => Some(text.len()), + Value::Bytes(bytes) => Some(bytes.len()), + _ => None, + } +} + fn string_byte_len(call: &OwnedHostCall<'_>) -> Result { let len = match call.args() { - [Value::String(text)] => text.len(), - [Value::Bytes(bytes)] => bytes.len(), + [value] => byte_len_of(value) + .ok_or_else(|| VmError::HostError("Lua length operand is not a string".to_string()))?, _ => { return Err(VmError::HostError( "Lua length operand is not a string".to_string(), @@ -519,6 +537,31 @@ fn string_byte_len(call: &OwnedHostCall<'_>) -> Result { Ok(Value::Float(len as f64)) } +/// Unbound `rawlen`. Strings share [`byte_len_of`]. An issued table is a raw +/// numeric border. A number, a Core array, and a foreign carrier are not tables. +fn raw_len(call: &mut OwnedHostCall<'_>) -> Result { + let value = match call.args() { + [value] => value.clone(), + _ => { + return Err(host_fault("Lua rawlen operand is not a string or table")); + } + }; + if let Some(len) = byte_len_of(&value) { + return Ok(Value::Float(len as f64)); + } + let table = match classify(&mut call.vm().host_context(), &value)? { + heap::GuestClass::Table(table) => table, + _ => { + return Err(host_fault("Lua rawlen operand is not a string or table")); + } + }; + let len = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.raw_sequence_len(table) + }) + .map_err(heap_error)?; + Ok(Value::Float(len)) +} + fn skip_parens(expr: &ast::Expr) -> &ast::Expr { let mut expr = expr; while let ast::Expr::Paren { inner, .. } = expr { @@ -2062,6 +2105,22 @@ impl Lower<'_> { self.call(STRING_BYTE_LEN, vec![Expr::Var(slot)]) } + fn rawlen_expr(&mut self, operand: &ast::Expr, span: ast::Span) -> Result { + let operand = skip_parens(operand); + self.reject_tail_next(operand, span)?; + let value = self.length_operand(operand)?; + let slot = self + .builder + .alloc_local_named(&format!("rawlen:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: value, + line: self.line(span), + }); + self.call(RAW_LEN, vec![Expr::Var(slot)]) + } + fn length_operand(&mut self, expr: &ast::Expr) -> Result { match skip_parens(expr) { ast::Expr::String { bytes, .. } => Ok(self.string_literal(bytes)), @@ -3256,7 +3315,7 @@ impl Lower<'_> { if self.name_is_bound(name) { return Err(self.unsupported(expr.span())); } - return self.length_expr(arg, expr.span()); + return self.rawlen_expr(arg, expr.span()); } if name.is("type") && let [arg] = args.exprs.as_slice() diff --git a/tests/luajit_heap_runtime/string_byte_length.rs b/tests/luajit_heap_runtime/string_byte_length.rs index 63137ad..1b9536b 100644 --- a/tests/luajit_heap_runtime/string_byte_length.rs +++ b/tests/luajit_heap_runtime/string_byte_length.rs @@ -1,8 +1,9 @@ //! String byte length for the Lua 5.2 candidate. //! -//! `#` and unbound `rawlen` share one private length operation. These tests -//! feed real `.lua` files through the candidate source plugin, Core, and the -//! interpreter. Table length, `__len`, and `pcall` stay out of this slice. +//! `#` uses the private string byte-length operation. Unbound `rawlen` of a +//! string or byte string uses the same byte-length helper and still returns +//! one binary64. Table `rawlen` is covered by `table_rawlen`. Table `#`, +//! `__len`, and `pcall` stay out of this slice. //! A sibling module keeps those fixtures out of the closure-graph tests. use std::fs; @@ -434,7 +435,15 @@ fn bound_rawlen_keeps_unsupported_diagnostic() { #[test] fn non_string_length_is_rejected() { - assert_rejected(NUMBER_OPERAND, "Lua length operand is not a string"); + assert_rejected( + NUMBER_OPERAND, + "Lua rawlen operand is not a string or table", + ); assert_rejected(NIL_OPERAND, "Lua length operand is not a string"); - assert_rejected(TABLE_OPERAND, "Lua length operand is not a string"); +} + +#[test] +fn empty_table_rawlen_is_zero() { + let run = run_file(TABLE_OPERAND, &[]).expect("empty table rawlen"); + assert_eq!(run.stack, vec![Value::Float(0.0)]); } diff --git a/tests/luajit_heap_runtime/table_rawlen.rs b/tests/luajit_heap_runtime/table_rawlen.rs new file mode 100644 index 0000000..4d3de3e --- /dev/null +++ b/tests/luajit_heap_runtime/table_rawlen.rs @@ -0,0 +1,369 @@ +//! Unbound single-argument `rawlen` on an issued table. +//! +//! Real `.lua` files go through `compile_source_file_with_options`, the +//! candidate plugin, and Core. String and byte operands keep the existing +//! byte-length result. This slice does not lower table `#`, dispatch `__len`, +//! or adjust argument lists. A sparse table's result is the first border of +//! the contiguous prefix from 1, not a layout-dependent border. +//! +//! A negative integer literal is not a lowerable index in this slice: unary +//! minus only stores `-0`. The negative case therefore uses the existing +//! `float_bits(1)` witness, which is that `-0`. + +use std::fs; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; + +use vm::{ + CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, ParseError, + SourceFlavor, SourcePlugin, Value, VmStatus, +}; + +use super::candidate; +use super::heap; + +struct Plugin; + +impl SourcePlugin for Plugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, super::catalog()) + } +} + +struct Attempt { + vm: vm::Vm, + stack: Result, String>, +} + +fn claim_file(label: &str, source: &str) -> PathBuf { + static NEXT: AtomicU64 = AtomicU64::new(1); + let parent = std::env::temp_dir().join("compat-frontends-lua-source-fixtures"); + fs::create_dir_all(&parent) + .unwrap_or_else(|error| panic!("create {}: {error}", parent.display())); + let pid = std::process::id(); + let root = loop { + let ticket = NEXT.fetch_add(1, Ordering::Relaxed); + let candidate = parent.join(format!("table-rawlen-{label}-{pid}-{ticket}")); + match fs::create_dir(&candidate) { + Ok(()) => break candidate, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("claim {}: {error}", candidate.display()), + } + }; + let path = root.join("chunk.lua"); + fs::write(&path, source).unwrap_or_else(|error| panic!("write {}: {error}", path.display())); + path +} + +fn attempt(label: &str, source: &str) -> Result { + let path = claim_file(label, source); + let catalog = std::sync::Arc::clone(super::catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(std::sync::Arc::clone(&catalog)); + let prepared = vm::compile_source_file_with_options(&path, options).map_err(|error| { + format!( + "{}: compile_source_file_with_options: {error}", + path.display() + ) + })?; + let mut vm = prepared + .into_vm() + .map_err(|error| format!("{}: vm: {error}", path.display()))?; + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog) + .map_err(|error| format!("{}: register: {error}", path.display()))?; + super::register_witnesses(&mut registry, &catalog); + registry + .bind_vm_cached(&mut vm) + .map_err(|error| format!("{}: bind: {error}", path.display()))?; + let stack = match vm.run() { + Ok(status) => { + assert_eq!(status, VmStatus::Halted, "{}", path.display()); + Ok(vm.stack().to_vec()) + } + Err(error) => Err(format!("{}: {error}", path.display())), + }; + Ok(Attempt { vm, stack }) +} + +fn run(label: &str, source: &str) -> Attempt { + let ran = attempt(label, source).unwrap_or_else(|error| panic!("{label}: {error}")); + if let Err(message) = &ran.stack { + panic!("{label}: runtime error: {message}"); + } + ran +} + +fn stack_of(ran: &Attempt) -> &[Value] { + ran.stack.as_ref().expect("halted stack") +} + +fn assert_len(label: &str, source: &str, expected: f64) -> Attempt { + let ran = run(label, source); + let actual = match stack_of(&ran) { + [Value::Float(number)] => *number, + other => panic!("{label}: expected one number, stack {other:?}"), + }; + assert!( + actual.to_bits() == expected.to_bits(), + "{label}: rawlen {actual} != {expected}" + ); + ran +} + +fn assert_fault(label: &str, source: &str, needle: &str) { + let ran = attempt(label, source).unwrap_or_else(|error| panic!("{label}: {error}")); + let Err(message) = &ran.stack else { + panic!("{label}: expected a host fault, stack {:?}", ran.stack); + }; + assert!( + message.contains(needle), + "{label}: {message} does not contain {needle}" + ); +} + +fn collections(vm: &mut vm::Vm) -> u32 { + heap::with_heap(&mut vm.host_context(), |heap| Ok(heap.stats())) + .expect("heap stats") + .collections +} + +#[test] +fn lua_file_rawlen_of_empty_table_is_zero() { + let mut ran = assert_len("empty", "return rawlen({})\n", 0.0); + assert_eq!(collections(&mut ran.vm), 0, "rawlen must not collect"); +} + +#[test] +fn lua_file_rawlen_of_dense_numeric_keys_is_the_prefix() { + let mut ran = assert_len( + "dense", + r#"local owner = {} +owner[1] = "a" +owner[2] = "b" +owner[3] = "c" +return rawlen(owner) +"#, + 3.0, + ); + assert_eq!(collections(&mut ran.vm), 0, "rawlen must not collect"); +} + +#[test] +fn lua_file_rawlen_after_delete_stops_at_the_gap() { + assert_len( + "deleted-tail", + r#"local owner = {} +owner[1] = "a" +owner[2] = "b" +owner[2] = nil +return rawlen(owner) +"#, + 1.0, + ); +} + +#[test] +fn lua_file_rawlen_ignores_text_key_that_looks_like_one() { + assert_len( + "text-one", + r#"local owner = {} +owner["1"] = "text" +return rawlen(owner) +"#, + 0.0, + ); + assert_len( + "text-and-number", + r#"local owner = {} +owner[1] = "num" +owner["1"] = "text" +return rawlen(owner) +"#, + 1.0, + ); +} + +#[test] +fn lua_file_rawlen_ignores_non_integer_and_huge_keys() { + // `-1` is not a lowerable index here. `float_bits(1)` is the existing + // negative zero, and it shares the key with `0`. Neither extends a prefix. + assert_len( + "non-integer", + r#"local owner = {} +local neg = float_bits(1) +local inf = float_bits(3) +local ninf = float_bits(4) +owner[1] = "a" +owner[2] = "b" +owner[0] = "zero" +owner[neg] = "negzero" +owner[1.5] = "half" +owner[1e16] = "huge" +rawset(owner, inf, "inf") +rawset(owner, ninf, "ninf") +return rawlen(owner) +"#, + 2.0, + ); +} + +#[test] +fn lua_file_rawlen_of_sparse_table_is_the_first_border() { + // Intentional candidate choice: the first border of the prefix from 1. + // This does not freeze a hash or array layout, and it is not a promise + // to match a capacity-dependent LuaJIT border. + assert_len( + "sparse-first-border", + r#"local owner = {} +owner[1] = "a" +owner[4] = "d" +return rawlen(owner) +"#, + 1.0, + ); + // No key 1: the first border is 0. The locked LuaJIT binary returned 3 for + // this assignment order, which is another legal border and depends on + // insert history. That result is not the candidate rule. + assert_len( + "no-key-one", + r#"local owner = {} +owner[2] = "b" +owner[3] = "c" +return rawlen(owner) +"#, + 0.0, + ); +} + +#[test] +fn lua_file_rawlen_skips_a_weak_value_gap() { + let held = r#"local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local orphan = {} +orphan.self = orphan +owner[1] = orphan +owner[2] = "stay" +orphan = nil +return rawlen(owner) +"#; + assert_len("weak-held", held, 2.0); + + let cleared = r#"local mt = {} +mt.__mode = "v" +local owner = {} +setmetatable(owner, mt) +local orphan = {} +orphan.self = orphan +owner[1] = orphan +owner[2] = "stay" +orphan = nil +collectgarbage("collect") +return rawlen(owner) +"#; + assert_len("weak-gap", cleared, 0.0); + + let witness = cleared.replace("return rawlen(owner)", "return type(owner[1])"); + let ran = run("weak-gap-type", &witness); + assert_eq!(stack_of(&ran), &[Value::string("nil")]); +} + +#[test] +fn lua_file_rawlen_ignores_a_protected_metatable_and_len_field() { + let source = r#"local mt = {} +mt.__metatable = "sealed" +mt.__len = "47" +local owner = {} +setmetatable(owner, mt) +owner[1] = "a" +owner[2] = "b" +return rawlen(owner) +"#; + assert_len("protected-rawlen", source, 2.0); + let seal = source.replace("return rawlen(owner)", "return getmetatable(owner)"); + let ran = run("protected-seal", &seal); + assert_eq!(stack_of(&ran), &[Value::string("sealed")]); +} + +#[test] +fn lua_file_rawlen_evaluates_its_operand_once() { + let mut ran = run( + "once", + r#"local ready = {} +ready[1] = "a" +ready[2] = "b" +local get = nil +do + local held = ready + get = function() + return held + end +end +return rawlen(get()) +"#, + ); + assert_eq!(stack_of(&ran), &[Value::Float(2.0)]); + assert_eq!(candidate::capture_counts(&mut ran.vm), (1, 0)); + assert_eq!(collections(&mut ran.vm), 0, "rawlen must not collect"); +} + +#[test] +fn lua_file_rawlen_rejects_a_non_table_and_a_forged_carrier() { + assert_fault( + "bool", + "return rawlen(true)\n", + "Lua rawlen operand is not a string or table", + ); + assert_fault( + "forged", + "return rawlen(external_shape())\n", + "Lua rawlen operand is not a string or table", + ); +} + +#[test] +fn lua_file_hash_of_a_table_stays_outside_this_slice() { + assert_fault( + "hash-table", + "return #{}\n", + "Lua length operand is not a string", + ); +} + +#[test] +fn lua_file_rawlen_ignores_object_keys_and_private_fields() { + assert_len( + "object-key", + r#"local owner = {} +local key = {} +rawset(owner, key, "obj") +owner[1] = "a" +return rawlen(owner) +"#, + 1.0, + ); + assert_len( + "private-field", + r#"local owner = {} +local planted = {} +plant_private_field(owner, planted) +return rawlen(owner) +"#, + 0.0, + ); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index a773141..b65aff3 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -23,6 +23,8 @@ mod source_closure; mod string_byte_length; #[path = "table_metatable_protection.rs"] mod table_metatable_protection; +#[path = "table_rawlen.rs"] +mod table_rawlen; use super::heap; use super::support; From a8f510da9824dd5bcba219a2e322957b333fb05d Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 16:03:42 +0800 Subject: [PATCH 095/225] feat(lua): pause sweep on a caller budget collect, heap::collect, and MarkSession::sweep drain one sweep. A unit is one slot, snapshot record, owner head, occupied edge, release, or root. A zero budget does not scan. Drop does not sweep. --- src/frontends/lua/heap/table.rs | 215 +-------- src/frontends/lua/heap/table/sweep.rs | 401 ++++++++++++++++ tests/luajit_heap_runtime/budgeted_sweep.rs | 494 ++++++++++++++++++++ 3 files changed, 913 insertions(+), 197 deletions(-) create mode 100644 src/frontends/lua/heap/table/sweep.rs create mode 100644 tests/luajit_heap_runtime/budgeted_sweep.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 37dc551..9753afe 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -16,7 +16,10 @@ use super::handle::{ClosureRef, HandleKind, TableRef, UpvalueRef}; #[path = "table/mark.rs"] mod mark; +#[path = "table/sweep.rs"] +mod sweep; use mark::MarkSession; +use sweep::SweepSession; static NEXT_DOMAIN: AtomicU64 = AtomicU64::new(1); @@ -257,12 +260,6 @@ struct EdgeSlot { edge: Option, } -enum SweepAction { - Keep, - Gap, - Drop, -} - enum EdgeValue { Table { slot: u32, @@ -540,9 +537,12 @@ pub struct ScanScratch { pub work_pushed: u64, /// Pending-close elements appended. Host mark only; pure collect is 0. pub pending_close_pushed: u64, - /// Dead-slot indices appended during sweep selection. 0 if sweep did not run. + /// Dead-slot indices appended during sweep selection, one per dead slot. + /// 0 if sweep did not run. The push rides with that slot's selection unit. pub dead_slots_pushed: u64, - /// Mark bitmap zero-initialized when the edge filter runs. 0 when skipped. + /// Snapshot slot records appended when the edge filter runs, one per slot. + /// Not a collective zero-fill. 0 when every live node is marked and the + /// filter is skipped. pub sweep_bitmap_inited: u64, } @@ -1885,37 +1885,14 @@ impl LuaHeap { /// Releases nodes the current mark did not reach. Does not mark again. /// - /// Selection and the marked count share one slot pass. After that pass, - /// every unmarked live node is released, so remaining live nodes are the - /// marked count. The report uses that count instead of walking the slot - /// vector again. + /// [`SweepSession`] drains the same sweep used by [`Self::collect`] and + /// by [`MarkSession::sweep`]. `heap::collect` reaches it through this + /// function after tokens close. The report is built once, after the drain. + /// This function does not return a partial sweep. pub(super) fn sweep_marked(&mut self, modes: MarkSnapshot) -> CollectReport { - let mut swept = Vec::new(); - let mut marked_nodes = 0u32; - self.scan.node_slot_visits += self.slots.len() as u64; - for (index, slot) in self.slots.iter().enumerate() { - match slot.state { - SlotState::Live { marked: false } => swept.push(index as u32), - SlotState::Live { marked: true } => marked_nodes += 1, - SlotState::Free | SlotState::Retired => {} - } - } - self.scan.scratch.dead_slots_pushed += swept.len() as u64; - if !swept.is_empty() { - self.sweep_edges_once(&modes); - for index in swept { - self.scan.node_slot_visits += 1; - self.release_slot(index); - } - } - let live_roots = self.clear_dead_roots(); - self.collections = self.collections.saturating_add(1); - self.last_marked = marked_nodes; - CollectReport { - live_nodes: marked_nodes, - marked_nodes, - live_roots, - } + let mut session = SweepSession::start(self, modes); + session.drain(); + session.report() } /// Reports whether `handle` names a live table in this heap. @@ -2053,147 +2030,6 @@ impl LuaHeap { self.drain_mark() } - /// One owner-chain walk of occupied records. Skipped when every live node is - /// marked, so an all-live collect does not walk edges and does not build - /// the mark bitmap. Weak-value flags come from `modes`, already parsed - /// during mark. This does not scan edges to find `__mode`. - fn sweep_edges_once(&mut self, modes: &MarkSnapshot) { - struct SweepSlot { - marked: bool, - kind: HandleKind, - generation: u32, - } - let sweep: Vec = self - .slots - .iter() - .map(|slot| SweepSlot { - marked: matches!(slot.state, SlotState::Live { marked: true }), - kind: slot.kind, - generation: slot.generation, - }) - .collect(); - self.scan.node_slot_visits += sweep.len() as u64; - self.scan.scratch.sweep_bitmap_inited += sweep.len() as u64; - let is_marked = |slot: u32| sweep.get(slot as usize).is_some_and(|found| found.marked); - let typed = |slot: u32, generation: u32, kind: HandleKind| { - sweep.get(slot as usize).is_some_and(|found| { - found.marked && found.kind == kind && found.generation == generation - }) - }; - let weak_values = match modes.modes.as_ref() { - // No stored weak mode: every owner is strong. Do not read - // metatable slots or edges to rediscover that. - None => Vec::new(), - Some(stored) => sweep - .iter() - .enumerate() - .map(|(index, found)| { - if !found.marked || found.kind != HandleKind::Table { - return false; - } - let Some((mt_slot, mt_generation)) = self.slots[index].metatable else { - return false; - }; - let Some(mt) = sweep.get(mt_slot as usize) else { - return false; - }; - if !mt.marked || mt.kind != HandleKind::Table || mt.generation != mt_generation - { - return false; - } - // Mark already counted this lookup. Reading the stored - // flag is not another parse and is not an edge scan. - stored.get(mt_slot as usize).is_some_and(|mode| mode.values) - }) - .collect(), - }; - let guest_cursor = |key: &EdgeKey| match key { - EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, - EdgeKey::Field(_) => false, - EdgeKey::Object { - slot, - generation, - kind: HandleKind::Table, - } => typed(*slot, *generation, HandleKind::Table), - EdgeKey::Object { .. } => false, - }; - // One pass per owner, with the predecessor kept so a removal does not - // rescan. A weak-value clear leaves the key in place with no value. - // That record is the cursor, not a second index. A dead key, a private - // field, or a strong edge is still removed. - let occupied_before = self.occupied_edges; - let mut visited = 0u64; - for owner in 0..self.slots.len() { - self.scan.owner_head_checks += 1; - let mut prev = None; - let mut cursor = self.slots[owner].edge_head; - while let Some(index) = cursor { - visited += 1; - let next = self.edge_slots[index as usize].next; - let action = { - let edge = self.edge_slots[index as usize] - .edge - .as_ref() - .expect("owner chain holds an occupied record"); - let owner_marked = is_marked(owner as u32); - let weak = weak_values.get(owner).copied().unwrap_or(false); - let value_dead = match &edge.value { - EdgeValue::Scalar(_) => false, - EdgeValue::Table { slot, .. } => !is_marked(*slot), - EdgeValue::Closure { slot, generation } => { - !typed(*slot, *generation, HandleKind::Closure) - } - EdgeValue::Upvalue { slot, generation } => { - !typed(*slot, *generation, HandleKind::Upvalue) - } - }; - let make_gap = owner_marked && weak && value_dead && guest_cursor(&edge.key); - let value_ok = make_gap - || match &edge.value { - EdgeValue::Table { slot, .. } => is_marked(*slot), - EdgeValue::Scalar(_) => true, - EdgeValue::Closure { slot, generation } => { - typed(*slot, *generation, HandleKind::Closure) - } - EdgeValue::Upvalue { slot, generation } => { - typed(*slot, *generation, HandleKind::Upvalue) - } - }; - let key_ok = match &edge.key { - EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, - EdgeKey::Object { - slot, - generation, - kind, - } if make_gap || edge.value.is_cursor_gap() => { - typed(*slot, *generation, *kind) - } - EdgeKey::Object { slot, .. } => is_marked(*slot), - }; - let keep = owner_marked && value_ok && key_ok; - if !keep { - SweepAction::Drop - } else if make_gap && !edge.value.is_cursor_gap() { - SweepAction::Gap - } else { - SweepAction::Keep - } - }; - match action { - SweepAction::Keep => prev = Some(index), - SweepAction::Gap => { - self.rewrite_gap(index); - prev = Some(index); - } - SweepAction::Drop => self.unlink_at(owner as u32, prev, index), - } - cursor = next; - } - } - self.scan.sweep_edge_checks += visited; - debug_assert_eq!(visited, u64::from(occupied_before)); - } - fn release_slot(&mut self, index: u32) { debug_assert!( self.slots[index as usize].edge_head.is_none() @@ -2261,24 +2097,6 @@ impl LuaHeap { } } - fn clear_dead_roots(&mut self) -> u32 { - let mut live = 0u32; - let len = self.roots.len(); - self.scan.root_slot_visits += len as u64; - for index in 0..len { - let Some(rooted) = self.roots[index] else { - continue; - }; - self.scan.node_slot_visits += 1; - if self.rooted_alive(rooted) { - live += 1; - } else { - self.roots[index] = None; - } - } - live - } - fn frame(&self, id: RootFrameId) -> Result<&Frame, HeapError> { self.frames .iter() @@ -2459,3 +2277,6 @@ fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { #[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/budgeted_mark.rs"] mod budgeted_mark; +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/budgeted_sweep.rs"] +mod budgeted_sweep; diff --git a/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs new file mode 100644 index 0000000..a4efdb8 --- /dev/null +++ b/src/frontends/lua/heap/table/sweep.rs @@ -0,0 +1,401 @@ +//! Pausable sweep after a finished mark. The session holds the heap borrow. +//! +//! A pulse spends one unit before it runs: one selection slot, one snapshot +//! slot when any live node is unmarked, one owner head, one occupied edge +//! (including a gap), or one node release or root slot. A zero budget does +//! not read the graph and does not mutate it. Drop does not sweep. +//! +//! The snapshot is one appended slot record per unit. It is not allocated or +//! zero-filled as a whole vector. `Vec` capacity above that count is not a +//! scan unit and is not a per-pulse wall-clock bound. Weak mode comes from +//! the owner's metatable and the mark snapshot when that owner is opened. +//! That read is part of the head unit. It does not rescan a mode string and +//! does not add `weak_mode_lookups`. +//! +//! Production callers drain this session before they return a report. A +//! partial pulse is only visible to the private test that still holds the +//! borrow. Guest `next` and raw reads belong after `drain`. + +use super::{ + CollectReport, EdgeKey, EdgeValue, HandleKind, LuaHeap, MarkSnapshot, ScanMeter, SlotState, +}; + +pub(super) struct SweepSession<'a> { + heap: &'a mut LuaHeap, + modes: MarkSnapshot, + phase: SweepPhase, + index: usize, + dead: Vec, + snapshot: Vec, + owner: usize, + owner_open: bool, + owner_weak: bool, + prev: Option, + cursor: Option, + marked_nodes: u32, + live_roots: u32, + report: Option, + pulse_spent: SweepUnits, +} + +struct SweepSlot { + marked: bool, + kind: HandleKind, + generation: u32, +} + +enum SweepPhase { + Select, + Snapshot, + Owners, + Release, + Roots, + Done, +} + +enum SweepAction { + Keep, + Gap, + Drop, +} + +pub(super) struct SweepView { + pub(super) finished: bool, + pub(super) meter: ScanMeter, + pub(super) spent: SweepUnits, +} + +/// Units charged by one pulse. Each field is one kind of unit. Node-slot +/// visits overlap selection, snapshot, release, and root liveness, so they +/// are not added into [`SweepUnits::total`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct SweepUnits { + pub(super) selection: u64, + pub(super) snapshot: u64, + pub(super) heads: u64, + pub(super) edges: u64, + pub(super) releases: u64, + pub(super) roots: u64, +} + +impl SweepUnits { + pub(super) fn total(self) -> u64 { + self.selection + self.snapshot + self.heads + self.edges + self.releases + self.roots + } +} + +impl<'a> SweepSession<'a> { + pub(super) fn start(heap: &'a mut LuaHeap, modes: MarkSnapshot) -> Self { + Self { + heap, + modes, + phase: SweepPhase::Select, + index: 0, + dead: Vec::new(), + snapshot: Vec::new(), + owner: 0, + owner_open: false, + owner_weak: false, + prev: None, + cursor: None, + marked_nodes: 0, + live_roots: 0, + report: None, + pulse_spent: SweepUnits::default(), + } + } + + pub(super) fn meter(&self) -> ScanMeter { + self.heap.scan + } + + pub(super) fn stats(&self) -> super::HeapStats { + self.heap.stats() + } + + pub(super) fn pulse(&mut self, budget: u64) -> SweepView { + if budget == 0 || matches!(self.phase, SweepPhase::Done) { + return self.view(SweepUnits::default()); + } + self.pulse_spent = SweepUnits::default(); + let mut left = budget; + let mut spins = 0u32; + while left > 0 && !matches!(self.phase, SweepPhase::Done) { + if self.step() { + left -= 1; + spins = 0; + } else { + spins += 1; + debug_assert!(spins <= 4, "sweep phase did not advance"); + } + } + self.view(self.pulse_spent) + } + + pub(super) fn drain(&mut self) { + while !matches!(self.phase, SweepPhase::Done) { + self.pulse(64); + } + } + + /// The report built when the sweep finished. A second call has nothing + /// left: completion is recorded once. + pub(super) fn report(&mut self) -> CollectReport { + self.report.take().expect("sweep report is issued once") + } + + fn view(&self, spent: SweepUnits) -> SweepView { + SweepView { + finished: matches!(self.phase, SweepPhase::Done), + meter: self.heap.scan, + spent, + } + } + + fn step(&mut self) -> bool { + match self.phase { + SweepPhase::Select => self.step_select(), + SweepPhase::Snapshot => self.step_snapshot(), + SweepPhase::Owners => self.step_owners(), + SweepPhase::Release => self.step_release(), + SweepPhase::Roots => self.step_root(), + SweepPhase::Done => false, + } + } + + fn step_select(&mut self) -> bool { + if self.index >= self.heap.slots.len() { + self.index = 0; + self.phase = if self.dead.is_empty() { + SweepPhase::Roots + } else { + SweepPhase::Snapshot + }; + return false; + } + let index = self.index; + self.index += 1; + self.heap.scan.node_slot_visits += 1; + self.pulse_spent.selection += 1; + match self.heap.slots[index].state { + SlotState::Live { marked: false } => { + self.dead.push(index as u32); + self.heap.scan.scratch.dead_slots_pushed += 1; + } + SlotState::Live { marked: true } => self.marked_nodes += 1, + SlotState::Free | SlotState::Retired => {} + } + true + } + + fn step_snapshot(&mut self) -> bool { + if self.index >= self.heap.slots.len() { + self.index = 0; + self.owner = 0; + self.phase = SweepPhase::Owners; + return false; + } + let index = self.index; + self.index += 1; + let slot = &self.heap.slots[index]; + self.snapshot.push(SweepSlot { + marked: matches!(slot.state, SlotState::Live { marked: true }), + kind: slot.kind, + generation: slot.generation, + }); + self.heap.scan.node_slot_visits += 1; + self.heap.scan.scratch.sweep_bitmap_inited += 1; + self.pulse_spent.snapshot += 1; + true + } + + fn step_owners(&mut self) -> bool { + if self.cursor.is_some() { + return self.step_edge(); + } + if self.owner_open { + self.owner_open = false; + self.owner += 1; + return false; + } + if self.owner >= self.heap.slots.len() { + self.index = 0; + self.phase = SweepPhase::Release; + return false; + } + self.open_owner() + } + + fn open_owner(&mut self) -> bool { + let owner = self.owner; + self.heap.scan.owner_head_checks += 1; + self.owner_weak = self.weak_values(owner); + self.prev = None; + self.cursor = self.heap.slots[owner].edge_head; + self.owner_open = true; + self.pulse_spent.heads += 1; + true + } + + fn weak_values(&self, owner: usize) -> bool { + let Some(modes) = self.modes.modes.as_ref() else { + return false; + }; + let found = &self.snapshot[owner]; + if !found.marked || found.kind != HandleKind::Table { + return false; + } + let Some((mt_slot, mt_generation)) = self.heap.slots[owner].metatable else { + return false; + }; + let Some(mt) = self.snapshot.get(mt_slot as usize) else { + return false; + }; + if !mt.marked || mt.kind != HandleKind::Table || mt.generation != mt_generation { + return false; + } + modes.get(mt_slot as usize).is_some_and(|mode| mode.values) + } + + fn step_edge(&mut self) -> bool { + let index = self.cursor.expect("edge step has a cursor"); + let owner = self.owner as u32; + let next = self.heap.edge_slots[index as usize].next; + let action = self.decide(owner, index); + match action { + SweepAction::Keep => self.prev = Some(index), + SweepAction::Gap => { + self.heap.rewrite_gap(index); + self.prev = Some(index); + } + SweepAction::Drop => self.heap.unlink_at(owner, self.prev, index), + } + self.cursor = next; + self.heap.scan.sweep_edge_checks += 1; + self.pulse_spent.edges += 1; + true + } + + fn decide(&self, owner: u32, index: u32) -> SweepAction { + let edge = self.heap.edge_slots[index as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + let owner_marked = self.is_marked(owner); + let weak = self.owner_weak; + let value_dead = match &edge.value { + EdgeValue::Scalar(_) => false, + EdgeValue::Table { slot, .. } => !self.is_marked(*slot), + EdgeValue::Closure { slot, generation } => { + !self.typed(*slot, *generation, HandleKind::Closure) + } + EdgeValue::Upvalue { slot, generation } => { + !self.typed(*slot, *generation, HandleKind::Upvalue) + } + }; + let make_gap = owner_marked && weak && value_dead && self.guest_cursor(&edge.key); + let value_ok = make_gap + || match &edge.value { + EdgeValue::Table { slot, .. } => self.is_marked(*slot), + EdgeValue::Scalar(_) => true, + EdgeValue::Closure { slot, generation } => { + self.typed(*slot, *generation, HandleKind::Closure) + } + EdgeValue::Upvalue { slot, generation } => { + self.typed(*slot, *generation, HandleKind::Upvalue) + } + }; + let key_ok = match &edge.key { + EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, + EdgeKey::Object { + slot, + generation, + kind, + } if make_gap || edge.value.is_cursor_gap() => self.typed(*slot, *generation, *kind), + EdgeKey::Object { slot, .. } => self.is_marked(*slot), + }; + let keep = owner_marked && value_ok && key_ok; + if !keep { + SweepAction::Drop + } else if make_gap && !edge.value.is_cursor_gap() { + SweepAction::Gap + } else { + SweepAction::Keep + } + } + + fn step_release(&mut self) -> bool { + if self.index >= self.dead.len() { + self.index = 0; + self.phase = SweepPhase::Roots; + return false; + } + let slot = self.dead[self.index]; + self.index += 1; + self.heap.scan.node_slot_visits += 1; + self.heap.release_slot(slot); + self.pulse_spent.releases += 1; + true + } + + fn step_root(&mut self) -> bool { + if self.index >= self.heap.roots.len() { + self.finish(); + return false; + } + let index = self.index; + self.index += 1; + self.heap.scan.root_slot_visits += 1; + self.pulse_spent.roots += 1; + let Some(rooted) = self.heap.roots[index] else { + return true; + }; + self.heap.scan.node_slot_visits += 1; + if self.heap.rooted_alive(rooted) { + self.live_roots += 1; + } else { + self.heap.roots[index] = None; + } + true + } + + fn finish(&mut self) { + if self.report.is_some() { + self.phase = SweepPhase::Done; + return; + } + self.heap.collections = self.heap.collections.saturating_add(1); + self.heap.last_marked = self.marked_nodes; + self.report = Some(CollectReport { + live_nodes: self.marked_nodes, + marked_nodes: self.marked_nodes, + live_roots: self.live_roots, + }); + self.phase = SweepPhase::Done; + } + + fn is_marked(&self, slot: u32) -> bool { + self.snapshot + .get(slot as usize) + .is_some_and(|found| found.marked) + } + + fn typed(&self, slot: u32, generation: u32, kind: HandleKind) -> bool { + self.snapshot.get(slot as usize).is_some_and(|found| { + found.marked && found.kind == kind && found.generation == generation + }) + } + + fn guest_cursor(&self, key: &EdgeKey) -> bool { + match key { + EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, + EdgeKey::Field(_) => false, + EdgeKey::Object { + slot, + generation, + kind: HandleKind::Table, + } => self.typed(*slot, *generation, HandleKind::Table), + EdgeKey::Object { .. } => false, + } + } +} diff --git a/tests/luajit_heap_runtime/budgeted_sweep.rs b/tests/luajit_heap_runtime/budgeted_sweep.rs new file mode 100644 index 0000000..4f97f28 --- /dev/null +++ b/tests/luajit_heap_runtime/budgeted_sweep.rs @@ -0,0 +1,494 @@ +//! Pausable sweep after a finished mark. Pulses share one borrow. +//! +//! Guest `next` and raw reads run only after `drain`. A zero budget does not +//! scan. These tests do not claim a guest-visible atomic publication. + +use super::{GuestClass, HeapLimits, LuaHeap, MarkSession, ScanMeter, SweepSession, TableRef}; +use vm::Value; + +fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { + HeapLimits { + nodes, + roots, + edges, + max_generation: 8, + } +} + +fn root_one(heap: &mut LuaHeap, table: TableRef) { + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, table).expect("root"); +} + +fn root_all(heap: &mut LuaHeap, tables: &[TableRef]) { + let frame = heap.enter_roots(tables.len() as u32).expect("frame"); + for (index, table) in tables.iter().copied().enumerate() { + heap.write_root(frame, index as u32, table).expect("root"); + } +} + +fn next_keys(heap: &LuaHeap, owner: TableRef) -> Vec { + let mut keys = Vec::new(); + let mut cursor = Value::Null; + while let Some((key, _)) = heap.next_guest(owner, &cursor).expect("next") { + keys.push(key.clone()); + cursor = key; + } + keys +} + +fn pulse_checked(session: &mut SweepSession<'_>, budget: u64) -> bool { + let before = session.meter(); + let view = session.pulse(budget); + assert!( + view.spent.total() <= budget, + "pulse spent {} over budget {budget}", + view.spent.total() + ); + assert!(view.meter.sweep_edge_checks - before.sweep_edge_checks <= budget); + assert!(view.meter.scratch.sweep_bitmap_inited - before.scratch.sweep_bitmap_inited <= budget); + view.finished +} + +fn drive(session: &mut SweepSession<'_>, budget: u64) -> ScanMeter { + let mut pulses = 0u32; + loop { + if pulse_checked(session, budget) { + return session.meter(); + } + pulses += 1; + assert!(pulses < 100_000, "sweep did not finish"); + } +} + +/// One saturated owner plus slot and root prep must not finish in one unit. +#[test] +fn saturated_owner_budget_one_stops_inside_prep() { + let edges = 64u32; + let mut heap = LuaHeap::new(limits(2, 1, edges)); + let owner = heap.alloc().expect("owner"); + let dead = heap.alloc().expect("dead"); + root_one(&mut heap, owner); + for key in 1..=edges { + heap.set_edge(owner, key, owner).expect("edge"); + } + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + let before = session.meter(); + let view = session.pulse(1); + assert!( + !view.finished && view.spent.total() <= 1, + "budget 1 finished the batch: finished={} spent={}", + view.finished, + view.spent.total() + ); + assert!(view.meter.sweep_edge_checks - before.sweep_edge_checks <= 1); + let meter = drive(&mut session, 1); + assert_eq!( + meter.sweep_edge_checks - before.sweep_edge_checks, + u64::from(edges) + ); + let report = session.report(); + drop(session); + assert_eq!(report.live_nodes, 1); + assert!(heap.alive(owner)); + assert!(!heap.alive(dead)); + assert_eq!(heap.stats().edge_slots, edges); + assert_eq!(heap.edge(owner, 1).expect("edge"), Some(owner)); +} + +/// Prep that fits the budget exactly leaves the first edge for the next pulse. +#[test] +fn exact_budget_exhaustion_continues_on_the_next_pulse() { + let edges = 8u32; + let mut heap = LuaHeap::new(limits(2, 1, edges)); + let owner = heap.alloc().expect("owner"); + let dead = heap.alloc().expect("dead"); + root_one(&mut heap, owner); + for key in 1..=edges { + heap.set_edge(owner, key, owner).expect("edge"); + } + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + let before = session.meter(); + // select 2 + snapshot 2 + first owner head. + let prep = session.pulse(5); + assert!(!prep.finished); + assert_eq!(prep.spent.total(), 5); + assert_eq!(prep.meter.sweep_edge_checks, before.sweep_edge_checks); + let one = session.pulse(1); + assert_eq!(one.spent.total(), 1); + assert_eq!(one.spent.edges, 1); + assert_eq!(one.meter.sweep_edge_checks - before.sweep_edge_checks, 1); + drive(&mut session, 1); + drop(session); + assert!(heap.alive(owner)); + assert!(!heap.alive(dead)); +} + +/// A zero budget, including one issued in the middle, does not scan or mutate. +#[test] +fn zero_budget_does_not_scan_or_mutate() { + let mut heap = LuaHeap::new(limits(4, 2, 3)); + let owner = heap.alloc().expect("owner"); + let dead = heap.alloc().expect("dead"); + let mt = heap.alloc().expect("mt"); + root_all(&mut heap, &[owner, mt]); + heap.set_metatable(owner, Some(mt)).expect("mt"); + heap.set_mode_scalar(mt, Value::string("v")).expect("mode"); + heap.set_named_edge(owner, "stay", owner).expect("edge"); + heap.set_named_edge(owner, "gone", dead).expect("edge"); + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + let marked = session.meter(); + let zero = session.pulse(0); + assert!(!zero.finished); + assert_eq!(zero.spent.total(), 0); + assert_eq!(zero.meter, marked); + assert_eq!(session.stats().collections, 0); + assert!(!pulse_checked(&mut session, 3)); + let mid = session.meter(); + let edges = session.stats().edge_slots; + let again = session.pulse(0); + assert!(!again.finished); + assert_eq!(again.spent.total(), 0); + assert_eq!(again.meter, mid); + assert_eq!(session.stats().edge_slots, edges); + assert_eq!(session.stats().collections, 0); + drive(&mut session, 1); + drop(session); + assert!(heap.named_edge(owner, "stay").expect("stay").is_some()); + assert!(heap.named_edge(owner, "gone").expect("gone").is_none()); +} + +/// An empty graph finishes on a positive budget and spends nothing. +#[test] +fn empty_graph_finishes_without_a_scan() { + let mut heap = LuaHeap::new(limits(1, 1, 1)); + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + let zero = session.pulse(0); + assert!(!zero.finished); + assert_eq!(zero.spent.total(), 0); + let done = session.pulse(1); + assert!(done.finished); + assert_eq!(done.spent.total(), 0); + let report = session.report(); + assert_eq!(report.live_nodes, 0); + assert_eq!(session.stats().collections, 1); + let extra = session.pulse(1); + assert!(extra.finished); + assert_eq!(extra.spent.total(), 0); + assert_eq!(session.stats().collections, 1); +} + +/// Every live node marked: no snapshot, no edge walk, no sweep heads. +#[test] +fn all_live_skips_edges_and_snapshot() { + let mut heap = LuaHeap::new(limits(1, 1, 1)); + let owner = heap.alloc().expect("owner"); + root_one(&mut heap, owner); + heap.set_edge(owner, 1, owner).expect("edge"); + let modes = heap.drain_mark(); + let marked = heap.take_scan_meter(); + let mut session = SweepSession::start(&mut heap, modes); + let mut spent = 0u64; + loop { + let view = session.pulse(1); + spent += view.spent.total(); + assert!(view.spent.total() <= 1); + if view.finished { + break; + } + } + let sweep = session.meter(); + drop(session); + assert_eq!(sweep.scratch.sweep_bitmap_inited, 0); + assert_eq!(sweep.sweep_edge_checks, 0); + assert_eq!(sweep.owner_head_checks, 0); + assert_eq!(marked.owner_head_checks, 1); + assert_eq!(spent, 2); + assert!(heap.alive(owner)); + assert_eq!(heap.edge(owner, 1).expect("edge"), Some(owner)); +} + +/// A dense dead region visits each occupied record once and keeps the live root. +#[test] +fn dense_dead_zone_visits_each_occupied_edge_once() { + let dead_nodes = 32u32; + let edges = dead_nodes - 1; + let mut heap = LuaHeap::new(limits(dead_nodes + 1, 1, edges)); + let live = heap.alloc().expect("live"); + root_one(&mut heap, live); + let mut previous = heap.alloc().expect("dead"); + for _ in 1..dead_nodes { + let next = heap.alloc().expect("dead"); + heap.set_edge(previous, 1, next).expect("edge"); + previous = next; + } + let modes = heap.drain_mark(); + let before = heap.take_scan_meter(); + let mut session = SweepSession::start(&mut heap, modes); + let meter = drive(&mut session, 1); + drop(session); + assert_eq!( + meter.sweep_edge_checks - before.sweep_edge_checks, + u64::from(edges) + ); + assert_eq!( + meter.scratch.sweep_bitmap_inited - before.scratch.sweep_bitmap_inited, + u64::from(dead_nodes + 1) + ); + assert!(heap.alive(live)); + assert_eq!(heap.stats().live_nodes, 1); + assert_eq!(heap.stats().edge_slots, 0); +} + +/// Two weak groups are fully visible only after the sweep drains. +/// +/// The 32 owners are the qualification shape: one shared metatable and one +/// metatable each. This does not claim the guest can observe an atomic +/// publication of that clear. +#[test] +fn two_weak_groups_are_visible_only_after_drain() { + let group = 16u32; + let owners = group * 2; + let nodes = 1 + group + owners + owners + owners; + let roots = 1 + group + owners + owners; + let edges = owners * 2 + 1 + group; + let mut heap = LuaHeap::new(limits(nodes, roots, edges)); + let shared = heap.alloc().expect("shared mt"); + heap.set_mode_scalar(shared, Value::string("v")) + .expect("mode"); + let mut separate = Vec::new(); + for _ in 0..group { + let mt = heap.alloc().expect("mt"); + heap.set_mode_scalar(mt, Value::string("v")).expect("mode"); + separate.push(mt); + } + let mut kept = Vec::new(); + let mut doomed = Vec::new(); + let mut tables = Vec::new(); + for index in 0..owners { + let owner = heap.alloc().expect("owner"); + let stay = heap.alloc().expect("stay"); + let gone = heap.alloc().expect("gone"); + let mt = if index < group { + shared + } else { + separate[(index - group) as usize] + }; + heap.set_metatable(owner, Some(mt)).expect("mt"); + heap.set_named_edge(owner, "gone", gone).expect("weak"); + heap.set_named_edge(owner, "stay", stay).expect("keep"); + tables.push(owner); + kept.push((owner, stay)); + doomed.push((owner, gone)); + } + let mut rooted = vec![shared]; + rooted.extend(separate.iter().copied()); + rooted.extend(tables.iter().copied()); + rooted.extend(kept.iter().map(|(_, stay)| *stay)); + root_all(&mut heap, &rooted); + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + assert!(!pulse_checked(&mut session, 1)); + assert_eq!(session.stats().collections, 0); + drive(&mut session, 7); + assert_eq!(session.stats().collections, 1); + drop(session); + for (owner, stay) in kept { + assert_eq!(heap.named_edge(owner, "stay").expect("stay"), Some(stay)); + assert!(heap.alive(stay)); + } + for (owner, gone) in doomed { + assert!(heap.named_edge(owner, "gone").expect("gone").is_none()); + assert!(!heap.alive(gone)); + } +} + +/// A dropped middle field edge leaves both named neighbors, in order. +/// +/// The field key is not a guest cursor, so a weak dead value is removed +/// rather than turned into a gap. The live target of a dead owner is kept. +#[test] +fn dead_edge_keeps_both_neighbor_records() { + let mut heap = LuaHeap::new(limits(6, 4, 5)); + let mt = heap.alloc().expect("mt"); + let owner = heap.alloc().expect("owner"); + let left = heap.alloc().expect("left"); + let mid = heap.alloc().expect("mid"); + let right = heap.alloc().expect("right"); + let dead_owner = heap.alloc().expect("dead owner"); + root_all(&mut heap, &[mt, owner, left, right]); + heap.set_metatable(owner, Some(mt)).expect("mt"); + heap.set_mode_scalar(mt, Value::string("v")).expect("mode"); + heap.issue_carrier(left).expect("left carrier"); + heap.issue_carrier(right).expect("right carrier"); + heap.set_named_edge(owner, "left", left).expect("left"); + heap.set_edge(owner, 1, mid).expect("field"); + heap.set_named_edge(owner, "right", right).expect("right"); + heap.set_named_edge(dead_owner, "out", left).expect("out"); + let modes = heap.drain_mark(); + let before = heap.take_scan_meter(); + let mut session = SweepSession::start(&mut heap, modes); + drive(&mut session, 1); + let sweep_edges = session.meter().sweep_edge_checks - before.sweep_edge_checks; + drop(session); + assert_eq!(sweep_edges, 5); + assert_eq!( + next_keys(&heap, owner), + vec![Value::string("left"), Value::string("right")] + ); + assert!(heap.edge(owner, 1).expect("field").is_none()); + assert_eq!(heap.named_edge(owner, "left").expect("left"), Some(left)); + assert_eq!(heap.named_edge(owner, "right").expect("right"), Some(right)); + assert!(heap.alive(left)); + assert!(heap.alive(right)); + assert!(!heap.alive(mid)); + assert!(!heap.alive(dead_owner)); + assert!(heap.named_edge(dead_owner, "out").is_err()); +} + +/// Weak gaps in two groups stay reachable as cursors and are not raw values. +#[test] +fn weak_gaps_keep_cursor_continuation() { + let mut heap = LuaHeap::new(limits(8, 6, 8)); + let shared = heap.alloc().expect("shared"); + let separate = heap.alloc().expect("separate"); + heap.set_mode_scalar(shared, Value::string("v")) + .expect("mode"); + heap.set_mode_scalar(separate, Value::string("v")) + .expect("mode"); + let mut owners = Vec::new(); + for mt in [shared, separate] { + let owner = heap.alloc().expect("owner"); + let gone = heap.alloc().expect("gone"); + let stay = heap.alloc().expect("stay"); + heap.set_metatable(owner, Some(mt)).expect("mt"); + heap.issue_carrier(stay).expect("carrier"); + heap.set_named_edge(owner, "gap", gone).expect("gap"); + heap.set_named_edge(owner, "stay", stay).expect("stay"); + owners.push((owner, stay)); + root_all(&mut heap, &[mt, owner, stay]); + } + let modes = heap.drain_mark(); + let lookups = heap.scan.weak_mode_lookups; + let bytes = heap.scan.weak_mode_bytes; + let mut session = SweepSession::start(&mut heap, modes); + drive(&mut session, 1); + assert_eq!(session.meter().weak_mode_lookups, lookups); + assert_eq!(session.meter().weak_mode_bytes, bytes); + drop(session); + for (owner, stay) in owners { + assert!(heap.named_edge(owner, "gap").expect("gap").is_none()); + assert_eq!(heap.named_edge(owner, "stay").expect("stay"), Some(stay)); + let continued = heap + .next_guest(owner, &Value::string("gap")) + .expect("cursor"); + let (key, value) = continued.expect("continuation"); + assert_eq!(key, Value::string("stay")); + assert_eq!(heap.guest_class(&value), GuestClass::Table(stay)); + assert_eq!(next_keys(&heap, owner), vec![Value::string("stay")]); + } +} + +/// Completion increments the collection count once, then further pulses do not. +#[test] +fn completion_report_is_issued_once() { + let mut heap = LuaHeap::new(limits(2, 1, 1)); + let owner = heap.alloc().expect("owner"); + let _dead = heap.alloc().expect("dead"); + root_one(&mut heap, owner); + heap.set_edge(owner, 1, owner).expect("edge"); + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + drive(&mut session, 1); + let report = session.report(); + assert_eq!(report.marked_nodes, 1); + assert_eq!(session.stats().collections, 1); + session.pulse(4); + assert_eq!(session.stats().collections, 1); + + let mut twin = LuaHeap::new(limits(2, 1, 1)); + let twin_owner = twin.alloc().expect("owner"); + let _twin_dead = twin.alloc().expect("dead"); + root_one(&mut twin, twin_owner); + twin.set_edge(twin_owner, 1, twin_owner).expect("edge"); + let mut mark = MarkSession::start(&mut twin); + mark.drain(); + let via_mark = mark.sweep(); + assert_eq!(via_mark, report); + assert_eq!(twin.stats().collections, 1); + assert_eq!(twin.take_scan_meter().sweep_edge_checks, 1); +} + +/// A freed slot can be reissued. The survivor's identity does not depend on color. +#[test] +fn reissue_after_drain_keeps_survivor_identity() { + let mut heap = LuaHeap::new(limits(3, 2, 1)); + let owner = heap.alloc().expect("owner"); + let stay = heap.alloc().expect("stay"); + let dead = heap.alloc().expect("dead"); + let slot = dead.slot(); + let generation = dead.generation(); + root_all(&mut heap, &[owner, stay]); + heap.set_named_edge(owner, "keep", stay).expect("keep"); + let carrier = heap.issue_carrier(stay).expect("carrier"); + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + drive(&mut session, 1); + drop(session); + assert!(!heap.alive(dead)); + let again = heap.alloc().expect("reissue"); + assert_eq!(again.slot(), slot); + assert_ne!(again.generation(), generation); + assert!( + heap.next_guest(again, &Value::Null) + .expect("next") + .is_none() + ); + assert_eq!(heap.named_edge(owner, "keep").expect("keep"), Some(stay)); + assert_eq!(heap.guest_class(&carrier), GuestClass::Table(stay)); + assert_eq!(heap.issued_value(stay).expect("issued"), carrier); +} + +/// `collect` and `MarkSession::sweep` finish on the same sweep meters. +#[test] +fn collect_and_mark_session_share_the_sweep_core() { + fn build() -> LuaHeap { + let mut heap = LuaHeap::new(limits(3, 1, 2)); + let owner = heap.alloc().expect("owner"); + let dead = heap.alloc().expect("dead"); + root_one(&mut heap, owner); + heap.set_named_edge(owner, "keep", owner).expect("keep"); + heap.set_named_edge(owner, "drop", dead).expect("drop"); + heap + } + let mut direct = build(); + let report = direct.collect(); + let direct_meter = direct.take_scan_meter(); + let mut paused = build(); + let mut mark = MarkSession::start(&mut paused); + mark.drain(); + let paused_report = mark.sweep(); + assert_eq!(paused_report, report); + assert_eq!(paused.take_scan_meter(), direct_meter); +} + +/// Dropping a session that has only selected a slot does not finish the sweep. +#[test] +fn drop_does_not_sweep() { + let mut heap = LuaHeap::new(limits(2, 1, 1)); + let owner = heap.alloc().expect("owner"); + let dead = heap.alloc().expect("dead"); + root_one(&mut heap, owner); + heap.set_edge(owner, 1, dead).expect("edge"); + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + assert!(!session.pulse(1).finished); + drop(session); + assert_eq!(heap.stats().collections, 0); + assert!(heap.alive(dead)); + assert_eq!(heap.stats().edge_slots, 1); +} From d1afea857efbe178bc32c77f2a630c6616249575 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 16:33:40 +0800 Subject: [PATCH 096/225] feat(lua): compare unbound rawequal without metatable dispatch Keep both static arguments on the existing temporary-root path, then compare issued table identity and raw scalars. Missing arguments and bound names stay refusals; extra static arguments are evaluated and ignored. --- tests/luajit_heap_runtime/candidate.rs | 132 +++++ tests/luajit_heap_runtime/rawequal.rs | 517 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 3 files changed, 651 insertions(+) create mode 100644 tests/luajit_heap_runtime/rawequal.rs diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 4d88259..1db0228 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -52,6 +52,9 @@ const RELEASE_RESULT: &str = "lua_internal::release_result"; // They are not Lua syntax and are not registered on the production entry. const COPY_FIELDS: &str = "lua_internal::copy_fields"; const EXTERNAL_SHAPE: &str = "lua_internal::external_shape"; +const BYTE_TEXT: &str = "lua_internal::byte_text"; +const HOST_INT: &str = "lua_internal::host_int"; +const RAW_EQUAL: &str = "lua_internal::raw_equal"; /// Lengths the IR consumer read from `next`'s return transport with Core `len`. /// @@ -100,6 +103,24 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { vec![], HostTypeSchema::Unknown, )); + builder.function(HostFunctionSchema::with_return( + BYTE_TEXT, + vec![], + HostTypeSchema::Unknown, + )); + builder.function(HostFunctionSchema::with_return( + HOST_INT, + vec![], + HostTypeSchema::Unknown, + )); + builder.function(HostFunctionSchema::with_return( + RAW_EQUAL, + vec![ + HostParamSchema::value("left", HostTypeSchema::Unknown), + HostParamSchema::value("right", HostTypeSchema::Unknown), + ], + HostTypeSchema::Bool, + )); builder.function(HostFunctionSchema::with_return( TYPE, vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], @@ -221,6 +242,9 @@ pub(super) fn register( Op::ReleaseResult, Op::CopyFields, Op::ExternalShape, + Op::ByteText, + Op::HostInt, + Op::RawEqual, Op::OpenCell, Op::ReadCell, Op::WriteCell, @@ -255,6 +279,9 @@ pub(super) fn register( Op::ReleaseResult => RELEASE_RESULT, Op::CopyFields => COPY_FIELDS, Op::ExternalShape => EXTERNAL_SHAPE, + Op::ByteText => BYTE_TEXT, + Op::HostInt => HOST_INT, + Op::RawEqual => RAW_EQUAL, Op::OpenCell => OPEN_CELL, Op::ReadCell => READ_CELL, Op::WriteCell => WRITE_CELL, @@ -299,6 +326,9 @@ enum Op { ReleaseResult, CopyFields, ExternalShape, + ByteText, + HostInt, + RawEqual, OpenCell, ReadCell, WriteCell, @@ -503,6 +533,9 @@ impl HostOwnedFunction for Op { } }, Self::ExternalShape => Value::array(vec![Value::Int(0), Value::Int(1)]), + Self::ByteText => Value::bytes(b"ab".to_vec()), + Self::HostInt => Value::Int(7), + Self::RawEqual => raw_equal(call)?, Self::OpenCell => open_cell(call)?, Self::ReadCell => read_cell(call)?, Self::WriteCell => write_cell(call)?, @@ -570,6 +603,59 @@ fn skip_parens(expr: &ast::Expr) -> &ast::Expr { expr } +fn raw_equal(call: &mut OwnedHostCall<'_>) -> Result { + let (left, right) = match call.args() { + [left, right] => (left.clone(), right.clone()), + _ => return Err(host_fault("Lua rawequal needs two values")), + }; + let same = values_raw_equal(&mut call.vm().host_context(), &left, &right)?; + Ok(Value::Bool(same)) +} + +enum EqualKind<'a> { + Nil, + Bool(bool), + Number(f64), + Bytes(&'a [u8]), + Table(heap::TableRef), +} + +fn equal_kind<'a>( + host: &mut vm::HostContext<'_>, + value: &'a Value, +) -> Result, VmError> { + match value { + Value::Null => Ok(EqualKind::Nil), + Value::Bool(bit) => Ok(EqualKind::Bool(*bit)), + Value::Float(number) => Ok(EqualKind::Number(*number)), + Value::Int(_) => Err(host_fault("host integer is not a Lua number")), + Value::String(text) => Ok(EqualKind::Bytes(text.as_bytes())), + Value::Bytes(bytes) => Ok(EqualKind::Bytes(bytes.as_ref())), + Value::Array(_) => match classify(host, value)? { + heap::GuestClass::Table(table) => Ok(EqualKind::Table(table)), + _ => Err(host_fault("Lua rawequal operand is not an issued table")), + }, + _ => Err(host_fault("Lua rawequal operand is not a supported value")), + } +} + +fn values_raw_equal( + host: &mut vm::HostContext<'_>, + left: &Value, + right: &Value, +) -> Result { + let left = equal_kind(host, left)?; + let right = equal_kind(host, right)?; + Ok(match (left, right) { + (EqualKind::Nil, EqualKind::Nil) => true, + (EqualKind::Bool(left), EqualKind::Bool(right)) => left == right, + (EqualKind::Number(left), EqualKind::Number(right)) => left == right, + (EqualKind::Bytes(left), EqualKind::Bytes(right)) => left == right, + (EqualKind::Table(left), EqualKind::Table(right)) => left == right, + _ => false, + }) +} + fn host_fault(message: &str) -> VmError { VmError::HostError(message.to_string()) } @@ -3391,6 +3477,26 @@ impl Lower<'_> { self.reject_tail_next(value, expr.span())?; return self.rawset_expr(table, key, value, expr.span()); } + if name.is("rawequal") { + // Same binding rule as rawset: a shadowed or upvalue name + // is not this builtin, and must not fall through to it. + if self.name_is_bound(name) { + return Err(self.unsupported(expr.span())); + } + return self.rawequal_expr(&args.exprs, expr.span()); + } + if name.is("byte_text") && args.exprs.is_empty() { + if self.name_is_bound(name) { + return Err(self.unsupported(expr.span())); + } + return self.call(BYTE_TEXT, vec![]); + } + if name.is("host_int") && args.exprs.is_empty() { + if self.name_is_bound(name) { + return Err(self.unsupported(expr.span())); + } + return self.call(HOST_INT, vec![]); + } if name.is("external_shape") && args.exprs.is_empty() { return self.call(EXTERNAL_SHAPE, vec![]); } @@ -3462,6 +3568,32 @@ impl Lower<'_> { self.call(name, checked) } + /// Evaluate every static argument on the same temporary-root path as an + /// index operand, then compare only the first two. Extra arguments are + /// evaluated and ignored. Fewer than two is a refusal, not an implicit nil. + fn rawequal_expr(&mut self, args: &[ast::Expr], span: ast::Span) -> Result { + if args.len() < 2 || args.last().is_some_and(|arg| self.is_next_call(arg)) { + return Err(self.unsupported(span)); + } + let temp_base = self.active_temps.len(); + let mut slots = Vec::with_capacity(args.len()); + for arg in args { + let value = self.equal_operand(arg)?; + slots.push(self.index_operand_slot(value, span)?); + } + self.active_temps.truncate(temp_base); + self.call(RAW_EQUAL, vec![Expr::Var(slots[0]), Expr::Var(slots[1])]) + } + + /// String literals keep their raw bytes. Other operands use the existing + /// expression lowerer, including calls that already return one value. + fn equal_operand(&mut self, expr: &ast::Expr) -> Result { + match skip_parens(expr) { + ast::Expr::String { bytes, .. } => Ok(self.string_literal(bytes)), + other => self.expr(other), + } + } + fn collect_expr(&mut self, span: ast::Span) -> Result { // All supported collects are explicit safepoints. Completed arguments // live in compat-emitted temporaries, not in an implicit Core stack scan. diff --git a/tests/luajit_heap_runtime/rawequal.rs b/tests/luajit_heap_runtime/rawequal.rs new file mode 100644 index 0000000..6f459bc --- /dev/null +++ b/tests/luajit_heap_runtime/rawequal.rs @@ -0,0 +1,517 @@ +//! Unbound `rawequal` for the Lua 5.2 candidate. +//! +//! Two static arguments are evaluated left to right and compared without +//! `__eq`, structural equality, or a host integer treated as a Lua number. +//! A fresh table argument is rooted only until the call returns. Extra static +//! arguments are evaluated and ignored. Fewer than two arguments is a lower +//! refusal, not an implicit nil: this candidate has no argument frame that +//! can raise LuaJIT's runtime "value expected". +//! +//! String-call syntax, a trailing `next` adjustment, method calls, and a +//! nested function that reads a chunk local are not lowered. Closures cannot +//! return `type` of a weak field, so the collection witness uses +//! `observe_table`, which records a handle without keeping the carrier. + +use std::sync::Arc; + +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + HostFunctionRegistry, HostImportSchema, HostOwnedFunction, OwnedHostCall, ParseError, + SourceFlavor, SourcePlugin, Value, VmError, VmStatus, +}; + +use super::candidate; +use super::heap; +use super::{catalog, register_witnesses}; + +struct NoteHost; + +#[derive(Clone, Debug, Default)] +struct NoteTags { + pairs: Vec<(f64, bool)>, +} + +impl HostOwnedFunction for NoteHost { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let (tag, value) = match call.args() { + [Value::Float(tag), Value::Bool(value)] => (*tag, *value), + _ => { + return Err(VmError::HostError( + "note_bool expected a tag and a bool".into(), + )); + } + }; + call.vm() + .host_context() + .scope_state_or_insert_with(NoteTags::default) + .map_err(|error| VmError::HostError(error.to_string()))? + .pairs + .push((tag, value)); + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(value)))) + } +} + +struct RawequalPlugin; + +impl SourcePlugin for RawequalPlugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, catalog()) + } +} + +struct Attempt { + vm: vm::Vm, + stack: Option>, +} + +fn attempt(source: &str) -> Result { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&RawequalPlugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .map_err(|error| error.to_string())? + .into_vm() + .map_err(|error| error.to_string())?; + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).map_err(|error| error.to_string())?; + register_witnesses(&mut registry, &catalog); + let note = catalog + .function("lua_host::note_bool") + .expect("note_bool schema"); + registry + .register_exact_owned( + "lua_host::note_bool", + note.params.len() as u8, + HostImportSchema::from_function(&catalog, note), + |_| Box::new(NoteHost), + ) + .map_err(|error| error.to_string())?; + registry + .bind_vm_cached(&mut vm) + .map_err(|error| error.to_string())?; + let status = vm.run().map_err(|error| error.to_string())?; + let stack = (status == VmStatus::Halted).then(|| vm.stack().to_vec()); + Ok(Attempt { vm, stack }) +} + +fn halted(source: &str) -> Attempt { + let ran = attempt(source).unwrap_or_else(|error| panic!("rawequal source failed: {error}")); + assert!( + ran.stack.is_some(), + "rawequal source must halt, stack {:?}", + ran.vm.stack() + ); + ran +} + +fn bool_result(source: &str) -> bool { + let ran = halted(source); + match ran.stack.as_deref() { + Some([Value::Bool(value)]) => *value, + other => panic!("expected one bool, got {other:?}"), + } +} + +fn notes_of(ran: &mut Attempt) -> Vec<(f64, bool)> { + ran.vm + .host_context() + .scope_state::() + .map(|note| note.pairs.clone()) + .unwrap_or_default() +} + +fn alive(ran: &mut Attempt, table: heap::TableRef) -> bool { + heap::with_heap(&mut ran.vm.host_context(), |heap| Ok(heap.alive(table))).expect("alive") +} + +const ALIAS: &str = "\ +local t = {} +local alias = t +local other = {} +return rawequal(t, alias) +"; + +const DISTINCT: &str = "\ +local t = {} +local other = {} +return rawequal(t, other) +"; + +const SAME_TABLE: &str = "\ +local t = {} +return rawequal(t, t) +"; + +const EQ_FIELD: &str = "\ +local a = {} +local b = {} +local mt = {} +mt.__eq = \"yes\" +setmetatable(a, mt) +setmetatable(b, mt) +note_bool(1, rawequal(a, b)) +note_bool(2, rawequal(a, a)) +return mt.__eq +"; + +const CYCLE: &str = "\ +local t = {} +t.self = t +return rawequal(t, t.self) +"; + +const SCALARS: &str = "\ +note_bool(1, rawequal(nil, nil)) +note_bool(2, rawequal(false, nil)) +note_bool(3, rawequal(true, true)) +note_bool(4, rawequal(true, false)) +note_bool(5, rawequal(1, \"1\")) +note_bool(6, rawequal(0, float_bits(1))) +note_bool(7, rawequal(float_bits(2), float_bits(2))) +note_bool(8, rawequal(\"a\\0b\", \"a\\0c\")) +note_bool(9, rawequal(\"a\\0b\", \"a\\0b\")) +note_bool(10, rawequal(\"\\255\\0a\", \"\\255\\0a\")) +note_bool(11, rawequal(\"\\255\\0a\", \"\\255\\0b\")) +note_bool(12, rawequal(\"ab\", byte_text())) +note_bool(13, rawequal(\"abc\", byte_text())) +note_bool(14, rawequal(byte_text(), byte_text())) +return true +"; + +const FORGED_SHAPE: &str = "\ +return rawequal(external_shape(), {}) +"; + +const FORGED_COPY: &str = "\ +local t = {} +return rawequal(t, copy_fields(t)) +"; + +const HOST_INT: &str = "\ +return rawequal(host_int(), 1) +"; + +const HOST_INT_PAIR: &str = "\ +return rawequal(host_int(), host_int()) +"; + +const ORDER: &str = "\ +return rawequal(note_bool(1, true), note_bool(2, false)) +"; + +const REVERSE_ORDER: &str = "\ +return rawequal(note_bool(2, true), note_bool(1, true)) +"; + +const EXTRA: &str = "\ +return rawequal(nil, nil, note_bool(9, true)) +"; + +const MISSING_SECOND: &str = "\ +return rawequal(nil) +"; + +const MISSING_BOTH: &str = "\ +return rawequal() +"; + +const STRING_CALL: &str = "\ +return rawequal\"ab\" +"; + +const TAIL_NEXT: &str = "\ +local t = {} +return rawequal(t, next(t)) +"; + +const BOUND_LOCAL: &str = "\ +local rawequal = 1 +return rawequal(nil, nil) +"; + +const BOUND_UPVALUE: &str = "\ +local rawequal = nil +local function probe() + local ok = rawequal(nil, nil) + return ok +end +return 1 +"; + +const UNBOUND_IN_FUNCTION: &str = "\ +local function probe() + note_bool(1, rawequal(nil, nil)) +end +probe() +return 1 +"; + +const WEAK_PREFIX: &str = "\ +local mt = {} +mt.__mode = \"v\" +local weak = {} +setmetatable(weak, mt) +local orphan = {} +orphan.self = orphan +weak[1] = orphan +observe_table(orphan, 0) +orphan = nil +"; + +const COLLECT_SECOND: &str = "\ +local eq = rawequal({}, (collectgarbage(\"collect\"))) +return eq +"; + +const COLLECT_FIRST: &str = "\ +local eq = rawequal((collectgarbage(\"collect\")), {}) +return eq +"; + +const OMIT_COLLECT: &str = "\ +local eq = rawequal({}, 0) +return eq +"; + +const COLLECT_THEN_RELEASE: &str = "\ +local eq = rawequal({}, (collectgarbage(\"collect\"))) +collectgarbage(\"collect\") +return eq +"; + +fn weak_source(arm: &str) -> String { + format!("{WEAK_PREFIX}{arm}") +} + +fn refuse(source: &str) { + let error = match attempt(source) { + Err(error) => error, + Ok(_) => panic!("bound or incomplete rawequal must not run"), + }; + assert!( + error.contains("Lua expression not lowered yet"), + "refusal must stay a lower error, not a nil result: {error}" + ); + assert!( + !error.contains("true"), + "omission must not be reported as a true comparison: {error}" + ); +} + +#[test] +fn lua_file_rawequal_compares_aliases_and_not_distinct_tables() { + assert!(bool_result(ALIAS), "an alias is the same issued table"); + assert!(bool_result(SAME_TABLE), "a table equals itself"); + assert!( + !bool_result(DISTINCT), + "a different empty table is not structurally equal" + ); +} + +#[test] +fn lua_file_rawequal_does_not_dispatch_eq_or_walk_a_cycle() { + let mut ran = halted(EQ_FIELD); + assert_eq!(ran.stack.as_deref(), Some(&[Value::string("yes")][..])); + assert_eq!( + notes_of(&mut ran), + vec![(1.0, false), (2.0, true)], + "__eq must not make distinct tables equal, and the same table stays true" + ); + let mut cycle = halted(CYCLE); + assert_eq!(cycle.stack.as_deref(), Some(&[Value::Bool(true)][..])); + let stats = + heap::with_heap(&mut cycle.vm.host_context(), |heap| Ok(heap.stats())).expect("stats"); + assert_eq!( + stats.live_edges, 1, + "identity comparison must not walk the cycle" + ); + assert_eq!( + stats.collections, 0, + "the cycle comparison does not collect" + ); +} + +#[test] +fn lua_file_rawequal_compares_scalars_and_string_bytes() { + let mut ran = halted(SCALARS); + assert_eq!( + notes_of(&mut ran), + vec![ + (1.0, true), + (2.0, false), + (3.0, true), + (4.0, false), + (5.0, false), + (6.0, true), + (7.0, false), + (8.0, false), + (9.0, true), + (10.0, true), + (11.0, false), + (12.0, true), + (13.0, false), + (14.0, true), + ] + ); +} + +#[test] +fn lua_file_rawequal_rejects_forged_carriers_and_host_integers() { + let shape = match attempt(FORGED_SHAPE) { + Err(error) => error, + Ok(_) => panic!("an unsigned shape is not a table"), + }; + assert!( + shape.contains("not an issued table"), + "forged shape must be rejected, not compared: {shape}" + ); + let copied = match attempt(FORGED_COPY) { + Err(error) => error, + Ok(_) => panic!("a field copy is not the issued table"), + }; + assert!( + copied.contains("not an issued table"), + "structural copy must be rejected, not equal: {copied}" + ); + for source in [HOST_INT, HOST_INT_PAIR] { + let error = match attempt(source) { + Err(error) => error, + Ok(_) => panic!("a host integer is not a Lua number"), + }; + assert!( + error.contains("host integer"), + "host integer must not compare as a number or as false: {error}" + ); + } +} + +#[test] +fn lua_file_rawequal_evaluates_static_arguments_left_to_right() { + let mut forward = halted(ORDER); + assert_eq!(forward.stack.as_deref(), Some(&[Value::Bool(false)][..])); + assert_eq!(notes_of(&mut forward), vec![(1.0, true), (2.0, false)]); + let mut reverse = halted(REVERSE_ORDER); + assert_eq!(reverse.stack.as_deref(), Some(&[Value::Bool(true)][..])); + assert_eq!( + notes_of(&mut reverse), + vec![(2.0, true), (1.0, true)], + "argument order is source order, not tag order" + ); + let mut extra = halted(EXTRA); + assert_eq!(extra.stack.as_deref(), Some(&[Value::Bool(true)][..])); + assert_eq!( + notes_of(&mut extra), + vec![(9.0, true)], + "an extra static argument is evaluated, then ignored" + ); +} + +#[test] +fn lua_file_rawequal_refuses_missing_arguments_and_bound_names() { + refuse(MISSING_SECOND); + refuse(MISSING_BOTH); + refuse(STRING_CALL); + refuse(TAIL_NEXT); + refuse(BOUND_LOCAL); + refuse(BOUND_UPVALUE); + let mut unbound = halted(UNBOUND_IN_FUNCTION); + assert_eq!(unbound.stack.as_deref(), Some(&[Value::Float(1.0)][..])); + assert_eq!( + notes_of(&mut unbound), + vec![(1.0, true)], + "an unbound name inside a function is the builtin" + ); +} + +#[test] +fn lua_file_rawequal_roots_the_first_table_only_until_the_call_returns() { + let mut kept = halted(&weak_source(COLLECT_SECOND)); + assert_eq!(kept.stack.as_deref(), Some(&[Value::Bool(false)][..])); + let kept_stats = + heap::with_heap(&mut kept.vm.host_context(), |heap| Ok(heap.stats())).expect("kept stats"); + assert_eq!( + kept_stats.collections, 1, + "the second argument collects once" + ); + assert_eq!( + kept_stats.last_marked, 3, + "metatable, weak table, and the unrooted first argument are marked" + ); + assert_eq!( + kept_stats.live_nodes, 3, + "the first argument stays live through that collection" + ); + let kept_seen = super::observed_tables(&mut kept.vm); + assert_eq!( + kept_seen.len(), + 1, + "the weak orphan was observed before collection" + ); + assert!( + !alive(&mut kept, kept_seen[0].table), + "the independent weak orphan must actually be collected" + ); + + let mut released = halted(&weak_source(COLLECT_THEN_RELEASE)); + let released_stats = + heap::with_heap(&mut released.vm.host_context(), |heap| Ok(heap.stats())).expect("release"); + assert_eq!( + released_stats.collections, 2, + "the call returns, then a second collect runs" + ); + assert_eq!( + released_stats.last_marked, 2, + "after the call, the first argument has no root" + ); + assert_eq!( + released_stats.live_nodes, 2, + "the returned first argument can be collected" + ); + + let mut omitted = halted(&weak_source(OMIT_COLLECT)); + let omitted_stats = + heap::with_heap(&mut omitted.vm.host_context(), |heap| Ok(heap.stats())).expect("omit"); + assert_eq!(omitted_stats.collections, 0, "the control does not collect"); + assert_eq!( + omitted_stats.live_nodes, 4, + "the orphan stays when collection is omitted" + ); + let omitted_seen = super::observed_tables(&mut omitted.vm); + assert!( + alive(&mut omitted, omitted_seen[0].table), + "without a collection the weak orphan stays live" + ); + + let mut reversed = halted(&weak_source(COLLECT_FIRST)); + let reversed_stats = + heap::with_heap(&mut reversed.vm.host_context(), |heap| Ok(heap.stats())).expect("reverse"); + assert_eq!(reversed_stats.collections, 1); + assert_eq!( + reversed_stats.last_marked, 2, + "collection in the first argument happens before the table exists" + ); + let reversed_seen = super::observed_tables(&mut reversed.vm); + assert!( + !alive(&mut reversed, reversed_seen[0].table), + "the weak orphan is collected when the collect runs first" + ); +} + +#[test] +fn rawequal_is_not_a_host_catalog_entry() { + assert!(catalog().function("lua_internal::new_table").is_some()); + assert!(catalog().function("lua_host::rawequal").is_none()); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index b65aff3..c582901 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -12,6 +12,8 @@ mod envelope_local_root; mod lexer; #[path = "../../src/frontends/lua/parser.rs"] mod parser; +#[path = "rawequal.rs"] +mod rawequal; #[path = "rawset.rs"] mod rawset; #[path = "../../src/frontends/lua/resolve.rs"] From 16a65ed8be63c5a260173b8e7f93a98ab7a1d348 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 16:59:14 +0800 Subject: [PATCH 097/225] fix(lua): skip nil and raw bytes in shared root gather A later collect used to reject those legal rawequal arguments as invalid root candidates. GatherRoot skips the two scalars because they have no heap node. Host integers, forged carriers, expired carriers, table roots, and callable envelopes stay on the existing path. --- tests/luajit_heap_runtime/candidate.rs | 35 +++++++++------- tests/luajit_heap_runtime/rawequal.rs | 56 ++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 14 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 1db0228..58644df 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -445,20 +445,27 @@ impl HostOwnedFunction for Op { )); } }; - let included = match classify(&mut call.vm().host_context(), &value)? { - heap::GuestClass::Table(_) => Some(value), - heap::GuestClass::Number - | heap::GuestClass::Boolean - | heap::GuestClass::String => None, - heap::GuestClass::Unissued => { - // A callable is not a table root. Its shadow envelope, - // when still assigned, is the issued table gather sees. - if matches!(value, Value::Callable(_)) { - None - } else { - return Err(VmError::HostError( - "invalid private Lua root candidate".to_string(), - )); + let included = if matches!(value, Value::Null | Value::Bytes(_)) { + // These scalars are legal Lua values and have no heap node. + // Host integers, forged arrays, and expired carriers still + // fall through to classification and stay rejected. + None + } else { + match classify(&mut call.vm().host_context(), &value)? { + heap::GuestClass::Table(_) => Some(value), + heap::GuestClass::Number + | heap::GuestClass::Boolean + | heap::GuestClass::String => None, + heap::GuestClass::Unissued => { + // A callable is not a table root. Its shadow envelope, + // when still assigned, is the issued table gather sees. + if matches!(value, Value::Callable(_)) { + None + } else { + return Err(VmError::HostError( + "invalid private Lua root candidate".to_string(), + )); + } } } }; diff --git a/tests/luajit_heap_runtime/rawequal.rs b/tests/luajit_heap_runtime/rawequal.rs index 6f459bc..2421bea 100644 --- a/tests/luajit_heap_runtime/rawequal.rs +++ b/tests/luajit_heap_runtime/rawequal.rs @@ -7,6 +7,9 @@ //! refusal, not an implicit nil: this candidate has no argument frame that //! can raise LuaJIT's runtime "value expected". //! +//! Nil and a raw byte string are legal arguments. Neither has a Lua heap +//! node, so a later explicit collect skips them in the shared root gather. +//! //! String-call syntax, a trailing `next` adjustment, method calls, and a //! nested function that reads a chunk local are not lowered. Closures cannot //! return `type` of a weak field, so the collection witness uses @@ -137,6 +140,39 @@ fn alive(ran: &mut Attempt, table: heap::TableRef) -> bool { heap::with_heap(&mut ran.vm.host_context(), |heap| Ok(heap.alive(table))).expect("alive") } +fn scalar_collect_is_false_and_reclaims_the_orphan(source: &str) { + let mut ran = halted(&weak_source(source)); + assert_eq!( + ran.stack.as_deref(), + Some(&[Value::Bool(false)][..]), + "the scalar is not equal to the collect result" + ); + let stats = + heap::with_heap(&mut ran.vm.host_context(), |heap| Ok(heap.stats())).expect("stats"); + assert_eq!( + stats.collections, 1, + "the later argument performs one real collection" + ); + assert_eq!( + stats.last_marked, 2, + "metatable and weak table are marked; the scalar is not a heap root" + ); + assert_eq!( + stats.live_nodes, 2, + "the scalar adds no heap node, and the orphan is swept" + ); + let seen = super::observed_tables(&mut ran.vm); + assert_eq!( + seen.len(), + 1, + "the weak orphan was observed before collection" + ); + assert!( + !alive(&mut ran, seen[0].table), + "the independent weak orphan must actually be collected" + ); +} + const ALIAS: &str = "\ local t = {} local alias = t @@ -292,6 +328,16 @@ collectgarbage(\"collect\") return eq "; +const NIL_THEN_COLLECT: &str = "\ +local eq = rawequal(nil, (collectgarbage(\"collect\"))) +return eq +"; + +const BYTES_THEN_COLLECT: &str = "\ +local eq = rawequal(\"\\255\\0a\", (collectgarbage(\"collect\"))) +return eq +"; + fn weak_source(arm: &str) -> String { format!("{WEAK_PREFIX}{arm}") } @@ -510,6 +556,16 @@ fn lua_file_rawequal_roots_the_first_table_only_until_the_call_returns() { ); } +#[test] +fn lua_file_rawequal_compares_nil_against_a_later_collect() { + scalar_collect_is_false_and_reclaims_the_orphan(NIL_THEN_COLLECT); +} + +#[test] +fn lua_file_rawequal_compares_raw_bytes_against_a_later_collect() { + scalar_collect_is_false_and_reclaims_the_orphan(BYTES_THEN_COLLECT); +} + #[test] fn rawequal_is_not_a_host_catalog_entry() { assert!(catalog().function("lua_internal::new_table").is_some()); From e45d3410c2222d64e08d7b11f16179e137daba85 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 17:08:58 +0800 Subject: [PATCH 098/225] feat(lua): pause pending-close enumeration on a caller budget Mark still finishes before host close. The doomed-token walk checks one slot per scan unit and resumes from its cursor. heap::collect drains that enumerator before synchronous close, so an unfinished scan is not given to sweep. --- src/frontends/lua/heap/table.rs | 34 +- src/frontends/lua/heap/table/pending_close.rs | 116 ++++++ .../budgeted_token_scan.rs | 386 ++++++++++++++++++ 3 files changed, 515 insertions(+), 21 deletions(-) create mode 100644 src/frontends/lua/heap/table/pending_close.rs create mode 100644 tests/luajit_heap_runtime/budgeted_token_scan.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 9753afe..9353c86 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -16,9 +16,12 @@ use super::handle::{ClosureRef, HandleKind, TableRef, UpvalueRef}; #[path = "table/mark.rs"] mod mark; +#[path = "table/pending_close.rs"] +mod pending_close; #[path = "table/sweep.rs"] mod sweep; use mark::MarkSession; +use pending_close::{PendingCloseSession, PendingCloseView}; use sweep::SweepSession; static NEXT_DOMAIN: AtomicU64 = AtomicU64::new(1); @@ -1846,29 +1849,15 @@ impl LuaHeap { true } - /// Marks once and returns unreachable stored tokens with their slots, - /// plus the weak modes sweep needs after those tokens close. Does not - /// release nodes. A close error drops the modes with this result; the - /// next collect marks and parses again. [`Self::sweep_marked`] uses this - /// same mark and does not build another mode index. + /// Marks once, then drains the pending-close enumerator. Each slot check + /// is one scan unit. The drain finishes before this returns, so host close + /// still sees every doomed token and the original mark snapshot. A partial + /// pulse is not returned from here and is not given to sweep. pub(super) fn mark_and_doomed_tokens(&mut self) -> DoomedMark { let modes = self.mark_reachable(); - let tokens: Vec = self - .slots - .iter() - .enumerate() - .filter_map(|(index, slot)| match slot.state { - SlotState::Live { marked: false } => slot.token.map(|raw| DoomedToken { - raw, - slot: index as u32, - generation: slot.generation, - }), - _ => None, - }) - .collect(); - self.scan.node_slot_visits += self.slots.len() as u64; - self.scan.scratch.pending_close_pushed += tokens.len() as u64; - DoomedMark { tokens, modes } + let mut session = PendingCloseSession::start(self, modes); + session.drain(); + session.finish() } /// Non-moving mark from explicit roots, then one sweep of unmarked nodes. @@ -2280,3 +2269,6 @@ mod budgeted_mark; #[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/budgeted_sweep.rs"] mod budgeted_sweep; +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/budgeted_token_scan.rs"] +mod budgeted_token_scan; diff --git a/src/frontends/lua/heap/table/pending_close.rs b/src/frontends/lua/heap/table/pending_close.rs new file mode 100644 index 0000000..d6e3f25 --- /dev/null +++ b/src/frontends/lua/heap/table/pending_close.rs @@ -0,0 +1,116 @@ +//! Pausable pending-close enumeration after a finished mark. +//! +//! The session holds the heap borrow. A pulse spends one scan unit before it +//! checks one slot. Budget 0 checks nothing and appends nothing. Only a live, +//! unmarked slot with a token is appended, in ascending slot index order. +//! `Vec` growth above that append is not a scan unit and is not a wall-clock +//! bound. +//! +//! `finish` is the only handoff. It returns the tokens and the original mark +//! snapshot, and it refuses an unfinished scan. Drop does not sweep and does +//! not close. This session does not mark again and is not a guest pause. + +use super::{DoomedMark, DoomedToken, LuaHeap, MarkSnapshot, ScanMeter, SlotState}; + +pub(super) struct PendingCloseSession<'a> { + heap: &'a mut LuaHeap, + modes: MarkSnapshot, + tokens: Vec, + index: usize, + done: bool, + pulse_pushed: u64, +} + +pub(super) struct PendingCloseView { + pub(super) finished: bool, + pub(super) meter: ScanMeter, + pub(super) spent: u64, + pub(super) pushed: u64, + pub(super) cursor: u32, +} + +impl<'a> PendingCloseSession<'a> { + /// Starts after mark. `modes` is the snapshot mark already built. This + /// does not walk slots and does not mark again. + pub(super) fn start(heap: &'a mut LuaHeap, modes: MarkSnapshot) -> Self { + Self { + heap, + modes, + tokens: Vec::new(), + index: 0, + done: false, + pulse_pushed: 0, + } + } + + pub(super) fn meter(&self) -> ScanMeter { + self.heap.scan + } + + pub(super) fn pulse(&mut self, budget: u64) -> PendingCloseView { + if budget == 0 || self.done { + return self.view(0, 0); + } + self.pulse_pushed = 0; + let mut left = budget; + let mut spent = 0u64; + while left > 0 && !self.done { + if self.step() { + left -= 1; + spent += 1; + } + } + self.view(spent, self.pulse_pushed) + } + + pub(super) fn drain(&mut self) { + while !self.done { + self.pulse(64); + } + } + + /// Tokens and the original snapshot. An unfinished scan does not return. + pub(super) fn finish(self) -> DoomedMark { + assert!(self.done, "pending close is not finished"); + DoomedMark { + tokens: self.tokens, + modes: self.modes, + } + } + + fn step(&mut self) -> bool { + if self.index >= self.heap.slots.len() { + self.done = true; + return false; + } + let index = self.index; + self.index += 1; + self.heap.scan.node_slot_visits += 1; + let slot = &self.heap.slots[index]; + if let SlotState::Live { marked: false } = slot.state + && let Some(raw) = slot.token + { + self.tokens.push(DoomedToken { + raw, + slot: index as u32, + generation: slot.generation, + }); + self.heap.scan.scratch.pending_close_pushed += 1; + self.pulse_pushed += 1; + } + if self.index >= self.heap.slots.len() { + self.done = true; + } + true + } + + fn view(&self, spent: u64, pushed: u64) -> PendingCloseView { + PendingCloseView { + finished: self.done, + meter: self.heap.scan, + spent, + pushed, + cursor: self.index as u32, + } + } +} diff --git a/tests/luajit_heap_runtime/budgeted_token_scan.rs b/tests/luajit_heap_runtime/budgeted_token_scan.rs new file mode 100644 index 0000000..68f835b --- /dev/null +++ b/tests/luajit_heap_runtime/budgeted_token_scan.rs @@ -0,0 +1,386 @@ +//! Pausable pending-close enumeration after a finished mark. +//! +//! A pulse spends one scan unit before it checks one slot. Budget 0 checks +//! nothing and appends nothing. `Vec` growth is not a scan unit and is not a +//! wall-clock bound. The session holds the heap borrow. `finish` is the only +//! handoff of tokens and the original mark snapshot. An unfinished session +//! cannot commit, and drop does not sweep. + +use super::{HeapLimits, LuaHeap, PendingCloseSession, PendingCloseView, ScanMeter, TableRef}; + +fn limits(nodes: u32) -> HeapLimits { + HeapLimits { + nodes, + roots: 4, + edges: 8, + max_generation: 8, + } +} + +fn root_one(heap: &mut LuaHeap, table: TableRef) { + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, table).expect("root"); +} + +fn bind(heap: &mut LuaHeap, table: TableRef, raw: u64) { + heap.bind_token(table, raw).expect("bind"); +} + +fn assert_pulse_meter(before: &ScanMeter, view: &PendingCloseView) { + assert_eq!( + view.meter.node_slot_visits - before.node_slot_visits, + view.spent, + "node_slot_visits must rise by the slots this pulse checked" + ); + assert_eq!( + view.meter.scratch.pending_close_pushed - before.scratch.pending_close_pushed, + view.pushed, + "pending_close_pushed must rise by the tokens this pulse appended" + ); + assert_eq!( + view.meter.mark_passes, before.mark_passes, + "enum must not remark" + ); + assert_eq!( + view.meter.weak_mode_slot_checks, before.weak_mode_slot_checks, + "enum must not rescan mode slots" + ); + assert_eq!(view.meter.root_slot_visits, before.root_slot_visits); + assert_eq!(view.meter.token_closes, before.token_closes); + assert_eq!(view.meter.token_slot_checks, before.token_slot_checks); + assert!(view.spent <= view.meter.node_slot_visits); +} + +/// Budget 1 on a wide slot vector checks the first slot and stops. +#[test] +fn budget_one_checks_one_slot_on_a_wide_vector() { + let mut heap = LuaHeap::new(limits(8)); + let mut tables = Vec::new(); + for raw in 1..=5 { + let table = heap.alloc().expect("table"); + bind(&mut heap, table, raw); + tables.push(table); + } + let modes = heap.drain_mark(); + let mut session = PendingCloseSession::start(&mut heap, modes); + let before = session.meter(); + let view = session.pulse(1); + assert_pulse_meter(&before, &view); + assert!( + !view.finished && view.spent == 1 && view.cursor == 1 && view.pushed == 1, + "budget 1 walked {} slots, pushed {}, finished={}, cursor={}", + view.spent, + view.pushed, + view.finished, + view.cursor + ); + assert_eq!(view.meter.node_slot_visits - before.node_slot_visits, 1); +} + +/// An empty slot vector finishes on a positive budget and spends nothing. +#[test] +fn empty_vector_finishes_without_a_slot_check() { + let mut heap = LuaHeap::new(limits(1)); + let modes = heap.drain_mark(); + let mut session = PendingCloseSession::start(&mut heap, modes); + let before = session.meter(); + let zero = session.pulse(0); + assert!(!zero.finished); + assert_eq!(zero.spent, 0); + assert_eq!(zero.pushed, 0); + assert_eq!(zero.cursor, 0); + assert_eq!(zero.meter, before); + let done = session.pulse(1); + assert!(done.finished); + assert_eq!(done.spent, 0); + assert_eq!(done.pushed, 0); + assert_eq!(done.cursor, 0); + assert_eq!(done.meter, before); + let committed = session.finish(); + assert!(committed.tokens.is_empty()); +} + +/// Budget 0, including one issued mid-scan, checks no slot and appends nothing. +#[test] +fn zero_budget_checks_no_slot_and_appends_nothing() { + let mut heap = LuaHeap::new(limits(4)); + let first = heap.alloc().expect("first"); + let second = heap.alloc().expect("second"); + bind(&mut heap, first, 11); + bind(&mut heap, second, 22); + let modes = heap.drain_mark(); + let mut session = PendingCloseSession::start(&mut heap, modes); + let marked = session.meter(); + let zero = session.pulse(0); + assert!(!zero.finished); + assert_eq!(zero.spent, 0); + assert_eq!(zero.pushed, 0); + assert_eq!(zero.cursor, 0); + assert_eq!(zero.meter, marked); + let one = session.pulse(1); + assert!(!one.finished); + assert_eq!(one.spent, 1); + assert_eq!(one.cursor, 1); + let mid = session.meter(); + let cursor = one.cursor; + let again = session.pulse(0); + assert!(!again.finished); + assert_eq!(again.spent, 0); + assert_eq!(again.pushed, 0); + assert_eq!(again.cursor, cursor); + assert_eq!(again.meter, mid); + let rest = session.pulse(1); + assert!(rest.finished); + assert_eq!(rest.cursor, 2); + let done = session.finish(); + assert_eq!(done.tokens.len(), 2); + assert_eq!(done.tokens[0].raw, 11); + assert_eq!(done.tokens[1].raw, 22); +} + +/// A free hole is visited and is not a pending token. Doomed tokens stay in slot order. +#[test] +fn sparse_free_hole_is_visited_and_skipped_for_tokens() { + let mut heap = LuaHeap::new(limits(4)); + let left = heap.alloc().expect("left"); + let hole = heap.alloc().expect("hole"); + let right = heap.alloc().expect("right"); + bind(&mut heap, left, 3); + bind(&mut heap, right, 9); + heap.rollback(hole).expect("free the middle slot"); + assert_eq!(left.slot(), 0); + assert_eq!(hole.slot(), 1); + assert_eq!(right.slot(), 2); + let modes = heap.drain_mark(); + let before_nodes = heap.stats().live_nodes; + let mut session = PendingCloseSession::start(&mut heap, modes); + let before = session.meter(); + let view = session.pulse(8); + assert_pulse_meter(&before, &view); + assert!(view.finished); + assert_eq!(view.spent, 3, "free hole is still one slot check"); + assert_eq!(view.cursor, 3); + assert_eq!(view.pushed, 2); + assert_eq!(view.meter.mark_passes, before.mark_passes); + let done = session.finish(); + assert_eq!(done.tokens.len(), 2); + assert_eq!(done.tokens[0].raw, 3); + assert_eq!(done.tokens[0].slot, 0); + assert_eq!(done.tokens[0].generation, left.generation()); + assert_eq!(done.tokens[1].raw, 9); + assert_eq!(done.tokens[1].slot, 2); + assert_eq!(done.tokens[1].generation, right.generation()); + let report = heap.sweep_marked(done.modes); + assert_eq!(report.live_nodes, 0); + assert_eq!(heap.stats().live_nodes, 0); + assert_eq!(before_nodes, 2); + assert!(!heap.alive(left)); + assert!(!heap.alive(right)); +} + +/// A live slot with no token is checked and is not appended. +#[test] +fn tokenless_live_slot_is_checked_and_not_appended() { + let mut heap = LuaHeap::new(limits(4)); + let doomed = heap.alloc().expect("doomed"); + let bare = heap.alloc().expect("no token"); + let closure = heap.alloc_closure().expect("closure"); + bind(&mut heap, doomed, 17); + let modes = heap.drain_mark(); + let mut session = PendingCloseSession::start(&mut heap, modes); + let before = session.meter(); + let view = session.pulse(3); + assert_pulse_meter(&before, &view); + assert!(view.finished); + assert_eq!(view.spent, 3); + assert_eq!(view.pushed, 1); + assert_eq!(view.cursor, 3); + let done = session.finish(); + assert_eq!(done.tokens.len(), 1); + assert_eq!(done.tokens[0].raw, 17); + assert_eq!(done.tokens[0].slot, doomed.slot()); + assert_eq!(done.tokens[0].generation, doomed.generation()); + assert!(heap.closure_alive(closure)); + assert!(heap.alive(bare)); + drop(done); + assert!( + heap.alive(bare), + "enumeration does not release a tokenless node" + ); +} + +/// A marked survivor keeps its token out of the pending-close list. +#[test] +fn marked_survivor_token_is_not_pending_close() { + let mut heap = LuaHeap::new(limits(4)); + let survivor = heap.alloc().expect("survivor"); + let doomed = heap.alloc().expect("doomed"); + bind(&mut heap, survivor, 100); + bind(&mut heap, doomed, 200); + root_one(&mut heap, survivor); + let modes = heap.drain_mark(); + let mut session = PendingCloseSession::start(&mut heap, modes); + let before = session.meter(); + let view = session.pulse(2); + assert_pulse_meter(&before, &view); + assert!(view.finished); + assert_eq!(view.spent, 2); + assert_eq!(view.pushed, 1); + assert_eq!(view.meter.mark_passes, before.mark_passes); + let done = session.finish(); + assert_eq!(done.tokens.len(), 1); + assert_eq!(done.tokens[0].raw, 200); + assert_eq!(done.tokens[0].slot, doomed.slot()); + assert_eq!(done.tokens[0].generation, doomed.generation()); + let report = heap.sweep_marked(done.modes); + assert_eq!(report.live_nodes, 1); + assert!(heap.alive(survivor)); + assert!(!heap.alive(doomed)); + assert_eq!( + heap.published_token(survivor) + .expect("survivor token stays"), + 100 + ); +} + +/// A budget equal to the slot count finishes on that boundary. One less stops on the cursor. +#[test] +fn exact_budget_stops_on_the_cursor_boundary() { + let mut heap = LuaHeap::new(limits(4)); + let mut tables = Vec::new(); + for raw in [7u64, 8, 9] { + let table = heap.alloc().expect("table"); + bind(&mut heap, table, raw); + tables.push(table); + } + let modes = heap.drain_mark(); + let mut session = PendingCloseSession::start(&mut heap, modes); + let before = session.meter(); + let short = session.pulse(2); + assert_pulse_meter(&before, &short); + assert!(!short.finished); + assert_eq!(short.spent, 2); + assert_eq!(short.cursor, 2); + assert_eq!(short.pushed, 2); + let mid = session.meter(); + let last = session.pulse(1); + assert_pulse_meter(&mid, &last); + assert!(last.finished); + assert_eq!(last.spent, 1); + assert_eq!(last.cursor, 3); + assert_eq!(last.pushed, 1); + let done = session.finish(); + assert_eq!( + done.tokens + .iter() + .map(|token| (token.raw, token.slot, token.generation)) + .collect::>(), + vec![ + (7, tables[0].slot(), tables[0].generation()), + (8, tables[1].slot(), tables[1].generation()), + (9, tables[2].slot(), tables[2].generation()), + ] + ); + + let mut heap = LuaHeap::new(limits(4)); + for raw in [1u64, 2, 3, 4] { + let table = heap.alloc().expect("table"); + bind(&mut heap, table, raw); + } + let modes = heap.drain_mark(); + let mut session = PendingCloseSession::start(&mut heap, modes); + let before = session.meter(); + let exact = session.pulse(4); + assert_pulse_meter(&before, &exact); + assert!(exact.finished, "budget equal to the slot count finishes"); + assert_eq!(exact.spent, 4); + assert_eq!(exact.cursor, 4); + assert_eq!(exact.pushed, 4); + let extra = session.pulse(1); + assert!(extra.finished); + assert_eq!(extra.spent, 0); + assert_eq!(extra.pushed, 0); + assert_eq!(extra.cursor, 4); + let _ = session.finish(); +} + +/// One-slot pulses keep the cursor and emit tokens in ascending slot order. +#[test] +fn resumed_pulses_keep_cursor_and_token_order() { + let mut heap = LuaHeap::new(limits(8)); + let early = heap.alloc().expect("early"); + heap.rollback(early).expect("bump generation"); + let reused = heap.alloc().expect("reused"); + assert_eq!(reused.slot(), early.slot()); + assert_eq!(reused.generation(), early.generation() + 1); + bind(&mut heap, reused, 41); + let bare = heap.alloc().expect("bare"); + let later = heap.alloc().expect("later"); + bind(&mut heap, later, 42); + let rooted = heap.alloc().expect("rooted"); + bind(&mut heap, rooted, 99); + root_one(&mut heap, rooted); + let modes = heap.drain_mark(); + let slots = heap.stats().node_slots; + let mut session = PendingCloseSession::start(&mut heap, modes); + let visits_before = session.meter().node_slot_visits; + let mut cursor = 0u32; + let mut pushed = 0u64; + for _ in 0..slots { + let before = session.meter(); + let view = session.pulse(1); + assert_pulse_meter(&before, &view); + assert_eq!(view.spent, 1); + assert_eq!(view.cursor, cursor + 1); + cursor = view.cursor; + pushed += view.pushed; + if view.finished { + break; + } + } + assert_eq!(cursor, slots); + assert_eq!(pushed, 2); + assert_eq!( + session.meter().node_slot_visits - visits_before, + u64::from(slots), + "one visit per slot, with no second pass" + ); + let done = session.finish(); + assert_eq!(done.tokens.len(), 2); + assert_eq!(done.tokens[0].raw, 41); + assert_eq!(done.tokens[0].slot, reused.slot()); + assert_eq!(done.tokens[0].generation, reused.generation()); + assert_eq!(done.tokens[1].raw, 42); + assert_eq!(done.tokens[1].slot, later.slot()); + assert_eq!(done.tokens[1].generation, later.generation()); + assert!( + done.tokens + .windows(2) + .all(|pair| pair[0].slot < pair[1].slot) + ); + assert!(done.tokens.iter().all(|token| token.raw != 99)); + assert!(heap.alive(bare)); + assert!(heap.alive(rooted)); +} + +/// An unfinished scan cannot hand tokens or the snapshot to sweep. +#[test] +fn unfinished_enumeration_cannot_be_committed() { + let mut heap = LuaHeap::new(limits(4)); + let first = heap.alloc().expect("first"); + let second = heap.alloc().expect("second"); + bind(&mut heap, first, 5); + bind(&mut heap, second, 6); + let modes = heap.drain_mark(); + let mut session = PendingCloseSession::start(&mut heap, modes); + let view = session.pulse(1); + assert!(!view.finished); + assert_eq!(view.cursor, 1); + let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| session.finish())); + assert!(caught.is_err(), "unfinished enumeration must not commit"); + assert_eq!(heap.stats().collections, 0, "refusal must not sweep"); + assert!(heap.alive(first)); + assert!(heap.alive(second)); + assert_eq!(heap.published_token(first).expect("token stays"), 5); + assert_eq!(heap.published_token(second).expect("token stays"), 6); +} From f685a3709a21321f5ea13fd9fbaeeb7def525c86 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 18:00:21 +0800 Subject: [PATCH 099/225] feat(lua): repair a parked gray cursor when its edge slot is reused A paused mark keeps its progress on the heap and only opens ordinary field edits. unlink_at advances that cursor to the old successor before the record returns to the free list, so a later reuse cannot be scanned as the original owner's next edge. --- src/frontends/lua/heap/table.rs | 23 + src/frontends/lua/heap/table/mark.rs | 844 ++++++++++++++++------- tests/luajit_heap_runtime/parked_mark.rs | 577 ++++++++++++++++ 3 files changed, 1178 insertions(+), 266 deletions(-) create mode 100644 tests/luajit_heap_runtime/parked_mark.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 9353c86..b03248b 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -21,6 +21,8 @@ mod pending_close; #[path = "table/sweep.rs"] mod sweep; use mark::MarkSession; +#[cfg(test)] +use mark::{ParkedMark, PausedOp, PendingScan}; use pending_close::{PendingCloseSession, PendingCloseView}; use sweep::SweepSession; @@ -97,6 +99,10 @@ pub enum HeapError { /// Execution-scope or resource-table failure. `publish` rolls the reserved /// node back before returning this error. Scope(String), + /// A parked mark does not allow this edit. The heap is unchanged. + MarkDenied, + /// A mark is already active, so a second start or private collect cannot run. + MarkActive, } impl HeapError { @@ -123,6 +129,8 @@ impl fmt::Display for HeapError { Self::NextUnsupported => write!(formatter, "next key is not a guest key"), Self::AlreadyInstalled => write!(formatter, "lua heap already installed"), Self::Scope(message) => write!(formatter, "lua heap scope error: {message}"), + Self::MarkDenied => write!(formatter, "lua mark denied this edit"), + Self::MarkActive => write!(formatter, "lua mark is already active"), } } } @@ -522,6 +530,12 @@ pub struct ScanMeter { pub node_slot_visits: u64, /// Root-slot reads during root enumeration and the dead-root sweep. pub root_slot_visits: u64, + /// Ordinary field writes accepted while a mark is parked. Not a pulse unit, + /// and not folded into the scan budget. A full collect leaves this at zero. + pub parked_edge_writes: u64, + /// Parked gray cursors advanced inside `unlink_at` after it has read the + /// old successor. Not a pulse unit. A full collect leaves this at zero. + pub parked_cursor_repairs: u64, pub scratch: ScanScratch, } @@ -621,6 +635,9 @@ pub struct LuaHeap { peak_roots: u32, peak_edges: u32, scan: ScanMeter, + /// Mark progress saved between pulses. Absent unless a session or the + /// parked driver is active. Done is not stored for the parked caller. + mark: Option, /// String and byte lengths stored in edge records. Not Vec capacity, not /// Core locals, and not a second scan of `edges`. payload_bytes: u64, @@ -671,6 +688,7 @@ impl LuaHeap { peak_roots: 0, peak_edges: 0, scan: ScanMeter::default(), + mark: None, payload_bytes: 0, } } @@ -2185,6 +2203,7 @@ impl LuaHeap { fn unlink_at(&mut self, owner: u32, prev: Option, index: u32) { let next = self.edge_slots[index as usize].next; + self.repair_parked_cursor(owner, index, next); match prev { Some(prev) => self.edge_slots[prev as usize].next = next, None => self.slots[owner as usize].edge_head = next, @@ -2272,3 +2291,7 @@ mod budgeted_sweep; #[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/budgeted_token_scan.rs"] mod budgeted_token_scan; + +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/parked_mark.rs"] +mod parked_mark; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index 1808b4c..9bb8954 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -1,18 +1,30 @@ -//! Pausable mark. A session holds the heap borrow until it is dropped or swept. +//! Pausable mark. Progress lives in [`MarkState`]. One stepper drains it. +//! +//! A long-borrow session holds the heap until it is dropped or swept. The +//! parked driver stores that same state on the heap between pulses, so a +//! restricted edit can run without handing out `&mut LuaHeap`. Done is not +//! left for the caller: the driver sweeps in that same window and returns +//! only a report. Drop and cancel clear the saved state and do not sweep. //! //! A pulse spends a caller budget on these units, each checked before it runs: //! one slot reset, one mode-edge open, one mode-string byte (including a NUL), //! one mode-cache initialization, one root slot, one reached owner's outgoing //! head, or one outgoing edge or gap. Target checks and the metatable check //! ride with the edge or the owner head. A zero budget does not read the graph. +//! +//! Reset and mode pulses still spend that budget. They do not open mutation. +//! Roots and Gray open only an ordinary field delete, or an ordinary field +//! write on an owner that is not yet marked. Allocation, rollback, metatable +//! and `__mode` writes, root edits, and token edits stay closed. A refused +//! edit returns before it changes the heap. use super::{ - CollectReport, EdgeKey, EdgeValue, HandleKind, LuaHeap, MarkSnapshot, SlotState, WeakMode, + CollectReport, EdgeKey, EdgeValue, HandleKind, HeapError, HeapStats, LuaHeap, MarkSnapshot, + SlotState, TableRef, WeakMode, }; use vm::Value; -pub(super) struct MarkSession<'a> { - heap: &'a mut LuaHeap, +pub(super) struct MarkState { phase: MarkPhase, gray: Vec, modes: Option>, @@ -22,8 +34,8 @@ pub(super) struct MarkSession<'a> { byte_at: usize, pending_mode: WeakMode, init_at: usize, - owner: Option, - cursor: Option, + pub(super) owner: Option, + pub(super) cursor: Option, owner_kind: HandleKind, owner_mode: WeakMode, } @@ -44,10 +56,40 @@ pub(super) struct MarkView { pub(super) meter: super::ScanMeter, } -impl<'a> MarkSession<'a> { - pub(super) fn start(heap: &'a mut LuaHeap) -> Self { +/// Owner and record the gray scan will charge next. The cursor is the record +/// index, not a field id. +#[derive(Clone, Copy, Debug)] +pub(super) struct PendingScan { + pub(super) owner: u32, + pub(super) cursor: u32, +} + +/// Operations the pause window does not open. The driver refuses each one +/// before calling the heap method that would apply it. +pub(super) enum PausedOp { + Alloc, + Rollback, + Metatable, + Mode, + Root, + Token, +} + +pub(super) struct MarkSession<'a> { + heap: &'a mut LuaHeap, +} + +/// Exclusive pure-heap mark. The caller does not receive `&mut LuaHeap` until +/// this driver is dropped, cancelled, or has swept a finished mark. +pub(super) struct ParkedMark<'a> { + heap: &'a mut LuaHeap, + done: Option, + swept: bool, +} + +impl MarkState { + fn new() -> Self { Self { - heap, phase: MarkPhase::Start, gray: Vec::new(), modes: None, @@ -64,336 +106,606 @@ impl<'a> MarkSession<'a> { } } + fn mutation_open(&self) -> bool { + matches!(self.phase, MarkPhase::Roots | MarkPhase::Gray) + } + + fn phase_name(&self) -> &'static str { + match self.phase { + MarkPhase::Start => "start", + MarkPhase::Reset => "reset", + MarkPhase::ModeOpen => "mode-open", + MarkPhase::ModeBytes => "mode-bytes", + MarkPhase::ModeInit => "mode-init", + MarkPhase::Roots => "roots", + MarkPhase::Gray => "gray", + MarkPhase::Done => "done", + } + } +} + +impl<'a> MarkSession<'a> { + pub(super) fn start(heap: &'a mut LuaHeap) -> Self { + debug_assert!(heap.mark.is_none(), "a mark is already parked"); + heap.mark = Some(MarkState::new()); + Self { heap } + } + pub(super) fn meter(&self) -> super::ScanMeter { self.heap.scan } pub(super) fn pulse(&mut self, budget: u64) -> MarkView { - if budget == 0 || matches!(self.phase, MarkPhase::Done) { - return self.view(); - } - if matches!(self.phase, MarkPhase::Start) { - self.heap.scan.mark_passes += 1; - self.phase = MarkPhase::Reset; - } - let mut left = budget; - let mut spins = 0u32; - while left > 0 && !matches!(self.phase, MarkPhase::Done) { - if self.step() { - left -= 1; - spins = 0; - } else { - spins += 1; - debug_assert!(spins <= 4, "mark phase did not advance"); - } - } - self.view() + let mut state = self.heap.mark.take().expect("mark state"); + let view = pulse_state(self.heap, &mut state, budget); + self.heap.mark = Some(state); + view } pub(super) fn drain(&mut self) { - while !matches!(self.phase, MarkPhase::Done) { + while self + .heap + .mark + .as_ref() + .is_some_and(|state| !matches!(state.phase, MarkPhase::Done)) + { self.pulse(64); } } pub(super) fn sweep(self) -> CollectReport { - let MarkSession { - heap, modes, phase, .. - } = self; + let state = self.heap.mark.take().expect("mark state"); assert!( - matches!(phase, MarkPhase::Done), + matches!(state.phase, MarkPhase::Done), "sweep needs a finished mark" ); - heap.sweep_marked(MarkSnapshot { modes }) + self.heap.sweep_marked(MarkSnapshot { modes: state.modes }) } - fn view(&self) -> MarkView { - MarkView { - finished: matches!(self.phase, MarkPhase::Done), - meter: self.heap.scan, - } + pub(super) fn into_snapshot(self) -> MarkSnapshot { + let state = self.heap.mark.take().expect("drained mark"); + assert!( + matches!(state.phase, MarkPhase::Done), + "drain needs a finished mark" + ); + MarkSnapshot { modes: state.modes } } +} - fn step(&mut self) -> bool { - match self.phase { - MarkPhase::Start => false, - MarkPhase::Reset => self.step_reset(), - MarkPhase::ModeOpen => self.step_mode_open(), - MarkPhase::ModeBytes => self.step_mode_byte(), - MarkPhase::ModeInit => self.step_mode_init(), - MarkPhase::Roots => self.step_root(), - MarkPhase::Gray => self.step_gray(), - MarkPhase::Done => false, - } +impl Drop for MarkSession<'_> { + fn drop(&mut self) { + self.heap.mark = None; } +} - fn step_reset(&mut self) -> bool { - if self.index >= self.heap.slots.len() { - self.phase = MarkPhase::Roots; - self.index = 0; - return false; +impl<'a> ParkedMark<'a> { + pub(super) fn start(heap: &'a mut LuaHeap) -> Result { + if heap.mark.is_some() { + return Err(HeapError::MarkActive); } - let index = self.index; - if let SlotState::Live { marked } = &mut self.heap.slots[index].state { - *marked = false; + heap.mark = Some(MarkState::new()); + Ok(Self { + heap, + done: None, + swept: false, + }) + } + + pub(super) fn meter(&self) -> super::ScanMeter { + self.heap.scan + } + + pub(super) fn stats(&self) -> HeapStats { + self.heap.stats() + } + + pub(super) fn logical_bytes(&self) -> u64 { + self.heap.logical_bytes() + } + + pub(super) fn pulse(&mut self, budget: u64) -> MarkView { + if self.done.is_some() { + return self.finished_view(); } - self.heap.scan.node_slot_visits += 1; - self.heap.scan.weak_mode_slot_checks += 1; - let mode_edge = self.heap.slots[index].mode_edge; - let is_table = self.heap.slots[index].kind == HandleKind::Table; - if self.heap.metatable_edges > 0 && is_table && mode_edge.is_some() { - self.mode_edge = mode_edge; - self.mode_owner = index; - self.byte_at = 0; - self.pending_mode = WeakMode::default(); - self.phase = MarkPhase::ModeOpen; + let mut state = self.heap.mark.take().expect("parked mark"); + let view = pulse_state(self.heap, &mut state, budget); + if matches!(state.phase, MarkPhase::Done) { + self.done = Some(MarkSnapshot { + modes: state.modes.take(), + }); } else { - self.index += 1; + self.heap.mark = Some(state); } - true + view } - fn step_mode_open(&mut self) -> bool { - let edge_index = self.mode_edge.expect("mode open has an edge"); - self.heap.scan.weak_mode_edge_checks += 1; - if self.mode_string_len(edge_index).is_some() { - self.phase = MarkPhase::ModeBytes; - } else { - self.advance_after_mode(); - } - true + pub(super) fn pending(&self) -> Option { + let state = self.heap.mark.as_ref()?; + Some(PendingScan { + owner: state.owner?, + cursor: state.cursor?, + }) } - fn step_mode_byte(&mut self) -> bool { - let edge_index = self.mode_edge.expect("mode byte has an edge"); - let at = self.byte_at; - let Some(byte) = self.mode_string_byte(edge_index, at) else { - self.finish_mode_parse(); - return false; - }; - self.heap.scan.weak_mode_bytes += 1; - self.byte_at = at + 1; - match byte { - b'k' => self.pending_mode.keys = true, - b'v' => self.pending_mode.values = true, - 0 => { - self.finish_mode_parse(); - return true; - } - _ => {} - } - let len = self.mode_string_len(edge_index).unwrap_or(0); - if self.byte_at >= len { - self.finish_mode_parse(); - } - true + pub(super) fn marked(&self, table: TableRef) -> bool { + self.heap + .slots + .get(table.slot() as usize) + .is_some_and(|slot| { + slot.generation == table.generation() + && slot.kind == HandleKind::Table + && matches!(slot.state, SlotState::Live { marked: true }) + }) } - fn finish_mode_parse(&mut self) { - let parsed = self.pending_mode; - if parsed.keys || parsed.values { - if self.modes.is_none() { - self.init_at = 0; - self.phase = MarkPhase::ModeInit; - return; - } - self.store_mode(parsed); + pub(super) fn phase_name(&self) -> &'static str { + if self.done.is_some() { + return "done"; } - self.advance_after_mode(); + self.heap + .mark + .as_ref() + .map(MarkState::phase_name) + .unwrap_or("absent") + } + + pub(super) fn mutation_open(&self) -> bool { + self.heap + .mark + .as_ref() + .is_some_and(MarkState::mutation_open) + } + + pub(super) fn write_allowed(&self, owner: TableRef) -> bool { + self.mutation_open() && self.heap.alive(owner) && !self.marked(owner) + } + + pub(super) fn field_index(&self, owner: TableRef, key: u32) -> Option { + self.heap.find_key(owner.slot(), &EdgeKey::Field(key)) + } + + pub(super) fn edge(&self, from: TableRef, key: u32) -> Result, HeapError> { + self.heap.edge(from, key) + } + + pub(super) fn metatable(&self, owner: TableRef) -> Result, HeapError> { + self.heap.metatable(owner) + } + + pub(super) fn field_scalar(&self, from: TableRef, key: u32) -> Result { + self.heap + .stored_value(from, |stored| stored == &EdgeKey::Field(key)) } - fn step_mode_init(&mut self) -> bool { - let slot_count = self.heap.slots.len(); - if self.modes.is_none() { - self.modes = Some(Vec::with_capacity(slot_count)); + pub(super) fn delete_field(&mut self, from: TableRef, key: u32) -> Result<(), HeapError> { + self.gate_field(from, key)?; + let key = EdgeKey::Field(key); + self.heap.clear_edge(from, &key); + Ok(()) + } + + pub(super) fn write_field( + &mut self, + from: TableRef, + key: u32, + to: TableRef, + ) -> Result<(), HeapError> { + self.gate_field(from, key)?; + self.heap.require_live(to)?; + if self.marked(from) { + return Err(HeapError::MarkDenied); } - let modes = self.modes.as_mut().expect("mode init has a cache"); - modes.push(WeakMode::default()); - self.heap.scan.scratch.weak_modes_inited += 1; - self.init_at += 1; - if self.init_at == slot_count { - let parsed = self.pending_mode; - self.store_mode(parsed); - self.advance_after_mode(); + self.heap.set_edge(from, key, to)?; + self.heap.scan.parked_edge_writes += 1; + Ok(()) + } + + /// Private collect while this driver holds the heap. It does not sweep. + pub(super) fn ordinary_collect(&mut self) -> Result { + Err(HeapError::MarkActive) + } + + /// A second start while saved progress is still on this heap. + pub(super) fn restart(&mut self) -> Result<(), HeapError> { + if self.heap.mark.is_some() || self.done.is_some() { + return Err(HeapError::MarkActive); } - true + Err(HeapError::MarkActive) } - fn store_mode(&mut self, parsed: WeakMode) { - let modes = self.modes.as_mut().expect("mode cache"); - modes[self.mode_owner] = parsed; + pub(super) fn deny(&mut self, op: PausedOp) -> Result<(), HeapError> { + match op { + PausedOp::Alloc + | PausedOp::Rollback + | PausedOp::Metatable + | PausedOp::Mode + | PausedOp::Root + | PausedOp::Token => Err(HeapError::MarkDenied), + } } - fn advance_after_mode(&mut self) { - self.mode_edge = None; - self.index += 1; - self.phase = MarkPhase::Reset; + pub(super) fn cancel(mut self) { + self.heap.mark = None; + self.done = None; } - fn step_root(&mut self) -> bool { - if self.index >= self.heap.roots.len() { - self.phase = MarkPhase::Gray; - return false; + /// Sweep a finished mark in this same window. An unfinished mark is not a + /// snapshot and is not swept. + pub(super) fn complete(&mut self) -> Result { + if self.swept { + return Err(HeapError::MarkDenied); } - let index = self.index; - self.index += 1; - self.heap.scan.root_slot_visits += 1; - let Some(rooted) = self.heap.roots[index] else { - return true; + let Some(modes) = self.done.take() else { + return Err(HeapError::MarkDenied); }; - self.heap.scan.node_slot_visits += 1; - if self.heap.rooted_alive(rooted) { - self.heap.scan.node_slot_visits += 1; - let slot = rooted.slot(); - if self.heap.mark_new(slot) { - self.gray.push(slot); - } + self.heap.mark = None; + self.swept = true; + Ok(self.heap.sweep_marked(modes)) + } + + fn finished_view(&self) -> MarkView { + MarkView { + finished: true, + meter: self.heap.scan, } - true } - fn step_gray(&mut self) -> bool { - if self.owner.is_some() { - if self.cursor.is_some() { - return self.charge_edge(); - } - self.owner = None; - return false; + fn gate_field(&self, from: TableRef, key: u32) -> Result<(), HeapError> { + let state = self.heap.mark.as_ref().ok_or(HeapError::MarkDenied)?; + if !state.mutation_open() { + return Err(HeapError::MarkDenied); } - self.begin_owner() + if key == LuaHeap::MODE_FIELD { + return Err(HeapError::MarkDenied); + } + self.heap.require_live(from)?; + Ok(()) } +} - fn begin_owner(&mut self) -> bool { - let Some(slot) = self.gray.pop() else { - self.phase = MarkPhase::Done; - return false; - }; - let kind = self.heap.slots[slot as usize].kind; - let mode = if kind == HandleKind::Table && self.heap.metatable_edges > 0 { - self.owner_mode(slot) +impl Drop for ParkedMark<'_> { + fn drop(&mut self) { + self.heap.mark = None; + } +} + +fn pulse_state(heap: &mut LuaHeap, state: &mut MarkState, budget: u64) -> MarkView { + if budget == 0 || matches!(state.phase, MarkPhase::Done) { + return view(heap, state); + } + if matches!(state.phase, MarkPhase::Start) { + heap.scan.mark_passes += 1; + state.phase = MarkPhase::Reset; + } + let mut left = budget; + let mut spins = 0u32; + while left > 0 && !matches!(state.phase, MarkPhase::Done) { + if step(heap, state) { + left -= 1; + spins = 0; } else { - WeakMode::default() - }; - self.heap.scan.owner_head_checks += 1; - self.cursor = self.heap.slots[slot as usize].edge_head; - self.owner = Some(slot); - self.owner_kind = kind; - self.owner_mode = mode; - true - } - - fn charge_edge(&mut self) -> bool { - let cursor = self.cursor.expect("edge unit has a cursor"); - let next = self.heap.edge_slots[cursor as usize].next; - self.cursor = next; - let gap = self.heap.edge_slots[cursor as usize] - .edge - .as_ref() - .is_some_and(|edge| edge.value.is_cursor_gap()); - if gap { - self.heap.scan.outgoing_gap_checks += 1; + spins += 1; + debug_assert!(spins <= 4, "mark phase did not advance"); + } + } + view(heap, state) +} + +fn view(heap: &LuaHeap, state: &MarkState) -> MarkView { + MarkView { + finished: matches!(state.phase, MarkPhase::Done), + meter: heap.scan, + } +} + +fn step(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + match state.phase { + MarkPhase::Start => false, + MarkPhase::Reset => step_reset(heap, state), + MarkPhase::ModeOpen => step_mode_open(heap, state), + MarkPhase::ModeBytes => step_mode_byte(heap, state), + MarkPhase::ModeInit => step_mode_init(heap, state), + MarkPhase::Roots => step_root(heap, state), + MarkPhase::Gray => step_gray(heap, state), + MarkPhase::Done => false, + } +} + +fn step_reset(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + if state.index >= heap.slots.len() { + state.phase = MarkPhase::Roots; + state.index = 0; + return false; + } + let index = state.index; + if let SlotState::Live { marked } = &mut heap.slots[index].state { + *marked = false; + } + heap.scan.node_slot_visits += 1; + heap.scan.weak_mode_slot_checks += 1; + let mode_edge = heap.slots[index].mode_edge; + let is_table = heap.slots[index].kind == HandleKind::Table; + if heap.metatable_edges > 0 && is_table && mode_edge.is_some() { + state.mode_edge = mode_edge; + state.mode_owner = index; + state.byte_at = 0; + state.pending_mode = WeakMode::default(); + state.phase = MarkPhase::ModeOpen; + } else { + state.index += 1; + } + true +} + +fn step_mode_open(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let edge_index = state.mode_edge.expect("mode open has an edge"); + heap.scan.weak_mode_edge_checks += 1; + if mode_string_len(heap, edge_index).is_some() { + state.phase = MarkPhase::ModeBytes; + } else { + advance_after_mode(state); + } + true +} + +fn step_mode_byte(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let edge_index = state.mode_edge.expect("mode byte has an edge"); + let at = state.byte_at; + let Some(byte) = mode_string_byte(heap, edge_index, at) else { + finish_mode_parse(state); + return false; + }; + heap.scan.weak_mode_bytes += 1; + state.byte_at = at + 1; + match byte { + b'k' => state.pending_mode.keys = true, + b'v' => state.pending_mode.values = true, + 0 => { + finish_mode_parse(state); return true; } - self.heap.scan.outgoing_edge_checks += 1; - self.follow_edge_ends(cursor); - true - } - - fn follow_edge_ends(&mut self, cursor: u32) { - let (object_key, value_target) = { - let edge = self.heap.edge_slots[cursor as usize] - .edge - .as_ref() - .expect("owner chain holds an occupied record"); - let object_key = match &edge.key { - EdgeKey::Object { - slot, - generation, - kind, - } => Some((*slot, *generation, *kind)), - EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => None, - }; - let value_target = match &edge.value { - EdgeValue::Table { slot, generation } => { - Some((*slot, *generation, HandleKind::Table)) - } - EdgeValue::Closure { slot, generation } => { - Some((*slot, *generation, HandleKind::Closure)) - } - EdgeValue::Upvalue { slot, generation } => { - Some((*slot, *generation, HandleKind::Upvalue)) - } - EdgeValue::Scalar(_) => None, - }; - (object_key, value_target) - }; - let from_table = self.owner_kind == HandleKind::Table; - if from_table - && !self.owner_mode.keys - && let Some((slot, generation, kind)) = object_key - { - let _matched = self.follow_one(slot, generation, kind); + _ => {} + } + let len = mode_string_len(heap, edge_index).unwrap_or(0); + if state.byte_at >= len { + finish_mode_parse(state); + } + true +} + +fn finish_mode_parse(state: &mut MarkState) { + let parsed = state.pending_mode; + if parsed.keys || parsed.values { + if state.modes.is_none() { + state.init_at = 0; + state.phase = MarkPhase::ModeInit; + return; } - // A table entry follows that table's weak mode. A closure or cell - // link is not a table entry, so it stays strong. - let strong_value = !from_table || !self.owner_mode.values; - if strong_value && let Some((slot, generation, kind)) = value_target { - let _matched = self.follow_one(slot, generation, kind); + store_mode(state, parsed); + } + advance_after_mode(state); +} + +fn step_mode_init(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let slot_count = heap.slots.len(); + if state.modes.is_none() { + state.modes = Some(Vec::with_capacity(slot_count)); + } + let modes = state.modes.as_mut().expect("mode init has a cache"); + modes.push(WeakMode::default()); + heap.scan.scratch.weak_modes_inited += 1; + state.init_at += 1; + if state.init_at == slot_count { + let parsed = state.pending_mode; + store_mode(state, parsed); + advance_after_mode(state); + } + true +} + +fn store_mode(state: &mut MarkState, parsed: WeakMode) { + let modes = state.modes.as_mut().expect("mode cache"); + modes[state.mode_owner] = parsed; +} + +fn advance_after_mode(state: &mut MarkState) { + state.mode_edge = None; + state.index += 1; + state.phase = MarkPhase::Reset; +} + +fn step_root(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + if state.index >= heap.roots.len() { + state.phase = MarkPhase::Gray; + return false; + } + let index = state.index; + state.index += 1; + heap.scan.root_slot_visits += 1; + let Some(rooted) = heap.roots[index] else { + return true; + }; + heap.scan.node_slot_visits += 1; + if heap.rooted_alive(rooted) { + heap.scan.node_slot_visits += 1; + let slot = rooted.slot(); + if heap.mark_new(slot) { + state.gray.push(slot); } } + true +} - fn owner_mode(&mut self, slot: u32) -> WeakMode { - let Some((to_slot, to_generation)) = self.heap.slots[slot as usize].metatable else { - return WeakMode::default(); - }; - self.heap.scan.metatable_edge_checks += 1; - if self.follow_one(to_slot, to_generation, HandleKind::Table) - && let Some(modes) = self.modes.as_ref() - { - self.heap.scan.weak_mode_lookups += 1; - return modes[to_slot as usize]; +fn step_gray(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + if state.owner.is_some() { + if state.cursor.is_some() { + return charge_edge(heap, state); } + state.owner = None; + return false; + } + begin_owner(heap, state) +} + +fn begin_owner(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let Some(slot) = state.gray.pop() else { + state.phase = MarkPhase::Done; + return false; + }; + let Some(stored) = heap.slots.get(slot as usize) else { + return false; + }; + if !matches!(stored.state, SlotState::Live { .. }) { + return false; + } + let kind = stored.kind; + let mode = if kind == HandleKind::Table && heap.metatable_edges > 0 { + owner_mode(heap, state, slot) + } else { WeakMode::default() + }; + heap.scan.owner_head_checks += 1; + state.cursor = heap.slots[slot as usize].edge_head; + state.owner = Some(slot); + state.owner_kind = kind; + state.owner_mode = mode; + true +} + +fn charge_edge(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let cursor = state.cursor.expect("edge unit has a cursor"); + let next = heap.edge_slots[cursor as usize].next; + state.cursor = next; + let gap = heap.edge_slots[cursor as usize] + .edge + .as_ref() + .is_some_and(|edge| edge.value.is_cursor_gap()); + if gap { + heap.scan.outgoing_gap_checks += 1; + return true; } + heap.scan.outgoing_edge_checks += 1; + follow_edge_ends(heap, state, cursor); + true +} - /// Same visits as the old target follow. True when the slot matches, even - /// if it was already marked. Only a newly marked slot joins the gray stack. - fn follow_one(&mut self, slot: u32, generation: u32, kind: HandleKind) -> bool { - self.heap.scan.node_slot_visits += 1; - if !self.heap.slot_matches(slot, generation, kind) { - return false; - } - self.heap.scan.node_slot_visits += 1; - if self.heap.mark_new(slot) { - self.gray.push(slot); - } - true +fn follow_edge_ends(heap: &mut LuaHeap, state: &mut MarkState, cursor: u32) { + let (object_key, value_target) = { + let edge = heap.edge_slots[cursor as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + let object_key = match &edge.key { + EdgeKey::Object { + slot, + generation, + kind, + } => Some((*slot, *generation, *kind)), + EdgeKey::Field(_) | EdgeKey::Utf8(_) | EdgeKey::Number(_) => None, + }; + let value_target = match &edge.value { + EdgeValue::Table { slot, generation } => Some((*slot, *generation, HandleKind::Table)), + EdgeValue::Closure { slot, generation } => { + Some((*slot, *generation, HandleKind::Closure)) + } + EdgeValue::Upvalue { slot, generation } => { + Some((*slot, *generation, HandleKind::Upvalue)) + } + EdgeValue::Scalar(_) => None, + }; + (object_key, value_target) + }; + let from_table = state.owner_kind == HandleKind::Table; + if from_table + && !state.owner_mode.keys + && let Some((slot, generation, kind)) = object_key + { + let _matched = follow_one(heap, state, slot, generation, kind); + } + // A table entry follows that table's weak mode. A closure or cell + // link is not a table entry, so it stays strong. + let strong_value = !from_table || !state.owner_mode.values; + if strong_value && let Some((slot, generation, kind)) = value_target { + let _matched = follow_one(heap, state, slot, generation, kind); } +} - fn mode_string_len(&self, edge_index: u32) -> Option { - let edge = self.heap.edge_slots[edge_index as usize].edge.as_ref()?; - match &edge.value { - EdgeValue::Scalar(Value::String(mode)) => Some(mode.len()), - _ => None, - } +fn owner_mode(heap: &mut LuaHeap, state: &mut MarkState, slot: u32) -> WeakMode { + let Some(stored) = heap.slots.get(slot as usize) else { + return WeakMode::default(); + }; + let Some((to_slot, to_generation)) = stored.metatable else { + return WeakMode::default(); + }; + heap.scan.metatable_edge_checks += 1; + if follow_one(heap, state, to_slot, to_generation, HandleKind::Table) + && let Some(modes) = state.modes.as_ref() + { + heap.scan.weak_mode_lookups += 1; + return modes.get(to_slot as usize).copied().unwrap_or_default(); } + WeakMode::default() +} - fn mode_string_byte(&self, edge_index: u32, at: usize) -> Option { - let edge = self.heap.edge_slots[edge_index as usize].edge.as_ref()?; - match &edge.value { - EdgeValue::Scalar(Value::String(mode)) => mode.as_bytes().get(at).copied(), - _ => None, - } +/// Same visits as the old target follow. True when the slot matches, even +/// if it was already marked. Only a newly marked slot joins the gray stack. +fn follow_one( + heap: &mut LuaHeap, + state: &mut MarkState, + slot: u32, + generation: u32, + kind: HandleKind, +) -> bool { + heap.scan.node_slot_visits += 1; + if !heap.slot_matches(slot, generation, kind) { + return false; + } + heap.scan.node_slot_visits += 1; + if heap.mark_new(slot) { + state.gray.push(slot); + } + true +} + +fn mode_string_len(heap: &LuaHeap, edge_index: u32) -> Option { + let edge = heap.edge_slots[edge_index as usize].edge.as_ref()?; + match &edge.value { + EdgeValue::Scalar(Value::String(mode)) => Some(mode.len()), + _ => None, + } +} + +fn mode_string_byte(heap: &LuaHeap, edge_index: u32, at: usize) -> Option { + let edge = heap.edge_slots[edge_index as usize].edge.as_ref()?; + match &edge.value { + EdgeValue::Scalar(Value::String(mode)) => mode.as_bytes().get(at).copied(), + _ => None, } } impl LuaHeap { + /// Advances a parked gray cursor when `unlink_at` removes its record. + /// One field compare. No chain, root, or slot walk. + pub(super) fn repair_parked_cursor(&mut self, owner: u32, index: u32, next: Option) { + let Some(state) = self.mark.as_mut() else { + return; + }; + if state.owner != Some(owner) || state.cursor != Some(index) { + return; + } + if next.is_some() { + state.cursor = next; + } else { + state.owner = None; + state.cursor = None; + } + self.scan.parked_cursor_repairs += 1; + } + pub(super) fn drain_mark(&mut self) -> MarkSnapshot { let mut session = MarkSession::start(self); session.drain(); - MarkSnapshot { - modes: session.modes.take(), - } + session.into_snapshot() } fn mark_new(&mut self, index: u32) -> bool { diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs new file mode 100644 index 0000000..b97bd42 --- /dev/null +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -0,0 +1,577 @@ +//! Parked mark on a private heap. The driver keeps the only `&mut LuaHeap`. +//! +//! A pulse of one stops on a real pending record, not on a guessed step count. +//! The bound below is only a harness limit. Sweep stays outside the pulse. + +use super::{ + HeapError, HeapLimits, HeapStats, LuaHeap, ParkedMark, PausedOp, PendingScan, ScanMeter, + TableRef, +}; +use vm::Value; + +const KEY_X: u32 = 1; +const KEY_Y: u32 = 2; +const KEY_Z: u32 = 3; +const KEY_W: u32 = 1; +const HARNESS_BOUND: u32 = 64; + +fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { + HeapLimits { + nodes, + roots, + edges, + max_generation: 8, + } +} + +struct Chain { + a: TableRef, + x: TableRef, + y: TableRef, + z: TableRef, + d: TableRef, + w: TableRef, +} + +fn chain(heap: &mut LuaHeap) -> Chain { + let a = heap.alloc().expect("A"); + let x = heap.alloc().expect("X"); + let y = heap.alloc().expect("Y"); + let z = heap.alloc().expect("Z"); + let d = heap.alloc().expect("D"); + let w = heap.alloc().expect("W"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, a).expect("root A"); + heap.set_edge(a, KEY_X, x).expect("A.X"); + heap.set_edge(a, KEY_Y, y).expect("A.Y"); + heap.set_edge(a, KEY_Z, z).expect("A.Z"); + Chain { a, x, y, z, d, w } +} + +fn pause_at(parked: &mut ParkedMark<'_>, owner: u32, cursor: u32) -> PendingScan { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!( + !view.finished, + "mark finished before owner {owner} record {cursor} was pending" + ); + assert_eq!(view.meter.sweep_edge_checks, 0, "a pulse must not sweep"); + assert_eq!( + view.meter.mark_passes, 1, + "pause stays in the original pass" + ); + if let Some(pending) = parked.pending() + && pending.owner == owner + && pending.cursor == cursor + { + assert_eq!(parked.phase_name(), "gray"); + assert!(parked.mutation_open()); + return pending; + } + } + panic!("pending record {cursor} on owner {owner} was not observed"); +} + +fn finish(parked: &mut ParkedMark<'_>) -> ScanMeter { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert_eq!(view.meter.sweep_edge_checks, 0, "a pulse must not sweep"); + assert_eq!(view.meter.mark_passes, 1); + if view.finished { + return view.meter; + } + } + panic!("mark did not finish within the harness bound"); +} + +fn string_bytes(value: &Value) -> Option<&[u8]> { + match value { + Value::String(text) => Some(text.as_bytes()), + _ => None, + } +} + +struct Picture { + stats: HeapStats, + meter: ScanMeter, + bytes: u64, +} + +fn picture(parked: &ParkedMark<'_>) -> Picture { + Picture { + stats: parked.stats(), + meter: parked.meter(), + bytes: parked.logical_bytes(), + } +} + +fn assert_same(before: &Picture, after: &Picture) { + assert_eq!(before.stats, after.stats, "refusal changed occupancy"); + assert_eq!(before.meter, after.meter, "refusal changed the scan meter"); + assert_eq!(before.bytes, after.bytes, "refusal changed payload"); +} + +#[test] +fn same_slot_reuse_keeps_the_owner_suffix() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let chain = chain(&mut heap); + let x_slot = chain.x.slot(); + let x_generation = chain.x.generation(); + let z_slot = chain.z.slot(); + let z_generation = chain.z.generation(); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let y_index = parked.field_index(chain.a, KEY_Y).expect("Y record"); + let z_index = parked.field_index(chain.a, KEY_Z).expect("Z record"); + let pending = pause_at(&mut parked, chain.a.slot(), y_index); + assert_eq!(pending.owner, chain.a.slot()); + assert_eq!(pending.cursor, y_index); + assert!(!parked.marked(chain.z), "Z is still ahead of the cursor"); + assert!(!parked.marked(chain.w), "W has no root"); + assert!( + parked.write_allowed(chain.d), + "D is live, unmarked, and the phase accepts a field write" + ); + assert_ne!(chain.d.slot(), chain.a.slot()); + + let before = parked.meter(); + parked.delete_field(chain.a, KEY_Y).expect("delete Y"); + parked + .write_field(chain.d, KEY_W, chain.w) + .expect("reuse the freed record"); + assert_eq!( + parked.field_index(chain.d, KEY_W), + Some(y_index), + "D must reuse Y's record, not a new slot" + ); + assert_eq!(parked.field_index(chain.a, KEY_Y), None); + assert_eq!(parked.edge(chain.a, KEY_Y).expect("Y edge"), None); + let after = parked.meter(); + assert_eq!(after.outgoing_edge_checks, before.outgoing_edge_checks); + assert_eq!(after.parked_edge_writes, before.parked_edge_writes + 1); + let pending_after = parked.pending(); + let repairs = after.parked_cursor_repairs; + + let _meter = finish(&mut parked); + let report = parked.complete().expect("sweep the finished mark"); + drop(parked); + assert!( + heap.alive(chain.z), + "Z must stay reachable from A; pending after the edit was {pending_after:?}, Y record {y_index}, Z record {z_index}, repairs {repairs}" + ); + assert!( + !heap.alive(chain.w), + "W must not be marked through the reused slot; pending after the edit was {pending_after:?}, repairs {repairs}" + ); + assert_eq!(heap.edge(chain.a, KEY_X).expect("X edge"), Some(chain.x)); + assert_eq!(chain.x.slot(), x_slot); + assert_eq!(chain.x.generation(), x_generation); + assert_eq!(heap.edge(chain.a, KEY_Z).expect("Z edge"), Some(chain.z)); + assert_eq!(chain.z.slot(), z_slot); + assert_eq!(chain.z.generation(), z_generation); + assert!(!heap.alive(chain.y)); + assert!(!heap.alive(chain.d)); + assert_eq!( + pending_after.map(|scan| (scan.owner, scan.cursor)), + Some((chain.a.slot(), z_index)), + "unlink advances A's cursor to Z" + ); + let meter = heap.take_scan_meter(); + assert_eq!(meter.mark_passes, 1, "one mark round"); + assert_eq!( + meter.parked_cursor_repairs, 1, + "the delete repairs the cursor once" + ); + assert_eq!(meter.parked_edge_writes, 1); + assert_eq!(report.live_nodes, 3, "A, X, and Z remain"); + assert_eq!(heap.stats().collections, 1); +} + +#[test] +fn delete_only_keeps_the_successor() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let chain = chain(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let y_index = parked.field_index(chain.a, KEY_Y).expect("Y record"); + let z_index = parked.field_index(chain.a, KEY_Z).expect("Z record"); + pause_at(&mut parked, chain.a.slot(), y_index); + parked.delete_field(chain.a, KEY_Y).expect("delete Y"); + assert_eq!(parked.field_index(chain.a, KEY_Y), None); + let pending_after = parked.pending(); + let repairs = parked.meter().parked_cursor_repairs; + + // Without a repair the next charge reads the freed record and hits the + // occupied-record check. That is the behavior failure, not a compile error. + let _meter = finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + heap.alive(chain.z), + "deleting Y must keep Z; pending was {pending_after:?}, Z record {z_index}, repairs {repairs}" + ); + assert_eq!(heap.edge(chain.a, KEY_X).expect("X edge"), Some(chain.x)); + assert_eq!(heap.edge(chain.a, KEY_Z).expect("Z edge"), Some(chain.z)); + assert!(!heap.alive(chain.y)); + assert!(!heap.alive(chain.w)); + assert_eq!( + pending_after.map(|scan| (scan.owner, scan.cursor)), + Some((chain.a.slot(), z_index)) + ); + let meter = heap.take_scan_meter(); + assert_eq!(meter.mark_passes, 1); + assert_eq!(meter.parked_cursor_repairs, 1); + assert_eq!(meter.parked_edge_writes, 0); + assert_eq!(heap.stats().collections, 1); +} + +#[test] +fn omitted_pause_keeps_the_pending_edge() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let chain = chain(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let y_index = parked.field_index(chain.a, KEY_Y).expect("Y record"); + pause_at(&mut parked, chain.a.slot(), y_index); + assert_eq!(parked.meter().parked_cursor_repairs, 0); + assert_eq!(parked.meter().parked_edge_writes, 0); + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert_eq!(heap.edge(chain.a, KEY_Y).expect("Y edge"), Some(chain.y)); + assert!(heap.alive(chain.y)); + assert!(heap.alive(chain.x)); + assert!(heap.alive(chain.z)); + assert!(!heap.alive(chain.d)); + assert!(!heap.alive(chain.w)); + let meter = heap.take_scan_meter(); + assert_eq!(meter.parked_cursor_repairs, 0); + assert_eq!(meter.parked_edge_writes, 0); + assert_eq!(meter.mark_passes, 1); +} + +#[test] +fn tail_slot_reuse_does_not_keep_the_new_target() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let a = heap.alloc().expect("A"); + let x = heap.alloc().expect("X"); + let y = heap.alloc().expect("Y"); + let d = heap.alloc().expect("D"); + let w = heap.alloc().expect("W"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, a).expect("root A"); + heap.set_edge(a, KEY_X, x).expect("A.X"); + heap.set_edge(a, KEY_Y, y).expect("A.Y"); + let x_slot = x.slot(); + let x_generation = x.generation(); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let y_index = parked.field_index(a, KEY_Y).expect("tail record"); + pause_at(&mut parked, a.slot(), y_index); + parked.delete_field(a, KEY_Y).expect("delete tail"); + parked + .write_field(d, KEY_W, w) + .expect("reuse the tail record"); + assert_eq!(parked.field_index(d, KEY_W), Some(y_index)); + assert_ne!(d.slot(), a.slot()); + let pending_after = parked.pending(); + let repairs = parked.meter().parked_cursor_repairs; + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + !heap.alive(w), + "a tail cursor must not follow the reused slot; pending was {pending_after:?}, repairs {repairs}" + ); + assert_eq!(heap.edge(a, KEY_X).expect("X edge"), Some(x)); + assert_eq!(x.slot(), x_slot); + assert_eq!(x.generation(), x_generation); + assert!(!heap.alive(y)); + assert!(pending_after.is_none(), "no successor ends A's scan"); + let meter = heap.take_scan_meter(); + assert_eq!(meter.parked_cursor_repairs, 1); + assert_eq!(meter.mark_passes, 1); + assert_eq!(heap.stats().collections, 1); +} + +#[test] +fn closed_phase_refuses_before_a_write() { + let mut heap = LuaHeap::new(limits(4, 2, 4)); + let owner = heap.alloc().expect("owner"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, owner).expect("root"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let idle = parked.pulse(0); + assert!(!idle.finished); + assert_eq!(idle.meter, ScanMeter::default()); + assert_eq!(parked.phase_name(), "start"); + let before = picture(&parked); + assert_eq!( + parked.delete_field(owner, KEY_X), + Err(HeapError::MarkDenied) + ); + assert_eq!( + parked.write_field(owner, KEY_X, owner), + Err(HeapError::MarkDenied) + ); + assert_same(&before, &picture(&parked)); + let step = parked.pulse(1); + assert!(!step.finished); + assert_eq!(parked.phase_name(), "reset"); + let before = picture(&parked); + assert_eq!( + parked.delete_field(owner, KEY_X), + Err(HeapError::MarkDenied) + ); + assert_same(&before, &picture(&parked)); + parked.cancel(); + + let mut heap = LuaHeap::new(limits(4, 2, 4)); + let mt = heap.alloc().expect("metatable"); + let owner = heap.alloc().expect("owner"); + let mode = "v\0".to_string(); + let frame = heap.enter_roots(2).expect("frame"); + heap.write_root(frame, 0, mt).expect("root mt"); + heap.write_root(frame, 1, owner).expect("root owner"); + heap.set_metatable(owner, Some(mt)).expect("metatable"); + heap.set_mode_scalar(mt, Value::string(mode.clone())) + .expect("mode"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let mut saw_mode = false; + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!(!view.finished); + if matches!( + parked.phase_name(), + "mode-open" | "mode-bytes" | "mode-init" + ) { + saw_mode = true; + break; + } + } + assert!(saw_mode, "a mode string must open a mode phase"); + assert!(!parked.mutation_open()); + let before = picture(&parked); + let stored = parked.field_scalar(mt, LuaHeap::MODE_FIELD).expect("mode"); + assert_eq!(string_bytes(&stored), Some(mode.as_bytes())); + let mt_ref = parked.metatable(owner).expect("mt read"); + assert_eq!( + parked.delete_field(owner, KEY_X), + Err(HeapError::MarkDenied) + ); + assert_eq!( + parked.write_field(owner, KEY_X, owner), + Err(HeapError::MarkDenied) + ); + assert_eq!(parked.deny(PausedOp::Mode), Err(HeapError::MarkDenied)); + assert_same(&before, &picture(&parked)); + let stored = parked.field_scalar(mt, LuaHeap::MODE_FIELD).expect("mode"); + assert_eq!(string_bytes(&stored), Some(mode.as_bytes())); + assert_eq!(parked.metatable(owner).expect("mt read"), mt_ref); + parked.cancel(); +} + +#[test] +fn open_phase_refuses_marked_owner_and_forbidden_ops() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let chain = chain(&mut heap); + let extra = heap.alloc().expect("extra"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let y_index = parked.field_index(chain.a, KEY_Y).expect("Y record"); + pause_at(&mut parked, chain.a.slot(), y_index); + assert!(parked.marked(chain.a)); + assert!(!parked.write_allowed(chain.a)); + let before = picture(&parked); + let y_edge = parked.edge(chain.a, KEY_Y).expect("Y edge"); + assert_eq!( + parked.write_field(chain.a, 4, extra), + Err(HeapError::MarkDenied), + "a marked owner cannot publish a new edge" + ); + assert_eq!( + parked.write_field(chain.a, LuaHeap::MODE_FIELD, extra), + Err(HeapError::MarkDenied) + ); + assert_eq!( + parked.delete_field(chain.a, LuaHeap::MODE_FIELD), + Err(HeapError::MarkDenied) + ); + for op in [ + PausedOp::Alloc, + PausedOp::Rollback, + PausedOp::Metatable, + PausedOp::Mode, + PausedOp::Root, + PausedOp::Token, + ] { + assert_eq!(parked.deny(op), Err(HeapError::MarkDenied)); + } + assert_eq!( + parked.ordinary_collect().expect_err("private collect"), + HeapError::MarkActive + ); + assert_eq!( + parked.restart().expect_err("second start"), + HeapError::MarkActive + ); + assert_same(&before, &picture(&parked)); + assert_eq!(parked.edge(chain.a, KEY_Y).expect("Y edge"), y_edge); + assert_eq!(parked.edge(chain.a, 4).expect("new edge"), None); + assert_eq!(parked.edge(extra, KEY_X).expect("extra"), None); + parked.cancel(); + assert_eq!(heap.stats().collections, 0); + assert!(heap.alive(chain.a)); + assert!(heap.alive(chain.y)); + assert!(heap.alive(extra)); +} + +#[test] +fn cancel_restarts_a_full_collect() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let chain = chain(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let y_index = parked.field_index(chain.a, KEY_Y).expect("Y record"); + pause_at(&mut parked, chain.a.slot(), y_index); + parked.cancel(); + assert_eq!(heap.stats().collections, 0); + assert!(heap.alive(chain.y), "cancel does not sweep"); + let _partial = heap.take_scan_meter(); + heap.collect(); + let meter = heap.take_scan_meter(); + assert_eq!(meter.mark_passes, 1, "the next collect starts a new pass"); + assert_eq!(meter.parked_cursor_repairs, 0); + assert_eq!(meter.parked_edge_writes, 0); + assert!(heap.alive(chain.a)); + assert!(heap.alive(chain.x)); + assert!(heap.alive(chain.y)); + assert!(heap.alive(chain.z)); + assert!(!heap.alive(chain.d)); + assert!(!heap.alive(chain.w)); + assert_eq!(heap.edge(chain.a, KEY_Y).expect("Y edge"), Some(chain.y)); + + let mut again = ParkedMark::start(&mut heap).expect("restart after cancel"); + let idle = again.pulse(0); + assert!(!idle.finished); + assert_eq!(idle.meter.mark_passes, 0); + assert_eq!(idle.meter, ScanMeter::default()); + again.cancel(); +} + +#[test] +fn zero_budget_does_not_read_or_finish() { + let mut heap = LuaHeap::new(limits(4, 2, 4)); + let owner = heap.alloc().expect("owner"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, owner).expect("root"); + heap.set_edge(owner, KEY_X, owner).expect("edge"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let idle = parked.pulse(0); + assert!(!idle.finished); + assert_eq!(idle.meter, ScanMeter::default()); + assert_eq!(parked.phase_name(), "start"); + assert!(parked.pending().is_none()); + assert_eq!(parked.complete(), Err(HeapError::MarkDenied)); + assert_eq!(parked.stats().collections, 0); + assert_eq!(parked.meter().sweep_edge_checks, 0); + parked.cancel(); +} + +#[test] +fn small_budget_stays_inside_the_pulse() { + let edges = 8u32; + let budget = 3u64; + let mut heap = LuaHeap::new(limits(2, 1, edges)); + let owner = heap.alloc().expect("owner"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, owner).expect("root"); + for key in 1..=edges { + heap.set_edge(owner, key, owner).expect("edge"); + } + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let first = parked.pulse(budget); + assert!(!first.finished, "budget {budget} must not walk the owner"); + assert!(first.meter.outgoing_edge_checks <= budget); + assert_eq!(first.meter.sweep_edge_checks, 0); + assert_eq!(parked.complete(), Err(HeapError::MarkDenied)); + assert_eq!(parked.stats().collections, 0); + let mut pulses = 0u32; + loop { + let before = parked.meter(); + let view = parked.pulse(budget); + let edge_delta = (view.meter.outgoing_edge_checks + view.meter.outgoing_gap_checks) + - (before.outgoing_edge_checks + before.outgoing_gap_checks); + assert!(edge_delta <= budget); + assert_eq!(view.meter.sweep_edge_checks, 0); + assert_eq!(view.meter.mark_passes, 1); + assert_eq!(view.meter.parked_edge_writes, 0); + assert_eq!(view.meter.parked_cursor_repairs, 0); + if view.finished { + break; + } + pulses += 1; + assert!(pulses < HARNESS_BOUND); + } + let report = parked.complete().expect("sweep after the mark"); + drop(parked); + let parked_meter = heap.take_scan_meter(); + assert_eq!(parked_meter.outgoing_edge_checks, u64::from(edges)); + assert_eq!(parked_meter.mark_passes, 1); + assert_eq!(parked_meter.parked_edge_writes, 0); + assert_eq!(parked_meter.parked_cursor_repairs, 0); + assert_eq!(report.live_nodes, 1); + + let mut twin = LuaHeap::new(limits(2, 1, edges)); + let twin_owner = twin.alloc().expect("twin"); + let frame = twin.enter_roots(1).expect("frame"); + twin.write_root(frame, 0, twin_owner).expect("root"); + for key in 1..=edges { + twin.set_edge(twin_owner, key, twin_owner).expect("edge"); + } + let twin_report = twin.collect(); + let twin_meter = twin.take_scan_meter(); + assert_eq!(parked_meter, twin_meter); + assert_eq!(report.marked_nodes, twin_report.marked_nodes); + assert_eq!(report.live_nodes, twin_report.live_nodes); +} + +#[test] +fn weak_graph_budget_one_matches_full_collect() { + fn build(heap: &mut LuaHeap) -> (TableRef, TableRef) { + let mt = heap.alloc().expect("metatable"); + let owner = heap.alloc().expect("owner"); + let orphan = heap.alloc().expect("orphan"); + let frame = heap.enter_roots(2).expect("frame"); + heap.write_root(frame, 0, mt).expect("root mt"); + heap.write_root(frame, 1, owner).expect("root owner"); + heap.set_metatable(owner, Some(mt)).expect("metatable"); + heap.set_mode_scalar(mt, Value::string("v\0".to_string())) + .expect("mode"); + heap.set_edge(owner, KEY_X, orphan).expect("weak value"); + heap.set_edge(orphan, KEY_X, orphan).expect("cycle"); + (owner, orphan) + } + + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let (owner, orphan) = build(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let mark = finish(&mut parked); + assert_eq!(mark.parked_edge_writes, 0); + assert_eq!(mark.parked_cursor_repairs, 0); + assert_eq!(mark.weak_mode_bytes, 2, "v and the NUL, not a second walk"); + let report = parked.complete().expect("sweep"); + drop(parked); + assert!(heap.alive(owner)); + assert!( + !heap.alive(orphan), + "a weak value with no other root is collected" + ); + let parked_meter = heap.take_scan_meter(); + + let mut twin = LuaHeap::new(limits(8, 4, 8)); + let (twin_owner, twin_orphan) = build(&mut twin); + let twin_report = twin.collect(); + assert!(twin.alive(twin_owner)); + assert!(!twin.alive(twin_orphan)); + assert_eq!(twin.take_scan_meter(), parked_meter); + assert_eq!(twin_report.live_nodes, report.live_nodes); + assert_eq!(twin_report.marked_nodes, report.marked_nodes); + assert_eq!(parked_meter.parked_cursor_repairs, 0); + assert_eq!(parked_meter.parked_edge_writes, 0); + assert_eq!(parked_meter.mark_passes, 1); +} From f70173eed031404e581c950b3cf4d4ca078d84bf Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 19:16:45 +0800 Subject: [PATCH 100/225] feat(lua): barrier a parked write into a scanned field or passed root A marked owner's existing ordinary field and a fixed root slot can be updated while Roots or Gray is parked. The new strong target joins the same gray queue. Weak values, new keys, and a failed root write do not. --- src/frontends/lua/heap/table.rs | 8 + src/frontends/lua/heap/table/mark.rs | 228 ++++++- tests/luajit_heap_runtime/parked_mark.rs | 824 ++++++++++++++++++++++- 3 files changed, 1047 insertions(+), 13 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index b03248b..0d1a715 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -536,6 +536,13 @@ pub struct ScanMeter { /// Parked gray cursors advanced inside `unlink_at` after it has read the /// old successor. Not a pulse unit. A full collect leaves this at zero. pub parked_cursor_repairs: u64, + /// Fixed root slots updated through `store_root` while a mark is parked. + /// Not a pulse unit. A full collect leaves this at zero. + pub parked_root_writes: u64, + /// Newly marked targets pushed to the parked gray queue by a write + /// barrier. An already-marked target does not increment this, and a weak + /// value is not pushed. Not a pulse unit. A full collect leaves this at zero. + pub parked_barrier_marks: u64, pub scratch: ScanScratch, } @@ -1789,6 +1796,7 @@ impl LuaHeap { } let index = found.start as usize + slot as usize; self.roots[index] = Some(rooted); + self.note_parked_root_store(rooted); Ok(()) } diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index 9bb8954..c057e22 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -13,14 +13,17 @@ //! ride with the edge or the owner head. A zero budget does not read the graph. //! //! Reset and mode pulses still spend that budget. They do not open mutation. -//! Roots and Gray open only an ordinary field delete, or an ordinary field -//! write on an owner that is not yet marked. Allocation, rollback, metatable -//! and `__mode` writes, root edits, and token edits stay closed. A refused -//! edit returns before it changes the heap. +//! Roots and Gray open an ordinary field delete, an ordinary field write on +//! an owner that is not yet marked, an in-place replacement of an existing +//! non-gap ordinary field on an already marked owner, and a fixed root-slot +//! update through the typed root writers. New keys, gap resurrection, +//! allocation, rollback, metatable and `__mode` writes, root-frame changes, +//! internal closure edges, and token edits stay closed. A refused edit +//! returns before it changes the heap. use super::{ - CollectReport, EdgeKey, EdgeValue, HandleKind, HeapError, HeapStats, LuaHeap, MarkSnapshot, - SlotState, TableRef, WeakMode, + ClosureRef, CollectReport, EdgeKey, EdgeValue, HandleKind, HeapError, HeapStats, LuaHeap, + MarkSnapshot, RootFrameId, Rooted, SlotState, TableRef, UpvalueRef, WeakMode, }; use vm::Value; @@ -293,13 +296,141 @@ impl<'a> ParkedMark<'a> { self.gate_field(from, key)?; self.heap.require_live(to)?; if self.marked(from) { - return Err(HeapError::MarkDenied); + return self.replace_discovered_field(from, key, to); } self.heap.set_edge(from, key, to)?; self.heap.scan.parked_edge_writes += 1; Ok(()) } + /// In-place replacement of one existing non-gap field. One key lookup. + /// A missing key or a cursor gap is refused before any record changes. + /// This does not insert, append, or reclaim another owner's gap. + fn replace_discovered_field( + &mut self, + from: TableRef, + key: u32, + to: TableRef, + ) -> Result<(), HeapError> { + let edge_key = EdgeKey::Field(key); + let Some(index) = self.heap.find_key(from.slot(), &edge_key) else { + return Err(HeapError::MarkDenied); + }; + let gap = self.heap.edge_slots[index as usize] + .edge + .as_ref() + .is_some_and(|edge| edge.value.is_cursor_gap()); + if gap { + return Err(HeapError::MarkDenied); + } + self.heap.replace_edge_value( + from.slot(), + index, + EdgeValue::Table { + slot: to.slot(), + generation: to.generation(), + }, + ); + self.heap.scan.parked_edge_writes += 1; + self.heap + .barrier_strong_field(from.slot(), to.slot(), to.generation()); + Ok(()) + } + + pub(super) fn write_table_root( + &mut self, + frame: RootFrameId, + slot: u32, + handle: TableRef, + ) -> Result<(), HeapError> { + self.gate_mutation()?; + self.heap.write_root(frame, slot, handle) + } + + pub(super) fn write_closure_root( + &mut self, + frame: RootFrameId, + slot: u32, + handle: ClosureRef, + ) -> Result<(), HeapError> { + self.gate_mutation()?; + self.heap.write_closure_root(frame, slot, handle) + } + + pub(super) fn write_upvalue_root( + &mut self, + frame: RootFrameId, + slot: u32, + handle: UpvalueRef, + ) -> Result<(), HeapError> { + self.gate_mutation()?; + self.heap.write_upvalue_root(frame, slot, handle) + } + + pub(super) fn scanning_owner(&self) -> Option { + self.heap.mark.as_ref().and_then(|state| state.owner) + } + + pub(super) fn object_index(&self, owner: TableRef, key: TableRef) -> Option { + self.heap.find_key(owner.slot(), &EdgeKey::object(key)) + } + + pub(super) fn record_is_gap(&self, index: u32) -> bool { + self.heap + .edge_slots + .get(index as usize) + .and_then(|record| record.edge.as_ref()) + .is_some_and(|edge| edge.value.is_cursor_gap()) + } + + pub(super) fn root_table( + &self, + frame: RootFrameId, + slot: u32, + ) -> Result, HeapError> { + let found = self.heap.frame(frame)?; + if slot >= found.width { + return Err(HeapError::StaleFrame); + } + match self.heap.roots[found.start as usize + slot as usize] { + Some(Rooted::Table(handle)) => Ok(Some(handle)), + Some(_) => Err(HeapError::WrongKind), + None => Ok(None), + } + } + + pub(super) fn root_closure( + &self, + frame: RootFrameId, + slot: u32, + ) -> Result, HeapError> { + let found = self.heap.frame(frame)?; + if slot >= found.width { + return Err(HeapError::StaleFrame); + } + match self.heap.roots[found.start as usize + slot as usize] { + Some(Rooted::Closure(handle)) => Ok(Some(handle)), + Some(_) => Err(HeapError::WrongKind), + None => Ok(None), + } + } + + pub(super) fn root_upvalue( + &self, + frame: RootFrameId, + slot: u32, + ) -> Result, HeapError> { + let found = self.heap.frame(frame)?; + if slot >= found.width { + return Err(HeapError::StaleFrame); + } + match self.heap.roots[found.start as usize + slot as usize] { + Some(Rooted::Upvalue(handle)) => Ok(Some(handle)), + Some(_) => Err(HeapError::WrongKind), + None => Ok(None), + } + } + /// Private collect while this driver holds the heap. It does not sweep. pub(super) fn ordinary_collect(&mut self) -> Result { Err(HeapError::MarkActive) @@ -351,16 +482,21 @@ impl<'a> ParkedMark<'a> { } fn gate_field(&self, from: TableRef, key: u32) -> Result<(), HeapError> { - let state = self.heap.mark.as_ref().ok_or(HeapError::MarkDenied)?; - if !state.mutation_open() { - return Err(HeapError::MarkDenied); - } + self.gate_mutation()?; if key == LuaHeap::MODE_FIELD { return Err(HeapError::MarkDenied); } self.heap.require_live(from)?; Ok(()) } + + fn gate_mutation(&self) -> Result<(), HeapError> { + let state = self.heap.mark.as_ref().ok_or(HeapError::MarkDenied)?; + if !state.mutation_open() { + return Err(HeapError::MarkDenied); + } + Ok(()) + } } impl Drop for ParkedMark<'_> { @@ -647,6 +783,42 @@ fn owner_mode(heap: &mut LuaHeap, state: &mut MarkState, slot: u32) -> WeakMode WeakMode::default() } +/// Counts a newly gray target. An already-marked slot does not increment. +fn enqueue_barrier_target( + heap: &mut LuaHeap, + state: &mut MarkState, + slot: u32, + generation: u32, + kind: HandleKind, +) { + let before = heap.scan.scratch.work_pushed; + let matched = follow_one(heap, state, slot, generation, kind); + if matched && heap.scan.scratch.work_pushed > before { + heap.scan.parked_barrier_marks += 1; + } +} + +/// Reads the reset-time mode cache. No metatable follow and no scan counter. +fn cached_values_weak(heap: &LuaHeap, state: &MarkState, owner: u32) -> bool { + if heap.metatable_edges == 0 { + return false; + } + let Some(stored) = heap.slots.get(owner as usize) else { + return false; + }; + if stored.kind != HandleKind::Table { + return false; + } + let Some((meta_slot, _)) = stored.metatable else { + return false; + }; + state + .modes + .as_ref() + .and_then(|modes| modes.get(meta_slot as usize)) + .is_some_and(|mode| mode.values) +} + /// Same visits as the old target follow. True when the slot matches, even /// if it was already marked. Only a newly marked slot joins the gray stack. fn follow_one( @@ -684,6 +856,40 @@ fn mode_string_byte(heap: &LuaHeap, edge_index: u32, at: usize) -> Option { } impl LuaHeap { + /// Counts a fixed root store and marks its target while mutation is open. + /// The enqueue uses the same `follow_one` path as a root visit. It does + /// not move the root cursor or the current owner cursor. + pub(super) fn note_parked_root_store(&mut self, rooted: Rooted) { + let Some(mut state) = self.mark.take() else { + return; + }; + if !state.mutation_open() { + self.mark = Some(state); + return; + } + self.scan.parked_root_writes += 1; + let (slot, generation, kind) = match rooted { + Rooted::Table(handle) => (handle.slot(), handle.generation(), HandleKind::Table), + Rooted::Closure(handle) => (handle.slot(), handle.generation(), HandleKind::Closure), + Rooted::Upvalue(handle) => (handle.slot(), handle.generation(), HandleKind::Upvalue), + }; + enqueue_barrier_target(self, &mut state, slot, generation, kind); + self.mark = Some(state); + } + + /// Marks a strong table value written into an already discovered field. + /// Weak values stay on the cached mode and are not followed. This does + /// not call `owner_mode` and does not move either cursor. + pub(super) fn barrier_strong_field(&mut self, owner: u32, slot: u32, generation: u32) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.mutation_open() && !cached_values_weak(self, &state, owner) { + enqueue_barrier_target(self, &mut state, slot, generation, HandleKind::Table); + } + self.mark = Some(state); + } + /// Advances a parked gray cursor when `unlink_at` removes its record. /// One field compare. No chain, root, or slot walk. pub(super) fn repair_parked_cursor(&mut self, owner: u32, index: u32, next: Option) { diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index b97bd42..1987d93 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -4,8 +4,8 @@ //! The bound below is only a harness limit. Sweep stays outside the pulse. use super::{ - HeapError, HeapLimits, HeapStats, LuaHeap, ParkedMark, PausedOp, PendingScan, ScanMeter, - TableRef, + HeapError, HeapLimits, HeapStats, LuaHeap, ParkedMark, PausedOp, PendingScan, RootFrameId, + ScanMeter, TableRef, }; use vm::Value; @@ -575,3 +575,823 @@ fn weak_graph_budget_one_matches_full_collect() { assert_eq!(parked_meter.parked_edge_writes, 0); assert_eq!(parked_meter.mark_passes, 1); } + +const KEY_KEPT: u32 = 1; +const KEY_REPLACED: u32 = 3; +const KEY_SUCCESSOR: u32 = 4; +const PASSED_SLOT: u32 = 1; + +#[derive(Clone, Copy)] +struct Cycle { + mt: TableRef, + watch: TableRef, + p: TableRef, + q: TableRef, + r: TableRef, + orphan: TableRef, +} + +fn plant_cycle(heap: &mut LuaHeap) -> Cycle { + let mt = heap.alloc().expect("metatable"); + let watch = heap.alloc().expect("weak watch"); + let p = heap.alloc().expect("P"); + let q = heap.alloc().expect("Q"); + let r = heap.alloc().expect("R"); + let orphan = heap.alloc().expect("orphan"); + heap.set_mode_scalar(mt, Value::string("v\0")) + .expect("weak values"); + heap.set_metatable(watch, Some(mt)) + .expect("watch metatable"); + heap.set_edge(watch, KEY_KEPT, p).expect("weak P"); + heap.set_edge(watch, KEY_REPLACED, orphan) + .expect("weak orphan"); + heap.set_edge(p, KEY_KEPT, q).expect("P to Q"); + heap.set_edge(q, KEY_KEPT, r).expect("Q to R"); + heap.set_edge(r, KEY_KEPT, p).expect("R to P"); + Cycle { + mt, + watch, + p, + q, + r, + orphan, + } +} + +fn pause_after_root_visits(parked: &mut ParkedMark<'_>, visits: u64) { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!(!view.finished, "mark finished before {visits} root visits"); + assert_eq!(view.meter.mark_passes, 1); + if parked.phase_name() == "roots" && parked.meter().root_slot_visits == visits { + return; + } + } + panic!( + "did not stop after {visits} root visits, phase {}", + parked.phase_name() + ); +} + +fn pulse_until_gray(parked: &mut ParkedMark<'_>) { + for _ in 0..HARNESS_BOUND { + if parked.phase_name() == "gray" { + return; + } + let view = parked.pulse(1); + assert!(!view.finished, "mark finished before gray"); + assert_eq!(view.meter.mark_passes, 1); + } + panic!("did not enter gray, phase {}", parked.phase_name()); +} + +fn charge_pending(parked: &mut ParkedMark<'_>) -> u32 { + let owner = parked.pending().expect("edge still pending").owner; + let view = parked.pulse(1); + assert!( + !view.finished, + "charging the last pending edge finished the mark" + ); + assert_eq!(view.meter.mark_passes, 1); + assert!(parked.pending().is_none(), "owner still has a pending edge"); + assert_eq!(parked.scanning_owner(), Some(owner)); + assert_eq!(parked.phase_name(), "gray"); + owner +} + +fn same_pending(left: Option, right: Option) -> bool { + match (left, right) { + (None, None) => true, + (Some(left), Some(right)) => left.owner == right.owner && left.cursor == right.cursor, + _ => false, + } +} + +fn assert_write_did_not_scan(before: &ScanMeter, after: &ScanMeter) { + assert_eq!(after.mark_passes, 1); + assert_eq!(after.mark_passes, before.mark_passes); + assert_eq!(after.outgoing_edge_checks, before.outgoing_edge_checks); + assert_eq!(after.outgoing_gap_checks, before.outgoing_gap_checks); + assert_eq!(after.owner_head_checks, before.owner_head_checks); + assert_eq!(after.root_slot_visits, before.root_slot_visits); + assert_eq!(after.parked_cursor_repairs, before.parked_cursor_repairs); +} + +fn assert_one_more_pulse_unit(parked: &mut ParkedMark<'_>) { + let before = parked.meter(); + let view = parked.pulse(1); + assert!(!view.finished); + assert_eq!(view.meter.mark_passes, 1); + let edges = (view.meter.outgoing_edge_checks + view.meter.outgoing_gap_checks) + - (before.outgoing_edge_checks + before.outgoing_gap_checks); + let roots = view.meter.root_slot_visits - before.root_slot_visits; + let heads = view.meter.owner_head_checks - before.owner_head_checks; + assert!( + edges + roots + heads <= 1, + "pulse(1) charged edges {edges} roots {roots} heads {heads}" + ); +} + +fn cycle_kept(heap: &LuaHeap, cycle: &Cycle) -> bool { + heap.alive(cycle.p) && heap.alive(cycle.q) && heap.alive(cycle.r) +} + +fn cycle_lost_message(heap: &LuaHeap, cycle: &Cycle, index: u32) -> String { + format!( + "record {index} stores P but the cycle was collected; P {} Q {} R {} orphan {} barrier_marks {} edge_writes {}", + heap.alive(cycle.p), + heap.alive(cycle.q), + heap.alive(cycle.r), + heap.alive(cycle.orphan), + heap.scan.parked_barrier_marks, + heap.scan.parked_edge_writes, + ) +} + +fn assert_cycle_identity(heap: &LuaHeap, cycle: &Cycle) { + assert_eq!(heap.edge(cycle.p, KEY_KEPT).expect("P to Q"), Some(cycle.q)); + assert_eq!(heap.edge(cycle.q, KEY_KEPT).expect("Q to R"), Some(cycle.r)); + assert_eq!(heap.edge(cycle.r, KEY_KEPT).expect("R to P"), Some(cycle.p)); + assert!( + !heap.alive(cycle.orphan), + "independent weak orphan is collected" + ); +} + +struct StrongOwner { + later: TableRef, + child: TableRef, + owner: TableRef, + kept: TableRef, + successor: Option, + cycle: Cycle, +} + +fn plant_strong_owner(heap: &mut LuaHeap, with_successor: bool) -> StrongOwner { + let later = heap.alloc().expect("unprocessed owner"); + let child = heap.alloc().expect("unprocessed child"); + heap.set_edge(later, KEY_KEPT, child) + .expect("unprocessed edge"); + let owner = heap.alloc().expect("owner"); + let kept = heap.alloc().expect("kept successor"); + let old = heap.alloc().expect("old value"); + heap.set_edge(owner, KEY_KEPT, kept).expect("kept field"); + heap.set_edge(owner, KEY_REPLACED, old) + .expect("field to replace"); + let successor = if with_successor { + let successor = heap.alloc().expect("pending successor"); + heap.set_edge(owner, KEY_SUCCESSOR, successor) + .expect("pending field"); + Some(successor) + } else { + None + }; + let cycle = plant_cycle(heap); + let frame = heap.enter_roots(4).expect("frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 1, owner).expect("root owner"); + heap.write_root(frame, 2, cycle.watch).expect("root watch"); + heap.write_root(frame, 3, cycle.mt).expect("root metatable"); + StrongOwner { + later, + child, + owner, + kept, + successor, + cycle, + } +} + +fn pause_on_owner_edge<'a>( + heap: &'a mut LuaHeap, + owner: TableRef, + key: u32, +) -> (ParkedMark<'a>, u32) { + let mut parked = ParkedMark::start(heap).expect("park"); + let index = parked.field_index(owner, key).expect("owner field"); + pause_at(&mut parked, owner.slot(), index); + (parked, index) +} + +#[test] +fn barrier_black_owner_keeps_the_cycle_until_release() { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let graph = plant_strong_owner(&mut heap, false); + let (mut parked, index) = pause_on_owner_edge(&mut heap, graph.owner, KEY_REPLACED); + let scanning = charge_pending(&mut parked); + assert_eq!(scanning, graph.owner.slot()); + assert!(parked.marked(graph.owner), "black owner is already marked"); + assert!( + !parked.marked(graph.child), + "the unprocessed child is not marked by setup" + ); + assert!(!parked.marked(graph.cycle.p), "P is only weakly reachable"); + let pending = parked.pending(); + let before = parked.meter(); + parked + .write_field(graph.owner, KEY_REPLACED, graph.cycle.p) + .expect("in-place replace on a black owner"); + assert_eq!(parked.field_index(graph.owner, KEY_REPLACED), Some(index)); + assert_eq!( + parked.edge(graph.owner, KEY_REPLACED).expect("replaced"), + Some(graph.cycle.p) + ); + assert_eq!( + parked + .edge(graph.owner, KEY_KEPT) + .expect("original successor"), + Some(graph.kept) + ); + assert!( + same_pending(parked.pending(), pending), + "the owner edge cursor moved" + ); + assert_eq!(parked.scanning_owner(), Some(graph.owner.slot())); + assert_eq!( + parked.meter().parked_edge_writes, + before.parked_edge_writes + 1 + ); + assert_write_did_not_scan(&before, &parked.meter()); + assert!( + !parked.marked(graph.child), + "the write marked an unprocessed child" + ); + assert_one_more_pulse_unit(&mut parked); + let view = finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!(heap.alive(graph.owner) && heap.alive(graph.kept) && heap.alive(graph.child)); + assert!( + cycle_kept(&heap, &graph.cycle) && heap.scan.parked_barrier_marks == 1, + "{}", + cycle_lost_message(&heap, &graph.cycle, index) + ); + assert_cycle_identity(&heap, &graph.cycle); + assert_eq!(view.mark_passes, 1); + assert_eq!(heap.scan.mark_passes, 1); + + heap.clear_edge(graph.owner, &super::EdgeKey::Field(KEY_REPLACED)); + heap.collect(); + assert!( + !heap.alive(graph.cycle.p) && !heap.alive(graph.cycle.q) && !heap.alive(graph.cycle.r), + "clearing the replaced field did not release the cycle" + ); + assert!(heap.alive(graph.owner) && heap.alive(graph.kept)); +} + +#[test] +fn barrier_gray_owner_keeps_the_cycle_and_the_pending_successor() { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let graph = plant_strong_owner(&mut heap, true); + let successor = graph.successor.expect("pending successor"); + let (mut parked, index) = pause_on_owner_edge(&mut heap, graph.owner, KEY_SUCCESSOR); + assert_eq!(parked.phase_name(), "gray"); + assert!(parked.marked(graph.owner)); + assert!(!parked.marked(graph.cycle.p)); + assert!( + !parked.marked(successor), + "the pending target is not marked yet" + ); + let pending = parked.pending(); + let before = parked.meter(); + parked + .write_field(graph.owner, KEY_REPLACED, graph.cycle.p) + .expect("in-place replace on the current gray owner"); + let replaced = parked + .field_index(graph.owner, KEY_REPLACED) + .expect("replaced record"); + assert_ne!( + Some(replaced), + pending.map(|cursor| cursor.cursor), + "the replace reused the pending successor record" + ); + assert!( + same_pending(parked.pending(), pending), + "the owner edge cursor moved" + ); + assert_eq!(parked.scanning_owner(), Some(graph.owner.slot())); + assert_eq!( + parked + .edge(graph.owner, KEY_SUCCESSOR) + .expect("pending edge"), + Some(successor) + ); + assert_eq!( + parked + .edge(graph.owner, KEY_KEPT) + .expect("original successor"), + Some(graph.kept) + ); + assert_eq!( + parked.meter().parked_edge_writes, + before.parked_edge_writes + 1 + ); + assert_write_did_not_scan(&before, &parked.meter()); + assert!( + !parked.marked(successor), + "the write marked the pending successor" + ); + assert_one_more_pulse_unit(&mut parked); + let view = finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert_eq!( + heap.edge(graph.owner, KEY_SUCCESSOR).expect("successor"), + Some(successor) + ); + assert!(heap.alive(successor) && heap.alive(graph.kept)); + assert!( + cycle_kept(&heap, &graph.cycle) && heap.scan.parked_barrier_marks == 1, + "{}", + cycle_lost_message(&heap, &graph.cycle, index) + ); + assert_cycle_identity(&heap, &graph.cycle); + assert_eq!(view.mark_passes, 1); + assert_eq!(heap.scan.mark_passes, 1); +} + +#[test] +fn barrier_omitted_write_collects_the_shared_cycle() { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let graph = plant_strong_owner(&mut heap, false); + let (mut parked, _) = pause_on_owner_edge(&mut heap, graph.owner, KEY_REPLACED); + charge_pending(&mut parked); + assert_eq!(parked.meter().parked_edge_writes, 0); + assert_eq!(parked.meter().parked_barrier_marks, 0); + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + !cycle_kept(&heap, &graph.cycle), + "omitting the write kept the weakly held cycle" + ); + assert!(!heap.alive(graph.cycle.orphan)); + assert_eq!(heap.scan.parked_barrier_marks, 0); + assert_eq!(heap.scan.parked_edge_writes, 0); + assert_eq!(heap.scan.mark_passes, 1); +} + +#[test] +fn barrier_weak_owner_replace_does_not_keep_the_cycle() { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let owner = heap.alloc().expect("weak owner"); + let old = heap.alloc().expect("old"); + let successor = heap.alloc().expect("successor"); + let cycle = plant_cycle(&mut heap); + heap.set_metatable(owner, Some(cycle.mt)) + .expect("weak owner"); + heap.set_edge(owner, KEY_REPLACED, old).expect("weak field"); + heap.set_edge(owner, KEY_SUCCESSOR, successor) + .expect("weak successor"); + let frame = heap.enter_roots(4).expect("frame"); + heap.write_root(frame, 0, owner).expect("root owner"); + heap.write_root(frame, 1, cycle.watch).expect("root watch"); + heap.write_root(frame, 2, cycle.mt).expect("root metatable"); + heap.write_root(frame, 3, successor) + .expect("keep the successor readable"); + let (mut parked, index) = pause_on_owner_edge(&mut heap, owner, KEY_SUCCESSOR); + let pending = parked.pending(); + parked + .write_field(owner, KEY_REPLACED, cycle.p) + .expect("in-place replace on a weak owner"); + assert_eq!( + parked.edge(owner, KEY_REPLACED).expect("replaced"), + Some(cycle.p) + ); + assert_eq!( + parked + .edge(owner, KEY_SUCCESSOR) + .expect("successor still readable"), + Some(successor) + ); + assert!( + same_pending(parked.pending(), pending), + "the owner edge cursor moved" + ); + let replaced = parked + .field_index(owner, KEY_REPLACED) + .expect("replaced record"); + assert_ne!(replaced, index, "the replace reused the pending record"); + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + !cycle_kept(&heap, &cycle), + "a weak-value replace kept the cycle at record {index}" + ); + assert!(!heap.alive(cycle.orphan)); + assert!(heap.alive(owner) && heap.alive(successor)); + assert_eq!(heap.scan.parked_barrier_marks, 0); + assert_eq!(heap.scan.parked_edge_writes, 1); + assert_eq!(heap.scan.mark_passes, 1); +} + +#[test] +fn barrier_already_marked_target_is_not_enqueued_again() { + fn run(write: bool) -> (u64, u64, u64) { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let graph = plant_strong_owner(&mut heap, false); + let (mut parked, _) = pause_on_owner_edge(&mut heap, graph.owner, KEY_REPLACED); + charge_pending(&mut parked); + assert!( + parked.marked(graph.later), + "Later was rooted before the write" + ); + let before = parked.meter(); + if write { + parked + .write_field(graph.owner, KEY_REPLACED, graph.later) + .expect("replace with an already marked target"); + assert_eq!( + parked.meter().scratch.work_pushed, + before.scratch.work_pushed + ); + assert_eq!( + parked.meter().parked_barrier_marks, + before.parked_barrier_marks + ); + } + finish(&mut parked); + let meter = parked.meter(); + parked.cancel(); + ( + meter.outgoing_edge_checks, + meter.owner_head_checks, + meter.scratch.work_pushed, + ) + } + + let written = run(true); + let omitted = run(false); + assert_eq!( + written.0, omitted.0, + "an already marked target was scanned again" + ); + assert_eq!( + written.1, omitted.1, + "an already marked target opened another owner" + ); + assert_eq!( + written.2, omitted.2, + "an already marked target was queued again" + ); +} + +#[test] +fn barrier_full_edges_replace_leaves_the_other_gap() { + let mut heap = LuaHeap::new(limits(8, 8, 3)); + let mt = heap.alloc().expect("metatable"); + let gap_owner = heap.alloc().expect("gap owner"); + let key_obj = heap.alloc().expect("object key"); + let dead = heap.alloc().expect("dead value"); + let owner = heap.alloc().expect("owner"); + let old = heap.alloc().expect("old value"); + heap.set_mode_scalar(mt, Value::string("v\0")) + .expect("weak values"); + heap.set_metatable(gap_owner, Some(mt)) + .expect("gap metatable"); + heap.set_object_edge(gap_owner, key_obj, dead) + .expect("object edge"); + heap.set_edge(owner, KEY_REPLACED, old).expect("full field"); + let frame = heap.enter_roots(4).expect("frame"); + heap.write_root(frame, 0, mt).expect("root metatable"); + heap.write_root(frame, 1, gap_owner) + .expect("root gap owner"); + heap.write_root(frame, 2, key_obj).expect("root key"); + heap.write_root(frame, 3, owner).expect("root owner"); + heap.collect(); + assert!(!heap.alive(dead)); + assert!(heap.alive(gap_owner) && heap.alive(key_obj) && heap.alive(owner)); + assert_eq!( + heap.stats().edge_slots, + 3, + "mode, gap, and field fill the edge cap" + ); + let _ = heap.take_scan_meter(); + let target = heap.alloc().expect("replacement"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let field = parked + .field_index(owner, KEY_REPLACED) + .expect("field at the cap"); + let gap = parked + .object_index(gap_owner, key_obj) + .expect("other owner's gap"); + assert!(parked.record_is_gap(gap), "prepared record is not a gap"); + assert_ne!(field, gap); + pause_at(&mut parked, owner.slot(), field); + charge_pending(&mut parked); + assert!(parked.marked(owner)); + assert!(!parked.marked(target)); + let occupied = parked.meter(); + parked + .write_field(owner, KEY_REPLACED, target) + .expect("in-place replace at the edge cap"); + assert_eq!(parked.field_index(owner, KEY_REPLACED), Some(field)); + assert_eq!(parked.object_index(gap_owner, key_obj), Some(gap)); + assert!( + parked.record_is_gap(gap), + "the other gap was reclaimed or rewritten" + ); + assert_eq!( + parked.stats().edge_slots, + 3, + "the replace allocated another edge" + ); + assert_eq!( + parked.meter().parked_cursor_repairs, + occupied.parked_cursor_repairs + ); + assert_eq!( + parked.meter().parked_edge_writes, + occupied.parked_edge_writes + 1 + ); + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + heap.alive(target) && heap.scan.parked_barrier_marks == 1, + "record {field} stores the target but it was collected; barrier_marks {} gap {gap}", + heap.scan.parked_barrier_marks + ); + assert!(heap.alive(gap_owner) && heap.alive(key_obj)); + assert_eq!(heap.scan.mark_passes, 1); +} + +struct PassedSlot { + frame: RootFrameId, + child: TableRef, + cycle: Cycle, +} + +fn pause_passed_slot(heap: &mut LuaHeap, gray: bool) -> (ParkedMark<'_>, PassedSlot) { + let later = heap.alloc().expect("later"); + let child = heap.alloc().expect("later child"); + heap.set_edge(later, KEY_KEPT, child).expect("later edge"); + let tail = heap.alloc().expect("tail"); + let cycle = plant_cycle(heap); + let frame = heap.enter_roots(4).expect("frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 2, tail).expect("root tail"); + heap.write_root(frame, 3, cycle.watch).expect("root watch"); + let mut parked = ParkedMark::start(heap).expect("park"); + if gray { + pause_after_root_visits(&mut parked, 4); + let orphan = parked + .field_index(cycle.watch, KEY_REPLACED) + .expect("watch orphan edge"); + pulse_until_gray(&mut parked); + pause_at(&mut parked, cycle.watch.slot(), orphan); + charge_pending(&mut parked); + assert_eq!(parked.phase_name(), "gray"); + assert_eq!(parked.meter().root_slot_visits, 4); + } else { + pause_after_root_visits(&mut parked, 2); + assert_eq!(parked.phase_name(), "roots"); + } + assert!( + parked.meter().root_slot_visits > u64::from(PASSED_SLOT), + "the empty root slot has not been passed" + ); + assert_eq!( + parked.root_table(frame, PASSED_SLOT).expect("slot"), + None, + "the passed slot was not empty" + ); + assert!(!parked.marked(cycle.p), "P is marked before the root write"); + ( + parked, + PassedSlot { + frame, + child, + cycle, + }, + ) +} + +fn assert_table_root_kept(gray: bool) { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let (mut parked, slot) = pause_passed_slot(&mut heap, gray); + let before = parked.meter(); + let visits = before.root_slot_visits; + let pending = parked.pending(); + let scanning = parked.scanning_owner(); + parked + .write_table_root(slot.frame, PASSED_SLOT, slot.cycle.p) + .expect("fixed table root update"); + assert_eq!( + parked.root_table(slot.frame, PASSED_SLOT).expect("stored"), + Some(slot.cycle.p) + ); + assert_eq!(parked.meter().root_slot_visits, visits); + assert_eq!( + parked.meter().parked_root_writes, + before.parked_root_writes + 1 + ); + assert!( + same_pending(parked.pending(), pending), + "the owner edge cursor moved" + ); + assert_eq!(parked.scanning_owner(), scanning); + assert_write_did_not_scan(&before, &parked.meter()); + assert_one_more_pulse_unit(&mut parked); + let view = finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + cycle_kept(&heap, &slot.cycle) && heap.scan.parked_barrier_marks == 1, + "{}", + cycle_lost_message(&heap, &slot.cycle, PASSED_SLOT) + ); + assert_cycle_identity(&heap, &slot.cycle); + assert!( + heap.alive(slot.child), + "the resumed gray queue lost Later's child" + ); + assert_eq!(view.mark_passes, 1); + assert_eq!(heap.scan.parked_root_writes, 1); + assert_eq!(heap.scan.mark_passes, 1); + heap.clear_root(slot.frame, PASSED_SLOT) + .expect("clear the retaining root"); + heap.collect(); + assert!( + !heap.alive(slot.cycle.p), + "clearing the root did not release P" + ); +} + +#[test] +fn barrier_roots_passed_slot_keeps_the_table() { + assert_table_root_kept(false); +} + +#[test] +fn barrier_gray_passed_slot_keeps_the_table() { + assert_table_root_kept(true); +} + +#[test] +fn barrier_passed_slot_keeps_the_closure_chain() { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let later = heap.alloc().expect("later"); + let tail = heap.alloc().expect("tail"); + let mt = heap.alloc().expect("metatable"); + let watch = heap.alloc().expect("watch"); + let orphan = heap.alloc().expect("orphan"); + let closure = heap.alloc_closure().expect("closure"); + let cell = heap.alloc_upvalue().expect("upvalue"); + let successor = heap.alloc().expect("successor"); + heap.set_mode_scalar(mt, Value::string("v\0")) + .expect("mode"); + heap.set_metatable(watch, Some(mt)) + .expect("watch metatable"); + heap.set_upvalue_edge(closure, cell).expect("closure cell"); + heap.write_upvalue(cell, successor).expect("cell current"); + heap.set_closure_edge(watch, KEY_KEPT, closure) + .expect("weak closure"); + heap.set_edge(watch, KEY_REPLACED, orphan) + .expect("weak orphan"); + let frame = heap.enter_roots(4).expect("frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 2, tail).expect("root tail"); + heap.write_root(frame, 3, watch).expect("root watch"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + pause_after_root_visits(&mut parked, 2); + assert_eq!(parked.phase_name(), "roots"); + let before = parked.meter(); + parked + .write_closure_root(frame, PASSED_SLOT, closure) + .expect("fixed closure root update"); + assert_eq!( + parked.root_closure(frame, PASSED_SLOT).expect("stored"), + Some(closure) + ); + assert_eq!(parked.meter().root_slot_visits, before.root_slot_visits); + assert_eq!(parked.meter().parked_root_writes, 1); + assert_write_did_not_scan(&before, &parked.meter()); + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + heap.closure_alive(closure) + && heap.upvalue_alive(cell) + && heap.alive(successor) + && heap.scan.parked_barrier_marks == 1, + "closure chain collected after a successful root write; closure {} cell {} successor {} barrier_marks {}", + heap.closure_alive(closure), + heap.upvalue_alive(cell), + heap.alive(successor), + heap.scan.parked_barrier_marks, + ); + assert_eq!(heap.read_upvalue(closure).expect("chain"), successor); + assert!(!heap.alive(orphan), "weak orphan was retained"); + assert_eq!(heap.scan.mark_passes, 1); + assert_eq!(heap.scan.parked_root_writes, 1); +} + +#[test] +fn barrier_passed_slot_keeps_the_upvalue_chain() { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let later = heap.alloc().expect("later"); + let tail = heap.alloc().expect("tail"); + let mt = heap.alloc().expect("metatable"); + let watch = heap.alloc().expect("watch"); + let orphan = heap.alloc().expect("orphan"); + let cell = heap.alloc_upvalue().expect("upvalue"); + let successor = heap.alloc().expect("successor"); + heap.set_mode_scalar(mt, Value::string("v\0")) + .expect("mode"); + heap.set_metatable(watch, Some(mt)) + .expect("watch metatable"); + heap.write_upvalue(cell, successor).expect("cell current"); + heap.set_cell_edge(watch, cell).expect("weak cell"); + heap.set_edge(watch, KEY_REPLACED, orphan) + .expect("weak orphan"); + let frame = heap.enter_roots(4).expect("frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 2, tail).expect("root tail"); + heap.write_root(frame, 3, watch).expect("root watch"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + pause_after_root_visits(&mut parked, 4); + let orphan_edge = parked + .field_index(watch, KEY_REPLACED) + .expect("orphan edge"); + pulse_until_gray(&mut parked); + pause_at(&mut parked, watch.slot(), orphan_edge); + charge_pending(&mut parked); + assert_eq!(parked.phase_name(), "gray"); + assert!( + !parked.marked(successor), + "weak scan marked the cell current" + ); + let before = parked.meter(); + let scanning = parked.scanning_owner(); + parked + .write_upvalue_root(frame, PASSED_SLOT, cell) + .expect("fixed upvalue root update"); + assert_eq!( + parked.root_upvalue(frame, PASSED_SLOT).expect("stored"), + Some(cell) + ); + assert_eq!(parked.meter().root_slot_visits, before.root_slot_visits); + assert_eq!(parked.scanning_owner(), scanning); + assert_eq!(parked.meter().parked_root_writes, 1); + assert_write_did_not_scan(&before, &parked.meter()); + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + heap.upvalue_alive(cell) && heap.alive(successor) && heap.scan.parked_barrier_marks == 1, + "upvalue chain collected after a successful root write; cell {} successor {} barrier_marks {}", + heap.upvalue_alive(cell), + heap.alive(successor), + heap.scan.parked_barrier_marks, + ); + assert_eq!(heap.current_table(cell).expect("current"), Some(successor)); + assert!(!heap.alive(orphan)); + assert_eq!(heap.scan.mark_passes, 1); + assert_eq!(heap.scan.parked_root_writes, 1); +} + +#[test] +fn barrier_refused_root_write_leaves_the_slot_and_meter() { + let mut heap = LuaHeap::new(limits(4, 4, 4)); + let frame = heap.enter_roots(2).expect("frame"); + let target = heap.alloc().expect("target"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let before = picture(&parked); + let err = parked + .write_table_root(frame, 0, target) + .expect_err("closed phase"); + assert_eq!(err, HeapError::MarkDenied); + assert_same(&picture(&parked), &before); + assert_eq!(parked.meter().parked_root_writes, 0); + assert_eq!(parked.meter().parked_barrier_marks, 0); + parked.cancel(); + + let mut heap = LuaHeap::new(limits(8, 4, 4)); + let stale = heap.alloc().expect("stale"); + heap.rollback(stale).expect("rollback"); + let later = heap.alloc().expect("later"); + let tail = heap.alloc().expect("tail"); + let frame = heap.enter_roots(3).expect("frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 2, tail).expect("root tail"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + pause_after_root_visits(&mut parked, 2); + let before = picture(&parked); + let stale_err = parked + .write_table_root(frame, PASSED_SLOT, stale) + .expect_err("stale handle"); + assert_eq!(stale_err, HeapError::StaleHandle); + assert_same(&picture(&parked), &before); + assert_eq!(parked.root_table(frame, PASSED_SLOT).expect("slot"), None); + let slot_err = parked + .write_table_root(frame, 3, later) + .expect_err("invalid slot"); + assert_eq!(slot_err, HeapError::StaleFrame); + assert_same(&picture(&parked), &before); + assert_eq!(parked.root_table(frame, PASSED_SLOT).expect("slot"), None); + assert_eq!(parked.meter().parked_root_writes, 0); + assert_eq!(parked.meter().parked_barrier_marks, 0); + assert_eq!(parked.meter().mark_passes, 1); +} From 3d52c8930e2d62481385f95a13cd7cf79396d035 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 19:53:51 +0800 Subject: [PATCH 101/225] fix(lua): refuse a parked rewrite of the private cell edge The shared field gate rejected only __mode. A marked table write replaced the real cell upvalue with a table, and delete removed that record. --- src/frontends/lua/heap/table/mark.rs | 7 +- tests/luajit_heap_runtime/parked_mark.rs | 224 ++++++++++++++++++++++- 2 files changed, 226 insertions(+), 5 deletions(-) diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index c057e22..451e338 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -18,8 +18,8 @@ //! non-gap ordinary field on an already marked owner, and a fixed root-slot //! update through the typed root writers. New keys, gap resurrection, //! allocation, rollback, metatable and `__mode` writes, root-frame changes, -//! internal closure edges, and token edits stay closed. A refused edit -//! returns before it changes the heap. +//! internal closure edges, the private cell edge, and token edits stay closed. +//! A refused edit returns before it changes the heap. use super::{ ClosureRef, CollectReport, EdgeKey, EdgeValue, HandleKind, HeapError, HeapStats, LuaHeap, @@ -483,7 +483,8 @@ impl<'a> ParkedMark<'a> { fn gate_field(&self, from: TableRef, key: u32) -> Result<(), HeapError> { self.gate_mutation()?; - if key == LuaHeap::MODE_FIELD { + // Field 0 is `__mode`. The private cell id is not a Lua key either. + if key == LuaHeap::MODE_FIELD || key == super::CELL_EDGE { return Err(HeapError::MarkDenied); } self.heap.require_live(from)?; diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index 1987d93..6012d0b 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -5,12 +5,13 @@ use super::{ HeapError, HeapLimits, HeapStats, LuaHeap, ParkedMark, PausedOp, PendingScan, RootFrameId, - ScanMeter, TableRef, + ScanMeter, TableRef, UpvalueRef, }; use vm::Value; const KEY_X: u32 = 1; -const KEY_Y: u32 = 2; +/// Ordinary field. Not the private cell field stored by `set_cell_edge`. +const KEY_Y: u32 = 5; const KEY_Z: u32 = 3; const KEY_W: u32 = 1; const HARNESS_BOUND: u32 = 64; @@ -421,6 +422,225 @@ fn open_phase_refuses_marked_owner_and_forbidden_ops() { assert!(heap.alive(extra)); } +/// Mark bits and gray pushes the refusal must not change. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct GraphGuards { + owner_marked: bool, + successor_marked: bool, + intruder_marked: bool, + work_pushed: u64, + barrier_marks: u64, + scanning: Option, +} + +struct CellRefusal { + phase_open: bool, + owner_marked: bool, + result: Result<(), HeapError>, + edge: Result, HeapError>, + index_before: Option, + index_after: Option, + pending_before: (u32, u32), + pending_after: Option<(u32, u32)>, + guards_before: GraphGuards, + guards_after: GraphGuards, + meter_before: ScanMeter, + meter_after: ScanMeter, + stats_before: HeapStats, + stats_after: HeapStats, + bytes_before: u64, + bytes_after: u64, + cell: UpvalueRef, + successor: TableRef, + kept: Option, +} + +struct KeptCell { + cell_edge: Result, + current: Result, HeapError>, + owner_alive: bool, + cell_alive: bool, + successor_alive: bool, + intruder_alive: bool, + orphan_alive: bool, +} + +fn graph_guards( + parked: &ParkedMark<'_>, + owner: TableRef, + successor: TableRef, + intruder: TableRef, +) -> GraphGuards { + GraphGuards { + owner_marked: parked.marked(owner), + successor_marked: parked.marked(successor), + intruder_marked: parked.marked(intruder), + work_pushed: parked.meter().scratch.work_pushed, + barrier_marks: parked.meter().parked_barrier_marks, + scanning: parked.scanning_owner(), + } +} + +/// One fresh heap. A write on this heap cannot change the delete heap. +fn cell_edge_refusal(write: bool) -> CellRefusal { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let owner = heap.alloc().expect("owner"); + let successor = heap.alloc().expect("successor"); + let intruder = heap.alloc().expect("intruder"); + let orphan = heap.alloc().expect("orphan"); + let cell = heap.alloc_upvalue().expect("cell"); + heap.write_upvalue(cell, successor).expect("current"); + heap.set_cell_edge(owner, cell).expect("cell edge"); + assert_eq!(heap.cell_edge(owner).expect("stored cell"), cell); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, owner).expect("root owner"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let index = parked + .field_index(owner, super::CELL_EDGE) + .expect("cell record"); + let pending = pause_at(&mut parked, owner.slot(), index); + let phase_open = parked.mutation_open() && parked.phase_name() == "gray"; + let owner_marked = parked.marked(owner); + assert!( + phase_open, + "cell edge refusal must run while mutation is open" + ); + assert!(owner_marked, "the owner is already marked"); + assert!( + !parked.marked(successor), + "the cell edge has not been charged" + ); + assert_eq!( + parked + .edge(owner, super::CELL_EDGE) + .expect_err("cell edge is an upvalue"), + HeapError::WrongKind + ); + let guards_before = graph_guards(&parked, owner, successor, intruder); + let before = picture(&parked); + let result = if write { + parked.write_field(owner, super::CELL_EDGE, intruder) + } else { + parked.delete_field(owner, super::CELL_EDGE) + }; + let edge = parked.edge(owner, super::CELL_EDGE); + let index_after = parked.field_index(owner, super::CELL_EDGE); + let guards_after = graph_guards(&parked, owner, successor, intruder); + let pending_after = parked.pending().map(|scan| (scan.owner, scan.cursor)); + let after = picture(&parked); + let kept = if result.is_err() { + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + Some(KeptCell { + cell_edge: heap.cell_edge(owner), + current: heap.current_table(cell), + owner_alive: heap.alive(owner), + cell_alive: heap.upvalue_alive(cell), + successor_alive: heap.alive(successor), + intruder_alive: heap.alive(intruder), + orphan_alive: heap.alive(orphan), + }) + } else { + drop(parked); + None + }; + CellRefusal { + phase_open, + owner_marked, + result, + edge, + index_before: Some(index), + index_after, + pending_before: (pending.owner, pending.cursor), + pending_after, + guards_before, + guards_after, + meter_before: before.meter, + meter_after: after.meter, + stats_before: before.stats, + stats_after: after.stats, + bytes_before: before.bytes, + bytes_after: after.bytes, + cell, + successor, + kept, + } +} + +#[test] +fn open_phase_refuses_marked_owner_cell_edge() { + let write = cell_edge_refusal(true); + let delete = cell_edge_refusal(false); + assert!( + write.phase_open && write.owner_marked && delete.phase_open && delete.owner_marked, + "both refusals run on a marked owner in an open phase" + ); + assert_eq!( + (&write.result, &delete.result), + (&Err(HeapError::MarkDenied), &Err(HeapError::MarkDenied)), + "write edge {:?} index {:?} -> {:?}; delete edge {:?} index {:?} -> {:?}", + write.edge, + write.index_before, + write.index_after, + delete.edge, + delete.index_before, + delete.index_after, + ); + assert_eq!( + write.guards_before, write.guards_after, + "write graph guards" + ); + assert_eq!( + delete.guards_before, delete.guards_after, + "delete graph guards" + ); + assert_eq!( + write.pending_after, + Some(write.pending_before), + "write pending cursor" + ); + assert_eq!( + delete.pending_after, + Some(delete.pending_before), + "delete pending cursor" + ); + assert_eq!(write.index_after, write.index_before, "write record"); + assert_eq!(delete.index_after, delete.index_before, "delete record"); + assert_eq!(write.meter_before, write.meter_after, "write meter"); + assert_eq!(delete.meter_before, delete.meter_after, "delete meter"); + assert_eq!(write.stats_before, write.stats_after, "write stats"); + assert_eq!(delete.stats_before, delete.stats_after, "delete stats"); + assert_eq!(write.bytes_before, write.bytes_after, "write bytes"); + assert_eq!(delete.bytes_before, delete.bytes_after, "delete bytes"); + let write_kept = write.kept.expect("write swept after refusal"); + let delete_kept = delete.kept.expect("delete swept after refusal"); + assert_eq!( + write_kept.cell_edge, + Ok(write.cell), + "write kept the upvalue" + ); + assert_eq!( + delete_kept.cell_edge, + Ok(delete.cell), + "delete kept the upvalue" + ); + assert_eq!( + write_kept.current, + Ok(Some(write.successor)), + "write kept the cell current" + ); + assert_eq!( + delete_kept.current, + Ok(Some(delete.successor)), + "delete kept the cell current" + ); + assert!(write_kept.owner_alive && write_kept.cell_alive && write_kept.successor_alive); + assert!(delete_kept.owner_alive && delete_kept.cell_alive && delete_kept.successor_alive); + assert!(!write_kept.intruder_alive && !write_kept.orphan_alive); + assert!(!delete_kept.intruder_alive && !delete_kept.orphan_alive); +} + #[test] fn cancel_restarts_a_full_collect() { let mut heap = LuaHeap::new(limits(8, 2, 8)); From 3d18654ced8cf4fe6d5b521a40c08ce7c4328f30 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 19:34:54 +0800 Subject: [PATCH 102/225] fix(lua/heap): publish weak clears at the end of the owner walk The same Owners walker now has a private observation boundary. Before Owners the original edges are readable. The walk publishes once when it finishes, still short of Release, and does not return a partial clear. A later budgeted pulse releases the judged-dead slots. A sweep with no dead slot does not invent that window. --- src/frontends/lua/heap/table/sweep.rs | 224 ++++++++- tests/luajit_heap_runtime/weak_publish.rs | 560 ++++++++++++++++++++++ 2 files changed, 780 insertions(+), 4 deletions(-) create mode 100644 tests/luajit_heap_runtime/weak_publish.rs diff --git a/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs index a4efdb8..a2446c5 100644 --- a/src/frontends/lua/heap/table/sweep.rs +++ b/src/frontends/lua/heap/table/sweep.rs @@ -12,13 +12,20 @@ //! That read is part of the head unit. It does not rescan a mode string and //! does not add `weak_mode_lookups`. //! -//! Production callers drain this session before they return a report. A -//! partial pulse is only visible to the private test that still holds the -//! borrow. Guest `next` and raw reads belong after `drain`. +//! Production callers drain this session before they return a report. `pulse` +//! still rewrites one owner unit at a time. The private observation entry does +//! not return that partial graph: before Owners the original edges are +//! readable, and the same Owners walker publishes once when it finishes, +//! still short of Release. That window's heads and edges are the walk it +//! actually did. They are not a `pulse(1)` bound. Guest lookup on the entry +//! rejects a handle already judged dead. A sweep with no dead slot never +//! enters Owners and does not invent a publish window. use super::{ - CollectReport, EdgeKey, EdgeValue, HandleKind, LuaHeap, MarkSnapshot, ScanMeter, SlotState, + CollectReport, EdgeKey, EdgeValue, GuestClass, HandleKind, HeapError, LuaHeap, MarkSnapshot, + ScanMeter, SlotState, TableRef, }; +use vm::Value; pub(super) struct SweepSession<'a> { heap: &'a mut LuaHeap, @@ -386,6 +393,85 @@ impl<'a> SweepSession<'a> { }) } + /// Reads the graph only outside the Owners walk. + /// + /// Select and Snapshot still hold the original edges. The first Release + /// index, after Owners, is the published graph. Any other phase, including + /// a unit inside Owners, returns nothing. + fn weak_view(&self) -> Option> { + let publish = match self.phase { + SweepPhase::Select | SweepPhase::Snapshot => WeakPublish::Original, + SweepPhase::Release if self.index == 0 && !self.dead.is_empty() => { + WeakPublish::Published + } + _ => return None, + }; + Some(self.boundary(publish)) + } + + /// Runs the current Owners walker to its end and returns that one boundary. + /// + /// The caller must still be before any owner unit. A walk that has already + /// rewritten an edge is not restarted and is not published. The transition + /// into Owners is not charged. Release does not start. + fn publish_owners(&mut self) -> Option> { + if matches!(self.phase, SweepPhase::Snapshot) && self.index >= self.heap.slots.len() { + let charged = self.step(); + debug_assert!(!charged); + } + if !matches!(self.phase, SweepPhase::Owners) || !self.at_owner_start() { + return None; + } + let mut spent = SweepUnits::default(); + let mut spins = 0u32; + while matches!(self.phase, SweepPhase::Owners) { + self.pulse_spent = SweepUnits::default(); + if self.step() { + spent.heads += self.pulse_spent.heads; + spent.edges += self.pulse_spent.edges; + spent.selection += self.pulse_spent.selection; + spent.snapshot += self.pulse_spent.snapshot; + spent.releases += self.pulse_spent.releases; + spent.roots += self.pulse_spent.roots; + spins = 0; + } else { + spins += 1; + debug_assert!(spins <= 4, "owner transition did not reach Release"); + } + } + debug_assert!(matches!(self.phase, SweepPhase::Release)); + debug_assert_eq!(self.index, 0); + debug_assert!(!self.owner_open); + debug_assert!(self.cursor.is_none()); + Some(PublishWindow { + spent, + view: self.boundary(WeakPublish::Published), + }) + } + + fn at_owner_start(&self) -> bool { + self.owner == 0 && !self.owner_open && self.cursor.is_none() + } + + fn boundary(&self, publish: WeakPublish) -> WeakView<'_> { + WeakView { + publish, + finished: false, + release_started: false, + heap: self.heap, + dead: &self.dead, + snapshot: &self.snapshot, + } + } + + /// Occupancy of one slot. This is not a guest lookup and does not accept + /// a table handle. + fn slot_physical(&self, slot: u32) -> Option<(bool, u32)> { + let stored = self.heap.slots.get(slot as usize)?; + let live = matches!(stored.state, SlotState::Live { .. }); + Some((live, stored.generation)) + } + fn guest_cursor(&self, key: &EdgeKey) -> bool { match key { EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, @@ -399,3 +485,133 @@ impl<'a> SweepSession<'a> { } } } + +/// Which exclusive boundary the observation entry is returning. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WeakPublish { + /// Select or Snapshot. No owner edge has been rewritten. + Original, + /// Owners has finished. Release has not taken a slot. + Published, +} + +/// Actual heads and edges of one exclusive Owners walk, plus the graph it left. +struct PublishWindow<'a> { + spent: SweepUnits, + view: WeakView<'a>, +} + +/// Read-only graph at one boundary. A judged-dead handle is not a target. +struct WeakView<'a> { + publish: WeakPublish, + finished: bool, + release_started: bool, + heap: &'a LuaHeap, + dead: &'a [u32], + snapshot: &'a [SweepSlot], +} + +#[derive(Debug, PartialEq, Eq)] +enum ObserveError { + JudgedDead, + Heap(HeapError), +} + +impl WeakView<'_> { + fn publish(&self) -> WeakPublish { + self.publish + } + + fn finished(&self) -> bool { + self.finished + } + + fn release_started(&self) -> bool { + self.release_started + } + + fn occupying_dead(&self) -> u32 { + self.dead.len() as u32 + } + + fn dead_still_physical(&self) -> u32 { + self.dead + .iter() + .filter(|&&slot| self.still_physical(slot)) + .count() as u32 + } + + fn named(&self, table: TableRef, name: &str) -> Result, ObserveError> { + self.reject(table)?; + match self.heap.named_edge(table, name) { + Ok(found) => Ok(found), + Err(error) => Err(ObserveError::Heap(error)), + } + } + + fn number(&self, table: TableRef, key: f64) -> Result { + self.reject(table)?; + match self.heap.number_value(table, key) { + Ok(found) => Ok(found), + Err(error) => Err(ObserveError::Heap(error)), + } + } + + fn object(&self, table: TableRef, key: TableRef) -> Result, ObserveError> { + self.reject(table)?; + self.reject(key)?; + match self.heap.object_edge(table, key) { + Ok(found) => Ok(found), + Err(error) => Err(ObserveError::Heap(error)), + } + } + + fn raw_sequence_len(&self, table: TableRef) -> Result { + self.reject(table)?; + match self.heap.raw_sequence_len(table) { + Ok(len) => Ok(len), + Err(error) => Err(ObserveError::Heap(error)), + } + } + + fn next( + &self, + table: TableRef, + cursor: &Value, + ) -> Result, ObserveError> { + self.reject(table)?; + if let GuestClass::Table(key) = self.heap.guest_class(cursor) { + self.reject(key)?; + } + match self.heap.next_guest(table, cursor) { + Ok(found) => Ok(found), + Err(error) => Err(ObserveError::Heap(error)), + } + } + + fn alive(&self, table: TableRef) -> Result { + self.reject(table)?; + Ok(self.heap.alive(table)) + } + + fn reject(&self, table: TableRef) -> Result<(), ObserveError> { + if self.dead.iter().any(|&slot| slot == table.slot()) { + return Err(ObserveError::JudgedDead); + } + Ok(()) + } + + fn still_physical(&self, slot: u32) -> bool { + let Some(stored) = self.heap.slots.get(slot as usize) else { + return false; + }; + let Some(snap) = self.snapshot.get(slot as usize) else { + return false; + }; + matches!(stored.state, SlotState::Live { .. }) && stored.generation == snap.generation + } +} + +#[cfg(test)] +#[path = "../../../../../tests/luajit_heap_runtime/weak_publish.rs"] +mod weak_publish; diff --git a/tests/luajit_heap_runtime/weak_publish.rs b/tests/luajit_heap_runtime/weak_publish.rs new file mode 100644 index 0000000..1b2a27d --- /dev/null +++ b/tests/luajit_heap_runtime/weak_publish.rs @@ -0,0 +1,560 @@ +//! Private weak-publish boundaries. +//! +//! The unit walker can rewrite one edge and leave the next edge of the same +//! table. That partial graph is recorded outside this file. These tests only +//! read the observation entry, which returns the original graph or the fully +//! published graph. + +use super::super::{HeapLimits, LuaHeap, ScanMeter}; +use super::{ObserveError, SweepSession, WeakPublish}; +use vm::Value; + +const TABLES: u32 = 32; +const TEXT_TABLES: u32 = 16; +const NUMBER_TABLES: u32 = 8; + +fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { + HeapLimits { + nodes, + roots, + edges, + max_generation: 8, + } +} + +fn root_all(heap: &mut LuaHeap, tables: &[super::super::TableRef]) { + let frame = heap.enter_roots(tables.len() as u32).expect("frame"); + for (index, table) in tables.iter().copied().enumerate() { + heap.write_root(frame, index as u32, table).expect("root"); + } +} + +struct Graph { + heap: LuaHeap, + owners: Vec, + nodes: u32, + edges: u32, + weak: Vec, +} + +struct Owner { + owner: super::super::TableRef, + live: super::super::TableRef, + live_carrier: Value, + kind: Kind, +} + +enum Kind { + Text { + first: super::super::TableRef, + second: super::super::TableRef, + first_carrier: Value, + }, + Number { + first_carrier: Value, + }, + Object { + keys: [super::super::TableRef; 2], + key_carriers: [Value; 2], + first_carrier: Value, + }, +} + +fn build(shared_metatable: bool) -> Graph { + let object_tables = TABLES - TEXT_TABLES - NUMBER_TABLES; + let metatables = if shared_metatable { 1 } else { TABLES }; + let object_keys = object_tables * 2; + let nodes = metatables + TABLES * 4 + object_keys; + let roots = metatables + TABLES * 2 + object_keys; + let edges = metatables + TABLES * 3 + TABLES * 2; + let mut heap = LuaHeap::new(limits(nodes, roots, edges)); + let mut rooted = Vec::new(); + let shared = if shared_metatable { + let table = heap.alloc().expect("metatable"); + heap.set_mode_scalar(table, Value::string("v")) + .expect("mode"); + rooted.push(table); + Some(table) + } else { + None + }; + let mut owners = Vec::new(); + let mut weak = Vec::new(); + for index in 0..TABLES { + let metatable = if let Some(shared) = shared { + shared + } else { + let table = heap.alloc().expect("metatable"); + heap.set_mode_scalar(table, Value::string("v")) + .expect("mode"); + rooted.push(table); + table + }; + let owner = heap.alloc().expect("owner"); + let live = heap.alloc().expect("live"); + let first = heap.alloc().expect("first weak"); + let second = heap.alloc().expect("second weak"); + let live_carrier = heap.issue_carrier(live).expect("live carrier"); + let first_carrier = heap.issue_carrier(first).expect("first carrier"); + let _second_carrier = heap.issue_carrier(second).expect("second carrier"); + heap.set_metatable(owner, Some(metatable)) + .expect("metatable"); + heap.set_named_edge(first, "self", first).expect("cycle"); + heap.set_named_edge(second, "self", second).expect("cycle"); + let kind = if index < TEXT_TABLES { + heap.set_named_edge(owner, "a", first).expect("a"); + heap.set_named_edge(owner, "stay", live).expect("stay"); + heap.set_named_edge(owner, "b", second).expect("b"); + Kind::Text { + first, + second, + first_carrier, + } + } else if index < TEXT_TABLES + NUMBER_TABLES { + heap.set_number_edge(owner, 1.0, first).expect("one"); + heap.set_number_edge(owner, 2.0, second).expect("two"); + heap.set_named_edge(owner, "stay", live).expect("stay"); + Kind::Number { first_carrier } + } else { + let left = heap.alloc().expect("left key"); + let right = heap.alloc().expect("right key"); + let left_carrier = heap.issue_carrier(left).expect("left carrier"); + let right_carrier = heap.issue_carrier(right).expect("right carrier"); + heap.set_object_edge(owner, left, first).expect("left"); + heap.set_named_edge(owner, "stay", live).expect("stay"); + heap.set_object_edge(owner, right, second).expect("right"); + rooted.push(left); + rooted.push(right); + Kind::Object { + keys: [left, right], + key_carriers: [left_carrier, right_carrier], + first_carrier, + } + }; + owners.push(Owner { + owner, + live, + live_carrier, + kind, + }); + rooted.push(owner); + rooted.push(live); + weak.push(first); + weak.push(second); + } + assert_eq!(weak.len(), 64); + root_all(&mut heap, &rooted); + let stats = heap.stats(); + assert_eq!(stats.node_slots, nodes, "node accounting"); + assert_eq!(stats.edge_slots, edges, "edge accounting"); + assert_eq!(rooted.len() as u32, roots, "root accounting"); + Graph { + heap, + owners, + nodes, + edges, + weak, + } +} + +fn visible_weak(view: &super::WeakView<'_>, owners: &[Owner]) -> u32 { + owners.iter().map(|owner| weak_present(view, owner)).sum() +} + +fn weak_present(view: &super::WeakView<'_>, owner: &Owner) -> u32 { + match &owner.kind { + Kind::Text { first, second, .. } => { + u32::from(view.named(owner.owner, "a").expect("a") == Some(*first)) + + u32::from(view.named(owner.owner, "b").expect("b") == Some(*second)) + } + Kind::Number { first_carrier } => { + let one = view.number(owner.owner, 1.0).expect("one"); + let two = view.number(owner.owner, 2.0).expect("two"); + u32::from(one == *first_carrier) + u32::from(two != Value::Null) + } + Kind::Object { + keys, + first_carrier, + .. + } => { + let left = view.object(owner.owner, keys[0]).expect("left"); + let right = view.object(owner.owner, keys[1]).expect("right"); + u32::from(left.is_some() && view_matches_carrier(left, first_carrier)) + + u32::from(right.is_some()) + } + } +} + +fn view_matches_carrier(found: Option, carrier: &Value) -> bool { + let Some(found) = found else { + return false; + }; + matches!(carrier, Value::Array(_)) && found.slot() == array_slot(carrier) +} + +fn array_slot(carrier: &Value) -> u32 { + match carrier { + Value::Array(values) => match values.first() { + Some(Value::Int(slot)) => u32::try_from(*slot).expect("slot"), + _ => panic!("carrier has no slot"), + }, + _ => panic!("expected carrier"), + } +} + +fn assert_boundary(view: &super::WeakView<'_>, owners: &[Owner], present: bool) { + let expected = if present { 64 } else { 0 }; + assert_eq!(visible_weak(view, owners), expected); + for owner in owners { + let found = weak_present(view, owner); + assert_eq!(found, if present { 2 } else { 0 }, "no partial owner"); + assert_eq!( + view.named(owner.owner, "stay").expect("stay"), + Some(owner.live), + "live identity" + ); + match &owner.kind { + Kind::Text { first_carrier, .. } => { + let continued = view.next(owner.owner, &Value::string("a")).expect("next a"); + let (key, value) = continued.expect("continuation pair"); + assert_eq!(key, Value::string("stay")); + assert_eq!(value, owner.live_carrier); + assert!( + view.next(owner.owner, &Value::string("b")) + .expect("last cursor") + .is_none(), + "last cursor tail is one nil" + ); + if !present { + assert!( + view.next(owner.owner, &Value::string("stay")) + .expect("published tail") + .is_none(), + "survivor tail is one nil after publish" + ); + } + assert!(matches!( + view.next(owner.owner, first_carrier), + Err(ObserveError::JudgedDead) + )); + } + Kind::Number { .. } => { + let len = view.raw_sequence_len(owner.owner).expect("rawlen"); + assert_eq!(len, if present { 2.0 } else { 0.0 }); + } + Kind::Object { + keys, key_carriers, .. + } => { + let continued = view + .next(owner.owner, &key_carriers[0]) + .expect("object next"); + let (key, value) = continued.expect("object continuation pair"); + assert_eq!(key, Value::string("stay")); + assert_eq!(value, owner.live_carrier); + assert!( + view.next(owner.owner, &key_carriers[1]) + .expect("object last cursor") + .is_none(), + "object last cursor tail is one nil" + ); + if !present { + assert!( + view.next(owner.owner, &Value::string("stay")) + .expect("object published tail") + .is_none(), + "object survivor tail is one nil after publish" + ); + } + assert!(view.alive(keys[0]).expect("key")); + assert!(view.alive(keys[1]).expect("key")); + assert_ne!(keys[0], owner.live); + assert_ne!(keys[1], owner.live); + } + } + } +} + +fn reject_judged_dead(view: &super::WeakView<'_>, dead: super::super::TableRef) { + assert!(matches!( + view.named(dead, "self"), + Err(ObserveError::JudgedDead) + )); + assert!(matches!(view.alive(dead), Err(ObserveError::JudgedDead))); + assert!(matches!( + view.raw_sequence_len(dead), + Err(ObserveError::JudgedDead) + )); +} + +fn finish_release(session: &mut SweepSession<'_>) { + for _ in 0..10_000 { + if session.pulse(1).finished { + return; + } + } + panic!("release did not finish"); +} + +fn sweep_delta(before: &ScanMeter, after: &ScanMeter) -> (u64, u64, u64, u64) { + ( + after.owner_head_checks - before.owner_head_checks, + after.sweep_edge_checks - before.sweep_edge_checks, + after.weak_mode_lookups - before.weak_mode_lookups, + after.weak_mode_bytes - before.weak_mode_bytes, + ) +} + +fn assert_paired(shared_metatable: bool) { + let mut graph = build(shared_metatable); + let mut twin_graph = build(shared_metatable); + let dead = match &graph.owners[0].kind { + Kind::Text { first, .. } => *first, + _ => panic!("first owner is a text table"), + }; + let modes = graph.heap.drain_mark(); + let twin_modes = twin_graph.heap.drain_mark(); + let mut session = SweepSession::start(&mut graph.heap, modes); + let mut twin = SweepSession::start(&mut twin_graph.heap, twin_modes); + let before = session.meter(); + let twin_before = twin.meter(); + assert_eq!(before, twin_before, "mark meters diverged before sweep"); + + assert!(session.publish_owners().is_none(), "prep is not a window"); + let inner = session.pulse(1); + assert_eq!(inner.spent.total(), 1, "pulse(1) is one unit"); + assert_eq!(inner.spent.selection, 1); + assert_ne!(inner.spent.total(), u64::from(graph.nodes + graph.edges)); + let rest = session.pulse(u64::from(graph.nodes) - 1); + assert_eq!(rest.spent.selection, u64::from(graph.nodes) - 1); + let snapshot = session.pulse(u64::from(graph.nodes)); + assert_eq!(snapshot.spent.snapshot, u64::from(graph.nodes)); + assert_eq!(snapshot.spent.heads, 0); + assert_eq!(snapshot.spent.edges, 0); + + let untouched = session.pulse(0); + assert_eq!(untouched.spent.total(), 0); + assert!(!untouched.finished); + { + let original = session.weak_view().expect("original"); + assert_eq!(original.publish(), WeakPublish::Original); + assert!(!original.finished()); + assert!(!original.release_started()); + assert_boundary(&original, &graph.owners, true); + reject_judged_dead(&original, dead); + } + + let (window_heads, window_edges) = { + let window = session.publish_owners().expect("published"); + assert_eq!(window.view.publish(), WeakPublish::Published); + assert!(!window.view.finished()); + assert!(!window.view.release_started()); + assert_eq!(window.spent.heads, u64::from(graph.nodes)); + assert_eq!(window.spent.edges, u64::from(graph.edges)); + assert_eq!(window.spent.selection, 0); + assert_eq!(window.spent.snapshot, 0); + assert_eq!(window.spent.releases, 0); + assert_eq!(window.spent.roots, 0); + assert_ne!(window.spent.total(), 1, "window is not a pulse unit"); + assert!(window.spent.total() > inner.spent.total()); + assert_boundary(&window.view, &graph.owners, false); + assert_eq!(window.view.occupying_dead(), 64); + assert_eq!(window.view.dead_still_physical(), 64); + reject_judged_dead(&window.view, dead); + (window.spent.heads, window.spent.edges) + }; + + let held = session.pulse(0); + assert_eq!(held.spent.total(), 0); + assert!(!held.finished); + { + let published = session.weak_view().expect("still published"); + assert_eq!(published.publish(), WeakPublish::Published); + assert!(!published.finished()); + assert!(!published.release_started()); + assert_eq!(visible_weak(&published, &graph.owners), 0); + assert_eq!(published.dead_still_physical(), 64); + } + assert_eq!(session.stats().collections, 0); + + let first = graph + .weak + .iter() + .copied() + .min_by_key(|table| table.slot()) + .expect("dead"); + let release = session.pulse(1); + assert_eq!(release.spent.total(), 1); + assert_eq!(release.spent.releases, 1); + assert!(!release.finished); + assert!( + session.weak_view().is_none(), + "release is not a publish boundary" + ); + assert_eq!( + session.slot_physical(first.slot()), + Some((false, first.generation().saturating_add(1))) + ); + let mut still_physical = 0u32; + for table in &graph.weak { + if table.slot() == first.slot() { + continue; + } + assert_eq!( + session.slot_physical(table.slot()), + Some((true, table.generation())) + ); + still_physical += 1; + } + assert_eq!(still_physical, 63); + finish_release(&mut session); + let report = session.report(); + let after = session.meter(); + let stats = session.stats(); + let physical: Vec<_> = (0..graph.nodes) + .map(|slot| session.slot_physical(slot)) + .collect(); + drop(session); + + twin.drain(); + let twin_report = twin.report(); + assert_eq!(report, twin_report); + assert_eq!(after, twin.meter()); + assert_eq!(stats.collections, twin.stats().collections); + assert_eq!(stats.collections, 1); + assert_eq!( + sweep_delta(&before, &after), + (window_heads, window_edges, 0, 0) + ); + assert_eq!( + sweep_delta(&twin_before, &twin.meter()), + sweep_delta(&before, &after), + "paired sweep walked once" + ); + for slot in 0..graph.nodes { + assert_eq!(physical[slot as usize], twin.slot_physical(slot)); + } + drop(twin); + assert_guest_pair(&graph, &twin_graph); +} + +fn assert_guest_pair(left: &Graph, right: &Graph) { + assert_eq!(left.owners.len(), right.owners.len()); + for (left_owner, right_owner) in left.owners.iter().zip(&right.owners) { + assert_eq!( + left.heap.alive(left_owner.live), + right.heap.alive(right_owner.live) + ); + assert!(left.heap.alive(left_owner.live)); + assert_eq!( + left.heap + .named_edge(left_owner.owner, "stay") + .expect("stay") + .map(|table| table.slot()), + right + .heap + .named_edge(right_owner.owner, "stay") + .expect("stay") + .map(|table| table.slot()) + ); + match (&left_owner.kind, &right_owner.kind) { + (Kind::Text { .. }, Kind::Text { .. }) => { + assert!(left + .heap + .named_edge(left_owner.owner, "a") + .expect("a") + .is_none()); + assert!(right + .heap + .named_edge(right_owner.owner, "a") + .expect("a") + .is_none()); + } + (Kind::Number { .. }, Kind::Number { .. }) => { + assert_eq!( + left.heap + .raw_sequence_len(left_owner.owner) + .expect("rawlen"), + right + .heap + .raw_sequence_len(right_owner.owner) + .expect("rawlen") + ); + assert_eq!( + left.heap + .raw_sequence_len(left_owner.owner) + .expect("rawlen"), + 0.0 + ); + } + ( + Kind::Object { + keys, key_carriers, .. + }, + Kind::Object { + keys: twin_keys, + key_carriers: twin_carriers, + .. + }, + ) => { + assert!(left.heap.alive(keys[0])); + assert!(right.heap.alive(twin_keys[0])); + assert_ne!(keys[0].slot(), left_owner.live.slot()); + let left_next = left + .heap + .next_guest(left_owner.owner, &key_carriers[0]) + .expect("next"); + let right_next = right + .heap + .next_guest(right_owner.owner, &twin_carriers[0]) + .expect("next"); + assert!(left_next.is_some()); + assert_eq!(left_next.is_some(), right_next.is_some()); + assert!(left + .heap + .object_edge(left_owner.owner, keys[0]) + .expect("cleared") + .is_none()); + } + _ => panic!("paired graphs diverged"), + } + } +} + +#[test] +fn shared_metatable_publishes_every_weak_value_at_one_boundary() { + assert_paired(true); +} + +#[test] +fn separate_metatables_publish_every_weak_value_at_one_boundary() { + assert_paired(false); +} + +#[test] +fn marked_graph_does_not_open_a_publish_window() { + let mut heap = LuaHeap::new(limits(1, 1, 1)); + let table = heap.alloc().expect("table"); + heap.set_named_edge(table, "stay", table).expect("edge"); + root_all(&mut heap, &[table]); + let modes = heap.drain_mark(); + let mut session = SweepSession::start(&mut heap, modes); + let zero = session.pulse(0); + assert_eq!(zero.spent.total(), 0); + assert!(session.publish_owners().is_none()); + assert_ne!( + session.weak_view().map(|view| view.publish()), + Some(WeakPublish::Published) + ); + loop { + assert!(session.publish_owners().is_none()); + assert_ne!( + session.weak_view().map(|view| view.publish()), + Some(WeakPublish::Published) + ); + if session.pulse(1).finished { + break; + } + } + assert_eq!(session.meter().sweep_edge_checks, 0); + let _ = session.report(); +} From 7dfdf0acacd66e69a7dface751e318041bca5644 Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 20:25:49 +0800 Subject: [PATCH 103/225] style(lua): format weak publish asserts for edition 2024 Apply cargo fmt for the manifest edition. Only three assert! calls in tests/luajit_heap_runtime/weak_publish.rs change line breaks. --- tests/luajit_heap_runtime/weak_publish.rs | 34 +++++++++++++---------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/tests/luajit_heap_runtime/weak_publish.rs b/tests/luajit_heap_runtime/weak_publish.rs index 1b2a27d..5fe02f7 100644 --- a/tests/luajit_heap_runtime/weak_publish.rs +++ b/tests/luajit_heap_runtime/weak_publish.rs @@ -458,16 +458,19 @@ fn assert_guest_pair(left: &Graph, right: &Graph) { ); match (&left_owner.kind, &right_owner.kind) { (Kind::Text { .. }, Kind::Text { .. }) => { - assert!(left - .heap - .named_edge(left_owner.owner, "a") - .expect("a") - .is_none()); - assert!(right - .heap - .named_edge(right_owner.owner, "a") - .expect("a") - .is_none()); + assert!( + left.heap + .named_edge(left_owner.owner, "a") + .expect("a") + .is_none() + ); + assert!( + right + .heap + .named_edge(right_owner.owner, "a") + .expect("a") + .is_none() + ); } (Kind::Number { .. }, Kind::Number { .. }) => { assert_eq!( @@ -509,11 +512,12 @@ fn assert_guest_pair(left: &Graph, right: &Graph) { .expect("next"); assert!(left_next.is_some()); assert_eq!(left_next.is_some(), right_next.is_some()); - assert!(left - .heap - .object_edge(left_owner.owner, keys[0]) - .expect("cleared") - .is_none()); + assert!( + left.heap + .object_edge(left_owner.owner, keys[0]) + .expect("cleared") + .is_none() + ); } _ => panic!("paired graphs diverged"), } From ebb02026c8a536bda01981d3791c19dafe6c32df Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 21:00:10 +0800 Subject: [PATCH 104/225] test(lua): cover mixed weak publication in one sweep Interleave k, v, and kv owners in the private publish window and count each group separately. The existing sweep already clears both kv shapes together, so this adds regression coverage only. --- tests/luajit_heap_runtime/weak_publish.rs | 434 ++++++++++++++++++++++ 1 file changed, 434 insertions(+) diff --git a/tests/luajit_heap_runtime/weak_publish.rs b/tests/luajit_heap_runtime/weak_publish.rs index 5fe02f7..f9a4cf5 100644 --- a/tests/luajit_heap_runtime/weak_publish.rs +++ b/tests/luajit_heap_runtime/weak_publish.rs @@ -12,6 +12,7 @@ use vm::Value; const TABLES: u32 = 32; const TEXT_TABLES: u32 = 16; const NUMBER_TABLES: u32 = 8; +const MIXED_OWNERS: u32 = 4; fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { HeapLimits { @@ -562,3 +563,436 @@ fn marked_graph_does_not_open_a_publish_window() { assert_eq!(session.meter().sweep_edge_checks, 0); let _ = session.report(); } + +/// One sweep, owners interleaved as `k`, `v`, `kv`, `kv`. +/// +/// The two `kv` rows are a dead object key with a rooted value, and a rooted +/// object key with a dead value. Each owner also keeps a separate strong key +/// and value. Dead carriers exist so `next` can name those objects; they are +/// not written into root slots, and a judged-dead handle is never a lookup +/// key or a `next` cursor. Group counts stay separate. The owners window +/// reports the heads and edges that walk visited. `pulse(1)` is one unit and +/// does not describe that window. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Group { + Keys, + Values, + KvDeadKey, + KvDeadValue, +} + +impl Group { + fn mode(self) -> &'static str { + match self { + Group::Keys => "k", + Group::Values => "v", + Group::KvDeadKey | Group::KvDeadValue => "kv", + } + } + + fn index(self) -> usize { + match self { + Group::Keys => 0, + Group::Values => 1, + Group::KvDeadKey => 2, + Group::KvDeadValue => 3, + } + } + + fn metatable_slot(self) -> usize { + match self { + Group::Keys => 0, + Group::Values => 1, + Group::KvDeadKey | Group::KvDeadValue => 2, + } + } +} + +enum WeakEdge { + DeadKey { + carrier: Value, + }, + NamedDead { + value: super::super::TableRef, + carrier: Value, + }, + RootedKeyDeadValue { + key: super::super::TableRef, + key_carrier: Value, + value: super::super::TableRef, + value_carrier: Value, + }, +} + +struct MixedOwner { + owner: super::super::TableRef, + keep_key: super::super::TableRef, + keep_key_carrier: Value, + keep_value: super::super::TableRef, + keep_value_carrier: Value, + group: Group, + weak: WeakEdge, +} + +struct Mixed { + heap: LuaHeap, + owners: Vec, + dead: Vec, + nodes: u32, + edges: u32, +} + +fn build_mixed(shared_metatable: bool) -> Mixed { + let owners_n = MIXED_OWNERS * 4; + let metatables = if shared_metatable { 3 } else { owners_n }; + let nodes = metatables + owners_n * 4 + MIXED_OWNERS; + let roots = metatables + owners_n * 3 + MIXED_OWNERS; + let edges = metatables + owners_n * 3; + let mut heap = LuaHeap::new(limits(nodes, roots, edges)); + let mut rooted = Vec::new(); + let mut shared = [None, None, None]; + let mut owners = Vec::new(); + let mut dead = Vec::new(); + let order = [ + Group::Keys, + Group::Values, + Group::KvDeadKey, + Group::KvDeadValue, + ]; + for _ in 0..MIXED_OWNERS { + for group in order { + let metatable = if let Some(existing) = shared[group.metatable_slot()] + && shared_metatable + { + existing + } else { + let table = heap.alloc().expect("metatable"); + heap.set_mode_scalar(table, Value::string(group.mode())) + .expect("mode"); + rooted.push(table); + if shared_metatable { + shared[group.metatable_slot()] = Some(table); + } + table + }; + let owner = heap.alloc().expect("owner"); + let keep_key = heap.alloc().expect("keep key"); + let keep_value = heap.alloc().expect("keep value"); + let dead_table = heap.alloc().expect("dead"); + let keep_key_carrier = heap.issue_carrier(keep_key).expect("keep key carrier"); + let keep_value_carrier = heap.issue_carrier(keep_value).expect("keep value carrier"); + let dead_carrier = heap.issue_carrier(dead_table).expect("dead carrier"); + assert_ne!(keep_key, dead_table); + assert_ne!(keep_value, dead_table); + heap.set_metatable(owner, Some(metatable)) + .expect("metatable"); + heap.set_object_edge(owner, keep_key, keep_value) + .expect("keep"); + heap.set_named_edge(dead_table, "self", dead_table) + .expect("cycle"); + let weak = match group { + Group::Keys | Group::KvDeadKey => { + heap.set_object_edge(owner, dead_table, keep_value) + .expect("dead key"); + WeakEdge::DeadKey { + carrier: dead_carrier, + } + } + Group::Values => { + heap.set_named_edge(owner, "orphan", dead_table) + .expect("orphan"); + WeakEdge::NamedDead { + value: dead_table, + carrier: dead_carrier, + } + } + Group::KvDeadValue => { + let held = heap.alloc().expect("held key"); + let held_carrier = heap.issue_carrier(held).expect("held carrier"); + assert_ne!(held, dead_table); + assert_ne!(held, keep_key); + heap.set_object_edge(owner, held, dead_table) + .expect("dead value"); + rooted.push(held); + WeakEdge::RootedKeyDeadValue { + key: held, + key_carrier: held_carrier, + value: dead_table, + value_carrier: dead_carrier, + } + } + }; + rooted.push(owner); + rooted.push(keep_key); + rooted.push(keep_value); + dead.push(dead_table); + owners.push(MixedOwner { + owner, + keep_key, + keep_key_carrier, + keep_value, + keep_value_carrier, + group, + weak, + }); + } + } + assert_eq!(owners.len() as u32, owners_n); + assert_eq!(dead.len() as u32, owners_n); + root_all(&mut heap, &rooted); + let stats = heap.stats(); + assert_eq!(stats.node_slots, nodes, "node accounting"); + assert_eq!(stats.edge_slots, edges, "edge accounting"); + assert_eq!(rooted.len() as u32, roots, "root accounting"); + Mixed { + heap, + owners, + dead, + nodes, + edges, + } +} + +fn finish_snapshot(session: &mut SweepSession<'_>, nodes: u32) { + let one = session.pulse(1); + assert_eq!(one.spent.total(), 1, "one pulse is one unit"); + assert_eq!(one.spent.selection, 1); + let rest = session.pulse(u64::from(nodes) - 1); + assert_eq!(rest.spent.selection, u64::from(nodes) - 1); + let snapshot = session.pulse(u64::from(nodes)); + assert_eq!(snapshot.spent.snapshot, u64::from(nodes)); + assert_eq!(snapshot.spent.heads, 0); + assert_eq!(snapshot.spent.edges, 0); + let held = session.pulse(0); + assert_eq!(held.spent.total(), 0); + assert!(!held.finished); +} + +fn assert_keep(view: &super::WeakView<'_>, owner: &MixedOwner) { + assert_eq!( + view.object(owner.owner, owner.keep_key).expect("keep"), + Some(owner.keep_value), + "kept key and value" + ); + assert!(view.alive(owner.keep_key).expect("keep key")); + assert!(view.alive(owner.keep_value).expect("keep value")); + let started = view.next(owner.owner, &Value::Null).expect("keep next"); + let (key, value) = started.expect("keep pair"); + assert_eq!(key, owner.keep_key_carrier); + assert_eq!(value, owner.keep_value_carrier); +} + +fn weak_visible(view: &super::WeakView<'_>, owner: &MixedOwner) -> bool { + match &owner.weak { + WeakEdge::DeadKey { carrier } => { + let found = view + .next(owner.owner, &owner.keep_key_carrier) + .expect("dead key next"); + match found { + Some((key, value)) => { + assert_eq!(key, *carrier); + assert_eq!(value, owner.keep_value_carrier); + true + } + None => false, + } + } + WeakEdge::NamedDead { value, carrier } => { + let named = view.named(owner.owner, "orphan").expect("orphan"); + let found = view + .next(owner.owner, &owner.keep_key_carrier) + .expect("orphan next"); + match (named, found) { + (Some(found_value), Some((key, got))) => { + assert_eq!(found_value, *value); + assert_eq!(key, Value::string("orphan")); + assert_eq!(got, *carrier); + true + } + (None, None) => false, + _ => panic!("orphan lookup and next diverged"), + } + } + WeakEdge::RootedKeyDeadValue { + key, + key_carrier, + value, + value_carrier, + } => { + assert!(view.alive(*key).expect("rooted key")); + let got = view.object(owner.owner, *key).expect("rooted key lookup"); + let found = view + .next(owner.owner, &owner.keep_key_carrier) + .expect("dead value next"); + match (got, found) { + (Some(found_value), Some((next_key, next_value))) => { + assert_eq!(found_value, *value); + assert_eq!(next_key, *key_carrier); + assert_eq!(next_value, *value_carrier); + true + } + (None, None) => false, + _ => panic!("object lookup and next diverged"), + } + } + } +} + +fn group_counts(view: &super::WeakView<'_>, owners: &[MixedOwner]) -> [u32; 4] { + let mut counts = [0u32; 4]; + for owner in owners { + assert_keep(view, owner); + if weak_visible(view, owner) { + counts[owner.group.index()] += 1; + } + } + counts +} + +fn reject_dead(view: &super::WeakView<'_>, dead: &[super::super::TableRef]) { + for table in dead { + assert!(matches!(view.alive(*table), Err(ObserveError::JudgedDead))); + assert!(matches!( + view.named(*table, "self"), + Err(ObserveError::JudgedDead) + )); + } +} + +fn publish_mixed(shared_metatable: bool) { + let mut graph = build_mixed(shared_metatable); + let modes = graph.heap.drain_mark(); + let mut session = SweepSession::start(&mut graph.heap, modes); + let before = session.meter(); + finish_snapshot(&mut session, graph.nodes); + { + let original = session.weak_view().expect("original"); + assert_eq!(original.publish(), WeakPublish::Original); + assert!(!original.finished()); + assert!(!original.release_started()); + assert_eq!(group_counts(&original, &graph.owners), [MIXED_OWNERS; 4]); + reject_dead(&original, &graph.dead); + } + + let (window_heads, window_edges) = { + let window = session.publish_owners().expect("published"); + assert_eq!(window.view.publish(), WeakPublish::Published); + assert!(!window.view.finished()); + assert!(!window.view.release_started()); + assert_eq!(window.spent.heads, u64::from(graph.nodes)); + assert_eq!(window.spent.edges, u64::from(graph.edges)); + assert_eq!(window.spent.selection, 0); + assert_eq!(window.spent.snapshot, 0); + assert_eq!(window.spent.releases, 0); + assert_eq!(window.spent.roots, 0); + assert_eq!( + window.spent.heads + window.spent.edges, + window.spent.total() + ); + assert_ne!(window.spent.total(), 1, "owners window is not one pulse"); + assert_eq!(group_counts(&window.view, &graph.owners), [0; 4]); + assert_eq!(window.view.occupying_dead(), graph.dead.len() as u32); + assert_eq!(window.view.dead_still_physical(), graph.dead.len() as u32); + reject_dead(&window.view, &graph.dead); + (window.spent.heads, window.spent.edges) + }; + + let held = session.pulse(0); + assert_eq!(held.spent.total(), 0); + assert!(!held.finished); + { + let published = session.weak_view().expect("still published"); + assert_eq!(published.publish(), WeakPublish::Published); + assert!(!published.release_started()); + assert_eq!(group_counts(&published, &graph.owners), [0; 4]); + assert_eq!(published.dead_still_physical(), graph.dead.len() as u32); + } + assert_eq!(session.stats().collections, 0); + + let first = graph + .dead + .iter() + .copied() + .min_by_key(|table| table.slot()) + .expect("dead"); + let release = session.pulse(1); + assert_eq!(release.spent.total(), 1); + assert_eq!(release.spent.releases, 1); + assert!(!release.finished); + assert!( + session.weak_view().is_none(), + "release is not a publish boundary" + ); + assert_eq!( + session.slot_physical(first.slot()), + Some((false, first.generation().saturating_add(1))) + ); + let mut still_physical = 0u32; + for table in &graph.dead { + if table.slot() == first.slot() { + continue; + } + assert_eq!( + session.slot_physical(table.slot()), + Some((true, table.generation())) + ); + still_physical += 1; + } + assert_eq!(still_physical, graph.dead.len() as u32 - 1); + finish_release(&mut session); + let after = session.meter(); + assert_eq!( + sweep_delta(&before, &after), + (window_heads, window_edges, 0, 0) + ); + assert_eq!(session.stats().collections, 1); + let _ = session.report(); +} + +#[test] +fn shared_modes_publish_interleaved_weak_groups_at_one_boundary() { + publish_mixed(true); +} + +#[test] +fn separate_modes_publish_interleaved_weak_groups_at_one_boundary() { + publish_mixed(false); +} + +#[test] +fn mixed_weak_observer_counts_one_deleted_entry() { + let mut graph = build_mixed(true); + let deleted = graph + .owners + .iter() + .find(|owner| owner.group == Group::Values) + .expect("value owner") + .owner; + graph + .heap + .set_named_scalar(deleted, "orphan", Value::Null) + .expect("delete one entry"); + let modes = graph.heap.drain_mark(); + let mut session = SweepSession::start(&mut graph.heap, modes); + finish_snapshot(&mut session, graph.nodes); + let original = session.weak_view().expect("original"); + assert_eq!(original.publish(), WeakPublish::Original); + assert_eq!( + group_counts(&original, &graph.owners), + [MIXED_OWNERS, MIXED_OWNERS - 1, MIXED_OWNERS, MIXED_OWNERS] + ); + let mut hidden = 0u32; + for owner in &graph.owners { + if owner.group != Group::Values { + continue; + } + let visible = weak_visible(&original, owner); + if owner.owner == deleted { + assert!(!visible); + hidden += 1; + } else { + assert!(visible); + } + } + assert_eq!(hidden, 1); +} From b0a8f18983da31ff4154d217e5e7c09d1c3bcd1d Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 20:59:56 +0800 Subject: [PATCH 105/225] fix(lua/heap): barrier a discovered field replace at the shared writer Ordinary set_edge replacement and the parked driver enqueue a strong table value once, from replace_edge_value. --- src/frontends/lua/heap/table.rs | 35 +++- src/frontends/lua/heap/table/mark.rs | 33 +++- tests/luajit_heap_runtime/parked_mark.rs | 229 +++++++++++++++++++++++ 3 files changed, 290 insertions(+), 7 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 0d1a715..5540949 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2241,11 +2241,23 @@ impl LuaHeap { } fn replace_edge_value(&mut self, owner: u32, index: u32, value: EdgeValue) { + let (old_gap, barrier) = { + let edge = self.edge_slots[index as usize] + .edge + .as_ref() + .expect("occupied edge record"); + let old_gap = edge.value.is_cursor_gap(); + let barrier = if self.mark.is_some() { + replaced_table_target(&edge.key, old_gap, &value) + } else { + None + }; + (old_gap, barrier) + }; let edge = self.edge_slots[index as usize] .edge .as_mut() .expect("occupied edge record"); - let old_gap = edge.value.is_cursor_gap(); self.payload_bytes -= value_payload(&edge.value); edge.value = value; let new_gap = edge.value.is_cursor_gap(); @@ -2256,6 +2268,9 @@ impl LuaHeap { _ => {} } self.note_mode_pointer(owner, index); + if let Some((slot, generation)) = barrier { + self.barrier_strong_field(owner, slot, generation); + } } fn rewrite_gap(&mut self, index: u32) { @@ -2290,6 +2305,24 @@ fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { matches!(key, EdgeKey::Object { slot: key_slot, .. } if *key_slot == slot) } +/// Ordinary non-gap field whose new value is a table. Reserved fields, +/// object keys, gaps, and non-table values stay out of the gray queue. +fn replaced_table_target(key: &EdgeKey, old_gap: bool, value: &EdgeValue) -> Option<(u32, u32)> { + if old_gap { + return None; + } + let EdgeKey::Field(field) = key else { + return None; + }; + if *field == LuaHeap::MODE_FIELD || *field == CELL_EDGE { + return None; + } + match value { + EdgeValue::Table { slot, generation } => Some((*slot, *generation)), + _ => None, + } +} + #[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/budgeted_mark.rs"] mod budgeted_mark; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index 451e338..909a64a 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -16,7 +16,9 @@ //! Roots and Gray open an ordinary field delete, an ordinary field write on //! an owner that is not yet marked, an in-place replacement of an existing //! non-gap ordinary field on an already marked owner, and a fixed root-slot -//! update through the typed root writers. New keys, gap resurrection, +//! update through the typed root writers. The shared field replacement +//! applies that barrier, so an ordinary `set_edge` of an existing field uses +//! the same gray queue. New keys, gap resurrection, //! allocation, rollback, metatable and `__mode` writes, root-frame changes, //! internal closure edges, the private cell edge, and token edits stay closed. //! A refused edit returns before it changes the heap. @@ -306,6 +308,7 @@ impl<'a> ParkedMark<'a> { /// In-place replacement of one existing non-gap field. One key lookup. /// A missing key or a cursor gap is refused before any record changes. /// This does not insert, append, or reclaim another owner's gap. + /// The shared writer barriers the table value; this path does not enqueue again. fn replace_discovered_field( &mut self, from: TableRef, @@ -332,8 +335,6 @@ impl<'a> ParkedMark<'a> { }, ); self.heap.scan.parked_edge_writes += 1; - self.heap - .barrier_strong_field(from.slot(), to.slot(), to.generation()); Ok(()) } @@ -367,6 +368,15 @@ impl<'a> ParkedMark<'a> { self.heap.write_upvalue_root(frame, slot, handle) } + /// Test borrow of the heap while saved mark state stays on it. + /// + /// `LuaHeap::set_edge` can replace an existing field through this borrow. + /// It is not a production entry and is absent outside tests. + #[cfg(test)] + pub(super) fn with_saved_heap(&mut self, body: impl FnOnce(&mut LuaHeap) -> R) -> R { + body(self.heap) + } + pub(super) fn scanning_owner(&self) -> Option { self.heap.mark.as_ref().and_then(|state| state.owner) } @@ -799,6 +809,13 @@ fn enqueue_barrier_target( } } +/// Reads the mark bit of a table owner. No chain walk and no scan counter. +fn discovered_table(heap: &LuaHeap, owner: u32) -> bool { + heap.slots.get(owner as usize).is_some_and(|slot| { + slot.kind == HandleKind::Table && matches!(slot.state, SlotState::Live { marked: true }) + }) +} + /// Reads the reset-time mode cache. No metatable follow and no scan counter. fn cached_values_weak(heap: &LuaHeap, state: &MarkState, owner: u32) -> bool { if heap.metatable_edges == 0 { @@ -879,13 +896,17 @@ impl LuaHeap { } /// Marks a strong table value written into an already discovered field. - /// Weak values stay on the cached mode and are not followed. This does - /// not call `owner_mode` and does not move either cursor. + /// Weak values stay on the cached mode and are not followed. An owner + /// that is not yet marked does not enter the gray queue. This does not + /// call `owner_mode` and does not move either cursor. pub(super) fn barrier_strong_field(&mut self, owner: u32, slot: u32, generation: u32) { let Some(mut state) = self.mark.take() else { return; }; - if state.mutation_open() && !cached_values_weak(self, &state, owner) { + if state.mutation_open() + && discovered_table(self, owner) + && !cached_values_weak(self, &state, owner) + { enqueue_barrier_target(self, &mut state, slot, generation, HandleKind::Table); } self.mark = Some(state); diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index 6012d0b..1b0a85a 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -1032,6 +1032,11 @@ fn barrier_black_owner_keeps_the_cycle_until_release() { before.parked_edge_writes + 1 ); assert_write_did_not_scan(&before, &parked.meter()); + assert_eq!( + parked.meter().node_slot_visits, + before.node_slot_visits + 2, + "the shared writer followed the new target once" + ); assert!( !parked.marked(graph.child), "the write marked an unprocessed child" @@ -1107,6 +1112,11 @@ fn barrier_gray_owner_keeps_the_cycle_and_the_pending_successor() { before.parked_edge_writes + 1 ); assert_write_did_not_scan(&before, &parked.meter()); + assert_eq!( + parked.meter().node_slot_visits, + before.node_slot_visits + 2, + "the shared writer followed the new target once" + ); assert!( !parked.marked(successor), "the write marked the pending successor" @@ -1615,3 +1625,222 @@ fn barrier_refused_root_write_leaves_the_slot_and_meter() { assert_eq!(parked.meter().parked_barrier_marks, 0); assert_eq!(parked.meter().mark_passes, 1); } + +/// Raw `set_edge` on a scanned owner. The write must succeed in place. +/// Keeping the white cycle is the product result; collecting it is the miss. +#[test] +fn raw_set_edge_on_scanned_owner_keeps_the_strong_cycle() { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let graph = plant_strong_owner(&mut heap, false); + let (mut parked, index) = pause_on_owner_edge(&mut heap, graph.owner, KEY_REPLACED); + let scanning = charge_pending(&mut parked); + assert_eq!(scanning, graph.owner.slot()); + assert_eq!(parked.phase_name(), "gray"); + assert!(parked.mutation_open()); + assert!( + parked.marked(graph.owner), + "the scanned owner is already marked" + ); + assert!(!parked.marked(graph.cycle.p), "P is only weakly reachable"); + assert!( + !parked.marked(graph.child), + "the unprocessed child is not marked by setup" + ); + let pending = parked.pending(); + let before = parked.meter(); + parked.with_saved_heap(|heap| { + heap.set_edge(graph.owner, KEY_REPLACED, graph.cycle.p) + .expect("raw in-place replace"); + }); + assert_eq!(parked.field_index(graph.owner, KEY_REPLACED), Some(index)); + assert_eq!( + parked.edge(graph.owner, KEY_REPLACED).expect("replaced"), + Some(graph.cycle.p) + ); + assert_eq!( + parked + .edge(graph.owner, KEY_KEPT) + .expect("original successor"), + Some(graph.kept) + ); + assert!( + same_pending(parked.pending(), pending), + "the owner edge cursor moved" + ); + assert_eq!(parked.scanning_owner(), Some(graph.owner.slot())); + assert_eq!(parked.meter().parked_edge_writes, before.parked_edge_writes); + assert_write_did_not_scan(&before, &parked.meter()); + assert!( + !parked.marked(graph.child), + "the write marked an unprocessed child" + ); + let visit_delta = parked.meter().node_slot_visits - before.node_slot_visits; + let pushed_delta = parked.meter().scratch.work_pushed - before.scratch.work_pushed; + let barrier_delta = parked.meter().parked_barrier_marks - before.parked_barrier_marks; + assert_one_more_pulse_unit(&mut parked); + let view = finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + cycle_kept(&heap, &graph.cycle), + "{}", + cycle_lost_message(&heap, &graph.cycle, index) + ); + assert_cycle_identity(&heap, &graph.cycle); + assert_eq!( + barrier_delta, 1, + "the shared gray queue marked the new target once" + ); + assert_eq!( + visit_delta, 2, + "one barrier follow reads the target slot twice" + ); + assert_eq!( + pushed_delta, 1, + "only the new target joined gray at the write" + ); + assert_eq!(heap.scan.parked_barrier_marks, 1); + assert_eq!(heap.scan.parked_edge_writes, 0); + assert_eq!(view.mark_passes, 1); + assert_eq!(heap.scan.mark_passes, 1); + assert!(heap.alive(graph.owner) && heap.alive(graph.kept) && heap.alive(graph.child)); + heap.clear_edge(graph.owner, &super::EdgeKey::Field(KEY_REPLACED)); + heap.collect(); + assert!( + !heap.alive(graph.cycle.p) && !heap.alive(graph.cycle.q) && !heap.alive(graph.cycle.r), + "clearing the replaced field did not release the cycle" + ); + assert!(heap.alive(graph.owner) && heap.alive(graph.kept)); +} + +#[test] +fn raw_set_edge_on_a_weak_owner_does_not_keep_the_cycle() { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let owner = heap.alloc().expect("weak owner"); + let old = heap.alloc().expect("old"); + let successor = heap.alloc().expect("successor"); + let cycle = plant_cycle(&mut heap); + heap.set_metatable(owner, Some(cycle.mt)) + .expect("weak owner"); + heap.set_edge(owner, KEY_REPLACED, old).expect("weak field"); + heap.set_edge(owner, KEY_SUCCESSOR, successor) + .expect("weak successor"); + let frame = heap.enter_roots(4).expect("frame"); + heap.write_root(frame, 0, owner).expect("root owner"); + heap.write_root(frame, 1, cycle.watch).expect("root watch"); + heap.write_root(frame, 2, cycle.mt).expect("root metatable"); + heap.write_root(frame, 3, successor) + .expect("keep the successor readable"); + let (mut parked, index) = pause_on_owner_edge(&mut heap, owner, KEY_SUCCESSOR); + charge_pending(&mut parked); + assert!(parked.marked(owner)); + assert_eq!(parked.phase_name(), "gray"); + let field = parked + .field_index(owner, KEY_REPLACED) + .expect("replaced field"); + assert_ne!(field, index); + let before = parked.meter(); + let pending = parked.pending(); + parked.with_saved_heap(|heap| { + heap.set_edge(owner, KEY_REPLACED, cycle.p) + .expect("raw replace"); + }); + assert_eq!(parked.field_index(owner, KEY_REPLACED), Some(field)); + assert_eq!( + parked.edge(owner, KEY_REPLACED).expect("replaced"), + Some(cycle.p) + ); + assert!( + same_pending(parked.pending(), pending), + "the owner edge cursor moved" + ); + assert_eq!( + parked.meter().parked_barrier_marks, + before.parked_barrier_marks + ); + assert_eq!(parked.meter().parked_edge_writes, before.parked_edge_writes); + assert_eq!( + parked.meter().scratch.work_pushed, + before.scratch.work_pushed + ); + assert_write_did_not_scan(&before, &parked.meter()); + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + !cycle_kept(&heap, &cycle), + "a weak raw replace kept the cycle at record {field}" + ); + assert!(!heap.alive(cycle.orphan)); + assert!(heap.alive(owner) && heap.alive(successor)); + assert_eq!(heap.scan.parked_barrier_marks, 0); + assert_eq!(heap.scan.parked_edge_writes, 0); + assert_eq!(heap.scan.mark_passes, 1); +} + +#[test] +fn raw_set_edge_on_an_unmarked_owner_waits_for_normal_discovery() { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let later = heap.alloc().expect("later"); + let owner = heap.alloc().expect("unmarked owner"); + let old = heap.alloc().expect("old"); + heap.set_edge(later, KEY_KEPT, owner) + .expect("later to owner"); + heap.set_edge(owner, KEY_REPLACED, old).expect("field"); + let cycle = plant_cycle(&mut heap); + let frame = heap.enter_roots(3).expect("frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 1, cycle.watch).expect("root watch"); + heap.write_root(frame, 2, cycle.mt).expect("root metatable"); + let mut parked = ParkedMark::start(&mut heap).expect("park"); + let later_edge = parked.field_index(later, KEY_KEPT).expect("later edge"); + pause_at(&mut parked, later.slot(), later_edge); + assert_eq!(parked.phase_name(), "gray"); + assert!( + !parked.marked(owner), + "the owner is still ahead of the cursor" + ); + assert!(!parked.marked(cycle.p)); + let field = parked + .field_index(owner, KEY_REPLACED) + .expect("owner field"); + let pending = parked.pending(); + let before = parked.meter(); + parked.with_saved_heap(|heap| { + heap.set_edge(owner, KEY_REPLACED, cycle.p) + .expect("raw replace"); + }); + assert_eq!(parked.field_index(owner, KEY_REPLACED), Some(field)); + assert_eq!( + parked.edge(owner, KEY_REPLACED).expect("replaced"), + Some(cycle.p) + ); + assert!(!parked.marked(owner)); + assert!(!parked.marked(cycle.p)); + assert!( + same_pending(parked.pending(), pending), + "the pending cursor moved" + ); + assert_eq!( + parked.meter().parked_barrier_marks, + before.parked_barrier_marks + ); + assert_eq!(parked.meter().parked_edge_writes, before.parked_edge_writes); + assert_eq!( + parked.meter().scratch.work_pushed, + before.scratch.work_pushed + ); + assert_write_did_not_scan(&before, &parked.meter()); + finish(&mut parked); + parked.complete().expect("sweep"); + drop(parked); + assert!( + cycle_kept(&heap, &cycle) && heap.scan.parked_barrier_marks == 0, + "unmarked owner was not discovered by the later scan, or the write barrier ran; {}", + cycle_lost_message(&heap, &cycle, field) + ); + assert_cycle_identity(&heap, &cycle); + assert!(heap.alive(later) && heap.alive(owner)); + assert_eq!(heap.scan.parked_edge_writes, 0); + assert_eq!(heap.scan.mark_passes, 1); +} From 7216459a5c22146634696b69679bd9ecb70df7ff Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 21:49:59 +0800 Subject: [PATCH 106/225] feat(lua/heap): park an incomplete mark across windows Leave the unfinished private mark on the heap when the exclusive driver is parked, and resume that same cursor. Drop and cancel still discard. A full collect drops any saved mark before marking from the current roots. --- src/frontends/lua/heap/table.rs | 7 + src/frontends/lua/heap/table/mark.rs | 45 +- tests/luajit_heap_runtime/parked_lifecycle.rs | 567 ++++++++++++++++++ 3 files changed, 612 insertions(+), 7 deletions(-) create mode 100644 tests/luajit_heap_runtime/parked_lifecycle.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 5540949..18b2b05 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2041,7 +2041,11 @@ impl LuaHeap { }) } + /// Drops any parked mark, then marks from the current roots. + /// A later close failure does not put that mark back. fn mark_reachable(&mut self) -> MarkSnapshot { + let abandoned = self.mark.take(); + drop(abandoned); self.drain_mark() } @@ -2333,6 +2337,9 @@ mod budgeted_sweep; #[path = "../../../../tests/luajit_heap_runtime/budgeted_token_scan.rs"] mod budgeted_token_scan; +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/parked_lifecycle.rs"] +mod parked_lifecycle; #[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/parked_mark.rs"] mod parked_mark; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index 909a64a..b4e108f 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -1,10 +1,12 @@ //! Pausable mark. Progress lives in [`MarkState`]. One stepper drains it. //! //! A long-borrow session holds the heap until it is dropped or swept. The -//! parked driver stores that same state on the heap between pulses, so a -//! restricted edit can run without handing out `&mut LuaHeap`. Done is not -//! left for the caller: the driver sweeps in that same window and returns -//! only a report. Drop and cancel clear the saved state and do not sweep. +//! parked driver stores that same state on the heap between pulses. `park` +//! consumes the driver and leaves an incomplete mark there; `resume` borrows +//! it and does not create another. Drop and cancel still clear the saved +//! state and do not sweep. Done is not left for the caller: the driver sweeps +//! in that same window and returns only a report. A full collect drops any +//! saved mark and starts again from reset. //! //! A pulse spends a caller budget on these units, each checked before it runs: //! one slot reset, one mode-edge open, one mode-string byte (including a NUL), @@ -84,12 +86,15 @@ pub(super) struct MarkSession<'a> { heap: &'a mut LuaHeap, } -/// Exclusive pure-heap mark. The caller does not receive `&mut LuaHeap` until -/// this driver is dropped, cancelled, or has swept a finished mark. +/// Exclusive pure-heap mark. `park` consumes the driver and can leave an +/// incomplete mark on the heap for `resume`. Drop and cancel still clear it. +/// Done is swept in this window and is not parked. pub(super) struct ParkedMark<'a> { heap: &'a mut LuaHeap, done: Option, swept: bool, + /// Set only by a successful `park`, so Drop does not clear that mark. + keep: bool, } impl MarkState { @@ -193,9 +198,33 @@ impl<'a> ParkedMark<'a> { heap, done: None, swept: false, + keep: false, }) } + /// Borrows a mark this heap already holds. Absent is `None`. + /// This does not create, reset, write, or replace that mark. + pub(super) fn resume(heap: &'a mut LuaHeap) -> Option { + heap.mark.as_ref()?; + Some(Self { + heap, + done: None, + swept: false, + keep: false, + }) + } + + /// Leaves an incomplete mark on the heap and ends this borrow. + /// Done, or a heap with no mark, is refused. Refusal does not sweep and + /// does not return a collection report. + pub(super) fn park(mut self) -> Result<(), HeapError> { + if self.heap.mark.is_none() || self.done.is_some() || self.swept { + return Err(HeapError::MarkDenied); + } + self.keep = true; + Ok(()) + } + pub(super) fn meter(&self) -> super::ScanMeter { self.heap.scan } @@ -512,7 +541,9 @@ impl<'a> ParkedMark<'a> { impl Drop for ParkedMark<'_> { fn drop(&mut self) { - self.heap.mark = None; + if !self.keep { + self.heap.mark = None; + } } } diff --git a/tests/luajit_heap_runtime/parked_lifecycle.rs b/tests/luajit_heap_runtime/parked_lifecycle.rs new file mode 100644 index 0000000..9ff33e9 --- /dev/null +++ b/tests/luajit_heap_runtime/parked_lifecycle.rs @@ -0,0 +1,567 @@ +//! Cross-window park and resume for one private mark. +//! +//! `park` consumes the exclusive driver. Drop and cancel still discard. +//! A full collect drops saved progress and marks again from the current roots. + +use super::{ + HeapError, HeapLimits, LuaHeap, ParkedMark, PendingScan, RootFrameId, ScanMeter, TableRef, +}; +use vm::Value; + +const HARNESS_BOUND: u32 = 64; +const KEY_X: u32 = 1; +const KEY_Y: u32 = 5; +const KEY_Z: u32 = 3; +const WEAK_KEY: u32 = 1; + +fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { + HeapLimits { + nodes, + roots, + edges, + max_generation: 8, + } +} + +fn pause_at(parked: &mut ParkedMark<'_>, owner: u32, cursor: u32) -> PendingScan { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!(!view.finished, "mark finished before the pending record"); + assert_eq!(view.meter.sweep_edge_checks, 0, "a pulse must not sweep"); + assert_eq!( + view.meter.mark_passes, 1, + "pause stays in the original pass" + ); + if let Some(pending) = parked.pending() + && pending.owner == owner + && pending.cursor == cursor + { + assert_eq!(parked.phase_name(), "gray"); + return pending; + } + } + panic!("pending record {cursor} on owner {owner} was not observed"); +} + +fn pulse_until_marked(parked: &mut ParkedMark<'_>, target: TableRef) { + for _ in 0..HARNESS_BOUND { + if parked.marked(target) { + assert_eq!(parked.meter().mark_passes, 1); + assert_eq!(parked.meter().sweep_edge_checks, 0); + return; + } + let view = parked.pulse(1); + assert!(!view.finished, "mark finished before the target was marked"); + assert_eq!(view.meter.sweep_edge_checks, 0); + } + panic!("target was not marked"); +} + +fn finish(parked: &mut ParkedMark<'_>) -> ScanMeter { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert_eq!(view.meter.sweep_edge_checks, 0, "a pulse must not sweep"); + assert_eq!(view.meter.mark_passes, 1); + if view.finished { + return view.meter; + } + } + panic!("mark did not finish within the harness bound"); +} + +struct Chain { + anchor: TableRef, + reached: TableRef, + pending_target: TableRef, + ahead: TableRef, + extra: TableRef, + y_index: u32, +} + +fn chain(heap: &mut LuaHeap) -> Chain { + let anchor = heap.alloc().expect("anchor"); + let reached = heap.alloc().expect("reached"); + let pending_target = heap.alloc().expect("pending"); + let ahead = heap.alloc().expect("ahead"); + let extra = heap.alloc().expect("extra"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, anchor).expect("root"); + heap.set_edge(anchor, KEY_X, reached).expect("reached edge"); + heap.set_edge(anchor, KEY_Y, pending_target) + .expect("pending edge"); + heap.set_edge(anchor, KEY_Z, ahead).expect("ahead edge"); + let y_index = heap + .find_key(anchor.slot(), &super::EdgeKey::Field(KEY_Y)) + .expect("pending record"); + Chain { + anchor, + reached, + pending_target, + ahead, + extra, + y_index, + } +} + +fn pause_chain(heap: &mut LuaHeap) -> (ParkedMark<'_>, Chain) { + let chain = chain(heap); + let mut parked = ParkedMark::start(heap).expect("start"); + let pending = pause_at(&mut parked, chain.anchor.slot(), chain.y_index); + assert_eq!(pending.cursor, chain.y_index); + assert!( + parked.marked(chain.reached), + "the edge before the cursor is marked" + ); + assert!( + !parked.marked(chain.pending_target), + "the pending edge is not marked yet" + ); + assert!( + !parked.marked(chain.ahead), + "the edge after the cursor is not marked" + ); + assert!( + !parked.marked(chain.extra), + "an unrooted node is not marked" + ); + (parked, chain) +} + +#[test] +fn second_start_is_refused_while_a_mark_is_parked() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let (parked, chain) = pause_chain(&mut heap); + let expected = (chain.anchor.slot(), chain.y_index); + parked.park().expect("park incomplete"); + + assert_eq!( + ParkedMark::start(&mut heap).err(), + Some(HeapError::MarkActive), + "a second start must be refused while parked progress remains" + ); + let resumed = ParkedMark::resume(&mut heap) + .expect("the refused start must leave the parked mark in place"); + assert_eq!( + resumed.pending().map(|scan| (scan.owner, scan.cursor)), + Some(expected), + "resume must see the same pending cursor" + ); +} + +#[test] +fn resume_keeps_the_pending_cursor_and_does_not_remark() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let (parked, chain) = pause_chain(&mut heap); + let expected = (chain.anchor.slot(), chain.y_index); + let before = parked.meter(); + assert_eq!(before.mark_passes, 1); + assert_eq!(parked.phase_name(), "gray"); + parked.park().expect("park incomplete"); + + let mut resumed = ParkedMark::resume(&mut heap).expect("resume the parked mark"); + assert_eq!( + resumed.pending().map(|scan| (scan.owner, scan.cursor)), + Some(expected), + "resume must find the same pending cursor" + ); + assert_eq!(resumed.phase_name(), "gray"); + assert_eq!( + resumed.meter().mark_passes, + 1, + "resume must not start another pass" + ); + assert!(resumed.marked(chain.reached)); + assert!(!resumed.marked(chain.pending_target)); + assert!(!resumed.marked(chain.ahead)); + + let held = resumed.meter(); + let view = resumed.pulse(0); + assert!(!view.finished, "a zero budget must not finish the mark"); + assert_eq!( + resumed.meter(), + held, + "a zero budget must not read the graph" + ); + assert_eq!( + resumed.pending().map(|scan| (scan.owner, scan.cursor)), + Some(expected), + "a zero budget must not move the cursor" + ); + + let _meter = finish(&mut resumed); + let report = resumed.complete().expect("sweep the finished mark"); + let swept = resumed.meter().sweep_edge_checks; + assert!(swept > 0, "the completion window sweeps"); + assert!( + resumed.park().is_err(), + "an already swept mark must not park" + ); + assert!(ParkedMark::resume(&mut heap).is_none()); + assert!(heap.alive(chain.anchor)); + assert!(heap.alive(chain.reached)); + assert!(heap.alive(chain.pending_target)); + assert!(heap.alive(chain.ahead)); + assert!( + !heap.alive(chain.extra), + "sweep must collect the unrooted node" + ); + assert_eq!(report.live_nodes, 4, "anchor and its three fields remain"); + assert_eq!( + heap.stats().collections, + 1, + "the completion window sweeps once" + ); + assert_eq!( + heap.take_scan_meter().sweep_edge_checks, + swept, + "refusing to park a swept mark must not sweep again" + ); +} + +#[test] +fn drop_cancel_and_completed_park_do_not_resume() { + let mut dropped = LuaHeap::new(limits(8, 2, 8)); + { + let (parked, _) = pause_chain(&mut dropped); + drop(parked); + } + assert!(ParkedMark::resume(&mut dropped).is_none()); + assert!( + ParkedMark::start(&mut dropped).is_ok(), + "drop must not leave a mark" + ); + + let mut cancelled = LuaHeap::new(limits(8, 2, 8)); + let (parked, _) = pause_chain(&mut cancelled); + parked.cancel(); + assert!(ParkedMark::resume(&mut cancelled).is_none()); + assert_eq!(cancelled.stats().collections, 0); + + let mut finished = LuaHeap::new(limits(8, 2, 8)); + let (mut parked, chain) = pause_chain(&mut finished); + let _meter = finish(&mut parked); + assert_eq!(parked.phase_name(), "done"); + assert_eq!(parked.meter().sweep_edge_checks, 0); + assert!( + parked.park().is_err(), + "a finished mark must not park, and refusal must not be a collect report" + ); + assert!(ParkedMark::resume(&mut finished).is_none()); + assert!(finished.alive(chain.extra), "refusing Done must not sweep"); + assert_eq!(finished.stats().collections, 0); + assert_eq!(finished.take_scan_meter().sweep_edge_checks, 0); + assert!( + ParkedMark::start(&mut finished).is_ok(), + "Done must not escape as a saved mark" + ); +} + +struct Observed { + frame: RootFrameId, + keeper: TableRef, + watch: TableRef, + metatable: TableRef, + target: TableRef, +} + +fn plant(heap: &mut LuaHeap, root_target: bool) -> Observed { + let keeper = heap.alloc().expect("keeper"); + let target = heap.alloc().expect("target"); + let metatable = heap.alloc().expect("metatable"); + let watch = heap.alloc().expect("watch"); + heap.set_mode_scalar(metatable, Value::string("v")) + .expect("weak values"); + heap.set_metatable(watch, Some(metatable)) + .expect("metatable"); + heap.set_edge(watch, WEAK_KEY, target).expect("weak target"); + let frame = heap.enter_roots(3).expect("frame"); + heap.write_root(frame, 0, keeper).expect("root keeper"); + heap.write_root(frame, 1, watch).expect("root watch"); + if root_target { + heap.write_root(frame, 2, target).expect("root target"); + } + Observed { + frame, + keeper, + watch, + metatable, + target, + } +} + +fn assert_current_roots(heap: &LuaHeap, observed: &Observed, target_alive: bool) { + assert!(heap.alive(observed.keeper)); + assert!(heap.alive(observed.watch)); + assert!(heap.alive(observed.metatable)); + assert_eq!(heap.alive(observed.target), target_alive); + assert_eq!( + heap.edge(observed.watch, WEAK_KEY) + .expect("weak edge") + .is_some(), + target_alive, + "the weak observer must not keep a target the current roots did not mark" + ); +} + +#[test] +fn full_collect_discards_parked_marks_and_matches_current_roots() { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let observed = plant(&mut heap, true); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + pulse_until_marked(&mut parked, observed.target); + parked.park().expect("park incomplete"); + heap.clear_root(observed.frame, 2) + .expect("drop the last strong root"); + let parked_work = heap.take_scan_meter(); + assert_eq!( + parked_work.mark_passes, 1, + "parked work is a separate meter read" + ); + assert_eq!(parked_work.sweep_edge_checks, 0, "park did not sweep"); + + let report = heap.collect(); + assert_current_roots(&heap, &observed, false); + assert!(ParkedMark::resume(&mut heap).is_none()); + assert_eq!(heap.stats().collections, 1); + let fresh = heap.take_scan_meter(); + assert_eq!(fresh.mark_passes, 1, "collect starts one new pass"); + assert!(fresh.sweep_edge_checks > 0, "collect sweeps"); + + let mut twin = LuaHeap::new(limits(8, 4, 8)); + let twin_observed = plant(&mut twin, false); + let twin_report = twin.collect(); + assert_current_roots(&twin, &twin_observed, false); + assert_eq!(twin_report.live_nodes, report.live_nodes); + assert_eq!(twin_report.marked_nodes, report.marked_nodes); + assert_eq!( + twin.take_scan_meter(), + fresh, + "re-mark matches a heap that never parked" + ); + + let mut contrast = LuaHeap::new(limits(8, 4, 8)); + let contrast_observed = plant(&mut contrast, true); + let mut contrast_parked = ParkedMark::start(&mut contrast).expect("start"); + pulse_until_marked(&mut contrast_parked, contrast_observed.target); + contrast_parked.park().expect("park incomplete"); + contrast + .clear_root(contrast_observed.frame, 2) + .expect("drop the last strong root"); + let mut resumed = ParkedMark::resume(&mut contrast).expect("resume keeps the old mark"); + let _meter = finish(&mut resumed); + let contrast_report = resumed.complete().expect("sweep the resumed mark"); + drop(resumed); + assert!( + contrast.alive(contrast_observed.target), + "resume must not clear a mark that already reached the target" + ); + assert_eq!( + contrast_report.live_nodes, 4, + "keeper, watch, metatable, and target" + ); + assert_eq!(contrast.stats().collections, 1); +} + +#[test] +fn host_collect_after_park_sweeps_from_current_roots() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + crate::heap::install(&mut host, crate::sweep_limits()).expect("install"); + let keeper_raw = crate::publish_raw(&mut host); + let keeper = crate::table_ref(&host, keeper_raw); + crate::root_table(&mut host, keeper); + let target_raw = crate::publish_raw(&mut host); + let target = crate::table_ref(&host, target_raw); + let frame = crate::heap::with_heap(&mut host, |heap| heap.enter_roots(1)).expect("frame"); + crate::heap::with_heap(&mut host, |heap| heap.write_root(frame, 0, target)).expect("root"); + crate::heap::with_heap(&mut host, |heap| { + let ahead = heap.alloc()?; + heap.set_edge(target, KEY_Y, ahead)?; + Ok(()) + }) + .expect("outgoing edge"); + let watch = crate::heap::with_heap(&mut host, |heap| { + let metatable = heap.alloc()?; + let watch = heap.alloc()?; + heap.set_mode_scalar(metatable, Value::string("v"))?; + heap.set_metatable(watch, Some(metatable))?; + heap.set_edge(watch, WEAK_KEY, target)?; + let watch_frame = heap.enter_roots(1)?; + heap.write_root(watch_frame, 0, watch)?; + Ok(watch) + }) + .expect("weak watch"); + + let saved = crate::heap::with_heap(&mut host, |heap| { + let mut parked = ParkedMark::start(heap)?; + let cursor = parked.field_index(target, KEY_Y).expect("outgoing record"); + let pending = pause_at(&mut parked, target.slot(), cursor); + assert!( + parked.marked(target), + "the scanning owner is already marked" + ); + let saved = (pending.owner, pending.cursor); + parked.park()?; + Ok(saved) + }) + .expect("park from the host window"); + + let refused = + crate::heap::with_heap(&mut host, |heap| Ok(ParkedMark::start(heap).is_err())) + .expect("start probe"); + assert!( + refused, + "a second start must be refused while the host window is parked" + ); + let same = crate::heap::with_heap(&mut host, |heap| { + let Some(parked) = ParkedMark::resume(heap) else { + return Ok(false); + }; + let pending = parked.pending().map(|scan| (scan.owner, scan.cursor)); + let same = + pending == Some(saved) && parked.marked(target) && parked.meter().mark_passes == 1; + parked.park()?; + Ok(same) + }) + .expect("resume probe"); + assert!(same, "resume must return the parked cursor as a scalar"); + + crate::heap::with_heap(&mut host, |heap| heap.clear_root(frame, 0)).expect("unroot"); + let parked_work = crate::heap::take_scan_meter(&mut host).expect("parked meter"); + assert_eq!(parked_work.mark_passes, 1); + assert_eq!(parked_work.sweep_edge_checks, 0); + + let report = crate::heap::collect(&mut host).expect("host collect"); + let collected = crate::heap::take_scan_meter(&mut host).expect("collect meter"); + assert_eq!(collected.mark_passes, 1, "host collect starts a new pass"); + assert!(collected.sweep_edge_checks > 0); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 1); + assert!(crate::heap::with_heap(&mut host, |heap| Ok(heap.alive(keeper))).expect("keeper")); + assert!(crate::heap::with_heap(&mut host, |heap| Ok(heap.alive(watch))).expect("watch")); + assert!(!crate::heap::with_heap(&mut host, |heap| Ok(heap.alive(target))).expect("target")); + assert!( + host.typed_resource_with_key::( + crate::resource_handle(keeper_raw), + &crate::heap::LuaTableResource::key(), + ) + .is_ok(), + "the rooted token stays open" + ); + assert!( + host.typed_resource_with_key::( + crate::resource_handle(target_raw), + &crate::heap::LuaTableResource::key(), + ) + .is_err(), + "host collect closes the unrooted token" + ); + let resumable = + crate::heap::with_heap(&mut host, |heap| Ok(ParkedMark::resume(heap).is_some())) + .expect("resume after collect"); + assert!( + !resumable, + "a finished host collect must not leave a parked mark" + ); + assert!(report.live_nodes >= 2, "keeper and the weak watch stay"); + }); +} + +#[test] +fn host_close_failure_drops_parked_progress_and_retries_from_roots() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + crate::heap::install(&mut host, crate::sweep_limits()).expect("install"); + let unrelated = host + .push_resource(crate::UnrelatedHostResource) + .expect("unrelated"); + let unrelated_raw = unrelated.handle().raw(); + let keeper_raw = crate::publish_raw(&mut host); + let keeper = crate::table_ref(&host, keeper_raw); + crate::root_table(&mut host, keeper); + let (doomed, frame) = crate::heap::with_heap(&mut host, |heap| { + let node = heap.alloc()?; + heap.bind_token(node, unrelated_raw)?; + let ahead = heap.alloc()?; + heap.set_edge(node, KEY_Y, ahead)?; + let frame = heap.enter_roots(1)?; + heap.write_root(frame, 0, node)?; + Ok((node, frame)) + }) + .expect("bind a foreign token"); + + let saved = crate::heap::with_heap(&mut host, |heap| { + let mut parked = ParkedMark::start(heap)?; + let cursor = parked.field_index(doomed, KEY_Y).expect("outgoing record"); + let pending = pause_at(&mut parked, doomed.slot(), cursor); + assert!( + parked.marked(doomed), + "the scanning owner is already marked" + ); + let saved = (pending.owner, pending.cursor); + parked.park()?; + Ok(saved) + }) + .expect("park before the failing collect"); + let same = crate::heap::with_heap(&mut host, |heap| { + let Some(parked) = ParkedMark::resume(heap) else { + return Ok(false); + }; + let pending = parked.pending().map(|scan| (scan.owner, scan.cursor)); + let same = pending == Some(saved) && parked.marked(doomed); + parked.park()?; + Ok(same) + }) + .expect("resume probe"); + assert!(same, "the parked cursor must still be there before collect"); + + crate::heap::with_heap(&mut host, |heap| heap.clear_root(frame, 0)).expect("unroot"); + let before_nodes = crate::heap::stats(&mut host).expect("before").live_nodes; + let parked_work = crate::heap::take_scan_meter(&mut host).expect("parked meter"); + assert_eq!(parked_work.sweep_edge_checks, 0); + + let error = crate::heap::collect(&mut host).expect_err("wrong resource type"); + crate::assert_type_mismatch(&error); + let failed = crate::heap::take_scan_meter(&mut host).expect("failed meter"); + assert_eq!(failed.sweep_edge_checks, 0, "close failure must not sweep"); + assert_eq!(failed.mark_passes, 1, "the failed collect marked again"); + assert_eq!( + crate::heap::stats(&mut host) + .expect("collections") + .collections, + 0 + ); + assert_eq!( + crate::heap::stats(&mut host).expect("nodes").live_nodes, + before_nodes + ); + assert!(crate::heap::with_heap(&mut host, |heap| Ok(heap.alive(keeper))).expect("keeper")); + assert!(crate::heap::with_heap(&mut host, |heap| Ok(heap.alive(doomed))).expect("doomed")); + assert!( + host.resource(&unrelated).is_ok(), + "the foreign resource stays open" + ); + let resumable = + crate::heap::with_heap(&mut host, |heap| Ok(ParkedMark::resume(heap).is_some())) + .expect("resume after failure"); + assert!(!resumable, "close failure must not restore the parked mark"); + + crate::heap::with_heap(&mut host, |heap| heap.unbind_token(doomed)) + .expect("fixture removes the foreign binding"); + let report = crate::heap::collect(&mut host).expect("retry after the obstacle is gone"); + assert_eq!(crate::heap::stats(&mut host).expect("retry").collections, 1); + assert!(crate::heap::with_heap(&mut host, |heap| Ok(heap.alive(keeper))).expect("keeper")); + assert!(!crate::heap::with_heap(&mut host, |heap| Ok(heap.alive(doomed))).expect("swept")); + assert!( + host.resource(&unrelated).is_ok(), + "the foreign resource is not a lua token" + ); + assert!( + host.typed_resource_with_key::( + crate::resource_handle(keeper_raw), + &crate::heap::LuaTableResource::key(), + ) + .is_ok() + ); + assert_eq!(report.live_nodes, 1, "only the rooted keeper remains"); + }); +} From 0907ef71b93f03dfde102c48ec4daa65640d1dba Mon Sep 17 00:00:00 2001 From: fffonion Date: Mon, 23 Nov 2026 23:08:27 +0800 Subject: [PATCH 107/225] feat(lua/heap): accept a safepoint root batch on the open mark Borrow a typed batch in the exclusive Roots or Gray window. Check the phase, the reserved root quota, and every handle before marking. Success enqueues through the existing gray queue and does not write a root slot or open a frame. --- src/frontends/lua/heap/table.rs | 14 +- src/frontends/lua/heap/table/mark.rs | 73 ++ tests/luajit_heap_runtime/safepoint_roots.rs | 787 +++++++++++++++++++ 3 files changed, 871 insertions(+), 3 deletions(-) create mode 100644 tests/luajit_heap_runtime/safepoint_roots.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 18b2b05..32f32d7 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -539,10 +539,15 @@ pub struct ScanMeter { /// Fixed root slots updated through `store_root` while a mark is parked. /// Not a pulse unit. A full collect leaves this at zero. pub parked_root_writes: u64, - /// Newly marked targets pushed to the parked gray queue by a write - /// barrier. An already-marked target does not increment this, and a weak - /// value is not pushed. Not a pulse unit. A full collect leaves this at zero. + /// Newly marked targets pushed to the parked gray queue by a write barrier + /// or a safepoint root batch. An already-marked target does not increment + /// this. Not a pulse unit. A full collect leaves this at zero. pub parked_barrier_marks: u64, + /// Entries accepted by a safepoint root batch, including duplicates. + /// A refused batch does not increment this. Precheck slot reads are not + /// counted here or in `node_slot_visits`. Not a pulse unit. A full collect + /// leaves this at zero. + pub parked_root_batch_accepts: u64, pub scratch: ScanScratch, } @@ -2343,3 +2348,6 @@ mod parked_lifecycle; #[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/parked_mark.rs"] mod parked_mark; +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/safepoint_roots.rs"] +mod safepoint_roots; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index b4e108f..9221e38 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -14,6 +14,12 @@ //! head, or one outgoing edge or gap. Target checks and the metatable check //! ride with the edge or the owner head. A zero budget does not read the graph. //! +//! A safepoint root batch is not one of those units. While Roots or Gray is +//! open, the batch checks the phase, the root quota, and every typed handle +//! before it marks anything. Those prechecks do not increment the scan meter. +//! Success then hands each entry to the existing gray queue. It does not write +//! a root slot, open a frame, copy the batch, or spend pulse budget. +//! //! Reset and mode pulses still spend that budget. They do not open mutation. //! Roots and Gray open an ordinary field delete, an ordinary field write on //! an owner that is not yet marked, an in-place replacement of an existing @@ -367,6 +373,64 @@ impl<'a> ParkedMark<'a> { Ok(()) } + /// Accepts a borrowed root batch in this exclusive window. + /// + /// Open only in Roots or Gray. Checks run in order: phase, then + /// `roots.len() + batch.len()` (no overflow, and not above `limits.roots`; + /// reserved empty slots and duplicate entries count), then each handle + /// through `require_live`, `require_closure`, or `require_upvalue`. Those + /// calls keep `WrongDomain`, `WrongKind`, and `StaleHandle`. The precheck + /// reads are not scan visits. A refusal does not mark, enqueue, move a + /// cursor, write a root slot, or change a success meter. + /// + /// Success hands each accepted entry, including a duplicate or an + /// already-marked handle, to the existing gray queue through + /// `enqueue_barrier_target` / `follow_one`. `follow_one` charges two + /// `node_slot_visits` per entry. Accepted entries are + /// `parked_root_batch_accepts`. A first enqueue reuses + /// `parked_barrier_marks`. `work_pushed` still counts every newly marked + /// node, whatever enqueued it. The borrowed slice is not stored. No frame + /// is opened, and the call does not spend pulse budget. + pub(super) fn accept_root_batch(&mut self, batch: &[Rooted]) -> Result<(), HeapError> { + self.gate_root_batch(batch)?; + if batch.is_empty() { + return Ok(()); + } + let mut state = self.heap.mark.take().expect("open mark"); + for rooted in batch { + let (slot, generation, kind) = rooted_identity(*rooted); + enqueue_barrier_target(self.heap, &mut state, slot, generation, kind); + } + self.heap.mark = Some(state); + self.heap.scan.parked_root_batch_accepts += + u64::try_from(batch.len()).expect("quota already checked the length"); + Ok(()) + } + + fn gate_root_batch(&self, batch: &[Rooted]) -> Result<(), HeapError> { + if self.done.is_some() || self.swept { + return Err(HeapError::MarkDenied); + } + let state = self.heap.mark.as_ref().ok_or(HeapError::MarkDenied)?; + if !state.mutation_open() { + return Err(HeapError::MarkDenied); + } + let occupied = u32::try_from(self.heap.roots.len()).map_err(|_| HeapError::RootCapacity)?; + let extra = u32::try_from(batch.len()).map_err(|_| HeapError::RootCapacity)?; + let end = occupied.checked_add(extra).ok_or(HeapError::RootCapacity)?; + if end > self.heap.limits.roots { + return Err(HeapError::RootCapacity); + } + for rooted in batch { + match *rooted { + Rooted::Table(handle) => self.heap.require_live(handle)?, + Rooted::Closure(handle) => self.heap.require_closure(handle)?, + Rooted::Upvalue(handle) => self.heap.require_upvalue(handle)?, + } + } + Ok(()) + } + pub(super) fn write_table_root( &mut self, frame: RootFrameId, @@ -825,6 +889,15 @@ fn owner_mode(heap: &mut LuaHeap, state: &mut MarkState, slot: u32) -> WeakMode WeakMode::default() } +/// Slot identity already stored on a typed root. This does not allocate a handle. +fn rooted_identity(rooted: Rooted) -> (u32, u32, HandleKind) { + match rooted { + Rooted::Table(handle) => (handle.slot(), handle.generation(), HandleKind::Table), + Rooted::Closure(handle) => (handle.slot(), handle.generation(), HandleKind::Closure), + Rooted::Upvalue(handle) => (handle.slot(), handle.generation(), HandleKind::Upvalue), + } +} + /// Counts a newly gray target. An already-marked slot does not increment. fn enqueue_barrier_target( heap: &mut LuaHeap, diff --git a/tests/luajit_heap_runtime/safepoint_roots.rs b/tests/luajit_heap_runtime/safepoint_roots.rs new file mode 100644 index 0000000..22a71d8 --- /dev/null +++ b/tests/luajit_heap_runtime/safepoint_roots.rs @@ -0,0 +1,787 @@ +//! Safepoint root batch on a resumed private mark. +//! +//! The batch is borrowed for one exclusive window. It does not write a root +//! slot or open a frame. A weak observer root is the phase gate; it must not +//! be what keeps a batch target alive. Precheck slot reads are not scan visits. +//! Visit and accept meters are sampled around the commit, before sweep. + +use super::{ + ClosureRef, HeapError, HeapLimits, LuaHeap, ParkedMark, RootFrameId, Rooted, ScanMeter, + TableRef, UpvalueRef, +}; +use vm::Value; + +const KEY_CHILD: u32 = 1; +const KEY_TARGET: u32 = 4; +const KEY_ORPHAN: u32 = 5; +const KEY_NEXT: u32 = 6; +const KEY_CLOSURE: u32 = 7; +const HARNESS_BOUND: u32 = 64; + +fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { + HeapLimits { + nodes, + roots, + edges, + max_generation: 8, + } +} + +struct Observed { + frame: RootFrameId, + later: TableRef, + child: TableRef, + target: TableRef, + successor: TableRef, + orphan: TableRef, +} + +fn observed(heap: &mut LuaHeap) -> Observed { + let later = heap.alloc().expect("later"); + let child = heap.alloc().expect("later child"); + heap.set_edge(later, KEY_CHILD, child).expect("later edge"); + let tail = heap.alloc().expect("tail"); + let mt = heap.alloc().expect("metatable"); + let watch = heap.alloc().expect("watch"); + let target = heap.alloc().expect("target"); + let successor = heap.alloc().expect("successor"); + let orphan = heap.alloc().expect("orphan"); + heap.set_edge(target, KEY_NEXT, successor) + .expect("target successor"); + heap.set_mode_scalar(mt, Value::string("v\0")) + .expect("weak values"); + heap.set_metatable(watch, Some(mt)) + .expect("watch metatable"); + heap.set_edge(watch, KEY_TARGET, target) + .expect("weak target"); + heap.set_edge(watch, KEY_ORPHAN, orphan) + .expect("weak orphan"); + let frame = heap.enter_roots(4).expect("observer frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 2, tail).expect("root tail"); + heap.write_root(frame, 3, watch).expect("root watch"); + Observed { + frame, + later, + child, + target, + successor, + orphan, + } +} + +fn pause_after_root_visits(parked: &mut ParkedMark<'_>, visits: u64) { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!(!view.finished, "mark finished before {visits} root visits"); + assert_eq!(view.meter.mark_passes, 1); + if parked.phase_name() == "roots" && parked.meter().root_slot_visits == visits { + return; + } + } + panic!( + "did not stop after {visits} root visits, phase {}", + parked.phase_name() + ); +} + +fn pause_at(parked: &mut ParkedMark<'_>, owner: u32, cursor: u32) { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!(!view.finished, "mark finished before the pending edge"); + assert_eq!(view.meter.mark_passes, 1); + if let Some(pending) = parked.pending() + && pending.owner == owner + && pending.cursor == cursor + { + assert_eq!(parked.phase_name(), "gray"); + return; + } + } + panic!("pending record {cursor} on owner {owner} was not observed"); +} + +fn finish(parked: &mut ParkedMark<'_>) -> ScanMeter { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert_eq!(view.meter.mark_passes, 1); + if view.finished { + return view.meter; + } + } + panic!("mark did not finish within the harness bound"); +} + +fn resume_at_roots(heap: &mut LuaHeap) -> ParkedMark<'_> { + let mut parked = ParkedMark::start(heap).expect("start"); + pause_after_root_visits(&mut parked, 2); + assert_eq!(parked.phase_name(), "roots"); + assert!(parked.mutation_open()); + parked.park().expect("release the exclusive window"); + let parked = ParkedMark::resume(heap).expect("resume the parked mark"); + assert_eq!(parked.phase_name(), "roots"); + parked +} + +fn resume_at_gray(heap: &mut LuaHeap, later: TableRef) -> ParkedMark<'_> { + let mut parked = ParkedMark::start(heap).expect("start"); + let cursor = parked.field_index(later, KEY_CHILD).expect("child edge"); + pause_at(&mut parked, later.slot(), cursor); + let pending = parked.pending().expect("gray cursor"); + parked.park().expect("release the exclusive window"); + let parked = ParkedMark::resume(heap).expect("resume the parked mark"); + assert_eq!(parked.phase_name(), "gray"); + assert_eq!( + parked.pending().map(|item| (item.owner, item.cursor)), + Some((pending.owner, pending.cursor)) + ); + parked +} + +fn assert_batch_did_not_touch_roots( + parked: &ParkedMark<'_>, + frame: RootFrameId, + before: &ScanMeter, +) { + let after = parked.meter(); + assert_eq!(after.root_slot_visits, before.root_slot_visits); + assert_eq!(after.parked_root_writes, before.parked_root_writes); + assert_eq!(after.mark_passes, 1); + assert_eq!(parked.stats().root_slots, 4); + assert_eq!(parked.stats().live_roots, 3); + assert_eq!( + parked.root_table(frame, 1).expect("empty observer slot"), + None + ); +} + +fn sweep_finished(parked: &mut ParkedMark<'_>) { + parked.complete().expect("sweep"); +} + +fn keep_table(gray: bool) { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let graph = observed(&mut heap); + let mut parked = if gray { + resume_at_gray(&mut heap, graph.later) + } else { + resume_at_roots(&mut heap) + }; + assert!( + !parked.marked(graph.target), + "the weak observer already marked the target" + ); + let before = parked.meter(); + let pending = parked.pending(); + let root_slots = parked.stats().root_slots; + let live_roots = parked.stats().live_roots; + let peak_roots = parked.stats().peak_roots; + parked + .accept_root_batch(&[Rooted::Table(graph.target)]) + .expect("open batch"); + let after = parked.meter(); + assert_eq!( + after.node_slot_visits, + before.node_slot_visits + 2, + "follow_one charges two visits per accepted entry; sample before sweep" + ); + assert_eq!(after.root_slot_visits, before.root_slot_visits); + assert_eq!( + after.parked_root_batch_accepts, + before.parked_root_batch_accepts + 1 + ); + assert_eq!(after.parked_barrier_marks, before.parked_barrier_marks + 1); + assert_eq!(after.scratch.work_pushed, before.scratch.work_pushed + 1); + assert_eq!(after.parked_root_writes, before.parked_root_writes); + assert_eq!(after.mark_passes, 1); + assert_eq!( + parked.pending().map(|item| (item.owner, item.cursor)), + pending.map(|item| (item.owner, item.cursor)) + ); + assert_eq!(parked.stats().root_slots, root_slots); + assert_eq!(parked.stats().live_roots, live_roots); + assert_eq!(parked.stats().peak_roots, peak_roots); + assert_eq!( + parked.root_table(graph.frame, 1).expect("slot"), + None, + "the batch wrote a root slot" + ); + if gray { + let edges = after.outgoing_edge_checks; + let view = parked.pulse(1); + assert!(!view.finished); + assert_eq!(view.meter.outgoing_edge_checks, edges + 1); + assert_eq!(view.meter.root_slot_visits, after.root_slot_visits); + } else { + let visits = after.root_slot_visits; + let view = parked.pulse(1); + assert!(!view.finished); + assert_eq!(view.meter.root_slot_visits, visits + 1); + assert_eq!(parked.phase_name(), "roots"); + } + let marked = finish(&mut parked); + assert_eq!(marked.mark_passes, 1); + assert_eq!(marked.parked_root_writes, 0); + sweep_finished(&mut parked); + drop(parked); + + assert!( + heap.alive(graph.child) && !heap.alive(graph.orphan), + "fixed root and weak observer were not independent; child {} orphan {}", + heap.alive(graph.child), + heap.alive(graph.orphan) + ); + assert!( + heap.alive(graph.target) && heap.alive(graph.successor), + "resumed batch returned success but did not keep the table; target {} successor {} child {}", + heap.alive(graph.target), + heap.alive(graph.successor), + heap.alive(graph.child) + ); + assert_eq!( + heap.edge(graph.target, KEY_NEXT).expect("successor edge"), + Some(graph.successor) + ); + assert_eq!( + heap.edge(graph.later, KEY_CHILD).expect("later child"), + Some(graph.child) + ); + assert_eq!(heap.stats().root_slots, 4); + assert_eq!(heap.stats().live_roots, 3); + assert_eq!(heap.current_frame(), Some(graph.frame)); + assert_eq!(heap.scan.parked_root_batch_accepts, 1); + assert_eq!(heap.scan.parked_barrier_marks, 1); + assert_eq!(heap.scan.parked_root_writes, 0); + + heap.collect(); + assert!( + !heap.alive(graph.target) && !heap.alive(graph.successor), + "the next cycle retained a batch or frame residue" + ); + assert!(heap.alive(graph.child), "the fixed root was dropped"); + assert_eq!(heap.stats().root_slots, 4); + assert_eq!(heap.current_frame(), Some(graph.frame)); +} + +#[test] +fn roots_batch_after_resume_keeps_the_table_and_its_successor() { + keep_table(false); +} + +#[test] +fn gray_batch_after_resume_keeps_the_table_and_its_successor() { + keep_table(true); +} + +struct Chains { + frame: RootFrameId, + later: TableRef, + child: TableRef, + closure: ClosureRef, + cell: UpvalueRef, + held: TableRef, + free_cell: UpvalueRef, + free_held: TableRef, + omitted: TableRef, + orphan: TableRef, +} + +fn chains(heap: &mut LuaHeap) -> Chains { + let later = heap.alloc().expect("later"); + let child = heap.alloc().expect("child"); + heap.set_edge(later, KEY_CHILD, child).expect("later edge"); + let tail = heap.alloc().expect("tail"); + let mt = heap.alloc().expect("metatable"); + let watch = heap.alloc().expect("watch"); + let closure = heap.alloc_closure().expect("closure"); + let cell = heap.alloc_upvalue().expect("closure cell"); + let held = heap.alloc().expect("closure table"); + let free_cell = heap.alloc_upvalue().expect("independent cell"); + let free_held = heap.alloc().expect("independent table"); + let omitted = heap.alloc().expect("omitted table"); + let orphan = heap.alloc().expect("orphan"); + heap.set_upvalue_edge(closure, cell).expect("closure cell"); + heap.write_upvalue(cell, held).expect("cell current"); + heap.write_upvalue(free_cell, free_held) + .expect("independent current"); + heap.set_mode_scalar(mt, Value::string("v\0")) + .expect("weak values"); + heap.set_metatable(watch, Some(mt)) + .expect("watch metatable"); + heap.set_closure_edge(watch, KEY_CLOSURE, closure) + .expect("weak closure"); + heap.set_cell_edge(watch, free_cell) + .expect("weak independent cell"); + heap.set_edge(watch, KEY_TARGET, omitted) + .expect("weak omitted"); + heap.set_edge(watch, KEY_ORPHAN, orphan) + .expect("weak orphan"); + let frame = heap.enter_roots(4).expect("observer frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 2, tail).expect("root tail"); + heap.write_root(frame, 3, watch).expect("root watch"); + Chains { + frame, + later, + child, + closure, + cell, + held, + free_cell, + free_held, + omitted, + orphan, + } +} + +fn assert_chain_identity(heap: &LuaHeap, graph: &Chains, free_kept: bool) { + assert!( + heap.alive(graph.child) && !heap.alive(graph.orphan) && !heap.alive(graph.omitted), + "roots shadowed the batch; child {} orphan {} omitted {}", + heap.alive(graph.child), + heap.alive(graph.orphan), + heap.alive(graph.omitted) + ); + assert!( + heap.closure_alive(graph.closure) + && heap.upvalue_alive(graph.cell) + && heap.alive(graph.held), + "closure chain was not kept; closure {} cell {} table {}", + heap.closure_alive(graph.closure), + heap.upvalue_alive(graph.cell), + heap.alive(graph.held) + ); + assert_eq!( + heap.read_upvalue(graph.closure).expect("closure current"), + graph.held + ); + assert_eq!(heap.upvalue_alive(graph.free_cell), free_kept); + assert_eq!(heap.alive(graph.free_held), free_kept); + if free_kept { + assert_eq!( + heap.current_table(graph.free_cell) + .expect("independent current"), + Some(graph.free_held) + ); + } + assert_eq!(heap.stats().root_slots, 4); + assert_eq!(heap.current_frame(), Some(graph.frame)); + assert_eq!(heap.scan.parked_root_writes, 0); +} + +fn keep_chains(gray: bool, include_free: bool) { + let mut heap = LuaHeap::new(limits(24, 8, 24)); + let graph = chains(&mut heap); + let mut parked = if gray { + resume_at_gray(&mut heap, graph.later) + } else { + resume_at_roots(&mut heap) + }; + assert!( + !parked.marked(graph.omitted), + "observer marked the omitted table" + ); + let before = parked.meter(); + let mut batch = vec![Rooted::Closure(graph.closure)]; + if include_free { + batch.push(Rooted::Upvalue(graph.free_cell)); + } + parked.accept_root_batch(&batch).expect("chain batch"); + let after = parked.meter(); + let entries = batch.len() as u64; + assert_eq!( + after.node_slot_visits, + before.node_slot_visits + 2 * entries + ); + assert_eq!(after.root_slot_visits, before.root_slot_visits); + assert_eq!(after.parked_root_batch_accepts, entries); + assert_eq!(after.parked_barrier_marks, entries); + assert_eq!( + after.scratch.work_pushed, + before.scratch.work_pushed + entries + ); + assert_eq!(after.parked_root_writes, 0); + assert_batch_did_not_touch_roots(&parked, graph.frame, &before); + finish(&mut parked); + sweep_finished(&mut parked); + drop(parked); + assert_chain_identity(&heap, &graph, include_free); +} + +#[test] +fn roots_batch_keeps_closure_and_upvalue_identity() { + keep_chains(false, true); +} + +#[test] +fn gray_batch_keeps_closure_and_upvalue_identity() { + keep_chains(true, true); +} + +#[test] +fn omitted_target_is_collected_while_the_named_closure_lives() { + keep_chains(false, false); +} + +#[test] +fn duplicate_entry_enqueues_once() { + let mut once_heap = LuaHeap::new(limits(16, 8, 16)); + let once_graph = observed(&mut once_heap); + let mut once = resume_at_roots(&mut once_heap); + let once_before = once.meter(); + once.accept_root_batch(&[Rooted::Table(once_graph.target)]) + .expect("single"); + assert_eq!( + once.meter().node_slot_visits, + once_before.node_slot_visits + 2 + ); + assert_eq!(once.meter().parked_barrier_marks, 1); + assert_eq!(once.meter().parked_root_batch_accepts, 1); + let once_mark = finish(&mut once); + + let mut twice_heap = LuaHeap::new(limits(16, 8, 16)); + let twice_graph = observed(&mut twice_heap); + let mut twice = resume_at_roots(&mut twice_heap); + let twice_before = twice.meter(); + twice + .accept_root_batch(&[ + Rooted::Table(twice_graph.target), + Rooted::Table(twice_graph.target), + ]) + .expect("duplicate"); + assert_eq!( + twice.meter().node_slot_visits, + twice_before.node_slot_visits + 4, + "each duplicate still takes two follow_one visits" + ); + assert_eq!(twice.meter().parked_barrier_marks, 1); + assert_eq!(twice.meter().parked_root_batch_accepts, 2); + assert_eq!( + twice.meter().scratch.work_pushed, + twice_before.scratch.work_pushed + 1 + ); + assert_eq!( + twice.meter().root_slot_visits, + twice_before.root_slot_visits + ); + let twice_mark = finish(&mut twice); + assert_eq!( + twice_mark.owner_head_checks, once_mark.owner_head_checks, + "the duplicate was pushed onto the gray queue again" + ); + assert_eq!( + twice_mark.outgoing_edge_checks, once_mark.outgoing_edge_checks, + "the duplicate was scanned again" + ); + sweep_finished(&mut twice); + drop(twice); + assert!(twice_heap.alive(twice_graph.target)); + assert!(twice_heap.alive(twice_graph.successor)); + assert!(!twice_heap.alive(twice_graph.orphan)); +} + +fn refuse_and_reclaim( + heap: &mut LuaHeap, + graph: &Observed, + batch_tail: Rooted, + expected: HeapError, +) { + let mut parked = resume_at_gray(heap, graph.later); + assert!(!parked.marked(graph.target), "target was already marked"); + let before = parked.meter(); + let pending = parked.pending().expect("gray cursor"); + let stats = parked.stats(); + let err = parked + .accept_root_batch(&[Rooted::Table(graph.target), batch_tail]) + .expect_err("invalid tail"); + assert_eq!(err, expected); + assert_eq!( + parked.meter(), + before, + "precheck reads and the refused batch changed the scan meter" + ); + assert_eq!( + parked.pending().map(|item| (item.owner, item.cursor)), + Some((pending.owner, pending.cursor)) + ); + assert_eq!(parked.stats(), stats); + assert_eq!(parked.root_table(graph.frame, 1).expect("slot"), None); + finish(&mut parked); + sweep_finished(&mut parked); + drop(parked); + assert!( + !heap.alive(graph.target) && !heap.alive(graph.successor), + "the refused batch marked the leading entry; target {} successor {}", + heap.alive(graph.target), + heap.alive(graph.successor) + ); + assert!(heap.alive(graph.child)); + assert!(!heap.alive(graph.orphan)); + assert_eq!(heap.scan.parked_root_batch_accepts, 0); + assert_eq!(heap.scan.parked_barrier_marks, 0); + assert_eq!(heap.scan.parked_root_writes, 0); +} + +#[test] +fn refused_stale_tail_does_not_mark_the_leading_entry() { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let graph = observed(&mut heap); + let stale = heap.alloc().expect("stale"); + heap.rollback(stale).expect("rollback"); + refuse_and_reclaim( + &mut heap, + &graph, + Rooted::Table(stale), + HeapError::StaleHandle, + ); +} + +#[test] +fn refused_foreign_tail_does_not_mark_the_leading_entry() { + let mut other = LuaHeap::new(limits(2, 1, 1)); + let foreign = other.alloc().expect("foreign"); + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let graph = observed(&mut heap); + refuse_and_reclaim( + &mut heap, + &graph, + Rooted::Table(foreign), + HeapError::WrongDomain, + ); +} + +#[test] +fn refused_wrong_kind_tail_does_not_mark_the_leading_entry() { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let graph = observed(&mut heap); + let closure = heap.alloc_closure().expect("live closure"); + // Existing constructor. Production does not build an unverified handle. + let wrong_kind = TableRef::table(closure.domain(), closure.slot(), closure.generation()); + refuse_and_reclaim( + &mut heap, + &graph, + Rooted::Table(wrong_kind), + HeapError::WrongKind, + ); +} + +struct Quota { + frame: RootFrameId, + target: TableRef, + successor: TableRef, + child: TableRef, +} + +fn quota_graph(heap: &mut LuaHeap) -> Quota { + let later = heap.alloc().expect("later"); + let child = heap.alloc().expect("child"); + heap.set_edge(later, KEY_CHILD, child).expect("later edge"); + let mt = heap.alloc().expect("metatable"); + let watch = heap.alloc().expect("watch"); + let target = heap.alloc().expect("target"); + let successor = heap.alloc().expect("successor"); + let orphan = heap.alloc().expect("orphan"); + heap.set_edge(target, KEY_NEXT, successor) + .expect("successor"); + heap.set_mode_scalar(mt, Value::string("v\0")) + .expect("mode"); + heap.set_metatable(watch, Some(mt)).expect("metatable"); + heap.set_edge(watch, KEY_TARGET, target) + .expect("weak target"); + heap.set_edge(watch, KEY_ORPHAN, orphan) + .expect("weak orphan"); + let frame = heap.enter_roots(3).expect("frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 2, watch).expect("root watch"); + Quota { + frame, + target, + successor, + child, + } +} + +fn resume_quota(heap: &mut LuaHeap) -> ParkedMark<'_> { + let mut parked = ParkedMark::start(heap).expect("start"); + pause_after_root_visits(&mut parked, 2); + assert_eq!(parked.phase_name(), "roots"); + assert_eq!(parked.stats().root_slots, 3); + assert_eq!( + parked.stats().live_roots, + 2, + "the empty reserved slot counts" + ); + parked.park().expect("park"); + ParkedMark::resume(heap).expect("resume") +} + +#[test] +fn full_root_quota_accepts_and_keeps_the_target() { + let mut heap = LuaHeap::new(limits(12, 4, 12)); + let graph = quota_graph(&mut heap); + let mut parked = resume_quota(&mut heap); + parked + .accept_root_batch(&[Rooted::Table(graph.target)]) + .expect("3 reserved slots + 1 entry = 4"); + assert_eq!(parked.meter().parked_root_batch_accepts, 1); + assert_eq!(parked.stats().root_slots, 3); + finish(&mut parked); + sweep_finished(&mut parked); + drop(parked); + assert!(heap.alive(graph.target) && heap.alive(graph.successor)); + assert!(heap.alive(graph.child)); + assert_eq!(heap.stats().root_slots, 3); + assert_eq!(heap.current_frame(), Some(graph.frame)); +} + +#[test] +fn quota_counts_empty_slots_and_duplicate_entries() { + let mut heap = LuaHeap::new(limits(12, 3, 12)); + let graph = quota_graph(&mut heap); + let mut parked = resume_quota(&mut heap); + let before = parked.meter(); + let err = parked + .accept_root_batch(&[Rooted::Table(graph.target)]) + .expect_err("3 reserved slots + 1 entry exceeds 3"); + assert_eq!(err, HeapError::RootCapacity); + assert_eq!(parked.meter(), before); + finish(&mut parked); + sweep_finished(&mut parked); + drop(parked); + assert!( + !heap.alive(graph.target), + "counting only occupied slots accepted a batch the quota rejects" + ); + assert!(heap.alive(graph.child)); + + let mut heap = LuaHeap::new(limits(12, 4, 12)); + let graph = quota_graph(&mut heap); + let mut parked = resume_quota(&mut heap); + let before = parked.meter(); + let err = parked + .accept_root_batch(&[Rooted::Table(graph.target), Rooted::Table(graph.target)]) + .expect_err("duplicate entries count toward the quota"); + assert_eq!(err, HeapError::RootCapacity); + assert_eq!(parked.meter(), before); + finish(&mut parked); + sweep_finished(&mut parked); + drop(parked); + assert!( + !heap.alive(graph.target) && !heap.alive(graph.successor), + "deduplicating the batch slipped past the quota and kept the target" + ); + assert!(heap.alive(graph.child)); + + let mut heap = LuaHeap::new(limits(12, 5, 12)); + let graph = quota_graph(&mut heap); + let mut parked = resume_quota(&mut heap); + let before = parked.meter(); + parked + .accept_root_batch(&[Rooted::Table(graph.target), Rooted::Table(graph.target)]) + .expect("3 reserved slots + 2 duplicate entries = 5"); + assert_eq!(parked.meter().node_slot_visits, before.node_slot_visits + 4); + assert_eq!(parked.meter().parked_root_batch_accepts, 2); + assert_eq!(parked.meter().parked_barrier_marks, 1); + assert_eq!(parked.stats().root_slots, 3); + finish(&mut parked); + sweep_finished(&mut parked); + drop(parked); + assert!(heap.alive(graph.target) && heap.alive(graph.successor)); +} + +#[test] +fn over_limit_is_reported_before_a_stale_tail() { + let mut heap = LuaHeap::new(limits(16, 4, 16)); + let stale = heap.alloc().expect("stale"); + heap.rollback(stale).expect("rollback"); + let graph = observed(&mut heap); + let mut parked = resume_at_roots(&mut heap); + let before = parked.meter(); + let err = parked + .accept_root_batch(&[Rooted::Table(graph.target), Rooted::Table(stale)]) + .expect_err("length before handles"); + assert_eq!(err, HeapError::RootCapacity); + assert_eq!(parked.meter(), before); + finish(&mut parked); + sweep_finished(&mut parked); + drop(parked); + assert!(!heap.alive(graph.target)); + assert!(heap.alive(graph.child)); +} + +#[test] +fn closed_phase_and_done_reject_the_batch() { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let graph = observed(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + let before = parked.meter(); + assert_eq!( + parked + .accept_root_batch(&[Rooted::Table(graph.target)]) + .expect_err("start"), + HeapError::MarkDenied + ); + assert_eq!(parked.meter(), before); + assert_eq!(parked.phase_name(), "start"); + let view = parked.pulse(1); + assert_eq!(view.meter.mark_passes, 1); + assert_ne!(parked.phase_name(), "roots"); + assert_ne!(parked.phase_name(), "gray"); + assert!(!parked.mutation_open()); + let reset = parked.meter(); + assert_eq!( + parked + .accept_root_batch(&[]) + .expect_err("empty batch is not a no-op while closed"), + HeapError::MarkDenied + ); + assert_eq!( + parked + .accept_root_batch(&[Rooted::Table(graph.target)]) + .expect_err("closed phase"), + HeapError::MarkDenied + ); + assert_eq!(parked.meter(), reset); + finish(&mut parked); + assert_eq!(parked.phase_name(), "done"); + let done = parked.meter(); + assert_eq!( + parked + .accept_root_batch(&[Rooted::Table(graph.target)]) + .expect_err("done"), + HeapError::MarkDenied + ); + assert_eq!( + parked.meter(), + done, + "the Done refusal must not be charged for the earlier root walk" + ); + sweep_finished(&mut parked); + drop(parked); + assert!(!heap.alive(graph.target) && !heap.alive(graph.successor)); + assert!(heap.alive(graph.child)); + assert_eq!(heap.scan.parked_root_batch_accepts, 0); + assert_eq!(heap.scan.parked_barrier_marks, 0); +} + +#[test] +fn empty_open_batch_is_a_noop() { + let mut heap = LuaHeap::new(limits(16, 8, 16)); + let graph = observed(&mut heap); + let mut parked = resume_at_roots(&mut heap); + let before = parked.meter(); + let stats = parked.stats(); + parked.accept_root_batch(&[]).expect("empty open batch"); + assert_eq!(parked.meter(), before); + assert_eq!(parked.stats(), stats); + assert_eq!(parked.phase_name(), "roots"); + assert_eq!(parked.meter().node_slot_visits, before.node_slot_visits); + assert_eq!(parked.meter().root_slot_visits, before.root_slot_visits); + finish(&mut parked); + sweep_finished(&mut parked); + drop(parked); + assert!(!heap.alive(graph.target)); + assert!(heap.alive(graph.child)); + assert_eq!(heap.stats().root_slots, 4); + assert_eq!(heap.current_frame(), Some(graph.frame)); +} From b2e4667406254a6f73984e3fe7f5c4b3097e6ecd Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 00:13:31 +0800 Subject: [PATCH 108/225] feat(lua/heap): hand the current root batch across the first Roots boundary --- src/frontends/lua/heap/table.rs | 4 + src/frontends/lua/heap/table/mark.rs | 146 +++- .../first_roots_handoff.rs | 781 ++++++++++++++++++ 3 files changed, 901 insertions(+), 30 deletions(-) create mode 100644 tests/luajit_heap_runtime/first_roots_handoff.rs diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 32f32d7..e299213 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2342,6 +2342,10 @@ mod budgeted_sweep; #[path = "../../../../tests/luajit_heap_runtime/budgeted_token_scan.rs"] mod budgeted_token_scan; +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/first_roots_handoff.rs"] +mod first_roots_handoff; + #[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/parked_lifecycle.rs"] mod parked_lifecycle; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index 9221e38..0d82e3f 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -14,11 +14,19 @@ //! head, or one outgoing edge or gap. Target checks and the metatable check //! ride with the edge or the owner head. A zero budget does not read the graph. //! -//! A safepoint root batch is not one of those units. While Roots or Gray is -//! open, the batch checks the phase, the root quota, and every typed handle -//! before it marks anything. Those prechecks do not increment the scan meter. -//! Success then hands each entry to the existing gray queue. It does not write -//! a root slot, open a frame, copy the batch, or spend pulse budget. +//! A safepoint root batch is not one of those units. `accept_root_batch` is +//! open only in Roots or Gray: phase, then root quota, then every typed +//! handle, before any mark. Those prechecks do not increment the scan meter. +//! Success hands each entry to the existing gray queue. It does not write a +//! root slot, open a frame, copy the batch, or spend pulse budget. +//! +//! A positive `pulse_with_root_batch` refuses Done or a missing mark before +//! it reads the batch. It then uses that same quota and handle check and +//! advances with the ordinary stepper. Roots or Gray, including a same-pulse +//! entry from Start, Reset, or Mode, commit once before any root or gray +//! step. A budget that runs out before Roots does not commit. The next call, +//! including one after park and resume, reads only the batch it was given. +//! Zero budget only observes. //! //! Reset and mode pulses still spend that budget. They do not open mutation. //! Roots and Gray open an ordinary field delete, an ordinary field write on @@ -259,6 +267,59 @@ impl<'a> ParkedMark<'a> { view } + /// Hands the current safepoint batch across the first Roots boundary. + /// + /// Zero budget only observes: it does not check the batch or read the + /// graph. A positive budget refuses Done or a missing mark before any + /// batch read, then checks quota and handles before the stepper moves. + /// Refusal does not scan or write. An open Roots or Gray phase commits + /// first. A closed phase commits once in this pulse, after the stepper + /// enters Roots and before any root or gray step. The slice is not stored. + pub(super) fn pulse_with_root_batch( + &mut self, + budget: u64, + batch: &[Rooted], + ) -> Result { + if budget == 0 { + return Ok(self.pulse(budget)); + } + self.advance_with_root_batch(budget, batch) + } + + fn advance_with_root_batch( + &mut self, + budget: u64, + batch: &[Rooted], + ) -> Result { + self.saved_mark()?; + if self + .heap + .mark + .as_ref() + .is_some_and(|state| matches!(state.phase, MarkPhase::Done)) + { + return Err(HeapError::MarkDenied); + } + validate_root_batch(self.heap, batch)?; + let mut state = self.heap.mark.take().expect("parked mark"); + let view = pulse_budget(self.heap, &mut state, budget, Some(batch)); + if matches!(state.phase, MarkPhase::Done) { + self.done = Some(MarkSnapshot { + modes: state.modes.take(), + }); + } else { + self.heap.mark = Some(state); + } + Ok(view) + } + + fn saved_mark(&self) -> Result<&MarkState, HeapError> { + if self.done.is_some() || self.swept { + return Err(HeapError::MarkDenied); + } + self.heap.mark.as_ref().ok_or(HeapError::MarkDenied) + } + pub(super) fn pending(&self) -> Option { let state = self.heap.mark.as_ref()?; Some(PendingScan { @@ -397,38 +458,16 @@ impl<'a> ParkedMark<'a> { return Ok(()); } let mut state = self.heap.mark.take().expect("open mark"); - for rooted in batch { - let (slot, generation, kind) = rooted_identity(*rooted); - enqueue_barrier_target(self.heap, &mut state, slot, generation, kind); - } + commit_root_batch(self.heap, &mut state, batch); self.heap.mark = Some(state); - self.heap.scan.parked_root_batch_accepts += - u64::try_from(batch.len()).expect("quota already checked the length"); Ok(()) } fn gate_root_batch(&self, batch: &[Rooted]) -> Result<(), HeapError> { - if self.done.is_some() || self.swept { + if !self.saved_mark()?.mutation_open() { return Err(HeapError::MarkDenied); } - let state = self.heap.mark.as_ref().ok_or(HeapError::MarkDenied)?; - if !state.mutation_open() { - return Err(HeapError::MarkDenied); - } - let occupied = u32::try_from(self.heap.roots.len()).map_err(|_| HeapError::RootCapacity)?; - let extra = u32::try_from(batch.len()).map_err(|_| HeapError::RootCapacity)?; - let end = occupied.checked_add(extra).ok_or(HeapError::RootCapacity)?; - if end > self.heap.limits.roots { - return Err(HeapError::RootCapacity); - } - for rooted in batch { - match *rooted { - Rooted::Table(handle) => self.heap.require_live(handle)?, - Rooted::Closure(handle) => self.heap.require_closure(handle)?, - Rooted::Upvalue(handle) => self.heap.require_upvalue(handle)?, - } - } - Ok(()) + validate_root_batch(self.heap, batch) } pub(super) fn write_table_root( @@ -611,7 +650,47 @@ impl Drop for ParkedMark<'_> { } } +fn validate_root_batch(heap: &LuaHeap, batch: &[Rooted]) -> Result<(), HeapError> { + let occupied = u32::try_from(heap.roots.len()).map_err(|_| HeapError::RootCapacity)?; + let extra = u32::try_from(batch.len()).map_err(|_| HeapError::RootCapacity)?; + let end = occupied.checked_add(extra).ok_or(HeapError::RootCapacity)?; + if end > heap.limits.roots { + return Err(HeapError::RootCapacity); + } + for rooted in batch { + match *rooted { + Rooted::Table(handle) => heap.require_live(handle)?, + Rooted::Closure(handle) => heap.require_closure(handle)?, + Rooted::Upvalue(handle) => heap.require_upvalue(handle)?, + } + } + Ok(()) +} + +fn commit_root_batch(heap: &mut LuaHeap, state: &mut MarkState, batch: &[Rooted]) { + if batch.is_empty() { + return; + } + for rooted in batch { + let (slot, generation, kind) = rooted_identity(*rooted); + enqueue_barrier_target(heap, state, slot, generation, kind); + } + heap.scan.parked_root_batch_accepts += + u64::try_from(batch.len()).expect("quota already checked the length"); +} + fn pulse_state(heap: &mut LuaHeap, state: &mut MarkState, budget: u64) -> MarkView { + pulse_budget(heap, state, budget, None) +} + +/// Same units, gray queue, and meters as [`pulse_state`]. A batch, when +/// present, is committed once before any Roots or Gray step. It is not stored. +fn pulse_budget( + heap: &mut LuaHeap, + state: &mut MarkState, + budget: u64, + batch: Option<&[Rooted]>, +) -> MarkView { if budget == 0 || matches!(state.phase, MarkPhase::Done) { return view(heap, state); } @@ -619,9 +698,16 @@ fn pulse_state(heap: &mut LuaHeap, state: &mut MarkState, budget: u64) -> MarkVi heap.scan.mark_passes += 1; state.phase = MarkPhase::Reset; } + let mut handed = false; let mut left = budget; let mut spins = 0u32; while left > 0 && !matches!(state.phase, MarkPhase::Done) { + if !handed && matches!(state.phase, MarkPhase::Roots | MarkPhase::Gray) { + if let Some(batch) = batch { + commit_root_batch(heap, state, batch); + } + handed = true; + } if step(heap, state) { left -= 1; spins = 0; diff --git a/tests/luajit_heap_runtime/first_roots_handoff.rs b/tests/luajit_heap_runtime/first_roots_handoff.rs new file mode 100644 index 0000000..ce88aa7 --- /dev/null +++ b/tests/luajit_heap_runtime/first_roots_handoff.rs @@ -0,0 +1,781 @@ +//! First Roots boundary for the current safepoint root batch. +//! +//! Zero fixed root slots and an empty gray queue let one ordinary positive +//! pulse cross Roots and Gray straight to Done. The handoff must commit the +//! borrowed batch inside that pulse, after the stepper enters Roots and before +//! any root or gray step. The slice is not saved on the mark. A later call, +//! including one after park and resume, reads the batch passed to that call. + +use super::{HeapError, HeapLimits, LuaHeap, ParkedMark, RootFrameId, Rooted, ScanMeter, TableRef}; +use vm::Value; + +const KEY_CHILD: u32 = 1; +const KEY_NEXT: u32 = 6; +const HARNESS_BOUND: u32 = 64; + +fn limits(nodes: u32, roots: u32, edges: u32) -> HeapLimits { + HeapLimits { + nodes, + roots, + edges, + max_generation: 8, + } +} + +struct Chain { + target: TableRef, + successor: TableRef, + orphan: TableRef, + other: TableRef, + other_child: TableRef, +} + +fn chain(heap: &mut LuaHeap) -> Chain { + let target = heap.alloc().expect("target"); + let successor = heap.alloc().expect("successor"); + let orphan = heap.alloc().expect("orphan"); + let other = heap.alloc().expect("other"); + let other_child = heap.alloc().expect("other child"); + heap.set_edge(target, KEY_NEXT, successor) + .expect("target successor"); + heap.set_edge(other, KEY_CHILD, other_child) + .expect("other child"); + Chain { + target, + successor, + orphan, + other, + other_child, + } +} + +fn chain_with_mode(heap: &mut LuaHeap) -> Chain { + let graph = chain(heap); + let mode = heap.alloc().expect("mode table"); + let watch = heap.alloc().expect("watch"); + heap.set_mode_scalar(mode, Value::string("v\0")) + .expect("mode string"); + heap.set_metatable(watch, Some(mode)).expect("metatable"); + graph +} + +struct Framed { + frame: RootFrameId, + later: TableRef, + child: TableRef, + tail: TableRef, + target: TableRef, + successor: TableRef, + orphan: TableRef, +} + +fn framed(heap: &mut LuaHeap) -> Framed { + let later = heap.alloc().expect("later"); + let child = heap.alloc().expect("child"); + heap.set_edge(later, KEY_CHILD, child).expect("later edge"); + let tail = heap.alloc().expect("tail"); + let target = heap.alloc().expect("target"); + let successor = heap.alloc().expect("successor"); + let orphan = heap.alloc().expect("orphan"); + heap.set_edge(target, KEY_NEXT, successor) + .expect("target successor"); + let frame = heap.enter_roots(4).expect("frame"); + heap.write_root(frame, 0, later).expect("root later"); + heap.write_root(frame, 2, tail).expect("root tail"); + Framed { + frame, + later, + child, + tail, + target, + successor, + orphan, + } +} + +fn assert_no_fixed_roots(heap: &LuaHeap) { + assert_eq!( + heap.stats().root_slots, + 0, + "the handoff opened a root frame" + ); + assert_eq!(heap.stats().live_roots, 0); + assert_eq!(heap.current_frame(), None); + assert_eq!(heap.scan.parked_root_writes, 0); +} + +fn assert_frame_untouched(parked: &ParkedMark<'_>, graph: &Framed) { + assert_eq!(parked.stats().root_slots, 4); + assert_eq!(parked.stats().live_roots, 2); + assert_eq!(parked.meter().parked_root_writes, 0); + assert_eq!( + parked.root_table(graph.frame, 0).expect("later slot"), + Some(graph.later) + ); + assert_eq!(parked.root_table(graph.frame, 1).expect("empty slot"), None); + assert_eq!( + parked.root_table(graph.frame, 2).expect("tail slot"), + Some(graph.tail) + ); + assert_eq!(parked.root_table(graph.frame, 3).expect("empty tail"), None); +} + +fn park_at_reset_tail(heap: &mut LuaHeap) -> ParkedMark<'_> { + let mut parked = ParkedMark::start(heap).expect("start"); + let slots = u64::from(parked.stats().node_slots); + assert!(slots > 0, "reset tail needs existing nodes"); + assert_eq!(parked.stats().root_slots, 0); + for _ in 0..HARNESS_BOUND { + if parked.phase_name() == "reset" && parked.meter().weak_mode_slot_checks == slots { + assert!(!parked.mutation_open()); + assert_eq!(parked.meter().mark_passes, 1); + assert_eq!(parked.meter().root_slot_visits, 0); + assert_eq!(parked.meter().parked_root_batch_accepts, 0); + return parked; + } + let view = parked.pulse(1); + assert!( + !view.finished, + "ordinary pulse finished before reset tail, phase {}", + parked.phase_name() + ); + assert!( + !parked.mutation_open(), + "mutation opened before reset tail, phase {}", + parked.phase_name() + ); + } + panic!( + "reset tail was not observed, phase {} checks {}", + parked.phase_name(), + parked.meter().weak_mode_slot_checks + ); +} + +fn pause_after_root_visits(parked: &mut ParkedMark<'_>, visits: u64) { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!(!view.finished, "mark finished before {visits} root visits"); + assert_eq!(view.meter.mark_passes, 1); + if parked.phase_name() == "roots" && parked.meter().root_slot_visits == visits { + return; + } + } + panic!( + "did not stop after {visits} root visits, phase {}", + parked.phase_name() + ); +} + +fn pause_at_gray(parked: &mut ParkedMark<'_>, owner: TableRef) { + let cursor = parked.field_index(owner, KEY_CHILD).expect("child edge"); + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!(!view.finished, "mark finished before the pending edge"); + if let Some(pending) = parked.pending() + && pending.owner == owner.slot() + && pending.cursor == cursor + { + assert_eq!(parked.phase_name(), "gray"); + return; + } + } + panic!("pending child edge was not observed"); +} + +fn finish_ordinary(parked: &mut ParkedMark<'_>) -> ScanMeter { + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + if view.finished { + return view.meter; + } + } + panic!( + "ordinary pulse did not finish, phase {}", + parked.phase_name() + ); +} + +fn sweep(parked: &mut ParkedMark<'_>) { + parked.complete().expect("sweep"); +} + +#[test] +fn ordinary_pulse_from_reset_tail_reaches_done_with_no_root_slots() { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let graph = chain(&mut heap); + let target_slot = graph.target.slot(); + let target_generation = graph.target.generation(); + let mut parked = park_at_reset_tail(&mut heap); + let before = parked.meter(); + let view = parked.pulse(1); + assert!( + view.finished, + "a positive pulse from the reset tail did not cross the empty roots window, phase {}", + parked.phase_name() + ); + assert_eq!(view.meter.mark_passes, 1); + assert_eq!(view.meter.root_slot_visits, before.root_slot_visits); + assert_eq!(view.meter.parked_root_batch_accepts, 0); + assert_eq!(view.meter.parked_barrier_marks, 0); + sweep(&mut parked); + drop(parked); + assert!( + !heap.alive(graph.target) && !heap.alive(graph.successor) && !heap.alive(graph.orphan), + "an unrooted pulse kept a node" + ); + assert_eq!(graph.target.slot(), target_slot); + assert_eq!(graph.target.generation(), target_generation); + assert_no_fixed_roots(&heap); +} + +#[test] +fn reset_tail_handoff_keeps_target_and_strong_successor() { + let mut heap = LuaHeap::new(limits(8, 1, 8)); + let graph = chain(&mut heap); + let target_slot = graph.target.slot(); + let target_generation = graph.target.generation(); + let successor_slot = graph.successor.slot(); + let successor_generation = graph.successor.generation(); + let mut parked = park_at_reset_tail(&mut heap); + let before = parked.meter(); + let view = parked + .pulse_with_root_batch(u64::from(HARNESS_BOUND), &[Rooted::Table(graph.target)]) + .expect("handoff"); + assert!( + view.finished, + "the handoff budget did not finish after entering roots, phase {}", + parked.phase_name() + ); + assert_eq!(view.meter.mark_passes, 1); + let marked = view.meter; + sweep(&mut parked); + let swept_roots = parked.meter().root_slot_visits; + let swept_accepts = parked.meter().parked_root_batch_accepts; + drop(parked); + + assert!( + heap.alive(graph.target) && heap.alive(graph.successor), + "handoff returned success but collected the target and its successor; target {} successor {} accepts {}", + heap.alive(graph.target), + heap.alive(graph.successor), + heap.scan.parked_root_batch_accepts + ); + assert!( + !heap.alive(graph.orphan), + "the independent orphan survived the same sweep" + ); + assert_eq!(graph.target.slot(), target_slot); + assert_eq!(graph.target.generation(), target_generation); + assert_eq!(graph.successor.slot(), successor_slot); + assert_eq!(graph.successor.generation(), successor_generation); + assert_eq!( + heap.edge(graph.target, KEY_NEXT).expect("successor edge"), + Some(graph.successor), + "the surviving target lost its original successor" + ); + assert_eq!(marked.mark_passes, before.mark_passes); + assert_eq!(marked.parked_root_batch_accepts, 1); + assert_eq!(marked.parked_barrier_marks, 1); + assert_eq!(marked.scratch.work_pushed, before.scratch.work_pushed + 2); + assert_eq!( + marked.root_slot_visits, before.root_slot_visits, + "the batch was charged as a root-slot scan" + ); + assert_eq!( + swept_roots, marked.root_slot_visits, + "sweep root visits were attributed to the batch" + ); + assert_eq!(swept_accepts, marked.parked_root_batch_accepts); + assert_no_fixed_roots(&heap); + + heap.collect(); + assert!( + !heap.alive(graph.target) && !heap.alive(graph.successor), + "the next cycle retained a batch or a hidden root frame" + ); + assert_no_fixed_roots(&heap); +} + +#[test] +fn omitted_target_is_collected_when_the_batch_names_another() { + let mut heap = LuaHeap::new(limits(8, 1, 8)); + let graph = chain(&mut heap); + let mut parked = park_at_reset_tail(&mut heap); + let view = parked + .pulse_with_root_batch(u64::from(HARNESS_BOUND), &[Rooted::Table(graph.other)]) + .expect("other handoff"); + assert!(view.finished); + assert_eq!(view.meter.mark_passes, 1); + assert_eq!(view.meter.parked_root_batch_accepts, 1); + sweep(&mut parked); + drop(parked); + assert!( + heap.alive(graph.other) && heap.alive(graph.other_child), + "the named batch root was collected; other {} child {}", + heap.alive(graph.other), + heap.alive(graph.other_child) + ); + assert!( + !heap.alive(graph.target) && !heap.alive(graph.successor), + "omitting the target still kept it; target {} successor {}", + heap.alive(graph.target), + heap.alive(graph.successor) + ); + assert!(!heap.alive(graph.orphan)); + assert_eq!( + heap.edge(graph.other, KEY_CHILD).expect("other edge"), + Some(graph.other_child) + ); + assert_no_fixed_roots(&heap); +} + +#[test] +fn exhausted_window_does_not_publish_and_the_next_batch_is_the_one_kept() { + let mut heap = LuaHeap::new(limits(8, 2, 8)); + let graph = chain(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + let slots = u64::from(parked.stats().node_slots); + let mut saw_closed = false; + for _ in 0..HARNESS_BOUND { + if parked.phase_name() == "reset" && parked.meter().weak_mode_slot_checks == slots { + break; + } + saw_closed = true; + let before = parked.meter(); + let view = parked + .pulse_with_root_batch(1, &[Rooted::Table(graph.other)]) + .expect("exhausted window"); + assert!(!view.finished, "budget 1 finished before roots"); + assert!(!parked.mutation_open(), "phase {}", parked.phase_name()); + assert_eq!( + view.meter.parked_root_batch_accepts, + before.parked_root_batch_accepts + ); + assert_eq!(view.meter.parked_barrier_marks, before.parked_barrier_marks); + assert_eq!(view.meter.mark_passes, 1); + assert!(!parked.marked(graph.other), "exhausted window marked A"); + assert!(!parked.marked(graph.target), "exhausted window marked B"); + } + assert!(saw_closed, "no closed window was observed"); + assert_eq!(parked.phase_name(), "reset"); + assert_eq!(parked.meter().parked_root_batch_accepts, 0); + parked.park().expect("park the unpublished window"); + let mut parked = ParkedMark::resume(&mut heap).expect("resume"); + assert_eq!(parked.phase_name(), "reset"); + assert_eq!(parked.meter().mark_passes, 1); + assert_eq!(parked.meter().parked_root_batch_accepts, 0); + assert!(!parked.marked(graph.other)); + let before = parked.meter(); + let entered = parked + .pulse_with_root_batch(1, &[Rooted::Table(graph.target)]) + .expect("roots window"); + assert!( + !entered.finished, + "the entering call finished before the commit could be sampled" + ); + assert_eq!(entered.meter.mark_passes, 1); + assert_eq!(entered.meter.parked_root_batch_accepts, 1); + assert_eq!(entered.meter.parked_barrier_marks, 1); + assert_eq!( + entered.meter.node_slot_visits, + before.node_slot_visits + 2, + "precheck or a second enqueue changed the commit visits" + ); + assert_eq!(entered.meter.root_slot_visits, before.root_slot_visits); + assert!(parked.mutation_open()); + assert_eq!(parked.phase_name(), "gray"); + let marked = finish_ordinary(&mut parked); + assert_eq!(marked.mark_passes, 1); + assert_eq!(marked.parked_root_batch_accepts, 1); + sweep(&mut parked); + drop(parked); + assert!( + heap.alive(graph.target) && heap.alive(graph.successor), + "the batch passed at roots was not the one kept; target {} successor {}", + heap.alive(graph.target), + heap.alive(graph.successor) + ); + assert!( + !heap.alive(graph.other) && !heap.alive(graph.other_child), + "the exhausted batch was published later; other {} child {}", + heap.alive(graph.other), + heap.alive(graph.other_child) + ); + assert!(!heap.alive(graph.orphan)); + assert_eq!( + heap.edge(graph.target, KEY_NEXT).expect("B edge"), + Some(graph.successor) + ); + assert_no_fixed_roots(&heap); +} + +#[test] +fn open_roots_handoff_keeps_the_batch_and_leaves_the_frame() { + let mut heap = LuaHeap::new(limits(12, 8, 12)); + let graph = framed(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + pause_after_root_visits(&mut parked, 2); + assert_eq!(parked.phase_name(), "roots"); + assert_frame_untouched(&parked, &graph); + let before = parked.meter(); + let view = parked + .pulse_with_root_batch(u64::from(HARNESS_BOUND), &[Rooted::Table(graph.target)]) + .expect("open roots handoff"); + assert!(view.finished, "phase {}", parked.phase_name()); + assert_eq!(view.meter.mark_passes, 1); + assert_eq!(view.meter.parked_root_batch_accepts, 1); + assert_eq!(view.meter.parked_barrier_marks, 1); + assert_eq!( + view.meter.root_slot_visits, + u64::from(parked.stats().root_slots), + "batch commit changed the root-slot scan" + ); + assert!(view.meter.root_slot_visits > before.root_slot_visits); + assert_frame_untouched(&parked, &graph); + let marked_roots = view.meter.root_slot_visits; + sweep(&mut parked); + assert_eq!( + parked.meter().root_slot_visits, + marked_roots + u64::from(parked.stats().root_slots), + "sweep root visits were folded into the batch" + ); + assert_eq!(parked.meter().parked_root_batch_accepts, 1); + assert_frame_untouched(&parked, &graph); + drop(parked); + assert!(heap.alive(graph.target) && heap.alive(graph.successor)); + assert!(heap.alive(graph.child), "the fixed root was dropped"); + assert!(!heap.alive(graph.orphan)); + assert_eq!( + heap.edge(graph.target, KEY_NEXT).expect("successor"), + Some(graph.successor) + ); + assert_eq!(heap.stats().root_slots, 4); + assert_eq!(heap.current_frame(), Some(graph.frame)); + assert_eq!(heap.scan.parked_root_writes, 0); +} + +#[test] +fn open_gray_handoff_keeps_the_batch_and_leaves_the_frame() { + let mut heap = LuaHeap::new(limits(12, 8, 12)); + let graph = framed(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + pause_at_gray(&mut parked, graph.later); + let pending = parked.pending().expect("gray cursor"); + let before = parked.meter(); + assert_frame_untouched(&parked, &graph); + let view = parked + .pulse_with_root_batch(u64::from(HARNESS_BOUND), &[Rooted::Table(graph.target)]) + .expect("open gray handoff"); + assert!(view.finished, "phase {}", parked.phase_name()); + assert_eq!(view.meter.mark_passes, 1); + assert_eq!(view.meter.parked_root_batch_accepts, 1); + assert_eq!(view.meter.parked_barrier_marks, 1); + assert_eq!( + view.meter.root_slot_visits, before.root_slot_visits, + "the gray handoff scanned root slots" + ); + assert_frame_untouched(&parked, &graph); + let marked_roots = view.meter.root_slot_visits; + sweep(&mut parked); + assert_eq!( + parked.meter().root_slot_visits, + marked_roots + u64::from(parked.stats().root_slots) + ); + assert_eq!(parked.meter().parked_root_batch_accepts, 1); + assert_eq!( + parked.root_table(graph.frame, 0).expect("later"), + Some(graph.later) + ); + drop(parked); + assert!( + heap.alive(graph.target) && heap.alive(graph.successor), + "gray handoff returned success but collected the batch; target {} successor {}", + heap.alive(graph.target), + heap.alive(graph.successor) + ); + assert!(heap.alive(graph.child)); + assert!(!heap.alive(graph.orphan)); + assert_eq!(pending.owner, graph.later.slot()); + assert_eq!(heap.stats().root_slots, 4); + assert_eq!(heap.current_frame(), Some(graph.frame)); +} + +#[test] +fn zero_budget_does_not_validate_or_publish() { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let graph = chain(&mut heap); + let stale = heap.alloc().expect("stale"); + heap.rollback(stale).expect("rollback"); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + let before = parked.meter(); + let stats = parked.stats(); + let view = parked + .pulse_with_root_batch(0, &[Rooted::Table(graph.target), Rooted::Table(stale)]) + .expect("zero budget observes an invalid batch"); + assert!(!view.finished); + assert_eq!(view.meter, before); + assert_eq!(parked.meter(), before); + assert_eq!(parked.phase_name(), "start"); + assert_eq!(parked.stats(), stats); + assert!(!parked.marked(graph.target)); + drop(parked); + + let mut framed_heap = LuaHeap::new(limits(12, 8, 12)); + let framed = framed(&mut framed_heap); + let mut open = ParkedMark::start(&mut framed_heap).expect("start"); + pause_after_root_visits(&mut open, 2); + let open_before = open.meter(); + let open_phase = open.phase_name(); + let observed = open + .pulse_with_root_batch(0, &[Rooted::Table(framed.target)]) + .expect("zero budget on open roots"); + assert!(!observed.finished); + assert_eq!(observed.meter, open_before); + assert_eq!(open.phase_name(), open_phase); + assert_eq!(open.meter().parked_root_batch_accepts, 0); + assert_frame_untouched(&open, &framed); + assert!(!open.marked(framed.target)); +} + +#[test] +fn finished_positive_budget_is_refused_before_a_scan() { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let graph = chain(&mut heap); + let stale = heap.alloc().expect("stale"); + heap.rollback(stale).expect("rollback"); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + let finished = parked.pulse(u64::from(HARNESS_BOUND)); + assert!(finished.finished); + let before = parked.meter(); + let err = parked + .pulse_with_root_batch(1, &[Rooted::Table(graph.target)]) + .err() + .expect("finished positive budget"); + assert_eq!(err, HeapError::MarkDenied); + assert_eq!(parked.meter(), before); + assert_eq!(parked.phase_name(), "done"); + let stale_err = parked + .pulse_with_root_batch(1, &[Rooted::Table(stale)]) + .err() + .expect("finished invalid batch"); + assert_eq!( + stale_err, + HeapError::MarkDenied, + "done was validated instead of refused" + ); + assert_eq!(parked.meter(), before); + assert_eq!(parked.phase_name(), "done"); +} + +#[test] +fn invalid_tail_is_refused_before_the_mark_advances() { + refuse_before_advance(InvalidTail::Stale, HeapError::StaleHandle); + refuse_before_advance(InvalidTail::Foreign, HeapError::WrongDomain); + refuse_before_advance(InvalidTail::WrongKind, HeapError::WrongKind); +} + +enum InvalidTail { + Stale, + Foreign, + WrongKind, +} + +fn refuse_before_advance(kind: InvalidTail, expected: HeapError) { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let graph = chain(&mut heap); + let tail = match kind { + InvalidTail::Stale => { + let stale = heap.alloc().expect("stale"); + heap.rollback(stale).expect("rollback"); + Rooted::Table(stale) + } + InvalidTail::Foreign => { + let mut other = LuaHeap::new(limits(2, 1, 1)); + let foreign = other.alloc().expect("foreign"); + Rooted::Table(foreign) + } + InvalidTail::WrongKind => { + let closure = heap.alloc_closure().expect("closure"); + let wrong = TableRef::table(closure.domain(), closure.slot(), closure.generation()); + Rooted::Table(wrong) + } + }; + let mut parked = ParkedMark::start(&mut heap).expect("start"); + let before = parked.meter(); + let stats = parked.stats(); + let err = parked + .pulse_with_root_batch(1, &[Rooted::Table(graph.target), tail]) + .err() + .expect("invalid tail"); + assert_eq!(err, expected); + assert_eq!(parked.phase_name(), "start"); + assert_eq!(parked.meter(), before, "refusal advanced or scanned"); + assert_eq!(parked.meter().mark_passes, 0); + assert_eq!(parked.stats(), stats); + assert!(!parked.marked(graph.target)); + let marked = finish_ordinary(&mut parked); + assert_eq!(marked.parked_root_batch_accepts, 0); + assert_eq!(marked.parked_barrier_marks, 0); + sweep(&mut parked); + drop(parked); + assert!( + !heap.alive(graph.target) && !heap.alive(graph.successor), + "the refused leading entry was marked" + ); + assert_no_fixed_roots(&heap); +} + +#[test] +fn over_quota_is_refused_before_the_mark_advances() { + let mut heap = LuaHeap::new(limits(8, 0, 8)); + let graph = chain(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + let before = parked.meter(); + let err = parked + .pulse_with_root_batch(1, &[Rooted::Table(graph.target)]) + .err() + .expect("zero root quota"); + assert_eq!(err, HeapError::RootCapacity); + assert_eq!(parked.phase_name(), "start"); + assert_eq!(parked.meter(), before); + assert_eq!(parked.meter().mark_passes, 0); + assert!(!parked.marked(graph.target)); + assert_eq!(parked.stats().root_slots, 0); +} + +#[test] +fn empty_batch_matches_an_ordinary_pulse() { + let from_start = |batch: bool| { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let _graph = chain(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + let view = if batch { + parked.pulse_with_root_batch(1, &[]).expect("empty") + } else { + parked.pulse(1) + }; + ( + parked.phase_name().to_string(), + view.finished, + view.meter, + parked.stats(), + ) + }; + let ordinary = from_start(false); + let empty = from_start(true); + assert_eq!(empty.0, ordinary.0); + assert_eq!(empty.1, ordinary.1); + assert_eq!(empty.2, ordinary.2); + assert_eq!(empty.3, ordinary.3); + assert_eq!(empty.2.parked_root_batch_accepts, 0); + assert!(!empty.1); + + let from_tail = |batch: bool| { + let mut heap = LuaHeap::new(limits(8, 4, 8)); + let graph = chain(&mut heap); + let mut parked = park_at_reset_tail(&mut heap); + let view = if batch { + parked.pulse_with_root_batch(1, &[]).expect("empty tail") + } else { + parked.pulse(1) + }; + assert!(view.finished); + sweep(&mut parked); + drop(parked); + ( + view.meter, + heap.alive(graph.target), + heap.stats().root_slots, + ) + }; + let ordinary_tail = from_tail(false); + let empty_tail = from_tail(true); + assert_eq!(empty_tail.0, ordinary_tail.0); + assert_eq!(empty_tail.1, ordinary_tail.1); + assert!(!empty_tail.1); + assert_eq!(empty_tail.2, 0); +} + +#[test] +fn mode_phases_hold_the_batch_until_roots() { + let mut heap = LuaHeap::new(limits(12, 2, 12)); + let graph = chain_with_mode(&mut heap); + let mut parked = ParkedMark::start(&mut heap).expect("start"); + let slots = u64::from(parked.stats().node_slots); + let mut saw_mode = false; + for _ in 0..HARNESS_BOUND { + let phase = parked.phase_name(); + if phase.starts_with("mode") { + saw_mode = true; + assert!(!parked.mutation_open()); + assert_eq!(parked.meter().parked_root_batch_accepts, 0); + } + if phase == "reset" && parked.meter().weak_mode_slot_checks == slots { + break; + } + let before = parked.meter(); + let view = parked + .pulse_with_root_batch(1, &[Rooted::Table(graph.other)]) + .expect("mode window"); + assert!(!view.finished, "phase {}", parked.phase_name()); + assert_eq!( + view.meter.parked_root_batch_accepts, + before.parked_root_batch_accepts + ); + assert!(!parked.mutation_open(), "phase {}", parked.phase_name()); + assert_eq!(view.meter.mark_passes, 1); + } + assert!(saw_mode, "mode phases were not observed"); + assert_eq!(parked.phase_name(), "reset"); + assert_eq!(parked.meter().parked_root_batch_accepts, 0); + assert!(!parked.marked(graph.other)); + let view = parked + .pulse_with_root_batch(u64::from(HARNESS_BOUND), &[Rooted::Table(graph.target)]) + .expect("roots after mode"); + assert!(view.finished, "phase {}", parked.phase_name()); + assert_eq!(view.meter.mark_passes, 1); + assert_eq!(view.meter.parked_root_batch_accepts, 1); + assert_eq!(view.meter.parked_barrier_marks, 1); + sweep(&mut parked); + drop(parked); + assert!(heap.alive(graph.target) && heap.alive(graph.successor)); + assert!(!heap.alive(graph.other) && !heap.alive(graph.orphan)); + assert_eq!( + heap.edge(graph.target, KEY_NEXT).expect("successor"), + Some(graph.successor) + ); + assert_no_fixed_roots(&heap); +} + +#[test] +fn closure_batch_keeps_the_cell_identity_without_a_root_frame() { + let mut heap = LuaHeap::new(limits(8, 1, 8)); + let closure = heap.alloc_closure().expect("closure"); + let cell = heap.alloc_upvalue().expect("cell"); + let held = heap.alloc().expect("held"); + let orphan = heap.alloc().expect("orphan"); + heap.set_upvalue_edge(closure, cell).expect("cell edge"); + heap.write_upvalue(cell, held).expect("current"); + let closure_slot = closure.slot(); + let cell_slot = cell.slot(); + let mut parked = park_at_reset_tail(&mut heap); + let view = parked + .pulse_with_root_batch(u64::from(HARNESS_BOUND), &[Rooted::Closure(closure)]) + .expect("closure handoff"); + assert!(view.finished); + assert_eq!(view.meter.mark_passes, 1); + assert_eq!(view.meter.parked_root_batch_accepts, 1); + assert_eq!(view.meter.root_slot_visits, 0); + sweep(&mut parked); + drop(parked); + assert!( + heap.closure_alive(closure) && heap.upvalue_alive(cell) && heap.alive(held), + "closure handoff dropped the chain" + ); + assert!(!heap.alive(orphan)); + assert_eq!(closure.slot(), closure_slot); + assert_eq!(cell.slot(), cell_slot); + assert_eq!(heap.read_upvalue(closure).expect("current"), held); + assert_no_fixed_roots(&heap); +} From bb9da3916eb5b0474717bdfab2fbba5c5118730e Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 01:21:52 +0800 Subject: [PATCH 109/225] test(lua): keep a pending table argument across a later Lua collect A value-position Lua call returns its real result, and a later safepoint publishes the earlier table into a typed temporary root that leaves only after the host consumer returns. --- tests/luajit_heap_runtime/candidate.rs | 230 +++++- tests/luajit_heap_runtime/pending_argument.rs | 747 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 3 files changed, 976 insertions(+), 3 deletions(-) create mode 100644 tests/luajit_heap_runtime/pending_argument.rs diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 58644df..baf9b3e 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -32,6 +32,9 @@ const WRITE_CELL: &str = "lua_internal::write_cell"; const TRACK_CLOSURE: &str = "lua_internal::track_closure"; const ENTER_RESULT: &str = "lua_internal::enter_result_frame"; const ENTER_CALLEE: &str = "lua_internal::enter_callee_frame"; +const ENTER_PENDING: &str = "lua_internal::enter_pending_frame"; +const WRITE_PENDING: &str = "lua_internal::write_pending_root"; +const LEAVE_PENDING: &str = "lua_internal::leave_pending_frame"; const ROOT_ISSUED: &str = "lua_internal::root_issued"; const SET_EDGE: &str = "lua_internal::set_edge"; const GET_EDGE: &str = "lua_internal::get_edge"; @@ -165,6 +168,13 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { for (name, params, result) in [ (ENTER_RESULT, vec!["width"], HostTypeSchema::Unknown), (ENTER_CALLEE, vec!["width"], HostTypeSchema::Float), + (ENTER_PENDING, vec!["width"], HostTypeSchema::Unknown), + ( + WRITE_PENDING, + vec!["frame", "slot", "value"], + HostTypeSchema::Float, + ), + (LEAVE_PENDING, vec!["frame"], HostTypeSchema::Float), ( ROOT_ISSUED, vec!["value", "slot", "role"], @@ -229,6 +239,9 @@ pub(super) fn register( Op::Count, Op::EnterResult, Op::EnterCallee, + Op::EnterPending, + Op::WritePending, + Op::LeavePending, Op::RootIssued, Op::SetEdge, Op::GetEdge, @@ -266,6 +279,9 @@ pub(super) fn register( Op::Count => COUNT, Op::EnterResult => ENTER_RESULT, Op::EnterCallee => ENTER_CALLEE, + Op::EnterPending => ENTER_PENDING, + Op::WritePending => WRITE_PENDING, + Op::LeavePending => LEAVE_PENDING, Op::RootIssued => ROOT_ISSUED, Op::SetEdge => SET_EDGE, Op::GetEdge => GET_EDGE, @@ -313,6 +329,9 @@ enum Op { Count, EnterResult, EnterCallee, + EnterPending, + WritePending, + LeavePending, RootIssued, SetEdge, GetEdge, @@ -520,6 +539,9 @@ impl HostOwnedFunction for Op { } Self::EnterResult => enter_result(call)?, Self::EnterCallee => enter_callee(call)?, + Self::EnterPending => enter_pending(call)?, + Self::WritePending => write_pending(call)?, + Self::LeavePending => leave_pending(call)?, Self::RootIssued => root_issued(call)?, Self::SetEdge => set_edge(call)?, Self::GetEdge => get_edge(call)?, @@ -772,6 +794,66 @@ fn enter_callee(call: &mut OwnedHostCall<'_>) -> Result { Ok(Value::Float(0.0)) } +fn enter_pending(call: &mut OwnedHostCall<'_>) -> Result { + let width = match call.args() { + [value] => float_u32(value)?, + _ => return Err(host_fault("invalid pending frame")), + }; + let frame = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.enter_roots(width) + }) + .map_err(heap_error)?; + Ok(frame_token(frame)) +} + +fn write_pending(call: &mut OwnedHostCall<'_>) -> Result { + let (frame_token, slot, value) = match call.args() { + [frame, slot, value] => (frame.clone(), float_u32(slot)?, value.clone()), + _ => return Err(host_fault("invalid pending root")), + }; + let table = match classify(&mut call.vm().host_context(), &value)? { + heap::GuestClass::Table(table) => table, + _ => { + if let Ok(frame) = decode_frame(call, &frame_token) { + let _ = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(frame) + }); + } + return Err(host_fault("pending root is not a table")); + } + }; + let frame = decode_frame(call, &frame_token)?; + if let Err(error) = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.write_root(frame, slot, table) + }) { + let _ = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(frame) + }); + return Err(heap_error(error)); + } + Ok(Value::Float(0.0)) +} + +fn leave_pending(call: &mut OwnedHostCall<'_>) -> Result { + let frame_token = match call.args() { + [frame] => frame.clone(), + _ => return Err(host_fault("invalid pending release")), + }; + let frame = decode_frame(call, &frame_token)?; + let current = heap::with_heap(&mut call.vm().host_context(), |heap| { + Ok(heap.current_frame()) + }) + .map_err(heap_error)?; + if current != Some(frame) { + return Err(host_fault("pending release is not the current frame")); + } + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(frame) + }) + .map_err(heap_error)?; + Ok(Value::Float(0.0)) +} + fn root_issued(call: &mut OwnedHostCall<'_>) -> Result { let (value, slot, role) = match call.args() { [value, slot, role] => (value.clone(), float_u32(slot)?, float_u32(role)?), @@ -1286,6 +1368,9 @@ fn note_collect( }) .map_err(heap_error)?; let meter = heap::take_scan_meter(host).map_err(heap_error)?; + if let Some(samples) = host.scope_state_mut::() { + samples.visits.push(meter.root_slot_visits); + } let witness = host .scope_state_mut::() .ok_or_else(|| host_fault("return witness disappeared"))?; @@ -3260,6 +3345,76 @@ impl Lower<'_> { Ok(()) } + /// Value-position direct call. The result is a real Get, not a swallowed + /// null. No root is published here; a later argument still has to root + /// an earlier table before this call can collect. + fn lower_direct_value(&mut self, call: &ast::Expr) -> Result { + let span = call.span(); + if self.in_function { + return Err(self.unsupported(span)); + } + let callee = self + .direct_function_call(call) + .ok_or_else(|| self.unsupported(span))?; + let info = self + .functions + .get(&callee.bytes) + .copied() + .ok_or_else(|| self.unsupported(span))?; + let line = self.line(span); + let transport = self + .builder + .alloc_local_named(&format!("#ret:{}", span.start))?; + let call_expr = Expr::Call(info.index, vec![], vec![], None, None); + let frame_expr = self.caller_frame.map(Expr::Var).unwrap_or(Expr::Null); + let finish = self.call( + FINISH_RETURN, + vec![ + call_expr, + frame_expr.clone(), + Expr::Float(0.0), + Expr::Null, + Expr::Float(if info.callee_width > 0 { 1.0 } else { 0.0 }), + ], + )?; + self.stmts.push(Stmt::Let { + index: transport, + declared_schema: None, + expr: finish, + line, + }); + let result = self + .builder + .alloc_local_named(&format!("#value:{}", span.start))?; + let value = if info.return_count > 0 { + let get = vm::BuiltinFunction::Get.call_index(); + Expr::Call( + get, + vec![], + vec![Expr::Var(transport), Expr::Int(0)], + None, + None, + ) + } else { + Expr::Null + }; + self.stmts.push(Stmt::Let { + index: result, + declared_schema: None, + expr: value, + line, + }); + let retire = self.call( + RETIRE_CALLEE, + vec![ + Expr::Float(if info.callee_width > 0 { 1.0 } else { 0.0 }), + frame_expr, + ], + )?; + self.emit_ignored(retire, line)?; + Ok(Expr::Var(result)) + } + fn field_read( &mut self, base: &ast::Expr, @@ -3399,8 +3554,7 @@ impl Lower<'_> { if !args.exprs.is_empty() { return Err(self.unsupported(expr.span())); } - self.lower_call_local(expr.span(), &[], expr)?; - return Ok(Expr::Null); + return self.lower_direct_value(expr); } if name.is("rawlen") && let [arg] = args.exprs.as_slice() @@ -3520,6 +3674,14 @@ impl Lower<'_> { } } + fn param_is_table(param: &HostParamSchema) -> bool { + matches!( + (¶m.ty, param.passing), + (HostTypeSchema::Resource(key), vm::HostParamPassing::Borrow) + if *key == heap::LuaTableResource::key() + ) + } + fn host_call( &mut self, name: &str, @@ -3542,7 +3704,13 @@ impl Lower<'_> { } let mut checked = Vec::new(); let temp_base = self.active_temps.len(); + let mut pending_slots = Vec::new(); + let mut pending_frames = Vec::new(); for (arg, param) in args.iter().zip(&function.params) { + if self.direct_function_call(arg).is_some() && !pending_slots.is_empty() { + pending_frames.push(self.open_pending_frame(&pending_slots, span)?); + pending_slots.clear(); + } let value = self.expr(arg)?; let slot = self .builder @@ -3554,6 +3722,9 @@ impl Lower<'_> { line: self.line(span), }); self.active_temps.push(slot); + if Self::param_is_table(param) { + pending_slots.push(slot); + } let forwarded = match (¶m.ty, param.passing) { (HostTypeSchema::Float, vm::HostParamPassing::Value) => NUMBER_ARG, (HostTypeSchema::Bool, vm::HostParamPassing::Value) => BOOL_ARG, @@ -3572,7 +3743,55 @@ impl Lower<'_> { checked.push(self.call(forwarded, vec![Expr::Var(slot)])?); } self.active_temps.truncate(temp_base); - self.call(name, checked) + let call_expr = self.call(name, checked)?; + if pending_frames.is_empty() { + return Ok(call_expr); + } + let result = self + .builder + .alloc_local_named(&format!("#host:{}", span.start))?; + self.stmts.push(Stmt::Let { + index: result, + declared_schema: None, + expr: call_expr, + line: self.line(span), + }); + for frame in pending_frames.into_iter().rev() { + let leave = self.call(LEAVE_PENDING, vec![Expr::Var(frame)])?; + self.emit_ignored(leave, self.line(span))?; + } + Ok(Expr::Var(result)) + } + + fn open_pending_frame( + &mut self, + slots: &[vm::LocalSlot], + span: ast::Span, + ) -> Result { + let line = self.line(span); + let width = u32::try_from(slots.len()).map_err(|_| self.unsupported(span))?; + let entered = self.call(ENTER_PENDING, vec![Expr::Float(width as f64)])?; + let frame = self + .builder + .alloc_local_named(&format!("#pending:{}", span.start))?; + self.stmts.push(Stmt::Let { + index: frame, + declared_schema: None, + expr: entered, + line, + }); + for (index, slot) in slots.iter().enumerate() { + let wrote = self.call( + WRITE_PENDING, + vec![ + Expr::Var(frame), + Expr::Float(index as f64), + Expr::Var(*slot), + ], + )?; + self.emit_ignored(wrote, line)?; + } + Ok(frame) } /// Evaluate every static argument on the same temporary-root path as an @@ -3789,6 +4008,11 @@ fn pack_array(values: Vec) -> Expr { ) } +#[derive(Clone, Debug, Default)] +pub(super) struct VisitSamples { + pub visits: Vec, +} + #[derive(Clone, Debug, Default)] pub(super) struct ReturnWitness { pub callee_depth: Option, diff --git a/tests/luajit_heap_runtime/pending_argument.rs b/tests/luajit_heap_runtime/pending_argument.rs new file mode 100644 index 0000000..6f6d90c --- /dev/null +++ b/tests/luajit_heap_runtime/pending_argument.rs @@ -0,0 +1,747 @@ +//! Source-level pending argument: a later zero-arg Lua call may collect. +//! +//! The host stores identities and scalars only. It does not retain a carrier. + +use std::sync::{Arc, OnceLock}; + +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + HostFunctionRegistry, HostImportSchema, HostOwnedFunction, HostParamPassing, HostParamSchema, + HostTypeSchema, OwnedHostCall, ParseError, SourceFlavor, SourcePlugin, Value, VmError, + VmStatus, +}; + +use super::ObservedTable; +use super::candidate; +use super::heap; + +const MARK: &str = "lua_host::mark"; +const PEEK: &str = "lua_host::peek"; +const CONSUME: &str = "lua_host::consume"; +const PIN: &str = "lua_host::pin"; +const AFTER: &str = "lua_host::after"; +const SNAP: &str = "lua_host::snap"; +const NOTE: &str = "lua_host::note"; + +#[derive(Clone, Debug, Default)] +struct Obs { + order: Vec, + peeked: Vec, + consumed: Vec, + snaps: Vec, + notes: Vec<(f64, String)>, +} + +#[derive(Clone, Debug, PartialEq)] +enum Event { + Mark(f64), + Peek, + Consume, + Snap(f64), + Note(f64), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Consumed { + table: heap::TableRef, + token: vm::ResourceHandle, + marker: f64, + live_roots: u32, + root_slots: u32, +} + +#[derive(Clone, Debug, PartialEq)] +struct Snap { + tag: f64, + live_roots: u32, + root_slots: u32, + live_nodes: u32, + collections: u32, + root_slot_visits: u64, + peeked_alive: Vec, +} + +struct Plugin; + +impl SourcePlugin for Plugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, catalog()) + } +} + +fn catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(vm::HostFunctionSchema::with_return( + MARK, + vec![HostParamSchema::value("tag", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + PEEK, + vec![HostParamSchema::with_passing( + "table", + table.clone(), + HostParamPassing::Borrow, + )], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + CONSUME, + vec![ + HostParamSchema::with_passing("table", table.clone(), HostParamPassing::Borrow), + HostParamSchema::value("marker", HostTypeSchema::Float), + ], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + PIN, + vec![ + HostParamSchema::with_passing("left", table.clone(), HostParamPassing::Borrow), + HostParamSchema::with_passing("right", table.clone(), HostParamPassing::Borrow), + HostParamSchema::value("marker", HostTypeSchema::Float), + ], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + AFTER, + vec![ + HostParamSchema::value("marker", HostTypeSchema::Float), + HostParamSchema::with_passing("table", table, HostParamPassing::Borrow), + ], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + SNAP, + vec![HostParamSchema::value("tag", HostTypeSchema::Float)], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + NOTE, + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("text", HostTypeSchema::String), + ], + HostTypeSchema::Bool, + )); + Arc::new(builder.build().unwrap()) + }) +} + +fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + for (name, op) in [ + (MARK, HostOp::Mark), + (PEEK, HostOp::Peek), + (CONSUME, HostOp::Consume), + (PIN, HostOp::Pin), + (AFTER, HostOp::After), + (SNAP, HostOp::Snap), + (NOTE, HostOp::Note), + ] { + let function = catalog.function(name).expect("pending host schema"); + registry + .register_exact_owned( + name, + function.params.len() as u8, + HostImportSchema::from_function(catalog, function), + move |_| Box::new(op), + ) + .expect("register pending host"); + } +} + +#[derive(Clone, Copy)] +enum HostOp { + Mark, + Peek, + Consume, + Pin, + After, + Snap, + Note, +} + +impl HostOwnedFunction for HostOp { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let args = call.args().to_vec(); + let mut host = call.vm().host_context(); + let value = match self { + Self::Mark => { + let [Value::Float(tag)] = args.as_slice() else { + return Err(host_fault("expected stage tag")); + }; + let tag = *tag; + note(&mut host, |state| state.order.push(Event::Mark(tag)))?; + Value::Float(tag) + } + Self::Peek => { + let observed = borrowed_table(&mut host, &args[0])?; + let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(observed.table))) + .map_err(|error| VmError::HostError(error.to_string()))?; + note(&mut host, |state| { + state.order.push(Event::Peek); + state.peeked.push(observed); + })?; + Value::Bool(alive) + } + Self::Consume | Self::Pin => { + let observed = borrowed_table(&mut host, &args[0])?; + let marker = match args.last() { + Some(Value::Float(marker)) => *marker, + _ => return Err(host_fault("expected marker")), + }; + let (live_roots, root_slots) = heap::with_heap(&mut host, |heap| { + let stats = heap.stats(); + Ok((stats.live_roots, stats.root_slots)) + }) + .map_err(|error| VmError::HostError(error.to_string()))?; + note(&mut host, |state| { + state.order.push(Event::Consume); + state.consumed.push(Consumed { + table: observed.table, + token: observed.token, + marker, + live_roots, + root_slots, + }); + })?; + Value::Float(marker) + } + Self::After => { + let marker = match args.first() { + Some(Value::Float(marker)) => *marker, + _ => return Err(host_fault("expected marker")), + }; + let observed = borrowed_table(&mut host, &args[1])?; + note(&mut host, |state| { + state.order.push(Event::Consume); + state.consumed.push(Consumed { + table: observed.table, + token: observed.token, + marker, + live_roots: 0, + root_slots: 0, + }); + })?; + Value::Float(marker) + } + Self::Snap => { + let [Value::Float(tag)] = args.as_slice() else { + return Err(host_fault("expected snap tag")); + }; + let tag = *tag; + let peeked = note(&mut host, |state| state.peeked.clone())?; + let (stats, visits) = heap::with_heap(&mut host, |heap| { + Ok((heap.stats(), heap.take_scan_meter().root_slot_visits)) + }) + .map_err(|error| VmError::HostError(error.to_string()))?; + let alive = peeked + .iter() + .map(|item| { + heap::with_heap(&mut host, |heap| Ok(heap.alive(item.table))) + .unwrap_or(false) + }) + .collect(); + note(&mut host, |state| { + state.order.push(Event::Snap(tag)); + state.snaps.push(Snap { + tag, + live_roots: stats.live_roots, + root_slots: stats.root_slots, + live_nodes: stats.live_nodes, + collections: stats.collections, + root_slot_visits: visits, + peeked_alive: alive, + }); + })?; + Value::Bool(true) + } + Self::Note => { + let [Value::Float(tag), Value::String(text)] = args.as_slice() else { + return Err(host_fault("expected note")); + }; + let noted = (*tag, text.to_string()); + note(&mut host, |state| { + state.order.push(Event::Note(noted.0)); + state.notes.push(noted); + })?; + Value::Bool(true) + } + }; + Ok(CallOutcome::Return(CallReturn::one(value))) + } +} + +fn note(host: &mut vm::HostContext<'_>, body: impl FnOnce(&mut Obs) -> T) -> Result { + let state = host + .scope_state_or_insert_with(Obs::default) + .map_err(|error| VmError::HostError(error.to_string()))?; + Ok(body(state)) +} + +fn borrowed_table(host: &mut vm::HostContext<'_>, value: &Value) -> Result { + let Value::Int(raw) = value else { + return Err(host_fault("expected table token")); + }; + let token = vm::ResourceHandle::from_raw( + u64::try_from(*raw).map_err(|_| host_fault("table token out of range"))?, + ) + .map_err(|_| host_fault("table token out of range"))?; + let key = heap::LuaTableResource::key(); + let table = host + .borrow_resource_with_key::(token, &key) + .map_err(|error| VmError::HostError(error.to_string()))? + .table(); + Ok(ObservedTable { table, token }) +} + +fn host_fault(message: &str) -> VmError { + VmError::HostError(message.to_string()) +} + +struct Ran { + status: Result, + stack: Vec, + obs: Obs, + live_roots: u32, + root_slots: u32, + collections: u32, + visits: Vec, + returned: Option, + discarded: Option, + issued: usize, +} + +fn run_source(source: &str) -> Ran { + run_with(source, None) +} + +fn run_with(source: &str, roots: Option) -> Ran { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .unwrap_or_else(|error| panic!("compile rejected the source: {error}")); + let mut vm = prepared.into_vm().expect("create VM"); + if let Some(roots) = roots { + heap::install( + &mut vm.host_context(), + heap::HeapLimits { + nodes: 4096, + roots, + edges: 8192, + max_generation: u32::MAX, + }, + ) + .unwrap_or_else(|error| panic!("install: {error}")); + } + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind runtime"); + vm.host_context() + .scope_state_or_insert_with(candidate::VisitSamples::default) + .expect("visit samples"); + let status = vm.run().map_err(|error| error.to_string()); + let obs = vm + .host_context() + .scope_state::() + .cloned() + .unwrap_or_default(); + let (live_roots, root_slots, collections) = heap::with_heap(&mut vm.host_context(), |heap| { + let stats = heap.stats(); + Ok((stats.live_roots, stats.root_slots, stats.collections)) + }) + .unwrap_or((u32::MAX, u32::MAX, u32::MAX)); + let visits = vm + .host_context() + .scope_state::() + .map(|samples| samples.visits.clone()) + .unwrap_or_default(); + let (returned, discarded, issued) = vm + .host_context() + .scope_state::() + .map(|witness| (witness.returned, witness.discarded, witness.issued.len())) + .unwrap_or((None, None, 0)); + let stack = vm.stack().to_vec(); + Ran { + status, + stack, + obs, + live_roots, + root_slots, + collections, + visits, + returned, + discarded, + issued, + } +} + +const SEEDED: &str = r#" +local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local target = {} + target.self = target + rawset(weak, 1, target) + local orphan = {} + orphan.self = orphan + rawset(weak, 2, orphan) + return weak +end +local weak = seed() +local function sweep() + mark(2) + collectgarbage("collect") + snap(2) + mark(41) + return 41 +end +peek(rawget(weak, 1)) +peek(rawget(weak, 2)) +local marker = consume(rawget(weak, (mark(1))), sweep()) +snap(4) +note(6, type(rawget(weak, 1))) +note(7, type(rawget(weak, 2))) +collectgarbage("collect") +snap(5) +note(8, type(rawget(weak, 1))) +return marker +"#; + +#[test] +fn pending_argument_value_call_returns_the_marker() { + let ran = run_source( + r#" +local function sweep() + return 41 +end +return sweep() +"#, + ); + assert_eq!(ran.status, Ok(VmStatus::Halted), "{ran:?}"); + assert_eq!(ran.stack, vec![Value::Float(41.0)], "{ran:?}"); +} + +#[test] +fn pending_argument_keeps_the_earlier_table_across_the_later_lua_collect() { + let ran = run_source(SEEDED); + assert_eq!( + ran.status, + Ok(VmStatus::Halted), + "status={:?} stack={:?} order={:?} snaps={:?} notes={:?} collections={} roots={}/{}", + ran.status, + ran.stack, + ran.obs.order, + ran.obs.snaps, + ran.obs.notes, + ran.collections, + ran.live_roots, + ran.root_slots, + ); + assert_eq!(ran.stack, vec![Value::Float(41.0)]); + assert_eq!( + ran.obs.order, + vec![ + Event::Peek, + Event::Peek, + Event::Mark(1.0), + Event::Mark(2.0), + Event::Snap(2.0), + Event::Mark(41.0), + Event::Consume, + Event::Snap(4.0), + Event::Note(6.0), + Event::Note(7.0), + Event::Snap(5.0), + Event::Note(8.0), + ] + ); + let target = ran.obs.peeked[0]; + let orphan = ran.obs.peeked[1]; + assert_ne!(target.table, orphan.table); + let consumed = ran + .obs + .consumed + .first() + .expect("consumer stored the identity"); + assert_eq!(consumed.table, target.table); + assert_eq!(consumed.token, target.token); + assert_eq!(consumed.marker, 41.0); + assert_eq!( + consumed.root_slots, 2, + "caller frame plus the pending frame" + ); + assert_eq!(consumed.live_roots, 2, "weak table and the pending table"); + let nested = snap(&ran, 2.0); + let released = snap(&ran, 4.0); + let later = snap(&ran, 5.0); + assert_eq!(nested.peeked_alive, vec![true, false]); + assert_eq!(nested.root_slots, 2); + assert_eq!(nested.live_roots, 2); + assert_eq!(nested.collections, 1); + assert_eq!( + nested.root_slot_visits, 0, + "return witness already took this meter" + ); + assert_eq!( + ran.visits, + vec![4, 2], + "nested and later collects stay separate" + ); + assert_ne!(ran.visits[0], nested.root_slots as u64); + assert_ne!(ran.visits[0], nested.live_roots as u64); + assert_eq!( + released.root_slots, 1, + "pending frame left before the next snap" + ); + assert_eq!(released.live_roots, 1); + assert_eq!(released.peeked_alive, vec![true, false]); + assert_eq!(later.peeked_alive, vec![false, false]); + assert_eq!(later.collections, 2); + assert_eq!(later.root_slots, 1); + assert_eq!(later.root_slot_visits, 0); + assert_ne!(ran.visits[0], ran.visits[1]); + assert_eq!( + ran.obs.notes, + vec![ + (6.0, "table".to_string()), + (7.0, "nil".to_string()), + (8.0, "nil".to_string()), + ] + ); + assert_eq!(ran.live_roots, 0, "chunk retire returned the caller frame"); + assert_eq!(ran.root_slots, 0); + assert_eq!( + ran.issued, 4, + "pending publish did not issue another witness root" + ); + assert_ne!(ran.returned, Some(target.table)); + assert_ne!(ran.discarded, Some(target.table)); +} + +#[test] +fn pending_argument_repeat_reuses_the_returned_frame() { + let ran = run_source( + r#" +local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local target = {} + target.self = target + rawset(weak, 1, target) + return weak +end +local weak = seed() +local function sweep() + collectgarbage("collect") + return 41 +end +local first = consume(rawget(weak, 1), sweep()) +local second = consume(rawget(weak, 1), sweep()) +return first + second +"#, + ); + assert_eq!(ran.status, Ok(VmStatus::Halted), "{ran:?}"); + assert_eq!(ran.stack, vec![Value::Float(82.0)], "{ran:?}"); + assert_eq!(ran.obs.consumed.len(), 2); + assert_eq!(ran.obs.consumed[0].table, ran.obs.consumed[1].table); + assert_eq!(ran.obs.consumed[0].root_slots, 2); + assert_eq!( + ran.obs.consumed[1].root_slots, 2, + "the first frame was returned" + ); + assert_eq!(ran.root_slots, 0); +} + +#[test] +fn pending_argument_omits_the_root_without_a_nested_safepoint() { + let ran = run_source( + r#" +local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local target = {} + target.self = target + rawset(weak, 1, target) + return weak +end +local weak = seed() +local marker = consume(rawget(weak, 1), 41) +note(9, type(rawget(weak, 1))) +return marker +"#, + ); + assert_eq!(ran.status, Ok(VmStatus::Halted), "{ran:?}"); + assert_eq!(ran.stack, vec![Value::Float(41.0)]); + assert_eq!( + ran.obs.consumed[0].root_slots, 1, + "scalar arg added no frame" + ); + assert_eq!(ran.obs.notes, vec![(9.0, "table".to_string())]); + assert!(ran.visits.is_empty()); +} + +#[test] +fn pending_argument_statement_sweep_collects_without_a_pending_root() { + let ran = run_source( + r#" +local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local target = {} + target.self = target + rawset(weak, 1, target) + local orphan = {} + orphan.self = orphan + rawset(weak, 2, orphan) + return weak +end +local weak = seed() +peek(rawget(weak, 1)) +peek(rawget(weak, 2)) +local function sweep() + collectgarbage("collect") + snap(2) + return 41 +end +sweep() +note(9, type(rawget(weak, 1))) +return 41 +"#, + ); + assert_eq!(ran.status, Ok(VmStatus::Halted), "{ran:?}"); + assert_eq!(ran.stack, vec![Value::Float(41.0)]); + assert!(ran.obs.consumed.is_empty()); + assert_eq!(snap(&ran, 2.0).peeked_alive, vec![false, false]); + assert_eq!(snap(&ran, 2.0).root_slots, 1); + assert_eq!(ran.visits, vec![2]); + assert_eq!(ran.obs.notes, vec![(9.0, "nil".to_string())]); +} + +#[test] +fn pending_argument_reverse_get_is_already_collected() { + let ran = run_source( + r#" +local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local target = {} + target.self = target + rawset(weak, 1, target) + return weak +end +local weak = seed() +peek(rawget(weak, 1)) +local function sweep() + collectgarbage("collect") + snap(2) + return 41 +end +return after(sweep(), rawget(weak, 1)) +"#, + ); + assert!(ran.status.is_err(), "{ran:?}"); + assert!(ran.obs.consumed.is_empty(), "{ran:?}"); + assert_eq!(snap(&ran, 2.0).peeked_alive, vec![false]); + assert_eq!(snap(&ran, 2.0).root_slots, 1); + assert_eq!(ran.visits, vec![2]); + assert_eq!(ran.root_slots, 1, "failed get did not keep a pending frame"); +} + +#[test] +fn pending_argument_rejects_a_forged_carrier() { + let ran = run_source( + r#" +local function sweep() + mark(2) + return 41 +end +return consume(7, sweep()) +"#, + ); + assert!(ran.status.is_err(), "{ran:?}"); + assert!(ran.obs.order.is_empty(), "the later call must not start"); + assert_eq!(ran.root_slots, 0); + assert!(ran.visits.is_empty()); +} + +#[test] +fn pending_argument_capacity_diverges_only_at_the_pending_frame() { + let source = r#" +local function seed() + local weak = {} + rawset(weak, 1, weak) + return weak +end +local weak = seed() +local function sweep() + return 41 +end +return pin(rawget(weak, 1), rawget(weak, 1), sweep()) +"#; + let tight = run_with(source, Some(2)); + assert!(tight.status.is_err(), "{tight:?}"); + assert!(tight.obs.consumed.is_empty(), "{tight:?}"); + assert_eq!(tight.root_slots, 1, "admission failure must not grow slots"); + assert!(tight.visits.is_empty()); + let wide = run_with(source, Some(3)); + assert_eq!(wide.status, Ok(VmStatus::Halted), "{wide:?}"); + assert_eq!(wide.stack, vec![Value::Float(41.0)]); + assert_eq!(wide.obs.consumed[0].root_slots, 3); + assert_eq!(wide.root_slots, 0); +} + +fn snap(ran: &Ran, tag: f64) -> &Snap { + ran.obs + .snaps + .iter() + .find(|snap| snap.tag == tag) + .unwrap_or_else(|| panic!("missing snap {tag}")) +} + +impl std::fmt::Debug for Ran { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Ran") + .field("status", &self.status) + .field("stack", &self.stack) + .field("order", &self.obs.order) + .field("snaps", &self.obs.snaps) + .field("notes", &self.obs.notes) + .field("consumed", &self.obs.consumed) + .field("collections", &self.collections) + .field("live_roots", &self.live_roots) + .field("root_slots", &self.root_slots) + .field("visits", &self.visits) + .field("issued", &self.issued) + .finish() + } +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index c582901..d1efe7e 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -12,6 +12,8 @@ mod envelope_local_root; mod lexer; #[path = "../../src/frontends/lua/parser.rs"] mod parser; +#[path = "pending_argument.rs"] +mod pending_argument; #[path = "rawequal.rs"] mod rawequal; #[path = "rawset.rs"] From 7b31656199475e8f42a4ca22e24f7d833df01474 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 03:31:48 +0800 Subject: [PATCH 110/225] feat(lua/heap): observe a private cycle before it releases dead tables One host call marks, closes doomed tokens, and lends the published weak graph once after owners and before release. An existing mark is refused without clearing it, and a failed close publishes nothing. --- src/frontends/lua/heap.rs | 19 +- src/frontends/lua/heap/table.rs | 26 + src/frontends/lua/heap/table/sweep.rs | 145 +++++ tests/luajit_heap_runtime/private_cycle.rs | 703 +++++++++++++++++++++ 4 files changed, 891 insertions(+), 2 deletions(-) create mode 100644 tests/luajit_heap_runtime/private_cycle.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 8d5ea76..9f66de7 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -52,8 +52,8 @@ mod table; pub use handle::{ClosureRef, HandleKind, TableRef, UpvalueRef}; pub use resource::LuaTableResource; pub use table::{ - CellValue, CollectReport, GuestClass, HeapError, HeapLimits, HeapStats, LuaHeap, RootFrameId, - ScanMeter, + CellValue, CollectReport, GuestClass, HeapError, HeapLimits, HeapStats, LuaHeap, ObserveFault, + PublishedRead, RootFrameId, ScanMeter, }; use vm::{HostContext, Value}; @@ -178,6 +178,21 @@ pub fn collect(host: &mut HostContext) -> Result( + host: &mut HostContext, + observe: impl for<'a> FnOnce(&'a PublishedRead<'a>) -> R, +) -> Result<(table::CollectReport, Option), HeapError> { + let marked = with_heap(host, |heap| heap.begin_private_cycle())?; + for token in marked.tokens { + retire_doomed_token(host, token)?; + } + with_heap(host, |heap| Ok(heap.sweep_observing(marked.modes, observe))) +} + fn retire_doomed_token(host: &mut HostContext, token: table::DoomedToken) -> Result<(), HeapError> { let handle = vm::ResourceHandle::from_raw(token.raw).map_err(|_| HeapError::CarrierOutOfRange)?; diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index e299213..c8b9b07 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -25,6 +25,7 @@ use mark::MarkSession; use mark::{ParkedMark, PausedOp, PendingScan}; use pending_close::{PendingCloseSession, PendingCloseView}; use sweep::SweepSession; +pub use sweep::{ObserveFault, PublishedRead}; static NEXT_DOMAIN: AtomicU64 = AtomicU64::new(1); @@ -1915,6 +1916,28 @@ impl LuaHeap { session.report() } + /// Refuses a parked mark without clearing it. Otherwise the same fresh + /// mark and pending-close enumeration as [`Self::mark_and_doomed_tokens`]. + pub(super) fn begin_private_cycle(&mut self) -> Result { + if self.mark.is_some() { + return Err(HeapError::MarkActive); + } + Ok(self.mark_and_doomed_tokens()) + } + + /// Same sweep session from selection through release. The callback runs + /// once, after Owners and before Release, and only when a dead slot exists. + pub(super) fn sweep_observing( + &mut self, + modes: MarkSnapshot, + observe: impl for<'a> FnOnce(&'a PublishedRead<'a>) -> R, + ) -> (CollectReport, Option) { + let mut session = SweepSession::start(self, modes); + let seen = session.observe_before_release(observe); + session.drain(); + (session.report(), seen) + } + /// Reports whether `handle` names a live table in this heap. pub fn alive(&self, handle: TableRef) -> bool { self.require_live(handle).is_ok() @@ -2353,5 +2376,8 @@ mod parked_lifecycle; #[path = "../../../../tests/luajit_heap_runtime/parked_mark.rs"] mod parked_mark; #[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/private_cycle.rs"] +mod private_cycle; +#[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/safepoint_roots.rs"] mod safepoint_roots; diff --git a/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs index a2446c5..ee346a3 100644 --- a/src/frontends/lua/heap/table/sweep.rs +++ b/src/frontends/lua/heap/table/sweep.rs @@ -151,6 +151,47 @@ impl<'a> SweepSession<'a> { self.report.take().expect("sweep report is issued once") } + /// Walk Select and Snapshot by their real units, then stop before the + /// first owner unit. An empty dead set is already Roots. This does not + /// call `pulse`. + pub(super) fn reach_before_owners(&mut self) -> bool { + loop { + match self.phase { + SweepPhase::Select | SweepPhase::Snapshot => { + let _ = self.step(); + } + SweepPhase::Owners => { + debug_assert!(self.at_owner_start()); + return true; + } + SweepPhase::Roots => return false, + SweepPhase::Release | SweepPhase::Done => { + debug_assert!(false, "release started before the owner boundary"); + return false; + } + } + } + } + + /// Publish every owner in this same session, lend one read-only view, and + /// return before Release. No dead slot means no view and no callback. + pub(super) fn observe_before_release( + &mut self, + observe: impl for<'b> FnOnce(&'b PublishedRead<'b>) -> R, + ) -> Option { + if !self.reach_before_owners() { + return None; + } + let seen = { + let window = self + .publish_owners() + .expect("the owner boundary is the first owner unit"); + let read = window.published(); + observe(&read) + }; + Some(seen) + } + fn view(&self, spent: SweepUnits) -> SweepView { SweepView { finished: matches!(self.phase, SweepPhase::Done), @@ -501,6 +542,23 @@ struct PublishWindow<'a> { view: WeakView<'a>, } +impl PublishWindow<'_> { + fn published(&self) -> PublishedRead<'_> { + PublishedRead { + view: WeakView { + publish: self.view.publish, + finished: self.view.finished, + release_started: self.view.release_started, + heap: self.view.heap, + dead: self.view.dead, + snapshot: self.view.snapshot, + }, + heads: self.spent.heads, + edges: self.spent.edges, + } + } +} + /// Read-only graph at one boundary. A judged-dead handle is not a target. struct WeakView<'a> { publish: WeakPublish, @@ -612,6 +670,93 @@ impl WeakView<'_> { } } +/// Why a published-boundary read was refused. A judged-dead handle is not a +/// lookup target. This error does not carry a slot index. +#[derive(Debug)] +pub enum ObserveFault { + JudgedDead, + Heap(HeapError), +} + +/// Values at the published boundary. The dead-slot list, snapshot, and heap +/// stay behind this view. +pub struct PublishedRead<'a> { + view: WeakView<'a>, + heads: u64, + edges: u64, +} + +impl PublishedRead<'_> { + pub fn named(&self, table: TableRef, name: &str) -> Result, ObserveFault> { + self.view.named(table, name).map_err(Self::fault) + } + + pub fn number(&self, table: TableRef, key: f64) -> Result { + self.view.number(table, key).map_err(Self::fault) + } + + pub fn object(&self, table: TableRef, key: TableRef) -> Result, ObserveFault> { + self.view.object(table, key).map_err(Self::fault) + } + + pub fn raw_sequence_len(&self, table: TableRef) -> Result { + self.view.raw_sequence_len(table).map_err(Self::fault) + } + + pub fn next( + &self, + table: TableRef, + cursor: &Value, + ) -> Result, ObserveFault> { + self.view.next(table, cursor).map_err(Self::fault) + } + + pub fn alive(&self, table: TableRef) -> Result { + self.view.alive(table).map_err(Self::fault) + } + + pub fn still_physical(&self, table: TableRef) -> bool { + let slot = table.slot(); + self.view.still_physical(slot) + && self + .view + .snapshot + .get(slot as usize) + .is_some_and(|snap| snap.generation == table.generation()) + } + + pub fn dead_still_physical(&self) -> u32 { + self.view.dead_still_physical() + } + + pub fn occupying_dead(&self) -> u32 { + self.view.occupying_dead() + } + + pub fn finished(&self) -> bool { + self.view.finished() + } + + pub fn release_started(&self) -> bool { + self.view.release_started() + } + + pub fn window_heads(&self) -> u64 { + self.heads + } + + pub fn window_edges(&self) -> u64 { + self.edges + } + + fn fault(error: ObserveError) -> ObserveFault { + match error { + ObserveError::JudgedDead => ObserveFault::JudgedDead, + ObserveError::Heap(error) => ObserveFault::Heap(error), + } + } +} + #[cfg(test)] #[path = "../../../../../tests/luajit_heap_runtime/weak_publish.rs"] mod weak_publish; diff --git a/tests/luajit_heap_runtime/private_cycle.rs b/tests/luajit_heap_runtime/private_cycle.rs new file mode 100644 index 0000000..d48f778 --- /dev/null +++ b/tests/luajit_heap_runtime/private_cycle.rs @@ -0,0 +1,703 @@ +//! One host call starts its own mark, closes doomed tokens, and observes the +//! published weak graph once before that same sweep releases dead nodes. + +use std::cell::Cell; + +use super::{HeapError, HeapLimits, LuaHeap, ParkedMark, TableRef}; +use vm::Value; + +const TABLES: u32 = 32; +const TEXT_TABLES: u32 = 16; +const NUMBER_TABLES: u32 = 8; + +struct Counts { + nodes: u32, + roots: u32, + edges: u32, + rooted: u32, + weak: u32, +} + +fn counts(shared_metatable: bool) -> Counts { + let object_tables = TABLES - TEXT_TABLES - NUMBER_TABLES; + let metatables = if shared_metatable { 1 } else { TABLES }; + let object_keys = object_tables * 2; + Counts { + nodes: metatables + TABLES * 4 + object_keys, + roots: metatables + TABLES * 2 + object_keys, + edges: metatables + TABLES * 3 + TABLES * 2, + rooted: metatables + TABLES * 2 + object_keys, + weak: TABLES * 2, + } +} + +#[derive(Clone, Copy)] +enum Kind { + Text, + Number, + Object, +} + +struct Owner { + owner: TableRef, + owner_raw: i64, + live: TableRef, + live_carrier: Value, + first: TableRef, + first_carrier: Value, + second: TableRef, + kind: Kind, + keys: Vec, + key_carriers: Vec, +} + +struct Graph { + owners: Vec, + weak: Vec, + weak_raws: Vec, + counts: Counts, +} + +struct Seen { + heads: u64, + edges: u64, + weak_left: u32, + strong_kept: u32, + dead_physical: u32, + occupying: u32, + finished: bool, + release_started: bool, + judged_dead: bool, + rawlen_cleared: bool, + next_kept: bool, +} + +fn limits(counts: &Counts) -> HeapLimits { + HeapLimits { + nodes: counts.nodes, + roots: counts.roots, + edges: counts.edges, + max_generation: 8, + } +} + +fn alloc_node(host: &mut vm::HostContext<'_>) -> TableRef { + crate::heap::with_heap(host, LuaHeap::alloc).expect("node") +} + +fn publish_node(host: &mut vm::HostContext<'_>) -> (TableRef, i64) { + let raw = crate::publish_raw(host); + (crate::table_ref(host, raw), raw) +} + +fn build_graph(host: &mut vm::HostContext<'_>, shared_metatable: bool) -> Graph { + let counts = counts(shared_metatable); + crate::heap::install(host, limits(&counts)).expect("limits"); + let shared = shared_metatable.then(|| alloc_node(host)); + let mut owners = Vec::new(); + let mut weak = Vec::new(); + let mut weak_raws = Vec::new(); + let mut rooted = Vec::new(); + if let Some(metatable) = shared { + rooted.push(metatable); + } + for index in 0..TABLES { + let metatable = shared.unwrap_or_else(|| { + let table = alloc_node(host); + rooted.push(table); + table + }); + let (owner, owner_raw) = publish_node(host); + let (live, _live_raw) = publish_node(host); + let (first, first_raw) = publish_node(host); + let (second, second_raw) = publish_node(host); + rooted.push(owner); + rooted.push(live); + weak.push(first); + weak.push(second); + weak_raws.push(first_raw); + weak_raws.push(second_raw); + let kind = if index < TEXT_TABLES { + Kind::Text + } else if index < TEXT_TABLES + NUMBER_TABLES { + Kind::Number + } else { + Kind::Object + }; + let mut key_carriers = Vec::new(); + let mut keys = Vec::new(); + if matches!(kind, Kind::Object) { + for _ in 0..2 { + let key = alloc_node(host); + rooted.push(key); + keys.push(key); + } + } + let carriers = crate::heap::with_heap(host, |heap| { + heap.set_metatable(owner, Some(metatable)) + .expect("metatable"); + if shared.is_none() || index == 0 { + heap.set_mode_scalar(metatable, Value::string("v")) + .expect("mode"); + } + let live_carrier = heap.issue_carrier(live).expect("live carrier"); + let first_carrier = heap.issue_carrier(first).expect("first carrier"); + let _second_carrier = heap.issue_carrier(second).expect("second carrier"); + for key in &keys { + key_carriers.push(heap.issue_carrier(*key).expect("key carrier")); + } + match kind { + Kind::Text => { + heap.set_named_edge(owner, "a", first).expect("a"); + heap.set_named_edge(owner, "stay", live).expect("stay"); + heap.set_named_edge(owner, "b", second).expect("b"); + } + Kind::Number => { + heap.set_number_edge(owner, 1.0, first).expect("1"); + heap.set_number_edge(owner, 2.0, second).expect("2"); + heap.set_named_edge(owner, "stay", live).expect("stay"); + } + Kind::Object => { + heap.set_object_edge(owner, keys[0], first).expect("left"); + heap.set_named_edge(owner, "stay", live).expect("stay"); + heap.set_object_edge(owner, keys[1], second).expect("right"); + } + } + heap.set_named_edge(first, "self", first) + .expect("first self"); + heap.set_named_edge(second, "self", second) + .expect("second self"); + Ok((live_carrier, first_carrier)) + }) + .expect("edges"); + owners.push(Owner { + owner, + owner_raw, + live, + live_carrier: carriers.0, + first, + first_carrier: carriers.1, + second, + kind, + keys, + key_carriers, + }); + } + crate::heap::with_heap(host, |heap| { + let frame = heap.enter_roots(rooted.len() as u32).expect("roots"); + for (index, table) in rooted.iter().enumerate() { + heap.write_root(frame, index as u32, *table).expect("root"); + } + let stats = heap.stats(); + assert_eq!(stats.node_slots, counts.nodes, "node accounting"); + assert_eq!( + stats.live_nodes, counts.nodes, + "all nodes live before collect" + ); + assert_eq!(stats.live_roots, counts.roots, "root accounting"); + assert_eq!(stats.edge_slots, counts.edges, "edge accounting"); + assert_eq!(weak.len() as u32, counts.weak, "weak node accounting"); + Ok(()) + }) + .expect("root"); + Graph { + owners, + weak, + weak_raws, + counts, + } +} + +fn token_open(host: &vm::HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + crate::resource_handle(raw), + &crate::heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn same_table(found: Option, expected: TableRef) -> bool { + found.is_some_and(|table| table == expected) +} + +fn read_published(view: &crate::heap::PublishedRead<'_>, graph: &Graph) -> Seen { + assert!(!view.finished(), "observation is not a finished sweep"); + assert!( + !view.release_started(), + "release has not started at the published boundary" + ); + assert_eq!(view.window_heads(), u64::from(graph.counts.nodes)); + assert_eq!(view.window_edges(), u64::from(graph.counts.edges)); + assert_eq!(view.occupying_dead(), graph.counts.weak); + let stale = TableRef::table( + graph.owners[0].owner.domain(), + graph.owners[0].owner.slot(), + graph.owners[0].owner.generation().wrapping_add(1), + ); + match view.named(stale, "stay") { + Err(crate::heap::ObserveFault::Heap(error)) => { + assert_eq!( + error, + HeapError::StaleHandle, + "a stale handle is not a slot index" + ); + } + other => panic!("stale handle must be a heap refusal, got {other:?}"), + } + assert_eq!( + view.dead_still_physical(), + graph.counts.weak, + "dead slots are still physical before release" + ); + let mut weak_left = 0; + let mut strong_kept = 0; + let mut rawlen_cleared = true; + let mut next_kept = true; + let mut judged_dead = true; + for owner in &graph.owners { + let stay = view + .named(owner.owner, "stay") + .expect("stay lookup") + .expect("strong value stays"); + assert_eq!(stay, owner.live); + strong_kept += 1; + match owner.kind { + Kind::Text => { + let left = view.named(owner.owner, "a").expect("text left"); + let right = view.named(owner.owner, "b").expect("text right"); + weak_left += u32::from(same_table(left, owner.first)); + weak_left += u32::from(same_table(right, owner.second)); + let continued = view + .next(owner.owner, &Value::string("a")) + .expect("text next"); + let Some((key, value)) = continued else { + next_kept = false; + continue; + }; + if key != Value::string("stay") || value != owner.live_carrier { + next_kept = false; + } + let dead_cursor = view.next(owner.owner, &owner.first_carrier); + judged_dead &= matches!(dead_cursor, Err(crate::heap::ObserveFault::JudgedDead)); + } + Kind::Number => { + let first = view.number(owner.owner, 1.0).expect("number 1"); + let second = view.number(owner.owner, 2.0).expect("number 2"); + weak_left += u32::from(first != Value::Null); + weak_left += u32::from(second != Value::Null); + let length = view.raw_sequence_len(owner.owner).expect("rawlen"); + rawlen_cleared &= length == 0.0; + } + Kind::Object => { + let left = view + .object(owner.owner, owner.keys[0]) + .expect("object left"); + let right = view + .object(owner.owner, owner.keys[1]) + .expect("object right"); + weak_left += u32::from(same_table(left, owner.first)); + weak_left += u32::from(same_table(right, owner.second)); + let continued = view + .next(owner.owner, &owner.key_carriers[0]) + .expect("object next"); + let Some((key, value)) = continued else { + next_kept = false; + continue; + }; + if key != Value::string("stay") || value != owner.live_carrier { + next_kept = false; + } + } + } + } + for table in &graph.weak { + assert!( + view.still_physical(*table), + "doomed table is physical at the published boundary" + ); + let alive = view.alive(*table); + judged_dead &= matches!(alive, Err(crate::heap::ObserveFault::JudgedDead)); + } + Seen { + heads: view.window_heads(), + edges: view.window_edges(), + weak_left, + strong_kept, + dead_physical: view.dead_still_physical(), + occupying: view.occupying_dead(), + finished: view.finished(), + release_started: view.release_started(), + judged_dead, + rawlen_cleared, + next_kept, + } +} + +fn assert_cycle(host: &mut vm::HostContext<'_>, graph: &Graph, seen: &Seen) { + assert_eq!(seen.weak_left, 0, "no partial owner kept a weak value"); + assert_eq!(seen.strong_kept, TABLES, "strong values stayed"); + assert!(seen.judged_dead, "dead handles are rejected before release"); + assert!(seen.rawlen_cleared, "weak number sequence was cleared"); + assert!(seen.next_kept, "next continued past cleared weak entries"); + assert!(!seen.finished); + assert!(!seen.release_started); + assert_eq!(seen.dead_physical, graph.counts.weak); + assert_eq!(seen.occupying, graph.counts.weak); + let report_nodes = + crate::heap::with_heap(host, |heap| Ok(heap.stats().live_nodes)).expect("stats"); + assert_eq!( + report_nodes, graph.counts.rooted, + "release removed the weak nodes after observation" + ); + for table in &graph.weak { + assert!(!crate::heap::with_heap(host, |heap| Ok(heap.alive(*table))).expect("alive")); + } + for raw in &graph.weak_raws { + assert!(!token_open(host, *raw), "doomed token stays closed"); + } + assert!( + token_open(host, graph.owners[0].owner_raw), + "rooted token stays open" + ); +} + +fn run_shared(shared_metatable: bool) { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_graph(&mut host, shared_metatable); + let before_resources = host.resource_count(); + let events = Cell::new(0u32); + let (report, seen) = crate::heap::collect_observing(&mut host, |view| { + events.set(events.get() + 1); + read_published(view, &graph) + }) + .expect("private cycle returns one report"); + assert_eq!( + report.live_nodes, graph.counts.rooted, + "collect finished; observation is the missing boundary" + ); + assert_eq!( + events.get(), + 1, + "published observation missing after collect" + ); + let seen = seen.expect("published observation missing"); + assert_eq!(events.get(), 1, "observer ran more than once"); + assert_cycle(&mut host, &graph, &seen); + let meter = + crate::heap::with_heap(&mut host, |heap| Ok(heap.take_scan_meter())).expect("meter"); + assert_eq!(meter.mark_passes, 1, "one fresh mark"); + assert_eq!(meter.token_closes, u64::from(graph.counts.weak)); + assert_eq!( + meter.sweep_edge_checks, seen.edges, + "observation added no sweep edges" + ); + assert_eq!( + meter.owner_head_checks, + seen.heads + u64::from(report.marked_nodes), + "mark heads and the atomic owner walk are separate" + ); + assert_eq!( + meter.scratch.pending_close_pushed, + u64::from(graph.counts.weak) + ); + assert_eq!( + meter.scratch.dead_slots_pushed, + u64::from(graph.counts.weak) + ); + assert_eq!( + meter.scratch.sweep_bitmap_inited, + u64::from(graph.counts.nodes) + ); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 1); + assert_eq!( + host.resource_count(), + before_resources - graph.counts.weak as usize, + "closed weak quota was returned" + ); + assert_eq!(report.marked_nodes, graph.counts.rooted); + assert_eq!(report.live_roots, graph.counts.roots); + }); +} + +#[test] +fn shared_metatable_cycle_observes_published_weak_graph_once() { + run_shared(true); +} + +#[test] +fn separate_metatables_cycle_observes_published_weak_graph_once() { + run_shared(false); +} + +#[test] +fn private_cycle_without_dead_slots_skips_publish() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + crate::heap::install( + &mut host, + HeapLimits { + nodes: 4, + roots: 1, + edges: 2, + max_generation: 8, + }, + ) + .expect("limits"); + let (table, raw) = publish_node(&mut host); + crate::heap::with_heap(&mut host, |heap| { + heap.set_named_edge(table, "self", table).expect("self"); + let frame = heap.enter_roots(1).expect("frame"); + heap.write_root(frame, 0, table).expect("root"); + Ok(()) + }) + .expect("root"); + let events = Cell::new(0u32); + let (report, seen) = crate::heap::collect_observing(&mut host, |_view| { + events.set(events.get() + 1); + }) + .expect("no-dead cycle"); + assert!(seen.is_none(), "no published event without dead slots"); + assert_eq!(events.get(), 0); + assert_eq!(report.live_nodes, 1); + let meter = + crate::heap::with_heap(&mut host, |heap| Ok(heap.take_scan_meter())).expect("meter"); + assert_eq!( + meter.sweep_edge_checks, 0, + "roots phase does not walk edges" + ); + assert_eq!(meter.token_closes, 0); + assert_eq!(meter.scratch.dead_slots_pushed, 0); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 1); + crate::heap::with_heap(&mut host, |heap| { + assert!(heap.alive(table)); + Ok(()) + }) + .expect("survivor"); + assert!(token_open(&host, raw), "rooted token stays open"); + }); +} + +#[test] +fn foreign_token_failure_publishes_nothing_and_retries_from_roots() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + crate::heap::install(&mut host, crate::sweep_limits()).expect("limits"); + let unrelated = host + .push_resource(crate::UnrelatedHostResource) + .expect("unrelated"); + let unrelated_raw = unrelated.handle().raw(); + let keeper = crate::publish_raw(&mut host); + let keeper_table = crate::table_ref(&host, keeper); + let prefix = crate::publish_raw(&mut host); + let other = crate::publish_raw(&mut host); + let doomed = crate::heap::with_heap(&mut host, LuaHeap::alloc).expect("doomed"); + let ahead = crate::heap::with_heap(&mut host, LuaHeap::alloc).expect("ahead"); + let suffix = crate::publish_raw(&mut host); + let metatable = alloc_node(&mut host); + let watch = alloc_node(&mut host); + let weak_value = alloc_node(&mut host); + crate::heap::with_heap(&mut host, |heap| { + heap.bind_token(doomed, unrelated_raw) + .expect("foreign token"); + heap.set_named_edge(doomed, "y", ahead).expect("edge"); + heap.set_mode_scalar(metatable, Value::string("v")) + .expect("mode"); + heap.set_metatable(watch, Some(metatable)) + .expect("metatable"); + heap.set_named_edge(watch, "gone", weak_value) + .expect("weak edge"); + let frame = heap.enter_roots(3).expect("frame"); + heap.write_root(frame, 0, keeper_table).expect("keeper"); + heap.write_root(frame, 1, metatable).expect("meta root"); + heap.write_root(frame, 2, watch).expect("watch root"); + Ok(()) + }) + .expect("weak graph"); + let before_resources = host.resource_count(); + let nodes_before = crate::heap::stats(&mut host).expect("stats").node_slots; + let events = Cell::new(0u32); + let error = crate::heap::collect_observing(&mut host, |_view| { + events.set(events.get() + 1); + }) + .expect_err("foreign token blocks the cycle"); + crate::assert_type_mismatch(&error); + assert_eq!(events.get(), 0, "no published event before close succeeds"); + let stats = crate::heap::stats(&mut host).expect("stats"); + assert_eq!( + stats.collections, 0, + "close failure is not a completed collect" + ); + assert_eq!(stats.node_slots, nodes_before, "no release"); + let meter = + crate::heap::with_heap(&mut host, |heap| Ok(heap.take_scan_meter())).expect("meter"); + assert_eq!(meter.sweep_edge_checks, 0, "no sweep before close succeeds"); + assert_eq!( + meter.token_closes, 3, + "prefix closes, then the foreign token stops" + ); + assert_eq!(meter.scratch.dead_slots_pushed, 0, "select has not run"); + assert_eq!(meter.scratch.sweep_bitmap_inited, 0, "snapshot has not run"); + crate::heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.named_edge(watch, "gone").expect("weak edge"), + Some(weak_value), + "weak graph is unchanged" + ); + assert!(heap.alive(weak_value)); + assert!(heap.alive(doomed)); + Ok(()) + }) + .expect("graph"); + assert!( + host.resource(&unrelated).is_ok(), + "foreign resource stays open" + ); + assert!(token_open(&host, suffix), "suffix stays open"); + assert!(!token_open(&host, prefix), "prefix stays closed"); + assert!(!token_open(&host, other), "other stays closed"); + let resources_after_failure = host.resource_count(); + assert_eq!(resources_after_failure, before_resources - 2); + + let retry = Cell::new(0u32); + let retry_error = crate::heap::collect_observing(&mut host, |_view| { + retry.set(retry.get() + 1); + }) + .expect_err("obstacle still blocks a fresh mark"); + crate::assert_type_mismatch(&retry_error); + assert_eq!(retry.get(), 0); + crate::heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.named_edge(watch, "gone").expect("edge"), + Some(weak_value) + ); + Ok(()) + }) + .expect("still weak"); + + crate::heap::with_heap(&mut host, |heap| heap.unbind_token(doomed)) + .expect("fixture drops the foreign token binding"); + let events = Cell::new(0u32); + let (report, seen) = crate::heap::collect_observing(&mut host, |_view| { + events.set(events.get() + 1); + true + }) + .expect("fresh mark after the obstacle is gone"); + assert_eq!(events.get(), 1, "recovered cycle publishes once"); + assert_eq!(seen, Some(true)); + crate::heap::with_heap(&mut host, |heap| { + assert!(heap.named_edge(watch, "gone").expect("cleared").is_none()); + assert!( + !heap.alive(weak_value), + "fresh mark collected the weak value" + ); + assert!(heap.alive(watch)); + assert!(heap.alive(keeper_table)); + assert!(!heap.alive(doomed)); + Ok(()) + }) + .expect("recovered graph"); + assert!( + !token_open(&host, suffix), + "suffix closes on the recovered cycle" + ); + assert_eq!(host.resource_count(), resources_after_failure - 1); + assert!(report.live_nodes >= 1); + let _ = ahead; + }); +} + +#[test] +fn parked_mark_refuses_private_cycle_and_resumes() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + crate::heap::install(&mut host, crate::sweep_limits()).expect("limits"); + let anchor = alloc_node(&mut host); + let target = alloc_node(&mut host); + let ahead = alloc_node(&mut host); + let extra = alloc_node(&mut host); + const KEY_Y: u32 = 5; + crate::heap::with_heap(&mut host, |heap| { + heap.set_edge(target, KEY_Y, ahead).expect("edge"); + let frame = heap.enter_roots(2).expect("frame"); + heap.write_root(frame, 0, anchor).expect("anchor"); + heap.write_root(frame, 1, target).expect("target"); + Ok(()) + }) + .expect("graph"); + let saved = crate::heap::with_heap(&mut host, |heap| { + let mut parked = ParkedMark::start(heap).expect("start"); + let cursor = parked.field_index(target, KEY_Y).expect("edge index"); + let mut saved = None; + for _ in 0..16 { + let view = parked.pulse(1); + if view.finished { + break; + } + if parked + .pending() + .is_some_and(|scan| scan.owner == target.slot() && scan.cursor == cursor) + { + saved = Some((target.slot(), cursor)); + break; + } + } + let saved = saved.expect("parked on the outgoing edge"); + assert_eq!(parked.phase_name(), "gray"); + assert!(parked.marked(target)); + parked.park().expect("park"); + Ok(saved) + }) + .expect("park"); + let nodes_before = crate::heap::stats(&mut host).expect("stats").node_slots; + let error = crate::heap::collect_observing(&mut host, |_view| ()) + .expect_err("parked mark must be refused"); + assert!( + matches!(error, HeapError::MarkActive), + "parked mark refused, got {error:?}" + ); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 0); + assert_eq!( + crate::heap::stats(&mut host).expect("stats").node_slots, + nodes_before + ); + crate::heap::with_heap(&mut host, |heap| { + let parked = ParkedMark::resume(heap).expect("original mark still parked"); + assert_eq!(parked.phase_name(), "gray"); + assert_eq!( + parked.pending().map(|scan| (scan.owner, scan.cursor)), + Some(saved), + "pending cursor is unchanged" + ); + assert!(parked.marked(target)); + assert_eq!( + parked.meter().mark_passes, + 1, + "refusal did not start another mark" + ); + assert_eq!(parked.meter().sweep_edge_checks, 0); + parked.park().expect("park again"); + Ok(()) + }) + .expect("resume"); + crate::heap::with_heap(&mut host, |heap| { + let mut parked = ParkedMark::resume(heap).expect("resume to finish"); + for _ in 0..16 { + if parked.pulse(1).finished { + break; + } + } + let _report = parked.complete().expect("original sweep"); + drop(parked); + assert!(heap.alive(anchor)); + assert!(heap.alive(target)); + assert!(heap.alive(ahead)); + assert!( + !heap.alive(extra), + "the original mark still sweeps unmarked nodes" + ); + Ok(()) + }) + .expect("original driver"); + }); +} From 00ada95f75960d967370fc03bbd16303bfa8722c Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 02:37:16 +0800 Subject: [PATCH 111/225] fix(lua): root a parenthesized later call before it collects host_call matched a direct call on the raw spelling, so (sweep()) ran and collected the earlier table. Look through parentheses only in that pending-root check. --- tests/luajit_heap_runtime/candidate.rs | 4 +- tests/luajit_heap_runtime/pending_argument.rs | 136 ++++++++++++++++++ 2 files changed, 139 insertions(+), 1 deletion(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index baf9b3e..aa9c234 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -3707,7 +3707,9 @@ impl Lower<'_> { let mut pending_slots = Vec::new(); let mut pending_frames = Vec::new(); for (arg, param) in args.iter().zip(&function.params) { - if self.direct_function_call(arg).is_some() && !pending_slots.is_empty() { + // Value parentheses still execute this direct call. Recognize + // them only here; other direct_function_call sites keep spelling. + if self.direct_function_call(skip_parens(arg)).is_some() && !pending_slots.is_empty() { pending_frames.push(self.open_pending_frame(&pending_slots, span)?); pending_slots.clear(); } diff --git a/tests/luajit_heap_runtime/pending_argument.rs b/tests/luajit_heap_runtime/pending_argument.rs index 6f6d90c..ed7f060 100644 --- a/tests/luajit_heap_runtime/pending_argument.rs +++ b/tests/luajit_heap_runtime/pending_argument.rs @@ -539,6 +539,142 @@ fn pending_argument_keeps_the_earlier_table_across_the_later_lua_collect() { assert_ne!(ran.discarded, Some(target.table)); } +fn seeded_with_later_call(later: &str) -> String { + const CALL: &str = "consume(rawget(weak, (mark(1))), sweep())"; + assert_eq!( + SEEDED.matches(CALL).count(), + 1, + "later sweep() call is not unique" + ); + SEEDED.replacen( + CALL, + &format!("consume(rawget(weak, (mark(1))), {later})"), + 1, + ) +} + +#[test] +fn pending_argument_parenthesized_later_call_keeps_the_earlier_table() { + for later in ["(sweep())", "((sweep()))"] { + let source = seeded_with_later_call(later); + assert!( + source.contains(&format!(", {later})")), + "arm {later} did not replace the later call" + ); + assert!( + !source.contains(", sweep()"), + "arm {later} still has the bare later call" + ); + let ran = run_source(&source); + assert_eq!( + ran.status, + Ok(VmStatus::Halted), + "arm {later} status={:?} stack={:?} order={:?} snaps={:?} notes={:?} consumed={:?} collections={} roots={}/{} visits={:?}", + ran.status, + ran.stack, + ran.obs.order, + ran.obs.snaps, + ran.obs.notes, + ran.obs.consumed, + ran.collections, + ran.live_roots, + ran.root_slots, + ran.visits, + ); + assert_eq!(ran.stack, vec![Value::Float(41.0)], "arm {later}"); + assert_eq!( + ran.obs.order, + vec![ + Event::Peek, + Event::Peek, + Event::Mark(1.0), + Event::Mark(2.0), + Event::Snap(2.0), + Event::Mark(41.0), + Event::Consume, + Event::Snap(4.0), + Event::Note(6.0), + Event::Note(7.0), + Event::Snap(5.0), + Event::Note(8.0), + ], + "arm {later}" + ); + let target = ran.obs.peeked[0]; + let orphan = ran.obs.peeked[1]; + assert_ne!(target.table, orphan.table, "arm {later}"); + let consumed = ran + .obs + .consumed + .first() + .expect("consumer stored the identity"); + assert_eq!(consumed.table, target.table, "arm {later}"); + assert_eq!(consumed.token, target.token, "arm {later}"); + assert_eq!(consumed.marker, 41.0, "arm {later}"); + assert_eq!( + consumed.root_slots, 2, + "arm {later} caller frame plus the pending frame" + ); + assert_eq!( + consumed.live_roots, 2, + "arm {later} weak table and the pending table" + ); + let nested = snap(&ran, 2.0); + let released = snap(&ran, 4.0); + let later_collect = snap(&ran, 5.0); + assert_eq!(nested.peeked_alive, vec![true, false], "arm {later}"); + assert_eq!(nested.root_slots, 2, "arm {later}"); + assert_eq!(nested.live_roots, 2, "arm {later}"); + assert_eq!(nested.collections, 1, "arm {later}"); + assert_eq!( + nested.root_slot_visits, 0, + "arm {later} return witness already took this meter" + ); + assert_eq!( + ran.visits, + vec![4, 2], + "arm {later} nested and later collects stay separate" + ); + assert_ne!(ran.visits[0], nested.root_slots as u64, "arm {later}"); + assert_ne!(ran.visits[0], nested.live_roots as u64, "arm {later}"); + assert_eq!( + released.root_slots, 1, + "arm {later} pending frame left before the next snap" + ); + assert_eq!(released.live_roots, 1, "arm {later}"); + assert_eq!(released.peeked_alive, vec![true, false], "arm {later}"); + assert_eq!( + later_collect.peeked_alive, + vec![false, false], + "arm {later}" + ); + assert_eq!(later_collect.collections, 2, "arm {later}"); + assert_eq!(later_collect.root_slots, 1, "arm {later}"); + assert_eq!(later_collect.root_slot_visits, 0, "arm {later}"); + assert_ne!(ran.visits[0], ran.visits[1], "arm {later}"); + assert_eq!( + ran.obs.notes, + vec![ + (6.0, "table".to_string()), + (7.0, "nil".to_string()), + (8.0, "nil".to_string()), + ], + "arm {later}" + ); + assert_eq!( + ran.live_roots, 0, + "arm {later} chunk retire returned the caller frame" + ); + assert_eq!(ran.root_slots, 0, "arm {later}"); + assert_eq!( + ran.issued, 4, + "arm {later} pending publish did not issue another witness root" + ); + assert_ne!(ran.returned, Some(target.table), "arm {later}"); + assert_ne!(ran.discarded, Some(target.table), "arm {later}"); + } +} + #[test] fn pending_argument_repeat_reuses_the_returned_frame() { let ran = run_source( From 28b0613e916dc5fc4ab111d67168eea7ec92fa36 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 04:48:24 +0800 Subject: [PATCH 112/225] feat(lua/heap): resume a saved mark through the same host close Continue an already saved private mark with the current root batch. A finished mark closes tokens and publishes the weak graph in that same call. An unfinished or refused call does not sweep. --- src/frontends/lua/heap.rs | 65 +++ src/frontends/lua/heap/table.rs | 28 +- src/frontends/lua/heap/table/mark.rs | 65 ++- tests/luajit_heap_runtime/resume_cycle.rs | 675 ++++++++++++++++++++++ 4 files changed, 816 insertions(+), 17 deletions(-) create mode 100644 tests/luajit_heap_runtime/resume_cycle.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 9f66de7..d8ebed5 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -187,6 +187,71 @@ pub fn collect_observing( observe: impl for<'a> FnOnce(&'a PublishedRead<'a>) -> R, ) -> Result<(table::CollectReport, Option), HeapError> { let marked = with_heap(host, |heap| heap.begin_private_cycle())?; + close_then_sweep_observing(host, marked, observe) +} + +/// A saved mark that this call did not finish, or the one report from the +/// sweep that followed a finished mark. +#[derive(Debug)] +enum SavedMarkResume { + /// The saved mark is still on the heap. No token was closed and nothing + /// was swept. + Paused, + /// Close and sweep finished in this call. The observer ran only when a + /// dead slot was published. + Completed(table::CollectReport, Option), +} + +/// Continues a mark this scope already saved. Does not start a mark and does +/// not install a heap. +/// +/// No saved mark is [`HeapError::MarkDenied`], including a missing heap. +/// Zero budget with a saved mark returns [`SavedMarkResume::Paused`] without +/// reading the batch or the graph. A positive budget that stops before Done +/// may move the cursor and returns `Paused` with no enumeration, close, or +/// sweep; a budget that runs out before Roots does not commit `batch`. +/// Done removes the saved mark, enumerates once, and closes through the same +/// token retirement as [`collect`]. The observer and sweep then share the +/// private-cycle tail. Close failure drops that snapshot, keeps the closed +/// prefix, publishes nothing, and leaves the continuation stateless. +/// +/// `batch` is an additional safepoint slice. It is not written into a fixed +/// root slot and is not deduped. A root already sitting in a fixed slot or a +/// pending frame must not be passed again. This is not a guest `step`. +/// +/// Private to this module. `Rooted` is not a public heap schema, so this +/// signature stays inside the heap module and its tests. +fn resume_private_cycle( + host: &mut HostContext, + budget: u64, + batch: &[table::Rooted], + observe: impl for<'a> FnOnce(&'a PublishedRead<'a>) -> R, +) -> Result, HeapError> { + if host.scope_state::().is_none() { + return Err(HeapError::MarkDenied); + } + if budget == 0 { + let saved = host + .scope_state::() + .is_some_and(LuaHeap::has_saved_mark); + if !saved { + return Err(HeapError::MarkDenied); + } + return Ok(SavedMarkResume::Paused); + } + let marked = with_heap(host, |heap| heap.take_finished_saved_mark(budget, batch))?; + let Some(marked) = marked else { + return Ok(SavedMarkResume::Paused); + }; + let (report, seen) = close_then_sweep_observing(host, marked, observe)?; + Ok(SavedMarkResume::Completed(report, seen)) +} + +fn close_then_sweep_observing( + host: &mut HostContext, + marked: table::DoomedMark, + observe: impl for<'a> FnOnce(&'a PublishedRead<'a>) -> R, +) -> Result<(table::CollectReport, Option), HeapError> { for token in marked.tokens { retire_doomed_token(host, token)?; } diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index c8b9b07..07e8f5f 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -329,8 +329,10 @@ pub enum CellValue { } /// One explicit root. Table, closure, and upvalue roots share the root vector. +/// +/// Visible to the private host continuation. Not a public heap schema. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Rooted { +pub(super) enum Rooted { Table(TableRef), Closure(ClosureRef), Upvalue(UpvalueRef), @@ -1881,12 +1883,33 @@ impl LuaHeap { true } + /// True when a mark is already stored. Does not read slots, edges, or a batch. + pub(super) fn has_saved_mark(&self) -> bool { + self.mark.is_some() + } + /// Marks once, then drains the pending-close enumerator. Each slot check /// is one scan unit. The drain finishes before this returns, so host close /// still sees every doomed token and the original mark snapshot. A partial /// pulse is not returned from here and is not given to sweep. pub(super) fn mark_and_doomed_tokens(&mut self) -> DoomedMark { let modes = self.mark_reachable(); + self.drain_pending_close(modes) + } + + /// Advances a saved mark with the borrowed batch. `None` means the same + /// state was written back and tokens were not enumerated. `Some` is the + /// owned close list of a finished mark; the saved state is already gone. + pub(super) fn take_finished_saved_mark( + &mut self, + budget: u64, + batch: &[Rooted], + ) -> Result, HeapError> { + let (_view, snapshot) = self.advance_saved_mark_with_root_batch(budget, batch)?; + Ok(snapshot.map(|modes| self.drain_pending_close(modes))) + } + + fn drain_pending_close(&mut self, modes: MarkSnapshot) -> DoomedMark { let mut session = PendingCloseSession::start(self, modes); session.drain(); session.finish() @@ -2379,5 +2402,8 @@ mod parked_mark; #[path = "../../../../tests/luajit_heap_runtime/private_cycle.rs"] mod private_cycle; #[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/resume_cycle.rs"] +mod resume_cycle; +#[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/safepoint_roots.rs"] mod safepoint_roots; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index 0d82e3f..feefe39 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -28,6 +28,13 @@ //! including one after park and resume, reads only the batch it was given. //! Zero budget only observes. //! +//! `ParkedMark::advance_with_root_batch` and the host continuation share +//! [`LuaHeap::advance_saved_mark_with_root_batch`]. That primitive checks the +//! saved mark, Done, the root quota, and each typed handle before it takes +//! the state, then uses this same `pulse_budget`. The host entry does not +//! build a `ParkedMark`: dropping one would discard an unparked mark, and +//! `complete` would sweep without closing tokens. +//! //! Reset and mode pulses still spend that budget. They do not open mutation. //! Roots and Gray open an ordinary field delete, an ordinary field write on //! an owner that is not yet marked, an in-place replacement of an existing @@ -291,24 +298,14 @@ impl<'a> ParkedMark<'a> { budget: u64, batch: &[Rooted], ) -> Result { - self.saved_mark()?; - if self - .heap - .mark - .as_ref() - .is_some_and(|state| matches!(state.phase, MarkPhase::Done)) - { + if self.done.is_some() || self.swept { return Err(HeapError::MarkDenied); } - validate_root_batch(self.heap, batch)?; - let mut state = self.heap.mark.take().expect("parked mark"); - let view = pulse_budget(self.heap, &mut state, budget, Some(batch)); - if matches!(state.phase, MarkPhase::Done) { - self.done = Some(MarkSnapshot { - modes: state.modes.take(), - }); - } else { - self.heap.mark = Some(state); + let (view, done) = self + .heap + .advance_saved_mark_with_root_batch(budget, batch)?; + if let Some(snapshot) = done { + self.done = Some(snapshot); } Ok(view) } @@ -650,6 +647,42 @@ impl Drop for ParkedMark<'_> { } } +impl LuaHeap { + /// Positive-budget step of a mark already stored on this heap. + /// + /// Order is the parked driver's order: saved state, Done, quota, then + /// each typed handle. Only then is `heap.mark` taken. [`pulse_budget`] + /// commits `batch` once, after this pulse enters Roots and before any + /// root or gray step. An unfinished mark is written back. A finished + /// mark is not stored; its modes are returned once. This does not + /// enumerate tokens, close them, or sweep. + pub(super) fn advance_saved_mark_with_root_batch( + &mut self, + budget: u64, + batch: &[Rooted], + ) -> Result<(MarkView, Option), HeapError> { + debug_assert!(budget > 0, "zero budget does not enter the shared advance"); + let state = self.mark.as_ref().ok_or(HeapError::MarkDenied)?; + if matches!(state.phase, MarkPhase::Done) { + return Err(HeapError::MarkDenied); + } + validate_root_batch(self, batch)?; + let mut state = self.mark.take().expect("saved mark"); + let view = pulse_budget(self, &mut state, budget, Some(batch)); + if matches!(state.phase, MarkPhase::Done) { + Ok(( + view, + Some(MarkSnapshot { + modes: state.modes.take(), + }), + )) + } else { + self.mark = Some(state); + Ok((view, None)) + } + } +} + fn validate_root_batch(heap: &LuaHeap, batch: &[Rooted]) -> Result<(), HeapError> { let occupied = u32::try_from(heap.roots.len()).map_err(|_| HeapError::RootCapacity)?; let extra = u32::try_from(batch.len()).map_err(|_| HeapError::RootCapacity)?; diff --git a/tests/luajit_heap_runtime/resume_cycle.rs b/tests/luajit_heap_runtime/resume_cycle.rs new file mode 100644 index 0000000..03804a9 --- /dev/null +++ b/tests/luajit_heap_runtime/resume_cycle.rs @@ -0,0 +1,675 @@ +//! Host continuation of a mark this scope already saved. +//! +//! The batch is borrowed for that call only. A finished mark closes tokens +//! and publishes the weak graph in the same call. An unfinished or refused +//! call does not sweep. This is not a guest step. + +use std::cell::Cell; + +use super::super::{SavedMarkResume, resume_private_cycle}; +use super::{HeapError, HeapLimits, LuaHeap, ParkedMark, Rooted, ScanMeter, TableRef}; +use vm::Value; + +const BUDGET: u64 = 64; +const BOUND: u32 = 64; + +struct Arm { + meta: TableRef, + anchor: TableRef, + anchor_raw: i64, + weak: TableRef, + weak_raw: i64, + target: TableRef, + target_raw: i64, + successor: TableRef, + successor_raw: i64, +} + +struct AtPublish { + cleared: bool, + weak_physical: bool, + weak_judged: bool, + anchor_alive: bool, + target_judged: bool, + target_physical: bool, + successor_judged: bool, + successor_physical: bool, + release_started: bool, + finished: bool, +} + +struct Finished { + report_nodes: u32, + meter: ScanMeter, + collections: u32, + root_slots: u32, + live_roots: u32, + frame: Option, + events: u32, + at: AtPublish, + anchor_alive: bool, + weak_alive: bool, + target_alive: bool, + successor_alive: bool, + anchor_open: bool, + weak_open: bool, + target_open: bool, + successor_open: bool, +} + +fn limits(roots: u32) -> HeapLimits { + HeapLimits { + nodes: 8, + roots, + edges: 8, + max_generation: 8, + } +} + +fn alloc_node(host: &mut vm::HostContext<'_>) -> TableRef { + crate::heap::with_heap(host, LuaHeap::alloc).expect("node") +} + +fn publish_node(host: &mut vm::HostContext<'_>) -> (TableRef, i64) { + let raw = crate::publish_raw(host); + (crate::table_ref(host, raw), raw) +} + +fn token_open(host: &vm::HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + crate::resource_handle(raw), + &crate::heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn alive(host: &mut vm::HostContext<'_>, table: TableRef) -> bool { + crate::heap::with_heap(host, |heap| Ok(heap.alive(table))).expect("alive") +} + +fn meter(host: &mut vm::HostContext<'_>) -> ScanMeter { + crate::heap::with_heap(host, |heap| Ok(heap.scan)).expect("meter") +} + +fn saved_phase(host: &mut vm::HostContext<'_>) -> &'static str { + crate::heap::with_heap(host, |heap| { + let parked = ParkedMark::resume(heap).expect("saved mark"); + let name = parked.phase_name(); + parked.park().expect("park"); + Ok(name) + }) + .expect("phase") +} + +fn save_at_start(host: &mut vm::HostContext<'_>) { + crate::heap::with_heap(host, |heap| { + let parked = ParkedMark::start(heap).expect("start"); + assert_eq!(parked.phase_name(), "start"); + assert_eq!(parked.meter().mark_passes, 0); + assert_eq!(parked.stats().root_slots, 0); + parked.park().expect("park"); + Ok(()) + }) + .expect("save start"); +} + +fn save_reset_tail(host: &mut vm::HostContext<'_>) { + crate::heap::with_heap(host, |heap| { + let mut parked = ParkedMark::start(heap).expect("start"); + let slots = u64::from(parked.stats().node_slots); + assert!(slots > 0, "reset tail needs existing nodes"); + for _ in 0..BOUND { + if parked.phase_name() == "reset" && parked.meter().weak_mode_slot_checks == slots { + assert!(!parked.mutation_open()); + assert_eq!(parked.meter().mark_passes, 1); + assert_eq!(parked.meter().root_slot_visits, 0); + assert_eq!(parked.meter().parked_root_batch_accepts, 0); + parked.park().expect("park"); + return Ok(()); + } + let view = parked.pulse(1); + assert!( + !view.finished, + "ordinary pulse finished before reset tail, phase {}", + parked.phase_name() + ); + } + panic!( + "reset tail was not observed, phase {} checks {}", + parked.phase_name(), + parked.meter().weak_mode_slot_checks + ); + }) + .expect("reset tail"); +} + +fn build_arm(host: &mut vm::HostContext<'_>, roots: u32) -> Arm { + crate::heap::install(host, limits(roots)).expect("limits"); + let meta = alloc_node(host); + let (anchor, anchor_raw) = publish_node(host); + let (weak, weak_raw) = publish_node(host); + let (target, target_raw) = publish_node(host); + let (successor, successor_raw) = publish_node(host); + crate::heap::with_heap(host, |heap| { + heap.set_mode_scalar(meta, Value::string("v")) + .expect("mode"); + heap.set_metatable(anchor, Some(meta)).expect("meta"); + heap.set_named_edge(anchor, "w", weak).expect("weak edge"); + heap.set_named_edge(target, "s", successor) + .expect("strong edge"); + assert_eq!(heap.stats().root_slots, 0); + assert_eq!(heap.stats().live_roots, 0); + assert_eq!(heap.current_frame(), None); + Ok(()) + }) + .expect("graph"); + Arm { + meta, + anchor, + anchor_raw, + weak, + weak_raw, + target, + target_raw, + successor, + successor_raw, + } +} + +fn read_publish(view: &crate::heap::PublishedRead<'_>, arm: &Arm) -> AtPublish { + AtPublish { + cleared: view.named(arm.anchor, "w").expect("A.w").is_none(), + weak_physical: view.still_physical(arm.weak), + weak_judged: matches!( + view.alive(arm.weak), + Err(crate::heap::ObserveFault::JudgedDead) + ), + anchor_alive: matches!(view.alive(arm.anchor), Ok(true)), + target_judged: matches!( + view.alive(arm.target), + Err(crate::heap::ObserveFault::JudgedDead) + ), + target_physical: view.still_physical(arm.target), + successor_judged: matches!( + view.alive(arm.successor), + Err(crate::heap::ObserveFault::JudgedDead) + ), + successor_physical: view.still_physical(arm.successor), + release_started: view.release_started(), + finished: view.finished(), + } +} + +fn finish_arm(host: &mut vm::HostContext<'_>, arm: &Arm, batch: &[Rooted]) -> Finished { + let events = Cell::new(0u32); + let outcome = resume_private_cycle(host, BUDGET, batch, |view| { + events.set(events.get() + 1); + read_publish(view, arm) + }) + .expect("resume"); + let SavedMarkResume::Completed(report, seen) = outcome else { + panic!("expected one completed report, not a pause"); + }; + let at = seen.expect("published observation missing"); + assert_eq!(events.get(), 1, "one published observation"); + assert!(at.cleared, "A.w cleared while W was still physical"); + assert!(at.weak_physical, "W still physical at publish"); + assert!(at.weak_judged, "W was judged dead before release"); + assert!(at.anchor_alive, "A was alive at publish"); + assert!(!at.release_started, "release has not started at publish"); + assert!(!at.finished, "observation is not a finished sweep"); + let stats = crate::heap::stats(host).expect("stats"); + let done = Finished { + report_nodes: report.live_nodes, + meter: meter(host), + collections: stats.collections, + root_slots: stats.root_slots, + live_roots: stats.live_roots, + frame: crate::heap::with_heap(host, |heap| Ok(heap.current_frame())).expect("frame"), + events: events.get(), + at, + anchor_alive: alive(host, arm.anchor), + weak_alive: alive(host, arm.weak), + target_alive: alive(host, arm.target), + successor_alive: alive(host, arm.successor), + anchor_open: token_open(host, arm.anchor_raw), + weak_open: token_open(host, arm.weak_raw), + target_open: token_open(host, arm.target_raw), + successor_open: token_open(host, arm.successor_raw), + }; + assert!(done.anchor_alive, "A must stay alive"); + assert!(done.anchor_open, "A token stays open"); + assert!(!done.weak_alive, "W is released after the call"); + assert!(!done.weak_open, "W token is closed"); + assert!(alive(host, arm.meta), "the metatable stays with A"); + assert_eq!( + done.meter.mark_passes, 1, + "same saved pass, not a remark and not skipped" + ); + assert_eq!(done.collections, 1, "one sweep in this call"); + assert_eq!( + done.root_slots, 0, + "the batch was not written to a fixed slot" + ); + assert_eq!(done.live_roots, 0); + assert!(done.frame.is_none(), "no hidden root frame"); + assert_eq!(done.meter.parked_root_writes, 0); + done +} + +fn keep_failure(done: &Finished) -> String { + format!( + "K/S should survive the [A, K] batch but were collected; mark_passes={} accepts={} token_closes={} collections={} events={} cleared={} w_physical={} w_alive={} k_judged_dead_at_publish={} k_physical_at_publish={} s_judged_dead_at_publish={} s_physical_at_publish={} live_nodes={} root_slots={}", + done.meter.mark_passes, + done.meter.parked_root_batch_accepts, + done.meter.token_closes, + done.collections, + done.events, + done.at.cleared, + done.at.weak_physical, + done.weak_alive, + done.at.target_judged, + done.at.target_physical, + done.at.successor_judged, + done.at.successor_physical, + done.report_nodes, + done.root_slots + ) +} + +/// Same graph as the omitted-target arm. This arm hands `[A, K]`. +#[test] +fn saved_resume_keeps_batch_target_and_sweeps_weak_value() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let arm = build_arm(&mut host, 2); + save_reset_tail(&mut host); + let done = finish_arm( + &mut host, + &arm, + &[Rooted::Table(arm.anchor), Rooted::Table(arm.target)], + ); + assert!( + done.target_alive && done.successor_alive && done.target_open && done.successor_open, + "{}", + keep_failure(&done) + ); + assert_eq!(done.meter.parked_root_batch_accepts, 2); + assert_eq!(done.meter.token_closes, 1, "only W is closed"); + assert_eq!(done.report_nodes, 4, "M, A, K, and S stay"); + assert_eq!(done.meter.scratch.dead_slots_pushed, 1); + }); +} + +/// Same graph as the keep arm. This arm hands only `[A]`. +#[test] +fn saved_resume_omitted_target_is_collected_with_the_weak_value() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let arm = build_arm(&mut host, 2); + save_reset_tail(&mut host); + let done = finish_arm(&mut host, &arm, &[Rooted::Table(arm.anchor)]); + assert!( + !done.target_alive && !done.successor_alive, + "K/S must be collected when the batch omits K" + ); + assert!(!done.target_open && !done.successor_open); + assert_eq!(done.meter.parked_root_batch_accepts, 1); + assert_eq!(done.meter.token_closes, 3, "W, K, and S close"); + assert_eq!(done.report_nodes, 2, "only M and A stay"); + assert_eq!(done.meter.scratch.dead_slots_pushed, 3); + }); +} + +#[test] +fn saved_resume_without_saved_state_is_denied_and_does_not_install() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let events = Cell::new(0u32); + let missing = resume_private_cycle(&mut host, 0, &[], |_| { + events.set(events.get() + 1); + }) + .expect_err("missing heap"); + assert!(matches!(missing, HeapError::MarkDenied)); + assert!(host.scope_state::().is_none()); + let missing = resume_private_cycle(&mut host, 4, &[], |_| { + events.set(events.get() + 1); + }) + .expect_err("missing heap, positive budget"); + assert!(matches!(missing, HeapError::MarkDenied)); + assert!( + host.scope_state::().is_none(), + "denial must not install a heap" + ); + assert_eq!(events.get(), 0); + + crate::heap::install(&mut host, limits(1)).expect("install"); + let denied = resume_private_cycle(&mut host, 0, &[], |_| { + events.set(events.get() + 1); + }) + .expect_err("installed heap has no saved mark"); + assert!(matches!(denied, HeapError::MarkDenied)); + let denied = resume_private_cycle(&mut host, 4, &[], |_| { + events.set(events.get() + 1); + }) + .expect_err("positive budget does not start a mark"); + assert!(matches!(denied, HeapError::MarkDenied)); + assert_eq!(events.get(), 0); + assert_eq!(meter(&mut host).mark_passes, 0); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 0); + assert_eq!(crate::heap::stats(&mut host).expect("stats").live_nodes, 0); + assert!( + !crate::heap::with_heap(&mut host, |heap| Ok(heap.has_saved_mark())).expect("saved") + ); + }); +} + +#[test] +fn saved_resume_refuses_the_batch_before_it_advances_then_finishes() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let arm = build_arm(&mut host, 1); + let stale = crate::heap::with_heap(&mut host, |heap| { + let stale = heap.alloc()?; + heap.rollback(stale)?; + Ok(stale) + }) + .expect("stale"); + save_reset_tail(&mut host); + let before = meter(&mut host); + let phase = saved_phase(&mut host); + assert_eq!(phase, "reset"); + let events = Cell::new(0u32); + + let paused = resume_private_cycle(&mut host, 0, &[Rooted::Table(stale)], |_| { + events.set(events.get() + 1); + }) + .expect("zero budget with a saved mark pauses"); + assert!(matches!(paused, SavedMarkResume::Paused)); + assert_eq!( + meter(&mut host), + before, + "zero budget does not read the batch" + ); + assert_eq!(saved_phase(&mut host), phase); + + let stale_error = resume_private_cycle(&mut host, 8, &[Rooted::Table(stale)], |_| { + events.set(events.get() + 1); + }) + .expect_err("stale handle"); + assert!(matches!(stale_error, HeapError::StaleHandle)); + assert_eq!( + meter(&mut host), + before, + "a refused batch does not move the mark" + ); + assert_eq!(saved_phase(&mut host), phase); + + let over = resume_private_cycle( + &mut host, + 8, + &[ + Rooted::Table(arm.anchor), + Rooted::Table(arm.target), + Rooted::Table(arm.weak), + ], + |_| { + events.set(events.get() + 1); + }, + ) + .expect_err("batch plus fixed slots exceeds the root quota"); + assert!(matches!(over, HeapError::RootCapacity)); + assert_eq!(meter(&mut host), before); + assert_eq!(saved_phase(&mut host), phase); + assert_eq!(events.get(), 0); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 0); + + let done = finish_arm(&mut host, &arm, &[Rooted::Table(arm.anchor)]); + assert_eq!(done.meter.mark_passes, 1, "the same saved pass finished"); + assert_eq!(done.meter.parked_root_batch_accepts, 1); + assert!(!done.target_alive, "K was not in the finishing batch"); + }); +} + +#[test] +fn saved_resume_exhausted_before_roots_keeps_the_next_batch() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + crate::heap::install( + &mut host, + HeapLimits { + nodes: 8, + roots: 1, + edges: 4, + max_generation: 8, + }, + ) + .expect("limits"); + let (anchor, anchor_raw) = publish_node(&mut host); + let (anchor_next, anchor_next_raw) = publish_node(&mut host); + let (other, other_raw) = publish_node(&mut host); + let (other_next, other_next_raw) = publish_node(&mut host); + crate::heap::with_heap(&mut host, |heap| { + heap.set_named_edge(anchor, "s", anchor_next)?; + heap.set_named_edge(other, "s", other_next)?; + assert_eq!(heap.stats().root_slots, 0); + Ok(()) + }) + .expect("edges"); + let resources = host.resource_count(); + save_at_start(&mut host); + + let first = resume_private_cycle(&mut host, 1, &[Rooted::Table(anchor)], |_| ()) + .expect("budget ends before roots"); + assert!(matches!(first, SavedMarkResume::Paused)); + let paused = meter(&mut host); + assert_eq!( + paused.mark_passes, 1, + "the saved pass started and was not replaced" + ); + assert_eq!(paused.parked_root_batch_accepts, 0, "A was not submitted"); + assert_eq!(paused.token_closes, 0); + assert_eq!(paused.sweep_edge_checks, 0); + assert_eq!(host.resource_count(), resources); + crate::heap::with_heap(&mut host, |heap| { + let parked = ParkedMark::resume(heap).expect("still saved"); + assert!(!parked.mutation_open(), "budget ended before roots"); + assert_ne!(parked.phase_name(), "roots"); + assert_ne!(parked.phase_name(), "gray"); + assert_ne!(parked.phase_name(), "done"); + assert!(!parked.marked(anchor), "A was not marked"); + assert_eq!(parked.meter().weak_mode_slot_checks, 1); + parked.park().expect("park"); + Ok(()) + }) + .expect("cursor"); + + let events = Cell::new(0u32); + let outcome = resume_private_cycle(&mut host, BUDGET, &[Rooted::Table(other)], |view| { + events.set(events.get() + 1); + assert!(!view.release_started()); + assert!(!view.finished()); + }) + .expect("next batch"); + let SavedMarkResume::Completed(report, seen) = outcome else { + panic!("the later batch should finish the same mark"); + }; + assert!(seen.is_some(), "A was released, so the sweep published"); + assert_eq!(events.get(), 1); + let done = meter(&mut host); + assert_eq!( + done.mark_passes, 1, + "the later call did not start another mark" + ); + assert_eq!(done.parked_root_batch_accepts, 1, "only B was accepted"); + assert_eq!(done.token_closes, 2, "A and its successor close"); + assert!(alive(&mut host, other) && alive(&mut host, other_next)); + assert!(token_open(&host, other_raw) && token_open(&host, other_next_raw)); + assert!(!alive(&mut host, anchor) && !alive(&mut host, anchor_next)); + assert!(!token_open(&host, anchor_raw) && !token_open(&host, anchor_next_raw)); + assert_eq!(report.live_nodes, 2); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 1); + assert_eq!(crate::heap::stats(&mut host).expect("stats").root_slots, 0); + }); +} + +#[test] +fn saved_resume_close_failure_keeps_the_prefix_and_retries_from_roots() { + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let unrelated = host + .push_resource(crate::UnrelatedHostResource) + .expect("unrelated"); + let unrelated_raw = unrelated.handle().raw(); + crate::heap::install( + &mut host, + HeapLimits { + nodes: 16, + roots: 4, + edges: 4, + max_generation: 16, + }, + ) + .expect("limits"); + let (keeper, keeper_raw) = publish_node(&mut host); + crate::root_table(&mut host, keeper); + let (prefix, prefix_raw) = publish_node(&mut host); + let foreign = crate::heap::with_heap(&mut host, |heap| { + let node = heap.alloc()?; + heap.bind_token(node, unrelated_raw)?; + Ok(node) + }) + .expect("foreign token"); + let (suffix, suffix_raw) = publish_node(&mut host); + let meta = alloc_node(&mut host); + crate::root_table(&mut host, meta); + let watch = alloc_node(&mut host); + crate::root_table(&mut host, watch); + let (weak, weak_raw) = publish_node(&mut host); + crate::heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(watch, Some(meta))?; + heap.set_named_edge(watch, "gone", weak)?; + Ok(()) + }) + .expect("weak edge"); + assert!(prefix.slot() < foreign.slot() && foreign.slot() < suffix.slot()); + let roots = crate::heap::stats(&mut host).expect("roots").root_slots; + assert_eq!(roots, 3); + let resources = host.resource_count(); + save_reset_tail(&mut host); + let events = Cell::new(0u32); + + let error = resume_private_cycle(&mut host, BUDGET, &[], |_| { + events.set(events.get() + 1); + }) + .expect_err("foreign close"); + crate::assert_type_mismatch(&error); + let failed = crate::heap::take_scan_meter(&mut host).expect("failed meter"); + assert_eq!(events.get(), 0, "close failure does not publish"); + assert_eq!(failed.mark_passes, 1, "the saved pass was not replaced"); + assert_eq!(failed.token_closes, 2, "prefix closed, foreign attempted"); + assert_eq!(failed.sweep_edge_checks, 0); + assert_eq!(failed.scratch.dead_slots_pushed, 0); + assert_eq!(failed.scratch.sweep_bitmap_inited, 0); + assert_eq!( + crate::heap::stats(&mut host).expect("stats").collections, + 0, + "an incomplete resume is not a collection" + ); + assert_eq!( + crate::heap::stats(&mut host).expect("stats").root_slots, + roots + ); + assert!(host.resource(&unrelated).is_ok(), "foreign resource stays"); + assert!( + !token_open(&host, prefix_raw), + "the closed prefix stays closed" + ); + assert!(token_open(&host, suffix_raw), "the suffix stays open"); + assert!(token_open(&host, weak_raw), "the weak token is not closed"); + assert!(token_open(&host, keeper_raw)); + assert_eq!(host.resource_count(), resources - 1); + assert!(alive(&mut host, prefix)); + assert!(alive(&mut host, foreign)); + assert!(alive(&mut host, suffix)); + assert!(alive(&mut host, weak)); + assert_eq!( + crate::heap::with_heap(&mut host, |heap| heap.named_edge(watch, "gone")).expect("edge"), + Some(weak), + "the weak edge is unchanged" + ); + assert!( + !crate::heap::with_heap(&mut host, |heap| Ok(heap.has_saved_mark())).expect("saved"), + "the finished snapshot was dropped" + ); + + let again = resume_private_cycle(&mut host, BUDGET, &[], |_| { + events.set(events.get() + 1); + }) + .expect_err("a later continuation has no saved mark"); + assert!(matches!(again, HeapError::MarkDenied)); + assert_eq!(events.get(), 0); + assert_eq!(host.resource_count(), resources - 1); + assert!(token_open(&host, suffix_raw)); + assert_eq!( + crate::heap::with_heap(&mut host, |heap| heap.named_edge(watch, "gone")).expect("edge"), + Some(weak) + ); + + let retried = crate::heap::collect_observing(&mut host, |_| { + events.set(events.get() + 1); + }) + .expect_err("the same obstacle fails a fresh mark"); + crate::assert_type_mismatch(&retried); + let retried_meter = crate::heap::take_scan_meter(&mut host).expect("retry meter"); + assert_eq!(events.get(), 0); + assert_eq!( + retried_meter.mark_passes, 1, + "the retry marks from the current roots" + ); + assert_eq!(retried_meter.sweep_edge_checks, 0); + assert_eq!( + retried_meter.token_closes, 1, + "only the foreign token is attempted" + ); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 0); + assert!(token_open(&host, suffix_raw)); + assert!(token_open(&host, weak_raw)); + assert_eq!( + crate::heap::with_heap(&mut host, |heap| heap.named_edge(watch, "gone")).expect("edge"), + Some(weak) + ); + + crate::heap::with_heap(&mut host, |heap| heap.unbind_token(foreign)) + .expect("fixture drops the foreign binding"); + let (report, seen) = crate::heap::collect_observing(&mut host, |view| { + events.set(events.get() + 1); + assert!(view.still_physical(weak)); + assert!(!view.release_started()); + assert!(!view.finished()); + view.named(watch, "gone").expect("gone").is_none() + }) + .expect("collect finishes after the fixture removes the obstacle"); + assert_eq!(events.get(), 1, "one published observation"); + assert_eq!(seen, Some(true), "the weak edge is cleared at publish"); + assert_eq!(report.live_nodes, 3, "keeper, metatable, and watch stay"); + assert!(!alive(&mut host, weak)); + assert!(!alive(&mut host, suffix)); + assert!(!alive(&mut host, prefix)); + assert!(!alive(&mut host, foreign)); + assert!(alive(&mut host, keeper)); + assert!(alive(&mut host, watch)); + assert!(alive(&mut host, meta)); + assert!(!token_open(&host, weak_raw)); + assert!(!token_open(&host, suffix_raw)); + assert!(!token_open(&host, prefix_raw)); + assert!(token_open(&host, keeper_raw)); + assert!(host.resource(&unrelated).is_ok()); + assert_eq!(host.resource_count(), resources - 3); + assert_eq!(crate::heap::stats(&mut host).expect("stats").collections, 1); + let recovered = crate::heap::take_scan_meter(&mut host).expect("recovered meter"); + assert_eq!(recovered.mark_passes, 1); + assert!(recovered.sweep_edge_checks > 0, "the recovery sweep ran"); + }); +} From 7edc33120a128ddadb3e49816c8da7ea2824a958 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 07:03:00 +0800 Subject: [PATCH 113/225] feat(lua/heap): resume a published sweep after the weak release Save one owned release tail when dead slots remain, and continue it through the same release and root machine. Host collects and external commits refuse while that tail is stored. --- src/frontends/lua/heap.rs | 98 +++ src/frontends/lua/heap/table.rs | 138 +++- src/frontends/lua/heap/table/mark.rs | 9 +- src/frontends/lua/heap/table/sweep.rs | 235 ++++-- tests/luajit_heap_runtime/parked_mark.rs | 6 +- tests/luajit_heap_runtime/published_sweep.rs | 776 +++++++++++++++++++ 6 files changed, 1188 insertions(+), 74 deletions(-) create mode 100644 tests/luajit_heap_runtime/published_sweep.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index d8ebed5..a19bfdd 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -171,6 +171,12 @@ pub fn with_heap( /// A Pending result is an error. This type has no path that starts an /// asynchronous close, and this collector does not add one. pub fn collect(host: &mut HostContext) -> Result { + if host + .scope_state::() + .is_some_and(LuaHeap::has_sweep_tail) + { + return Err(HeapError::SweepPending); + } let marked = with_heap(host, |heap| Ok(heap.mark_and_doomed_tokens()))?; for token in marked.tokens { retire_doomed_token(host, token)?; @@ -178,6 +184,86 @@ pub fn collect(host: &mut HostContext) -> Result Result { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + if heap.has_sweep_tail() { + return Err(HeapError::SweepPending); + } + if heap.has_saved_mark() { + return Err(HeapError::MarkActive); + } + let marked = with_heap(host, |heap| Ok(heap.mark_and_doomed_tokens()))?; + for token in marked.tokens { + retire_doomed_token(host, token)?; + } + let halt = with_heap(host, |heap| Ok(heap.halt_at_publish(marked.modes)))?; + Ok(match halt { + table::PublishHalt::Completed(report) => PublishedBoundary::Completed(report), + table::PublishHalt::Published { heads, edges } => PublishedBoundary::Published { + window_heads: heads, + window_edges: edges, + }, + }) +} + +/// Continues a published sweep this scope already saved. Does not install a +/// heap and does not start a sweep. No saved tail is [`HeapError::SweepDenied`]. +/// +/// Zero budget with a saved tail returns [`PublishedResume::Paused`] without +/// reading the graph. A positive budget spends that many release or root units +/// on the same machine as a full sweep. The one report is returned only when +/// the tail finishes, and that tail is then gone. +fn resume_published_sweep( + host: &mut HostContext, + budget: u64, +) -> Result { + if host.scope_state::().is_none() { + return Err(HeapError::SweepDenied); + } + if budget == 0 { + let saved = host + .scope_state::() + .is_some_and(LuaHeap::has_sweep_tail); + if !saved { + return Err(HeapError::SweepDenied); + } + return Ok(PublishedResume::Paused); + } + match with_heap(host, |heap| Ok(heap.resume_sweep_tail(budget)))? { + table::TailResume::Denied => Err(HeapError::SweepDenied), + table::TailResume::Paused => Ok(PublishedResume::Paused), + table::TailResume::Completed(report) => Ok(PublishedResume::Completed(report)), + } +} + /// One host call: a fresh mark, the existing synchronous token close, then /// one sweep. The observer is lent only at the published boundary and does /// not receive the host. A parked mark is refused and left in place. This is @@ -186,6 +272,12 @@ pub fn collect_observing( host: &mut HostContext, observe: impl for<'a> FnOnce(&'a PublishedRead<'a>) -> R, ) -> Result<(table::CollectReport, Option), HeapError> { + if host + .scope_state::() + .is_some_and(LuaHeap::has_sweep_tail) + { + return Err(HeapError::SweepPending); + } let marked = with_heap(host, |heap| heap.begin_private_cycle())?; close_then_sweep_observing(host, marked, observe) } @@ -230,6 +322,12 @@ fn resume_private_cycle( if host.scope_state::().is_none() { return Err(HeapError::MarkDenied); } + if host + .scope_state::() + .is_some_and(LuaHeap::has_sweep_tail) + { + return Err(HeapError::SweepPending); + } if budget == 0 { let saved = host .scope_state::() diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 07e8f5f..7555d57 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -104,6 +104,10 @@ pub enum HeapError { MarkDenied, /// A mark is already active, so a second start or private collect cannot run. MarkActive, + /// A published sweep tail is still stored, so this mutation or collect cannot run. + SweepPending, + /// No heap is installed, or no published sweep tail can accept this resume. + SweepDenied, } impl HeapError { @@ -132,6 +136,8 @@ impl fmt::Display for HeapError { Self::Scope(message) => write!(formatter, "lua heap scope error: {message}"), Self::MarkDenied => write!(formatter, "lua mark denied this edit"), Self::MarkActive => write!(formatter, "lua mark is already active"), + Self::SweepPending => write!(formatter, "lua sweep is still pending"), + Self::SweepDenied => write!(formatter, "lua sweep denied this resume"), } } } @@ -653,6 +659,9 @@ pub struct LuaHeap { /// Mark progress saved between pulses. Absent unless a session or the /// parked driver is active. Done is not stored for the parked caller. mark: Option, + /// Release/root continuation after a published sweep. Absent unless publish + /// stopped with a dead slot. Done is not stored. + sweep_tail: Option, /// String and byte lengths stored in edge records. Not Vec capacity, not /// Core locals, and not a second scan of `edges`. payload_bytes: u64, @@ -677,6 +686,20 @@ fn sequence_index(key: &EdgeKey, cap: u32) -> Option { Some(number as u32) } +/// Where a publish-only sweep stopped. A completion means no dead slot was +/// published. `Published` has rewritten weak edges and has not released. +pub(super) enum PublishHalt { + Completed(CollectReport), + Published { heads: u64, edges: u64 }, +} + +/// Host-facing result of spending budget on a saved sweep tail. +pub(super) enum TailResume { + Denied, + Paused, + Completed(CollectReport), +} + impl LuaHeap { /// Reserved direct field id for `__mode`; ordinary field ids start at 1. pub const MODE_FIELD: u32 = 0; @@ -704,6 +727,7 @@ impl LuaHeap { peak_edges: 0, scan: ScanMeter::default(), mark: None, + sweep_tail: None, payload_bytes: 0, } } @@ -737,7 +761,9 @@ impl LuaHeap { } fn alloc_slot(&mut self, kind: HandleKind) -> Result<(u32, u32), HeapError> { - if let Some(index) = self.free_list.pop() { + if !self.free_list.is_empty() { + self.ensure_sweep_open()?; + let index = self.free_list.pop().expect("free list was not empty"); let slot = &mut self.slots[index as usize]; if !matches!(slot.state, SlotState::Free) { return Err(HeapError::StaleHandle); @@ -758,6 +784,7 @@ impl LuaHeap { if self.limits.max_generation == 0 { return Err(HeapError::GenerationExhausted); } + self.ensure_sweep_open()?; let index = u32::try_from(self.slots.len()).map_err(|_| HeapError::NodeCapacity)?; self.slots.push(Slot { generation: 1, @@ -779,6 +806,7 @@ impl LuaHeap { /// cannot be reissued as 1. pub fn rollback(&mut self, handle: TableRef) -> Result<(), HeapError> { self.require_live(handle)?; + self.ensure_sweep_open()?; self.clear_roots_to(handle); self.remove_edges_touching(handle.slot()); self.release_slot(handle.slot()); @@ -795,6 +823,7 @@ impl LuaHeap { if self.slots[index].carrier.is_some() { return Err(HeapError::StaleHandle); } + self.ensure_sweep_open()?; let value = Value::array(vec![ Value::Int(i64::from(table.slot())), Value::Int(i64::from(table.generation())), @@ -957,8 +986,7 @@ impl LuaHeap { pub fn clear_upvalue(&mut self, cell: UpvalueRef) -> Result<(), HeapError> { self.require_upvalue(cell)?; let key = EdgeKey::Field(CURRENT_EDGE); - self.unlink_key(cell.slot(), &key); - Ok(()) + self.unlink_key(cell.slot(), &key) } /// Reads the current edge through a closure. @@ -1109,7 +1137,7 @@ impl LuaHeap { self.require_live(from)?; let key = EdgeKey::Field(key); if matches!(value, Value::Null) { - self.clear_edge(from, &key); + self.clear_edge(from, &key)?; Ok(()) } else { self.write_edge(from, key, EdgeValue::Scalar(value)) @@ -1148,7 +1176,7 @@ impl LuaHeap { ); self.require_live(from)?; if matches!(value, Value::Null) { - self.clear_edge(from, &key); + self.clear_edge(from, &key)?; Ok(()) } else { self.write_edge(from, key, EdgeValue::Scalar(value)) @@ -1206,8 +1234,7 @@ impl LuaHeap { self.require_live(from)?; self.require_live(key)?; let key = EdgeKey::object(key); - self.clear_edge(from, &key); - Ok(()) + self.clear_edge(from, &key) } /// Writes one table under a closure identity key. @@ -1247,8 +1274,7 @@ impl LuaHeap { self.require_live(from)?; self.require_closure(key)?; let key = EdgeKey::closure_key(key); - self.clear_edge(from, &key); - Ok(()) + self.clear_edge(from, &key) } /// Reads a closure-key edge. The key domain, kind, and generation must @@ -1304,8 +1330,7 @@ impl LuaHeap { pub fn clear_number_edge(&mut self, from: TableRef, key: f64) -> Result<(), HeapError> { let key = Self::number_key(key)?; self.require_live(from)?; - self.clear_edge(from, &key); - Ok(()) + self.clear_edge(from, &key) } /// Reads a binary64 key. NaN reads nil after the table is confirmed live. @@ -1380,8 +1405,8 @@ impl LuaHeap { Ok(EdgeKey::number(key)) } - fn clear_edge(&mut self, from: TableRef, key: &EdgeKey) { - self.unlink_key(from.slot(), key); + fn clear_edge(&mut self, from: TableRef, key: &EdgeKey) -> Result<(), HeapError> { + self.unlink_key(from.slot(), key) } fn write_table_edge( @@ -1417,6 +1442,7 @@ impl LuaHeap { key: EdgeKey, value: EdgeValue, ) -> Result<(), HeapError> { + self.ensure_sweep_open()?; if let Some(index) = self.find_key(from_slot, &key) { self.replace_edge_value(from_slot, index, value); return Ok(()); @@ -1688,6 +1714,7 @@ impl LuaHeap { if let Some(target) = mt { self.require_live(target)?; } + self.ensure_sweep_open()?; let had = self.slots[owner.slot() as usize].metatable.is_some(); let next = mt.map(|target| (target.slot(), target.generation())); if had != next.is_some() { @@ -1729,6 +1756,7 @@ impl LuaHeap { if end > self.limits.roots { return Err(HeapError::RootCapacity); } + self.ensure_sweep_open()?; self.roots.resize(end as usize, None); let generation = self.next_frame_generation; self.next_frame_generation = self.next_frame_generation.saturating_add(1); @@ -1802,6 +1830,7 @@ impl LuaHeap { if slot >= found.width { return Err(HeapError::StaleFrame); } + self.ensure_sweep_open()?; let index = found.start as usize + slot as usize; self.roots[index] = Some(rooted); self.note_parked_root_store(rooted); @@ -1817,6 +1846,7 @@ impl LuaHeap { if slot >= found.width { return Err(HeapError::StaleFrame); } + self.ensure_sweep_open()?; let index = found.start as usize + slot as usize; self.roots[index] = None; Ok(()) @@ -1828,6 +1858,7 @@ impl LuaHeap { if top.index != frame.index || top.generation != frame.generation { return Err(HeapError::StaleFrame); } + self.ensure_sweep_open()?; let start = top.start as usize; self.roots.truncate(start); self.frames.pop(); @@ -1838,11 +1869,11 @@ impl LuaHeap { /// as a root. pub fn bind_token(&mut self, table: TableRef, raw: u64) -> Result<(), HeapError> { self.require_live(table)?; - let slot = &mut self.slots[table.slot() as usize]; - if slot.token.is_some() { + if self.slots[table.slot() as usize].token.is_some() { return Err(HeapError::StaleHandle); } - slot.token = Some(raw); + self.ensure_sweep_open()?; + self.slots[table.slot() as usize].token = Some(raw); Ok(()) } @@ -1858,6 +1889,7 @@ impl LuaHeap { /// [`Self::clear_exact_token`] instead. pub fn unbind_token(&mut self, table: TableRef) -> Result<(), HeapError> { self.require_live(table)?; + self.ensure_sweep_open()?; self.slots[table.slot() as usize].token = None; Ok(()) } @@ -1888,6 +1920,49 @@ impl LuaHeap { self.mark.is_some() } + /// True when a published sweep tail is stored. Does not read slots or edges. + pub(super) fn has_sweep_tail(&self) -> bool { + self.sweep_tail.is_some() + } + + /// A saved tail owns the graph. Checked after handle and capacity validation, + /// and before the first write or chain walk of a commit. + fn ensure_sweep_open(&self) -> Result<(), HeapError> { + if self.sweep_tail.is_some() { + Err(HeapError::SweepPending) + } else { + Ok(()) + } + } + + /// Spends `budget` on the saved tail. Zero restores it without a scan. + pub(super) fn resume_sweep_tail(&mut self, budget: u64) -> TailResume { + let Some(tail) = self.sweep_tail.take() else { + return TailResume::Denied; + }; + match tail.drive(self, budget) { + sweep::TailStep::Paused(tail) => { + self.sweep_tail = Some(tail); + TailResume::Paused + } + sweep::TailStep::Completed(report) => TailResume::Completed(report), + } + } + + /// Finishes a saved tail before a fresh pure-heap cycle. No tail is a no-op. + fn drain_sweep_tail(&mut self) { + let Some(tail) = self.sweep_tail.take() else { + return; + }; + match tail.drive(self, u64::MAX) { + sweep::TailStep::Completed(_) => {} + sweep::TailStep::Paused(tail) => { + self.sweep_tail = Some(tail); + debug_assert!(false, "a full budget must finish a saved sweep tail"); + } + } + } + /// Marks once, then drains the pending-close enumerator. Each slot check /// is one scan unit. The drain finishes before this returns, so host close /// still sees every doomed token and the original mark snapshot. A partial @@ -1919,10 +1994,12 @@ impl LuaHeap { /// Freed slots are reused with a bumped generation. A slot whose next /// generation would pass `max_generation` is retired instead. /// + /// A saved published tail is drained first, then this starts a fresh cycle. /// This is the pure-heap collector. A host heap must use `heap::collect`, /// which closes tokens before [`Self::sweep_marked`]. Calling this on a /// host heap would skip that close. pub fn collect(&mut self) -> CollectReport { + self.drain_sweep_tail(); let modes = self.mark_reachable(); self.sweep_marked(modes) } @@ -1945,6 +2022,9 @@ impl LuaHeap { if self.mark.is_some() { return Err(HeapError::MarkActive); } + if self.sweep_tail.is_some() { + return Err(HeapError::SweepPending); + } Ok(self.mark_and_doomed_tokens()) } @@ -1961,6 +2041,23 @@ impl LuaHeap { (session.report(), seen) } + /// Publishes weak edges and stores the release tail. No dead slot finishes + /// the sweep and records the one report. + pub(super) fn halt_at_publish(&mut self, modes: MarkSnapshot) -> PublishHalt { + debug_assert!(self.sweep_tail.is_none(), "publish must not stack a tail"); + let mut session = SweepSession::start(self, modes); + if !session.reach_before_owners() { + session.drain(); + return PublishHalt::Completed(session.report()); + } + let (heads, edges) = session + .publish_counts() + .expect("the owner boundary publishes once"); + let tail = session.into_release_tail(); + self.sweep_tail = Some(tail); + PublishHalt::Published { heads, edges } + } + /// Reports whether `handle` names a live table in this heap. pub fn alive(&self, handle: TableRef) -> bool { self.require_live(handle).is_ok() @@ -2243,7 +2340,8 @@ impl LuaHeap { self.slots[owner as usize].edge_tail = Some(index); } - fn unlink_key(&mut self, owner: u32, key: &EdgeKey) { + fn unlink_key(&mut self, owner: u32, key: &EdgeKey) -> Result<(), HeapError> { + self.ensure_sweep_open()?; let mut prev = None; let mut cursor = self .slots @@ -2257,11 +2355,12 @@ impl LuaHeap { .is_some_and(|edge| edge.key == *key); if matched { self.unlink_at(owner, prev, index); - return; + return Ok(()); } prev = Some(index); cursor = next; } + Ok(()) } fn unlink_at(&mut self, owner: u32, prev: Option, index: u32) { @@ -2402,6 +2501,9 @@ mod parked_mark; #[path = "../../../../tests/luajit_heap_runtime/private_cycle.rs"] mod private_cycle; #[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/published_sweep.rs"] +mod published_sweep; +#[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/resume_cycle.rs"] mod resume_cycle; #[cfg(test)] diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index feefe39..bd4aa59 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -158,6 +158,10 @@ impl MarkState { impl<'a> MarkSession<'a> { pub(super) fn start(heap: &'a mut LuaHeap) -> Self { debug_assert!(heap.mark.is_none(), "a mark is already parked"); + debug_assert!( + !heap.has_sweep_tail(), + "a published sweep tail and a mark session cannot coexist" + ); heap.mark = Some(MarkState::new()); Self { heap } } @@ -214,6 +218,9 @@ impl<'a> ParkedMark<'a> { if heap.mark.is_some() { return Err(HeapError::MarkActive); } + if heap.has_sweep_tail() { + return Err(HeapError::SweepPending); + } heap.mark = Some(MarkState::new()); Ok(Self { heap, @@ -378,7 +385,7 @@ impl<'a> ParkedMark<'a> { pub(super) fn delete_field(&mut self, from: TableRef, key: u32) -> Result<(), HeapError> { self.gate_field(from, key)?; let key = EdgeKey::Field(key); - self.heap.clear_edge(from, &key); + self.heap.clear_edge(from, &key)?; Ok(()) } diff --git a/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs index ee346a3..0be701f 100644 --- a/src/frontends/lua/heap/table/sweep.rs +++ b/src/frontends/lua/heap/table/sweep.rs @@ -60,6 +60,134 @@ enum SweepPhase { Done, } +/// Release or root scan saved after publish. No snapshot, modes, or owner cursor. +#[derive(Debug)] +pub(super) enum TailPhase { + Release, + Roots, + Done, +} + +/// Owned continuation of one published sweep. Only the fields Release and Roots need. +#[derive(Debug)] +pub(super) struct SweepTail { + phase: TailPhase, + index: usize, + dead: Vec, + marked_nodes: u32, + live_roots: u32, +} + +pub(super) enum TailStep { + Paused(SweepTail), + Completed(CollectReport), +} + +impl SweepTail { + /// Spends `budget` on the shared release/root machine. Zero does not read the heap. + pub(super) fn drive(self, heap: &mut LuaHeap, budget: u64) -> TailStep { + let mut phase = self.phase; + let mut index = self.index; + let dead = self.dead; + let marked_nodes = self.marked_nodes; + let mut live_roots = self.live_roots; + let mut report = None; + let mut releases = 0u64; + let mut roots = 0u64; + let mut left = budget; + let mut spins = 0u32; + while left > 0 && !matches!(phase, TailPhase::Done) { + let mut cursor = TailCursor { + phase: &mut phase, + index: &mut index, + dead: &dead, + marked_nodes, + live_roots: &mut live_roots, + report: &mut report, + releases: &mut releases, + roots: &mut roots, + }; + if step_tail(heap, &mut cursor) { + left -= 1; + spins = 0; + } else { + spins += 1; + debug_assert!(spins <= 4, "uncharged tail transition did not settle"); + } + } + if matches!(phase, TailPhase::Done) { + return TailStep::Completed(report.take().expect("a finished tail records one report")); + } + TailStep::Paused(SweepTail { + phase, + index, + dead, + marked_nodes, + live_roots, + }) + } +} + +/// One release, root, or uncharged transition. Callers share this with [`SweepSession`]. +struct TailCursor<'a> { + phase: &'a mut TailPhase, + index: &'a mut usize, + dead: &'a [u32], + marked_nodes: u32, + live_roots: &'a mut u32, + report: &'a mut Option, + releases: &'a mut u64, + roots: &'a mut u64, +} + +fn step_tail(heap: &mut LuaHeap, cursor: &mut TailCursor<'_>) -> bool { + match *cursor.phase { + TailPhase::Release => { + if *cursor.index >= cursor.dead.len() { + *cursor.index = 0; + *cursor.phase = TailPhase::Roots; + return false; + } + let slot = cursor.dead[*cursor.index]; + *cursor.index += 1; + heap.scan.node_slot_visits += 1; + heap.release_slot(slot); + *cursor.releases += 1; + true + } + TailPhase::Roots => { + if *cursor.index >= heap.roots.len() { + if cursor.report.is_none() { + heap.collections = heap.collections.saturating_add(1); + heap.last_marked = cursor.marked_nodes; + *cursor.report = Some(CollectReport { + live_nodes: cursor.marked_nodes, + marked_nodes: cursor.marked_nodes, + live_roots: *cursor.live_roots, + }); + } + *cursor.phase = TailPhase::Done; + return false; + } + let root_index = *cursor.index; + *cursor.index += 1; + heap.scan.root_slot_visits += 1; + *cursor.roots += 1; + let Some(rooted) = heap.roots[root_index] else { + return true; + }; + heap.scan.node_slot_visits += 1; + if heap.rooted_alive(rooted) { + *cursor.live_roots += 1; + } else { + heap.roots[root_index] = None; + } + true + } + TailPhase::Done => false, + } +} + enum SweepAction { Keep, Gap, @@ -93,6 +221,10 @@ impl SweepUnits { impl<'a> SweepSession<'a> { pub(super) fn start(heap: &'a mut LuaHeap, modes: MarkSnapshot) -> Self { + debug_assert!( + heap.sweep_tail.is_none(), + "a saved sweep tail and a new sweep cannot coexist" + ); Self { heap, modes, @@ -205,12 +337,38 @@ impl<'a> SweepSession<'a> { SweepPhase::Select => self.step_select(), SweepPhase::Snapshot => self.step_snapshot(), SweepPhase::Owners => self.step_owners(), - SweepPhase::Release => self.step_release(), - SweepPhase::Roots => self.step_root(), - SweepPhase::Done => false, + SweepPhase::Release | SweepPhase::Roots | SweepPhase::Done => self.step_saved_tail(), } } + fn step_saved_tail(&mut self) -> bool { + let mut phase = match self.phase { + SweepPhase::Release => TailPhase::Release, + SweepPhase::Roots => TailPhase::Roots, + SweepPhase::Done => TailPhase::Done, + SweepPhase::Select | SweepPhase::Snapshot | SweepPhase::Owners => { + unreachable!("saved tail phases only") + } + }; + let mut cursor = TailCursor { + phase: &mut phase, + index: &mut self.index, + dead: &self.dead, + marked_nodes: self.marked_nodes, + live_roots: &mut self.live_roots, + report: &mut self.report, + releases: &mut self.pulse_spent.releases, + roots: &mut self.pulse_spent.roots, + }; + let charged = step_tail(self.heap, &mut cursor); + self.phase = match phase { + TailPhase::Release => SweepPhase::Release, + TailPhase::Roots => SweepPhase::Roots, + TailPhase::Done => SweepPhase::Done, + }; + charged + } + fn step_select(&mut self) -> bool { if self.index >= self.heap.slots.len() { self.index = 0; @@ -372,56 +530,6 @@ impl<'a> SweepSession<'a> { } } - fn step_release(&mut self) -> bool { - if self.index >= self.dead.len() { - self.index = 0; - self.phase = SweepPhase::Roots; - return false; - } - let slot = self.dead[self.index]; - self.index += 1; - self.heap.scan.node_slot_visits += 1; - self.heap.release_slot(slot); - self.pulse_spent.releases += 1; - true - } - - fn step_root(&mut self) -> bool { - if self.index >= self.heap.roots.len() { - self.finish(); - return false; - } - let index = self.index; - self.index += 1; - self.heap.scan.root_slot_visits += 1; - self.pulse_spent.roots += 1; - let Some(rooted) = self.heap.roots[index] else { - return true; - }; - self.heap.scan.node_slot_visits += 1; - if self.heap.rooted_alive(rooted) { - self.live_roots += 1; - } else { - self.heap.roots[index] = None; - } - true - } - - fn finish(&mut self) { - if self.report.is_some() { - self.phase = SweepPhase::Done; - return; - } - self.heap.collections = self.heap.collections.saturating_add(1); - self.heap.last_marked = self.marked_nodes; - self.report = Some(CollectReport { - live_nodes: self.marked_nodes, - marked_nodes: self.marked_nodes, - live_roots: self.live_roots, - }); - self.phase = SweepPhase::Done; - } - fn is_marked(&self, slot: u32) -> bool { self.snapshot .get(slot as usize) @@ -490,6 +598,27 @@ impl<'a> SweepSession<'a> { }) } + /// Same owner walk as [`Self::publish_owners`], returning only the charged + /// head and edge counts. The window borrow ends before this returns. + pub(super) fn publish_counts(&mut self) -> Option<(u64, u64)> { + let window = self.publish_owners()?; + Some((window.spent.heads, window.spent.edges)) + } + + /// Drops the snapshot, modes, and owner cursor. The caller stores this tail. + pub(super) fn into_release_tail(self) -> SweepTail { + debug_assert!(matches!(self.phase, SweepPhase::Release)); + debug_assert_eq!(self.index, 0); + debug_assert!(self.report.is_none()); + SweepTail { + phase: TailPhase::Release, + index: 0, + dead: self.dead, + marked_nodes: self.marked_nodes, + live_roots: self.live_roots, + } + } + fn at_owner_start(&self) -> bool { self.owner == 0 && !self.owner_open && self.cursor.is_none() } diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index 1b0a85a..7fb53ff 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -1055,7 +1055,8 @@ fn barrier_black_owner_keeps_the_cycle_until_release() { assert_eq!(view.mark_passes, 1); assert_eq!(heap.scan.mark_passes, 1); - heap.clear_edge(graph.owner, &super::EdgeKey::Field(KEY_REPLACED)); + heap.clear_edge(graph.owner, &super::EdgeKey::Field(KEY_REPLACED)) + .expect("clear"); heap.collect(); assert!( !heap.alive(graph.cycle.p) && !heap.alive(graph.cycle.q) && !heap.alive(graph.cycle.r), @@ -1704,7 +1705,8 @@ fn raw_set_edge_on_scanned_owner_keeps_the_strong_cycle() { assert_eq!(view.mark_passes, 1); assert_eq!(heap.scan.mark_passes, 1); assert!(heap.alive(graph.owner) && heap.alive(graph.kept) && heap.alive(graph.child)); - heap.clear_edge(graph.owner, &super::EdgeKey::Field(KEY_REPLACED)); + heap.clear_edge(graph.owner, &super::EdgeKey::Field(KEY_REPLACED)) + .expect("clear"); heap.collect(); assert!( !heap.alive(graph.cycle.p) && !heap.alive(graph.cycle.q) && !heap.alive(graph.cycle.r), diff --git a/tests/luajit_heap_runtime/published_sweep.rs b/tests/luajit_heap_runtime/published_sweep.rs new file mode 100644 index 0000000..3f43f33 --- /dev/null +++ b/tests/luajit_heap_runtime/published_sweep.rs @@ -0,0 +1,776 @@ +//! Published sweep tail. +//! +//! Publish clears weak values and closes their tokens, then saves one owned +//! release tail. Resume spends budget on that tail and must free the still +//! physical dead slot. The ordinary sweep uses the same release and root steps. +//! +//! Commit gates, each checked after handle or capacity validation and before +//! the first write or chain walk. Low-level `unlink_at`, `rewrite_gap`, and +//! `release_slot` stay ungated; sweep calls those directly. +//! +//! - alloc table/closure/upvalue, including a free-list reuse: `alloc_slot` +//! - rollback: after `require_live` +//! - `issue_carrier`: after the existing-carrier check +//! - table, closure, upvalue, and mode writes: `write_from` +//! - table, object, number, closure-key, and upvalue deletes: `unlink_key` +//! - metatable replace: `set_metatable` +//! - `enter_roots`, `store_root` (table, closure, upvalue), `clear_root`, `leave_roots` +//! - `bind_token`, `unbind_token` +//! - `heap::publish`: the alloc gate, so no token is pushed +//! - `heap::collect`, `collect_observing`, `resume_private_cycle`: before mark or close +//! - `ParkedMark::start`, `begin_private_cycle`: before a mark is installed +//! +//! `clear_exact_token` is the close primitive. Host collect is refused before +//! it runs, so a saved tail never reaches it. + +use super::ParkedMark; +use vm::Value; + +use crate::heap::{ + self, HeapError, HeapLimits, LuaHeap, PublishedBoundary, PublishedResume, ScanMeter, TableRef, +}; + +fn limits() -> HeapLimits { + HeapLimits { + nodes: 8, + roots: 4, + edges: 8, + max_generation: 8, + } +} + +fn token_open(host: &mut vm::HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + crate::resource_handle(raw), + &heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn slot_generation(heap: &LuaHeap, table: TableRef) -> u32 { + heap.slots[table.slot() as usize].generation +} + +#[test] +fn published_resume_frees_the_closed_dead_slot() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let meta = heap::with_heap(&mut host, LuaHeap::alloc).expect("meta"); + let (owner, owner_token) = publish(&mut host); + let (live, live_token) = publish(&mut host); + let (dead, dead_token) = publish(&mut host); + let resources_before = host.resource_count(); + let original_generation = dead.generation(); + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "stay", live)?; + heap.set_named_edge(owner, "gone", dead)?; + heap.set_number_edge(owner, 1.0, dead)?; + heap.set_named_edge(dead, "self", dead)?; + let live_carrier = heap.issue_carrier(live)?; + let frame = heap.enter_roots(3)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, live)?; + assert_eq!(heap.raw_sequence_len(owner)?, 1.0); + Ok(live_carrier) + }) + .expect("graph"); + let live_carrier = + heap::with_heap(&mut host, |heap| heap.issued_value(live)).expect("carrier"); + let _ = heap::take_scan_meter(&mut host).expect("clear meter"); + + let published = heap::collect_until_published(&mut host).expect("publish"); + let PublishedBoundary::Published { + window_heads, + window_edges, + } = published + else { + panic!("publish must stop before release, got {published:?}"); + }; + assert_eq!(window_heads, 4, "one owner head per slot"); + assert_eq!(window_edges, 5, "mode, stay, gone, number, self"); + let stats = heap::stats(&mut host).expect("stats"); + assert_eq!(stats.collections, 0, "publish is not a completion report"); + assert_eq!(stats.live_nodes, 4, "dead node still occupies a slot"); + assert_eq!( + stats.live_edges, 2, + "weak values became gaps; unmarked self edge dropped" + ); + assert!(!token_open(&mut host, dead_token), "dead token closed"); + assert!(token_open(&mut host, live_token)); + assert!(token_open(&mut host, owner_token)); + assert_eq!(host.resource_count(), resources_before - 1); + heap::with_heap(&mut host, |heap| { + assert!(heap.alive(dead), "dead slot still physical"); + assert_eq!(slot_generation(heap, dead), original_generation); + assert!(heap.alive(live)); + assert!(heap.alive(owner)); + assert_eq!(heap.named_edge(owner, "gone")?, None, "weak value cleared"); + assert_eq!(heap.named_edge(owner, "stay")?, Some(live)); + assert_eq!(heap.raw_sequence_len(owner)?, 0.0, "rawlen ignores the gap"); + let started = heap.next_guest(owner, &Value::Null)?.expect("stay"); + assert_eq!(started.0, Value::string("stay")); + assert_eq!(started.1, live_carrier); + assert_eq!( + heap.next_guest(owner, &Value::string("gone"))?, + None, + "cleared key remains a cursor" + ); + Ok(()) + }) + .expect("published graph"); + let publish_meter = heap::take_scan_meter(&mut host).expect("publish meter"); + assert_eq!( + publish_meter.owner_head_checks, + window_heads + 3, + "mark reads the three rooted nodes; sweep reads one head per slot" + ); + assert_eq!(publish_meter.sweep_edge_checks, window_edges); + assert_eq!(publish_meter.scratch.dead_slots_pushed, 1); + assert_eq!(publish_meter.scratch.sweep_bitmap_inited, window_heads); + assert_eq!(publish_meter.token_closes, 1); + assert_eq!(publish_meter.mark_passes, 1); + + let zero = heap::resume_published_sweep(&mut host, 0).expect("saved tail accepts zero"); + assert!( + matches!(zero, PublishedResume::Paused), + "zero budget pauses without scanning, got {zero:?}" + ); + let meter = heap::take_scan_meter(&mut host).expect("zero meter"); + assert_eq!(meter, ScanMeter::default(), "zero budget does not scan"); + let still = heap::with_heap(&mut host, |heap| Ok(heap.alive(dead))).expect("alive"); + assert!(still, "zero budget does not release"); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + + let one = heap::resume_published_sweep(&mut host, 1); + let (released, generation) = heap::with_heap(&mut host, |heap| { + Ok((!heap.alive(dead), slot_generation(heap, dead))) + }) + .expect("resume facts"); + let completed = matches!(one, Ok(PublishedResume::Completed(_))); + let collections = heap::stats(&mut host).expect("stats").collections; + assert!( + released && generation != original_generation && !completed, + "resume left the dead node physical and produced no completion report; released={released} completed={completed} generation={generation} original={original_generation} collections={collections} outcome={one:?}" + ); + + let resume_meter = heap::take_scan_meter(&mut host).expect("release meter"); + assert_eq!(resume_meter.node_slot_visits, 1, "one release visit"); + assert_eq!(resume_meter.root_slot_visits, 0); + assert_eq!( + resume_meter.owner_head_checks, 0, + "resume does not repeat Owners" + ); + assert_eq!(resume_meter.sweep_edge_checks, 0); + assert_eq!( + resume_meter.scratch.dead_slots_pushed, 0, + "no re-enumeration" + ); + assert_eq!(resume_meter.scratch.sweep_bitmap_inited, 0); + assert_eq!(resume_meter.mark_passes, 0, "no remark"); + assert_eq!(resume_meter.token_closes, 0); + assert_eq!(resume_meter.scratch.pending_close_pushed, 0); + assert_eq!(collections, 0, "one release is not the completion report"); + assert_eq!(host.resource_count(), resources_before - 1); + assert!(token_open(&mut host, live_token)); + assert!(token_open(&mut host, owner_token)); + + let rest = heap::resume_published_sweep(&mut host, 8).expect("finish roots"); + let PublishedResume::Completed(report) = rest else { + panic!("remaining budget must finish once, got {rest:?}"); + }; + assert_eq!(report.live_nodes, 3); + assert_eq!(report.marked_nodes, 3); + assert_eq!(report.live_roots, 3); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + let finish_meter = heap::take_scan_meter(&mut host).expect("finish meter"); + assert_eq!(finish_meter.root_slot_visits, 3); + assert_eq!(finish_meter.node_slot_visits, 3); + assert_eq!(finish_meter.owner_head_checks, 0); + assert_eq!(finish_meter.scratch.dead_slots_pushed, 0); + assert_eq!(finish_meter.mark_passes, 0); + let again = heap::resume_published_sweep(&mut host, 8); + assert_eq!(again.unwrap_err(), HeapError::SweepDenied); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + assert_eq!( + heap::take_scan_meter(&mut host).expect("denied meter"), + ScanMeter::default() + ); + let reused = heap::with_heap(&mut host, LuaHeap::alloc).expect("reuse"); + assert_eq!(reused.slot(), dead.slot()); + assert_eq!(reused.generation(), original_generation + 1); + }); +} + +fn publish(host: &mut vm::HostContext<'_>) -> (TableRef, i64) { + let raw = crate::publish_raw(host); + (crate::table_ref(host, raw), raw) +} + +fn assert_pending(error: HeapError) { + assert_eq!(error, HeapError::SweepPending); +} + +#[test] +fn published_resume_splits_before_the_uncharged_finish() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let meta = heap::with_heap(&mut host, LuaHeap::alloc).expect("meta"); + let (owner, _) = publish(&mut host); + let (live, _) = publish(&mut host); + let (dead, dead_token) = publish(&mut host); + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "stay", live)?; + heap.set_named_edge(owner, "gone", dead)?; + let frame = heap.enter_roots(4)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, live)?; + Ok(frame) + }) + .expect("graph"); + let _ = heap::take_scan_meter(&mut host); + let published = heap::collect_until_published(&mut host).expect("publish"); + assert!(matches!(published, PublishedBoundary::Published { .. })); + let _ = heap::take_scan_meter(&mut host); + + let zero = heap::resume_published_sweep(&mut host, 0).expect("zero"); + assert!(matches!(zero, PublishedResume::Paused)); + assert_eq!( + heap::take_scan_meter(&mut host).expect("zero meter"), + ScanMeter::default() + ); + + let released = heap::resume_published_sweep(&mut host, 1).expect("release"); + assert!(matches!(released, PublishedResume::Paused)); + let release_meter = heap::take_scan_meter(&mut host).expect("release meter"); + assert_eq!(release_meter.node_slot_visits, 1); + assert_eq!(release_meter.root_slot_visits, 0); + assert!(!token_open(&mut host, dead_token)); + + let first_roots = heap::resume_published_sweep(&mut host, 2).expect("two roots"); + assert!(matches!(first_roots, PublishedResume::Paused)); + let first_meter = heap::take_scan_meter(&mut host).expect("first roots"); + assert_eq!(first_meter.root_slot_visits, 2); + assert_eq!(first_meter.node_slot_visits, 2); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + + let third = heap::resume_published_sweep(&mut host, 1).expect("third root"); + assert!(matches!(third, PublishedResume::Paused)); + assert_eq!( + heap::take_scan_meter(&mut host) + .expect("third") + .root_slot_visits, + 1 + ); + + let last = heap::resume_published_sweep(&mut host, 1).expect("last charged root"); + assert!( + matches!(last, PublishedResume::Paused), + "the last charged root does not finish, got {last:?}" + ); + let last_meter = heap::take_scan_meter(&mut host).expect("last meter"); + assert_eq!(last_meter.root_slot_visits, 1); + assert_eq!( + last_meter.node_slot_visits, 0, + "the empty root slot charges without a node" + ); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + + let finished = heap::resume_published_sweep(&mut host, 1).expect("uncharged finish"); + let PublishedResume::Completed(report) = finished else { + panic!("the call after the last charge only records the report, got {finished:?}"); + }; + let finish_meter = heap::take_scan_meter(&mut host).expect("finish meter"); + assert_eq!(finish_meter, ScanMeter::default(), "finish does not charge"); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + assert_eq!(report.marked_nodes, 3); + + let again = heap::resume_published_sweep(&mut host, 1).expect_err("tail is gone"); + assert_eq!(again, HeapError::SweepDenied); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + assert_eq!( + heap::take_scan_meter(&mut host).expect("denied"), + ScanMeter::default() + ); + }); +} + +#[test] +fn published_pause_refuses_commits_and_keeps_validation_first() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let meta = heap::with_heap(&mut host, LuaHeap::alloc).expect("meta"); + let (owner, owner_token) = publish(&mut host); + let (live, live_token) = publish(&mut host); + let (dead, _) = publish(&mut host); + let (stale, closure, cell, bare, frame) = heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "stay", live)?; + heap.set_named_edge(owner, "gone", dead)?; + heap.set_number_edge(owner, 1.0, dead)?; + heap.set_object_edge(owner, live, live)?; + let closure = heap.alloc_closure()?; + let cell = heap.alloc_upvalue()?; + heap.write_upvalue(cell, live)?; + heap.set_closure_key_edge(owner, closure, live)?; + heap.set_closure_edge(owner, 9, closure)?; + let stale = heap.alloc()?; + heap.rollback(stale)?; + let bare = heap.alloc()?; + let frame = heap.enter_roots(3)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, live)?; + Ok((stale, closure, cell, bare, frame)) + }) + .expect("graph"); + let resources_before = host.resource_count(); + let _ = heap::take_scan_meter(&mut host); + assert!(matches!( + heap::collect_until_published(&mut host).expect("publish"), + PublishedBoundary::Published { .. } + )); + let _ = heap::take_scan_meter(&mut host); + let stats_before = heap::stats(&mut host).expect("stats"); + let generation = + heap::with_heap(&mut host, |heap| Ok(slot_generation(heap, dead))).expect("gen"); + + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.clear_number_edge(owner, f64::NAN), + Err(HeapError::NanIndex) + ); + assert_eq!( + heap.set_named_edge(stale, "x", live), + Err(HeapError::StaleHandle) + ); + assert_eq!(heap.bind_token(live, 1), Err(HeapError::StaleHandle)); + assert_eq!(heap.enter_roots(2), Err(HeapError::RootCapacity)); + assert_eq!(heap.enter_roots(0), Err(HeapError::StaleFrame)); + let mut other = LuaHeap::new(limits()); + let foreign = other.alloc()?; + assert_eq!( + heap.set_named_edge(foreign, "x", live), + Err(HeapError::WrongDomain) + ); + let created = other.alloc()?; + assert!(other.alive(created), "a heap with no tail still allocates"); + + assert_pending(heap.alloc().unwrap_err()); + assert_pending(heap.alloc_closure().unwrap_err()); + assert_pending(heap.alloc_upvalue().unwrap_err()); + assert_pending(heap.rollback(bare).unwrap_err()); + assert_pending(heap.issue_carrier(bare).unwrap_err()); + assert_pending(heap.set_named_edge(dead, "x", live).unwrap_err()); + assert_pending(heap.set_named_edge(owner, "extra", live).unwrap_err()); + assert_pending( + heap.set_named_scalar(owner, "stay", Value::Null) + .unwrap_err(), + ); + assert_pending(heap.clear_object_edge(owner, live).unwrap_err()); + assert_pending(heap.clear_number_edge(owner, 1.0).unwrap_err()); + assert_pending(heap.clear_closure_key(owner, closure).unwrap_err()); + assert_pending(heap.clear_upvalue(cell).unwrap_err()); + assert_pending(heap.write_upvalue(cell, owner).unwrap_err()); + assert_pending(heap.set_closure_edge(owner, 9, closure).unwrap_err()); + assert_pending(heap.set_mode_scalar(meta, Value::string("k")).unwrap_err()); + assert_pending(heap.set_metatable(owner, None).unwrap_err()); + assert_pending(heap.enter_roots(1).unwrap_err()); + assert_pending(heap.write_root(frame, 0, live).unwrap_err()); + assert_pending(heap.write_closure_root(frame, 0, closure).unwrap_err()); + assert_pending(heap.write_upvalue_root(frame, 0, cell).unwrap_err()); + assert_pending(heap.clear_root(frame, 0).unwrap_err()); + assert_pending(heap.leave_roots(frame).unwrap_err()); + assert_pending(heap.bind_token(bare, 7).unwrap_err()); + assert_pending(heap.unbind_token(live).unwrap_err()); + assert_eq!(heap.named_edge(owner, "stay")?, Some(live)); + assert_eq!( + heap.current_table(cell)?, + None, + "the unrooted cell was swept; the refused write did not restore it" + ); + assert!(heap.alive(bare)); + assert!(heap.alive(dead)); + assert_eq!(slot_generation(heap, dead), generation); + assert_eq!(heap.current_frame(), Some(frame)); + Ok(()) + }) + .expect("refused commits"); + assert_eq!( + heap::publish(&mut host).unwrap_err(), + HeapError::SweepPending + ); + assert_eq!(host.resource_count(), resources_before - 1); + assert!(token_open(&mut host, owner_token)); + assert!(token_open(&mut host, live_token)); + assert_eq!(heap::stats(&mut host).expect("stats"), stats_before); + assert_eq!( + heap::take_scan_meter(&mut host).expect("refused meter"), + ScanMeter::default() + ); + let still = heap::resume_published_sweep(&mut host, 0).expect("progress unchanged"); + assert!(matches!(still, PublishedResume::Paused)); + let one = heap::resume_published_sweep(&mut host, 1).expect("same dead slot"); + assert!(matches!(one, PublishedResume::Paused)); + let released = heap::with_heap(&mut host, |heap| Ok(!heap.alive(dead))).expect("released"); + assert!(released, "refusals did not consume the release"); + }); +} + +#[test] +fn node_capacity_wins_while_a_tail_is_saved() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 3, + roots: 2, + edges: 4, + max_generation: 4, + }); + let meta = heap.alloc().expect("meta"); + let owner = heap.alloc().expect("owner"); + let dead = heap.alloc().expect("dead"); + heap.set_mode_scalar(meta, Value::string("v")) + .expect("mode"); + heap.set_metatable(owner, Some(meta)).expect("mt"); + heap.set_named_edge(owner, "gone", dead).expect("weak"); + let frame = heap.enter_roots(2).expect("frame"); + heap.write_root(frame, 0, meta).expect("meta"); + heap.write_root(frame, 1, owner).expect("owner"); + let marked = heap.mark_and_doomed_tokens(); + assert!(matches!( + heap.halt_at_publish(marked.modes), + super::PublishHalt::Published { .. } + )); + assert_eq!(heap.alloc().expect_err("full"), HeapError::NodeCapacity); + assert_eq!(heap.stats().node_slots, 3); + assert!(heap.has_sweep_tail()); +} + +#[test] +fn published_close_failure_saves_no_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let unrelated = host + .push_resource(crate::UnrelatedHostResource) + .expect("unrelated"); + let unrelated_raw = unrelated.handle().raw(); + let (keeper, _) = publish(&mut host); + heap::with_heap(&mut host, |heap| { + let frame = heap.enter_roots(1)?; + heap.write_root(frame, 0, keeper) + }) + .expect("root"); + let (prefix, prefix_token) = publish(&mut host); + let (_other, other_token) = publish(&mut host); + let doomed = heap::with_heap(&mut host, |heap| { + let node = heap.alloc()?; + heap.bind_token(node, unrelated_raw)?; + Ok(node) + }) + .expect("foreign token"); + let (suffix, suffix_token) = publish(&mut host); + let resources_before = host.resource_count(); + let _ = heap::take_scan_meter(&mut host); + + let error = heap::collect_until_published(&mut host).expect_err("type mismatch"); + crate::assert_type_mismatch(&error); + let failed = heap::take_scan_meter(&mut host).expect("failed meter"); + assert_eq!( + failed.sweep_edge_checks, 0, + "close failure does not publish" + ); + assert_eq!(failed.scratch.dead_slots_pushed, 0); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + assert!(!token_open(&mut host, prefix_token), "prefix close is real"); + assert!(!token_open(&mut host, other_token)); + assert!(token_open(&mut host, suffix_token), "suffix stays open"); + assert_eq!( + heap::resume_published_sweep(&mut host, 1).expect_err("no tail"), + HeapError::SweepDenied + ); + let allocated = heap::with_heap(&mut host, LuaHeap::alloc).expect("no tail, alloc works"); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(allocated))).expect("alive")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(prefix))).expect("prefix")); + assert_eq!(host.resource_count(), resources_before - 2); + + heap::with_heap(&mut host, |heap| heap.unbind_token(doomed)).expect("remove obstacle"); + let retried = heap::collect_until_published(&mut host).expect("retry publishes"); + assert!( + matches!(retried, PublishedBoundary::Published { .. }), + "dead slots remain, so retry saves a tail, got {retried:?}" + ); + assert!( + !token_open(&mut host, suffix_token), + "suffix closes on the retry" + ); + let finished = heap::resume_published_sweep(&mut host, 8).expect("retry finishes"); + assert!(matches!(finished, PublishedResume::Completed(_))); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(suffix))).expect("suffix")); + let _ = keeper; + }); +} + +#[test] +fn published_with_no_dead_slot_finishes_without_a_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let (keeper, token) = publish(&mut host); + heap::with_heap(&mut host, |heap| { + let frame = heap.enter_roots(1)?; + heap.write_root(frame, 0, keeper) + }) + .expect("root"); + let finished = heap::collect_until_published(&mut host).expect("no dead slot"); + let PublishedBoundary::Completed(report) = finished else { + panic!("no dead slot must finish, got {finished:?}"); + }; + assert!(report.live_nodes >= 1); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + assert!(token_open(&mut host, token)); + assert_eq!( + heap::resume_published_sweep(&mut host, 1).expect_err("no tail"), + HeapError::SweepDenied + ); + }); +} + +#[test] +fn saved_mark_still_refuses_a_new_publish() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + heap::with_heap(&mut host, |heap| { + let parked = ParkedMark::start(heap).expect("start"); + parked.park().expect("park"); + Ok(()) + }) + .expect("park"); + let error = heap::collect_until_published(&mut host).expect_err("mark active"); + assert_eq!(error, HeapError::MarkActive); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + heap::with_heap(&mut host, |heap| { + assert!(ParkedMark::resume(heap).is_some(), "the mark stays"); + assert!(!heap.has_sweep_tail()); + Ok(()) + }) + .expect("mark remains"); + assert_eq!( + heap::take_scan_meter(&mut host).expect("meter"), + ScanMeter::default() + ); + }); +} + +#[test] +fn host_collect_refuses_while_the_tail_can_still_finish() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let meta = heap::with_heap(&mut host, LuaHeap::alloc).expect("meta"); + let (owner, _) = publish(&mut host); + let (dead, _) = publish(&mut host); + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "gone", dead)?; + let frame = heap.enter_roots(2)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + Ok(()) + }) + .expect("graph"); + let _ = heap::take_scan_meter(&mut host); + assert!(matches!( + heap::collect_until_published(&mut host).expect("publish"), + PublishedBoundary::Published { .. } + )); + let _ = heap::take_scan_meter(&mut host); + let stats = heap::stats(&mut host).expect("stats"); + + assert_eq!( + heap::collect(&mut host).expect_err("full"), + HeapError::SweepPending + ); + assert_eq!( + heap::collect_observing(&mut host, |_| ()).expect_err("private"), + HeapError::SweepPending + ); + assert_eq!( + crate::heap::resume_private_cycle(&mut host, 1, &[], |_| ()).expect_err("resume"), + HeapError::SweepPending + ); + heap::with_heap(&mut host, |heap| { + assert_eq!(ParkedMark::start(heap).err(), Some(HeapError::SweepPending)); + assert_eq!( + heap.begin_private_cycle().err(), + Some(HeapError::SweepPending) + ); + assert!(!heap.has_saved_mark(), "a refused start installs no mark"); + Ok(()) + }) + .expect("starts refused"); + assert_eq!(heap::stats(&mut host).expect("stats"), stats); + assert_eq!( + heap::take_scan_meter(&mut host).expect("meter"), + ScanMeter::default() + ); + + let finished = heap::resume_published_sweep(&mut host, 8).expect("tail still finishes"); + assert!(matches!(finished, PublishedResume::Completed(_))); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(dead))).expect("dead")); + }); +} + +#[test] +fn stateless_publish_and_zero_resume_do_not_install_a_heap() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + assert!(host.scope_state::().is_none()); + assert_eq!( + heap::collect_until_published(&mut host).expect_err("no heap"), + HeapError::SweepDenied + ); + assert_eq!( + heap::resume_published_sweep(&mut host, 0).expect_err("zero"), + HeapError::SweepDenied + ); + assert_eq!( + heap::resume_published_sweep(&mut host, 4).expect_err("positive"), + HeapError::SweepDenied + ); + assert!( + host.scope_state::().is_none(), + "no heap was installed" + ); + }); +} + +#[test] +fn pure_heap_collect_drains_the_tail_then_collects_fresh() { + let mut heap = LuaHeap::new(limits()); + let meta = heap.alloc().expect("meta"); + let owner = heap.alloc().expect("owner"); + let dead = heap.alloc().expect("dead"); + heap.set_mode_scalar(meta, Value::string("v")) + .expect("mode"); + heap.set_metatable(owner, Some(meta)).expect("mt"); + heap.set_named_edge(owner, "gone", dead).expect("weak"); + let frame = heap.enter_roots(2).expect("frame"); + heap.write_root(frame, 0, meta).expect("meta"); + heap.write_root(frame, 1, owner).expect("owner"); + let marked = heap.mark_and_doomed_tokens(); + assert!(matches!( + heap.halt_at_publish(marked.modes), + super::PublishHalt::Published { .. } + )); + assert!(heap.alive(dead)); + assert!(heap.has_sweep_tail()); + let report = heap.collect(); + assert!(!heap.has_sweep_tail(), "drain consumed the tail"); + assert!(!heap.alive(dead), "drain released the dead slot"); + assert_eq!( + heap.stats().collections, + 2, + "drain records one report, then a fresh cycle" + ); + assert!( + report.live_nodes >= 2, + "the fresh cycle marked the rooted nodes" + ); + + let mut idle = LuaHeap::new(limits()); + let idle_report = idle.collect(); + assert_eq!( + idle.stats().collections, + 1, + "no tail is still one fresh collect" + ); + assert_eq!(idle_report.live_nodes, 0); +} + +#[test] +fn published_resume_matches_a_full_collect() { + fn build(host: &mut vm::HostContext<'_>) -> (TableRef, TableRef, TableRef, i64) { + heap::install(host, limits()).expect("install"); + let meta = heap::with_heap(host, LuaHeap::alloc).expect("meta"); + let (owner, _) = publish(host); + let (live, live_token) = publish(host); + let (dead, _) = publish(host); + heap::with_heap(host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "stay", live)?; + heap.set_named_edge(owner, "gone", dead)?; + heap.set_number_edge(owner, 1.0, dead)?; + heap.issue_carrier(live)?; + let frame = heap.enter_roots(3)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, live)?; + Ok(()) + }) + .expect("graph"); + (owner, live, dead, live_token) + } + fn witness( + host: &mut vm::HostContext<'_>, + owner: TableRef, + live: TableRef, + dead: TableRef, + ) -> (f64, bool, bool, bool, u32) { + heap::with_heap(host, |heap| { + let started = heap.next_guest(owner, &Value::Null)?; + let stay = started.is_some_and(|(key, _)| key == Value::string("stay")); + let gone_cursor = heap.next_guest(owner, &Value::string("gone"))?.is_none(); + Ok(( + heap.raw_sequence_len(owner)?, + stay, + gone_cursor, + heap.named_edge(owner, "stay")? == Some(live) + && heap.named_edge(owner, "gone")?.is_none(), + slot_generation(heap, dead), + )) + }) + .expect("witness") + } + + let resumed = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let (owner, live, dead, live_token) = build(&mut host); + assert!(matches!( + heap::collect_until_published(&mut host).expect("publish"), + PublishedBoundary::Published { .. } + )); + assert!(matches!( + heap::resume_published_sweep(&mut host, 8).expect("resume"), + PublishedResume::Completed(_) + )); + assert!(token_open(&mut host, live_token)); + witness(&mut host, owner, live, dead) + }); + let collected = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let (owner, live, dead, live_token) = build(&mut host); + heap::collect(&mut host).expect("full collect"); + assert!(token_open(&mut host, live_token)); + witness(&mut host, owner, live, dead) + }); + assert_eq!( + resumed, collected, + "publish plus resume matches a full collect" + ); + assert_eq!(resumed.0, 0.0, "rawlen ignores the cleared weak number"); + assert!(resumed.1 && resumed.2 && resumed.3); + assert_ne!(resumed.4, 1, "both paths released the dead slot"); +} From f9bb077f1b47f82c3ec9ce21ccfa2e0123dc026f Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 06:28:39 +0800 Subject: [PATCH 114/225] test(lua): assign equal named fields after saving both sides Equal-length non-optional field stores save local receivers, evaluate bool, string, nil, and field reads into private slots, then write through the existing edge from right to left. --- tests/luajit_heap_runtime/candidate.rs | 99 ++++++ .../parallel_field_assign.rs | 289 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 3 files changed, 390 insertions(+) create mode 100644 tests/luajit_heap_runtime/parallel_field_assign.rs diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index aa9c234..4132b25 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1861,6 +1861,16 @@ impl Lower<'_> { } if let ([name], [value]) = (names.as_slice(), values.exprs.as_slice()) => { self.lower_local(*span, &name.name, value) } + ast::Stmt::Assign { + span, + targets, + values, + } if targets.len() >= 2 + && targets.len() == values.exprs.len() + && targets.iter().all(plain_named_field) => + { + self.lower_parallel_named_fields(*span, targets, &values.exprs) + } ast::Stmt::Assign { span, targets, @@ -2891,6 +2901,70 @@ impl Lower<'_> { } } + /// Save each local-table receiver, evaluate every right-hand value into a + /// private slot, then write those slots from right to left through the + /// same named-field edge. One target stays on `lower_assign`. The slots + /// are not guest bindings. + fn lower_parallel_named_fields( + &mut self, + span: ast::Span, + targets: &[ast::AssignTarget], + values: &[ast::Expr], + ) -> Result<(), ParseError> { + let temp_base = self.active_temps.len(); + let mut receivers = Vec::with_capacity(targets.len()); + for target in targets { + let ast::AssignTarget::Field { + table, + name, + nav: false, + .. + } = target + else { + return Err(self.statement_unsupported(span)); + }; + let key = utf8_field(&name.bytes).map_err(|_| self.unsupported(target.span()))?; + let from = self.expr(table)?; + let from = self.index_operand_slot(from, target.span())?; + receivers.push((from, key)); + } + let mut saved = Vec::with_capacity(values.len()); + for (index, value) in values.iter().enumerate() { + if !parallel_rhs_allowed(value) { + return Err(self.unsupported(value.span())); + } + let expr = match value { + ast::Expr::Nil { .. } => Expr::Null, + other => self.expr(other)?, + }; + let slot = self.builder.alloc_local_named(&format!( + "#parallel-rhs:{}:{}", + self.stmts.len(), + index + ))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr, + line: self.line(value.span()), + }); + saved.push(slot); + } + self.active_temps.truncate(temp_base); + for (slot, (from, key)) in saved.iter().rev().zip(receivers.iter().rev()) { + let written = self.call( + SET_EDGE, + vec![ + Expr::Var(*from), + Expr::String(key.clone()), + Expr::Var(*slot), + ], + )?; + self.emit_ignored(written, self.line(span))?; + } + Ok(()) + } + fn lower_assign( &mut self, span: ast::Span, @@ -3985,6 +4059,31 @@ fn utf8_field(name: &[u8]) -> Result { String::from_utf8(name.to_vec()).map_err(|_| ()) } +/// A non-optional `name.field` whose receiver is a local name. +fn plain_named_field(target: &ast::AssignTarget) -> bool { + matches!( + target, + ast::AssignTarget::Field { + table, + nav: false, + .. + } if matches!(table.as_ref(), ast::Expr::Name { .. }) + ) +} + +/// No call. Bool, string, nil, a local, or one ordinary field read. +fn parallel_rhs_allowed(expr: &ast::Expr) -> bool { + match expr { + ast::Expr::Nil { .. } | ast::Expr::Bool { .. } | ast::Expr::String { .. } => true, + ast::Expr::Name { .. } => true, + ast::Expr::SuffixChain { base, steps, .. } => { + matches!(base.as_ref(), ast::Expr::Name { .. }) + && matches!(steps.as_slice(), [ast::Suffix::Field { nav: false, .. }]) + } + _ => false, + } +} + fn syntactic_direct_call(expr: &ast::Expr) -> bool { matches!( expr, diff --git a/tests/luajit_heap_runtime/parallel_field_assign.rs b/tests/luajit_heap_runtime/parallel_field_assign.rs new file mode 100644 index 0000000..7dde229 --- /dev/null +++ b/tests/luajit_heap_runtime/parallel_field_assign.rs @@ -0,0 +1,289 @@ +//! Equal-length parallel assignment of ordinary named fields. +//! +//! Lua text goes through the candidate SourcePlugin, Core, and the VM. +//! Each left side is a non-optional named field of a local table. Each +//! right side is a bool, string, nil, local, or ordinary field read, with +//! no call. Observation is one returned boolean from `rawequal`, so the +//! same source can be compared with stock Lua without a candidate host. + +use std::sync::Arc; + +use vm::{ + CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, ParseError, + SourceFlavor, SourcePlugin, Value, VmStatus, +}; + +use super::candidate; + +struct Plugin; + +impl SourcePlugin for Plugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, super::catalog()) + } +} + +fn bool_result(source: &str) -> bool { + let catalog = Arc::clone(super::catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let mut vm = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .unwrap_or_else(|error| panic!("lower Lua text: {error}")) + .into_vm() + .unwrap_or_else(|error| panic!("vm: {error}")); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate hosts"); + super::register_witnesses(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind hosts"); + let status = vm.run().unwrap_or_else(|error| panic!("run: {error}")); + assert_eq!(status, VmStatus::Halted); + match vm.stack() { + [Value::Bool(value)] => *value, + other => panic!("expected one bool, got {other:?}"), + } +} + +/// Two named fields exchange string values read from those same fields. +#[test] +fn named_fields_swap_strings_before_either_write() { + assert!( + bool_result( + r#"local t = {} +t.a = "left" +t.b = "right" +t.a, t.b = t.b, t.a +return rawequal(t.a, "right") +"#, + ), + "the left field must receive the saved right string" + ); + assert!( + bool_result( + r#"local t = {} +t.a = "left" +t.b = "right" +t.a, t.b = t.b, t.a +return rawequal(t.b, "left") +"#, + ), + "the right field must receive the saved left string" + ); +} + +/// Bool fields use the same save-then-write order as strings. +#[test] +fn named_fields_swap_bools_before_either_write() { + assert!( + bool_result( + r#"local t = {} +t.a = true +t.b = false +t.a, t.b = t.b, t.a +return rawequal(t.a, false) +"#, + ), + "the left field must receive the saved false" + ); + assert!( + bool_result( + r#"local t = {} +t.a = true +t.b = false +t.a, t.b = t.b, t.a +return rawequal(t.b, true) +"#, + ), + "the right field must receive the saved true" + ); +} + +/// Literal bool and string values are stored, not only field reads. +#[test] +fn literal_bool_and_string_are_stored_on_named_fields() { + assert!(bool_result( + r#"local t = {} +t.flag = false +t.text = "old" +t.flag, t.text = true, "new" +return rawequal(t.flag, true) +"#, + )); + assert!(bool_result( + r#"local t = {} +t.flag = false +t.text = "old" +t.flag, t.text = true, "new" +return rawequal(t.text, "new") +"#, + )); +} + +/// Already issued tables move by field read. `rawequal` checks identity. +#[test] +fn field_read_moves_issued_tables_by_identity() { + assert!( + bool_result( + r#"local left = {} +local right = {} +local t = {} +t.a = left +t.b = right +t.a, t.b = t.b, t.a +return rawequal(t.a, right) +"#, + ), + "the left field must be the original right table" + ); + assert!( + bool_result( + r#"local left = {} +local right = {} +local t = {} +t.a = left +t.b = right +t.a, t.b = t.b, t.a +return rawequal(t.b, left) +"#, + ), + "the right field must be the original left table" + ); +} + +/// Two local tables are different receivers. Reusing the first would drop +/// the write to the second. +#[test] +fn distinct_local_receivers_exchange_named_fields() { + assert!(bool_result( + r#"local a = {} +local b = {} +a.x = "from-a" +b.y = "from-b" +a.x, b.y = b.y, a.x +return rawequal(a.x, "from-b") +"#, + )); + assert!(bool_result( + r#"local a = {} +local b = {} +a.x = "from-a" +b.y = "from-b" +a.x, b.y = b.y, a.x +return rawequal(b.y, "from-a") +"#, + )); +} + +/// A field read can move an already issued table onto another local. +#[test] +fn field_read_moves_an_issued_table_to_another_receiver() { + assert!( + bool_result( + r#"local payload = {} +local holder = {} +holder.src = payload +local dest = {} +dest.out, holder.src = holder.src, nil +return rawequal(dest.out, payload) +"#, + ), + "the destination must keep the original table" + ); + assert!( + bool_result( + r#"local payload = {} +local holder = {} +holder.src = payload +local dest = {} +dest.out, holder.src = holder.src, nil +return rawequal(holder.src, nil) +"#, + ), + "nil is stored only after the field read" + ); +} + +/// The right value is written first. The left value is the one that remains. +#[test] +fn repeated_field_keeps_the_left_value() { + assert!( + bool_result( + r#"local t = {} +t.a = "init" +t.a, t.a = "left", "right" +return rawequal(t.a, "left") +"#, + ), + "reverse writes must leave the leftmost value" + ); +} + +/// The same two strings written forward leave the opposite value, so the +/// repeated-field result is not just the last source value. +#[test] +fn forward_writes_of_the_same_strings_keep_the_right_value() { + assert!( + bool_result( + r#"local t = {} +t.a = "init" +t.a = "left" +t.a = "right" +return rawequal(t.a, "right") +"#, + ), + "explicit forward writes must be observable as the opposite result" + ); +} + +/// `nil` is applied after every right-hand read. An unwritten field stays. +#[test] +fn nil_clear_uses_values_read_before_any_write() { + assert!( + bool_result( + r#"local t = {} +t.keep = "stay" +t.src = "old" +t.dst = "other" +t.src, t.dst = nil, t.src +return rawequal(t.dst, "old") +"#, + ), + "the later read must see src before nil is stored" + ); + assert!( + bool_result( + r#"local t = {} +t.keep = "stay" +t.src = "old" +t.dst = "other" +t.src, t.dst = nil, t.src +return rawequal(t.src, nil) +"#, + ), + "the saved nil must clear src" + ); + assert!( + bool_result( + r#"local t = {} +t.keep = "stay" +t.src = "old" +t.dst = "other" +t.src, t.dst = nil, t.src +return rawequal(t.keep, "stay") +"#, + ), + "a field that is not a target must keep its value" + ); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index d1efe7e..316c37b 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -10,6 +10,8 @@ mod envelope_local_root; #[path = "../../src/frontends/lua/lexer.rs"] #[allow(dead_code)] mod lexer; +#[path = "parallel_field_assign.rs"] +mod parallel_field_assign; #[path = "../../src/frontends/lua/parser.rs"] mod parser; #[path = "pending_argument.rs"] From 17a398eb971fe760dbb67282f50e7b2f54dc62a9 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 07:21:23 +0800 Subject: [PATCH 115/225] fix(lua): root parallel assignment values across a trailing call A last parenthesized no-argument static call may collect. Snapshot every receiver first, root those copies and the already-evaluated tables, then write right to left and leave the frame. Scalars and nil are not roots. --- tests/luajit_heap_runtime/candidate.rs | 209 ++++++ .../parallel_assignment_roots.rs | 695 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 3 files changed, 906 insertions(+) create mode 100644 tests/luajit_heap_runtime/parallel_assignment_roots.rs diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 4132b25..b6ae9e0 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -34,6 +34,7 @@ const ENTER_RESULT: &str = "lua_internal::enter_result_frame"; const ENTER_CALLEE: &str = "lua_internal::enter_callee_frame"; const ENTER_PENDING: &str = "lua_internal::enter_pending_frame"; const WRITE_PENDING: &str = "lua_internal::write_pending_root"; +const WRITE_OPTIONAL_PENDING: &str = "lua_internal::write_optional_pending_root"; const LEAVE_PENDING: &str = "lua_internal::leave_pending_frame"; const ROOT_ISSUED: &str = "lua_internal::root_issued"; const SET_EDGE: &str = "lua_internal::set_edge"; @@ -174,6 +175,11 @@ pub(super) fn install_schemas(builder: &mut HostApiBuilder) { vec!["frame", "slot", "value"], HostTypeSchema::Float, ), + ( + WRITE_OPTIONAL_PENDING, + vec!["frame", "slot", "value"], + HostTypeSchema::Float, + ), (LEAVE_PENDING, vec!["frame"], HostTypeSchema::Float), ( ROOT_ISSUED, @@ -241,6 +247,7 @@ pub(super) fn register( Op::EnterCallee, Op::EnterPending, Op::WritePending, + Op::WriteOptionalPending, Op::LeavePending, Op::RootIssued, Op::SetEdge, @@ -281,6 +288,7 @@ pub(super) fn register( Op::EnterCallee => ENTER_CALLEE, Op::EnterPending => ENTER_PENDING, Op::WritePending => WRITE_PENDING, + Op::WriteOptionalPending => WRITE_OPTIONAL_PENDING, Op::LeavePending => LEAVE_PENDING, Op::RootIssued => ROOT_ISSUED, Op::SetEdge => SET_EDGE, @@ -331,6 +339,7 @@ enum Op { EnterCallee, EnterPending, WritePending, + WriteOptionalPending, LeavePending, RootIssued, SetEdge, @@ -541,6 +550,7 @@ impl HostOwnedFunction for Op { Self::EnterCallee => enter_callee(call)?, Self::EnterPending => enter_pending(call)?, Self::WritePending => write_pending(call)?, + Self::WriteOptionalPending => write_optional_pending(call)?, Self::LeavePending => leave_pending(call)?, Self::RootIssued => root_issued(call)?, Self::SetEdge => set_edge(call)?, @@ -834,6 +844,63 @@ fn write_pending(call: &mut OwnedHostCall<'_>) -> Result { Ok(Value::Float(0.0)) } +/// Candidate-private root write. Tables use the same frame check and +/// `write_root` as `WRITE_PENDING`. Legal scalars, nil, bytes, and callables +/// leave the slot empty and do not abort the later call. Forged, stale, and +/// other unissued values still reject, and that rejection drops the frame. +fn write_optional_pending(call: &mut OwnedHostCall<'_>) -> Result { + let (frame_token, slot, value) = match call.args() { + [frame, slot, value] => (frame.clone(), float_u32(slot)?, value.clone()), + _ => return Err(host_fault("invalid pending root")), + }; + let table = match optional_pending_table(call, &value) { + Ok(Some(table)) => table, + Ok(None) => return Ok(Value::Float(0.0)), + Err(error) => { + abandon_pending(call, &frame_token); + return Err(error); + } + }; + let frame = decode_frame(call, &frame_token)?; + if let Err(error) = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.write_root(frame, slot, table) + }) { + let _ = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(frame) + }); + return Err(heap_error(error)); + } + Ok(Value::Float(0.0)) +} + +fn optional_pending_table( + call: &mut OwnedHostCall<'_>, + value: &Value, +) -> Result, VmError> { + if matches!(value, Value::Null | Value::Bytes(_)) { + return Ok(None); + } + match classify(&mut call.vm().host_context(), value)? { + heap::GuestClass::Table(table) => Ok(Some(table)), + heap::GuestClass::Number | heap::GuestClass::Boolean | heap::GuestClass::String => Ok(None), + heap::GuestClass::Unissued => { + if matches!(value, Value::Callable(_)) { + Ok(None) + } else { + Err(host_fault("invalid private Lua root candidate")) + } + } + } +} + +fn abandon_pending(call: &mut OwnedHostCall<'_>, token: &Value) { + if let Ok(frame) = decode_frame(call, token) { + let _ = heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(frame) + }); + } +} + fn leave_pending(call: &mut OwnedHostCall<'_>) -> Result { let frame_token = match call.args() { [frame] => frame.clone(), @@ -2905,12 +2972,21 @@ impl Lower<'_> { /// private slot, then write those slots from right to left through the /// same named-field edge. One target stays on `lower_assign`. The slots /// are not guest bindings. + /// + /// The only call accepted here is a last value wrapped in at least one + /// pair of parentheses and naming a no-argument static Lua function. + /// That shape copies every receiver before the call, then keeps those + /// copies and the already-evaluated values in one pending frame until + /// the right-to-left writes finish. Scalars and nil are not roots. fn lower_parallel_named_fields( &mut self, span: ast::Span, targets: &[ast::AssignTarget], values: &[ast::Expr], ) -> Result<(), ParseError> { + if self.trailing_parenthesized_direct_call(values) { + return self.lower_parallel_named_call(span, targets, values); + } let temp_base = self.active_temps.len(); let mut receivers = Vec::with_capacity(targets.len()); for target in targets { @@ -2965,6 +3041,139 @@ impl Lower<'_> { Ok(()) } + fn trailing_parenthesized_direct_call(&self, values: &[ast::Expr]) -> bool { + let Some(last) = values.last() else { + return false; + }; + matches!(last, ast::Expr::Paren { .. }) + && self.direct_function_call(skip_parens(last)).is_some() + } + + /// Receivers are copied before any right-hand value. The pending frame + /// stays open across the call and the reverse writes, then leaves once. + fn lower_parallel_named_call( + &mut self, + span: ast::Span, + targets: &[ast::AssignTarget], + values: &[ast::Expr], + ) -> Result<(), ParseError> { + let Some(last) = values.last() else { + return Err(self.statement_unsupported(span)); + }; + if self.in_function { + return Err(self.unsupported(last.span())); + } + let temp_base = self.active_temps.len(); + let mut receivers = Vec::with_capacity(targets.len()); + for target in targets { + let ast::AssignTarget::Field { + table, + name, + nav: false, + .. + } = target + else { + return Err(self.statement_unsupported(span)); + }; + let key = utf8_field(&name.bytes).map_err(|_| self.unsupported(target.span()))?; + let from = self.expr(table)?; + let from = self.snapshot_private(from, target.span(), "parallel-recv")?; + receivers.push((from, key)); + } + let mut saved = Vec::with_capacity(values.len()); + for value in values.iter().take(values.len() - 1) { + if !parallel_rhs_allowed(value) { + return Err(self.unsupported(value.span())); + } + let expr = if matches!(value, ast::Expr::Nil { .. }) { + Expr::Null + } else { + self.expr(value)? + }; + saved.push(self.snapshot_private(expr, value.span(), "parallel-rhs")?); + } + self.active_temps.truncate(temp_base); + let mut rooted = Vec::with_capacity(receivers.len() + saved.len()); + for (slot, _) in &receivers { + rooted.push(*slot); + } + rooted.extend(saved.iter().copied()); + let frame = self.open_optional_pending(&rooted, span)?; + let call = self.lower_direct_value(skip_parens(last))?; + let call_slot = match call { + Expr::Var(slot) => slot, + other => self.snapshot_private(other, last.span(), "parallel-rhs")?, + }; + saved.push(call_slot); + if saved.len() != receivers.len() { + return Err(self.statement_unsupported(span)); + } + for (slot, (from, key)) in saved.iter().rev().zip(receivers.iter().rev()) { + let written = self.call( + SET_EDGE, + vec![ + Expr::Var(*from), + Expr::String(key.clone()), + Expr::Var(*slot), + ], + )?; + self.emit_ignored(written, self.line(span))?; + } + let leave = self.call(LEAVE_PENDING, vec![Expr::Var(frame)])?; + self.emit_ignored(leave, self.line(span))?; + Ok(()) + } + + fn snapshot_private( + &mut self, + expr: Expr, + span: ast::Span, + label: &str, + ) -> Result { + let slot = self + .builder + .alloc_local_named(&format!("#{label}:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr, + line: self.line(span), + }); + Ok(slot) + } + + fn open_optional_pending( + &mut self, + slots: &[LocalSlot], + span: ast::Span, + ) -> Result { + if slots.is_empty() { + return Err(self.statement_unsupported(span)); + } + let frame = self + .builder + .alloc_local_named(&format!("#optional-pending:{}", self.stmts.len()))?; + let entered = self.call(ENTER_PENDING, vec![Expr::Float(slots.len() as f64)])?; + self.stmts.push(Stmt::Let { + index: frame, + declared_schema: None, + expr: entered, + line: self.line(span), + }); + for (slot, source) in slots.iter().enumerate() { + let written = self.call( + WRITE_OPTIONAL_PENDING, + vec![ + Expr::Var(frame), + Expr::Float(slot as f64), + Expr::Var(*source), + ], + )?; + self.emit_ignored(written, self.line(span))?; + } + Ok(frame) + } + fn lower_assign( &mut self, span: ast::Span, diff --git a/tests/luajit_heap_runtime/parallel_assignment_roots.rs b/tests/luajit_heap_runtime/parallel_assignment_roots.rs new file mode 100644 index 0000000..1498ef4 --- /dev/null +++ b/tests/luajit_heap_runtime/parallel_assignment_roots.rs @@ -0,0 +1,695 @@ +//! Equal named-field assignment whose last value is a parenthesized static call. +//! +//! Lua text goes through the candidate SourcePlugin, Core, and the VM. +//! Parentheses keep one result. A function still cannot return a boolean or +//! string through the existing pass-through; those literals are written as +//! earlier values. The collect witness stores identities, not carriers. + +use std::sync::{Arc, OnceLock}; + +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + HostFunctionRegistry, HostImportSchema, HostOwnedFunction, HostParamPassing, HostParamSchema, + HostTypeSchema, OwnedHostCall, ParseError, SourceFlavor, SourcePlugin, Value, VmError, + VmStatus, +}; + +use super::ObservedTable; +use super::candidate; +use super::heap; + +const PEEK: &str = "lua_host::peek"; +const SNAP: &str = "lua_host::snap"; +const NOTE: &str = "lua_host::note"; +const EDGE: &str = "lua_host::edge"; + +#[derive(Clone, Debug, Default)] +struct Obs { + peeked: Vec, + snaps: Vec, + notes: Vec<(f64, String)>, + edges: Vec>, +} + +#[derive(Clone, Debug, PartialEq)] +struct Snap { + tag: f64, + live_roots: u32, + root_slots: u32, + collections: u32, + resources: usize, + root_slot_visits: u64, + peeked_alive: Vec, + token_open: Vec, +} + +struct Plugin; + +impl SourcePlugin for Plugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, catalog()) + } +} + +fn catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(vm::HostFunctionSchema::with_return( + PEEK, + vec![HostParamSchema::with_passing( + "table", + table.clone(), + HostParamPassing::Borrow, + )], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + SNAP, + vec![HostParamSchema::value("tag", HostTypeSchema::Float)], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + NOTE, + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("text", HostTypeSchema::String), + ], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + EDGE, + vec![ + HostParamSchema::with_passing("table", table, HostParamPassing::Borrow), + HostParamSchema::value("key", HostTypeSchema::String), + ], + HostTypeSchema::Bool, + )); + Arc::new(builder.build().unwrap()) + }) +} + +#[derive(Clone, Copy)] +enum HostOp { + Peek, + Snap, + Note, + Edge, +} + +impl HostOwnedFunction for HostOp { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let args = call.args().to_vec(); + let mut host = call.vm().host_context(); + let value = match self { + Self::Peek => { + let observed = borrowed_table(&mut host, &args[0])?; + let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(observed.table))) + .map_err(|error| VmError::HostError(error.to_string()))?; + note(&mut host, |state| state.peeked.push(observed))?; + Value::Bool(alive) + } + Self::Snap => { + let [Value::Float(tag)] = args.as_slice() else { + return Err(host_fault("expected snap tag")); + }; + let tag = *tag; + let peeked = host + .scope_state::() + .map(|state| state.peeked.clone()) + .unwrap_or_default(); + let (stats, visits) = heap::with_heap(&mut host, |heap| { + Ok((heap.stats(), heap.take_scan_meter().root_slot_visits)) + }) + .map_err(|error| VmError::HostError(error.to_string()))?; + let key = heap::LuaTableResource::key(); + let mut peeked_alive = Vec::with_capacity(peeked.len()); + let mut token_open = Vec::with_capacity(peeked.len()); + for item in &peeked { + let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(item.table))) + .unwrap_or(false); + let open = host + .borrow_resource_with_key::(item.token, &key) + .is_ok(); + peeked_alive.push(alive); + token_open.push(open); + } + let resources = host.resource_count(); + note(&mut host, |state| { + state.snaps.push(Snap { + tag, + live_roots: stats.live_roots, + root_slots: stats.root_slots, + collections: stats.collections, + resources, + root_slot_visits: visits, + peeked_alive, + token_open, + }); + })?; + Value::Bool(true) + } + Self::Note => { + let [Value::Float(tag), Value::String(text)] = args.as_slice() else { + return Err(host_fault("expected note")); + }; + let noted = (*tag, text.to_string()); + note(&mut host, |state| state.notes.push(noted))?; + Value::Bool(true) + } + Self::Edge => { + let observed = borrowed_table(&mut host, &args[0])?; + let Some(Value::String(key)) = args.get(1) else { + return Err(host_fault("expected edge key")); + }; + let found = heap::with_heap(&mut host, |heap| heap.named_edge(observed.table, key)) + .map_err(|error| VmError::HostError(error.to_string()))?; + note(&mut host, |state| state.edges.push(found))?; + Value::Bool(found.is_some()) + } + }; + Ok(CallOutcome::Return(CallReturn::one(value))) + } +} + +fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + for (name, op) in [ + (PEEK, HostOp::Peek), + (SNAP, HostOp::Snap), + (NOTE, HostOp::Note), + (EDGE, HostOp::Edge), + ] { + let function = catalog.function(name).expect("assignment root host schema"); + registry + .register_exact_owned( + name, + function.params.len() as u8, + HostImportSchema::from_function(catalog, function), + move |_| Box::new(op), + ) + .expect("register assignment root host"); + } +} + +fn note(host: &mut vm::HostContext<'_>, body: impl FnOnce(&mut Obs) -> T) -> Result { + let state = host + .scope_state_or_insert_with(Obs::default) + .map_err(|error| VmError::HostError(error.to_string()))?; + Ok(body(state)) +} + +fn borrowed_table(host: &mut vm::HostContext<'_>, value: &Value) -> Result { + let Value::Int(raw) = value else { + return Err(host_fault("expected table token")); + }; + let token = vm::ResourceHandle::from_raw( + u64::try_from(*raw).map_err(|_| host_fault("table token out of range"))?, + ) + .map_err(|_| host_fault("table token out of range"))?; + let key = heap::LuaTableResource::key(); + let table = host + .borrow_resource_with_key::(token, &key) + .map_err(|error| VmError::HostError(error.to_string()))? + .table(); + Ok(ObservedTable { table, token }) +} + +fn host_fault(message: &str) -> VmError { + VmError::HostError(message.to_string()) +} + +struct Ran { + status: Result, + stack: Vec, + obs: Obs, + resources: usize, + visits: Vec, +} + +fn run_source(source: &str) -> Ran { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .unwrap_or_else(|error| panic!("compile rejected the source: {error}")); + let mut vm = prepared.into_vm().expect("create VM"); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind runtime"); + vm.host_context() + .scope_state_or_insert_with(candidate::VisitSamples::default) + .expect("visit samples"); + let status = vm.run().map_err(|error| error.to_string()); + let obs = vm + .host_context() + .scope_state::() + .cloned() + .unwrap_or_default(); + let resources = vm.host_context().resource_count(); + let visits = vm + .host_context() + .scope_state::() + .map(|samples| samples.visits.clone()) + .unwrap_or_default(); + let stack = vm.stack().to_vec(); + Ran { + status, + stack, + obs, + resources, + visits, + } +} + +fn snap<'a>(ran: &'a Ran, tag: f64) -> &'a Snap { + ran.obs + .snaps + .iter() + .find(|snap| snap.tag == tag) + .unwrap_or_else(|| panic!("missing snap {tag}: {:?}", ran.obs.snaps)) +} + +fn bool_chunk(source: &str) -> Vec { + let mut vm = + super::try_candidate(source).unwrap_or_else(|error| panic!("lower Lua text: {error}")); + assert_eq!(vm.run().unwrap(), VmStatus::Halted); + vm.stack().to_vec() +} + +#[test] +fn trailing_parenthesized_call_keeps_the_saved_left_value() { + let stack = bool_chunk( + r#"local function sweep() + local made = {} + return made +end +local t = {} +local marker = {} +t.a, t.a = marker, (sweep()) +return rawequal(t.a, marker) +"#, + ); + assert_eq!(stack, vec![Value::Bool(true)]); +} + +#[test] +fn double_parentheses_still_keep_one_call_result() { + let stack = bool_chunk( + r#"local function sweep() + local made = {} + return made +end +local t = {} +local u = {} +t.a, u.b = "left", ((sweep())) +return type(u.b) +"#, + ); + assert_eq!(stack, vec![Value::string("table")]); +} + +#[test] +fn call_shape_stores_string_and_boolean_literals() { + let stack = bool_chunk( + r#"local function sweep() + return nil +end +local t = {} +local u = {} +t.a, u.b = "kept", (sweep()) +t.c, u.d = true, (sweep()) +return rawequal(t.a, "kept") +"#, + ); + assert_eq!(stack, vec![Value::Bool(true)]); + let flag = bool_chunk( + r#"local function sweep() + return nil +end +local t = {} +t.c, t.d = true, (sweep()) +return rawequal(t.c, true) +"#, + ); + assert_eq!(flag, vec![Value::Bool(true)]); +} + +#[test] +fn nil_before_the_call_does_not_block_the_result() { + let stack = bool_chunk( + r#"local function sweep() + local made = {} + return made +end +local t = {} +local u = {} +t.a, u.b = nil, (sweep()) +return type(u.b) +"#, + ); + assert_eq!(stack, vec![Value::string("table")]); +} + +#[test] +fn function_boolean_return_is_not_a_pass_through_value() { + let mut vm = super::try_candidate( + r#"local function sweep() + local flag = false + return flag +end +local t = {} +t.a, t.b = true, (sweep()) +return rawequal(t.b, false) +"#, + ) + .unwrap_or_else(|error| panic!("lower Lua text: {error}")); + let error = vm.run().expect_err("bool return is not pass-through"); + assert!( + error + .to_string() + .contains("return element is not a pass-through value"), + "{error}" + ); +} + +#[test] +fn function_string_return_is_not_a_pass_through_value() { + let mut vm = super::try_candidate( + r#"local function sweep() + local text = "swept" + return text +end +local t = {} +t.a, t.b = "left", (sweep()) +return rawequal(t.b, "swept") +"#, + ) + .unwrap_or_else(|error| panic!("lower Lua text: {error}")); + let error = vm.run().expect_err("string return is not pass-through"); + assert!( + error + .to_string() + .contains("return element is not a pass-through value"), + "{error}" + ); +} + +#[test] +fn unparenthesized_call_stays_unlowered() { + let error = match super::try_candidate( + r#"local function sweep() + return nil +end +local t = {} +local u = {} +t.a, u.b = true, sweep() +return true +"#, + ) { + Err(error) => error, + Ok(_) => panic!("bare call is outside this slice"), + }; + assert!(error.contains("Lua expression not lowered yet"), "{error}"); +} + +#[test] +fn call_in_an_earlier_value_stays_unlowered() { + let error = match super::try_candidate( + r#"local function sweep() + return nil +end +local t = {} +local u = {} +t.a, u.b = (sweep()), true +return true +"#, + ) { + Err(error) => error, + Ok(_) => panic!("only the last value may call"), + }; + assert!(error.contains("Lua expression not lowered yet"), "{error}"); +} + +#[test] +fn no_call_assignment_does_not_open_a_root_frame() { + let ran = run_source( + r#"local t = {} +snap(1) +t.a, t.b = true, "x" +snap(2) +return rawequal(t.a, true) +"#, + ); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + assert_eq!(ran.stack, vec![Value::Bool(true)]); + let before = snap(&ran, 1.0); + let after = snap(&ran, 2.0); + assert_eq!(before.root_slots, after.root_slots); + assert_eq!(before.collections, 0); + assert_eq!(after.collections, 0); + assert!(ran.visits.is_empty()); +} + +fn seeded(call: &str, early: &str) -> String { + format!( + r#"local function seed() + local weak = {{}} + local mode = {{}} + mode.__mode = "v" + setmetatable(weak, mode) + local target = {{}} + target.self = target + rawset(weak, 1, target) + local orphan = {{}} + orphan.self = orphan + rawset(weak, 2, orphan) + return weak +end +local weak = seed() +local dest = {{}} +local other = {{}} +local early = {early} +local lost = rawget(weak, 2) +local function sweep() + collectgarbage("collect") + snap(2) + return nil +end +peek(early) +peek(lost) +snap(1) +dest.kept, dest.kept, other.mid, other.flag = early, nil, true, {call} +snap(3) +note(1, type(dest.kept)) +note(2, type(other.mid)) +note(3, type(other.flag)) +note(4, type(rawget(weak, 2))) +edge(dest, "kept") +early = nil +lost = nil +dest.kept = nil +collectgarbage("collect") +snap(4) +note(5, type(rawget(weak, 1))) +return rawequal(type(other.mid), "boolean") +"# + ) +} + +fn assert_collect_witness(ran: &Ran, early_is_target: bool) { + assert_eq!( + ran.status.as_ref().map(|_| ()), + Ok(()), + "status={:?} stack={:?} notes={:?} snaps={:?}", + ran.status, + ran.stack, + ran.obs.notes, + ran.obs.snaps + ); + assert_eq!(ran.stack, vec![Value::Bool(true)]); + let target = ran.obs.peeked[0]; + let orphan = ran.obs.peeked[1]; + assert_ne!(target.table, orphan.table); + let before = snap(ran, 1.0); + let during = snap(ran, 2.0); + let written = snap(ran, 3.0); + let cleared = snap(ran, 4.0); + assert_eq!(before.collections, 0); + assert_eq!(during.collections, 1, "the call collected"); + assert_eq!( + written.root_slots, before.root_slots, + "leave restores the frame width after the reverse writes" + ); + assert_eq!(written.live_roots, before.live_roots); + assert!( + during.root_slots > before.root_slots, + "pending frame is open at the safepoint" + ); + assert_eq!( + during.root_slots - before.root_slots, + 7, + "four receivers plus three already-evaluated values" + ); + assert_eq!(during.peeked_alive[1], false, "orphan has no root"); + assert_eq!(during.token_open[1], false, "orphan token closed"); + assert!( + during.resources < before.resources, + "orphan resource collected" + ); + assert_eq!(ran.obs.notes[1], (2.0, "boolean".to_string())); + assert_eq!(ran.obs.notes[2], (3.0, "nil".to_string())); + assert_eq!(ran.obs.notes[3], (4.0, "nil".to_string())); + if early_is_target { + assert_eq!( + during.peeked_alive[0], true, + "early RHS root kept the target" + ); + assert_eq!(during.token_open[0], true); + assert_eq!( + during.live_roots - before.live_roots, + 5, + "four receiver slots and the target; nil and true are not roots" + ); + assert_eq!(ran.obs.notes[0], (1.0, "table".to_string())); + assert_eq!(ran.obs.edges, vec![Some(target.table)]); + assert_eq!(written.peeked_alive[0], true); + assert_eq!( + cleared.peeked_alive[0], false, + "cleared edge lets the target die" + ); + assert_eq!(cleared.token_open[0], false); + assert!(cleared.resources < written.resources); + assert_eq!(ran.obs.notes[4], (5.0, "nil".to_string())); + assert_eq!(cleared.collections, 2); + assert_eq!(ran.resources, cleared.resources); + } + assert_eq!(ran.visits.len(), 2, "two real collects"); + assert_ne!(ran.visits[0], during.root_slots as u64); + assert_ne!(ran.visits[0], during.live_roots as u64); + assert!(ran.visits[0] > 0); +} + +#[test] +fn parenthesized_sweep_keeps_only_the_extracted_rhs() { + let ran = run_source(&seeded("(sweep())", "rawget(weak, 1)")); + assert_collect_witness(&ran, true); +} + +#[test] +fn double_parenthesized_sweep_keeps_the_same_identity() { + let ran = run_source(&seeded("((sweep()))", "rawget(weak, 1)")); + assert_collect_witness(&ran, true); +} + +#[test] +fn string_before_a_double_call_does_not_block_collection() { + let source = seeded("((sweep()))", "rawget(weak, 1)") + .replace("nil, true, ((sweep()))", "nil, \"keep\", ((sweep()))"); + let ran = run_source(&source); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + let during = snap(&ran, 2.0); + assert_eq!(during.collections, 1); + assert_eq!(during.peeked_alive, vec![true, false]); + assert_eq!(ran.obs.notes[1], (2.0, "string".to_string())); +} + +#[test] +fn sweep_without_collection_leaves_the_orphan() { + let source = r#"local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local target = {} + target.self = target + rawset(weak, 1, target) + local orphan = {} + orphan.self = orphan + rawset(weak, 2, orphan) + return weak +end +local weak = seed() +local dest = {} +local other = {} +local early = rawget(weak, 1) +local lost = rawget(weak, 2) +local function sweep() + snap(2) + return nil +end +peek(early) +peek(lost) +snap(1) +dest.kept, other.flag = early, (sweep()) +snap(3) +return rawequal(dest.kept, rawget(weak, 1)) +"#; + let ran = run_source(source); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + assert_eq!(ran.stack, vec![Value::Bool(true)]); + let during = snap(&ran, 2.0); + assert_eq!(during.collections, 0); + assert_eq!(during.peeked_alive, vec![true, true]); + assert_eq!(snap(&ran, 3.0).root_slots, snap(&ran, 1.0).root_slots); + assert!(ran.visits.is_empty()); +} + +#[test] +fn dropping_the_early_rhs_lets_the_target_die() { + let source = r#"local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local target = {} + target.self = target + rawset(weak, 1, target) + local orphan = {} + orphan.self = orphan + rawset(weak, 2, orphan) + return weak +end +local weak = seed() +local dest = {} +local other = {} +local early = rawget(weak, 1) +local lost = rawget(weak, 2) +local function sweep() + collectgarbage("collect") + snap(2) + return nil +end +peek(early) +peek(lost) +snap(1) +dest.kept, other.flag = nil, (sweep()) +snap(3) +note(1, type(rawget(weak, 1))) +return true +"#; + let ran = run_source(source); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + let during = snap(&ran, 2.0); + assert_eq!(during.collections, 1); + assert_eq!(during.peeked_alive, vec![false, false]); + assert_eq!(during.token_open, vec![false, false]); + assert!(during.resources < snap(&ran, 1.0).resources); + assert_eq!(ran.obs.notes, vec![(1.0, "nil".to_string())]); + assert_eq!(snap(&ran, 3.0).root_slots, snap(&ran, 1.0).root_slots); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 316c37b..7f974ae 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -10,6 +10,8 @@ mod envelope_local_root; #[path = "../../src/frontends/lua/lexer.rs"] #[allow(dead_code)] mod lexer; +#[path = "parallel_assignment_roots.rs"] +mod parallel_assignment_roots; #[path = "parallel_field_assign.rs"] mod parallel_field_assign; #[path = "../../src/frontends/lua/parser.rs"] From 22c0109e809749f448447d26fc6503fd596e2797 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 07:26:16 +0800 Subject: [PATCH 116/225] test(lua): satisfy assignment-root clippy denies Elide the snap lifetime and compare booleans with assert. --- .../parallel_assignment_roots.rs | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/tests/luajit_heap_runtime/parallel_assignment_roots.rs b/tests/luajit_heap_runtime/parallel_assignment_roots.rs index 1498ef4..cc93d45 100644 --- a/tests/luajit_heap_runtime/parallel_assignment_roots.rs +++ b/tests/luajit_heap_runtime/parallel_assignment_roots.rs @@ -277,7 +277,7 @@ fn run_source(source: &str) -> Ran { } } -fn snap<'a>(ran: &'a Ran, tag: f64) -> &'a Snap { +fn snap(ran: &Ran, tag: f64) -> &Snap { ran.obs .snaps .iter() @@ -546,8 +546,8 @@ fn assert_collect_witness(ran: &Ran, early_is_target: bool) { 7, "four receivers plus three already-evaluated values" ); - assert_eq!(during.peeked_alive[1], false, "orphan has no root"); - assert_eq!(during.token_open[1], false, "orphan token closed"); + assert!(!during.peeked_alive[1], "orphan has no root"); + assert!(!during.token_open[1], "orphan token closed"); assert!( during.resources < before.resources, "orphan resource collected" @@ -556,11 +556,8 @@ fn assert_collect_witness(ran: &Ran, early_is_target: bool) { assert_eq!(ran.obs.notes[2], (3.0, "nil".to_string())); assert_eq!(ran.obs.notes[3], (4.0, "nil".to_string())); if early_is_target { - assert_eq!( - during.peeked_alive[0], true, - "early RHS root kept the target" - ); - assert_eq!(during.token_open[0], true); + assert!(during.peeked_alive[0], "early RHS root kept the target"); + assert!(during.token_open[0]); assert_eq!( during.live_roots - before.live_roots, 5, @@ -568,12 +565,9 @@ fn assert_collect_witness(ran: &Ran, early_is_target: bool) { ); assert_eq!(ran.obs.notes[0], (1.0, "table".to_string())); assert_eq!(ran.obs.edges, vec![Some(target.table)]); - assert_eq!(written.peeked_alive[0], true); - assert_eq!( - cleared.peeked_alive[0], false, - "cleared edge lets the target die" - ); - assert_eq!(cleared.token_open[0], false); + assert!(written.peeked_alive[0]); + assert!(!cleared.peeked_alive[0], "cleared edge lets the target die"); + assert!(!cleared.token_open[0]); assert!(cleared.resources < written.resources); assert_eq!(ran.obs.notes[4], (5.0, "nil".to_string())); assert_eq!(cleared.collections, 2); From 6d4afe6a47150f081cf3d7ca57c96fa4a86ffbc8 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 07:45:32 +0800 Subject: [PATCH 117/225] feat(lua/heap): delete one named field during a published sweep tail Remove one ordinary UTF-8 record from a live marked table while the saved tail stays in Release or Roots. The ordinary setter and clear_edge still refuse. --- src/frontends/lua/heap.rs | 23 + src/frontends/lua/heap/table.rs | 106 +++ tests/luajit_heap_runtime/published_delete.rs | 698 ++++++++++++++++++ 3 files changed, 827 insertions(+) create mode 100644 tests/luajit_heap_runtime/published_delete.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index a19bfdd..61be574 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -264,6 +264,29 @@ fn resume_published_sweep( } } +/// Deletes one ordinary UTF-8 named field while this scope's published sweep +/// tail is saved. Does not install a heap and does not resume the tail. +/// +/// No installed heap is [`HeapError::SweepDenied`]. The installed domain is +/// checked before any other handle or tail result, so a foreign receiver is +/// [`HeapError::WrongDomain`] even when no tail is saved. A same-domain stale +/// or wrong-kind receiver still uses that handle error. No saved tail, after +/// those checks, is [`HeapError::SweepDenied`]. This is not a guest +/// `collectgarbage` step. +fn delete_published_named( + host: &mut HostContext, + table: TableRef, + name: &str, +) -> Result { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + if table.domain() != heap.domain() { + return Err(HeapError::WrongDomain); + } + with_heap(host, |heap| heap.delete_published_named(table, name)) +} + /// One host call: a fresh mark, the existing synchronous token close, then /// one sweep. The observer is lent only at the published boundary and does /// not receive the host. A parked mark is refused and left in place. This is diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 7555d57..28d257c 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -700,6 +700,14 @@ pub(super) enum TailResume { Completed(CollectReport), } +/// Classification of one located named record. Not a heap error. +enum PublishedName { + Gap, + Internal, + Scalar, + Table(u32, u32), +} + impl LuaHeap { /// Reserved direct field id for `__mode`; ordinary field ids start at 1. pub const MODE_FIELD: u32 = 0; @@ -1183,6 +1191,96 @@ impl LuaHeap { } } + /// Removes one ordinary UTF-8 field while a sweep tail is saved. + /// + /// [`Self::require_live`] runs before the tail check, so a stale or + /// wrong-kind receiver is not reported as a missing tail. An unmarked live + /// owner, a `__mode` name, a cursor gap, an internal closure or upvalue + /// value, and an unmarked live table target are [`HeapError::SweepPending`]. + /// A table target is checked with the same generation, kind, and mark rule + /// as the owner. Nothing is unlinked on those errors. One owner-chain walk + /// borrows `name`; it does not construct a key. [`Self::unlink_key`] is not + /// used, so its write gate stays on the ordinary delete path. A missing + /// ordinary field is `Ok(false)`. One removed record is `Ok(true)`. This + /// does not mark, resume the tail, or add a sweep count. + pub(super) fn delete_published_named( + &mut self, + from: TableRef, + name: &str, + ) -> Result { + self.require_live(from)?; + if self.sweep_tail.is_none() { + return Err(HeapError::SweepDenied); + } + if !Self::slot_marked(&self.slots[from.slot() as usize].state) { + return Err(HeapError::SweepPending); + } + if EdgeKey::is_mode_name(name) { + return Err(HeapError::SweepPending); + } + let Some((prev, index)) = self.locate_named(from.slot(), name) else { + return Ok(false); + }; + if !self.published_name_unlinks(index)? { + return Err(HeapError::SweepPending); + } + self.unlink_at(from.slot(), prev, index); + Ok(true) + } + + fn slot_marked(state: &SlotState) -> bool { + matches!(state, SlotState::Live { marked: true }) + } + + /// One borrowed-name walk. The predecessor is the argument `unlink_at` needs. + fn locate_named(&self, owner: u32, name: &str) -> Option<(Option, u32)> { + let mut prev = None; + let mut cursor = self.slots.get(owner as usize)?.edge_head; + while let Some(index) = cursor { + let record = &self.edge_slots[index as usize]; + if record + .edge + .as_ref() + .is_some_and(|edge| edge.key.matches_name(name)) + { + return Some((prev, index)); + } + prev = Some(index); + cursor = record.next; + } + None + } + + /// Whether the located record may be unlinked. A table target uses the + /// existing handle check before the mark bit. Other refusals are `Ok(false)`. + fn published_name_unlinks(&self, index: u32) -> Result { + let (utf8, value) = { + let edge = self.edge_slots[index as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + let utf8 = matches!(edge.key, EdgeKey::Utf8(_)); + let value = match &edge.value { + EdgeValue::Scalar(Value::Null) => PublishedName::Gap, + EdgeValue::Closure { .. } | EdgeValue::Upvalue { .. } => PublishedName::Internal, + EdgeValue::Table { slot, generation } => PublishedName::Table(*slot, *generation), + EdgeValue::Scalar(_) => PublishedName::Scalar, + }; + (utf8, value) + }; + if !utf8 { + return Ok(false); + } + match value { + PublishedName::Gap | PublishedName::Internal => Ok(false), + PublishedName::Scalar => Ok(true), + PublishedName::Table(slot, generation) => { + self.require_kind(self.domain, slot, generation, HandleKind::Table)?; + Ok(Self::slot_marked(&self.slots[slot as usize].state)) + } + } + } + /// True when the name constructor selects the reserved mode field. pub fn names_mode_field(name: &str) -> bool { matches!(EdgeKey::named(name), EdgeKey::Field(Self::MODE_FIELD)) @@ -1925,6 +2023,11 @@ impl LuaHeap { self.sweep_tail.is_some() } + /// Domain that issued handles for this heap. Does not read slots. + pub(super) fn domain(&self) -> u64 { + self.domain + } + /// A saved tail owns the graph. Checked after handle and capacity validation, /// and before the first write or chain walk of a commit. fn ensure_sweep_open(&self) -> Result<(), HeapError> { @@ -2501,6 +2604,9 @@ mod parked_mark; #[path = "../../../../tests/luajit_heap_runtime/private_cycle.rs"] mod private_cycle; #[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/published_delete.rs"] +mod published_delete; +#[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/published_sweep.rs"] mod published_sweep; #[cfg(test)] diff --git a/tests/luajit_heap_runtime/published_delete.rs b/tests/luajit_heap_runtime/published_delete.rs new file mode 100644 index 0000000..1c1e53e --- /dev/null +++ b/tests/luajit_heap_runtime/published_delete.rs @@ -0,0 +1,698 @@ +//! Delete one ordinary named field while a published sweep tail is saved. +//! +//! Not a guest `collectgarbage` step. The saved tail stays Release/Roots. +//! A successful delete removes one live UTF-8 record and does not mark, +//! resume, or close a token. + +use vm::Value; + +use super::{EdgeKey, EdgeValue, SlotState}; +use crate::heap::{ + self, HeapError, HeapLimits, LuaHeap, PublishedBoundary, PublishedResume, ScanMeter, TableRef, +}; + +fn limits() -> HeapLimits { + HeapLimits { + nodes: 16, + roots: 4, + edges: 24, + max_generation: 8, + } +} + +fn publish(host: &mut vm::HostContext<'_>) -> (TableRef, i64) { + let raw = crate::publish_raw(host); + (crate::table_ref(host, raw), raw) +} + +fn token_open(host: &mut vm::HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + crate::resource_handle(raw), + &heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn slot_generation(heap: &LuaHeap, table: TableRef) -> u32 { + heap.slots[table.slot() as usize].generation +} + +struct Ring { + owner: TableRef, + owner_token: i64, + weak: TableRef, + nodes: [TableRef; 3], + tokens: [i64; 3], + carriers: [Value; 3], + orphan: TableRef, + orphan_token: i64, + orphan_generation: u32, + meta: TableRef, +} + +fn build_ring(host: &mut vm::HostContext<'_>) -> Ring { + heap::install(host, limits()).expect("install"); + let meta = heap::with_heap(host, LuaHeap::alloc).expect("meta"); + let (owner, owner_token) = publish(host); + let (weak, _) = publish(host); + let (a, a_token) = publish(host); + let (b, b_token) = publish(host); + let (c, c_token) = publish(host); + let (orphan, orphan_token) = publish(host); + let (carriers, orphan_generation) = heap::with_heap(host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(weak, Some(meta))?; + heap.set_named_edge(owner, "entry", a)?; + heap.set_named_edge(a, "link", b)?; + heap.set_named_edge(b, "link", c)?; + heap.set_named_edge(c, "link", a)?; + heap.set_named_edge(orphan, "link", orphan)?; + heap.set_named_edge(weak, "o", orphan)?; + heap.set_named_edge(weak, "a", a)?; + heap.set_named_edge(weak, "b", b)?; + heap.set_named_edge(weak, "c", c)?; + let carriers = [ + heap.issue_carrier(a)?, + heap.issue_carrier(b)?, + heap.issue_carrier(c)?, + ]; + let frame = heap.enter_roots(2)?; + heap.write_root(frame, 0, owner)?; + heap.write_root(frame, 1, weak)?; + Ok((carriers, slot_generation(heap, orphan))) + }) + .expect("graph"); + Ring { + owner, + owner_token, + weak, + nodes: [a, b, c], + tokens: [a_token, b_token, c_token], + carriers, + orphan, + orphan_token, + orphan_generation, + meta, + } +} + +fn assert_ring(heap: &LuaHeap, graph: &Ring, rooted: bool) -> Result<(), HeapError> { + assert_eq!( + heap.named_edge(graph.nodes[0], "link")?, + Some(graph.nodes[1]) + ); + assert_eq!( + heap.named_edge(graph.nodes[1], "link")?, + Some(graph.nodes[2]) + ); + assert_eq!( + heap.named_edge(graph.nodes[2], "link")?, + Some(graph.nodes[0]) + ); + assert_eq!(heap.named_edge(graph.weak, "a")?, Some(graph.nodes[0])); + assert_eq!(heap.named_edge(graph.weak, "b")?, Some(graph.nodes[1])); + assert_eq!( + heap.named_edge(graph.weak, "c")?, + Some(graph.nodes[2]), + "the third weak observation keeps the original node" + ); + assert_eq!(heap.named_edge(graph.owner, "entry")?.is_some(), rooted); + if rooted { + assert_eq!(heap.named_edge(graph.owner, "entry")?, Some(graph.nodes[0])); + } + Ok(()) +} + +#[test] +fn published_delete_keeps_the_marked_ring_until_the_next_cycle() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_ring(&mut host); + let resources_before = host.resource_count(); + let _ = heap::take_scan_meter(&mut host).expect("clear meter"); + let published = heap::collect_until_published(&mut host).expect("publish"); + let PublishedBoundary::Published { + window_heads, + window_edges, + } = published + else { + panic!("publish must stop before release, got {published:?}"); + }; + assert_eq!(window_heads, 7, "one owner head per slot"); + assert_eq!(window_edges, 10, "mode, entry, four links, four weak edges"); + assert!( + !token_open(&mut host, graph.orphan_token), + "orphan token closed" + ); + assert!(token_open(&mut host, graph.tokens[0])); + assert!(token_open(&mut host, graph.tokens[1])); + assert!(token_open(&mut host, graph.tokens[2])); + assert_eq!(host.resource_count(), resources_before - 1); + heap::with_heap(&mut host, |heap| { + assert!(heap.alive(graph.orphan), "orphan slot still physical"); + assert_eq!(slot_generation(heap, graph.orphan), graph.orphan_generation); + assert!(heap.alive(graph.meta)); + assert_eq!( + heap.named_edge(graph.weak, "o")?, + None, + "weak orphan became a gap" + ); + let continued = heap + .next_guest(graph.weak, &Value::string("o"))? + .expect("gap cursor continues"); + assert_eq!(continued.0, Value::string("a")); + assert_eq!(continued.1, graph.carriers[0]); + assert_ring(heap, &graph, true)?; + Ok(()) + }) + .expect("published graph"); + let _ = heap::take_scan_meter(&mut host).expect("publish meter"); + let before = heap::stats(&mut host).expect("stats before delete"); + assert_eq!(before.collections, 0); + assert_eq!(before.live_nodes, 7); + let tail = heap::with_heap(&mut host, |heap| Ok(format!("{:?}", heap.sweep_tail))) + .expect("saved tail"); + + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "entry"), + Ok(true), + "published tail deletes the last strong edge" + ); + heap::with_heap(&mut host, |heap| { + assert_eq!( + format!("{:?}", heap.sweep_tail), + tail, + "tail progress unchanged" + ); + assert_eq!(heap.named_edge(graph.owner, "entry")?, None); + assert_ring(heap, &graph, false)?; + assert_eq!( + heap.next_guest(graph.weak, &Value::string("o"))? + .expect("gap cursor still continues") + .1, + graph.carriers[0] + ); + Ok(()) + }) + .expect("delete"); + + let after = heap::stats(&mut host).expect("stats after delete"); + assert_eq!( + before.live_edges - 1, + after.live_edges, + "only the deleted edge" + ); + assert_eq!(before.edge_slots - 1, after.edge_slots); + assert_eq!(before.live_nodes, after.live_nodes); + assert_eq!(before.live_roots, after.live_roots); + assert_eq!(before.collections, after.collections); + assert_eq!( + heap::take_scan_meter(&mut host).expect("delete meter"), + ScanMeter::default(), + "delete is not mark, Owners, or tail progress" + ); + let paused = heap::resume_published_sweep(&mut host, 0).expect("tail still saved"); + assert!(matches!(paused, PublishedResume::Paused)); + + let released = heap::resume_published_sweep(&mut host, 1).expect("release orphan"); + assert!(matches!(released, PublishedResume::Paused)); + heap::with_heap(&mut host, |heap| { + assert!( + !heap.alive(graph.orphan), + "the saved dead slot was released" + ); + assert_ne!(slot_generation(heap, graph.orphan), graph.orphan_generation); + for node in graph.nodes { + assert!(heap.alive(node), "a marked ring node is not in this tail"); + assert_eq!(slot_generation(heap, node), node.generation()); + } + Ok(()) + }) + .expect("release facts"); + for token in graph.tokens { + assert!(token_open(&mut host, token)); + } + + let mut reports = 0u32; + let mut report_nodes = 0u32; + for _ in 0..8 { + match heap::resume_published_sweep(&mut host, 1).expect("small budget") { + PublishedResume::Paused => {} + PublishedResume::Completed(report) => { + reports += 1; + report_nodes = report.live_nodes; + break; + } + } + } + assert_eq!(reports, 1, "the tail finishes once"); + assert_eq!( + report_nodes, 6, + "orphan released; the ring is still physical" + ); + assert_eq!(heap::stats(&mut host).expect("finished").collections, 1); + for token in graph.tokens { + assert!( + token_open(&mut host, token), + "same-cycle completion keeps the token" + ); + } + heap::with_heap(&mut host, |heap| { + for node in graph.nodes { + assert!(heap.alive(node)); + assert_eq!(slot_generation(heap, node), node.generation()); + } + assert_ring(heap, &graph, false)?; + Ok(()) + }) + .expect("retained ring"); + let again = heap::resume_published_sweep(&mut host, 1).expect_err("tail is gone"); + assert_eq!(again, HeapError::SweepDenied); + + let collected = heap::collect(&mut host).expect("next cycle"); + assert_eq!( + collected.live_nodes, 3, + "owner, weak observer, and mode table" + ); + assert!(!token_open(&mut host, graph.tokens[0])); + assert!(!token_open(&mut host, graph.tokens[1])); + assert!(!token_open(&mut host, graph.tokens[2])); + assert!(token_open(&mut host, graph.owner_token)); + assert_eq!(host.resource_count(), resources_before - 4); + heap::with_heap(&mut host, |heap| { + for node in graph.nodes { + assert!(!heap.alive(node), "the next cycle releases the ring"); + assert_ne!(slot_generation(heap, node), node.generation()); + } + assert_eq!(heap.named_edge(graph.weak, "a")?, None); + assert_eq!(heap.named_edge(graph.weak, "b")?, None); + assert_eq!( + heap.named_edge(graph.weak, "c")?, + None, + "three weak edges cleared" + ); + assert!(heap.alive(graph.owner)); + assert!(heap.alive(graph.weak)); + assert!(heap.alive(graph.meta)); + Ok(()) + }) + .expect("second cycle"); + }); +} + +/// One resume finishes the tail. The ring stays, and this test does not start +/// the next cycle. That is the normal-completion and omitted-followup arms. +#[test] +fn omitted_followup_after_delete_keeps_the_ring() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_ring(&mut host); + let resources_before = host.resource_count(); + let published = heap::collect_until_published(&mut host).expect("publish"); + assert!(matches!(published, PublishedBoundary::Published { .. })); + let _ = heap::take_scan_meter(&mut host); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "entry"), + Ok(true) + ); + let resumed = heap::resume_published_sweep(&mut host, 8).expect("one resume"); + let PublishedResume::Completed(report) = resumed else { + panic!("one budget finishes the saved tail, got {resumed:?}"); + }; + assert_eq!( + report.live_nodes, 6, + "one report; the ring is still physical" + ); + assert_eq!(heap::stats(&mut host).expect("finished").collections, 1); + assert_eq!(host.resource_count(), resources_before - 1); + for token in graph.tokens { + assert!( + token_open(&mut host, token), + "no followup, token stays open" + ); + } + heap::with_heap(&mut host, |heap| { + for node in graph.nodes { + assert!(heap.alive(node)); + assert_eq!(slot_generation(heap, node), node.generation()); + } + assert_ring(heap, &graph, false)?; + Ok(()) + }) + .expect("omitted followup"); + }); +} + +/// The same graph with no post-publish delete. The strong entry keeps the ring +/// through the tail and the next cycle. +#[test] +fn omitted_delete_keeps_the_ring_through_the_next_cycle() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_ring(&mut host); + let resources_before = host.resource_count(); + let published = heap::collect_until_published(&mut host).expect("publish"); + assert!(matches!(published, PublishedBoundary::Published { .. })); + let resumed = heap::resume_published_sweep(&mut host, 8).expect("finish"); + let PublishedResume::Completed(report) = resumed else { + panic!("tail finishes, got {resumed:?}"); + }; + assert_eq!(report.live_nodes, 6); + assert!(token_open(&mut host, graph.owner_token)); + for token in graph.tokens { + assert!(token_open(&mut host, token), "entry still roots the ring"); + } + let collected = heap::collect(&mut host).expect("next cycle"); + assert_eq!( + collected.live_nodes, 6, + "orphan already released; ring stays" + ); + assert_eq!(host.resource_count(), resources_before - 1); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.named_edge(graph.owner, "entry")?, Some(graph.nodes[0])); + assert_ring(heap, &graph, true)?; + for (name, node) in [("a", 0), ("b", 1), ("c", 2)] { + assert_eq!(heap.named_edge(graph.weak, name)?, Some(graph.nodes[node])); + } + Ok(()) + }) + .expect("kept ring"); + }); +} + +/// Deleting the strong entry before publish closes the ring at that boundary. +/// The slots are still physical until the tail releases them. +#[test] +fn delete_before_publish_closes_the_ring_at_the_boundary() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_ring(&mut host); + let resources_before = host.resource_count(); + heap::with_heap(&mut host, |heap| { + heap.set_named_scalar(graph.owner, "entry", Value::Null)?; + Ok(()) + }) + .expect("ordinary delete"); + let published = heap::collect_until_published(&mut host).expect("publish"); + let PublishedBoundary::Published { + window_heads, + window_edges, + } = published + else { + panic!("a weak orphan still publishes, got {published:?}"); + }; + assert_eq!(window_heads, 7); + assert_eq!(window_edges, 9, "the entry edge is already gone"); + assert!(!token_open(&mut host, graph.orphan_token)); + for token in graph.tokens { + assert!( + !token_open(&mut host, token), + "no strong entry, token closes now" + ); + } + assert_eq!(host.resource_count(), resources_before - 4); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.named_edge(graph.owner, "entry")?, None); + for node in graph.nodes { + assert!(heap.alive(node), "closed token, physical slot"); + assert_eq!(slot_generation(heap, node), node.generation()); + } + assert!(heap.alive(graph.orphan)); + for name in ["a", "b", "c", "o"] { + assert_eq!(heap.named_edge(graph.weak, name)?, None); + } + Ok(()) + }) + .expect("boundary"); + let resumed = heap::resume_published_sweep(&mut host, 8).expect("release"); + let PublishedResume::Completed(report) = resumed else { + panic!("tail finishes, got {resumed:?}"); + }; + assert_eq!(report.live_nodes, 3, "only the rooted tables stay"); + heap::with_heap(&mut host, |heap| { + for node in graph.nodes { + assert!(!heap.alive(node)); + assert_ne!(slot_generation(heap, node), node.generation()); + } + Ok(()) + }) + .expect("released"); + }); +} + +/// No installed heap, and an installed heap with no saved tail. A present +/// field is not removed. A stale or wrong-kind receiver is not SweepDenied. +#[test] +fn published_delete_rejects_before_a_tail_without_installing() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let ghost = TableRef::table(1, 0, 1); + assert_eq!( + heap::delete_published_named(&mut host, ghost, "entry"), + Err(HeapError::SweepDenied) + ); + assert_eq!( + heap::delete_published_named(&mut host, ghost, "entry"), + Err(HeapError::SweepDenied), + "the refusal does not install a heap" + ); + + let graph = build_ring(&mut host); + let stats = heap::stats(&mut host).expect("installed"); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "entry"), + Err(HeapError::SweepDenied) + ); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.named_edge(graph.owner, "entry")?, Some(graph.nodes[0])); + Ok(()) + }) + .expect("field remains"); + assert_eq!(heap::stats(&mut host).expect("unchanged"), stats); + + let stale = heap::with_heap(&mut host, |heap| { + let rolled = heap.alloc()?; + heap.rollback(rolled)?; + Ok(rolled) + }) + .expect("stale"); + assert_eq!( + heap::delete_published_named(&mut host, stale, "entry"), + Err(HeapError::StaleHandle) + ); + let closure = heap::with_heap(&mut host, |heap| heap.alloc_closure()).expect("closure"); + let forged = TableRef::table(closure.domain(), closure.slot(), closure.generation()); + assert_eq!( + heap::delete_published_named(&mut host, forged, "entry"), + Err(HeapError::WrongKind) + ); + let mut other = LuaHeap::new(limits()); + let foreign = other.alloc().expect("foreign"); + assert_eq!( + heap::delete_published_named(&mut host, foreign, "entry"), + Err(HeapError::WrongDomain) + ); + assert!(other.alive(foreign), "the other heap is not touched"); + }); +} + +/// Every refused shape leaves the saved tail, roots, and edge counts alone. +/// The ordinary setter and `clear_edge` still stop at SweepPending. `next` +/// continues from the original weak gap. +#[test] +fn published_delete_refuses_shapes_without_moving_the_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_ring(&mut host); + heap::with_heap(&mut host, |heap| { + let frame = heap.enter_roots(2)?; + let closure = heap.alloc_closure()?; + let upvalue = heap.alloc_upvalue()?; + heap.write_closure_root(frame, 0, closure)?; + heap.write_upvalue_root(frame, 1, upvalue)?; + heap.write_from( + graph.owner.slot(), + EdgeKey::named("hidden"), + EdgeValue::Closure { + slot: closure.slot(), + generation: closure.generation(), + }, + )?; + heap.write_from( + graph.owner.slot(), + EdgeKey::named("box"), + EdgeValue::Upvalue { + slot: upvalue.slot(), + generation: upvalue.generation(), + }, + )?; + heap.write_from( + graph.owner.slot(), + EdgeKey::named("kind"), + EdgeValue::Table { + slot: closure.slot(), + generation: closure.generation(), + }, + )?; + heap.write_from( + graph.owner.slot(), + EdgeKey::named("extra"), + EdgeValue::Table { + slot: graph.nodes[0].slot(), + generation: graph.nodes[0].generation(), + }, + )?; + Ok(()) + }) + .expect("plant"); + let published = heap::collect_until_published(&mut host).expect("publish"); + assert!(matches!(published, PublishedBoundary::Published { .. })); + let _ = heap::take_scan_meter(&mut host); + let before = heap::stats(&mut host).expect("before"); + let tail = + heap::with_heap(&mut host, |heap| Ok(format!("{:?}", heap.sweep_tail))).expect("tail"); + + assert_eq!( + heap::delete_published_named(&mut host, graph.orphan, "link"), + Err(HeapError::SweepPending), + "unmarked live owner" + ); + assert_eq!( + heap::delete_published_named(&mut host, graph.meta, "__mode"), + Err(HeapError::SweepPending) + ); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "__mode"), + Err(HeapError::SweepPending), + "absent mode name is not a missing ordinary field" + ); + assert_eq!( + heap::delete_published_named(&mut host, graph.weak, "o"), + Err(HeapError::SweepPending), + "cursor gap" + ); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "hidden"), + Err(HeapError::SweepPending), + "internal closure value" + ); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "box"), + Err(HeapError::SweepPending), + "internal upvalue value" + ); + heap::with_heap(&mut host, |heap| { + heap.slots[graph.nodes[0].slot() as usize].state = SlotState::Live { marked: false }; + Ok(()) + }) + .expect("poke mark"); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "entry"), + Err(HeapError::SweepPending), + "unmarked live table target" + ); + heap::with_heap(&mut host, |heap| { + heap.slots[graph.nodes[0].slot() as usize].state = SlotState::Live { marked: true }; + let (_, index) = heap + .locate_named(graph.owner.slot(), "extra") + .expect("extra"); + if let EdgeValue::Table { generation, .. } = + &mut heap.edge_slots[index as usize].edge.as_mut().unwrap().value + { + *generation = 0; + } + Ok(()) + }) + .expect("poke generation"); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "extra"), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "kind"), + Err(HeapError::WrongKind) + ); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.clear_edge(graph.owner, &EdgeKey::named("entry")), + Err(HeapError::SweepPending) + ); + assert_eq!( + heap.set_named_scalar(graph.owner, "entry", Value::Null), + Err(HeapError::SweepPending) + ); + assert_eq!(heap.named_edge(graph.owner, "entry")?, Some(graph.nodes[0])); + assert!(heap.slots[graph.meta.slot() as usize].mode_edge.is_some()); + assert!(heap.locate_named(graph.owner.slot(), "hidden").is_some()); + assert!(heap.locate_named(graph.owner.slot(), "box").is_some()); + assert!(heap.locate_named(graph.weak.slot(), "o").is_some()); + assert_eq!( + heap.named_edge(graph.owner, "extra")? + .expect("stale target edge remains") + .generation(), + 0 + ); + assert!(heap.named_edge(graph.owner, "kind")?.is_some()); + assert_eq!( + heap.next_guest(graph.weak, &Value::string("o"))? + .expect("gap cursor still continues") + .1, + graph.carriers[0] + ); + assert!(heap.alive(graph.orphan)); + assert_eq!( + slot_generation(heap, graph.orphan), + graph.orphan.generation() + ); + Ok(()) + }) + .expect("zero effect"); + assert_eq!( + heap::delete_published_named(&mut host, graph.owner, "missing"), + Ok(false) + ); + let mut other = LuaHeap::new(limits()); + let foreign = other.alloc().expect("foreign"); + assert_eq!( + heap::delete_published_named(&mut host, foreign, "entry"), + Err(HeapError::WrongDomain) + ); + assert!(other.alive(foreign)); + + assert_eq!(heap::stats(&mut host).expect("after"), before); + assert_eq!( + heap::take_scan_meter(&mut host).expect("meter"), + ScanMeter::default() + ); + heap::with_heap(&mut host, |heap| { + assert_eq!(format!("{:?}", heap.sweep_tail), tail); + Ok(()) + }) + .expect("tail unchanged"); + + assert!(matches!( + heap::resume_published_sweep(&mut host, 0).expect("zero"), + PublishedResume::Paused + )); + assert!(matches!( + heap::resume_published_sweep(&mut host, 1).expect("one release"), + PublishedResume::Paused + )); + assert!(!token_open(&mut host, graph.orphan_token)); + assert_eq!( + heap::delete_published_named(&mut host, graph.orphan, "link"), + Err(HeapError::StaleHandle), + "released handle" + ); + for token in graph.tokens { + assert!(token_open(&mut host, token)); + } + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(graph.orphan)); + assert!(heap.alive(graph.nodes[0])); + assert_eq!(heap.named_edge(graph.owner, "entry")?, Some(graph.nodes[0])); + Ok(()) + }) + .expect("only the original dead slot moved"); + }); +} From 8eacc17e787be3396441ba144f2c994685e74712 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 08:15:54 +0800 Subject: [PATCH 118/225] fix(lua): root earlier assignment calls until the last call A parallel named-field assignment can now hold a parenthesized static call in any value, more than once. One pending frame opens before the first call and publishes each value a later call can collect. --- tests/luajit_heap_runtime/candidate.rs | 120 ++++--- .../parallel_assignment_roots.rs | 331 +++++++++++++++++- 2 files changed, 397 insertions(+), 54 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index b6ae9e0..003ced0 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -2973,18 +2973,24 @@ impl Lower<'_> { /// same named-field edge. One target stays on `lower_assign`. The slots /// are not guest bindings. /// - /// The only call accepted here is a last value wrapped in at least one - /// pair of parentheses and naming a no-argument static Lua function. - /// That shape copies every receiver before the call, then keeps those - /// copies and the already-evaluated values in one pending frame until - /// the right-to-left writes finish. Scalars and nil are not roots. + /// A parenthesized no-argument static Lua function is accepted in any + /// value, including more than once. Receivers are copied first, including + /// a captured table. One pending frame opens before the first such call. + /// Its width is the receivers plus every value index before the last + /// call. Already-evaluated values, and each later value that still has a + /// call after it, are written into that frame before the next call. The + /// last call's result is not rooted. Scalars and nil are not roots. + /// Right-to-left writes then leave the frame once. fn lower_parallel_named_fields( &mut self, span: ast::Span, targets: &[ast::AssignTarget], values: &[ast::Expr], ) -> Result<(), ParseError> { - if self.trailing_parenthesized_direct_call(values) { + if values + .iter() + .any(|value| self.parenthesized_static_call(value)) + { return self.lower_parallel_named_call(span, targets, values); } let temp_base = self.active_temps.len(); @@ -3041,27 +3047,32 @@ impl Lower<'_> { Ok(()) } - fn trailing_parenthesized_direct_call(&self, values: &[ast::Expr]) -> bool { - let Some(last) = values.last() else { - return false; - }; - matches!(last, ast::Expr::Paren { .. }) - && self.direct_function_call(skip_parens(last)).is_some() + fn parenthesized_static_call(&self, expr: &ast::Expr) -> bool { + matches!(expr, ast::Expr::Paren { .. }) + && self.direct_function_call(skip_parens(expr)).is_some() } - /// Receivers are copied before any right-hand value. The pending frame - /// stays open across the call and the reverse writes, then leaves once. + /// Receivers are copied before any right-hand value. One pending frame + /// stays open from the first parenthesized static call through the + /// reverse writes, then leaves once. fn lower_parallel_named_call( &mut self, span: ast::Span, targets: &[ast::AssignTarget], values: &[ast::Expr], ) -> Result<(), ParseError> { - let Some(last) = values.last() else { + let mut call_indexes = Vec::new(); + for (index, value) in values.iter().enumerate() { + if self.parenthesized_static_call(value) { + call_indexes.push(index); + } + } + let Some(&last_call_index) = call_indexes.last() else { return Err(self.statement_unsupported(span)); }; + let first_call_index = call_indexes[0]; if self.in_function { - return Err(self.unsupported(last.span())); + return Err(self.unsupported(values[first_call_index].span())); } let temp_base = self.active_temps.len(); let mut receivers = Vec::with_capacity(targets.len()); @@ -3081,16 +3092,11 @@ impl Lower<'_> { receivers.push((from, key)); } let mut saved = Vec::with_capacity(values.len()); - for value in values.iter().take(values.len() - 1) { + for value in values.iter().take(first_call_index) { if !parallel_rhs_allowed(value) { return Err(self.unsupported(value.span())); } - let expr = if matches!(value, ast::Expr::Nil { .. }) { - Expr::Null - } else { - self.expr(value)? - }; - saved.push(self.snapshot_private(expr, value.span(), "parallel-rhs")?); + saved.push(self.save_parallel_value(value)?); } self.active_temps.truncate(temp_base); let mut rooted = Vec::with_capacity(receivers.len() + saved.len()); @@ -3098,13 +3104,25 @@ impl Lower<'_> { rooted.push(*slot); } rooted.extend(saved.iter().copied()); - let frame = self.open_optional_pending(&rooted, span)?; - let call = self.lower_direct_value(skip_parens(last))?; - let call_slot = match call { - Expr::Var(slot) => slot, - other => self.snapshot_private(other, last.span(), "parallel-rhs")?, - }; - saved.push(call_slot); + let width = receivers.len() + last_call_index; + let frame = self.open_optional_pending(&rooted, width, span)?; + for (index, value) in values.iter().enumerate().skip(first_call_index) { + let slot = if self.parenthesized_static_call(value) { + let call = self.lower_direct_value(skip_parens(value))?; + match call { + Expr::Var(slot) => slot, + other => self.snapshot_private(other, value.span(), "parallel-rhs")?, + } + } else if parallel_rhs_allowed(value) { + self.save_parallel_value(value)? + } else { + return Err(self.unsupported(value.span())); + }; + if index < last_call_index { + self.write_optional_pending(frame, receivers.len() + index, slot, value.span())?; + } + saved.push(slot); + } if saved.len() != receivers.len() { return Err(self.statement_unsupported(span)); } @@ -3124,6 +3142,33 @@ impl Lower<'_> { Ok(()) } + fn save_parallel_value(&mut self, value: &ast::Expr) -> Result { + let expr = if matches!(value, ast::Expr::Nil { .. }) { + Expr::Null + } else { + self.expr(value)? + }; + self.snapshot_private(expr, value.span(), "parallel-rhs") + } + + fn write_optional_pending( + &mut self, + frame: LocalSlot, + index: usize, + source: LocalSlot, + span: ast::Span, + ) -> Result<(), ParseError> { + let written = self.call( + WRITE_OPTIONAL_PENDING, + vec![ + Expr::Var(frame), + Expr::Float(index as f64), + Expr::Var(source), + ], + )?; + self.emit_ignored(written, self.line(span)) + } + fn snapshot_private( &mut self, expr: Expr, @@ -3145,15 +3190,16 @@ impl Lower<'_> { fn open_optional_pending( &mut self, slots: &[LocalSlot], + width: usize, span: ast::Span, ) -> Result { - if slots.is_empty() { + if slots.is_empty() || width < slots.len() { return Err(self.statement_unsupported(span)); } let frame = self .builder .alloc_local_named(&format!("#optional-pending:{}", self.stmts.len()))?; - let entered = self.call(ENTER_PENDING, vec![Expr::Float(slots.len() as f64)])?; + let entered = self.call(ENTER_PENDING, vec![Expr::Float(width as f64)])?; self.stmts.push(Stmt::Let { index: frame, declared_schema: None, @@ -3161,15 +3207,7 @@ impl Lower<'_> { line: self.line(span), }); for (slot, source) in slots.iter().enumerate() { - let written = self.call( - WRITE_OPTIONAL_PENDING, - vec![ - Expr::Var(frame), - Expr::Float(slot as f64), - Expr::Var(*source), - ], - )?; - self.emit_ignored(written, self.line(span))?; + self.write_optional_pending(frame, slot, *source, span)?; } Ok(frame) } diff --git a/tests/luajit_heap_runtime/parallel_assignment_roots.rs b/tests/luajit_heap_runtime/parallel_assignment_roots.rs index cc93d45..2f6518d 100644 --- a/tests/luajit_heap_runtime/parallel_assignment_roots.rs +++ b/tests/luajit_heap_runtime/parallel_assignment_roots.rs @@ -1,4 +1,4 @@ -//! Equal named-field assignment whose last value is a parenthesized static call. +//! Equal named-field assignment with parenthesized static calls. //! //! Lua text goes through the candidate SourcePlugin, Core, and the VM. //! Parentheses keep one result. A function still cannot return a boolean or @@ -22,6 +22,8 @@ const PEEK: &str = "lua_host::peek"; const SNAP: &str = "lua_host::snap"; const NOTE: &str = "lua_host::note"; const EDGE: &str = "lua_host::edge"; +const ARM: &str = "lua_host::arm"; +const TOUCH: &str = "lua_host::touch"; #[derive(Clone, Debug, Default)] struct Obs { @@ -29,6 +31,8 @@ struct Obs { snaps: Vec, notes: Vec<(f64, String)>, edges: Vec>, + /// Table a no-arg function can stamp. Not a heap root. + armed: Option, } #[derive(Clone, Debug, PartialEq)] @@ -94,11 +98,25 @@ fn catalog() -> &'static Arc { builder.function(vm::HostFunctionSchema::with_return( EDGE, vec![ - HostParamSchema::with_passing("table", table, HostParamPassing::Borrow), + HostParamSchema::with_passing("table", table.clone(), HostParamPassing::Borrow), HostParamSchema::value("key", HostTypeSchema::String), ], HostTypeSchema::Bool, )); + builder.function(vm::HostFunctionSchema::with_return( + ARM, + vec![HostParamSchema::with_passing( + "table", + table, + HostParamPassing::Borrow, + )], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + TOUCH, + vec![], + HostTypeSchema::Bool, + )); Arc::new(builder.build().unwrap()) }) } @@ -109,6 +127,8 @@ enum HostOp { Snap, Note, Edge, + Arm, + Touch, } impl HostOwnedFunction for HostOp { @@ -181,6 +201,22 @@ impl HostOwnedFunction for HostOp { note(&mut host, |state| state.edges.push(found))?; Value::Bool(found.is_some()) } + Self::Arm => { + let observed = borrowed_table(&mut host, &args[0])?; + note(&mut host, |state| state.armed = Some(observed.table))?; + Value::Bool(true) + } + Self::Touch => { + let armed = host + .scope_state::() + .and_then(|state| state.armed) + .ok_or_else(|| host_fault("touch without arm"))?; + heap::with_heap(&mut host, |heap| { + heap.set_named_scalar(armed, "step", Value::string("called")) + }) + .map_err(|error| VmError::HostError(error.to_string()))?; + Value::Bool(true) + } }; Ok(CallOutcome::Return(CallReturn::one(value))) } @@ -192,6 +228,8 @@ fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { (SNAP, HostOp::Snap), (NOTE, HostOp::Note), (EDGE, HostOp::Edge), + (ARM, HostOp::Arm), + (TOUCH, HostOp::Touch), ] { let function = catalog.function(name).expect("assignment root host schema"); registry @@ -429,21 +467,288 @@ return true } #[test] -fn call_in_an_earlier_value_stays_unlowered() { - let error = match super::try_candidate( - r#"local function sweep() +fn early_call_then_plain_rhs_observes_evaluation_and_write_order() { + // A local function cannot capture the log table, so the host stamps it. + // The stamp is not a heap root. The later field read must see it, and + // the overlapping left write must beat the right-hand marker. + let ran = run_source( + r#"local log = {} +log.step = "start" +arm(log) +local function first() + touch() + local made = {} + return made +end +local dest = {} +local marker = {} +dest.slot, dest.seen, dest.slot = (first()), log.step, marker +note(1, dest.seen) +peek(marker) +edge(dest, "slot") +return true +"#, + ); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + assert_eq!(ran.obs.notes, vec![(1.0, "called".to_string())]); + let marker = ran.obs.peeked[0]; + let stored = ran.obs.edges[0].expect("left write kept a table"); + assert_ne!( + stored, marker.table, + "right-to-left write leaves the call result" + ); +} + +#[test] +fn first_call_table_survives_second_call_collect() { + let ran = run_source( + r#"local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local orphan = {} + orphan.self = orphan + rawset(weak, 2, orphan) + return weak +end +local function fresh() + local made = {} + return made +end +local weak = seed() +local a = fresh() +local b = fresh() +local lost = rawget(weak, 2) +peek(lost) +lost = nil +local function first() + local made = {} + made.self = made + peek(made) + return made +end +local function sweep() + collectgarbage("collect") + snap(2) return nil end -local t = {} -local u = {} -t.a, u.b = (sweep()), true +snap(1) +a.field, b.field = (first()), (sweep()) +snap(3) +edge(a, "field") +note(1, type(a.field)) +note(2, type(b.field)) +rawset(weak, 1, a.field) +collectgarbage("collect") +snap(4) +note(3, type(rawget(weak, 1))) +a.field = nil +collectgarbage("collect") +snap(5) +note(4, type(rawget(weak, 1))) return true "#, - ) { - Err(error) => error, - Ok(_) => panic!("only the last value may call"), - }; - assert!(error.contains("Lua expression not lowered yet"), "{error}"); + ); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + let before = snap(&ran, 1.0); + let during = snap(&ran, 2.0); + let after = snap(&ran, 3.0); + let held = snap(&ran, 4.0); + let dropped = snap(&ran, 5.0); + let target = ran.obs.peeked[1]; + assert_eq!(during.collections, 1); + assert_eq!(during.peeked_alive, vec![false, true]); + assert_eq!(during.token_open, vec![false, true]); + assert_eq!(during.root_slots, before.root_slots + 3); + assert_eq!(during.live_roots, before.live_roots + 3); + assert_eq!(after.root_slots, before.root_slots); + assert_eq!(after.live_roots, before.live_roots); + assert_eq!(ran.obs.edges, vec![Some(target.table)]); + assert_eq!( + ran.obs.notes, + vec![ + (1.0, "table".to_string()), + (2.0, "nil".to_string()), + (3.0, "table".to_string()), + (4.0, "nil".to_string()), + ] + ); + assert!( + held.token_open[1], + "written edge keeps the target: {held:?}" + ); + assert!( + !dropped.token_open[1], + "next collect reclaims the target: {dropped:?}" + ); + assert!( + !dropped.token_open[0], + "orphan stays collected: {dropped:?}" + ); + assert_eq!(dropped.collections, 3); + assert_eq!(ran.visits.len(), 3, "three real collects: {:?}", ran.visits); +} + +#[test] +fn evaluated_table_between_calls_survives_the_later_collect() { + let ran = run_source( + r#"local function seed() + local weak = {} + local mode = {} + mode.__mode = "v" + setmetatable(weak, mode) + local orphan = {} + orphan.self = orphan + rawset(weak, 2, orphan) + local mid = {} + mid.self = mid + rawset(weak, 3, mid) + return weak +end +local function fresh() + local made = {} + return made +end +local weak = seed() +local a = fresh() +local b = fresh() +local c = fresh() +local mid = rawget(weak, 3) +local lost = rawget(weak, 2) +peek(mid) +peek(lost) +lost = nil +local function first() + local made = {} + made.self = made + peek(made) + return made +end +local function sweep() + collectgarbage("collect") + snap(2) + return nil +end +snap(1) +a.field, b.field, c.field = (first()), mid, (sweep()) +snap(3) +edge(a, "field") +edge(b, "field") +note(1, type(a.field)) +note(2, type(b.field)) +note(3, type(c.field)) +return true +"#, + ); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + let before = snap(&ran, 1.0); + let during = snap(&ran, 2.0); + let mid = ran.obs.peeked[0]; + let target = ran.obs.peeked[2]; + assert_eq!(during.collections, 1); + assert_eq!(during.peeked_alive, vec![true, false, true]); + assert_eq!(during.token_open, vec![true, false, true]); + assert_eq!(during.root_slots, before.root_slots + 5); + assert_eq!(during.live_roots, before.live_roots + 5); + assert_eq!(ran.obs.edges, vec![Some(target.table), Some(mid.table)]); + assert_eq!( + ran.obs.notes, + vec![ + (1.0, "table".to_string()), + (2.0, "table".to_string()), + (3.0, "nil".to_string()), + ] + ); + assert_eq!(snap(&ran, 3.0).root_slots, before.root_slots); +} + +#[test] +fn scalar_or_nil_between_calls_is_not_a_root() { + let nil_between = r#"local function fresh() + local made = {} + return made +end +local function first() + return nil +end +local function sweep() + collectgarbage("collect") + snap(2) + return nil +end +local a = fresh() +local b = fresh() +local c = fresh() +snap(1) +a.field, b.field, c.field = (first()), nil, (sweep()) +snap(3) +note(1, type(a.field)) +note(2, type(b.field)) +note(3, type(c.field)) +return true +"#; + let ran = run_source(nil_between); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + let before = snap(&ran, 1.0); + let during = snap(&ran, 2.0); + assert_eq!(during.root_slots, before.root_slots + 5); + assert_eq!(during.live_roots, before.live_roots + 3); + assert_eq!( + ran.obs.notes, + vec![ + (1.0, "nil".to_string()), + (2.0, "nil".to_string()), + (3.0, "nil".to_string()), + ] + ); + + let kept = nil_between.replace( + "(first()), nil, (sweep())", + "(first()), \"kept\", (sweep())", + ); + let ran = run_source(&kept); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + assert_eq!(snap(&ran, 2.0).live_roots, snap(&ran, 1.0).live_roots + 3); + assert_eq!(ran.obs.notes[1], (2.0, "string".to_string())); + + let flag = nil_between.replace("(first()), nil, (sweep())", "(first()), true, (sweep())"); + let ran = run_source(&flag); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + assert_eq!(snap(&ran, 2.0).live_roots, snap(&ran, 1.0).live_roots + 3); + assert_eq!(ran.obs.notes[1], (2.0, "boolean".to_string())); + + let early = r#"local function fresh() + local made = {} + return made +end +local function first() + return nil +end +local function sweep() + collectgarbage("collect") + snap(2) + return nil +end +local a = fresh() +local b = fresh() +local c = fresh() +local d = fresh() +snap(1) +a.field, b.field, c.field, d.field = "early", (first()), nil, (sweep()) +snap(3) +note(1, a.field) +note(2, type(c.field)) +return true +"#; + let ran = run_source(early); + assert_eq!(ran.status.as_ref().map(|_| ()), Ok(()), "{:?}", ran.status); + let before = snap(&ran, 1.0); + let during = snap(&ran, 2.0); + assert_eq!(during.root_slots, before.root_slots + 7); + assert_eq!(during.live_roots, before.live_roots + 4); + assert_eq!(ran.obs.notes[0], (1.0, "early".to_string())); + assert_eq!(ran.obs.notes[1], (2.0, "nil".to_string())); } #[test] From 8a67805a4c8ea2572d6bec4bef1e3334a3a87f28 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 08:50:05 +0800 Subject: [PATCH 119/225] feat(lua/heap): allocate one unmarked table during a published sweep tail Reserve one ordinary table on a saved published tail, bind a real host token, and count it only in the completion report. --- src/frontends/lua/heap.rs | 30 + src/frontends/lua/heap/table.rs | 124 +++- src/frontends/lua/heap/table/sweep.rs | 16 +- .../published_late_allocation.rs | 596 ++++++++++++++++++ 4 files changed, 750 insertions(+), 16 deletions(-) create mode 100644 tests/luajit_heap_runtime/published_late_allocation.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 61be574..7064391 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -287,6 +287,36 @@ fn delete_published_named( with_heap(host, |heap| heap.delete_published_named(table, name)) } +/// Allocates one unmarked table while this scope's published sweep tail is +/// saved. Does not install a heap, resume the tail, or open a write. +/// +/// No installed heap, or no saved tail, is [`HeapError::SweepDenied`] and +/// does not change the scope. A full node vector is [`HeapError::NodeCapacity`] +/// before a resource is pushed. A refused `push_resource` releases only that +/// empty reservation. This is not a guest `collectgarbage` step. +fn publish_late(host: &mut HostContext) -> Result<(TableRef, vm::ResourceHandle), HeapError> { + let Some(heap) = host.scope_state_mut::() else { + return Err(HeapError::SweepDenied); + }; + let reservation = heap.reserve_late_table()?; + let table = reservation.table(); + match host.push_resource(LuaTableResource::new(table)) { + Ok(resource) => { + let handle = resource.handle(); + host.scope_state_mut::() + .expect("late reservation keeps the installed heap") + .commit_late(reservation, handle.raw()); + Ok((table, handle)) + } + Err(error) => { + host.scope_state_mut::() + .expect("late reservation keeps the installed heap") + .abandon_late(reservation); + Err(HeapError::from_scope(error)) + } + } +} + /// One host call: a fresh mark, the existing synchronous token close, then /// one sweep. The observer is lent only at the published boundary and does /// not receive the host. A parked mark is refused and left in place. This is diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 28d257c..127df21 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -231,6 +231,30 @@ struct Slot { mode_edge: Option, } +/// Empty slot reserved for one late table. It is not a handle and cannot be +/// cloned. The caller must commit the real token or release the slot. +pub(super) struct LateReservation { + domain: u64, + index: u32, + generation: u32, + spent: bool, +} + +impl LateReservation { + pub(super) fn table(&self) -> TableRef { + TableRef::table(self.domain, self.index, self.generation) + } +} + +impl Drop for LateReservation { + fn drop(&mut self) { + debug_assert!( + self.spent, + "late reservation dropped without commit or release" + ); + } +} + /// Bytes of a string or byte payload stored in a heap record. Capacity is not /// part of the logical extent: only the stored length is. `usize` fits in /// `u64` on every Rust target, so the conversion is exact. @@ -771,20 +795,7 @@ impl LuaHeap { fn alloc_slot(&mut self, kind: HandleKind) -> Result<(u32, u32), HeapError> { if !self.free_list.is_empty() { self.ensure_sweep_open()?; - let index = self.free_list.pop().expect("free list was not empty"); - let slot = &mut self.slots[index as usize]; - if !matches!(slot.state, SlotState::Free) { - return Err(HeapError::StaleHandle); - } - slot.kind = kind; - slot.state = SlotState::Live { marked: false }; - slot.token = None; - slot.carrier = None; - slot.metatable = None; - slot.edge_head = None; - slot.edge_tail = None; - slot.mode_edge = None; - return Ok((index, slot.generation)); + return self.take_free_slot(kind); } if self.slots.len() >= self.limits.nodes as usize { return Err(HeapError::NodeCapacity); @@ -793,6 +804,27 @@ impl LuaHeap { return Err(HeapError::GenerationExhausted); } self.ensure_sweep_open()?; + self.grow_slot(kind) + } + + fn take_free_slot(&mut self, kind: HandleKind) -> Result<(u32, u32), HeapError> { + let index = self.free_list.pop().expect("free list was not empty"); + let slot = &mut self.slots[index as usize]; + if !matches!(slot.state, SlotState::Free) { + return Err(HeapError::StaleHandle); + } + slot.kind = kind; + slot.state = SlotState::Live { marked: false }; + slot.token = None; + slot.carrier = None; + slot.metatable = None; + slot.edge_head = None; + slot.edge_tail = None; + slot.mode_edge = None; + Ok((index, slot.generation)) + } + + fn grow_slot(&mut self, kind: HandleKind) -> Result<(u32, u32), HeapError> { let index = u32::try_from(self.slots.len()).map_err(|_| HeapError::NodeCapacity)?; self.slots.push(Slot { generation: 1, @@ -809,6 +841,59 @@ impl LuaHeap { Ok((index, 1)) } + /// One unmarked table while a published tail is saved. Capacity is checked + /// before the tail gate, matching [`Self::alloc_slot`]. The reservation is + /// not a handle until the caller commits or releases it. + pub(super) fn reserve_late_table(&mut self) -> Result { + self.ensure_published_tail()?; + let (index, generation) = self.place_published_table()?; + Ok(LateReservation { + domain: self.domain, + index, + generation, + spent: false, + }) + } + + fn place_published_table(&mut self) -> Result<(u32, u32), HeapError> { + if !self.free_list.is_empty() { + self.ensure_published_tail()?; + return self.take_free_slot(HandleKind::Table); + } + if self.slots.len() >= self.limits.nodes as usize { + return Err(HeapError::NodeCapacity); + } + if self.limits.max_generation == 0 { + return Err(HeapError::GenerationExhausted); + } + self.ensure_published_tail()?; + self.grow_slot(HandleKind::Table) + } + + pub(super) fn commit_late(&mut self, mut reservation: LateReservation, raw: u64) { + debug_assert!(self.sweep_tail.is_some()); + let index = reservation.index as usize; + debug_assert!(self.slots[index].token.is_none()); + debug_assert!(matches!( + self.slots[index].state, + SlotState::Live { marked: false } + )); + self.slots[index].token = Some(raw); + self.sweep_tail + .as_mut() + .expect("published tail accepted the reservation") + .note_late(); + reservation.spent = true; + } + + pub(super) fn abandon_late(&mut self, mut reservation: LateReservation) { + let index = reservation.index; + debug_assert!(self.slots[index as usize].token.is_none()); + debug_assert!(self.slots[index as usize].edge_head.is_none()); + self.release_slot(index); + reservation.spent = true; + } + /// Releases a reserved node. A stale or foreign handle is refused and the /// heap is left unchanged. The slot stays in the vector so its generation /// cannot be reissued as 1. @@ -2038,6 +2123,14 @@ impl LuaHeap { } } + fn ensure_published_tail(&self) -> Result<(), HeapError> { + if self.sweep_tail.is_some() { + Ok(()) + } else { + Err(HeapError::SweepDenied) + } + } + /// Spends `budget` on the saved tail. Zero restores it without a scan. pub(super) fn resume_sweep_tail(&mut self, budget: u64) -> TailResume { let Some(tail) = self.sweep_tail.take() else { @@ -2607,6 +2700,9 @@ mod private_cycle; #[path = "../../../../tests/luajit_heap_runtime/published_delete.rs"] mod published_delete; #[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/published_late_allocation.rs"] +mod published_late_allocation; +#[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/published_sweep.rs"] mod published_sweep; #[cfg(test)] diff --git a/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs index 0be701f..ffdbb51 100644 --- a/src/frontends/lua/heap/table/sweep.rs +++ b/src/frontends/lua/heap/table/sweep.rs @@ -68,7 +68,8 @@ pub(super) enum TailPhase { Done, } -/// Owned continuation of one published sweep. Only the fields Release and Roots need. +/// Owned continuation of one published sweep. Release, Roots, and the +/// late-node count recorded after publish. #[derive(Debug)] pub(super) struct SweepTail { phase: TailPhase, @@ -76,6 +77,7 @@ pub(super) struct SweepTail { dead: Vec, marked_nodes: u32, live_roots: u32, + late_nodes: u32, } pub(super) enum TailStep { @@ -90,6 +92,7 @@ impl SweepTail { let mut index = self.index; let dead = self.dead; let marked_nodes = self.marked_nodes; + let late_nodes = self.late_nodes; let mut live_roots = self.live_roots; let mut report = None; let mut releases = 0u64; @@ -102,6 +105,7 @@ impl SweepTail { index: &mut index, dead: &dead, marked_nodes, + late_nodes, live_roots: &mut live_roots, report: &mut report, releases: &mut releases, @@ -124,8 +128,13 @@ impl SweepTail { dead, marked_nodes, live_roots, + late_nodes, }) } + + pub(super) fn note_late(&mut self) { + self.late_nodes = self.late_nodes.saturating_add(1); + } } /// One release, root, or uncharged transition. Callers share this with [`SweepSession`]. @@ -134,6 +143,7 @@ struct TailCursor<'a> { index: &'a mut usize, dead: &'a [u32], marked_nodes: u32, + late_nodes: u32, live_roots: &'a mut u32, report: &'a mut Option, releases: &'a mut u64, @@ -161,7 +171,7 @@ fn step_tail(heap: &mut LuaHeap, cursor: &mut TailCursor<'_>) -> bool { heap.collections = heap.collections.saturating_add(1); heap.last_marked = cursor.marked_nodes; *cursor.report = Some(CollectReport { - live_nodes: cursor.marked_nodes, + live_nodes: cursor.marked_nodes.saturating_add(cursor.late_nodes), marked_nodes: cursor.marked_nodes, live_roots: *cursor.live_roots, }); @@ -355,6 +365,7 @@ impl<'a> SweepSession<'a> { index: &mut self.index, dead: &self.dead, marked_nodes: self.marked_nodes, + late_nodes: 0, live_roots: &mut self.live_roots, report: &mut self.report, releases: &mut self.pulse_spent.releases, @@ -616,6 +627,7 @@ impl<'a> SweepSession<'a> { dead: self.dead, marked_nodes: self.marked_nodes, live_roots: self.live_roots, + late_nodes: 0, } } diff --git a/tests/luajit_heap_runtime/published_late_allocation.rs b/tests/luajit_heap_runtime/published_late_allocation.rs new file mode 100644 index 0000000..d6761aa --- /dev/null +++ b/tests/luajit_heap_runtime/published_late_allocation.rs @@ -0,0 +1,596 @@ +//! One private table allocated after a published sweep tail is saved. +//! +//! Not a guest step and not a second allocator. The late node is unmarked, +//! gets one real `resource` token, and is absent from the tail's +//! fixed dead suffix. The next host collection closes that token. + +use vm::Value; + +use super::SlotState; +use crate::heap::{ + self, HeapError, HeapLimits, LuaHeap, PublishedBoundary, PublishedResume, ScanMeter, TableRef, +}; + +fn limits() -> HeapLimits { + HeapLimits { + nodes: 8, + roots: 4, + edges: 8, + max_generation: 8, + } +} + +fn publish(host: &mut vm::HostContext<'_>) -> (TableRef, i64) { + let raw = crate::publish_raw(host); + (crate::table_ref(host, raw), raw) +} + +fn token_open(host: &mut vm::HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + crate::resource_handle(raw), + &heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn handle_open(host: &mut vm::HostContext<'_>, handle: vm::ResourceHandle) -> bool { + host.typed_resource_with_key::(handle, &heap::LuaTableResource::key()) + .is_ok() +} + +fn raw_token(handle: vm::ResourceHandle) -> i64 { + i64::try_from(handle.raw()).expect("resource handle fits a positive integer") +} + +struct WeakPair { + owner: TableRef, + live: TableRef, + dead_a: TableRef, + dead_b: TableRef, + dead_a_token: i64, + dead_b_token: i64, + dead_a_generation: u32, + dead_b_generation: u32, +} + +fn install_pair(host: &mut vm::HostContext<'_>, limits: HeapLimits) -> WeakPair { + heap::install(host, limits).expect("install"); + let meta = heap::with_heap(host, LuaHeap::alloc).expect("meta"); + let (owner, _) = publish(host); + let (live, _) = publish(host); + let (dead_a, dead_a_token) = publish(host); + let (dead_b, dead_b_token) = publish(host); + let (dead_a_generation, dead_b_generation) = heap::with_heap(host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "stay", live)?; + heap.set_named_edge(owner, "a", dead_a)?; + heap.set_named_edge(owner, "b", dead_b)?; + let frame = heap.enter_roots(3)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, live)?; + Ok(( + heap.slots[dead_a.slot() as usize].generation, + heap.slots[dead_b.slot() as usize].generation, + )) + }) + .expect("graph"); + WeakPair { + owner, + live, + dead_a, + dead_b, + dead_a_token, + dead_b_token, + dead_a_generation, + dead_b_generation, + } +} + +fn publish_boundary(host: &mut vm::HostContext<'_>) -> WeakPair { + let graph = install_pair(host, limits()); + let published = heap::collect_until_published(host).expect("publish"); + assert!( + matches!(published, PublishedBoundary::Published { .. }), + "publish must save a tail, got {published:?}" + ); + assert!( + !token_open(host, graph.dead_a_token), + "first dead token closed" + ); + assert!( + !token_open(host, graph.dead_b_token), + "second dead token closed" + ); + heap::with_heap(host, |heap| { + assert!(heap.alive(graph.dead_a), "first dead slot still physical"); + assert!(heap.alive(graph.dead_b), "second dead slot still physical"); + assert_eq!( + heap.slots[graph.dead_a.slot() as usize].generation, + graph.dead_a_generation + ); + assert_eq!( + heap.slots[graph.dead_b.slot() as usize].generation, + graph.dead_b_generation + ); + assert!(heap.has_sweep_tail()); + Ok(()) + }) + .expect("published graph"); + graph +} + +fn tail_cursor(heap: &LuaHeap) -> String { + let text = format!("{:?}", heap.sweep_tail); + let marker = "late_nodes: "; + let Some(start) = text.find(marker) else { + return text; + }; + let rest = &text[start + marker.len()..]; + let digits = rest.chars().take_while(|c| c.is_ascii_digit()).count(); + let mut cursor = String::new(); + cursor.push_str(&text[..start]); + cursor.push_str("late_nodes: _"); + cursor.push_str(&rest[digits..]); + cursor +} + +fn drive_tail( + host: &mut vm::HostContext<'_>, + mut after_first: impl FnMut(&mut vm::HostContext<'_>), +) -> (heap::CollectReport, ScanMeter) { + let _ = heap::take_scan_meter(host).expect("clear tail meter"); + assert!( + matches!( + heap::resume_published_sweep(host, 0).expect("zero budget"), + PublishedResume::Paused + ), + "zero budget does not finish the tail" + ); + let mut saw_pause = false; + let mut report = None; + for _ in 0..16 { + match heap::resume_published_sweep(host, 1).expect("one unit") { + PublishedResume::Paused => { + if !saw_pause { + saw_pause = true; + after_first(host); + } + } + PublishedResume::Completed(done) => { + assert!(report.is_none(), "the tail records one report"); + report = Some(done); + break; + } + } + } + assert!(saw_pause, "the first release must pause before the report"); + let report = report.expect("the tail finishes once"); + let again = heap::resume_published_sweep(host, 1); + assert!( + matches!(again, Err(HeapError::SweepDenied)), + "a finished tail is not resumed again, got {again:?}" + ); + let meter = heap::take_scan_meter(host).expect("tail meter"); + (report, meter) +} + +fn refuse_ordinary_publish(host: &mut vm::HostContext<'_>) { + let before = heap::stats(host).expect("stats"); + let resources = host.resource_count(); + let refused = heap::publish(host); + assert_eq!(refused, Err(HeapError::SweepPending)); + let after = heap::stats(host).expect("stats after ordinary publish"); + assert_eq!(after.live_nodes, before.live_nodes); + assert_eq!(after.node_slots, before.node_slots); + assert_eq!(after.peak_nodes, before.peak_nodes); + assert_eq!(host.resource_count(), resources); +} + +#[test] +fn published_late_allocation_keeps_an_unmarked_token_until_the_next_collect() { + let (late_report, late_meter, late_token, late_slot) = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = publish_boundary(&mut host); + refuse_ordinary_publish(&mut host); + let before = heap::stats(&mut host).expect("stats"); + let _ = heap::take_scan_meter(&mut host).expect("clear publish meter"); + let (late, handle) = heap::publish_late(&mut host).expect("late table"); + let leaked = heap::take_scan_meter(&mut host).expect("late alloc meter"); + assert_eq!(leaked, ScanMeter::default(), "late alloc is not a scan"); + assert_eq!( + late.slot(), + before.node_slots, + "growth, not a dead suffix slot" + ); + assert_ne!(late.slot(), graph.dead_a.slot()); + assert_ne!(late.slot(), graph.dead_b.slot()); + heap::with_heap(&mut host, |heap| { + assert!(matches!( + heap.slots[late.slot() as usize].state, + SlotState::Live { marked: false } + )); + assert_eq!(heap.slots[late.slot() as usize].token, Some(handle.raw())); + assert!(heap.alive(graph.dead_a)); + assert!(heap.alive(graph.dead_b)); + Ok(()) + }) + .expect("late slot"); + assert!(handle_open(&mut host, handle)); + let resources = host.resource_count(); + let (report, meter) = drive_tail(&mut host, |host| { + heap::with_heap(host, |heap| { + assert!(!heap.alive(graph.dead_a), "first dead released"); + assert!(heap.alive(graph.dead_b), "second dead still pending"); + assert!(heap.alive(late), "suffix does not visit the late node"); + assert_eq!(heap.slots[late.slot() as usize].token, Some(handle.raw())); + Ok(()) + }) + .expect("first release"); + assert!(handle_open(host, handle)); + }); + assert_eq!(report.marked_nodes, 3); + assert_eq!(report.live_nodes, report.marked_nodes + 1); + assert_eq!(report.live_roots, 3); + let stats = heap::stats(&mut host).expect("finished stats"); + assert_eq!(stats.live_nodes, report.live_nodes); + assert_eq!(stats.last_marked, report.marked_nodes); + assert_eq!(stats.collections, 1); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(late))).expect("alive")); + assert_eq!(host.resource_count(), resources); + let again = heap::collect(&mut host).expect("next collect"); + assert!( + !handle_open(&mut host, handle), + "next collect closes the late token" + ); + assert!(!token_open(&mut host, raw_token(handle))); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(late))).expect("swept")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.owner))).expect("owner")); + assert_eq!(again.live_nodes, 3); + assert_eq!(again.marked_nodes, 3); + (report, meter, raw_token(handle), late.slot()) + }); + let _ = (late_token, late_slot); + + let (control_report, control_meter) = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = publish_boundary(&mut host); + drive_tail(&mut host, |host| { + heap::with_heap(host, |heap| { + assert!(!heap.alive(graph.dead_a)); + assert!(heap.alive(graph.dead_b)); + Ok(()) + }) + .expect("control first release"); + }) + }); + assert_eq!( + late_meter, control_meter, + "Release and Roots metering is unchanged" + ); + assert_eq!(late_report.marked_nodes, control_report.marked_nodes); + assert_eq!(late_report.live_roots, control_report.live_roots); + assert_eq!(late_report.live_nodes, control_report.live_nodes + 1); +} + +#[test] +fn published_late_allocation_reuses_only_a_released_slot() { + let (same_size_meter, same_size_slots) = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let meta = heap::with_heap(&mut host, LuaHeap::alloc).expect("meta"); + let (owner, _) = publish(&mut host); + let (live, _) = publish(&mut host); + let (dead_a, dead_a_token) = publish(&mut host); + let (dead_b, dead_b_token) = publish(&mut host); + let spare = heap::with_heap(&mut host, LuaHeap::alloc).expect("spare"); + heap::with_heap(&mut host, |heap| heap.rollback(spare)).expect("prior free slot"); + let spare_generation = heap::with_heap(&mut host, |heap| { + Ok(heap.slots[spare.slot() as usize].generation) + }) + .expect("spare generation"); + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "stay", live)?; + heap.set_named_edge(owner, "a", dead_a)?; + heap.set_named_edge(owner, "b", dead_b)?; + let frame = heap.enter_roots(3)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, live)?; + Ok(()) + }) + .expect("graph"); + let published = heap::collect_until_published(&mut host).expect("publish"); + assert!(matches!(published, PublishedBoundary::Published { .. })); + assert!(!token_open(&mut host, dead_a_token)); + assert!(!token_open(&mut host, dead_b_token)); + let before_slots = heap::stats(&mut host).expect("stats").node_slots; + let cursor = heap::with_heap(&mut host, |heap| Ok(tail_cursor(heap))).expect("cursor"); + let (late, handle) = heap::publish_late(&mut host).expect("reuse prior free slot"); + assert_eq!(late.slot(), spare.slot()); + assert_eq!(late.generation(), spare_generation); + assert_ne!(late.slot(), dead_a.slot()); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(dead_a))).expect("pending")); + let after_cursor = + heap::with_heap(&mut host, |heap| Ok(tail_cursor(heap))).expect("cursor"); + assert_eq!(after_cursor, cursor, "late alloc does not walk the suffix"); + assert_eq!( + heap::stats(&mut host).expect("stats").node_slots, + before_slots + ); + assert!(handle_open(&mut host, handle)); + let (report, meter) = drive_tail(&mut host, |_| {}); + assert_eq!(report.live_nodes, report.marked_nodes + 1); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(late))).expect("survives tail")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(owner))).expect("owner")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(live))).expect("live")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(dead_b))).expect("released")); + (meter, before_slots) + }); + + let (control_meter, control_slots) = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let meta = heap::with_heap(&mut host, LuaHeap::alloc).expect("meta"); + let (owner, _) = publish(&mut host); + let (live, _) = publish(&mut host); + let (dead_a, _) = publish(&mut host); + let (dead_b, _) = publish(&mut host); + let spare = heap::with_heap(&mut host, LuaHeap::alloc).expect("spare"); + heap::with_heap(&mut host, |heap| heap.rollback(spare)).expect("same free slot"); + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "stay", live)?; + heap.set_named_edge(owner, "a", dead_a)?; + heap.set_named_edge(owner, "b", dead_b)?; + let frame = heap.enter_roots(3)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, live)?; + Ok(()) + }) + .expect("control graph"); + let published = heap::collect_until_published(&mut host).expect("publish"); + assert!(matches!(published, PublishedBoundary::Published { .. })); + let slots = heap::stats(&mut host).expect("stats").node_slots; + let (_report, meter) = drive_tail(&mut host, |_| {}); + (meter, slots) + }); + assert_eq!(same_size_slots, control_slots, "same slot vector"); + assert_eq!( + same_size_meter, control_meter, + "same-size tail metering is unchanged" + ); + + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = publish_boundary(&mut host); + let first = heap::resume_published_sweep(&mut host, 1).expect("release first dead"); + assert!(matches!(first, PublishedResume::Paused)); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.dead_a))).expect("released") + ); + let released_generation = graph.dead_a.generation(); + let (late, handle) = heap::publish_late(&mut host).expect("reuse released index"); + assert_eq!(late.slot(), graph.dead_a.slot()); + assert_ne!(late.generation(), released_generation); + assert_ne!(late, graph.dead_a, "old handle is stale"); + assert!(heap::with_heap(&mut host, |heap| Ok(!heap.alive(graph.dead_a))).expect("stale")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.dead_b))).expect("pending")); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(late))).expect("reused live")); + let cursor = heap::with_heap(&mut host, |heap| Ok(tail_cursor(heap))).expect("cursor"); + let root_refused = heap::with_heap(&mut host, |heap| heap.enter_roots(1)); + assert_eq!(root_refused, Err(HeapError::SweepPending)); + let write_refused = heap::with_heap(&mut host, |heap| { + heap.set_named_edge(graph.live, "extra", graph.owner) + }); + assert_eq!(write_refused, Err(HeapError::SweepPending)); + let after = heap::with_heap(&mut host, |heap| Ok(tail_cursor(heap))).expect("cursor"); + assert_eq!(after, cursor); + let (report, _) = drive_tail(&mut host, |_| {}); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(late))).expect("suffix skipped reuse") + ); + assert!( + !heap::with_heap(&mut host, |heap| Ok(heap.alive(graph.dead_b))).expect("other dead") + ); + assert_eq!(report.live_nodes, report.marked_nodes + 1); + assert!(handle_open(&mut host, handle)); + }); +} + +struct QuotaFill; + +impl vm::resource::HostResource for QuotaFill {} + +#[test] +fn published_late_allocation_rolls_back_capacity_failures() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let tight = HeapLimits { + nodes: 5, + roots: 4, + edges: 8, + max_generation: 8, + }; + let _graph = install_pair(&mut host, tight); + let published = heap::collect_until_published(&mut host).expect("publish"); + assert!(matches!(published, PublishedBoundary::Published { .. })); + let before = heap::stats(&mut host).expect("stats"); + let resources = host.resource_count(); + let refused = heap::publish_late(&mut host); + assert_eq!(refused, Err(HeapError::NodeCapacity)); + let after = heap::stats(&mut host).expect("stats"); + assert_eq!(after.live_nodes, before.live_nodes); + assert_eq!(after.node_slots, before.node_slots); + assert_eq!(after.peak_nodes, before.peak_nodes); + assert_eq!(host.resource_count(), resources); + let (report, _) = drive_tail(&mut host, |_| {}); + assert_eq!(report.live_nodes, report.marked_nodes); + assert_eq!( + heap::stats(&mut host).expect("done").live_nodes, + report.live_nodes + ); + }); + + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = publish_boundary(&mut host); + while host.resource_count() < vm::resource::handle::DEFAULT_MAX_RESOURCES { + host.push_resource(QuotaFill) + .expect("fill the real resource table"); + } + let before = heap::stats(&mut host).expect("stats"); + let resources = host.resource_count(); + let cursor = heap::with_heap(&mut host, |heap| Ok(tail_cursor(heap))).expect("cursor"); + let refused = heap::publish_late(&mut host); + let after = heap::stats(&mut host).expect("stats after"); + let error = refused.expect_err("a full resource table refuses the late token"); + assert_eq!(after.node_slots, before.node_slots + 1, "high water stays"); + assert_eq!(after.peak_nodes, before.peak_nodes + 1); + assert_eq!( + after.live_nodes, before.live_nodes, + "the empty reservation is released" + ); + assert_eq!(host.resource_count(), resources, "no new open token"); + match &error { + HeapError::Scope(message) if message.contains("resource_limit_exceeded") => {} + other => panic!("refusal must be the real push_resource limit, got {other:?}"), + } + heap::with_heap(&mut host, |heap| { + let index = before.node_slots; + assert!(matches!(heap.slots[index as usize].state, SlotState::Free)); + assert_eq!(heap.slots[index as usize].generation, 2); + assert_eq!(heap.slots[index as usize].token, None); + assert_eq!(heap.free_list.last().copied(), Some(index)); + assert_eq!(tail_cursor(heap), cursor); + assert!(heap.alive(graph.dead_a)); + Ok(()) + }) + .expect("rolled back slot"); + let (report, _) = drive_tail(&mut host, |_| {}); + assert_eq!(report.live_nodes, report.marked_nodes); + assert_eq!(report.marked_nodes, 3); + let done = heap::stats(&mut host).expect("done"); + assert_eq!(done.live_nodes, report.live_nodes); + assert_eq!(done.last_marked, report.marked_nodes); + assert_eq!(done.node_slots, before.node_slots + 1); + assert_eq!(done.peak_nodes, before.peak_nodes + 1); + }); +} + +#[test] +fn published_late_allocation_does_not_install_without_a_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let refused = heap::publish_late(&mut host); + assert_eq!(refused, Err(HeapError::SweepDenied)); + assert!(host.scope_state::().is_none()); + assert_eq!(host.resource_count(), 0); + }); + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let table = heap::with_heap(&mut host, LuaHeap::alloc).expect("table"); + let before = heap::stats(&mut host).expect("stats"); + let refused = heap::publish_late(&mut host); + assert_eq!(refused, Err(HeapError::SweepDenied)); + let after = heap::stats(&mut host).expect("stats"); + assert_eq!(after, before); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(table))).expect("alive")); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.has_sweep_tail())).expect("no tail")); + assert_eq!(host.resource_count(), 0); + }); +} + +#[test] +fn published_late_allocation_rejects_delete_without_moving_the_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = publish_boundary(&mut host); + let (late, handle) = heap::publish_late(&mut host).expect("late table"); + let cursor = heap::with_heap(&mut host, |heap| Ok(tail_cursor(heap))).expect("cursor"); + let rejected = heap::delete_published_named(&mut host, late, "entry"); + assert_eq!(rejected, Err(HeapError::SweepPending)); + let removed = heap::delete_published_named(&mut host, graph.owner, "stay"); + assert_eq!(removed, Ok(true), "a marked ordinary field still deletes"); + let missing = heap::delete_published_named(&mut host, graph.owner, "stay"); + assert_eq!(missing, Ok(false)); + heap::with_heap(&mut host, |heap| { + assert_eq!(tail_cursor(heap), cursor); + assert!(heap.alive(late)); + assert!(matches!( + heap.slots[late.slot() as usize].state, + SlotState::Live { marked: false } + )); + assert_eq!(heap.slots[late.slot() as usize].token, Some(handle.raw())); + assert_eq!(heap.named_edge(graph.owner, "stay")?, None); + Ok(()) + }) + .expect("delete left the tail"); + assert!(handle_open(&mut host, handle)); + let (report, _) = drive_tail(&mut host, |_| {}); + assert_eq!(report.live_nodes, report.marked_nodes + 1); + assert!(handle_open(&mut host, handle)); + }); +} + +#[test] +fn published_late_allocation_drain_leaves_the_late_node() { + let (late_meter, late_marked, late_live) = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = publish_boundary(&mut host); + let _ = heap::take_scan_meter(&mut host).expect("clear publish meter"); + let (late, handle) = heap::publish_late(&mut host).expect("late table"); + let leaked = heap::take_scan_meter(&mut host).expect("late meter"); + assert_eq!(leaked, ScanMeter::default()); + heap::with_heap(&mut host, |heap| { + heap.drain_sweep_tail(); + assert!(!heap.has_sweep_tail()); + assert!(heap.alive(late)); + assert!(!heap.alive(graph.dead_a)); + assert!(!heap.alive(graph.dead_b)); + assert_eq!(heap.slots[late.slot() as usize].token, Some(handle.raw())); + Ok(()) + }) + .expect("drain"); + assert!(handle_open(&mut host, handle)); + let stats = heap::stats(&mut host).expect("after drain"); + assert_eq!(stats.collections, 1); + assert_eq!(stats.last_marked, 3); + assert_eq!(stats.live_nodes, stats.last_marked + 1); + let meter = heap::take_scan_meter(&mut host).expect("drain meter"); + let again = heap::collect(&mut host).expect("next collect"); + assert!(!handle_open(&mut host, handle)); + assert_eq!(again.live_nodes, 3); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(late))).expect("swept")); + (meter, stats.last_marked, stats.live_nodes) + }); + let _ = (late_marked, late_live); + + let control_meter = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = publish_boundary(&mut host); + let _ = heap::take_scan_meter(&mut host).expect("clear"); + heap::with_heap(&mut host, |heap| { + heap.drain_sweep_tail(); + assert!(!heap.alive(graph.dead_a)); + assert!(!heap.alive(graph.dead_b)); + Ok(()) + }) + .expect("control drain"); + let stats = heap::stats(&mut host).expect("control"); + assert_eq!(stats.collections, 1); + assert_eq!(stats.last_marked, 3); + assert_eq!(stats.live_nodes, 3); + heap::take_scan_meter(&mut host).expect("control meter") + }); + assert_eq!( + late_meter, control_meter, + "drain uses the same Release and Roots steps" + ); +} From 5600aa204066ce99584684141cdb2c0790be70d6 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 10:27:03 +0800 Subject: [PATCH 120/225] docs(lua/heap): correct the published late reservation comment The tail gate runs before slot reuse or the growth capacity check. The reservation is not a handle until committed. --- src/frontends/lua/heap/table.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 127df21..5d27936 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -841,9 +841,9 @@ impl LuaHeap { Ok((index, 1)) } - /// One unmarked table while a published tail is saved. Capacity is checked - /// before the tail gate, matching [`Self::alloc_slot`]. The reservation is - /// not a handle until the caller commits or releases it. + /// Reserves one unmarked table after checking for a saved published tail. + /// The tail gate runs before slot reuse or the growth capacity check. + /// The reservation is not a handle until committed. pub(super) fn reserve_late_table(&mut self) -> Result { self.ensure_published_tail()?; let (index, generation) = self.place_published_table()?; From a547f328a0ec89fb7916f8c537d11136fea0db1c Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 09:19:55 +0800 Subject: [PATCH 121/225] feat(lua/heap): refill one named gap during a published sweep tail Replace one ordinary UTF-8 gap with an already issued table while the saved tail stays in Release or Roots. A missing name does not reclaim or inspect the target, and the ordinary setter still refuses. --- src/frontends/lua/heap.rs | 24 + src/frontends/lua/heap/table.rs | 62 ++ tests/luajit_heap_runtime/published_refill.rs | 702 ++++++++++++++++++ 3 files changed, 788 insertions(+) create mode 100644 tests/luajit_heap_runtime/published_refill.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 7064391..ce5c4c8 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -317,6 +317,30 @@ fn publish_late(host: &mut HostContext) -> Result<(TableRef, vm::ResourceHandle) } } +/// Replaces one ordinary UTF-8 gap with an already issued table while this +/// scope's published sweep tail is saved. Does not install a heap and does +/// not resume the tail. +/// +/// No installed heap is [`HeapError::SweepDenied`]. The installed domain is +/// checked on `from` before any other handle or tail result, so a foreign +/// owner is [`HeapError::WrongDomain`] even when no tail is saved. `to` is +/// not examined until a real gap is found. This is not a guest +/// `collectgarbage` step or a guest `rawset`. +fn refill_published_gap( + host: &mut HostContext, + from: TableRef, + name: &str, + to: TableRef, +) -> Result { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + if from.domain() != heap.domain() { + return Err(HeapError::WrongDomain); + } + with_heap(host, |heap| heap.refill_published_gap(from, name, to)) +} + /// One host call: a fresh mark, the existing synchronous token close, then /// one sweep. The observer is lent only at the published boundary and does /// not receive the host. A parked mark is refused and left in place. This is diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 5d27936..2d8835d 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -1313,6 +1313,65 @@ impl LuaHeap { Ok(true) } + /// Replaces one ordinary UTF-8 gap while a sweep tail is saved. + /// + /// The owner checks match [`Self::delete_published_named`]: live, then a + /// saved tail, then this round's mark, then the reserved mode name, then + /// one borrowed [`Self::locate_named`]. A missing name is `Ok(false)` and + /// does not reclaim storage or inspect `to`. A located record that is not + /// ordinary UTF-8, or not a gap, is [`HeapError::SweepPending`]. Only a + /// real hit checks `to`: domain, kind, generation, and physical live, + /// then this round's mark, then the carrier [`Self::issued_value`] would + /// refuse as [`HeapError::StaleHandle`]. One [`Self::replace_edge_value`] + /// commits that table and returns `Ok(true)`. This does not mark, resume + /// the tail, add a key, or call the ordinary writer. + pub(super) fn refill_published_gap( + &mut self, + from: TableRef, + name: &str, + to: TableRef, + ) -> Result { + self.require_live(from)?; + if self.sweep_tail.is_none() { + return Err(HeapError::SweepDenied); + } + if !Self::slot_marked(&self.slots[from.slot() as usize].state) { + return Err(HeapError::SweepPending); + } + if EdgeKey::is_mode_name(name) { + return Err(HeapError::SweepPending); + } + let Some((_, index)) = self.locate_named(from.slot(), name) else { + return Ok(false); + }; + if !self.published_utf8_gap(index) { + return Err(HeapError::SweepPending); + } + self.require_live(to)?; + if !Self::slot_marked(&self.slots[to.slot() as usize].state) { + return Err(HeapError::SweepPending); + } + self.issued_value(to)?; + self.replace_edge_value( + from.slot(), + index, + EdgeValue::Table { + slot: to.slot(), + generation: to.generation(), + }, + ); + Ok(true) + } + + /// The located record is an ordinary UTF-8 cursor gap. + fn published_utf8_gap(&self, index: u32) -> bool { + let edge = self.edge_slots[index as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + matches!(edge.key, EdgeKey::Utf8(_)) && edge.value.is_cursor_gap() + } + fn slot_marked(state: &SlotState) -> bool { matches!(state, SlotState::Live { marked: true }) } @@ -2703,6 +2762,9 @@ mod published_delete; #[path = "../../../../tests/luajit_heap_runtime/published_late_allocation.rs"] mod published_late_allocation; #[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/published_refill.rs"] +mod published_refill; +#[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/published_sweep.rs"] mod published_sweep; #[cfg(test)] diff --git a/tests/luajit_heap_runtime/published_refill.rs b/tests/luajit_heap_runtime/published_refill.rs new file mode 100644 index 0000000..b317f33 --- /dev/null +++ b/tests/luajit_heap_runtime/published_refill.rs @@ -0,0 +1,702 @@ +//! Same-key refill of an ordinary UTF-8 gap while a published sweep tail is saved. +//! +//! Not a guest `collectgarbage` step and not a `.lua` rawset. `heap::collect` +//! and `set_named_edge` are the host paths a production guest step or rawset +//! would share; both still refuse while the tail is saved. `named_value` and +//! `next_guest` are the private host's observation of the pre-issued carrier. + +use vm::Value; + +use super::{EdgeKey, EdgeValue, SlotState}; +use crate::heap::{ + self, CollectReport, GuestClass, HeapError, HeapLimits, LuaHeap, PublishedBoundary, + PublishedResume, ScanMeter, TableRef, +}; + +fn limits() -> HeapLimits { + HeapLimits { + nodes: 16, + roots: 8, + edges: 24, + max_generation: 8, + } +} + +fn publish(host: &mut vm::HostContext<'_>) -> (TableRef, i64) { + let raw = crate::publish_raw(host); + (crate::table_ref(host, raw), raw) +} + +fn token_open(host: &mut vm::HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + crate::resource_handle(raw), + &heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn slot_generation(heap: &LuaHeap, table: TableRef) -> u32 { + heap.slots[table.slot() as usize].generation +} + +fn marked(heap: &LuaHeap, table: TableRef) -> bool { + matches!( + heap.slots[table.slot() as usize].state, + SlotState::Live { marked: true } + ) +} + +fn utf8_gap(heap: &LuaHeap, owner: TableRef, name: &str) -> bool { + let Some((_, index)) = heap.locate_named(owner.slot(), name) else { + return false; + }; + heap.edge_slots[index as usize] + .edge + .as_ref() + .is_some_and(|edge| matches!(edge.key, EdgeKey::Utf8(_)) && edge.value.is_cursor_gap()) +} + +fn tail_text(host: &mut vm::HostContext<'_>) -> String { + heap::with_heap(host, |heap| Ok(format!("{:?}", heap.sweep_tail))).expect("tail") +} + +fn finish_tail(host: &mut vm::HostContext<'_>) -> CollectReport { + let resumed = heap::resume_published_sweep(host, 64).expect("finish"); + let PublishedResume::Completed(report) = resumed else { + panic!("one budget finishes the saved tail, got {resumed:?}"); + }; + assert_eq!( + heap::resume_published_sweep(host, 1).expect_err("tail is gone"), + HeapError::SweepDenied + ); + report +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Place { + head: Option, + tail: Option, + index: u32, + next: Option, + free: Option, + occupied: u32, + payload: u64, + logical: u64, +} + +fn place(heap: &LuaHeap, owner: TableRef, name: &str) -> Place { + let (_, index) = heap.locate_named(owner.slot(), name).expect(name); + let slot = &heap.slots[owner.slot() as usize]; + Place { + head: slot.edge_head, + tail: slot.edge_tail, + index, + next: heap.edge_slots[index as usize].next, + free: heap.edge_free_head, + occupied: heap.occupied_edges, + payload: heap.payload_bytes, + logical: heap.logical_bytes(), + } +} + +fn assert_original_carrier( + heap: &LuaHeap, + owner: TableRef, + name: &str, + table: TableRef, + carrier: &Value, +) -> Result<(), HeapError> { + let read = heap.named_value(owner, name)?; + assert_eq!(read, *carrier); + assert_eq!( + heap.guest_class(&read), + GuestClass::Table(table), + "private host read is the pre-issued carrier, not a new array" + ); + Ok(()) +} + +struct Graph { + weak: TableRef, + other: TableRef, + spare: TableRef, + keeper: TableRef, + target: TableRef, + target_token: i64, + target_carrier: Value, + successor: TableRef, + successor_carrier: Value, + doomed_a: TableRef, + doomed_a_token: i64, + doomed_b: TableRef, + doomed_b_token: i64, + doomed_b_carrier: Value, + bare: TableRef, + meta: TableRef, +} + +fn build_graph(host: &mut vm::HostContext<'_>) -> Graph { + heap::install(host, limits()).expect("install"); + let meta = heap::with_heap(host, LuaHeap::alloc).expect("meta"); + let (weak, _) = publish(host); + let (other, _) = publish(host); + let (spare, _) = publish(host); + let (keeper, _) = publish(host); + let (target, target_token) = publish(host); + let (successor, _) = publish(host); + let (doomed_a, doomed_a_token) = publish(host); + let (doomed_b, doomed_b_token) = publish(host); + let bare = heap::with_heap(host, LuaHeap::alloc).expect("bare"); + let (target_carrier, successor_carrier, doomed_b_carrier) = heap::with_heap(host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(weak, Some(meta))?; + heap.set_metatable(other, Some(meta))?; + heap.set_named_edge(weak, "a", doomed_a)?; + heap.set_named_edge(weak, "after", successor)?; + heap.set_named_edge(weak, "solid", target)?; + heap.set_named_edge(other, "gap", doomed_b)?; + heap.set_named_edge(other, "next", successor)?; + heap.set_named_edge(keeper, "hold", target)?; + heap.set_named_edge(keeper, "succ", successor)?; + heap.set_named_edge(keeper, "bare", bare)?; + let target_carrier = heap.issue_carrier(target)?; + let successor_carrier = heap.issue_carrier(successor)?; + let doomed_b_carrier = heap.issue_carrier(doomed_b)?; + let frame = heap.enter_roots(4)?; + heap.write_root(frame, 0, weak)?; + heap.write_root(frame, 1, other)?; + heap.write_root(frame, 2, spare)?; + heap.write_root(frame, 3, keeper)?; + Ok((target_carrier, successor_carrier, doomed_b_carrier)) + }) + .expect("graph"); + Graph { + weak, + other, + spare, + keeper, + target, + target_token, + target_carrier, + successor, + successor_carrier, + doomed_a, + doomed_a_token, + doomed_b, + doomed_b_token, + doomed_b_carrier, + bare, + meta, + } +} + +fn publish_two_gaps(host: &mut vm::HostContext<'_>, graph: &Graph) { + let published = heap::collect_until_published(host).expect("publish"); + let PublishedBoundary::Published { + window_heads, + window_edges, + } = published + else { + panic!("a real dead slot must save the tail, got {published:?}"); + }; + assert_eq!(window_heads, 10, "one owner head per slot"); + assert_eq!(window_edges, 9, "mode plus eight table edges"); + assert!(!token_open(host, graph.doomed_a_token)); + assert!(!token_open(host, graph.doomed_b_token)); + assert!(token_open(host, graph.target_token)); + heap::with_heap(host, |heap| { + assert!(utf8_gap(heap, graph.weak, "a"), "first real gap"); + assert!(utf8_gap(heap, graph.other, "gap"), "second real gap"); + assert!(heap.alive(graph.doomed_a), "dead slot still physical"); + assert_eq!( + slot_generation(heap, graph.doomed_a), + graph.doomed_a.generation() + ); + assert!(!marked(heap, graph.doomed_a), "dead slot was not poked"); + assert!(heap.alive(graph.doomed_b)); + assert!(!marked(heap, graph.doomed_b)); + assert_eq!( + heap.issued_value(graph.doomed_b)?, + graph.doomed_b_carrier, + "the unmarked dead slot still has its carrier" + ); + assert!(marked(heap, graph.weak)); + assert!(marked(heap, graph.other)); + assert!(marked(heap, graph.spare)); + assert!(marked(heap, graph.target)); + assert!(marked(heap, graph.bare)); + assert!(heap.slots[graph.bare.slot() as usize].carrier.is_none()); + Ok(()) + }) + .expect("published facts"); +} + +/// Full edge quota. A missing name does not reclaim the other owner's gap. +/// The private wrapper reuses the cleared record and the pre-issued carrier. +/// The ordinary writer and host collect still refuse. The next cycle keeps +/// the target while its strong root remains. +#[test] +fn published_refill_reuses_the_issued_carrier_under_a_full_quota() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_graph(&mut host); + publish_two_gaps(&mut host, &graph); + let _ = heap::take_scan_meter(&mut host).expect("clear meter"); + let before = heap::stats(&mut host).expect("before"); + assert_eq!(before.collections, 0); + let tail = tail_text(&mut host); + let resources = host.resource_count(); + heap::with_heap(&mut host, |heap| { + heap.limits.edges = heap.occupied_edges; + assert_eq!(heap.occupied_edges, heap.limits.edges); + assert_eq!( + heap.next_guest(graph.weak, &Value::Null)? + .expect("gap is skipped") + .1, + graph.successor_carrier + ); + Ok(()) + }) + .expect("quota"); + let weak_place = heap::with_heap(&mut host, |heap| Ok(place(heap, graph.weak, "a"))) + .expect("weak place"); + let other_place = heap::with_heap(&mut host, |heap| Ok(place(heap, graph.other, "gap"))) + .expect("other place"); + let mode_edge = heap::with_heap(&mut host, |heap| { + Ok(heap.slots[graph.meta.slot() as usize].mode_edge) + }) + .expect("mode"); + + assert_eq!( + heap::collect(&mut host).expect_err("production collect"), + HeapError::SweepPending + ); + assert_eq!( + heap::with_heap(&mut host, |heap| { + heap.set_named_edge(graph.weak, "a", graph.target) + }), + Err(HeapError::SweepPending), + "ordinary writer still stops at the sweep gate" + ); + + let mut foreign_heap = LuaHeap::new(limits()); + let foreign = foreign_heap.alloc().expect("foreign"); + assert_eq!( + heap::refill_published_gap(&mut host, graph.spare, "missing", foreign), + Ok(false), + "a missing name does not inspect the target" + ); + assert!(foreign_heap.alive(foreign)); + heap::with_heap(&mut host, |heap| { + assert_eq!(place(heap, graph.other, "gap"), other_place); + assert!(utf8_gap(heap, graph.other, "gap")); + assert_eq!( + heap.next_guest(graph.other, &Value::string("gap"))? + .expect("other gap cursor continues"), + (Value::string("next"), graph.successor_carrier.clone()) + ); + Ok(()) + }) + .expect("missing key did not reclaim"); + + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.target), + Ok(true) + ); + heap::with_heap(&mut host, |heap| { + assert_eq!(place(heap, graph.weak, "a"), weak_place); + assert_eq!(place(heap, graph.other, "gap"), other_place); + assert_eq!(heap.slots[graph.meta.slot() as usize].mode_edge, mode_edge); + assert_original_carrier(heap, graph.weak, "a", graph.target, &graph.target_carrier)?; + assert_eq!( + heap.next_guest(graph.weak, &Value::Null)? + .expect("refilled key is now visible"), + (Value::string("a"), graph.target_carrier.clone()) + ); + assert_eq!( + heap.next_guest(graph.weak, &Value::string("a"))? + .expect("successor stays"), + (Value::string("after"), graph.successor_carrier.clone()) + ); + assert_eq!(heap.named_edge(graph.weak, "after")?, Some(graph.successor)); + assert_eq!(heap.live_edge_count, before.live_edges + 1); + Ok(()) + }) + .expect("refilled"); + let mut expected = before; + expected.live_edges += 1; + assert_eq!(heap::stats(&mut host).expect("after"), expected); + assert_eq!(host.resource_count(), resources); + assert_eq!(tail_text(&mut host), tail); + assert_eq!( + heap::take_scan_meter(&mut host).expect("meter"), + ScanMeter::default() + ); + assert!(matches!( + heap::resume_published_sweep(&mut host, 0).expect("zero"), + PublishedResume::Paused + )); + + let report = finish_tail(&mut host); + assert_eq!(report.live_nodes, 8, "two dead slots released; one report"); + assert_eq!(heap::stats(&mut host).expect("finished").collections, 1); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(graph.doomed_a)); + assert_ne!( + slot_generation(heap, graph.doomed_a), + graph.doomed_a.generation() + ); + assert_original_carrier(heap, graph.weak, "a", graph.target, &graph.target_carrier)?; + assert_eq!( + heap.next_guest(graph.weak, &Value::string("a"))? + .expect("successor after the tail"), + (Value::string("after"), graph.successor_carrier.clone()) + ); + Ok(()) + }) + .expect("reread"); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.target), + Err(HeapError::SweepDenied), + "the finished round has no tail" + ); + + let kept = heap::collect(&mut host).expect("strong root retains the target"); + assert_eq!(kept.live_nodes, 8); + assert!(token_open(&mut host, graph.target_token)); + heap::with_heap(&mut host, |heap| { + assert!(heap.alive(graph.target)); + assert_original_carrier(heap, graph.weak, "a", graph.target, &graph.target_carrier)?; + Ok(()) + }) + .expect("retained"); + }); +} + +/// Refusals leave the tail, resources, and edge statistics alone. A missing +/// name still does not inspect `to`. The ordinary write gate stays closed. +#[test] +fn published_refill_rejects_without_moving_the_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let ghost = TableRef::table(1, 0, 1); + assert_eq!( + heap::refill_published_gap(&mut host, ghost, "a", ghost), + Err(HeapError::SweepDenied) + ); + assert_eq!( + heap::refill_published_gap(&mut host, ghost, "a", ghost), + Err(HeapError::SweepDenied), + "the refusal does not install a heap" + ); + assert!(host.scope_state::().is_none()); + + let graph = build_graph(&mut host); + let installed = heap::stats(&mut host).expect("installed"); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.target), + Err(HeapError::SweepDenied) + ); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.named_edge(graph.weak, "a")?, Some(graph.doomed_a)); + Ok(()) + }) + .expect("field remains"); + assert_eq!(heap::stats(&mut host).expect("unchanged"), installed); + + let stale = heap::with_heap(&mut host, |heap| { + let rolled = heap.alloc()?; + heap.rollback(rolled)?; + Ok(rolled) + }) + .expect("stale"); + assert_eq!( + heap::refill_published_gap(&mut host, stale, "a", graph.target), + Err(HeapError::StaleHandle) + ); + let forged = heap::with_heap(&mut host, |heap| { + let closure = heap.alloc_closure()?; + let frame = heap.enter_roots(1)?; + heap.write_closure_root(frame, 0, closure)?; + heap.write_from( + graph.weak.slot(), + EdgeKey::named("hidden"), + EdgeValue::Closure { + slot: closure.slot(), + generation: closure.generation(), + }, + )?; + Ok(TableRef::table( + closure.domain(), + closure.slot(), + closure.generation(), + )) + }) + .expect("closure"); + assert_eq!( + heap::refill_published_gap(&mut host, forged, "a", graph.target), + Err(HeapError::WrongKind) + ); + let mut foreign_heap = LuaHeap::new(limits()); + let foreign = foreign_heap.alloc().expect("foreign"); + assert_eq!( + heap::refill_published_gap(&mut host, foreign, "a", graph.target), + Err(HeapError::WrongDomain) + ); + assert!(foreign_heap.alive(foreign)); + + let published = heap::collect_until_published(&mut host).expect("publish"); + assert!(matches!(published, PublishedBoundary::Published { .. })); + let _ = heap::take_scan_meter(&mut host); + let before = heap::stats(&mut host).expect("before"); + let tail = tail_text(&mut host); + let resources = host.resource_count(); + let logical = heap::with_heap(&mut host, |heap| Ok(heap.logical_bytes())).expect("bytes"); + let frozen = |host: &mut vm::HostContext<'_>| { + assert_eq!(host.resource_count(), resources); + assert_eq!(heap::stats(host).expect("stats"), before); + assert_eq!(tail_text(host), tail); + assert_eq!( + heap::with_heap(host, |heap| Ok(heap.logical_bytes())).expect("bytes"), + logical + ); + }; + + assert_eq!( + heap::refill_published_gap(&mut host, graph.doomed_a, "a", graph.target), + Err(HeapError::SweepPending), + "unmarked live owner" + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.meta, "__mode", graph.target), + Err(HeapError::SweepPending) + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "__mode", graph.target), + Err(HeapError::SweepPending), + "reserved name is not a missing ordinary field" + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "solid", graph.target), + Err(HeapError::SweepPending), + "non-gap" + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "hidden", graph.target), + Err(HeapError::SweepPending), + "internal value is not a gap" + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.doomed_b), + Err(HeapError::SweepPending), + "unmarked physical dead slot, same generation, carrier present" + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.bare), + Err(HeapError::StaleHandle), + "marked target with no carrier" + ); + frozen(&mut host); + let stale_target = TableRef::table(graph.target.domain(), graph.target.slot(), 0); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", stale_target), + Err(HeapError::StaleHandle) + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", forged), + Err(HeapError::WrongKind) + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", foreign), + Err(HeapError::WrongDomain) + ); + frozen(&mut host); + assert_eq!( + heap::refill_published_gap(&mut host, graph.spare, "missing", foreign), + Ok(false) + ); + frozen(&mut host); + assert_eq!( + heap::with_heap(&mut host, |heap| { + heap.set_named_edge(graph.weak, "a", graph.target) + }), + Err(HeapError::SweepPending) + ); + assert_eq!( + heap::with_heap(&mut host, |heap| { + heap.clear_edge(graph.weak, &EdgeKey::named("a")) + }), + Err(HeapError::SweepPending) + ); + frozen(&mut host); + heap::with_heap(&mut host, |heap| { + assert!(utf8_gap(heap, graph.weak, "a")); + assert!(utf8_gap(heap, graph.other, "gap")); + assert!(heap.locate_named(graph.weak.slot(), "hidden").is_some()); + assert!(heap.slots[graph.meta.slot() as usize].mode_edge.is_some()); + assert_eq!( + heap.next_guest(graph.other, &Value::string("gap"))? + .expect("gap cursor still continues") + .1, + graph.successor_carrier + ); + Ok(()) + }) + .expect("zero effect"); + assert!(foreign_heap.alive(foreign)); + assert_eq!( + heap::take_scan_meter(&mut host).expect("meter"), + ScanMeter::default() + ); + }); +} + +/// A gap left by the previous cycle stays refillable after `__mode` changes. +/// This round's tail comes from a new dead slot. The entry does not reread mode. +#[test] +fn published_refill_accepts_a_prior_gap_after_mode_changes() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_graph(&mut host); + publish_two_gaps(&mut host, &graph); + let report = finish_tail(&mut host); + assert_eq!(report.live_nodes, 8); + heap::with_heap(&mut host, |heap| { + assert!(utf8_gap(heap, graph.weak, "a"), "the gap outlives the tail"); + assert!(!heap.alive(graph.doomed_a)); + Ok(()) + }) + .expect("prior gap"); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.target), + Err(HeapError::SweepDenied) + ); + + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(graph.meta, Value::string("k"))?; + Ok(()) + }) + .expect("mode"); + let mode_edge = heap::with_heap(&mut host, |heap| { + Ok(heap.slots[graph.meta.slot() as usize].mode_edge) + }) + .expect("mode edge"); + assert!(mode_edge.is_some()); + + let (fresh, fresh_token) = publish(&mut host); + let published = heap::collect_until_published(&mut host).expect("next publish"); + assert!( + matches!(published, PublishedBoundary::Published { .. }), + "the new dead slot opens a real tail, got {published:?}" + ); + assert!(!token_open(&mut host, fresh_token)); + heap::with_heap(&mut host, |heap| { + assert!(heap.alive(fresh)); + assert_eq!(slot_generation(heap, fresh), fresh.generation()); + assert!(!marked(heap, fresh), "this round's dead slot was not poked"); + assert!(utf8_gap(heap, graph.weak, "a")); + assert_eq!(heap.named_value(graph.meta, "__mode")?, Value::string("k")); + assert_eq!( + heap.set_named_edge(graph.weak, "a", graph.target), + Err(HeapError::SweepPending), + "mode change is not a write-gate bypass" + ); + Ok(()) + }) + .expect("still a gap"); + + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.target), + Ok(true), + "the prior gap does not depend on the current mode" + ); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.slots[graph.meta.slot() as usize].mode_edge, mode_edge); + assert_eq!(heap.named_value(graph.meta, "__mode")?, Value::string("k")); + assert_original_carrier(heap, graph.weak, "a", graph.target, &graph.target_carrier)?; + assert_eq!( + heap.refill_published_gap(graph.weak, "solid", graph.target), + Err(HeapError::SweepPending), + "a non-gap is still refused" + ); + Ok(()) + }) + .expect("refilled without touching mode"); + }); +} + +/// After the tail, clearing the target's only strong edge lets the next real +/// collection release it. The weak edge becomes a gap again. +#[test] +fn published_refill_releases_the_target_after_its_strong_root_is_cleared() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_graph(&mut host); + let resources = host.resource_count(); + publish_two_gaps(&mut host, &graph); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.target), + Ok(true) + ); + let report = finish_tail(&mut host); + assert_eq!(report.live_nodes, 8); + heap::with_heap(&mut host, |heap| { + heap.set_named_scalar(graph.keeper, "hold", Value::Null)?; + Ok(()) + }) + .expect("drop the strong edge"); + let cleaned = heap::collect(&mut host).expect("next cycle"); + assert_eq!( + cleaned.live_nodes, 7, + "the refilled target is actually released" + ); + assert!(!token_open(&mut host, graph.target_token)); + assert_eq!(host.resource_count(), resources - 3); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(graph.target)); + assert_ne!( + slot_generation(heap, graph.target), + graph.target.generation() + ); + assert!(utf8_gap(heap, graph.weak, "a")); + assert!(utf8_gap(heap, graph.weak, "solid")); + assert_eq!(heap.named_value(graph.weak, "a")?, Value::Null); + assert!(heap.alive(graph.successor)); + assert!(heap.alive(graph.keeper)); + Ok(()) + }) + .expect("cleaned"); + }); +} + +/// Omitting the refill leaves the gap. The strong root keeps the target, and +/// the next collection does not invent a value. +#[test] +fn omitted_refill_keeps_the_gap_and_the_strong_target() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_graph(&mut host); + publish_two_gaps(&mut host, &graph); + let report = finish_tail(&mut host); + assert_eq!(report.live_nodes, 8); + let collected = heap::collect(&mut host).expect("omitted followup"); + assert_eq!(collected.live_nodes, 8); + assert!(token_open(&mut host, graph.target_token)); + heap::with_heap(&mut host, |heap| { + assert!(utf8_gap(heap, graph.weak, "a")); + assert_eq!(heap.named_value(graph.weak, "a")?, Value::Null); + assert!(heap.alive(graph.target)); + assert_eq!(heap.named_edge(graph.keeper, "hold")?, Some(graph.target)); + Ok(()) + }) + .expect("omitted"); + }); +} From 1b20b4d574c28f08897cfc9416a7371893393188 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 10:27:37 +0800 Subject: [PATCH 122/225] feat(lua/heap): step one private cycle from a saved mark to its tail Open one saved mark, spend each call's budget on that mark or the published tail, and close tokens only when the mark finishes. --- src/frontends/lua/heap.rs | 88 +++ src/frontends/lua/heap/table.rs | 8 + src/frontends/lua/heap/table/mark.rs | 6 + tests/luajit_heap_runtime/step_cycle.rs | 690 ++++++++++++++++++++++++ 4 files changed, 792 insertions(+) create mode 100644 tests/luajit_heap_runtime/step_cycle.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index ce5c4c8..a61366c 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -221,6 +221,17 @@ fn collect_until_published(host: &mut HostContext) -> Result Result { for token in marked.tokens { retire_doomed_token(host, token)?; } @@ -264,6 +275,83 @@ fn resume_published_sweep( } } +/// One call of a private host step cycle. +/// +/// `Paused { tail: false }` is a saved mark. `Paused { tail: true }` is a +/// published release tail. Published counts are not a pause signal: a zero +/// edge window is still [`StepOutcome::Published`] when a dead slot remains. +#[derive(Debug)] +enum StepOutcome { + /// This call did not finish the saved mark or the saved tail. + Paused { tail: bool }, + /// The mark finished and weak edges were published. Release did not start. + Published { + window_heads: u64, + window_edges: u64, + }, + /// The cycle finished in this call. The report was recorded once. + Completed(table::CollectReport), +} + +/// Saves one mark. Does not scan, install a heap, or clear an existing mark or tail. +fn open_private_step_cycle(host: &mut HostContext) -> Result<(), HeapError> { + let Some(heap) = host.scope_state_mut::() else { + return Err(HeapError::SweepDenied); + }; + heap.open_private_step() +} + +/// Advances one private cycle by `budget`. +/// +/// No heap is [`HeapError::SweepDenied`] and installs nothing. A heap with +/// neither a saved mark nor a sweep tail, including after completion, is +/// [`HeapError::MarkDenied`]. A saved tail is resumed first; that path does +/// not read `batch`. Zero budget does not read `batch` or the graph. A +/// positive mark budget uses the existing batch check before any scan. +/// Finishing the mark closes tokens and publishes in this call. Pending-close +/// enumeration, per-token close, and the Owners walk are metered on their own +/// fields and are not limited by `budget`. Close failure returns the original +/// error and does not restore the taken mark. This call does not resume a +/// tail it just published. +fn step_private_cycle( + host: &mut HostContext, + budget: u64, + batch: &[table::Rooted], +) -> Result { + let (tail, saved) = { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + (heap.has_sweep_tail(), heap.has_saved_mark()) + }; + if tail { + return match resume_published_sweep(host, budget)? { + PublishedResume::Paused => Ok(StepOutcome::Paused { tail: true }), + PublishedResume::Completed(report) => Ok(StepOutcome::Completed(report)), + }; + } + if !saved { + return Err(HeapError::MarkDenied); + } + if budget == 0 { + return Ok(StepOutcome::Paused { tail: false }); + } + let marked = with_heap(host, |heap| heap.take_finished_saved_mark(budget, batch))?; + let Some(marked) = marked else { + return Ok(StepOutcome::Paused { tail: false }); + }; + match close_then_halt_at_publish(host, marked)? { + PublishedBoundary::Completed(report) => Ok(StepOutcome::Completed(report)), + PublishedBoundary::Published { + window_heads, + window_edges, + } => Ok(StepOutcome::Published { + window_heads, + window_edges, + }), + } +} + /// Deletes one ordinary UTF-8 named field while this scope's published sweep /// tail is saved. Does not install a heap and does not resume the tail. /// diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 2d8835d..2b51673 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2218,6 +2218,11 @@ impl LuaHeap { } } + /// Saves one mark for a private step cycle. Does not scan. + pub(super) fn open_private_step(&mut self) -> Result<(), HeapError> { + mark::ParkedMark::open_saved(self) + } + /// Marks once, then drains the pending-close enumerator. Each slot check /// is one scan unit. The drain finishes before this returns, so host close /// still sees every doomed token and the original mark snapshot. A partial @@ -2773,3 +2778,6 @@ mod resume_cycle; #[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/safepoint_roots.rs"] mod safepoint_roots; +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/step_cycle.rs"] +mod step_cycle; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index bd4aa59..b4f2ee6 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -253,6 +253,12 @@ impl<'a> ParkedMark<'a> { Ok(()) } + /// Opens one saved mark and parks it. Does not scan. + /// Refusal leaves the heap unchanged. + pub(super) fn open_saved(heap: &'a mut LuaHeap) -> Result<(), HeapError> { + Self::start(heap)?.park() + } + pub(super) fn meter(&self) -> super::ScanMeter { self.heap.scan } diff --git a/tests/luajit_heap_runtime/step_cycle.rs b/tests/luajit_heap_runtime/step_cycle.rs new file mode 100644 index 0000000..f146f17 --- /dev/null +++ b/tests/luajit_heap_runtime/step_cycle.rs @@ -0,0 +1,690 @@ +//! One private host step cycle. +//! +//! `open_private_step_cycle` saves a mark and does not scan. `step_private_cycle` +//! spends the call budget on that mark, or on an already published tail. The +//! batch is borrowed for the call only. Pending-close enumeration, token close, +//! and the Owners walk stay on their own meters and are not capped by the budget. + +use std::sync::Arc; + +use super::ParkedMark; +use vm::Value; + +use crate::heap::{ + self, HeapError, HeapLimits, LuaHeap, ScanMeter, StepOutcome, TableRef, + open_private_step_cycle, step_private_cycle, +}; + +const BOUND: u32 = 64; + +fn limits() -> HeapLimits { + HeapLimits { + nodes: 8, + roots: 4, + edges: 8, + max_generation: 8, + } +} + +fn publish(host: &mut vm::HostContext<'_>) -> (TableRef, i64) { + let raw = crate::publish_raw(host); + (crate::table_ref(host, raw), raw) +} + +fn token_open(host: &mut vm::HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + crate::resource_handle(raw), + &heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn slot_generation(heap: &LuaHeap, table: TableRef) -> u32 { + heap.slots[table.slot() as usize].generation +} + +fn clear_meter(host: &mut vm::HostContext<'_>) -> ScanMeter { + heap::take_scan_meter(host).expect("meter") +} + +fn phase_name(host: &mut vm::HostContext<'_>) -> String { + heap::with_heap(host, |heap| { + let parked = ParkedMark::resume(heap).expect("saved mark"); + let name = parked.phase_name().to_string(); + let open = parked.mutation_open(); + parked.park().expect("park"); + assert!(!open || name == "roots" || name == "gray"); + Ok(name) + }) + .expect("phase") +} + +fn has_tail(host: &mut vm::HostContext<'_>) -> bool { + heap::with_heap(host, |heap| Ok(heap.has_sweep_tail())).expect("tail") +} + +fn marked(host: &mut vm::HostContext<'_>, table: TableRef) -> bool { + heap::with_heap(host, |heap| { + let parked = ParkedMark::resume(heap).expect("saved mark"); + let marked = parked.marked(table); + parked.park().expect("park"); + Ok(marked) + }) + .expect("marked") +} + +fn foreign_table() -> TableRef { + let mut other = LuaHeap::new(HeapLimits { + nodes: 2, + roots: 1, + edges: 1, + max_generation: 2, + }); + other.alloc().expect("foreign") +} + +fn finish(host: &mut vm::HostContext<'_>, batch: &[super::Rooted]) -> heap::CollectReport { + for _ in 0..BOUND { + match step_private_cycle(host, 1, batch).expect("step") { + StepOutcome::Paused { .. } | StepOutcome::Published { .. } => {} + StepOutcome::Completed(report) => return report, + } + } + panic!("bounded loop did not finish the cycle"); +} + +#[test] +fn budget_one_pauses_mark_then_one_tail_unit_finishes_once() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let meta = heap::with_heap(&mut host, LuaHeap::alloc).expect("meta"); + let (owner, owner_token) = publish(&mut host); + let (live, live_token) = publish(&mut host); + let (weak, weak_token) = publish(&mut host); + let (extra, extra_token) = publish(&mut host); + let (orphan, orphan_token) = publish(&mut host); + let weak_generation = weak.generation(); + let extra_generation = extra.generation(); + let orphan_generation = orphan.generation(); + let (carrier, frame) = heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "gone", weak)?; + let frame = heap.enter_roots(3)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, live)?; + let carrier = heap.issue_carrier(live)?; + Ok((carrier, frame)) + }) + .expect("graph"); + let Value::Array(carrier) = carrier else { + panic!("live carrier is the issued array"); + }; + let resources_before = host.resource_count(); + clear_meter(&mut host); + open_private_step_cycle(&mut host).expect("open"); + + let illegal = [super::Rooted::Table(foreign_table())]; + let zero = + step_private_cycle(&mut host, 0, &illegal).expect("zero does not read the batch"); + assert!(matches!(zero, StepOutcome::Paused { tail: false })); + assert_eq!(clear_meter(&mut host), ScanMeter::default()); + assert_eq!(phase_name(&mut host), "start"); + assert!(!has_tail(&mut host)); + + let first = step_private_cycle(&mut host, 1, &[]).expect("budget 1"); + assert!( + matches!(first, StepOutcome::Paused { tail: false }), + "budget 1 only advances mark, got {first:?}" + ); + let started = clear_meter(&mut host); + assert_eq!(started.mark_passes, 1, "one mark start"); + assert_eq!(started.parked_root_batch_accepts, 0); + assert_eq!(started.token_closes, 0); + assert_eq!(started.scratch.pending_close_pushed, 0); + assert_eq!(started.sweep_edge_checks, 0); + assert_eq!(started.scratch.dead_slots_pushed, 0); + assert_eq!(phase_name(&mut host), "mode-open"); + assert!(!has_tail(&mut host)); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + + let again = step_private_cycle(&mut host, 0, &illegal).expect("zero after a pause"); + assert!(matches!(again, StepOutcome::Paused { tail: false })); + assert_eq!(clear_meter(&mut host), ScanMeter::default()); + assert_eq!(phase_name(&mut host), "mode-open"); + + let mut published = None; + let mut publish_meter = None; + for _ in 0..BOUND { + clear_meter(&mut host); + let outcome = step_private_cycle(&mut host, 1, &[]).expect("mark step"); + if matches!(outcome, StepOutcome::Published { .. }) { + published = Some(outcome); + publish_meter = Some(clear_meter(&mut host)); + break; + } + assert!( + matches!(outcome, StepOutcome::Paused { tail: false }), + "small budgets stay in mark until publish, got {outcome:?}" + ); + } + let StepOutcome::Published { + window_heads, + window_edges, + } = published.expect("publish is a phase, not a step-count guess") + else { + unreachable!("loop only stores Published"); + }; + assert_eq!(window_heads, 6, "one owner head per slot"); + assert_eq!(window_edges, 2, "mode edge and the weak named edge"); + let publish_meter = publish_meter.expect("publish meter"); + assert_eq!( + publish_meter.mark_passes, 0, + "publish does not start another mark" + ); + assert_eq!( + publish_meter.scratch.pending_close_pushed, 3, + "pending-close enumeration is listed apart from the budget" + ); + assert_eq!( + publish_meter.token_closes, 3, + "every doomed token closes in this call, not one per budget" + ); + assert_eq!(publish_meter.sweep_edge_checks, window_edges); + assert!( + publish_meter.owner_head_checks >= window_heads, + "Owners walks every slot; budget 1 does not cap that walk" + ); + assert_eq!(publish_meter.scratch.dead_slots_pushed, 3); + assert_eq!(publish_meter.scratch.sweep_bitmap_inited, window_heads); + assert_eq!( + publish_meter.parked_root_batch_accepts, 0, + "the orphan was not admitted" + ); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + assert!(has_tail(&mut host)); + assert!(!token_open(&mut host, weak_token)); + assert!(!token_open(&mut host, extra_token)); + assert!(!token_open(&mut host, orphan_token)); + assert!(token_open(&mut host, live_token)); + assert!(token_open(&mut host, owner_token)); + assert_eq!(host.resource_count(), resources_before - 3); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.named_edge(owner, "gone")?, None, "weak value is nil"); + assert!(heap.alive(weak) && heap.alive(extra) && heap.alive(orphan)); + assert_eq!(slot_generation(heap, weak), weak_generation); + assert_eq!(slot_generation(heap, extra), extra_generation); + assert_eq!(slot_generation(heap, orphan), orphan_generation); + assert!(heap.alive(live)); + Ok(()) + }) + .expect("published occupancy"); + + clear_meter(&mut host); + let tail_zero = + step_private_cycle(&mut host, 0, &illegal).expect("tail zero ignores batch"); + assert!(matches!(tail_zero, StepOutcome::Paused { tail: true })); + assert_eq!(clear_meter(&mut host), ScanMeter::default()); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(weak))).expect("still physical")); + + let roots_before = heap::stats(&mut host).expect("roots").root_slots; + let entered = heap::with_heap(&mut host, |heap| heap.enter_roots(1)); + assert_eq!(entered, Err(HeapError::SweepPending)); + let left = heap::with_heap(&mut host, |heap| heap.leave_roots(frame)); + assert_eq!(left, Err(HeapError::SweepPending)); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.current_frame(), Some(frame)); + assert_eq!(heap.stats().root_slots, roots_before); + Ok(()) + }) + .expect("frame stays"); + assert_eq!( + open_private_step_cycle(&mut host), + Err(HeapError::SweepPending) + ); + assert!(has_tail(&mut host)); + + clear_meter(&mut host); + let one = + step_private_cycle(&mut host, 1, &illegal).expect("tail ignores an illegal batch"); + assert!(matches!(one, StepOutcome::Paused { tail: true })); + let release = clear_meter(&mut host); + assert_eq!(release.node_slot_visits, 1); + assert_eq!(release.root_slot_visits, 0); + assert_eq!(release.owner_head_checks, 0); + assert_eq!(release.sweep_edge_checks, 0); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(weak), "budget 1 releases the first dead slot"); + assert_ne!(slot_generation(heap, weak), weak_generation); + assert!(heap.alive(extra) && heap.alive(orphan)); + assert_eq!(slot_generation(heap, extra), extra_generation); + Ok(()) + }) + .expect("one release"); + + let mut completed = None; + for _ in 0..BOUND { + match step_private_cycle(&mut host, 1, &illegal).expect("tail") { + StepOutcome::Paused { tail: true } => {} + StepOutcome::Completed(report) => { + completed = Some(report); + break; + } + other => panic!("tail does not publish again, got {other:?}"), + } + } + let report = completed.expect("one completion report"); + assert_eq!(report.live_nodes, 3); + assert_eq!(report.live_roots, 3); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + assert!(!has_tail(&mut host)); + let Value::Array(after) = + heap::with_heap(&mut host, |heap| heap.issued_value(live)).expect("carrier") + else { + panic!("survivor carrier is still an array"); + }; + assert!( + Arc::ptr_eq(&carrier, &after), + "survivor carrier pointer is unchanged" + ); + heap::with_heap(&mut host, |heap| { + assert!(heap.alive(live) && heap.alive(owner) && heap.alive(meta)); + assert!(!heap.alive(weak) && !heap.alive(extra) && !heap.alive(orphan)); + Ok(()) + }) + .expect("released"); + assert!(matches!( + step_private_cycle(&mut host, 1, &[]), + Err(HeapError::MarkDenied) + )); + }); +} + +#[test] +fn no_dead_slot_completes_without_a_published_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let (live, _) = publish(&mut host); + heap::with_heap(&mut host, |heap| { + let frame = heap.enter_roots(1)?; + heap.write_root(frame, 0, live)?; + Ok(()) + }) + .expect("root"); + open_private_step_cycle(&mut host).expect("open"); + let mut published = false; + let mut report = None; + for _ in 0..BOUND { + match step_private_cycle(&mut host, 1, &[]).expect("step") { + StepOutcome::Paused { tail: false } => {} + StepOutcome::Published { .. } => published = true, + StepOutcome::Completed(done) => { + report = Some(done); + break; + } + other => panic!("unexpected {other:?}"), + } + } + assert!(!published, "no dead slot must not publish a tail"); + assert_eq!(report.expect("completed").live_nodes, 1); + assert!(!has_tail(&mut host)); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + assert!(matches!( + step_private_cycle(&mut host, 1, &[]), + Err(HeapError::MarkDenied) + )); + }); +} + +#[test] +fn dead_slots_without_weak_edges_still_publish_a_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let (live, _) = publish(&mut host); + let (dead, dead_token) = publish(&mut host); + let (other, other_token) = publish(&mut host); + heap::with_heap(&mut host, |heap| { + let frame = heap.enter_roots(1)?; + heap.write_root(frame, 0, live)?; + Ok(()) + }) + .expect("root"); + open_private_step_cycle(&mut host).expect("open"); + let mut published = None; + for _ in 0..BOUND { + match step_private_cycle(&mut host, 1, &[]).expect("step") { + StepOutcome::Paused { tail: false } => {} + StepOutcome::Published { + window_heads, + window_edges, + } => { + published = Some((window_heads, window_edges)); + break; + } + other => panic!("zero edges must not be treated as a pause, got {other:?}"), + } + } + let (heads, edges) = published.expect("published tail"); + assert_eq!(heads, 3); + assert_eq!(edges, 0, "a zero edge count is still the published phase"); + assert!(has_tail(&mut host)); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + assert!(!token_open(&mut host, dead_token)); + assert!(!token_open(&mut host, other_token)); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.alive(dead) && heap.alive(other))) + .expect("physical") + ); + let paused = step_private_cycle(&mut host, 0, &[]).expect("tail saved"); + assert!(matches!(paused, StepOutcome::Paused { tail: true })); + }); +} + +#[test] +fn reset_budget_keeps_the_next_batch_and_the_fixed_frame_until_the_next_cycle() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 8, + roots: 4, + edges: 4, + max_generation: 8, + }, + ) + .expect("install"); + let (frame_root, _) = publish(&mut host); + let (first, _) = publish(&mut host); + let (second, _) = publish(&mut host); + let frame = heap::with_heap(&mut host, |heap| { + let frame = heap.enter_roots(1)?; + heap.write_root(frame, 0, frame_root)?; + Ok(frame) + }) + .expect("frame"); + open_private_step_cycle(&mut host).expect("open"); + + let paused = step_private_cycle(&mut host, 1, &[super::Rooted::Table(first)]).expect("A"); + assert!(matches!(paused, StepOutcome::Paused { tail: false })); + let meter = clear_meter(&mut host); + assert_eq!(meter.mark_passes, 1); + assert_eq!(meter.parked_root_batch_accepts, 0, "A was not admitted"); + assert_eq!(phase_name(&mut host), "reset"); + assert!(!marked(&mut host, first)); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.alive(frame_root))).expect("frame root")); + + let mut admitted = false; + for _ in 0..BOUND { + let outcome = + step_private_cycle(&mut host, 1, &[super::Rooted::Table(second)]).expect("B"); + let meter = clear_meter(&mut host); + if meter.parked_root_batch_accepts == 1 { + assert!(matches!( + outcome, + StepOutcome::Paused { tail: false } | StepOutcome::Published { .. } + )); + let name = phase_name(&mut host); + assert!( + name == "roots" || name == "gray", + "B is admitted in roots/gray, got {name}" + ); + assert!(marked(&mut host, second)); + assert!(!marked(&mut host, first)); + admitted = true; + break; + } + assert!(matches!(outcome, StepOutcome::Paused { tail: false })); + } + assert!(admitted, "B must be admitted before the cycle ends"); + let report = finish(&mut host, &[super::Rooted::Table(second)]); + assert_eq!(report.live_nodes, 2, "frame root and B stay"); + heap::with_heap(&mut host, |heap| { + assert!(heap.alive(frame_root) && heap.alive(second)); + assert!(!heap.alive(first), "A was never admitted"); + heap.leave_roots(frame)?; + Ok(()) + }) + .expect("leave after completion"); + + open_private_step_cycle(&mut host).expect("next cycle"); + let _ = finish(&mut host, &[]); + assert!(!heap::with_heap(&mut host, |heap| Ok(heap.alive(frame_root))).expect("collected")); + }); +} + +#[test] +fn omitted_collection_keeps_the_weak_value_and_token() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let meta = heap::with_heap(&mut host, LuaHeap::alloc).expect("meta"); + let (owner, _) = publish(&mut host); + let (weak, weak_token) = publish(&mut host); + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "gone", weak)?; + let frame = heap.enter_roots(2)?; + heap.write_root(frame, 0, meta)?; + heap.write_root(frame, 1, owner)?; + assert_eq!(heap.named_edge(owner, "gone")?, Some(weak)); + Ok(()) + }) + .expect("control"); + assert!(token_open(&mut host, weak_token)); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + assert!( + host.scope_state::() + .is_some_and(|heap| heap.mark.is_none()) + ); + }); +} + +#[test] +fn missing_heap_refuses_open_and_step_without_installing() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + assert!(host.scope_state::().is_none()); + assert_eq!( + open_private_step_cycle(&mut host), + Err(HeapError::SweepDenied) + ); + assert!(host.scope_state::().is_none()); + assert!(matches!( + step_private_cycle(&mut host, 1, &[]), + Err(HeapError::SweepDenied) + )); + assert!(host.scope_state::().is_none()); + }); +} + +#[test] +fn repeat_open_refuses_a_saved_mark() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + open_private_step_cycle(&mut host).expect("open"); + assert_eq!(phase_name(&mut host), "start"); + assert_eq!( + open_private_step_cycle(&mut host), + Err(HeapError::MarkActive) + ); + assert_eq!(phase_name(&mut host), "start"); + assert!(!has_tail(&mut host)); + }); +} + +#[test] +fn illegal_batch_is_refused_before_the_scan() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let (live, _) = publish(&mut host); + let stale = heap::with_heap(&mut host, |heap| { + let stale = heap.alloc()?; + heap.rollback(stale)?; + Ok(stale) + }) + .expect("stale"); + open_private_step_cycle(&mut host).expect("open"); + clear_meter(&mut host); + + let foreign = step_private_cycle( + &mut host, + 1, + &[ + super::Rooted::Table(live), + super::Rooted::Table(foreign_table()), + ], + ); + assert!(matches!(foreign, Err(HeapError::WrongDomain))); + assert_eq!(clear_meter(&mut host), ScanMeter::default()); + assert_eq!(phase_name(&mut host), "start"); + assert!(!marked(&mut host, live)); + + let stale = step_private_cycle( + &mut host, + 1, + &[super::Rooted::Table(live), super::Rooted::Table(stale)], + ); + assert!(matches!(stale, Err(HeapError::StaleHandle))); + assert_eq!(clear_meter(&mut host), ScanMeter::default()); + assert_eq!(phase_name(&mut host), "start"); + assert!(!marked(&mut host, live)); + }); + + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install( + &mut host, + HeapLimits { + nodes: 4, + roots: 1, + edges: 1, + max_generation: 4, + }, + ) + .expect("install"); + let (first, _) = publish(&mut host); + let (second, _) = publish(&mut host); + open_private_step_cycle(&mut host).expect("open"); + clear_meter(&mut host); + let over = step_private_cycle( + &mut host, + 1, + &[super::Rooted::Table(first), super::Rooted::Table(second)], + ); + assert!(matches!(over, Err(HeapError::RootCapacity))); + assert_eq!(clear_meter(&mut host), ScanMeter::default()); + assert_eq!(phase_name(&mut host), "start"); + assert!(!marked(&mut host, first)); + assert!(!marked(&mut host, second)); + }); +} + +#[test] +fn close_obstacle_keeps_the_prefix_and_reopen_fails_until_removed() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, crate::sweep_limits()).expect("install"); + let unrelated = host + .push_resource(crate::UnrelatedHostResource) + .expect("unrelated"); + let unrelated_raw = unrelated.handle().raw(); + let (keeper, _) = publish(&mut host); + crate::root_table(&mut host, keeper); + let (prefix, prefix_raw) = publish(&mut host); + let (other, other_raw) = publish(&mut host); + let doomed = heap::with_heap(&mut host, |heap| { + let node = heap.alloc()?; + heap.bind_token(node, unrelated_raw)?; + Ok(node) + }) + .expect("foreign token"); + let (suffix, suffix_raw) = publish(&mut host); + let before_resources = host.resource_count(); + open_private_step_cycle(&mut host).expect("open"); + + let (error, meter) = step_until_close_fails(&mut host); + crate::assert_type_mismatch(&error); + assert_eq!( + meter.token_closes, 3, + "prefix, other, and the foreign attempt" + ); + assert_eq!(meter.scratch.pending_close_pushed, 4); + assert_eq!(meter.sweep_edge_checks, 0, "close failure does not publish"); + assert_eq!(meter.scratch.dead_slots_pushed, 0); + assert!(!has_tail(&mut host)); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + assert!(host.resource(&unrelated).is_ok()); + assert!(!token_open(&mut host, prefix_raw)); + assert!(!token_open(&mut host, other_raw)); + assert!(token_open(&mut host, suffix_raw)); + let resources_after_failure = host.resource_count(); + assert_eq!(resources_after_failure, before_resources - 2); + heap::with_heap(&mut host, |heap| { + assert!( + ParkedMark::resume(heap).is_none(), + "taken mark is not restored" + ); + assert!(heap.alive(prefix) && heap.alive(doomed) && heap.alive(suffix)); + Ok(()) + }) + .expect("prefix stays physical"); + + open_private_step_cycle(&mut host).expect("explicit reopen starts a new cycle"); + let (again, again_meter) = step_until_close_fails(&mut host); + crate::assert_type_mismatch(&again); + assert_eq!( + again_meter.token_closes, 1, + "only the foreign token is attempted" + ); + assert_eq!(again_meter.scratch.pending_close_pushed, 2); + assert_eq!(again_meter.sweep_edge_checks, 0); + assert_eq!( + host.resource_count(), + resources_after_failure, + "closed prefix quota is not returned again" + ); + assert!(token_open(&mut host, suffix_raw)); + assert!(!has_tail(&mut host)); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + + heap::with_heap(&mut host, |heap| heap.unbind_token(doomed)).expect("fixture unbind"); + crate::root_table(&mut host, prefix); + open_private_step_cycle(&mut host).expect("recover"); + let report = finish(&mut host, &[]); + assert_eq!( + report.live_nodes, 2, + "keeper and the newly rooted prefix stay" + ); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + assert!(!token_open(&mut host, suffix_raw)); + assert_eq!(host.resource_count(), resources_after_failure - 1); + assert!(host.resource(&unrelated).is_ok()); + heap::with_heap(&mut host, |heap| { + assert!(heap.alive(keeper) && heap.alive(prefix)); + assert!(!heap.alive(other) && !heap.alive(doomed) && !heap.alive(suffix)); + Ok(()) + }) + .expect("recovered"); + }); +} + +fn step_until_close_fails(host: &mut vm::HostContext<'_>) -> (HeapError, ScanMeter) { + for _ in 0..BOUND { + clear_meter(host); + match step_private_cycle(host, 1, &[]) { + Err(error) => return (error, clear_meter(host)), + Ok(StepOutcome::Paused { tail: false }) => {} + Ok(other) => panic!("close obstacle must not publish, got {other:?}"), + } + } + panic!("bounded loop did not reach the close obstacle"); +} From cdd6a351d18b6597fa17015c04582c7038b72130 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 11:17:19 +0800 Subject: [PATCH 123/225] feat(lua/heap): retire one top root frame during a published sweep tail Drop the top frame from a saved tail without resuming the sweep: Release keeps the dead cursor, and Roots deducts only the scanned prefix. --- src/frontends/lua/heap.rs | 22 + src/frontends/lua/heap/table.rs | 49 + src/frontends/lua/heap/table/sweep.rs | 46 + .../published_root_frame_retirement.rs | 847 ++++++++++++++++++ 4 files changed, 964 insertions(+) create mode 100644 tests/luajit_heap_runtime/published_root_frame_retirement.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index a61366c..9c27d1a 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -352,6 +352,28 @@ fn step_private_cycle( } } +/// Drops the top root frame while this scope's published sweep tail is saved. +/// +/// No heap is [`HeapError::SweepDenied`] and installs nothing. An installed +/// heap checks the frame before the tail: no frame is [`HeapError::NoRootFrame`], +/// a non-top or old generation is [`HeapError::StaleFrame`], and a valid top +/// frame with no tail is [`HeapError::SweepDenied`]. Refusal does not move the +/// cursor, counts, root vector, or frame stack. +/// +/// Release keeps the dead cursor and the accumulated counts. Roots deducts +/// `Some` tags already scanned in this frame, including duplicates, then clamps +/// the root cursor downward. This does not look up nodes, rescan roots, advance +/// the sweep, or roll back the scan meter. Not a guest `collectgarbage` step. +fn retire_published_root_frame( + host: &mut HostContext, + frame: table::RootFrameId, +) -> Result { + if host.scope_state::().is_none() { + return Err(HeapError::SweepDenied); + } + with_heap(host, |heap| heap.retire_published_root_frame(frame)) +} + /// Deletes one ordinary UTF-8 named field while this scope's published sweep /// tail is saved. Does not install a heap and does not resume the tail. /// diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 2b51673..8501be0 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -182,6 +182,21 @@ pub struct CollectReport { pub live_roots: u32, } +/// Accounting for one top frame removed during a saved published tail. +/// +/// Each field is this retirement only. None of them is a scan unit, and none +/// of them replaces the cycle report. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct FrameRetirement { + /// The tail was still releasing dead slots, so the dead cursor stayed put. + pub(super) release_phase: bool, + /// Scanned slots of this frame. Zero in Release, and zero when the root + /// cursor has not entered the frame. + pub(super) prefix_slots: u32, + /// `Some` tags in that prefix. A repeated handle counts once per slot. + pub(super) dropped_live: u32, +} + /// Identity of one explicit root frame. Frames are a stack. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RootFrameId { @@ -2107,6 +2122,37 @@ impl LuaHeap { Ok(()) } + /// Drops the top frame while a published tail is saved. + /// + /// The frame is checked before the tail. No frame is [`HeapError::NoRootFrame`]. + /// A frame that is not top, or an old generation, is [`HeapError::StaleFrame`]. + /// A valid top frame with no tail is [`HeapError::SweepDenied`]. Refusal + /// does not change the cursor, counts, root vector, or frame stack. + /// + /// On success the tail adjusts its own prefix, then this truncates the root + /// vector to the frame start and pops the frame. It does not resume the sweep. + pub(super) fn retire_published_root_frame( + &mut self, + frame: RootFrameId, + ) -> Result { + let (start, width) = { + let top = self.frames.last().ok_or(HeapError::NoRootFrame)?; + if top.index != frame.index || top.generation != frame.generation { + return Err(HeapError::StaleFrame); + } + if self.sweep_tail.is_none() { + return Err(HeapError::SweepDenied); + } + (top.start as usize, top.width as usize) + }; + let mut tail = self.sweep_tail.take().expect("published tail"); + let retirement = tail.retire_frame_prefix(&self.roots, start, width); + self.sweep_tail = Some(tail); + self.roots.truncate(start); + self.frames.pop(); + Ok(retirement) + } + /// Records the typed token that owns `table`. The handle is not installed /// as a root. pub fn bind_token(&mut self, table: TableRef, raw: u64) -> Result<(), HeapError> { @@ -2770,6 +2816,9 @@ mod published_late_allocation; #[path = "../../../../tests/luajit_heap_runtime/published_refill.rs"] mod published_refill; #[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/published_root_frame_retirement.rs"] +mod published_root_frame_retirement; +#[cfg(test)] #[path = "../../../../tests/luajit_heap_runtime/published_sweep.rs"] mod published_sweep; #[cfg(test)] diff --git a/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs index ffdbb51..4a55b95 100644 --- a/src/frontends/lua/heap/table/sweep.rs +++ b/src/frontends/lua/heap/table/sweep.rs @@ -135,6 +135,52 @@ impl SweepTail { pub(super) fn note_late(&mut self) { self.late_nodes = self.late_nodes.saturating_add(1); } + + /// Adjusts the saved cursor for one retiring top frame. + /// + /// Release keeps the dead cursor and the accumulated counts. Roots counts + /// `Some` tags in the scanned overlap of this frame, including duplicates, + /// then clamps the cursor downward. A cursor that has not entered the frame + /// is not sliced and is not moved forward. This does not read nodes or the + /// scan meter. + pub(super) fn retire_frame_prefix( + &mut self, + roots: &[Option], + start: usize, + width: usize, + ) -> super::FrameRetirement { + debug_assert!( + matches!(self.phase, TailPhase::Release | TailPhase::Roots), + "a saved tail is release or roots" + ); + if matches!(self.phase, TailPhase::Release) { + return super::FrameRetirement { + release_phase: true, + prefix_slots: 0, + dropped_live: 0, + }; + } + let index = self.index; + if index <= start { + self.index = index.min(start); + return super::FrameRetirement { + release_phase: false, + prefix_slots: 0, + dropped_live: 0, + }; + } + let frame_end = start.saturating_add(width); + let slice_end = index.min(frame_end).min(roots.len()); + let overlap = roots.get(start..slice_end).unwrap_or(&[]); + let dropped_live = overlap.iter().filter(|slot| slot.is_some()).count() as u32; + self.live_roots = self.live_roots.saturating_sub(dropped_live); + self.index = index.min(start); + super::FrameRetirement { + release_phase: false, + prefix_slots: overlap.len() as u32, + dropped_live, + } + } } /// One release, root, or uncharged transition. Callers share this with [`SweepSession`]. diff --git a/tests/luajit_heap_runtime/published_root_frame_retirement.rs b/tests/luajit_heap_runtime/published_root_frame_retirement.rs new file mode 100644 index 0000000..48d16fc --- /dev/null +++ b/tests/luajit_heap_runtime/published_root_frame_retirement.rs @@ -0,0 +1,847 @@ +//! One top root frame retired during a saved published sweep tail. +//! +//! The host entry is private. It does not install a heap, resume the sweep, +//! look up nodes, or roll back the scan meter. Release keeps the dead cursor. +//! Roots deducts only `Some` tags already scanned in the retiring frame. + +use std::sync::Arc; + +use vm::Value; + +use crate::heap::{ + self, HeapError, HeapLimits, LuaHeap, ScanMeter, StepOutcome, TableRef, + open_private_step_cycle, retire_published_root_frame, step_private_cycle, +}; + +const BOUND: u32 = 64; +const LOWER_SOME: u32 = 4; +const TOP_SOME: u32 = 3; +const ROOT_SLOTS: usize = 8; + +#[derive(Debug)] +struct TailFacts { + phase: String, + index: usize, + dead_len: usize, + live_roots: u32, + marked_nodes: u32, + late_nodes: u32, +} + +struct Graph { + owner: TableRef, + subject: TableRef, + subject_token: i64, + dead_a: TableRef, + dead_a_generation: u32, + dead_b: TableRef, + dead_b_generation: u32, + lower: super::RootFrameId, + top: super::RootFrameId, + carrier: Arc>, +} + +fn limits() -> HeapLimits { + HeapLimits { + nodes: 16, + roots: 8, + edges: 16, + max_generation: 8, + } +} + +fn publish(host: &mut vm::HostContext<'_>) -> (TableRef, i64) { + let raw = crate::publish_raw(host); + (crate::table_ref(host, raw), raw) +} + +fn token_open(host: &mut vm::HostContext<'_>, raw: i64) -> bool { + host.typed_resource_with_key::( + crate::resource_handle(raw), + &heap::LuaTableResource::key(), + ) + .is_ok() +} + +fn clear_meter(host: &mut vm::HostContext<'_>) -> ScanMeter { + heap::take_scan_meter(host).expect("meter") +} + +fn parse_tail(text: &str) -> TailFacts { + assert!( + text.starts_with("Some("), + "expected a saved tail, got {text}" + ); + let phase = field_token(text, "phase"); + let dead = dead_body(text); + TailFacts { + phase, + index: field_usize(text, "index"), + dead_len: if dead.is_empty() { + 0 + } else { + dead.split(',').count() + }, + live_roots: field_usize(text, "live_roots") as u32, + marked_nodes: field_usize(text, "marked_nodes") as u32, + late_nodes: field_usize(text, "late_nodes") as u32, + } +} + +fn field_token(text: &str, name: &str) -> String { + let marker = format!("{name}: "); + let start = text + .find(&marker) + .unwrap_or_else(|| panic!("no {name} in {text}")); + let rest = &text[start + marker.len()..]; + let end = rest + .find([',', ' ', '}']) + .unwrap_or_else(|| panic!("no end for {name} in {text}")); + rest[..end].to_string() +} + +fn field_usize(text: &str, name: &str) -> usize { + let token = field_token(text, name); + token + .parse() + .unwrap_or_else(|_| panic!("bad {name} token {token} in {text}")) +} + +fn dead_body(text: &str) -> String { + let marker = "dead: ["; + let start = text + .find(marker) + .unwrap_or_else(|| panic!("no dead list in {text}")); + let rest = &text[start + marker.len()..]; + let end = rest + .find(']') + .unwrap_or_else(|| panic!("no dead end in {text}")); + rest[..end].to_string() +} + +fn tail_facts(host: &mut vm::HostContext<'_>) -> TailFacts { + heap::with_heap(host, |heap| { + Ok(parse_tail(&format!("{:?}", heap.sweep_tail))) + }) + .expect("tail") +} + +fn install_graph(host: &mut vm::HostContext<'_>) -> Graph { + heap::install(host, limits()).expect("install"); + let meta = heap::with_heap(host, LuaHeap::alloc).expect("meta"); + let anchor = heap::with_heap(host, LuaHeap::alloc).expect("anchor"); + let lower_peer = heap::with_heap(host, LuaHeap::alloc).expect("lower peer"); + let (owner, _) = publish(host); + let (subject, subject_token) = publish(host); + let (peer, _) = publish(host); + let (dead_a, _) = publish(host); + let (dead_b, _) = publish(host); + let built = heap::with_heap(host, |heap| { + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + heap.set_named_edge(owner, "a", dead_a)?; + heap.set_named_edge(owner, "b", dead_b)?; + heap.set_named_edge(owner, "watch", subject)?; + let lower = heap.enter_roots(4)?; + heap.write_root(lower, 0, meta)?; + heap.write_root(lower, 1, owner)?; + heap.write_root(lower, 2, anchor)?; + heap.write_root(lower, 3, lower_peer)?; + let top = heap.enter_roots(4)?; + heap.write_root(top, 0, subject)?; + heap.write_root(top, 2, subject)?; + heap.write_root(top, 3, peer)?; + let carrier = heap.issue_carrier(subject)?; + Ok(( + heap.slots[dead_a.slot() as usize].generation, + heap.slots[dead_b.slot() as usize].generation, + carrier, + lower, + top, + )) + }) + .expect("graph"); + let (dead_a_generation, dead_b_generation, carrier, lower, top) = built; + let Value::Array(carrier) = carrier else { + panic!("subject carrier is the issued array"); + }; + Graph { + owner, + subject, + subject_token, + dead_a, + dead_a_generation, + dead_b, + dead_b_generation, + lower, + top, + carrier, + } +} + +fn open_and_publish(host: &mut vm::HostContext<'_>) { + clear_meter(host); + open_private_step_cycle(host).expect("open"); + for _ in 0..BOUND { + match step_private_cycle(host, 1, &[]).expect("mark") { + StepOutcome::Paused { tail: false } => {} + StepOutcome::Published { .. } => { + let facts = tail_facts(host); + assert_eq!(facts.phase, "Release"); + assert_eq!(facts.index, 0); + assert_eq!(facts.dead_len, 2, "two weak orphans stay physical"); + assert_eq!(facts.live_roots, 0); + return; + } + other => panic!("small budgets stay in mark until publish, got {other:?}"), + } + } + panic!("publish did not arrive"); +} + +fn step_paused(host: &mut vm::HostContext<'_>) -> ScanMeter { + clear_meter(host); + let outcome = step_private_cycle(host, 1, &[]).expect("tail step"); + assert!( + matches!(outcome, StepOutcome::Paused { tail: true }), + "budget 1 does not finish, got {outcome:?}" + ); + clear_meter(host) +} + +fn drive_roots_index(host: &mut vm::HostContext<'_>, target: usize) { + for _ in 0..BOUND { + let facts = tail_facts(host); + if facts.phase == "Roots" && facts.index == target { + return; + } + if facts.phase == "Roots" && facts.index > target { + panic!("root cursor overshot {target}, got {facts:?}"); + } + let meter = step_paused(host); + if tail_facts(host).phase == "Roots" { + assert_eq!(meter.root_slot_visits, 1, "one root slot per charged step"); + } + } + panic!( + "did not reach roots index {target}, now {:?}", + tail_facts(host) + ); +} + +fn finish(host: &mut vm::HostContext<'_>) -> heap::CollectReport { + for _ in 0..BOUND { + clear_meter(host); + match step_private_cycle(host, 1, &[]).expect("finish") { + StepOutcome::Paused { tail: true } => {} + StepOutcome::Completed(report) => { + assert_eq!( + clear_meter(host), + ScanMeter::default(), + "the report step is uncharged" + ); + return report; + } + other => panic!("a saved tail does not publish again, got {other:?}"), + } + } + panic!("tail did not finish"); +} + +/// All eight root slots are already scanned. Truncate/pop without deducting +/// the three top `Some` tags leaves those slots in the completion report. +#[test] +fn published_root_retirement_drops_scanned_top_slots_from_the_report() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + open_and_publish(&mut host); + drive_roots_index(&mut host, ROOT_SLOTS); + let scanned = tail_facts(&mut host); + assert_eq!(scanned.phase, "Roots"); + assert_eq!(scanned.index, ROOT_SLOTS); + assert_eq!(scanned.live_roots, LOWER_SOME + TOP_SOME); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + let meter_before = heap::with_heap(&mut host, |heap| Ok(heap.scan)).expect("meter"); + + let retired = retire_published_root_frame(&mut host, graph.top).expect("retire top"); + let meter_after = heap::with_heap(&mut host, |heap| Ok(heap.scan)).expect("meter"); + assert_eq!( + meter_after, meter_before, + "retirement does not roll the meter back" + ); + let report = finish(&mut host); + assert_eq!( + ( + report.live_roots, + retired.dropped_live, + retired.prefix_slots, + retired.release_phase, + ), + (LOWER_SOME, TOP_SOME, 4, false), + "truncate/pop without deducting scanned top slots leaves live_roots too large" + ); + assert_eq!(report.marked_nodes, scanned.marked_nodes); + assert_eq!(report.live_nodes, report.marked_nodes); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 1); + let Value::Array(after) = + heap::with_heap(&mut host, |heap| heap.issued_value(graph.subject)).expect("carrier") + else { + panic!("floating subject carrier is still an array"); + }; + assert!(Arc::ptr_eq(&graph.carrier, &after)); + assert!(token_open(&mut host, graph.subject_token)); + assert_eq!( + step_private_cycle(&mut host, 1, &[]).expect_err("one report"), + HeapError::MarkDenied + ); + }); +} + +/// The root cursor has scanned one lower slot and has not entered the top frame. +/// Moving that cursor to the frame start skips the remaining lower slots. +#[test] +fn published_root_retirement_still_scans_unvisited_lower_slots() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + open_and_publish(&mut host); + drive_roots_index(&mut host, 1); + let before = tail_facts(&mut host); + assert_eq!(before.phase, "Roots"); + assert_eq!(before.index, 1); + assert!(before.index < 4, "the cursor has not entered the top frame"); + assert_eq!(before.live_roots, 1); + + let retired = retire_published_root_frame(&mut host, graph.top).expect("retire top"); + let cursor = tail_facts(&mut host); + let mut root_visits = 0u64; + let mut seen = Vec::new(); + let report = loop { + clear_meter(&mut host); + match step_private_cycle(&mut host, 1, &[]).expect("continue") { + StepOutcome::Paused { tail: true } => { + let facts = tail_facts(&mut host); + seen.push(facts.index); + root_visits += clear_meter(&mut host).root_slot_visits; + } + StepOutcome::Completed(report) => { + assert_eq!(clear_meter(&mut host), ScanMeter::default()); + break report; + } + other => panic!("continuation stays on the tail, got {other:?}"), + } + }; + assert_eq!( + ( + report.live_roots, + root_visits, + cursor.index, + cursor.phase.as_str(), + retired.prefix_slots, + retired.dropped_live, + seen.as_slice(), + ), + (LOWER_SOME, 3, 1, "Roots", 0, 0, &[2, 3, 4][..]), + "setting the cursor to the frame start skips unscanned lower slots" + ); + assert_eq!(report.marked_nodes, before.marked_nodes); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())).expect("frame") + == Some(graph.lower) + ); + }); +} + +fn generation(host: &mut vm::HostContext<'_>, table: TableRef) -> u32 { + heap::with_heap( + host, + |heap| Ok(heap.slots[table.slot() as usize].generation), + ) + .expect("generation") +} + +fn alive(host: &mut vm::HostContext<'_>, table: TableRef) -> bool { + heap::with_heap(host, |heap| Ok(heap.alive(table))).expect("alive") +} + +fn watch(host: &mut vm::HostContext<'_>, owner: TableRef) -> Option { + heap::with_heap(host, |heap| heap.named_edge(owner, "watch")).expect("watch") +} + +fn tail_text(host: &mut vm::HostContext<'_>) -> String { + heap::with_heap(host, |heap| Ok(format!("{:?}", heap.sweep_tail))).expect("tail text") +} + +fn raw_token(handle: vm::ResourceHandle) -> i64 { + i64::try_from(handle.raw()).expect("resource handle fits a positive integer") +} + +fn publish_until_release(host: &mut vm::HostContext<'_>) { + clear_meter(host); + open_private_step_cycle(host).expect("open"); + for _ in 0..BOUND { + match step_private_cycle(host, 1, &[]).expect("mark") { + StepOutcome::Paused { tail: false } => {} + StepOutcome::Published { .. } => { + let facts = tail_facts(host); + assert_eq!(facts.phase, "Release"); + assert_eq!(facts.index, 0); + return; + } + other => panic!("small budgets stay in mark until publish, got {other:?}"), + } + } + panic!("publish did not arrive"); +} + +fn save_unrooted_tail(host: &mut vm::HostContext<'_>) { + clear_meter(host); + open_private_step_cycle(host).expect("open"); + for _ in 0..BOUND { + match step_private_cycle(host, 1, &[]).expect("step") { + StepOutcome::Paused { tail: false } => {} + StepOutcome::Published { .. } => return, + other => panic!("an unrooted node publishes a tail, got {other:?}"), + } + } + panic!("unrooted publish did not arrive"); +} + +/// One dead slot has been released. The dead cursor and its history stay put, +/// and the remaining lower slots are still scanned one at a time. +#[test] +fn published_root_retirement_keeps_the_release_cursor_and_scans_lower_slots() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + open_and_publish(&mut host); + clear_meter(&mut host); + let outcome = step_private_cycle(&mut host, 1, &[]).expect("one release"); + assert!(matches!(outcome, StepOutcome::Paused { tail: true })); + let pending = heap::with_heap(&mut host, |heap| Ok(heap.scan)).expect("meter"); + assert_eq!(pending.node_slot_visits, 1); + assert_eq!(pending.root_slot_visits, 0); + assert_eq!( + generation(&mut host, graph.dead_a), + graph.dead_a_generation + 1 + ); + assert_eq!(generation(&mut host, graph.dead_b), graph.dead_b_generation); + let marked = tail_facts(&mut host).marked_nodes; + + let retired = retire_published_root_frame(&mut host, graph.top).expect("retire"); + let kept = heap::with_heap(&mut host, |heap| Ok(heap.scan)).expect("meter"); + let cursor = tail_facts(&mut host); + assert_eq!( + kept, pending, + "retirement does not roll the release meter back" + ); + assert_eq!( + ( + retired.release_phase, + retired.prefix_slots, + retired.dropped_live, + cursor.phase.as_str(), + cursor.index, + cursor.live_roots, + cursor.marked_nodes, + ), + (true, 0, 0, "Release", 1, 0, marked) + ); + clear_meter(&mut host); + step_paused(&mut host); + assert_eq!( + generation(&mut host, graph.dead_a), + graph.dead_a_generation + 1 + ); + assert_eq!( + generation(&mut host, graph.dead_b), + graph.dead_b_generation + 1 + ); + assert_eq!(tail_facts(&mut host).phase, "Release"); + assert_eq!(tail_facts(&mut host).index, 2); + drive_roots_index(&mut host, 4); + let report = finish(&mut host); + assert_eq!(report.live_roots, LOWER_SOME); + assert_eq!(report.marked_nodes, marked); + assert!(!alive(&mut host, graph.dead_a)); + assert!(!alive(&mut host, graph.dead_b)); + assert_eq!( + generation(&mut host, graph.dead_a), + graph.dead_a_generation + 1 + ); + assert_eq!( + generation(&mut host, graph.dead_b), + graph.dead_b_generation + 1 + ); + }); +} + +/// The scanned top prefix contains one empty slot. That slot is in the prefix +/// and is not a live root. +#[test] +fn published_root_retirement_counts_a_scanned_hole_without_calling_it_live() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + open_and_publish(&mut host); + drive_roots_index(&mut host, 6); + let scanned = tail_facts(&mut host); + assert_eq!(scanned.live_roots, LOWER_SOME + 1); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.roots[4], Some(super::Rooted::Table(graph.subject))); + assert!(heap.roots[5].is_none()); + Ok(()) + }) + .expect("hole"); + let retired = retire_published_root_frame(&mut host, graph.top).expect("retire"); + assert_eq!( + ( + retired.prefix_slots, + retired.dropped_live, + retired.release_phase + ), + (2, 1, false) + ); + assert_eq!(tail_facts(&mut host).index, 4); + let report = finish(&mut host); + assert_eq!(report.live_roots, LOWER_SOME); + }); +} + +/// The same subject occupies two already scanned slots. Both tags are deducted. +#[test] +fn published_root_retirement_deducts_duplicate_scanned_tags() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + open_and_publish(&mut host); + drive_roots_index(&mut host, 7); + assert_eq!(tail_facts(&mut host).live_roots, LOWER_SOME + 2); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.roots[4], Some(super::Rooted::Table(graph.subject))); + assert_eq!(heap.roots[6], Some(super::Rooted::Table(graph.subject))); + Ok(()) + }) + .expect("duplicate"); + let retired = retire_published_root_frame(&mut host, graph.top).expect("retire"); + assert_eq!((retired.prefix_slots, retired.dropped_live), (3, 2)); + let report = finish(&mut host); + assert_eq!(report.live_roots, LOWER_SOME); + }); +} + +/// Two successive top frames account disjoint prefixes and then the report is zero. +#[test] +fn published_root_retirement_accounts_two_frames_in_disjoint_prefixes() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + open_and_publish(&mut host); + drive_roots_index(&mut host, ROOT_SLOTS); + let first = retire_published_root_frame(&mut host, graph.top).expect("top"); + assert_eq!(heap::stats(&mut host).expect("stats").root_slots, 4); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())).expect("frame"), + Some(graph.lower) + ); + let second = retire_published_root_frame(&mut host, graph.lower).expect("lower"); + assert_eq!(heap::stats(&mut host).expect("stats").root_slots, 0); + assert_eq!( + ( + first.prefix_slots, + first.dropped_live, + second.prefix_slots, + second.dropped_live, + ), + (4, TOP_SOME, 4, LOWER_SOME) + ); + assert_eq!( + first.dropped_live + second.dropped_live, + LOWER_SOME + TOP_SOME + ); + let report = finish(&mut host); + assert_eq!(report.live_roots, 0); + }); +} + +#[test] +fn published_root_retirement_checks_the_frame_before_the_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let missing = retire_published_root_frame(&mut host, heap::RootFrameId::from_parts(0, 1)); + assert_eq!(missing, Err(HeapError::SweepDenied)); + assert!(host.scope_state::().is_none()); + }); + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let absent = retire_published_root_frame(&mut host, heap::RootFrameId::from_parts(0, 1)); + assert_eq!(absent, Err(HeapError::NoRootFrame)); + assert!(heap::with_heap(&mut host, |heap| Ok(heap.sweep_tail.is_none())).expect("tail")); + let frame = heap::with_heap(&mut host, |heap| { + let popped = heap.enter_roots(1)?; + heap.leave_roots(popped)?; + let frame = heap.enter_roots(1)?; + Ok((popped, frame)) + }) + .expect("frame"); + let (popped, frame) = frame; + assert_eq!( + retire_published_root_frame(&mut host, popped), + Err(HeapError::StaleFrame) + ); + let stale = retire_published_root_frame( + &mut host, + heap::RootFrameId::from_parts(frame.parts().0, frame.parts().1 + 1), + ); + assert_eq!(stale, Err(HeapError::StaleFrame)); + assert_eq!( + retire_published_root_frame(&mut host, frame), + Err(HeapError::SweepDenied) + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())).expect("frame"), + Some(frame) + ); + assert_eq!(heap::stats(&mut host).expect("stats").root_slots, 1); + assert_eq!( + heap::with_heap(&mut host, |heap| heap.enter_roots(0)).expect_err("zero"), + HeapError::StaleFrame + ); + assert_eq!(heap::stats(&mut host).expect("stats").root_slots, 1); + }); + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits()).expect("install"); + let (dead, token) = publish(&mut host); + save_unrooted_tail(&mut host); + assert!( + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())) + .expect("frame") + .is_none() + ); + let before = tail_text(&mut host); + let refused = retire_published_root_frame(&mut host, heap::RootFrameId::from_parts(0, 1)); + assert_eq!(refused, Err(HeapError::NoRootFrame)); + assert_eq!(tail_text(&mut host), before); + assert!(!token_open(&mut host, token)); + assert!(dead.slot() < limits().nodes); + }); +} + +#[test] +fn published_root_retirement_refuses_a_non_top_or_old_frame_without_moving_the_tail() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + open_and_publish(&mut host); + let before = tail_text(&mut host); + let meter = heap::with_heap(&mut host, |heap| Ok(heap.scan)).expect("meter"); + let non_top = retire_published_root_frame(&mut host, graph.lower); + let old = retire_published_root_frame( + &mut host, + heap::RootFrameId::from_parts(graph.top.parts().0, graph.top.parts().1 + 1), + ); + assert_eq!(non_top, Err(HeapError::StaleFrame)); + assert_eq!(old, Err(HeapError::StaleFrame)); + assert_eq!(tail_text(&mut host), before); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.scan)).expect("meter"), + meter + ); + assert_eq!( + heap::stats(&mut host).expect("stats").root_slots, + ROOT_SLOTS as u32 + ); + assert_eq!( + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())).expect("frame"), + Some(graph.top) + ); + }); +} + +#[test] +fn published_root_retirement_keeps_ordinary_root_and_write_gates() { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + open_and_publish(&mut host); + let before = tail_text(&mut host); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.leave_roots(graph.top), Err(HeapError::SweepPending)); + assert_eq!(heap.enter_roots(1), Err(HeapError::RootCapacity)); + assert_eq!( + heap.write_root(graph.lower, 0, graph.owner), + Err(HeapError::SweepPending) + ); + assert_eq!( + heap.clear_root(graph.lower, 0), + Err(HeapError::SweepPending) + ); + assert_eq!( + heap.set_named_edge(graph.owner, "extra", graph.subject), + Err(HeapError::SweepPending) + ); + Ok(()) + }) + .expect("gates"); + assert_eq!(tail_text(&mut host), before); + assert_eq!( + heap::stats(&mut host).expect("stats").root_slots, + ROOT_SLOTS as u32 + ); + let retired = retire_published_root_frame(&mut host, graph.top).expect("retire"); + assert!(retired.release_phase); + heap::with_heap(&mut host, |heap| { + assert_eq!(heap.leave_roots(graph.lower), Err(HeapError::SweepPending)); + assert_eq!(heap.leave_roots(graph.top), Err(HeapError::StaleFrame)); + assert_eq!(heap.enter_roots(1), Err(HeapError::SweepPending)); + assert_eq!( + heap.clear_root(graph.lower, 1), + Err(HeapError::SweepPending) + ); + assert_eq!( + heap.set_named_edge(graph.owner, "extra", graph.subject), + Err(HeapError::SweepPending) + ); + Ok(()) + }) + .expect("gates after"); + let cursor = tail_facts(&mut host); + let (late, handle) = heap::publish_late(&mut host).expect("late still opens"); + let after = tail_facts(&mut host); + assert_eq!(after.index, cursor.index); + assert_eq!(after.phase, cursor.phase); + assert_eq!(after.late_nodes, cursor.late_nodes + 1); + assert!(token_open(&mut host, raw_token(handle))); + assert!(alive(&mut host, late)); + assert_eq!(heap::stats(&mut host).expect("stats").root_slots, 4); + }); +} + +struct Arm { + subject_open: bool, + weak_present: bool, + late_open: bool, + collections: u32, + live_roots: u32, + live_nodes: u32, + marked_nodes: u32, +} + +fn arm_after_complete( + host: &mut vm::HostContext<'_>, + graph: &Graph, + retire: bool, +) -> (Arm, Option) { + open_and_publish(host); + let late_token = if retire { + let (late, handle) = heap::publish_late(host).expect("late"); + let facts = tail_facts(host); + assert_eq!(facts.late_nodes, 1); + let retired = retire_published_root_frame(host, graph.top).expect("retire"); + assert!(retired.release_phase); + assert_eq!(retired.prefix_slots, 0); + assert_eq!(tail_facts(host).index, 0); + assert!(alive(host, late)); + assert!(matches!( + heap::with_heap(host, |heap| Ok(heap.slots[late.slot() as usize].state)) + .expect("state"), + super::SlotState::Live { marked: false } + )); + Some(raw_token(handle)) + } else { + None + }; + let report = finish(host); + let arm = Arm { + subject_open: token_open(host, graph.subject_token), + weak_present: watch(host, graph.owner) == Some(graph.subject), + late_open: late_token.is_some_and(|token| token_open(host, token)), + collections: heap::stats(host).expect("stats").collections, + live_roots: report.live_roots, + live_nodes: report.live_nodes, + marked_nodes: report.marked_nodes, + }; + (arm, late_token) +} + +/// A late node allocated before retirement stays alive for this cycle only. +/// Keeping the frame, retiring before the cycle, and omitting the next cycle +/// do not produce that same pair of observations. +#[test] +fn published_root_retirement_floats_the_current_cycle_and_collects_next() { + let floated = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + let (before_next, late_token) = arm_after_complete(&mut host, &graph, true); + assert!(before_next.subject_open); + assert!(before_next.weak_present); + assert!(before_next.late_open); + assert_eq!(before_next.live_nodes, before_next.marked_nodes + 1); + assert_eq!(before_next.live_roots, LOWER_SOME); + let Value::Array(after) = + heap::with_heap(&mut host, |heap| heap.issued_value(graph.subject)).expect("carrier") + else { + panic!("carrier remains an array"); + }; + assert!(Arc::ptr_eq(&graph.carrier, &after)); + heap::collect(&mut host).expect("next"); + assert_eq!( + heap::stats(&mut host).expect("stats").collections, + before_next.collections + 1 + ); + ( + !token_open(&mut host, graph.subject_token), + watch(&mut host, graph.owner).is_none(), + !token_open(&mut host, late_token.expect("late token")), + alive(&mut host, graph.owner), + ) + }); + let omitted = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + let (arm, _) = arm_after_complete(&mut host, &graph, true); + ( + arm.subject_open, + arm.weak_present, + arm.late_open, + arm.collections, + ) + }); + let retained = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + let (arm, _) = arm_after_complete(&mut host, &graph, false); + let again = heap::collect(&mut host).expect("next"); + ( + arm.live_roots, + token_open(&mut host, graph.subject_token), + watch(&mut host, graph.owner) == Some(graph.subject), + again.live_roots, + ) + }); + let before_cycle = crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = install_graph(&mut host); + heap::with_heap(&mut host, |heap| heap.leave_roots(graph.top)).expect("leave before cycle"); + publish_until_release(&mut host); + let closed_at_publish = !token_open(&mut host, graph.subject_token); + let weak_cleared = watch(&mut host, graph.owner).is_none(); + let report = finish(&mut host); + ( + closed_at_publish, + weak_cleared, + report.live_roots, + !alive(&mut host, graph.subject), + ) + }); + assert_eq!(floated, (true, true, true, true)); + assert_eq!(omitted, (true, true, true, 1)); + assert_eq!( + retained, + (LOWER_SOME + TOP_SOME, true, true, LOWER_SOME + TOP_SOME) + ); + assert_eq!(before_cycle, (true, true, LOWER_SOME, true)); +} From 1bc5e207f0f8629e86dec3d4abb7c73ed2e08088 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 13:54:05 +0800 Subject: [PATCH 124/225] test(lua/heap): refill a published gap during a partial root scan Release the published dead slots, pause after a determined root prefix, and read the saved tail. Refill the cleaned name in place, then finish the remaining root slots once. --- tests/luajit_heap_runtime/published_refill.rs | 373 ++++++++++++++++++ 1 file changed, 373 insertions(+) diff --git a/tests/luajit_heap_runtime/published_refill.rs b/tests/luajit_heap_runtime/published_refill.rs index b317f33..2a4d9c1 100644 --- a/tests/luajit_heap_runtime/published_refill.rs +++ b/tests/luajit_heap_runtime/published_refill.rs @@ -4,6 +4,8 @@ //! and `set_named_edge` are the host paths a production guest step or rawset //! would share; both still refuse while the tail is saved. `named_value` and //! `next_guest` are the private host's observation of the pre-issued carrier. +//! The Roots witness reads the saved tail receipt and the scan meter. It does +//! not build a tail. use vm::Value; @@ -700,3 +702,374 @@ fn omitted_refill_keeps_the_gap_and_the_strong_target() { .expect("omitted"); }); } + +/// Root slots charged before the refill. The rest of the frame stays pending. +const ROOT_PREFIX: usize = 2; + +fn unmarked_slots(heap: &LuaHeap) -> Vec { + heap.slots + .iter() + .enumerate() + .filter_map(|(index, slot)| { + matches!(slot.state, SlotState::Live { marked: false }).then_some(index as u32) + }) + .collect() +} + +fn marked_slot_count(heap: &LuaHeap) -> u32 { + heap.slots + .iter() + .filter(|slot| matches!(slot.state, SlotState::Live { marked: true })) + .count() as u32 +} + +fn tail_receipt(phase: &str, index: usize, dead: &[u32], marked: u32, live_roots: u32) -> String { + format!( + "Some(SweepTail {{ phase: {phase}, index: {index}, dead: {dead:?}, \ + marked_nodes: {marked}, live_roots: {live_roots} }})" + ) +} + +fn visits(nodes: u64, roots: u64) -> ScanMeter { + ScanMeter { + node_slot_visits: nodes, + root_slot_visits: roots, + ..ScanMeter::default() + } +} + +struct RootsWitness { + prefix_receipt: String, + report: CollectReport, +} + +fn resume_paused(host: &mut vm::HostContext<'_>, budget: u64) { + let resumed = heap::resume_published_sweep(host, budget).expect("saved tail"); + assert!( + matches!(resumed, PublishedResume::Paused), + "the saved tail is not finished, got {resumed:?}" + ); +} + +/// Refill during a real Roots prefix, or omit it and keep the gap. Both arms +/// release the published dead slots, scan the same prefix, then finish the +/// remaining root slots once. `named_value` is the direct read a `rawget` +/// candidate would use. The tail comes from `collect_until_published`. +fn drive_roots_refill(refill: bool) -> RootsWitness { + crate::support::with_idle_vm(|vm| { + let mut host = vm.host_context(); + let graph = build_graph(&mut host); + let resources_before = host.resource_count(); + publish_two_gaps(&mut host, &graph); + let _ = heap::take_scan_meter(&mut host).expect("clear publish meter"); + + let (dead, marked, root_slots) = heap::with_heap(&mut host, |heap| { + let dead = unmarked_slots(heap); + let mut expected = [graph.doomed_a.slot(), graph.doomed_b.slot()]; + expected.sort_unstable(); + assert_eq!(dead, expected, "the dead set is the two published orphans"); + assert!( + heap.roots.iter().all(|root| root.is_some()), + "the frame has no hole to hide a skipped visit" + ); + assert!( + heap.roots.len() > ROOT_PREFIX, + "a partial prefix needs a pending suffix" + ); + Ok((dead, marked_slot_count(heap), heap.roots.len())) + }) + .expect("dead set"); + assert_eq!( + tail_text(&mut host), + tail_receipt("Release", 0, &dead, marked, 0), + "publish saved a real Release tail" + ); + + resume_paused(&mut host, dead.len() as u64); + assert_eq!( + heap::take_scan_meter(&mut host).expect("release meter"), + visits(dead.len() as u64, 0), + "release visits the dead slots and no root slot" + ); + assert_eq!( + tail_text(&mut host), + tail_receipt("Release", dead.len(), &dead, marked, 0), + "the budget ended on the last release; Roots has not started" + ); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(graph.doomed_a)); + assert!(!heap.alive(graph.doomed_b)); + assert_ne!( + slot_generation(heap, graph.doomed_a), + graph.doomed_a.generation() + ); + assert_ne!( + slot_generation(heap, graph.doomed_b), + graph.doomed_b.generation() + ); + Ok(()) + }) + .expect("released"); + assert!(!token_open(&mut host, graph.doomed_a_token)); + assert!(!token_open(&mut host, graph.doomed_b_token)); + assert_eq!(heap::stats(&mut host).expect("released").collections, 0); + + resume_paused(&mut host, ROOT_PREFIX as u64); + assert_eq!( + heap::take_scan_meter(&mut host).expect("prefix meter"), + visits(ROOT_PREFIX as u64, ROOT_PREFIX as u64), + "the prefix is occupied root slots, not a call-count guess" + ); + let prefix_receipt = tail_receipt("Roots", ROOT_PREFIX, &dead, marked, ROOT_PREFIX as u32); + assert_eq!( + tail_text(&mut host), + prefix_receipt, + "receipt shows Roots, a scanned prefix, and an unfinished tail" + ); + assert_eq!(heap::stats(&mut host).expect("paused").collections, 0); + assert!(matches!( + heap::resume_published_sweep(&mut host, 0).expect("zero"), + PublishedResume::Paused + )); + assert_eq!( + tail_text(&mut host), + prefix_receipt, + "zero budget does not move the cursor" + ); + assert_eq!( + heap::collect(&mut host).expect_err("production collect"), + HeapError::SweepPending + ); + assert_eq!( + heap::take_scan_meter(&mut host).expect("clear incremental meter"), + ScanMeter::default() + ); + + let before = heap::stats(&mut host).expect("before"); + let resources = host.resource_count(); + let (weak_place, other_place, mode_edge, saved_cursor) = + heap::with_heap(&mut host, |heap| { + let saved_cursor = heap + .next_guest(graph.weak, &Value::string("a"))? + .expect("the cleaned key is a saved cursor"); + Ok(( + place(heap, graph.weak, "a"), + place(heap, graph.other, "gap"), + heap.slots[graph.meta.slot() as usize].mode_edge, + saved_cursor, + )) + }) + .expect("places"); + assert_eq!(saved_cursor.0, Value::string("after")); + assert_eq!(saved_cursor.1, graph.successor_carrier); + + if refill { + assert_eq!( + heap::with_heap(&mut host, |heap| { + heap.set_named_edge(graph.weak, "a", graph.target) + }), + Err(HeapError::SweepPending), + "ordinary writer still stops at the sweep gate" + ); + assert_eq!( + heap::refill_published_gap(&mut host, graph.weak, "a", graph.target), + Ok(true) + ); + heap::with_heap(&mut host, |heap| { + assert_eq!(place(heap, graph.weak, "a"), weak_place); + assert_eq!(place(heap, graph.other, "gap"), other_place); + assert_eq!(heap.slots[graph.meta.slot() as usize].mode_edge, mode_edge); + assert_original_carrier( + heap, + graph.weak, + "a", + graph.target, + &graph.target_carrier, + )?; + assert_eq!( + heap.next_guest(graph.weak, &Value::string("a"))? + .expect("saved cursor unchanged"), + saved_cursor.clone() + ); + assert_eq!( + heap.next_guest(graph.weak, &Value::Null)? + .expect("refilled key is now visible"), + (Value::string("a"), graph.target_carrier.clone()) + ); + assert_eq!( + heap.next_guest(graph.other, &Value::string("gap"))? + .expect("other gap cursor"), + (Value::string("next"), graph.successor_carrier.clone()) + ); + assert!(utf8_gap(heap, graph.other, "gap")); + assert_eq!(heap.named_edge(graph.keeper, "hold")?, Some(graph.target)); + assert_eq!(heap.live_edge_count, before.live_edges + 1); + Ok(()) + }) + .expect("refilled"); + let mut expected = before; + expected.live_edges += 1; + assert_eq!(heap::stats(&mut host).expect("after"), expected); + assert_eq!(host.resource_count(), resources); + assert_eq!( + tail_text(&mut host), + prefix_receipt, + "refill does not move the cursor or collect another root" + ); + assert_eq!( + heap::take_scan_meter(&mut host).expect("refill meter"), + ScanMeter::default(), + "refill does not continue the scan" + ); + assert_eq!( + heap::with_heap(&mut host, |heap| { + heap.set_named_edge(graph.weak, "solid", graph.successor) + }), + Err(HeapError::SweepPending), + "refill does not open the ordinary writer" + ); + assert_eq!(tail_text(&mut host), prefix_receipt); + assert_eq!( + heap::take_scan_meter(&mut host).expect("writer refusal"), + ScanMeter::default() + ); + } else { + heap::with_heap(&mut host, |heap| { + assert!(utf8_gap(heap, graph.weak, "a")); + assert_eq!(heap.named_value(graph.weak, "a")?, Value::Null); + assert_eq!(place(heap, graph.other, "gap"), other_place); + assert_eq!( + heap.next_guest(graph.weak, &Value::string("a"))? + .expect("omitted cursor"), + saved_cursor.clone() + ); + Ok(()) + }) + .expect("gap remains before the suffix"); + assert_eq!(heap::stats(&mut host).expect("omitted"), before); + assert_eq!(host.resource_count(), resources); + assert_eq!(tail_text(&mut host), prefix_receipt); + assert_eq!( + heap::take_scan_meter(&mut host).expect("omission meter"), + ScanMeter::default() + ); + } + + let remaining = root_slots - ROOT_PREFIX; + resume_paused(&mut host, remaining as u64); + assert_eq!( + heap::take_scan_meter(&mut host).expect("suffix meter"), + visits(remaining as u64, remaining as u64), + "the same Roots phase scans the remaining slots" + ); + assert_eq!( + tail_text(&mut host), + tail_receipt("Roots", root_slots, &dead, marked, root_slots as u32), + "the cursor is at the end of Roots and the cycle is not reported" + ); + assert_eq!(heap::stats(&mut host).expect("suffix").collections, 0); + + let resumed = heap::resume_published_sweep(&mut host, 1).expect("complete"); + let PublishedResume::Completed(report) = resumed else { + panic!("the uncharged completion finishes once, got {resumed:?}"); + }; + assert_eq!( + heap::take_scan_meter(&mut host).expect("completion meter"), + ScanMeter::default(), + "completion does not scan another root" + ); + assert_eq!(report.live_nodes, marked); + assert_eq!(report.marked_nodes, marked); + assert_eq!(report.live_roots, root_slots as u32); + assert_eq!(heap::stats(&mut host).expect("finished").collections, 1); + assert_eq!( + heap::resume_published_sweep(&mut host, 1).expect_err("tail is gone"), + HeapError::SweepDenied + ); + + if refill { + heap::with_heap(&mut host, |heap| { + assert_original_carrier( + heap, + graph.weak, + "a", + graph.target, + &graph.target_carrier, + )?; + Ok(()) + }) + .expect("identity survives the rest of the root scan"); + let kept = heap::collect(&mut host).expect("strong root retains the target"); + assert_eq!(kept.live_nodes, marked); + assert!(token_open(&mut host, graph.target_token)); + heap::with_heap(&mut host, |heap| { + assert_original_carrier( + heap, + graph.weak, + "a", + graph.target, + &graph.target_carrier, + )?; + heap.set_named_scalar(graph.keeper, "hold", Value::Null)?; + Ok(()) + }) + .expect("drop the independent strong root"); + let cleaned = heap::collect(&mut host).expect("next cycle"); + assert_eq!(cleaned.live_nodes, marked - 1); + assert!(!token_open(&mut host, graph.target_token)); + assert_eq!(host.resource_count(), resources_before - 3); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(graph.target)); + assert_ne!( + slot_generation(heap, graph.target), + graph.target.generation() + ); + assert!(utf8_gap(heap, graph.weak, "a")); + assert!(utf8_gap(heap, graph.weak, "solid")); + assert_eq!(heap.named_value(graph.weak, "a")?, Value::Null); + assert!(heap.alive(graph.successor)); + assert!(heap.alive(graph.keeper)); + Ok(()) + }) + .expect("released after the strong root was cleared"); + } else { + assert!(token_open(&mut host, graph.target_token)); + heap::with_heap(&mut host, |heap| { + assert!(utf8_gap(heap, graph.weak, "a"), "omission keeps the gap"); + assert_eq!(heap.named_value(graph.weak, "a")?, Value::Null); + assert!(heap.alive(graph.target)); + assert_eq!(heap.named_edge(graph.keeper, "hold")?, Some(graph.target)); + assert_eq!( + heap.next_guest(graph.weak, &Value::string("a"))? + .expect("cursor still continues"), + saved_cursor + ); + Ok(()) + }) + .expect("omission"); + } + + RootsWitness { + prefix_receipt, + report, + } + }) +} + +/// Roots partial prefix: the pre-issued carrier stays readable, the saved +/// cursor and the other gap stay put, and the same phase finishes once. +/// The omission run is the matching control. +#[test] +fn published_refill_during_partial_root_scan_keeps_the_carrier_and_resumes() { + let refilled = drive_roots_refill(true); + let omitted = drive_roots_refill(false); + assert_eq!( + refilled.prefix_receipt, omitted.prefix_receipt, + "both runs paused on the same Roots prefix" + ); + assert_eq!( + refilled.report.live_roots, omitted.report.live_roots, + "finished root count matches the omission control" + ); + assert_eq!(refilled.report, omitted.report); +} From be2a8ae60295274a499c99091d9687f717340a9d Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 15:18:25 +0800 Subject: [PATCH 125/225] test(lua/heap): require late_nodes zero on the roots refill receipt The published roots refill does not allocate after the sweep is saved. The union baseline already prints late_nodes, so the shared receipt must require that field to stay zero. --- tests/luajit_heap_runtime/published_refill.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/luajit_heap_runtime/published_refill.rs b/tests/luajit_heap_runtime/published_refill.rs index 2a4d9c1..ee192ce 100644 --- a/tests/luajit_heap_runtime/published_refill.rs +++ b/tests/luajit_heap_runtime/published_refill.rs @@ -726,7 +726,7 @@ fn marked_slot_count(heap: &LuaHeap) -> u32 { fn tail_receipt(phase: &str, index: usize, dead: &[u32], marked: u32, live_roots: u32) -> String { format!( "Some(SweepTail {{ phase: {phase}, index: {index}, dead: {dead:?}, \ - marked_nodes: {marked}, live_roots: {live_roots} }})" + marked_nodes: {marked}, live_roots: {live_roots}, late_nodes: 0 }})" ) } From 26f37825578e4b5ee36a10551af8bc330fe0c6eb Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 13:03:30 +0800 Subject: [PATCH 126/225] feat(lua): retire one callee frame on a published scalar return When a sweep tail is already saved, retire_callee drops the top frame through the reviewed private retirement. No tail still uses leave_roots, and chunk retirement is unchanged. (cherry picked from commit 3850e0a6ba6dd24cd308b37cdbb5da28f8f6fd87) --- src/frontends/lua/heap.rs | 57 +- tests/luajit_heap_runtime/candidate.rs | 14 +- .../source_scalar_retire.rs | 903 ++++++++++++++++++ .../value_boundary_tests.rs | 2 + 4 files changed, 970 insertions(+), 6 deletions(-) create mode 100644 tests/luajit_heap_runtime/source_scalar_retire.rs diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 9c27d1a..c94dd71 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -280,8 +280,8 @@ fn resume_published_sweep( /// `Paused { tail: false }` is a saved mark. `Paused { tail: true }` is a /// published release tail. Published counts are not a pause signal: a zero /// edge window is still [`StepOutcome::Published`] when a dead slot remains. -#[derive(Debug)] -enum StepOutcome { +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StepOutcome { /// This call did not finish the saved mark or the saved tail. Paused { tail: bool }, /// The mark finished and weak edges were published. Release did not start. @@ -601,3 +601,56 @@ pub fn stats(host: &mut HostContext) -> Result { pub fn take_scan_meter(host: &mut HostContext) -> Result { with_heap(host, |heap| Ok(heap.take_scan_meter())) } + +/// Saves one private mark for a cycle whose roots already sit in fixed frames. +/// +/// Does not scan. A missing heap, an existing mark, or a saved tail is the +/// private open's existing refusal. Not a guest `collectgarbage` step. +#[cfg(test)] +pub fn open_fixed_step(host: &mut HostContext) -> Result<(), HeapError> { + open_private_step_cycle(host) +} + +/// True when this scope has a heap and neither a saved mark nor a sweep tail. +#[cfg(test)] +pub fn fixed_step_idle(host: &mut HostContext) -> Result { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + Ok(!heap.has_sweep_tail() && !heap.has_saved_mark()) +} + +/// Steps one private cycle whose roots already sit in fixed frames. +/// +/// `budget` must be positive. Zero is refused before the private stepper, so +/// this adapter does not use the zero-budget observe path. The batch is empty: +/// a root already registered in a frame is not submitted again. The result is +/// the real [`StepOutcome`]. Not a guest `collectgarbage` step. +#[cfg(test)] +pub fn step_fixed_frames(host: &mut HostContext, budget: u64) -> Result { + if budget == 0 { + return Err(HeapError::MarkDenied); + } + step_private_cycle(host, budget, &[]) +} + +/// Whether this scope still has the published sweep tail. +#[cfg(test)] +pub fn saved_sweep_tail(host: &mut HostContext) -> Result { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + Ok(heap.has_sweep_tail()) +} + +/// Drops one top frame while this scope's published sweep tail is saved. +/// +/// The private retirement remains the authority. Refusal does not move the +/// cursor, counts, root vector, or frame stack. Not a guest `collectgarbage` step. +#[cfg(test)] +pub fn retire_saved_tail_frame( + host: &mut HostContext, + frame: RootFrameId, +) -> Result<(), HeapError> { + retire_published_root_frame(host, frame).map(|_| ()) +} diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 003ced0..2c9ed54 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1207,10 +1207,16 @@ fn retire_callee(call: &mut OwnedHostCall<'_>) -> Result { if caller == Some(callee) { return Err(host_fault("would retire the caller result frame")); } - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.leave_roots(callee) - }) - .map_err(heap_error)?; + let tail = heap::saved_sweep_tail(&mut call.vm().host_context()).map_err(heap_error)?; + if tail { + heap::retire_saved_tail_frame(&mut call.vm().host_context(), callee) + .map_err(heap_error)?; + } else { + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.leave_roots(callee) + }) + .map_err(heap_error)?; + } left = true; } let top_is_caller = heap::with_heap(&mut call.vm().host_context(), |heap| { diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs new file mode 100644 index 0000000..39588c8 --- /dev/null +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -0,0 +1,903 @@ +//! Source scalar return across a published private step cycle. +//! +//! The Lua source is lowered, compiled, and run. The step host records the +//! real `StepOutcome`. It does not invent a pause, a publication, or a report. +//! Roots already sit in the callee frame, so the step batch is empty. + +use std::sync::{Arc, OnceLock}; + +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + HostFunctionRegistry, HostImportSchema, HostOwnedFunction, HostParamPassing, HostParamSchema, + HostTypeSchema, OpCode, OwnedHostCall, ParseError, Program, SourceFlavor, SourcePlugin, Value, + VmError, VmStatus, +}; + +use super::ObservedTable; +use super::candidate::{self, ReturnedElement}; +use super::heap::{self, StepOutcome}; + +const STEP: &str = "lua_host::step"; +const PEEK: &str = "lua_host::peek"; +const SAME: &str = "lua_host::same"; +const NOTE: &str = "lua_host::note"; +const TEXT: &str = "lua_host::text"; + +const SOURCE: &str = r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + w[3] = {} + peek(t) + note(30, rawlen(w)) + step(1) + step(10000) + note(10, rawlen(w)) + note(11, same(t, rawget(w, 1))) + text(2, type(rawget(w, 2))) + text(3, type(rawget(w, 3))) + step(1) + local n = rawlen(w) + return n +end +witness() +step(1) +step(1) +collectgarbage("collect") +return 1 +"#; + +#[derive(Clone, Debug, PartialEq)] +enum Stop { + Halted, + HostError(String), + Other(String), +} + +#[derive(Clone, Debug)] +struct StepNote { + budget: u64, + opened: bool, + outcome: StepOutcome, + node_slot_visits: u64, + live_nodes_before: u32, + live_nodes_after: u32, + root_slots: u32, + live_roots: u32, + frame: Option, + tail: bool, + subject_alive: Option, + collections: u32, +} + +#[derive(Clone, Debug, Default)] +struct Trace { + steps: Vec, + peeks: Vec, + sames: Vec<(heap::TableRef, heap::TableRef)>, + notes: Vec<(f64, f64)>, + texts: Vec<(f64, String)>, +} + +#[derive(Clone, Debug)] +struct HandoffSnap { + elements: Vec, + callee_left: bool, + lua_frame_alive_at_publish: bool, + handoff_depth: Option, + published_root: bool, +} + +#[derive(Clone, Debug)] +struct Ran { + stop: Stop, + stack: Vec, + trace: Trace, + frame: Option, + tail: bool, + collections: u32, + live_nodes: u32, + root_slots: u32, + live_roots: u32, + subject_alive: Option, + token_open: Option, + handoff: Option, + collects: usize, +} + +struct Plugin; + +impl SourcePlugin for Plugin { + fn flavor(&self) -> SourceFlavor { + SourceFlavor::Lua + } + + fn extensions(&self) -> &'static [&'static str] { + &[] + } + + fn import_syntax(&self) -> FrontendImportSyntax { + FrontendImportSyntax::Lua + } + + fn parse_source(&self, source: &str) -> Result { + candidate::lower(source, catalog()) + } +} + +fn catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(vm::HostFunctionSchema::with_return( + STEP, + vec![HostParamSchema::value("budget", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + PEEK, + vec![HostParamSchema::with_passing( + "table", + table.clone(), + HostParamPassing::Borrow, + )], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + SAME, + vec![ + HostParamSchema::with_passing("left", table.clone(), HostParamPassing::Borrow), + HostParamSchema::with_passing("right", table, HostParamPassing::Borrow), + ], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + NOTE, + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("value", HostTypeSchema::Float), + ], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + TEXT, + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("text", HostTypeSchema::String), + ], + HostTypeSchema::Bool, + )); + Arc::new(builder.build().expect("source scalar catalog")) + }) +} + +fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { + for (name, op) in [ + (STEP, HostOp::Step), + (PEEK, HostOp::Peek), + (SAME, HostOp::Same), + (NOTE, HostOp::Note), + (TEXT, HostOp::Text), + ] { + let function = catalog.function(name).expect("scalar step host schema"); + registry + .register_exact_owned( + name, + function.params.len() as u8, + HostImportSchema::from_function(catalog, function), + move |_| Box::new(op), + ) + .expect("register scalar step host"); + } +} + +#[derive(Clone, Copy)] +enum HostOp { + Step, + Peek, + Same, + Note, + Text, +} + +impl HostOwnedFunction for HostOp { + fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { + let args = call.args().to_vec(); + let mut host = call.vm().host_context(); + let value = match self { + Self::Step => step_host(&mut host, &args)?, + Self::Peek => { + let observed = borrowed_table(&mut host, &args[0])?; + let alive = heap::with_heap(&mut host, |heap| Ok(heap.alive(observed.table))) + .map_err(host_heap)?; + note(&mut host, |state| { + state.peeks.push(observed); + })?; + Value::Bool(alive) + } + Self::Same => { + let left = borrowed_table(&mut host, &args[0])?; + let right = borrowed_table(&mut host, &args[1])?; + let same = left.table == right.table; + note(&mut host, |state| { + state.sames.push((left.table, right.table)); + })?; + Value::Float(if same { 1.0 } else { 0.0 }) + } + Self::Note => { + let [Value::Float(tag), Value::Float(value)] = args.as_slice() else { + return Err(host_fault("expected numeric note")); + }; + let noted = (*tag, *value); + note(&mut host, |state| state.notes.push(noted))?; + Value::Float(noted.1) + } + Self::Text => { + let [Value::Float(tag), Value::String(text)] = args.as_slice() else { + return Err(host_fault("expected text note")); + }; + let noted = (*tag, text.to_string()); + note(&mut host, |state| state.texts.push(noted))?; + Value::Bool(true) + } + }; + Ok(CallOutcome::Return(CallReturn::one(value))) + } +} + +fn step_host(host: &mut vm::HostContext<'_>, args: &[Value]) -> Result { + let [Value::Float(budget)] = args else { + return Err(host_fault("expected step budget")); + }; + if !budget.is_finite() || *budget <= 0.0 || budget.fract() != 0.0 { + return Err(host_fault("step budget must be a positive integer")); + } + let budget = *budget as u64; + let idle = heap::fixed_step_idle(host).map_err(host_heap)?; + if idle { + heap::open_fixed_step(host).map_err(host_heap)?; + } + let subject = note(host, |state| state.peeks.first().map(|item| item.table))?; + let before = heap::stats(host).map_err(host_heap)?; + let _cleared = heap::take_scan_meter(host).map_err(host_heap)?; + let outcome = heap::step_fixed_frames(host, budget).map_err(host_heap)?; + let meter = heap::take_scan_meter(host).map_err(host_heap)?; + let after = heap::stats(host).map_err(host_heap)?; + let frame = heap::with_heap(host, |heap| Ok(heap.current_frame())).map_err(host_heap)?; + let tail = heap::saved_sweep_tail(host).map_err(host_heap)?; + let subject_alive = match subject { + Some(table) => { + Some(heap::with_heap(host, |heap| Ok(heap.alive(table))).map_err(host_heap)?) + } + None => None, + }; + note(host, |state| { + state.steps.push(StepNote { + budget, + opened: idle, + outcome, + node_slot_visits: meter.node_slot_visits, + live_nodes_before: before.live_nodes, + live_nodes_after: after.live_nodes, + root_slots: after.root_slots, + live_roots: after.live_roots, + frame, + tail, + subject_alive, + collections: after.collections, + }); + })?; + let code = match outcome { + StepOutcome::Paused { tail: false } => 0.0, + StepOutcome::Published { .. } => 1.0, + StepOutcome::Paused { tail: true } => 2.0, + StepOutcome::Completed(_) => 3.0, + }; + Ok(Value::Float(code)) +} + +fn note( + host: &mut vm::HostContext<'_>, + body: impl FnOnce(&mut Trace) -> T, +) -> Result { + let state = host + .scope_state_or_insert_with(Trace::default) + .map_err(|error| VmError::HostError(error.to_string()))?; + Ok(body(state)) +} + +fn borrowed_table(host: &mut vm::HostContext<'_>, value: &Value) -> Result { + let Value::Int(raw) = value else { + return Err(host_fault("expected table token")); + }; + let token = vm::ResourceHandle::from_raw( + u64::try_from(*raw).map_err(|_| host_fault("table token out of range"))?, + ) + .map_err(|_| host_fault("table token out of range"))?; + let key = heap::LuaTableResource::key(); + let table = host + .borrow_resource_with_key::(token, &key) + .map_err(|error| VmError::HostError(error.to_string()))? + .table(); + Ok(ObservedTable { table, token }) +} + +fn host_fault(message: &str) -> VmError { + VmError::HostError(message.to_string()) +} + +fn host_heap(error: heap::HeapError) -> VmError { + VmError::HostError(error.to_string()) +} + +fn run(source: &str) -> Ran { + let catalog = Arc::clone(catalog()); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&Plugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .unwrap_or_else(|error| panic!("compile rejected the source: {error}")); + let mut vm = prepared.into_vm().expect("create VM"); + assert_return_window(vm.program()); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind runtime"); + let status = vm.run(); + let trace = vm + .host_context() + .scope_state::() + .cloned() + .unwrap_or_default(); + let frame = vm + .host_context() + .scope_state::() + .and_then(|heap| heap.current_frame()); + let tail = heap::saved_sweep_tail(&mut vm.host_context()).unwrap_or(false); + let stats = heap::stats(&mut vm.host_context()) + .unwrap_or_else(|error| panic!("heap stats unavailable after {status:?}: {error}")); + let subject = trace.peeks.first().copied(); + let (subject_alive, token_open) = match subject { + Some(observed) => { + let alive = + heap::with_heap( + &mut vm.host_context(), + |heap| Ok(heap.alive(observed.table)), + ) + .unwrap_or(false); + let open = vm + .host_context() + .typed_resource_with_key::( + observed.token, + &heap::LuaTableResource::key(), + ) + .is_ok(); + (Some(alive), Some(open)) + } + None => (None, None), + }; + let handoff = vm + .host_context() + .scope_state::() + .map(|witness| { + let last = witness.handoffs.last(); + HandoffSnap { + elements: last + .map(|item| item.elements.clone()) + .unwrap_or_else(|| witness.elements.clone()), + callee_left: witness.callee_left, + lua_frame_alive_at_publish: witness.lua_frame_alive_at_publish, + handoff_depth: witness.handoff_depth, + published_root: witness.published_root, + } + }); + let collects = vm + .host_context() + .scope_state::() + .map(|witness| witness.collects.len()) + .unwrap_or(0); + let stop = match status { + Ok(VmStatus::Halted) => Stop::Halted, + Err(VmError::HostError(message)) => Stop::HostError(message), + Ok(other) => Stop::Other(format!("{other:?}")), + Err(other) => Stop::Other(other.to_string()), + }; + Ran { + stop, + stack: vm.stack().to_vec(), + trace, + frame, + tail, + collections: stats.collections, + live_nodes: stats.live_nodes, + root_slots: stats.root_slots, + live_roots: stats.live_roots, + subject_alive, + token_open, + handoff, + collects, + } +} + +fn assert_return_window(program: &Program) { + let finish = import_index(program, candidate::FINISH_RETURN); + let retire = import_index(program, candidate::RETIRE_CALLEE); + let mut call_ip = None; + let mut prototype = None; + let mut ip = 0; + while ip < program.code.len() { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == OpCode::CallScript && call_ip.is_none() { + call_ip = Some(ip); + prototype = Some(u32::from_le_bytes( + program.code[ip + 1..ip + 5].try_into().expect("prototype"), + )); + assert_eq!(program.code[ip + 5], 0, "the witness takes no arguments"); + } + ip += 1 + op.operand_len(); + } + let call_ip = call_ip.expect("CallScript"); + let prototype = program + .callable_prototypes + .get(prototype.expect("prototype") as usize) + .expect("witness prototype"); + let vm::CallableTarget::ScriptFunction(index) = prototype.target else { + panic!("CallScript target is not a script function"); + }; + let function = program + .script_functions + .get(index as usize) + .expect("script function"); + assert!( + call_ip < function.entry_ip as usize || call_ip >= function.end_ip as usize, + "the call site is outside the callee" + ); + assert!( + region_has(program, function.entry_ip, function.end_ip, OpCode::Ret), + "the callee must return through Core Ret" + ); + let finish_ip = next_call(program, call_ip, finish); + assert_no_calls_between(program, call_ip, finish_ip); + let retire_ip = next_call(program, finish_ip, retire); + if let Some(collect) = import_index_opt(program, candidate::COLLECT) { + assert!( + !region_calls(program, finish_ip as u32, retire_ip as u32, collect), + "collect does not sit between publish and retire" + ); + } + if let Some(gather) = import_index_opt(program, "lua_internal::gather_root") { + assert!( + !region_calls(program, call_ip as u32, retire_ip as u32, gather), + "the step host must not gather a fresh root batch before retire" + ); + } + if let Some(pending) = import_index_opt(program, "lua_internal::enter_pending_frame") { + assert!( + !region_calls(program, 0, program.code.len() as u32, pending), + "this witness must not open a pending frame" + ); + } +} + +fn import_index(program: &Program, name: &str) -> u16 { + import_index_opt(program, name).unwrap_or_else(|| panic!("missing import {name}")) +} + +fn import_index_opt(program: &Program, name: &str) -> Option { + program + .imports + .iter() + .position(|import| import.name == name) + .map(|index| index.try_into().expect("import index")) +} + +fn region_has(program: &Program, start: u32, end: u32, want: OpCode) -> bool { + let mut ip = start as usize; + let end = end as usize; + while ip < end { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == want { + return true; + } + ip += 1 + op.operand_len(); + } + false +} + +fn region_calls(program: &Program, start: u32, end: u32, import: u16) -> bool { + let mut ip = start as usize; + let end = end as usize; + while ip < end { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == OpCode::Call && call_index(program, ip) == import { + return true; + } + ip += 1 + op.operand_len(); + } + false +} + +fn next_call(program: &Program, from: usize, import: u16) -> usize { + let op = OpCode::try_from(program.code[from]).expect("opcode"); + let mut ip = from + 1 + op.operand_len(); + while ip < program.code.len() { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + if op == OpCode::Call && call_index(program, ip) == import { + return ip; + } + ip += 1 + op.operand_len(); + } + panic!("import {import} does not follow ip {from}"); +} + +fn assert_no_calls_between(program: &Program, from: usize, until: usize) { + let op = OpCode::try_from(program.code[from]).expect("opcode"); + let mut ip = from + 1 + op.operand_len(); + while ip < until { + let op = OpCode::try_from(program.code[ip]).expect("opcode"); + assert!( + !matches!(op, OpCode::Call | OpCode::CallValue | OpCode::CallScript), + "a call sits between Ret and finish_return at {ip}" + ); + ip += 1 + op.operand_len(); + } +} + +fn call_index(program: &Program, ip: usize) -> u16 { + u16::from_le_bytes(program.code[ip + 1..ip + 3].try_into().expect("call index")) +} + +fn note_value(trace: &Trace, tag: f64) -> f64 { + trace + .notes + .iter() + .find(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing note {tag} in {:?}", trace.notes)) + .1 +} + +fn text_value(trace: &Trace, tag: f64) -> &str { + trace + .texts + .iter() + .find(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing text {tag} in {:?}", trace.texts)) + .1 + .as_str() +} + +#[test] +fn source_scalar_return_keeps_the_published_round() { + let ran = run(SOURCE); + let steps = &ran.trace.steps; + assert!( + steps.len() >= 3, + "the witness must step before it returns: {ran:#?}" + ); + assert!( + matches!(steps[0].outcome, StepOutcome::Paused { tail: false }), + "budget 1 must pause the mark before publication: {ran:#?}" + ); + assert_eq!(steps[0].budget, 1); + assert!(steps[0].opened, "the first step opens the idle cycle"); + assert!( + matches!(steps[1].outcome, StepOutcome::Published { .. }), + "the following positive budget must publish and not resume that tail: {ran:#?}" + ); + assert_eq!(note_value(&ran.trace, 30.0), 3.0, "rawlen before publish"); + assert_eq!(note_value(&ran.trace, 10.0), 1.0, "rawlen after publish"); + assert_eq!( + note_value(&ran.trace, 11.0), + 1.0, + "published weak read keeps t" + ); + assert_eq!(ran.trace.sames.len(), 1); + assert_eq!(ran.trace.sames[0].0, ran.trace.sames[0].1); + assert_eq!(ran.trace.peeks.len(), 1); + assert_eq!(ran.trace.sames[0].0, ran.trace.peeks[0].table); + assert_eq!(text_value(&ran.trace, 2.0), "nil"); + assert_eq!(text_value(&ran.trace, 3.0), "nil"); + assert!( + matches!(steps[2].outcome, StepOutcome::Paused { tail: true }), + "budget 1 after publish releases one dead slot and stays in the tail: {ran:#?}" + ); + assert_eq!(steps[2].budget, 1); + assert_eq!(steps[2].node_slot_visits, 1, "one real dead slot"); + assert_eq!(steps[2].live_nodes_before, steps[2].live_nodes_after + 1); + assert_eq!(steps[2].subject_alive, Some(true)); + assert!(steps[2].tail, "the release step keeps the published tail"); + assert_eq!(steps[2].collections, 0); + assert_eq!( + steps[2].live_roots, 3, + "the callee frame still holds its three roots" + ); + assert!( + steps[..3] + .iter() + .all(|step| !matches!(step.outcome, StepOutcome::Completed(_))), + "the cycle must still be open at the return: {ran:#?}" + ); + let handoff = ran.handoff.as_ref().expect("finish_return ran"); + assert!(handoff.lua_frame_alive_at_publish); + assert!( + !handoff.published_root, + "a scalar return does not write a caller root" + ); + assert!( + matches!(handoff.elements.as_slice(), [ReturnedElement::Number(number)] if *number == 1.0) + ); + assert_eq!( + ran.stop, + Stop::Halted, + "retire after Published must leave the callee and continue the same round: {ran:#?}" + ); + assert!(handoff.callee_left, "the callee frame left during retire"); + assert_eq!(handoff.handoff_depth, Some(1)); + assert!(ran.frame.is_none(), "no caller frame remains: {ran:#?}"); + assert_eq!(ran.root_slots, 0, "root count follows retained frames"); + assert!( + steps.len() >= 5, + "return is followed by two budget-1 steps: {ran:#?}" + ); + assert!( + matches!(steps[3].outcome, StepOutcome::Paused { tail: true }), + "budget 1 after return continues the same tail: {ran:#?}" + ); + assert_eq!(steps[3].budget, 1); + assert_eq!(steps[3].node_slot_visits, 1, "second real dead slot"); + assert_eq!(steps[3].live_nodes_before, steps[3].live_nodes_after + 1); + assert_eq!(steps[3].subject_alive, Some(true)); + assert!(steps[3].frame.is_none()); + assert!(steps[3].tail); + assert_eq!(steps[3].live_roots, 0); + assert!( + matches!(steps[4].outcome, StepOutcome::Completed(_)), + "the next budget finishes this round once: {ran:#?}" + ); + assert_eq!( + steps + .iter() + .filter(|step| matches!(step.outcome, StepOutcome::Completed(_))) + .count(), + 1 + ); + assert_eq!( + steps[4].subject_alive, + Some(true), + "the marked subject survives this round" + ); + assert_eq!(steps[4].root_slots, 0); + assert_eq!( + steps[4].collections, 1, + "the completion report is this round's only collection" + ); + assert_eq!(ran.stack, vec![Value::Float(1.0)]); + assert_eq!(ran.collects, 1, "the later full collect is a new round"); + assert_eq!( + ran.collections, 2, + "the step report and the later collect are separate rounds" + ); + assert_eq!( + ran.live_nodes, 0, + "the next full collect reclaims the unrooted nodes" + ); + assert_eq!(ran.live_roots, 0); + assert_eq!( + ran.subject_alive, + Some(false), + "the next full collect reclaims t" + ); + assert_eq!(ran.token_open, Some(false), "that collect closes the token"); + assert!( + !ran.tail, + "the independent collect does not leave the old tail" + ); +} + +const LATE_WRITE: &str = r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + w[3] = {} + step(1) + step(10000) + text(1, "before-write") + w[3] = "late" + return 1 +end +witness() +return 1 +"#; + +const EARLY_WRITE: &str = r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + w[3] = {} + w[3] = "late" + text(1, type(w[3])) + return 1 +end +return witness() +"#; + +const COLLECT_DURING_TAIL: &str = r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + w[3] = {} + step(1) + step(10000) + collectgarbage("collect") + return 1 +end +witness() +return 1 +"#; + +const CHUNK_TAIL: &str = r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + w[3] = {} + step(1) + step(10000) + return 1 +end +local n = witness() +"#; + +const PLAIN_RETURN: &str = r#" +local function witness() + local t = {} + return 1 +end +witness() +return 1 +"#; + +fn assert_sweep_pending(ran: &Ran, why: &str) { + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message == "lua sweep is still pending"), + "{why}: {ran:#?}" + ); +} + +#[test] +fn published_tail_rejects_a_late_string_write() { + let ran = run(LATE_WRITE); + assert!( + matches!( + ran.trace.steps.last().map(|step| step.outcome), + Some(StepOutcome::Published { .. }) + ), + "the write runs only after publication: {ran:#?}" + ); + assert_eq!(text_value(&ran.trace, 1.0), "before-write"); + assert!( + ran.trace + .steps + .iter() + .all(|step| !matches!(step.outcome, StepOutcome::Completed(_))), + "the late write must not finish the round: {ran:#?}" + ); + assert!( + ran.tail, + "the tail is still saved when the write is refused" + ); + assert!(ran.frame.is_some(), "the callee frame is still current"); + let handoff = ran.handoff.as_ref(); + assert!( + handoff.is_none_or(|item| !item.callee_left && item.elements.is_empty()), + "the write fails before return: {ran:#?}" + ); + assert_eq!(ran.collects, 0); + assert_sweep_pending(&ran, "post-publish string write"); +} + +#[test] +fn same_shape_string_write_succeeds_before_publish() { + let ran = run(EARLY_WRITE); + assert_eq!(ran.stop, Stop::Halted, "{ran:#?}"); + assert_eq!(ran.stack, vec![Value::Float(1.0)]); + assert_eq!(text_value(&ran.trace, 1.0), "string"); + assert!(ran.trace.steps.is_empty(), "the early write does not step"); + assert!(!ran.tail); + let handoff = ran.handoff.expect("ordinary return"); + assert!(handoff.callee_left, "no tail still uses leave_roots"); + assert!(matches!( + handoff.elements.as_slice(), + [ReturnedElement::Number(number)] if *number == 1.0 + )); +} + +#[test] +fn published_tail_keeps_the_full_collect_gate() { + let ran = run(COLLECT_DURING_TAIL); + assert!(matches!( + ran.trace.steps.last().map(|step| step.outcome), + Some(StepOutcome::Published { .. }) + )); + assert!( + ran.trace + .steps + .iter() + .all(|step| !matches!(step.outcome, StepOutcome::Completed(_))) + ); + assert!(ran.tail); + assert!(ran.frame.is_some()); + assert!( + ran.handoff + .as_ref() + .is_none_or(|item| !item.callee_left && item.elements.is_empty()), + "collect fails before return: {ran:#?}" + ); + assert_eq!(ran.collects, 0, "the refused collect records no report"); + assert_sweep_pending(&ran, "full collect during a published tail"); +} + +#[test] +fn published_tail_keeps_the_chunk_retire_gate() { + let ran = run(CHUNK_TAIL); + assert!(matches!( + ran.trace.steps.last().map(|step| step.outcome), + Some(StepOutcome::Published { .. }) + )); + assert!( + ran.trace + .steps + .iter() + .all(|step| !matches!(step.outcome, StepOutcome::Completed(_))) + ); + let handoff = ran.handoff.as_ref().expect("callee return ran"); + assert!(handoff.callee_left, "the callee used the private retire"); + assert!( + ran.frame.is_some(), + "chunk leave_roots did not drop the caller frame" + ); + assert!(ran.tail); + assert_eq!(ran.collects, 0); + assert_sweep_pending(&ran, "chunk retire during a published tail"); +} + +#[test] +fn ordinary_scalar_return_still_leaves_roots() { + let ran = run(PLAIN_RETURN); + assert_eq!(ran.stop, Stop::Halted, "{ran:#?}"); + assert_eq!(ran.stack, vec![Value::Float(1.0)]); + assert!(!ran.tail); + assert!(ran.frame.is_none()); + let handoff = ran.handoff.expect("ordinary return"); + assert!(handoff.callee_left); + assert!( + matches!(handoff.elements.as_slice(), [ReturnedElement::Number(number)] if *number == 1.0) + ); + assert!(!handoff.published_root); +} diff --git a/tests/luajit_heap_runtime/value_boundary_tests.rs b/tests/luajit_heap_runtime/value_boundary_tests.rs index 7f974ae..a0485e3 100644 --- a/tests/luajit_heap_runtime/value_boundary_tests.rs +++ b/tests/luajit_heap_runtime/value_boundary_tests.rs @@ -27,6 +27,8 @@ mod resolve; mod return_frame; #[path = "source_closure.rs"] mod source_closure; +#[path = "source_scalar_retire.rs"] +mod source_scalar_retire; #[path = "string_byte_length.rs"] mod string_byte_length; #[path = "table_metatable_protection.rs"] From dc160b173176cd6a6767a113d36f0330451b8f2c Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 14:44:30 +0800 Subject: [PATCH 127/225] fix(lua): refuse a published tail table before the callee retires A direct value call publishes nothing, so a returned table used to retire its frame and then be consumed by rawlen. Fail closed on a validated table in the return transport while a published sweep tail is saved, before any caller root, handoff, or frame exit. Number and nil returns still retire. (cherry picked from commit 1ff1b6f4da63bd96591070ef5ae48938c3d8c45e) --- tests/luajit_heap_runtime/candidate.rs | 14 ++ .../source_scalar_retire.rs | 152 ++++++++++++++++++ 2 files changed, 166 insertions(+) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 2c9ed54..1f25e4f 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1078,6 +1078,20 @@ fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { for value in values.iter() { elements.push(return_element(call, value)?); } + // Shapes are already validated. A retiring callee cannot carry a table + // across a saved tail, before any caller root, handoff, or frame exit. + // Number and nil still retire. publish and the diagnostic witness are not + // this check. + if callee_flag + && elements + .iter() + .any(|element| matches!(element, ReturnedElement::Table { .. })) + { + let tail = heap::saved_sweep_tail(&mut call.vm().host_context()).map_err(heap_error)?; + if tail { + return Err(heap_error(heap::HeapError::SweepPending)); + } + } // Classify each consumed position. Nil, scalars, and the transport array // do not become roots. The callee source name is not consulted. let wrote = publish_consumed_tables(call, &values, &frame_token, publish, &root_slots)?; diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index 39588c8..51e8753 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -614,6 +614,9 @@ fn source_scalar_return_keeps_the_published_round() { assert_eq!(steps[2].subject_alive, Some(true)); assert!(steps[2].tail, "the release step keeps the published tail"); assert_eq!(steps[2].collections, 0); + let callee_before_return = steps[2] + .frame + .expect("callee frame before the scalar return"); assert_eq!( steps[2].live_roots, 3, "the callee frame still holds its three roots" @@ -640,6 +643,11 @@ fn source_scalar_return_keeps_the_published_round() { ); assert!(handoff.callee_left, "the callee frame left during retire"); assert_eq!(handoff.handoff_depth, Some(1)); + assert_ne!( + ran.frame, + Some(callee_before_return), + "the caller slot is not the retired callee {callee_before_return:?}" + ); assert!(ran.frame.is_none(), "no caller frame remains: {ran:#?}"); assert_eq!(ran.root_slots, 0, "root count follows retained frames"); assert!( @@ -901,3 +909,147 @@ fn ordinary_scalar_return_still_leaves_roots() { ); assert!(!handoff.published_root); } + +/// Direct `return rawlen(witness())` consumes the callee table with publish 0. +/// A saved tail must refuse that table before rawlen runs. The same shape with +/// no tail still returns the length. +const TABLE_RETURN: &str = r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + t[1] = t + w[1] = t + w[2] = {} + w[3] = {} + peek(t) + note(30, rawlen(w)) + step(1) + step(10000) + note(10, rawlen(w)) + note(11, same(t, rawget(w, 1))) + text(2, type(rawget(w, 2))) + text(3, type(rawget(w, 3))) + step(1) + return w +end +return rawlen(witness()) +"#; + +const TABLE_RETURN_OPEN: &str = r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + t[1] = t + w[1] = t + w[2] = {} + w[3] = {} + return w +end +return rawlen(witness()) +"#; + +#[test] +fn published_tail_refuses_direct_table_consumption() { + let open = run(TABLE_RETURN_OPEN); + assert_eq!( + open.stop, + Stop::Halted, + "no-tail table return must still reach rawlen: {open:#?}" + ); + assert_eq!( + open.stack, + vec![Value::Float(3.0)], + "no-tail rawlen sees the self-cycle and both orphans: {open:#?}" + ); + assert!(!open.tail, "the open control must not publish a tail"); + let open_handoff = open.handoff.expect("no-tail finish_return"); + assert!( + !open_handoff.published_root, + "direct consumption does not write a caller root" + ); + assert!(matches!( + open_handoff.elements.as_slice(), + [ReturnedElement::Table { .. }] + )); + assert!( + open_handoff.callee_left, + "no tail still retires through leave_roots" + ); + + let ran = run(TABLE_RETURN); + let steps = &ran.trace.steps; + assert!( + steps.len() >= 3, + "the witness must publish and release before it returns w: {ran:#?}" + ); + assert!( + matches!(steps[0].outcome, StepOutcome::Paused { tail: false }), + "budget 1 must pause before publication: {ran:#?}" + ); + assert!( + matches!(steps[1].outcome, StepOutcome::Published { .. }), + "the return must happen after publication: {ran:#?}" + ); + assert_eq!(note_value(&ran.trace, 30.0), 3.0, "rawlen before publish"); + assert_eq!(note_value(&ran.trace, 10.0), 1.0, "rawlen after publish"); + assert_eq!( + note_value(&ran.trace, 11.0), + 1.0, + "published weak read keeps t" + ); + assert_eq!(text_value(&ran.trace, 2.0), "nil"); + assert_eq!(text_value(&ran.trace, 3.0), "nil"); + assert!( + matches!(steps[2].outcome, StepOutcome::Paused { tail: true }), + "budget 1 after publish must pause in Release: {ran:#?}" + ); + assert_eq!(steps[2].budget, 1); + assert!(steps[2].tail, "the release pause keeps the published tail"); + assert_eq!(steps[2].collections, 0); + let callee = steps[2] + .frame + .expect("callee frame during the release pause"); + assert!( + steps + .iter() + .all(|step| !matches!(step.outcome, StepOutcome::Completed(_))), + "the cycle is still open at the table return: {ran:#?}" + ); + assert!( + matches!( + ran.stop, + Stop::HostError(ref message) if message == "lua sweep is still pending" + ), + "direct rawlen consumed a published tail table: stop={:?} stack={:?} published_root={:?} frame={:?} tail={} callee={:?} handoff={:?}", + ran.stop, + ran.stack, + ran.handoff.as_ref().map(|item| item.published_root), + ran.frame, + ran.tail, + callee, + ran.handoff, + ); + assert_eq!(ran.frame, Some(callee), "the original callee stays current"); + assert!(ran.tail, "the published tail stays saved"); + assert_eq!(ran.collects, 0, "refusal records no completion report"); + assert!( + ran.collections == 0, + "the step host recorded no completion report: {ran:#?}" + ); + assert!( + !matches!(ran.stack.as_slice(), [Value::Float(_)]), + "rawlen must not publish a length: {ran:#?}" + ); + assert!( + ran.handoff + .as_ref() + .is_none_or(|item| !item.callee_left && item.elements.is_empty()), + "the table is refused before handoff and retire: {ran:#?}" + ); +} From a8e8a540c0df6befccc5f7b7bc87f6ca1b364fe3 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 16:19:49 +0800 Subject: [PATCH 128/225] feat(lua): publish one returned table into the caller root during Release A saved Release tail can hand one issued table to the direct caller's empty slot before the existing callee retirement. Guest identity and the Core token are checked separately, and every refusal finishes before the slot write. The handoff does not scan, move the tail, or use the ordinary writer. (cherry picked from commit 3bc7604844014a92957094060ae78aea1a386545) --- src/frontends/lua/heap.rs | 70 +++ src/frontends/lua/heap/table.rs | 117 +++++ src/frontends/lua/heap/table/sweep.rs | 23 +- tests/luajit_heap_runtime/candidate.rs | 87 +++- .../source_scalar_retire.rs | 455 ++++++++++++++++++ 5 files changed, 740 insertions(+), 12 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index c94dd71..a49a52d 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -55,6 +55,8 @@ pub use table::{ CellValue, CollectReport, GuestClass, HeapError, HeapLimits, HeapStats, LuaHeap, ObserveFault, PublishedRead, RootFrameId, ScanMeter, }; +#[cfg(test)] +pub use table::{SavedTailPhase, SavedTailState}; use vm::{HostContext, Value}; @@ -654,3 +656,71 @@ pub fn retire_saved_tail_frame( ) -> Result<(), HeapError> { retire_published_root_frame(host, frame).map(|_| ()) } + +/// Phase, cursor, and accounted roots of the saved tail. Does not resume it. +#[cfg(test)] +pub fn saved_tail_state(host: &mut HostContext) -> Result, HeapError> { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + Ok(heap.saved_tail_state()) +} + +/// Copies the scan meter without clearing it. +#[cfg(test)] +pub fn copy_scan_meter(host: &mut HostContext) -> Result { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + Ok(heap.scan_meter()) +} + +/// The table currently stored in one frame slot. Does not scan. +#[cfg(test)] +pub fn rooted_table( + host: &mut HostContext, + frame: RootFrameId, + slot: u32, +) -> Result, HeapError> { + with_heap(host, |heap| heap.rooted_table(frame, slot)) +} + +/// Publishes one returned table into the direct caller slot during Release. +/// +/// The guest carrier and the Core token are checked separately. A stored raw +/// id is not treated as proof that the token is still open. Phase, frame, +/// slot, and mark are checked again before the slot is written. This does not +/// call the ordinary root writer. +#[cfg(test)] +pub fn publish_release_return_root( + host: &mut HostContext, + caller: RootFrameId, + slot: u32, + value: &Value, +) -> Result<(), HeapError> { + if host.scope_state::().is_none() { + return Err(HeapError::SweepDenied); + } + let table = with_heap(host, |heap| match heap.guest_class(value) { + GuestClass::Table(table) => Ok(table), + _ => Err(HeapError::StaleHandle), + })?; + let raw = with_heap(host, |heap| heap.published_token(table))?; + admit_open_table_token(host, table, raw)?; + with_heap(host, |heap| { + heap.store_release_caller_root(caller, slot, table) + }) +} + +/// Borrows the typed token. Does not take ownership and does not write a root. +#[cfg(test)] +fn admit_open_table_token(host: &HostContext, table: TableRef, raw: u64) -> Result<(), HeapError> { + let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let borrowed = host + .borrow_resource_with_key::(handle, &LuaTableResource::key()) + .map_err(HeapError::from_scope)?; + if borrowed.get().table() != table { + return Err(HeapError::StaleHandle); + } + Ok(()) +} diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 8501be0..ae925ed 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -171,6 +171,26 @@ pub struct HeapStats { pub peak_edges: u32, } +/// Phase of a saved published tail. Callers use this instead of `Debug` text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SavedTailPhase { + /// Dead slots are still being released. + Release, + /// Occupied root slots are being counted. + Roots, + /// The tail recorded its report and is finished. + Done, +} + +/// Cursor and accounted roots of one saved tail. Reading this does not scan. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SavedTailState { + pub phase: SavedTailPhase, + pub cursor: usize, + pub live_roots: u32, + pub dead_len: usize, +} + /// Result of one collection. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct CollectReport { @@ -2094,6 +2114,58 @@ impl LuaHeap { Ok(()) } + /// Stores one marked, published table in the direct caller's empty slot. + /// + /// Only a saved Release tail admits this. Phase, frame, slot, emptiness, + /// liveness, and the mark bit are all checked before the assignment. The + /// ordinary writer is not used: this does not call `ensure_sweep_open`, + /// does not park a mark, and does not move the tail cursor, its accounted + /// root count, the scan meter, or the frame stack. + #[cfg(test)] + pub(super) fn store_release_caller_root( + &mut self, + caller: RootFrameId, + slot: u32, + table: TableRef, + ) -> Result<(), HeapError> { + let release = self + .sweep_tail + .as_ref() + .is_some_and(|tail| tail.phase() == sweep::TailPhase::Release); + if self.sweep_tail.is_none() { + return Err(HeapError::SweepDenied); + } + if !release { + return Err(HeapError::SweepPending); + } + let Some(direct) = self.frames.len().checked_sub(2) else { + return Err(HeapError::StaleFrame); + }; + let found = &self.frames[direct]; + if found.index != caller.index || found.generation != caller.generation { + return Err(HeapError::StaleFrame); + } + if slot >= found.width { + return Err(HeapError::StaleFrame); + } + let index = found.start as usize + slot as usize; + if self.roots.get(index).is_none() { + return Err(HeapError::StaleFrame); + } + if self.roots[index].is_some() { + return Err(HeapError::SweepPending); + } + self.require_live(table)?; + if !Self::slot_marked(&self.slots[table.slot() as usize].state) { + return Err(HeapError::SweepPending); + } + // The binding must still be on this slot. Core usability is a separate + // check and is not implied by this raw id. + self.published_token(table)?; + self.roots[index] = Some(Rooted::Table(table)); + Ok(()) + } + /// Clears one slot of an open frame. The frame does not have to be the /// top frame. Other slots, including another slot holding the same table, /// stay. A stale id or an out-of-range slot is refused. An empty slot @@ -2213,6 +2285,51 @@ impl LuaHeap { self.sweep_tail.is_some() } + /// Phase, cursor, and accounted roots. Does not scan or resume the tail. + #[cfg(test)] + pub fn saved_tail_state(&self) -> Option { + let tail = self.sweep_tail.as_ref()?; + let phase = match tail.phase() { + sweep::TailPhase::Release => SavedTailPhase::Release, + sweep::TailPhase::Roots => SavedTailPhase::Roots, + sweep::TailPhase::Done => SavedTailPhase::Done, + }; + Some(SavedTailState { + phase, + cursor: tail.cursor(), + live_roots: tail.accounted_roots(), + dead_len: tail.dead_len(), + }) + } + + /// Copies the scan meter. Does not clear it and does not visit a slot. + #[cfg(test)] + pub fn scan_meter(&self) -> ScanMeter { + self.scan + } + + /// The table in one frame slot, if that slot holds a table. Does not scan. + #[cfg(test)] + pub fn rooted_table( + &self, + frame: RootFrameId, + slot: u32, + ) -> Result, HeapError> { + let (start, width) = { + let found = self.frame(frame)?; + (found.start, found.width) + }; + if slot >= width { + return Err(HeapError::StaleFrame); + } + let index = start as usize + slot as usize; + match self.roots.get(index).copied().flatten() { + None => Ok(None), + Some(Rooted::Table(table)) => Ok(Some(table)), + Some(_) => Err(HeapError::StaleHandle), + } + } + /// Domain that issued handles for this heap. Does not read slots. pub(super) fn domain(&self) -> u64 { self.domain diff --git a/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs index 4a55b95..3fc2d84 100644 --- a/src/frontends/lua/heap/table/sweep.rs +++ b/src/frontends/lua/heap/table/sweep.rs @@ -61,7 +61,7 @@ enum SweepPhase { } /// Release or root scan saved after publish. No snapshot, modes, or owner cursor. -#[derive(Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum TailPhase { Release, Roots, @@ -86,6 +86,27 @@ pub(super) enum TailStep { } impl SweepTail { + #[cfg(test)] + pub(super) fn phase(&self) -> TailPhase { + self.phase + } + + #[cfg(test)] + pub(super) fn cursor(&self) -> usize { + self.index + } + + /// Roots already accounted by a root scan. A Release handoff must not change this. + #[cfg(test)] + pub(super) fn accounted_roots(&self) -> u32 { + self.live_roots + } + + #[cfg(test)] + pub(super) fn dead_len(&self) -> usize { + self.dead.len() + } + /// Spends `budget` on the shared release/root machine. Zero does not read the heap. pub(super) fn drive(self, heap: &mut LuaHeap, budget: u64) -> TailStep { let mut phase = self.phase; diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 1f25e4f..92ff060 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1078,23 +1078,41 @@ fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { for value in values.iter() { elements.push(return_element(call, value)?); } - // Shapes are already validated. A retiring callee cannot carry a table - // across a saved tail, before any caller root, handoff, or frame exit. - // Number and nil still retire. publish and the diagnostic witness are not - // this check. - if callee_flag + // A saved Release tail may publish one issued table into the direct + // caller's empty slot, then the existing retire drops the callee frame. + // Every other table shape, including publish=0, still refuses before any + // root write. Number and nil do not enter this path. + let release_root = if callee_flag && elements .iter() .any(|element| matches!(element, ReturnedElement::Table { .. })) { - let tail = heap::saved_sweep_tail(&mut call.vm().host_context()).map_err(heap_error)?; - if tail { - return Err(heap_error(heap::HeapError::SweepPending)); + match heap::saved_tail_state(&mut call.vm().host_context()).map_err(heap_error)? { + Some(_) => { + if !publish || values.len() != 1 || root_slots.len() != 1 { + return Err(heap_error(heap::HeapError::SweepPending)); + } + Some(publish_release_table( + call, + &values[0], + &frame_token, + &root_slots, + )?) + } + None => None, } - } + } else { + None + }; // Classify each consumed position. Nil, scalars, and the transport array - // do not become roots. The callee source name is not consulted. - let wrote = publish_consumed_tables(call, &values, &frame_token, publish, &root_slots)?; + // do not become roots. The callee source name is not consulted. The + // Release handoff above already wrote its one root and must not call this + // writer again. + let wrote = if release_root.is_some() { + true + } else { + publish_consumed_tables(call, &values, &frame_token, publish, &root_slots)? + }; let lua_frame_alive = if callee_flag { heap::with_heap(&mut call.vm().host_context(), |heap| { Ok(heap.current_frame().is_some()) @@ -1125,6 +1143,7 @@ fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { witness.lua_frame_alive_at_publish = lua_frame_alive; witness.returned_edge_at_handoff = returned_edge; witness.discarded_edge_at_handoff = discarded_edge; + witness.release_root = release_root; witness.handoffs.push(Handoff { elements, published_root: wrote, @@ -1140,6 +1159,41 @@ fn finish_return(call: &mut OwnedHostCall<'_>) -> Result { Ok(transport) } +fn publish_release_table( + call: &mut OwnedHostCall<'_>, + value: &Value, + frame_token: &Value, + root_slots: &[Value], +) -> Result { + if !matches!( + classify(&mut call.vm().host_context(), value)?, + heap::GuestClass::Table(_) + ) { + return Err(heap_error(heap::HeapError::SweepPending)); + } + if matches!(frame_token, Value::Null) { + return Err(heap_error(heap::HeapError::SweepPending)); + } + let frame = decode_frame(call, frame_token)?; + let slot = float_u32(&root_slots[0])?; + let meter_before = heap::copy_scan_meter(&mut call.vm().host_context()).map_err(heap_error)?; + let tail_before = heap::saved_tail_state(&mut call.vm().host_context()) + .map_err(heap_error)? + .ok_or_else(|| heap_error(heap::HeapError::SweepDenied))?; + heap::publish_release_return_root(&mut call.vm().host_context(), frame, slot, value) + .map_err(heap_error)?; + let meter_after = heap::copy_scan_meter(&mut call.vm().host_context()).map_err(heap_error)?; + let tail_after = heap::saved_tail_state(&mut call.vm().host_context()) + .map_err(heap_error)? + .ok_or_else(|| heap_error(heap::HeapError::SweepDenied))?; + Ok(ReleaseRootNote { + meter_before, + meter_after, + tail_before, + tail_after, + }) +} + fn publish_consumed_tables( call: &mut OwnedHostCall<'_>, values: &[Value], @@ -4406,6 +4460,17 @@ pub(super) struct ReturnWitness { pub issued: Vec, /// Whether the latest issued table was still alive at each guest collect. pub issued_alive_at_collect: Vec, + /// Meter and tail snapshot around a Release caller-root write. Absent when + /// that path did not run. + pub release_root: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) struct ReleaseRootNote { + pub meter_before: heap::ScanMeter, + pub meter_after: heap::ScanMeter, + pub tail_before: heap::SavedTailState, + pub tail_after: heap::SavedTailState, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index 51e8753..f4e86df 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -65,6 +65,7 @@ struct StepNote { opened: bool, outcome: StepOutcome, node_slot_visits: u64, + root_slot_visits: u64, live_nodes_before: u32, live_nodes_after: u32, root_slots: u32, @@ -108,6 +109,8 @@ struct Ran { token_open: Option, handoff: Option, collects: usize, + returned: Option, + release_root: Option, } struct Plugin; @@ -284,6 +287,7 @@ fn step_host(host: &mut vm::HostContext<'_>, args: &[Value]) -> Result Ran { .scope_state::() .map(|witness| witness.collects.len()) .unwrap_or(0); + let (returned, release_root) = vm + .host_context() + .scope_state::() + .map(|witness| (witness.returned, witness.release_root.clone())) + .unwrap_or((None, None)); let stop = match status { Ok(VmStatus::Halted) => Stop::Halted, Err(VmError::HostError(message)) => Stop::HostError(message), @@ -423,6 +432,8 @@ fn run(source: &str) -> Ran { token_open, handoff, collects, + returned, + release_root, } } @@ -1053,3 +1064,447 @@ fn published_tail_refuses_direct_table_consumption() { "the table is refused before handoff and retire: {ran:#?}" ); } + +const RETAIN_OPEN: &str = r#" +local function callee() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + t[1] = t + w[1] = t + w[2] = {} + w[3] = {} + peek(t) + note(12, same(t, rawget(t, 1))) + return t +end +local kept = callee() +peek(kept) +note(13, same(kept, rawget(kept, 1))) +collectgarbage("collect") +peek(kept) +note(14, same(kept, rawget(kept, 1))) +kept = nil +collectgarbage("collect") +return 1 +"#; + +const RETAIN_RELEASE: &str = r#" +local function callee() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + t[1] = t + w[1] = t + w[2] = {} + w[3] = {} + peek(t) + note(30, rawlen(w)) + step(1) + step(10000) + note(10, rawlen(w)) + note(11, same(t, rawget(w, 1))) + note(12, same(t, rawget(t, 1))) + text(2, type(rawget(w, 2))) + text(3, type(rawget(w, 3))) + step(1) + return t +end +local kept = callee() +peek(kept) +note(13, same(kept, rawget(kept, 1))) +step(10000) +collectgarbage("collect") +peek(kept) +note(14, same(kept, rawget(kept, 1))) +kept = nil +collectgarbage("collect") +return 1 +"#; + +fn assert_kept_identity(ran: &Ran) { + assert_eq!(ran.stop, Stop::Halted, "{ran:#?}"); + assert_eq!(ran.stack, vec![Value::Float(1.0)], "{ran:#?}"); + assert_eq!( + ran.trace.peeks.len(), + 3, + "callee, caller, and held collect: {ran:#?}" + ); + let issued = ran.trace.peeks[0].table; + assert_eq!( + ran.trace.peeks[1].table, issued, + "caller keeps the original table" + ); + assert_eq!( + ran.trace.peeks[2].table, issued, + "the next collection keeps that identity" + ); + assert_eq!(issued.domain(), ran.trace.peeks[1].table.domain()); + assert_eq!(issued.slot(), ran.trace.peeks[1].table.slot()); + assert_eq!(issued.generation(), ran.trace.peeks[1].table.generation()); + assert_eq!(note_value(&ran.trace, 12.0), 1.0, "self-loop before return"); + assert_eq!(note_value(&ran.trace, 13.0), 1.0, "self-loop after publish"); + assert_eq!( + note_value(&ran.trace, 14.0), + 1.0, + "self-loop after the held collection" + ); + assert_eq!(ran.returned, Some(issued)); + let handoff = ran.handoff.as_ref().expect("finish_return witness"); + assert!(handoff.published_root, "the caller slot receives the table"); + assert!( + handoff.callee_left, + "the callee frame leaves after the publish" + ); + assert!( + handoff.lua_frame_alive_at_publish, + "the callee frame is still current when the caller slot is written" + ); + assert!(matches!( + handoff.elements.as_slice(), + [ReturnedElement::Table { + same_ref: true, + same_carrier: true + }] + )); + assert_eq!( + ran.subject_alive, + Some(false), + "clearing the slot lets the next collection reclaim it" + ); + assert_eq!( + ran.token_open, + Some(false), + "that collection closes the original token" + ); + assert_eq!(ran.live_roots, 0); + assert_eq!(ran.collects, 2, "held collect, then the clear collect"); +} + +#[test] +fn no_tail_local_keeps_the_returned_table_identity() { + let ran = run(RETAIN_OPEN); + assert!(!ran.tail, "no tail was saved: {ran:#?}"); + assert!( + ran.release_root.is_none(), + "the open path does not use the Release writer" + ); + assert_kept_identity(&ran); + assert_eq!(ran.collections, 2, "only the two guest collections ran"); +} + +#[test] +fn published_release_retains_one_returned_table() { + let ran = run(RETAIN_RELEASE); + assert_kept_identity(&ran); + let steps = &ran.trace.steps; + assert!( + steps.len() >= 4, + "publish, release pause, then the continuation: {steps:?}" + ); + assert!(matches!( + steps[0].outcome, + StepOutcome::Paused { tail: false } + )); + assert!(matches!(steps[1].outcome, StepOutcome::Published { .. })); + assert!(matches!( + steps[2].outcome, + StepOutcome::Paused { tail: true } + )); + assert_eq!( + steps[2].node_slot_visits, 1, + "one release visit before the return" + ); + assert_eq!( + steps[2].root_slot_visits, 0, + "Release has not scanned roots" + ); + assert_eq!(note_value(&ran.trace, 30.0), 3.0); + assert_eq!( + note_value(&ran.trace, 10.0), + 1.0, + "weak clear was published" + ); + assert_eq!(note_value(&ran.trace, 11.0), 1.0); + assert_eq!(text_value(&ran.trace, 2.0), "nil"); + assert_eq!(text_value(&ran.trace, 3.0), "nil"); + let note = ran.release_root.as_ref().expect("Release handoff note"); + assert_eq!( + note.meter_before, note.meter_after, + "the handoff does not scan" + ); + assert_eq!( + note.meter_before.root_slot_visits, + note.meter_after.root_slot_visits + ); + assert_eq!(note.tail_before.phase, heap::SavedTailPhase::Release); + assert_eq!(note.tail_after.phase, heap::SavedTailPhase::Release); + assert_eq!(note.tail_before.cursor, note.tail_after.cursor); + assert_eq!(note.tail_before.live_roots, note.tail_after.live_roots); + assert_eq!(note.tail_before.dead_len, note.tail_after.dead_len); + assert_eq!( + note.tail_before.live_roots, 0, + "Release has not accounted a root yet" + ); + let completed: Vec<_> = steps + .iter() + .filter(|step| matches!(step.outcome, StepOutcome::Completed(_))) + .collect(); + assert_eq!(completed.len(), 1, "this cycle reports once: {steps:?}"); + let report = match completed[0].outcome { + StepOutcome::Completed(report) => report, + _ => unreachable!("filtered"), + }; + assert_eq!( + report.live_roots, 1, + "the continuation counts the caller slot once" + ); + assert_eq!( + completed[0].root_slot_visits, 1, + "the later root scan visits that slot once" + ); + assert!( + steps + .iter() + .take(3) + .all(|step| !matches!(step.outcome, StepOutcome::Completed(_))), + "completion is after the return" + ); + assert_ne!( + steps[2].frame, completed[0].frame, + "the callee has left before the report" + ); + assert_eq!( + ran.collections, 3, + "tail report, held collect, then the clear collect" + ); +} + +#[derive(Clone, Copy, Debug)] +enum Refusal { + WrongFrame, + StaleGeneration, + Occupied, + Unmarked, + ClosedToken, + Roots, + NoTail, +} + +struct ReleaseGraph { + caller: heap::RootFrameId, + callee: heap::RootFrameId, + subject: Value, + subject_ref: heap::TableRef, + unmarked: Value, + spare: Value, + occupant: Option, +} + +fn table_of(host: &mut vm::HostContext<'_>, value: &Value) -> heap::TableRef { + match heap::with_heap(host, |heap| Ok(heap.guest_class(value))).expect("class") { + heap::GuestClass::Table(table) => table, + other => panic!("expected an issued table, got {other:?}"), + } +} + +fn open_release(vm: &mut vm::Vm, prefill: bool) -> ReleaseGraph { + let mut host = vm.host_context(); + heap::install(&mut host, heap::HeapLimits::production()).expect("install"); + let caller = heap::with_heap(&mut host, |heap| heap.enter_roots(1)).expect("caller"); + let occupant = if prefill { + let value = heap::publish_guest(&mut host).expect("occupant"); + let table = table_of(&mut host, &value); + heap::with_heap(&mut host, |heap| heap.write_root(caller, 0, table)).expect("prefill"); + Some(table) + } else { + None + }; + let callee = heap::with_heap(&mut host, |heap| heap.enter_roots(1)).expect("callee"); + let subject = heap::publish_guest(&mut host).expect("subject"); + let subject_ref = table_of(&mut host, &subject); + heap::with_heap(&mut host, |heap| heap.write_root(callee, 0, subject_ref)) + .expect("root subject"); + let unmarked = heap::publish_guest(&mut host).expect("unmarked"); + let spare = heap::publish_guest(&mut host).expect("spare unmarked"); + let _dead = heap::publish(&mut host).expect("dead slot"); + heap::open_fixed_step(&mut host).expect("open"); + let _pause = heap::step_fixed_frames(&mut host, 1).expect("mark pause"); + let published = heap::step_fixed_frames(&mut host, 10_000).expect("publish"); + assert!( + matches!(published, StepOutcome::Published { .. }), + "the graph must publish a tail: {published:?}" + ); + let release = heap::step_fixed_frames(&mut host, 1).expect("release"); + assert!( + matches!(release, StepOutcome::Paused { tail: true }), + "one release unit must leave the tail saved: {release:?}" + ); + let state = heap::saved_tail_state(&mut host) + .expect("tail") + .expect("saved"); + assert_eq!(state.phase, heap::SavedTailPhase::Release); + ReleaseGraph { + caller, + callee, + subject, + subject_ref, + unmarked, + spare, + occupant, + } +} + +fn drive_to_roots(host: &mut vm::HostContext<'_>) { + for _ in 0..16 { + let state = heap::saved_tail_state(host).expect("tail read"); + if state.is_some_and(|item| item.phase == heap::SavedTailPhase::Roots) { + return; + } + assert!(state.is_some(), "the tail ended before Roots"); + heap::step_fixed_frames(host, 1).expect("step toward Roots"); + } + panic!("did not reach Roots"); +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct AdmissionSnap { + tail: Option, + meter: heap::ScanMeter, + stats: heap::HeapStats, + caller_root: Option, + frame: Option, +} + +fn admission_snap(host: &mut vm::HostContext<'_>, caller: heap::RootFrameId) -> AdmissionSnap { + AdmissionSnap { + tail: heap::saved_tail_state(host).expect("tail"), + meter: heap::copy_scan_meter(host).expect("meter"), + stats: heap::stats(host).expect("stats"), + caller_root: heap::rooted_table(host, caller, 0).expect("slot"), + frame: heap::with_heap(host, |heap| Ok(heap.current_frame())).expect("frame"), + } +} + +#[test] +fn release_return_root_refuses_without_writing() { + for case in [ + Refusal::WrongFrame, + Refusal::StaleGeneration, + Refusal::Occupied, + Refusal::Unmarked, + Refusal::ClosedToken, + Refusal::Roots, + Refusal::NoTail, + ] { + crate::support::with_idle_vm(|vm| { + let graph = open_release(vm, matches!(case, Refusal::Occupied)); + let mut host = vm.host_context(); + if matches!(case, Refusal::Roots) { + drive_to_roots(&mut host); + } + if matches!(case, Refusal::NoTail) { + let done = heap::step_fixed_frames(&mut host, 10_000).expect("finish tail"); + assert!( + matches!(done, StepOutcome::Completed(_)), + "the no-tail case starts after the report: {done:?}" + ); + } + if matches!(case, Refusal::ClosedToken) { + let raw = + heap::with_heap(&mut host, |heap| heap.published_token(graph.subject_ref)) + .expect("binding"); + let handle = vm::ResourceHandle::from_raw(raw).expect("handle"); + host.close_resource::( + handle, + vm::ResourceCloseReason::Requested, + ) + .expect("close token"); + } + let before = admission_snap(&mut host, graph.caller); + let unmarked_live = matches!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&graph.unmarked))) + .expect("class"), + heap::GuestClass::Table(_) + ); + let value = if !matches!(case, Refusal::Unmarked) { + &graph.subject + } else if unmarked_live { + &graph.unmarked + } else { + &graph.spare + }; + if matches!(case, Refusal::Unmarked) { + assert!( + matches!( + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(value))) + .expect("class"), + heap::GuestClass::Table(_) + ), + "the unmarked refusal needs a still-issued table" + ); + } + let frame = match case { + Refusal::WrongFrame => graph.callee, + Refusal::StaleGeneration => { + let (index, generation) = graph.caller.parts(); + heap::RootFrameId::from_parts(index, generation.wrapping_add(1)) + } + _ => graph.caller, + }; + let error = heap::publish_release_return_root(&mut host, frame, 0, value) + .expect_err("the refused shape must not write"); + match case { + Refusal::WrongFrame | Refusal::StaleGeneration => { + assert!( + matches!(error, heap::HeapError::StaleFrame), + "{case:?} returned {error:?}" + ); + } + Refusal::NoTail => { + assert!( + matches!(error, heap::HeapError::SweepDenied), + "{case:?} returned {error:?}" + ); + } + Refusal::ClosedToken => { + assert!( + matches!(error, heap::HeapError::Scope(_)), + "a stored raw id must not pass a closed token: {error:?}" + ); + let still = + heap::with_heap(&mut host, |heap| heap.published_token(graph.subject_ref)); + assert!( + still.is_ok(), + "the heap binding remains; Core usability is a separate check: {still:?}" + ); + } + Refusal::Occupied | Refusal::Roots => { + assert!( + matches!(error, heap::HeapError::SweepPending), + "{case:?} returned {error:?}" + ); + } + Refusal::Unmarked => { + assert!( + matches!(error, heap::HeapError::StaleHandle), + "publish already cleared the doomed binding: {error:?}" + ); + } + } + let after = admission_snap(&mut host, graph.caller); + assert_eq!(before, after, "{case:?} changed heap state"); + if let Some(occupant) = graph.occupant { + assert_eq!( + after.caller_root, + Some(occupant), + "the occupied slot was replaced" + ); + } + }); + } +} From 8689ec215cdc4a1d9aace77b5811ffe423122878 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 17:38:37 +0800 Subject: [PATCH 129/225] Wire omitted-data GC step in the opt-in Lua test candidate --- src/frontends/lua/heap.rs | 26 ++ tests/luajit_heap_runtime/candidate.rs | 133 ++++++-- .../source_scalar_retire.rs | 284 +++++++++++++++++- 3 files changed, 414 insertions(+), 29 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index a49a52d..d3b0ace 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -604,6 +604,32 @@ pub fn take_scan_meter(host: &mut HostContext) -> Result { with_heap(host, |heap| Ok(heap.take_scan_meter())) } +/// Advances the explicitly enabled source candidate at a positive-budget safepoint. +/// Root candidates have been classified only on the mark path; the private +/// stepper validates the complete batch before scanning and ignores it on a tail. +#[cfg(test)] +pub fn step_source_safepoint( + host: &mut HostContext, + budget: std::num::NonZeroU64, + tables: Vec, +) -> Result { + if saved_source_tail(host) { + return step_private_cycle(host, budget.get(), &[]); + } + with_heap(host, |_| Ok(()))?; + if fixed_step_idle(host)? { + open_private_step_cycle(host)?; + } + let batch: Vec<_> = tables.into_iter().map(table::Rooted::Table).collect(); + step_private_cycle(host, budget.get(), &batch) +} + +#[cfg(test)] +pub fn saved_source_tail(host: &HostContext) -> bool { + host.scope_state::() + .is_some_and(LuaHeap::has_sweep_tail) +} + /// Saves one private mark for a cycle whose roots already sit in fixed frames. /// /// Does not scan. A missing heap, an existing mark, or a saved tail is the diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 92ff060..5702018 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1,7 +1,8 @@ //! Executable slice of the AST lowering. The production file entry does not //! select it until the supported execution and root-transfer gates pass. -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::num::NonZeroU64; use vm::compiler::ir::{FunctionDecl, FunctionImpl, ResolvedHostCall, ResolvedHostParam}; use vm::{ AssignmentKind, CallOutcome, CallReturn, Expr, FrontendIr, HostApiBuilder, HostApiCatalog, @@ -25,6 +26,8 @@ const BOOL_ARG: &str = "lua_internal::bool_arg"; const STRING_ARG: &str = "lua_internal::string_arg"; const GATHER_ROOT: &str = "lua_internal::gather_root"; pub(super) const COLLECT: &str = "lua_internal::collect"; +const STEP: &str = "lua_internal::step"; +const STEP_HAS_TAIL: &str = "lua_internal::step_has_tail"; const COUNT: &str = "lua_internal::count"; const OPEN_CELL: &str = "lua_internal::open_cell"; const READ_CELL: &str = "lua_internal::read_cell"; @@ -76,6 +79,29 @@ pub(super) fn next_counts(vm: &mut vm::Vm) -> Vec { .unwrap_or_default() } +#[derive(Default)] +struct StepBudgets(VecDeque); + +pub(super) fn set_step_budgets(host: &mut vm::HostContext<'_>, budgets: &[NonZeroU64]) { + host.scope_state_or_insert_with(StepBudgets::default) + .expect("test step budget state") + .0 = budgets.iter().copied().collect(); +} + +/// Opt in to the fixture-budgeted guest step in this catalog only. +pub(super) fn install_step_schemas(builder: &mut HostApiBuilder) { + builder.function(HostFunctionSchema::with_return( + STEP_HAS_TAIL, + vec![], + HostTypeSchema::Bool, + )); + builder.function(HostFunctionSchema::with_return( + STEP, + vec![HostParamSchema::value("roots", HostTypeSchema::Unknown)], + HostTypeSchema::Bool, + )); +} + pub(super) fn install_schemas(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( GATHER_ROOT, @@ -242,6 +268,8 @@ pub(super) fn register( Op::StringArg, Op::GatherRoot, Op::Collect, + Op::Step, + Op::StepHasTail, Op::Count, Op::EnterResult, Op::EnterCallee, @@ -283,6 +311,8 @@ pub(super) fn register( Op::StringArg => STRING_ARG, Op::GatherRoot => GATHER_ROOT, Op::Collect => COLLECT, + Op::Step => STEP, + Op::StepHasTail => STEP_HAS_TAIL, Op::Count => COUNT, Op::EnterResult => ENTER_RESULT, Op::EnterCallee => ENTER_CALLEE, @@ -311,6 +341,9 @@ pub(super) fn register( Op::WriteCell => WRITE_CELL, Op::TrackClosure => TRACK_CLOSURE, }; + if matches!(op, Op::Step | Op::StepHasTail) && catalog.function(name).is_none() { + continue; + } let function = catalog.function(name).expect("private Lua operation"); let schema = HostImportSchema::from_function(catalog, function); registry.register_exact_owned(name, function.params.len() as u8, schema, move |_| { @@ -334,6 +367,8 @@ enum Op { StringArg, GatherRoot, Collect, + Step, + StepHasTail, Count, EnterResult, EnterCallee, @@ -517,29 +552,12 @@ impl HostOwnedFunction for Op { Value::Array(roots) } Self::Collect => { - let roots = match call.args() { - [Value::Null] => Vec::new(), - [Value::Array(roots)] => roots.iter().cloned().collect(), - _ => { - return Err(VmError::HostError( - "invalid private Lua root list".to_string(), - )); - } - }; - let mut tables = Vec::with_capacity(roots.len()); - for root in &roots { - match classify(&mut call.vm().host_context(), root)? { - heap::GuestClass::Table(table) => tables.push(table), - _ => { - return Err(VmError::HostError( - "invalid private Lua table root".to_string(), - )); - } - } - } + let tables = decode_safepoint_roots(call)?; collect_at_safepoint(&mut call.vm().host_context(), &tables)?; Value::Float(0.0) } + Self::Step => step_at_safepoint(call)?, + Self::StepHasTail => Value::Bool(heap::saved_source_tail(&call.vm().host_context())), Self::Count => { let kib = heap::with_heap(&mut call.vm().host_context(), |heap| Ok(heap.logical_kib())) @@ -1730,6 +1748,49 @@ pub(super) fn capture_counts(vm: &mut vm::Vm) -> (u32, u32) { .unwrap_or((0, 0)) } +fn decode_safepoint_roots(call: &mut OwnedHostCall<'_>) -> Result, VmError> { + let roots = match call.args() { + [Value::Null] => return Ok(Vec::new()), + [Value::Array(roots)] => roots.clone(), + _ => { + return Err(VmError::HostError( + "invalid private Lua root list".to_string(), + )); + } + }; + let mut host = call.vm().host_context(); + roots + .iter() + .map(|root| match classify(&mut host, root)? { + heap::GuestClass::Table(table) => Ok(table), + _ => Err(VmError::HostError( + "invalid private Lua table root".to_string(), + )), + }) + .collect() +} + +fn step_at_safepoint(call: &mut OwnedHostCall<'_>) -> Result { + let mut host = call.vm().host_context(); + let budget = host + .scope_state_mut::() + .and_then(|budgets| budgets.0.pop_front()) + .ok_or_else(|| VmError::HostError("missing source step fixture budget".to_string()))?; + let tables = if heap::saved_source_tail(&host) { + Vec::new() + } else { + decode_safepoint_roots(call)? + }; + let mut host = call.vm().host_context(); + let outcome = heap::step_source_safepoint(&mut host, budget, tables).map_err(heap_error)?; + if let heap::StepOutcome::Completed(report) = outcome { + note_collect(&mut host, report)?; + Ok(Value::Bool(true)) + } else { + Ok(Value::Bool(false)) + } +} + fn collect_at_safepoint( host: &mut vm::HostContext<'_>, roots: &[heap::TableRef], @@ -3975,6 +4036,13 @@ impl Lower<'_> { if bytes == b"count" { return self.count_expr(expr.span()); } + if bytes == b"step" + && !self.name_is_bound(name) + && self.catalog.function(STEP).is_some() + && self.catalog.function(STEP_HAS_TAIL).is_some() + { + return self.step_expr(expr.span()); + } } if name.is("copy_fields") && let [arg] = args.exprs.as_slice() @@ -4218,6 +4286,27 @@ impl Lower<'_> { } fn collect_expr(&mut self, span: ast::Span) -> Result { + let roots = self.gather_safepoint_roots(span)?; + self.call(COLLECT, vec![roots]) + } + + fn step_expr(&mut self, span: ast::Span) -> Result { + // Defer root gathering to the mark branch, including the reads of + // IR locals. A saved tail passes only the null placeholder to Core. + let start = self.stmts.len(); + let roots = self.gather_safepoint_roots(span)?; + let gather = self.stmts.split_off(start); + Ok(Expr::IfElse { + condition: Box::new(self.call(STEP_HAS_TAIL, vec![])?), + then_expr: Box::new(self.call(STEP, vec![Expr::Null])?), + else_expr: Box::new(Expr::Block { + stmts: gather, + expr: Box::new(self.call(STEP, vec![roots])?), + }), + }) + } + + fn gather_safepoint_roots(&mut self, span: ast::Span) -> Result { // All supported collects are explicit safepoints. Completed arguments // live in compat-emitted temporaries, not in an implicit Core stack scan. let live: Vec<_> = self @@ -4240,7 +4329,7 @@ impl Lower<'_> { }); roots = Expr::MoveVar(next); } - self.call(COLLECT, vec![roots]) + Ok(roots) } fn count_expr(&mut self, _span: ast::Span) -> Result { diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index f4e86df..702c28e 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -2,8 +2,10 @@ //! //! The Lua source is lowered, compiled, and run. The step host records the //! real `StepOutcome`. It does not invent a pause, a publication, or a report. -//! Roots already sit in the callee frame, so the step batch is empty. +//! The private host uses fixed frames; the opt-in guest spelling gathers the +//! current source roots on mark steps and bypasses gathering on tail steps. +use std::num::NonZeroU64; use std::sync::{Arc, OnceLock}; use vm::{ @@ -22,6 +24,7 @@ const PEEK: &str = "lua_host::peek"; const SAME: &str = "lua_host::same"; const NOTE: &str = "lua_host::note"; const TEXT: &str = "lua_host::text"; +const BIT: &str = "lua_host::bit"; const SOURCE: &str = r#" local function witness() @@ -83,6 +86,8 @@ struct Trace { sames: Vec<(heap::TableRef, heap::TableRef)>, notes: Vec<(f64, f64)>, texts: Vec<(f64, String)>, + bits: Vec<(f64, bool)>, + bit_cycle_state: Vec<(bool, u32)>, } #[derive(Clone, Debug)] @@ -113,7 +118,12 @@ struct Ran { release_root: Option, } -struct Plugin; +struct Plugin { + guest_step: bool, +} + +static PLUGIN: Plugin = Plugin { guest_step: false }; +static STEP_PLUGIN: Plugin = Plugin { guest_step: true }; impl SourcePlugin for Plugin { fn flavor(&self) -> SourceFlavor { @@ -129,15 +139,20 @@ impl SourcePlugin for Plugin { } fn parse_source(&self, source: &str) -> Result { - candidate::lower(source, catalog()) + candidate::lower(source, catalog(self.guest_step)) } } -fn catalog() -> &'static Arc { +fn catalog(guest_step: bool) -> &'static Arc { static CATALOG: OnceLock> = OnceLock::new(); - CATALOG.get_or_init(|| { + static STEP_CATALOG: OnceLock> = OnceLock::new(); + let catalog = if guest_step { &STEP_CATALOG } else { &CATALOG }; + catalog.get_or_init(|| { let mut builder = vm::HostApiBuilder::new(); candidate::install_schemas(&mut builder); + if guest_step { + candidate::install_step_schemas(&mut builder); + } let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); builder.function(vm::HostFunctionSchema::with_return( STEP, @@ -177,6 +192,14 @@ fn catalog() -> &'static Arc { ], HostTypeSchema::Bool, )); + builder.function(vm::HostFunctionSchema::with_return( + BIT, + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("bit", HostTypeSchema::Bool), + ], + HostTypeSchema::Bool, + )); Arc::new(builder.build().expect("source scalar catalog")) }) } @@ -188,6 +211,7 @@ fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { (SAME, HostOp::Same), (NOTE, HostOp::Note), (TEXT, HostOp::Text), + (BIT, HostOp::Bit), ] { let function = catalog.function(name).expect("scalar step host schema"); registry @@ -208,6 +232,7 @@ enum HostOp { Same, Note, Text, + Bit, } impl HostOwnedFunction for HostOp { @@ -242,6 +267,18 @@ impl HostOwnedFunction for HostOp { note(&mut host, |state| state.notes.push(noted))?; Value::Float(noted.1) } + Self::Bit => { + let [Value::Float(tag), Value::Bool(bit)] = args.as_slice() else { + return Err(host_fault("expected a guest boolean")); + }; + let tail = heap::saved_sweep_tail(&mut host).map_err(host_heap)?; + let collections = heap::stats(&mut host).map_err(host_heap)?.collections; + note(&mut host, |state| { + state.bits.push((*tag, *bit)); + state.bit_cycle_state.push((tail, collections)); + })?; + Value::Bool(*bit) + } Self::Text => { let [Value::Float(tag), Value::String(text)] = args.as_slice() else { return Err(host_fault("expected text note")); @@ -342,9 +379,18 @@ fn host_heap(error: heap::HeapError) -> VmError { } fn run(source: &str) -> Ran { - let catalog = Arc::clone(catalog()); + run_with_step_budgets(source, None) +} + +fn run_with_step_budgets(source: &str, budgets: Option<&[u64]>) -> Ran { + let catalog = Arc::clone(catalog(budgets.is_some())); + let plugin = if budgets.is_some() { + &STEP_PLUGIN + } else { + &PLUGIN + }; let options = CompileSourceFileOptions::new() - .with_source_plugin(&Plugin) + .with_source_plugin(plugin) .with_host_api_catalog(Arc::clone(&catalog)); let prepared = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) .unwrap_or_else(|error| panic!("compile rejected the source: {error}")); @@ -354,6 +400,13 @@ fn run(source: &str) -> Ran { candidate::register(&mut registry, &catalog).expect("register candidate runtime"); register(&mut registry, &catalog); registry.bind_vm_cached(&mut vm).expect("bind runtime"); + if let Some(budgets) = budgets { + let budgets: Vec<_> = budgets + .iter() + .map(|&budget| NonZeroU64::new(budget).expect("positive fixture budget")) + .collect(); + candidate::set_step_budgets(&mut vm.host_context(), &budgets); + } let status = vm.run(); let trace = vm .host_context() @@ -584,6 +637,223 @@ fn text_value(trace: &Trace, tag: f64) -> &str { .as_str() } +const STEP_WITNESS: &str = r#"local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + w[3] = {} + peek(t) + note(10, rawlen(w)) + note(20, same(t, rawget(w, 1))) + -- tick 1 + note(11, rawlen(w)) + note(21, same(t, rawget(w, 1))) + -- tick 2 + note(12, rawlen(w)) + note(22, same(t, rawget(w, 1))) + -- tick 3 + note(13, rawlen(w)) + note(23, same(t, rawget(w, 1))) + -- tick 4 + note(14, rawlen(w)) + note(24, same(t, rawget(w, 1))) + text(2, type(rawget(w, 2))) + text(3, type(rawget(w, 3))) + return 1 +end +witness() +return 1 +"#; + +fn run_step_witness(arm: &str, ticks: [&str; 4], budgets: Option<&[u64]>) -> Ran { + let mut source = STEP_WITNESS.to_owned(); + for (i, tick) in ticks.into_iter().enumerate() { + if !tick.is_empty() { + source = source.replace(&format!("-- tick {}", i + 1), tick); + } + } + let ran = run_with_step_budgets(&source, budgets); + assert_eq!(ran.stop, Stop::Halted, "{arm}: {ran:#?}"); + assert_eq!(ran.stack, [Value::Float(1.0)]); + let original = ran.trace.peeks[0].table; + assert_eq!(ran.trace.peeks.len(), 1); + assert_eq!(ran.trace.sames, [(original, original); 5]); + for tag in [20.0, 21.0, 22.0, 23.0, 24.0] { + assert_eq!(note_value(&ran.trace, tag), 1.0); + } + assert!(!ran.tail, "all successful arms leave no saved tail"); + assert!(ran.frame.is_none()); + ran +} + +fn weak_lengths(ran: &Ran) -> [f64; 5] { + [10.0, 11.0, 12.0, 13.0, 14.0].map(|tag| note_value(&ran.trace, tag)) +} + +fn assert_final_weak_types(ran: &Ran, expected: &str) { + assert_eq!(text_value(&ran.trace, 2.0), expected); + assert_eq!(text_value(&ran.trace, 3.0), expected); +} + +#[test] +fn guest_step_reports_completion_after_visible_weak_clear() { + let ran = run_step_witness( + "guest-step", + [ + r#"bit(1, collectgarbage("step"))"#, + r#"bit(2, collectgarbage("step"))"#, + r#"bit(3, collectgarbage("step"))"#, + r#"bit(4, collectgarbage("step"))"#, + ], + Some(&[1, 10_000, 1, 10_000]), + ); + let lengths = weak_lengths(&ran); + assert_eq!( + ran.trace.bits, + [(1.0, false), (2.0, false), (3.0, false), (4.0, true)] + ); + assert_eq!( + ran.trace.bit_cycle_state, + [(false, 0), (true, 0), (true, 0), (false, 1)] + ); + assert_eq!(lengths[0], 3.0); + assert_eq!(lengths[4], 1.0); + assert!( + lengths[1..] + .iter() + .zip(&ran.trace.bit_cycle_state) + .any(|(&length, &(tail, collections))| length == 1.0 && tail && collections == 0), + "weak clear visible while the incomplete tail is saved", + ); + assert_final_weak_types(&ran, "nil"); + assert!(ran.trace.steps.is_empty(), "no private test step host ran"); + assert_eq!(ran.collects, 1); + assert_eq!(ran.collections, 1); +} + +const TEMPORARY_STEP: &str = r#" +local function witness() + local w = {} + local mt = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = {} + w[2] = {} + peek(rawget(w, 1)) + -- publish + text(1, type(rawget(w, 1))) + text(2, type(rawget(w, 2))) + -- identity + -- This is not a guest value. Any root gather during the saved tail rejects it. + local unissued = external_shape() + bit(2, collectgarbage("step")) + return 1 +end +witness() +return 1 +"#; + +#[test] +fn guest_step_marks_current_argument_and_skips_tail_root_gather() { + for hold_argument in [true, false] { + let (publish, identity) = if hold_argument { + ( + r#"bit(1, rawequal(rawget(w, 1), (collectgarbage("step"))))"#, + "peek(rawget(w, 1))", + ) + } else { + (r#"bit(1, collectgarbage("step"))"#, "") + }; + let ran = run_with_step_budgets( + &TEMPORARY_STEP + .replace("-- publish", publish) + .replace("-- identity", identity), + Some(&[10_000, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:#?}"); + assert_eq!(ran.trace.bits, [(1.0, false), (2.0, true)]); + assert_eq!(ran.trace.bit_cycle_state, [(true, 0), (false, 1)]); + assert_eq!( + text_value(&ran.trace, 1.0), + if hold_argument { "table" } else { "nil" } + ); + assert_eq!(text_value(&ran.trace, 2.0), "nil"); + assert_eq!(ran.trace.peeks.len(), if hold_argument { 2 } else { 1 }); + if hold_argument { + assert_eq!(ran.trace.peeks[0].table, ran.trace.peeks[1].table); + } + assert_eq!(ran.subject_alive, Some(hold_argument)); + assert!(ran.frame.is_none() && !ran.tail); + assert_eq!(ran.root_slots, 0); + assert_eq!(ran.collections, 1); + assert!(ran.trace.steps.is_empty()); + } +} + +#[test] +fn private_step_matches_guest_witness_graph() { + let ran = run_step_witness( + "private-step", + [ + "note(1, step(1))", + "note(2, step(10000))", + "note(3, step(1))", + "note(4, step(10000))", + ], + None, + ); + assert_eq!(weak_lengths(&ran), [3.0, 3.0, 1.0, 1.0, 1.0]); + assert_final_weak_types(&ran, "nil"); + let [mark, publish, release, done] = ran.trace.steps.as_slice() else { + panic!("expected four private step observations: {ran:#?}"); + }; + assert!(matches!(mark.outcome, StepOutcome::Paused { tail: false })); + assert!(matches!(publish.outcome, StepOutcome::Published { .. })); + assert!(matches!( + release.outcome, + StepOutcome::Paused { tail: true } + )); + assert!(matches!(done.outcome, StepOutcome::Completed(_))); + assert_eq!( + [mark, publish, release, done].map(|step| step.collections), + [0, 0, 0, 1] + ); + assert_eq!( + [1.0, 2.0, 3.0, 4.0].map(|tag| note_value(&ran.trace, tag)), + [0.0, 1.0, 2.0, 3.0] + ); + assert_eq!(ran.collections, 1); + assert!(ran.trace.bits.is_empty()); +} + +#[test] +fn full_collect_matches_guest_witness_graph() { + let ran = run_step_witness( + "full-collect", + [r#"collectgarbage("collect")"#, "", "", ""], + None, + ); + assert_eq!(weak_lengths(&ran), [3.0, 1.0, 1.0, 1.0, 1.0]); + assert_final_weak_types(&ran, "nil"); + assert!(ran.trace.steps.is_empty()); + assert_eq!(ran.collects, 1); + assert_eq!(ran.collections, 1); +} + +#[test] +fn omitted_collect_matches_guest_witness_graph() { + let ran = run_step_witness("omitted", [""; 4], None); + assert_eq!(weak_lengths(&ran), [3.0; 5]); + assert_final_weak_types(&ran, "table"); + assert!(ran.trace.steps.is_empty()); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); +} + #[test] fn source_scalar_return_keeps_the_published_round() { let ran = run(SOURCE); From a0b760af1d2a26f0e66b19ba13fcb98e8f04dc03 Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 18:12:51 +0800 Subject: [PATCH 130/225] fix(lua/heap): mark new UTF-8 table edges during a parked mark --- src/frontends/lua/heap/table.rs | 13 ++ tests/luajit_heap_runtime/parked_mark.rs | 163 +++++++++++++++++++++++ 2 files changed, 176 insertions(+) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index ae925ed..dc433d5 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -1727,6 +1727,16 @@ impl LuaHeap { if self.occupied_edges >= self.limits.edges && !self.reclaim_cursor_gap() { return Err(HeapError::EdgeCapacity); } + // A parked mark may have already scanned this owner. Only a new + // ordinary string field with a table value needs this insertion barrier. + let barrier = if self.mark.is_some() + && matches!(key, EdgeKey::Utf8(_)) + && let EdgeValue::Table { slot, generation } = &value + { + Some((*slot, *generation)) + } else { + None + }; let added = key_payload(&key) + value_payload(&value); let index = self.take_edge_slot(); self.edge_slots[index as usize].edge = Some(Edge { key, value }); @@ -1736,6 +1746,9 @@ impl LuaHeap { self.live_edge_count += 1; self.note_mode_pointer(from_slot, index); self.note_edge_peak(); + if let Some((slot, generation)) = barrier { + self.barrier_strong_field(from_slot, slot, generation); + } Ok(()) } diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index 7fb53ff..e69ecdd 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -248,6 +248,169 @@ fn omitted_pause_keeps_the_pending_edge() { assert_eq!(meter.mark_passes, 1); } +#[derive(Clone, Copy)] +enum NewNamedWrite { + Strong, + WeakValue, + Omitted, +} + +fn new_named_write_after_owner_scan(write: NewNamedWrite) { + use crate::heap::{self, GuestClass, StepOutcome}; + + const NAME: &str = "新键"; + const CHILD: &str = "child"; + let retained = matches!(write, NewNamedWrite::Strong); + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits(8, 2, 8)).expect("install"); + let raw = crate::publish_raw(&mut host); + let target = crate::table_ref(&host, raw); + let (owner, sentinel, child, carrier) = heap::with_heap(&mut host, |heap| { + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let child = heap.alloc()?; + let unrelated = heap.alloc()?; // Forces a real published tail in all arms. + if matches!(write, NewNamedWrite::WeakValue) { + let meta = heap.alloc()?; + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + } + let frame = heap.enter_roots(2)?; + // The Gray stack pops the owner first, then the sentinel. + heap.write_root(frame, 0, sentinel)?; + heap.write_root(frame, 1, owner)?; + heap.set_named_scalar(owner, "old", Value::Bool(true))?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + // Exercise a normal insertion and then an in-place replacement before marking. + heap.set_named_edge(target, CHILD, unrelated)?; + assert_eq!(heap.named_edge(target, CHILD)?, Some(unrelated)); + heap.set_named_edge(target, CHILD, child)?; + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + Ok((owner, sentinel, child, heap.issue_carrier(target)?)) + }) + .expect("graph"); + heap::open_fixed_step(&mut host).expect("start a saved mark"); + let (pending, before) = heap::with_heap(&mut host, |heap| { + let (_, old_record) = heap.locate_named(owner.slot(), "old").expect("old field"); + let (_, sentinel_record) = heap + .locate_named(sentinel.slot(), "pending") + .expect("sentinel field"); + let mut parked = ParkedMark::resume(heap).expect("resume saved mark"); + pause_at(&mut parked, owner.slot(), old_record); + let before_owner_edge = parked.meter().outgoing_edge_checks; + let pending = pause_at(&mut parked, sentinel.slot(), sentinel_record); + let before = parked.meter(); + assert!(before.outgoing_edge_checks > before_owner_edge); + assert!(parked.marked(owner)); + assert!(!parked.marked(target) && !parked.marked(child)); + parked.park()?; + assert!(heap.locate_named(owner.slot(), NAME).is_none()); + if !matches!(write, NewNamedWrite::Omitted) { + heap.set_named_edge(owner, NAME, target)?; + assert_eq!(heap.named_edge(owner, NAME)?, Some(target)); + } + Ok((pending, before)) + }) + .expect("ordinary write while Gray is parked"); + let after = heap::with_heap(&mut host, |heap| { + let parked = ParkedMark::resume(heap).expect("write kept the saved mark"); + assert_eq!(parked.phase_name(), "gray"); + let cursor = parked.pending().expect("sentinel still pending"); + assert_eq!( + (cursor.owner, cursor.cursor), + (pending.owner, pending.cursor) + ); + assert!(!parked.marked(child), "the write must not scan descendants"); + let after = parked.meter(); + assert_eq!(after.outgoing_edge_checks, before.outgoing_edge_checks); + assert_eq!(after.owner_head_checks, before.owner_head_checks); + parked.park()?; + Ok(after) + }) + .expect("cursor observation"); + + // The private fixed-frame path passes an empty supplemental root batch. + let published = heap::step_fixed_frames(&mut host, 128).expect("publish saved mark"); + assert!( + matches!(published, StepOutcome::Published { .. }), + "{published:?}" + ); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.set_named_edge(owner, "blocked", sentinel), + Err(HeapError::SweepPending) + ); + assert!(heap.locate_named(owner.slot(), "blocked").is_none()); + if !retained { + assert_eq!(heap.named_value(owner, NAME)?, Value::Null); + assert_eq!( + heap.locate_named(owner.slot(), NAME).is_some(), + matches!(write, NewNamedWrite::WeakValue), + "a weak-value write leaves a cleared cursor; omission adds no record" + ); + } + Ok(()) + }) + .expect("read during publication"); + let done = heap::step_fixed_frames(&mut host, 128).expect("finish saved tail"); + assert!(matches!(done, StepOutcome::Completed(_)), "{done:?}"); + assert!(heap::fixed_step_idle(&mut host).expect("idle")); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.alive(target), + retained, + "a fresh strong UTF-8 field on a scanned owner must keep its target alive" + ); + assert_eq!( + heap.alive(child), + retained, + "transitive marking in the same pass" + ); + assert_eq!(heap.stats().collections, 1); + assert_eq!(heap.scan_meter().mark_passes, 1); + if retained { + let value = heap.named_value(owner, NAME)?; + assert_eq!(value, carrier); + assert_eq!(heap.guest_class(&value), GuestClass::Table(target)); + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + heap.set_named_scalar(owner, NAME, Value::Null)?; + } + Ok(()) + }) + .expect("same-cycle reachability"); + assert_eq!( + after.parked_barrier_marks - before.parked_barrier_marks, + u64::from(retained) + ); + if retained { + heap::collect(&mut host).expect("next collection after removing the only strong edge"); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(target) && !heap.alive(child)); + assert_eq!(heap.stats().collections, 2); + Ok(()) + }) + .expect("later reclamation"); + } + }); +} + +#[test] +fn gray_new_named_strong_edge_keeps_target_and_descendant() { + new_named_write_after_owner_scan(NewNamedWrite::Strong); +} + +#[test] +fn gray_new_named_weak_value_clears_at_publication() { + new_named_write_after_owner_scan(NewNamedWrite::WeakValue); +} + +#[test] +fn gray_new_named_write_omitted_leaves_target_unreachable() { + new_named_write_after_owner_scan(NewNamedWrite::Omitted); +} + #[test] fn tail_slot_reuse_does_not_keep_the_new_target() { let mut heap = LuaHeap::new(limits(8, 2, 8)); From 686fb29fc9693336f7ec37e3453f4e3f364ec66c Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 00:57:25 +0800 Subject: [PATCH 131/225] test(lua): opt in to guest GC stop, restart, and isrunning Keep the switch in the VM execution scope so an explicit collect or an omitted-data step can resume after stop without collecting, spending a step budget, or crossing a reset. --- tests/luajit_heap_runtime/candidate.rs | 105 +++- .../source_scalar_retire.rs | 547 +++++++++++++++++- 2 files changed, 642 insertions(+), 10 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 5702018..6f28f43 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -28,6 +28,9 @@ const GATHER_ROOT: &str = "lua_internal::gather_root"; pub(super) const COLLECT: &str = "lua_internal::collect"; const STEP: &str = "lua_internal::step"; const STEP_HAS_TAIL: &str = "lua_internal::step_has_tail"; +const GC_STOP: &str = "lua_internal::gc_stop"; +const GC_RESTART: &str = "lua_internal::gc_restart"; +const GC_IS_RUNNING: &str = "lua_internal::gc_is_running"; const COUNT: &str = "lua_internal::count"; const OPEN_CELL: &str = "lua_internal::open_cell"; const READ_CELL: &str = "lua_internal::read_cell"; @@ -102,6 +105,26 @@ pub(super) fn install_step_schemas(builder: &mut HostApiBuilder) { )); } +/// Opt in to guest `stop` / `restart` / `isrunning` in this catalog only. +/// The switch lives in the VM execution scope, not in this catalog. +pub(super) fn install_run_control_schemas(builder: &mut HostApiBuilder) { + builder.function(HostFunctionSchema::with_return( + GC_STOP, + vec![], + HostTypeSchema::Float, + )); + builder.function(HostFunctionSchema::with_return( + GC_RESTART, + vec![], + HostTypeSchema::Float, + )); + builder.function(HostFunctionSchema::with_return( + GC_IS_RUNNING, + vec![], + HostTypeSchema::Bool, + )); +} + pub(super) fn install_schemas(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( GATHER_ROOT, @@ -270,6 +293,9 @@ pub(super) fn register( Op::Collect, Op::Step, Op::StepHasTail, + Op::GcStop, + Op::GcRestart, + Op::GcIsRunning, Op::Count, Op::EnterResult, Op::EnterCallee, @@ -313,6 +339,9 @@ pub(super) fn register( Op::Collect => COLLECT, Op::Step => STEP, Op::StepHasTail => STEP_HAS_TAIL, + Op::GcStop => GC_STOP, + Op::GcRestart => GC_RESTART, + Op::GcIsRunning => GC_IS_RUNNING, Op::Count => COUNT, Op::EnterResult => ENTER_RESULT, Op::EnterCallee => ENTER_CALLEE, @@ -341,7 +370,11 @@ pub(super) fn register( Op::WriteCell => WRITE_CELL, Op::TrackClosure => TRACK_CLOSURE, }; - if matches!(op, Op::Step | Op::StepHasTail) && catalog.function(name).is_none() { + if matches!( + op, + Op::Step | Op::StepHasTail | Op::GcStop | Op::GcRestart | Op::GcIsRunning + ) && catalog.function(name).is_none() + { continue; } let function = catalog.function(name).expect("private Lua operation"); @@ -369,6 +402,9 @@ enum Op { Collect, Step, StepHasTail, + GcStop, + GcRestart, + GcIsRunning, Count, EnterResult, EnterCallee, @@ -554,10 +590,18 @@ impl HostOwnedFunction for Op { Self::Collect => { let tables = decode_safepoint_roots(call)?; collect_at_safepoint(&mut call.vm().host_context(), &tables)?; + restore_running_after_progress(&mut call.vm().host_context())?; Value::Float(0.0) } - Self::Step => step_at_safepoint(call)?, + Self::Step => { + let value = step_at_safepoint(call)?; + restore_running_after_progress(&mut call.vm().host_context())?; + value + } Self::StepHasTail => Value::Bool(heap::saved_source_tail(&call.vm().host_context())), + Self::GcStop => set_gc_running(&mut call.vm().host_context(), false)?, + Self::GcRestart => set_gc_running(&mut call.vm().host_context(), true)?, + Self::GcIsRunning => gc_is_running(&call.vm().host_context()), Self::Count => { let kib = heap::with_heap(&mut call.vm().host_context(), |heap| Ok(heap.logical_kib())) @@ -1770,6 +1814,39 @@ fn decode_safepoint_roots(call: &mut OwnedHostCall<'_>) -> Result, running: bool) -> Result { + // Control only. Do not publish roots, pop a step budget, or touch a saved tail. + let control = host + .scope_state_or_insert_with(|| GcRunControl { running: true }) + .map_err(|error| VmError::HostError(error.to_string()))?; + control.running = running; + Ok(Value::Float(0.0)) +} + +fn gc_is_running(host: &vm::HostContext<'_>) -> Value { + Value::Bool( + host.scope_state::() + .map(|control| control.running) + .unwrap_or(true), + ) +} + +fn restore_running_after_progress(host: &mut vm::HostContext<'_>) -> Result<(), VmError> { + // Only a completed explicit collect or omitted-data step reaches here. + // A refusal returns before this call, so it cannot record a completion or + // skip the heap gate by flipping the switch. + if let Some(control) = host.scope_state_mut::() { + control.running = true; + } + Ok(()) +} + fn step_at_safepoint(call: &mut OwnedHostCall<'_>) -> Result { let mut host = call.vm().host_context(); let budget = host @@ -4043,6 +4120,9 @@ impl Lower<'_> { { return self.step_expr(expr.span()); } + if self.run_control_spelling(bytes) && self.run_control_ready(name) { + return self.run_control_expr(bytes, expr.span()); + } } if name.is("copy_fields") && let [arg] = args.exprs.as_slice() @@ -4285,6 +4365,27 @@ impl Lower<'_> { } } + fn run_control_spelling(&self, bytes: &[u8]) -> bool { + matches!(bytes, b"stop" | b"restart" | b"isrunning") + } + + fn run_control_ready(&self, name: &ast::Name) -> bool { + !self.name_is_bound(name) + && self.catalog.function(GC_STOP).is_some() + && self.catalog.function(GC_RESTART).is_some() + && self.catalog.function(GC_IS_RUNNING).is_some() + } + + fn run_control_expr(&mut self, bytes: &[u8], span: ast::Span) -> Result { + let name = match bytes { + b"stop" => GC_STOP, + b"restart" => GC_RESTART, + b"isrunning" => GC_IS_RUNNING, + _ => return Err(self.unsupported(span)), + }; + self.call(name, vec![]) + } + fn collect_expr(&mut self, span: ast::Span) -> Result { let roots = self.gather_safepoint_roots(span)?; self.call(COLLECT, vec![roots]) diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index 702c28e..6dd767c 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -120,10 +120,21 @@ struct Ran { struct Plugin { guest_step: bool, + run_control: bool, } -static PLUGIN: Plugin = Plugin { guest_step: false }; -static STEP_PLUGIN: Plugin = Plugin { guest_step: true }; +static PLUGIN: Plugin = Plugin { + guest_step: false, + run_control: false, +}; +static STEP_PLUGIN: Plugin = Plugin { + guest_step: true, + run_control: false, +}; +static CONTROL_PLUGIN: Plugin = Plugin { + guest_step: true, + run_control: true, +}; impl SourcePlugin for Plugin { fn flavor(&self) -> SourceFlavor { @@ -139,20 +150,34 @@ impl SourcePlugin for Plugin { } fn parse_source(&self, source: &str) -> Result { - candidate::lower(source, catalog(self.guest_step)) + candidate::lower(source, catalog_for(self.guest_step, self.run_control)) } } fn catalog(guest_step: bool) -> &'static Arc { + catalog_for(guest_step, false) +} + +fn catalog_for(guest_step: bool, run_control: bool) -> &'static Arc { static CATALOG: OnceLock> = OnceLock::new(); static STEP_CATALOG: OnceLock> = OnceLock::new(); - let catalog = if guest_step { &STEP_CATALOG } else { &CATALOG }; + static CONTROL_CATALOG: OnceLock> = OnceLock::new(); + let catalog = if run_control { + &CONTROL_CATALOG + } else if guest_step { + &STEP_CATALOG + } else { + &CATALOG + }; catalog.get_or_init(|| { let mut builder = vm::HostApiBuilder::new(); candidate::install_schemas(&mut builder); - if guest_step { + if guest_step || run_control { candidate::install_step_schemas(&mut builder); } + if run_control { + candidate::install_run_control_schemas(&mut builder); + } let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); builder.function(vm::HostFunctionSchema::with_return( STEP, @@ -379,12 +404,26 @@ fn host_heap(error: heap::HeapError) -> VmError { } fn run(source: &str) -> Ran { - run_with_step_budgets(source, None) + drive(source, None, false, None) } fn run_with_step_budgets(source: &str, budgets: Option<&[u64]>) -> Ran { - let catalog = Arc::clone(catalog(budgets.is_some())); - let plugin = if budgets.is_some() { + drive(source, budgets, false, None) +} + +fn run_control(source: &str, budgets: Option<&[u64]>) -> Ran { + drive(source, budgets, true, None) +} + +fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option) -> Ran { + let catalog = Arc::clone(if run_control { + catalog_for(true, true) + } else { + catalog(budgets.is_some()) + }); + let plugin: &Plugin = if run_control { + &CONTROL_PLUGIN + } else if budgets.is_some() { &STEP_PLUGIN } else { &PLUGIN @@ -407,6 +446,18 @@ fn run_with_step_budgets(source: &str, budgets: Option<&[u64]>) -> Ran { .collect(); candidate::set_step_budgets(&mut vm.host_context(), &budgets); } + if let Some(nodes) = nodes { + heap::install( + &mut vm.host_context(), + heap::HeapLimits { + nodes, + roots: 64, + edges: 64, + max_generation: 8, + }, + ) + .expect("test host installs the node quota before execution"); + } let status = vm.run(); let trace = vm .host_context() @@ -637,6 +688,24 @@ fn text_value(trace: &Trace, tag: f64) -> &str { .as_str() } +fn bit_value(trace: &Trace, tag: f64) -> bool { + trace + .bits + .iter() + .find(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing bit {tag} in {:?}", trace.bits)) + .1 +} + +fn cycle_at(trace: &Trace, tag: f64) -> (bool, u32) { + let index = trace + .bits + .iter() + .position(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing bit {tag} in {:?}", trace.bits)); + trace.bit_cycle_state[index] +} + const STEP_WITNESS: &str = r#"local function witness() local w = {} local mt = {} @@ -1778,3 +1847,465 @@ fn release_return_root_refuses_without_writing() { }); } } + +fn bind_control(source: &str) -> vm::Vm { + let catalog = Arc::clone(catalog_for(true, true)); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&CONTROL_PLUGIN) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .unwrap_or_else(|error| panic!("compile rejected the source: {error}")); + let mut vm = prepared.into_vm().expect("create VM"); + assert_return_window(vm.program()); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind runtime"); + vm +} + +fn finish_reset(vm: &mut vm::Vm) { + vm.reset_for_reuse().expect("start reset"); + let waker = std::task::Waker::noop(); + let mut context = std::task::Context::from_waker(waker); + match vm.poll_reset_for_reuse(&mut context) { + std::task::Poll::Ready(Ok(())) => {} + other => panic!("reset did not finish: {other:?}"), + } +} + +fn control_bits(vm: &mut vm::Vm) -> Vec<(f64, bool)> { + vm.host_context() + .scope_state::() + .map(|trace| trace.bits.clone()) + .unwrap_or_default() +} + +const CONTROL_SWITCH: &str = r#" +local function witness() + local t = {} + peek(t) + bit(1, collectgarbage("isrunning")) + note(1, collectgarbage("stop")) + bit(2, collectgarbage("isrunning")) + return 1 +end +witness() +return 1 +"#; + +#[test] +fn guest_run_control_is_observable_and_does_not_collect() { + let ran = run_control( + r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + peek(t) + bit(1, collectgarbage("isrunning")) + note(1, collectgarbage("stop")) + note(2, collectgarbage("stop")) + bit(2, collectgarbage("isrunning")) + note(3, collectgarbage("count")) + note(4, collectgarbage("count")) + note(5, rawlen(w)) + text(1, type(rawget(w, 2))) + note(6, collectgarbage("restart")) + note(7, collectgarbage("restart")) + bit(3, collectgarbage("isrunning")) + note(8, rawlen(w)) + text(2, type(rawget(w, 2))) + collectgarbage("collect") + bit(4, collectgarbage("isrunning")) + note(9, rawlen(w)) + text(3, type(rawget(w, 2))) + note(10, same(t, rawget(w, 1))) + return 1 +end +witness() +return 1 +"#, + None, + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(ran.stack, [Value::Float(1.0)]); + assert!( + bit_value(&ran.trace, 1.0), + "a fresh execution starts running" + ); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert_eq!(note_value(&ran.trace, 2.0), 0.0, "stop is idempotent"); + assert!(!bit_value(&ran.trace, 2.0)); + let count = note_value(&ran.trace, 3.0); + assert!( + count.is_finite() && count > 0.0, + "count is the logical meter: {count}" + ); + assert_eq!(count, note_value(&ran.trace, 4.0), "stop does not allocate"); + assert_eq!(note_value(&ran.trace, 5.0), 2.0); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!(note_value(&ran.trace, 6.0), 0.0); + assert_eq!(note_value(&ran.trace, 7.0), 0.0, "restart is idempotent"); + assert!(bit_value(&ran.trace, 3.0)); + assert_eq!(note_value(&ran.trace, 8.0), 2.0); + assert_eq!( + text_value(&ran.trace, 2.0), + "table", + "restart does not collect" + ); + assert!(bit_value(&ran.trace, 4.0)); + assert_eq!(note_value(&ran.trace, 9.0), 1.0); + assert_eq!(text_value(&ran.trace, 3.0), "nil"); + assert_eq!(note_value(&ran.trace, 10.0), 1.0, "the strong value stays"); + assert!( + ran.trace.steps.is_empty(), + "control does not run the private step host" + ); + assert_eq!(ran.collects, 1, "only the final explicit collect completes"); + assert_eq!(ran.collections, 1); + assert!(!ran.tail); +} + +#[test] +fn explicit_collect_from_stop_restores_running_and_clears_weak() { + let ran = run_control( + r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + peek(t) + bit(1, collectgarbage("isrunning")) + note(1, collectgarbage("stop")) + bit(2, collectgarbage("isrunning")) + text(1, type(rawget(w, 2))) + collectgarbage("collect") + bit(3, collectgarbage("isrunning")) + text(2, type(rawget(w, 2))) + note(2, same(t, rawget(w, 1))) + note(3, rawlen(w)) + return 1 +end +witness() +return 1 +"#, + None, + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert!(bit_value(&ran.trace, 1.0)); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 2.0)); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert!( + bit_value(&ran.trace, 3.0), + "explicit collect restores running" + ); + assert_eq!(text_value(&ran.trace, 2.0), "nil"); + assert_eq!(note_value(&ran.trace, 2.0), 1.0); + assert_eq!(note_value(&ran.trace, 3.0), 1.0); + assert_eq!(ran.collects, 1); + assert_eq!(ran.collections, 1); +} + +#[test] +fn stopped_guest_step_advances_and_restores_even_when_false() { + let ran = run_control( + r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + w[3] = {} + peek(t) + note(1, collectgarbage("stop")) + bit(1, collectgarbage("isrunning")) + bit(2, collectgarbage("step")) + bit(3, collectgarbage("isrunning")) + note(11, rawlen(w)) + bit(4, collectgarbage("step")) + note(12, rawlen(w)) + bit(5, collectgarbage("step")) + bit(6, collectgarbage("step")) + note(14, rawlen(w)) + text(2, type(rawget(w, 2))) + text(3, type(rawget(w, 3))) + note(20, same(t, rawget(w, 1))) + return 1 +end +witness() +return 1 +"#, + Some(&[1, 10_000, 1, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 1.0)); + assert!( + !bit_value(&ran.trace, 2.0), + "the small budget does not complete" + ); + assert!( + bit_value(&ran.trace, 3.0), + "a false step still restores running" + ); + assert!(!bit_value(&ran.trace, 4.0)); + assert!(!bit_value(&ran.trace, 5.0)); + assert!(bit_value(&ran.trace, 6.0)); + assert_eq!( + [ + cycle_at(&ran.trace, 2.0), + cycle_at(&ran.trace, 4.0), + cycle_at(&ran.trace, 5.0), + cycle_at(&ran.trace, 6.0), + ], + [(false, 0), (true, 0), (true, 0), (false, 1)] + ); + assert_eq!(note_value(&ran.trace, 11.0), 3.0); + assert_eq!( + note_value(&ran.trace, 12.0), + 1.0, + "weak clear is visible on the tail" + ); + assert_eq!(note_value(&ran.trace, 14.0), 1.0); + assert_eq!(text_value(&ran.trace, 2.0), "nil"); + assert_eq!(text_value(&ran.trace, 3.0), "nil"); + assert_eq!(note_value(&ran.trace, 20.0), 1.0); + assert!(ran.trace.steps.is_empty()); + assert_eq!(ran.collects, 1); + assert_eq!(ran.collections, 1); +} + +#[test] +fn stop_during_published_tail_keeps_the_cycle_and_budget() { + let ran = run_control( + r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + bit(1, collectgarbage("step")) + note(1, collectgarbage("stop")) + bit(2, collectgarbage("isrunning")) + note(2, collectgarbage("restart")) + bit(3, collectgarbage("isrunning")) + bit(4, collectgarbage("step")) + bit(5, collectgarbage("step")) + note(20, same(held, rawget(w, 1))) + return 1 +end +witness() +return 1 +"#, + Some(&[10_000, 1, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert!(!bit_value(&ran.trace, 1.0)); + assert_eq!(cycle_at(&ran.trace, 1.0), (true, 0)); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 2.0)); + assert_eq!( + cycle_at(&ran.trace, 2.0), + (true, 0), + "stop does not open a cycle" + ); + assert_eq!(note_value(&ran.trace, 2.0), 0.0); + assert!(bit_value(&ran.trace, 3.0)); + assert_eq!( + cycle_at(&ran.trace, 3.0), + (true, 0), + "restart does not open a cycle" + ); + assert!( + !bit_value(&ran.trace, 4.0), + "the saved unit budget still pauses" + ); + assert_eq!(cycle_at(&ran.trace, 4.0), (true, 0)); + assert!(bit_value(&ran.trace, 5.0)); + assert_eq!(cycle_at(&ran.trace, 5.0), (false, 1)); + assert_eq!(note_value(&ran.trace, 20.0), 1.0); + assert_eq!(ran.collects, 1); + assert_eq!(ran.collections, 1); + assert!(!ran.tail); +} + +#[test] +fn run_control_does_not_cross_vms_or_a_reset_execution() { + let stopped = run_control(CONTROL_SWITCH, None); + assert_eq!(stopped.stop, Stop::Halted, "{stopped:?}"); + assert!(bit_value(&stopped.trace, 1.0)); + assert!(!bit_value(&stopped.trace, 2.0)); + let fresh = run_control(CONTROL_SWITCH, None); + assert_eq!(fresh.stop, Stop::Halted, "{fresh:?}"); + assert!( + bit_value(&fresh.trace, 1.0), + "the shared catalog must not carry the stopped switch into another VM" + ); + assert!(!bit_value(&fresh.trace, 2.0)); + + let mut vm = bind_control(CONTROL_SWITCH); + assert!(matches!(vm.run(), Ok(VmStatus::Halted))); + assert_eq!(control_bits(&mut vm), [(1.0, true), (2.0, false)]); + finish_reset(&mut vm); + assert!( + vm.host_context().scope_state::().is_none(), + "reset publishes a new execution scope" + ); + assert!(matches!(vm.run(), Ok(VmStatus::Halted))); + assert_eq!( + control_bits(&mut vm), + [(1.0, true), (2.0, false)], + "a new execution on the reused VM starts running" + ); +} + +#[test] +fn ordinary_catalog_and_shadowed_name_reject_run_control() { + let witness = |body: &str| { + format!("local function witness()\n {body}\n return 1\nend\nwitness()\nreturn 1\n") + }; + for option in ["stop", "restart", "isrunning"] { + let source = witness(&format!("collectgarbage(\"{option}\")")); + candidate::lower(&source, catalog(false)).expect_err("ordinary catalog keeps the refusal"); + candidate::lower(&source, catalog(true)).expect_err("step opt-in is not run control"); + } + candidate::lower(&witness("collectgarbage(\"collect\")"), catalog(false)) + .expect("ordinary collect still lowers"); + candidate::lower(&witness("collectgarbage(\"count\")"), catalog(false)) + .expect("ordinary count still lowers"); + let dynamic = witness("local opt = \"stop\"\n collectgarbage(opt)"); + candidate::lower(&dynamic, catalog_for(true, true)) + .expect_err("a dynamic option is not this slice"); + let extra = witness("collectgarbage(\"stop\", 0)"); + candidate::lower(&extra, catalog_for(true, true)).expect_err("extra data is not this slice"); + let shadowed = r#" +local collectgarbage = 1 +local function witness() + return collectgarbage("stop") +end +witness() +return 1 +"#; + candidate::lower(shadowed, catalog_for(true, true)) + .expect_err("an upvalue shadows the builtin"); + for option in ["restart", "isrunning"] { + let source = format!( + "local collectgarbage = 1\nlocal function witness()\n return collectgarbage(\"{option}\")\nend\nwitness()\nreturn 1\n" + ); + candidate::lower(&source, catalog_for(true, true)).expect_err(option); + } +} + +#[test] +fn stop_does_not_cancel_a_host_supplied_node_quota() { + let ran = drive( + r#" +local function witness() + local a = {} + peek(a) + note(1, collectgarbage("stop")) + bit(1, collectgarbage("isrunning")) + local b = {} + peek(b) + return 1 +end +witness() +return 1 +"#, + None, + true, + Some(1), + ); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message.contains("lua heap node capacity")), + "the installed node cap still refuses: {:?}", + ran.stop + ); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 1.0)); + assert_eq!( + ran.live_nodes, 1, + "the refused table did not occupy another node" + ); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); +} + +#[test] +fn refused_progress_does_not_fake_completion_or_skip_the_gate() { + let sweep = run_control( + r#" +local function witness() + local w = {} + local mt = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = {} + w[2] = {} + peek(rawget(w, 1)) + bit(1, collectgarbage("step")) + note(1, collectgarbage("stop")) + bit(2, collectgarbage("isrunning")) + collectgarbage("collect") + return 1 +end +witness() +return 1 +"#, + Some(&[10_000]), + ); + assert!( + matches!(sweep.stop, Stop::HostError(ref message) if message.contains("lua sweep is still pending")), + "collect must keep the published-tail gate: {:?}", + sweep.stop + ); + assert!(!bit_value(&sweep.trace, 1.0)); + assert_eq!(cycle_at(&sweep.trace, 1.0), (true, 0)); + assert!(!bit_value(&sweep.trace, 2.0)); + assert_eq!(cycle_at(&sweep.trace, 2.0), (true, 0)); + assert!(sweep.tail, "the refusal must leave the original tail"); + assert_eq!(sweep.collects, 0); + assert_eq!(sweep.collections, 0); + + let missing = run_control( + r#" +local function witness() + local t = {} + peek(t) + note(1, collectgarbage("stop")) + bit(1, collectgarbage("isrunning")) + collectgarbage("step") + return 1 +end +witness() +return 1 +"#, + Some(&[]), + ); + assert!( + matches!(missing.stop, Stop::HostError(ref message) if message.contains("missing source step fixture budget")), + "a missing budget is a real refusal: {:?}", + missing.stop + ); + assert!(!bit_value(&missing.trace, 1.0)); + assert_eq!(missing.collects, 0); + assert_eq!(missing.collections, 0); + assert!(!missing.tail); +} From d995c3ce09692bd3fcde9eeb4d37f261d69579fa Mon Sep 17 00:00:00 2001 From: fffonion Date: Tue, 24 Nov 2026 23:37:34 +0800 Subject: [PATCH 132/225] Accept explicit default data on the opt-in Lua GC step --- tests/luajit_heap_runtime/candidate.rs | 28 +++++++ .../source_scalar_retire.rs | 82 ++++++++++++++++++- 2 files changed, 109 insertions(+), 1 deletion(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 6f28f43..1248097 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -4124,6 +4124,16 @@ impl Lower<'_> { return self.run_control_expr(bytes, expr.span()); } } + // Explicit nil, parser +0, and the string "0" share the omitted step. + // Only those static literals; other expressions stay unsupported. + if name.is("collectgarbage") + && !self.name_is_bound(name) + && self.catalog.function(STEP).is_some() + && self.catalog.function(STEP_HAS_TAIL).is_some() + && self.explicit_default_step_data(&args.exprs) + { + return self.step_expr(expr.span()); + } if name.is("copy_fields") && let [arg] = args.exprs.as_slice() { @@ -4391,6 +4401,24 @@ impl Lower<'_> { self.call(COLLECT, vec![roots]) } + fn explicit_default_step_data(&self, args: &[ast::Expr]) -> bool { + let [ast::Expr::String { bytes, .. }, data] = args else { + return false; + }; + if bytes != b"step" { + return false; + } + match data { + ast::Expr::Nil { .. } => true, + ast::Expr::String { bytes, .. } => bytes == b"0", + ast::Expr::Number { raw, kind, span } => matches!( + self.proven_number(raw, *kind, *span), + Ok(Expr::Float(value)) if value.to_bits() == 0 + ), + _ => false, + } + } + fn step_expr(&mut self, span: ast::Span) -> Result { // Defer root gathering to the mark branch, including the reads of // IR locals. A saved tail passes only the null placeholder to Core. diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index 6dd767c..2e63027 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -432,7 +432,7 @@ fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option .with_source_plugin(plugin) .with_host_api_catalog(Arc::clone(&catalog)); let prepared = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) - .unwrap_or_else(|error| panic!("compile rejected the source: {error}")); + .unwrap_or_else(|error| panic!("compile rejected the source: {error}\n{source}")); let mut vm = prepared.into_vm().expect("create VM"); assert_return_window(vm.program()); let mut registry = HostFunctionRegistry::empty(); @@ -768,6 +768,41 @@ fn assert_final_weak_types(ran: &Ran, expected: &str) { assert_eq!(text_value(&ran.trace, 3.0), expected); } +/// The opt-in slice only lets the guest spell the default data. An empty +/// `data` is the already-supported omitted argument. +fn collect_step_call(data: &str) -> String { + if data.is_empty() { + r#"collectgarbage("step")"#.to_string() + } else { + format!(r#"collectgarbage("step", {data})"#) + } +} + +fn assert_guest_step_cycle(ran: &Ran) { + assert_eq!(weak_lengths(ran), [3.0, 3.0, 1.0, 1.0, 1.0]); + assert_eq!( + ran.trace.bits, + [(1.0, false), (2.0, false), (3.0, false), (4.0, true)] + ); + assert_eq!( + ran.trace.bit_cycle_state, + [(false, 0), (true, 0), (true, 0), (false, 1)] + ); + assert_final_weak_types(ran, "nil"); + assert!(ran.trace.steps.is_empty(), "no private test step host ran"); + assert_eq!(ran.collects, 1, "one completion report"); + assert_eq!(ran.collections, 1, "one completed round"); +} + +fn assert_step_source_rejected(source: &str) { + let error = candidate::lower(source, catalog(true)) + .expect_err("the opt-in step lowering accepted an unsupported shape"); + assert!( + error.message.contains("not lowered yet"), + "expected the existing unsupported path for {source:?}, got {error}" + ); +} + #[test] fn guest_step_reports_completion_after_visible_weak_clear() { let ran = run_step_witness( @@ -804,6 +839,51 @@ fn guest_step_reports_completion_after_visible_weak_clear() { assert_eq!(ran.collections, 1); } +#[test] +fn guest_step_explicit_default_data_matches_omitted() { + for (label, data) in [ + ("omitted", ""), + ("nil", "nil"), + ("zero", "0"), + ("string-zero", "\"0\""), + ] { + let calls: Vec<_> = (1..=4) + .map(|tag| format!("bit({tag}, {})", collect_step_call(data))) + .collect(); + let ran = run_step_witness( + label, + [ + calls[0].as_str(), + calls[1].as_str(), + calls[2].as_str(), + calls[3].as_str(), + ], + Some(&[1, 10_000, 1, 10_000]), + ); + assert_guest_step_cycle(&ran); + } +} + +#[test] +fn guest_step_explicit_default_data_rejects_other_shapes() { + for source in [ + "return collectgarbage(\"step\", 1)\n", + "return collectgarbage(\"step\", \"1\")\n", + "return collectgarbage(\"step\", \"0.0\")\n", + "return collectgarbage(\"step\", \"00\")\n", + "return collectgarbage(\"step\", nil, nil)\n", + "local n = nil\nreturn collectgarbage(\"step\", n)\n", + "return collectgarbage(\"step\", (nil))\n", + "return collectgarbage(\"step\", -0)\n", + "local collectgarbage = type\nreturn collectgarbage(\"step\", nil)\n", + ] { + assert_step_source_rejected(source); + } + let ordinary = candidate::lower("return collectgarbage(\"step\", nil)\n", catalog(false)) + .expect_err("ordinary catalog accepted explicit step data"); + assert!(ordinary.message.contains("not lowered yet"), "{ordinary}"); +} + const TEMPORARY_STEP: &str = r#" local function witness() local w = {} From 39c6648f49d75a81a79d74fd4e037de372fb1c83 Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 01:41:24 +0800 Subject: [PATCH 133/225] Record mixed weak-group publication on the opt-in Lua GC step Observe k, v, and both kv edges from all present to all clear, keep the strong identities, and check a real partial v deletion. The walk does not retain a doomed key or value across collectgarbage("step"). Donor: cdf68d325accad29d0e03ace51d3d2b565b84ed0 EOF conflict with the run-control replay resolved by appending that donor's suffix verbatim to the clean three-way intermediate blob. --- .../source_scalar_retire.rs | 317 ++++++++++++++++++ 1 file changed, 317 insertions(+) diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index 2e63027..e1ff0bb 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -2389,3 +2389,320 @@ return 1 assert_eq!(missing.collections, 0); assert!(!missing.tail); } + +/// Four weak groups publish together through real `collectgarbage("step")`. +/// +/// Upstream control: `evidence/lua52-gc-step/mixed-weak-clear-visibility.{lua,json}`. +/// The lowerable subset has no loop and no `~=`, so a weak-key walk is two +/// `next` calls inside a `do`. That block ends before the next step, which +/// drops the cursors from the gather list; the test must not keep a doomed +/// key or value live in order to count it. Weak values are read only as +/// `type(rawget(...))`. `bit`, `text`, and `note` record those Lua results +/// across the existing host boundary. They do not build the graph or choose +/// the step outcome. The budget queue is the fixture `collectgarbage("step")` +/// consumes, not a LuaJIT step index. +#[test] +fn guest_mixed_weak_step_publishes_four_groups_together() { + for shared in [false, true] { + let step = run_mixed(shared, MixedArm::Step); + assert_mixed_step(&step, shared); + let full = run_mixed(shared, MixedArm::Full); + assert_mixed_settled(&full, shared, MixedArm::Full, [0, 0, 0, 0], 1); + let omitted = run_mixed(shared, MixedArm::Omit); + assert_mixed_settled(&omitted, shared, MixedArm::Omit, [1, 1, 1, 1], 0); + let partial = run_mixed(shared, MixedArm::Partial); + assert_mixed_settled(&partial, shared, MixedArm::Partial, [1, 0, 1, 1], 0); + } +} + +#[derive(Clone, Copy, Debug)] +enum MixedArm { + Step, + Full, + Omit, + Partial, +} + +fn run_mixed(shared: bool, arm: MixedArm) -> Ran { + let budgets: Option<&[u64]> = match arm { + MixedArm::Step => Some(&[1, 10_000, 1, 10_000]), + MixedArm::Full | MixedArm::Omit | MixedArm::Partial => None, + }; + let source = mixed_source(shared, arm); + let ran = run_with_step_budgets(&source, budgets); + assert_eq!( + ran.stop, + Stop::Halted, + "shared={shared} {arm:?} did not halt\n{source}" + ); + assert_eq!(ran.stack, [Value::Float(1.0)], "shared={shared} {arm:?}"); + assert!( + ran.trace.steps.is_empty(), + "shared={shared} {arm:?} used the private step host" + ); + assert!(!ran.tail, "shared={shared} {arm:?} left a sweep tail"); + assert!(ran.frame.is_none(), "shared={shared} {arm:?} left a frame"); + ran +} + +fn assert_mixed_settled( + ran: &Ran, + shared: bool, + arm: MixedArm, + expected: [u32; 4], + collects: usize, +) { + let counts = mixed_counts(&ran.trace, 0); + assert_eq!( + counts, expected, + "shared={shared} {arm:?} group counts, not a combined total" + ); + assert!( + mixed_steps(&ran.trace).is_empty(), + "shared={shared} {arm:?} stepped" + ); + assert_eq!(ran.collects, collects, "shared={shared} {arm:?} reports"); + assert_eq!( + ran.collections, collects as u32, + "shared={shared} {arm:?} heap completions" + ); +} + +fn assert_mixed_step(ran: &Ran, shared: bool) { + let points: Vec<[u32; 4]> = (0..=4) + .map(|point| mixed_counts(&ran.trace, point)) + .collect(); + let steps = mixed_steps(&ran.trace); + assert_eq!( + points[0], + [1, 1, 1, 1], + "shared={shared} groups were not all present before the first step: {points:?}" + ); + let mut cleared = false; + for counts in &points { + assert!( + *counts == [1, 1, 1, 1] || *counts == [0, 0, 0, 0], + "shared={shared} mixed weak snapshot {counts:?} in {points:?}" + ); + if cleared { + assert_eq!( + *counts, + [0, 0, 0, 0], + "shared={shared} resurrected {points:?}" + ); + } + cleared = *counts == [0, 0, 0, 0]; + } + assert_eq!(steps.len(), 4, "shared={shared} steps {steps:?}"); + let trues: Vec<_> = steps + .iter() + .enumerate() + .filter(|(_, (bit, _, _))| *bit) + .map(|(index, _)| index) + .collect(); + assert_eq!( + trues, + vec![3], + "shared={shared} expected one final true, steps={steps:?} points={points:?}" + ); + let mut saw_incomplete_clear = false; + for (index, (bit, tail, collections)) in steps.iter().enumerate() { + let after = points[index + 1]; + if !*bit && after == [0, 0, 0, 0] { + assert_eq!( + (*tail, *collections), + (true, 0), + "shared={shared} cleared while a step was still incomplete" + ); + saw_incomplete_clear = true; + } + if *bit { + assert_eq!(after, [0, 0, 0, 0], "shared={shared} true before clear"); + assert_eq!(*collections, 1, "shared={shared} true without a report"); + assert!(!*tail, "shared={shared} true left a tail"); + } + } + assert!( + saw_incomplete_clear, + "shared={shared} never showed Bool false with all four groups clear: points={points:?} steps={steps:?}" + ); + assert_eq!(ran.collects, 1, "shared={shared} completion reports"); + assert_eq!(ran.collections, 1, "shared={shared} heap completions"); +} + +fn mixed_counts(trace: &Trace, point: u32) -> [u32; 4] { + [ + mixed_key_count(trace, point, 1, "k"), + mixed_value_count(trace, point, 2, "v"), + mixed_key_count(trace, point, 3, "kv-key"), + mixed_value_count(trace, point, 4, "kv-value"), + ] +} + +fn mixed_tag(point: u32, group: u32, signal: u32) -> f64 { + f64::from(1000 + point * 100 + group * 10 + signal) +} + +fn mixed_bit(trace: &Trace, tag: f64) -> bool { + trace + .bits + .iter() + .find(|(found, _)| *found == tag) + .unwrap_or_else(|| panic!("missing mixed bit {tag}")) + .1 +} + +fn mixed_key_count(trace: &Trace, point: u32, group: u32, label: &str) -> u32 { + let tag = |signal| mixed_tag(point, group, signal); + let type_a = text_value(trace, tag(1)); + let type_b = text_value(trace, tag(2)); + let a_keep = mixed_bit(trace, tag(1)); + let b_keep = mixed_bit(trace, tag(2)); + let av_value = mixed_bit(trace, tag(3)); + let bv_value = mixed_bit(trace, tag(4)); + let b_nil = mixed_bit(trace, tag(5)); + let bv_nil = mixed_bit(trace, tag(6)); + assert_eq!( + note_value(trace, tag(1)), + 1.0, + "{label} strong identity at point {point}" + ); + match ( + type_a, type_b, a_keep, b_keep, av_value, bv_value, b_nil, bv_nil, + ) { + ("table", "table", true, false, true, true, false, false) + | ("table", "table", false, true, true, true, false, false) => 1, + ("table", "nil", true, false, true, false, true, true) => 0, + other => panic!("{label} unexpected weak-key observation at point {point}: {other:?}"), + } +} + +fn mixed_value_count(trace: &Trace, point: u32, group: u32, label: &str) -> u32 { + let tag = |signal| mixed_tag(point, group, signal); + assert_eq!( + note_value(trace, tag(1)), + 1.0, + "{label} strong identity at point {point}" + ); + match text_value(trace, tag(1)) { + "table" => 1, + "nil" => 0, + other => panic!("{label} unexpected weak-value type at point {point}: {other}"), + } +} + +fn mixed_steps(trace: &Trace) -> Vec<(bool, bool, u32)> { + trace + .bits + .iter() + .zip(&trace.bit_cycle_state) + .filter(|((tag, _), _)| (1.0..=4.0).contains(tag)) + .map(|((_, bit), (tail, collections))| (*bit, *tail, *collections)) + .collect() +} + +fn mixed_source(shared: bool, arm: MixedArm) -> String { + let mut source = String::from( + "local function witness()\n return 1\nend\nwitness()\n\ + local k_owner = {}\nlocal k_key = {}\nlocal k_value = {}\n\ + local v_owner = {}\nlocal v_key = {}\nlocal v_value = {}\n\ + local kvk_owner = {}\nlocal kvk_key = {}\nlocal kvk_value = {}\n\ + local kvv_owner = {}\nlocal kvv_key = {}\nlocal kvv_value = {}\n", + ); + if shared { + source.push_str( + "local mode_k = {}\nmode_k.__mode = \"k\"\n\ + local mode_v = {}\nmode_v.__mode = \"v\"\n\ + local mode_kv = {}\nmode_kv.__mode = \"kv\"\n\ + setmetatable(k_owner, mode_k)\nsetmetatable(v_owner, mode_v)\n\ + setmetatable(kvk_owner, mode_kv)\nsetmetatable(kvv_owner, mode_kv)\n", + ); + } else { + for (owner, mode) in [ + ("k_owner", "k"), + ("v_owner", "v"), + ("kvk_owner", "kv"), + ("kvv_owner", "kv"), + ] { + let mt = format!("{owner}_mt"); + source.push_str(&format!( + "local {mt} = {{}}\n{mt}.__mode = \"{mode}\"\nsetmetatable({owner}, {mt})\n" + )); + } + } + source.push_str( + "k_owner[k_key] = k_value\nv_owner[v_key] = v_value\n\ + kvk_owner[kvk_key] = kvk_value\nkvv_owner[kvv_key] = kvv_value\n\ + do\n local k_dead = {}\n k_dead.self = k_dead\n k_owner[k_dead] = k_value\nend\n\ + do\n local v_dead = {}\n v_dead.self = v_dead\n v_owner.orphan = v_dead\nend\n\ + do\n local kvk_dead = {}\n kvk_dead.self = kvk_dead\n kvk_owner[kvk_dead] = kvk_value\nend\n\ + do\n local kvv_dead = {}\n kvv_dead.self = kvv_dead\n kvv_owner.orphan = kvv_dead\nend\n", + ); + if matches!(arm, MixedArm::Partial) { + source.push_str("rawset(v_owner, \"orphan\", nil)\n"); + } + if matches!(arm, MixedArm::Full) { + source.push_str("collectgarbage(\"collect\")\n"); + } + let points: &[u32] = if matches!(arm, MixedArm::Step) { + &[0, 1, 2, 3, 4] + } else { + &[0] + }; + for point in points { + if *point > 0 { + source.push_str(&format!("bit({point}, collectgarbage(\"step\"))\n")); + } + push_key_observe(&mut source, *point, 1, "k_owner", "k_key", "k_value"); + push_value_observe(&mut source, *point, 2, "v_owner", "v_key", "v_value"); + push_key_observe(&mut source, *point, 3, "kvk_owner", "kvk_key", "kvk_value"); + push_value_observe(&mut source, *point, 4, "kvv_owner", "kvv_key", "kvv_value"); + } + source.push_str("return 1\n"); + source +} + +fn push_key_observe( + source: &mut String, + point: u32, + group: u32, + owner: &str, + key: &str, + value: &str, +) { + let tag = |signal| 1000 + point * 100 + group * 10 + signal; + let prefix = format!("p{point}g{group}"); + source.push_str(&format!( + "do\n local {prefix}a, {prefix}av = next({owner}, nil)\n \ + local {prefix}b, {prefix}bv = next({owner}, {prefix}a)\n \ + text({t1}, type({prefix}a))\n text({t2}, type({prefix}b))\n \ + bit({b1}, rawequal({prefix}a, {key}))\n bit({b2}, rawequal({prefix}b, {key}))\n \ + bit({b3}, rawequal({prefix}av, {value}))\n bit({b4}, rawequal({prefix}bv, {value}))\n \ + bit({b5}, rawequal({prefix}b, nil))\n bit({b6}, rawequal({prefix}bv, nil))\n \ + note({n1}, same({value}, rawget({owner}, {key})))\nend\n", + t1 = tag(1), + t2 = tag(2), + b1 = tag(1), + b2 = tag(2), + b3 = tag(3), + b4 = tag(4), + b5 = tag(5), + b6 = tag(6), + n1 = tag(1), + )); +} + +fn push_value_observe( + source: &mut String, + point: u32, + group: u32, + owner: &str, + key: &str, + value: &str, +) { + let tag = 1000 + point * 100 + group * 10 + 1; + source.push_str(&format!( + "text({tag}, type(rawget({owner}, \"orphan\")))\n\ + note({tag}, same({value}, rawget({owner}, {key})))\n" + )); +} From 1de5a9ff0498f0637375e32005835bdc6dcba6ce Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 02:48:30 +0800 Subject: [PATCH 134/225] Join runtime step data with guest run control Replay the reviewed runtime-data step onto the reviewed run-control step. Keep each side's insertions, control first, and register StepData only when its schema is present. A successful partial step restores running; it is not only a completed collect or an omitted-data step. Static default literals never call the data host. An expression that lowers does, and both zero signs compare equal there. Source unary -0 is rejected at lowering and does not arrive. Non-canonical zero strings from the explicit-default negatives now lower. Keep them as category refusals before a step, not as new data. --- tests/luajit_heap_runtime/candidate.rs | 98 +++++++- .../source_scalar_retire.rs | 233 +++++++++++++++++- 2 files changed, 320 insertions(+), 11 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 1248097..8a58884 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -31,6 +31,7 @@ const STEP_HAS_TAIL: &str = "lua_internal::step_has_tail"; const GC_STOP: &str = "lua_internal::gc_stop"; const GC_RESTART: &str = "lua_internal::gc_restart"; const GC_IS_RUNNING: &str = "lua_internal::gc_is_running"; +const STEP_DATA: &str = "lua_internal::step_data"; const COUNT: &str = "lua_internal::count"; const OPEN_CELL: &str = "lua_internal::open_cell"; const READ_CELL: &str = "lua_internal::read_cell"; @@ -91,6 +92,13 @@ pub(super) fn set_step_budgets(host: &mut vm::HostContext<'_>, budgets: &[NonZer .0 = budgets.iter().copied().collect(); } +/// Remaining fixture budgets. This read does not pop, step, or gather. +pub(super) fn remaining_step_budgets(host: &mut vm::HostContext<'_>) -> Vec { + host.scope_state::() + .map(|budgets| budgets.0.iter().map(|budget| budget.get()).collect()) + .unwrap_or_default() +} + /// Opt in to the fixture-budgeted guest step in this catalog only. pub(super) fn install_step_schemas(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( @@ -103,6 +111,11 @@ pub(super) fn install_step_schemas(builder: &mut HostApiBuilder) { vec![HostParamSchema::value("roots", HostTypeSchema::Unknown)], HostTypeSchema::Bool, )); + builder.function(HostFunctionSchema::with_return( + STEP_DATA, + vec![HostParamSchema::value("data", HostTypeSchema::Unknown)], + HostTypeSchema::Bool, + )); } /// Opt in to guest `stop` / `restart` / `isrunning` in this catalog only. @@ -296,6 +309,7 @@ pub(super) fn register( Op::GcStop, Op::GcRestart, Op::GcIsRunning, + Op::StepData, Op::Count, Op::EnterResult, Op::EnterCallee, @@ -342,6 +356,7 @@ pub(super) fn register( Op::GcStop => GC_STOP, Op::GcRestart => GC_RESTART, Op::GcIsRunning => GC_IS_RUNNING, + Op::StepData => STEP_DATA, Op::Count => COUNT, Op::EnterResult => ENTER_RESULT, Op::EnterCallee => ENTER_CALLEE, @@ -372,7 +387,12 @@ pub(super) fn register( }; if matches!( op, - Op::Step | Op::StepHasTail | Op::GcStop | Op::GcRestart | Op::GcIsRunning + Op::Step + | Op::StepHasTail + | Op::GcStop + | Op::GcRestart + | Op::GcIsRunning + | Op::StepData ) && catalog.function(name).is_none() { continue; @@ -405,6 +425,7 @@ enum Op { GcStop, GcRestart, GcIsRunning, + StepData, Count, EnterResult, EnterCallee, @@ -602,6 +623,7 @@ impl HostOwnedFunction for Op { Self::GcStop => set_gc_running(&mut call.vm().host_context(), false)?, Self::GcRestart => set_gc_running(&mut call.vm().host_context(), true)?, Self::GcIsRunning => gc_is_running(&call.vm().host_context()), + Self::StepData => step_data_default(call)?, Self::Count => { let kib = heap::with_heap(&mut call.vm().host_context(), |heap| Ok(heap.logical_kib())) @@ -1838,7 +1860,10 @@ fn gc_is_running(host: &vm::HostContext<'_>) -> Value { } fn restore_running_after_progress(host: &mut vm::HostContext<'_>) -> Result<(), VmError> { - // Only a completed explicit collect or omitted-data step reaches here. + // A successful explicit collect, or a successful step, reaches here. + // Success includes a partial step: Bool false does not record completion, + // but still restores running. Omitted data, a static default literal, and + // a runtime expression that already passed the data check share that step. // A refusal returns before this call, so it cannot record a completion or // skip the heap gate by flipping the switch. if let Some(control) = host.scope_state_mut::() { @@ -1847,6 +1872,38 @@ fn restore_running_after_progress(host: &mut vm::HostContext<'_>) -> Result<(), Ok(()) } +fn step_data_default(call: &mut OwnedHostCall<'_>) -> Result { + // Category only. Do not pop a budget, read a tail, or gather. + // Static nil, the byte string "0", and the positive-zero number token + // never call this host; they take the explicit-default arm. An expression + // that expr() lowers arrives here as f64, and both zero sign bits compare + // equal. Source unary `-0` is not an expr(): lowering rejects it, so it + // never arrives. Source unary + is unsupported. Host Int is not a Lua + // number and is not normalized to zero. + let value = match call.args() { + [value] => value.clone(), + _ => { + return Err(VmError::HostError( + "step data is not the default".to_string(), + )); + } + }; + let accepted = match &value { + Value::Null => true, + Value::Float(number) => *number == 0.0, + Value::String(text) => text.as_bytes() == b"0", + Value::Bytes(bytes) => bytes.as_ref() == b"0", + _ => false, + }; + if accepted { + Ok(Value::Bool(true)) + } else { + Err(VmError::HostError( + "step data is not the default".to_string(), + )) + } +} + fn step_at_safepoint(call: &mut OwnedHostCall<'_>) -> Result { let mut host = call.vm().host_context(); let budget = host @@ -4124,8 +4181,9 @@ impl Lower<'_> { return self.run_control_expr(bytes, expr.span()); } } - // Explicit nil, parser +0, and the string "0" share the omitted step. - // Only those static literals; other expressions stay unsupported. + // Explicit nil, the parsed positive zero, and the byte string "0" + // share the omitted step. The number token is +0; source unary + + // is not supported. if name.is("collectgarbage") && !self.name_is_bound(name) && self.catalog.function(STEP).is_some() @@ -4134,6 +4192,16 @@ impl Lower<'_> { { return self.step_expr(expr.span()); } + if name.is("collectgarbage") + && !self.name_is_bound(name) + && self.catalog.function(STEP).is_some() + && self.catalog.function(STEP_HAS_TAIL).is_some() + && self.catalog.function(STEP_DATA).is_some() + && let [ast::Expr::String { bytes, .. }, data] = args.exprs.as_slice() + && bytes == b"step" + { + return self.step_with_runtime_data(expr.span(), data); + } if name.is("copy_fields") && let [arg] = args.exprs.as_slice() { @@ -4419,6 +4487,28 @@ impl Lower<'_> { } } + fn step_with_runtime_data( + &mut self, + span: ast::Span, + data: &ast::Expr, + ) -> Result { + // One ordinary evaluation, then the category host, then the reviewed + // step. A data fault stays; this path does not roll it back. + let value = self.expr(data)?; + let slot = self + .builder + .alloc_local_named(&format!("#step-data:{}", self.stmts.len()))?; + self.stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: value, + line: self.line(span), + }); + let checked = self.call(STEP_DATA, vec![Expr::Var(slot)])?; + self.emit_ignored(checked, self.line(span))?; + self.step_expr(span) + } + fn step_expr(&mut self, span: ast::Span) -> Result { // Defer root gathering to the mark branch, including the reads of // IR locals. A saved tail passes only the null placeholder to Core. diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index e1ff0bb..8e48242 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -116,6 +116,7 @@ struct Ran { collects: usize, returned: Option, release_root: Option, + budgets: Vec, } struct Plugin { @@ -516,6 +517,7 @@ fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option .scope_state::() .map(|witness| (witness.returned, witness.release_root.clone())) .unwrap_or((None, None)); + let budgets = candidate::remaining_step_budgets(&mut vm.host_context()); let stop = match status { Ok(VmStatus::Halted) => Stop::Halted, Err(VmError::HostError(message)) => Stop::HostError(message), @@ -538,6 +540,7 @@ fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option collects, returned, release_root, + budgets, } } @@ -867,21 +870,237 @@ fn guest_step_explicit_default_data_matches_omitted() { #[test] fn guest_step_explicit_default_data_rejects_other_shapes() { for source in [ - "return collectgarbage(\"step\", 1)\n", - "return collectgarbage(\"step\", \"1\")\n", - "return collectgarbage(\"step\", \"0.0\")\n", - "return collectgarbage(\"step\", \"00\")\n", "return collectgarbage(\"step\", nil, nil)\n", - "local n = nil\nreturn collectgarbage(\"step\", n)\n", - "return collectgarbage(\"step\", (nil))\n", + "local opt = \"step\"\nreturn collectgarbage(opt, nil)\n", + // Unary minus is not an ordinary expression. The candidate's number + // token parses as positive zero; source unary + is also unsupported. "return collectgarbage(\"step\", -0)\n", - "local collectgarbage = type\nreturn collectgarbage(\"step\", nil)\n", + "local collectgarbage = nil\nreturn collectgarbage(\"step\", nil)\n", + "local function collectgarbage()\n return nil\nend\nreturn collectgarbage(\"step\", nil)\n", ] { assert_step_source_rejected(source); } let ordinary = candidate::lower("return collectgarbage(\"step\", nil)\n", catalog(false)) .expect_err("ordinary catalog accepted explicit step data"); assert!(ordinary.message.contains("not lowered yet"), "{ordinary}"); + let runtime = candidate::lower( + "local n = nil\nreturn collectgarbage(\"step\", n)\n", + catalog(false), + ) + .expect_err("ordinary catalog accepted runtime step data"); + assert!(runtime.message.contains("not lowered yet"), "{runtime}"); +} + +fn witness_chunk(body: &str) -> String { + format!("local function witness()\n{body} return 1\nend\nwitness()\nreturn 1\n") +} + +/// Runtime data of the same three categories uses the omitted step's bool, +/// weak-clear timing, and single completion report. Literals stay on the +/// reviewed arm above. +#[test] +fn guest_step_runtime_default_data_matches_omitted() { + for (label, data, prelude) in [ + ("runtime-nil", "(nil)", ""), + ("runtime-zero", "0+0", ""), + ("runtime-string", "s", " local s = \"0\"\n"), + ] { + let mut source = STEP_WITNESS.to_owned(); + if !prelude.is_empty() { + source = source.replacen("-- tick 1", &format!("{prelude} -- tick 1"), 1); + } + for tag in 1..=4 { + source = source.replace( + &format!("-- tick {tag}"), + &format!("bit({tag}, {})", collect_step_call(data)), + ); + } + let ran = run_with_step_budgets(&source, Some(&[1, 10_000, 1, 10_000])); + assert_eq!(ran.stop, Stop::Halted, "{label}: {ran:#?}"); + assert_eq!(ran.stack, [Value::Float(1.0)], "{label}"); + assert_guest_step_cycle(&ran); + assert!(ran.budgets.is_empty(), "{label} left {:?}", ran.budgets); + } +} + +/// The data call runs once, including when its value is not a default. +#[test] +fn guest_step_runtime_default_data_evaluates_once() { + let accepted = run_with_step_budgets( + &witness_chunk(" bit(1, collectgarbage(\"step\", note(7, 0)))\n"), + Some(&[1]), + ); + assert_eq!(accepted.stop, Stop::Halted, "{accepted:#?}"); + assert_eq!(accepted.trace.notes, [(7.0, 0.0)]); + assert_eq!(accepted.trace.bits.len(), 1, "{accepted:#?}"); + assert_eq!(accepted.trace.bits[0].0, 1.0); + assert!(accepted.budgets.is_empty(), "{:?}", accepted.budgets); + + let rejected = run_with_step_budgets( + &witness_chunk(" bit(1, collectgarbage(\"step\", note(8, 1)))\n"), + Some(&[1, 9]), + ); + assert!( + matches!(rejected.stop, Stop::HostError(ref message) if message == "step data is not the default"), + "{rejected:#?}" + ); + assert_eq!( + rejected.trace.notes, + [(8.0, 1.0)], + "the rejected call still evaluated once" + ); + assert!( + rejected.trace.bits.is_empty(), + "bit did not run: {rejected:#?}" + ); + assert_eq!(rejected.budgets, [1, 9]); + assert!(!rejected.tail); + assert_eq!(rejected.collects, 0); + assert_eq!(rejected.collections, 0); +} + +/// A bool or non-default number is refused before any step or root gather. +/// The live unissued value would make a mark gather fail with a different fault. +#[test] +fn guest_step_runtime_default_data_rejects_before_advance() { + let queued = [1_u64, 10_000]; + for (label, data) in [ + ("bool", "true"), + ("number", "1"), + ("text", "\"1\""), + // Parent lowering negatives. After the join they lower, then the + // category host refuses them before a step. They are not new data. + ("text-0.0", "\"0.0\""), + ("text-00", "\"00\""), + ] { + let ran = run_with_step_budgets( + &witness_chunk(&format!( + " local unissued = external_shape()\n bit(1, collectgarbage(\"step\", {data}))\n" + )), + Some(&queued), + ); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message == "step data is not the default"), + "{label}: {ran:#?}" + ); + assert_eq!(ran.budgets, queued, "{label}"); + assert!(!ran.tail, "{label}"); + assert_eq!(ran.collects, 0, "{label}"); + assert_eq!(ran.collections, 0, "{label}"); + assert!(ran.trace.bits.is_empty(), "{label}"); + assert!(ran.trace.steps.is_empty(), "{label}"); + } + let gathered = run_with_step_budgets( + &witness_chunk(" local unissued = external_shape()\n bit(1, collectgarbage(\"step\"))\n"), + Some(&queued), + ); + assert!( + matches!( + gathered.stop, + Stop::HostError(ref message) if message.contains("invalid private Lua root candidate") + ), + "mark gather control: {gathered:#?}" + ); + assert_eq!(gathered.budgets, queued, "gather fails before a budget pop"); + assert!(!gathered.tail); + assert_eq!(gathered.collects, 0); +} + +/// An already-supported step inside the data call crosses publish. The outer +/// step then reads that tail and does not gather the caller's unissued value. +/// Cancelling the inner steps makes the same outer call gather and refuse. +#[test] +fn guest_step_runtime_data_reads_tail_after_nested_step() { + let stepped = r#" +local function produce() + local w = {} + local mt = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = {} + w[2] = {} + collectgarbage("step") + collectgarbage("step") + return nil +end +local unissued = external_shape() +bit(1, collectgarbage("step", produce())) +return 1 +"#; + let cancelled = r#" +local function produce() + return nil +end +local unissued = external_shape() +bit(1, collectgarbage("step", produce())) +return 1 +"#; + let ran = run_with_step_budgets(stepped, Some(&[1, 10_000, 1])); + assert_eq!(ran.trace.bits, [(1.0, false)], "{ran:#?}"); + assert_eq!(ran.trace.bit_cycle_state, [(true, 0)]); + assert!(ran.tail, "the outer step continued the saved tail"); + assert!(ran.budgets.is_empty(), "{:?}", ran.budgets); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert_sweep_pending(&ran, "chunk exit keeps the tail the outer step read"); + + let idle = run_with_step_budgets(cancelled, Some(&[1, 10_000, 1])); + assert!( + matches!( + idle.stop, + Stop::HostError(ref message) if message.contains("invalid private Lua root candidate") + ), + "cancelled inner step must gather, not step: {idle:#?}" + ); + assert_eq!(idle.budgets, [1, 10_000, 1]); + assert!(!idle.tail); + assert_eq!(idle.collects, 0); + assert!(idle.trace.bits.is_empty()); +} + +/// A same-name function with arguments is the existing arity refusal. A local +/// binding is the dedicated shadow path. Neither is the opt-in step. +#[test] +fn guest_step_same_name_function_is_not_the_shadow_path() { + let function = run_with_step_budgets( + "local function collectgarbage()\n return nil\nend\nreturn collectgarbage()\n", + Some(&[1]), + ); + assert_eq!(function.stop, Stop::Halted, "{function:#?}"); + assert_eq!(function.stack, [Value::Null]); + assert_eq!(function.budgets, [1]); + assert!(function.trace.bits.is_empty()); + assert!(!function.tail); + + let arity = candidate::lower( + "local function collectgarbage()\n return nil\nend\nreturn collectgarbage(\"step\", nil)\n", + catalog(true), + ) + .expect_err("a same-name function accepted arguments"); + assert!(arity.message.contains("not lowered yet"), "{arity}"); + assert_eq!(arity.line, 4usize, "arity refusal is the call, got {arity}"); + + let shadow = candidate::lower( + "local collectgarbage = nil\nreturn collectgarbage(\"step\", nil)\n", + catalog(true), + ) + .expect_err("a shadowed name became the step builtin"); + assert!(shadow.message.contains("not lowered yet"), "{shadow}"); + assert_eq!( + shadow.line, 2usize, + "shadow refusal is the call, got {shadow}" + ); + + let init = candidate::lower( + "local collectgarbage = type\nreturn collectgarbage(\"step\", nil)\n", + catalog(true), + ) + .expect_err("an unbound value initializer was accepted"); + assert!(init.message.contains("not lowered yet"), "{init}"); + assert_eq!( + init.line, 1usize, + "this is the initializer, not the call shadow, got {init}" + ); } const TEMPORARY_STEP: &str = r#" From 5e87baa23c30d964d28b7aa916a6185e5bea542a Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 02:53:33 +0800 Subject: [PATCH 135/225] Prove runtime data and run control on one catalog A stopped collector accepts variable zero as a real partial step, then literal zero, and completes the weak cycle once. After a published tail, an evaluated non-default is a category refusal: the switch stays stopped, the tail and completion report stay, and the next budget is not consumed. Valid data with a saved tail continues and does not gather. The same data without a tail gathers and refuses. Ordinary and step-only catalogs stay single-purpose. The private switch is read after HostError because the guest cannot call isrunning once the VM has stopped. --- tests/luajit_heap_runtime/candidate.rs | 14 +- .../source_scalar_retire.rs | 228 ++++++++++++++++++ 2 files changed, 237 insertions(+), 5 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 8a58884..55b7a4b 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -1852,11 +1852,15 @@ fn set_gc_running(host: &mut vm::HostContext<'_>, running: bool) -> Result) -> Value { - Value::Bool( - host.scope_state::() - .map(|control| control.running) - .unwrap_or(true), - ) + Value::Bool(gc_running(host)) +} + +/// Read the guest switch after the VM has already stopped. A HostError cannot +/// call `isrunning`. This read does not restart, step, or gather. +pub(super) fn gc_running(host: &vm::HostContext<'_>) -> bool { + host.scope_state::() + .map(|control| control.running) + .unwrap_or(true) } fn restore_running_after_progress(host: &mut vm::HostContext<'_>) -> Result<(), VmError> { diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index 8e48242..a174a6f 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -117,6 +117,7 @@ struct Ran { returned: Option, release_root: Option, budgets: Vec, + running: bool, } struct Plugin { @@ -518,6 +519,7 @@ fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option .map(|witness| (witness.returned, witness.release_root.clone())) .unwrap_or((None, None)); let budgets = candidate::remaining_step_budgets(&mut vm.host_context()); + let running = candidate::gc_running(&vm.host_context()); let stop = match status { Ok(VmStatus::Halted) => Stop::Halted, Err(VmError::HostError(message)) => Stop::HostError(message), @@ -541,6 +543,7 @@ fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option returned, release_root, budgets, + running, } } @@ -2925,3 +2928,228 @@ fn push_value_observe( note({tag}, same({value}, rawget({owner}, {key})))\n" )); } + +/// Stop, then a variable zero, enters a real partial step on the combined +/// catalog. Bool false restores running and does not complete. A later literal +/// `0` is the static default on that same catalog; the weak clear completes once. +#[test] +fn stopped_runtime_zero_steps_partial_then_completes_once() { + let variable = "local zero = 0\nreturn collectgarbage(\"step\", zero)\n"; + let stop = "return collectgarbage(\"stop\")\n"; + let ordinary = candidate::lower(variable, catalog(false)) + .expect_err("ordinary catalog accepted runtime step data"); + assert!(ordinary.message.contains("not lowered yet"), "{ordinary}"); + let ordinary_stop = + candidate::lower(stop, catalog(false)).expect_err("ordinary catalog accepted stop"); + assert!( + ordinary_stop.message.contains("not lowered yet"), + "{ordinary_stop}" + ); + candidate::lower(variable, catalog(true)).expect("step catalog rejected runtime zero"); + let step_stop = + candidate::lower(stop, catalog(true)).expect_err("step-only catalog accepted stop"); + assert!(step_stop.message.contains("not lowered yet"), "{step_stop}"); + candidate::lower(variable, catalog_for(true, true)) + .expect("combined catalog rejected runtime zero"); + candidate::lower(stop, catalog_for(true, true)).expect("combined catalog rejected stop"); + + let ran = run_control( + r#" +local function witness() + local w = {} + local mt = {} + local t = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = t + w[2] = {} + w[3] = {} + peek(t) + local zero = 0 + note(1, collectgarbage("stop")) + bit(1, collectgarbage("isrunning")) + bit(2, collectgarbage("step", zero)) + bit(3, collectgarbage("isrunning")) + note(11, rawlen(w)) + bit(4, collectgarbage("step", 0)) + note(12, rawlen(w)) + bit(5, collectgarbage("step", zero)) + bit(6, collectgarbage("step", 0)) + note(14, rawlen(w)) + text(2, type(rawget(w, 2))) + text(3, type(rawget(w, 3))) + note(20, same(t, rawget(w, 1))) + return 1 +end +witness() +return 1 +"#, + Some(&[1, 10_000, 1, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 1.0), "stop is observable"); + assert!( + !bit_value(&ran.trace, 2.0), + "variable zero returns the real partial Bool false" + ); + assert_eq!( + cycle_at(&ran.trace, 2.0), + (false, 0), + "the partial step does not publish a tail or a completion" + ); + assert!( + bit_value(&ran.trace, 3.0), + "a false runtime step still restores running" + ); + assert!(!bit_value(&ran.trace, 4.0)); + assert!(!bit_value(&ran.trace, 5.0)); + assert!(bit_value(&ran.trace, 6.0), "the cycle completes once"); + assert_eq!( + [ + cycle_at(&ran.trace, 4.0), + cycle_at(&ran.trace, 5.0), + cycle_at(&ran.trace, 6.0), + ], + [(true, 0), (true, 0), (false, 1)] + ); + assert_eq!(note_value(&ran.trace, 11.0), 3.0); + assert_eq!( + note_value(&ran.trace, 12.0), + 1.0, + "the independent weak items clear on the published tail" + ); + assert_eq!(note_value(&ran.trace, 14.0), 1.0); + assert_eq!(text_value(&ran.trace, 2.0), "nil"); + assert_eq!(text_value(&ran.trace, 3.0), "nil"); + assert_eq!(note_value(&ran.trace, 20.0), 1.0); + assert!( + ran.running, + "the successful completion leaves the switch running" + ); + assert!(ran.budgets.is_empty(), "{:?}", ran.budgets); + assert_eq!(ran.collects, 1); + assert_eq!(ran.collections, 1); + assert!(!ran.tail); +} + +/// A published tail, then stop, then an evaluated non-default. The category +/// host refuses before the next budget. Valid data still reads that tail and +/// does not gather; without a tail the same data gathers and refuses. +#[test] +fn stopped_tail_rejects_evaluated_data_before_next_budget() { + let queued = [10_000_u64, 1, 10_000]; + let refused = run_control( + r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + bit(1, collectgarbage("step")) + note(1, collectgarbage("stop")) + bit(2, collectgarbage("isrunning")) + local unissued = external_shape() + collectgarbage("step", note(8, 1)) + return 1 +end +witness() +return 1 +"#, + Some(&queued), + ); + assert!( + matches!(refused.stop, Stop::HostError(ref message) if message == "step data is not the default"), + "category refusal, not lowering: {refused:?}" + ); + assert_eq!( + refused.trace.notes, + [(1.0, 0.0), (8.0, 1.0)], + "stop and the rejected data expression both ran" + ); + assert!(!bit_value(&refused.trace, 1.0)); + assert_eq!( + cycle_at(&refused.trace, 1.0), + (true, 0), + "the refusal starts from a published tail" + ); + assert!( + !bit_value(&refused.trace, 2.0), + "stop was visible before the refusal" + ); + assert!(!refused.running, "the refusal does not restore running"); + assert!(refused.tail, "the published tail remains"); + assert_eq!(refused.collections, 0); + assert_eq!(refused.collects, 0); + assert_eq!( + refused.budgets, + [1, 10_000], + "the next budget segment was not consumed: {:?}", + refused.budgets + ); + assert_eq!(refused.trace.bits.len(), 2, "{refused:?}"); + + let continued = run_control( + r#" +local function witness() + local w = {} + local mt = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = {} + w[2] = {} + bit(1, collectgarbage("step")) + local unissued = external_shape() + local zero = 0 + bit(2, collectgarbage("step", zero)) + return 1 +end +witness() +return 1 +"#, + Some(&[10_000, 1]), + ); + assert_eq!(continued.stop, Stop::Halted, "{continued:?}"); + assert!(!bit_value(&continued.trace, 1.0)); + assert_eq!(cycle_at(&continued.trace, 1.0), (true, 0)); + assert!( + !bit_value(&continued.trace, 2.0), + "valid runtime zero continues the saved tail" + ); + assert_eq!(cycle_at(&continued.trace, 2.0), (true, 0)); + assert!(continued.tail, "the unit budget still leaves the tail"); + assert!(continued.running); + assert!(continued.budgets.is_empty(), "{:?}", continued.budgets); + assert_eq!(continued.collects, 0); + assert_eq!(continued.collections, 0); + + let gathered = run_control( + r#" +local function witness() + local unissued = external_shape() + local zero = 0 + bit(1, collectgarbage("step", zero)) + return 1 +end +witness() +return 1 +"#, + Some(&[1, 9]), + ); + assert!( + matches!( + gathered.stop, + Stop::HostError(ref message) if message.contains("invalid private Lua root candidate") + ), + "no tail must gather, not accept the data and step: {gathered:?}" + ); + assert_eq!(gathered.budgets, [1, 9], "gather fails before a budget pop"); + assert!(!gathered.tail); + assert_eq!(gathered.collects, 0); + assert_eq!(gathered.collections, 0); + assert!(gathered.trace.bits.is_empty(), "{gathered:?}"); +} From cd9af058e24031083a7a446114bea20d4bdbbe84 Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 03:45:58 +0800 Subject: [PATCH 136/225] Replay the parked UTF-8 replacement barrier onto runtime step data Apply the reviewed in-place UTF-8 barrier using its own parent as the merge base. The heap table and parked-mark files match that commit. The runtime step files stay at the destination commit. This replay adds no cross-source test, comment edit, numeric key, automatic GC, or production wiring. --- src/frontends/lua/heap/table.rs | 13 +- tests/luajit_heap_runtime/parked_mark.rs | 237 +++++++++++++++++++++++ 2 files changed, 245 insertions(+), 5 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index dc433d5..aa76519 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2895,16 +2895,19 @@ fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { matches!(key, EdgeKey::Object { slot: key_slot, .. } if *key_slot == slot) } -/// Ordinary non-gap field whose new value is a table. Reserved fields, -/// object keys, gaps, and non-table values stay out of the gray queue. +/// Ordinary non-gap field or UTF-8 key whose new value is a table. +/// Reserved fields, object keys, numbers, gaps, and non-table values stay +/// out of the gray queue. fn replaced_table_target(key: &EdgeKey, old_gap: bool, value: &EdgeValue) -> Option<(u32, u32)> { if old_gap { return None; } - let EdgeKey::Field(field) = key else { - return None; + let ordinary = match key { + EdgeKey::Utf8(_) => true, + EdgeKey::Field(field) => *field != LuaHeap::MODE_FIELD && *field != CELL_EDGE, + EdgeKey::Object { .. } | EdgeKey::Number(_) => false, }; - if *field == LuaHeap::MODE_FIELD || *field == CELL_EDGE { + if !ordinary { return None; } match value { diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index e69ecdd..de8fa29 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -411,6 +411,243 @@ fn gray_new_named_write_omitted_leaves_target_unreachable() { new_named_write_after_owner_scan(NewNamedWrite::Omitted); } +#[derive(Clone, Copy)] +enum ExistingNamedWrite { + Strong, + WeakValue, + Omitted, +} + +const FRESH_UTF8: &str = "新键"; + +fn assert_ordinary_utf8_hit(heap: &LuaHeap, owner: u32, name: &str, index: u32) { + let key = super::EdgeKey::named(name); + let fresh = super::EdgeKey::named(FRESH_UTF8); + assert_ne!(name, FRESH_UTF8); + assert!(matches!(key, super::EdgeKey::Utf8(ref text) if text == name)); + assert!(matches!(fresh, super::EdgeKey::Utf8(_))); + assert_ne!(key, fresh); + assert_eq!( + heap.find_key(owner, &key), + Some(index), + "find_key hits the existing ordinary UTF-8 record" + ); + assert_eq!( + heap.find_key(owner, &fresh), + None, + "the replacement key is not a new key" + ); + let stored = heap.edge_slots[index as usize] + .edge + .as_ref() + .expect("occupied record"); + assert!(matches!(&stored.key, super::EdgeKey::Utf8(text) if text == name)); + assert!(!stored.value.is_cursor_gap()); +} + +/// Replaces an already scanned ordinary UTF-8 record in place. +fn existing_named_replacement_after_owner_scan(write: ExistingNamedWrite) { + use crate::heap::{self, GuestClass, StepOutcome}; + + const OLD: &str = "旧键"; + const CHILD: &str = "child"; + let retained = matches!(write, ExistingNamedWrite::Strong); + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits(8, 2, 8)).expect("install"); + let raw = crate::publish_raw(&mut host); + let target = crate::table_ref(&host, raw); + let (owner, sentinel, child, carrier) = heap::with_heap(&mut host, |heap| { + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let child = heap.alloc()?; + let unrelated = heap.alloc()?; // Forces a real published tail in all arms. + if matches!(write, ExistingNamedWrite::WeakValue) { + let meta = heap.alloc()?; + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + } + let frame = heap.enter_roots(2)?; + // The Gray stack pops the owner first, then the sentinel. + heap.write_root(frame, 0, sentinel)?; + heap.write_root(frame, 1, owner)?; + heap.set_named_scalar(owner, OLD, Value::Bool(true))?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + heap.set_named_edge(target, CHILD, unrelated)?; + heap.set_named_edge(target, CHILD, child)?; + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + assert_eq!(heap.named_value(owner, OLD)?, Value::Bool(true)); + Ok((owner, sentinel, child, heap.issue_carrier(target)?)) + }) + .expect("graph"); + heap::open_fixed_step(&mut host).expect("start a saved mark"); + let old_record = heap::with_heap(&mut host, |heap| { + let (_, old_record) = heap.locate_named(owner.slot(), OLD).expect("old field"); + let (_, sentinel_record) = heap + .locate_named(sentinel.slot(), "pending") + .expect("sentinel field"); + let mut parked = ParkedMark::resume(heap).expect("resume saved mark"); + pause_at(&mut parked, owner.slot(), old_record); + let pending = pause_at(&mut parked, sentinel.slot(), sentinel_record); + assert_eq!(pending.owner, sentinel.slot()); + assert!(parked.marked(owner), "the scanned owner is already marked"); + assert!(!parked.marked(target) && !parked.marked(child)); + let before = parked.meter(); + parked.park()?; + assert_ordinary_utf8_hit(heap, owner.slot(), OLD, old_record); + let edges_before = (heap.stats().live_edges, heap.stats().edge_slots); + if !matches!(write, ExistingNamedWrite::Omitted) { + heap.set_named_edge(owner, OLD, target)?; + assert_eq!(heap.named_edge(owner, OLD)?, Some(target)); + } else { + assert_eq!(heap.named_value(owner, OLD)?, Value::Bool(true)); + } + assert_ordinary_utf8_hit(heap, owner.slot(), OLD, old_record); + assert_eq!( + heap.locate_named(owner.slot(), OLD).map(|(_, index)| index), + Some(old_record), + "the old key record index is unchanged" + ); + assert_eq!( + (heap.stats().live_edges, heap.stats().edge_slots), + edges_before, + "the write does not change the edge count" + ); + if !matches!(write, ExistingNamedWrite::Omitted) { + let stored = heap.edge_slots[old_record as usize] + .edge + .as_ref() + .expect("replaced record"); + assert!(matches!( + stored.value, + super::EdgeValue::Table { slot, generation } + if slot == target.slot() && generation == target.generation() + )); + } + let parked = ParkedMark::resume(heap).expect("write kept the saved mark"); + assert_eq!(parked.phase_name(), "gray"); + let cursor = parked.pending().expect("sentinel still pending"); + assert_eq!( + (cursor.owner, cursor.cursor), + (pending.owner, pending.cursor), + "the pending scan cursor is unchanged" + ); + assert!( + !parked.marked(child), + "the write must not scan the child edge" + ); + assert_eq!( + parked.marked(target), + retained, + "only a strong replacement enters the gray queue immediately" + ); + let after = parked.meter(); + assert_write_did_not_scan(&before, &after); + assert_eq!(after.parked_edge_writes, before.parked_edge_writes); + assert_eq!( + after.parked_barrier_marks - before.parked_barrier_marks, + u64::from(retained) + ); + assert_eq!( + after.scratch.work_pushed - before.scratch.work_pushed, + u64::from(retained) + ); + assert_eq!( + after.node_slot_visits - before.node_slot_visits, + u64::from(retained) * 2 + ); + parked.park()?; + Ok(old_record) + }) + .expect("in-place replacement while Gray is parked"); + + let published = heap::step_fixed_frames(&mut host, 128).expect("publish saved mark"); + assert!( + matches!(published, StepOutcome::Published { .. }), + "{published:?}" + ); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.set_named_edge(owner, "blocked", sentinel), + Err(HeapError::SweepPending) + ); + assert!(heap.locate_named(owner.slot(), "blocked").is_none()); + if matches!(write, ExistingNamedWrite::WeakValue) { + assert_eq!(heap.named_value(owner, OLD)?, Value::Null); + let (_, index) = heap + .locate_named(owner.slot(), OLD) + .expect("a weak-value replacement leaves the cleared cursor"); + assert_eq!(index, old_record); + let stored = heap.edge_slots[index as usize] + .edge + .as_ref() + .expect("retained gap"); + assert!(stored.value.is_cursor_gap()); + assert!(matches!(&stored.key, super::EdgeKey::Utf8(text) if text == OLD)); + } + if matches!(write, ExistingNamedWrite::Omitted) { + assert_eq!(heap.named_value(owner, OLD)?, Value::Bool(true)); + } + Ok(()) + }) + .expect("read during publication"); + let done = heap::step_fixed_frames(&mut host, 128).expect("finish saved tail"); + assert!(matches!(done, StepOutcome::Completed(_)), "{done:?}"); + assert!(heap::fixed_step_idle(&mut host).expect("idle")); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.alive(target), + retained, + "an in-place strong UTF-8 replacement on a scanned owner must keep its target alive" + ); + assert_eq!( + heap.alive(child), + retained, + "the child is reached only by the continued scan" + ); + assert_eq!(heap.stats().collections, 1); + assert_eq!(heap.scan_meter().mark_passes, 1); + if matches!(write, ExistingNamedWrite::Omitted) { + assert_eq!(heap.named_value(owner, OLD)?, Value::Bool(true)); + } + if retained { + let value = heap.named_value(owner, OLD)?; + assert_eq!(value, carrier); + assert_eq!(heap.guest_class(&value), GuestClass::Table(target)); + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + heap.set_named_scalar(owner, OLD, Value::Null)?; + } + Ok(()) + }) + .expect("same-cycle reachability"); + if retained { + heap::collect(&mut host).expect("next collection after removing the only strong edge"); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(target) && !heap.alive(child)); + assert_eq!(heap.stats().collections, 2); + Ok(()) + }) + .expect("later reclamation"); + } + }); +} + +#[test] +fn gray_existing_utf8_strong_replacement_keeps_the_new_graph() { + existing_named_replacement_after_owner_scan(ExistingNamedWrite::Strong); +} + +#[test] +fn gray_existing_utf8_weak_replacement_clears_at_publication() { + existing_named_replacement_after_owner_scan(ExistingNamedWrite::WeakValue); +} + +#[test] +fn gray_existing_utf8_omitted_replacement_keeps_the_original_scalar() { + existing_named_replacement_after_owner_scan(ExistingNamedWrite::Omitted); +} + #[test] fn tail_slot_reuse_does_not_keep_the_new_target() { let mut heap = LuaHeap::new(limits(8, 2, 8)); From a79f3d736dcf06d1beacf85b430aab4c4a7d912b Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 04:36:32 +0800 Subject: [PATCH 137/225] Replay the parked number replacement barrier onto runtime step data Apply the reviewed in-place number barrier using its own parent as the merge base. The heap table and parked-mark files match that commit. The runtime step files stay at the destination commit. This replay adds no comment, cross-source test, new numeric key, automatic GC, object key, gap, or production wiring. --- src/frontends/lua/heap/table.rs | 10 +- tests/luajit_heap_runtime/parked_mark.rs | 270 +++++++++++++++++++++++ 2 files changed, 275 insertions(+), 5 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index aa76519..4dadc08 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2895,17 +2895,17 @@ fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { matches!(key, EdgeKey::Object { slot: key_slot, .. } if *key_slot == slot) } -/// Ordinary non-gap field or UTF-8 key whose new value is a table. -/// Reserved fields, object keys, numbers, gaps, and non-table values stay -/// out of the gray queue. +/// Ordinary non-gap field, UTF-8, or number key whose new value is a table. +/// Reserved fields, object keys, gaps, and non-table values stay out of the +/// gray queue. fn replaced_table_target(key: &EdgeKey, old_gap: bool, value: &EdgeValue) -> Option<(u32, u32)> { if old_gap { return None; } let ordinary = match key { - EdgeKey::Utf8(_) => true, + EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, EdgeKey::Field(field) => *field != LuaHeap::MODE_FIELD && *field != CELL_EDGE, - EdgeKey::Object { .. } | EdgeKey::Number(_) => false, + EdgeKey::Object { .. } => false, }; if !ordinary { return None; diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index de8fa29..f3473e2 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -648,6 +648,276 @@ fn gray_existing_utf8_omitted_replacement_keeps_the_original_scalar() { existing_named_replacement_after_owner_scan(ExistingNamedWrite::Omitted); } +#[derive(Clone, Copy)] +enum ExistingNumberWrite { + Strong, + WeakValue, + Omitted, +} + +/// Ordinary finite key. `EdgeKey::number` already stores `+0` and `-0` as the +/// same bits, so this witness does not pair those spellings. +const NUMBER_KEY: f64 = 7.0; +const ORIGINAL_NUMBER_SCALAR: &str = "原值"; + +/// Replaces an already scanned ordinary number record in place. +fn existing_number_replacement_after_owner_scan(write: ExistingNumberWrite) { + use crate::heap::{self, GuestClass, StepOutcome}; + + const CHILD: &str = "child"; + const OTHER_KEY: f64 = 9.0; + let retained = matches!(write, ExistingNumberWrite::Strong); + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits(8, 2, 8)).expect("install"); + let raw = crate::publish_raw(&mut host); + let target = crate::table_ref(&host, raw); + let (owner, sentinel, child, stale, carrier) = heap::with_heap(&mut host, |heap| { + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let child = heap.alloc()?; + let unrelated = heap.alloc()?; // Forces a real published tail in all arms. + let stale = heap.alloc()?; + heap.rollback(stale)?; + if matches!(write, ExistingNumberWrite::WeakValue) { + let meta = heap.alloc()?; + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + } + let frame = heap.enter_roots(2)?; + // The Gray stack pops the owner first, then the sentinel. + heap.write_root(frame, 0, sentinel)?; + heap.write_root(frame, 1, owner)?; + heap.set_number_scalar(owner, NUMBER_KEY, Value::string(ORIGINAL_NUMBER_SCALAR))?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + heap.set_named_edge(target, CHILD, unrelated)?; + heap.set_named_edge(target, CHILD, child)?; + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + assert_eq!( + heap.number_value(owner, NUMBER_KEY)?, + Value::string(ORIGINAL_NUMBER_SCALAR) + ); + Ok((owner, sentinel, child, stale, heap.issue_carrier(target)?)) + }) + .expect("graph"); + heap::open_fixed_step(&mut host).expect("start a saved mark"); + let old_record = heap::with_heap(&mut host, |heap| { + let number_key = super::EdgeKey::number(NUMBER_KEY); + let old_record = heap + .find_key(owner.slot(), &number_key) + .expect("existing number record"); + let stored = heap.edge_slots[old_record as usize] + .edge + .as_ref() + .expect("occupied number record"); + assert_eq!(&stored.key, &number_key); + assert!(matches!(stored.key, super::EdgeKey::Number(_))); + assert!(!matches!(stored.key, super::EdgeKey::Field(_))); + assert!(!stored.value.is_cursor_gap()); + let (_, sentinel_record) = heap + .locate_named(sentinel.slot(), "pending") + .expect("sentinel field"); + let mut parked = ParkedMark::resume(heap).expect("resume saved mark"); + pause_at(&mut parked, owner.slot(), old_record); + let pending = pause_at(&mut parked, sentinel.slot(), sentinel_record); + assert_eq!(pending.owner, sentinel.slot()); + assert!(parked.marked(owner), "the scanned owner is already marked"); + assert!( + !parked.marked(target), + "the replacement target has no supplemental root" + ); + let before = parked.meter(); + parked.park()?; + let edges_before = (heap.stats().live_edges, heap.stats().edge_slots); + if !matches!(write, ExistingNumberWrite::Omitted) { + heap.set_number_edge(owner, NUMBER_KEY, target)?; + assert_eq!(heap.number_value(owner, NUMBER_KEY)?, carrier); + } else { + assert_eq!( + heap.number_value(owner, NUMBER_KEY)?, + Value::string(ORIGINAL_NUMBER_SCALAR) + ); + } + assert_eq!( + heap.find_key(owner.slot(), &number_key), + Some(old_record), + "the old number record index is unchanged" + ); + assert_eq!( + (heap.stats().live_edges, heap.stats().edge_slots), + edges_before, + "the write does not change the edge count" + ); + if !matches!(write, ExistingNumberWrite::Omitted) { + let stored = heap.edge_slots[old_record as usize] + .edge + .as_ref() + .expect("replaced record"); + assert_eq!(&stored.key, &number_key); + assert!(matches!( + stored.value, + super::EdgeValue::Table { slot, generation } + if slot == target.slot() && generation == target.generation() + )); + } + let parked = ParkedMark::resume(heap).expect("write kept the saved mark"); + assert_eq!(parked.phase_name(), "gray"); + let cursor = parked.pending().expect("sentinel still pending"); + assert_eq!( + (cursor.owner, cursor.cursor), + (pending.owner, pending.cursor), + "the pending scan cursor is unchanged" + ); + assert!( + !parked.marked(child), + "the write must not scan the child edge" + ); + assert_eq!( + parked.marked(target), + retained, + "only a strong number replacement enters the gray queue immediately" + ); + let after = parked.meter(); + assert_write_did_not_scan(&before, &after); + assert_eq!(after.parked_edge_writes, before.parked_edge_writes); + assert_eq!( + after.parked_barrier_marks - before.parked_barrier_marks, + u64::from(retained) + ); + assert_eq!( + after.scratch.work_pushed - before.scratch.work_pushed, + u64::from(retained) + ); + assert_eq!( + after.node_slot_visits - before.node_slot_visits, + u64::from(retained) * 2 + ); + parked.park()?; + Ok(old_record) + }) + .expect("in-place number replacement while Gray is parked"); + + let published = heap::step_fixed_frames(&mut host, 128).expect("publish saved mark"); + assert!( + matches!(published, StepOutcome::Published { .. }), + "{published:?}" + ); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + heap::with_heap(&mut host, |heap| { + // NaN and a stale handle stay ahead of the sweep refusal. + assert_eq!( + heap.set_number_edge(owner, f64::NAN, sentinel), + Err(HeapError::NanIndex) + ); + assert_eq!( + heap.clear_number_edge(owner, f64::NAN), + Err(HeapError::NanIndex) + ); + assert_eq!( + heap.set_number_edge(stale, NUMBER_KEY, sentinel), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.set_number_edge(owner, NUMBER_KEY, stale), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.set_number_edge(owner, OTHER_KEY, sentinel), + Err(HeapError::SweepPending) + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::number(OTHER_KEY)) + .is_none() + ); + if matches!(write, ExistingNumberWrite::WeakValue) { + assert_eq!( + heap.number_value(owner, NUMBER_KEY)?, + Value::Null, + "a weak number replacement publishes nil" + ); + let index = heap + .find_key(owner.slot(), &super::EdgeKey::number(NUMBER_KEY)) + .expect("a weak-value replacement leaves the cleared cursor"); + assert_eq!(index, old_record); + let stored = heap.edge_slots[index as usize] + .edge + .as_ref() + .expect("retained gap"); + assert!(stored.value.is_cursor_gap()); + assert_eq!(&stored.key, &super::EdgeKey::number(NUMBER_KEY)); + } + if matches!(write, ExistingNumberWrite::Omitted) { + assert_eq!( + heap.number_value(owner, NUMBER_KEY)?, + Value::string(ORIGINAL_NUMBER_SCALAR) + ); + } + if matches!(write, ExistingNumberWrite::Strong) { + assert_eq!(heap.number_value(owner, NUMBER_KEY)?, carrier); + } + Ok(()) + }) + .expect("read during publication"); + let done = heap::step_fixed_frames(&mut host, 128).expect("finish saved tail"); + assert!(matches!(done, StepOutcome::Completed(_)), "{done:?}"); + assert!(heap::fixed_step_idle(&mut host).expect("idle")); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.alive(target), + retained, + "an in-place strong number replacement on a scanned owner must keep its target alive" + ); + assert_eq!( + heap.alive(child), + retained, + "the child is reached only by the continued scan" + ); + assert_eq!(heap.stats().collections, 1); + assert_eq!(heap.scan_meter().mark_passes, 1); + if matches!(write, ExistingNumberWrite::Omitted) { + assert_eq!( + heap.number_value(owner, NUMBER_KEY)?, + Value::string(ORIGINAL_NUMBER_SCALAR), + "an omitted number replacement keeps the original string" + ); + } + if retained { + let value = heap.number_value(owner, NUMBER_KEY)?; + assert_eq!(value, carrier); + assert_eq!(heap.guest_class(&value), GuestClass::Table(target)); + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + heap.clear_number_edge(owner, NUMBER_KEY)?; + } + Ok(()) + }) + .expect("same-cycle reachability"); + if retained { + heap::collect(&mut host).expect("next collection after removing the only strong edge"); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(target) && !heap.alive(child)); + assert_eq!(heap.stats().collections, 2); + Ok(()) + }) + .expect("later reclamation"); + } + }); +} + +#[test] +fn gray_existing_number_strong_replacement_keeps_the_new_graph() { + existing_number_replacement_after_owner_scan(ExistingNumberWrite::Strong); +} + +#[test] +fn gray_existing_number_weak_replacement_clears_at_publication() { + existing_number_replacement_after_owner_scan(ExistingNumberWrite::WeakValue); +} + +#[test] +fn gray_existing_number_omitted_replacement_keeps_the_original_string() { + existing_number_replacement_after_owner_scan(ExistingNumberWrite::Omitted); +} + #[test] fn tail_slot_reuse_does_not_keep_the_new_target() { let mut heap = LuaHeap::new(limits(8, 2, 8)); From 2e6e443e934f671e95a983c46d5a42b096d3a59b Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 05:19:04 +0800 Subject: [PATCH 138/225] Replay the reviewed idle empty-local step onto runtime step data Apply the reviewed restart safepoint using its own parent as the merge base. Same-point insertions keep runtime text, then the automatic text. The missing-schema skip takes the union of both operation lists. This replay adds no comment cleanup, cross-source test, new numeric key, root-batch capacity, Release allocation, or production wiring. --- tests/luajit_heap_runtime/candidate.rs | 154 +++++- .../source_scalar_retire.rs | 486 ++++++++++++++++-- 2 files changed, 585 insertions(+), 55 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 55b7a4b..e4f554d 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -32,6 +32,7 @@ const GC_STOP: &str = "lua_internal::gc_stop"; const GC_RESTART: &str = "lua_internal::gc_restart"; const GC_IS_RUNNING: &str = "lua_internal::gc_is_running"; const STEP_DATA: &str = "lua_internal::step_data"; +const AUTO_TABLE_RESTART: &str = "lua_internal::auto_table_restart"; const COUNT: &str = "lua_internal::count"; const OPEN_CELL: &str = "lua_internal::open_cell"; const READ_CELL: &str = "lua_internal::read_cell"; @@ -138,6 +139,16 @@ pub(super) fn install_run_control_schemas(builder: &mut HostApiBuilder) { )); } +/// Opt in to one automatic empty-local safepoint. Not part of the ordinary +/// catalog or the run-control catalog. +pub(super) fn install_auto_table_restart_schema(builder: &mut HostApiBuilder) { + builder.function(HostFunctionSchema::with_return( + AUTO_TABLE_RESTART, + vec![HostParamSchema::value("roots", HostTypeSchema::Unknown)], + HostTypeSchema::Float, + )); +} + pub(super) fn install_schemas(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( GATHER_ROOT, @@ -310,6 +321,7 @@ pub(super) fn register( Op::GcRestart, Op::GcIsRunning, Op::StepData, + Op::AutoTableRestart, Op::Count, Op::EnterResult, Op::EnterCallee, @@ -357,6 +369,7 @@ pub(super) fn register( Op::GcRestart => GC_RESTART, Op::GcIsRunning => GC_IS_RUNNING, Op::StepData => STEP_DATA, + Op::AutoTableRestart => AUTO_TABLE_RESTART, Op::Count => COUNT, Op::EnterResult => ENTER_RESULT, Op::EnterCallee => ENTER_CALLEE, @@ -393,6 +406,7 @@ pub(super) fn register( | Op::GcRestart | Op::GcIsRunning | Op::StepData + | Op::AutoTableRestart ) && catalog.function(name).is_none() { continue; @@ -426,6 +440,7 @@ enum Op { GcRestart, GcIsRunning, StepData, + AutoTableRestart, Count, EnterResult, EnterCallee, @@ -621,7 +636,8 @@ impl HostOwnedFunction for Op { } Self::StepHasTail => Value::Bool(heap::saved_source_tail(&call.vm().host_context())), Self::GcStop => set_gc_running(&mut call.vm().host_context(), false)?, - Self::GcRestart => set_gc_running(&mut call.vm().host_context(), true)?, + Self::GcRestart => gc_restart(&mut call.vm().host_context())?, + Self::AutoTableRestart => auto_table_restart(call)?, Self::GcIsRunning => gc_is_running(&call.vm().host_context()), Self::StepData => step_data_default(call)?, Self::Count => { @@ -1838,19 +1854,47 @@ fn decode_safepoint_roots(call: &mut OwnedHostCall<'_>) -> Result, + auto_requested: bool, +} + +fn fresh_run_control() -> GcRunControl { + GcRunControl { + running: true, + threshold_bytes: None, + auto_requested: false, + } } fn set_gc_running(host: &mut vm::HostContext<'_>, running: bool) -> Result { // Control only. Do not publish roots, pop a step budget, or touch a saved tail. let control = host - .scope_state_or_insert_with(|| GcRunControl { running: true }) + .scope_state_or_insert_with(fresh_run_control) .map_err(|error| VmError::HostError(error.to_string()))?; control.running = running; Ok(Value::Float(0.0)) } +fn gc_restart(host: &mut vm::HostContext<'_>) -> Result { + // Current logical amount only. Do not install a heap, collect, or pop a budget. + let bytes = host + .scope_state::() + .map(|heap| heap.logical_bytes()) + .unwrap_or(0); + let control = host + .scope_state_or_insert_with(fresh_run_control) + .map_err(|error| VmError::HostError(error.to_string()))?; + control.running = true; + control.threshold_bytes = Some(bytes); + control.auto_requested = false; + Ok(Value::Float(0.0)) +} + fn gc_is_running(host: &vm::HostContext<'_>) -> Value { Value::Bool(gc_running(host)) } @@ -1908,6 +1952,99 @@ fn step_data_default(call: &mut OwnedHostCall<'_>) -> Result { } } +fn pop_step_budget(host: &mut vm::HostContext<'_>) -> Result { + host.scope_state_mut::() + .and_then(|budgets| budgets.0.pop_front()) + .ok_or_else(|| VmError::HostError("missing source step fixture budget".to_string())) +} + +fn auto_table_due(host: &mut vm::HostContext<'_>) -> Result { + let (running, threshold, requested) = match host.scope_state::() { + Some(control) => ( + control.running, + control.threshold_bytes, + control.auto_requested, + ), + None => return Ok(false), + }; + if !running || requested { + return Ok(false); + } + let Some(threshold) = threshold else { + return Ok(false); + }; + // An absent heap is not an idle cycle. Do not install one here. + if host.scope_state::().is_none() { + return Ok(false); + } + // A saved tail or mark is an existing cycle. Leave the ordinary allocation gate. + if heap::saved_source_tail(host) || !heap::fixed_step_idle(host).map_err(heap_error)? { + return Ok(false); + } + let logical = host + .scope_state::() + .map(|heap| heap.logical_bytes()) + .unwrap_or(0); + Ok(logical >= threshold) +} + +fn confirm_round_finished(host: &mut vm::HostContext<'_>) -> Result<(), VmError> { + if heap::saved_source_tail(host) || !heap::fixed_step_idle(host).map_err(heap_error)? { + return Err(VmError::HostError( + "auto table restart left a cycle open before publish".to_string(), + )); + } + Ok(()) +} + +/// One idle empty-local safepoint after single-arg restart. +/// +/// The mark allowance and, only when that call publishes a tail, the +/// continuation allowance are separate host phase budgets. Pending close, +/// token close, and the Owners walk stay on the existing driver's own meters +/// and are not limited by either allowance. This does not call `heap::collect` +/// and does not treat a saved tail as idle. +fn auto_table_restart(call: &mut OwnedHostCall<'_>) -> Result { + if !auto_table_due(&mut call.vm().host_context())? { + return Ok(Value::Float(0.0)); + } + let tables = decode_safepoint_roots(call)?; + let mut host = call.vm().host_context(); + let mark_budget = pop_step_budget(&mut host)?; + if let Some(control) = host.scope_state_mut::() { + control.auto_requested = true; + } + let first = heap::step_source_safepoint(&mut host, mark_budget, tables).map_err(heap_error)?; + match first { + heap::StepOutcome::Completed(report) => { + note_collect(&mut host, report)?; + confirm_round_finished(&mut host)?; + } + heap::StepOutcome::Published { .. } => { + let sweep_budget = pop_step_budget(&mut host)?; + let second = heap::step_source_safepoint(&mut host, sweep_budget, Vec::new()) + .map_err(heap_error)?; + match second { + heap::StepOutcome::Completed(report) => { + note_collect(&mut host, report)?; + confirm_round_finished(&mut host)?; + } + other => { + return Err(VmError::HostError(format!( + "auto table restart did not finish the published tail: {other:?}" + ))); + } + } + } + heap::StepOutcome::Paused { tail } => { + return Err(VmError::HostError(format!( + "auto table restart mark paused tail={tail}" + ))); + } + } + Ok(Value::Float(0.0)) +} + fn step_at_safepoint(call: &mut OwnedHostCall<'_>) -> Result { let mut host = call.vm().host_context(); let budget = host @@ -2892,6 +3029,11 @@ impl Lower<'_> { name: &ast::Name, value: &ast::Expr, ) -> Result<(), ParseError> { + if self.catalog.function(AUTO_TABLE_RESTART).is_some() + && matches!(value, ast::Expr::Table { fields, .. } if fields.is_empty()) + { + self.emit_auto_table_safepoint(span)?; + } let expr = self.expr(value)?; let index = self .builder @@ -2934,6 +3076,14 @@ impl Lower<'_> { Ok(()) } + fn emit_auto_table_safepoint(&mut self, span: ast::Span) -> Result<(), ParseError> { + // Only this source local. Shadow and cell constructors call NEW_TABLE + // themselves and do not pass through here. + let roots = self.gather_safepoint_roots(span)?; + let expr = self.call(AUTO_TABLE_RESTART, vec![roots])?; + self.emit_ignored(expr, self.line(span)) + } + fn open_captured_cell( &mut self, span: ast::Span, diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index a174a6f..6214bcd 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -123,19 +123,28 @@ struct Ran { struct Plugin { guest_step: bool, run_control: bool, + auto_table: bool, } static PLUGIN: Plugin = Plugin { guest_step: false, run_control: false, + auto_table: false, }; static STEP_PLUGIN: Plugin = Plugin { guest_step: true, run_control: false, + auto_table: false, }; static CONTROL_PLUGIN: Plugin = Plugin { guest_step: true, run_control: true, + auto_table: false, +}; +static AUTO_TABLE_PLUGIN: Plugin = Plugin { + guest_step: true, + run_control: true, + auto_table: true, }; impl SourcePlugin for Plugin { @@ -152,7 +161,12 @@ impl SourcePlugin for Plugin { } fn parse_source(&self, source: &str) -> Result { - candidate::lower(source, catalog_for(self.guest_step, self.run_control)) + let catalog = if self.auto_table { + catalog_auto() + } else { + catalog_for(self.guest_step, self.run_control) + }; + candidate::lower(source, catalog) } } @@ -160,6 +174,56 @@ fn catalog(guest_step: bool) -> &'static Arc { catalog_for(guest_step, false) } +fn install_witness_schemas(builder: &mut vm::HostApiBuilder) { + let table = HostTypeSchema::Resource(heap::LuaTableResource::key()); + builder.function(vm::HostFunctionSchema::with_return( + STEP, + vec![HostParamSchema::value("budget", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + PEEK, + vec![HostParamSchema::with_passing( + "table", + table.clone(), + HostParamPassing::Borrow, + )], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + SAME, + vec![ + HostParamSchema::with_passing("left", table.clone(), HostParamPassing::Borrow), + HostParamSchema::with_passing("right", table, HostParamPassing::Borrow), + ], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + NOTE, + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("value", HostTypeSchema::Float), + ], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + TEXT, + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("text", HostTypeSchema::String), + ], + HostTypeSchema::Bool, + )); + builder.function(vm::HostFunctionSchema::with_return( + BIT, + vec![ + HostParamSchema::value("tag", HostTypeSchema::Float), + HostParamSchema::value("bit", HostTypeSchema::Bool), + ], + HostTypeSchema::Bool, + )); +} + fn catalog_for(guest_step: bool, run_control: bool) -> &'static Arc { static CATALOG: OnceLock> = OnceLock::new(); static STEP_CATALOG: OnceLock> = OnceLock::new(); @@ -180,57 +244,24 @@ fn catalog_for(guest_step: bool, run_control: bool) -> &'static Arc &'static Arc { + static AUTO_CATALOG: OnceLock> = OnceLock::new(); + AUTO_CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + candidate::install_step_schemas(&mut builder); + candidate::install_run_control_schemas(&mut builder); + candidate::install_auto_table_restart_schema(&mut builder); + install_witness_schemas(&mut builder); + Arc::new(builder.build().expect("auto table restart catalog")) + }) +} + fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { for (name, op) in [ (STEP, HostOp::Step), @@ -417,12 +448,11 @@ fn run_control(source: &str, budgets: Option<&[u64]>) -> Ran { drive(source, budgets, true, None) } +fn run_auto_table(source: &str, budgets: Option<&[u64]>) -> Ran { + drive_plugin(source, budgets, &AUTO_TABLE_PLUGIN, None) +} + fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option) -> Ran { - let catalog = Arc::clone(if run_control { - catalog_for(true, true) - } else { - catalog(budgets.is_some()) - }); let plugin: &Plugin = if run_control { &CONTROL_PLUGIN } else if budgets.is_some() { @@ -430,6 +460,22 @@ fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option } else { &PLUGIN }; + drive_plugin(source, budgets, plugin, nodes) +} + +fn drive_plugin( + source: &str, + budgets: Option<&[u64]>, + plugin: &'static Plugin, + nodes: Option, +) -> Ran { + let catalog = Arc::clone(if plugin.auto_table { + catalog_auto() + } else if plugin.run_control { + catalog_for(true, true) + } else { + catalog(plugin.guest_step) + }); let options = CompileSourceFileOptions::new() .with_source_plugin(plugin) .with_host_api_catalog(Arc::clone(&catalog)); @@ -3153,3 +3199,337 @@ return 1 assert_eq!(gathered.collections, 0); assert!(gathered.trace.bits.is_empty(), "{gathered:?}"); } + +/// Ordinary catalog has no automatic table safepoint. An empty local after a +/// weak witness must not collect. +#[test] +fn ordinary_catalog_empty_local_does_not_collect_a_weak_witness() { + let ran = run(r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + local fresh = {} + peek(fresh) + text(1, type(fresh)) + text(2, type(rawget(w, 2))) + note(1, same(held, rawget(w, 1))) + note(2, rawlen(w)) + return 1 +end +witness() +return 1 +"#); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(ran.stack, [Value::Float(1.0)]); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!(text_value(&ran.trace, 2.0), "table"); + assert_eq!(note_value(&ran.trace, 1.0), 1.0); + assert_eq!(note_value(&ran.trace, 2.0), 2.0); + assert_eq!(ran.trace.peeks.len(), 2); + assert_ne!(ran.trace.peeks[0].table, ran.trace.peeks[1].table); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); + assert!(ran.trace.steps.is_empty()); +} + +/// Stop still suppresses collection. The following empty local is ordinary +/// allocation, not a safepoint. +#[test] +fn stopped_empty_local_keeps_the_weak_witness() { + let ran = run_control( + r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + note(1, collectgarbage("stop")) + bit(1, collectgarbage("isrunning")) + text(1, type(rawget(w, 2))) + local fresh = {} + peek(fresh) + bit(2, collectgarbage("isrunning")) + text(2, type(fresh)) + text(3, type(rawget(w, 2))) + note(2, same(held, rawget(w, 1))) + note(3, rawlen(w)) + return 1 +end +witness() +return 1 +"#, + None, + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 1.0)); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert!(!bit_value(&ran.trace, 2.0)); + assert_eq!(text_value(&ran.trace, 2.0), "table"); + assert_eq!( + text_value(&ran.trace, 3.0), + "table", + "stop must keep the weak item across the empty local" + ); + assert_eq!(note_value(&ran.trace, 2.0), 1.0); + assert_eq!(note_value(&ran.trace, 3.0), 2.0); + assert_eq!(ran.trace.peeks.len(), 2); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); + assert!(ran.subject_alive.unwrap_or(false)); +} + +/// Same refusal as the existing node cap: stop must not collect to make room. +#[test] +fn stopped_empty_local_keeps_the_installed_node_quota_refusal() { + let ran = drive( + r#" +local function witness() + local a = {} + peek(a) + note(1, collectgarbage("stop")) + bit(1, collectgarbage("isrunning")) + local b = {} + peek(b) + return 1 +end +witness() +return 1 +"#, + None, + true, + Some(1), + ); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message.contains("lua heap node capacity")), + "stop must not change the installed node refusal: {:?}", + ran.stop + ); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 1.0)); + assert_eq!(ran.live_nodes, 1, "the refused table did not occupy a node"); + assert_eq!( + ran.trace.peeks.len(), + 1, + "the second table was not published" + ); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); + assert!(ran.subject_alive.unwrap_or(false)); + assert!(ran.token_open.unwrap_or(false)); +} + +/// The run-control catalog does not grow this automatic safepoint. +#[test] +fn run_control_empty_local_keeps_the_weak_witness() { + let ran = run_control( + r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + note(1, collectgarbage("stop")) + note(2, collectgarbage("restart")) + text(1, type(rawget(w, 2))) + local fresh = {} + peek(fresh) + text(2, type(fresh)) + text(3, type(rawget(w, 2))) + note(3, same(held, rawget(w, 1))) + return 1 +end +witness() +return 1 +"#, + Some(&[10_000, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!(text_value(&ran.trace, 2.0), "table"); + assert_eq!( + text_value(&ran.trace, 3.0), + "table", + "run control without the empty-local opt-in must keep the weak item" + ); + assert_eq!(note_value(&ran.trace, 3.0), 1.0); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); + assert!(ran.trace.steps.is_empty()); +} + +/// The opt-in schema does not collect or widen the node cap while stopped. +#[test] +fn stopped_auto_table_keeps_the_installed_node_quota_refusal() { + let ran = drive_plugin( + r#" +local function witness() + local a = {} + peek(a) + note(1, collectgarbage("stop")) + bit(1, collectgarbage("isrunning")) + local b = {} + peek(b) + return 1 +end +witness() +return 1 +"#, + None, + &AUTO_TABLE_PLUGIN, + Some(1), + ); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message.contains("lua heap node capacity")), + "stopped opt-in must keep the installed node refusal: {:?}", + ran.stop + ); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 1.0)); + assert_eq!(ran.live_nodes, 1); + assert_eq!(ran.trace.peeks.len(), 1); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); +} + +/// Restart and a pure read keep the weak witness. With the empty-local opt-in +/// and two configured host budgets, the next empty local finishes one idle +/// cycle before publish. +#[test] +fn restarted_empty_local_clears_old_weak_before_the_new_table_is_published() { + let ran = run_auto_table( + r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + bit(1, collectgarbage("isrunning")) + note(1, collectgarbage("stop")) + bit(2, collectgarbage("isrunning")) + text(1, type(rawget(w, 2))) + note(2, rawlen(w)) + note(3, same(held, rawget(w, 1))) + note(11, collectgarbage("count")) + note(4, collectgarbage("restart")) + bit(3, collectgarbage("isrunning")) + note(12, collectgarbage("count")) + text(2, type(rawget(w, 2))) + note(5, rawlen(w)) + note(6, same(held, rawget(w, 1))) + bit(4, collectgarbage("isrunning")) + local fresh = {} + bit(5, peek(fresh)) + text(3, type(fresh)) + text(4, type(rawget(w, 2))) + note(7, rawlen(w)) + note(8, same(held, rawget(w, 1))) + w[3] = {} + text(5, type(rawget(w, 3))) + collectgarbage("collect") + text(6, type(rawget(w, 3))) + note(9, same(held, rawget(w, 1))) + return 1 +end +witness() +return 1 +"#, + Some(&[10_000, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(ran.stack, [Value::Float(1.0)]); + assert!( + bit_value(&ran.trace, 1.0), + "a fresh execution starts running" + ); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert!(!bit_value(&ran.trace, 2.0)); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!(note_value(&ran.trace, 2.0), 2.0); + assert_eq!(note_value(&ran.trace, 3.0), 1.0); + let before = note_value(&ran.trace, 11.0); + assert!( + before.is_finite() && before > 0.0, + "count is the logical meter: {before}" + ); + assert_eq!(note_value(&ran.trace, 4.0), 0.0); + assert!(bit_value(&ran.trace, 3.0)); + assert_eq!( + note_value(&ran.trace, 12.0), + before, + "restart does not allocate" + ); + assert_eq!( + text_value(&ran.trace, 2.0), + "table", + "restart and the following read must keep the weak item" + ); + assert_eq!(note_value(&ran.trace, 5.0), 2.0); + assert_eq!(note_value(&ran.trace, 6.0), 1.0); + assert!(bit_value(&ran.trace, 4.0)); + assert_eq!(cycle_at(&ran.trace, 4.0), (false, 0)); + assert!(bit_value(&ran.trace, 5.0), "the new table is usable"); + assert_eq!(text_value(&ran.trace, 3.0), "table"); + assert_eq!(ran.trace.peeks.len(), 2); + assert_ne!(ran.trace.peeks[0].table, ran.trace.peeks[1].table); + assert_eq!( + text_value(&ran.trace, 4.0), + "nil", + "the empty local must clear the old weak item before publish; got {:?}", + ran.trace.texts + ); + assert_eq!(note_value(&ran.trace, 7.0), 1.0); + assert_eq!( + note_value(&ran.trace, 8.0), + 1.0, + "the strong root keeps its identity" + ); + assert_eq!( + cycle_at(&ran.trace, 5.0), + (false, 1), + "the safepoint must finish before the new table is published: {:?}", + ran.trace.bit_cycle_state + ); + assert_eq!( + text_value(&ran.trace, 5.0), + "table", + "a later empty table must not start another automatic cycle" + ); + assert_eq!(text_value(&ran.trace, 6.0), "nil"); + assert_eq!(note_value(&ran.trace, 9.0), 1.0); + assert!( + ran.trace.steps.is_empty(), + "lua_host::step is not this safepoint" + ); + assert!(!ran.tail); + assert_eq!( + ran.collections, 2, + "automatic cycle plus the explicit collect" + ); + assert_eq!(ran.collects, 2, "both completions record the real report"); + assert!(ran.subject_alive.unwrap_or(false)); + assert!(ran.token_open.unwrap_or(false)); +} From 44cae19ad0802210431a84c49f750294a487e5d6 Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 05:19:05 +0800 Subject: [PATCH 139/225] Replay the reviewed due-gather gate onto runtime step data Apply the reviewed trigger gate using its own parent as the merge base. The automatic constant update keeps STEP_DATA and takes the replaced AUTO_TABLE_RESTART declaration together with AUTO_TABLE_DUE. Same-point insertions keep runtime text, then the automatic text. This replay adds no comment cleanup, cross-source test, new numeric key, root-batch capacity, Release allocation, or production wiring. --- tests/luajit_heap_runtime/candidate.rs | 94 ++- .../source_scalar_retire.rs | 727 +++++++++++++++++- 2 files changed, 798 insertions(+), 23 deletions(-) diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index e4f554d..9cd4687 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -24,7 +24,7 @@ const TABLE_ARG: &str = "lua_internal::table_arg"; const NUMBER_ARG: &str = "lua_internal::number_arg"; const BOOL_ARG: &str = "lua_internal::bool_arg"; const STRING_ARG: &str = "lua_internal::string_arg"; -const GATHER_ROOT: &str = "lua_internal::gather_root"; +pub(super) const GATHER_ROOT: &str = "lua_internal::gather_root"; pub(super) const COLLECT: &str = "lua_internal::collect"; const STEP: &str = "lua_internal::step"; const STEP_HAS_TAIL: &str = "lua_internal::step_has_tail"; @@ -32,7 +32,8 @@ const GC_STOP: &str = "lua_internal::gc_stop"; const GC_RESTART: &str = "lua_internal::gc_restart"; const GC_IS_RUNNING: &str = "lua_internal::gc_is_running"; const STEP_DATA: &str = "lua_internal::step_data"; -const AUTO_TABLE_RESTART: &str = "lua_internal::auto_table_restart"; +pub(super) const AUTO_TABLE_DUE: &str = "lua_internal::auto_table_due"; +pub(super) const AUTO_TABLE_RESTART: &str = "lua_internal::auto_table_restart"; const COUNT: &str = "lua_internal::count"; const OPEN_CELL: &str = "lua_internal::open_cell"; const READ_CELL: &str = "lua_internal::read_cell"; @@ -140,8 +141,18 @@ pub(super) fn install_run_control_schemas(builder: &mut HostApiBuilder) { } /// Opt in to one automatic empty-local safepoint. Not part of the ordinary -/// catalog or the run-control catalog. -pub(super) fn install_auto_table_restart_schema(builder: &mut HostApiBuilder) { +/// catalog or the run-control catalog. Due is a read-only observation; the +/// restart entry is the only writer. Either schema alone does not connect the +/// source route. +pub(super) fn install_auto_table_due_schema(builder: &mut HostApiBuilder) { + builder.function(HostFunctionSchema::with_return( + AUTO_TABLE_DUE, + vec![], + HostTypeSchema::Bool, + )); +} + +pub(super) fn install_auto_table_restart_entry_schema(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( AUTO_TABLE_RESTART, vec![HostParamSchema::value("roots", HostTypeSchema::Unknown)], @@ -149,6 +160,11 @@ pub(super) fn install_auto_table_restart_schema(builder: &mut HostApiBuilder) { )); } +pub(super) fn install_auto_table_restart_schema(builder: &mut HostApiBuilder) { + install_auto_table_due_schema(builder); + install_auto_table_restart_entry_schema(builder); +} + pub(super) fn install_schemas(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( GATHER_ROOT, @@ -321,6 +337,7 @@ pub(super) fn register( Op::GcRestart, Op::GcIsRunning, Op::StepData, + Op::AutoTableDue, Op::AutoTableRestart, Op::Count, Op::EnterResult, @@ -369,6 +386,7 @@ pub(super) fn register( Op::GcRestart => GC_RESTART, Op::GcIsRunning => GC_IS_RUNNING, Op::StepData => STEP_DATA, + Op::AutoTableDue => AUTO_TABLE_DUE, Op::AutoTableRestart => AUTO_TABLE_RESTART, Op::Count => COUNT, Op::EnterResult => ENTER_RESULT, @@ -406,6 +424,7 @@ pub(super) fn register( | Op::GcRestart | Op::GcIsRunning | Op::StepData + | Op::AutoTableDue | Op::AutoTableRestart ) && catalog.function(name).is_none() { @@ -440,6 +459,7 @@ enum Op { GcRestart, GcIsRunning, StepData, + AutoTableDue, AutoTableRestart, Count, EnterResult, @@ -637,6 +657,7 @@ impl HostOwnedFunction for Op { Self::StepHasTail => Value::Bool(heap::saved_source_tail(&call.vm().host_context())), Self::GcStop => set_gc_running(&mut call.vm().host_context(), false)?, Self::GcRestart => gc_restart(&mut call.vm().host_context())?, + Self::AutoTableDue => Value::Bool(auto_table_due(&mut call.vm().host_context())?), Self::AutoTableRestart => auto_table_restart(call)?, Self::GcIsRunning => gc_is_running(&call.vm().host_context()), Self::StepData => step_data_default(call)?, @@ -1988,6 +2009,39 @@ fn auto_table_due(host: &mut vm::HostContext<'_>) -> Result { Ok(logical >= threshold) } +/// Read-only snapshot for the once-only witness. Does not decode roots, pop a +/// budget, set the latch, or start a cycle. +pub(super) struct AutoTableMeter { + pub logical: u64, + pub threshold: u64, + pub running: bool, + pub requested: bool, + pub due: bool, +} + +pub(super) fn auto_table_meter(host: &mut vm::HostContext<'_>) -> Result { + let due = auto_table_due(host)?; + let logical = host + .scope_state::() + .map(|heap| heap.logical_bytes()) + .unwrap_or(0); + let (running, threshold, requested) = match host.scope_state::() { + Some(control) => ( + control.running, + control.threshold_bytes.unwrap_or(0), + control.auto_requested, + ), + None => (false, 0, false), + }; + Ok(AutoTableMeter { + logical, + threshold, + running, + requested, + due, + }) +} + fn confirm_round_finished(host: &mut vm::HostContext<'_>) -> Result<(), VmError> { if heap::saved_source_tail(host) || !heap::fixed_step_idle(host).map_err(heap_error)? { return Err(VmError::HostError( @@ -3029,7 +3083,7 @@ impl Lower<'_> { name: &ast::Name, value: &ast::Expr, ) -> Result<(), ParseError> { - if self.catalog.function(AUTO_TABLE_RESTART).is_some() + if self.auto_table_routed() && matches!(value, ast::Expr::Table { fields, .. } if fields.is_empty()) { self.emit_auto_table_safepoint(span)?; @@ -3076,11 +3130,32 @@ impl Lower<'_> { Ok(()) } + fn auto_table_routed(&self) -> bool { + self.catalog.function(AUTO_TABLE_DUE).is_some() + && self.catalog.function(AUTO_TABLE_RESTART).is_some() + } + fn emit_auto_table_safepoint(&mut self, span: ast::Span) -> Result<(), ParseError> { // Only this source local. Shadow and cell constructors call NEW_TABLE // themselves and do not pass through here. + // + // The due call has no guest arguments, so the judgment does not read or + // move a live value. Gather statements are reserved in the taken branch + // and are not executed when the judgment is false. The restart entry + // still refuses a direct call that is not due. + let due = self.call(AUTO_TABLE_DUE, vec![])?; + let start = self.stmts.len(); let roots = self.gather_safepoint_roots(span)?; - let expr = self.call(AUTO_TABLE_RESTART, vec![roots])?; + let gather = self.stmts.split_off(start); + let taken = self.call(AUTO_TABLE_RESTART, vec![roots])?; + let expr = Expr::IfElse { + condition: Box::new(due), + then_expr: Box::new(Expr::Block { + stmts: gather, + expr: Box::new(taken), + }), + else_expr: Box::new(Expr::Float(0.0)), + }; self.emit_ignored(expr, self.line(span)) } @@ -4436,6 +4511,13 @@ impl Lower<'_> { if name.is("external_shape") && args.exprs.is_empty() { return self.call(EXTERNAL_SHAPE, vec![]); } + if name.is("direct_auto_restart") && args.exprs.is_empty() { + // Test probe for the dispatch gate. Not the automatic route. + if self.catalog.function(AUTO_TABLE_RESTART).is_none() { + return Err(self.unsupported(expr.span())); + } + return self.call(AUTO_TABLE_RESTART, vec![Expr::Null]); + } let name = std::str::from_utf8(&name.bytes).map_err(|_| self.unsupported(expr.span()))?; self.host_call(&format!("lua_host::{name}"), &args.exprs, expr.span()) diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index 6214bcd..d180906 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -5,14 +5,15 @@ //! The private host uses fixed frames; the opt-in guest spelling gathers the //! current source roots on mark steps and bypasses gathering on tail steps. +use std::collections::HashSet; use std::num::NonZeroU64; use std::sync::{Arc, OnceLock}; use vm::{ - CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + CallOutcome, CallReturn, CompileSourceFileOptions, Expr, FrontendImportSyntax, FrontendIr, HostFunctionRegistry, HostImportSchema, HostOwnedFunction, HostParamPassing, HostParamSchema, - HostTypeSchema, OpCode, OwnedHostCall, ParseError, Program, SourceFlavor, SourcePlugin, Value, - VmError, VmStatus, + HostTypeSchema, OpCode, OwnedHostCall, ParseError, Program, SourceFlavor, SourcePlugin, Stmt, + Value, VmError, VmStatus, }; use super::ObservedTable; @@ -25,6 +26,8 @@ const SAME: &str = "lua_host::same"; const NOTE: &str = "lua_host::note"; const TEXT: &str = "lua_host::text"; const BIT: &str = "lua_host::bit"; +const SHAPE: &str = "lua_host::shape"; +const METER: &str = "lua_host::meter"; const SOURCE: &str = r#" local function witness() @@ -124,27 +127,51 @@ struct Plugin { guest_step: bool, run_control: bool, auto_table: bool, + restart_entry_only: bool, + due_only: bool, } static PLUGIN: Plugin = Plugin { guest_step: false, run_control: false, auto_table: false, + restart_entry_only: false, + due_only: false, }; static STEP_PLUGIN: Plugin = Plugin { guest_step: true, run_control: false, auto_table: false, + restart_entry_only: false, + due_only: false, }; static CONTROL_PLUGIN: Plugin = Plugin { guest_step: true, run_control: true, auto_table: false, + restart_entry_only: false, + due_only: false, }; static AUTO_TABLE_PLUGIN: Plugin = Plugin { guest_step: true, run_control: true, auto_table: true, + restart_entry_only: false, + due_only: false, +}; +static RESTART_ENTRY_PLUGIN: Plugin = Plugin { + guest_step: true, + run_control: true, + auto_table: false, + restart_entry_only: true, + due_only: false, +}; +static DUE_ONLY_PLUGIN: Plugin = Plugin { + guest_step: true, + run_control: true, + auto_table: false, + restart_entry_only: false, + due_only: true, }; impl SourcePlugin for Plugin { @@ -161,12 +188,7 @@ impl SourcePlugin for Plugin { } fn parse_source(&self, source: &str) -> Result { - let catalog = if self.auto_table { - catalog_auto() - } else { - catalog_for(self.guest_step, self.run_control) - }; - candidate::lower(source, catalog) + candidate::lower(source, plugin_catalog(self)) } } @@ -214,6 +236,16 @@ fn install_witness_schemas(builder: &mut vm::HostApiBuilder) { ], HostTypeSchema::Bool, )); + builder.function(vm::HostFunctionSchema::with_return( + SHAPE, + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::Float, + )); + builder.function(vm::HostFunctionSchema::with_return( + METER, + vec![HostParamSchema::value("tag", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); builder.function(vm::HostFunctionSchema::with_return( BIT, vec![ @@ -262,6 +294,44 @@ fn catalog_auto() -> &'static Arc { }) } +fn catalog_restart_entry() -> &'static Arc { + static ENTRY_CATALOG: OnceLock> = OnceLock::new(); + ENTRY_CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + candidate::install_step_schemas(&mut builder); + candidate::install_run_control_schemas(&mut builder); + candidate::install_auto_table_restart_entry_schema(&mut builder); + install_witness_schemas(&mut builder); + Arc::new(builder.build().expect("restart entry catalog")) + }) +} + +fn catalog_due_only() -> &'static Arc { + static DUE_CATALOG: OnceLock> = OnceLock::new(); + DUE_CATALOG.get_or_init(|| { + let mut builder = vm::HostApiBuilder::new(); + candidate::install_schemas(&mut builder); + candidate::install_step_schemas(&mut builder); + candidate::install_run_control_schemas(&mut builder); + candidate::install_auto_table_due_schema(&mut builder); + install_witness_schemas(&mut builder); + Arc::new(builder.build().expect("due observation catalog")) + }) +} + +fn plugin_catalog(plugin: &Plugin) -> &'static Arc { + if plugin.auto_table { + catalog_auto() + } else if plugin.restart_entry_only { + catalog_restart_entry() + } else if plugin.due_only { + catalog_due_only() + } else { + catalog_for(plugin.guest_step, plugin.run_control) + } +} + fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { for (name, op) in [ (STEP, HostOp::Step), @@ -270,6 +340,8 @@ fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { (NOTE, HostOp::Note), (TEXT, HostOp::Text), (BIT, HostOp::Bit), + (SHAPE, HostOp::Shape), + (METER, HostOp::Meter), ] { let function = catalog.function(name).expect("scalar step host schema"); registry @@ -291,6 +363,8 @@ enum HostOp { Note, Text, Bit, + Shape, + Meter, } impl HostOwnedFunction for HostOp { @@ -345,6 +419,32 @@ impl HostOwnedFunction for HostOp { note(&mut host, |state| state.texts.push(noted))?; Value::Bool(true) } + Self::Shape => Value::Float(if saved_external_shape(args.first()) { + 1.0 + } else { + 0.0 + }), + Self::Meter => { + let [Value::Float(tag)] = args.as_slice() else { + return Err(host_fault("expected meter tag")); + }; + let snap = candidate::auto_table_meter(&mut host)?; + let tag = *tag; + note(&mut host, |state| { + state.notes.push((tag, snap.logical as f64)); + state.notes.push((tag + 1.0, snap.threshold as f64)); + state + .notes + .push((tag + 2.0, if snap.due { 1.0 } else { 0.0 })); + state + .notes + .push((tag + 3.0, if snap.requested { 1.0 } else { 0.0 })); + state + .notes + .push((tag + 4.0, if snap.running { 1.0 } else { 0.0 })); + })?; + Value::Float(snap.logical as f64) + } }; Ok(CallOutcome::Return(CallReturn::one(value))) } @@ -432,6 +532,16 @@ fn host_fault(message: &str) -> VmError { VmError::HostError(message.to_string()) } +/// The array from `external_shape`: saved and readable, but not a Lua table. +fn saved_external_shape(value: Option<&Value>) -> bool { + let Some(Value::Array(items)) = value else { + return false; + }; + items.len() == 2 + && matches!(items.first(), Some(Value::Int(0))) + && matches!(items.get(1), Some(Value::Int(1))) +} + fn host_heap(error: heap::HeapError) -> VmError { VmError::HostError(error.to_string()) } @@ -469,13 +579,7 @@ fn drive_plugin( plugin: &'static Plugin, nodes: Option, ) -> Ran { - let catalog = Arc::clone(if plugin.auto_table { - catalog_auto() - } else if plugin.run_control { - catalog_for(true, true) - } else { - catalog(plugin.guest_step) - }); + let catalog = Arc::clone(plugin_catalog(plugin)); let options = CompileSourceFileOptions::new() .with_source_plugin(plugin) .with_host_api_catalog(Arc::clone(&catalog)); @@ -3516,7 +3620,7 @@ return 1 assert_eq!( text_value(&ran.trace, 5.0), "table", - "a later empty table must not start another automatic cycle" + "w[3] = {{}} is an assignment, not `local name = {{}}`, so it is not an automatic safepoint" ); assert_eq!(text_value(&ran.trace, 6.0), "nil"); assert_eq!(note_value(&ran.trace, 9.0), 1.0); @@ -3533,3 +3637,592 @@ return 1 assert!(ran.subject_alive.unwrap_or(false)); assert!(ran.token_open.unwrap_or(false)); } + +const LIVE_UNISSUED_PREFIX: &str = r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + local unissued = external_shape() + note(1, shape(unissued)) +"#; + +/// Due empty local still gathers. The saved array is usable, then GATHER_ROOT +/// rejects it. This is the positive control for the skipped-gather witness. +#[test] +fn due_empty_local_rejects_a_saved_unissued_shape_at_gather() { + let ran = run_auto_table( + &format!( + "{LIVE_UNISSUED_PREFIX} + note(2, collectgarbage(\"restart\")) + bit(1, collectgarbage(\"isrunning\")) + text(1, type(rawget(w, 2))) + local fresh = {{}} + peek(fresh) + return 1 +end +witness() +return 1 +" + ), + Some(&[10_000, 10_000]), + ); + assert_eq!( + note_value(&ran.trace, 1.0), + 1.0, + "the array was saved and read" + ); + assert_eq!( + note_value(&ran.trace, 2.0), + 0.0, + "restart itself does not collect" + ); + assert!( + bit_value(&ran.trace, 1.0), + "restart leaves the collector running" + ); + assert_eq!( + text_value(&ran.trace, 1.0), + "table", + "weak item before the local" + ); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message.contains("invalid private Lua root candidate")), + "due gather must reject the unissued array at GATHER_ROOT, not a later host: {:?}", + ran.stop + ); + assert_eq!(ran.trace.peeks.len(), 1, "the new table was not published"); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); +} + +/// Heap exists, restart has already reached the threshold, then stop. The next +/// empty local is not due. A still-live unissued array must not be gathered. +#[test] +fn stopped_reached_threshold_skips_gather_on_the_next_empty_local() { + let ran = run_auto_table( + &format!( + "{LIVE_UNISSUED_PREFIX} + note(2, collectgarbage(\"restart\")) + note(3, collectgarbage(\"stop\")) + bit(1, collectgarbage(\"isrunning\")) + text(1, type(rawget(w, 2))) + local fresh = {{}} + peek(fresh) + text(2, type(fresh)) + text(3, type(rawget(w, 2))) + note(4, same(held, rawget(w, 1))) + return 1 +end +witness() +return 1 +" + ), + Some(&[10_000, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!( + note_value(&ran.trace, 1.0), + 1.0, + "the array was saved and read" + ); + assert_eq!(note_value(&ran.trace, 2.0), 0.0); + assert_eq!(note_value(&ran.trace, 3.0), 0.0); + assert!(!bit_value(&ran.trace, 1.0)); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!( + text_value(&ran.trace, 2.0), + "table", + "the empty local is ordinary allocation" + ); + assert_eq!( + text_value(&ran.trace, 3.0), + "table", + "stop after a reached threshold must not gather or collect" + ); + assert_eq!(note_value(&ran.trace, 4.0), 1.0); + assert_eq!(ran.trace.peeks.len(), 2); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); + assert!(ran.trace.steps.is_empty()); +} + +/// Full opt-in, heap present, collector still running, but restart never wrote +/// a threshold. The empty local is not due, so the live unissued array is not +/// gathered. +#[test] +fn running_without_restart_skips_gather_on_an_empty_local() { + let ran = run_auto_table( + &format!( + "{LIVE_UNISSUED_PREFIX} + text(1, type(rawget(w, 2))) + local fresh = {{}} + peek(fresh) + text(2, type(fresh)) + text(3, type(rawget(w, 2))) + note(4, same(held, rawget(w, 1))) + return 1 +end +witness() +return 1 +" + ), + Some(&[10_000, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(note_value(&ran.trace, 1.0), 1.0); + assert_eq!(text_value(&ran.trace, 2.0), "table"); + assert_eq!(text_value(&ran.trace, 3.0), "table"); + assert_eq!(note_value(&ran.trace, 4.0), 1.0); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); +} + +/// A direct restart-entry call while stopped must return before decode, budget, +/// latch, or a cycle. Empty budgets would fault if the dispatch gate were skipped. +#[test] +fn direct_auto_restart_while_stopped_does_not_pass_the_due_gate() { + let ran = run_auto_table( + r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + note(1, collectgarbage("restart")) + note(2, collectgarbage("stop")) + note(3, direct_auto_restart()) + text(1, type(rawget(w, 2))) + return 1 +end +witness() +return 1 +"#, + Some(&[]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(note_value(&ran.trace, 1.0), 0.0); + assert_eq!(note_value(&ran.trace, 2.0), 0.0); + assert_eq!( + note_value(&ran.trace, 3.0), + 0.0, + "not due returns before the body" + ); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); +} + +fn incomplete_route_source() -> String { + format!( + "{LIVE_UNISSUED_PREFIX} + note(2, collectgarbage(\"restart\")) + bit(1, collectgarbage(\"isrunning\")) + local fresh = {{}} + peek(fresh) + text(2, type(fresh)) + text(3, type(rawget(w, 2))) + return 1 +end +witness() +return 1 +" + ) +} + +fn assert_unrouted_empty_local(ran: &Ran) { + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!( + note_value(&ran.trace, 1.0), + 1.0, + "the array was saved and read" + ); + assert!(bit_value(&ran.trace, 1.0)); + assert_eq!(text_value(&ran.trace, 2.0), "table"); + assert_eq!( + text_value(&ran.trace, 3.0), + "table", + "an incomplete catalog must not gather or collect" + ); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); +} + +#[test] +fn restart_entry_without_due_schema_does_not_connect_the_route() { + let ran = drive_plugin( + &incomplete_route_source(), + Some(&[10_000, 10_000]), + &RESTART_ENTRY_PLUGIN, + None, + ); + assert_unrouted_empty_local(&ran); + assert!( + due_branch(&candidate::lower(&incomplete_route_source(), catalog_restart_entry()).unwrap()) + .is_none() + ); +} + +#[test] +fn due_schema_without_restart_entry_does_not_connect_the_route() { + let ran = drive_plugin( + &incomplete_route_source(), + Some(&[10_000, 10_000]), + &DUE_ONLY_PLUGIN, + None, + ); + assert_unrouted_empty_local(&ran); + assert!( + due_branch(&candidate::lower(&incomplete_route_source(), catalog_due_only()).unwrap()) + .is_none() + ); +} + +#[test] +fn ordinary_run_control_catalog_does_not_connect_the_auto_route() { + let ran = drive_plugin( + &incomplete_route_source(), + Some(&[10_000, 10_000]), + &CONTROL_PLUGIN, + None, + ); + assert_unrouted_empty_local(&ran); + assert!( + due_branch(&candidate::lower(&incomplete_route_source(), catalog_for(true, true)).unwrap()) + .is_none() + ); +} + +/// First empty local spends the only two budget segments. A later real +/// `local name = {}` stays available, and an assignment-seeded weak item is +/// still present, because the latch makes that local not due. +#[test] +fn second_empty_local_does_not_repeat_the_automatic_cycle() { + let pad = "x".repeat(4096); + let ran = run_auto_table( + &format!( + r#" +local function witness() + local w = {{}} + local mt = {{}} + local held = {{}} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {{}} + peek(held) + note(11, collectgarbage("count")) + note(2, collectgarbage("restart")) + local fresh = {{}} + bit(5, peek(fresh)) + text(3, type(fresh)) + text(4, type(rawget(w, 2))) + w[3] = {{}} + held.pad = "{pad}" + meter(40) + note(13, collectgarbage("count")) + local again = {{}} + bit(6, peek(again)) + text(7, type(again)) + text(8, type(rawget(w, 3))) + collectgarbage("collect") + text(9, type(rawget(w, 3))) + note(9, same(held, rawget(w, 1))) + return 1 +end +witness() +return 1 +"# + ), + Some(&[10_000, 10_000]), + ); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_eq!(text_value(&ran.trace, 3.0), "table"); + assert_eq!( + text_value(&ran.trace, 4.0), + "nil", + "the first local collected" + ); + assert_eq!(cycle_at(&ran.trace, 5.0), (false, 1)); + let logical = note_value(&ran.trace, 40.0); + let threshold = note_value(&ran.trace, 41.0); + assert!( + threshold > 0.0 && logical >= threshold, + "logical {logical} must already meet the restart threshold {threshold} before the second local" + ); + assert!( + note_value(&ran.trace, 13.0) >= note_value(&ran.trace, 11.0), + "count before the second local must not sit below the restart reading" + ); + assert!( + note_value(&ran.trace, 42.0) == 0.0, + "the latch makes the second local not due" + ); + assert!( + note_value(&ran.trace, 43.0) == 1.0, + "the first cycle set the one-shot latch" + ); + assert!( + note_value(&ran.trace, 44.0) == 1.0, + "the collector is still running" + ); + assert!( + bit_value(&ran.trace, 6.0), + "the second empty local is usable" + ); + assert_eq!(text_value(&ran.trace, 7.0), "table"); + assert_eq!( + text_value(&ran.trace, 8.0), + "table", + "the assignment-seeded weak item must survive the second local" + ); + assert_eq!( + cycle_at(&ran.trace, 6.0), + (false, 1), + "the second local must not record another collection" + ); + assert_eq!( + text_value(&ran.trace, 9.0), + "nil", + "a later explicit collect can clear it" + ); + assert_eq!(note_value(&ran.trace, 9.0), 1.0); + assert_eq!( + ran.collections, 2, + "automatic cycle plus the explicit collect" + ); + assert_eq!(ran.collects, 2); + assert!(ran.trace.steps.is_empty()); + assert!(!ran.tail); +} + +const RESERVED_SOURCE: &str = r#" +local function witness() + local held = external_shape() + local fresh = {} + return 1 +end +witness() +return 1 +"#; + +/// The due call has no guest arguments. Gather statements, including their +/// reserved slots, live only in the taken branch and are absent from the +/// not-due branch. +#[test] +fn due_branch_reserves_gather_slots_without_a_guest_argument() { + let ir = candidate::lower(RESERVED_SOURCE, catalog_auto()).expect("lower opt-in"); + let branch = due_branch(&ir).expect("opt-in empty local emits the due branch"); + assert!( + branch.condition_args == 0, + "the judgment must not evaluate a guest argument" + ); + assert!( + branch.gather_slots >= 1, + "the taken branch reserves gather slots" + ); + assert!(branch.gather_slots_unique); + assert!( + !branch.then_calls.is_empty() + && branch + .then_calls + .iter() + .all(|name| name == candidate::GATHER_ROOT), + "the taken branch is only gather statements: {:?}", + branch.then_calls + ); + assert_eq!(branch.then_expr, candidate::AUTO_TABLE_RESTART); + assert!( + branch.else_calls.is_empty(), + "the not-due branch does no host work" + ); + assert!(branch.restart_args_have_no_call); + let plain = candidate::lower(RESERVED_SOURCE, catalog_for(true, true)).expect("lower plain"); + assert!(due_branch(&plain).is_none()); + assert!( + branch.gather_slots + count_lets(&plain) <= count_lets(&ir), + "skipping the branch at run time does not remove the reserved IR slots" + ); +} + +struct DueBranch { + condition_args: usize, + gather_slots: usize, + gather_slots_unique: bool, + then_calls: Vec, + then_expr: String, + else_calls: Vec, + restart_args_have_no_call: bool, +} + +fn due_branch(ir: &FrontendIr) -> Option { + let mut found = None; + for function in ir.function_impls.values() { + for stmt in &function.body_stmts { + visit_stmt(stmt, &mut found); + } + visit_expr(&function.body_expr, &mut found); + } + for stmt in &ir.stmts { + visit_stmt(stmt, &mut found); + } + found +} + +fn visit_stmt(stmt: &Stmt, found: &mut Option) { + match stmt { + Stmt::Let { expr, .. } | Stmt::Assign { expr, .. } => visit_expr(expr, found), + _ => {} + } +} + +fn visit_expr(expr: &Expr, found: &mut Option) { + if let Expr::IfElse { + condition, + then_expr, + else_expr, + } = expr + && condition + .host_call_resolution() + .is_some_and(|call| call.name == candidate::AUTO_TABLE_DUE) + { + let Expr::Call(_, _, args, _, _) = condition.as_ref() else { + unreachable!("due resolution is a call"); + }; + let Expr::Block { stmts, expr: taken } = then_expr.as_ref() else { + panic!("due branch must hold the gather statements"); + }; + let mut slots = Vec::new(); + let mut then_calls = Vec::new(); + for stmt in stmts { + let Stmt::Let { index, expr, .. } = stmt else { + panic!("gather branch contains a non-let: {stmt:?}"); + }; + let name = expr + .host_call_resolution() + .map(|call| call.name.clone()) + .unwrap_or_default(); + then_calls.push(name); + slots.push(format!("{index:?}")); + } + let unique = slots.iter().collect::>().len() == slots.len(); + let restart_args_have_no_call = match taken.as_ref() { + Expr::Call(_, _, args, _, _) => args.iter().all(|arg| call_names(arg).is_empty()), + _ => false, + }; + *found = Some(DueBranch { + condition_args: args.len(), + gather_slots: slots.len(), + gather_slots_unique: unique, + then_calls, + then_expr: taken + .host_call_resolution() + .map(|call| call.name.clone()) + .unwrap_or_default(), + else_calls: call_names(else_expr), + restart_args_have_no_call, + }); + return; + } + match expr { + Expr::IfElse { + condition, + then_expr, + else_expr, + } => { + visit_expr(condition, found); + visit_expr(then_expr, found); + visit_expr(else_expr, found); + } + Expr::Block { stmts, expr } => { + for stmt in stmts { + visit_stmt(stmt, found); + } + visit_expr(expr, found); + } + Expr::Call(_, _, args, _, _) => { + for arg in args { + visit_expr(arg, found); + } + } + _ => {} + } +} + +fn call_names(expr: &Expr) -> Vec { + let mut names = Vec::new(); + fn walk(expr: &Expr, names: &mut Vec) { + if let Some(call) = expr.host_call_resolution() { + names.push(call.name.clone()); + } + match expr { + Expr::Call(_, _, args, _, _) => { + for arg in args { + walk(arg, names); + } + } + Expr::IfElse { + condition, + then_expr, + else_expr, + } => { + walk(condition, names); + walk(then_expr, names); + walk(else_expr, names); + } + Expr::Block { stmts, expr } => { + for stmt in stmts { + if let Stmt::Let { expr, .. } | Stmt::Assign { expr, .. } = stmt { + walk(expr, names); + } + } + walk(expr, names); + } + _ => {} + } + } + walk(expr, &mut names); + names +} + +fn count_lets(ir: &FrontendIr) -> usize { + fn stmts(stmts: &[Stmt]) -> usize { + stmts + .iter() + .map(|stmt| match stmt { + Stmt::Let { expr, .. } | Stmt::Assign { expr, .. } => 1 + exprs(expr), + _ => 0, + }) + .sum() + } + fn exprs(expr: &Expr) -> usize { + match expr { + Expr::Block { stmts: inner, expr } => stmts(inner) + exprs(expr), + Expr::IfElse { + condition, + then_expr, + else_expr, + } => exprs(condition) + exprs(then_expr) + exprs(else_expr), + Expr::Call(_, _, args, _, _) => args.iter().map(exprs).sum(), + _ => 0, + } + } + let mut total = stmts(&ir.stmts); + for function in ir.function_impls.values() { + total += stmts(&function.body_stmts); + total += exprs(&function.body_expr); + } + total +} From 4a034cef01fe1b35c6ec618e06d714c795c566b6 Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 05:19:05 +0800 Subject: [PATCH 140/225] Replay the reviewed gray allocation finish onto runtime step data Apply the reviewed gray pause allocation using its own parent as the merge base. Observation fields keep runtime budgets and running, then the gray phase, pending mark, and parked root-write count. The heap files match the automatic commit. Barrier files stay at the destination. This replay adds no comment cleanup, cross-source test, new numeric key, root-batch capacity, Release allocation, or production wiring. --- src/frontends/lua/heap.rs | 8 + src/frontends/lua/heap/table/mark.rs | 11 + tests/luajit_heap_runtime/candidate.rs | 26 +- .../source_scalar_retire.rs | 424 ++++++++++++++++++ 4 files changed, 464 insertions(+), 5 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index d3b0ace..9dc1520 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -692,6 +692,14 @@ pub fn saved_tail_state(host: &mut HostContext) -> Result Ok(heap.saved_tail_state()) } +/// Saved mark phase and whether gray work remains. Absent means no saved mark. +/// Does not take the mark, scan, enqueue, or write. +#[cfg(test)] +pub fn saved_mark_query(host: &HostContext) -> Option<(&'static str, bool)> { + host.scope_state::() + .and_then(LuaHeap::saved_mark_query) +} + /// Copies the scan meter without clearing it. #[cfg(test)] pub fn copy_scan_meter(host: &mut HostContext) -> Result { diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index b4f2ee6..232a72d 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -1110,6 +1110,17 @@ fn mode_string_byte(heap: &LuaHeap, edge_index: u32, at: usize) -> Option { } impl LuaHeap { + /// Phase and whether a gray edge or queued owner is still unscanned. + /// Does not take the mark, scan, or write. + #[cfg(test)] + pub fn saved_mark_query(&self) -> Option<(&'static str, bool)> { + let state = self.mark.as_ref()?; + Some(( + state.phase_name(), + !state.gray.is_empty() || state.cursor.is_some(), + )) + } + /// Counts a fixed root store and marks its target while mutation is open. /// The enqueue uses the same `follow_one` path as a root visit. It does /// not move the root cursor or the current owner cursor. diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 9cd4687..5282951 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -155,7 +155,10 @@ pub(super) fn install_auto_table_due_schema(builder: &mut HostApiBuilder) { pub(super) fn install_auto_table_restart_entry_schema(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( AUTO_TABLE_RESTART, - vec![HostParamSchema::value("roots", HostTypeSchema::Unknown)], + vec![ + HostParamSchema::value("roots", HostTypeSchema::Unknown), + HostParamSchema::value("handoff", HostTypeSchema::Float), + ], HostTypeSchema::Float, )); } @@ -1853,8 +1856,8 @@ pub(super) fn capture_counts(vm: &mut vm::Vm) -> (u32, u32) { fn decode_safepoint_roots(call: &mut OwnedHostCall<'_>) -> Result, VmError> { let roots = match call.args() { - [Value::Null] => return Ok(Vec::new()), - [Value::Array(roots)] => roots.clone(), + [Value::Null] | [Value::Null, _] => return Ok(Vec::new()), + [Value::Array(roots)] | [Value::Array(roots), _] => roots.clone(), _ => { return Err(VmError::HostError( "invalid private Lua root list".to_string(), @@ -2063,6 +2066,10 @@ fn auto_table_restart(call: &mut OwnedHostCall<'_>) -> Result { return Ok(Value::Float(0.0)); } let tables = decode_safepoint_roots(call)?; + // 1 is emitted only for a function-local empty table, whose next statements + // are NEW_TABLE and ROOT_ISSUED. The host still requires a saved gray phase + // with a pending scan; chunk locals and direct calls pass 0. + let root_handoff = matches!(call.args().get(1), Some(Value::Float(flag)) if *flag == 1.0); let mut host = call.vm().host_context(); let mark_budget = pop_step_budget(&mut host)?; if let Some(control) = host.scope_state_mut::() { @@ -2090,6 +2097,11 @@ fn auto_table_restart(call: &mut OwnedHostCall<'_>) -> Result { } } } + heap::StepOutcome::Paused { tail: false } + if root_handoff && matches!(heap::saved_mark_query(&host), Some(("gray", true))) => + { + return Ok(Value::Float(0.0)); + } heap::StepOutcome::Paused { tail } => { return Err(VmError::HostError(format!( "auto table restart mark paused tail={tail}" @@ -3147,7 +3159,11 @@ impl Lower<'_> { let start = self.stmts.len(); let roots = self.gather_safepoint_roots(span)?; let gather = self.stmts.split_off(start); - let taken = self.call(AUTO_TABLE_RESTART, vec![roots])?; + // Only a function-local empty table continues into NEW_TABLE and then + // ROOT_ISSUED, with no guest safepoint between those statements. + // Chunk locals, and the direct probe, pass 0 and keep the pause error. + let handoff = Expr::Float(if self.in_function { 1.0 } else { 0.0 }); + let taken = self.call(AUTO_TABLE_RESTART, vec![roots, handoff])?; let expr = Expr::IfElse { condition: Box::new(due), then_expr: Box::new(Expr::Block { @@ -4516,7 +4532,7 @@ impl Lower<'_> { if self.catalog.function(AUTO_TABLE_RESTART).is_none() { return Err(self.unsupported(expr.span())); } - return self.call(AUTO_TABLE_RESTART, vec![Expr::Null]); + return self.call(AUTO_TABLE_RESTART, vec![Expr::Null, Expr::Float(0.0)]); } let name = std::str::from_utf8(&name.bytes).map_err(|_| self.unsupported(expr.span()))?; diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index d180906..7529b8a 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -28,6 +28,7 @@ const TEXT: &str = "lua_host::text"; const BIT: &str = "lua_host::bit"; const SHAPE: &str = "lua_host::shape"; const METER: &str = "lua_host::meter"; +const MARK_PHASE: &str = "lua_host::mark_phase"; const SOURCE: &str = r#" local function witness() @@ -82,6 +83,18 @@ struct StepNote { collections: u32, } +#[derive(Clone, Debug)] +struct MarkNote { + tag: f64, + phase: Option<&'static str>, + pending: bool, + parked_root_writes: u64, + work_pushed: u64, + mark_passes: u64, + live_nodes: u32, + collects: usize, +} + #[derive(Clone, Debug, Default)] struct Trace { steps: Vec, @@ -91,6 +104,7 @@ struct Trace { texts: Vec<(f64, String)>, bits: Vec<(f64, bool)>, bit_cycle_state: Vec<(bool, u32)>, + marks: Vec, } #[derive(Clone, Debug)] @@ -121,6 +135,9 @@ struct Ran { release_root: Option, budgets: Vec, running: bool, + mark_phase: Option<&'static str>, + mark_pending: bool, + parked_root_writes: u64, } struct Plugin { @@ -254,6 +271,11 @@ fn install_witness_schemas(builder: &mut vm::HostApiBuilder) { ], HostTypeSchema::Bool, )); + builder.function(vm::HostFunctionSchema::with_return( + MARK_PHASE, + vec![HostParamSchema::value("tag", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); } fn catalog_for(guest_step: bool, run_control: bool) -> &'static Arc { @@ -342,6 +364,7 @@ fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { (BIT, HostOp::Bit), (SHAPE, HostOp::Shape), (METER, HostOp::Meter), + (MARK_PHASE, HostOp::MarkPhase), ] { let function = catalog.function(name).expect("scalar step host schema"); registry @@ -365,6 +388,7 @@ enum HostOp { Bit, Shape, Meter, + MarkPhase, } impl HostOwnedFunction for HostOp { @@ -445,6 +469,31 @@ impl HostOwnedFunction for HostOp { })?; Value::Float(snap.logical as f64) } + Self::MarkPhase => { + let [Value::Float(tag)] = args.as_slice() else { + return Err(host_fault("expected mark phase tag")); + }; + let mark = heap::saved_mark_query(&host); + let meter = heap::copy_scan_meter(&mut host).map_err(host_heap)?; + let stats = heap::stats(&mut host).map_err(host_heap)?; + let collects = host + .scope_state::() + .map(|witness| witness.collects.len()) + .unwrap_or(0); + note(&mut host, |state| { + state.marks.push(MarkNote { + tag: *tag, + phase: mark.map(|(phase, _)| phase), + pending: mark.is_some_and(|(_, pending)| pending), + parked_root_writes: meter.parked_root_writes, + work_pushed: meter.scratch.work_pushed, + mark_passes: meter.mark_passes, + live_nodes: stats.live_nodes, + collects, + }); + })?; + Value::Float(0.0) + } }; Ok(CallOutcome::Return(CallReturn::one(value))) } @@ -676,6 +725,8 @@ fn drive_plugin( Ok(other) => Stop::Other(format!("{other:?}")), Err(other) => Stop::Other(other.to_string()), }; + let mark = heap::saved_mark_query(&vm.host_context()); + let meter = heap::copy_scan_meter(&mut vm.host_context()).unwrap_or_default(); Ran { stop, stack: vm.stack().to_vec(), @@ -694,6 +745,9 @@ fn drive_plugin( release_root, budgets, running, + mark_phase: mark.map(|(phase, _)| phase), + mark_pending: mark.is_some_and(|(_, pending)| pending), + parked_root_writes: meter.parked_root_writes, } } @@ -4226,3 +4280,373 @@ fn count_lets(ir: &FrontendIr) -> usize { } total } + +/// This graph's measured pause map, from a read-only phase sweep on the parent: +/// 1 is reset, 33 is roots, 34..=54 is gray with a pending scan, 56 is gray +/// with the scan already drained, and 58 publishes the tail. 40 is inside the +/// pending gray window, not a one-unit guess. +const GRAY_PENDING_BUDGET: u64 = 40; +const GRAY_NODES_BEFORE_FRESH: u32 = 13; + +fn gray_function(tail: &str) -> String { + format!( + "local function witness()\n \ +local w = {{}}\n \ +local mt = {{}}\n \ +local held = {{}}\n \ +local ballast = {{}}\n \ +mt.__mode = \"v\"\n \ +setmetatable(w, mt)\n \ +w[1] = held\n \ +w[2] = {{}}\n \ +ballast[1] = {{}}\n \ +ballast[2] = {{}}\n \ +ballast[3] = {{}}\n \ +ballast[4] = {{}}\n \ +ballast[5] = {{}}\n \ +ballast[6] = {{}}\n \ +ballast[7] = {{}}\n \ +ballast[8] = {{}}\n \ +{tail}\n\ +end\nwitness()\nreturn 1\n", + tail = tail + ) +} + +fn mark_note(trace: &Trace, tag: f64) -> &MarkNote { + trace + .marks + .iter() + .find(|note| note.tag == tag) + .unwrap_or_else(|| panic!("missing mark note {tag} in {:?}", trace.marks)) +} + +fn assert_fresh_not_built(ran: &Ran) { + assert_eq!( + ran.trace.peeks.len(), + 1, + "only the pre-existing root was peeked" + ); + assert_eq!(ran.parked_root_writes, 0, "ROOT_ISSUED did not run"); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); + assert_eq!( + text_value(&ran.trace, 1.0), + "table", + "weak item still present" + ); +} + +/// Opt-in restart that pauses in gray with scan work still queued must finish +/// the empty local through the existing NEW_TABLE plus ROOT_ISSUED handoff, +/// leave that cycle saved, and let a later explicit step finish it once. +#[test] +fn auto_gray_pause_allocates_the_empty_local_and_keeps_the_cycle() { + let source = gray_function( + "\ +bit(1, peek(held)) + note(1, collectgarbage(\"restart\")) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(2, peek(fresh)) + mark_phase(1) + text(2, type(rawget(w, 2))) + bit(3, collectgarbage(\"step\")) + mark_phase(2) + text(3, type(rawget(w, 2))) + bit(4, collectgarbage(\"step\")) + text(4, type(rawget(w, 2))) + bit(5, collectgarbage(\"step\")) + bit(6, peek(held)) + bit(7, peek(fresh)) + return 1", + ); + let ran = run_auto_table(&source, Some(&[GRAY_PENDING_BUDGET, 1, 10_000, 10_000])); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert!( + bit_value(&ran.trace, 1.0), + "held was alive before the pause" + ); + assert!(bit_value(&ran.trace, 2.0), "fresh was allocated"); + assert!(bit_value(&ran.trace, 6.0), "held survived the continuation"); + assert!( + bit_value(&ran.trace, 7.0), + "fresh survived the continuation" + ); + let held = ran.trace.peeks[0].table; + let fresh = ran.trace.peeks[1].table; + assert_ne!(held, fresh, "the new table is not the existing strong root"); + assert_eq!(ran.trace.peeks[2].table, held); + assert_eq!(ran.trace.peeks[3].table, fresh); + let at_handoff = mark_note(&ran.trace, 1.0); + assert_eq!(at_handoff.phase, Some("gray")); + assert!( + at_handoff.pending, + "scan work remained after the root handoff" + ); + assert!( + at_handoff.parked_root_writes >= 1, + "ROOT_ISSUED wrote the new root during gray: {at_handoff:?}" + ); + assert!( + at_handoff.work_pushed >= 11, + "the new root was marked onto the gray queue: {at_handoff:?}" + ); + assert_eq!(at_handoff.mark_passes, 1); + assert_eq!( + at_handoff.collects, 0, + "the automatic pause did not record a completion" + ); + assert_eq!(at_handoff.live_nodes, GRAY_NODES_BEFORE_FRESH + 1); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!( + text_value(&ran.trace, 2.0), + "table", + "weak item survived the handoff" + ); + assert!( + !bit_value(&ran.trace, 3.0), + "the one-unit explicit step must be the next budget, not a later 10000" + ); + let after_unit = mark_note(&ran.trace, 2.0); + assert_eq!(after_unit.phase, Some("gray")); + assert!(after_unit.pending); + assert_eq!(text_value(&ran.trace, 3.0), "table"); + assert!( + !bit_value(&ran.trace, 4.0), + "publishing the weak clear is not a completion" + ); + assert_eq!( + text_value(&ran.trace, 4.0), + "nil", + "the explicit continuation cleared the weak item" + ); + assert!( + bit_value(&ran.trace, 5.0), + "the following explicit step completed the saved tail" + ); + assert_eq!( + ran.collects, 1, + "the continuation recorded the completion once" + ); + assert_eq!(ran.collections, 1); + assert!(!ran.tail); + assert!( + ran.trace.steps.is_empty(), + "guest collectgarbage step is not the private step host" + ); +} + +/// The same pause must not skip the ordinary node-capacity refusal. +#[test] +fn auto_gray_pause_still_refuses_a_full_node_quota() { + let source = gray_function( + "\ +bit(1, peek(held)) + note(1, collectgarbage(\"restart\")) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(2, peek(fresh)) + return 1", + ); + let ran = drive_plugin( + &source, + Some(&[GRAY_PENDING_BUDGET]), + &AUTO_TABLE_PLUGIN, + Some(GRAY_NODES_BEFORE_FRESH), + ); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message.contains("lua heap node capacity")), + "gray pause must not bypass the node quota: {:?}", + ran.stop + ); + assert_fresh_not_built(&ran); + assert_eq!(ran.mark_phase, Some("gray")); + assert!(ran.mark_pending); + assert_eq!(ran.live_nodes, GRAY_NODES_BEFORE_FRESH); +} + +#[test] +fn auto_gray_graph_reset_pause_does_not_allocate() { + let source = gray_function( + "\ +bit(1, peek(held)) + note(1, collectgarbage(\"restart\")) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(2, peek(fresh)) + return 1", + ); + let ran = run_auto_table(&source, Some(&[1])); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message == "auto table restart mark paused tail=false"), + "{:?}", + ran.stop + ); + assert_eq!(ran.mark_phase, Some("reset")); + assert!(!ran.mark_pending); + assert_fresh_not_built(&ran); +} + +#[test] +fn auto_gray_graph_roots_pause_does_not_allocate() { + let source = gray_function( + "\ +bit(1, peek(held)) + note(1, collectgarbage(\"restart\")) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(2, peek(fresh)) + return 1", + ); + let ran = run_auto_table(&source, Some(&[33])); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message == "auto table restart mark paused tail=false"), + "{:?}", + ran.stop + ); + assert_eq!(ran.mark_phase, Some("roots")); + assert!(ran.mark_pending); + assert_fresh_not_built(&ran); +} + +#[test] +fn auto_gray_pause_without_pending_scan_does_not_allocate() { + let source = gray_function( + "\ +bit(1, peek(held)) + note(1, collectgarbage(\"restart\")) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(2, peek(fresh)) + return 1", + ); + let ran = run_auto_table(&source, Some(&[56])); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message == "auto table restart mark paused tail=false"), + "{:?}", + ran.stop + ); + assert_eq!(ran.mark_phase, Some("gray")); + assert!(!ran.mark_pending, "drained gray is not remaining scan work"); + assert_fresh_not_built(&ran); +} + +#[test] +fn auto_gray_published_tail_is_not_swallowed() { + let source = gray_function( + "\ +bit(1, peek(held)) + note(1, collectgarbage(\"restart\")) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(2, peek(fresh)) + return 1", + ); + let ran = run_auto_table(&source, Some(&[58])); + assert!( + matches!( + ran.stop, + Stop::HostError(ref message) + if message.contains("missing source step fixture budget") + || message.contains("did not finish the published tail") + ), + "a published tail must stay an error: {:?}", + ran.stop + ); + assert_eq!(ran.trace.peeks.len(), 1, "fresh was not constructed"); + assert_eq!(ran.parked_root_writes, 0); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert!(ran.tail); + assert!(ran.mark_phase.is_none()); +} + +#[test] +fn chunk_auto_gray_pause_does_not_allocate() { + let source = r#" +local function keep_return_window() + return 1 +end +local w = {} +local mt = {} +local held = {} +local ballast = {} +mt.__mode = "v" +setmetatable(w, mt) +w[1] = held +w[2] = {} +ballast[1] = {} +ballast[2] = {} +ballast[3] = {} +ballast[4] = {} +ballast[5] = {} +ballast[6] = {} +ballast[7] = {} +ballast[8] = {} +bit(1, peek(held)) +note(1, collectgarbage("restart")) +text(1, type(rawget(w, 2))) +local fresh = {} +bit(2, peek(fresh)) +keep_return_window() +return 1 +"#; + let ran = run_auto_table(source, Some(&[GRAY_PENDING_BUDGET])); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message == "auto table restart mark paused tail=false"), + "chunk has no ROOT_ISSUED handoff: {:?}", + ran.stop + ); + assert_eq!(ran.mark_phase, Some("gray")); + assert!(ran.mark_pending); + assert_fresh_not_built(&ran); +} + +#[test] +fn stopped_gray_graph_does_not_start_a_cycle() { + let source = gray_function( + "\ +bit(1, peek(held)) + note(1, collectgarbage(\"stop\")) + bit(2, collectgarbage(\"isrunning\")) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(3, peek(fresh)) + return 1", + ); + let ran = run_auto_table(&source, None); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert!(bit_value(&ran.trace, 1.0)); + assert!(!bit_value(&ran.trace, 2.0)); + assert!(bit_value(&ran.trace, 3.0)); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!(ran.trace.peeks.len(), 2); + assert_ne!(ran.trace.peeks[0].table, ran.trace.peeks[1].table); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(ran.mark_phase.is_none()); + assert!(!ran.tail); + assert!(ran.trace.steps.is_empty()); +} + +#[test] +fn direct_auto_restart_gray_pause_does_not_allocate() { + let source = gray_function( + "\ +bit(1, peek(held)) + note(1, collectgarbage(\"restart\")) + text(1, type(rawget(w, 2))) + note(2, direct_auto_restart()) + return 1", + ); + let ran = run_auto_table(&source, Some(&[GRAY_PENDING_BUDGET])); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message == "auto table restart mark paused tail=false"), + "a direct call is not the root handoff: {:?}", + ran.stop + ); + assert_fresh_not_built(&ran); +} From f12c5fd6f5816d5cb2682f8f58ea4cd7d9b9781d Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 06:14:36 +0800 Subject: [PATCH 141/225] Replay the reviewed root-batch capacity onto the runtime union Apply the reviewed capacity commit using its own parent as the merge base. The only conflict keeps the runtime helper remaining_step_budgets, then the capacity helper step_budget_snapshot, each as its original bytes. The two helpers are not merged. Heap files match the capacity commit. This replay adds no cross-source test, Release allocation, new object key, gap refill, production wiring, or cleanup. --- src/frontends/lua/heap.rs | 16 + src/frontends/lua/heap/table/mark.rs | 15 +- tests/luajit_heap_runtime/candidate.rs | 57 +++ .../source_scalar_retire.rs | 414 ++++++++++++++++++ 4 files changed, 500 insertions(+), 2 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 9dc1520..7df56df 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -700,6 +700,22 @@ pub fn saved_mark_query(host: &HostContext) -> Option<(&'static str, bool)> { .and_then(LuaHeap::saved_mark_query) } +/// Capacity of an already decoded automatic root batch. +/// +/// A missing heap is `SweepDenied` and does not install one. This does not +/// pop a budget, set a latch, open a mark, or scan. The private stepper still +/// rechecks the same sum before it takes a saved mark. +#[cfg(test)] +pub fn preflight_automatic_root_capacity( + host: &HostContext, + batch_len: usize, +) -> Result<(), HeapError> { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + heap.root_batch_fits(batch_len) +} + /// Copies the scan meter without clearing it. #[cfg(test)] pub fn copy_scan_meter(host: &mut HostContext) -> Result { diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index 232a72d..9f54e0e 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -661,6 +661,12 @@ impl Drop for ParkedMark<'_> { } impl LuaHeap { + /// Checked `roots.len() + extra` against `limits.roots`. + /// Does not read handles, open a mark, or scan. + pub(crate) fn root_batch_fits(&self, extra: usize) -> Result<(), HeapError> { + checked_root_occupancy(self, extra) + } + /// Positive-budget step of a mark already stored on this heap. /// /// Order is the parked driver's order: saved state, Done, quota, then @@ -696,13 +702,18 @@ impl LuaHeap { } } -fn validate_root_batch(heap: &LuaHeap, batch: &[Rooted]) -> Result<(), HeapError> { +fn checked_root_occupancy(heap: &LuaHeap, extra: usize) -> Result<(), HeapError> { let occupied = u32::try_from(heap.roots.len()).map_err(|_| HeapError::RootCapacity)?; - let extra = u32::try_from(batch.len()).map_err(|_| HeapError::RootCapacity)?; + let extra = u32::try_from(extra).map_err(|_| HeapError::RootCapacity)?; let end = occupied.checked_add(extra).ok_or(HeapError::RootCapacity)?; if end > heap.limits.roots { return Err(HeapError::RootCapacity); } + Ok(()) +} + +fn validate_root_batch(heap: &LuaHeap, batch: &[Rooted]) -> Result<(), HeapError> { + checked_root_occupancy(heap, batch.len())?; for rooted in batch { match *rooted { Rooted::Table(handle) => heap.require_live(handle)?, diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 5282951..c87edcb 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -101,6 +101,13 @@ pub(super) fn remaining_step_budgets(host: &mut vm::HostContext<'_>) -> Vec .unwrap_or_default() } +/// Remaining fixture allowances, oldest first. Does not pop, install, or step. +pub(super) fn step_budget_snapshot(host: &vm::HostContext<'_>) -> Vec { + host.scope_state::() + .map(|budgets| budgets.0.iter().map(|budget| budget.get()).collect()) + .unwrap_or_default() +} + /// Opt in to the fixture-budgeted guest step in this catalog only. pub(super) fn install_step_schemas(builder: &mut HostApiBuilder) { builder.function(HostFunctionSchema::with_return( @@ -2014,6 +2021,7 @@ fn auto_table_due(host: &mut vm::HostContext<'_>) -> Result { /// Read-only snapshot for the once-only witness. Does not decode roots, pop a /// budget, set the latch, or start a cycle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct AutoTableMeter { pub logical: u64, pub threshold: u64, @@ -2054,6 +2062,50 @@ fn confirm_round_finished(host: &mut vm::HostContext<'_>) -> Result<(), VmError> Ok(()) } +/// Decoded automatic batch measured in the same scope, before a budget pop. +/// +/// `planned` is `roots.len() + batch`. Empty fixed slots are in `root_slots`; +/// a live scalar is in neither count. Recording this does not install a heap, +/// pop a budget, set the latch, or open a mark. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct AutoRootPlan { + pub phase: Option<&'static str>, + pub root_slots: u32, + pub batch: u32, + pub planned: u32, +} + +pub(super) fn auto_root_plan(host: &vm::HostContext<'_>) -> Option { + host.scope_state::().copied() +} + +fn note_auto_root_plan(host: &mut vm::HostContext<'_>, batch: usize) -> Result<(), VmError> { + let (phase, root_slots) = { + let Some(heap) = host.scope_state::() else { + return Err(VmError::HostError( + "auto root plan has no installed heap".to_string(), + )); + }; + ( + heap.saved_mark_query().map(|(phase, _)| phase), + heap.stats().root_slots, + ) + }; + let batch = u32::try_from(batch) + .map_err(|_| VmError::HostError("auto root plan batch does not fit u32".to_string()))?; + let planned = root_slots + .checked_add(batch) + .ok_or_else(|| VmError::HostError("auto root plan overflow".to_string()))?; + host.scope_state_or_insert_with(|| AutoRootPlan { + phase, + root_slots, + batch, + planned, + }) + .map_err(|error| VmError::HostError(error.to_string()))?; + Ok(()) +} + /// One idle empty-local safepoint after single-arg restart. /// /// The mark allowance and, only when that call publishes a tail, the @@ -2070,6 +2122,11 @@ fn auto_table_restart(call: &mut OwnedHostCall<'_>) -> Result { // are NEW_TABLE and ROOT_ISSUED. The host still requires a saved gray phase // with a pending scan; chunk locals and direct calls pass 0. let root_handoff = matches!(call.args().get(1), Some(Value::Float(flag)) if *flag == 1.0); + { + let mut host = call.vm().host_context(); + note_auto_root_plan(&mut host, tables.len())?; + heap::preflight_automatic_root_capacity(&host, tables.len()).map_err(heap_error)?; + } let mut host = call.vm().host_context(); let mark_budget = pop_step_budget(&mut host)?; if let Some(control) = host.scope_state_mut::() { diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index 7529b8a..b696910 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -29,6 +29,7 @@ const BIT: &str = "lua_host::bit"; const SHAPE: &str = "lua_host::shape"; const METER: &str = "lua_host::meter"; const MARK_PHASE: &str = "lua_host::mark_phase"; +const OCCUPY: &str = "lua_host::occupy"; const SOURCE: &str = r#" local function witness() @@ -95,6 +96,21 @@ struct MarkNote { collects: usize, } +/// Read-only occupancy taken from the already installed heap. A missing heap +/// is an error from the host; this note does not call `with_heap`. +#[derive(Clone, Copy, Debug)] +struct OccupancyNote { + tag: f64, + root_slots: u32, + live_roots: u32, + live_nodes: u32, + node_slots: u32, + edge_slots: u32, + phase: Option<&'static str>, + mark_passes: u64, + node_slot_visits: u64, +} + #[derive(Clone, Debug, Default)] struct Trace { steps: Vec, @@ -105,6 +121,7 @@ struct Trace { bits: Vec<(f64, bool)>, bit_cycle_state: Vec<(bool, u32)>, marks: Vec, + occupancy: Vec, } #[derive(Clone, Debug)] @@ -276,6 +293,11 @@ fn install_witness_schemas(builder: &mut vm::HostApiBuilder) { vec![HostParamSchema::value("tag", HostTypeSchema::Float)], HostTypeSchema::Float, )); + builder.function(vm::HostFunctionSchema::with_return( + OCCUPY, + vec![HostParamSchema::value("tag", HostTypeSchema::Float)], + HostTypeSchema::Float, + )); } fn catalog_for(guest_step: bool, run_control: bool) -> &'static Arc { @@ -365,6 +387,7 @@ fn register(registry: &mut HostFunctionRegistry, catalog: &vm::HostApiCatalog) { (SHAPE, HostOp::Shape), (METER, HostOp::Meter), (MARK_PHASE, HostOp::MarkPhase), + (OCCUPY, HostOp::Occupy), ] { let function = catalog.function(name).expect("scalar step host schema"); registry @@ -389,6 +412,7 @@ enum HostOp { Shape, Meter, MarkPhase, + Occupy, } impl HostOwnedFunction for HostOp { @@ -494,6 +518,32 @@ impl HostOwnedFunction for HostOp { })?; Value::Float(0.0) } + Self::Occupy => { + let [Value::Float(tag)] = args.as_slice() else { + return Err(host_fault("expected occupy tag")); + }; + let snap = { + let Some(heap) = host.scope_state::() else { + return Err(host_fault("occupy requires the installed heap")); + }; + let stats = heap.stats(); + let mark = heap.saved_mark_query(); + let meter = heap.scan_meter(); + OccupancyNote { + tag: *tag, + root_slots: stats.root_slots, + live_roots: stats.live_roots, + live_nodes: stats.live_nodes, + node_slots: stats.node_slots, + edge_slots: stats.edge_slots, + phase: mark.map(|(phase, _)| phase), + mark_passes: meter.mark_passes, + node_slot_visits: meter.node_slot_visits, + } + }; + note(&mut host, |state| state.occupancy.push(snap))?; + Value::Float(0.0) + } }; Ok(CallOutcome::Return(CallReturn::one(value))) } @@ -4650,3 +4700,367 @@ bit(1, peek(held)) ); assert_fresh_not_built(&ran); } + +/// Fixed frame at the first due empty local: `w`, `mt`, `held`, `fresh`, `spare`. +const ROOT_CAPACITY_SLOTS: u32 = 5; +/// Issued tables in the decoded batch. The live scalar is not one of them. +const ROOT_CAPACITY_BATCH: u32 = 3; +const ROOT_CAPACITY_PLANNED: u32 = ROOT_CAPACITY_SLOTS + ROOT_CAPACITY_BATCH; +const ROOT_STEP_BUDGETS: [u64; 2] = [10_000, 10_000]; + +const AUTOMATIC_ROOT_CAPACITY_SOURCE: &str = r#" +local function witness() + local w = {} + local mt = {} + local held = {} + local scalar = 7 + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + note(1, collectgarbage("restart")) + note(20, scalar) + meter(30) + occupy(1) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(5, peek(fresh)) + text(3, type(fresh)) + text(4, type(rawget(w, 2))) + note(8, same(held, rawget(w, 1))) + note(21, scalar) + local spare = {} + bit(9, peek(spare)) + return 1 +end +witness() +return 1 +"#; + +#[derive(Clone, Debug)] +struct RootArm { + roots_limit: u32, + stop: Stop, + trace: Trace, + tail: bool, + collections: u32, + live_nodes: u32, + root_slots: u32, + live_roots: u32, + node_slots: u32, + edge_slots: u32, + collects: usize, + mark_phase: Option<&'static str>, + mark_passes: u64, + node_slot_visits: u64, + parked_root_writes: u64, + budgets: Vec, + meter: candidate::AutoTableMeter, + plan: Option, + idle: bool, + held_alive: Option, +} + +fn occupy_note(trace: &Trace) -> &OccupancyNote { + trace + .occupancy + .first() + .unwrap_or_else(|| panic!("occupy did not run in this scope: {:?}", trace.occupancy)) +} + +fn run_auto_roots(source: &str, roots: u32) -> RootArm { + let plugin = &AUTO_TABLE_PLUGIN; + let catalog = Arc::clone(plugin_catalog(plugin)); + let options = CompileSourceFileOptions::new() + .with_source_plugin(plugin) + .with_host_api_catalog(Arc::clone(&catalog)); + let prepared = vm::compile_source_with_flavor_and_options(source, SourceFlavor::Lua, options) + .unwrap_or_else(|error| panic!("compile rejected the source: {error}")); + let mut vm = prepared.into_vm().expect("create VM"); + assert_return_window(vm.program()); + let mut registry = HostFunctionRegistry::empty(); + candidate::register(&mut registry, &catalog).expect("register candidate runtime"); + register(&mut registry, &catalog); + registry.bind_vm_cached(&mut vm).expect("bind runtime"); + let prepared_budgets: Vec<_> = ROOT_STEP_BUDGETS + .iter() + .map(|&budget| NonZeroU64::new(budget).expect("positive fixture budget")) + .collect(); + candidate::set_step_budgets(&mut vm.host_context(), &prepared_budgets); + let production = heap::HeapLimits::production(); + heap::install( + &mut vm.host_context(), + heap::HeapLimits { + nodes: production.nodes, + roots, + edges: production.edges, + max_generation: production.max_generation, + }, + ) + .expect("install the roots limit before execution"); + let status = vm.run(); + let stop = match status { + Ok(VmStatus::Halted) => Stop::Halted, + Err(VmError::HostError(message)) => Stop::HostError(message), + Ok(other) => Stop::Other(format!("{other:?}")), + Err(other) => Stop::Other(other.to_string()), + }; + let mut host = vm.host_context(); + let trace = host.scope_state::().cloned().unwrap_or_default(); + let stats = host + .scope_state::() + .map(|heap| heap.stats()) + .unwrap_or_else(|| { + panic!("installed heap missing after {stop:?}; refusing to install again") + }); + let mark = heap::saved_mark_query(&host); + let scan = heap::copy_scan_meter(&mut host) + .unwrap_or_else(|error| panic!("scan copy failed without installing: {error}")); + let tail = heap::saved_sweep_tail(&mut host) + .unwrap_or_else(|error| panic!("tail read failed without installing: {error}")); + let idle = heap::fixed_step_idle(&mut host) + .unwrap_or_else(|error| panic!("idle read failed without installing: {error}")); + let meter = candidate::auto_table_meter(&mut host) + .unwrap_or_else(|error| panic!("meter read failed without installing: {error}")); + let budgets = candidate::step_budget_snapshot(&host); + let plan = candidate::auto_root_plan(&host); + let collects = host + .scope_state::() + .map(|witness| witness.collects.len()) + .unwrap_or(0); + let held_alive = trace.peeks.first().map(|observed| { + host.scope_state::() + .is_some_and(|heap| heap.alive(observed.table)) + }); + RootArm { + roots_limit: roots, + stop, + trace, + tail, + collections: stats.collections, + live_nodes: stats.live_nodes, + root_slots: stats.root_slots, + live_roots: stats.live_roots, + node_slots: stats.node_slots, + edge_slots: stats.edge_slots, + collects, + mark_phase: mark.map(|(phase, _)| phase), + mark_passes: scan.mark_passes, + node_slot_visits: scan.node_slot_visits, + parked_root_writes: scan.parked_root_writes, + budgets, + meter, + plan, + idle, + held_alive, + } +} + +fn assert_same_scope_plan(ran: &RootArm) { + let occupy = occupy_note(&ran.trace); + assert_eq!(occupy.tag, 1.0); + assert!( + occupy.phase.is_none(), + "the pre-safepoint read must still be idle: {occupy:?}" + ); + assert!( + occupy.root_slots > occupy.live_roots, + "an empty fixed slot must count in root capacity: {occupy:?}" + ); + assert_eq!( + note_value(&ran.trace, 20.0), + 7.0, + "the scalar is live and is not a table root" + ); + assert_eq!(occupy.root_slots, ROOT_CAPACITY_SLOTS, "{occupy:?}"); + assert_eq!( + occupy.live_roots, ROOT_CAPACITY_BATCH, + "issued tables only; the scalar is not a root slot: {occupy:?}" + ); + let plan = ran + .plan + .unwrap_or_else(|| panic!("decoded plan was not recorded in this scope: {ran:?}")); + assert!( + plan.phase.is_none(), + "the decoded batch was measured before a mark: {plan:?}" + ); + assert_eq!( + plan.root_slots, occupy.root_slots, + "plan {plan:?} occupy {occupy:?}" + ); + assert_eq!(plan.batch, ROOT_CAPACITY_BATCH, "{plan:?}"); + assert_eq!(plan.planned, plan.root_slots + plan.batch); + assert_eq!(plan.planned, ROOT_CAPACITY_PLANNED, "{plan:?}"); + assert_ne!( + ran.roots_limit, 0, + "the arm must install a real roots limit" + ); +} + +/// Exact `roots.len() + batch` still finishes the first automatic empty local. +#[test] +fn exact_automatic_root_capacity_finishes_the_empty_local() { + let ran = run_auto_roots(AUTOMATIC_ROOT_CAPACITY_SOURCE, ROOT_CAPACITY_PLANNED); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + assert_same_scope_plan(&ran); + assert!(bit_value(&ran.trace, 5.0), "fresh was allocated"); + assert!( + bit_value(&ran.trace, 9.0), + "the later empty slot was allocated" + ); + assert_eq!(ran.trace.peeks.len(), 3); + assert_ne!(ran.trace.peeks[0].table, ran.trace.peeks[1].table); + assert_eq!(text_value(&ran.trace, 3.0), "table"); + assert_eq!( + text_value(&ran.trace, 4.0), + "nil", + "the automatic cycle clears the independent weak item" + ); + assert_eq!(note_value(&ran.trace, 8.0), 1.0, "held keeps its identity"); + assert_eq!( + note_value(&ran.trace, 21.0), + 7.0, + "the scalar survives the cycle" + ); + assert_eq!(cycle_at(&ran.trace, 5.0), (false, 1)); + assert_eq!(ran.collects, 1); + assert_eq!(ran.collections, 1); + assert!(!ran.tail); + assert!(ran.mark_phase.is_none()); + assert!(ran.idle); + assert!(ran.held_alive.unwrap_or(false)); + assert!(ran.trace.steps.is_empty()); + assert!( + ran.budgets.len() < ROOT_STEP_BUDGETS.len(), + "the exact arm must actually spend a step allowance: {:?}", + ran.budgets + ); +} + +/// One root short of the decoded batch must refuse before latch, budget, or mark. +#[test] +fn automatic_root_capacity_one_short_keeps_the_idle_heap() { + let ran = run_auto_roots(AUTOMATIC_ROOT_CAPACITY_SOURCE, ROOT_CAPACITY_PLANNED - 1); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message == "lua heap root capacity"), + "first refusal must be root capacity, not another resource error: {:?}", + ran.stop + ); + assert_same_scope_plan(&ran); + assert_eq!(ran.roots_limit + 1, ran.plan.expect("plan").planned); + assert!( + ran.mark_phase.is_none(), + "refusal must not leave a saved mark, got {:?} plan {:?}", + ran.mark_phase, + ran.plan + ); + assert!(ran.idle, "fixed step must stay idle"); + assert!(!ran.tail, "refusal must not publish a tail"); + assert!(!ran.meter.requested, "auto_requested {:?}", ran.meter); + assert!(ran.meter.due, "due must stay true: {:?}", ran.meter); + assert!(ran.meter.running, "running changed: {:?}", ran.meter); + assert_eq!( + ran.meter.threshold as f64, + note_value(&ran.trace, 31.0), + "threshold changed: {:?} notes {:?}", + ran.meter, + ran.trace.notes + ); + assert_eq!( + note_value(&ran.trace, 32.0), + 1.0, + "due was true before the safepoint" + ); + assert_eq!( + note_value(&ran.trace, 33.0), + 0.0, + "latch was clear before the safepoint" + ); + assert_eq!( + note_value(&ran.trace, 34.0), + 1.0, + "running before the safepoint" + ); + assert_eq!( + ran.budgets, + ROOT_STEP_BUDGETS.to_vec(), + "both allowances must remain" + ); + let occupy = occupy_note(&ran.trace); + assert_eq!(ran.root_slots, occupy.root_slots); + assert_eq!(ran.live_roots, occupy.live_roots); + assert_eq!(ran.live_nodes, occupy.live_nodes); + assert_eq!(ran.node_slots, occupy.node_slots); + assert_eq!(ran.edge_slots, occupy.edge_slots); + assert_eq!(ran.mark_passes, occupy.mark_passes); + assert_eq!(ran.node_slot_visits, occupy.node_slot_visits); + assert_eq!(ran.parked_root_writes, 0); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert_eq!(ran.trace.peeks.len(), 1, "fresh was not built"); + assert_eq!( + text_value(&ran.trace, 1.0), + "table", + "weak item still present" + ); + assert!(ran.held_alive.unwrap_or(false)); + assert!(ran.trace.steps.is_empty(), "no scan step ran"); +} + +/// The short roots limit still admits the frame and an ordinary allocation. +/// Stop keeps the non-due path, so this is not the automatic refusal. +#[test] +fn stopped_tight_root_limit_still_allocates_the_empty_local() { + let source = r#" +local function witness() + local w = {} + local mt = {} + local held = {} + local scalar = 7 + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + peek(held) + note(1, collectgarbage("stop")) + note(20, scalar) + meter(30) + occupy(1) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(5, peek(fresh)) + note(21, scalar) + local spare = {} + bit(9, peek(spare)) + return 1 +end +witness() +return 1 +"#; + let ran = run_auto_roots(source, ROOT_CAPACITY_PLANNED - 1); + assert_eq!(ran.stop, Stop::Halted, "{ran:?}"); + let occupy = occupy_note(&ran.trace); + assert_eq!(occupy.root_slots, ROOT_CAPACITY_SLOTS, "{occupy:?}"); + assert!(occupy.root_slots > occupy.live_roots, "{occupy:?}"); + assert_eq!(note_value(&ran.trace, 20.0), 7.0); + assert!( + ran.plan.is_none(), + "stop is not due, so no automatic batch is decoded" + ); + assert!( + bit_value(&ran.trace, 5.0), + "fresh allocated without a collection" + ); + assert!(bit_value(&ran.trace, 9.0)); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!(note_value(&ran.trace, 21.0), 7.0); + assert_eq!(ran.collects, 0); + assert_eq!(ran.collections, 0); + assert!(!ran.tail); + assert!(ran.mark_phase.is_none()); + assert!(ran.idle); + assert!(!ran.meter.requested); + assert_eq!(ran.budgets, ROOT_STEP_BUDGETS.to_vec()); + assert_eq!(ran.trace.peeks.len(), 3); +} From 092fd1bf19ca30a4ef49ba980b6c293b6286d0d6 Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 06:14:36 +0800 Subject: [PATCH 142/225] Replay the reviewed new number-key barrier onto the capacity union Apply the reviewed new-number barrier using its own parent as the merge base. The destination barrier blobs match that parent, so both files take the donor blobs in order. No extra conflict is resolved here. This replay adds no cross-source test, Release allocation, new object key, gap refill, production wiring, or cleanup. --- src/frontends/lua/heap/table.rs | 6 +- tests/luajit_heap_runtime/parked_mark.rs | 417 +++++++++++++++++++++++ 2 files changed, 420 insertions(+), 3 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 4dadc08..14f34a6 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -1727,10 +1727,10 @@ impl LuaHeap { if self.occupied_edges >= self.limits.edges && !self.reclaim_cursor_gap() { return Err(HeapError::EdgeCapacity); } - // A parked mark may have already scanned this owner. Only a new - // ordinary string field with a table value needs this insertion barrier. + // A parked mark may have already scanned this owner. A new ordinary + // string or number field with a table value needs this insertion barrier. let barrier = if self.mark.is_some() - && matches!(key, EdgeKey::Utf8(_)) + && matches!(key, EdgeKey::Utf8(_) | EdgeKey::Number(_)) && let EdgeValue::Table { slot, generation } = &value { Some((*slot, *generation)) diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index f3473e2..4768685 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -918,6 +918,423 @@ fn gray_existing_number_omitted_replacement_keeps_the_original_string() { existing_number_replacement_after_owner_scan(ExistingNumberWrite::Omitted); } +#[derive(Clone, Copy)] +enum NewNumberWrite { + Strong, + WeakValue, + Omitted, +} + +/// Fresh numeric key. `-0` is the write spelling and `+0` is the lookup. +/// `EdgeKey::number` stores both as the zero bits, so a hit would be a +/// replacement. The independent string `"0"` stays a text record. +const NEW_NUMBER_WRITE: f64 = -0.0; +const NEW_NUMBER_READ: f64 = 0.0; +const NUMBER_TEXT_KEY: &str = "0"; +const NUMBER_TEXT_VALUE: &str = "text"; + +fn number_record_indexes(heap: &LuaHeap, owner: u32) -> Vec { + let mut found = Vec::new(); + let mut cursor = heap.slots[owner as usize].edge_head; + while let Some(index) = cursor { + let record = &heap.edge_slots[index as usize]; + cursor = record.next; + if record + .edge + .as_ref() + .is_some_and(|edge| matches!(edge.key, super::EdgeKey::Number(_))) + { + found.push(index); + } + } + found +} + +fn assert_fresh_number_key(heap: &LuaHeap, owner: u32) { + let written = super::EdgeKey::number(NEW_NUMBER_WRITE); + let read = super::EdgeKey::number(NEW_NUMBER_READ); + let text = super::EdgeKey::named(NUMBER_TEXT_KEY); + assert!(NEW_NUMBER_WRITE.is_sign_negative()); + assert_eq!(NEW_NUMBER_WRITE, 0.0); + assert_ne!(NEW_NUMBER_WRITE.to_bits(), NEW_NUMBER_READ.to_bits()); + assert_eq!(written, read); + assert!(matches!(written, super::EdgeKey::Number(0))); + assert!(matches!(text, super::EdgeKey::Utf8(ref stored) if stored == NUMBER_TEXT_KEY)); + assert_ne!(written, text); + assert_eq!( + heap.find_key(owner, &written), + None, + "the numeric slot is missing before the write" + ); + assert!( + number_record_indexes(heap, owner).is_empty(), + "no number record is present before the write" + ); +} + +/// Inserts an unmatched ordinary number key after the owner has been scanned. +fn new_number_insert_after_owner_scan(write: NewNumberWrite) { + use crate::heap::{self, GuestClass, StepOutcome}; + + const CHILD: &str = "child"; + const BLOCKED_KEY: f64 = 11.0; + let retained = matches!(write, NewNumberWrite::Strong); + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits(8, 2, 8)).expect("install"); + let raw = crate::publish_raw(&mut host); + let target = crate::table_ref(&host, raw); + let (owner, sentinel, child, stale, carrier) = heap::with_heap(&mut host, |heap| { + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let child = heap.alloc()?; + let unrelated = heap.alloc()?; // Forces a real published tail in all arms. + let stale = heap.alloc()?; + heap.rollback(stale)?; + if matches!(write, NewNumberWrite::WeakValue) { + let meta = heap.alloc()?; + heap.set_mode_scalar(meta, Value::string("v"))?; + heap.set_metatable(owner, Some(meta))?; + } + let frame = heap.enter_roots(2)?; + // The Gray stack pops the owner first, then the sentinel. + heap.write_root(frame, 0, sentinel)?; + heap.write_root(frame, 1, owner)?; + heap.set_named_scalar(owner, NUMBER_TEXT_KEY, Value::string(NUMBER_TEXT_VALUE))?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + heap.set_named_edge(target, CHILD, unrelated)?; + heap.set_named_edge(target, CHILD, child)?; + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + assert_eq!( + heap.named_value(owner, NUMBER_TEXT_KEY)?, + Value::string(NUMBER_TEXT_VALUE) + ); + assert_eq!(heap.number_value(owner, NEW_NUMBER_READ)?, Value::Null); + assert_fresh_number_key(heap, owner.slot()); + Ok((owner, sentinel, child, stale, heap.issue_carrier(target)?)) + }) + .expect("graph"); + heap::open_fixed_step(&mut host).expect("start a saved mark"); + heap::with_heap(&mut host, |heap| { + let (_, text_record) = heap + .locate_named(owner.slot(), NUMBER_TEXT_KEY) + .expect("text field"); + let (_, sentinel_record) = heap + .locate_named(sentinel.slot(), "pending") + .expect("sentinel field"); + let mut parked = ParkedMark::resume(heap).expect("resume saved mark"); + pause_at(&mut parked, owner.slot(), text_record); + let before_owner_edge = parked.meter().outgoing_edge_checks; + let pending = pause_at(&mut parked, sentinel.slot(), sentinel_record); + assert_eq!(pending.owner, sentinel.slot()); + assert!( + parked.meter().outgoing_edge_checks > before_owner_edge, + "the owner scan charged its text edge" + ); + assert!(parked.marked(owner), "the scanned owner is already marked"); + assert!( + !parked.marked(target) && !parked.marked(child), + "the new target has no supplemental root" + ); + let before = parked.meter(); + parked.park()?; + assert_fresh_number_key(heap, owner.slot()); + let edges_before = (heap.stats().live_edges, heap.stats().edge_slots); + if !matches!(write, NewNumberWrite::Omitted) { + heap.set_number_edge(owner, NEW_NUMBER_WRITE, target)?; + assert_eq!(heap.number_value(owner, NEW_NUMBER_READ)?, carrier); + assert_eq!( + (heap.stats().live_edges, heap.stats().edge_slots), + (edges_before.0 + 1, edges_before.1 + 1), + "the new number key adds one record" + ); + let indexes = number_record_indexes(heap, owner.slot()); + assert_eq!(indexes.len(), 1, "the same number key has one record"); + let index = indexes[0]; + assert_eq!( + heap.find_key(owner.slot(), &super::EdgeKey::number(NEW_NUMBER_READ)), + Some(index) + ); + assert_eq!( + heap.find_key(owner.slot(), &super::EdgeKey::number(NEW_NUMBER_WRITE)), + Some(index) + ); + let stored = heap.edge_slots[index as usize] + .edge + .as_ref() + .expect("inserted number record"); + assert!(matches!(stored.key, super::EdgeKey::Number(0))); + assert!(!stored.value.is_cursor_gap()); + assert!(matches!( + stored.value, + super::EdgeValue::Table { slot, generation } + if slot == target.slot() && generation == target.generation() + )); + } else { + assert_eq!( + (heap.stats().live_edges, heap.stats().edge_slots), + edges_before, + "omission adds no record" + ); + assert_fresh_number_key(heap, owner.slot()); + } + assert_eq!( + heap.named_value(owner, NUMBER_TEXT_KEY)?, + Value::string(NUMBER_TEXT_VALUE), + "the independent string key keeps its original value" + ); + let parked = ParkedMark::resume(heap).expect("write kept the saved mark"); + assert_eq!(parked.phase_name(), "gray"); + let cursor = parked.pending().expect("sentinel still pending"); + assert_eq!( + (cursor.owner, cursor.cursor), + (pending.owner, pending.cursor), + "the pending scan cursor is unchanged" + ); + assert!( + !parked.marked(child), + "the write must not scan the child edge" + ); + assert_eq!( + parked.marked(target), + retained, + "only a strong new number key enters the gray queue immediately" + ); + let after = parked.meter(); + assert_write_did_not_scan(&before, &after); + assert_eq!(after.parked_edge_writes, before.parked_edge_writes); + assert_eq!( + after.parked_barrier_marks - before.parked_barrier_marks, + u64::from(retained) + ); + assert_eq!( + after.scratch.work_pushed - before.scratch.work_pushed, + u64::from(retained) + ); + assert_eq!( + after.node_slot_visits - before.node_slot_visits, + u64::from(retained) * 2 + ); + assert_eq!(after.metatable_edge_checks, before.metatable_edge_checks); + assert_eq!(after.weak_mode_lookups, before.weak_mode_lookups); + assert_eq!(after.weak_mode_slot_checks, before.weak_mode_slot_checks); + parked.park()?; + Ok(()) + }) + .expect("fresh number insert while Gray is parked"); + + let published = heap::step_fixed_frames(&mut host, 128).expect("publish saved mark"); + assert!( + matches!(published, StepOutcome::Published { .. }), + "{published:?}" + ); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + heap::with_heap(&mut host, |heap| { + // NaN and a stale handle stay ahead of the sweep refusal. + assert_eq!( + heap.set_number_edge(owner, f64::NAN, sentinel), + Err(HeapError::NanIndex) + ); + assert_eq!( + heap.clear_number_edge(owner, f64::NAN), + Err(HeapError::NanIndex) + ); + assert_eq!( + heap.set_number_edge(stale, NEW_NUMBER_WRITE, sentinel), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.set_number_edge(owner, NEW_NUMBER_WRITE, stale), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.set_number_edge(owner, BLOCKED_KEY, sentinel), + Err(HeapError::SweepPending) + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::number(BLOCKED_KEY)) + .is_none() + ); + assert_eq!( + heap.named_value(owner, NUMBER_TEXT_KEY)?, + Value::string(NUMBER_TEXT_VALUE) + ); + if matches!(write, NewNumberWrite::WeakValue) { + assert_eq!( + heap.number_value(owner, NEW_NUMBER_READ)?, + Value::Null, + "a weak number insert publishes nil" + ); + let indexes = number_record_indexes(heap, owner.slot()); + assert_eq!(indexes.len(), 1, "a weak insert leaves one cleared cursor"); + let stored = heap.edge_slots[indexes[0] as usize] + .edge + .as_ref() + .expect("retained gap"); + assert!(stored.value.is_cursor_gap()); + assert!(matches!(stored.key, super::EdgeKey::Number(0))); + } + if matches!(write, NewNumberWrite::Omitted) { + assert_eq!(heap.number_value(owner, NEW_NUMBER_READ)?, Value::Null); + assert!(number_record_indexes(heap, owner.slot()).is_empty()); + } + if matches!(write, NewNumberWrite::Strong) { + assert_eq!(heap.number_value(owner, NEW_NUMBER_READ)?, carrier); + } + Ok(()) + }) + .expect("read during publication"); + let done = heap::step_fixed_frames(&mut host, 128).expect("finish saved tail"); + assert!(matches!(done, StepOutcome::Completed(_)), "{done:?}"); + assert!(heap::fixed_step_idle(&mut host).expect("idle")); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.alive(target), + retained, + "a fresh strong number key on a scanned owner must keep its target alive" + ); + assert_eq!( + heap.alive(child), + retained, + "the child is reached only by the continued scan" + ); + assert_eq!(heap.stats().collections, 1); + assert_eq!(heap.scan_meter().mark_passes, 1); + assert_eq!( + heap.named_value(owner, NUMBER_TEXT_KEY)?, + Value::string(NUMBER_TEXT_VALUE) + ); + if matches!(write, NewNumberWrite::Omitted) { + assert_eq!(heap.number_value(owner, NEW_NUMBER_READ)?, Value::Null); + } + if retained { + let value = heap.number_value(owner, NEW_NUMBER_READ)?; + assert_eq!(value, carrier); + assert_eq!(heap.guest_class(&value), GuestClass::Table(target)); + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + heap.clear_number_edge(owner, NEW_NUMBER_READ)?; + } + Ok(()) + }) + .expect("same-cycle reachability"); + if retained { + heap::collect(&mut host).expect("next collection after removing the only strong edge"); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(target) && !heap.alive(child)); + assert_eq!(heap.stats().collections, 2); + Ok(()) + }) + .expect("later reclamation"); + } + }); +} + +#[test] +fn gray_new_number_strong_insert_keeps_target_and_descendant() { + new_number_insert_after_owner_scan(NewNumberWrite::Strong); +} + +#[test] +fn gray_new_number_weak_insert_clears_at_publication() { + new_number_insert_after_owner_scan(NewNumberWrite::WeakValue); +} + +#[test] +fn gray_new_number_write_omitted_leaves_target_unreachable() { + new_number_insert_after_owner_scan(NewNumberWrite::Omitted); +} + +/// Node and edge caps refuse before a parked number insert can enqueue. +#[test] +fn gray_new_number_insert_refuses_at_node_and_edge_limits() { + use crate::heap::{self, StepOutcome}; + + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits(3, 2, 2)).expect("install"); + let raw = crate::publish_raw(&mut host); + let target = crate::table_ref(&host, raw); + let (owner, sentinel) = heap::with_heap(&mut host, |heap| { + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let frame = heap.enter_roots(2)?; + heap.write_root(frame, 0, sentinel)?; + heap.write_root(frame, 1, owner)?; + heap.set_named_scalar(owner, NUMBER_TEXT_KEY, Value::string(NUMBER_TEXT_VALUE))?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + assert_eq!(heap.stats().node_slots, 3); + assert_eq!(heap.stats().edge_slots, 2); + assert_fresh_number_key(heap, owner.slot()); + Ok((owner, sentinel)) + }) + .expect("tight graph"); + heap::open_fixed_step(&mut host).expect("start a saved mark"); + heap::with_heap(&mut host, |heap| { + let (_, text_record) = heap + .locate_named(owner.slot(), NUMBER_TEXT_KEY) + .expect("text field"); + let (_, sentinel_record) = heap + .locate_named(sentinel.slot(), "pending") + .expect("sentinel field"); + let mut parked = ParkedMark::resume(heap).expect("resume saved mark"); + pause_at(&mut parked, owner.slot(), text_record); + let pending = pause_at(&mut parked, sentinel.slot(), sentinel_record); + assert!(parked.marked(owner)); + assert!(!parked.marked(target)); + let before = parked.meter(); + parked.park()?; + assert_eq!( + heap.set_number_edge(owner, f64::NAN, target), + Err(HeapError::NanIndex) + ); + assert_eq!( + heap.set_number_edge(owner, NEW_NUMBER_WRITE, target), + Err(HeapError::EdgeCapacity) + ); + assert_eq!(heap.alloc(), Err(HeapError::NodeCapacity)); + assert_fresh_number_key(heap, owner.slot()); + assert_eq!( + heap.named_value(owner, NUMBER_TEXT_KEY)?, + Value::string(NUMBER_TEXT_VALUE) + ); + let parked = ParkedMark::resume(heap).expect("refusal kept the saved mark"); + assert_eq!(parked.phase_name(), "gray"); + let cursor = parked.pending().expect("sentinel still pending"); + assert_eq!( + (cursor.owner, cursor.cursor), + (pending.owner, pending.cursor) + ); + assert!(!parked.marked(target), "a refused insert does not enqueue"); + let after = parked.meter(); + assert_write_did_not_scan(&before, &after); + assert_eq!(after.parked_barrier_marks, before.parked_barrier_marks); + assert_eq!(after.scratch.work_pushed, before.scratch.work_pushed); + assert_eq!(after.metatable_edge_checks, before.metatable_edge_checks); + assert_eq!(after.weak_mode_lookups, before.weak_mode_lookups); + assert_eq!(after.weak_mode_slot_checks, before.weak_mode_slot_checks); + parked.park()?; + Ok(()) + }) + .expect("capacity refusal while Gray is parked"); + let published = heap::step_fixed_frames(&mut host, 128).expect("publish"); + assert!(matches!(published, StepOutcome::Published { .. })); + let done = heap::step_fixed_frames(&mut host, 128).expect("finish"); + assert!(matches!(done, StepOutcome::Completed(_)), "{done:?}"); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(target), "the refused target is collected"); + assert!(heap.alive(owner)); + assert_eq!( + heap.named_value(owner, NUMBER_TEXT_KEY)?, + Value::string(NUMBER_TEXT_VALUE) + ); + assert!(number_record_indexes(heap, owner.slot()).is_empty()); + assert_eq!(heap.stats().collections, 1); + Ok(()) + }) + .expect("refused target did not survive"); + }); +} + #[test] fn tail_slot_reuse_does_not_keep_the_new_target() { let mut heap = LuaHeap::new(limits(8, 2, 8)); From 599f16377c728708f2aafe8a9e1b207ce520043a Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 06:14:37 +0800 Subject: [PATCH 143/225] Replay the reviewed existing object-key barrier onto the new-number union Apply the reviewed object-key barrier using its own parent as the merge base. Both barrier files take that donor's blobs. The net six files stay mode 100644. This replay adds no cross-source test, Release allocation, new object key, gap refill, production wiring, or cleanup. --- src/frontends/lua/heap/table.rs | 11 +- tests/luajit_heap_runtime/parked_mark.rs | 444 +++++++++++++++++++++++ 2 files changed, 452 insertions(+), 3 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 14f34a6..44fb328 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2895,9 +2895,10 @@ fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { matches!(key, EdgeKey::Object { slot: key_slot, .. } if *key_slot == slot) } -/// Ordinary non-gap field, UTF-8, or number key whose new value is a table. -/// Reserved fields, object keys, gaps, and non-table values stay out of the -/// gray queue. +/// Ordinary non-gap field, UTF-8, number, or table-object key whose new value +/// is a table. Reserved fields, closure and upvalue object keys, gaps, and +/// non-table values stay out of the gray queue. The table-object key itself +/// is not recolored; only the new table value is offered to the barrier. fn replaced_table_target(key: &EdgeKey, old_gap: bool, value: &EdgeValue) -> Option<(u32, u32)> { if old_gap { return None; @@ -2905,6 +2906,10 @@ fn replaced_table_target(key: &EdgeKey, old_gap: bool, value: &EdgeValue) -> Opt let ordinary = match key { EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, EdgeKey::Field(field) => *field != LuaHeap::MODE_FIELD && *field != CELL_EDGE, + EdgeKey::Object { + kind: HandleKind::Table, + .. + } => true, EdgeKey::Object { .. } => false, }; if !ordinary { diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index 4768685..8c721f5 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -918,6 +918,450 @@ fn gray_existing_number_omitted_replacement_keeps_the_original_string() { existing_number_replacement_after_owner_scan(ExistingNumberWrite::Omitted); } +#[derive(Clone, Copy)] +enum ExistingObjectWrite { + Strong, + WeakValue, + /// Key mode `k`. The value stays strong. The key has its own root. + WeakKey, + Omitted, +} + +const ORIGINAL_OBJECT_SCALAR: &str = "原值"; +const OBJECT_SHAPE: &str = "key"; + +fn object_write_retains(write: ExistingObjectWrite) -> bool { + matches!( + write, + ExistingObjectWrite::Strong | ExistingObjectWrite::WeakKey + ) +} + +/// Replaces an already scanned table-object record in place. +/// +/// The record is built with `set_object_scalar`, not a gap and not a new key. +/// The key and a same-shape lookalike are both issued and independently rooted. +/// An unmarked weak key is outside this slice. +fn existing_object_replacement_after_owner_scan(write: ExistingObjectWrite) { + use crate::heap::{self, GuestClass, StepOutcome}; + + const CHILD: &str = "child"; + let retained = object_write_retains(write); + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits(16, 8, 16)).expect("install"); + let raw = crate::publish_raw(&mut host); + let target = crate::table_ref(&host, raw); + let (owner, sentinel, child, stale, key, other, closure, frame, meta, carrier) = + heap::with_heap(&mut host, |heap| { + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let child = heap.alloc()?; + let unrelated = heap.alloc()?; + let stale = heap.alloc()?; + heap.rollback(stale)?; + let key = heap.alloc()?; + let other = heap.alloc()?; + let closure = heap.alloc_closure()?; + let meta = match write { + ExistingObjectWrite::WeakValue | ExistingObjectWrite::WeakKey => { + let meta = heap.alloc()?; + let mode = match write { + ExistingObjectWrite::WeakValue => "v", + ExistingObjectWrite::WeakKey => "k", + ExistingObjectWrite::Strong | ExistingObjectWrite::Omitted => { + unreachable!("only the weak arms store a mode") + } + }; + heap.set_mode_scalar(meta, Value::string(mode))?; + heap.set_metatable(owner, Some(meta))?; + Some(meta) + } + ExistingObjectWrite::Strong | ExistingObjectWrite::Omitted => None, + }; + let frame = heap.enter_roots(5)?; + // Pushed in order, popped in reverse. The owner is scanned + // before the sentinel. The key is already a root. + heap.write_root(frame, 0, sentinel)?; + heap.write_root(frame, 1, owner)?; + heap.write_root(frame, 2, key)?; + heap.write_root(frame, 3, other)?; + heap.write_closure_root(frame, 4, closure)?; + heap.set_named_scalar(key, "tag", Value::string(OBJECT_SHAPE))?; + heap.set_named_scalar(other, "tag", Value::string(OBJECT_SHAPE))?; + heap.set_object_scalar(owner, key, Value::string(ORIGINAL_OBJECT_SCALAR))?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + heap.set_named_edge(target, CHILD, unrelated)?; + heap.set_named_edge(target, CHILD, child)?; + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + assert_eq!( + heap.named_value(key, "tag")?, + heap.named_value(other, "tag")? + ); + assert_ne!(key, other); + assert_eq!( + heap.object_value(owner, key)?, + Value::string(ORIGINAL_OBJECT_SCALAR) + ); + assert_eq!(heap.object_value(owner, other)?, Value::Null); + let carrier = heap.issue_carrier(target)?; + let key_carrier = heap.issue_carrier(key)?; + let other_carrier = heap.issue_carrier(other)?; + assert_eq!(heap.guest_class(&key_carrier), GuestClass::Table(key)); + assert_eq!(heap.guest_class(&other_carrier), GuestClass::Table(other)); + assert_ne!(key_carrier, other_carrier); + Ok(( + owner, sentinel, child, stale, key, other, closure, frame, meta, carrier, + )) + }) + .expect("graph"); + heap::open_fixed_step(&mut host).expect("start a saved mark"); + let old_record = heap::with_heap(&mut host, |heap| { + let object_key = super::EdgeKey::object(key); + let old_record = heap + .find_key(owner.slot(), &object_key) + .expect("existing object record"); + let stored = heap.edge_slots[old_record as usize] + .edge + .as_ref() + .expect("occupied object record"); + assert_eq!(&stored.key, &object_key); + assert!(matches!( + stored.key, + super::EdgeKey::Object { + slot, + generation, + kind: super::HandleKind::Table, + } if slot == key.slot() && generation == key.generation() + )); + assert!(!stored.value.is_cursor_gap()); + assert!(matches!( + stored.value, + super::EdgeValue::Scalar(Value::String(_)) + )); + let (_, sentinel_record) = heap + .locate_named(sentinel.slot(), "pending") + .expect("sentinel field"); + for slot in 0..4 { + let rooted = heap.rooted_table(frame, slot)?; + assert_ne!(rooted, Some(target), "target has no fixed root"); + assert_ne!(rooted, Some(child), "child has no fixed root"); + } + let values_weak = if let Some(meta) = meta { + let stored = heap.named_value(meta, "__mode")?; + let Value::String(text) = &stored else { + panic!("stored mode is not a string: {stored:?}"); + }; + let expected = match write { + ExistingObjectWrite::WeakValue => "v", + ExistingObjectWrite::WeakKey => "k", + ExistingObjectWrite::Strong | ExistingObjectWrite::Omitted => { + unreachable!("a metatable is only stored for a weak arm") + } + }; + assert_eq!( + text.as_str(), + expected, + "the barrier reads this stored mode" + ); + text.as_bytes().contains(&b'v') + } else { + false + }; + assert_eq!( + retained, + !matches!(write, ExistingObjectWrite::Omitted) && !values_weak, + "retention follows strong values, not weak keys" + ); + let mut parked = ParkedMark::resume(heap).expect("resume saved mark"); + assert_eq!(parked.meter().parked_root_batch_accepts, 0); + pause_at(&mut parked, owner.slot(), old_record); + assert!( + parked.marked(key), + "the independent root marked the key before this record was charged" + ); + assert!(!parked.marked(target) && !parked.marked(child)); + let checks_on_record = parked.meter().outgoing_edge_checks; + let pending = pause_at(&mut parked, sentinel.slot(), sentinel_record); + assert!( + parked.meter().outgoing_edge_checks > checks_on_record, + "the owner scan charged this object record" + ); + assert_eq!(pending.owner, sentinel.slot()); + assert_eq!(pending.cursor, sentinel_record); + assert!(parked.marked(owner), "the scanned owner is already marked"); + assert!(parked.marked(key) && parked.marked(other)); + let before = parked.meter(); + parked.park()?; + let edges_before = (heap.stats().live_edges, heap.stats().edge_slots); + if !matches!(write, ExistingObjectWrite::Omitted) { + heap.set_object_edge(owner, key, target)?; + assert_eq!(heap.object_value(owner, key)?, carrier); + assert_eq!(heap.guest_class(&carrier), GuestClass::Table(target)); + assert_eq!(heap.object_value(owner, other)?, Value::Null); + } else { + assert_eq!( + heap.object_value(owner, key)?, + Value::string(ORIGINAL_OBJECT_SCALAR) + ); + } + assert_eq!( + heap.find_key(owner.slot(), &object_key), + Some(old_record), + "the old object record index is unchanged" + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(other)) + .is_none() + ); + assert_eq!( + (heap.stats().live_edges, heap.stats().edge_slots), + edges_before, + "the write does not change the edge count" + ); + let stored = heap.edge_slots[old_record as usize] + .edge + .as_ref() + .expect("replaced record"); + assert!(matches!( + stored.key, + super::EdgeKey::Object { + slot, + generation, + kind: super::HandleKind::Table, + } if slot == key.slot() && generation == key.generation() + )); + if !matches!(write, ExistingObjectWrite::Omitted) { + assert!(matches!( + stored.value, + super::EdgeValue::Table { slot, generation } + if slot == target.slot() && generation == target.generation() + )); + } + let parked = ParkedMark::resume(heap).expect("write kept the saved mark"); + assert_eq!(parked.phase_name(), "gray"); + let cursor = parked.pending().expect("sentinel still pending"); + assert_eq!( + (cursor.owner, cursor.cursor), + (pending.owner, pending.cursor), + "the pending scan cursor is unchanged" + ); + assert!( + parked.marked(key), + "the write must not recolor the existing object key" + ); + assert!( + !parked.marked(child), + "the write must not scan the child edge" + ); + assert_eq!( + parked.marked(target), + retained, + "only a strong object-key replacement enters the gray queue immediately" + ); + let after = parked.meter(); + assert_write_did_not_scan(&before, &after); + assert_eq!(after.parked_edge_writes, before.parked_edge_writes); + assert_eq!( + after.parked_root_batch_accepts, + before.parked_root_batch_accepts + ); + assert_eq!( + after.parked_barrier_marks - before.parked_barrier_marks, + u64::from(retained) + ); + assert_eq!( + after.scratch.work_pushed - before.scratch.work_pushed, + u64::from(retained) + ); + assert_eq!( + after.node_slot_visits - before.node_slot_visits, + u64::from(retained) * 2, + "the barrier follows the table value, not the object key" + ); + assert_eq!(after.metatable_edge_checks, before.metatable_edge_checks); + assert_eq!(after.weak_mode_lookups, before.weak_mode_lookups); + parked.park()?; + Ok(old_record) + }) + .expect("in-place object replacement while Gray is parked"); + + let published = heap::step_fixed_frames(&mut host, 128).expect("publish saved mark"); + assert!( + matches!(published, StepOutcome::Published { .. }), + "{published:?}" + ); + assert_eq!(heap::stats(&mut host).expect("stats").collections, 0); + heap::with_heap(&mut host, |heap| { + let before_refuse = heap.object_value(owner, key)?; + let forged = + super::TableRef::table(heap.domain(), closure.slot(), closure.generation()); + assert!( + heap.closure_alive(closure), + "the closure key control is still live" + ); + assert_eq!( + heap.set_object_edge(stale, forged, sentinel), + Err(HeapError::WrongKind), + "object-key kind is checked before the owner and the sweep tail" + ); + assert_eq!( + heap.set_object_edge(owner, stale, sentinel), + Err(HeapError::StaleHandle), + "a stale object key is refused before the sweep tail" + ); + assert_eq!( + heap.set_object_edge(stale, key, sentinel), + Err(HeapError::StaleHandle), + "the owner is checked after the key and before the sweep tail" + ); + assert_eq!( + heap.set_object_edge(owner, key, stale), + Err(HeapError::StaleHandle), + "the value is checked after the key and owner" + ); + assert_eq!( + heap.set_object_edge(owner, key, forged), + Err(HeapError::WrongKind), + "a closure-shaped value is not a table edge" + ); + assert_eq!( + heap.set_object_edge(owner, key, sentinel), + Err(HeapError::SweepPending), + "a live in-place object replacement still stops at the saved tail" + ); + assert_eq!( + heap.set_object_edge(owner, other, sentinel), + Err(HeapError::SweepPending) + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(other)) + .is_none() + ); + assert_eq!( + heap.clear_object_edge(stale, key), + Err(HeapError::StaleHandle) + ); + assert_eq!( + heap.clear_object_edge(owner, forged), + Err(HeapError::WrongKind), + "clear checks the owner, then the key kind" + ); + assert_eq!( + heap.clear_object_edge(owner, key), + Err(HeapError::SweepPending) + ); + assert_eq!(heap.object_value(owner, key)?, before_refuse); + assert_eq!( + heap.find_key(owner.slot(), &super::EdgeKey::object(key)), + Some(old_record) + ); + if matches!(write, ExistingObjectWrite::WeakValue) { + assert_eq!( + heap.object_value(owner, key)?, + Value::Null, + "a weak object replacement publishes nil" + ); + let index = heap + .find_key(owner.slot(), &super::EdgeKey::object(key)) + .expect("a weak-value replacement leaves the cleared cursor"); + assert_eq!(index, old_record); + let stored = heap.edge_slots[index as usize] + .edge + .as_ref() + .expect("retained gap"); + assert!(stored.value.is_cursor_gap()); + assert!(matches!( + stored.key, + super::EdgeKey::Object { + slot, + generation, + kind: super::HandleKind::Table, + } if slot == key.slot() && generation == key.generation() + )); + } + if matches!(write, ExistingObjectWrite::Omitted) { + assert_eq!( + heap.object_value(owner, key)?, + Value::string(ORIGINAL_OBJECT_SCALAR) + ); + } + if retained { + assert_eq!(heap.object_value(owner, key)?, carrier); + assert_eq!(heap.guest_class(&carrier), GuestClass::Table(target)); + } + assert_eq!(heap.object_value(owner, other)?, Value::Null); + Ok(()) + }) + .expect("read during publication"); + let done = heap::step_fixed_frames(&mut host, 128).expect("finish saved tail"); + assert!(matches!(done, StepOutcome::Completed(_)), "{done:?}"); + assert!(heap::fixed_step_idle(&mut host).expect("idle")); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.alive(target), + retained, + "an in-place strong object replacement on a scanned owner must keep its target alive" + ); + assert_eq!( + heap.alive(child), + retained, + "the child is reached only by the continued scan" + ); + assert!(heap.alive(key) && heap.alive(other)); + assert_eq!(heap.stats().collections, 1); + assert_eq!(heap.scan_meter().mark_passes, 1); + if matches!(write, ExistingObjectWrite::Omitted) { + assert_eq!( + heap.object_value(owner, key)?, + Value::string(ORIGINAL_OBJECT_SCALAR), + "an omitted object replacement keeps the original string" + ); + } + if retained { + let value = heap.object_value(owner, key)?; + assert_eq!(value, carrier); + assert_eq!(heap.guest_class(&value), GuestClass::Table(target)); + assert_eq!(heap.named_edge(target, CHILD)?, Some(child)); + heap.clear_object_edge(owner, key)?; + } + Ok(()) + }) + .expect("same-cycle reachability"); + if retained { + heap::collect(&mut host).expect("next collection after removing the only strong edge"); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(target) && !heap.alive(child)); + assert!(heap.alive(key) && heap.alive(other)); + assert_eq!(heap.object_value(owner, key)?, Value::Null); + assert_eq!(heap.stats().collections, 2); + Ok(()) + }) + .expect("later reclamation"); + } + }); +} + +#[test] +fn gray_existing_object_strong_replacement_keeps_the_new_graph() { + existing_object_replacement_after_owner_scan(ExistingObjectWrite::Strong); +} + +#[test] +fn gray_existing_object_weak_replacement_clears_at_publication() { + existing_object_replacement_after_owner_scan(ExistingObjectWrite::WeakValue); +} + +#[test] +fn gray_existing_object_weak_key_strong_value_keeps_the_new_graph() { + existing_object_replacement_after_owner_scan(ExistingObjectWrite::WeakKey); +} + +#[test] +fn gray_existing_object_omitted_replacement_keeps_the_original_string() { + existing_object_replacement_after_owner_scan(ExistingObjectWrite::Omitted); +} + #[derive(Clone, Copy)] enum NewNumberWrite { Strong, From f2522a7c3512e4f17ede02f6391ba856a17ebffa Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 07:53:50 +0800 Subject: [PATCH 144/225] Replay the reviewed new table-object key barrier onto the root union Apply 4f37ba9 using its own parent b05684d as the merge base. table.rs and parked_mark.rs already match that parent, so those paths take the donor blobs. mark.rs keeps the destination root-batch helpers and the donor barrier_new_table_key, each once. This replay adds no production wiring, Release allocation, gap refill, or same-program linkage. --- src/frontends/lua/heap/table.rs | 42 ++ src/frontends/lua/heap/table/mark.rs | 58 +++ tests/luajit_heap_runtime/parked_mark.rs | 573 +++++++++++++++++++++++ 3 files changed, 673 insertions(+) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 44fb328..3c6da08 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -297,6 +297,35 @@ fn stored_len(len: usize) -> u64 { len as u64 } +/// A new table-object key, with a table value when the value is itself a table. +/// A string value keeps `value` empty so the barrier follows only the key. +struct NewTableKeyInsert { + key_slot: u32, + key_generation: u32, + value: Option<(u32, u32)>, +} + +fn new_table_key_insert(key: &EdgeKey, value: &EdgeValue) -> Option { + let EdgeKey::Object { + slot, + generation, + kind: HandleKind::Table, + } = key + else { + return None; + }; + let value = match value { + EdgeValue::Table { slot, generation } => Some((*slot, *generation)), + EdgeValue::Scalar(Value::String(_)) => None, + _ => return None, + }; + Some(NewTableKeyInsert { + key_slot: *slot, + key_generation: *generation, + value, + }) +} + fn key_payload(key: &EdgeKey) -> u64 { match key { EdgeKey::Utf8(text) => stored_len(text.len()), @@ -1737,6 +1766,11 @@ impl LuaHeap { } else { None }; + let table_key = if self.mark.is_some() { + new_table_key_insert(&key, &value) + } else { + None + }; let added = key_payload(&key) + value_payload(&value); let index = self.take_edge_slot(); self.edge_slots[index as usize].edge = Some(Edge { key, value }); @@ -1749,6 +1783,14 @@ impl LuaHeap { if let Some((slot, generation)) = barrier { self.barrier_strong_field(from_slot, slot, generation); } + if let Some(insert) = table_key { + self.barrier_new_table_key( + from_slot, + insert.key_slot, + insert.key_generation, + insert.value, + ); + } Ok(()) } diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs index 9f54e0e..0d6c79e 100644 --- a/src/frontends/lua/heap/table/mark.rs +++ b/src/frontends/lua/heap/table/mark.rs @@ -1084,6 +1084,29 @@ fn cached_values_weak(heap: &LuaHeap, state: &MarkState, owner: u32) -> bool { .is_some_and(|mode| mode.values) } +/// Both weak bits from the same reset-time cache. No metatable follow and +/// no scan counter. The values-only fast path above is unchanged. +fn cached_owner_mode(heap: &LuaHeap, state: &MarkState, owner: u32) -> WeakMode { + if heap.metatable_edges == 0 { + return WeakMode::default(); + } + let Some(stored) = heap.slots.get(owner as usize) else { + return WeakMode::default(); + }; + if stored.kind != HandleKind::Table { + return WeakMode::default(); + } + let Some((meta_slot, _)) = stored.metatable else { + return WeakMode::default(); + }; + state + .modes + .as_ref() + .and_then(|modes| modes.get(meta_slot as usize)) + .copied() + .unwrap_or_default() +} + /// Same visits as the old target follow. True when the slot matches, even /// if it was already marked. Only a newly marked slot joins the gray stack. fn follow_one( @@ -1170,6 +1193,41 @@ impl LuaHeap { self.mark = Some(state); } + /// Enqueues a newly inserted table-object key, and a strong table value. + /// + /// A string value is not a table node. An owner that is not yet marked is + /// left for the continued scan. Successors stay on the gray queue. This + /// does not read a metatable or move the pending cursor. + pub(super) fn barrier_new_table_key( + &mut self, + owner: u32, + key_slot: u32, + key_generation: u32, + value: Option<(u32, u32)>, + ) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.mutation_open() && discovered_table(self, owner) { + let mode = cached_owner_mode(self, &state, owner); + if !mode.keys { + enqueue_barrier_target( + self, + &mut state, + key_slot, + key_generation, + HandleKind::Table, + ); + } + if !mode.values + && let Some((slot, generation)) = value + { + enqueue_barrier_target(self, &mut state, slot, generation, HandleKind::Table); + } + } + self.mark = Some(state); + } + /// Advances a parked gray cursor when `unlink_at` removes its record. /// One field compare. No chain, root, or slot walk. pub(super) fn repair_parked_cursor(&mut self, owner: u32, index: u32, next: Option) { diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index 8c721f5..ef521ec 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -3377,3 +3377,576 @@ fn raw_set_edge_on_an_unmarked_owner_waits_for_normal_discovery() { assert_eq!(heap.scan.parked_edge_writes, 0); assert_eq!(heap.scan.mark_passes, 1); } + +/// New table-object key inserted into an already scanned owner. +/// +/// `midcycle-existing-object-key` is an old record and is not this slice. +/// LuaJIT `evidence/lua52-gc-step/midcycle-reference-publication.lua` key/omit +/// is only the external scalar-payload control for a new object key. +enum NewTableKeyArm { + Strong, + WeakValue, + WeakKey, + WeakBoth, + StringValue, + SameTarget, + Omitted, +} + +#[test] +fn gray_new_table_key_strong_retains_both_ends() { + exercise_new_table_key(NewTableKeyArm::Strong); +} + +#[test] +fn gray_new_table_key_weak_values_follow_key_only() { + exercise_new_table_key(NewTableKeyArm::WeakValue); +} + +#[test] +fn gray_new_table_key_weak_keys_follow_value_only() { + exercise_new_table_key(NewTableKeyArm::WeakKey); +} + +#[test] +fn gray_new_table_key_weak_both_keeps_physical_rules() { + exercise_new_table_key(NewTableKeyArm::WeakBoth); +} + +#[test] +fn gray_new_table_key_string_value_follows_key_only() { + exercise_new_table_key(NewTableKeyArm::StringValue); +} + +#[test] +fn gray_new_table_key_same_target_pushes_once() { + exercise_new_table_key(NewTableKeyArm::SameTarget); +} + +#[test] +fn gray_new_table_key_omitted_collects_unmarked() { + exercise_new_table_key(NewTableKeyArm::Omitted); +} + +fn exercise_new_table_key(arm: NewTableKeyArm) { + let mode = match arm { + NewTableKeyArm::WeakValue => Some("v"), + NewTableKeyArm::WeakKey => Some("k"), + NewTableKeyArm::WeakBoth => Some("kv"), + NewTableKeyArm::Strong + | NewTableKeyArm::StringValue + | NewTableKeyArm::SameTarget + | NewTableKeyArm::Omitted => None, + }; + let pin_key = matches!(arm, NewTableKeyArm::WeakKey); + let string_value = matches!(arm, NewTableKeyArm::StringValue); + let same_target = matches!(arm, NewTableKeyArm::SameTarget); + let omitted = matches!(arm, NewTableKeyArm::Omitted); + crate::with_idle_vm(|vm| { + use crate::heap::{self, GuestClass, StepOutcome}; + + let mut host = vm.host_context(); + heap::install(&mut host, limits(16, 8, 16)).expect("install"); + let planted = heap::with_heap(&mut host, |heap| { + let prior = heap.alloc()?; + let prior_slot = prior.slot(); + let prior_generation = prior.generation(); + heap.rollback(prior)?; + let key = heap.alloc()?; + assert_eq!( + key.slot(), + prior_slot, + "the new key reuses the released slot" + ); + assert_ne!( + key.generation(), + prior_generation, + "the new key is a different generation" + ); + let lookalike = heap.alloc()?; + assert_ne!( + lookalike.slot(), + key.slot(), + "lookalike is an independent key" + ); + let key_child = heap.alloc()?; + let target = if string_value || same_target { + None + } else { + Some(heap.alloc()?) + }; + let value_child = if target.is_some() { + Some(heap.alloc()?) + } else { + None + }; + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let closure = heap.alloc_closure()?; + let unrelated = heap.alloc()?; + heap.set_named_scalar(key, "tag", Value::string("key"))?; + heap.set_named_scalar(lookalike, "tag", Value::string("key"))?; + heap.set_named_edge(key, "next", key_child)?; + if let (Some(target), Some(child)) = (target, value_child) { + heap.set_named_edge(target, "next", child)?; + } + heap.set_named_scalar(owner, "old", Value::string("kept"))?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + if let Some(mode) = mode { + let meta = heap.alloc()?; + heap.set_mode_scalar(meta, Value::string(mode))?; + heap.set_metatable(owner, Some(meta))?; + assert_eq!(heap.named_value(meta, "__mode")?, Value::string(mode)); + } + let stale = super::TableRef::table(heap.domain(), prior_slot, prior_generation); + let key_carrier = heap.issue_carrier(key)?; + assert_eq!(heap.guest_class(&key_carrier), GuestClass::Table(key)); + let target_carrier = target.map(|table| heap.issue_carrier(table)).transpose()?; + if let (Some(table), Some(carrier)) = (target, target_carrier.as_ref()) { + assert_eq!(heap.guest_class(carrier), GuestClass::Table(table)); + } + let frame = heap.enter_roots(4)?; + heap.write_root(frame, 0, sentinel)?; + heap.write_root(frame, 1, owner)?; + heap.write_closure_root(frame, 2, closure)?; + if pin_key { + heap.write_root(frame, 3, key)?; + } + Ok(( + key, + lookalike, + key_child, + target, + value_child, + owner, + sentinel, + closure, + unrelated, + stale, + key_carrier, + target_carrier, + )) + }) + .expect("plant"); + let ( + key, + lookalike, + key_child, + target, + value_child, + owner, + sentinel, + closure, + _unrelated, + stale, + key_carrier, + target_carrier, + ) = planted; + let _ = closure; + heap::open_fixed_step(&mut host).expect("open"); + heap::with_heap(&mut host, |heap| { + let (_, old) = heap.locate_named(owner.slot(), "old").expect("old record"); + let (_, sentinel_record) = heap + .locate_named(sentinel.slot(), "pending") + .expect("pending record"); + let mut parked = ParkedMark::resume(heap).expect("resume"); + pause_at(&mut parked, owner.slot(), old); + let before_owner = parked.meter().outgoing_edge_checks; + let pending = pause_at(&mut parked, sentinel.slot(), sentinel_record); + assert!( + parked.meter().outgoing_edge_checks > before_owner, + "the owner record was not scanned before the new key" + ); + assert!( + parked.marked(owner), + "the owner color is from the scan, not the insert" + ); + if pin_key { + assert!( + parked.marked(key), + "the pinned key was marked before the insert" + ); + } else { + assert!(!parked.marked(key), "the new key starts unmarked"); + assert!( + !parked.marked(key_child), + "the key successor starts unmarked" + ); + } + if let Some(target) = target { + assert!(!parked.marked(target), "the new value starts unmarked"); + } + let before = parked.meter(); + parked.with_saved_heap(|heap| { + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(key)) + .is_none(), + "the new key has no physical record" + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(lookalike)) + .is_none(), + "the lookalike has no physical record" + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(stale)) + .is_none(), + "the previous generation has no physical record" + ); + if !omitted { + if string_value { + heap.set_object_scalar(owner, key, Value::string("标量"))?; + } else if same_target { + heap.set_object_edge(owner, key, key)?; + } else if let Some(target) = target { + heap.set_object_edge(owner, key, target)?; + } + let record = heap + .find_key(owner.slot(), &super::EdgeKey::object(key)) + .expect("inserted record"); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(lookalike)) + .is_none(), + "same shape does not alias a different generation identity" + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(stale)) + .is_none(), + "the previous generation does not alias the new key" + ); + let edge = heap.edge_slots[record as usize] + .edge + .as_ref() + .expect("occupied"); + assert_eq!(edge.key, super::EdgeKey::object(key)); + if string_value { + assert_eq!( + heap.object_value(owner, key)?, + Value::string("标量"), + "the scalar payload is stored" + ); + } else if same_target { + assert_eq!(heap.object_value(owner, key)?, key_carrier); + } else if let Some(carrier) = target_carrier.clone() { + assert_eq!(heap.object_value(owner, key)?, carrier); + } + } + Ok(()) + })?; + assert!( + same_pending(parked.pending(), Some(pending)), + "the pending cursor moved" + ); + assert_eq!( + parked.scanning_owner(), + Some(sentinel.slot()), + "the write moved the gray owner" + ); + assert_write_did_not_scan(&before, &parked.meter()); + let after = parked.meter(); + assert_eq!(after.metatable_edge_checks, before.metatable_edge_checks); + assert_eq!(after.weak_mode_lookups, before.weak_mode_lookups); + let visits = after.node_slot_visits - before.node_slot_visits; + let pushed = after.scratch.work_pushed - before.scratch.work_pushed; + let barriers = after.parked_barrier_marks - before.parked_barrier_marks; + match arm { + NewTableKeyArm::Strong => { + let target = target.expect("strong value"); + let child = value_child.expect("value successor"); + assert!(parked.marked(key), "strong key is enqueued immediately"); + assert!( + parked.marked(target), + "strong value is enqueued immediately" + ); + assert!( + !parked.marked(key_child), + "key successor waits for the continued scan" + ); + assert!( + !parked.marked(child), + "value successor waits for the continued scan" + ); + assert_eq!(visits, 4, "strong insert follows the key and the value"); + assert_eq!(pushed, 2, "strong insert pushes each unmarked end once"); + assert_eq!(barriers, 2); + } + NewTableKeyArm::WeakValue => { + assert!(parked.marked(key), "weak values still enqueue the new key"); + assert!( + !parked.marked(target.expect("weak value")), + "weak values do not enqueue the value" + ); + assert!( + !parked.marked(key_child), + "key successor waits for the continued scan" + ); + assert_eq!(visits, 2, "weak values follow only the new key"); + assert_eq!(pushed, 1); + assert_eq!(barriers, 1); + } + NewTableKeyArm::WeakKey => { + assert!(parked.marked(key), "the pinned key was already marked"); + assert!( + parked.marked(target.expect("weak-key value")), + "weak keys still enqueue the unmarked value" + ); + assert_eq!(visits, 2, "weak keys do not attempt to follow the key"); + assert_eq!(pushed, 1, "only the value is newly pushed"); + assert_eq!(barriers, 1); + } + NewTableKeyArm::WeakBoth => { + assert!(!parked.marked(key), "weak keys are not enqueued"); + assert!( + !parked.marked(target.expect("weak value")), + "weak values are not enqueued" + ); + assert_eq!(visits, 0, "kv does not follow either end"); + assert_eq!(pushed, 0); + assert_eq!(barriers, 0); + } + NewTableKeyArm::StringValue => { + assert!( + parked.marked(key), + "a string value still enqueues the new key" + ); + assert!( + !parked.marked(key_child), + "key successor waits for the continued scan" + ); + assert_eq!(visits, 2, "a string value follows only the new key"); + assert_eq!(pushed, 1); + assert_eq!(barriers, 1); + } + NewTableKeyArm::SameTarget => { + assert!( + parked.marked(key), + "the shared target is enqueued immediately" + ); + assert!( + !parked.marked(key_child), + "the successor waits for the continued scan" + ); + assert_eq!(visits, 4, "both ends are attempted"); + assert_eq!(pushed, 1, "the same target is pushed once"); + assert_eq!(barriers, 1); + } + NewTableKeyArm::Omitted => { + assert!(!parked.marked(key), "omit does not mark the key"); + assert_eq!(visits, 0); + assert_eq!(pushed, 0); + assert_eq!(barriers, 0); + } + } + parked.park().expect("park"); + Ok(()) + }) + .expect("write"); + let published = heap::step_fixed_frames(&mut host, 128).expect("publish"); + assert!( + matches!(published, StepOutcome::Published { .. }), + "{published:?}" + ); + let done = heap::step_fixed_frames(&mut host, 128).expect("finish"); + let StepOutcome::Completed(_report) = done else { + panic!("expected completion, got {done:?}"); + }; + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.named_value(owner, "old")?, + Value::string("kept"), + "the already scanned record stays" + ); + assert_eq!( + heap.named_value(sentinel, "pending")?, + Value::Bool(true), + "the sentinel record stays" + ); + assert!(!heap.alive(lookalike), "the lookalike was not rooted"); + match arm { + NewTableKeyArm::Strong => { + assert!(heap.alive(key), "new table key stays live this cycle"); + let target = target.expect("strong value"); + assert!(heap.alive(target), "new table value stays live this cycle"); + assert!(heap.alive(key_child), "key successor stays live this cycle"); + assert!( + heap.alive(value_child.expect("value successor")), + "value successor stays live this cycle" + ); + } + NewTableKeyArm::WeakValue => { + assert!( + heap.alive(key), + "weak-value new table key stays live this cycle" + ); + assert!( + !heap.alive(target.expect("weak value")), + "weak value is cleared this cycle" + ); + assert!(heap.alive(key_child), "key successor stays live this cycle"); + } + NewTableKeyArm::WeakKey => { + assert!(heap.alive(key), "pinned weak key stays live"); + assert!( + heap.alive(target.expect("weak-key value")), + "unmarked table value stays live this cycle" + ); + assert!( + heap.alive(value_child.expect("value successor")), + "value successor stays live this cycle" + ); + } + NewTableKeyArm::WeakBoth => { + assert!(!heap.alive(key), "weak key is not kept by the table"); + assert!( + !heap.alive(target.expect("weak value")), + "weak value is not kept by the table" + ); + } + NewTableKeyArm::StringValue => { + assert!(heap.alive(key), "string payload key stays live this cycle"); + assert!( + heap.alive(key_child), + "string payload key successor stays live this cycle" + ); + } + NewTableKeyArm::SameTarget => { + assert!(heap.alive(key), "same target stays live this cycle"); + assert!( + heap.alive(key_child), + "same target successor stays live this cycle" + ); + } + NewTableKeyArm::Omitted => { + assert!(!heap.alive(key), "omitted key is collected"); + assert!( + !heap.alive(target.expect("omitted value")), + "omitted value is collected" + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(key)) + .is_none(), + "omit leaves no record" + ); + } + } + if matches!( + arm, + NewTableKeyArm::Strong + | NewTableKeyArm::WeakValue + | NewTableKeyArm::StringValue + | NewTableKeyArm::SameTarget + ) { + heap.clear_object_edge(owner, key)?; + let _again = heap.collect(); + assert!(!heap.alive(key), "deleting the new edge collects the key"); + assert!( + !heap.alive(key_child), + "the key successor dies with the key" + ); + if let Some(target) = target { + assert!( + !heap.alive(target), + "deleting the new edge collects the value" + ); + } + } + Ok(()) + }) + .expect("cycle end"); + }); +} + +#[test] +fn gray_new_table_key_full_edges_refuse_without_gap() { + crate::with_idle_vm(|vm| { + use crate::heap; + + let mut host = vm.host_context(); + heap::install(&mut host, limits(4, 2, 2)).expect("install"); + let (owner, sentinel, key, target) = heap::with_heap(&mut host, |heap| { + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let key = heap.alloc()?; + let target = heap.alloc()?; + heap.set_named_scalar(owner, "old", Value::string("kept"))?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + assert!( + !owner_chain_has_gap(heap, owner.slot()), + "the capacity arm starts with no recyclable gap" + ); + let frame = heap.enter_roots(2)?; + heap.write_root(frame, 0, sentinel)?; + heap.write_root(frame, 1, owner)?; + Ok((owner, sentinel, key, target)) + }) + .expect("plant"); + heap::open_fixed_step(&mut host).expect("open"); + heap::with_heap(&mut host, |heap| { + let (_, old) = heap.locate_named(owner.slot(), "old").expect("old record"); + let (_, sentinel_record) = heap + .locate_named(sentinel.slot(), "pending") + .expect("pending record"); + let mut parked = ParkedMark::resume(heap).expect("resume"); + pause_at(&mut parked, owner.slot(), old); + let pending = pause_at(&mut parked, sentinel.slot(), sentinel_record); + let before = parked.meter(); + parked.with_saved_heap(|heap| { + assert!(!owner_chain_has_gap(heap, owner.slot())); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(key)) + .is_none() + ); + assert_eq!( + heap.set_object_edge(owner, key, target), + Err(HeapError::EdgeCapacity), + "a full chain with no gap does not insert" + ); + assert!( + heap.find_key(owner.slot(), &super::EdgeKey::object(key)) + .is_none(), + "capacity refusal leaves no record" + ); + assert_eq!(heap.alloc(), Err(HeapError::NodeCapacity)); + Ok(()) + })?; + assert!( + !parked.marked(key), + "capacity refusal does not mark the key" + ); + assert!( + !parked.marked(target), + "capacity refusal does not mark the value" + ); + assert_eq!( + parked.meter().parked_barrier_marks, + before.parked_barrier_marks + ); + assert_eq!( + parked.meter().node_slot_visits, + before.node_slot_visits, + "capacity refusal does not enqueue" + ); + assert!(same_pending(parked.pending(), Some(pending))); + assert_write_did_not_scan(&before, &parked.meter()); + parked.park().expect("park"); + Ok(()) + }) + .expect("refuse"); + }); +} + +fn owner_chain_has_gap(heap: &LuaHeap, owner: u32) -> bool { + let mut cursor = heap.slots[owner as usize].edge_head; + while let Some(index) = cursor { + let slot = &heap.edge_slots[index as usize]; + if slot + .edge + .as_ref() + .is_some_and(|edge| edge.value.is_cursor_gap()) + { + return true; + } + cursor = slot.next; + } + false +} From ccac89e5f24c99c888ca79fabc85c732d9676c4c Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 07:55:09 +0800 Subject: [PATCH 145/225] Replay the reviewed ordinary gap refill barrier onto the new table-key union Apply a2f75a9 using 4f37ba9 as the merge base. This commit keeps the gap behavior. The unused-mut removal stays in the following commit. This replay adds no production wiring, Release allocation, or same-program linkage. --- src/frontends/lua/heap/table.rs | 11 +- tests/luajit_heap_runtime/parked_mark.rs | 477 +++++++++++++++++++++++ 2 files changed, 484 insertions(+), 4 deletions(-) diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index 3c6da08..f29c9b5 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -2937,12 +2937,15 @@ fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { matches!(key, EdgeKey::Object { slot: key_slot, .. } if *key_slot == slot) } -/// Ordinary non-gap field, UTF-8, number, or table-object key whose new value -/// is a table. Reserved fields, closure and upvalue object keys, gaps, and -/// non-table values stay out of the gray queue. The table-object key itself +/// Ordinary field, UTF-8, number, or table-object key whose new value is a +/// table. Reserved fields, closure and upvalue object keys, and non-table +/// values stay out of the gray queue. A prior gap is also refused, except when +/// an ordinary UTF-8 or number key is refilled with a table: that value uses +/// the same strong-field enqueue as a live edge. The table-object key itself /// is not recolored; only the new table value is offered to the barrier. fn replaced_table_target(key: &EdgeKey, old_gap: bool, value: &EdgeValue) -> Option<(u32, u32)> { - if old_gap { + let ordinary_named_or_number = matches!(key, EdgeKey::Utf8(_) | EdgeKey::Number(_)); + if old_gap && !ordinary_named_or_number { return None; } let ordinary = match key { diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index ef521ec..e1f68b4 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -3950,3 +3950,480 @@ fn owner_chain_has_gap(heap: &LuaHeap, owner: u32) -> bool { } false } + +const GAP_TEXT: &str = "gap"; +const PEER_TEXT: &str = "peer"; +const GAP_NUMBER: f64 = -7.0; +const PEER_NUMBER: f64 = -8.0; +const NUMBER_SPELLING: &str = "-7"; +const GAP_CHILD: &str = "child"; + +#[derive(Clone, Copy)] +enum OrdinaryGapKey { + Text, + Number, +} + +#[derive(Clone, Copy)] +enum OrdinaryGapWrite { + Strong, + WeakValue, + Omitted, +} + +fn ordinary_gap_retains(write: OrdinaryGapWrite) -> bool { + matches!(write, OrdinaryGapWrite::Strong) +} + +fn locate_ordinary( + heap: &LuaHeap, + owner: TableRef, + key: OrdinaryGapKey, + peer: bool, +) -> Option { + match (key, peer) { + (OrdinaryGapKey::Text, false) => heap + .locate_named(owner.slot(), GAP_TEXT) + .map(|(_, index)| index), + (OrdinaryGapKey::Text, true) => heap + .locate_named(owner.slot(), PEER_TEXT) + .map(|(_, index)| index), + (OrdinaryGapKey::Number, false) => { + heap.find_key(owner.slot(), &super::EdgeKey::number(GAP_NUMBER)) + } + (OrdinaryGapKey::Number, true) => { + heap.find_key(owner.slot(), &super::EdgeKey::number(PEER_NUMBER)) + } + } +} + +fn read_ordinary(heap: &LuaHeap, owner: TableRef, key: OrdinaryGapKey) -> Result { + match key { + OrdinaryGapKey::Text => heap.named_value(owner, GAP_TEXT), + OrdinaryGapKey::Number => heap.number_value(owner, GAP_NUMBER), + } +} + +fn write_ordinary_table( + heap: &mut LuaHeap, + owner: TableRef, + key: OrdinaryGapKey, + target: TableRef, +) -> Result<(), HeapError> { + match key { + OrdinaryGapKey::Text => heap.set_named_edge(owner, GAP_TEXT, target), + OrdinaryGapKey::Number => heap.set_number_edge(owner, GAP_NUMBER, target), + } +} + +fn write_ordinary_peer( + heap: &mut LuaHeap, + owner: TableRef, + key: OrdinaryGapKey, +) -> Result<(), HeapError> { + match key { + OrdinaryGapKey::Text => heap.set_named_scalar(owner, PEER_TEXT, Value::string("peer")), + OrdinaryGapKey::Number => heap.set_number_scalar(owner, PEER_NUMBER, Value::string("peer")), + } +} + +fn clear_ordinary( + heap: &mut LuaHeap, + owner: TableRef, + key: OrdinaryGapKey, +) -> Result<(), HeapError> { + match key { + OrdinaryGapKey::Text => heap.set_named_scalar(owner, GAP_TEXT, Value::Null), + OrdinaryGapKey::Number => heap.clear_number_edge(owner, GAP_NUMBER), + } +} + +fn stored_table(heap: &LuaHeap, index: u32) -> Option { + let edge = heap.edge_slots[index as usize].edge.as_ref()?; + match &edge.value { + super::EdgeValue::Table { slot, generation } => { + Some(TableRef::table(heap.domain, *slot, *generation)) + } + _ => None, + } +} + +fn record_is_gap(heap: &LuaHeap, index: u32) -> bool { + heap.edge_slots[index as usize] + .edge + .as_ref() + .is_some_and(|edge| edge.value.is_cursor_gap()) +} + +fn pause_on_later_pass(parked: &mut ParkedMark<'_>, owner: u32, cursor: u32) -> PendingScan { + let sweep = parked.meter().sweep_edge_checks; + for _ in 0..HARNESS_BOUND { + let view = parked.pulse(1); + assert!( + !view.finished, + "mark finished before owner {owner} record {cursor} was pending" + ); + assert_eq!( + view.meter.sweep_edge_checks, sweep, + "a later-pass pulse must not sweep" + ); + if let Some(pending) = parked.pending() + && pending.owner == owner + && pending.cursor == cursor + { + assert_eq!(parked.phase_name(), "gray"); + assert_eq!( + view.meter.mark_passes, 2, + "the pending record is in the new pass" + ); + assert!(parked.mutation_open()); + return pending; + } + } + panic!("pending record {cursor} on owner {owner} was not observed"); +} + +fn slot_generation(heap: &LuaHeap, table: TableRef) -> u32 { + heap.slots[table.slot() as usize].generation +} + +fn root_holds(slot: &Option, table: TableRef) -> bool { + matches!( + slot, + Some(super::Rooted::Table(found)) + if found.slot() == table.slot() && found.generation() == table.generation() + ) +} + +/// Refills a physical gap left by a real weak-value cycle. +/// +/// The first collection clears the old value and keeps the record. The second +/// cycle is a saved Gray pause after that record has been charged. The refill +/// uses the ordinary text or number writer, not the published tail entry. +fn ordinary_gap_refill_after_real_clear(key: OrdinaryGapKey, write: OrdinaryGapWrite) { + use crate::heap::{self, StepOutcome}; + + let retained = ordinary_gap_retains(write); + crate::with_idle_vm(|vm| { + let mut host = vm.host_context(); + heap::install(&mut host, limits(16, 4, 16)).expect("install"); + let built = heap::with_heap(&mut host, |heap| { + let mode = heap.alloc()?; + heap.set_mode_scalar(mode, Value::string("v"))?; + let owner = heap.alloc()?; + let sentinel = heap.alloc()?; + let weak = heap.alloc()?; + let old = heap.alloc()?; + heap.set_metatable(owner, Some(mode))?; + heap.set_metatable(weak, Some(mode))?; + let frame = heap.enter_roots(4)?; + // Gray pops the highest root first: owner, then the pending sentinel. + heap.write_root(frame, 0, mode)?; + heap.write_root(frame, 1, weak)?; + heap.write_root(frame, 2, sentinel)?; + heap.write_root(frame, 3, owner)?; + write_ordinary_table(heap, owner, key, old)?; + write_ordinary_peer(heap, owner, key)?; + heap.issue_carrier(old)?; + heap.set_named_scalar(sentinel, "pending", Value::Bool(true))?; + let gap_key = heap + .next_guest(owner, &Value::Null)? + .expect("the old value is the first cursor") + .0; + let peer = heap + .next_guest(owner, &gap_key)? + .expect("the sibling follows the old value"); + assert!(heap.next_guest(owner, &peer.0)?.is_none()); + let gap_index = locate_ordinary(heap, owner, key, false).expect("gap record"); + let peer_index = locate_ordinary(heap, owner, key, true).expect("peer record"); + let sentinel_index = heap + .locate_named(sentinel.slot(), "pending") + .map(|(_, index)| index) + .expect("sentinel record"); + Ok(( + mode, + owner, + sentinel, + weak, + old, + gap_key, + peer, + gap_index, + peer_index, + sentinel_index, + )) + }) + .expect("first-cycle graph"); + let ( + mode, + owner, + sentinel, + weak, + old, + gap_key, + peer, + gap_index, + peer_index, + sentinel_index, + ) = built; + let old_generation = old.generation(); + + heap::collect(&mut host).expect("weak values clear in a full cycle"); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(old), "the old node is not live"); + assert_ne!( + slot_generation(heap, old), + old_generation, + "the old node generation was released" + ); + assert!( + record_is_gap(heap, gap_index), + "the original record is a physical gap" + ); + assert_eq!( + locate_ordinary(heap, owner, key, false), + Some(gap_index), + "the gap kept its record index" + ); + assert_eq!( + locate_ordinary(heap, owner, key, true), + Some(peer_index), + "the other same-owner record remains" + ); + assert_eq!(read_ordinary(heap, owner, key)?, Value::Null); + assert_eq!(heap.next_guest(owner, &Value::Null)?, Some(peer.clone())); + assert_eq!( + heap.next_guest(owner, &gap_key)?, + Some(peer.clone()), + "the saved next cursor continues" + ); + assert_eq!(heap.stats().collections, 1); + assert_eq!(heap.scan_meter().mark_passes, 1); + if matches!(key, OrdinaryGapKey::Number) { + let spelling = super::EdgeKey::named(NUMBER_SPELLING); + assert_ne!( + super::EdgeKey::number(GAP_NUMBER), + spelling, + "a negative integer does not alias its spelling" + ); + assert!(heap.find_key(owner.slot(), &spelling).is_none()); + assert_ne!(gap_key, Value::string(NUMBER_SPELLING)); + } + Ok(()) + }) + .expect("physical gap after the first cycle"); + + assert!( + heap::fixed_step_idle(&mut host).expect("between cycles"), + "the mode change is idle" + ); + let (target, child, orphan, owner_carrier, target_carrier) = + heap::with_heap(&mut host, |heap| { + if !matches!(write, OrdinaryGapWrite::WeakValue) { + heap.set_metatable(owner, None)?; + assert_eq!(heap.metatable(owner)?, None); + } else { + assert_eq!(heap.metatable(owner)?, Some(mode)); + } + let target = heap.alloc()?; + let child = heap.alloc()?; + let orphan = heap.alloc()?; + heap.set_named_edge(target, GAP_CHILD, child)?; + heap.set_named_edge(weak, "watch", target)?; + heap.set_named_edge(weak, GAP_CHILD, child)?; + heap.set_named_edge(weak, "orphan", orphan)?; + assert!( + heap.roots.iter().all(|slot| !root_holds(slot, target) + && !root_holds(slot, child) + && !root_holds(slot, orphan)), + "the new objects have no fixed root" + ); + assert_eq!(heap.stats().live_roots, 4); + let owner_carrier = heap.issue_carrier(owner)?; + let target_carrier = heap.issue_carrier(target)?; + Ok((target, child, orphan, owner_carrier, target_carrier)) + }) + .expect("weak observation only"); + + heap::open_fixed_step(&mut host).expect("second Gray cycle"); + heap::with_heap(&mut host, |heap| { + let mut parked = ParkedMark::resume(heap).expect("resume second mark"); + let seen = pause_on_later_pass(&mut parked, owner.slot(), gap_index); + assert_eq!(parked.meter().mark_passes, 2, "this is a new mark pass"); + assert_eq!((seen.owner, seen.cursor), (owner.slot(), gap_index)); + let gaps_before = parked.meter().outgoing_gap_checks; + let pending = pause_on_later_pass(&mut parked, sentinel.slot(), sentinel_index); + assert_eq!( + parked.meter().outgoing_gap_checks, + gaps_before + 1, + "the original gap record was charged" + ); + assert!(parked.marked(owner), "the owner was scanned"); + assert!( + !parked.marked(target) && !parked.marked(child), + "weak observation does not mark the refill" + ); + assert_eq!( + (pending.owner, pending.cursor), + (sentinel.slot(), sentinel_index), + "another owner is still pending" + ); + parked.park()?; + assert!( + record_is_gap(heap, gap_index), + "scanning the gap did not rewrite the record" + ); + let chain_next = heap.edge_slots[gap_index as usize].next; + let occupied = heap.stats().edge_slots; + let live = heap.stats().live_edges; + let before = heap.scan_meter(); + if !matches!(write, OrdinaryGapWrite::Omitted) { + write_ordinary_table(heap, owner, key, target)?; + } + assert_eq!(locate_ordinary(heap, owner, key, false), Some(gap_index)); + assert_eq!(locate_ordinary(heap, owner, key, true), Some(peer_index)); + assert_eq!(heap.edge_slots[gap_index as usize].next, chain_next); + assert_eq!(heap.issued_value(owner)?, owner_carrier); + assert_eq!(heap.issued_value(target)?, target_carrier); + assert_eq!( + heap.stats().edge_slots, + occupied, + "replace does not allocate" + ); + let live_delta = u32::from(!matches!(write, OrdinaryGapWrite::Omitted)); + assert_eq!(heap.stats().live_edges, live + live_delta); + if !matches!(write, OrdinaryGapWrite::Omitted) { + let index = locate_ordinary(heap, owner, key, false).expect("refilled record"); + assert_eq!(stored_table(heap, index), Some(target)); + } else { + assert!( + record_is_gap(heap, gap_index), + "an omitted write leaves the gap" + ); + assert_eq!(read_ordinary(heap, owner, key)?, Value::Null); + } + let mut parked = ParkedMark::resume(heap).expect("mark survived the ordinary write"); + let cursor = parked.pending().expect("sentinel still pending"); + assert_eq!( + (cursor.owner, cursor.cursor), + (pending.owner, pending.cursor) + ); + assert!(!parked.marked(child), "the write must not scan the child"); + let after = parked.meter(); + assert_eq!(after.mark_passes, 2); + assert_eq!(after.mark_passes, before.mark_passes); + assert_eq!(after.outgoing_edge_checks, before.outgoing_edge_checks); + assert_eq!(after.outgoing_gap_checks, before.outgoing_gap_checks); + assert_eq!(after.owner_head_checks, before.owner_head_checks); + assert_eq!(after.root_slot_visits, before.root_slot_visits); + assert_eq!(after.parked_cursor_repairs, before.parked_cursor_repairs); + parked.park()?; + Ok(()) + }) + .expect("ordinary refill while Gray is parked"); + + let published = heap::step_fixed_frames(&mut host, 128).expect("publish"); + assert!( + matches!(published, StepOutcome::Published { .. }), + "{published:?}" + ); + assert_eq!(heap::stats(&mut host).expect("published").collections, 1); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.set_named_edge(owner, "blocked", sentinel), + Err(HeapError::SweepPending) + ); + if matches!(write, OrdinaryGapWrite::WeakValue) { + assert_eq!(read_ordinary(heap, owner, key)?, Value::Null); + assert!( + record_is_gap(heap, gap_index), + "weak publication restores the gap" + ); + assert_eq!(locate_ordinary(heap, owner, key, false), Some(gap_index)); + } + if matches!(write, OrdinaryGapWrite::Omitted) { + assert!(record_is_gap(heap, gap_index)); + assert_eq!(read_ordinary(heap, owner, key)?, Value::Null); + } + Ok(()) + }) + .expect("publication"); + let done = heap::step_fixed_frames(&mut host, 128).expect("finish this cycle"); + assert!(matches!(done, StepOutcome::Completed(_)), "{done:?}"); + assert!(heap::fixed_step_idle(&mut host).expect("idle")); + heap::with_heap(&mut host, |heap| { + assert_eq!( + heap.alive(target), + retained, + "ordinary gap refill must keep a strong value alive through this cycle" + ); + assert_eq!( + heap.alive(child), + retained, + "the child is reached only by the continued scan" + ); + assert!( + !heap.alive(orphan), + "the weak orphan proves this cycle released nodes" + ); + assert_ne!(slot_generation(heap, orphan), orphan.generation()); + assert_eq!(heap.stats().collections, 2); + assert_eq!(heap.scan_meter().mark_passes, 2); + assert_eq!(locate_ordinary(heap, owner, key, true), Some(peer_index)); + if retained { + assert_eq!(slot_generation(heap, target), target.generation()); + assert_eq!(read_ordinary(heap, owner, key)?, target_carrier); + assert_eq!(heap.named_edge(target, GAP_CHILD)?, Some(child)); + clear_ordinary(heap, owner, key)?; + } else { + assert_ne!(slot_generation(heap, target), target.generation()); + assert!(record_is_gap(heap, gap_index)); + } + Ok(()) + }) + .expect("this cycle's release"); + if retained { + heap::collect(&mut host).expect("next cycle after the only strong edge is removed"); + heap::with_heap(&mut host, |heap| { + assert!(!heap.alive(target) && !heap.alive(child)); + assert_ne!(slot_generation(heap, target), target.generation()); + assert_ne!(slot_generation(heap, child), child.generation()); + assert_eq!(heap.stats().collections, 3); + assert_eq!(heap.scan_meter().mark_passes, 3); + assert!(locate_ordinary(heap, owner, key, false).is_none()); + Ok(()) + }) + .expect("later reclamation"); + } + }); +} + +#[test] +fn gray_ordinary_gap_text_strong_refill_keeps_the_new_graph() { + ordinary_gap_refill_after_real_clear(OrdinaryGapKey::Text, OrdinaryGapWrite::Strong); +} + +#[test] +fn gray_ordinary_gap_number_strong_refill_keeps_the_new_graph() { + ordinary_gap_refill_after_real_clear(OrdinaryGapKey::Number, OrdinaryGapWrite::Strong); +} + +#[test] +fn gray_ordinary_gap_text_weak_refill_publishes_nil() { + ordinary_gap_refill_after_real_clear(OrdinaryGapKey::Text, OrdinaryGapWrite::WeakValue); +} + +#[test] +fn gray_ordinary_gap_number_weak_refill_publishes_nil() { + ordinary_gap_refill_after_real_clear(OrdinaryGapKey::Number, OrdinaryGapWrite::WeakValue); +} + +#[test] +fn gray_ordinary_gap_text_omitted_write_keeps_the_gap() { + ordinary_gap_refill_after_real_clear(OrdinaryGapKey::Text, OrdinaryGapWrite::Omitted); +} + +#[test] +fn gray_ordinary_gap_number_omitted_write_keeps_the_gap() { + ordinary_gap_refill_after_real_clear(OrdinaryGapKey::Number, OrdinaryGapWrite::Omitted); +} From fbea45cba1df1710e238a602b7bcebad5b904b24 Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 07:55:09 +0800 Subject: [PATCH 146/225] Replay the reviewed unused-mut removal on the ordinary gap refill resume Apply 49d705e using a2f75a9 as the merge base. Only parked_mark.rs changes, and only by dropping the unused mut. The gap behavior stays in the parent commit. This replay adds no production wiring, Release allocation, or same-program linkage. --- tests/luajit_heap_runtime/parked_mark.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/luajit_heap_runtime/parked_mark.rs b/tests/luajit_heap_runtime/parked_mark.rs index e1f68b4..1f1dce1 100644 --- a/tests/luajit_heap_runtime/parked_mark.rs +++ b/tests/luajit_heap_runtime/parked_mark.rs @@ -4302,7 +4302,7 @@ fn ordinary_gap_refill_after_real_clear(key: OrdinaryGapKey, write: OrdinaryGapW ); assert_eq!(read_ordinary(heap, owner, key)?, Value::Null); } - let mut parked = ParkedMark::resume(heap).expect("mark survived the ordinary write"); + let parked = ParkedMark::resume(heap).expect("mark survived the ordinary write"); let cursor = parked.pending().expect("sentinel still pending"); assert_eq!( (cursor.owner, cursor.cursor), From 7c3771c6ab6418959000cf4c81105e86297c8807 Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 08:28:10 +0800 Subject: [PATCH 147/225] Replay the reviewed automatic release allocation onto the barrier union Apply 9e946e8 using its own parent 5547f99 as the merge base. Both merge-file directions are clean and byte-equal. This commit keeps the empty-local allocation, the isomorphic stopped shape, the quota refusal, and the registered-token rollback. The injected committed-late observation stays in the following commit. This replay adds no same-program linkage and does not replace the barrier, Gray query, or capacity guard. --- src/frontends/lua/heap.rs | 162 ++++++++ src/frontends/lua/heap/table.rs | 146 ++++++++ src/frontends/lua/heap/table/sweep.rs | 15 + tests/luajit_heap_runtime/candidate.rs | 170 ++++++++- .../source_scalar_retire.rs | 345 +++++++++++++++++- 5 files changed, 824 insertions(+), 14 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index 7df56df..e144708 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -429,6 +429,168 @@ fn publish_late(host: &mut HostContext) -> Result<(TableRef, vm::ResourceHandle) } } +/// Publishes one empty table into the current top frame while Release is paused. +/// +/// Admission, including the empty root slot, is checked before a node or a +/// Core token is registered. `Ok(None)` means this pause is not an admitted +/// Release handoff; nothing was reserved. A later refusal closes the token, +/// confirms it is closed, and only then returns the slot. The Release cursor, +/// mark count, and accounted roots are not moved. +#[cfg(test)] +pub fn publish_automatic_release_table( + host: &mut HostContext, + slot: u32, + fail_after_registration: bool, +) -> Result, HeapError> { + let Some(heap) = host.scope_state::() else { + return Ok(None); + }; + if !heap.automatic_release_slot_admitted(slot)? { + return Ok(None); + } + let reservation = { + let heap = host + .scope_state_mut::() + .expect("admission found the installed heap"); + heap.reserve_late_table()? + }; + if !host + .scope_state::() + .expect("reservation keeps the installed heap") + .automatic_release_slot_admitted(slot)? + { + host.scope_state_mut::() + .expect("reservation keeps the installed heap") + .abandon_late(reservation); + return Err(HeapError::Scope( + "release handoff lost admission after reserve".to_string(), + )); + } + let table = reservation.table(); + let resource = match host.push_resource(LuaTableResource::new(table)) { + Ok(resource) => resource, + Err(error) => { + host.scope_state_mut::() + .expect("reservation keeps the installed heap") + .abandon_late(reservation); + return Err(HeapError::from_scope(error)); + } + }; + let handle = resource.handle(); + if fail_after_registration { + return rollback_unbound_release( + host, + reservation, + handle, + HeapError::Scope( + "automatic release allocation refused after the token was registered".to_string(), + ), + ); + } + let value = match host.scope_state_mut::() { + Some(heap) => heap.issue_reserved_carrier(table), + None => Err(HeapError::SweepDenied), + }; + let value = match value { + Ok(value) => value, + Err(error) => return rollback_unbound_release(host, reservation, handle, error), + }; + if !host + .scope_state::() + .is_some_and(|heap| heap.automatic_release_slot_admitted(slot).unwrap_or(false)) + { + return rollback_unbound_release( + host, + reservation, + handle, + HeapError::Scope("release handoff lost admission after issue".to_string()), + ); + } + let raw = handle.raw(); + host.scope_state_mut::() + .expect("reservation keeps the installed heap") + .commit_late(reservation, raw); + if let Err(error) = host + .scope_state_mut::() + .expect("committed late node keeps the installed heap") + .store_release_top_root(slot, table) + { + close_confirmed_token(host, handle)?; + host.scope_state_mut::() + .expect("committed late node keeps the installed heap") + .undo_committed_late(table)?; + return Err(error); + } + Ok(Some(value)) +} + +#[cfg(test)] +fn rollback_unbound_release( + host: &mut HostContext, + reservation: table::LateReservation, + handle: vm::ResourceHandle, + error: HeapError, +) -> Result, HeapError> { + close_confirmed_token(host, handle)?; + host.scope_state_mut::() + .expect("unbound reservation keeps the installed heap") + .abandon_late(reservation); + Err(error) +} + +#[cfg(test)] +fn close_confirmed_token( + host: &mut HostContext, + handle: vm::ResourceHandle, +) -> Result<(), HeapError> { + match host.close_resource::(handle, vm::ResourceCloseReason::Requested) { + Ok(vm::resource::CloseProgress::Ready) => {} + Ok(_) => { + return Err(HeapError::Scope( + "lua table close did not finish synchronously".to_string(), + )); + } + Err(error) => return Err(HeapError::from_scope(error)), + } + match host.close_resource::(handle, vm::ResourceCloseReason::Requested) { + Err(error) if retired_lua_token(&error) => Ok(()), + Ok(_) => Err(HeapError::Scope( + "lua table close did not stay closed".to_string(), + )), + Err(error) => Err(HeapError::from_scope(error)), + } +} + +/// True when `slot` can receive one automatic empty table on the saved Release tail. +#[cfg(test)] +pub fn automatic_release_slot_admitted( + host: &mut HostContext, + slot: u32, +) -> Result { + let Some(heap) = host.scope_state::() else { + return Ok(false); + }; + heap.automatic_release_slot_admitted(slot) +} + +/// Mark count and late-node count of the saved tail. Does not resume it. +#[cfg(test)] +pub fn saved_tail_accounting(host: &mut HostContext) -> Result, HeapError> { + let Some(heap) = host.scope_state::() else { + return Ok(None); + }; + Ok(heap.saved_tail_accounting()) +} + +/// Table roots in the current top frame, in slot order. Does not scan. +#[cfg(test)] +pub fn top_frame_tables(host: &mut HostContext) -> Result>, HeapError> { + let Some(heap) = host.scope_state::() else { + return Ok(Vec::new()); + }; + Ok(heap.top_frame_tables()) +} + /// Replaces one ordinary UTF-8 gap with an already issued table while this /// scope's published sweep tail is saved. Does not install a heap and does /// not resume the tail. diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs index f29c9b5..f8848e0 100644 --- a/src/frontends/lua/heap/table.rs +++ b/src/frontends/lua/heap/table.rs @@ -993,6 +993,36 @@ impl LuaHeap { Ok(value) } + /// Issues the carrier for one unmarked reservation while a sweep tail is saved. + /// + /// Ordinary [`Self::issue_carrier`] stays closed: it still calls + /// `ensure_sweep_open` and refuses a second issue. This path requires the + /// exact live unmarked reservation and does not resume the tail. + #[cfg(test)] + pub(super) fn issue_reserved_carrier(&mut self, table: TableRef) -> Result { + self.ensure_published_tail()?; + self.require_live(table)?; + let index = table.slot() as usize; + if Self::slot_marked(&self.slots[index].state) { + return Err(HeapError::Scope( + "release handoff carrier slot was marked".to_string(), + )); + } + if self.slots[index].carrier.is_some() || self.slots[index].token.is_some() { + return Err(HeapError::StaleHandle); + } + let value = Value::array(vec![ + Value::Int(i64::from(table.slot())), + Value::Int(i64::from(table.generation())), + ]); + let carrier = match &value { + Value::Array(issued) => Arc::clone(issued), + _ => unreachable!("Value::array returns an array"), + }; + self.slots[index].carrier = Some(carrier); + Ok(value) + } + /// Classifies a guest value against this heap. /// /// A table result requires the live slot, the issued generation, and the @@ -2221,6 +2251,122 @@ impl LuaHeap { Ok(()) } + /// True when this top-frame slot can receive one automatic empty table. + /// + /// Release must already have visited a dead slot and left a suffix. The + /// slot must be the current top frame's empty fixed root. A Roots pause, + /// a cursor that has not released, or a finished suffix is `Ok(false)` + /// and does not allocate. An occupied or missing slot is an error and + /// does not allocate either. + #[cfg(test)] + pub(super) fn automatic_release_slot_admitted(&self, slot: u32) -> Result { + let Some(tail) = self.sweep_tail.as_ref() else { + return Ok(false); + }; + if tail.phase() != sweep::TailPhase::Release { + return Ok(false); + } + let cursor = tail.cursor(); + if cursor == 0 || cursor >= tail.dead_len() { + return Ok(false); + } + self.release_top_slot_empty(slot)?; + Ok(true) + } + + /// Stores one unmarked reservation in the current top frame's empty slot. + /// + /// This is not [`Self::store_release_caller_root`]: that path still requires + /// a marked table in the direct caller. This write does not call + /// `ensure_sweep_open`, does not park a mark, and does not move the Release + /// cursor, the mark count, or the accounted root count. + #[cfg(test)] + pub(super) fn store_release_top_root( + &mut self, + slot: u32, + table: TableRef, + ) -> Result<(), HeapError> { + if !self.automatic_release_slot_admitted(slot)? { + return Err(HeapError::Scope( + "release handoff root was not empty at store".to_string(), + )); + } + self.require_live(table)?; + let index = table.slot() as usize; + if Self::slot_marked(&self.slots[index].state) { + return Err(HeapError::Scope( + "release handoff root table was marked".to_string(), + )); + } + let frame = self.frames.last().expect("admission found the top frame"); + let root_index = frame.start as usize + slot as usize; + self.roots[root_index] = Some(Rooted::Table(table)); + Ok(()) + } + + #[cfg(test)] + fn release_top_slot_empty(&self, slot: u32) -> Result<(), HeapError> { + let Some(frame) = self.frames.last() else { + return Err(HeapError::NoRootFrame); + }; + if slot >= frame.width { + return Err(HeapError::StaleFrame); + } + let index = frame.start as usize + slot as usize; + if self.roots.get(index).is_none() { + return Err(HeapError::StaleFrame); + } + if self.roots[index].is_some() { + return Err(HeapError::Scope(format!( + "release handoff slot {slot} is occupied" + ))); + } + Ok(()) + } + + /// Drops one late node that was committed and then refused. The Core token + /// must already be closed. Does not move the Release cursor or mark count. + #[cfg(test)] + pub(super) fn undo_committed_late(&mut self, table: TableRef) -> Result<(), HeapError> { + self.ensure_published_tail()?; + self.require_live(table)?; + let index = table.slot() as usize; + if Self::slot_marked(&self.slots[index].state) { + return Err(HeapError::SweepPending); + } + self.sweep_tail + .as_mut() + .expect("published tail accepted the undo") + .undo_late(); + self.slots[index].carrier = None; + self.slots[index].token = None; + self.release_slot(table.slot()); + Ok(()) + } + + #[cfg(test)] + pub fn saved_tail_accounting(&self) -> Option<(u32, u32)> { + let tail = self.sweep_tail.as_ref()?; + Some((tail.marked_nodes(), tail.late_nodes())) + } + + #[cfg(test)] + pub fn top_frame_tables(&self) -> Vec> { + let Some(frame) = self.frames.last() else { + return Vec::new(); + }; + let start = frame.start as usize; + (0..frame.width) + .map(|slot| { + let index = start + slot as usize; + match self.roots.get(index) { + Some(Some(Rooted::Table(table))) => Some(*table), + _ => None, + } + }) + .collect() + } + /// Clears one slot of an open frame. The frame does not have to be the /// top frame. Other slots, including another slot holding the same table, /// stay. A stale id or an out-of-range slot is refused. An empty slot diff --git a/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs index 3fc2d84..57ed217 100644 --- a/src/frontends/lua/heap/table/sweep.rs +++ b/src/frontends/lua/heap/table/sweep.rs @@ -107,6 +107,21 @@ impl SweepTail { self.dead.len() } + #[cfg(test)] + pub(super) fn marked_nodes(&self) -> u32 { + self.marked_nodes + } + + #[cfg(test)] + pub(super) fn late_nodes(&self) -> u32 { + self.late_nodes + } + + #[cfg(test)] + pub(super) fn undo_late(&mut self) { + self.late_nodes = self.late_nodes.saturating_sub(1); + } + /// Spends `budget` on the shared release/root machine. Zero does not read the heap. pub(super) fn drive(self, heap: &mut LuaHeap, budget: u64) -> TailStep { let mut phase = self.phase; diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index c87edcb..9631d94 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -503,8 +503,11 @@ enum Op { impl HostOwnedFunction for Op { fn call(&mut self, call: &mut OwnedHostCall<'_>) -> Result { let value = match self { - Self::NewTable => heap::publish_guest(&mut call.vm().host_context()) - .map_err(|error| VmError::HostError(error.to_string()))?, + Self::NewTable => match take_automatic_release_table(&mut call.vm().host_context())? { + Some(value) => value, + None => heap::publish_guest(&mut call.vm().host_context()) + .map_err(|error| VmError::HostError(error.to_string()))?, + }, Self::Type => { let value = match call.args() { [value] => value.clone(), @@ -1065,10 +1068,12 @@ fn root_issued(call: &mut OwnedHostCall<'_>) -> Result { heap.current_frame().ok_or(heap::HeapError::StaleFrame) }) .map_err(heap_error)?; - heap::with_heap(&mut call.vm().host_context(), |heap| { - heap.write_root(frame, slot, table) - }) - .map_err(heap_error)?; + if !acknowledge_release_root(&mut call.vm().host_context(), table, slot)? { + heap::with_heap(&mut call.vm().host_context(), |heap| { + heap.write_root(frame, slot, table) + }) + .map_err(heap_error)?; + } with_witness(call.vm(), |witness| { witness.issued.push(table); if role == 0 { @@ -2079,6 +2084,42 @@ pub(super) fn auto_root_plan(host: &vm::HostContext<'_>) -> Option host.scope_state::().copied() } +/// One function-local empty table that the next `NEW_TABLE` may publish +/// into the saved Release tail. Not a permission for ordinary `alloc`. +struct ReleaseAllocPermit { + slot: u32, + consumed: bool, +} + +/// The top-frame root already written for that permit. `ROOT_ISSUED` records +/// the witness and does not call the ordinary writer. +struct ReleaseRootAck { + table: heap::TableRef, + slot: u32, + pending: bool, +} + +/// Test-only refusal after the Core token is registered. Not a source example. +#[derive(Clone, Copy, Debug)] +pub(super) struct ReleaseAllocFault; + +pub(super) fn arm_release_alloc_fault(host: &mut vm::HostContext<'_>) -> Result<(), VmError> { + host.scope_state_or_insert_with(|| ReleaseAllocFault) + .map(|_| ()) + .map_err(|error| VmError::HostError(error.to_string())) +} + +fn release_handoff_slot(flag: Option<&Value>) -> Option { + let Value::Float(flag) = flag? else { + return None; + }; + if !flag.is_finite() || *flag < 1.0 || flag.fract() != 0.0 { + return None; + } + let slot = (*flag as u64).checked_sub(1)?; + u32::try_from(slot).ok() +} + fn note_auto_root_plan(host: &mut vm::HostContext<'_>, batch: usize) -> Result<(), VmError> { let (phase, root_slots) = { let Some(heap) = host.scope_state::() else { @@ -2106,6 +2147,95 @@ fn note_auto_root_plan(host: &mut vm::HostContext<'_>, batch: usize) -> Result<( Ok(()) } +/// One idle empty-local safepoint after single-arg restart. +/// +/// The mark allowance and, only when that call publishes a tail, the +/// continuation allowance are separate host phase budgets. Pending close, +/// token close, and the Owners walk stay on the existing driver's own meters +/// and are not limited by either allowance. This does not call `heap::collect` +/// and does not treat a saved tail as idle. +fn prepare_automatic_release(host: &mut vm::HostContext<'_>, slot: u32) -> Result { + let admitted = heap::automatic_release_slot_admitted(host, slot).map_err(heap_error)?; + if !admitted { + return Ok(false); + } + if host + .scope_state::() + .is_some_and(|permit| !permit.consumed) + { + return Err(VmError::HostError( + "automatic release allocation is already pending".to_string(), + )); + } + let permit = ReleaseAllocPermit { + slot, + consumed: false, + }; + if let Some(existing) = host.scope_state_mut::() { + *existing = permit; + } else { + host.scope_state_or_insert_with(|| permit) + .map_err(|error| VmError::HostError(error.to_string()))?; + } + Ok(true) +} + +fn take_automatic_release_table(host: &mut vm::HostContext<'_>) -> Result, VmError> { + let Some(slot) = host.scope_state::().and_then(|permit| { + if permit.consumed { + None + } else { + Some(permit.slot) + } + }) else { + return Ok(None); + }; + if let Some(permit) = host.scope_state_mut::() { + permit.consumed = true; + } + let fail = host.scope_state::().is_some(); + let value = heap::publish_automatic_release_table(host, slot, fail).map_err(heap_error)?; + let Some(value) = value else { + return Err(VmError::HostError( + "automatic release allocation was not admitted at NEW_TABLE".to_string(), + )); + }; + let table = match classify(host, &value)? { + heap::GuestClass::Table(table) => table, + _ => { + return Err(VmError::HostError( + "automatic release carrier is not a table".to_string(), + )); + } + }; + let ack = ReleaseRootAck { + table, + slot, + pending: true, + }; + if let Some(existing) = host.scope_state_mut::() { + *existing = ack; + } else { + host.scope_state_or_insert_with(|| ack) + .map_err(|error| VmError::HostError(error.to_string()))?; + } + Ok(Some(value)) +} + +fn acknowledge_release_root( + host: &mut vm::HostContext<'_>, + table: heap::TableRef, + slot: u32, +) -> Result { + let matches = host + .scope_state::() + .is_some_and(|ack| ack.pending && ack.table == table && ack.slot == slot); + if matches && let Some(ack) = host.scope_state_mut::() { + ack.pending = false; + } + Ok(matches) +} + /// One idle empty-local safepoint after single-arg restart. /// /// The mark allowance and, only when that call publishes a tail, the @@ -2118,10 +2248,12 @@ fn auto_table_restart(call: &mut OwnedHostCall<'_>) -> Result { return Ok(Value::Float(0.0)); } let tables = decode_safepoint_roots(call)?; - // 1 is emitted only for a function-local empty table, whose next statements - // are NEW_TABLE and ROOT_ISSUED. The host still requires a saved gray phase - // with a pending scan; chunk locals and direct calls pass 0. - let root_handoff = matches!(call.args().get(1), Some(Value::Float(flag)) if *flag == 1.0); + // A positive integer is the function-local root slot plus one. The next + // statements are NEW_TABLE and ROOT_ISSUED. Chunk locals and direct calls + // pass 0. Gray still only continues when that slot is present; the slot + // number is used by the Release handoff, not by the gray pause. + let handoff_slot = release_handoff_slot(call.args().get(1)); + let root_handoff = handoff_slot.is_some(); { let mut host = call.vm().host_context(); note_auto_root_plan(&mut host, tables.len())?; @@ -2147,6 +2279,15 @@ fn auto_table_restart(call: &mut OwnedHostCall<'_>) -> Result { note_collect(&mut host, report)?; confirm_round_finished(&mut host)?; } + heap::StepOutcome::Paused { tail: true } => { + let unfinished = "auto table restart did not finish the published tail: Paused { tail: true }".to_string(); + let Some(slot) = handoff_slot else { + return Err(VmError::HostError(unfinished)); + }; + if !prepare_automatic_release(&mut host, slot)? { + return Err(VmError::HostError(unfinished)); + } + } other => { return Err(VmError::HostError(format!( "auto table restart did not finish the published tail: {other:?}" @@ -3218,8 +3359,13 @@ impl Lower<'_> { let gather = self.stmts.split_off(start); // Only a function-local empty table continues into NEW_TABLE and then // ROOT_ISSUED, with no guest safepoint between those statements. - // Chunk locals, and the direct probe, pass 0 and keep the pause error. - let handoff = Expr::Float(if self.in_function { 1.0 } else { 0.0 }); + // The handoff float is that local's root slot plus one. Chunk locals, + // and the direct probe, pass 0 and keep the pause error. + let handoff = Expr::Float(if self.in_function { + f64::from(self.root_slot) + 1.0 + } else { + 0.0 + }); let taken = self.call(AUTO_TABLE_RESTART, vec![roots, handoff])?; let expr = Expr::IfElse { condition: Box::new(due), diff --git a/tests/luajit_heap_runtime/source_scalar_retire.rs b/tests/luajit_heap_runtime/source_scalar_retire.rs index b696910..877d2a8 100644 --- a/tests/luajit_heap_runtime/source_scalar_retire.rs +++ b/tests/luajit_heap_runtime/source_scalar_retire.rs @@ -120,6 +120,10 @@ struct Trace { texts: Vec<(f64, String)>, bits: Vec<(f64, bool)>, bit_cycle_state: Vec<(bool, u32)>, + bit_accounting: Vec>, + bit_tail: Vec>, + bit_roots: Vec>>, + bit_resources: Vec, marks: Vec, occupancy: Vec, } @@ -155,6 +159,9 @@ struct Ran { mark_phase: Option<&'static str>, mark_pending: bool, parked_root_writes: u64, + tail_state: Option, + peek_end: Vec<(bool, bool)>, + resources: usize, } struct Plugin { @@ -453,9 +460,17 @@ impl HostOwnedFunction for HostOp { }; let tail = heap::saved_sweep_tail(&mut host).map_err(host_heap)?; let collections = heap::stats(&mut host).map_err(host_heap)?.collections; + let accounting = heap::saved_tail_accounting(&mut host).map_err(host_heap)?; + let tail_state = heap::saved_tail_state(&mut host).map_err(host_heap)?; + let roots = heap::top_frame_tables(&mut host).map_err(host_heap)?; + let resources = host.resource_count(); note(&mut host, |state| { state.bits.push((*tag, *bit)); state.bit_cycle_state.push((tail, collections)); + state.bit_accounting.push(accounting); + state.bit_tail.push(tail_state); + state.bit_roots.push(roots); + state.bit_resources.push(resources); })?; Value::Bool(*bit) } @@ -658,7 +673,24 @@ fn run_control(source: &str, budgets: Option<&[u64]>) -> Ran { } fn run_auto_table(source: &str, budgets: Option<&[u64]>) -> Ran { - drive_plugin(source, budgets, &AUTO_TABLE_PLUGIN, None) + drive_plugin_opts(source, budgets, &AUTO_TABLE_PLUGIN, None, 8, false) +} + +fn run_auto_table_limited( + source: &str, + budgets: Option<&[u64]>, + nodes: u32, + max_generation: u32, + fail_after_registration: bool, +) -> Ran { + drive_plugin_opts( + source, + budgets, + &AUTO_TABLE_PLUGIN, + Some(nodes), + max_generation, + fail_after_registration, + ) } fn drive(source: &str, budgets: Option<&[u64]>, run_control: bool, nodes: Option) -> Ran { @@ -677,6 +709,17 @@ fn drive_plugin( budgets: Option<&[u64]>, plugin: &'static Plugin, nodes: Option, +) -> Ran { + drive_plugin_opts(source, budgets, plugin, nodes, 8, false) +} + +fn drive_plugin_opts( + source: &str, + budgets: Option<&[u64]>, + plugin: &'static Plugin, + nodes: Option, + max_generation: u32, + fail_after_registration: bool, ) -> Ran { let catalog = Arc::clone(plugin_catalog(plugin)); let options = CompileSourceFileOptions::new() @@ -704,11 +747,14 @@ fn drive_plugin( nodes, roots: 64, edges: 64, - max_generation: 8, + max_generation, }, ) .expect("test host installs the node quota before execution"); } + if fail_after_registration { + candidate::arm_release_alloc_fault(&mut vm.host_context()).expect("arm release fault"); + } let status = vm.run(); let trace = vm .host_context() @@ -777,6 +823,30 @@ fn drive_plugin( }; let mark = heap::saved_mark_query(&vm.host_context()); let meter = heap::copy_scan_meter(&mut vm.host_context()).unwrap_or_default(); + let tail_state = heap::saved_tail_state(&mut vm.host_context()) + .ok() + .flatten(); + let peek_end: Vec<(bool, bool)> = trace + .peeks + .iter() + .map(|observed| { + let alive = + heap::with_heap( + &mut vm.host_context(), + |heap| Ok(heap.alive(observed.table)), + ) + .unwrap_or(false); + let open = vm + .host_context() + .typed_resource_with_key::( + observed.token, + &heap::LuaTableResource::key(), + ) + .is_ok(); + (alive, open) + }) + .collect(); + let resources = vm.host_context().resource_count(); Ran { stop, stack: vm.stack().to_vec(), @@ -798,6 +868,9 @@ fn drive_plugin( mark_phase: mark.map(|(phase, _)| phase), mark_pending: mark.is_some_and(|(_, pending)| pending), parked_root_writes: meter.parked_root_writes, + tail_state, + peek_end, + resources, } } @@ -4614,6 +4687,274 @@ bit(1, peek(held)) assert!(ran.mark_phase.is_none()); } +/// Same function, one ordinary empty local, after restart has made the heap due. +/// Four weak-only entries give the published tail a dead suffix. The first +/// budget is fixture evidence that this graph publishes; it is not a phase +/// contract. The second budget does one Release visit and leaves a suffix. +const RELEASE_ALLOC_BODY: &str = r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + w[3] = {} + w[4] = {} + w[5] = {} + bit(1, peek(held)) + bit(2, peek(w)) + note(1, collectgarbage("restart")) + text(1, type(rawget(w, 2))) + local fresh = {} + text(2, type(rawget(w, 2))) + bit(3, peek(fresh)) + collectgarbage("step") + bit(4, peek(fresh)) + collectgarbage("collect") + bit(5, peek(fresh)) + return 1 +end +witness() +collectgarbage("collect") +return 1 +"#; + +const RELEASE_ALLOC_PAUSE: &str = r#" +local function witness() + local w = {} + local mt = {} + local held = {} + mt.__mode = "v" + setmetatable(w, mt) + w[1] = held + w[2] = {} + w[3] = {} + w[4] = {} + w[5] = {} + bit(1, peek(held)) + bit(2, peek(w)) + note(1, collectgarbage("restart")) + text(1, type(rawget(w, 2))) + local fresh = {} + bit(3, peek(fresh)) + return 1 +end +witness() +return 1 +"#; + +fn release_pause_error(message: &str) -> bool { + message == "auto table restart did not finish the published tail: Paused { tail: true }" +} + +#[test] +fn auto_release_pause_allocates_the_empty_local() { + let ran = run_auto_table(RELEASE_ALLOC_BODY, Some(&[10_000, 1, 10_000])); + assert_eq!(ran.stop, Stop::Halted, "{ran:#?}"); + assert_eq!( + ran.trace.peeks.len(), + 5, + "fresh is issued and re-read: {ran:#?}" + ); + let fresh = ran.trace.peeks[2].table; + assert_eq!(ran.trace.peeks[3].table, fresh); + assert_eq!(ran.trace.peeks[4].table, fresh); + assert!( + fresh.generation() > 1, + "the new node reuses a released slot: {fresh:?}" + ); + assert_eq!( + ran.trace.bit_cycle_state[2], + (true, 0), + "handoff keeps the tail" + ); + assert_eq!( + ran.trace.bit_cycle_state[3], + (false, 1), + "explicit continuation completes once" + ); + assert_eq!( + ran.trace.bits[3], + (4.0, true), + "the same object stays reachable" + ); + assert_eq!( + ran.trace.bits[4], + (5.0, true), + "the function root keeps it through another cycle" + ); + assert_eq!(text_value(&ran.trace, 1.0), "table"); + assert_eq!( + text_value(&ran.trace, 2.0), + "nil", + "the independent weak entry was cleared" + ); + assert_eq!( + ran.parked_root_writes, 0, + "the handoff must not park a mark" + ); + let accounting = ran.trace.bit_accounting[2].expect("tail accounting at the handoff"); + assert_eq!(accounting.1, 1, "one late node: {accounting:?}"); + assert!( + accounting.0 > 0, + "the handoff does not clear the mark count" + ); + let tail = ran.trace.bit_tail[2].expect("saved tail at the handoff"); + assert_eq!(tail.phase, heap::SavedTailPhase::Release); + assert_eq!( + tail.cursor, 1, + "the handoff does not move the release cursor" + ); + assert_eq!( + tail.live_roots, 0, + "the new root is not counted until continuation" + ); + assert!( + tail.cursor < tail.dead_len, + "an unconsumed dead suffix remains" + ); + let roots = &ran.trace.bit_roots[2]; + assert_eq!( + roots.get(3).copied().flatten(), + Some(fresh), + "top-frame slot 3 is fresh" + ); + let alive = ran.peek_end[2]; + assert!(!alive.0, "scalar return then collect releases the node"); + assert!(!alive.1, "the token is closed with the node"); +} + +#[test] +fn stopped_release_shape_allocates_without_a_cycle() { + let source = + RELEASE_ALLOC_PAUSE.replace("collectgarbage(\"restart\")", "collectgarbage(\"stop\")"); + let ran = run_auto_table(&source, None); + assert_eq!(ran.stop, Stop::Halted, "{ran:#?}"); + assert!(!ran.tail, "stop must not start a cycle"); + assert_eq!(ran.collections, 0); + assert_eq!( + ran.trace.peeks.len(), + 3, + "the empty local is an ordinary allocation" + ); + assert_eq!(text_value(&ran.trace, 1.0), "table"); +} + +#[test] +fn auto_release_roots_pause_does_not_allocate() { + let ran = run_auto_table(RELEASE_ALLOC_PAUSE, Some(&[10_000, 5])); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if release_pause_error(message)), + "{ran:#?}" + ); + assert_eq!(ran.trace.peeks.len(), 2); + assert_eq!(ran.collections, 0); + let state = ran.tail_state.expect("saved tail"); + assert_eq!(state.phase, heap::SavedTailPhase::Roots); + assert_eq!( + heap_tail_late(&ran), + Some(0), + "the Roots refusal adds no late node" + ); +} + +#[test] +fn auto_release_chunk_local_does_not_allocate() { + let source = r#" +local function keep_return_window() + return 1 +end +keep_return_window() +local w = {} +local mt = {} +local held = {} +mt.__mode = "v" +setmetatable(w, mt) +w[1] = held +w[2] = {} +w[3] = {} +w[4] = {} +w[5] = {} +bit(1, peek(held)) +bit(2, peek(w)) +note(1, collectgarbage("restart")) +text(1, type(rawget(w, 2))) +local fresh = {} +bit(3, peek(fresh)) +return 1 +"#; + let ran = run_auto_table(source, Some(&[10_000, 1])); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if release_pause_error(message)), + "chunk has no root handoff: {ran:#?}" + ); + assert_eq!(ran.trace.peeks.len(), 2); + let state = ran.tail_state.expect("saved tail"); + assert_eq!(state.phase, heap::SavedTailPhase::Release); + assert!(state.cursor > 0 && state.cursor < state.dead_len); + assert_eq!(heap_tail_late(&ran), Some(0)); +} + +#[test] +fn auto_release_pause_refuses_a_full_node_quota() { + let ran = run_auto_table_limited(RELEASE_ALLOC_PAUSE, Some(&[10_000, 1]), 7, 1, false); + assert!( + matches!(ran.stop, Stop::HostError(ref message) if message.contains("node capacity")), + "{ran:#?}" + ); + assert_eq!(ran.trace.peeks.len(), 2, "the refused local is not issued"); + assert_eq!(ran.collections, 0); + let state = ran.tail_state.expect("legal scan remains"); + assert_eq!(state.phase, heap::SavedTailPhase::Release); + assert_eq!(state.cursor, 1); + assert!(state.cursor < state.dead_len); + assert_eq!(state.live_roots, 0); + assert_eq!(heap_tail_late(&ran), Some(0)); + assert_eq!( + ran.live_nodes, 6, + "the release visit is scan progress, not a new node" + ); +} + +#[test] +fn auto_release_pause_rolls_back_a_registered_token() { + let refused = run_auto_table_limited(RELEASE_ALLOC_PAUSE, Some(&[10_000, 1]), 64, 8, true); + let clean = run_auto_table_limited(RELEASE_ALLOC_PAUSE, Some(&[10_000, 1]), 7, 1, false); + assert!( + matches!(refused.stop, Stop::HostError(ref message) if message.contains("refused after the token was registered")), + "{refused:#?}" + ); + assert!( + matches!(clean.stop, Stop::HostError(ref message) if message.contains("node capacity")), + "capacity refusal is the no-token control: {clean:#?}" + ); + assert_eq!(refused.trace.peeks.len(), 2); + assert_eq!(heap_tail_late(&refused), Some(0)); + assert_eq!( + refused.tail_state, clean.tail_state, + "rollback does not move the legal scan" + ); + assert_eq!(refused.live_nodes, clean.live_nodes); + assert_eq!( + refused.resources, clean.resources, + "the registered token is closed" + ); +} + +fn heap_tail_late(ran: &Ran) -> Option { + ran.tail_state.and(Some(0)).map(|_| { + ran.trace + .bit_accounting + .iter() + .rev() + .find_map(|item| *item) + .map(|(_, late)| late) + .unwrap_or(0) + }) +} + #[test] fn chunk_auto_gray_pause_does_not_allocate() { let source = r#" From a8cb17e1bf6a57cf7fb3d90b8e0008eeaabc5a81 Mon Sep 17 00:00:00 2001 From: fffonion Date: Wed, 25 Nov 2026 08:28:10 +0800 Subject: [PATCH 148/225] Replay the reviewed automatic release handoff evidence onto the barrier union Apply 8d9198f using 9e946e8 as the merge base. source_scalar_retire.rs has one empty-base insertion in drive_plugin_opts, immediately before `let stop = match status`. Keep the original budgets and running lines, then the original status_debug line. Both directions resolve to the same bytes. This replay adds no same-program linkage and does not replace the barrier, Gray query, or capacity guard. --- src/frontends/lua/heap.rs | 70 ++++- tests/luajit_heap_runtime/candidate.rs | 19 +- .../source_scalar_retire.rs | 267 ++++++++++++++++-- 3 files changed, 324 insertions(+), 32 deletions(-) diff --git a/src/frontends/lua/heap.rs b/src/frontends/lua/heap.rs index e144708..09a6dd1 100644 --- a/src/frontends/lua/heap.rs +++ b/src/frontends/lua/heap.rs @@ -436,11 +436,16 @@ fn publish_late(host: &mut HostContext) -> Result<(TableRef, vm::ResourceHandle) /// Release handoff; nothing was reserved. A later refusal closes the token, /// confirms it is closed, and only then returns the slot. The Release cursor, /// mark count, and accounted roots are not moved. +/// `fail_after_commit` is a test injection. It runs only after `commit_late` +/// has succeeded and before the first root write, then uses the same close, +/// `undo_committed_late`, and slot-release branch as a real store error. +/// #[cfg(test)] pub fn publish_automatic_release_table( host: &mut HostContext, slot: u32, fail_after_registration: bool, + fail_after_commit: bool, ) -> Result, HeapError> { let Some(heap) = host.scope_state::() else { return Ok(None); @@ -507,20 +512,28 @@ pub fn publish_automatic_release_table( ); } let raw = handle.raw(); + let before = release_txn_snap(host)?; host.scope_state_mut::() .expect("reservation keeps the installed heap") .commit_late(reservation, raw); - if let Err(error) = host - .scope_state_mut::() - .expect("committed late node keeps the installed heap") - .store_release_top_root(slot, table) - { + let stored = if fail_after_commit { + Err(HeapError::Scope( + "injected after commit_late and before the first root write".to_string(), + )) + } else { + host.scope_state_mut::() + .expect("committed late node keeps the installed heap") + .store_release_top_root(slot, table) + }; + if let Err(error) = stored { close_confirmed_token(host, handle)?; host.scope_state_mut::() .expect("committed late node keeps the installed heap") .undo_committed_late(table)?; return Err(error); } + let after = release_txn_snap(host)?; + remember_release_txn(host, ReleaseTxnWitness { before, after })?; Ok(Some(value)) } @@ -582,6 +595,53 @@ pub fn saved_tail_accounting(host: &mut HostContext) -> Result Option { + host.scope_state::().copied() +} + +#[cfg(test)] +fn release_txn_snap(host: &mut HostContext) -> Result { + let tail = saved_tail_state(host)?.ok_or(HeapError::SweepDenied)?; + let (marked, late) = saved_tail_accounting(host)?.ok_or(HeapError::SweepDenied)?; + Ok(ReleaseTxnSnap { tail, marked, late }) +} + +#[cfg(test)] +fn remember_release_txn( + host: &mut HostContext, + witness: ReleaseTxnWitness, +) -> Result<(), HeapError> { + if let Some(existing) = host.scope_state_mut::() { + *existing = witness; + return Ok(()); + } + host.scope_state_or_insert_with(|| witness) + .map(|_| ()) + .map_err(HeapError::from_scope) +} + /// Table roots in the current top frame, in slot order. Does not scan. #[cfg(test)] pub fn top_frame_tables(host: &mut HostContext) -> Result>, HeapError> { diff --git a/tests/luajit_heap_runtime/candidate.rs b/tests/luajit_heap_runtime/candidate.rs index 9631d94..24b2756 100644 --- a/tests/luajit_heap_runtime/candidate.rs +++ b/tests/luajit_heap_runtime/candidate.rs @@ -2103,12 +2103,27 @@ struct ReleaseRootAck { #[derive(Clone, Copy, Debug)] pub(super) struct ReleaseAllocFault; +pub(super) struct ReleaseAllocPostCommitFault; + pub(super) fn arm_release_alloc_fault(host: &mut vm::HostContext<'_>) -> Result<(), VmError> { host.scope_state_or_insert_with(|| ReleaseAllocFault) .map(|_| ()) .map_err(|error| VmError::HostError(error.to_string())) } +pub(super) fn arm_release_alloc_post_commit_fault( + host: &mut vm::HostContext<'_>, +) -> Result<(), VmError> { + host.scope_state_or_insert_with(|| ReleaseAllocPostCommitFault) + .map(|_| ()) + .map_err(|error| VmError::HostError(error.to_string())) +} + +pub(super) fn release_alloc_permit(host: &vm::HostContext<'_>) -> Option<(u32, bool)> { + host.scope_state::() + .map(|permit| (permit.slot, permit.consumed)) +} + fn release_handoff_slot(flag: Option<&Value>) -> Option { let Value::Float(flag) = flag? else { return None; @@ -2194,7 +2209,9 @@ fn take_automatic_release_table(host: &mut vm::HostContext<'_>) -> Result