nushell/crates/nu-engine/src/call_ext.rs

103 lines
2.6 KiB
Rust
Raw Normal View History

2021-10-25 08:31:39 +02:00
use nu_protocol::{
ast::Call,
2021-10-25 18:58:58 +02:00
engine::{EngineState, Stack},
FromValue, ShellError,
2021-10-25 08:31:39 +02:00
};
2021-10-01 23:53:13 +02:00
use crate::eval_expression;
2021-10-01 23:53:13 +02:00
pub trait CallExt {
fn get_flag<T: FromValue>(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-10-01 23:53:13 +02:00
name: &str,
) -> Result<Option<T>, ShellError>;
fn rest<T: FromValue>(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-10-01 23:53:13 +02:00
starting_pos: usize,
) -> Result<Vec<T>, ShellError>;
2021-10-02 04:59:11 +02:00
fn opt<T: FromValue>(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-10-02 04:59:11 +02:00
pos: usize,
) -> Result<Option<T>, ShellError>;
2021-10-25 08:31:39 +02:00
fn req<T: FromValue>(
&self,
engine_state: &EngineState,
stack: &mut Stack,
pos: usize,
) -> Result<T, ShellError>;
2021-10-01 23:53:13 +02:00
}
impl CallExt for Call {
fn get_flag<T: FromValue>(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-10-01 23:53:13 +02:00
name: &str,
) -> Result<Option<T>, ShellError> {
if let Some(expr) = self.get_flag_expr(name) {
2021-10-25 08:31:39 +02:00
let result = eval_expression(engine_state, stack, &expr)?;
2021-10-01 23:53:13 +02:00
FromValue::from_value(&result).map(Some)
} else {
Ok(None)
}
}
fn rest<T: FromValue>(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-10-01 23:53:13 +02:00
starting_pos: usize,
) -> Result<Vec<T>, ShellError> {
let mut output = vec![];
for expr in self.positional_iter().skip(starting_pos) {
2021-10-25 08:31:39 +02:00
let result = eval_expression(engine_state, stack, expr)?;
2021-10-01 23:53:13 +02:00
output.push(FromValue::from_value(&result)?);
}
Ok(output)
}
2021-10-02 04:59:11 +02:00
fn opt<T: FromValue>(
&self,
2021-10-25 08:31:39 +02:00
engine_state: &EngineState,
stack: &mut Stack,
2021-10-02 04:59:11 +02:00
pos: usize,
) -> Result<Option<T>, ShellError> {
if let Some(expr) = self.positional_nth(pos) {
let result = eval_expression(engine_state, stack, expr)?;
2021-10-02 04:59:11 +02:00
FromValue::from_value(&result).map(Some)
} else {
Ok(None)
}
}
2021-10-25 08:31:39 +02:00
fn req<T: FromValue>(
&self,
engine_state: &EngineState,
stack: &mut Stack,
pos: usize,
) -> Result<T, ShellError> {
if let Some(expr) = self.positional_nth(pos) {
let result = eval_expression(engine_state, stack, expr)?;
2021-10-02 04:59:11 +02:00
FromValue::from_value(&result)
} else if self.positional_len() == 0 {
Err(ShellError::AccessEmptyContent(self.head))
2021-10-02 04:59:11 +02:00
} else {
Err(ShellError::AccessBeyondEnd(
self.positional_len() - 1,
2021-10-02 04:59:11 +02:00
self.head,
))
}
}
2021-10-01 23:53:13 +02:00
}