Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions impl/rust-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
68 changes: 47 additions & 21 deletions impl/rust-cli/src/executable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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<ExecutionResult> {
// 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.
Expand Down Expand Up @@ -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)
}

Expand Down
33 changes: 33 additions & 0 deletions impl/rust-cli/tests/function_and_script_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()?;
Expand Down
Loading
Loading