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 let progress = idle.progress();
138 if let Err(error) = idle.wait(progress, self.source) {
139 return Attempt::Cancel(root, error.into());
140 }
141 }
142 };
143 Attempt::Complete(loop {
144 let idle = match polled.park() {
145 Ok(ControlFlow::Continue(idle)) => idle,
146 Ok(ControlFlow::Break(())) => break Err(drive::Error::Shutdown),
147 Err(error) => break Err(error.into()),
148 };
149 if let Some(idle) = idle {
150 let progress = idle.progress();
151 if matches!(progress, schedule::Progress::Quiescent) {
152 match idle.sync() {
153 Ok(poll::Commit::Drained) => break Ok(output),
154 Ok(poll::Commit::Pending) => {}
155 Err(error) => break Err(error.into()),
156 }
157 } else if let Err(error) = idle.wait(progress, self.source) {
158 break Err(error.into());
159 }
160 }
161 let tick = self.source.start();
162 polled = match self.state.next_root(&self.slot, tick, &mut shutdown) {
163 Ok(ready) => ready.skip(),
164 Err(error) => break Err(error),
165 };
166 })
167 }
168}
169
170impl<'d, T, C> Block<'d, T, C> {
171 pub(crate) fn new(
172 driver: driver::Reference<'d>,
173 state: T,
174 source: C,
175 ) -> Result<Self, drive::Error> {
176 let target = driver
177 .targets::<routes::Wake>()
178 .bind(indices::SlotIndex::ZERO, route::Epoch::INITIAL);
179 let slot = driver.ready().make_slot(target.dispatch())?;
180 Ok(Self {
181 state,
182 source,
183 slot,
184 })
185 }
186}
187
188impl<'run, 'driver, 'app, 'd: 'app, D, S, C>
189 Block<'d, scope::Scope<'run, 'driver, 'app, 'd, D, S>, C>
190where
191 D: executor::raw::App<'d>,
192 C: clock::Time,
193{
194 pub(crate) fn run<R>(
195 self,
196 root: R,
197 tick: impl Fn(C) -> Result<Sample, drive::Error>,
198 shutdown: impl FnMut() -> turn::Status,
199 ) -> Result<R::Output, drive::Error>
200 where
201 R: root::Root<'d>,
202 {
203 let (output, ()) = self
204 .drive(root, tick, shutdown, |idle| {
205 Ok(matches!(idle.sync()?, poll::Commit::Drained).then_some(()))
206 })?
207 .complete()?;
208 Ok(output)
209 }
210
211 pub(crate) fn run_until<R>(
212 self,
213 root: R,
214 tick: impl Fn(C) -> Result<Sample, drive::Error>,
215 shutdown: impl FnMut() -> turn::Status,
216 ) -> Result<ControlFlow<R::Output>, drive::Error>
217 where
218 R: root::Root<'d>,
219 {
220 Ok(
221 match self.drive(root, tick, shutdown, |idle| {
222 Ok(matches!(idle.sync()?, poll::Commit::Drained).then_some(()))
223 })? {
224 Outcome::Complete(output, ()) | Outcome::Shutdown(Some(output)) => {
225 ControlFlow::Break(output)
226 }
227 Outcome::Shutdown(None) => ControlFlow::Continue(()),
228 },
229 )
230 }
231
232 pub(crate) fn run_fixed<R>(
233 self,
234 root: R,
235 tick: impl Fn(C) -> Result<Sample, drive::Error>,
236 shutdown: impl FnMut() -> turn::Status,
237 ) -> Result<Fixed<'d, R::Output>, drive::Error>
238 where
239 R: root::Root<'d>,
240 {
241 let (output, now) = self
242 .drive(root, tick, shutdown, |idle| {
243 let fixed = idle.is_fixed();
244 let now = idle.now();
245 let commit = idle.sync()?;
246 Ok((fixed && matches!(commit, poll::Commit::Drained)).then_some(now))
247 })?
248 .complete()?;
249 Ok(Fixed::new(output, now))
250 }
251
252 fn drive<R, P>(
253 mut self,
254 root: R,
255 tick: impl Fn(C) -> Result<Sample, drive::Error>,
256 mut shutdown: impl FnMut() -> turn::Status,
257 complete: impl for<'turn> Fn(
258 turn::Idle<'turn, 'd, modes::App<'turn, 'app, 'd, D, S>>,
259 ) -> Result<Option<P>, drive::Error>,
260 ) -> Result<Outcome<R::Output, P>, drive::Error>
261 where
262 R: root::Root<'d>,
263 {
264 let wake = self.slot.target();
265 let (mut polled, output) = {
266 let mut root = pin::pin!(root);
267 let mut first = true;
268 loop {
269 let tick = tick(self.source)?;
270 let ready = self.state.next_root(&self.slot, tick, &mut shutdown)?;
271 let poll = first || ready.is_root();
272 let (polled, output) = if poll {
273 ready.poll(root.as_mut(), wake)
274 } else {
275 (ready.skip(), task::Poll::Pending)
276 };
277 first = false;
278 match output {
279 task::Poll::Ready(output) => break (polled, output),
280 task::Poll::Pending => match polled.park()? {
281 ControlFlow::Break(()) => return Ok(Outcome::Shutdown(None)),
282 ControlFlow::Continue(Some(idle)) => {
283 let progress = idle.progress();
284 idle.wait(progress, self.source)?;
285 }
286 ControlFlow::Continue(None) => {}
287 },
288 }
289 }
290 };
291 loop {
292 match polled.park()? {
293 ControlFlow::Break(()) => return Ok(Outcome::Shutdown(Some(output))),
294 ControlFlow::Continue(Some(idle)) => {
295 if let Some(proof) = complete(idle)? {
296 return Ok(Outcome::Complete(output, proof));
297 }
298 }
299 ControlFlow::Continue(None) => {}
300 }
301 let tick = tick(self.source)?;
302 polled = self.state.next_app(tick, &mut shutdown)?;
303 }
304 }
305}