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
+4 -2
View File
@@ -166,7 +166,7 @@ candidate and returns 500, retaining the previous document.
This stage supports live mounted UI for both complete programs and Console inputs, with immutable window frames on the existing worker.
Native mouse/keyboard activation and code-driven callbacks share onClick/click. Managed Mount objects expose each occurrence, and property dependencies and measurement caches avoid recomputing clean visual subtrees. Arrangement still traverses occurrences.
Tab chrome/multiple windows, native class allocation inheritance and trait definitions, window-size language inputs and process isolation are still being implemented. Worker threads,
Tab chrome/multiple windows, trait definitions and custom visual measurement/painting, window-size language inputs and process isolation are still being implemented. Worker threads,
source budgets and VM instruction limits are not a complete untrusted-code sandbox.
## Developer tools
@@ -176,7 +176,9 @@ container append/remove/replace/move, Page open/close/navigation, ui.present,
ui.state(value), ui.textOf(state, "value"), and button.onClick/click are available
in the persistent Console. Method bodies can call other methods without a trailing
return. Bound text tracks its source property; clean derived subtrees and unchanged measurements are reused. Buttons have a native background, focus ring and pointer/keyboard activation.
`Page()`, `TextBlock(...)`, `Row(...)`, `Column(...)` and `Button(...)` are callable managed type objects; `Page.base` is ContainerBlock and `page.type` is Page. `isInstance(page, Block)` and `isSubtype(Page, Block)` query nominal relations. Object and Type are explicitly bootstrapped in the same GC heap. Ordinary source class declarations, positional field construction, member assignment and inherited method dispatch are supported; native allocator subclasses and traits are still pending. Native visual methods now live on their nominal type tables and use the same receiver binding as source methods. See [managed-types.endor](examples/managed-types.endor) and [classes.endor](examples/classes.endor).
`Page()`, `TextBlock(...)`, `Row(...)`, `Column(...)` and `Button(...)` are callable managed type objects; `Page.base` is ContainerBlock and `page.type` is Page. `isInstance(page, Block)` and `isSubtype(Page, Block)` query nominal relations. Object and Type are explicitly bootstrapped in the same GC heap. Ordinary source class declarations, positional field construction, member assignment and inherited method dispatch are supported; source subclasses of concrete native visual types now reuse their real native allocator; abstract types remain unconstructible. Traits are still pending. Native visual methods now live on their nominal type tables and use the same receiver binding as source methods. See [managed-types.endor](examples/managed-types.endor), [classes.endor](examples/classes.endor) and [native-subclasses.endor](examples/native-subclasses.endor).
Source native subclass construction takes native arguments first, followed by all inherited and own declared fields. For example, a TextBlock subclass with one field accepts `CustomText("text", 2, "#242422", fieldValue)`; optional native arguments can be omitted before the required field suffix. Field storage belongs to the current shared Block content: replacement updates aliases and bindings and releases the previous fields through Aster. This is an implementation subset; field annotations are not yet runtime checked.
Toggle developer tools with Command-Option-I or F12 on macOS, Control-Shift-I or
F12 on Windows/Linux. The compact Console, Sources, Network and Settings tabs
+1
View File
@@ -2,6 +2,7 @@
| File | Purpose |
| --- | --- |
| [native-subclasses.endor](native-subclasses.endor) | Real native TextBlock/Button/Page source subclasses, inherited fields, method overrides and shared field bindings. |
| [classes.endor](classes.endor) | Endor class fields, inheritance, overriding, a retained receiver and Event arguments; native keyboard input updates shared model properties. |
| [managed-types.endor](managed-types.endor) | Callable managed Endor types, one shared counter, two bound displays and a language callback invoked from native Button input. |
| [page.endor](page.endor) | Four top-level statements construct text, a rectangle and a page, then call page.render; no main wrapper. |
+35
View File
@@ -0,0 +1,35 @@
class StatusText: TextBlock {
activeColor: String
function activate(self: StatusText, event: Event): Unit {
self.setText("继承的原生文本已更新")
self.setColor(self.activeColor)
}
}
class CustomStatus: StatusText {
message: String
function activate(self: CustomStatus, event: Event): Unit {
TextBlock.setText(self, self.message)
self.setColor(self.activeColor)
}
}
class ActionButton: Button {
target: Block
function activate(self: ActionButton, event: Event): Unit {
self.target.activate(event)
}
}
class CustomPage: Page {
caption: String
}
label = CustomStatus("点击按钮更新同一个自定义文本对象", 2, "#242422", "#237A45", "源码子类与原生载荷共同工作")
button = ActionButton("调用源码子类方法", label)
button.onClick(button.activate)
page = CustomPage("Endor 原生类型的源码继承")
page.render(Column(24, 16, TextBlock(page.caption, 2), label, label, button, ui.textOf(label, "message")))
+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");
+1 -1