Allow parse-time evaluation of calls, pipelines and subexpressions (#9499)

Co-authored-by: Antoine Stevan <44101798+amtoine@users.noreply.github.com>
This commit is contained in:
Jakub Žádník
2023-08-26 16:41:29 +03:00
committed by GitHub
parent 3d73287ea4
commit 5ac5b90aed
37 changed files with 849 additions and 161 deletions

View File

@ -1,6 +1,7 @@
use nu_protocol::{
ast::Call,
engine::{EngineState, Stack},
engine::{EngineState, Stack, StateWorkingSet},
eval_const::eval_constant,
FromValue, ShellError,
};
@ -14,6 +15,12 @@ pub trait CallExt {
name: &str,
) -> Result<Option<T>, ShellError>;
fn get_flag_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
name: &str,
) -> Result<Option<T>, ShellError>;
fn rest<T: FromValue>(
&self,
engine_state: &EngineState,
@ -21,6 +28,12 @@ pub trait CallExt {
starting_pos: usize,
) -> Result<Vec<T>, ShellError>;
fn rest_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
starting_pos: usize,
) -> Result<Vec<T>, ShellError>;
fn opt<T: FromValue>(
&self,
engine_state: &EngineState,
@ -35,6 +48,12 @@ pub trait CallExt {
pos: usize,
) -> Result<T, ShellError>;
fn req_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
pos: usize,
) -> Result<T, ShellError>;
fn req_parser_info<T: FromValue>(
&self,
engine_state: &EngineState,
@ -58,6 +77,19 @@ impl CallExt for Call {
}
}
fn get_flag_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
name: &str,
) -> Result<Option<T>, ShellError> {
if let Some(expr) = self.get_flag_expr(name) {
let result = eval_constant(working_set, &expr)?;
FromValue::from_value(&result).map(Some)
} else {
Ok(None)
}
}
fn rest<T: FromValue>(
&self,
engine_state: &EngineState,
@ -74,6 +106,21 @@ impl CallExt for Call {
Ok(output)
}
fn rest_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
starting_pos: usize,
) -> Result<Vec<T>, ShellError> {
let mut output = vec![];
for expr in self.positional_iter().skip(starting_pos) {
let result = eval_constant(working_set, expr)?;
output.push(FromValue::from_value(&result)?);
}
Ok(output)
}
fn opt<T: FromValue>(
&self,
engine_state: &EngineState,
@ -107,6 +154,24 @@ impl CallExt for Call {
}
}
fn req_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
pos: usize,
) -> Result<T, ShellError> {
if let Some(expr) = self.positional_nth(pos) {
let result = eval_constant(working_set, expr)?;
FromValue::from_value(&result)
} else if self.positional_len() == 0 {
Err(ShellError::AccessEmptyContent { span: self.head })
} else {
Err(ShellError::AccessBeyondEnd {
max_idx: self.positional_len() - 1,
span: self.head,
})
}
}
fn req_parser_info<T: FromValue>(
&self,
engine_state: &EngineState,

View File

@ -2,7 +2,7 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use nu_protocol::ast::{Call, Expr, PathMember};
use nu_protocol::engine::{EngineState, Stack};
use nu_protocol::engine::{EngineState, Stack, StateWorkingSet, PWD_ENV};
use nu_protocol::{Config, PipelineData, ShellError, Span, Value, VarId};
use nu_path::canonicalize_with;
@ -159,8 +159,9 @@ pub fn env_to_strings(
/// Shorthand for env_to_string() for PWD with custom error
pub fn current_dir_str(engine_state: &EngineState, stack: &Stack) -> Result<String, ShellError> {
if let Some(pwd) = stack.get_env_var(engine_state, "PWD") {
match env_to_string("PWD", &pwd, engine_state, stack) {
if let Some(pwd) = stack.get_env_var(engine_state, PWD_ENV) {
// TODO: PWD should be string by default, we don't need to run ENV_CONVERSIONS on it
match env_to_string(PWD_ENV, &pwd, engine_state, stack) {
Ok(cwd) => {
if Path::new(&cwd).is_absolute() {
Ok(cwd)
@ -187,11 +188,55 @@ pub fn current_dir_str(engine_state: &EngineState, stack: &Stack) -> Result<Stri
}
}
/// Simplified version of current_dir_str() for constant evaluation
pub fn current_dir_str_const(working_set: &StateWorkingSet) -> Result<String, ShellError> {
if let Some(pwd) = working_set.get_env_var(PWD_ENV) {
match pwd {
Value::String { val, span } => {
if Path::new(val).is_absolute() {
Ok(val.clone())
} else {
Err(ShellError::GenericError(
"Invalid current directory".to_string(),
format!("The 'PWD' environment variable must be set to an absolute path. Found: '{val}'"),
Some(*span),
None,
Vec::new()
))
}
}
_ => Err(ShellError::GenericError(
"PWD is not a string".to_string(),
"".to_string(),
None,
Some(
"Cusrrent working directory environment variable 'PWD' must be a string."
.to_string(),
),
Vec::new(),
)),
}
} else {
Err(ShellError::GenericError(
"Current directory not found".to_string(),
"".to_string(),
None,
Some("The environment variable 'PWD' was not found. It is required to define the current directory.".to_string()),
Vec::new(),
))
}
}
/// Calls current_dir_str() and returns the current directory as a PathBuf
pub fn current_dir(engine_state: &EngineState, stack: &Stack) -> Result<PathBuf, ShellError> {
current_dir_str(engine_state, stack).map(PathBuf::from)
}
/// Version of current_dir() for constant evaluation
pub fn current_dir_const(working_set: &StateWorkingSet) -> Result<PathBuf, ShellError> {
current_dir_str_const(working_set).map(PathBuf::from)
}
/// Get the contents of path environment variable as a list of strings
///
/// On non-Windows: It will fetch PATH