1use std::{mem, ops::ControlFlow, pin, task};
2
3use dope_core::driver::{self, result::poll, route, route::indices, schedule, schedule::ready};
4use drive::{clock, turn};
5use schedule::clock::{Moment, Sample};
6use turn::{modes, routes, scope};
7
8use crate::executor::{self, boot, drive, root};
9
10#[must_use = "fixed-point evidence and its root output must be observed"]
12pub struct Fixed<'d, T> {
13 output: T,
14 now: Moment<'d>,
15}
16
17impl<'d, T> Fixed<'d, T> {
18 pub(crate) const fn new(output: T, now: Moment<'d>) -> Self {
19 Self { output, now }
20 }
21
22 pub const fn output(&self) -> &T {
23 &self.output
24 }
25
26 pub fn into_output(self) -> T {
27 self.output
28 }
29
30 pub const fn now(&self) -> Moment<'d> {
31 self.now
32 }
33}
34
35const _: () = {
36 assert!(mem::size_of::<Fixed<'_, ()>>() == mem::size_of::<Moment<'_>>());
37 assert!(mem::align_of::<Fixed<'_, ()>>() == mem::align_of::<Moment<'_>>());
38};
39
40pub(crate) struct Block<'d, T, C> {
41 state: T,
42 source: C,
43 slot: ready::Slot<'d, routes::Wake>,
44}
45
46enum Attempt<R, O> {
47 Complete(Result<O, drive::Error>),
48 Cancel(R, drive::Error),
49}
50
51enum Outcome<O, P> {
52 Complete(O, P),
53 Shutdown(Option<O>),
54}
55
56impl<O, P> Outcome<O, P> {
57 fn complete(self) -> Result<(O, P), drive::Error> {
58 match self {
59 Self::Complete(output, proof) => Ok((output, proof)),
60 Self::Shutdown(_) => Err(drive::Error::Shutdown),
61 }
62 }
63}
64
65impl<R, O> Attempt<R, O> {
66 fn finish<'d>(self) -> Result<O, drive::Error>
67 where
68 R: boot::Root<'d, Output = O>,
69 {
70 match self {
71 Self::Complete(result) => result,
72 Self::Cancel(root, source) => {
73 R::cancel(root);
74 Err(source)
75 }
76 }
77 }
78}
79
80impl<'run, 'driver, 'd, C> Block<'d, scope::Boot<'run, 'driver, 'd>, C>
81where
82 C: clock::Source,
83{
84 pub(crate) fn run_boot<R>(
85 start: Result<Self, drive::Error>,
86 root: R,
87 shutdown: impl FnMut() -> turn::Status,
88 ) -> Result<R::Output, drive::Error>
89 where
90 R: boot::Root<'d>,
91 {
92 match start {
93 Ok(block) => block.poll_boot(root, shutdown),
94 Err(source) => Attempt::Cancel(root, source),
95 }
96 .finish()
97 }
98
99 fn poll_boot<R>(
100 mut self,
101 mut root: R,
102 mut shutdown: impl FnMut() -> turn::Status,
103 ) -> Attempt<R, R::Output>
104 where
105 R: boot::Root<'d>,
106 {
107 let wake = self.slot.target();
108 let (mut polled, output) = {
109 let mut cause = boot::Cause::Start;
110 loop {
111 let tick = self.source.start();
112 let ready = match self.state.next_root(&self.slot, tick, &mut shutdown) {
113 Ok(ready) => ready,
114 Err(source) => return Attempt::Cancel(root, source),
115 };
116 let polled = if matches!(cause, boot::Cause::Start) || ready.is_root() {
117 let (polled, output) = ready.poll_boot(root, wake, cause);
118 match output {
119 boot::Poll::Pending(next) => {
120 root = next;
121 polled
122 }
123 boot::Poll::Ready(output) => break (polled, output),
124 }
125 } else {
126 ready.skip()
127 };
128 cause = boot::Cause::Wake;
129 let idle = match polled.park() {
130 Ok(ControlFlow::Continue(Some(idle))) => idle,
131 Ok(ControlFlow::Continue(None)) => continue,
132 Ok(ControlFlow::Break(())) => {
133 return Attempt::Cancel(root, drive::Error::Shutdown);
134 }
135 Err(error) => return Attempt::Cancel(root, error.into()),
136 };
137 if let Err(error) = idle.wait(|idle| idle.progress(), self.source) {
138 return Attempt::Cancel(root, error.into());
139 }
140 }
141 };
142 Attempt::Complete(loop {
143 let idle = match polled.park() {
144 Ok(ControlFlow::Continue(idle)) => idle,
145 Ok(ControlFlow::Break(())) => break Err(drive::Error::Shutdown),
146 Err(error) => break Err(error.into()),
147 };
148 if let Some(idle) = idle {
149 let progress = idle.progress();
150 if matches!(progress, schedule::Progress::Quiescent) {
151 match idle.sync() {
152 Ok(poll::Commit::Drained) => break Ok(output),
153 Ok(poll::Commit::Pending) => {}
154 Err(error) => break Err(error.into()),
155 }
156 } else if let Err(error) = idle.wait(|_| progress, self.source) {
157 break Err(error.into());
158 }
159 }
160 let tick = self.source.start();
161 polled = match self.state.next_root(&self.slot, tick, &mut shutdown) {
162 Ok(ready) => ready.skip(),
163 Err(error) => break Err(error),
164 };
165 })
166 }
167}
168
169impl<'d, T, C> Block<'d, T, C> {
170 pub(crate) fn new(
171 driver: driver::Reference<'d>,
172 state: T,
173 source: C,
174 ) -> Result<Self, drive::Error> {
175 let target = driver
176 .targets::<routes::Wake>()
177 .bind(indices::SlotIndex::ZERO, route::Epoch::INITIAL);
178 let slot = driver.ready().make_slot(target.dispatch())?;
179 Ok(Self {
180 state,
181 source,
182 slot,
183 })
184 }
185}
186
187impl<'run, 'driver, 'app, 'd: 'app, D, S, C>
188 Block<'d, scope::Scope<'run, 'driver, 'app, 'd, D, S>, C>
189where
190 D: executor::raw::App<'d>,
191 C: clock::Time,
192{
193 pub(crate) fn run<R>(
194 self,
195 root: R,
196 tick: impl Fn(C) -> Result<Sample, drive::Error>,
197 shutdown: impl FnMut() -> turn::Status,
198 ) -> Result<R::Output, drive::Error>
199 where
200 R: root::Root<'d>,
201 {
202 let (output, ()) = self
203 .drive(root, tick, shutdown, |idle| {
204 Ok(matches!(idle.sync()?, poll::Commit::Drained).then_some(()))
205 })?
206 .complete()?;
207 Ok(output)
208 }
209
210 pub(crate) fn run_until<R>(
211 self,
212 root: R,
213 tick: impl Fn(C) -> Result<Sample, drive::Error>,
214 shutdown: impl FnMut() -> turn::Status,
215 ) -> Result<ControlFlow<R::Output>, drive::Error>
216 where
217 R: root::Root<'d>,
218 {
219 Ok(
220 match self.drive(root, tick, shutdown, |idle| {
221 Ok(matches!(idle.sync()?, poll::Commit::Drained).then_some(()))
222 })? {
223 Outcome::Complete(output, ()) | Outcome::Shutdown(Some(output)) => {
224 ControlFlow::Break(output)
225 }
226 Outcome::Shutdown(None) => ControlFlow::Continue(()),
227 },
228 )
229 }
230
231 pub(crate) fn run_fixed<R>(
232 self,
233 root: R,
234 tick: impl Fn(C) -> Result<Sample, drive::Error>,
235 shutdown: impl FnMut() -> turn::Status,
236 ) -> Result<Fixed<'d, R::Output>, drive::Error>
237 where
238 R: root::Root<'d>,
239 {
240 let (output, now) = self
241 .drive(root, tick, shutdown, |idle| {
242 let fixed = idle.is_fixed();
243 let now = idle.now();
244 let commit = idle.sync()?;
245 Ok((fixed && matches!(commit, poll::Commit::Drained)).then_some(now))
246 })?
247 .complete()?;
248 Ok(Fixed::new(output, now))
249 }
250
251 fn drive<R, P>(
252 mut self,
253 root: R,
254 tick: impl Fn(C) -> Result<Sample, drive::Error>,
255 mut shutdown: impl FnMut() -> turn::Status,
256 complete: impl for<'turn> Fn(
257 turn::Idle<'turn, 'd, modes::App<'turn, 'app, 'd, D, S>>,
258 ) -> Result<Option<P>, drive::Error>,
259 ) -> Result<Outcome<R::Output, P>, drive::Error>
260 where
261 R: root::Root<'d>,
262 {
263 let wake = self.slot.target();
264 let (mut polled, output) = {
265 let mut root = pin::pin!(root);
266 let mut first = true;
267 loop {
268 let tick = tick(self.source)?;
269 let ready = self.state.next_root(&self.slot, tick, &mut shutdown)?;
270 let poll = first || ready.is_root();
271 let (polled, output) = if poll {
272 ready.poll(root.as_mut(), wake)
273 } else {
274 (ready.skip(), task::Poll::Pending)
275 };
276 first = false;
277 match output {
278 task::Poll::Ready(output) => break (polled, output),
279 task::Poll::Pending => match polled.park()? {
280 ControlFlow::Break(()) => return Ok(Outcome::Shutdown(None)),
281 ControlFlow::Continue(Some(idle)) => {
282 idle.wait(|idle| idle.progress(), self.source)?;
283 }
284 ControlFlow::Continue(None) => {}
285 },
286 }
287 }
288 };
289 loop {
290 match polled.park()? {
291 ControlFlow::Break(()) => return Ok(Outcome::Shutdown(Some(output))),
292 ControlFlow::Continue(Some(idle)) => {
293 if let Some(proof) = complete(idle)? {
294 return Ok(Outcome::Complete(output, proof));
295 }
296 }
297 ControlFlow::Continue(None) => {}
298 }
299 let tick = tick(self.source)?;
300 polled = self.state.next_app(tick, &mut shutdown)?;
301 }
302 }
303}