Split blocks and closures (#7075)

* Split closures and blocks

* Tests mostly working

* finish last fixes, passes all tests

* fmt
This commit is contained in:
JT
2022-11-10 21:21:49 +13:00
committed by GitHub
parent 921a66554e
commit 63433f1bc8
57 changed files with 576 additions and 220 deletions

View File

@ -228,7 +228,7 @@ mod test {
vals: vec![Value::Bool { val: true, span }],
span,
},
Value::Block {
Value::Closure {
val: 0,
captures: HashMap::new(),
span,

View File

@ -19,11 +19,7 @@ impl Command for Def {
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required("def_name", SyntaxShape::String, "definition name")
.required("params", SyntaxShape::Signature, "parameters")
.required(
"block",
SyntaxShape::Block(Some(vec![])),
"body of the definition",
)
.required("body", SyntaxShape::Closure(None), "body of the definition")
.category(Category::Core)
}

View File

@ -19,11 +19,7 @@ impl Command for DefEnv {
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required("def_name", SyntaxShape::String, "definition name")
.required("params", SyntaxShape::Signature, "parameters")
.required(
"block",
SyntaxShape::Block(Some(vec![])),
"body of the definition",
)
.required("block", SyntaxShape::Block, "body of the definition")
.category(Category::Core)
}

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, ListStream, PipelineData, RawStream, ShellError, Signature, SyntaxShape,
Type, Value,
@ -20,8 +20,8 @@ impl Command for Do {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("do")
.required("closure", SyntaxShape::Any, "the closure to run")
.input_output_types(vec![(Type::Any, Type::Any)])
.required("block", SyntaxShape::Any, "the block to run")
.switch(
"ignore-errors",
"ignore shell errors as the block runs",
@ -43,7 +43,7 @@ impl Command for Do {
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let block: CaptureBlock = call.req(engine_state, stack, 0)?;
let block: Closure = call.req(engine_state, stack, 0)?;
let rest: Vec<Value> = call.rest(engine_state, stack, 1)?;
let ignore_errors = call.has_flag("ignore-errors");
let capture_errors = call.has_flag("capture-errors");

View File

@ -19,11 +19,7 @@ impl Command for ExportDef {
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required("name", SyntaxShape::String, "definition name")
.required("params", SyntaxShape::Signature, "parameters")
.required(
"block",
SyntaxShape::Block(Some(vec![])),
"body of the definition",
)
.required("block", SyntaxShape::Block, "body of the definition")
.category(Category::Core)
}

View File

@ -19,11 +19,7 @@ impl Command for ExportDefEnv {
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required("name", SyntaxShape::String, "definition name")
.required("params", SyntaxShape::Signature, "parameters")
.required(
"block",
SyntaxShape::Block(Some(vec![])),
"body of the definition",
)
.required("block", SyntaxShape::Block, "body of the definition")
.category(Category::Core)
}

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, eval_expression, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, ListStream, PipelineData, Signature, Span,
SyntaxShape, Type, Value,
@ -31,11 +31,7 @@ impl Command for For {
SyntaxShape::Keyword(b"in".to_vec(), Box::new(SyntaxShape::Any)),
"range of the loop",
)
.required(
"block",
SyntaxShape::Block(Some(vec![])),
"the block to run",
)
.required("block", SyntaxShape::Block, "the block to run")
.switch(
"numbered",
"returned a numbered item ($it.index and $it.item)",
@ -75,7 +71,7 @@ impl Command for For {
.expect("internal error: missing keyword");
let values = eval_expression(engine_state, stack, keyword_expr)?;
let capture_block: CaptureBlock = call.req(engine_state, stack, 2)?;
let capture_block: Closure = call.req(engine_state, stack, 2)?;
let numbered = call.has_flag("numbered");

View File

@ -1,8 +1,8 @@
use nu_engine::{eval_block, eval_expression, eval_expression_with_input, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Block, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, FromValue, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};
#[derive(Clone)]
@ -23,7 +23,7 @@ impl Command for If {
.required("cond", SyntaxShape::Expression, "condition to check")
.required(
"then_block",
SyntaxShape::Block(Some(vec![])),
SyntaxShape::Block,
"block to run if check succeeds",
)
.optional(
@ -51,7 +51,7 @@ impl Command for If {
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let cond = call.positional_nth(0).expect("checked through parser");
let then_block: CaptureBlock = call.req(engine_state, stack, 1)?;
let then_block: Block = call.req(engine_state, stack, 1)?;
let else_case = call.positional_nth(2);
let result = eval_expression(engine_state, stack, cond)?;
@ -59,10 +59,9 @@ impl Command for If {
Value::Bool { val, .. } => {
if *val {
let block = engine_state.get_block(then_block.block_id);
let mut stack = stack.captures_to_stack(&then_block.captures);
eval_block(
engine_state,
&mut stack,
stack,
block,
input,
call.redirect_stdout,
@ -71,14 +70,10 @@ impl Command for If {
} else if let Some(else_case) = else_case {
if let Some(else_expr) = else_case.as_keyword() {
if let Some(block_id) = else_expr.as_block() {
let result = eval_expression(engine_state, stack, else_expr)?;
let else_block: CaptureBlock = FromValue::from_value(&result)?;
let mut stack = stack.captures_to_stack(&else_block.captures);
let block = engine_state.get_block(block_id);
eval_block(
engine_state,
&mut stack,
stack,
block,
input,
call.redirect_stdout,

View File

@ -18,11 +18,7 @@ impl Command for Module {
Signature::build("module")
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required("module_name", SyntaxShape::String, "module name")
.required(
"block",
SyntaxShape::Block(Some(vec![])),
"body of the module",
)
.required("block", SyntaxShape::Block, "body of the module")
.category(Category::Core)
}

View File

@ -263,6 +263,7 @@ fn nu_value_to_string(value: Value, separator: &str, config: &Config) -> String
.collect::<Vec<_>>()
.join(separator),
Value::Block { val, .. } => format!("<Block {}>", val),
Value::Closure { val, .. } => format!("<Closure {}>", val),
Value::Nothing { .. } => String::new(),
Value::Error { error } => format!("{:?}", error),
Value::Binary { val, .. } => format!("{:?}", val),

View File

@ -1,7 +1,7 @@
use nu_engine::{eval_block, redirect_env, CallExt};
use nu_protocol::{
ast::Call,
engine::{CaptureBlock, Command, EngineState, Stack},
engine::{Closure, Command, EngineState, Stack},
Category, Example, PipelineData, Signature, Span, SyntaxShape, Type, Value,
};
@ -18,7 +18,7 @@ impl Command for ExportEnv {
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.required(
"block",
SyntaxShape::Block(Some(vec![])),
SyntaxShape::Block,
"the block to run to set the environment",
)
.category(Category::Env)
@ -35,7 +35,7 @@ impl Command for ExportEnv {
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let capture_block: CaptureBlock = call.req(engine_state, caller_stack, 0)?;
let capture_block: Closure = call.req(engine_state, caller_stack, 0)?;
let block = engine_state.get_block(capture_block.block_id);
let mut callee_stack = caller_stack.captures_to_stack(&capture_block.captures);

View File

@ -3,7 +3,7 @@ use std::collections::HashMap;
use nu_engine::{eval_block, CallExt};
use nu_protocol::{
ast::Call,
engine::{CaptureBlock, Command, EngineState, Stack},
engine::{Closure, Command, EngineState, Stack},
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
};
@ -25,7 +25,7 @@ impl Command for WithEnv {
)
.required(
"block",
SyntaxShape::Block(Some(vec![])),
SyntaxShape::Closure(None),
"the block to run once the variable is set",
)
.category(Category::Env)
@ -80,7 +80,7 @@ fn with_env(
// let external_redirection = args.call_info.args.external_redirection;
let variable: Value = call.req(engine_state, stack, 0)?;
let capture_block: CaptureBlock = call.req(engine_state, stack, 1)?;
let capture_block: Closure = call.req(engine_state, stack, 1)?;
let block = engine_state.get_block(capture_block.block_id);
let mut stack = stack.captures_to_stack(&capture_block.captures);

View File

@ -14,8 +14,6 @@ mod test_examples {
};
use crate::To;
use itertools::Itertools;
use nu_engine;
use nu_parser;
use nu_protocol::{
ast::Block,
engine::{Command, EngineState, Stack, StateDelta, StateWorkingSet},
@ -95,7 +93,7 @@ mod test_examples {
engine_state
}
fn check_example_input_and_output_types_match_command_signature<'a>(
fn check_example_input_and_output_types_match_command_signature(
example: &Example,
cwd: &PathBuf,
engine_state: &mut Box<EngineState>,
@ -108,7 +106,7 @@ mod test_examples {
// Skip tests that don't have results to compare to
if let Some(example_output) = example.result.as_ref() {
if let Some(example_input_type) =
eval_pipeline_without_terminal_expression(example.example, &cwd, engine_state)
eval_pipeline_without_terminal_expression(example.example, cwd, engine_state)
{
let example_input_type = example_input_type.get_type();
let example_output_type = example_output.get_type();
@ -177,19 +175,18 @@ mod test_examples {
|| example_matches_signature_via_vectorization_over_list
|| example_matches_signature_via_cell_path_operation)
{
assert!(
false,
"The example `{}` demonstrates a transformation of type {:?} -> {:?}. \
However, this does not match the declared signature: {:?}.{} \
For this command, `vectorizes_over_list` is {} and `operates_on_cell_paths()` is {}.",
example.example,
example_input_type,
example_output_type,
signature_input_output_types,
if signature_input_output_types.is_empty() { " (Did you forget to declare the input and output types for the command?)" } else { "" },
signature_vectorizes_over_list,
signature_operates_on_cell_paths
);
panic!(
"The example `{}` demonstrates a transformation of type {:?} -> {:?}. \
However, this does not match the declared signature: {:?}.{} \
For this command, `vectorizes_over_list` is {} and `operates_on_cell_paths()` is {}.",
example.example,
example_input_type,
example_output_type,
signature_input_output_types,
if signature_input_output_types.is_empty() { " (Did you forget to declare the input and output types for the command?)" } else { "" },
signature_vectorizes_over_list,
signature_operates_on_cell_paths
);
};
};
}
@ -217,7 +214,7 @@ mod test_examples {
.expect("Error merging environment");
let empty_input = PipelineData::new(Span::test_data());
let result = eval(example.example, empty_input, &cwd, engine_state);
let result = eval(example.example, empty_input, cwd, engine_state);
// Note. Value implements PartialEq for Bool, Int, Float, String and Block
// If the command you are testing requires to compare another case, then
@ -267,8 +264,8 @@ mod test_examples {
eval_block(block, input, cwd, engine_state, delta)
}
fn parse(contents: &str, engine_state: &Box<EngineState>) -> (Block, StateDelta) {
let mut working_set = StateWorkingSet::new(&*engine_state);
fn parse(contents: &str, engine_state: &EngineState) -> (Block, StateDelta) {
let mut working_set = StateWorkingSet::new(engine_state);
let (output, err) =
nu_parser::parse(&mut working_set, None, contents.as_bytes(), false, &[]);
@ -300,7 +297,7 @@ mod test_examples {
},
);
match nu_engine::eval_block(&engine_state, &mut stack, &block, input, true, true) {
match nu_engine::eval_block(engine_state, &mut stack, &block, input, true, true) {
Err(err) => panic!("test eval error in `{}`: {:?}", "TODO", err),
Ok(result) => result.into_value(Span::test_data()),
}
@ -319,7 +316,7 @@ mod test_examples {
if !block.pipelines[0].expressions.is_empty() {
let empty_input = PipelineData::new(Span::test_data());
Some(eval_block(block, empty_input, &cwd, engine_state, delta))
Some(eval_block(block, empty_input, cwd, engine_state, delta))
} else {
Some(Value::nothing(Span::test_data()))
}

View File

@ -6,7 +6,7 @@ use std::time::Duration;
use notify::{DebouncedEvent, RecommendedWatcher, RecursiveMode, Watcher};
use nu_engine::{current_dir, eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack, StateWorkingSet};
use nu_protocol::engine::{Closure, Command, EngineState, Stack, StateWorkingSet};
use nu_protocol::{
format_error, Category, Example, IntoPipelineData, PipelineData, ShellError, Signature,
Spanned, SyntaxShape, Value,
@ -35,7 +35,7 @@ impl Command for Watch {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("watch")
.required("path", SyntaxShape::Filepath, "the path to watch. Can be a file or directory")
.required("block", SyntaxShape::Block(None), "A Nu block of code to run whenever a file changes. The block will be passed `operation`, `path`, and `new_path` (for renames only) arguments in that order")
.required("block", SyntaxShape::Block, "A Nu block of code to run whenever a file changes. The block will be passed `operation`, `path`, and `new_path` (for renames only) arguments in that order")
.named(
"debounce-ms",
SyntaxShape::Int,
@ -82,7 +82,7 @@ impl Command for Watch {
}
};
let capture_block: CaptureBlock = call.req(engine_state, stack, 1)?;
let capture_block: Closure = call.req(engine_state, stack, 1)?;
let block = engine_state
.clone()
.get_block(capture_block.block_id)

View File

@ -1,7 +1,7 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::{
ast::Call,
engine::{CaptureBlock, Command, EngineState, Stack},
engine::{Closure, Command, EngineState, Stack},
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Type,
Value,
};
@ -68,7 +68,7 @@ impl Command for All {
) -> Result<PipelineData, ShellError> {
let span = call.head;
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block_id = capture_block.block_id;
let block = engine_state.get_block(block_id);

View File

@ -1,7 +1,7 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::{
ast::Call,
engine::{CaptureBlock, Command, EngineState, Stack},
engine::{Closure, Command, EngineState, Stack},
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Type,
Value,
};
@ -67,7 +67,7 @@ impl Command for Any {
) -> Result<PipelineData, ShellError> {
let span = call.head;
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block_id = capture_block.block_id;
let block = engine_state.get_block(block_id);

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, redirect_env, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, Signature, SyntaxShape, Type, Value,
};
@ -17,9 +17,9 @@ impl Command for Collect {
Signature::build("collect")
.input_output_types(vec![(Type::List(Box::new(Type::Any)), Type::Any)])
.required(
"block",
SyntaxShape::Block(Some(vec![SyntaxShape::Any])),
"the block to run once the stream is collected",
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
"the closure to run once the stream is collected",
)
.switch(
"keep-env",
@ -40,7 +40,7 @@ impl Command for Collect {
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let mut stack_captures = stack.captures_to_stack(&capture_block.captures);

View File

@ -1,7 +1,7 @@
use super::utils::chain_error_with_input;
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, Signature,
Span, SyntaxShape, Type, Value,
@ -16,7 +16,7 @@ impl Command for Each {
}
fn usage(&self) -> &str {
"Run a block on each row of input"
"Run a closure on each row of input"
}
fn extra_usage(&self) -> &str {
@ -40,9 +40,9 @@ with 'transpose' first."#
Type::List(Box::new(Type::Any)),
)])
.required(
"block",
SyntaxShape::Block(Some(vec![SyntaxShape::Any])),
"the block to run",
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
"the closure to run",
)
.switch("keep-empty", "keep empty result cells", Some('k'))
.switch("numbered", "iterate with an index", Some('n'))
@ -127,7 +127,7 @@ with 'transpose' first."#
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let numbered = call.has_flag("numbered");
let keep_empty = call.has_flag("keep-empty");

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, Signature,
Span, SyntaxShape, Type, Value,
@ -29,9 +29,9 @@ impl Command for EachWhile {
Type::List(Box::new(Type::Any)),
)])
.required(
"block",
SyntaxShape::Block(Some(vec![SyntaxShape::Any])),
"the block to run",
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
"the closure to run",
)
.switch("numbered", "iterate with an index", Some('n'))
.category(Category::Filters)
@ -97,7 +97,7 @@ impl Command for EachWhile {
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let numbered = call.has_flag("numbered");
let metadata = input.metadata();

View File

@ -354,6 +354,7 @@ fn find_with_rest_and_highlight(
| Value::Range { .. }
| Value::Float { .. }
| Value::Block { .. }
| Value::Closure { .. }
| Value::Nothing { .. }
| Value::Error { .. } => lower_value
.eq(span, term, span)
@ -413,6 +414,7 @@ fn find_with_rest_and_highlight(
| Value::Range { .. }
| Value::Float { .. }
| Value::Block { .. }
| Value::Closure { .. }
| Value::Nothing { .. }
| Value::Error { .. } => lower_value
.eq(span, term, span)

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, Spanned, SyntaxShape,
Type, Value,
@ -117,8 +117,8 @@ pub fn group_by(
};
match grouper {
Some(Value::Block { .. }) => {
let block: Option<CaptureBlock> = call.opt(engine_state, stack, 0)?;
Some(Value::Block { .. }) | Some(Value::Closure { .. }) => {
let block: Option<Closure> = call.opt(engine_state, stack, 0)?;
let error_key = "error";
for value in values {

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::{Call, CellPath, PathMember};
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, FromValue, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, SyntaxShape, Type, Value,
@ -91,7 +91,7 @@ fn insert(
// Replace is a block, so set it up and run it instead of using it as the replacement
if replacement.as_block().is_ok() {
let capture_block: CaptureBlock = FromValue::from_value(&replacement)?;
let capture_block: Closure = FromValue::from_value(&replacement)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let mut stack = stack.captures_to_stack(&capture_block.captures);

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, FromValue, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, SyntaxShape, Type, Value,
@ -113,7 +113,7 @@ repeating this process with row 1, and so on."#
let merge_value: Value = if argument_was_block {
// When given a block, run it to obtain the matching value.
let capture_block: CaptureBlock = FromValue::from_value(&replacement)?;
let capture_block: Closure = FromValue::from_value(&replacement)?;
let mut stack = stack.captures_to_stack(&capture_block.captures);
stack.with_env(&stack.env_vars.clone(), &stack.env_hidden.clone());

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, Signature,
Span, SyntaxShape, Type, Value,
@ -18,7 +18,7 @@ impl Command for ParEach {
}
fn usage(&self) -> &str {
"Run a block on each element of input in parallel"
"Run a closure on each element of input in parallel"
}
fn signature(&self) -> nu_protocol::Signature {
@ -28,9 +28,9 @@ impl Command for ParEach {
Type::List(Box::new(Type::Any)),
)])
.required(
"block",
SyntaxShape::Block(Some(vec![SyntaxShape::Any])),
"the block to run",
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
"the closure to run",
)
.switch("numbered", "iterate with an index", Some('n'))
.category(Category::Filters)
@ -64,7 +64,7 @@ impl Command for ParEach {
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let numbered = call.has_flag("numbered");
let metadata = input.metadata();

View File

@ -3,7 +3,7 @@ use std::sync::atomic::Ordering;
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape, Type, Value,
};
@ -26,8 +26,8 @@ impl Command for Reduce {
Some('f'),
)
.required(
"block",
SyntaxShape::Block(Some(vec![SyntaxShape::Any, SyntaxShape::Any])),
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any, SyntaxShape::Any])),
"reducing function",
)
.switch("numbered", "iterate with an index", Some('n'))
@ -103,7 +103,7 @@ impl Command for Reduce {
let fold: Option<Value> = call.get_flag(engine_state, stack, "fold")?;
let numbered = call.has_flag("numbered");
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let mut stack = stack.captures_to_stack(&capture_block.captures);
let block = engine_state.get_block(capture_block.block_id);
let ctrlc = engine_state.ctrlc.clone();

View File

@ -1,7 +1,7 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::{
ast::Call,
engine::{CaptureBlock, Command, EngineState, Stack},
engine::{Closure, Command, EngineState, Stack},
Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span,
SyntaxShape, Type, Value,
};
@ -73,7 +73,7 @@ impl Command for SkipUntil {
let span = call.head;
let metadata = input.metadata();
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let var_id = block.signature.get_positional(0).and_then(|arg| arg.var_id);

View File

@ -1,7 +1,7 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::{
ast::Call,
engine::{CaptureBlock, Command, EngineState, Stack},
engine::{Closure, Command, EngineState, Stack},
Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span,
SyntaxShape, Type, Value,
};
@ -74,7 +74,7 @@ impl Command for SkipWhile {
let span = call.head;
let metadata = input.metadata();
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let var_id = block.signature.get_positional(0).and_then(|arg| arg.var_id);

View File

@ -1,7 +1,7 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::{
ast::Call,
engine::{CaptureBlock, Command, EngineState, Stack},
engine::{Closure, Command, EngineState, Stack},
Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span,
SyntaxShape, Type, Value,
};
@ -68,7 +68,7 @@ impl Command for TakeUntil {
) -> Result<PipelineData, ShellError> {
let span = call.head;
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let var_id = block.signature.get_positional(0).and_then(|arg| arg.var_id);

View File

@ -1,7 +1,7 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::{
ast::Call,
engine::{CaptureBlock, Command, EngineState, Stack},
engine::{Closure, Command, EngineState, Stack},
Category, Example, IntoInterruptiblePipelineData, PipelineData, ShellError, Signature, Span,
SyntaxShape, Type, Value,
};
@ -68,7 +68,7 @@ impl Command for TakeWhile {
) -> Result<PipelineData, ShellError> {
let span = call.head;
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let var_id = block.signature.get_positional(0).and_then(|arg| arg.var_id);

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::{Call, CellPath, PathMember};
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, FromValue, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, SyntaxShape, Type, Value,
@ -90,7 +90,7 @@ fn update(
// Replace is a block, so set it up and run it instead of using it as the replacement
if replacement.as_block().is_ok() {
let capture_block: CaptureBlock = FromValue::from_value(&replacement)?;
let capture_block: Closure = FromValue::from_value(&replacement)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let mut stack = stack.captures_to_stack(&capture_block.captures);

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::{Block, Call};
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
PipelineIterator, ShellError, Signature, Span, SyntaxShape, Type, Value,
@ -20,9 +20,9 @@ impl Command for UpdateCells {
Signature::build("update cells")
.input_output_types(vec![(Type::Table(vec![]), Type::Table(vec![]))])
.required(
"block",
SyntaxShape::Block(Some(vec![SyntaxShape::Any])),
"the block to run an update for each cell",
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
"the closure to run an update for each cell",
)
.named(
"columns",
@ -125,7 +125,7 @@ impl Command for UpdateCells {
) -> Result<PipelineData, ShellError> {
// the block to run on each cell
let engine_state = engine_state.clone();
let block: CaptureBlock = call.req(&engine_state, stack, 0)?;
let block: Closure = call.req(&engine_state, stack, 0)?;
let mut stack = stack.captures_to_stack(&block.captures);
let orig_env_vars = stack.env_vars.clone();
let orig_env_hidden = stack.env_hidden.clone();

View File

@ -1,6 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::{Call, CellPath, PathMember};
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, FromValue, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData,
ShellError, Signature, Span, SyntaxShape, Type, Value,
@ -110,7 +110,7 @@ fn upsert(
// Replace is a block, so set it up and run it instead of using it as the replacement
if replacement.as_block().is_ok() {
let capture_block: CaptureBlock = FromValue::from_value(&replacement)?;
let capture_block: Closure = FromValue::from_value(&replacement)?;
let block = engine_state.get_block(capture_block.block_id).clone();
let mut stack = stack.captures_to_stack(&capture_block.captures);

View File

@ -1,7 +1,7 @@
use super::utils::chain_error_with_input;
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, ShellError,
Signature, Span, SyntaxShape, Type, Value,
@ -30,9 +30,9 @@ impl Command for Where {
])
.optional("cond", SyntaxShape::RowCondition, "condition")
.named(
"block",
SyntaxShape::Block(Some(vec![SyntaxShape::Any])),
"use where with a block or variable instead",
"closure",
SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
"use where with a closure",
Some('b'),
)
.category(Category::Filters)
@ -49,8 +49,7 @@ impl Command for Where {
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
if let Ok(Some(capture_block)) = call.get_flag::<CaptureBlock>(engine_state, stack, "block")
{
if let Ok(Some(capture_block)) = call.get_flag::<Closure>(engine_state, stack, "block") {
let metadata = input.metadata();
let ctrlc = engine_state.ctrlc.clone();
let engine_state = engine_state.clone();
@ -180,7 +179,7 @@ impl Command for Where {
}
.map(|x| x.set_metadata(metadata))
} else {
let capture_block: Option<CaptureBlock> = call.opt(engine_state, stack, 0)?;
let capture_block: Option<Closure> = call.opt(engine_state, stack, 0)?;
if let Some(block) = capture_block {
let span = call.head;

View File

@ -217,6 +217,12 @@ fn convert_to_value(
"blocks not supported in nuon".into(),
expr.span,
)),
Expr::Closure(..) => Err(ShellError::OutsideSpannedLabeledError(
original_text.to_string(),
"Error when loading".into(),
"closures not supported in nuon".into(),
expr.span,
)),
Expr::Binary(val) => Ok(Value::Binary { val, span }),
Expr::Bool(val) => Ok(Value::Bool { val, span }),
Expr::Call(..) => Err(ShellError::OutsideSpannedLabeledError(

View File

@ -125,7 +125,7 @@ pub fn value_to_json_value(v: &Value) -> Result<nu_json::Value, ShellError> {
Value::List { vals, .. } => nu_json::Value::Array(json_list(vals)?),
Value::Error { error } => return Err(error.clone()),
Value::Block { .. } | Value::Range { .. } => nu_json::Value::Null,
Value::Closure { .. } | Value::Block { .. } | Value::Range { .. } => nu_json::Value::Null,
Value::Binary { val, .. } => {
nu_json::Value::Array(val.iter().map(|x| nu_json::Value::U64(*x as u64)).collect())
}

View File

@ -66,6 +66,10 @@ fn value_to_string(v: &Value, span: Span) -> Result<String, ShellError> {
"block not supported".into(),
span,
)),
Value::Closure { .. } => Err(ShellError::UnsupportedInput(
"closure not supported".into(),
span,
)),
Value::Bool { val, .. } => {
if *val {
Ok("true".to_string())

View File

@ -100,6 +100,7 @@ fn local_into_string(value: Value, separator: &str, config: &Config) -> String {
.collect::<Vec<_>>()
.join(separator),
Value::Block { val, .. } => format!("<Block {}>", val),
Value::Closure { val, .. } => format!("<Closure {}>", val),
Value::Nothing { .. } => String::new(),
Value::Error { error } => format!("{:?}", error),
Value::Binary { val, .. } => format!("{:?}", val),

View File

@ -67,6 +67,11 @@ fn helper(engine_state: &EngineState, v: &Value) -> Result<toml::Value, ShellErr
let code = String::from_utf8_lossy(code).to_string();
toml::Value::String(code)
}
Value::Closure { span, .. } => {
let code = engine_state.get_span_contents(span);
let code = String::from_utf8_lossy(code).to_string();
toml::Value::String(code)
}
Value::Nothing { .. } => toml::Value::String("<Nothing>".to_string()),
Value::Error { error } => return Err(error.clone()),
Value::Binary { val, .. } => toml::Value::Array(

View File

@ -72,6 +72,7 @@ pub fn value_to_yaml_value(v: &Value) -> Result<serde_yaml::Value, ShellError> {
serde_yaml::Value::Sequence(out)
}
Value::Block { .. } => serde_yaml::Value::Null,
Value::Closure { .. } => serde_yaml::Value::Null,
Value::Nothing { .. } => serde_yaml::Value::Null,
Value::Error { error } => return Err(error.clone()),
Value::Binary { val, .. } => serde_yaml::Value::Sequence(

View File

@ -2,7 +2,7 @@ use std::time::Instant;
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, Signature, SyntaxShape, Value,
};
@ -21,11 +21,7 @@ impl Command for Benchmark {
fn signature(&self) -> nu_protocol::Signature {
Signature::build("benchmark")
.required(
"block",
SyntaxShape::Block(Some(vec![])),
"the block to run",
)
.required("block", SyntaxShape::Block, "the block to run")
.category(Category::System)
}
@ -36,7 +32,7 @@ impl Command for Benchmark {
call: &Call,
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
let capture_block: Closure = call.req(engine_state, stack, 0)?;
let block = engine_state.get_block(capture_block.block_id);
let redirect_stdout = call.redirect_stdout;