From 64bf7470479538a73fcf05de7a64935a623622a2 Mon Sep 17 00:00:00 2001 From: Sprite Date: Tue, 24 Nov 2026 22:23:03 +0000 Subject: [PATCH] M3 app model: App, Entity, Context, subscriptions, events, globals - app: port of GPUI's App effect cycle (update / flush_effects with deferred subscription activation and notification dedup), EntityMap (typed cells, leasing, explicit release), Context (notify, emit, observe, subscribe, observe_self/subscribe_self, on_release, observe_release, observe_global, defer_call), SubscriberSet and Subscription. - TypeId-keyed maps become EventKey[E] / GlobalKey[G]: values cross the app's untyped maps as closures writing into the key's typed slot. - No Drop: App::release replaces the last-handle drop; subscriptions end with unsubscribe() or when their entity is released. - Fail loudly on re-entrant updates, reads during updates, use after release, cross-app use, missing globals, global_mut outside an update. - Tests: GPUI's subscription tests ported, plus app-model and panic tests. - examples/counter; PORTING.md M3 status, deviations, toolchain notes. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 + docs/PORTING.md | 61 ++- src/app/app.mbt | 484 ++++++++++++++++++++++++ src/app/app_test.mbt | 461 ++++++++++++++++++++++ src/app/context.mbt | 199 ++++++++++ src/app/entity.mbt | 152 ++++++++ src/app/keys.mbt | 81 ++++ src/app/moon.pkg | 4 + src/app/pkg.generated.mbti | 113 ++++++ src/app/subscription.mbt | 179 +++++++++ src/app/subscription_wbtest.mbt | 98 +++++ src/examples/counter/main.mbt | 77 ++++ src/examples/counter/main_wbtest.mbt | 13 + src/examples/counter/moon.pkg | 5 + src/examples/counter/pkg.generated.mbti | 17 + 15 files changed, 1940 insertions(+), 8 deletions(-) create mode 100644 src/app/app.mbt create mode 100644 src/app/app_test.mbt create mode 100644 src/app/context.mbt create mode 100644 src/app/entity.mbt create mode 100644 src/app/keys.mbt create mode 100644 src/app/moon.pkg create mode 100644 src/app/pkg.generated.mbti create mode 100644 src/app/subscription.mbt create mode 100644 src/app/subscription_wbtest.mbt create mode 100644 src/examples/counter/main.mbt create mode 100644 src/examples/counter/main_wbtest.mbt create mode 100644 src/examples/counter/moon.pkg create mode 100644 src/examples/counter/pkg.generated.mbti diff --git a/README.md b/README.md index ea56089..bc2f6a1 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,7 @@ roadmap. | `experiments/gpui/scene` | `scene.rs`, `bounds_tree.rs` | Ported (primitives, draw ordering, layers, batching, replay) | | `experiments/gpui/font` | font descriptors in `text_system.rs` | Ported (`Font`, weights, styles, features, fallbacks) | | `experiments/gpui/style` | `style.rs`, `styled.rs`, Refineable, gpui_macros style helpers | Ported (`Style`/`StyleRefinement`, the full `Styled` fluent API) | +| `experiments/gpui/app` | `app.rs`, `entity_map.rs`, `context.rs`, `subscription.rs` | Ported (entities, contexts, notify/observe, typed events and globals, effect flushing) | | `experiments/gpui/layout` | `taffy.rs` | Ported on [`Milky2018/chicle`](https://mooncakes.io/docs/Milky2018/chicle) (flexbox, grid, block) | ## Example @@ -37,6 +38,9 @@ moon run src/examples/card --target js .text_color(@color.rgb(0x1f2328)).text_sm() ``` +`src/examples/counter` shows the app model: two entities talking through +notifications, a typed event and a global (`moon run src/examples/counter --target js`). + The first example that renders in the browser comes with milestone M8; see the roadmap. diff --git a/docs/PORTING.md b/docs/PORTING.md index bd4cfca..3189f9e 100644 --- a/docs/PORTING.md +++ b/docs/PORTING.md @@ -135,7 +135,7 @@ stays isolated. | `layout` | `taffy.rs` (engine on `Milky2018/chicle`, a taffy port) | pure | **done** (no cross-frame node cache yet) | | `keymap` | `keymap.rs`, `keymap/*`, `platform/keystroke.rs` | pure | planned | | `action` | `action.rs` | pure | planned | -| `app` | `app.rs`, `app/*`, `subscription.rs`, `global.rs`, `gpui.rs` traits | pure | planned | +| `app` | `app.rs`, `app/entity_map.rs`, `app/context.rs`, `subscription.rs`, `global.rs` | pure | **done** (no windows, executors or actions yet) | | `executor` | `executor.rs`, `platform_scheduler.rs`, `scheduler` crate | pure core + platform hooks | planned | | `element` | `element.rs`, `view.rs`, `elements/div.rs`, `interactive.rs` | pure | planned | | `window` | `window.rs`, `key_dispatch.rs`, `tab_stop.rs` | pure (talks to platform traits) | planned | @@ -352,13 +352,15 @@ gantt - Tests: GPUI's rounding and stroke-snapping tests, plus layout scenarios. The engine is checked separately by the 1,038-fixture conformance suite in `conformance/chicle`. -- **M3: app model.** - - `App`, `Entity[T]`/`WeakEntity[T]`, and `Context[T]`. - - `notify`, `observe`, `subscribe`/`emit` with typed event keys, globals, - and observers. - - The effect queue and `flush_effects` semantics: deferral, and dedup of - notifications. - - Tests ported from GPUI's `app` tests. +- **M3: app model (done).** + - `App`, `Entity[T]`/`WeakEntity[T]`/`Reservation[T]`, and `Context[T]`. + - `notify`, `observe`, `subscribe`/`emit` with typed `EventKey`s, + globals with `GlobalKey`s, release listeners, and `defer_call`. + - The effect queue and `flush_effects` semantics: deferred activation of + new subscriptions, dedup of notifications, and cascading effects. + - Tests: GPUI's subscription tests are ported, plus app-model tests, + including the aborts expected on misuse. + - `src/examples/counter` shows the model end to end. - **M4: executor.** - Foreground executor, timers, and `Task[T]` (cancel and detach). - `TestScheduler` with a virtual clock and `run_until_parked`. @@ -460,6 +462,43 @@ gantt `parent`/`children` queries. Misuse fails loudly: an unknown or stale `LayoutId`, or a child given two parents, aborts. +### Deviations taken in M3 (app model) +- **Type keys replace `TypeId`.** Events and globals are identified by + `EventKey[E]` and `GlobalKey[G]` values, created once per type (usually a + top-level `let`). The app stores values under the key's id as closures + that write into the key's typed slot. Reading one back through the same + key is type-safe and needs no downcast. + - `EventEmitter` (a compile-time check that `T` may emit `E`) has no + equivalent: any entity may emit any `EventKey`. +- **Entities are not reference counted.** A handle points at a typed cell. + `App::release(entity)` plays the role of the last handle being dropped: + - Weak handles stop upgrading at once. + - At the next flush, observers and subscriptions are removed and release + listeners run. + - Double release is a no-op. + - Use after release, re-entrant updates, reads during an update, and using + an entity with another `App` all abort, as GPUI panics. +- **Subscriptions do not end when dropped.** A `Subscription` stays active + until `unsubscribe()` is called, or until the entity it belongs to is + released. GPUI unsubscribes on drop; `detach()` is kept for parity. +- **Entity state is passed by reference.** Update callbacks receive the + state; entity types should be structs with `mut` fields (GPUI's `&mut T`). +- **Renames.** + - Entity creation is `App::new_entity`, because `App::new` creates the app. + - `cx.defer` is `defer_call`, because `defer` is a MoonBit keyword. + - `Context` does not deref to `App`; use `cx.app`. +- **Top-level `App` methods open an update.** Methods such as `notify`, + `set_global`, `release` and `defer_call` flush their effects when called + outside an update. + - `global_mut` and `default_global` return the global to be mutated, so + they must be called inside `App::update`; outside one they abort. +- **Not yet ported:** + - `observe_new` (needs a per-type key for entities). + - Accessed-entity tracking and window invalidation (M6). + - `spawn` and `AsyncApp` (M4). + - Actions (M5). + - Leak detection. + ## 7. Design decisions Decided on 2026-11-24, following the recommendations below. @@ -497,4 +536,10 @@ Decided on 2026-11-24, following the recommendations below. Always run `python3 tools/gen_style.py && moon fmt` together. - A value converts implicitly to a trait object (`&IntoLength`) at a call site. That is how GPUI's `impl Into` parameters are expressed. +- `defer` is a keyword (GPUI's `cx.defer` became `defer_call`). +- Closures are not allowed to raise implicitly: `assert_*` cannot be called + inside a callback in a test. Record values and assert afterwards. A test + whose name starts with `panic` passes only if it aborts; use this to test + the fail-loudly paths. +- `Ref(x)` builds a `Ref`; `{ val: x }` needs a type annotation. - Test-only imports go in `import { ... } for "test"` in `moon.pkg`. diff --git a/src/app/app.mbt b/src/app/app.mbt new file mode 100644 index 0000000..edf7a2a --- /dev/null +++ b/src/app/app.mbt @@ -0,0 +1,484 @@ +// The application state and effect cycle, ported from gpui/src/app.rs. +// +// All state lives in entities owned by the `App`. Updates run inside +// `App::update`; side effects (notifications, events, global changes, +// deferred callbacks, releases) are queued and flushed when the outermost +// update returns, exactly like GPUI's `flush_effects`. +// +// Not ported yet: windows and view invalidation (M6), executors and `spawn` +// (M4), actions and keymaps (M5), `observe_new` (needs a per-type key for +// entities), and the platform services. + +///| +let next_app_id : Ref[Int32] = { val: 0, } + +///| +priv enum Effect { + Notify(EntityId) + Emit(emitter~ : EntityId, event_key~ : Int32, payload~ : () -> Unit) + NotifyGlobalObservers(Int32) + Defer((App) -> Unit) +} + +///| +/// A typed event listener stored without its type: `handler` reads the +/// payload back through the listener's own `EventKey`. +priv struct EventListener { + event_key : Int32 + handler : (() -> Unit, App) -> Bool +} + +///| +priv struct EntityRecord { + /// Drops the state once release listeners have run. + free : () -> Unit +} + +///| +/// The application: owner of all entities and globals (GPUI: `App`). +pub struct App { + priv id : Int32 + priv mut next_entity_id : Int32 + priv entities : Map[EntityId, EntityRecord] + priv mut pending_updates : Int32 + priv mut flushing_effects : Bool + priv pending_effects : @deque.Deque[Effect] + priv pending_notifications : @hashset.HashSet[EntityId] + priv pending_global_notifications : @hashset.HashSet[Int32] + priv dropped_entities : Array[EntityId] + priv observers : SubscriberSet[EntityId, (App) -> Bool] + priv event_listeners : SubscriberSet[EntityId, EventListener] + priv release_listeners : SubscriberSet[EntityId, (App) -> Unit] + priv global_observers : SubscriberSet[Int32, (App) -> Bool] + priv globals : Map[Int32, () -> Unit] +} + +///| +/// A new, empty application. GPUI creates its `App` through `Application` +/// with a platform; there is no platform layer yet (M7/M8). +pub fn App::new() -> App { + let id = next_app_id.val + next_app_id.val = id + 1 + { + id, + next_entity_id: 1, + entities: {}, + pending_updates: 0, + flushing_effects: false, + pending_effects: @deque.Deque([]), + pending_notifications: @hashset.HashSet([]), + pending_global_notifications: @hashset.HashSet([]), + dropped_entities: [], + observers: SubscriberSet::new(), + event_listeners: SubscriberSet::new(), + release_listeners: SubscriberSet::new(), + global_observers: SubscriberSet::new(), + globals: {}, + } +} + +///| +/// Runs `f`; queued effects are flushed when the outermost update returns. +pub fn[R] App::update(self : App, f : (App) -> R) -> R { + self.pending_updates = self.pending_updates + 1 + let result = f(self) + if self.pending_updates == 1 && !self.flushing_effects { + self.flush_effects() + } + self.pending_updates = self.pending_updates - 1 + result +} + +///| +fn App::push_effect(self : App, effect : Effect) -> Unit { + match effect { + Notify(emitter) => + if !self.pending_notifications.add_and_check(emitter) { + return + } + NotifyGlobalObservers(key) => + if !self.pending_global_notifications.add_and_check(key) { + return + } + _ => () + } + self.pending_effects.push_back(effect) +} + +///| +/// Applies queued effects until none remain (GPUI: `flush_effects`). +fn App::flush_effects(self : App) -> Unit { + self.flushing_effects = true + while true { + self.release_dropped_entities() + match self.pending_effects.pop_front() { + Some(Notify(emitter)) => { + self.pending_notifications.remove(emitter) + self.observers.retain(emitter, fn(handler) { handler(self) }) + } + Some(Emit(emitter~, event_key~, payload~)) => + self.event_listeners.retain(emitter, fn(listener) { + if listener.event_key == event_key { + (listener.handler)(payload, self) + } else { + true + } + }) + Some(NotifyGlobalObservers(key)) => { + self.pending_global_notifications.remove(key) + self.global_observers.retain(key, fn(observer) { observer(self) }) + } + Some(Defer(callback)) => callback(self) + None => if self.dropped_entities.is_empty() { break } + } + } + self.flushing_effects = false +} + +///| +/// Removes released entities' observers and subscriptions, then runs their +/// release listeners (GPUI: `release_dropped_entities`). +fn App::release_dropped_entities(self : App) -> Unit { + while !self.dropped_entities.is_empty() { + let dropped = self.dropped_entities.copy() + self.dropped_entities.clear() + for entity_id in dropped { + ignore(self.observers.remove(entity_id)) + ignore(self.event_listeners.remove(entity_id)) + for callback in self.release_listeners.remove(entity_id) { + callback(self) + } + if self.entities.get(entity_id) is Some(record) { + (record.free)() + self.entities.remove(entity_id) + } + } + } +} + +///| +/// Queues `f` to run after the current effects (GPUI: `App::defer`; +/// renamed because `defer` is a MoonBit keyword). +pub fn App::defer_call(self : App, f : (App) -> Unit) -> Unit { + self.update(fn(app) { app.push_effect(Defer(f)) }) +} + +// --------------------------------------------------------------------------- +// Entities +// --------------------------------------------------------------------------- + +///| +/// Hands out an id for an entity whose state is created later with +/// `insert_entity` (GPUI: `reserve_entity`). +pub fn[T] App::reserve_entity(self : App) -> Reservation[T] { + let id = EntityId(self.next_entity_id) + self.next_entity_id = self.next_entity_id + 1 + { + cell: { app_id: self.id, id, value: None, leased: false, released: false, }, + } +} + +///| +/// Builds the state of a reserved entity (GPUI: `insert_entity`). +pub fn[T] App::insert_entity( + self : App, + reservation : Reservation[T], + build : (Context[T]) -> T, +) -> Entity[T] { + let cell = reservation.cell + cell.check_app(self, "insert") + guard cell.value is None && !self.entities.contains(cell.id) else { + abort("cannot insert \{cell.id}: the reservation was already used") + } + self.update(fn(app) { + let value = build({ app, weak: { cell, }, }) + cell.value = Some(value) + app.entities[cell.id] = { free: fn() { cell.value = None }, } + { cell, } + }) +} + +///| +/// Creates an entity whose state is built by `build` (GPUI: `App::new`; +/// renamed because `App::new` is the app's constructor here). +pub fn[T] App::new_entity(self : App, build : (Context[T]) -> T) -> Entity[T] { + self.insert_entity(self.reserve_entity(), build) +} + +///| +/// Updates an entity's state; effects flush afterwards +/// (GPUI: `update_entity`). Fails loudly if the entity is already being +/// updated or has been released. +pub fn[T, R] App::update_entity( + self : App, + entity : Entity[T], + f : (T, Context[T]) -> R, +) -> R { + let cell = entity.cell + cell.check_app(self, "update") + self.update(fn(app) { + let value = cell.lease("update") + let result = f(value, { app, weak: { cell, }, }) + cell.end_lease() + result + }) +} + +///| +/// Reads an entity's state (GPUI: `read_entity`). The state must not be +/// mutated through the returned value. +pub fn[T] App::read_entity(self : App, entity : Entity[T]) -> T { + entity.cell.check_app(self, "read") + entity.cell.read() +} + +///| +/// Releases an entity: its observers and subscriptions are removed and its +/// release listeners run during the next effect flush. Weak handles stop +/// upgrading immediately. Releasing twice is a no-op. +pub fn[T] App::release(self : App, entity : Entity[T]) -> Unit { + let cell = entity.cell + cell.check_app(self, "release") + guard !cell.released else { return } + guard !cell.leased else { + abort("cannot release \{cell.id} while it is being updated") + } + cell.released = true + self.update(fn(app) { app.dropped_entities.push(cell.id) }) +} + +///| +/// Number of live (inserted, not yet released) entities. +pub fn App::entity_count(self : App) -> Int32 { + self.entities.length() +} + +///| +/// Marks an entity as changed: its observers run during the next flush +/// (GPUI: `App::notify`). Repeated notifications before the flush coalesce. +pub fn App::notify(self : App, entity_id : EntityId) -> Unit { + self.update(fn(app) { app.push_effect(Notify(entity_id)) }) +} + +///| +fn[T] App::emit_event( + self : App, + emitter : EntityId, + key : EventKey[T], + event : T, +) -> Unit { + self.update(fn(app) { + app.push_effect(Emit(emitter~, event_key=key.id, payload=key.erase(event))) + }) +} + +///| +fn App::new_observer( + self : App, + entity_id : EntityId, + handler : (App) -> Bool, +) -> Subscription { + let (subscription, activate) = self.observers.insert_pending( + entity_id, handler, + ) + // New observers start after the effects already queued (GPUI semantics). + self.defer_call(fn(_) { activate() }) + subscription +} + +///| +fn[T] App::observe_internal( + self : App, + entity : Entity[T], + on_notify : (Entity[T], App) -> Bool, +) -> Subscription { + let weak = entity.downgrade() + self.new_observer(entity.entity_id(), fn(app) { + match weak.upgrade() { + Some(entity) => on_notify(entity, app) + None => false + } + }) +} + +///| +/// Calls `on_notify` whenever `entity` is notified. +pub fn[T] App::observe( + self : App, + entity : Entity[T], + on_notify : (Entity[T], App) -> Unit, +) -> Subscription { + self.observe_internal(entity, fn(entity, app) { + on_notify(entity, app) + true + }) +} + +///| +fn[T, E] App::subscribe_internal( + self : App, + entity : Entity[T], + key : EventKey[E], + on_event : (Entity[T], E, App) -> Bool, +) -> Subscription { + let weak = entity.downgrade() + let listener : EventListener = { + event_key: key.id, + handler: fn(payload, app) { + let event = key.unerase(payload) + match weak.upgrade() { + Some(entity) => on_event(entity, event, app) + None => false + } + }, + } + let (subscription, activate) = self.event_listeners.insert_pending( + entity.entity_id(), + listener, + ) + self.defer_call(fn(_) { activate() }) + subscription +} + +///| +/// Calls `on_event` for every event of kind `key` that `entity` emits. +pub fn[T, E] App::subscribe( + self : App, + entity : Entity[T], + key : EventKey[E], + on_event : (Entity[T], E, App) -> Unit, +) -> Subscription { + self.subscribe_internal(entity, key, fn(entity, event, app) { + on_event(entity, event, app) + true + }) +} + +///| +/// Calls `on_release` with the entity's state when it is released +/// (GPUI: `observe_release`). +pub fn[T] App::observe_release( + self : App, + entity : Entity[T], + on_release : (T, App) -> Unit, +) -> Subscription { + let cell = entity.cell + self.release_listeners.insert(cell.id, fn(app) { + guard cell.value is Some(value) else { return } + on_release(value, app) + }) +} + +// --------------------------------------------------------------------------- +// Globals +// --------------------------------------------------------------------------- + +///| +pub fn[G] App::has_global(self : App, key : GlobalKey[G]) -> Bool { + self.globals.contains(key.id) +} + +///| +/// The global for `key`; fails loudly if it is not set (GPUI: `global`). +pub fn[G] App::global(self : App, key : GlobalKey[G]) -> G { + match self.globals.get(key.id) { + Some(erased) => key.unerase(erased) + None => abort("no global of type \{key.name} exists") + } +} + +///| +pub fn[G] App::try_global(self : App, key : GlobalKey[G]) -> G? { + match self.globals.get(key.id) { + Some(erased) => Some(key.unerase(erased)) + None => None + } +} + +///| +/// The global for `key`, to be mutated by the caller; its observers run when +/// the enclosing update finishes (GPUI: `global_mut`). Must be called inside +/// `App::update` (or an entity update), so that the mutation happens before +/// observers run; fails loudly otherwise. +pub fn[G] App::global_mut(self : App, key : GlobalKey[G]) -> G { + guard self.pending_updates > 0 else { + abort( + "global_mut(\{key.name}) must be called inside App::update; use update_global or set_global outside", + ) + } + let value = self.global(key) + self.push_effect(NotifyGlobalObservers(key.id)) + value +} + +///| +/// The global for `key`, created with `init` if missing (GPUI: +/// `default_global`). Like `global_mut`, must be called inside an update. +pub fn[G] App::default_global( + self : App, + key : GlobalKey[G], + init : () -> G, +) -> G { + if !self.has_global(key) { + self.globals[key.id] = key.erase(init()) + } + self.global_mut(key) +} + +///| +/// Sets the global for `key` and notifies its observers. +pub fn[G] App::set_global(self : App, key : GlobalKey[G], value : G) -> Unit { + self.update(fn(app) { + app.push_effect(NotifyGlobalObservers(key.id)) + app.globals[key.id] = key.erase(value) + }) +} + +///| +/// Removes and returns the global for `key`; fails loudly if missing. +pub fn[G] App::remove_global(self : App, key : GlobalKey[G]) -> G { + let value = self.global(key) + self.update(fn(app) { + app.push_effect(NotifyGlobalObservers(key.id)) + app.globals.remove(key.id) + }) + value +} + +///| +/// Updates the global for `key` (GPUI: `update_global`). The global is +/// leased: reading it inside `f` fails loudly, as in GPUI. +pub fn[G, R] App::update_global( + self : App, + key : GlobalKey[G], + f : (G, App) -> R, +) -> R { + self.update(fn(app) { + guard app.globals.get(key.id) is Some(erased) else { + abort("no global of type \{key.name} exists") + } + let value = key.unerase(erased) + app.globals.remove(key.id) + let result = f(value, app) + app.globals[key.id] = key.erase(value) + app.push_effect(NotifyGlobalObservers(key.id)) + result + }) +} + +///| +/// Calls `f` whenever the global for `key` changes. +pub fn[G] App::observe_global( + self : App, + key : GlobalKey[G], + f : (App) -> Unit, +) -> Subscription { + let (subscription, activate) = self.global_observers.insert_pending(key.id, fn( + app, + ) { + f(app) + true + }) + self.defer_call(fn(_) { activate() }) + subscription +} diff --git a/src/app/app_test.mbt b/src/app/app_test.mbt new file mode 100644 index 0000000..819683b --- /dev/null +++ b/src/app/app_test.mbt @@ -0,0 +1,461 @@ +///| +struct Counter { + mut count : Int32 +} + +///| +struct Log { + entries : Array[String] +} + +///| +let changed : @app.EventKey[Int32] = @app.EventKey::new("Changed") + +///| +let renamed : @app.EventKey[String] = @app.EventKey::new("Renamed") + +///| +struct Settings { + mut theme : String +} + +///| +let settings_key : @app.GlobalKey[Settings] = @app.GlobalKey::new("Settings") + +///| +let marker_key : @app.GlobalKey[Int32] = @app.GlobalKey::new("Marker") + +///| +fn new_counter(app : @app.App, count~ : Int32 = 0) -> @app.Entity[Counter] { + app.new_entity(fn(_) { { count, } }) +} + +///| +test "entities are created, read and updated" { + let app = @app.App::new() + let counter = new_counter(app, count=1) + assert_eq(counter.read(app).count, 1) + let context_ok = Ref(false) + let result = counter.update(app, fn(state, cx) { + state.count += 1 + context_ok.val = cx.entity_id() == counter.entity_id() && + cx.entity() == counter + state.count * 10 + }) + assert_eq(result, 20) + assert_true(context_ok.val) + assert_eq(app.read_entity(counter).count, 2) + assert_eq(app.entity_count(), 1) + let other = new_counter(app) + assert_not_eq(other.entity_id(), counter.entity_id()) + assert_false(other == counter) +} + +///| +test "reserve then insert" { + let app = @app.App::new() + let reservation : @app.Reservation[Counter] = app.reserve_entity() + let id = reservation.entity_id() + let seen_id : Ref[@app.EntityId?] = Ref(None) + let entity = app.insert_entity(reservation, fn(cx) { + seen_id.val = Some(cx.entity_id()) + { count: 7, } + }) + assert_eq(seen_id.val, Some(id)) + assert_eq(entity.entity_id(), id) + assert_eq(entity.read(app).count, 7) +} + +///| +test "observers run after the update and notifications coalesce" { + let app = @app.App::new() + let counter = new_counter(app) + let seen = [] + let during = Ref(-1) + let subscription = app.observe(counter, fn(entity, app) { + seen.push(entity.read(app).count) + }) + counter.update(app, fn(state, cx) { + state.count = 1 + cx.notify() + state.count = 2 + cx.notify() + // Nothing runs until the outermost update returns. + during.val = seen.length() + }) + assert_eq(during.val, 0) + assert_eq(seen, [2]) + subscription.unsubscribe() + counter.update(app, fn(_, cx) { cx.notify() }) + assert_eq(seen, [2]) +} + +///| +test "nested updates flush once at the end" { + let app = @app.App::new() + let counter = new_counter(app) + let seen = [] + app.observe(counter, fn(_, _) { seen.push("notified") }).detach() + let during = Ref(-1) + app.update(fn(app) { + counter.update(app, fn(_, cx) { cx.notify() }) + during.val = seen.length() + counter.update(app, fn(_, cx) { cx.notify() }) + }) + assert_eq(during.val, 0) + assert_eq(seen, ["notified"]) +} + +///| +test "observers registered during an update see effects queued after them" { + let app = @app.App::new() + let counter = new_counter(app) + let seen = [] + app.update(fn(app) { + // Notified before the observer exists: not delivered to it. + app.notify(counter.entity_id()) + app.observe(counter, fn(_, _) { seen.push("first") }).detach() + }) + assert_eq(seen, []) + app.update(fn(app) { + app.observe(counter, fn(_, _) { seen.push("second") }).detach() + // Queued after the observer's activation: delivered. + app.notify(counter.entity_id()) + }) + assert_eq(seen, ["first", "second"]) +} + +///| +test "events are delivered by kind" { + let app = @app.App::new() + let counter = new_counter(app) + let ints = [] + let strings = [] + app.subscribe(counter, changed, fn(_, value, _) { ints.push(value) }).detach() + app + .subscribe(counter, renamed, fn(_, value, _) { strings.push(value) }) + .detach() + counter.update(app, fn(state, cx) { + state.count = 5 + cx.emit(changed, state.count) + cx.emit(renamed, "five") + cx.emit(changed, 6) + }) + assert_eq(ints, [5, 6]) + assert_eq(strings, ["five"]) +} + +///| +test "entities observe and subscribe to each other" { + let app = @app.App::new() + let source = new_counter(app) + let log : @app.Entity[Log] = app.new_entity(fn(cx) { + cx + .observe(source, fn(log, source, cx) { + log.entries.push("notified \{source.read(cx.app).count}") + }) + .detach() + cx + .subscribe(source, changed, fn(log, _, value, _) { + log.entries.push("changed \{value}") + }) + .detach() + { entries: [], } + }) + source.update(app, fn(state, cx) { + state.count = 3 + cx.emit(changed, 3) + cx.notify() + }) + assert_eq(log.read(app).entries, ["changed 3", "notified 3"]) +} + +///| +test "self observation and self subscription" { + let app = @app.App::new() + let counter : @app.Entity[Counter] = app.new_entity(fn(cx) { + cx.observe_self(fn(state, _) { state.count += 100 }).detach() + cx + .subscribe_self(changed, fn(state, value, _) { state.count += value }) + .detach() + { count: 0, } + }) + counter.update(app, fn(_, cx) { + cx.emit(changed, 2) + cx.notify() + }) + assert_eq(counter.read(app).count, 102) +} + +///| +test "observers cascade within one flush" { + let app = @app.App::new() + let a = new_counter(app) + let b = new_counter(app) + let order = [] + app + .observe(a, fn(_, app) { + order.push("a") + b.update(app, fn(_, cx) { cx.notify() }) + }) + .detach() + app.observe(b, fn(_, _) { order.push("b") }).detach() + a.update(app, fn(_, cx) { cx.notify() }) + assert_eq(order, ["a", "b"]) +} + +///| +test "release removes observers, runs release listeners, stops weak handles" { + let app = @app.App::new() + let counter : @app.Entity[Counter] = app.new_entity(fn(cx) { + cx.on_release(fn(state, _) { state.count = -1 }).detach() + { count: 4, } + }) + let released = [] + app + .observe_release(counter, fn(state, _) { released.push(state.count) }) + .detach() + let notified = [] + app.observe(counter, fn(_, _) { notified.push(1) }).detach() + let weak = counter.downgrade() + assert_true(weak.upgrade() is Some(_)) + let upgraded_during = Ref(true) + let released_during = Ref(-1) + app.update(fn(app) { + app.release(counter) + // Weak handles stop upgrading immediately, listeners run at the flush. + upgraded_during.val = weak.upgrade() is Some(_) + released_during.val = released.length() + }) + assert_false(upgraded_during.val) + assert_eq(released_during.val, 0) + // Listeners run in registration order: on_release first. + assert_eq(released, [-1]) + assert_true(counter.is_released()) + assert_eq(app.entity_count(), 0) + assert_eq(weak.update(app, fn(_, _) { 1 }), None) + // Releasing again is a no-op. + app.release(counter) + assert_eq(released, [-1]) +} + +///| +test "observer entities stop observing when released" { + let app = @app.App::new() + let source = new_counter(app) + let seen = [] + let watcher : @app.Entity[Log] = app.new_entity(fn(cx) { + cx.observe(source, fn(_, _, _) { seen.push("seen") }).detach() + { entries: [], } + }) + source.update(app, fn(_, cx) { cx.notify() }) + assert_eq(seen, ["seen"]) + app.release(watcher) + source.update(app, fn(_, cx) { cx.notify() }) + assert_eq(seen, ["seen"]) +} + +///| +test "observe_release between entities" { + let app = @app.App::new() + let child = new_counter(app, count=9) + let parent : @app.Entity[Log] = app.new_entity(fn(cx) { + cx + .observe_release(child, fn(log, child_state, _) { + log.entries.push("child released with \{child_state.count}") + }) + .detach() + { entries: [], } + }) + app.release(child) + assert_eq(parent.read(app).entries, ["child released with 9"]) +} + +///| +test "globals" { + let app = @app.App::new() + assert_false(app.has_global(settings_key)) + assert_true(app.try_global(settings_key) is None) + app.set_global(settings_key, { theme: "light", }) + assert_eq(app.global(settings_key).theme, "light") + let changes = [] + app + .observe_global(settings_key, fn(app) { + changes.push(app.global(settings_key).theme) + }) + .detach() + app.update_global(settings_key, fn(settings, _) { settings.theme = "dark" }) + assert_eq(changes, ["dark"]) + app.update(fn(app) { app.global_mut(settings_key).theme = "solarized" }) + assert_eq(changes, ["dark", "solarized"]) + // Different keys hold different types independently. + app.set_global(marker_key, 42) + assert_eq(app.global(marker_key), 42) + assert_eq( + app.update(fn(app) { app.default_global(marker_key, fn() { 0 }) }), + 42, + ) + let removed = app.remove_global(marker_key) + assert_eq(removed, 42) + assert_false(app.has_global(marker_key)) + assert_eq( + app.update(fn(app) { app.default_global(marker_key, fn() { 7 }) }), + 7, + ) + // Globals are per app. + assert_false(@app.App::new().has_global(settings_key)) +} + +///| +test "entities observe globals until released" { + let app = @app.App::new() + app.set_global(marker_key, 0) + let counter : @app.Entity[Counter] = app.new_entity(fn(cx) { + cx.observe_global(marker_key, fn(state, _) { state.count += 1 }).detach() + { count: 0, } + }) + app.set_global(marker_key, 1) + app.set_global(marker_key, 2) + assert_eq(counter.read(app).count, 2) + let weak = counter.downgrade() + app.release(counter) + app.set_global(marker_key, 3) + assert_true(weak.upgrade() is None) +} + +///| +/// Port of GPUI's `test_unsubscribe_during_callback_with_insert`. +test "unsubscribe during callback with insert" { + let app = @app.App::new() + app.set_global(marker_key, 0) + let a_count = Ref(0) + let b_count = Ref(0) + let sub_a : Ref[@app.Subscription?] = Ref(None) + let sub_b : Ref[@app.Subscription?] = Ref(None) + sub_a.val = Some( + app.observe_global(marker_key, fn(app) { + a_count.val += 1 + sub_a.val.unwrap().unsubscribe() + app.observe_global(marker_key, fn(_) { }).detach() + }), + ) + sub_b.val = Some( + app.observe_global(marker_key, fn(_) { + b_count.val += 1 + sub_b.val.unwrap().unsubscribe() + }), + ) + app.set_global(marker_key, 1) + assert_eq(a_count.val, 1) + assert_eq(b_count.val, 1) + app.set_global(marker_key, 2) + assert_eq(a_count.val, 1) + assert_eq(b_count.val, 1) +} + +///| +/// Port of GPUI's `test_callback_dropped_by_earlier_callback_does_not_fire`. +test "callback unsubscribed by an earlier callback does not fire" { + let app = @app.App::new() + app.set_global(marker_key, 0) + let b_count = Ref(0) + let sub_b : Ref[@app.Subscription?] = Ref(None) + app + .observe_global(marker_key, fn(_) { + if sub_b.val is Some(sub) { + sub.unsubscribe() + } + }) + .detach() + sub_b.val = Some(app.observe_global(marker_key, fn(_) { b_count.val += 1 })) + app.set_global(marker_key, 1) + assert_eq(b_count.val, 0) +} + +///| +/// Port of GPUI's `test_self_drop_during_callback` and +/// `test_subscription_drop`. +test "self unsubscribe and unsubscribe before firing" { + let app = @app.App::new() + app.set_global(marker_key, 0) + let count = Ref(0) + let sub : Ref[@app.Subscription?] = Ref(None) + sub.val = Some( + app.observe_global(marker_key, fn(_) { + count.val += 1 + sub.val.unwrap().unsubscribe() + }), + ) + app.set_global(marker_key, 1) + app.set_global(marker_key, 2) + assert_eq(count.val, 1) + let other = Ref(0) + let subscription = app.observe_global(marker_key, fn(_) { other.val += 1 }) + subscription.unsubscribe() + app.set_global(marker_key, 3) + assert_eq(other.val, 0) +} + +///| +test "defer_call runs after current effects" { + let app = @app.App::new() + let order = [] + app.update(fn(app) { + app.defer_call(fn(_) { order.push("deferred") }) + order.push("update") + }) + assert_eq(order, ["update", "deferred"]) + let counter = new_counter(app) + counter.update(app, fn(_, cx) { + cx.defer_call(fn(app) { order.push("count \{counter.read(app).count}") }) + }) + assert_eq(order, ["update", "deferred", "count 0"]) +} + +///| +test "panic on re-entrant update" { + let app = @app.App::new() + let counter = new_counter(app) + counter.update(app, fn(_, cx) { counter.update(cx.app, fn(_, _) { }) }) +} + +///| +test "panic on reading an entity while it is updated" { + let app = @app.App::new() + let counter = new_counter(app) + counter.update(app, fn(_, cx) { ignore(counter.read(cx.app)) }) +} + +///| +test "panic on updating a released entity" { + let app = @app.App::new() + let counter = new_counter(app) + app.release(counter) + counter.update(app, fn(_, _) { }) +} + +///| +test "panic on using an entity with another app" { + let app = @app.App::new() + let counter = new_counter(app) + ignore(counter.read(@app.App::new())) +} + +///| +test "panic on reading a missing global" { + ignore(@app.App::new().global(settings_key)) +} + +///| +test "panic on reading a global while it is being updated" { + let app = @app.App::new() + app.set_global(marker_key, 1) + app.update_global(marker_key, fn(_, app) { ignore(app.global(marker_key)) }) +} + +///| +test "panic on global_mut outside an update" { + let app = @app.App::new() + app.set_global(marker_key, 1) + ignore(app.global_mut(marker_key)) +} diff --git a/src/app/context.mbt b/src/app/context.mbt new file mode 100644 index 0000000..89fe945 --- /dev/null +++ b/src/app/context.mbt @@ -0,0 +1,199 @@ +// Port of gpui/src/app/context.rs: the context passed to entity callbacks. +// +// GPUI's `Context` derefs to `App`; here the app is the public `app` +// field (`cx.app.set_global(...)`). Window-related methods (`listener`, +// `observe_in`, focus) come with the Window (M6), `spawn` with the executors +// (M4). + +///| +/// The context of an update to entity `T` (GPUI: `Context<'_, T>`). +pub struct Context[T] { + app : App + priv weak : WeakEntity[T] +} + +///| +pub fn[T] Context::entity_id(self : Context[T]) -> EntityId { + self.weak.entity_id() +} + +///| +/// The entity being updated. +pub fn[T] Context::entity(self : Context[T]) -> Entity[T] { + match self.weak.upgrade() { + Some(entity) => entity + None => abort("the entity must be alive if we have an entity context") + } +} + +///| +pub fn[T] Context::weak_entity(self : Context[T]) -> WeakEntity[T] { + self.weak +} + +///| +/// Marks this entity as changed (GPUI: `cx.notify()`). +pub fn[T] Context::notify(self : Context[T]) -> Unit { + self.app.notify(self.weak.entity_id()) +} + +///| +/// Emits `event` to subscribers of this entity's `key` events +/// (GPUI: `cx.emit(event)`). +pub fn[T, E] Context::emit( + self : Context[T], + key : EventKey[E], + event : E, +) -> Unit { + self.app.emit_event(self.weak.entity_id(), key, event) +} + +///| +/// Queues `f` to run after the current effects. +pub fn[T] Context::defer_call(self : Context[T], f : (App) -> Unit) -> Unit { + self.app.defer_call(f) +} + +///| +/// Runs `f` on this entity's state, if it is still alive. +fn[T] invoke_on( + weak : WeakEntity[T], + app : App, + f : (T, Context[T]) -> Unit, +) -> Bool { + match weak.upgrade() { + Some(entity) => { + app.update_entity(entity, f) + true + } + None => false + } +} + +///| +/// Calls `on_notify` on this entity whenever `entity` is notified. Stops when +/// either entity is released (GPUI: `cx.observe`). +pub fn[T, W] Context::observe( + self : Context[T], + entity : Entity[W], + on_notify : (T, Entity[W], Context[T]) -> Unit, +) -> Subscription { + let observer = self.weak + self.app.observe_internal(entity, fn(entity, app) { + invoke_on(observer, app, fn(this, cx) { on_notify(this, entity, cx) }) + }) +} + +///| +/// Calls `on_notify` whenever this entity is notified. +pub fn[T] Context::observe_self( + self : Context[T], + on_notify : (T, Context[T]) -> Unit, +) -> Subscription { + let observer = self.weak + self.app.observe_internal(self.entity(), fn(_, app) { + invoke_on(observer, app, on_notify) + }) +} + +///| +/// Calls `on_event` on this entity for every `key` event `entity` emits. +/// Stops when either entity is released (GPUI: `cx.subscribe`). +pub fn[T, W, E] Context::subscribe( + self : Context[T], + entity : Entity[W], + key : EventKey[E], + on_event : (T, Entity[W], E, Context[T]) -> Unit, +) -> Subscription { + let subscriber = self.weak + self.app.subscribe_internal(entity, key, fn(entity, event, app) { + invoke_on(subscriber, app, fn(this, cx) { + on_event(this, entity, event, cx) + }) + }) +} + +///| +/// Calls `on_event` for every `key` event this entity emits. +pub fn[T, E] Context::subscribe_self( + self : Context[T], + key : EventKey[E], + on_event : (T, E, Context[T]) -> Unit, +) -> Subscription { + let subscriber = self.weak + self.app.subscribe_internal(self.entity(), key, fn(_, event, app) { + invoke_on(subscriber, app, fn(this, cx) { on_event(this, event, cx) }) + }) +} + +///| +/// Calls `on_release` with this entity's state when it is released +/// (GPUI: `cx.on_release`). +pub fn[T] Context::on_release( + self : Context[T], + on_release : (T, App) -> Unit, +) -> Subscription { + self.app.observe_release({ cell: self.weak.cell, }, on_release) +} + +///| +/// Calls `on_release` on this entity when `entity` is released +/// (GPUI: `cx.observe_release`). +pub fn[T, W] Context::observe_release( + self : Context[T], + entity : Entity[W], + on_release : (T, W, Context[T]) -> Unit, +) -> Subscription { + let observer = self.weak + self.app.observe_release(entity, fn(released, app) { + ignore( + invoke_on(observer, app, fn(this, cx) { on_release(this, released, cx) }), + ) + }) +} + +///| +/// Calls `f` on this entity whenever the global for `key` changes. Stops when +/// this entity is released (GPUI: `cx.observe_global`). +pub fn[T, G] Context::observe_global( + self : Context[T], + key : GlobalKey[G], + f : (T, Context[T]) -> Unit, +) -> Subscription { + let observer = self.weak + let (subscription, activate) = self.app.global_observers.insert_pending( + key.id, + fn(app) { invoke_on(observer, app, f) }, + ) + self.app.defer_call(fn(_) { activate() }) + subscription +} + +///| +/// Updates this entity's state from a weak handle, if it is still alive. +pub fn[T, R] WeakEntity::update( + self : WeakEntity[T], + app : App, + f : (T, Context[T]) -> R, +) -> R? { + match self.upgrade() { + Some(entity) => Some(app.update_entity(entity, f)) + None => None + } +} + +///| +/// `app.update_entity(self, f)`. +pub fn[T, R] Entity::update( + self : Entity[T], + app : App, + f : (T, Context[T]) -> R, +) -> R { + app.update_entity(self, f) +} + +///| +/// `app.read_entity(self)`. +pub fn[T] Entity::read(self : Entity[T], app : App) -> T { + app.read_entity(self) +} diff --git a/src/app/entity.mbt b/src/app/entity.mbt new file mode 100644 index 0000000..d33ddd1 --- /dev/null +++ b/src/app/entity.mbt @@ -0,0 +1,152 @@ +// Entities, ported from gpui/src/app/entity_map.rs. +// +// Deviations from GPUI: +// - A handle points directly at a typed cell holding the state; there is no +// `Box` map to downcast from. +// - Handles are not reference counted (no `Drop`). An entity lives until +// `App::release` is called; then its observers and event subscriptions are +// removed and its release listeners run, as when the last GPUI handle +// drops. `WeakEntity::upgrade` returns `None` from the moment of release. +// - State is passed to update callbacks by reference (MoonBit structs with +// `mut` fields), playing the role of GPUI's `&mut T`. + +///| +/// Identifies an entity within its app. +#derive(Eq, Hash, Compare, Debug) +pub(all) struct EntityId(Int32) + +///| +pub impl Show for EntityId with fn output(self, logger) { + logger.write_string("EntityId(\{self.0})") +} + +///| +priv struct EntityCell[T] { + app_id : Int32 + id : EntityId + mut value : T? + /// True while an update callback holds the state. + mut leased : Bool + mut released : Bool +} + +///| +/// A strong handle to state owned by the app (GPUI: `Entity`). +pub struct Entity[T] { + priv cell : EntityCell[T] +} + +///| +/// A handle that does not keep the entity alive (GPUI: `WeakEntity`). +pub struct WeakEntity[T] { + priv cell : EntityCell[T] +} + +///| +/// An entity id handed out before the entity's state exists +/// (GPUI: `Reservation`). +pub struct Reservation[T] { + priv cell : EntityCell[T] +} + +///| +pub fn[T] Entity::entity_id(self : Entity[T]) -> EntityId { + self.cell.id +} + +///| +pub fn[T] Entity::downgrade(self : Entity[T]) -> WeakEntity[T] { + { cell: self.cell, } +} + +///| +/// Whether `App::release` has been called for this entity. +pub fn[T] Entity::is_released(self : Entity[T]) -> Bool { + self.cell.released +} + +///| +pub impl[T] Eq for Entity[T] with fn equal(self, other) { + physical_equal(self.cell, other.cell) +} + +///| +pub impl[T] Hash for Entity[T] with fn hash_combine(self, hasher) { + hasher.combine(self.cell.id) +} + +///| +pub impl[T] Show for Entity[T] with fn output(self, logger) { + logger.write_string("Entity(\{self.cell.id.0})") +} + +///| +pub fn[T] WeakEntity::entity_id(self : WeakEntity[T]) -> EntityId { + self.cell.id +} + +///| +/// The strong handle, unless the entity has been released. +pub fn[T] WeakEntity::upgrade(self : WeakEntity[T]) -> Entity[T]? { + if self.cell.released { + None + } else { + Some({ cell: self.cell, }) + } +} + +///| +pub fn[T] Reservation::entity_id(self : Reservation[T]) -> EntityId { + self.cell.id +} + +///| +fn[T] EntityCell::check_app( + self : EntityCell[T], + app : App, + operation : String, +) -> Unit { + guard self.app_id == app.id else { + abort("cannot \{operation} \{self.id}: it belongs to a different App") + } +} + +///| +/// Takes the state for an update, failing loudly on re-entrancy or use after +/// release (GPUI: `EntityMap::lease`). +fn[T] EntityCell::lease(self : EntityCell[T], operation : String) -> T { + guard !self.released else { + abort("cannot \{operation} \{self.id}: the entity has been released") + } + guard !self.leased else { + abort("cannot \{operation} \{self.id} while it is already being updated") + } + guard self.value is Some(value) else { + abort( + "cannot \{operation} \{self.id}: the entity has not been inserted yet", + ) + } + self.leased = true + value +} + +///| +fn[T] EntityCell::end_lease(self : EntityCell[T]) -> Unit { + self.leased = false +} + +///| +/// Reads the state. Fails if the entity is being updated or was released +/// (GPUI: `EntityMap::read`). +fn[T] EntityCell::read(self : EntityCell[T]) -> T { + guard !self.released else { + abort("cannot read \{self.id}: the entity has been released") + } + guard !self.leased else { + abort("cannot read \{self.id} while it is already being updated") + } + guard self.value is Some(value) else { + abort("cannot read \{self.id}: the entity has not been inserted yet") + } + value +} diff --git a/src/app/keys.mbt b/src/app/keys.mbt new file mode 100644 index 0000000..dc4f1f9 --- /dev/null +++ b/src/app/keys.mbt @@ -0,0 +1,81 @@ +// Type keys: MoonBit's replacement for GPUI's `TypeId`-keyed maps of +// `Box` (globals, events). +// +// A key is created once per type, usually as a top-level `let`: +// +// let theme_key : @app.GlobalKey[Theme] = @app.GlobalKey::new("Theme") +// +// The app stores values under the key's id without knowing their type. A +// stored value is a closure that writes the value into its key's typed slot, +// so reading it back through the same key is type-safe without downcasts. + +///| +let next_key_id : Ref[Int32] = { val: 0, } + +///| +fn fresh_key_id() -> Int32 { + let id = next_key_id.val + next_key_id.val = id + 1 + id +} + +///| +/// Identifies one kind of global state (GPUI: `TypeId::of::()` for a +/// `G: Global`). +pub struct GlobalKey[G] { + id : Int32 + name : String + priv slot : Ref[G?] +} + +///| +pub fn[G] GlobalKey::new(name : String) -> GlobalKey[G] { + { id: fresh_key_id(), name, slot: { val: None, }, } +} + +///| +/// A type-erased value that can only be read back through `key`. +fn[G] GlobalKey::erase(self : GlobalKey[G], value : G) -> () -> Unit { + fn() { self.slot.val = Some(value) } +} + +///| +fn[G] GlobalKey::unerase(self : GlobalKey[G], erased : () -> Unit) -> G { + self.slot.val = None + erased() + guard self.slot.val is Some(value) else { + abort("global \{self.name}: stored value has the wrong key") + } + self.slot.val = None + value +} + +///| +/// Identifies one kind of event (GPUI: `TypeId::of::()` for events +/// declared with `impl EventEmitter for T`). +pub struct EventKey[E] { + id : Int32 + name : String + priv slot : Ref[E?] +} + +///| +pub fn[E] EventKey::new(name : String) -> EventKey[E] { + { id: fresh_key_id(), name, slot: { val: None, }, } +} + +///| +fn[E] EventKey::erase(self : EventKey[E], event : E) -> () -> Unit { + fn() { self.slot.val = Some(event) } +} + +///| +fn[E] EventKey::unerase(self : EventKey[E], erased : () -> Unit) -> E { + self.slot.val = None + erased() + guard self.slot.val is Some(event) else { + abort("event \{self.name}: payload has the wrong key") + } + self.slot.val = None + event +} diff --git a/src/app/moon.pkg b/src/app/moon.pkg new file mode 100644 index 0000000..32182eb --- /dev/null +++ b/src/app/moon.pkg @@ -0,0 +1,4 @@ +import { + "moonbitlang/core/deque", + "moonbitlang/core/hashset", +} diff --git a/src/app/pkg.generated.mbti b/src/app/pkg.generated.mbti new file mode 100644 index 0000000..c94bd6d --- /dev/null +++ b/src/app/pkg.generated.mbti @@ -0,0 +1,113 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/gpui/app" + +import { + "moonbitlang/core/debug", +} + +// Values + +// Errors + +// Types and methods +pub struct App { + // private fields +} +pub fn[G] App::default_global(Self, GlobalKey[G], () -> G) -> G +pub fn App::defer_call(Self, (Self) -> Unit) -> Unit +pub fn App::entity_count(Self) -> Int32 +pub fn[G] App::global(Self, GlobalKey[G]) -> G +pub fn[G] App::global_mut(Self, GlobalKey[G]) -> G +pub fn[G] App::has_global(Self, GlobalKey[G]) -> Bool +pub fn[T] App::insert_entity(Self, Reservation[T], (Context[T]) -> T) -> Entity[T] +pub fn App::new() -> Self +pub fn[T] App::new_entity(Self, (Context[T]) -> T) -> Entity[T] +pub fn App::notify(Self, EntityId) -> Unit +pub fn[T] App::observe(Self, Entity[T], (Entity[T], Self) -> Unit) -> Subscription +pub fn[G] App::observe_global(Self, GlobalKey[G], (Self) -> Unit) -> Subscription +pub fn[T] App::observe_release(Self, Entity[T], (T, Self) -> Unit) -> Subscription +pub fn[T] App::read_entity(Self, Entity[T]) -> T +pub fn[T] App::release(Self, Entity[T]) -> Unit +pub fn[G] App::remove_global(Self, GlobalKey[G]) -> G +pub fn[T] App::reserve_entity(Self) -> Reservation[T] +pub fn[G] App::set_global(Self, GlobalKey[G], G) -> Unit +pub fn[T, E] App::subscribe(Self, Entity[T], EventKey[E], (Entity[T], E, Self) -> Unit) -> Subscription +pub fn[G] App::try_global(Self, GlobalKey[G]) -> G? +pub fn[R] App::update(Self, (Self) -> R) -> R +pub fn[T, R] App::update_entity(Self, Entity[T], (T, Context[T]) -> R) -> R +pub fn[G, R] App::update_global(Self, GlobalKey[G], (G, Self) -> R) -> R + +pub struct Context[T] { + app : App + // private fields +} +pub fn[T] Context::defer_call(Self[T], (App) -> Unit) -> Unit +pub fn[T, E] Context::emit(Self[T], EventKey[E], E) -> Unit +pub fn[T] Context::entity(Self[T]) -> Entity[T] +pub fn[T] Context::entity_id(Self[T]) -> EntityId +pub fn[T] Context::notify(Self[T]) -> Unit +pub fn[T, W] Context::observe(Self[T], Entity[W], (T, Entity[W], Self[T]) -> Unit) -> Subscription +pub fn[T, G] Context::observe_global(Self[T], GlobalKey[G], (T, Self[T]) -> Unit) -> Subscription +pub fn[T, W] Context::observe_release(Self[T], Entity[W], (T, W, Self[T]) -> Unit) -> Subscription +pub fn[T] Context::observe_self(Self[T], (T, Self[T]) -> Unit) -> Subscription +pub fn[T] Context::on_release(Self[T], (T, App) -> Unit) -> Subscription +pub fn[T, W, E] Context::subscribe(Self[T], Entity[W], EventKey[E], (T, Entity[W], E, Self[T]) -> Unit) -> Subscription +pub fn[T, E] Context::subscribe_self(Self[T], EventKey[E], (T, E, Self[T]) -> Unit) -> Subscription +pub fn[T] Context::weak_entity(Self[T]) -> WeakEntity[T] + +pub struct Entity[T] { + // private fields +} +pub fn[T] Entity::downgrade(Self[T]) -> WeakEntity[T] +pub fn[T] Entity::entity_id(Self[T]) -> EntityId +pub fn[T] Entity::is_released(Self[T]) -> Bool +pub fn[T] Entity::read(Self[T], App) -> T +pub fn[T, R] Entity::update(Self[T], App, (T, Context[T]) -> R) -> R +pub impl[T] Eq for Entity[T] +pub impl[T] Hash for Entity[T] +pub impl[T] Show for Entity[T] + +#derive(Compare, Eq, Hash, @debug.Debug) +pub(all) struct EntityId(Int32) +pub impl Show for EntityId + +pub struct EventKey[E] { + id : Int32 + name : String + // private fields +} +pub fn[E] EventKey::new(String) -> Self[E] + +pub struct GlobalKey[G] { + id : Int32 + name : String + // private fields +} +pub fn[G] GlobalKey::new(String) -> Self[G] + +pub struct Reservation[T] { + // private fields +} +pub fn[T] Reservation::entity_id(Self[T]) -> EntityId + +type SubscriberSet[K, C] + +pub struct Subscription { + // private fields +} +pub fn Subscription::detach(Self) -> Unit +pub fn Subscription::is_active(Self) -> Bool +pub fn Subscription::join(Self, Self) -> Self +pub fn Subscription::new(() -> Unit) -> Self +pub fn Subscription::unsubscribe(Self) -> Unit + +pub struct WeakEntity[T] { + // private fields +} +pub fn[T] WeakEntity::entity_id(Self[T]) -> EntityId +pub fn[T, R] WeakEntity::update(Self[T], App, (T, Context[T]) -> R) -> R? +pub fn[T] WeakEntity::upgrade(Self[T]) -> Entity[T]? + +// Type aliases + +// Traits diff --git a/src/app/subscription.mbt b/src/app/subscription.mbt new file mode 100644 index 0000000..530939f --- /dev/null +++ b/src/app/subscription.mbt @@ -0,0 +1,179 @@ +// Port of gpui/src/subscription.rs. +// +// Deviation from GPUI: a Rust `Subscription` unsubscribes when dropped. There +// is no `Drop` in MoonBit, so a `Subscription` stays active until +// `unsubscribe()` is called, or until the entity it belongs to is released. +// `detach()` is kept for API parity; it only documents intent. + +///| +#derive(Eq) +priv enum SubscriberState { + Pending + Active + Dropped +} + +///| +priv struct Subscriber[C] { + id : Int32 + mut state : SubscriberState + callback : C +} + +///| +/// A set of callbacks keyed by emitter. Callbacks run in subscription order; +/// subscriptions created while callbacks run are pending until activated. +struct SubscriberSet[K, C] { + subscribers : Map[K, Array[Subscriber[C]]] + mut next_subscriber_id : Int32 +} + +///| +fn[K : Hash + Eq, C] SubscriberSet::new() -> SubscriberSet[K, C] { + { subscribers: {}, next_subscriber_id: 0, } +} + +///| +/// Inserts an active subscriber. +fn[K : Hash + Eq, C] SubscriberSet::insert( + self : SubscriberSet[K, C], + key : K, + callback : C, +) -> Subscription { + let (subscription, activate) = self.insert_pending(key, callback) + activate() + subscription +} + +///| +/// Inserts a subscriber that does not run until `activate` is called. +fn[K : Hash + Eq, C] SubscriberSet::insert_pending( + self : SubscriberSet[K, C], + key : K, + callback : C, +) -> (Subscription, () -> Unit) { + let id = self.next_subscriber_id + self.next_subscriber_id = id + 1 + let subscriber = { id, state: Pending, callback, } + match self.subscribers.get(key) { + Some(list) => list.push(subscriber) + None => self.subscribers[key] = [subscriber] + } + let subscription = Subscription::new(fn() { + subscriber.state = Dropped + if self.subscribers.get(key) is Some(list) { + let remaining = list.filter(fn(s) { s.id != id }) + if remaining.is_empty() { + self.subscribers.remove(key) + } else { + self.subscribers[key] = remaining + } + } + }) + let activate = fn() { + if subscriber.state == Pending { + subscriber.state = Active + } + } + (subscription, activate) +} + +///| +/// Removes every subscriber of `key`, returning the active callbacks. +fn[K : Hash + Eq, C] SubscriberSet::remove( + self : SubscriberSet[K, C], + key : K, +) -> Array[C] { + match self.subscribers.get(key) { + None => [] + Some(list) => { + self.subscribers.remove(key) + list.filter(fn(s) { s.state == Active }).map(fn(s) { s.callback }) + } + } +} + +///| +/// Calls `f` on every active subscriber of `key`, in order; a subscriber is +/// removed when `f` returns false or when it was unsubscribed meanwhile. +/// Subscribers added during the iteration are kept but not visited. +fn[K : Hash + Eq, C] SubscriberSet::retain( + self : SubscriberSet[K, C], + key : K, + f : (C) -> Bool, +) -> Unit { + guard self.subscribers.get(key) is Some(list) else { return } + // Detach the list so that insertions during callbacks go to a fresh list. + self.subscribers.remove(key) + let kept : Array[Subscriber[C]] = [] + for subscriber in list { + let keep = match subscriber.state { + Pending => true + Dropped => false + Active => f(subscriber.callback) && subscriber.state != Dropped + } + if keep && subscriber.state != Dropped { + kept.push(subscriber) + } + } + match self.subscribers.get(key) { + Some(added) => + // Ids only grow, so newly added subscribers come after the kept ones. + self.subscribers[key] = [ + ..kept, + ..added.filter(fn(s) { s.state != Dropped }), + ] + None => if !kept.is_empty() { self.subscribers[key] = kept } + } +} + +///| +/// A handle to a registered callback. Call `unsubscribe` to stop it. +pub struct Subscription { + priv mut unsubscribe_fn : (() -> Unit)? +} + +///| +/// A subscription that runs `unsubscribe` once when unsubscribed. +pub fn Subscription::new(unsubscribe : () -> Unit) -> Subscription { + { unsubscribe_fn: Some(unsubscribe), } +} + +///| +/// Stops the callback. Idempotent. +pub fn Subscription::unsubscribe(self : Subscription) -> Unit { + if self.unsubscribe_fn is Some(f) { + self.unsubscribe_fn = None + f() + } +} + +///| +/// Keeps the callback registered for as long as its entities live. In +/// MoonBit this is the default (there is no drop); kept for GPUI parity. +pub fn Subscription::detach(self : Subscription) -> Unit { + self.unsubscribe_fn = None +} + +///| +/// Whether `unsubscribe` has not been called (and `detach` neither). +pub fn Subscription::is_active(self : Subscription) -> Bool { + self.unsubscribe_fn is Some(_) +} + +///| +/// One subscription that unsubscribes both. +pub fn Subscription::join(a : Subscription, b : Subscription) -> Subscription { + let a_fn = a.unsubscribe_fn + let b_fn = b.unsubscribe_fn + a.unsubscribe_fn = None + b.unsubscribe_fn = None + Subscription::new(fn() { + if a_fn is Some(f) { + f() + } + if b_fn is Some(f) { + f() + } + }) +} diff --git a/src/app/subscription_wbtest.mbt b/src/app/subscription_wbtest.mbt new file mode 100644 index 0000000..a651cb4 --- /dev/null +++ b/src/app/subscription_wbtest.mbt @@ -0,0 +1,98 @@ +///| +/// Number of subscribers (pending or active) of `key`. +fn[K : Hash + Eq, C] SubscriberSet::count( + self : SubscriberSet[K, C], + key : K, +) -> Int32 { + match self.subscribers.get(key) { + Some(list) => list.length() + None => 0 + } +} + +///| +/// Port of GPUI's `test_immediate_and_pending_insertions`. +test "immediate and pending insertions" { + let subscribers : SubscriberSet[Int32, Int32] = SubscriberSet::new() + let first = subscribers.insert(1, 10) + let (second, activate_second) = subscribers.insert_pending(1, 20) + let visited = [] + subscribers.retain(1, fn(callback) { + visited.push(callback) + subscribers.insert(1, 30).detach() + true + }) + // Pending (20) and newly inserted (30) subscribers are not visited. + assert_eq(visited, [10]) + activate_second() + assert_eq(subscribers.remove(1), [10, 20, 30]) + first.unsubscribe() + second.unsubscribe() + let (pending, _activate) = subscribers.insert_pending(1, 40) + assert_eq(subscribers.remove(1).length(), 0) + pending.unsubscribe() +} + +///| +/// Port of GPUI's `test_activation_after_drop_during_retain`. +test "activation after unsubscribe during retain" { + let subscribers : SubscriberSet[Int32, Int32] = SubscriberSet::new() + let (first, activate_first) = subscribers.insert_pending(1, 10) + let (second, activate_second) = subscribers.insert_pending(1, 20) + subscribers.retain(1, fn(_) { abort("pending subscriber invoked") }) + activate_first() + let mut second_taken = false + let visited = [] + subscribers.retain(1, fn(callback) { + visited.push(callback) + guard !second_taken else { abort("only the first callback runs") } + second_taken = true + // Unsubscribing then activating must not revive the subscriber. + second.unsubscribe() + activate_second() + true + }) + assert_eq(visited, [10]) + assert_eq(subscribers.remove(1), [10]) + first.unsubscribe() +} + +///| +test "retain removes callbacks returning false and keeps order" { + let subscribers : SubscriberSet[String, Int32] = SubscriberSet::new() + for i in 0..<5 { + subscribers.insert("k", i).detach() + } + subscribers.retain("k", fn(i) { i % 2 == 0 }) + let seen = [] + subscribers.retain("k", fn(i) { + seen.push(i) + true + }) + assert_eq(seen, [0, 2, 4]) + // A subscriber unsubscribed by an earlier callback does not run. + let later = subscribers.insert("k", 9) + let seen = [] + subscribers.retain("k", fn(i) { + seen.push(i) + later.unsubscribe() + true + }) + assert_eq(seen, [0, 2, 4]) + assert_eq(subscribers.count("k"), 3) + assert_eq(subscribers.count("none"), 0) +} + +///| +test "subscription join and is_active" { + let log = [] + let a = Subscription::new(fn() { log.push("a") }) + let b = Subscription::new(fn() { log.push("b") }) + let joined = Subscription::join(a, b) + assert_false(a.is_active()) + assert_true(joined.is_active()) + joined.unsubscribe() + joined.unsubscribe() + assert_eq(log, ["a", "b"]) + assert_false(joined.is_active()) +} diff --git a/src/examples/counter/main.mbt b/src/examples/counter/main.mbt new file mode 100644 index 0000000..6543725 --- /dev/null +++ b/src/examples/counter/main.mbt @@ -0,0 +1,77 @@ +// The app model (M3) without a window: two entities talking through +// notifications, typed events and a global. +// +// Run with: moon run src/examples/counter --target js + +///| +struct Counter { + mut count : Int32 +} + +///| +struct History { + entries : Array[String] +} + +///| +/// An event a counter emits when it passes a threshold. +let milestone : @app.EventKey[Int32] = @app.EventKey::new("Milestone") + +///| +/// App-wide configuration. +struct Config { + mut step : Int32 +} + +///| +let config_key : @app.GlobalKey[Config] = @app.GlobalKey::new("Config") + +///| +fn report() -> String { + let app = @app.App::new() + app.set_global(config_key, { step: 1, }) + let counter : @app.Entity[Counter] = app.new_entity(fn(_) { { count: 0, } }) + // The history observes the counter and subscribes to its milestones; both + // stop automatically when either entity is released. + let history : @app.Entity[History] = app.new_entity(fn(cx) { + cx + .observe(counter, fn(history, counter, cx) { + history.entries.push("count is \{counter.read(cx.app).count}") + }) + .detach() + cx + .subscribe(counter, milestone, fn(history, _, value, _) { + history.entries.push("milestone \{value}!") + }) + .detach() + cx + .observe_release(counter, fn(history, counter, _) { + history.entries.push("counter released at \{counter.count}") + }) + .detach() + { entries: [], } + }) + let increment = fn() { + counter.update(app, fn(counter, cx) { + counter.count += cx.app.global(config_key).step + if counter.count % 5 == 0 { + cx.emit(milestone, counter.count) + } + // Notifying twice in one update still runs observers once. + cx.notify() + cx.notify() + }) + } + increment() + increment() + app.update_global(config_key, fn(config, _) { config.step = 3 }) + increment() + app.release(counter) + // Updating a released entity would abort; the history keeps working. + history.read(app).entries.join("\n") +} + +///| +fn main { + println(report()) +} diff --git a/src/examples/counter/main_wbtest.mbt b/src/examples/counter/main_wbtest.mbt new file mode 100644 index 0000000..f37a63a --- /dev/null +++ b/src/examples/counter/main_wbtest.mbt @@ -0,0 +1,13 @@ +///| +test "counter report" { + inspect( + report(), + content=( + #|count is 1 + #|count is 2 + #|milestone 5! + #|count is 5 + #|counter released at 5 + ), + ) +} diff --git a/src/examples/counter/moon.pkg b/src/examples/counter/moon.pkg new file mode 100644 index 0000000..b357fe3 --- /dev/null +++ b/src/examples/counter/moon.pkg @@ -0,0 +1,5 @@ +import { + "experiments/gpui/app", +} + +pkgtype(kind: "executable") diff --git a/src/examples/counter/pkg.generated.mbti b/src/examples/counter/pkg.generated.mbti new file mode 100644 index 0000000..211e357 --- /dev/null +++ b/src/examples/counter/pkg.generated.mbti @@ -0,0 +1,17 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/gpui/examples/counter" + +// Values + +// Errors + +// Types and methods +type Config + +type Counter + +type History + +// Type aliases + +// Traits -- 2.54.1