feat: notify Endor objects of mount lifecycle transitions
Verify Tessera GUI / verify (push) Failing after 7m23s
Verify Tessera GUI / verify (push) Failing after 7m23s
This commit is contained in:
+2
-1
@@ -10,9 +10,10 @@
|
||||
| ui_bridge.rs | Inheritable native nominal constructors with source fields, shared type method tables and bound receiver dispatch, tab registry, Page lifecycle/navigation and immutable frame extraction |
|
||||
| block.rs | Aster-managed Block/Cell/data graph, stable child slots, content-owned field storage, shared assignment, cycle validation and explicit text bindings |
|
||||
| snapshot.rs | Property dependencies across shared field-storage paths, reverse parent links and cached immutable visual derivation |
|
||||
| mount.rs | Managed per-occurrence contexts, weak reverse links, geometry and focus queries |
|
||||
| mount.rs | Managed per-occurrence contexts, weak reverse links, ordered mount/unmount hooks, geometry and focus queries |
|
||||
| events.rs | Bounded native input transport to the owning VM |
|
||||
| event_dispatch.rs | Managed Event, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver |
|
||||
| vm_sequence.rs | Shared validated call-sequence builder for event and lifecycle batches in the existing VM frame loop |
|
||||
| layout.rs | Iterative measurement/arrangement, stable occurrence IDs, measurement cache and geometry budgets |
|
||||
| document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation and display commands |
|
||||
| app.rs | Window events, redraw and system widget pointer/keyboard/IME routing |
|
||||
|
||||
+154
-3
@@ -312,7 +312,7 @@ impl ReplSession {
|
||||
pub fn execute(&mut self, source: &str, namespace: &str) -> Result<ReplResult> {
|
||||
if self.faulted {
|
||||
bail!(
|
||||
"runtime stopped after an event failure; reset the session or replace its program"
|
||||
"runtime stopped after a callback or rendering failure; reset the session or replace its program"
|
||||
);
|
||||
}
|
||||
if source.len() > MAX_SOURCE_BYTES {
|
||||
@@ -492,7 +492,7 @@ impl ReplSession {
|
||||
|
||||
pub fn dispatch(&mut self, input: &crate::events::Input) -> Result<ReplResult> {
|
||||
if self.faulted {
|
||||
bail!("runtime stopped after an event failure");
|
||||
bail!("runtime stopped after a callback or rendering failure");
|
||||
}
|
||||
if input.session != self.id {
|
||||
bail!("event belongs to another runtime session");
|
||||
@@ -576,7 +576,7 @@ impl Drop for Candidate {
|
||||
}
|
||||
}
|
||||
|
||||
fn runtime_error(vm: &Vm, error: VmError) -> anyhow::Error {
|
||||
pub(crate) fn runtime_error(vm: &Vm, error: VmError) -> anyhow::Error {
|
||||
let locations = vm
|
||||
.last_traceback()
|
||||
.iter()
|
||||
@@ -795,6 +795,157 @@ mod tests {
|
||||
const EXAMPLE: &str = include_str!("../examples/hello.endor");
|
||||
const PAGE: &str = include_str!("../examples/page.endor");
|
||||
|
||||
#[test]
|
||||
fn mount_hooks_run_per_occurrence_settle_and_unmount_before_parent() {
|
||||
let (mut session, initial) = ReplSession::load(
|
||||
include_str!("../examples/mount-lifecycle.endor"),
|
||||
"app.main",
|
||||
51,
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
initial.validate().unwrap();
|
||||
for (expression, expected) in [
|
||||
("log.mounted.value", "2"),
|
||||
("log.parentMounted", "1"),
|
||||
("log.childMounted", "3"),
|
||||
] {
|
||||
assert_eq!(
|
||||
session.execute(expression, "app.main").unwrap().value,
|
||||
expected
|
||||
);
|
||||
}
|
||||
session
|
||||
.execute(
|
||||
"saved = child.mounts().at(0)\nchild.setColor(\"#237A45\")",
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("log.mounted.value", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"2"
|
||||
);
|
||||
let closed = session
|
||||
.execute("page.close()", "app.main")
|
||||
.unwrap()
|
||||
.document
|
||||
.unwrap();
|
||||
assert!(closed.frame.mounts.is_empty());
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("log.unmounted.value", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"2"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("log.childUnmounted", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"5"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("log.parentUnmounted", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"6"
|
||||
);
|
||||
assert_eq!(
|
||||
session.execute("saved.mounted", "app.main").unwrap().value,
|
||||
"false"
|
||||
);
|
||||
assert!(session.execute("saved.bounds()", "app.main").is_err());
|
||||
session.execute("page.open()", "app.main").unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("log.mounted.value", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"4"
|
||||
);
|
||||
assert_eq!(
|
||||
session.execute("saved.mounted", "app.main").unwrap().value,
|
||||
"false"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_switch_replaces_mount_context_even_for_shared_root() {
|
||||
let (mut session, _) = ReplSession::load(
|
||||
include_str!("../examples/mount-lifecycle.endor"),
|
||||
"app.main",
|
||||
52,
|
||||
1,
|
||||
)
|
||||
.unwrap();
|
||||
session
|
||||
.execute(
|
||||
"saved = child.mounts().at(0)\nsecond = Page()\nsecond.render(root)",
|
||||
"app.main",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("log.mounted.value", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"4"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("log.unmounted.value", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"2"
|
||||
);
|
||||
assert_eq!(
|
||||
session.execute("saved.mounted", "app.main").unwrap().value,
|
||||
"false"
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("child.mounts().at(0).page()", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
session.execute("second", "app.main").unwrap().value
|
||||
);
|
||||
session.execute("page.activate()", "app.main").unwrap();
|
||||
assert_eq!(
|
||||
session
|
||||
.execute("log.mounted.value", "app.main")
|
||||
.unwrap()
|
||||
.value,
|
||||
"6"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_hook_can_edit_container_without_session_lock_and_failure_stops_domain() {
|
||||
let source = r#"class GrowingColumn: Column {
|
||||
function onMount(self: GrowingColumn, mount: Mount): Unit { self.append(TextBlock("from hook")) }
|
||||
}
|
||||
root = GrowingColumn(0, 0)
|
||||
page = Page()
|
||||
page.render(root)"#;
|
||||
let (_, document) = ReplSession::load(source, "app.main", 53, 1).unwrap();
|
||||
assert!(document.frame.commands.iter().any(
|
||||
|command| matches!(command, RenderCommand::Text { value, .. } if value == "from hook")
|
||||
));
|
||||
let mut session = ReplSession::new(54).unwrap();
|
||||
let source = r#"class BrokenText: TextBlock {
|
||||
function onMount(self: BrokenText, mount: Mount): Unit { self.setText(1) }
|
||||
}
|
||||
page = Page()
|
||||
page.render(BrokenText("x"))"#;
|
||||
assert!(session.execute(source, "app.main").is_err());
|
||||
assert!(session.is_faulted());
|
||||
}
|
||||
|
||||
fn event_session(extra: &str) -> (ReplSession, RenderDocument) {
|
||||
let source = format!("{}\n{}", include_str!("../examples/events.endor"), extra);
|
||||
ReplSession::load(&source, "app.main", 41, 1).unwrap()
|
||||
|
||||
+3
-23
@@ -2,9 +2,8 @@
|
||||
//! function sequences calls, so all handlers share one execution budget.
|
||||
use crate::{block, mount::Mount, ui_bridge::attach_desktop_type};
|
||||
use endor_core::{
|
||||
CodeLayout, ContextNativeFunction, EndorCode, EndorCodeObject, Instruction, NativeCallable,
|
||||
NativeContext, NativeResult, ObjectPayload, ObjectRef, Opcode, Value, Vm, VmError,
|
||||
WeakObjectRef,
|
||||
ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectPayload, ObjectRef,
|
||||
Value, Vm, VmError, WeakObjectRef,
|
||||
};
|
||||
|
||||
const MAX_DELIVERIES: usize = 10_000;
|
||||
@@ -407,26 +406,7 @@ pub fn dispatch(
|
||||
vec![event_ref, guard],
|
||||
))?;
|
||||
calls.push(finish);
|
||||
let mut instructions = Vec::with_capacity(calls.len() * 4 + 1);
|
||||
for index in 0..calls.len() {
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, index as u32));
|
||||
instructions.push(Instruction::simple(Opcode::PushNull));
|
||||
instructions.push(Instruction::new(Opcode::Call, 0));
|
||||
if index + 1 != calls.len() {
|
||||
instructions.push(Instruction::simple(Opcode::PopTop));
|
||||
}
|
||||
}
|
||||
instructions.push(Instruction::simple(Opcode::ReturnValue));
|
||||
let code = EndorCode::from_instructions(
|
||||
&instructions,
|
||||
calls.into_iter().map(Value::Object).collect(),
|
||||
CodeLayout::default(),
|
||||
)?
|
||||
.with_location("<event dispatch>", "<tessera>", 1);
|
||||
let code = cx.allocate(EndorCodeObject::new(code))?;
|
||||
let globals = cx.new_dict()?;
|
||||
let driver = cx.new_function("event dispatch", code, globals)?;
|
||||
attach_desktop_type(cx, driver, "Function", desktop)?;
|
||||
let driver = crate::vm_sequence::build(cx, calls, "<event dispatch>", desktop)?;
|
||||
event.dispatch = Some(cx.store().downgrade(guard)?);
|
||||
event.group = 0;
|
||||
event.stopped_at = None;
|
||||
|
||||
@@ -20,6 +20,7 @@ mod sources;
|
||||
mod system_ui;
|
||||
mod text;
|
||||
mod ui_bridge;
|
||||
mod vm_sequence;
|
||||
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
|
||||
+89
-9
@@ -58,7 +58,7 @@ struct Method {
|
||||
impl NativeCallable for Method {
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let mount = cx.store().payload::<Mount>(self.owner, "Mount")?.clone();
|
||||
if !mount.mounted {
|
||||
if !mount.mounted && matches!(self.query, Query::Bounds | Query::Focus | Query::HitTest) {
|
||||
return Err(VmError::InvalidArgument("Mount is no longer attached"));
|
||||
}
|
||||
let arity = if matches!(self.query, Query::HitTest) {
|
||||
@@ -150,6 +150,7 @@ impl NativeCallable for Method {
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct MountTable {
|
||||
pub active: HashMap<u64, WeakObjectRef>,
|
||||
order: Vec<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -158,10 +159,51 @@ struct Sync {
|
||||
page: Option<ObjectRef>,
|
||||
nodes: Vec<WeakObjectRef>,
|
||||
old: HashMap<u64, WeakObjectRef>,
|
||||
old_order: Vec<u64>,
|
||||
frame: Frame,
|
||||
output: Arc<Mutex<HashMap<u64, WeakObjectRef>>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct LifecycleCall {
|
||||
function: ObjectRef,
|
||||
block: ObjectRef,
|
||||
mount: ObjectRef,
|
||||
}
|
||||
impl NativeCallable for LifecycleCall {
|
||||
fn invoke(&self, _: &mut NativeContext<'_>, _: &[Value]) -> Result<NativeResult, VmError> {
|
||||
Ok(NativeResult::Invoke {
|
||||
function: self.function,
|
||||
arguments: vec![Value::Object(self.block), Value::Object(self.mount)],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn lifecycle_call(
|
||||
cx: &mut NativeContext<'_>,
|
||||
mount: ObjectRef,
|
||||
name: &'static str,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
let block = cx.store().payload::<Mount>(mount, "Mount")?.block;
|
||||
let definition = cx
|
||||
.store()
|
||||
.type_of(block)?
|
||||
.ok_or(VmError::InvalidArgument("untyped mounted Block"))?;
|
||||
let function = cx
|
||||
.store()
|
||||
.lookup_method(definition, name)?
|
||||
.ok_or(VmError::InvalidArgument("Block has no lifecycle method"))?;
|
||||
cx.allocate(ContextNativeFunction::new(
|
||||
name,
|
||||
LifecycleCall {
|
||||
function,
|
||||
block,
|
||||
mount,
|
||||
},
|
||||
vec![function, block, mount],
|
||||
))
|
||||
}
|
||||
|
||||
impl NativeCallable for Sync {
|
||||
fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result<NativeResult, VmError> {
|
||||
let mut blocks = HashMap::new();
|
||||
@@ -175,6 +217,7 @@ impl NativeCallable for Sync {
|
||||
.map(|page| cx.store().downgrade(page))
|
||||
.transpose()?;
|
||||
let mut objects = HashMap::new();
|
||||
let mut created = Vec::new();
|
||||
for geometry in &self.frame.mounts {
|
||||
let block = *blocks
|
||||
.get(&geometry.block_id)
|
||||
@@ -187,7 +230,13 @@ impl NativeCallable for Sync {
|
||||
.map(|weak| cx.upgrade(*weak))
|
||||
.transpose()?
|
||||
.flatten();
|
||||
let object = if let Some(old) = old {
|
||||
let reusable = if let Some(old) = old {
|
||||
let mount = cx.store().payload::<Mount>(old, "Mount")?;
|
||||
(mount.mounted && mount.page == page && mount.block == block).then_some(old)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let object = if let Some(old) = reusable {
|
||||
old
|
||||
} else {
|
||||
let object = cx.allocate(Mount {
|
||||
@@ -223,6 +272,7 @@ impl NativeCallable for Sync {
|
||||
}
|
||||
cx.set_attr(object, "id", Value::Number((geometry.id as i64).into()))?;
|
||||
cx.set_attr(object, "block", Value::Object(block))?;
|
||||
created.push(object);
|
||||
object
|
||||
};
|
||||
objects.insert(geometry.id, object);
|
||||
@@ -245,6 +295,7 @@ impl NativeCallable for Sync {
|
||||
};
|
||||
let old = cx.store().payload::<Mount>(object, "Mount")?;
|
||||
if !old.mounted
|
||||
|| old.version != mount.version
|
||||
|| old.geometry != mount.geometry
|
||||
|| old.page != mount.page
|
||||
|| old.parent != mount.parent
|
||||
@@ -269,9 +320,13 @@ impl NativeCallable for Sync {
|
||||
Value::Object(object),
|
||||
)?;
|
||||
}
|
||||
for (id, weak) in &self.old {
|
||||
if !objects.contains_key(id)
|
||||
&& let Some(object) = cx.upgrade(*weak)?
|
||||
let mut hooks = Vec::new();
|
||||
// Layout records are preorder; reversing guarantees children unmount
|
||||
// before their parents. A Page change creates fresh Mount contexts.
|
||||
for id in self.old_order.iter().rev() {
|
||||
let weak = self.old[id];
|
||||
if let Some(object) = cx.upgrade(weak)?
|
||||
&& objects.get(id) != Some(&object)
|
||||
{
|
||||
let mut mount = cx.store().payload::<Mount>(object, "Mount")?.clone();
|
||||
mount.mounted = false;
|
||||
@@ -280,8 +335,22 @@ impl NativeCallable for Sync {
|
||||
mount.next_sibling = None;
|
||||
cx.replace_payload(object, mount)?;
|
||||
cx.set_attr(object, "mounted", Value::Bool(false))?;
|
||||
hooks.push(lifecycle_call(cx, object, "onUnmount")?);
|
||||
}
|
||||
}
|
||||
for object in created {
|
||||
hooks.push(lifecycle_call(cx, object, "onMount")?);
|
||||
}
|
||||
let driver = if hooks.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(crate::vm_sequence::build(
|
||||
cx,
|
||||
hooks,
|
||||
"<mount lifecycle>",
|
||||
self.desktop,
|
||||
)?)
|
||||
};
|
||||
let weak = objects
|
||||
.into_iter()
|
||||
.map(|(id, object)| Ok((id, cx.store().downgrade(object)?)))
|
||||
@@ -291,7 +360,9 @@ impl NativeCallable for Sync {
|
||||
.output
|
||||
.lock()
|
||||
.map_err(|_| VmError::InvalidArgument("Mount registry poisoned"))? = weak;
|
||||
Ok(NativeResult::Return(Value::Nil))
|
||||
Ok(NativeResult::Return(
|
||||
driver.map(Value::Object).unwrap_or(Value::Nil),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,7 +374,7 @@ impl MountTable {
|
||||
page: Option<ObjectRef>,
|
||||
nodes: Vec<WeakObjectRef>,
|
||||
frame: &Frame,
|
||||
) -> Result<(), VmError> {
|
||||
) -> Result<Option<ObjectRef>, VmError> {
|
||||
let output = Arc::new(Mutex::new(HashMap::new()));
|
||||
let mut captures = vec![desktop];
|
||||
captures.extend(page);
|
||||
@@ -314,6 +385,7 @@ impl MountTable {
|
||||
page,
|
||||
nodes,
|
||||
old: self.active.clone(),
|
||||
old_order: self.order.clone(),
|
||||
frame: frame.clone(),
|
||||
output: output.clone(),
|
||||
},
|
||||
@@ -321,13 +393,21 @@ impl MountTable {
|
||||
))?;
|
||||
let result = vm.call(function, &[]);
|
||||
vm.release(function)?;
|
||||
vm.release_value(result?)?;
|
||||
let result = result?;
|
||||
self.active = std::mem::take(
|
||||
&mut *output
|
||||
.lock()
|
||||
.map_err(|_| VmError::InvalidArgument("Mount registry poisoned"))?,
|
||||
);
|
||||
Ok(())
|
||||
self.order = frame.mounts.iter().map(|mount| mount.id).collect();
|
||||
match result {
|
||||
Value::Object(hooks) => Ok(Some(hooks)),
|
||||
Value::Nil => Ok(None),
|
||||
value => {
|
||||
vm.release_value(value)?;
|
||||
Err(VmError::InvalidArgument("invalid lifecycle batch"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+40
-13
@@ -210,6 +210,8 @@ enum Operation {
|
||||
On,
|
||||
Dispatch,
|
||||
OnEvent,
|
||||
OnMount,
|
||||
OnUnmount,
|
||||
Click,
|
||||
Present,
|
||||
}
|
||||
@@ -493,7 +495,7 @@ impl NativeCallable for Function {
|
||||
Click => (0, 1),
|
||||
On => (2, 3),
|
||||
Dispatch => (1, 2),
|
||||
OnEvent => (1, 1),
|
||||
OnEvent | OnMount | OnUnmount => (1, 1),
|
||||
};
|
||||
if !(minimum..=maximum).contains(&args.len()) {
|
||||
return Err(invalid("incorrect UI method argument count"));
|
||||
@@ -916,7 +918,7 @@ impl NativeCallable for Function {
|
||||
data.subscriptions = active;
|
||||
result = Value::Object(token);
|
||||
}
|
||||
OnEvent => return Ok(NativeResult::Return(Value::Nil)),
|
||||
OnEvent | OnMount | OnUnmount => return Ok(NativeResult::Return(Value::Nil)),
|
||||
Click | Dispatch => {
|
||||
let desktop = self
|
||||
.session
|
||||
@@ -1095,19 +1097,42 @@ impl UiBridge {
|
||||
let page = state.pending.unwrap_or(state.active);
|
||||
let desktop = state.desktop;
|
||||
let nodes = state.nodes.clone();
|
||||
state.mounts.synchronize(vm, desktop, page, nodes, frame)?;
|
||||
if snapshot.is_none() {
|
||||
state.layout.clear_occurrences();
|
||||
let hooks = state.mounts.synchronize(vm, desktop, page, nodes, frame)?;
|
||||
let result = (|| {
|
||||
if snapshot.is_none() {
|
||||
state.layout.clear_occurrences();
|
||||
}
|
||||
if let Some(page) = state.pending.take() {
|
||||
state.active = page;
|
||||
}
|
||||
vm.set_attr(state.desktop, "pending", Value::Nil)?;
|
||||
vm.set_attr(state.desktop, "focusRequested", Value::Bool(false))?;
|
||||
state.last_snapshot = snapshot;
|
||||
state.published_version = frame.layout_version;
|
||||
// Hooks may call Page/container APIs; never hold the session mutex
|
||||
// across user code. Publish only after the refresh loop settles.
|
||||
drop(state);
|
||||
if let Some(hooks) = hooks {
|
||||
let value = vm
|
||||
.call_with_limits(
|
||||
hooks,
|
||||
&[],
|
||||
endor_core::ExecutionLimits {
|
||||
max_frames: 128,
|
||||
max_instructions: 1_000_000,
|
||||
},
|
||||
)
|
||||
.map_err(|error| crate::endor_host::runtime_error(vm, error))?;
|
||||
vm.release_value(value)?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Some(hooks) = hooks {
|
||||
vm.release(hooks)?;
|
||||
}
|
||||
if let Some(page) = state.pending.take() {
|
||||
state.active = page;
|
||||
}
|
||||
vm.set_attr(state.desktop, "pending", Value::Nil)?;
|
||||
vm.set_attr(state.desktop, "focusRequested", Value::Bool(false))?;
|
||||
state.last_snapshot = snapshot;
|
||||
state.published_version = frame.layout_version;
|
||||
Ok(())
|
||||
result
|
||||
}
|
||||
|
||||
pub fn layout_frame(&self, vm: &Vm, root: &UiNode) -> Result<crate::document::Frame> {
|
||||
let mut state = self
|
||||
.session
|
||||
@@ -1291,6 +1316,8 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
|
||||
("Block", "on", Operation::On),
|
||||
("Block", "dispatch", Operation::Dispatch),
|
||||
("Block", "onEvent", Operation::OnEvent),
|
||||
("Block", "onMount", Operation::OnMount),
|
||||
("Block", "onUnmount", Operation::OnUnmount),
|
||||
("Block", "click", Operation::Click),
|
||||
("TextBlock", "setText", Operation::SetText),
|
||||
("TextBlock", "setColor", Operation::SetColor),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Validated call sequences share the current VM budget and explicit frames.
|
||||
use endor_core::{
|
||||
CodeLayout, EndorCode, EndorCodeObject, Instruction, NativeContext, ObjectRef, Opcode, Value,
|
||||
VmError,
|
||||
};
|
||||
|
||||
pub fn build(
|
||||
cx: &mut NativeContext<'_>,
|
||||
calls: Vec<ObjectRef>,
|
||||
name: &'static str,
|
||||
desktop: ObjectRef,
|
||||
) -> Result<ObjectRef, VmError> {
|
||||
let mut instructions = Vec::with_capacity(calls.len() * 4 + 2);
|
||||
let mut constants: Vec<Value> = calls.into_iter().map(Value::Object).collect();
|
||||
for index in 0..constants.len() {
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, index as u32));
|
||||
instructions.push(Instruction::simple(Opcode::PushNull));
|
||||
instructions.push(Instruction::new(Opcode::Call, 0));
|
||||
if index + 1 != constants.len() {
|
||||
instructions.push(Instruction::simple(Opcode::PopTop));
|
||||
}
|
||||
}
|
||||
if constants.is_empty() {
|
||||
constants.push(Value::Nil);
|
||||
instructions.push(Instruction::new(Opcode::LoadConst, 0));
|
||||
}
|
||||
instructions.push(Instruction::simple(Opcode::ReturnValue));
|
||||
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 driver = cx.new_function(name, code, globals)?;
|
||||
crate::ui_bridge::attach_desktop_type(cx, driver, "Function", desktop)?;
|
||||
Ok(driver)
|
||||
}
|
||||
Reference in New Issue
Block a user