From 9c52b93975cfe119bad4a745b338fab96e32e0a8 Mon Sep 17 00:00:00 2001 From: WindSoilder Date: Fri, 29 Sep 2023 00:49:42 +0800 Subject: [PATCH] allow early return outside of main (#10514) # Description Fixes: #9792 When evaluating file, we need to allow early return if we evaluate script file first. --- crates/nu-cli/src/eval_file.rs | 14 +++++++++++--- crates/nu-command/tests/commands/return_.rs | 9 +++++++++ .../fixtures/formats/early_return_outside_main.nu | 7 +++++++ 3 files changed, 27 insertions(+), 3 deletions(-) create mode 100644 tests/fixtures/formats/early_return_outside_main.nu diff --git a/crates/nu-cli/src/eval_file.rs b/crates/nu-cli/src/eval_file.rs index 5ae10ee078..b4e6aa7ae3 100644 --- a/crates/nu-cli/src/eval_file.rs +++ b/crates/nu-cli/src/eval_file.rs @@ -2,7 +2,7 @@ use crate::util::eval_source; use log::info; use log::trace; use miette::{IntoDiagnostic, Result}; -use nu_engine::eval_block_with_early_return; +use nu_engine::eval_block; use nu_engine::{convert_env_values, current_dir}; use nu_parser::parse; use nu_path::canonicalize_with; @@ -126,14 +126,22 @@ pub fn evaluate_file( if engine_state.find_decl(b"main", &[]).is_some() { let args = format!("main {}", args.join(" ")); - let pipeline_data = eval_block_with_early_return( + let pipeline_data = eval_block( engine_state, stack, &block, PipelineData::empty(), false, false, - ) + ); + let pipeline_data = match pipeline_data { + Err(ShellError::Return(_, _)) => { + // allows early exists before `main` is run. + return Ok(()); + } + + x => x, + } .unwrap_or_else(|e| { let working_set = StateWorkingSet::new(engine_state); report_error(&working_set, &e); diff --git a/crates/nu-command/tests/commands/return_.rs b/crates/nu-command/tests/commands/return_.rs index e5944dc5cd..f8fefeb8b6 100644 --- a/crates/nu-command/tests/commands/return_.rs +++ b/crates/nu-command/tests/commands/return_.rs @@ -23,3 +23,12 @@ fn return_works_in_script_without_def_main() { assert!(actual.err.is_empty()); } + +#[test] +fn return_works_in_script_with_def_main() { + let actual = nu!( + cwd: "tests/fixtures/formats", + pipeline("nu early_return_outside_main.nu") + ); + assert!(actual.err.is_empty()); +} diff --git a/tests/fixtures/formats/early_return_outside_main.nu b/tests/fixtures/formats/early_return_outside_main.nu new file mode 100644 index 0000000000..ff2bc3ea8b --- /dev/null +++ b/tests/fixtures/formats/early_return_outside_main.nu @@ -0,0 +1,7 @@ +let y = 'not hiya' + +return + +def main [] { + error make {msg: "this should not show"} +}