From eeab51348efc58aa538cffcf119ea852591c64c4 Mon Sep 17 00:00:00 2001 From: Sprite Date: Tue, 24 Nov 2026 22:36:23 +0000 Subject: [PATCH] M4 executors: coroutine executor, tasks, timers, test dispatcher, AsyncApp - executor: coroutines on MoonBit's async intrinsics (%async.suspend / run / capture_cancellation / raise_cancellation_signal), scheduled by a Dispatcher trait (the platform hook) instead of core/async's event loop; works on wasm, wasm-gc, js and native. - Task[T]: wait (re-raises task errors), cancel (unwinds at the next suspension point, running defers; waiters get TaskCancelled), ready, try_result, detach. Executor: spawn, timer, sleep, yield_now, now. - TestDispatcher: deterministic FIFO queue and virtual clock with GPUI's advance_clock semantics (run, then step to each due timer). - app: AsyncApp, App::spawn, Context::spawn (weak handle), foreground/background executors, run_until_parked / advance_clock; App::new() owns a TestDispatcher unless given a dispatcher. - Tests ported/adapted from the scheduler crate; app async tests; the counter example gains a ticker task. Docs: M4 status and deviations. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- docs/PORTING.md | 51 ++++++- src/app/app.mbt | 20 ++- src/app/async_app.mbt | 121 +++++++++++++++ src/app/async_test.mbt | 118 +++++++++++++++ src/app/moon.pkg | 7 + src/app/pkg.generated.mbti | 20 ++- src/examples/counter/main.mbt | 19 ++- src/examples/counter/main_wbtest.mbt | 4 +- src/executor/coroutine.mbt | 157 +++++++++++++++++++ src/executor/dispatcher.mbt | 123 +++++++++++++++ src/executor/executor_test.mbt | 216 +++++++++++++++++++++++++++ src/executor/executor_wbtest.mbt | 11 ++ src/executor/moon.pkg | 10 ++ src/executor/pkg.generated.mbti | 54 +++++++ src/executor/task.mbt | 184 +++++++++++++++++++++++ 16 files changed, 1108 insertions(+), 13 deletions(-) create mode 100644 src/app/async_app.mbt create mode 100644 src/app/async_test.mbt create mode 100644 src/executor/coroutine.mbt create mode 100644 src/executor/dispatcher.mbt create mode 100644 src/executor/executor_test.mbt create mode 100644 src/executor/executor_wbtest.mbt create mode 100644 src/executor/moon.pkg create mode 100644 src/executor/pkg.generated.mbti create mode 100644 src/executor/task.mbt diff --git a/README.md b/README.md index bc2f6a1..5a4f153 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ roadmap. | `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/executor` | `executor.rs`, `scheduler` crate | Ported (tasks, timers, cancellation, deterministic test dispatcher; single thread) | | `experiments/gpui/layout` | `taffy.rs` | Ported on [`Milky2018/chicle`](https://mooncakes.io/docs/Milky2018/chicle) (flexbox, grid, block) | ## Example @@ -38,8 +39,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`). +`src/examples/counter` shows the app model and executors: two entities +talking through notifications, a typed event and a global, and a task +ticking on a simulated clock (`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 3189f9e..6ac7752 100644 --- a/docs/PORTING.md +++ b/docs/PORTING.md @@ -136,7 +136,7 @@ stays isolated. | `keymap` | `keymap.rs`, `keymap/*`, `platform/keystroke.rs` | pure | planned | | `action` | `action.rs` | 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 | +| `executor` | `executor.rs`, `scheduler` crate (`executor.rs`, `test_scheduler.rs`) | pure core + `Dispatcher` platform hook | **done** (single thread) | | `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 | | `text` | `text_system.rs`, `text_system/*` | mixed: wrapping/caching pure, shaping platform | planned | @@ -218,7 +218,7 @@ records what I verified with toolchain `moon 0.1.20261119`. | Browser APIs | `mizchi/js_browser@0.13.0` (MIT), `dijdzv/websys`, `peter-jerry-ye/canvas` | **js only** | DOM, Canvas2D, events, and rAF. | | WebGPU | `Milky2018/wgpu_mbt@0.16.2` | **native only** | wgpu-native C API bindings; macOS is supported, Linux and Windows are experimental. `tonyfettes/webgpu` and `emadurandal/rhodonite_webgpu` cover browser WebGPU. | | Windowing | `Milky2018/window@0.6.2` (winit port, **native, macOS only**), `mizchi/glfw`, `klaseca/sdl`, `laplaceliu/tycho_window` (Xlib) | native only | | -| Async | `moonbitlang/async@0.22.10` | **native** (some wasm) | Not usable on js. Core has a `moonbitlang/core/async` package; its js story needs checking before the executor milestone. | +| Async | `moonbitlang/async@0.22.10`, `moonbitlang/core/async` | native, wasm; js partly; **not wasm-gc** | Not used. Both own the event loop (`async fn main`, task groups), which conflicts with a platform-driven executor, and neither supports wasm-gc. `executor` uses the same compiler intrinsics (`%async.suspend`/`%async.run`) directly; see M4. | | Taffy-free layout ref | `Frank-III/onebit-tui` | native | Uses Yoga through FFI. Not useful here. | Recommendation: depend on `moon_cosmic` for text when that milestone @@ -361,10 +361,16 @@ gantt - 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`. - - `spawn` from `Context`. +- **M4: executor (done).** + - `Executor` (spawn, timer, sleep, yield_now, now), and `Task[T]` (wait, + cancel with unwinding, try_result, ready, detach). + - A `Dispatcher` trait as the platform hook, plus `TestDispatcher`, a + deterministic dispatcher with a virtual clock (`tick`, + `run_until_parked`, `advance_clock`, with GPUI's timer semantics). + - `AsyncApp`, `App::spawn`, `Context::spawn` (weak entity), and the + app's `foreground_executor`/`background_executor`. + - `App::new()` uses its own `TestDispatcher` (like GPUI's + `TestAppContext`); a platform passes its own dispatcher. - **M5: input model.** - `Keystroke::parse`, `Modifiers`. - `KeyContext` and the predicate parser and evaluator. @@ -499,6 +505,33 @@ gantt - Actions (M5). - Leak detection. +### Deviations taken in M4 (executor) +- **Coroutines come from MoonBit's experimental async intrinsics.** + `%async.suspend`, `%async.run`, `%async.capture_cancellation`, and + `%async.raise_cancellation_signal` are scheduled by our own `Dispatcher`. + This is what `moonbitlang/core/async` is built on, minus its event loop. + It works on all four backends, including wasm-gc. + - The package must set `experimental: true`, and packages importing it + need `"allow-experimental-packages": true`. + - Risk: the intrinsics may change with the toolchain. They are wrapped in + `src/executor/coroutine.mbt`. +- **One thread.** Background and foreground executors are the same executor + on the main thread, as in GPUI's single-threaded web backend. There are no + priorities, dedicated threads, `block_on`, or `scoped`. +- **Tasks are not cancelled on drop.** A GPUI `Task` cancels its future when + dropped. Here a task runs to completion unless `cancel()` is called. + - Cancellation resumes the task with a cancellation signal at its next + suspension point, running its `defer` blocks. + - Waiters get `TaskCancelled`; errors raised by a task are re-raised by + `wait`. +- **Durations are integer milliseconds.** `now()` returns `Int64` + milliseconds. +- **The test dispatcher is FIFO and deterministic.** GPUI's `TestScheduler` + can randomize the interleaving of sessions with a seed. That is not ported. + There is also no parking detection. +- **`AsyncApp` methods return values, not `Result`s.** An app is never + dropped while a task references it. + ## 7. Design decisions Decided on 2026-11-24, following the recommendations below. @@ -541,5 +574,11 @@ Decided on 2026-11-24, following the recommendations below. 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. +- `test` is a keyword, so a binding cannot be named `test`. Trait-object + coercion does not reach inside tuples: build `(&Trait, ...)` values + separately. +- Async code: `async fn` bodies that never suspend get an "unused async" + warning; a plain `fn` closure is accepted where an `async` one is + expected. Closures that raise must say so (`fn() raise { ... }`). - `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 index edf7a2a..b513f00 100644 --- a/src/app/app.mbt +++ b/src/app/app.mbt @@ -51,15 +51,33 @@ pub struct App { priv release_listeners : SubscriberSet[EntityId, (App) -> Unit] priv global_observers : SubscriberSet[Int32, (App) -> Bool] priv globals : Map[Int32, () -> Unit] + priv executor : @executor.Executor + /// Set when the app drives its own deterministic dispatcher (tests). + priv test_dispatcher : @executor.TestDispatcher? } ///| /// 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 { +/// +/// Async work runs on `dispatcher`. Without one, the app gets a +/// deterministic `TestDispatcher` that runs nothing until driven with +/// `run_until_parked` or `advance_clock` (like GPUI's `TestAppContext`). +pub fn App::new(dispatcher? : &@executor.Dispatcher) -> App { let id = next_app_id.val next_app_id.val = id + 1 + let test_dispatcher = match dispatcher { + Some(_) => None + None => Some(@executor.TestDispatcher::new()) + } + let executor = match (dispatcher, test_dispatcher) { + (Some(dispatcher), _) => @executor.Executor::new(dispatcher) + (None, Some(own)) => @executor.Executor::new(own) + (None, None) => abort("unreachable") + } { + executor, + test_dispatcher, id, next_entity_id: 1, entities: {}, diff --git a/src/app/async_app.mbt b/src/app/async_app.mbt new file mode 100644 index 0000000..bd2f8ed --- /dev/null +++ b/src/app/async_app.mbt @@ -0,0 +1,121 @@ +// Async integration, ported from gpui/src/app/async_context.rs and the +// `spawn` methods of App and Context. +// +// Deviation from GPUI: `AsyncApp` methods return plain values. GPUI's return +// `Result`s because the app may have been dropped while a task was +// suspended; a MoonBit `App` is never dropped while referenced. + +///| +/// A handle to the app that async tasks hold across suspension points +/// (GPUI: `AsyncApp`). Each call runs as its own update and flushes effects. +pub struct AsyncApp { + app : App +} + +///| +pub fn App::to_async(self : App) -> AsyncApp { + { app: self, } +} + +///| +/// The executor for work that must run on the main thread (GPUI: +/// `ForegroundExecutor`). There is one thread, so it is the same executor as +/// `background_executor`. +pub fn App::foreground_executor(self : App) -> @executor.Executor { + self.executor +} + +///| +/// The executor for work off the main thread (GPUI: `BackgroundExecutor`). +/// Shares the main thread here; see `foreground_executor`. +pub fn App::background_executor(self : App) -> @executor.Executor { + self.executor +} + +///| +/// Runs `f` as a task with an `AsyncApp` (GPUI: `cx.spawn`). +pub fn[R] App::spawn( + self : App, + f : async (AsyncApp) -> R, +) -> @executor.Task[R] { + let cx = self.to_async() + self.executor.spawn(async fn() { f(cx) }) +} + +///| +fn App::expect_test_dispatcher( + self : App, + operation : String, +) -> @executor.TestDispatcher { + match self.test_dispatcher { + Some(dispatcher) => dispatcher + None => + abort( + "App::\{operation} needs the app's own TestDispatcher (App::new() without a dispatcher)", + ) + } +} + +///| +/// Runs ready tasks until none is left (tests; GPUI: +/// `TestAppContext::run_until_parked`). +pub fn App::run_until_parked(self : App) -> Unit { + self.expect_test_dispatcher("run_until_parked").run_until_parked() +} + +///| +/// Advances the virtual clock, running timers and tasks (tests; GPUI: +/// `BackgroundExecutor::advance_clock`). +pub fn App::advance_clock(self : App, ms : Int32) -> Unit { + self.expect_test_dispatcher("advance_clock").advance_clock(ms) +} + +///| +/// Runs `f` as an update (GPUI: `AsyncApp::update`). +pub fn[R] AsyncApp::update(self : AsyncApp, f : (App) -> R) -> R { + self.app.update(f) +} + +///| +pub fn[T, R] AsyncApp::update_entity( + self : AsyncApp, + entity : Entity[T], + f : (T, Context[T]) -> R, +) -> R { + self.app.update_entity(entity, f) +} + +///| +pub fn[T] AsyncApp::read_entity(self : AsyncApp, entity : Entity[T]) -> T { + self.app.read_entity(entity) +} + +///| +pub fn[R] AsyncApp::spawn( + self : AsyncApp, + f : async (AsyncApp) -> R, +) -> @executor.Task[R] { + self.app.spawn(f) +} + +///| +pub fn AsyncApp::foreground_executor(self : AsyncApp) -> @executor.Executor { + self.app.executor +} + +///| +pub fn AsyncApp::background_executor(self : AsyncApp) -> @executor.Executor { + self.app.executor +} + +///| +/// Runs `f` as a task with a weak handle to this entity (GPUI: `cx.spawn`). +/// The task does not keep the entity alive: update it through the weak +/// handle, which yields `None` once the entity is released. +pub fn[T, R] Context::spawn( + self : Context[T], + f : async (WeakEntity[T], AsyncApp) -> R, +) -> @executor.Task[R] { + let weak = self.weak + self.app.spawn(async fn(cx) { f(weak, cx) }) +} diff --git a/src/app/async_test.mbt b/src/app/async_test.mbt new file mode 100644 index 0000000..809d906 --- /dev/null +++ b/src/app/async_test.mbt @@ -0,0 +1,118 @@ +///| +struct Status { + mut text : String + mut loads : Int32 +} + +///| +fn new_status(app : @app.App) -> @app.Entity[Status] { + app.new_entity(fn(_) { { text: "idle", loads: 0, } }) +} + +///| +test "app tasks update entities and flush effects per update" { + let app = @app.App::new() + let status = new_status(app) + let seen = [] + app + .observe(status, fn(status, app) { seen.push(status.read(app).text) }) + .detach() + let task = app.spawn(async fn(cx) { + cx.update_entity(status, fn(status, cx) { + status.text = "loading" + cx.notify() + }) + cx.background_executor().sleep(100) + cx.update_entity(status, fn(status, cx) { + status.text = "done" + status.loads += 1 + cx.notify() + }) + cx.read_entity(status).loads + }) + // Nothing runs until the test drives the app's dispatcher. + assert_eq(seen, []) + app.run_until_parked() + assert_eq(seen, ["loading"]) + app.advance_clock(99) + assert_eq(seen, ["loading"]) + app.advance_clock(1) + assert_eq(seen, ["loading", "done"]) + assert_eq(task.try_result(), Some(1)) +} + +///| +test "entity tasks hold weak handles" { + let app = @app.App::new() + let results = [] + let status : @app.Entity[Status] = app.new_entity(fn(cx) { + cx + .spawn(async fn(weak, cx) { + cx.foreground_executor().sleep(10) + let first = weak.update(cx.app, fn(status, _) { status.loads += 1 }) + results.push(first is Some(_)) + cx.foreground_executor().sleep(10) + // Released in between: the weak handle no longer upgrades. + let second = weak.update(cx.app, fn(status, _) { status.loads += 1 }) + results.push(second is Some(_)) + }) + .detach() + { text: "", loads: 0, } + }) + app.advance_clock(10) + assert_eq(results, [true]) + assert_eq(status.read(app).loads, 1) + app.release(status) + app.advance_clock(10) + assert_eq(results, [true, false]) +} + +///| +test "cancelling a spawned task stops it" { + let app = @app.App::new() + let status = new_status(app) + let task = app.spawn(async fn(cx) { + cx.background_executor().sleep(50) + cx.update_entity(status, fn(status, _) { status.text = "should not happen" }) + }) + app.run_until_parked() + task.cancel() + app.advance_clock(100) + assert_true(task.is_cancelled()) + assert_eq(status.read(app).text, "idle") +} + +///| +test "tasks spawned from AsyncApp and executor clock" { + let app = @app.App::new() + let order = [] + app + .spawn(async fn(cx) { + let child = cx.spawn(async fn(cx) { + cx.background_executor().sleep(5) + order.push("child") + 7 + }) + order.push("parent waits") + let value = child.wait() + order.push("parent got \{value} at \{cx.background_executor().now()}") + }) + .detach() + app.advance_clock(5) + assert_eq(order, ["parent waits", "child", "parent got 7 at 5"]) +} + +///| +test "apps can run on a caller-provided dispatcher" { + let dispatcher = @executor.TestDispatcher::new() + let app = @app.App::new(dispatcher~) + let task = app.spawn(fn(_) { "ran" }) + dispatcher.run_until_parked() + assert_eq(task.try_result(), Some("ran")) +} + +///| +test "panic on run_until_parked without the app's own dispatcher" { + let app = @app.App::new(dispatcher=@executor.TestDispatcher::new()) + app.run_until_parked() +} diff --git a/src/app/moon.pkg b/src/app/moon.pkg index 32182eb..4082d6d 100644 --- a/src/app/moon.pkg +++ b/src/app/moon.pkg @@ -1,4 +1,11 @@ import { + "experiments/gpui/executor", "moonbitlang/core/deque", "moonbitlang/core/hashset", } + +// experiments/gpui/executor uses MoonBit's experimental async intrinsics. + +options( + "allow-experimental-packages": true, +) diff --git a/src/app/pkg.generated.mbti b/src/app/pkg.generated.mbti index c94bd6d..bf054cd 100644 --- a/src/app/pkg.generated.mbti +++ b/src/app/pkg.generated.mbti @@ -2,6 +2,7 @@ package "experiments/gpui/app" import { + "experiments/gpui/executor", "moonbitlang/core/debug", } @@ -13,14 +14,17 @@ import { pub struct App { // private fields } +pub fn App::advance_clock(Self, Int32) -> Unit +pub fn App::background_executor(Self) -> @executor.Executor 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 App::foreground_executor(Self) -> @executor.Executor 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 App::new(dispatcher? : &@executor.Dispatcher) -> 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 @@ -30,13 +34,26 @@ 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 App::run_until_parked(Self) -> Unit pub fn[G] App::set_global(Self, GlobalKey[G], G) -> Unit +pub fn[R] App::spawn(Self, async (AsyncApp) -> R) -> @executor.Task[R] pub fn[T, E] App::subscribe(Self, Entity[T], EventKey[E], (Entity[T], E, Self) -> Unit) -> Subscription +pub fn App::to_async(Self) -> AsyncApp 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 AsyncApp { + app : App +} +pub fn AsyncApp::background_executor(Self) -> @executor.Executor +pub fn AsyncApp::foreground_executor(Self) -> @executor.Executor +pub fn[T] AsyncApp::read_entity(Self, Entity[T]) -> T +pub fn[R] AsyncApp::spawn(Self, async (Self) -> R) -> @executor.Task[R] +pub fn[R] AsyncApp::update(Self, (App) -> R) -> R +pub fn[T, R] AsyncApp::update_entity(Self, Entity[T], (T, Context[T]) -> R) -> R + pub struct Context[T] { app : App // private fields @@ -51,6 +68,7 @@ pub fn[T, G] Context::observe_global(Self[T], GlobalKey[G], (T, Self[T]) -> Unit 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, R] Context::spawn(Self[T], async (WeakEntity[T], AsyncApp) -> R) -> @executor.Task[R] 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] diff --git a/src/examples/counter/main.mbt b/src/examples/counter/main.mbt index 6543725..97196ce 100644 --- a/src/examples/counter/main.mbt +++ b/src/examples/counter/main.mbt @@ -1,5 +1,6 @@ -// The app model (M3) without a window: two entities talking through -// notifications, typed events and a global. +// The app model (M3) and executors (M4) without a window: two entities +// talking through notifications, typed events and a global, and a task +// ticking on the app's simulated clock. // // Run with: moon run src/examples/counter --target js @@ -66,6 +67,20 @@ fn report() -> String { increment() app.update_global(config_key, fn(config, _) { config.step = 3 }) increment() + // A task that increments every 100ms until cancelled. `App::new()` uses a + // deterministic test dispatcher, so time only moves when we advance it. + let ticker = app.spawn(async fn(cx) { + while true { + cx.background_executor().sleep(100) + cx.update_entity(counter, fn(counter, cx) { + counter.count += 1 + cx.notify() + }) + } + }) + app.advance_clock(250) + ticker.cancel() + app.advance_clock(1000) app.release(counter) // Updating a released entity would abort; the history keeps working. history.read(app).entries.join("\n") diff --git a/src/examples/counter/main_wbtest.mbt b/src/examples/counter/main_wbtest.mbt index f37a63a..ed7a01d 100644 --- a/src/examples/counter/main_wbtest.mbt +++ b/src/examples/counter/main_wbtest.mbt @@ -7,7 +7,9 @@ test "counter report" { #|count is 2 #|milestone 5! #|count is 5 - #|counter released at 5 + #|count is 6 + #|count is 7 + #|counter released at 7 ), ) } diff --git a/src/executor/coroutine.mbt b/src/executor/coroutine.mbt new file mode 100644 index 0000000..7ac03cb --- /dev/null +++ b/src/executor/coroutine.mbt @@ -0,0 +1,157 @@ +// Coroutines on top of MoonBit's async intrinsics, scheduled by a +// `Dispatcher` instead of `moonbitlang/core/async`'s event loop. +// +// Why not `moonbitlang/core/async`: it owns the event loop (`async fn main`, +// `with_task_group`) and does not support the wasm-gc backend. GPUI's +// executors are driven by the platform (the browser's event loop, a native run +// loop, or a deterministic test scheduler), so we schedule coroutines +// ourselves with the same intrinsics `moonbitlang/core/async` is built on. +// They are experimental; see docs/PORTING.md. + +///| +async fn[T] async_suspend(cb : ((T) -> Unit) -> Unit) -> T noraise + nocancel = "%async.suspend" + +///| +fn run_async(f : async () -> Unit noraise + nocancel) = "%async.run" + +///| +async fn[X] raise_cancellation_signal() -> X noraise = "%async.raise_cancellation_signal" + +///| +async fn[X] capture_cancellation( + f : async () -> X, + handler~ : async () -> X nocancel, +) -> X nocancel = "%async.capture_cancellation" + +///| +priv enum Wake { + Continue + Cancelled +} + +///| +/// One running computation. While suspended, `continuation` resumes it. +priv struct Coroutine { + scheduler : Scheduler + mut continuation : ((Wake) -> Unit)? + mut cancelled : Bool + mut scheduled : Bool + mut finished : Bool + /// Woken while running: the next `suspend` returns immediately. + mut missed_wake : Bool +} + +///| +/// Runs coroutines one step at a time through a dispatcher. +priv struct Scheduler { + dispatcher : &Dispatcher +} + +///| +/// The coroutine running right now, across all schedulers (there is one +/// thread). +let current : Ref[Coroutine?] = { val: None, } + +///| +/// Schedules `coroutine` to continue on the dispatcher, once. +fn Coroutine::wake(self : Coroutine) -> Unit { + if self.scheduled || self.finished { + return + } + self.scheduled = true + self.scheduler.dispatcher.dispatch(fn() { self.step() }) +} + +///| +fn Coroutine::step(self : Coroutine) -> Unit { + self.scheduled = false + guard self.continuation is Some(continuation) else { + // Woken while running (it has not suspended yet). + if !self.finished { + self.missed_wake = true + } + return + } + self.continuation = None + let previous = current.val + current.val = Some(self) + continuation(if self.cancelled { Cancelled } else { Continue }) + current.val = previous +} + +///| +/// The coroutine running right now; fails loudly outside of a task. +fn current_coroutine(operation : String) -> Coroutine { + match current.val { + Some(coroutine) => coroutine + None => abort("\{operation} must be called from inside a task") + } +} + +///| +/// Suspends the current coroutine until it is woken. If the task is cancelled +/// (before or while suspended), raises the cancellation signal, which unwinds +/// the task and runs its `defer` blocks. +async fn suspend(coroutine : Coroutine) -> Unit noraise { + if coroutine.cancelled { + raise_cancellation_signal() + } + if coroutine.missed_wake { + coroutine.missed_wake = false + return + } + let wake : Wake = async_suspend(fn(k) { coroutine.continuation = Some(k) }) + match wake { + Continue => () + Cancelled => raise_cancellation_signal() + } +} + +///| +/// Starts `body` as a new coroutine on the next dispatcher turn. +fn Scheduler::spawn( + self : Scheduler, + body : async () -> Unit, + on_cancelled : () -> Unit, + on_error : (Error) -> Unit, + on_finished : () -> Unit, +) -> Coroutine { + let coroutine : Coroutine = { + scheduler: self, + continuation: None, + cancelled: false, + scheduled: false, + finished: false, + missed_wake: false, + } + coroutine.continuation = Some(fn(wake) { + match wake { + Cancelled => { + // Cancelled before it ever ran: the body never starts. + coroutine.finished = true + on_cancelled() + on_finished() + } + Continue => + run_async(() => { + capture_cancellation(body, handler=() => on_cancelled()) catch { + error => on_error(error) + } + coroutine.finished = true + on_finished() + }) + } + }) + coroutine.wake() + coroutine +} + +///| +fn Coroutine::cancel(self : Coroutine) -> Unit { + if self.finished || self.cancelled { + return + } + self.cancelled = true + // Resume it so that it observes the cancellation (and runs its `defer`s). + self.wake() +} diff --git a/src/executor/dispatcher.mbt b/src/executor/dispatcher.mbt new file mode 100644 index 0000000..fe57d15 --- /dev/null +++ b/src/executor/dispatcher.mbt @@ -0,0 +1,123 @@ +// The platform hook that runs executor work (GPUI: `PlatformDispatcher`, +// reduced to a single thread: GPUI's background threads are not available +// on the web and MoonBit has no threads; background tasks share the main +// thread, as in GPUI's single-threaded web backend). + +///| +/// Runs callbacks on the (only) thread, soon or after a delay. +pub(open) trait Dispatcher { + /// Run `runnable` soon, after the current callback returns. + fn dispatch(Self, runnable : () -> Unit) -> Unit + /// Run `runnable` after `delay_ms` milliseconds. + fn dispatch_after(Self, delay_ms : Int32, runnable : () -> Unit) -> Unit + /// Milliseconds since an arbitrary, fixed origin. + fn now(Self) -> Int64 +} + +///| +priv struct PendingTimer { + deadline : Int64 + runnable : () -> Unit +} + +///| +/// A deterministic dispatcher with a virtual clock, for tests (GPUI: +/// `TestScheduler`/`TestDispatcher`). Nothing runs until the test drives it +/// with `tick`, `run_until_parked` or `advance_clock`. +pub struct TestDispatcher { + priv queue : @deque.Deque[() -> Unit] + priv timers : Array[PendingTimer] + priv mut now_ms : Int64 +} + +///| +pub fn TestDispatcher::new() -> TestDispatcher { + { queue: @deque.Deque([]), timers: [], now_ms: 0, } +} + +///| +pub impl Dispatcher for TestDispatcher with fn dispatch(self, runnable) { + self.queue.push_back(runnable) +} + +///| +pub impl Dispatcher for TestDispatcher with fn dispatch_after( + self, + delay_ms, + runnable, +) { + guard delay_ms >= 0 else { + abort("dispatch_after: negative delay \{delay_ms}ms") + } + let timer = { deadline: self.now_ms + delay_ms.to_int64(), runnable, } + // Keep timers sorted by deadline; equal deadlines keep insertion order. + let mut index = self.timers.length() + while index > 0 && self.timers[index - 1].deadline > timer.deadline { + index = index - 1 + } + self.timers.insert(index, timer) +} + +///| +pub impl Dispatcher for TestDispatcher with fn now(self) { + self.now_ms +} + +///| +/// Moves timers whose deadline has passed into the run queue. +fn TestDispatcher::fire_due_timers(self : TestDispatcher) -> Unit { + while !self.timers.is_empty() && self.timers[0].deadline <= self.now_ms { + self.queue.push_back(self.timers.remove(0).runnable) + } +} + +///| +/// Runs one ready callback; false if none is ready. +pub fn TestDispatcher::tick(self : TestDispatcher) -> Bool { + self.fire_due_timers() + match self.queue.pop_front() { + Some(runnable) => { + runnable() + true + } + None => false + } +} + +///| +/// Runs callbacks until none is ready without advancing the clock (GPUI: +/// `run_until_parked`). +pub fn TestDispatcher::run_until_parked(self : TestDispatcher) -> Unit { + while self.tick() { + () + } +} + +///| +/// Advances the virtual clock by `ms`, firing timers in deadline order and +/// running everything they wake (GPUI: `advance_clock`). +pub fn TestDispatcher::advance_clock(self : TestDispatcher, ms : Int32) -> Unit { + guard ms >= 0 else { abort("advance_clock: negative duration \{ms}ms") } + let target = self.now_ms + ms.to_int64() + while true { + self.run_until_parked() + if !self.timers.is_empty() && self.timers[0].deadline <= target { + self.now_ms = self.timers[0].deadline + } else { + break + } + } + self.now_ms = target +} + +///| +/// Whether any callback is ready or any timer is pending. +pub fn TestDispatcher::has_pending_work(self : TestDispatcher) -> Bool { + !self.queue.is_empty() || !self.timers.is_empty() +} + +///| +/// Number of pending timers. +pub fn TestDispatcher::pending_timer_count(self : TestDispatcher) -> Int32 { + self.timers.length() +} diff --git a/src/executor/executor_test.mbt b/src/executor/executor_test.mbt new file mode 100644 index 0000000..fa6e135 --- /dev/null +++ b/src/executor/executor_test.mbt @@ -0,0 +1,216 @@ +///| +fn setup() -> (@executor.TestDispatcher, @executor.Executor) { + let dispatcher = @executor.TestDispatcher::new() + (dispatcher, @executor.Executor::new(dispatcher)) +} + +///| +fn[T] result_of(task : @executor.Task[T]) -> T? { + task.try_result() catch { + _ => None + } +} + +///| +suberror Boom { + Boom(String) +} + +///| +/// Port of the scheduler crate's `test_foreground_executor_spawn`. +test "spawn runs on the dispatcher" { + let (dispatcher, executor) = setup() + let task = executor.spawn(fn() { 42 }) + // Nothing runs until the dispatcher is driven. + assert_false(task.is_ready()) + dispatcher.run_until_parked() + assert_true(task.is_ready()) + assert_eq(result_of(task), Some(42)) + assert_eq(result_of(@executor.Task::ready("now")), Some("now")) +} + +///| +/// Like the scheduler crate's `test_foreground_ordering`: tasks start in +/// spawn order. +test "tasks run in spawn order" { + let (dispatcher, executor) = setup() + let trace = [] + for i in 0..<10 { + executor.spawn(fn() { trace.push(i) }).detach() + } + dispatcher.run_until_parked() + assert_eq(trace, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) +} + +///| +/// Port of the scheduler crate's `test_timer_ordering`. +test "timers fire in deadline order on the virtual clock" { + let (dispatcher, executor) = setup() + let order = [] + for delay in [100, 50, 150] { + executor + .spawn(async fn() { + executor.sleep(delay) + order.push((delay, executor.now())) + }) + .detach() + } + dispatcher.run_until_parked() + assert_eq(order, []) + dispatcher.advance_clock(60) + assert_eq(order, [(50, 50L)]) + assert_eq(executor.now(), 60L) + dispatcher.advance_clock(1000) + assert_eq(order, [(50, 50L), (100, 100L), (150, 150L)]) + assert_false(dispatcher.has_pending_work()) +} + +///| +test "tasks await tasks and errors propagate" { + let (dispatcher, executor) = setup() + let inner = executor.spawn(async fn() { + executor.sleep(10) + 20 + }) + let outer = executor.spawn(async fn() { inner.wait() + 1 }) + let failing : @executor.Task[Int32] = executor.spawn(fn() raise { + raise Boom("bad") + }) + let observer = executor.spawn(async fn() { + try failing.wait() catch { + Boom(message) => "caught \{message}" + _ => "other" + } noraise { + _ => "no error" + } + }) + dispatcher.advance_clock(10) + assert_eq(result_of(outer), Some(21)) + assert_eq(result_of(observer), Some("caught bad")) + let raised = try failing.try_result() catch { + Boom(_) => true + _ => false + } noraise { + _ => false + } + assert_true(raised) +} + +///| +test "cancel before start: the body never runs" { + let (dispatcher, executor) = setup() + let ran = Ref(false) + let task = executor.spawn(fn() { ran.val = true }) + task.cancel() + dispatcher.run_until_parked() + assert_false(ran.val) + assert_true(task.is_cancelled()) + let raised = try task.try_result() catch { + @executor.TaskCancelled => true + _ => false + } noraise { + _ => false + } + assert_true(raised) +} + +///| +test "cancel while suspended unwinds the task and notifies waiters" { + let (dispatcher, executor) = setup() + let log = [] + let sleeper = executor.spawn(async fn() { + defer log.push("cleanup") + log.push("sleeping") + executor.sleep(1000) + log.push("woke up") + }) + let waiter = executor.spawn(async fn() { + try sleeper.wait() catch { + @executor.TaskCancelled => "sleeper cancelled" + _ => "other error" + } noraise { + _ => "finished" + } + }) + dispatcher.run_until_parked() + assert_eq(log, ["sleeping"]) + sleeper.cancel() + dispatcher.run_until_parked() + assert_eq(log, ["sleeping", "cleanup"]) + assert_eq(result_of(waiter), Some("sleeper cancelled")) + // The timer still fires later, but nothing resumes. + dispatcher.advance_clock(2000) + assert_eq(log, ["sleeping", "cleanup"]) + // Cancelling a finished task does nothing. + waiter.cancel() + assert_false(waiter.is_cancelled()) +} + +///| +test "cancelled timers report cancellation" { + let (dispatcher, executor) = setup() + let timer = executor.timer(50) + timer.cancel() + assert_true(timer.is_cancelled()) + dispatcher.advance_clock(100) + assert_true(timer.is_cancelled()) +} + +///| +test "a task can cancel itself" { + let (dispatcher, executor) = setup() + let log = [] + let task_ref : Ref[@executor.Task[Unit]?] = Ref(None) + let task = executor.spawn(async fn() { + defer log.push("unwound") + task_ref.val.unwrap().cancel() + log.push("still running until the next suspension") + executor.yield_now() + log.push("never") + }) + task_ref.val = Some(task) + dispatcher.run_until_parked() + assert_eq(log, ["still running until the next suspension", "unwound"]) + assert_true(task.is_cancelled()) +} + +///| +test "yield_now interleaves tasks" { + let (dispatcher, executor) = setup() + let trace = [] + for name in ["a", "b"] { + executor + .spawn(async fn() { + for i in 0..<3 { + trace.push("\{name}\{i}") + executor.yield_now() + } + }) + .detach() + } + dispatcher.run_until_parked() + assert_eq(trace, ["a0", "b0", "a1", "b1", "a2", "b2"]) +} + +///| +test "tick runs one step at a time" { + let (dispatcher, executor) = setup() + let trace = [] + executor.spawn(fn() { trace.push(1) }).detach() + executor.spawn(fn() { trace.push(2) }).detach() + assert_true(dispatcher.tick()) + assert_eq(trace, [1]) + assert_true(dispatcher.tick()) + assert_false(dispatcher.tick()) + assert_eq(trace, [1, 2]) + assert_eq(dispatcher.pending_timer_count(), 0) +} + +///| +test "panic on a task waiting for itself" { + let (dispatcher, executor) = setup() + let task_ref : Ref[@executor.Task[Unit]?] = Ref(None) + let task = executor.spawn(async fn() { task_ref.val.unwrap().wait() }) + task_ref.val = Some(task) + dispatcher.run_until_parked() +} diff --git a/src/executor/executor_wbtest.mbt b/src/executor/executor_wbtest.mbt new file mode 100644 index 0000000..6977912 --- /dev/null +++ b/src/executor/executor_wbtest.mbt @@ -0,0 +1,11 @@ +///| +test "panic on waiting outside a task" { + let dispatcher = TestDispatcher::new() + let task = Executor::new(dispatcher).timer(1) + // A coroutine that is not a task: `wait` cannot suspend it. + run_async(() => { + capture_cancellation(() => task.wait(), handler=() => ()) catch { + _ => () + } + }) +} diff --git a/src/executor/moon.pkg b/src/executor/moon.pkg new file mode 100644 index 0000000..36a60b8 --- /dev/null +++ b/src/executor/moon.pkg @@ -0,0 +1,10 @@ +import { + "moonbitlang/core/deque", +} + +// The coroutine intrinsics (%async.*) are experimental. + +options( + "allow-experimental-packages": true, + experimental: true, +) diff --git a/src/executor/pkg.generated.mbti b/src/executor/pkg.generated.mbti new file mode 100644 index 0000000..2c632a7 --- /dev/null +++ b/src/executor/pkg.generated.mbti @@ -0,0 +1,54 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/gpui/executor" + +import { + "moonbitlang/core/debug", +} + +// Values + +// Errors +#derive(@debug.Debug) +pub suberror TaskCancelled + +// Types and methods +pub struct Executor { + // private fields +} +pub fn Executor::new(&Dispatcher) -> Self +pub fn Executor::now(Self) -> Int64 +pub async fn Executor::sleep(Self, Int32) -> Unit +pub fn[T] Executor::spawn(Self, async () -> T) -> Task[T] +pub fn Executor::timer(Self, Int32) -> Task[Unit] +pub async fn Executor::yield_now(Self) -> Unit + +pub struct Task[T] { + // private fields +} +pub fn[T] Task::cancel(Self[T]) -> Unit +pub fn[T] Task::detach(Self[T]) -> Unit +pub fn[T] Task::is_cancelled(Self[T]) -> Bool +pub fn[T] Task::is_ready(Self[T]) -> Bool +pub fn[T] Task::ready(T) -> Self[T] +pub fn[T] Task::try_result(Self[T]) -> T? raise +pub async fn[T] Task::wait(Self[T]) -> T + +pub struct TestDispatcher { + // private fields +} +pub fn TestDispatcher::advance_clock(Self, Int32) -> Unit +pub fn TestDispatcher::has_pending_work(Self) -> Bool +pub fn TestDispatcher::new() -> Self +pub fn TestDispatcher::pending_timer_count(Self) -> Int32 +pub fn TestDispatcher::run_until_parked(Self) -> Unit +pub fn TestDispatcher::tick(Self) -> Bool +pub impl Dispatcher for TestDispatcher + +// Type aliases + +// Traits +pub(open) trait Dispatcher { + fn dispatch(Self, () -> Unit) -> Unit + fn dispatch_after(Self, Int32, () -> Unit) -> Unit + fn now(Self) -> Int64 +} diff --git a/src/executor/task.mbt b/src/executor/task.mbt new file mode 100644 index 0000000..7bb5b6f --- /dev/null +++ b/src/executor/task.mbt @@ -0,0 +1,184 @@ +// Tasks and executors, ported from gpui/src/executor.rs and the `scheduler` +// crate (crates/scheduler/src/executor.rs). +// +// Deviations from GPUI: +// - Dropping a GPUI `Task` cancels it. There is no `Drop` in MoonBit: a task +// runs to completion unless `cancel()` is called. `detach()` is kept for +// parity. +// - There is one thread: background and foreground executors schedule on the +// same dispatcher (as GPUI's single-threaded web backend does). +// - Durations are milliseconds (`Int`); `now()` is milliseconds (`Int64`). + +///| +/// Raised by `Task::wait` when the task was cancelled. +#derive(Debug) +pub suberror TaskCancelled + +///| +priv enum Outcome[T] { + Pending + Done(T) + Failed(Error) + Cancelled +} + +///| +priv struct TaskState[T] { + mut outcome : Outcome[T] + waiters : Array[Coroutine] + mut coroutine : Coroutine? + /// Cancels work that is not a coroutine (timers). + mut on_cancel : (() -> Unit)? +} + +///| +/// The result of asynchronous work (GPUI: `Task`). Await it with `wait`. +pub struct Task[T] { + priv state : TaskState[T] +} + +///| +fn[T] TaskState::new() -> TaskState[T] { + { outcome: Pending, waiters: [], coroutine: None, on_cancel: None, } +} + +///| +fn[T] TaskState::complete(self : TaskState[T], outcome : Outcome[T]) -> Unit { + guard self.outcome is Pending else { return } + self.outcome = outcome + let waiters = self.waiters.copy() + self.waiters.clear() + for waiter in waiters { + waiter.wake() + } +} + +///| +/// A task that is already complete (GPUI: `Task::ready`). +pub fn[T] Task::ready(value : T) -> Task[T] { + { state: { ..TaskState::new(), outcome: Done(value), }, } +} + +///| +/// Whether the task has finished: completed, failed or cancelled. +pub fn[T] Task::is_ready(self : Task[T]) -> Bool { + !(self.state.outcome is Pending) +} + +///| +/// Whether the task was cancelled. +pub fn[T] Task::is_cancelled(self : Task[T]) -> Bool { + self.state.outcome is Cancelled +} + +///| +/// Lets the task run to completion without anyone awaiting it. In MoonBit +/// this is the default; kept for GPUI parity. +pub fn[T] Task::detach(self : Task[T]) -> Unit { + ignore(self) +} + +///| +/// Cancels the task. A running task is resumed with a cancellation signal at +/// its next suspension point, unwinding it (running `defer` blocks). Waiters +/// get `TaskCancelled`. No effect on finished tasks. +pub fn[T] Task::cancel(self : Task[T]) -> Unit { + guard self.state.outcome is Pending else { return } + match (self.state.coroutine, self.state.on_cancel) { + (Some(coroutine), _) => coroutine.cancel() + (None, Some(on_cancel)) => on_cancel() + (None, None) => self.state.complete(Cancelled) + } +} + +///| +/// The result if the task has finished: `Some(value)`, or raises the task's +/// error (or `TaskCancelled`); `None` while it is pending. +pub fn[T] Task::try_result(self : Task[T]) -> T? raise { + match self.state.outcome { + Pending => None + Done(value) => Some(value) + Failed(error) => raise error + Cancelled => raise TaskCancelled + } +} + +///| +/// Waits for the task from inside another task and returns its value. Raises +/// the task's error, or `TaskCancelled`. +pub async fn[T] Task::wait(self : Task[T]) -> T { + let state = self.state + while state.outcome is Pending { + let coroutine = current_coroutine("Task::wait") + if state.coroutine is Some(own) && physical_equal(own, coroutine) { + abort("a task cannot wait for itself") + } + state.waiters.push(coroutine) + suspend(coroutine) + } + match state.outcome { + Done(value) => value + Failed(error) => raise error + Cancelled => raise TaskCancelled + Pending => abort("unreachable: task still pending after wait") + } +} + +///| +/// Spawns tasks and timers on a dispatcher (GPUI: `ForegroundExecutor` and +/// `BackgroundExecutor`, which coincide on one thread). +pub struct Executor { + priv scheduler : Scheduler +} + +///| +pub fn Executor::new(dispatcher : &Dispatcher) -> Executor { + { scheduler: { dispatcher, }, } +} + +///| +/// Runs `f` as a task, starting on the next dispatcher turn. +pub fn[T] Executor::spawn(self : Executor, f : async () -> T) -> Task[T] { + let state : TaskState[T] = TaskState::new() + let coroutine = self.scheduler.spawn( + async fn() { + let value = f() + state.complete(Done(value)) + }, + fn() { state.complete(Cancelled) }, + fn(error) { state.complete(Failed(error)) }, + fn() { }, + ) + state.coroutine = Some(coroutine) + { state, } +} + +///| +/// A task that completes after `ms` milliseconds (GPUI: `timer`). +pub fn Executor::timer(self : Executor, ms : Int32) -> Task[Unit] { + let state : TaskState[Unit] = TaskState::new() + state.on_cancel = Some(fn() { state.complete(Cancelled) }) + self.scheduler.dispatcher.dispatch_after(ms, fn() { state.complete(Done(())) }) + { state, } +} + +///| +/// Suspends the current task for `ms` milliseconds. +pub async fn Executor::sleep(self : Executor, ms : Int32) -> Unit { + self.timer(ms).wait() +} + +///| +/// Lets other ready tasks run before continuing. +pub async fn Executor::yield_now(self : Executor) -> Unit { + let coroutine = current_coroutine("Executor::yield_now") + ignore(self) + coroutine.wake() + suspend(coroutine) +} + +///| +/// The dispatcher's clock, in milliseconds. +pub fn Executor::now(self : Executor) -> Int64 { + self.scheduler.dispatcher.now() +} -- 2.54.1