feat: construct native visual subclasses from Endor source
Verify Tessera GUI / verify (push) Successful in 9m53s

This commit is contained in:
2026-10-21 02:06:25 +08:00
parent 0d5e4b318d
commit 6c42e5dde4
9 changed files with 259 additions and 22 deletions
+3 -3
View File
@@ -7,9 +7,9 @@
| activity.rs | Bounded in-memory HTTP exchanges with marked previews and allowlisted request headers |
| endor_host.rs | Aster compilation, fresh PUT candidates retained after successful publication, shared Console/program VM, bounded execution, root cleanup and AST developer tree for function/class/member assignment nodes |
| endor_script.rs | Batch complete inputs for Aster's Interactive parser/compiler, retain Module entry, and rebase Aster spans to the original snapshot |
| ui_bridge.rs | Managed nominal type constructors, 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, shared assignment, cycle validation and explicit text bindings |
| snapshot.rs | Property dependencies, reverse parent links and cached immutable visual derivation |
| 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 |
| events.rs | Managed Event marker and bounded native input transport to the owning VM |
| layout.rs | Iterative measurement/arrangement, stable occurrence IDs, measurement cache and geometry budgets |
+24 -1
View File
@@ -41,6 +41,23 @@ pub struct Block {
}
impl ObjectPayload for Block {
fn attribute_target(&self, store: &ObjectStore) -> Result<Option<ObjectRef>, VmError> {
let Value::Object(value) = store.cell_get(self.state)? else {
return Err(VmError::InvalidArgument("Block state is not an object"));
};
if store.object(value)?.payload().as_any().is::<Block>() {
Ok(Some(value))
} else {
store
.payload::<Data>(value, "Block data")?
.properties
.map(Some)
.ok_or(VmError::InvalidArgument(
"Block has no managed property storage",
))
}
}
fn type_target(&self, store: &ObjectStore) -> Result<Option<ObjectRef>, VmError> {
let Value::Object(value) = store.cell_get(self.state)? else {
return Err(VmError::InvalidArgument("Block state is not an object"));
@@ -94,6 +111,7 @@ pub struct Data {
pub history_index: usize,
pub text_binding: Option<(ObjectRef, String)>,
pub click: Option<ObjectRef>,
pub properties: Option<ObjectRef>,
}
impl Data {
@@ -116,6 +134,7 @@ impl Data {
history_index: 0,
text_binding: None,
click: None,
properties: None,
}
}
pub fn is_container(&self) -> bool {
@@ -134,6 +153,9 @@ impl ObjectPayload for Data {
"tessera-block-data"
}
fn trace(&self, visit: &mut dyn FnMut(ObjectRef)) {
if let Some(properties) = self.properties {
visit(properties);
}
for child in &self.children {
visit(child.block);
}
@@ -149,11 +171,12 @@ impl ObjectPayload for Data {
}
}
pub fn allocate(cx: &mut NativeContext<'_>, data: Data) -> Result<ObjectRef, VmError> {
pub fn allocate(cx: &mut NativeContext<'_>, mut data: Data) -> Result<ObjectRef, VmError> {
let page = matches!(data.kind, Kind::Page);
for child in &data.children {
validate(cx.store(), child.block, None)?;
}
data.properties = Some(cx.new_object()?);
let data = cx.allocate(data)?;
let state = cx.new_cell(Some(Value::Object(data)))?;
cx.allocate(Block { state, page })
+80
View File
@@ -795,6 +795,86 @@ mod tests {
const EXAMPLE: &str = include_str!("../examples/hello.endor");
const PAGE: &str = include_str!("../examples/page.endor");
#[test]
fn source_native_subclasses_share_live_fields_and_release_replaced_storage() {
let (mut session, initial) = ReplSession::load(
include_str!("../examples/native-subclasses.endor"),
"app.main",
31,
1,
)
.unwrap();
initial.validate().unwrap();
assert_eq!(
session
.execute("isInstance(label, TextBlock)", "app.main")
.unwrap()
.value,
"true"
);
assert_eq!(
session
.execute("isInstance(page, Page)", "app.main")
.unwrap()
.value,
"true"
);
session.execute("alias = label", "app.main").unwrap();
let globals = session.candidate.globals.unwrap();
let Value::Object(label) = session
.candidate
.vm
.dict_get(globals, &Value::Text("label".into()))
.unwrap()
.unwrap()
else {
panic!("Block expected")
};
let path = session
.candidate
.vm
.object_store()
.attribute_path(label)
.unwrap();
let previous = session
.candidate
.vm
.downgrade(*path.last().unwrap())
.unwrap();
let updated = session
.execute(
r##"label = CustomStatus("replacement", 2, "#242422", "#237A45", "new field")"##,
"app.main",
)
.unwrap()
.document
.unwrap();
assert!(updated.frame.commands.iter().any(
|command| matches!(command, RenderCommand::Text { value, .. } if value == "new field")
));
session
.bridge
.reclaim(&mut session.candidate.vm, &mut session.candidate.roots)
.unwrap();
assert!(session.candidate.vm.upgrade(previous).unwrap().is_none());
assert_eq!(
session.execute("alias.message", "app.main").unwrap().value,
"\"new field\""
);
let updated = session
.execute("button.click()", "app.main")
.unwrap()
.document
.unwrap();
assert_eq!(updated.frame.commands.iter().filter(|command| matches!(command, RenderCommand::Text { value, .. } if value == "new field")).count(), 3);
let updated = session
.execute("alias.message = \"changed field\"", "app.main")
.unwrap()
.document
.unwrap();
assert!(updated.frame.commands.iter().any(|command| matches!(command, RenderCommand::Text { value, .. } if value == "changed field")));
}
#[test]
fn loaded_program_console_and_native_events_share_unique_source_ids() {
let (mut session, initial) = ReplSession::load(
+7 -4
View File
@@ -141,10 +141,13 @@ impl RenderCache {
let kind = match &data.kind {
Kind::Text { value, size, color } => {
let value = if let Some((source, field)) = &data.text_binding {
dependencies.push(Dependency {
object: *source,
property: Some(field.clone()),
});
let storage = store.attribute_path(*source)?;
for (index, object) in storage.iter().enumerate() {
dependencies.push(Dependency {
object: *object,
property: (index + 1 == storage.len()).then(|| field.clone()),
});
}
match store.get_attr(*source, field)? {
Value::Nil => "nil".into(),
Value::Bool(v) => v.to_string(),
+104 -11
View File
@@ -3,8 +3,8 @@ use std::sync::{Arc, Mutex};
use anyhow::{Result, bail};
use endor_core::{
ContextNativeFunction, EndorReal, NativeCallable, NativeContext, NativeResult, ObjectRef,
TypeConstructor, Value, Vm, VmError, WeakObjectRef,
ContextNativeFunction, EndorReal, EndorTypeObject, NativeCallable, NativeContext, NativeResult,
ObjectRef, TypeConstructor, Value, Vm, VmError, WeakObjectRef,
};
use crate::{
@@ -215,6 +215,7 @@ struct Function {
operation: Operation,
owner: Option<ObjectRef>,
session: Shared,
requested_type: Option<ObjectRef>,
}
/// One shared implementation on the nominal type. The VM binds receivers;
@@ -236,11 +237,55 @@ impl NativeCallable for TypeMethod {
operation: self.operation,
owner: Some(owner),
session: self.session.clone(),
requested_type: None,
}
.invoke(cx, &args[1..])
}
}
/// The Type dispatcher passes the requested subclass explicitly. Native
/// constructor options precede the subclass's inherited/own field arguments.
#[derive(Debug)]
struct NativeFactory {
operation: Operation,
session: Shared,
}
impl NativeCallable for NativeFactory {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let requested = object(args.first())?;
let fields = cx
.store()
.payload::<EndorTypeObject>(requested, "Type")?
.fields()
.to_vec();
let values = &args[1..];
let native_count = values
.len()
.checked_sub(fields.len())
.ok_or(invalid("missing subclass field arguments"))?;
let result = Function {
operation: self.operation,
owner: None,
session: self.session.clone(),
requested_type: Some(requested),
}
.invoke(cx, &values[..native_count])?;
let NativeResult::Return(Value::Object(instance)) = result else {
return Err(invalid("native constructor did not return an instance"));
};
if cx.store().type_of(instance)? != Some(requested) {
return Err(invalid(
"native constructor returned an incorrect nominal type",
));
}
for (field, value) in fields.iter().zip(&values[native_count..]) {
cx.set_attr(instance, &field.name, value.clone())?;
}
Ok(NativeResult::Return(Value::Object(instance)))
}
}
fn invalid(message: &'static str) -> VmError {
VmError::InvalidArgument(message)
}
@@ -305,6 +350,7 @@ fn bind(
operation,
owner: Some(owner),
session: session.clone(),
requested_type: None,
},
vec![owner, desktop],
))?;
@@ -316,6 +362,15 @@ fn new_block(
cx: &mut NativeContext<'_>,
data: Data,
session: &Shared,
) -> Result<ObjectRef, VmError> {
new_typed_block(cx, data, session, None)
}
fn new_typed_block(
cx: &mut NativeContext<'_>,
data: Data,
session: &Shared,
requested: Option<ObjectRef>,
) -> Result<ObjectRef, VmError> {
let type_name = match data.kind {
Kind::Text { .. } => "TextBlock",
@@ -327,8 +382,17 @@ fn new_block(
Kind::Page => "Page",
};
let page = matches!(data.kind, Kind::Page);
let desktop = session
.lock()
.map_err(|_| invalid("UI session poisoned"))?
.desktop;
let expected = desktop_type(cx.store(), type_name, desktop)?;
let type_object = requested.unwrap_or(expected);
if !cx.store().is_subtype(type_object, expected)? {
return Err(invalid("native constructor cannot allocate this subclass"));
}
let block = block::allocate(cx, data)?;
attach_named_type(cx, block, type_name, session)?;
cx.attach_type(block, type_object)?;
{
let mut state = session.lock().map_err(|_| invalid("UI session poisoned"))?;
if state.nodes.len() >= MAX_UI_NODES {
@@ -626,10 +690,11 @@ impl NativeCallable for Function {
{
return Err(invalid("text exceeds size limits"));
}
return Ok(NativeResult::Return(Value::Object(new_block(
return Ok(NativeResult::Return(Value::Object(new_typed_block(
cx,
data,
&self.session,
self.requested_type,
)?)));
}
if matches!(self.operation, OpenValue) {
@@ -1083,6 +1148,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
operation,
owner: None,
session: session.clone(),
requested_type: None,
},
vec![desktop],
))?;
@@ -1113,7 +1179,30 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
] {
let base = object(Some(&vm.get_attr(ui, base_name)?))?;
let constructor = match constructor_name {
Some(name) => TypeConstructor::Native(object(Some(&vm.get_attr(ui, name)?))?),
Some(constructor_name) => {
let operation = match constructor_name {
"text" => Operation::Text,
"rect" => Operation::Rect,
"spacer" => Operation::Spacer,
"row" => Operation::Row,
"column" => Operation::Column,
"button" => Operation::Button,
"page" => Operation::Page,
_ => return Err(invalid("unknown native type allocator").into()),
};
let factory = vm.allocate(ContextNativeFunction::new(
constructor_name,
NativeFactory {
operation,
session: session.clone(),
},
vec![desktop],
))?;
roots.push(factory);
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
vm.attach_type(factory, function_type)?;
TypeConstructor::NativeTyped(factory)
}
None => TypeConstructor::Abstract,
};
let definition = vm.new_type(name, base, constructor)?;
@@ -1208,15 +1297,19 @@ pub fn attach_desktop_type(
name: &str,
desktop: ObjectRef,
) -> Result<(), VmError> {
let types = object(Some(&cx.store().get_attr(desktop, "types")?))?;
let definition = object(
cx.store()
.dict_get(types, &Value::Text(name.into()))?
.as_ref(),
)?;
let definition = desktop_type(cx.store(), name, desktop)?;
cx.attach_type(instance, definition)
}
fn desktop_type(
store: &endor_core::ObjectStore,
name: &str,
desktop: ObjectRef,
) -> Result<ObjectRef, VmError> {
let types = object(Some(&store.get_attr(desktop, "types")?))?;
object(store.dict_get(types, &Value::Text(name.into()))?.as_ref())
}
pub fn snapshot(vm: &Vm, value: &Value) -> Result<Arc<UiNode>> {
let Value::Object(root) = value else {
bail!("main must return a Block");