From ab40e424e0acc1d91a6b215372794781fd21f46b Mon Sep 17 00:00:00 2001 From: Codex Bot Date: Thu, 22 Oct 2026 15:08:29 +0800 Subject: [PATCH] Publish UI factory contracts and separate native options from subclass fields --- README.md | 8 +- examples/constructor-contracts.endor | 18 +++ src/README.md | 6 +- src/api.rs | 2 +- src/endor_host.rs | 101 ++++++++++++ src/event_dispatch.rs | 7 +- src/object_list.rs | 4 + src/ui_bridge.rs | 219 ++++++++++++++++++++++++++- vendor/aster | 2 +- 9 files changed, 358 insertions(+), 9 deletions(-) create mode 100644 examples/constructor-contracts.endor diff --git a/README.md b/README.md index 2f3997b..ad9abc2 100644 --- a/README.md +++ b/README.md @@ -424,7 +424,13 @@ 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. 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. +Host CallEffect distinguishes ReadOnly, Delegated, Mutating and External. Delegated means the native wrapper itself is read-only while its continuation has dynamic effects; ui.present uses this category and the actual callback remains in the same VM scope. It is not a static purity proof. 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. + +Public ui functions, captured state set/increment methods and native constructor factories now publish signatures. Bootstrap fills immutable signatures after all referenced types exist, preserving function identities. A native factory first separates the requested subclass fields from native options; its envelope checks the Type receiver/general result/effect, then the concrete options and declared fields are checked before allocation or window effects. Optional Rect/Text options and variadic Row/Column children therefore do not consume subclass fields. Event/ObjectList factories retain their own field/member validation. Generic Type construction still has no single fixed reflected signature. See [constructor-contracts.endor](examples/constructor-contracts.endor). + +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/examples/constructor-contracts.endor b/examples/constructor-contracts.endor new file mode 100644 index 0000000..7447085 --- /dev/null +++ b/examples/constructor-contracts.endor @@ -0,0 +1,18 @@ +class TaggedRect: RectBlock { tag: String } +class TaggedColumn: Column { tag: String } +class TaggedEvent: Event { tag: String } +class TaggedList: ObjectList { tag: String } +class Actions { + rect: TaggedRect + function recolor(self: Actions): Unit { self.rect.color = "#237A45" } +} +rect = TaggedRect(180, 60, "省略 radius/color 后的字段") +event = TaggedEvent("click", "事件字段") +items = TaggedList(rect, event, "列表成员之后的字段") +actions = Actions(rect) +button = Button("调用原对象方法") +button.onClick(actions.recolor) +root = TaggedColumn(24, 16, TextBlock("原生选项与子类字段分别检查", 2), rect, ui.textOf(rect, "tag"), ui.textOf(event, "tag"), ui.textOf(items, "tag"), button, "可变子项之后的字段") +page = Page() +page.title = "构造器契约" +page.render(root) diff --git a/src/README.md b/src/README.md index 5c1e58a..48ad933 100644 --- a/src/README.md +++ b/src/README.md @@ -7,13 +7,13 @@ | 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/override checks with native constructor preflight and shared native arity intervals plus resolved types/unions/effects on methods, 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/override checks with deferred typed public/native constructor signatures and split option/field preflight plus shared native arity intervals plus resolved types/unions/effects on 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 | | 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 | +| event_dispatch.rs | Typed Event factory and managed Event/Subscription methods, weak Subscription tokens, Block-owned connections and occurrence-specific capture/target/bubble through a budgeted VM driver | | 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 | @@ -24,7 +24,7 @@ | 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 resolved type/read-only signatures, occurrence validation, value conversion and bounded results | -| object_list.rs | Typed read-only indexed access and traced results shared by Mount queries and visual protocol results | +| object_list.rs | Typed factory envelopes, read-only indexed access and traced 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 | | app.rs | Window events, logical viewport publication, redraw, native multi-window tab dragging and system widget pointer/keyboard/IME routing | diff --git a/src/api.rs b/src/api.rs index 51ffe26..4658330 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1103,7 +1103,7 @@ 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 and static source 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; Delegated allows a read-only native wrapper while delegated targets keep the same VM read-only/budget scope (ui.present); 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. Public ui functions, captured state methods and native factories publish signatures after the registry exists. Factories check the Type receiver/general result/effect and split native options from requested-class fields before validating both; omitted Rect/Text options and Row/Column variable children cannot absorb subclass fields. Event/ObjectList keep dedicated member/field checks. Generic Type reflection still has no single fixed constructor signature. See examples/constructor-contracts.endor. Source/Delegated transitive effects remain unknown; static inference remains 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/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. diff --git a/src/endor_host.rs b/src/endor_host.rs index b1e6a17..e9b563f 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -2951,6 +2951,107 @@ page.render(block) assert!(session.refresh_document().unwrap().is_none()); } + #[test] + fn constructor_options_and_subclass_fields_have_independent_contracts() { + let (mut session, document) = ReplSession::load( + include_str!("../examples/constructor-contracts.endor"), + "app.main", + 166, + 1, + ) + .unwrap(); + document.validate().unwrap(); + for (expression, expected) in [ + ("rect.width", "180"), + ("rect.radius", "0"), + ("rect.tag", "\"省略 radius/color 后的字段\""), + ("root.tag", "\"可变子项之后的字段\""), + ("event.kind", "\"click\""), + ("items.count", "2"), + ("ui.isInstance(items.at(0), TaggedRect)", "true"), + ] { + assert_eq!( + session.execute(expression, "app.main").unwrap().value, + expected, + "{expression}" + ); + } + let blocks = session + .execute("ui.stats().blocks", "app.main") + .unwrap() + .value; + for (expression, expected) in [ + ("TaggedRect(\"bad\", 60, \"tag\")", "expects Number"), + ("TaggedColumn(0, 0, 7, \"tag\")", "expects Block"), + ("ui.rect(1, 2, \"bad\")", "expects Number"), + ("ui.text(7)", "expects String"), + ("TaggedEvent(7, \"tag\")", "expects String"), + ("ui.isSubtype(7, Block)", "expects Type"), + ] { + let error = session + .execute(expression, "app.main") + .err() + .expect("invalid typed constructor/API"); + assert!( + error.to_string().contains(expected), + "{expression}: {error:#}" + ); + } + assert_eq!( + session + .execute("ui.stats().blocks", "app.main") + .unwrap() + .value, + blocks + ); + session.execute("button.click()", "app.main").unwrap(); + assert_eq!( + session.execute("rect.color", "app.main").unwrap().value, + "\"#237A45\"" + ); + for name in [ + "open", + "present", + "text", + "rect", + "spacer", + "row", + "column", + "button", + "page", + "state", + "textOf", + "stats", + "viewport", + "window", + "isInstance", + "isSubtype", + "implement", + "implements", + "supports", + "after", + ] { + let Value::Object(function) = session + .candidate + .vm + .get_attr(session.bridge.ui, name) + .unwrap() + else { + panic!("native Function") + }; + let signature = session + .candidate + .vm + .object_store() + .native_signature(function) + .unwrap() + .expect("published UI signature"); + signature + .validate(session.candidate.vm.object_store()) + .unwrap(); + } + } + #[test] fn source_overrides_accept_wider_inputs_and_more_specific_results() { let source = include_str!("../examples/method-contracts.endor"); diff --git a/src/event_dispatch.rs b/src/event_dispatch.rs index e97501f..8355c45 100644 --- a/src/event_dispatch.rs +++ b/src/event_dispatch.rs @@ -179,8 +179,13 @@ impl NativeCallable for Method { } #[derive(Debug)] -pub struct Constructor; +pub struct Constructor { + pub signature: Option, +} impl NativeCallable for Constructor { + fn signature(&self) -> Option { + self.signature.clone() + } fn arity(&self) -> Option { Some(endor_core::CallArity::range(2, usize::MAX)) } diff --git a/src/object_list.rs b/src/object_list.rs index 0e452f1..6cc281a 100644 --- a/src/object_list.rs +++ b/src/object_list.rs @@ -102,9 +102,13 @@ pub fn items(store: &endor_core::ObjectStore, list: ObjectRef) -> Result<&[Objec #[derive(Debug)] pub struct Constructor { + pub signature: Option, pub desktop: ObjectRef, } impl NativeCallable for Constructor { + fn signature(&self) -> Option { + self.signature.clone() + } fn arity(&self) -> Option { Some(endor_core::CallArity::range(1, usize::MAX)) } diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index 6e8fa61..8959c34 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -396,8 +396,90 @@ fn method_signature( Ok(signature) } +fn operation_signature( + store: &endor_core::ObjectStore, + desktop: ObjectRef, + operation: Operation, +) -> Result { + use AnnotationType::{Any, Bool, Number, String as TextType, Trait, Type, Unit}; + use Operation::*; + let nominal = |name| desktop_type(store, name, desktop).map(AnnotationType::Nominal); + let (parameters, variadic, returns, effect) = match operation { + IsInstance => (vec![Any, Type], None, Bool, CallEffect::ReadOnly), + IsSubtype => (vec![Type, Type], None, Bool, CallEffect::ReadOnly), + Implement => (vec![Type, Trait], None, Unit, CallEffect::Mutating), + Implements => (vec![Type, Trait], None, Bool, CallEffect::ReadOnly), + Supports => (vec![Any, Trait], None, Bool, CallEffect::ReadOnly), + OpenValue => (vec![Any], None, nominal("Page")?, CallEffect::Mutating), + Present => (vec![Any], None, nominal("Block")?, CallEffect::Delegated), + State => (vec![Any], None, Any, CallEffect::ReadOnly), + StateSet => (vec![Any], None, Unit, CallEffect::Mutating), + Increment => (vec![], None, Unit, CallEffect::Mutating), + Stats => (vec![], None, Any, CallEffect::External), + Viewport => ( + vec![], + None, + nominal("MeasureResult")?, + CallEffect::ReadOnly, + ), + Window => (vec![], None, nominal("Window")?, CallEffect::ReadOnly), + NewWindow => (vec![], None, nominal("Window")?, CallEffect::Mutating), + TextOf => ( + vec![Any, TextType, Number, TextType], + None, + nominal("TextBlock")?, + CallEffect::ReadOnly, + ), + Text => ( + vec![TextType, Number, TextType], + None, + nominal("TextBlock")?, + CallEffect::ReadOnly, + ), + Rect => ( + vec![Number, Number, Number, TextType], + None, + nominal("RectBlock")?, + CallEffect::ReadOnly, + ), + Spacer => (vec![Number], None, nominal("Spacer")?, CallEffect::ReadOnly), + Scroll => ( + vec![Number, Number, nominal("Block")?], + None, + nominal("ScrollBlock")?, + CallEffect::ReadOnly, + ), + Row | Column => ( + vec![Number, Number], + Some(nominal("Block")?), + nominal(if matches!(operation, Row) { + "Row" + } else { + "Column" + })?, + CallEffect::ReadOnly, + ), + Button => ( + vec![TextType], + None, + nominal("Button")?, + CallEffect::ReadOnly, + ), + Page => (vec![], None, nominal("Page")?, CallEffect::ReadOnly), + _ => return Err(invalid("unsupported UI function signature")), + }; + Ok(CallSignature { + arity: operation.arity(), + parameters: parameters.into_iter().map(CallType::from).collect(), + variadic: variadic.map(CallType::from), + returns: returns.into(), + effect, + }) +} + #[derive(Debug)] struct Function { + signature: Option, operation: Operation, owner: Option, session: Shared, @@ -432,6 +514,7 @@ impl NativeCallable for TypeMethod { return Err(invalid("incorrect receiver type for visual method")); } Function { + signature: None, operation: self.operation, owner: Some(owner), session: self.session.clone(), @@ -445,11 +528,16 @@ impl NativeCallable for TypeMethod { /// constructor options precede the subclass's inherited/own field arguments. #[derive(Debug)] struct NativeFactory { + signature: Option, + options: Option, operation: Operation, session: Shared, } impl NativeCallable for NativeFactory { + fn signature(&self) -> Option { + self.signature.clone() + } fn arity(&self) -> Option { Some(endor_core::CallArity::range( self.operation.arity().required + 1, @@ -471,7 +559,16 @@ impl NativeCallable for NativeFactory { .ok_or(invalid("missing subclass field arguments"))?; cx.store() .check_class_field_arguments(requested, &values[native_count..])?; + self.options + .as_ref() + .ok_or(invalid("native factory is not initialized"))? + .check_arguments( + cx.store(), + "native constructor options", + &values[..native_count], + )?; let result = Function { + signature: None, operation: self.operation, owner: None, session: self.session.clone(), @@ -554,6 +651,7 @@ fn bind( let function = cx.allocate(ContextNativeFunction::new( name, Function { + signature: Some(operation_signature(cx.store(), desktop, operation)?), operation, owner: Some(owner), session: session.clone(), @@ -811,6 +909,9 @@ fn present_value( } impl NativeCallable for Function { + fn signature(&self) -> Option { + self.signature.clone() + } fn arity(&self) -> Option { Some(self.operation.arity()) } @@ -2515,6 +2616,8 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { next_mount: 0, retired_commands: Vec::new(), })); + let mut public_functions = Vec::new(); + let mut factories = Vec::new(); for (name, operation) in [ ("implement", Operation::Implement), ("implements", Operation::Implements), @@ -2539,6 +2642,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { let function = vm.allocate(ContextNativeFunction::new( name, Function { + signature: None, operation, owner: None, session: session.clone(), @@ -2548,6 +2652,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { ))?; roots.push(function); vm.set_attr(ui, name, Value::Object(function))?; + public_functions.push((name, function, operation)); } let root_types = vm.bootstrap_types()?; roots.extend([root_types.object, root_types.type_type]); @@ -2582,7 +2687,10 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { Some("object-list") => { let factory = vm.allocate(ContextNativeFunction::new( "object-list", - crate::object_list::Constructor { desktop }, + crate::object_list::Constructor { + desktop, + signature: None, + }, vec![desktop], ))?; roots.push(factory); @@ -2593,7 +2701,7 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { Some("event") => { let factory = vm.allocate(ContextNativeFunction::new( "event", - crate::event_dispatch::Constructor, + crate::event_dispatch::Constructor { signature: None }, vec![], ))?; roots.push(factory); @@ -2617,6 +2725,8 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { let factory = vm.allocate(ContextNativeFunction::new( constructor_name, NativeFactory { + signature: None, + options: None, operation, session: session.clone(), }, @@ -2629,6 +2739,10 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { } None => TypeConstructor::Abstract, }; + if let (Some(tag), TypeConstructor::NativeTyped(factory)) = (constructor_name, constructor) + { + factories.push((tag, factory)); + } let definition = vm.new_type(name, base, constructor)?; roots.push(definition); vm.set_attr(ui, name, Value::Object(definition))?; @@ -2681,6 +2795,107 @@ pub fn install(vm: &mut Vm, roots: &mut Vec) -> Result { let function_type = object(Some(&vm.get_attr(ui, "Function")?))?; vm.set_function_type(function_type)?; vm.set_source_type_checks(true)?; + for (name, function, operation) in public_functions { + vm.replace_payload( + function, + ContextNativeFunction::new( + name, + Function { + signature: Some(operation_signature(vm.object_store(), desktop, operation)?), + operation, + owner: None, + session: session.clone(), + requested_type: None, + }, + vec![desktop], + ), + )?; + } + for (name, function) in factories { + let operation = match name { + "text" => Some(Operation::Text), + "rect" => Some(Operation::Rect), + "spacer" => Some(Operation::Spacer), + "scroll" => Some(Operation::Scroll), + "row" => Some(Operation::Row), + "column" => Some(Operation::Column), + "button" => Some(Operation::Button), + "page" => Some(Operation::Page), + "window-create" => Some(Operation::NewWindow), + "event" | "object-list" => None, + _ => return Err(invalid("unknown deferred factory").into()), + }; + if let Some(operation) = operation { + let options = operation_signature(vm.object_store(), desktop, operation)?; + let envelope = CallSignature { + arity: endor_core::CallArity::range(options.arity.required + 1, usize::MAX), + parameters: vec![AnnotationType::Type.into()], + variadic: Some(AnnotationType::Any.into()), + returns: options.returns.clone(), + effect: options.effect, + }; + let mut captures = vec![desktop]; + captures.extend(options.references()); + vm.replace_payload( + function, + ContextNativeFunction::new( + name, + NativeFactory { + signature: Some(envelope), + options: Some(options), + operation, + session: session.clone(), + }, + captures, + ), + )?; + } else { + let kind = if name == "event" { + "Event" + } else { + "ObjectList" + }; + let signature = CallSignature { + arity: endor_core::CallArity::range( + if name == "event" { 2 } else { 1 }, + usize::MAX, + ), + parameters: if name == "event" { + vec![AnnotationType::Type.into(), AnnotationType::String.into()] + } else { + vec![AnnotationType::Type.into()] + }, + variadic: Some(AnnotationType::Any.into()), + returns: AnnotationType::Nominal(desktop_type(vm.object_store(), kind, desktop)?) + .into(), + effect: CallEffect::ReadOnly, + }; + if name == "event" { + vm.replace_payload( + function, + ContextNativeFunction::new( + name, + crate::event_dispatch::Constructor { + signature: Some(signature), + }, + vec![], + ), + )?; + } else { + vm.replace_payload( + function, + ContextNativeFunction::new( + name, + crate::object_list::Constructor { + desktop, + signature: Some(signature), + }, + vec![desktop], + ), + )?; + } + } + } for name in [ "open", "text", diff --git a/vendor/aster b/vendor/aster index 100bf63..c96dce1 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit 100bf637f944d1031b10f4fa7c7784a72fb93004 +Subproject commit c96dce118b30ce3b66ffe3f809a89f20f05883f5