diff --git a/README.md b/README.md index 67286d3..3562996 100644 --- a/README.md +++ b/README.md @@ -194,7 +194,7 @@ Saved detached Mounts expose `mounted = false`, cleared parent/child/sibling lin Native visual methods are now available on Block: `measure(mount, Constraints(minWidth, minHeight, maxWidth, maxHeight))`, `arrange(mount, Bounds(x, y, width, height))`, `paint(mount, Bounds(...))` and `hitTest(mount, Point(x, y))`. The Mount must be live and belong to that exact Block occurrence. These query methods return managed MeasureResult, Arrangement and DisplayList objects, using the renderer's native geometry and painting functions. They do not publish geometry or pixels. Results are readable in Endor: `result.width`, `arrangement.children.at(0).x`, `drawing.commands.at(0).color`; indexed ObjectList results provide count, first and at(index), with traced references. Arrangement child bounds also carry their stable slot. Paint returns only that object's own commands; descendants are separate occurrences. -Outside a renderer layout call, native measurement queries find intrinsic native subtree size and clamp it to the given constraints. During layout, native base methods use the staged measured children of that occurrence. Native Row/Column arrangement uses child sizes, padding and gaps; it does not stretch children to fill the supplied bounds. Hit testing uses local coordinates against the current Mount dimensions. Coordinates/dimensions must be finite and remain within the native layout limit. Width/height and constraint ranges cannot be negative or inverted. The value constructors preserve fields as ordinary objects; methods validate their contents when used, and global annotation type checking remains pending. +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. @@ -212,6 +212,10 @@ The target's managed content owns its bindings; each binding traces the actual c One Block can have up to 128 active bindings. Each computation has 100000 instructions/128 frames, and a refresh rejects after 10000 computations if dependencies do not stabilize; it reports an error and preserves the published picture instead of silently truncating propagation. A live binding-computation failure stops that runtime. General type/effect checking remains pending. See [property-bindings.endor](examples/property-bindings.endor) for actual Endor source. +Declared fields now use the same runtime type-check switch as source functions, enabled in Tessera. Ordinary and native subclass constructors validate field arguments before allocating/opening native objects. Subsequent source assignments, native set_attr calls and binding writes check the actual declaring field before changing its storage; an error preserves that field's old value. Declared fields cannot be deleted while checks are enabled. Inherited fields use their declaring ancestor and environment. The declaring class name means that actual definition, so REPL redefinition preserves old self-type fields; other names resolve dynamically from the declaration's globals/builtins. Shared Block forwarding selects the current content's type and storage. See [field-contracts.endor](examples/field-contracts.endor). + +These are checks at construction/write boundaries. Enabling does not scan old objects, and changing a referenced object's shared content does not revalidate every field that refers to it. Trusted hosts still own low-level payload/storage/attach operations. Complete initialization, local/captured type-name resolution, override variance, static and effect typing remain pending. + `invalidate("paint")` requests a frame while retaining measurement caches; `invalidate("layout")` also clears affected intrinsic measurements; `invalidate("content")` also invalidates derived content and ancestor dependencies. The default reason is layout. Requests coalesce at the refresh boundary, cover all aliases/occurrences of the same current content and preserve Mount identities. Hidden objects do not force visible frames. See [visual-protocols.endor](examples/visual-protocols.endor). Source measure/arrange overrides now participate in actual layout with structural Mount contexts available before first measurement. Source paint and hitTest also run in the frame/input pipeline. Full parameter/return type and effect contracts, more precise context dependencies and general container constraint negotiation remain future work. A source subclass can override `measure(self, mount, constraints): MeasureResult` and `arrange(self, mount, geometry): Arrangement`. The persistent renderer creates stable Mount identities and parent/child/sibling links before measuring. Measurement proceeds bottom-up with the current logical viewport as the Page constraints (headless callers default to 0..1000000); native parents and explicit native base calls use the current occurrence's measured child sizes, including source overrides. Arrangement proceeds top-down; each child Bounds must be assigned exactly once using its stable slot, with nominal result types and finite geometry checked. Source arrangements can resize or move children; omission, duplicate/foreign slots and invalid geometry reject the frame. See [source-layout.endor](examples/source-layout.endor). @@ -400,8 +404,8 @@ mismatches reject before the body; a bad return does not roll back completed wri The per-call return definition remains rooted until success/error cleanup. See [function-types.endor](examples/function-types.endor) for actual Endor source. -This adds no static inference, field-write checks, override variance, generics, -effect typing or common native-signature metadata. Native APIs continue to validate +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 their arguments and results at their own boundaries. diff --git a/examples/field-contracts.endor b/examples/field-contracts.endor new file mode 100644 index 0000000..d841082 --- /dev/null +++ b/examples/field-contracts.endor @@ -0,0 +1,16 @@ +class CounterText: TextBlock { + value: Number + function change(self: CounterText, event: Event): Unit { + self.value = 10 + } +} +class Model { + target: Block +} +counter = CounterText("共享的原生子类对象", 9) +model = Model(counter) +button = Button("把 Number 字段改成 10") +connection = button.on("click", counter.change) +page = Page() +page.title = "字段类型契约" +page.render(Column(24, 16, counter, ui.textOf(counter, "value"), button, TextBlock("GUI 和源码写入同一个受检查的字段"))) diff --git a/src/README.md b/src/README.md index 4164cc2..4d38d45 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 annotation checks, tab registry, stable-slot insertion, source-dispatched tab reorder/drop, 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, 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 | | 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 | @@ -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 annotation/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, 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, diff --git a/src/api.rs b/src/api.rs index 20bb9fe..8ea5c08 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1077,7 +1077,7 @@ expose actual type relations. Types, bases, instances and native constructors li in the same GC graph. Ordinary source classes support `class Child: Base`, typed field declarations, explicit first `self` parameters, positional field construction and member assignment. Inherited methods bind the actual receiver; overridden methods -are dynamically selected through self. Concrete native visual subclasses reuse real native allocators; abstract bases remain unconstructible. Explicit traits and source parameter/return annotation checks are enabled; field-write constraints and static/effect typing remain pending. Native Block/Page methods use the same type method tables and binding path. +are dynamically selected through self. Concrete native visual subclasses reuse real native allocators; abstract bases remain unconstructible. Explicit traits and source parameter/return annotation checks are enabled; declared-field construction/write checks are enabled alongside source function checks; complete initialization and static/effect typing remain pending. Native Block/Page methods use the same type method tables and binding path. Window is a host-provided managed resource: ui.window(), page.window(), page.open(window), window.pages()/id()/viewport(), resize(width,height), moveTo(x,y), setTitle(text) and focus(). Requests project to their actual native window only after successful input/candidate completion and carry the current runtime session. Resize is asynchronous and the reported viewport is authoritative; this host accepts 1..4096 logical dimensions with a native 720x480 minimum. Failed input/candidates discard pending requests and read-only rendering rejects window effects. Open Pages appear in native tab chrome, with page.title, click activation/close, Ctrl+Tab cycling and Cmd/Ctrl+W close when page keyboard focus is active. Overflow arrows reach additional pages. These operations call actual Page methods in the same VM; tab IDs are weak runtime projections and add no GC roots. The 36-logical-pixel bar reduces Page constraint height; window/ui viewport reports the full inner size and native pointer positions are translated into content coordinates. Window() now creates additional native windows in the same VM, up to 16 open resources. Page.open(window)/moveToWindow(window) preserve Page and business identity while replacing Mounts; detachToWindow() creates and returns a new Window. Dragging a tab away from its strip invokes the same method. Window.close()/secondary OS close remove Page roots, unmount, and retire the resource context; retained Pages can reopen in another live window, and closed Window resources reject viewport/resize/title/focus operations. Closing the primary OS shell exits the application. Secondary viewport inputs and frame publication use the same worker. Secondary close after callback/rendering failure uses host-only teardown without invoking source callbacks or resuming execution. After reset/discard, closing an old picture never touches a fresh VM resource with the same number; viewport inputs are also generation-scoped. A teardown failure discards the affected VM and disables remaining pictures. Native initialization/surface errors are reported rather than panicking; failed secondary creation leaves a managed resource closable from Console. Native tab reordering, existing-window drops and release-point placement use the managed methods described below. Full application-exit notifications remain pending. @@ -1093,9 +1093,11 @@ Native wheel POST /events uses kind scroll with the normal window/session/layout ui.after(owner,key,milliseconds,callback) returns Task. The zero-argument callback runs on the owning VM worker after at least the integer 0..86400000 ms delay and must return Unit. Idle polling can add up to 100 ms; execution load may delay delivery further. Task.cancel/active/status expose cancellation, eligibility and pending/running/completed/cancelled/failed state. One owner/key replaces the prior pending task. Owner scopes and callback captures are managed strong edges; scheduler and owner links are weak. ui is an application owner. Hidden live objects continue; Page close cancels its and its Mount tasks, even close/reopen within one input. Page movement preserves Page tasks but replaces Mounts. Window close cancels its Pages/tasks; reset/DELETE/program replacement discard old scheduler/VM and generation checks reject stale publication. Failed PUT preserves old tasks. Callback failure stops the domain and cancels remaining tasks; earlier writes do not roll back. Read-only rendering cannot schedule/cancel. Limits: 64 pending per owner, 1024 per runtime, 64 delivered per poll, 128 frames/100000 instructions per callback. Providers currently support timers; network/file providers and await are pending. -Source function parameter annotations are checked before the body and return annotations before returning. Object accepts any live value; Unit accepts nil; Number, String/Text and Bool match scalar kinds. Function includes source/native functions and bound methods, while callable class definitions remain Type. View is a compatibility alias for Block. Other names resolve actual Type/Trait objects in the function's globals then captured builtins at each call. The method's own class uses the receiver's actual owning definition, preserving old bound methods after REPL redefinition. Other type names are not frozen at definition. UnknownAnnotation and TypeMismatch report failures; bad returns do not roll back earlier writes. No static inference, field-write validation, override variance, generic or effect typing is provided. +Source function parameter annotations are checked before the body and return annotations before returning. Object accepts any live value; Unit accepts nil; Number, String/Text and Bool match scalar kinds. Function includes source/native functions and bound methods, while callable class definitions remain Type. View is a compatibility alias for Block. Other names resolve actual Type/Trait objects in the function's globals then captured builtins at each call. The method's own class uses the receiver's actual owning definition, preserving old bound methods after REPL redefinition. Other type names are not frozen at definition. UnknownAnnotation and TypeMismatch report failures; bad returns do not roll back earlier writes. Declared-field construction and set_attr writes are also checked, as described below. Static inference, override variance, generic and effect typing remain pending. -Trait definitions Visual, EventTarget, Children and Presentable are managed nominal capabilities. ui.implement(type,capability) explicitly declares an implementation after required-method/positional-arity checks; ui.implements(type,capability) and ui.supports(value,capability) query it. Block declares Visual/EventTarget; ContainerBlock declares Children, inherited by Page. Same-name methods alone never declare an implementation. Source subclass construction and host method replacement validate inherited/affected descendant contracts. Native callable signatures are trusted; source parameter/return annotations are checked at invocation. Native signature metadata, field-write and effect checks and formal trait syntax remain pending. EventTarget requires canonical on/dispatch/onEvent arities 3/2/1 after self; native optional convenience forms remain. +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. 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 1943de9..60d3423 100644 --- a/src/endor_host.rs +++ b/src/endor_host.rs @@ -993,6 +993,106 @@ mod tests { const EXAMPLE: &str = include_str!("../examples/hello.endor"); const PAGE: &str = include_str!("../examples/page.endor"); + #[test] + fn checked_fields_reject_native_constructor_side_effects_and_preserve_live_values() { + let (mut session, _) = ReplSession::load( + include_str!("../examples/field-contracts.endor"), + "app.main", + 1, + 210, + ) + .unwrap(); + for invalid in [ + r#"counter.value = "wrong""#, + r#"CounterText("bad", "wrong")"#, + "Model(42)", + ] { + let error = session.execute(invalid, "app.main").err().unwrap(); + assert!(error.to_string().contains("field"), "{error:#}"); + assert!( + session.documents[&crate::window::MAIN_WINDOW] + .frame + .fault + .is_none() + ); + } + assert_eq!( + session.execute("counter.value", "app.main").unwrap().value, + "9" + ); + session + .execute("class CheckedPage: Page { count: Number }", "app.main") + .unwrap(); + let pages = session + .execute("ui.window().pages().count", "app.main") + .unwrap() + .value; + assert!( + session + .execute(r#"CheckedPage("wrong")"#, "app.main") + .is_err() + ); + assert_eq!( + session + .execute("ui.window().pages().count", "app.main") + .unwrap() + .value, + pages + ); + let updated = session + .execute("button.click()", "app.main") + .unwrap() + .document + .unwrap(); + assert!( + updated.frame.commands.iter().any( + |command| matches!(command, RenderCommand::Text { value, .. } if value == "10") + ) + ); + assert_eq!( + session.execute("counter.value", "app.main").unwrap().value, + "10" + ); + } + + #[test] + fn checked_fields_follow_shared_block_forwarding_and_binding_writes() { + let (mut session, _) = ReplSession::load( + r#" +class Numeric: TextBlock { value: Number } +class Textual: TextBlock { value: String } +block = Numeric("old", 9) +alias = block +page = Page() +page.render(block) +"#, + "app.main", + 1, + 211, + ) + .unwrap(); + session + .execute(r#"block = Textual("new", "kept")"#, "app.main") + .unwrap(); + assert!(session.execute("alias.value = 42", "app.main").is_err()); + assert_eq!( + session.execute("alias.value", "app.main").unwrap().value, + r#""kept""# + ); + session + .execute(r#"alias.value = "updated""#, "app.main") + .unwrap(); + assert_eq!( + session.execute("block.value", "app.main").unwrap().value, + r#""updated""# + ); + assert!( + session + .execute("alias.bind(\"value\", ui.viewport)", "app.main") + .is_err() + ); + } + #[test] fn positional_insert_preserves_existing_slots_and_mounts_and_rejects_invalid_graphs() { let source = r#"head=TextBlock("head") diff --git a/src/ui_bridge.rs b/src/ui_bridge.rs index 5d22a28..1b7f11d 100644 --- a/src/ui_bridge.rs +++ b/src/ui_bridge.rs @@ -345,6 +345,8 @@ impl NativeCallable for NativeFactory { .len() .checked_sub(fields.len()) .ok_or(invalid("missing subclass field arguments"))?; + cx.store() + .check_class_field_arguments(requested, &values[native_count..])?; let result = Function { operation: self.operation, owner: None, diff --git a/vendor/aster b/vendor/aster index 6346041..20e29e3 160000 --- a/vendor/aster +++ b/vendor/aster @@ -1 +1 @@ -Subproject commit 6346041f779029a3279bc11492b8ccaeb5825734 +Subproject commit 20e29e3c5a4c014a3e67aece65eb1c133a7794ec