From 0a03ecc557c974ab07d81e31ce0791f7ab7c5922 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 17:43:47 +0000 Subject: [PATCH 1/2] fix(shell): a function pops its frame when a command in it fails A call to a shell function pushes a frame: the caller's positional parameters, and the old value of each variable the body declares `local`. `execute_function_call` popped the frame after the body. A command in the body that returned an error left through `?` inside the body loop, before the pop. The caller then kept the function's `local` values and had the function's arguments as its own `$1`, `$2`, ... and `$#`. The call depth stayed raised as well, so `local` and `return` were accepted outside any function. A nested call left one frame behind for each function the error passed through. The body now runs in a function of its own, `run_function_body`. Its result, whichever it is, comes back to one place in `execute_function_call`, which pops the frame and then returns the result. The error still goes to the caller. The body loop and the pop are otherwise unchanged. This fault was noted in the review of #233 and left out of it. Where the fault shows. At the prompt: the interactive loop reports an error and reads the next line with the same state. It does not show with `-c` or a script file on `main`: there the first error ends the whole run, before a later command can show what the caller kept. That is a separate fault and is not touched here. So this line from the review f() { local x=inner; mkdir /no/such/parent/dir; }; x=outer; f; echo "$x" given to `-c` prints the error and exits 1 before and after this change, where bash 5.2.21 prints `outer`. With the function in a sourced file, the same commands at the prompt printed `inner` before this change. They print `outer` now, as bash does. Tests. Four in the new tests/function_frame_tests.rs run the built shell at its prompt through a pseudo-terminal: a `local` variable, the positional parameters, a nested call, and `local` and `return` at the prompt after a function failed. The `after:` lines they expect are what bash 5.2.21 prints for the same lines. They drive both prompts (the line editor of the default build and the plain prompt of --no-default-features) and are built on Linux only. One test in function_and_script_tests.rs calls the library and runs on every platform. All five fail on the code before this change, with both builds, and pass after it. For the pseudo-terminal, the `nix` crate (already a dependency, same version) is also listed under dev-dependencies with its `term` feature, so the feature is on for test builds only. Cargo.lock does not change. cargo fmt --check and cargo clippy --all-targets -- -D warnings are clean. cargo test --no-fail-fast: 832 passed, 0 failed, 15 ignored, with OLDPWD and PWD set and with both unset. Also run as the CI matrix does: --all-features (839 passed) and --no-default-features (832 passed), no failures. No proof is added or changed, and no proof covers function frames. The evidence for this change is tests only. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01J4QvDjYffb3HcnwwDyrsF9 --- impl/rust-cli/Cargo.toml | 5 + impl/rust-cli/src/executable.rs | 68 ++-- .../tests/function_and_script_tests.rs | 33 ++ impl/rust-cli/tests/function_frame_tests.rs | 349 ++++++++++++++++++ 4 files changed, 434 insertions(+), 21 deletions(-) create mode 100644 impl/rust-cli/tests/function_frame_tests.rs diff --git a/impl/rust-cli/Cargo.toml b/impl/rust-cli/Cargo.toml index d0a8569c..e2a4525d 100644 --- a/impl/rust-cli/Cargo.toml +++ b/impl/rust-cli/Cargo.toml @@ -84,6 +84,11 @@ which = "7.0" proptest = "1.10" tempfile = "3.26" +# Pseudo-terminal for the tests that run the built shell at its prompt +# (tests/function_frame_tests.rs). Same crate and version as above; the `term` +# feature is turned on for test builds only. +nix = { version = "0.31", default-features = false, features = ["fs", "term"] } + # Benchmarking criterion = "0.5" diff --git a/impl/rust-cli/src/executable.rs b/impl/rust-cli/src/executable.rs index aeb72a25..eabc20a3 100644 --- a/impl/rust-cli/src/executable.rs +++ b/impl/rust-cli/src/executable.rs @@ -1459,11 +1459,12 @@ impl ExecutableCommand for Command { /// 1. Save current positional parameters /// 2. Set new positional parameters from function arguments /// 3. Push a function frame for local variable scoping -/// 4. Parse the raw function body, splitting on semicolons/newlines with -/// control-structure awareness (so `if/fi`, `for/done`, `while/done`, -/// and `case/esac` work inside a function body) -/// 5. Execute each segment; stop early on `return` / `exit` -/// 6. Restore positional parameters and local variables +/// 4. Run the body ([`run_function_body`]) +/// 5. Pop the frame: restore positional parameters and local variables +/// +/// Step 5 runs however the body ended: at its last command, at `return` or +/// `exit`, or at a command that returned an error. The error still goes to +/// the caller; the frame does not go with it. fn execute_function_call( func_def: &crate::functions::FunctionDef, args: &[String], @@ -1478,6 +1479,47 @@ fn execute_function_call( // Push a function frame state.functions.push_frame(saved_params.clone()); + // Run the body. There is no `?` on this call, and there must not be one: + // the frame is popped before the result goes back, whichever it is. An + // error that left with the frame still pushed would leave the caller + // with the function's local variables and positional parameters, and + // with a call depth that lets `local` and `return` run outside any + // function. + let result = run_function_body(func_def, state); + + // Pop function frame and restore local variables + if let Some(frame) = state.functions.pop_frame() { + // Restore positional parameters + state.set_positional_params(frame.saved_params); + + // Restore local variables to their previous values + for (var_name, prev_value) in &frame.saved_vars { + match prev_value { + Some(val) => state.set_variable(var_name.clone(), val.clone()), + None => { + state.unset_variable(var_name); + } + } + } + } + + result +} + +/// Run the body of a shell function, inside the frame that +/// [`execute_function_call`] pushed and will pop. +/// +/// 1. Parse the raw function body, splitting on semicolons/newlines with +/// control-structure awareness (so `if/fi`, `for/done`, `while/done`, +/// and `case/esac` work inside a function body) +/// 2. Execute each segment; stop early on `return` / `exit` +/// +/// This is a function of its own so that every way out of the body, the `?` +/// below included, comes back to one place in the caller. +fn run_function_body( + func_def: &crate::functions::FunctionDef, + state: &mut ShellState, +) -> Result { // Execute function body. We prefer the raw body string (which preserves // control-structure integrity) and fall back to the pre-split segments // for older in-memory definitions. @@ -1535,22 +1577,6 @@ fn execute_function_call( } } - // Pop function frame and restore local variables - if let Some(frame) = state.functions.pop_frame() { - // Restore positional parameters - state.set_positional_params(frame.saved_params); - - // Restore local variables to their previous values - for (var_name, prev_value) in &frame.saved_vars { - match prev_value { - Some(val) => state.set_variable(var_name.clone(), val.clone()), - None => { - state.unset_variable(var_name); - } - } - } - } - Ok(last_result) } diff --git a/impl/rust-cli/tests/function_and_script_tests.rs b/impl/rust-cli/tests/function_and_script_tests.rs index 51801da1..9710fe13 100644 --- a/impl/rust-cli/tests/function_and_script_tests.rs +++ b/impl/rust-cli/tests/function_and_script_tests.rs @@ -158,6 +158,39 @@ fn test_function_local_variables() -> Result<()> { Ok(()) } +/// A command in the body returns an error. The error goes on to the caller, +/// and the frame is popped all the same. +/// +/// This test calls the library, so it runs on every platform. The tests that +/// run the built shell are in `function_frame_tests.rs` (Linux only). +#[test] +fn test_function_that_fails_pops_its_frame() -> Result<()> { + let temp = tempdir()?; + let mut state = ShellState::new(temp.path().to_str().unwrap())?; + + state.set_variable("X", "global"); + state.set_positional_params(vec!["outer_arg".to_string()]); + + // `inner` fails: the parent of the directory does not exist + let inner_cmd = parse_command("inner() { local X=inner_val; mkdir no/such/parent/dir; }")?; + inner_cmd.execute(&mut state)?; + let outer_cmd = parse_command("outer() { local X=outer_val; inner inner_arg; }")?; + outer_cmd.execute(&mut state)?; + + let invoke_cmd = parse_command("outer outer_arg_1 outer_arg_2")?; + let result = invoke_cmd.execute(&mut state); + + // The error still reaches the caller + assert!(result.is_err(), "the failed mkdir should be an error"); + + // Both frames are gone, and the caller has its own values back + assert_eq!(state.functions.call_depth(), 0); + assert_eq!(state.get_variable("X"), Some("global")); + assert_eq!(state.positional_params, vec!["outer_arg".to_string()]); + + Ok(()) +} + #[test] fn test_function_return_value() -> Result<()> { let temp = tempdir()?; diff --git a/impl/rust-cli/tests/function_frame_tests.rs b/impl/rust-cli/tests/function_frame_tests.rs new file mode 100644 index 00000000..c8b97479 --- /dev/null +++ b/impl/rust-cli/tests/function_frame_tests.rs @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) Jonathan D.A. Jewell +//! A function gives its caller's variables and positional parameters back, +//! also when a command in it fails. +//! +//! A call pushes a frame: the caller's positional parameters, and the old +//! value of each variable the body declares `local`. The frame was popped +//! when the body ran to its end or reached `return`. A command that returned +//! an error left through `?`, past the pop. The caller then kept the +//! function's `local` values, had the function's arguments as `$1`, `$2`, +//! ..., and the shell went on as if it were still inside the function. +//! +//! These tests run the built shell, and they run it as a person does: at the +//! prompt, through a pseudo-terminal. That is where the fault shows. The +//! prompt reports an error and reads the next line with the same state. With +//! `-c` or a script file the first error ends the whole run (another fault, +//! not this one), so no command is left to show what the caller kept. +//! +//! The `after:` lines expected here are what GNU bash 5.2.21 prints for the +//! same lines. +//! +//! Built on Linux only: the pseudo-terminal handling here has been run +//! nowhere else. + +#![cfg(target_os = "linux")] + +use std::fs::{self, File}; +use std::io::{Read, Write}; +use std::path::Path; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use nix::fcntl::{fcntl, FcntlArg, FdFlag}; +use nix::pty::{openpty, Winsize}; + +/// The line editor asks the terminal where the cursor is before it draws the +/// prompt, and gives up after two seconds without an answer. +const CURSOR_QUERY: &[u8] = b"\x1b[6n"; + +/// What a terminal answers: row 1, column 1. +const CURSOR_ANSWER: &[u8] = b"\x1b[1;1R"; + +/// Every prompt of the shell ends like this, in both of its builds. +const PROMPT_END: &str = "> "; + +/// The longest a session may take. One takes well under a second. +const LIMIT: Duration = Duration::from_secs(30); + +/// Runs the built shell at its prompt in `dir`, types `lines` and then +/// `exit`, and returns everything the shell sent to the terminal. +/// +/// The shell has two prompts. The default build reads keys through a line +/// editor; a build with `--no-default-features` prints a prompt and reads a +/// line. Both are driven here, whichever was built. +fn at_the_prompt(dir: &Path, lines: &[&str]) -> String { + let size = Winsize { + ws_row: 24, + ws_col: 80, + ws_xpixel: 0, + ws_ypixel: 0, + }; + let pty = openpty(Some(&size), None).expect("open a pseudo-terminal"); + // Keep both ends out of the shells that other tests start meanwhile. + for end in [&pty.master, &pty.slave] { + fcntl(end, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)).expect("set close-on-exec"); + } + let mut screen = File::from(pty.master); + let mut keyboard = screen.try_clone().expect("a second handle on the terminal"); + + let mut shell = { + let terminal = pty.slave; + let mut command = Command::new(env!("CARGO_BIN_EXE_vsh")); + command + .arg("-r") + .arg(dir) + .current_dir(dir) + // The line editor keeps its history file in the home directory. + .env("HOME", dir) + .env("NO_COLOR", "1") + .env("TERM", "xterm") + .env_remove("RUST_BACKTRACE") + .stdin(Stdio::from( + terminal.try_clone().expect("terminal for input"), + )) + .stdout(Stdio::from( + terminal.try_clone().expect("terminal for output"), + )) + .stderr(Stdio::from(terminal)); + command.spawn().expect("start the built shell") + // `command` ends here, and with it this process's handles on the + // shell's end of the terminal: reading `screen` stops once the + // shell has gone. + }; + + // Read on a thread of its own, so that a shell that never finishes + // cannot hold the test past `LIMIT`. + let (sender, sent) = mpsc::channel::>(); + let reader = std::thread::spawn(move || { + let mut chunk = [0u8; 4096]; + // Reading ends with an error once the shell has gone. + while let Ok(count) = screen.read(&mut chunk) { + if count == 0 || sender.send(chunk[..count].to_vec()).is_err() { + break; + } + } + }); + + let started = Instant::now(); + let mut to_type = lines.iter().copied().chain(["exit"]); + let mut transcript: Vec = Vec::new(); + let mut searched = 0; + let mut line_editor = false; + let mut typed_at = 0; + let status = loop { + let gone = match sent.recv_timeout(Duration::from_millis(20)) { + Ok(chunk) => { + transcript.extend_from_slice(&chunk); + false + } + Err(mpsc::RecvTimeoutError::Timeout) => false, + Err(mpsc::RecvTimeoutError::Disconnected) => true, + }; + + // The line editor asks for the cursor before it draws each prompt. + while let Some(at) = find(&transcript[searched..], CURSOR_QUERY) { + searched += at + CURSOR_QUERY.len(); + press(&mut keyboard, CURSOR_ANSWER); + if !line_editor { + // The first query means the editor is reading keys. Type + // every line now: it takes one line at each Enter and keeps + // the rest for its next prompt. + line_editor = true; + for line in to_type.by_ref() { + type_line(&mut keyboard, line); + } + } + } + + // The plain prompt asks nothing: it is printed, and the shell waits + // for a line. Type one line at each new prompt. + if !line_editor && transcript.len() > typed_at { + let shown = plain(&String::from_utf8_lossy(&transcript)); + if shown.ends_with(PROMPT_END) { + if let Some(line) = to_type.next() { + type_line(&mut keyboard, line); + typed_at = transcript.len(); + } + } + } + + if gone { + match shell.try_wait().expect("wait for the shell") { + Some(status) => break status, + // The terminal closes a moment before the shell can be + // waited for. + None => std::thread::sleep(Duration::from_millis(1)), + } + } + if started.elapsed() > LIMIT { + let _ = shell.kill(); + let _ = shell.wait(); + panic!( + "the shell did not finish within {LIMIT:?}; the terminal showed:\n{}", + plain(&String::from_utf8_lossy(&transcript)) + ); + } + }; + reader.join().expect("the reading thread"); + + let transcript = String::from_utf8_lossy(&transcript).into_owned(); + assert!( + to_type.next().is_none(), + "the shell left ({status}) before every line was typed; the terminal showed:\n{}", + plain(&transcript) + ); + transcript +} + +/// Sends `keys` to the shell as if they were pressed. +/// +/// The write fails only when the shell has gone. The transcript then says +/// why, and the assertions show it. +fn press(keyboard: &mut File, keys: &[u8]) { + let _ = keyboard.write_all(keys); +} + +/// Types `line` and presses Enter. +fn type_line(keyboard: &mut File, line: &str) { + press(keyboard, line.as_bytes()); + press(keyboard, b"\r"); +} + +fn find(haystack: &[u8], needle: &[u8]) -> Option { + haystack + .windows(needle.len()) + .position(|window| window == needle) +} + +/// `text` without the colour and cursor codes the line editor sends. +fn plain(text: &str) -> String { + let mut out = String::new(); + let mut chars = text.chars(); + while let Some(c) = chars.next() { + if c != '\x1b' { + out.push(c); + continue; + } + // Either `ESC [`, parameters and a final letter, or `ESC` and one + // character. + if chars.next() == Some('[') { + for c in chars.by_ref() { + if ('@'..='~').contains(&c) { + break; + } + } + } + } + out +} + +/// The lines the shell printed that start with `prefix`. +/// +/// A line the test typed never does: it is shown after the prompt. +fn printed(transcript: &str, prefix: &str) -> Vec { + plain(transcript) + .lines() + .map(str::trim_end) + .filter(|line| line.starts_with(prefix)) + .map(String::from) + .collect() +} + +/// A fresh directory holding `functions` in `defs.sh`, for `source`. +/// +/// The functions come from a file because the prompt cuts a typed line at +/// every `;`, also inside `{ }`: a body of two commands cannot be typed +/// there on one line. +fn directory_with(functions: &str) -> tempfile::TempDir { + let dir = tempfile::tempdir().expect("temporary directory"); + fs::write(dir.path().join("defs.sh"), functions).expect("write defs.sh"); + dir +} + +/// In every test the command that fails is `mkdir` under a directory that +/// does not exist. The built-in returns an error for it. +const NO_PARENT: &str = "mkdir /no/such/parent/dir"; + +#[test] +fn a_function_that_fails_leaves_the_callers_variable_as_it_was() { + let dir = directory_with(&format!("f() {{ local x=inner; {NO_PARENT}; }}\n")); + + let seen = at_the_prompt( + dir.path(), + &[ + "source ./defs.sh", + "x=outer", + "f", + r#"echo "after: x is $x.""#, + ], + ); + + assert_eq!( + printed(&seen, "after:"), + ["after: x is outer."], + "the terminal showed:\n{}", + plain(&seen) + ); + // The frame is popped; the error still reaches the prompt. + assert_eq!( + printed(&seen, "Error:").len(), + 1, + "the failed mkdir should be reported once; the terminal showed:\n{}", + plain(&seen) + ); +} + +#[test] +fn a_function_that_fails_gives_the_caller_its_positional_parameters_back() { + let dir = directory_with(&format!("f() {{ {NO_PARENT}; }}\n")); + + let seen = at_the_prompt( + dir.path(), + &[ + "source ./defs.sh", + "set -- outer1 outer2", + "f inner1", + r#"echo "after: first is $1, count is $#.""#, + ], + ); + + assert_eq!( + printed(&seen, "after:"), + ["after: first is outer1, count is 2."], + "the terminal showed:\n{}", + plain(&seen) + ); +} + +/// `outer` calls `inner`, and a command in `inner` fails. The error passes +/// through both, so both frames have to go: the caller sees neither +/// `inner`'s variable and argument nor `outer`'s. +#[test] +fn a_failure_in_a_nested_call_pops_the_frame_of_every_function_it_leaves() { + let dir = directory_with(&format!( + "inner() {{ local x=in; {NO_PARENT}; }}\n\ + outer() {{ local x=mid; inner deep; }}\n" + )); + + let seen = at_the_prompt( + dir.path(), + &[ + "source ./defs.sh", + "x=top", + "set -- top1", + "outer mid1 mid2", + r#"echo "after: x is $x, first is $1, count is $#.""#, + ], + ); + + assert_eq!( + printed(&seen, "after:"), + ["after: x is top, first is top1, count is 1."], + "the terminal showed:\n{}", + plain(&seen) + ); +} + +/// The shell counts frames to know whether it is inside a function. With +/// the frame left behind, `local` and `return` typed at the prompt were +/// accepted. bash refuses both there. +#[test] +fn after_a_function_failed_the_shell_is_no_longer_inside_it() { + let dir = directory_with(&format!("f() {{ {NO_PARENT}; }}\n")); + + let seen = at_the_prompt( + dir.path(), + &["source ./defs.sh", "f", "local y=1", "return 0"], + ); + + for refused in ["Error: local:", "Error: return:"] { + assert_eq!( + printed(&seen, refused).len(), + 1, + "a line starting {refused:?} should be printed once; the terminal showed:\n{}", + plain(&seen) + ); + } +} From 86ab3fd95733e358fb999f8d691e0d060dc6992f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 01:27:45 +0000 Subject: [PATCH 2/2] fix(shell): a command that fails fails only itself; set -e works A built-in that failed was an error that unwound through every command around it, to the script or the prompt. So `mkdir x || echo no` never ran `echo no`, a loop stopped at its first failure, a function stopped and its caller stopped with it, and a `-c` script or script file ended at the first built-in that failed. That last one stood in for `set -e`, which was not implemented: `set -e` only stored a variable, so `set -e; false; echo after` printed `after`. Every command is now a boundary (`ExecutableCommand::execute`). A command that fails prints `vsh: ` and the reason, and gives status 1; whatever ran it goes on. `execute` no longer returns `Err` for a failed command. `set -e` is honoured. A simple command that fails ends the shell with its status, and the EXIT trap still runs. It does not apply in the condition of `if`, `elif`, `while` and `until`, or to a command of an `&&` or `||` list before its last command, nor to a function called in one of those places (`ShellState::errexit_suppressed`, opened and closed by `as_condition`). `! cmd` is still not implemented. Three statuses change, to what bash gives: - `return` outside a function: 2 (was an error, so 1). - `eval` of a line that cannot be read: 2 (was 1). - `if` whose conditions all fail and that has no `else`: 0 (was 1). POSIX gives 0, and with `set -e` a 1 there would end the shell. Measured on the built shell, with bash 5.2.21 as reference: - 56 failure and `set -e` lines: 53 match bash (13 before). The other three are older faults this does not touch: a redirection from a file that does not exist gives 127, `shift` is not a built-in, and the built-in `ls` gives 1 for a missing file where `ls` gives 2. - The #233 battery: 69 of 128 match (67 before), no case gets worse. `builtin-05` (`set -e; false; echo notreached`) and `rm-02` (`rm nosuch; echo rc=$?`) now pass, and come off known_failing.txt; the count in the test goes from 61 to 59. Tests. The new tests/command_boundary_tests.rs runs the built shell on 28 lines in four groups: a failure fails only its own command (including the line from the review of #233), the statuses above, `set -e` ends the shell, and where `set -e` does not apply. Each expected result is what bash 5.2.21 gives. All four tests fail on the code before this change. Changed tests, each because the behaviour changed as described: - function_and_script_tests.rs: `return` and `local` outside a function, `source` of a missing file and a function whose last command fails now check a status, not an error from `execute`. - function_frame_tests.rs: the failure is reported as `vsh: ...`, not `Error: ...`. - builtin_strictness_tests.rs: an EXIT trap statement that runs and fails is reported as `vsh: ...` like any failed command; one that cannot be read still says `vsh: trap:`. CLAUDE.md, README.adoc and ROADMAP.adoc: the battery count is 69, `set -e` is off the list of what does not work, and the line saying a failed built-in ends a `-c` script is gone. cargo fmt --check and cargo clippy --all-targets -- -D warnings (also with --all-features) are clean. cargo test --no-fail-fast: 889 passed, 0 failed, 15 ignored, with OLDPWD and PWD set, with both unset, and with --no-default-features. The prompt tests ran 400 times against each of the two prompts with no failure. No proof covers this; the evidence is tests only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01J4QvDjYffb3HcnwwDyrsF9 --- CLAUDE.md | 11 +- README.adoc | 2 +- ROADMAP.adoc | 2 +- impl/rust-cli/src/executable.rs | 114 ++++++++++-- impl/rust-cli/src/state.rs | 11 ++ .../tests/builtin_strictness_tests.rs | 4 +- impl/rust-cli/tests/command_boundary_tests.rs | 170 ++++++++++++++++++ .../tests/conformance/known_failing.txt | 2 - impl/rust-cli/tests/conformance_battery.rs | 2 +- .../tests/function_and_script_tests.rs | 41 +++-- impl/rust-cli/tests/function_frame_tests.rs | 6 +- 11 files changed, 316 insertions(+), 49 deletions(-) create mode 100644 impl/rust-cli/tests/command_boundary_tests.rs diff --git a/CLAUDE.md b/CLAUDE.md index dd84010c..f2feba60 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,7 +24,7 @@ Opus audit session that fixed all broken tests, real bugs, and documentation. **Measured, not claimed (2026-11-17, gate G0).** `impl/rust-cli/tests/conformance_battery.rs` starts the built shell on 128 everyday command lines and compares the result with bash: -**67 match**. The cases that fail are listed in +**69 match**. The cases that fail are listed in `impl/rust-cli/tests/conformance/known_failing.txt`. That list is a ratchet: it may only shrink, and a case may not be added to it to make a build pass. @@ -40,7 +40,9 @@ Works through the built shell (passing battery cases, or checked by hand interac - `test`, `[ ... ]`, and `[[ ... ]]` on its own; `if/elif/else`, `while`, a single `for`, `case` - Functions, `local`, `return`; `$VAR`, `${VAR}`, `${VAR:-default}`, `${#VAR}`, `${VAR:o:n}` - `$((expr))`, and `$(cmd)` of another program, as the whole value of an assignment -- `echo`, `printf`, `eval`, `set --`, `alias`, `trap ... EXIT`, `exit N` +- `echo`, `printf`, `eval`, `set --`, `set -e`, `alias`, `trap ... EXIT`, `exit N` +- A command that fails fails only itself, with a status: the next command of a script, + a function or a loop runs, and `||` runs its right side - Reversible variable assignment (undo/redo) - Transaction grouping (`begin`/`commit`/`rollback`) - `explain`, `checkpoint`/`restore`, `diff`, `replay`, `history --proofs` @@ -53,14 +55,11 @@ In the source and unit-tested, but NOT working through the built shell (battery - `$((expr))` and `$(cmd)` inside an argument (`echo $((1+2))` prints the text); backquotes - A quoted `*`, `?`, `[`, `{` or `~` reaches other programs with a backslash added - `${VAR#pat}`, `${VAR%pat}`, `${VAR^^}` (give an empty string); `$$` -- Nested `for` loops (silently wrong), `break`, `continue`, `! cmd`, `set -e` +- Nested `for` loops (silently wrong), `break`, `continue`, `! cmd` - Subshells, brace groups in pipelines, arrays, `(( ))`, the C-style `for` - `export` and `VAR=value cmd` do not reach the program being run - Here documents passed with `-c`; redirections on built-in commands outside the session root (`ls nosuch 2>/dev/null`) -- A built-in that fails with an error (`mkdir` on a directory that exists, say) ends a `-c` - script, and the rest of an `&&` or `||` list with it. A refused built-in and `false` do - not: they fail with status 1 and the script goes on - Ctrl-Z does not suspend a running program Not exercised by the battery: process substitution, command correction, the pager. diff --git a/README.adoc b/README.adoc index 2269cfcb..cb1fa3d5 100644 --- a/README.adoc +++ b/README.adoc @@ -53,7 +53,7 @@ Valence Shell is a formally verified shell with proven reversibility guarantees. [NOTE] ==== -*Measured, not claimed.* `impl/rust-cli/tests/conformance_battery.rs` starts the built shell on 128 everyday command lines and compares the result with bash. On 2026-11-17, 67 match. The cases that fail are listed in `impl/rust-cli/tests/conformance/known_failing.txt`, which may only shrink. Below, `[x]` means it works through the built shell, `[~]` means in part, and the limit is stated. +*Measured, not claimed.* `impl/rust-cli/tests/conformance_battery.rs` starts the built shell on 128 everyday command lines and compares the result with bash. On 2026-11-18, 69 match. The cases that fail are listed in `impl/rust-cli/tests/conformance/known_failing.txt`, which may only shrink. Below, `[x]` means it works through the built shell, `[~]` means in part, and the limit is stated. ==== * [~] Built-in file commands with undo: `mkdir`, `rmdir`, `touch`, `rm`, `cp`, `mv`, `ln -s`, `chmod`, `chown`, in their plain forms only (one operand each; two for `cp`, `mv` and `ln -s`; a mode or an owner and then one file for `chmod` and `chown`; no options, the `-s` of `ln -s` apart). An option or an extra operand is refused and nothing is done diff --git a/ROADMAP.adoc b/ROADMAP.adoc index f7c3f986..ab03bbf8 100644 --- a/ROADMAP.adoc +++ b/ROADMAP.adoc @@ -88,7 +88,7 @@ integration), #56/#57/#58 (the three admits surfaced by #55). [IMPORTANT] ==== -*Parked* by owner ruling OD-42 (2026-11-17; recorded in `docs/plans/VSH-ROUTE-PLAN-2026-11-04.adoc` on valence-shell#230). The engine is the product and the shell interpreter is one front end, which comes last. What the interpreter does today is measured by `impl/rust-cli/tests/conformance_battery.rs` (67 of 128 command lines match bash), not by the list below, parts of which are out of date. +*Parked* by owner ruling OD-42 (2026-11-17; recorded in `docs/plans/VSH-ROUTE-PLAN-2026-11-04.adoc` on valence-shell#230). The engine is the product and the shell interpreter is one front end, which comes last. What the interpreter does today is measured by `impl/rust-cli/tests/conformance_battery.rs` (69 of 128 command lines match bash), not by the list below, parts of which are out of date. ==== Most critical missing POSIX features, ranked by impact (per CLAUDE.md diff --git a/impl/rust-cli/src/executable.rs b/impl/rust-cli/src/executable.rs index 969e5b36..68bc6b09 100644 --- a/impl/rust-cli/src/executable.rs +++ b/impl/rust-cli/src/executable.rs @@ -70,8 +70,10 @@ pub enum ExecutionResult { Return { exit_code: i32 }, } -impl ExecutableCommand for Command { - fn execute(&self, state: &mut ShellState) -> Result { +impl Command { + /// Run the command itself. A failure can come back as an error here; + /// [`ExecutableCommand::execute`] turns it into a failed status. + fn run(&self, state: &mut ShellState) -> Result { match self { // Filesystem operations (reversible) Command::Mkdir { path, redirects } => { @@ -949,16 +951,13 @@ impl ExecutableCommand for Command { let params: Vec = args[1..].to_vec(); state.set_positional_params(params); } else if args[0].starts_with('-') || args[0].starts_with('+') { - // Shell options (stub: just acknowledge) - // -e: exit on error, -x: trace, -u: error on unset, etc. + // Shell options. `-e` is honoured; `-x` and `-u` are only + // recorded. for arg in args { let enable = arg.starts_with('-'); for ch in arg[1..].chars() { match ch { - 'e' => state.set_variable( - "SHOPT_E".to_string(), - if enable { "1" } else { "0" }.to_string(), - ), + 'e' => state.errexit = enable, 'x' => state.set_variable( "SHOPT_X".to_string(), if enable { "1" } else { "0" }.to_string(), @@ -1000,8 +999,15 @@ impl ExecutableCommand for Command { .map(|a| crate::parser::expand_variables(a, state)) .collect(); let combined = expanded_args.join(" "); - let cmd = crate::parser::parse_command(&combined)?; - cmd.execute(state) + match crate::parser::parse_command(&combined) { + Ok(cmd) => cmd.execute(state), + // A line that cannot be read is status 2, as in bash + // and dash. + Err(e) => { + eprintln!("vsh: eval: {e}"); + Ok(ExecutionResult::ExternalCommand { exit_code: 2 }) + } + } } // Control structures @@ -1011,8 +1017,9 @@ impl ExecutableCommand for Command { elif_parts, else_body, } => { - // Execute condition and get exit code - let cond_result = condition.execute(state)?; + // Execute condition and get exit code. `set -e` does not + // apply to it. + let cond_result = as_condition(state, |s| condition.execute(s))?; let cond_exit = match cond_result { ExecutionResult::Success => 0, ExecutionResult::Exit => return Ok(ExecutionResult::Exit), @@ -1029,7 +1036,7 @@ impl ExecutableCommand for Command { // Try elif parts for (elif_cond, elif_body) in elif_parts { - let elif_result = elif_cond.execute(state)?; + let elif_result = as_condition(state, |s| elif_cond.execute(s))?; let elif_exit = match elif_result { ExecutionResult::Success => 0, ExecutionResult::Exit => return Ok(ExecutionResult::Exit), @@ -1048,8 +1055,9 @@ impl ExecutableCommand for Command { return execute_block(else_cmds, state); } - // No branch matched — return last condition's exit code - Ok(ExecutionResult::ExternalCommand { exit_code: 1 }) + // No branch ran: the status is 0 (POSIX 2.9.4.4). It was 1, + // which `set -e` would take for a failure. + Ok(ExecutionResult::ExternalCommand { exit_code: 0 }) } Command::WhileLoop { condition, body } => { @@ -1125,8 +1133,9 @@ impl ExecutableCommand for Command { } => { use crate::parser::LogicalOperator; - // Execute left command - let left_result = left.execute(state)?; + // Execute left command. `set -e` does not apply to it, only + // to the command that ends the list. + let left_result = as_condition(state, |s| left.execute(s))?; // Get exit code from left command let left_exit_code = match left_result { @@ -1214,7 +1223,9 @@ impl ExecutableCommand for Command { // Return from function Command::Return { code } => { if state.functions.call_depth() == 0 { - anyhow::bail!("return: can only return from a function"); + // Status 2, as bash gives. + eprintln!("vsh: return: can only return from a function"); + return Ok(ExecutionResult::ExternalCommand { exit_code: 2 }); } let exit_code = code.unwrap_or(state.last_exit_code); state.last_exit_code = exit_code; @@ -1296,6 +1307,58 @@ impl ExecutableCommand for Command { } } + /// The commands that hold other commands. Their status is that of a + /// command inside them, which `set -e` has already seen, or of a + /// condition, which `set -e` does not apply to. + fn is_compound(&self) -> bool { + matches!( + self, + Command::If { .. } + | Command::WhileLoop { .. } + | Command::UntilLoop { .. } + | Command::ForLoop { .. } + | Command::CaseStatement { .. } + | Command::LogicalOp { .. } + | Command::Source { .. } + | Command::Eval { .. } + ) + } +} + +impl ExecutableCommand for Command { + /// Every command is a boundary. A command that fails prints what went + /// wrong and fails with status 1; whatever ran it goes on, as in a POSIX + /// shell: the next line of a script or a function, the next turn of a + /// loop, the other side of `||`. It used to be an error that unwound + /// through every enclosing command, so `mkdir x || echo no` never ran + /// `echo no`, and a script ended at the first built-in that failed. + /// + /// With `set -e`, a simple command that fails ends the shell, outside + /// the contexts listed at [`ShellState::errexit_suppressed`]. + /// + /// This never returns `Err`. The type stays a `Result` for the callers. + fn execute(&self, state: &mut ShellState) -> Result { + let result = match self.run(state) { + Ok(result) => result, + Err(e) => { + eprintln!("vsh: {e}"); + state.last_exit_code = 1; + ExecutionResult::ExternalCommand { exit_code: 1 } + } + }; + if let ExecutionResult::ExternalCommand { exit_code } = result { + if exit_code != 0 + && state.errexit + && state.errexit_suppressed == 0 + && !self.is_compound() + { + state.last_exit_code = exit_code; + return Ok(ExecutionResult::Exit); + } + } + Ok(result) + } + fn is_reversible(&self) -> bool { matches!( self, @@ -1733,6 +1796,19 @@ fn run_function_body( Ok(last_result) } +/// Run `f` where `set -e` does not apply: a condition, or a command of an +/// `&&` or `||` list that is not the last. The context closes on every way +/// out of `f`. +fn as_condition( + state: &mut ShellState, + f: impl FnOnce(&mut ShellState) -> Result, +) -> Result { + state.errexit_suppressed += 1; + let result = f(state); + state.errexit_suppressed -= 1; + result +} + /// Execute a block of commands in sequence, returning the result of the last command. /// /// Short-circuits on `Exit` (shell-wide) and `Return` (function-scope) so the @@ -1790,7 +1866,7 @@ fn execute_loop( } iterations += 1; - let cond_result = condition.execute(state)?; + let cond_result = as_condition(state, |s| condition.execute(s))?; let cond_exit = match cond_result { ExecutionResult::Success => 0, ExecutionResult::Exit => return Ok(ExecutionResult::Exit), diff --git a/impl/rust-cli/src/state.rs b/impl/rust-cli/src/state.rs index c48b1bf7..291aecd3 100644 --- a/impl/rust-cli/src/state.rs +++ b/impl/rust-cli/src/state.rs @@ -288,6 +288,15 @@ pub struct ShellState { /// loops. A script, or `-c`, leaves it unset. pub interactive: bool, + /// `set -e`: a simple command that fails ends the shell, with its status. + pub errexit: bool, + + /// How many contexts are open in which `set -e` does not apply: the + /// condition of `if`, `elif`, `while` and `until`, and every command of + /// an `&&` or `||` list but the last. A function called there is inside + /// the context too. + pub errexit_suppressed: usize, + /// Previous directory for cd - support pub previous_dir: Option, @@ -351,6 +360,8 @@ impl ShellState { state_file, last_exit_code: 0, interactive: false, + errexit: false, + errexit_suppressed: 0, previous_dir: None, variables: HashMap::new(), exported_vars: HashSet::new(), diff --git a/impl/rust-cli/tests/builtin_strictness_tests.rs b/impl/rust-cli/tests/builtin_strictness_tests.rs index eae154df..77f38a57 100644 --- a/impl/rust-cli/tests/builtin_strictness_tests.rs +++ b/impl/rust-cli/tests/builtin_strictness_tests.rs @@ -499,6 +499,8 @@ fn an_exit_trap_reports_a_statement_that_fails() { "stdout: {}", run.stdout ); - assert!(run.stderr.contains("vsh: trap: "), "stderr: {}", run.stderr); + // A statement that cannot be read says `vsh: trap:`. One that runs and + // fails is reported like any failed command, `vsh: ` and the reason. + assert!(run.stderr.contains("vsh: "), "stderr: {}", run.stderr); assert!(run.stderr.contains("exists"), "stderr: {}", run.stderr); } diff --git a/impl/rust-cli/tests/command_boundary_tests.rs b/impl/rust-cli/tests/command_boundary_tests.rs new file mode 100644 index 00000000..c6a5eba5 --- /dev/null +++ b/impl/rust-cli/tests/command_boundary_tests.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) Jonathan D.A. Jewell +//! A command that fails fails only itself, and `set -e` ends the shell. +//! +//! A built-in that failed used to be an error that unwound through every +//! command around it: `mkdir x || echo no` never ran `echo no`, a loop +//! stopped at its first failure, and a script ended at the first built-in +//! that failed. That last one stood in for `set -e`, which was not +//! implemented: `set -e; false; echo after` printed `after`. +//! +//! Now each command is a boundary. A failure prints what went wrong and +//! gives a status, and whatever ran the command goes on. `set -e` ends the +//! shell at a simple command that fails, except in a condition and in an +//! `&&` or `||` list before its last command. +//! +//! Every expected output and status here is what GNU bash 5.2.21 gives for +//! the same line (`bash -c`, standard error not compared); dash 5.2 agrees +//! except where a case says otherwise. Each test runs the built shell. + +use std::process::{Command, Stdio}; + +/// Runs `script` with `vsh -c` in a fresh directory. Returns the standard +/// output, without the shell's own `[op:` receipt lines, and the status. +fn vsh(script: &str) -> (String, i32) { + let dir = tempfile::tempdir().expect("temporary directory"); + let output = Command::new(env!("CARGO_BIN_EXE_vsh")) + .arg("-r") + .arg(dir.path()) + .arg("-c") + .arg(script) + .current_dir(dir.path()) + .env("HOME", dir.path()) + .env("NO_COLOR", "1") + .env_remove("RUST_BACKTRACE") + .stdin(Stdio::null()) + .output() + .expect("start the built shell"); + let stdout = String::from_utf8_lossy(&output.stdout) + .split_inclusive('\n') + .filter(|line| !line.starts_with("[op:") && !line.starts_with("[txn:")) + .collect(); + (stdout, output.status.code().unwrap_or(-1)) +} + +/// Runs each case and reports every one that differs, not only the first. +fn check(cases: &[(&str, &str, i32)]) { + let wrong: Vec = cases + .iter() + .filter_map(|&(script, out, status)| { + let (got_out, got_status) = vsh(script); + (got_out != out || got_status != status).then(|| { + format!( + " {script}\n expected {out:?}, status {status}\n got \ + {got_out:?}, status {got_status}" + ) + }) + }) + .collect(); + assert!( + wrong.is_empty(), + "{} of {} cases differ from bash:\n{}", + wrong.len(), + cases.len(), + wrong.join("\n") + ); +} + +#[test] +fn a_command_that_fails_fails_only_itself() { + check(&[ + // The line from the review of #233. + ( + r#"f() { local x=inner; mkdir /no/such/parent/dir; }; x=outer; f; echo "$x""#, + "outer\n", + 0, + ), + ("mkdir no/such/dir; echo rc=$?", "rc=1\n", 0), + ("mkdir no/such/dir || echo fallback", "fallback\n", 0), + ("rm nosuch && echo no; echo rc=$?", "rc=1\n", 0), + ( + "for i in 1 2; do rm nosuch; echo body$i; done; echo end", + "body1\nbody2\nend\n", + 0, + ), + ( + "f() { rm nosuch; echo infunc; }; f; echo rc=$?", + "infunc\nrc=0\n", + 0, + ), + ( + "f() { rm nosuch; }; if f; then echo yes; else echo no; fi", + "no\n", + 0, + ), + ( + "case x in x) rm nosuch; echo arm;; esac; echo end", + "arm\nend\n", + 0, + ), + ( + "trap 'echo bye' EXIT; rm nosuch; echo after", + "after\nbye\n", + 0, + ), + ]); +} + +/// The status a failure gives. dash differs on the first three: it ends the +/// shell at `return` and `local` outside a function, and at the `eval`. +#[test] +fn a_failure_gives_the_status_bash_gives() { + check(&[ + ("return 0; echo rc=$?", "rc=2\n", 0), + ("eval 'if'; echo rc=$?", "rc=2\n", 0), + ("local y=1; echo rc=$?", "rc=1\n", 0), + // No branch ran: status 0. It was 1, which `set -e` would take for + // a failure. + ("if false; then :; fi; echo rc=$?", "rc=0\n", 0), + ]); +} + +#[test] +fn set_e_ends_the_shell_at_a_command_that_fails() { + check(&[ + ("set -e; false; echo after", "", 1), + ("set -e; rm nosuch; echo after", "", 1), + ("set -e; f() { false; echo infunc; }; f; echo after", "", 1), + ("set -e; true && false; echo after", "", 1), + ( + "set -e; for i in 1 2; do false; echo body; done; echo after", + "", + 1, + ), + // A function that returns a failure is a command that fails. + ("set -e; f() { return 3; }; f; echo after", "", 3), + // The EXIT trap still runs. + ( + "set -e; trap 'echo bye' EXIT; false; echo after", + "bye\n", + 1, + ), + ]); +} + +#[test] +fn set_e_does_not_apply_to_a_condition_or_inside_a_list() { + check(&[ + ("set -e; false && true; echo after", "after\n", 0), + ("set -e; false || true; echo after", "after\n", 0), + ( + "set -e; mkdir no/such/dir || true; echo after", + "after\n", + 0, + ), + ("set -e; if false; then :; fi; echo after", "after\n", 0), + ( + "set -e; if mkdir no/such/dir; then :; else echo no; fi; echo after", + "no\nafter\n", + 0, + ), + ("set -e; while false; do :; done; echo after", "after\n", 0), + // A function called as a condition is in the condition too. + ( + "set -e; f() { false; echo infunc; }; if f; then echo y; fi; echo after", + "infunc\ny\nafter\n", + 0, + ), + ("set -e; set +e; false; echo after", "after\n", 0), + ]); +} diff --git a/impl/rust-cli/tests/conformance/known_failing.txt b/impl/rust-cli/tests/conformance/known_failing.txt index 5c8a1e33..5176dff0 100644 --- a/impl/rust-cli/tests/conformance/known_failing.txt +++ b/impl/rust-cli/tests/conformance/known_failing.txt @@ -50,7 +50,6 @@ sub-01 # mkdir zzdir; (cd zzdir; pwd | grep -c zzdir); pwd | grep -c zzdir sub-03 # { echo a; echo b; } | wc -l sub-04 # echo a & wait; echo done builtin-03 # read a b <<< "one two"; echo $b -builtin-05 # set -e; false; echo notreached builtin-06 # x=1; unset x; echo "[${x}]" builtin-07 # type echo | head -1 | grep -c echo builtin-12 # mkdir zzdir; pushd zzdir >/dev/null; pwd | grep -c zzdir; popd >/dev/null @@ -66,7 +65,6 @@ loop-10 # for i in a b; do for j in 1 2; do echo $i$j; done; done subst-05 # x=$(echo hi); echo $x fs-09 # touch a b c; ls | wc -l fs-10 # mkdir x y; ls | wc -l -rm-02 # rm nosuch; echo rc=$? rm-03 # rm -f nosuch; echo rc=$? rm-04 # mkdir d; touch d/x; rm -r d; ls | wc -l rm-05 # touch a; touch b; rm a b; ls | wc -l diff --git a/impl/rust-cli/tests/conformance_battery.rs b/impl/rust-cli/tests/conformance_battery.rs index c71f1f49..7aaf95f5 100644 --- a/impl/rust-cli/tests/conformance_battery.rs +++ b/impl/rust-cli/tests/conformance_battery.rs @@ -54,7 +54,7 @@ const KNOWN_FAILING: &str = include_str!("conformance/known_failing.txt"); /// What this does not catch: one case taken off the list and another put /// on in the same change. Only a comparison with the base branch catches /// that. -const KNOWN_FAILING_COUNT: usize = 61; +const KNOWN_FAILING_COUNT: usize = 59; /// Longest a single case may run. A case that does not finish counts as failed. const TIME_LIMIT: Duration = Duration::from_secs(5); diff --git a/impl/rust-cli/tests/function_and_script_tests.rs b/impl/rust-cli/tests/function_and_script_tests.rs index 9710fe13..13cd0f96 100644 --- a/impl/rust-cli/tests/function_and_script_tests.rs +++ b/impl/rust-cli/tests/function_and_script_tests.rs @@ -158,8 +158,8 @@ fn test_function_local_variables() -> Result<()> { Ok(()) } -/// A command in the body returns an error. The error goes on to the caller, -/// and the frame is popped all the same. +/// A command in the body fails. The function goes on to its end, and both +/// frames are popped. /// /// This test calls the library, so it runs on every platform. The tests that /// run the built shell are in `function_frame_tests.rs` (Linux only). @@ -178,10 +178,13 @@ fn test_function_that_fails_pops_its_frame() -> Result<()> { outer_cmd.execute(&mut state)?; let invoke_cmd = parse_command("outer outer_arg_1 outer_arg_2")?; - let result = invoke_cmd.execute(&mut state); + let result = invoke_cmd.execute(&mut state)?; - // The error still reaches the caller - assert!(result.is_err(), "the failed mkdir should be an error"); + // The failed mkdir is the last command, so the call fails with status 1 + assert!( + matches!(result, ExecutionResult::ExternalCommand { exit_code: 1 }), + "{result:?}" + ); // Both frames are gone, and the caller has its own values back assert_eq!(state.functions.call_depth(), 0); @@ -220,11 +223,13 @@ fn test_return_outside_function_fails() -> Result<()> { let mut state = ShellState::new(temp.path().to_str().unwrap())?; let cmd = parse_command("return 0")?; - let result = cmd.execute(&mut state); + let result = cmd.execute(&mut state)?; - assert!(result.is_err()); - let err = result.unwrap_err(); - assert!(err.to_string().contains("can only return from a function")); + // A failed command with status 2, as in bash; not a return + assert!( + matches!(result, ExecutionResult::ExternalCommand { exit_code: 2 }), + "{result:?}" + ); Ok(()) } @@ -235,11 +240,14 @@ fn test_local_outside_function_fails() -> Result<()> { let mut state = ShellState::new(temp.path().to_str().unwrap())?; let cmd = parse_command("local X=5")?; - let result = cmd.execute(&mut state); + let result = cmd.execute(&mut state)?; - assert!(result.is_err()); - let err = result.unwrap_err(); - assert!(err.to_string().contains("can only be used in a function")); + // A failed command with status 1, as in bash, and nothing was set + assert!( + matches!(result, ExecutionResult::ExternalCommand { exit_code: 1 }), + "{result:?}" + ); + assert_eq!(state.get_variable("X"), None); Ok(()) } @@ -385,9 +393,12 @@ fn test_source_nonexistent_file_fails() -> Result<()> { let mut state = ShellState::new(temp.path().to_str().unwrap())?; let cmd = parse_command("source /nonexistent/file.sh")?; - let result = cmd.execute(&mut state); + let result = cmd.execute(&mut state)?; - assert!(result.is_err()); + assert!( + matches!(result, ExecutionResult::ExternalCommand { exit_code: 1 }), + "{result:?}" + ); Ok(()) } diff --git a/impl/rust-cli/tests/function_frame_tests.rs b/impl/rust-cli/tests/function_frame_tests.rs index c8b97479..a56cccf8 100644 --- a/impl/rust-cli/tests/function_frame_tests.rs +++ b/impl/rust-cli/tests/function_frame_tests.rs @@ -266,9 +266,9 @@ fn a_function_that_fails_leaves_the_callers_variable_as_it_was() { "the terminal showed:\n{}", plain(&seen) ); - // The frame is popped; the error still reaches the prompt. + // The frame is popped; the failure is still reported. assert_eq!( - printed(&seen, "Error:").len(), + printed(&seen, "vsh: Parent directory does not exist").len(), 1, "the failed mkdir should be reported once; the terminal showed:\n{}", plain(&seen) @@ -338,7 +338,7 @@ fn after_a_function_failed_the_shell_is_no_longer_inside_it() { &["source ./defs.sh", "f", "local y=1", "return 0"], ); - for refused in ["Error: local:", "Error: return:"] { + for refused in ["vsh: local:", "vsh: return:"] { assert_eq!( printed(&seen, refused).len(), 1,