diff --git a/src/frontends/lua/ast.rs b/src/frontends/lua/ast.rs new file mode 100644 index 0000000..7c6d87c --- /dev/null +++ b/src/frontends/lua/ast.rs @@ -0,0 +1,455 @@ +//! 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 }, +} + +/// 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 { + 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, + }, + /// 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, + }, + /// 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, + base: Box, + steps: Vec, + }, + 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::BinaryChain { span, .. } + | Self::Ternary { span, .. } + | Self::SuffixChain { span, .. } + | Self::Function { span, .. } + | Self::ShortFunction { span, .. } + | Self::Table { span, .. } => *span, + } + } + + pub fn is_multi(&self) -> bool { + match self { + Self::Vararg { .. } => true, + Self::SuffixChain { steps, .. } => matches!( + steps.last(), + Some(Suffix::Call { .. } | Suffix::Method { .. }) + ), + _ => false, + } + } +} diff --git a/src/frontends/lua/control.rs b/src/frontends/lua/control.rs new file mode 100644 index 0000000..566e20d --- /dev/null +++ b/src/frontends/lua/control.rs @@ -0,0 +1,1737 @@ +//! 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` 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 `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 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: +//! `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. +//! +//! 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`. +//! +//! 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}; +use vm::compiler::HostCallResolver; +use vm::{ + AssignmentKind, Expr as CoreExpr, FrontendIr, LocalIrBuilder, LocalSlot, ParseError, + Stmt as CoreStmt, TypeSchema, +}; + +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"; + +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))); + } + 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 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)? + }; + let mut ir = lower.builder.finish(stmts); + ir.implicit_extern_names = lower.externs; + Ok(ir) +} + +struct Lower<'a> { + source: &'a str, + resolution: &'a Resolution, + builder: LocalIrBuilder, + slots: Vec>, + dispatching: bool, + state: Option, + result: Option, + label_state: Vec>, + repeat_flags: u32, + nfor_ordinal: u32, + nfor_slots: Vec, + for_indexes: Vec, + holds: Option<&'a HostCallResolver<'a>>, + label_loops: Vec>, + pending_labels: Vec, + link_by_binding: Vec>, + externs: Vec, +} + +#[derive(Clone, Copy)] +struct Iteration { + owner: Span, + state: LocalSlot, +} + +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, + 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, + builder: LocalIrBuilder::new(), + slots, + dispatching: false, + state: None, + result: None, + label_state, + repeat_flags: 0, + nfor_ordinal: 0, + nfor_slots: Vec::new(), + for_indexes: Vec::new(), + holds, + label_loops, + pending_labels: Vec::new(), + link_by_binding, + externs: Vec::new(), + } + } + + 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(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> { + 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, 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. + 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. + let mut root = Vec::new(); + 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)); + } + root.push(dispatch_loop(state, dispatch_body, 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, + iteration: Option, + ) -> Result<(), ParseError> { + for stmt in stmts { + match stmt { + Stmt::Empty { .. } => {} + 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)?; + 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 } if iteration.is_none() => { + blocks.flush(Exit::Return { + expr: self.one_value(values, *span)?, + line: self.line(*span), + }); + } + 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, + limit, + step, + body, + span, + }, + _, + ) => { + 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(()); + } + 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, iteration: Option) -> 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, iteration), + 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], + 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, iteration)?); + } else { + self.append_items(stmt, &mut items, iteration)?; + } + } + Ok(items) + } + + fn if_item( + &mut self, + 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")); + } + if if_has_label(arms, else_body) { + return Err(self.fail(span, "a label inside if is not in this slice")); + } + 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, iteration)?, + None => Vec::new(), + }; + for arm in arms.iter().rev() { + 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, + 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: core_truthy(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, + enclosing_loop: bool, + ) -> Result, ParseError> { + let body_stmts = self.loop_body(body, span)?; + let line = self.line(span); + let stmt = CoreStmt::While { + condition: core_truthy(self.expr(cond)?), + body: body_stmts, + line, + }; + self.with_return_guard(vec![stmt], body, line, enclosing_loop) + } + + fn repeat_stmt( + &mut self, + body: &Block, + until: &Expr, + span: Span, + enclosing_loop: bool, + ) -> Result, ParseError> { + 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)?; + // 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. + let stmt = 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, + }; + self.with_return_guard(vec![stmt], body, line, enclosing_loop) + } + + fn numeric_for_stmts( + &mut self, + name: &Name, + start: &Expr, + limit: &Expr, + step: Option<&Expr>, + body: &Block, + span: Span, + ) -> Result, ParseError> { + 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 { + 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); + let stmts = 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, + }, + ]; + Ok(stmts) + } + + 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); + } + 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( + &self, + mut stmts: Vec, + body: &Block, + line: u32, + enclosing_loop: bool, + ) -> Result, ParseError> { + if self.loop_can_exit_chunk_arm(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 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 { + 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: pending_exit, + 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")); + }; + // 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), + CoreStmt::Break { line }, + ]) + } + + 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")); + }; + // 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 block_has_goto(&self, block: &Block, owner: Option) -> bool { + block + .stmts + .iter() + .any(|stmt| self.stmt_has_goto(stmt, owner)) + } + + fn stmt_has_goto(&self, stmt: &Stmt, owner: Option) -> bool { + match stmt { + 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, owner), + Stmt::If { + arms, else_body, .. + } => { + arms.iter().any(|arm| self.block_has_goto(&arm.body, owner)) + || else_body + .as_ref() + .is_some_and(|body| self.block_has_goto(body, owner)) + } + _ => false, + } + } + + 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, + 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], + 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 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")); + } + 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, .. } => { + if !in_loop { + return Err(self.fail(*span, "goto or label in a direct statement")); + } + 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")); + } + 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, + limit, + step, + 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)?), + } + } + 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::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")); + } + 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)?; + 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)?; + 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))) + } + + 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)?; + 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)) + } + 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(Box::new(core_truthy(*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) + } + 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, + 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_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, state)?); + } + Ok(out) + } + + fn emit_item(&self, item: &Item, state: LocalSlot) -> 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, state)?, + else_branch: self.emit_items(else_body, state)?, + line: *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), + } + } + + fn emit_exit( + &self, + exit: &Exit, + index: usize, + len: usize, + state: LocalSlot, + ) -> Result, ParseError> { + match exit { + Exit::Fallthrough => { + let next = if index + 1 < len { + self.state_id_of(index + 1) + } else { + EXIT_STATE + }; + Ok(transfer(state, next, 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 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(transfer(state, 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_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() { + 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 alloc_repeat_flag(&mut self) -> Result { + let name = format!("$lua_repeat_again_{}", self.repeat_flags); + self.repeat_flags += 1; + 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 + .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 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() { + 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 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, + declared_schema: None, + expr, + line, + } +} + +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, + 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 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_label_owners( + block: &Block, + owner: Option, + resolution: &Resolution, + owners: &mut [Option], +) { + for stmt in &block.stmts { + match stmt { + Stmt::Label { name, .. } if owner.is_some() => { + if let Some(index) = resolution + .labels + .iter() + .position(|label| label.span == name.span) + { + owners[index] = owner; + } + } + 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_label_owners(&arm.body, owner, resolution, owners); + } + if let Some(body) = else_body { + mark_label_owners(body, owner, resolution, owners); + } + } + _ => {} + } + } +} + +fn stmt_contains_label(stmt: &Stmt) -> bool { + match stmt { + Stmt::Label { .. } => true, + 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) + } + // Nested loops own their labels and lower them in their own regions. + _ => 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/heap.rs b/src/frontends/lua/heap.rs new file mode 100644 index 0000000..eee843e --- /dev/null +++ b/src/frontends/lua/heap.rs @@ -0,0 +1,2007 @@ +//! 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`. Collection +//! closes each swept node's token through the scope close contract and returns +//! that quota before the node is released. +//! +//! A bare userdata keeps its existing semantics: no guest carrier, finalizer, +//! environment, or Core token. The private pending-finalizer slice adds one +//! optional metatable reference and a retained state for a live unmarked +//! typed userdata; neither is a guest metamethod or a callback path. The +//! private host path in this module also issues +//! a separate `resource` capability for one userdata node. Its +//! heap slot stores the raw Core handle and the payload stores the exact Lua +//! domain, kind, slot, and generation, so the checked borrow rejects a wrong +//! heap, kind, key, generation, or same-type token for another object. The +//! close is synchronous (`Ready`); a `Pending` result is an error. The host +//! collector closes that token through the same `retire_doomed_token` path as +//! a table token and clears the exact binding before weak publication and +//! Release. A pure `LuaHeap` sweep refuses a dead slot that still carries a +//! bound token instead of skipping it. +//! +//! The private pending-finalizer slice has one selecting entry, +//! [`collect_pending_finalizers`]. After the ordinary mark converges it walks +//! the live-userdata chain from its head, one real chain node per selection +//! unit, retains live unmarked typed userdata whose metatable has a raw +//! non-nil `__gc` field, and marks the userdata so the ordinary gray pass +//! follows its userdata-to-metatable strong edge and the metatable's own +//! strong entries. A retained userdata keeps its original generation, typed +//! payload, and Core token. A white candidate whose raw `__gc` is missing, nil, +//! or a weak-cleared gap is settled instead: that exact generation is marked +//! finalized without a queue record and without a mark, so it is never queued +//! again even if a raw `__gc` is installed later, and an unreachable one dies +//! in the same cycle. Settlement is not retention. +//! +//! At weak publication a weak value that names a retained pending userdata or +//! a live settled generation is cleared, while a weak key keeps the entry and +//! its scalar only when the object is actually marked. A `k`-only table also +//! clears a pending or settled userdata value from its string-keyed and +//! object-keyed hash entries; numeric keys keep the previous strong-value rule +//! because this representation has no array/hash split. A sweep with no dead +//! slot still runs the Owners walk when a pending finalizer or a marked +//! settled generation needs that publication. Ordinary collections never +//! select; they offer every existing record as a host-retained edge, so no +//! live token is closed or orphaned while it waits for a consumer. +//! +//! A successful private collection records the queue length it published as a +//! consumable prefix only after the real weak publication finished. The +//! private real handoff [`take_published_pending_finalizer`] then pops exactly +//! that front record with one published-front pop from the slot-linked queue, +//! verifies the exact +//! live userdata and typed Core token, writes the userdata into one specified +//! empty root slot, and settles that generation in the same commit. It never +//! calls guest code. A saved mark or Release tail refuses before any write, and +//! records retained by a failed or ordinary collection stay outside the ready +//! prefix. The first-round order is the selecting scan's live-chain order: +//! reverse allocation inside one cohort, appended after any older published +//! records; it is not a slot-index sort and not a guest callback order. The +//! test-only retirement control remains a historical fixture with the same +//! prefix invariant. No callback, resurrection, guest step, or production +//! entry is added here. +//! +//! The private action handoff [`take_published_pending_finalizer_action`] +//! resolves the current raw `__gc` of that same published head in the exclusive +//! borrow that pops it, so a change made between two dequeues is observed. It +//! never reuses the selection cache and never pre-parses a batch. A missing +//! metatable, a missing field, or a true stored-nil gap is `Skip`; a present +//! non-callable value keeps only its original Lua type tag, never the scalar +//! bytes; a live closure is the direct action; a live table or a live +//! userdata adds only its own current instance metatable's raw `__call` +//! closure, with the original object kept as the receiver. Neither receiver +//! form inherits `__call` and neither dispatches a table-valued `__call` +//! again. The commit roots the userdata, the actual closure, and every +//! independent receiver in caller-supplied empty, distinct slots, then settles +//! once; a userdata receiver that is the pending object itself is already +//! rooted as that object and needs no second slot. `Skip` and a typed reject +//! retire exactly once with only the userdata root. An independent userdata +//! receiver is checked through the same typed `lua.userdata` owner contract as +//! the head before the pop, and the commit re-resolves the action in its own +//! exclusive borrow and requires that exact identity. No guest callback, +//! diagnostic text, or Core handle copy is produced here. +//! +//! Borrowed from the ES5 heap at `3e348a010bc8d84baa5b7d1169a5f50aeb4e46ec` +//! `src/javascript/heap.rs`: slot plus generation handles, explicit root +//! 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. +//! +//! 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, 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 +//! 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 +//! `/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. Only a table entry follows `__mode`. A +//! frame root is not a weak edge. + +#[path = "heap/handle.rs"] +mod handle; +#[path = "heap/resource.rs"] +mod resource; +#[path = "heap/table.rs"] +mod table; + +pub use handle::{ClosureRef, HandleKind, TableRef, UpvalueRef, UserdataRef}; +pub use resource::{LuaTableResource, LuaUserdataResource}; +#[cfg(test)] +pub(crate) use table::SelectingPendingMark; +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}; + +/// 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 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 { + 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)) { + Ok(resource) => resource, + Err(error) => { + with_heap(host, |heap| heap.rollback(table))?; + return Err(HeapError::from_scope(error)); + } + }; + 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((table, raw)) +} + +/// Allocates one bare userdata and publishes its private typed resource token. +/// +/// The Lua slot is reserved with an exact reservation record before +/// `HostContext::push_resource`. A refused insert rolls back only that empty +/// reservation in O(1), so a Lua quota or phase refusal never registers a +/// Core resource and never scans the graph. After registration this stores +/// the raw handle on the reservation (not in the published slot binding), +/// borrows the token with the exact `lua.userdata` key, and confirms that its +/// payload names this exact userdata (domain, kind, slot, and generation) +/// before it publishes the slot binding. The returned handle is published +/// only after both directions of that binding exist. +/// +/// A later failure closes the registered token through `close_resource`, +/// requires [`vm::resource::CloseProgress::Ready`], and confirms the handle is +/// retired before it rolls the Lua slot back. If that close is not confirmed, +/// the reservation stays with its staged raw handle and its generation is not +/// advanced. A normal collection retains that exact reservation: the shared +/// mark offers it as a host-retained edge and the pending-close enumeration +/// ignores the unpublished token. The next call to this function recovers it +/// before reserving again: the typed payload must name the exact userdata, +/// the same token is closed synchronously and confirmed retired, and only +/// then is the record cleared and the slot generation returned. A failed +/// recovery keeps the record for a later attempt. An ordinary borrow never +/// accepts the staged record. +/// `LuaUserdataResource` has no asynchronous close path: the default +/// synchronous close returns `Ready`, and `Pending` is an error here. +pub fn publish_userdata(host: &mut HostContext) -> Result { + recover_pending_userdata(host)?; + let userdata = with_heap(host, LuaHeap::reserve_userdata)?; + let resource = match host.push_resource(LuaUserdataResource::new(userdata)) { + Ok(resource) => resource, + Err(error) => { + with_heap(host, |heap| heap.rollback_empty_userdata(userdata))?; + return Err(HeapError::from_scope(error)); + } + }; + let handle = resource.handle(); + let raw = handle.raw(); + if let Err(error) = with_heap(host, |heap| heap.stage_userdata_token(userdata, raw)) { + return rollback_registered_userdata(host, userdata, handle, error); + } + let payload = match checked_userdata_payload(host, handle) { + Ok(payload) => payload, + Err(error) => { + return rollback_registered_userdata(host, userdata, handle, error); + } + }; + if payload != userdata { + return rollback_registered_userdata(host, userdata, handle, HeapError::TokenMismatch); + } + if let Err(error) = with_heap(host, |heap| heap.bind_userdata_token(userdata, raw)) { + return rollback_registered_userdata(host, userdata, handle, error); + } + Ok(userdata) +} + +/// Recovers a reservation left by a refused registered rollback before the +/// next issuance reserves again. +/// +/// The record and its live slot are validated first. For a registered +/// reservation, the typed payload must name the exact userdata, then that same +/// token is closed and confirmed retired before the record is cleared and the +/// slot generation returned. A close failure or owner mismatch keeps the +/// record, so a later call can retry it. An unregistered empty reservation has +/// no Core token: it is rolled back in O(1) without a close. No record is a +/// no-op. The whole recovery is one record check, one exact typed borrow, one +/// synchronous close, and one O(1) rollback: it adds no scan unit, no graph +/// search, and no owner walk. +fn recover_pending_userdata(host: &mut HostContext) -> Result<(), HeapError> { + let Some((userdata, raw)) = with_heap(host, |heap| heap.pending_userdata_reservation())? else { + return Ok(()); + }; + if let Some(raw) = raw { + let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let owner = checked_userdata_payload(host, handle)?; + if owner != userdata { + return Err(HeapError::TokenMismatch); + } + close_confirmed_token::(host, handle)?; + } + with_heap(host, |heap| heap.rollback_empty_userdata(userdata))?; + Ok(()) +} + +/// Borrows the typed resource token recorded for `userdata`. +/// +/// The Lua handle is checked against the installed heap domain, live slot, +/// generation, and kind. The stored raw handle is then validated by the Core +/// resource table (arena, slot generation, concrete `TypeId`, and the exact +/// `lua.userdata` key). Finally the payload must name this same userdata, so a +/// same-type token for another object is refused even though its key matches. +/// A missing heap is [`HeapError::SweepDenied`]; a foreign Lua heap is +/// [`HeapError::WrongDomain`]; a stale or unbound Lua slot is +/// [`HeapError::StaleHandle`]; a payload for another object is +/// [`HeapError::TokenMismatch`]. +pub fn borrow_published_userdata( + host: &HostContext, + userdata: UserdataRef, +) -> Result { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + if userdata.domain() != heap.domain() { + return Err(HeapError::WrongDomain); + } + let raw = heap.published_userdata_token(userdata)?; + let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let borrowed = host + .borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + .map_err(HeapError::from_scope)?; + if borrowed.get().userdata() != userdata { + return Err(HeapError::TokenMismatch); + } + Ok(userdata) +} + +/// Borrows one registered userdata token with the exact key and copies its +/// payload out. The borrow ends here, so a caller can close or roll back the +/// same `HostContext` on the error path. +fn checked_userdata_payload( + host: &HostContext, + handle: vm::ResourceHandle, +) -> Result { + let borrowed = host + .borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + .map_err(HeapError::from_scope)?; + Ok(borrowed.get().userdata()) +} + +/// Closes one registered userdata token and confirms that a second close sees +/// it retired. If the close is not confirmed, the reservation keeps its staged +/// raw handle and its generation, so the private retry can close the same +/// token. A controlled test refusal returns before any close is attempted. +fn rollback_registered_userdata( + host: &mut HostContext, + userdata: UserdataRef, + handle: vm::ResourceHandle, + error: HeapError, +) -> Result { + #[cfg(test)] + if take_userdata_rollback_refusal(host) { + return Err(HeapError::Scope( + "injected userdata rollback refusal before close".to_string(), + )); + } + close_confirmed_token::(host, handle)?; + with_heap(host, |heap| heap.rollback_empty_userdata(userdata))?; + Err(error) +} + +/// One-shot test hook consumed by the real [`rollback_registered_userdata`] +/// control flow. It refuses that rollback before the first close. It is not a +/// `Pending` close and never fabricates a Core progress value. +#[cfg(test)] +#[derive(Clone, Copy, Debug, Default)] +struct UserdataRollbackRefusal { + armed: bool, +} + +/// Arms the one-shot refusal for the next registered userdata rollback. +#[cfg(test)] +pub fn arm_userdata_rollback_refusal(host: &mut HostContext) -> Result<(), HeapError> { + if let Some(stored) = host.scope_state_mut::() { + stored.armed = true; + return Ok(()); + } + host.scope_state_or_insert_with(|| UserdataRollbackRefusal { armed: true }) + .map(|_| ()) + .map_err(HeapError::from_scope) +} + +#[cfg(test)] +fn take_userdata_rollback_refusal(host: &mut HostContext) -> bool { + let Some(stored) = host.scope_state_mut::() else { + return false; + }; + let armed = stored.armed; + stored.armed = false; + armed +} + +/// Reads the staged (unpublished) raw handle for one exact reservation. +/// Test-only: an ordinary borrow never accepts this record. +#[cfg(test)] +pub fn pending_userdata_raw( + host: &mut HostContext, + userdata: UserdataRef, +) -> Result, HeapError> { + with_heap(host, |heap| Ok(heap.pending_userdata_token(userdata).ok())) +} + +/// Retries one registered userdata rollback after a refused attempt. It reads +/// the staged raw handle and closes that same Core token, then releases the +/// empty reservation. Test-only immediate entry: the production recovery is +/// the next [`publish_userdata`] call, which validates the exact owner and +/// performs the same close and generation return. Normal collections retain +/// the record this entry consumes. +#[cfg(test)] +pub fn retry_pending_userdata_rollback( + host: &mut HostContext, + userdata: UserdataRef, +) -> Result { + let raw = with_heap(host, |heap| heap.pending_userdata_token(userdata))?; + let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + close_confirmed_token::(host, handle)?; + with_heap(host, |heap| heap.rollback_empty_userdata(userdata)) +} + +/// Closes one typed token, requires the synchronous result, and confirms that +/// the handle is retired. A Pending close is an error: these types have no +/// asynchronous close path. +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 typed resource 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_token(&error) => Ok(()), + Ok(_) => Err(HeapError::Scope( + "lua typed resource close did not stay closed".to_string(), + )), + Err(error) => Err(HeapError::from_scope(error)), + } +} + +/// One controlled userdata failure after registration, for the private test +/// injection. It records the real Core handle, the resource count on both +/// sides, and whether the real rollback completed or retained the staged raw. +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UserdataPostRegisterFailure { + /// The reserved Lua handle, still live and unpublished on the refusal path. + pub userdata: UserdataRef, + pub raw: u64, + pub registered_count: usize, + pub ended_count: usize, + /// `Some(Ready)` only when this call actually completed the synchronous + /// close. `None` means the one-shot refusal returned before any close: + /// this witness never reports a fabricated `Pending`. + pub close: Option, + /// The staged raw retained for a retry when the rollback was refused. + pub pending_raw: Option, + pub slot: u32, + /// Generation after the call: advanced only when the slot was released. + pub generation: u32, +} + +/// The witness from the last [`publish_userdata_after_register_failure`] call. +#[cfg(test)] +pub fn last_userdata_post_register_failure( + host: &HostContext, +) -> Option { + host.scope_state::().copied() +} + +/// Test-only injection: registers a real userdata token, stages its raw, then +/// fails before the slot binding is published and runs the real +/// [`rollback_registered_userdata`] control flow. With no armed refusal it +/// closes and confirms that same token and rolls the slot back. With the +/// one-shot refusal armed it returns before the close and keeps the staged +/// raw. A normal collection then retains that exact registration, and the +/// next [`publish_userdata`] call recovers it through the production path. +/// It never fabricates a handle and never skips the real rollback. +#[cfg(test)] +pub fn publish_userdata_after_register_failure( + host: &mut HostContext, +) -> Result { + let userdata = with_heap(host, LuaHeap::reserve_userdata)?; + let resource = match host.push_resource(LuaUserdataResource::new(userdata)) { + Ok(resource) => resource, + Err(error) => { + with_heap(host, |heap| heap.rollback_empty_userdata(userdata))?; + return Err(HeapError::from_scope(error)); + } + }; + let handle = resource.handle(); + let raw = handle.raw(); + with_heap(host, |heap| heap.stage_userdata_token(userdata, raw))?; + let registered_count = host.resource_count(); + let outcome = rollback_registered_userdata( + host, + userdata, + handle, + HeapError::Scope("injected userdata failure after registration".to_string()), + ); + let ended_count = host.resource_count(); + let pending_raw = pending_userdata_raw(host, userdata)?; + let generation = with_heap(host, |heap| { + Ok(heap.slot_generation(userdata.slot()).unwrap_or(0)) + })?; + let close = (pending_raw.is_none() && ended_count + 1 == registered_count) + .then_some(vm::resource::CloseProgress::Ready); + let witness = UserdataPostRegisterFailure { + userdata, + raw, + registered_count, + ended_count, + close, + pending_raw, + slot: userdata.slot(), + generation, + }; + if let Some(stored) = host.scope_state_mut::() { + *stored = witness; + } else { + host.scope_state_or_insert_with(|| witness) + .map_err(HeapError::from_scope)?; + } + outcome?; + unreachable!("rollback_registered_userdata always returns its failure") +} + +/// 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) +} + +/// 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. +/// +/// 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 +/// 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, 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` and `LuaUserdataResource` use the default synchronous +/// close, which returns Ready. A Pending result is an error. These types have +/// no path that starts an asynchronous close, and this collector does not add +/// one. On error the already closed prefix is real: its bindings stay cleared, +/// but the failing token and the whole unclosed suffix keep their bindings, +/// no weak edge is published, no release tail is saved, and no generation is +/// advanced. +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)?; + } + with_heap(host, |heap| Ok(heap.sweep_marked(marked.modes))) +} + +/// Publish stopped before release, or the heap had no weak edge to publish. +#[derive(Debug)] +pub(crate) enum PublishedBoundary { + /// Neither a dead slot, nor a retained pending finalizer, nor a live + /// settled userdata needs a weak publication. Sweep finished and + /// recorded the one report. + Completed(table::CollectReport), + /// Weak edges are published. Dead slots are still physical. No report. + /// `window_heads`/`window_edges` are the actual Owners walk, which can + /// be non-empty with no dead slot when a pending finalizer's or a settled + /// userdata's weak value is cleared. + Published { + window_heads: u64, + window_edges: u64, + }, +} + +/// A saved published sweep that this call did not finish, or the one report +/// from the tail that did finish. +#[derive(Debug)] +pub(crate) enum PublishedResume { + /// The tail is still saved. This call did not finish the sweep. + Paused, + /// The tail finished in this call. The report was recorded once. + Completed(table::CollectReport), +} + +/// Marks, closes doomed tokens, publishes weak edges, and saves the release tail. +/// +/// Does not take an observer. A parked mark is refused and left in place. +/// Close failure publishes nothing and saves no tail. +pub(crate) fn collect_until_published( + host: &mut HostContext, +) -> 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()))?; + close_then_halt_at_publish(host, marked, false) +} + +/// Closes doomed tokens, then publishes or finishes. Same order as the +/// original collector: a close error returns before publish, so there is no +/// tail and no report. +/// +/// `settle_rollback` is true only for the selecting entry. On a close error +/// that pass's new settlement flags are returned to their previous state, just +/// like its new pending records are handled by the caller; an already closed +/// prefix stays closed and a pending record from an earlier pass is untouched. +fn close_then_halt_at_publish( + host: &mut HostContext, + marked: table::DoomedMark, + settle_rollback: bool, +) -> Result { + for token in marked.tokens { + if let Err(error) = retire_doomed_token(host, token) { + if settle_rollback { + with_heap(host, |heap| { + heap.discard_settlements(); + Ok(()) + })?; + } + return Err(error); + } + } + 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, + }, + }) +} + +/// Private single-shot collector for the pending-finalizer slice. +/// +/// Phases and boundaries, in order: +/// 1. Refuse a saved mark or saved release tail. No heap installs one. +/// 2. Run one ordinary non-moving mark with the same roots, registered +/// reservation offer, and pending-record offers. A parked mark is dropped, +/// as in [`collect`]. +/// 3. After the ordinary gray, rescan, and late work empties, walk the +/// live-userdata chain from its head, one chain node per selection unit. +/// Select each live, unmarked userdata that binds a typed Core token +/// and whose metatable has a raw non-nil `__gc` field. Mark it through the +/// ordinary target follow; the next gray pass follows its metatable edge +/// and the metatable's own strong entries. A raw field that is missing, +/// nil, or already a weak-cleared cursor gap settles that exact white +/// identity instead: the generation is finalized without a queue record +/// and without a mark. A slot already pending or settled is not selected +/// again. Candidates that share a metatable pay one lookup for that +/// metatable per round, but each one still receives its own queue or +/// settlement result. +/// 4. Enumerate pending-close candidates as usual. A selected userdata is +/// marked, so it is not in that list and its token stays bound. A settled +/// userdata is not marked by the settlement, so an unreachable one is +/// ordinary dead garbage in this same cycle. +/// 5. Borrow every pending record with its exact `lua.userdata` token and +/// require the payload to name the same slot and generation. A mismatch +/// returns before any close or publish and rolls back this pass's new +/// records and settlement flags. +/// 6. Close each doomed token synchronously and confirm `Ready`. A close +/// error also rolls back this pass's new settlement flags; an already +/// closed prefix and earlier pending records stay as they were. +/// 7. Run the Owners walk once. Weak values that name a retained pending +/// userdata or a live settled generation are published as gaps; weak keys +/// keep the entry and its scalar only when the object is marked. A dead +/// slot is not required for this step. Store the Release/Roots tail and +/// return [`PublishedBoundary::Published`]; a heap with no dead slot, no +/// pending finalizer, and no live settled userdata finishes and returns +/// [`PublishedBoundary::Completed`]. +/// +/// Release and Roots do not run here. The caller finishes them with +/// [`resume_published_sweep`]. No callback, resurrection, guest step, or +/// production entry is added. The records are retained by later ordinary +/// collections until the test-only explicit retirement control consumes one. +pub(crate) fn collect_pending_finalizers( + host: &mut HostContext, +) -> 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); + } + // Capture the queue's own round-start boundary before this pass can + // append a record: the exact tail identity and length. A later owner + // failure rolls back only the segment appended after this pair; the + // published prefix is never substituted for it, and a valid unpublished + // segment left by an earlier failed close stays queued. + let base = with_heap(host, |heap| Ok(heap.pending_finalizer_checkpoint()))?; + let marked = with_heap(host, |heap| Ok(heap.mark_and_pending_tokens()))?; + if let Err(error) = verify_pending_finalizers(host) { + // This is the owner-verification preflight's own transaction: remove + // only the records and settlement flags appended by this selecting + // pass. Earlier valid records and settled generations are untouched, + // no doomed token has been closed yet, and no weak edge has been + // published, so the two later failure prefixes are not mixed into + // this rollback. + with_heap(host, |heap| { + heap.discard_pending_finalizers_from(base); + heap.discard_settlements(); + Ok(()) + })?; + return Err(error); + } + let boundary = close_then_halt_at_publish(host, marked, true)?; + with_heap(host, |heap| { + // The real weak publication finished in this call. Only now do the + // retained records become a consumable prefix. A saved Release tail + // still refuses a dequeue until the caller resumes it to completion. + heap.publish_pending_finalizer_prefix(); + heap.clear_selecting_settlements(); + Ok(()) + })?; + Ok(boundary) +} + +/// Borrows each pending record with its concrete `lua.userdata` key and +/// checks that the payload names the same slot and generation. +/// +/// The borrow ends before the next record. This runs after the selecting mark +/// and before any doomed token closes or any weak edge is published. A +/// missing or wrong token returns [`HeapError::TokenMismatch`] or the real +/// scope error; no record is mutated. The caller then discards only the +/// records appended by this pass. +fn verify_pending_finalizers(host: &HostContext) -> Result<(), HeapError> { + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + let records = heap.pending_finalizer_records(); + for (raw, slot, generation) in records { + let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let borrowed = host + .borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + .map_err(HeapError::from_scope)?; + let payload = borrowed.get().userdata(); + if payload.domain() != heap.domain() + || payload.slot() != slot + || payload.generation() != generation + || payload.kind() != HandleKind::Userdata + { + return Err(HeapError::TokenMismatch); + } + #[cfg(test)] + heap.record_owner_verification_success(slot, generation); + } + Ok(()) +} + +/// Test-only explicit retirement control for one pending finalizer. +/// +/// This is the current consumer stand-in for a later real finalizer call: it +/// removes the record, clears the pending flag, and marks that generation as +/// settled without closing the token or running guest code. Selection will +/// not pick the settled object again; a later collection may then close that +/// token and advance the slot generation. It is not a callback and does not +/// fabricate a close status. It also keeps the queue's published-prefix +/// invariant: removing a published position drops the ready prefix by one, +/// while removing an unpublished position leaves it unchanged. +#[cfg(test)] +pub fn retire_pending_finalizer_test_control( + host: &mut HostContext, + userdata: UserdataRef, +) -> Result<(), HeapError> { + with_heap(host, |heap| heap.retire_pending_finalizer(userdata)) +} + +/// Private real handoff for one published pending-finalizer head. +/// +/// This is not a guest `__gc` callback and does not run guest code. It refuses +/// a saved mark ([`HeapError::MarkActive`]) or release tail +/// ([`HeapError::SweepPending`]) before reading the queue. The head must be in +/// the prefix that one successful private publication made consumable; an +/// unpublished or absent head returns a scope error. The specified frame and +/// slot must name an open, previously empty root slot +/// ([`HeapError::StaleFrame`] or a scope error for an occupied slot). The +/// record's live slot must still bind its exact generation, kind, pending +/// flag, and raw handle, and the typed `lua.userdata` payload must name that +/// same userdata ([`HeapError::TokenMismatch`] otherwise). All of those checks +/// happen before the first queue, root, or slot write. +/// +/// On success the head is popped with one published-front removal, the exact +/// `UserdataRef` is written into the specified root slot, and that generation +/// is marked settled and no longer pending. The returned handle is the same +/// typed object the queue verified; the raw Core token is not returned or +/// copied into a guest value. The order is the selecting scan's live-chain +/// order: reverse allocation inside one cohort, after any older published +/// records; it is not a callback order. +pub(crate) fn take_published_pending_finalizer( + host: &mut HostContext, + frame: RootFrameId, + slot: u32, +) -> 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 head = heap.pending_finalizer_published_front()?; + heap.pending_finalizer_root_slot(frame, slot)?; + let userdata = UserdataRef::userdata(heap.domain(), head.slot, head.generation); + if heap.published_userdata_token(userdata)? != head.raw { + return Err(HeapError::TokenMismatch); + } + let handle = + vm::ResourceHandle::from_raw(head.raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let borrowed = host + .borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + .map_err(HeapError::from_scope)?; + if borrowed.get().userdata() != userdata { + return Err(HeapError::TokenMismatch); + } + drop(borrowed); + with_heap(host, |heap| { + heap.take_published_finalizer_into_root(frame, slot, head) + }) +} + +/// The current raw finalizer decision for one published pending head. +/// +/// This is a private dispatch plan, not a guest callable. It is recomputed at +/// dequeue time from the userdata's current metatable, so a modifier that ran +/// earlier in the same batch is observed. A `Closure`, the `call` inside +/// `TableCall`, or the `call` inside `UserdataCall` is an actual closure +/// identity; a receiver form also keeps the original object instead of +/// replacing it with the callable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PendingFinalizerAction { + /// No live metatable, no raw `__gc` record, or a true stored-nil gap. + Skip, + /// A present raw `__gc` value that is not callable in this slice's + /// one-layer raw form. + NonCallable(PendingFinalizerNotCallable), + /// The raw `__gc` is a live closure. + Closure(ClosureRef), + /// The raw `__gc` is a live table whose own current metatable stores a raw + /// `__call` closure. The receiver is that original table. + TableCall { + receiver: TableRef, + call: ClosureRef, + }, + /// The raw `__gc` is a live userdata whose own current metatable stores a + /// raw `__call` closure. The receiver is that original userdata. + UserdataCall { + receiver: UserdataRef, + call: ClosureRef, + }, +} + +/// The original Lua type tag of a present raw `__gc` value that is not +/// callable in this slice. +/// +/// These tags carry no scalar payload: a boolean, number, or string keeps only +/// its type, never its bytes. A table or userdata reason keeps the exact +/// original receiver identity, so a later diagnostic can name the original +/// called type instead of the invalid `__call` value. This slice emits no +/// diagnostic text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PendingFinalizerNotCallable { + /// The original value was a boolean. + Boolean, + /// The original value was a number (`Int` or `Float`). + Number, + /// The original value was a Lua string (`String` or byte string). + String, + /// An internal upvalue carrier from the existing `EdgeValue` contract. No + /// named-field writer stores it; it is not a guest Lua value. + Upvalue, + /// A live userdata receiver with no live own metatable or no raw `__call` + /// field. + UserdataWithoutCall(UserdataRef), + /// A live userdata receiver whose raw `__call` exists but is not a live + /// closure. Another table is refused here: this slice does not dispatch + /// twice. + UserdataCallNotClosure(UserdataRef), + /// A table receiver with no live metatable or no raw `__call` field. + TableWithoutCall(TableRef), + /// A table receiver whose raw `__call` exists but is not a live closure. + /// Another table is refused here: this slice does not dispatch twice. + TableCallNotClosure(TableRef), + /// A stored object target no longer names a live node of its kind, or a + /// scalar carrier outside the named-field writer contract. + Detached, +} + +/// The no-allocation reject tag for one stored scalar, or `None` for a stored +/// nil. +/// +/// The private named-field writers can store a boolean or a Lua string +/// directly under `__gc`; a binary64 number remains limited to the reserved +/// `__mode` field and a byte string has no named-field writer. This helper is +/// therefore the narrowest complete classification: it maps `Int`/`Float` to +/// [`PendingFinalizerNotCallable::Number`] and `String`/`Bytes` to +/// [`PendingFinalizerNotCallable::String`] without copying either payload. +/// `Array`, `Map`, and `Callable` are outside this heap's named-field scalar +/// contract and are reported as `Detached`, not as a new guest tag. +pub(crate) fn pending_finalizer_scalar_reject( + value: &Value, +) -> Option { + match value { + Value::Null => None, + Value::Bool(_) => Some(PendingFinalizerNotCallable::Boolean), + Value::Int(_) | Value::Float(_) => Some(PendingFinalizerNotCallable::Number), + Value::String(_) | Value::Bytes(_) => Some(PendingFinalizerNotCallable::String), + Value::Array(_) | Value::Map(_) | Value::Callable(_) => { + Some(PendingFinalizerNotCallable::Detached) + } + } +} + +/// One committed private action handoff. +/// +/// The identities are already rooted in the caller's frame. No raw Core token +/// or guest callable is copied out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct TakenPendingFinalizer { + /// The exact typed userdata that left the published prefix. + pub userdata: UserdataRef, + /// The current raw decision that this same commit rooted. + pub action: PendingFinalizerAction, + /// Root slots written from the caller's plan: one for a skip or typed + /// reject, two for a direct closure or a self-receiver userdata call, and + /// three for a table call or an independent userdata receiver. + pub roots_written: u32, +} + +/// Private real dequeue that re-reads the current raw finalizer of the head. +/// +/// This is not a guest `__gc` callback and does not run guest code. It refuses +/// a saved mark ([`HeapError::MarkActive`]) or release tail +/// ([`HeapError::SweepPending`]) before reading the queue. The head must be in +/// the prefix that one successful private publication made consumable; an +/// unpublished or absent head returns a scope error. The record's live slot +/// must still bind its exact generation, kind, pending flag, and raw handle, +/// and the typed `lua.userdata` payload must name that same userdata +/// ([`HeapError::TokenMismatch`] otherwise). Every one of those checks happens +/// before the first queue, root, or slot write. +/// +/// The current raw `__gc` is resolved after the head checks. When it is a live +/// userdata receiver different from the head, that receiver must still own a +/// real typed `lua.userdata` token naming it (the same checked owner contract +/// as the head); a payload for another object is [`HeapError::TokenMismatch`]. +/// The commit then re-resolves the action in the same exclusive borrow that +/// pops the head and requires the exact prepared identity, so no fallible +/// action or owner check remains after the pop. `slots[0]` must be an open, +/// empty root slot for the userdata. A direct closure adds an empty distinct +/// `slots[1]`; the table form and an independent userdata receiver add the +/// closure at `slots[1]` and the original receiver at an empty distinct +/// `slots[2]`. A userdata receiver that is the pending object itself is +/// already rooted at `slots[0]`, so its call needs only two positions. A short +/// plan, an overlapping plan, a stale frame, an occupied slot, or an +/// out-of-range position is refused before any write, so the head and every +/// existing root stay. A `Skip` or typed reject needs only `slots[0]`, is +/// returned as its typed result, and is settled exactly once; it is never +/// re-queued. The commit pops one published-front record, writes the required +/// roots together, and settles that generation. The returned action and rooted +/// identities are private; the raw Core token is not copied into a guest +/// value. +pub(crate) fn take_published_pending_finalizer_action( + host: &mut HostContext, + frame: RootFrameId, + slots: &[u32], +) -> 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 head = heap.pending_finalizer_published_front()?; + let userdata = UserdataRef::userdata(heap.domain(), head.slot, head.generation); + if heap.published_userdata_token(userdata)? != head.raw { + return Err(HeapError::TokenMismatch); + } + let handle = + vm::ResourceHandle::from_raw(head.raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let borrowed = host + .borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + .map_err(HeapError::from_scope)?; + if borrowed.get().userdata() != userdata { + return Err(HeapError::TokenMismatch); + } + drop(borrowed); + // One fixed-size prepared action: the independent receiver's typed owner is + // checked before the commit borrow. The commit re-resolves the same action + // in its own exclusive borrow and refuses any identity change before the + // pop, so the root set always matches the checked receiver. + let action = with_heap(host, |heap| Ok(heap.pending_finalizer_action(userdata)))?; + verify_pending_finalizer_receiver(host, userdata, action)?; + with_heap(host, |heap| { + heap.take_published_finalizer_action_into_roots(frame, slots, head, action) + }) +} + +/// Checks that one independent userdata receiver still owns a real typed +/// `lua.userdata` token naming that same object. +/// +/// A receiver that is the pending object itself is already covered by the head +/// payload check and is not borrowed twice; the commit roots it at `slots[0]`. +/// This is one slot token read and one checked Core borrow with a payload +/// identity comparison. It reads no queue record and writes nothing. +fn verify_pending_finalizer_receiver( + host: &HostContext, + userdata: UserdataRef, + action: PendingFinalizerAction, +) -> Result<(), HeapError> { + let PendingFinalizerAction::UserdataCall { receiver, .. } = action else { + return Ok(()); + }; + if receiver == userdata { + return Ok(()); + } + let Some(heap) = host.scope_state::() else { + return Err(HeapError::SweepDenied); + }; + let raw = heap.published_userdata_token(receiver)?; + let handle = vm::ResourceHandle::from_raw(raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let borrowed = host + .borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + .map_err(HeapError::from_scope)?; + if borrowed.get().userdata() != receiver { + return Err(HeapError::TokenMismatch); + } + Ok(()) +} + +/// Number of pending records in the published prefix. Test-only header read; +/// it does not read a stored record. +#[cfg(test)] +pub fn pending_finalizer_published_count(host: &mut HostContext) -> Result { + with_heap(host, |heap| Ok(heap.pending_finalizer_published_count())) +} + +/// Number of stored pending records. Test-only header read; it does not read a +/// stored record. +#[cfg(test)] +pub fn pending_finalizer_count(host: &mut HostContext) -> Result { + with_heap(host, |heap| Ok(heap.pending_finalizer_count())) +} + +/// One userdata root slot. Test-only; does not scan or read the queue. +#[cfg(test)] +pub fn rooted_userdata( + host: &mut HostContext, + frame: RootFrameId, + slot: u32, +) -> Result, HeapError> { + with_heap(host, |heap| heap.rooted_userdata(frame, slot)) +} + +/// One closure root slot. Test-only; does not scan or read the queue. +#[cfg(test)] +pub fn rooted_closure( + host: &mut HostContext, + frame: RootFrameId, + slot: u32, +) -> Result, HeapError> { + with_heap(host, |heap| heap.rooted_closure(frame, slot)) +} + +/// Saves one empty private mark for a handoff refusal test. Test-only: the +/// real handoff must refuse a saved mark before it reads the queue. It does +/// not scan, close, publish, or run guest code. +#[cfg(test)] +pub fn open_saved_mark_for_test(host: &mut HostContext) -> Result<(), HeapError> { + with_heap(host, |heap| heap.open_private_step()) +} + +/// 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. +pub(crate) 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 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(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. + 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, false)? { + PublishedBoundary::Completed(report) => Ok(StepOutcome::Completed(report)), + PublishedBoundary::Published { + window_heads, + window_edges, + } => Ok(StepOutcome::Published { + window_heads, + window_edges, + }), + } +} + +/// 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. +/// +/// 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)) +} + +/// 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)) + } + } +} + +/// 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. +/// `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); + }; + 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(); + let before = release_txn_snap(host)?; + host.scope_state_mut::() + .expect("reservation keeps the installed heap") + .commit_late(reservation, raw); + 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)) +} + +#[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) +} + +/// 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()) +} + +/// One saved-tail reading around an automatic Release handoff. +/// +/// `marked` and `late` come from the tail itself. This does not resume it. +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ReleaseTxnSnap { + pub tail: SavedTailState, + pub marked: u32, + pub late: u32, +} + +/// Readings taken immediately before `commit_late` and after the root store. +/// Absent when that handoff did not store a root. +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ReleaseTxnWitness { + pub before: ReleaseTxnSnap, + pub after: ReleaseTxnSnap, +} + +/// Returns the committed handoff readings, if this execution stored one. +#[cfg(test)] +pub fn release_txn_witness(host: &HostContext) -> 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> { + 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. +/// +/// 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 +/// not a guest `collectgarbage` step. +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) +} + +/// 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 host + .scope_state::() + .is_some_and(LuaHeap::has_sweep_tail) + { + return Err(HeapError::SweepPending); + } + 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)?; + } + with_heap(host, |heap| Ok(heap.sweep_observing(marked.modes, observe))) +} + +fn retire_doomed_token(host: &mut HostContext, token: table::DoomedToken) -> Result<(), HeapError> { + match token.kind { + HandleKind::Table => retire_typed_token::(host, token), + HandleKind::Userdata => retire_userdata_token(host, token), + HandleKind::Closure | HandleKind::Upvalue => Err(HeapError::WrongKind), + } +} + +/// Closes one doomed userdata token after confirming that the open resource +/// payload names the exact Lua slot the mark captured. +/// +/// The slot must still store the captured raw handle at the same generation. +/// The typed borrow validates the Core arena, generation, concrete `TypeId`, +/// and the `lua.userdata` key, and its payload must equal the handle derived +/// from that slot record. A same-type token for another (even rooted) userdata +/// is [`HeapError::TokenMismatch`] and is not closed. The read-only borrow is +/// released before the close runs. An already-retired handle keeps the +/// existing clear-or-error branch. A `Pending` result is an error. +fn retire_userdata_token( + host: &mut HostContext, + token: table::DoomedToken, +) -> Result<(), HeapError> { + let handle = + vm::ResourceHandle::from_raw(token.raw).map_err(|_| HeapError::CarrierOutOfRange)?; + let expected = with_heap(host, |heap| heap.bound_userdata_for_token(&token))?; + let retired = match host + .borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + { + Ok(borrowed) => { + if borrowed.get().userdata() != expected { + return Err(HeapError::TokenMismatch); + } + None + } + Err(error) => { + if !retired_token(&error) { + return Err(HeapError::from_scope(error)); + } + Some(error) + } + }; + if let Some(error) = retired { + let cleared = with_heap(host, |heap| Ok(heap.clear_exact_token(token)))?; + return if cleared { + Ok(()) + } else { + Err(HeapError::from_scope(error)) + }; + } + with_heap(host, |heap| { + heap.note_token_close(); + Ok(()) + })?; + match host.close_resource::(handle, vm::ResourceCloseReason::Requested) { + Ok(vm::resource::CloseProgress::Ready) => {} + Ok(_) => { + return Err(HeapError::Scope( + "lua typed resource close did not finish synchronously".to_string(), + )); + } + Err(error) => { + if !retired_token(&error) { + return Err(HeapError::from_scope(error)); + } + let cleared = with_heap(host, |heap| Ok(heap.clear_exact_token(token)))?; + return if cleared { + Ok(()) + } else { + Err(HeapError::from_scope(error)) + }; + } + } + let cleared = with_heap(host, |heap| Ok(heap.clear_exact_token(token)))?; + if !cleared { + return Err(HeapError::StaleHandle); + } + Ok(()) +} + +/// Closes one doomed token through the concrete resource type that the slot +/// kind owns. The slot, generation, kind, and raw handle were captured at mark +/// time; the clear primitive rechecks that exact identity and leaves a reused +/// successor alone. A Pending close is an error and does not clear the binding +/// or release the slot. `ResourceAlreadyClosed` and `ResourceStale` retire the +/// token only when [`table::LuaHeap::clear_exact_token`] confirms the binding. +fn retire_typed_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) => { + if progress != vm::resource::CloseProgress::Ready { + return Err(HeapError::Scope( + "lua typed resource close did not finish synchronously".to_string(), + )); + } + let cleared = with_heap(host, |heap| Ok(heap.clear_exact_token(token)))?; + if !cleared { + return Err(HeapError::StaleHandle); + } + Ok(()) + } + Err(error) => { + if !retired_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)) + } + } + } +} + +fn retired_token(error: &vm::HostContextError) -> bool { + match error.kind() { + vm::HostContextErrorKind::Scope(vm::execution_scope::ExecutionScopeError::Resource( + resource, + )) + | vm::HostContextErrorKind::Resource(resource) => matches!( + resource.code(), + vm::resource::ResourceErrorCode::ResourceAlreadyClosed + | vm::resource::ResourceErrorCode::ResourceStale + ), + _ => false, + } +} + +/// 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 +/// 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())) +} + +/// 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 +/// 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(|_| ()) +} + +/// 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()) +} + +/// 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) +} + +/// Saved mark cursor. Absent means no saved mark. Does not take, scan, or write. +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SavedMarkWatch { + pub phase: &'static str, + pub pending: bool, + pub cursor_owner: Option, + pub cursor_index: Option, + pub gray_len: u32, +} + +/// One existing edge record. `value_slot` is set only for a table value. +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SavedEdgeWatch { + pub index: u32, + pub value_slot: Option, + pub value_string: bool, +} + +/// Reads the saved mark cursor. Does not take the mark, scan, enqueue, or write. +#[cfg(test)] +pub fn saved_mark_watch(host: &HostContext) -> Option { + host.scope_state::()?.saved_mark_watch() +} + +/// Live marked bit. A missing heap or a stale handle is false. Does not scan. +#[cfg(test)] +pub fn table_marked(host: &HostContext, table: TableRef) -> bool { + host.scope_state::() + .is_some_and(|heap| heap.table_marked(table)) +} + +/// Saved gray-vector membership. Does not walk edges or push. +#[cfg(test)] +pub fn table_in_gray(host: &HostContext, table: TableRef) -> bool { + host.scope_state::() + .is_some_and(|heap| heap.table_in_gray(table)) +} + +/// Whether the current top frame already roots this table. Does not scan edges. +#[cfg(test)] +pub fn current_frame_roots_table(host: &HostContext, table: TableRef) -> bool { + let Some(heap) = host.scope_state::() else { + return false; + }; + let Some(frame) = heap.current_frame() else { + return false; + }; + heap.frame_roots_table(frame, table) +} + +/// Existing number-key record. `None` means the key is absent or the table is dead. +#[cfg(test)] +pub fn number_edge_watch(host: &HostContext, table: TableRef, key: f64) -> Option { + let (index, value_slot, value_string) = host + .scope_state::()? + .number_edge_watch(table, key)?; + Some(SavedEdgeWatch { + index, + value_slot, + value_string, + }) +} + +/// Existing UTF-8 record. Same read-only contract as [`number_edge_watch`]. +#[cfg(test)] +pub fn utf8_edge_watch(host: &HostContext, table: TableRef, key: &str) -> Option { + let (index, value_slot, value_string) = + host.scope_state::()?.utf8_edge_watch(table, key)?; + Some(SavedEdgeWatch { + index, + value_slot, + value_string, + }) +} + +/// 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 { + 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/handle.rs b/src/frontends/lua/heap/handle.rs new file mode 100644 index 0000000..52adad6 --- /dev/null +++ b/src/frontends/lua/heap/handle.rs @@ -0,0 +1,200 @@ +//! Private handles. They are not VM values and have no bare-integer ABI. + +/// Kind carried by a private handle. Table, closure, upvalue, and bare +/// userdata 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 a + /// scalar (boolean, binary64, string, or bytes), or is absent (nil). It has + /// no open or closed flag. + Upvalue, + /// A bare userdata node. It has no guest carrier and no Core resource + /// token. The private pending-finalizer slice can attach one metatable + /// reference with `set_userdata_metatable`; that reference is a strong + /// edge only in the private slice and is not a guest metamethod surface. + Userdata, +} + +/// 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. Guest values +/// are not built from these fields. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TableRef { + domain: u64, + slot: u32, + generation: u32, + kind: HandleKind, +} + +impl TableRef { + /// 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, + 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 + } +} + +/// 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, a scalar (boolean, binary64, string, +/// or bytes), 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 + } +} + +/// Domain-checked reference to one bare userdata node. +/// +/// Construction stays inside the heap. A guest `Value` is not a +/// `UserdataRef`. A bare node has no environment or payload. The private +/// pending-finalizer slice stores one optional metatable reference on the +/// slot and can retain the node for a future finalizer consumer; it still has +/// no guest carrier. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct UserdataRef { + domain: u64, + slot: u32, + generation: u32, + kind: HandleKind, +} + +impl UserdataRef { + pub(super) fn userdata(domain: u64, slot: u32, generation: u32) -> Self { + Self { + domain, + slot, + generation, + kind: HandleKind::Userdata, + } + } + + /// 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. Userdata 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..afe78f8 --- /dev/null +++ b/src/frontends/lua/heap/resource.rs @@ -0,0 +1,87 @@ +//! 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::ResourceTypeKey; +use vm::host_extension::HostResourceType; +use vm::resource::HostResource; + +use super::handle::{TableRef, UserdataRef}; + +/// 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"; +} + +/// Public object capability for one private typed userdata node. +/// +/// This is a separate concrete resource type and catalog key from +/// [`LuaTableResource`]. A table token is not accepted for a userdata slot. +/// The payload carries the exact Lua domain, kind, slot, and generation that +/// the heap bound. A same-type token for another userdata has the same key but +/// a different payload, so the checked borrow rejects it. +/// +/// It uses the default synchronous close, which returns +/// [`CloseProgress::Ready`](vm::resource::CloseProgress). No path of this type +/// starts an asynchronous close. +#[derive(Debug)] +pub struct LuaUserdataResource { + userdata: UserdataRef, +} + +impl LuaUserdataResource { + pub(crate) fn new(userdata: UserdataRef) -> Self { + Self { userdata } + } + + /// The exact private handle stored in this token. + pub fn userdata(&self) -> UserdataRef { + self.userdata + } + + /// Catalog key used by `typed_resource_with_key`. + pub fn key() -> ResourceTypeKey { + ResourceTypeKey::new(Self::KEY).expect("lua.userdata is a valid resource key") + } +} + +impl HostResource for LuaUserdataResource { + fn resource_type_key() -> Option { + Some(Self::key()) + } +} + +impl HostResourceType for LuaUserdataResource { + const KEY: &'static str = "lua.userdata"; + const DESCRIPTION: &'static str = "Lua userdata"; +} diff --git a/src/frontends/lua/heap/table.rs b/src/frontends/lua/heap/table.rs new file mode 100644 index 0000000..410a591 --- /dev/null +++ b/src/frontends/lua/heap/table.rs @@ -0,0 +1,7321 @@ +//! Non-moving mark/sweep storage for tables, closures, shared cells, and bare +//! userdata. +//! +//! Closure, cell, and userdata 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. An object +//! key stores the slot, generation, and kind. A closure or userdata key is +//! that record with its own kind. It is not a private field id and not a +//! second edge table. + +use std::fmt; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +use vm::{ + CallOutcome, CallReturn, CallableKind, CallableTarget, CallableValue, HostContextError, + HostFunctionRegistry, HostFunctionSchema, HostImportSchema, HostParamSchema, HostTypeSchema, + Value, Vm, VmError, VmResult, +}; + +use super::handle::{ClosureRef, HandleKind, TableRef, UpvalueRef, UserdataRef}; +use super::{ + PendingFinalizerAction, PendingFinalizerNotCallable, TakenPendingFinalizer, + pending_finalizer_scalar_reject, +}; + +#[path = "table/mark.rs"] +mod mark; +#[path = "table/pending_close.rs"] +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; +pub use sweep::{ObserveFault, PublishedRead}; + +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; +/// 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. +#[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 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, +} + +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, + /// The bound token has the right type and key, but its payload names a + /// different object of that type. + TokenMismatch, + /// `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 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, + /// `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 + /// 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, + /// 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, + /// The closure-slot callable carrier does not admit an environment with + /// captures. Core's empty Lua environment container is not a capture. + CallableHasEnvironment, + /// This live closure generation already holds one carrier. Rebinding, + /// including with a different Arc, is refused and the stored Arc stays. + CarrierAlreadyBound, + /// This live closure generation holds no callable carrier. + CarrierNotBound, +} + +impl HeapError { + pub(super) fn from_scope(error: HostContextError) -> Self { + Self::Scope(error.to_string()) + } +} + +fn guest_import_fault(error: HeapError) -> VmError { + VmError::HostError(format!("lua heap: {error:?}")) +} + +/// The raw Lua name of the one-layer call field on a metatable. +/// +/// It is stored as ordinary UTF-8, not a numeric field id. The one-argument +/// admission callback and the two-argument raw-field handoff share this name. +const RAW_CALL_FIELD: &str = "__call"; + +/// Checks the exact compiled shape a controlled guest callable must have and +/// returns its real capture count from this VM's program. +/// +/// Both private guest imports use this. The count is read from the prototype +/// the invoking VM compiled, never from a caller-supplied number. A prototype +/// that is not one compiled Lua closure script function is a host error, so a +/// non-closure value cannot reach either heap admission. +fn script_callable_capture_slots(vm: &Vm, callable: &Arc) -> VmResult { + let prototype = vm + .program() + .callable_prototypes + .get(callable.prototype_id as usize) + .ok_or_else(|| { + VmError::HostError(format!( + "the guest callable names prototype {} outside this VM program", + callable.prototype_id + )) + })?; + if prototype.kind != CallableKind::Closure + || !matches!(prototype.target, CallableTarget::ScriptFunction(_)) + { + return Err(VmError::HostError( + "the guest callable prototype is not a compiled Lua script function".to_string(), + )); + } + Ok(prototype.capture_slots.len()) +} + +/// The only function that admits a guest callable. +/// +/// It is private and reachable only through the import registered by +/// [`LuaHeap::register_guest_callable_import`]. The VM dispatch supplies the +/// guest argument, so the callable is one value this VM's own execution +/// produced or received; there is no separate `(Arc, VM)` or `(Value, VM)` +/// entry to call. +/// +/// The capture count comes from this VM's compiled prototype for +/// `callable.prototype_id`, not from a caller-supplied number. The container +/// bit is not used: Core attaches an empty `CallableEnvironment` to every Lua +/// closure, including a chunk-level function with no captures. A prototype +/// with a real capture returns `false` and leaves the heap unchanged. A +/// zero-capture callable is allocated a fresh closure generation and stored +/// there; `true` reports that admission. +fn admit_guest_callable(vm: &mut Vm, args: &[Value]) -> VmResult { + let [value] = args else { + return Err(VmError::HostError( + "the guest callable import expects exactly one argument".to_string(), + )); + }; + let Value::Callable(callable) = value else { + return Err(VmError::HostError( + "the guest callable import expects a callable value".to_string(), + )); + }; + if callable.kind != CallableKind::Closure { + return Err(VmError::HostError( + "the guest callable import only admits a Lua closure".to_string(), + )); + } + let capture_slots = script_callable_capture_slots(vm, callable)?; + let callable = Arc::clone(callable); + if capture_slots != 0 { + return Ok(CallOutcome::Return(CallReturn::one(Value::Bool(false)))); + } + let mut host = vm.host_context(); + let closure = + super::with_heap(&mut host, LuaHeap::alloc_closure).map_err(guest_import_fault)?; + super::with_heap(&mut host, |heap| { + heap.store_guest_callable(closure, callable, capture_slots) + }) + .map_err(guest_import_fault)?; + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))) +} + +/// The only function that hands one guest callable into an existing raw +/// `__call` record. +/// +/// It is private and reachable only through the import registered by +/// [`LuaHeap::register_guest_callable_field_import`]. The two arguments are the +/// receiver's issued table carrier and the exact guest callable. The owner is +/// checked by [`LuaHeap::guest_class`], so a same-shaped ordinary array is not +/// the table. The callable is checked against this VM's compiled prototype and +/// must have zero captures. +/// +/// The result is `true` only when the existing record was replaced by a fresh +/// closure generation that owns the exact callable Arc and the record names +/// that generation. A missing record, an unsupported raw value, a captured +/// callable, a non-issued owner, a saved mark, a published Release tail, or a +/// full node vector returns `false`; a false result does not change the record, +/// the node vector, or any generation. A host scope failure is a host error. +/// +/// This is a direct Lua producer, not an arbitrary host injection check. The +/// guest argument is the issuance evidence; Core's `Vm::owns_callable` is not +/// visible here, so this entry does not claim that a callable returned by some +/// host belongs to this VM. +fn admit_guest_callable_to_raw_call(vm: &mut Vm, args: &[Value]) -> VmResult { + let [owner, target] = args else { + return Err(VmError::HostError( + "the raw call field import expects exactly two arguments".to_string(), + )); + }; + let Value::Callable(target) = target else { + return Ok(CallOutcome::Return(CallReturn::one(Value::Bool(false)))); + }; + if target.kind != CallableKind::Closure { + return Ok(CallOutcome::Return(CallReturn::one(Value::Bool(false)))); + } + let capture_slots = match script_callable_capture_slots(vm, target) { + Ok(capture_slots) => capture_slots, + Err(_) => return Ok(CallOutcome::Return(CallReturn::one(Value::Bool(false)))), + }; + if capture_slots != 0 { + return Ok(CallOutcome::Return(CallReturn::one(Value::Bool(false)))); + } + let callable = Arc::clone(target); + let mut host = vm.host_context(); + match super::with_heap(&mut host, |heap| { + heap.handoff_guest_callable_to_raw_call(owner, callable, capture_slots) + }) { + Ok(_) => Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))), + Err(HeapError::Scope(message)) => Err(guest_import_fault(HeapError::Scope(message))), + Err(_) => Ok(CallOutcome::Return(CallReturn::one(Value::Bool(false)))), + } +} + +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::TokenMismatch => write!(formatter, "typed token names another object"), + 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::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}"), + 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"), + Self::CallableHasEnvironment => { + write!(formatter, "lua closure carrier callable has an environment") + } + Self::CarrierAlreadyBound => { + write!(formatter, "lua closure carrier already bound") + } + Self::CarrierNotBound => write!(formatter, "lua closure carrier is not bound"), + } + } +} + +/// 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, + /// 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, 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, + /// 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, +} + +/// 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 { + /// 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, +} + +/// 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 { + index: u32, + 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, + Live { marked: bool }, + Retired, +} + +/// One issued value bound to a slot for its current generation. +/// +/// A table slot holds the VM array issued by [`LuaHeap::issue_carrier`]; a +/// closure slot holds the exact no-capture Core `Value::Callable` Arc that the +/// controlled `.lua` guest registration import admitted. The import derives +/// the capture count from the same VM's compiled prototype, so no caller can +/// pass a bare count. Neither variant is a mark edge, a root, or a Core +/// resource. [`LuaHeap::release_slot`] clears the field for the retired +/// generation, and a reused slot starts empty. +/// +/// Reusing the existing carrier field keeps the one-carrier-per-generation +/// invariant and prevents a table and a callable from coexisting. The enum is +/// one tag plus the same one-word pointer, so the per-slot record grows by one +/// word, the same as an extra `Option>` field would, without a second +/// field to reset on release and reuse. +enum SlotCarrier { + Table(Arc>), + Callable(Arc), +} + +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. + token: Option, + /// One carrier for this live generation. A table slot owns the VM array + /// so a field can read it back while the node is live. A closure slot owns + /// the exact Core script callable the private test entry registered. The + /// field is identity only, not an object edge, and does not participate in + /// marking. Release clears it before reuse. + carrier: Option, + /// Optional metatable. Not a field key and not an edge record. + metatable: Option<(u32, u32)>, + /// This live userdata was selected by the private pending-finalizer scan. + /// The Core token stays bound and the slot stays live until an explicit + /// retirement control removes the record. A later ordinary mark retains + /// the object and its metatable graph instead of releasing them. Weak + /// values that name this userdata are still cleared because the object is + /// unreachable from guest roots; weak keys keep the entry because the + /// selected object is retained for the eventual finalizer consumer. + pending_finalizer: bool, + /// Successor of this slot's pending-finalizer record, with the exact + /// successor generation. `None` at the queue tail and for a slot that is + /// not queued. The queue reader follows this link and does not read the + /// successor record. + pending_next: Option<(u32, u32)>, + /// Raw Core handle captured when this slot's pending record was enqueued. + /// The queue never rebuilds this value from the current token, so a later + /// rebind leaves the stored record unchanged. `None` when not queued. + pending_raw: Option, + /// Slot generation captured when this slot's pending record was enqueued. + /// Zero when not queued. + pending_generation: u32, + /// This generation was finalized without a queue record: either the + /// explicit test retirement control consumed its pending record, or the + /// selecting white-userdata pass found no raw `__gc` on its metatable. + /// Selection must not pick the object again, and a later raw `__gc` on + /// the same generation does not queue it. The flag never marks the object + /// and never keeps it alive; it only makes a live marked generation + /// value-dead for weak-value publication and for a hash value of a + /// `k`-only weak table. Release and slot reuse clear the flag. + finalizer_settled: bool, + /// Previous node in this heap's live-userdata chain, with its exact + /// generation. `None` at the head and for a slot that is not linked. + live_userdata_prev: Option<(u32, u32)>, + /// Next node in this heap's live-userdata chain, with its exact + /// generation. `None` at the tail and for a slot that is not linked. + live_userdata_next: Option<(u32, u32)>, + /// This slot is linked in the live-userdata chain at its current + /// generation. A new userdata links at the head; a release unlinks in + /// constant work before the generation advances. Every other kind is + /// false. + live_userdata_linked: bool, + /// Next slot in the current selecting pass's settlement journal, if this + /// slot is a journal node. The links live on the slots, so one settlement + /// is a constant number of slot writes and never grows or copies a vector. + /// A link left by an earlier pass is unreachable: the head is reset to + /// `None` when that pass starts or publishes, and a new append overwrites + /// this field before the slot can join the current chain. Release does not + /// read the journal; slot reuse clears both fields with the slot record. + settlement_next: Option, + /// Exact generation journalled by this node. Together with the slot index + /// this is the identity the rollback re-checks before clearing + /// `finalizer_settled`; zero means no current journal identity. + settlement_generation: u32, + /// Cached raw `__gc` lookup result when this table slot is a candidate + /// metatable. Valid only with `pending_gc_generation` and + /// `pending_gc_round`; a cache hit reads no edge record. A reused slot or + /// a later mark round does not inherit it. + pending_gc_generation: u32, + pending_gc_round: u64, + pending_gc_non_nil: bool, + /// 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, + /// Write version of the direct `__mode` record. Every store, in-place + /// replacement, and unlink bumps it, so a late byte read cannot combine + /// bytes from two writes. + mode_epoch: u32, + /// Generation whose parsed mode is stored for this slot. Zero means no + /// parse for the current generation. A reused slot cannot inherit the + /// mode of an older generation. + mode_generation: u32, + /// Mark round that wrote the parsed mode. The reset-sized mode vector is + /// rebuilt each round, but the slot generation survives; a stamp from an + /// earlier round is not a current observation of the direct field. + mode_round: u64, + /// Parsed weak bits for a slot outside the reset-sized `modes` vector. + /// Written together with `mode_generation` and `mode_round`; that triple + /// is the parse identity. The reset parse of an indexed slot stays in the + /// vector; this slot field replaces the old record-keyed map, so a late + /// parse neither inserts into a tree nor queries one. + mode_weak: WeakMode, + /// Current direct `__mode` record version inspected by this round, either + /// by the reset walk or by a finished late read, including a read whose + /// bytes name no weak side. This is not a weak-mode cache: `mode_generation` + /// and `mode_round` above stay unset for a strong read. The triple only + /// lets a first attachment skip a second read of the same field version. A + /// later write bumps `mode_epoch` and is still registered and read late. + mode_checked_generation: u32, + mode_checked_round: u64, + mode_checked_epoch: u32, + /// This table is linked in the saved mark's late-mode parse queue. The + /// links live on the slot, so a setter append and a release unlink are + /// constant work and allocate nothing. + late_mode_epoch: u64, + late_mode_prev: Option, + late_mode_next: Option, + /// One coalesced deferred metatable-transition check for this owner. + /// `old` is the first tuple and `new` is the latest tuple. + late_owner_epoch: u64, + late_owner_old: Option<(u32, u32)>, + /// Old weak observation captured when the check was queued. The old + /// metatable can be released before the queued check runs; this keeps the + /// value/key bits that were actually observed then. + late_owner_old_mode: Option, + late_owner_new: Option<(u32, u32)>, + late_owner_prev: Option, + late_owner_next: Option, + /// Deleted-mode discovery stamp for a slot past the reset-sized sidecar. + /// `discover_batch == 0` is unarmed. `discover_round` rejects a stamp from + /// an earlier mark: batch numbers restart at one, and a same-generation + /// metatable can outlive the mark that armed the stamp. + discover_generation: u32, + discover_batch: u32, + discover_round: u64, + /// Mark epoch in which this owner's ordinary scan opened a weak side. + /// Zero means no current-cycle weak start; an older epoch is inert. Set on + /// the target slot only, so a grown slot needs no vector entry. + rescan_epoch: u64, + /// This owner is linked in the current mark's rescan queue. + rescan_queued: bool, + /// Previous rescan-queue node. `None` at the head or when not queued. + rescan_prev: Option, + /// Next rescan-queue node. `None` at the tail or when not queued. + rescan_next: Option, + /// This marked target is linked in the current mark's deferred-replay + /// queue. The links live on the slot, so a replay append is constant work + /// and never touches the ordinary Gray chain. A tag from an older mark is + /// inert; release unlinks the slot before reuse. + late_target_epoch: u64, + late_target_prev: Option, + late_target_next: Option, + /// This marked slot is linked in the current mark's ordinary Gray LIFO. + /// The head and its exact slot generation live in `MarkState`; the two + /// neighbour links and this round's tag live here, beside but separate + /// from the late, rescan, and pending links. Push and pop are constant + /// work and never allocate, copy, or relocate a work vector. `epoch` is + /// the mark round that linked the node, so a link left by an abandoned + /// mark is inert; `generation` is the exact slot generation that was + /// linked. Release unlinks this node before the slot generation advances, + /// which is what keeps a middle item from cutting its successors off. + gray_epoch: u64, + gray_generation: u32, + gray_prev: Option, + gray_next: 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. +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()), + 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 { .. } + | EdgeValue::Userdata { .. } => 0, + } +} + +fn edge_payload(edge: &Edge) -> u64 { + key_payload(&edge.key) + value_payload(&edge.value) +} + +struct Edge { + /// 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. 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, + /// The saved mark has one deferred late-mode check for this record. + /// A new write updates this record in place; an unlink removes it. + late_epoch: u64, + late_owner: u32, + /// Latest table value written through this edge while the mode is + /// pending. Only this target is offered after the parse. + late_value: Option<(u32, u32)>, + /// Table-object key of a new key insertion while the mode is pending. + late_key: Option<(u32, u32)>, + late_prev: Option, + late_next: Option, +} + +enum EdgeValue { + Table { + 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, + }, + /// A bare userdata target. Not a guest table and not a Core number. + Userdata { + slot: u32, + generation: u32, + }, + /// 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, binary64, string, or bytes; that value is not + /// a key. + Scalar(Value), +} + +impl EdgeValue { + fn object_slot(&self) -> Option { + match self { + Self::Table { slot, .. } + | Self::Closure { slot, .. } + | Self::Upvalue { slot, .. } + | Self::Userdata { slot, .. } => Some(*slot), + 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. +/// +/// 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. 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, binary64, string, or bytes. Not a + /// table key. + Scalar(Value), +} + +/// One explicit root. Table, closure, upvalue, and bare userdata roots share +/// the root vector. +/// +/// Visible to the private host continuation. Not a public heap schema. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Rooted { + Table(TableRef), + Closure(ClosureRef), + Upvalue(UpvalueRef), + Userdata(UserdataRef), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum EdgeKey { + Field(u32), + Object { + slot: u32, + generation: u32, + kind: HandleKind, + }, + /// 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 { + 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()) + } + + fn userdata_key(key: UserdataRef) -> Self { + Self::identity(key.slot(), key.generation(), key.kind()) + } + + /// One object-key record. Table, closure, and userdata keys differ by `kind`. + fn identity(slot: u32, generation: u32, kind: HandleKind) -> Self { + Self::Object { + slot, + generation, + kind, + } + } + + /// 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 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" + } + + /// 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 + /// 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) + } + } +} + +/// 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, + start: u32, + width: u32, +} + +/// Counts the loops one collect actually ran. +/// +/// 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. 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 an owner chain. `metatable_edge_checks` counts +/// stored metatable refs followed from marked table or userdata nodes. A +/// collect with none stored does not read those slots, so the field-edge +/// counters stay the same as a heap that never had a metatable. +/// +/// `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 +/// 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, + 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 `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, + 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, + /// 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, + /// Parked rescan cursors advanced inside `unlink_at` after it has read the + /// old successor. Independent of `parked_cursor_repairs`. Not a pulse unit. + /// A full collect leaves this at zero. + pub parked_rescan_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 + /// 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, + /// Chain-head reads of an owner whose weak-value scan already started and + /// whose metatable later became strong. Not an ordinary first coloring, + /// and not the setter that only recorded the request. + pub owner_rescan_heads: u64, + /// Setter requests that recorded one such owner. A repeat does not + /// increment this. Not an outgoing edge visit and not a pulse unit. + pub owner_rescan_schedules: u64, + /// One capacity-slot read while looking for an owner of a metatable whose + /// direct value-weak `__mode` was deleted. Free and retired slots count. + /// This is not a live-node walk. The setter does not increment this. + /// One probe is one pulse unit. + pub mode_owner_probes: u64, + /// Comparisons with an indexed deleted-mode stamp: at most one per + /// capacity-slot probe. The setter does not compare stamps. Not a pulse + /// unit in addition to the probe. + pub mode_discover_compares: u64, + /// Deleted-mode identity records written outside mode-cache init. + /// Scalar cursor and batch changes do not write a record. Not a pulse unit. + pub mode_discover_writes: u64, + /// Matching direct `__mode` deletes that replaced this cycle's value-weak, + /// key-strong cache with the missing-field mode. One per real unlink, not + /// a slot walk and not a pulse unit. + pub mode_cache_updates: u64, + /// Direct `__mode` strings written on tables allocated after the indexed + /// cache was sized. One per metatable slot linked into the late parse + /// queue; a repeat write on the same slot reuses the queued marker and is + /// `mode_late_cancels`. This is the setter-side append only: bytes and + /// parsed stores are `weak_mode_bytes` and `mode_late_parsed`. + pub mode_late_registrations: u64, + /// O(1) slot/edge identity reads that route a setter or barrier through + /// the late window. Not a pulse unit. + pub mode_late_lookups: u64, + /// A write replaced or unlinked a direct `__mode` record whose slot was + /// already queued; the queued parse restarts from the new bytes. Not a + /// pulse unit and not a second registration. + pub mode_late_cancels: u64, + /// Parsed late modes stored for one metatable slot generation. One per + /// completed read, not one per indexed vector slot. No suffix is grown and + /// no indexed prefix is copied; the record-keyed store moves no vector. + pub mode_late_parsed: u64, + /// New deferred owner checks or edge writes. Bounded by owner slots and + /// edge records, never by mutation count. + pub mode_late_events: u64, + /// A repeat write updated an existing deferred owner check or edge write + /// in place. This is the coalescing path that keeps the backlog bounded. + pub mode_late_event_reuses: u64, + /// Deferred owner checks and edge writes consumed after every parse. + pub mode_late_deferred: u64, + /// Live slot records read by the private pending-finalizer selection scan. + /// One per live-userdata chain node in the separate selection phase; a + /// node that cannot be selected still counts, while a table, closure, + /// cell, free slot, and retired slot is never read by this walk. Not + /// charged by an ordinary collection. + pub pending_finalizer_scan_slots: u64, + /// Userdata slots newly retained by the private pending-finalizer + /// selection. One per record appended; an already pending userdata or a + /// non-qualifying slot does not increment this. Not a callback count. + pub pending_finalizers_selected: u64, + /// Pending-finalizer records offered as host-retained edges by a mark. + /// One per record read in the root phase, including a record whose exact + /// slot is no longer valid. Not a pulse unit and not a selection. + pub pending_finalizer_offers: u64, + /// Edge records read while resolving the raw `__gc` field of a candidate + /// metatable for the private pending-finalizer selection. One per record + /// in the owner chain; a cache hit from the same mark round and exact + /// metatable generation reads none. This is not a whole-owner scan. + pub pending_finalizer_gc_edge_checks: u64, + /// Raw `__gc` lookups started for the private pending-finalizer selection. + /// One per uncached candidate metatable. A cache hit does not increment + /// this and does not re-walk the chain. + pub pending_finalizer_gc_lookups: u64, + /// Test-only: settlement journal node appends performed by the selecting + /// scan. One per settled identity and at most one per `pulse(1)` unit. + /// No vector growth or prefix copy participates. + #[cfg(test)] + pub settlement_journal_appends: u64, + /// Test-only: settlement journal nodes actually visited by a failed-pass + /// rollback. One per node this pass appended; a successful publication + /// and Release visit no node and leave this at zero. + #[cfg(test)] + pub settlement_journal_visits: u64, + /// Test-only: pending-queue records visited by Release after a dead-slot + /// release. The bounded per-slot invariant must keep this at zero; the + /// ordinary release path reads only the released slot's own fields. + #[cfg(test)] + pub pending_release_queue_reads: u64, + /// Test-only: stored pending-queue records transferred out by a queue + /// extraction, including the extracted record itself. One front pop + /// charges one record and reads no successor; an exact removal charges its + /// removed record; a rolled-back suffix charges its records. This is + /// separate from the record-read count and does not count a tail append, + /// a publication, or a checkpoint header restore. + #[cfg(test)] + pub pending_queue_storage_moves: u64, + /// Test-only: slot records whose pending link fields the queue boundary + /// wrote. A tail append charges the new slot and, when non-empty, the old + /// tail; a front pop charges the old head; a publication charges none. + /// This is a real per-slot write count, not a logical pulse count. + #[cfg(test)] + pub pending_queue_slot_writes: u64, + /// Test-only: header metadata boundaries written by the queue. One append, + /// one front pop, one publication, one exact removal, or one checkpoint + /// rollback is one header write regardless of the number of fields. + #[cfg(test)] + pub pending_queue_header_writes: 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 { + /// 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, + /// Pending-close elements appended. Host mark only; pure collect is 0. + pub pending_close_pushed: u64, + /// 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, + /// 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, + /// Slot state entries initialized for this mark's rescan bookkeeping: one + /// per weak owner's first start, tagged on that target slot. A repeat or a + /// setter reuses the tag and does not count another. Bounded by the node + /// limit. 0 when this cycle never started a weak owner scan. + /// Not the deleted-mode sidecar: that one is `mode_discover_inited`. + pub owner_rescan_inited: u64, + /// Deleted-mode sidecar slots pushed during mode-cache init. One per + /// `step_mode_init` unit, and the same capacity as that wave's + /// `weak_modes_inited`. A setter and a gray probe do not push. This is + /// not `owner_rescan_inited`, which is a separate all-at-once zero of + /// rescan bits. + pub mode_discover_inited: u64, + /// Owners linked into the rescan queue. One per owner per mark. A repeat + /// setter does not link again and does not increment this. + pub owner_rescan_pushed: u64, +} + +/// A stored token identified while marking. Close checks this slot, +/// generation, and kind directly; it does not search the slot vector. The +/// kind selects the concrete typed resource that owns the raw handle. +#[derive(Clone, Copy, Debug)] +pub(super) struct DoomedToken { + pub(super) raw: u64, + pub(super) slot: u32, + pub(super) generation: u32, + pub(super) kind: HandleKind, +} + +/// Parsed weak modes for one collect. Built during the clear-mark slot walk +/// from each table's direct `__mode` pointer, and resolved into one value per +/// snapshot record for 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>, + /// Mark round that owns the parsed modes. A slot record carries the round + /// that wrote its parse, so a reused generation or an earlier round + /// cannot contribute a stale weak bit to this snapshot. + round: u64, +} + +/// 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, + values: bool, +} + +/// 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, + limits: HeapLimits, + slots: Vec, + free_list: 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>, + frames: Vec, + next_frame_generation: u32, + collections: u32, + last_marked: u32, + peak_nodes: u32, + 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, + /// Source of the per-mark rescan epoch stored on slot records. It never + /// returns to zero, so an old tag cannot match a new mark after reuse. + rescan_epoch: u64, + /// 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, + /// The single userdata slot the typed issuer has reserved, before its + /// Core token is published. The raw field appears only after the real + /// Core registration succeeded. Ordinary borrows and the pending-close + /// enumeration do not read this record, so a staged token is never a + /// guest value. A completed mark retains a registered (`raw` is `Some`) + /// reservation as a host edge, and the next normal issuance closes and + /// releases it before reserving again. + pending_userdata: Option, + /// Userdata slots retained by the private pending-finalizer selection. + /// + /// Each record names one exact live userdata generation and the Core raw + /// handle that its slot still binds. Selection appends at most one record + /// per userdata; an ordinary mark offers every record as a host-retained + /// edge so no live token is closed or orphaned while it waits for a + /// consumer. The explicit retirement test control removes the record and + /// clears the slot flag; a later collection may then close the token and + /// release the slot. A valid record's slot is retained and cannot reach + /// Release, so there is no release-time queue repair. + /// + /// The storage is private: every record read goes through + /// [`PendingQueue`]'s counted boundary, including the test-only release + /// meter. No call site counts by hand. + pending_finalizers: PendingQueue, + /// Head and tail of the intrusive live-userdata chain, with the exact + /// generation of each endpoint. A new userdata links at the head and a + /// release unlinks its own node in constant work. The chain is the + /// private pending selection order: allocation-reverse inside one cohort + /// and no batch sort or vector rebuild. Release reads only the released + /// slot's own links; it does not walk this chain. + live_userdata_head: Option<(u32, u32)>, + live_userdata_tail: Option<(u32, u32)>, + /// Head and length of the current selecting pass's settlement journal. + /// + /// Each node is a live userdata slot whose `settlement_next` links the + /// previous head and whose `settlement_generation` names the exact + /// identity. An append is one flag write, one link write, one generation + /// write, and one head write: a constant upper bound per `pulse(1)` + /// settlement unit, with no vector growth or prefix copy. A successful + /// publication drops the journal by resetting these fields; it does not + /// visit the links, and Release does not read them. A failed pass walks + /// exactly its own chain, clears those flags, and stops. That rollback + /// work is charged to the failure path, never to the next mark's first + /// pulse and never to Release. + settlement_head: Option, + #[cfg(test)] + settlement_journal_len: u32, + /// Owner chains opened by the legacy table rollback edge walk. + /// Test-only observation: an empty userdata reservation rollback must + /// leave this unchanged, so its work stays independent of the graph size. + #[cfg(test)] + rollback_owner_visits: u64, + /// Slot indices actually indexed by sweep selection and by the + /// registered-reservation identity guard. Test-only: the pushes record + /// the real indexing points and never read another slot. Tests clear the + /// trace after Mark, so a shared Select pulse trace starts at the cursor. + /// Interior mutability keeps the identity guard's `&self` read-only. + #[cfg(test)] + selection_slot_trace: std::cell::RefCell>, + /// Test-only: edge-record indices read while resolving a candidate + /// metatable's raw `__gc`. Each push is one real record read; a cache hit + /// adds none. The pairs are `(metatable_slot, edge_record_index)`. + #[cfg(test)] + pending_gc_edge_trace: std::cell::RefCell>, + /// Test-only: live-userdata chain nodes read by the private selection, in + /// visit order. Each entry is one real slot-record read and the exact + /// generation the chain cursor named, so a test can distinguish a real + /// chain walk from a counter that merely reports the number of candidates. + /// The shared handle lets the test-only selecting driver take a per-pulse + /// delta while its mark session still borrows the heap. + #[cfg(test)] + pending_live_trace: LiveTrace, + /// Test-only: exact pending-record identities read by the Roots offer, in + /// visit order. One entry is one real queue record read of that cursor, + /// including a record whose raw binding no longer matches. A test can take + /// a per-pulse delta while the selecting mark session still borrows the + /// heap, so the offer cursor is observed without a head search. + #[cfg(test)] + pending_offer_trace: LiveTrace, + /// Test-only: pending-finalizer records whose exact typed owner borrow and + /// slot/generation check passed in the pre-publication verifier, in record + /// order. A refused pass leaves the successes that happened before the + /// first mismatch, so a test can prove "C verified, then A failed" without + /// substituting an offer, selection, or materialized-record count. + #[cfg(test)] + owner_verification_trace: std::cell::RefCell>, + /// Test-only: identities actually visited by a failed settlement + /// journal rollback, in visit order. A successful pass and Release leave + /// it empty, so the trace distinguishes precise cleanup from a drain + /// deferred to the next pulse or to Release. + #[cfg(test)] + settlement_journal_trace: std::cell::RefCell>, + /// Test-only anti-control for the secondary propagation. When armed, a + /// selected pending userdata is still marked and protected, but its + /// metatable edge is not followed while its owner head is scanned. This + /// proves the graph-retention assertion depends on that real propagation. + /// It is not a callback path and never fabricates a close or a status. + #[cfg(test)] + skip_pending_finalizer_metatable: bool, + /// Test-only anti-control for the bounded Release invariant. When armed, + /// the next publish clears this exact pending slot's mark bit. Shared + /// Select must then refuse the slot before Snapshot or Owners, so no weak + /// edge is published and no release starts. + #[cfg(test)] + reclaim_pending_slot: Option, + /// Test-only observation: closure handles admitted by the controlled guest + /// import, in admission order. Written only after a successful store. The + /// vector does not admit, retain, or expose a callable; slot refusal + /// tests read it and the file-entry witness uses it to find the exact + /// generations. No non-test code can reach the field. + #[cfg(test)] + admitted_guest_callables: Vec, +} + +/// Test-only shared handle for the live-userdata chain-read trace. +/// +/// The heap must stay `Send`, so this uses an `Arc>` rather than an +/// `Rc`. The `borrow`/`borrow_mut` names keep the existing internal write site +/// and accessors unchanged; the selecting driver takes a clone of the handle +/// before it borrows the heap for a mark session, then reads each pulse delta +/// without touching the heap. +#[cfg(test)] +#[derive(Clone)] +struct LiveTrace(std::sync::Arc>>); + +#[cfg(test)] +impl LiveTrace { + fn new() -> Self { + Self(std::sync::Arc::new(std::sync::Mutex::new(Vec::new()))) + } + + fn share(&self) -> Self { + self.clone() + } + + fn borrow(&self) -> std::sync::MutexGuard<'_, Vec<(u32, u32)>> { + self.0.lock().expect("live trace lock") + } + + fn borrow_mut(&self) -> std::sync::MutexGuard<'_, Vec<(u32, u32)>> { + self.0.lock().expect("live trace lock") + } +} + +/// One typed userdata retained after the ordinary mark converged. +/// +/// `raw` is the exact Core handle still bound in `slot`; the selection and the +/// host pre-publication check both read that same binding, so a record cannot +/// name a different object. The record is not a root vector entry, is not a +/// guest value, and is visible only to this table module and its heap parent. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct PendingFinalizer { + pub(super) slot: u32, + pub(super) generation: u32, + pub(super) raw: u64, +} + +/// The one-layer raw `__call` result on one receiver's own current instance +/// metatable. A table-valued `__call` is `NotClosure`; this slice never +/// dispatches it again. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CurrentRawCall { + WithoutCall, + NotClosure, + Closure(ClosureRef), +} + +mod pending_queue { + //! Private storage for retained pending-finalizer records. + //! + //! The queue is a per-slot singly linked FIFO, not a `VecDeque`. Every record + //! lives on the exact userdata slot it names; the queue header stores only + //! `head`, `tail`, `len`, and the published-prefix length. A tail append writes + //! the new slot, at most the old tail slot, and the header, so it cannot + //! relocate or copy an old record. A front pop reads the old head record (which + //! carries the successor identity) and never reads the successor record. A + //! successful private publication only raises the published length. + //! + //! Each slot keeps the record's exact generation and raw-handle snapshot plus + //! the successor's `(slot, generation)` identity. The queue never rebuilds a + //! record from the slot's current token, so a later rebind cannot change an + //! already stored record. The links use their own fields and never borrow the + //! live-userdata chain or the settlement journal. + //! + //! Every stored-record read goes through one of the accessors below, which is + //! the single place where the test-only read meter observes a real queue read. + //! The write boundary is separate: `slot_writes` counts slot records whose + //! pending link fields the queue wrote, `header_writes` counts header + //! boundaries, and `transfers` counts records extracted from the queue + //! (including a front pop, an exact removal, and a rolled-back suffix). + //! `write_trace` records the actual slot indices written, in order, so a test + //! can prove a tail append touches only the new slot and at most the old tail. + //! No caller outside this module can index a stored record: no positional + //! accessor or raw iterator is exported. + //! + //! A failed selecting pass rolls back from the round-start checkpoint: the + //! queue tail identity and length observed before the pass appended anything. + //! It detaches the new tail, walks only that new segment, and restores the + //! header to the checkpoint. It never walks or moves the older segment and + //! never substitutes the published length for the checkpoint. Middle removal + //! (the test retirement control) may search linearly for the predecessor so no + //! production reverse link is needed. + + use std::cell::Cell; + + use super::super::HandleKind; + use super::{PendingFinalizer, Slot, SlotState}; + + /// Exact queued-record identity: the slot index and its generation. + pub(crate) type PendingCursor = (u32, u32); + + /// The queue boundary captured before a selecting pass appended anything. + /// + /// `tail` is the exact identity of the last record and `len` is the queue + /// length at that moment. The pair, not the published length, is the only + /// rollback base for that pass. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub(crate) struct PendingCheckpoint { + pub(super) tail: Option, + pub(super) len: usize, + } + + /// Header and link accessors for the slot-linked FIFO. + #[derive(Default)] + pub(super) struct PendingQueue { + head: Option, + tail: Option, + len: usize, + /// Number of leading records a successful private publication made + /// consumable. Always at most `len`. + published: usize, + /// Test-only count of records read through this boundary. + #[cfg(test)] + reads: Cell, + /// Test-only count of slot records whose pending link fields this queue + /// wrote. One tail append charges the new slot and, when non-empty, the + /// old tail; a front pop charges the old head. + #[cfg(test)] + slot_writes: Cell, + /// Test-only count of header metadata writes. One append, one pop, one + /// publication, one exact removal, or one checkpoint rollback is one + /// header boundary, regardless of how many header fields change. + #[cfg(test)] + header_writes: Cell, + /// Test-only count of records extracted from the queue. A front pop, an + /// exact removal, and a rolled-back suffix record each count once. + #[cfg(test)] + transfers: Cell, + /// Test-only actual slot indices written by this queue, in write order. + #[cfg(test)] + write_trace: std::cell::RefCell>, + } + + impl PendingQueue { + pub(super) fn len(&self) -> usize { + self.len + } + + /// The consumable prefix length. This is a header read only. + pub(super) fn published_len(&self) -> usize { + self.published + } + + /// First queued record identity, if any. Header read only. + pub(super) fn head(&self) -> Option { + self.head + } + + /// Round-start tail identity and length. Header reads only. + pub(super) fn checkpoint(&self) -> PendingCheckpoint { + PendingCheckpoint { + tail: self.tail, + len: self.len, + } + } + + /// Appends one record at the tail. + /// + /// The new slot stores the exact generation/raw snapshot and a `None` + /// successor. A non-empty queue also writes the old tail's successor + /// identity. No other slot and no old record is read or moved. + pub(super) fn push(&mut self, slots: &mut [Slot], record: PendingFinalizer) { + let identity = (record.slot, record.generation); + { + let slot = &mut slots[record.slot as usize]; + debug_assert!(!slot.pending_finalizer, "a record slot is appended twice"); + slot.pending_finalizer = true; + slot.pending_generation = record.generation; + slot.pending_raw = Some(record.raw); + slot.pending_next = None; + } + self.slot_write(record.slot); + if let Some((tail_slot, tail_generation)) = self.tail { + let tail = &mut slots[tail_slot as usize]; + debug_assert_eq!(tail.generation, tail_generation); + debug_assert_eq!(tail.pending_generation, tail_generation); + debug_assert!(tail.pending_finalizer); + debug_assert!(tail.pending_next.is_none()); + tail.pending_next = Some(identity); + self.slot_write(tail_slot); + } else { + self.head = Some(identity); + } + self.tail = Some(identity); + self.len += 1; + self.header_write(); + } + + /// The published head record, if the ready prefix is non-empty. + /// + /// This reads exactly the head slot record; it does not read a successor. + pub(super) fn published_front(&self, slots: &[Slot]) -> Option { + if self.published == 0 { + return None; + } + let (slot_index, generation) = self.head?; + let slot = slots.get(slot_index as usize)?; + self.read(); + if slot.generation != generation + || !slot.pending_finalizer + || slot.pending_generation != generation + { + return None; + } + let raw = slot.pending_raw?; + Some(PendingFinalizer { + slot: slot_index, + generation, + raw, + }) + } + + /// Pops the expected published front. + /// + /// One record read returns the snapshotted record and its successor + /// identity. The successor record itself is not read: the pop moves the + /// head cursor to the identity the old head stored. The expected value is + /// the record the caller just read from `published_front`; the identity + /// assertion is debug-only because those two calls are adjacent and no + /// mutation can intervene. + pub(super) fn pop_published_front( + &mut self, + slots: &mut [Slot], + expected: PendingFinalizer, + ) -> Option { + if self.published == 0 { + return None; + } + let (slot_index, generation) = self.head?; + let slot = slots.get_mut(slot_index as usize)?; + self.read(); + if slot.generation != generation + || !slot.pending_finalizer + || slot.pending_generation != generation + { + return None; + } + let raw = slot.pending_raw?; + let record = PendingFinalizer { + slot: slot_index, + generation, + raw, + }; + let next = slot.pending_next; + debug_assert_eq!(record, expected); + slot.pending_finalizer = false; + slot.pending_generation = 0; + slot.pending_raw = None; + slot.pending_next = None; + self.slot_write(slot_index); + self.header_write(); + self.transfer(); + self.published -= 1; + self.len -= 1; + self.head = next; + if self.len == 0 { + debug_assert!(next.is_none()); + self.tail = None; + } else { + debug_assert!(next.is_some()); + } + Some(record) + } + + /// Iterates stored records in queue order. Each yielded record is one read; + /// the successor identity comes from the record just read. + pub(super) fn iter<'a>(&'a self, slots: &'a [Slot]) -> PendingQueueIter<'a> { + PendingQueueIter { + queue: self, + slots, + next: self.head, + } + } + + /// One queued record read for the host-retained edge offer in Roots. + /// + /// The cursor's exact slot record is read once. `retained` is the exact + /// live userdata identity if that record still names its own pending + /// generation and its snapshotted raw handle still matches the slot's + /// current token; `next` is the successor identity stored on the same + /// record. A record whose generation no longer matches, or whose pending + /// flag is gone, ends the offer cursor; a record whose raw handle is + /// rebound stays in the queue and is skipped without ending it, which + /// preserves the ordinary/parked mark's existing mis-binding behavior. + pub(super) fn offer( + &self, + slots: &[Slot], + cursor: PendingCursor, + ) -> (Option<(u32, u32)>, Option) { + let (slot_index, generation) = cursor; + let Some(slot) = slots.get(slot_index as usize) else { + return (None, None); + }; + self.read(); + if slot.generation != generation + || !slot.pending_finalizer + || slot.pending_generation != generation + { + return (None, None); + } + let next = slot.pending_next; + let exact = slot.kind == HandleKind::Userdata + && !slot.finalizer_settled + && slot.pending_raw.is_some_and(|raw| slot.token == Some(raw)) + && matches!(slot.state, SlotState::Live { .. }); + (exact.then_some((slot_index, generation)), next) + } + + /// Makes every currently stored record consumable. This is one header + /// write. Records appended afterwards stay unpublished until the next + /// successful private publication. + pub(super) fn publish_all(&mut self) { + self.published = self.len; + self.header_write(); + } + + /// Removes one exact record by identity (slot, generation, snapshotted + /// raw). This is the test-only retirement path: it may walk stored + /// records to find the predecessor, so it needs no production reverse + /// link. A head removal reads the old head's successor identity and does + /// not read the successor record. One record is read for every visited + /// position; the removed record is one transfer. + #[cfg(test)] + pub(super) fn remove_exact( + &mut self, + slots: &mut [Slot], + slot_index: u32, + generation: u32, + raw: u64, + ) -> Option { + let mut previous: Option = None; + let mut cursor = self.head; + let mut position = 0usize; + while let Some((cursor_slot, cursor_generation)) = cursor { + let record_slot = slots.get(cursor_slot as usize)?; + self.read(); + if record_slot.generation != cursor_generation + || !record_slot.pending_finalizer + || record_slot.pending_generation != cursor_generation + { + return None; + } + let record_raw = record_slot.pending_raw?; + if cursor_slot == slot_index && cursor_generation == generation && record_raw == raw + { + let next = record_slot.pending_next; + match previous { + Some((previous_slot, previous_generation)) => { + let predecessor = &mut slots[previous_slot as usize]; + debug_assert_eq!(predecessor.generation, previous_generation); + debug_assert!(predecessor.pending_finalizer); + debug_assert_eq!( + predecessor.pending_next, + Some((cursor_slot, cursor_generation)) + ); + predecessor.pending_next = next; + self.slot_write(previous_slot); + } + None => { + self.head = next; + } + } + if self.tail == Some((cursor_slot, cursor_generation)) { + self.tail = previous; + } + if position < self.published { + self.published -= 1; + } + self.len -= 1; + let removed = &mut slots[cursor_slot as usize]; + removed.pending_finalizer = false; + removed.pending_generation = 0; + removed.pending_raw = None; + removed.pending_next = None; + self.slot_write(cursor_slot); + self.header_write(); + self.transfer(); + return Some(PendingFinalizer { + slot: cursor_slot, + generation: cursor_generation, + raw, + }); + } + previous = Some((cursor_slot, cursor_generation)); + cursor = record_slot.pending_next; + position += 1; + } + None + } + + /// Removes and returns every record appended after `base`. + /// + /// The old tail's successor names the first new record, so the walk starts + /// at the new segment and never traverses the older segment. The old tail + /// is the only boundary record read (through its own successor field). + /// The header is restored to `base`, and the published prefix is clamped + /// to it. A checkpoint at or beyond the current length is a no-op. + pub(super) fn discard_from_checkpoint( + &mut self, + slots: &mut [Slot], + base: PendingCheckpoint, + ) -> Vec { + let mut discarded = Vec::new(); + if base.len >= self.len { + return discarded; + } + let first = match base.tail { + Some((tail_slot, tail_generation)) => { + let tail = slots + .get_mut(tail_slot as usize) + .expect("checkpoint tail slot"); + debug_assert_eq!(tail.generation, tail_generation); + debug_assert_eq!(tail.pending_generation, tail_generation); + debug_assert!(tail.pending_finalizer); + let first = tail.pending_next; + if first.is_none() { + debug_assert!(false, "a non-empty new segment has a first record"); + return discarded; + } + tail.pending_next = None; + self.slot_write(tail_slot); + first + } + None => { + debug_assert_eq!(base.len, 0); + self.head + } + }; + let Some(mut cursor) = first else { + debug_assert!(false, "a non-empty new segment has a first record"); + return discarded; + }; + loop { + let (slot_index, generation) = cursor; + let Some(record_slot) = slots.get_mut(slot_index as usize) else { + break; + }; + self.read(); + if record_slot.generation != generation + || !record_slot.pending_finalizer + || record_slot.pending_generation != generation + { + break; + } + let Some(raw) = record_slot.pending_raw else { + break; + }; + let next = record_slot.pending_next; + if record_slot.token == Some(raw) { + record_slot.pending_finalizer = false; + } + record_slot.pending_generation = 0; + record_slot.pending_raw = None; + record_slot.pending_next = None; + self.slot_write(slot_index); + discarded.push(PendingFinalizer { + slot: slot_index, + generation, + raw, + }); + self.transfer(); + match next { + Some(next) => cursor = next, + None => break, + } + } + self.len = base.len; + self.tail = base.tail; + self.published = self.published.min(base.len); + if base.len == 0 { + self.head = None; + } + self.header_write(); + discarded + } + + /// Test-only counts of reads, slot writes, header writes, and transfers + /// since construction. This does not clear them and reads no record. + #[cfg(test)] + pub(super) fn counts(&self) -> (u64, u64, u64, u64) { + ( + self.reads.get(), + self.slot_writes.get(), + self.header_writes.get(), + self.transfers.get(), + ) + } + + /// Returns the reads since the previous take and clears the count. + #[cfg(test)] + pub(super) fn take_reads(&mut self) -> u64 { + self.reads.replace(0) + } + + /// Returns the slot writes since the previous take and clears the count. + #[cfg(test)] + pub(super) fn take_slot_writes(&mut self) -> u64 { + self.slot_writes.replace(0) + } + + /// Returns the header writes since the previous take and clears the count. + #[cfg(test)] + pub(super) fn take_header_writes(&mut self) -> u64 { + self.header_writes.replace(0) + } + + /// Returns the transferred records since the previous take and clears it. + #[cfg(test)] + pub(super) fn take_transfers(&mut self) -> u64 { + self.transfers.replace(0) + } + + /// Returns the actual slot indices written since the previous take. + #[cfg(test)] + pub(super) fn take_write_trace(&mut self) -> Vec { + std::mem::take(&mut *self.write_trace.borrow_mut()) + } + + #[cfg(test)] + fn read(&self) { + self.reads.set(self.reads.get() + 1); + } + + #[cfg(test)] + fn slot_write(&self, slot: u32) { + self.slot_writes.set(self.slot_writes.get() + 1); + self.write_trace.borrow_mut().push(slot); + } + + #[cfg(test)] + fn header_write(&self) { + self.header_writes.set(self.header_writes.get() + 1); + } + + #[cfg(test)] + fn transfer(&self) { + self.transfers.set(self.transfers.get() + 1); + } + + #[cfg(not(test))] + fn read(&self) {} + + #[cfg(not(test))] + fn slot_write(&self, _slot: u32) {} + + #[cfg(not(test))] + fn header_write(&self) {} + + #[cfg(not(test))] + fn transfer(&self) {} + } + + /// Counted iterator over the slot-linked queue. It yields owned records, so + /// the caller never reaches the slot link fields directly. + pub(super) struct PendingQueueIter<'a> { + queue: &'a PendingQueue, + slots: &'a [Slot], + next: Option, + } + + impl Iterator for PendingQueueIter<'_> { + type Item = PendingFinalizer; + + fn next(&mut self) -> Option { + let (slot_index, generation) = self.next?; + let slot = self.slots.get(slot_index as usize)?; + self.queue.read(); + if slot.generation != generation + || !slot.pending_finalizer + || slot.pending_generation != generation + { + self.next = None; + return None; + } + let raw = slot.pending_raw?; + self.next = slot.pending_next; + Some(PendingFinalizer { + slot: slot_index, + generation, + raw, + }) + } + } +} +use pending_queue::{PendingCheckpoint, PendingCursor, PendingQueue}; + +/// One userdata that passed the slot-local selection checks and whose +/// metatable's raw `__gc` field still has to be resolved by a metered walk. +/// It carries no value and grants no write by itself. +#[derive(Clone, Copy, Debug)] +pub(super) struct PendingCandidate { + pub(super) slot: u32, + pub(super) generation: u32, + pub(super) metatable_slot: u32, + pub(super) metatable_generation: u32, +} + +/// One typed-issuer userdata reservation, keyed by its exact slot and +/// generation. `raw` is the registered Core handle that a published binding +/// does not yet own. +#[derive(Clone, Copy, Debug)] +struct PendingUserdata { + slot: u32, + generation: u32, + raw: Option, +} + +/// 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) +} + +/// Where a publish-only sweep stopped. A completion means neither a dead slot +/// nor a retained pending finalizer 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), +} + +/// 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; + + /// 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(), + edge_slots: Vec::new(), + edge_free_head: None, + occupied_edges: 0, + live_edge_count: 0, + metatable_edges: 0, + roots: Vec::new(), + frames: Vec::new(), + next_frame_generation: 1, + collections: 0, + last_marked: 0, + peak_nodes: 0, + peak_roots: 0, + peak_edges: 0, + scan: ScanMeter::default(), + mark: None, + rescan_epoch: 0, + sweep_tail: None, + payload_bytes: 0, + pending_userdata: None, + pending_finalizers: PendingQueue::default(), + live_userdata_head: None, + live_userdata_tail: None, + settlement_head: None, + #[cfg(test)] + settlement_journal_len: 0, + #[cfg(test)] + rollback_owner_visits: 0, + #[cfg(test)] + selection_slot_trace: std::cell::RefCell::new(Vec::new()), + #[cfg(test)] + pending_gc_edge_trace: std::cell::RefCell::new(Vec::new()), + #[cfg(test)] + pending_live_trace: LiveTrace::new(), + pending_offer_trace: LiveTrace::new(), + #[cfg(test)] + owner_verification_trace: std::cell::RefCell::new(Vec::new()), + #[cfg(test)] + settlement_journal_trace: std::cell::RefCell::new(Vec::new()), + #[cfg(test)] + skip_pending_finalizer_metatable: false, + #[cfg(test)] + reclaim_pending_slot: None, + #[cfg(test)] + admitted_guest_callables: Vec::new(), + } + } + + /// Returns the counts since the previous take and clears them. + /// Does not collect, and does not record this read as collection work. + /// + /// The pending-queue read count is folded in from the queue's own access + /// boundary. There is no separate call-site accounting: a scan that reads + /// stored records is visible here even when it was added later. + pub fn take_scan_meter(&mut self) -> ScanMeter { + let meter = self.scan; + #[cfg(test)] + let meter = { + let mut meter = meter; + meter.pending_release_queue_reads += self.pending_finalizers.take_reads(); + meter.pending_queue_storage_moves += self.pending_finalizers.take_transfers(); + meter.pending_queue_slot_writes += self.pending_finalizers.take_slot_writes(); + meter.pending_queue_header_writes += self.pending_finalizers.take_header_writes(); + meter + }; + self.scan = ScanMeter::default(); + meter + } + + /// 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)) + } + + /// Reserves a live, unrooted bare userdata. It uses the same node cap as a + /// table. It has no guest carrier, finalizer, or resource token. + /// + /// A paused mark and a published tail are refused before a free slot is + /// taken or a new slot is grown. `alloc_slot` alone does not see a paused + /// gray mark. A full node vector still reports capacity and does not write. + pub fn alloc_userdata(&mut self) -> Result { + if !self.free_list.is_empty() { + self.deny_unbarriered()?; + } else if self.slots.len() >= self.limits.nodes as usize { + return Err(HeapError::NodeCapacity); + } else if self.limits.max_generation == 0 { + return Err(HeapError::GenerationExhausted); + } else { + self.deny_unbarriered()?; + } + let (index, generation) = self.alloc_slot(HandleKind::Userdata)?; + self.link_live_userdata_head(index, generation); + Ok(UserdataRef::userdata(self.domain, index, generation)) + } + + fn alloc_slot(&mut self, kind: HandleKind) -> Result<(u32, u32), HeapError> { + if !self.free_list.is_empty() { + self.ensure_sweep_open()?; + return self.take_free_slot(kind); + } + 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_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.pending_finalizer = false; + slot.pending_next = None; + slot.pending_raw = None; + slot.pending_generation = 0; + slot.finalizer_settled = false; + slot.live_userdata_prev = None; + slot.live_userdata_next = None; + slot.live_userdata_linked = false; + slot.settlement_next = None; + slot.settlement_generation = 0; + slot.pending_gc_generation = 0; + slot.pending_gc_round = 0; + slot.pending_gc_non_nil = false; + slot.edge_head = None; + slot.edge_tail = None; + slot.mode_edge = None; + slot.mode_epoch = 0; + slot.mode_generation = 0; + slot.mode_round = 0; + slot.mode_weak = WeakMode::default(); + slot.mode_checked_generation = 0; + slot.mode_checked_round = 0; + slot.mode_checked_epoch = 0; + slot.late_mode_epoch = 0; + slot.late_mode_prev = None; + slot.late_mode_next = None; + slot.late_owner_epoch = 0; + slot.late_owner_old = None; + slot.late_owner_old_mode = None; + slot.late_owner_new = None; + slot.late_owner_prev = None; + slot.late_owner_next = None; + slot.discover_generation = 0; + slot.discover_batch = 0; + slot.discover_round = 0; + slot.rescan_epoch = 0; + slot.rescan_queued = false; + slot.rescan_prev = None; + slot.rescan_next = None; + slot.late_target_epoch = 0; + slot.late_target_prev = None; + slot.late_target_next = None; + slot.gray_epoch = 0; + slot.gray_generation = 0; + slot.gray_prev = None; + slot.gray_next = 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, + kind, + state: SlotState::Live { marked: false }, + token: None, + carrier: None, + metatable: None, + pending_finalizer: false, + pending_next: None, + pending_raw: None, + pending_generation: 0, + finalizer_settled: false, + live_userdata_prev: None, + live_userdata_next: None, + live_userdata_linked: false, + settlement_next: None, + settlement_generation: 0, + pending_gc_generation: 0, + pending_gc_round: 0, + pending_gc_non_nil: false, + edge_head: None, + edge_tail: None, + mode_edge: None, + mode_epoch: 0, + mode_generation: 0, + mode_round: 0, + mode_weak: WeakMode::default(), + mode_checked_generation: 0, + mode_checked_round: 0, + mode_checked_epoch: 0, + late_mode_epoch: 0, + late_mode_prev: None, + late_mode_next: None, + late_owner_epoch: 0, + late_owner_old: None, + late_owner_old_mode: None, + late_owner_new: None, + late_owner_prev: None, + late_owner_next: None, + discover_generation: 0, + discover_batch: 0, + discover_round: 0, + rescan_epoch: 0, + rescan_queued: false, + rescan_prev: None, + rescan_next: None, + late_target_epoch: 0, + late_target_prev: None, + late_target_next: None, + gray_epoch: 0, + gray_generation: 0, + gray_prev: None, + gray_next: None, + }); + self.note_node_peak(); + Ok((index, 1)) + } + + /// 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()?; + 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. + pub fn rollback(&mut self, handle: TableRef) -> Result<(), HeapError> { + self.require_live(handle)?; + self.ensure_sweep_open()?; + self.clear_rooted_to(Rooted::Table(handle)); + self.remove_edges_touching(handle.slot()); + self.release_slot(handle.slot()); + Ok(()) + } + + /// Issues the guest array for a live table. + /// + /// 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.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())), + ]); + let carrier = match &value { + Value::Array(issued) => Arc::clone(issued), + _ => unreachable!("Value::array returns an array"), + }; + self.slots[index].carrier = Some(SlotCarrier::Table(carrier)); + 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(SlotCarrier::Table(carrier)); + Ok(value) + } + + /// Fixed name of the controlled `.lua` guest callable import. + /// + /// The completion slice already admits the `note` host name, so the + /// heap-owned admission reuses that slot instead of changing the lowerer. + /// The test compile catalog declares exactly this import, and its + /// dispatch function is private to this module. There is no crate-visible + /// entry that takes an `Arc`, a `Value`, a VM, or a capture + /// count. + pub(crate) const GUEST_CALLABLE_IMPORT: &'static str = "note"; + + /// Declares the schema of the controlled guest callable import. + /// + /// One untyped guest argument is the callable. The boolean result is + /// `true` when a live closure generation now holds the exact Arc and + /// `false` when the same VM's compiled prototype declares captures. The + /// caller cannot choose the count: [`admit_guest_callable`] reads the + /// prototype layout from the VM that invoked the import. + pub(crate) fn guest_callable_import_schema() -> HostFunctionSchema { + HostFunctionSchema::with_return( + Self::GUEST_CALLABLE_IMPORT, + vec![HostParamSchema::value("target", HostTypeSchema::Unknown)], + HostTypeSchema::Bool, + ) + } + + /// Registers the heap-owned callable import on one host registry. + /// + /// The caller supplies the schema compiled into its catalog. Only the + /// exact controlled shape is accepted. The dispatch function stays + /// private, so registering this import is the whole crate-visible + /// surface: no API accepts an `Arc` and a bare count, and + /// no API accepts a caller-supplied `Value` together with a VM to mint an + /// admission. The import derives the capture count from the VM that + /// invokes it and from the value's prototype in that VM. + /// + /// This is a direct Lua producer, not an arbitrary host injection check. + /// Core's `Vm::owns_callable` is not visible here and `CallableValue` + /// carries no VM identity, so this entry does not claim that a callable + /// returned by some host belongs to this VM. The issuance evidence is the + /// guest argument itself. + pub(crate) fn register_guest_callable_import( + registry: &mut HostFunctionRegistry, + schema: HostImportSchema, + ) -> VmResult { + if schema.name != Self::GUEST_CALLABLE_IMPORT + || schema.params.len() != 1 + || schema.params[0].name != "target" + || schema.params[0].schema != HostTypeSchema::Unknown + || schema.params[0].passing != vm::HostParamPassing::Value + || schema.return_type != HostTypeSchema::Bool + { + return Err(VmError::HostError( + "the guest callable import schema is not the heap-controlled shape".to_string(), + )); + } + registry.register_exact_static(Self::GUEST_CALLABLE_IMPORT, 1, schema, admit_guest_callable) + } + + /// Declares the fixed two-argument raw-call-field shape. + /// + /// The owner is the receiver table's issued guest array; the target is one + /// callable this VM's guest produced. Both are `Unknown` values, and the + /// boolean result is `true` only when the existing raw `__call` record was + /// replaced by a fresh closure generation holding the exact target Arc. + /// The caller cannot choose a slot, generation, capture count, or field. + pub(crate) fn guest_callable_field_import_schema() -> HostFunctionSchema { + HostFunctionSchema::with_return( + Self::GUEST_CALLABLE_IMPORT, + vec![ + HostParamSchema::value("owner", HostTypeSchema::Unknown), + HostParamSchema::value("target", HostTypeSchema::Unknown), + ], + HostTypeSchema::Bool, + ) + } + + /// Registers the heap-owned two-argument raw-call-field import. + /// + /// The caller supplies the schema compiled into its catalog. Only the + /// exact controlled shape is accepted; the dispatch function remains + /// private. There is no crate-visible entry that accepts a raw slot, + /// generation, field id, `Arc`, or caller-supplied capture + /// count, and this method does not widen the one-argument admission above. + pub(crate) fn register_guest_callable_field_import( + registry: &mut HostFunctionRegistry, + schema: HostImportSchema, + ) -> VmResult { + if schema.name != Self::GUEST_CALLABLE_IMPORT + || schema.params.len() != 2 + || schema.params[0].name != "owner" + || schema.params[0].schema != HostTypeSchema::Unknown + || schema.params[0].passing != vm::HostParamPassing::Value + || schema.params[1].name != "target" + || schema.params[1].schema != HostTypeSchema::Unknown + || schema.params[1].passing != vm::HostParamPassing::Value + || schema.return_type != HostTypeSchema::Bool + { + return Err(VmError::HostError( + "the raw call field import schema is not the heap-controlled shape".to_string(), + )); + } + registry.register_exact_static( + Self::GUEST_CALLABLE_IMPORT, + 2, + schema, + admit_guest_callable_to_raw_call, + ) + } + + /// Replaces one existing raw `__call` record with a fresh closure + /// generation that owns the exact guest callable Arc. + /// + /// The accepted raw states are exactly two: the fixture's `false` sentinel + /// and one live closure generation whose slot still holds a callable + /// carrier from this admission. Every validation happens before the first + /// write: the issued owner and its exact array Arc, the owner's current + /// metatable, the exact `__call` record, the live installed closure when + /// one is present, a saved mark, a published Release tail, the zero-capture + /// target shape passed by the caller, and node capacity. The remaining + /// transaction is one slot allocation, one carrier store on that fresh + /// generation, and one in-place replacement of the existing edge value. + /// None of those three steps can fail, and none inserts a new edge, root, + /// scan rule, or metatable. + fn handoff_guest_callable_to_raw_call( + &mut self, + owner_value: &Value, + callable: Arc, + capture_slots: usize, + ) -> Result { + if capture_slots != 0 || callable.kind != CallableKind::Closure { + return Err(HeapError::CallableHasEnvironment); + } + let GuestClass::Table(owner) = self.guest_class(owner_value) else { + return Err(HeapError::WrongKind); + }; + let Some((metatable_slot, metatable_generation)) = + self.slots[owner.slot() as usize].metatable + else { + return Err(HeapError::StaleHandle); + }; + if !self.slot_matches(metatable_slot, metatable_generation, HandleKind::Table) { + return Err(HeapError::StaleHandle); + } + let key = EdgeKey::Utf8(RAW_CALL_FIELD.to_owned()); + let Some(index) = self.find_key(metatable_slot, &key) else { + return Err(HeapError::StaleHandle); + }; + let accepted = { + let edge = self.edge_slots[index as usize] + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + match &edge.value { + EdgeValue::Scalar(Value::Bool(false)) => true, + EdgeValue::Closure { slot, generation } => { + self.slot_matches(*slot, *generation, HandleKind::Closure) + && matches!( + self.slots[*slot as usize].carrier, + Some(SlotCarrier::Callable(_)) + ) + } + _ => false, + } + }; + if !accepted { + return Err(HeapError::WrongKind); + } + if self.mark.is_some() { + return Err(HeapError::MarkDenied); + } + if self.sweep_tail.is_some() { + return Err(HeapError::SweepPending); + } + if !self.closure_slot_capacity_open() { + return Err(HeapError::NodeCapacity); + } + let closure = self.alloc_closure()?; + let closure_slot = closure.slot() as usize; + debug_assert!( + self.slots[closure_slot].carrier.is_none(), + "a fresh closure generation starts unbound" + ); + // The remaining transaction cannot fail: allocation produced an + // unbound live closure, and replacing the located edge value does not + // allocate, insert, or run a barrier (no mark or tail is open here). + self.slots[closure_slot].carrier = Some(SlotCarrier::Callable(callable)); + #[cfg(test)] + self.admitted_guest_callables.push(closure); + self.replace_edge_value( + metatable_slot, + index, + EdgeValue::Closure { + slot: closure.slot(), + generation: closure.generation(), + }, + ); + Ok(closure) + } + + /// Whether a fresh closure generation can be placed without a write. + /// + /// This mirrors the two `alloc_slot` paths: a free-list slot is reusable + /// without a capacity or generation check, and a new slot needs room under + /// both the node cap and the generation cap. Callers that must reject at + /// full capacity before the first write use this instead of guessing after + /// `alloc_closure`. + fn closure_slot_capacity_open(&self) -> bool { + !self.free_list.is_empty() + || (self.slots.len() < self.limits.nodes as usize && self.limits.max_generation != 0) + } + + /// Stores one admitted callable on one live closure generation. + /// + /// Private to this module. The only non-test caller is + /// [`admit_guest_callable`], which derives `capture_slots` from the + /// invoking VM's compiled prototype. A live generation holds at most one + /// carrier, so a second store, including one with a different Arc, is + /// refused and the stored Arc stays. A failed store stores no Arc. + /// + /// The callable is one identity carrier like the issued table array: mark + /// does not read it, it is not a root or an edge, and it does not add scan + /// work. Release clears it with the slot, and a reused generation starts + /// empty. + fn store_guest_callable( + &mut self, + closure: ClosureRef, + callable: Arc, + capture_slots: usize, + ) -> Result<(), HeapError> { + self.require_closure(closure)?; + if capture_slots != 0 { + return Err(HeapError::CallableHasEnvironment); + } + let index = closure.slot() as usize; + if self.slots[index].carrier.is_some() { + return Err(HeapError::CarrierAlreadyBound); + } + self.ensure_sweep_open()?; + self.slots[index].carrier = Some(SlotCarrier::Callable(callable)); + #[cfg(test)] + self.admitted_guest_callables.push(closure); + Ok(()) + } + + /// Test-only: closure generations the controlled guest import admitted, in + /// admission order. Observation only; the stored Arcs stay private to the + /// slot carrier and no test can put a value back into this vector. + #[cfg(test)] + pub(crate) fn guest_callable_admissions(&self) -> &[ClosureRef] { + &self.admitted_guest_callables + } + + /// Returns the exact Arc bound to one live closure generation. + /// + /// The handle's domain, kind, slot, and generation are checked first. An + /// unbound generation is [`HeapError::CarrierNotBound`]. There is no + /// prototype or schema lookup: the stored Arc is the only identity. + pub(crate) fn closure_callable( + &self, + closure: ClosureRef, + ) -> Result, HeapError> { + self.require_closure(closure)?; + match self.slots[closure.slot() as usize].carrier.as_ref() { + Some(SlotCarrier::Callable(callable)) => Ok(Arc::clone(callable)), + Some(SlotCarrier::Table(_)) | None => Err(HeapError::CarrierNotBound), + } + } + + /// Test-only: a closure handle naming this live table's slot and + /// generation. The kind check must refuse it before any carrier access. + /// This is not a handle constructor for guests or production code. + #[cfg(test)] + pub(crate) fn closure_handle_for_table(&self, table: TableRef) -> ClosureRef { + ClosureRef::closure(self.domain, table.slot(), table.generation()) + } + + /// 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. 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, + 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 = match stored.carrier.as_ref()? { + SlotCarrier::Table(current) => current, + SlotCarrier::Callable(_) => return None, + }; + if !Arc::ptr_eq(current, 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> { + 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`]. A + /// boolean, binary64, string, or bytes value uses + /// [`Self::write_scalar_upvalue`]. After the write commits, an already + /// discovered cell shades only that direct table. The published tail is + /// still refused inside the write, before any barrier. + 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(), + }, + )?; + self.barrier_strong_closed_cell( + cell.slot(), + cell.generation(), + table.slot(), + table.generation(), + mark::ClosedCellTarget::Table, + ); + Ok(()) + } + + /// Replaces the current edge with a closure. Same record as a table write. + /// + /// After the write commits, an already discovered cell shades only that + /// direct closure. The capture and its table wait for the continued scan. + /// The published tail is still refused inside the write, before any barrier. + 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(), + }, + )?; + self.barrier_strong_closed_cell( + cell.slot(), + cell.generation(), + closure.slot(), + closure.generation(), + mark::ClosedCellTarget::Closure, + ); + Ok(()) + } + + /// 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. 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(_) | Value::String(_) | Value::Bytes(_) + ) { + 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)?; + let key = EdgeKey::Field(CURRENT_EDGE); + self.unlink_key(cell.slot(), &key) + } + + /// 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. The edge itself is decoded by + /// [`Self::current_edge`]. + pub fn read_cell(&self, closure: ClosureRef) -> Result, HeapError> { + let cell = self.upvalue_of(closure)?; + self.current_edge(cell) + } + + /// Reads the table currently stored through a closure's cell. + /// + /// 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 { + let cell = self.upvalue_of(closure)?; + match self.current_table(cell)? { + Some(table) => Ok(table), + 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) + } + + /// Test-only: reads one raw named closure record exactly. + /// + /// This is the readback the file-entry witness uses to prove the raw + /// `__call` field now names the generation the handoff wrote. It is not an + /// admission, write, or lookup-by-prototype path, and a missing record or + /// a non-closure value is refused before any generation is constructed. + #[cfg(test)] + pub(crate) fn named_closure_edge( + &self, + from: TableRef, + name: &str, + ) -> Result { + self.require_live(from)?; + let Some(value) = self.stored_from(from.slot(), &EdgeKey::named(name)) 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) + } + + /// Test-only: reads one raw named scalar record. + /// + /// `None` is an absent record. A stored nil gap, boolean, string, or bytes + /// value is returned as its exact `Value`. A table, closure, upvalue, or + /// userdata target is `WrongKind`, not a scalar. This observes the existing + /// record and does not create one, follow `__index`, or cache a result. + #[cfg(test)] + pub(crate) fn named_raw_scalar( + &self, + from: TableRef, + name: &str, + ) -> Result, HeapError> { + self.require_live(from)?; + let Some(value) = self.stored_from(from.slot(), &EdgeKey::named(name)) else { + return Ok(None); + }; + match value { + EdgeValue::Scalar(value) => Ok(Some(value.clone())), + _ => Err(HeapError::WrongKind), + } + } + + /// 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. 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); + }; + 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::Userdata { .. } | EdgeValue::Scalar(_) => { + 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 + /// 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(key); + if matches!(value, Value::Null) { + 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 one bare userdata under a Lua string key. + /// + /// This is the typed strong-edge form used by the private linked-finalizer + /// fixture: a metatable field can name the exact live userdata generation. + /// The write uses the same record, quota, and mutation gates as a table + /// field. It does not issue a guest value. + pub fn set_named_userdata( + &mut self, + from: TableRef, + name: &str, + value: UserdataRef, + ) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_userdata(value)?; + self.deny_unbarriered()?; + self.write_edge( + from, + EdgeKey::named(name), + EdgeValue::Userdata { + slot: value.slot(), + generation: value.generation(), + }, + ) + } + + /// Writes one closure under a Lua string key. + /// + /// This is the private strong-edge form used by the pending-finalizer raw + /// `__gc` and `__call` fixtures: a metatable field can name the exact live + /// closure generation. The write uses the same record, quota, and mutation + /// gates as a table field. It does not issue a guest value and does not + /// make that closure a callable. + pub fn set_named_closure( + &mut self, + from: TableRef, + name: &str, + value: ClosureRef, + ) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_closure(value)?; + self.deny_unbarriered()?; + self.write_edge( + from, + EdgeKey::named(name), + EdgeValue::Closure { + slot: value.slot(), + generation: value.generation(), + }, + ) + } + + /// Writes a scalar under a Lua string key, or deletes that record on nil. + /// + /// 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, + 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(_) | Value::Bool(_)) + || (mode && matches!(value, Value::Float(_))) + ); + self.require_live(from)?; + if matches!(value, Value::Null) { + self.clear_edge(from, &key)?; + Ok(()) + } else { + self.write_edge(from, key, EdgeValue::Scalar(value)) + } + } + + /// Test-only: writes a stored nil under a named field without deleting the + /// record. This is the same scalar-null representation weak publication + /// leaves as a cursor gap; the private raw `__gc` lookup must treat it as + /// absent rather than as a value. + #[cfg(test)] + pub(crate) fn set_named_gap_test_control( + &mut self, + from: TableRef, + name: &str, + ) -> Result<(), HeapError> { + self.require_live(from)?; + self.write_edge(from, EdgeKey::named(name), EdgeValue::Scalar(Value::Null)) + } + + /// 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) + } + + /// 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 }) + } + + /// 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 { .. } + | EdgeValue::Userdata { .. } => 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)) + } + + /// 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 + /// 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_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> { + self.require_live(from)?; + self.require_live(key)?; + let key = EdgeKey::object(key); + self.clear_edge(from, &key) + } + + /// 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)) + } + + /// Writes one boolean, binary64, string, or bytes value under a bare userdata key. + /// + /// Nil removes that record through [`Self::clear_edge`]. It does not store + /// a cursor gap, and a missing key allocates nothing. An integer, array, + /// map, callable, or any other carrier is [`HeapError::WrongKind`] and + /// leaves the table unchanged. + /// + /// The key is an object record with userdata kind. It is not a table key + /// and not a numeric key. Handle checks run before the gray and published + /// tail gates, and those gates run before value classification. A bad + /// handle does not write and does not depend on phase. Nil uses the same + /// gates. This write has no edge barrier, so a paused mark or saved tail + /// is refused before the record changes. + pub fn set_userdata_key_scalar( + &mut self, + from: TableRef, + key: UserdataRef, + value: Value, + ) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_userdata(key)?; + self.deny_unbarriered()?; + let stored = EdgeKey::userdata_key(key); + match value { + Value::Null => self.clear_edge(from, &stored), + Value::Bool(_) | Value::Float(_) | Value::String(_) | Value::Bytes(_) => { + self.write_edge(from, stored, EdgeValue::Scalar(value)) + } + _ => Err(HeapError::WrongKind), + } + } + + /// Reads the scalar stored under a bare userdata key. + /// + /// A dead or reused key is `StaleHandle`. A stored userdata or other + /// internal target is `WrongKind`, not a Core number or table. + pub fn userdata_key_value(&self, from: TableRef, key: UserdataRef) -> Result { + self.require_userdata(key)?; + let key = EdgeKey::userdata_key(key); + self.stored_value(from, |stored| stored == &key) + } + + /// Writes one bare userdata under a bare userdata key. + /// + /// This is the same-object `t[u] = u` form for the weak `kv` evidence. + /// Key and value keep their own roles: the key is not a guest cursor, and + /// a value that is value-dead cannot be published as a gap under it. + pub fn set_userdata_key_userdata( + &mut self, + from: TableRef, + key: UserdataRef, + value: UserdataRef, + ) -> Result<(), HeapError> { + self.require_live(from)?; + self.require_userdata(key)?; + self.require_userdata(value)?; + self.deny_unbarriered()?; + self.write_edge( + from, + EdgeKey::userdata_key(key), + EdgeValue::Userdata { + slot: value.slot(), + generation: value.generation(), + }, + ) + } + + /// 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) + } + + /// 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 + /// 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 bare userdata under a binary64 key. + /// + /// NaN is refused before any lookup. `+0` and `-0` select the same record. + /// The value stays a userdata identity; readers must not return it as a + /// table or a Core number. Handle checks run before the gray and published + /// tail gates. This write has no edge barrier, so those gates refuse it + /// before the record changes. + pub fn set_number_userdata( + &mut self, + from: TableRef, + key: f64, + value: UserdataRef, + ) -> Result<(), HeapError> { + let key = Self::number_key(key)?; + self.require_live(from)?; + self.require_userdata(value)?; + self.deny_unbarriered()?; + self.write_edge( + from, + key, + EdgeValue::Userdata { + slot: value.slot(), + generation: value.generation(), + }, + ) + } + + /// Reads the userdata stored under a binary64 key. + /// + /// NaN reads as missing after the table is confirmed live. A stored table, + /// closure, or cell is `WrongKind`. A scalar, including a weak-cleared + /// cursor, is missing. This does not claim a guest `rawget`. + pub fn number_userdata( + &self, + from: TableRef, + key: f64, + ) -> Result, HeapError> { + self.require_live(from)?; + if key.is_nan() { + return Ok(None); + } + let key = EdgeKey::number(key); + match self.read_edge(from, |stored| stored == &key)? { + Some(EdgeValue::Userdata { slot, generation }) => { + Ok(Some(UserdataRef::userdata(self.domain, *slot, *generation))) + } + Some(EdgeValue::Scalar(_)) | None => Ok(None), + Some( + EdgeValue::Table { .. } | EdgeValue::Closure { .. } | EdgeValue::Upvalue { .. }, + ) => Err(HeapError::WrongKind), + } + } + + /// 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) + } + + /// 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) + } + + /// 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); + } + Ok(EdgeKey::number(key)) + } + + fn clear_edge(&mut self, from: TableRef, key: &EdgeKey) -> Result<(), HeapError> { + self.unlink_key(from.slot(), key) + } + + 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> { + self.write_from(from.slot(), key, value) + } + + fn write_from( + &mut self, + from_slot: u32, + 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(()); + } + if self.occupied_edges >= self.limits.edges && !self.reclaim_cursor_gap() { + return Err(HeapError::EdgeCapacity); + } + // 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(_) | EdgeKey::Number(_)) + && let EdgeValue::Table { slot, generation } = &value + { + Some((*slot, *generation)) + } 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 }); + 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(); + if let Some((slot, generation)) = barrier { + self.barrier_strong_field(from_slot, index, Some((slot, generation))); + } + if let Some(insert) = table_key { + self.barrier_new_table_key( + from_slot, + index, + insert.key_slot, + insert.key_generation, + insert.value, + ); + } + 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 { + 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`. + pub fn edge(&self, from: TableRef, key: u32) -> Result, HeapError> { + let key = EdgeKey::Field(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> { + 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 { + self.stored_value(from, |stored| stored.matches_name(name)) + } + + /// 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 + /// 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 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, + 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(); + 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() + .is_some_and(|cursor| cursor.matches(&edge.key)) + { + passed = true; + } + continue; + } + if edge.value.is_cursor_gap() { + 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 { .. } | EdgeValue::Userdata { .. } => { + Err(HeapError::NextUnsupported) + } + } + } + + /// 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)?; + let key = EdgeKey::object(key); + self.read_table_edge(from, |stored| stored == &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)?; + let key = EdgeKey::object(key); + self.stored_value(from, |stored| stored == &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)) + } + Some(EdgeValue::Scalar(value)) => Ok(value.clone()), + Some( + EdgeValue::Closure { .. } | EdgeValue::Upvalue { .. } | EdgeValue::Userdata { .. }, + ) => Err(HeapError::WrongKind), + None => Ok(Value::Null), + } + } + + fn read_table_edge( + &self, + from: TableRef, + matches_key: impl Fn(&EdgeKey) -> bool, + ) -> Result, HeapError> { + 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 { .. } | EdgeValue::Userdata { .. }, + ) => Err(HeapError::WrongKind), + } + } + + fn stored_from(&self, from_slot: u32, key: &EdgeKey) -> Option<&EdgeValue> { + let index = self.find_key(from_slot, key)?; + self.edge_slots[index as usize] + .edge + .as_ref() + .map(|edge| &edge.value) + } + + /// One raw stored value under a Lua string key through the owner's chain. + /// + /// A missing key returns `None`; a stored `Value::Null` gap still returns a + /// value record, so the caller can tell an absent field from a true + /// stored-nil gap. This does not consult `__index`, a metatable, or the + /// selection cache, and it does not construct a key. The owner-chain walk + /// is linear in that owner's stored edge count. + fn raw_named_value(&self, owner: u32, name: &str) -> Option<&EdgeValue> { + let index = self.find_matching(owner, |key| key.matches_name(name))?; + self.edge_slots + .get(index as usize)? + .edge + .as_ref() + .map(|edge| &edge.value) + } + + /// 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)?; + 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)) + } + + /// 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)?; + } + self.ensure_sweep_open()?; + let old_tuple = self.slots[owner.slot() as usize].metatable; + let new_tuple = mt.map(|target| (target.slot(), target.generation())); + // A metatable first attached while mutation is open can have a direct + // `__mode` that the reset walk never read: with no metatable attached + // at Reset, the walk parses nothing. Register that read before the + // owner can be opened, and let the transition check below see the + // queued parse as unknown rather than as a strong default. + if let Some(target) = mt { + self.note_attached_mode(target.slot(), target.generation()); + } + let rescan = self.needs_owner_rescan(owner.slot(), old_tuple, new_tuple); + let had = old_tuple.is_some(); + if had != new_tuple.is_some() { + if new_tuple.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 = new_tuple; + if rescan { + self.schedule_owner_rescan(owner.slot()); + } + if let Some(target) = mt { + self.barrier_strong_metatable(owner.slot(), target.slot(), target.generation()); + } + 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))) + } + + /// Attaches or clears one metatable reference on a typed userdata. + /// + /// This is the minimal fixture wiring for the private pending-finalizer + /// slice, not a guest metamethod path. A userdata has no owner chain, so + /// the reference is stored only in the one `metatable` tuple. The target + /// must be a live table in this heap. A new attachment counts in + /// `metatable_edges`, the same flag that lets reset parse direct + /// `__mode` fields; a replacement that keeps the reference present does + /// not change the count. A parked mark or a saved published tail is + /// refused before the slot changes, matching the unbarriered + /// `alloc_userdata` contract. The edge is strong: `open_owner` follows it + /// when the userdata is marked, and the pending selection marks the + /// selected userdata after the ordinary mark converges. + pub(crate) fn set_userdata_metatable( + &mut self, + userdata: UserdataRef, + mt: Option, + ) -> Result<(), HeapError> { + self.require_userdata(userdata)?; + if let Some(target) = mt { + self.require_live(target)?; + } + self.deny_unbarriered()?; + let index = userdata.slot() as usize; + let old = self.slots[index].metatable; + let new = mt.map(|target| (target.slot(), target.generation())); + if old.is_some() != new.is_some() { + if new.is_some() { + self.metatable_edges = self.metatable_edges.saturating_add(1); + } else { + self.metatable_edges = self.metatable_edges.saturating_sub(1); + } + } + self.slots[index].metatable = new; + Ok(()) + } + + /// The metatable reference stored on one typed userdata. + /// + /// This is a raw slot read, not a guest `getmetatable`. A missing + /// reference is `Ok(None)`. + pub(crate) fn userdata_metatable( + &self, + userdata: UserdataRef, + ) -> Result, HeapError> { + self.require_userdata(userdata)?; + Ok(self.slots[userdata.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)?; + let carrier = match self.slots[table.slot() as usize] + .carrier + .as_ref() + .ok_or(HeapError::StaleHandle)? + { + SlotCarrier::Table(carrier) => carrier, + SlotCarrier::Callable(_) => return Err(HeapError::StaleHandle), + }; + Ok(Value::Array(Arc::clone(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 { + 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.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); + 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. 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, + slot: u32, + handle: TableRef, + ) -> Result<(), HeapError> { + self.require_live(handle)?; + self.store_root(frame, slot, Rooted::Table(handle)) + } + + /// 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)?; + 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)) + } + + /// Stores a bare userdata 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. The existing root barrier marks the node while mutation is + /// open. This does not write an edge. + pub fn write_userdata_root( + &mut self, + frame: RootFrameId, + slot: u32, + handle: UserdataRef, + ) -> Result<(), HeapError> { + self.require_userdata(handle)?; + self.store_root(frame, slot, Rooted::Userdata(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); + } + self.ensure_sweep_open()?; + let index = found.start as usize + slot as usize; + self.roots[index] = Some(rooted); + self.note_parked_root_store(rooted); + 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(()) + } + + /// 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 + /// 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); + } + self.ensure_sweep_open()?; + 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)?; + 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(); + 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> { + self.require_live(table)?; + if self.slots[table.slot() as usize].token.is_some() { + return Err(HeapError::StaleHandle); + } + self.ensure_sweep_open()?; + self.slots[table.slot() as usize].token = Some(raw); + 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) + } + + /// Records the typed token that owns `userdata`. The handle is not + /// installed as a root. + /// + /// The caller must already have confirmed that the raw handle names this + /// exact userdata through its typed resource payload. The issuer does that + /// check before binding; this raw write cannot repeat it without a + /// `HostContext`. + pub(crate) fn bind_userdata_token( + &mut self, + userdata: UserdataRef, + raw: u64, + ) -> Result<(), HeapError> { + self.require_userdata(userdata)?; + let index = userdata.slot() as usize; + if self.slots[index].token.is_some() { + return Err(HeapError::StaleHandle); + } + self.ensure_sweep_open()?; + if let Some(pending) = self.pending_userdata + && pending.slot == userdata.slot() + { + if pending.generation != userdata.generation() { + return Err(HeapError::StaleHandle); + } + if pending.raw.is_some_and(|staged| staged != raw) { + return Err(HeapError::TokenMismatch); + } + self.pending_userdata = None; + } + self.slots[index].token = Some(raw); + Ok(()) + } + + /// The raw token stored for one live typed userdata. + /// + /// A missing binding is [`HeapError::StaleHandle`]. A handle from another + /// domain, of another kind, or at an old generation is rejected first. + pub(crate) fn published_userdata_token(&self, userdata: UserdataRef) -> Result { + self.require_userdata(userdata)?; + self.slots[userdata.slot() as usize] + .token + .ok_or(HeapError::StaleHandle) + } + + /// The exact live userdata that one mark-time token record still names. + /// + /// The collector reads this before it closes a userdata resource: the slot + /// must be live at the captured generation and kind and must still store + /// the captured raw handle. This is one slot identity read, counted in + /// `token_slot_checks`; it does not search the slot vector. + pub(super) fn bound_userdata_for_token( + &mut self, + token: &DoomedToken, + ) -> Result { + self.scan.token_slot_checks += 1; + let matches = self.slots.get(token.slot as usize).is_some_and(|slot| { + slot.generation == token.generation + && slot.kind == HandleKind::Userdata + && slot.token == Some(token.raw) + && matches!(slot.state, SlotState::Live { .. }) + }); + if !matches { + return Err(HeapError::StaleHandle); + } + Ok(UserdataRef::userdata( + self.domain, + token.slot, + token.generation, + )) + } + + /// Clears the token stored on `userdata` without searching other slots. + /// Does not close a host resource and does not sweep. The host collector + /// uses [`Self::clear_exact_token`] instead. + pub(crate) fn unbind_userdata_token(&mut self, userdata: UserdataRef) -> Result<(), HeapError> { + self.require_userdata(userdata)?; + self.ensure_sweep_open()?; + self.slots[userdata.slot() as usize].token = None; + Ok(()) + } + + /// Reserves one userdata slot for the typed issuer and records the exact + /// reservation. The record is not a published binding: an ordinary borrow, + /// the pending-close enumeration, and the sweep do not read it. + /// + /// A later failure can roll this slot back with + /// [`Self::rollback_empty_userdata`], which validates the record and the + /// empty slot in O(1) and does not scan the roots or the owner chains. + pub(super) fn reserve_userdata(&mut self) -> Result { + if self.pending_userdata.is_some() { + return Err(HeapError::Scope( + "a userdata reservation is already in flight".to_string(), + )); + } + let userdata = self.alloc_userdata()?; + self.pending_userdata = Some(PendingUserdata { + slot: userdata.slot(), + generation: userdata.generation(), + raw: None, + }); + Ok(userdata) + } + + /// Attaches the registered Core raw handle to the exact reservation, + /// before the slot binding is published. + pub(super) fn stage_userdata_token( + &mut self, + userdata: UserdataRef, + raw: u64, + ) -> Result<(), HeapError> { + self.require_userdata(userdata)?; + let Some(pending) = self.pending_userdata.as_mut() else { + return Err(HeapError::StaleHandle); + }; + if pending.slot != userdata.slot() || pending.generation != userdata.generation() { + return Err(HeapError::StaleHandle); + } + pending.raw = Some(raw); + Ok(()) + } + + /// The exact reservation this heap is holding, if any. + /// + /// Returns the private handle and the staged Core raw (`None` before a + /// successful registration). The record is only returned when it names a + /// live, empty userdata at its recorded generation, of kind userdata, + /// with no published token, edge, metatable, mode pointer, or carrier. + /// Recovery validates the exact owner before it closes the staged token, + /// and must not close a token for a record whose slot it cannot release. + /// A saved mark or a saved release tail owns the graph, so both refuse + /// recovery before any close: the caller keeps the record unchanged. + /// This is one record check, not a heap scan. + pub(super) fn pending_userdata_reservation( + &self, + ) -> Result)>, HeapError> { + let Some(pending) = self.pending_userdata else { + return Ok(None); + }; + self.ensure_sweep_open()?; + if self.mark.is_some() { + return Err(HeapError::MarkDenied); + } + let Some(slot) = self.slots.get(pending.slot as usize) else { + return Err(HeapError::StaleHandle); + }; + if slot.generation != pending.generation + || slot.kind != HandleKind::Userdata + || slot.token.is_some() + || slot.edge_head.is_some() + || slot.edge_tail.is_some() + || slot.metatable.is_some() + || slot.mode_edge.is_some() + || slot.carrier.is_some() + || !matches!(slot.state, SlotState::Live { .. }) + { + return Err(HeapError::StaleHandle); + } + Ok(Some(( + UserdataRef::userdata(self.domain, pending.slot, pending.generation), + pending.raw, + ))) + } + + /// The slot of a registered reservation that the current mark must + /// retain, if the record still names the exact live userdata. + /// + /// A registered reservation (`raw` is `Some`) is a host-retained node: it + /// is not published and not guest-visible, but a normal collection must + /// not release its slot or strand its Core token without the record that + /// can close it. An unregistered empty reservation (`raw` is `None`) is + /// not retained: it owns no Core resource, and a collection may reclaim + /// it. Domain is the heap's own, so checking the record plus this slot is + /// the whole identity check. This does not search other slots. + fn registered_pending_userdata_slot(&self) -> Option { + let pending = self.pending_userdata?; + pending.raw?; + let slot = self.slots.get(pending.slot as usize)?; + #[cfg(test)] + self.selection_slot_trace.borrow_mut().push(pending.slot); + if slot.generation == pending.generation + && slot.kind == HandleKind::Userdata + && slot.token.is_none() + && matches!(slot.state, SlotState::Live { .. }) + { + Some(pending.slot) + } else { + None + } + } + + /// Examines one live-userdata chain node for the private pending-finalizer + /// selection, without reading the metatable edge chain. + /// + /// A candidate is a live, unmarked userdata that already published a + /// typed Core token, is not pending or settled yet, and stores a live + /// table metatable at its exact generation. The raw `__gc` lookup is a + /// separate metered walk; this function reads one slot record only. A + /// missing token, a table owner, an absent metatable, or a dead metatable + /// is not a candidate. A missing or nil raw `__gc` is still a candidate: + /// it is the settlement arm, not a non-candidate. + pub(super) fn pending_finalizer_candidate(&self, index: usize) -> Option { + let slot = self.slots.get(index)?; + if !matches!(slot.state, SlotState::Live { marked: false }) { + return None; + } + if slot.kind != HandleKind::Userdata || slot.pending_finalizer || slot.finalizer_settled { + return None; + } + slot.token?; + let (metatable_slot, metatable_generation) = slot.metatable?; + if !self.slot_matches(metatable_slot, metatable_generation, HandleKind::Table) { + return None; + } + Some(PendingCandidate { + slot: index as u32, + generation: slot.generation, + metatable_slot, + metatable_generation, + }) + } + + /// The metatable's cached raw `__gc` result for this mark round and exact + /// generation, if a previous candidate already paid for the walk. + /// Reads one slot record and no edge record. + pub(super) fn cached_pending_gc( + &self, + candidate: &PendingCandidate, + round: u64, + ) -> Option { + let metatable = self.slots.get(candidate.metatable_slot as usize)?; + if metatable.generation == candidate.metatable_generation + && metatable.pending_gc_generation == candidate.metatable_generation + && metatable.pending_gc_round == round + { + Some(metatable.pending_gc_non_nil) + } else { + None + } + } + + /// Stores one completed raw `__gc` result on the exact metatable + /// generation for this mark round. It does not grow a side table. + pub(super) fn cache_pending_gc( + &mut self, + metatable_slot: u32, + metatable_generation: u32, + round: u64, + non_nil: bool, + ) { + let Some(metatable) = self.slots.get_mut(metatable_slot as usize) else { + return; + }; + if metatable.generation != metatable_generation { + return; + } + metatable.pending_gc_generation = metatable_generation; + metatable.pending_gc_round = round; + metatable.pending_gc_non_nil = non_nil; + } + + /// The next cursor and raw `__gc` result of one edge record read. + /// + /// Missing records, a stored nil (`EdgeValue::Scalar(Value::Null)`), and a + /// weak-cleared cursor gap are not values. `false`, strings, numbers, and + /// every object carrier are values. This reads the raw record only; it + /// does not consult `__index`. + pub(super) fn pending_gc_record(&self, index: u32) -> (Option, bool, bool) { + let record = &self.edge_slots[index as usize]; + let edge = record + .edge + .as_ref() + .expect("owner chain holds an occupied record"); + let matched = edge.key.matches_name("__gc"); + let non_nil = matched && !matches!(edge.value, EdgeValue::Scalar(Value::Null)); + (record.next, matched, non_nil) + } + + /// Commits one metered raw-`__gc`-positive candidate into the pending + /// record list. Re-checks the exact slot identity before any write, so a + /// candidate that changed during the walk is not recorded. + /// + /// The append writes the exact generation and current raw-handle snapshot + /// onto that slot and links it after the old tail. It touches no other + /// slot record and never relocates an old record. + pub(super) fn commit_pending_finalizer(&mut self, candidate: &PendingCandidate) -> bool { + let index = candidate.slot as usize; + let Some(slot) = self.slots.get(index) else { + return false; + }; + if slot.generation != candidate.generation + || !matches!(slot.state, SlotState::Live { marked: false }) + || slot.kind != HandleKind::Userdata + || slot.pending_finalizer + || slot.finalizer_settled + { + return false; + } + let Some(raw) = slot.token else { + return false; + }; + let generation = slot.generation; + let record = PendingFinalizer { + slot: candidate.slot, + generation, + raw, + }; + self.pending_finalizers.push(&mut self.slots, record); + true + } + + /// Settles one metered raw-`__gc`-negative candidate. + /// + /// Upstream `lj_gc_separateudata` marks such a white userdata finalized + /// without queueing it. This writes the same per-identity state on the + /// exact slot generation: no queue record, no mark, and no retention. + /// The same call links the identity into this pass's intrusive settlement + /// journal, one slot node and one head update, so the rollback record is + /// constant work per pulse unit and never grows or copies a vector. The + /// live-token, unmarked, userdata, and generation checks mirror + /// [`Self::commit_pending_finalizer`]; a candidate that changed during + /// the walk is not settled. + pub(super) fn settle_pending_finalizer(&mut self, candidate: &PendingCandidate) -> bool { + let index = candidate.slot as usize; + let Some(slot) = self.slots.get(index) else { + return false; + }; + if slot.generation != candidate.generation + || !matches!(slot.state, SlotState::Live { marked: false }) + || slot.kind != HandleKind::Userdata + || slot.pending_finalizer + || slot.finalizer_settled + || slot.token.is_none() + { + return false; + } + let generation = candidate.generation; + let head = self.settlement_head; + let slot = &mut self.slots[index]; + slot.finalizer_settled = true; + slot.settlement_generation = generation; + slot.settlement_next = head; + self.settlement_head = Some(candidate.slot); + #[cfg(test)] + { + self.settlement_journal_len += 1; + self.scan.settlement_journal_appends += 1; + } + true + } + + /// Drops the current journal before a new selecting scan starts, or after + /// a successful publication. + /// + /// This drops the head only. The links and generation stamps stay on the + /// slots, but they are unreachable: a later append overwrites the next + /// link before the slot can join the new chain, and slot reuse clears both + /// fields. A successful pass therefore performs no per-node work here and + /// no node visit is charged to Release or to the next mark's first pulse. + pub(super) fn clear_selecting_settlements(&mut self) { + self.settlement_head = None; + #[cfg(test)] + { + self.settlement_journal_len = 0; + } + } + + /// Clears exactly the settlement flags named by the current failed pass + /// and drops the journal. + /// + /// The walk follows this pass's intrusive chain, one slot node at a time, + /// and touches no other node. Each entry is re-checked against the live + /// slot generation and the userdata kind. A slot that changed, was already + /// pending, or was settled by an earlier pass is not cleared, so valid + /// previous-cycle state and a pending record's flag survive the rollback. + /// The journal head and length are dropped before the walk, so a refused + /// or interrupted pass cannot leave a partially reachable chain. + pub(super) fn discard_settlements(&mut self) { + let mut cursor = self.settlement_head.take(); + #[cfg(test)] + { + self.settlement_journal_len = 0; + } + while let Some(index) = cursor { + let Some(slot) = self.slots.get_mut(index as usize) else { + break; + }; + let next = slot.settlement_next.take(); + let generation = std::mem::take(&mut slot.settlement_generation); + #[cfg(test)] + { + self.scan.settlement_journal_visits += 1; + self.settlement_journal_trace + .borrow_mut() + .push((index, generation)); + } + if slot.generation == generation + && slot.kind == HandleKind::Userdata + && slot.finalizer_settled + && !slot.pending_finalizer + { + slot.finalizer_settled = false; + } + cursor = next; + } + } + + /// Number of pending-finalizer records. Does not read the graph or a + /// stored record; it reads only the queue length. + pub(super) fn pending_finalizer_count(&self) -> usize { + self.pending_finalizers.len() + } + + /// Number of leading records that a successful private publication made + /// consumable. A header read only; no stored record is read. + pub(super) fn pending_finalizer_published_count(&self) -> usize { + self.pending_finalizers.published_len() + } + + /// The published head record, if the ready prefix is non-empty. + /// + /// This is one queue record read and no write. A queue that has records + /// but no published prefix is not consumable: selection may have retained + /// them for a later mark, but no successful weak publication has released + /// them to a consumer yet. + pub(super) fn pending_finalizer_published_front(&self) -> Result { + self.pending_finalizers + .published_front(&self.slots) + .ok_or_else(|| { + HeapError::Scope("lua pending finalizer head is not published".to_string()) + }) + } + + /// Checks one specified root slot can receive the published head. + /// + /// Any open frame generation is accepted; an unknown or old frame, an + /// out-of-range slot, a missing root entry, and an occupied slot are all + /// refused before a queue or root write. A valid empty slot is `Ok(())`. + pub(super) fn pending_finalizer_root_slot( + &self, + frame: RootFrameId, + slot: u32, + ) -> Result<(), HeapError> { + self.pending_finalizer_root_index(frame, slot).map(|_| ()) + } + + fn pending_finalizer_root_index( + &self, + frame: RootFrameId, + slot: u32, + ) -> Result { + // `frame` walks the open-frame stack, so this lookup is linear in the + // number of open frames and reads no queue record. + let found = self.frame(frame)?; + 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::Scope( + "lua pending finalizer root slot is occupied".to_string(), + )); + } + Ok(index) + } + + /// Resolves the concrete root positions for one dequeue plan. + /// + /// `slots[0]` receives the userdata. A direct closure adds `slots[1]`; a + /// table call or an independent userdata receiver adds the closure at + /// `slots[1]` and the original receiver at `slots[2]`. A self-receiver + /// userdata call needs only the first two positions. Only the first + /// `needed` positions are read. They must be distinct, inside one open + /// frame, present, and empty. A short plan or a duplicate is refused before + /// any queue, root, or slot write. Each position locates its frame by + /// walking the open-frame stack, so this plan is linear in the number of + /// open frames and the number of required positions; it does not read the + /// queue, any edge chain, or the root vector beyond the checked entries. + fn pending_finalizer_root_indices( + &self, + frame: RootFrameId, + slots: &[u32], + needed: usize, + ) -> Result<[usize; 3], HeapError> { + if needed > 3 || slots.len() < needed { + return Err(HeapError::Scope( + "lua pending finalizer needs more root slots".to_string(), + )); + } + let mut indices = [0usize; 3]; + for (offset, slot) in slots[..needed].iter().copied().enumerate() { + if slots[..offset].contains(&slot) { + return Err(HeapError::Scope( + "lua pending finalizer root slots overlap".to_string(), + )); + } + indices[offset] = self.pending_finalizer_root_index(frame, slot)?; + } + Ok(indices) + } + + /// The exact live userdata a published head record still names. + /// + /// The record's slot must still bind the same generation, kind, pending + /// flag, raw handle, and live state. A successor generation in the same + /// slot is refused. This is the shared identity preflight of both dequeue + /// entries; it reads one record and writes nothing. + fn pending_finalizer_head_identity( + &self, + head: PendingFinalizer, + ) -> Result { + let Some(slot_record) = self.slots.get(head.slot as usize) else { + return Err(HeapError::StaleHandle); + }; + if slot_record.generation != head.generation + || slot_record.kind != HandleKind::Userdata + || !slot_record.pending_finalizer + || slot_record.finalizer_settled + || slot_record.token != Some(head.raw) + || !matches!(slot_record.state, SlotState::Live { .. }) + { + return Err(HeapError::StaleHandle); + } + Ok(UserdataRef::userdata( + self.domain, + head.slot, + head.generation, + )) + } + + /// The current raw finalizer action for one live pending userdata. + /// + /// This is the dequeue-time re-read: the userdata's current metatable is + /// read again, then its raw `__gc` field. A boolean, number, or string + /// keeps only its Lua type tag; a stored nil stays `Skip`. A live table or + /// a live userdata adds exactly one raw `__call` lookup on that receiver's + /// own current instance metatable through [`Self::current_metatable_raw_call`]. + /// It does not reuse the selection cache, does not follow `__index`, does + /// not walk an inherited metatable, and does not dispatch a table-valued + /// `__call` a second time. Each raw field lookup walks one owner chain, so + /// the cost is linear in the receiver metatable's stored edge count. Nothing + /// is written. + pub(super) fn pending_finalizer_action(&self, userdata: UserdataRef) -> PendingFinalizerAction { + let Some(slot) = self.slots.get(userdata.slot() as usize) else { + return PendingFinalizerAction::Skip; + }; + let Some((metatable_slot, metatable_generation)) = slot.metatable else { + return PendingFinalizerAction::Skip; + }; + if !self.slot_matches(metatable_slot, metatable_generation, HandleKind::Table) { + return PendingFinalizerAction::Skip; + } + let Some(value) = self.raw_named_value(metatable_slot, "__gc") else { + return PendingFinalizerAction::Skip; + }; + match value { + EdgeValue::Scalar(value) => match pending_finalizer_scalar_reject(value) { + Some(reject) => PendingFinalizerAction::NonCallable(reject), + None => PendingFinalizerAction::Skip, + }, + EdgeValue::Userdata { slot, generation } => { + if !self.slot_matches(*slot, *generation, HandleKind::Userdata) { + return PendingFinalizerAction::NonCallable( + PendingFinalizerNotCallable::Detached, + ); + } + let receiver = UserdataRef::userdata(self.domain, *slot, *generation); + match self.current_metatable_raw_call(*slot) { + CurrentRawCall::WithoutCall => PendingFinalizerAction::NonCallable( + PendingFinalizerNotCallable::UserdataWithoutCall(receiver), + ), + CurrentRawCall::NotClosure => PendingFinalizerAction::NonCallable( + PendingFinalizerNotCallable::UserdataCallNotClosure(receiver), + ), + CurrentRawCall::Closure(call) => { + PendingFinalizerAction::UserdataCall { receiver, call } + } + } + } + EdgeValue::Upvalue { .. } => { + PendingFinalizerAction::NonCallable(PendingFinalizerNotCallable::Upvalue) + } + EdgeValue::Closure { slot, generation } => { + if self.slot_matches(*slot, *generation, HandleKind::Closure) { + PendingFinalizerAction::Closure(ClosureRef::closure( + self.domain, + *slot, + *generation, + )) + } else { + PendingFinalizerAction::NonCallable(PendingFinalizerNotCallable::Detached) + } + } + EdgeValue::Table { slot, generation } => { + if !self.slot_matches(*slot, *generation, HandleKind::Table) { + return PendingFinalizerAction::NonCallable( + PendingFinalizerNotCallable::Detached, + ); + } + let receiver = TableRef::table(self.domain, *slot, *generation); + match self.current_metatable_raw_call(*slot) { + CurrentRawCall::WithoutCall => PendingFinalizerAction::NonCallable( + PendingFinalizerNotCallable::TableWithoutCall(receiver), + ), + CurrentRawCall::NotClosure => PendingFinalizerAction::NonCallable( + PendingFinalizerNotCallable::TableCallNotClosure(receiver), + ), + CurrentRawCall::Closure(call) => { + PendingFinalizerAction::TableCall { receiver, call } + } + } + } + } + } + + /// One raw `__call` lookup on a receiver's own current instance metatable. + /// + /// This is exactly one layer: the receiver slot's current metatable is + /// read, then its raw `__call` record. `__index` and the metatable's own + /// metatable are never followed, and a table-valued `__call` is not + /// dispatched again. The owner-chain lookup is linear in that metatable's + /// stored edge count and reads no selection cache. Nothing is written. + fn current_metatable_raw_call(&self, receiver_slot: u32) -> CurrentRawCall { + let Some((metatable_slot, metatable_generation)) = + self.slots[receiver_slot as usize].metatable + else { + return CurrentRawCall::WithoutCall; + }; + if !self.slot_matches(metatable_slot, metatable_generation, HandleKind::Table) { + return CurrentRawCall::WithoutCall; + } + let Some(call) = self.raw_named_value(metatable_slot, "__call") else { + return CurrentRawCall::WithoutCall; + }; + match call { + EdgeValue::Scalar(Value::Null) => CurrentRawCall::WithoutCall, + EdgeValue::Closure { slot, generation } + if self.slot_matches(*slot, *generation, HandleKind::Closure) => + { + CurrentRawCall::Closure(ClosureRef::closure(self.domain, *slot, *generation)) + } + _ => CurrentRawCall::NotClosure, + } + } + + /// Pops exactly `head`, writes the already validated roots, and settles + /// that generation once. + /// + /// This is the shared commit behind both dequeue entries. Every fallible + /// check, including the current raw-field resolution and the whole root + /// plan, has already finished in this same exclusive borrow. The published + /// front pop reads one record and its successor identity, clears the queued + /// slot fields, and moves one record out; it never reads the successor + /// record. The pop happens before the first root or slot write, and a + /// refusal leaves the queue and every root unchanged. No guest code is + /// called. + fn commit_published_finalizer( + &mut self, + head: PendingFinalizer, + userdata: UserdataRef, + roots: &[(usize, Rooted)], + ) -> Result { + let Some(popped) = self + .pending_finalizers + .pop_published_front(&mut self.slots, head) + else { + return Err(HeapError::Scope( + "lua pending finalizer head is not published".to_string(), + )); + }; + debug_assert_eq!(popped, head); + for (index, rooted) in roots { + self.roots[*index] = Some(*rooted); + } + let slot_record = &mut self.slots[head.slot as usize]; + slot_record.finalizer_settled = true; + Ok(userdata) + } + + /// Pops the exact published head, roots its typed userdata in the + /// specified empty slot, and settles that generation in one commit. + /// + /// Every refusal is checked before the first queue, root, or slot write: + /// a saved mark or tail, an unpublished head, a bad frame or slot, an + /// occupied root, and a record whose live slot no longer binds the exact + /// generation, kind, pending flag, and raw handle. The front record is + /// then popped with one published-front pop, the exact userdata is + /// written into the root slot, and the slot's pending flag is replaced by + /// its settled flag. It does not call a guest callback and does not read a + /// raw `__gc` field: this is the retained single-root test path. + pub(super) fn take_published_finalizer_into_root( + &mut self, + frame: RootFrameId, + slot: u32, + head: PendingFinalizer, + ) -> Result { + self.deny_unbarriered()?; + let indices = self.pending_finalizer_root_indices(frame, &[slot], 1)?; + let userdata = self.pending_finalizer_head_identity(head)?; + self.commit_published_finalizer(head, userdata, &[(indices[0], Rooted::Userdata(userdata))]) + } + + /// Pops one published head with a fresh raw-finalizer decision and roots + /// every identity that decision needs. + /// + /// The queue record is not trusted for callability: after the shared + /// identity preflight, the userdata's current metatable and its raw + /// `__gc` are read again in this same exclusive borrow, before any write. + /// `prepared` is the fixed-size action whose independent userdata receiver + /// already passed the typed owner check in the caller; this method + /// re-resolves the action and refuses any identity change + /// ([`HeapError::StaleHandle`]) before the pop. A table or userdata value + /// adds one raw `__call` read on that receiver's own current instance + /// metatable. An inherited or table-valued `__call` is a typed reject, not + /// a second dispatch, and the reject keeps the exact original receiver. + /// `slots[0]` always receives the userdata; a direct closure adds + /// `slots[1]`; a table call or an independent userdata receiver adds the + /// closure at `slots[1]` and the original receiver at `slots[2]`. A + /// userdata call whose receiver is the pending object itself adds only + /// `slots[1]`, because `slots[0]` already roots that receiver. Only that + /// required prefix is validated and written, and its positions must be + /// distinct. A skip or a reject retires exactly once with only the + /// userdata root. No guest code is called and no Core handle is copied. + pub(super) fn take_published_finalizer_action_into_roots( + &mut self, + frame: RootFrameId, + slots: &[u32], + head: PendingFinalizer, + prepared: PendingFinalizerAction, + ) -> Result { + self.deny_unbarriered()?; + let userdata = self.pending_finalizer_head_identity(head)?; + let action = self.pending_finalizer_action(userdata); + if action != prepared { + return Err(HeapError::StaleHandle); + } + let needed = match &action { + PendingFinalizerAction::Skip | PendingFinalizerAction::NonCallable(_) => 1, + PendingFinalizerAction::Closure(_) => 2, + PendingFinalizerAction::TableCall { .. } => 3, + PendingFinalizerAction::UserdataCall { receiver, .. } if *receiver == userdata => 2, + PendingFinalizerAction::UserdataCall { .. } => 3, + }; + let indices = self.pending_finalizer_root_indices(frame, slots, needed)?; + match action { + PendingFinalizerAction::Skip | PendingFinalizerAction::NonCallable(_) => { + self.commit_published_finalizer( + head, + userdata, + &[(indices[0], Rooted::Userdata(userdata))], + )?; + } + PendingFinalizerAction::Closure(closure) => { + self.commit_published_finalizer( + head, + userdata, + &[ + (indices[0], Rooted::Userdata(userdata)), + (indices[1], Rooted::Closure(closure)), + ], + )?; + } + PendingFinalizerAction::TableCall { receiver, call } => { + self.commit_published_finalizer( + head, + userdata, + &[ + (indices[0], Rooted::Userdata(userdata)), + (indices[1], Rooted::Closure(call)), + (indices[2], Rooted::Table(receiver)), + ], + )?; + } + PendingFinalizerAction::UserdataCall { receiver, call } => { + if receiver == userdata { + self.commit_published_finalizer( + head, + userdata, + &[ + (indices[0], Rooted::Userdata(userdata)), + (indices[1], Rooted::Closure(call)), + ], + )?; + } else { + self.commit_published_finalizer( + head, + userdata, + &[ + (indices[0], Rooted::Userdata(userdata)), + (indices[1], Rooted::Closure(call)), + (indices[2], Rooted::Userdata(receiver)), + ], + )?; + } + } + } + Ok(TakenPendingFinalizer { + userdata, + action, + roots_written: needed as u32, + }) + } + + /// Makes every currently stored pending record consumable after a + /// successful private publication. One header write; no record is read, + /// moved, or sorted. + pub(super) fn publish_pending_finalizer_prefix(&mut self) { + self.pending_finalizers.publish_all(); + } + + /// Removes only the records appended after `base` and clears their exact + /// slot flags. This is the pre-verification rollback of one selecting + /// batch: earlier valid records, their slots, tokens, and generations are + /// not read for mutation. The mark bits left by the failed pass are not + /// pending state; the next mark resets them. + /// + /// `base` is the round-start tail identity and length, never the published + /// length. The queue detaches that old tail's link and walks only the new + /// segment, so an unpublished older segment and the published prefix stay + /// queued and keep their order. + pub(crate) fn discard_pending_finalizers_from(&mut self, base: PendingCheckpoint) { + let _discarded = self + .pending_finalizers + .discard_from_checkpoint(&mut self.slots, base); + } + + /// One pending record read for the ordinary/parked Roots offer. + /// + /// `cursor` is the exact slot generation of the record offered now. The + /// method reads that one slot record, returns the live identity only if the + /// record still names the exact live generation whose snapshotted raw + /// handle matches the slot's current token, and returns the successor + /// identity stored on the same record. It never searches from the head and + /// never reads the successor record. + pub(super) fn pending_finalizer_offer( + &self, + cursor: PendingCursor, + ) -> (Option<(u32, u32)>, Option) { + let offer = self.pending_finalizers.offer(&self.slots, cursor); + #[cfg(test)] + self.pending_offer_trace.borrow_mut().push(cursor); + offer + } + + /// Copies the exact pending records as `(raw, slot, generation)`. + /// + /// The host entry borrows each token with that raw and its concrete + /// `lua.userdata` key before it closes any doomed token or publishes weak + /// edges. Order is the live-userdata chain order: newest allocation first + /// inside one cohort, with each later cohort stored after the earlier + /// records that are still queued. + pub(crate) fn pending_finalizer_records(&self) -> Vec<(u64, u32, u32)> { + self.pending_finalizers + .iter(&self.slots) + .map(|pending| (pending.raw, pending.slot, pending.generation)) + .collect() + } + + /// Round-start queue tail identity and length. Header reads only; no + /// record is read. This is the rollback base one selecting pass captures + /// before its selection can append anything. + pub(super) fn pending_finalizer_checkpoint(&self) -> PendingCheckpoint { + self.pending_finalizers.checkpoint() + } + + /// First queued record identity. A header read only, used to seed the mark + /// offer cursor once at mark start; it is not a positional search. + pub(super) fn pending_finalizer_head(&self) -> Option { + self.pending_finalizers.head() + } + + /// Test-only explicit retirement control for the eventual finalizer + /// consumer. + /// + /// It removes one exact record, clears the slot flag, and leaves the Core + /// token bound and the object live. It does not call a callback, close a + /// token, run guest code, or mark anything. A later collection may then + /// judge the object dead and close its token. Missing record, mismatch, a + /// parked mark, or a saved tail is refused before any change. + #[cfg(test)] + pub(crate) fn retire_pending_finalizer( + &mut self, + userdata: UserdataRef, + ) -> Result<(), HeapError> { + self.require_userdata(userdata)?; + self.deny_unbarriered()?; + let index = userdata.slot(); + let raw = self.slots[index as usize] + .token + .ok_or(HeapError::StaleHandle)?; + let Some(removed) = self.pending_finalizers.remove_exact( + &mut self.slots, + index, + userdata.generation(), + raw, + ) else { + return Err(HeapError::StaleHandle); + }; + debug_assert_eq!( + (removed.slot, removed.generation, removed.raw), + (index, userdata.generation(), raw) + ); + self.slots[index as usize].finalizer_settled = true; + Ok(()) + } + + /// Test-only: exact identities read by the Roots pending-record offer, in + /// visit order. The vector grows only under `cfg(test)` and is not read by + /// production. One entry is one real queue record read. + #[cfg(test)] + pub(crate) fn pending_offer_trace(&self) -> Vec<(u32, u32)> { + self.pending_offer_trace.borrow().clone() + } + + /// Test-only: the queue's real boundary counters since construction: + /// `(reads, slot_writes, header_writes, transfers)`. It does not clear them + /// and reads no record, so a session can take per-pulse deltas. + #[cfg(test)] + pub(crate) fn pending_queue_counts(&self) -> (u64, u64, u64, u64) { + self.pending_finalizers.counts() + } + + /// Test-only: actual slot indices written by the queue since the previous + /// take, in write order. This is the real per-slot write trace. + #[cfg(test)] + pub(crate) fn take_pending_queue_write_trace(&mut self) -> Vec { + self.pending_finalizers.take_write_trace() + } + + /// Test-only read of the per-slot pending flag. + #[cfg(test)] + pub(crate) fn slot_pending_finalizer(&self, userdata: UserdataRef) -> Result { + self.require_userdata(userdata)?; + Ok(self.slots[userdata.slot() as usize].pending_finalizer) + } + + /// Test-only read of the per-slot settled flag. + #[cfg(test)] + pub(crate) fn slot_finalizer_settled(&self, userdata: UserdataRef) -> Result { + self.require_userdata(userdata)?; + Ok(self.slots[userdata.slot() as usize].finalizer_settled) + } + + /// Test-only anti-control arm for the secondary metatable propagation. + /// + /// With the flag armed, `open_owner` does not follow the metatable edge of + /// a selected pending userdata. The userdata itself is still marked and + /// retained; its graph then dies. This proves the graph-retention + /// assertion depends on the real propagation. It changes no record and + /// runs no callback. + #[cfg(test)] + pub(crate) fn arm_pending_finalizer_metatable_skip(&mut self, armed: bool) { + self.skip_pending_finalizer_metatable = armed; + } + + /// Test-only anti-control for the Release invariant: the next publish + /// clears this exact pending slot's mark bit, so the bounded Select check + /// must reject it before any weak publication or release. It does not + /// change a record, token, or generation. + #[cfg(test)] + pub(crate) fn arm_pending_finalizer_reclaim_control( + &mut self, + userdata: UserdataRef, + ) -> Result<(), HeapError> { + self.require_userdata(userdata)?; + if !self.slots[userdata.slot() as usize].pending_finalizer { + return Err(HeapError::StaleHandle); + } + self.reclaim_pending_slot = Some(userdata.slot()); + Ok(()) + } + + /// The staged Core raw handle for one exact reservation, before publish. + /// + /// Test-only: the private retry entry reads it to close the same token + /// after a refused rollback. An ordinary borrow never accepts it. + #[cfg(test)] + pub(super) fn pending_userdata_token(&self, userdata: UserdataRef) -> Result { + self.require_userdata(userdata)?; + let Some(pending) = self.pending_userdata else { + return Err(HeapError::StaleHandle); + }; + if pending.slot != userdata.slot() || pending.generation != userdata.generation() { + return Err(HeapError::StaleHandle); + } + pending.raw.ok_or(HeapError::StaleHandle) + } + + /// Releases one empty userdata reservation made by + /// [`Self::reserve_userdata`] and returns the slot generation after + /// release. + /// + /// The exact pending record must still name this slot and generation, and + /// the slot itself must carry no binding, edge, metatable, mode pointer, + /// or carrier. Those checks are O(1): this call does not walk the roots or + /// the owner chains, and it is not a rollback for an arbitrary published + /// userdata. The next issuance takes the next generation (or the slot + /// retires at the generation cap). + pub(super) fn rollback_empty_userdata( + &mut self, + handle: UserdataRef, + ) -> Result { + self.require_userdata(handle)?; + self.ensure_sweep_open()?; + let index = handle.slot() as usize; + let Some(pending) = self.pending_userdata else { + return Err(HeapError::StaleHandle); + }; + if pending.slot != handle.slot() || pending.generation != handle.generation() { + return Err(HeapError::StaleHandle); + } + let slot = &self.slots[index]; + if slot.token.is_some() + || slot.edge_head.is_some() + || slot.edge_tail.is_some() + || slot.metatable.is_some() + || slot.mode_edge.is_some() + || slot.carrier.is_some() + { + return Err(HeapError::Scope( + "userdata rollback is only valid for an empty reservation".to_string(), + )); + } + self.pending_userdata = None; + self.release_slot(handle.slot()); + Ok(self.slots[index].generation) + } + + /// 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.ensure_sweep_open()?; + self.slots[table.slot() as usize].token = None; + Ok(()) + } + + /// 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, generation, kind, and raw + /// handle 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.kind == token.kind + && slot.token == Some(token.raw) + }); + if !matches { + return false; + } + self.scan.token_slot_checks += 1; + self.slots[token.slot as usize].token = None; + 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() + } + + /// 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() + } + + /// 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), + } + } + + /// The userdata in one frame slot, if that slot holds a userdata. This is + /// a test observation for the private handoff and does not scan. + #[cfg(test)] + pub(crate) fn rooted_userdata( + &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::Userdata(userdata)) => Ok(Some(userdata)), + Some(_) => Err(HeapError::StaleHandle), + } + } + + /// The closure in one frame slot, if that slot holds a closure. This is a + /// test observation for the private action handoff and does not scan. + #[cfg(test)] + pub(crate) fn rooted_closure( + &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::Closure(closure)) => Ok(Some(closure)), + Some(_) => Err(HeapError::StaleHandle), + } + } + + /// Domain that issued handles for this heap. Does not read slots. + pub(super) fn domain(&self) -> u64 { + self.domain + } + + /// Next nonzero epoch for slot weak-start and rescan-queue tags. Wrapping + /// skips zero, so a new mark never accepts a stale tag. + fn advance_rescan_epoch(&mut self) -> u64 { + loop { + self.rescan_epoch = self.rescan_epoch.wrapping_add(1); + if self.rescan_epoch != 0 { + return self.rescan_epoch; + } + } + } + + /// 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(()) + } + } + + /// Refuses a userdata allocation or edge write that has no full barrier. + /// + /// A saved tail is reported first. A parked mark, including paused gray, is + /// `MarkDenied`. `alloc_slot` only checks the tail, so callers that cannot + /// barrier the new node must use this before taking or growing a slot. + fn deny_unbarriered(&self) -> Result<(), HeapError> { + self.ensure_sweep_open()?; + if self.mark.is_some() { + return Err(HeapError::MarkDenied); + } + Ok(()) + } + + 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 { + 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"); + } + } + } + + /// 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 + /// 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) + } + + /// The private single-shot entry's mark: the same ordinary mark, then one + /// selection scan for finalizer-eligible userdata after the gray, rescan, + /// and late work has emptied, then the usual pending-close enumeration. + /// + /// Selection marks each raw-`__gc`-positive userdata through the ordinary + /// target follow, so `open_owner` follows its metatable edge and the + /// metatable's own strong entries are scanned by the ordinary gray loop. + /// A raw-`__gc`-negative candidate is settled instead: it is not marked, + /// not queued, and not retained, but a live marked generation is + /// value-dead for weak publication. The phase does not run in + /// [`Self::mark_and_doomed_tokens`], so an ordinary host collection + /// neither selects new objects nor charges the selection units. A second + /// selecting pass skips a slot that is already pending or settled. + pub(super) fn mark_and_pending_tokens(&mut self) -> DoomedMark { + let modes = self.mark_reachable_selecting_pending(); + 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() + } + + /// 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. + /// + /// 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`]. A dead slot that + /// still stores a bound host token is refused by the shared sweep + /// selection, before weak publication or release, so this path cannot + /// skip a typed resource. + /// + /// # Panics + /// + /// Panics when the shared selection step reaches an unmarked live slot + /// that still carries a bound host token. This method has no + /// `HostContext`, so it cannot close that resource. The host collector + /// closes every doomed token first and clears the binding. + pub fn collect(&mut self) -> CollectReport { + self.drain_sweep_tail(); + let modes = self.mark_reachable(); + self.sweep_marked(modes) + } + + /// Releases nodes the current mark did not reach. Does not mark 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. The shared selection + /// step refuses (panics on) a dead slot that still stores a host token: + /// a host caller must close and clear every doomed binding first. + pub(super) fn sweep_marked(&mut self, modes: MarkSnapshot) -> CollectReport { + let mut session = SweepSession::start(self, modes); + session.drain(); + 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); + } + if self.sweep_tail.is_some() { + return Err(HeapError::SweepPending); + } + 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 that sweep + /// publishes: a dead slot exists, or a retained pending finalizer needs + /// its weak values cleared. + 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) + } + + /// Publishes weak edges and stores the release tail. No dead slot and no + /// retained pending finalizer 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"); + #[cfg(test)] + if let Some(slot) = self.reclaim_pending_slot.take() + && let Some(stored) = self.slots.get_mut(slot as usize) + && stored.pending_finalizer + && matches!(stored.state, SlotState::Live { marked: true }) + { + stored.state = SlotState::Live { marked: false }; + } + 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() + } + + /// 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() + } + + /// Reports whether `handle` names a live bare userdata in this heap. + pub fn userdata_alive(&self, handle: UserdataRef) -> bool { + self.require_userdata(handle).is_ok() + } + + /// Generation stored in one slot, if that slot exists. Test-only: the + /// generation check for a live handle is its own typed accessor. + #[cfg(test)] + pub(crate) fn slot_generation(&self, slot: u32) -> Option { + self.slots + .get(slot as usize) + .map(|stored| stored.generation) + } + + /// Whether one slot is physically live. Test-only. + #[cfg(test)] + pub(crate) fn slot_is_live(&self, slot: u32) -> bool { + self.slots + .get(slot as usize) + .is_some_and(|stored| matches!(stored.state, SlotState::Live { .. })) + } + + /// Owner chains the legacy rollback edge walk opened since the heap was + /// created. Test-only observation for the empty-reservation rollback. + #[cfg(test)] + pub(crate) fn rollback_owner_visits(&self) -> u64 { + self.rollback_owner_visits + } + + /// Clears the recorded selection slot indices. Test-only. + #[cfg(test)] + pub(super) fn clear_selection_slot_trace(&mut self) { + self.selection_slot_trace.borrow_mut().clear(); + } + + /// Slot indices actually indexed since the last clear. Test-only. + #[cfg(test)] + pub(super) fn selection_slot_trace(&self) -> Vec { + self.selection_slot_trace.borrow().clone() + } + + /// Edge records read by the raw `__gc` selection lookup since the last + /// clear, as `(metatable_slot, edge_record_index)`. Test-only. + #[cfg(test)] + pub(crate) fn pending_gc_edge_trace(&self) -> Vec<(u32, u32)> { + self.pending_gc_edge_trace.borrow().clone() + } + + /// Clears the raw `__gc` edge-read trace. Test-only. + #[cfg(test)] + pub(crate) fn clear_pending_gc_edge_trace(&mut self) { + self.pending_gc_edge_trace.borrow_mut().clear(); + } + + /// Live-userdata chain nodes read by the private selection since the last + /// clear, as `(slot, generation)` in visit order. Test-only: each entry is + /// one real slot-record read, not a selected-record count. + #[cfg(test)] + pub(crate) fn pending_live_trace(&self) -> Vec<(u32, u32)> { + self.pending_live_trace.borrow().clone() + } + + /// Clears the live-userdata chain-read trace. Test-only. + #[cfg(test)] + pub(crate) fn clear_pending_live_trace(&mut self) { + self.pending_live_trace.borrow_mut().clear(); + } + + /// Records one pending-finalizer record whose typed owner borrow and + /// exact slot/generation check passed. Test-only; the push is the real + /// success boundary in the pre-publication verifier. + #[cfg(test)] + pub(crate) fn record_owner_verification_success(&self, slot: u32, generation: u32) { + self.owner_verification_trace + .borrow_mut() + .push((slot, generation)); + } + + /// Identities that passed the real pending-finalizer owner check since + /// the last clear, in record order. Test-only. + #[cfg(test)] + pub(crate) fn owner_verification_trace(&self) -> Vec<(u32, u32)> { + self.owner_verification_trace.borrow().clone() + } + + /// Number of real pending-finalizer owner-check successes since the last + /// clear. Test-only; a prefix of a refused pass stays visible. + #[cfg(test)] + pub(crate) fn owner_verification_successes(&self) -> usize { + self.owner_verification_trace.borrow().len() + } + + /// Clears the real owner-verification success trace. Test-only. + #[cfg(test)] + pub(crate) fn clear_owner_verification_trace(&mut self) { + self.owner_verification_trace.borrow_mut().clear(); + } + + /// Walks the live-userdata chain head to tail and asserts each link is + /// internally consistent at its exact generation. Test-only observation + /// for release, rollback, neighbour, and same-slot successor checks. + #[cfg(test)] + pub(crate) fn live_userdata_chain(&self) -> Vec<(u32, u32)> { + let mut chain = Vec::new(); + let mut previous = None; + let mut cursor = self.live_userdata_head; + while let Some((index, generation)) = cursor { + let slot = self + .slots + .get(index as usize) + .expect("a live-userdata chain node names a slot"); + assert_eq!(slot.generation, generation, "chain generation"); + assert_eq!(slot.kind, HandleKind::Userdata, "chain node kind"); + assert!(slot.live_userdata_linked, "chain node is linked"); + assert_eq!(slot.live_userdata_prev, previous, "chain back link"); + chain.push((index, generation)); + previous = Some((index, generation)); + cursor = slot.live_userdata_next; + assert!(chain.len() <= self.slots.len(), "chain must not cycle"); + } + assert_eq!(previous, self.live_userdata_tail, "chain tail"); + chain + } + + /// Identities currently linked in the settlement journal, from the head. + /// Test-only: the walk observes membership and does not count as a + /// rollback visit or as a successful-pass drain. + #[cfg(test)] + pub(crate) fn settlement_journal_members(&self) -> Vec<(u32, u32)> { + let mut members = Vec::new(); + let mut cursor = self.settlement_head; + while let Some(index) = cursor { + let Some(slot) = self.slots.get(index as usize) else { + break; + }; + members.push((index, slot.settlement_generation)); + cursor = slot.settlement_next; + } + members + } + + /// Number of identities currently linked in the settlement journal. + /// Test-only. + #[cfg(test)] + pub(crate) fn settlement_journal_len(&self) -> u32 { + self.settlement_journal_len + } + + /// Takes the identities actually visited by a failed-pass journal + /// rollback, in visit order. Test-only; a successful pass and Release + /// leave the trace empty. + #[cfg(test)] + pub(crate) fn take_settlement_journal_trace(&mut self) -> Vec<(u32, u32)> { + std::mem::take(&mut *self.settlement_journal_trace.borrow_mut()) + } + + /// 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(), + live_roots: self.live_roots(), + live_edges: self.live_edge_count, + node_slots: self.slots.len() as u32, + root_slots: self.roots.len() as u32, + edge_slots: self.occupied_edges, + collections: self.collections, + last_marked: self.last_marked, + peak_nodes: self.peak_nodes, + peak_roots: self.peak_roots, + peak_edges: self.peak_edges, + } + } + + /// 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 (`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: + /// - `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`. 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 = (u64::from(self.occupied_edges)) * (std::mem::size_of::() as u64); + nodes + edges + self.payload_bytes + } + + fn require_live(&self, handle: TableRef) -> Result<(), HeapError> { + 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_userdata(&self, handle: UserdataRef) -> Result<(), HeapError> { + self.require_kind( + handle.domain(), + handle.slot(), + handle.generation(), + HandleKind::Userdata, + ) + } + + fn require_kind( + &self, + domain: u64, + slot: u32, + generation: u32, + kind: HandleKind, + ) -> Result<(), HeapError> { + if domain != self.domain { + return Err(HeapError::WrongDomain); + } + if self.slot_matches(slot, generation, kind) { + return 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_matches(&self, index: u32, generation: u32, kind: HandleKind) -> bool { + self.slots.get(index as usize).is_some_and(|slot| { + slot.generation == generation + && slot.kind == kind + && matches!(slot.state, SlotState::Live { .. }) + }) + } + + /// 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() + } + + /// Drops any parked mark, then runs one mark whose selection phase scans + /// for finalizer-eligible userdata after the ordinary work empties. + /// Selection records and marks each chosen userdata; its metatable graph + /// is then scanned by the same gray loop. A close failure after this mark + /// does not put the mark back, but the records and marked bits remain + /// until the next reset, so a retry marks the same records again. + fn mark_reachable_selecting_pending(&mut self) -> MarkSnapshot { + let abandoned = self.mark.take(); + drop(abandoned); + let mut session = MarkSession::start_selecting_pending(self); + session.drain(); + session.into_snapshot() + } + + /// Links one freshly allocated userdata at the live-chain head. + /// + /// The caller has already committed the live slot at `generation`. The + /// append is four link writes and the two head/tail fields; it grows + /// nothing and moves no other node. A slot that is already linked is a + /// caller bug. + fn link_live_userdata_head(&mut self, index: u32, generation: u32) { + debug_assert_eq!(self.slots[index as usize].generation, generation); + debug_assert_eq!(self.slots[index as usize].kind, HandleKind::Userdata); + debug_assert!(matches!( + self.slots[index as usize].state, + SlotState::Live { .. } + )); + debug_assert!(!self.slots[index as usize].live_userdata_linked); + let head = self.live_userdata_head; + { + let slot = &mut self.slots[index as usize]; + slot.live_userdata_prev = None; + slot.live_userdata_next = head; + slot.live_userdata_linked = true; + } + if let Some((head_index, head_generation)) = head { + let head_slot = &mut self.slots[head_index as usize]; + debug_assert_eq!(head_slot.generation, head_generation); + debug_assert!(head_slot.live_userdata_linked); + debug_assert!(head_slot.live_userdata_prev.is_none()); + head_slot.live_userdata_prev = Some((index, generation)); + } + self.live_userdata_head = Some((index, generation)); + if self.live_userdata_tail.is_none() { + self.live_userdata_tail = Some((index, generation)); + } + } + + /// Unlinks one live userdata from the chain in constant work. + /// + /// The links carry the exact generation of each neighbour, so a successor + /// generation cannot be reached through an old link. A slot that is not + /// linked is left alone: release of a table, closure, or cell does not + /// touch this chain. The head and tail updates are the same bounded + /// neighbour writes; no node is scanned, moved, or sorted. + fn unlink_live_userdata(&mut self, index: u32) { + if !self.slots[index as usize].live_userdata_linked { + return; + } + debug_assert_eq!(self.slots[index as usize].kind, HandleKind::Userdata); + let identity = (index, self.slots[index as usize].generation); + let prev = self.slots[index as usize].live_userdata_prev.take(); + let next = self.slots[index as usize].live_userdata_next.take(); + self.slots[index as usize].live_userdata_linked = false; + match prev { + Some((prev_index, prev_generation)) => { + let prev_slot = &mut self.slots[prev_index as usize]; + debug_assert_eq!(prev_slot.generation, prev_generation); + debug_assert!(prev_slot.live_userdata_linked); + debug_assert_eq!(prev_slot.live_userdata_next, Some(identity)); + prev_slot.live_userdata_next = next; + } + None => { + debug_assert_eq!(self.live_userdata_head, Some(identity)); + self.live_userdata_head = next; + } + } + match next { + Some((next_index, next_generation)) => { + let next_slot = &mut self.slots[next_index as usize]; + debug_assert_eq!(next_slot.generation, next_generation); + debug_assert!(next_slot.live_userdata_linked); + debug_assert_eq!(next_slot.live_userdata_prev, Some(identity)); + next_slot.live_userdata_prev = prev; + } + None => { + debug_assert_eq!(self.live_userdata_tail, Some(identity)); + self.live_userdata_tail = prev; + } + } + } + + fn release_slot(&mut self, index: u32) { + // A live userdata leaves the selection chain before the generation + // advances, the state becomes Free/Retired, or any field is cleared. + // The unlink is the released slot's own two neighbours and two links, + // never a walk of the chain and never a pending-queue read. + if self.slots[index as usize].kind == HandleKind::Userdata { + self.unlink_live_userdata(index); + } else { + debug_assert!( + !self.slots[index as usize].live_userdata_linked, + "a non-userdata slot cannot join the live-userdata chain" + ); + } + 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.pending_userdata.is_some_and(|pending| { + pending.slot == index && pending.generation == self.slots[index as usize].generation + }) { + debug_assert!( + self.pending_userdata + .is_some_and(|pending| pending.raw.is_none()), + "a registered userdata reservation reached release without its mark retention" + ); + self.pending_userdata = None; + } + // A pending record is a host-retained edge; a selected slot must not + // reach release. The per-slot flag is the bounded invariant: release + // reads only this slot, never the pending queue. + debug_assert!( + !self.slots[index as usize].pending_finalizer, + "a pending finalizer reached release without its retirement" + ); + self.slots[index as usize].pending_finalizer = false; + self.slots[index as usize].pending_next = None; + self.slots[index as usize].pending_raw = None; + self.slots[index as usize].pending_generation = 0; + self.slots[index as usize].finalizer_settled = false; + self.slots[index as usize].pending_gc_generation = 0; + self.slots[index as usize].pending_gc_round = 0; + self.slots[index as usize].pending_gc_non_nil = false; + let mark = self.mark.as_mut(); + mark::release_ordinary_gray(mark, &mut self.slots, index); + let mark = self.mark.as_mut(); + mark::release_rescan_slot(mark, &mut self.slots, index); + let mark = self.mark.as_mut(); + mark::release_late_slot(mark, &mut self.slots, index); + 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; + slot.mode_epoch = 0; + slot.mode_generation = 0; + slot.mode_round = 0; + slot.mode_weak = WeakMode::default(); + slot.mode_checked_generation = 0; + slot.mode_checked_round = 0; + slot.mode_checked_epoch = 0; + slot.discover_generation = 0; + slot.discover_batch = 0; + slot.discover_round = 0; + 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) { + for owner in 0..self.slots.len() { + #[cfg(test)] + { + self.rollback_owner_visits += 1; + } + 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; + } + } + debug_assert!(self.slots[slot as usize].edge_head.is_none()); + debug_assert!(self.slots[slot as usize].edge_tail.is_none()); + } + + fn clear_rooted_to(&mut self, rooted: Rooted) { + for root in &mut self.roots { + if *root == Some(rooted) { + *root = None; + } + } + } + + fn rooted_alive(&self, rooted: Rooted) -> bool { + match rooted { + Rooted::Table(handle) => self.alive(handle), + Rooted::Closure(handle) => self.closure_alive(handle), + Rooted::Upvalue(handle) => self.upvalue_alive(handle), + Rooted::Userdata(handle) => self.userdata_alive(handle), + } + } + + 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.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, + late_epoch: 0, + late_owner: 0, + late_value: None, + late_key: None, + late_prev: None, + late_next: 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) -> Result<(), HeapError> { + self.ensure_sweep_open()?; + 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 Ok(()); + } + prev = Some(index); + cursor = next; + } + Ok(()) + } + + fn unlink_at(&mut self, owner: u32, prev: Option, index: u32) { + let next = self.edge_slots[index as usize].next; + let cleared_mode = self.slots[owner as usize].mode_edge == Some(index); + 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, + } + if self.slots[owner as usize].edge_tail == Some(index) { + self.slots[owner as usize].edge_tail = prev; + } + if cleared_mode { + self.slots[owner as usize].mode_edge = None; + self.slots[owner as usize].mode_epoch = + self.slots[owner as usize].mode_epoch.wrapping_add(1); + } + self.free_edge_record(index); + if cleared_mode { + self.note_direct_mode_deleted(owner); + } + } + + fn free_edge_record(&mut self, index: u32) { + mark::release_late_edge(self.mark.as_mut(), &mut self.edge_slots, index); + 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 (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"); + 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); + if self.mark.is_some() { + self.barrier_strong_field(owner, index, barrier); + } + } + + 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); + self.slots[owner as usize].mode_epoch = + self.slots[owner as usize].mode_epoch.wrapping_add(1); + self.note_late_mode_write(owner); + } + } +} + +fn edge_key_is_slot(key: &EdgeKey, slot: u32) -> bool { + matches!(key, EdgeKey::Object { slot: key_slot, .. } if *key_slot == slot) +} + +/// 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)> { + let ordinary_named_or_number = matches!(key, EdgeKey::Utf8(_) | EdgeKey::Number(_)); + if old_gap && !ordinary_named_or_number { + return None; + } + 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 { + return None; + } + match value { + EdgeValue::Table { slot, generation } => Some((*slot, *generation)), + _ => None, + } +} + +/// Test-only queue boundary counts: `(reads, slot_writes, header_writes, +/// transfers)`. The alias keeps the pulse boundary signature readable and is +/// not part of the production API. +#[cfg(test)] +pub(crate) type PendingQueueCounts = (u64, u64, u64, u64); + +/// Test-only facade over the private selecting mark. +/// +/// The pulse witness drives the real mark one charged unit at a time, so it +/// can read the real pending-`__gc` edge meter before and after every call. +/// It also snapshots the real live-userdata chain-read trace after every +/// pulse, so a caller can assert the exact per-pulse chain cursor delta +/// without treating a scan-slot counter or a selected-record count as the +/// walk. It does not publish weak edges, close a token, or run a callback. +#[cfg(test)] +pub(crate) struct SelectingPendingMark<'a> { + session: MarkSession<'a>, + live_trace: LiveTrace, + live_seen: usize, + /// Number of Roots offer-trace entries already returned by a queue-meter + /// pulse. The trace vector lives on the heap and grows monotonically. + offer_seen: usize, +} + +#[cfg(test)] +impl<'a> SelectingPendingMark<'a> { + pub(crate) fn start(heap: &'a mut LuaHeap) -> Self { + let live_trace = heap.pending_live_trace.share(); + let live_seen = live_trace.borrow().len(); + let offer_seen = heap.pending_offer_trace().len(); + Self { + session: MarkSession::start_selecting_pending(heap), + live_trace, + live_seen, + offer_seen, + } + } + + /// Copies the cumulative meter without changing mark state. + pub(crate) fn meter(&self) -> ScanMeter { + self.session.meter() + } + + /// Test-only: queue boundary counters after the last pulse. The alias is + /// `(reads, slot_writes, header_writes, transfers)` and is read from the + /// queue's real access boundary, not from a logical pulse count. + #[cfg(test)] + pub(crate) fn pending_queue_counts(&self) -> PendingQueueCounts { + self.session.pending_queue_counts() + } + + /// Test-only: drains the queue's actual slot-write trace for this session. + #[cfg(test)] + pub(crate) fn take_pending_queue_write_trace(&mut self) -> Vec { + self.session.take_pending_queue_write_trace() + } + + /// Runs one unit and returns `(finished, cumulative meter, queue counts, + /// offer-record deltas)`. Each offer delta element is one real queue record + /// read by this call through the Roots cursor. + #[cfg(test)] + pub(crate) fn pulse_with_queue_meter( + &mut self, + budget: u64, + ) -> (bool, ScanMeter, PendingQueueCounts, Vec<(u32, u32)>) { + let view = self.session.pulse(budget); + let trace = self.session.pending_offer_trace(); + let start = self.offer_seen.min(trace.len()); + let offers = trace[start..].to_vec(); + self.offer_seen = trace.len(); + ( + view.finished, + view.meter, + self.session.pending_queue_counts(), + offers, + ) + } + + /// Runs one unit and returns `(finished, cumulative meter, chain reads)`. + /// Each `chain reads` element is one real live-userdata chain node read by + /// this call, in visit order; the delta never includes an earlier pulse. + pub(crate) fn pulse_with_live_trace( + &mut self, + budget: u64, + ) -> (bool, ScanMeter, Vec<(u32, u32)>) { + let view = self.session.pulse(budget); + let trace = self.live_trace.borrow(); + let start = self.live_seen.min(trace.len()); + let live_reads = trace[start..].to_vec(); + self.live_seen = trace.len(); + (view.finished, view.meter, live_reads) + } + + /// Runs one unit and returns `(finished, cumulative meter)`. + pub(crate) fn pulse(&mut self, budget: u64) -> (bool, ScanMeter) { + let (finished, meter, _live_reads) = self.pulse_with_live_trace(budget); + (finished, meter) + } +} + +/// Test-only typed published-head transaction surface. +/// +/// This relative path resolves to the real module in the compiler harness +/// (`tests/compiler/heap_file_entry/tests/luajit_heap_runtime/`) and to the +/// empty stand-in in the heap harness (`tests/luajit_heap_runtime/`), so only +/// the compiler harness compiles and consumes these heap-owner entries. The +/// module is a child of this table module, so it can use the private head, +/// root, and settle primitives without widening any of them. +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/typed_published_api.rs"] +mod typed_published_api; + +/// Slot-level callable-carrier units. The business path (a real `.lua` guest +/// import) is exercised by the file-entry witness; these units use fabricated +/// `CallableValue` Arcs only to reach the private store and the generation +/// mechanics that a guest cannot name directly. That is the narrow test-only +/// scope for pure slot refusal; no production or dequeue path can call the +/// store with a bare count. +#[cfg(test)] +mod callable_carrier_units { + use super::*; + + fn callable(prototype_id: u32) -> Arc { + Arc::new(CallableValue { + prototype_id, + kind: CallableKind::Closure, + env: None, + }) + } + + #[test] + fn slot_units_cover_rebind_capture_foreign_wrong_kind_and_table_carrier() { + let mut heap = LuaHeap::new(HeapLimits::production()); + let closure = heap.alloc_closure().expect("closure"); + let first = callable(1); + let second = callable(2); + assert!( + !Arc::ptr_eq(&first, &second), + "the two Arcs are distinct instances" + ); + + heap.store_guest_callable(closure, Arc::clone(&first), 0) + .expect("store first"); + assert_eq!( + heap.guest_callable_admissions(), + &[closure], + "a successful store is the only thing that records an admission" + ); + assert_eq!( + heap.store_guest_callable(closure, Arc::clone(&second), 0), + Err(HeapError::CarrierAlreadyBound), + "a same-generation rebind is refused" + ); + { + let stored = heap.closure_callable(closure).expect("stored first"); + assert!( + Arc::ptr_eq(&stored, &first), + "the refused rebind left the original Arc" + ); + assert!(!Arc::ptr_eq(&stored, &second)); + } + assert_eq!(Arc::strong_count(&first), 2, "local and slot"); + assert_eq!( + Arc::strong_count(&second), + 1, + "the refused Arc is not retained" + ); + + let fresh = heap.alloc_closure().expect("fresh closure"); + let captured = callable(3); + let captured_before = Arc::strong_count(&captured); + assert_eq!( + heap.store_guest_callable(fresh, Arc::clone(&captured), 1), + Err(HeapError::CallableHasEnvironment), + "a capture count is refused before the slot changes" + ); + assert_eq!( + Arc::strong_count(&captured), + captured_before, + "the refused store retains no Arc" + ); + assert!( + matches!( + heap.closure_callable(fresh), + Err(HeapError::CarrierNotBound) + ), + "the refused generation stays unbound" + ); + + let unbound = heap.alloc_closure().expect("unbound closure"); + assert!(matches!( + heap.closure_callable(unbound), + Err(HeapError::CarrierNotBound) + )); + + let table = heap.alloc().expect("table"); + let wrong_kind = heap.closure_handle_for_table(table); + assert!(matches!( + heap.closure_callable(wrong_kind), + Err(HeapError::WrongKind) + )); + assert_eq!( + heap.store_guest_callable(wrong_kind, Arc::clone(&second), 0), + Err(HeapError::WrongKind) + ); + + let mut foreign_heap = LuaHeap::new(HeapLimits::production()); + let foreign = foreign_heap.alloc_closure().expect("foreign closure"); + assert!(matches!( + heap.closure_callable(foreign), + Err(HeapError::WrongDomain) + )); + assert_eq!( + heap.store_guest_callable(foreign, Arc::clone(&second), 0), + Err(HeapError::WrongDomain) + ); + + // The existing table carrier path stays one carrier per generation + // and is not a callable carrier. + let issued = heap.issue_carrier(table).expect("table carrier"); + assert!( + matches!(issued, Value::Array(_)), + "the table carrier stays the issued VM array" + ); + assert!( + matches!(heap.issue_carrier(table), Err(HeapError::StaleHandle)), + "a second issue for the live generation is refused" + ); + assert!(matches!( + heap.closure_callable(wrong_kind), + Err(HeapError::WrongKind) + )); + } + + #[test] + fn guest_import_schema_is_registered_only_in_the_controlled_shape() { + let schema = LuaHeap::guest_callable_import_schema(); + assert_eq!(schema.name, LuaHeap::GUEST_CALLABLE_IMPORT); + assert_eq!(schema.params.len(), 1); + assert_eq!(schema.params[0].name, "target"); + assert_eq!(schema.params[0].ty, HostTypeSchema::Unknown); + assert_eq!(schema.params[0].passing, vm::HostParamPassing::Value); + assert_eq!(schema.return_type, HostTypeSchema::Bool); + + let mut builder = vm::HostApiBuilder::new(); + builder.function(schema); + let catalog = builder.build().expect("controlled catalog"); + let function = catalog + .function(LuaHeap::GUEST_CALLABLE_IMPORT) + .expect("declared function"); + let import = HostImportSchema::from_function(&catalog, function); + let mut registry = HostFunctionRegistry::empty(); + LuaHeap::register_guest_callable_import(&mut registry, import.clone()) + .expect("the controlled import registers"); + + let mut tampered = import; + tampered.return_type = HostTypeSchema::Int; + let mut registry = HostFunctionRegistry::empty(); + assert!( + LuaHeap::register_guest_callable_import(&mut registry, tampered).is_err(), + "a caller-supplied shape is not accepted as the controlled import" + ); + } + + #[test] + fn raw_call_field_import_schema_is_registered_only_in_the_fixed_two_argument_shape() { + let schema = LuaHeap::guest_callable_field_import_schema(); + assert_eq!(schema.name, LuaHeap::GUEST_CALLABLE_IMPORT); + assert_eq!(schema.params.len(), 2); + assert_eq!(schema.params[0].name, "owner"); + assert_eq!(schema.params[0].ty, HostTypeSchema::Unknown); + assert_eq!(schema.params[0].passing, vm::HostParamPassing::Value); + assert_eq!(schema.params[1].name, "target"); + assert_eq!(schema.params[1].ty, HostTypeSchema::Unknown); + assert_eq!(schema.params[1].passing, vm::HostParamPassing::Value); + assert_eq!(schema.return_type, HostTypeSchema::Bool); + + let mut builder = vm::HostApiBuilder::new(); + builder.function(schema); + let catalog = builder.build().expect("raw call field catalog"); + let function = catalog + .function(LuaHeap::GUEST_CALLABLE_IMPORT) + .expect("declared field function"); + let import = HostImportSchema::from_function(&catalog, function); + let mut registry = HostFunctionRegistry::empty(); + LuaHeap::register_guest_callable_field_import(&mut registry, import.clone()) + .expect("the fixed two-argument import registers"); + + let mut tampered = import; + tampered.params[0].name = "slot".to_string(); + let mut registry = HostFunctionRegistry::empty(); + assert!( + LuaHeap::register_guest_callable_field_import(&mut registry, tampered).is_err(), + "a caller-supplied owner name is not accepted as the controlled shape" + ); + + let mut tampered = HostImportSchema::from_function(&catalog, function); + tampered.params[1].schema = HostTypeSchema::Int; + let mut registry = HostFunctionRegistry::empty(); + assert!( + LuaHeap::register_guest_callable_field_import(&mut registry, tampered).is_err(), + "a caller-supplied target type is not accepted as the controlled shape" + ); + } + + #[test] + fn release_drops_one_arc_and_a_reused_generation_starts_unbound() { + let mut heap = LuaHeap::new(HeapLimits::production()); + let first_slot = heap.alloc_closure().expect("first closure"); + let first = callable(10); + heap.store_guest_callable(first_slot, Arc::clone(&first), 0) + .expect("store first"); + assert_eq!(Arc::strong_count(&first), 2, "local and slot"); + + let report = heap.collect(); + assert_eq!( + report.live_nodes, 0, + "the unrooted closure must be collected" + ); + assert!(!heap.closure_alive(first_slot)); + assert!(matches!( + heap.closure_callable(first_slot), + Err(HeapError::StaleHandle) + )); + assert_eq!( + Arc::strong_count(&first), + 1, + "release dropped exactly the slot's one Arc" + ); + assert_eq!( + heap.slot_generation(first_slot.slot()), + Some(first_slot.generation() + 1), + "release advanced the slot generation" + ); + + let reused = heap.alloc_closure().expect("reuse the released slot"); + assert_eq!(reused.slot(), first_slot.slot()); + assert_eq!(reused.generation(), first_slot.generation() + 1); + assert!( + matches!( + heap.closure_callable(reused), + Err(HeapError::CarrierNotBound) + ), + "a reused generation starts unbound" + ); + + let second = callable(11); + heap.store_guest_callable(reused, Arc::clone(&second), 0) + .expect("store on the reused generation"); + assert_eq!( + heap.guest_callable_admissions(), + &[first_slot, reused], + "each admitted generation is recorded once, in order" + ); + { + let stored = heap.closure_callable(reused).expect("stored second"); + assert!( + Arc::ptr_eq(&stored, &second), + "the reused generation returns the new Arc" + ); + assert!( + !Arc::ptr_eq(&stored, &first), + "the reused generation cannot return the old Arc" + ); + } + assert!( + matches!( + heap.closure_callable(first_slot), + Err(HeapError::StaleHandle) + ), + "the old generation stays stale after reuse" + ); + } +} + +/// Storage-level units for the raw `__call` field handoff. The business path +/// is one real `.lua` guest import; these units use fabricated `CallableValue` +/// Arcs only to reach the state machine a guest cannot name: saved mark, +/// published Release tail, full node/edge caps, and the unsupported raw values. +#[cfg(test)] +mod raw_call_field_units { + use super::*; + + fn callable(prototype_id: u32) -> Arc { + Arc::new(CallableValue { + prototype_id, + kind: CallableKind::Closure, + env: None, + }) + } + + fn picture( + heap: &LuaHeap, + owner: TableRef, + metatable: TableRef, + ) -> (HeapStats, Option, Option) { + ( + heap.stats(), + heap.slot_generation(owner.slot()), + heap.slot_generation(metatable.slot()), + ) + } + + fn owner_with_metatable( + heap: &mut LuaHeap, + edge: Option, + ) -> (TableRef, TableRef, Value) { + let owner = heap.alloc().expect("owner"); + let metatable = heap.alloc().expect("metatable"); + heap.set_metatable(owner, Some(metatable)) + .expect("attach metatable"); + if let Some(value) = edge { + heap.set_named_scalar(metatable, RAW_CALL_FIELD, value) + .expect("sentinel"); + } + let owner_value = heap.issue_carrier(owner).expect("owner carrier"); + (owner, metatable, owner_value) + } + + #[test] + fn full_edge_cap_replaces_the_sentinel_then_the_installed_closure() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 8, + roots: 2, + edges: 1, + max_generation: 8, + }); + let (owner, metatable, owner_value) = + owner_with_metatable(&mut heap, Some(Value::Bool(false))); + let before = picture(&heap, owner, metatable); + assert_eq!( + heap.stats().edge_slots, + 1, + "the false sentinel occupies the one allowed edge record" + ); + + let first = callable(1); + let first_closure = heap + .handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&first), 0) + .expect("first replacement"); + assert_eq!( + heap.named_closure_edge(metatable, RAW_CALL_FIELD) + .expect("raw edge is a closure"), + first_closure, + "the raw edge must name the fresh first generation" + ); + assert!( + Arc::ptr_eq( + &heap.closure_callable(first_closure).expect("first carrier"), + &first + ), + "the first generation must own the exact guest Arc" + ); + let after_first = picture(&heap, owner, metatable); + assert_eq!(after_first.0.live_nodes, before.0.live_nodes + 1); + assert_eq!( + after_first.0.edge_slots, before.0.edge_slots, + "replacing an existing record must not allocate a second edge" + ); + assert_eq!(after_first.0.live_edges, before.0.live_edges); + assert_eq!(after_first.1, before.1, "the owner generation is unchanged"); + assert_eq!( + after_first.2, before.2, + "the metatable generation is unchanged" + ); + assert_eq!(Arc::strong_count(&first), 2, "local plus the new slot"); + + let second = callable(2); + let second_closure = heap + .handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&second), 0) + .expect("second replacement over the existing closure"); + assert_ne!(first_closure.slot(), second_closure.slot()); + assert_eq!( + heap.named_closure_edge(metatable, RAW_CALL_FIELD) + .expect("raw edge is a closure"), + second_closure, + "the raw edge must name the fresh second generation" + ); + assert!( + Arc::ptr_eq( + &heap + .closure_callable(second_closure) + .expect("second carrier"), + &second + ), + "the second generation must own the exact guest Arc" + ); + assert!( + heap.closure_alive(first_closure), + "the replaced generation stays live until a real collection" + ); + assert!( + Arc::ptr_eq( + &heap + .closure_callable(first_closure) + .expect("first carrier survives replacement"), + &first + ), + "the old generation still owns its own Arc" + ); + let after_second = picture(&heap, owner, metatable); + assert_eq!(after_second.0.live_nodes, after_first.0.live_nodes + 1); + assert_eq!(after_second.0.edge_slots, after_first.0.edge_slots); + assert_eq!(after_second.1, before.1); + assert_eq!(after_second.2, before.2); + assert_eq!(Arc::strong_count(&second), 2, "local plus the new slot"); + } + + #[test] + fn missing_and_unsupported_raw_states_refuse_without_a_change() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 10, + roots: 2, + edges: 4, + max_generation: 8, + }); + let (owner, metatable, owner_value) = owner_with_metatable(&mut heap, None); + let callable = callable(7); + + let missing_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::StaleHandle) + ); + assert_eq!(picture(&heap, owner, metatable), missing_before); + assert_eq!(heap.named_raw_scalar(metatable, RAW_CALL_FIELD), Ok(None)); + assert_eq!(Arc::strong_count(&callable), 1); + + heap.set_named_scalar(metatable, RAW_CALL_FIELD, Value::Bool(true)) + .expect("true sentinel"); + let true_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::WrongKind) + ); + assert_eq!(picture(&heap, owner, metatable), true_before); + assert_eq!( + heap.named_raw_scalar(metatable, RAW_CALL_FIELD), + Ok(Some(Value::Bool(true))) + ); + assert_eq!(Arc::strong_count(&callable), 1); + + heap.set_named_gap_test_control(metatable, RAW_CALL_FIELD) + .expect("stored nil gap"); + let gap_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::WrongKind) + ); + assert_eq!(picture(&heap, owner, metatable), gap_before); + assert_eq!( + heap.named_raw_scalar(metatable, RAW_CALL_FIELD), + Ok(Some(Value::Null)) + ); + assert_eq!(Arc::strong_count(&callable), 1); + + let other = heap.alloc().expect("table target"); + heap.set_named_edge(metatable, RAW_CALL_FIELD, other) + .expect("table-valued raw call"); + let table_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::WrongKind) + ); + assert_eq!(picture(&heap, owner, metatable), table_before); + assert_eq!(heap.named_edge(metatable, RAW_CALL_FIELD), Ok(Some(other))); + assert_eq!(Arc::strong_count(&callable), 1); + + let userdata = heap.alloc_userdata().expect("userdata target"); + heap.set_named_userdata(metatable, RAW_CALL_FIELD, userdata) + .expect("userdata-valued raw call"); + let userdata_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::WrongKind) + ); + assert_eq!(picture(&heap, owner, metatable), userdata_before); + assert_eq!(Arc::strong_count(&callable), 1); + + let bare_closure = heap.alloc_closure().expect("closure without a carrier"); + heap.set_named_closure(metatable, RAW_CALL_FIELD, bare_closure) + .expect("closure-valued raw call"); + let bare_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::WrongKind) + ); + assert_eq!(picture(&heap, owner, metatable), bare_before); + assert_eq!(Arc::strong_count(&callable), 1); + + let captured_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 1), + Err(HeapError::CallableHasEnvironment) + ); + assert_eq!(picture(&heap, owner, metatable), captured_before); + assert_eq!(Arc::strong_count(&callable), 1); + + let lookalike = Value::array(vec![ + Value::Int(i64::from(owner.slot())), + Value::Int(i64::from(owner.generation())), + ]); + let unissued_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&lookalike, Arc::clone(&callable), 0), + Err(HeapError::WrongKind) + ); + assert_eq!(picture(&heap, owner, metatable), unissued_before); + assert_eq!(Arc::strong_count(&callable), 1); + } + + #[test] + fn saved_mark_and_published_release_tail_refuse_before_any_write() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 10, + roots: 2, + edges: 2, + max_generation: 8, + }); + let (owner, metatable, owner_value) = + owner_with_metatable(&mut heap, Some(Value::Bool(false))); + let callable = callable(9); + + ParkedMark::open_saved(&mut heap).expect("saved mark"); + assert!(heap.has_saved_mark()); + let mark_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::MarkDenied) + ); + assert_eq!(picture(&heap, owner, metatable), mark_before); + assert_eq!( + heap.named_raw_scalar(metatable, RAW_CALL_FIELD), + Ok(Some(Value::Bool(false))) + ); + assert_eq!(Arc::strong_count(&callable), 1); + drop(ParkedMark::resume(&mut heap).expect("saved mark is still open")); + assert!(!heap.has_saved_mark()); + + let dead = heap.alloc().expect("dead table"); + let frame = heap.enter_roots(1).expect("root frame"); + heap.write_root(frame, 0, owner).expect("root owner"); + let modes = heap.mark_reachable(); + match heap.halt_at_publish(modes) { + PublishHalt::Published { .. } => {} + _ => panic!("expected a published Release tail"), + } + assert!(heap.has_sweep_tail()); + assert_eq!( + heap.saved_tail_state().expect("saved tail state").phase, + SavedTailPhase::Release + ); + let tail_before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::SweepPending) + ); + assert_eq!(picture(&heap, owner, metatable), tail_before); + assert_eq!( + heap.named_raw_scalar(metatable, RAW_CALL_FIELD), + Ok(Some(Value::Bool(false))) + ); + assert_eq!(Arc::strong_count(&callable), 1); + assert!(matches!( + heap.resume_sweep_tail(u64::MAX), + TailResume::Completed(_) + )); + assert!(!heap.alive(dead)); + heap.clear_root(frame, 0).expect("clear the owner root"); + heap.leave_roots(frame).expect("leave the owner root frame"); + } + + #[test] + fn full_node_capacity_refuses_without_changing_the_field() { + let mut heap = LuaHeap::new(HeapLimits { + nodes: 2, + roots: 2, + edges: 1, + max_generation: 8, + }); + let (owner, metatable, owner_value) = + owner_with_metatable(&mut heap, Some(Value::Bool(false))); + assert_eq!(heap.stats().node_slots, 2); + let callable = callable(11); + let before = picture(&heap, owner, metatable); + assert_eq!( + heap.handoff_guest_callable_to_raw_call(&owner_value, Arc::clone(&callable), 0), + Err(HeapError::NodeCapacity) + ); + assert_eq!(picture(&heap, owner, metatable), before); + assert_eq!( + heap.named_raw_scalar(metatable, RAW_CALL_FIELD), + Ok(Some(Value::Bool(false))) + ); + assert_eq!(Arc::strong_count(&callable), 1); + } +} + +#[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; +#[cfg(test)] +#[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; +#[cfg(test)] +#[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/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_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)] +#[path = "../../../../tests/luajit_heap_runtime/resume_cycle.rs"] +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; +#[cfg(test)] +#[path = "../../../../tests/luajit_heap_runtime/userdata_identity.rs"] +mod userdata_identity; diff --git a/src/frontends/lua/heap/table/mark.rs b/src/frontends/lua/heap/table/mark.rs new file mode 100644 index 0000000..745bec9 --- /dev/null +++ b/src/frontends/lua/heap/table/mark.rs @@ -0,0 +1,3789 @@ +//! 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. `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), +//! 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. The private pending-finalizer selection adds one phase whose pulse +//! unit is one live-userdata chain node read; only the private selecting entry +//! enables it. +//! +//! Late work is bounded by live sites, not by mutation count: one parse per +//! metatable slot (intrusive queue), one deferred transition check per owner, +//! and one deferred target per edge record (coalesced in place). A known mode +//! is decided by the setter; only a mode still being read queues deferred +//! work, so repeated overwrites of one marked edge do not starve ordinary +//! Gray steps. The two implementation costs are explicit rather than hidden: +//! a late parse stores into the record-keyed map, one O(log L) insertion and +//! one such query per owner head, with L bounded by live metatable slots; the +//! ordinary Gray work is an intrusive LIFO on the slot records, so a push or +//! a pop writes a constant number of neighbour links, never allocates, and +//! never copies or relocates a work vector. Every ordinary pulse still +//! charges at most one of the listed units. +//! +//! A safepoint root batch is not one of those units. `accept_root_batch` is +//! open in Roots, Gray, or the late sub-phase: 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. An accepting phase, including the +//! late sub-phase and a same-pulse entry from Start, Reset, or Mode, commits +//! once before any root, gray, or late step. A budget that runs out before an +//! accepting phase does not commit. The next call, 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 +//! non-gap ordinary field on an already marked owner, and a fixed root-slot +//! 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. + +use super::{ + ClosureRef, CollectReport, EdgeKey, EdgeValue, HandleKind, HeapError, HeapStats, LuaHeap, + MarkSnapshot, PendingCandidate, RootFrameId, Rooted, Slot, SlotState, TableRef, UpvalueRef, + WeakMode, +}; +use vm::Value; + +/// One open raw-`__gc` lookup in the private pending-finalizer selection. +/// `cursor` is the next metatable edge record to read; one pulse step reads at +/// most that one record. +#[derive(Clone, Copy)] +struct PendingGcLookup { + candidate: PendingCandidate, + cursor: Option, +} + +pub(super) struct MarkState { + phase: MarkPhase, + /// Head and tail of the ordinary Gray LIFO. The head carries the exact + /// slot generation that was linked, so a pop never opens a successor + /// generation that reused the slot. The node links live on the slots; + /// this Vec-free queue never allocates, copies, or relocates. + gray_head: Option<(u32, u32)>, + gray_tail: Option<(u32, u32)>, + gray_len: u32, + /// Test-only actual link accesses: one per node read, one per node write, + /// and one per head/tail header update. They make the local constant of a + /// push, a pop, and a release visible instead of inferred. + #[cfg(test)] + gray_node_reads: u64, + #[cfg(test)] + gray_node_writes: u64, + #[cfg(test)] + gray_header_writes: u64, + modes: Option>, + /// Marked targets from a deferred replay, linked on their slot records. + /// They are scanned after the ordinary Gray LIFO empties and drained + /// last-in-first-out, so a replay never touches the ordinary chain and + /// never relocates it. At most one node per slot: a target joins only on + /// the mark-bit transition. + late_target_head: Option, + late_target_tail: Option, + index: usize, + /// Set when the root enumeration has offered the exact registered + /// userdata reservation to the mark. That reservation is not a guest + /// value and does not enter `roots`; it is one host-retained edge checked + /// once per mark after the explicit roots. + pending_reservation_checked: bool, + /// Private single-shot entry only: after the ordinary gray, rescan, and + /// late work empties, walk the live-userdata chain once for + /// finalizer-eligible + /// userdata. Each selected userdata is marked through the ordinary target + /// follow, so the following gray pass traces its metatable graph. An + /// ordinary mark leaves this false and never charges the selection units. + select_pending: bool, + /// The one selection scan finished. A second gray pass may now finish the + /// mark. + pending_scan_done: bool, + /// Next live-userdata chain node and the exact generation the cursor + /// names. `None` ends the selection phase. The pair is read from the + /// chain link, so a successor generation occupying the same slot is not + /// visited through an old node. + pending_live: Option<(u32, u32)>, + /// One open raw-`__gc` lookup for the candidate just read from + /// `pending_live`. + /// Each step reads at most one metatable edge record and caches the result + /// for this mark round and exact metatable generation. + pending_lookup: Option, + /// Next pending record offered as a host-retained edge in Roots, as the + /// exact slot/generation identity. The first record is read from the queue + /// header once when the mark starts; every later step follows the successor + /// identity stored on the record just read. It never searches from the head + /// and reads at most one queue record per pulse unit. `None` ends the offer. + pending_offer: Option<(u32, u32)>, + mode_edge: Option, + mode_owner: usize, + byte_at: usize, + pending_mode: WeakMode, + init_at: usize, + pub(super) owner: Option, + pub(super) cursor: Option, + owner_kind: HandleKind, + owner_mode: WeakMode, + /// First node of this mark's rescan queue. The links live on the slots, so + /// a push or a release-time unlink is constant work and allocates nothing. + rescan_head: Option, + /// Identifies this mark's weak-start and queue tags on slot records. A new + /// mark gets a new value; a slot tag from an older mark is inert without a + /// whole-slot clear, including after an abandoned mark. + rescan_epoch: u64, + rescan_owner: Option, + rescan_cursor: Option, + rescan_mode: WeakMode, + /// Indexed by metatable slot; initialized alongside the weak-mode cache. + /// Stamps from completed passes are left in place and no longer match. + discover_marks: Vec, + /// Zero is reserved for unarmed slots. Each new batch requires another + /// distinct cache entry to become strong, so at most `limits.nodes` + /// batches can start in one mark (no slot reuse in the mutation window). + discover_batch: u32, + /// A delete after the cursor moves stamps the next batch instead, so + /// owners behind the cursor are not missed. + discover_next: bool, + discover_at: usize, + discover_on: bool, + /// Slots with a direct `__mode` write that still needs a budgeted read, + /// in first-write order. The links live on the slots; no index vector is + /// grown in the late window. + late_mode_head: Option, + late_mode_tail: Option, + /// One open parse. It is identified by the slot, generation, edge record + /// and write version; a different value at any of them restarts at byte + /// zero rather than mixing two writes. + late_slot: Option, + late_generation: u32, + late_epoch: u32, + late_edge: Option, + late_byte_at: usize, + late_pending_mode: WeakMode, + /// Owners whose metatable transition needs the finished late cache. At + /// most one record per owner, first-old/final-new. + late_owner_head: Option, + late_owner_tail: Option, + /// Edge records with a write that needs the finished late cache. At most + /// one record per edge, latest live target. + late_edge_head: Option, + late_edge_tail: Option, + /// Phase the late window returns to. Set only on entering `ModeLate`. + late_return: Option, +} + +/// A write that already happened in the mutation window but whose mode read +/// depends on a late metatable. There is no separate event vector: the state +/// lives on the owner slot or the edge record, so a repeat write coalesces in +/// place and an unlink or release removes it in constant work. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +struct ModeDiscoveryMark { + generation: u32, + batch: u32, + /// Mark round that armed this stamp. Batch numbers restart at one each + /// mark, so a same-generation metatable that survives into a later round + /// must not match an old slot-fallback stamp. + round: u64, +} + +/// Mark phases. `ModeLate` is entered only while the mark is already inside +/// the roots or gray window: a `__mode` field written during that window +/// registers a bounded late parse. The setter only links the slot; one pulse +/// unit opens or restarts the parse, one reads one byte, and one consumes a +/// deferred owner or edge check. No indexed cache is grown. +#[derive(Clone, Copy, PartialEq, Eq)] +enum MarkPhase { + Start, + Reset, + ModeOpen, + ModeBytes, + ModeInit, + Roots, + Gray, + Pending, + ModeLate, + Done, +} + +pub(super) struct MarkView { + pub(super) finished: bool, + pub(super) meter: super::ScanMeter, +} + +/// 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. `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 { + fn new(rescan_epoch: u64) -> Self { + Self { + phase: MarkPhase::Start, + gray_head: None, + gray_tail: None, + gray_len: 0, + #[cfg(test)] + gray_node_reads: 0, + #[cfg(test)] + gray_node_writes: 0, + #[cfg(test)] + gray_header_writes: 0, + modes: None, + late_target_head: None, + late_target_tail: None, + index: 0, + pending_reservation_checked: false, + select_pending: false, + pending_scan_done: false, + pending_live: None, + pending_lookup: None, + pending_offer: None, + 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(), + rescan_head: None, + rescan_epoch, + rescan_owner: None, + rescan_cursor: None, + rescan_mode: WeakMode::default(), + discover_marks: Vec::new(), + discover_batch: 0, + discover_next: false, + discover_at: 0, + discover_on: false, + late_mode_head: None, + late_mode_tail: None, + late_slot: None, + late_generation: 0, + late_epoch: 0, + late_edge: None, + late_byte_at: 0, + late_pending_mode: WeakMode::default(), + late_owner_head: None, + late_owner_tail: None, + late_edge_head: None, + late_edge_tail: None, + late_return: None, + } + } + + fn mutation_open(&self) -> bool { + matches!(self.phase, MarkPhase::Roots | MarkPhase::Gray) + } + + /// The write hooks stay active through the late-mode sub-phase: a guest + /// can write between any two pulses, and a late parse is still inside the + /// roots/gray window rather than a new mark. + fn write_barriers_open(&self) -> bool { + matches!( + self.phase, + MarkPhase::Roots | MarkPhase::Gray | MarkPhase::ModeLate + ) + } + + fn has_late_work(&self) -> bool { + self.late_mode_head.is_some() + || self.late_owner_head.is_some() + || self.late_edge_head.is_some() + } + + 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::Pending => "pending-finalizer", + MarkPhase::ModeLate => "mode-late", + 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"); + debug_assert!( + !heap.has_sweep_tail(), + "a published sweep tail and a mark session cannot coexist" + ); + let rescan_epoch = heap.advance_rescan_epoch(); + let mut state = MarkState::new(rescan_epoch); + state.pending_offer = heap.pending_finalizer_head(); + heap.mark = Some(state); + Self { heap } + } + + /// One ordinary mark, plus one selection scan after the ordinary work + /// empties. Only the private pending-finalizer entry uses this starter. + /// The scan starts from an empty settlement journal; a previous pulse-only + /// selecting mark leaves its chain head here, and its flags stay. + pub(super) fn start_selecting_pending(heap: &'a mut LuaHeap) -> Self { + heap.clear_selecting_settlements(); + let session = Self::start(heap); + session + .heap + .mark + .as_mut() + .expect("start installed the mark state") + .select_pending = true; + session + } + + pub(super) fn meter(&self) -> super::ScanMeter { + self.heap.scan + } + + /// Test-only queue boundary counters while this session still borrows the + /// heap: `(reads, slot_writes, header_writes, transfers)`. + #[cfg(test)] + pub(super) fn pending_queue_counts(&self) -> (u64, u64, u64, u64) { + self.heap.pending_queue_counts() + } + + /// Test-only copy of the Roots offer trace. The caller takes per-pulse + /// deltas by length. + #[cfg(test)] + pub(super) fn pending_offer_trace(&self) -> Vec<(u32, u32)> { + self.heap.pending_offer_trace() + } + + /// Test-only: drains the queue's actual slot-write trace. + #[cfg(test)] + pub(super) fn take_pending_queue_write_trace(&mut self) -> Vec { + self.heap.take_pending_queue_write_trace() + } + + pub(super) fn pulse(&mut self, budget: u64) -> MarkView { + 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 self + .heap + .mark + .as_ref() + .is_some_and(|state| !matches!(state.phase, MarkPhase::Done)) + { + self.pulse(64); + } + } + + pub(super) fn sweep(self) -> CollectReport { + let state = self.heap.mark.take().expect("mark state"); + assert!( + matches!(state.phase, MarkPhase::Done), + "sweep needs a finished mark" + ); + self.heap.sweep_marked(MarkSnapshot { + modes: state.modes, + round: state.rescan_epoch, + }) + } + + 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, + round: state.rescan_epoch, + } + } +} + +impl Drop for MarkSession<'_> { + fn drop(&mut self) { + self.heap.mark = None; + } +} + +impl<'a> ParkedMark<'a> { + pub(super) fn start(heap: &'a mut LuaHeap) -> Result { + if heap.mark.is_some() { + return Err(HeapError::MarkActive); + } + if heap.has_sweep_tail() { + return Err(HeapError::SweepPending); + } + let rescan_epoch = heap.advance_rescan_epoch(); + let mut state = MarkState::new(rescan_epoch); + state.pending_offer = heap.pending_finalizer_head(); + heap.mark = Some(state); + Ok(Self { + 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(()) + } + + /// 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 + } + + 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(); + } + 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(), + round: state.rescan_epoch, + }); + } else { + self.heap.mark = Some(state); + } + 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 { + if self.done.is_some() || self.swept { + return Err(HeapError::MarkDenied); + } + let (view, done) = self + .heap + .advance_saved_mark_with_root_batch(budget, batch)?; + if let Some(snapshot) = done { + self.done = Some(snapshot); + } + 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 { + owner: state.owner?, + cursor: state.cursor?, + }) + } + + /// Owner and record the weak-to-strong rescan will charge next. + /// Independent of [`Self::pending`]. Absent unless that scan is paused + /// on a record. This reads two fields and does not move either cursor. + pub(super) fn pending_rescan(&self) -> Option { + let state = self.heap.mark.as_ref()?; + Some(PendingScan { + owner: state.rescan_owner?, + cursor: state.rescan_cursor?, + }) + } + + /// Test-only direct read of the saved mark's rescan list head. The node + /// links live on the slots; this accessor observes only the header that + /// the setter path writes when it schedules one owner. + #[cfg(test)] + pub(super) fn rescan_head(&self) -> Option { + self.heap.mark.as_ref().and_then(|state| state.rescan_head) + } + + /// Next slot a deleted-mode probe will read. `None` when that walk is + /// not armed. This does not move the cursor. + #[cfg(test)] + pub(super) fn discovery_slot(&self) -> Option { + let state = self.heap.mark.as_ref()?; + if !state.discover_on { + return None; + } + u32::try_from(state.discover_at).ok() + } + + 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 }) + }) + } + + pub(super) fn phase_name(&self) -> &'static str { + if self.done.is_some() { + return "done"; + } + 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) + } + + /// Mutation through the whole roots/gray window, including the budgeted + /// late-mode sub-phase. Used by the write hooks and gated root writers. + pub(super) fn write_barriers_open(&self) -> bool { + self.heap + .mark + .as_ref() + .is_some_and(MarkState::write_barriers_open) + } + + pub(super) fn write_allowed(&self, owner: TableRef) -> bool { + self.write_barriers_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)) + } + + 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 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. + /// The shared writer barriers the table value; this path does not enqueue again. + 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; + Ok(()) + } + + /// Accepts a borrowed root batch in this exclusive window. + /// + /// Open in Roots, Gray, or the late sub-phase. 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"); + commit_root_batch(self.heap, &mut state, batch); + self.heap.mark = Some(state); + Ok(()) + } + + fn gate_root_batch(&self, batch: &[Rooted]) -> Result<(), HeapError> { + if !self.saved_mark()?.write_barriers_open() { + return Err(HeapError::MarkDenied); + } + validate_root_batch(self.heap, batch) + } + + 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) + } + + /// 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) + } + + 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) + } + + /// 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); + } + Err(HeapError::MarkActive) + } + + 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), + } + } + + pub(super) fn cancel(mut self) { + self.heap.mark = None; + self.done = None; + } + + /// 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 Some(modes) = self.done.take() else { + return Err(HeapError::MarkDenied); + }; + 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, + } + } + + fn gate_field(&self, from: TableRef, key: u32) -> Result<(), HeapError> { + self.gate_mutation()?; + // 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)?; + Ok(()) + } + + fn gate_mutation(&self) -> Result<(), HeapError> { + let state = self.heap.mark.as_ref().ok_or(HeapError::MarkDenied)?; + if !state.write_barriers_open() { + return Err(HeapError::MarkDenied); + } + Ok(()) + } +} + +impl Drop for ParkedMark<'_> { + fn drop(&mut self) { + if !self.keep { + self.heap.mark = None; + } + } +} + +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 + /// 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(), + round: state.rescan_epoch, + }), + )) + } else { + self.mark = Some(state); + Ok((view, None)) + } + } +} + +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(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)?, + Rooted::Closure(handle) => heap.require_closure(handle)?, + Rooted::Upvalue(handle) => heap.require_upvalue(handle)?, + Rooted::Userdata(handle) => heap.require_userdata(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); + } + if matches!(state.phase, MarkPhase::Start) { + 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 | MarkPhase::ModeLate + ) + { + if let Some(batch) = batch { + commit_root_batch(heap, state, batch); + } + handed = true; + } + if step(heap, state) { + left -= 1; + spins = 0; + } else { + 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 { + if matches!(state.phase, MarkPhase::Roots | MarkPhase::Gray) && state.has_late_work() { + state.late_return = Some(state.phase); + state.phase = MarkPhase::ModeLate; + } + 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::Pending => step_pending(heap, state), + MarkPhase::ModeLate => step_mode_late(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; + // Every slot the round may reuse loses the ordinary Gray tag, both Gray + // neighbour links, this slot's weak-start/rescan membership tag, and any + // late-target queue tag in the existing per-slot Reset unit. The stamp can + // wrap and be reused by a later round, so flags or links left by an + // abandoned mark must never join the new round's rescan scheduling or its + // late-target list. The rescan header and cursor and the late-mode, + // late-owner, and deferred-edge queues are elsewhere and are not touched + // here. + { + let stored = &mut heap.slots[index]; + clear_gray_slot(stored); + stored.rescan_epoch = 0; + stored.rescan_queued = false; + stored.rescan_prev = None; + stored.rescan_next = None; + stored.late_target_epoch = 0; + stored.late_target_prev = None; + stored.late_target_next = None; + if let SlotState::Live { marked } = &mut stored.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 { + // The record version was inspected here even though its value is not + // a mode string. First attachment must not re-read this version; a + // later write still bumps `mode_epoch` and registers a late parse. + mark_mode_checked(heap, state, state.mode_owner as u32); + 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(heap, 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(heap, state); + return true; + } + _ => {} + } + let len = mode_string_len(heap, edge_index).unwrap_or(0); + if state.byte_at >= len { + finish_mode_parse(heap, state); + } + true +} + +fn finish_mode_parse(heap: &mut LuaHeap, state: &mut MarkState) { + let parsed = state.pending_mode; + mark_mode_checked(heap, state, state.mode_owner as u32); + if parsed.keys || parsed.values { + if state.modes.is_none() { + state.init_at = 0; + state.phase = MarkPhase::ModeInit; + return; + } + store_mode(heap, 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)); + state.discover_marks = Vec::with_capacity(slot_count); + } + let modes = state.modes.as_mut().expect("mode init has a cache"); + modes.push(WeakMode::default()); + state.discover_marks.push(ModeDiscoveryMark::default()); + heap.scan.scratch.weak_modes_inited += 1; + heap.scan.scratch.mode_discover_inited += 1; + state.init_at += 1; + if state.init_at == slot_count { + let parsed = state.pending_mode; + store_mode(heap, state, parsed); + advance_after_mode(state); + } + true +} + +/// Store one parsed mode for the generation that owned the read. The reset +/// walk writes into the indexed vector it sized. A parse outside that vector +/// writes the slot's own weak bits; no record-keyed tree is touched, and the +/// slot generation and this mark's round travel with the bits as the parse +/// identity. +fn store_cache_mode( + heap: &mut LuaHeap, + state: &mut MarkState, + slot: u32, + generation: u32, + parsed: WeakMode, +) { + let in_indexed = state + .modes + .as_ref() + .is_some_and(|modes| (slot as usize) < modes.len()); + match heap.slots.get_mut(slot as usize) { + Some(stored) => { + stored.mode_generation = generation; + stored.mode_round = state.rescan_epoch; + if !in_indexed { + stored.mode_weak = parsed; + } + } + None => return, + } + if in_indexed && let Some(modes) = state.modes.as_mut() { + modes[slot as usize] = parsed; + } +} + +fn store_mode(heap: &mut LuaHeap, state: &mut MarkState, parsed: WeakMode) { + let slot = state.mode_owner as u32; + let generation = heap.slots[state.mode_owner].generation; + store_cache_mode(heap, state, slot, generation, parsed); +} + +/// Records the exact direct `__mode` record version inspected by this round, +/// either by the reset walk or by a finished late read. The read consumes the +/// string even when it names no weak side, so this stamp is what tells a later +/// first attachment that this field version is already inspected. It +/// deliberately does not touch `mode_generation`, `mode_round`, or the weak +/// bits: those remain the parsed weak-mode cache, and a write after this read +/// must still admit a late parse that sees, for example, an `x -> v` rewrite +/// before the owner opens. +fn mark_mode_checked(heap: &mut LuaHeap, state: &MarkState, slot: u32) { + let Some(stored) = heap.slots.get_mut(slot as usize) else { + return; + }; + stored.mode_checked_generation = stored.generation; + stored.mode_checked_round = state.rescan_epoch; + stored.mode_checked_epoch = stored.mode_epoch; +} + +fn advance_after_mode(state: &mut MarkState) { + state.mode_edge = None; + state.index += 1; + state.phase = MarkPhase::Reset; +} + +/// One budget unit of the late window. Every queued mode is parsed before any +/// deferred owner or edge check. Each call charges at most one open/restart, +/// one byte, or one deferred event. The queues are intrusive on the records, +/// so a new registration is a constant append and a release unlink is +/// constant work. +fn step_mode_late(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + if state.late_mode_head.is_some() { + return step_late_mode(heap, state); + } + if let Some((owner, old_tuple, new_tuple, old_mode)) = pop_late_owner(heap, state) { + apply_owner_check(heap, state, owner, old_tuple, new_tuple, old_mode); + return true; + } + if let Some((index, owner, key, value)) = pop_late_edge(heap, state) { + apply_edge_check(heap, state, index, owner, key, value); + return true; + } + state.phase = state.late_return.take().unwrap_or(MarkPhase::Roots); + false +} + +/// Open, restart, or advance the head parse by one unit. The parse identity +/// includes the slot generation, the current `__mode` edge record, and that +/// record's write version. A rewrite or unlink changes at least one of them, +/// so the reader resets its cursor and pending bits instead of combining the +/// new bytes with the old prefix or length. +fn step_late_mode(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let Some(slot) = state.late_mode_head else { + return false; + }; + let Some(stored) = heap.slots.get(slot as usize) else { + pop_late_mode(heap, state); + return true; + }; + if stored.kind != HandleKind::Table || !matches!(stored.state, SlotState::Live { .. }) { + pop_late_mode(heap, state); + return true; + } + let generation = stored.generation; + let edge = stored.mode_edge; + let epoch = stored.mode_epoch; + if state.late_slot != Some(slot) + || state.late_generation != generation + || state.late_edge != edge + || state.late_epoch != epoch + { + state.late_slot = Some(slot); + state.late_generation = generation; + state.late_edge = edge; + state.late_epoch = epoch; + state.late_byte_at = 0; + state.late_pending_mode = WeakMode::default(); + heap.scan.weak_mode_edge_checks += 1; + if edge.is_none() { + finish_late_mode(heap, state, WeakMode::default()); + } + return true; + } + let Some(edge) = edge else { + finish_late_mode(heap, state, WeakMode::default()); + return true; + }; + let at = state.late_byte_at; + let Some(byte) = mode_string_byte(heap, edge, at) else { + finish_late_mode(heap, state, state.late_pending_mode); + return true; + }; + heap.scan.weak_mode_bytes += 1; + state.late_byte_at = at + 1; + match byte { + b'k' => state.late_pending_mode.keys = true, + b'v' => state.late_pending_mode.values = true, + 0 => { + finish_late_mode(heap, state, state.late_pending_mode); + return true; + } + _ => {} + } + let len = mode_string_len(heap, edge).unwrap_or(0); + if state.late_byte_at >= len { + finish_late_mode(heap, state, state.late_pending_mode); + } + true +} + +fn push_late_mode(heap: &mut LuaHeap, state: &mut MarkState, slot: u32) { + { + let stored = &mut heap.slots[slot as usize]; + stored.late_mode_epoch = state.rescan_epoch; + stored.late_mode_prev = state.late_mode_tail; + stored.late_mode_next = None; + } + if let Some(tail) = state.late_mode_tail { + heap.slots[tail as usize].late_mode_next = Some(slot); + } else { + state.late_mode_head = Some(slot); + } + state.late_mode_tail = Some(slot); +} + +fn pop_late_mode(heap: &mut LuaHeap, state: &mut MarkState) -> Option { + let slot = state.late_mode_head?; + let next = heap + .slots + .get(slot as usize) + .and_then(|stored| stored.late_mode_next); + if let Some(stored) = heap.slots.get_mut(slot as usize) { + stored.late_mode_epoch = 0; + stored.late_mode_prev = None; + stored.late_mode_next = None; + } + state.late_mode_head = next; + match next { + Some(next) => { + if let Some(stored) = heap.slots.get_mut(next as usize) { + stored.late_mode_prev = None; + } + } + None => state.late_mode_tail = None, + } + Some(slot) +} + +fn push_late_owner(heap: &mut LuaHeap, state: &mut MarkState, owner: u32) { + { + let stored = &mut heap.slots[owner as usize]; + stored.late_owner_epoch = state.rescan_epoch; + stored.late_owner_prev = state.late_owner_tail; + stored.late_owner_next = None; + } + if let Some(tail) = state.late_owner_tail { + heap.slots[tail as usize].late_owner_next = Some(owner); + } else { + state.late_owner_head = Some(owner); + } + state.late_owner_tail = Some(owner); +} + +#[allow(clippy::type_complexity)] +fn pop_late_owner( + heap: &mut LuaHeap, + state: &mut MarkState, +) -> Option<( + u32, + Option<(u32, u32)>, + Option<(u32, u32)>, + Option, +)> { + let owner = state.late_owner_head?; + let stored = heap.slots.get(owner as usize)?; + let old_tuple = stored.late_owner_old; + let old_mode = stored.late_owner_old_mode; + let new_tuple = stored.late_owner_new; + let next = stored.late_owner_next; + { + let stored = &mut heap.slots[owner as usize]; + stored.late_owner_epoch = 0; + stored.late_owner_old = None; + stored.late_owner_old_mode = None; + stored.late_owner_new = None; + stored.late_owner_prev = None; + stored.late_owner_next = None; + } + state.late_owner_head = next; + match next { + Some(next) => { + if let Some(stored) = heap.slots.get_mut(next as usize) { + stored.late_owner_prev = None; + } + } + None => state.late_owner_tail = None, + } + Some((owner, old_tuple, new_tuple, old_mode)) +} + +fn push_late_edge(heap: &mut LuaHeap, state: &mut MarkState, index: u32) { + { + let record = &mut heap.edge_slots[index as usize]; + record.late_epoch = state.rescan_epoch; + record.late_prev = state.late_edge_tail; + record.late_next = None; + } + if let Some(tail) = state.late_edge_tail { + heap.edge_slots[tail as usize].late_next = Some(index); + } else { + state.late_edge_head = Some(index); + } + state.late_edge_tail = Some(index); +} + +#[allow(clippy::type_complexity)] +fn pop_late_edge( + heap: &mut LuaHeap, + state: &mut MarkState, +) -> Option<(u32, u32, Option<(u32, u32)>, Option<(u32, u32)>)> { + let index = state.late_edge_head?; + let record = heap.edge_slots.get(index as usize)?; + let owner = record.late_owner; + let key = record.late_key; + let value = record.late_value; + let next = record.late_next; + { + let record = &mut heap.edge_slots[index as usize]; + record.late_epoch = 0; + record.late_owner = 0; + record.late_value = None; + record.late_key = None; + record.late_prev = None; + record.late_next = None; + } + state.late_edge_head = next; + match next { + Some(next) => { + if let Some(record) = heap.edge_slots.get_mut(next as usize) { + record.late_prev = None; + } + } + None => state.late_edge_tail = None, + } + Some((index, owner, key, value)) +} + +fn finish_late_mode(heap: &mut LuaHeap, state: &mut MarkState, parsed: WeakMode) { + let Some(slot) = state.late_slot else { + return; + }; + let generation = state.late_generation; + pop_late_mode(heap, state); + state.late_slot = None; + state.late_byte_at = 0; + state.late_pending_mode = WeakMode::default(); + if parsed.keys || parsed.values { + store_parsed_mode(heap, state, slot, generation, parsed, true); + } else { + // A strong late result is a field observation, not an authoritative + // weak cache. It ends the wait for this version and lets a same-version + // reattachment skip a second read, but `mode_epoch` moves on the next + // write, so that write still registers a new late parse. + mark_mode_checked(heap, state, slot); + heap.scan.mode_late_parsed += 1; + } +} + +/// Store one parsed mode with the generation that owned the read. A late +/// value-weak entry is replaced at its real slot, and the generation stamp +/// makes a later reuse read as strong rather than inheriting the old mode. +fn store_parsed_mode( + heap: &mut LuaHeap, + state: &mut MarkState, + slot: u32, + generation: u32, + parsed: WeakMode, + late: bool, +) { + store_cache_mode(heap, state, slot, generation, parsed); + if late { + heap.scan.mode_late_parsed += 1; + } +} + +fn apply_owner_check( + heap: &mut LuaHeap, + state: &mut MarkState, + owner: u32, + old_tuple: Option<(u32, u32)>, + new_tuple: Option<(u32, u32)>, + observed_old_mode: Option, +) { + let live = heap.slots.get(owner as usize).is_some_and(|stored| { + stored.kind == HandleKind::Table && matches!(stored.state, SlotState::Live { .. }) + }); + // The coalesced record keeps the first old tuple and the latest new one. + // Only apply it while the owner really points at that final attachment; + // a later setter updates the record, so a mismatch is not this check's + // observation. + let final_attachment = live + && heap + .slots + .get(owner as usize) + .is_some_and(|stored| stored.metatable == new_tuple); + if final_attachment && old_tuple != new_tuple { + let old_mode = observed_old_mode.unwrap_or_else(|| { + mode_before_direct_delete(heap, state, old_tuple) + .unwrap_or_else(|| mode_of_tuple(heap, state, old_tuple)) + }); + let new_mode = mode_of_tuple(heap, state, new_tuple); + if (old_mode.keys && !new_mode.keys) || (old_mode.values && !new_mode.values) { + schedule_started_owner(heap, state, owner); + } + } + heap.scan.mode_late_deferred += 1; +} + +fn apply_edge_check( + heap: &mut LuaHeap, + state: &mut MarkState, + _index: u32, + owner: u32, + key: Option<(u32, u32)>, + value: Option<(u32, u32)>, +) { + if discovered_table(heap, owner) { + let mode = cached_owner_mode(heap, state, owner); + if !mode.keys + && let Some((slot, generation)) = key + { + late_enqueue_target(heap, state, slot, generation, HandleKind::Table); + } + if !mode.values + && let Some((slot, generation)) = value + { + late_enqueue_target(heap, state, slot, generation, HandleKind::Table); + } + } + heap.scan.mode_late_deferred += 1; +} + +fn clear_late_slot(stored: &mut Slot) { + stored.late_mode_epoch = 0; + stored.late_mode_prev = None; + stored.late_mode_next = None; + stored.late_owner_epoch = 0; + stored.late_owner_old = None; + stored.late_owner_old_mode = None; + stored.late_owner_new = None; + stored.late_owner_prev = None; + stored.late_owner_next = None; + stored.late_target_epoch = 0; + stored.late_target_prev = None; + stored.late_target_next = None; +} + +fn clear_late_edge(record: &mut super::EdgeSlot) { + record.late_epoch = 0; + record.late_owner = 0; + record.late_value = None; + record.late_key = None; + record.late_prev = None; + record.late_next = None; +} + +/// Remove a released slot from both intrusive late queues. A tag from an +/// older epoch is not in the current list. A released slot must never stay +/// queued: reuse would otherwise inherit queue membership or parse state. +pub(super) fn release_late_slot(state: Option<&mut MarkState>, slots: &mut [Slot], index: u32) { + let Some(state) = state else { + if let Some(stored) = slots.get_mut(index as usize) { + clear_late_slot(stored); + } + return; + }; + let epoch = state.rescan_epoch; + let Some(stored) = slots.get(index as usize) else { + return; + }; + let mode_epoch = stored.late_mode_epoch; + let mode_prev = stored.late_mode_prev; + let mode_next = stored.late_mode_next; + let owner_epoch = stored.late_owner_epoch; + let owner_prev = stored.late_owner_prev; + let owner_next = stored.late_owner_next; + let target_epoch = stored.late_target_epoch; + let target_prev = stored.late_target_prev; + let target_next = stored.late_target_next; + if mode_epoch == epoch { + let prev = mode_prev; + let next = mode_next; + match prev { + Some(prev) => { + if let Some(prev) = slots.get_mut(prev as usize) { + prev.late_mode_next = next; + } + } + None => state.late_mode_head = next, + } + match next { + Some(next) => { + if let Some(next) = slots.get_mut(next as usize) { + next.late_mode_prev = prev; + } + } + None => state.late_mode_tail = prev, + } + if state.late_slot == Some(index) { + state.late_slot = None; + state.late_edge = None; + state.late_byte_at = 0; + state.late_pending_mode = WeakMode::default(); + } + } + if owner_epoch == epoch { + let prev = owner_prev; + let next = owner_next; + match prev { + Some(prev) => { + if let Some(prev) = slots.get_mut(prev as usize) { + prev.late_owner_next = next; + } + } + None => state.late_owner_head = next, + } + match next { + Some(next) => { + if let Some(next) = slots.get_mut(next as usize) { + next.late_owner_prev = prev; + } + } + None => state.late_owner_tail = prev, + } + } + // A target tag from the current stamp is only meaningful once the current + // round has opened its target list. Before Reset first publishes work the + // header is empty: an abandoned head still carries its old one-stamp link + // (with `prev = None`), and accepting it would adopt the old successor as + // the new head and rewrite that neighbour. With an empty header, clear + // only the released slot. + if target_epoch == epoch && state.late_target_head.is_some() { + let prev = target_prev; + let next = target_next; + match prev { + Some(prev) => { + if let Some(prev) = slots.get_mut(prev as usize) { + prev.late_target_next = next; + } + } + None => state.late_target_head = next, + } + match next { + Some(next) => { + if let Some(next) = slots.get_mut(next as usize) { + next.late_target_prev = prev; + } + } + None => state.late_target_tail = prev, + } + } + if let Some(stored) = slots.get_mut(index as usize) { + clear_late_slot(stored); + } +} + +/// Remove one released edge record from the deferred-edge queue. +pub(super) fn release_late_edge( + mark: Option<&mut MarkState>, + edge_slots: &mut [super::EdgeSlot], + index: u32, +) { + let Some(state) = mark else { + if let Some(record) = edge_slots.get_mut(index as usize) { + clear_late_edge(record); + } + return; + }; + let epoch = state.rescan_epoch; + let Some(record) = edge_slots.get(index as usize) else { + return; + }; + if record.late_epoch == epoch { + let prev = record.late_prev; + let next = record.late_next; + match prev { + Some(prev) => { + if let Some(prev) = edge_slots.get_mut(prev as usize) { + prev.late_next = next; + } + } + None => state.late_edge_head = next, + } + match next { + Some(next) => { + if let Some(next) = edge_slots.get_mut(next as usize) { + next.late_prev = prev; + } + } + None => state.late_edge_tail = prev, + } + } + if let Some(record) = edge_slots.get_mut(index as usize) { + clear_late_edge(record); + } +} + +/// Record (or update in place) the one deferred transition check for an +/// owner. First old wins, latest new wins. No pending list is walked. +fn queue_owner_check( + heap: &mut LuaHeap, + state: &mut MarkState, + owner: u32, + old_tuple: Option<(u32, u32)>, + new_tuple: Option<(u32, u32)>, +) { + heap.scan.mode_late_lookups += 1; + if heap.slots[owner as usize].late_owner_epoch == state.rescan_epoch { + heap.slots[owner as usize].late_owner_new = new_tuple; + heap.scan.mode_late_event_reuses += 1; + return; + } + // Capture the old observation while the old metatable can still be + // resolved. A release before the deferred check must not turn an + // observed weak side into an apparent strong one. An old mode that is + // itself still being read stays unresolved; the parse queue drains before + // this check runs. + let old_mode = if late_mode_unknown(heap, state, old_tuple) { + None + } else { + Some( + mode_before_direct_delete(heap, state, old_tuple) + .unwrap_or_else(|| mode_of_tuple(heap, state, old_tuple)), + ) + }; + let stored = &mut heap.slots[owner as usize]; + stored.late_owner_old = old_tuple; + stored.late_owner_old_mode = old_mode; + stored.late_owner_new = new_tuple; + push_late_owner(heap, state, owner); + heap.scan.mode_late_events += 1; +} + +fn remove_late_edge(heap: &mut LuaHeap, state: &mut MarkState, index: u32) { + let Some(record) = heap.edge_slots.get(index as usize) else { + return; + }; + if record.late_epoch != state.rescan_epoch { + return; + } + let prev = record.late_prev; + let next = record.late_next; + match prev { + Some(prev) => { + if let Some(prev) = heap.edge_slots.get_mut(prev as usize) { + prev.late_next = next; + } + } + None => state.late_edge_head = next, + } + match next { + Some(next) => { + if let Some(next) = heap.edge_slots.get_mut(next as usize) { + next.late_prev = prev; + } + } + None => state.late_edge_tail = prev, + } + if let Some(record) = heap.edge_slots.get_mut(index as usize) { + record.late_epoch = 0; + record.late_owner = 0; + record.late_value = None; + record.late_key = None; + record.late_prev = None; + record.late_next = None; + } +} + +/// Update one edge record's latest table-value target. An existing queued +/// event is changed in place; when both key and value targets are gone, the +/// record leaves the queue. +fn queue_edge_value( + heap: &mut LuaHeap, + state: &mut MarkState, + index: u32, + owner: u32, + target: Option<(u32, u32)>, +) { + heap.scan.mode_late_lookups += 1; + let queued = heap.edge_slots[index as usize].late_epoch == state.rescan_epoch; + if queued { + heap.edge_slots[index as usize].late_value = target; + heap.scan.mode_late_event_reuses += 1; + if target.is_none() && heap.edge_slots[index as usize].late_key.is_none() { + remove_late_edge(heap, state, index); + } + return; + } + let Some(target) = target else { + return; + }; + { + let record = &mut heap.edge_slots[index as usize]; + record.late_owner = owner; + record.late_value = Some(target); + record.late_key = None; + } + push_late_edge(heap, state, index); + heap.scan.mode_late_events += 1; +} + +/// Updates the payload of an edge record that is already in this mark's +/// deferred-edge queue. A known-mode overwrite must not replay a target that +/// the parser had queued before the overwrite: the record is changed in place, +/// or leaves the queue when both its value and key are gone. This never +/// creates a second event and does not route the setter through a tree. +fn update_queued_edge_value( + heap: &mut LuaHeap, + state: &mut MarkState, + index: u32, + target: Option<(u32, u32)>, +) { + if heap.edge_slots[index as usize].late_epoch != state.rescan_epoch { + return; + } + heap.edge_slots[index as usize].late_value = target; + heap.scan.mode_late_event_reuses += 1; + if target.is_none() && heap.edge_slots[index as usize].late_key.is_none() { + remove_late_edge(heap, state, index); + } +} + +/// Record or merge a new table-object key and its table value on one edge. +fn queue_edge_key( + heap: &mut LuaHeap, + state: &mut MarkState, + index: u32, + owner: u32, + key: (u32, u32), + value: Option<(u32, u32)>, +) { + heap.scan.mode_late_lookups += 1; + if heap.edge_slots[index as usize].late_epoch == state.rescan_epoch { + let record = &mut heap.edge_slots[index as usize]; + record.late_owner = owner; + record.late_key = Some(key); + record.late_value = value; + heap.scan.mode_late_event_reuses += 1; + return; + } + { + let record = &mut heap.edge_slots[index as usize]; + record.late_owner = owner; + record.late_key = Some(key); + record.late_value = value; + } + push_late_edge(heap, state, index); + heap.scan.mode_late_events += 1; +} + +/// Whether `tuple` names a metatable with a queued late parse. A parsed cache +/// entry is already readable; a queued marker is not. +fn late_mode_unknown(heap: &LuaHeap, state: &MarkState, tuple: Option<(u32, u32)>) -> bool { + let Some((slot, generation)) = tuple else { + return false; + }; + heap.slots.get(slot as usize).is_some_and(|stored| { + stored.generation == generation + && stored.kind == HandleKind::Table + && stored.late_mode_epoch == state.rescan_epoch + }) +} + +/// Reads the owner's current metatable tuple through the slot vector. No +/// follower, no mark step, and no scan counter. +fn owner_mode_unknown(heap: &LuaHeap, state: &MarkState, owner: u32) -> bool { + let tuple = heap + .slots + .get(owner as usize) + .and_then(|slot| slot.metatable); + late_mode_unknown(heap, state, tuple) +} + +/// Queues one owner that already started a weak scan. Same checks and meters +/// as the synchronous setter path, without taking the saved mark. +fn schedule_started_owner(heap: &mut LuaHeap, state: &mut MarkState, owner: u32) { + if heap + .slots + .get(owner as usize) + .is_some_and(|slot| slot.rescan_epoch == state.rescan_epoch) + && !heap.slots[owner as usize].rescan_queued + { + push_rescan(heap, state, owner); + heap.scan.scratch.owner_rescan_pushed += 1; + heap.scan.owner_rescan_schedules += 1; + } +} + +fn step_root(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + if state.index >= heap.roots.len() { + // The exact registered userdata reservation is a host-retained edge, + // not a guest root: offer it once after the explicit roots. An empty + // (unregistered) reservation is not retained. The record and slot + // identity reads are one node-slot visit; the ordinary mark update + // and any owner scan follow the same units as a rooted node. + if !state.pending_reservation_checked { + state.pending_reservation_checked = true; + if let Some(slot) = heap.registered_pending_userdata_slot() { + heap.scan.node_slot_visits += 1; + let generation = heap.slots[slot as usize].generation; + if heap.mark_new(slot) { + push_ordinary_gray(heap, state, slot, generation); + } + return true; + } + } + // Pending finalizers are host-retained edges, not guest roots. Each + // record is offered once, after the explicit roots and the registered + // reservation. The cursor names that record's exact slot generation; + // one step reads that one record and follows the successor identity it + // stores. It never searches from the queue head and never reads the + // successor record. A record whose raw handle was rebound is skipped + // without closing anything; an exact record is marked like a root. + if let Some(cursor) = state.pending_offer { + heap.scan.pending_finalizer_offers += 1; + let (retained, next) = heap.pending_finalizer_offer(cursor); + state.pending_offer = next; + if let Some((slot, generation)) = retained { + heap.scan.node_slot_visits += 1; + if heap.mark_new(slot) { + push_ordinary_gray(heap, state, slot, generation); + } + } + return true; + } + 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, generation, _kind) = rooted_identity(rooted); + if heap.mark_new(slot) { + push_ordinary_gray(heap, state, slot, generation); + } + } + true +} + +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; + } + if state.gray_len != 0 { + debug_assert!( + state.gray_head.is_some(), + "ordinary Gray length has no head" + ); + return begin_owner(heap, state); + } + // Deferred replay targets come after the ordinary Gray LIFO. They are + // linked on their slots and drained last-in-first-out, matching the LIFO + // order the ordinary chain has for these pushes; a replay never touches + // that chain. Ordinary work is always preferred, so a bounded replay + // backlog cannot starve it; one pulse opens at most one owner head here. + if let Some(slot) = pop_late_target(heap, state) { + return open_owner(heap, state, slot); + } + if state.rescan_owner.is_some() { + if state.rescan_cursor.is_some() { + return charge_rescan(heap, state); + } + state.rescan_owner = None; + return false; + } + if let Some(slot) = pop_rescan(heap, state) { + return open_rescan(heap, state, slot); + } + if state.discover_on { + return probe_deleted_mode_owner(heap, state); + } + if state.select_pending && !state.pending_scan_done { + state.pending_live = heap.live_userdata_head; + state.phase = MarkPhase::Pending; + return false; + } + state.phase = MarkPhase::Done; + false +} + +/// One live-userdata chain node of the private pending-finalizer selection +/// scan, or one edge record of an open raw-`__gc` lookup. +/// +/// The scan runs only after the ordinary gray, rescan, and late work has +/// emptied and only when the private entry asked for it. It starts at the +/// live-userdata chain head, which is the most recently allocated generation +/// of this heap. Each step reads exactly one chain node, charged as one +/// node-slot visit and one pending selection slot; it follows that node's +/// saved next identity, so a table, closure, cell, free slot, or retired slot +/// is never touched by this walk. A candidate then opens a metered lookup +/// whose each step reads at most one metatable edge record; the result is +/// cached on the exact metatable generation for this mark round. A cursor +/// generation that no longer matches the slot is not reinterpreted against a +/// successor generation: the walk stops without following that node's links. +/// A positive result records the candidate and marks it through the ordinary +/// `follow_one` path; the following Gray pass opens it as an owner and +/// follows its metatable. A negative result settles that exact white identity +/// without marking it or queueing it; a cache hit applies the same result to +/// each later candidate that shares the metatable, so every eligible white +/// identity is settled. The scan itself never opens an owner, walks a whole +/// chain in one step, sorts the batch, or clears a weak entry. The whole +/// batch is read before Gray starts, so a metatable edge cannot mark a later +/// candidate early. When the chain and every lookup finish, the phase returns +/// to Gray; that transition is uncharged. +fn step_pending(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + if state.pending_lookup.is_some() { + return step_pending_gc(heap, state); + } + let Some((index, generation)) = state.pending_live else { + state.pending_scan_done = true; + state.phase = MarkPhase::Gray; + return false; + }; + state.pending_live = None; + heap.scan.pending_finalizer_scan_slots += 1; + heap.scan.node_slot_visits += 1; + let next = { + let Some(slot) = heap.slots.get(index as usize) else { + state.pending_scan_done = true; + state.phase = MarkPhase::Gray; + return true; + }; + #[cfg(test)] + heap.pending_live_trace + .borrow_mut() + .push((index, generation)); + if slot.generation != generation + || !slot.live_userdata_linked + || slot.kind != HandleKind::Userdata + || !matches!(slot.state, SlotState::Live { .. }) + { + // An old chain cursor must not become a visit of the successor + // generation that now occupies this slot. Stop instead of + // following links that no longer belong to the cursor identity. + state.pending_scan_done = true; + state.phase = MarkPhase::Gray; + return true; + } + slot.live_userdata_next + }; + state.pending_live = next; + let Some(candidate) = heap.pending_finalizer_candidate(index as usize) else { + return true; + }; + if let Some(non_nil) = heap.cached_pending_gc(&candidate, state.rescan_epoch) { + apply_pending_gc(heap, state, &candidate, non_nil); + return true; + } + let cursor = heap.slots[candidate.metatable_slot as usize].edge_head; + heap.scan.pending_finalizer_gc_lookups += 1; + state.pending_lookup = Some(PendingGcLookup { candidate, cursor }); + true +} + +/// Applies one completed raw-`__gc` result to the exact candidate. +/// +/// A non-nil field is the existing queue path: the candidate gets one pending +/// record and a mark through the ordinary target follow. A missing or nil +/// field settles the identity instead: no record and no mark. Both outcomes +/// re-check the slot identity in their heap method; a candidate that changed +/// during the walk is not selected or settled. +fn apply_pending_gc( + heap: &mut LuaHeap, + state: &mut MarkState, + candidate: &super::PendingCandidate, + non_nil: bool, +) { + if non_nil { + if heap.commit_pending_finalizer(candidate) { + heap.scan.pending_finalizers_selected += 1; + let _matched = follow_one( + heap, + state, + candidate.slot, + candidate.generation, + HandleKind::Userdata, + ); + } + } else { + let _settled = heap.settle_pending_finalizer(candidate); + } +} + +/// One edge record of the open raw-`__gc` lookup. +/// +/// The first matching record decides: a missing field has already ended the +/// walk as negative, a stored nil or cursor gap is negative, and every other +/// value (including `false`) is positive. The result is stored on the +/// metatable slot for this round before the candidate is committed, so a +/// second candidate sharing that exact generation pays no second walk. +fn step_pending_gc(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let lookup = state.pending_lookup.expect("an open lookup was observed"); + let Some(index) = lookup.cursor else { + heap.cache_pending_gc( + lookup.candidate.metatable_slot, + lookup.candidate.metatable_generation, + state.rescan_epoch, + false, + ); + state.pending_lookup = None; + apply_pending_gc(heap, state, &lookup.candidate, false); + return true; + }; + let (next, matched, non_nil) = heap.pending_gc_record(index); + heap.scan.pending_finalizer_gc_edge_checks += 1; + #[cfg(test)] + heap.pending_gc_edge_trace + .borrow_mut() + .push((lookup.candidate.metatable_slot, index)); + if matched { + heap.cache_pending_gc( + lookup.candidate.metatable_slot, + lookup.candidate.metatable_generation, + state.rescan_epoch, + non_nil, + ); + state.pending_lookup = None; + apply_pending_gc(heap, state, &lookup.candidate, non_nil); + return true; + } + state.pending_lookup = Some(PendingGcLookup { + cursor: next, + ..lookup + }); + true +} + +/// Test-only record of one `open_owner` attempt. `live` and `marked` describe +/// the slot at the instant the saved chain item named it, so an item that +/// resolves to a reused generation is distinguishable from the original one. +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct OpenTrace { + pub slot: u32, + pub generation: u32, + pub live: bool, + pub marked: bool, +} + +#[cfg(test)] +thread_local! { + static OPEN_TRACE: std::cell::RefCell> = + const { std::cell::RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +fn record_open_attempt(slot: u32, generation: u32, live: bool, marked: bool) { + OPEN_TRACE.with(|trace| { + trace.borrow_mut().push(OpenTrace { + slot, + generation, + live, + marked, + }); + }); +} + +/// Test-only: clear and read the owner-open trace. It is per thread, so one +/// test does not observe another test's opens. +#[cfg(test)] +pub(super) fn clear_open_trace() { + OPEN_TRACE.with(|trace| trace.borrow_mut().clear()); +} + +#[cfg(test)] +pub(super) fn open_trace() -> Vec { + OPEN_TRACE.with(|trace| trace.borrow().clone()) +} + +/// The four link fields of one ordinary Gray node. One `read_gray_link` or +/// `write_gray_link` is the unit the test-only access counters record, so a +/// push, a pop, and a release each have a visible local constant. +#[derive(Clone, Copy)] +struct GrayLink { + epoch: u64, + generation: u32, + prev: Option, + next: Option, +} + +fn read_gray_link(slots: &[Slot], state: &mut MarkState, index: u32) -> GrayLink { + #[cfg(test)] + { + state.gray_node_reads += 1; + } + #[cfg(not(test))] + let _ = state; + let stored = &slots[index as usize]; + GrayLink { + epoch: stored.gray_epoch, + generation: stored.gray_generation, + prev: stored.gray_prev, + next: stored.gray_next, + } +} + +fn write_gray_link(slots: &mut [Slot], state: &mut MarkState, index: u32, link: GrayLink) { + #[cfg(test)] + { + state.gray_node_writes += 1; + } + #[cfg(not(test))] + let _ = state; + let stored = &mut slots[index as usize]; + stored.gray_epoch = link.epoch; + stored.gray_generation = link.generation; + stored.gray_prev = link.prev; + stored.gray_next = link.next; +} + +fn write_gray_prev(slots: &mut [Slot], state: &mut MarkState, index: u32, prev: Option) { + #[cfg(test)] + { + state.gray_node_writes += 1; + } + #[cfg(not(test))] + let _ = state; + slots[index as usize].gray_prev = prev; +} + +fn write_gray_next(slots: &mut [Slot], state: &mut MarkState, index: u32, next: Option) { + #[cfg(test)] + { + state.gray_node_writes += 1; + } + #[cfg(not(test))] + let _ = state; + slots[index as usize].gray_next = next; +} + +fn clear_gray_link(slots: &mut [Slot], state: &mut MarkState, index: u32) { + write_gray_link( + slots, + state, + index, + GrayLink { + epoch: 0, + generation: 0, + prev: None, + next: None, + }, + ); +} + +fn clear_gray_slot(stored: &mut Slot) { + stored.gray_epoch = 0; + stored.gray_generation = 0; + stored.gray_prev = None; + stored.gray_next = None; +} + +/// Pushes one newly marked slot at the head of the ordinary Gray LIFO. The +/// old head's predecessor link is updated in place; the node lives in the +/// slot arena, so this does not allocate or copy a queue. A push happens only +/// on the white-to-marked transition, so one slot joins at most once per +/// round. +fn push_ordinary_gray(heap: &mut LuaHeap, state: &mut MarkState, slot: u32, generation: u32) { + let existing = read_gray_link(&heap.slots, state, slot); + debug_assert_ne!( + existing.epoch, state.rescan_epoch, + "a slot joined the ordinary Gray chain twice in one round" + ); + let old_head = state.gray_head; + write_gray_link( + &mut heap.slots, + state, + slot, + GrayLink { + epoch: state.rescan_epoch, + generation, + prev: None, + next: old_head.map(|(head, _)| head), + }, + ); + match old_head { + Some((head, _)) => write_gray_prev(&mut heap.slots, state, head, Some(slot)), + None => state.gray_tail = Some((slot, generation)), + } + state.gray_head = Some((slot, generation)); + state.gray_len += 1; + #[cfg(test)] + { + state.gray_header_writes += 1; + } +} + +/// Pops the exact head of the ordinary Gray LIFO. The stored generation +/// travels back to the caller so `begin_owner` can refuse to open a successor +/// generation; the successor becomes the new head with its own recorded +/// generation. Both neighbour updates are constant work. +fn pop_ordinary_gray(heap: &mut LuaHeap, state: &mut MarkState) -> Option<(u32, u32)> { + let (slot, generation) = state.gray_head?; + let link = read_gray_link(&heap.slots, state, slot); + debug_assert_eq!( + link.epoch, state.rescan_epoch, + "ordinary Gray head belongs to an older round" + ); + debug_assert_eq!( + link.generation, generation, + "ordinary Gray head identity changed" + ); + debug_assert!(link.prev.is_none(), "ordinary Gray head has a predecessor"); + match link.next { + Some(next) => { + let next_link = read_gray_link(&heap.slots, state, next); + debug_assert_eq!( + next_link.prev, + Some(slot), + "ordinary Gray successor does not link back to the head" + ); + write_gray_prev(&mut heap.slots, state, next, None); + state.gray_head = Some((next, next_link.generation)); + } + None => { + state.gray_head = None; + state.gray_tail = None; + } + } + clear_gray_link(&mut heap.slots, state, slot); + state.gray_len -= 1; + #[cfg(test)] + { + state.gray_header_writes += 1; + } + Some((slot, generation)) +} + +/// Removes a released slot from the ordinary Gray LIFO before its generation +/// advances. The links are on the slot, so this is constant work and never +/// walks the chain. Removing a middle node stitches its neighbours together, +/// so the remaining queue stays reachable. A tag from an older round is not +/// in the current chain, and only the released slot is cleared in that case. +pub(super) fn release_ordinary_gray(state: Option<&mut MarkState>, slots: &mut [Slot], index: u32) { + let Some(state) = state else { + if let Some(stored) = slots.get_mut(index as usize) { + clear_gray_slot(stored); + } + return; + }; + let Some(stored) = slots.get(index as usize) else { + return; + }; + let linked_generation = stored.generation; + let link = read_gray_link(slots, state, index); + if link.epoch != state.rescan_epoch || link.generation != linked_generation { + if let Some(stored) = slots.get_mut(index as usize) { + clear_gray_slot(stored); + } + return; + } + if state.gray_len == 0 { + // The current round links no node, so a tag that matches its reused + // stamp is left over from an abandoned mark (the stamp wrapped). It is + // not a queue member: clear this slot only and never follow its old + // neighbours or move the header. + if let Some(stored) = slots.get_mut(index as usize) { + clear_gray_slot(stored); + } + return; + } + let mut header_changed = false; + match link.prev { + Some(prev) => write_gray_next(slots, state, prev, link.next), + None => { + debug_assert_eq!( + state.gray_head.map(|(head, _)| head), + Some(index), + "ordinary Gray head does not name the released node" + ); + state.gray_head = match link.next { + Some(next) => { + let next_link = read_gray_link(slots, state, next); + Some((next, next_link.generation)) + } + None => None, + }; + header_changed = true; + } + } + match link.next { + Some(next) => write_gray_prev(slots, state, next, link.prev), + None => { + debug_assert_eq!( + state.gray_tail.map(|(tail, _)| tail), + Some(index), + "ordinary Gray tail does not name the released node" + ); + state.gray_tail = match link.prev { + Some(prev) => { + let prev_link = read_gray_link(slots, state, prev); + Some((prev, prev_link.generation)) + } + None => None, + }; + header_changed = true; + } + } + clear_gray_link(slots, state, index); + state.gray_len = state.gray_len.saturating_sub(1); + #[cfg(test)] + { + if header_changed { + state.gray_header_writes += 1; + } + } + #[cfg(not(test))] + let _ = header_changed; +} + +fn begin_owner(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let Some((slot, generation)) = pop_ordinary_gray(heap, state) else { + state.phase = MarkPhase::Done; + return false; + }; + let live_generation = heap.slots.get(slot as usize).is_some_and(|stored| { + stored.generation == generation && matches!(stored.state, SlotState::Live { .. }) + }); + if !live_generation { + // Release unlinks a node before it advances the slot generation, so a + // linked item always names a live generation. Keep the defensive + // check: a stale item must never open a reused generation, and the + // remaining chain is still reachable because the head already moved. + debug_assert!(false, "a linked ordinary Gray item lost its identity"); + return true; + } + open_owner(heap, state, slot) +} + +/// Opens one marked slot as the current owner. One caller unit. Shared by the +/// ordinary Gray LIFO and the deferred-replay list. +fn open_owner(heap: &mut LuaHeap, state: &mut MarkState, slot: u32) -> bool { + let Some(stored) = heap.slots.get(slot as usize) else { + #[cfg(test)] + record_open_attempt(slot, 0, false, false); + return false; + }; + #[cfg(test)] + record_open_attempt( + slot, + stored.generation, + matches!(stored.state, SlotState::Live { .. }), + matches!(stored.state, SlotState::Live { marked: true }), + ); + if !matches!(stored.state, SlotState::Live { .. }) { + return false; + } + let kind = stored.kind; + let userdata_metatable = if kind == HandleKind::Userdata { + stored.metatable + } else { + None + }; + let mode = if kind == HandleKind::Table && heap.metatable_edges > 0 { + owner_mode(heap, state, slot) + } else { + WeakMode::default() + }; + // A userdata metatable is a strong edge of the marked userdata. Following + // it rides on this same owner-head unit, exactly as a table's metatable + // check rides on the table head. The test-only anti-control can suppress + // this follow for a selected pending userdata; the userdata itself stays + // marked and retained in that arm. + #[cfg(test)] + let skip_metatable = + heap.skip_pending_finalizer_metatable && heap.slots[slot as usize].pending_finalizer; + #[cfg(not(test))] + let skip_metatable = false; + if let Some((metatable_slot, metatable_generation)) = userdata_metatable + && heap.metatable_edges > 0 + && !skip_metatable + { + heap.scan.metatable_edge_checks += 1; + let _matched = follow_one( + heap, + state, + metatable_slot, + metatable_generation, + HandleKind::Table, + ); + } + 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; + if mode.keys || mode.values { + note_weak_started(heap, state, slot); + } + 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 +} + +fn charge_rescan(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + // An open rescan has a cached mode. A same-tuple rewrite or a late parse + // on that metatable does not change the owner's metatable tuple, so the + // tuple comparison used to miss it. Re-read the resolved mode on every + // charged record; this is two slot reads and does not touch the meter. + // The late parse queue drains before Gray resumes, so the slot bits read + // here are final for this round. + if let Some(owner) = state.rescan_owner { + state.rescan_mode = cached_owner_mode(heap, state, owner); + } + let cursor = state.rescan_cursor.expect("rescan unit has a cursor"); + let next = heap.edge_slots[cursor as usize].next; + state.rescan_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_rescan_ends(heap, state, cursor); + true +} + +fn pop_rescan(heap: &mut LuaHeap, state: &mut MarkState) -> Option { + let slot = state.rescan_head?; + let next = { + let stored = heap.slots.get_mut(slot as usize)?; + debug_assert_eq!( + stored.rescan_epoch, state.rescan_epoch, + "rescan head belongs to an older cycle" + ); + debug_assert!(stored.rescan_queued, "rescan head is not queued"); + stored.rescan_queued = false; + stored.rescan_prev = None; + stored.rescan_next.take() + }; + state.rescan_head = next; + if let Some(next) = next + && let Some(stored) = heap.slots.get_mut(next as usize) + { + stored.rescan_prev = None; + } + Some(slot) +} + +fn push_late_target(heap: &mut LuaHeap, state: &mut MarkState, slot: u32) { + { + let stored = &mut heap.slots[slot as usize]; + stored.late_target_epoch = state.rescan_epoch; + stored.late_target_prev = None; + stored.late_target_next = state.late_target_head; + } + match state.late_target_head { + Some(head) => heap.slots[head as usize].late_target_prev = Some(slot), + None => state.late_target_tail = Some(slot), + } + state.late_target_head = Some(slot); +} + +fn pop_late_target(heap: &mut LuaHeap, state: &mut MarkState) -> Option { + let slot = state.late_target_head?; + let next = heap + .slots + .get(slot as usize) + .and_then(|stored| stored.late_target_next); + if let Some(stored) = heap.slots.get_mut(slot as usize) { + stored.late_target_epoch = 0; + stored.late_target_prev = None; + stored.late_target_next = None; + } + state.late_target_head = next; + match next { + Some(next) => { + if let Some(stored) = heap.slots.get_mut(next as usize) { + stored.late_target_prev = None; + } + } + None => state.late_target_tail = None, + } + Some(slot) +} + +fn push_rescan(heap: &mut LuaHeap, state: &mut MarkState, owner: u32) { + { + let stored = &mut heap.slots[owner as usize]; + stored.rescan_queued = true; + stored.rescan_prev = None; + stored.rescan_next = state.rescan_head; + } + if let Some(head) = state.rescan_head { + heap.slots[head as usize].rescan_prev = Some(owner); + } + state.rescan_head = Some(owner); +} + +/// Removes a slot being released from this mark's rescan list before its state +/// becomes Free. The links are on the slot, so this is constant work and does +/// not walk the queue. A tag from an older epoch is not in the current list; +/// it is cleared without touching the current head. A released slot must never +/// stay queued: reuse would otherwise inherit queue membership. +/// +/// The stamp can wrap and be reused, so the tag and the queued bit alone do +/// not prove current membership. The header must name this exact node, or the +/// recorded predecessor must really link to it under the same stamp. A stale +/// head from an abandoned round fails both checks: its release clears only +/// this slot and never adopts the old successor or rewrites that neighbour. +pub(super) fn release_rescan_slot( + mut state: Option<&mut MarkState>, + slots: &mut [Slot], + index: u32, +) { + let Some(stored) = slots.get(index as usize) else { + return; + }; + let epoch = stored.rescan_epoch; + let queued = stored.rescan_queued; + let prev = stored.rescan_prev; + let next = stored.rescan_next; + let same_cycle = state + .as_ref() + .is_some_and(|state| state.rescan_epoch == epoch); + // A nonempty current header proves the reset walk reached Gray, so any + // matching tag was pushed by this round. While the header is empty the + // list is not open: even an internally consistent old predecessor link + // must not be followed or rewritten, and only the released slot changes. + let chain_open = same_cycle + && state + .as_ref() + .is_some_and(|state| state.rescan_head.is_some()); + let linked_head = chain_open + && queued + && state + .as_ref() + .is_some_and(|state| state.rescan_head == Some(index)); + let linked_prev = chain_open + && queued + && prev.is_some_and(|prev| { + slots.get(prev as usize).is_some_and(|prev_slot| { + prev_slot.rescan_epoch == epoch + && prev_slot.rescan_queued + && prev_slot.rescan_next == Some(index) + }) + }); + if linked_head { + if let Some(state) = state.as_mut() { + state.rescan_head = next; + } + if let Some(next) = next + && let Some(next_slot) = slots.get_mut(next as usize) + { + next_slot.rescan_prev = None; + } + } else if linked_prev { + if let Some(prev) = prev + && let Some(prev_slot) = slots.get_mut(prev as usize) + { + prev_slot.rescan_next = next; + } + if let Some(next) = next + && let Some(next_slot) = slots.get_mut(next as usize) + { + next_slot.rescan_prev = prev; + } + } + if let Some(stored) = slots.get_mut(index as usize) { + stored.rescan_epoch = 0; + stored.rescan_queued = false; + stored.rescan_prev = None; + stored.rescan_next = None; + } +} + +fn open_rescan(heap: &mut LuaHeap, state: &mut MarkState, slot: u32) -> bool { + let Some(stored) = heap.slots.get(slot as usize) else { + return false; + }; + if stored.kind != HandleKind::Table || !matches!(stored.state, SlotState::Live { .. }) { + return false; + } + let mode = cached_owner_mode(heap, state, slot); + heap.scan.owner_head_checks += 1; + heap.scan.owner_rescan_heads += 1; + state.rescan_cursor = heap.slots[slot as usize].edge_head; + state.rescan_owner = Some(slot); + state.rescan_mode = mode; + true +} + +/// Reads one capacity slot and at most one indexed discovery stamp. A +/// matching owner that already started a weak scan is queued on the existing +/// intrusive rescan list. Only the discovery cursor advances here. +fn probe_deleted_mode_owner(heap: &mut LuaHeap, state: &mut MarkState) -> bool { + let at = state.discover_at; + if at >= heap.slots.len() { + state.discover_at = 0; + state.discover_on = std::mem::take(&mut state.discover_next); + if state.discover_on { + state.discover_batch += 1; + } + return false; + } + state.discover_at = at + 1; + heap.scan.mode_owner_probes += 1; + let Some(stored) = heap.slots.get(at) else { + return true; + }; + if stored.kind != HandleKind::Table || !matches!(stored.state, SlotState::Live { .. }) { + return true; + } + let Some((meta_slot, meta_gen)) = stored.metatable else { + return true; + }; + let Some(stamp) = discovery_stamp(heap, state, meta_slot) else { + return true; + }; + let active = ModeDiscoveryMark { + generation: meta_gen, + batch: state.discover_batch, + round: state.rescan_epoch, + }; + heap.scan.mode_discover_compares += 1; + if stamp == active { + queue_started_owner(heap, state, at as u32); + } + true +} + +fn queue_started_owner(heap: &mut LuaHeap, state: &mut MarkState, owner: u32) { + let started = heap + .slots + .get(owner as usize) + .is_some_and(|stored| stored.rescan_epoch == state.rescan_epoch); + if !started { + return; + } + if heap + .slots + .get(owner as usize) + .is_some_and(|stored| stored.rescan_queued) + { + return; + } + push_rescan(heap, state, owner); + heap.scan.scratch.owner_rescan_pushed += 1; + heap.scan.owner_rescan_schedules += 1; +} + +/// Called only on the cache's weak-to-strong transition, once per metatable +/// slot per mark. The stamp lives in the reset-sized sidecar below its length +/// and on the metatable slot beyond it, so no late vector growth is needed. +/// A stale generation or an unexpected path does not panic the collector. +fn arm_deleted_mode(heap: &mut LuaHeap, state: &mut MarkState, slot: u32, generation: u32) { + if !state.discover_on { + state.discover_batch += 1; + state.discover_on = true; + } + let batch = if state.discover_at == 0 { + state.discover_batch + } else { + state.discover_next = true; + state.discover_batch + 1 + }; + let stamp = ModeDiscoveryMark { + generation, + batch, + round: state.rescan_epoch, + }; + if let Some(found) = state.discover_marks.get_mut(slot as usize) { + *found = stamp; + } else if let Some(stored) = heap.slots.get_mut(slot as usize) { + stored.discover_generation = generation; + stored.discover_batch = batch; + stored.discover_round = state.rescan_epoch; + } else { + return; + } + heap.scan.mode_discover_writes += 1; +} + +fn follow_rescan_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("rescan 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::Userdata { slot, generation } => { + Some((*slot, *generation, HandleKind::Userdata)) + } + EdgeValue::Scalar(_) => None, + }; + (object_key, value_target) + }; + if !state.rescan_mode.keys + && let Some((slot, generation, kind)) = object_key + { + let _matched = follow_one(heap, state, slot, generation, kind); + } + if !state.rescan_mode.values + && let Some((slot, generation, kind)) = value_target + { + let _matched = follow_one(heap, state, slot, generation, kind); + } +} + +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::Userdata { slot, generation } => { + Some((*slot, *generation, HandleKind::Userdata)) + } + 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, cell, or + // userdata value on a non-table owner is not a table entry, so it stays + // strong. A userdata value on a table is weak exactly when values are. + 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); + } +} + +/// Tags the target slot when its ordinary scan opens a weak side. The tag is +/// the slot's own epoch, so a grown slot needs no vector entry and no suffix +/// initialization. The first tag for a slot in a mark is one initialized slot +/// state; a repeat is a no-op. An older epoch is inert and is replaced here. +fn note_weak_started(heap: &mut LuaHeap, state: &mut MarkState, slot: u32) { + let epoch = state.rescan_epoch; + let first = { + let Some(stored) = heap.slots.get_mut(slot as usize) else { + return; + }; + if stored.rescan_epoch == epoch { + false + } else { + stored.rescan_epoch = epoch; + stored.rescan_queued = false; + stored.rescan_prev = None; + stored.rescan_next = None; + true + } + }; + if first { + heap.scan.scratch.owner_rescan_inited = + heap.scan.scratch.owner_rescan_inited.saturating_add(1); + } +} + +/// Parsed mode for one metatable slot generation. The indexed reset vector is +/// read when it covers the slot; otherwise the slot's own weak bits are read. +/// Both carry the generation and the round stamp written at the parse's +/// linearization point, so a released/reused slot or a cache left by an +/// earlier round cannot be a current observation of the direct field. The +/// late parse therefore costs one slot write and every query is a slot read, +/// not a tree insert or lookup. +fn mode_for_slot( + heap: &LuaHeap, + state: &MarkState, + slot: u32, + generation: u32, +) -> Option { + let stored = heap.slots.get(slot as usize)?; + if stored.generation != generation + || stored.mode_generation != generation + || stored.mode_round != state.rescan_epoch + { + return None; + } + if let Some(modes) = state.modes.as_ref() + && let Some(mode) = modes.get(slot as usize) + { + return Some(*mode); + } + Some(stored.mode_weak) +} + +fn mode_of_tuple(heap: &LuaHeap, state: &MarkState, tuple: Option<(u32, u32)>) -> WeakMode { + let Some((slot, generation)) = tuple else { + return WeakMode::default(); + }; + mode_for_slot(heap, state, slot, generation).unwrap_or_default() +} + +fn discovery_stamp(heap: &LuaHeap, state: &MarkState, slot: u32) -> Option { + if let Some(stamp) = state.discover_marks.get(slot as usize) { + return Some(*stamp); + } + heap.slots + .get(slot as usize) + .map(|stored| ModeDiscoveryMark { + generation: stored.discover_generation, + batch: stored.discover_batch, + round: stored.discover_round, + }) +} + +/// The value-weak mode a tuple had before a direct `__mode` unlink replaced +/// the cache entry with the missing-field mode. The discovery stamp recorded +/// the same metatable generation, so a setter moving an already-started owner +/// away still sees the old weak side. Only the value bit returns: the delete +/// path arms on value-weak, key-strong entries. +fn mode_before_direct_delete( + heap: &LuaHeap, + state: &MarkState, + tuple: Option<(u32, u32)>, +) -> Option { + let (slot, generation) = tuple?; + let stamp = discovery_stamp(heap, state, slot)?; + if stamp.batch == 0 || stamp.generation != generation || stamp.round != state.rescan_epoch { + return None; + } + Some(WeakMode { + keys: false, + values: true, + }) +} + +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(mode) = mode_for_slot(heap, state, to_slot, to_generation) + { + heap.scan.weak_mode_lookups += 1; + return mode; + } + 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), + Rooted::Userdata(handle) => (handle.slot(), handle.generation(), HandleKind::Userdata), + } +} + +/// 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; + } +} + +/// Marks one deferred-replay target and links it on its slot record. This is +/// the replay-only queue: it never pushes the ordinary Gray chain, so a replay +/// at a capacity boundary does not relocate the stored segment. The same +/// target checks and meter as [`enqueue_barrier_target`] ride on the one +/// deferred unit that called this. +fn late_enqueue_target( + heap: &mut LuaHeap, + state: &mut MarkState, + slot: u32, + generation: u32, + kind: HandleKind, +) { + let before = heap.scan.scratch.work_pushed; + heap.scan.node_slot_visits += 1; + let mut matched = false; + if heap.slot_matches(slot, generation, kind) { + heap.scan.node_slot_visits += 1; + if heap.mark_new(slot) { + push_late_target(heap, state, slot); + } + matched = true; + } + if matched && heap.scan.scratch.work_pushed > before { + heap.scan.parked_barrier_marks += 1; + } +} + +/// 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 mark bit of one upvalue generation. A reused slot of another +/// generation is not this cell. No chain walk and no scan counter. +fn discovered_upvalue(heap: &LuaHeap, owner: u32, generation: u32) -> bool { + heap.slots.get(owner as usize).is_some_and(|slot| { + slot.kind == HandleKind::Upvalue + && slot.generation == generation + && 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 { + 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, meta_generation)) = stored.metatable else { + return false; + }; + mode_for_slot(heap, state, meta_slot, meta_generation).is_some_and(|mode| mode.values) +} + +/// Both weak bits from the same cycle 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, meta_generation)) = stored.metatable else { + return WeakMode::default(); + }; + mode_for_slot(heap, state, meta_slot, meta_generation).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( + 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) { + push_ordinary_gray(heap, state, slot, generation); + } + 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, + } +} + +/// The direct object a closed-cell write just stored. +/// +/// Only these two carriers use the current edge. The write names which one it +/// stored; the barrier does not inspect the record again. +pub(super) enum ClosedCellTarget { + Table, + Closure, +} + +impl LuaHeap { + /// Phase and whether a gray edge, queued owner, or late-mode unit 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_len != 0 + || state.cursor.is_some() + || state.rescan_owner.is_some() + || state.rescan_cursor.is_some() + || state.rescan_head.is_some() + || state.late_target_head.is_some() + || state.discover_on + || state.has_late_work(), + )) + } + + /// Phase, pending bit, cursor owner slot, cursor record, and gray length. + /// Reads the saved mark only. Does not take it, walk an edge, enqueue, or write. + #[cfg(test)] + pub fn saved_mark_watch(&self) -> Option { + let state = self.mark.as_ref()?; + Some(super::super::SavedMarkWatch { + phase: state.phase_name(), + pending: state.gray_len != 0 + || state.cursor.is_some() + || state.late_target_head.is_some() + || state.has_late_work(), + cursor_owner: state.owner, + cursor_index: state.cursor, + gray_len: state.gray_len, + }) + } + + /// Exact ordinary Gray chain, head to tail, as slot/generation pairs. + /// Test-only: the links are read while the saved mark is borrowed and no + /// link is written. A chain that does not match its head, tail, or node + /// generations is a test failure, not a silent zero. + #[cfg(test)] + pub fn saved_mark_gray_snapshot(&self) -> Option> { + let state = self.mark.as_ref()?; + let mut nodes = Vec::with_capacity(state.gray_len as usize); + let mut cursor = state.gray_head; + while let Some((slot, generation)) = cursor { + let stored = self + .slots + .get(slot as usize) + .expect("ordinary Gray node names a missing slot"); + assert_eq!( + stored.gray_epoch, state.rescan_epoch, + "ordinary Gray node belongs to an older round" + ); + assert_eq!( + stored.gray_generation, generation, + "ordinary Gray node identity changed" + ); + assert_eq!( + stored.generation, generation, + "ordinary Gray node names a stale generation" + ); + nodes.push((slot, generation)); + assert!( + nodes.len() <= self.slots.len(), + "ordinary Gray chain has a cycle" + ); + cursor = stored.gray_next.map(|next| { + let next_slot = self + .slots + .get(next as usize) + .expect("ordinary Gray successor names a missing slot"); + (next, next_slot.gray_generation) + }); + } + assert_eq!( + state.gray_tail.map(|(slot, _)| slot), + nodes.last().map(|(slot, _)| *slot), + "ordinary Gray tail does not match the last node" + ); + assert_eq!( + usize::try_from(state.gray_len).expect("chain length fits the arena"), + nodes.len(), + "ordinary Gray length does not match the chain" + ); + Some(nodes) + } + + /// Test-only actual ordinary Gray link accesses: + /// `(node reads, node writes, head/tail header writes)`. + #[cfg(test)] + pub fn saved_mark_gray_access(&self) -> Option<(u64, u64, u64)> { + self.mark.as_ref().map(|state| { + ( + state.gray_node_reads, + state.gray_node_writes, + state.gray_header_writes, + ) + }) + } + + /// Test-only capacity of the slot arena that stores both the nodes and + /// their ordinary Gray links. It is independent of any mark work queue. + #[cfg(test)] + pub fn saved_mark_gray_arena_capacity(&self) -> Option { + self.mark.as_ref().map(|_| self.slots.capacity()) + } + + /// Live marked bit of one table. Does not walk an edge or change the bit. + #[cfg(test)] + pub fn table_marked(&self, table: TableRef) -> bool { + self.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 }) + }) + } + + /// Whether this table's slot is linked in the saved ordinary Gray chain. + /// Reads the chain links only. Compares slots, not generations, so it is + /// not generation evidence; `saved_mark_gray_snapshot` carries identity. + #[cfg(test)] + pub fn table_in_gray(&self, table: TableRef) -> bool { + let Some(state) = self.mark.as_ref() else { + return false; + }; + let mut cursor = state.gray_head; + let mut steps = 0usize; + while let Some((slot, generation)) = cursor { + if slot == table.slot() { + return true; + } + let Some(stored) = self.slots.get(slot as usize) else { + return false; + }; + if stored.gray_epoch != state.rescan_epoch || stored.gray_generation != generation { + return false; + } + cursor = stored.gray_next.and_then(|next| { + self.slots + .get(next as usize) + .map(|next_slot| (next, next_slot.gray_generation)) + }); + steps += 1; + if steps > self.slots.len() { + return false; + } + } + false + } + + /// Whether one open frame already roots this table. Empty and non-table + /// slots are skipped. Does not scan edges. + #[cfg(test)] + pub fn frame_roots_table(&self, frame: RootFrameId, table: TableRef) -> bool { + let Ok(found) = self.frame(frame) else { + return false; + }; + (0..found.width).any(|slot| { + self.rooted_table(frame, slot) + .ok() + .flatten() + .is_some_and(|rooted| rooted == table) + }) + } + + /// Record index of one number key, plus the table slot of its value when + /// that value is a table, and whether the value is a string. One owner-chain + /// read. Does not write, enqueue, or move a cursor. + #[cfg(test)] + pub fn number_edge_watch(&self, table: TableRef, key: f64) -> Option<(u32, Option, bool)> { + if key.is_nan() || !self.alive(table) { + return None; + } + self.edge_watch(table, &EdgeKey::number(key)) + } + + /// Record index of one UTF-8 key. Same read-only shape as [`Self::number_edge_watch`]. + #[cfg(test)] + pub fn utf8_edge_watch(&self, table: TableRef, key: &str) -> Option<(u32, Option, bool)> { + if !self.alive(table) { + return None; + } + self.edge_watch(table, &EdgeKey::named(key)) + } + + #[cfg(test)] + fn edge_watch(&self, table: TableRef, key: &EdgeKey) -> Option<(u32, Option, bool)> { + let index = self.find_key(table.slot(), key)?; + let edge = self.edge_slots[index as usize].edge.as_ref()?; + let (value_slot, value_string) = match &edge.value { + EdgeValue::Table { slot, .. } => (Some(*slot), false), + EdgeValue::Scalar(Value::String(_)) => (None, true), + _ => (None, false), + }; + Some((index, value_slot, value_string)) + } + + /// 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. The late-mode + /// sub-phase still belongs to that window. + pub(super) fn note_parked_root_store(&mut self, rooted: Rooted) { + let Some(mut state) = self.mark.take() else { + return; + }; + if !state.write_barriers_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), + Rooted::Userdata(handle) => (handle.slot(), handle.generation(), HandleKind::Userdata), + }; + 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. An owner + /// that is not yet marked does not enter the gray queue. A field whose + /// metatable is still being read records the target on the edge record and + /// lets the budgeted late parse decide; a weak arm must not mark it early. + /// Once the mode is known, the same call decides immediately instead of + /// queueing a later event. A later write updates the pending record in + /// place, so repeated overwrites of one live edge keep one deferred site. + /// This does not call `owner_mode` and does not move either cursor. + pub(super) fn barrier_strong_field( + &mut self, + owner: u32, + index: u32, + target: Option<(u32, u32)>, + ) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.write_barriers_open() && discovered_table(self, owner) { + let unknown = owner_mode_unknown(self, &state, owner); + if unknown { + // The mode is being read; record the latest target on this + // edge record and let the budgeted parse decide. A known mode + // must decide now: queueing it would inject one ModeLate unit + // per overwrite and starve ordinary Gray work. + queue_edge_value(self, &mut state, index, owner, target); + } else { + // A known mode decides now. If this record still carries a + // payload from an earlier unknown-mode write, update or cancel + // it in place: the parse did not make that old target live. + update_queued_edge_value(self, &mut state, index, target); + if let Some((slot, generation)) = target + && !cached_values_weak(self, &state, owner) + { + enqueue_barrier_target(self, &mut state, slot, generation, HandleKind::Table); + } + } + } + self.mark = Some(state); + } + + /// Checks whether either weak side becomes strong using the tuples captured + /// before the slot write. The old mode comes from this cycle's cache and + /// that tuple, not from the edge count, so clearing the last metatable + /// edge cannot make the old mode look strong. A direct value-weak delete + /// already replaced that cache entry with the missing-field mode; its + /// discovery stamp restores the pre-delete value bit for an owner that + /// started under the same metatable. A not-yet-started owner is left for + /// the ordinary scan. A new metatable whose `__mode` is still being read is + /// recorded on the owner slot instead: the deferred evaluation uses the + /// same transition rule after the budgeted parse, and no long string is + /// walked here. A second setter for the same owner updates the recorded + /// final tuple in place and keeps the original old tuple. This does not + /// enqueue, scan, walk a pending list, or move a cursor. + pub(super) fn needs_owner_rescan( + &mut self, + owner: u32, + old_tuple: Option<(u32, u32)>, + new_tuple: Option<(u32, u32)>, + ) -> bool { + let Some(mut state) = self.mark.take() else { + return false; + }; + let mut rescan = false; + if state.write_barriers_open() && old_tuple != new_tuple { + let queued = self + .slots + .get(owner as usize) + .is_some_and(|slot| slot.late_owner_epoch == state.rescan_epoch); + if queued { + self.slots[owner as usize].late_owner_new = new_tuple; + self.scan.mode_late_lookups += 1; + self.scan.mode_late_event_reuses += 1; + } else if late_mode_unknown(self, &state, new_tuple) { + queue_owner_check(self, &mut state, owner, old_tuple, new_tuple); + } else { + self.scan.mode_late_lookups += 1; + let old_mode = mode_before_direct_delete(self, &state, old_tuple) + .unwrap_or_else(|| mode_of_tuple(self, &state, old_tuple)); + let new_mode = mode_of_tuple(self, &state, new_tuple); + rescan = ((old_mode.keys && !new_mode.keys) + || (old_mode.values && !new_mode.values)) + && self + .slots + .get(owner as usize) + .is_some_and(|slot| slot.rescan_epoch == state.rescan_epoch); + } + } + self.mark = Some(state); + rescan + } + + /// After a real direct `__mode` unlink, replace this cycle's value-weak + /// cache for that same generation. Owners that have not started read the + /// missing-field mode. Owners that already started stay for the budgeted + /// probe. A key-weak cache, a missing record, and a closed mutation are + /// left alone. The stamp lives on the metatable slot, so a grown or reused + /// slot needs no sidecar growth. This does not walk slots or move either + /// cursor. + pub(super) fn note_direct_mode_deleted(&mut self, owner: u32) { + let Some(mut state) = self.mark.take() else { + return; + }; + if !state.write_barriers_open() { + self.mark = Some(state); + return; + } + let generation = self.slots[owner as usize].generation; + let cached = mode_for_slot(self, &state, owner, generation); + if !cached.is_some_and(|mode| mode.values && !mode.keys) { + self.mark = Some(state); + return; + } + store_cache_mode(self, &mut state, owner, generation, WeakMode::default()); + self.scan.mode_cache_updates += 1; + if self.slots[owner as usize].late_mode_epoch == state.rescan_epoch { + self.scan.mode_late_cancels += 1; + } + arm_deleted_mode(self, &mut state, owner, generation); + self.mark = Some(state); + } + + /// Queues one chain-head rescan for an owner that already started a weak + /// scan. A repeat reads the slot tag and does not walk the queue. This + /// does not scan the owner, reset a mark, initialize an unrelated slot, + /// allocate a queue buffer, or move the ordinary cursor. + pub(super) fn schedule_owner_rescan(&mut self, owner: u32) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.write_barriers_open() + && self + .slots + .get(owner as usize) + .is_some_and(|slot| slot.rescan_epoch == state.rescan_epoch) + && !self.slots[owner as usize].rescan_queued + { + push_rescan(self, &mut state, owner); + self.scan.scratch.owner_rescan_pushed += 1; + self.scan.owner_rescan_schedules += 1; + } + self.mark = Some(state); + } + + /// Enqueues a metatable stored on an already discovered owner. + /// + /// The edge is strong even when that owner caches weak values. Only the + /// direct metatable is queued; its `__index` child waits for the continued + /// scan. An absent metatable is not a target. This does not read `__mode`, + /// scan the owner, restart the cycle, or push an object that is already marked. + pub(super) fn barrier_strong_metatable(&mut self, owner: u32, slot: u32, generation: u32) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.write_barriers_open() && discovered_table(self, owner) { + enqueue_barrier_target(self, &mut state, slot, generation, HandleKind::Table); + } + self.mark = Some(state); + } + + /// Enqueues the direct object stored through an already discovered closed cell. + /// + /// The current edge is strong: a cell is not a table entry, so weak values + /// do not apply. The caller names the stored table or closure. Only that + /// object is queued; a closure's capture waits for the continued scan. The + /// cell itself is not rescanned. This does not add a root, read `__mode`, + /// or move either cursor. An owner that is not this upvalue generation, or + /// is not yet marked, is left for the continued scan. A published tail + /// never reaches here. + pub(super) fn barrier_strong_closed_cell( + &mut self, + owner: u32, + owner_generation: u32, + slot: u32, + generation: u32, + target: ClosedCellTarget, + ) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.write_barriers_open() && discovered_upvalue(self, owner, owner_generation) { + let kind = match target { + ClosedCellTarget::Table => HandleKind::Table, + ClosedCellTarget::Closure => HandleKind::Closure, + }; + enqueue_barrier_target(self, &mut state, slot, generation, kind); + } + 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. A new + /// metatable still being read records the key and value on the new edge + /// record, so a weak side is not marked early. A known mode decides in + /// this call and queues no later event. A later write merges into that + /// same record. This does not move the pending cursor. + pub(super) fn barrier_new_table_key( + &mut self, + owner: u32, + index: u32, + key_slot: u32, + key_generation: u32, + value: Option<(u32, u32)>, + ) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.write_barriers_open() && discovered_table(self, owner) { + let unknown = owner_mode_unknown(self, &state, owner); + if unknown { + queue_edge_key( + self, + &mut state, + index, + owner, + (key_slot, key_generation), + value, + ); + } else { + // A known mode decides now. The deferred record is only for a + // mode that is still being read; queueing every insertion + // would make each new key cost a later ModeLate unit. + 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); + } + + /// Registers the direct `__mode` of a metatable first attached while + /// mutation is open. The reset walk skips every mode read when no + /// metatable is attached, so a prewritten metatable that is attached for + /// the first time during Roots or Gray has never been parsed in this + /// round. The setter only links the slot into the intrusive late parse + /// queue; it reads no byte and performs no tree operation. A metatable + /// already parsed in this round, or with no direct mode record, needs no + /// registration, and an already queued slot keeps its one entry. A field + /// version the reset walk already inspected at its current record version + /// also needs no second read, even when the bytes named a strong mode and + /// left no weak cache: the checked field version and an effective weak + /// mode are different observations. A rewrite bumps `mode_epoch`, so that + /// later version still registers here (or on the write path). + pub(super) fn note_attached_mode(&mut self, slot: u32, generation: u32) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.write_barriers_open() { + let needs_read = self.slots.get(slot as usize).is_some_and(|stored| { + let checked = stored.mode_checked_generation == generation + && stored.mode_checked_round == state.rescan_epoch + && stored.mode_checked_epoch == stored.mode_epoch; + stored.kind == HandleKind::Table + && stored.generation == generation + && stored.mode_edge.is_some() + && !checked + && (stored.mode_generation != generation + || stored.mode_round != state.rescan_epoch) + }); + if needs_read && self.slots[slot as usize].late_mode_epoch != state.rescan_epoch { + push_late_mode(self, &mut state, slot); + self.scan.mode_late_registrations += 1; + } + } + self.mark = Some(state); + } + + /// Registers a direct `__mode` write made while mutation is open. The + /// setter only bumps the record version and links the metatable slot into + /// the late parse queue. A current-round parsed cache for the same slot + /// generation is already readable and needs no second read; a cache left + /// by an earlier round is stale and must not block this write. A write on + /// a slot that is already queued keeps the one queue entry and + /// invalidates the open parse, which restarts at byte zero. No string is + /// read and no indexed cache is grown here. + pub(super) fn note_late_mode_write(&mut self, owner: u32) { + let Some(mut state) = self.mark.take() else { + return; + }; + if state.write_barriers_open() { + self.scan.mode_late_lookups += 1; + let current_mode = self.slots[owner as usize].kind == HandleKind::Table + && self.slots[owner as usize].mode_generation + == self.slots[owner as usize].generation + && self.slots[owner as usize].mode_round == state.rescan_epoch; + if self.slots[owner as usize].late_mode_epoch == state.rescan_epoch { + self.scan.mode_late_cancels += 1; + } else if !current_mode { + push_late_mode(self, &mut state, owner); + self.scan.mode_late_registrations += 1; + } + } + self.mark = Some(state); + } + + /// Advances a parked gray cursor, a parked rescan cursor, or both, when + /// `unlink_at` removes that record. Two independent field compares. 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) { + if next.is_some() { + state.cursor = next; + } else { + state.owner = None; + state.cursor = None; + } + self.scan.parked_cursor_repairs += 1; + } + if state.rescan_owner == Some(owner) && state.rescan_cursor == Some(index) { + if next.is_some() { + state.rescan_cursor = next; + } else { + state.rescan_owner = None; + state.rescan_cursor = None; + } + self.scan.parked_rescan_cursor_repairs += 1; + } + } + + pub(super) fn drain_mark(&mut self) -> MarkSnapshot { + let mut session = MarkSession::start(self); + session.drain(); + session.into_snapshot() + } + + 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/src/frontends/lua/heap/table/pending_close.rs b/src/frontends/lua/heap/table/pending_close.rs new file mode 100644 index 0000000..dbf20f4 --- /dev/null +++ b/src/frontends/lua/heap/table/pending_close.rs @@ -0,0 +1,118 @@ +//! 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. Each +//! candidate keeps the slot kind so the host collector closes the concrete +//! typed resource that owns the raw handle. `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, + kind: slot.kind, + }); + 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/src/frontends/lua/heap/table/sweep.rs b/src/frontends/lua/heap/table/sweep.rs new file mode 100644 index 0000000..126f0c0 --- /dev/null +++ b/src/frontends/lua/heap/table/sweep.rs @@ -0,0 +1,1198 @@ +//! 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. `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, no +//! retained pending finalizer, and no live finalized userdata never enters +//! Owners and does not invent a publish window. A retained pending finalizer +//! forces the Owners walk so its weak values can be cleared even when every +//! retained slot stays live. The same is true for a settled (finalized without +//! a queue record) generation: a weak value that names it is value-dead, so +//! its weak value is cleared while a weak key keeps the entry. Independently +//! of the value bit, a `k`-only table clears a pending or settled userdata +//! value from its string-keyed and object-keyed hash entries, matching the +//! upstream hash loop. A negative or non-integer numeric key and an integer +//! above the upstream last possible array index are hash keys; other numeric +//! keys keep the previous rule because this representation does not carry +//! the actual array/hash split. + +use super::{ + CollectReport, EdgeKey, EdgeValue, GuestClass, HandleKind, HeapError, LuaHeap, MarkSnapshot, + ScanMeter, SlotState, TableRef, WeakMode, +}; +use vm::Value; + +/// The largest numeric key that the upstream dense array can still hold. +/// +/// LuaJIT caps the array part at `LJ_MAX_ASIZE = (1 << 27) + 1` slots, +/// including the zero slot (`lj_def.h:60-61`), and `inarray` accepts an +/// index only when `index < asize` (`lj_tab.h:79-84`). The largest index +/// that can ever be an array slot is therefore `2^27`, and every larger +/// integer key is necessarily a hash key. +const LAST_POSSIBLE_ARRAY_INDEX: f64 = 134_217_728.0; // (1 << 27) + +pub(super) struct SweepSession<'a> { + heap: &'a mut LuaHeap, + modes: MarkSnapshot, + phase: SweepPhase, + index: usize, + dead: Vec, + snapshot: Vec, + owner: usize, + owner_open: bool, + /// The open owner's parsed value-weak bit. A weak value that is dead is + /// published as a cursor gap or dropped. + owner_weak: bool, + /// The open owner's parsed key-weak bit. It keeps the existing weak-key + /// mark rule and also arms the upstream finalized-value check on the + /// hash entries of a `k`-only table. + owner_weak_keys: bool, + prev: Option, + cursor: Option, + marked_nodes: u32, + live_roots: u32, + /// At least one live slot is a retained pending finalizer. Such a slot is + /// not dead, but weak values that name it must still be published, so + /// Select enters Snapshot and Owners even when the dead list is empty. + pending_present: bool, + /// At least one live slot is a settled userdata generation. Settlement + /// never marks or retains the object, but a marked settled generation is + /// value-dead for weak publication; Owners must run even when no dead + /// slot and no pending record exist. + settled_present: bool, + report: Option, + pulse_spent: SweepUnits, +} + +struct SweepSlot { + marked: bool, + kind: HandleKind, + generation: u32, + /// The slot was selected as a pending finalizer when this mark finished. + /// A weak value in a marked weak table still treats it as value-dead; a + /// weak key keeps the entry because the slot is retained and marked. + pending: bool, + /// The slot generation was settled without a queue record. A weak value + /// in a marked weak table treats it as value-dead; a weak key keeps the + /// entry only when the object is actually marked. + settled: bool, + /// Generation whose parsed mode this slot held when the mark finished. + /// A metatable reused after that parse does not inherit the old mode. + mode_generation: u32, + /// Mark round that wrote the parse. A reset cache or a late parse from an + /// earlier round is not a current observation. + mode_round: u64, + /// The resolved weak bits for this slot, captured at the snapshot unit. + /// Sweep reads this record only; it does not query the indexed vector or + /// any record-keyed store. Both reset-parsed and late-parsed modes arrive + /// here through the same charged slot visit. + mode_weak: WeakMode, +} + +enum SweepPhase { + Select, + Snapshot, + Owners, + Release, + Roots, + Done, +} + +/// Release or root scan saved after publish. No snapshot, modes, or owner cursor. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum TailPhase { + Release, + Roots, + Done, +} + +/// Owned continuation of one published sweep. Release, Roots, and the +/// late-node count recorded after publish. +#[derive(Debug)] +pub(super) struct SweepTail { + phase: TailPhase, + index: usize, + dead: Vec, + marked_nodes: u32, + live_roots: u32, + late_nodes: u32, +} + +pub(super) enum TailStep { + Paused(SweepTail), + Completed(CollectReport), +} + +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() + } + + #[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; + 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; + 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, + late_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, + late_nodes, + }) + } + + 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`]. +struct TailCursor<'a> { + phase: &'a mut TailPhase, + 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, + 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.saturating_add(cursor.late_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, + 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 { + debug_assert!( + heap.sweep_tail.is_none(), + "a saved sweep tail and a new sweep cannot coexist" + ); + Self { + heap, + modes, + phase: SweepPhase::Select, + index: 0, + dead: Vec::new(), + snapshot: Vec::new(), + owner: 0, + owner_open: false, + owner_weak: false, + owner_weak_keys: false, + prev: None, + cursor: None, + marked_nodes: 0, + live_roots: 0, + pending_present: false, + settled_present: false, + 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") + } + + /// Walk Select and Snapshot by their real units, then stop before the + /// first owner unit. An empty dead set with no retained pending finalizer + /// 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 and no retained pending finalizer + /// 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), + 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 | 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, + late_nodes: 0, + 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; + self.phase = if self.dead.is_empty() && !self.pending_present && !self.settled_present { + 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; + #[cfg(test)] + self.heap + .selection_slot_trace + .borrow_mut() + .push(index as u32); + // One selection unit reads one slot. The registered reservation is a + // host-retained node: compare the record's slot number with the slot + // just read, and only an exact match checks this same borrowed slot + // for a registered raw, generation, kind, liveness, and an unbound + // token. A non-matching record is one record read, not a second slot + // index, so the unit never re-reads the reservation slot through the + // vector. + let slot = &self.heap.slots[index]; + match slot.state { + SlotState::Live { marked: false } => { + assert!( + !slot.pending_finalizer, + "lua heap sweep selected pending-finalizer slot {index} as dead; the mark must retain every live pending record" + ); + assert!( + slot.token.is_none(), + "lua heap sweep reached dead slot {index} with a bound host token; the host collector must close it and clear the binding before sweep" + ); + assert!( + !self.heap.pending_userdata.is_some_and(|pending| { + pending.slot as usize == index + && pending.raw.is_some() + && slot.generation == pending.generation + && slot.kind == HandleKind::Userdata + && slot.token.is_none() + && matches!(slot.state, SlotState::Live { .. }) + }), + "lua heap sweep reached the registered userdata reservation at slot {index}; the mark must retain it" + ); + // A pending finalizer must have been marked by its record + // offer. If it was not, the record is stale and the slot is + // now genuinely dead, so the ordinary dead path applies. + self.dead.push(index as u32); + self.heap.scan.scratch.dead_slots_pushed += 1; + } + SlotState::Live { marked: true } => { + self.marked_nodes += 1; + if slot.pending_finalizer { + self.pending_present = true; + } + if slot.finalizer_settled { + self.settled_present = true; + } + } + 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]; + // The snapshot unit is where the mode is resolved. The indexed vector + // covers the reset-sized prefix; a late parse outside it lives in the + // slot's own weak bits. Both are accepted only with the snapshot's + // round and the slot's generation, so a reused or stale parse reads + // as strong here. Sweep itself only reads this array. + let mode_weak = + if slot.mode_generation == slot.generation && slot.mode_round == self.modes.round { + match self.modes.modes.as_ref().and_then(|modes| modes.get(index)) { + Some(mode) => *mode, + None => slot.mode_weak, + } + } else { + WeakMode::default() + }; + self.snapshot.push(SweepSlot { + marked: matches!(slot.state, SlotState::Live { marked: true }), + kind: slot.kind, + generation: slot.generation, + pending: slot.pending_finalizer, + settled: slot.finalizer_settled, + mode_generation: slot.mode_generation, + mode_round: slot.mode_round, + mode_weak, + }); + 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; + let mode = self.owner_mode(owner); + self.owner_weak = mode.values; + self.owner_weak_keys = mode.keys; + self.prev = None; + self.cursor = self.heap.slots[owner].edge_head; + self.owner_open = true; + self.pulse_spent.heads += 1; + true + } + + fn owner_mode(&self, owner: usize) -> WeakMode { + let found = &self.snapshot[owner]; + if !found.marked || found.kind != HandleKind::Table { + return WeakMode::default(); + } + let Some((mt_slot, mt_generation)) = self.heap.slots[owner].metatable else { + return WeakMode::default(); + }; + let Some(mt) = self.snapshot.get(mt_slot as usize) else { + return WeakMode::default(); + }; + if !mt.marked || mt.kind != HandleKind::Table || mt.generation != mt_generation { + return WeakMode::default(); + } + if mt.mode_generation != mt_generation || mt.mode_round != self.modes.round { + return WeakMode::default(); + } + mt.mode_weak + } + + 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_values = self.owner_weak; + let weak_keys = self.owner_weak_keys; + 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) + } + EdgeValue::Userdata { slot, generation } => { + !self.typed(*slot, *generation, HandleKind::Userdata) + || self.pending(*slot, *generation) + || self.settled(*slot, *generation) + } + }; + // Upstream `gc_clearweak` checks every hash node of a marked weak + // table and clears a value when `gc_mayclear(value, 1)` reports a + // white value or a finalized userdata (`lj_gc.c:456-470,488-497`). + // That hash loop is not gated by `LJ_GC_WEAKVAL`, so a `k`-only table + // also drops a finalized userdata value. `isfinalized` covers both a + // separated queued finalizer (this heap's pending record) and a + // finalized userdata with no queue record (settled). + // + // This heap has one owner chain and does not model LuaJIT's dense + // array part. A guest string key (an ordinary name or the reserved + // `__mode` field, which `EdgeKey::named` stores as field id 0) and an + // object key are always hash keys, so those branches are claimed. A + // numeric key may name a dense array slot in LuaJIT: a negative + // number or a non-integer is never an integer array index, and an + // integer above `LAST_POSSIBLE_ARRAY_INDEX` cannot be one either, so + // those are hash keys. Zero, negative zero, and integers up to that + // bound can be array slots or hash nodes depending on the real array + // part, which this slice does not carry, so they keep the previous + // strong-value rule. Boolean keys have no representation here. The + // LuaJIT layout of an integer within the possible array range is + // therefore not claimed. + let hash_key = match &edge.key { + EdgeKey::Utf8(_) | EdgeKey::Object { .. } => true, + EdgeKey::Field(field) => *field == LuaHeap::MODE_FIELD, + EdgeKey::Number(bits) => { + let number = f64::from_bits(*bits); + number < 0.0 || number.fract() != 0.0 || number > LAST_POSSIBLE_ARRAY_INDEX + } + }; + let finalized_value = match &edge.value { + EdgeValue::Userdata { slot, generation } => { + self.pending(*slot, *generation) || self.settled(*slot, *generation) + } + EdgeValue::Table { .. } + | EdgeValue::Closure { .. } + | EdgeValue::Upvalue { .. } + | EdgeValue::Scalar(_) => false, + }; + let k_hash_finalized = + owner_marked && weak_keys && !weak_values && hash_key && finalized_value; + let clear_value = (weak_values && value_dead) || k_hash_finalized; + let make_gap = owner_marked && clear_value && 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) + } + EdgeValue::Userdata { slot, generation } => { + // A pending or settled userdata is value-dead for a weak + // value and for the hash value of a `k`-only table, even + // though it stays marked and retained. A guest-cursor key + // can publish that as a gap; a bare userdata key cannot, + // so the whole record is dropped instead of keeping the + // retained object as a strong value. + self.typed(*slot, *generation, HandleKind::Userdata) + && !(weak_values + && (self.pending(*slot, *generation) + || self.settled(*slot, *generation))) + && !k_hash_finalized + } + }; + 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 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 + }) + } + + /// One pending userdata generation in this sweep's snapshot. + /// + /// The slot is retained and marked, so it counts as alive for object + /// keys, but a weak value that names it is still published as a gap. A + /// stale edge to a reused generation is not pending. + fn pending(&self, slot: u32, generation: u32) -> bool { + self.snapshot.get(slot as usize).is_some_and(|found| { + found.pending && found.kind == HandleKind::Userdata && found.generation == generation + }) + } + + /// One settled (finalized without a queue record) userdata generation in + /// this sweep's snapshot. + /// + /// Settlement is not retention. The weak-value rule still applies when + /// the object is marked through another edge or a later root, matching + /// the upstream finalized flag. A weak key is decided by the real mark + /// bit elsewhere, not by this flag. A stale edge to a reused generation is + /// not settled. + fn settled(&self, slot: u32, generation: u32) -> bool { + self.snapshot.get(slot as usize).is_some_and(|found| { + found.settled && found.kind == HandleKind::Userdata && found.generation == generation + }) + } + + /// 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), + }) + } + + /// 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, + late_nodes: 0, + } + } + + 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)) + } + + /// Whether a cleared value under this key can stay as a cursor gap. + /// + /// The reserved `__mode` field is the one internal field id that is a + /// guest-visible string key: `guest_key` renders it as "__mode" and a + /// stored `__mode` name matches that field, so a real `next` cursor can + /// continue past it. Every other internal field id is not a guest key. + fn guest_cursor(&self, key: &EdgeKey) -> bool { + match key { + EdgeKey::Utf8(_) | EdgeKey::Number(_) => true, + EdgeKey::Field(field) => *field == LuaHeap::MODE_FIELD, + EdgeKey::Object { + slot, + generation, + kind: HandleKind::Table, + } => self.typed(*slot, *generation, HandleKind::Table), + EdgeKey::Object { .. } => false, + } + } +} + +/// 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>, +} + +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, + 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 + } +} + +/// 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/src/frontends/lua/imports.rs b/src/frontends/lua/imports.rs new file mode 100644 index 0000000..9398a06 --- /dev/null +++ b/src/frontends/lua/imports.rs @@ -0,0 +1,204 @@ +//! 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 ordinary +//! call cannot enter the module graph. A named link binds the declared local +//! 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, Span, Stmt, Suffix}; +use super::lexer; +use super::parser; +use vm::{ImportClause, ModuleImport, NamedImport, ParseError, SourceError, SourcePathError}; + +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(link) = classify_local(stmt) { + links.push(link); + } + if binds_require(stmt) { + require_shadowed = true; + } + } + 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 { + SourcePathError::Source(SourceError::Parse(ParseError::at_line( + usize::try_from(err.line).unwrap_or(usize::MAX), + err.message, + ))) +} + +fn classify_local(stmt: &Stmt) -> Option { + let Stmt::Local { names, values, .. } = stmt else { + return None; + }; + let [local_name] = names.as_slice() else { + return None; + }; + // 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)?; + 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(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: link.alias, + }]), + }; + ModuleImport { + spec: link.spec, + line: lines.line_at(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)?; + 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 { + 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() +} + +// 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 new file mode 100644 index 0000000..a7d46d7 --- /dev/null +++ b/src/frontends/lua/lexer.rs @@ -0,0 +1,1116 @@ +//! 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, + }) +} + +/// 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() + } + + 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) { + self.pos += newline_width(&self.src[self.pos..]); + 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 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'.' { + if dot.is_some() { + return Err(()); + } + dot = Some(p); + p += 1; + } else { + break; + } + } + 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 + }; + 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; + 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) { + 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(()); + } + } + // 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(), + 16 => c.is_ascii_hexdigit(), + _ => false, + } +} diff --git a/src/frontends/lua/lower.rs b/src/frontends/lua/lower.rs new file mode 100644 index 0000000..934f6f9 --- /dev/null +++ b/src/frontends/lua/lower.rs @@ -0,0 +1,1800 @@ +//! Test-only dynamic completion lowering for the Lua protected-call preflight. +//! +//! Production `LuaPlugin` does not call this module. A test `SourcePlugin` +//! feeds the real lexer, parser and resolver, then asks here for Core IR. It +//! is not a file entry, a second VM, or a fallback to the line lowerer. +//! +//! Every Lua function is lowered to the private completion `[Bool, ...values]`: +//! +//! - `true` at slot 0 means the call returned; slots 1.. are exactly the +//! source-visible values. Zero returns is `[true]`, one nil is `[true, nil]`. +//! - `false` at slot 0 means an explicit guest error raised by `error(value, 0)`; +//! slot 1 is the original object and no further values exist. +//! +//! Only call sites whose callee is statically admitted to be a Lua callable +//! produced by this lowering read that completion. A call of a host import +//! returns an ordinary value and is never unpacked by array shape. A real +//! `VmError` from a host call is not transformed into a guest tag; it stops the +//! VM on the normal error path. +//! +//! Admission is a whole-chunk static analysis, not a fixture property. A +//! parameter may be invoked dynamically only when every argument that reaches +//! that parameter from a statically visible call site (including `pcall` +//! forwarding) is itself a Lua function literal or another admitted parameter. +//! A missing argument is padded with nil at the Lua call boundary and counts +//! as a possible non-Lua value, so it taints the parameter for callable +//! admission even when another call site supplies a function literal. A +//! callable binding must come from a function literal in this chunk and must +//! never be reassigned. Non-Lua data may flow through parameters and be +//! returned; only the dynamic callee position is constrained. Anything else is +//! refused at lowering time. +//! +//! The slice deliberately refuses unsupported statements, expressions, +//! multi-value forms, and extra arguments instead of guessing. Missing +//! arguments are padded with nil, matching the Lua call boundary, but return +//! values are never padded: the completion arity is the executed arity. +//! +//! `pcall` is a lowering form, not a callable value: it performs one dynamic +//! `CallValue` on its target and turns the target's completion into a private +//! sequence. `error(value, 0)` is a lowering form that completes the current +//! Lua function with `[false, value]` immediately. Both are limited to the +//! exact shapes documented here. +//! +//! A second private entry, [`lower_source_with_roots`], keeps this completion +//! and admission contract but wraps every lowered function in one real LuaHeap +//! root frame. Each admitted Lua call then hands its error payload to the +//! caller's reserved temp slot while the callee frame is still the top frame; +//! only after that write is the callee frame retired. A `pcall` that binds the +//! payload moves it from the temp slot into its formal slot; a status-only or +//! statement `pcall` discards the object and clears the exact temp root in the +//! same statement. A protected call in tail-return position and a table literal +//! have no root handoff in this slice, so both are refused at lowering. That +//! entry is compiled only by the root-handoff test. Production `LuaPlugin` +//! never reaches it. +use std::collections::{HashMap, HashSet}; + +use super::ast::{ + Args, Block, Chunk, Expr as LuaExpr, ExprList, Field, FuncBody, Name, Span, Stmt as LuaStmt, + Suffix, +}; +use super::lexer; +use super::parser; +use super::resolve::{self, BindingKind, Resolution, ResolveError}; +use vm::compiler::HostCallResolver; +use vm::{ + BuiltinFunction, ClosureExpr, Expr, FrontendIr, LocalIrBuilder, LocalSlot, ParseError, Stmt, + TypeSchema, +}; + +/// The only globals this test candidate binds as host imports. They are real +/// host functions injected by the test, not guest callables. +const HOST_IMPORTS: &[&str] = &["mark", "note", "fault", "tick"]; + +/// Guest-visible host calls admitted only by the private root-handoff mode. +/// They allocate real LuaHeap tables; no Core array stands in for a table. +const ROOT_GUEST_IMPORTS: &[&str] = &["newtable", "setchild"]; + +/// Private root transport calls. Their host bodies live in the test; the +/// lowerer only emits the frame protocol around the existing completion +/// transport. +const ROOT_ENTER: &str = "lua_root_enter"; +const ROOT_HANDOFF: &str = "lua_root_handoff"; +const ROOT_FORMAL: &str = "lua_root_formal"; +const ROOT_DISCARD: &str = "lua_root_discard"; +const ROOT_FINISH: &str = "lua_root_finish"; + +/// Slots reserved in every root frame: slot 0 receives the handoff payload +/// while the callee frame is still live; slot 1 receives the formal result of +/// a `pcall` in that function. Both start empty. +const ROOT_FRAME_WIDTH: i64 = 2; +const ROOT_HANDOFF_SLOT: i64 = 0; +const ROOT_FORMAL_SLOT: i64 = 1; + +pub(super) fn lower_source_with( + source: &str, + hosts: Option<&HostCallResolver<'_>>, +) -> Result { + lower_source(source, hosts, false) +} + +/// Private root-handoff entry. Same lexer, parser, resolver, admission +/// analysis and completion transport as [`lower_source_with`]; the only +/// addition is the real Lua heap frame protocol around each admitted Lua call. +/// Production `LuaPlugin` does not call this entry. +pub(super) fn lower_source_with_roots( + source: &str, + hosts: Option<&HostCallResolver<'_>>, +) -> Result { + lower_source(source, hosts, true) +} + +fn lower_source( + source: &str, + hosts: Option<&HostCallResolver<'_>>, + roots: bool, +) -> 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() { + return Err(ParseError::at_line( + line_of(source, error_span(error)), + static_message(error), + )); + } + if let Some(limit) = resolution.limits.first() { + let kind = match limit.kind { + resolve::LexicalLimitKind::Locals => "active local slots", + resolve::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, hosts, roots); + lower.analyze(&chunk)?; + let mut pre = Vec::new(); + let chunk_frame = if roots { + let frame = lower.alloc_temp("root_chunk")?; + pre.push(Stmt::Let { + index: frame, + declared_schema: None, + expr: lower.root_enter_call()?, + line: 1, + }); + Some(frame) + } else { + None + }; + lower.push_frame(chunk.span, None, chunk_frame); + let body = lower.lower_block(&chunk.body.stmts)?; + let body = match chunk_frame { + Some(frame) => lower.root_finish_call(body, frame, 1)?, + None => body, + }; + lower.pop_frame(); + pre.push(Stmt::Expr { + expr: body, + line: 1, + }); + let mut ir = lower.builder.finish(pre); + ir.implicit_extern_names = Vec::new(); + Ok(ir) +} + +#[derive(Clone, Copy, Debug)] +struct Proof { + arity: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CallClass { + /// The expression evaluates to a private `[Bool, ...values]` completion of + /// a Lua callable that was statically admitted. + Lua, + /// The expression evaluates to a private sequence `[ok, ...values]` of one + /// `pcall` target call. It never raises the guest error itself. + Pcall, + /// The expression evaluates to the explicit error object argument. + Error, + /// The expression evaluates to an ordinary host call result. + Host, +} + +struct Site<'a> { + callee_binding: Option, + literal: Option, + pcall: bool, + args: Vec<&'a LuaExpr>, +} + +struct Frame { + span: Span, + declared: HashSet, + captures: HashMap, + capture_copies: Vec<(LocalSlot, LocalSlot)>, + /// Binding of the local function currently being created, if any. A use of + /// that binding inside its own body would capture a not-yet-assigned slot. + creating: Option, + /// Core local holding this function's Lua heap root-frame token in the + /// private root-handoff mode. `None` in the completion-only mode. + root: Option, +} + +struct Lower<'a> { + source: &'a str, + resolution: &'a Resolution, + hosts: Option<&'a HostCallResolver<'a>>, + roots: bool, + builder: LocalIrBuilder, + binding_slots: Vec>, + frames: Vec, + temp: u32, + body_by_id: HashMap, + function_body_of_binding: Vec>, + param_bindings: HashMap>, + possible: Vec>, + non_lua: Vec, + assigned: Vec, + sites: Vec>, +} + +impl<'a> Lower<'a> { + fn new( + source: &'a str, + resolution: &'a Resolution, + hosts: Option<&'a HostCallResolver<'a>>, + roots: bool, + ) -> Self { + let count = resolution.bindings.len(); + Self { + source, + resolution, + hosts, + roots, + builder: LocalIrBuilder::new(), + binding_slots: vec![None; count], + frames: Vec::new(), + temp: 0, + body_by_id: HashMap::new(), + function_body_of_binding: vec![None; count], + param_bindings: HashMap::new(), + possible: vec![HashSet::new(); count], + non_lua: vec![false; count], + assigned: vec![false; count], + sites: Vec::new(), + } + } + + // ---- static admission ------------------------------------------------- + + fn analyze(&mut self, chunk: &'a Chunk) -> Result<(), ParseError> { + self.walk_block(&chunk.body)?; + self.propagate(); + Ok(()) + } + + fn walk_block(&mut self, block: &'a Block) -> Result<(), ParseError> { + for stmt in &block.stmts { + self.walk_stmt(stmt)?; + } + Ok(()) + } + + fn walk_stmt(&mut self, stmt: &'a LuaStmt) -> Result<(), ParseError> { + match stmt { + LuaStmt::Empty { .. } + | LuaStmt::Break { .. } + | LuaStmt::Continue { .. } + | LuaStmt::Goto { .. } + | LuaStmt::Label { .. } => Ok(()), + LuaStmt::Do { body, .. } + | LuaStmt::While { body, .. } + | LuaStmt::Repeat { body, .. } + | LuaStmt::NumericFor { body, .. } + | LuaStmt::GenericFor { body, .. } => { + match stmt { + LuaStmt::While { cond, .. } => self.walk_expr(cond)?, + LuaStmt::Repeat { until, .. } => self.walk_expr(until)?, + LuaStmt::NumericFor { + start, limit, step, .. + } => { + self.walk_expr(start)?; + self.walk_expr(limit)?; + if let Some(step) = step { + self.walk_expr(step)?; + } + } + LuaStmt::GenericFor { iters, .. } => self.walk_expr_list(iters)?, + _ => {} + } + self.walk_block(body) + } + LuaStmt::If { + arms, else_body, .. + } => { + for arm in arms { + self.walk_expr(&arm.cond)?; + self.walk_block(&arm.body)?; + } + if let Some(body) = else_body { + self.walk_block(body)?; + } + Ok(()) + } + LuaStmt::Local { names, values, .. } => { + self.walk_expr_list(values)?; + if names.len() == 1 + && values.exprs.len() == 1 + && let Some(body) = function_literal(&values.exprs[0]) + { + let id = body.span.start; + if let Some(binding) = + self.declaration_binding(&names[0].name, BindingKind::Local) + { + self.function_body_of_binding[binding] = Some(id); + self.possible[binding].insert(id); + } + } + Ok(()) + } + LuaStmt::LocalFunction { name, func, .. } => { + let body = func; + self.register_function(body)?; + if let Some(binding) = self.declaration_binding(name, BindingKind::Function) { + self.function_body_of_binding[binding] = Some(body.span.start); + self.possible[binding].insert(body.span.start); + } + self.walk_block(&body.body) + } + LuaStmt::Function { name, body, .. } => { + let _ = name; + self.register_function(body)?; + self.walk_block(&body.body) + } + LuaStmt::Assign { + targets, values, .. + } => { + self.walk_expr_list(values)?; + for target in targets { + self.mark_target_assigned(target); + self.walk_target(target)?; + } + Ok(()) + } + LuaStmt::CompoundAssign { target, value, .. } => { + self.mark_target_assigned(target); + self.walk_target(target)?; + self.walk_expr(value) + } + LuaStmt::Call { call, .. } => self.walk_expr(call), + LuaStmt::Return { values, .. } => self.walk_expr_list(values), + } + } + + fn walk_target(&mut self, target: &'a super::ast::AssignTarget) -> Result<(), ParseError> { + match target { + super::ast::AssignTarget::Name(_) => Ok(()), + super::ast::AssignTarget::Index { table, key, .. } => { + self.walk_expr(table)?; + self.walk_expr(key) + } + super::ast::AssignTarget::Field { table, .. } => self.walk_expr(table), + } + } + + fn mark_target_assigned(&mut self, target: &super::ast::AssignTarget) { + if let super::ast::AssignTarget::Name(name) = target + && let Some(binding) = self.use_binding(name) + { + self.assigned[binding] = true; + } + } + + fn walk_expr_list(&mut self, list: &'a ExprList) -> Result<(), ParseError> { + for expr in &list.exprs { + self.walk_expr(expr)?; + } + Ok(()) + } + + fn walk_expr(&mut self, expr: &'a LuaExpr) -> Result<(), ParseError> { + match expr { + LuaExpr::Nil { .. } + | LuaExpr::Bool { .. } + | LuaExpr::Number { .. } + | LuaExpr::String { .. } + | LuaExpr::Vararg { .. } + | LuaExpr::Name { .. } => Ok(()), + LuaExpr::Paren { inner, .. } => self.walk_expr(inner), + LuaExpr::Unary { expr, .. } => self.walk_expr(expr), + LuaExpr::Binary { left, right, .. } => { + self.walk_expr(left)?; + self.walk_expr(right) + } + LuaExpr::BinaryChain { base, steps, .. } => { + self.walk_expr(base)?; + for step in steps { + self.walk_expr(&step.expr)?; + } + Ok(()) + } + LuaExpr::Ternary { + cond, + then_expr, + else_expr, + .. + } => { + self.walk_expr(cond)?; + self.walk_expr(then_expr)?; + self.walk_expr(else_expr) + } + LuaExpr::SuffixChain { base, steps, .. } => { + if let Some(site) = self.site_of(expr) { + self.sites.push(site); + } + self.walk_expr(base)?; + for step in steps { + match step { + Suffix::Field { .. } => {} + Suffix::Index { key, .. } => self.walk_expr(key)?, + Suffix::Call { args, .. } | Suffix::Method { args, .. } => match args { + Args::List(list) => self.walk_expr_list(list)?, + Args::String { .. } => {} + Args::Table { fields, .. } => { + for field in fields { + self.walk_field(field)?; + } + } + }, + } + } + Ok(()) + } + LuaExpr::Function { body, .. } => { + self.register_function(body)?; + self.walk_block(&body.body) + } + LuaExpr::ShortFunction { body, .. } => match body.as_ref() { + super::ast::ShortBody::Expr(expr) => self.walk_expr(expr), + super::ast::ShortBody::Block(block) => self.walk_block(block), + }, + LuaExpr::Table { fields, .. } => { + for field in fields { + self.walk_field(field)?; + } + Ok(()) + } + } + } + + fn walk_field(&mut self, field: &'a Field) -> Result<(), ParseError> { + match field { + Field::Item { value, .. } | Field::Name { value, .. } => self.walk_expr(value), + Field::Index { key, value, .. } => { + self.walk_expr(key)?; + self.walk_expr(value) + } + } + } + + fn register_function(&mut self, func: &'a FuncBody) -> Result<(), ParseError> { + let id = func.span.start; + if self.body_by_id.contains_key(&id) { + return Err(ParseError::at_line( + line_of(self.source, func.span), + "duplicate function body span in the completion slice", + )); + } + self.body_by_id.insert(id, func); + let mut params = Vec::with_capacity(func.params.len()); + for param in &func.params { + let binding = self + .declaration_binding(param, BindingKind::Param) + .ok_or_else(|| { + ParseError::at_line( + line_of(self.source, param.span), + "function parameter has no resolver binding", + ) + })?; + params.push(binding); + } + self.param_bindings.insert(id, params); + Ok(()) + } + + /// A call site shape this slice can reason about: one direct call step with + /// a list argument on a plain name or a function literal. + fn site_of(&self, expr: &'a LuaExpr) -> Option> { + let LuaExpr::SuffixChain { base, steps, .. } = expr else { + return None; + }; + let [ + Suffix::Call { + args: Args::List(list), + .. + }, + ] = steps.as_slice() + else { + return None; + }; + let mut site = Site { + callee_binding: None, + literal: None, + pcall: false, + args: list.exprs.iter().collect(), + }; + match base.as_ref() { + LuaExpr::Name { name, .. } => match self.use_binding(name) { + Some(binding) => site.callee_binding = Some(binding), + None if name.is("pcall") => site.pcall = true, + None => {} + }, + LuaExpr::Function { body, .. } => site.literal = Some(body.span.start), + _ => {} + } + Some(site) + } + + /// One fixpoint over both facts admission needs: which function bodies can + /// reach a parameter, and whether any reachable argument is a non-Lua + /// value. A missing argument is nil at the Lua call boundary, so it is a + /// non-Lua source even when another call site supplies a function literal. + fn propagate(&mut self) { + loop { + let mut changed = false; + for site in &self.sites { + let targets = self.site_targets(site); + let offset = usize::from(site.pcall); + for target in targets { + let params = self + .param_bindings + .get(&target) + .cloned() + .unwrap_or_default(); + for (index, ¶m) in params.iter().enumerate() { + let Some(arg) = site.args.get(offset + index) else { + if !self.non_lua[param] { + self.non_lua[param] = true; + changed = true; + } + continue; + }; + let sources = self.expr_sources(arg); + for source in sources { + if self.possible[param].insert(source) { + changed = true; + } + } + if !self.expr_lua_only(arg) && !self.non_lua[param] { + self.non_lua[param] = true; + changed = true; + } + } + } + } + if !changed { + break; + } + } + } + + fn site_targets(&self, site: &Site<'a>) -> Vec { + if let Some(binding) = site.callee_binding { + return self.possible[binding].iter().copied().collect(); + } + if let Some(literal) = site.literal { + return vec![literal]; + } + if site.pcall { + return site + .args + .first() + .map(|callee| self.expr_sources(callee)) + .unwrap_or_default(); + } + Vec::new() + } + + fn expr_sources(&self, expr: &LuaExpr) -> Vec { + match expr { + LuaExpr::Function { body, .. } => vec![body.span.start], + LuaExpr::Paren { inner, .. } => self.expr_sources(inner), + LuaExpr::Name { name, .. } => self + .use_binding(name) + .map(|binding| self.possible[binding].iter().copied().collect()) + .unwrap_or_default(), + _ => Vec::new(), + } + } + + /// Whether every value this expression can evaluate to is a Lua callable + /// produced by this lowering: a function literal, or a name whose binding + /// is a non-reassigned function literal or an admitted parameter with no + /// known non-Lua source. Any other expression may be ordinary data. + fn expr_lua_only(&self, expr: &LuaExpr) -> bool { + match expr { + LuaExpr::Function { .. } => true, + LuaExpr::Paren { inner, .. } => self.expr_lua_only(inner), + LuaExpr::Name { name, .. } => self + .use_binding(name) + .is_some_and(|binding| self.binding_lua_only(binding)), + _ => false, + } + } + + fn binding_lua_only(&self, binding: usize) -> bool { + if self.assigned[binding] { + return false; + } + if self.function_body_of_binding[binding].is_some() { + return true; + } + self.resolution.bindings[binding].kind == BindingKind::Param && !self.non_lua[binding] + } + + /// Whether `binding` is an immutable binding whose every admitted source + /// is a Lua callable produced by this lowering. This is the value-position + /// counterpart of `proof_for`: a read never selects an arity, so a + /// parameter whose callable sources disagree on arity is still admitted + /// here, while one with no known source or any non-Lua source is not. + fn binding_is_admitted_callable(&self, binding: usize) -> bool { + if self.assigned[binding] { + return false; + } + if self.function_body_of_binding[binding].is_some() { + return true; + } + self.resolution.bindings[binding].kind == BindingKind::Param + && !self.possible[binding].is_empty() + && !self.non_lua[binding] + } + + // ---- binding and slot plumbing --------------------------------------- + + fn use_binding(&self, name: &Name) -> Option { + self.resolution + .uses + .iter() + .find(|usage| usage.span == name.span) + .and_then(|usage| usage.binding) + } + + fn declaration_binding(&self, name: &Name, kind: BindingKind) -> Option { + self.resolution + .bindings + .iter() + .position(|binding| binding.span == name.span && binding.kind == kind) + } + + fn push_frame(&mut self, span: Span, creating: Option, root: Option) { + self.frames.push(Frame { + span, + declared: HashSet::new(), + captures: HashMap::new(), + capture_copies: Vec::new(), + creating, + root, + }); + } + + fn pop_frame(&mut self) -> Frame { + self.frames.pop().expect("completion frame stack") + } + + fn declare(&mut self, binding: usize) -> Result { + let slot = match self.binding_slots[binding] { + Some(slot) => slot, + None => { + let name = format!("$lua_completion_b{binding}"); + let slot = self.builder.alloc_local_named(&name)?; + self.binding_slots[binding] = Some(slot); + slot + } + }; + self.frames + .last_mut() + .expect("completion frame") + .declared + .insert(binding); + Ok(slot) + } + + fn slot_for(&mut self, binding: usize) -> Result { + let top = self.frames.len().checked_sub(1).expect("completion frame"); + self.access_in_frame(top, binding) + } + + fn access_in_frame( + &mut self, + frame_index: usize, + binding: usize, + ) -> Result { + if self.frames[frame_index].declared.contains(&binding) { + return self.binding_slots[binding].ok_or_else(|| { + ParseError::at_line(1, "declared completion binding has no local slot") + }); + } + if let Some(slot) = self.frames[frame_index].captures.get(&binding) { + return Ok(*slot); + } + if self.frames[frame_index].creating == Some(binding) { + return Err(ParseError::at_line( + line_of(self.source, self.frames[frame_index].span), + "recursive Lua function references are not in the completion slice", + )); + } + if frame_index == 0 { + return Err(ParseError::at_line( + 1, + "binding is not visible in this completion slice", + )); + } + let source = self.access_in_frame(frame_index - 1, binding)?; + let name = format!("$lua_completion_cap_{frame_index}_{binding}"); + let target = self.builder.alloc_local_named(&name)?; + self.frames[frame_index].captures.insert(binding, target); + self.frames[frame_index] + .capture_copies + .push((source, target)); + Ok(target) + } + + /// A nested Lua function reaches an outer callable through a capture copy. + /// The fixed Core classifies a capture by scanning the closure body for a + /// read of the captured slot, and `Expr::LocalCall` names its callee slot + /// without counting as a read. Left implicit, the capture falls back to + /// `Move`, which detaches the original Lua binding even though Lua keeps + /// that binding usable after the closure is created. Return an explicit + /// by-value copy the call performs (`.copy()`, a `ToOwned` read) as the + /// callee slot, so the capture is classified `Copy` and the original + /// binding survives. This is the callee half of one read policy: every + /// read of an admitted immutable Lua callable binding, in any value + /// position, uses the same explicit non-consuming read (see + /// `binding_is_admitted_callable`). + fn captured_callee_slot( + &mut self, + binding: usize, + span: Span, + ) -> Result<(LocalSlot, Option), ParseError> { + let slot = self.slot_for(binding)?; + let Some(captured) = self + .frames + .last() + .expect("completion frame") + .captures + .get(&binding) + .copied() + else { + return Ok((slot, None)); + }; + let copy = self.alloc_temp("callee_copy")?; + Ok(( + copy, + Some(Stmt::Let { + index: copy, + declared_schema: None, + expr: explicit_value_read(captured), + line: self.line(span), + }), + )) + } + + fn alloc_temp(&mut self, role: &str) -> Result { + let name = format!("$lua_completion_tmp_{role}_{}", self.temp); + self.temp += 1; + self.builder.alloc_local_named(&name) + } + + /// Opens one private Lua heap root frame of the fixed width. Emitted only + /// by the root-handoff entry; the completion-only entry never calls it. + fn root_enter_call(&mut self) -> Result { + self.root_host_call( + ROOT_ENTER, + vec![Expr::Int(ROOT_FRAME_WIDTH)], + Span { start: 0, end: 0 }, + ) + } + + /// Resolves one private root transport host call through the same test host + /// catalog the guest-visible host imports use. These names never appear in + /// a Lua source; they are compiler-emitted frame protocol. + fn root_host_call( + &mut self, + name: &str, + args: Vec, + span: Span, + ) -> Result { + let arity = u8::try_from(args.len()) + .map_err(|_| self.fail(span, "root transport call has too many arguments"))?; + self.builder + .declare_function(name, Some(arity)) + .map_err(|error| self.fail(span, error.message))?; + let signature = vec![TypeSchema::Unknown; args.len()]; + let resolver = self.hosts.ok_or_else(|| { + self.fail( + span, + "root transport requires the completion test host catalog", + ) + })?; + let resolved = resolver + .resolve(name, &signature) + .map_err(|error| self.fail(span, format!("root transport resolution: {error}")))?; + let index = self + .builder + .function_index(name) + .ok_or_else(|| self.fail(span, "root transport function was not declared"))?; + Ok(Expr::Call( + index, + Vec::new(), + args, + Some(Box::new(resolved)), + None, + )) + } + + /// Wraps one completed admitted Lua call with the caller-side handoff. + /// The callee's Lua root frame is still the top frame here: publishing to + /// the parent happens before that frame is retired, inside the host. + fn wrap_handoff(&mut self, completion: Expr, span: Span) -> Result { + if !self.roots { + return Ok(completion); + } + let frame = self + .frames + .last() + .and_then(|frame| frame.root) + .ok_or_else(|| { + self.fail( + span, + "a Lua call cannot hand off without a current root frame", + ) + })?; + self.root_host_call(ROOT_HANDOFF, vec![completion, Expr::Var(frame)], span) + } + + /// Closes the chunk root frame. Only the chunk uses this: a callee frame + /// is retired by its caller's handoff after the parent root is written. + fn root_finish_call( + &mut self, + completion: Expr, + frame: LocalSlot, + span_start: u32, + ) -> Result { + self.root_host_call( + ROOT_FINISH, + vec![completion, Expr::Var(frame), Expr::Int(ROOT_FORMAL_SLOT)], + Span { + start: span_start, + end: span_start, + }, + ) + } + + // ---- function and statement lowering -------------------------------- + + fn lower_function( + &mut self, + func: &'a FuncBody, + creating: Option, + ) -> Result { + let root = if self.roots { + Some(self.alloc_temp("root_frame")?) + } else { + None + }; + self.push_frame(func.span, creating, root); + let mut param_slots = Vec::with_capacity(func.params.len()); + for param in &func.params { + let binding = self + .declaration_binding(param, BindingKind::Param) + .ok_or_else(|| { + ParseError::at_line( + line_of(self.source, param.span), + "function parameter has no resolver binding", + ) + })?; + param_slots.push(self.declare(binding)?); + } + let body = self.lower_block(&func.body.stmts)?; + let body = match root { + Some(slot) => Expr::Block { + stmts: vec![Stmt::Let { + index: slot, + declared_schema: None, + expr: self.root_enter_call()?, + line: self.line(func.span), + }], + expr: Box::new(body), + }, + None => body, + }; + let frame = self.pop_frame(); + Ok(ClosureExpr { + param_slots, + capture_copies: frame.capture_copies, + body: Box::new(body), + }) + } + + fn lower_block(&mut self, stmts: &'a [LuaStmt]) -> Result { + let mut pre: Vec = Vec::new(); + let mut index = 0; + while index < stmts.len() { + match &stmts[index] { + LuaStmt::Empty { .. } => index += 1, + LuaStmt::Local { + names, + values, + span, + } => { + if let Some(tail) = + self.lower_local(names, values, *span, &stmts[index + 1..], &mut pre)? + { + return Ok(block(pre, tail)); + } + index += 1; + } + LuaStmt::LocalFunction { + name, func, span, .. + } => { + let binding = self + .declaration_binding(name, BindingKind::Function) + .ok_or_else(|| { + self.fail( + name.span, + "local function has no resolver binding in the completion slice", + ) + })?; + let slot = self.declare(binding)?; + let closure = self.lower_function(func, Some(binding))?; + pre.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: Expr::Closure(closure), + line: self.line(*span), + }); + index += 1; + } + LuaStmt::Call { call, span } => { + if let Some(tail) = + self.lower_call_statement(call, *span, &stmts[index + 1..], &mut pre)? + { + return Ok(block(pre, tail)); + } + index += 1; + } + LuaStmt::Return { values, span } => { + let expr = self.lower_return(values, *span)?; + return Ok(block(pre, expr)); + } + other => { + return Err( + self.fail(stmt_span(other), "statement is not in the completion slice") + ); + } + } + } + Ok(block(pre, completion(&[]))) + } + + fn lower_local( + &mut self, + names: &'a [super::ast::LocalName], + values: &'a ExprList, + span: Span, + rest: &'a [LuaStmt], + pre: &mut Vec, + ) -> Result, ParseError> { + let line = self.line(span); + if names.is_empty() { + return Err(self.fail(span, "empty local declaration in the completion slice")); + } + if names.len() == 1 + && values.exprs.len() == 1 + && let Some(body) = function_literal(&values.exprs[0]) + { + let binding = self + .declaration_binding(&names[0].name, BindingKind::Local) + .ok_or_else(|| self.fail(names[0].name.span, "local has no resolver binding"))?; + let slot = self.declare(binding)?; + let closure = self.lower_function(body, Some(binding))?; + pre.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: Expr::Closure(closure), + line, + }); + return Ok(None); + } + if values.exprs.len() == 1 && is_call_shape(&values.exprs[0]) { + let (class, value) = self.lower_call(&values.exprs[0])?; + match class { + CallClass::Lua => { + let completion = self.alloc_temp("completion")?; + pre.push(Stmt::Let { + index: completion, + declared_schema: None, + expr: value, + line, + }); + let mut then_stmts = Vec::new(); + for (index, name) in names.iter().enumerate() { + let binding = self + .declaration_binding(&name.name, BindingKind::Local) + .ok_or_else(|| { + self.fail(name.name.span, "local has no resolver binding") + })?; + let slot = self.declare(binding)?; + then_stmts.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: guarded_get(completion, index as i64 + 1), + line, + }); + } + let rest_expr = self.lower_block(rest)?; + return Ok(Some(Expr::IfElse { + condition: Box::new(status_of(completion)), + then_expr: Box::new(block(then_stmts, rest_expr)), + else_expr: Box::new(Expr::Var(completion)), + })); + } + CallClass::Pcall => { + let sequence = self.alloc_temp("pcall")?; + pre.push(Stmt::Let { + index: sequence, + declared_schema: None, + expr: value, + line, + }); + let mut formal_slot = None; + for (index, name) in names.iter().enumerate() { + let binding = self + .declaration_binding(&name.name, BindingKind::Local) + .ok_or_else(|| { + self.fail(name.name.span, "local has no resolver binding") + })?; + let slot = self.declare(binding)?; + pre.push(Stmt::Let { + index: slot, + declared_schema: None, + expr: guarded_get(sequence, index as i64), + line, + }); + if index == 1 { + formal_slot = Some(slot); + } + } + if self.roots + && let Some(frame) = self.frames.last().and_then(|frame| frame.root) + { + match formal_slot { + Some(err) => { + // The protected payload is bound. Adopt the + // temp handoff root into the formal slot and + // clear the temp slot in one host call. A + // non-table payload needs no root, but the + // host still verifies the reserved slots. + let formal = self.root_host_call( + ROOT_FORMAL, + vec![ + Expr::Var(err), + Expr::Var(frame), + Expr::Int(ROOT_HANDOFF_SLOT), + Expr::Int(ROOT_FORMAL_SLOT), + ], + span, + )?; + let discarded = self.alloc_temp("root_formal")?; + pre.push(Stmt::Let { + index: discarded, + declared_schema: None, + expr: formal, + line, + }); + } + None => { + // No second local binds the payload: the whole + // protected sequence is discarded. Clear the + // exact temp root now, not at the next call. + let discard = self.root_host_call( + ROOT_DISCARD, + vec![ + Expr::Var(sequence), + Expr::Var(frame), + Expr::Int(ROOT_HANDOFF_SLOT), + ], + span, + )?; + let discarded = self.alloc_temp("root_discard")?; + pre.push(Stmt::Let { + index: discarded, + declared_schema: None, + expr: discard, + line, + }); + } + } + } + return Ok(None); + } + CallClass::Error => return Ok(Some(completion_error(value))), + CallClass::Host => { + for (index, name) in names.iter().enumerate() { + let binding = self + .declaration_binding(&name.name, BindingKind::Local) + .ok_or_else(|| { + self.fail(name.name.span, "local has no resolver binding") + })?; + let slot = self.declare(binding)?; + let expr = if index == 0 { + value.clone() + } else { + Expr::Null + }; + pre.push(Stmt::Let { + index: slot, + declared_schema: None, + expr, + line, + }); + } + return Ok(None); + } + } + } + if values.exprs.len() > names.len() { + return Err(self.fail( + span, + "more initializer values than locals are not in the completion slice", + )); + } + for (index, name) in names.iter().enumerate() { + let binding = self + .declaration_binding(&name.name, BindingKind::Local) + .ok_or_else(|| self.fail(name.name.span, "local has no resolver binding"))?; + let slot = self.declare(binding)?; + let expr = match values.exprs.get(index) { + Some(value) => self.lower_scalar(value)?, + None => Expr::Null, + }; + pre.push(Stmt::Let { + index: slot, + declared_schema: None, + expr, + line, + }); + } + Ok(None) + } + + fn lower_call_statement( + &mut self, + call: &'a LuaExpr, + span: Span, + rest: &'a [LuaStmt], + pre: &mut Vec, + ) -> Result, ParseError> { + let line = self.line(span); + let (class, value) = self.lower_call(call)?; + match class { + CallClass::Lua => { + let completion = self.alloc_temp("completion")?; + pre.push(Stmt::Let { + index: completion, + declared_schema: None, + expr: value, + line, + }); + let rest_expr = self.lower_block(rest)?; + Ok(Some(Expr::IfElse { + condition: Box::new(status_of(completion)), + then_expr: Box::new(rest_expr), + else_expr: Box::new(Expr::Var(completion)), + })) + } + CallClass::Pcall => { + let discarded = self.alloc_temp("discarded")?; + pre.push(Stmt::Let { + index: discarded, + declared_schema: None, + expr: value, + line, + }); + if self.roots + && let Some(frame) = self.frames.last().and_then(|frame| frame.root) + { + // Statement position discards every protected result. + // Clear the exact temp root in this same statement so the + // next handoff does not find it occupied. + let discard = self.root_host_call( + ROOT_DISCARD, + vec![ + Expr::Var(discarded), + Expr::Var(frame), + Expr::Int(ROOT_HANDOFF_SLOT), + ], + span, + )?; + let sink = self.alloc_temp("root_discard")?; + pre.push(Stmt::Let { + index: sink, + declared_schema: None, + expr: discard, + line, + }); + } + Ok(None) + } + CallClass::Host => { + let discarded = self.alloc_temp("discarded")?; + pre.push(Stmt::Let { + index: discarded, + declared_schema: None, + expr: value, + line, + }); + Ok(None) + } + CallClass::Error => Ok(Some(completion_error(value))), + } + } + + fn lower_return(&mut self, values: &'a ExprList, span: Span) -> Result { + if values.exprs.is_empty() { + return Ok(completion(&[])); + } + if values.exprs.len() == 1 { + let expr = &values.exprs[0]; + if is_call_shape(expr) { + let (class, value) = self.lower_call(expr)?; + if self.roots && class == CallClass::Pcall { + return Err(self.fail( + span, + "a protected call in tail-return position has no table root handoff in this slice", + )); + } + return Ok(match class { + CallClass::Lua => value, + CallClass::Pcall => pcall_tail_completion(value), + CallClass::Error => completion_error(value), + CallClass::Host => completion(&[value]), + }); + } + return Ok(completion(&[self.lower_scalar(expr)?])); + } + for expr in &values.exprs { + if is_call_shape(expr) { + return Err(self.fail( + span, + "a call in a multi-value return list is outside the completion slice", + )); + } + } + let mut lowered = Vec::with_capacity(values.exprs.len()); + for expr in &values.exprs { + lowered.push(self.lower_scalar(expr)?); + } + Ok(completion(&lowered)) + } + + fn lower_call(&mut self, call: &'a LuaExpr) -> Result<(CallClass, Expr), ParseError> { + let LuaExpr::SuffixChain { base, steps, span } = call else { + return Err(self.fail(expr_span(call), "call shape is not in the completion slice")); + }; + let [ + Suffix::Call { + args: Args::List(list), + .. + }, + ] = steps.as_slice() + else { + return Err(self.fail(*span, "call shape is not in the completion slice")); + }; + match base.as_ref() { + LuaExpr::Name { name, .. } => self.lower_named_call(name, &list.exprs, *span), + LuaExpr::Function { body, .. } => { + let closure = self.lower_function(body, None)?; + let adapted = self.adapt_arguments(&list.exprs, body.params.len(), *span)?; + let call = Expr::ClosureCall(closure, adapted); + Ok((CallClass::Lua, self.wrap_handoff(call, *span)?)) + } + other => Err(self.fail( + expr_span(other), + "call target shape is not in the completion slice", + )), + } + } + + fn lower_named_call( + &mut self, + name: &'a Name, + args: &'a [LuaExpr], + span: Span, + ) -> Result<(CallClass, Expr), ParseError> { + if let Some(binding) = self.use_binding(name) { + let proof = self.proof_for(binding, name.span)?; + let (slot, copy) = self.captured_callee_slot(binding, span)?; + let adapted = self.adapt_arguments(args, proof.arity, span)?; + let call = Expr::LocalCall(slot, Vec::new(), adapted, None); + let value = match copy { + Some(stmt) => Expr::Block { + stmts: vec![stmt], + expr: Box::new(call), + }, + None => call, + }; + return Ok((CallClass::Lua, self.wrap_handoff(value, span)?)); + } + if name.is("pcall") { + return self.lower_pcall(args, span); + } + if name.is("error") { + return self.lower_error(args, span); + } + if HOST_IMPORTS.iter().any(|host| name.is(host)) + || (self.roots && ROOT_GUEST_IMPORTS.iter().any(|host| name.is(host))) + { + return self.lower_host_call(name, args, span); + } + Err(self.fail(name.span, "unsupported global call in the completion slice")) + } + + fn proof_for(&self, binding: usize, span: Span) -> Result { + if self.assigned[binding] { + return Err(ParseError::at_line( + line_of(self.source, span), + "callable binding is reassigned, so its Lua provenance is not provable", + )); + } + if let Some(id) = self.function_body_of_binding[binding] { + let body = self + .body_by_id + .get(&id) + .ok_or_else(|| ParseError::at_line(1, "function binding has no registered body"))?; + return Ok(Proof { + arity: body.params.len(), + }); + } + if self.resolution.bindings[binding].kind == BindingKind::Param { + let mut arity: Option = None; + if self.possible[binding].is_empty() || self.non_lua[binding] { + return Err(ParseError::at_line( + line_of(self.source, span), + "dynamic call target is not a proven Lua callable", + )); + } + for id in &self.possible[binding] { + let body = self + .body_by_id + .get(id) + .ok_or_else(|| ParseError::at_line(1, "argument function has no body"))?; + let candidate = body.params.len(); + match arity { + None => arity = Some(candidate), + Some(existing) if existing == candidate => {} + Some(_) => { + return Err(ParseError::at_line( + line_of(self.source, span), + "dynamic call target arity is not uniquely known in this slice", + )); + } + } + } + return Ok(Proof { + arity: arity.expect("non-empty source set"), + }); + } + Err(ParseError::at_line( + line_of(self.source, span), + "call target is not a Lua function binding or admitted parameter", + )) + } + + fn lower_pcall( + &mut self, + args: &'a [LuaExpr], + span: Span, + ) -> Result<(CallClass, Expr), ParseError> { + let Some((callee, forwarded)) = args.split_first() else { + return Err(self.fail(span, "pcall requires a callable argument")); + }; + let LuaExpr::SuffixChain { .. } = callee else { + // The callee is a plain expression (name or literal), not a call. + return match callee { + LuaExpr::Name { name, .. } => { + let binding = self.use_binding(name).ok_or_else(|| { + self.fail(name.span, "pcall target is not a proven Lua callable") + })?; + let proof = self.proof_for(binding, name.span)?; + let (slot, copy) = self.captured_callee_slot(binding, span)?; + let adapted = self.adapt_arguments(forwarded, proof.arity, span)?; + let call = Expr::LocalCall(slot, Vec::new(), adapted, None); + let value = match copy { + Some(stmt) => Expr::Block { + stmts: vec![stmt], + expr: Box::new(call), + }, + None => call, + }; + Ok((CallClass::Pcall, self.wrap_handoff(value, span)?)) + } + LuaExpr::Function { body, .. } => { + let closure = self.lower_function(body, None)?; + let adapted = self.adapt_arguments(forwarded, body.params.len(), span)?; + let call = Expr::ClosureCall(closure, adapted); + Ok((CallClass::Pcall, self.wrap_handoff(call, span)?)) + } + other => Err(self.fail( + expr_span(other), + "pcall target is not a proven Lua callable", + )), + }; + }; + Err(self.fail(span, "pcall target shape is not in the completion slice")) + } + + fn lower_error( + &mut self, + args: &'a [LuaExpr], + span: Span, + ) -> Result<(CallClass, Expr), ParseError> { + let [payload, level] = args else { + return Err(self.fail(span, "error requires exactly two arguments in this slice")); + }; + if !is_zero_level(level) { + return Err(self.fail( + expr_span(level), + "only error(value, 0) is in the completion slice", + )); + } + let value = self.lower_scalar(payload)?; + Ok((CallClass::Error, value)) + } + + fn lower_host_call( + &mut self, + name: &'a Name, + args: &'a [LuaExpr], + span: Span, + ) -> Result<(CallClass, Expr), ParseError> { + let text = std::str::from_utf8(&name.bytes) + .map_err(|_| self.fail(name.span, "host import name is not UTF-8"))?; + let arity = u8::try_from(args.len()) + .map_err(|_| self.fail(span, "host call has too many arguments"))?; + self.builder + .declare_function(text, Some(arity)) + .map_err(|error| self.fail(name.span, error.message))?; + let signature = vec![TypeSchema::Unknown; args.len()]; + let resolver = self.hosts.ok_or_else(|| { + self.fail( + name.span, + "host call requires the completion test host catalog", + ) + })?; + let resolved = resolver + .resolve(text, &signature) + .map_err(|error| self.fail(name.span, format!("host call resolution: {error}")))?; + let index = self + .builder + .function_index(text) + .ok_or_else(|| self.fail(name.span, "host function was not declared"))?; + let mut lowered = Vec::with_capacity(args.len()); + for arg in args { + lowered.push(self.lower_scalar(arg)?); + } + Ok(( + CallClass::Host, + Expr::Call(index, Vec::new(), lowered, Some(Box::new(resolved)), None), + )) + } + + fn adapt_arguments( + &mut self, + args: &'a [LuaExpr], + arity: usize, + span: Span, + ) -> Result, ParseError> { + if args.len() > arity { + return Err(self.fail( + span, + "extra call arguments are outside the completion slice", + )); + } + let mut lowered = Vec::with_capacity(arity); + for arg in args { + lowered.push(self.lower_scalar(arg)?); + } + while lowered.len() < arity { + lowered.push(Expr::Null); + } + Ok(lowered) + } + + fn lower_scalar(&mut self, expr: &'a LuaExpr) -> Result { + match expr { + LuaExpr::Nil { .. } => Ok(Expr::Null), + LuaExpr::Bool { value, .. } => Ok(Expr::Bool(*value)), + LuaExpr::Number { raw, kind, span } => { + number_literal(raw, *kind).ok_or_else(|| self.fail(*span, "unsupported number")) + } + LuaExpr::String { bytes, span } => String::from_utf8(bytes.clone()) + .map(Expr::String) + .map_err(|_| self.fail(*span, "non-UTF-8 string is outside this slice")), + LuaExpr::Name { name, .. } => { + let binding = self.use_binding(name).ok_or_else(|| { + self.fail( + name.span, + "global name used as a value is outside the completion slice", + ) + })?; + let slot = self.slot_for(binding)?; + if self.binding_is_admitted_callable(binding) { + // A Lua callable is an immutable shared reference. Reading + // it never consumes the binding, whether the value feeds a + // forwarded pcall argument, a host argument, a return, or + // any other value position. Emit the same explicit + // by-value read the callee position uses so the fixed + // Core's capture scan sees a copy, not a move, on every + // capture edge; `ToOwned` compiles to the same plain local + // read as `Var`. + Ok(explicit_value_read(slot)) + } else { + Ok(Expr::Var(slot)) + } + } + LuaExpr::Paren { inner, .. } => self.lower_scalar(inner), + LuaExpr::Function { body, .. } => { + let closure = self.lower_function(body, None)?; + Ok(Expr::Closure(closure)) + } + LuaExpr::Table { fields, .. } => { + if self.roots { + return Err(self.fail( + expr_span(expr), + "table literals are not issued heap tables in the root handoff slice", + )); + } + let mut array = lua_ir_call(BuiltinFunction::ArrayNew.call_index(), Vec::new()); + for field in fields { + let Field::Item { value, .. } = field else { + return Err(self.fail( + expr_span(expr), + "only array items are in the completion slice", + )); + }; + let value = self.lower_scalar(value)?; + array = + lua_ir_call(BuiltinFunction::ArrayPush.call_index(), vec![array, value]); + } + Ok(array) + } + other if is_call_shape(other) => { + // A host call in a value/argument position is an ordinary + // value. Only the host class is admitted here: a Lua callable + // or pcall in scalar position would need a multi-value + // decision that this slice does not make. + let (class, value) = self.lower_call(other)?; + match class { + CallClass::Host => Ok(value), + _ => Err(self.fail( + expr_span(other), + "a Lua callable call in scalar value position is outside the completion slice", + )), + } + } + other => Err(self.fail( + expr_span(other), + "expression is not in the completion slice", + )), + } + } + + // ---- small helpers ---------------------------------------------------- + + fn fail(&self, span: Span, message: impl Into) -> ParseError { + ParseError::at_line(line_of(self.source, span), message) + } + + fn line(&self, span: Span) -> u32 { + u32::try_from(line_of(self.source, span)).unwrap_or(u32::MAX) + } +} + +fn block(stmts: Vec, expr: Expr) -> Expr { + if stmts.is_empty() { + expr + } else { + Expr::Block { + stmts, + expr: Box::new(expr), + } + } +} + +fn lua_ir_call(index: u16, args: Vec) -> Expr { + Expr::Call(index, Vec::new(), args, None, None) +} + +/// One non-consuming by-value read of an immutable Lua callable slot. The +/// fixed Core's availability and capture classification treat `ToOwned` as an +/// explicit copy and a bare `Var` as an implicit read that can move a movable +/// captured binding; codegen compiles both to the same plain local read. +fn explicit_value_read(slot: LocalSlot) -> Expr { + Expr::ToOwned(Box::new(Expr::Var(slot))) +} + +fn packed_array(values: Vec) -> Expr { + values.into_iter().fold( + lua_ir_call(BuiltinFunction::ArrayNew.call_index(), Vec::new()), + |array, value| lua_ir_call(BuiltinFunction::ArrayPush.call_index(), vec![array, value]), + ) +} + +fn completion(values: &[Expr]) -> Expr { + let mut all = Vec::with_capacity(values.len() + 1); + all.push(Expr::Bool(true)); + all.extend(values.iter().cloned()); + packed_array(all) +} + +fn completion_error(value: Expr) -> Expr { + packed_array(vec![Expr::Bool(false), value]) +} + +fn pcall_tail_completion(sequence: Expr) -> Expr { + lua_ir_call( + BuiltinFunction::Concat.call_index(), + vec![completion(&[]), sequence], + ) +} + +fn status_of(slot: LocalSlot) -> Expr { + lua_ir_call( + BuiltinFunction::Get.call_index(), + vec![Expr::Var(slot), Expr::Int(0)], + ) +} + +/// Reads a completion slot only when it exists. The bounds check is a Core +/// branch, so the `get` call is evaluated lazily and a zero-return completion +/// never reaches the out-of-bounds host error. +fn guarded_get(slot: LocalSlot, index: i64) -> Expr { + let length = lua_ir_call(BuiltinFunction::Len.call_index(), vec![Expr::Var(slot)]); + Expr::IfElse { + condition: Box::new(Expr::Gt(Box::new(length), Box::new(Expr::Int(index)))), + then_expr: Box::new(lua_ir_call( + BuiltinFunction::Get.call_index(), + vec![Expr::Var(slot), Expr::Int(index)], + )), + else_expr: Box::new(Expr::Null), + } +} + +fn is_call_shape(expr: &LuaExpr) -> bool { + let LuaExpr::SuffixChain { steps, .. } = expr else { + return false; + }; + matches!( + steps.as_slice(), + [Suffix::Call { + args: Args::List(_), + .. + }] + ) +} + +fn function_literal(expr: &LuaExpr) -> Option<&FuncBody> { + match expr { + LuaExpr::Function { body, .. } => Some(body), + _ => None, + } +} + +fn is_zero_level(expr: &LuaExpr) -> bool { + matches!( + expr, + LuaExpr::Number { + raw, + kind: super::ast::NumberKind::Integer, + .. + } if raw == "0" + ) +} + +fn number_literal(raw: &str, kind: super::ast::NumberKind) -> Option { + use super::ast::NumberKind; + match kind { + NumberKind::Integer => raw.parse::().ok().map(Expr::Int), + NumberKind::HexInteger => i64::from_str_radix(raw.trim_start_matches("0x"), 16) + .ok() + .map(Expr::Int), + NumberKind::Float | NumberKind::HexFloat => raw.parse::().ok().map(Expr::Float), + _ => None, + } +} + +fn stmt_span(stmt: &LuaStmt) -> Span { + match stmt { + LuaStmt::Empty { span } + | LuaStmt::Do { span, .. } + | LuaStmt::While { span, .. } + | LuaStmt::Repeat { span, .. } + | LuaStmt::If { span, .. } + | LuaStmt::NumericFor { span, .. } + | LuaStmt::GenericFor { span, .. } + | LuaStmt::Local { span, .. } + | LuaStmt::LocalFunction { span, .. } + | LuaStmt::Function { span, .. } + | LuaStmt::Assign { span, .. } + | LuaStmt::CompoundAssign { span, .. } + | LuaStmt::Call { span, .. } + | LuaStmt::Label { span, .. } + | LuaStmt::Goto { span, .. } + | LuaStmt::Break { span } + | LuaStmt::Continue { span } + | LuaStmt::Return { span, .. } => *span, + } +} + +fn expr_span(expr: &LuaExpr) -> Span { + match expr { + LuaExpr::Nil { span } + | LuaExpr::Bool { span, .. } + | LuaExpr::Number { span, .. } + | LuaExpr::String { span, .. } + | LuaExpr::Vararg { span } + | LuaExpr::Name { span, .. } + | LuaExpr::Paren { span, .. } + | LuaExpr::Unary { span, .. } + | LuaExpr::Binary { span, .. } + | LuaExpr::BinaryChain { span, .. } + | LuaExpr::Ternary { span, .. } + | LuaExpr::SuffixChain { span, .. } + | LuaExpr::Function { span, .. } + | LuaExpr::ShortFunction { span, .. } + | LuaExpr::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 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/number.rs b/src/frontends/lua/number.rs new file mode 100644 index 0000000..7f6404b --- /dev/null +++ b/src/frontends/lua/number.rs @@ -0,0 +1,378 @@ +//! 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 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 +//! 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 +//! 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 +//! 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::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)] +pub(crate) struct ClassifiedNumber { + expr: Expr, +} + +impl ClassifiedNumber { + pub(crate) fn literal(value: f64) -> Self { + Self { + expr: Expr::Float(value), + } + } + + pub(crate) fn neg(self) -> Self { + Self { + expr: Expr::Neg(Box::new(self.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) -> Self { + Self { + expr: Expr::Sub(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) -> Self { + Self { + expr: Expr::Div(Box::new(self.expr), Box::new(rhs.expr)), + } + } + + 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)), + }, + } + } +} + +/// 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, + 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 + } + + 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 + /// 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(ClassifiedNumber { + expr: Expr::Block { + stmts: vec![ + bind_temp(lhs_slot, lhs.into_expr()), + bind_temp(rhs_slot, rhs.into_expr()), + ], + expr: Box::new(remainder), + }, + }) + } + + /// 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. + /// + /// 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.into_expr())); + Ok(ClassifiedNumber { + expr: Expr::Var(slot), + }) + } + + /// 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 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() { + 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) + .ok_or_else(|| ParseError::new("lua number temp ordinal overflow"))?; + } + } +} + +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/src/frontends/lua/number_source.rs b/src/frontends/lua/number_source.rs new file mode 100644 index 0000000..00f10e8 --- /dev/null +++ b/src/frontends/lua/number_source.rs @@ -0,0 +1,560 @@ +//! 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. 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. 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::{BitwiseBinary, ClassifiedNumber, NumberLowering}; +use super::resolve::Resolution; +use vm::compiler::HostCallResolver; +use vm::{FrontendIr, LocalIrBuilder, ParseError, Stmt as CoreStmt}; + +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)] +pub(crate) enum NumberSourceError { + Syntax { message: String }, + 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, + 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 { + message: format!("resolve: {error:?}"), + }); + } + let mut builder = LocalIrBuilder::new(); + let mut stmts = Vec::new(); + let name_probes = { + let mut lowering = NumberLowering::new(&mut builder); + let mut env = NumberSource { + locals: Vec::new(), + resolver, + }; + 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 + .iter() + .map(|(name, _)| name.clone()) + .collect(); + let logical_slots = ir.locals; + Ok(LoweredNumberChunk { + ir, + logical_slots, + binding_names, + name_probes, + }) +} + +fn lower_stmt( + source: &str, + stmt: &Stmt, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + env: &mut NumberSource<'_>, +) -> 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)?; + 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(UnsupportedReason::Statement)), + } +} + +fn lower_local( + source: &str, + span: Span, + names: &[LocalName], + values: &ExprList, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + env: &mut NumberSource<'_>, +) -> Result<(), NumberSourceError> { + if names.len() != 1 || values.exprs.len() != 1 { + 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(UnsupportedReason::LocalName))?; + let bound = lowering + .bind_named(text, lowered, line_of(source, span), stmts) + .map_err(kernel_error)?; + env.locals.push(ProvenLocal { + name: name.bytes.clone(), + value: bound, + }); + Ok(()) +} + +fn lower_expr( + source: &str, + expr: &Expr, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + env: &NumberSource<'_>, +) -> Result { + match expr { + Expr::Number { raw, kind, .. } => lower_number(raw, *kind), + 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, &env.resolver) + } + Expr::BinaryChain { base, steps, .. } => { + let mut acc = lower_expr(source, base, lowering, stmts, env)?; + 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, &env.resolver)?; + } + Ok(acc) + } + _ => Err(unsupported(UnsupportedReason::Expression)), + } +} + +fn lower_unary( + op: UnOp, + expr: &Expr, + source: &str, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + env: &NumberSource<'_>, +) -> Result { + 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)?; + if op == UnOp::Neg { + Ok(inner.neg()) + } else { + lowering + .bitwise_not(&env.resolver, inner) + .map_err(kernel_error) + } +} + +fn apply( + op: BinOp, + lhs: ClassifiedNumber, + rhs: ClassifiedNumber, + lowering: &mut NumberLowering<'_>, + stmts: &mut Vec, + resolver: &HostCallResolver<'_>, +) -> Result { + let rhs = lowering.materialize(rhs, stmts).map_err(kernel_error)?; + 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 { + let value = match kind { + 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 | NumberKind::HexInteger => parse_hex_literal(raw)?, + NumberKind::Integer | NumberKind::Float => parse_decimal(raw)?, + NumberKind::Binary => parse_binary_literal(raw)?, + }; + if value.is_nan() { + return Err(unsupported(UnsupportedReason::LiteralForm)); + } + 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(UnsupportedReason::LiteralForm)) +} + +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; + 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'1' => byte - b'0', + _ => return Err(unsupported(UnsupportedReason::LiteralForm)), + }; + let scaled = magnitude + .checked_mul(2) + .ok_or_else(|| unsupported(UnsupportedReason::LiteralForm))?; + magnitude = scaled + .checked_add(u64::from(digit)) + .ok_or_else(|| unsupported(UnsupportedReason::LiteralForm))?; + } + Ok(magnitude as f64) +} + +/// One round-to-nearest-even from the full hex significand onto binary64. +/// +/// The scan keeps 64 bits of magnitude and one sticky flag. That is enough for +/// a 53-bit significand plus a guard bit; every later digit folds into sticky. +/// Extra space stays constant. The exponent is applied as a bit place, not as +/// a second floating multiply. +fn parse_hex_literal(raw: &str) -> 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() + .find(|local| local.name == name) + .map(|local| local.value.clone()) + .ok_or_else(|| unsupported(UnsupportedReason::UnprovenName)) +} + +fn single_proven(values: &ExprList) -> Result<&Expr, NumberSourceError> { + if values.exprs.len() == 1 { + Ok(&values.exprs[0]) + } else { + Err(unsupported(UnsupportedReason::NotSingle)) + } +} + +fn kernel_error(error: ParseError) -> NumberSourceError { + NumberSourceError::CompileUnsupported { + reason: UnsupportedReason::Kernel { + message: error.message, + }, + } +} + +fn unsupported(reason: UnsupportedReason) -> NumberSourceError { + NumberSourceError::CompileUnsupported { reason } +} + +fn not_float(kind: NumberKind) -> 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/src/frontends/lua/parser.rs b/src/frontends/lua/parser.rs new file mode 100644 index 0000000..79b7b17 --- /dev/null +++ b/src/frontends/lua/parser.rs @@ -0,0 +1,1100 @@ +//! 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, + level: u32, +} + +const LJ_MAX_XLEVEL: u32 = 200; + +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, + level: 0, + }; + 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 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) + } + + 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 { + 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 + } else { + stmts.last().map(stmt_span).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]; + 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")); + } + 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::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'?')) { + self.synlevel_begin()?; + let then_expr = self.expr(Flags { + nores: false, + nocolon: true, + nonav: false, + })?; + 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, + 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 { + 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 base = self.unop(flags)?; + while let Some((op, left_pri, right_pri)) = binop_of(self.kind()) { + if left_pri <= limit { + break; + } + 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(base) + } + + 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 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 base_span = expr.span(); + let mut steps = Vec::new(); + 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()?; + 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 { + 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()?; + 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()?; + 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()?; + steps.push(Suffix::Field { + span: base_span.cover(field.span), + name: field, + nav, + }); + } else { + break; + } + } + Ok(Primary { + expr: finish_suffix_chain(expr, steps), + 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 { + 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::SuffixChain { + span, + 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, + 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..88b5a06 --- /dev/null +++ b/src/frontends/lua/resolve.rs @@ -0,0 +1,972 @@ +//! 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. +//! +//! 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::*; + +/// 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, + 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, + /// 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. + /// + /// The control candidate checks this after `errors` and before lowering. + /// This does not change the production LuaPlugin entry. + pub limits: 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 NameUse { + pub span: Span, + pub binding: Option, + pub function_id: u32, +} + +#[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, + }, +} + +#[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, + 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, + hidden_base: u32, + labels: Vec, + jumps: Vec, +} + +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 { + 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(), + uses: Vec::new(), + errors: Vec::new(), + limits: 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(), + hidden: 0, + upvalues: Vec::new(), + }); + self.enter_scope(); + } + + 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(), + }); + } + + 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); + } + + 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) { + 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; + } + 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 && 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], + ) { + self.charge_local(name.span); + 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 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() + .rev() + .find(|local| local.name == name) + .map(|local| local.binding_index) + } + + /// 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); + self.account_upvalue(name.span, binding, function_id); + self.resolution.uses.push(NameUse { + span: name.span, + binding, + 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, + 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 + && 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); + let scope = self.scopes.len() - 1; + self.reject_continues_into_locals(scope); + 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.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); + } + Stmt::GenericFor { + names, + iters, + body, + 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, &[]); + } + 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]); + } 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()); + } + 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 { name, .. } => self.note_name(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::BinaryChain { base, steps, .. } => { + self.walk_expr(base); + for step in steps { + self.walk_expr(&step.expr); + } + } + Expr::Ternary { + cond, + then_expr, + else_expr, + .. + } => { + self.walk_expr(cond); + self.walk_expr(then_expr); + self.walk_expr(else_expr); + } + 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::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, stmt) in block.stmts.iter().enumerate() { + if !matches!(stmt, 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/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 { diff --git a/tests/compiler/compiler_lua_call_boundary_tests.rs b/tests/compiler/compiler_lua_call_boundary_tests.rs new file mode 100644 index 0000000..b23c2a3 --- /dev/null +++ b/tests/compiler/compiler_lua_call_boundary_tests.rs @@ -0,0 +1,516 @@ +//! Core-level call-boundary witness for the Lua protected-call preflight. +//! +//! These tests use only the locked Core public API. Each arm runs one VM whose +//! root frame calls a real guest `parent`; `parent` holds a real guest script +//! callable in its own frame and reaches the child frame through the one +//! `CallValue` instruction decoded from the program's real instruction +//! boundaries. No second VM, no host-side re-entry, and no Lua frontend is +//! involved. +//! +//! The guest inputs are the exact RSS fixtures copied from the preflight +//! `next-run/` directory. They are linked with `include_str!` so the witness +//! stays anchored to the exact original bytes. +//! +//! The first real compiler runs on those untouched bytes failed in this order: +//! +//! 1. Untouched fixture: `Parse(ParseError { message: "expected parameter +//! name", ... })` at the closing `)` of `parent` (the reported line and +//! span differ per arm; the omitted arm reports line 18, span 457..458). +//! Locked Core accepts no trailing comma after the final parameter. +//! 2. Only that comma removed: `Parse(ParseError { message: "function header +//! changed while parsing 'parent'" })`. The predeclaration arity scan +//! counts the comma inside the callable result type `[bool, [int]]` as a +//! parameter separator. +//! 3. Callable result widened to `array` and the trailing comma removed: +//! `Parse(ParseError { message: "unknown function 'len'" })`. `len` is an +//! ordinary builtin without a source-level name in this compile mode; the +//! language postfix form is `.length`. +//! 4. `len(r)` changed to `r.length`: `Parse(ParseError { message: "local 'r' +//! is partially moved; access remaining fields/elements directly or +//! reinitialize moved children before using 'r' as a whole" })`. Reading +//! `r[0]` and then returning the whole `r` is rejected by strict ownership. +//! +//! The rewrite below is therefore syntax-only and keeps every runtime value +//! and control-flow decision identical: +//! +//! - delete the one trailing parameter comma; +//! - annotate `parent`'s callable parameter and the root callable binding as +//! `fn([int]) -> array` instead of `fn([int]) -> [bool, [int]]` (the callee +//! prototype still carries the exact `[bool, [int]]` result; the runtime +//! callable schema check only requires a callable value); +//! - use the language postfix `r.length` for the length builtin; +//! - read `tag = r[0]` and `payload = r[1]` and return those elements instead +//! of the partially moved transport array. The guest therefore still reads +//! the completion tag and the exact transport length itself, and the payload +//! keeps its original Core array identity. +//! +//! Each replacement below asserts that its exact before-pattern occurs once, +//! so the witness cannot silently drift from the original fixtures. +//! +//! At `mark(1)` the host also binds the observed call to the actual `held` +//! argument, not merely to some callable in the parent frame: +//! +//! - the caller is the frame immediately below the active callee; +//! - the caller prototype's `parameter_slots[0]` selects one exact local slot; +//! - that slot is read with checked arithmetic inside the caller's own +//! `local_base..local_base + local_count` frame range; +//! - the value must be a `Value::Callable` whose prototype is the prototype of +//! the frame that is actually executing, and whose prototype target is a +//! script function. +//! +//! No other slot is searched, so an unrelated callable cannot satisfy the +//! witness. + +use std::sync::{Arc, Mutex}; + +use vm::vm::{VmExecutionFrameSnapshot, VmFrameContinuation}; +use vm::{CallOutcome, CallReturn, CallableTarget, HostFunction, Value, Vm, VmError, VmStatus}; + +const GUEST_SUCCESS: &str = include_str!("fixtures/core_active_protected_call/guest-success.rss"); +const GUEST_ERROR: &str = include_str!("fixtures/core_active_protected_call/guest-error.rss"); +const GUEST_OMITTED: &str = include_str!("fixtures/core_active_protected_call/guest-omitted.rss"); +const GUEST_HOST_FAULT: &str = + include_str!("fixtures/core_active_protected_call/guest-host-fault.rss"); + +#[derive(Clone, Debug, PartialEq, Eq)] +struct Mark { + phase: i64, + frame_len: usize, + call_depth: usize, + last_prototype: Option, + last_return_ip: Option, + parent_prototype: Option, + held_parameter: HeldParameterWitness, +} + +/// Exact observation of the active parent frame's first declared parameter. +/// +/// Only `parameter_slots[0]` of the caller prototype is read. The absolute +/// index is formed with checked arithmetic and then read with `get`, so both +/// the relative slot check and the concrete local-range bounds check are +/// recorded instead of assumed. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct HeldParameterWitness { + caller_prototype: Option, + declared_slot: Option, + caller_local_base: Option, + caller_local_count: Option, + slot_inside_caller_frame: bool, + read_within_bounds: bool, + value_is_callable: bool, + callable_prototype: Option, + callable_is_script_function: bool, + callee_prototype: Option, +} + +struct MarkHost { + log: Arc>>, +} + +impl HostFunction for MarkHost { + fn call(&mut self, vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::Int(phase)] = args else { + return Err(VmError::HostError("mark expects one int".to_string())); + }; + let frames = vm.execution_frames(); + let parent = frames.iter().rev().nth(1); + // The strict parent-parameter binding belongs to the callee marker: at + // `mark(1)` the parent is one frame below the active callee. + let held_parameter = if *phase == 1 { + observe_held_parameter(vm, &frames) + } else { + HeldParameterWitness::default() + }; + let mark = Mark { + phase: *phase, + frame_len: frames.len(), + call_depth: vm.call_depth(), + last_prototype: frames.last().and_then(|frame| frame.prototype_id), + last_return_ip: frames.last().and_then(|frame| match &frame.continuation { + VmFrameContinuation::ResumeBytecode { return_ip } => Some(*return_ip), + _ => None, + }), + parent_prototype: parent.and_then(|frame| frame.prototype_id), + held_parameter, + }; + self.log.lock().expect("mark log").push(mark); + Ok(CallOutcome::Return(CallReturn::one(Value::Int(*phase)))) + } +} + +/// Reads the caller's declared first parameter and records the exact callee +/// binding for the caller's strict assertions. +/// +/// The caller is the frame immediately below the active frame. The slot comes +/// from the caller prototype itself (`parameter_slots[0]`), is required to be +/// inside the caller's declared local count, and is then read with +/// `checked_add` plus a bounds-checked slice lookup. The value must be a +/// `Value::Callable` whose prototype is the executing callee frame's +/// prototype, and whose prototype target must be a script function. No other +/// slot is scanned. +fn observe_held_parameter(vm: &Vm, frames: &[VmExecutionFrameSnapshot]) -> HeldParameterWitness { + let (Some(callee), Some(caller)) = (frames.last(), frames.iter().rev().nth(1)) else { + return HeldParameterWitness::default(); + }; + let mut witness = HeldParameterWitness { + caller_prototype: caller.prototype_id, + caller_local_base: Some(caller.local_base), + caller_local_count: Some(caller.local_count), + callee_prototype: callee.prototype_id, + ..HeldParameterWitness::default() + }; + let program = vm.program(); + let Some(prototype) = caller + .prototype_id + .and_then(|id| program.callable_prototypes.get(id as usize)) + else { + return witness; + }; + let Some(&declared_slot) = prototype.parameter_slots.first() else { + return witness; + }; + witness.declared_slot = Some(declared_slot); + let relative = usize::from(declared_slot); + if relative >= caller.local_count { + return witness; + } + witness.slot_inside_caller_frame = true; + let Some(absolute) = caller.local_base.checked_add(relative) else { + return witness; + }; + let Some(value) = vm.locals().get(absolute) else { + return witness; + }; + witness.read_within_bounds = true; + let Value::Callable(callable) = value else { + return witness; + }; + witness.value_is_callable = true; + witness.callable_prototype = Some(callable.prototype_id); + witness.callable_is_script_function = matches!( + program + .callable_prototypes + .get(callable.prototype_id as usize) + .map(|prototype| prototype.target), + Some(CallableTarget::ScriptFunction(_)) + ); + witness +} + +/// Rewrites the exact fixture into the minimal syntax accepted by this Core pin. +/// +/// The original bytes stay in the fixture; every edit is asserted to target +/// exactly one site, and no template is kept alongside the fixture. +fn rewrite_fixture(raw: &str) -> String { + let mut rewritten = raw.to_string(); + for (before, after) in [ + // Locked Core rejects a trailing comma after the final parameter. + (" do_call: bool,\n", " do_call: bool\n"), + // The predeclaration arity scan mistakes the comma in the callable + // result tuple for a parameter separator. + ( + " held: fn([int]) -> [bool, [int]],\n", + " held: fn([int]) -> array,\n", + ), + ( + "let held: fn([int]) -> [bool, [int]] = ", + "let held: fn([int]) -> array = ", + ), + // `len` is an ordinary builtin without a source-level name here. + ("len(r)", "r.length"), + // Reading r[0] and returning the whole r violates strict ownership. + ( + ") -> [[bool, [int]], int, int, bool, [int]] {", + ") -> [bool, [int], int, int, [int]] {", + ), + ( + " let tag = r[0];\n", + " let tag = r[0];\n let payload = r[1];\n", + ), + ( + " [r, arity, marker, tag, t]\n", + " [tag, payload, arity, marker, t]\n", + ), + ] { + assert_eq!( + rewritten.matches(before).count(), + 1, + "rewrite target must occur exactly once: {before:?}" + ); + rewritten = rewritten.replace(before, after); + } + rewritten +} + +/// Decodes the whole instruction stream with `OpCode::operand_len()` and +/// requires exactly one `CallValue` site, owned by a script prototype. +fn call_site(program: &vm::Program) -> (u32, usize) { + let code = &program.code; + let mut ip = 0usize; + let mut sites = Vec::new(); + while ip < code.len() { + let op = vm::OpCode::try_from(code[ip]).expect("invalid opcode"); + let next = ip + 1 + op.operand_len(); + assert!(next <= code.len(), "truncated instruction at {ip}"); + if op == vm::OpCode::CallValue { + assert_eq!(code[ip + 1], 1, "held(t) must pass exactly one argument"); + let owners: Vec<_> = program + .function_regions + .iter() + .filter(|region| region.start_ip as usize <= ip && next <= region.end_ip as usize) + .collect(); + let [owner] = owners.as_slice() else { + panic!("expected a unique caller region for CallValue at {ip}"); + }; + sites.push(( + owner + .prototype_id + .expect("held(t) must be inside the parent prototype"), + next, + )); + } + ip = next; + } + let [site] = sites.as_slice() else { + panic!("expected one decoded CallValue site; got {sites:?}"); + }; + *site +} + +fn assert_executed_site(vm: &Vm, log: &Mutex>, invoked: bool) { + let (caller, return_ip) = call_site(vm.program()); + let records = log.lock().expect("mark log"); + assert!( + records + .iter() + .filter(|mark| mark.phase != 1) + .all(|mark| mark.last_prototype == Some(caller)), + "outer markers must run in the parent frame: {records:?}" + ); + let callees: Vec<_> = records.iter().filter(|mark| mark.phase == 1).collect(); + if invoked { + let [callee] = callees.as_slice() else { + panic!("expected one callee marker; got {callees:?}"); + }; + assert_eq!( + callee.last_return_ip, + Some(return_ip), + "the executed callee must resume at the decoded CallValue successor" + ); + assert_ne!( + callee.last_prototype, + Some(caller), + "the callee frame must not be the parent frame" + ); + assert_eq!( + callee.parent_prototype, + Some(caller), + "the active parent frame must be one below the callee" + ); + let held = &callee.held_parameter; + assert_eq!( + held.caller_prototype, + Some(caller), + "the held argument must be read from the parent frame: {held:?}" + ); + assert_eq!( + held.callee_prototype, callee.last_prototype, + "the witness must compare against the executing callee frame: {held:?}" + ); + assert_eq!( + held.declared_slot, + Some(0), + "the Core pin must declare the first parameter in slot 0: {held:?}" + ); + assert!( + held.slot_inside_caller_frame, + "the declared parameter slot must be inside the parent frame: {held:?}" + ); + assert!( + held.read_within_bounds, + "the bounds-checked parent local read must succeed: {held:?}" + ); + assert!( + held.value_is_callable, + "the first declared parameter must hold a real callable: {held:?}" + ); + assert_eq!( + held.callable_prototype, callee.last_prototype, + "the held callable must be the executing callee, not any other callable: {held:?}" + ); + assert!( + held.callable_is_script_function, + "the held callable prototype target must be a script function: {held:?}" + ); + assert_eq!(callee.frame_len, 3, "root + parent + callee"); + } else { + assert!(callees.is_empty(), "the omitted arm must not call"); + } +} + +fn build_guest(raw: &str) -> (Vm, Arc>>) { + let source = rewrite_fixture(raw); + let compiled = vm::compile_source(&source).expect("preflight source must compile"); + let imports: Vec<_> = compiled + .program + .imports + .iter() + .filter(|import| import.name == "mark") + .collect(); + let [mark] = imports.as_slice() else { + panic!("expected one mark import; got {imports:?}"); + }; + assert_eq!(mark.arity, 1); + let _ = call_site(&compiled.program); + let mut vm = Vm::new(compiled.program); + vm.set_jit_config(vm::JitConfig { + enabled: false, + hot_loop_threshold: 0, + max_trace_len: 0, + }); + let log = Arc::new(Mutex::new(Vec::new())); + vm.bind_function( + "mark", + Box::new(MarkHost { + log: Arc::clone(&log), + }), + ); + (vm, log) +} + +fn unpack(vm: &Vm) -> (bool, i64, i64, Value, Value) { + let [top] = vm.stack() else { + panic!("expected exactly one root result"); + }; + let Value::Array(result) = top else { + panic!("root result must be the outer array"); + }; + assert_eq!(result.len(), 5, "outer result arity"); + let Value::Bool(tag) = &result[0] else { + panic!("element 0 must be the guest-read completion tag"); + }; + let Value::Array(_) = &result[1] else { + panic!("element 1 must be the guest-read payload"); + }; + let Value::Int(arity) = &result[2] else { + panic!("element 2 must be the guest-read transport arity"); + }; + let Value::Int(marker) = &result[3] else { + panic!("element 3 must be int"); + }; + // `same_array` answers false for a non-array, so the comparator `t` must + // first be proven to be an array; otherwise the omitted arm's payload + // inequality would pass without comparing two arrays. + let Value::Array(_) = &result[4] else { + panic!("element 4 must be the comparator array t"); + }; + (*tag, *arity, *marker, result[1].clone(), result[4].clone()) +} + +fn same_array(left: &Value, right: &Value) -> bool { + match (left, right) { + (Value::Array(left), Value::Array(right)) => Arc::ptr_eq(left, right), + _ => false, + } +} + +fn phases(log: &Arc>>) -> Vec { + log.lock() + .expect("mark log") + .iter() + .map(|mark| mark.phase) + .collect() +} + +fn frame_lens(log: &Arc>>) -> Vec { + log.lock() + .expect("mark log") + .iter() + .map(|mark| mark.frame_len) + .collect() +} + +#[test] +fn core_active_protected_call_preflight_success_data_transport() { + let (mut vm, log) = build_guest(GUEST_SUCCESS); + assert_eq!(vm.run().expect("success arm must halt"), VmStatus::Halted); + let (tag, arity, marker, payload, original) = unpack(&vm); + assert!(tag, "success tag"); + assert_eq!(arity, 2, "exactly two transport values, read by the guest"); + assert_eq!(marker, 1, "parent continued after the call"); + assert!( + same_array(&payload, &original), + "payload must be the same Core array object as the parent's t" + ); + assert_eq!(phases(&log), vec![0, 1, 2]); + assert_eq!(frame_lens(&log), vec![2, 3, 2]); + assert_executed_site(&vm, &log, true); + let records = log.lock().expect("mark log"); + assert_eq!(records[0].last_prototype, records[2].last_prototype); + assert_ne!(records[1].last_prototype, records[0].last_prototype); + assert_eq!(records[1].frame_len, records[0].frame_len + 1); +} + +#[test] +fn core_active_protected_call_preflight_explicit_error_is_data() { + let (mut vm, log) = build_guest(GUEST_ERROR); + assert_eq!( + vm.run() + .expect("explicit error payload must not be a VmError"), + VmStatus::Halted + ); + let (tag, arity, marker, payload, original) = unpack(&vm); + assert!(!tag, "explicit error tag"); + assert_eq!(arity, 2, "error transport keeps exact arity"); + assert_eq!(marker, 1, "parent continued after the error payload"); + assert!( + same_array(&payload, &original), + "error payload keeps the original object" + ); + assert_eq!(phases(&log), vec![0, 1, 2]); + assert_eq!(frame_lens(&log), vec![2, 3, 2]); + assert_executed_site(&vm, &log, true); +} + +#[test] +fn core_active_protected_call_preflight_omitted_call_has_no_callee_marker() { + let (mut vm, log) = build_guest(GUEST_OMITTED); + assert_eq!(vm.run().expect("omitted arm must halt"), VmStatus::Halted); + let (tag, arity, marker, payload, original) = unpack(&vm); + assert!(!tag); + assert_eq!(arity, 2); + assert_eq!(marker, 0, "the callable must not run"); + assert!( + !same_array(&payload, &original), + "the omitted call cannot deliver the original object" + ); + assert_eq!(phases(&log), vec![0, 2]); + assert_eq!(frame_lens(&log), vec![2, 2]); + assert_executed_site(&vm, &log, false); +} + +#[test] +fn core_active_protected_call_preflight_host_error_is_not_a_payload() { + let (mut vm, log) = build_guest(GUEST_HOST_FAULT); + let error = vm.run().expect_err("a real host error must abort the run"); + assert!( + matches!(error, VmError::HostError(ref message) if message == "assertion failed"), + "unexpected error: {error:?}" + ); + assert_eq!(phases(&log), vec![0, 1], "mark(2) must not run"); + assert_eq!( + frame_lens(&log), + vec![2, 3], + "the callee frame stays active" + ); + assert!( + vm.execution_frames().len() >= 3, + "the callee frame is not unwound by an error: {:?}", + vm.execution_frames() + ); + assert_executed_site(&vm, &log, true); + assert!( + !vm.is_reusable(), + "an errored active-frame VM is not reusable" + ); +} diff --git a/tests/compiler/compiler_lua_completion_tests.rs b/tests/compiler/compiler_lua_completion_tests.rs new file mode 100644 index 0000000..ae29902 --- /dev/null +++ b/tests/compiler/compiler_lua_completion_tests.rs @@ -0,0 +1,1402 @@ +//! Dynamic Lua completion transport through the real `.lua` file entry. +//! +//! Every input is a real Lua 5.2-compat file under +//! `tests/fixtures/luajit/completion/`. The candidate plugin feeds the real +//! lexer/parser/resolver, then lowers each Lua function to the private +//! completion `[Bool, ...values]`, compiles through the fixed Core and runs one +//! interpreter VM (JIT disabled). No LuaHeap is involved; the payload table is +//! compared by Core array identity only. `mark`, `note`, and `fault` are real +//! host functions injected by the test. +//! +//! The default production `LuaPlugin` still runs the line lowerer and does not +//! support these chunks. That legacy rejection is recorded as the first +//! unsupported layer for the same real input; a compile-time rejection is not +//! counted as a business RED. The candidate path then executes the same file +//! and the behavioral assertions are the real RED/GREEN boundary. + +#[allow(dead_code)] +#[path = "../../src/frontends/lua/ast.rs"] +mod ast; +#[path = "../../src/frontends/lua/lexer.rs"] +mod lexer; +#[path = "../../src/frontends/lua/lower.rs"] +mod lower; +#[path = "../../src/frontends/lua/parser.rs"] +mod parser; +#[path = "../../src/frontends/lua/resolve.rs"] +mod resolve; + +#[path = "compiler_lua_completion_tests/root_handoff.rs"] +mod root_handoff; + +#[path = "compiler_lua_completion_tests/active_finalizer.rs"] +mod active_finalizer; + +#[path = "compiler_lua_completion_tests/callable_carrier.rs"] +mod callable_carrier; + +#[path = "compiler_lua_completion_tests/callable_raw_call.rs"] +mod callable_raw_call; + +#[path = "compiler_lua_completion_tests/active_typed_resource_transport.rs"] +mod active_typed_resource_transport; + +use std::path::PathBuf; +use std::sync::{Arc, Mutex, OnceLock}; + +use vm::compiler::HostCallResolver; +use vm::vm::{VmExecutionFrameSnapshot, VmFrameContinuation}; +use vm::{ + CallOutcome, CallReturn, CompileSourceFileOptions, FrontendImportSyntax, FrontendIr, + HostApiBuilder, HostApiCatalog, HostFunction, HostFunctionSchema, HostParamSchema, + HostTypeSchema, OpCode, ParseError, Program, SourceError, SourceFlavor, SourcePathError, + SourcePlugin, Value, Vm, VmError, VmStatus, +}; + +const FUEL_BUDGET: u64 = 1_000_000; +const FUEL_CHECK_INTERVAL: u32 = 1; + +const DEFAULT_ENTRY_FIXTURES: &[&str] = &[ + "argument-order.lua", + "dynamic-error.lua", + "dynamic-success.lua", + "dynamic-false-table.lua", + "host-return-false.lua", + "ordinary-zero.lua", + "ordinary-one-nil.lua", + "protected-zero.lua", + "protected-one-nil.lua", + "scalar-zero.lua", + "host-fault.lua", + "uncaught-error.lua", +]; + +struct CompletionLuaPlugin; + +static COMPLETION_LUA_PLUGIN: CompletionLuaPlugin = CompletionLuaPlugin; + +impl SourcePlugin for CompletionLuaPlugin { + 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 { + let resolver = HostCallResolver::new(catalog()); + lower::lower_source_with(source, Some(&resolver)) + } +} + +/// Test-only host catalog for the three real host functions the fixtures use. +/// The candidate resolves every host call through this catalog, so the Core +/// module loader never sees them as imported externs. +fn catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = HostApiBuilder::new(); + builder.function(HostFunctionSchema::with_return( + "mark", + vec![HostParamSchema::value("label", HostTypeSchema::String)], + HostTypeSchema::Int, + )); + builder.function(HostFunctionSchema::with_return( + "note", + vec![HostParamSchema::value("value", HostTypeSchema::Unknown)], + HostTypeSchema::Bool, + )); + builder.function(HostFunctionSchema::with_return( + "fault", + Vec::new(), + HostTypeSchema::Unknown, + )); + builder.function(HostFunctionSchema::with_return( + "tick", + vec![HostParamSchema::value("label", HostTypeSchema::String)], + HostTypeSchema::Int, + )); + // Private root-handoff surface. `newtable`/`setchild` are the only + // guest-visible names; the `lua_root_*` calls are compiler-emitted. + builder.function(HostFunctionSchema::with_return( + "newtable", + Vec::new(), + HostTypeSchema::Unknown, + )); + builder.function(HostFunctionSchema::with_return( + "setchild", + vec![ + HostParamSchema::value("original", HostTypeSchema::Unknown), + HostParamSchema::value("child", HostTypeSchema::Unknown), + ], + HostTypeSchema::Unknown, + )); + for (name, arity) in [ + ("lua_root_enter", 1usize), + ("lua_root_handoff", 2), + ("lua_root_formal", 4), + ("lua_root_discard", 3), + ("lua_root_finish", 3), + ] { + builder.function(HostFunctionSchema::with_return( + name, + (0..arity) + .map(|index| { + HostParamSchema::value(format!("arg{index}"), HostTypeSchema::Unknown) + }) + .collect(), + HostTypeSchema::Unknown, + )); + } + Arc::new(builder.build().expect("completion host catalog")) + }) +} + +fn candidate_options() -> CompileSourceFileOptions { + CompileSourceFileOptions::new() + .with_source_plugin(&COMPLETION_LUA_PLUGIN) + .with_host_api_catalog(Arc::clone(catalog())) +} + +fn fixture_path(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("fixtures") + .join("luajit") + .join("completion") + .join(name) +} + +/// Records the first layer at which the default entry refuses each real input. +/// +/// The assertion is only that the default entry refuses the file; the message +/// text is printed, never matched, so this control does not freeze a legacy +/// diagnostic. +#[test] +fn default_entry_records_first_unsupported_layer() { + for name in DEFAULT_ENTRY_FIXTURES { + let path = fixture_path(name); + let result = + vm::compile_source_file_with_options(&path, pd_vm_compat_frontends::compile_options()); + match result { + Ok(_) => panic!("default entry must not support the completion fixture {name}"), + Err(error) => { + let layer = default_entry_layer(&error); + eprintln!( + "LUA_COMPLETION default-entry fixture={name} first-layer={layer} error={error:?}" + ); + } + } + } +} + +/// Coarse first-layer label: parse and compile failures are distinct variants. +/// This is a label, not a text match, and no variant is treated as a +/// behavioral result. +fn default_entry_layer(error: &SourcePathError) -> &'static str { + match error { + SourcePathError::Source(vm::SourceError::Parse(_)) => "parse", + SourcePathError::Source(vm::SourceError::Compile(_)) => "compile", + SourcePathError::SourceWithMap { error, .. } => match error { + vm::SourceError::Parse(_) => "parse", + vm::SourceError::Compile(_) => "compile", + }, + _ => "loader", + } +} + +#[derive(Clone, Debug)] +struct MarkRecord { + label: String, + frame_len: usize, + last_prototype: Option, + last_return_ip: Option, + parent_prototype: Option, + held: HeldParameterWitness, +} + +/// Exact observation of the active parent frame's first declared parameter. +/// +/// Only `parameter_slots[0]` of the caller prototype is read, with checked +/// arithmetic inside the caller frame, exactly like the accepted Core +/// active-parent witness. No other slot is searched. +#[derive(Clone, Debug, Default)] +struct HeldParameterWitness { + caller_prototype: Option, + declared_slot: Option, + slot_inside_caller_frame: bool, + read_within_bounds: bool, + value_is_callable: bool, + callable_prototype: Option, + callable_is_script_function: bool, + callee_prototype: Option, +} + +#[derive(Clone, Default)] +struct Observation { + marks: Arc>>, + seen: Arc>>, + ticks: Arc>>, +} + +struct MarkHost { + marks: Arc>>, + seen: Arc>>, +} + +impl HostFunction for MarkHost { + fn call(&mut self, vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::String(label)] = args else { + return Err(VmError::HostError( + "mark expects one string label".to_string(), + )); + }; + let frames = vm.execution_frames(); + let parent = frames.iter().rev().nth(1); + let record = MarkRecord { + label: label.as_str().to_string(), + frame_len: frames.len(), + last_prototype: frames.last().and_then(|frame| frame.prototype_id), + last_return_ip: frames.last().and_then(|frame| match &frame.continuation { + VmFrameContinuation::ResumeBytecode { return_ip } => Some(*return_ip), + _ => None, + }), + parent_prototype: parent.and_then(|frame| frame.prototype_id), + held: observe_held_parameter(vm, &frames), + }; + let _ = &self.seen; + self.marks.lock().expect("mark log").push(record); + Ok(CallOutcome::Return(CallReturn::one(Value::Int(0)))) + } +} + +fn observe_held_parameter(vm: &Vm, frames: &[VmExecutionFrameSnapshot]) -> HeldParameterWitness { + let (Some(callee), Some(caller)) = (frames.last(), frames.iter().rev().nth(1)) else { + return HeldParameterWitness::default(); + }; + let mut witness = HeldParameterWitness { + caller_prototype: caller.prototype_id, + callee_prototype: callee.prototype_id, + ..HeldParameterWitness::default() + }; + let program = vm.program(); + let Some(prototype) = caller + .prototype_id + .and_then(|id| program.callable_prototypes.get(id as usize)) + else { + return witness; + }; + let Some(&declared_slot) = prototype.parameter_slots.first() else { + return witness; + }; + witness.declared_slot = Some(declared_slot); + let relative = usize::from(declared_slot); + if relative >= caller.local_count { + return witness; + } + witness.slot_inside_caller_frame = true; + let Some(absolute) = caller.local_base.checked_add(relative) else { + return witness; + }; + let Some(value) = vm.locals().get(absolute) else { + return witness; + }; + witness.read_within_bounds = true; + let Value::Callable(callable) = value else { + return witness; + }; + witness.value_is_callable = true; + witness.callable_prototype = Some(callable.prototype_id); + witness.callable_is_script_function = matches!( + program + .callable_prototypes + .get(callable.prototype_id as usize) + .map(|prototype| prototype.target), + Some(vm::CallableTarget::ScriptFunction(_)) + ); + witness +} + +struct NoteHost { + seen: Arc>>, +} + +impl HostFunction for NoteHost { + fn call(&mut self, _vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [value] = args else { + return Err(VmError::HostError("note expects one value".to_string())); + }; + *self.seen.lock().expect("seen payload") = Some(value.clone()); + // The false here is an ordinary host return value, not a completion. + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(false)))) + } +} + +struct FaultHost; + +impl HostFunction for FaultHost { + fn call(&mut self, _vm: &mut Vm, _args: &[Value]) -> vm::VmResult { + Err(VmError::HostError("completion host fault".to_string())) + } +} + +struct TickHost { + ticks: Arc>>, +} + +impl HostFunction for TickHost { + fn call(&mut self, _vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::String(label)] = args else { + return Err(VmError::HostError( + "tick expects one string label".to_string(), + )); + }; + let mut ticks = self.ticks.lock().expect("tick log"); + ticks.push(label.as_str().to_string()); + Ok(CallOutcome::Return(CallReturn::one(Value::Int( + ticks.len() as i64, + )))) + } +} + +/// Typed result of the candidate file-execution exit. +/// +/// `drive_fixture` runs this consumer on the real path, after `Vm::run` and +/// before any caller observes the run. A normal completion is an ordered value +/// list; an uncaught explicit Lua error is a typed failure carrying exactly its +/// original payload. A real `VmError` is surfaced unchanged, and any other +/// `VmStatus` is reported as itself, never as a guest error. +#[derive(Debug)] +enum CompletionExit { + /// Normal completion: values in order, preserving zero returns, one nil, + /// and trailing nils. + Values(Vec), + /// An uncaught explicit guest error: exactly the original payload. + Uncaught { payload: Value }, + /// The underlying VM stopped on a real core or host error. + VmFailure(VmError), + /// The underlying VM reported a status other than `Halted`. + VmStatus(VmStatus), + /// The stack did not match the private transport; fail closed. + MalformedTransport { detail: String }, +} + +/// Consume the candidate completion at the file-execution exit. +/// +/// This is the one place that reads the private `[Bool, ...values]` transport. +/// It is not a per-test assertion and it never guesses provenance from a guest +/// value's shape: only the single chunk result slot of a candidate-compiled +/// file is inspected. `[false, payload]` is the explicit error completion. +fn consume_completion_exit(status: Result, stack: Vec) -> CompletionExit { + let status = match status { + Err(error) => return CompletionExit::VmFailure(error), + Ok(status) => status, + }; + if status != VmStatus::Halted { + return CompletionExit::VmStatus(status); + } + let [Value::Array(items)] = stack.as_slice() else { + return CompletionExit::MalformedTransport { + detail: format!("expected exactly one completion array, stack={stack:?}"), + }; + }; + match items.first() { + Some(Value::Bool(true)) => CompletionExit::Values(items[1..].to_vec()), + Some(Value::Bool(false)) if items.len() == 2 => CompletionExit::Uncaught { + payload: items[1].clone(), + }, + Some(Value::Bool(false)) => CompletionExit::MalformedTransport { + detail: format!("error completion must carry exactly one payload: {items:?}"), + }, + Some(other) => CompletionExit::MalformedTransport { + detail: format!("completion status is not a Bool: {other:?}"), + }, + None => CompletionExit::MalformedTransport { + detail: "completion is empty".to_string(), + }, + } +} + +struct Run { + stack: Vec, + fuel_consumed: u64, + marks: Vec, + seen: Option, + ticks: Vec, + exit: CompletionExit, + call_sites: Vec, + capture_plans: Vec, +} + +/// The fixed Core's capture decision for one closure prototype, read from the +/// compiled program. `Copy` keeps the source binding usable; `Move` detaches +/// it at `BindCallable` time. +#[derive(Clone, Debug)] +struct CapturePlan { + source_slots: Vec, + modes: Vec, +} + +fn capture_plans(program: &Program) -> Vec { + program + .callable_prototypes + .iter() + .filter(|prototype| !prototype.capture_modes.is_empty()) + .map(|plan| CapturePlan { + source_slots: plan.capture_source_slots.clone(), + modes: plan.capture_modes.clone(), + }) + .collect() +} + +fn drive_fixture(name: &str) -> Run { + let path = fixture_path(name); + let compiled = vm::compile_source_file_with_options(&path, candidate_options()) + .unwrap_or_else(|error| panic!("{name}: candidate compile failed: {error:?}")); + let call_sites = decoded_call_sites(&compiled.program); + let capture_plans = capture_plans(&compiled.program); + let mut vm = Vm::new_with_jit_config( + compiled.program, + vm::JitConfig { + enabled: false, + hot_loop_threshold: 8, + max_trace_len: 256, + }, + ); + let observation = Observation::default(); + vm.bind_function( + "mark", + Box::new(MarkHost { + marks: Arc::clone(&observation.marks), + seen: Arc::clone(&observation.seen), + }), + ); + vm.bind_function( + "note", + Box::new(NoteHost { + seen: Arc::clone(&observation.seen), + }), + ); + vm.bind_function("fault", Box::new(FaultHost)); + vm.bind_function( + "tick", + Box::new(TickHost { + ticks: Arc::clone(&observation.ticks), + }), + ); + vm.set_fuel_check_interval(FUEL_CHECK_INTERVAL) + .unwrap_or_else(|error| panic!("{name}: fuel interval: {error}")); + vm.set_fuel(FUEL_BUDGET); + let status = vm.run(); + let remaining = vm + .get_fuel() + .unwrap_or_else(|| panic!("{name}: fuel metering missing")); + let fuel_consumed = FUEL_BUDGET + .checked_sub(remaining) + .unwrap_or_else(|| panic!("{name}: fuel increased")); + let marks = observation.marks.lock().expect("mark log").clone(); + let seen = observation.seen.lock().expect("seen payload").clone(); + let ticks = observation.ticks.lock().expect("tick log").clone(); + let stack = vm.stack().to_vec(); + let status_log = format!("{status:?}"); + let exit = consume_completion_exit(status, stack.clone()); + if let CompletionExit::MalformedTransport { detail } = &exit { + eprintln!("LUA_COMPLETION malformed-transport fixture={name} detail={detail}"); + } + eprintln!( + "LUA_COMPLETION fixture={name} fuel_budget={FUEL_BUDGET} check_interval={FUEL_CHECK_INTERVAL} consumed={fuel_consumed} remaining={remaining} jit=disabled status={status_log} exit={exit:?} stack={stack:?} marks={:?} captures={capture_plans:?}", + marks + .iter() + .map(|mark| mark.label.as_str()) + .collect::>() + ); + Run { + stack, + fuel_consumed, + marks, + seen, + ticks, + exit, + call_sites, + capture_plans, + } +} + +fn run_stopped(name: &str) -> Run { + let run = drive_fixture(name); + assert!(run.fuel_consumed > 0, "{name}: recorded no fuel"); + assert!( + run.fuel_consumed < FUEL_BUDGET, + "{name}: exhausted the fuel budget" + ); + run +} + +fn run_halted(name: &str) -> Run { + let run = run_stopped(name); + match &run.exit { + CompletionExit::Values(_) => {} + other => panic!("{name}: expected a normal completion exit, got {other:?}"), + } + run +} + +/// Decodes the whole instruction stream with `OpCode::operand_len()` and +/// returns every `CallValue` site with its exact successor and owning +/// prototype. +#[derive(Clone, Copy, Debug)] +struct DecodedCallSite { + ip: usize, + argc: u8, + return_ip: usize, + owner: Option, +} + +fn decoded_call_sites(program: &Program) -> Vec { + let code = &program.code; + let mut ip = 0usize; + let mut sites = Vec::new(); + while ip < code.len() { + let op = OpCode::try_from(code[ip]).expect("invalid opcode"); + let next = ip + 1 + op.operand_len(); + assert!(next <= code.len(), "truncated instruction at {ip}"); + if op == OpCode::CallValue { + let owners: Vec<_> = program + .function_regions + .iter() + .filter(|region| region.start_ip as usize <= ip && next <= region.end_ip as usize) + .collect(); + let [owner] = owners.as_slice() else { + panic!("expected a unique caller region for CallValue at {ip}"); + }; + sites.push(DecodedCallSite { + ip, + argc: code[ip + 1], + return_ip: next, + owner: owner.prototype_id, + }); + } + ip = next; + } + sites +} + +/// Binds the executed marker to the one decoded CallValue whose successor is +/// the executed callee's resume address, owned by the active caller frame. +fn assert_dynamic_call_witness(run: &Run, callee_label: &str, expected_argc: u8) { + let mark = run + .marks + .iter() + .find(|mark| mark.label == callee_label) + .unwrap_or_else(|| panic!("missing {callee_label} marker: {:?}", labels(run))); + let caller = mark + .parent_prototype + .expect("callee marker must have a caller frame"); + let return_ip = mark + .last_return_ip + .expect("callee marker must resume through a CallValue continuation"); + let sites = &run.call_sites; + let matching: Vec<_> = sites + .iter() + .filter(|site| { + site.owner == Some(caller) && site.return_ip == return_ip && site.argc == expected_argc + }) + .collect(); + assert_eq!( + matching.len(), + 1, + "expected one executed CallValue (owner={caller:?}, return_ip={return_ip}, argc={expected_argc}); sites={sites:?}" + ); + let site = matching[0]; + assert_eq!( + site.ip + 2, + site.return_ip, + "CallValue carries one argc operand byte" + ); + let held = &mark.held; + assert_eq!( + held.caller_prototype, + Some(caller), + "held argument must be read from the caller frame: {held:?}" + ); + assert_eq!( + held.callee_prototype, mark.last_prototype, + "the witness must compare against the executing callee frame: {held:?}" + ); + assert!( + held.declared_slot.is_some(), + "the caller prototype must declare a first parameter: {held:?}" + ); + assert!( + held.slot_inside_caller_frame, + "the declared parameter slot must be inside the parent frame: {held:?}" + ); + assert!(held.read_within_bounds, "{held:?}"); + assert!(held.value_is_callable, "{held:?}"); + assert_eq!( + held.callable_prototype, mark.last_prototype, + "the held callable must be the executing callee: {held:?}" + ); + assert!( + held.callable_is_script_function, + "the held callable prototype target must be a script function: {held:?}" + ); + assert_ne!( + mark.last_prototype, mark.parent_prototype, + "the dynamic callee must not be the caller frame" + ); +} + +fn labels(run: &Run) -> Vec<&str> { + run.marks.iter().map(|mark| mark.label.as_str()).collect() +} + +fn completed_values<'a>(name: &str, run: &'a Run) -> &'a [Value] { + match &run.exit { + CompletionExit::Values(values) => values, + other => panic!("{name}: expected a normal completion exit, got {other:?}"), + } +} + +fn uncaught_payload<'a>(name: &str, run: &'a Run) -> &'a Value { + match &run.exit { + CompletionExit::Uncaught { payload } => payload, + other => panic!("{name}: expected a typed uncaught guest error, got {other:?}"), + } +} + +fn same_array(left: &Value, right: &Value) -> bool { + match (left, right) { + (Value::Array(left), Value::Array(right)) => Arc::ptr_eq(left, right), + _ => false, + } +} + +fn payload_of(name: &str, run: &Run) -> Value { + run.seen + .clone() + .unwrap_or_else(|| panic!("{name}: note never observed a payload")) +} + +fn compile_message(name: &str) -> String { + let path = fixture_path(name); + let error = vm::compile_source_file_with_options(&path, candidate_options()) + .err() + .unwrap_or_else(|| panic!("{name}: must be refused at lowering/compile")); + match error { + SourcePathError::SourceWithMap { + error: SourceError::Parse(parse), + .. + } + | SourcePathError::Source(SourceError::Parse(parse)) => parse.message, + other => panic!("{name}: expected a parse-layer refusal, got {other:?}"), + } +} + +#[test] +fn dynamic_error_propagates_through_ordinary_call_and_pcall_recovers() { + let run = run_halted("dynamic-error.lua"); + assert_eq!( + labels(&run), + [ + "outer", + "middle", + "leaf", + "inner-caught", + "outer-tail", + "done" + ], + "the ordinary caller tail must be skipped and the outer tail kept" + ); + let values = completed_values("dynamic-error.lua", &run); + assert_eq!( + values.len(), + 2, + "pcall returns exactly false and the payload" + ); + assert_eq!(values[0], Value::Bool(false)); + let observed = payload_of("dynamic-error.lua", &run); + assert!( + same_array(&values[1], &observed), + "the caught error must keep the original table object" + ); + assert_eq!( + run.marks.iter().filter(|mark| mark.label == "leaf").count(), + 1, + "the dynamic callee must run exactly once" + ); + assert_eq!( + run.marks + .iter() + .filter(|mark| mark.label == "middle") + .count(), + 1 + ); + let outer_frame = run + .marks + .iter() + .find(|mark| mark.label == "outer") + .expect("outer marker") + .frame_len; + let leaf_frame = run + .marks + .iter() + .find(|mark| mark.label == "leaf") + .expect("leaf marker") + .frame_len; + assert_eq!( + leaf_frame, + outer_frame + 2, + "the dynamic callee runs two frames below the outer frame" + ); + assert_dynamic_call_witness(&run, "leaf", 1); +} + +#[test] +fn call_arguments_evaluate_left_to_right_before_one_callee_run() { + let run = run_halted("argument-order.lua"); + assert_eq!( + labels(&run), + ["middle", "leaf", "middle-tail", "done"], + "both arguments run before the single callee" + ); + assert_eq!( + run.ticks, + ["first", "second"], + "dynamic call arguments must evaluate left to right" + ); + assert_eq!( + run.marks.iter().filter(|mark| mark.label == "leaf").count(), + 1, + "the dynamic callee must run exactly once" + ); + assert_eq!( + completed_values("argument-order.lua", &run), + &[Value::Int(2)][..], + "the second argument is the returned value, unpadded" + ); + let Value::Int(first) = run.seen.clone().expect("note observed the first argument") else { + panic!("note must observe the first tick value"); + }; + assert_eq!(first, 1); + assert_dynamic_call_witness(&run, "leaf", 2); +} + +#[test] +fn dynamic_success_keeps_the_ordinary_tail_and_true() { + let run = run_halted("dynamic-success.lua"); + assert_eq!( + labels(&run), + [ + "outer", + "middle", + "leaf", + "middle-tail", + "inner-caught", + "outer-tail", + "done" + ] + ); + let values = completed_values("dynamic-success.lua", &run); + assert_eq!(values.len(), 2); + assert_eq!(values[0], Value::Bool(true)); + assert!(same_array( + &values[1], + &payload_of("dynamic-success.lua", &run) + )); + assert_dynamic_call_witness(&run, "leaf", 1); +} + +#[test] +fn false_first_table_item_is_data_not_an_error() { + let run = run_halted("dynamic-false-table.lua"); + assert_eq!( + labels(&run), + [ + "outer", + "middle", + "leaf", + "middle-tail", + "inner-caught", + "outer-tail", + "done" + ], + "a false table item must not turn the success path into an error" + ); + let values = completed_values("dynamic-false-table.lua", &run); + assert_eq!(values[0], Value::Bool(true)); + let Value::Array(payload) = &values[1] else { + panic!("payload must be the original table"); + }; + assert_eq!(payload.first(), Some(&Value::Bool(false))); + assert!(same_array( + &values[1], + &payload_of("dynamic-false-table.lua", &run) + )); +} + +#[test] +fn host_false_return_is_not_a_completion_status() { + let run = run_halted("host-return-false.lua"); + assert_eq!( + labels(&run), + ["middle", "leaf", "leaf-tail", "middle-tail", "done"], + "a false host return value must not stop either tail" + ); + let values = completed_values("host-return-false.lua", &run); + assert_eq!(values.len(), 1); + assert!(same_array( + &values[0], + &payload_of("host-return-false.lua", &run) + )); +} + +#[test] +fn ordinary_tail_zero_and_one_nil_stay_distinct() { + let zero = run_halted("ordinary-zero.lua"); + assert_eq!(labels(&zero), ["zero"]); + let values = completed_values("ordinary-zero.lua", &zero); + assert!( + values.is_empty(), + "ordinary tail zero returns is zero values" + ); + + let one_nil = run_halted("ordinary-one-nil.lua"); + assert_eq!(labels(&one_nil), ["nil"]); + let values = completed_values("ordinary-one-nil.lua", &one_nil); + assert_eq!(values.len(), 1, "one explicit nil is one value"); + assert_eq!(values[0], Value::Null); +} + +#[test] +fn protected_tail_zero_and_one_nil_stay_distinct() { + let zero = run_halted("protected-zero.lua"); + assert_eq!(labels(&zero), ["zero"]); + assert_eq!( + completed_values("protected-zero.lua", &zero), + &[Value::Bool(true)][..], + "pcall adds exactly its success value" + ); + assert_dynamic_call_witness(&zero, "zero", 0); + + let one_nil = run_halted("protected-one-nil.lua"); + assert_eq!(labels(&one_nil), ["nil"]); + assert_eq!( + completed_values("protected-one-nil.lua", &one_nil), + &[Value::Bool(true), Value::Null][..] + ); +} + +#[test] +fn single_slot_zero_return_binds_nil_with_lazy_guard() { + let run = run_halted("scalar-zero.lua"); + assert_eq!(labels(&run), ["zero", "scalar-tail", "done"]); + assert_eq!( + completed_values("scalar-zero.lua", &run), + &[Value::Null][..] + ); + assert_dynamic_call_witness(&run, "zero", 0); +} + +#[test] +fn uncaught_explicit_error_is_not_a_normal_chunk_result() { + let run = run_stopped("uncaught-error.lua"); + assert_eq!(labels(&run), ["leaf"]); + let payload = uncaught_payload("uncaught-error.lua", &run); + let observed = payload_of("uncaught-error.lua", &run); + assert!( + same_array(payload, &observed), + "the typed uncaught failure must keep the original table object" + ); +} + +#[test] +fn host_error_aborts_without_guest_catch() { + let run = drive_fixture("host-fault.lua"); + let error = match &run.exit { + CompletionExit::VmFailure(error) => error, + other => panic!("a real host error must abort the VM, got {other:?}"), + }; + assert!( + matches!(error, VmError::HostError(message) if message == "completion host fault"), + "unexpected host error: {error:?}" + ); + assert_eq!( + labels(&run), + ["outer", "middle", "leaf"], + "no marker after the fault and no pcall recovery may run" + ); + assert!( + !run.stack.iter().any(|value| matches!( + value, + Value::Array(items) if matches!(items.first(), Some(Value::Bool(_))) + )), + "the host error must not turn into a guest completion tag: {:?}", + run.stack + ); +} + +#[test] +fn unproven_host_callable_is_refused_at_lowering() { + let message = compile_message("unproven-callable.lua"); + assert!( + message.contains("not a proven Lua callable"), + "unexpected refusal: {message}" + ); +} + +#[test] +fn unknown_global_call_is_refused_at_lowering() { + let message = compile_message("unknown-global.lua"); + assert!( + message.contains("unsupported global call"), + "unexpected refusal: {message}" + ); +} + +/// Admission RED/GREEN boundary: the candidate lowering must refuse the input +/// before any VM runs. If the current lowering still admits it, the same real +/// fixture is executed and the panic reports the actual runtime gate, so a +/// diagnostic is never assumed from a helper-only assertion. +fn assert_lowering_refusal(name: &str, needle: &str) { + let path = fixture_path(name); + match vm::compile_source_file_with_options(&path, candidate_options()) { + Err(SourcePathError::SourceWithMap { + error: SourceError::Parse(parse), + .. + }) + | Err(SourcePathError::Source(SourceError::Parse(parse))) => { + eprintln!( + "LUA_COMPLETION refusal fixture={name} message={}", + parse.message + ); + assert!( + parse.message.contains(needle), + "{name}: unexpected refusal: {}", + parse.message + ); + } + Err(other) => panic!("{name}: expected a lowering/parse refusal, got {other:?}"), + Ok(_) => { + let run = drive_fixture(name); + panic!( + "{name}: the fixture must be refused at lowering, but the candidate ran: exit={:?} stack={:?} marks={:?}", + run.exit, + run.stack, + labels(&run) + ); + } + } +} + +#[test] +fn missing_callable_argument_is_refused_at_lowering() { + assert_lowering_refusal("missing-callee-argument.lua", "not a proven Lua callable"); +} + +#[test] +fn pcall_missing_callable_argument_is_refused_at_lowering() { + assert_lowering_refusal( + "pcall-missing-callee-argument.lua", + "not a proven Lua callable", + ); +} + +#[test] +fn pcall_forwarded_non_lua_argument_is_refused_at_lowering() { + assert_lowering_refusal("pcall-forwarded-non-lua.lua", "not a proven Lua callable"); +} + +#[test] +fn all_lua_multilevel_forwarding_runs() { + let run = run_halted("forward-all-lua.lua"); + assert_eq!(labels(&run), ["forward", "invoke", "leaf", "done"]); + assert_eq!( + completed_values("forward-all-lua.lua", &run), + &[Value::Bool(true), Value::Int(7)][..] + ); + assert_dynamic_call_witness(&run, "leaf", 1); +} + +fn count_label(run: &Run, label: &str) -> usize { + run.marks.iter().filter(|mark| mark.label == label).count() +} + +/// The forwarding closure in the capture-order fixtures captures exactly one +/// local: the `invoke` binding. The original binding must be copied into the +/// closure cell, not moved out of its slot, because Lua keeps it usable. +fn assert_single_copy_capture(run: &Run, name: &str) { + assert_eq!( + run.capture_plans.len(), + 1, + "{name}: only the forwarding closure may capture: {:?}", + run.capture_plans + ); + let plan = &run.capture_plans[0]; + assert_eq!( + plan.source_slots.len(), + 1, + "{name}: the forwarding closure captures one binding: {plan:?}" + ); + assert_eq!( + plan.modes, + [vm::CaptureBindingMode::Copy], + "{name}: the captured original binding must be copied, not moved: {plan:?}" + ); +} + +/// Every executed marker must resume through exactly one decoded `CallValue` +/// owned by the active caller frame, with the marker's return address and the +/// expected argc. Repeated executions of the same site stay one site. +fn assert_marker_call_site(run: &Run, mark: &MarkRecord, expected_argc: u8) { + let return_ip = mark + .last_return_ip + .expect("marker must resume through a CallValue continuation"); + let matching: Vec<_> = run + .call_sites + .iter() + .filter(|site| { + site.owner == mark.parent_prototype + && site.return_ip == return_ip + && site.argc == expected_argc + }) + .collect(); + assert_eq!( + matching.len(), + 1, + "expected one CallValue (owner={:?}, return_ip={return_ip}, argc={expected_argc}) for {}; sites={:?}", + mark.parent_prototype, + mark.label, + run.call_sites + ); + assert_eq!( + matching[0].ip + 2, + matching[0].return_ip, + "CallValue carries one argc operand byte" + ); +} + +/// `direct-before.lua` is the layout control: the original `invoke` binding is +/// called before `forward` is created, so no capture has happened yet. +#[test] +fn direct_before_calls_original_binding_control() { + let run = run_halted("direct-before.lua"); + assert_eq!( + labels(&run), + ["invoke", "leaf", "forward", "invoke", "leaf", "done"], + "the original call and the forwarded call both run before done" + ); + assert_eq!( + completed_values("direct-before.lua", &run), + &[Value::Bool(true), Value::Int(7), Value::Int(5)][..], + "pcall returns true, the forwarded 7, and the original call's 5" + ); + assert_eq!(count_label(&run, "invoke"), 2, "invoke runs twice"); + assert_eq!(count_label(&run, "leaf"), 2, "leaf runs twice"); + assert_eq!(count_label(&run, "forward"), 1, "forward runs once"); + let invoke_marks: Vec<_> = run + .marks + .iter() + .filter(|mark| mark.label == "invoke") + .collect(); + for mark in &invoke_marks { + assert_marker_call_site(&run, mark, 2); + } + let mut invoke_callers: Vec<_> = invoke_marks + .iter() + .map(|mark| mark.parent_prototype) + .collect(); + invoke_callers.sort_unstable(); + invoke_callers.dedup(); + assert_eq!( + invoke_callers.len(), + 2, + "the original call and the closure-forwarded call have distinct callers" + ); + for mark in run.marks.iter().filter(|mark| mark.label == "leaf") { + assert_marker_call_site(&run, mark, 1); + } + assert_dynamic_call_witness(&run, "leaf", 1); + assert_eq!( + payload_of("direct-before.lua", &run), + Value::Int(7), + "the last leaf argument is the forwarded 7" + ); +} + +/// `direct-after.lua` calls the original `invoke` binding after `forward` has +/// captured it. Lua keeps that binding usable; the capture must not detach it. +#[test] +fn direct_after_calls_original_binding_after_capture() { + let run = run_halted("direct-after.lua"); + assert_eq!( + labels(&run), + ["invoke", "leaf", "forward", "invoke", "leaf", "done"], + "the captured call must not break the later original call" + ); + assert_eq!( + completed_values("direct-after.lua", &run), + &[Value::Bool(true), Value::Int(7), Value::Int(5)][..], + "pcall returns true, the forwarded 7, and the later original call's 5" + ); + assert_eq!(count_label(&run, "invoke"), 2, "invoke runs twice"); + assert_eq!(count_label(&run, "leaf"), 2, "leaf runs twice"); + for mark in run.marks.iter().filter(|mark| mark.label == "invoke") { + assert_marker_call_site(&run, mark, 2); + } + for mark in run.marks.iter().filter(|mark| mark.label == "leaf") { + assert_marker_call_site(&run, mark, 1); + } + assert_dynamic_call_witness(&run, "leaf", 1); + assert_single_copy_capture(&run, "direct-after.lua"); + assert_eq!(payload_of("direct-after.lua", &run), Value::Int(7)); +} + +/// `protected-after.lua` wraps the post-capture original binding call in +/// `pcall`. The direct protected call succeeds and contributes its Boolean. +#[test] +fn protected_after_calls_original_binding_after_capture() { + let run = run_halted("protected-after.lua"); + assert_eq!( + labels(&run), + ["invoke", "leaf", "forward", "invoke", "leaf", "done"], + "the protected original call and the forwarded call both run" + ); + assert_eq!( + completed_values("protected-after.lua", &run), + &[ + Value::Bool(true), + Value::Int(7), + Value::Int(5), + Value::Bool(true) + ][..], + "forward pcall succeeds, then the protected original call returns true and 5" + ); + assert_eq!(count_label(&run, "invoke"), 2, "invoke runs twice"); + assert_eq!(count_label(&run, "leaf"), 2, "leaf runs twice"); + for mark in run.marks.iter().filter(|mark| mark.label == "invoke") { + assert_marker_call_site(&run, mark, 2); + } + for mark in run.marks.iter().filter(|mark| mark.label == "leaf") { + assert_marker_call_site(&run, mark, 1); + } + assert_dynamic_call_witness(&run, "leaf", 1); + assert_single_copy_capture(&run, "protected-after.lua"); + assert_eq!(payload_of("protected-after.lua", &run), Value::Int(7)); +} + +/// Lua 5.2 keeps the outer local `f` usable after the nested closure is +/// created. Both the direct `f(f)` and the nested `inner()`'s `f(f)` return 1, +/// whether the direct call is written before or after the capture site. +#[test] +fn nested_direct_capture_keeps_the_original_binding() { + for name in ["nested-direct-before.lua", "nested-direct-after.lua"] { + let run = run_halted(name); + assert_eq!( + completed_values(name, &run), + &[Value::Int(1), Value::Int(1)][..], + "{name}: both the direct and nested calls must return 1" + ); + } +} + +/// Compares the actual `Value::Callable` payload by `Arc::ptr_eq`. Core's +/// ordinary `Value` equality would also accept two distinct carriers of the +/// same prototype, so only pointer identity proves one shared callable. +fn same_callable(left: &Value, right: &Value) -> bool { + match (left, right) { + (Value::Callable(left), Value::Callable(right)) => Arc::ptr_eq(left, right), + _ => false, + } +} + +/// The ordinary path returns `direct, nested, f, other` as real file results. +/// Both the direct `f(f)` and the nested `inner()`'s `f(f)` must yield the +/// exact same `SharedCallable` as the original `f`; the separately declared +/// `other` must stay a different one. +#[test] +fn nested_callable_identity_survives_ordinary_call() { + let name = "nested-callable-identity-ordinary.lua"; + let run = run_halted(name); + let values = completed_values(name, &run); + assert_eq!( + values.len(), + 4, + "exactly direct, nested, f, other: {values:?}" + ); + let (direct, nested, original, other) = (&values[0], &values[1], &values[2], &values[3]); + assert!( + matches!(original, Value::Callable(_)) && matches!(other, Value::Callable(_)), + "both declared function bindings are returned as callables: {values:?}" + ); + assert!( + same_callable(direct, original), + "the direct call result must be the original callable Arc: direct={direct:?} original={original:?}" + ); + assert!( + same_callable(nested, original), + "the nested call result must be the original callable Arc: nested={nested:?} original={original:?}" + ); + assert!( + !same_callable(other, original), + "a different declared function must not share the original Arc: other={other:?} original={original:?}" + ); + assert_eq!( + run.capture_plans.len(), + 2, + "the outer and inner capture edges are both visible: {:?}", + run.capture_plans + ); + for plan in &run.capture_plans { + assert_eq!( + plan.modes, + [vm::CaptureBindingMode::Copy], + "every nested callable capture edge must copy, not move: {plan:?}" + ); + } +} + +/// The protected path returns `direct_ok, direct, nested_ok, nested, f, +/// other`. Both `pcall(f, f)` results must share the original Arc, both +/// status flags must be the exact Boolean `true`, and `other` must differ. +#[test] +fn nested_callable_identity_survives_protected_call() { + let name = "nested-callable-identity-protected.lua"; + let run = run_halted(name); + let values = completed_values(name, &run); + assert_eq!( + values.len(), + 6, + "exactly direct_ok, direct, nested_ok, nested, f, other: {values:?}" + ); + assert_eq!(values[0], Value::Bool(true), "direct pcall flag"); + assert_eq!(values[2], Value::Bool(true), "nested pcall flag"); + let (direct, nested, original, other) = (&values[1], &values[3], &values[4], &values[5]); + assert!( + matches!(original, Value::Callable(_)) && matches!(other, Value::Callable(_)), + "both declared function bindings are returned as callables: {values:?}" + ); + assert!( + same_callable(direct, original), + "the direct pcall result must be the original callable Arc: direct={direct:?} original={original:?}" + ); + assert!( + same_callable(nested, original), + "the nested pcall result must be the original callable Arc: nested={nested:?} original={original:?}" + ); + assert!( + !same_callable(other, original), + "a different declared function must not share the original Arc: other={other:?} original={original:?}" + ); + assert_eq!( + run.capture_plans.len(), + 2, + "the outer and inner capture edges are both visible: {:?}", + run.capture_plans + ); + for plan in &run.capture_plans { + assert_eq!( + plan.modes, + [vm::CaptureBindingMode::Copy], + "every nested callable capture edge must copy, not move: {plan:?}" + ); + } +} + +/// A callable parameter is admitted by binding identity, not by its name. The +/// same two-level shape through `pcall(callee, callee)` must keep the original +/// `leaf` callable in the parameter slot, so the post-capture `return callee` +/// still yields the original Arc. +#[test] +fn nested_callable_identity_survives_callable_parameter() { + let name = "nested-callable-identity-parameter.lua"; + let run = run_halted(name); + let values = completed_values(name, &run); + assert_eq!( + values.len(), + 4, + "exactly original, ok, passed, leaf: {values:?}" + ); + assert_eq!(values[1], Value::Bool(true), "pcall flag"); + assert!( + matches!(values[3], Value::Callable(_)), + "the declared leaf must be returned as a callable: {values:?}" + ); + assert!( + same_callable(&values[0], &values[3]), + "the parameter slot must still hold the original Arc after the capture: original={:?} leaf={:?}", + values[0], + values[3] + ); + assert!( + same_callable(&values[2], &values[3]), + "the pcall result must be the original Arc: passed={:?} leaf={:?}", + values[2], + values[3] + ); + assert_eq!( + run.capture_plans.len(), + 2, + "the parameter capture and the inner capture are both visible: {:?}", + run.capture_plans + ); + for plan in &run.capture_plans { + assert_eq!( + plan.modes, + [vm::CaptureBindingMode::Copy], + "every nested callable capture edge must copy, not move: {plan:?}" + ); + } +} + +#[test] +fn missing_data_arguments_pad_nil_without_rejecting() { + let run = run_halted("missing-data-argument.lua"); + assert_eq!(labels(&run), ["take", "take", "forward", "take", "done"]); + assert_eq!( + completed_values("missing-data-argument.lua", &run), + &[Value::Null, Value::Bool(true), Value::Null, Value::Int(42)][..] + ); +} + +#[test] +fn ordinary_trailing_nil_is_preserved() { + let run = run_halted("ordinary-trailing-nil.lua"); + assert_eq!(labels(&run), ["pair"]); + assert_eq!( + completed_values("ordinary-trailing-nil.lua", &run), + &[Value::Int(1), Value::Null][..] + ); +} + +#[test] +fn completion_exit_separates_vm_status_and_malformed_transport() { + match consume_completion_exit(Ok(VmStatus::Yielded), Vec::new()) { + CompletionExit::VmStatus(VmStatus::Yielded) => {} + other => panic!("a non-Halted status must be reported as itself: {other:?}"), + } + let malformed = [ + Vec::new(), + vec![Value::Int(1)], + vec![Value::array(Vec::new())], + vec![Value::array(vec![Value::Int(0)])], + vec![Value::array(vec![Value::Bool(false)])], + vec![Value::array(vec![ + Value::Bool(false), + Value::Null, + Value::Null, + ])], + vec![Value::array(vec![Value::Bool(true)]), Value::Null], + ]; + for stack in malformed { + match consume_completion_exit(Ok(VmStatus::Halted), stack) { + CompletionExit::MalformedTransport { .. } => {} + other => panic!("malformed transport must fail closed: {other:?}"), + } + } +} diff --git a/tests/compiler/compiler_lua_completion_tests/active_finalizer.rs b/tests/compiler/compiler_lua_completion_tests/active_finalizer.rs new file mode 100644 index 0000000..6ae7044 --- /dev/null +++ b/tests/compiler/compiler_lua_completion_tests/active_finalizer.rs @@ -0,0 +1,1825 @@ +//! Active Lua parent frame invoking the callable an exact typed host returns. +//! +//! One real `.lua` file (`tests/fixtures/luajit/finalizer/`) is fed through the +//! real lexer, parser, resolver and private completion lowering, compiled +//! through the fixed Core and run in one interpreter VM with JIT disabled. +//! Every Lua function and every host call in the fixture is real. The only +//! generated node is the typed local and the `Expr::LocalCall` target that the +//! production admission gate (`proof_for`) refuses to emit for a host-returned +//! callable: the plugin retargets the one dynamic call node the real lowering +//! produced for the admitted parameter onto the typed local that holds the +//! host-returned callable, and marks that local with an explicit +//! `TypeSchema::Callable`. Core typing, codegen and the VM then do the rest: +//! `CallValue(2)`, a real script frame, a real `Ret`, and the parent's resumed +//! return address. +//! +//! The host adapter is registered with `register_exact_static`, so the program +//! carries the catalog schema for every import and the returned callable is +//! checked by `validate_host_call_return`/`validate_callable_value` against the +//! compiled `CallablePrototype.schema` at run time. `register_exact_owned` is +//! not used: this pin refuses a return schema with a resource nested inside an +//! aggregate on that path, and no schema validation is disabled or downgraded +//! to `Unknown`. +//! +//! The private completion lowerer admits exactly four guest host-call names +//! (`mark`, `note`, `fault`, `tick`) and one arity per name, so the private test +//! catalog binds those names to the four adapters this witness needs. The +//! fixture comments name each adapter's real job; `mark` additionally returns +//! the integer the test staged for the arm and observes the active frame, and +//! `note` is the typed callable-returning adapter. +//! +//! Witnessed here: +//! +//! - the returned value is the exact `SharedCallable` the VM produced for the +//! guest binding (`Arc::ptr_eq`, not schema equality); +//! - the receiver is the original issued Lua table, and a same-shaped ordinary +//! array is not that table; +//! - the second argument is a real `resource` token: the Core +//! resource table borrow revalidates arena, generation, concrete type and the +//! exact `lua.userdata` key, the heap payload names the same userdata, and the +//! same handle is refused as a `lua.table` token; +//! - the callee frame's declared parameter slots hold exactly those values; +//! - the call resumes the parent at the decoded `CallValue` successor and the +//! parent continues with its own markers and its own returned value. +//! +//! Refuting controls, each a separate single `Vm::run` of the same file: +//! +//! - `OmitCall`: the typed host still runs and the typed local is still bound, +//! but the call statement is absent from the executed IR, so no child frame +//! and no callee marker exists; +//! - `OtherInstance`: the host returns another real Lua callable of the same +//! declared two-parameter shape (a different chunk-level function with a +//! different capture), so the call still runs and the original-instance +//! assertion and the capture observation are both refuted; +//! - `OtherSignature`: the host returns a real one-parameter callable, so the +//! typed return check refuses the value with the Core type error before any +//! call runs; +//! - `OtherCapture` (attempted, refused before the call): the host really +//! receives and selects `second`, the second instance of the one factory +//! prototype that also produced `first`, so the two values are one nested +//! prototype with two different captures. This pin compiles no callable +//! schema for a nested closure prototype, so the exact typed return check +//! refuses the selected instance with the Core callable type error and the +//! guest call never happens. The host-selected same-prototype call is +//! therefore *not* achieved: this arm records the pinned diagnostic and the +//! witness does not claim that control. +//! +//! Not claimed here: a real finalizer dequeue, the pending-finalizer queue, a +//! source-level general closure bridge, close, collection, or a host-selected +//! call of a nested same-prototype instance (this pin refuses that typed +//! return). The heap is only used to issue one real table carrier and one real +//! userdata token; nothing is collected or closed. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use vm::compiler::HostCallResolver; +use vm::vm::VmFrameContinuation; +use vm::{ + CallOutcome, CallReturn, ClosureExpr, CompileSourceFileOptions, Expr, FrontendImportSyntax, + FrontendIr, HostApiBuilder, HostApiCatalog, HostFunctionRegistry, HostFunctionSchema, + HostImport, HostImportSchema, HostParamSchema, HostTypeSchema, JitConfig, LocalSlot, + ParseError, ResourceTypeSchema, SourceError, SourceFlavor, SourcePathError, SourcePlugin, Stmt, + TypeSchema, Value, Vm, VmError, VmStatus, +}; + +use super::{FUEL_BUDGET, FUEL_CHECK_INTERVAL, decoded_call_sites}; +use crate::heap::{self, GuestClass, LuaTableResource, LuaUserdataResource, TableRef, UserdataRef}; + +/// The one fixture every arm executes. +const FIXTURE: &str = "active_typed_parent_call.lua"; +/// The admission control that must stay refused at lowering. +const UNADMITTED_FIXTURE: &str = "active_typed_unadmitted.lua"; +/// `parent(cb, first, second, single, other, recv, ud)`. +const PARENT_PARAMS: usize = 7; +/// `cb(recv, ud)`. +const CALL_ARGC: u8 = 2; +/// The admitted callee is the parent's first declared parameter. +const PARENT_CALLEE_SLOT: usize = 0; +/// The receiver and the userdata argument positions in `parent`. +const PARENT_RECEIVER_SLOT: usize = 5; +const PARENT_USERDATA_SLOT: usize = 6; + +// ---- one run at a time ---------------------------------------------------- + +/// The exact observation of the last admitted run. This test module drives +/// every arm sequentially in one test body, so a process-wide slot holds the +/// same value a per-run handle would carry; no other test touches it. +static WITNESS: Mutex> = Mutex::new(None); + +/// The integer the marker host returns and the fixture passes back as its +/// selection mode. +static SELECT: AtomicUsize = AtomicUsize::new(0); + +/// The structural record the plugin produced for the last compile. +static PATCH: Mutex> = Mutex::new(None); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Arm { + Positive, + OmitCall, + OtherInstance, + OtherSignature, + OtherCapture, +} + +impl Arm { + fn label(self) -> &'static str { + match self { + Arm::Positive => "positive", + Arm::OmitCall => "omit-call", + Arm::OtherInstance => "other-instance", + Arm::OtherSignature => "other-signature", + Arm::OtherCapture => "other-capture", + } + } + + fn select(self) -> usize { + match self { + Arm::Positive | Arm::OmitCall => 0, + Arm::OtherInstance => 1, + Arm::OtherSignature => 2, + Arm::OtherCapture => 3, + } + } + + fn plugin(self) -> &'static dyn SourcePlugin { + match self { + Arm::OmitCall => &OMIT_PLUGIN, + _ => &CALL_PLUGIN, + } + } +} + +// ---- the private test catalog and exact registration ---------------------- + +fn typed_callable_host_schema() -> HostTypeSchema { + HostTypeSchema::Callable { + params: vec![HostTypeSchema::Unknown, HostTypeSchema::Unknown], + result: Box::new(HostTypeSchema::Unknown), + } +} + +fn typed_callable_schema() -> TypeSchema { + typed_callable_schema_with(usize::from(CALL_ARGC)) +} + +fn typed_callable_schema_with(parameters: usize) -> TypeSchema { + TypeSchema::Callable { + params: vec![TypeSchema::Unknown; parameters], + result: Box::new(TypeSchema::Unknown), + } +} + +fn active_catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = HostApiBuilder::new(); + // The marker channel. The label schema stays `Unknown` because a Lua + // parameter has no static schema in this frontend and the callee + // reports its capture through the label; the host body still requires + // a real string and the return is the staged arm integer. + builder.function(HostFunctionSchema::with_return( + "mark", + vec![HostParamSchema::value("label", HostTypeSchema::Unknown)], + HostTypeSchema::Int, + )); + // The typed callable-returning adapter. This is the schema under test. + builder.function(HostFunctionSchema::with_return( + "note", + vec![ + HostParamSchema::value("mode", HostTypeSchema::Int), + HostParamSchema::value("target", HostTypeSchema::Unknown), + HostParamSchema::value("first", HostTypeSchema::Unknown), + HostParamSchema::value("second", HostTypeSchema::Unknown), + HostParamSchema::value("single", HostTypeSchema::Unknown), + HostParamSchema::value("other", HostTypeSchema::Unknown), + ], + typed_callable_host_schema(), + )); + // One freshly issued LuaHeap table carrier. + builder.function(HostFunctionSchema::with_return( + "tick", + vec![HostParamSchema::value("label", HostTypeSchema::String)], + HostTypeSchema::Unknown, + )); + // One freshly issued typed userdata token. + builder.resource(ResourceTypeSchema::new( + LuaUserdataResource::key(), + "Lua userdata", + )); + builder.function(HostFunctionSchema::with_return( + "fault", + Vec::new(), + HostTypeSchema::Resource(LuaUserdataResource::key()), + )); + Arc::new(builder.build().expect("active typed call catalog")) + }) +} + +fn catalog_schema(name: &str) -> HostImportSchema { + let catalog = active_catalog(); + let function = catalog + .function(name) + .unwrap_or_else(|| panic!("catalog is missing '{name}'")); + HostImportSchema::from_function(catalog, function) +} + +/// Binds every host the fixture calls through the exact static registration +/// path, so the compiled program and the VM share one catalog schema per +/// import and the typed return is validated at run time. +fn bind_hosts(vm: &mut Vm) -> Result<(), VmError> { + let mut registry = HostFunctionRegistry::empty(); + registry.register_exact_static("mark", 1, catalog_schema("mark"), host_mark)?; + registry.register_exact_static("note", 6, catalog_schema("note"), host_note)?; + registry.register_exact_static("tick", 1, catalog_schema("tick"), host_tick)?; + registry.register_exact_static("fault", 0, catalog_schema("fault"), host_fault)?; + registry.bind_vm_cached(vm) +} + +// ---- observation records -------------------------------------------------- + +#[derive(Clone, Debug)] +struct MarkRecord { + label: String, + frame_len: usize, + last_prototype: Option, + last_return_ip: Option, + parent_prototype: Option, + callee: Option, +} + +/// What one active two-parameter callee frame actually received. +#[derive(Clone, Debug)] +struct CalleeRecord { + prototype_id: u32, + local_base: usize, + local_count: usize, + parameter_slots: Vec, + parameter_values: Vec>, + receiver_class: String, + ordinary_array_class: String, + token_parts: (u64, u32, u32), + rebound_parts: (u64, u32, u32), + table_token_refused: bool, + caller_callable: Option, + caller_declared_slot: Option, +} + +#[derive(Clone, Debug)] +struct PickRecord { + mode: i64, + prototype_id: u32, + first: Value, + second: Value, + other: Value, + chosen: Value, +} + +#[derive(Clone, Debug, Default)] +struct Witness { + marks: Vec, + picks: Vec, + issued_table: Option, + issued_table_ref: Option, + issued_userdata: Option, + issued_userdata_raw: Option, +} + +fn with_witness(body: impl FnOnce(&mut Witness) -> T) -> T { + let mut guard = WITNESS.lock().expect("active typed witness"); + let witness = guard + .as_mut() + .expect("the active typed witness must be installed before the run"); + body(witness) +} + +fn host_fault_error(message: impl Into) -> VmError { + VmError::HostError(message.into()) +} + +fn heap_fault(error: heap::HeapError) -> VmError { + VmError::HostError(format!("lua heap: {error:?}")) +} + +// ---- the hosts ------------------------------------------------------------ + +/// Records one active-frame marker and returns the staged arm integer. In a +/// two-parameter callee frame it also records the declared formal slots, the +/// receiver class and revalidates the `lua.userdata` token those slots hold. +fn host_mark(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::String(label)] = args else { + return Err(host_fault_error("mark expects one string label")); + }; + let label = label.as_str().to_string(); + let (frame_len, last_prototype, last_return_ip, parent_prototype, frame) = { + let frames = vm.execution_frames(); + let program = vm.program(); + let locals = vm.locals(); + let parent = frames.iter().rev().nth(1); + let frame = frames.last().and_then(|child| { + let prototype_id = child.prototype_id?; + let prototype = program.callable_prototypes.get(prototype_id as usize)?; + if prototype.parameter_slots.len() != usize::from(CALL_ARGC) { + return None; + } + let declared = prototype.parameter_slots.clone(); + let mut values = Vec::with_capacity(declared.len()); + for slot in &declared { + let absolute = child.local_base.checked_add(usize::from(*slot))?; + if absolute >= child.local_base + child.local_count { + return None; + } + values.push(locals.get(absolute).cloned()); + } + let caller = frames.iter().rev().nth(1); + let mut caller_callable = None; + let mut caller_declared_slot = None; + if let Some(caller) = caller + && let Some(caller_prototype) = caller + .prototype_id + .and_then(|id| program.callable_prototypes.get(id as usize)) + && let Some(&slot) = caller_prototype.parameter_slots.first() + && let Some(absolute) = caller.local_base.checked_add(usize::from(slot)) + { + caller_declared_slot = Some(slot); + caller_callable = locals.get(absolute).cloned(); + } + Some(( + prototype_id, + child.local_base, + child.local_count, + declared, + values, + caller_callable, + caller_declared_slot, + )) + }); + ( + frames.len(), + frames.last().and_then(|frame| frame.prototype_id), + frames.last().and_then(|frame| match &frame.continuation { + VmFrameContinuation::ResumeBytecode { return_ip } => Some(*return_ip), + _ => None, + }), + parent.and_then(|frame| frame.prototype_id), + frame, + ) + }; + + let mut record = MarkRecord { + label, + frame_len, + last_prototype, + last_return_ip, + parent_prototype, + callee: None, + }; + if let Some((prototype_id, local_base, local_count, slots, values, caller, caller_slot)) = frame + { + let receiver = values + .first() + .cloned() + .flatten() + .ok_or_else(|| host_fault_error("the callee's first formal slot is empty"))?; + let userdata = values + .get(1) + .cloned() + .flatten() + .ok_or_else(|| host_fault_error("the callee's second formal slot is empty"))?; + let mut host = vm.host_context(); + let receiver_class = heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&receiver))) + .map_err(heap_fault)?; + // A same-shaped ordinary array is data, not the issued table. + let ordinary = Value::array(vec![Value::Int(0), Value::Int(0)]); + let ordinary_class = heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&ordinary))) + .map_err(heap_fault)?; + let Value::Int(raw) = userdata else { + return Err(host_fault_error(format!( + "the callee's userdata argument is not a handle token: {userdata:?}" + ))); + }; + let raw = u64::try_from(raw) + .map_err(|_| host_fault_error("the userdata handle token is not a positive integer"))?; + let handle = vm::ResourceHandle::from_raw(raw).map_err(|error| { + host_fault_error(format!("the userdata handle is invalid: {error}")) + })?; + let token_parts = { + let borrowed = host + .borrow_resource_with_key::( + handle, + &LuaUserdataResource::key(), + ) + .map_err(|error| { + host_fault_error(format!("the lua.userdata borrow was refused: {error}")) + })?; + let payload = borrowed.get().userdata(); + (payload.domain(), payload.slot(), payload.generation()) + }; + let rebound_parts = { + let borrowed = host + .borrow_resource_with_key::( + handle, + &LuaUserdataResource::key(), + ) + .map_err(|error| { + host_fault_error(format!( + "the second lua.userdata borrow was refused: {error}" + )) + })?; + let payload = borrowed.get().userdata(); + let rebound = heap::borrow_published_userdata(&host, payload).map_err(heap_fault)?; + (rebound.domain(), rebound.slot(), rebound.generation()) + }; + let table_token_refused = host + .borrow_resource_with_key::(handle, &LuaTableResource::key()) + .is_err(); + record.callee = Some(CalleeRecord { + prototype_id, + local_base, + local_count, + parameter_slots: slots, + parameter_values: values, + receiver_class: format!("{receiver_class:?}"), + ordinary_array_class: format!("{ordinary_class:?}"), + token_parts, + rebound_parts, + table_token_refused, + caller_callable: caller, + caller_declared_slot: caller_slot, + }); + } + with_witness(|witness| witness.marks.push(record)); + let select = i64::try_from(SELECT.load(Ordering::SeqCst)) + .map_err(|_| host_fault_error("the selected arm does not fit a guest integer"))?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int(select)))) +} + +/// Returns one of the candidates the fixture already wrote at the call site. +/// The value is always the exact `SharedCallable` the VM produced for that +/// guest binding; the host never fabricates a callable. +fn host_note(_vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::Int(mode), target, first, second, single, other] = args else { + return Err(host_fault_error( + "note expects a mode and five written candidates", + )); + }; + let chosen = match *mode { + 0 => target, + 1 => other, + 2 => single, + // The second instance of the same factory prototype that produced + // `first`. The host really selects this captured sibling; whether the + // exact typed return accepts it is the question the arm records. + 3 => second, + other => { + return Err(host_fault_error(format!( + "note mode {other} is not a fixture arm" + ))); + } + }; + let Value::Callable(callable) = chosen else { + return Err(host_fault_error( + "the selected typed candidate is not a callable", + )); + }; + let record = PickRecord { + mode: *mode, + prototype_id: callable.prototype_id, + first: first.clone(), + second: second.clone(), + other: other.clone(), + chosen: chosen.clone(), + }; + with_witness(|witness| witness.picks.push(record)); + Ok(CallOutcome::Return(CallReturn::one(chosen.clone()))) +} + +/// Issues one real LuaHeap table and returns its guest carrier. +fn host_tick(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::String(_label)] = args else { + return Err(host_fault_error("tick expects one string label")); + }; + let mut host = vm.host_context(); + let issued = heap::publish_guest(&mut host).map_err(heap_fault)?; + let class = + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&issued))).map_err(heap_fault)?; + let GuestClass::Table(table) = class else { + return Err(host_fault_error( + "the issued table is not a live heap table", + )); + }; + // Keep the heap's own handle alive in the record: a still-live table is + // what makes the carrier an issued Lua table rather than an array. + with_witness(|witness| { + witness.issued_table_ref = Some(table); + witness.issued_table = Some(issued.clone()); + }); + Ok(CallOutcome::Return(CallReturn::one(issued))) +} + +/// Issues one real typed `lua.userdata` token. The Core resource table +/// validates the returned carrier against the catalog key before the guest +/// sees it. +fn host_fault(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + if !args.is_empty() { + return Err(host_fault_error("fault takes no arguments")); + } + let mut host = vm.host_context(); + let userdata = heap::publish_userdata(&mut host).map_err(heap_fault)?; + let raw = heap::with_heap(&mut host, |heap| heap.published_userdata_token(userdata)) + .map_err(heap_fault)?; + let raw = i64::try_from(raw) + .map_err(|_| host_fault_error("the userdata token does not fit a signed carrier"))?; + with_witness(|witness| { + witness.issued_userdata = Some(userdata); + witness.issued_userdata_raw = Some(raw); + }); + Ok(CallOutcome::Return(CallReturn::one(Value::Int(raw)))) +} + +// ---- the private plugin: real lowering plus the one generated node -------- + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CallMode { + /// Keep the call node and retarget it onto the typed local. + Call, + /// Drop the call node and its completion branch. + Omit, +} + +struct ActivePlugin { + mode: CallMode, + declared_parameters: usize, +} + +static CALL_PLUGIN: ActivePlugin = ActivePlugin { + mode: CallMode::Call, + declared_parameters: 2, +}; +static OMIT_PLUGIN: ActivePlugin = ActivePlugin { + mode: CallMode::Omit, + declared_parameters: 2, +}; +static SCHEMA_PLUGIN: ActivePlugin = ActivePlugin { + mode: CallMode::Call, + declared_parameters: 3, +}; + +#[derive(Clone, Debug)] +struct CallPatch { + completion_slot: LocalSlot, + written_callee: LocalSlot, + typed_callee: LocalSlot, + argc: u8, + arg_slots: Vec, +} + +#[derive(Clone, Debug, Default)] +struct PatchReport { + typed_local: Option, + declared_schema: Option, + call: Option, + omitted: bool, + parent_parameters: Vec, +} + +impl SourcePlugin for ActivePlugin { + 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 { + let resolver = HostCallResolver::new(active_catalog()); + let mut ir = super::lower::lower_source_with(source, Some(&resolver))?; + let report = patch_ir(&mut ir, self.mode, self.declared_parameters)?; + *PATCH.lock().expect("active typed patch report") = Some(report); + Ok(ir) + } +} + +fn patch_error(message: impl Into) -> ParseError { + ParseError::at_line(1, message) +} + +fn patch_ir( + ir: &mut FrontendIr, + mode: CallMode, + declared_parameters: usize, +) -> Result { + let mut report = PatchReport::default(); + patch_stmts(&mut ir.stmts, mode, declared_parameters, &mut report)?; + Ok(report) +} + +fn patch_stmts( + stmts: &mut [Stmt], + mode: CallMode, + declared_parameters: usize, + report: &mut PatchReport, +) -> Result<(), ParseError> { + for stmt in stmts.iter_mut() { + match stmt { + Stmt::Let { expr, .. } | Stmt::Expr { expr, .. } => { + patch_expr_closures(expr, mode, declared_parameters, report)?; + } + _ => {} + } + } + Ok(()) +} + +/// Descends through block expressions looking for Lua closure bindings. The +/// chunk's own statements live in one `Stmt::Expr` block, so this walk has to +/// start there rather than at the top-level statement list alone. +fn patch_expr_closures( + expr: &mut Expr, + mode: CallMode, + declared_parameters: usize, + report: &mut PatchReport, +) -> Result<(), ParseError> { + match expr { + Expr::Closure(closure) => patch_closure_body(closure, mode, declared_parameters, report), + Expr::Block { stmts, expr } => { + patch_stmts(stmts, mode, declared_parameters, report)?; + patch_expr_closures(expr, mode, declared_parameters, report) + } + _ => Ok(()), + } +} + +fn patch_closure_body( + closure: &mut ClosureExpr, + mode: CallMode, + declared_parameters: usize, + report: &mut PatchReport, +) -> Result<(), ParseError> { + let Expr::Block { stmts, expr: tail } = closure.body.as_mut() else { + return Ok(()); + }; + if closure.param_slots.len() == PARENT_PARAMS { + patch_parent( + stmts, + tail, + closure.param_slots.clone(), + mode, + declared_parameters, + report, + )?; + } + for stmt in stmts.iter_mut() { + let Stmt::Let { expr, .. } = stmt else { + continue; + }; + patch_expr_closures(expr, mode, declared_parameters, report)?; + } + Ok(()) +} + +fn is_slot_read(expr: &Expr, slot: LocalSlot) -> bool { + matches!(expr, Expr::Var(read) if *read == slot) +} + +fn reads_completion(expr: &Expr, completion: LocalSlot) -> bool { + let Expr::Call(_, _, args, _, _) = expr else { + return false; + }; + matches!(args.as_slice(), [first, second] if is_slot_read(first, completion) + && matches!(second, Expr::Int(0))) +} + +fn patch_parent( + stmts: &mut Vec, + tail: &mut Expr, + parameters: Vec, + mode: CallMode, + declared_parameters: usize, + report: &mut PatchReport, +) -> Result<(), ParseError> { + if parameters.len() != PARENT_PARAMS { + return Err(patch_error("the parent parameter list changed")); + } + report.parent_parameters = parameters.clone(); + let typed_schema = typed_callable_schema_with(declared_parameters); + + let mut typed_local = None; + for stmt in stmts.iter_mut() { + let Stmt::Let { + index, + declared_schema, + expr: Expr::Call(_, _, _, Some(resolution), _), + .. + } = stmt + else { + continue; + }; + if resolution.name != "note" { + continue; + } + if typed_local.is_some() { + return Err(patch_error( + "the parent declares two typed candidate locals", + )); + } + *declared_schema = Some(typed_schema.clone()); + typed_local = Some(*index); + } + let Some(typed_local) = typed_local else { + return Err(patch_error("the parent has no typed candidate local")); + }; + report.typed_local = Some(typed_local); + report.declared_schema = Some(typed_schema); + + let mut call_position = None; + for (position, stmt) in stmts.iter_mut().enumerate() { + let Stmt::Let { + index: completion, + expr: Expr::LocalCall(callee, _, args, _), + .. + } = stmt + else { + continue; + }; + if *callee != parameters[PARENT_CALLEE_SLOT] { + continue; + } + if args.len() != usize::from(CALL_ARGC) { + return Err(patch_error("the admitted dynamic call changed its arity")); + } + if !is_slot_read(&args[0], parameters[PARENT_RECEIVER_SLOT]) + || !is_slot_read(&args[1], parameters[PARENT_USERDATA_SLOT]) + { + return Err(patch_error( + "the admitted dynamic call does not pass the receiver and userdata slots", + )); + } + if call_position.is_some() { + return Err(patch_error("the parent has two admitted dynamic calls")); + } + *callee = typed_local; + report.call = Some(CallPatch { + completion_slot: *completion, + written_callee: parameters[PARENT_CALLEE_SLOT], + typed_callee: typed_local, + argc: CALL_ARGC, + arg_slots: vec![ + parameters[PARENT_RECEIVER_SLOT], + parameters[PARENT_USERDATA_SLOT], + ], + }); + call_position = Some((position, *completion)); + } + + match (mode, call_position) { + (CallMode::Call, Some(_)) => Ok(()), + (CallMode::Call, None) => Err(patch_error("the parent has no admitted dynamic call")), + (CallMode::Omit, Some((position, completion))) => { + stmts.remove(position); + let replaced = std::mem::replace(tail, Expr::Null); + let Expr::IfElse { + condition, + then_expr, + .. + } = replaced + else { + return Err(patch_error( + "the admitted dynamic call has no completion branch", + )); + }; + if !reads_completion(&condition, completion) { + return Err(patch_error( + "the completion branch does not read the call's own slot", + )); + } + *tail = *then_expr; + report.omitted = true; + Ok(()) + } + (CallMode::Omit, None) => Err(patch_error("the parent has no admitted dynamic call")), + } +} + +// ---- one arm -------------------------------------------------------------- + +struct ArmRun { + arm: Arm, + status: Result, + stack: Vec, + witness: Witness, + patch: PatchReport, + call_sites: Vec, + prototypes: Vec, + host_imports: Vec, + host_schemas: Vec>, + local_schemas: Vec>, + fuel_consumed: u64, +} + +fn fixture_path() -> std::path::PathBuf { + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("fixtures") + .join("luajit") + .join("finalizer") + .join(FIXTURE) +} + +fn run_arm(arm: Arm) -> ArmRun { + *PATCH.lock().expect("active typed patch report") = None; + SELECT.store(arm.select(), Ordering::SeqCst); + *WITNESS.lock().expect("active typed witness") = Some(Witness::default()); + + let options = CompileSourceFileOptions::new() + .with_source_plugin(arm.plugin()) + .with_host_api_catalog(Arc::clone(active_catalog())); + let path = fixture_path(); + let compiled = vm::compile_source_file_with_options(&path, options) + .unwrap_or_else(|error| panic!("{}: compile failed: {error:?}", arm.label())); + let patch = PATCH + .lock() + .expect("active typed patch report") + .clone() + .unwrap_or_else(|| panic!("{}: the plugin produced no patch report", arm.label())); + let call_sites = decoded_call_sites(&compiled.program); + let prototypes = compiled.program.callable_prototypes.clone(); + let host_imports = compiled.program.imports.clone(); + let host_schemas = compiled.program.host_import_schemas().to_vec(); + let local_schemas = compiled + .program + .type_map + .as_ref() + .map(|map| map.local_schemas.clone()) + .unwrap_or_default(); + + let mut runtime = Vm::new_with_jit_config( + compiled.program, + JitConfig { + enabled: false, + hot_loop_threshold: 8, + max_trace_len: 256, + }, + ); + bind_hosts(&mut runtime) + .unwrap_or_else(|error| panic!("{}: bind failed: {error}", arm.label())); + runtime + .set_fuel_check_interval(FUEL_CHECK_INTERVAL) + .unwrap_or_else(|error| panic!("{}: fuel interval: {error}", arm.label())); + runtime.set_fuel(FUEL_BUDGET); + let status = runtime.run(); + let remaining = runtime + .get_fuel() + .unwrap_or_else(|| panic!("{}: fuel metering missing", arm.label())); + let fuel_consumed = FUEL_BUDGET + .checked_sub(remaining) + .unwrap_or_else(|| panic!("{}: fuel increased", arm.label())); + let stack = runtime.stack().to_vec(); + let witness = WITNESS + .lock() + .expect("active typed witness") + .take() + .unwrap_or_else(|| panic!("{}: the witness was not installed", arm.label())); + + let run = ArmRun { + arm, + status, + stack, + witness, + patch, + call_sites, + prototypes, + host_imports, + host_schemas, + local_schemas, + fuel_consumed, + }; + run.report(); + run +} + +impl ArmRun { + fn report(&self) { + eprintln!( + "LUA_ACTIVE_TYPED arm={} fuel={} status={:?} exit={:?} patch={:?}", + self.arm.label(), + self.fuel_consumed, + self.status, + self.exit(), + self.patch + ); + eprintln!( + "LUA_ACTIVE_TYPED arm={} marks={:?}", + self.arm.label(), + self.witness + .marks + .iter() + .map(|mark| (mark.label.as_str(), mark.frame_len, mark.last_prototype)) + .collect::>() + ); + for mark in &self.witness.marks { + let Some(callee) = &mark.callee else { + continue; + }; + eprintln!( + "LUA_ACTIVE_TYPED arm={} callee label={} prototype={} slots={:?} values={:?} receiver={} ordinary={} token={:?} rebound={:?} table_refused={} caller_slot={:?} caller_callable={:?}", + self.arm.label(), + mark.label, + callee.prototype_id, + callee.parameter_slots, + callee.parameter_values, + callee.receiver_class, + callee.ordinary_array_class, + callee.token_parts, + callee.rebound_parts, + callee.table_token_refused, + callee.caller_declared_slot, + callee.caller_callable, + ); + } + for pick in &self.witness.picks { + eprintln!( + "LUA_ACTIVE_TYPED arm={} pick mode={} prototype={}", + self.arm.label(), + pick.mode, + pick.prototype_id + ); + } + } + + fn exit(&self) -> Option> { + let Ok(VmStatus::Halted) = &self.status else { + return None; + }; + let [Value::Array(items)] = self.stack.as_slice() else { + return None; + }; + Some(items.as_ref().clone()) + } + + fn labels(&self) -> Vec<&str> { + self.witness + .marks + .iter() + .map(|mark| mark.label.as_str()) + .collect() + } + + fn mark(&self, label: &str) -> &MarkRecord { + self.witness + .marks + .iter() + .find(|mark| mark.label == label) + .unwrap_or_else(|| { + panic!( + "{}: missing '{label}' marker, saw {:?}", + self.arm.label(), + self.labels() + ) + }) + } + + /// The one marker recorded inside a two-parameter callee frame. + fn callee_mark(&self) -> &MarkRecord { + let mut marked = self + .witness + .marks + .iter() + .filter(|mark| mark.callee.is_some()); + let first = marked + .next() + .unwrap_or_else(|| panic!("{}: no callee frame was observed", self.arm.label())); + assert!( + marked.next().is_none(), + "{}: more than one callee frame was observed", + self.arm.label() + ); + first + } + + fn callee(&self) -> &CalleeRecord { + self.callee_mark() + .callee + .as_ref() + .expect("the callee mark carries its record") + } + + fn pick(&self) -> &PickRecord { + self.witness + .picks + .first() + .unwrap_or_else(|| panic!("{}: the typed host never ran", self.arm.label())) + } + + fn assert_fuel(&self) { + assert!( + self.fuel_consumed > 0, + "{}: no fuel spent", + self.arm.label() + ); + assert!( + self.fuel_consumed < FUEL_BUDGET, + "{}: exhausted fuel", + self.arm.label() + ); + } + + fn assert_typed_import(&self) { + let index = self + .host_imports + .iter() + .position(|import| import.name == "note") + .unwrap_or_else(|| panic!("{}: note is not an import", self.arm.label())); + assert_eq!( + self.host_imports[index].return_type, + vm::ValueType::Callable, + "{}: the import must carry a callable return", + self.arm.label() + ); + let schema = self.host_schemas[index].as_ref().unwrap_or_else(|| { + panic!( + "{}: note has no program schema; the runtime check would be disabled", + self.arm.label() + ) + }); + assert_eq!( + schema.return_type, + typed_callable_host_schema(), + "{}: the program must carry the full callable return schema", + self.arm.label() + ); + assert_eq!( + schema.params.len(), + 6, + "{}: the typed adapter arity", + self.arm.label() + ); + let userdata = self + .host_imports + .iter() + .position(|import| import.name == "fault") + .unwrap_or_else(|| panic!("{}: fault is not an import", self.arm.label())); + let schema = self.host_schemas[userdata] + .as_ref() + .unwrap_or_else(|| panic!("{}: fault has no program schema", self.arm.label())); + assert_eq!( + schema.return_type, + HostTypeSchema::Resource(LuaUserdataResource::key()), + "{}: the userdata return must stay a typed resource", + self.arm.label() + ); + } + + fn assert_typed_local(&self) { + let slot = self + .patch + .typed_local + .unwrap_or_else(|| panic!("{}: no typed local", self.arm.label())); + assert_eq!( + self.patch.declared_schema, + Some(typed_callable_schema()), + "{}: the generated typed local must declare the callable schema", + self.arm.label() + ); + assert!( + self.patch.call.is_some() || self.patch.omitted, + "{}: the typed local must be the one the call node uses", + self.arm.label() + ); + // This pin records a compiled local schema only for the slots it walks + // as statement bindings, so the annotation generated inside `parent` is + // proven by the retargeted `CallValue` instead. The typed resource local + // is recorded, and it is the independent compile-time check that the + // userdata carrier is a real `lua.userdata` value. + let resource_locals: Vec = self + .local_schemas + .iter() + .enumerate() + .filter(|(_, schema)| { + schema.as_ref() == Some(&TypeSchema::Resource(LuaUserdataResource::key())) + }) + .map(|(slot, _)| slot) + .collect(); + assert_eq!( + resource_locals.len(), + 1, + "{}: exactly one local must carry the typed userdata schema, saw {resource_locals:?}", + self.arm.label() + ); + eprintln!( + "LUA_ACTIVE_TYPED arm={} typed_local={slot} resource_locals={resource_locals:?}", + self.arm.label() + ); + } + + fn prototype(&self, id: u32) -> &vm::CallablePrototype { + self.prototypes + .get(id as usize) + .unwrap_or_else(|| panic!("{}: prototype {id} is missing", self.arm.label())) + } + + fn assert_two_parameter_script_prototype(&self, id: u32) { + let prototype = self.prototype(id); + assert_eq!( + prototype.arity, + CALL_ARGC, + "{}: the callable must be a two-parameter Lua function", + self.arm.label() + ); + assert_eq!( + prototype.schema, + Some(typed_callable_schema()), + "{}: the compiled callable prototype schema", + self.arm.label() + ); + assert_eq!( + prototype.parameter_slots.len(), + usize::from(CALL_ARGC), + "{}: the compiled formal parameter slots", + self.arm.label() + ); + assert!( + matches!(prototype.target, vm::CallableTarget::ScriptFunction(_)), + "{}: the executed callable must be a script function", + self.arm.label() + ); + } +} + +fn same_callable(left: &Value, right: &Value) -> bool { + match (left, right) { + (Value::Callable(left), Value::Callable(right)) => Arc::ptr_eq(left, right), + _ => false, + } +} + +fn same_array(left: &Value, right: &Value) -> bool { + match (left, right) { + (Value::Array(left), Value::Array(right)) => Arc::ptr_eq(left, right), + _ => false, + } +} + +fn callable_id(value: &Value) -> u32 { + match value { + Value::Callable(callable) => callable.prototype_id, + other => panic!("expected a callable, got {other:?}"), + } +} + +/// Binds the executed callee marker to the one decoded `CallValue` whose +/// successor is that child frame's resume address and whose owner is the +/// active parent frame. +fn assert_resumed_call_site(run: &ArmRun, child_label: &str) -> (usize, u32) { + let child = run.mark(child_label); + let caller = child + .parent_prototype + .expect("the callee marker must have a caller frame"); + let return_ip = child + .last_return_ip + .expect("the callee marker must resume through a CallValue"); + let matching: Vec<_> = run + .call_sites + .iter() + .filter(|site| { + site.owner == Some(caller) && site.return_ip == return_ip && site.argc == CALL_ARGC + }) + .collect(); + assert_eq!( + matching.len(), + 1, + "{}: expected exactly one executed CallValue(owner={caller:?}, return_ip={return_ip}, argc={CALL_ARGC}); sites={:?}", + run.arm.label(), + run.call_sites + ); + let site = matching[0]; + assert_eq!( + site.ip + 2, + site.return_ip, + "{}: CallValue carries one argc operand byte", + run.arm.label() + ); + (return_ip, caller) +} + +fn assert_receiver_and_token(run: &ArmRun) { + let callee = run.callee(); + assert_eq!( + callee.ordinary_array_class, + "Unissued", + "{}: an ordinary array must not be the issued table", + run.arm.label() + ); + assert!( + callee.receiver_class.starts_with("Table("), + "{}: the receiver must be the issued heap table, saw {}", + run.arm.label(), + callee.receiver_class + ); + assert_eq!( + callee.receiver_class, + format!( + "{:?}", + GuestClass::Table( + run.witness + .issued_table_ref + .expect("the issued table handle must stay live") + ) + ), + "{}: the callee's receiver must be the same live heap table", + run.arm.label() + ); + let issued_table = run + .witness + .issued_table + .as_ref() + .unwrap_or_else(|| panic!("{}: no issued table", run.arm.label())); + assert!( + same_array( + &callee.parameter_values[0].clone().expect("receiver slot"), + issued_table + ), + "{}: the callee must receive the original issued table carrier", + run.arm.label() + ); + let issued_userdata = run + .witness + .issued_userdata + .as_ref() + .unwrap_or_else(|| panic!("{}: no issued userdata", run.arm.label())); + let issued_parts = ( + issued_userdata.domain(), + issued_userdata.slot(), + issued_userdata.generation(), + ); + assert_eq!( + callee.token_parts, + issued_parts, + "{}: the Core borrow must name the issued userdata", + run.arm.label() + ); + assert_eq!( + callee.rebound_parts, + issued_parts, + "{}: the heap borrow must name the same userdata", + run.arm.label() + ); + assert!( + callee.table_token_refused, + "{}: the same handle must be refused as a lua.table token", + run.arm.label() + ); + assert_eq!( + callee.parameter_values[1], + Some(Value::Int( + run.witness + .issued_userdata_raw + .expect("the fixture issued one userdata") + )), + "{}: the callee must receive the issued token carrier", + run.arm.label() + ); +} + +fn assert_formal_slots(run: &ArmRun) { + let callee = run.callee(); + let child_prototype = run.prototype(callee.prototype_id); + assert_eq!( + callee.parameter_slots, + child_prototype.parameter_slots, + "{}: the witness must read the declared callee slots", + run.arm.label() + ); + assert_eq!( + callee.parameter_values.len(), + usize::from(CALL_ARGC), + "{}: the callee must declare two formal slots", + run.arm.label() + ); + assert!( + callee.parameter_values[0] + .as_ref() + .is_some_and(|value| same_array( + value, + run.witness.issued_table.as_ref().expect("issued table") + )), + "{}: the first formal slot must hold the receiver carrier", + run.arm.label() + ); + assert!( + callee.local_count > 0, + "{}: the callee frame must be non-empty", + run.arm.label() + ); + assert!( + callee.local_base > 0, + "{}: the callee frame must sit above the chunk frame", + run.arm.label() + ); +} + +// ---- the arms ------------------------------------------------------------- + +#[test] +fn active_parent_invokes_typed_host_returned_callable() { + let positive = run_arm(Arm::Positive); + assert_positive(&positive); + + let omitted = run_arm(Arm::OmitCall); + assert_omit_control(&positive, &omitted); + + let other = run_arm(Arm::OtherInstance); + assert_other_instance_control(&positive, &other); + + let signature = run_arm(Arm::OtherSignature); + assert_signature_control(&signature); + + let capture = run_arm(Arm::OtherCapture); + assert_same_prototype_capture_control(&capture); + + assert_declared_schema_is_checked(); + assert_unadmitted_call_is_refused(); +} + +/// The real lowerer still refuses a dynamic call whose callee is a local bound +/// from a host return. This is why the witness generates one typed local and +/// one call node instead of relaxing the admission rule, and it is a real +/// compile-layer refusal of the same catalog and the same plugin. +fn assert_unadmitted_call_is_refused() { + let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests") + .join("fixtures") + .join("luajit") + .join("finalizer") + .join(UNADMITTED_FIXTURE); + let options = CompileSourceFileOptions::new() + .with_source_plugin(&CALL_PLUGIN) + .with_host_api_catalog(Arc::clone(active_catalog())); + let error = vm::compile_source_file_with_options(&path, options) + .err() + .unwrap_or_else(|| panic!("the unadmitted dynamic call must be refused at lowering")); + let detail = match &error { + SourcePathError::SourceWithMap { + error: SourceError::Parse(parse), + .. + } + | SourcePathError::Source(SourceError::Parse(parse)) => parse.message.clone(), + other => panic!("unadmitted: expected a lowering refusal, got {other:?}"), + }; + eprintln!("LUA_ACTIVE_TYPED arm=unadmitted refusal={detail}"); + assert!( + detail.contains("not a Lua function binding or admitted parameter"), + "unadmitted: expected the Lua-provenance refusal, got {detail}" + ); +} + +/// The generated typed local is not decoration: Core typing checks the +/// declared callable schema against the value the host returns and validates +/// the retargeted call's argument list against it. Declaring three parameters +/// for the same node is refused at compile time, before any VM exists. +fn assert_declared_schema_is_checked() { + *PATCH.lock().expect("active typed patch report") = None; + let options = CompileSourceFileOptions::new() + .with_source_plugin(&SCHEMA_PLUGIN) + .with_host_api_catalog(Arc::clone(active_catalog())); + let path = fixture_path(); + let error = vm::compile_source_file_with_options(&path, options) + .err() + .unwrap_or_else(|| { + panic!("a three-parameter typed local must refuse the two-parameter callable") + }); + let detail = match &error { + SourcePathError::SourceWithMap { + error: SourceError::Compile(compile), + .. + } + | SourcePathError::Source(SourceError::Compile(compile)) => format!("{compile:?}"), + other => panic!("schema-mismatch: expected a compile-layer refusal, got {other:?}"), + }; + eprintln!("LUA_ACTIVE_TYPED arm=schema-mismatch compile-error={detail}"); + assert!( + detail.contains("declared as schema type"), + "schema-mismatch: expected the declared-schema refusal, got {detail}" + ); + let patch = PATCH + .lock() + .expect("active typed patch report") + .clone() + .unwrap_or_else(|| panic!("schema-mismatch: the plugin produced no patch report")); + assert_eq!( + patch.declared_schema, + Some(typed_callable_schema_with(3)), + "schema-mismatch: the plugin must have declared the three-parameter schema" + ); +} + +fn assert_positive(run: &ArmRun) { + run.assert_fuel(); + run.assert_typed_import(); + run.assert_typed_local(); + assert!( + matches!(run.status, Ok(VmStatus::Halted)), + "positive: the parent must run to a normal halt, got {:?}", + run.status + ); + assert_eq!( + run.labels(), + ["parent-enter", "mode", "parent-tag", "parent-after", "done"], + "positive: the callee must run between the parent's own markers" + ); + let values = run.exit().unwrap_or_else(|| { + panic!( + "positive: expected the chunk completion, got {:?}", + run.status + ) + }); + assert_eq!(values.len(), 8, "positive: [true] plus seven values"); + let selected = &values[1]; + let decoy = &values[2]; + let other = &values[3]; + let first = &values[4]; + let second = &values[5]; + let receiver = &values[6]; + let userdata = &values[7]; + assert!( + same_callable(other, &run.pick().other), + "positive: 'other' is the guest control instance" + ); + assert!( + !same_callable(other, decoy), + "positive: the two chunk-level functions are distinct instances" + ); + assert!( + same_callable(selected, decoy), + "positive: the typed host must return the original guest callable" + ); + assert!( + same_callable(first, &run.pick().first), + "positive: 'first' is the guest instance" + ); + assert!( + same_callable(second, &run.pick().second), + "positive: 'second' is the guest instance" + ); + assert!( + !same_callable(first, second), + "positive: the two written instances must stay distinct" + ); + assert_eq!( + callable_id(first), + callable_id(second), + "positive: both nested instances come from one prototype" + ); + // This pin records a compiled callable schema for the chunk-level function + // bindings only. The nested `callback` prototype therefore carries none and + // can never be handed through a typed callable return: that is a compiled + // fact of this pin, recorded here instead of assumed. + assert_eq!( + run.prototype(callable_id(first)).schema, + None, + "positive: a nested closure prototype carries no compiled callable schema" + ); + + // The executed callee is the value the host returned, and it is the same + // Arc the parent's own first parameter slot still holds. + let executed = run.callee().prototype_id; + assert_eq!( + callable_id(selected), + executed, + "positive: the executed frame must be the returned callable" + ); + let held = run + .callee() + .caller_callable + .as_ref() + .unwrap_or_else(|| panic!("positive: the parent's first parameter is empty")); + assert!( + same_callable(held, selected), + "positive: the parent's held argument must be the returned callable" + ); + let held_slot = run + .mark("parent-enter") + .last_prototype + .and_then(|id| run.prototype(id).parameter_slots.first().copied()); + assert_eq!( + run.callee().caller_declared_slot, + held_slot, + "positive: the held argument is the parent's first declared slot" + ); + + assert_receiver_and_token(run); + assert_formal_slots(run); + run.assert_two_parameter_script_prototype(executed); + let (return_ip, caller) = assert_resumed_call_site(run, "parent-tag"); + assert!(return_ip > 0, "positive: the resume address is real"); + assert_eq!( + run.mark("parent-enter").last_prototype, + Some(caller), + "positive: the parent's own marker names the caller prototype" + ); + assert_eq!( + run.mark("parent-enter").frame_len + 1, + run.mark("parent-tag").frame_len, + "positive: the callee frame is one below the parent" + ); + assert_eq!( + run.mark("parent-after").frame_len, + run.mark("parent-enter").frame_len, + "positive: the parent resumes at its own depth" + ); + assert_eq!( + run.mark("done").parent_prototype, + None, + "positive: the chunk marker has no caller" + ); + let call = run + .patch + .call + .as_ref() + .unwrap_or_else(|| panic!("positive: the call node was not patched")); + assert_eq!(call.argc, CALL_ARGC); + assert_ne!( + call.written_callee, call.typed_callee, + "positive: the callee slot must be retargeted" + ); + assert_eq!( + call.arg_slots, + vec![ + run.patch.parent_parameters[PARENT_RECEIVER_SLOT], + run.patch.parent_parameters[PARENT_USERDATA_SLOT], + ], + "positive: the call still passes the declared receiver and userdata slots" + ); + assert_ne!( + call.completion_slot, call.typed_callee, + "positive: the completion slot is the call result, not the callee" + ); + assert!( + !run.patch.omitted, + "positive: the call statement must be present" + ); + assert!( + same_array( + receiver, + &run.witness.issued_table.clone().expect("issued table") + ), + "positive: the chunk returns the issued table carrier" + ); + assert_eq!( + userdata, + &Value::Int( + run.witness + .issued_userdata_raw + .expect("the fixture issued one userdata") + ), + "positive: the chunk returns the issued token" + ); +} + +fn assert_omit_control(positive: &ArmRun, omitted: &ArmRun) { + omitted.assert_fuel(); + omitted.assert_typed_import(); + omitted.assert_typed_local(); + assert!( + matches!(omitted.status, Ok(VmStatus::Halted)), + "omit: the parent still runs to a normal halt, got {:?}", + omitted.status + ); + assert!( + omitted.patch.omitted, + "omit: the call statement must be omitted" + ); + assert_eq!( + omitted.labels(), + ["parent-enter", "mode", "parent-after", "done"], + "omit: no callee marker may appear while the typed getter still ran" + ); + assert_eq!( + omitted.witness.picks.len(), + 1, + "omit: the typed host still ran exactly once" + ); + assert!( + omitted + .witness + .marks + .iter() + .all(|mark| mark.callee.is_none()), + "omit: no callee frame may observe the arguments" + ); + let values = omitted + .exit() + .unwrap_or_else(|| panic!("omit: expected the chunk completion")); + assert_eq!(values.len(), 8, "omit: the same chunk shape"); + assert!( + same_callable(&values[1], &values[2]), + "omit: the typed local still holds the original guest callable" + ); + assert_eq!( + positive.patch.call.as_ref().map(|call| call.typed_callee), + omitted.patch.typed_local, + "omit and positive must bind the same typed local" + ); + assert_eq!( + omitted.patch.call.as_ref().map(|call| call.argc), + Some(CALL_ARGC), + "omit: the omitted node was the same two-argument call" + ); +} + +fn assert_other_instance_control(positive: &ArmRun, other: &ArmRun) { + other.assert_fuel(); + other.assert_typed_import(); + other.assert_typed_local(); + assert!( + matches!(other.status, Ok(VmStatus::Halted)), + "other-instance: the call still runs to a normal halt, got {:?}", + other.status + ); + assert_eq!( + other.labels(), + ["parent-enter", "mode", "other-tag", "parent-after", "done"], + "other-instance: the callee frame still runs and reports its own capture" + ); + let values = other + .exit() + .unwrap_or_else(|| panic!("other-instance: expected the chunk completion")); + let selected = &values[1]; + let decoy = &values[2]; + let written_other = &values[3]; + assert!( + !same_callable(selected, decoy), + "other-instance: another real callable must not pass the original-instance assertion" + ); + assert!( + same_callable(selected, written_other), + "other-instance: the host returned the written control instance" + ); + assert_eq!( + other.callee().prototype_id, + callable_id(selected), + "other-instance: the executed callee is the returned instance" + ); + // Both chunk-level functions carry the same compiled callable schema and + // arity, so the return check accepts both and only pointer identity + // separates them. + other.assert_two_parameter_script_prototype(callable_id(selected)); + other.assert_two_parameter_script_prototype(callable_id(decoy)); + assert_ne!( + callable_id(selected), + callable_id(decoy), + "other-instance: the two accepted callables are different prototypes" + ); + assert_eq!( + other.callee_mark().label, + "other-tag", + "other-instance: the capture of the selected instance must be observed" + ); + assert_eq!( + positive.callee_mark().label, + "parent-tag", + "positive: the capture of the original instance must be observed" + ); + assert_ne!( + positive.callee_mark().label, + other.callee_mark().label, + "the two accepted instances must differ by captured value" + ); + assert!( + !same_callable(selected, &positive.pick().chosen), + "other-instance: the selection must differ from the positive selection" + ); + assert_eq!( + other.callee().parameter_values.len(), + usize::from(CALL_ARGC), + "other-instance: the same two formal slots receive the arguments" + ); + assert_receiver_and_token(other); +} + +fn assert_signature_control(run: &ArmRun) { + run.assert_fuel(); + run.assert_typed_import(); + run.assert_typed_local(); + match &run.status { + Err(VmError::TypeMismatch(kind)) => assert_eq!( + *kind, "callable", + "other-signature: the callable return check must refuse the value" + ), + other => { + panic!("other-signature: expected the Core callable type refusal, got {other:?}") + } + } + assert!( + run.witness.marks.iter().all(|mark| mark.callee.is_none()), + "other-signature: no callee frame may run" + ); + assert_eq!( + run.labels(), + ["parent-enter", "mode"], + "other-signature: the parent stops at the typed host return" + ); + let pick = run.pick(); + assert_eq!( + pick.prototype_id, + callable_id(&pick.chosen), + "other-signature: the refused value is the written single-parameter instance" + ); + assert_eq!( + run.prototype(pick.prototype_id).arity, + 1, + "other-signature: the refused callable has one parameter" + ); +} + +/// The host actually selects the other capture of the factory pair. `first` +/// and `second` are two instances of `make`'s one nested `callback` prototype, +/// so the selected value is a real sibling instance, not the chunk-level +/// `decoy` or `other` control. This pin attaches no compiled callable schema to +/// a nested closure prototype, so the exact typed return check refuses the +/// selected instance with the Core callable type error and the guest call never +/// starts. The host-selected same-prototype call is therefore not achieved +/// here; the arm records the pinned diagnostic instead of presenting the pair +/// as an executed control. +fn assert_same_prototype_capture_control(run: &ArmRun) { + run.assert_fuel(); + run.assert_typed_import(); + run.assert_typed_local(); + + // The host was handed both factory instances and really selected `second`. + let pick = run.pick(); + assert_eq!( + pick.mode, 3, + "other-capture: the staged arm must select the factory sibling" + ); + assert!( + same_callable(&pick.chosen, &pick.second), + "other-capture: the host must select the second factory instance itself" + ); + assert!( + !same_callable(&pick.chosen, &pick.first), + "other-capture: the selected value must be the other capture of the pair" + ); + assert!( + !same_callable(&pick.first, &pick.second), + "other-capture: the two factory instances must stay distinct Arcs" + ); + assert_eq!( + callable_id(&pick.first), + callable_id(&pick.second), + "other-capture: both factory instances must share one nested prototype" + ); + + // The pinned compile-time fact that refuses the typed return: the nested + // prototype is a real two-parameter script function with no compiled + // callable schema. + let prototype = run.prototype(pick.prototype_id); + assert_eq!( + prototype.arity, CALL_ARGC, + "other-capture: the refusal must not be an arity mismatch" + ); + assert_eq!( + prototype.schema, None, + "other-capture: this pin attaches no callable schema to a nested closure prototype" + ); + assert!( + matches!(prototype.target, vm::CallableTarget::ScriptFunction(_)), + "other-capture: the selected instance must still be a real Lua function" + ); + + // The selected instance never becomes guest-visible: the exact typed return + // check refuses it at the host boundary, so no call node of this run is + // executed with it. + match &run.status { + Err(VmError::TypeMismatch(kind)) => assert_eq!( + *kind, "callable", + "other-capture: the typed return check must refuse the nested callable" + ), + other => { + panic!("other-capture: expected the Core callable type refusal, got {other:?}") + } + } + assert_eq!( + run.labels(), + ["parent-enter", "mode"], + "other-capture: the parent must stop at the typed host return" + ); + assert!( + run.witness.marks.iter().all(|mark| mark.callee.is_none()), + "other-capture: no callee frame may run for the refused instance" + ); + assert!( + run.exit().is_none(), + "other-capture: the failed run must have no chunk completion" + ); + eprintln!( + "LUA_ACTIVE_TYPED arm=other-capture control=not-achieved same_prototype={} chosen_is_second=1 refusal=TypeMismatch(callable)", + callable_id(&pick.chosen) + ); +} diff --git a/tests/compiler/compiler_lua_completion_tests/active_typed_callback_root_retirement.rs b/tests/compiler/compiler_lua_completion_tests/active_typed_callback_root_retirement.rs new file mode 100644 index 0000000..f9a72fe --- /dev/null +++ b/tests/compiler/compiler_lua_completion_tests/active_typed_callback_root_retirement.rs @@ -0,0 +1,748 @@ +//! Synchronous `CallValue(2)` returns `Bool`, `parent-after` still borrows A, +//! and an exact `retire` import then calls `leave_roots` on this commit's full +//! `RootFrameId`. The import does not collect and does not advance a phase. +//! `sweep` is the later guest collection. `done` only observes. +//! +//! The omission arm reaches the same `sweep` and cleans the same kind of +//! unrooted weak orphan, but it never calls `retire`, so A and the commit +//! root frame stay. The commit witness keeps a strong callable, and B stays +//! reachable through the raw `__call` edge. This file does not claim that Arc +//! has retired. + +use vm::{CallOutcome, CallReturn, ResourceHandle, Value, Vm, VmError, VmStatus}; + +use crate::heap::{self, GuestClass, LuaUserdataResource, TableRef, UserdataRef}; + +use super::{ + Arm, ArmRun, host_fault_error, published_commit, published_pending, published_prepared, + published_slot_generation, published_userdata_alive, raw_handle, run_arm, +}; + +const RETIRE_MODE: i64 = 12; +const ORPHAN_KEY: f64 = 2.0; +const CLEARED_PREPARE_KEY: f64 = 1.0; + +#[derive(Clone, Debug)] +struct ExitRecord { + frame: heap::RootFrameId, + prepare_frame: heap::RootFrameId, + top_before: heap::RootFrameId, + top_after: heap::RootFrameId, + roots_before: u32, + roots_after: u32, + collections_before: u32, + collections_after: u32, + scan_before: heap::ScanMeter, + scan_after: heap::ScanMeter, + tail_before: bool, + tail_after: bool, + mark_before: bool, + mark_after: bool, + token_open_before: bool, + borrowed_userdata: UserdataRef, + weak_before: TableRef, + receiver_before: TableRef, + sentinel_before: TableRef, + weak_after: TableRef, + receiver_after: TableRef, + sentinel_after: TableRef, + stale_userdata: bool, + stale_closure: bool, + stale_receiver: bool, +} + +#[derive(Clone, Debug)] +struct SweepRecord { + orphan: TableRef, + orphan_rooted: bool, + roots_before: u32, + roots_after_create: u32, + collections_before: u32, + collections_after: u32, + weak_cleared: bool, + prepare_key_still_null: bool, + orphan_dead: bool, +} + +#[derive(Clone, Debug, Default)] +struct RetirementScope { + exit: Option, + sweep: Option, +} + +fn with_retirement( + vm: &mut Vm, + body: impl FnOnce(&mut RetirementScope) -> T, +) -> vm::VmResult { + let mut host = vm.host_context(); + if host.scope_state::().is_none() { + host.scope_state_or_insert_with(RetirementScope::default) + .map_err(|error| host_fault_error(format!("retirement scope: {error:?}")))?; + } + let scope = host + .scope_state_mut::() + .ok_or_else(|| host_fault_error("retirement scope was not installed"))?; + Ok(body(scope)) +} + +fn heap_fault(error: heap::HeapError) -> VmError { + super::heap_fault(error) +} + +/// Exact exit import. Confirms the three commit roots and the live token, then +/// calls `leave_roots` on the successful commit's full frame id. It does not +/// collect, step, or clear a root. +pub(super) fn host_retire(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + if !args.is_empty() { + return Err(host_fault_error("retire takes no arguments")); + } + let prepared = super::with_run_scope(vm, |scope| scope.witness.prepared.clone()) + .ok_or_else(|| host_fault_error("retire requires the prepared published head"))?; + let commit = super::with_run_scope(vm, |scope| { + scope + .witness + .commits + .iter() + .rev() + .find(|commit| commit.outcome.is_ok()) + .cloned() + }) + .ok_or_else(|| host_fault_error("retire requires this run's successful commit"))?; + let (frame, roots_written) = commit.outcome.clone().map_err(|error| { + host_fault_error(format!("retire requires a successful commit, got {error}")) + })?; + if roots_written != 3 { + return Err(host_fault_error( + "retire requires the commit that wrote exactly three roots", + )); + } + + let mut host = vm.host_context(); + let tail_before = heap::with_heap(&mut host, |heap| Ok(heap.saved_tail_state().is_some())) + .map_err(heap_fault)?; + if tail_before { + return Err(host_fault_error( + "retire refuses a saved tail; it does not finish or advance one", + )); + } + let mark_before = heap::saved_mark_watch(&host).is_some(); + if mark_before { + return Err(host_fault_error( + "retire refuses a saved mark; it does not advance a phase", + )); + } + let stats_before = heap::with_heap(&mut host, |heap| Ok(heap.stats())).map_err(heap_fault)?; + let scan_before = + heap::with_heap(&mut host, |heap| Ok(heap.scan_meter())).map_err(heap_fault)?; + let top_before = heap::with_heap(&mut host, |heap| Ok(heap.current_frame())) + .map_err(heap_fault)? + .ok_or_else(|| host_fault_error("retire requires a current root frame"))?; + if top_before != frame { + return Err(host_fault_error( + "retire only leaves the current top frame, which must be this commit", + )); + } + let rooted_user = heap::with_heap(&mut host, |heap| Ok(heap.rooted_userdata(frame, 0))) + .map_err(heap_fault)? + .map_err(heap_fault)?; + let rooted_closure = heap::with_heap(&mut host, |heap| Ok(heap.rooted_closure(frame, 1))) + .map_err(heap_fault)? + .map_err(heap_fault)?; + let rooted_receiver = heap::with_heap(&mut host, |heap| Ok(heap.rooted_table(frame, 2))) + .map_err(heap_fault)? + .map_err(heap_fault)?; + if rooted_user != Some(prepared.userdata) { + return Err(host_fault_error( + "the commit frame's first root is not the live userdata A", + )); + } + let Some(closure) = rooted_closure else { + return Err(host_fault_error("the commit frame's closure root is empty")); + }; + if (closure.domain(), closure.slot(), closure.generation()) != commit.action_closure { + return Err(host_fault_error( + "the commit frame's closure root is not the committed raw action", + )); + } + if rooted_receiver != Some(prepared.receiver) { + return Err(host_fault_error( + "the commit frame's receiver root is not the prepared receiver", + )); + } + let weak_before = heap::with_heap(&mut host, |heap| { + Ok(heap.rooted_table(prepared.root_frame, 0)) + }) + .map_err(heap_fault)? + .map_err(heap_fault)?; + let receiver_before = heap::with_heap(&mut host, |heap| { + Ok(heap.rooted_table(prepared.root_frame, 1)) + }) + .map_err(heap_fault)? + .map_err(heap_fault)?; + let sentinel_before = heap::with_heap(&mut host, |heap| { + Ok(heap.rooted_table(prepared.root_frame, 2)) + }) + .map_err(heap_fault)? + .map_err(heap_fault)?; + if weak_before != Some(prepared.weak_table) + || receiver_before != Some(prepared.receiver) + || sentinel_before != Some(prepared.sentinel) + { + return Err(host_fault_error( + "the prepare frame does not still hold the weak table, receiver, and sentinel", + )); + } + // End this host borrow before the next host_context() call. + { + let _host = host; + } + + let borrowed_userdata = { + let host = vm.host_context(); + let borrowed = host + .borrow_resource_with_key::( + raw_handle(prepared.userdata_raw)?, + &LuaUserdataResource::key(), + ) + .map_err(|error| { + host_fault_error(format!("A token must still borrow before retire: {error}")) + })?; + borrowed.get().userdata() + }; + if borrowed_userdata != prepared.userdata { + return Err(host_fault_error( + "the live token borrow does not name userdata A", + )); + } + + let mut host = vm.host_context(); + heap::with_heap(&mut host, |heap| heap.leave_roots(frame)).map_err(heap_fault)?; + let tail_after = heap::with_heap(&mut host, |heap| Ok(heap.saved_tail_state().is_some())) + .map_err(heap_fault)?; + let mark_after = heap::saved_mark_watch(&host).is_some(); + let stats_after = heap::with_heap(&mut host, |heap| Ok(heap.stats())).map_err(heap_fault)?; + let scan_after = + heap::with_heap(&mut host, |heap| Ok(heap.scan_meter())).map_err(heap_fault)?; + let top_after = heap::with_heap(&mut host, |heap| Ok(heap.current_frame())) + .map_err(heap_fault)? + .ok_or_else(|| host_fault_error("leave_roots left no prepare frame"))?; + if top_after != prepared.root_frame { + return Err(host_fault_error( + "leave_roots must reveal the prepare frame as the new top", + )); + } + if stats_after.root_slots != stats_before.root_slots - 3 { + return Err(host_fault_error(format!( + "leave_roots must shorten the root vector by exactly three, {} -> {}", + stats_before.root_slots, stats_after.root_slots + ))); + } + if stats_after.collections != stats_before.collections || scan_after != scan_before { + return Err(host_fault_error( + "leave_roots collected or advanced a scan; this import must not", + )); + } + if tail_after || mark_after { + return Err(host_fault_error( + "leave_roots saved a tail or a mark; this import must not", + )); + } + let stale_userdata = heap::with_heap(&mut host, |heap| Ok(heap.rooted_userdata(frame, 0))) + .map_err(heap_fault)?; + let stale_closure = + heap::with_heap(&mut host, |heap| Ok(heap.rooted_closure(frame, 1))).map_err(heap_fault)?; + let stale_receiver = + heap::with_heap(&mut host, |heap| Ok(heap.rooted_table(frame, 2))).map_err(heap_fault)?; + if !matches!(stale_userdata, Err(heap::HeapError::StaleFrame)) + || !matches!(stale_closure, Err(heap::HeapError::StaleFrame)) + || !matches!(stale_receiver, Err(heap::HeapError::StaleFrame)) + { + return Err(host_fault_error( + "the retired commit frame is still readable", + )); + } + let weak_after = heap::with_heap(&mut host, |heap| { + Ok(heap.rooted_table(prepared.root_frame, 0)) + }) + .map_err(heap_fault)? + .map_err(heap_fault)?; + let receiver_after = heap::with_heap(&mut host, |heap| { + Ok(heap.rooted_table(prepared.root_frame, 1)) + }) + .map_err(heap_fault)? + .map_err(heap_fault)?; + let sentinel_after = heap::with_heap(&mut host, |heap| { + Ok(heap.rooted_table(prepared.root_frame, 2)) + }) + .map_err(heap_fault)? + .map_err(heap_fault)?; + if weak_after != weak_before + || receiver_after != receiver_before + || sentinel_after != sentinel_before + { + return Err(host_fault_error( + "leave_roots changed the prepare frame's weak table, receiver, or sentinel", + )); + } + let record = ExitRecord { + frame, + prepare_frame: prepared.root_frame, + top_before, + top_after, + roots_before: stats_before.root_slots, + roots_after: stats_after.root_slots, + collections_before: stats_before.collections, + collections_after: stats_after.collections, + scan_before, + scan_after, + tail_before, + tail_after, + mark_before, + mark_after, + token_open_before: true, + borrowed_userdata, + weak_before: weak_before.expect("weak before"), + receiver_before: receiver_before.expect("receiver before"), + sentinel_before: sentinel_before.expect("sentinel before"), + weak_after: weak_after.expect("weak after"), + receiver_after: receiver_after.expect("receiver after"), + sentinel_after: sentinel_after.expect("sentinel after"), + stale_userdata: true, + stale_closure: true, + stale_receiver: true, + }; + // End this host borrow before the next host_context() call. + { + let _host = host; + } + with_retirement(vm, |scope| { + scope.exit = Some(record); + })?; + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))) +} + +/// Guest collection after the parent returns. Creates one weak orphan, does +/// not root it, and runs the real collector. It does not call `leave_roots` +/// or `clear_root`. +pub(super) fn host_sweep(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + if !args.is_empty() { + return Err(host_fault_error("sweep takes no arguments")); + } + let prepared = super::with_run_scope(vm, |scope| scope.witness.prepared.clone()) + .ok_or_else(|| host_fault_error("sweep requires the prepared published head"))?; + let mut host = vm.host_context(); + if heap::with_heap(&mut host, |heap| Ok(heap.saved_tail_state().is_some())) + .map_err(heap_fault)? + { + return Err(host_fault_error( + "sweep refuses a saved tail; the guest path collects only when sweep is open", + )); + } + let roots_before = + heap::with_heap(&mut host, |heap| Ok(heap.stats().root_slots)).map_err(heap_fault)?; + let collections_before = + heap::with_heap(&mut host, |heap| Ok(heap.stats().collections)).map_err(heap_fault)?; + let orphan = { + let value = heap::publish_guest(&mut host).map_err(heap_fault)?; + let class = + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&value))).map_err(heap_fault)?; + let GuestClass::Table(orphan) = class else { + return Err(host_fault_error( + "the guest orphan must be an issued heap table", + )); + }; + orphan + }; + if orphan == prepared.weak_table || orphan == prepared.receiver || orphan == prepared.sentinel { + return Err(host_fault_error( + "the guest orphan must be a new table, not an already rooted one", + )); + } + heap::with_heap(&mut host, |heap| heap.set_edge(orphan, 1, orphan)).map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| { + heap.set_number_edge(prepared.weak_table, ORPHAN_KEY, orphan) + }) + .map_err(heap_fault)?; + let roots_after_create = + heap::with_heap(&mut host, |heap| Ok(heap.stats().root_slots)).map_err(heap_fault)?; + let orphan_rooted = heap::current_frame_roots_table(&host, orphan); + if orphan_rooted || roots_after_create != roots_before { + return Err(host_fault_error( + "the guest orphan must not be entered into a root frame", + )); + } + let prepare_key = heap::with_heap(&mut host, |heap| { + heap.number_value(prepared.weak_table, CLEARED_PREPARE_KEY) + }) + .map_err(heap_fault)?; + // The guest path collects here, after the unrooted weak orphan exists and + // before done. This import does not leave roots. + heap::collect(&mut host).map_err(heap_fault)?; + let collections_after = + heap::with_heap(&mut host, |heap| Ok(heap.stats().collections)).map_err(heap_fault)?; + let weak_value = heap::with_heap(&mut host, |heap| { + heap.number_value(prepared.weak_table, ORPHAN_KEY) + }) + .map_err(heap_fault)?; + let prepare_after = heap::with_heap(&mut host, |heap| { + heap.number_value(prepared.weak_table, CLEARED_PREPARE_KEY) + }) + .map_err(heap_fault)?; + let orphan_dead = + heap::with_heap(&mut host, |heap| Ok(!heap.alive(orphan))).map_err(heap_fault)?; + let record = SweepRecord { + orphan, + orphan_rooted, + roots_before, + roots_after_create, + collections_before, + collections_after, + weak_cleared: weak_value == Value::Null, + prepare_key_still_null: prepare_key == Value::Null && prepare_after == Value::Null, + orphan_dead, + }; + // End this host borrow before the next host_context() call. + { + let _host = host; + } + with_retirement(vm, |scope| { + scope.sweep = Some(record); + })?; + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))) +} + +fn take_retirement(run: &mut ArmRun) -> RetirementScope { + let mut host = run.vm.host_context(); + host.take_scope_state::() + .unwrap_or_else(|| { + panic!( + "{}: the retirement scope was not installed", + run.arm.label() + ) + }) +} + +fn token_borrows(run: &mut ArmRun, raw: i64) -> bool { + let Ok(raw) = u64::try_from(raw) else { + return false; + }; + let Ok(handle) = ResourceHandle::from_raw(raw) else { + return false; + }; + let host = run.vm.host_context(); + host.borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + .is_ok() +} + +fn root_slots(run: &mut ArmRun) -> u32 { + let mut host = run.vm.host_context(); + heap::with_heap(&mut host, |heap| Ok(heap.stats().root_slots)).expect("root length") +} + +fn collections(run: &mut ArmRun) -> u32 { + let mut host = run.vm.host_context(); + heap::with_heap(&mut host, |heap| Ok(heap.stats().collections)).expect("collections") +} + +fn current_root(run: &mut ArmRun) -> Option { + let mut host = run.vm.host_context(); + heap::with_heap(&mut host, |heap| Ok(heap.current_frame())).expect("current frame") +} + +fn assert_halted(run: &ArmRun) { + assert!( + matches!(run.status, Ok(VmStatus::Halted)), + "{}: the script must halt, got {:?}", + run.arm.label(), + run.status + ); +} + +fn assert_call_value_two(run: &ArmRun) { + let parent = run + .mark("parent-enter") + .last_prototype + .unwrap_or_else(|| panic!("{}: parent-enter has no prototype", run.arm.label())); + let dynamic: Vec<_> = run + .call_sites + .iter() + .filter(|site| site.owner == Some(parent) && site.argc == 2) + .collect(); + assert_eq!( + dynamic.len(), + 1, + "{}: the parent has one dynamic call", + run.arm.label() + ); + assert_eq!( + dynamic[0].argc, + 2, + "{}: the dynamic call is CallValue(2)", + run.arm.label() + ); +} + +fn assert_parent_after_borrows_a(run: &ArmRun) { + let prepared = published_prepared(run); + let after = run.mark("parent-after"); + let probe = after.continuation.as_ref().unwrap_or_else(|| { + panic!( + "{}: parent-after did not borrow the argument token", + run.arm.label() + ) + }); + assert_eq!( + probe.raw, + prepared.userdata_raw, + "{}: parent-after borrowed a different token", + run.arm.label() + ); + assert_eq!( + probe.parts, + ( + prepared.userdata.domain(), + prepared.userdata.slot(), + prepared.userdata.generation(), + ), + "{}: parent-after's borrow is not userdata A", + run.arm.label() + ); +} + +fn assert_compiled_bool(run: &ArmRun, expected: bool) { + let slot = run.witness.call_result_slot.unwrap_or_else(|| { + panic!( + "{}: the compiled CallValue result was not stored in a frame local", + run.arm.label() + ) + }); + assert_eq!( + run.witness.call_result, + Some(Value::Bool(expected)), + "{}: the compiled call result slot {slot:?} does not hold the callback bool", + run.arm.label() + ); + assert!( + run.witness.host_true_beside_call, + "{}: a host import true must still sit beside the call result, or the slot check cannot tell them apart", + run.arm.label() + ); +} + +fn assert_sweep_cleaned_orphan(run: &mut ArmRun, sweep: &SweepRecord) { + assert!( + !sweep.orphan_rooted && sweep.roots_before == sweep.roots_after_create, + "{}: the weak orphan {:?} was rooted", + run.arm.label(), + sweep.orphan + ); + assert!( + sweep.weak_cleared && sweep.orphan_dead && sweep.prepare_key_still_null, + "{}: the guest collection did not clear the new weak orphan", + run.arm.label() + ); + assert_eq!( + sweep.collections_after, + sweep.collections_before + 1, + "{}: sweep must run exactly one real collection", + run.arm.label() + ); + assert_eq!( + collections(run), + sweep.collections_after, + "{}: a collection ran after the guest sweep or after Vm::run", + run.arm.label() + ); + assert_eq!( + root_slots(run), + sweep.roots_after_create, + "{}: roots changed after the guest sweep", + run.arm.label() + ); +} + +fn assert_b_stays(run: &mut ArmRun) { + let prepared = published_prepared(run).clone(); + let (callable_kept, action) = { + let commit = published_commit(run); + let callable_kept = matches!( + &commit.callable, + Value::Callable(arc) if std::sync::Arc::strong_count(arc) >= 1 + ); + (callable_kept, commit.action_closure) + }; + assert!( + callable_kept, + "{}: the commit witness must keep the strong callable; this is not an Arc retirement", + run.arm.label() + ); + let edge = super::heap_query(&mut run.vm, |heap| { + heap.named_closure_edge(prepared.receiver_metatable, "__call") + }); + assert_eq!( + (edge.domain(), edge.slot(), edge.generation()), + action, + "{}: B must stay reachable through the raw __call edge", + run.arm.label() + ); + assert_eq!( + published_slot_generation(run, prepared.successor), + prepared.successor.generation(), + "{}: B's generation changed", + run.arm.label() + ); + assert!( + token_borrows(run, prepared.successor_raw), + "{}: B's token must still borrow", + run.arm.label() + ); + assert_eq!( + published_pending(run), + vec![( + u64::try_from(prepared.successor_raw).expect("B token"), + prepared.successor.slot(), + prepared.successor.generation(), + )], + "{}: B must remain the pending head", + run.arm.label() + ); +} + +fn assert_exit_retired_only_the_commit_frame(run: &mut ArmRun, exit: &ExitRecord) { + let userdata = published_prepared(run).userdata; + assert_eq!(exit.top_before, exit.frame); + assert_eq!(exit.prepare_frame, published_prepared(run).root_frame); + assert_eq!(exit.top_after, exit.prepare_frame); + assert_eq!(exit.roots_after, exit.roots_before - 3); + assert_eq!(exit.collections_before, exit.collections_after); + assert_eq!(exit.scan_before, exit.scan_after); + assert!(!exit.tail_before && !exit.tail_after); + assert!(!exit.mark_before && !exit.mark_after); + assert!(exit.token_open_before); + assert_eq!(exit.borrowed_userdata, userdata); + assert!(exit.stale_userdata && exit.stale_closure && exit.stale_receiver); + assert_eq!(exit.weak_before, published_prepared(run).weak_table); + assert_eq!(exit.receiver_before, published_prepared(run).receiver); + assert_eq!(exit.sentinel_before, published_prepared(run).sentinel); + assert_eq!(exit.weak_after, exit.weak_before); + assert_eq!(exit.receiver_after, exit.receiver_before); + assert_eq!(exit.sentinel_after, exit.sentinel_before); + assert_eq!( + current_root(run), + Some(exit.prepare_frame), + "{}: the prepare frame must still be top after Vm::run; done must not clear roots", + run.arm.label() + ); + let mut host = run.vm.host_context(); + let stale = heap::with_heap(&mut host, |heap| Ok(heap.rooted_userdata(exit.frame, 0))) + .expect("retired frame read"); + assert!( + matches!(stale, Err(heap::HeapError::StaleFrame)), + "{}: the retired frame became readable after Vm::run", + run.arm.label() + ); +} + +fn assert_common_guest_path(run: &mut ArmRun) -> (Option, SweepRecord) { + assert_halted(run); + assert_eq!( + run.labels(), + ["parent-enter", "target-enter", "parent-after", "done"], + "{}: done is an observation mark after the call", + run.arm.label() + ); + assert_call_value_two(run); + assert_parent_after_borrows_a(run); + let scope = take_retirement(run); + let sweep = scope + .sweep + .clone() + .unwrap_or_else(|| panic!("{}: sweep did not run", run.arm.label())); + assert_sweep_cleaned_orphan(run, &sweep); + assert_b_stays(run); + (scope.exit, sweep) +} + +#[test] +fn synchronous_table_call_retires_the_commit_root_before_guest_collection() { + let mut run = run_arm(Arm::CallbackRootRetirement); + assert_eq!(i64::try_from(run.arm.select()).unwrap(), RETIRE_MODE); + let (exit, _sweep) = assert_common_guest_path(&mut run); + let exit = exit.expect("retirement: retire must run inside the parent frame"); + assert_exit_retired_only_the_commit_frame(&mut run, &exit); + assert_compiled_bool(&run, true); + let prepared = published_prepared(&run).clone(); + assert!( + !published_userdata_alive(&mut run, prepared.userdata), + "retirement: guest collection must drop A after the exit import" + ); + assert_eq!( + published_slot_generation(&mut run, prepared.userdata), + prepared.userdata.generation() + 1, + "retirement: A's slot generation must advance by one" + ); + assert!( + !token_borrows(&mut run, prepared.userdata_raw), + "retirement: A's real borrow must fail after the guest collection" + ); +} + +#[test] +fn omitted_exit_import_keeps_the_commit_root_through_guest_collection() { + let mut run = run_arm(Arm::CallbackRootOmission); + let (exit, sweep) = assert_common_guest_path(&mut run); + assert!(exit.is_none(), "omission: the exit import must not run"); + assert_compiled_bool(&run, true); + let prepared = published_prepared(&run).clone(); + let commit = published_commit(&run); + let frame = commit.outcome.clone().expect("omission commit").0; + assert!( + published_userdata_alive(&mut run, prepared.userdata), + "omission: A stays alive because the exit import was not called" + ); + assert_eq!( + published_slot_generation(&mut run, prepared.userdata), + prepared.userdata.generation(), + "omission: A's generation stays" + ); + assert!( + token_borrows(&mut run, prepared.userdata_raw), + "omission: A's token still borrows" + ); + assert_eq!( + current_root(&mut run), + Some(frame), + "omission: the commit root frame is still top" + ); + let rooted = { + let mut host = run.vm.host_context(); + heap::with_heap(&mut host, |heap| Ok(heap.rooted_userdata(frame, 0))) + .expect("omission frame read") + .expect("omission frame must still be readable") + }; + assert_eq!(rooted, Some(prepared.userdata)); + assert_eq!( + root_slots(&mut run), + sweep.roots_after_create, + "omission: sweep did not shorten the root vector" + ); +} + +#[test] +fn callback_bool_false_is_the_compiled_slot_not_a_host_true() { + let mut run = run_arm(Arm::CallbackRootFalseReturn); + assert_eq!(i64::try_from(run.arm.select()).unwrap(), RETIRE_MODE); + let (exit, _sweep) = assert_common_guest_path(&mut run); + let exit = exit.expect("false-return: the same exit import must run"); + assert_exit_retired_only_the_commit_frame(&mut run, &exit); + assert_compiled_bool(&run, false); + let prepared = published_prepared(&run).clone(); + assert!( + !published_userdata_alive(&mut run, prepared.userdata), + "false-return: the same exit import still retires A" + ); + assert!( + !token_borrows(&mut run, prepared.userdata_raw), + "false-return: A's real borrow fails after the same guest collection" + ); +} diff --git a/tests/compiler/compiler_lua_completion_tests/active_typed_resource_transport.rs b/tests/compiler/compiler_lua_completion_tests/active_typed_resource_transport.rs new file mode 100644 index 0000000..6891aba --- /dev/null +++ b/tests/compiler/compiler_lua_completion_tests/active_typed_resource_transport.rs @@ -0,0 +1,7626 @@ +//! Typed `resource` transport through a host-returned Lua callable. +//! +//! One real `.lua` file is fed through the real lexer, parser, resolver and +//! private completion lowering, compiled through the fixed Core and run in one +//! interpreter VM with JIT disabled. Every Lua function and host call is real. +//! The plugin makes four structural changes, all local to this test and none +//! touching a catalog schema: +//! +//! - it declares the exact callable schema on the two chunk-level closure +//! bindings, so their compiled prototypes carry it; +//! - it declares the exact callable schema on the typed local that holds the +//! callable the exact static host `note` returns, and retargets the one +//! dynamic call the real lowering produced onto that local; +//! - it rewrites the typed target's own return expression from the private +//! completion array to the `Bool` its declared signature names, because +//! Core validates a script call's real return against the prototype result; +//! - it uses the plain local read (identical codegen) for admitted callables +//! instead of the private lowerer's explicit `ToOwned` copy, because this +//! pin classifies a callable whose schema contains a resource as owned and +//! refuses `.copy()` on it; none of these callables is captured. +//! +//! The positive prototype is a real top-level zero-capture Lua closure whose +//! compiled prototype declares `(Array, Resource(lua.userdata)) -> Bool`. +//! `Array` is the actual shape of the issued LuaHeap carrier +//! (`[slot, generation]`, both `Int`), not `Unknown`. The import is registered +//! with `register_exact_static`, so the program carries that exact return +//! schema and Core's `validate_host_call_return`/`validate_callable_value` +//! accepts only a callable whose own prototype schema matches it. +//! +//! Witnessed in the positive run: +//! +//! - the host receives and returns the exact `SharedCallable` Arc the VM +//! produced for the guest binding (`Arc::ptr_eq` at the host boundary, in the +//! parent's `cb` slot and in a second parent-frame local); +//! - `CallValue(2)` enters a real script frame whose declared parameter slots +//! hold the original issued `Array` carrier and the original +//! `lua.userdata` token handle, bound to the decoded call site and resume +//! address; +//! - the child frame uses the formal typed resource API +//! (`ResourceHandle::from_raw` + `HostContext::borrow_resource_with_key::< +//! LuaUserdataResource>`) to read the payload, and the heap's published +//! handle also names the same userdata; +//! - the parent continuation re-borrows the same token in the same VM after +//! one script call and then returns its own `Bool` completion. +//! +//! Two separate runtime type controls share the same declarations: +//! +//! - `OtherResourceKey`: the host really selects `other_resource`, a real +//! top-level zero-capture closure with the same arity, receiver schema and +//! result, whose prototype declares the second parameter as the other legally +//! registered resource key (`lua.table`). The static host body runs, Core's +//! real return boundary refuses the callable with `TypeMismatch("callable")`, +//! and no callback frame starts. +//! - `OtherArgumentToken`: the correctly declared callable is returned and +//! invoked, but the actual second argument is a real registered `lua.table` +//! token. Core's real call entry refuses the operand with the resource key +//! `HostError` and no callback frame starts. +//! +//! Both controls compile successfully; neither is a compile-time schema +//! mismatch. The compile-time declaration check is covered by the retargeted +//! typed local itself, and the runtime layer is what produces these two +//! diagnostics. +//! +//! The callback entry is observed before any fallible work: every marker host +//! call first records the live last frame's actual prototype id, depth and +//! resume address. Marker records are still committed only after the typed +//! borrows, so the raw entry record is what preserves the evidence when a +//! probe fails after the frame really entered. The positive run has exactly +//! one entry into a declared two-parameter typed script callable; both +//! negative controls have none. +//! +//! Control B binds its diagnostic to the native +//! `resource_type_key_mismatch` error itself: the stable code, the +//! `resource::table` operation, the expected `lua.userdata` and actual +//! `lua.table` keys, and the raw handle of this run's issued `lua.table` +//! token. It is an exact native message, so any test probe wrapper (which +//! prefixes its own text) can no longer satisfy the assertion. +//! +//! Two more fixed-pin constraints are recorded here rather than hidden: the +//! completion status read `get(completion, 0)` cannot be typed for a callable +//! whose declared result is the required concrete `Bool` +//! (`builtin 'get' does not accept argument types (bool, int)`), so the parent +//! keeps the real call and continues after it without that status branch; and +//! Core's script-return check compares the target's real return value with the +//! prototype result, so the target returns `Bool(true)` instead of the +//! private completion array. The typed local, the exact import return schema +//! and both closure prototypes keep the exact signature: no `Unknown`, no +//! fabricated handle, no relaxed schema. The child's real `Bool` return is +//! observed in the parent frame. +//! +//! The first four arms do not claim a finalizer dequeue, the pending queue, +//! commit, root handoff, close, collection, scheduling pauses, or a +//! source-level general closure bridge. The heap only issues one real table +//! carrier, one real `lua.userdata` token and one real `lua.table` token; +//! nothing is collected or closed there. +//! +//! ## Typed published head commit +//! +//! Four more arms run one real `.lua` fixture. `fault()` builds, in this same +//! VM, two real typed userdata A and B whose shared metatable stores +//! `__gc = recv`, clears one independent weak-value orphan with the real +//! selecting collection, finishes the published Release tail, and returns A's +//! real token. The plugin inserts `bind(recv, target)`, `wrong_token()`, +//! `admit`, and `commit` as exact statics. `admit` is the read-only +//! `Borrow/Value/Borrow` seam over the same typed local and the same two +//! parent slots. `commit` re-reads the live published head, metatable, raw +//! action, issued receiver carrier, exact stored callable `Arc`, typed payload +//! owner, token, and a fresh three-root plan in one exclusive heap borrow; it +//! opens the root frame and pops, roots, and settles only after all of them +//! match. The following `CallValue(2)` uses the same local and the same two +//! slots into the real two-parameter child frame, and the parent continuation +//! re-borrows the same token. After the run, withdrawing only the three commit +//! roots and collecting retires A's token and generation while B stays the +//! published head and the independently rooted sentinel stays readable. Three +//! controls pass the queued successor's real token, an equal-valued unissued +//! receiver array, or a raw `__call` rewritten between the seam and the +//! commit; each is refused by the same entry before any write, and the same VM +//! then re-takes the real credentials and commits A. A mutation that removes +//! only the callable `Arc` comparison turns the raw-edge control into a real +//! `Ok(Halted)` business failure. +//! +//! ## Pre-commit borrow seam +//! +//! Two extra arms keep the same real fixture and insert one more exact static +//! import, `admit`, between the typed local and the parent's own `CallValue(2)`. +//! The catalog declares it as +//! `(Borrow, Resource(lua.userdata)) -> Bool>>, +//! Value>, Borrow) -> Bool`, and the plugin +//! resolves the call with those concrete operand schemas, so the compiled +//! program carries the complete `HostImportSchema` and catalog fingerprint and +//! `register_exact_static` binds the static body. The body records the actual +//! callable Arc, receiver carrier and typed userdata payload, refuses only a +//! receiver the heap did not issue (with its own `HostError`), and otherwise +//! returns one fixed `Bool`. The positive arm then runs the same compiled +//! `CallValue(2)` into the real two-parameter child frame and the parent +//! continuation with those identical operands; the control arm passes an +//! equal-valued but never issued array, built at run time from the issued +//! carrier's two integers, and stops in the static body. Not claimed: a queue +//! write, dequeue, commit, root plan, generation snapshot, or GC. +//! +//! ## Compile and run scope ownership +//! +//! The compile input (`GATE_MODE`) and the structural patch report belong to +//! the plugin instance that performed that compile. The runtime selection +//! (`SELECT`) and the observation witness belong to the execution scope of +//! the VM that ran the fixture. Two arms compiled and interpreted on two +//! threads therefore cannot read, overwrite or take each other's patch or +//! records; the two-thread controls at the bottom of this module drive the +//! real compiler and the real interpreter concurrently. + +use std::cell::Cell; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::time::{Duration, Instant}; + +use vm::compiler::{HostCallResolver, ResolvedHostCall}; +use vm::vm::VmFrameContinuation; +use vm::{ + BuiltinFunction, CallOutcome, CallReturn, ClosureExpr, CompileSourceFileOptions, Expr, + FrontendImportSyntax, FrontendIr, FunctionDecl, HostApiBuilder, HostApiCatalog, + HostFunctionRegistry, HostFunctionSchema, HostImport, HostImportSchema, HostParamPassing, + HostParamSchema, HostTypeSchema, JitConfig, LocalSlot, OpCode, ParseError, Program, + ResourceHandle, ResourceTypeSchema, SourceFlavor, SourcePlugin, Stmt, TypeSchema, Value, Vm, + VmError, VmStatus, +}; + +use super::{FUEL_BUDGET, FUEL_CHECK_INTERVAL, decoded_call_sites}; +use crate::heap::{self, GuestClass, LuaTableResource, LuaUserdataResource, TableRef, UserdataRef}; + +#[path = "active_typed_callback_root_retirement.rs"] +mod active_typed_callback_root_retirement; + +/// The fixture the positive and resource-key control arms execute. +const FIXTURE: &str = "active_typed_resource_transport.lua"; +/// The fixture whose only structural difference is the actual second argument. +const OTHER_ARGUMENT_FIXTURE: &str = "active_typed_resource_other_arg.lua"; +/// `parent(cb, first, second, single, other, recv, arg2, mode)`. +const PARENT_PARAMS: usize = 8; +/// `cb(recv, arg2)`. +const CALL_ARGC: u8 = 2; +/// The admitted callable and the two actual arguments in `parent`. +const PARENT_CALLEE_SLOT: usize = 0; +const PARENT_RECEIVER_SLOT: usize = 5; +const PARENT_ARGUMENT_SLOT: usize = 6; + +/// The second exact static import this module registers and the exact label of +/// the raw entry record its static body writes before any fallible check. +const PRECOMMIT_IMPORT: &str = "admit"; +const PRECOMMIT_ENTRY_LABEL: &str = "precommit-admit-enter"; +/// The static body's own diagnostic kinds; the test host never wraps these. +const PRECOMMIT_REFUSAL_RECEIVER: &str = + "typed precommit seam refused: receiver is not the issued LuaHeap carrier"; + +/// The fixture that carries a real published typed head through the parent. +const PUBLISHED_COMMIT_FIXTURE: &str = "active_typed_published_commit.lua"; +/// Its parent has the pre-commit operands plus the successor token and mode. +const PUBLISHED_PARENT_PARAMS: usize = 9; +const PUBLISHED_WRONG_SLOT: usize = 7; +/// The parent's `second` parameter carries the exact alternate closure Arc. +const PUBLISHED_ALTERNATE_SLOT: usize = 2; +/// The exact imports the published-commit plugin resolves and inserts. None of +/// these names is a guest-lowered host name; the plugin adds the IR calls. +const BIND_IMPORT: &str = "bind"; +const COMMIT_IMPORT: &str = "commit"; +const SWAP_IMPORT: &str = "swap"; +const WRONG_TOKEN_IMPORT: &str = "wrong_token"; +const COMMIT_ENTRY_LABEL: &str = "published-commit-enter"; +/// The typed commit body's own diagnostic prefix; the test host never wraps it. +const COMMIT_REFUSAL_PREFIX: &str = "typed published commit refused: "; + +/// The fixture whose parent asks the private exact static `produce` for the +/// callable instead of taking one of its own callable arguments. +const PRODUCER_FIXTURE: &str = "active_typed_published_head_producer.lua"; +/// The exact static that reads the published head's raw `__gc` / `__call` +/// chain and returns the stored callable Arc for Core's typed return check. +const PRODUCER_IMPORT: &str = "produce"; +const PRODUCER_ENTRY_LABEL: &str = "producer-enter"; +/// The distinct source-level marker of the before-read replacement closure. +const ALTERNATE_LABEL: &str = "alternate-enter"; +/// The fixture whose parent optionally calls the exact `retire` import after +/// the real `CallValue(2)` returns, then always reaches the guest `sweep`. +const RETIREMENT_FIXTURE: &str = "active_typed_callback_root_retirement.lua"; +const RETIRE_IMPORT: &str = "retire"; +const SWEEP_IMPORT: &str = "sweep"; +/// Producer-shaped gate whose compiled target result is `Bool(false)`. +const FALSE_RETURN_GATE: usize = 11; + +/// The first statement of the two declared closures names them. +const TARGET_LABEL: &str = "target-enter"; +const OTHER_LABEL: &str = "other-enter"; + +// ---- compile state per plugin, run state per VM execution scope ---------- + +/// Compile-time arm input and the structural report belong to one plugin +/// instance. Two arms compiled on two threads cannot observe each other's +/// gate mode or patch report. +struct TransportPlugin { + gate_mode: usize, + pause_on_compile: bool, + patch: Mutex>, +} + +impl TransportPlugin { + fn new(arm: Arm) -> Self { + Self { + gate_mode: arm.gate_mode(), + pause_on_compile: false, + patch: Mutex::new(None), + } + } + + fn with_compile_pause(arm: Arm) -> Self { + Self { + gate_mode: arm.gate_mode(), + pause_on_compile: true, + patch: Mutex::new(None), + } + } + + fn take_patch(&self, arm: Arm) -> PatchReport { + self.patch + .lock() + .expect("typed resource patch report") + .take() + .unwrap_or_else(|| panic!("{}: the plugin produced no patch report", arm.label())) + } +} + +/// Runtime arm input and the observation witness belong to exactly the +/// execution scope of the VM that produced them. Another VM cannot read, +/// overwrite or take them. +struct RunScope { + select: usize, + witness: Witness, + /// Compiled `CallValue` result local. Set only for the retirement arms. + call_result_slot: Option, +} + +fn with_run_scope(vm: &mut Vm, body: impl FnOnce(&mut RunScope) -> T) -> T { + let mut host = vm.host_context(); + let scope = host + .scope_state_mut::() + .expect("the typed resource run scope must be installed before the run"); + body(scope) +} + +// ---- controlled interleaving for the two-thread controls ------------------ + +/// The test-only ordering points. They gate timing only, and no lock that +/// protects shared observation is held across either wait. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum InterleavePoint { + /// Inside `TransportPlugin::parse_source`, after that plugin instance + /// wrote its own patch report and before it returns. + Compile, + /// In `host_mark("chunk-mode")`, before the VM's own selected arm is read. + Runtime, + /// In the run driver, after the VM stopped and before its own execution + /// scope is taken. + Take, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum InterleaveRole { + First, + Second, +} + +const POINT_RUNTIME: u8 = 1 << 0; +const POINT_TAKE: u8 = 1 << 1; + +thread_local! { + static INTERLEAVE_PLAN: Cell> = const { Cell::new(None) }; +} + +fn interleave_plan(role: InterleaveRole, points: u8) { + INTERLEAVE_PLAN.with(|plan| plan.set(Some((role, points)))); +} + +fn clear_interleave_plan() { + INTERLEAVE_PLAN.with(|plan| plan.set(None)); +} + +fn interleave_pause(point: InterleavePoint) { + let Some((role, points)) = INTERLEAVE_PLAN.with(|plan| plan.get()) else { + return; + }; + let bit = match point { + InterleavePoint::Compile => return, + InterleavePoint::Runtime => POINT_RUNTIME, + InterleavePoint::Take => POINT_TAKE, + }; + let expected_role = match point { + InterleavePoint::Compile | InterleavePoint::Runtime => InterleaveRole::First, + InterleavePoint::Take => InterleaveRole::Second, + }; + if role != expected_role || points & bit == 0 { + return; + } + interleave_gate_for(point).park(point); +} + +struct InterleaveGate { + reached: Mutex>, + reached_signal: Condvar, + released: Mutex>, + released_signal: Condvar, +} + +static COMPILE_INTERLEAVE_GATE: OnceLock = OnceLock::new(); +static RUNTIME_INTERLEAVE_GATE: OnceLock = OnceLock::new(); + +fn compile_interleave_gate() -> &'static InterleaveGate { + COMPILE_INTERLEAVE_GATE.get_or_init(InterleaveGate::new) +} + +fn runtime_interleave_gate() -> &'static InterleaveGate { + RUNTIME_INTERLEAVE_GATE.get_or_init(InterleaveGate::new) +} + +fn interleave_gate_for(point: InterleavePoint) -> &'static InterleaveGate { + match point { + InterleavePoint::Compile => compile_interleave_gate(), + InterleavePoint::Runtime | InterleavePoint::Take => runtime_interleave_gate(), + } +} + +impl InterleaveGate { + fn new() -> Self { + Self { + reached: Mutex::new(None), + reached_signal: Condvar::new(), + released: Mutex::new(Vec::new()), + released_signal: Condvar::new(), + } + } + + fn park(&self, point: InterleavePoint) { + *self + .reached + .lock() + .expect("typed transport interleave reached") = Some(point); + self.reached_signal.notify_all(); + let deadline = Instant::now() + Duration::from_secs(120); + let mut released = self + .released + .lock() + .expect("typed transport interleave released"); + while !released.contains(&point) { + let now = Instant::now(); + assert!( + now < deadline, + "typed transport interleave: the {point:?} point was not released" + ); + let wait = deadline + .saturating_duration_since(now) + .min(Duration::from_millis(100)); + let (guard, _) = self + .released_signal + .wait_timeout(released, wait) + .expect("typed transport interleave released wait"); + released = guard; + } + } + + fn wait_reached( + &self, + point: InterleavePoint, + thread: &std::thread::JoinHandle, + ) -> Result<(), String> { + let mut reached = self + .reached + .lock() + .expect("typed transport interleave reached"); + let deadline = Instant::now() + Duration::from_secs(120); + while reached.as_ref() != Some(&point) { + if thread.is_finished() { + return Err(format!( + "the first thread ended before the {point:?} interleave point" + )); + } + let now = Instant::now(); + if now >= deadline { + return Err(format!( + "the first thread did not reach the {point:?} interleave point" + )); + } + let wait = deadline + .saturating_duration_since(now) + .min(Duration::from_millis(100)); + let (guard, _) = self + .reached_signal + .wait_timeout(reached, wait) + .expect("typed transport interleave reached wait"); + reached = guard; + } + Ok(()) + } + + fn release(&self, point: InterleavePoint) { + self.released + .lock() + .expect("typed transport interleave release") + .push(point); + self.released_signal.notify_all(); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Arm { + Positive, + OtherResourceKey, + OtherArgumentToken, + PrecommitBorrowSeam, + PrecommitUnissuedReceiver, + PublishedCommit, + PublishedCommitOtherOwner, + PublishedCommitUnissuedReceiver, + PublishedCommitRawArcChanged, + PublishedHeadProducer, + PublishedHeadProducerReplacedBeforeRead, + PublishedHeadProducerReplacedBeforeCommit, + PublishedHeadProducerWrongSignature, + CallbackRootRetirement, + CallbackRootOmission, + CallbackRootFalseReturn, +} + +impl Arm { + fn label(self) -> &'static str { + match self { + Arm::Positive => "positive", + Arm::OtherResourceKey => "other-resource-key", + Arm::OtherArgumentToken => "other-argument-token", + Arm::PrecommitBorrowSeam => "precommit-borrow-seam", + Arm::PrecommitUnissuedReceiver => "precommit-unissued-receiver", + Arm::PublishedCommit => "published-commit", + Arm::PublishedCommitOtherOwner => "published-commit-other-owner", + Arm::PublishedCommitUnissuedReceiver => "published-commit-unissued-receiver", + Arm::PublishedCommitRawArcChanged => "published-commit-raw-arc-changed", + Arm::PublishedHeadProducer => "published-head-producer", + Arm::PublishedHeadProducerReplacedBeforeRead => { + "published-head-producer-replaced-before-read" + } + Arm::PublishedHeadProducerReplacedBeforeCommit => { + "published-head-producer-replaced-before-commit" + } + Arm::PublishedHeadProducerWrongSignature => "published-head-producer-wrong-signature", + Arm::CallbackRootRetirement => "callback-root-retirement", + Arm::CallbackRootOmission => "callback-root-omission", + Arm::CallbackRootFalseReturn => "callback-root-false-return", + } + } + + fn fixture(self) -> &'static str { + match self { + Arm::OtherArgumentToken => OTHER_ARGUMENT_FIXTURE, + Arm::PublishedCommit + | Arm::PublishedCommitOtherOwner + | Arm::PublishedCommitUnissuedReceiver + | Arm::PublishedCommitRawArcChanged => PUBLISHED_COMMIT_FIXTURE, + Arm::PublishedHeadProducer + | Arm::PublishedHeadProducerReplacedBeforeRead + | Arm::PublishedHeadProducerReplacedBeforeCommit + | Arm::PublishedHeadProducerWrongSignature => PRODUCER_FIXTURE, + Arm::CallbackRootRetirement + | Arm::CallbackRootOmission + | Arm::CallbackRootFalseReturn => RETIREMENT_FIXTURE, + _ => FIXTURE, + } + } + + fn select(self) -> usize { + match self { + Arm::OtherResourceKey => 5, + Arm::PublishedCommit => 3, + Arm::PublishedCommitOtherOwner => 4, + Arm::PublishedCommitRawArcChanged => 6, + Arm::PublishedCommitUnissuedReceiver => 7, + Arm::PublishedHeadProducer => 8, + Arm::PublishedHeadProducerReplacedBeforeRead => 9, + Arm::PublishedHeadProducerReplacedBeforeCommit => 10, + Arm::PublishedHeadProducerWrongSignature => 11, + Arm::CallbackRootRetirement | Arm::CallbackRootFalseReturn => 12, + Arm::CallbackRootOmission => 13, + _ => 0, + } + } + + fn gate_mode(self) -> usize { + match self { + Arm::PrecommitBorrowSeam => 1, + Arm::PrecommitUnissuedReceiver => 2, + Arm::PublishedCommit => 3, + Arm::PublishedCommitOtherOwner => 4, + Arm::PublishedCommitUnissuedReceiver => 5, + Arm::PublishedCommitRawArcChanged => 6, + Arm::PublishedHeadProducer => 7, + Arm::PublishedHeadProducerReplacedBeforeRead => 8, + Arm::PublishedHeadProducerReplacedBeforeCommit => 9, + Arm::PublishedHeadProducerWrongSignature => 10, + Arm::CallbackRootRetirement => 12, + Arm::CallbackRootOmission => 13, + Arm::CallbackRootFalseReturn => FALSE_RETURN_GATE, + _ => 0, + } + } + + fn observes_call_result(self) -> bool { + matches!( + self, + Arm::CallbackRootRetirement | Arm::CallbackRootOmission | Arm::CallbackRootFalseReturn + ) + } +} + +// ---- the private test catalog and exact registration ---------------------- + +/// `(Array, Resource(lua.userdata)) -> Bool`, the declared prototype. +fn userdata_callable_schema() -> TypeSchema { + TypeSchema::Callable { + params: vec![ + TypeSchema::Array(Box::new(TypeSchema::Int)), + TypeSchema::Resource(LuaUserdataResource::key()), + ], + result: Box::new(TypeSchema::Bool), + } +} + +/// The same arity, receiver and result with the other legal resource key. +fn table_callable_schema() -> TypeSchema { + TypeSchema::Callable { + params: vec![ + TypeSchema::Array(Box::new(TypeSchema::Int)), + TypeSchema::Resource(LuaTableResource::key()), + ], + result: Box::new(TypeSchema::Bool), + } +} + +/// The exact static import return schema. The callable's own signature is +/// concrete in both parameters and the result; no `Unknown` is accepted here. +fn typed_host_callable_schema() -> HostTypeSchema { + HostTypeSchema::Callable { + params: vec![ + HostTypeSchema::Array(Box::new(HostTypeSchema::Int)), + HostTypeSchema::Resource(LuaUserdataResource::key()), + ], + result: Box::new(HostTypeSchema::Bool), + } +} + +/// The second exact static import under test. The callable parameter contains +/// a resource, so this pin only accepts a reference passing mode for it; the +/// direct `lua.userdata` token is borrowed too. The receiver keeps the real +/// `Array` carrier shape of the issued LuaHeap table. +fn precommit_import_schema() -> HostFunctionSchema { + HostFunctionSchema::with_return( + PRECOMMIT_IMPORT, + vec![ + HostParamSchema::with_passing( + "target", + typed_host_callable_schema(), + HostParamPassing::Borrow, + ), + HostParamSchema::value( + "receiver", + HostTypeSchema::Array(Box::new(HostTypeSchema::Int)), + ), + HostParamSchema::with_passing( + "token", + HostTypeSchema::Resource(LuaUserdataResource::key()), + HostParamPassing::Borrow, + ), + ], + HostTypeSchema::Bool, + ) +} + +/// The typed exclusive commit body. It takes the same actual operands as the +/// read-only seam: the typed callable local, the original receiver carrier and +/// the actual typed userdata token. The static body re-checks them against the +/// live published head before it writes anything. +fn commit_import_schema() -> HostFunctionSchema { + HostFunctionSchema::with_return( + COMMIT_IMPORT, + vec![ + HostParamSchema::with_passing( + "target", + typed_host_callable_schema(), + HostParamPassing::Borrow, + ), + HostParamSchema::value( + "receiver", + HostTypeSchema::Array(Box::new(HostTypeSchema::Int)), + ), + HostParamSchema::with_passing( + "token", + HostTypeSchema::Resource(LuaUserdataResource::key()), + HostParamPassing::Borrow, + ), + ], + HostTypeSchema::Bool, + ) +} + +/// The read-only exact static that sources the callable from the published +/// head. It has no callable argument: only the actual issued receiver carrier +/// and the actual typed userdata token. The return is the same exact callable +/// schema Core checks for the committed typed local. +fn produce_import_schema() -> HostFunctionSchema { + HostFunctionSchema::with_return( + PRODUCER_IMPORT, + vec![ + HostParamSchema::value( + "receiver", + HostTypeSchema::Array(Box::new(HostTypeSchema::Int)), + ), + HostParamSchema::with_passing( + "token", + HostTypeSchema::Resource(LuaUserdataResource::key()), + HostParamPassing::Borrow, + ), + ], + typed_host_callable_schema(), + ) +} + +fn transport_catalog() -> &'static Arc { + static CATALOG: OnceLock> = OnceLock::new(); + CATALOG.get_or_init(|| { + let mut builder = HostApiBuilder::new(); + // Both keys are legally registered resource types before any function + // signature references them. + builder.resource(ResourceTypeSchema::new( + LuaTableResource::key(), + "Lua table", + )); + builder.resource(ResourceTypeSchema::new( + LuaUserdataResource::key(), + "Lua userdata", + )); + // Markers, the staged arm integer, and the real `lua.table` token + // issuer. The token is a real registered handle; its schema is + // deliberately `Unknown` because this one adapter also returns plain + // marker integers. + builder.function(HostFunctionSchema::with_return( + "mark", + vec![HostParamSchema::value("label", HostTypeSchema::String)], + HostTypeSchema::Unknown, + )); + // The exact typed callable-returning adapter under test. + builder.function(HostFunctionSchema::with_return( + "note", + vec![ + HostParamSchema::value("mode", HostTypeSchema::Int), + HostParamSchema::value("target", HostTypeSchema::Unknown), + HostParamSchema::value("first", HostTypeSchema::Unknown), + HostParamSchema::value("second", HostTypeSchema::Unknown), + HostParamSchema::value("single", HostTypeSchema::Unknown), + HostParamSchema::value("other", HostTypeSchema::Unknown), + ], + typed_host_callable_schema(), + )); + // The second exact static import: the typed local (borrowed, it + // contains a resource), the original issued receiver carrier and the + // actual typed userdata token (borrowed). No `Unknown` parameter. + builder.function(precommit_import_schema()); + // The published-commit fixture's own exact statics. `prepare` issues + // A, installs the shared `__gc = receiver` and the raw `__call` + // closure, clears one weak orphan, and finishes the published tail; + // `wrong_token` returns the queued successor's real typed token; + // `swap` rewrites the receiver's raw `__call` between the seam and the + // commit; `commit` is the typed exclusive commit body. + builder.function(HostFunctionSchema::with_return( + BIND_IMPORT, + vec![ + HostParamSchema::value("owner", HostTypeSchema::Unknown), + HostParamSchema::value("target", HostTypeSchema::Unknown), + ], + HostTypeSchema::Bool, + )); + builder.function(HostFunctionSchema::with_return( + WRONG_TOKEN_IMPORT, + Vec::new(), + HostTypeSchema::Resource(LuaUserdataResource::key()), + )); + builder.function(HostFunctionSchema::with_return( + SWAP_IMPORT, + vec![ + HostParamSchema::value("owner", HostTypeSchema::Unknown), + HostParamSchema::value("target", HostTypeSchema::Unknown), + ], + HostTypeSchema::Bool, + )); + builder.function(commit_import_schema()); + // The read-only typed head producer. It takes only the issued + // receiver carrier and the actual typed userdata token; the callable + // itself comes from the heap's published `__gc`/`__call` chain. + builder.function(produce_import_schema()); + builder.function(HostFunctionSchema::with_return( + RETIRE_IMPORT, + Vec::new(), + HostTypeSchema::Bool, + )); + builder.function(HostFunctionSchema::with_return( + SWEEP_IMPORT, + Vec::new(), + HostTypeSchema::Bool, + )); + // One freshly issued LuaHeap table carrier, whose real shape is + // `Array`. + builder.function(HostFunctionSchema::with_return( + "tick", + vec![HostParamSchema::value("label", HostTypeSchema::String)], + HostTypeSchema::Array(Box::new(HostTypeSchema::Int)), + )); + // One freshly issued typed userdata token. + builder.function(HostFunctionSchema::with_return( + "fault", + Vec::new(), + HostTypeSchema::Resource(LuaUserdataResource::key()), + )); + Arc::new(builder.build().expect("active typed resource catalog")) + }) +} + +fn catalog_schema(name: &str) -> HostImportSchema { + let catalog = transport_catalog(); + let function = catalog + .function(name) + .unwrap_or_else(|| panic!("catalog is missing '{name}'")); + HostImportSchema::from_function(catalog, function) +} + +/// Binds every host through the exact static path, so the compiled program and +/// the VM share one catalog schema per import and Core validates the typed +/// return at run time. +fn bind_hosts_for(vm: &mut Vm, retirement: bool) -> Result<(), VmError> { + let mut registry = HostFunctionRegistry::empty(); + registry.register_exact_static("mark", 1, catalog_schema("mark"), host_mark)?; + registry.register_exact_static("note", 6, catalog_schema("note"), host_note)?; + registry.register_exact_static( + PRECOMMIT_IMPORT, + 3, + catalog_schema(PRECOMMIT_IMPORT), + host_precommit, + )?; + registry.register_exact_static("tick", 1, catalog_schema("tick"), host_tick)?; + registry.register_exact_static("fault", 0, catalog_schema("fault"), host_fault)?; + registry.register_exact_static(BIND_IMPORT, 2, catalog_schema(BIND_IMPORT), host_bind)?; + registry.register_exact_static( + WRONG_TOKEN_IMPORT, + 0, + catalog_schema(WRONG_TOKEN_IMPORT), + host_wrong_token, + )?; + registry.register_exact_static("swap", 2, catalog_schema("swap"), host_swap)?; + registry.register_exact_static(COMMIT_IMPORT, 3, catalog_schema(COMMIT_IMPORT), host_commit)?; + registry.register_exact_static( + PRODUCER_IMPORT, + 2, + catalog_schema(PRODUCER_IMPORT), + host_produce, + )?; + if retirement { + registry.register_exact_static( + RETIRE_IMPORT, + 0, + catalog_schema(RETIRE_IMPORT), + active_typed_callback_root_retirement::host_retire, + )?; + registry.register_exact_static( + SWEEP_IMPORT, + 0, + catalog_schema(SWEEP_IMPORT), + active_typed_callback_root_retirement::host_sweep, + )?; + } + registry.bind_vm_cached(vm) +} + +// ---- observation records -------------------------------------------------- + +#[derive(Clone, Debug)] +struct TokenProbe { + raw: i64, + parts: (u64, u32, u32), + rebound_parts: (u64, u32, u32), +} + +#[derive(Clone, Debug)] +struct TableTokenRecord { + raw: i64, + parts: (u64, u32, u32), +} + +/// One observation of the second exact static import, recorded by its static +/// body from the actual operands and the live VM before any refusal. +#[derive(Clone, Debug)] +struct GateRecord { + callable: Value, + receiver: Value, + receiver_class: GuestClass, + receiver_is_issued: bool, + token_raw: i64, + token_parts: Option<(u64, u32, u32)>, + token_is_issued: bool, + refused: bool, +} + +/// One prepared published head, read after the released Release tail finished. +/// It is a fixed snapshot of the real A/B state, not a queue lease and not a +/// root: the commit body must re-read every identity in its own borrow. +#[derive(Clone, Debug)] +struct PublishedPrepareRecord { + receiver: TableRef, + receiver_metatable: TableRef, + finalizer_metatable: TableRef, + userdata: UserdataRef, + userdata_raw: i64, + successor: UserdataRef, + successor_raw: i64, + call_closure: Option, + weak_table: TableRef, + sentinel: TableRef, + root_frame: heap::RootFrameId, + published_count: usize, + queue_len: usize, +} + +/// One actual invocation of the typed commit body, recorded from its real +/// operands and the live heap before the exclusive borrow returns. +#[derive(Clone, Debug)] +struct PublishedCommitRecord { + callable: Value, + receiver: Value, + receiver_class: GuestClass, + token_raw: i64, + payload_parts: Option<(u64, u32, u32)>, + payload_is_head: bool, + weak_matches_callable: bool, + head_parts: (u64, u32, u32), + head_raw: i64, + metatable_parts: (u64, u32, u32), + action_receiver: (u64, u32, u32), + action_closure: (u64, u32, u32), + published_before: usize, + queue_before: usize, + outcome: Result<(heap::RootFrameId, u32), String>, + taken_userdata: Option, +} + +/// One read-only invocation of the exact static producer. It records the +/// actual heap head identities, the stored callable as a `Weak` only, the +/// actual prototype id of that Arc, and the parent's own callable slot (the +/// old fixture selection) as an identity comparison, never as an extra strong +/// `Arc`. The queue/flag/top-frame fields are read before and after the pass. +#[derive(Clone, Debug)] +struct ProducerRecord { + userdata: UserdataRef, + raw_token: i64, + metatable: TableRef, + receiver: TableRef, + closure: heap::ClosureRef, + callable: std::sync::Weak, + published_count: usize, + queue_len: usize, + returned_prototype: u32, + receiver_class: GuestClass, + payload_is_head: bool, + token_still_open: bool, + parent_candidate_matches: bool, + parent_candidate_prototype: Option, + queue_before: Vec<(u64, u32, u32)>, + queue_after: Vec<(u64, u32, u32)>, + top_frame_before: Option, + top_frame_after: Option, + pending_before: [bool; 2], + pending_after: [bool; 2], + settled_before: [bool; 2], + settled_after: [bool; 2], +} + +/// The first observation of one host callback. Recorded before any frame +/// verification, resource probe, or error wrapping, from the live execution +/// frames alone, so a later probe failure cannot erase whether the callback +/// frame actually entered. +#[derive(Clone, Debug)] +struct EntryRecord { + /// The first marker the entered frame executes. + label: String, + /// The actual execution-frame depth at entry. + frame_len: usize, + /// The actual prototype id of the entered (last) frame. + prototype_id: Option, + /// The actual resume address of the entered frame, when it resumes + /// bytecode through the executed `CallValue`. + return_ip: Option, + /// The actual prototype id of the caller frame. + parent_prototype: Option, +} + +#[derive(Clone, Debug)] +struct ParentEntryFacts { + argument_raw: i64, +} + +#[derive(Clone, Debug)] +struct CalleeRecord { + prototype_id: u32, + parameter_slots: Vec, + parameter_values: Vec>, + receiver_class: String, + ordinary_array_class: String, + token: TokenProbe, + table_token_refused: bool, + caller_callable: Option, + caller_declared_slot: Option, + parent_same_arc_slots: Vec, +} + +#[derive(Clone, Debug)] +struct MarkRecord { + label: String, + frame_len: usize, + last_prototype: Option, + last_return_ip: Option, + parent_prototype: Option, + parent_entry: Option, + continuation: Option, + child_return: Option, + callee: Option, +} + +#[derive(Clone, Debug)] +struct PickRecord { + mode: i64, + target: Value, + first: Value, + second: Value, + single: Value, + other: Value, + chosen: Value, + chosen_is_target: bool, + chosen_is_other: bool, +} + +#[derive(Clone, Debug, Default)] +struct Witness { + entries: Vec, + marks: Vec, + picks: Vec, + gates: Vec, + prepared: Option, + commits: Vec, + producers: Vec, + issued_table: Option, + issued_table_ref: Option, + issued_userdata: Option, + issued_userdata_raw: Option, + table_token: Option, + /// The compiled call-result slot and the value read from it at parent-after. + call_result_slot: Option, + call_result: Option, + /// True when some other parent local is still `Bool(true)`. + host_true_beside_call: bool, +} + +/// The independent entry record of the active (last) frame, read from the live +/// frames alone before any host-side probe can fail. +fn frame_entry(vm: &Vm, label: &str) -> EntryRecord { + let frames = vm.execution_frames(); + let current = frames.last(); + EntryRecord { + label: label.to_string(), + frame_len: frames.len(), + prototype_id: current.and_then(|frame| frame.prototype_id), + return_ip: current.and_then(|frame| match &frame.continuation { + VmFrameContinuation::ResumeBytecode { return_ip } => Some(*return_ip), + _ => None, + }), + parent_prototype: frames + .iter() + .rev() + .nth(1) + .and_then(|frame| frame.prototype_id), + } +} + +fn host_fault_error(message: impl Into) -> VmError { + VmError::HostError(message.into()) +} + +fn heap_fault(error: heap::HeapError) -> VmError { + VmError::HostError(format!("lua heap: {error:?}")) +} + +// ---- typed token probes --------------------------------------------------- + +/// The formal Core API: a raw handle is validated by the resource table and +/// then borrowed with the exact concrete `lua.userdata` key. The payload is +/// copied out before the borrow ends, so a heap check can follow. +fn probe_userdata(host: &vm::HostContext, raw: i64) -> Result { + let raw_u64 = u64::try_from(raw) + .map_err(|_| host_fault_error("the userdata token is not a positive handle"))?; + let handle = ResourceHandle::from_raw(raw_u64) + .map_err(|error| host_fault_error(format!("the userdata handle is invalid: {error}")))?; + let payload = { + let borrowed = host + .borrow_resource_with_key::(handle, &LuaUserdataResource::key()) + .map_err(|error| { + host_fault_error(format!("the lua.userdata borrow was refused: {error}")) + })?; + borrowed.get().userdata() + }; + let rebound = heap::borrow_published_userdata(host, payload).map_err(heap_fault)?; + Ok(TokenProbe { + raw, + parts: (payload.domain(), payload.slot(), payload.generation()), + rebound_parts: (rebound.domain(), rebound.slot(), rebound.generation()), + }) +} + +/// The same formal borrow with the other registered key. It proves the token +/// issued by `mark("table-token")` is a real `lua.table` resource. +fn probe_table(host: &vm::HostContext, raw: i64) -> Result<(u64, u32, u32), VmError> { + let raw_u64 = u64::try_from(raw) + .map_err(|_| host_fault_error("the table token is not a positive handle"))?; + let handle = ResourceHandle::from_raw(raw_u64) + .map_err(|error| host_fault_error(format!("the table handle is invalid: {error}")))?; + let borrowed = host + .borrow_resource_with_key::(handle, &LuaTableResource::key()) + .map_err(|error| host_fault_error(format!("the lua.table borrow was refused: {error}")))?; + let table = borrowed.get().table(); + Ok((table.domain(), table.slot(), table.generation())) +} + +// ---- the hosts ------------------------------------------------------------ + +fn host_mark(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::String(label)] = args else { + return Err(host_fault_error("mark expects one string label")); + }; + let label = label.as_str().to_string(); + + // The first observation of this host callback. This runs before every + // fallible frame check, resource probe and error wrapper below, so a + // probe that fails after the frame really entered still leaves the + // entered frame's actual prototype, depth and resume address recorded. + let entry = frame_entry(vm, &label); + with_run_scope(vm, |scope| scope.witness.entries.push(entry)); + + if label == "chunk-mode" { + interleave_pause(InterleavePoint::Runtime); + let select = i64::try_from(with_run_scope(vm, |scope| scope.select)) + .map_err(|_| host_fault_error("the selected arm does not fit a guest integer"))?; + return Ok(CallOutcome::Return(CallReturn::one(Value::Int(select)))); + } + + if label == "table-token" { + let mut host = vm.host_context(); + let issued = heap::publish(&mut host).map_err(heap_fault)?; + let Value::Int(raw) = issued else { + return Err(host_fault_error("the issued table token is not a handle")); + }; + let parts = probe_table(&host, raw)?; + with_run_scope(vm, |scope| { + scope.witness.table_token = Some(TableTokenRecord { raw, parts }); + }); + return Ok(CallOutcome::Return(CallReturn::one(Value::Int(raw)))); + } + + let parent_entry; + let continuation; + let child_return; + let frame; + let (frame_len, last_prototype, last_return_ip, parent_prototype) = { + let frames = vm.execution_frames(); + let program = vm.program(); + let locals = vm.locals(); + let current = frames.last(); + let parent = frames.iter().rev().nth(1); + + parent_entry = (label == "parent-enter") + .then(|| { + current.and_then(|frame| { + let prototype_id = frame.prototype_id?; + let prototype = program.callable_prototypes.get(prototype_id as usize)?; + if prototype.parameter_slots.len() != PARENT_PARAMS + && prototype.parameter_slots.len() != PUBLISHED_PARENT_PARAMS + { + return None; + } + let slot = *prototype.parameter_slots.get(PARENT_ARGUMENT_SLOT)?; + let value = locals.get(frame.local_base + usize::from(slot))?; + let Value::Int(raw) = value else { + return None; + }; + Some(ParentEntryFacts { argument_raw: *raw }) + }) + }) + .flatten(); + + continuation = (label == "parent-after") + .then(|| { + current.and_then(|frame| { + let prototype_id = frame.prototype_id?; + let prototype = program.callable_prototypes.get(prototype_id as usize)?; + if prototype.parameter_slots.len() != PARENT_PARAMS + && prototype.parameter_slots.len() != PUBLISHED_PARENT_PARAMS + { + return None; + } + let slot = *prototype.parameter_slots.get(PARENT_ARGUMENT_SLOT)?; + let value = locals.get(frame.local_base + usize::from(slot))?; + let Value::Int(raw) = value else { + return None; + }; + Some(*raw) + }) + }) + .flatten(); + + child_return = (label == "parent-after") + .then(|| { + current.and_then(|frame| { + let values = + locals.get(frame.local_base..frame.local_base + frame.local_count)?; + values + .iter() + .find(|value| matches!(value, Value::Bool(true))) + .cloned() + }) + }) + .flatten(); + + frame = current.and_then(|child| { + let prototype_id = child.prototype_id?; + let prototype = program.callable_prototypes.get(prototype_id as usize)?; + if prototype.parameter_slots.len() != usize::from(CALL_ARGC) { + return None; + } + let declared = prototype.parameter_slots.clone(); + let mut values = Vec::with_capacity(declared.len()); + for slot in &declared { + let absolute = child.local_base.checked_add(usize::from(*slot))?; + if absolute >= child.local_base + child.local_count { + return None; + } + values.push(locals.get(absolute).cloned()); + } + let mut caller_callable = None; + let mut caller_declared_slot = None; + let mut parent_same_arc_slots = Vec::new(); + if let Some(caller) = parent + && let Some(caller_prototype) = caller + .prototype_id + .and_then(|id| program.callable_prototypes.get(id as usize)) + && let Some(&slot) = caller_prototype.parameter_slots.first() + && let Some(absolute) = caller.local_base.checked_add(usize::from(slot)) + { + caller_declared_slot = Some(slot); + caller_callable = locals.get(absolute).cloned(); + if let Some(Value::Callable(caller_arc)) = &caller_callable { + let start = caller.local_base; + let end = caller.local_base + caller.local_count; + if let Some(values) = locals.get(start..end) { + for (offset, value) in values.iter().enumerate() { + if let Value::Callable(candidate) = value + && Arc::ptr_eq(candidate, caller_arc) + { + parent_same_arc_slots.push(offset as u16); + } + } + } + } + } + Some(( + prototype_id, + child.local_base, + child.local_count, + declared, + values, + caller_callable, + caller_declared_slot, + parent_same_arc_slots, + )) + }); + + ( + frames.len(), + current.and_then(|frame| frame.prototype_id), + current.and_then(|frame| match &frame.continuation { + VmFrameContinuation::ResumeBytecode { return_ip } => Some(*return_ip), + _ => None, + }), + parent.and_then(|frame| frame.prototype_id), + ) + }; + + let mut record = MarkRecord { + label: label.clone(), + frame_len, + last_prototype, + last_return_ip, + parent_prototype, + parent_entry, + continuation: None, + child_return, + callee: None, + }; + + if let Some(( + prototype_id, + _local_base, + _local_count, + slots, + values, + caller, + caller_slot, + same_arc, + )) = frame + { + let receiver = values + .first() + .cloned() + .flatten() + .ok_or_else(|| host_fault_error("the callee's first formal slot is empty"))?; + let token = values + .get(1) + .cloned() + .flatten() + .ok_or_else(|| host_fault_error("the callee's second formal slot is empty"))?; + let Value::Int(raw) = token else { + return Err(host_fault_error(format!( + "the callee's second formal slot is not a handle token: {token:?}" + ))); + }; + let mut host = vm.host_context(); + let receiver_class = heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&receiver))) + .map_err(heap_fault)?; + let ordinary = Value::array(vec![Value::Int(0), Value::Int(0)]); + let ordinary_class = heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&ordinary))) + .map_err(heap_fault)?; + let token_probe = probe_userdata(&host, raw)?; + let table_token_refused = host + .borrow_resource_with_key::( + raw_handle(raw)?, + &LuaTableResource::key(), + ) + .is_err(); + record.callee = Some(CalleeRecord { + prototype_id, + parameter_slots: slots, + parameter_values: values, + receiver_class: format!("{receiver_class:?}"), + ordinary_array_class: format!("{ordinary_class:?}"), + token: token_probe, + table_token_refused, + caller_callable: caller, + caller_declared_slot: caller_slot, + parent_same_arc_slots: same_arc, + }); + } + + if let Some(raw) = continuation { + let host = vm.host_context(); + record.continuation = Some(probe_userdata(&host, raw)?); + } + + if label == "parent-after" { + let slot = with_run_scope(vm, |scope| scope.call_result_slot); + if let Some(slot) = slot { + let (value, host_true) = { + let frames = vm.execution_frames(); + let locals = vm.locals(); + let current = frames.last(); + let value = current.and_then(|frame| { + let absolute = frame.local_base.checked_add(usize::from(slot))?; + locals.get(absolute).cloned() + }); + let host_true = current.is_some_and(|frame| { + locals + .get(frame.local_base..frame.local_base + frame.local_count) + .is_some_and(|values| { + values.iter().enumerate().any(|(index, local)| { + index != usize::from(slot) && matches!(local, Value::Bool(true)) + }) + }) + }); + (value, host_true) + }; + with_run_scope(vm, |scope| { + scope.witness.call_result_slot = Some(slot); + scope.witness.call_result = value; + scope.witness.host_true_beside_call = host_true; + }); + } + } + + with_run_scope(vm, |scope| scope.witness.marks.push(record)); + Ok(CallOutcome::Return(CallReturn::one(Value::Int(0)))) +} + +/// The VM local written by the `Stloc` immediately after the real +/// `CallValue(2)`. That is the compiled result slot, not the IR temp. +fn compiled_call_result_slot(program: &Program) -> Option { + let code = &program.code; + let mut ip = 0; + while ip < code.len() { + let op = OpCode::try_from(code[ip]).ok()?; + let next = ip + 1 + op.operand_len(); + if next > code.len() { + return None; + } + if op == OpCode::CallValue && code[ip + 1] == CALL_ARGC { + if next < code.len() && OpCode::try_from(code[next]).ok() == Some(OpCode::Stloc) { + return LocalSlot::try_from(usize::from(code[next + 1])).ok(); + } + return None; + } + ip = next; + } + None +} + +/// The raw handle of one guest token, through the formal Core constructor. +fn raw_handle(raw: i64) -> vm::VmResult { + let raw = + u64::try_from(raw).map_err(|_| host_fault_error("the token is not a positive handle"))?; + ResourceHandle::from_raw(raw) + .map_err(|error| host_fault_error(format!("the token handle is invalid: {error}"))) +} + +/// Returns one of the candidates the fixture already wrote at the call site. +/// The returned value is always the exact `SharedCallable` the VM produced. +fn host_note(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::Int(mode), target, first, second, single, other] = args else { + return Err(host_fault_error( + "note expects a mode and five written candidates", + )); + }; + let chosen = match *mode { + 0 | 3 | 4 | 6 | 7 => target, + 5 => other, + // The producer arms still call the old selection once. Its staged mode + // is the published-head arm selector, and like every other published + // arm it names the written target candidate. + 8..=13 => target, + other_mode => { + return Err(host_fault_error(format!( + "note mode {other_mode} is not a fixture arm" + ))); + } + }; + if !matches!(chosen, Value::Callable(_)) { + return Err(host_fault_error( + "the selected typed candidate is not a callable", + )); + } + let record = PickRecord { + mode: *mode, + target: target.clone(), + first: first.clone(), + second: second.clone(), + single: single.clone(), + other: other.clone(), + chosen: chosen.clone(), + chosen_is_target: same_callable(chosen, target), + chosen_is_other: same_callable(chosen, other), + }; + with_run_scope(vm, |scope| scope.witness.picks.push(record)); + Ok(CallOutcome::Return(CallReturn::one(chosen.clone()))) +} + +/// Issues one real LuaHeap table and returns its guest carrier. +fn host_tick(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [Value::String(_label)] = args else { + return Err(host_fault_error("tick expects one string label")); + }; + let mut host = vm.host_context(); + let issued = heap::publish_guest(&mut host).map_err(heap_fault)?; + let class = + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&issued))).map_err(heap_fault)?; + let GuestClass::Table(table) = class else { + return Err(host_fault_error( + "the issued carrier is not a live heap table", + )); + }; + with_run_scope(vm, |scope| { + scope.witness.issued_table_ref = Some(table); + scope.witness.issued_table = Some(issued.clone()); + }); + Ok(CallOutcome::Return(CallReturn::one(issued))) +} + +/// Issues one real typed `lua.userdata` token, or, for the published-commit +/// arms, builds the complete published A/B state first. +/// +/// The published arms select at least three. Their receiver must already be the +/// table `tick` issued; this body gives it a metatable with the false raw +/// `__call` sentinel, publishes B and then A as real typed userdata, attaches +/// their shared `__gc = receiver` metatable, roots a separate weak table and +/// one unrelated sentinel, runs the real selecting collection, and finishes +/// the saved Release tail. The exact `bind` import runs after this and installs +/// the raw `__call`. The returned token is A's real typed `lua.userdata`. +fn host_fault(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + if !args.is_empty() { + return Err(host_fault_error("fault takes no arguments")); + } + let select = with_run_scope(vm, |scope| scope.select); + if select >= 3 { + return host_build_published_head(vm); + } + let mut host = vm.host_context(); + let userdata = heap::publish_userdata(&mut host).map_err(heap_fault)?; + let raw = heap::with_heap(&mut host, |heap| heap.published_userdata_token(userdata)) + .map_err(heap_fault)?; + let raw = i64::try_from(raw) + .map_err(|_| host_fault_error("the userdata token does not fit a signed carrier"))?; + with_run_scope(vm, |scope| { + scope.witness.issued_userdata = Some(userdata); + scope.witness.issued_userdata_raw = Some(raw); + }); + Ok(CallOutcome::Return(CallReturn::one(Value::Int(raw)))) +} + +/// The second exact static import. It is bound with `register_exact_static`, +/// so Core hands the actual operands to this body before the parent's own +/// `CallValue(2)` without an owned-dispatch argument preflight. The body +/// records the real callable Arc, the heap classification of the receiver and +/// the borrowed userdata payload, then refuses with its own `HostError` when +/// the receiver is not the issued carrier. It returns one fixed `Bool` and +/// writes nothing. +fn host_precommit(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + // The independent raw entry record comes first: it is taken from the live + // frames alone, so a later probe failure cannot erase that this static + // body ran in the parent frame. + let entry = frame_entry(vm, PRECOMMIT_ENTRY_LABEL); + with_run_scope(vm, |scope| scope.witness.entries.push(entry)); + + let [callable, receiver, token] = args else { + return Err(host_fault_error( + "the precommit static import expects three operands", + )); + }; + let Value::Callable(_) = callable else { + return Err(host_fault_error( + "the precommit static import received a non-callable first operand", + )); + }; + let Value::Int(token_raw) = *token else { + return Err(host_fault_error( + "the precommit static import received a non-handle token operand", + )); + }; + + // The exact static `note` has already selected the callable and the + // fixture has already issued the one carrier and the one userdata token. + let (issued_table, issued_userdata) = with_run_scope(vm, |scope| { + assert!( + !scope.witness.picks.is_empty(), + "the exact static note must run before the precommit import" + ); + ( + scope.witness.issued_table_ref, + scope.witness.issued_userdata, + ) + }); + + let mut host = vm.host_context(); + let receiver_class = + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(receiver))).map_err(heap_fault)?; + let receiver_is_issued = match (&receiver_class, issued_table) { + (GuestClass::Table(table), Some(issued)) => *table == issued, + _ => false, + }; + let payload = { + let borrowed = host + .borrow_resource_with_key::( + raw_handle(token_raw)?, + &LuaUserdataResource::key(), + ) + .map_err(|error| { + host_fault_error(format!("the precommit token borrow was refused: {error}")) + })?; + borrowed.get().userdata() + }; + let payload_rebound = heap::borrow_published_userdata(&host, payload).map_err(heap_fault)?; + let token_is_issued = issued_userdata == Some(payload) && payload == payload_rebound; + let token_parts = (payload.domain(), payload.slot(), payload.generation()); + + let record = GateRecord { + callable: callable.clone(), + receiver: receiver.clone(), + receiver_class, + receiver_is_issued, + token_raw, + token_parts: Some(token_parts), + token_is_issued, + refused: !receiver_is_issued, + }; + with_run_scope(vm, |scope| scope.witness.gates.push(record)); + + if !receiver_is_issued { + return Err(host_fault_error(PRECOMMIT_REFUSAL_RECEIVER)); + } + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))) +} + +/// Builds the real published typed-head state for the published-commit arms. +/// +/// The receiver must be the table `tick` issued without a metatable. This body +/// installs the receiver's own metatable with the false raw `__call` sentinel, +/// hands the exact target `Arc` into that record through the same private heap +/// admission the controlled field import uses, publishes B and then A as real +/// typed userdata, attaches their shared `__gc = receiver` metatable, roots a +/// separate weak table and one unrelated sentinel, publishes them with the +/// real selecting collection, and finishes the saved Release tail. Only then +/// does it read the fixed A/B identities and return A's real typed token. +fn host_build_published_head(vm: &mut Vm) -> vm::VmResult { + let receiver_ref = with_run_scope(vm, |scope| scope.witness.issued_table_ref) + .ok_or_else(|| host_fault_error("fault requires the issued receiver table"))?; + let receiver_metatable = { + let mut host = vm.host_context(); + let existing = + heap::with_heap(&mut host, |heap| heap.metatable(receiver_ref)).map_err(heap_fault)?; + if existing.is_some() { + return Err(host_fault_error( + "fault expects a receiver without a metatable", + )); + } + let metatable = heap::with_heap(&mut host, |heap| heap.alloc()).map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| { + heap.set_metatable(receiver_ref, Some(metatable)) + }) + .map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| { + heap.set_named_scalar(metatable, "__call", Value::Bool(false)) + }) + .map_err(heap_fault)?; + metatable + }; + + let mut host = vm.host_context(); + // B is published first and A second, so the selecting scan's reverse + // allocation order makes A the published head and B its successor. + let successor = heap::publish_userdata(&mut host).map_err(heap_fault)?; + let successor_raw = heap::with_heap(&mut host, |heap| heap.published_userdata_token(successor)) + .map_err(heap_fault)?; + let userdata = heap::publish_userdata(&mut host).map_err(heap_fault)?; + let userdata_raw = heap::with_heap(&mut host, |heap| heap.published_userdata_token(userdata)) + .map_err(heap_fault)?; + let finalizer_metatable = + heap::with_heap(&mut host, |heap| heap.alloc()).map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| { + heap.set_named_edge(finalizer_metatable, "__gc", receiver_ref) + }) + .map_err(heap_fault)?; + for candidate in [userdata, successor] { + heap::with_heap(&mut host, |heap| { + heap.set_userdata_metatable(candidate, Some(finalizer_metatable)) + }) + .map_err(heap_fault)?; + } + + // One real issued-table weak-value orphan: the real selecting publication + // clears the only weak reference to it. + let orphan = { + let value = heap::publish_guest(&mut host).map_err(heap_fault)?; + let class = + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(&value))).map_err(heap_fault)?; + let GuestClass::Table(orphan) = class else { + return Err(host_fault_error( + "prepare's weak orphan must be an issued heap table", + )); + }; + orphan + }; + heap::with_heap(&mut host, |heap| heap.set_edge(orphan, 1, orphan)).map_err(heap_fault)?; + let weak_table = heap::with_heap(&mut host, |heap| heap.alloc()).map_err(heap_fault)?; + let weak_mode = heap::with_heap(&mut host, |heap| heap.alloc()).map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| { + heap.set_mode_scalar(weak_mode, Value::string("v")) + }) + .map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| { + heap.set_metatable(weak_table, Some(weak_mode)) + }) + .map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| { + heap.set_number_edge(weak_table, 1.0, orphan) + }) + .map_err(heap_fault)?; + let sentinel = heap::with_heap(&mut host, |heap| heap.alloc()).map_err(heap_fault)?; + let root_frame = heap::with_heap(&mut host, |heap| heap.enter_roots(4)).map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| heap.write_root(root_frame, 0, weak_table)) + .map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| { + heap.write_root(root_frame, 1, receiver_ref) + }) + .map_err(heap_fault)?; + heap::with_heap(&mut host, |heap| heap.write_root(root_frame, 2, sentinel)) + .map_err(heap_fault)?; + + let queue_before = heap::pending_finalizer_count(&mut host).map_err(heap_fault)?; + if queue_before != 0 { + return Err(host_fault_error( + "prepare expects an empty pending queue before publication", + )); + } + let boundary = heap::collect_pending_finalizers(&mut host).map_err(heap_fault)?; + if !matches!(boundary, heap::PublishedBoundary::Published { .. }) { + return Err(host_fault_error( + "prepare's real selecting collection must save a Release tail", + )); + } + let finished = heap::resume_published_sweep(&mut host, u64::MAX).map_err(heap_fault)?; + if !matches!(finished, heap::PublishedResume::Completed(_)) { + return Err(host_fault_error( + "prepare must finish the published Release tail", + )); + } + let published_count = heap::pending_finalizer_published_count(&mut host).map_err(heap_fault)?; + let queue_len = heap::pending_finalizer_count(&mut host).map_err(heap_fault)?; + if published_count != 2 || queue_len != 2 { + return Err(host_fault_error(format!( + "prepare expected A and B published, saw published={published_count} queue={queue_len}" + ))); + } + let weak_cleared = heap::with_heap(&mut host, |heap| heap.number_value(weak_table, 1.0)) + .map(|value| value == Value::Null) + .map_err(heap_fault)?; + if !weak_cleared { + return Err(host_fault_error( + "prepare's independent weak value must be cleared at publication", + )); + } + let userdata_raw_i64 = i64::try_from(userdata_raw) + .map_err(|_| host_fault_error("the prepared token does not fit a signed carrier"))?; + let record = PublishedPrepareRecord { + receiver: receiver_ref, + receiver_metatable, + finalizer_metatable, + userdata, + userdata_raw: userdata_raw_i64, + successor, + successor_raw: i64::try_from(successor_raw) + .map_err(|_| host_fault_error("the successor token does not fit a signed carrier"))?, + call_closure: None, + weak_table, + sentinel, + root_frame, + published_count, + queue_len, + }; + let _ = host; + with_run_scope(vm, |scope| { + scope.witness.issued_table_ref = Some(receiver_ref); + scope.witness.issued_userdata = Some(userdata); + scope.witness.issued_userdata_raw = Some(userdata_raw_i64); + scope.witness.prepared = Some(record); + }); + Ok(CallOutcome::Return(CallReturn::one(Value::Int( + userdata_raw_i64, + )))) +} + +/// The read-only exact static producer. +/// +/// The two operands are the actual parent-frame values: the original issued +/// receiver carrier and the actual typed userdata token. This body never +/// receives a candidate callable. It borrows the token payload through the +/// formal Core API, then reads the published head, the current userdata +/// metatable's raw `__gc`, and one layer of raw `__call` through the heap +/// owner's read-only preflight. That preflight returns the stored callable as +/// a `Weak`, and this body upgrades exactly one strong `Arc` to return to +/// Core, which validates it against the exact `(Array, +/// Resource(lua.userdata)) -> Bool` return schema and stores it in the typed +/// local. The record keeps only heap identities, the `Weak`, the returned +/// prototype id, and a pointer comparison against the parent's own callable +/// slot, so this body adds no second strong reference and opens no root. +fn host_produce(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let entry = frame_entry(vm, PRODUCER_ENTRY_LABEL); + with_run_scope(vm, |scope| scope.witness.entries.push(entry)); + + let [receiver, token] = args else { + return Err(host_fault_error( + "the typed producer expects the receiver and token operands", + )); + }; + let Value::Int(token_raw) = *token else { + return Err(host_fault_error( + "the typed producer received a non-handle token operand", + )); + }; + let token_u64 = u64::try_from(token_raw) + .map_err(|_| host_fault_error("the userdata token is not a positive handle"))?; + + let prepared = with_run_scope(vm, |scope| scope.witness.prepared.clone()) + .ok_or_else(|| host_fault_error("produce requires the prepared published head"))?; + + // The actual typed payload comes from the Core resource table with the + // exact concrete key. The borrow ends before any heap read. + let payload = { + let host = vm.host_context(); + let borrowed = host + .borrow_resource_with_key::( + raw_handle(token_raw)?, + &LuaUserdataResource::key(), + ) + .map_err(|error| { + host_fault_error(format!("the producer token borrow was refused: {error}")) + })?; + borrowed.get().userdata() + }; + + // The parent's own first parameter is the old fixture selection. Read its + // prototype id and later its exact Arc identity by reference; no clone of + // that candidate Arc is kept by this body. + let parent_candidate_prototype = { + let frames = vm.execution_frames(); + let program = vm.program(); + let locals = vm.locals(); + frames.last().and_then(|frame| { + let prototype = frame + .prototype_id + .and_then(|id| program.callable_prototypes.get(id as usize))?; + if prototype.parameter_slots.len() != PUBLISHED_PARENT_PARAMS { + return None; + } + let slot = *prototype.parameter_slots.first()?; + match locals.get(frame.local_base.checked_add(usize::from(slot))?) { + Some(Value::Callable(candidate)) => Some(candidate.prototype_id), + _ => None, + } + }) + }; + + let (read, receiver_class) = { + let mut host = vm.host_context(); + let receiver_class = heap::with_heap(&mut host, |heap| Ok(heap.guest_class(receiver))) + .map_err(heap_fault)?; + let read = read_published_typed_call_head( + &mut host, + receiver, + Some(payload), + token_u64, + prepared.successor, + prepared.root_frame, + ) + .map_err(heap_fault)?; + (read, receiver_class) + }; + let token_still_open = { + let host = vm.host_context(); + host.typed_resource_with_key::( + raw_handle(token_raw)?, + &LuaUserdataResource::key(), + ) + .is_ok() + }; + let callable = read + .callable + .upgrade() + .ok_or_else(|| host_fault_error("the published head callable is no longer live"))?; + // Re-run the identity comparison against the upgraded heap Arc. The + // parent slot is read by reference and is never cloned here; this is the + // only strong Arc the producer returns. + let parent_candidate_matches = { + let frames = vm.execution_frames(); + let program = vm.program(); + let locals = vm.locals(); + frames.last().is_some_and(|frame| { + frame + .prototype_id + .and_then(|id| program.callable_prototypes.get(id as usize)) + .filter(|prototype| prototype.parameter_slots.len() == PUBLISHED_PARENT_PARAMS) + .and_then(|prototype| prototype.parameter_slots.first()) + .and_then(|slot| locals.get(frame.local_base.checked_add(usize::from(*slot))?)) + .is_some_and(|value| match value { + Value::Callable(candidate) => Arc::ptr_eq(candidate, &callable), + _ => false, + }) + }) + }; + let record = ProducerRecord { + userdata: read.userdata, + raw_token: i64::try_from(read.raw_token).unwrap_or(i64::MAX), + metatable: read.metatable, + receiver: read.receiver, + closure: read.closure, + callable: read.callable.clone(), + published_count: read.published_count, + queue_len: read.queue_len, + returned_prototype: callable.prototype_id, + receiver_class, + payload_is_head: payload == read.userdata, + token_still_open, + parent_candidate_matches, + parent_candidate_prototype, + queue_before: read.queue_before, + queue_after: read.queue_after, + top_frame_before: read.top_frame_before, + top_frame_after: read.top_frame_after, + pending_before: read.pending_before, + pending_after: read.pending_after, + settled_before: read.settled_before, + settled_after: read.settled_after, + }; + with_run_scope(vm, |scope| scope.witness.producers.push(record)); + Ok(CallOutcome::Return(CallReturn::one(Value::Callable( + callable, + )))) +} + +/// Installs the exact target `Arc` into the receiver's own metatable raw +/// `__call` record, the same heap admission the controlled field import runs, +/// and pins that installed closure generation in the prepared witness. +fn host_bind(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [owner, target] = args else { + return Err(host_fault_error("bind expects the owner and the callable")); + }; + let Value::Callable(target_arc) = target else { + return Err(host_fault_error("bind expects a callable target")); + }; + install_guest_callable_into_raw_call(vm, owner, target).map_err(heap_fault)?; + let (receiver, metatable, closure) = { + let mut host = vm.host_context(); + let class = + heap::with_heap(&mut host, |heap| Ok(heap.guest_class(owner))).map_err(heap_fault)?; + let GuestClass::Table(receiver) = class else { + return Err(host_fault_error( + "bind expects the issued receiver table carrier", + )); + }; + let metatable = heap::with_heap(&mut host, |heap| heap.metatable(receiver)) + .map_err(heap_fault)? + .ok_or_else(|| host_fault_error("bind expects the receiver metatable"))?; + let closure = heap::with_heap(&mut host, |heap| { + heap.named_closure_edge(metatable, "__call") + }) + .map_err(heap_fault)?; + let stored = heap::with_heap(&mut host, |heap| heap.closure_callable(closure)) + .map_err(heap_fault)?; + if !Arc::ptr_eq(&stored, target_arc) { + return Err(host_fault_error( + "bind's raw __call must hold the exact target Arc", + )); + } + (receiver, metatable, closure) + }; + let stored = with_run_scope(vm, |scope| { + let Some(record) = scope.witness.prepared.as_mut() else { + return false; + }; + if record.receiver != receiver { + return false; + } + record.receiver_metatable = metatable; + record.call_closure = Some(closure); + true + }); + if !stored { + return Err(host_fault_error( + "bind must follow the prepared published head for its own receiver", + )); + } + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))) +} + +/// Returns the queued successor's real typed token. It is a legal +/// `lua.userdata` handle naming a different object than the published head. +fn host_wrong_token(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + if !args.is_empty() { + return Err(host_fault_error("wrong_token takes no arguments")); + } + let raw = with_run_scope(vm, |scope| { + scope + .witness + .prepared + .as_ref() + .map(|record| record.successor_raw) + }) + .ok_or_else(|| host_fault_error("wrong_token requires the prepared published head"))?; + Ok(CallOutcome::Return(CallReturn::one(Value::Int(raw)))) +} + +/// Rewrites the receiver's raw `__call` to the given zero-capture closure +/// between the typed seam and the typed commit. Only the arm whose selected +/// mode is the raw-edge-change control performs the real heap admission; the +/// other published arms execute the same compiled call but keep their edge. +fn host_swap(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let [owner, target] = args else { + return Err(host_fault_error("swap expects the owner and the callable")); + }; + let select = with_run_scope(vm, |scope| scope.select); + if select == 6 || select == 10 { + install_guest_callable_into_raw_call(vm, owner, target).map_err(heap_fault)?; + } + Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))) +} + +/// The typed exclusive commit body. +/// +/// The operands are the parent frame's actual values: the same typed callable +/// local the following `CallValue(2)` uses, the original receiver carrier and +/// the actual typed userdata token. The body first reads a fixed snapshot and +/// the real `lua.userdata` payload, then hands those exact identities to the +/// heap's exclusive commit. That entry re-reads the live head, metatable, +/// action, issued receiver, closure `Arc`, and root plan in one borrow and +/// refuses before any write; the body never trusts the snapshot, a bare +/// handle, or the later `CallValue` check. +fn host_commit(vm: &mut Vm, args: &[Value]) -> vm::VmResult { + let entry = frame_entry(vm, COMMIT_ENTRY_LABEL); + with_run_scope(vm, |scope| scope.witness.entries.push(entry)); + + let [callable, receiver, token] = args else { + return Err(host_fault_error( + "the typed commit body expects three operands", + )); + }; + let Value::Callable(callable_arc) = callable else { + return Err(host_fault_error( + "the typed commit body received a non-callable first operand", + )); + }; + let Value::Int(token_raw) = *token else { + return Err(host_fault_error( + "the typed commit body received a non-handle token operand", + )); + }; + + let (snapshot, payload, receiver_class, weak_matches) = { + let mut host = vm.host_context(); + let snapshot = snapshot_published_typed_table_call(&mut host).map_err(heap_fault)?; + let receiver_class = heap::with_heap(&mut host, |heap| Ok(heap.guest_class(receiver))) + .map_err(heap_fault)?; + let payload = raw_handle(token_raw).ok().and_then(|handle| { + host.borrow_resource_with_key::( + handle, + &LuaUserdataResource::key(), + ) + .ok() + .map(|borrowed| borrowed.get().userdata()) + }); + let weak_matches = snapshot + .callable + .upgrade() + .is_some_and(|stored| Arc::ptr_eq(&stored, callable_arc)); + (snapshot, payload, receiver_class, weak_matches) + }; + let payload_is_head = payload == Some(snapshot.userdata); + let head_parts = ( + snapshot.userdata.domain(), + snapshot.userdata.slot(), + snapshot.userdata.generation(), + ); + let metatable_parts = ( + snapshot.metatable.domain(), + snapshot.metatable.slot(), + snapshot.metatable.generation(), + ); + let action_receiver = ( + snapshot.receiver.domain(), + snapshot.receiver.slot(), + snapshot.receiver.generation(), + ); + let action_closure = ( + snapshot.closure.domain(), + snapshot.closure.slot(), + snapshot.closure.generation(), + ); + let published_before = snapshot.published_count; + let queue_before = snapshot.queue_len; + let token_u64 = u64::try_from(token_raw).unwrap_or(u64::MAX); + + let mut host = vm.host_context(); + let outcome = commit_published_typed_table_call( + &mut host, + callable_arc, + payload, + snapshot.metatable, + receiver, + token_u64, + ); + let _ = host; + let (recorded_outcome, taken_userdata) = match &outcome { + Ok((frame, taken)) => (Ok((*frame, taken.roots_written)), Some(taken.userdata)), + Err(error) => (Err(format!("{error:?}")), None), + }; + let record = PublishedCommitRecord { + callable: callable.clone(), + receiver: receiver.clone(), + receiver_class, + token_raw, + payload_parts: payload + .map(|userdata| (userdata.domain(), userdata.slot(), userdata.generation())), + payload_is_head, + weak_matches_callable: weak_matches, + head_parts, + head_raw: i64::try_from(snapshot.raw_token).unwrap_or(i64::MAX), + metatable_parts, + action_receiver, + action_closure, + published_before, + queue_before, + outcome: recorded_outcome, + taken_userdata, + }; + with_run_scope(vm, |scope| scope.witness.commits.push(record)); + match outcome { + Ok(_) => Ok(CallOutcome::Return(CallReturn::one(Value::Bool(true)))), + Err(error) => Err(host_fault_error(format!( + "{COMMIT_REFUSAL_PREFIX}{error:?}" + ))), + } +} + +// ---- the private plugin: real lowering plus declared schemas -------------- + +#[derive(Clone, Debug)] +struct CallPatch { + completion_slot: LocalSlot, + written_callee: LocalSlot, + typed_callee: LocalSlot, + argc: u8, + arg_slots: Vec, +} + +/// The inserted pre-commit seam call: the host-import slot, the same typed +/// local the dynamic call uses, the fresh result local and the exact +/// resolution the real catalog returned. +#[derive(Clone, Debug)] +struct GatePatch { + import_index: u16, + typed_local: LocalSlot, + result_slot: LocalSlot, + resolution: ResolvedHostCall, +} + +/// The actual operand choice the published-commit arm passes to the typed +/// commit body. `Argument` is the head's real token, `Wrong` is the queued +/// successor's real token, and `ForgedArgument` additionally builds an +/// equal-valued array from the issued receiver's two integers. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CommitArgument { + Argument, + Wrong, + ForgedArgument, +} + +/// The actual fixture callable the chunk-level `bind` installs into the +/// receiver's raw `__call`. The positive and post-read-replacement controls +/// install `Target`; the before-read replacement installs `Alternate`; the +/// wrong-signature control installs `Other`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum BindChoice { + Target, + Alternate, + Other, +} + +/// The inserted exclusive commit call and its actual operand plan. +#[derive(Clone, Debug)] +struct CommitPatch { + import_index: u16, + typed_local: LocalSlot, + result_slot: LocalSlot, + resolution: ResolvedHostCall, + argument: CommitArgument, +} + +/// One resolved import the published-commit plugin adds to the IR directly. +#[derive(Clone)] +struct PublishedImport { + import_index: u16, + resolution: ResolvedHostCall, +} + +/// The resolved exclusive commit import plus the operand choice for this arm. +#[derive(Clone)] +struct PublishedCommitSpec { + import_index: u16, + resolution: ResolvedHostCall, + argument: CommitArgument, + /// The raw-edge-change arm inserts the real heap `swap` between the seam + /// and the commit. + swap: Option, +} + +#[derive(Clone, Debug, Default)] +struct PatchReport { + typed_local: Option, + declared_schema: Option, + call: Option, + gate: Option, + commit: Option, + sentinel_bind: Option, + sentinel_wrong: Option, + parent_parameters: Vec, + target_declared: bool, + alternate_declared: bool, + other_declared: bool, + continuation_rewritten: bool, + producer: bool, + producer_import: Option, +} + +impl SourcePlugin for TransportPlugin { + 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 { + let resolver = HostCallResolver::new(transport_catalog()); + let mut ir = super::lower::lower_source_with(source, Some(&resolver))?; + let report = patch_ir(&mut ir, &resolver, self.gate_mode)?; + *self.patch.lock().expect("typed resource patch report") = Some(report); + if self.pause_on_compile { + compile_interleave_gate().park(InterleavePoint::Compile); + } + Ok(ir) + } +} + +fn patch_error(message: impl Into) -> ParseError { + ParseError::at_line(1, message) +} + +/// Resolves and declares one plugin-added exact static import. +fn insert_published_import( + ir: &mut FrontendIr, + resolver: &HostCallResolver<'_>, + name: &str, + args: &[TypeSchema], + value_type: vm::ValueType, +) -> Result { + let import_index = u16::try_from(ir.functions.len()) + .map_err(|_| patch_error("too many declared host functions"))?; + let resolution = resolver + .resolve(name, args) + .map_err(|error| patch_error(format!("the {name} import did not resolve: {error}")))?; + let arity = u8::try_from(resolution.params.len()) + .map_err(|_| patch_error("a plugin import arity overflows a byte"))?; + ir.functions.push(FunctionDecl { + name: name.to_string(), + arity, + index: import_index, + args: resolution + .params + .iter() + .map(|param| param.name.clone()) + .collect(), + arg_schemas: resolution + .params + .iter() + .map(|param| Some(param.schema.clone())) + .collect(), + return_schema: Some(resolution.return_type.clone()), + type_params: Vec::new(), + exported: false, + return_type: value_type, + symbol: None, + }); + Ok(PublishedImport { + import_index, + resolution, + }) +} + +/// Adds the chunk-level `bind(recv, target)` and `wrong_token()` calls the +/// published-commit fixture cannot name itself, and rewrites the parent call's +/// eighth operand to the successor-token local. +fn patch_published_chunk( + stmts: &mut Vec, + bind: &PublishedImport, + wrong: &PublishedImport, + bind_choice: BindChoice, + next_local: &mut usize, + report: &mut PatchReport, +) -> Result { + let mut fault_position = None; + let mut receiver_slot = None; + let mut target_slot = None; + let mut alternate_slot = None; + let mut other_slot = None; + let mut parent_position = None; + for (position, stmt) in stmts.iter_mut().enumerate() { + match stmt { + Stmt::Let { + index: _, + expr: Expr::Call(_, _, _, Some(resolution), _), + .. + } if resolution.name == "fault" => { + fault_position = Some(position); + } + Stmt::Let { + index, + expr: Expr::Call(_, _, _, Some(resolution), _), + .. + } if resolution.name == "tick" => { + receiver_slot = Some(*index); + } + Stmt::Let { + index, + expr: Expr::Closure(closure), + .. + } => match closure_first_mark_label(closure) { + Some(TARGET_LABEL) => target_slot = Some(*index), + Some(ALTERNATE_LABEL) => alternate_slot = Some(*index), + Some(OTHER_LABEL) => other_slot = Some(*index), + _ => {} + }, + Stmt::Let { + expr: Expr::LocalCall(_, _, args, _), + .. + } if args.len() == PUBLISHED_PARENT_PARAMS => { + parent_position = Some(position); + } + _ => {} + } + } + let bind_slot = match bind_choice { + BindChoice::Target => target_slot, + BindChoice::Alternate => alternate_slot, + BindChoice::Other => other_slot, + }; + if let (Some(fault_position), Some(receiver_slot), Some(bind_slot), Some(parent_position)) = + (fault_position, receiver_slot, bind_slot, parent_position) + { + let bind_result = LocalSlot::try_from(*next_local) + .map_err(|_| patch_error("the bind result local overflows a slot"))?; + *next_local = next_local + .checked_add(1) + .ok_or_else(|| patch_error("too many locals for the bind result"))?; + let wrong_slot = LocalSlot::try_from(*next_local) + .map_err(|_| patch_error("the wrong-token local overflows a slot"))?; + *next_local = next_local + .checked_add(1) + .ok_or_else(|| patch_error("too many locals for the wrong token"))?; + let Stmt::Let { + expr: Expr::LocalCall(_, _, args, _), + .. + } = &mut stmts[parent_position] + else { + return Err(patch_error("the published parent call changed shape")); + }; + args[PUBLISHED_WRONG_SLOT] = Expr::Var(wrong_slot); + let bind_statement = Stmt::Let { + index: bind_result, + declared_schema: None, + expr: Expr::Call( + bind.import_index, + Vec::new(), + vec![Expr::Var(receiver_slot), Expr::Var(bind_slot)], + Some(Box::new(bind.resolution.clone())), + None, + ), + line: 1, + }; + let wrong_statement = Stmt::Let { + index: wrong_slot, + declared_schema: None, + expr: Expr::Call( + wrong.import_index, + Vec::new(), + Vec::new(), + Some(Box::new(wrong.resolution.clone())), + None, + ), + line: 1, + }; + stmts.insert(fault_position + 1, wrong_statement); + stmts.insert(fault_position + 1, bind_statement); + report.sentinel_bind = Some(bind_result); + report.sentinel_wrong = Some(wrong_slot); + return Ok(true); + } + // The completion lowering wraps the chunk statements in one block + // expression; descend until the level that owns the fault and parent call. + for stmt in stmts.iter_mut() { + let inner = match stmt { + Stmt::Expr { + expr: Expr::Block { stmts: inner, .. }, + .. + } + | Stmt::Let { + expr: Expr::Block { stmts: inner, .. }, + .. + } => inner, + _ => continue, + }; + if patch_published_chunk(inner, bind, wrong, bind_choice, next_local, report)? { + return Ok(true); + } + } + Ok(false) +} + +/// The resolved pre-commit seam the plugin installs, when the current arm asks +/// for it. +struct GateSpec { + import_index: u16, + resolution: ResolvedHostCall, + forged_receiver: bool, +} + +fn patch_ir( + ir: &mut FrontendIr, + resolver: &HostCallResolver<'_>, + gate_mode: usize, +) -> Result { + let mut report = PatchReport::default(); + let gate = if gate_mode == 0 { + None + } else { + let import_index = u16::try_from(ir.functions.len()) + .map_err(|_| patch_error("too many declared host functions"))?; + // Resolve against the real catalog with the concrete operand schemas: + // no `Unknown`, no downgraded key, no fabricated token. + let resolution = resolver + .resolve( + PRECOMMIT_IMPORT, + &[ + userdata_callable_schema(), + TypeSchema::Array(Box::new(TypeSchema::Int)), + TypeSchema::Resource(LuaUserdataResource::key()), + ], + ) + .map_err(|error| { + patch_error(format!("the precommit import did not resolve: {error}")) + })?; + let arity = u8::try_from(resolution.params.len()) + .map_err(|_| patch_error("the precommit import arity overflows a byte"))?; + // The resolver maps the catalog return to `Bool`; the compiled import + // is asserted against that exact return below. + let return_type = vm::ValueType::Bool; + // The declaration is built from the resolver output itself: names, + // concrete parameter schemas and the return stay the exact selected + // catalog identity. + ir.functions.push(FunctionDecl { + name: PRECOMMIT_IMPORT.to_string(), + arity, + index: import_index, + args: resolution + .params + .iter() + .map(|param| param.name.clone()) + .collect(), + arg_schemas: resolution + .params + .iter() + .map(|param| Some(param.schema.clone())) + .collect(), + return_schema: Some(resolution.return_type.clone()), + type_params: Vec::new(), + exported: false, + return_type, + symbol: None, + }); + Some(GateSpec { + import_index, + resolution, + forged_receiver: gate_mode == 2, + }) + }; + let producer = gate_mode >= 7; + let bind_choice = match gate_mode { + 8 => BindChoice::Alternate, + 10 => BindChoice::Other, + _ => BindChoice::Target, + }; + // A published-commit arm gets a second exact static import resolved with + // the same concrete operands. The commit body runs after the read-only + // seam and before the parent's own `CallValue(2)`. + let mut commit = if gate_mode >= 3 { + let import_index = u16::try_from(ir.functions.len()) + .map_err(|_| patch_error("too many declared host functions"))?; + let resolution = resolver + .resolve( + COMMIT_IMPORT, + &[ + userdata_callable_schema(), + TypeSchema::Array(Box::new(TypeSchema::Int)), + TypeSchema::Resource(LuaUserdataResource::key()), + ], + ) + .map_err(|error| patch_error(format!("the commit import did not resolve: {error}")))?; + let arity = u8::try_from(resolution.params.len()) + .map_err(|_| patch_error("the commit import arity overflows a byte"))?; + ir.functions.push(FunctionDecl { + name: COMMIT_IMPORT.to_string(), + arity, + index: import_index, + args: resolution + .params + .iter() + .map(|param| param.name.clone()) + .collect(), + arg_schemas: resolution + .params + .iter() + .map(|param| Some(param.schema.clone())) + .collect(), + return_schema: Some(resolution.return_type.clone()), + type_params: Vec::new(), + exported: false, + return_type: vm::ValueType::Bool, + symbol: None, + }); + let argument = match gate_mode { + 4 => CommitArgument::Wrong, + 5 => CommitArgument::ForgedArgument, + _ => CommitArgument::Argument, + }; + Some(PublishedCommitSpec { + import_index, + resolution, + argument, + swap: None, + }) + } else { + None + }; + // The published-commit fixture's chunk gets two more exact static calls + // that are not guest-lowered names: `bind(recv, target)` installs the raw + // `__call` and `wrong_token()` returns the queued successor's real token. + // The parent call's eighth operand is rewritten to that token slot. + let published_chunk = if gate_mode >= 3 { + let bind = insert_published_import( + ir, + resolver, + BIND_IMPORT, + &[TypeSchema::Unknown, TypeSchema::Unknown], + vm::ValueType::Bool, + )?; + let wrong = + insert_published_import(ir, resolver, WRONG_TOKEN_IMPORT, &[], vm::ValueType::Int)?; + if (gate_mode == 6 || gate_mode == 9) + && let Some(spec) = commit.as_mut() + { + spec.swap = Some(insert_published_import( + ir, + resolver, + SWAP_IMPORT, + &[TypeSchema::Unknown, TypeSchema::Unknown], + vm::ValueType::Bool, + )?); + } + Some((bind, wrong)) + } else { + None + }; + // The producer fixture cannot name a private host call in source. The + // plugin inserts the exact static `produce(recv, arg2)`: the callable + // operand is absent, and only the actual issued receiver carrier and the + // actual typed userdata token cross the boundary. Core's exact return + // schema is the same callable schema the typed local declares. + let produce = if producer { + Some(insert_published_import( + ir, + resolver, + PRODUCER_IMPORT, + &[ + TypeSchema::Array(Box::new(TypeSchema::Int)), + TypeSchema::Resource(LuaUserdataResource::key()), + ], + vm::ValueType::Callable, + )?) + } else { + None + }; + // Only the arms that must retire get this import. The omission arm uses + // the same fixture and the same producer rewrite, but the plugin does not + // insert the call, so the parent continuation never names it. + let retire = if gate_mode == 12 || gate_mode == FALSE_RETURN_GATE { + Some(insert_published_import( + ir, + resolver, + RETIRE_IMPORT, + &[], + vm::ValueType::Bool, + )?) + } else { + None + }; + // The guest collection import is also unnamed in source. Every retirement + // arm, including the omission arm, gets it before `done`. It does not + // leave roots. + let sweep = if matches!(gate_mode, FALSE_RETURN_GATE | 12 | 13) { + Some(insert_published_import( + ir, + resolver, + SWEEP_IMPORT, + &[], + vm::ValueType::Bool, + )?) + } else { + None + }; + let mut next_local = ir.locals; + let rewrite = ProducerRewrite { + enabled: producer, + produce: produce.as_ref(), + retire: retire.as_ref(), + observe_call: matches!(gate_mode, FALSE_RETURN_GATE | 12 | 13), + callback_false: gate_mode == FALSE_RETURN_GATE, + }; + patch_stmts( + &mut ir.stmts, + gate.as_ref(), + commit.as_ref(), + &rewrite, + &mut next_local, + &mut report, + )?; + if let Some((bind, wrong)) = &published_chunk + && !patch_published_chunk( + &mut ir.stmts, + bind, + wrong, + bind_choice, + &mut next_local, + &mut report, + )? + { + return Err(patch_error( + "the published-commit chunk is missing its fault, tick, target or parent call", + )); + } + if let Some(sweep) = sweep.as_ref() + && !insert_sweep_before_done(&mut ir.stmts, sweep, &mut next_local)? + { + return Err(patch_error( + "the retirement chunk has no done mark for the guest collection import", + )); + } + ir.locals = next_local; + report.producer = producer; + report.producer_import = produce.as_ref().map(|produce| produce.import_index); + // The private lowerer reads every admitted Lua callable through an + // explicit `ToOwned` copy. This pin classifies a callable whose schema + // contains a resource as an owned local and then refuses `.copy()` on it. + // None of the callables in this fixture is captured by a nested closure, + // so they are plain shared reads; use the same plain local read codegen + // produces for `ToOwned` and keep the exact declared schema intact. + strip_callable_copies(&mut ir.stmts); + Ok(report) +} + +fn strip_callable_copies(stmts: &mut [Stmt]) { + for stmt in stmts.iter_mut() { + match stmt { + Stmt::Let { expr, .. } | Stmt::Expr { expr, .. } => strip_to_owned(expr), + _ => {} + } + } +} + +fn strip_to_owned(expr: &mut Expr) { + if let Expr::ToOwned(inner) = expr { + strip_to_owned(inner); + if let Expr::Var(slot) = inner.as_ref().clone() { + *expr = Expr::Var(slot); + return; + } + } + match expr { + Expr::Call(_, _, args, _, _) | Expr::LocalCall(_, _, args, _) => { + for arg in args { + strip_to_owned(arg); + } + } + Expr::Closure(closure) => strip_to_owned(&mut closure.body), + Expr::ClosureCall(closure, args) => { + strip_to_owned(&mut closure.body); + for arg in args { + strip_to_owned(arg); + } + } + Expr::Block { stmts, expr } => { + strip_callable_copies(stmts); + strip_to_owned(expr); + } + Expr::IfElse { + condition, + then_expr, + else_expr, + } => { + strip_to_owned(condition); + strip_to_owned(then_expr); + strip_to_owned(else_expr); + } + _ => {} + } +} + +struct ProducerRewrite<'a> { + enabled: bool, + produce: Option<&'a PublishedImport>, + retire: Option<&'a PublishedImport>, + observe_call: bool, + callback_false: bool, +} + +fn patch_stmts( + stmts: &mut [Stmt], + gate: Option<&GateSpec>, + commit: Option<&PublishedCommitSpec>, + rewrite: &ProducerRewrite<'_>, + next_local: &mut usize, + report: &mut PatchReport, +) -> Result<(), ParseError> { + for stmt in stmts.iter_mut() { + match stmt { + Stmt::Let { + declared_schema, + expr: Expr::Closure(closure), + .. + } => { + match closure_first_mark_label(closure) { + Some(TARGET_LABEL) => { + *declared_schema = Some(userdata_callable_schema()); + report.target_declared = true; + // Core validates a script call's real return against + // the prototype's declared result. The private + // completion lowering wraps every source return into + // an array; the declared typed target returns the + // `Bool` this signature names. Only the typed target + // is rewritten: its call site is the sequential + // continuation below, and no completion consumer + // observes it. + if let Expr::Block { expr, .. } = closure.body.as_mut() { + // The false-return arm keeps the source `return true`. + // Only this compiled target result becomes `Bool(false)`, + // so the parent can tell that slot from a host `true`. + **expr = Expr::Bool(!rewrite.callback_false); + } + } + Some(ALTERNATE_LABEL) if rewrite.enabled => { + // The before-read replacement is a second real + // zero-capture closure with the same exact schema and + // its own execution marker. It is only declared on + // the producer fixture, so the original published + // arms keep their compiled shape. + *declared_schema = Some(userdata_callable_schema()); + if let Expr::Block { expr, .. } = closure.body.as_mut() { + **expr = Expr::Bool(true); + } + report.alternate_declared = true; + } + Some(OTHER_LABEL) => { + *declared_schema = Some(table_callable_schema()); + report.other_declared = true; + } + _ => {} + } + if closure.param_slots.len() == PARENT_PARAMS + || closure.param_slots.len() == PUBLISHED_PARENT_PARAMS + { + patch_parent(closure, gate, commit, rewrite, next_local, report)?; + } + } + Stmt::Expr { + expr: Expr::Block { stmts, .. }, + .. + } => patch_stmts(stmts, gate, commit, rewrite, next_local, report)?, + _ => {} + } + } + Ok(()) +} + +/// The first statement of the closure body is `mark("