From 8b698cb39f471b86c7344c4972bdf37692dbc42b Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 22 Oct 2026 14:37:43 +0800 Subject: [PATCH] Register typed GUI capabilities and reject incompatible presenters early --- README.md | 4 ++-- src/README.md | 2 +- src/api.rs | 4 ++-- src/endor_host.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++++ src/protocols.rs | 55 ++++++++++++++++++++++++++++++++++++----------- vendor/aster | 2 +- 6 files changed, 102 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index bdbb05c..2f3997b 100644 --- a/README.md +++ b/README.md @@ -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 with declared-field type checks; methods also validate their geometry when used. Whole-program static typing 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/insert/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. Source and native positional intervals are checked against the canonical call count, including self; native methods without metadata cannot declare a capability; source argument/return annotations are checked at invocation as described below. Native parameter/return type metadata, effect types and formal trait syntax remain 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/insert/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. Source and native positional intervals are checked against the canonical call count, including self; native methods without metadata cannot declare a capability; source argument/return annotations are checked at invocation as described below. Typed requirements also compare parameter/return types and known native effects. Runtime calls check actual results across delegation. Static source effect inference 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. @@ -424,7 +424,7 @@ Native methods publish positional argument intervals through Aster CallArity. Th Native typed contracts now cover measure(Block, Mount, Constraints): MeasureResult, arrange(Block, Mount, Bounds): Arrangement, paint(Block, Mount, Bounds): DisplayList and hitTest(Block, Mount, Point): Bool, plus Point geometry queries and Window, Block/Container/Page, Mount, Task, Event, Subscription and ObjectList.at methods. The explicit receiver is checked before binding dispatch. Aster checks types before invoking the implementation and checks actual returns, including final results delegated to Endor functions. Signature definitions are traced managed edges; pending delegated return checks retain execution roots and use the existing VM frame/budget machinery. Wrong returns release temporary results but do not roll back earlier writes. -Host CallEffect distinguishes ReadOnly, Mutating and External. A declared mutating/external call is rejected before invocation during read-only rendering; declaring ReadOnly does not bypass the existing heap write barrier. Legacy missing metadata remains unknown, and trusted native code still must obey its I/O contract. CallType supports single types and flat nonempty unions, retaining every branch definition. Page.open accepts Window or nil, Page.window returns Window or nil, and Block.on accepts Bool or String for its optional phase. Mount parent/child/sibling/Page queries have nullable results; bounds() returns an actual Bounds object so Point.inside(mount.bounds()) composes directly. Scope/resource eligibility, numeric ranges and phase names keep their domain checks. This adds native contract metadata, not Endor union syntax. Constructors and other management APIs are not yet fully covered. Source overrides now check contravariant parameters and covariant returns at class construction, method replacement and before invocation with dynamically resolved annotations. Ancestor replacement checks overriding descendants before mutation. Forward names may defer until invocation, where unresolved or incompatible contracts fail before the body. Known native effects may only shrink; source effects remain unknown and read-only execution retains its barriers. Trait type/effect compatibility and static effect inference remain pending. See [method-contracts.endor](examples/method-contracts.endor) for real Endor widening parameters to Object and returning a MeasureResult subclass. Existing [visual-protocols.endor](examples/visual-protocols.endor) and [layout-negotiation.endor](examples/layout-negotiation.endor) exercise the typed visual methods with actual Endor code. +Host CallEffect distinguishes ReadOnly, Mutating and External. A declared mutating/external call is rejected before invocation during read-only rendering; declaring ReadOnly does not bypass the existing heap write barrier. Legacy missing metadata remains unknown, and trusted native code still must obey its I/O contract. CallType supports single types and flat nonempty unions, retaining every branch definition. Page.open accepts Window or nil, Page.window returns Window or nil, and Block.on accepts Bool or String for its optional phase. Mount parent/child/sibling/Page queries have nullable results; bounds() returns an actual Bounds object so Point.inside(mount.bounds()) composes directly. Scope/resource eligibility, numeric ranges and phase names keep their domain checks. This adds native contract metadata, not Endor union syntax. Constructors and other management APIs are not yet fully covered. Source overrides now check contravariant parameters and covariant returns at class construction, method replacement and before invocation with dynamically resolved annotations. Ancestor replacement checks overriding descendants before mutation. Forward names may defer until invocation, where unresolved or incompatible contracts fail before the body. Known native effects may only shrink; source effects remain unknown and read-only execution retains its barriers. Visual, EventTarget, Children and Presentable now use typed Trait requirements. Registration checks parameter/return substitution and known native effects before recording the declaration, including existing descendants. Runtime calls recheck dynamic annotations and final Trait results, including delegated source/native returns. Concrete implementations retain wider parameters and optional convenience forms. Source effects remain unknown; static effect inference remains pending. See [method-contracts.endor](examples/method-contracts.endor) for real Endor widening parameters to Object and returning a MeasureResult subclass. Existing [visual-protocols.endor](examples/visual-protocols.endor) and [layout-negotiation.endor](examples/layout-negotiation.endor) exercise the typed visual methods with actual Endor code. Event listeners and onClick callbacks must be Functions with known metadata accepting zero arguments or one Event. If both forms work, the dispatcher passes Event. Binding computes and Task callbacks must accept zero arguments, checked before replacing a binding, adding a connection or scheduling work. Native and source callbacks follow the same rule. See [native-signatures.endor](examples/native-signatures.endor) for real native one-argument and zero-argument handlers. Event and ObjectList subclass allocators also check declared field suffixes before allocation. diff --git a/src/README.md b/src/README.md index dac71b9..5c1e58a 100644 --- a/src/README.md +++ b/src/README.md @@ -14,7 +14,7 @@ | mount.rs | Typed per-occurrence methods and nominal Bounds results, managed contexts, weak reverse links, ordered mount/unmount hooks, geometry and focus queries | | events.rs | Bounded native input transport with kind-specific tab-drop/desktop-position metadata to the owning VM | | event_dispatch.rs | Typed managed Event/Subscription methods, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver | -| protocols.rs | Register explicit Visual/EventTarget/Children (including insert)/Presentable managed traits and native type declarations | +| protocols.rs | Register typed Visual/EventTarget/Children (including insert)/Presentable managed trait requirements, using canonical signatures and explicit native type declarations | | presentation.rs | Per-window layout, Mount/focus/tab state and read dependencies; VM changes fan out before any view consumes work | | tasks.rs | Typed Task/ui.after methods, managed owner scopes and callbacks, weak timer index, request-key replacement, lifecycle cancellation and budgeted worker delivery | | tabs.rs | Immutable tab chrome, shared draw/hit geometry, overflow navigation, drag gaps/anchors/insertion markers and opaque published Page identities | diff --git a/src/api.rs b/src/api.rs index 8b6213e..51ffe26 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1103,9 +1103,9 @@ Declared fields are checked at construction and set_attr writes through the same Native methods now publish positional CallArity intervals, checked by the VM before invocation. Source defaults and bound receivers participate in the same query. Traits validate acceptance of their canonical count including self and reject native methods without metadata. Event listeners/onClick require Function metadata accepting zero arguments or one Event, preferring Event if both work. Binding computes and Task callbacks require zero-argument acceptance before registration/replacement. Generic Type constructor reflection and complete native signature coverage remain separate gaps. See examples/native-signatures.endor. -Native CallSignature checks resolved parameter/return types for visual measure/arrange/paint/hitTest, Point queries, Window/Block/Container/Page/Mount/Task/Event/Subscription methods and ObjectList.at. Signature definitions are traced managed edges. Parameters fail before dispatch; final results delegated to source/native functions must satisfy all pending native return contracts, with rooted definitions and the same frame/instruction budgets. Wrong returns release scoped results but do not undo earlier writes. CallEffect ReadOnly allows result allocation; Mutating/External calls are rejected before invocation during read-only execution. Existing heap barriers still apply, and this does not sandbox trusted native I/O. CallType unions preserve every branch definition. Page.open accepts Window or nil; page.window returns Window or nil; Block.on accepts Bool or String for its optional phase, while phase names retain domain validation. Mount relation queries are nullable, and bounds() is a real Bounds object usable by Point.inside. Native union metadata does not add Endor union syntax. Source method overrides now enforce parameter contravariance, return covariance and accepted-count preservation at class creation/method replacement, with call-time rechecks for dynamic annotation names. Ancestor replacement checks overriding descendants atomically. Unknown forward names may defer until invocation; known incompatibilities reject before effects. Native effects may only shrink; source effects remain unknown and runtime read-only barriers still apply. See examples/method-contracts.endor. Constructors/other API coverage, trait type/effect requirements and static effect inference remain pending. Unknown legacy metadata remains unknown. See examples/visual-protocols.endor and examples/layout-negotiation.endor. +Native CallSignature checks resolved parameter/return types for visual measure/arrange/paint/hitTest, Point queries, Window/Block/Container/Page/Mount/Task/Event/Subscription methods and ObjectList.at. Signature definitions are traced managed edges. Parameters fail before dispatch; final results delegated to source/native functions must satisfy all pending native return contracts, with rooted definitions and the same frame/instruction budgets. Wrong returns release scoped results but do not undo earlier writes. CallEffect ReadOnly allows result allocation; Mutating/External calls are rejected before invocation during read-only execution. Existing heap barriers still apply, and this does not sandbox trusted native I/O. CallType unions preserve every branch definition. Page.open accepts Window or nil; page.window returns Window or nil; Block.on accepts Bool or String for its optional phase, while phase names retain domain validation. Mount relation queries are nullable, and bounds() is a real Bounds object usable by Point.inside. Native union metadata does not add Endor union syntax. Source method overrides now enforce parameter contravariance, return covariance and accepted-count preservation at class creation/method replacement, with call-time rechecks for dynamic annotation names. Ancestor replacement checks overriding descendants atomically. Unknown forward names may defer until invocation; known incompatibilities reject before effects. Native effects may only shrink; source effects remain unknown and runtime read-only barriers still apply. See examples/method-contracts.endor. Constructors/other API coverage and static source effect inference remain pending. Unknown legacy metadata remains unknown. See examples/visual-protocols.endor and examples/layout-negotiation.endor. -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. Source/native positional intervals are checked, and missing native arity metadata prevents a capability declaration; source parameter/return annotations are checked at invocation. Trait type/effect compatibility and formal trait syntax remain pending. EventTarget requires canonical on/dispatch/onEvent arities 3/2/1 after self; native optional convenience forms remain. +Trait definitions Visual, EventTarget, Children and Presentable are managed nominal capabilities. ui.implement(type,capability) explicitly declares an implementation after required-method/positional-arity/type/known-native-effect 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. Source/native positional intervals are checked, and missing native arity metadata prevents a capability declaration; source parameter/return annotations are checked at invocation. These capabilities use typed signatures: registration checks parameter contravariance, return covariance and known native effects. Actual calls recheck dynamic names and final results across delegation, with rooted return definitions. Explicit typed method annotations remain checked even if a different host disables global source checks; concrete implementations keep wider inputs and optional convenience forms. Source static effects 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. diff --git a/src/endor_host.rs b/src/endor_host.rs index a1c5f3a..b1e6a17 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -3837,6 +3837,60 @@ page.render(block) ); } + #[test] + fn presentable_type_contracts_reject_before_registration_or_body_effects() { + let mut session = ReplSession::new(232).unwrap(); + session.execute("marker = ui.state(0)", "app.main").unwrap(); + for (name, method) in [ + ( + "WrongParameter", + "function present(self: WrongParameter, window: Point): Block { marker.increment() return TextBlock(\"bad\") }", + ), + ( + "WrongResult", + "function present(self: WrongResult, window: Window): Number { marker.increment() return 7 }", + ), + ] { + let input = format!("class {name} {{ {method} }} ui.implement({name}, Presentable)"); + let error = session + .execute(&input, "app.main") + .err() + .expect("incompatible typed capability"); + assert!( + error + .to_string() + .contains("trait Presentable method present"), + "{error:#}" + ); + assert_eq!( + session + .execute(&format!("ui.implements({name}, Presentable)"), "app.main") + .unwrap() + .value, + "false" + ); + assert_eq!( + session.execute("marker.value", "app.main").unwrap().value, + "0" + ); + } + session.execute(r#" + class Good { + function present(self: Good, window: Object): TextBlock { return TextBlock("typed") } + } + ui.implement(Good, Presentable) + view = ui.present(Good()) + "#, "app.main").unwrap(); + assert_eq!( + session + .execute("ui.isInstance(view, TextBlock)", "app.main") + .unwrap() + .value, + "true" + ); + assert!(!session.is_faulted()); + } + #[test] fn presentable_dispatch_preserves_source_identity_and_reactive_display() { let (mut session, initial) = ReplSession::load( diff --git a/src/protocols.rs b/src/protocols.rs index a8361a8..27d85ee 100644 --- a/src/protocols.rs +++ b/src/protocols.rs @@ -1,5 +1,8 @@ //! Host capability definitions over Aster's explicit managed trait relations. -use endor_core::{MethodRequirement, ObjectRef, Value, Vm, VmError}; +use endor_core::{ + AnnotationType, CallArity, CallEffect, CallSignature, ObjectRef, TypedMethodRequirement, Value, + Vm, VmError, +}; pub fn install( vm: &mut Vm, @@ -38,22 +41,48 @@ pub fn install( ), ("Presentable", vec![("present", 1)], None), ] { - let requirements = methods - .into_iter() - .map(|(name, parameters)| MethodRequirement { - name: name.into(), - parameters, - }) - .collect(); - let capability = vm.new_trait(name, requirements)?; + let owner_definition = if let Some(owner) = owner { + let Value::Object(definition) = vm.get_attr(ui, owner)? else { + return Err(VmError::InvalidArgument("missing protocol owner")); + }; + Some(definition) + } else { + None + }; + let mut requirements = Vec::new(); + for (method, parameters) in methods { + let mut signature = if let Some(owner) = owner_definition { + let function = vm + .object_store() + .lookup_method(owner, method)? + .ok_or(VmError::InvalidArgument("missing protocol method"))?; + vm.object_store() + .native_signature(function)? + .ok_or(VmError::InvalidArgument( + "protocol method lacks native types", + ))? + } else { + let window = crate::ui_bridge::desktop_type(vm.object_store(), "Window", desktop)?; + let block = crate::ui_bridge::desktop_type(vm.object_store(), "Block", desktop)?; + CallSignature::exact( + vec![AnnotationType::Any, AnnotationType::Nominal(window)], + AnnotationType::Nominal(block), + CallEffect::External, + ) + }; + signature.arity = CallArity::exact(parameters + 1); + signature.parameters[0] = AnnotationType::Any.into(); + requirements.push(TypedMethodRequirement { + name: method.into(), + signature, + }); + } + let capability = vm.new_typed_trait(name, requirements)?; roots.push(capability); vm.attach_type(capability, trait_type)?; vm.set_attr(ui, name, Value::Object(capability))?; vm.dict_set(types, Value::Text(name.into()), Value::Object(capability))?; - if let Some(owner) = owner { - let Value::Object(owner) = vm.get_attr(ui, owner)? else { - return Err(VmError::InvalidArgument("missing protocol owner")); - }; + if let Some(owner) = owner_definition { vm.implement_trait(owner, capability)?; } } diff --git a/vendor/aster b/vendor/aster index e26e227..100bf63 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit e26e227dd0a3dcbd1aaf61765ebdcd4d61ce05e5 +Subproject commit 100bf637f944d1031b10f4fa7c7784a72fb93004