feat: prepare layout and paint occurrences lazily within VM quanta

This commit is contained in:
2026-10-23 11:23:08 +08:00
parent 65f5092f0f
commit 618bffdada
3 changed files with 262 additions and 147 deletions
+95 -72
View File
@@ -10,8 +10,8 @@ use crate::{
}; };
use anyhow::Result; use anyhow::Result;
use endor_core::{ use endor_core::{
CodeLayout, ContextNativeFunction, EndorCode, EndorCodeObject, Instruction, NativeCallable, ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectRef, Value, Vm,
NativeContext, NativeResult, ObjectRef, Opcode, Value, Vm, VmError, WeakObjectRef, VmError, WeakObjectRef,
}; };
use std::{ use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet}, collections::{BTreeMap, BTreeSet, HashMap, HashSet},
@@ -479,7 +479,7 @@ impl NativeCallable for Collect {
#[derive(Debug)] #[derive(Debug)]
struct Settle { struct Settle {
plan: Shared, plan: Shared,
mounts: Vec<WeakObjectRef>, mounts: Arc<[WeakObjectRef]>,
} }
impl NativeCallable for Settle { impl NativeCallable for Settle {
fn arity(&self) -> Option<endor_core::CallArity> { fn arity(&self) -> Option<endor_core::CallArity> {
@@ -585,7 +585,7 @@ impl NativeCallable for Settle {
}; };
if repeat { if repeat {
// No stale geometry from a prior pass is observable during measurement. // No stale geometry from a prior pass is observable during measurement.
for weak in &self.mounts { for weak in self.mounts.iter() {
let mount = cx.upgrade(*weak)?.ok_or(invalid("layout Mount expired"))?; let mount = cx.upgrade(*weak)?.ok_or(invalid("layout Mount expired"))?;
if let Some(context) = &cx.store().payload::<Mount>(mount, "Mount")?.layout { if let Some(context) = &cx.store().payload::<Mount>(mount, "Mount")?.layout {
context context
@@ -609,80 +609,103 @@ impl NativeCallable for Prepare {
fn arity(&self) -> Option<endor_core::CallArity> { fn arity(&self) -> Option<endor_core::CallArity> {
Some(endor_core::CallArity::exact(0)) Some(endor_core::CallArity::exact(0))
} }
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> { fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
let mut instructions = Vec::new(); let advance = cx.allocate(ContextNativeFunction::new(
let mut constants = Vec::new(); "next layout occurrence",
for phase in [Phase::Measure, Phase::Arrange] { Advance {
let indices: Vec<_> = match phase { plan: self.plan.clone(),
Phase::Measure => (0..self.mounts.len()).rev().collect(), mounts: self.mounts.clone().into(),
Phase::Arrange => (0..self.mounts.len()).collect(), desktop: self.desktop,
}; next: Mutex::new(0),
for index in indices { },
let mount = cx vec![self.desktop],
.upgrade(self.mounts[index])? ))?;
.ok_or(invalid("layout Mount expired"))?; let function = crate::vm_sequence::repeat_call(cx, advance, "source layout", self.desktop)?;
let step = cx.allocate(ContextNativeFunction::new( Ok(NativeResult::Invoke {
"layout step", function,
Step { arguments: vec![],
plan: self.plan.clone(), })
index, }
phase, }
mount,
desktop: self.desktop, #[derive(Debug)]
}, struct Advance {
vec![mount, self.desktop], plan: Shared,
))?; mounts: Arc<[WeakObjectRef]>,
let collector = cx.allocate(ContextNativeFunction::new( desktop: ObjectRef,
"collect layout", next: Mutex<usize>,
Collect { }
plan: self.plan.clone(), impl NativeCallable for Advance {
index, fn arity(&self) -> Option<endor_core::CallArity> {
phase, Some(endor_core::CallArity::exact(0))
desktop: self.desktop, }
}, fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
vec![self.desktop], let count = self.mounts.len();
))?; let position = {
let start = constants.len() as u32; let mut next = self
constants.extend([Value::Object(collector), Value::Object(step)]); .next
instructions.extend([ .lock()
Instruction::new(Opcode::LoadConst, start), .map_err(|_| invalid("layout cursor poisoned"))?;
Instruction::simple(Opcode::PushNull), let position = *next;
Instruction::new(Opcode::LoadConst, start + 1), if position < count * 2 {
Instruction::simple(Opcode::PushNull), *next += 1;
Instruction::new(Opcode::Call, 0),
Instruction::new(Opcode::Call, 1),
Instruction::simple(Opcode::PopTop),
]);
} }
} position
let settle = cx.allocate(ContextNativeFunction::new( };
"settle source layout", if position == count * 2 {
Settle { let settled = Settle {
plan: self.plan.clone(), plan: self.plan.clone(),
mounts: self.mounts.clone(), mounts: self.mounts.clone(),
}
.invoke(cx, &[])?;
let NativeResult::Return(Value::Bool(repeat)) = settled else {
return Err(invalid("invalid settling result"));
};
if repeat {
*self
.next
.lock()
.map_err(|_| invalid("layout cursor poisoned"))? = 0;
}
return Ok(NativeResult::Return(Value::Bool(repeat)));
}
let (phase, index) = if position < count {
(Phase::Measure, count - position - 1)
} else {
(Phase::Arrange, position - count)
};
let mount = cx
.upgrade(self.mounts[index])?
.ok_or(invalid("layout Mount expired"))?;
let step = cx.allocate(ContextNativeFunction::new(
"layout step",
Step {
plan: self.plan.clone(),
index,
phase,
mount,
desktop: self.desktop,
}, },
vec![], vec![mount, self.desktop],
))?; ))?;
let check = constants.len() as u32; let collector = cx.allocate(ContextNativeFunction::new(
constants.push(Value::Object(settle)); "collect layout",
instructions.extend([ Collect {
Instruction::new(Opcode::LoadConst, check), plan: self.plan.clone(),
Instruction::simple(Opcode::PushNull), index,
Instruction::new(Opcode::Call, 0), phase,
]); desktop: self.desktop,
crate::vm_sequence::repeat_while(&mut instructions)?; },
let end = constants.len() as u32; vec![self.desktop],
constants.push(Value::Nil); ))?;
instructions.extend([ let function = crate::vm_sequence::collect_and_continue(
Instruction::new(Opcode::LoadConst, end), cx,
Instruction::simple(Opcode::ReturnValue), collector,
]); step,
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())? vec![],
.with_location("<source layout>", "<tessera>", 1); "layout occurrence",
let code = cx.allocate(EndorCodeObject::new(code))?; self.desktop,
let globals = cx.new_dict()?; )?;
let function = cx.new_function("source layout", code, globals)?;
Ok(NativeResult::Invoke { Ok(NativeResult::Invoke {
function, function,
arguments: vec![], arguments: vec![],
+91 -75
View File
@@ -9,8 +9,8 @@ use crate::{
}; };
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use endor_core::{ use endor_core::{
CodeLayout, ContextNativeFunction, EndorCode, EndorCodeObject, Instruction, NativeCallable, ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectRef, ObjectStore,
NativeContext, NativeResult, ObjectRef, ObjectStore, Opcode, Value, Vm, VmError, WeakObjectRef, Value, Vm, VmError, WeakObjectRef,
}; };
use std::{ use std::{
collections::{BTreeMap, BTreeSet, HashMap}, collections::{BTreeMap, BTreeSet, HashMap},
@@ -189,83 +189,99 @@ impl NativeCallable for Prepare {
} }
fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> { fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
let mut constants = Vec::new(); let advance = cx.allocate(ContextNativeFunction::new(
let mut instructions = Vec::new(); "next paint occurrence",
for (id, weak) in &self.mounts { Advance {
let mount = cx desktop: self.desktop,
.upgrade(*weak)? mounts: self.mounts.clone().into(),
.ok_or(invalid("paint Mount has expired"))?; next: Mutex::new(0),
let data = cx.store().payload::<Mount>(mount, "Mount")?.clone(); output: self.output.clone(),
if !data.mounted { },
return Err(invalid("paint Mount is detached")); vec![self.desktop],
} ))?;
let definition = cx let function = crate::vm_sequence::repeat_call(cx, advance, "source paint", self.desktop)?;
.store() Ok(NativeResult::Invoke {
.type_of(data.block)? function,
.ok_or(invalid("untyped paint target"))?; arguments: vec![],
let function = cx })
.store() }
.lookup_method(definition, "paint")? }
.ok_or(invalid("missing paint method"))?;
if crate::native_visual::is_intrinsic(cx.store(), function, "paint", self.desktop)? { #[derive(Debug)]
continue; struct Advance {
} desktop: ObjectRef,
let bounds = cx.new_object()?; mounts: Arc<[(u64, WeakObjectRef)]>,
attach_desktop_type(cx, bounds, "Bounds", self.desktop)?; next: Mutex<usize>,
for (name, value) in [ output: Output,
("x", data.geometry.x), }
("y", data.geometry.y), impl NativeCallable for Advance {
("width", data.geometry.width), fn arity(&self) -> Option<endor_core::CallArity> {
("height", data.geometry.height), Some(endor_core::CallArity::exact(0))
] { }
cx.set_attr(bounds, name, Value::Number((value as f64).into()))?; fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
} let occurrence = {
let collector = cx.allocate(ContextNativeFunction::new( let mut next = self
"collect source paint", .next
Collect { .lock()
desktop: self.desktop, .map_err(|_| invalid("paint cursor poisoned"))?;
mount: *id, let occurrence = self.mounts.get(*next).copied();
output: self.output.clone(), *next += usize::from(occurrence.is_some());
}, occurrence
vec![self.desktop], };
))?; let Some((id, weak)) = occurrence else {
let start = constants.len() as u32; return Ok(NativeResult::Return(Value::Bool(false)));
constants.extend([ };
Value::Object(collector), let mount = cx
Value::Object(function), .upgrade(weak)?
.ok_or(invalid("paint Mount has expired"))?;
let data = cx.store().payload::<Mount>(mount, "Mount")?.clone();
if !data.mounted {
return Err(invalid("paint Mount is detached"));
}
let definition = cx
.store()
.type_of(data.block)?
.ok_or(invalid("untyped paint target"))?;
let function = cx
.store()
.lookup_method(definition, "paint")?
.ok_or(invalid("missing paint method"))?;
if crate::native_visual::is_intrinsic(cx.store(), function, "paint", self.desktop)? {
return Ok(NativeResult::Return(Value::Bool(true)));
}
let bounds = cx.new_object()?;
attach_desktop_type(cx, bounds, "Bounds", self.desktop)?;
for (name, value) in [
("x", data.geometry.x),
("y", data.geometry.y),
("width", data.geometry.width),
("height", data.geometry.height),
] {
cx.set_attr(bounds, name, Value::Number((value as f64).into()))?;
}
let collector = cx.allocate(ContextNativeFunction::new(
"collect source paint",
Collect {
desktop: self.desktop,
mount: id,
output: self.output.clone(),
},
vec![self.desktop],
))?;
let function = crate::vm_sequence::collect_and_continue(
cx,
collector,
function,
vec![
Value::Object(data.block), Value::Object(data.block),
Value::Object(mount), Value::Object(mount),
Value::Object(bounds), Value::Object(bounds),
]); ],
instructions.extend([ "paint occurrence",
Instruction::new(Opcode::LoadConst, start), self.desktop,
Instruction::simple(Opcode::PushNull), )?;
Instruction::new(Opcode::LoadConst, start + 1),
Instruction::simple(Opcode::PushNull),
Instruction::new(Opcode::LoadConst, start + 2),
Instruction::new(Opcode::LoadConst, start + 3),
Instruction::new(Opcode::LoadConst, start + 4),
Instruction::new(Opcode::Call, 3),
Instruction::new(Opcode::Call, 1),
Instruction::simple(Opcode::PopTop),
]);
}
if instructions.is_empty() {
return Ok(NativeResult::Return(Value::Nil));
}
let index = constants.len() as u32;
constants.push(Value::Nil);
instructions.extend([
Instruction::new(Opcode::LoadConst, index),
Instruction::simple(Opcode::ReturnValue),
]);
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
.with_location("<source paint>", "<tessera>", 1);
let code = cx.allocate(EndorCodeObject::new(code))?;
let globals = cx.new_dict()?;
let driver = cx.new_function("source paint", code, globals)?;
Ok(NativeResult::Invoke { Ok(NativeResult::Invoke {
function: driver, function,
arguments: vec![], arguments: vec![],
}) })
} }
+76
View File
@@ -34,6 +34,82 @@ pub fn build(
Ok(driver) Ok(driver)
} }
/// A fixed-size driver. Each callback returns whether another occurrence is
/// needed; delegated source calls and all iterations share this VM budget.
pub fn repeat_call(
cx: &mut NativeContext<'_>,
callback: ObjectRef,
name: &'static str,
desktop: ObjectRef,
) -> Result<ObjectRef, VmError> {
let mut instructions = vec![
Instruction::new(Opcode::LoadConst, 0),
Instruction::simple(Opcode::PushNull),
Instruction::new(Opcode::Call, 0),
];
repeat_while(&mut instructions)?;
instructions.extend([
Instruction::new(Opcode::LoadConst, 1),
Instruction::simple(Opcode::ReturnValue),
]);
driver(
cx,
instructions,
vec![Value::Object(callback), Value::Nil],
name,
desktop,
)
}
/// Prepare only the current occurrence, collect its result, then continue the
/// outer driver. The helper frame and its managed captures die before the next.
pub fn collect_and_continue(
cx: &mut NativeContext<'_>,
collector: ObjectRef,
function: ObjectRef,
arguments: Vec<Value>,
name: &'static str,
desktop: ObjectRef,
) -> Result<ObjectRef, VmError> {
let count = arguments.len();
let mut constants = vec![Value::Object(collector), Value::Object(function)];
constants.extend(arguments);
constants.push(Value::Bool(true));
let mut instructions = vec![
Instruction::new(Opcode::LoadConst, 0),
Instruction::simple(Opcode::PushNull),
Instruction::new(Opcode::LoadConst, 1),
Instruction::simple(Opcode::PushNull),
];
for index in 0..count {
instructions.push(Instruction::new(Opcode::LoadConst, index as u32 + 2));
}
instructions.extend([
Instruction::new(Opcode::Call, count as u32),
Instruction::new(Opcode::Call, 1),
Instruction::simple(Opcode::PopTop),
Instruction::new(Opcode::LoadConst, count as u32 + 2),
Instruction::simple(Opcode::ReturnValue),
]);
driver(cx, instructions, constants, name, desktop)
}
fn driver(
cx: &mut NativeContext<'_>,
instructions: Vec<Instruction>,
constants: Vec<Value>,
name: &'static str,
desktop: ObjectRef,
) -> Result<ObjectRef, VmError> {
let code = EndorCode::from_instructions(&instructions, constants, CodeLayout::default())?
.with_location(name, "<tessera>", 1);
let code = cx.allocate(EndorCodeObject::new(code))?;
let globals = cx.new_dict()?;
let function = cx.new_function(name, code, globals)?;
crate::ui_bridge::attach_desktop_type(cx, function, "Function", desktop)?;
Ok(function)
}
/// Consume the condition on the stack: true repeats this same frame from zero, /// Consume the condition on the stack: true repeats this same frame from zero,
/// false falls through. Operand widths include EXTENDED_ARG code units. /// false falls through. Operand widths include EXTENDED_ARG code units.
pub fn repeat_while(instructions: &mut Vec<Instruction>) -> Result<(), VmError> { pub fn repeat_while(instructions: &mut Vec<Instruction>) -> Result<(), VmError> {