nushell/crates/nu-command/src/core_commands/for_.rs

168 lines
5.2 KiB
Rust
Raw Normal View History

2021-10-09 18:14:02 +02:00
use nu_engine::{eval_block, eval_expression};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EvaluationContext};
2021-10-25 06:01:02 +02:00
use nu_protocol::{Example, IntoPipelineData, PipelineData, Signature, Span, SyntaxShape, Value};
2021-10-09 18:14:02 +02:00
2021-10-25 06:01:02 +02:00
#[derive(Clone)]
2021-10-09 18:14:02 +02:00
pub struct For;
impl Command for For {
fn name(&self) -> &str {
"for"
}
fn usage(&self) -> &str {
"Loop over a range"
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("for")
.required(
"var_name",
SyntaxShape::VarWithOptType,
"name of the looping variable",
)
.required(
"range",
2021-10-09 18:58:33 +02:00
SyntaxShape::Keyword(b"in".to_vec(), Box::new(SyntaxShape::Any)),
2021-10-09 18:14:02 +02:00
"range of the loop",
)
.required(
"block",
SyntaxShape::Block(Some(vec![])),
"the block to run",
)
.creates_scope()
}
fn run(
&self,
context: &EvaluationContext,
call: &Call,
2021-10-25 06:01:02 +02:00
_input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
2021-10-09 18:14:02 +02:00
let var_id = call.positional[0]
.as_var()
.expect("internal error: missing variable");
let keyword_expr = call.positional[1]
.as_keyword()
.expect("internal error: missing keyword");
let values = eval_expression(context, keyword_expr)?;
let block = call.positional[2]
.as_block()
.expect("internal error: expected block");
2021-10-09 18:58:33 +02:00
2021-10-09 18:14:02 +02:00
let context = context.clone();
2021-10-25 06:01:02 +02:00
match values {
Value::List { vals, span } => Ok(vals
.into_iter()
.map(move |x| {
let block = context.engine_state.get_block(block);
2021-10-09 18:58:33 +02:00
2021-10-25 06:24:10 +02:00
let mut state = context.enter_scope();
2021-10-09 18:58:33 +02:00
2021-10-25 06:01:02 +02:00
state.add_var(var_id, x);
2021-10-09 18:58:33 +02:00
2021-10-25 06:01:02 +02:00
match eval_block(&state, block, PipelineData::new()) {
Ok(value) => Value::List {
vals: value.collect(),
span,
},
Err(error) => Value::Error { error },
}
})
.into_pipeline_data()),
2021-10-25 06:24:10 +02:00
Value::Range { val, span } => Ok(val
.into_range_iter()?
.map(move |x| {
let block = context.engine_state.get_block(block);
let mut state = context.enter_scope();
state.add_var(var_id, x);
match eval_block(&state, block, PipelineData::new()) {
Ok(value) => Value::List {
vals: value.collect(),
span,
},
Err(error) => Value::Error { error },
}
})
.into_pipeline_data()),
x => {
let block = context.engine_state.get_block(block);
let mut state = context.enter_scope();
state.add_var(var_id, x);
eval_block(&state, block, PipelineData::new())
}
2021-10-25 06:01:02 +02:00
}
2021-10-09 18:14:02 +02:00
}
fn examples(&self) -> Vec<Example> {
let span = Span::unknown();
vec![
Example {
description: "Echo the square of each integer",
example: "for x in [1 2 3] { $x * $x }",
2021-10-09 15:10:10 +02:00
result: Some(Value::List {
vals: vec![
Value::Int { val: 1, span },
Value::Int { val: 4, span },
Value::Int { val: 9, span },
],
span: Span::unknown(),
}),
2021-10-09 18:14:02 +02:00
},
Example {
description: "Work with elements of a range",
example: "for $x in 1..3 { $x }",
2021-10-09 15:10:10 +02:00
result: Some(Value::List {
vals: vec![
Value::Int { val: 1, span },
Value::Int { val: 2, span },
Value::Int { val: 3, span },
],
span: Span::unknown(),
}),
2021-10-09 18:14:02 +02:00
},
2021-10-09 18:58:33 +02:00
// FIXME? Numbered `for` is kinda strange, but was supported in previous nushell
// Example {
// description: "Number each item and echo a message",
// example: "for $it in ['bob' 'fred'] --numbered { $\"($it.index) is ($it.item)\" }",
// result: Some(Value::List {
// vals: vec![
// Value::String {
// val: "0 is bob".into(),
// span,
// },
// Value::String {
// val: "0 is fred".into(),
// span,
// },
// ],
// span: Span::unknown(),
// }),
// },
2021-10-09 18:14:02 +02:00
]
}
}
2021-10-09 18:58:33 +02:00
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(For {})
}
}