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 oxdock_diagnostics::{Diagnostic, DiagnosticResult, Span};
8use oxdock_fs::GuardedPath;
9use oxdock_parser::{
10 Arg, AssertTarget, Command, KEYWORD_BREAK, KEYWORD_CONTINUE, KEYWORD_RETURN, Step, StepKind,
11 Value, guard_option_allows,
12};
13use oxdock_process::{BackgroundHandle, CommandStdin, ProcessManager, SharedInput, SharedOutput};
14
15fn exit_status_from_code(code: i32) -> ExitStatus {
17 #[cfg(unix)]
18 {
19 use std::os::unix::process::ExitStatusExt;
20 ExitStatus::from_raw(code << 8)
21 }
22 #[cfg(windows)]
23 {
24 use std::os::windows::process::ExitStatusExt;
25 ExitStatus::from_raw(code as u32)
26 }
27}
28
29use super::diagnostics as step_diag;
30use super::handlers;
31use super::io::{ExactCapture, SlidingWindow, StreamHandle};
32use super::native::PureTable;
33use super::state::{ExecState, TaskEntry, TaskPhase};
34use oxdock_pipe::PipeInner;
35
36pub(super) struct ThreadJoinHandle {
39 join: Option<std::thread::JoinHandle<DiagnosticResult<()>>>,
40 cancel_token: Arc<AtomicBool>,
41 cancel_hub: Arc<oxdock_process::CancelHub>,
42 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
43 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
51 thread_error: Option<Diagnostic>,
58 thread_context: Vec<String>,
66 thread_exit_code: Option<i64>,
71}
72
73impl ThreadJoinHandle {
74 pub(super) fn new(
75 join: std::thread::JoinHandle<DiagnosticResult<()>>,
76 cancel_token: Arc<AtomicBool>,
77 cancel_hub: Arc<oxdock_process::CancelHub>,
78 active_process: Arc<Mutex<Option<Box<dyn BackgroundHandle>>>>,
79 worker: Arc<Mutex<Option<std::thread::ThreadId>>>,
80 ) -> Self {
81 Self {
82 join: Some(join),
83 cancel_token,
84 cancel_hub,
85 active_process,
86 worker,
87 thread_error: None,
88 thread_context: Vec::new(),
89 thread_exit_code: None,
90 }
91 }
92
93 fn reemit_error(&self) -> Diagnostic {
103 let diag = match (self.thread_error.clone(), self.thread_exit_code) {
104 (Some(mut diag), maybe_code) => {
105 if let Some(code) = maybe_code
106 && super::exit::exit_code_of_diag(&diag).is_none()
107 {
108 let exit = match diag.shared_source() {
109 Some(prior) => super::exit::ExitRequest::with_source(code, prior),
110 None => super::exit::ExitRequest::new(code),
111 };
112 diag = diag.with_source(Arc::new(exit));
113 }
114 diag
115 }
116 (None, Some(code)) => step_diag::eval_exit_requested(code),
117 (None, None) => {
118 step_diag::eval_async_thread_panicked("background thread failed without an error")
119 }
120 };
121 diag.with_contexts(self.thread_context.clone())
122 }
123
124 fn is_self(&self) -> bool {
126 let guard = self.worker.lock().unwrap_or_else(|e| e.into_inner());
127 guard.is_some_and(|id| id == std::thread::current().id())
128 }
129
130 fn reap(&mut self) {
132 if self.join.is_none() {
133 return;
134 }
135 if self.is_self() {
136 let _ = self.join.take();
140 return;
141 }
142 let handle = self.join.take().unwrap();
143 match handle.join() {
144 Ok(Ok(())) => {}
145 Ok(Err(diag)) => {
146 self.thread_exit_code = super::exit::exit_code_of_diag(&diag);
156 self.thread_error = Some(diag);
157 }
158 Err(panic) => {
159 let msg = if let Some(s) = panic.downcast_ref::<&str>() {
160 s.to_string()
161 } else if let Some(s) = panic.downcast_ref::<String>() {
162 s.clone()
163 } else {
164 "thread panicked".to_string()
165 };
166 self.thread_error = Some(step_diag::eval_async_thread_panicked(&msg));
167 }
168 }
169 }
170}
171
172impl BackgroundHandle for ThreadJoinHandle {
173 fn try_wait(&mut self) -> DiagnosticResult<Option<ExitStatus>> {
174 if let Some(join) = &self.join {
175 if join.is_finished() {
176 self.reap();
177 } else {
178 return Ok(None);
179 }
180 }
181 if self.thread_error.is_some() || self.thread_exit_code.is_some() {
185 Err(self.reemit_error())
186 } else {
187 Ok(Some(exit_status_from_code(0)))
188 }
189 }
190
191 fn kill(&mut self) -> DiagnosticResult<()> {
192 self.cancel_token.store(true, Ordering::SeqCst);
194 self.cancel_hub.mark_cancelled();
197 if let Ok(mut guard) = self.active_process.lock()
199 && let Some(ref mut proc) = *guard
200 {
201 let _ = proc.kill();
202 }
203 self.reap();
205 Ok(())
206 }
207
208 fn wait(&mut self) -> DiagnosticResult<ExitStatus> {
209 self.reap();
210 if self.thread_error.is_some() || self.thread_exit_code.is_some() {
212 Err(self.reemit_error())
213 } else {
214 Ok(exit_status_from_code(0))
215 }
216 }
217}
218
219impl Drop for ThreadJoinHandle {
220 fn drop(&mut self) {
221 let _ = self.kill();
222 }
223}
224
225static ASSERT_GENERATION: AtomicUsize = AtomicUsize::new(0);
229
230#[derive(Debug)]
237pub(super) enum Flow {
238 Done,
239 Break { idx: usize },
240 Continue { idx: usize },
241 Return { idx: usize, value: Value },
242}
243
244pub(super) fn allocate_assert_generation() -> usize {
245 ASSERT_GENERATION.fetch_add(1, Ordering::Relaxed)
246}
247
248#[derive(Clone, Copy, PartialEq, Eq)]
250pub(super) enum AssertStream {
251 Stdout,
252 Stderr,
253}
254
255fn extract_stream_needle(kind: &StepKind) -> Option<(AssertStream, &Arg)> {
259 let step = match kind {
260 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
261 other => other,
262 };
263 match step {
264 StepKind::AssertContains { haystack, needle } => match haystack {
265 AssertTarget::Stdout => Some((AssertStream::Stdout, needle)),
266 AssertTarget::Stderr => Some((AssertStream::Stderr, needle)),
267 _ => None,
268 },
269 _ => None,
270 }
271}
272
273fn needs_exact_stdout(kind: &StepKind) -> bool {
276 let step = match kind {
277 StepKind::WithIo { cmd, .. } => cmd.as_ref(),
278 other => other,
279 };
280 matches!(
281 step,
282 StepKind::AssertEq {
283 actual: AssertTarget::Stdout,
284 ..
285 } | StepKind::AssertNe {
286 actual: AssertTarget::Stdout,
287 ..
288 }
289 )
290}
291
292pub(super) enum ResolvedAssertTarget {
295 Value(Value),
296 Stdout,
297 Stderr,
298 Pipe(Vec<u8>),
299}
300
301pub(super) fn resolve_assert_target<P: ProcessManager>(
307 target: &AssertTarget,
308 cx: &mut StepCtx<'_, P>,
309) -> DiagnosticResult<ResolvedAssertTarget> {
310 match target {
311 AssertTarget::Value(arg) => {
312 let value = super::args::evaluate_assert_operand(arg, cx)?;
313 if let Some(handle) = value.as_pipe_handle() {
314 let bytes = cx
315 .state
316 .io
317 .peek_pipe_content(&handle)
318 .map_err(|e| step_diag::eval_pipe_assertion_read_failed(&e))?;
319 return Ok(ResolvedAssertTarget::Pipe(bytes));
320 }
321 Ok(ResolvedAssertTarget::Value(value))
322 }
323 AssertTarget::Stdout => Ok(ResolvedAssertTarget::Stdout),
324 AssertTarget::Stderr => Ok(ResolvedAssertTarget::Stderr),
325 }
326}
327
328pub(super) fn pre_register_assertions<P: ProcessManager>(
335 state: &mut ExecState<P>,
336 steps: &[Step],
337 generation: usize,
338) -> DiagnosticResult<()> {
339 let mut windows = match state.assert_windows.lock() {
340 Ok(guard) => guard,
341 Err(_) => {
342 return Err(super::diagnostics::std_assert_lock_poisoned(
343 "assert_windows",
344 ));
345 }
346 };
347 let mut stderr_windows = match state.assert_windows_stderr.lock() {
348 Ok(guard) => guard,
349 Err(_) => {
350 return Err(super::diagnostics::std_assert_lock_poisoned(
351 "assert_windows_stderr",
352 ));
353 }
354 };
355 let mut exact = match state.exact_stdout.lock() {
356 Ok(guard) => guard,
357 Err(_) => return Err(super::diagnostics::std_assert_lock_poisoned("exact_stdout")),
358 };
359 for (idx, step) in steps.iter().enumerate() {
360 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
361 let resolved = super::args::resolve_arg_state(arg, state)?;
362 let map = match stream {
363 AssertStream::Stdout => &mut windows,
364 AssertStream::Stderr => &mut stderr_windows,
365 };
366 map.insert((generation, idx), SlidingWindow::new(resolved.into_bytes()));
367 }
368 if needs_exact_stdout(&step.kind) {
369 exact.entry(generation).or_insert_with(ExactCapture::new);
370 }
371 }
372 Ok(())
373}
374
375#[allow(clippy::collapsible_if)]
381pub(super) fn sync_iteration_assert_needles<P: ProcessManager>(
382 state: &ExecState<P>,
383 steps: &[Step],
384 generation: usize,
385) -> DiagnosticResult<()> {
386 let mut windows = match state.assert_windows.lock() {
387 Ok(guard) => guard,
388 Err(_) => {
389 return Err(super::diagnostics::std_assert_lock_poisoned(
390 "assert_windows",
391 ));
392 }
393 };
394 let mut stderr_windows = match state.assert_windows_stderr.lock() {
395 Ok(guard) => guard,
396 Err(_) => {
397 return Err(super::diagnostics::std_assert_lock_poisoned(
398 "assert_windows_stderr",
399 ));
400 }
401 };
402 for (idx, step) in steps.iter().enumerate() {
403 if let Some((stream, arg)) = extract_stream_needle(&step.kind) {
404 let map = match stream {
405 AssertStream::Stdout => &mut windows,
406 AssertStream::Stderr => &mut stderr_windows,
407 };
408 if let Some(w) = map.get_mut(&(generation, idx)) {
409 let resolved = super::args::resolve_arg_state(arg, state)?;
410 w.update_needle(resolved.into_bytes());
411 }
412 }
413 }
414 Ok(())
415}
416
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub struct TtyRequest {
426 pub rows: Option<u16>,
428 pub cols: Option<u16>,
430}
431
432pub struct StepCtx<'a, P: ProcessManager> {
445 pub(super) state: &'a mut ExecState<P>,
446 pub(super) process: &'a mut P,
447 pub(super) stdin: CommandStdin,
448 pub(super) expose_stdin: bool,
449 pub(super) out: Option<StreamHandle>,
450 pub(super) err: Option<StreamHandle>,
451 pub(super) out_pipe: Option<Arc<PipeInner>>,
457 pub(super) stdin_pipe: Option<Arc<PipeInner>>,
462 pub(super) tty: Option<TtyRequest>,
467}
468
469impl<'a, P: ProcessManager> StepCtx<'a, P> {
470 pub(super) fn for_mcp(
474 state: &'a mut ExecState<P>,
475 process: &'a mut P,
476 stdin: CommandStdin,
477 out: Option<StreamHandle>,
478 err: Option<StreamHandle>,
479 ) -> Self {
480 Self {
481 state,
482 process,
483 stdin,
484 expose_stdin: false,
485 out,
486 err,
487 out_pipe: None,
488 stdin_pipe: None,
489 tty: None,
490 }
491 }
492
493 pub(super) fn err_shared(&self) -> Option<SharedOutput> {
497 match self.err.clone() {
498 Some(StreamHandle::Stream(writer)) => Some(writer),
499 _ => None,
500 }
501 }
502
503 pub fn get_var(&self, key: &str) -> Option<Value> {
505 self.state.get_var(key)
506 }
507
508 pub fn get_env(&self, key: &str) -> Option<String> {
512 self.state.get_env(key).map(str::to_string)
513 }
514
515 pub fn env_snapshot(&self) -> HashMap<String, String> {
522 self.state.envs.as_ref().clone()
523 }
524
525 pub fn ensure_scratch_materialized(&self) -> DiagnosticResult<()> {
530 self.state
531 .cargo_scratch
532 .ensure_materialized()
533 .map_err(|err| super::diagnostics::eval_scratch_materialize_failed(&err))
534 }
535
536 pub fn cwd(&self) -> &GuardedPath {
538 &self.state.cwd
539 }
540
541 pub fn workspace_root(&self) -> &GuardedPath {
546 self.state.fs.root()
547 }
548
549 pub fn pure_functions(&self) -> std::sync::Arc<PureTable> {
557 self.state.pure_function_table()
558 }
559
560 pub fn new_pipe(&self) -> Value {
565 Value::pipe_fresh_in_task(self.state.task_id)
566 }
567
568 pub fn pipe_reader(&self, value: &Value) -> DiagnosticResult<SharedInput> {
577 use oxdock_pipe::{Materialized, materialize};
578 let Some(handle) = value.as_pipe_handle() else {
579 return Err(super::diagnostics::std_pipe_needs_pipe(
580 "pipe_reader",
581 value.type_name(),
582 ));
583 };
584 match materialize(&handle, false)? {
585 Materialized::Script(backend) => Ok(backend.reader_handle()),
586 #[cfg(not(miri))]
587 Materialized::Os(entry) => {
588 let owned = entry
589 .reader
590 .take()
591 .map_err(|_| super::diagnostics::std_pipe_handle_spent())?;
592 Ok(Arc::new(Mutex::new(owned)))
593 }
594 }
595 }
596
597 pub fn pipe_writer(&self, value: &Value) -> DiagnosticResult<SharedOutput> {
601 use oxdock_pipe::{Materialized, materialize};
602 let Some(handle) = value.as_pipe_handle() else {
603 return Err(super::diagnostics::std_pipe_needs_pipe(
604 "pipe_writer",
605 value.type_name(),
606 ));
607 };
608 match materialize(&handle, false)? {
609 Materialized::Script(backend) => Ok(backend.writer_handle()),
610 #[cfg(not(miri))]
611 Materialized::Os(entry) => {
612 let owned = entry
613 .writer
614 .take()
615 .map_err(|_| super::diagnostics::std_pipe_handle_spent())?;
616 Ok(Arc::new(Mutex::new(owned)))
617 }
618 }
619 }
620
621 pub fn close_pipe(&self, value: &Value) -> DiagnosticResult<()> {
627 let Some(handle) = value.as_pipe_handle() else {
628 return Err(super::diagnostics::std_pipe_needs_pipe(
629 "close_pipe",
630 value.type_name(),
631 ));
632 };
633 let Some(backend) = oxdock_pipe::script_backend(&handle) else {
634 return Err(super::diagnostics::std_pipe_close_needs_script());
635 };
636 backend.force_close();
637 Ok(())
638 }
639
640 pub fn is_cancelled(&self) -> bool {
644 self.state
645 .cancel_token
646 .load(std::sync::atomic::Ordering::SeqCst)
647 }
648
649 pub fn cancel_token(&self) -> Arc<AtomicBool> {
654 Arc::clone(&self.state.cancel_token)
655 }
656
657 pub fn cancel_hub(&self) -> Arc<oxdock_process::CancelHub> {
661 Arc::clone(&self.state.cancel_hub)
662 }
663
664 pub fn is_async_task(&self) -> bool {
667 self.state.inside_async
668 }
669
670 pub fn module_state<T: Send + Sync + 'static>(
676 &self,
677 module: &str,
678 ) -> Option<std::sync::Arc<T>> {
679 self.state
680 .module_states
681 .get(&(module.to_string(), std::any::TypeId::of::<T>()))?
682 .clone()
683 .downcast::<T>()
684 .ok()
685 }
686
687 pub fn pipe_backend(&self, value: &Value) -> Option<Arc<PipeInner>> {
694 let handle = value.as_pipe_handle()?;
695 oxdock_pipe::script_backend(&handle)
696 }
697}
698
699#[allow(clippy::too_many_arguments)]
700pub(super) fn execute_steps<P: ProcessManager>(
701 state: &mut ExecState<P>,
702 process: &mut P,
703 steps: &[Step],
704 stdin: CommandStdin,
705 expose_stdin: bool,
706 out: Option<StreamHandle>,
707 err: Option<StreamHandle>,
708 out_pipe: Option<Arc<PipeInner>>,
709 stdin_pipe: Option<Arc<PipeInner>>,
710 wait_at_end: bool,
711) -> DiagnosticResult<Flow> {
712 let generation = allocate_assert_generation();
713 let flow = match execute_steps_inner(InnerArgs {
714 state,
715 process,
716 generation,
717 steps,
718 stdin,
719 expose_stdin,
720 out,
721 err,
722 out_pipe,
723 stdin_pipe,
724 wait_at_end,
725 }) {
726 Ok(flow) => flow,
727 Err(e) => {
728 teardown_tasks_on_error(state);
734 cleanup_assertion_generation(state, generation)?;
735 return Err(e);
736 }
737 };
738 cleanup_assertion_generation(state, generation)?;
740 Ok(flow)
741}
742
743fn cleanup_assertion_generation<P: ProcessManager>(
746 state: &mut ExecState<P>,
747 generation: usize,
748) -> DiagnosticResult<()> {
749 let mut windows = match state.assert_windows.lock() {
750 Ok(guard) => guard,
751 Err(_) => {
752 return Err(super::diagnostics::std_assert_lock_poisoned(
753 "assert_windows",
754 ));
755 }
756 };
757 windows.retain(|(g, _), _| *g != generation);
758 let mut stderr_windows = match state.assert_windows_stderr.lock() {
759 Ok(guard) => guard,
760 Err(_) => {
761 return Err(super::diagnostics::std_assert_lock_poisoned(
762 "assert_windows_stderr",
763 ));
764 }
765 };
766 stderr_windows.retain(|(g, _), _| *g != generation);
767 let mut exact = match state.exact_stdout.lock() {
768 Ok(guard) => guard,
769 Err(_) => return Err(super::diagnostics::std_assert_lock_poisoned("exact_stdout")),
770 };
771 exact.retain(|g, _| *g != generation);
772 Ok(())
773}
774
775fn teardown_tasks_on_error<P: ProcessManager>(state: &mut ExecState<P>) {
780 for survivor in state.bg_children.iter_mut() {
781 let _ = survivor.handle.kill();
782 }
783 state.bg_children.clear();
784 if state.inside_async {
785 return;
786 }
787 let entries: Vec<Arc<TaskEntry>> = {
788 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
789 named.values().cloned().collect()
790 };
791 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
792 for entry in &entries {
793 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
794 match guard.phase {
795 TaskPhase::Running | TaskPhase::Awaiting => {
796 guard.phase = TaskPhase::Cancelled;
797 if let Some(handle) = guard.handle.take() {
798 to_kill.push((Arc::clone(entry), handle));
799 }
800 }
801 TaskPhase::Cancelled | TaskPhase::Completed => {}
802 }
803 }
804 for (entry, mut handle) in to_kill {
805 let _ = handle.kill();
806 entry.finish_teardown();
807 }
808}
809
810#[allow(clippy::too_many_arguments)]
813pub(super) fn execute_single_step_with_generation<P: ProcessManager>(
814 state: &mut ExecState<P>,
815 process: &mut P,
816 cmd: &StepKind,
817 generation: usize,
818 idx: usize,
819 stdin: CommandStdin,
820 expose_stdin: bool,
821 out: Option<StreamHandle>,
822 err: Option<StreamHandle>,
823 out_pipe: Option<Arc<PipeInner>>,
824 stdin_pipe: Option<Arc<PipeInner>>,
825 tty: Option<TtyRequest>,
826) -> DiagnosticResult<Flow> {
827 let mut cx = StepCtx {
828 state,
829 process,
830 stdin,
831 expose_stdin,
832 out,
833 err,
834 out_pipe,
835 stdin_pipe,
836 tty,
837 };
838 match cmd {
843 StepKind::FuncDef { .. }
844 | StepKind::Call { .. }
845 | StepKind::Return { .. }
846 | StepKind::ImportFile { .. }
847 | StepKind::ImportFuncs { .. }
848 | StepKind::While { .. }
849 | StepKind::Break
850 | StepKind::Continue
851 | StepKind::For { .. }
852 | StepKind::If { .. }
853 | StepKind::Switch { .. }
854 | StepKind::Timeout { .. }
855 | StepKind::Fail { .. }
856 | StepKind::Isolated { .. }
857 | StepKind::WithIo { .. }
858 | StepKind::Bind {
859 rhs: oxdock_parser::BindRhs::Capture(_),
860 ..
861 } => {
862 return dispatch_flow_step(cmd, &mut cx, generation, idx);
863 }
864 _ => {}
865 }
866 match cmd {
867 StepKind::Run(arg) => {
868 let cmd = super::args::resolve_arg(arg, &mut cx)?;
869 let cmd = super::args::expand_dsl_vars(&cmd, cx.state)?;
870 handlers::run(&mut cx, &cmd)
871 }
872 StepKind::RunExec { argv } => {
873 let resolved = handlers::resolve_run_exec_argv(argv, &mut cx)?;
874 handlers::run_argv(&mut cx, &resolved)
875 }
876 StepKind::Echo(arg) => {
877 let msg = super::args::resolve_arg(arg, &mut cx)?;
878 handlers::echo(&mut cx, &msg)
879 }
880 StepKind::AsyncBlock { .. } => handlers::dispatch_async_block(cmd, &mut cx),
881 StepKind::Workdir(arg) => {
882 let path = super::args::resolve_arg(arg, &mut cx)?;
883 handlers::workdir(&mut cx, &path)
884 }
885 StepKind::Workspace(target) => handlers::workspace(&mut cx, target),
886 StepKind::RemoteBlock {
887 target,
888 vars,
889 env,
890 body,
891 } => super::remote::run_remote_block(&mut cx, target, vars, env, body),
892 StepKind::Env { key, value } => {
893 let resolved = super::args::resolve_arg(value, &mut cx)?;
894 handlers::env(&mut cx, key, &resolved)
895 }
896 StepKind::InheritEnv { keys } => {
897 handlers::inherit_env(&mut cx, keys)?;
898 sync_iteration_assert_needles(
899 cx.state,
900 &[Step {
901 guard: None,
902 kind: cmd.clone(),
903 scope_enter: 0,
904 scope_exit: 0,
905 line: 0,
906 col: 0,
907 }],
908 generation,
909 )?;
910 Ok(())
911 }
912 StepKind::IsolatedInheritEnv { keys } => {
913 handlers::isolated_inherit_env(&mut cx, keys)?;
914 Ok(())
915 }
916 StepKind::Copy {
917 from_workspace,
918 from_host,
919 to_host,
920 from,
921 to,
922 } => {
923 if *from_host || *to_host {
924 super::remote::copy_transfer(&mut cx, *from_host, *to_host, from, to)
925 } else {
926 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
927 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
928 handlers::copy(
929 &mut cx,
930 from_workspace.clone(),
931 &from_resolved,
932 &to_resolved,
933 )
934 }
935 }
936 StepKind::CopyGit {
937 rev,
938 from,
939 to,
940 include_dirty,
941 } => {
942 let rev_resolved = super::args::resolve_arg(rev, &mut cx)?;
943 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
944 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
945 handlers::copy_git(
946 &mut cx,
947 &rev_resolved,
948 &from_resolved,
949 &to_resolved,
950 *include_dirty,
951 )
952 }
953 StepKind::Archive { src, dst, raw } => {
954 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
955 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
956 handlers::archive(&mut cx, &src_resolved, &dst_resolved, *raw)
957 }
958 StepKind::Unarchive {
959 src,
960 dst,
961 max_bytes,
962 } => {
963 let src_resolved = super::args::resolve_arg(src, &mut cx)?;
964 let dst_resolved = super::args::resolve_arg(dst, &mut cx)?;
965 let cap_resolved = super::args::resolve_arg_opt(max_bytes, &mut cx)?;
966 handlers::unarchive(
967 &mut cx,
968 &src_resolved,
969 &dst_resolved,
970 cap_resolved.as_deref(),
971 )
972 }
973 StepKind::Symlink {
974 from_workspace,
975 from,
976 to,
977 } => {
978 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
979 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
980 handlers::symlink(
981 &mut cx,
982 from_workspace.clone(),
983 &from_resolved,
984 &to_resolved,
985 )
986 }
987 StepKind::Mkdir(arg) => {
988 let path = super::args::resolve_arg(arg, &mut cx)?;
989 handlers::mkdir(&mut cx, &path)
990 }
991 StepKind::Install { from, to } => {
992 let from_resolved = super::args::resolve_arg(from, &mut cx)?;
993 let to_resolved = super::args::resolve_arg(to, &mut cx)?;
994 handlers::install(&mut cx, &from_resolved, &to_resolved)
995 }
996 StepKind::SetExecutable { path } => {
997 let resolved = super::args::resolve_arg(path, &mut cx)?;
998 handlers::set_executable(&mut cx, &resolved)
999 }
1000 StepKind::Ls(arg) => {
1001 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1002 handlers::ls(&mut cx, &resolved)
1003 }
1004 StepKind::Read(arg) => {
1005 let resolved = super::args::resolve_arg_opt(arg, &mut cx)?;
1006 handlers::read(&mut cx, &resolved)
1007 }
1008 StepKind::ReadLine { var } => handlers::read_line(&mut cx, var),
1009 StepKind::Prompt {
1010 var,
1011 message,
1012 default,
1013 } => {
1014 let message_resolved = super::args::resolve_arg(message, &mut cx)?;
1015 let default_resolved = match default {
1016 Some(d) => Some(super::args::resolve_arg(d, &mut cx)?),
1017 None => None,
1018 };
1019 handlers::prompt(&mut cx, var, &message_resolved, default_resolved.as_deref())
1020 }
1021 StepKind::ListAppend { list, item } => {
1022 let value = super::args::evaluate_assert_operand(item, &mut cx)?;
1023 handlers::push_into(&mut cx, list, value)
1024 }
1025 StepKind::Write { path, contents } => {
1026 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1027 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
1028 handlers::write(&mut cx, &path_resolved, contents_resolved.as_deref())
1029 }
1030 StepKind::Append { path, contents } => {
1031 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1032 let contents_resolved = super::args::resolve_arg_opt(contents, &mut cx)?;
1033 handlers::append(&mut cx, &path_resolved, contents_resolved.as_deref())
1034 }
1035 StepKind::AppendLine { path, contents } => {
1036 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1037 let contents_resolved = super::args::resolve_arg(contents, &mut cx)?;
1038 handlers::append_line(&mut cx, &path_resolved, &contents_resolved)
1039 }
1040 StepKind::Remove { path, recursive } => {
1041 let path_resolved = super::args::resolve_arg(path, &mut cx)?;
1042 handlers::remove(&mut cx, &path_resolved, *recursive)
1043 }
1044 StepKind::Expand { path, overrides } => {
1045 let path_resolved = super::args::resolve_arg_opt(path, &mut cx)?;
1046 let overrides_resolved = super::args::resolve_overrides(overrides, &mut cx)?;
1047 handlers::replace(&mut cx, &path_resolved, &overrides_resolved)
1048 }
1049 StepKind::AssertEq {
1050 hash,
1051 actual,
1052 expected,
1053 }
1054 | StepKind::AssertNe {
1055 hash,
1056 actual,
1057 expected,
1058 } => {
1059 let (verb, expect_equal) = match cmd {
1060 StepKind::AssertEq { .. } => (Command::AssertEq.as_str(), true),
1061 _ => (Command::AssertNe.as_str(), false),
1062 };
1063 let target = resolve_assert_target(actual, &mut cx)?;
1064 let expected_resolved = match expected {
1065 Some(e) => Some(super::args::evaluate_assert_operand(e, &mut cx)?),
1066 None => None,
1067 };
1068 handlers::assert_equality(
1069 &mut cx,
1070 generation,
1071 verb,
1072 expect_equal,
1073 hash,
1074 &target,
1075 expected_resolved.as_ref(),
1076 )
1077 }
1078 StepKind::AssertContains { haystack, needle } => {
1079 let target = resolve_assert_target(haystack, &mut cx)?;
1080 handlers::assert_contains(&mut cx, generation, idx, &target, needle)
1081 }
1082 StepKind::WithIoBlock { .. } => Err(step_diag::eval_with_io_unexpanded()),
1083 StepKind::Exit(code) => {
1084 let code = super::args::resolve_arg_as_int(code, &mut cx)?;
1085 handlers::exit(&mut cx, code)
1086 }
1087 StepKind::Bind {
1088 var,
1089 decl_type,
1090 is_const,
1091 rhs: oxdock_parser::BindRhs::Expr(expr),
1092 } => handlers::assign(&mut cx, var, decl_type.clone(), expr, *is_const),
1093 StepKind::Bind {
1094 var,
1095 decl_type,
1096 is_const,
1097 rhs: oxdock_parser::BindRhs::Async(body),
1098 } => handlers::dispatch_assign_async(var, decl_type.clone(), body, &mut cx, *is_const),
1099 StepKind::Bind {
1100 var,
1101 decl_type,
1102 is_const,
1103 rhs: oxdock_parser::BindRhs::Await { task_var, .. },
1104 } => handlers::dispatch_await_capture(var, decl_type.clone(), task_var, &mut cx, *is_const),
1105 StepKind::Set { var, expr } => handlers::set_var_value(&mut cx, var, expr),
1106 StepKind::Await { var, .. } => handlers::dispatch_await(var, &mut cx),
1107 StepKind::Cancel { var, .. } => handlers::dispatch_cancel(var, &mut cx),
1108 StepKind::Sleep { duration } => {
1109 let duration = super::args::resolve_arg_as_duration(duration, &mut cx)?;
1110 handlers::sleep(&mut cx, &duration)
1111 }
1112 StepKind::TypeAlias { .. } => {
1113 Ok(())
1116 }
1117 StepKind::FuncDef { .. }
1118 | StepKind::Call { .. }
1119 | StepKind::Return { .. }
1120 | StepKind::ImportFile { .. }
1121 | StepKind::ImportFuncs { .. }
1122 | StepKind::While { .. }
1123 | StepKind::Break
1124 | StepKind::Continue
1125 | StepKind::For { .. }
1126 | StepKind::If { .. }
1127 | StepKind::Switch { .. }
1128 | StepKind::Timeout { .. }
1129 | StepKind::Fail { .. }
1130 | StepKind::Isolated { .. }
1131 | StepKind::WithIo { .. }
1132 | StepKind::Bind {
1133 rhs: oxdock_parser::BindRhs::Capture(_),
1134 ..
1135 } => {
1136 unreachable!("compound steps dispatch before this match")
1137 }
1138 }?;
1139 Ok(Flow::Done)
1140}
1141
1142#[allow(clippy::too_many_arguments)]
1143fn step_error(step: &Step, idx: usize, mut err: Diagnostic) -> Diagnostic {
1153 let mut loc = format!("step {}", idx + 1);
1154 if step.line > 0 {
1155 loc.push_str(&format!(", line {}", step.line));
1156 if step.col > 0 {
1157 loc.push_str(&format!(", col {}", step.col));
1158 }
1159 }
1160 if step.line > 0 {
1161 let span = if step.col > 0 {
1162 Span::line_col(step.line, step.col)
1163 } else {
1164 Span::line_only(step.line)
1165 };
1166 if err.span().is_none() {
1169 err = err.with_span(span);
1170 }
1171 }
1172 err.with_contexts(vec![loc])
1175}
1176
1177struct InnerArgs<'a, P: ProcessManager> {
1181 state: &'a mut ExecState<P>,
1182 process: &'a mut P,
1183 generation: usize,
1184 steps: &'a [Step],
1185 stdin: CommandStdin,
1186 expose_stdin: bool,
1187 out: Option<StreamHandle>,
1188 err: Option<StreamHandle>,
1189 out_pipe: Option<Arc<PipeInner>>,
1190 stdin_pipe: Option<Arc<PipeInner>>,
1191 wait_at_end: bool,
1192}
1193
1194fn execute_steps_inner<P: ProcessManager>(args: InnerArgs<'_, P>) -> DiagnosticResult<Flow> {
1195 let InnerArgs {
1196 state,
1197 process,
1198 generation,
1199 steps,
1200 stdin,
1201 expose_stdin,
1202 out,
1203 err,
1204 out_pipe,
1205 stdin_pipe,
1206 wait_at_end,
1207 } = args;
1208 pre_register_assertions(state, steps, generation)?;
1210
1211 for (idx, step) in steps.iter().enumerate() {
1212 if state.cancel_token.load(Ordering::SeqCst) {
1214 return Err(step_diag::eval_async_cancelled());
1215 }
1216 if step.scope_enter > 0 {
1217 for _ in 0..step.scope_enter {
1218 state.push_scope();
1219 }
1220 }
1221
1222 let should_run = guard_option_allows(step.guard.as_ref(), &state.envs);
1223 let flow_result: DiagnosticResult<Flow> = (|| {
1227 if !should_run {
1228 Ok(Flow::Done)
1229 } else {
1230 let flow_result: DiagnosticResult<Flow> = match &step.kind {
1235 StepKind::FuncDef { .. }
1236 | StepKind::Call { .. }
1237 | StepKind::Return { .. }
1238 | StepKind::ImportFile { .. }
1239 | StepKind::ImportFuncs { .. }
1240 | StepKind::While { .. }
1241 | StepKind::Break
1242 | StepKind::Continue
1243 | StepKind::For { .. }
1244 | StepKind::If { .. }
1245 | StepKind::Switch { .. }
1246 | StepKind::Timeout { .. }
1247 | StepKind::Fail { .. }
1248 | StepKind::Isolated { .. }
1249 | StepKind::WithIo { .. }
1250 | StepKind::Bind {
1251 rhs: oxdock_parser::BindRhs::Capture(_),
1252 ..
1253 } => {
1254 let mut cx = StepCtx {
1255 state,
1256 process,
1257 stdin: stdin.clone(),
1258 expose_stdin,
1259 out: out.clone(),
1260 err: err.clone(),
1261 out_pipe: out_pipe.clone(),
1262 stdin_pipe: stdin_pipe.clone(),
1263 tty: None,
1264 };
1265 dispatch_flow_step(&step.kind, &mut cx, generation, idx)
1266 }
1267 _ => {
1268 let flow = execute_single_step_with_generation(
1269 state,
1270 process,
1271 &step.kind,
1272 generation,
1273 idx,
1274 stdin.clone(),
1275 expose_stdin,
1276 out.clone(),
1277 err.clone(),
1278 out_pipe.clone(),
1279 stdin_pipe.clone(),
1280 None,
1281 )?;
1282 if matches!(
1283 &step.kind,
1284 StepKind::Env { .. }
1285 | StepKind::InheritEnv { .. }
1286 | StepKind::IsolatedInheritEnv { .. }
1287 ) {
1288 sync_iteration_assert_needles(state, steps, generation)?;
1289 }
1290 Ok(flow)
1291 }
1292 };
1293 flow_result
1294 }
1295 })()
1296 .map_err(|err| step_error(step, idx, err));
1297
1298 let restore_result = restore_scopes(state, step.scope_exit);
1299 let expiry_drained = if let Some(expiry) = state.keeper_expiry.as_mut() {
1304 expiry.expire_step(steps, idx)
1305 } else {
1306 false
1307 };
1308 if expiry_drained {
1309 state.keeper_expiry = None;
1310 }
1311 let flow = flow_result?;
1312 restore_result?;
1313 match flow {
1314 Flow::Done => {}
1315 Flow::Break { .. } | Flow::Continue { .. } | Flow::Return { .. } => {
1316 return Ok(flow);
1317 }
1318 }
1319 }
1320
1321 let reap_named = !state.inside_async;
1329 let floor = state.reap_floor;
1334 let in_scope = |id: u64| floor.map(|f| id >= f).unwrap_or(true);
1335 let has_bg = state.bg_children.iter().any(|c| in_scope(c.task_id));
1336 let named_pending = |state: &ExecState<P>| {
1337 reap_named
1338 && state
1339 .named_tasks
1340 .lock()
1341 .unwrap_or_else(|e| e.into_inner())
1342 .iter()
1343 .any(|(id, entry)| {
1344 in_scope(*id) && !entry.state.lock().unwrap_or_else(|e| e.into_inner()).reaped
1345 })
1346 };
1347 let has_named = named_pending(state);
1348 if wait_at_end && (has_bg || has_named) {
1349 loop {
1350 let mut failed_status: Option<Diagnostic> = None;
1351
1352 if failed_status.is_none() && state.cancel_token.load(Ordering::SeqCst) {
1357 failed_status = Some(step_diag::eval_async_cancelled());
1358 }
1359
1360 let mut i = 0;
1364 while i < state.bg_children.len() {
1365 if !in_scope(state.bg_children[i].task_id) {
1366 i += 1;
1367 continue;
1368 }
1369 match state.bg_children[i].handle.try_wait() {
1370 Ok(Some(status)) => {
1371 if !status.success() && failed_status.is_none() {
1372 failed_status = Some(step_diag::eval_async_exit_status(None, &status));
1373 break;
1374 }
1375 state.bg_children.swap_remove(i);
1376 }
1377 Ok(None) => {
1378 i += 1;
1379 }
1380 Err(e) => {
1381 if failed_status.is_none() {
1382 failed_status = Some(e);
1383 }
1384 break;
1385 }
1386 }
1387 }
1388
1389 if failed_status.is_none() && reap_named {
1393 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1394 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1395 named
1396 .iter()
1397 .map(|(id, entry)| (*id, Arc::clone(entry)))
1398 .collect()
1399 };
1400 for (id, entry) in &entries {
1401 if !in_scope(*id) {
1402 continue;
1403 }
1404 enum Poll {
1405 Pending,
1406 CompletedOk,
1407 CompletedErr(Diagnostic),
1408 }
1409 let poll = {
1410 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1411 match guard.phase {
1412 TaskPhase::Running | TaskPhase::Awaiting => {
1413 match guard.handle.as_mut() {
1414 Some(handle) => match handle.try_wait() {
1415 Ok(Some(status)) => {
1416 let _ = guard.handle.take();
1417 guard.phase = TaskPhase::Completed;
1418 if status.success() {
1419 Poll::CompletedOk
1420 } else {
1421 Poll::CompletedErr(
1422 step_diag::eval_async_exit_status(
1423 Some(*id),
1424 &status,
1425 ),
1426 )
1427 }
1428 }
1429 Ok(None) => Poll::Pending,
1430 Err(e) => {
1431 let _ = guard.handle.take();
1432 guard.phase = TaskPhase::Completed;
1433 Poll::CompletedErr(e)
1434 }
1435 },
1436 None => Poll::Pending,
1439 }
1440 }
1441 TaskPhase::Cancelled | TaskPhase::Completed => Poll::Pending,
1442 }
1443 };
1444 match poll {
1445 Poll::Pending => {}
1446 Poll::CompletedOk => {
1447 entry.finish_teardown();
1448 }
1449 Poll::CompletedErr(e) => {
1450 entry.finish_teardown();
1451 if failed_status.is_none() {
1452 failed_status = Some(e);
1453 }
1454 break;
1455 }
1456 }
1457 }
1458 }
1459
1460 if let Some(err) = failed_status {
1465 for survivor in state.bg_children.iter_mut() {
1466 if in_scope(survivor.task_id) {
1467 let _ = survivor.handle.kill();
1468 }
1469 }
1470 if reap_named {
1471 let entries: Vec<(u64, Arc<TaskEntry>)> = {
1472 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1473 named
1474 .iter()
1475 .map(|(id, entry)| (*id, Arc::clone(entry)))
1476 .collect()
1477 };
1478 let mut to_kill: Vec<(Arc<TaskEntry>, Box<dyn BackgroundHandle>)> = Vec::new();
1479 for (id, entry) in &entries {
1480 if !in_scope(*id) {
1481 continue;
1482 }
1483 let mut guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1484 match guard.phase {
1485 TaskPhase::Running | TaskPhase::Awaiting => {
1486 guard.phase = TaskPhase::Cancelled;
1487 if let Some(handle) = guard.handle.take() {
1488 to_kill.push((Arc::clone(entry), handle));
1489 }
1490 }
1491 TaskPhase::Cancelled | TaskPhase::Completed => {}
1492 }
1493 }
1494 for (entry, mut handle) in to_kill {
1495 let _ = handle.kill();
1496 entry.finish_teardown();
1497 }
1498 }
1499 state.bg_children.retain(|c| !in_scope(c.task_id));
1503 return Err(err);
1504 }
1505
1506 let bg_empty = !state.bg_children.iter().any(|c| in_scope(c.task_id));
1507 if bg_empty && !named_pending(state) {
1508 return Ok(Flow::Done);
1509 }
1510 if reap_named {
1514 let unreaped: Vec<Arc<TaskEntry>> = {
1515 let named = state.named_tasks.lock().unwrap_or_else(|e| e.into_inner());
1516 named
1517 .iter()
1518 .filter(|(id, entry)| {
1519 if !in_scope(**id) {
1520 return false;
1521 }
1522 let guard = entry.state.lock().unwrap_or_else(|e| e.into_inner());
1523 matches!(guard.phase, TaskPhase::Cancelled) && !guard.reaped
1524 })
1525 .map(|(_, entry)| Arc::clone(entry))
1526 .collect()
1527 };
1528 for entry in &unreaped {
1529 entry.wait_reaped();
1530 }
1531 }
1532 std::thread::sleep(std::time::Duration::from_millis(10));
1533 }
1534 }
1535
1536 Ok(Flow::Done)
1537}
1538
1539fn restore_scopes<P: ProcessManager>(
1540 state: &mut ExecState<P>,
1541 count: usize,
1542) -> DiagnosticResult<()> {
1543 for _ in 0..count {
1544 state.pop_scope()?;
1545 }
1546 Ok(())
1547}
1548
1549#[allow(clippy::too_many_arguments)]
1556pub(super) fn execute_scoped_remote_body<P: ProcessManager>(
1557 state: &mut ExecState<P>,
1558 process: &mut P,
1559 steps: &[Step],
1560 stdin: CommandStdin,
1561 expose_stdin: bool,
1562 out: Option<StreamHandle>,
1563 err: Option<StreamHandle>,
1564 out_pipe: Option<Arc<PipeInner>>,
1565 stdin_pipe: Option<Arc<PipeInner>>,
1566) -> DiagnosticResult<()> {
1567 let flow = execute_scoped_steps(
1568 state,
1569 process,
1570 steps,
1571 stdin,
1572 expose_stdin,
1573 out,
1574 err,
1575 out_pipe,
1576 stdin_pipe,
1577 true,
1578 )?;
1579 match flow {
1580 Flow::Done => Ok(()),
1581 Flow::Break { idx } => Err(step_diag::eval_flow_crosses_remote(idx + 1, KEYWORD_BREAK)),
1582 Flow::Continue { idx } => Err(step_diag::eval_flow_crosses_remote(
1583 idx + 1,
1584 KEYWORD_CONTINUE,
1585 )),
1586 Flow::Return { idx, .. } => {
1587 Err(step_diag::eval_flow_crosses_remote(idx + 1, KEYWORD_RETURN))
1588 }
1589 }
1590}
1591
1592#[allow(clippy::too_many_arguments)]
1597pub(super) fn execute_scoped_steps<P: ProcessManager>(
1598 state: &mut ExecState<P>,
1599 process: &mut P,
1600 steps: &[Step],
1601 stdin: CommandStdin,
1602 expose_stdin: bool,
1603 out: Option<StreamHandle>,
1604 err: Option<StreamHandle>,
1605 out_pipe: Option<Arc<PipeInner>>,
1606 stdin_pipe: Option<Arc<PipeInner>>,
1607 wait_at_end: bool,
1608) -> DiagnosticResult<Flow> {
1609 state.push_scope();
1610 let res = execute_steps(
1611 state,
1612 process,
1613 steps,
1614 stdin,
1615 expose_stdin,
1616 out,
1617 err,
1618 out_pipe,
1619 stdin_pipe,
1620 wait_at_end,
1621 );
1622 let pop_res = state.pop_scope();
1625 match (res, pop_res) {
1626 (Ok(flow), Ok(())) => Ok(flow),
1627 (Err(e), _) => Err(e),
1628 (Ok(_), Err(e)) => Err(e),
1629 }
1630}
1631
1632fn dispatch_flow_step<P: ProcessManager>(
1636 cmd: &StepKind,
1637 cx: &mut StepCtx<'_, P>,
1638 generation: usize,
1639 idx: usize,
1640) -> DiagnosticResult<Flow> {
1641 match cmd {
1642 StepKind::FuncDef {
1643 name,
1644 params,
1645 return_type,
1646 is_async,
1647 body,
1648 ..
1649 } => {
1650 handlers::define_func(cx, name, params, return_type, *is_async, body)?;
1651 Ok(Flow::Done)
1652 }
1653 StepKind::Call { name, args } => {
1654 let _ = handlers::call_func_value(cx, name, args)?;
1655 Ok(Flow::Done)
1656 }
1657 StepKind::Return { expr, .. } => handlers::handle_return(cx, idx, expr),
1658 StepKind::ImportFile { path, alias } => {
1659 let _ = super::import::import_file(cx, path, alias)?;
1660 Ok(Flow::Done)
1661 }
1662 StepKind::ImportFuncs {
1663 path,
1664 alias,
1665 func_names,
1666 type_names,
1667 } => {
1668 super::import::import_funcs(cx, path, alias.as_deref(), func_names, type_names)?;
1669 Ok(Flow::Done)
1670 }
1671 StepKind::While { cond, body } => handlers::while_loop(cx, cond, body),
1672 StepKind::Break => Ok(Flow::Break { idx }),
1673 StepKind::Continue => Ok(Flow::Continue { idx }),
1674 StepKind::For {
1675 key_var,
1676 key_type,
1677 var,
1678 var_type,
1679 in_expr,
1680 body,
1681 } => handlers::for_loop(
1682 cx,
1683 key_var.as_deref(),
1684 key_type.clone(),
1685 var,
1686 var_type.clone(),
1687 in_expr,
1688 body,
1689 ),
1690 StepKind::If {
1691 cond,
1692 then_body,
1693 else_ifs,
1694 else_body,
1695 } => handlers::if_then(cx, cond, then_body, else_ifs, else_body),
1696 StepKind::Switch {
1697 discriminant,
1698 cases,
1699 default_body,
1700 } => handlers::switch_run(cx, discriminant, cases, default_body),
1701 StepKind::Timeout { duration, body } => {
1702 let duration = super::args::resolve_arg_as_duration(duration, cx)?;
1703 handlers::timeout(cx, &duration, body)
1704 }
1705 StepKind::Fail {
1706 code,
1707 message,
1708 body,
1709 } => handlers::fail(cx, code, message, body),
1710 StepKind::Isolated { body } => handlers::isolated(cx, body),
1711 StepKind::WithIo { bindings, cmd } => handlers::with_io(cx, generation, idx, bindings, cmd),
1712 StepKind::Bind {
1713 var,
1714 decl_type,
1715 is_const,
1716 rhs: oxdock_parser::BindRhs::Capture(cmd),
1717 } => handlers::assign_capture(cx, generation, idx, var, decl_type.clone(), cmd, *is_const),
1718 _ => {
1719 unreachable!("dispatch_flow_step handles only compound steps")
1720 }
1721 }
1722}
1723
1724#[cfg(test)]
1725mod thread_handle_tests {
1726 use super::super::exit::exit_code_of_diag;
1727 use super::*;
1728
1729 fn bare_handle(
1730 join: Option<std::thread::JoinHandle<DiagnosticResult<()>>>,
1731 ) -> ThreadJoinHandle {
1732 ThreadJoinHandle {
1733 join,
1734 cancel_token: Arc::new(AtomicBool::new(false)),
1735 cancel_hub: Arc::new(oxdock_process::CancelHub::new()),
1736 active_process: Arc::new(Mutex::new(None)),
1737 worker: Arc::new(Mutex::new(None)),
1738 thread_error: None,
1739 thread_context: Vec::new(),
1740 thread_exit_code: None,
1741 }
1742 }
1743
1744 #[test]
1745 fn panic_payload_reports_thread_panicked_key() {
1746 let join = std::thread::spawn(|| -> DiagnosticResult<()> {
1747 panic!("boom-payload");
1748 });
1749 let mut handle = bare_handle(Some(join));
1750 let diag = handle.wait().expect_err("panic must surface");
1751 assert_eq!(diag.key(), "dsl.eval.async_thread_panicked");
1752 assert!(diag.message().contains("boom-payload"));
1753 }
1754
1755 #[test]
1756 fn wrapped_diagnostic_keeps_key_and_outer_context() {
1757 let leaf = step_diag::eval_async_cancelled();
1758 let join = std::thread::spawn(|| -> DiagnosticResult<()> {
1759 Err(leaf.with_contexts(vec!["step 1".to_string(), "step 2".to_string()]))
1760 });
1761 let mut handle = bare_handle(Some(join));
1762 let diag = handle.wait().expect_err("wrapped failure must surface");
1763 assert_eq!(diag.key(), "dsl.eval.async_cancelled");
1764 assert_eq!(
1765 diag.contexts(),
1766 &["step 1".to_string(), "step 2".to_string()],
1767 "each outer frame replays natively in order: {diag:#}"
1768 );
1769 assert_eq!(diag.to_string(), "step 1: step 2: ASYNC task cancelled");
1770 }
1771
1772 #[test]
1773 fn sourceless_diagnostic_keeps_key_and_exit_code() {
1774 let mut handle = bare_handle(None);
1775 handle.thread_error = Some(step_diag::eval_async_cancelled());
1776 handle.thread_exit_code = Some(7);
1777 let diag = handle.reemit_error();
1778 assert_eq!(exit_code_of_diag(&diag), Some(7));
1779 assert_eq!(diag.key(), "dsl.eval.async_cancelled");
1780 }
1781
1782 #[test]
1783 fn sourced_diagnostic_keeps_key_source_and_exit_code() {
1784 let sourced = step_diag::eval_async_cancelled().with_source(Arc::new(std::io::Error::new(
1785 std::io::ErrorKind::NotFound,
1786 "gone",
1787 )));
1788 assert!(
1789 std::error::Error::source(&sourced).is_some(),
1790 "fixture must carry a source to cover the chained branch"
1791 );
1792 let mut handle = bare_handle(None);
1793 handle.thread_error = Some(sourced);
1794 handle.thread_exit_code = Some(7);
1795 let diag = handle.reemit_error();
1796 let err = anyhow::Error::new(diag.clone());
1797 assert_eq!(exit_code_of_diag(&diag), Some(7));
1798 assert_eq!(diag.key(), "dsl.eval.async_cancelled");
1799 let io = err
1800 .chain()
1801 .find_map(|cause| cause.downcast_ref::<std::io::Error>())
1802 .expect("original source survives behind the exit code");
1803 assert_eq!(io.kind(), std::io::ErrorKind::NotFound);
1804 assert_eq!(
1805 format!("{err:#}"),
1806 "ASYNC task cancelled: EXIT requested with code 7: gone"
1807 );
1808 }
1809
1810 #[test]
1811 fn bare_exit_request_relays_as_keyed_diagnostic() {
1812 let join = std::thread::spawn(|| -> DiagnosticResult<()> {
1816 Err(step_diag::eval_exit_requested(7).with_contexts(vec!["step 2".to_string()]))
1817 });
1818 let mut handle = bare_handle(Some(join));
1819 let diag = handle.wait().expect_err("exit request must surface");
1820 assert_eq!(exit_code_of_diag(&diag), Some(7));
1821 assert_eq!(diag.key(), "dsl.eval.exit_requested");
1822 assert_eq!(diag.fields().get("code"), Some(&"7".to_string()));
1823 assert_eq!(format!("{diag:#}"), "step 2: EXIT requested with code 7");
1824 }
1825
1826 #[test]
1827 fn bare_exit_code_without_diagnostic_reemits_exit_requested() {
1828 let mut handle = bare_handle(None);
1831 handle.thread_exit_code = Some(7);
1832 let diag = handle.reemit_error();
1833 assert_eq!(exit_code_of_diag(&diag), Some(7));
1834 assert_eq!(diag.key(), "dsl.eval.exit_requested");
1835 assert_eq!(diag.fields().get("code"), Some(&"7".to_string()));
1836 }
1837}
1838
1839#[cfg(test)]
1840mod step_error_tests {
1841 use super::*;
1842 use oxdock_parser::StepKind;
1843
1844 fn step_at(line: usize, col: usize) -> Step {
1845 Step {
1846 guard: None,
1847 kind: StepKind::Break,
1848 scope_enter: 0,
1849 scope_exit: 0,
1850 line,
1851 col,
1852 }
1853 }
1854
1855 #[test]
1856 fn coordinates_attach_span_and_keep_text_prefix() {
1857 let leaf = step_diag::eval_async_cancelled();
1858 assert!(leaf.span().is_none());
1859 let err = step_error(&step_at(5, 3), 0, leaf);
1860 let span = err.span().expect("coordinates attach natively");
1861 assert_eq!(span.line, 5);
1862 assert_eq!(span.col_start, Some(3));
1863 assert!(
1864 format!("{err:#}").starts_with("step 1, line 5, col 3: "),
1865 "text prefix stays byte-identical: {err:#}"
1866 );
1867 }
1868
1869 #[test]
1870 fn innermost_span_wins_on_nested_dispatch() {
1871 let leaf = step_diag::eval_async_cancelled();
1872 let inner = step_error(&step_at(5, 3), 1, leaf);
1873 let outer = step_error(&step_at(9, 1), 0, inner);
1874 let span = outer.span().expect("span survives");
1875 assert_eq!((span.line, span.col_start), (5, Some(3)));
1876 assert!(
1877 format!("{outer:#}").starts_with("step 1, line 9, col 1: step 2, line 5, col 3: "),
1878 "both text frames chain like a call path: {outer:#}"
1879 );
1880 }
1881
1882 #[test]
1883 fn unknown_position_keeps_bare_prefix_without_span() {
1884 let leaf = step_diag::eval_async_cancelled();
1885 let err = step_error(&step_at(0, 0), 0, leaf);
1886 assert!(err.span().is_none());
1887 assert_eq!(format!("{err:#}"), "step 1: ASYNC task cancelled");
1888 }
1889
1890 #[test]
1891 fn prespanned_outermost_diagnostic_keeps_its_span() {
1892 let leaf = step_diag::eval_async_cancelled().with_span(Span::line_col(2, 4));
1895 let err = step_error(&step_at(9, 1), 0, leaf);
1896 let span = err.span().expect("span survives");
1897 assert_eq!((span.line, span.col_start), (2, Some(4)));
1898 }
1899
1900 #[test]
1901 fn synthetic_inner_yields_to_parsed_outer_coordinates() {
1902 let leaf = step_diag::eval_async_cancelled();
1906 let inner = step_error(&step_at(0, 0), 1, leaf);
1907 let outer = step_error(&step_at(9, 1), 0, inner);
1908 let span = outer.span().expect("outer coordinates attach");
1909 assert_eq!((span.line, span.col_start), (9, Some(1)));
1910 assert!(
1911 format!("{outer:#}").starts_with("step 1, line 9, col 1: step 2: "),
1912 "inner text frame replays under the outer prefix: {outer:#}"
1913 );
1914 }
1915
1916 #[test]
1917 fn line_without_column_attaches_line_only_span() {
1918 let leaf = step_diag::eval_async_cancelled();
1919 let err = step_error(&step_at(7, 0), 0, leaf);
1920 let span = err.span().expect("line-only span attaches");
1921 assert_eq!(span.line, 7);
1922 assert_eq!(span.col_start, None);
1923 assert!(
1924 format!("{err:#}").starts_with("step 1, line 7: "),
1925 "prefix names the line with no column: {err:#}"
1926 );
1927 }
1928}