feat(gfx): integrate wasi-gfx for loading and presenting GUI
CI / test (push) Successful in 24s

This commit is contained in:
Antigravity committed 2026-11-25 02:54:03 +00:00
1 parent ccb809bdc3
commit 7caadb3f7f
59 files changed
+7495 -16

No files matched your search

+274
View File
@@ -0,0 +1,274 @@
// #region subtask
///|
priv struct SubTask {
handle : Int
state : SubTaskState
}
///|
priv enum SubTaskState {
Starting = 0
Started = 1
Returned = 2
Cancelled_before_started = 3
Cancelled_before_returned = 4
}
///|
fn SubTaskState::from(int : Int) -> SubTaskState {
match int {
0 => Starting
1 => Started
2 => Returned
3 => Cancelled_before_started
4 => Cancelled_before_returned
_ => panic()
}
}
///|
fn SubTask::from(code : Int) -> SubTask {
{ handle: code >> 4, state: SubTaskState::from(code & 0xf) }
}
///|
/// The baseline intrinsic cooperatively waits in the component model and
/// returns only after the subtask reaches a terminal state.
fn SubTask::cancel(self : SubTask) -> SubTaskState {
SubTaskState::from(subtask_cancel(self.handle))
}
// #endregion
// #region events
///|
priv enum EventCode {
None = 0
SubTask = 1
StreamRead = 2
StreamWrite = 3
FutureRead = 4
FutureWrite = 5
TaskCancelled = 6
}
///|
fn EventCode::from(int : Int) -> EventCode {
match int {
0 => None
1 => SubTask
2 => StreamRead
3 => StreamWrite
4 => FutureRead
5 => FutureWrite
6 => TaskCancelled
_ => panic()
}
}
///|
priv enum Events {
None
Subtask(Int, SubTaskState)
StreamRead(Int, StreamResult)
StreamWrite(Int, StreamResult)
FutureRead(Int, FutureReadResult)
FutureWrite(Int, FutureWriteResult)
TaskCancelled
}
///|
fn Events::new(code : EventCode, i : Int, j : Int) -> Events {
match code {
None => None
SubTask => Subtask(i, SubTaskState::from(j))
StreamRead => StreamRead(i, StreamResult::from(j))
StreamWrite => StreamWrite(i, StreamResult::from(j))
FutureRead => FutureRead(i, FutureReadResult::from(j))
FutureWrite => FutureWrite(i, FutureWriteResult::from(j))
TaskCancelled => TaskCancelled
}
}
// #endregion
// #region waitable set
///|
#borrow(array)
extern "wasm" fn int_array2ptr(array : FixedArray[Int]) -> Int =
#|(func (param i32) (result i32) local.get 0)
///|
struct WaitableSet(Int) derive(Eq, Hash)
///|
#deprecated
pub extend WaitableSet with Eq::{not_equal, equal}
///|
#deprecated
pub extend WaitableSet with Hash::{hash, hash_combine}
///|
fn WaitableSet::new() -> WaitableSet {
WaitableSet(waitable_set_new())
}
///|
fn WaitableSet::drop(self : Self) -> Unit {
waitable_set_drop(self.0)
}
///|
fn WaitableSet::poll(self : Self) -> (Events, Int) {
let payload : FixedArray[Int] = FixedArray::make(2, 0)
let event = waitable_set_poll(self.0, int_array2ptr(payload))
(Events::new(EventCode::from(event), payload[0], payload[1]), payload[0])
}
// #endregion
// #region Future
///|
priv enum FutureReadResult {
Completed = 0
Cancelled = 2
}
///|
fn FutureReadResult::from(int : Int) -> FutureReadResult {
match int {
0 => Completed
2 => Cancelled
_ => panic()
}
}
///|
priv enum FutureWriteResult {
Completed = 0
Dropped = 1
Cancelled = 2
}
///|
fn FutureWriteResult::from(int : Int) -> FutureWriteResult {
match int {
0 => Completed
1 => Dropped
2 => Cancelled
_ => panic()
}
}
// #endregion
// #region Stream
///|
priv struct StreamResult {
progress : Int
copy_result : CopyResult
}
///|
fn StreamResult::from(int : Int) -> StreamResult {
let progress = int >> 4
let copy_result = CopyResult::from(int & 0xf)
{ progress, copy_result }
}
///|
priv enum CopyResult {
Completed = 0
Dropped = 1
Cancelled = 2
}
///|
fn CopyResult::from(int : Int) -> CopyResult {
match int {
0 => Completed
1 => Dropped
2 => Cancelled
_ => panic()
}
}
// #endregion
// #region callback code
///|
/// Code to let the runtime know what to do in the callback
priv enum CallbackCode {
Completed
Yield
Wait(WaitableSet)
}
///|
fn CallbackCode::encode(self : Self) -> Int {
match self {
Completed => 0
Yield => 1
Wait(id) => 2 | (id.0 << 4)
}
}
// #endregion
// #region Component async primitives
///|
fn subtask_cancel(id : Int) -> Int = "$root" "[subtask-cancel]"
///|
fn subtask_drop(id : Int) = "$root" "[subtask-drop]"
///|
fn tls_set(tls : Int) = "$root" "[context-set-0]"
///|
fn tls_get() -> Int = "$root" "[context-get-0]"
///|
fn task_cancel() = "[export]$root" "[task-cancel]"
///|
fn waitable_set_new() -> Int = "$root" "[waitable-set-new]"
///|
fn waitable_set_drop(set : Int) = "$root" "[waitable-set-drop]"
///|
/// This poll is deliberately non-cancellable. Component-task cancellation is
/// delivered by the stackless callback instead of being consumed here.
fn waitable_set_poll(set : Int, payload : Int) -> Int = "$root" "[waitable-set-poll]"
///|
fn task_wakeup_stream_new() -> Int64 = "$root" "[stream-new-unit]"
///|
fn task_wakeup_stream_read(handle : Int, ptr : Int, len : Int) -> Int = "$root" "[async-lower][stream-read-unit]"
///|
fn task_wakeup_stream_write(handle : Int, ptr : Int, len : Int) -> Int = "$root" "[async-lower][stream-write-unit]"
///|
fn task_wakeup_stream_cancel_read(handle : Int) -> Int = "$root" "[stream-cancel-read-unit]"
///|
fn task_wakeup_stream_drop_readable(handle : Int) = "$root" "[stream-drop-readable-unit]"
///|
fn task_wakeup_stream_drop_writable(handle : Int) = "$root" "[stream-drop-writable-unit]"
///|
fn waitable_join(waitable : Int, set : Int) = "$root" "[waitable-join]"
// #endregion
+73
View File
@@ -0,0 +1,73 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv struct CondVarWaiter {
// Once a signal is assigned, cancellation must not lose it before the
// waiter resumes. This matches moonbitlang/async's condition variable.
mut woken : Bool
mut coro : Coroutine?
}
///|
/// A condition variable for synchronization between tasks.
pub struct CondVar {
priv waiters : @deque.Deque[CondVarWaiter]
}
///|
/// Create a new condition variable.
#alias(new, deprecated)
pub fn CondVar::CondVar() -> CondVar {
{ waiters: Deque([]) }
}
///|
/// Wait until the condition variable is signaled.
pub async fn CondVar::wait(self : CondVar) -> Unit noraise {
let waiter = { woken: false, coro: Some(current_coroutine()) }
self.waiters.push_back(waiter)
match suspend_check_cancel() {
Continue => ()
Cancelled if waiter.woken => ()
Cancelled => {
waiter.coro = None
raise_cancellation_signal()
}
}
}
///|
/// Wake the first waiting task. Does nothing when no task is waiting.
pub fn CondVar::signal(self : CondVar) -> Unit {
while self.waiters.pop_front() is Some(waiter) {
if waiter.coro is Some(coro) {
waiter.woken = true
coro.wake()
break
}
}
}
///|
/// Wake all waiting tasks. Does nothing when no task is waiting.
pub fn CondVar::broadcast(self : CondVar) -> Unit {
for waiter in self.waiters {
if waiter.coro is Some(coro) {
waiter.woken = true
coro.wake()
}
}
self.waiters.clear()
}
+218
View File
@@ -0,0 +1,218 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv enum SuspendResult {
Continue
Cancelled
}
///|
priv enum State {
Done
Fail(Error)
Cancelled
Running
Suspend((SuspendResult) -> Unit)
}
///|
struct Coroutine {
coro_id : Int
lane : TaskLane
mut state : State
mut shielded : Bool
mut cancelled : Bool
mut ready : Bool
mut spawner : ((async () -> Unit) -> Unit)?
downstream : Set[Coroutine]
}
///|
impl Eq for Coroutine with fn equal(c1, c2) {
c1.coro_id == c2.coro_id
}
///|
impl Hash for Coroutine with fn hash_combine(self, hasher) {
Hash::hash_combine(self.coro_id, hasher)
}
///|
fn Coroutine::wake(self : Coroutine) -> Unit {
if !self.ready {
self.ready = true
enqueue(self)
signal_component_task(self.lane)
}
}
///|
pub fn is_being_cancelled() -> Bool {
let coro = current_coroutine()
coro.cancelled && !coro.shielded
}
///|
pub async fn check_cancellation() -> Unit noraise {
if is_being_cancelled() {
raise_cancellation_signal()
}
}
///|
fn Coroutine::cancel(self : Coroutine) -> Unit {
match self.state {
Done | Fail(_) | Cancelled => return
Running | Suspend(_) => ()
}
self.cancelled = true
if !self.shielded {
self.wake()
}
}
///|
async fn suspend_check_cancel() -> SuspendResult noraise {
guard! scheduler.curr_coro is Some(coro)
if coro.cancelled && !coro.shielded {
return Cancelled
}
coro.lane.blocking += 1
defer {
coro.lane.blocking -= 1
}
async_suspend(fn(cont) {
guard! coro.state is Running
coro.state = Suspend(cont)
})
}
///|
async fn suspend() -> Unit noraise {
match suspend_check_cancel() {
Continue => ()
Cancelled => raise_cancellation_signal()
}
}
///|
fn spawn_owned(
f : async () -> Unit,
lane : TaskLane,
inherited_spawner : ((async () -> Unit) -> Unit)?,
) -> Coroutine {
scheduler.coro_id += 1
let coro = {
state: Running,
ready: true,
shielded: false,
downstream: Set([]),
coro_id: scheduler.coro_id,
lane,
cancelled: false,
spawner: inherited_spawner,
}
fn run(_) {
run_async(() => {
// Even a task cancelled before its first turn enters its body, so entry
// defers run. Cancellation is delivered at its first suspension/check.
try capture_cancellation(f, handler=() => coro.state = Cancelled) catch {
err => coro.state = Fail(err)
} noraise {
_ if coro.state is Running => coro.state = Done
_ => ()
}
for coro in coro.downstream {
coro.wake()
}
coro.downstream.clear()
})
}
coro.state = Suspend(run)
enqueue(coro)
coro
}
///|
fn spawn(f : async () -> Unit) -> Coroutine {
match scheduler.curr_coro {
Some(parent) => spawn_owned(f, parent.lane, parent.spawner)
None => {
let waitable_set = current_waitableset()
let task_state = component_task_state(waitable_set).unwrap()
spawn_owned(f, task_state.lane, None)
}
}
}
///|
fn Coroutine::unwrap(self : Coroutine) -> SuspendResult raise {
match self.state {
Done => Continue
Cancelled => Cancelled
Fail(err) => raise err
Running | Suspend(_) => panic()
}
}
///|
async fn Coroutine::wait(target : Coroutine) -> SuspendResult {
guard! scheduler.curr_coro is Some(coro)
guard! !physical_equal(coro, target)
match target.state {
Done => return Continue
Cancelled => return Cancelled
Fail(err) => raise err
Running | Suspend(_) => ()
}
target.downstream.add(coro)
defer target.downstream.remove(coro)
suspend()
target.unwrap()
}
///|
fn Coroutine::check_error(coro : Coroutine) -> Unit raise {
match coro.state {
Fail(err) => raise err
Done | Cancelled | Running | Suspend(_) => ()
}
}
///|
pub async fn[X] protect_from_cancel(f : async () -> X) -> X nocancel {
guard! scheduler.curr_coro is Some(coro)
// The shield prevents delivery; capture_cancellation expresses that invariant
// in the effect type without changing normal error propagation.
capture_cancellation(handler=() => panic(), () => {
if coro.shielded {
f()
} else {
coro.shielded = true
defer {
coro.shielded = false
}
f()
}
})
}
///|
/// Observe cancellation without clearing the task's sticky cancelled state.
/// Returns None on cancellation, Some on success, and propagates normal errors.
pub async fn[X] handle_cancellation(f : async () -> X) -> X? {
capture_cancellation(handler=() => None, () => Some(f()))
}
+658
View File
@@ -0,0 +1,658 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// State owned by one P3 component task. `task.state` is the sole completion
/// source; `owned_coroutines` contains only runtime bridge coroutines.
priv struct ComponentTaskState {
lane : TaskLane
subscribers : Map[Int, Subscriber]
task : Coroutine
owned_coroutines : @set.Set[Coroutine]
mut resolution : TaskResolution
mut cancellation_pending : Bool
}
///|
priv struct TaskWakeup {
reader : Int
writer : Int
mut reading : Bool
mut signaled : Bool
}
///|
priv struct Subscriber {
mut event : Events?
coro : @set.Set[Coroutine]
}
///|
priv enum TaskResolution {
Pending
FlushPending
Resolved
}
///|
fn current_waitableset() -> WaitableSet {
WaitableSet(tls_get())
}
///|
fn component_task_state(waitable_set : WaitableSet) -> ComponentTaskState? {
component_tasks.get(waitable_set)
}
///|
fn finish_waitableset(
waitable_set : WaitableSet,
task_state : ComponentTaskState,
) -> Unit {
guard task_state.owned_coroutines.is_empty() else { panic() }
guard task_state.lane.blocking == 0 && task_state.lane.run_later.is_empty() else {
panic()
}
drop_task_wakeup(task_state)
guard task_state.subscribers.is_empty() else { panic() }
component_tasks.remove(waitable_set)
waitable_set.drop()
tls_set(0)
}
///|
fn acknowledge_cancellation(task_state : ComponentTaskState) -> Unit {
guard task_state.cancellation_pending else { return }
match task_state.task.state {
Done => () // The generated wrapper already called task.return.
Fail(_) | Cancelled =>
if task_state.resolution is Pending {
task_cancel()
task_state.resolution = Resolved
}
Running | Suspend(_) => return
}
task_state.cancellation_pending = false
}
///|
fn notify_subscriber(
task_state : ComponentTaskState,
waitable_id : Int,
event : Events,
) -> Unit {
if task_state.lane.wakeup is Some(wakeup) && wakeup.reader == waitable_id {
guard! event is StreamRead(i, { progress: 1, copy_result: Completed }) &&
i == waitable_id
wakeup.reading = false
wakeup.signaled = false
task_state.subscribers.remove(waitable_id)
waitable_join(waitable_id, 0)
return
}
guard! task_state.subscribers.get(waitable_id) is Some(subscriber)
subscriber.event = Some(event)
subscriber.coro.each(Coroutine::wake)
// Keep the delivered event discoverable until its waiter consumes it. A
// local cancellation can race with the wakeup, and cancelling an already
// terminal canonical operation would trap.
waitable_join(waitable_id, 0)
}
///|
fn next_callback(
waitable_set : WaitableSet,
task_state : ComponentTaskState,
) -> Int {
if task_state.resolution is FlushPending {
task_state.resolution = Resolved
reschedule(task_state.lane)
}
acknowledge_cancellation(task_state)
if task_state.task.state is (Done | Fail(_) | Cancelled) &&
no_more_work(task_state.lane) {
let resolution = task_state.resolution
finish_waitableset(waitable_set, task_state)
guard! resolution is Resolved
return CallbackCode::Completed.encode()
}
if has_immediately_ready_task(task_state.lane) {
if !task_state.subscribers.is_empty() {
let (event, waitable_id) = waitable_set.poll()
match event {
None => ()
TaskCancelled => panic()
_ => notify_subscriber(task_state, waitable_id, event)
}
}
tls_set(waitable_set.0)
return CallbackCode::Yield.encode()
}
tls_set(waitable_set.0)
arm_task_wakeup(waitable_set, task_state)
CallbackCode::Wait(waitable_set.0).encode()
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn with_waitableset(f : async () -> Unit) -> Int {
let waitable_set = WaitableSet::new()
let lane = { blocking: 0, run_later: Deque([]), wakeup: None }
tls_set(waitable_set.0)
let task = spawn_owned(f, lane, None)
let task_state = {
lane,
subscribers: Map([]),
task,
owned_coroutines: Set([]),
resolution: Pending,
cancellation_pending: false,
}
component_tasks.set(waitable_set, task_state)
reschedule(lane)
next_callback(waitable_set, task_state)
}
///|
/// Record that the generated export wrapper has resolved the component-model
/// task. One additional fair scheduling round lets the enclosing MoonBit task
/// group observe its body completing without draining runnable background work.
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn task_returned() -> Unit {
let waitable_set = current_waitableset()
guard! component_task_state(waitable_set) is Some(task_state)
guard! task_state.resolution is Pending
task_state.resolution = FlushPending
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn cb(event : Int, waitable_id : Int, code : Int) -> Int {
let waitable_set = current_waitableset()
guard component_task_state(waitable_set) is Some(task_state) else { panic() }
let events = Events::new(EventCode::from(event), waitable_id, code)
let preserve_task_wakeup = match events {
StreamRead(i, _) =>
match task_state.lane.wakeup {
Some(wakeup) => wakeup.reader == i
None => false
}
_ => false
}
cancel_task_wakeup_read(task_state, preserve=preserve_task_wakeup)
match events {
None => {
reschedule(task_state.lane)
next_callback(waitable_set, task_state)
}
TaskCancelled => {
task_state.cancellation_pending = true
task_state.task.cancel()
task_state.owned_coroutines.each(Coroutine::cancel)
reschedule(task_state.lane)
next_callback(waitable_set, task_state)
}
_ => {
notify_subscriber(task_state, waitable_id, events)
reschedule(task_state.lane)
next_callback(waitable_set, task_state)
}
}
}
///|
let component_tasks : Map[WaitableSet, ComponentTaskState] = Map([])
///|
/// Spawn a coroutine owned by the current component-model async task.
///
/// This is intended for runtime bridge work such as lowering local futures and
/// streams to component-model handles. The coroutine does not participate in
/// `TaskGroup` structured concurrency, but it is cancelled when the current
/// component-model task is cancelled and keeps the waitable-set alive until it
/// terminates.
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn spawn_component_task_current(f : async () -> Unit) -> Unit {
let waitable_set = current_waitableset()
guard! component_task_state(waitable_set) is Some(task_state)
let coro = spawn_owned(
async fn() -> Unit {
let coro = current_coroutine()
defer task_state.owned_coroutines.remove(coro)
f()
},
task_state.lane,
Some(spawn_component_task_current),
)
task_state.owned_coroutines.add(coro)
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn has_component_task_scope() -> Bool {
let waitable_set = current_waitableset()
component_task_state(waitable_set) is Some(_)
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn current_component_task_token() -> Int {
current_waitableset().0
}
///|
fn detach_waitable(task_state : ComponentTaskState, waitable_id : Int) -> Unit {
if task_state.subscribers.get(waitable_id) is Some(subscriber) {
subscriber.coro.clear()
task_state.subscribers.remove(waitable_id)
}
waitable_join(waitable_id, 0)
}
///|
fn task_wakeup(lane : TaskLane) -> TaskWakeup {
match lane.wakeup {
Some(wakeup) => wakeup
None => {
let pair = task_wakeup_stream_new()
let wakeup = {
reader: pair.to_int(),
writer: (pair >> 32).to_int(),
reading: false,
signaled: false,
}
lane.wakeup = Some(wakeup)
wakeup
}
}
}
///|
fn arm_task_wakeup(
waitable_set : WaitableSet,
task_state : ComponentTaskState,
) -> Unit {
let wakeup = task_wakeup(task_state.lane)
if wakeup.reading {
return
}
let result = task_wakeup_stream_read(wakeup.reader, 0, 1)
guard! result == -1
let subscribers = task_state.subscribers
guard! subscribers.get(wakeup.reader) is None
subscribers.set(wakeup.reader, { event: None, coro: Set([]) })
waitable_join(wakeup.reader, waitable_set.0)
wakeup.reading = true
wakeup.signaled = false
}
///|
fn signal_component_task(lane : TaskLane) -> Unit {
guard lane.wakeup is Some(wakeup) else { return }
if !wakeup.reading || wakeup.signaled {
return
}
let result = StreamResult::from(task_wakeup_stream_write(wakeup.writer, 0, 1))
guard! result.progress == 1 && result.copy_result is Completed
wakeup.signaled = true
}
///|
fn cancel_task_wakeup_read(
task_state : ComponentTaskState,
preserve~ : Bool,
) -> Unit {
guard task_state.lane.wakeup is Some(wakeup) else { return }
if !wakeup.reading || preserve {
return
}
waitable_join(wakeup.reader, 0)
task_state.subscribers.remove(wakeup.reader)
ignore(task_wakeup_stream_cancel_read(wakeup.reader))
wakeup.reading = false
wakeup.signaled = false
}
///|
fn drop_task_wakeup(task_state : ComponentTaskState) -> Unit {
guard task_state.lane.wakeup is Some(wakeup) else { return }
if wakeup.reading {
waitable_join(wakeup.reader, 0)
task_state.subscribers.remove(wakeup.reader)
ignore(task_wakeup_stream_cancel_read(wakeup.reader))
}
task_wakeup_stream_drop_readable(wakeup.reader)
task_wakeup_stream_drop_writable(wakeup.writer)
task_state.lane.wakeup = None
}
///|
fn cancel_waitable_event(
owner_task : Int,
waitable_id : Int,
cancel : () -> Events,
) -> Events {
let waitable_set = WaitableSet(owner_task)
guard! component_task_state(waitable_set) is Some(task_state)
guard! task_state.subscribers.get(waitable_id) is Some(subscriber)
// Baseline cancel-read is synchronous and traps while its endpoint belongs
// to a waitable set. Detach before invoking the generated intrinsic.
waitable_join(waitable_id, 0)
let event = match subscriber.event {
Some(event) => event
None => cancel()
}
subscriber.event = Some(event)
subscriber.coro.each(Coroutine::wake)
task_state.subscribers.remove(waitable_id)
event
}
///|
/// Complete an operation immediately or suspend until its terminal waitable
/// event arrives. This is the single owner of subscription registration and
/// detachment for future and stream copy operations.
async fn waitable_event(waitable_id : Int, immediate : Events?) -> Events {
let waitable_set = current_waitableset()
let task_state = component_task_state(waitable_set).unwrap()
let subscribers = task_state.subscribers
match immediate {
Some(event) => {
if subscribers.get(waitable_id) is Some(subscriber) {
subscriber.event = Some(event)
subscriber.coro.each(Coroutine::wake)
subscriber.coro.clear()
waitable_join(waitable_id, 0)
}
subscribers.remove(waitable_id)
event
}
None => {
let subscriber = if subscribers.get(waitable_id) is Some(subscriber) {
subscriber
} else {
let subscriber = { event: None, coro: Set([]) }
subscribers.set(waitable_id, subscriber)
subscriber
}
guard! subscriber.event is None
waitable_join(waitable_id, waitable_set.0)
let coro = current_coroutine()
subscriber.coro.add(coro)
defer subscriber.coro.remove(coro)
let event = match suspend_check_cancel() {
Continue => subscriber.event.unwrap()
Cancelled =>
match subscriber.event {
// Completion owns the canonical buffer once its event is
// delivered, even if local cancellation wakes the same coroutine.
Some(event) => event
None => raise_cancellation_signal()
}
}
subscribers.remove(waitable_id)
event
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_subtask(
val : Int,
settle_lowered_arguments : (Bool) -> Unit,
drop_returned_result : () -> Unit,
) -> Unit {
let task = SubTask::from(val)
let mut cleaned = false
// Once the subtask leaves Starting, canonical arguments are either
// transferred or rejected. Generated code owns the corresponding action.
fn settle_arguments(state : SubTaskState) -> Unit {
if !cleaned && !(state is Starting) {
cleaned = true
settle_lowered_arguments(state is Cancelled_before_started)
}
}
// Immediate completion without a handle.
if task.handle == 0 {
settle_arguments(task.state)
match task.state {
Returned => return
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
Cancelled_before_returned => raise SubTaskCancelled(before_started=false)
_ => panic()
}
}
defer subtask_drop(task.handle)
// Initial state, return if finished
settle_arguments(task.state)
match task.state {
Returned => return
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
Cancelled_before_returned => raise SubTaskCancelled(before_started=false)
_ => ()
}
// A subtask can report intermediate states, so register the same subscriber
// again after each callback until a terminal state arrives.
let waitable_set = current_waitableset()
let task_state = component_task_state(waitable_set).unwrap()
let set = @set.Set([])
let subscriber = { event: None, coro: set }
let coro = current_coroutine()
set.add(coro)
defer {
set.remove(coro)
detach_waitable(task_state, task.handle)
}
for ;; {
let subscribers = task_state.subscribers
guard! subscribers.get(task.handle) is None
subscribers.set(task.handle, subscriber)
waitable_join(task.handle, waitable_set.0)
if suspend_check_cancel() is Cancelled {
protect_from_cancel(() => {
detach_waitable(task_state, task.handle)
// Consume a delivered terminal event before requesting cancellation:
// cancelling an already terminal canonical operation traps.
if subscriber.event is Some(Subtask(i, state)) {
guard! i == task.handle
settle_arguments(state)
match state {
Returned => {
drop_returned_result()
return
}
Cancelled_before_started | Cancelled_before_returned => return
Starting | Started => subscriber.event = None
}
}
let state = task.cancel()
settle_arguments(state)
match state {
Returned => drop_returned_result()
Cancelled_before_started | Cancelled_before_returned => ()
Starting | Started => panic()
}
})
raise_cancellation_signal()
}
task_state.subscribers.remove(task.handle)
// Subsequent state, return if finished
if subscriber.event is Some(Subtask(i, state)) {
guard! i == task.handle
settle_arguments(state)
match state {
Returned => return
Cancelled_before_started => raise SubTaskCancelled(before_started=true)
Cancelled_before_returned =>
raise SubTaskCancelled(before_started=false)
_ => subscriber.event = None
}
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_future_read(idx : Int, val : Int) -> Unit {
let event = if val == -1 {
waitable_event(idx, None)
} else {
let result = FutureReadResult::from(val)
waitable_event(idx, Some(FutureRead(idx, result)))
}
guard! event is FutureRead(i, result) && i == idx
match result {
Completed => return
Cancelled => raise FutureReadError::Cancelled
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn cancel_future_read(
owner_task : Int,
idx : Int,
cancel : () -> Int,
) -> Bool {
let event = cancel_waitable_event(owner_task, idx, () => {
FutureRead(idx, FutureReadResult::from(cancel()))
})
guard! event is FutureRead(i, result) && i == idx
match result {
Completed => true
Cancelled => false
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn cancel_stream_read(
owner_task : Int,
idx : Int,
cancel : () -> Int,
) -> Int {
let event = cancel_waitable_event(owner_task, idx, () => {
StreamRead(idx, StreamResult::from(cancel()))
})
guard! event is StreamRead(i, result) && i == idx
result.progress
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub fn cancel_stream_write(idx : Int, cancel : () -> Int) -> Int {
let event = cancel_waitable_event(current_component_task_token(), idx, () => {
StreamWrite(idx, StreamResult::from(cancel()))
})
guard! event is StreamWrite(i, result) && i == idx
result.progress
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_future_write_terminal(idx : Int, val : Int) -> Bool? {
let event = if val == -1 {
waitable_event(idx, None)
} else {
let result = FutureWriteResult::from(val)
waitable_event(idx, Some(FutureWrite(idx, result)))
}
guard! event is FutureWrite(i, result) && i == idx
match result {
Completed => Some(true)
Dropped => Some(false)
Cancelled => None
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_stream_read(idx : Int, val : Int) -> (Int, Bool) {
let event = if val == -1 {
waitable_event(idx, None)
} else {
let result = StreamResult::from(val)
waitable_event(idx, Some(StreamRead(idx, result)))
}
guard! event is StreamRead(i, { progress, copy_result }) && i == idx
match copy_result {
Completed => return (progress, false)
Dropped => return (progress, true)
Cancelled =>
if progress > 0 {
return (progress, false)
} else {
raise StreamReadCancelled
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
#doc(hidden)
pub async fn suspend_for_stream_write(idx : Int, val : Int) -> (Int, Bool) {
let event = if val == -1 {
waitable_event(idx, None)
} else {
let result = StreamResult::from(val)
waitable_event(idx, Some(StreamWrite(idx, result)))
}
guard! event is StreamWrite(i, { progress, copy_result }) && i == idx
match copy_result {
Completed => return (progress, false)
Dropped => return (progress, true)
Cancelled => return (progress, false)
}
}
///|
pub suberror OpCancelled {
SubTaskCancelled(before_started~ : Bool)
StreamReadCancelled
}
///|
pub(all) suberror FutureReadError {
Cancelled
Dropped
}
///|
#internal(wit_bindgen, "generated binding code only")
pub(all) suberror EndpointBusy {
Read
Write
}
+44
View File
@@ -0,0 +1,44 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// A mutex for synchronization between tasks.
#valtype
pub struct Mutex {
priv semaphore : Semaphore
}
///|
/// Create a mutex in the released state.
pub fn Mutex::Mutex() -> Mutex {
{ semaphore: Semaphore(1) }
}
///|
/// Acquire the mutex in FIFO order.
pub async fn Mutex::acquire(self : Mutex) -> Unit noraise {
self.semaphore.acquire()
}
///|
/// Try to acquire the mutex without waiting.
pub fn Mutex::try_acquire(self : Mutex) -> Bool {
self.semaphore.try_acquire()
}
///|
/// Release the mutex. The mutex must already be acquired.
pub fn Mutex::release(self : Mutex) -> Unit {
self.semaphore.release()
}
+31
View File
@@ -0,0 +1,31 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
async fn[T] async_suspend(cb : ((T) -> Unit) -> Unit) -> T noraise + nocancel = "%async.suspend"
///|
fn run_async(f : async () -> Unit noraise + nocancel) = "%async.run"
///|
/// Deliver cancellation from the runtime, or resume it after boundary cleanup.
#internal(wit_bindgen, "runtime and generated binding code only")
#doc(hidden)
pub 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"
+211
View File
@@ -0,0 +1,211 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv enum PromiseState[X] {
Pending
Completed(X)
Failed(Error)
Closed
ReaderDropped
Consumed
}
///|
priv struct PromiseCell[X] {
mut state : PromiseState[X]
ready : Semaphore
cleanup : ((X) -> Unit)?
mut reading : Bool
}
///|
/// The local producer side of a one-shot `Future[X]`.
///
/// This is a MoonBit coordination value, not a component-model future writable
/// endpoint. Conversion to a component future remains generated at an FFI site.
pub struct Promise[X] {
priv cell : Ref[PromiseCell[X]]
}
///|
pub(all) suberror PromiseClosed derive(Debug)
///|
#deprecated
pub extend PromiseClosed with Debug::{to_repr}
///|
fn[X] new_future_promise(cleanup : ((X) -> Unit)?) -> (Future[X], Promise[X]) {
let cell : Ref[PromiseCell[X]] = {
val: {
state: Pending,
ready: Semaphore(1, initial_value=0),
cleanup,
reading: false,
},
}
({ inner: Promised(cell) }, { cell, })
}
///|
/// Create a local one-shot Future/Promise pair.
pub fn[X] Future::new() -> (Future[X], Promise[X]) {
new_future_promise(None)
}
///|
/// Create a local one-shot Future/Promise pair with value-discard cleanup.
///
/// The cleanup callback runs when the promise completed successfully but the
/// future is dropped before consuming the value.
pub fn[X] Future::new_with_cleanup(
cleanup : (X) -> Unit,
) -> (Future[X], Promise[X]) {
new_future_promise(Some(cleanup))
}
///|
/// Complete the paired future with `value`.
///
/// `true` means the future accepted ownership. `false` means its reader was
/// already dropped and the caller retains ownership of `value`.
pub fn[X] Promise::complete(self : Promise[X], value : X) -> Bool {
match self.cell.val.state {
Pending => {
self.cell.val.state = Completed(value)
self.cell.val.ready.release()
true
}
ReaderDropped => false
Completed(_) | Failed(_) | Closed | Consumed =>
abort("promise already settled")
}
}
///|
/// Complete the paired future with an error raised by `Future::get`.
pub fn[X] Promise::fail(self : Promise[X], error : Error) -> Bool {
match self.cell.val.state {
Pending => {
self.cell.val.state = Failed(error)
self.cell.val.ready.release()
true
}
ReaderDropped => false
Completed(_) | Failed(_) | Closed | Consumed =>
abort("promise already settled")
}
}
///|
/// Close the paired future without producing a value.
///
/// A local waiter observes `PromiseClosed`. An outgoing component future still
/// cannot represent this terminal state and follows the bridge's no-value
/// failure policy if it has already crossed an FFI boundary.
pub fn[X] Promise::close(self : Promise[X]) -> Bool {
match self.cell.val.state {
Pending => {
self.cell.val.state = Closed
self.cell.val.ready.release()
true
}
ReaderDropped => false
Completed(_) | Failed(_) | Closed | Consumed =>
abort("promise already settled")
}
}
///|
fn[X] consume_promised_future(cell : Ref[PromiseCell[X]]) -> X raise {
match cell.val.state {
Completed(value) => {
cell.val.state = Consumed
value
}
Failed(error) => {
cell.val.state = Consumed
raise error
}
Closed => {
cell.val.state = Consumed
raise PromiseClosed
}
Pending => panic()
ReaderDropped => raise FutureReadError::Dropped
Consumed => abort("future already consumed")
}
}
///|
async fn[X] promised_future_get(cell : Ref[PromiseCell[X]]) -> X {
if cell.val.reading {
abort("future read already in progress")
}
match cell.val.state {
Pending => {
cell.val.reading = true
{
errdefer {
cell.val.reading = false
if cell.val.state is Pending {
cell.val.state = ReaderDropped
}
}
cell.val.ready.acquire()
}
cell.val.reading = false
consume_promised_future(cell)
}
Completed(_) | Failed(_) | Closed => consume_promised_future(cell)
ReaderDropped => consume_promised_future(cell)
Consumed => abort("future already consumed")
}
}
///|
fn[X] promised_future_drop(
cell : Ref[PromiseCell[X]],
fallback_cleanup : ((X) -> Unit)?,
) -> Unit {
if cell.val.reading {
match cell.val.state {
Pending => {
cell.val.state = ReaderDropped
cell.val.ready.release()
}
// Once settlement assigned a result, the waiting reader owns it.
Completed(_) | Failed(_) | Closed => ()
ReaderDropped | Consumed => ()
}
return
}
match cell.val.state {
Pending => cell.val.state = ReaderDropped
Completed(value) => {
cell.val.state = Consumed
match cell.val.cleanup {
Some(cleanup) => cleanup(value)
None =>
match fallback_cleanup {
Some(cleanup) => cleanup(value)
None => ()
}
}
}
Failed(_) | Closed => cell.val.state = Consumed
ReaderDropped | Consumed => ()
}
}
+74
View File
@@ -0,0 +1,74 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv struct Scheduler {
mut coro_id : Int
mut curr_coro : Coroutine?
}
///|
/// The per-component-task part of the scheduler. Coroutines retain this lane,
/// not `ComponentTaskState`, so a retired task cannot be kept alive by an RC
/// cycle through its registry entry or subscribers.
priv struct TaskLane {
mut blocking : Int
run_later : @deque.Deque[Coroutine]
mut wakeup : TaskWakeup?
}
///|
let scheduler : Scheduler = { coro_id: 0, curr_coro: None }
///|
fn current_coroutine() -> Coroutine {
scheduler.curr_coro.unwrap()
}
///|
fn enqueue(coro : Coroutine) -> Unit {
coro.lane.run_later.push_back(coro)
}
///|
fn has_immediately_ready_task(lane : TaskLane) -> Bool {
!lane.run_later.is_empty()
}
///|
fn no_more_work(lane : TaskLane) -> Bool {
lane.blocking == 0 && lane.run_later.is_empty()
}
///|
/// Run one fair scheduling round for a component task. Coroutines woken or
/// spawned during this round are left for the next round so the component
/// event loop gets a chance to poll completed waitables.
fn reschedule(lane : TaskLane) -> Unit {
let count = lane.run_later.length()
for _ in 0..<count {
guard lane.run_later.pop_front() is Some(coro) else { break }
coro.ready = false
guard coro.state is Suspend(cont) else { }
coro.state = Running
let last_coro = scheduler.curr_coro
scheduler.curr_coro = Some(coro)
if coro.cancelled && !coro.shielded {
cont(Cancelled)
} else {
cont(Continue)
}
scheduler.curr_coro = last_coro
}
}
+95
View File
@@ -0,0 +1,95 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv struct SemaphoreWaiter {
// Once a permit is assigned, cancellation must not lose it before the
// waiter resumes. This matches moonbitlang/async's semaphore semantics.
mut acquired : Bool
mut coro : Coroutine?
}
///|
pub struct Semaphore {
size : Int
priv mut value : Int
priv waiters : @deque.Deque[SemaphoreWaiter]
}
///|
/// Create a semaphore with at most `size` permits.
///
/// The initial number of available permits is `initial_value`, or `size` when
/// omitted.
#alias(new, deprecated)
pub fn Semaphore::Semaphore(
size : Int,
initial_value? : Int = size,
) -> Semaphore {
if size <= 0 {
abort("size of semaphore must be positive")
}
guard! initial_value >= 0 && initial_value <= size
{ value: initial_value, size, waiters: Deque([]) }
}
///|
/// Release one permit. Waiting coroutines acquire permits in FIFO order.
///
/// Each call must correspond one-to-one with a successful `acquire`. Calling
/// `release` without owning a permit is invalid.
pub fn Semaphore::release(self : Semaphore) -> Unit {
if self.value >= self.size {
abort("semaphore: too many release")
}
while self.waiters.pop_front() is Some(waiter) {
if waiter.coro is Some(coro) {
waiter.acquired = true
coro.wake()
break
}
} nobreak {
self.value += 1
}
}
///|
/// Acquire one permit, suspending in FIFO order when none is available.
pub async fn Semaphore::acquire(self : Semaphore) -> Unit noraise {
if self.value > 0 {
self.value -= 1
} else {
let waiter = { coro: Some(current_coroutine()), acquired: false }
self.waiters.push_back(waiter)
match suspend_check_cancel() {
Continue => ()
Cancelled if waiter.acquired => ()
Cancelled => {
waiter.coro = None
raise_cancellation_signal()
}
}
}
}
///|
/// Try to acquire one permit without suspending.
pub fn Semaphore::try_acquire(self : Semaphore) -> Bool {
if self.value > 0 {
self.value -= 1
true
} else {
false
}
}
+61
View File
@@ -0,0 +1,61 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
/// `Task[X]` represents a running task with result type `X`,
/// it can be used to wait and retrieve the result value of the task.
pub struct Task[X] {
priv value : Ref[X?]
priv coro : Coroutine
}
///|
/// An observed task terminated by cancellation. This is an ordinary error in
/// the waiter, distinct from cancellation of the waiter itself.
pub suberror TaskCancelled derive(Debug)
///|
#deprecated
pub extend TaskCancelled with Debug::{to_repr}
///|
/// Wait for a task and retrieve its result value.
/// If the task fails, `wait` will also fail with the same error.
///
/// If the target task was cancelled, `wait` raises `TaskCancelled`.
/// Cancellation of the current task propagates as a cancellation signal.
pub async fn[X] Task::wait(self : Task[X]) -> X {
match self.coro.wait() {
Continue => self.value.val.unwrap()
Cancelled => raise TaskCancelled::TaskCancelled
}
}
///|
/// Try to obtain the result of the task.
/// If the task already terminated, its result value will be returned.
/// If the task already failed, `try_wait` will fail immediately.
/// If the task is still running, `try_wait` returns `None`.
/// `try_wait` is a synchoronous function: it never blocks.
pub fn[X] Task::try_wait(self : Task[X]) -> X? raise {
self.coro.check_error()
self.value.val
}
///|
/// Cancel a running task. Cancelling a terminated task has no effect.
/// Subsequent attempt to wait for a cancelled task will receive error.
pub fn[X] Task::cancel(self : Task[X]) -> Unit {
self.coro.cancel()
}
+269
View File
@@ -0,0 +1,269 @@
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
priv enum TaskGroupState {
Done
Fail(Error)
Cancelled
Running
}
///|
priv struct GroupDeferBlock(async () -> Unit nocancel)
///|
/// A `TaskGroup` can be used to spawn children tasks that run in parallel.
/// Task groups implements *structured concurrency*:
/// a task group will only return after all its children task terminates.
///
/// Task groups also handles *error propagation*:
/// by default, if any child task raises error,
/// the whole task group will also raise that error,
/// and all other remaining child tasks will be cancelled.
///
/// The type parameter `X` in `TaskGroup[X]` is the result type of the group,
/// see `with_task_group` for more detail.
pub struct TaskGroup[X] {
priv children : Set[Coroutine]
priv parent : Coroutine
priv mut waiting : Int
priv mut state : TaskGroupState
priv mut result : X?
priv group_defer : Array[GroupDeferBlock]
}
///|
fn[X] TaskGroup::spawn_coroutine(
self : TaskGroup[X],
f : async () -> Unit,
no_wait~ : Bool,
allow_failure~ : Bool,
) -> Coroutine {
guard self.state is Running || !self.children.is_empty() else {
abort("trying to spawn from a terminated task group")
}
if !no_wait {
self.waiting += 1
}
async fn worker() {
let coro = current_coroutine()
defer {
self.children.remove(coro)
if !no_wait {
self.waiting -= 1
if self.waiting == 0 && self.state is Running {
for child in self.children {
child.cancel()
}
self.state = Done
}
}
if self.children.is_empty() {
self.parent.wake()
}
}
f() catch {
err if allow_failure => raise err
err => {
if self.state is Running {
for child in self.children {
child.cancel()
}
self.state = Fail(err)
} else {
self.state = Fail(err)
}
raise err
}
}
}
let coro = spawn(worker)
self.children.add(coro)
if !(self.state is Running) {
coro.cancel()
}
coro
}
///|
/// Spawn a child task in a task group, and run it asynchronously in the background.
///
/// Unless `no_wait` (`false` by default) is `true`,
/// the task group will wait for this task to complete before normal exit.
/// No matter what the value of `no_wait` is,
/// `with_task_group` will only return after all child tasks terminate.
/// The task will be cancelled automatically if it is still running
/// when the task group wishes to terminate.
///
/// Unless `allow_failure` (`false` by default) is `true`,
/// the whole task group will also fail if the spawned task fails,
/// other tasks in the group will be cancelled in this case.
///
/// Cancelled tasks are not considered failing. A normal error raised during
/// cancellation cleanup is still considered a failure.
///
/// A task spawned while the group is cancelling still starts, but begins in a
/// cancelled state so its entry cleanup can run. Spawning after the group has
/// terminated or from a group defer is invalid and aborts.
///
/// It is undefined whether the child task will start running immediately
/// before `spawn_bg` returns.
pub fn[X] TaskGroup::spawn_bg(
self : TaskGroup[X],
f : async () -> Unit,
no_wait? : Bool = false,
allow_failure? : Bool = false,
) -> Unit {
ignore(self.spawn_coroutine(f, no_wait~, allow_failure~))
}
///|
/// Spawn a child task in a task group, compute a result asynchronously.
/// A task handle will be returned, the result value of the task can be waited
/// and retrieved using `.wait()`, or cancelled using `.cancel()`.
///
/// Unless `no_wait` (`false` by default) is `true`,
/// the task group will wait for this task to complete before normal exit.
/// No matter what the value of `no_wait` is,
/// `with_task_group` will only return after all child tasks terminate.
/// The task will be cancelled automatically if it is still running
/// when the task group wishes to terminate.
///
/// Unless `allow_failure` (`false` by default) is `true`,
/// the whole task group will also fail if the spawned task fails,
/// other tasks in the group will be cancelled in this case.
///
/// Cancelled tasks are not considered failing. A normal error raised during
/// cancellation cleanup is still considered a failure.
///
/// A task spawned while the group is cancelling still starts, but begins in a
/// cancelled state so its entry cleanup can run. Spawning after the group has
/// terminated or from a group defer is invalid and aborts.
///
/// It is undefined whether the child task will start running immediately
/// before `spawn` returns.
pub fn[G, X] TaskGroup::spawn(
self : TaskGroup[G],
f : async () -> X,
no_wait? : Bool = false,
allow_failure? : Bool = false,
) -> Task[X] {
let value = @ref.new(Option::None)
let coro = self.spawn_coroutine(
() => value.val = Some(f()),
no_wait~,
allow_failure~,
)
{ value, coro }
}
///|
/// Attach a defer block, represented as a cleanup function, to a task group.
/// The cleanup function runs after every child task has terminated. Spawning a
/// new child from a group defer is invalid and aborts.
/// Group scoped defer blocks are executed in FILO order, just like normal `defer`.
/// `with_task_group` will only exit after all group defer blocks terminate.
///
/// Group defer blocks must be `nocancel`. Use `protect_from_cancel` when
/// running cancellable operations in a group defer.
/// It is highly recommended to add a hard timeout to async defer block in this case,
/// to avoid infinite hanging due to blocked operation.
pub fn[X] TaskGroup::add_defer(
self : TaskGroup[X],
block : async () -> Unit nocancel,
) -> Unit {
guard self.state is Running else {
abort("trying to attach defer to a terminated task group")
}
self.group_defer.push(GroupDeferBlock(block))
}
///|
/// `with_task_group(f)` creates a new task group and run `f` with the new group.
/// `f` itself will be run in a child task of the new group.
/// `with_task_group` exits after all the whole group terminates,
/// which means all child tasks in the group have terminated, including `f`.
///
/// If all children task terminate successfully,
/// `with_task_group` will return the result of `f`.
pub async fn[X] with_task_group(f : async (TaskGroup[X]) -> X) -> X {
let tg = {
children: Set([]),
parent: current_coroutine(),
waiting: 0,
state: Running,
result: None,
group_defer: [],
}
let curr = current_coroutine()
let prev = curr.spawner
curr.spawner = Some(fn(child) { tg.spawn_bg(child) })
defer {
curr.spawner = prev
}
tg.spawn_bg(() => {
let value = f(tg)
if tg.result is None {
tg.result = Some(value)
}
})
match suspend_check_cancel() {
Continue => ()
Cancelled => {
if tg.state is Running {
tg.state = Cancelled
}
if !tg.children.is_empty() {
for child in tg.children {
child.cancel()
}
protect_from_cancel(() => suspend())
}
}
}
guard! tg.children.is_empty()
while tg.group_defer.pop() is Some(defer_block) {
defer_block() catch {
err => if tg.state is Done { tg.state = Fail(err) }
}
}
match tg.state {
Done => tg.result.unwrap()
Fail(err) => raise err
Cancelled => raise_cancellation_signal()
Running => panic()
}
}
///|
/// Force a task group to terminate immediately with the given result value.
/// All child tasks in the group, including potentially the current one,
/// will be cancelled.
pub async fn[X] TaskGroup::return_immediately(
self : TaskGroup[X],
value : X,
) -> Unit noraise {
if self.result is None {
self.result = Some(value)
}
if self.state is Running {
self.state = Done
for child in self.children {
child.cancel()
}
}
check_cancellation()
}
+964
View File
@@ -0,0 +1,964 @@
///|
pub struct Sink[X] {
priv write : async (ArrayView[X]) -> Int
priv close : async () -> Unit
priv is_open : () -> Bool
priv has_cleanup : () -> Bool
priv cleanup : ((X) -> Unit)?
priv write_window_size : Int
}
///|
let default_sink_write_window_size : Int = 64
///|
/// The write callback must either raise before consuming any value or return
/// the number consumed. It must not raise after partial consumption because
/// `ArrayView` cannot carry an ownership offset through an exception.
/// The close callback must be idempotent.
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Sink::from_callbacks(
write : async (ArrayView[X]) -> Int,
close : async () -> Unit,
is_open : () -> Bool,
cleanup : ((X) -> Unit)?,
write_window_size : Int,
) -> Sink[X] {
guard! write_window_size > 0
{
write,
close,
is_open,
has_cleanup: () => cleanup is Some(_),
cleanup,
write_window_size,
}
}
///|
/// Consumes up to one bounded window and returns the number of values consumed.
///
/// Consumption includes values accepted by the peer and values recursively
/// cleaned after the peer closes. Check `is_open()` to distinguish those cases.
pub async fn[X] Sink::write(self : Sink[X], data : ArrayView[X]) -> Int {
if data.length() == 0 {
return 0
}
let length = if data.length() < self.write_window_size {
data.length()
} else {
self.write_window_size
}
// The callback may suspend, so it must not retain the caller's borrowed view.
let buffer = FixedArray::from_array(data[:length])
let written = (self.write)(buffer[:])
guard! written >= 0 && written <= length
if !(self.is_open)() && written < length && (self.has_cleanup)() {
self.cleanup_unaccepted(buffer[:], written)
return length
}
written
}
///|
/// Writes one bounded window from an immutable byte view.
///
/// This is the byte-stream counterpart of `write(ArrayView[T])`. MoonBit keeps
/// `BytesView` and `ArrayView[Byte]` as distinct types, so byte strings need a
/// separate entry point until the language provides a shared read-only view.
pub async fn Sink::write_bytes(self : Sink[Byte], data : BytesView) -> Int {
if data.length() == 0 {
return 0
}
let length = if data.length() < self.write_window_size {
data.length()
} else {
self.write_window_size
}
let buffer = data[:length].to_fixedarray()
let written = (self.write)(buffer[:])
guard! written >= 0 && written <= length
if !(self.is_open)() && written < length && (self.has_cleanup)() {
self.cleanup_unaccepted(buffer[:], written)
return length
}
written
}
///|
/// Returns whether the sink can still accept values from its peer.
pub fn[X] Sink::is_open(self : Sink[X]) -> Bool {
(self.is_open)()
}
///|
fn[X] Sink::cleanup_unaccepted(
self : Sink[X],
data : ArrayView[X],
offset : Int,
) -> Unit {
match self.cleanup {
Some(cleanup) =>
for i in offset..<data.length() {
cleanup(data[i])
}
None => ()
}
}
///|
fn Sink::cleanup_unaccepted_bytes(
self : Sink[Byte],
data : BytesView,
offset : Int,
) -> Unit {
match self.cleanup {
Some(cleanup) =>
for i in offset..<data.length() {
cleanup(data[i])
}
None => ()
}
}
///|
/// Writes the entire slice to the sink unless the sink closes first.
///
/// Returns `true` if all items were written while the sink remained open and
/// `false` if the endpoint closed during the operation. When the sink has a
/// cleanup callback, every item was either accepted or cleaned and must not be
/// retried. Producers of explicitly managed resources must use such a sink.
pub async fn[X] Sink::write_all(self : Sink[X], data : ArrayView[X]) -> Bool {
let mut offset = 0
for ;; {
if offset >= data.length() {
return true
}
let written = {
errdefer self.cleanup_unaccepted(data, offset)
self.write(data[offset:])
}
offset = offset + written
if !self.is_open() {
self.cleanup_unaccepted(data, offset)
return false
}
guard! written > 0
}
}
///|
/// Writes the entire byte view unless the sink closes first.
pub async fn Sink::write_all_bytes(self : Sink[Byte], data : BytesView) -> Bool {
let mut offset = 0
for ;; {
if offset >= data.length() {
return true
}
let written = {
errdefer self.cleanup_unaccepted_bytes(data, offset)
self.write_bytes(data[offset:])
}
offset = offset + written
if !self.is_open() {
self.cleanup_unaccepted_bytes(data, offset)
return false
}
guard! written > 0
}
}
///|
/// Closes the writable end of the stream.
///
/// Closing is idempotent. A peer waiting for values observes the end of the
/// stream after any values already accepted by the sink have been read.
pub async fn[X] Sink::close(self : Sink[X]) -> Unit {
(self.close)()
}
///|
priv struct LocalFutureState[X] {
mut value : X?
mut closed : Bool
cleanup : ((X) -> Unit)?
}
///|
fn[X] local_future_close(
state : Ref[LocalFutureState[X]],
fallback_cleanup : ((X) -> Unit)?,
) -> Unit {
if state.val.closed {
return
}
match state.val.value {
Some(value) => {
state.val.value = None
match state.val.cleanup {
Some(cleanup) => cleanup(value)
None =>
match fallback_cleanup {
Some(cleanup) => cleanup(value)
None => ()
}
}
}
None => ()
}
state.val.closed = true
}
///|
fn[X] local_future_get(state : Ref[LocalFutureState[X]]) -> X raise {
match state.val.value {
Some(value) => {
state.val.value = None
state.val.closed = true
value
}
None => raise FutureReadError::Dropped
}
}
///|
priv struct StreamPipeReader[X] {
max : Int
mut value : FixedArray[X]?
mut ended : Bool
mut coro : Coroutine?
}
///|
priv struct StreamPipeWriter[X] {
mut value : FixedArray[X]?
mut accepted : Int
mut coro : Coroutine?
}
///|
priv struct StreamPipe[X] {
capacity : Int
chunks : @deque.Deque[FixedArray[X]]
mut buffered : Int
mut writer_closed : Bool
mut reader_dropped : Bool
mut cleanup : ((X) -> Unit)?
mut head : FixedArray[X]?
mut head_pos : Int
readers : @deque.Deque[StreamPipeReader[X]]
writers : @deque.Deque[StreamPipeWriter[X]]
}
///|
fn[X] wake_stream_pipe_reader(
reader : StreamPipeReader[X],
value : FixedArray[X]?,
ended : Bool,
) -> Unit {
match reader.coro {
Some(coro) => {
reader.value = value
reader.ended = ended
reader.coro = None
coro.wake()
}
None => ()
}
}
///|
fn[X] wake_stream_pipe_writer(
writer : StreamPipeWriter[X],
accepted : Int,
) -> Unit {
match writer.coro {
Some(coro) => {
writer.accepted = accepted
writer.value = None
writer.coro = None
coro.wake()
}
None => writer.value = None
}
}
///|
fn[X] take_stream_pipe_reader(
pipe : Ref[StreamPipe[X]],
) -> StreamPipeReader[X]? {
while pipe.val.readers.pop_front() is Some(reader) {
if reader.coro is Some(_) {
return Some(reader)
}
}
None
}
///|
fn[X] take_stream_pipe_writer(
pipe : Ref[StreamPipe[X]],
) -> StreamPipeWriter[X]? {
while pipe.val.writers.pop_front() is Some(writer) {
if writer.coro is Some(_) && writer.value is Some(_) {
return Some(writer)
}
}
None
}
///|
fn[X] fill_stream_pipe_from_writers(pipe : Ref[StreamPipe[X]]) -> Unit {
if pipe.val.capacity <= 0 || pipe.val.writer_closed || pipe.val.reader_dropped {
return
}
for ;; {
let available = pipe.val.capacity - pipe.val.buffered
if available <= 0 {
return
}
guard take_stream_pipe_writer(pipe) is Some(writer) else { return }
guard writer.value is Some(data) else { continue }
let take = if available < data.length() { available } else { data.length() }
let chunk = FixedArray::from_array(data[:take])
pipe.val.chunks.push_back(chunk)
pipe.val.buffered = pipe.val.buffered + take
wake_stream_pipe_writer(writer, take)
}
}
///|
fn[X] stream_pipe_drop_reader(pipe : Ref[StreamPipe[X]]) -> Unit {
stream_pipe_drop_reader_with_cleanup(pipe, pipe.val.cleanup)
}
///|
fn[X] stream_pipe_drop_reader_with_cleanup(
pipe : Ref[StreamPipe[X]],
cleanup : ((X) -> Unit)?,
) -> Unit {
if pipe.val.reader_dropped {
return
}
match cleanup {
Some(cleanup) => {
match pipe.val.head {
Some(head) =>
for i in pipe.val.head_pos..<head.length() {
cleanup(head[i])
}
None => ()
}
while pipe.val.chunks.pop_front() is Some(chunk) {
for value in chunk {
cleanup(value)
}
}
}
None => ()
}
pipe.val.head = None
pipe.val.head_pos = 0
pipe.val.chunks.clear()
pipe.val.buffered = 0
pipe.val.reader_dropped = true
while pipe.val.readers.pop_front() is Some(reader) {
wake_stream_pipe_reader(reader, None, true)
}
while pipe.val.writers.pop_front() is Some(writer) {
let consumed = match (cleanup, writer.value) {
(Some(cleanup), Some(data)) => {
for value in data {
cleanup(value)
}
data.length()
}
_ => 0
}
wake_stream_pipe_writer(writer, consumed)
}
}
///|
fn[X] stream_pipe_reject_reader(
pipe : Ref[StreamPipe[X]],
fallback : (X) -> Unit,
) -> Unit {
if pipe.val.cleanup is None {
pipe.val.cleanup = Some(fallback)
}
stream_pipe_drop_reader(pipe)
}
///|
fn[X] stream_pipe_close_writer(pipe : Ref[StreamPipe[X]]) -> Unit {
if pipe.val.writer_closed {
return
}
pipe.val.writer_closed = true
while pipe.val.writers.pop_front() is Some(writer) {
wake_stream_pipe_writer(writer, 0)
}
if pipe.val.buffered == 0 {
while pipe.val.readers.pop_front() is Some(reader) {
wake_stream_pipe_reader(reader, None, true)
}
}
}
///|
async fn[X] stream_pipe_write(
pipe : Ref[StreamPipe[X]],
data : ArrayView[X],
) -> Int {
if data.length() == 0 || pipe.val.writer_closed || pipe.val.reader_dropped {
return 0
}
match take_stream_pipe_reader(pipe) {
Some(reader) => {
let take = if reader.max < data.length() {
reader.max
} else {
data.length()
}
let chunk = FixedArray::from_array(data[:take])
wake_stream_pipe_reader(reader, Some(chunk), false)
return take
}
None => ()
}
if pipe.val.capacity > 0 && pipe.val.buffered < pipe.val.capacity {
let available = pipe.val.capacity - pipe.val.buffered
let take = if available < data.length() { available } else { data.length() }
let chunk = FixedArray::from_array(data[:take])
pipe.val.chunks.push_back(chunk)
pipe.val.buffered = pipe.val.buffered + take
return take
}
let writer = StreamPipeWriter::{
value: Some(FixedArray::from_array(data)),
accepted: 0,
coro: Some(current_coroutine()),
}
pipe.val.writers.push_back(writer)
match suspend_check_cancel() {
Continue => ()
Cancelled if writer.coro is None => return writer.accepted
Cancelled => {
writer.coro = None
writer.value = None
raise_cancellation_signal()
}
}
writer.value = None
writer.accepted
}
///|
async fn[X] stream_pipe_read(
pipe : Ref[StreamPipe[X]],
count : Int,
) -> FixedArray[X]? {
if count <= 0 {
return Some([])
}
for ;; {
if pipe.val.reader_dropped {
return None
}
match pipe.val.head {
Some(head) => {
let available = head.length() - pipe.val.head_pos
let take = if count < available { count } else { available }
let result = FixedArray::from_array(
head[pipe.val.head_pos:pipe.val.head_pos + take],
)
pipe.val.head_pos = pipe.val.head_pos + take
pipe.val.buffered = pipe.val.buffered - take
if pipe.val.head_pos >= head.length() {
pipe.val.head = None
pipe.val.head_pos = 0
}
fill_stream_pipe_from_writers(pipe)
return Some(result)
}
None => ()
}
if pipe.val.chunks.pop_front() is Some(chunk) {
pipe.val.head = Some(chunk)
pipe.val.head_pos = 0
continue
}
match take_stream_pipe_writer(pipe) {
Some(writer) => {
guard writer.value is Some(data) else { continue }
let take = if count < data.length() { count } else { data.length() }
let result = FixedArray::from_array(data[:take])
wake_stream_pipe_writer(writer, take)
return Some(result)
}
None => ()
}
if pipe.val.writer_closed {
return None
}
let reader = StreamPipeReader::{
max: count,
value: None,
ended: false,
coro: Some(current_coroutine()),
}
pipe.val.readers.push_back(reader)
if suspend_check_cancel() is Cancelled {
reader.coro = None
match reader.value {
Some(value) => return Some(value)
None if reader.ended => return None
None => raise_cancellation_signal()
}
}
match reader.value {
Some(value) => return Some(value)
None if reader.ended => return None
None => ()
}
}
}
///|
priv struct FutureSource[X] {
get : async () -> X
close : async () -> Unit
close_sync : () -> Unit
}
///|
priv struct FutureProducerState[X] {
mut producer : (async () -> X)?
mut on_unstarted_drop : (() -> Unit)?
}
///|
priv enum FutureState[X] {
Source(FutureSource[X])
Local(Ref[LocalFutureState[X]])
Pending(Ref[FutureProducerState[X]])
Promised(Ref[PromiseCell[X]])
}
///|
pub struct Future[X] {
priv inner : FutureState[X]
}
///|
pub fn[X] Future::ready_with_cleanup(
value : X,
cleanup : (X) -> Unit,
) -> Future[X] {
let state : Ref[LocalFutureState[X]] = {
val: { value: Some(value), closed: false, cleanup: Some(cleanup) },
}
{ inner: Local(state) }
}
///|
pub fn[X] Future::ready(value : X) -> Future[X] {
let state : Ref[LocalFutureState[X]] = {
val: { value: Some(value), closed: false, cleanup: None },
}
{ inner: Local(state) }
}
///|
/// Creates a lazy future from an async producer.
///
/// `on_unstarted_drop`, when present, releases resources captured by a producer
/// that is discarded before its first `get`. Once the producer starts, it owns
/// its runtime cleanup and this callback is never invoked.
pub fn[X] Future::from(
producer : async () -> X,
on_unstarted_drop? : () -> Unit,
) -> Future[X] {
{ inner: Pending({ val: { producer: Some(producer), on_unstarted_drop } }) }
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Future::from_source(
get : async () -> X,
close : async () -> Unit,
close_sync : () -> Unit,
) -> Future[X] {
{ inner: Source({ get, close, close_sync }) }
}
///|
/// Waits for and consumes the future's single value.
///
/// A `Future` is a one-shot value. Calling `get` again, or calling it after the
/// readable end has been dropped, fails instead of replaying the value.
pub async fn[X] Future::get(self : Future[X]) -> X {
match self.inner {
Source(source) => (source.get)()
Local(state) => local_future_get(state)
Pending(state) =>
match state.val.producer {
Some(producer) => {
state.val.producer = None
state.val.on_unstarted_drop = None
producer()
}
None => raise FutureReadError::Dropped
}
Promised(cell) => promised_future_get(cell)
}
}
///|
/// Releases the readable end without consuming its value.
///
/// If the value is already locally available, its registered cleanup callback
/// runs. An unstarted lazy producer is discarded and runs
/// `on_unstarted_drop`, when provided.
pub async fn[X] Future::drop(self : Future[X]) -> Unit noraise {
match self.inner {
Source(source) => (source.close)() catch { _ => () }
Local(state) => local_future_close(state, None)
Pending(state) => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
Promised(cell) => promised_future_drop(cell, None)
}
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Future::drop_sync(self : Future[X]) -> Unit {
match self.inner {
Source(source) => (source.close_sync)()
Local(state) => local_future_close(state, None)
Pending(state) => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
Promised(cell) => promised_future_drop(cell, None)
}
}
///|
/// Rejects a future that was prepared for a component-model transfer but was
/// never transferred. A locally available value uses its registered cleanup,
/// falling back to the generated canonical-ABI cleanup. An unstarted producer
/// is discarded without running it.
#internal(wit_bindgen, "generated binding code only")
pub async fn[X] Future::reject(
self : Future[X],
cleanup : (X) -> Unit,
) -> Unit noraise {
match self.inner {
Source(source) => (source.close)() catch { _ => () }
Local(state) => local_future_close(state, Some(cleanup))
Pending(state) => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
Promised(cell) => promised_future_drop(cell, Some(cleanup))
}
}
///|
priv struct StreamProducerState[X] {
mut producer : (async (Sink[X]) -> Unit)?
mut cleanup : ((X) -> Unit)?
mut on_unstarted_drop : (() -> Unit)?
mut pipe : Ref[StreamPipe[X]]?
}
///|
priv struct StreamSource[X] {
read : async (Int) -> FixedArray[X]?
close : async () -> Unit
close_sync : () -> Unit
}
///|
priv enum StreamState[X] {
Source(StreamSource[X])
Local(Ref[StreamPipe[X]])
Outgoing(Ref[StreamProducerState[X]])
}
///|
pub struct Stream[X] {
priv inner : StreamState[X]
}
///|
fn[X] new_stream_pipe(
capacity : Int,
cleanup : ((X) -> Unit)?,
) -> Ref[StreamPipe[X]] {
if capacity < 0 {
abort("stream capacity must not be negative")
}
{
val: {
capacity,
chunks: Deque([]),
buffered: 0,
writer_closed: false,
reader_dropped: false,
cleanup,
head: None,
head_pos: 0,
readers: Deque([]),
writers: Deque([]),
},
}
}
///|
fn[X] stream_pipe_sink(pipe : Ref[StreamPipe[X]]) -> Sink[X] {
{
write: (data : ArrayView[X]) => stream_pipe_write(pipe, data),
close: () => stream_pipe_close_writer(pipe),
is_open: () => !pipe.val.writer_closed && !pipe.val.reader_dropped,
has_cleanup: () => pipe.val.cleanup is Some(_),
cleanup: Some(fn(value) {
match pipe.val.cleanup {
Some(cleanup) => cleanup(value)
None => ()
}
}),
write_window_size: default_sink_write_window_size,
}
}
///|
fn[X] new_local_stream(
capacity : Int,
cleanup : ((X) -> Unit)?,
) -> (Stream[X], Sink[X]) {
let pipe = new_stream_pipe(capacity, cleanup)
let stream = Stream::{ inner: Local(pipe) }
let sink = stream_pipe_sink(pipe)
(stream, sink)
}
///|
fn spawn_stream_producer(task : async () -> Unit) -> Unit {
let current = current_coroutine()
match current.spawner {
Some(spawner) => spawner(task)
None => ignore(spawn(task))
}
}
///|
fn[X] materialize_stream_producer(
state : Ref[StreamProducerState[X]],
) -> Ref[StreamPipe[X]] {
match state.val.pipe {
Some(pipe) => pipe
None => {
let pipe = new_stream_pipe(0, state.val.cleanup)
state.val.cleanup = None
state.val.pipe = Some(pipe)
match state.val.producer {
Some(producer) => {
state.val.producer = None
state.val.on_unstarted_drop = None
let sink = stream_pipe_sink(pipe)
spawn_stream_producer(async fn() {
defer stream_pipe_close_writer(pipe)
producer(sink) catch {
_ => ()
}
})
}
None => stream_pipe_close_writer(pipe)
}
pipe
}
}
}
///|
pub fn[X] Stream::new(capacity? : Int = 0) -> (Stream[X], Sink[X]) {
new_local_stream(capacity, None)
}
///|
/// Creates a local stream whose unread values are cleaned up when its readable
/// end is dropped.
pub fn[X] Stream::new_with_cleanup(
cleanup : (X) -> Unit,
capacity? : Int = 0,
) -> (Stream[X], Sink[X]) {
new_local_stream(capacity, Some(cleanup))
}
///|
/// Creates a lazy stream from an async producer.
///
/// `cleanup`, when present, releases buffered or pending values if the readable
/// end is dropped after the producer starts. Producers of explicitly managed
/// resources should provide it.
///
/// `on_unstarted_drop`, when present, releases resources captured by a producer
/// that is discarded before its first read or before a prepared component
/// transfer commits. Once the producer starts, it owns its runtime cleanup and
/// this callback is never invoked.
pub fn[X] Stream::produce(
producer : async (Sink[X]) -> Unit,
cleanup? : (X) -> Unit,
on_unstarted_drop? : () -> Unit,
) -> Stream[X] {
{
inner: Outgoing({
val: { producer: Some(producer), cleanup, on_unstarted_drop, pipe: None },
}),
}
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Stream::from_source(
read : async (Int) -> FixedArray[X]?,
close : async () -> Unit,
close_sync : () -> Unit,
) -> Stream[X] {
{ inner: Source({ read, close, close_sync }) }
}
///|
/// Reads at most `count` values from the stream.
///
/// `Some(values)` contains the next owned chunk and may be empty when the peer
/// reports no progress. `None` means the writable end has closed and no
/// buffered values remain. A non-positive count returns an empty chunk without
/// waiting.
pub async fn[X] Stream::read(self : Stream[X], count : Int) -> FixedArray[X]? {
match self.inner {
Source(source) => (source.read)(count)
Local(pipe) => stream_pipe_read(pipe, count)
Outgoing(state) =>
stream_pipe_read(materialize_stream_producer(state), count)
}
}
///|
/// Releases the readable end and discards unread values.
///
/// Registered cleanup callbacks run for locally buffered values. An unstarted
/// lazy producer is discarded and runs `on_unstarted_drop`, when provided.
pub async fn[X] Stream::drop(self : Stream[X]) -> Unit noraise {
match self.inner {
Source(source) => (source.close)() catch { _ => () }
Local(pipe) => stream_pipe_drop_reader(pipe)
Outgoing(state) =>
match state.val.pipe {
Some(pipe) => stream_pipe_drop_reader(pipe)
None => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.cleanup = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Stream::drop_sync(self : Stream[X]) -> Unit {
match self.inner {
Source(source) => (source.close_sync)()
Local(pipe) => stream_pipe_drop_reader(pipe)
Outgoing(state) =>
match state.val.pipe {
Some(pipe) => stream_pipe_drop_reader(pipe)
None => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.cleanup = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
}
}
}
///|
#internal(wit_bindgen, "generated binding code only")
pub fn[X] Stream::take_producer(self : Stream[X]) -> (async (Sink[X]) -> Unit)? {
match self.inner {
Outgoing(state) =>
match state.val.pipe {
Some(_) => None
None => {
let producer = state.val.producer
state.val.producer = None
state.val.cleanup = None
state.val.on_unstarted_drop = None
producer
}
}
Source(_) | Local(_) => None
}
}
///|
/// Rejects a stream that was prepared for a component-model transfer but was
/// never transferred. Component sources are closed immediately and buffered
/// local values are cleaned synchronously. An unstarted producer is discarded
/// without running it; its optional `on_unstarted_drop` callback owns cleanup of
/// captured resources.
#internal(wit_bindgen, "generated binding code only")
pub async fn[X] Stream::reject(
self : Stream[X],
cleanup : (X) -> Unit,
) -> Unit noraise {
match self.inner {
Source(source) => (source.close)() catch { _ => () }
Local(pipe) => stream_pipe_reject_reader(pipe, cleanup)
Outgoing(state) =>
match state.val.pipe {
Some(pipe) => stream_pipe_reject_reader(pipe, cleanup)
None => {
let cleanup = state.val.on_unstarted_drop
state.val.producer = None
state.val.cleanup = None
state.val.on_unstarted_drop = None
match cleanup {
Some(cleanup) => cleanup()
None => ()
}
}
}
}
}
+8
View File
@@ -0,0 +1,8 @@
import {
"moonbitlang/core/deque" @deque,
"moonbitlang/core/ref" @ref,
"moonbitlang/core/set" @set,
}
warnings = "-44"
supported_targets = "wasm"
+148
View File
@@ -0,0 +1,148 @@
// Generated using `moon info`, DON'T EDIT IT
package "moonplasma/desktop/async-core"
import {
"moonbitlang/core/debug",
}
// Values
pub async fn check_cancellation() -> Unit noraise
pub async fn[X] handle_cancellation(async () -> X) -> X?
pub fn is_being_cancelled() -> Bool
pub async fn[X] protect_from_cancel(async () -> X) -> X nocancel
pub async fn[X] with_task_group(async (TaskGroup[X]) -> X) -> X
// Errors
pub(all) suberror EndpointBusy {
Read
Write
}
pub(all) suberror FutureReadError {
Cancelled
Dropped
}
pub suberror OpCancelled {
SubTaskCancelled(before_started~ : Bool)
StreamReadCancelled
}
#derive(@debug.Debug)
pub(all) suberror PromiseClosed
#deprecated
pub fn PromiseClosed::to_repr(Self) -> @debug.Repr
#derive(@debug.Debug)
pub suberror TaskCancelled
#deprecated
pub fn TaskCancelled::to_repr(Self) -> @debug.Repr
// Types and methods
pub struct CondVar {
// private fields
}
#alias(new, deprecated)
pub fn CondVar::CondVar() -> Self
pub fn CondVar::broadcast(Self) -> Unit
pub fn CondVar::signal(Self) -> Unit
pub async fn CondVar::wait(Self) -> Unit noraise
type Coroutine
pub struct Future[X] {
// private fields
}
pub async fn[X] Future::drop(Self[X]) -> Unit noraise
pub fn[X] Future::drop_sync(Self[X]) -> Unit
pub fn[X] Future::from(async () -> X, on_unstarted_drop? : () -> Unit) -> Self[X]
pub fn[X] Future::from_source(async () -> X, async () -> Unit, () -> Unit) -> Self[X]
pub async fn[X] Future::get(Self[X]) -> X
pub fn[X] Future::new() -> (Self[X], Promise[X])
pub fn[X] Future::new_with_cleanup((X) -> Unit) -> (Self[X], Promise[X])
pub fn[X] Future::ready(X) -> Self[X]
pub fn[X] Future::ready_with_cleanup(X, (X) -> Unit) -> Self[X]
pub async fn[X] Future::reject(Self[X], (X) -> Unit) -> Unit noraise
pub struct Mutex {
// private fields
}
pub fn Mutex::Mutex() -> Self
pub async fn Mutex::acquire(Self) -> Unit noraise
pub fn Mutex::release(Self) -> Unit
pub fn Mutex::try_acquire(Self) -> Bool
pub struct Promise[X] {
// private fields
}
pub fn[X] Promise::close(Self[X]) -> Bool
pub fn[X] Promise::complete(Self[X], X) -> Bool
pub fn[X] Promise::fail(Self[X], Error) -> Bool
pub struct Semaphore {
size : Int32
// private fields
}
#alias(new, deprecated)
pub fn Semaphore::Semaphore(Int32, initial_value? : Int32) -> Self
pub async fn Semaphore::acquire(Self) -> Unit noraise
pub fn Semaphore::release(Self) -> Unit
pub fn Semaphore::try_acquire(Self) -> Bool
pub struct Sink[X] {
// private fields
}
pub async fn[X] Sink::close(Self[X]) -> Unit
pub fn[X] Sink::from_callbacks(async (ArrayView[X]) -> Int32, async () -> Unit, () -> Bool, ((X) -> Unit)?, Int32) -> Self[X]
pub fn[X] Sink::is_open(Self[X]) -> Bool
pub async fn[X] Sink::write(Self[X], ArrayView[X]) -> Int32
pub async fn[X] Sink::write_all(Self[X], ArrayView[X]) -> Bool
pub async fn Sink::write_all_bytes(Self[Byte], BytesView) -> Bool
pub async fn Sink::write_bytes(Self[Byte], BytesView) -> Int32
pub struct Stream[X] {
// private fields
}
pub async fn[X] Stream::drop(Self[X]) -> Unit noraise
pub fn[X] Stream::drop_sync(Self[X]) -> Unit
pub fn[X] Stream::from_source(async (Int32) -> FixedArray[X]?, async () -> Unit, () -> Unit) -> Self[X]
pub fn[X] Stream::new(capacity? : Int32) -> (Self[X], Sink[X])
pub fn[X] Stream::new_with_cleanup((X) -> Unit, capacity? : Int32) -> (Self[X], Sink[X])
pub fn[X] Stream::produce(async (Sink[X]) -> Unit, cleanup? : (X) -> Unit, on_unstarted_drop? : () -> Unit) -> Self[X]
pub async fn[X] Stream::read(Self[X], Int32) -> FixedArray[X]?
pub async fn[X] Stream::reject(Self[X], (X) -> Unit) -> Unit noraise
pub fn[X] Stream::take_producer(Self[X]) -> (async (Sink[X]) -> Unit)?
pub struct Task[X] {
// private fields
}
pub fn[X] Task::cancel(Self[X]) -> Unit
pub fn[X] Task::try_wait(Self[X]) -> X? raise
pub async fn[X] Task::wait(Self[X]) -> X
pub struct TaskGroup[X] {
// private fields
}
pub fn[X] TaskGroup::add_defer(Self[X], async () -> Unit nocancel) -> Unit
pub async fn[X] TaskGroup::return_immediately(Self[X], X) -> Unit noraise
pub fn[G, X] TaskGroup::spawn(Self[G], async () -> X, no_wait? : Bool, allow_failure? : Bool) -> Task[X]
pub fn[X] TaskGroup::spawn_bg(Self[X], async () -> Unit, no_wait? : Bool, allow_failure? : Bool) -> Unit
#derive(Eq, Hash)
type WaitableSet
#deprecated
pub fn WaitableSet::equal(Self, Self) -> Bool
#deprecated
pub fn WaitableSet::hash(Self) -> Int32
#deprecated
pub fn WaitableSet::hash_combine(Self, Hasher) -> Unit
#deprecated
pub fn WaitableSet::not_equal(Self, Self) -> Bool
// Type aliases
// Traits
+1
View File
@@ -0,0 +1 @@
// Generated by `wit-bindgen` 0.63.0. DO NOT EDIT!