Enable source function type checks in the shared GUI runtime
Verify Tessera GUI / verify (push) Failing after 7m34s

This commit is contained in:
2026-10-21 22:40:11 +08:00
parent 6e69c5e5ce
commit 3a7b755532
7 changed files with 149 additions and 6 deletions
+26 -1
View File
@@ -196,7 +196,7 @@ Native visual methods are now available on Block: `measure(mount, Constraints(mi
Outside a renderer layout call, native measurement queries find intrinsic native subtree size and clamp it to the given constraints. During layout, native base methods use the staged measured children of that occurrence. Native Row/Column arrangement uses child sizes, padding and gaps; it does not stretch children to fill the supplied bounds. Hit testing uses local coordinates against the current Mount dimensions. Coordinates/dimensions must be finite and remain within the native layout limit. Width/height and constraint ranges cannot be negative or inverted. The value constructors preserve fields as ordinary objects; methods validate their contents when used, and global annotation type checking remains pending.
Visual, EventTarget, Children and Presentable are explicit managed Trait definitions. Block declares Visual (measure/arrange/paint/hitTest) and EventTarget (on/dispatch/onEvent); ContainerBlock declares Children (append/remove/replace/move/children), inherited by Page. `ui.supports(value, capability)` queries an instance; `ui.implements(type, capability)` queries a type. `ui.implement(type, capability)` checks required methods and establishes an explicit relation. Matching member names alone never declare a capability. Aster checks source positional parameter counts, including self, when registering, creating subclasses or replacing methods; declaration and ancestor updates also validate existing affected descendants. Native callable signatures remain trusted host declarations; argument/return annotations, effect types and formal trait syntax are still pending.
Visual, EventTarget, Children and Presentable are explicit managed Trait definitions. Block declares Visual (measure/arrange/paint/hitTest) and EventTarget (on/dispatch/onEvent); ContainerBlock declares Children (append/remove/replace/move/children), inherited by Page. `ui.supports(value, capability)` queries an instance; `ui.implements(type, capability)` queries a type. `ui.implement(type, capability)` checks required methods and establishes an explicit relation. Matching member names alone never declare a capability. Aster checks source positional parameter counts, including self, when registering, creating subclasses or replacing methods; declaration and ancestor updates also validate existing affected descendants. Native callable signatures remain trusted host declarations; source argument/return annotations are checked at invocation as described below. Native signature metadata, effect types and formal trait syntax remain pending.
A plain source object can declare Presentable by implementing `present(self, window: Window): Block` and calling `ui.implement(MyType, Presentable)`. `ui.present(value)` invokes this method with the calling window and checks the returned actual Block; `ui.open(value)` also opens the result in a Page. Block values pass through directly. The existing summary viewer remains the fallback for unregistered values, and merely viewing a function does not execute it. Presentation runs through the same bounded VM call sequence; there is no recursive host evaluator. A source adapter can keep the original object through fields/callbacks/bindings; [presentable.endor](examples/presentable.endor) shows a source-preserving view and GUI calls to the original object's method. Presentation methods are ordinary calls; visual measure/arrange/paint/hitTest still run read-only and check their nominal results at runtime. Source implementations of EventTarget.on/dispatch must provide the contract's canonical 3/2 arguments after self; native methods retain their existing optional convenience arguments.
@@ -372,3 +372,28 @@ explicitly validates the pinned engine itself. CI uses official Cargo sources
and standard HTTPS checkout without custom SSH secrets. Font checks cover
proportional/monospace advances, fractional scaling, multiline height, Chinese
fallback, grapheme-safe truncation, antialiasing and alpha blending.
### Source function types
Tessera enables Aster runtime checks for source parameter and return annotations.
`Object` accepts any live value, `Unit` accepts nil, `Number`, `String`/`Text` and
`Bool` check their value kinds. `Function` accepts source/native functions and
bound methods; callable class definitions remain `Type`. Newly created functions
share the actual managed Function type, so `isInstance(callback, Function)` works.
`View` is retained as a global compatibility alias for Block.
Other annotation names resolve through the function's own globals and captured
builtins on each invocation. A real Type requires nominal inheritance; a Trait
requires an explicit implementation. A method's own declaring-class annotation
uses its receiver's actual owning definition, allowing saved bound methods on old
instances to survive a REPL class-name redefinition. Other global type names are
not frozen when a function is defined. TypeMismatch reports the function,
parameter/return and expected/actual names. Unknown annotations and argument
mismatches reject before the body; a bad return does not roll back completed writes.
The per-call return definition remains rooted until success/error cleanup.
See [function-types.endor](examples/function-types.endor) for actual Endor source.
This adds no static inference, field-write checks, override variance, generics,
effect typing or common native-signature metadata. Native APIs continue to validate
their arguments and results at their own boundaries.
+20
View File
@@ -0,0 +1,20 @@
function identity(value: Number): Number { return value }
function callNumber(callback: Function): Number { return callback() }
function visual(value: Visual): Block { return value }
class Actions {
state: Object
function read(self: Actions): Number { return self.state.value }
function click(self: Actions, event: Event): Unit { self.state.increment() }
}
state = ui.state(0)
actions = Actions(state)
savedFunction = actions.read
initial = identity(callNumber(savedFunction))
button = Button("调用带类型检查的对象方法")
connection = button.on("click",actions.click)
root = visual(Column(24,16,TextBlock("源码、原生与绑定方法统一为 Function"),ui.textOf(state,"value"),button))
page = Page()
page.title = "函数类型检查"
page.render(root)
// identity("wrong") 会在进入函数体前报类型错误。
// callNumber(RectBlock) 会拒绝把类型构造器作为 Function。
+2 -2
View File
@@ -7,7 +7,7 @@
| 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 | Inheritable native nominal constructors with source fields, shared type method tables and bound receiver dispatch, tab registry, Page lifecycle/navigation and immutable frame extraction |
| ui_bridge.rs | Inheritable native nominal constructors with source fields, shared type method tables and bound receiver dispatch, configured unified Function classification and source annotation checks, tab registry, Page lifecycle/navigation and immutable frame extraction |
| binding.rs | Target-owned managed property bindings, weak Subscription tokens, read-only compute and borrowed dependency/output caches |
| 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 and visual-method identity dependencies across shared field-storage paths, reverse parent links and cached immutable visual derivation |
@@ -57,7 +57,7 @@ contain only immutable native data.
Tests in api.rs execute real HTTP CRUD, persistent Console/reset/PUT isolation and a controlled queued-PUT/DELETE race
without opening a window. Tests in endor_host.rs cover lifecycle, direct script and
module entry, page methods, multiline inputs, original source ranges, malformed input,
entry checks, budgets, failure preservation, live object identity, explicit rendering,
entry checks, source function annotation/function identity and REPL class redefinition, budgets, failure preservation, live object identity, explicit rendering,
compile-before-execute behavior and stale-result invalidation. They
run only in remote CI. Font tests in text.rs and software_renderer.rs cover real
advances, multiline height, fractional scaling, CJK fallback, grapheme-safe fitting,
+4 -2
View File
@@ -1041,7 +1041,7 @@ expose actual type relations. Types, bases, instances and native constructors li
in the same GC graph. Ordinary source classes support `class Child: Base`, typed field
declarations, explicit first `self` parameters, positional field construction and
member assignment. Inherited methods bind the actual receiver; overridden methods
are dynamically selected through self. Concrete native visual subclasses reuse real native allocators; abstract bases remain unconstructible. Traits and annotation checking remain pending. Native Block/Page methods use the same type method tables and binding path.
are dynamically selected through self. Concrete native visual subclasses reuse real native allocators; abstract bases remain unconstructible. Explicit traits and source parameter/return annotation checks are enabled; field-write constraints and static/effect typing remain pending. Native Block/Page methods use the same type method tables and binding path.
Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), setTitle(text) and focus(). Requests project to their actual native window only after successful input/candidate completion and carry the current runtime session. Resize is asynchronous and the reported viewport is authoritative; this host accepts 1..4096 logical dimensions with a native 720x480 minimum. Failed input/candidates discard pending requests and read-only rendering rejects window effects. Open Pages appear in native tab chrome, with page.title, click activation/close, Ctrl+Tab cycling and Cmd/Ctrl+W close when page keyboard focus is active. Overflow arrows reach additional pages. These operations call actual Page methods in the same VM; tab IDs are weak runtime projections and add no GC roots. The 36-logical-pixel bar reduces Page constraint height; window/ui viewport reports the full inner size and native pointer positions are translated into content coordinates. Window() now creates additional native windows in the same VM, up to 16 open resources. Page.open(window)/moveToWindow(window) preserve Page and business identity while replacing Mounts; detachToWindow() creates and returns a new Window. Dragging a tab away from its strip invokes the same method. Window.close()/secondary OS close remove Page roots, unmount, and retire the resource context; retained Pages can reopen in another live window, and closed Window resources reject viewport/resize/title/focus operations. Closing the primary OS shell exits the application. Secondary viewport inputs and frame publication use the same worker. Secondary close after callback/rendering failure uses host-only teardown without invoking source callbacks or resuming execution. After reset/discard, closing an old picture never touches a fresh VM resource with the same number; viewport inputs are also generation-scoped. A teardown failure discards the affected VM and disables remaining pictures. Native initialization/surface errors are reported rather than panicking; failed secondary creation leaves a managed resource closable from Console. Existing-window drag/drop, release-point placement and full application-exit notifications remain pending.
@@ -1053,7 +1053,9 @@ ScrollBlock(width,height,child) is a ContainerBlock with managed viewport dimens
Native wheel POST /events uses kind scroll with the normal window/session/layout_version, a scrollable mount ID, point=[x,y], delta=[dx,dy], and no press_point. Deltas are signed finite logical pixels within +/-1000000; positive moves toward the end of content. Other kinds must omit delta. Native Shift+wheel maps to horizontal. The host checks the active committed frame, target attachment and clipped viewport before invoking Mount.scrollBy. These fields are transport metadata; source code uses the Endor methods above.
Trait definitions Visual, EventTarget, Children and Presentable are managed nominal capabilities. ui.implement(type,capability) explicitly declares an implementation after required-method/positional-arity checks; ui.implements(type,capability) and ui.supports(value,capability) query it. Block declares Visual/EventTarget; ContainerBlock declares Children, inherited by Page. Same-name methods alone never declare an implementation. Source subclass construction and host method replacement validate inherited/affected descendant contracts. Native callable signatures are trusted; full parameter/return annotation and effect checks and formal trait syntax remain pending. EventTarget requires canonical on/dispatch/onEvent arities 3/2/1 after self; native optional convenience forms remain.
Source function parameter annotations are checked before the body and return annotations before returning. Object accepts any live value; Unit accepts nil; Number, String/Text and Bool match scalar kinds. Function includes source/native functions and bound methods, while callable class definitions remain Type. View is a compatibility alias for Block. Other names resolve actual Type/Trait objects in the function's globals then captured builtins at each call. The method's own class uses the receiver's actual owning definition, preserving old bound methods after REPL redefinition. Other type names are not frozen at definition. UnknownAnnotation and TypeMismatch report failures; bad returns do not roll back earlier writes. No static inference, field-write validation, override variance, generic or effect typing is provided.
Trait definitions Visual, EventTarget, Children and Presentable are managed nominal capabilities. ui.implement(type,capability) explicitly declares an implementation after required-method/positional-arity checks; ui.implements(type,capability) and ui.supports(value,capability) query it. Block declares Visual/EventTarget; ContainerBlock declares Children, inherited by Page. Same-name methods alone never declare an implementation. Source subclass construction and host method replacement validate inherited/affected descendant contracts. Native callable signatures are trusted; source parameter/return annotations are checked at invocation. Native signature metadata, field-write and effect checks and formal trait syntax remain pending. EventTarget requires canonical on/dispatch/onEvent arities 3/2/1 after self; native optional convenience forms remain.
For a plain object explicitly implementing Presentable, present(self, window: Window): Block is invoked by ui.present(value) or ui.open(value), using the current managed Window and the same VM budget. The result must be an actual Block. Blocks pass through directly; unregistered values retain the summary fallback. Source views retain their business object via managed fields/callbacks/bindings, as in examples/presentable.endor. Viewing function definitions does not itself execute them. Rendering methods still run read-only with nominal result checks.
+88
View File
@@ -955,6 +955,94 @@ mod tests {
const EXAMPLE: &str = include_str!("../examples/hello.endor");
const PAGE: &str = include_str!("../examples/page.endor");
#[test]
fn source_annotations_classify_functions_and_reject_before_body() {
let (mut session, _) = ReplSession::load(
include_str!("../examples/function-types.endor"),
"app.main",
1,
180,
)
.unwrap();
for expression in [
"isInstance(identity,Function)",
"isInstance(ui.rect,Function)",
"isInstance(actions.read,Function)",
] {
assert_eq!(
session.execute(expression, "app.main").unwrap().value,
"true"
);
}
assert_eq!(
session
.execute("isInstance(RectBlock,Function)", "app.main")
.unwrap()
.value,
"false"
);
session
.execute(
"function checked(value: Number): Number { state.increment() return value }",
"app.main",
)
.unwrap();
let error = session
.execute("checked(\"wrong\")", "app.main")
.err()
.unwrap();
assert!(
error.to_string().contains("parameter value expects Number"),
"{error:#}"
);
assert_eq!(
session.execute("state.value", "app.main").unwrap().value,
"0"
);
assert_eq!(
session.execute("checked(7)", "app.main").unwrap().value,
"7"
);
session
.execute("function wrong(): Number { return \"wrong\" }", "app.main")
.unwrap();
let error = session.execute("wrong()", "app.main").err().unwrap();
assert!(
error.to_string().contains("return expects Number"),
"{error:#}"
);
assert!(
session
.execute("callNumber(RectBlock)", "app.main")
.is_err()
);
session
.execute(
"class Actions { function read(self: Actions): Number { return 9 } }",
"app.main",
)
.unwrap();
assert_eq!(
session
.execute("callNumber(savedFunction)", "app.main")
.unwrap()
.value,
"1"
);
assert_eq!(
session
.execute("isInstance(actions,Actions)", "app.main")
.unwrap()
.value,
"false"
);
session.execute("button.click()", "app.main").unwrap();
assert_eq!(
session.execute("state.value", "app.main").unwrap().value,
"2"
);
}
#[test]
fn stopped_window_teardown_detaches_mounts_without_running_source_hooks() {
let source = r#"class WatchedPage: Page {
+8
View File
@@ -1588,6 +1588,12 @@ impl UiBridge {
pub fn install_globals(&self, vm: &mut Vm, globals: ObjectRef) -> Result<()> {
vm.dict_set(globals, Value::Text("ui".into()), Value::Object(self.ui))?;
// Compatibility spelling used by the original module examples.
vm.dict_set(
globals,
Value::Text("View".into()),
vm.get_attr(self.ui, "Block")?,
)?;
for name in TYPE_NAMES.iter().chain(QUERY_NAMES) {
let value = vm.get_attr(self.ui, name)?;
vm.dict_set(globals, Value::Text((*name).into()), value)?;
@@ -2370,6 +2376,8 @@ pub fn install(vm: &mut Vm, roots: &mut Vec<ObjectRef>) -> Result<UiBridge> {
vm.attach_type(desktop, root_types.object)?;
vm.attach_type(ui, root_types.object)?;
let function_type = object(Some(&vm.get_attr(ui, "Function")?))?;
vm.set_function_type(function_type)?;
vm.set_source_type_checks(true)?;
for name in [
"open",
"text",
+1 -1