Skip to main content

logicaffeine_compile/concurrency/
vm_driver.rs

1//! The VM task driver (T11).
2//!
3//! [`VmTask`] wraps one resumable [`Vm`] as a scheduler [`Task`]. On each `poll`
4//! it delivers the scheduler's resume value into the VM's reserved register, runs
5//! the VM until its next concurrency op (`run_until_block`), drains any output the
6//! slice produced into a shared sink, and maps the VM's `VmBlock` request to a
7//! scheduler [`TaskStep`]. It mirrors the tree-walker's
8//! [`super::driver::InterpreterTask`].
9
10use std::cell::RefCell;
11use std::rc::Rc;
12
13use logicaffeine_runtime::{RtPayload, Task, TaskCtx, TaskStep};
14
15use crate::interpreter::RuntimeValue;
16use crate::vm::{Value, Vm, VmBlock, VmStep};
17
18use super::driver::ErrSink;
19use super::marshal;
20
21/// Where a VM task's `Show` output goes — the one place the cooperative and
22/// work-stealing drivers diverge.
23enum OutputMode {
24    /// Cooperative (M:1): every task drains into one shared sink on the single
25    /// thread, so per-task slices interleave in pick order directly.
26    Shared(Rc<RefCell<Vec<String>>>),
27    /// Work-stealing (M:N): a worker polls task bodies off-thread, so output is
28    /// buffered locally and reported per-slice via [`Task::take_output`]; the
29    /// coordinator re-orders the slices into pick order on its thread.
30    Buffered(Vec<String>),
31}
32
33/// Drives one VM task on the scheduler. `err_sink` (first writer wins) receives
34/// the task's error if it fails.
35pub struct VmTask<'p> {
36    vm: Vm<'p>,
37    output: OutputMode,
38    err_sink: Option<ErrSink>,
39}
40
41impl<'p> VmTask<'p> {
42    /// A cooperative task draining into the shared `output` sink.
43    pub fn new(vm: Vm<'p>, output: Rc<RefCell<Vec<String>>>, err_sink: Option<ErrSink>) -> Self {
44        VmTask {
45            vm,
46            output: OutputMode::Shared(output),
47            err_sink,
48        }
49    }
50
51    /// A work-stealing task: output buffers locally (reported via `take_output`),
52    /// and a spawn forwards a `SpawnDesc` the worker rebuilds — never a boxed body
53    /// (which is `!Send` and could not cross a worker boundary anyway).
54    pub fn work_stealing(vm: Vm<'p>, err_sink: Option<ErrSink>) -> Self {
55        VmTask {
56            vm,
57            output: OutputMode::Buffered(Vec::new()),
58            err_sink,
59        }
60    }
61
62    fn block_to_step(&self, req: VmBlock) -> TaskStep<'p> {
63        match req {
64            VmBlock::NewChan(cap) => TaskStep::NewChan(cap),
65            VmBlock::Send(ch, p) => TaskStep::Send(ch, p),
66            VmBlock::Recv(ch) => TaskStep::Recv(ch),
67            VmBlock::TrySend(ch, p) => TaskStep::TrySend(ch, p),
68            VmBlock::TryRecv(ch) => TaskStep::TryRecv(ch),
69            VmBlock::Close(ch) => TaskStep::Close(ch),
70            VmBlock::SpawnDesc {
71                func,
72                args,
73                want_handle,
74            } => match &self.output {
75                // Cooperative: build the child VM inline over the shared program +
76                // sink, and hand the scheduler the boxed body.
77                OutputMode::Shared(sink) => {
78                    let child_vm = self.vm.spawn_task_vm(func, &args);
79                    let child = VmTask::new(child_vm, sink.clone(), self.err_sink.clone());
80                    TaskStep::Spawn(Box::new(child))
81                }
82                // Work-stealing: forward the `Send` descriptor; the receiving
83                // worker builds the child locally over its own program borrow.
84                OutputMode::Buffered(_) => TaskStep::SpawnDesc {
85                    func,
86                    args,
87                    want_handle,
88                },
89            },
90            VmBlock::Await(t) => TaskStep::Await(t),
91            VmBlock::Abort(t) => TaskStep::Abort(t),
92            VmBlock::Select(arms) => TaskStep::Select(arms),
93            VmBlock::Sleep(d) => TaskStep::Sleep(d),
94            // Peer networking never reaches this cooperative-scheduler driver: a program that
95            // networks routes to the dedicated async VM runner (`run_vm_net_async`), which owns a
96            // `NetInbox` and services these directly. Defensive `IoPending` if it ever does.
97            VmBlock::NetConnect(_)
98            | VmBlock::NetListen(_)
99            | VmBlock::NetSend(_, _)
100            | VmBlock::NetStream(_, _)
101            | VmBlock::NetAwait(_, _)
102            | VmBlock::NetMakePeer(_)
103            | VmBlock::NetSync(_, _)
104            | VmBlock::Tcp(_, _)
105            | VmBlock::Serve(_, _) => TaskStep::IoPending,
106        }
107    }
108}
109
110impl<'p> Task<'p> for VmTask<'p> {
111    fn poll(&mut self, ctx: &mut TaskCtx) -> TaskStep<'p> {
112        // Deliver whatever the scheduler resumed us with. A resolved `Select`
113        // routes the received value into the winning arm's var and the arm index
114        // into the `SelectWait` destination; every other block delivers a single
115        // value into the reserved register.
116        if let Some(arm) = ctx.selected_arm.take() {
117            let payload = std::mem::replace(&mut ctx.resumed_with, RtPayload::Nothing);
118            self.vm
119                .deliver_select(arm, Value::from_runtime(marshal::rebuild(payload)));
120        } else {
121            let resume = ctx_to_value(ctx);
122            self.vm.deliver_resume(resume);
123        }
124
125        let step = self.vm.run_until_block();
126
127        // Stream this slice's output. Cooperative drains straight into the shared
128        // sink; work-stealing buffers locally for the coordinator to flush in pick
129        // order (see [`Task::take_output`]).
130        let lines = self.vm.drain_lines();
131        if !lines.is_empty() {
132            match &mut self.output {
133                OutputMode::Shared(sink) => sink.borrow_mut().extend(lines),
134                OutputMode::Buffered(buf) => buf.extend(lines),
135            }
136        }
137
138        match step {
139            Ok(VmStep::Done(result)) => {
140                let payload = marshal::materialize(&result).unwrap_or(RtPayload::Nothing);
141                TaskStep::Exit(payload)
142            }
143            Ok(VmStep::Blocked) => {
144                let req = self
145                    .vm
146                    .take_pending()
147                    .expect("a blocked VM slice must leave a pending request");
148                self.block_to_step(req)
149            }
150            Ok(VmStep::Paused) => {
151                unreachable!(
152                    "the driver uses run_until_block; the debug stepper is never driven here"
153                )
154            }
155            Err(e) => {
156                if let Some(sink) = &self.err_sink {
157                    let mut slot = sink.borrow_mut();
158                    if slot.is_none() {
159                        *slot = Some(e);
160                    }
161                }
162                TaskStep::Exit(RtPayload::Nothing)
163            }
164        }
165    }
166
167    /// Hand the work-stealing coordinator this slice's buffered output so it can
168    /// be flushed in pick order. A no-op for cooperative tasks (they drain into
169    /// the shared sink directly).
170    fn take_output(&mut self) -> Vec<String> {
171        match &mut self.output {
172            OutputMode::Buffered(buf) => std::mem::take(buf),
173            OutputMode::Shared(_) => Vec::new(),
174        }
175    }
176}
177
178/// Translate the scheduler's resume context into the VM resume value: a freshly
179/// created channel id, a spawned task handle, or a received/awaited payload.
180fn ctx_to_value(ctx: &mut TaskCtx) -> Value {
181    if let Some(id) = ctx.new_chan {
182        Value::from_runtime(RuntimeValue::Chan(id))
183    } else if let Some(id) = ctx.spawned {
184        Value::from_runtime(RuntimeValue::TaskHandle(id))
185    } else {
186        let payload = std::mem::replace(&mut ctx.resumed_with, RtPayload::Nothing);
187        Value::from_runtime(marshal::rebuild(payload))
188    }
189}