From 25275b515cf15711800425774649e0b43f3aa645 Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 22 Oct 2026 12:03:24 +0800 Subject: [PATCH] Publish native arity and validate callback contracts before registration --- README.md | 8 +++- examples/native-signatures.endor | 12 +++++ src/README.md | 8 ++-- src/api.rs | 4 +- src/binding.rs | 18 +++++++- src/endor_host.rs | 64 ++++++++++++++++++++++++++ src/event_dispatch.rs | 40 +++++++++++++++- src/mount.rs | 21 +++++++++ src/native_visual.rs | 12 +++++ src/object_list.rs | 10 ++++ src/source_hit.rs | 12 +++++ src/source_layout.rs | 12 +++++ src/source_paint.rs | 8 ++++ src/tasks.rs | 15 ++++-- src/ui_bridge.rs | 78 +++++++++++++++++++++++--------- src/window.rs | 8 ++++ vendor/aster | 2 +- 17 files changed, 297 insertions(+), 35 deletions(-) create mode 100644 examples/native-signatures.endor diff --git a/README.md b/README.md index 3562996..1c27d6b 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. 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. +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. 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. @@ -405,10 +405,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 common native-signature metadata remain pending. Native APIs continue to validate +effect typing and native parameter/return type metadata remain pending. Native APIs continue to validate their arguments and results at their own boundaries. +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. + +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. + ### Owner-managed asynchronous tasks `ui.after(owner, key, milliseconds, callback)` returns a managed `Task` and runs diff --git a/examples/native-signatures.endor b/examples/native-signatures.endor new file mode 100644 index 0000000..a86ebe1 --- /dev/null +++ b/examples/native-signatures.endor @@ -0,0 +1,12 @@ +received = ui.state(Event("waiting")) +count = ui.state(0) +function eventKind(): String { return received.value.kind } +label = TextBlock("waiting") +subscription = label.bind("text", eventKind) +withEvent = Button("传递 Event 给原生 set") +firstConnection = withEvent.on("click", received.set) +withoutEvent = Button("调用零参数原生 increment") +secondConnection = withoutEvent.on("click", count.increment) +page = Page() +page.title = "原生方法签名" +page.render(Column(24, 16, TextBlock("源码和原生回调共用参数契约"), label, ui.textOf(count, "value"), withEvent, withoutEvent)) diff --git a/src/README.md b/src/README.md index 4d38d45..dabb0c5 100644 --- a/src/README.md +++ b/src/README.md @@ -7,8 +7,8 @@ | 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, tab registry, stable-slot insertion, source-dispatched tab reorder/drop, 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 | +| 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 | +| 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 | | mount.rs | Managed per-occurrence contexts, weak reverse links, ordered mount/unmount hooks, geometry and focus queries | @@ -58,7 +58,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, stable-slot insertion and tab drop/override/stale-target behavior, multiline inputs, original source ranges, malformed input, -owner/task cancellation, hidden-object delivery, stale request and callback failure, entry checks, source function/declared-field annotation checks, constructor side-effect prevention, shared field forwarding/function identity and REPL class redefinition, budgets, failure preservation, live object identity, explicit rendering, +owner/task cancellation, hidden-object delivery, stale request and callback failure, entry checks, source function/declared-field annotation checks, constructor side-effect prevention, native callback signature/pre-registration validation, shared field forwarding/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, @@ -129,3 +129,5 @@ Mount.scrollBy method without changing guest focus. Mount requests mark a per-window projection refresh; snapshots/caches never own business objects. Tab drops validate source and destination window/session/layout plus the actual VM Page order before callbacks. The bridge invokes managed Page methods, respecting source overrides that decline or redirect a window move. Reordering within a window retains Mounts; moving windows retains Page identity and replaces Mounts. Native drag feedback is host state, with no additional managed roots. Desktop placement is an asynchronous physical outer-origin request, protected by the existing session/commit boundary. Regression sources cover the HTTP event allowlist, stale frame reuse, stable insertion, source overrides and signed positions; these were compiled, not locally executed. + +NativeCallable implementations publish positional metadata, including internal layout/paint/hit/event continuations. The VM validates it before entering Rust. Event delivery uses the same source/native/bound arity query; binding and Task registration reject incompatible or unknown metadata before changing ownership. Native parameter/return types and effects remain checked by existing host boundaries rather than this count-only metadata. diff --git a/src/api.rs b/src/api.rs index 8ea5c08..ccdacbd 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1097,7 +1097,9 @@ 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. -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, 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 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. + +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. 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/binding.rs b/src/binding.rs index ac9d496..de96089 100644 --- a/src/binding.rs +++ b/src/binding.rs @@ -58,7 +58,23 @@ pub fn connect( .properties .ok_or(VmError::InvalidArgument("missing property storage"))?; cx.store().get_attr(properties, field)?; - cx.store().object(compute)?; + if !cx.store().object(compute)?.payload().is_function() { + return Err(VmError::InvalidArgument( + "binding compute must be a Function", + )); + } + if !cx + .store() + .call_arity(compute)? + .ok_or(VmError::InvalidArgument( + "binding compute requires positional metadata", + ))? + .accepts(0) + { + return Err(VmError::InvalidArgument( + "binding compute requires zero unbound parameters", + )); + } let mut retained = vec![]; for connection in &data.bindings { let mut binding = cx diff --git a/src/endor_host.rs b/src/endor_host.rs index 60d3423..8775ee3 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -993,6 +993,70 @@ mod tests { const EXAMPLE: &str = include_str!("../examples/hello.endor"); const PAGE: &str = include_str!("../examples/page.endor"); + #[test] + fn native_signatures_validate_registration_and_deliver_the_event_argument() { + let (mut session, _) = ReplSession::load( + include_str!("../examples/native-signatures.endor"), + "app.main", + 1, + 220, + ) + .unwrap(); + for invalid in [ + r#"withEvent.on("click", ui.textOf)"#, + r#"withEvent.on("click", Page)"#, + r#"label.bind("text", received.set)"#, + r#"ui.after(ui,"bad",60000,received.set)"#, + "count.increment(1)", + ] { + assert!(session.execute(invalid, "app.main").is_err(), "{invalid}"); + assert!( + session.documents[&crate::window::MAIN_WINDOW] + .frame + .fault + .is_none() + ); + } + let document = session + .execute("withEvent.click()", "app.main") + .unwrap() + .document + .unwrap(); + assert!(document.frame.commands.iter().any( + |command| matches!(command, RenderCommand::Text { value, .. } if value == "click") + )); + assert_eq!( + session + .execute("received.value.kind", "app.main") + .unwrap() + .value, + r#""click""# + ); + session.execute("withoutEvent.click()", "app.main").unwrap(); + assert_eq!( + session.execute("count.value", "app.main").unwrap().value, + "1" + ); + assert!(session.poll_tasks().unwrap().is_none()); + let globals = session.candidate.globals.unwrap(); + let Value::Object(received) = session + .candidate + .vm + .dict_get(globals, &Value::Text("received".into())) + .unwrap() + .unwrap() + else { + panic!("state") + }; + let Value::Object(set) = session.candidate.vm.get_attr(received, "set").unwrap() else { + panic!("set") + }; + assert_eq!( + session.candidate.vm.call_arity(set).unwrap(), + Some(endor_core::CallArity::exact(1)) + ); + } + #[test] fn checked_fields_reject_native_constructor_side_effects_and_preserve_live_values() { let (mut session, _) = ReplSession::load( diff --git a/src/event_dispatch.rs b/src/event_dispatch.rs index 77adb8e..e88a0e6 100644 --- a/src/event_dispatch.rs +++ b/src/event_dispatch.rs @@ -11,6 +11,24 @@ fn invalid(message: &'static str) -> VmError { VmError::InvalidArgument(message) } +pub fn validate_handler( + store: &endor_core::ObjectStore, + function: ObjectRef, +) -> Result<(), VmError> { + if !store.object(function)?.payload().is_function() { + return Err(invalid("event handler must be a Function")); + } + let arity = store + .call_arity(function)? + .ok_or(invalid("event handler requires positional metadata"))?; + if !arity.accepts(0) && !arity.accepts(1) { + return Err(invalid( + "event handler must accept zero arguments or one Event", + )); + } + Ok(()) +} + #[derive(Debug, Clone, Default)] pub struct Event { dispatch: Option, @@ -84,6 +102,10 @@ enum Method { Connected, } impl NativeCallable for Method { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(1)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let [Value::Object(owner)] = args else { return Err(invalid("event method receiver")); @@ -159,6 +181,10 @@ impl NativeCallable for Method { #[derive(Debug)] pub struct Constructor; impl NativeCallable for Constructor { + fn arity(&self) -> Option { + Some(endor_core::CallArity::range(2, usize::MAX)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let [Value::Object(definition), Value::Text(kind), values @ ..] = args else { return Err(invalid("Event requires an event kind")); @@ -171,6 +197,8 @@ impl NativeCallable for Constructor { if fields.len() != values.len() { return Err(invalid("incorrect Event field arguments")); } + cx.store() + .check_class_field_arguments(*definition, values)?; let event = new_event(cx, *definition, kind)?; for (field, value) in fields.iter().zip(values) { cx.set_attr(event, &field.name, value.clone())?; @@ -240,6 +268,10 @@ struct Delivery { handler: Handler, } impl NativeCallable for Delivery { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { let mut event = cx.store().payload::(self.event, "Event")?.clone(); if event.immediate || event.stopped_at.is_some_and(|group| group != self.group) { @@ -280,8 +312,8 @@ impl NativeCallable for Delivery { if matches!(self.handler, Handler::ObjectMethod) || cx .store() - .positional_parameter_count(function)? - .is_some_and(|count| count > 0) + .call_arity(function)? + .is_some_and(|arity| arity.accepts(1)) { arguments.push(Value::Object(self.event)); } @@ -294,6 +326,10 @@ impl NativeCallable for Delivery { #[derive(Debug)] struct Finish(ObjectRef); impl NativeCallable for Finish { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { let mut event = cx.store().payload::(self.0, "Event")?.clone(); event.dispatch = None; diff --git a/src/mount.rs b/src/mount.rs index 05981bd..555afa2 100644 --- a/src/mount.rs +++ b/src/mount.rs @@ -71,6 +71,19 @@ struct Method { } impl NativeCallable for Method { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact( + if matches!( + self.query, + Query::HitTest | Query::ScrollTo | Query::ScrollBy + ) { + 2 + } else { + 0 + }, + )) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let mount = cx.store().payload::(self.owner, "Mount")?.clone(); if !mount.mounted @@ -246,6 +259,10 @@ struct LifecycleCall { mount: ObjectRef, } impl NativeCallable for LifecycleCall { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, _: &mut NativeContext<'_>, _: &[Value]) -> Result { Ok(NativeResult::Invoke { function: self.function, @@ -280,6 +297,10 @@ fn lifecycle_call( } impl NativeCallable for Sync { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, _args: &[Value]) -> Result { let mut blocks = HashMap::new(); for weak in &self.nodes { diff --git a/src/native_visual.rs b/src/native_visual.rs index d0785f6..ec156d2 100644 --- a/src/native_visual.rs +++ b/src/native_visual.rs @@ -81,6 +81,10 @@ struct Method { desktop: ObjectRef, } impl NativeCallable for Method { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(3)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let [owner, context, input] = args else { return Err(invalid("visual method expects a Mount and an input value")); @@ -257,6 +261,14 @@ struct PointMethod { circle: bool, } impl NativeCallable for PointMethod { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(if self.circle { + 4 + } else { + 2 + })) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let Some(Value::Object(point)) = args.first() else { return Err(invalid("Point method requires a Point")); diff --git a/src/object_list.rs b/src/object_list.rs index 8b37d86..b9ec6d0 100644 --- a/src/object_list.rs +++ b/src/object_list.rs @@ -28,6 +28,10 @@ impl ObjectPayload for ObjectList { #[derive(Debug)] struct At(ObjectRef); impl NativeCallable for At { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(1)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let [Value::Number(index)] = args else { return Err(VmError::InvalidArgument("object list at expects an index")); @@ -94,6 +98,10 @@ pub struct Constructor { pub desktop: ObjectRef, } impl NativeCallable for Constructor { + fn arity(&self) -> Option { + Some(endor_core::CallArity::range(1, usize::MAX)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let [Value::Object(definition), values @ ..] = args else { return Err(VmError::InvalidArgument("ObjectList type argument")); @@ -115,6 +123,8 @@ impl NativeCallable for Constructor { .ok_or(VmError::InvalidArgument( "missing ObjectList subclass fields", ))?; + cx.store() + .check_class_field_arguments(*definition, &values[count..])?; let members = values[..count] .iter() .map(|value| { diff --git a/src/source_hit.rs b/src/source_hit.rs index 9a0da90..0308952 100644 --- a/src/source_hit.rs +++ b/src/source_hit.rs @@ -9,6 +9,10 @@ use endor_core::{ #[derive(Debug)] struct Boolean; impl NativeCallable for Boolean { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(1)) + } + fn invoke(&self, _: &mut NativeContext<'_>, args: &[Value]) -> Result { let [Value::Bool(value)] = args else { return Err(VmError::InvalidArgument("hitTest must return Bool")); @@ -19,6 +23,10 @@ impl NativeCallable for Boolean { #[derive(Debug)] struct SameTarget; impl NativeCallable for SameTarget { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(2)) + } + fn invoke(&self, _: &mut NativeContext<'_>, args: &[Value]) -> Result { let value = match args { [Value::Object(first), Value::Object(second)] if first == second => { @@ -132,6 +140,10 @@ struct Prepare { desktop: ObjectRef, } impl NativeCallable for Prepare { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { let down = selector(cx, &self.candidates, self.press, self.desktop)?; let up = selector(cx, &self.candidates, self.release, self.desktop)?; diff --git a/src/source_layout.rs b/src/source_layout.rs index 9978651..e34abab 100644 --- a/src/source_layout.rs +++ b/src/source_layout.rs @@ -98,6 +98,10 @@ struct Step { desktop: ObjectRef, } impl NativeCallable for Step { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { let mount = cx.store().payload::(self.mount, "Mount")?.clone(); let definition = cx @@ -258,6 +262,10 @@ struct Collect { desktop: ObjectRef, } impl NativeCallable for Collect { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(1)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let pending = if matches!(self.phase, Phase::Measure) { self.plan @@ -403,6 +411,10 @@ struct Prepare { desktop: ObjectRef, } impl NativeCallable for Prepare { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { let mut instructions = Vec::new(); let mut constants = Vec::new(); diff --git a/src/source_paint.rs b/src/source_paint.rs index 414e9aa..4a1cf57 100644 --- a/src/source_paint.rs +++ b/src/source_paint.rs @@ -133,6 +133,10 @@ struct Collect { output: Output, } impl NativeCallable for Collect { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(1)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let [Value::Object(result)] = args else { return Err(invalid("paint must return a DisplayList")); @@ -168,6 +172,10 @@ struct Prepare { output: Output, } impl NativeCallable for Prepare { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(0)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, _: &[Value]) -> Result { let block_type = named_type(cx.store(), self.desktop, "Block")?; let native = cx diff --git a/src/tasks.rs b/src/tasks.rs index ed34f7d..72eb907 100644 --- a/src/tasks.rs +++ b/src/tasks.rs @@ -196,6 +196,10 @@ struct After { desktop: ObjectRef, } impl NativeCallable for After { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(4)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { if cx.store().is_read_only() { return Err(invalid( @@ -212,10 +216,11 @@ impl NativeCallable for After { if !cx.store().object(callback)?.payload().is_function() { return Err(invalid("task callback must be a Function")); } - if cx + if !cx .store() - .positional_parameter_count(callback)? - .is_some_and(|count| count != 0) + .call_arity(callback)? + .ok_or(invalid("task callback requires positional metadata"))? + .accepts(0) { return Err(invalid("task callback requires zero unbound parameters")); } @@ -323,6 +328,10 @@ struct Method { desktop: ObjectRef, } impl NativeCallable for Method { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(1)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let [value] = args else { return Err(invalid("Task methods accept no arguments")); diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index 1b7f11d..d709e98 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -291,6 +291,35 @@ enum Operation { Present, } +impl Operation { + fn arity(self) -> endor_core::CallArity { + use Operation::*; + let (minimum, maximum) = match self { + IsInstance | IsSubtype | Bind | Implement | Implements | Supports => (2, 2), + Stats | Viewport | Window | PageWindow | Mounts => (0, 0), + State | StateSet => (1, 1), + Increment => (0, 0), + TextOf => (2, 4), + Scroll => (3, 3), + Text => (1, 3), + Rect => (2, 4), + MoveTab | MoveWindow | OpenValue | Spacer | SetText | SetColor | Append | Remove + | Render | Navigate | OnClick | Present => (1, 1), + Row | Column => (2, MAX_UI_NODES + 2), + Button => (1, 1), + Insert | Replace | Move => (2, 2), + Page | Unmount | Close | Activate | Back | Forward | Children | NewWindow + | CloseWindow | Detach => (0, 0), + Open => (0, 1), + Click | Invalidate => (0, 1), + On => (2, 3), + Dispatch => (1, 2), + OnEvent | OnMount | OnUnmount => (1, 1), + }; + endor_core::CallArity::range(minimum, maximum) + } +} + #[derive(Debug)] struct Function { operation: Operation, @@ -309,6 +338,14 @@ struct TypeMethod { } impl NativeCallable for TypeMethod { + fn arity(&self) -> Option { + let arity = self.operation.arity(); + Some(endor_core::CallArity::range( + arity.required + 1, + arity.maximum + 1, + )) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let owner = object(args.first())?; if !cx.store().is_instance(owner, self.expected)? { @@ -333,6 +370,13 @@ struct NativeFactory { } impl NativeCallable for NativeFactory { + fn arity(&self) -> Option { + Some(endor_core::CallArity::range( + self.operation.arity().required + 1, + usize::MAX, + )) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let requested = object(args.first())?; let fields = cx @@ -617,6 +661,10 @@ struct PresentResult { session: Shared, } impl NativeCallable for PresentResult { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(1)) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let [Value::Object(root)] = args else { return Err(invalid("Presentable.present must return a Block")); @@ -683,30 +731,14 @@ fn present_value( } impl NativeCallable for Function { + fn arity(&self) -> Option { + Some(self.operation.arity()) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { use Operation::*; - let (minimum, maximum) = match self.operation { - IsInstance | IsSubtype | Bind | Implement | Implements | Supports => (2, 2), - Stats | Viewport | Window | PageWindow | Mounts => (0, 0), - State | StateSet => (1, 1), - Increment => (0, 0), - TextOf => (2, 4), - Scroll => (3, 3), - Text => (1, 3), - Rect => (2, 4), - MoveTab | MoveWindow | OpenValue | Spacer | SetText | SetColor | Append | Remove - | Render | Navigate | OnClick | Present => (1, 1), - Row | Column => (2, MAX_UI_NODES + 2), - Button => (1, 1), - Insert | Replace | Move => (2, 2), - Page | Unmount | Close | Activate | Back | Forward | Children | NewWindow - | CloseWindow | Detach => (0, 0), - Open => (0, 1), - Click | Invalidate => (0, 1), - On => (2, 3), - Dispatch => (1, 2), - OnEvent | OnMount | OnUnmount => (1, 1), - }; + let arity = self.operation.arity(); + let (minimum, maximum) = (arity.required, arity.maximum); if !(minimum..=maximum).contains(&args.len()) { return Err(invalid("incorrect UI method argument count")); } @@ -1381,6 +1413,7 @@ impl NativeCallable for Function { } OnClick => { let handler = object(args.first())?; + crate::event_dispatch::validate_handler(cx.store(), handler)?; data.click = Some(handler); result = Value::Object(owner); } @@ -1390,6 +1423,7 @@ impl NativeCallable for Function { return Err(invalid("invalid event kind")); } let handler = object(args.get(1))?; + crate::event_dispatch::validate_handler(cx.store(), handler)?; let capture = match args.get(2) { None | Some(Value::Bool(false)) => false, Some(Value::Bool(true)) => true, diff --git a/src/window.rs b/src/window.rs index dabd60b..10ba19a 100644 --- a/src/window.rs +++ b/src/window.rs @@ -113,6 +113,14 @@ struct Method { desktop: ObjectRef, } impl NativeCallable for Method { + fn arity(&self) -> Option { + Some(endor_core::CallArity::exact(match self.operation { + Operation::Resize | Operation::MoveTo => 3, + Operation::SetTitle => 2, + _ => 1, + })) + } + fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result { let Some(Value::Object(owner)) = args.first() else { return Err(invalid("Window method requires a Window")); diff --git a/vendor/aster b/vendor/aster index 20e29e3..44519ab 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit 20e29e3c5a4c014a3e67aece65eb1c133a7794ec +Subproject commit 44519abf7e1ce879da7c27875195ca5a2393cb1a