1use std::collections::HashMap;
2use std::process::ExitStatus;
3use std::sync::Arc;
4use std::sync::Mutex;
5use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6
7use anyhow::{Result, bail};
8use oxdock_fs::GuardedPath;
9use oxdock_parser::{Arg, AssertTarget, Step, StepKind, Value, guard_option_allows};
10use oxdock_process::{BackgroundHandle, CommandStdin, ProcessManager, SharedInput, SharedOutput};
11
12fn exit_status_from_code(code: i32) -> ExitStatus {
14 #[cfg(unix)]
15 {
16 use std::os::unix::process::ExitStatusExt;
17 ExitStatus::from_raw(code << 8)
18 }
19 #[cfg(windows)]
20 {
21 use std::os::windows::process::ExitStatusExt;
22 ExitStatus::from_raw(code as u32)
23 }
24}
25
26use super::handlers;
27use super::io::{ExactCapture, SlidingWindow, StreamHandle};
28use super::native::PureTable;
29use super::state::{ExecState, TaskEntry, TaskPhase};
30use oxdock_pipe::PipeInner;
31
32pub(super) struct ThreadJoinHandle {
35 join: Option<std::thread::JoinHandle<Result<()>>>,
36 cancel_token: Arc<AtomicBool>,
37 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
38 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
46 thread_error: Option<anyhow::Error>,
48 thread_exit_code: Option<i64>,
52}
53
54impl ThreadJoinHandle {
55 pub(super) fn new(
56 join: std::thread::JoinHandle<Result<()>>,
57 cancel_token: Arc<AtomicBool>,
58 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
59 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
60 ) -> Self {
61 Self {
62 join: Some(join),
63 cancel_token,
64 active_process,
65 worker,
66 thread_error: None,
67 thread_exit_code: None,
68 }
69 }
70
71 fn reemit_error(&self) -> anyhow::Error {
77 let msg = self
78 .thread_error
79 .as_ref()
80 .map(|err| format!("{err:#}"))
81 .unwrap_or_else(|| "background thread failed without an error".to_string());
82 match self.thread_exit_code {
83 Some(code) => anyhow::Error::new(super::exit::ExitRequest(code)).context(msg),
84 None => anyhow::anyhow!("{msg}"),
85 }
86 }
87
88 fn is_self(&self) -> bool {
90 let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
91 guard.is_some_and(|id| id == std::thread::current().id())
92 }
93
94 fn reap(&mut self) {
96 if self.join.is_none() {
97 return;
98 }
99 if self.is_self() {
100 let _ = self.join.take();
104 return;
105 }
106 let handle = self.join.take().unwrap();
107 match handle.join() {
108 Ok(Ok(())) => {}
109 Ok(Err(e)) => {
110 self.thread_exit_code = super::exit::exit_code_of(&e);
111 self.thread_error = Some(e);
112 }
113 Err(panic) => {
114 let msg = if let Some(s) = panic.downcast_ref::<&str>() {
115 s.to_string()
116 } else if let Some(s) = panic.downcast_ref::<String>() {
117 s.clone()
118 } else {
119 "thread panicked".to_string()
120 };
121 self.thread_error = Some(anyhow::anyhow!("{msg}"));
122 }
123 }
124 }
125}
126
127impl BackgroundHandle for ThreadJoinHandle {
128 fn try_wait(&mut self) -> Result<Option<ExitStatus>> {
129 if let Some(join) = &self.join {
130 if join.is_finished() {
131 self.reap();
132 } else {
133 return Ok(None);
134 }
135 }
136 if self.thread_error.is_some() {
142 Err(self.reemit_error())
143 } else {
144 Ok(Some(exit_status_from_code(0)))
145 }
146 }
147
148 fn kill(&mut self) -> Result<()> {
149 self.cancel_token.store(true, Ordering::SeqCst);
151 if let Ok(mut guard) = self.active_process.lock()
153 && let Some(ref mut proc) = *guard
154 {
155 let _ = proc.kill();
156 }
157 self.reap();
159 Ok(())
160 }
161
162 fn wait(&mut self) -> Result<ExitStatus> {
163 self.reap();
164 if self.thread_error.is_some() {
166 Err(self.reemit_error())
167 } else {
168 Ok(exit_status_from_code(0))
169 }
170 }
171}
172
173impl Drop for ThreadJoinHandle {
174 fn drop(&mut self) {
175 let _ = self.kill();
176 }
177}
178
179static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
183
184#[derive(Debug)]
191pub(super) enum Flow {
192 Done,
193 Break { idx: usize },
194 Continue { idx: usize },
195 Return { idx: usize, value: Value },
196}
197
198pub(super) fn allocate_assert_generation() -> usize {
199 ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
200}
201
202#[derive(Clone, Copy, PartialEq, Eq)]
204pub(super) enum AssertStream {
205 Stdout,
206 Stderr,
207}
208
209fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
213 let step = match kind {
214 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
215 other => other,
216 };
217 match step {
218 StepKind::AssertContains { haystack, needle } => match haystack {
219 AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
220 AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
221 _ => None,
222 },
223 _ => None,
224 }
225}
226
227fn needs_exact_stdout(kind: &StepKind) -> bool {
230 let step = match kind {
231 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
232 other => other,
233 };
234 matches!(
235 step,
236 StepKind::AssertEq {
237 actual: AssertTarget::Stdout,
238 ..
239 }
240 )
241}
242
243pub(super) enum ResolvedAssertTarget {
246 Value(Value),
247 Stdout,
248 Stderr,
249 Pipe(Vec<u8>),
250}
251
252pub(super) fn resolve_assert_target<P: ProcessManager>(
258 target: &AssertTarget,
259 cx: &mut StepCtx<'_, P>,
260) -> Result<ResolvedAssertTarget> {
261 match target {
262 AssertTarget::Value(arg) => {
263 let value = super::args::evaluate_assert_operand(arg, cx)?;
264 if let Some(handle) = value.as_pipe_handle() {
265 let bytes =
266 cx.state.io.peek_pipe_content(&handle).map_err(|e| {
267 anyhow::anyhow!("step pipe assertion cannot read pipe: {e}")
268 })?;
269 return Ok(ResolvedAssertTarget::Pipe(bytes));
270 }
271 Ok(ResolvedAssertTarget::Value(value))
272 }
273 AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
274 AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
275 }
276}
277
278pub(super) fn pre_register_assertions<P: ProcessManager>(
285 state: &mut ExecState<P>,
286 steps: &[Step],
287 generation: usize,
288) -> Result<()> {
289 let mut windows = match state.assert_windows.lock() {
290 Ok(guard) => guard,
291 Err(_) => bail!("assert_windows poisoned"),
292 };
293 let mut stderr_windows = match state.assert_windows_stderr.lock() {
294 Ok(guard) => guard,
295 Err(_) => bail!("assert_windows_stderr poisoned"),
296 };
297 let mut exact = match state.exact_stdout.lock() {
298 Ok(guard) => guard,
299 Err(_) => bail!("exact_stdout poisoned"),
300 };
301 for (idx, step) in steps.iter().enumerate() {
302 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
303 let resolved = super::args::resolve_arg_state(arg, state)?;
304 let map = match stream {
305 AssertStream::Stdout => &mut windows,
306 AssertStream::Stderr => &mut stderr_windows,
307 };
308 map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
309 }
310 if needs_exact_stdout(&step.kind) {
311 exact.entry(generation).or_insert_with(ExactCapture::new);
312 }
313 }
314 Ok(())
315}
316
317#[allow(clippy::collapsible_if)]
323pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
324 state: &ExecState<P>,
325 steps: &[Step],
326 generation: usize,
327) -> Result<()> {
328 let mut windows = match state.assert_windows.lock() {
329 Ok(guard) => guard,
330 Err(_) => bail!("assert_windows poisoned"),
331 };
332 let mut stderr_windows = match state.assert_windows_stderr.lock() {
333 Ok(guard) => guard,
334 Err(_) => bail!("assert_windows_stderr poisoned"),
335 };
336 for (idx, step) in steps.iter().enumerate() {
337 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
338 let map = match stream {
339 AssertStream::Stdout => &mut windows,
340 AssertStream::Stderr => &mut stderr_windows,
341 };
342 if let Some(w) = map.get_mut(&(generation, idx)) {
343 let resolved = super::args::resolve_arg_state(arg, state)?;
344 w.update_needle(resolved.into_bytes());
345 }
346 }
347 }
348 Ok(())
349}
350
351pub struct StepCtx<'a, P: ProcessManager> {
364 pub(super) state: &'a mut ExecState<P>,
365 pub(super) process: &'a mut P,
366 pub(super) stdin: CommandStdin,
367 pub(super) expose_stdin: bool,
368 pub(super) out: Option<StreamHandle>,
369 pub(super) err: Option<StreamHandle>,
370 pub(super) out_pipe: Option<Arc<PipeInner>>,
376 pub(super) stdin_pipe: Option<Arc<PipeInner>>,
381}
382
383impl<'a, P: ProcessManager> StepCtx<'a, P> {
384 pub(super) fn err_shared(&self) -> Option<SharedOutput> {
388 match self.err.clone() {
389 Some(StreamHandle::Stream(writer)) => Some(writer),
390 _ => None,
391 }
392 }
393
394 pub fn get_var(&self, key: &str) -> Option<Value> {
396 self.state.get_var(key)
397 }
398
399 pub fn get_env(&self, key: &str) -> Option<String> {
401 self.state.envs.get(key).cloned()
402 }
403
404 pub fn env_snapshot(&self) -> HashMap<String, String> {
411 self.state.envs.as_ref().clone()
412 }
413
414 pub fn cwd(&self) -> &GuardedPath {
416 &self.state.cwd
417 }
418
419 pub fn pure_functions(&self) -> std::sync::Arc<PureTable> {
426 self.state.pure_function_table()
427 }
428
429 pub fn new_pipe(&self) -> Value {
434 Value::pipe_fresh_in_task(self.state.task_id)
435 }
436
437 pub fn pipe_reader(&self, value: &Value) -> Result<SharedInput> {
446 use oxdock_pipe::{Materialized, materialize};
447 let Some(handle) = value.as_pipe_handle() else {
448 anyhow::bail!(
449 "host pipe_reader needs a PIPE value, got {}",
450 value.type_name()
451 );
452 };
453 match materialize(&handle, false)? {
454 Materialized::Script(backend) => Ok(backend.reader_handle()),
455 #[cfg(not(miri))]
456 Materialized::Os(entry) => {
457 let owned = entry.reader.take().map_err(|_| {
458 anyhow::anyhow!(
459 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
460 )
461 })?;
462 Ok(Arc::new(Mutex::new(owned)))
463 }
464 }
465 }
466
467 pub fn pipe_writer(&self, value: &Value) -> Result<SharedOutput> {
471 use oxdock_pipe::{Materialized, materialize};
472 let Some(handle) = value.as_pipe_handle() else {
473 anyhow::bail!(
474 "host pipe_writer needs a PIPE value, got {}",
475 value.type_name()
476 );
477 };
478 match materialize(&handle, false)? {
479 Materialized::Script(backend) => Ok(backend.writer_handle()),
480 #[cfg(not(miri))]
481 Materialized::Os(entry) => {
482 let owned = entry.writer.take().map_err(|_| {
483 anyhow::anyhow!(
484 "OS pipe handle has already been consumed by another binding; declare a fresh LET $x: PIPE for a new session"
485 )
486 })?;
487 Ok(Arc::new(Mutex::new(owned)))
488 }
489 }
490 }
491
492 pub fn close_pipe(&self, value: &Value) -> Result<()> {
498 let Some(handle) = value.as_pipe_handle() else {
499 anyhow::bail!(
500 "host close_pipe needs a PIPE value, got {}",
501 value.type_name()
502 );
503 };
504 let Some(backend) = oxdock_pipe::script_backend(&handle) else {
505 anyhow::bail!(
506 "host close_pipe needs a script-materialized pipe (unbound and OS handles cannot be force-closed)"
507 );
508 };
509 backend.force_close();
510 Ok(())
511 }
512
513 pub fn is_cancelled(&self) -> bool {
517 self.state
518 .cancel_token
519 .load(std::sync::atomic::Ordering::SeqCst)
520 }
521
522 pub fn is_async_task(&self) -> bool {
525 self.state.inside_async
526 }
527
528 pub fn module_state<T: Send + Sync + 'static>(
534 &self,
535 module: &str,
536 ) -> Option<std::sync::Arc<T>> {
537 self.state
538 .module_states
539 .get(&(module.to_string(), std::any::TypeId::of::<T>()))?
540 .clone()
541 .downcast::<T>()
542 .ok()
543 }
544
545 pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
552 let handle = value.as_pipe_handle()?;
553 oxdock_pipe::script_backend(&handle)
554 }
555}
556
557#[allow(clippy::too_many_arguments)]
558pub(super) fn execute_steps<P: ProcessManager>(
559 state: &mut ExecState<P>,
560 process: &mut P,
561 steps: &[Step],
562 stdin: CommandStdin,
563 expose_stdin: bool,
564 out: Option<StreamHandle>,
565 err: Option<StreamHandle>,
566 out_pipe: Option<Arc<PipeInner>>,
567 stdin_pipe: Option<Arc<PipeInner>>,
568 wait_at_end: bool,
569) -> Result<Flow> {
570 let generation = allocate_assert_generation();
571 let flow = match execute_steps_inner(
572 state,
573 process,
574 generation,
575 steps,
576 stdin,
577 expose_stdin,
578 out,
579 err,
580 out_pipe,
581 stdin_pipe,
582 wait_at_end,
583 ) {
584 Ok(flow) => flow,
585 Err(e) => {
586 teardown_tasks_on_error(state);
592 cleanup_assertion_generation(state, generation)?;
593 return Err(e);
594 }
595 };
596 cleanup_assertion_generation(state, generation)?;
598 Ok(flow)
599}
600
601fn cleanup_assertion_generation<P: ProcessManager>(
604 state: &mut ExecState<P>,
605 generation: usize,
606) -> Result<()> {
607 let mut windows = match state.assert_windows.lock() {
608 Ok(guard) => guard,
609 Err(_) => bail!("assert_windows poisoned"),
610 };
611 windows.retain(|(g, _), _| *g != generation);
612 let mut stderr_windows = match state.assert_windows_stderr.lock() {
613 Ok(guard) => guard,
614 Err(_) => bail!("assert_windows_stderr poisoned"),
615 };
616 stderr_windows.retain(|(g, _), _| *g != generation);
617 let mut exact = match state.exact_stdout.lock() {
618 Ok(guard) => guard,
619 Err(_) => bail!("exact_stdout poisoned"),
620 };
621 exact.retain(|g, _| *g != generation);
622 Ok(())
623}
624
625fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
630 for survivor in state.bg_children.iter_mut() {
631 let _ = survivor.kill();
632 }
633 state.bg_children.clear();
634 if state.inside_async {
635 return;
636 }
637 let entries: Vec<Arc<TaskEntry>> = {
638 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
639 named.values().cloned().collect()
640 };
641 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
642 for entry in &entries {
643 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
644 match guard.phase {
645 TaskPhase::Running | TaskPhase::Awaiting => {
646 guard.phase = TaskPhase::Cancelled;
647 if let Some(handle) = guard.handle.take() {
648 to_kill.push((Arc::clone(entry), handle));
649 }
650 }
651 TaskPhase::Cancelled | TaskPhase::Completed => {}
652 }
653 }
654 for (entry, mut handle) in to_kill {
655 let _ = handle.kill();
656 entry.finish_teardown();
657 }
658}
659
660#[allow(clippy::too_many_arguments)]
663pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
664 state: &mut ExecState<P>,
665 process: &mut P,
666 cmd: &StepKind,
667 generation: usize,
668 idx: usize,
669 stdin: CommandStdin,
670 expose_stdin: bool,
671 out: Option<StreamHandle>,
672 err: Option<StreamHandle>,
673 out_pipe: Option<Arc<PipeInner>>,
674 stdin_pipe: Option<Arc<PipeInner>>,
675) -> Result<Flow> {
676 let mut cx = StepCtx {
677 state,
678 process,
679 stdin,
680 expose_stdin,
681 out,
682 err,
683 out_pipe,
684 stdin_pipe,
685 };
686 match cmd {
690 StepKind::FuncDef { .. }
691 | StepKind::Call { .. }
692 | StepKind::Return { .. }
693 | StepKind::While { .. }
694 | StepKind::Break
695 | StepKind::Continue
696 | StepKind::For { .. }
697 | StepKind::If { .. }
698 | StepKind::Timeout { .. }
699 | StepKind::WithIo { .. }
700 | StepKind::AssignCapture { .. } => {
701 return dispatch_flow_step(cmd, &mut cx, generation, idx);
702 }
703 _ => {}
704 }
705 match cmd {
706 StepKind::Run(arg) => {
707 let cmd = super::args::resolve_arg(arg, &mut cx)?;
708 let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
709 handlers::run(&mut cx, idx, &cmd)
710 }
711 StepKind::RunExec { argv } => {
712 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
713 handlers::run_argv(&mut cx, idx, &resolved)
714 }
715 StepKind::Echo(arg) => {
716 let msg = super::args::resolve_arg(arg, &mut cx)?;
717 handlers::echo(&mut cx, &msg)
718 }
719 StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
720 StepKind::Workdir(arg) => {
721 let path = super::args::resolve_arg(arg, &mut cx)?;
722 handlers::workdir(&mut cx, idx, &path)
723 }
724 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
725 StepKind::RemoteBlock {
726 target,
727 vars,
728 env,
729 body,
730 } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
731 StepKind::Env { key, value } => {
732 let resolved = super::args::resolve_arg(value, &mut cx)?;
733 handlers::env(&mut cx, key, &resolved)
734 }
735 StepKind::InheritEnv { keys } => {
736 handlers::inherit_env(&mut cx, keys)?;
737 sync_iteration_assert_needles(
738 cx.state,
739 &[Step {
740 guard: None,
741 kind: cmd.clone(),
742 scope_enter: 0,
743 scope_exit: 0,
744 }],
745 generation,
746 )?;
747 Ok(())
748 }
749 StepKind::Copy {
750 from_workspace,
751 from_host,
752 to_host,
753 from,
754 to,
755 } => {
756 if *from_host || *to_host {
757 super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
758 } else {
759 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
760 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
761 handlers::copy(
762 &mut cx,
763 idx,
764 from_workspace.clone(),
765 &from_resolved,
766 &to_resolved,
767 )
768 }
769 }
770 StepKind::CopyGit {
771 rev,
772 from,
773 to,
774 include_dirty,
775 } => {
776 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
777 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
778 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
779 handlers::copy_git(
780 &mut cx,
781 idx,
782 &rev_resolved,
783 &from_resolved,
784 &to_resolved,
785 *include_dirty,
786 )
787 }
788 StepKind::HashSha256 { path } => {
789 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
790 handlers::hash_sha256(&mut cx, idx, &path_resolved)
791 }
792 StepKind::Archive { src, dst, raw } => {
793 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
794 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
795 handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
796 }
797 StepKind::Unarchive {
798 src,
799 dst,
800 max_bytes,
801 } => {
802 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
803 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
804 let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
805 handlers::unarchive(
806 &mut cx,
807 idx,
808 &src_resolved,
809 &dst_resolved,
810 cap_resolved.as_deref(),
811 )
812 }
813 StepKind::Symlink {
814 from_workspace,
815 from,
816 to,
817 } => {
818 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
819 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
820 handlers::symlink(
821 &mut cx,
822 idx,
823 from_workspace.clone(),
824 &from_resolved,
825 &to_resolved,
826 )
827 }
828 StepKind::Mkdir(arg) => {
829 let path = super::args::resolve_arg(arg, &mut cx)?;
830 handlers::mkdir(&mut cx, idx, &path)
831 }
832 StepKind::Install { from, to } => {
833 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
834 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
835 handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
836 }
837 StepKind::Ls(arg) => {
838 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
839 handlers::ls(&mut cx, idx, &resolved)
840 }
841 StepKind::Cwd => handlers::cwd(&mut cx, idx),
842 StepKind::Read(arg) => {
843 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
844 handlers::read(&mut cx, idx, &resolved)
845 }
846 StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
847 StepKind::Prompt {
848 var,
849 message,
850 default,
851 } => {
852 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
853 let default_resolved = match default {
854 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
855 None => None,
856 };
857 handlers::prompt(
858 &mut cx,
859 idx,
860 var,
861 &message_resolved,
862 default_resolved.as_deref(),
863 )
864 }
865 StepKind::ListAppend { list, item } => {
866 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
867 handlers::push_into(&mut cx, idx, list, value)
868 }
869 StepKind::Write { path, contents } => {
870 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
871 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
872 handlers::write(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
873 }
874 StepKind::Append { path, contents } => {
875 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
876 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
877 handlers::append(&mut cx, idx, &path_resolved, contents_resolved.as_deref())
878 }
879 StepKind::Remove { path, recursive } => {
880 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
881 handlers::remove(&mut cx, idx, &path_resolved, *recursive)
882 }
883 StepKind::Expand { path, overrides } => {
884 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
885 let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
886 handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
887 }
888 StepKind::AssertEq {
889 hash,
890 actual,
891 expected,
892 } => {
893 let target = resolve_assert_target(actual, &mut cx)?;
894 let expected_resolved = match expected {
895 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
896 None => None,
897 };
898 handlers::assert_eq(
899 &mut cx,
900 idx,
901 generation,
902 idx,
903 hash,
904 &target,
905 expected_resolved.as_ref(),
906 )
907 }
908 StepKind::AssertContains { haystack, needle } => {
909 let target = resolve_assert_target(haystack, &mut cx)?;
910 handlers::assert_contains(&mut cx, idx, generation, idx, &target, needle)
911 }
912 StepKind::WithIoBlock { .. } => {
913 bail!("WITH_IO block should have been expanded during parsing")
914 }
915 StepKind::Exit(code) => {
916 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
917 handlers::exit(&mut cx, code)
918 }
919 StepKind::Assign {
920 var,
921 decl_type,
922 expr,
923 } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
924 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
925 StepKind::AssignAsync {
926 var,
927 decl_type,
928 body,
929 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
930 StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
931 StepKind::AwaitCapture {
932 out_var,
933 out_type,
934 task_var,
935 } => handlers::dispatch_await_capture(out_var, out_type.clone(), task_var, &mut cx),
936 StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
937 StepKind::Sleep { duration } => {
938 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
939 handlers::sleep(&mut cx, idx, &duration)
940 }
941 StepKind::TypeAlias { .. } => {
942 Ok(())
945 }
946 StepKind::FuncDef { .. }
947 | StepKind::Call { .. }
948 | StepKind::Return { .. }
949 | StepKind::While { .. }
950 | StepKind::Break
951 | StepKind::Continue
952 | StepKind::For { .. }
953 | StepKind::If { .. }
954 | StepKind::Timeout { .. }
955 | StepKind::WithIo { .. }
956 | StepKind::AssignCapture { .. } => {
957 unreachable!("compound steps dispatch before this match")
958 }
959 }?;
960 Ok(Flow::Done)
961}
962
963#[allow(clippy::too_many_arguments)]
964fn execute_steps_inner<P: ProcessManager>(
965 state: &mut ExecState<P>,
966 process: &mut P,
967 generation: usize,
968 steps: &[Step],
969 stdin: CommandStdin,
970 expose_stdin: bool,
971 out: Option<StreamHandle>,
972 err: Option<StreamHandle>,
973 out_pipe: Option<Arc<PipeInner>>,
974 stdin_pipe: Option<Arc<PipeInner>>,
975 wait_at_end: bool,
976) -> Result<Flow> {
977 pre_register_assertions(state, steps, generation)?;
979
980 for (idx, step) in steps.iter().enumerate() {
981 if state.cancel_token.load(Ordering::SeqCst) {
983 bail!("ASYNC task cancelled");
984 }
985 if step.scope_enter > 0 {
986 for _ in 0..step.scope_enter {
987 state.push_scope();
988 }
989 }
990
991 let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
992 let flow_result: Result<Flow> = if !should_run {
993 Ok(Flow::Done)
994 } else {
995 let mut cx = StepCtx {
996 state,
997 process,
998 stdin: stdin.clone(),
999 expose_stdin,
1000 out: out.clone(),
1001 err: err.clone(),
1002 out_pipe: out_pipe.clone(),
1003 stdin_pipe: stdin_pipe.clone(),
1004 };
1005 let flow_result: Result<Flow> = match &step.kind {
1008 StepKind::FuncDef { .. }
1009 | StepKind::Call { .. }
1010 | StepKind::Return { .. }
1011 | StepKind::While { .. }
1012 | StepKind::Break
1013 | StepKind::Continue
1014 | StepKind::For { .. }
1015 | StepKind::If { .. }
1016 | StepKind::Timeout { .. }
1017 | StepKind::WithIo { .. }
1018 | StepKind::AssignCapture { .. } => {
1019 dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1020 }
1021 _ => {
1022 match &step.kind {
1023 StepKind::InheritEnv { keys } => {
1024 handlers::inherit_env(&mut cx, keys)?;
1025 sync_iteration_assert_needles(cx.state, steps, generation)?;
1026 Ok(())
1027 }
1028 StepKind::Workdir(arg) => {
1029 let path = super::args::resolve_arg(arg, &mut cx)?;
1030 handlers::workdir(&mut cx, idx, &path)
1031 }
1032 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
1033 StepKind::RemoteBlock {
1034 target,
1035 vars,
1036 env,
1037 body,
1038 } => super::remote::run_remote_block(&mut cx, target, vars, env, body, idx),
1039 StepKind::Env { key, value } => {
1040 let resolved = super::args::resolve_arg(value, &mut cx)?;
1041 handlers::env(&mut cx, key, &resolved)?;
1042 sync_iteration_assert_needles(cx.state, steps, generation)?;
1043 Ok(())
1044 }
1045 StepKind::Run(arg) => {
1046 let cmd = super::args::resolve_arg(arg, &mut cx)?;
1047 let cmd = super::args::expand_dsl_vars(&cmd, cx.state);
1048 handlers::run(&mut cx, idx, &cmd)
1049 }
1050 StepKind::RunExec { argv } => {
1051 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
1052 handlers::run_argv(&mut cx, idx, &resolved)
1053 }
1054 StepKind::Echo(arg) => {
1055 let msg = super::args::resolve_arg(arg, &mut cx)?;
1056 handlers::echo(&mut cx, &msg)
1057 }
1058 StepKind::AsyncBlock { .. } => {
1059 handlers::dispatch_async_block(&step.kind, &mut cx)
1060 }
1061 StepKind::Copy {
1062 from_workspace,
1063 from_host,
1064 to_host,
1065 from,
1066 to,
1067 } => {
1068 if *from_host || *to_host {
1069 super::remote::copy_transfer(
1070 &mut cx, *from_host, *to_host, from, to,
1071 )
1072 } else {
1073 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1074 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1075 handlers::copy(
1076 &mut cx,
1077 idx,
1078 from_workspace.clone(),
1079 &from_resolved,
1080 &to_resolved,
1081 )
1082 }
1083 }
1084 StepKind::CopyGit {
1085 rev,
1086 from,
1087 to,
1088 include_dirty,
1089 } => {
1090 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
1091 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1092 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1093 handlers::copy_git(
1094 &mut cx,
1095 idx,
1096 &rev_resolved,
1097 &from_resolved,
1098 &to_resolved,
1099 *include_dirty,
1100 )
1101 }
1102 StepKind::HashSha256 { path } => {
1103 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1104 handlers::hash_sha256(&mut cx, idx, &path_resolved)
1105 }
1106 StepKind::Archive { src, dst, raw } => {
1107 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1108 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1109 handlers::archive(&mut cx, idx, &src_resolved, &dst_resolved, *raw)
1110 }
1111 StepKind::Unarchive {
1112 src,
1113 dst,
1114 max_bytes,
1115 } => {
1116 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
1117 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
1118 let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
1119 handlers::unarchive(
1120 &mut cx,
1121 idx,
1122 &src_resolved,
1123 &dst_resolved,
1124 cap_resolved.as_deref(),
1125 )
1126 }
1127 StepKind::Symlink {
1128 from_workspace,
1129 from,
1130 to,
1131 } => {
1132 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1133 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1134 handlers::symlink(
1135 &mut cx,
1136 idx,
1137 from_workspace.clone(),
1138 &from_resolved,
1139 &to_resolved,
1140 )
1141 }
1142 StepKind::Mkdir(arg) => {
1143 let path = super::args::resolve_arg(arg, &mut cx)?;
1144 handlers::mkdir(&mut cx, idx, &path)
1145 }
1146 StepKind::Install { from, to } => {
1147 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
1148 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
1149 handlers::install(&mut cx, idx, &from_resolved, &to_resolved)
1150 }
1151 StepKind::Ls(arg) => {
1152 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1153 handlers::ls(&mut cx, idx, &resolved)
1154 }
1155 StepKind::Cwd => handlers::cwd(&mut cx, idx),
1156 StepKind::Read(arg) => {
1157 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1158 handlers::read(&mut cx, idx, &resolved)
1159 }
1160 StepKind::ReadLine { var } => handlers::read_line(&mut cx, idx, var),
1161 StepKind::Prompt {
1162 var,
1163 message,
1164 default,
1165 } => {
1166 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1167 let default_resolved = match default {
1168 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1169 None => None,
1170 };
1171 handlers::prompt(
1172 &mut cx,
1173 idx,
1174 var,
1175 &message_resolved,
1176 default_resolved.as_deref(),
1177 )
1178 }
1179 StepKind::ListAppend { list, item } => {
1180 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1181 handlers::push_into(&mut cx, idx, list, value)
1182 }
1183 StepKind::Write { path, contents } => {
1184 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1185 let contents_resolved =
1186 super::args::resolve_arg_opt(contents, &mut cx)?;
1187 handlers::write(
1188 &mut cx,
1189 idx,
1190 &path_resolved,
1191 contents_resolved.as_deref(),
1192 )
1193 }
1194 StepKind::Append { path, contents } => {
1195 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1196 let contents_resolved =
1197 super::args::resolve_arg_opt(contents, &mut cx)?;
1198 handlers::append(
1199 &mut cx,
1200 idx,
1201 &path_resolved,
1202 contents_resolved.as_deref(),
1203 )
1204 }
1205 StepKind::Remove { path, recursive } => {
1206 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1207 handlers::remove(&mut cx, idx, &path_resolved, *recursive)
1208 }
1209 StepKind::Expand { path, overrides } => {
1210 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1211 let overrides_resolved =
1212 super::args::resolve_overrides(overrides, &mut cx)?;
1213 handlers::replace(&mut cx, idx, &path_resolved, &overrides_resolved)
1214 }
1215 StepKind::AssertEq {
1216 hash,
1217 actual,
1218 expected,
1219 } => {
1220 let target = resolve_assert_target(actual, &mut cx)?;
1221 let expected_resolved = match expected {
1222 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1223 None => None,
1224 };
1225 handlers::assert_eq(
1226 &mut cx,
1227 idx,
1228 generation,
1229 idx,
1230 hash,
1231 &target,
1232 expected_resolved.as_ref(),
1233 )
1234 }
1235 StepKind::AssertContains { haystack, needle } => {
1236 let target = resolve_assert_target(haystack, &mut cx)?;
1237 handlers::assert_contains(
1238 &mut cx, idx, generation, idx, &target, needle,
1239 )
1240 }
1241 StepKind::WithIoBlock { .. } => {
1242 bail!("WITH_IO block should have been expanded during parsing")
1243 }
1244 StepKind::Exit(code) => {
1245 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1246 handlers::exit(&mut cx, code)
1247 }
1248 StepKind::Assign {
1249 var,
1250 decl_type,
1251 expr,
1252 } => handlers::assign(&mut cx, var, decl_type.clone(), expr),
1253 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1254 StepKind::AssignAsync {
1255 var,
1256 decl_type,
1257 body,
1258 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx),
1259 StepKind::Await { var } => handlers::dispatch_await(var, &mut cx),
1260 StepKind::AwaitCapture {
1261 out_var,
1262 out_type,
1263 task_var,
1264 } => handlers::dispatch_await_capture(
1265 out_var,
1266 out_type.clone(),
1267 task_var,
1268 &mut cx,
1269 ),
1270 StepKind::Cancel { var } => handlers::dispatch_cancel(var, &mut cx),
1271 StepKind::Sleep { duration } => {
1272 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1273 handlers::sleep(&mut cx, idx, &duration)
1274 }
1275 StepKind::TypeAlias { .. } => {
1276 Ok(())
1279 }
1280 StepKind::FuncDef { .. }
1281 | StepKind::Call { .. }
1282 | StepKind::Return { .. }
1283 | StepKind::While { .. }
1284 | StepKind::Break
1285 | StepKind::Continue
1286 | StepKind::For { .. }
1287 | StepKind::If { .. }
1288 | StepKind::Timeout { .. }
1289 | StepKind::WithIo { .. }
1290 | StepKind::AssignCapture { .. } => {
1291 unreachable!("compound steps dispatch in the outer match")
1292 }
1293 }?;
1294 Ok(Flow::Done)
1295 }
1296 };
1297 flow_result
1298 };
1299
1300 let restore_result = restore_scopes(state, step.scope_exit);
1301 let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1306 expiry.expire_step(steps, idx)
1307 } else {
1308 false
1309 };
1310 if expiry_drained {
1311 state.keeper_expiry = None;
1312 }
1313 let flow = flow_result?;
1314 restore_result?;
1315 match flow {
1316 Flow::Done => {}
1317 Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1318 return Ok(flow);
1319 }
1320 }
1321 }
1322
1323 let reap_named = !state.inside_async;
1331 let has_bg = !state.bg_children.is_empty();
1332 let named_pending = |state: &ExecState<P>| {
1333 reap_named
1334 && state
1335 .named_tasks
1336 .lock()
1337 .unwrap_or_else(|e| e.into_inner())
1338 .values()
1339 .any(|entry| !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped)
1340 };
1341 let has_named = named_pending(state);
1342 if wait_at_end && (has_bg || has_named) {
1343 loop {
1344 let mut failed_status: Option<anyhow::Error> = None;
1345
1346 if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1351 failed_status = Some(anyhow::anyhow!("ASYNC task cancelled"));
1352 }
1353
1354 let mut i = 0;
1356 while i < state.bg_children.len() {
1357 match state.bg_children[i].try_wait() {
1358 Ok(Some(status)) => {
1359 if !status.success() && failed_status.is_none() {
1360 failed_status =
1361 Some(anyhow::anyhow!("ASYNC process exited with status {status}"));
1362 break;
1363 }
1364 state.bg_children.swap_remove(i);
1365 }
1366 Ok(None) => {
1367 i += 1;
1368 }
1369 Err(e) => {
1370 if failed_status.is_none() {
1371 failed_status = Some(e);
1372 }
1373 break;
1374 }
1375 }
1376 }
1377
1378 if failed_status.is_none() && reap_named {
1382 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1383 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1384 named
1385 .iter()
1386 .map(|(id, entry)| (*id, Arc::clone(entry)))
1387 .collect()
1388 };
1389 for (id, entry) in &entries {
1390 enum Poll {
1391 Pending,
1392 CompletedOk,
1393 CompletedErr(anyhow::Error),
1394 }
1395 let poll = {
1396 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1397 match guard.phase {
1398 TaskPhase::Running | TaskPhase::Awaiting => {
1399 match guard.handle.as_mut() {
1400 Some(handle) => match handle.try_wait() {
1401 Ok(Some(status)) => {
1402 let _ = guard.handle.take();
1403 guard.phase = TaskPhase::Completed;
1404 if status.success() {
1405 Poll::CompletedOk
1406 } else {
1407 Poll::CompletedErr(anyhow::anyhow!(
1408 "named ASYNC task {id} exited with status {status}"
1409 ))
1410 }
1411 }
1412 Ok(None) => Poll::Pending,
1413 Err(e) => {
1414 let _ = guard.handle.take();
1415 guard.phase = TaskPhase::Completed;
1416 Poll::CompletedErr(e)
1417 }
1418 },
1419 None => Poll::Pending,
1422 }
1423 }
1424 TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1425 }
1426 };
1427 match poll {
1428 Poll::Pending => {}
1429 Poll::CompletedOk => {
1430 entry.finish_teardown();
1431 }
1432 Poll::CompletedErr(e) => {
1433 entry.finish_teardown();
1434 if failed_status.is_none() {
1435 failed_status = Some(e);
1436 }
1437 break;
1438 }
1439 }
1440 }
1441 }
1442
1443 if let Some(err) = failed_status {
1448 for survivor in state.bg_children.iter_mut() {
1449 let _ = survivor.kill();
1450 }
1451 if reap_named {
1452 let entries: Vec<Arc<TaskEntry>> = {
1453 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1454 named.values().cloned().collect()
1455 };
1456 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1457 for entry in &entries {
1458 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1459 match guard.phase {
1460 TaskPhase::Running | TaskPhase::Awaiting => {
1461 guard.phase = TaskPhase::Cancelled;
1462 if let Some(handle) = guard.handle.take() {
1463 to_kill.push((Arc::clone(entry), handle));
1464 }
1465 }
1466 TaskPhase::Cancelled | TaskPhase::Completed => {}
1467 }
1468 }
1469 for (entry, mut handle) in to_kill {
1470 let _ = handle.kill();
1471 entry.finish_teardown();
1472 }
1473 }
1474 state.bg_children.clear();
1475 return Err(err);
1476 }
1477
1478 let bg_empty = state.bg_children.is_empty();
1479 if bg_empty && !named_pending(state) {
1480 return Ok(Flow::Done);
1481 }
1482 if reap_named {
1486 let unreaped: Vec<Arc<TaskEntry>> = {
1487 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1488 named
1489 .values()
1490 .filter(|entry| {
1491 let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1492 matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1493 })
1494 .cloned()
1495 .collect()
1496 };
1497 for entry in &unreaped {
1498 entry.wait_reaped();
1499 }
1500 }
1501 std::thread::sleep(std::time::Duration::from_millis(10));
1502 }
1503 }
1504
1505 Ok(Flow::Done)
1506}
1507
1508fn restore_scopes<P: ProcessManager>(state: &mut ExecState<P>, count: usize) -> Result<()> {
1509 for _ in 0..count {
1510 state.pop_scope()?;
1511 }
1512 Ok(())
1513}
1514
1515#[allow(clippy::too_many_arguments)]
1522pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1523 state: &mut ExecState<P>,
1524 process: &mut P,
1525 steps: &[Step],
1526 stdin: CommandStdin,
1527 expose_stdin: bool,
1528 out: Option<StreamHandle>,
1529 err: Option<StreamHandle>,
1530 out_pipe: Option<Arc<PipeInner>>,
1531 stdin_pipe: Option<Arc<PipeInner>>,
1532) -> Result<()> {
1533 let flow = execute_scoped_steps(
1534 state,
1535 process,
1536 steps,
1537 stdin,
1538 expose_stdin,
1539 out,
1540 err,
1541 out_pipe,
1542 stdin_pipe,
1543 true,
1544 )?;
1545 match flow {
1546 Flow::Done => Ok(()),
1547 Flow::Break { idx } => {
1548 bail!("step {}: BREAK cannot cross a REMOTE boundary", idx + 1);
1549 }
1550 Flow::Continue { idx } => {
1551 bail!("step {}: CONTINUE cannot cross a REMOTE boundary", idx + 1);
1552 }
1553 Flow::Return { idx, .. } => {
1554 bail!("step {}: RETURN cannot cross a REMOTE boundary", idx + 1);
1555 }
1556 }
1557}
1558
1559#[allow(clippy::too_many_arguments)]
1564pub(super) fn execute_scoped_steps<P: ProcessManager>(
1565 state: &mut ExecState<P>,
1566 process: &mut P,
1567 steps: &[Step],
1568 stdin: CommandStdin,
1569 expose_stdin: bool,
1570 out: Option<StreamHandle>,
1571 err: Option<StreamHandle>,
1572 out_pipe: Option<Arc<PipeInner>>,
1573 stdin_pipe: Option<Arc<PipeInner>>,
1574 wait_at_end: bool,
1575) -> Result<Flow> {
1576 state.push_scope();
1577 let res = execute_steps(
1578 state,
1579 process,
1580 steps,
1581 stdin,
1582 expose_stdin,
1583 out,
1584 err,
1585 out_pipe,
1586 stdin_pipe,
1587 wait_at_end,
1588 );
1589 let pop_res = state.pop_scope();
1592 match (res, pop_res) {
1593 (Ok(flow), Ok(())) => Ok(flow),
1594 (Err(e), _) => Err(e),
1595 (Ok(_), Err(e)) => Err(e),
1596 }
1597}
1598
1599fn dispatch_flow_step<P: ProcessManager>(
1603 cmd: &StepKind,
1604 cx: &mut StepCtx<'_, P>,
1605 generation: usize,
1606 idx: usize,
1607) -> Result<Flow> {
1608 match cmd {
1609 StepKind::FuncDef { name, params, body } => {
1610 handlers::define_func(cx, name, params, body)?;
1611 Ok(Flow::Done)
1612 }
1613 StepKind::Call { name, args } => {
1614 let _ = handlers::call_func_value(cx, idx, name, args)?;
1615 Ok(Flow::Done)
1616 }
1617 StepKind::Return { expr } => handlers::handle_return(cx, idx, expr),
1618 StepKind::While { cond, body } => handlers::while_loop(cx, idx, cond, body),
1619 StepKind::Break => Ok(Flow::Break { idx }),
1620 StepKind::Continue => Ok(Flow::Continue { idx }),
1621 StepKind::For {
1622 key_var,
1623 key_type,
1624 var,
1625 var_type,
1626 in_expr,
1627 body,
1628 } => handlers::for_loop(
1629 cx,
1630 key_var.as_deref(),
1631 key_type.clone(),
1632 var,
1633 var_type.clone(),
1634 in_expr,
1635 body,
1636 ),
1637 StepKind::If {
1638 cond,
1639 then_body,
1640 else_ifs,
1641 else_body,
1642 } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1643 StepKind::Timeout { duration, body } => {
1644 let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1645 handlers::timeout(cx, idx, &duration, body)
1646 }
1647 StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1648 StepKind::AssignCapture {
1649 var,
1650 decl_type,
1651 cmd,
1652 } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd),
1653 _ => {
1654 unreachable!("dispatch_flow_step handles only compound steps")
1655 }
1656 }
1657}