From 543c909d538e65666ce6447b43c23e9a9307a5c7 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 22 Oct 2026 13:52:01 +0800 Subject: [PATCH] Publish native visual and window type and effect contracts --- README.md | 9 ++++-- src/README.md | 6 ++-- src/api.rs | 6 ++-- src/endor_host.rs | 52 +++++++++++++++++++++++++++++++ src/native_visual.rs | 57 +++++++++++++++++++++++++++++----- src/ui_bridge.rs | 74 ++++++++++++++++++++++++++++++++++++++++++-- src/window.rs | 31 ++++++++++++++++++- vendor/aster | 2 +- 8 files changed, 217 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 8ef4e28..e4cb9e0 100644 --- a/README.md +++ b/README.md @@ -417,11 +417,14 @@ The per-call return definition remains rooted until success/error cleanup. See [function-types.endor](examples/function-types.endor) for actual Endor source. Declared-field construction/write checks are described above. Static inference, override variance, generics, -effect typing and native parameter/return type metadata remain pending. Native APIs continue to validate -their arguments and results at their own boundaries. +static effect typing and complete native signature coverage remain pending. Native APIs retain their domain-specific value and resource checks. -Native methods publish positional argument intervals through Aster CallArity. The VM checks counts before invoking them, and trait registration/descendant updates verify that each source or native method accepts the canonical argument count. Optional/default parameters are included; bound receiver counts are removed for callback queries. Generic Type construction still uses its host constructor rules. This does not provide native parameter/return type annotations or effect typing. +Native methods publish positional argument intervals through Aster CallArity. The VM checks counts before invoking them, and trait registration/descendant updates verify that each source or native method accepts the canonical argument count. Optional/default parameters are included; bound receiver counts are removed for callback queries. Generic Type construction still uses its host constructor rules. CallSignature adds optional resolved parameter/return types and host effect metadata, as described below. + +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, Window methods and the representable Block/Container/Page 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. Constructors and other management APIs are not yet fully covered; Page.open/window and Block.on keep absent type metadata until nullable/union types can represent their existing forms. Source override variance, trait type/effect compatibility and static effect inference remain pending. 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 8c82558..0faacd0 100644 --- a/src/README.md +++ b/src/README.md @@ -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, asynchronous completion/fault boundaries, 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, configured unified Function classification and source/field annotation checks with native constructor preflight and shared native arity intervals, tab registry, stable-slot insertion, source-dispatched tab reorder/drop and callback registration checks, 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/field annotation checks with native constructor preflight and shared native arity intervals plus resolved types/effects on representable methods, tab registry, stable-slot insertion, source-dispatched tab reorder/drop and callback registration checks, Page lifecycle/navigation and immutable frame extraction | | binding.rs | Target-owned managed property bindings, weak Subscription tokens, zero-argument callback preflight, 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 | @@ -18,12 +18,12 @@ | presentation.rs | Per-window layout, Mount/focus/tab state and read dependencies; VM changes fan out before any view consumes work | | tasks.rs | 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 | -| window.rs | Native Window construction/close, context ownership, ordered Page roots, read-only guards, Page reordering, physical desktop placement and coalesced GUI projections | +| window.rs | Typed native Window queries/effects, construction/close, context ownership, ordered Page roots, read-only guards, Page reordering, physical desktop placement and coalesced GUI projections | | vm_sequence.rs | Shared validated call-sequence builder and EXTENDED_ARG-aware same-frame repetition for layout, event and lifecycle work | | source_layout.rs | Read-only source layout, repeated constraint/geometry solving with cycle detection, per-Mount measurement caches with subcall dependencies, viewport constraints, typed/slot validation and occurrence geometry | | source_hit.rs | Read-only source/native pointer target selectors, reverse paint order, strict Bool results and matching press/release targets | | source_paint.rs | Read-only source paint dispatch, shared VM budget, paired text-wrap bounds and checked command conversion and versioned object dependencies | -| native_visual.rs | Managed native visual protocol queries with occurrence validation, value conversion and bounded results | +| native_visual.rs | Managed native visual protocol queries with resolved type/read-only signatures, occurrence validation, value conversion and bounded results | | object_list.rs | Traced indexed results shared by Mount queries and visual protocol results | | layout.rs | Shared native geometry/paint functions, iterative measurement/arrangement, stable occurrence IDs, measurement cache, solve-pass counters, geometry budgets and width-sensitive native text measurement | | document.rs | Published source/AST/UI snapshot, revisions, invalidation, frame validation, single-line fault banner (full cause retained in Frame), validated optional text-wrap bounds and display commands | diff --git a/src/api.rs b/src/api.rs index 8dd2111..7680857 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1101,9 +1101,11 @@ Source function parameter annotations are checked before the body and return ann Declared fields are checked at construction and set_attr writes through the same enabled type-check switch. Native subclass fields are validated before native allocation/opening effects. Failure preserves the field; declared deletion is rejected. Inherited fields use their declaring definition/environment, the declaring class name keeps its actual identity after REPL redefinition, and other names resolve dynamically in declaration globals/builtins. Shared Block forwarding selects the current content type/storage. This does not scan old objects or revalidate all referring fields after shared-reference changes; trusted payload/storage/attach operations and complete initialization remain host responsibilities. Static/effect typing, override variance and local/captured type annotations remain pending. See examples/field-contracts.endor. -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 native parameter/return type/effect metadata remain separate gaps. See examples/native-signatures.endor. +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. -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. Native parameter/return type metadata, 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. +Native CallSignature checks resolved parameter/return types for visual measure/arrange/paint/hitTest, Point queries, Window methods and representable Block/Container/Page methods. 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. Constructors/other API coverage, nullable/union signatures for Page.open/window and Block.on, override variance and static 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. 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 d3444df..f027a0c 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -2951,6 +2951,58 @@ page.render(block) assert!(session.refresh_document().unwrap().is_none()); } + #[test] + fn native_contracts_reject_wrong_types_before_geometry_or_window_effects() { + let (mut session, _) = ReplSession::load( + include_str!("../examples/visual-protocols.endor"), + "app.main", + 162, + 1, + ) + .unwrap(); + session + .execute("context = rect.mounts().at(0)", "app.main") + .unwrap(); + for (expression, expected) in [ + ("rect.measure(context, Point(0, 0))", "expects Constraints"), + ( + "rect.measure(Point(0, 0), Constraints(0, 0, 120, 80))", + "expects Mount", + ), + ("rect.paint(context, Point(0, 0))", "expects Bounds"), + ( + "Point(0, 0).inside(Constraints(0, 0, 120, 80))", + "expects Bounds", + ), + ("Point(0, 0).inCircle(0, 0, \"bad\")", "expects Number"), + ("ui.window().resize(\"bad\", 700)", "expects Number"), + ("rect.setColor(7)", "expects String"), + ] { + let error = session + .execute(expression, "app.main") + .err() + .expect("invalid native call"); + assert!( + error.to_string().contains(expected), + "{expression}: {error:#}" + ); + } + assert_eq!( + session.execute("results.color", "app.main").unwrap().value, + "\"#DDEEFF\"" + ); + assert_eq!( + session + .execute( + "rect.measure(context, Constraints(0, 0, 120, 80)).width", + "app.main" + ) + .unwrap() + .value, + "120" + ); + } + #[test] fn native_visual_methods_use_managed_values_and_match_real_geometry() { let (mut session, initial) = ReplSession::load( diff --git a/src/native_visual.rs b/src/native_visual.rs index 134be66..d6417b8 100644 --- a/src/native_visual.rs +++ b/src/native_visual.rs @@ -8,8 +8,8 @@ use crate::{ ui_bridge::{MAX_DIMENSION, attach_desktop_type}, }; use endor_core::{ - ContextNativeFunction, NativeCallable, NativeContext, NativeResult, ObjectRef, Value, Vm, - VmError, + AnnotationType, CallEffect, CallSignature, ContextNativeFunction, NativeCallable, + NativeContext, NativeResult, ObjectRef, Value, Vm, VmError, }; fn invalid(message: &'static str) -> VmError { @@ -85,8 +85,12 @@ enum Query { struct Method { query: Query, desktop: ObjectRef, + signature: CallSignature, } impl NativeCallable for Method { + fn signature(&self) -> Option { + Some(self.signature.clone()) + } fn arity(&self) -> Option { Some(endor_core::CallArity::exact(3)) } @@ -278,8 +282,12 @@ impl NativeCallable for Method { struct PointMethod { expected: ObjectRef, circle: bool, + signature: CallSignature, } impl NativeCallable for PointMethod { + fn signature(&self) -> Option { + Some(self.signature.clone()) + } fn arity(&self) -> Option { Some(endor_core::CallArity::exact(if self.circle { 4 @@ -345,15 +353,34 @@ pub fn install( block_type: ObjectRef, function_type: ObjectRef, ) -> Result<(), VmError> { - for (name, query) in [ - ("measure", Query::Measure), - ("arrange", Query::Arrange), - ("paint", Query::Paint), - ("hitTest", Query::HitTest), + let nominal = |name| { + crate::ui_bridge::desktop_type(vm.object_store(), name, desktop) + .map(AnnotationType::Nominal) + }; + let mount = nominal("Mount")?; + let constraints = nominal("Constraints")?; + let bounds = nominal("Bounds")?; + let point = nominal("Point")?; + let measure = nominal("MeasureResult")?; + let arrangement = nominal("Arrangement")?; + let display = nominal("DisplayList")?; + for (name, query, input, returns) in [ + ("measure", Query::Measure, constraints, measure), + ("arrange", Query::Arrange, bounds, arrangement), + ("paint", Query::Paint, bounds, display), + ("hitTest", Query::HitTest, point, AnnotationType::Bool), ] { let function = vm.allocate(ContextNativeFunction::new( name, - Method { query, desktop }, + Method { + query, + desktop, + signature: CallSignature::exact( + vec![AnnotationType::Nominal(block_type), mount, input], + returns, + CallEffect::ReadOnly, + ), + }, vec![desktop], ))?; roots.push(function); @@ -371,6 +398,20 @@ pub fn install( PointMethod { expected: point_type, circle, + signature: CallSignature::exact( + if circle { + vec![ + point, + AnnotationType::Number, + AnnotationType::Number, + AnnotationType::Number, + ] + } else { + vec![point, bounds] + }, + AnnotationType::Bool, + CallEffect::ReadOnly, + ), }, vec![point_type], ))?; diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index ee17b95..21185f5 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -3,8 +3,9 @@ use std::sync::{Arc, Mutex}; use anyhow::{Result, bail}; use endor_core::{ - ContextNativeFunction, EndorReal, EndorTypeObject, NativeCallable, NativeContext, NativeResult, - ObjectRef, TypeConstructor, Value, Vm, VmError, WeakObjectRef, + AnnotationType, CallEffect, CallSignature, ContextNativeFunction, EndorReal, EndorTypeObject, + NativeCallable, NativeContext, NativeResult, ObjectRef, TypeConstructor, Value, Vm, VmError, + WeakObjectRef, }; use crate::{ @@ -320,6 +321,70 @@ impl Operation { } } +fn method_signature( + store: &endor_core::ObjectStore, + desktop: ObjectRef, + receiver: ObjectRef, + operation: Operation, +) -> Result, VmError> { + use AnnotationType::{Any, Function, Nominal, Number, String as TextType, Unit}; + use Operation::*; + let nominal = |name| desktop_type(store, name, desktop).map(Nominal); + let (arguments, returns, effect) = match operation { + Bind => ( + vec![TextType, Function], + nominal("Subscription")?, + CallEffect::Mutating, + ), + Mounts => (vec![], nominal("ObjectList")?, CallEffect::ReadOnly), + Children => (vec![], Any, CallEffect::ReadOnly), + Invalidate => (vec![TextType], Unit, CallEffect::Mutating), + SetText | SetColor => (vec![TextType], Unit, CallEffect::Mutating), + Append => (vec![nominal("Block")?], Number, CallEffect::Mutating), + Insert => ( + vec![Number, nominal("Block")?], + Number, + CallEffect::Mutating, + ), + Remove => (vec![Number], Unit, CallEffect::Mutating), + Replace => (vec![Number, nominal("Block")?], Unit, CallEffect::Mutating), + Move => (vec![Number, Number], Unit, CallEffect::Mutating), + Render | Navigate => (vec![nominal("Block")?], Unit, CallEffect::Mutating), + OnClick => (vec![Function], Nominal(receiver), CallEffect::Mutating), + OnEvent => (vec![nominal("Event")?], Unit, CallEffect::ReadOnly), + OnMount | OnUnmount => (vec![nominal("Mount")?], Unit, CallEffect::ReadOnly), + Click => (vec![nominal("Mount")?], Unit, CallEffect::Mutating), + Dispatch => ( + vec![nominal("Event")?, nominal("Mount")?], + Unit, + CallEffect::Mutating, + ), + MoveWindow => ( + vec![nominal("Window")?], + Nominal(receiver), + CallEffect::Mutating, + ), + MoveTab => (vec![Number], Nominal(receiver), CallEffect::Mutating), + Activate => (vec![], Nominal(receiver), CallEffect::Mutating), + Detach => (vec![], nominal("Window")?, CallEffect::Mutating), + Unmount | Close | CloseWindow | Back | Forward => (vec![], Unit, CallEffect::Mutating), + // These accept nullable/union values not yet expressible in AnnotationType. + // Keep absent metadata explicit instead of narrowing existing calls. + Open | PageWindow | On => return Ok(None), + _ => return Err(invalid("unsupported native method signature")), + }; + let arity = operation.arity(); + let mut parameters = vec![Nominal(receiver)]; + parameters.extend(arguments); + Ok(Some(CallSignature { + arity: endor_core::CallArity::range(arity.required + 1, arity.maximum + 1), + parameters, + variadic: None, + returns, + effect, + })) +} + #[derive(Debug)] struct Function { operation: Operation, @@ -332,12 +397,16 @@ struct Function { /// individual Blocks no longer allocate owner-capturing method closures. #[derive(Debug)] struct TypeMethod { + signature: Option, operation: Operation, expected: ObjectRef, session: Shared, } impl NativeCallable for TypeMethod { + fn signature(&self) -> Option { + self.signature.clone() + } fn arity(&self) -> Option { let arity = self.operation.arity(); Some(endor_core::CallArity::range( @@ -2663,6 +2732,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { let method = vm.allocate(ContextNativeFunction::new( name, TypeMethod { + signature: method_signature(vm.object_store(), desktop, expected, operation)?, operation, expected, session: session.clone(), diff --git a/src/window.rs b/src/window.rs index 10ba19a..20c4d1e 100644 --- a/src/window.rs +++ b/src/window.rs @@ -109,10 +109,14 @@ enum Operation { } #[derive(Debug)] struct Method { + signature: endor_core::CallSignature, operation: Operation, desktop: ObjectRef, } impl NativeCallable for Method { + fn signature(&self) -> Option { + Some(self.signature.clone()) + } fn arity(&self) -> Option { Some(endor_core::CallArity::exact(match self.operation { Operation::Resize | Operation::MoveTo => 3, @@ -334,9 +338,34 @@ pub fn install( ("setTitle", Operation::SetTitle), ("focus", Operation::Focus), ] { + use endor_core::{AnnotationType as T, CallEffect, CallSignature}; + let (parameters, returns, effect) = match operation { + Operation::Id => (vec![], T::Number, CallEffect::ReadOnly), + Operation::Pages => ( + vec![], + T::Nominal(desktop_type(vm.object_store(), "ObjectList", desktop)?), + CallEffect::ReadOnly, + ), + Operation::Viewport => ( + vec![], + T::Nominal(desktop_type(vm.object_store(), "MeasureResult", desktop)?), + CallEffect::ReadOnly, + ), + Operation::Resize | Operation::MoveTo => { + (vec![T::Number, T::Number], T::Unit, CallEffect::Mutating) + } + Operation::SetTitle => (vec![T::String], T::Unit, CallEffect::Mutating), + Operation::Focus => (vec![], T::Unit, CallEffect::Mutating), + }; + let mut arguments = vec![T::Nominal(definition)]; + arguments.extend(parameters); let function = vm.allocate(ContextNativeFunction::new( name, - Method { operation, desktop }, + Method { + operation, + desktop, + signature: CallSignature::exact(arguments, returns, effect), + }, vec![desktop], ))?; roots.push(function); diff --git a/vendor/aster b/vendor/aster index f9243c7..680caf8 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit f9243c77c7609a1afc7cbe6a81fdaa988677d399 +Subproject commit 680caf81e39c6df7f5e1cf6a5c28770380d523db