repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/compile_error.rs | crates/nu-protocol/src/errors/compile_error.rs | use crate::{RegId, Span};
use miette::Diagnostic;
use serde::{Deserialize, Serialize};
use thiserror::Error;
/// An internal compiler error, generally means a Nushell bug rather than an issue with user error
/// since parsing and typechecking has already passed.
#[derive(Debug, Clone, Error, Diagnostic, PartialEq, Serialize, Deserialize)]
pub enum CompileError {
#[error("Register overflow.")]
#[diagnostic(code(nu::compile::register_overflow))]
RegisterOverflow {
#[label("the code being compiled is probably too large")]
block_span: Option<Span>,
},
#[error("Register {reg_id} was uninitialized when used, possibly reused.")]
#[diagnostic(
code(nu::compile::register_uninitialized),
help(
"this is a compiler bug. Please report it at https://github.com/nushell/nushell/issues/new\nfrom: {caller}"
)
)]
RegisterUninitialized { reg_id: RegId, caller: String },
#[error("Register {reg_id} was uninitialized when used, possibly reused.")]
#[diagnostic(
code(nu::compile::register_uninitialized),
help(
"this is a compiler bug. Please report it at https://github.com/nushell/nushell/issues/new\nfrom: {caller}"
)
)]
RegisterUninitializedWhilePushingInstruction {
reg_id: RegId,
caller: String,
instruction: String,
#[label("while adding this instruction: {instruction}")]
span: Span,
},
#[error("Block contains too much string data: maximum 4 GiB exceeded.")]
#[diagnostic(
code(nu::compile::data_overflow),
help("try loading the string data from a file instead")
)]
DataOverflow {
#[label("while compiling this block")]
block_span: Option<Span>,
},
#[error("Block contains too many files.")]
#[diagnostic(
code(nu::compile::register_overflow),
help("try using fewer file redirections")
)]
FileOverflow {
#[label("while compiling this block")]
block_span: Option<Span>,
},
#[error("Invalid redirect mode: File should not be specified by commands.")]
#[diagnostic(
code(nu::compile::invalid_redirect_mode),
help(
"this is a command bug. Please report it at https://github.com/nushell/nushell/issues/new"
)
)]
InvalidRedirectMode {
#[label("while compiling this expression")]
span: Span,
},
#[error("Encountered garbage, likely due to parse error.")]
#[diagnostic(code(nu::compile::garbage))]
Garbage {
#[label("garbage found here")]
span: Span,
},
#[error("Unsupported operator expression.")]
#[diagnostic(code(nu::compile::unsupported_operator_expression))]
UnsupportedOperatorExpression {
#[label("this expression is in operator position but is not an operator")]
span: Span,
},
#[error("Attempted access of $env by integer path.")]
#[diagnostic(code(nu::compile::access_env_by_int))]
AccessEnvByInt {
#[label("$env keys should be strings")]
span: Span,
},
#[error("Encountered invalid `{keyword}` keyword call.")]
#[diagnostic(code(nu::compile::invalid_keyword_call))]
InvalidKeywordCall {
keyword: String,
#[label("this call is not properly formed")]
span: Span,
},
#[error("Attempted to set branch target of non-branch instruction.")]
#[diagnostic(
code(nu::compile::set_branch_target_of_non_branch_instruction),
help(
"this is a compiler bug. Please report it at https://github.com/nushell/nushell/issues/new"
)
)]
SetBranchTargetOfNonBranchInstruction {
instruction: String,
#[label("tried to modify: {instruction}")]
span: Span,
},
/// You're trying to run an unsupported external command.
///
/// ## Resolution
///
/// Make sure there's an appropriate `run-external` declaration for this external command.
#[error("External calls are not supported.")]
#[diagnostic(
code(nu::compile::run_external_not_found),
help("`run-external` was not found in scope")
)]
RunExternalNotFound {
#[label("can't be run in this context")]
span: Span,
},
/// Invalid assignment left-hand side
///
/// ## Resolution
///
/// Assignment requires that you assign to a variable or variable cell path.
#[error("Assignment operations require a variable.")]
#[diagnostic(
code(nu::compile::assignment_requires_variable),
help("try assigning to a variable or a cell path of a variable")
)]
AssignmentRequiresVar {
#[label("needs to be a variable")]
span: Span,
},
/// Invalid assignment left-hand side
///
/// ## Resolution
///
/// Assignment requires that you assign to a mutable variable or cell path.
#[error("Assignment to an immutable variable.")]
#[diagnostic(
code(nu::compile::assignment_requires_mutable_variable),
help("declare the variable with `mut`, or shadow it again with `let`")
)]
AssignmentRequiresMutableVar {
#[label("needs to be a mutable variable")]
span: Span,
},
/// This environment variable cannot be set manually.
///
/// ## Resolution
///
/// This environment variable is set automatically by Nushell and cannot not be set manually.
#[error("{envvar_name} cannot be set manually.")]
#[diagnostic(
code(nu::compile::automatic_env_var_set_manually),
help(
r#"The environment variable '{envvar_name}' is set automatically by Nushell and cannot be set manually."#
)
)]
AutomaticEnvVarSetManually {
envvar_name: String,
#[label("cannot set '{envvar_name}' manually")]
span: Span,
},
/// It is not possible to replace the entire environment at once
///
/// ## Resolution
///
/// Setting the entire environment is not allowed. Change environment variables individually
/// instead.
#[error("Cannot replace environment.")]
#[diagnostic(
code(nu::compile::cannot_replace_env),
help("Assigning a value to '$env' is not allowed.")
)]
CannotReplaceEnv {
#[label("setting '$env' not allowed")]
span: Span,
},
#[error("Unexpected expression.")]
#[diagnostic(code(nu::compile::unexpected_expression))]
UnexpectedExpression {
expr_name: String,
#[label("{expr_name} is not allowed in this context")]
span: Span,
},
#[error("Missing required declaration: `{decl_name}`")]
#[diagnostic(code(nu::compile::missing_required_declaration))]
MissingRequiredDeclaration {
decl_name: String,
#[label("`{decl_name}` must be in scope to compile this expression")]
span: Span,
},
#[error("Invalid literal")]
#[diagnostic(code(nu::compile::invalid_literal))]
InvalidLiteral {
msg: String,
#[label("{msg}")]
span: Span,
},
#[error("{msg}")]
#[diagnostic(code(nu::compile::not_in_a_try))]
NotInATry {
msg: String,
#[label("can't be used outside of a try block")]
span: Option<Span>,
},
#[error("{msg}")]
#[diagnostic(code(nu::compile::not_in_a_loop))]
NotInALoop {
msg: String,
#[label("can't be used outside of a loop")]
span: Option<Span>,
},
#[error("Incoherent loop state: the loop that ended was not the one we were expecting.")]
#[diagnostic(
code(nu::compile::incoherent_loop_state),
help(
"this is a compiler bug. Please report it at https://github.com/nushell/nushell/issues/new"
)
)]
IncoherentLoopState {
#[label("while compiling this block")]
block_span: Option<Span>,
},
#[error("Undefined label `{label_id}`.")]
#[diagnostic(
code(nu::compile::undefined_label),
help(
"this is a compiler bug. Please report it at https://github.com/nushell/nushell/issues/new"
)
)]
UndefinedLabel {
label_id: usize,
#[label("label was used while compiling this code")]
span: Option<Span>,
},
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/chained_error.rs | crates/nu-protocol/src/errors/chained_error.rs | use super::shell_error::ShellError;
use crate::Span;
use miette::{LabeledSpan, Severity, SourceCode};
use thiserror::Error;
/// An error struct that contains source errors.
///
/// However, it's a bit special; if the error is constructed for the first time using
/// [`ChainedError::new`], it will behave the same as the single source error.
///
/// If it's constructed nestedly using [`ChainedError::new_chained`], it will treat all underlying errors as related.
///
/// For a usage example, please check [`ShellError::into_chainned`].
#[derive(Debug, Clone, PartialEq, Error)]
pub struct ChainedError {
first: bool,
pub(crate) sources: Vec<ShellError>,
span: Span,
}
impl std::fmt::Display for ChainedError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.first {
write!(f, "{}", self.sources[0])
} else {
write!(f, "oops")
}
}
}
impl ChainedError {
pub fn new(source: ShellError, span: Span) -> Self {
Self {
first: true,
sources: vec![source],
span,
}
}
pub fn new_chained(sources: Self, span: Span) -> Self {
Self {
first: false,
sources: vec![ShellError::ChainedError(sources)],
span,
}
}
}
impl miette::Diagnostic for ChainedError {
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> {
if self.first {
self.sources[0].related()
} else {
Some(Box::new(self.sources.iter().map(|s| s as _)))
}
}
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
if self.first {
self.sources[0].code()
} else {
Some(Box::new("chained_error"))
}
}
fn severity(&self) -> Option<Severity> {
if self.first {
self.sources[0].severity()
} else {
None
}
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
if self.first {
self.sources[0].help()
} else {
None
}
}
fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
if self.first {
self.sources[0].url()
} else {
None
}
}
fn labels<'a>(&'a self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + 'a>> {
if self.first {
self.sources[0].labels()
} else {
Some(Box::new(
vec![LabeledSpan::new_with_span(
Some("error happened when running this".to_string()),
self.span,
)]
.into_iter(),
))
}
}
// Finally, we redirect the source_code method to our own source.
fn source_code(&self) -> Option<&dyn SourceCode> {
if self.first {
self.sources[0].source_code()
} else {
None
}
}
fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> {
if self.first {
self.sources[0].diagnostic_source()
} else {
None
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/labeled_error.rs | crates/nu-protocol/src/errors/labeled_error.rs | use super::{ShellError, shell_error::io::IoError};
use crate::{FromValue, IntoValue, Span, Type, Value, record};
use miette::{Diagnostic, LabeledSpan, NamedSource, SourceSpan};
use serde::{Deserialize, Serialize};
use std::{fmt, fs};
// # use nu_protocol::{FromValue, Value, ShellError, record, Span};
/// A very generic type of error used for interfacing with external code, such as scripts and
/// plugins.
///
/// This generally covers most of the interface of [`miette::Diagnostic`], but with types that are
/// well-defined for our protocol.
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct LabeledError {
/// The main message for the error.
pub msg: String,
/// Labeled spans attached to the error, demonstrating to the user where the problem is.
#[serde(default)]
pub labels: Box<Vec<ErrorLabel>>,
/// A unique machine- and search-friendly error code to associate to the error. (e.g.
/// `nu::shell::missing_config_value`)
#[serde(default)]
pub code: Option<String>,
/// A link to documentation about the error, used in conjunction with `code`
#[serde(default)]
pub url: Option<String>,
/// Additional help for the error, usually a hint about what the user might try
#[serde(default)]
pub help: Option<String>,
/// Errors that are related to or caused this error
#[serde(default)]
pub inner: Box<Vec<ShellError>>,
}
impl LabeledError {
/// Create a new plain [`LabeledError`] with the given message.
///
/// This is usually used builder-style with methods like [`.with_label()`](Self::with_label) to
/// build an error.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::LabeledError;
/// let error = LabeledError::new("Something bad happened");
/// assert_eq!("Something bad happened", error.to_string());
/// ```
pub fn new(msg: impl Into<String>) -> Self {
Self {
msg: msg.into(),
..Default::default()
}
}
/// Add a labeled span to the error to demonstrate to the user where the problem is.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::{LabeledError, Span};
/// # let span = Span::test_data();
/// let error = LabeledError::new("An error")
/// .with_label("happened here", span);
/// assert_eq!("happened here", &error.labels[0].text);
/// assert_eq!(span, error.labels[0].span);
/// ```
pub fn with_label(mut self, text: impl Into<String>, span: Span) -> Self {
self.labels.push(ErrorLabel {
text: text.into(),
span,
});
self
}
/// Add a unique machine- and search-friendly error code to associate to the error. (e.g.
/// `nu::shell::missing_config_value`)
///
/// # Example
///
/// ```rust
/// # use nu_protocol::LabeledError;
/// let error = LabeledError::new("An error")
/// .with_code("my_product::error");
/// assert_eq!(Some("my_product::error"), error.code.as_deref());
/// ```
pub fn with_code(mut self, code: impl Into<String>) -> Self {
self.code = Some(code.into());
self
}
/// Add a link to documentation about the error, used in conjunction with `code`.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::LabeledError;
/// let error = LabeledError::new("An error")
/// .with_url("https://example.org/");
/// assert_eq!(Some("https://example.org/"), error.url.as_deref());
/// ```
pub fn with_url(mut self, url: impl Into<String>) -> Self {
self.url = Some(url.into());
self
}
/// Add additional help for the error, usually a hint about what the user might try.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::LabeledError;
/// let error = LabeledError::new("An error")
/// .with_help("did you try turning it off and back on again?");
/// assert_eq!(Some("did you try turning it off and back on again?"), error.help.as_deref());
/// ```
pub fn with_help(mut self, help: impl Into<String>) -> Self {
self.help = Some(help.into());
self
}
/// Add an error that is related to or caused this error.
///
/// # Example
///
/// ```rust
/// # use nu_protocol::{LabeledError, ShellError};
/// let error = LabeledError::new("An error")
/// .with_inner(LabeledError::new("out of coolant"));
/// let check: ShellError = LabeledError::new("out of coolant").into();
/// assert_eq!(check, error.inner[0]);
/// ```
pub fn with_inner(mut self, inner: impl Into<ShellError>) -> Self {
let inner_error: ShellError = inner.into();
self.inner.push(inner_error);
self
}
/// Create a [`LabeledError`] from a type that implements [`miette::Diagnostic`].
///
/// # Example
///
/// [`ShellError`] implements `miette::Diagnostic`:
///
/// ```rust
/// # use nu_protocol::{ShellError, LabeledError, shell_error::{self, io::IoError}, Span};
/// #
/// let error = LabeledError::from_diagnostic(
/// &ShellError::Io(IoError::new_with_additional_context(
/// shell_error::io::ErrorKind::from_std(std::io::ErrorKind::Other),
/// Span::test_data(),
/// None,
/// "some error"
/// ))
/// );
/// assert!(error.to_string().contains("I/O error"));
/// ```
pub fn from_diagnostic(diag: &(impl miette::Diagnostic + ?Sized)) -> Self {
Self {
msg: diag.to_string(),
labels: diag
.labels()
.into_iter()
.flatten()
.map(|label| ErrorLabel {
text: label.label().unwrap_or("").into(),
span: Span::new(label.offset(), label.offset() + label.len()),
})
.collect::<Vec<_>>()
.into(),
code: diag.code().map(|s| s.to_string()),
url: diag.url().map(|s| s.to_string()),
help: diag.help().map(|s| s.to_string()),
inner: diag
.related()
.into_iter()
.flatten()
.map(|i| Self::from_diagnostic(i).into())
.collect::<Vec<_>>()
.into(),
}
}
}
/// A labeled span within a [`LabeledError`].
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorLabel {
/// Text to show together with the span
pub text: String,
/// Span pointing at where the text references in the source
pub span: Span,
}
impl From<ErrorLabel> for LabeledSpan {
fn from(val: ErrorLabel) -> Self {
LabeledSpan::new(
(!val.text.is_empty()).then_some(val.text),
val.span.start,
val.span.end - val.span.start,
)
}
}
impl From<ErrorLabel> for SourceSpan {
fn from(val: ErrorLabel) -> Self {
SourceSpan::new(val.span.start.into(), val.span.end - val.span.start)
}
}
impl FromValue for ErrorLabel {
fn from_value(v: Value) -> Result<Self, ShellError> {
let record = v.clone().into_record()?;
let text = String::from_value(match record.get("text") {
Some(val) => val.clone(),
None => Value::string("", v.span()),
})
.unwrap_or("originates from here".into());
let span = Span::from_value(match record.get("span") {
Some(val) => val.clone(),
// Maybe there's a better way...
None => Value::record(
record! {
"start" => Value::int(v.span().start as i64, v.span()),
"end" => Value::int(v.span().end as i64, v.span()),
},
v.span(),
),
});
match span {
Ok(s) => Ok(Self { text, span: s }),
Err(e) => Err(e),
}
}
fn expected_type() -> crate::Type {
Type::Record(
vec![
("text".into(), Type::String),
("span".into(), Type::record()),
]
.into(),
)
}
}
impl IntoValue for ErrorLabel {
fn into_value(self, span: Span) -> Value {
record! {
"text" => Value::string(self.text, span),
"span" => span.into_value(span),
}
.into_value(span)
}
}
/// Optionally named error source
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorSource {
name: Option<String>,
text: Option<String>,
path: Option<String>,
}
impl ErrorSource {
pub fn new(name: Option<String>, text: String) -> Self {
Self {
name,
text: Some(text),
path: None,
}
}
}
impl From<ErrorSource> for NamedSource<String> {
fn from(value: ErrorSource) -> Self {
let name = value.name.unwrap_or_default();
match value {
ErrorSource {
text: Some(text),
path: None,
..
} => NamedSource::new(name, text),
ErrorSource {
text: None,
path: Some(path),
..
} => {
let text = fs::read_to_string(&path).unwrap_or_default();
NamedSource::new(path, text)
}
_ => NamedSource::new(name, "".into()),
}
}
}
impl FromValue for ErrorSource {
fn from_value(v: Value) -> Result<Self, ShellError> {
let record = v.clone().into_record()?;
let name = record
.get("name")
.and_then(|s| String::from_value(s.clone()).ok());
// let name = String::from_value(record.get("name").unwrap().clone()).ok();
let text = if let Some(text) = record.get("text") {
String::from_value(text.clone()).ok()
} else {
None
};
let path = if let Some(path) = record.get("path") {
String::from_value(path.clone()).ok()
} else {
None
};
match (text, path) {
// Prioritize not reading from a file and using the text raw
(text @ Some(_), _) => Ok(ErrorSource {
name,
text,
path: None,
}),
(_, path @ Some(_)) => Ok(ErrorSource {
name: path.clone(),
text: None,
path,
}),
_ => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> crate::Type {
Type::Record(
vec![
("name".into(), Type::String),
("text".into(), Type::String),
("path".into(), Type::String),
]
.into(),
)
}
}
impl IntoValue for ErrorSource {
fn into_value(self, span: Span) -> Value {
match self {
Self {
name: Some(name),
text: Some(text),
..
} => record! {
"name" => Value::string(name, span),
"text" => Value::string(text, span),
},
Self {
text: Some(text), ..
} => record! {
"text" => Value::string(text, span)
},
Self {
name: Some(name),
path: Some(path),
..
} => record! {
"name" => Value::string(name, span),
"path" => Value::string(path, span),
},
Self {
path: Some(path), ..
} => record! {
"path" => Value::string(path, span),
},
_ => record! {},
}
.into_value(span)
}
}
impl fmt::Display for LabeledError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.msg)
}
}
impl std::error::Error for LabeledError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.inner.first().map(|r| r as _)
}
}
impl Diagnostic for LabeledError {
fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
self.code.as_ref().map(Box::new).map(|b| b as _)
}
fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
self.help.as_ref().map(Box::new).map(|b| b as _)
}
fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> {
self.url.as_ref().map(Box::new).map(|b| b as _)
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
Some(Box::new(
self.labels.iter().map(|label| label.clone().into()),
))
}
fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
Some(Box::new(self.inner.iter().map(|r| r as _)))
}
}
impl From<ShellError> for LabeledError {
fn from(err: ShellError) -> Self {
Self::from_diagnostic(&err)
}
}
impl From<IoError> for LabeledError {
fn from(err: IoError) -> Self {
Self::from_diagnostic(&err)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/parse_warning.rs | crates/nu-protocol/src/errors/parse_warning.rs | use crate::Span;
use miette::Diagnostic;
use std::hash::Hash;
use thiserror::Error;
use crate::{ReportMode, Reportable};
#[derive(Clone, Debug, Error, Diagnostic)]
#[diagnostic(severity(Warning))]
pub enum ParseWarning {
/// A parse-time deprecation. Indicates that something will be removed in a future release.
///
/// Use [`ShellWarning::Deprecated`](crate::ShellWarning::Deprecated) if this is a deprecation
/// which is only detectable at run-time.
#[error("{dep_type} deprecated.")]
#[diagnostic(code(nu::parser::deprecated))]
Deprecated {
dep_type: String,
label: String,
#[label("{label}")]
span: Span,
#[help]
help: Option<String>,
report_mode: ReportMode,
},
}
impl ParseWarning {
pub fn span(&self) -> Span {
match self {
ParseWarning::Deprecated { span, .. } => *span,
}
}
}
impl Reportable for ParseWarning {
fn report_mode(&self) -> ReportMode {
match self {
ParseWarning::Deprecated { report_mode, .. } => *report_mode,
}
}
}
// To keep track of reported warnings
impl Hash for ParseWarning {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
ParseWarning::Deprecated {
dep_type, label, ..
} => {
dep_type.hash(state);
label.hash(state);
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/mod.rs | crates/nu-protocol/src/errors/mod.rs | mod chained_error;
mod compile_error;
mod config;
mod labeled_error;
mod parse_error;
mod parse_warning;
mod short_handler;
pub mod report_error;
pub mod shell_error;
pub mod shell_warning;
pub use compile_error::CompileError;
pub use config::{ConfigError, ConfigWarning};
pub use labeled_error::{ErrorLabel, ErrorSource, LabeledError};
pub use parse_error::{DidYouMean, ParseError};
pub use parse_warning::ParseWarning;
pub use report_error::{
ReportMode, Reportable, format_cli_error, report_parse_error, report_parse_warning,
report_shell_error, report_shell_warning,
};
pub use shell_error::ShellError;
pub use shell_warning::ShellWarning;
pub use short_handler::ShortReportHandler;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/parse_error.rs | crates/nu-protocol/src/errors/parse_error.rs | use crate::{Span, Type, ast::RedirectionSource, did_you_mean};
use miette::Diagnostic;
use serde::{Deserialize, Serialize};
use std::{
fmt::Display,
str::{Utf8Error, from_utf8},
};
use thiserror::Error;
#[derive(Clone, Debug, Error, Diagnostic, Serialize, Deserialize)]
pub enum ParseError {
/// The parser encountered unexpected tokens, when the code should have
/// finished. You should remove these or finish adding what you intended
/// to add.
#[error("Extra tokens in code.")]
#[diagnostic(code(nu::parser::extra_tokens), help("Try removing them."))]
ExtraTokens(#[label = "extra tokens"] Span),
#[error("Invalid characters after closing delimiter")]
#[diagnostic(
code(nu::parser::extra_token_after_closing_delimiter),
help("Try removing them.")
)]
ExtraTokensAfterClosingDelimiter(#[label = "invalid characters"] Span),
#[error("Extra positional argument.")]
#[diagnostic(code(nu::parser::extra_positional), help("Usage: {0}"))]
ExtraPositional(String, #[label = "extra positional argument"] Span),
#[error("Required positional parameter after optional parameter")]
#[diagnostic(code(nu::parser::required_after_optional))]
RequiredAfterOptional(
String,
#[label = "required parameter {0} after optional parameter"] Span,
),
#[error("Unexpected end of code.")]
#[diagnostic(code(nu::parser::unexpected_eof))]
UnexpectedEof(String, #[label("expected closing {0}")] Span),
#[error("Unclosed delimiter.")]
#[diagnostic(code(nu::parser::unclosed_delimiter))]
Unclosed(String, #[label("unclosed {0}")] Span),
#[error("Unbalanced delimiter.")]
#[diagnostic(code(nu::parser::unbalanced_delimiter))]
Unbalanced(String, String, #[label("unbalanced {0} and {1}")] Span),
#[error("Parse mismatch during operation.")]
#[diagnostic(code(nu::parser::parse_mismatch))]
Expected(&'static str, #[label("expected {0}")] Span),
#[error("Parse mismatch during operation.")]
#[diagnostic(code(nu::parser::parse_mismatch_with_full_string_msg))]
ExpectedWithStringMsg(String, #[label("expected {0}")] Span),
#[error("Parse mismatch during operation.")]
#[diagnostic(code(nu::parser::parse_mismatch_with_did_you_mean))]
ExpectedWithDidYouMean(&'static str, DidYouMean, #[label("expected {0}. {1}")] Span),
#[error("Command does not support {0} input.")]
#[diagnostic(code(nu::parser::input_type_mismatch))]
InputMismatch(String, #[label("command doesn't support {0} input")] Span),
#[error("Command output doesn't match {0}.")]
#[diagnostic(code(nu::parser::output_type_mismatch))]
OutputMismatch(
Type,
String,
#[label("expected {0}, but command outputs {1}")] Span,
),
#[error("Type mismatch during operation.")]
#[diagnostic(code(nu::parser::type_mismatch))]
Mismatch(String, String, #[label("expected {0}, found {1}")] Span), // expected, found, span
#[error("The '&&' operator is not supported in Nushell")]
#[diagnostic(
code(nu::parser::shell_andand),
help("use ';' instead of the shell '&&', or 'and' instead of the boolean '&&'")
)]
ShellAndAnd(#[label("instead of '&&', use ';' or 'and'")] Span),
#[error("The '||' operator is not supported in Nushell")]
#[diagnostic(
code(nu::parser::shell_oror),
help("use 'try' instead of the shell '||', or 'or' instead of the boolean '||'")
)]
ShellOrOr(#[label("instead of '||', use 'try' or 'or'")] Span),
#[error("The '2>' shell operation is 'err>' in Nushell.")]
#[diagnostic(code(nu::parser::shell_err))]
ShellErrRedirect(#[label("use 'err>' instead of '2>' in Nushell")] Span),
#[error("The '2>&1' shell operation is 'out+err>' in Nushell.")]
#[diagnostic(
code(nu::parser::shell_outerr),
help("Nushell redirection will write all of stdout before stderr.")
)]
ShellOutErrRedirect(#[label("use 'out+err>' instead of '2>&1' in Nushell")] Span),
#[error("Multiple redirections provided for {0}.")]
#[diagnostic(code(nu::parser::multiple_redirections))]
MultipleRedirections(
RedirectionSource,
#[label = "first redirection"] Span,
#[label = "second redirection"] Span,
),
#[error("Unexpected redirection.")]
#[diagnostic(code(nu::parser::unexpected_redirection))]
UnexpectedRedirection {
#[label = "redirecting nothing"]
span: Span,
},
/// One or more of the values have types not supported by the operator.
#[error("The '{op}' operator does not work on values of type '{unsupported}'.")]
#[diagnostic(code(nu::parser::operator_unsupported_type))]
OperatorUnsupportedType {
op: &'static str,
unsupported: Type,
#[label = "does not support '{unsupported}'"]
op_span: Span,
#[label("{unsupported}")]
unsupported_span: Span,
#[help]
help: Option<&'static str>,
},
/// The operator supports the types of both values, but not the specific combination of their types.
#[error("Types '{lhs}' and '{rhs}' are not compatible for the '{op}' operator.")]
#[diagnostic(code(nu::parser::operator_incompatible_types))]
OperatorIncompatibleTypes {
op: &'static str,
lhs: Type,
rhs: Type,
#[label = "does not operate between '{lhs}' and '{rhs}'"]
op_span: Span,
#[label("{lhs}")]
lhs_span: Span,
#[label("{rhs}")]
rhs_span: Span,
#[help]
help: Option<&'static str>,
},
#[error("Capture of mutable variable.")]
#[diagnostic(code(nu::parser::expected_keyword))]
CaptureOfMutableVar(#[label("capture of mutable variable")] Span),
#[error("Expected keyword.")]
#[diagnostic(code(nu::parser::expected_keyword))]
ExpectedKeyword(String, #[label("expected {0}")] Span),
#[error("Unexpected keyword.")]
#[diagnostic(
code(nu::parser::unexpected_keyword),
help("'{0}' keyword is allowed only in a module.")
)]
UnexpectedKeyword(String, #[label("unexpected {0}")] Span),
#[error("Can't create alias to parser keyword.")]
#[diagnostic(
code(nu::parser::cant_alias_keyword),
help("Only the following keywords can be aliased: {0}.")
)]
CantAliasKeyword(String, #[label("not supported in alias")] Span),
#[error("Can't create alias to expression.")]
#[diagnostic(
code(nu::parser::cant_alias_expression),
help("Only command calls can be aliased.")
)]
CantAliasExpression(String, #[label("aliasing {0} is not supported")] Span),
#[error("Unknown operator")]
#[diagnostic(code(nu::parser::unknown_operator), help("{1}"))]
UnknownOperator(
&'static str,
&'static str,
#[label("Operator '{0}' not supported")] Span,
),
#[error("Statement used in pipeline.")]
#[diagnostic(
code(nu::parser::unexpected_keyword),
help(
"'{0}' keyword is not allowed in pipeline. Use '{0}' by itself, outside of a pipeline."
)
)]
BuiltinCommandInPipeline(String, #[label("not allowed in pipeline")] Span),
#[error("{0} statement used in pipeline.")]
#[diagnostic(
code(nu::parser::unexpected_keyword),
help(
"Assigning '{1}' to '{2}' does not produce a value to be piped. If the pipeline result is meant to be assigned to '{2}', use '{0} {2} = ({1} | ...)'."
)
)]
AssignInPipeline(String, String, String, #[label("'{0}' in pipeline")] Span),
#[error("`{0}` used as variable name.")]
#[diagnostic(
code(nu::parser::name_is_builtin_var),
help(
"'{0}' is the name of a builtin Nushell variable and cannot be used as a variable name"
)
)]
NameIsBuiltinVar(String, #[label("already a builtin variable")] Span),
#[error("Incorrect value")]
#[diagnostic(code(nu::parser::incorrect_value), help("{2}"))]
IncorrectValue(String, #[label("unexpected {0}")] Span, String),
#[error("Invalid binary string.")]
#[diagnostic(code(nu::parser::invalid_binary_string), help("{1}"))]
InvalidBinaryString(#[label("invalid binary string")] Span, String),
#[error("Multiple rest params.")]
#[diagnostic(code(nu::parser::multiple_rest_params))]
MultipleRestParams(#[label = "multiple rest params"] Span),
#[error("Variable not found.")]
#[diagnostic(code(nu::parser::variable_not_found))]
VariableNotFound(DidYouMean, #[label = "variable not found. {0}"] Span),
#[error("Use $env.{0} instead of ${0}.")]
#[diagnostic(code(nu::parser::env_var_not_var))]
EnvVarNotVar(String, #[label = "use $env.{0} instead of ${0}"] Span),
#[error("Variable name not supported.")]
#[diagnostic(code(nu::parser::variable_not_valid))]
VariableNotValid(#[label = "variable name can't contain spaces or quotes"] Span),
#[error("Alias name not supported.")]
#[diagnostic(code(nu::parser::variable_not_valid))]
AliasNotValid(
#[label = "alias name can't be a number, a filesize, or contain a hash # or caret ^"] Span,
),
#[error("Command name not supported.")]
#[diagnostic(code(nu::parser::variable_not_valid))]
CommandDefNotValid(
#[label = "command name can't be a number, a filesize, or contain a hash # or caret ^"]
Span,
),
#[error("Module not found.")]
#[diagnostic(
code(nu::parser::module_not_found),
help(
"module files and their paths must be available before your script is run as parsing occurs before anything is evaluated"
)
)]
ModuleNotFound(#[label = "module {1} not found"] Span, String),
#[error("Missing mod.nu file.")]
#[diagnostic(
code(nu::parser::module_missing_mod_nu_file),
help(
"Directory {0} is missing a mod.nu file.\n\nWhen importing a directory as a Nushell module, it needs to contain a mod.nu file (can be empty). Alternatively, you can use .nu files in the directory as modules individually."
)
)]
ModuleMissingModNuFile(
String,
#[label = "module directory is missing a mod.nu file"] Span,
),
#[error("Circular import.")]
#[diagnostic(code(nu::parser::circular_import), help("{0}"))]
CircularImport(String, #[label = "detected circular import"] Span),
#[error("Can't export {0} named same as the module.")]
#[diagnostic(
code(nu::parser::named_as_module),
help(
"Module {1} can't export {0} named the same as the module. Either change the module name, or export `{2}` {0}."
)
)]
NamedAsModule(
String,
String,
String,
#[label = "can't export from module {1}"] Span,
),
#[error("Module already contains 'main' command.")]
#[diagnostic(
code(nu::parser::module_double_main),
help("Tried to add 'main' command to module '{0}' but it has already been added.")
)]
ModuleDoubleMain(
String,
#[label = "module '{0}' already contains 'main'"] Span,
),
#[error("Can't export alias defined as 'main'.")]
#[diagnostic(
code(nu::parser::export_main_alias_not_allowed),
help(
"Exporting aliases as 'main' is not allowed. Either rename the alias or convert it to a custom command."
)
)]
ExportMainAliasNotAllowed(#[label = "can't export from module"] Span),
#[error("Active overlay not found.")]
#[diagnostic(code(nu::parser::active_overlay_not_found))]
ActiveOverlayNotFound(#[label = "not an active overlay"] Span),
#[error("Overlay prefix mismatch.")]
#[diagnostic(
code(nu::parser::overlay_prefix_mismatch),
help(
"Overlay {0} already exists {1} a prefix. To add it again, do it {1} the --prefix flag."
)
)]
OverlayPrefixMismatch(
String,
String,
#[label = "already exists {1} a prefix"] Span,
),
#[error("Module or overlay not found.")]
#[diagnostic(
code(nu::parser::module_or_overlay_not_found),
help(
"Requires either an existing overlay, a module, or an import pattern defining a module."
)
)]
ModuleOrOverlayNotFound(#[label = "not a module or an overlay"] Span),
#[error("Cannot remove the last overlay.")]
#[diagnostic(
code(nu::parser::cant_remove_last_overlay),
help("At least one overlay must always be active.")
)]
CantRemoveLastOverlay(#[label = "this is the last overlay, can't remove it"] Span),
#[error("Cannot hide default overlay.")]
#[diagnostic(
code(nu::parser::cant_hide_default_overlay),
help("'{0}' is a default overlay. Default overlays cannot be hidden.")
)]
CantHideDefaultOverlay(String, #[label = "can't hide overlay"] Span),
#[error("Cannot add overlay.")]
#[diagnostic(code(nu::parser::cant_add_overlay_help), help("{0}"))]
CantAddOverlayHelp(String, #[label = "cannot add this overlay"] Span),
#[error("Duplicate command definition within a block.")]
#[diagnostic(code(nu::parser::duplicate_command_def))]
DuplicateCommandDef(#[label = "defined more than once"] Span),
#[error("Unknown command.")]
#[diagnostic(
code(nu::parser::unknown_command),
// TODO: actual suggestions like "Did you mean `foo`?"
)]
UnknownCommand(#[label = "unknown command"] Span),
#[error("Non-UTF8 string.")]
#[diagnostic(code(nu::parser::non_utf8))]
NonUtf8(#[label = "non-UTF8 string"] Span),
#[error("The `{0}` command doesn't have flag `{1}`.")]
#[diagnostic(code(nu::parser::unknown_flag), help("{3}"))]
UnknownFlag(String, String, #[label = "unknown flag"] Span, String),
#[error("Unknown type.")]
#[diagnostic(code(nu::parser::unknown_type))]
UnknownType(#[label = "unknown type"] Span),
#[error("Missing flag argument.")]
#[diagnostic(code(nu::parser::missing_flag_param))]
MissingFlagParam(String, #[label = "flag missing {0} argument"] Span),
#[error("Only the last flag in a short flag batch can take an argument.")]
#[diagnostic(code(nu::parser::only_last_flag_in_batch_can_take_arg))]
OnlyLastFlagInBatchCanTakeArg(#[label = "only the last flag can take args"] Span),
#[error("Missing required positional argument.")]
#[diagnostic(
code(nu::parser::missing_positional),
help("Usage: {2}. Use `--help` for more information.")
)]
MissingPositional(String, #[label("missing {0}")] Span, String),
#[error("Missing argument to `{1}`.")]
#[diagnostic(code(nu::parser::keyword_missing_arg))]
KeywordMissingArgument(
String,
String,
#[label("missing {0} value that follows {1}")] Span,
),
#[error("Missing type.")]
#[diagnostic(code(nu::parser::missing_type))]
MissingType(#[label = "expected type"] Span),
#[error("Type mismatch.")]
#[diagnostic(code(nu::parser::type_mismatch))]
TypeMismatch(Type, Type, #[label("expected {0}, found {1}")] Span), // expected, found, span
#[error("Type mismatch.")]
#[diagnostic(code(nu::parser::type_mismatch_help), help("{3}"))]
TypeMismatchHelp(Type, Type, #[label("expected {0}, found {1}")] Span, String), // expected, found, span, help
#[error("Missing required flag.")]
#[diagnostic(code(nu::parser::missing_required_flag))]
MissingRequiredFlag(String, #[label("missing required flag {0}")] Span),
#[error("Incomplete math expression.")]
#[diagnostic(code(nu::parser::incomplete_math_expression))]
IncompleteMathExpression(#[label = "incomplete math expression"] Span),
#[error("Unknown state.")]
#[diagnostic(code(nu::parser::unknown_state))]
UnknownState(String, #[label("{0}")] Span),
#[error("Internal error.")]
#[diagnostic(code(nu::parser::unknown_state))]
InternalError(String, #[label("{0}")] Span),
#[error("Parser incomplete.")]
#[diagnostic(code(nu::parser::parser_incomplete))]
IncompleteParser(#[label = "parser support missing for this expression"] Span),
#[error("Rest parameter needs a name.")]
#[diagnostic(code(nu::parser::rest_needs_name))]
RestNeedsName(#[label = "needs a parameter name"] Span),
#[error("Parameter not correct type.")]
#[diagnostic(code(nu::parser::parameter_mismatch_type))]
ParameterMismatchType(
String,
String,
String,
#[label = "parameter {0} needs to be '{1}' instead of '{2}'"] Span,
),
#[error("Default values should be constant expressions.")]
#[diagnostic(code(nu::parser::non_constant_default_value))]
NonConstantDefaultValue(#[label = "expected a constant value"] Span),
#[error("Extra columns.")]
#[diagnostic(code(nu::parser::extra_columns))]
ExtraColumns(
usize,
#[label("expected {0} column{}", if *.0 == 1 { "" } else { "s" })] Span,
),
#[error("Missing columns.")]
#[diagnostic(code(nu::parser::missing_columns))]
MissingColumns(
usize,
#[label("expected {0} column{}", if *.0 == 1 { "" } else { "s" })] Span,
),
#[error("{0}")]
#[diagnostic(code(nu::parser::assignment_mismatch))]
AssignmentMismatch(String, String, #[label("{1}")] Span),
#[error("Wrong import pattern structure.")]
#[diagnostic(code(nu::parser::wrong_import_pattern))]
WrongImportPattern(String, #[label = "{0}"] Span),
#[error("Export not found.")]
#[diagnostic(code(nu::parser::export_not_found))]
ExportNotFound(#[label = "could not find imports"] Span),
#[error("File not found")]
#[diagnostic(
code(nu::parser::sourced_file_not_found),
help("sourced files need to be available before your script is run")
)]
SourcedFileNotFound(String, #[label("File not found: {0}")] Span),
#[error("File not found")]
#[diagnostic(
code(nu::parser::registered_file_not_found),
help("registered files need to be available before your script is run")
)]
RegisteredFileNotFound(String, #[label("File not found: {0}")] Span),
#[error("File not found")]
#[diagnostic(code(nu::parser::file_not_found))]
FileNotFound(String, #[label("File not found: {0}")] Span),
#[error("Plugin not found")]
#[diagnostic(
code(nu::parser::plugin_not_found),
help(
"plugins need to be added to the plugin registry file before your script is run (see `plugin add`)"
)
)]
PluginNotFound {
name: String,
#[label("Plugin not found: {name}")]
name_span: Span,
#[label("in this registry file")]
plugin_config_span: Option<Span>,
},
#[error("Invalid literal")] // <problem> in <entity>.
#[diagnostic()]
InvalidLiteral(String, String, #[label("{0} in {1}")] Span),
#[error("{0}")]
#[diagnostic()]
LabeledError(String, String, #[label("{1}")] Span),
#[error("{error}")]
#[diagnostic(help("{help}"))]
LabeledErrorWithHelp {
error: String,
label: String,
help: String,
#[label("{label}")]
span: Span,
},
#[error("Redirection can not be used with {0}.")]
#[diagnostic()]
RedirectingBuiltinCommand(
&'static str,
#[label("not allowed here")] Span,
#[label("...and here")] Option<Span>,
),
#[error("This command does not have a ...rest parameter")]
#[diagnostic(
code(nu::parser::unexpected_spread_arg),
help(
"To spread arguments, the command needs to define a multi-positional parameter in its signature, such as ...rest"
)
)]
UnexpectedSpreadArg(String, #[label = "unexpected spread argument"] Span),
/// Invalid assignment left-hand side
///
/// ## Resolution
///
/// Assignment requires that you assign to a mutable variable or cell path.
#[error("Assignment to an immutable variable.")]
#[diagnostic(
code(nu::parser::assignment_requires_mutable_variable),
help("declare the variable with `mut`, or shadow it again with `let`")
)]
AssignmentRequiresMutableVar(#[label("needs to be a mutable variable")] Span),
/// Invalid assignment left-hand side
///
/// ## Resolution
///
/// Assignment requires that you assign to a variable or variable cell path.
#[error("Assignment operations require a variable.")]
#[diagnostic(
code(nu::parser::assignment_requires_variable),
help("try assigning to a variable or a cell path of a variable")
)]
AssignmentRequiresVar(#[label("needs to be a variable")] Span),
#[error("Attributes must be followed by a definition.")]
#[diagnostic(
code(nu::parser::attribute_requires_definition),
help("try following this line with a `def` or `extern` definition")
)]
AttributeRequiresDefinition(#[label("must be followed by a definition")] Span),
}
impl ParseError {
pub fn span(&self) -> Span {
match self {
ParseError::ExtraTokens(s) => *s,
ParseError::ExtraPositional(_, s) => *s,
ParseError::UnexpectedEof(_, s) => *s,
ParseError::Unclosed(_, s) => *s,
ParseError::Unbalanced(_, _, s) => *s,
ParseError::Expected(_, s) => *s,
ParseError::ExpectedWithStringMsg(_, s) => *s,
ParseError::ExpectedWithDidYouMean(_, _, s) => *s,
ParseError::Mismatch(_, _, s) => *s,
ParseError::OperatorUnsupportedType { op_span, .. } => *op_span,
ParseError::OperatorIncompatibleTypes { op_span, .. } => *op_span,
ParseError::ExpectedKeyword(_, s) => *s,
ParseError::UnexpectedKeyword(_, s) => *s,
ParseError::CantAliasKeyword(_, s) => *s,
ParseError::CantAliasExpression(_, s) => *s,
ParseError::BuiltinCommandInPipeline(_, s) => *s,
ParseError::AssignInPipeline(_, _, _, s) => *s,
ParseError::NameIsBuiltinVar(_, s) => *s,
ParseError::CaptureOfMutableVar(s) => *s,
ParseError::IncorrectValue(_, s, _) => *s,
ParseError::InvalidBinaryString(s, _) => *s,
ParseError::MultipleRestParams(s) => *s,
ParseError::VariableNotFound(_, s) => *s,
ParseError::EnvVarNotVar(_, s) => *s,
ParseError::VariableNotValid(s) => *s,
ParseError::AliasNotValid(s) => *s,
ParseError::CommandDefNotValid(s) => *s,
ParseError::ModuleNotFound(s, _) => *s,
ParseError::ModuleMissingModNuFile(_, s) => *s,
ParseError::NamedAsModule(_, _, _, s) => *s,
ParseError::ModuleDoubleMain(_, s) => *s,
ParseError::ExportMainAliasNotAllowed(s) => *s,
ParseError::CircularImport(_, s) => *s,
ParseError::ModuleOrOverlayNotFound(s) => *s,
ParseError::ActiveOverlayNotFound(s) => *s,
ParseError::OverlayPrefixMismatch(_, _, s) => *s,
ParseError::CantRemoveLastOverlay(s) => *s,
ParseError::CantHideDefaultOverlay(_, s) => *s,
ParseError::CantAddOverlayHelp(_, s) => *s,
ParseError::DuplicateCommandDef(s) => *s,
ParseError::UnknownCommand(s) => *s,
ParseError::NonUtf8(s) => *s,
ParseError::UnknownFlag(_, _, s, _) => *s,
ParseError::RequiredAfterOptional(_, s) => *s,
ParseError::UnknownType(s) => *s,
ParseError::MissingFlagParam(_, s) => *s,
ParseError::OnlyLastFlagInBatchCanTakeArg(s) => *s,
ParseError::MissingPositional(_, s, _) => *s,
ParseError::KeywordMissingArgument(_, _, s) => *s,
ParseError::MissingType(s) => *s,
ParseError::TypeMismatch(_, _, s) => *s,
ParseError::TypeMismatchHelp(_, _, s, _) => *s,
ParseError::InputMismatch(_, s) => *s,
ParseError::OutputMismatch(_, _, s) => *s,
ParseError::MissingRequiredFlag(_, s) => *s,
ParseError::IncompleteMathExpression(s) => *s,
ParseError::UnknownState(_, s) => *s,
ParseError::InternalError(_, s) => *s,
ParseError::IncompleteParser(s) => *s,
ParseError::RestNeedsName(s) => *s,
ParseError::ParameterMismatchType(_, _, _, s) => *s,
ParseError::NonConstantDefaultValue(s) => *s,
ParseError::ExtraColumns(_, s) => *s,
ParseError::MissingColumns(_, s) => *s,
ParseError::AssignmentMismatch(_, _, s) => *s,
ParseError::WrongImportPattern(_, s) => *s,
ParseError::ExportNotFound(s) => *s,
ParseError::SourcedFileNotFound(_, s) => *s,
ParseError::RegisteredFileNotFound(_, s) => *s,
ParseError::FileNotFound(_, s) => *s,
ParseError::PluginNotFound { name_span, .. } => *name_span,
ParseError::LabeledError(_, _, s) => *s,
ParseError::ShellAndAnd(s) => *s,
ParseError::ShellOrOr(s) => *s,
ParseError::ShellErrRedirect(s) => *s,
ParseError::ShellOutErrRedirect(s) => *s,
ParseError::MultipleRedirections(_, _, s) => *s,
ParseError::UnexpectedRedirection { span } => *span,
ParseError::UnknownOperator(_, _, s) => *s,
ParseError::InvalidLiteral(_, _, s) => *s,
ParseError::LabeledErrorWithHelp { span: s, .. } => *s,
ParseError::RedirectingBuiltinCommand(_, s, _) => *s,
ParseError::UnexpectedSpreadArg(_, s) => *s,
ParseError::ExtraTokensAfterClosingDelimiter(s) => *s,
ParseError::AssignmentRequiresVar(s) => *s,
ParseError::AssignmentRequiresMutableVar(s) => *s,
ParseError::AttributeRequiresDefinition(s) => *s,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DidYouMean(Option<String>);
fn did_you_mean_impl(possibilities_bytes: &[&[u8]], input_bytes: &[u8]) -> Option<String> {
let input = from_utf8(input_bytes).ok()?;
let possibilities = possibilities_bytes
.iter()
.map(|p| from_utf8(p))
.collect::<Result<Vec<&str>, Utf8Error>>()
.ok()?;
did_you_mean(&possibilities, input)
}
impl DidYouMean {
pub fn new(possibilities_bytes: &[&[u8]], input_bytes: &[u8]) -> DidYouMean {
DidYouMean(did_you_mean_impl(possibilities_bytes, input_bytes))
}
}
impl From<Option<String>> for DidYouMean {
fn from(value: Option<String>) -> Self {
Self(value)
}
}
impl Display for DidYouMean {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(suggestion) = &self.0 {
write!(f, "Did you mean '{suggestion}'?")
} else {
write!(f, "")
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/shell_error/io.rs | crates/nu-protocol/src/errors/shell_error/io.rs | #[cfg(doc)] // allow mentioning this in doc comments
use super::ShellError;
use miette::{Diagnostic, LabeledSpan, SourceSpan};
use std::{
error::Error as StdError,
fmt::{self, Display, Formatter},
path::{Path, PathBuf},
};
use thiserror::Error;
use crate::Span;
use super::location::Location;
/// Alias for a `Result` with the error type [`ErrorKind`] by default.
///
/// This may be used in all situations that would usually return an [`std::io::Error`] but are
/// already part of the [`nu_protocol`](crate) crate and can therefore interact with
/// [`shell_error::io`](self) directly.
///
/// To make programming inside this module easier, you can pass the `E` type with another error.
/// This avoids the annoyance of having a shadowed `Result`.
pub type Result<T, E = ErrorKind> = std::result::Result<T, E>;
/// Represents an I/O error in the [`ShellError::Io`] variant.
///
/// This is the central I/O error for the [`ShellError::Io`] variant.
/// It represents all I/O errors by encapsulating [`ErrorKind`], an extension of
/// [`std::io::ErrorKind`].
/// The `span` indicates where the error occurred in user-provided code.
/// If the error is not tied to user-provided code, the `location` refers to the precise point in
/// the Rust code where the error originated.
/// The optional `path` provides the file or directory involved in the error.
/// If [`ErrorKind`] alone doesn't provide enough detail, additional context can be added to clarify
/// the issue.
///
/// For handling user input errors (e.g., commands), prefer using [`new`](Self::new).
/// Alternatively, use the [`factory`](Self::factory) method to simplify error creation in repeated
/// contexts.
/// For internal errors, use [`new_internal`](Self::new_internal) to include the location in Rust
/// code where the error originated.
///
/// # Examples
///
/// ## User Input Error
/// ```rust
/// # use nu_protocol::shell_error::io::{IoError, ErrorKind};
/// # use nu_protocol::Span;
/// use std::path::PathBuf;
///
/// # let span = Span::test_data();
/// let path = PathBuf::from("/some/missing/file");
/// let error = IoError::new(ErrorKind::FileNotFound, span, path);
/// println!("Error: {:?}", error);
/// ```
///
/// ## Internal Error
/// ```rust
/// # use nu_protocol::shell_error::io::{IoError, ErrorKind};
// #
/// let error = IoError::new_internal(
/// ErrorKind::from_std(std::io::ErrorKind::UnexpectedEof),
/// "Failed to read data from buffer",
/// nu_protocol::location!()
/// );
/// println!("Error: {:?}", error);
/// ```
///
/// ## Using the Factory Method
/// ```rust
/// # use nu_protocol::shell_error::io::{IoError, ErrorKind};
/// # use nu_protocol::{Span, ShellError};
/// use std::path::PathBuf;
///
/// # fn should_return_err() -> Result<(), ShellError> {
/// # let span = Span::new(50, 60);
/// let path = PathBuf::from("/some/file");
/// let from_io_error = IoError::factory(span, Some(path.as_path()));
///
/// let content = std::fs::read_to_string(&path).map_err(from_io_error)?;
/// # Ok(())
/// # }
/// #
/// # assert!(should_return_err().is_err());
/// ```
///
/// # ShellErrorBridge
///
/// The [`ShellErrorBridge`](super::bridge::ShellErrorBridge) struct is used to contain a
/// [`ShellError`] inside a [`std::io::Error`].
/// This allows seamless transfer of `ShellError` instances where `std::io::Error` is expected.
/// When a `ShellError` needs to be packed into an I/O context, use this bridge.
/// Similarly, when handling an I/O error that is expected to contain a `ShellError`,
/// use the bridge to unpack it.
///
/// This approach ensures clarity about where such container transfers occur.
/// All other I/O errors should be handled using the provided constructors for `IoError`.
/// This way, the code explicitly indicates when and where a `ShellError` transfer might happen.
#[derive(Debug, Eq, Clone, PartialEq)]
#[non_exhaustive]
pub struct IoError {
/// The type of the underlying I/O error.
///
/// [`std::io::ErrorKind`] provides detailed context about the type of I/O error that occurred
/// and is part of [`std::io::Error`].
/// If a kind cannot be represented by it, consider adding a new variant to [`ErrorKind`].
///
/// Only in very rare cases should [`std::io::Error::other()`] be used, make sure you provide
/// `additional_context` to get useful errors in these cases.
pub kind: ErrorKind,
/// The source location of the error.
pub span: Span,
/// The path related to the I/O error, if applicable.
///
/// Many I/O errors involve a file or directory path, but operating system error messages
/// often don't include the specific path.
/// Setting this to [`Some`] allows users to see which path caused the error.
pub path: Option<PathBuf>,
/// Additional details to provide more context about the error.
///
/// Only set this field if it adds meaningful context.
/// If [`ErrorKind`] already contains all the necessary information, leave this as [`None`].
pub additional_context: Option<AdditionalContext>,
/// The precise location in the Rust code where the error originated.
///
/// This field is particularly useful for debugging errors that stem from the Rust
/// implementation rather than user-provided Nushell code.
/// The original [`Location`] is converted to a string to more easily report the error
/// attributing the location.
///
/// This value is only used if `span` is [`Span::unknown()`] as most of the time we want to
/// refer to user code than the Rust code.
pub location: Option<String>,
}
/// Prevents other crates from constructing certain enum variants directly.
///
/// This type is only used to block construction while still allowing pattern matching.
/// It's not meant to be used for anything else.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Sealed;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Diagnostic)]
pub enum ErrorKind {
/// [`std::io::ErrorKind`] from the standard library.
///
/// This variant wraps a standard library error kind and extends our own error enum with it.
/// The hidden field prevents other crates, even our own, from constructing this directly.
/// Most of the time, you already have a full [`std::io::Error`], so just pass that directly to
/// [`IoError::new`] or [`IoError::new_with_additional_context`].
/// This allows us to inspect the raw os error of `std::io::Error`s.
///
/// Matching is still easy:
///
/// ```rust
/// # use nu_protocol::shell_error::io::ErrorKind;
/// #
/// # let err_kind = ErrorKind::from_std(std::io::ErrorKind::NotFound);
/// match err_kind {
/// ErrorKind::Std(std::io::ErrorKind::NotFound, ..) => { /* ... */ }
/// _ => {}
/// }
/// ```
///
/// If you want to provide an [`std::io::ErrorKind`] manually, use [`ErrorKind::from_std`].
#[allow(private_interfaces)]
Std(std::io::ErrorKind, Sealed),
/// Killing a job process failed.
///
/// This error is part [`ShellError::Io`](super::ShellError::Io) instead of
/// [`ShellError::Job`](super::ShellError::Job) as this error occurs because some I/O operation
/// failed on the OS side.
/// And not part of our logic.
KillJobProcess,
NotAFile,
/// The file or directory is in use by another program.
///
/// On Windows, this maps to
/// [`ERROR_SHARING_VIOLATION`](::windows::Win32::Foundation::ERROR_SHARING_VIOLATION) and
/// prevents access like deletion or modification.
#[cfg_attr(not(windows), allow(rustdoc::broken_intra_doc_links))]
AlreadyInUse,
// use these variants in cases where we know precisely whether a file or directory was expected
FileNotFound,
DirectoryNotFound,
}
impl ErrorKind {
/// Construct an [`ErrorKind`] from a [`std::io::ErrorKind`] without a full [`std::io::Error`].
///
/// In most cases, you should use [`IoError::new`] and pass the full [`std::io::Error`] instead.
/// This method is only meant for cases where we provide our own io error kinds.
pub fn from_std(kind: std::io::ErrorKind) -> Self {
Self::Std(kind, Sealed)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error, Diagnostic)]
#[error("{0}")]
pub struct AdditionalContext(String);
impl From<String> for AdditionalContext {
fn from(value: String) -> Self {
AdditionalContext(value)
}
}
impl IoError {
/// Creates a new [`IoError`] with the given kind, span, and optional path.
///
/// This constructor should be used in all cases where the combination of the error kind, span,
/// and path provides enough information to describe the error clearly.
/// For example, errors like "File not found" or "Permission denied" are typically
/// self-explanatory when paired with the file path and the location in user-provided
/// Nushell code (`span`).
///
/// # Constraints
/// If `span` is unknown, use:
/// - `new_internal` if no path is available.
/// - `new_internal_with_path` if a path is available.
pub fn new(kind: impl Into<ErrorKind>, span: Span, path: impl Into<Option<PathBuf>>) -> Self {
let path = path.into();
if span == Span::unknown() {
debug_assert!(
path.is_some(),
"for unknown spans with paths, use `new_internal_with_path`"
);
debug_assert!(
path.is_none(),
"for unknown spans without paths, use `new_internal`"
);
}
Self {
kind: kind.into(),
span,
path,
additional_context: None,
location: None,
}
}
/// Creates a new [`IoError`] with additional context.
///
/// Use this constructor when the error kind, span, and path are not sufficient to fully
/// explain the error, and additional context can provide meaningful details.
/// Avoid redundant context (e.g., "Permission denied" for an error kind of
/// [`ErrorKind::PermissionDenied`](std::io::ErrorKind::PermissionDenied)).
///
/// # Constraints
/// If `span` is unknown, use:
/// - `new_internal` if no path is available.
/// - `new_internal_with_path` if a path is available.
pub fn new_with_additional_context(
kind: impl Into<ErrorKind>,
span: Span,
path: impl Into<Option<PathBuf>>,
additional_context: impl ToString,
) -> Self {
let path = path.into();
if span == Span::unknown() {
debug_assert!(
path.is_some(),
"for unknown spans with paths, use `new_internal_with_path`"
);
debug_assert!(
path.is_none(),
"for unknown spans without paths, use `new_internal`"
);
}
Self {
kind: kind.into(),
span,
path,
additional_context: Some(additional_context.to_string().into()),
location: None,
}
}
/// Creates a new [`IoError`] for internal I/O errors without a user-provided span or path.
///
/// This constructor is intended for internal errors in the Rust implementation that still need
/// to be reported to the end user.
/// Since these errors are not tied to user-provided Nushell code, they generally have no
/// meaningful span or path.
///
/// Instead, these errors provide:
/// - `additional_context`:
/// Details about what went wrong internally.
/// - `location`:
/// The location in the Rust code where the error occurred, allowing us to trace and debug
/// the issue.
/// Use the [`nu_protocol::location!`](crate::location) macro to generate the location
/// information.
///
/// # Examples
/// ```rust
/// use nu_protocol::shell_error::{self, io::IoError};
///
/// let error = IoError::new_internal(
/// shell_error::io::ErrorKind::from_std(std::io::ErrorKind::UnexpectedEof),
/// "Failed to read from buffer",
/// nu_protocol::location!(),
/// );
/// ```
pub fn new_internal(
kind: impl Into<ErrorKind>,
additional_context: impl ToString,
location: Location,
) -> Self {
Self {
kind: kind.into(),
span: Span::unknown(),
path: None,
additional_context: Some(additional_context.to_string().into()),
location: Some(location.to_string()),
}
}
/// Creates a new `IoError` for internal I/O errors with a specific path.
///
/// This constructor is similar to [`new_internal`](Self::new_internal) but also includes a
/// file or directory path relevant to the error.
/// Use this function in rare cases where an internal error involves a specific path, and the
/// combination of path and additional context is helpful.
///
/// # Examples
/// ```rust
/// use nu_protocol::shell_error::{self, io::IoError};
/// use std::path::PathBuf;
///
/// let error = IoError::new_internal_with_path(
/// shell_error::io::ErrorKind::FileNotFound,
/// "Could not find special file",
/// nu_protocol::location!(),
/// PathBuf::from("/some/file"),
/// );
/// ```
pub fn new_internal_with_path(
kind: impl Into<ErrorKind>,
additional_context: impl ToString,
location: Location,
path: PathBuf,
) -> Self {
Self {
kind: kind.into(),
span: Span::unknown(),
path: path.into(),
additional_context: Some(additional_context.to_string().into()),
location: Some(location.to_string()),
}
}
/// Creates a factory closure for constructing [`IoError`] instances from [`std::io::Error`] values.
///
/// This method is particularly useful when you need to handle multiple I/O errors which all
/// take the same span and path.
/// Instead of calling `.map_err(|err| IoError::new(err, span, path))` every time, you
/// can create the factory closure once and pass that into `.map_err`.
pub fn factory<'p, P>(span: Span, path: P) -> impl Fn(std::io::Error) -> Self + use<'p, P>
where
P: Into<Option<&'p Path>>,
{
let path = path.into();
move |err: std::io::Error| IoError::new(err, span, path.map(PathBuf::from))
}
}
impl From<std::io::Error> for ErrorKind {
fn from(err: std::io::Error) -> Self {
(&err).into()
}
}
impl From<&std::io::Error> for ErrorKind {
fn from(err: &std::io::Error) -> Self {
#[cfg(windows)]
if let Some(raw_os_error) = err.raw_os_error() {
use windows::Win32::Foundation;
#[allow(clippy::single_match, reason = "in the future we can expand here")]
match Foundation::WIN32_ERROR(raw_os_error as u32) {
Foundation::ERROR_SHARING_VIOLATION => return ErrorKind::AlreadyInUse,
_ => {}
}
}
#[cfg(debug_assertions)]
if err.kind() == std::io::ErrorKind::Other {
panic!(
"\
suspicious conversion:
tried to convert `std::io::Error` with `std::io::ErrorKind::Other`
into `nu_protocol::shell_error::io::ErrorKind`
I/O errors should always be specific, provide more context
{err:#?}\
"
)
}
ErrorKind::Std(err.kind(), Sealed)
}
}
impl From<nu_system::KillByPidError> for ErrorKind {
fn from(value: nu_system::KillByPidError) -> Self {
match value {
nu_system::KillByPidError::Output(error) => error.into(),
nu_system::KillByPidError::KillProcess => ErrorKind::KillJobProcess,
}
}
}
impl StdError for IoError {}
impl Display for IoError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self.kind {
ErrorKind::Std(std::io::ErrorKind::NotFound, _) => write!(f, "Not found"),
ErrorKind::FileNotFound => write!(f, "File not found"),
ErrorKind::DirectoryNotFound => write!(f, "Directory not found"),
_ => write!(f, "I/O error"),
}
}
}
impl Display for ErrorKind {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
ErrorKind::Std(std::io::ErrorKind::NotFound, _) => write!(f, "Not found"),
ErrorKind::Std(error_kind, _) => {
let msg = error_kind.to_string();
let (first, rest) = msg.split_at(1);
write!(f, "{}{}", first.to_uppercase(), rest)
}
ErrorKind::KillJobProcess => write!(f, "Killing job process failed"),
ErrorKind::NotAFile => write!(f, "Not a file"),
ErrorKind::AlreadyInUse => write!(f, "Already in use"),
ErrorKind::FileNotFound => write!(f, "File not found"),
ErrorKind::DirectoryNotFound => write!(f, "Directory not found"),
}
}
}
impl std::error::Error for ErrorKind {}
impl Diagnostic for IoError {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
let mut code = String::from("nu::shell::io::");
match self.kind {
ErrorKind::Std(error_kind, _) => match error_kind {
std::io::ErrorKind::NotFound => code.push_str("not_found"),
std::io::ErrorKind::PermissionDenied => code.push_str("permission_denied"),
std::io::ErrorKind::ConnectionRefused => code.push_str("connection_refused"),
std::io::ErrorKind::ConnectionReset => code.push_str("connection_reset"),
std::io::ErrorKind::ConnectionAborted => code.push_str("connection_aborted"),
std::io::ErrorKind::NotConnected => code.push_str("not_connected"),
std::io::ErrorKind::AddrInUse => code.push_str("addr_in_use"),
std::io::ErrorKind::AddrNotAvailable => code.push_str("addr_not_available"),
std::io::ErrorKind::BrokenPipe => code.push_str("broken_pipe"),
std::io::ErrorKind::AlreadyExists => code.push_str("already_exists"),
std::io::ErrorKind::WouldBlock => code.push_str("would_block"),
std::io::ErrorKind::InvalidInput => code.push_str("invalid_input"),
std::io::ErrorKind::InvalidData => code.push_str("invalid_data"),
std::io::ErrorKind::TimedOut => code.push_str("timed_out"),
std::io::ErrorKind::WriteZero => code.push_str("write_zero"),
std::io::ErrorKind::Interrupted => code.push_str("interrupted"),
std::io::ErrorKind::Unsupported => code.push_str("unsupported"),
std::io::ErrorKind::UnexpectedEof => code.push_str("unexpected_eof"),
std::io::ErrorKind::OutOfMemory => code.push_str("out_of_memory"),
std::io::ErrorKind::Other => code.push_str("other"),
kind => code.push_str(&kind.to_string().to_lowercase().replace(" ", "_")),
},
ErrorKind::KillJobProcess => code.push_str("kill_job_process"),
ErrorKind::NotAFile => code.push_str("not_a_file"),
ErrorKind::AlreadyInUse => code.push_str("already_in_use"),
ErrorKind::FileNotFound => code.push_str("file_not_found"),
ErrorKind::DirectoryNotFound => code.push_str("directory_not_found"),
}
Some(Box::new(code))
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
let make_msg = |path: &Path| {
let path = format!("'{}'", path.display());
match self.kind {
ErrorKind::NotAFile => format!("{path} is not a file"),
ErrorKind::AlreadyInUse => {
format!("{path} is already being used by another program")
}
ErrorKind::Std(std::io::ErrorKind::NotFound, _)
| ErrorKind::FileNotFound
| ErrorKind::DirectoryNotFound => format!("{path} does not exist"),
_ => format!("The error occurred at {path}"),
}
};
self.path
.as_ref()
.map(|path| make_msg(path))
.map(|s| Box::new(s) as Box<dyn std::fmt::Display>)
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> {
let span_is_unknown = self.span == Span::unknown();
let span = match (span_is_unknown, self.location.as_ref()) {
(true, None) => return None,
(false, _) => SourceSpan::from(self.span),
(true, Some(location)) => SourceSpan::new(0.into(), location.len()),
};
let label = LabeledSpan::new_with_span(Some(self.kind.to_string()), span);
Some(Box::new(std::iter::once(label)))
}
fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
self.additional_context
.as_ref()
.map(|ctx| ctx as &dyn Diagnostic)
}
fn source_code(&self) -> Option<&dyn miette::SourceCode> {
let span_is_unknown = self.span == Span::unknown();
match (span_is_unknown, self.location.as_ref()) {
(true, None) | (false, _) => None,
(true, Some(location)) => Some(location as &dyn miette::SourceCode),
}
}
}
impl From<IoError> for std::io::Error {
fn from(value: IoError) -> Self {
Self::new(value.kind.into(), value)
}
}
impl From<ErrorKind> for std::io::ErrorKind {
fn from(value: ErrorKind) -> Self {
match value {
ErrorKind::Std(error_kind, _) => error_kind,
_ => std::io::ErrorKind::Other,
}
}
}
/// More specific variants of [`NotFound`](std::io::ErrorKind).
///
/// Use these to define how a `NotFound` error maps to our custom [`ErrorKind`].
pub enum NotFound {
/// Map into [`FileNotFound`](ErrorKind::FileNotFound).
File,
/// Map into [`DirectoryNotFound`](ErrorKind::DirectoryNotFound).
Directory,
}
/// Extension trait for working with [`std::io::Error`].
pub trait IoErrorExt {
/// Map [`NotFound`](std::io::ErrorKind) variants into more precise variants.
///
/// The OS doesn't know when an entity was not found whether it was meant to be a file or a
/// directory or something else.
/// But sometimes we, the application, know what we expect and with this method, we can further
/// specify it.
///
/// # Examples
/// Reading a file.
/// If the file isn't found, return [`FileNotFound`](ErrorKind::FileNotFound).
/// ```rust
/// # use nu_protocol::{
/// # shell_error::io::{ErrorKind, IoErrorExt, IoError, NotFound},
/// # ShellError, Span,
/// # };
/// # use std::{fs, path::PathBuf};
/// #
/// # fn example() -> Result<(), ShellError> {
/// # let span = Span::test_data();
/// let a_file = PathBuf::from("scripts/ellie.nu");
/// let ellie = fs::read_to_string(&a_file).map_err(|err| {
/// ShellError::Io(IoError::new(
/// err.not_found_as(NotFound::File),
/// span,
/// a_file,
/// ))
/// })?;
/// # Ok(())
/// # }
/// #
/// # assert!(matches!(
/// # example(),
/// # Err(ShellError::Io(IoError {
/// # kind: ErrorKind::FileNotFound,
/// # ..
/// # }))
/// # ));
/// ```
fn not_found_as(self, kind: NotFound) -> ErrorKind;
}
impl IoErrorExt for ErrorKind {
fn not_found_as(self, kind: NotFound) -> ErrorKind {
match (kind, self) {
(NotFound::File, Self::Std(std::io::ErrorKind::NotFound, _)) => ErrorKind::FileNotFound,
(NotFound::Directory, Self::Std(std::io::ErrorKind::NotFound, _)) => {
ErrorKind::DirectoryNotFound
}
_ => self,
}
}
}
impl IoErrorExt for std::io::Error {
fn not_found_as(self, kind: NotFound) -> ErrorKind {
ErrorKind::from(self).not_found_as(kind)
}
}
impl IoErrorExt for &std::io::Error {
fn not_found_as(self, kind: NotFound) -> ErrorKind {
ErrorKind::from(self).not_found_as(kind)
}
}
#[cfg(test)]
mod assert_not_impl {
use super::*;
/// Assertion that `ErrorKind` does not implement `From<std::io::ErrorKind>`.
///
/// This implementation exists only in tests to make sure that no crate,
/// including ours, accidentally adds a `From<std::io::ErrorKind>` impl for `ErrorKind`.
/// If someone tries, it will fail due to conflicting implementations.
///
/// We want to force usage of [`IoError::new`] with a full [`std::io::Error`] instead of
/// allowing conversion from just an [`std::io::ErrorKind`].
/// That way, we can properly inspect and classify uncategorized I/O errors.
impl From<std::io::ErrorKind> for ErrorKind {
fn from(_: std::io::ErrorKind) -> Self {
unimplemented!("ErrorKind should not implement From<std::io::ErrorKind>")
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/shell_error/network.rs | crates/nu-protocol/src/errors/shell_error/network.rs | use miette::{Diagnostic, LabeledSpan};
use thiserror::Error;
use crate::{ShellError, Span, Spanned};
#[derive(Debug, Clone, PartialEq, Error, Diagnostic)]
pub enum NetworkError {
// Replace ShellError::NetworkFailure with this one
#[error("Network failure")]
#[diagnostic(code(nu::shell::network))]
Generic {
msg: String,
#[label("{msg}")]
span: Span,
},
#[error(transparent)]
#[diagnostic(transparent)]
Dns(DnsError),
// TODO: add more precise network errors to avoid generic ones
}
#[derive(Debug, Clone, PartialEq, Error)]
#[error("DNS Error")]
pub struct DnsError {
pub kind: DnsErrorKind,
pub span: Span,
pub query: Spanned<String>,
}
impl Diagnostic for DnsError {
fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
self.kind.code()
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
Some(Box::new(
[
LabeledSpan::new_with_span(Some("Could not be resolved".into()), self.query.span),
LabeledSpan::new_with_span(Some(self.kind.to_string()), self.span),
]
.into_iter(),
))
}
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
Some(Box::new(format!("While querying \"{}\"", self.query)))
}
}
#[derive(Debug, Clone, PartialEq, Error, Diagnostic)]
pub enum DnsErrorKind {
/// Temporary failure in name resolution.
///
/// May also be returned when the DNS server returns SERVFAIL.
#[error("Temporary failure in name resolution")]
#[diagnostic(code(nu::shell::network::dns::again))]
Again,
/// NAME or SERVICE is unknown.
///
/// May also be returned when the domain does not exist (NXDOMAIN) or
/// exists but has no address records (NODATA).
#[error("Name or service is unknown")]
#[diagnostic(code(nu::shell::network::dns::no_name))]
NoName,
/// The specified network host exists, but has no data defined.
///
/// This is no longer a POSIX standard, however it is still returned by
/// some platforms.
#[error("Host exists but has no address records")]
#[diagnostic(code(nu::shell::network::dns::no_data))]
NoData,
/// Non recoverable failure in name resolution.
#[error("Non recoverable failure in name resolution")]
#[diagnostic(code(nu::shell::network::dns::fail))]
Fail,
}
impl From<DnsError> for ShellError {
fn from(value: DnsError) -> Self {
ShellError::Network(NetworkError::Dns(value))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/shell_error/bridge.rs | crates/nu-protocol/src/errors/shell_error/bridge.rs | use super::ShellError;
use serde::{Deserialize, Serialize};
use thiserror::Error;
/// A bridge for transferring a [`ShellError`] between Nushell or similar processes.
///
/// This newtype encapsulates a [`ShellError`] to facilitate its transfer between Nushell processes
/// or processes with similar behavior.
/// By defining this type, we eliminate ambiguity about what is being transferred and avoid the
/// need to implement [`From<io::Error>`](From) and [`Into<io::Error>`](Into) directly on
/// `ShellError`.
#[derive(Debug, Clone, PartialEq, Error, Serialize, Deserialize)]
#[error("{0}")]
pub struct ShellErrorBridge(pub ShellError);
impl TryFrom<std::io::Error> for ShellErrorBridge {
type Error = std::io::Error;
fn try_from(value: std::io::Error) -> Result<Self, Self::Error> {
let kind = value.kind();
value
.downcast()
.inspect(|_| debug_assert_eq!(kind, std::io::ErrorKind::Other))
}
}
impl From<ShellErrorBridge> for std::io::Error {
fn from(value: ShellErrorBridge) -> Self {
std::io::Error::other(value)
}
}
#[test]
fn test_bridge_io_error_roundtrip() {
let shell_error = ShellError::GenericError {
error: "some error".into(),
msg: "some message".into(),
span: None,
help: None,
inner: vec![],
};
let bridge = ShellErrorBridge(shell_error);
let io_error = std::io::Error::from(bridge.clone());
let bridge_again = ShellErrorBridge::try_from(io_error).unwrap();
assert_eq!(bridge.0, bridge_again.0);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/shell_error/mod.rs | crates/nu-protocol/src/errors/shell_error/mod.rs | use super::chained_error::ChainedError;
use crate::{
ConfigError, FromValue, LabeledError, ParseError, Span, Spanned, Type, Value,
ast::Operator,
engine::{Stack, StateWorkingSet},
format_cli_error, record,
};
use job::JobError;
use miette::{Diagnostic, LabeledSpan, NamedSource};
use serde::{Deserialize, Serialize};
use std::num::NonZeroI32;
use thiserror::Error;
pub mod bridge;
pub mod io;
pub mod job;
pub mod location;
pub mod network;
/// The fundamental error type for the evaluation engine. These cases represent different kinds of errors
/// the evaluator might face, along with helpful spans to label. An error renderer will take this error value
/// and pass it into an error viewer to display to the user.
#[derive(Debug, Clone, Error, Diagnostic, PartialEq)]
pub enum ShellError {
/// One or more of the values have types not supported by the operator.
#[error("The '{op}' operator does not work on values of type '{unsupported}'.")]
#[diagnostic(code(nu::shell::operator_unsupported_type))]
OperatorUnsupportedType {
op: Operator,
unsupported: Type,
#[label = "does not support '{unsupported}'"]
op_span: Span,
#[label("{unsupported}")]
unsupported_span: Span,
#[help]
help: Option<&'static str>,
},
/// The operator supports the types of both values, but not the specific combination of their types.
#[error("Types '{lhs}' and '{rhs}' are not compatible for the '{op}' operator.")]
#[diagnostic(code(nu::shell::operator_incompatible_types))]
OperatorIncompatibleTypes {
op: Operator,
lhs: Type,
rhs: Type,
#[label = "does not operate between '{lhs}' and '{rhs}'"]
op_span: Span,
#[label("{lhs}")]
lhs_span: Span,
#[label("{rhs}")]
rhs_span: Span,
#[help]
help: Option<&'static str>,
},
/// An arithmetic operation's resulting value overflowed its possible size.
///
/// ## Resolution
///
/// Check the inputs to the operation and add guards for their sizes.
/// Integers are generally of size i64, floats are generally f64.
#[error("Operator overflow.")]
#[diagnostic(code(nu::shell::operator_overflow))]
OperatorOverflow {
msg: String,
#[label = "{msg}"]
span: Span,
#[help]
help: Option<String>,
},
/// The pipelined input into a command was not of the expected type. For example, it might
/// expect a string input, but received a table instead.
///
/// ## Resolution
///
/// Check the relevant pipeline and extract or convert values as needed.
#[error("Pipeline mismatch.")]
#[diagnostic(code(nu::shell::pipeline_mismatch))]
PipelineMismatch {
exp_input_type: String,
#[label("expected: {exp_input_type}")]
dst_span: Span,
#[label("value originates here")]
src_span: Span,
},
// TODO: properly unify
/// The pipelined input into a command was not of the expected type. For example, it might
/// expect a string input, but received a table instead.
///
/// (duplicate of [`ShellError::PipelineMismatch`] that reports the observed type)
///
/// ## Resolution
///
/// Check the relevant pipeline and extract or convert values as needed.
#[error("Input type not supported.")]
#[diagnostic(code(nu::shell::only_supports_this_input_type))]
OnlySupportsThisInputType {
exp_input_type: String,
wrong_type: String,
#[label("only {exp_input_type} input data is supported")]
dst_span: Span,
#[label("input type: {wrong_type}")]
src_span: Span,
},
/// No input value was piped into the command.
///
/// ## Resolution
///
/// Only use this command to process values from a previous expression.
#[error("Pipeline empty.")]
#[diagnostic(code(nu::shell::pipeline_mismatch))]
PipelineEmpty {
#[label("no input value was piped in")]
dst_span: Span,
},
// TODO: remove non type error usages
/// A command received an argument of the wrong type.
///
/// ## Resolution
///
/// Convert the argument type before passing it in, or change the command to accept the type.
#[error("Type mismatch.")]
#[diagnostic(code(nu::shell::type_mismatch))]
TypeMismatch {
err_message: String,
#[label = "{err_message}"]
span: Span,
},
/// A value's type did not match the expected type.
///
/// ## Resolution
///
/// Convert the value to the correct type or provide a value of the correct type.
#[error("Type mismatch")]
#[diagnostic(code(nu::shell::type_mismatch))]
RuntimeTypeMismatch {
expected: Type,
actual: Type,
#[label = "expected {expected}, but got {actual}"]
span: Span,
},
/// A value had the correct type but is otherwise invalid.
///
/// ## Resolution
///
/// Ensure the value meets the criteria in the error message.
#[error("Invalid value")]
#[diagnostic(code(nu::shell::invalid_value))]
InvalidValue {
valid: String,
actual: String,
#[label = "expected {valid}, but got {actual}"]
span: Span,
},
/// A command received an argument with correct type but incorrect value.
///
/// ## Resolution
///
/// Correct the argument value before passing it in or change the command.
#[error("Incorrect value.")]
#[diagnostic(code(nu::shell::incorrect_value))]
IncorrectValue {
msg: String,
#[label = "{msg}"]
val_span: Span,
#[label = "encountered here"]
call_span: Span,
},
/// Invalid assignment left-hand side
///
/// ## Resolution
///
/// Assignment requires that you assign to a variable or variable cell path.
#[error("Assignment operations require a variable.")]
#[diagnostic(code(nu::shell::assignment_requires_variable))]
AssignmentRequiresVar {
#[label = "needs to be a variable"]
lhs_span: Span,
},
/// Invalid assignment left-hand side
///
/// ## Resolution
///
/// Assignment requires that you assign to a mutable variable or cell path.
#[error("Assignment to an immutable variable.")]
#[diagnostic(code(nu::shell::assignment_requires_mutable_variable))]
AssignmentRequiresMutableVar {
#[label = "needs to be a mutable variable"]
lhs_span: Span,
},
/// An operator was not recognized during evaluation.
///
/// ## Resolution
///
/// Did you write the correct operator?
#[error("Unknown operator: {op_token}.")]
#[diagnostic(code(nu::shell::unknown_operator))]
UnknownOperator {
op_token: String,
#[label = "unknown operator"]
span: Span,
},
/// An expected command parameter is missing.
///
/// ## Resolution
///
/// Add the expected parameter and try again.
#[error("Missing parameter: {param_name}.")]
#[diagnostic(code(nu::shell::missing_parameter))]
MissingParameter {
param_name: String,
#[label = "missing parameter: {param_name}"]
span: Span,
},
/// Two parameters conflict with each other or are otherwise mutually exclusive.
///
/// ## Resolution
///
/// Remove one of the parameters/options and try again.
#[error("Incompatible parameters.")]
#[diagnostic(code(nu::shell::incompatible_parameters))]
IncompatibleParameters {
left_message: String,
// Be cautious, as flags can share the same span, resulting in a panic (ex: `rm -pt`)
#[label("{left_message}")]
left_span: Span,
right_message: String,
#[label("{right_message}")]
right_span: Span,
},
/// There's some issue with number or matching of delimiters in an expression.
///
/// ## Resolution
///
/// Check your syntax for mismatched braces, RegExp syntax errors, etc, based on the specific error message.
#[error("Delimiter error")]
#[diagnostic(code(nu::shell::delimiter_error))]
DelimiterError {
msg: String,
#[label("{msg}")]
span: Span,
},
/// An operation received parameters with some sort of incompatibility
/// (for example, different number of rows in a table, incompatible column names, etc).
///
/// ## Resolution
///
/// Refer to the specific error message for details on what's incompatible and then fix your
/// inputs to make sure they match that way.
#[error("Incompatible parameters.")]
#[diagnostic(code(nu::shell::incompatible_parameters))]
IncompatibleParametersSingle {
msg: String,
#[label = "{msg}"]
span: Span,
},
/// You're trying to run an unsupported external command.
///
/// ## Resolution
///
/// Make sure there's an appropriate `run-external` declaration for this external command.
#[error("Running external commands not supported")]
#[diagnostic(code(nu::shell::external_commands))]
ExternalNotSupported {
#[label = "external not supported"]
span: Span,
},
// TODO: consider moving to a more generic error variant for invalid values
/// The given probability input is invalid. The probability must be between 0 and 1.
///
/// ## Resolution
///
/// Make sure the probability is between 0 and 1 and try again.
#[error("Invalid Probability.")]
#[diagnostic(code(nu::shell::invalid_probability))]
InvalidProbability {
#[label = "invalid probability: must be between 0 and 1"]
span: Span,
},
/// The first value in a `..` range must be compatible with the second one.
///
/// ## Resolution
///
/// Check to make sure both values are compatible, and that the values are enumerable in Nushell.
#[error("Invalid range {left_flank}..{right_flank}")]
#[diagnostic(code(nu::shell::invalid_range))]
InvalidRange {
left_flank: String,
right_flank: String,
#[label = "expected a valid range"]
span: Span,
},
/// Catastrophic nushell failure. This reflects a completely unexpected or unrecoverable error.
///
/// ## Resolution
///
/// It is very likely that this is a bug. Please file an issue at <https://github.com/nushell/nushell/issues> with relevant information.
#[error("Nushell failed: {msg}.")]
#[diagnostic(
code(nu::shell::nushell_failed),
help(
"This shouldn't happen. Please file an issue: https://github.com/nushell/nushell/issues"
)
)]
// Only use this one if Nushell completely falls over and hits a state that isn't possible or isn't recoverable
NushellFailed { msg: String },
/// Catastrophic nushell failure. This reflects a completely unexpected or unrecoverable error.
///
/// ## Resolution
///
/// It is very likely that this is a bug. Please file an issue at <https://github.com/nushell/nushell/issues> with relevant information.
#[error("Nushell failed: {msg}.")]
#[diagnostic(
code(nu::shell::nushell_failed_spanned),
help(
"This shouldn't happen. Please file an issue: https://github.com/nushell/nushell/issues"
)
)]
// Only use this one if Nushell completely falls over and hits a state that isn't possible or isn't recoverable
NushellFailedSpanned {
msg: String,
label: String,
#[label = "{label}"]
span: Span,
},
/// Catastrophic nushell failure. This reflects a completely unexpected or unrecoverable error.
///
/// ## Resolution
///
/// It is very likely that this is a bug. Please file an issue at <https://github.com/nushell/nushell/issues> with relevant information.
#[error("Nushell failed: {msg}.")]
#[diagnostic(code(nu::shell::nushell_failed_help))]
// Only use this one if Nushell completely falls over and hits a state that isn't possible or isn't recoverable
NushellFailedHelp {
msg: String,
#[help]
help: String,
},
/// A referenced variable was not found at runtime.
///
/// ## Resolution
///
/// Check the variable name. Did you typo it? Did you forget to declare it? Is the casing right?
#[error("Variable not found")]
#[diagnostic(code(nu::shell::variable_not_found))]
VariableNotFoundAtRuntime {
#[label = "variable not found"]
span: Span,
},
/// A referenced environment variable was not found at runtime.
///
/// ## Resolution
///
/// Check the environment variable name. Did you typo it? Did you forget to declare it? Is the casing right?
#[error("Environment variable '{envvar_name}' not found")]
#[diagnostic(code(nu::shell::env_variable_not_found))]
EnvVarNotFoundAtRuntime {
envvar_name: String,
#[label = "environment variable not found"]
span: Span,
},
/// A referenced module was not found at runtime.
///
/// ## Resolution
///
/// Check the module name. Did you typo it? Did you forget to declare it? Is the casing right?
#[error("Module '{mod_name}' not found")]
#[diagnostic(code(nu::shell::module_not_found))]
ModuleNotFoundAtRuntime {
mod_name: String,
#[label = "module not found"]
span: Span,
},
/// A referenced overlay was not found at runtime.
///
/// ## Resolution
///
/// Check the overlay name. Did you typo it? Did you forget to declare it? Is the casing right?
#[error("Overlay '{overlay_name}' not found")]
#[diagnostic(code(nu::shell::overlay_not_found))]
OverlayNotFoundAtRuntime {
overlay_name: String,
#[label = "overlay not found"]
span: Span,
},
/// The given item was not found. This is a fairly generic error that depends on context.
///
/// ## Resolution
///
/// This error is triggered in various places, and simply signals that "something" was not found. Refer to the specific error message for further details.
#[error("Not found.")]
#[diagnostic(code(nu::parser::not_found))]
NotFound {
#[label = "did not find anything under this name"]
span: Span,
},
/// Failed to convert a value of one type into a different type.
///
/// ## Resolution
///
/// Not all values can be coerced this way. Check the supported type(s) and try again.
#[error("Can't convert to {to_type}.")]
#[diagnostic(code(nu::shell::cant_convert))]
CantConvert {
to_type: String,
from_type: String,
#[label("can't convert {from_type} to {to_type}")]
span: Span,
#[help]
help: Option<String>,
},
/// Failed to convert a value of one type into a different type by specifying a unit.
///
/// ## Resolution
///
/// Check that the provided value can be converted in the provided: only Durations can be converted to duration units, and only Filesize can be converted to filesize units.
#[error("Can't convert {from_type} to the specified unit.")]
#[diagnostic(code(nu::shell::cant_convert_value_to_unit))]
CantConvertToUnit {
to_type: String,
from_type: String,
#[label("can't convert {from_type} to {to_type}")]
span: Span,
#[label("conversion originates here")]
unit_span: Span,
#[help]
help: Option<String>,
},
/// An environment variable cannot be represented as a string.
///
/// ## Resolution
///
/// Not all types can be converted to environment variable values, which must be strings. Check the input type and try again.
#[error("'{envvar_name}' is not representable as a string.")]
#[diagnostic(
code(nu::shell::env_var_not_a_string),
help(
r#"The '{envvar_name}' environment variable must be a string or be convertible to a string.
Either make sure '{envvar_name}' is a string, or add a 'to_string' entry for it in ENV_CONVERSIONS."#
)
)]
EnvVarNotAString {
envvar_name: String,
#[label("value not representable as a string")]
span: Span,
},
/// This environment variable cannot be set manually.
///
/// ## Resolution
///
/// This environment variable is set automatically by Nushell and cannot not be set manually.
#[error("{envvar_name} cannot be set manually.")]
#[diagnostic(
code(nu::shell::automatic_env_var_set_manually),
help(
r#"The environment variable '{envvar_name}' is set automatically by Nushell and cannot be set manually."#
)
)]
AutomaticEnvVarSetManually {
envvar_name: String,
#[label("cannot set '{envvar_name}' manually")]
span: Span,
},
/// It is not possible to replace the entire environment at once
///
/// ## Resolution
///
/// Setting the entire environment is not allowed. Change environment variables individually
/// instead.
#[error("Cannot replace environment.")]
#[diagnostic(
code(nu::shell::cannot_replace_env),
help(r#"Assigning a value to '$env' is not allowed."#)
)]
CannotReplaceEnv {
#[label("setting '$env' not allowed")]
span: Span,
},
/// Division by zero is not a thing.
///
/// ## Resolution
///
/// Add a guard of some sort to check whether a denominator input to this division is zero, and branch off if that's the case.
#[error("Division by zero.")]
#[diagnostic(code(nu::shell::division_by_zero))]
DivisionByZero {
#[label("division by zero")]
span: Span,
},
/// An error happened while trying to create a range.
///
/// This can happen in various unexpected situations, for example if the range would loop forever (as would be the case with a 0-increment).
///
/// ## Resolution
///
/// Check your range values to make sure they're countable and would not loop forever.
#[error("Can't convert range to countable values")]
#[diagnostic(code(nu::shell::range_to_countable))]
CannotCreateRange {
#[label = "can't convert to countable values"]
span: Span,
},
/// You attempted to access an index beyond the available length of a value.
///
/// ## Resolution
///
/// Check your lengths and try again.
#[error("Row number too large (max: {max_idx}).")]
#[diagnostic(code(nu::shell::access_beyond_end))]
AccessBeyondEnd {
max_idx: usize,
#[label = "index too large (max: {max_idx})"]
span: Span,
},
/// You attempted to insert data at a list position higher than the end.
///
/// ## Resolution
///
/// To insert data into a list, assign to the last used index + 1.
#[error("Inserted at wrong row number (should be {available_idx}).")]
#[diagnostic(code(nu::shell::access_beyond_end))]
InsertAfterNextFreeIndex {
available_idx: usize,
#[label = "can't insert at index (the next available index is {available_idx})"]
span: Span,
},
/// You attempted to access an index when it's empty.
///
/// ## Resolution
///
/// Check your lengths and try again.
#[error("Row number too large (empty content).")]
#[diagnostic(code(nu::shell::access_beyond_end))]
AccessEmptyContent {
#[label = "index too large (empty content)"]
span: Span,
},
// TODO: check to be taken over by `AccessBeyondEnd`
/// You attempted to access an index beyond the available length of a stream.
///
/// ## Resolution
///
/// Check your lengths and try again.
#[error("Row number too large.")]
#[diagnostic(code(nu::shell::access_beyond_end_of_stream))]
AccessBeyondEndOfStream {
#[label = "index too large"]
span: Span,
},
/// Tried to index into a type that does not support pathed access.
///
/// ## Resolution
///
/// Check your types. Only composite types can be pathed into.
#[error("Data cannot be accessed with a cell path")]
#[diagnostic(code(nu::shell::incompatible_path_access))]
IncompatiblePathAccess {
type_name: String,
#[label("{type_name} doesn't support cell paths")]
span: Span,
},
/// The requested column does not exist.
///
/// ## Resolution
///
/// Check the spelling of your column name. Did you forget to rename a column somewhere?
#[error("Cannot find column '{col_name}'")]
#[diagnostic(code(nu::shell::column_not_found))]
CantFindColumn {
col_name: String,
#[label = "cannot find column '{col_name}'"]
span: Option<Span>,
#[label = "value originates here"]
src_span: Span,
},
/// Attempted to insert a column into a table, but a column with that name already exists.
///
/// ## Resolution
///
/// Drop or rename the existing column (check `rename -h`) and try again.
#[error("Column already exists")]
#[diagnostic(code(nu::shell::column_already_exists))]
ColumnAlreadyExists {
col_name: String,
#[label = "column '{col_name}' already exists"]
span: Span,
#[label = "value originates here"]
src_span: Span,
},
/// The given operation can only be performed on lists.
///
/// ## Resolution
///
/// Check the input type to this command. Are you sure it's a list?
#[error("Not a list value")]
#[diagnostic(code(nu::shell::not_a_list))]
NotAList {
#[label = "value not a list"]
dst_span: Span,
#[label = "value originates here"]
src_span: Span,
},
/// Fields can only be defined once
///
/// ## Resolution
///
/// Check the record to ensure you aren't reusing the same field name
#[error("Record field or table column used twice: {col_name}")]
#[diagnostic(code(nu::shell::column_defined_twice))]
ColumnDefinedTwice {
col_name: String,
#[label = "field redefined here"]
second_use: Span,
#[label = "field first defined here"]
first_use: Span,
},
/// Attempted to create a record from different number of columns and values
///
/// ## Resolution
///
/// Check the record has the same number of columns as values
#[error("Attempted to create a record from different number of columns and values")]
#[diagnostic(code(nu::shell::record_cols_vals_mismatch))]
RecordColsValsMismatch {
#[label = "problematic value"]
bad_value: Span,
#[label = "attempted to create the record here"]
creation_site: Span,
},
/// Failed to detect columns
///
/// ## Resolution
///
/// Use `detect columns --guess` or `parse` instead
#[error("Failed to detect columns")]
#[diagnostic(code(nu::shell::failed_to_detect_columns))]
ColumnDetectionFailure {
#[label = "value coming from here"]
bad_value: Span,
#[label = "tried to detect columns here"]
failure_site: Span,
},
/// Attempted to us a relative range on an infinite stream
///
/// ## Resolution
///
/// Ensure that either the range is absolute or the stream has a known length.
#[error("Relative range values cannot be used with streams that don't have a known length")]
#[diagnostic(code(nu::shell::relative_range_on_infinite_stream))]
RelativeRangeOnInfiniteStream {
#[label = "Relative range values cannot be used with streams that don't have a known length"]
span: Span,
},
/// An error happened while performing an external command.
///
/// ## Resolution
///
/// This error is fairly generic. Refer to the specific error message for further details.
#[error("External command failed")]
#[diagnostic(code(nu::shell::external_command), help("{help}"))]
ExternalCommand {
label: String,
help: String,
#[label("{label}")]
span: Span,
},
/// An external command exited with a non-zero exit code.
///
/// ## Resolution
///
/// Check the external command's error message.
#[error("External command had a non-zero exit code")]
#[diagnostic(code(nu::shell::non_zero_exit_code))]
NonZeroExitCode {
exit_code: NonZeroI32,
#[label("exited with code {exit_code}")]
span: Span,
},
#[cfg(unix)]
/// An external command exited due to a signal.
///
/// ## Resolution
///
/// Check why the signal was sent or triggered.
#[error("External command was terminated by a signal")]
#[diagnostic(code(nu::shell::terminated_by_signal))]
TerminatedBySignal {
signal_name: String,
signal: i32,
#[label("terminated by {signal_name} ({signal})")]
span: Span,
},
#[cfg(unix)]
/// An external command core dumped.
///
/// ## Resolution
///
/// Check why the core dumped was triggered.
#[error("External command core dumped")]
#[diagnostic(code(nu::shell::core_dumped))]
CoreDumped {
signal_name: String,
signal: i32,
#[label("core dumped with {signal_name} ({signal})")]
span: Span,
},
/// An operation was attempted with an input unsupported for some reason.
///
/// ## Resolution
///
/// This error is fairly generic. Refer to the specific error message for further details.
#[error("Unsupported input")]
#[diagnostic(code(nu::shell::unsupported_input))]
UnsupportedInput {
msg: String,
input: String,
#[label("{msg}")]
msg_span: Span,
#[label("{input}")]
input_span: Span,
},
/// Failed to parse an input into a datetime value.
///
/// ## Resolution
///
/// Make sure your datetime input format is correct.
///
/// For example, these are some valid formats:
///
/// * "5 pm"
/// * "2020/12/4"
/// * "2020.12.04 22:10 +2"
/// * "2020-04-12 22:10:57 +02:00"
/// * "2020-04-12T22:10:57.213231+02:00"
/// * "Tue, 1 Jul 2003 10:52:37 +0200""#
#[error("Unable to parse datetime: [{msg}].")]
#[diagnostic(
code(nu::shell::datetime_parse_error),
help(
r#"Examples of supported inputs:
* "5 pm"
* "2020/12/4"
* "2020.12.04 22:10 +2"
* "2020-04-12 22:10:57 +02:00"
* "2020-04-12T22:10:57.213231+02:00"
* "Tue, 1 Jul 2003 10:52:37 +0200""#
)
)]
DatetimeParseError {
msg: String,
#[label("datetime parsing failed")]
span: Span,
},
/// A network operation failed.
///
/// ## Resolution
///
/// It's always DNS.
#[error("Network failure")]
#[diagnostic(code(nu::shell::network_failure))]
NetworkFailure {
msg: String,
#[label("{msg}")]
span: Span,
},
#[error(transparent)]
#[diagnostic(transparent)]
Network(#[from] network::NetworkError),
/// Help text for this command could not be found.
///
/// ## Resolution
///
/// Check the spelling for the requested command and try again. Are you sure it's defined and your configurations are loading correctly? Can you execute it?
#[error("Command not found")]
#[diagnostic(code(nu::shell::command_not_found))]
CommandNotFound {
#[label("command not found")]
span: Span,
},
/// This alias could not be found
///
/// ## Resolution
///
/// The alias does not exist in the current scope. It might exist in another scope or overlay or be hidden.
#[error("Alias not found")]
#[diagnostic(code(nu::shell::alias_not_found))]
AliasNotFound {
#[label("alias not found")]
span: Span,
},
/// The registered plugin data for a plugin is invalid.
///
/// ## Resolution
///
/// `plugin add` the plugin again to update the data, or remove it with `plugin rm`.
#[error("The registered plugin data for `{plugin_name}` is invalid")]
#[diagnostic(code(nu::shell::plugin_registry_data_invalid))]
PluginRegistryDataInvalid {
plugin_name: String,
#[label("plugin `{plugin_name}` loaded here")]
span: Option<Span>,
#[help(
"the format in the plugin registry file is not compatible with this version of Nushell.\n\nTry adding the plugin again with `{}`"
)]
add_command: String,
},
/// A plugin failed to load.
///
/// ## Resolution
///
/// This is a fairly generic error. Refer to the specific error message for further details.
#[error("Plugin failed to load: {msg}")]
#[diagnostic(code(nu::shell::plugin_failed_to_load))]
PluginFailedToLoad { msg: String },
/// A message from a plugin failed to encode.
///
/// ## Resolution
///
/// This is likely a bug with the plugin itself.
#[error("Plugin failed to encode: {msg}")]
#[diagnostic(code(nu::shell::plugin_failed_to_encode))]
PluginFailedToEncode { msg: String },
/// A message to a plugin failed to decode.
///
/// ## Resolution
///
/// This is either an issue with the inputs to a plugin (bad JSON?) or a bug in the plugin itself. Fix or report as appropriate.
#[error("Plugin failed to decode: {msg}")]
#[diagnostic(code(nu::shell::plugin_failed_to_decode))]
PluginFailedToDecode { msg: String },
/// A custom value cannot be sent to the given plugin.
///
/// ## Resolution
///
/// Custom values can only be used with the plugin they came from. Use a command from that
/// plugin instead.
#[error("Custom value `{name}` cannot be sent to plugin")]
#[diagnostic(code(nu::shell::custom_value_incorrect_for_plugin))]
CustomValueIncorrectForPlugin {
name: String,
#[label("the `{dest_plugin}` plugin does not support this kind of value")]
span: Span,
dest_plugin: String,
#[help("this value came from the `{}` plugin")]
src_plugin: Option<String>,
},
/// The plugin failed to encode a custom value.
///
/// ## Resolution
///
/// This is likely a bug with the plugin itself. The plugin may have tried to send a custom
/// value that is not serializable.
#[error("Custom value failed to encode")]
#[diagnostic(code(nu::shell::custom_value_failed_to_encode))]
CustomValueFailedToEncode {
msg: String,
#[label("{msg}")]
span: Span,
},
/// The plugin failed to encode a custom value.
///
/// ## Resolution
///
/// This may be a bug within the plugin, or the plugin may have been updated in between the
/// creation of the custom value and its use.
#[error("Custom value failed to decode")]
#[diagnostic(code(nu::shell::custom_value_failed_to_decode))]
#[diagnostic(help("the plugin may have been updated and no longer support this custom value"))]
CustomValueFailedToDecode {
msg: String,
#[label("{msg}")]
span: Span,
},
/// An I/O operation failed.
///
/// ## Resolution
///
/// This is the main I/O error, for further details check the error kind and additional context.
#[error(transparent)]
#[diagnostic(transparent)]
Io(#[from] io::IoError),
/// A name was not found. Did you mean a different name?
///
/// ## Resolution
///
/// The error message will suggest a possible match for what you meant.
#[error("Name not found")]
#[diagnostic(code(nu::shell::name_not_found))]
DidYouMean {
suggestion: String,
#[label("did you mean '{suggestion}'?")]
span: Span,
},
/// A name was not found. Did you mean a different name?
///
/// ## Resolution
///
/// The error message will suggest a possible match for what you meant.
#[error("{msg}")]
#[diagnostic(code(nu::shell::did_you_mean_custom))]
DidYouMeanCustom {
msg: String,
suggestion: String,
#[label("did you mean '{suggestion}'?")]
span: Span,
},
/// The given input must be valid UTF-8 for further processing.
///
/// ## Resolution
///
/// Check your input's encoding. Are there any funny characters/bytes?
#[error("Non-UTF8 string")]
#[diagnostic(
code(nu::parser::non_utf8),
help("see `decode` for handling character sets other than UTF-8")
)]
NonUtf8 {
#[label("non-UTF8 string")]
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/shell_error/location.rs | crates/nu-protocol/src/errors/shell_error/location.rs | use thiserror::Error;
/// Represents a specific location in the Rust code.
///
/// This data structure is used to provide detailed information about where in the Rust code
/// an error occurred.
/// While most errors in [`ShellError`](super::ShellError) are related to user-provided Nushell
/// code, some originate from the underlying Rust implementation.
/// With this type, we can pinpoint the exact location of such errors, improving debugging
/// and error reporting.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("{file}:{line}:{column}")]
pub struct Location {
file: &'static str,
line: u32,
column: u32,
}
impl Location {
/// Internal constructor for [`Location`].
///
/// This function is not intended to be called directly.
/// Instead, use the [`location!`] macro to create instances.
#[doc(hidden)]
#[deprecated(
note = "This function is not meant to be called directly. Use `nu_protocol::location` instead."
)]
pub fn new(file: &'static str, line: u32, column: u32) -> Self {
Location { file, line, column }
}
}
/// Macro to create a new [`Location`] for the exact position in your code.
///
/// This macro captures the current file, line, and column during compilation,
/// providing an easy way to associate errors with specific locations in the Rust code.
///
/// # Note
/// This macro relies on the [`file!`], [`line!`], and [`column!`] macros to fetch the
/// compilation context.
#[macro_export]
macro_rules! location {
() => {{
#[allow(deprecated)]
$crate::shell_error::location::Location::new(file!(), line!(), column!())
}};
}
#[test]
fn test_location_macro() {
let location = crate::location!();
let line = line!() - 1; // Adjust for the macro call being on the previous line.
let file = file!();
assert_eq!(location.line, line);
assert_eq!(location.file, file);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/shell_error/job.rs | crates/nu-protocol/src/errors/shell_error/job.rs | use miette::Diagnostic;
use thiserror::Error;
use crate::{JobId, Span};
/// Errors when working working with jobs.
#[derive(Debug, Clone, Copy, PartialEq, Error, Diagnostic)]
pub enum JobError {
#[error("Job {id} not found")]
#[diagnostic(
code(nu::shell::job::not_found),
help(
"The operation could not be completed, there is no job currently running with this id"
)
)]
NotFound { span: Span, id: JobId },
#[error("No frozen job to unfreeze")]
#[diagnostic(
code(nu::shell::job::none_to_unfreeze),
help("There is currently no frozen job to unfreeze")
)]
NoneToUnfreeze { span: Span },
#[error("Job {id} is not frozen")]
#[diagnostic(
code(nu::shell::job::cannot_unfreeze),
help("You tried to unfreeze a job which is not frozen")
)]
CannotUnfreeze { span: Span, id: JobId },
#[error("The job {id} is frozen")]
#[diagnostic(
code(nu::shell::job::already_frozen),
help("This operation cannot be performed because the job is frozen")
)]
AlreadyFrozen { span: Span, id: JobId },
#[error("No message was received in the requested time interval")]
#[diagnostic(
code(nu::shell::job::recv_timeout),
help("No message arrived within the specified time limit")
)]
RecvTimeout { span: Span },
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/filesize.rs | crates/nu-protocol/src/value/filesize.rs | use crate::{FromValue, IntoValue, ShellError, Span, Type, Value};
use num_format::{Locale, WriteFormatted};
use serde::{Deserialize, Serialize};
use std::{
char,
fmt::{self, Write},
iter::Sum,
ops::{Add, Mul, Neg, Sub},
str::FromStr,
};
use thiserror::Error;
pub const SUPPORTED_FILESIZE_UNITS: [&str; 13] = [
"B", "kB", "MB", "GB", "TB", "PB", "EB", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB",
];
/// A signed number of bytes.
///
/// [`Filesize`] is a wrapper around [`i64`]. Whereas [`i64`] is a dimensionless value, [`Filesize`] represents a
/// numerical value with a dimensional unit (byte).
///
/// A [`Filesize`] can be created from an [`i64`] using [`Filesize::new`] or the `From` or `Into` trait implementations.
/// To get the underlying [`i64`] value, use [`Filesize::get`] or the `From` or `Into` trait implementations.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[repr(transparent)]
#[serde(transparent)]
pub struct Filesize(i64);
impl Filesize {
/// A [`Filesize`] of 0 bytes.
pub const ZERO: Self = Self(0);
/// The smallest possible [`Filesize`] value.
pub const MIN: Self = Self(i64::MIN);
/// The largest possible [`Filesize`] value.
pub const MAX: Self = Self(i64::MAX);
/// Create a new [`Filesize`] from a [`i64`] number of bytes.
pub const fn new(bytes: i64) -> Self {
Self(bytes)
}
/// Creates a [`Filesize`] from a signed multiple of a [`FilesizeUnit`].
///
/// If the resulting number of bytes calculated by `value * unit.as_bytes()` overflows an
/// [`i64`], then `None` is returned.
pub const fn from_unit(value: i64, unit: FilesizeUnit) -> Option<Self> {
if let Some(bytes) = value.checked_mul(unit.as_bytes() as i64) {
Some(Self(bytes))
} else {
None
}
}
/// Returns the underlying [`i64`] number of bytes in a [`Filesize`].
pub const fn get(&self) -> i64 {
self.0
}
/// Returns true if a [`Filesize`] is positive and false if it is zero or negative.
pub const fn is_positive(self) -> bool {
self.0.is_positive()
}
/// Returns true if a [`Filesize`] is negative and false if it is zero or positive.
pub const fn is_negative(self) -> bool {
self.0.is_negative()
}
/// Returns a [`Filesize`] representing the sign of `self`.
/// - 0 if the file size is zero
/// - 1 if the file size is positive
/// - -1 if the file size is negative
pub const fn signum(self) -> Self {
Self(self.0.signum())
}
/// Returns the largest [`FilesizeUnit`] with a metric prefix that is smaller than or equal to `self`.
///
/// # Examples
/// ```
/// # use nu_protocol::{Filesize, FilesizeUnit};
///
/// let filesize = Filesize::from(FilesizeUnit::KB);
/// assert_eq!(filesize.largest_metric_unit(), FilesizeUnit::KB);
///
/// let filesize = Filesize::new(FilesizeUnit::KB.as_bytes() as i64 - 1);
/// assert_eq!(filesize.largest_metric_unit(), FilesizeUnit::B);
///
/// let filesize = Filesize::from(FilesizeUnit::KiB);
/// assert_eq!(filesize.largest_metric_unit(), FilesizeUnit::KB);
/// ```
pub const fn largest_metric_unit(&self) -> FilesizeUnit {
const KB: u64 = FilesizeUnit::KB.as_bytes();
const MB: u64 = FilesizeUnit::MB.as_bytes();
const GB: u64 = FilesizeUnit::GB.as_bytes();
const TB: u64 = FilesizeUnit::TB.as_bytes();
const PB: u64 = FilesizeUnit::PB.as_bytes();
const EB: u64 = FilesizeUnit::EB.as_bytes();
match self.0.unsigned_abs() {
0..KB => FilesizeUnit::B,
KB..MB => FilesizeUnit::KB,
MB..GB => FilesizeUnit::MB,
GB..TB => FilesizeUnit::GB,
TB..PB => FilesizeUnit::TB,
PB..EB => FilesizeUnit::PB,
EB.. => FilesizeUnit::EB,
}
}
/// Returns the largest [`FilesizeUnit`] with a binary prefix that is smaller than or equal to `self`.
///
/// # Examples
/// ```
/// # use nu_protocol::{Filesize, FilesizeUnit};
///
/// let filesize = Filesize::from(FilesizeUnit::KiB);
/// assert_eq!(filesize.largest_binary_unit(), FilesizeUnit::KiB);
///
/// let filesize = Filesize::new(FilesizeUnit::KiB.as_bytes() as i64 - 1);
/// assert_eq!(filesize.largest_binary_unit(), FilesizeUnit::B);
///
/// let filesize = Filesize::from(FilesizeUnit::MB);
/// assert_eq!(filesize.largest_binary_unit(), FilesizeUnit::KiB);
/// ```
pub const fn largest_binary_unit(&self) -> FilesizeUnit {
const KIB: u64 = FilesizeUnit::KiB.as_bytes();
const MIB: u64 = FilesizeUnit::MiB.as_bytes();
const GIB: u64 = FilesizeUnit::GiB.as_bytes();
const TIB: u64 = FilesizeUnit::TiB.as_bytes();
const PIB: u64 = FilesizeUnit::PiB.as_bytes();
const EIB: u64 = FilesizeUnit::EiB.as_bytes();
match self.0.unsigned_abs() {
0..KIB => FilesizeUnit::B,
KIB..MIB => FilesizeUnit::KiB,
MIB..GIB => FilesizeUnit::MiB,
GIB..TIB => FilesizeUnit::GiB,
TIB..PIB => FilesizeUnit::TiB,
PIB..EIB => FilesizeUnit::PiB,
EIB.. => FilesizeUnit::EiB,
}
}
}
impl From<i64> for Filesize {
fn from(value: i64) -> Self {
Self(value)
}
}
impl From<Filesize> for i64 {
fn from(filesize: Filesize) -> Self {
filesize.0
}
}
macro_rules! impl_from {
($($ty:ty),* $(,)?) => {
$(
impl From<$ty> for Filesize {
#[inline]
fn from(value: $ty) -> Self {
Self(value.into())
}
}
impl TryFrom<Filesize> for $ty {
type Error = <i64 as TryInto<$ty>>::Error;
#[inline]
fn try_from(filesize: Filesize) -> Result<Self, Self::Error> {
filesize.0.try_into()
}
}
)*
};
}
impl_from!(u8, i8, u16, i16, u32, i32);
macro_rules! impl_try_from {
($($ty:ty),* $(,)?) => {
$(
impl TryFrom<$ty> for Filesize {
type Error = <$ty as TryInto<i64>>::Error;
#[inline]
fn try_from(value: $ty) -> Result<Self, Self::Error> {
value.try_into().map(Self)
}
}
impl TryFrom<Filesize> for $ty {
type Error = <i64 as TryInto<$ty>>::Error;
#[inline]
fn try_from(filesize: Filesize) -> Result<Self, Self::Error> {
filesize.0.try_into()
}
}
)*
};
}
impl_try_from!(u64, usize, isize);
/// The error type returned when a checked conversion from a floating point type fails.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Error)]
pub struct TryFromFloatError(());
impl fmt::Display for TryFromFloatError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "out of range float type conversion attempted")
}
}
impl TryFrom<f64> for Filesize {
type Error = TryFromFloatError;
#[inline]
fn try_from(value: f64) -> Result<Self, Self::Error> {
if i64::MIN as f64 <= value && value <= i64::MAX as f64 {
Ok(Self(value as i64))
} else {
Err(TryFromFloatError(()))
}
}
}
impl TryFrom<f32> for Filesize {
type Error = TryFromFloatError;
#[inline]
fn try_from(value: f32) -> Result<Self, Self::Error> {
if i64::MIN as f32 <= value && value <= i64::MAX as f32 {
Ok(Self(value as i64))
} else {
Err(TryFromFloatError(()))
}
}
}
impl FromValue for Filesize {
fn from_value(value: Value) -> Result<Self, ShellError> {
value.as_filesize()
}
fn expected_type() -> Type {
Type::Filesize
}
}
impl IntoValue for Filesize {
fn into_value(self, span: Span) -> Value {
Value::filesize(self.0, span)
}
}
impl Add for Filesize {
type Output = Option<Self>;
fn add(self, rhs: Self) -> Self::Output {
self.0.checked_add(rhs.0).map(Self)
}
}
impl Sub for Filesize {
type Output = Option<Self>;
fn sub(self, rhs: Self) -> Self::Output {
self.0.checked_sub(rhs.0).map(Self)
}
}
impl Mul<i64> for Filesize {
type Output = Option<Self>;
fn mul(self, rhs: i64) -> Self::Output {
self.0.checked_mul(rhs).map(Self)
}
}
impl Mul<Filesize> for i64 {
type Output = Option<Filesize>;
fn mul(self, rhs: Filesize) -> Self::Output {
self.checked_mul(rhs.0).map(Filesize::new)
}
}
impl Mul<f64> for Filesize {
type Output = Option<Self>;
fn mul(self, rhs: f64) -> Self::Output {
let bytes = ((self.0 as f64) * rhs).round();
if i64::MIN as f64 <= bytes && bytes <= i64::MAX as f64 {
Some(Self(bytes as i64))
} else {
None
}
}
}
impl Mul<Filesize> for f64 {
type Output = Option<Filesize>;
fn mul(self, rhs: Filesize) -> Self::Output {
let bytes = (self * (rhs.0 as f64)).round();
if i64::MIN as f64 <= bytes && bytes <= i64::MAX as f64 {
Some(Filesize(bytes as i64))
} else {
None
}
}
}
impl Neg for Filesize {
type Output = Option<Self>;
fn neg(self) -> Self::Output {
self.0.checked_neg().map(Self)
}
}
impl Sum<Filesize> for Option<Filesize> {
fn sum<I: Iterator<Item = Filesize>>(iter: I) -> Self {
let mut sum = Filesize::ZERO;
for filesize in iter {
sum = (sum + filesize)?;
}
Some(sum)
}
}
impl fmt::Display for Filesize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", FilesizeFormatter::new().format(*self))
}
}
/// All the possible filesize units for a [`Filesize`].
///
/// This type contains both units with metric (SI) prefixes which are powers of 10 (e.g., kB = 1000 bytes)
/// and units with binary prefixes which are powers of 2 (e.g., KiB = 1024 bytes).
///
/// The number of bytes in a [`FilesizeUnit`] can be obtained using [`as_bytes`](Self::as_bytes).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FilesizeUnit {
/// One byte
B,
/// Kilobyte = 1000 bytes
KB,
/// Megabyte = 10<sup>6</sup> bytes
MB,
/// Gigabyte = 10<sup>9</sup> bytes
GB,
/// Terabyte = 10<sup>12</sup> bytes
TB,
/// Petabyte = 10<sup>15</sup> bytes
PB,
/// Exabyte = 10<sup>18</sup> bytes
EB,
/// Kibibyte = 1024 bytes
KiB,
/// Mebibyte = 2<sup>20</sup> bytes
MiB,
/// Gibibyte = 2<sup>30</sup> bytes
GiB,
/// Tebibyte = 2<sup>40</sup> bytes
TiB,
/// Pebibyte = 2<sup>50</sup> bytes
PiB,
/// Exbibyte = 2<sup>60</sup> bytes
EiB,
}
impl FilesizeUnit {
/// Returns the number of bytes in a [`FilesizeUnit`].
pub const fn as_bytes(&self) -> u64 {
match self {
Self::B => 1,
Self::KB => 10_u64.pow(3),
Self::MB => 10_u64.pow(6),
Self::GB => 10_u64.pow(9),
Self::TB => 10_u64.pow(12),
Self::PB => 10_u64.pow(15),
Self::EB => 10_u64.pow(18),
Self::KiB => 2_u64.pow(10),
Self::MiB => 2_u64.pow(20),
Self::GiB => 2_u64.pow(30),
Self::TiB => 2_u64.pow(40),
Self::PiB => 2_u64.pow(50),
Self::EiB => 2_u64.pow(60),
}
}
/// Convert a [`FilesizeUnit`] to a [`Filesize`].
///
/// To create a [`Filesize`] from a multiple of a [`FilesizeUnit`] use [`Filesize::from_unit`].
pub const fn as_filesize(&self) -> Filesize {
Filesize::new(self.as_bytes() as i64)
}
/// Returns the symbol [`str`] for a [`FilesizeUnit`].
///
/// The symbol is exactly the same as the enum case name in Rust code except for
/// [`FilesizeUnit::KB`] which is `kB`.
///
/// The returned string is the same exact string needed for a successful call to
/// [`parse`](str::parse) for a [`FilesizeUnit`].
///
/// # Examples
/// ```
/// # use nu_protocol::FilesizeUnit;
/// assert_eq!(FilesizeUnit::B.as_str(), "B");
/// assert_eq!(FilesizeUnit::KB.as_str(), "kB");
/// assert_eq!(FilesizeUnit::KiB.as_str(), "KiB");
/// assert_eq!(FilesizeUnit::KB.as_str().parse(), Ok(FilesizeUnit::KB));
/// ```
pub const fn as_str(&self) -> &'static str {
match self {
Self::B => "B",
Self::KB => "kB",
Self::MB => "MB",
Self::GB => "GB",
Self::TB => "TB",
Self::PB => "PB",
Self::EB => "EB",
Self::KiB => "KiB",
Self::MiB => "MiB",
Self::GiB => "GiB",
Self::TiB => "TiB",
Self::PiB => "PiB",
Self::EiB => "EiB",
}
}
/// Returns `true` if a [`FilesizeUnit`] has a metric (SI) prefix (a power of 10).
///
/// Note that this returns `true` for [`FilesizeUnit::B`] as well.
pub const fn is_metric(&self) -> bool {
match self {
Self::B | Self::KB | Self::MB | Self::GB | Self::TB | Self::PB | Self::EB => true,
Self::KiB | Self::MiB | Self::GiB | Self::TiB | Self::PiB | Self::EiB => false,
}
}
/// Returns `true` if a [`FilesizeUnit`] has a binary prefix (a power of 2).
///
/// Note that this returns `true` for [`FilesizeUnit::B`] as well.
pub const fn is_binary(&self) -> bool {
match self {
Self::KB | Self::MB | Self::GB | Self::TB | Self::PB | Self::EB => false,
Self::B | Self::KiB | Self::MiB | Self::GiB | Self::TiB | Self::PiB | Self::EiB => true,
}
}
}
impl From<FilesizeUnit> for Filesize {
fn from(unit: FilesizeUnit) -> Self {
unit.as_filesize()
}
}
impl fmt::Display for FilesizeUnit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// The error returned when failing to parse a [`FilesizeUnit`].
///
/// This occurs when the string being parsed does not exactly match the name of one of the
/// enum cases in [`FilesizeUnit`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, Error)]
pub struct ParseFilesizeUnitError(());
impl fmt::Display for ParseFilesizeUnitError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "invalid file size unit")
}
}
impl FromStr for FilesizeUnit {
type Err = ParseFilesizeUnitError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"B" => Self::B,
"kB" => Self::KB,
"MB" => Self::MB,
"GB" => Self::GB,
"TB" => Self::TB,
"PB" => Self::PB,
"EB" => Self::EB,
"KiB" => Self::KiB,
"MiB" => Self::MiB,
"GiB" => Self::GiB,
"TiB" => Self::TiB,
"PiB" => Self::PiB,
"EiB" => Self::EiB,
_ => return Err(ParseFilesizeUnitError(())),
})
}
}
/// The different file size unit display formats for a [`FilesizeFormatter`].
///
/// To see more information about each possible format, see the documentation for each of the enum
/// cases of [`FilesizeUnitFormat`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FilesizeUnitFormat {
/// [`Metric`](Self::Metric) will make a [`FilesizeFormatter`] use the
/// [`largest_metric_unit`](Filesize::largest_metric_unit) of a [`Filesize`] when formatting it.
Metric,
/// [`Binary`](Self::Binary) will make a [`FilesizeFormatter`] use the
/// [`largest_binary_unit`](Filesize::largest_binary_unit) of a [`Filesize`] when formatting it.
Binary,
/// [`FilesizeUnitFormat::Unit`] will make a [`FilesizeFormatter`] use the provided
/// [`FilesizeUnit`] when formatting all [`Filesize`]s.
Unit(FilesizeUnit),
}
impl FilesizeUnitFormat {
/// Returns a string representation of a [`FilesizeUnitFormat`].
///
/// The returned string is the same exact string needed for a successful call to
/// [`parse`](str::parse) for a [`FilesizeUnitFormat`].
///
/// # Examples
/// ```
/// # use nu_protocol::{FilesizeUnit, FilesizeUnitFormat};
/// assert_eq!(FilesizeUnitFormat::Metric.as_str(), "metric");
/// assert_eq!(FilesizeUnitFormat::Binary.as_str(), "binary");
/// assert_eq!(FilesizeUnitFormat::Unit(FilesizeUnit::KB).as_str(), "kB");
/// assert_eq!(FilesizeUnitFormat::Metric.as_str().parse(), Ok(FilesizeUnitFormat::Metric));
/// ```
pub const fn as_str(&self) -> &'static str {
match self {
Self::Metric => "metric",
Self::Binary => "binary",
Self::Unit(unit) => unit.as_str(),
}
}
/// Returns `true` for [`FilesizeUnitFormat::Metric`] or if the underlying [`FilesizeUnit`]
/// is metric according to [`FilesizeUnit::is_metric`].
///
/// Note that this returns `true` for [`FilesizeUnit::B`] as well.
pub const fn is_metric(&self) -> bool {
match self {
Self::Metric => true,
Self::Binary => false,
Self::Unit(unit) => unit.is_metric(),
}
}
/// Returns `true` for [`FilesizeUnitFormat::Binary`] or if the underlying [`FilesizeUnit`]
/// is binary according to [`FilesizeUnit::is_binary`].
///
/// Note that this returns `true` for [`FilesizeUnit::B`] as well.
pub const fn is_binary(&self) -> bool {
match self {
Self::Metric => false,
Self::Binary => true,
Self::Unit(unit) => unit.is_binary(),
}
}
}
impl From<FilesizeUnit> for FilesizeUnitFormat {
fn from(unit: FilesizeUnit) -> Self {
Self::Unit(unit)
}
}
impl fmt::Display for FilesizeUnitFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// The error returned when failing to parse a [`FilesizeUnitFormat`].
///
/// This occurs when the string being parsed does not exactly match any of:
/// - `metric`
/// - `binary`
/// - The name of any of the enum cases in [`FilesizeUnit`]. The exception is [`FilesizeUnit::KB`] which must be `kB`.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Error)]
pub struct ParseFilesizeUnitFormatError(());
impl fmt::Display for ParseFilesizeUnitFormatError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "invalid file size unit format")
}
}
impl FromStr for FilesizeUnitFormat {
type Err = ParseFilesizeUnitFormatError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
"metric" => Self::Metric,
"binary" => Self::Binary,
s => Self::Unit(s.parse().map_err(|_| ParseFilesizeUnitFormatError(()))?),
})
}
}
/// A configurable formatter for [`Filesize`]s.
///
/// [`FilesizeFormatter`] is a builder struct that you can modify via the following methods:
/// - [`unit`](Self::unit)
/// - [`show_unit`](Self::show_unit)
/// - [`precision`](Self::precision)
/// - [`locale`](Self::locale)
///
/// For more information, see the documentation for each of those methods.
///
/// # Examples
/// ```
/// # use nu_protocol::{Filesize, FilesizeFormatter, FilesizeUnit};
/// # use num_format::Locale;
/// let filesize = Filesize::from_unit(4, FilesizeUnit::KiB).unwrap();
/// let formatter = FilesizeFormatter::new();
///
/// assert_eq!(formatter.unit(FilesizeUnit::B).format(filesize).to_string(), "4096 B");
/// assert_eq!(formatter.unit(FilesizeUnit::KiB).format(filesize).to_string(), "4 KiB");
/// assert_eq!(formatter.precision(2).format(filesize).to_string(), "4.09 kB");
/// assert_eq!(
/// formatter
/// .unit(FilesizeUnit::B)
/// .locale(Locale::en)
/// .format(filesize)
/// .to_string(),
/// "4,096 B",
/// );
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FilesizeFormatter {
unit: FilesizeUnitFormat,
show_unit: bool,
precision: Option<usize>,
locale: Locale,
}
impl FilesizeFormatter {
/// Create a new, default [`FilesizeFormatter`].
///
/// The default formatter has:
/// - a [`unit`](Self::unit) of [`FilesizeUnitFormat::Metric`].
/// - a [`show_unit`](Self::show_unit) of `true`.
/// - a [`precision`](Self::precision) of `None`.
/// - a [`locale`](Self::locale) of [`Locale::en_US_POSIX`]
/// (a very plain format with no thousands separators).
pub fn new() -> Self {
FilesizeFormatter {
unit: FilesizeUnitFormat::Metric,
show_unit: true,
precision: None,
locale: Locale::en_US_POSIX,
}
}
/// Set the [`FilesizeUnitFormat`] used by the formatter.
///
/// A [`FilesizeUnit`] or a [`FilesizeUnitFormat`] can be provided to this method.
/// [`FilesizeUnitFormat::Metric`] and [`FilesizeUnitFormat::Binary`] will use a unit of an
/// appropriate scale for each [`Filesize`], whereas providing a [`FilesizeUnit`] will use that
/// unit to format all [`Filesize`]s.
///
/// # Examples
/// ```
/// # use nu_protocol::{Filesize, FilesizeFormatter, FilesizeUnit, FilesizeUnitFormat};
/// let formatter = FilesizeFormatter::new().precision(1);
///
/// let filesize = Filesize::from_unit(4, FilesizeUnit::KiB).unwrap();
/// assert_eq!(formatter.unit(FilesizeUnit::B).format(filesize).to_string(), "4096 B");
/// assert_eq!(formatter.unit(FilesizeUnitFormat::Binary).format(filesize).to_string(), "4.0 KiB");
///
/// let filesize = Filesize::from_unit(4, FilesizeUnit::MiB).unwrap();
/// assert_eq!(formatter.unit(FilesizeUnitFormat::Metric).format(filesize).to_string(), "4.1 MB");
/// assert_eq!(formatter.unit(FilesizeUnitFormat::Binary).format(filesize).to_string(), "4.0 MiB");
/// ```
pub fn unit(mut self, unit: impl Into<FilesizeUnitFormat>) -> Self {
self.unit = unit.into();
self
}
/// Sets whether to show or omit the file size unit in the formatted output.
///
/// This setting can be used to disable the unit formatting from [`FilesizeFormatter`]
/// and instead provide your own.
///
/// Note that the [`FilesizeUnitFormat`] provided to [`unit`](Self::unit) is still used to
/// format the numeric portion of a [`Filesize`]. So, setting `show_unit` to `false` is only
/// recommended for [`FilesizeUnitFormat::Unit`], since this will keep the unit the same
/// for all [`Filesize`]s. [`FilesizeUnitFormat::Metric`] and [`FilesizeUnitFormat::Binary`],
/// on the other hand, will adapt the unit to match the magnitude of each formatted [`Filesize`].
///
/// # Examples
/// ```
/// # use nu_protocol::{Filesize, FilesizeFormatter, FilesizeUnit};
/// let filesize = Filesize::from_unit(4, FilesizeUnit::KiB).unwrap();
/// let formatter = FilesizeFormatter::new().show_unit(false);
///
/// assert_eq!(formatter.unit(FilesizeUnit::B).format(filesize).to_string(), "4096");
/// assert_eq!(format!("{} KB", formatter.unit(FilesizeUnit::KiB).format(filesize)), "4 KB");
/// ```
pub fn show_unit(self, show_unit: bool) -> Self {
Self { show_unit, ..self }
}
/// Set the number of digits to display after the decimal place.
///
/// Note that digits after the decimal place will never be shown if:
/// - [`unit`](Self::unit) is [`FilesizeUnit::B`],
/// - [`unit`](Self::unit) is [`FilesizeUnitFormat::Metric`] and the number of bytes
/// is less than [`FilesizeUnit::KB`]
/// - [`unit`](Self::unit) is [`FilesizeUnitFormat::Binary`] and the number of bytes
/// is less than [`FilesizeUnit::KiB`].
///
/// Additionally, the precision specified in the format string
/// (i.e., [`std::fmt::Formatter::precision`]) will take precedence if is specified.
/// If the format string precision and the [`FilesizeFormatter`]'s precision are both `None`,
/// then all digits after the decimal place, if any, are shown.
///
/// # Examples
/// ```
/// # use nu_protocol::{Filesize, FilesizeFormatter, FilesizeUnit, FilesizeUnitFormat};
/// let filesize = Filesize::from_unit(4, FilesizeUnit::KiB).unwrap();
/// let formatter = FilesizeFormatter::new();
///
/// assert_eq!(formatter.precision(2).format(filesize).to_string(), "4.09 kB");
/// assert_eq!(formatter.precision(0).format(filesize).to_string(), "4 kB");
/// assert_eq!(formatter.precision(None).format(filesize).to_string(), "4.096 kB");
/// assert_eq!(
/// formatter
/// .precision(None)
/// .unit(FilesizeUnit::KiB)
/// .format(filesize)
/// .to_string(),
/// "4 KiB",
/// );
/// assert_eq!(
/// formatter
/// .unit(FilesizeUnit::B)
/// .precision(2)
/// .format(filesize)
/// .to_string(),
/// "4096 B",
/// );
/// assert_eq!(format!("{:.2}", formatter.precision(0).format(filesize)), "4.09 kB");
/// ```
pub fn precision(mut self, precision: impl Into<Option<usize>>) -> Self {
self.precision = precision.into();
self
}
/// Set the [`Locale`] to use when formatting the numeric portion of a [`Filesize`].
///
/// The [`Locale`] determines the decimal place character, minus sign character,
/// digit grouping method, and digit separator character.
///
/// # Examples
/// ```
/// # use nu_protocol::{Filesize, FilesizeFormatter, FilesizeUnit, FilesizeUnitFormat};
/// # use num_format::Locale;
/// let filesize = Filesize::from_unit(-4, FilesizeUnit::MiB).unwrap();
/// let formatter = FilesizeFormatter::new().unit(FilesizeUnit::KB).precision(1);
///
/// assert_eq!(formatter.format(filesize).to_string(), "-4194.3 kB");
/// assert_eq!(formatter.locale(Locale::en).format(filesize).to_string(), "-4,194.3 kB");
/// assert_eq!(formatter.locale(Locale::rm).format(filesize).to_string(), "\u{2212}4β194.3 kB");
/// let filesize = Filesize::from_unit(-4, FilesizeUnit::GiB).unwrap();
/// assert_eq!(formatter.locale(Locale::ta).format(filesize).to_string(), "-42,94,967.2 kB");
/// ```
pub fn locale(mut self, locale: Locale) -> Self {
self.locale = locale;
self
}
/// Format a [`Filesize`] into a [`FormattedFilesize`] which implements [`fmt::Display`].
///
/// # Examples
/// ```
/// # use nu_protocol::{Filesize, FilesizeFormatter, FilesizeUnit};
/// let filesize = Filesize::from_unit(4, FilesizeUnit::KB).unwrap();
/// let formatter = FilesizeFormatter::new();
///
/// assert_eq!(format!("{}", formatter.format(filesize)), "4 kB");
/// assert_eq!(formatter.format(filesize).to_string(), "4 kB");
/// ```
pub fn format(&self, filesize: Filesize) -> FormattedFilesize {
FormattedFilesize {
format: *self,
filesize,
}
}
}
impl Default for FilesizeFormatter {
fn default() -> Self {
Self::new()
}
}
/// The resulting struct from calling [`FilesizeFormatter::format`] on a [`Filesize`].
///
/// The only purpose of this struct is to implement [`fmt::Display`].
#[derive(Debug, Clone)]
pub struct FormattedFilesize {
format: FilesizeFormatter,
filesize: Filesize,
}
impl fmt::Display for FormattedFilesize {
fn fmt(&self, mut f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Self { filesize, format } = *self;
let FilesizeFormatter {
unit,
show_unit,
precision,
locale,
} = format;
let unit = match unit {
FilesizeUnitFormat::Metric => filesize.largest_metric_unit(),
FilesizeUnitFormat::Binary => filesize.largest_binary_unit(),
FilesizeUnitFormat::Unit(unit) => unit,
};
let Filesize(filesize) = filesize;
let precision = f.precision().or(precision);
let bytes = unit.as_bytes() as i64;
let whole = filesize / bytes;
let fract = (filesize % bytes).unsigned_abs();
f.write_formatted(&whole, &locale)
.map_err(|_| std::fmt::Error)?;
if unit != FilesizeUnit::B && precision != Some(0) && !(precision.is_none() && fract == 0) {
f.write_str(locale.decimal())?;
let bytes = unit.as_bytes();
let mut fract = fract * 10;
let mut i = 0;
loop {
let q = fract / bytes;
let r = fract % bytes;
// Quick soundness proof:
// r <= bytes by definition of remainder `%`
// => 10 * r <= 10 * bytes
// => fract <= 10 * bytes before next iteration, fract = r * 10
// => fract / bytes <= 10
// => q <= 10 next iteration, q = fract / bytes
debug_assert!(q <= 10);
f.write_char(char::from_digit(q as u32, 10).expect("q <= 10"))?;
i += 1;
if r == 0 || precision.is_some_and(|p| i >= p) {
break;
}
fract = r * 10;
}
if let Some(precision) = precision {
for _ in 0..(precision - i) {
f.write_char('0')?;
}
}
}
if show_unit {
write!(f, " {unit}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[rstest]
#[case(1024, FilesizeUnit::KB, "1.024 kB")]
#[case(1024, FilesizeUnit::B, "1024 B")]
#[case(1024, FilesizeUnit::KiB, "1 KiB")]
#[case(3_000_000, FilesizeUnit::MB, "3 MB")]
#[case(3_000_000, FilesizeUnit::KB, "3000 kB")]
fn display_unit(#[case] bytes: i64, #[case] unit: FilesizeUnit, #[case] exp: &str) {
assert_eq!(
exp,
FilesizeFormatter::new()
.unit(unit)
.format(Filesize::new(bytes))
.to_string()
);
}
#[rstest]
#[case(1000, "1000 B")]
#[case(1024, "1 KiB")]
#[case(1025, "1.0009765625 KiB")]
fn display_auto_binary(#[case] val: i64, #[case] exp: &str) {
assert_eq!(
exp,
FilesizeFormatter::new()
.unit(FilesizeUnitFormat::Binary)
.format(Filesize::new(val))
.to_string()
);
}
#[rstest]
#[case(999, "999 B")]
#[case(1000, "1 kB")]
#[case(1024, "1.024 kB")]
fn display_auto_metric(#[case] val: i64, #[case] exp: &str) {
assert_eq!(
exp,
FilesizeFormatter::new()
.unit(FilesizeUnitFormat::Metric)
.format(Filesize::new(val))
.to_string()
);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/range.rs | crates/nu-protocol/src/value/range.rs | //! A Range is an iterator over integers or floats.
use crate::{ShellError, Signals, Span, Value, ast::RangeInclusion};
use core::ops::Bound;
use serde::{Deserialize, Serialize};
use std::{cmp::Ordering, fmt::Display};
mod int_range {
use crate::{FromValue, ShellError, Signals, Span, Value, ast::RangeInclusion};
use serde::{Deserialize, Serialize};
use std::{cmp::Ordering, fmt::Display, ops::Bound};
use super::Range;
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct IntRange {
pub(crate) start: i64,
pub(crate) step: i64,
pub(crate) end: Bound<i64>,
}
impl IntRange {
pub fn new(
start: Value,
next: Value,
end: Value,
inclusion: RangeInclusion,
span: Span,
) -> Result<Self, ShellError> {
fn to_int(value: Value) -> Result<Option<i64>, ShellError> {
match value {
Value::Int { val, .. } => Ok(Some(val)),
Value::Nothing { .. } => Ok(None),
val => Err(ShellError::CantConvert {
to_type: "int".into(),
from_type: val.get_type().to_string(),
span: val.span(),
help: None,
}),
}
}
let start = to_int(start)?.unwrap_or(0);
let next_span = next.span();
let next = to_int(next)?;
if next.is_some_and(|next| next == start) {
return Err(ShellError::CannotCreateRange { span: next_span });
}
let end = to_int(end)?;
let step = match (next, end) {
(Some(next), Some(end)) => {
if (next < start) != (end < start) {
return Err(ShellError::CannotCreateRange { span });
}
next - start
}
(Some(next), None) => next - start,
(None, Some(end)) => {
if end < start {
-1
} else {
1
}
}
(None, None) => 1,
};
let end = if let Some(end) = end {
match inclusion {
RangeInclusion::Inclusive => Bound::Included(end),
RangeInclusion::RightExclusive => Bound::Excluded(end),
}
} else {
Bound::Unbounded
};
Ok(Self { start, step, end })
}
pub fn start(&self) -> i64 {
self.start
}
// Resolves the absolute start position given the length of the input value
pub fn absolute_start(&self, len: u64) -> u64 {
match self.start {
start if start < 0 => len.saturating_sub(start.unsigned_abs()),
start => len.min(start.unsigned_abs()),
}
}
/// Returns the distance between the start and end of the range
/// The result will always be 0 or positive
pub fn distance(&self) -> Bound<u64> {
match self.end {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(end) | Bound::Excluded(end) if self.start > end => {
Bound::Excluded(0)
}
Bound::Included(end) => Bound::Included((end - self.start) as u64),
Bound::Excluded(end) => Bound::Excluded((end - self.start) as u64),
}
}
pub fn end(&self) -> Bound<i64> {
self.end
}
pub fn absolute_end(&self, len: u64) -> Bound<u64> {
match self.end {
Bound::Unbounded => Bound::Unbounded,
Bound::Included(i) => match i {
_ if len == 0 => Bound::Excluded(0),
i if i < 0 => Bound::Excluded(len.saturating_sub((i + 1).unsigned_abs())),
i => Bound::Included((len.saturating_sub(1)).min(i.unsigned_abs())),
},
Bound::Excluded(i) => Bound::Excluded(match i {
i if i < 0 => len.saturating_sub(i.unsigned_abs()),
i => len.min(i.unsigned_abs()),
}),
}
}
pub fn absolute_bounds(&self, len: usize) -> (usize, Bound<usize>) {
let start = self.absolute_start(len as u64) as usize;
let end = self.absolute_end(len as u64).map(|e| e as usize);
match end {
Bound::Excluded(end) | Bound::Included(end) if end < start => {
(start, Bound::Excluded(start))
}
Bound::Excluded(end) => (start, Bound::Excluded(end)),
Bound::Included(end) => (start, Bound::Included(end)),
Bound::Unbounded => (start, Bound::Unbounded),
}
}
pub fn step(&self) -> i64 {
self.step
}
pub fn is_unbounded(&self) -> bool {
self.end == Bound::Unbounded
}
pub fn is_relative(&self) -> bool {
self.is_start_relative() || self.is_end_relative()
}
pub fn is_start_relative(&self) -> bool {
self.start < 0
}
pub fn is_end_relative(&self) -> bool {
match self.end {
Bound::Included(end) | Bound::Excluded(end) => end < 0,
_ => false,
}
}
pub fn contains(&self, value: i64) -> bool {
if self.step < 0 {
// Decreasing range
if value > self.start {
return false;
}
match self.end {
Bound::Included(end) if value < end => return false,
Bound::Excluded(end) if value <= end => return false,
_ => {}
};
} else {
// Increasing range
if value < self.start {
return false;
}
match self.end {
Bound::Included(end) if value > end => return false,
Bound::Excluded(end) if value >= end => return false,
_ => {}
};
}
(value - self.start) % self.step == 0
}
pub fn into_range_iter(self, signals: Signals) -> Iter {
Iter {
current: Some(self.start),
step: self.step,
end: self.end,
signals,
}
}
}
impl Ord for IntRange {
fn cmp(&self, other: &Self) -> Ordering {
// Ranges are compared roughly according to their list representation.
// Compare in order:
// - the head element (start)
// - the tail elements (step)
// - the length (end)
self.start
.cmp(&other.start)
.then(self.step.cmp(&other.step))
.then_with(|| match (self.end, other.end) {
(Bound::Included(l), Bound::Included(r))
| (Bound::Excluded(l), Bound::Excluded(r)) => {
let ord = l.cmp(&r);
if self.step < 0 { ord.reverse() } else { ord }
}
(Bound::Included(l), Bound::Excluded(r)) => match l.cmp(&r) {
Ordering::Equal => Ordering::Greater,
ord if self.step < 0 => ord.reverse(),
ord => ord,
},
(Bound::Excluded(l), Bound::Included(r)) => match l.cmp(&r) {
Ordering::Equal => Ordering::Less,
ord if self.step < 0 => ord.reverse(),
ord => ord,
},
(Bound::Included(_), Bound::Unbounded) => Ordering::Less,
(Bound::Excluded(_), Bound::Unbounded) => Ordering::Less,
(Bound::Unbounded, Bound::Included(_)) => Ordering::Greater,
(Bound::Unbounded, Bound::Excluded(_)) => Ordering::Greater,
(Bound::Unbounded, Bound::Unbounded) => Ordering::Equal,
})
}
}
impl PartialOrd for IntRange {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for IntRange {
fn eq(&self, other: &Self) -> bool {
self.start == other.start && self.step == other.step && self.end == other.end
}
}
impl Eq for IntRange {}
impl Display for IntRange {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..", self.start)?;
if self.step != 1 {
write!(f, "{}..", self.start + self.step)?;
}
match self.end {
Bound::Included(end) => write!(f, "{end}"),
Bound::Excluded(end) => write!(f, "<{end}"),
Bound::Unbounded => Ok(()),
}
}
}
impl FromValue for IntRange {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
let range = Range::from_value(v)?;
match range {
Range::IntRange(v) => Ok(v),
Range::FloatRange(_) => Err(ShellError::TypeMismatch {
err_message: "expected an int range".into(),
span,
}),
}
}
}
pub struct Iter {
current: Option<i64>,
step: i64,
end: Bound<i64>,
signals: Signals,
}
impl Iterator for Iter {
type Item = i64;
fn next(&mut self) -> Option<Self::Item> {
if let Some(current) = self.current {
let not_end = match (self.step < 0, self.end) {
(true, Bound::Included(end)) => current >= end,
(true, Bound::Excluded(end)) => current > end,
(false, Bound::Included(end)) => current <= end,
(false, Bound::Excluded(end)) => current < end,
(_, Bound::Unbounded) => true, // will stop once integer overflows
};
if not_end && !self.signals.interrupted() {
self.current = current.checked_add(self.step);
Some(current)
} else {
self.current = None;
None
}
} else {
None
}
}
}
}
mod float_range {
use crate::{IntRange, Range, ShellError, Signals, Span, Value, ast::RangeInclusion};
use nu_utils::ObviousFloat;
use serde::{Deserialize, Serialize};
use std::{cmp::Ordering, fmt::Display, ops::Bound};
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct FloatRange {
pub(crate) start: f64,
pub(crate) step: f64,
pub(crate) end: Bound<f64>,
}
impl FloatRange {
pub fn new(
start: Value,
next: Value,
end: Value,
inclusion: RangeInclusion,
span: Span,
) -> Result<Self, ShellError> {
fn to_float(value: Value) -> Result<Option<f64>, ShellError> {
match value {
Value::Float { val, .. } => Ok(Some(val)),
Value::Int { val, .. } => Ok(Some(val as f64)),
Value::Nothing { .. } => Ok(None),
val => Err(ShellError::CantConvert {
to_type: "float".into(),
from_type: val.get_type().to_string(),
span: val.span(),
help: None,
}),
}
}
// `start` must be finite (not NaN or infinity).
// `next` must be finite and not equal to `start`.
// `end` must not be NaN (but can be infinite).
//
// TODO: better error messages for the restrictions above
let start_span = start.span();
let start = to_float(start)?.unwrap_or(0.0);
if !start.is_finite() {
return Err(ShellError::CannotCreateRange { span: start_span });
}
let end_span = end.span();
let end = to_float(end)?;
if end.is_some_and(f64::is_nan) {
return Err(ShellError::CannotCreateRange { span: end_span });
}
let next_span = next.span();
let next = to_float(next)?;
if next.is_some_and(|next| next == start || !next.is_finite()) {
return Err(ShellError::CannotCreateRange { span: next_span });
}
let step = match (next, end) {
(Some(next), Some(end)) => {
if (next < start) != (end < start) {
return Err(ShellError::CannotCreateRange { span });
}
next - start
}
(Some(next), None) => next - start,
(None, Some(end)) => {
if end < start {
-1.0
} else {
1.0
}
}
(None, None) => 1.0,
};
let end = if let Some(end) = end {
if end.is_infinite() {
Bound::Unbounded
} else {
match inclusion {
RangeInclusion::Inclusive => Bound::Included(end),
RangeInclusion::RightExclusive => Bound::Excluded(end),
}
}
} else {
Bound::Unbounded
};
Ok(Self { start, step, end })
}
pub fn start(&self) -> f64 {
self.start
}
pub fn end(&self) -> Bound<f64> {
self.end
}
pub fn step(&self) -> f64 {
self.step
}
pub fn is_unbounded(&self) -> bool {
self.end == Bound::Unbounded
}
pub fn contains(&self, value: f64) -> bool {
if self.step < 0.0 {
// Decreasing range
if value > self.start {
return false;
}
match self.end {
Bound::Included(end) if value <= end => return false,
Bound::Excluded(end) if value < end => return false,
_ => {}
};
} else {
// Increasing range
if value < self.start {
return false;
}
match self.end {
Bound::Included(end) if value >= end => return false,
Bound::Excluded(end) if value > end => return false,
_ => {}
};
}
((value - self.start) % self.step).abs() < f64::EPSILON
}
pub fn into_range_iter(self, signals: Signals) -> Iter {
Iter {
start: self.start,
step: self.step,
end: self.end,
iter: Some(0),
signals,
}
}
}
impl Ord for FloatRange {
fn cmp(&self, other: &Self) -> Ordering {
fn float_cmp(a: f64, b: f64) -> Ordering {
// There is no way a `FloatRange` can have NaN values:
// - `FloatRange::new` ensures no values are NaN.
// - `From<IntRange> for FloatRange` cannot give NaNs either.
// - There are no other ways to create a `FloatRange`.
// - There is no way to modify values of a `FloatRange`.
a.partial_cmp(&b).expect("not NaN")
}
// Ranges are compared roughly according to their list representation.
// Compare in order:
// - the head element (start)
// - the tail elements (step)
// - the length (end)
float_cmp(self.start, other.start)
.then(float_cmp(self.step, other.step))
.then_with(|| match (self.end, other.end) {
(Bound::Included(l), Bound::Included(r))
| (Bound::Excluded(l), Bound::Excluded(r)) => {
let ord = float_cmp(l, r);
if self.step < 0.0 { ord.reverse() } else { ord }
}
(Bound::Included(l), Bound::Excluded(r)) => match float_cmp(l, r) {
Ordering::Equal => Ordering::Greater,
ord if self.step < 0.0 => ord.reverse(),
ord => ord,
},
(Bound::Excluded(l), Bound::Included(r)) => match float_cmp(l, r) {
Ordering::Equal => Ordering::Less,
ord if self.step < 0.0 => ord.reverse(),
ord => ord,
},
(Bound::Included(_), Bound::Unbounded) => Ordering::Less,
(Bound::Excluded(_), Bound::Unbounded) => Ordering::Less,
(Bound::Unbounded, Bound::Included(_)) => Ordering::Greater,
(Bound::Unbounded, Bound::Excluded(_)) => Ordering::Greater,
(Bound::Unbounded, Bound::Unbounded) => Ordering::Equal,
})
}
}
impl PartialOrd for FloatRange {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for FloatRange {
fn eq(&self, other: &Self) -> bool {
self.start == other.start && self.step == other.step && self.end == other.end
}
}
impl Eq for FloatRange {}
impl Display for FloatRange {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}..", ObviousFloat(self.start))?;
if self.step != 1f64 {
write!(f, "{}..", ObviousFloat(self.start + self.step))?;
}
match self.end {
Bound::Included(end) => write!(f, "{}", ObviousFloat(end)),
Bound::Excluded(end) => write!(f, "<{}", ObviousFloat(end)),
Bound::Unbounded => Ok(()),
}
}
}
impl From<IntRange> for FloatRange {
fn from(range: IntRange) -> Self {
Self {
start: range.start as f64,
step: range.step as f64,
end: match range.end {
Bound::Included(b) => Bound::Included(b as f64),
Bound::Excluded(b) => Bound::Excluded(b as f64),
Bound::Unbounded => Bound::Unbounded,
},
}
}
}
impl From<Range> for FloatRange {
fn from(range: Range) -> Self {
match range {
Range::IntRange(range) => range.into(),
Range::FloatRange(range) => range,
}
}
}
pub struct Iter {
start: f64,
step: f64,
end: Bound<f64>,
iter: Option<u64>,
signals: Signals,
}
impl Iterator for Iter {
type Item = f64;
fn next(&mut self) -> Option<Self::Item> {
if let Some(iter) = self.iter {
let current = self.start + self.step * iter as f64;
let not_end = match (self.step < 0.0, self.end) {
(true, Bound::Included(end)) => current >= end,
(true, Bound::Excluded(end)) => current > end,
(false, Bound::Included(end)) => current <= end,
(false, Bound::Excluded(end)) => current < end,
(_, Bound::Unbounded) => current.is_finite(),
};
if not_end && !self.signals.interrupted() {
self.iter = iter.checked_add(1);
Some(current)
} else {
self.iter = None;
None
}
} else {
None
}
}
}
}
pub use float_range::FloatRange;
pub use int_range::IntRange;
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Range {
IntRange(IntRange),
FloatRange(FloatRange),
}
impl Range {
pub fn new(
start: Value,
next: Value,
end: Value,
inclusion: RangeInclusion,
span: Span,
) -> Result<Self, ShellError> {
// promote to float range if any Value is float
if matches!(start, Value::Float { .. })
|| matches!(next, Value::Float { .. })
|| matches!(end, Value::Float { .. })
{
FloatRange::new(start, next, end, inclusion, span).map(Self::FloatRange)
} else {
IntRange::new(start, next, end, inclusion, span).map(Self::IntRange)
}
}
pub fn contains(&self, value: &Value) -> bool {
match (self, value) {
(Self::IntRange(range), Value::Int { val, .. }) => range.contains(*val),
(Self::IntRange(range), Value::Float { val, .. }) => {
FloatRange::from(*range).contains(*val)
}
(Self::FloatRange(range), Value::Int { val, .. }) => range.contains(*val as f64),
(Self::FloatRange(range), Value::Float { val, .. }) => range.contains(*val),
_ => false,
}
}
pub fn is_bounded(&self) -> bool {
match self {
Range::IntRange(range) => range.end() != Bound::<i64>::Unbounded,
Range::FloatRange(range) => range.end() != Bound::<f64>::Unbounded,
}
}
pub fn into_range_iter(self, span: Span, signals: Signals) -> Iter {
match self {
Range::IntRange(range) => Iter::IntIter(range.into_range_iter(signals), span),
Range::FloatRange(range) => Iter::FloatIter(range.into_range_iter(signals), span),
}
}
}
impl Ord for Range {
fn cmp(&self, other: &Self) -> Ordering {
match (self, other) {
(Range::IntRange(l), Range::IntRange(r)) => l.cmp(r),
(Range::FloatRange(l), Range::FloatRange(r)) => l.cmp(r),
(Range::IntRange(int), Range::FloatRange(float)) => FloatRange::from(*int).cmp(float),
(Range::FloatRange(float), Range::IntRange(int)) => float.cmp(&FloatRange::from(*int)),
}
}
}
impl PartialOrd for Range {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Range {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Range::IntRange(l), Range::IntRange(r)) => l == r,
(Range::FloatRange(l), Range::FloatRange(r)) => l == r,
(Range::IntRange(int), Range::FloatRange(float)) => FloatRange::from(*int) == *float,
(Range::FloatRange(float), Range::IntRange(int)) => *float == FloatRange::from(*int),
}
}
}
impl Eq for Range {}
impl Display for Range {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Range::IntRange(range) => write!(f, "{range}"),
Range::FloatRange(range) => write!(f, "{range}"),
}
}
}
impl From<IntRange> for Range {
fn from(range: IntRange) -> Self {
Self::IntRange(range)
}
}
impl From<FloatRange> for Range {
fn from(range: FloatRange) -> Self {
Self::FloatRange(range)
}
}
pub enum Iter {
IntIter(int_range::Iter, Span),
FloatIter(float_range::Iter, Span),
}
impl Iterator for Iter {
type Item = Value;
fn next(&mut self) -> Option<Self::Item> {
match self {
Iter::IntIter(iter, span) => iter.next().map(|val| Value::int(val, *span)),
Iter::FloatIter(iter, span) => iter.next().map(|val| Value::float(val, *span)),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/test_derive.rs | crates/nu-protocol/src/value/test_derive.rs | use crate::{FromValue, IntoValue, Record, Span, Value, record};
use bytes::Bytes;
use std::collections::HashMap;
// Make nu_protocol available in this namespace, consumers of this crate will
// have this without such an export.
// The derive macro fully qualifies paths to "nu_protocol".
use crate as nu_protocol;
trait IntoTestValue {
fn into_test_value(self) -> Value;
}
impl<T> IntoTestValue for T
where
T: IntoValue,
{
fn into_test_value(self) -> Value {
self.into_value(Span::test_data())
}
}
#[derive(IntoValue, FromValue, Debug, PartialEq)]
struct NamedFieldsStruct<T>
where
T: IntoValue + FromValue,
{
array: [u16; 4],
bool: bool,
char: char,
f32: f32,
f64: f64,
i8: i8,
i16: i16,
i32: i32,
i64: i64,
isize: isize,
u16: u16,
u32: u32,
unit: (),
tuple: (u32, bool),
some: Option<u32>,
none: Option<u32>,
vec: Vec<T>,
string: String,
hashmap: HashMap<String, u32>,
nested: Nestee,
}
#[derive(IntoValue, FromValue, Debug, PartialEq)]
struct Nestee {
u32: u32,
some: Option<u32>,
none: Option<u32>,
}
impl NamedFieldsStruct<u32> {
fn make() -> Self {
Self {
array: [1, 2, 3, 4],
bool: true,
char: 'a',
f32: std::f32::consts::PI,
f64: std::f64::consts::E,
i8: 127,
i16: -32768,
i32: 2147483647,
i64: -9223372036854775808,
isize: 2,
u16: 65535,
u32: 4294967295,
unit: (),
tuple: (1, true),
some: Some(123),
none: None,
vec: vec![10, 20, 30],
string: "string".to_string(),
hashmap: HashMap::from_iter([("a".to_string(), 10), ("b".to_string(), 20)]),
nested: Nestee {
u32: 3,
some: Some(42),
none: None,
},
}
}
fn value() -> Value {
Value::test_record(record! {
"array" => Value::test_list(vec![
Value::test_int(1),
Value::test_int(2),
Value::test_int(3),
Value::test_int(4)
]),
"bool" => Value::test_bool(true),
"char" => Value::test_string('a'),
"f32" => Value::test_float(std::f32::consts::PI.into()),
"f64" => Value::test_float(std::f64::consts::E),
"i8" => Value::test_int(127),
"i16" => Value::test_int(-32768),
"i32" => Value::test_int(2147483647),
"i64" => Value::test_int(-9223372036854775808),
"isize" => Value::test_int(2),
"u16" => Value::test_int(65535),
"u32" => Value::test_int(4294967295),
"unit" => Value::test_nothing(),
"tuple" => Value::test_list(vec![
Value::test_int(1),
Value::test_bool(true)
]),
"some" => Value::test_int(123),
"none" => Value::test_nothing(),
"vec" => Value::test_list(vec![
Value::test_int(10),
Value::test_int(20),
Value::test_int(30)
]),
"string" => Value::test_string("string"),
"hashmap" => Value::test_record(record! {
"a" => Value::test_int(10),
"b" => Value::test_int(20)
}),
"nested" => Value::test_record(record! {
"u32" => Value::test_int(3),
"some" => Value::test_int(42),
"none" => Value::test_nothing(),
})
})
}
}
#[test]
fn named_fields_struct_into_value() {
let expected = NamedFieldsStruct::value();
let actual = NamedFieldsStruct::make().into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn named_fields_struct_from_value() {
let expected = NamedFieldsStruct::make();
let actual = NamedFieldsStruct::from_value(NamedFieldsStruct::value()).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn named_fields_struct_roundtrip() {
let expected = NamedFieldsStruct::make();
let actual =
NamedFieldsStruct::from_value(NamedFieldsStruct::make().into_test_value()).unwrap();
assert_eq!(expected, actual);
let expected = NamedFieldsStruct::value();
let actual = NamedFieldsStruct::<u32>::from_value(NamedFieldsStruct::value())
.unwrap()
.into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn named_fields_struct_missing_value() {
let value = Value::test_record(Record::new());
let res: Result<NamedFieldsStruct<u32>, _> = NamedFieldsStruct::from_value(value);
assert!(res.is_err());
}
#[test]
fn named_fields_struct_incorrect_type() {
// Should work for every type that is not a record.
let value = Value::test_nothing();
let res: Result<NamedFieldsStruct<u32>, _> = NamedFieldsStruct::from_value(value);
assert!(res.is_err());
}
#[derive(IntoValue, FromValue, Debug, PartialEq, Default)]
struct ALotOfOptions {
required: bool,
float: Option<f64>,
int: Option<i64>,
value: Option<Value>,
nested: Option<Nestee>,
}
#[test]
fn missing_options() {
let value = Value::test_record(Record::new());
let res: Result<ALotOfOptions, _> = ALotOfOptions::from_value(value);
assert!(res.is_err());
let value = Value::test_record(record! {"required" => Value::test_bool(true)});
let expected = ALotOfOptions {
required: true,
..Default::default()
};
let actual = ALotOfOptions::from_value(value).unwrap();
assert_eq!(expected, actual);
let value = Value::test_record(record! {
"required" => Value::test_bool(true),
"float" => Value::test_float(std::f64::consts::PI),
});
let expected = ALotOfOptions {
required: true,
float: Some(std::f64::consts::PI),
..Default::default()
};
let actual = ALotOfOptions::from_value(value).unwrap();
assert_eq!(expected, actual);
let value = Value::test_record(record! {
"required" => Value::test_bool(true),
"int" => Value::test_int(12),
"nested" => Value::test_record(record! {
"u32" => Value::test_int(34),
}),
});
let expected = ALotOfOptions {
required: true,
int: Some(12),
nested: Some(Nestee {
u32: 34,
some: None,
none: None,
}),
..Default::default()
};
let actual = ALotOfOptions::from_value(value).unwrap();
assert_eq!(expected, actual);
}
#[derive(IntoValue, FromValue, Debug, PartialEq)]
struct UnnamedFieldsStruct<T>(u32, String, T)
where
T: IntoValue + FromValue;
impl UnnamedFieldsStruct<f64> {
fn make() -> Self {
UnnamedFieldsStruct(420, "Hello, tuple!".to_string(), 33.33)
}
fn value() -> Value {
Value::test_list(vec![
Value::test_int(420),
Value::test_string("Hello, tuple!"),
Value::test_float(33.33),
])
}
}
#[test]
fn unnamed_fields_struct_into_value() {
let expected = UnnamedFieldsStruct::value();
let actual = UnnamedFieldsStruct::make().into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn unnamed_fields_struct_from_value() {
let expected = UnnamedFieldsStruct::make();
let value = UnnamedFieldsStruct::value();
let actual = UnnamedFieldsStruct::from_value(value).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn unnamed_fields_struct_roundtrip() {
let expected = UnnamedFieldsStruct::make();
let actual =
UnnamedFieldsStruct::from_value(UnnamedFieldsStruct::make().into_test_value()).unwrap();
assert_eq!(expected, actual);
let expected = UnnamedFieldsStruct::value();
let actual = UnnamedFieldsStruct::<f64>::from_value(UnnamedFieldsStruct::value())
.unwrap()
.into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn unnamed_fields_struct_missing_value() {
let value = Value::test_list(vec![]);
let res: Result<UnnamedFieldsStruct<f64>, _> = UnnamedFieldsStruct::from_value(value);
assert!(res.is_err());
}
#[test]
fn unnamed_fields_struct_incorrect_type() {
// Should work for every type that is not a record.
let value = Value::test_nothing();
let res: Result<UnnamedFieldsStruct<f64>, _> = UnnamedFieldsStruct::from_value(value);
assert!(res.is_err());
}
#[derive(IntoValue, FromValue, Debug, PartialEq)]
struct UnitStruct;
#[test]
fn unit_struct_into_value() {
let expected = Value::test_nothing();
let actual = UnitStruct.into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn unit_struct_from_value() {
let expected = UnitStruct;
let actual = UnitStruct::from_value(Value::test_nothing()).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn unit_struct_roundtrip() {
let expected = UnitStruct;
let actual = UnitStruct::from_value(UnitStruct.into_test_value()).unwrap();
assert_eq!(expected, actual);
let expected = Value::test_nothing();
let actual = UnitStruct::from_value(Value::test_nothing())
.unwrap()
.into_test_value();
assert_eq!(expected, actual);
}
#[derive(IntoValue, FromValue, Debug, PartialEq)]
enum Enum {
AlphaOne,
BetaTwo,
CharlieThree,
}
impl Enum {
fn make() -> [Self; 3] {
[Enum::AlphaOne, Enum::BetaTwo, Enum::CharlieThree]
}
fn value() -> Value {
Value::test_list(vec![
Value::test_string("alpha_one"),
Value::test_string("beta_two"),
Value::test_string("charlie_three"),
])
}
}
#[test]
fn enum_into_value() {
let expected = Enum::value();
let actual = Enum::make().into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn enum_from_value() {
let expected = Enum::make();
let actual = <[Enum; 3]>::from_value(Enum::value()).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn enum_roundtrip() {
let expected = Enum::make();
let actual = <[Enum; 3]>::from_value(Enum::make().into_test_value()).unwrap();
assert_eq!(expected, actual);
let expected = Enum::value();
let actual = <[Enum; 3]>::from_value(Enum::value())
.unwrap()
.into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn enum_unknown_variant() {
let value = Value::test_string("delta_four");
let res = Enum::from_value(value);
assert!(res.is_err());
}
#[test]
fn enum_incorrect_type() {
// Should work for every type that is not a record.
let value = Value::test_nothing();
let res = Enum::from_value(value);
assert!(res.is_err());
}
mod enum_rename_all {
use super::*;
use crate as nu_protocol;
// Generate the `Enum` from before but with all possible `rename_all` variants.
macro_rules! enum_rename_all {
($($ident:ident: $case:literal => [$a1:literal, $b2:literal, $c3:literal]),*) => {
$(
#[derive(Debug, PartialEq, IntoValue, FromValue)]
#[nu_value(rename_all = $case)]
enum $ident {
AlphaOne,
BetaTwo,
CharlieThree
}
impl $ident {
fn make() -> [Self; 3] {
[Self::AlphaOne, Self::BetaTwo, Self::CharlieThree]
}
fn value() -> Value {
Value::test_list(vec![
Value::test_string($a1),
Value::test_string($b2),
Value::test_string($c3),
])
}
}
)*
#[test]
fn into_value() {$({
let expected = $ident::value();
let actual = $ident::make().into_test_value();
assert_eq!(expected, actual);
})*}
#[test]
fn from_value() {$({
let expected = $ident::make();
let actual = <[$ident; 3]>::from_value($ident::value()).unwrap();
assert_eq!(expected, actual);
})*}
}
}
enum_rename_all! {
Upper: "UPPER CASE" => ["ALPHA ONE", "BETA TWO", "CHARLIE THREE"],
Lower: "lower case" => ["alpha one", "beta two", "charlie three"],
Title: "Title Case" => ["Alpha One", "Beta Two", "Charlie Three"],
Camel: "camelCase" => ["alphaOne", "betaTwo", "charlieThree"],
Pascal: "PascalCase" => ["AlphaOne", "BetaTwo", "CharlieThree"],
Snake: "snake_case" => ["alpha_one", "beta_two", "charlie_three"],
UpperSnake: "UPPER_SNAKE_CASE" => ["ALPHA_ONE", "BETA_TWO", "CHARLIE_THREE"],
Kebab: "kebab-case" => ["alpha-one", "beta-two", "charlie-three"],
Cobol: "COBOL-CASE" => ["ALPHA-ONE", "BETA-TWO", "CHARLIE-THREE"],
Train: "Train-Case" => ["Alpha-One", "Beta-Two", "Charlie-Three"],
Flat: "flatcase" => ["alphaone", "betatwo", "charliethree"],
UpperFlat: "UPPERFLATCASE" => ["ALPHAONE", "BETATWO", "CHARLIETHREE"]
}
}
mod named_fields_struct_rename_all {
use super::*;
use crate as nu_protocol;
macro_rules! named_fields_struct_rename_all {
($($ident:ident: $case:literal => [$a1:literal, $b2:literal, $c3:literal]),*) => {
$(
#[derive(Debug, PartialEq, IntoValue, FromValue)]
#[nu_value(rename_all = $case)]
struct $ident {
alpha_one: (),
beta_two: (),
charlie_three: (),
}
impl $ident {
fn make() -> Self {
Self {
alpha_one: (),
beta_two: (),
charlie_three: (),
}
}
fn value() -> Value {
Value::test_record(record! {
$a1 => Value::test_nothing(),
$b2 => Value::test_nothing(),
$c3 => Value::test_nothing(),
})
}
}
)*
#[test]
fn into_value() {$({
let expected = $ident::value();
let actual = $ident::make().into_test_value();
assert_eq!(expected, actual);
})*}
#[test]
fn from_value() {$({
let expected = $ident::make();
let actual = $ident::from_value($ident::value()).unwrap();
assert_eq!(expected, actual);
})*}
}
}
named_fields_struct_rename_all! {
Upper: "UPPER CASE" => ["ALPHA ONE", "BETA TWO", "CHARLIE THREE"],
Lower: "lower case" => ["alpha one", "beta two", "charlie three"],
Title: "Title Case" => ["Alpha One", "Beta Two", "Charlie Three"],
Camel: "camelCase" => ["alphaOne", "betaTwo", "charlieThree"],
Pascal: "PascalCase" => ["AlphaOne", "BetaTwo", "CharlieThree"],
Snake: "snake_case" => ["alpha_one", "beta_two", "charlie_three"],
UpperSnake: "UPPER_SNAKE_CASE" => ["ALPHA_ONE", "BETA_TWO", "CHARLIE_THREE"],
Kebab: "kebab-case" => ["alpha-one", "beta-two", "charlie-three"],
Cobol: "COBOL-CASE" => ["ALPHA-ONE", "BETA-TWO", "CHARLIE-THREE"],
Train: "Train-Case" => ["Alpha-One", "Beta-Two", "Charlie-Three"],
Flat: "flatcase" => ["alphaone", "betatwo", "charliethree"],
UpperFlat: "UPPERFLATCASE" => ["ALPHAONE", "BETATWO", "CHARLIETHREE"]
}
}
#[derive(IntoValue, FromValue, Debug, PartialEq)]
struct ByteContainer {
vec: Vec<u8>,
bytes: Bytes,
}
impl ByteContainer {
fn make() -> Self {
ByteContainer {
vec: vec![1, 2, 3],
bytes: Bytes::from_static(&[4, 5, 6]),
}
}
fn value() -> Value {
Value::test_record(record! {
"vec" => Value::test_list(vec![
Value::test_int(1),
Value::test_int(2),
Value::test_int(3),
]),
"bytes" => Value::test_binary(vec![4, 5, 6]),
})
}
}
#[test]
fn bytes_into_value() {
let expected = ByteContainer::value();
let actual = ByteContainer::make().into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn bytes_from_value() {
let expected = ByteContainer::make();
let actual = ByteContainer::from_value(ByteContainer::value()).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn bytes_roundtrip() {
let expected = ByteContainer::make();
let actual = ByteContainer::from_value(ByteContainer::make().into_test_value()).unwrap();
assert_eq!(expected, actual);
let expected = ByteContainer::value();
let actual = ByteContainer::from_value(ByteContainer::value())
.unwrap()
.into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn struct_type_name_attr() {
#[derive(FromValue, Debug)]
#[nu_value(type_name = "struct")]
struct TypeNameStruct;
assert_eq!(
TypeNameStruct::expected_type().to_string().as_str(),
"struct"
);
}
#[test]
fn enum_type_name_attr() {
#[derive(FromValue, Debug)]
#[nu_value(type_name = "enum")]
struct TypeNameEnum;
assert_eq!(TypeNameEnum::expected_type().to_string().as_str(), "enum");
}
#[derive(IntoValue, FromValue, Default, Debug, PartialEq)]
struct RenamedFieldStruct {
#[nu_value(rename = "renamed")]
field: (),
}
impl RenamedFieldStruct {
fn value() -> Value {
Value::test_record(record! {
"renamed" => Value::test_nothing(),
})
}
}
#[test]
fn renamed_field_struct_into_value() {
let expected = RenamedFieldStruct::value();
let actual = RenamedFieldStruct::default().into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn renamed_field_struct_from_value() {
let expected = RenamedFieldStruct::default();
let actual = RenamedFieldStruct::from_value(RenamedFieldStruct::value()).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn renamed_field_struct_roundtrip() {
let expected = RenamedFieldStruct::default();
let actual =
RenamedFieldStruct::from_value(RenamedFieldStruct::default().into_test_value()).unwrap();
assert_eq!(expected, actual);
let expected = RenamedFieldStruct::value();
let actual = RenamedFieldStruct::from_value(RenamedFieldStruct::value())
.unwrap()
.into_test_value();
assert_eq!(expected, actual);
}
#[derive(IntoValue, FromValue, Default, Debug, PartialEq)]
enum RenamedVariantEnum {
#[default]
#[nu_value(rename = "renamed")]
Variant,
}
impl RenamedVariantEnum {
fn value() -> Value {
Value::test_string("renamed")
}
}
#[test]
fn renamed_variant_enum_into_value() {
let expected = RenamedVariantEnum::value();
let actual = RenamedVariantEnum::default().into_test_value();
assert_eq!(expected, actual);
}
#[test]
fn renamed_variant_enum_from_value() {
let expected = RenamedVariantEnum::default();
let actual = RenamedVariantEnum::from_value(RenamedVariantEnum::value()).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn renamed_variant_enum_roundtrip() {
let expected = RenamedVariantEnum::default();
let actual =
RenamedVariantEnum::from_value(RenamedVariantEnum::default().into_test_value()).unwrap();
assert_eq!(expected, actual);
let expected = RenamedVariantEnum::value();
let actual = RenamedVariantEnum::from_value(RenamedVariantEnum::value())
.unwrap()
.into_test_value();
assert_eq!(expected, actual);
}
#[derive(IntoValue, FromValue, Default, Debug, PartialEq)]
struct DefaultFieldStruct {
#[nu_value(default)]
field: String,
#[nu_value(rename = "renamed", default)]
field_two: String,
}
#[test]
fn default_field_struct_from_value() {
let populated = DefaultFieldStruct {
field: "hello".into(),
field_two: "world".into(),
};
let populated_record = Value::test_record(record! {
"field" => Value::test_string("hello"),
"renamed" => Value::test_string("world"),
});
let actual = DefaultFieldStruct::from_value(populated_record).unwrap();
assert_eq!(populated, actual);
let default = DefaultFieldStruct::default();
let default_record = Value::test_record(Record::new());
let actual = DefaultFieldStruct::from_value(default_record).unwrap();
assert_eq!(default, actual);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/glob.rs | crates/nu-protocol/src/value/glob.rs | use serde::Deserialize;
use std::fmt::Display;
// Introduce this `NuGlob` enum rather than using `Value::Glob` directlry
// So we can handle glob easily without considering too much variant of `Value` enum.
#[derive(Debug, Clone, Deserialize)]
pub enum NuGlob {
/// Don't expand the glob pattern, normally it includes a quoted string(except backtick)
/// And a variable that doesn't annotated with `glob` type
DoNotExpand(String),
/// A glob pattern that is required to expand, it includes bare word
/// And a variable which is annotated with `glob` type
Expand(String),
}
impl NuGlob {
pub fn strip_ansi_string_unlikely(self) -> Self {
match self {
NuGlob::DoNotExpand(s) => NuGlob::DoNotExpand(nu_utils::strip_ansi_string_unlikely(s)),
NuGlob::Expand(s) => NuGlob::Expand(nu_utils::strip_ansi_string_unlikely(s)),
}
}
pub fn is_expand(&self) -> bool {
matches!(self, NuGlob::Expand(..))
}
}
impl AsRef<str> for NuGlob {
fn as_ref(&self) -> &str {
match self {
NuGlob::DoNotExpand(s) | NuGlob::Expand(s) => s,
}
}
}
impl Display for NuGlob {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_ref())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/custom_value.rs | crates/nu-protocol/src/value/custom_value.rs | use std::{cmp::Ordering, fmt, path::Path};
use crate::{ShellError, Span, Spanned, Type, Value, ast::Operator, casing::Casing};
/// Trait definition for a custom [`Value`](crate::Value) type
#[typetag::serde(tag = "type")]
pub trait CustomValue: fmt::Debug + Send + Sync {
/// Custom `Clone` implementation
///
/// This can reemit a `Value::Custom(Self, span)` or materialize another representation
/// if necessary.
fn clone_value(&self, span: Span) -> Value;
//fn category(&self) -> Category;
/// The friendly type name to show for the custom value, e.g. in `describe` and in error
/// messages. This does not have to be the same as the name of the struct or enum, but
/// conventionally often is.
fn type_name(&self) -> String;
/// Converts the custom value to a base nushell value.
///
/// This imposes the requirement that you can represent the custom value in some form using the
/// Value representations that already exist in nushell
fn to_base_value(&self, span: Span) -> Result<Value, ShellError>;
/// Any representation used to downcast object to its original type
fn as_any(&self) -> &dyn std::any::Any;
/// Any representation used to downcast object to its original type (mutable reference)
fn as_mut_any(&mut self) -> &mut dyn std::any::Any;
/// Follow cell path by numeric index (e.g. rows).
///
/// Let `$val` be the custom value then these are the fields passed to this method:
/// ```text
/// βββ index [path_span]
/// β΄
/// $val.0?
/// βββ¬β β¬
/// β β°ββ optional, `true` if present
/// β°ββ self [self_span]
/// ```
fn follow_path_int(
&self,
self_span: Span,
index: usize,
path_span: Span,
optional: bool,
) -> Result<Value, ShellError> {
let _ = (self_span, index, optional);
Err(ShellError::IncompatiblePathAccess {
type_name: self.type_name(),
span: path_span,
})
}
/// Follow cell path by string key (e.g. columns).
///
/// Let `$val` be the custom value then these are the fields passed to this method:
/// ```text
/// βββ column_name [path_span]
/// β βββ casing, `Casing::Insensitive` if present
/// ββββ΄ββ β΄
/// $val.column?!
/// βββ¬β β¬
/// β β°ββ optional, `true` if present
/// β°ββ self [self_span]
/// ```
fn follow_path_string(
&self,
self_span: Span,
column_name: String,
path_span: Span,
optional: bool,
casing: Casing,
) -> Result<Value, ShellError> {
let _ = (self_span, column_name, optional, casing);
Err(ShellError::IncompatiblePathAccess {
type_name: self.type_name(),
span: path_span,
})
}
/// ordering with other value (see [`std::cmp::PartialOrd`])
fn partial_cmp(&self, _other: &Value) -> Option<Ordering> {
None
}
/// Definition of an operation between the object that implements the trait
/// and another Value.
///
/// The Operator enum is used to indicate the expected operation.
///
/// Default impl raises [`ShellError::OperatorUnsupportedType`].
fn operation(
&self,
lhs_span: Span,
operator: Operator,
op: Span,
right: &Value,
) -> Result<Value, ShellError> {
let _ = (lhs_span, right);
Err(ShellError::OperatorUnsupportedType {
op: operator,
unsupported: Type::Custom(self.type_name().into()),
op_span: op,
unsupported_span: lhs_span,
help: None,
})
}
/// Save custom value to disk.
///
/// This method is used in `save` to save a custom value to disk.
/// This is done before opening any file, so saving can be handled differently.
///
/// The default impl just returns an error.
fn save(
&self,
path: Spanned<&Path>,
value_span: Span,
save_span: Span,
) -> Result<(), ShellError> {
let _ = path;
Err(ShellError::GenericError {
error: "Cannot save custom value".into(),
msg: format!("Saving custom value {} failed", self.type_name()),
span: Some(save_span),
help: None,
inner: vec![
ShellError::GenericError {
error: "Custom value does not implement `save`".into(),
msg: format!("{} doesn't implement saving to disk", self.type_name()),
span: Some(value_span),
help: Some("Check the plugin's documentation for this value type. It might use a different way to save.".into()),
inner: vec![],
}],
})
}
/// For custom values in plugins: return `true` here if you would like to be notified when all
/// copies of this custom value are dropped in the engine.
///
/// The notification will take place via `custom_value_dropped()` on the plugin type.
///
/// The default is `false`.
fn notify_plugin_on_drop(&self) -> bool {
false
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/into_value.rs | crates/nu-protocol/src/value/into_value.rs | use crate::{Range, Record, ShellError, Span, Value, ast::CellPath, engine::Closure};
use chrono::{DateTime, FixedOffset};
use std::{
borrow::{Borrow, Cow},
collections::HashMap,
};
/// A trait for converting a value into a [`Value`].
///
/// This conversion is infallible, for fallible conversions use [`TryIntoValue`].
///
/// # Derivable
/// This trait can be used with `#[derive]`.
/// When derived on structs with named fields, the resulting value representation will use
/// [`Value::Record`], where each field of the record corresponds to a field of the struct.
///
/// By default, field names will be used as-is unless specified otherwise:
/// - If `#[nu_value(rename = "...")]` is applied to a specific field, that name is used.
/// - If `#[nu_value(rename_all = "...")]` is applied to the struct, field names will be
/// case-converted accordingly.
/// - If neither attribute is used, the original field name will be retained.
///
/// For structs with unnamed fields, the value representation will be [`Value::List`], with all
/// fields inserted into a list.
/// Unit structs will be represented as [`Value::Nothing`] since they contain no data.
///
/// For enums, the resulting value representation depends on the variant name:
/// - If `#[nu_value(rename = "...")]` is applied to a specific variant, that name is used.
/// - If `#[nu_value(rename_all = "...")]` is applied to the enum, variant names will be
/// case-converted accordingly.
/// - If neither attribute is used, variant names will default to snake_case.
///
/// Only enums with no fields may derive this trait.
/// The resulting value will be the name of the variant as a [`Value::String`].
///
/// All case options from [`heck`] are supported, as well as the values allowed by
/// [`#[serde(rename_all)]`](https://serde.rs/container-attrs.html#rename_all).
///
/// # Enum Example
/// ```
/// # use nu_protocol::{IntoValue, Value, Span, record};
/// #
/// # let span = Span::unknown();
/// #
/// #[derive(IntoValue)]
/// #[nu_value(rename_all = "COBOL-CASE")]
/// enum Bird {
/// MountainEagle,
/// ForestOwl,
/// #[nu_value(rename = "RIVER-QUACK")]
/// RiverDuck,
/// }
///
/// assert_eq!(
/// Bird::ForestOwl.into_value(span),
/// Value::string("FOREST-OWL", span)
/// );
///
/// assert_eq!(
/// Bird::RiverDuck.into_value(span),
/// Value::string("RIVER-QUACK", span)
/// );
/// ```
///
/// # Struct Example
/// ```
/// # use nu_protocol::{IntoValue, Value, Span, record};
/// #
/// # let span = Span::unknown();
/// #
/// #[derive(IntoValue)]
/// #[nu_value(rename_all = "kebab-case")]
/// struct Person {
/// first_name: String,
/// last_name: String,
/// #[nu_value(rename = "age")]
/// age_years: u32,
/// }
///
/// assert_eq!(
/// Person {
/// first_name: "John".into(),
/// last_name: "Doe".into(),
/// age_years: 42,
/// }.into_value(span),
/// Value::record(record! {
/// "first-name" => Value::string("John", span),
/// "last-name" => Value::string("Doe", span),
/// "age" => Value::int(42, span),
/// }, span)
/// );
/// ```
pub trait IntoValue: Sized {
/// Converts the given value to a [`Value`].
fn into_value(self, span: Span) -> Value;
}
// Primitive Types
impl<T, const N: usize> IntoValue for [T; N]
where
T: IntoValue,
{
fn into_value(self, span: Span) -> Value {
Vec::from(self).into_value(span)
}
}
macro_rules! primitive_into_value {
($type:ty, $method:ident) => {
primitive_into_value!($type => $type, $method);
};
($type:ty => $as_type:ty, $method:ident) => {
impl IntoValue for $type {
fn into_value(self, span: Span) -> Value {
Value::$method(<$as_type>::from(self), span)
}
}
};
}
primitive_into_value!(bool, bool);
primitive_into_value!(char, string);
primitive_into_value!(f32 => f64, float);
primitive_into_value!(f64, float);
primitive_into_value!(i8 => i64, int);
primitive_into_value!(i16 => i64, int);
primitive_into_value!(i32 => i64, int);
primitive_into_value!(i64, int);
primitive_into_value!(u8 => i64, int);
primitive_into_value!(u16 => i64, int);
primitive_into_value!(u32 => i64, int);
// u64 and usize may be truncated as Value only supports i64.
impl IntoValue for isize {
fn into_value(self, span: Span) -> Value {
Value::int(self as i64, span)
}
}
impl IntoValue for () {
fn into_value(self, span: Span) -> Value {
Value::nothing(span)
}
}
macro_rules! tuple_into_value {
($($t:ident:$n:tt),+) => {
impl<$($t),+> IntoValue for ($($t,)+) where $($t: IntoValue,)+ {
fn into_value(self, span: Span) -> Value {
let vals = vec![$(self.$n.into_value(span)),+];
Value::list(vals, span)
}
}
}
}
// Tuples in std are implemented for up to 12 elements, so we do it here too.
tuple_into_value!(T0:0);
tuple_into_value!(T0:0, T1:1);
tuple_into_value!(T0:0, T1:1, T2:2);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3, T4:4);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3, T4:4, T5:5);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7, T8:8);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7, T8:8, T9:9);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7, T8:8, T9:9, T10:10);
tuple_into_value!(T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7, T8:8, T9:9, T10:10, T11:11);
// Other std Types
impl IntoValue for String {
fn into_value(self, span: Span) -> Value {
Value::string(self, span)
}
}
impl IntoValue for &str {
fn into_value(self, span: Span) -> Value {
Value::string(self, span)
}
}
impl<T> IntoValue for Vec<T>
where
T: IntoValue,
{
fn into_value(self, span: Span) -> Value {
Value::list(self.into_iter().map(|v| v.into_value(span)).collect(), span)
}
}
impl<T> IntoValue for Box<T>
where
T: IntoValue,
{
fn into_value(self, span: Span) -> Value {
let t: T = *self;
t.into_value(span)
}
}
impl<T> IntoValue for Option<T>
where
T: IntoValue,
{
fn into_value(self, span: Span) -> Value {
match self {
Some(v) => v.into_value(span),
None => Value::nothing(span),
}
}
}
/// This blanket implementation permits the use of [`Cow<'_, B>`] ([`Cow<'_, str>`] etc) based on
/// the [IntoValue] implementation of `B`'s owned form ([str] => [String]).
///
/// It's meant to make using the [IntoValue] derive macro on types that contain [Cow] fields
/// possible.
impl<B> IntoValue for Cow<'_, B>
where
B: ?Sized + ToOwned,
B::Owned: IntoValue,
{
fn into_value(self, span: Span) -> Value {
<B::Owned as IntoValue>::into_value(self.into_owned(), span)
}
}
impl<K, V> IntoValue for HashMap<K, V>
where
K: Borrow<str> + Into<String>,
V: IntoValue,
{
fn into_value(self, span: Span) -> Value {
// The `Borrow<str>` constraint is to ensure uniqueness, as implementations of `Borrow`
// must uphold by certain properties (e.g., `(x == y) == (x.borrow() == y.borrow())`.
//
// The `Into<String>` constraint is necessary for us to convert the key into a `String`.
// Most types that implement `Borrow<str>` also implement `Into<String>`.
// Implementations of `Into` must also be lossless and value-preserving conversions.
// So, when combined with the `Borrow` constraint, this means that the converted
// `String` keys should be unique.
self.into_iter()
.map(|(k, v)| (k.into(), v.into_value(span)))
.collect::<Record>()
.into_value(span)
}
}
impl IntoValue for std::time::Duration {
fn into_value(self, span: Span) -> Value {
let val: u128 = self.as_nanos();
debug_assert!(val <= i64::MAX as u128, "duration value too large");
// Capping is the best effort here.
let val: i64 = val.try_into().unwrap_or(i64::MAX);
Value::duration(val, span)
}
}
// Nu Types
impl IntoValue for Range {
fn into_value(self, span: Span) -> Value {
Value::range(self, span)
}
}
impl IntoValue for Record {
fn into_value(self, span: Span) -> Value {
Value::record(self, span)
}
}
impl IntoValue for Closure {
fn into_value(self, span: Span) -> Value {
Value::closure(self, span)
}
}
impl IntoValue for ShellError {
fn into_value(self, span: Span) -> Value {
Value::error(self, span)
}
}
impl IntoValue for CellPath {
fn into_value(self, span: Span) -> Value {
Value::cell_path(self, span)
}
}
impl IntoValue for Value {
fn into_value(self, span: Span) -> Value {
self.with_span(span)
}
}
// Foreign Types
impl IntoValue for DateTime<FixedOffset> {
fn into_value(self, span: Span) -> Value {
Value::date(self, span)
}
}
impl IntoValue for bytes::Bytes {
fn into_value(self, span: Span) -> Value {
Value::binary(self.to_vec(), span)
}
}
// TODO: use this type for all the `into_value` methods that types implement but return a Result
/// A trait for trying to convert a value into a `Value`.
///
/// Types like streams may fail while collecting the `Value`,
/// for these types it is useful to implement a fallible variant.
///
/// This conversion is fallible, for infallible conversions use [`IntoValue`].
/// All types that implement `IntoValue` will automatically implement this trait.
pub trait TryIntoValue: Sized {
// TODO: instead of ShellError, maybe we could have a IntoValueError that implements Into<ShellError>
/// Tries to convert the given value into a `Value`.
fn try_into_value(self, span: Span) -> Result<Value, ShellError>;
}
impl<T> TryIntoValue for T
where
T: IntoValue,
{
fn try_into_value(self, span: Span) -> Result<Value, ShellError> {
Ok(self.into_value(span))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/record.rs | crates/nu-protocol/src/value/record.rs | //! Our insertion ordered map-type [`Record`]
use std::{
iter::FusedIterator,
marker::PhantomData,
ops::{Deref, DerefMut, RangeBounds},
};
use crate::{
ShellError, Span, Value,
casing::{CaseInsensitive, CaseSensitive, CaseSensitivity, Casing, WrapCased},
};
use serde::{Deserialize, Serialize, de::Visitor, ser::SerializeMap};
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Record {
inner: Vec<(String, Value)>,
}
/// A wrapper around [`Record`] that handles lookups. Whether the keys are compared case sensitively
/// or not is controlled with the `Sensitivity` parameter.
///
/// It is never actually constructed as a value and only used as a reference to an existing [`Record`].
#[repr(transparent)]
pub struct CasedRecord<Sensitivity: CaseSensitivity>(Record, PhantomData<Sensitivity>);
impl<Sensitivity: CaseSensitivity> CasedRecord<Sensitivity> {
#[inline]
const fn from_record(record: &Record) -> &Self {
// SAFETY: `CasedRecord` has the same memory layout as `Record`.
unsafe { &*(record as *const Record as *const Self) }
}
#[inline]
const fn from_record_mut(record: &mut Record) -> &mut Self {
// SAFETY: `CasedRecord` has the same memory layout as `Record`.
unsafe { &mut *(record as *mut Record as *mut Self) }
}
pub fn index_of(&self, col: impl AsRef<str>) -> Option<usize> {
let col = col.as_ref();
self.0.columns().rposition(|k| Sensitivity::eq(k, col))
}
pub fn contains(&self, col: impl AsRef<str>) -> bool {
self.index_of(col.as_ref()).is_some()
}
pub fn get(&self, col: impl AsRef<str>) -> Option<&Value> {
let index = self.index_of(col.as_ref())?;
Some(self.0.get_index(index)?.1)
}
pub fn get_mut(&mut self, col: impl AsRef<str>) -> Option<&mut Value> {
let index = self.index_of(col.as_ref())?;
Some(self.0.get_index_mut(index)?.1)
}
/// Remove single value by key and return it
pub fn remove(&mut self, col: impl AsRef<str>) -> Option<Value> {
let index = self.index_of(col.as_ref())?;
Some(self.0.remove_index(index))
}
/// Insert into the record, replacing preexisting value if found.
///
/// Returns `Some(previous_value)` if found. Else `None`
pub fn insert<K>(&mut self, col: K, val: Value) -> Option<Value>
where
K: AsRef<str> + Into<String>,
{
if let Some(curr_val) = self.get_mut(col.as_ref()) {
Some(std::mem::replace(curr_val, val))
} else {
self.0.push(col, val);
None
}
}
}
impl<'a> WrapCased for &'a Record {
type Wrapper<S: CaseSensitivity> = &'a CasedRecord<S>;
#[inline]
fn case_sensitive(self) -> Self::Wrapper<CaseSensitive> {
CasedRecord::<CaseSensitive>::from_record(self)
}
#[inline]
fn case_insensitive(self) -> Self::Wrapper<CaseInsensitive> {
CasedRecord::<CaseInsensitive>::from_record(self)
}
}
impl<'a> WrapCased for &'a mut Record {
type Wrapper<S: CaseSensitivity> = &'a mut CasedRecord<S>;
#[inline]
fn case_sensitive(self) -> Self::Wrapper<CaseSensitive> {
CasedRecord::<CaseSensitive>::from_record_mut(self)
}
#[inline]
fn case_insensitive(self) -> Self::Wrapper<CaseInsensitive> {
CasedRecord::<CaseInsensitive>::from_record_mut(self)
}
}
impl AsRef<Record> for Record {
fn as_ref(&self) -> &Record {
self
}
}
impl AsMut<Record> for Record {
fn as_mut(&mut self) -> &mut Record {
self
}
}
impl Deref for Record {
type Target = CasedRecord<CaseSensitive>;
fn deref(&self) -> &Self::Target {
self.case_sensitive()
}
}
impl DerefMut for Record {
fn deref_mut(&mut self) -> &mut Self::Target {
self.case_sensitive()
}
}
/// A wrapper around [`Record`] that affects whether key comparisons are case sensitive or not.
///
/// Implements commonly used methods of [`Record`].
pub struct DynCasedRecord<R> {
record: R,
casing: Casing,
}
impl Clone for DynCasedRecord<&Record> {
fn clone(&self) -> Self {
*self
}
}
impl Copy for DynCasedRecord<&Record> {}
impl<'a> DynCasedRecord<&'a Record> {
pub fn index_of(self, col: impl AsRef<str>) -> Option<usize> {
match self.casing {
Casing::Sensitive => self.record.case_sensitive().index_of(col.as_ref()),
Casing::Insensitive => self.record.case_insensitive().index_of(col.as_ref()),
}
}
pub fn contains(self, col: impl AsRef<str>) -> bool {
self.get(col.as_ref()).is_some()
}
pub fn get(self, col: impl AsRef<str>) -> Option<&'a Value> {
match self.casing {
Casing::Sensitive => self.record.case_sensitive().get(col.as_ref()),
Casing::Insensitive => self.record.case_insensitive().get(col.as_ref()),
}
}
}
impl<'a> DynCasedRecord<&'a mut Record> {
/// Explicit reborrowing. See [Self::reborrow_mut()]
pub fn reborrow(&self) -> DynCasedRecord<&Record> {
DynCasedRecord {
record: &*self.record,
casing: self.casing,
}
}
/// Explicit reborrowing. Using this before methods that receive `self` is necessary to avoid
/// consuming the `DynCasedRecord` instance.
///
/// ```
/// use nu_protocol::{record, record::{Record, DynCasedRecord}, Value, casing::Casing};
///
/// let mut rec = record!{
/// "A" => Value::test_nothing(),
/// "B" => Value::test_int(42),
/// "C" => Value::test_nothing(),
/// "D" => Value::test_int(42),
/// };
/// let mut cased_rec: DynCasedRecord<&mut Record> = rec.cased_mut(Casing::Insensitive);
/// ```
///
/// The following will fail to compile:
///
/// ```compile_fail
/// # use nu_protocol::{record, record::{Record, DynCasedRecord}, Value, casing::Casing};
/// # let mut rec = record!{};
/// # let mut cased_rec: DynCasedRecord<&mut Record> = rec.cased_mut(Casing::Insensitive);
/// let a = cased_rec.get_mut("a");
/// let b = cased_rec.get_mut("b");
/// ```
///
/// This is due to the fact `.get_mut()` receives `self`[^self] _by value_, which limits its use to
/// just once, unless we construct a new `DynCasedRecord`.
///
/// [^self]: Receiving `&mut self` works, but has an undesirable effect on the return value's
/// lifetime. With `Self == &'wrapper mut DynCasedRecord<&'source mut Record>`, return value's
/// lifetime will be `'wrapper` rather than `'source`.
///
/// We can create a new `DynCasedRecord<&mut Record>` from an existing one even though `&mut T` is
/// not [`Copy`]. This is accomplished with [reborrowing] which happens implicitly with native
/// references. Reborrowing also happens to be a tragically under documented feature of rust.
///
/// Though there isn't a trait for it yet, it's possible and simple to implement, it just has
/// to be called explicitly:
///
/// ```
/// # use nu_protocol::{record, record::{Record, DynCasedRecord}, Value, casing::Casing};
/// # let mut rec = record!{};
/// # let mut cased_rec: DynCasedRecord<&mut Record> = rec.cased_mut(Casing::Insensitive);
/// let a = cased_rec.reborrow_mut().get_mut("a");
/// let b = cased_rec.reborrow_mut().get_mut("b");
/// ```
///
/// [reborrowing]: https://quinedot.github.io/rust-learning/st-reborrow.html
pub fn reborrow_mut(&mut self) -> DynCasedRecord<&mut Record> {
DynCasedRecord {
record: &mut *self.record,
casing: self.casing,
}
}
pub fn get_mut(self, col: impl AsRef<str>) -> Option<&'a mut Value> {
match self.casing {
Casing::Sensitive => self.record.case_sensitive().get_mut(col.as_ref()),
Casing::Insensitive => self.record.case_insensitive().get_mut(col.as_ref()),
}
}
pub fn remove(self, col: impl AsRef<str>) -> Option<Value> {
match self.casing {
Casing::Sensitive => self.record.case_sensitive().remove(col.as_ref()),
Casing::Insensitive => self.record.case_insensitive().remove(col.as_ref()),
}
}
/// Insert into the record, replacing preexisting value if found.
///
/// Returns `Some(previous_value)` if found. Else `None`
pub fn insert<K>(self, col: K, val: Value) -> Option<Value>
where
K: AsRef<str> + Into<String>,
{
match self.casing {
Casing::Sensitive => self.record.case_sensitive().insert(col.as_ref(), val),
Casing::Insensitive => self.record.case_insensitive().insert(col.as_ref(), val),
}
}
}
impl Record {
pub fn new() -> Self {
Self::default()
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
inner: Vec::with_capacity(capacity),
}
}
pub fn cased(&self, casing: Casing) -> DynCasedRecord<&Record> {
DynCasedRecord {
record: self,
casing,
}
}
pub fn cased_mut(&mut self, casing: Casing) -> DynCasedRecord<&mut Record> {
DynCasedRecord {
record: self,
casing,
}
}
/// Create a [`Record`] from a `Vec` of columns and a `Vec` of [`Value`]s
///
/// Returns an error if `cols` and `vals` have different lengths.
///
/// For perf reasons, this will not validate the rest of the record assumptions:
/// - unique keys
pub fn from_raw_cols_vals(
cols: Vec<String>,
vals: Vec<Value>,
input_span: Span,
creation_site_span: Span,
) -> Result<Self, ShellError> {
if cols.len() == vals.len() {
let inner = cols.into_iter().zip(vals).collect();
Ok(Self { inner })
} else {
Err(ShellError::RecordColsValsMismatch {
bad_value: input_span,
creation_site: creation_site_span,
})
}
}
pub fn iter(&self) -> Iter<'_> {
self.into_iter()
}
pub fn iter_mut(&mut self) -> IterMut<'_> {
self.into_iter()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn len(&self) -> usize {
self.inner.len()
}
/// Naive push to the end of the datastructure.
///
/// <div class="warning">
/// May duplicate data!
///
/// Consider using [`CasedRecord::insert`] or [`DynCasedRecord::insert`] instead.
/// </div>
pub fn push(&mut self, col: impl Into<String>, val: Value) {
self.inner.push((col.into(), val));
}
pub fn get_index(&self, idx: usize) -> Option<(&String, &Value)> {
self.inner.get(idx).map(|(col, val): &(_, _)| (col, val))
}
pub fn get_index_mut(&mut self, idx: usize) -> Option<(&mut String, &mut Value)> {
self.inner.get_mut(idx).map(|(col, val)| (col, val))
}
/// Remove single value by index
fn remove_index(&mut self, index: usize) -> Value {
self.inner.remove(index).1
}
/// Remove elements in-place that do not satisfy `keep`
///
/// ```rust
/// use nu_protocol::{record, Value};
///
/// let mut rec = record!(
/// "a" => Value::test_nothing(),
/// "b" => Value::test_int(42),
/// "c" => Value::test_nothing(),
/// "d" => Value::test_int(42),
/// );
/// rec.retain(|_k, val| !val.is_nothing());
/// let mut iter_rec = rec.columns();
/// assert_eq!(iter_rec.next().map(String::as_str), Some("b"));
/// assert_eq!(iter_rec.next().map(String::as_str), Some("d"));
/// assert_eq!(iter_rec.next(), None);
/// ```
pub fn retain<F>(&mut self, mut keep: F)
where
F: FnMut(&str, &Value) -> bool,
{
self.retain_mut(|k, v| keep(k, v));
}
/// Remove elements in-place that do not satisfy `keep` while allowing mutation of the value.
///
/// This can for example be used to recursively prune nested records.
///
/// ```rust
/// use nu_protocol::{record, Record, Value};
///
/// fn remove_foo_recursively(val: &mut Value) {
/// if let Value::Record {val, ..} = val {
/// val.to_mut().retain_mut(keep_non_foo);
/// }
/// }
///
/// fn keep_non_foo(k: &str, v: &mut Value) -> bool {
/// if k == "foo" {
/// return false;
/// }
/// remove_foo_recursively(v);
/// true
/// }
///
/// let mut test = Value::test_record(record!(
/// "foo" => Value::test_nothing(),
/// "bar" => Value::test_record(record!(
/// "foo" => Value::test_nothing(),
/// "baz" => Value::test_nothing(),
/// ))
/// ));
///
/// remove_foo_recursively(&mut test);
/// let expected = Value::test_record(record!(
/// "bar" => Value::test_record(record!(
/// "baz" => Value::test_nothing(),
/// ))
/// ));
/// assert_eq!(test, expected);
/// ```
pub fn retain_mut<F>(&mut self, mut keep: F)
where
F: FnMut(&str, &mut Value) -> bool,
{
self.inner.retain_mut(|(col, val)| keep(col, val));
}
/// Truncate record to the first `len` elements.
///
/// `len > self.len()` will be ignored
///
/// ```rust
/// use nu_protocol::{record, Value};
///
/// let mut rec = record!(
/// "a" => Value::test_nothing(),
/// "b" => Value::test_int(42),
/// "c" => Value::test_nothing(),
/// "d" => Value::test_int(42),
/// );
/// rec.truncate(42); // this is fine
/// assert_eq!(rec.columns().map(String::as_str).collect::<String>(), "abcd");
/// rec.truncate(2); // truncate
/// assert_eq!(rec.columns().map(String::as_str).collect::<String>(), "ab");
/// rec.truncate(0); // clear the record
/// assert_eq!(rec.len(), 0);
/// ```
pub fn truncate(&mut self, len: usize) {
self.inner.truncate(len);
}
pub fn columns(&self) -> Columns<'_> {
Columns {
iter: self.inner.iter(),
}
}
pub fn into_columns(self) -> IntoColumns {
IntoColumns {
iter: self.inner.into_iter(),
}
}
pub fn values(&self) -> Values<'_> {
Values {
iter: self.inner.iter(),
}
}
pub fn into_values(self) -> IntoValues {
IntoValues {
iter: self.inner.into_iter(),
}
}
/// Obtain an iterator to remove elements in `range`
///
/// Elements not consumed from the iterator will be dropped
///
/// ```rust
/// use nu_protocol::{record, Value};
///
/// let mut rec = record!(
/// "a" => Value::test_nothing(),
/// "b" => Value::test_int(42),
/// "c" => Value::test_string("foo"),
/// );
/// {
/// let mut drainer = rec.drain(1..);
/// assert_eq!(drainer.next(), Some(("b".into(), Value::test_int(42))));
/// // Dropping the `Drain`
/// }
/// let mut rec_iter = rec.into_iter();
/// assert_eq!(rec_iter.next(), Some(("a".into(), Value::test_nothing())));
/// assert_eq!(rec_iter.next(), None);
/// ```
pub fn drain<R>(&mut self, range: R) -> Drain<'_>
where
R: RangeBounds<usize> + Clone,
{
Drain {
iter: self.inner.drain(range),
}
}
/// Sort the record by its columns.
///
/// ```rust
/// use nu_protocol::{record, Value};
///
/// let mut rec = record!(
/// "c" => Value::test_string("foo"),
/// "b" => Value::test_int(42),
/// "a" => Value::test_nothing(),
/// );
///
/// rec.sort_cols();
///
/// assert_eq!(
/// Value::test_record(rec),
/// Value::test_record(record!(
/// "a" => Value::test_nothing(),
/// "b" => Value::test_int(42),
/// "c" => Value::test_string("foo"),
/// ))
/// );
/// ```
pub fn sort_cols(&mut self) {
self.inner.sort_by(|(k1, _), (k2, _)| k1.cmp(k2))
}
}
impl Serialize for Record {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut map = serializer.serialize_map(Some(self.len()))?;
for (k, v) in self {
map.serialize_entry(k, v)?;
}
map.end()
}
}
impl<'de> Deserialize<'de> for Record {
/// Special deserialization implementation that turns a map-pattern into a [`Record`]
///
/// Denies duplicate keys
///
/// ```rust
/// use serde_json::{from_str, Result};
/// use nu_protocol::{Record, Value, record};
///
/// // A `Record` in json is a Record with a packed `Value`
/// // The `Value` record has a single key indicating its type and the inner record describing
/// // its representation of value and the associated `Span`
/// let ok = r#"{"a": {"Int": {"val": 42, "span": {"start": 0, "end": 0}}},
/// "b": {"Int": {"val": 37, "span": {"start": 0, "end": 0}}}}"#;
/// let ok_rec: Record = from_str(ok).unwrap();
/// assert_eq!(Value::test_record(ok_rec),
/// Value::test_record(record!{"a" => Value::test_int(42),
/// "b" => Value::test_int(37)}));
/// // A repeated key will lead to a deserialization error
/// let bad = r#"{"a": {"Int": {"val": 42, "span": {"start": 0, "end": 0}}},
/// "a": {"Int": {"val": 37, "span": {"start": 0, "end": 0}}}}"#;
/// let bad_rec: Result<Record> = from_str(bad);
/// assert!(bad_rec.is_err());
/// ```
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_map(RecordVisitor)
}
}
struct RecordVisitor;
impl<'de> Visitor<'de> for RecordVisitor {
type Value = Record;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a nushell `Record` mapping string keys/columns to nushell `Value`")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut record = Record::with_capacity(map.size_hint().unwrap_or(0));
while let Some((key, value)) = map.next_entry::<String, Value>()? {
if record.insert(key, value).is_some() {
return Err(serde::de::Error::custom(
"invalid entry, duplicate keys are not allowed for `Record`",
));
}
}
Ok(record)
}
}
impl FromIterator<(String, Value)> for Record {
fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
// TODO: should this check for duplicate keys/columns?
Self {
inner: iter.into_iter().collect(),
}
}
}
impl Extend<(String, Value)> for Record {
fn extend<T: IntoIterator<Item = (String, Value)>>(&mut self, iter: T) {
for (k, v) in iter {
// TODO: should this .insert with a check?
self.push(k, v)
}
}
}
pub struct IntoIter {
iter: std::vec::IntoIter<(String, Value)>,
}
impl Iterator for IntoIter {
type Item = (String, Value);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl DoubleEndedIterator for IntoIter {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back()
}
}
impl ExactSizeIterator for IntoIter {
fn len(&self) -> usize {
self.iter.len()
}
}
impl FusedIterator for IntoIter {}
impl IntoIterator for Record {
type Item = (String, Value);
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
iter: self.inner.into_iter(),
}
}
}
pub struct Iter<'a> {
iter: std::slice::Iter<'a, (String, Value)>,
}
impl<'a> Iterator for Iter<'a> {
type Item = (&'a String, &'a Value);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(col, val): &(_, _)| (col, val))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl DoubleEndedIterator for Iter<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|(col, val): &(_, _)| (col, val))
}
}
impl ExactSizeIterator for Iter<'_> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl FusedIterator for Iter<'_> {}
impl<'a> IntoIterator for &'a Record {
type Item = (&'a String, &'a Value);
type IntoIter = Iter<'a>;
fn into_iter(self) -> Self::IntoIter {
Iter {
iter: self.inner.iter(),
}
}
}
pub struct IterMut<'a> {
iter: std::slice::IterMut<'a, (String, Value)>,
}
impl<'a> Iterator for IterMut<'a> {
type Item = (&'a String, &'a mut Value);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(col, val)| (&*col, val))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl DoubleEndedIterator for IterMut<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|(col, val)| (&*col, val))
}
}
impl ExactSizeIterator for IterMut<'_> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl FusedIterator for IterMut<'_> {}
impl<'a> IntoIterator for &'a mut Record {
type Item = (&'a String, &'a mut Value);
type IntoIter = IterMut<'a>;
fn into_iter(self) -> Self::IntoIter {
IterMut {
iter: self.inner.iter_mut(),
}
}
}
pub struct Columns<'a> {
iter: std::slice::Iter<'a, (String, Value)>,
}
impl<'a> Iterator for Columns<'a> {
type Item = &'a String;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(col, _)| col)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl DoubleEndedIterator for Columns<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|(col, _)| col)
}
}
impl ExactSizeIterator for Columns<'_> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl FusedIterator for Columns<'_> {}
pub struct IntoColumns {
iter: std::vec::IntoIter<(String, Value)>,
}
impl Iterator for IntoColumns {
type Item = String;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(col, _)| col)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl DoubleEndedIterator for IntoColumns {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|(col, _)| col)
}
}
impl ExactSizeIterator for IntoColumns {
fn len(&self) -> usize {
self.iter.len()
}
}
impl FusedIterator for IntoColumns {}
pub struct Values<'a> {
iter: std::slice::Iter<'a, (String, Value)>,
}
impl<'a> Iterator for Values<'a> {
type Item = &'a Value;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(_, val)| val)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl DoubleEndedIterator for Values<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|(_, val)| val)
}
}
impl ExactSizeIterator for Values<'_> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl FusedIterator for Values<'_> {}
pub struct IntoValues {
iter: std::vec::IntoIter<(String, Value)>,
}
impl Iterator for IntoValues {
type Item = Value;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|(_, val)| val)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl DoubleEndedIterator for IntoValues {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|(_, val)| val)
}
}
impl ExactSizeIterator for IntoValues {
fn len(&self) -> usize {
self.iter.len()
}
}
impl FusedIterator for IntoValues {}
pub struct Drain<'a> {
iter: std::vec::Drain<'a, (String, Value)>,
}
impl Iterator for Drain<'_> {
type Item = (String, Value);
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl DoubleEndedIterator for Drain<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back()
}
}
impl ExactSizeIterator for Drain<'_> {
fn len(&self) -> usize {
self.iter.len()
}
}
impl FusedIterator for Drain<'_> {}
#[macro_export]
macro_rules! record {
// The macro only compiles if the number of columns equals the number of values,
// so it's safe to call `unwrap` below.
{$($col:expr => $val:expr),+ $(,)?} => {
$crate::Record::from_raw_cols_vals(
::std::vec![$($col.into(),)+],
::std::vec![$($val,)+],
$crate::Span::unknown(),
$crate::Span::unknown(),
).unwrap()
};
{} => {
$crate::Record::new()
};
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/mod.rs | crates/nu-protocol/src/value/mod.rs | mod custom_value;
mod duration;
mod filesize;
mod from_value;
mod glob;
mod into_value;
mod range;
#[cfg(test)]
mod test_derive;
pub mod record;
pub use custom_value::CustomValue;
pub use duration::*;
pub use filesize::*;
pub use from_value::FromValue;
pub use glob::*;
pub use into_value::{IntoValue, TryIntoValue};
pub use nu_utils::MultiLife;
pub use range::{FloatRange, IntRange, Range};
pub use record::Record;
use crate::{
BlockId, Config, ShellError, Signals, Span, Type,
ast::{Bits, Boolean, CellPath, Comparison, Math, Operator, PathMember},
did_you_mean,
engine::{Closure, EngineState},
};
use chrono::{DateTime, Datelike, Duration, FixedOffset, Local, Locale, TimeZone};
use chrono_humanize::HumanTime;
use fancy_regex::Regex;
use nu_utils::{
ObviousFloat, SharedCow, contains_emoji,
locale::{LOCALE_OVERRIDE_ENV_VAR, get_system_locale_string},
};
use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
cmp::Ordering,
fmt::{Debug, Display, Write},
ops::{Bound, ControlFlow},
path::PathBuf,
};
/// Core structured values that pass through the pipeline in Nushell.
// NOTE: Please do not reorder these enum cases without thinking through the
// impact on the PartialOrd implementation and the global sort order
// NOTE: All variants are marked as `non_exhaustive` to prevent them
// from being constructed (outside of this crate) with the struct
// expression syntax. This makes using the constructor methods the
// only way to construct `Value`'s
#[derive(Debug, Serialize, Deserialize)]
pub enum Value {
#[non_exhaustive]
Bool {
val: bool,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Int {
val: i64,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Float {
val: f64,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
String {
val: String,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Glob {
val: String,
no_expand: bool,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Filesize {
val: Filesize,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Duration {
/// The duration in nanoseconds.
val: i64,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Date {
val: DateTime<FixedOffset>,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Range {
val: Box<Range>,
#[serde(skip)]
signals: Option<Signals>,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Record {
val: SharedCow<Record>,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
List {
vals: Vec<Value>,
#[serde(skip)]
signals: Option<Signals>,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Closure {
val: Box<Closure>,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Error {
error: Box<ShellError>,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Binary {
val: Vec<u8>,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
CellPath {
val: CellPath,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Custom {
val: Box<dyn CustomValue>,
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
#[non_exhaustive]
Nothing {
/// note: spans are being refactored out of Value
/// please use .span() instead of matching this span value
#[serde(rename = "span")]
internal_span: Span,
},
}
// This is to document/enforce the size of `Value` in bytes.
// We should try to avoid increasing the size of `Value`,
// and PRs that do so will have to change the number below so that it's noted in review.
const _: () = assert!(std::mem::size_of::<Value>() <= 56);
impl Clone for Value {
fn clone(&self) -> Self {
match self {
Value::Bool { val, internal_span } => Value::bool(*val, *internal_span),
Value::Int { val, internal_span } => Value::int(*val, *internal_span),
Value::Filesize { val, internal_span } => Value::Filesize {
val: *val,
internal_span: *internal_span,
},
Value::Duration { val, internal_span } => Value::Duration {
val: *val,
internal_span: *internal_span,
},
Value::Date { val, internal_span } => Value::Date {
val: *val,
internal_span: *internal_span,
},
Value::Range {
val,
signals,
internal_span,
} => Value::Range {
val: val.clone(),
signals: signals.clone(),
internal_span: *internal_span,
},
Value::Float { val, internal_span } => Value::float(*val, *internal_span),
Value::String { val, internal_span } => Value::String {
val: val.clone(),
internal_span: *internal_span,
},
Value::Glob {
val,
no_expand: quoted,
internal_span,
} => Value::Glob {
val: val.clone(),
no_expand: *quoted,
internal_span: *internal_span,
},
Value::Record { val, internal_span } => Value::Record {
val: val.clone(),
internal_span: *internal_span,
},
Value::List {
vals,
signals,
internal_span,
} => Value::List {
vals: vals.clone(),
signals: signals.clone(),
internal_span: *internal_span,
},
Value::Closure { val, internal_span } => Value::Closure {
val: val.clone(),
internal_span: *internal_span,
},
Value::Nothing { internal_span } => Value::Nothing {
internal_span: *internal_span,
},
Value::Error {
error,
internal_span,
} => Value::Error {
error: error.clone(),
internal_span: *internal_span,
},
Value::Binary { val, internal_span } => Value::Binary {
val: val.clone(),
internal_span: *internal_span,
},
Value::CellPath { val, internal_span } => Value::CellPath {
val: val.clone(),
internal_span: *internal_span,
},
Value::Custom { val, internal_span } => val.clone_value(*internal_span),
}
}
}
impl Value {
fn cant_convert_to<T>(&self, typ: &str) -> Result<T, ShellError> {
Err(ShellError::CantConvert {
to_type: typ.into(),
from_type: self.get_type().to_string(),
span: self.span(),
help: None,
})
}
/// Returns the inner `bool` value or an error if this `Value` is not a bool
pub fn as_bool(&self) -> Result<bool, ShellError> {
if let Value::Bool { val, .. } = self {
Ok(*val)
} else {
self.cant_convert_to("boolean")
}
}
/// Returns the inner `i64` value or an error if this `Value` is not an int
pub fn as_int(&self) -> Result<i64, ShellError> {
if let Value::Int { val, .. } = self {
Ok(*val)
} else {
self.cant_convert_to("int")
}
}
/// Returns the inner `f64` value or an error if this `Value` is not a float
pub fn as_float(&self) -> Result<f64, ShellError> {
if let Value::Float { val, .. } = self {
Ok(*val)
} else {
self.cant_convert_to("float")
}
}
/// Returns this `Value` converted to a `f64` or an error if it cannot be converted
///
/// Only the following `Value` cases will return an `Ok` result:
/// - `Int`
/// - `Float`
///
/// ```
/// # use nu_protocol::Value;
/// for val in Value::test_values() {
/// assert_eq!(
/// matches!(val, Value::Float { .. } | Value::Int { .. }),
/// val.coerce_float().is_ok(),
/// );
/// }
/// ```
pub fn coerce_float(&self) -> Result<f64, ShellError> {
match self {
Value::Float { val, .. } => Ok(*val),
Value::Int { val, .. } => Ok(*val as f64),
val => val.cant_convert_to("float"),
}
}
/// Returns the inner `i64` filesize value or an error if this `Value` is not a filesize
pub fn as_filesize(&self) -> Result<Filesize, ShellError> {
if let Value::Filesize { val, .. } = self {
Ok(*val)
} else {
self.cant_convert_to("filesize")
}
}
/// Returns the inner `i64` duration value or an error if this `Value` is not a duration
pub fn as_duration(&self) -> Result<i64, ShellError> {
if let Value::Duration { val, .. } = self {
Ok(*val)
} else {
self.cant_convert_to("duration")
}
}
/// Returns the inner [`DateTime`] value or an error if this `Value` is not a date
pub fn as_date(&self) -> Result<DateTime<FixedOffset>, ShellError> {
if let Value::Date { val, .. } = self {
Ok(*val)
} else {
self.cant_convert_to("datetime")
}
}
/// Returns a reference to the inner [`Range`] value or an error if this `Value` is not a range
pub fn as_range(&self) -> Result<Range, ShellError> {
if let Value::Range { val, .. } = self {
Ok(**val)
} else {
self.cant_convert_to("range")
}
}
/// Unwraps the inner [`Range`] value or returns an error if this `Value` is not a range
pub fn into_range(self) -> Result<Range, ShellError> {
if let Value::Range { val, .. } = self {
Ok(*val)
} else {
self.cant_convert_to("range")
}
}
/// Returns a reference to the inner `str` value or an error if this `Value` is not a string
pub fn as_str(&self) -> Result<&str, ShellError> {
if let Value::String { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("string")
}
}
/// Unwraps the inner `String` value or returns an error if this `Value` is not a string
pub fn into_string(self) -> Result<String, ShellError> {
if let Value::String { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("string")
}
}
/// Returns this `Value` converted to a `str` or an error if it cannot be converted
///
/// Only the following `Value` cases will return an `Ok` result:
/// - `Bool`
/// - `Int`
/// - `Float`
/// - `String`
/// - `Glob`
/// - `Binary` (only if valid utf-8)
/// - `Date`
///
/// ```
/// # use nu_protocol::Value;
/// for val in Value::test_values() {
/// assert_eq!(
/// matches!(
/// val,
/// Value::Bool { .. }
/// | Value::Int { .. }
/// | Value::Float { .. }
/// | Value::String { .. }
/// | Value::Glob { .. }
/// | Value::Binary { .. }
/// | Value::Date { .. }
/// ),
/// val.coerce_str().is_ok(),
/// );
/// }
/// ```
pub fn coerce_str(&self) -> Result<Cow<'_, str>, ShellError> {
match self {
Value::Bool { val, .. } => Ok(Cow::Owned(val.to_string())),
Value::Int { val, .. } => Ok(Cow::Owned(val.to_string())),
Value::Float { val, .. } => Ok(Cow::Owned(val.to_string())),
Value::String { val, .. } => Ok(Cow::Borrowed(val)),
Value::Glob { val, .. } => Ok(Cow::Borrowed(val)),
Value::Binary { val, .. } => match std::str::from_utf8(val) {
Ok(s) => Ok(Cow::Borrowed(s)),
Err(_) => self.cant_convert_to("string"),
},
Value::Date { val, .. } => Ok(Cow::Owned(
val.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
)),
val => val.cant_convert_to("string"),
}
}
/// Returns this `Value` converted to a `String` or an error if it cannot be converted
///
/// # Note
/// This function is equivalent to `value.coerce_str().map(Cow::into_owned)`
/// which might allocate a new `String`.
///
/// To avoid this allocation, prefer [`coerce_str`](Self::coerce_str)
/// if you do not need an owned `String`,
/// or [`coerce_into_string`](Self::coerce_into_string)
/// if you do not need to keep the original `Value` around.
///
/// Only the following `Value` cases will return an `Ok` result:
/// - `Bool`
/// - `Int`
/// - `Float`
/// - `String`
/// - `Glob`
/// - `Binary` (only if valid utf-8)
/// - `Date`
///
/// ```
/// # use nu_protocol::Value;
/// for val in Value::test_values() {
/// assert_eq!(
/// matches!(
/// val,
/// Value::Bool { .. }
/// | Value::Int { .. }
/// | Value::Float { .. }
/// | Value::String { .. }
/// | Value::Glob { .. }
/// | Value::Binary { .. }
/// | Value::Date { .. }
/// ),
/// val.coerce_string().is_ok(),
/// );
/// }
/// ```
pub fn coerce_string(&self) -> Result<String, ShellError> {
self.coerce_str().map(Cow::into_owned)
}
/// Returns this `Value` converted to a `String` or an error if it cannot be converted
///
/// Only the following `Value` cases will return an `Ok` result:
/// - `Bool`
/// - `Int`
/// - `Float`
/// - `String`
/// - `Glob`
/// - `Binary` (only if valid utf-8)
/// - `Date`
///
/// ```
/// # use nu_protocol::Value;
/// for val in Value::test_values() {
/// assert_eq!(
/// matches!(
/// val,
/// Value::Bool { .. }
/// | Value::Int { .. }
/// | Value::Float { .. }
/// | Value::String { .. }
/// | Value::Glob { .. }
/// | Value::Binary { .. }
/// | Value::Date { .. }
/// ),
/// val.coerce_into_string().is_ok(),
/// );
/// }
/// ```
pub fn coerce_into_string(self) -> Result<String, ShellError> {
let span = self.span();
match self {
Value::Bool { val, .. } => Ok(val.to_string()),
Value::Int { val, .. } => Ok(val.to_string()),
Value::Float { val, .. } => Ok(val.to_string()),
Value::String { val, .. } => Ok(val),
Value::Glob { val, .. } => Ok(val),
Value::Binary { val, .. } => match String::from_utf8(val) {
Ok(s) => Ok(s),
Err(err) => Value::binary(err.into_bytes(), span).cant_convert_to("string"),
},
Value::Date { val, .. } => Ok(val.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)),
val => val.cant_convert_to("string"),
}
}
/// Returns this `Value` as a `char` or an error if it is not a single character string
pub fn as_char(&self) -> Result<char, ShellError> {
let span = self.span();
if let Value::String { val, .. } = self {
let mut chars = val.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => Ok(c),
_ => Err(ShellError::MissingParameter {
param_name: "single character separator".into(),
span,
}),
}
} else {
self.cant_convert_to("char")
}
}
/// Converts this `Value` to a `PathBuf` or returns an error if it is not a string
pub fn to_path(&self) -> Result<PathBuf, ShellError> {
if let Value::String { val, .. } = self {
Ok(PathBuf::from(val))
} else {
self.cant_convert_to("path")
}
}
/// Returns a reference to the inner [`Record`] value or an error if this `Value` is not a record
pub fn as_record(&self) -> Result<&Record, ShellError> {
if let Value::Record { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("record")
}
}
/// Unwraps the inner [`Record`] value or returns an error if this `Value` is not a record
pub fn into_record(self) -> Result<Record, ShellError> {
if let Value::Record { val, .. } = self {
Ok(val.into_owned())
} else {
self.cant_convert_to("record")
}
}
/// Returns a reference to the inner list slice or an error if this `Value` is not a list
pub fn as_list(&self) -> Result<&[Value], ShellError> {
if let Value::List { vals, .. } = self {
Ok(vals)
} else {
self.cant_convert_to("list")
}
}
/// Unwraps the inner list `Vec` or returns an error if this `Value` is not a list
pub fn into_list(self) -> Result<Vec<Value>, ShellError> {
if let Value::List { vals, .. } = self {
Ok(vals)
} else {
self.cant_convert_to("list")
}
}
/// Returns a reference to the inner [`Closure`] value or an error if this `Value` is not a closure
pub fn as_closure(&self) -> Result<&Closure, ShellError> {
if let Value::Closure { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("closure")
}
}
/// Unwraps the inner [`Closure`] value or returns an error if this `Value` is not a closure
pub fn into_closure(self) -> Result<Closure, ShellError> {
if let Value::Closure { val, .. } = self {
Ok(*val)
} else {
self.cant_convert_to("closure")
}
}
/// Returns a reference to the inner binary slice or an error if this `Value` is not a binary value
pub fn as_binary(&self) -> Result<&[u8], ShellError> {
if let Value::Binary { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("binary")
}
}
/// Unwraps the inner binary `Vec` or returns an error if this `Value` is not a binary value
pub fn into_binary(self) -> Result<Vec<u8>, ShellError> {
if let Value::Binary { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("binary")
}
}
/// Returns this `Value` as a `u8` slice or an error if it cannot be converted
///
/// Prefer [`coerce_into_binary`](Self::coerce_into_binary)
/// if you do not need to keep the original `Value` around.
///
/// Only the following `Value` cases will return an `Ok` result:
/// - `Binary`
/// - `String`
///
/// ```
/// # use nu_protocol::Value;
/// for val in Value::test_values() {
/// assert_eq!(
/// matches!(val, Value::Binary { .. } | Value::String { .. }),
/// val.coerce_binary().is_ok(),
/// );
/// }
/// ```
pub fn coerce_binary(&self) -> Result<&[u8], ShellError> {
match self {
Value::Binary { val, .. } => Ok(val),
Value::String { val, .. } => Ok(val.as_bytes()),
val => val.cant_convert_to("binary"),
}
}
/// Returns this `Value` as a `Vec<u8>` or an error if it cannot be converted
///
/// Only the following `Value` cases will return an `Ok` result:
/// - `Binary`
/// - `String`
///
/// ```
/// # use nu_protocol::Value;
/// for val in Value::test_values() {
/// assert_eq!(
/// matches!(val, Value::Binary { .. } | Value::String { .. }),
/// val.coerce_into_binary().is_ok(),
/// );
/// }
/// ```
pub fn coerce_into_binary(self) -> Result<Vec<u8>, ShellError> {
match self {
Value::Binary { val, .. } => Ok(val),
Value::String { val, .. } => Ok(val.into_bytes()),
val => val.cant_convert_to("binary"),
}
}
/// Returns a reference to the inner [`CellPath`] value or an error if this `Value` is not a cell path
pub fn as_cell_path(&self) -> Result<&CellPath, ShellError> {
if let Value::CellPath { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("cell path")
}
}
/// Unwraps the inner [`CellPath`] value or returns an error if this `Value` is not a cell path
pub fn into_cell_path(self) -> Result<CellPath, ShellError> {
if let Value::CellPath { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("cell path")
}
}
/// Interprets this `Value` as a boolean based on typical conventions for environment values.
///
/// The following rules are used:
/// - Values representing `false`:
/// - Empty strings or strings that equal to "false" in any case
/// - The number `0` (as an integer, float or string)
/// - `Nothing`
/// - Explicit boolean `false`
/// - Values representing `true`:
/// - Non-zero numbers (integer or float)
/// - Non-empty strings
/// - Explicit boolean `true`
///
/// For all other, more complex variants of [`Value`], the function cannot determine a
/// boolean representation and returns `Err`.
pub fn coerce_bool(&self) -> Result<bool, ShellError> {
match self {
Value::Bool { val: false, .. } | Value::Int { val: 0, .. } | Value::Nothing { .. } => {
Ok(false)
}
Value::Float { val, .. } if val <= &f64::EPSILON => Ok(false),
Value::String { val, .. } => match val.trim().to_ascii_lowercase().as_str() {
"" | "0" | "false" => Ok(false),
_ => Ok(true),
},
Value::Bool { .. } | Value::Int { .. } | Value::Float { .. } => Ok(true),
_ => self.cant_convert_to("bool"),
}
}
/// Returns a reference to the inner [`CustomValue`] trait object or an error if this `Value` is not a custom value
pub fn as_custom_value(&self) -> Result<&dyn CustomValue, ShellError> {
if let Value::Custom { val, .. } = self {
Ok(val.as_ref())
} else {
self.cant_convert_to("custom value")
}
}
/// Unwraps the inner [`CustomValue`] trait object or returns an error if this `Value` is not a custom value
pub fn into_custom_value(self) -> Result<Box<dyn CustomValue>, ShellError> {
if let Value::Custom { val, .. } = self {
Ok(val)
} else {
self.cant_convert_to("custom value")
}
}
/// Get the span for the current value
pub fn span(&self) -> Span {
match self {
Value::Bool { internal_span, .. }
| Value::Int { internal_span, .. }
| Value::Float { internal_span, .. }
| Value::Filesize { internal_span, .. }
| Value::Duration { internal_span, .. }
| Value::Date { internal_span, .. }
| Value::Range { internal_span, .. }
| Value::String { internal_span, .. }
| Value::Glob { internal_span, .. }
| Value::Record { internal_span, .. }
| Value::List { internal_span, .. }
| Value::Closure { internal_span, .. }
| Value::Nothing { internal_span, .. }
| Value::Binary { internal_span, .. }
| Value::CellPath { internal_span, .. }
| Value::Custom { internal_span, .. }
| Value::Error { internal_span, .. } => *internal_span,
}
}
/// Set the value's span to a new span
pub fn set_span(&mut self, new_span: Span) {
match self {
Value::Bool { internal_span, .. }
| Value::Int { internal_span, .. }
| Value::Float { internal_span, .. }
| Value::Filesize { internal_span, .. }
| Value::Duration { internal_span, .. }
| Value::Date { internal_span, .. }
| Value::Range { internal_span, .. }
| Value::String { internal_span, .. }
| Value::Glob { internal_span, .. }
| Value::Record { internal_span, .. }
| Value::List { internal_span, .. }
| Value::Closure { internal_span, .. }
| Value::Nothing { internal_span, .. }
| Value::Binary { internal_span, .. }
| Value::CellPath { internal_span, .. }
| Value::Custom { internal_span, .. } => *internal_span = new_span,
Value::Error { .. } => (),
}
}
/// Update the value with a new span
pub fn with_span(mut self, new_span: Span) -> Value {
self.set_span(new_span);
self
}
/// Get the type of the current Value
pub fn get_type(&self) -> Type {
match self {
Value::Bool { .. } => Type::Bool,
Value::Int { .. } => Type::Int,
Value::Float { .. } => Type::Float,
Value::Filesize { .. } => Type::Filesize,
Value::Duration { .. } => Type::Duration,
Value::Date { .. } => Type::Date,
Value::Range { .. } => Type::Range,
Value::String { .. } => Type::String,
Value::Glob { .. } => Type::Glob,
Value::Record { val, .. } => {
Type::Record(val.iter().map(|(x, y)| (x.clone(), y.get_type())).collect())
}
Value::List { vals, .. } => {
let ty = Type::supertype_of(vals.iter().map(Value::get_type)).unwrap_or(Type::Any);
match ty {
Type::Record(columns) => Type::Table(columns),
ty => Type::list(ty),
}
}
Value::Nothing { .. } => Type::Nothing,
Value::Closure { .. } => Type::Closure,
Value::Error { .. } => Type::Error,
Value::Binary { .. } => Type::Binary,
Value::CellPath { .. } => Type::CellPath,
Value::Custom { val, .. } => Type::Custom(val.type_name().into()),
}
}
/// Determine of the [`Value`] is a [subtype](https://en.wikipedia.org/wiki/Subtyping) of `other`
///
/// If you have a [`Value`], this method should always be used over chaining [`Value::get_type`] with [`Type::is_subtype_of`](crate::Type::is_subtype_of).
///
/// This method is able to leverage that information encoded in a `Value` to provide more accurate
/// type comparison than if one were to collect the type into [`Type`](crate::Type) value with [`Value::get_type`].
///
/// Empty lists are considered subtypes of all `list<T>` types.
///
/// Lists of mixed records where some column is present in all record is a subtype of `table<column>`.
/// For example, `[{a: 1, b: 2}, {a: 1}]` is a subtype of `table<a: int>` (but not `table<a: int, b: int>`).
///
/// See also: [`PipelineData::is_subtype_of`](crate::PipelineData::is_subtype_of)
pub fn is_subtype_of(&self, other: &Type) -> bool {
// records are structurally typed
let record_compatible = |val: &Value, other: &[(String, Type)]| match val {
Value::Record { val, .. } => other
.iter()
.all(|(key, ty)| val.get(key).is_some_and(|inner| inner.is_subtype_of(ty))),
_ => false,
};
// All cases matched explicitly to ensure this does not accidentally allocate `Type` if any composite types are introduced in the future
match (self, other) {
(_, Type::Any) => true,
(val, Type::OneOf(types)) => types.iter().any(|t| val.is_subtype_of(t)),
// `Type` allocation for scalar types is trivial
(
Value::Bool { .. }
| Value::Int { .. }
| Value::Float { .. }
| Value::String { .. }
| Value::Glob { .. }
| Value::Filesize { .. }
| Value::Duration { .. }
| Value::Date { .. }
| Value::Range { .. }
| Value::Closure { .. }
| Value::Error { .. }
| Value::Binary { .. }
| Value::CellPath { .. }
| Value::Nothing { .. },
_,
) => self.get_type().is_subtype_of(other),
// matching composite types
(val @ Value::Record { .. }, Type::Record(inner)) => record_compatible(val, inner),
(Value::List { vals, .. }, Type::List(inner)) => {
vals.iter().all(|val| val.is_subtype_of(inner))
}
(Value::List { vals, .. }, Type::Table(inner)) => {
vals.iter().all(|val| record_compatible(val, inner))
}
(Value::Custom { val, .. }, Type::Custom(inner)) => val.type_name() == **inner,
// non-matching composite types
(Value::Record { .. } | Value::List { .. } | Value::Custom { .. }, _) => false,
}
}
pub fn get_data_by_key(&self, name: &str) -> Option<Value> {
let span = self.span();
match self {
Value::Record { val, .. } => val.get(name).cloned(),
Value::List { vals, .. } => {
let out = vals
.iter()
.map(|item| {
item.as_record()
.ok()
.and_then(|val| val.get(name).cloned())
.unwrap_or(Value::nothing(span))
})
.collect::<Vec<_>>();
if !out.is_empty() {
Some(Value::list(out, span))
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/from_value.rs | crates/nu-protocol/src/value/from_value.rs | use crate::{
NuGlob, Range, Record, ShellError, Span, Spanned, Type, Value,
ast::{CellPath, PathMember},
casing::Casing,
engine::Closure,
};
use chrono::{DateTime, FixedOffset};
use std::{
any,
borrow::Cow,
cmp::Ordering,
collections::{HashMap, VecDeque},
fmt,
num::{
NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroIsize, NonZeroU16, NonZeroU32,
NonZeroU64, NonZeroUsize,
},
path::PathBuf,
str::FromStr,
};
/// A trait for loading a value from a [`Value`].
///
/// # Derivable
/// This trait can be used with `#[derive]`.
///
/// When derived on structs with named fields, it expects a [`Value::Record`] where each field of
/// the struct maps to a corresponding field in the record.
///
/// - If `#[nu_value(rename = "...")]` is applied to a field, that name will be used as the key in
/// the record.
/// - If `#[nu_value(rename_all = "...")]` is applied on the container (struct) the key of the
/// field will be case-converted accordingly.
/// - If neither attribute is applied, the field name is used as is.
/// - If `#[nu_value(default)]` is applied to a field, the field type's [`Default`] implementation
/// will be used if the corresponding record field is missing
///
/// Supported case conversions include those provided by [`heck`], such as
/// "snake_case", "kebab-case", "PascalCase", and others.
/// Additionally, all values accepted by
/// [`#[serde(rename_all = "...")]`](https://serde.rs/container-attrs.html#rename_all) are valid here.
///
/// For structs with unnamed fields, it expects a [`Value::List`], and the fields are populated in
/// the order they appear in the list.
/// Unit structs expect a [`Value::Nothing`], as they contain no data.
/// Attempting to convert from a non-matching `Value` type will result in an error.
///
/// Only enums with no fields may derive this trait.
/// The expected value representation will be the name of the variant as a [`Value::String`].
///
/// - If `#[nu_value(rename = "...")]` is applied to a variant, that name will be used.
/// - If `#[nu_value(rename_all = "...")]` is applied on the enum container, the name of variant
/// will be case-converted accordingly.
/// - If neither attribute is applied, the variant name will default to
/// ["snake_case"](heck::ToSnakeCase).
///
/// Additionally, you can use `#[nu_value(type_name = "...")]` in the derive macro to set a custom type name
/// for `FromValue::expected_type`. This will result in a `Type::Custom` with the specified type name.
/// This can be useful in situations where the default type name is not desired.
///
/// # Enum Example
/// ```
/// # use nu_protocol::{FromValue, Value, ShellError, record, Span};
/// #
/// # let span = Span::unknown();
/// #
/// #[derive(FromValue, Debug, PartialEq)]
/// #[nu_value(rename_all = "COBOL-CASE", type_name = "birb")]
/// enum Bird {
/// MountainEagle,
/// ForestOwl,
/// #[nu_value(rename = "RIVER-QUACK")]
/// RiverDuck,
/// }
///
/// assert_eq!(
/// Bird::from_value(Value::string("FOREST-OWL", span)).unwrap(),
/// Bird::ForestOwl
/// );
///
/// assert_eq!(
/// Bird::from_value(Value::string("RIVER-QUACK", span)).unwrap(),
/// Bird::RiverDuck
/// );
///
/// assert_eq!(
/// &Bird::expected_type().to_string(),
/// "birb"
/// );
/// ```
///
/// # Struct Example
/// ```
/// # use nu_protocol::{FromValue, Value, ShellError, record, Span};
/// #
/// # let span = Span::unknown();
/// #
/// #[derive(FromValue, PartialEq, Eq, Debug)]
/// #[nu_value(rename_all = "kebab-case")]
/// struct Person {
/// first_name: String,
/// last_name: String,
/// #[nu_value(rename = "age")]
/// age_years: u32,
/// }
///
/// let value = Value::record(record! {
/// "first-name" => Value::string("John", span),
/// "last-name" => Value::string("Doe", span),
/// "age" => Value::int(42, span),
/// }, span);
///
/// assert_eq!(
/// Person::from_value(value).unwrap(),
/// Person {
/// first_name: "John".into(),
/// last_name: "Doe".into(),
/// age_years: 42,
/// }
/// );
/// ```
pub trait FromValue: Sized {
// TODO: instead of ShellError, maybe we could have a FromValueError that implements Into<ShellError>
/// Loads a value from a [`Value`].
///
/// This method retrieves a value similarly to how strings are parsed using [`FromStr`].
/// The operation might fail if the `Value` contains unexpected types or structures.
fn from_value(v: Value) -> Result<Self, ShellError>;
/// Expected `Value` type.
///
/// This is used to print out errors of what type of value is expected for conversion.
/// Even if not used in [`from_value`](FromValue::from_value) this should still be implemented
/// so that other implementations like `Option` or `Vec` can make use of it.
/// It is advised to call this method in `from_value` to ensure that expected type in the error
/// is consistent.
///
/// Unlike the default implementation, derived implementations explicitly reveal the concrete
/// type, such as [`Type::Record`] or [`Type::List`], instead of an opaque type.
fn expected_type() -> Type {
Type::Custom(
any::type_name::<Self>()
.split(':')
.next_back()
.expect("str::split returns an iterator with at least one element")
.to_string()
.into_boxed_str(),
)
}
}
// Primitive Types
impl<T, const N: usize> FromValue for [T; N]
where
T: FromValue,
{
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
let v_ty = v.get_type();
let vec = Vec::<T>::from_value(v)?;
vec.try_into()
.map_err(|err_vec: Vec<T>| ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v_ty.to_string(),
span,
help: Some(match err_vec.len().cmp(&N) {
Ordering::Less => format!(
"input list too short ({}), expected length of {N}, add missing values",
err_vec.len()
),
Ordering::Equal => {
unreachable!("conversion would have worked if the length would be the same")
}
Ordering::Greater => format!(
"input list too long ({}), expected length of {N}, remove trailing values",
err_vec.len()
),
}),
})
}
fn expected_type() -> Type {
Type::Custom(format!("list<{};{N}>", T::expected_type()).into_boxed_str())
}
}
impl FromValue for bool {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Bool { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Bool
}
}
impl FromValue for char {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
let v_ty = v.get_type();
match v {
Value::String { ref val, .. } => match char::from_str(val) {
Ok(c) => Ok(c),
Err(_) => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v_ty.to_string(),
span,
help: Some("make the string only one char long".to_string()),
}),
},
_ => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v_ty.to_string(),
span,
help: None,
}),
}
}
fn expected_type() -> Type {
Type::String
}
}
impl FromValue for f32 {
fn from_value(v: Value) -> Result<Self, ShellError> {
f64::from_value(v).map(|float| float as f32)
}
}
impl FromValue for f64 {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Float { val, .. } => Ok(val),
Value::Int { val, .. } => Ok(val as f64),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Float
}
}
impl FromValue for i64 {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Int { val, .. } => Ok(val),
Value::Duration { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Int
}
}
/// This implementation supports **positive** durations only.
impl FromValue for std::time::Duration {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Duration { val, .. } => {
let nanos = u64::try_from(val)
.map_err(|_| ShellError::NeedsPositiveValue { span: v.span() })?;
Ok(Self::from_nanos(nanos))
}
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Duration
}
}
//
// We can not use impl<T: FromValue> FromValue for NonZero<T> as NonZero requires an unstable trait
// As a result, we use this macro to implement FromValue for each NonZero type.
//
macro_rules! impl_from_value_for_nonzero {
($nonzero:ty, $base:ty) => {
impl FromValue for $nonzero {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
let val = <$base>::from_value(v)?;
<$nonzero>::new(val).ok_or_else(|| ShellError::IncorrectValue {
msg: "use a value other than 0".into(),
val_span: span,
call_span: span,
})
}
fn expected_type() -> Type {
Type::Int
}
}
};
}
impl_from_value_for_nonzero!(NonZeroU16, u16);
impl_from_value_for_nonzero!(NonZeroU32, u32);
impl_from_value_for_nonzero!(NonZeroU64, u64);
impl_from_value_for_nonzero!(NonZeroUsize, usize);
impl_from_value_for_nonzero!(NonZeroI8, i8);
impl_from_value_for_nonzero!(NonZeroI16, i16);
impl_from_value_for_nonzero!(NonZeroI32, i32);
impl_from_value_for_nonzero!(NonZeroI64, i64);
impl_from_value_for_nonzero!(NonZeroIsize, isize);
macro_rules! impl_from_value_for_int {
($type:ty) => {
impl FromValue for $type {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
let int = i64::from_value(v)?;
const MIN: i64 = <$type>::MIN as i64;
const MAX: i64 = <$type>::MAX as i64;
#[allow(overlapping_range_endpoints)] // calculating MIN-1 is not possible for i64::MIN
#[allow(unreachable_patterns)] // isize might max out i64 number range
<$type>::try_from(int).map_err(|_| match int {
MIN..=MAX => unreachable!(
"int should be within the valid range for {}",
stringify!($type)
),
i64::MIN..=MIN => int_too_small_error(int, <$type>::MIN, span),
MAX..=i64::MAX => int_too_large_error(int, <$type>::MAX, span),
})
}
fn expected_type() -> Type {
i64::expected_type()
}
}
};
}
impl_from_value_for_int!(i8);
impl_from_value_for_int!(i16);
impl_from_value_for_int!(i32);
impl_from_value_for_int!(isize);
macro_rules! impl_from_value_for_uint {
($type:ty, $max:expr) => {
impl FromValue for $type {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
const MAX: i64 = $max;
match v {
Value::Int { val, .. } | Value::Duration { val, .. } => {
match val {
i64::MIN..=-1 => Err(ShellError::NeedsPositiveValue { span }),
0..=MAX => Ok(val as $type),
#[allow(unreachable_patterns)] // u64 will max out the i64 number range
n => Err(ShellError::GenericError {
error: "Integer too large".to_string(),
msg: format!("{n} is larger than {MAX}"),
span: Some(span),
help: None,
inner: vec![],
}),
}
}
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Custom("non-negative int".to_string().into_boxed_str())
}
}
};
}
// Sadly we cannot implement FromValue for u8 without losing the impl of Vec<u8>,
// Rust would find two possible implementations then, Vec<u8> and Vec<T = u8>,
// and wouldn't compile.
// The blanket implementation for Vec<T> is probably more useful than
// implementing FromValue for u8.
impl_from_value_for_uint!(u16, u16::MAX as i64);
impl_from_value_for_uint!(u32, u32::MAX as i64);
impl_from_value_for_uint!(u64, i64::MAX); // u64::Max would be -1 as i64
#[cfg(target_pointer_width = "64")]
impl_from_value_for_uint!(usize, i64::MAX);
#[cfg(target_pointer_width = "32")]
impl_from_value_for_uint!(usize, usize::MAX as i64);
impl FromValue for () {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Nothing { .. } => Ok(()),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Nothing
}
}
macro_rules! tuple_from_value {
($template:literal, $($t:ident:$n:tt),+) => {
impl<$($t),+> FromValue for ($($t,)+) where $($t: FromValue,)+ {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::List { vals, .. } => {
let mut deque = VecDeque::from(vals);
Ok(($(
{
let v = deque.pop_front().ok_or_else(|| ShellError::CantFindColumn {
col_name: $n.to_string(),
span: None,
src_span: span
})?;
$t::from_value(v)?
},
)*))
},
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Custom(
format!(
$template,
$($t::expected_type()),*
)
.into_boxed_str(),
)
}
}
};
}
// Tuples in std are implemented for up to 12 elements, so we do it here too.
tuple_from_value!("[{}]", T0:0);
tuple_from_value!("[{}, {}]", T0:0, T1:1);
tuple_from_value!("[{}, {}, {}]", T0:0, T1:1, T2:2);
tuple_from_value!("[{}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3);
tuple_from_value!("[{}, {}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3, T4:4);
tuple_from_value!("[{}, {}, {}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3, T4:4, T5:5);
tuple_from_value!("[{}, {}, {}, {}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6);
tuple_from_value!("[{}, {}, {}, {}, {}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7);
tuple_from_value!("[{}, {}, {}, {}, {}, {}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7, T8:8);
tuple_from_value!("[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7, T8:8, T9:9);
tuple_from_value!("[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7, T8:8, T9:9, T10:10);
tuple_from_value!("[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}]", T0:0, T1:1, T2:2, T3:3, T4:4, T5:5, T6:6, T7:7, T8:8, T9:9, T10:10, T11:11);
// Other std Types
impl FromValue for PathBuf {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::String { val, .. } => Ok(val.into()),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::String
}
}
impl FromValue for String {
fn from_value(v: Value) -> Result<Self, ShellError> {
// FIXME: we may want to fail a little nicer here
match v {
Value::CellPath { val, .. } => Ok(val.to_string()),
Value::String { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::String
}
}
// This impl is different from Vec<T> as it allows reading from Value::Binary and Value::String too.
// This also denies implementing FromValue for u8 as it would be in conflict with the Vec<T> impl.
impl FromValue for Vec<u8> {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Binary { val, .. } => Ok(val),
Value::String { val, .. } => Ok(val.into_bytes()),
Value::List { vals, .. } => {
const U8MIN: i64 = u8::MIN as i64;
const U8MAX: i64 = u8::MAX as i64;
let mut this = Vec::with_capacity(vals.len());
for val in vals {
let span = val.span();
let int = i64::from_value(val)?;
// calculating -1 on these ranges would be less readable
#[allow(overlapping_range_endpoints)]
#[allow(clippy::match_overlapping_arm)]
match int {
U8MIN..=U8MAX => this.push(int as u8),
i64::MIN..=U8MIN => return Err(int_too_small_error(int, U8MIN, span)),
U8MAX..=i64::MAX => return Err(int_too_large_error(int, U8MAX, span)),
};
}
Ok(this)
}
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Binary
}
}
// Blanket std Implementations
impl<T> FromValue for Option<T>
where
T: FromValue,
{
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Nothing { .. } => Ok(None),
v => T::from_value(v).map(Option::Some),
}
}
fn expected_type() -> Type {
T::expected_type()
}
}
impl<A, B> FromValue for Result<A, B>
where
A: FromValue,
B: FromValue,
{
fn from_value(v: Value) -> std::result::Result<Self, ShellError> {
match (A::from_value(v.clone()), B::from_value(v.clone())) {
(Ok(a), _) => Ok(Ok(a)),
(_, Ok(b)) => Ok(Err(b)),
(Err(ea), Err(_)) => Err(ea),
}
}
fn expected_type() -> Type {
Type::OneOf(vec![A::expected_type(), B::expected_type()].into())
}
}
/// This blanket implementation permits the use of [`Cow<'_, B>`] ([`Cow<'_, str>`] etc) based on
/// the [FromValue] implementation of `B`'s owned form ([str] => [String]).
///
/// It's meant to make using the [FromValue] derive macro on types that contain [Cow] fields
/// possible.
impl<B> FromValue for Cow<'_, B>
where
B: ?Sized + ToOwned,
B::Owned: FromValue,
{
fn from_value(v: Value) -> Result<Self, ShellError> {
<B::Owned as FromValue>::from_value(v).map(Cow::Owned)
}
fn expected_type() -> Type {
<B::Owned as FromValue>::expected_type()
}
}
impl<V> FromValue for HashMap<String, V>
where
V: FromValue,
{
fn from_value(v: Value) -> Result<Self, ShellError> {
let record = v.into_record()?;
let items: Result<Vec<(String, V)>, ShellError> = record
.into_iter()
.map(|(k, v)| Ok((k, V::from_value(v)?)))
.collect();
Ok(HashMap::from_iter(items?))
}
fn expected_type() -> Type {
Type::Record(vec![].into_boxed_slice())
}
}
impl<T> FromValue for Box<T>
where
T: FromValue,
{
fn from_value(v: Value) -> Result<Self, ShellError> {
match T::from_value(v) {
Ok(val) => Ok(Box::new(val)),
Err(e) => Err(e),
}
}
}
impl<T> FromValue for Vec<T>
where
T: FromValue,
{
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::List { vals, .. } => vals
.into_iter()
.map(|v| T::from_value(v))
.collect::<Result<Vec<T>, ShellError>>(),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::List(Box::new(T::expected_type()))
}
}
// Nu Types
impl FromValue for Value {
fn from_value(v: Value) -> Result<Self, ShellError> {
Ok(v)
}
fn expected_type() -> Type {
Type::Any
}
}
impl FromValue for CellPath {
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::CellPath { val, .. } => Ok(val),
Value::String { val, .. } => Ok(CellPath {
members: vec![PathMember::String {
val,
span,
optional: false,
casing: Casing::Sensitive,
}],
}),
Value::Int { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue { span })
} else {
Ok(CellPath {
members: vec![PathMember::Int {
val: val as usize,
span,
optional: false,
}],
})
}
}
x => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: x.get_type().to_string(),
span,
help: None,
}),
}
}
fn expected_type() -> Type {
Type::CellPath
}
}
impl FromValue for Closure {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Closure { val, .. } => Ok(*val),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
impl FromValue for DateTime<FixedOffset> {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Date { val, .. } => Ok(val),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Date
}
}
impl FromValue for NuGlob {
fn from_value(v: Value) -> Result<Self, ShellError> {
// FIXME: we may want to fail a little nicer here
match v {
Value::CellPath { val, .. } => Ok(NuGlob::Expand(val.to_string())),
Value::String { val, .. } => Ok(NuGlob::DoNotExpand(val)),
Value::Glob {
val,
no_expand: quoted,
..
} => {
if quoted {
Ok(NuGlob::DoNotExpand(val))
} else {
Ok(NuGlob::Expand(val))
}
}
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::String
}
}
impl FromValue for Range {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Range { val, .. } => Ok(*val),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Range
}
}
impl FromValue for Record {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Record { val, .. } => Ok(val.into_owned()),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
}
// Blanket Nu Implementations
impl<T> FromValue for Spanned<T>
where
T: FromValue,
{
fn from_value(v: Value) -> Result<Self, ShellError> {
let span = v.span();
Ok(Spanned {
item: T::from_value(v)?,
span,
})
}
fn expected_type() -> Type {
T::expected_type()
}
}
// Foreign Types
impl FromValue for bytes::Bytes {
fn from_value(v: Value) -> Result<Self, ShellError> {
match v {
Value::Binary { val, .. } => Ok(val.into()),
v => Err(ShellError::CantConvert {
to_type: Self::expected_type().to_string(),
from_type: v.get_type().to_string(),
span: v.span(),
help: None,
}),
}
}
fn expected_type() -> Type {
Type::Binary
}
}
// Use generics with `fmt::Display` to allow passing different kinds of integer
fn int_too_small_error(int: impl fmt::Display, min: impl fmt::Display, span: Span) -> ShellError {
ShellError::GenericError {
error: "Integer too small".to_string(),
msg: format!("{int} is smaller than {min}"),
span: Some(span),
help: None,
inner: vec![],
}
}
fn int_too_large_error(int: impl fmt::Display, max: impl fmt::Display, span: Span) -> ShellError {
ShellError::GenericError {
error: "Integer too large".to_string(),
msg: format!("{int} is larger than {max}"),
span: Some(span),
help: None,
inner: vec![],
}
}
#[cfg(test)]
mod tests {
use crate::{FromValue, IntoValue, Record, Span, Type, Value, engine::Closure};
use std::ops::Deref;
#[test]
fn expected_type_default_impl() {
assert_eq!(
Record::expected_type(),
Type::Custom("Record".to_string().into_boxed_str())
);
assert_eq!(
Closure::expected_type(),
Type::Custom("Closure".to_string().into_boxed_str())
);
}
#[test]
fn from_value_vec_u8() {
let vec: Vec<u8> = vec![1, 2, 3];
let span = Span::test_data();
let string = "Hello Vec<u8>!".to_string();
assert_eq!(
Vec::<u8>::from_value(vec.clone().into_value(span)).unwrap(),
vec.clone(),
"Vec<u8> roundtrip"
);
assert_eq!(
Vec::<u8>::from_value(Value::test_string(string.clone()))
.unwrap()
.deref(),
string.as_bytes(),
"Vec<u8> from String"
);
assert_eq!(
Vec::<u8>::from_value(Value::test_binary(vec.clone())).unwrap(),
vec,
"Vec<u8> from Binary"
);
assert!(Vec::<u8>::from_value(vec![u8::MIN as i32 - 1].into_value(span)).is_err());
assert!(Vec::<u8>::from_value(vec![u8::MAX as i32 + 1].into_value(span)).is_err());
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/value/duration.rs | crates/nu-protocol/src/value/duration.rs | use chrono::Duration;
use std::{
borrow::Cow,
fmt::{Display, Formatter},
};
#[derive(Clone, Copy)]
pub enum TimePeriod {
Nanos(i64),
Micros(i64),
Millis(i64),
Seconds(i64),
Minutes(i64),
Hours(i64),
Days(i64),
Weeks(i64),
Months(i64),
Years(i64),
}
impl TimePeriod {
pub fn to_text(self) -> Cow<'static, str> {
match self {
Self::Nanos(n) => format!("{n} ns").into(),
Self::Micros(n) => format!("{n} Β΅s").into(),
Self::Millis(n) => format!("{n} ms").into(),
Self::Seconds(n) => format!("{n} sec").into(),
Self::Minutes(n) => format!("{n} min").into(),
Self::Hours(n) => format!("{n} hr").into(),
Self::Days(n) => format!("{n} day").into(),
Self::Weeks(n) => format!("{n} wk").into(),
Self::Months(n) => format!("{n} month").into(),
Self::Years(n) => format!("{n} yr").into(),
}
}
}
impl Display for TimePeriod {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_text())
}
}
pub fn format_duration(duration: i64) -> String {
let (sign, periods) = format_duration_as_timeperiod(duration);
let text = periods
.into_iter()
.map(|p| p.to_text().to_string().replace(' ', ""))
.collect::<Vec<String>>();
format!(
"{}{}",
if sign == -1 { "-" } else { "" },
text.join(" ").trim()
)
}
pub fn format_duration_as_timeperiod(duration: i64) -> (i32, Vec<TimePeriod>) {
// Attribution: most of this is taken from chrono-humanize-rs. Thanks!
// https://gitlab.com/imp/chrono-humanize-rs/-/blob/master/src/humantime.rs
// Current duration doesn't know a date it's based on, weeks is the max time unit it can normalize into.
// Don't guess or estimate how many years or months it might contain.
let (sign, duration) = if duration >= 0 {
(1, duration)
} else {
(-1, -duration)
};
let dur = Duration::nanoseconds(duration);
/// Split this a duration into number of whole weeks and the remainder
fn split_weeks(duration: Duration) -> (Option<i64>, Duration) {
let weeks = duration.num_weeks();
normalize_split(weeks, Duration::try_weeks(weeks), duration)
}
/// Split this a duration into number of whole days and the remainder
fn split_days(duration: Duration) -> (Option<i64>, Duration) {
let days = duration.num_days();
normalize_split(days, Duration::try_days(days), duration)
}
/// Split this a duration into number of whole hours and the remainder
fn split_hours(duration: Duration) -> (Option<i64>, Duration) {
let hours = duration.num_hours();
normalize_split(hours, Duration::try_hours(hours), duration)
}
/// Split this a duration into number of whole minutes and the remainder
fn split_minutes(duration: Duration) -> (Option<i64>, Duration) {
let minutes = duration.num_minutes();
normalize_split(minutes, Duration::try_minutes(minutes), duration)
}
/// Split this a duration into number of whole seconds and the remainder
fn split_seconds(duration: Duration) -> (Option<i64>, Duration) {
let seconds = duration.num_seconds();
normalize_split(seconds, Duration::try_seconds(seconds), duration)
}
/// Split this a duration into number of whole milliseconds and the remainder
fn split_milliseconds(duration: Duration) -> (Option<i64>, Duration) {
let millis = duration.num_milliseconds();
normalize_split(millis, Duration::try_milliseconds(millis), duration)
}
/// Split this a duration into number of whole seconds and the remainder
fn split_microseconds(duration: Duration) -> (Option<i64>, Duration) {
let micros = duration.num_microseconds().unwrap_or_default();
normalize_split(micros, Duration::microseconds(micros), duration)
}
/// Split this a duration into number of whole seconds and the remainder
fn split_nanoseconds(duration: Duration) -> (Option<i64>, Duration) {
let nanos = duration.num_nanoseconds().unwrap_or_default();
normalize_split(nanos, Duration::nanoseconds(nanos), duration)
}
fn normalize_split(
wholes: i64,
wholes_duration: impl Into<Option<Duration>>,
total_duration: Duration,
) -> (Option<i64>, Duration) {
match wholes_duration.into() {
Some(wholes_duration) if wholes != 0 => {
(Some(wholes), total_duration - wholes_duration)
}
_ => (None, total_duration),
}
}
let mut periods = vec![];
let (weeks, remainder) = split_weeks(dur);
if let Some(weeks) = weeks {
periods.push(TimePeriod::Weeks(weeks));
}
let (days, remainder) = split_days(remainder);
if let Some(days) = days {
periods.push(TimePeriod::Days(days));
}
let (hours, remainder) = split_hours(remainder);
if let Some(hours) = hours {
periods.push(TimePeriod::Hours(hours));
}
let (minutes, remainder) = split_minutes(remainder);
if let Some(minutes) = minutes {
periods.push(TimePeriod::Minutes(minutes));
}
let (seconds, remainder) = split_seconds(remainder);
if let Some(seconds) = seconds {
periods.push(TimePeriod::Seconds(seconds));
}
let (millis, remainder) = split_milliseconds(remainder);
if let Some(millis) = millis {
periods.push(TimePeriod::Millis(millis));
}
let (micros, remainder) = split_microseconds(remainder);
if let Some(micros) = micros {
periods.push(TimePeriod::Micros(micros));
}
let (nanos, _remainder) = split_nanoseconds(remainder);
if let Some(nanos) = nanos {
periods.push(TimePeriod::Nanos(nanos));
}
if periods.is_empty() {
periods.push(TimePeriod::Seconds(0));
}
(sign, periods)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/datetime_format.rs | crates/nu-protocol/src/config/datetime_format.rs | use super::prelude::*;
use crate as nu_protocol;
#[derive(Clone, Debug, Default, IntoValue, Serialize, Deserialize)]
pub struct DatetimeFormatConfig {
pub normal: Option<String>,
pub table: Option<String>,
}
impl UpdateFromValue for DatetimeFormatConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"normal" => match val {
Value::Nothing { .. } => self.normal = None,
Value::String { val, .. } => self.normal = Some(val.clone()),
_ => errors.type_mismatch(path, Type::custom("string or nothing"), val),
},
"table" => match val {
Value::Nothing { .. } => self.table = None,
Value::String { val, .. } => self.table = Some(val.clone()),
_ => errors.type_mismatch(path, Type::custom("string or nothing"), val),
},
_ => errors.unknown_option(path, val),
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/prelude.rs | crates/nu-protocol/src/config/prelude.rs | pub(super) use super::{ConfigPath, UpdateFromValue, error::ConfigErrors};
pub use crate::{IntoValue, ShellError, ShellWarning, Span, Type, Value, record};
pub use serde::{Deserialize, Serialize};
pub use std::str::FromStr;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/filesize.rs | crates/nu-protocol/src/config/filesize.rs | use super::prelude::*;
use crate::{Filesize, FilesizeFormatter, FilesizeUnitFormat, FormattedFilesize};
use nu_utils::get_system_locale;
impl IntoValue for FilesizeUnitFormat {
fn into_value(self, span: Span) -> Value {
self.as_str().into_value(span)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FilesizeConfig {
pub unit: FilesizeUnitFormat,
pub show_unit: bool,
pub precision: Option<usize>,
}
impl FilesizeConfig {
pub fn formatter(&self) -> FilesizeFormatter {
FilesizeFormatter::new()
.unit(self.unit)
.show_unit(self.show_unit)
.precision(self.precision)
.locale(get_system_locale()) // TODO: cache this somewhere or pass in as argument
}
pub fn format(&self, filesize: Filesize) -> FormattedFilesize {
self.formatter().format(filesize)
}
}
impl Default for FilesizeConfig {
fn default() -> Self {
Self {
unit: FilesizeUnitFormat::Metric,
show_unit: true,
precision: Some(1),
}
}
}
impl From<FilesizeConfig> for FilesizeFormatter {
fn from(config: FilesizeConfig) -> Self {
config.formatter()
}
}
impl UpdateFromValue for FilesizeConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"unit" => {
if let Ok(str) = val.as_str() {
match str.parse() {
Ok(unit) => self.unit = unit,
Err(_) => errors.invalid_value(path, "'metric', 'binary', 'B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', or 'EiB'", val),
}
} else {
errors.type_mismatch(path, Type::String, val)
}
}
"show_unit" => self.show_unit.update(val, path, errors),
"precision" => match *val {
Value::Nothing { .. } => self.precision = None,
Value::Int { val, .. } if val >= 0 => self.precision = Some(val as usize),
Value::Int { .. } => errors.invalid_value(path, "a non-negative integer", val),
_ => errors.type_mismatch(path, Type::custom("int or nothing"), val),
},
_ => errors.unknown_option(path, val),
}
}
}
}
impl IntoValue for FilesizeConfig {
fn into_value(self, span: Span) -> Value {
record! {
"unit" => self.unit.into_value(span),
"show_unit" => self.show_unit.into_value(span),
"precision" => self.precision.map(|x| x as i64).into_value(span),
}
.into_value(span)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/ls.rs | crates/nu-protocol/src/config/ls.rs | use super::prelude::*;
use crate as nu_protocol;
#[derive(Clone, Copy, Debug, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub struct LsConfig {
pub use_ls_colors: bool,
pub clickable_links: bool,
}
impl Default for LsConfig {
fn default() -> Self {
Self {
use_ls_colors: true,
clickable_links: true,
}
}
}
impl UpdateFromValue for LsConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"use_ls_colors" => self.use_ls_colors.update(val, path, errors),
"clickable_links" => self.clickable_links.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/ansi_coloring.rs | crates/nu-protocol/src/config/ansi_coloring.rs | use super::{ConfigErrors, ConfigPath, IntoValue, ShellError, UpdateFromValue, Value};
use crate::{self as nu_protocol, FromValue, engine::EngineState};
use serde::{Deserialize, Serialize};
use std::io::IsTerminal;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, IntoValue, Serialize, Deserialize)]
pub enum UseAnsiColoring {
#[default]
Auto,
True,
False,
}
impl UseAnsiColoring {
/// Determines whether ANSI colors should be used.
///
/// This method evaluates the `UseAnsiColoring` setting and considers environment variables
/// (`FORCE_COLOR`, `NO_COLOR`, and `CLICOLOR`) when the value is set to `Auto`.
/// The configuration value (`UseAnsiColoring`) takes precedence over environment variables, as
/// it is more direct and internally may be modified to override ANSI coloring behavior.
///
/// Most users should have the default value `Auto` which allows the environment variables to
/// control ANSI coloring.
/// However, when explicitly set to `True` or `False`, the environment variables are ignored.
///
/// Behavior based on `UseAnsiColoring`:
/// - `True`: Forces ANSI colors to be enabled, ignoring terminal support and environment variables.
/// - `False`: Disables ANSI colors completely.
/// - `Auto`: Determines whether ANSI colors should be used based on environment variables and terminal support.
///
/// When set to `Auto`, the following environment variables are checked in order:
/// 1. `FORCE_COLOR`: If set, ANSI colors are always enabled, overriding all other settings.
/// 2. `NO_COLOR`: If set, ANSI colors are disabled, overriding `CLICOLOR` and terminal checks.
/// 3. `CLICOLOR`: If set, its value determines whether ANSI colors are enabled (`1` for enabled, `0` for disabled).
///
/// If none of these variables are set, ANSI coloring is enabled only if the standard output is
/// a terminal.
///
/// By prioritizing the `UseAnsiColoring` value, we ensure predictable behavior and prevent
/// conflicts with internal overrides that depend on this configuration.
pub fn get(self, engine_state: &EngineState) -> bool {
let is_terminal = match self {
Self::Auto => std::io::stdout().is_terminal(),
Self::True => return true,
Self::False => return false,
};
let env_value = |env_name| {
engine_state
.get_env_var_insensitive(env_name)
.map(|(_, v)| v)
.and_then(|v| v.coerce_bool().ok())
.unwrap_or(false)
};
if env_value("force_color") {
return true;
}
if env_value("no_color") {
return false;
}
if let Some((_, cli_color)) = engine_state.get_env_var_insensitive("clicolor")
&& let Ok(cli_color) = cli_color.coerce_bool()
{
return cli_color;
}
is_terminal
}
}
impl From<bool> for UseAnsiColoring {
fn from(value: bool) -> Self {
match value {
true => Self::True,
false => Self::False,
}
}
}
impl FromValue for UseAnsiColoring {
fn from_value(v: Value) -> Result<Self, ShellError> {
if let Ok(v) = v.as_bool() {
return Ok(v.into());
}
#[derive(FromValue)]
enum UseAnsiColoringString {
Auto = 0,
True = 1,
False = 2,
}
Ok(match UseAnsiColoringString::from_value(v)? {
UseAnsiColoringString::Auto => Self::Auto,
UseAnsiColoringString::True => Self::True,
UseAnsiColoringString::False => Self::False,
})
}
}
impl UpdateFromValue for UseAnsiColoring {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Ok(value) = UseAnsiColoring::from_value(value.clone()) else {
errors.type_mismatch(path, UseAnsiColoring::expected_type(), value);
return;
};
*self = value;
}
}
#[cfg(test)]
mod tests {
use super::*;
use nu_protocol::Config;
fn set_env(engine_state: &mut EngineState, name: &str, value: bool) {
engine_state.add_env_var(name.to_string(), Value::test_bool(value));
}
#[test]
fn test_use_ansi_coloring_true() {
let mut engine_state = EngineState::new();
engine_state.config = Config {
use_ansi_coloring: UseAnsiColoring::True,
..Default::default()
}
.into();
// explicit `True` ignores environment variables
assert!(
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "clicolor", false);
assert!(
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "clicolor", true);
assert!(
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "no_color", true);
assert!(
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "force_color", true);
assert!(
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
}
#[test]
fn test_use_ansi_coloring_false() {
let mut engine_state = EngineState::new();
engine_state.config = Config {
use_ansi_coloring: UseAnsiColoring::False,
..Default::default()
}
.into();
// explicit `False` ignores environment variables
assert!(
!engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "clicolor", false);
assert!(
!engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "clicolor", true);
assert!(
!engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "no_color", true);
assert!(
!engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "force_color", true);
assert!(
!engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
}
#[test]
fn test_use_ansi_coloring_auto() {
let mut engine_state = EngineState::new();
engine_state.config = Config {
use_ansi_coloring: UseAnsiColoring::Auto,
..Default::default()
}
.into();
// no environment variables, behavior depends on terminal state
let is_terminal = std::io::stdout().is_terminal();
assert_eq!(
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state),
is_terminal
);
// `clicolor` determines ANSI behavior if no higher-priority variables are set
set_env(&mut engine_state, "clicolor", true);
assert!(
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
set_env(&mut engine_state, "clicolor", false);
assert!(
!engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
// `no_color` overrides `clicolor` and terminal state
set_env(&mut engine_state, "no_color", true);
assert!(
!engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
// `force_color` overrides everything
set_env(&mut engine_state, "force_color", true);
assert!(
engine_state
.get_config()
.use_ansi_coloring
.get(&engine_state)
);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/rm.rs | crates/nu-protocol/src/config/rm.rs | use super::prelude::*;
use crate as nu_protocol;
#[derive(Clone, Copy, Debug, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub struct RmConfig {
pub always_trash: bool,
}
#[allow(clippy::derivable_impls)]
impl Default for RmConfig {
fn default() -> Self {
Self {
always_trash: false,
}
}
}
impl UpdateFromValue for RmConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"always_trash" => self.always_trash.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/table.rs | crates/nu-protocol/src/config/table.rs | use std::{num::NonZeroU16, time::Duration};
use super::{config_update_string_enum, prelude::*};
use crate::{self as nu_protocol, ConfigError, FromValue};
#[derive(Clone, Copy, Debug, Default, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub enum TableMode {
Basic,
Thin,
Light,
Compact,
WithLove,
CompactDouble,
#[default]
Rounded,
Reinforced,
Heavy,
None,
Psql,
Markdown,
Dots,
Restructured,
AsciiRounded,
BasicCompact,
Single,
Double,
}
impl FromStr for TableMode {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"basic" => Ok(Self::Basic),
"thin" => Ok(Self::Thin),
"light" => Ok(Self::Light),
"compact" => Ok(Self::Compact),
"with_love" => Ok(Self::WithLove),
"compact_double" => Ok(Self::CompactDouble),
"default" => Ok(TableMode::default()),
"rounded" => Ok(Self::Rounded),
"reinforced" => Ok(Self::Reinforced),
"heavy" => Ok(Self::Heavy),
"none" => Ok(Self::None),
"psql" => Ok(Self::Psql),
"markdown" => Ok(Self::Markdown),
"dots" => Ok(Self::Dots),
"restructured" => Ok(Self::Restructured),
"ascii_rounded" => Ok(Self::AsciiRounded),
"basic_compact" => Ok(Self::BasicCompact),
"single" => Ok(Self::Single),
"double" => Ok(Self::Double),
_ => Err(
"'basic', 'thin', 'light', 'compact', 'with_love', 'compact_double', 'rounded', 'reinforced', 'heavy', 'none', 'psql', 'markdown', 'dots', 'restructured', 'ascii_rounded', 'basic_compact', 'single', or 'double'",
),
}
}
}
impl UpdateFromValue for TableMode {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
config_update_string_enum(self, value, path, errors)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum FooterMode {
/// Never show the footer
Never,
/// Always show the footer
Always,
/// Only show the footer if there are more than RowCount rows
RowCount(u64),
/// Calculate the screen height and row count, if screen height is larger than row count, don't show footer
Auto,
}
impl FromStr for FooterMode {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"always" => Ok(FooterMode::Always),
"never" => Ok(FooterMode::Never),
"auto" => Ok(FooterMode::Auto),
_ => Err("'never', 'always', 'auto', or int"),
}
}
}
impl UpdateFromValue for FooterMode {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
match value {
Value::String { val, .. } => match val.parse() {
Ok(val) => *self = val,
Err(err) => errors.invalid_value(path, err.to_string(), value),
},
&Value::Int { val, .. } => {
if val >= 0 {
*self = Self::RowCount(val as u64);
} else {
errors.invalid_value(path, "a non-negative integer", value);
}
}
_ => errors.type_mismatch(
path,
Type::custom("'never', 'always', 'auto', or int"),
value,
),
}
}
}
impl IntoValue for FooterMode {
fn into_value(self, span: Span) -> Value {
match self {
FooterMode::Always => "always".into_value(span),
FooterMode::Never => "never".into_value(span),
FooterMode::Auto => "auto".into_value(span),
FooterMode::RowCount(c) => (c as i64).into_value(span),
}
}
}
#[derive(Clone, Copy, Debug, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub enum TableIndexMode {
/// Always show indexes
Always,
/// Never show indexes
Never,
/// Show indexes when a table has "index" column
Auto,
}
impl FromStr for TableIndexMode {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"always" => Ok(TableIndexMode::Always),
"never" => Ok(TableIndexMode::Never),
"auto" => Ok(TableIndexMode::Auto),
_ => Err("'never', 'always' or 'auto'"),
}
}
}
impl UpdateFromValue for TableIndexMode {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
config_update_string_enum(self, value, path, errors)
}
}
/// A Table view configuration, for a situation where
/// we need to limit cell width in order to adjust for a terminal size.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TrimStrategy {
/// Wrapping strategy.
///
/// It it's similar to original nu_table, strategy.
Wrap {
/// A flag which indicates whether is it necessary to try
/// to keep word boundaries.
try_to_keep_words: bool,
},
/// Truncating strategy, where we just cut the string.
/// And append the suffix if applicable.
Truncate {
/// Suffix which can be appended to a truncated string after being cut.
///
/// It will be applied only when there's enough room for it.
/// For example in case where a cell width must be 12 chars, but
/// the suffix takes 13 chars it won't be used.
suffix: Option<String>,
},
}
impl TrimStrategy {
pub fn wrap(dont_split_words: bool) -> Self {
Self::Wrap {
try_to_keep_words: dont_split_words,
}
}
pub fn truncate(suffix: Option<String>) -> Self {
Self::Truncate { suffix }
}
}
impl Default for TrimStrategy {
fn default() -> Self {
Self::Wrap {
try_to_keep_words: true,
}
}
}
impl IntoValue for TrimStrategy {
fn into_value(self, span: Span) -> Value {
match self {
TrimStrategy::Wrap { try_to_keep_words } => {
record! {
"methodology" => "wrapping".into_value(span),
"wrapping_try_keep_words" => try_to_keep_words.into_value(span),
}
}
TrimStrategy::Truncate { suffix } => {
record! {
"methodology" => "truncating".into_value(span),
"truncating_suffix" => suffix.into_value(span),
}
}
}
.into_value(span)
}
}
impl UpdateFromValue for TrimStrategy {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
let Some(methodology) = record.get("methodology") else {
errors.missing_column(path, "methodology", value.span());
return;
};
match methodology.as_str() {
Ok("wrapping") => {
let mut try_to_keep_words = if let &mut Self::Wrap { try_to_keep_words } = self {
try_to_keep_words
} else {
false
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"wrapping_try_keep_words" => try_to_keep_words.update(val, path, errors),
"methodology" | "truncating_suffix" => (),
_ => errors.unknown_option(path, val),
}
}
*self = Self::Wrap { try_to_keep_words };
}
Ok("truncating") => {
let mut suffix = if let Self::Truncate { suffix } = self {
suffix.take()
} else {
None
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"truncating_suffix" => match val {
Value::Nothing { .. } => suffix = None,
Value::String { val, .. } => suffix = Some(val.clone()),
_ => errors.type_mismatch(path, Type::String, val),
},
"methodology" | "wrapping_try_keep_words" => (),
_ => errors.unknown_option(path, val),
}
}
*self = Self::Truncate { suffix };
}
Ok(_) => errors.invalid_value(
&path.push("methodology"),
"'wrapping' or 'truncating'",
methodology,
),
Err(_) => errors.type_mismatch(&path.push("methodology"), Type::String, methodology),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TableIndent {
pub left: usize,
pub right: usize,
}
impl TableIndent {
pub fn new(left: usize, right: usize) -> Self {
Self { left, right }
}
}
impl IntoValue for TableIndent {
fn into_value(self, span: Span) -> Value {
record! {
"left" => (self.left as i64).into_value(span),
"right" => (self.right as i64).into_value(span),
}
.into_value(span)
}
}
impl Default for TableIndent {
fn default() -> Self {
Self { left: 1, right: 1 }
}
}
impl UpdateFromValue for TableIndent {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
match value {
&Value::Int { val, .. } => {
if let Ok(val) = val.try_into() {
self.left = val;
self.right = val;
} else {
errors.invalid_value(path, "a non-negative integer", value);
}
}
Value::Record { val: record, .. } => {
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"left" => self.left.update(val, path, errors),
"right" => self.right.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
_ => errors.type_mismatch(path, Type::custom("int or record"), value),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TableConfig {
pub mode: TableMode,
pub index_mode: TableIndexMode,
pub show_empty: bool,
pub padding: TableIndent,
pub trim: TrimStrategy,
pub header_on_separator: bool,
pub abbreviated_row_count: Option<usize>,
pub footer_inheritance: bool,
pub missing_value_symbol: String,
pub batch_duration: Duration,
pub stream_page_size: NonZeroU16,
}
impl IntoValue for TableConfig {
fn into_value(self, span: Span) -> Value {
let abbv_count = self
.abbreviated_row_count
.map(|t| t as i64)
.into_value(span);
record! {
"mode" => self.mode.into_value(span),
"index_mode" => self.index_mode.into_value(span),
"show_empty" => self.show_empty.into_value(span),
"padding" => self.padding.into_value(span),
"trim" => self.trim.into_value(span),
"header_on_separator" => self.header_on_separator.into_value(span),
"abbreviated_row_count" => abbv_count,
"footer_inheritance" => self.footer_inheritance.into_value(span),
"missing_value_symbol" => self.missing_value_symbol.into_value(span),
"batch_duration" => self.batch_duration.into_value(span),
"stream_page_size" => self.stream_page_size.get().into_value(span),
}
.into_value(span)
}
}
impl Default for TableConfig {
fn default() -> Self {
Self {
mode: TableMode::Rounded,
index_mode: TableIndexMode::Always,
show_empty: true,
trim: TrimStrategy::default(),
header_on_separator: false,
padding: TableIndent::default(),
abbreviated_row_count: None,
footer_inheritance: false,
missing_value_symbol: "β".into(),
batch_duration: Duration::from_secs(1),
stream_page_size: const { NonZeroU16::new(1000).expect("Non zero integer") },
}
}
}
impl UpdateFromValue for TableConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"mode" => self.mode.update(val, path, errors),
"index_mode" => self.index_mode.update(val, path, errors),
"show_empty" => self.show_empty.update(val, path, errors),
"trim" => self.trim.update(val, path, errors),
"header_on_separator" => self.header_on_separator.update(val, path, errors),
"padding" => self.padding.update(val, path, errors),
"abbreviated_row_count" => match val {
Value::Nothing { .. } => self.abbreviated_row_count = None,
&Value::Int { val: count, .. } => {
if let Ok(count) = count.try_into() {
self.abbreviated_row_count = Some(count);
} else {
errors.invalid_value(path, "a non-negative integer", val);
}
}
_ => errors.type_mismatch(path, Type::custom("int or nothing"), val),
},
"footer_inheritance" => self.footer_inheritance.update(val, path, errors),
"missing_value_symbol" => match val.as_str() {
Ok(val) => self.missing_value_symbol = val.to_string(),
Err(_) => errors.type_mismatch(path, Type::String, val),
},
"batch_duration" => {
match Duration::from_value(val.clone()).map_err(ConfigError::from) {
Ok(val) => self.batch_duration = val,
Err(err) => errors.error(err),
}
}
"stream_page_size" => {
let Ok(n) = val.as_int() else {
errors.type_mismatch(path, Type::Int, val);
continue;
};
let Some(n) = u16::try_from(n).ok().and_then(NonZeroU16::new) else {
errors.invalid_value(path, "a positive value", val);
continue;
};
self.stream_page_size = n;
}
_ => errors.unknown_option(path, val),
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/error.rs | crates/nu-protocol/src/config/error.rs | use super::ConfigPath;
use crate::{Config, ConfigError, ConfigWarning, ShellError, ShellWarning, Span, Type, Value};
#[derive(Debug)]
#[must_use]
pub(super) struct ConfigErrors<'a> {
config: &'a Config,
errors: Vec<ConfigError>,
warnings: Vec<ConfigWarning>,
}
impl<'a> ConfigErrors<'a> {
pub fn new(config: &'a Config) -> Self {
Self {
config,
errors: Vec::new(),
warnings: Vec::new(),
}
}
pub fn has_errors(&self) -> bool {
!self.errors.is_empty()
}
pub fn has_warnings(&self) -> bool {
!self.warnings.is_empty()
}
pub fn error(&mut self, error: ConfigError) {
self.errors.push(error);
}
pub fn warn(&mut self, warning: ConfigWarning) {
self.warnings.push(warning);
}
pub fn type_mismatch(&mut self, path: &ConfigPath, expected: Type, actual: &Value) {
self.error(ConfigError::TypeMismatch {
path: path.to_string(),
expected,
actual: actual.get_type(),
span: actual.span(),
});
}
pub fn invalid_value(
&mut self,
path: &ConfigPath,
expected: impl Into<String>,
actual: &Value,
) {
self.error(ConfigError::InvalidValue {
path: path.to_string(),
valid: expected.into(),
actual: if let Ok(str) = actual.as_str() {
format!("'{str}'")
} else {
actual.to_abbreviated_string(self.config)
},
span: actual.span(),
});
}
pub fn missing_column(&mut self, path: &ConfigPath, column: &'static str, span: Span) {
self.error(ConfigError::MissingRequiredColumn {
path: path.to_string(),
column,
span,
})
}
pub fn unknown_option(&mut self, path: &ConfigPath, value: &Value) {
self.error(ConfigError::UnknownOption {
path: path.to_string(),
span: value.span(),
});
}
// We'll probably need this again in the future so allow dead code for now
#[allow(dead_code)]
pub fn deprecated_option(&mut self, path: &ConfigPath, suggestion: &'static str, span: Span) {
self.error(ConfigError::Deprecated {
path: path.to_string(),
suggestion,
span,
});
}
pub fn check(self) -> Result<Option<ShellWarning>, ShellError> {
match (self.has_errors(), self.has_warnings()) {
(true, _) => Err(ShellError::InvalidConfig {
errors: self.errors,
}),
(false, true) => Ok(Some(ShellWarning::InvalidConfig {
warnings: self.warnings,
})),
(false, false) => Ok(None),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/helper.rs | crates/nu-protocol/src/config/helper.rs | use super::error::ConfigErrors;
use crate::{Record, ShellError, Span, Type, Value};
use std::{
borrow::Borrow,
collections::HashMap,
fmt::{self, Display},
hash::Hash,
ops::{Deref, DerefMut},
str::FromStr,
};
pub(super) struct ConfigPath<'a> {
components: Vec<&'a str>,
}
impl<'a> ConfigPath<'a> {
pub fn new() -> Self {
Self {
components: vec!["$env.config"],
}
}
pub fn push(&mut self, key: &'a str) -> ConfigPathScope<'_, 'a> {
self.components.push(key);
ConfigPathScope { inner: self }
}
}
impl Display for ConfigPath<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.components.join("."))
}
}
pub(super) struct ConfigPathScope<'whole, 'part> {
inner: &'whole mut ConfigPath<'part>,
}
impl Drop for ConfigPathScope<'_, '_> {
fn drop(&mut self) {
self.inner.components.pop();
}
}
impl<'a> Deref for ConfigPathScope<'_, 'a> {
type Target = ConfigPath<'a>;
fn deref(&self) -> &Self::Target {
self.inner
}
}
impl DerefMut for ConfigPathScope<'_, '_> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.inner
}
}
pub(super) trait UpdateFromValue: Sized {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
);
}
impl UpdateFromValue for Value {
fn update(&mut self, value: &Value, _path: &mut ConfigPath, _errors: &mut ConfigErrors) {
*self = value.clone();
}
}
impl UpdateFromValue for bool {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
if let Ok(val) = value.as_bool() {
*self = val;
} else {
errors.type_mismatch(path, Type::Bool, value);
}
}
}
impl UpdateFromValue for i64 {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
if let Ok(val) = value.as_int() {
*self = val;
} else {
errors.type_mismatch(path, Type::Int, value);
}
}
}
impl UpdateFromValue for usize {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
if let Ok(val) = value.as_int() {
if let Ok(val) = val.try_into() {
*self = val;
} else {
errors.invalid_value(path, "a non-negative integer", value);
}
} else {
errors.type_mismatch(path, Type::Int, value);
}
}
}
impl UpdateFromValue for String {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
if let Ok(val) = value.as_str() {
*self = val.into();
} else {
errors.type_mismatch(path, Type::String, value);
}
}
}
impl<K, V> UpdateFromValue for HashMap<K, V>
where
K: Borrow<str> + for<'a> From<&'a str> + Eq + Hash,
V: Default + UpdateFromValue,
{
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
if let Ok(record) = value.as_record() {
*self = record
.iter()
.map(|(key, val)| {
let mut old = self.remove(key).unwrap_or_default();
old.update(val, &mut path.push(key), errors);
(key.as_str().into(), old)
})
.collect();
} else {
errors.type_mismatch(path, Type::record(), value);
}
}
}
pub(super) fn config_update_string_enum<T>(
choice: &mut T,
value: &Value,
path: &mut ConfigPath,
errors: &mut ConfigErrors,
) where
T: FromStr,
T::Err: Display,
{
if let Ok(str) = value.as_str() {
match str.parse() {
Ok(val) => *choice = val,
Err(err) => errors.invalid_value(path, err.to_string(), value),
}
} else {
errors.type_mismatch(path, Type::String, value);
}
}
pub fn extract_value<'record>(
column: &'static str,
record: &'record Record,
span: Span,
) -> Result<&'record Value, ShellError> {
record
.get(column)
.ok_or_else(|| ShellError::MissingRequiredColumn { column, span })
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/history.rs | crates/nu-protocol/src/config/history.rs | use super::{config_update_string_enum, prelude::*};
use crate::{self as nu_protocol, ConfigWarning};
#[derive(Clone, Copy, Debug, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub enum HistoryFileFormat {
/// Store history as an SQLite database with additional context
Sqlite,
/// store history as a plain text file where every line is one command (without any context such as timestamps)
Plaintext,
}
impl HistoryFileFormat {
pub fn default_file_name(self) -> std::path::PathBuf {
match self {
HistoryFileFormat::Plaintext => "history.txt",
HistoryFileFormat::Sqlite => "history.sqlite3",
}
.into()
}
}
impl FromStr for HistoryFileFormat {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"sqlite" => Ok(Self::Sqlite),
"plaintext" => Ok(Self::Plaintext),
#[cfg(feature = "sqlite")]
_ => Err("'sqlite' or 'plaintext'"),
#[cfg(not(feature = "sqlite"))]
_ => Err("'plaintext'"),
}
}
}
impl UpdateFromValue for HistoryFileFormat {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
config_update_string_enum(self, value, path, errors);
#[cfg(not(feature = "sqlite"))]
if *self == HistoryFileFormat::Sqlite {
*self = HistoryFileFormat::Plaintext;
errors.warn(ConfigWarning::IncompatibleOptions {
label: "SQLite-based history file only supported with the `sqlite` feature, falling back to plain text history",
span: value.span(),
help: "Compile Nushell with `sqlite` feature enabled",
});
}
}
}
#[derive(Clone, Copy, Debug, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub struct HistoryConfig {
pub max_size: i64,
pub sync_on_enter: bool,
pub file_format: HistoryFileFormat,
pub isolation: bool,
}
impl HistoryConfig {
pub fn file_path(&self) -> Option<std::path::PathBuf> {
nu_path::nu_config_dir().map(|mut history_path| {
history_path.push(self.file_format.default_file_name());
history_path.into()
})
}
}
impl Default for HistoryConfig {
fn default() -> Self {
Self {
max_size: 100_000,
sync_on_enter: true,
file_format: HistoryFileFormat::Plaintext,
isolation: false,
}
}
}
impl UpdateFromValue for HistoryConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
// might not be correct if file format was changed away from sqlite rather than isolation,
// but this is an edge case and the span of the relevant value here should be close enough
let mut isolation_span = value.span();
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"isolation" => {
isolation_span = val.span();
self.isolation.update(val, path, errors)
}
"sync_on_enter" => self.sync_on_enter.update(val, path, errors),
"max_size" => self.max_size.update(val, path, errors),
"file_format" => self.file_format.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
// Listing all formats separately in case additional ones are added
match (self.isolation, self.file_format) {
(true, HistoryFileFormat::Plaintext) => {
errors.warn(ConfigWarning::IncompatibleOptions {
label: "history isolation only compatible with SQLite format",
span: isolation_span,
help: r#"disable history isolation, or set $env.config.history.file_format = "sqlite""#,
});
}
(true, HistoryFileFormat::Sqlite) => (),
(false, _) => (),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/hooks.rs | crates/nu-protocol/src/config/hooks.rs | use super::prelude::*;
use crate as nu_protocol;
use std::collections::HashMap;
/// Definition of a parsed hook from the config object
#[derive(Clone, Debug, IntoValue, PartialEq, Serialize, Deserialize)]
pub struct Hooks {
pub pre_prompt: Vec<Value>,
pub pre_execution: Vec<Value>,
pub env_change: HashMap<String, Vec<Value>>,
pub display_output: Option<Value>,
pub command_not_found: Option<Value>,
}
impl Hooks {
pub fn new() -> Self {
Self {
pre_prompt: Vec::new(),
pre_execution: Vec::new(),
env_change: HashMap::new(),
display_output: Some(Value::string(
"if (term size).columns >= 100 { table -e } else { table }",
Span::unknown(),
)),
command_not_found: None,
}
}
}
impl Default for Hooks {
fn default() -> Self {
Self::new()
}
}
impl UpdateFromValue for Hooks {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"pre_prompt" => {
if let Ok(hooks) = val.as_list() {
self.pre_prompt = hooks.into()
} else {
errors.type_mismatch(path, Type::list(Type::Any), val);
}
}
"pre_execution" => {
if let Ok(hooks) = val.as_list() {
self.pre_execution = hooks.into()
} else {
errors.type_mismatch(path, Type::list(Type::Any), val);
}
}
"env_change" => {
if let Ok(record) = val.as_record() {
self.env_change = record
.iter()
.map(|(key, val)| {
let old = self.env_change.remove(key).unwrap_or_default();
let new = if let Ok(hooks) = val.as_list() {
hooks.into()
} else {
errors.type_mismatch(
&path.push(key),
Type::list(Type::Any),
val,
);
old
};
(key.as_str().into(), new)
})
.collect();
} else {
errors.type_mismatch(path, Type::record(), val);
}
}
"display_output" => {
self.display_output = if val.is_nothing() {
None
} else {
Some(val.clone())
}
}
"command_not_found" => {
self.command_not_found = if val.is_nothing() {
None
} else {
Some(val.clone())
}
}
_ => errors.unknown_option(path, val),
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/mod.rs | crates/nu-protocol/src/config/mod.rs | //! Module containing the internal representation of user configuration
use crate::FromValue;
use crate::{self as nu_protocol};
use helper::*;
use prelude::*;
use std::collections::HashMap;
pub use ansi_coloring::UseAnsiColoring;
pub use completions::{
CompletionAlgorithm, CompletionConfig, CompletionSort, ExternalCompleterConfig,
};
pub use datetime_format::DatetimeFormatConfig;
pub use display_errors::DisplayErrors;
pub use filesize::FilesizeConfig;
pub use helper::extract_value;
pub use history::{HistoryConfig, HistoryFileFormat};
pub use hooks::Hooks;
pub use ls::LsConfig;
pub use output::{BannerKind, ErrorStyle};
pub use plugin_gc::{PluginGcConfig, PluginGcConfigs};
pub use reedline::{CursorShapeConfig, EditBindings, NuCursorShape, ParsedKeybinding, ParsedMenu};
pub use rm::RmConfig;
pub use shell_integration::ShellIntegrationConfig;
pub use table::{FooterMode, TableConfig, TableIndent, TableIndexMode, TableMode, TrimStrategy};
mod ansi_coloring;
mod completions;
mod datetime_format;
mod display_errors;
mod error;
mod filesize;
mod helper;
mod history;
mod hooks;
mod ls;
mod output;
mod plugin_gc;
mod prelude;
mod reedline;
mod rm;
mod shell_integration;
mod table;
#[derive(Clone, Debug, IntoValue, Serialize, Deserialize)]
pub struct Config {
pub filesize: FilesizeConfig,
pub table: TableConfig,
pub ls: LsConfig,
pub color_config: HashMap<String, Value>,
pub footer_mode: FooterMode,
pub float_precision: i64,
pub recursion_limit: i64,
pub use_ansi_coloring: UseAnsiColoring,
pub completions: CompletionConfig,
pub edit_mode: EditBindings,
pub show_hints: bool,
pub history: HistoryConfig,
pub keybindings: Vec<ParsedKeybinding>,
pub menus: Vec<ParsedMenu>,
pub hooks: Hooks,
pub rm: RmConfig,
pub shell_integration: ShellIntegrationConfig,
pub buffer_editor: Value,
pub show_banner: BannerKind,
pub bracketed_paste: bool,
pub render_right_prompt_on_last_line: bool,
pub explore: HashMap<String, Value>,
pub cursor_shape: CursorShapeConfig,
pub datetime_format: DatetimeFormatConfig,
pub error_style: ErrorStyle,
pub display_errors: DisplayErrors,
pub use_kitty_protocol: bool,
pub highlight_resolved_externals: bool,
/// Configuration for plugins.
///
/// Users can provide configuration for a plugin through this entry. The entry name must
/// match the registered plugin name so `plugin add nu_plugin_example` will be able to place
/// its configuration under a `nu_plugin_example` column.
pub plugins: HashMap<String, Value>,
/// Configuration for plugin garbage collection.
pub plugin_gc: PluginGcConfigs,
}
impl Default for Config {
fn default() -> Config {
Config {
show_banner: BannerKind::default(),
table: TableConfig::default(),
rm: RmConfig::default(),
ls: LsConfig::default(),
datetime_format: DatetimeFormatConfig::default(),
explore: HashMap::new(),
history: HistoryConfig::default(),
completions: CompletionConfig::default(),
recursion_limit: 50,
filesize: FilesizeConfig::default(),
cursor_shape: CursorShapeConfig::default(),
color_config: HashMap::new(),
footer_mode: FooterMode::RowCount(25),
float_precision: 2,
buffer_editor: Value::nothing(Span::unknown()),
use_ansi_coloring: UseAnsiColoring::default(),
bracketed_paste: true,
edit_mode: EditBindings::default(),
show_hints: true,
shell_integration: ShellIntegrationConfig::default(),
render_right_prompt_on_last_line: false,
hooks: Hooks::new(),
menus: Vec::new(),
keybindings: Vec::new(),
error_style: ErrorStyle::Fancy,
display_errors: DisplayErrors::default(),
use_kitty_protocol: false,
highlight_resolved_externals: false,
plugins: HashMap::new(),
plugin_gc: PluginGcConfigs::default(),
}
}
}
impl UpdateFromValue for Config {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"ls" => self.ls.update(val, path, errors),
"rm" => self.rm.update(val, path, errors),
"history" => self.history.update(val, path, errors),
"completions" => self.completions.update(val, path, errors),
"cursor_shape" => self.cursor_shape.update(val, path, errors),
"table" => self.table.update(val, path, errors),
"filesize" => self.filesize.update(val, path, errors),
"explore" => self.explore.update(val, path, errors),
"color_config" => self.color_config.update(val, path, errors),
"footer_mode" => self.footer_mode.update(val, path, errors),
"float_precision" => self.float_precision.update(val, path, errors),
"use_ansi_coloring" => self.use_ansi_coloring.update(val, path, errors),
"edit_mode" => self.edit_mode.update(val, path, errors),
"show_hints" => self.show_hints.update(val, path, errors),
"shell_integration" => self.shell_integration.update(val, path, errors),
"buffer_editor" => match val {
Value::Nothing { .. } | Value::String { .. } => {
self.buffer_editor = val.clone();
}
Value::List { vals, .. }
if vals.iter().all(|val| matches!(val, Value::String { .. })) =>
{
self.buffer_editor = val.clone();
}
_ => errors.type_mismatch(
path,
Type::custom("string, list<string>, or nothing"),
val,
),
},
"show_banner" => self.show_banner.update(val, path, errors),
"display_errors" => self.display_errors.update(val, path, errors),
"render_right_prompt_on_last_line" => self
.render_right_prompt_on_last_line
.update(val, path, errors),
"bracketed_paste" => self.bracketed_paste.update(val, path, errors),
"use_kitty_protocol" => self.use_kitty_protocol.update(val, path, errors),
"highlight_resolved_externals" => {
self.highlight_resolved_externals.update(val, path, errors)
}
"plugins" => self.plugins.update(val, path, errors),
"plugin_gc" => self.plugin_gc.update(val, path, errors),
"menus" => match Vec::from_value(val.clone()) {
Ok(menus) => self.menus = menus,
Err(err) => errors.error(err.into()),
},
"keybindings" => match Vec::from_value(val.clone()) {
Ok(keybindings) => self.keybindings = keybindings,
Err(err) => errors.error(err.into()),
},
"hooks" => self.hooks.update(val, path, errors),
"datetime_format" => self.datetime_format.update(val, path, errors),
"error_style" => self.error_style.update(val, path, errors),
"recursion_limit" => {
if let Ok(limit) = val.as_int() {
if limit > 1 {
self.recursion_limit = limit;
} else {
errors.invalid_value(path, "an int greater than 1", val);
}
} else {
errors.type_mismatch(path, Type::Int, val);
}
}
_ => errors.unknown_option(path, val),
}
}
}
}
impl Config {
pub fn update_from_value(
&mut self,
old: &Config,
value: &Value,
) -> Result<Option<ShellWarning>, ShellError> {
// Current behaviour is that config errors are displayed, but do not prevent the rest
// of the config from being updated (fields with errors are skipped/not updated).
// Errors are simply collected one-by-one and wrapped into a ShellError variant at the end.
let mut errors = ConfigErrors::new(old);
let mut path = ConfigPath::new();
self.update(value, &mut path, &mut errors);
errors.check()
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/completions.rs | crates/nu-protocol/src/config/completions.rs | use super::{config_update_string_enum, prelude::*};
use crate as nu_protocol;
use crate::engine::Closure;
#[derive(Clone, Copy, Debug, Default, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompletionAlgorithm {
#[default]
Prefix,
Substring,
Fuzzy,
}
impl FromStr for CompletionAlgorithm {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"prefix" => Ok(Self::Prefix),
"substring" => Ok(Self::Substring),
"fuzzy" => Ok(Self::Fuzzy),
_ => Err("'prefix' or 'fuzzy' or 'substring'"),
}
}
}
impl UpdateFromValue for CompletionAlgorithm {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
config_update_string_enum(self, value, path, errors)
}
}
#[derive(Clone, Copy, Debug, Default, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompletionSort {
#[default]
Smart,
Alphabetical,
}
impl FromStr for CompletionSort {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"smart" => Ok(Self::Smart),
"alphabetical" => Ok(Self::Alphabetical),
_ => Err("'smart' or 'alphabetical'"),
}
}
}
impl UpdateFromValue for CompletionSort {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
config_update_string_enum(self, value, path, errors)
}
}
#[derive(Clone, Debug, IntoValue, Serialize, Deserialize)]
pub struct ExternalCompleterConfig {
pub enable: bool,
pub max_results: i64,
pub completer: Option<Closure>,
}
impl Default for ExternalCompleterConfig {
fn default() -> Self {
Self {
enable: true,
max_results: 100,
completer: None,
}
}
}
impl UpdateFromValue for ExternalCompleterConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"completer" => match val {
Value::Nothing { .. } => self.completer = None,
Value::Closure { val, .. } => self.completer = Some(val.as_ref().clone()),
_ => errors.type_mismatch(path, Type::custom("closure or nothing"), val),
},
"max_results" => self.max_results.update(val, path, errors),
"enable" => self.enable.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
}
#[derive(Clone, Debug, IntoValue, Serialize, Deserialize)]
pub struct CompletionConfig {
pub sort: CompletionSort,
pub case_sensitive: bool,
pub quick: bool,
pub partial: bool,
pub algorithm: CompletionAlgorithm,
pub external: ExternalCompleterConfig,
pub use_ls_colors: bool,
}
impl Default for CompletionConfig {
fn default() -> Self {
Self {
sort: CompletionSort::default(),
case_sensitive: false,
quick: true,
partial: true,
algorithm: CompletionAlgorithm::default(),
external: ExternalCompleterConfig::default(),
use_ls_colors: true,
}
}
}
impl UpdateFromValue for CompletionConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"sort" => self.sort.update(val, path, errors),
"quick" => self.quick.update(val, path, errors),
"partial" => self.partial.update(val, path, errors),
"algorithm" => self.algorithm.update(val, path, errors),
"case_sensitive" => self.case_sensitive.update(val, path, errors),
"external" => self.external.update(val, path, errors),
"use_ls_colors" => self.use_ls_colors.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/plugin_gc.rs | crates/nu-protocol/src/config/plugin_gc.rs | use super::prelude::*;
use crate as nu_protocol;
use std::collections::HashMap;
/// Configures when plugins should be stopped if inactive
#[derive(Clone, Debug, Default, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginGcConfigs {
/// The config to use for plugins not otherwise specified
pub default: PluginGcConfig,
/// Specific configs for plugins (by name)
pub plugins: HashMap<String, PluginGcConfig>,
}
impl PluginGcConfigs {
/// Get the plugin GC configuration for a specific plugin name. If not specified by name in the
/// config, this is `default`.
pub fn get(&self, plugin_name: &str) -> &PluginGcConfig {
self.plugins.get(plugin_name).unwrap_or(&self.default)
}
}
impl UpdateFromValue for PluginGcConfigs {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"default" => self.default.update(val, path, errors),
"plugins" => self.plugins.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
}
/// Configures when a plugin should be stopped if inactive
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginGcConfig {
/// True if the plugin should be stopped automatically
pub enabled: bool,
/// When to stop the plugin if not in use for this long (in nanoseconds)
pub stop_after: i64,
}
impl Default for PluginGcConfig {
fn default() -> Self {
PluginGcConfig {
enabled: true,
stop_after: 10_000_000_000, // 10sec
}
}
}
impl IntoValue for PluginGcConfig {
fn into_value(self, span: Span) -> Value {
record! {
"enabled" => self.enabled.into_value(span),
"stop_after" => Value::duration(self.stop_after, span),
}
.into_value(span)
}
}
impl UpdateFromValue for PluginGcConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"enabled" => self.enabled.update(val, path, errors),
"stop_after" => {
if let Ok(duration) = val.as_duration() {
if duration >= 0 {
self.stop_after = duration;
} else {
errors.invalid_value(path, "a non-negative duration", val);
}
} else {
errors.type_mismatch(path, Type::Duration, val);
}
}
_ => errors.unknown_option(path, val),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Config, Span, record};
fn test_pair() -> (PluginGcConfigs, Value) {
(
PluginGcConfigs {
default: PluginGcConfig {
enabled: true,
stop_after: 30_000_000_000,
},
plugins: [(
"my_plugin".to_owned(),
PluginGcConfig {
enabled: false,
stop_after: 0,
},
)]
.into_iter()
.collect(),
},
Value::test_record(record! {
"default" => Value::test_record(record! {
"enabled" => Value::test_bool(true),
"stop_after" => Value::test_duration(30_000_000_000),
}),
"plugins" => Value::test_record(record! {
"my_plugin" => Value::test_record(record! {
"enabled" => Value::test_bool(false),
"stop_after" => Value::test_duration(0),
}),
}),
}),
)
}
#[test]
fn update() {
let (expected, input) = test_pair();
let config = Config::default();
let mut errors = ConfigErrors::new(&config);
let mut result = PluginGcConfigs::default();
result.update(&input, &mut ConfigPath::new(), &mut errors);
assert!(!errors.has_errors(), "errors: {errors:#?}");
assert_eq!(expected, result);
}
#[test]
fn reconstruct() {
let (input, expected) = test_pair();
assert_eq!(expected, input.into_value(Span::test_data()));
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/output.rs | crates/nu-protocol/src/config/output.rs | use super::{config_update_string_enum, prelude::*};
use crate::{self as nu_protocol};
#[derive(Clone, Copy, Debug, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub enum ErrorStyle {
Fancy,
Plain,
Short,
}
impl FromStr for ErrorStyle {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"fancy" => Ok(Self::Fancy),
"plain" => Ok(Self::Plain),
"short" => Ok(Self::Short),
_ => Err("'fancy', 'plain', or 'short'"),
}
}
}
impl UpdateFromValue for ErrorStyle {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
config_update_string_enum(self, value, path, errors)
}
}
/// Option: show_banner
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum BannerKind {
/// No banner on startup
None,
/// Abbreviated banner just containing the startup-time
Short,
/// The full banner including Ellie
#[default]
Full,
}
impl IntoValue for BannerKind {
fn into_value(self, span: Span) -> Value {
match self {
// This uses a custom implementation to reflect common config
// bool: true, false was used for a long time
// string: short was added later
BannerKind::None => Value::bool(false, span),
BannerKind::Short => Value::string("short", span),
BannerKind::Full => Value::bool(true, span),
}
}
}
impl UpdateFromValue for BannerKind {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
match value {
Value::Bool { val, .. } => match val {
true => {
*self = BannerKind::Full;
}
false => {
*self = BannerKind::None;
}
},
Value::String { val, .. } => match val.as_str() {
"true" => {
*self = BannerKind::Full;
}
"full" => {
*self = BannerKind::Full;
}
"short" => {
*self = BannerKind::Short;
}
"false" => {
*self = BannerKind::None;
}
"none" => {
*self = BannerKind::None;
}
_ => {
errors.invalid_value(path, "true/'full', 'short', false/'none'", value);
}
},
_ => {
errors.invalid_value(path, "true/'full', 'short', false/'none'", value);
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/reedline.rs | crates/nu-protocol/src/config/reedline.rs | use super::{config_update_string_enum, prelude::*};
use crate as nu_protocol;
use crate::{FromValue, engine::Closure};
/// Definition of a parsed keybinding from the config object
#[derive(Clone, Debug, FromValue, IntoValue, Serialize, Deserialize)]
pub struct ParsedKeybinding {
pub name: Option<Value>,
pub modifier: Value,
pub keycode: Value,
pub event: Value,
pub mode: Value,
}
/// Definition of a parsed menu from the config object
#[derive(Clone, Debug, FromValue, IntoValue, Serialize, Deserialize)]
pub struct ParsedMenu {
pub name: Value,
pub marker: Value,
pub only_buffer_difference: Value,
pub style: Value,
pub r#type: Value,
pub source: Option<Closure>,
}
/// Definition of a Nushell CursorShape (to be mapped to crossterm::cursor::CursorShape)
#[derive(Clone, Copy, Debug, Default, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub enum NuCursorShape {
Underscore,
Line,
Block,
BlinkUnderscore,
BlinkLine,
BlinkBlock,
#[default]
Inherit,
}
impl FromStr for NuCursorShape {
type Err = &'static str;
fn from_str(s: &str) -> Result<NuCursorShape, &'static str> {
match s.to_ascii_lowercase().as_str() {
"line" => Ok(NuCursorShape::Line),
"block" => Ok(NuCursorShape::Block),
"underscore" => Ok(NuCursorShape::Underscore),
"blink_line" => Ok(NuCursorShape::BlinkLine),
"blink_block" => Ok(NuCursorShape::BlinkBlock),
"blink_underscore" => Ok(NuCursorShape::BlinkUnderscore),
"inherit" => Ok(NuCursorShape::Inherit),
_ => Err(
"'line', 'block', 'underscore', 'blink_line', 'blink_block', 'blink_underscore' or 'inherit'",
),
}
}
}
impl UpdateFromValue for NuCursorShape {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
config_update_string_enum(self, value, path, errors)
}
}
#[derive(Clone, Copy, Debug, Default, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub struct CursorShapeConfig {
pub emacs: NuCursorShape,
pub vi_insert: NuCursorShape,
pub vi_normal: NuCursorShape,
}
impl UpdateFromValue for CursorShapeConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"vi_insert" => self.vi_insert.update(val, path, errors),
"vi_normal" => self.vi_normal.update(val, path, errors),
"emacs" => self.emacs.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
}
#[derive(Clone, Copy, Debug, Default, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub enum EditBindings {
Vi,
#[default]
Emacs,
}
impl FromStr for EditBindings {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
"vi" => Ok(Self::Vi),
"emacs" => Ok(Self::Emacs),
_ => Err("'emacs' or 'vi'"),
}
}
}
impl UpdateFromValue for EditBindings {
fn update(&mut self, value: &Value, path: &mut ConfigPath, errors: &mut ConfigErrors) {
config_update_string_enum(self, value, path, errors)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/shell_integration.rs | crates/nu-protocol/src/config/shell_integration.rs | use super::prelude::*;
use crate as nu_protocol;
#[derive(Clone, Copy, Debug, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShellIntegrationConfig {
pub osc2: bool,
pub osc7: bool,
pub osc8: bool,
pub osc9_9: bool,
pub osc133: bool,
pub osc633: bool,
pub reset_application_mode: bool,
}
#[allow(clippy::derivable_impls)]
impl Default for ShellIntegrationConfig {
fn default() -> Self {
Self {
osc2: true,
osc7: !cfg!(windows),
osc8: true,
osc9_9: cfg!(windows),
osc133: true,
osc633: true,
reset_application_mode: true,
}
}
}
impl UpdateFromValue for ShellIntegrationConfig {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"osc2" => self.osc2.update(val, path, errors),
"osc7" => self.osc7.update(val, path, errors),
"osc8" => self.osc8.update(val, path, errors),
"osc9_9" => self.osc9_9.update(val, path, errors),
"osc133" => self.osc133.update(val, path, errors),
"osc633" => self.osc633.update(val, path, errors),
"reset_application_mode" => self.reset_application_mode.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/config/display_errors.rs | crates/nu-protocol/src/config/display_errors.rs | use super::prelude::*;
use crate as nu_protocol;
use crate::ShellError;
#[derive(Clone, Copy, Debug, IntoValue, PartialEq, Eq, Serialize, Deserialize)]
pub struct DisplayErrors {
pub exit_code: bool,
pub termination_signal: bool,
}
impl DisplayErrors {
pub fn should_show(&self, error: &ShellError) -> bool {
match error {
ShellError::NonZeroExitCode { .. } => self.exit_code,
#[cfg(unix)]
ShellError::TerminatedBySignal { .. } => self.termination_signal,
_ => true,
}
}
}
impl Default for DisplayErrors {
fn default() -> Self {
Self {
exit_code: false,
termination_signal: true,
}
}
}
impl UpdateFromValue for DisplayErrors {
fn update<'a>(
&mut self,
value: &'a Value,
path: &mut ConfigPath<'a>,
errors: &mut ConfigErrors,
) {
let Value::Record { val: record, .. } = value else {
errors.type_mismatch(path, Type::record(), value);
return;
};
for (col, val) in record.iter() {
let path = &mut path.push(col);
match col.as_str() {
"exit_code" => self.exit_code.update(val, path, errors),
"termination_signal" => self.termination_signal.update(val, path, errors),
_ => errors.unknown_option(path, val),
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/argument.rs | crates/nu-protocol/src/engine/argument.rs | use std::sync::Arc;
use crate::{Span, Value, ast::Expression, ir::DataSlice};
/// Represents a fully evaluated argument to a call.
#[derive(Debug, Clone)]
pub enum Argument {
/// A positional argument
Positional {
span: Span,
val: Value,
ast: Option<Arc<Expression>>,
},
/// A spread argument, e.g. `...$args`
Spread {
span: Span,
vals: Value,
ast: Option<Arc<Expression>>,
},
/// A named argument with no value, e.g. `--flag`
Flag {
data: Arc<[u8]>,
name: DataSlice,
short: DataSlice,
span: Span,
},
/// A named argument with a value, e.g. `--flag value` or `--flag=`
Named {
data: Arc<[u8]>,
name: DataSlice,
short: DataSlice,
span: Span,
val: Value,
ast: Option<Arc<Expression>>,
},
/// Information generated by the parser for use by certain keyword commands
ParserInfo {
data: Arc<[u8]>,
name: DataSlice,
// TODO: rather than `Expression`, this would probably be best served by a specific enum
// type for this purpose.
info: Box<Expression>,
},
}
impl Argument {
/// The span encompassing the argument's usage within the call, distinct from the span of the
/// actual value of the argument.
pub fn span(&self) -> Option<Span> {
match self {
Argument::Positional { span, .. } => Some(*span),
Argument::Spread { span, .. } => Some(*span),
Argument::Flag { span, .. } => Some(*span),
Argument::Named { span, .. } => Some(*span),
// Because `ParserInfo` is generated, its span shouldn't be used
Argument::ParserInfo { .. } => None,
}
}
/// The original AST [`Expression`] for the argument's value. This is not usually available;
/// declarations have to opt-in if they require this.
pub fn ast_expression(&self) -> Option<&Arc<Expression>> {
match self {
Argument::Positional { ast, .. } => ast.as_ref(),
Argument::Spread { ast, .. } => ast.as_ref(),
Argument::Flag { .. } => None,
Argument::Named { ast, .. } => ast.as_ref(),
Argument::ParserInfo { .. } => None,
}
}
}
/// Stores the argument context for calls in IR evaluation.
#[derive(Debug, Clone, Default)]
pub struct ArgumentStack {
arguments: Vec<Argument>,
}
impl ArgumentStack {
/// Create a new, empty argument stack.
pub const fn new() -> Self {
ArgumentStack { arguments: vec![] }
}
/// Returns the index of the end of the argument stack. Call and save this before adding
/// arguments.
pub fn get_base(&self) -> usize {
self.arguments.len()
}
/// Calculates the number of arguments past the given [previously retrieved](.get_base) base
/// pointer.
pub fn get_len(&self, base: usize) -> usize {
self.arguments.len().checked_sub(base).unwrap_or_else(|| {
panic!(
"base ({}) is beyond the end of the arguments stack ({})",
base,
self.arguments.len()
);
})
}
/// Push an argument onto the end of the argument stack.
pub fn push(&mut self, argument: Argument) {
self.arguments.push(argument);
}
/// Clear all of the arguments after the given base index, to prepare for the next frame.
pub fn leave_frame(&mut self, base: usize) {
self.arguments.truncate(base);
}
/// Get arguments for the frame based on the given [`base`](`.get_base()`) and
/// [`len`](`.get_len()`) parameters.
pub fn get_args(&self, base: usize, len: usize) -> &[Argument] {
&self.arguments[base..(base + len)]
}
/// Move arguments for the frame based on the given [`base`](`.get_base()`) and
/// [`len`](`.get_len()`) parameters.
pub fn drain_args(&mut self, base: usize, len: usize) -> impl Iterator<Item = Argument> + '_ {
self.arguments.drain(base..(base + len))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/jobs.rs | crates/nu-protocol/src/engine/jobs.rs | use std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
sync::{
Arc, Mutex,
mpsc::{Receiver, RecvTimeoutError, Sender, TryRecvError},
},
};
#[cfg(not(target_family = "wasm"))]
use std::time::{Duration, Instant};
use nu_system::{UnfreezeHandle, kill_by_pid};
use crate::{PipelineData, Signals, shell_error};
use crate::JobId;
pub struct Jobs {
next_job_id: usize,
// this is the ID of the most recently added frozen job in the jobs table.
// the methods of this struct must ensure the invariant of this always
// being None or pointing to a valid job in the table
last_frozen_job_id: Option<JobId>,
jobs: HashMap<JobId, Job>,
}
impl Default for Jobs {
fn default() -> Self {
Self {
next_job_id: 1,
last_frozen_job_id: None,
jobs: HashMap::default(),
}
}
}
impl Jobs {
pub fn iter(&self) -> impl Iterator<Item = (JobId, &Job)> {
self.jobs.iter().map(|(k, v)| (*k, v))
}
pub fn lookup(&self, id: JobId) -> Option<&Job> {
self.jobs.get(&id)
}
pub fn lookup_mut(&mut self, id: JobId) -> Option<&mut Job> {
self.jobs.get_mut(&id)
}
pub fn remove_job(&mut self, id: JobId) -> Option<Job> {
if self.last_frozen_job_id.is_some_and(|last| id == last) {
self.last_frozen_job_id = None;
}
self.jobs.remove(&id)
}
fn assign_last_frozen_id_if_frozen(&mut self, id: JobId, job: &Job) {
if let Job::Frozen(_) = job {
self.last_frozen_job_id = Some(id);
}
}
pub fn add_job(&mut self, job: Job) -> JobId {
let this_id = JobId::new(self.next_job_id);
self.assign_last_frozen_id_if_frozen(this_id, &job);
self.jobs.insert(this_id, job);
self.next_job_id += 1;
this_id
}
pub fn most_recent_frozen_job_id(&mut self) -> Option<JobId> {
self.last_frozen_job_id
}
// this is useful when you want to remove a job from the list and add it back later
pub fn add_job_with_id(&mut self, id: JobId, job: Job) -> Result<(), &'static str> {
self.assign_last_frozen_id_if_frozen(id, &job);
if let std::collections::hash_map::Entry::Vacant(e) = self.jobs.entry(id) {
e.insert(job);
Ok(())
} else {
Err("job already exists")
}
}
/// This function tries to forcefully kill a job from this job table,
/// removes it from the job table. It always succeeds in removing the job
/// from the table, but may fail in killing the job's active processes.
pub fn kill_and_remove(&mut self, id: JobId) -> shell_error::io::Result<()> {
if let Some(job) = self.jobs.get(&id) {
let err = job.kill();
self.remove_job(id);
err?
}
Ok(())
}
/// This function tries to forcefully kill all the background jobs and
/// removes all of them from the job table.
///
/// It returns an error if any of the job killing attempts fails, but always
/// succeeds in removing the jobs from the table.
pub fn kill_all(&mut self) -> shell_error::io::Result<()> {
self.last_frozen_job_id = None;
let first_err = self
.iter()
.map(|(_, job)| job.kill().err())
.fold(None, |acc, x| acc.or(x));
self.jobs.clear();
if let Some(err) = first_err {
Err(err)
} else {
Ok(())
}
}
}
pub enum Job {
Thread(ThreadJob),
Frozen(FrozenJob),
}
// A thread job represents a job that is currently executing as a background thread in nushell.
// This is an Arc-y type, cloning it does not uniquely clone the information of this particular
// job.
// Although rust's documentation does not document the acquire-release semantics of Mutex, this
// is a direct undocumentented requirement of its soundness, and is thus assumed by this
// implementaation.
// see issue https://github.com/rust-lang/rust/issues/126239.
#[derive(Clone)]
pub struct ThreadJob {
signals: Signals,
pids: Arc<Mutex<HashSet<u32>>>,
tag: Option<String>,
pub sender: Sender<Mail>,
}
impl ThreadJob {
pub fn new(signals: Signals, tag: Option<String>, sender: Sender<Mail>) -> Self {
ThreadJob {
signals,
pids: Arc::new(Mutex::new(HashSet::default())),
sender,
tag,
}
}
/// Tries to add the provided pid to the active pid set of the current job.
///
/// Returns true if the pid was added successfully, or false if the
/// current job is interrupted.
pub fn try_add_pid(&self, pid: u32) -> bool {
let mut pids = self.pids.lock().expect("PIDs lock was poisoned");
// note: this signals check must occur after the pids lock has been locked.
if self.signals.interrupted() {
false
} else {
pids.insert(pid);
true
}
}
pub fn collect_pids(&self) -> Vec<u32> {
let lock = self.pids.lock().expect("PID lock was poisoned");
lock.iter().copied().collect()
}
pub fn kill(&self) -> shell_error::io::Result<()> {
// it's okay to make this interrupt outside of the mutex, since it has acquire-release
// semantics.
self.signals.trigger();
let mut pids = self.pids.lock().expect("PIDs lock was poisoned");
for pid in pids.iter() {
kill_by_pid((*pid).into())?;
}
pids.clear();
Ok(())
}
pub fn remove_pid(&self, pid: u32) {
let mut pids = self.pids.lock().expect("PID lock was poisoned");
pids.remove(&pid);
}
}
impl Job {
pub fn kill(&self) -> shell_error::io::Result<()> {
match self {
Job::Thread(thread_job) => thread_job.kill(),
Job::Frozen(frozen_job) => frozen_job.kill(),
}
}
pub fn tag(&self) -> Option<&String> {
match self {
Job::Thread(thread_job) => thread_job.tag.as_ref(),
Job::Frozen(frozen_job) => frozen_job.tag.as_ref(),
}
}
pub fn assign_tag(&mut self, tag: Option<String>) {
match self {
Job::Thread(thread_job) => thread_job.tag = tag,
Job::Frozen(frozen_job) => frozen_job.tag = tag,
}
}
}
pub struct FrozenJob {
pub unfreeze: UnfreezeHandle,
pub tag: Option<String>,
}
impl FrozenJob {
pub fn kill(&self) -> shell_error::io::Result<()> {
#[cfg(unix)]
{
Ok(kill_by_pid(self.unfreeze.pid() as i64)?)
}
// it doesn't happen outside unix.
#[cfg(not(unix))]
{
Ok(())
}
}
}
/// Stores the information about the background job currently being executed by this thread, if any
#[derive(Clone)]
pub struct CurrentJob {
pub id: JobId,
// The background thread job associated with this thread.
// If None, it indicates this thread is currently the main job
pub background_thread_job: Option<ThreadJob>,
// note: although the mailbox is Mutex'd, it is only ever accessed
// by the current job's threads
pub mailbox: Arc<Mutex<Mailbox>>,
}
// The storage for unread messages
//
// Messages are initially sent over a mpsc channel,
// and may then be stored in a IgnoredMail struct when
// filtered out by a tag.
pub struct Mailbox {
receiver: Receiver<Mail>,
ignored_mail: IgnoredMail,
}
impl Mailbox {
pub fn new(receiver: Receiver<Mail>) -> Self {
Mailbox {
receiver,
ignored_mail: IgnoredMail::default(),
}
}
#[cfg(not(target_family = "wasm"))]
pub fn recv_timeout(
&mut self,
filter_tag: Option<FilterTag>,
timeout: Duration,
) -> Result<PipelineData, RecvTimeoutError> {
if let Some(value) = self.ignored_mail.pop(filter_tag) {
Ok(value)
} else {
let mut waited_so_far = Duration::ZERO;
let mut before = Instant::now();
while waited_so_far < timeout {
let (tag, value) = self.receiver.recv_timeout(timeout - waited_so_far)?;
if filter_tag.is_none() || filter_tag == tag {
return Ok(value);
} else {
self.ignored_mail.add((tag, value));
let now = Instant::now();
waited_so_far += now - before;
before = now;
}
}
Err(RecvTimeoutError::Timeout)
}
}
#[cfg(not(target_family = "wasm"))]
pub fn try_recv(
&mut self,
filter_tag: Option<FilterTag>,
) -> Result<PipelineData, TryRecvError> {
if let Some(value) = self.ignored_mail.pop(filter_tag) {
Ok(value)
} else {
loop {
let (tag, value) = self.receiver.try_recv()?;
if filter_tag.is_none() || filter_tag == tag {
return Ok(value);
} else {
self.ignored_mail.add((tag, value));
}
}
}
}
pub fn clear(&mut self) {
self.ignored_mail.clear();
while self.receiver.try_recv().is_ok() {}
}
}
// A data structure used to store messages which were received, but currently ignored by a tag filter
// messages are added and popped in a first-in-first-out matter.
#[derive(Default)]
struct IgnoredMail {
next_id: usize,
messages: BTreeMap<usize, Mail>,
by_tag: HashMap<FilterTag, BTreeSet<usize>>,
}
pub type FilterTag = u64;
pub type Mail = (Option<FilterTag>, PipelineData);
impl IgnoredMail {
pub fn add(&mut self, (tag, value): Mail) {
let id = self.next_id;
self.next_id += 1;
self.messages.insert(id, (tag, value));
if let Some(tag) = tag {
self.by_tag.entry(tag).or_default().insert(id);
}
}
pub fn pop(&mut self, tag: Option<FilterTag>) -> Option<PipelineData> {
if let Some(tag) = tag {
self.pop_oldest_with_tag(tag)
} else {
self.pop_oldest()
}
}
pub fn clear(&mut self) {
self.messages.clear();
self.by_tag.clear();
}
fn pop_oldest(&mut self) -> Option<PipelineData> {
let (id, (tag, value)) = self.messages.pop_first()?;
if let Some(tag) = tag {
let needs_cleanup = if let Some(ids) = self.by_tag.get_mut(&tag) {
ids.remove(&id);
ids.is_empty()
} else {
false
};
if needs_cleanup {
self.by_tag.remove(&tag);
}
}
Some(value)
}
fn pop_oldest_with_tag(&mut self, tag: FilterTag) -> Option<PipelineData> {
let ids = self.by_tag.get_mut(&tag)?;
let id = ids.pop_first()?;
if ids.is_empty() {
self.by_tag.remove(&tag);
}
Some(self.messages.remove(&id)?.1)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/variable.rs | crates/nu-protocol/src/engine/variable.rs | use crate::{Span, Type, Value};
#[derive(Clone, Debug)]
pub struct Variable {
pub declaration_span: Span,
pub ty: Type,
pub mutable: bool,
pub const_val: Option<Value>,
}
impl Variable {
pub fn new(declaration_span: Span, ty: Type, mutable: bool) -> Variable {
Self {
declaration_span,
ty,
mutable,
const_val: None,
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/sequence.rs | crates/nu-protocol/src/engine/sequence.rs | use crate::ShellError;
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
/// Implements an atomically incrementing sequential series of numbers
#[derive(Debug, Default)]
pub struct Sequence(AtomicUsize);
impl Sequence {
/// Return the next available id from a sequence, returning an error on overflow
#[track_caller]
pub fn next(&self) -> Result<usize, ShellError> {
// It's totally safe to use Relaxed ordering here, as there aren't other memory operations
// that depend on this value having been set for safety
//
// We're only not using `fetch_add` so that we can check for overflow, as wrapping with the
// identifier would lead to a serious bug - however unlikely that is.
self.0
.fetch_update(Relaxed, Relaxed, |current| current.checked_add(1))
.map_err(|_| ShellError::NushellFailedHelp {
msg: "an accumulator for identifiers overflowed".into(),
help: format!("see {}", std::panic::Location::caller()),
})
}
}
#[test]
fn output_is_sequential() {
let sequence = Sequence::default();
for (expected, generated) in (0..1000).zip(std::iter::repeat_with(|| sequence.next())) {
assert_eq!(expected, generated.expect("error in sequence"));
}
}
#[test]
fn output_is_unique_even_under_contention() {
let sequence = Sequence::default();
std::thread::scope(|scope| {
// Spawn four threads, all advancing the sequence simultaneously
let threads = (0..4)
.map(|_| {
scope.spawn(|| {
(0..100000)
.map(|_| sequence.next())
.collect::<Result<Vec<_>, _>>()
})
})
.collect::<Vec<_>>();
// Collect all of the results into a single flat vec
let mut results = threads
.into_iter()
.flat_map(|thread| thread.join().expect("panicked").expect("error"))
.collect::<Vec<usize>>();
// Check uniqueness
results.sort();
let initial_length = results.len();
results.dedup();
let deduplicated_length = results.len();
assert_eq!(initial_length, deduplicated_length);
})
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/command.rs | crates/nu-protocol/src/engine/command.rs | use serde::{Deserialize, Serialize};
use super::{EngineState, Stack, StateWorkingSet};
use crate::{
Alias, BlockId, DeprecationEntry, DynamicCompletionCallRef, DynamicSuggestion, Example,
OutDest, PipelineData, ShellError, Signature, Value, engine::Call,
};
use std::{borrow::Cow, fmt::Display};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArgType<'a> {
Flag(Cow<'a, str>),
Positional(usize),
}
impl<'a> Display for ArgType<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ArgType::Flag(flag_name) => match flag_name {
Cow::Borrowed(v) => write!(f, "{v}"),
Cow::Owned(v) => write!(f, "{v}"),
},
ArgType::Positional(idx) => write!(f, "{idx}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CommandType {
Builtin,
Custom,
Keyword,
External,
Alias,
Plugin,
}
impl Display for CommandType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let str = match self {
CommandType::Builtin => "built-in",
CommandType::Custom => "custom",
CommandType::Keyword => "keyword",
CommandType::External => "external",
CommandType::Alias => "alias",
CommandType::Plugin => "plugin",
};
write!(f, "{str}")
}
}
pub trait Command: Send + Sync + CommandClone {
fn name(&self) -> &str;
fn signature(&self) -> Signature;
/// Short preferably single sentence description for the command.
///
/// Will be shown with the completions etc.
fn description(&self) -> &str;
/// Longer documentation description, if necessary.
///
/// Will be shown below `description`
fn extra_description(&self) -> &str {
""
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError>;
/// Used by the parser to run command at parse time
///
/// If a command has `is_const()` set to true, it must also implement this method.
#[allow(unused_variables)]
fn run_const(
&self,
working_set: &StateWorkingSet,
call: &Call,
input: PipelineData,
) -> Result<PipelineData, ShellError> {
Err(ShellError::MissingConstEvalImpl { span: call.head })
}
fn examples(&self) -> Vec<Example<'_>> {
Vec::new()
}
// Related terms to help with command search
fn search_terms(&self) -> Vec<&str> {
vec![]
}
fn attributes(&self) -> Vec<(String, Value)> {
vec![]
}
// Whether can run in const evaluation in the parser
fn is_const(&self) -> bool {
false
}
// Is a sub command
fn is_sub(&self) -> bool {
self.name().contains(' ')
}
// If command is a block i.e. def blah [] { }, get the block id
fn block_id(&self) -> Option<BlockId> {
None
}
// Return reference to the command as Alias
fn as_alias(&self) -> Option<&Alias> {
None
}
/// The identity of the plugin, if this is a plugin command
#[cfg(feature = "plugin")]
fn plugin_identity(&self) -> Option<&crate::PluginIdentity> {
None
}
fn command_type(&self) -> CommandType {
CommandType::Builtin
}
fn is_builtin(&self) -> bool {
self.command_type() == CommandType::Builtin
}
fn is_custom(&self) -> bool {
self.command_type() == CommandType::Custom
}
fn is_keyword(&self) -> bool {
self.command_type() == CommandType::Keyword
}
fn is_known_external(&self) -> bool {
self.command_type() == CommandType::External
}
fn is_alias(&self) -> bool {
self.command_type() == CommandType::Alias
}
fn is_plugin(&self) -> bool {
self.command_type() == CommandType::Plugin
}
fn deprecation_info(&self) -> Vec<DeprecationEntry> {
vec![]
}
fn pipe_redirection(&self) -> (Option<OutDest>, Option<OutDest>) {
(None, None)
}
// engine_state and stack are required to get completion from plugin.
/// Get completion items for `arg_type`.
///
/// It's useful when you want to get auto completion items of a flag or positional argument
/// dynamically.
///
/// The implementation can returns 3 types of return values:
/// - None: I couldn't find any suggestions, please fall back to default completions
/// - Some(vec![]): there are no suggestions
/// - Some(vec![item1, item2]): item1 and item2 are available
#[allow(unused_variables)]
#[expect(deprecated)]
fn get_dynamic_completion(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: DynamicCompletionCallRef,
arg_type: &ArgType,
_experimental: ExperimentalMarker,
) -> Result<Option<Vec<DynamicSuggestion>>, ShellError> {
Ok(None)
}
/// Return true if the AST nodes for the arguments are required for IR evaluation. This is
/// currently inefficient so is not generally done.
fn requires_ast_for_arguments(&self) -> bool {
false
}
}
pub trait CommandClone {
fn clone_box(&self) -> Box<dyn Command>;
}
impl<T> CommandClone for T
where
T: 'static + Command + Clone,
{
fn clone_box(&self) -> Box<dyn Command> {
Box::new(self.clone())
}
}
impl Clone for Box<dyn Command> {
fn clone(&self) -> Box<dyn Command> {
self.clone_box()
}
}
/// Marker type for tagging [`Command`] methods as experimental.
///
/// Add this marker as a parameter to a method to make implementors see a deprecation warning when
/// they implement it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[deprecated(note = "this method is very experimental, likely to change")]
pub struct ExperimentalMarker;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/call.rs | crates/nu-protocol/src/engine/call.rs | use crate::{
DeclId, FromValue, ShellError, Span, Value,
ast::{self, Expression},
ir,
};
use super::{EngineState, Stack, StateWorkingSet};
/// This is a HACK to help [`Command`](super::Command) support both the old AST evaluator and the
/// new IR evaluator at the same time. It should be removed once we are satisfied with the new
/// evaluator.
#[derive(Debug, Clone)]
pub struct Call<'a> {
pub head: Span,
pub decl_id: DeclId,
pub inner: CallImpl<'a>,
}
#[derive(Debug, Clone)]
pub enum CallImpl<'a> {
AstRef(&'a ast::Call),
AstBox(Box<ast::Call>),
IrRef(&'a ir::Call),
IrBox(Box<ir::Call>),
}
impl Call<'_> {
/// Returns a new AST call with the given span. This is often used by commands that need an
/// empty call to pass to a command. It's not easily possible to add anything to this.
pub fn new(span: Span) -> Self {
// this is using the boxed variant, which isn't so efficient... but this is only temporary
// anyway.
Call {
head: span,
decl_id: DeclId::new(0),
inner: CallImpl::AstBox(Box::new(ast::Call::new(span))),
}
}
/// Convert the `Call` from any lifetime into `'static`, by cloning the data within onto the
/// heap.
pub fn to_owned(&self) -> Call<'static> {
Call {
head: self.head,
decl_id: self.decl_id,
inner: self.inner.to_owned(),
}
}
/// Assert that the call is `ast::Call`, and fail with an error if it isn't.
///
/// Provided as a stop-gap for commands that can't work with `ir::Call`, or just haven't been
/// implemented yet. Eventually these issues should be resolved and then this can be removed.
pub fn assert_ast_call(&self) -> Result<&ast::Call, ShellError> {
match &self.inner {
CallImpl::AstRef(call) => Ok(call),
CallImpl::AstBox(call) => Ok(call),
_ => Err(ShellError::NushellFailedSpanned {
msg: "Can't be used in IR context".into(),
label: "this command is not yet supported by IR evaluation".into(),
span: self.head,
}),
}
}
/// FIXME: implementation asserts `ast::Call` and proxies to that
pub fn has_flag_const(
&self,
working_set: &StateWorkingSet,
flag_name: &str,
) -> Result<bool, ShellError> {
self.assert_ast_call()?
.has_flag_const(working_set, flag_name)
}
/// FIXME: implementation asserts `ast::Call` and proxies to that
pub fn get_flag_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
name: &str,
) -> Result<Option<T>, ShellError> {
self.assert_ast_call()?.get_flag_const(working_set, name)
}
/// FIXME: implementation asserts `ast::Call` and proxies to that
pub fn req_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
pos: usize,
) -> Result<T, ShellError> {
self.assert_ast_call()?.req_const(working_set, pos)
}
/// FIXME: implementation asserts `ast::Call` and proxies to that
pub fn rest_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
starting_pos: usize,
) -> Result<Vec<T>, ShellError> {
self.assert_ast_call()?
.rest_const(working_set, starting_pos)
}
/// Returns a span covering the call's arguments.
pub fn arguments_span(&self) -> Span {
match &self.inner {
CallImpl::AstRef(call) => call.arguments_span(),
CallImpl::AstBox(call) => call.arguments_span(),
CallImpl::IrRef(call) => call.arguments_span(),
CallImpl::IrBox(call) => call.arguments_span(),
}
}
/// Returns a span covering the whole call.
pub fn span(&self) -> Span {
match &self.inner {
CallImpl::AstRef(call) => call.span(),
CallImpl::AstBox(call) => call.span(),
CallImpl::IrRef(call) => call.span(),
CallImpl::IrBox(call) => call.span(),
}
}
/// Get a parser info argument by name.
pub fn get_parser_info<'a>(&'a self, stack: &'a Stack, name: &str) -> Option<&'a Expression> {
match &self.inner {
CallImpl::AstRef(call) => call.get_parser_info(name),
CallImpl::AstBox(call) => call.get_parser_info(name),
CallImpl::IrRef(call) => call.get_parser_info(stack, name),
CallImpl::IrBox(call) => call.get_parser_info(stack, name),
}
}
/// Evaluator-agnostic implementation of `rest_iter_flattened()`. Evaluates or gets all of the
/// positional and spread arguments, flattens spreads, and then returns one list of values.
pub fn rest_iter_flattened(
&self,
engine_state: &EngineState,
stack: &mut Stack,
eval_expression: fn(
&EngineState,
&mut Stack,
&ast::Expression,
) -> Result<Value, ShellError>,
starting_pos: usize,
) -> Result<Vec<Value>, ShellError> {
fn by_ast(
call: &ast::Call,
engine_state: &EngineState,
stack: &mut Stack,
eval_expression: fn(
&EngineState,
&mut Stack,
&ast::Expression,
) -> Result<Value, ShellError>,
starting_pos: usize,
) -> Result<Vec<Value>, ShellError> {
call.rest_iter_flattened(starting_pos, |expr| {
eval_expression(engine_state, stack, expr)
})
}
fn by_ir(
call: &ir::Call,
stack: &Stack,
starting_pos: usize,
) -> Result<Vec<Value>, ShellError> {
call.rest_iter_flattened(stack, starting_pos)
}
match &self.inner {
CallImpl::AstRef(call) => {
by_ast(call, engine_state, stack, eval_expression, starting_pos)
}
CallImpl::AstBox(call) => {
by_ast(call, engine_state, stack, eval_expression, starting_pos)
}
CallImpl::IrRef(call) => by_ir(call, stack, starting_pos),
CallImpl::IrBox(call) => by_ir(call, stack, starting_pos),
}
}
/// Get the original AST expression for a positional argument. Does not usually work for IR
/// unless the decl specified `requires_ast_for_arguments()`
pub fn positional_nth<'a>(&'a self, stack: &'a Stack, index: usize) -> Option<&'a Expression> {
match &self.inner {
CallImpl::AstRef(call) => call.positional_nth(index),
CallImpl::AstBox(call) => call.positional_nth(index),
CallImpl::IrRef(call) => call.positional_ast(stack, index).map(|arc| arc.as_ref()),
CallImpl::IrBox(call) => call.positional_ast(stack, index).map(|arc| arc.as_ref()),
}
}
}
impl CallImpl<'_> {
pub fn to_owned(&self) -> CallImpl<'static> {
match self {
CallImpl::AstRef(call) => CallImpl::AstBox(Box::new((*call).clone())),
CallImpl::AstBox(call) => CallImpl::AstBox(call.clone()),
CallImpl::IrRef(call) => CallImpl::IrBox(Box::new((*call).clone())),
CallImpl::IrBox(call) => CallImpl::IrBox(call.clone()),
}
}
}
impl<'a> From<&'a ast::Call> for Call<'a> {
fn from(call: &'a ast::Call) -> Self {
Call {
head: call.head,
decl_id: call.decl_id,
inner: CallImpl::AstRef(call),
}
}
}
impl<'a> From<&'a ir::Call> for Call<'a> {
fn from(call: &'a ir::Call) -> Self {
Call {
head: call.head,
decl_id: call.decl_id,
inner: CallImpl::IrRef(call),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/call_info.rs | crates/nu-protocol/src/engine/call_info.rs | use crate::{Span, ast::Call};
#[derive(Debug, Clone)]
pub struct UnevaluatedCallInfo {
pub args: Call,
pub name_span: Span,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/stack_out_dest.rs | crates/nu-protocol/src/engine/stack_out_dest.rs | use crate::{OutDest, engine::Stack};
use std::{
fs::File,
mem,
ops::{Deref, DerefMut},
sync::Arc,
};
#[derive(Debug, Clone)]
pub enum Redirection {
/// A pipe redirection.
///
/// This will only affect the last command of a block.
/// This is created by pipes and pipe redirections (`|`, `e>|`, `o+e>|`, etc.),
/// or set by the next command in the pipeline (e.g., `ignore` sets stdout to [`OutDest::Null`]).
Pipe(OutDest),
/// A file redirection.
///
/// This will affect all commands in the block.
/// This is only created by file redirections (`o>`, `e>`, `o+e>`, etc.).
File(Arc<File>),
}
impl Redirection {
pub fn file(file: File) -> Self {
Self::File(Arc::new(file))
}
}
#[derive(Debug, Clone)]
pub(crate) struct StackOutDest {
/// The stream to use for the next command's stdout.
pub pipe_stdout: Option<OutDest>,
/// The stream to use for the next command's stderr.
pub pipe_stderr: Option<OutDest>,
/// The stream used for the command stdout if `pipe_stdout` is `None`.
///
/// This should only ever be `File` or `Inherit`.
pub stdout: OutDest,
/// The stream used for the command stderr if `pipe_stderr` is `None`.
///
/// This should only ever be `File` or `Inherit`.
pub stderr: OutDest,
/// The previous stdout used before the current `stdout` was set.
///
/// This is used only when evaluating arguments to commands,
/// since the arguments are lazily evaluated inside each command
/// after redirections have already been applied to the command/stack.
///
/// This should only ever be `File` or `Inherit`.
pub parent_stdout: Option<OutDest>,
/// The previous stderr used before the current `stderr` was set.
///
/// This is used only when evaluating arguments to commands,
/// since the arguments are lazily evaluated inside each command
/// after redirections have already been applied to the command/stack.
///
/// This should only ever be `File` or `Inherit`.
pub parent_stderr: Option<OutDest>,
}
impl StackOutDest {
pub(crate) fn new() -> Self {
Self {
pipe_stdout: Some(OutDest::Print),
pipe_stderr: Some(OutDest::Print),
stdout: OutDest::Inherit,
stderr: OutDest::Inherit,
parent_stdout: None,
parent_stderr: None,
}
}
/// Returns the [`OutDest`] to use for current command's stdout.
///
/// This will be the pipe redirection if one is set,
/// otherwise it will be the current file redirection,
/// otherwise it will be the process's stdout indicated by [`OutDest::Inherit`].
pub(crate) fn stdout(&self) -> &OutDest {
self.pipe_stdout.as_ref().unwrap_or(&self.stdout)
}
/// Returns the [`OutDest`] to use for current command's stderr.
///
/// This will be the pipe redirection if one is set,
/// otherwise it will be the current file redirection,
/// otherwise it will be the process's stderr indicated by [`OutDest::Inherit`].
pub(crate) fn stderr(&self) -> &OutDest {
self.pipe_stderr.as_ref().unwrap_or(&self.stderr)
}
fn push_stdout(&mut self, stdout: OutDest) -> Option<OutDest> {
let stdout = mem::replace(&mut self.stdout, stdout);
self.parent_stdout.replace(stdout)
}
fn push_stderr(&mut self, stderr: OutDest) -> Option<OutDest> {
let stderr = mem::replace(&mut self.stderr, stderr);
self.parent_stderr.replace(stderr)
}
}
pub struct StackIoGuard<'a> {
stack: &'a mut Stack,
old_pipe_stdout: Option<OutDest>,
old_pipe_stderr: Option<OutDest>,
old_parent_stdout: Option<OutDest>,
old_parent_stderr: Option<OutDest>,
}
impl<'a> StackIoGuard<'a> {
pub(crate) fn new(
stack: &'a mut Stack,
stdout: Option<Redirection>,
stderr: Option<Redirection>,
) -> Self {
let out_dest = &mut stack.out_dest;
let (old_pipe_stdout, old_parent_stdout) = match stdout {
Some(Redirection::Pipe(stdout)) => {
let old = out_dest.pipe_stdout.replace(stdout);
(old, out_dest.parent_stdout.take())
}
Some(Redirection::File(file)) => {
let file = OutDest::from(file);
(
out_dest.pipe_stdout.replace(file.clone()),
out_dest.push_stdout(file),
)
}
None => (out_dest.pipe_stdout.take(), out_dest.parent_stdout.take()),
};
let (old_pipe_stderr, old_parent_stderr) = match stderr {
Some(Redirection::Pipe(stderr)) => {
let old = out_dest.pipe_stderr.replace(stderr);
(old, out_dest.parent_stderr.take())
}
Some(Redirection::File(file)) => (
out_dest.pipe_stderr.take(),
out_dest.push_stderr(file.into()),
),
None => (out_dest.pipe_stderr.take(), out_dest.parent_stderr.take()),
};
StackIoGuard {
stack,
old_pipe_stdout,
old_parent_stdout,
old_pipe_stderr,
old_parent_stderr,
}
}
}
impl Deref for StackIoGuard<'_> {
type Target = Stack;
fn deref(&self) -> &Self::Target {
self.stack
}
}
impl DerefMut for StackIoGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.stack
}
}
impl Drop for StackIoGuard<'_> {
fn drop(&mut self) {
self.out_dest.pipe_stdout = self.old_pipe_stdout.take();
self.out_dest.pipe_stderr = self.old_pipe_stderr.take();
let old_stdout = self.old_parent_stdout.take();
if let Some(stdout) = mem::replace(&mut self.out_dest.parent_stdout, old_stdout) {
self.out_dest.stdout = stdout;
}
let old_stderr = self.old_parent_stderr.take();
if let Some(stderr) = mem::replace(&mut self.out_dest.parent_stderr, old_stderr) {
self.out_dest.stderr = stderr;
}
}
}
pub struct StackCollectValueGuard<'a> {
stack: &'a mut Stack,
old_pipe_stdout: Option<OutDest>,
old_pipe_stderr: Option<OutDest>,
}
impl<'a> StackCollectValueGuard<'a> {
pub(crate) fn new(stack: &'a mut Stack) -> Self {
let old_pipe_stdout = stack.out_dest.pipe_stdout.replace(OutDest::Value);
let old_pipe_stderr = stack.out_dest.pipe_stderr.take();
Self {
stack,
old_pipe_stdout,
old_pipe_stderr,
}
}
}
impl Deref for StackCollectValueGuard<'_> {
type Target = Stack;
fn deref(&self) -> &Self::Target {
&*self.stack
}
}
impl DerefMut for StackCollectValueGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.stack
}
}
impl Drop for StackCollectValueGuard<'_> {
fn drop(&mut self) {
self.out_dest.pipe_stdout = self.old_pipe_stdout.take();
self.out_dest.pipe_stderr = self.old_pipe_stderr.take();
}
}
pub struct StackCallArgGuard<'a> {
stack: &'a mut Stack,
old_pipe_stdout: Option<OutDest>,
old_pipe_stderr: Option<OutDest>,
old_stdout: Option<OutDest>,
old_stderr: Option<OutDest>,
}
impl<'a> StackCallArgGuard<'a> {
pub(crate) fn new(stack: &'a mut Stack) -> Self {
let old_pipe_stdout = stack.out_dest.pipe_stdout.replace(OutDest::Value);
let old_pipe_stderr = stack.out_dest.pipe_stderr.take();
let old_stdout = stack
.out_dest
.parent_stdout
.take()
.map(|stdout| mem::replace(&mut stack.out_dest.stdout, stdout));
let old_stderr = stack
.out_dest
.parent_stderr
.take()
.map(|stderr| mem::replace(&mut stack.out_dest.stderr, stderr));
Self {
stack,
old_pipe_stdout,
old_pipe_stderr,
old_stdout,
old_stderr,
}
}
}
impl Deref for StackCallArgGuard<'_> {
type Target = Stack;
fn deref(&self) -> &Self::Target {
&*self.stack
}
}
impl DerefMut for StackCallArgGuard<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.stack
}
}
impl Drop for StackCallArgGuard<'_> {
fn drop(&mut self) {
self.out_dest.pipe_stdout = self.old_pipe_stdout.take();
self.out_dest.pipe_stderr = self.old_pipe_stderr.take();
if let Some(stdout) = self.old_stdout.take() {
self.out_dest.push_stdout(stdout);
}
if let Some(stderr) = self.old_stderr.take() {
self.out_dest.push_stderr(stderr);
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/state_delta.rs | crates/nu-protocol/src/engine/state_delta.rs | use crate::{
Module, Span,
ast::Block,
engine::{
CachedFile, Command, EngineState, OverlayFrame, ScopeFrame, Variable, VirtualPath,
description::Doccomments,
},
};
use std::sync::Arc;
#[cfg(feature = "plugin")]
use crate::{PluginRegistryItem, RegisteredPlugin};
/// A delta (or change set) between the current global state and a possible future global state. Deltas
/// can be applied to the global state to update it to contain both previous state and the state held
/// within the delta.
#[derive(Clone)]
pub struct StateDelta {
pub(super) files: Vec<CachedFile>,
pub(super) virtual_paths: Vec<(String, VirtualPath)>,
pub(super) vars: Vec<Variable>, // indexed by VarId
pub(super) decls: Vec<Box<dyn Command>>, // indexed by DeclId
pub blocks: Vec<Arc<Block>>, // indexed by BlockId
pub(super) modules: Vec<Arc<Module>>, // indexed by ModuleId
pub spans: Vec<Span>, // indexed by SpanId
pub(super) doccomments: Doccomments,
pub scope: Vec<ScopeFrame>,
#[cfg(feature = "plugin")]
pub(super) plugins: Vec<Arc<dyn RegisteredPlugin>>,
#[cfg(feature = "plugin")]
pub(super) plugin_registry_items: Vec<PluginRegistryItem>,
}
impl StateDelta {
pub fn new(engine_state: &EngineState) -> Self {
let last_overlay = engine_state.last_overlay(&[]);
let scope_frame = ScopeFrame::with_empty_overlay(
engine_state.last_overlay_name(&[]).to_owned(),
last_overlay.origin,
last_overlay.prefixed,
);
StateDelta {
files: vec![],
virtual_paths: vec![],
vars: vec![],
decls: vec![],
blocks: vec![],
modules: vec![],
spans: vec![],
scope: vec![scope_frame],
doccomments: Doccomments::new(),
#[cfg(feature = "plugin")]
plugins: vec![],
#[cfg(feature = "plugin")]
plugin_registry_items: vec![],
}
}
pub fn num_files(&self) -> usize {
self.files.len()
}
pub fn num_virtual_paths(&self) -> usize {
self.virtual_paths.len()
}
pub fn num_vars(&self) -> usize {
self.vars.len()
}
pub fn num_decls(&self) -> usize {
self.decls.len()
}
pub fn num_blocks(&self) -> usize {
self.blocks.len()
}
pub fn num_modules(&self) -> usize {
self.modules.len()
}
pub fn last_scope_frame_mut(&mut self) -> &mut ScopeFrame {
self.scope
.last_mut()
.expect("internal error: missing required scope frame")
}
pub fn last_scope_frame(&self) -> &ScopeFrame {
self.scope
.last()
.expect("internal error: missing required scope frame")
}
pub fn last_overlay_mut(&mut self) -> Option<&mut OverlayFrame> {
let last_scope = self
.scope
.last_mut()
.expect("internal error: missing required scope frame");
if let Some(last_overlay_id) = last_scope.active_overlays.last() {
Some(
&mut last_scope
.overlays
.get_mut(last_overlay_id.get())
.expect("internal error: missing required overlay")
.1,
)
} else {
None
}
}
pub fn last_overlay(&self) -> Option<&OverlayFrame> {
let last_scope = self
.scope
.last()
.expect("internal error: missing required scope frame");
if let Some(last_overlay_id) = last_scope.active_overlays.last() {
Some(
&last_scope
.overlays
.get(last_overlay_id.get())
.expect("internal error: missing required overlay")
.1,
)
} else {
None
}
}
pub fn enter_scope(&mut self) {
self.scope.push(ScopeFrame::new());
}
pub fn exit_scope(&mut self) {
self.scope.pop();
}
pub fn get_file_contents(&self) -> &[CachedFile] {
&self.files
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/closure.rs | crates/nu-protocol/src/engine/closure.rs | use std::borrow::Cow;
use crate::{BlockId, ShellError, Span, Value, VarId, engine::EngineState};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Closure {
pub block_id: BlockId,
pub captures: Vec<(VarId, Value)>,
}
impl Closure {
pub fn coerce_into_string<'a>(
&self,
engine_state: &'a EngineState,
span: Span,
) -> Result<Cow<'a, str>, ShellError> {
let block = engine_state.get_block(self.block_id);
if let Some(span) = block.span {
let contents_bytes = engine_state.get_span_contents(span);
Ok(String::from_utf8_lossy(contents_bytes))
} else {
Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: "closure".into(),
span,
help: Some(format!(
"unable to retrieve block contents for closure with id {}",
self.block_id.get()
)),
})
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/mod.rs | crates/nu-protocol/src/engine/mod.rs | //! Representation of the engine state and many of the details that implement the scoping
mod argument;
mod cached_file;
mod call;
mod call_info;
mod closure;
mod command;
mod description;
mod engine_state;
mod error_handler;
mod jobs;
mod overlay;
mod pattern_match;
mod sequence;
mod stack;
mod stack_out_dest;
mod state_delta;
mod state_working_set;
mod variable;
pub use cached_file::CachedFile;
pub use argument::*;
pub use call::*;
pub use call_info::*;
pub use closure::*;
pub use command::*;
pub use engine_state::*;
pub use error_handler::*;
pub use jobs::*;
pub use overlay::*;
pub use pattern_match::*;
pub use sequence::*;
pub use stack::*;
pub use stack_out_dest::*;
pub use state_delta::*;
pub use state_working_set::*;
pub use variable::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/stack.rs | crates/nu-protocol/src/engine/stack.rs | use crate::{
Config, ENV_VARIABLE_ID, IntoValue, NU_VARIABLE_ID, OutDest, ShellError, Span, Value, VarId,
engine::{
ArgumentStack, DEFAULT_OVERLAY_NAME, EngineState, ErrorHandlerStack, Redirection,
StackCallArgGuard, StackCollectValueGuard, StackIoGuard, StackOutDest,
},
report_shell_warning,
};
use nu_utils::IgnoreCaseExt;
use std::{
collections::{HashMap, HashSet},
fs::File,
path::{Component, MAIN_SEPARATOR},
sync::Arc,
};
/// Environment variables per overlay
pub type EnvVars = HashMap<String, HashMap<String, Value>>;
/// A runtime value stack used during evaluation
///
/// A note on implementation:
///
/// We previously set up the stack in a traditional way, where stack frames had parents which would
/// represent other frames that you might return to when exiting a function.
///
/// While experimenting with blocks, we found that we needed to have closure captures of variables
/// seen outside of the blocks, so that they blocks could be run in a way that was both thread-safe
/// and followed the restrictions for closures applied to iterators. The end result left us with
/// closure-captured single stack frames that blocks could see.
///
/// Blocks make up the only scope and stack definition abstraction in Nushell. As a result, we were
/// creating closure captures at any point we wanted to have a Block value we could safely evaluate
/// in any context. This meant that the parents were going largely unused, with captured variables
/// taking their place. The end result is this, where we no longer have separate frames, but instead
/// use the Stack as a way of representing the local and closure-captured state.
#[derive(Debug, Clone)]
pub struct Stack {
/// Variables
pub vars: Vec<(VarId, Value)>,
/// Environment variables arranged as a stack to be able to recover values from parent scopes
pub env_vars: Vec<Arc<EnvVars>>,
/// Tells which environment variables from engine state are hidden, per overlay.
pub env_hidden: Arc<HashMap<String, HashSet<String>>>,
/// List of active overlays
pub active_overlays: Vec<String>,
/// Argument stack for IR evaluation
pub arguments: ArgumentStack,
/// Error handler stack for IR evaluation
pub error_handlers: ErrorHandlerStack,
pub recursion_count: u64,
pub parent_stack: Option<Arc<Stack>>,
/// Variables that have been deleted (this is used to hide values from parent stack lookups)
pub parent_deletions: Vec<VarId>,
/// Locally updated config. Use [`.get_config()`](Self::get_config) to access correctly.
pub config: Option<Arc<Config>>,
pub(crate) out_dest: StackOutDest,
}
impl Default for Stack {
fn default() -> Self {
Self::new()
}
}
impl Stack {
/// Create a new stack.
///
/// stdout and stderr will be set to [`OutDest::Inherit`]. So, if the last command is an external command,
/// then its output will be forwarded to the terminal/stdio streams.
///
/// Use [`Stack::collect_value`] afterwards if you need to evaluate an expression to a [`Value`]
/// (as opposed to a [`PipelineData`](crate::PipelineData)).
pub fn new() -> Self {
Self {
vars: Vec::new(),
env_vars: Vec::new(),
env_hidden: Arc::new(HashMap::new()),
active_overlays: vec![DEFAULT_OVERLAY_NAME.to_string()],
arguments: ArgumentStack::new(),
error_handlers: ErrorHandlerStack::new(),
recursion_count: 0,
parent_stack: None,
parent_deletions: vec![],
config: None,
out_dest: StackOutDest::new(),
}
}
/// Create a new child stack from a parent.
///
/// Changes from this child can be merged back into the parent with
/// [`Stack::with_changes_from_child`]
pub fn with_parent(parent: Arc<Stack>) -> Stack {
Stack {
// here we are still cloning environment variable-related information
env_vars: parent.env_vars.clone(),
env_hidden: parent.env_hidden.clone(),
active_overlays: parent.active_overlays.clone(),
arguments: ArgumentStack::new(),
error_handlers: ErrorHandlerStack::new(),
recursion_count: parent.recursion_count,
vars: vec![],
parent_deletions: vec![],
config: parent.config.clone(),
out_dest: parent.out_dest.clone(),
parent_stack: Some(parent),
}
}
/// Take an [`Arc`] parent, and a child, and apply all the changes from a child back to the parent.
///
/// Here it is assumed that `child` was created by a call to [`Stack::with_parent`] with `parent`.
///
/// For this to be performant and not clone `parent`, `child` should be the only other
/// referencer of `parent`.
pub fn with_changes_from_child(parent: Arc<Stack>, child: Stack) -> Stack {
// we're going to drop the link to the parent stack on our new stack
// so that we can unwrap the Arc as a unique reference
drop(child.parent_stack);
let mut unique_stack = Arc::unwrap_or_clone(parent);
unique_stack
.vars
.retain(|(var, _)| !child.parent_deletions.contains(var));
for (var, value) in child.vars {
unique_stack.add_var(var, value);
}
unique_stack.env_vars = child.env_vars;
unique_stack.env_hidden = child.env_hidden;
unique_stack.active_overlays = child.active_overlays;
unique_stack.config = child.config;
unique_stack
}
pub fn with_env(
&mut self,
env_vars: &[Arc<EnvVars>],
env_hidden: &Arc<HashMap<String, HashSet<String>>>,
) {
// Do not clone the environment if it hasn't changed
if self.env_vars.iter().any(|scope| !scope.is_empty()) {
env_vars.clone_into(&mut self.env_vars);
}
if !self.env_hidden.is_empty() {
self.env_hidden.clone_from(env_hidden);
}
}
/// Lookup a variable, returning None if it is not present
fn lookup_var(&self, var_id: VarId) -> Option<Value> {
for (id, val) in &self.vars {
if var_id == *id {
return Some(val.clone());
}
}
if let Some(stack) = &self.parent_stack
&& !self.parent_deletions.contains(&var_id)
{
return stack.lookup_var(var_id);
}
None
}
/// Lookup a variable, erroring if it is not found
///
/// The passed-in span will be used to tag the value
pub fn get_var(&self, var_id: VarId, span: Span) -> Result<Value, ShellError> {
match self.lookup_var(var_id) {
Some(v) => Ok(v.with_span(span)),
None => Err(ShellError::VariableNotFoundAtRuntime { span }),
}
}
/// Lookup a variable, erroring if it is not found
///
/// While the passed-in span will be used for errors, the returned value
/// has the span from where it was originally defined
pub fn get_var_with_origin(&self, var_id: VarId, span: Span) -> Result<Value, ShellError> {
match self.lookup_var(var_id) {
Some(v) => Ok(v),
None => {
if var_id == NU_VARIABLE_ID || var_id == ENV_VARIABLE_ID {
return Err(ShellError::GenericError {
error: "Built-in variables `$env` and `$nu` have no metadata".into(),
msg: "no metadata available".into(),
span: Some(span),
help: None,
inner: vec![],
});
}
Err(ShellError::VariableNotFoundAtRuntime { span })
}
}
}
/// Get the local config if set, otherwise the config from the engine state.
///
/// This is the canonical way to get [`Config`] when [`Stack`] is available.
pub fn get_config(&self, engine_state: &EngineState) -> Arc<Config> {
self.config
.clone()
.unwrap_or_else(|| engine_state.config.clone())
}
/// Update the local config with the config stored in the `config` environment variable. Run
/// this after assigning to `$env.config`.
///
/// The config will be updated with successfully parsed values even if an error occurs.
pub fn update_config(&mut self, engine_state: &EngineState) -> Result<(), ShellError> {
if let Some(value) = self.get_env_var(engine_state, "config") {
let old = self.get_config(engine_state);
let mut config = (*old).clone();
let result = config.update_from_value(&old, value);
// The config value is modified by the update, so we should add it again
self.add_env_var("config".into(), config.clone().into_value(value.span()));
self.config = Some(config.into());
if let Some(warning) = result? {
report_shell_warning(Some(self), engine_state, &warning);
}
} else {
self.config = None;
}
Ok(())
}
pub fn add_var(&mut self, var_id: VarId, value: Value) {
//self.vars.insert(var_id, value);
for (id, val) in &mut self.vars {
if *id == var_id {
*val = value;
return;
}
}
self.vars.push((var_id, value));
}
pub fn remove_var(&mut self, var_id: VarId) {
for (idx, (id, _)) in self.vars.iter().enumerate() {
if *id == var_id {
self.vars.remove(idx);
break;
}
}
// even if we did have it in the original layer, we need to make sure to remove it here
// as well (since the previous update might have simply hid the parent value)
if self.parent_stack.is_some() {
self.parent_deletions.push(var_id);
}
}
pub fn add_env_var(&mut self, var: String, value: Value) {
if let Some(last_overlay) = self.active_overlays.last() {
if let Some(env_hidden) = Arc::make_mut(&mut self.env_hidden).get_mut(last_overlay) {
// if the env var was hidden, let's activate it again
env_hidden.remove(&var);
}
if let Some(scope) = self.env_vars.last_mut() {
let scope = Arc::make_mut(scope);
if let Some(env_vars) = scope.get_mut(last_overlay) {
env_vars.insert(var, value);
} else {
scope.insert(last_overlay.into(), [(var, value)].into_iter().collect());
}
} else {
self.env_vars.push(Arc::new(
[(last_overlay.into(), [(var, value)].into_iter().collect())]
.into_iter()
.collect(),
));
}
} else {
// TODO: Remove panic
panic!("internal error: no active overlay");
}
}
pub fn set_last_exit_code(&mut self, code: i32, span: Span) {
self.add_env_var("LAST_EXIT_CODE".into(), Value::int(code.into(), span));
}
pub fn set_last_error(&mut self, error: &ShellError) {
if let Some(code) = error.external_exit_code() {
self.set_last_exit_code(code.item, code.span);
} else if let Some(code) = error.exit_code() {
self.set_last_exit_code(code, Span::unknown());
}
}
pub fn last_overlay_name(&self) -> Result<String, ShellError> {
self.active_overlays
.last()
.cloned()
.ok_or_else(|| ShellError::NushellFailed {
msg: "No active overlay".into(),
})
}
pub fn captures_to_stack(&self, captures: Vec<(VarId, Value)>) -> Stack {
self.captures_to_stack_preserve_out_dest(captures)
.collect_value()
}
pub fn captures_to_stack_preserve_out_dest(&self, captures: Vec<(VarId, Value)>) -> Stack {
let mut env_vars = self.env_vars.clone();
env_vars.push(Arc::new(HashMap::new()));
Stack {
vars: captures,
env_vars,
env_hidden: self.env_hidden.clone(),
active_overlays: self.active_overlays.clone(),
arguments: ArgumentStack::new(),
error_handlers: ErrorHandlerStack::new(),
recursion_count: self.recursion_count,
parent_stack: None,
parent_deletions: vec![],
config: self.config.clone(),
out_dest: self.out_dest.clone(),
}
}
pub fn gather_captures(&self, engine_state: &EngineState, captures: &[(VarId, Span)]) -> Stack {
let mut vars = Vec::with_capacity(captures.len());
let fake_span = Span::new(0, 0);
for (capture, _) in captures {
// Note: this assumes we have calculated captures correctly and that commands
// that take in a var decl will manually set this into scope when running the blocks
if let Ok(value) = self.get_var(*capture, fake_span) {
vars.push((*capture, value));
} else if let Some(const_val) = &engine_state.get_var(*capture).const_val {
vars.push((*capture, const_val.clone()));
}
}
let mut env_vars = self.env_vars.clone();
env_vars.push(Arc::new(HashMap::new()));
Stack {
vars,
env_vars,
env_hidden: self.env_hidden.clone(),
active_overlays: self.active_overlays.clone(),
arguments: ArgumentStack::new(),
error_handlers: ErrorHandlerStack::new(),
recursion_count: self.recursion_count,
parent_stack: None,
parent_deletions: vec![],
config: self.config.clone(),
out_dest: self.out_dest.clone(),
}
}
/// Flatten the env var scope frames into one frame
pub fn get_env_vars(&self, engine_state: &EngineState) -> HashMap<String, Value> {
let mut result = HashMap::new();
for active_overlay in self.active_overlays.iter() {
if let Some(env_vars) = engine_state.env_vars.get(active_overlay) {
result.extend(
env_vars
.iter()
.filter(|(k, _)| {
if let Some(env_hidden) = self.env_hidden.get(active_overlay) {
!env_hidden.contains(*k)
} else {
// nothing has been hidden in this overlay
true
}
})
.map(|(k, v)| (k.clone(), v.clone()))
.collect::<HashMap<String, Value>>(),
);
}
}
result.extend(self.get_stack_env_vars());
result
}
/// Get flattened environment variables only from the stack
pub fn get_stack_env_vars(&self) -> HashMap<String, Value> {
let mut result = HashMap::new();
for scope in &self.env_vars {
for active_overlay in self.active_overlays.iter() {
if let Some(env_vars) = scope.get(active_overlay) {
result.extend(env_vars.clone());
}
}
}
result
}
/// Get flattened environment variables only from the stack and one overlay
pub fn get_stack_overlay_env_vars(&self, overlay_name: &str) -> HashMap<String, Value> {
let mut result = HashMap::new();
for scope in &self.env_vars {
if let Some(active_overlay) = self.active_overlays.iter().find(|n| n == &overlay_name)
&& let Some(env_vars) = scope.get(active_overlay)
{
result.extend(env_vars.clone());
}
}
result
}
/// Get hidden envs, but without envs defined previously in `excluded_overlay_name`.
pub fn get_hidden_env_vars(
&self,
excluded_overlay_name: &str,
engine_state: &EngineState,
) -> HashMap<String, Value> {
let mut result = HashMap::new();
for overlay_name in self.active_overlays.iter().rev() {
if overlay_name == excluded_overlay_name {
continue;
}
if let Some(env_names) = self.env_hidden.get(overlay_name) {
for n in env_names {
if result.contains_key(n) {
continue;
}
// get env value.
if let Some(Some(v)) = engine_state
.env_vars
.get(overlay_name)
.map(|env_vars| env_vars.get(n))
{
result.insert(n.to_string(), v.clone());
}
}
}
}
result
}
/// Same as get_env_vars, but returns only the names as a HashSet
pub fn get_env_var_names(&self, engine_state: &EngineState) -> HashSet<String> {
let mut result = HashSet::new();
for active_overlay in self.active_overlays.iter() {
if let Some(env_vars) = engine_state.env_vars.get(active_overlay) {
result.extend(
env_vars
.keys()
.filter(|k| {
if let Some(env_hidden) = self.env_hidden.get(active_overlay) {
!env_hidden.contains(*k)
} else {
// nothing has been hidden in this overlay
true
}
})
.cloned()
.collect::<HashSet<String>>(),
);
}
}
for scope in &self.env_vars {
for active_overlay in self.active_overlays.iter() {
if let Some(env_vars) = scope.get(active_overlay) {
result.extend(env_vars.keys().cloned().collect::<HashSet<String>>());
}
}
}
result
}
pub fn get_env_var<'a>(
&'a self,
engine_state: &'a EngineState,
name: &str,
) -> Option<&'a Value> {
for scope in self.env_vars.iter().rev() {
for active_overlay in self.active_overlays.iter().rev() {
if let Some(env_vars) = scope.get(active_overlay)
&& let Some(v) = env_vars.get(name)
{
return Some(v);
}
}
}
for active_overlay in self.active_overlays.iter().rev() {
let is_hidden = if let Some(env_hidden) = self.env_hidden.get(active_overlay) {
env_hidden.contains(name)
} else {
false
};
if !is_hidden
&& let Some(env_vars) = engine_state.env_vars.get(active_overlay)
&& let Some(v) = env_vars.get(name)
{
return Some(v);
}
}
None
}
// Case-Insensitive version of get_env_var
// Returns Some((name, value)) if found, None otherwise.
// When updating environment variables, make sure to use
// the same case (from the returned "name") as the original
// environment variable name.
pub fn get_env_var_insensitive<'a>(
&'a self,
engine_state: &'a EngineState,
name: &str,
) -> Option<(&'a String, &'a Value)> {
for scope in self.env_vars.iter().rev() {
for active_overlay in self.active_overlays.iter().rev() {
if let Some(env_vars) = scope.get(active_overlay)
&& let Some(v) = env_vars.iter().find(|(k, _)| k.eq_ignore_case(name))
{
return Some((v.0, v.1));
}
}
}
for active_overlay in self.active_overlays.iter().rev() {
let is_hidden = if let Some(env_hidden) = self.env_hidden.get(active_overlay) {
env_hidden.iter().any(|k| k.eq_ignore_case(name))
} else {
false
};
if !is_hidden
&& let Some(env_vars) = engine_state.env_vars.get(active_overlay)
&& let Some(v) = env_vars.iter().find(|(k, _)| k.eq_ignore_case(name))
{
return Some((v.0, v.1));
}
}
None
}
pub fn has_env_var(&self, engine_state: &EngineState, name: &str) -> bool {
for scope in self.env_vars.iter().rev() {
for active_overlay in self.active_overlays.iter().rev() {
if let Some(env_vars) = scope.get(active_overlay)
&& env_vars.contains_key(name)
{
return true;
}
}
}
for active_overlay in self.active_overlays.iter().rev() {
let is_hidden = if let Some(env_hidden) = self.env_hidden.get(active_overlay) {
env_hidden.contains(name)
} else {
false
};
if !is_hidden
&& let Some(env_vars) = engine_state.env_vars.get(active_overlay)
&& env_vars.contains_key(name)
{
return true;
}
}
false
}
pub fn remove_env_var(&mut self, engine_state: &EngineState, name: &str) -> bool {
for scope in self.env_vars.iter_mut().rev() {
let scope = Arc::make_mut(scope);
for active_overlay in self.active_overlays.iter().rev() {
if let Some(env_vars) = scope.get_mut(active_overlay)
&& env_vars.remove(name).is_some()
{
return true;
}
}
}
for active_overlay in self.active_overlays.iter().rev() {
if let Some(env_vars) = engine_state.env_vars.get(active_overlay)
&& env_vars.get(name).is_some()
{
let env_hidden = Arc::make_mut(&mut self.env_hidden);
if let Some(env_hidden_in_overlay) = env_hidden.get_mut(active_overlay) {
env_hidden_in_overlay.insert(name.into());
} else {
env_hidden.insert(active_overlay.into(), [name.into()].into_iter().collect());
}
return true;
}
}
false
}
pub fn has_env_overlay(&self, name: &str, engine_state: &EngineState) -> bool {
for scope in self.env_vars.iter().rev() {
if scope.contains_key(name) {
return true;
}
}
engine_state.env_vars.contains_key(name)
}
pub fn is_overlay_active(&self, name: &str) -> bool {
self.active_overlays.iter().any(|n| n == name)
}
pub fn add_overlay(&mut self, name: String) {
self.active_overlays.retain(|o| o != &name);
self.active_overlays.push(name);
}
pub fn remove_overlay(&mut self, name: &str) {
self.active_overlays.retain(|o| o != name);
}
/// Returns the [`OutDest`] to use for the current command's stdout.
///
/// This will be the pipe redirection if one is set,
/// otherwise it will be the current file redirection,
/// otherwise it will be the process's stdout indicated by [`OutDest::Inherit`].
pub fn stdout(&self) -> &OutDest {
self.out_dest.stdout()
}
/// Returns the [`OutDest`] to use for the current command's stderr.
///
/// This will be the pipe redirection if one is set,
/// otherwise it will be the current file redirection,
/// otherwise it will be the process's stderr indicated by [`OutDest::Inherit`].
pub fn stderr(&self) -> &OutDest {
self.out_dest.stderr()
}
/// Returns the [`OutDest`] of the pipe redirection applied to the current command's stdout.
pub fn pipe_stdout(&self) -> Option<&OutDest> {
self.out_dest.pipe_stdout.as_ref()
}
/// Returns the [`OutDest`] of the pipe redirection applied to the current command's stderr.
pub fn pipe_stderr(&self) -> Option<&OutDest> {
self.out_dest.pipe_stderr.as_ref()
}
/// Temporarily set the pipe stdout redirection to [`OutDest::Value`].
///
/// This is used before evaluating an expression into a `Value`.
pub fn start_collect_value(&mut self) -> StackCollectValueGuard<'_> {
StackCollectValueGuard::new(self)
}
/// Temporarily use the output redirections in the parent scope.
///
/// This is used before evaluating an argument to a call.
pub fn use_call_arg_out_dest(&mut self) -> StackCallArgGuard<'_> {
StackCallArgGuard::new(self)
}
/// Temporarily apply redirections to stdout and/or stderr.
pub fn push_redirection(
&mut self,
stdout: Option<Redirection>,
stderr: Option<Redirection>,
) -> StackIoGuard<'_> {
StackIoGuard::new(self, stdout, stderr)
}
/// Mark stdout for the last command as [`OutDest::Value`].
///
/// This will irreversibly alter the output redirections, and so it only makes sense to use this on an owned `Stack`
/// (which is why this function does not take `&mut self`).
///
/// See [`Stack::start_collect_value`] which can temporarily set stdout as [`OutDest::Value`] for a mutable `Stack` reference.
pub fn collect_value(mut self) -> Self {
self.out_dest.pipe_stdout = Some(OutDest::Value);
self.out_dest.pipe_stderr = None;
self
}
/// Clears any pipe and file redirections and resets stdout and stderr to [`OutDest::Inherit`].
///
/// This will irreversibly reset the output redirections, and so it only makes sense to use this on an owned `Stack`
/// (which is why this function does not take `&mut self`).
pub fn reset_out_dest(mut self) -> Self {
self.out_dest = StackOutDest::new();
self
}
/// Clears any pipe redirections, keeping the current stdout and stderr.
///
/// This will irreversibly reset some of the output redirections, and so it only makes sense to use this on an owned `Stack`
/// (which is why this function does not take `&mut self`).
pub fn reset_pipes(mut self) -> Self {
self.out_dest.pipe_stdout = None;
self.out_dest.pipe_stderr = None;
self
}
/// Replaces the default stdout of the stack with a given file.
///
/// This method configures the default stdout to redirect to a specified file.
/// It is primarily useful for applications using `nu` as a language, where the stdout of
/// external commands that are not explicitly piped can be redirected to a file.
///
/// # Using Pipes
///
/// For use in third-party applications pipes might be very useful as they allow using the
/// stdout of external commands for different uses.
/// For example the [`os_pipe`](https://docs.rs/os_pipe) crate provides a elegant way to to
/// access the stdout.
///
/// ```
/// # use std::{fs::File, io::{self, Read}, thread, error};
/// # use nu_protocol::engine::Stack;
/// #
/// let (mut reader, writer) = os_pipe::pipe().unwrap();
/// // Use a thread to avoid blocking the execution of the called command.
/// let reader = thread::spawn(move || {
/// let mut buf: Vec<u8> = Vec::new();
/// reader.read_to_end(&mut buf)?;
/// Ok::<_, io::Error>(buf)
/// });
///
/// #[cfg(windows)]
/// let file = std::os::windows::io::OwnedHandle::from(writer).into();
/// #[cfg(unix)]
/// let file = std::os::unix::io::OwnedFd::from(writer).into();
///
/// let stack = Stack::new().stdout_file(file);
///
/// // Execute some nu code.
///
/// drop(stack); // drop the stack so that the writer will be dropped too
/// let buf = reader.join().unwrap().unwrap();
/// // Do with your buffer whatever you want.
/// ```
pub fn stdout_file(mut self, file: File) -> Self {
self.out_dest.stdout = OutDest::File(Arc::new(file));
self
}
/// Replaces the default stderr of the stack with a given file.
///
/// For more info, see [`stdout_file`](Self::stdout_file).
pub fn stderr_file(mut self, file: File) -> Self {
self.out_dest.stderr = OutDest::File(Arc::new(file));
self
}
/// Set the PWD environment variable to `path`.
///
/// This method accepts `path` with trailing slashes, but they're removed
/// before writing the value into PWD.
pub fn set_cwd(&mut self, path: impl AsRef<std::path::Path>) -> Result<(), ShellError> {
// Helper function to create a simple generic error.
// Its messages are not especially helpful, but these errors don't occur often, so it's probably fine.
fn error(msg: &str) -> Result<(), ShellError> {
Err(ShellError::GenericError {
error: msg.into(),
msg: "".into(),
span: None,
help: None,
inner: vec![],
})
}
let path = path.as_ref();
if !path.is_absolute() {
if let Some(Component::Prefix(_)) = path.components().next() {
return Err(ShellError::GenericError {
error: "Cannot set $env.PWD to a prefix-only path".to_string(),
msg: "".into(),
span: None,
help: Some(format!(
"Try to use {}{MAIN_SEPARATOR} instead",
path.display()
)),
inner: vec![],
});
}
error("Cannot set $env.PWD to a non-absolute path")
} else if !path.exists() {
error("Cannot set $env.PWD to a non-existent directory")
} else if !path.is_dir() {
error("Cannot set $env.PWD to a non-directory")
} else {
// Strip trailing slashes, if any.
let path = nu_path::strip_trailing_slash(path);
let value = Value::string(path.to_string_lossy(), Span::unknown());
self.add_env_var("PWD".into(), value);
Ok(())
}
}
}
#[cfg(test)]
mod test {
use std::sync::Arc;
use crate::{Span, Value, VarId, engine::EngineState};
use super::Stack;
#[test]
fn test_children_see_inner_values() {
let mut original = Stack::new();
original.add_var(VarId::new(0), Value::test_string("hello"));
let cloned = Stack::with_parent(Arc::new(original));
assert_eq!(
cloned.get_var(VarId::new(0), Span::test_data()),
Ok(Value::test_string("hello"))
);
}
#[test]
fn test_children_dont_see_deleted_values() {
let mut original = Stack::new();
original.add_var(VarId::new(0), Value::test_string("hello"));
let mut cloned = Stack::with_parent(Arc::new(original));
cloned.remove_var(VarId::new(0));
assert_eq!(
cloned.get_var(VarId::new(0), Span::test_data()),
Err(crate::ShellError::VariableNotFoundAtRuntime {
span: Span::test_data()
})
);
}
#[test]
fn test_children_changes_override_parent() {
let mut original = Stack::new();
original.add_var(VarId::new(0), Value::test_string("hello"));
let mut cloned = Stack::with_parent(Arc::new(original));
cloned.add_var(VarId::new(0), Value::test_string("there"));
assert_eq!(
cloned.get_var(VarId::new(0), Span::test_data()),
Ok(Value::test_string("there"))
);
cloned.remove_var(VarId::new(0));
// the underlying value shouldn't magically re-appear
assert_eq!(
cloned.get_var(VarId::new(0), Span::test_data()),
Err(crate::ShellError::VariableNotFoundAtRuntime {
span: Span::test_data()
})
);
}
#[test]
fn test_children_changes_persist_in_offspring() {
let mut original = Stack::new();
original.add_var(VarId::new(0), Value::test_string("hello"));
let mut cloned = Stack::with_parent(Arc::new(original));
cloned.add_var(VarId::new(1), Value::test_string("there"));
cloned.remove_var(VarId::new(0));
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/overlay.rs | crates/nu-protocol/src/engine/overlay.rs | use crate::{DeclId, ModuleId, OverlayId, VarId};
use std::collections::HashMap;
pub static DEFAULT_OVERLAY_NAME: &str = "zero";
/// Tells whether a decl is visible or not
#[derive(Debug, Clone)]
pub struct Visibility {
decl_ids: HashMap<DeclId, bool>,
}
impl Visibility {
pub fn new() -> Self {
Visibility {
decl_ids: HashMap::new(),
}
}
pub fn is_decl_id_visible(&self, decl_id: &DeclId) -> bool {
*self.decl_ids.get(decl_id).unwrap_or(&true) // by default it's visible
}
pub fn hide_decl_id(&mut self, decl_id: &DeclId) {
self.decl_ids.insert(*decl_id, false);
}
pub fn use_decl_id(&mut self, decl_id: &DeclId) {
self.decl_ids.insert(*decl_id, true);
}
/// Overwrite own values with the other
pub fn merge_with(&mut self, other: Visibility) {
self.decl_ids.extend(other.decl_ids);
}
/// Take new values from the other but keep own values
pub fn append(&mut self, other: &Visibility) {
for (decl_id, visible) in other.decl_ids.iter() {
if !self.decl_ids.contains_key(decl_id) {
self.decl_ids.insert(*decl_id, *visible);
}
}
}
}
#[derive(Debug, Clone)]
pub struct ScopeFrame {
/// List of both active and inactive overlays in this ScopeFrame.
///
/// The order does not have any meaning. Indexed locally (within this ScopeFrame) by
/// OverlayIds in active_overlays.
pub overlays: Vec<(Vec<u8>, OverlayFrame)>,
/// List of currently active overlays.
///
/// Order is significant: The last item points at the last activated overlay.
pub active_overlays: Vec<OverlayId>,
/// Removed overlays from previous scope frames / permanent state
pub removed_overlays: Vec<Vec<u8>>,
/// temporary storage for predeclarations
pub predecls: HashMap<Vec<u8>, DeclId>,
}
impl ScopeFrame {
pub fn new() -> Self {
Self {
overlays: vec![],
active_overlays: vec![],
removed_overlays: vec![],
predecls: HashMap::new(),
}
}
pub fn with_empty_overlay(name: Vec<u8>, origin: ModuleId, prefixed: bool) -> Self {
Self {
overlays: vec![(name, OverlayFrame::from_origin(origin, prefixed))],
active_overlays: vec![OverlayId::new(0)],
removed_overlays: vec![],
predecls: HashMap::new(),
}
}
pub fn get_var(&self, var_name: &[u8]) -> Option<&VarId> {
for overlay_id in self.active_overlays.iter().rev() {
if let Some(var_id) = self
.overlays
.get(overlay_id.get())
.expect("internal error: missing overlay")
.1
.vars
.get(var_name)
{
return Some(var_id);
}
}
None
}
pub fn active_overlay_ids(&self, removed_overlays: &mut Vec<Vec<u8>>) -> Vec<OverlayId> {
for name in &self.removed_overlays {
if !removed_overlays.contains(name) {
removed_overlays.push(name.clone());
}
}
self.active_overlays
.iter()
.filter(|id| {
!removed_overlays
.iter()
.any(|name| name == self.get_overlay_name(**id))
})
.copied()
.collect()
}
pub fn active_overlays<'a, 'b>(
&'b self,
removed_overlays: &'a mut Vec<Vec<u8>>,
) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
where
'b: 'a,
{
self.active_overlay_ids(removed_overlays)
.into_iter()
.map(|id| self.get_overlay(id))
}
pub fn active_overlay_names(&self, removed_overlays: &mut Vec<Vec<u8>>) -> Vec<&[u8]> {
self.active_overlay_ids(removed_overlays)
.iter()
.map(|id| self.get_overlay_name(*id))
.collect()
}
pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
&self
.overlays
.get(overlay_id.get())
.expect("internal error: missing overlay")
.0
}
pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
&self
.overlays
.get(overlay_id.get())
.expect("internal error: missing overlay")
.1
}
pub fn get_overlay_mut(&mut self, overlay_id: OverlayId) -> &mut OverlayFrame {
&mut self
.overlays
.get_mut(overlay_id.get())
.expect("internal error: missing overlay")
.1
}
pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
self.overlays
.iter()
.position(|(n, _)| n == name)
.map(OverlayId::new)
}
pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
self.overlays
.iter()
.position(|(n, _)| n == name)
.map(OverlayId::new)
.filter(|id| self.active_overlays.contains(id))
}
}
#[derive(Debug, Clone)]
pub struct OverlayFrame {
pub vars: HashMap<Vec<u8>, VarId>,
pub predecls: HashMap<Vec<u8>, DeclId>, // temporary storage for predeclarations
pub decls: HashMap<Vec<u8>, DeclId>,
pub modules: HashMap<Vec<u8>, ModuleId>,
pub shadowed_vars: Vec<VarId>,
pub visibility: Visibility,
pub origin: ModuleId, // The original module the overlay was created from
pub prefixed: bool, // Whether the overlay has definitions prefixed with its name
}
impl OverlayFrame {
pub fn from_origin(origin: ModuleId, prefixed: bool) -> Self {
Self {
vars: HashMap::new(),
predecls: HashMap::new(),
decls: HashMap::new(),
modules: HashMap::new(),
shadowed_vars: Vec::new(),
visibility: Visibility::new(),
origin,
prefixed,
}
}
pub fn insert_decl(&mut self, name: Vec<u8>, decl_id: DeclId) -> Option<DeclId> {
self.decls.insert(name, decl_id)
}
pub fn insert_module(&mut self, name: Vec<u8>, module_id: ModuleId) -> Option<ModuleId> {
self.modules.insert(name, module_id)
}
pub fn insert_variable(&mut self, name: Vec<u8>, variable_id: VarId) -> Option<VarId> {
let res = self.vars.insert(name, variable_id);
if let Some(old_id) = res {
self.shadowed_vars.push(old_id);
}
res
}
pub fn get_decl(&self, name: &[u8]) -> Option<DeclId> {
self.decls.get(name).cloned()
}
}
impl Default for Visibility {
fn default() -> Self {
Self::new()
}
}
impl Default for ScopeFrame {
fn default() -> Self {
Self::new()
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/cached_file.rs | crates/nu-protocol/src/engine/cached_file.rs | use crate::Span;
use std::sync::Arc;
/// Unit of cached source code
#[derive(Clone)]
pub struct CachedFile {
// Use Arcs of slice types for more compact representation (capacity less)
// Could possibly become an `Arc<PathBuf>`
/// The file name with which the code is associated (also includes REPL input)
pub name: Arc<str>,
/// Source code as raw bytes
pub content: Arc<[u8]>,
/// global span coordinates that are covered by this [`CachedFile`]
pub covered_span: Span,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/error_handler.rs | crates/nu-protocol/src/engine/error_handler.rs | use crate::RegId;
/// Describes an error handler stored during IR evaluation.
#[derive(Debug, Clone, Copy)]
pub struct ErrorHandler {
/// Instruction index within the block that will handle the error
pub handler_index: usize,
/// Register to put the error information into, when an error occurs
pub error_register: Option<RegId>,
}
/// Keeps track of error handlers pushed during evaluation of an IR block.
#[derive(Debug, Clone, Default)]
pub struct ErrorHandlerStack {
handlers: Vec<ErrorHandler>,
}
impl ErrorHandlerStack {
pub const fn new() -> ErrorHandlerStack {
ErrorHandlerStack { handlers: vec![] }
}
/// Get the current base of the stack, which establishes a frame.
pub fn get_base(&self) -> usize {
self.handlers.len()
}
/// Push a new error handler onto the stack.
pub fn push(&mut self, handler: ErrorHandler) {
self.handlers.push(handler);
}
/// Try to pop an error handler from the stack. Won't go below `base`, to avoid retrieving a
/// handler belonging to a parent frame.
pub fn pop(&mut self, base: usize) -> Option<ErrorHandler> {
if self.handlers.len() > base {
self.handlers.pop()
} else {
None
}
}
/// Reset the stack to the state it was in at the beginning of the frame, in preparation to
/// return control to the parent frame.
pub fn leave_frame(&mut self, base: usize) {
if self.handlers.len() >= base {
self.handlers.truncate(base);
} else {
panic!(
"ErrorHandlerStack bug: tried to leave frame at {base}, but current base is {}",
self.get_base()
)
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/pattern_match.rs | crates/nu-protocol/src/engine/pattern_match.rs | use crate::{
Span, Value, VarId,
ast::{Expr, MatchPattern, Pattern, RangeInclusion},
};
pub trait Matcher {
fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool;
}
impl Matcher for MatchPattern {
fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool {
self.pattern.match_value(value, matches)
}
}
impl Matcher for Pattern {
fn match_value(&self, value: &Value, matches: &mut Vec<(VarId, Value)>) -> bool {
match self {
Pattern::Garbage => false,
Pattern::IgnoreValue => true,
Pattern::IgnoreRest => false, // `..` and `..$foo` only match in specific contexts
Pattern::Rest(_) => false, // so we return false here and handle them elsewhere
Pattern::Record(field_patterns) => match value {
Value::Record { val, .. } => {
'top: for field_pattern in field_patterns {
for (col, val) in &**val {
if col == &field_pattern.0 {
// We have found the field
let result = field_pattern.1.match_value(val, matches);
if !result {
return false;
} else {
continue 'top;
}
}
}
return false;
}
true
}
_ => false,
},
Pattern::Variable(var_id) => {
// TODO: FIXME: This needs the span of this variable
matches.push((*var_id, value.clone()));
true
}
Pattern::List(items) => match &value {
Value::List { vals, .. } => {
if items.len() > vals.len() {
// We only allow this is to have a rest pattern in the n+1 position
if items.len() == (vals.len() + 1) {
match &items[vals.len()].pattern {
Pattern::IgnoreRest => {}
Pattern::Rest(var_id) => matches.push((
*var_id,
Value::list(Vec::new(), items[vals.len()].span),
)),
_ => {
// There is a pattern which can't skip missing values, so we fail
return false;
}
}
} else {
// There are patterns that can't be matches, so we fail
return false;
}
}
for (val_idx, val) in vals.iter().enumerate() {
// We require that the pattern and the value have the same number of items, or the pattern does not match
// The only exception is if the pattern includes a `..` pattern
if let Some(pattern) = items.get(val_idx) {
match &pattern.pattern {
Pattern::IgnoreRest => {
break;
}
Pattern::Rest(var_id) => {
let rest_vals = vals[val_idx..].to_vec();
matches.push((*var_id, Value::list(rest_vals, pattern.span)));
break;
}
_ => {
if !pattern.match_value(val, matches) {
return false;
}
}
}
} else {
return false;
}
}
true
}
_ => false,
},
Pattern::Expression(pattern_value) => {
// TODO: Fill this out with the rest of them
match &pattern_value.expr {
Expr::Nothing => {
matches!(value, Value::Nothing { .. })
}
Expr::Int(x) => {
if let Value::Int { val, .. } = &value {
x == val
} else {
false
}
}
Expr::Float(x) => {
if let Value::Float { val, .. } = &value {
x == val
} else {
false
}
}
Expr::Binary(x) => {
if let Value::Binary { val, .. } = &value {
x == val
} else {
false
}
}
Expr::Bool(x) => {
if let Value::Bool { val, .. } = &value {
x == val
} else {
false
}
}
Expr::String(x) | Expr::RawString(x) => {
if let Value::String { val, .. } = &value {
x == val
} else {
false
}
}
Expr::DateTime(x) => {
if let Value::Date { val, .. } = &value {
x == val
} else {
false
}
}
Expr::ValueWithUnit(val) => {
let span = val.unit.span;
if let Expr::Int(size) = val.expr.expr {
match &val.unit.item.build_value(size, span) {
Ok(v) => v == value,
_ => false,
}
} else {
false
}
}
Expr::Range(range) => {
// TODO: Add support for floats
let start = if let Some(start) = &range.from {
match &start.expr {
Expr::Int(start) => *start,
_ => return false,
}
} else {
0
};
let end = if let Some(end) = &range.to {
match &end.expr {
Expr::Int(end) => *end,
_ => return false,
}
} else {
i64::MAX
};
let step = if let Some(step) = &range.next {
match &step.expr {
Expr::Int(step) => *step - start,
_ => return false,
}
} else if end < start {
-1
} else {
1
};
let (start, end) = if end < start {
(end, start)
} else {
(start, end)
};
if let Value::Int { val, .. } = &value {
if matches!(range.operator.inclusion, RangeInclusion::RightExclusive) {
*val >= start && *val < end && ((*val - start) % step) == 0
} else {
*val >= start && *val <= end && ((*val - start) % step) == 0
}
} else {
false
}
}
_ => false,
}
}
Pattern::Value(pattern_value) => value == pattern_value,
Pattern::Or(patterns) => {
let mut result = false;
for pattern in patterns {
let mut local_matches = vec![];
if !result {
if pattern.match_value(value, &mut local_matches) {
// TODO: do we need to replace previous variables that defaulted to nothing?
matches.append(&mut local_matches);
result = true;
} else {
// Create variables that don't match and assign them to null
let vars = pattern.variables();
for var in &vars {
let mut found = false;
for match_ in matches.iter() {
if match_.0 == *var {
found = true;
}
}
if !found {
// FIXME: don't use Span::unknown()
matches.push((*var, Value::nothing(Span::unknown())))
}
}
}
} else {
// We already have a match, so ignore the remaining match variables
// And assign them to null
let vars = pattern.variables();
for var in &vars {
let mut found = false;
for match_ in matches.iter() {
if match_.0 == *var {
found = true;
}
}
if !found {
// FIXME: don't use Span::unknown()
matches.push((*var, Value::nothing(Span::unknown())))
}
}
}
}
result
}
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/description.rs | crates/nu-protocol/src/engine/description.rs | use crate::{ModuleId, Span};
use std::collections::HashMap;
/// Organizes documentation comments for various primitives
#[derive(Debug, Clone)]
pub(super) struct Doccomments {
// TODO: Move decl doccomments here
module_comments: HashMap<ModuleId, Vec<Span>>,
}
impl Doccomments {
pub fn new() -> Self {
Doccomments {
module_comments: HashMap::new(),
}
}
pub fn add_module_comments(&mut self, module_id: ModuleId, comments: Vec<Span>) {
self.module_comments.insert(module_id, comments);
}
pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
self.module_comments.get(&module_id).map(|v| v.as_ref())
}
/// Overwrite own values with the other
pub fn merge_with(&mut self, other: Doccomments) {
self.module_comments.extend(other.module_comments);
}
}
impl Default for Doccomments {
fn default() -> Self {
Self::new()
}
}
pub(super) fn build_desc(comment_lines: &[&[u8]]) -> (String, String) {
let mut description = String::new();
let mut num_spaces = 0;
let mut first = true;
// Use the comments to build the item/command description
for contents in comment_lines {
let comment_line = if first {
// Count the number of spaces still at the front, skipping the '#'
let mut pos = 1;
while pos < contents.len() {
if let Some(b' ') = contents.get(pos) {
// continue
} else {
break;
}
pos += 1;
}
num_spaces = pos;
first = false;
String::from_utf8_lossy(&contents[pos..]).to_string()
} else {
let mut pos = 1;
while pos < contents.len() && pos < num_spaces {
if let Some(b' ') = contents.get(pos) {
// continue
} else {
break;
}
pos += 1;
}
String::from_utf8_lossy(&contents[pos..]).to_string()
};
if !description.is_empty() {
description.push('\n');
}
description.push_str(&comment_line);
}
if let Some((brief_desc, extra_desc)) = description.split_once("\r\n\r\n") {
(brief_desc.to_string(), extra_desc.to_string())
} else if let Some((brief_desc, extra_desc)) = description.split_once("\n\n") {
(brief_desc.to_string(), extra_desc.to_string())
} else {
(description, String::default())
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/state_working_set.rs | crates/nu-protocol/src/engine/state_working_set.rs | use crate::{
BlockId, Category, CompileError, Config, DeclId, FileId, GetSpan, Module, ModuleId, OverlayId,
ParseError, ParseWarning, ResolvedImportPattern, Signature, Span, SpanId, Type, Value, VarId,
VirtualPathId,
ast::Block,
engine::{
CachedFile, Command, CommandType, EngineState, OverlayFrame, StateDelta, Variable,
VirtualPath, Visibility, description::build_desc,
},
};
use core::panic;
use std::{
collections::{HashMap, HashSet},
path::{Path, PathBuf},
sync::Arc,
};
#[cfg(feature = "plugin")]
use crate::{PluginIdentity, PluginRegistryItem, RegisteredPlugin};
/// A temporary extension to the global state. This handles bridging between the global state and the
/// additional declarations and scope changes that are not yet part of the global scope.
///
/// This working set is created by the parser as a way of handling declarations and scope changes that
/// may later be merged or dropped (and not merged) depending on the needs of the code calling the parser.
pub struct StateWorkingSet<'a> {
pub permanent_state: &'a EngineState,
pub delta: StateDelta,
pub files: FileStack,
/// Whether or not predeclarations are searched when looking up a command (used with aliases)
pub search_predecls: bool,
pub parse_errors: Vec<ParseError>,
pub parse_warnings: Vec<ParseWarning>,
pub compile_errors: Vec<CompileError>,
}
impl<'a> StateWorkingSet<'a> {
pub fn new(permanent_state: &'a EngineState) -> Self {
// Initialize the file stack with the top-level file.
let files = if let Some(file) = permanent_state.file.clone() {
FileStack::with_file(file)
} else {
FileStack::new()
};
Self {
delta: StateDelta::new(permanent_state),
permanent_state,
files,
search_predecls: true,
parse_errors: vec![],
parse_warnings: vec![],
compile_errors: vec![],
}
}
pub fn permanent(&self) -> &EngineState {
self.permanent_state
}
pub fn error(&mut self, parse_error: ParseError) {
self.parse_errors.push(parse_error)
}
pub fn warning(&mut self, parse_warning: ParseWarning) {
self.parse_warnings.push(parse_warning)
}
pub fn num_files(&self) -> usize {
self.delta.num_files() + self.permanent_state.num_files()
}
pub fn num_virtual_paths(&self) -> usize {
self.delta.num_virtual_paths() + self.permanent_state.num_virtual_paths()
}
pub fn num_vars(&self) -> usize {
self.delta.num_vars() + self.permanent_state.num_vars()
}
pub fn num_decls(&self) -> usize {
self.delta.num_decls() + self.permanent_state.num_decls()
}
pub fn num_blocks(&self) -> usize {
self.delta.num_blocks() + self.permanent_state.num_blocks()
}
pub fn num_modules(&self) -> usize {
self.delta.num_modules() + self.permanent_state.num_modules()
}
pub fn unique_overlay_names(&self) -> HashSet<&[u8]> {
let mut names: HashSet<&[u8]> = self.permanent_state.active_overlay_names(&[]).collect();
for scope_frame in self.delta.scope.iter().rev() {
for overlay_id in scope_frame.active_overlays.iter().rev() {
let (overlay_name, _) = scope_frame
.overlays
.get(overlay_id.get())
.expect("internal error: missing overlay");
names.insert(overlay_name);
names.retain(|n| !scope_frame.removed_overlays.iter().any(|m| n == m));
}
}
names
}
pub fn num_overlays(&self) -> usize {
self.unique_overlay_names().len()
}
pub fn add_decl(&mut self, decl: Box<dyn Command>) -> DeclId {
let name = decl.name().as_bytes().to_vec();
self.delta.decls.push(decl);
let decl_id = self.num_decls() - 1;
let decl_id = DeclId::new(decl_id);
self.last_overlay_mut().insert_decl(name, decl_id);
decl_id
}
pub fn use_decls(&mut self, decls: Vec<(Vec<u8>, DeclId)>) {
let overlay_frame = self.last_overlay_mut();
for (name, decl_id) in decls {
overlay_frame.insert_decl(name, decl_id);
overlay_frame.visibility.use_decl_id(&decl_id);
}
}
pub fn use_modules(&mut self, modules: Vec<(Vec<u8>, ModuleId)>) {
let overlay_frame = self.last_overlay_mut();
for (name, module_id) in modules {
overlay_frame.insert_module(name, module_id);
// overlay_frame.visibility.use_module_id(&module_id); // TODO: Add hiding modules
}
}
pub fn use_variables(&mut self, variables: Vec<(Vec<u8>, VarId)>) {
let overlay_frame = self.last_overlay_mut();
for (mut name, var_id) in variables {
if !name.starts_with(b"$") {
name.insert(0, b'$');
}
overlay_frame.insert_variable(name, var_id);
}
}
pub fn add_predecl(&mut self, decl: Box<dyn Command>) -> Option<DeclId> {
let name = decl.name().as_bytes().to_vec();
self.delta.decls.push(decl);
let decl_id = self.num_decls() - 1;
let decl_id = DeclId::new(decl_id);
self.delta
.last_scope_frame_mut()
.predecls
.insert(name, decl_id)
}
#[cfg(feature = "plugin")]
pub fn find_or_create_plugin(
&mut self,
identity: &PluginIdentity,
make: impl FnOnce() -> Arc<dyn RegisteredPlugin>,
) -> Arc<dyn RegisteredPlugin> {
// Check in delta first, then permanent_state
if let Some(plugin) = self
.delta
.plugins
.iter()
.chain(self.permanent_state.plugins())
.find(|p| p.identity() == identity)
{
plugin.clone()
} else {
let plugin = make();
self.delta.plugins.push(plugin.clone());
plugin
}
}
#[cfg(feature = "plugin")]
pub fn update_plugin_registry(&mut self, item: PluginRegistryItem) {
self.delta.plugin_registry_items.push(item);
}
pub fn merge_predecl(&mut self, name: &[u8]) -> Option<DeclId> {
self.move_one_predecl_to_overlay(name);
let overlay_frame = self.last_overlay_mut();
if let Some(decl_id) = overlay_frame.predecls.remove(name) {
overlay_frame.insert_decl(name.into(), decl_id);
return Some(decl_id);
}
None
}
fn move_one_predecl_to_overlay(&mut self, name: &[u8]) {
self.delta
.last_scope_frame_mut()
.predecls
.remove_entry(name)
.map(|(name, decl_id)| self.last_overlay_mut().predecls.insert(name, decl_id));
}
pub fn hide_decl(&mut self, name: &[u8]) -> Option<DeclId> {
let mut removed_overlays = vec![];
let mut visibility: Visibility = Visibility::new();
// Since we can mutate scope frames in delta, remove the id directly
for scope_frame in self.delta.scope.iter_mut().rev() {
for overlay_id in scope_frame
.active_overlay_ids(&mut removed_overlays)
.iter()
.rev()
{
let overlay_frame = scope_frame.get_overlay_mut(*overlay_id);
visibility.append(&overlay_frame.visibility);
if let Some(decl_id) = overlay_frame.get_decl(name)
&& visibility.is_decl_id_visible(&decl_id)
{
// Hide decl only if it's not already hidden
overlay_frame.visibility.hide_decl_id(&decl_id);
return Some(decl_id);
}
}
}
// We cannot mutate the permanent state => store the information in the current overlay frame
// for scope in self.permanent_state.scope.iter().rev() {
for overlay_frame in self
.permanent_state
.active_overlays(&removed_overlays)
.rev()
{
visibility.append(&overlay_frame.visibility);
if let Some(decl_id) = overlay_frame.get_decl(name)
&& visibility.is_decl_id_visible(&decl_id)
{
// Hide decl only if it's not already hidden
self.last_overlay_mut().visibility.hide_decl_id(&decl_id);
return Some(decl_id);
}
}
None
}
pub fn hide_decls(&mut self, decls: &[Vec<u8>]) {
for decl in decls.iter() {
self.hide_decl(decl); // let's assume no errors
}
}
pub fn add_block(&mut self, block: Arc<Block>) -> BlockId {
log::trace!(
"block id={} added, has IR = {:?}",
self.num_blocks(),
block.ir_block.is_some()
);
self.delta.blocks.push(block);
BlockId::new(self.num_blocks() - 1)
}
pub fn add_module(&mut self, name: &str, module: Module, comments: Vec<Span>) -> ModuleId {
let name = name.as_bytes().to_vec();
self.delta.modules.push(Arc::new(module));
let module_id = self.num_modules() - 1;
let module_id = ModuleId::new(module_id);
if !comments.is_empty() {
self.delta
.doccomments
.add_module_comments(module_id, comments);
}
self.last_overlay_mut().modules.insert(name, module_id);
module_id
}
pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
self.delta
.doccomments
.get_module_comments(module_id)
.or_else(|| self.permanent_state.get_module_comments(module_id))
}
pub fn next_span_start(&self) -> usize {
let permanent_span_start = self.permanent_state.next_span_start();
if let Some(cached_file) = self.delta.files.last() {
cached_file.covered_span.end
} else {
permanent_span_start
}
}
pub fn files(&self) -> impl Iterator<Item = &CachedFile> {
self.permanent_state.files().chain(self.delta.files.iter())
}
pub fn get_contents_of_file(&self, file_id: FileId) -> Option<&[u8]> {
if let Some(cached_file) = self.permanent_state.get_file_contents().get(file_id.get()) {
return Some(&cached_file.content);
}
// The index subtraction will not underflow, if we hit the permanent state first.
// Check if you try reordering for locality
if let Some(cached_file) = self
.delta
.get_file_contents()
.get(file_id.get() - self.permanent_state.num_files())
{
return Some(&cached_file.content);
}
None
}
#[must_use]
pub fn add_file(&mut self, filename: String, contents: &[u8]) -> FileId {
// First, look for the file to see if we already have it
for (idx, cached_file) in self.files().enumerate() {
if *cached_file.name == filename && &*cached_file.content == contents {
return FileId::new(idx);
}
}
let next_span_start = self.next_span_start();
let next_span_end = next_span_start + contents.len();
let covered_span = Span::new(next_span_start, next_span_end);
self.delta.files.push(CachedFile {
name: filename.into(),
content: contents.into(),
covered_span,
});
FileId::new(self.num_files() - 1)
}
#[must_use]
pub fn add_virtual_path(&mut self, name: String, virtual_path: VirtualPath) -> VirtualPathId {
self.delta.virtual_paths.push((name, virtual_path));
VirtualPathId::new(self.num_virtual_paths() - 1)
}
pub fn get_span_for_filename(&self, filename: &str) -> Option<Span> {
let predicate = |file: &CachedFile| &*file.name == filename;
// search from end to start, in case there're duplicated files with the same name
let file_id = self
.delta
.files
.iter()
.rposition(predicate)
.map(|idx| idx + self.permanent_state.num_files())
.or_else(|| self.permanent_state.files().rposition(predicate))?;
let file_id = FileId::new(file_id);
Some(self.get_span_for_file(file_id))
}
/// Panics:
/// On invalid `FileId`
///
/// Use with care
pub fn get_span_for_file(&self, file_id: FileId) -> Span {
let result = self
.files()
.nth(file_id.get())
.expect("internal error: could not find source for previously parsed file");
result.covered_span
}
pub fn get_span_contents(&self, span: Span) -> &[u8] {
let permanent_end = self.permanent_state.next_span_start();
if permanent_end <= span.start {
for cached_file in &self.delta.files {
if cached_file.covered_span.contains_span(span) {
return &cached_file.content[span.start - cached_file.covered_span.start
..span.end - cached_file.covered_span.start];
}
}
}
// if no files with span were found, fall back on permanent ones
self.permanent_state.get_span_contents(span)
}
pub fn enter_scope(&mut self) {
self.delta.enter_scope();
}
pub fn exit_scope(&mut self) {
self.delta.exit_scope();
}
/// Find the [`DeclId`](crate::DeclId) corresponding to a predeclaration with `name`.
pub fn find_predecl(&self, name: &[u8]) -> Option<DeclId> {
let mut removed_overlays = vec![];
for scope_frame in self.delta.scope.iter().rev() {
if let Some(decl_id) = scope_frame.predecls.get(name) {
return Some(*decl_id);
}
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
if let Some(decl_id) = overlay_frame.predecls.get(name) {
return Some(*decl_id);
}
}
}
None
}
/// Find the [`DeclId`](crate::DeclId) corresponding to a declaration with `name`.
///
/// Extends [`EngineState::find_decl`] to also search for predeclarations
/// (if [`StateWorkingSet::search_predecls`] is set), and declarations from scopes existing
/// only in [`StateDelta`].
pub fn find_decl(&self, name: &[u8]) -> Option<DeclId> {
let mut removed_overlays = vec![];
let mut visibility: Visibility = Visibility::new();
for scope_frame in self.delta.scope.iter().rev() {
if self.search_predecls
&& let Some(decl_id) = scope_frame.predecls.get(name)
&& visibility.is_decl_id_visible(decl_id)
{
return Some(*decl_id);
}
// check overlay in delta
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
visibility.append(&overlay_frame.visibility);
if self.search_predecls
&& let Some(decl_id) = overlay_frame.predecls.get(name)
&& visibility.is_decl_id_visible(decl_id)
{
return Some(*decl_id);
}
if let Some(decl_id) = overlay_frame.get_decl(name)
&& visibility.is_decl_id_visible(&decl_id)
{
return Some(decl_id);
}
}
}
// check overlay in perma
self.permanent_state.find_decl(name, &removed_overlays)
}
/// Find the name of the declaration corresponding to `decl_id`.
///
/// Extends [`EngineState::find_decl_name`] to also search for predeclarations (if [`StateWorkingSet::search_predecls`] is set),
/// and declarations from scopes existing only in [`StateDelta`].
pub fn find_decl_name(&self, decl_id: DeclId) -> Option<&[u8]> {
let mut removed_overlays = vec![];
let mut visibility: Visibility = Visibility::new();
for scope_frame in self.delta.scope.iter().rev() {
if self.search_predecls {
for (name, id) in scope_frame.predecls.iter() {
if id == &decl_id {
return Some(name);
}
}
}
// check overlay in delta
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
visibility.append(&overlay_frame.visibility);
if self.search_predecls {
for (name, id) in overlay_frame.predecls.iter() {
if id == &decl_id {
return Some(name);
}
}
}
if visibility.is_decl_id_visible(&decl_id) {
for (name, id) in overlay_frame.decls.iter() {
if id == &decl_id {
return Some(name);
}
}
}
}
}
// check overlay in perma
self.permanent_state
.find_decl_name(decl_id, &removed_overlays)
}
/// Find the [`ModuleId`](crate::ModuleId) corresponding to `name`.
///
/// Extends [`EngineState::find_module`] to also search for ,
/// and declarations from scopes existing only in [`StateDelta`].
pub fn find_module(&self, name: &[u8]) -> Option<ModuleId> {
let mut removed_overlays = vec![];
for scope_frame in self.delta.scope.iter().rev() {
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
if let Some(module_id) = overlay_frame.modules.get(name) {
return Some(*module_id);
}
}
}
for overlay_frame in self
.permanent_state
.active_overlays(&removed_overlays)
.rev()
{
if let Some(module_id) = overlay_frame.modules.get(name) {
return Some(*module_id);
}
}
None
}
pub fn next_var_id(&self) -> VarId {
let num_permanent_vars = self.permanent_state.num_vars();
VarId::new(num_permanent_vars + self.delta.vars.len())
}
pub fn list_variables(&self) -> Vec<&[u8]> {
let mut removed_overlays = vec![];
let mut variables = HashSet::new();
for scope_frame in self.delta.scope.iter() {
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays) {
variables.extend(overlay_frame.vars.keys().map(|k| &k[..]));
}
}
let permanent_vars = self
.permanent_state
.active_overlays(&removed_overlays)
.flat_map(|overlay_frame| overlay_frame.vars.keys().map(|k| &k[..]));
variables.extend(permanent_vars);
variables.into_iter().collect()
}
pub fn find_variable(&self, name: &[u8]) -> Option<VarId> {
let mut name = name.to_vec();
if !name.starts_with(b"$") {
name.insert(0, b'$');
}
let mut removed_overlays = vec![];
for scope_frame in self.delta.scope.iter().rev() {
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
if let Some(var_id) = overlay_frame.vars.get(&name) {
return Some(*var_id);
}
}
}
for overlay_frame in self
.permanent_state
.active_overlays(&removed_overlays)
.rev()
{
if let Some(var_id) = overlay_frame.vars.get(&name) {
return Some(*var_id);
}
}
None
}
pub fn find_variable_in_current_frame(&self, name: &[u8]) -> Option<VarId> {
let mut removed_overlays = vec![];
for scope_frame in self.delta.scope.iter().rev().take(1) {
for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() {
if let Some(var_id) = overlay_frame.vars.get(name) {
return Some(*var_id);
}
}
}
None
}
pub fn add_variable(
&mut self,
mut name: Vec<u8>,
span: Span,
ty: Type,
mutable: bool,
) -> VarId {
let next_id = self.next_var_id();
// correct name if necessary
if !name.starts_with(b"$") {
name.insert(0, b'$');
}
self.last_overlay_mut().insert_variable(name, next_id);
self.delta.vars.push(Variable::new(span, ty, mutable));
next_id
}
/// Returns the current working directory as a String, which is guaranteed to be canonicalized.
/// Returns an empty string if $env.PWD doesn't exist, is not a String, or is not an absolute path.
///
/// It does NOT consider modifications to the working directory made on a stack.
#[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")]
pub fn get_cwd(&self) -> String {
self.permanent_state
.cwd(None)
.map(|path| path.to_string_lossy().to_string())
.unwrap_or_default()
}
pub fn get_env_var(&self, name: &str) -> Option<&Value> {
self.permanent_state.get_env_var(name)
}
/// Returns a reference to the config stored at permanent state
///
/// At runtime, you most likely want to call [`Stack::get_config()`][super::Stack::get_config()]
/// because this method does not capture environment updates during runtime.
pub fn get_config(&self) -> &Arc<Config> {
&self.permanent_state.config
}
pub fn set_variable_type(&mut self, var_id: VarId, ty: Type) {
let num_permanent_vars = self.permanent_state.num_vars();
if var_id.get() < num_permanent_vars {
panic!("Internal error: attempted to set into permanent state from working set")
} else {
self.delta.vars[var_id.get() - num_permanent_vars].ty = ty;
}
}
pub fn set_variable_const_val(&mut self, var_id: VarId, val: Value) {
let num_permanent_vars = self.permanent_state.num_vars();
if var_id.get() < num_permanent_vars {
panic!("Internal error: attempted to set into permanent state from working set")
} else {
self.delta.vars[var_id.get() - num_permanent_vars].const_val = Some(val);
}
}
pub fn get_variable(&self, var_id: VarId) -> &Variable {
let num_permanent_vars = self.permanent_state.num_vars();
if var_id.get() < num_permanent_vars {
self.permanent_state.get_var(var_id)
} else {
self.delta
.vars
.get(var_id.get() - num_permanent_vars)
.expect("internal error: missing variable")
}
}
pub fn get_variable_if_possible(&self, var_id: VarId) -> Option<&Variable> {
let num_permanent_vars = self.permanent_state.num_vars();
if var_id.get() < num_permanent_vars {
Some(self.permanent_state.get_var(var_id))
} else {
self.delta.vars.get(var_id.get() - num_permanent_vars)
}
}
pub fn get_constant(&self, var_id: VarId) -> Result<&Value, ParseError> {
let var = self.get_variable(var_id);
if let Some(const_val) = &var.const_val {
Ok(const_val)
} else {
Err(ParseError::InternalError(
"constant does not have a constant value".into(),
var.declaration_span,
))
}
}
pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
let num_permanent_decls = self.permanent_state.num_decls();
if decl_id.get() < num_permanent_decls {
self.permanent_state.get_decl(decl_id)
} else {
self.delta
.decls
.get(decl_id.get() - num_permanent_decls)
.expect("internal error: missing declaration")
.as_ref()
}
}
pub fn get_decl_mut(&mut self, decl_id: DeclId) -> &mut Box<dyn Command> {
let num_permanent_decls = self.permanent_state.num_decls();
if decl_id.get() < num_permanent_decls {
panic!("internal error: can only mutate declarations in working set")
} else {
self.delta
.decls
.get_mut(decl_id.get() - num_permanent_decls)
.expect("internal error: missing declaration")
}
}
pub fn get_signature(&self, decl: &dyn Command) -> Signature {
if let Some(block_id) = decl.block_id() {
*self.get_block(block_id).signature.clone()
} else {
decl.signature()
}
}
/// Apply a function to all commands. The function accepts a command name and its DeclId
pub fn traverse_commands(&self, mut f: impl FnMut(&[u8], DeclId)) {
for scope_frame in self.delta.scope.iter().rev() {
for overlay_id in scope_frame.active_overlays.iter().rev() {
let overlay_frame = scope_frame.get_overlay(*overlay_id);
for (name, decl_id) in &overlay_frame.decls {
if overlay_frame.visibility.is_decl_id_visible(decl_id) {
f(name, *decl_id);
}
}
}
}
self.permanent_state.traverse_commands(f);
}
pub fn find_commands_by_predicate(
&self,
mut predicate: impl FnMut(&[u8]) -> bool,
ignore_deprecated: bool,
) -> Vec<(DeclId, Vec<u8>, Option<String>, CommandType)> {
let mut output = vec![];
self.traverse_commands(|name, decl_id| {
if !predicate(name) {
return;
}
let command = self.get_decl(decl_id);
if ignore_deprecated && command.signature().category == Category::Removed {
return;
}
output.push((
decl_id,
name.to_vec(),
Some(command.description().to_string()),
command.command_type(),
));
});
output
}
pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
let num_permanent_blocks = self.permanent_state.num_blocks();
if block_id.get() < num_permanent_blocks {
self.permanent_state.get_block(block_id)
} else {
self.delta
.blocks
.get(block_id.get() - num_permanent_blocks)
.expect("internal error: missing block")
}
}
pub fn get_module(&self, module_id: ModuleId) -> &Module {
let num_permanent_modules = self.permanent_state.num_modules();
if module_id.get() < num_permanent_modules {
self.permanent_state.get_module(module_id)
} else {
self.delta
.modules
.get(module_id.get() - num_permanent_modules)
.expect("internal error: missing module")
}
}
pub fn get_block_mut(&mut self, block_id: BlockId) -> &mut Block {
let num_permanent_blocks = self.permanent_state.num_blocks();
if block_id.get() < num_permanent_blocks {
panic!("Attempt to mutate a block that is in the permanent (immutable) state")
} else {
self.delta
.blocks
.get_mut(block_id.get() - num_permanent_blocks)
.map(Arc::make_mut)
.expect("internal error: missing block")
}
}
/// Find the overlay corresponding to `name`.
pub fn find_overlay(&self, name: &[u8]) -> Option<&OverlayFrame> {
for scope_frame in self.delta.scope.iter().rev() {
if let Some(overlay_id) = scope_frame.find_overlay(name) {
return Some(scope_frame.get_overlay(overlay_id));
}
}
self.permanent_state
.find_overlay(name)
.map(|id| self.permanent_state.get_overlay(id))
}
pub fn last_overlay_name(&self) -> &[u8] {
let mut removed_overlays = vec![];
for scope_frame in self.delta.scope.iter().rev() {
if let Some(last_name) = scope_frame
.active_overlay_names(&mut removed_overlays)
.iter()
.rev()
.next_back()
{
return last_name;
}
}
self.permanent_state.last_overlay_name(&removed_overlays)
}
pub fn last_overlay(&self) -> &OverlayFrame {
let mut removed_overlays = vec![];
for scope_frame in self.delta.scope.iter().rev() {
if let Some(last_overlay) = scope_frame
.active_overlays(&mut removed_overlays)
.rev()
.next_back()
{
return last_overlay;
}
}
self.permanent_state.last_overlay(&removed_overlays)
}
pub fn last_overlay_mut(&mut self) -> &mut OverlayFrame {
if self.delta.last_overlay_mut().is_none() {
// If there is no overlay, automatically activate the last one
let overlay_frame = self.last_overlay();
let name = self.last_overlay_name().to_vec();
let origin = overlay_frame.origin;
let prefixed = overlay_frame.prefixed;
self.add_overlay(
name,
origin,
ResolvedImportPattern::new(vec![], vec![], vec![], vec![]),
prefixed,
);
}
self.delta
.last_overlay_mut()
.expect("internal error: missing added overlay")
}
/// Collect all decls that belong to an overlay
pub fn decls_of_overlay(&self, name: &[u8]) -> HashMap<Vec<u8>, DeclId> {
let mut result = HashMap::new();
if let Some(overlay_id) = self.permanent_state.find_overlay(name) {
let overlay_frame = self.permanent_state.get_overlay(overlay_id);
for (decl_key, decl_id) in &overlay_frame.decls {
result.insert(decl_key.to_owned(), *decl_id);
}
}
for scope_frame in self.delta.scope.iter() {
if let Some(overlay_id) = scope_frame.find_overlay(name) {
let overlay_frame = scope_frame.get_overlay(overlay_id);
for (decl_key, decl_id) in &overlay_frame.decls {
result.insert(decl_key.to_owned(), *decl_id);
}
}
}
result
}
pub fn add_overlay(
&mut self,
name: Vec<u8>,
origin: ModuleId,
definitions: ResolvedImportPattern,
prefixed: bool,
) {
let last_scope_frame = self.delta.last_scope_frame_mut();
last_scope_frame
.removed_overlays
.retain(|removed_name| removed_name != &name);
let overlay_id = if let Some(overlay_id) = last_scope_frame.find_overlay(&name) {
last_scope_frame.get_overlay_mut(overlay_id).origin = origin;
overlay_id
} else {
last_scope_frame
.overlays
.push((name, OverlayFrame::from_origin(origin, prefixed)));
OverlayId::new(last_scope_frame.overlays.len() - 1)
};
last_scope_frame
.active_overlays
.retain(|id| id != &overlay_id);
last_scope_frame.active_overlays.push(overlay_id);
self.use_decls(definitions.decls);
self.use_modules(definitions.modules);
let mut constants = vec![];
for (name, const_vid) in definitions.constants {
constants.push((name, const_vid));
}
for (name, const_val) in definitions.constant_values {
let const_var_id =
self.add_variable(name.clone(), Span::unknown(), const_val.get_type(), false);
self.set_variable_const_val(const_var_id, const_val);
constants.push((name, const_var_id));
}
self.use_variables(constants);
}
pub fn remove_overlay(&mut self, name: &[u8], keep_custom: bool) {
let last_scope_frame = self.delta.last_scope_frame_mut();
let maybe_module_id = if let Some(overlay_id) = last_scope_frame.find_overlay(name) {
last_scope_frame
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/engine/engine_state.rs | crates/nu-protocol/src/engine/engine_state.rs | use crate::{
BlockId, Config, DeclId, FileId, GetSpan, Handlers, HistoryConfig, JobId, Module, ModuleId,
OverlayId, ShellError, SignalAction, Signals, Signature, Span, SpanId, Type, Value, VarId,
VirtualPathId,
ast::Block,
debugger::{Debugger, NoopDebugger},
engine::{
CachedFile, Command, DEFAULT_OVERLAY_NAME, EnvVars, OverlayFrame, ScopeFrame, Stack,
StateDelta, Variable, Visibility,
description::{Doccomments, build_desc},
},
eval_const::create_nu_constant,
report_error::ReportLog,
shell_error::io::IoError,
};
use fancy_regex::Regex;
use lru::LruCache;
use nu_path::AbsolutePathBuf;
use nu_utils::IgnoreCaseExt;
use std::{
collections::HashMap,
num::NonZeroUsize,
path::PathBuf,
sync::{
Arc, Mutex, MutexGuard, PoisonError,
atomic::{AtomicBool, AtomicU32, Ordering},
mpsc::Sender,
mpsc::channel,
},
};
type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>;
#[cfg(feature = "plugin")]
use crate::{PluginRegistryFile, PluginRegistryItem, RegisteredPlugin};
use super::{CurrentJob, Jobs, Mail, Mailbox, ThreadJob};
#[derive(Clone, Debug)]
pub enum VirtualPath {
File(FileId),
Dir(Vec<VirtualPathId>),
}
pub struct ReplState {
pub buffer: String,
// A byte position, as `EditCommand::MoveToPosition` is also a byte position
pub cursor_pos: usize,
/// Immediately accept the buffer on the next loop.
pub accept: bool,
}
pub struct IsDebugging(AtomicBool);
impl IsDebugging {
pub fn new(val: bool) -> Self {
IsDebugging(AtomicBool::new(val))
}
}
impl Clone for IsDebugging {
fn clone(&self) -> Self {
IsDebugging(AtomicBool::new(self.0.load(Ordering::Relaxed)))
}
}
/// The core global engine state. This includes all global definitions as well as any global state that
/// will persist for the whole session.
///
/// Declarations, variables, blocks, and other forms of data are held in the global state and referenced
/// elsewhere using their IDs. These IDs are simply their index into the global state. This allows us to
/// more easily handle creating blocks, binding variables and callsites, and more, because each of these
/// will refer to the corresponding IDs rather than their definitions directly. At runtime, this means
/// less copying and smaller structures.
///
/// Many of the larger objects in this structure are stored within `Arc` to decrease the cost of
/// cloning `EngineState`. While `Arc`s are generally immutable, they can be modified using
/// `Arc::make_mut`, which automatically clones to a new allocation if there are other copies of
/// the `Arc` already in use, but will let us modify the `Arc` directly if we have the only
/// reference to it.
///
/// Note that the runtime stack is not part of this global state. Runtime stacks are handled differently,
/// but they also rely on using IDs rather than full definitions.
#[derive(Clone)]
pub struct EngineState {
files: Vec<CachedFile>,
pub(super) virtual_paths: Vec<(String, VirtualPath)>,
vars: Vec<Variable>,
decls: Arc<Vec<Box<dyn Command + 'static>>>,
// The Vec is wrapped in Arc so that if we don't need to modify the list, we can just clone
// the reference and not have to clone each individual Arc inside. These lists can be
// especially long, so it helps
pub(super) blocks: Arc<Vec<Arc<Block>>>,
pub(super) modules: Arc<Vec<Arc<Module>>>,
pub spans: Vec<Span>,
doccomments: Doccomments,
pub scope: ScopeFrame,
signals: Signals,
pub signal_handlers: Option<Handlers>,
pub env_vars: Arc<EnvVars>,
pub previous_env_vars: Arc<HashMap<String, Value>>,
pub config: Arc<Config>,
pub pipeline_externals_state: Arc<(AtomicU32, AtomicU32)>,
pub repl_state: Arc<Mutex<ReplState>>,
pub table_decl_id: Option<DeclId>,
#[cfg(feature = "plugin")]
pub plugin_path: Option<PathBuf>,
#[cfg(feature = "plugin")]
plugins: Vec<Arc<dyn RegisteredPlugin>>,
config_path: HashMap<String, PathBuf>,
pub history_enabled: bool,
pub history_session_id: i64,
// Path to the file Nushell is currently evaluating, or None if we're in an interactive session.
pub file: Option<PathBuf>,
pub regex_cache: Arc<Mutex<LruCache<String, Regex>>>,
pub is_interactive: bool,
pub is_login: bool,
pub is_lsp: bool,
startup_time: i64,
is_debugging: IsDebugging,
pub debugger: Arc<Mutex<Box<dyn Debugger>>>,
pub report_log: Arc<Mutex<ReportLog>>,
pub jobs: Arc<Mutex<Jobs>>,
// The job being executed with this engine state, or None if main thread
pub current_job: CurrentJob,
pub root_job_sender: Sender<Mail>,
// When there are background jobs running, the interactive behavior of `exit` changes depending on
// the value of this flag:
// - if this is false, then a warning about running jobs is shown and `exit` enables this flag
// - if this is true, then `exit` will `std::process::exit`
//
// This ensures that running exit twice will terminate the program correctly
pub exit_warning_given: Arc<AtomicBool>,
}
// The max number of compiled regexes to keep around in a LRU cache, arbitrarily chosen
const REGEX_CACHE_SIZE: usize = 100; // must be nonzero, otherwise will panic
pub const NU_VARIABLE_ID: VarId = VarId::new(0);
pub const IN_VARIABLE_ID: VarId = VarId::new(1);
pub const ENV_VARIABLE_ID: VarId = VarId::new(2);
// NOTE: If you add more to this list, make sure to update the > checks based on the last in the list
// The first span is unknown span
pub const UNKNOWN_SPAN_ID: SpanId = SpanId::new(0);
impl EngineState {
pub fn new() -> Self {
let (send, recv) = channel::<Mail>();
Self {
files: vec![],
virtual_paths: vec![],
vars: vec![
Variable::new(Span::new(0, 0), Type::Any, false),
Variable::new(Span::new(0, 0), Type::Any, false),
Variable::new(Span::new(0, 0), Type::Any, false),
Variable::new(Span::new(0, 0), Type::Any, false),
Variable::new(Span::new(0, 0), Type::Any, false),
],
decls: Arc::new(vec![]),
blocks: Arc::new(vec![]),
modules: Arc::new(vec![Arc::new(Module::new(
DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
))]),
spans: vec![Span::unknown()],
doccomments: Doccomments::new(),
// make sure we have some default overlay:
scope: ScopeFrame::with_empty_overlay(
DEFAULT_OVERLAY_NAME.as_bytes().to_vec(),
ModuleId::new(0),
false,
),
signal_handlers: None,
signals: Signals::empty(),
env_vars: Arc::new(
[(DEFAULT_OVERLAY_NAME.to_string(), HashMap::new())]
.into_iter()
.collect(),
),
previous_env_vars: Arc::new(HashMap::new()),
config: Arc::new(Config::default()),
pipeline_externals_state: Arc::new((AtomicU32::new(0), AtomicU32::new(0))),
repl_state: Arc::new(Mutex::new(ReplState {
buffer: "".to_string(),
cursor_pos: 0,
accept: false,
})),
table_decl_id: None,
#[cfg(feature = "plugin")]
plugin_path: None,
#[cfg(feature = "plugin")]
plugins: vec![],
config_path: HashMap::new(),
history_enabled: true,
history_session_id: 0,
file: None,
regex_cache: Arc::new(Mutex::new(LruCache::new(
NonZeroUsize::new(REGEX_CACHE_SIZE).expect("tried to create cache of size zero"),
))),
is_interactive: false,
is_login: false,
is_lsp: false,
startup_time: -1,
is_debugging: IsDebugging::new(false),
debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
report_log: Arc::default(),
jobs: Arc::new(Mutex::new(Jobs::default())),
current_job: CurrentJob {
id: JobId::new(0),
background_thread_job: None,
mailbox: Arc::new(Mutex::new(Mailbox::new(recv))),
},
root_job_sender: send,
exit_warning_given: Arc::new(AtomicBool::new(false)),
}
}
pub fn signals(&self) -> &Signals {
&self.signals
}
pub fn reset_signals(&mut self) {
self.signals.reset();
if let Some(ref handlers) = self.signal_handlers {
handlers.run(SignalAction::Reset);
}
}
pub fn set_signals(&mut self, signals: Signals) {
self.signals = signals;
}
/// Merges a `StateDelta` onto the current state. These deltas come from a system, like the parser, that
/// creates a new set of definitions and visible symbols in the current scope. We make this transactional
/// as there are times when we want to run the parser and immediately throw away the results (namely:
/// syntax highlighting and completions).
///
/// When we want to preserve what the parser has created, we can take its output (the `StateDelta`) and
/// use this function to merge it into the global state.
pub fn merge_delta(&mut self, mut delta: StateDelta) -> Result<(), ShellError> {
// Take the mutable reference and extend the permanent state from the working set
self.files.extend(delta.files);
self.virtual_paths.extend(delta.virtual_paths);
self.vars.extend(delta.vars);
self.spans.extend(delta.spans);
self.doccomments.merge_with(delta.doccomments);
// Avoid potentially cloning the Arcs if we aren't adding anything
if !delta.decls.is_empty() {
Arc::make_mut(&mut self.decls).extend(delta.decls);
}
if !delta.blocks.is_empty() {
Arc::make_mut(&mut self.blocks).extend(delta.blocks);
}
if !delta.modules.is_empty() {
Arc::make_mut(&mut self.modules).extend(delta.modules);
}
let first = delta.scope.remove(0);
for (delta_name, delta_overlay) in first.clone().overlays {
if let Some((_, existing_overlay)) = self
.scope
.overlays
.iter_mut()
.find(|(name, _)| name == &delta_name)
{
// Updating existing overlay
for item in delta_overlay.decls.into_iter() {
existing_overlay.decls.insert(item.0, item.1);
}
for item in delta_overlay.vars.into_iter() {
existing_overlay.insert_variable(item.0, item.1);
}
for item in delta_overlay.modules.into_iter() {
existing_overlay.modules.insert(item.0, item.1);
}
existing_overlay
.visibility
.merge_with(delta_overlay.visibility);
} else {
// New overlay was added to the delta
self.scope.overlays.push((delta_name, delta_overlay));
}
}
let mut activated_ids = self.translate_overlay_ids(&first);
let mut removed_ids = vec![];
for name in &first.removed_overlays {
if let Some(overlay_id) = self.find_overlay(name) {
removed_ids.push(overlay_id);
}
}
// Remove overlays removed in delta
self.scope
.active_overlays
.retain(|id| !removed_ids.contains(id));
// Move overlays activated in the delta to be first
self.scope
.active_overlays
.retain(|id| !activated_ids.contains(id));
self.scope.active_overlays.append(&mut activated_ids);
#[cfg(feature = "plugin")]
if !delta.plugins.is_empty() {
for plugin in std::mem::take(&mut delta.plugins) {
// Connect plugins to the signal handlers
if let Some(handlers) = &self.signal_handlers {
plugin.clone().configure_signal_handler(handlers)?;
}
// Replace plugins that overlap in identity.
if let Some(existing) = self
.plugins
.iter_mut()
.find(|p| p.identity().name() == plugin.identity().name())
{
// Stop the existing plugin, so that the new plugin definitely takes over
existing.stop()?;
*existing = plugin;
} else {
self.plugins.push(plugin);
}
}
}
#[cfg(feature = "plugin")]
if !delta.plugin_registry_items.is_empty() {
// Update the plugin file with the new signatures.
if self.plugin_path.is_some() {
self.update_plugin_file(std::mem::take(&mut delta.plugin_registry_items))?;
}
}
Ok(())
}
/// Merge the environment from the runtime Stack into the engine state
pub fn merge_env(&mut self, stack: &mut Stack) -> Result<(), ShellError> {
for mut scope in stack.env_vars.drain(..) {
for (overlay_name, mut env) in Arc::make_mut(&mut scope).drain() {
if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
// Updating existing overlay
env_vars.extend(env.drain());
} else {
// Pushing a new overlay
Arc::make_mut(&mut self.env_vars).insert(overlay_name, env);
}
}
}
let cwd = self.cwd(Some(stack))?;
std::env::set_current_dir(cwd).map_err(|err| {
IoError::new_internal(err, "Could not set current dir", crate::location!())
})?;
if let Some(config) = stack.config.take() {
// If config was updated in the stack, replace it.
self.config = config;
// Make plugin GC config changes take effect immediately.
#[cfg(feature = "plugin")]
self.update_plugin_gc_configs(&self.config.plugin_gc);
}
Ok(())
}
/// Clean up unused variables from a Stack to prevent memory leaks.
/// This removes variables that are no longer referenced by any overlay.
pub fn cleanup_stack_variables(&mut self, stack: &mut Stack) {
use std::collections::HashSet;
let mut shadowed_vars = HashSet::new();
for (_, frame) in self.scope.overlays.iter_mut() {
shadowed_vars.extend(frame.shadowed_vars.to_owned());
frame.shadowed_vars.clear();
}
// Remove variables from stack that are no longer referenced
stack
.vars
.retain(|(var_id, _)| !shadowed_vars.contains(var_id));
}
pub fn active_overlay_ids<'a, 'b>(
&'b self,
removed_overlays: &'a [Vec<u8>],
) -> impl DoubleEndedIterator<Item = &'b OverlayId> + 'a
where
'b: 'a,
{
self.scope.active_overlays.iter().filter(|id| {
!removed_overlays
.iter()
.any(|name| name == self.get_overlay_name(**id))
})
}
pub fn active_overlays<'a, 'b>(
&'b self,
removed_overlays: &'a [Vec<u8>],
) -> impl DoubleEndedIterator<Item = &'b OverlayFrame> + 'a
where
'b: 'a,
{
self.active_overlay_ids(removed_overlays)
.map(|id| self.get_overlay(*id))
}
pub fn active_overlay_names<'a, 'b>(
&'b self,
removed_overlays: &'a [Vec<u8>],
) -> impl DoubleEndedIterator<Item = &'b [u8]> + 'a
where
'b: 'a,
{
self.active_overlay_ids(removed_overlays)
.map(|id| self.get_overlay_name(*id))
}
/// Translate overlay IDs from other to IDs in self
fn translate_overlay_ids(&self, other: &ScopeFrame) -> Vec<OverlayId> {
let other_names = other.active_overlays.iter().map(|other_id| {
&other
.overlays
.get(other_id.get())
.expect("internal error: missing overlay")
.0
});
other_names
.map(|other_name| {
self.find_overlay(other_name)
.expect("internal error: missing overlay")
})
.collect()
}
pub fn last_overlay_name(&self, removed_overlays: &[Vec<u8>]) -> &[u8] {
self.active_overlay_names(removed_overlays)
.last()
.expect("internal error: no active overlays")
}
pub fn last_overlay(&self, removed_overlays: &[Vec<u8>]) -> &OverlayFrame {
self.active_overlay_ids(removed_overlays)
.last()
.map(|id| self.get_overlay(*id))
.expect("internal error: no active overlays")
}
pub fn get_overlay_name(&self, overlay_id: OverlayId) -> &[u8] {
&self
.scope
.overlays
.get(overlay_id.get())
.expect("internal error: missing overlay")
.0
}
pub fn get_overlay(&self, overlay_id: OverlayId) -> &OverlayFrame {
&self
.scope
.overlays
.get(overlay_id.get())
.expect("internal error: missing overlay")
.1
}
pub fn render_env_vars(&self) -> HashMap<&str, &Value> {
let mut result: HashMap<&str, &Value> = HashMap::new();
for overlay_name in self.active_overlay_names(&[]) {
let name = String::from_utf8_lossy(overlay_name);
if let Some(env_vars) = self.env_vars.get(name.as_ref()) {
result.extend(env_vars.iter().map(|(k, v)| (k.as_str(), v)));
}
}
result
}
pub fn add_env_var(&mut self, name: String, val: Value) {
let overlay_name = String::from_utf8_lossy(self.last_overlay_name(&[])).to_string();
if let Some(env_vars) = Arc::make_mut(&mut self.env_vars).get_mut(&overlay_name) {
env_vars.insert(name, val);
} else {
Arc::make_mut(&mut self.env_vars)
.insert(overlay_name, [(name, val)].into_iter().collect());
}
}
pub fn get_env_var(&self, name: &str) -> Option<&Value> {
for overlay_id in self.scope.active_overlays.iter().rev() {
let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref())
&& let Some(val) = env_vars.get(name)
{
return Some(val);
}
}
None
}
// Returns Some((name, value)) if found, None otherwise.
// When updating environment variables, make sure to use
// the same case (the returned "name") as the original
// environment variable name.
pub fn get_env_var_insensitive(&self, name: &str) -> Option<(&String, &Value)> {
for overlay_id in self.scope.active_overlays.iter().rev() {
let overlay_name = String::from_utf8_lossy(self.get_overlay_name(*overlay_id));
if let Some(env_vars) = self.env_vars.get(overlay_name.as_ref())
&& let Some(v) = env_vars.iter().find(|(k, _)| k.eq_ignore_case(name))
{
return Some((v.0, v.1));
}
}
None
}
#[cfg(feature = "plugin")]
pub fn plugins(&self) -> &[Arc<dyn RegisteredPlugin>] {
&self.plugins
}
#[cfg(feature = "plugin")]
fn update_plugin_file(&self, updated_items: Vec<PluginRegistryItem>) -> Result<(), ShellError> {
// Updating the signatures plugin file with the added signatures
use std::fs::File;
let plugin_path = self
.plugin_path
.as_ref()
.ok_or_else(|| ShellError::GenericError {
error: "Plugin file path not set".into(),
msg: "".into(),
span: None,
help: Some("you may be running nu with --no-config-file".into()),
inner: vec![],
})?;
// Read the current contents of the plugin file if it exists
let mut contents = match File::open(plugin_path.as_path()) {
Ok(mut plugin_file) => PluginRegistryFile::read_from(&mut plugin_file, None),
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
Ok(PluginRegistryFile::default())
} else {
Err(ShellError::Io(IoError::new_internal_with_path(
err,
"Failed to open plugin file",
crate::location!(),
PathBuf::from(plugin_path),
)))
}
}
}?;
// Update the given signatures
for item in updated_items {
contents.upsert_plugin(item);
}
// Write it to the same path
let plugin_file = File::create(plugin_path.as_path()).map_err(|err| {
IoError::new_internal_with_path(
err,
"Failed to write plugin file",
crate::location!(),
PathBuf::from(plugin_path),
)
})?;
contents.write_to(plugin_file, None)
}
/// Update plugins with new garbage collection config
#[cfg(feature = "plugin")]
fn update_plugin_gc_configs(&self, plugin_gc: &crate::PluginGcConfigs) {
for plugin in &self.plugins {
plugin.set_gc_config(plugin_gc.get(plugin.identity().name()));
}
}
pub fn num_files(&self) -> usize {
self.files.len()
}
pub fn num_virtual_paths(&self) -> usize {
self.virtual_paths.len()
}
pub fn num_vars(&self) -> usize {
self.vars.len()
}
pub fn num_decls(&self) -> usize {
self.decls.len()
}
pub fn num_blocks(&self) -> usize {
self.blocks.len()
}
pub fn num_modules(&self) -> usize {
self.modules.len()
}
pub fn num_spans(&self) -> usize {
self.spans.len()
}
pub fn print_vars(&self) {
for var in self.vars.iter().enumerate() {
println!("var{}: {:?}", var.0, var.1);
}
}
pub fn print_decls(&self) {
for decl in self.decls.iter().enumerate() {
println!("decl{}: {:?}", decl.0, decl.1.signature());
}
}
pub fn print_blocks(&self) {
for block in self.blocks.iter().enumerate() {
println!("block{}: {:?}", block.0, block.1);
}
}
pub fn print_contents(&self) {
for cached_file in self.files.iter() {
let string = String::from_utf8_lossy(&cached_file.content);
println!("{string}");
}
}
/// Find the [`DeclId`](crate::DeclId) corresponding to a declaration with `name`.
///
/// Searches within active overlays, and filtering out overlays in `removed_overlays`.
pub fn find_decl(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<DeclId> {
let mut visibility: Visibility = Visibility::new();
for overlay_frame in self.active_overlays(removed_overlays).rev() {
visibility.append(&overlay_frame.visibility);
if let Some(decl_id) = overlay_frame.get_decl(name)
&& visibility.is_decl_id_visible(&decl_id)
{
return Some(decl_id);
}
}
None
}
/// Find the name of the declaration corresponding to `decl_id`.
///
/// Searches within active overlays, and filtering out overlays in `removed_overlays`.
pub fn find_decl_name(&self, decl_id: DeclId, removed_overlays: &[Vec<u8>]) -> Option<&[u8]> {
let mut visibility: Visibility = Visibility::new();
for overlay_frame in self.active_overlays(removed_overlays).rev() {
visibility.append(&overlay_frame.visibility);
if visibility.is_decl_id_visible(&decl_id) {
for (name, id) in overlay_frame.decls.iter() {
if id == &decl_id {
return Some(name);
}
}
}
}
None
}
/// Find the [`OverlayId`](crate::OverlayId) corresponding to `name`.
///
/// Searches all overlays, not just active overlays. To search only in active overlays, use [`find_active_overlay`](EngineState::find_active_overlay)
pub fn find_overlay(&self, name: &[u8]) -> Option<OverlayId> {
self.scope.find_overlay(name)
}
/// Find the [`OverlayId`](crate::OverlayId) of the active overlay corresponding to `name`.
///
/// Searches only active overlays. To search in all overlays, use [`find_overlay`](EngineState::find_active_overlay)
pub fn find_active_overlay(&self, name: &[u8]) -> Option<OverlayId> {
self.scope.find_active_overlay(name)
}
/// Find the [`ModuleId`](crate::ModuleId) corresponding to `name`.
///
/// Searches within active overlays, and filtering out overlays in `removed_overlays`.
pub fn find_module(&self, name: &[u8], removed_overlays: &[Vec<u8>]) -> Option<ModuleId> {
for overlay_frame in self.active_overlays(removed_overlays).rev() {
if let Some(module_id) = overlay_frame.modules.get(name) {
return Some(*module_id);
}
}
None
}
pub fn get_module_comments(&self, module_id: ModuleId) -> Option<&[Span]> {
self.doccomments.get_module_comments(module_id)
}
#[cfg(feature = "plugin")]
pub fn plugin_decls(&self) -> impl Iterator<Item = &Box<dyn Command + 'static>> {
let mut unique_plugin_decls = HashMap::new();
// Make sure there are no duplicate decls: Newer one overwrites the older one
for decl in self.decls.iter().filter(|d| d.is_plugin()) {
unique_plugin_decls.insert(decl.name(), decl);
}
let mut plugin_decls: Vec<(&str, &Box<dyn Command>)> =
unique_plugin_decls.into_iter().collect();
// Sort the plugins by name so we don't end up with a random plugin file each time
plugin_decls.sort_by(|a, b| a.0.cmp(b.0));
plugin_decls.into_iter().map(|(_, decl)| decl)
}
pub fn which_module_has_decl(
&self,
decl_name: &[u8],
removed_overlays: &[Vec<u8>],
) -> Option<&[u8]> {
for overlay_frame in self.active_overlays(removed_overlays).rev() {
for (module_name, module_id) in overlay_frame.modules.iter() {
let module = self.get_module(*module_id);
if module.has_decl(decl_name) {
return Some(module_name);
}
}
}
None
}
/// Apply a function to all commands. The function accepts a command name and its DeclId
pub fn traverse_commands(&self, mut f: impl FnMut(&[u8], DeclId)) {
for overlay_frame in self.active_overlays(&[]).rev() {
for (name, decl_id) in &overlay_frame.decls {
if overlay_frame.visibility.is_decl_id_visible(decl_id) {
f(name, *decl_id);
}
}
}
}
pub fn get_span_contents(&self, span: Span) -> &[u8] {
for file in &self.files {
if file.covered_span.contains_span(span) {
return &file.content
[(span.start - file.covered_span.start)..(span.end - file.covered_span.start)];
}
}
&[0u8; 0]
}
/// If the span's content starts with the given prefix, return two subspans
/// corresponding to this prefix, and the rest of the content.
pub fn span_match_prefix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
let contents = self.get_span_contents(span);
if contents.starts_with(prefix) {
span.split_at(prefix.len())
} else {
None
}
}
/// If the span's content ends with the given postfix, return two subspans
/// corresponding to the rest of the content, and this postfix.
pub fn span_match_postfix(&self, span: Span, prefix: &[u8]) -> Option<(Span, Span)> {
let contents = self.get_span_contents(span);
if contents.ends_with(prefix) {
span.split_at(span.len() - prefix.len())
} else {
None
}
}
/// Get the global config from the engine state.
///
/// Use [`Stack::get_config()`] instead whenever the `Stack` is available, as it takes into
/// account local changes to `$env.config`.
pub fn get_config(&self) -> &Arc<Config> {
&self.config
}
pub fn set_config(&mut self, conf: impl Into<Arc<Config>>) {
let conf = conf.into();
#[cfg(feature = "plugin")]
if conf.plugin_gc != self.config.plugin_gc {
// Make plugin GC config changes take effect immediately.
self.update_plugin_gc_configs(&conf.plugin_gc);
}
self.config = conf;
}
/// Fetch the configuration for a plugin
///
/// The `plugin` must match the registered name of a plugin. For `plugin add
/// nu_plugin_example` the plugin name to use will be `"example"`
pub fn get_plugin_config(&self, plugin: &str) -> Option<&Value> {
self.config.plugins.get(plugin)
}
/// Returns the configuration settings for command history or `None` if history is disabled
pub fn history_config(&self) -> Option<HistoryConfig> {
self.history_enabled.then(|| self.config.history)
}
pub fn get_var(&self, var_id: VarId) -> &Variable {
self.vars
.get(var_id.get())
.expect("internal error: missing variable")
}
pub fn get_constant(&self, var_id: VarId) -> Option<&Value> {
let var = self.get_var(var_id);
var.const_val.as_ref()
}
pub fn generate_nu_constant(&mut self) {
self.vars[NU_VARIABLE_ID.get()].const_val = Some(create_nu_constant(self, Span::unknown()));
}
pub fn get_decl(&self, decl_id: DeclId) -> &dyn Command {
self.decls
.get(decl_id.get())
.expect("internal error: missing declaration")
.as_ref()
}
/// Get all commands within scope, sorted by the commands' names
pub fn get_decls_sorted(&self, include_hidden: bool) -> Vec<(Vec<u8>, DeclId)> {
let mut decls_map = HashMap::new();
for overlay_frame in self.active_overlays(&[]) {
let new_decls = if include_hidden {
overlay_frame.decls.clone()
} else {
overlay_frame
.decls
.clone()
.into_iter()
.filter(|(_, id)| overlay_frame.visibility.is_decl_id_visible(id))
.collect()
};
decls_map.extend(new_decls);
}
let mut decls: Vec<(Vec<u8>, DeclId)> = decls_map.into_iter().collect();
decls.sort_by(|a, b| a.0.cmp(&b.0));
decls
}
pub fn get_signature(&self, decl: &dyn Command) -> Signature {
if let Some(block_id) = decl.block_id() {
*self.blocks[block_id.get()].signature.clone()
} else {
decl.signature()
}
}
/// Get signatures of all commands within scope with their decl ids.
pub fn get_signatures_and_declids(&self, include_hidden: bool) -> Vec<(Signature, DeclId)> {
self.get_decls_sorted(include_hidden)
.into_iter()
.map(|(_, id)| {
let decl = self.get_decl(id);
(self.get_signature(decl).update_from_command(decl), id)
})
.collect()
}
pub fn get_block(&self, block_id: BlockId) -> &Arc<Block> {
self.blocks
.get(block_id.get())
.expect("internal error: missing block")
}
/// Optionally get a block by id, if it exists
///
/// Prefer to use [`.get_block()`](Self::get_block) in most cases - `BlockId`s that don't exist
/// are normally a compiler error. This only exists to stop plugins from crashing the engine if
/// they send us something invalid.
pub fn try_get_block(&self, block_id: BlockId) -> Option<&Arc<Block>> {
self.blocks.get(block_id.get())
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/attribute.rs | crates/nu-protocol/src/ast/attribute.rs | use super::Expression;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Attribute {
pub expr: Expression,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AttributeBlock {
pub attributes: Vec<Attribute>,
pub item: Box<Expression>,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/value_with_unit.rs | crates/nu-protocol/src/ast/value_with_unit.rs | use super::Expression;
use crate::{Spanned, Unit};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ValueWithUnit {
pub expr: Expression,
pub unit: Spanned<Unit>,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/expr.rs | crates/nu-protocol/src/ast/expr.rs | use chrono::FixedOffset;
use serde::{Deserialize, Serialize};
use super::{
AttributeBlock, Call, CellPath, Expression, ExternalArgument, FullCellPath, Keyword,
MatchPattern, Operator, Range, Table, ValueWithUnit,
};
use crate::{
BlockId, ModuleId, OutDest, Signature, Span, VarId, ast::ImportPattern, engine::StateWorkingSet,
};
/// An [`Expression`] AST node
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Expr {
AttributeBlock(AttributeBlock),
Bool(bool),
Int(i64),
Float(f64),
Binary(Vec<u8>),
Range(Box<Range>),
Var(VarId),
VarDecl(VarId),
Call(Box<Call>),
ExternalCall(Box<Expression>, Box<[ExternalArgument]>), // head, args
Operator(Operator),
RowCondition(BlockId),
UnaryNot(Box<Expression>),
BinaryOp(Box<Expression>, Box<Expression>, Box<Expression>), //lhs, op, rhs
Collect(VarId, Box<Expression>),
Subexpression(BlockId),
Block(BlockId),
Closure(BlockId),
MatchBlock(Vec<(MatchPattern, Expression)>),
List(Vec<ListItem>),
Table(Table),
Record(Vec<RecordItem>),
Keyword(Box<Keyword>),
ValueWithUnit(Box<ValueWithUnit>),
DateTime(chrono::DateTime<FixedOffset>),
/// The boolean is `true` if the string is quoted.
Filepath(String, bool),
/// The boolean is `true` if the string is quoted.
Directory(String, bool),
/// The boolean is `true` if the string is quoted.
GlobPattern(String, bool),
String(String),
RawString(String),
CellPath(CellPath),
FullCellPath(Box<FullCellPath>),
ImportPattern(Box<ImportPattern>),
Overlay(Option<ModuleId>),
Signature(Box<Signature>),
StringInterpolation(Vec<Expression>),
/// The boolean is `true` if the string is quoted.
GlobInterpolation(Vec<Expression>, bool),
Nothing,
Garbage,
}
// This is to document/enforce the size of `Expr` in bytes.
// We should try to avoid increasing the size of `Expr`,
// and PRs that do so will have to change the number below so that it's noted in review.
const _: () = assert!(std::mem::size_of::<Expr>() <= 40);
impl Expr {
pub fn pipe_redirection(
&self,
working_set: &StateWorkingSet,
) -> (Option<OutDest>, Option<OutDest>) {
match self {
Expr::AttributeBlock(ab) => ab.item.expr.pipe_redirection(working_set),
Expr::Call(call) => working_set.get_decl(call.decl_id).pipe_redirection(),
Expr::Collect(_, _) => {
// A collect expression always has default redirection, it's just going to collect
// stdout unless another type of redirection is specified
(None, None)
},
Expr::Subexpression(block_id) | Expr::Block(block_id) => working_set
.get_block(*block_id)
.pipe_redirection(working_set),
Expr::FullCellPath(cell_path) => cell_path.head.expr.pipe_redirection(working_set),
Expr::Bool(_)
| Expr::Int(_)
| Expr::Float(_)
| Expr::Binary(_)
| Expr::Range(_)
| Expr::Var(_)
| Expr::UnaryNot(_)
| Expr::BinaryOp(_, _, _)
| Expr::Closure(_) // piping into a closure value, not into a closure call
| Expr::List(_)
| Expr::Table(_)
| Expr::Record(_)
| Expr::ValueWithUnit(_)
| Expr::DateTime(_)
| Expr::String(_)
| Expr::RawString(_)
| Expr::CellPath(_)
| Expr::StringInterpolation(_)
| Expr::GlobInterpolation(_, _)
| Expr::Nothing => {
// These expressions do not use the output of the pipeline in any meaningful way,
// but we still need to use the pipeline output, so the previous command
// can be stopped with SIGPIPE(in unix).
(None, None)
}
Expr::VarDecl(_)
| Expr::Operator(_)
| Expr::Filepath(_, _)
| Expr::Directory(_, _)
| Expr::GlobPattern(_, _)
| Expr::ImportPattern(_)
| Expr::Overlay(_)
| Expr::Signature(_)
| Expr::Garbage => {
// These should be impossible to pipe to,
// but even it is, the pipeline output is not used in any way.
(Some(OutDest::Null), None)
}
Expr::RowCondition(_) | Expr::MatchBlock(_) => {
// These should be impossible to pipe to,
// but if they are, then the pipeline output could be used.
(None, None)
}
Expr::ExternalCall(_, _) => {
// No override necessary, pipes will always be created in eval
(None, None)
}
Expr::Keyword(_) => {
// Not sure about this; let's return no redirection override for now.
(None, None)
}
}
}
}
/// Expressions permitted inside a record expression/literal
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RecordItem {
/// A key: val mapping
Pair(Expression, Expression),
/// Span for the "..." and the expression that's being spread
Spread(Span, Expression),
}
/// Expressions permitted inside a list expression/literal
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ListItem {
/// A normal expression
Item(Expression),
/// Span for the "..." and the expression that's being spread
Spread(Span, Expression),
}
impl ListItem {
pub fn expr(&self) -> &Expression {
let (ListItem::Item(expr) | ListItem::Spread(_, expr)) = self;
expr
}
pub fn expr_mut(&mut self) -> &mut Expression {
let (ListItem::Item(expr) | ListItem::Spread(_, expr)) = self;
expr
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/range.rs | crates/nu-protocol/src/ast/range.rs | use super::{Expression, RangeOperator};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Range {
pub from: Option<Expression>,
pub next: Option<Expression>,
pub to: Option<Expression>,
pub operator: RangeOperator,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/call.rs | crates/nu-protocol/src/ast/call.rs | use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use crate::{
DeclId, FromValue, ShellError, Span, Spanned, Value, ast::Expression, engine::StateWorkingSet,
eval_const::eval_constant,
};
/// Parsed command arguments
///
/// Primarily for internal commands
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Argument {
/// A positional argument (that is not [`Argument::Spread`])
///
/// ```nushell
/// my_cmd positional
/// ```
Positional(Expression),
/// A named/flag argument that can optionally receive a [`Value`] as an [`Expression`]
///
/// The optional second `Spanned<String>` refers to the short-flag version if used
/// ```nushell
/// my_cmd --flag
/// my_cmd -f
/// my_cmd --flag-with-value <expr>
/// ```
Named((Spanned<String>, Option<Spanned<String>>, Option<Expression>)),
/// unknown argument used in "fall-through" signatures
Unknown(Expression),
/// a list spread to fill in rest arguments
Spread(Expression),
}
impl Argument {
/// The span for an argument
pub fn span(&self) -> Span {
match self {
Argument::Positional(e) => e.span,
Argument::Named((named, short, expr)) => {
let start = named.span.start;
let end = if let Some(expr) = expr {
expr.span.end
} else if let Some(short) = short {
short.span.end
} else {
named.span.end
};
Span::new(start, end)
}
Argument::Unknown(e) => e.span,
Argument::Spread(e) => e.span,
}
}
pub fn expr(&self) -> Option<&Expression> {
match self {
Argument::Named((_, _, expr)) => expr.as_ref(),
Argument::Positional(expr) | Argument::Unknown(expr) | Argument::Spread(expr) => {
Some(expr)
}
}
}
}
/// Argument passed to an external command
///
/// Here the parsing rules slightly differ to directly pass strings to the external process
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ExternalArgument {
/// Expression that needs to be evaluated to turn into an external process argument
Regular(Expression),
/// Occurrence of a `...` spread operator that needs to be expanded
Spread(Expression),
}
impl ExternalArgument {
pub fn expr(&self) -> &Expression {
match self {
ExternalArgument::Regular(expr) => expr,
ExternalArgument::Spread(expr) => expr,
}
}
}
/// Parsed call of a `Command`
///
/// As we also implement some internal keywords in terms of the `Command` trait, this type stores the passed arguments as [`Expression`].
/// Some of its methods lazily evaluate those to [`Value`] while others return the underlying
/// [`Expression`].
///
/// For further utilities check the `nu_engine::CallExt` trait that extends [`Call`]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Call {
/// identifier of the declaration to call
pub decl_id: DeclId,
pub head: Span,
pub arguments: Vec<Argument>,
/// this field is used by the parser to pass additional command-specific information
pub parser_info: HashMap<String, Expression>,
}
impl Call {
pub fn new(head: Span) -> Call {
Self {
decl_id: DeclId::new(0),
head,
arguments: vec![],
parser_info: HashMap::new(),
}
}
/// The span encompassing the arguments
///
/// If there are no arguments the span covers where the first argument would exist
///
/// If there are one or more arguments the span encompasses the start of the first argument to
/// end of the last argument
pub fn arguments_span(&self) -> Span {
if self.arguments.is_empty() {
self.head.past()
} else {
Span::merge_many(self.arguments.iter().map(|a| a.span()))
}
}
pub fn named_iter(
&self,
) -> impl DoubleEndedIterator<Item = &(Spanned<String>, Option<Spanned<String>>, Option<Expression>)>
{
self.arguments.iter().filter_map(|arg| match arg {
Argument::Named(named) => Some(named),
Argument::Positional(_) => None,
Argument::Unknown(_) => None,
Argument::Spread(_) => None,
})
}
pub fn named_iter_mut(
&mut self,
) -> impl Iterator<Item = &mut (Spanned<String>, Option<Spanned<String>>, Option<Expression>)>
{
self.arguments.iter_mut().filter_map(|arg| match arg {
Argument::Named(named) => Some(named),
Argument::Positional(_) => None,
Argument::Unknown(_) => None,
Argument::Spread(_) => None,
})
}
pub fn named_len(&self) -> usize {
self.named_iter().count()
}
pub fn add_named(
&mut self,
named: (Spanned<String>, Option<Spanned<String>>, Option<Expression>),
) {
self.arguments.push(Argument::Named(named));
}
pub fn add_positional(&mut self, positional: Expression) {
self.arguments.push(Argument::Positional(positional));
}
pub fn add_unknown(&mut self, unknown: Expression) {
self.arguments.push(Argument::Unknown(unknown));
}
pub fn add_spread(&mut self, args: Expression) {
self.arguments.push(Argument::Spread(args));
}
pub fn positional_iter(&self) -> impl Iterator<Item = &Expression> {
self.arguments
.iter()
.take_while(|arg| match arg {
Argument::Spread(_) => false, // Don't include positional arguments given to rest parameter
_ => true,
})
.filter_map(|arg| match arg {
Argument::Named(_) => None,
Argument::Positional(positional) => Some(positional),
Argument::Unknown(unknown) => Some(unknown),
Argument::Spread(_) => None,
})
}
pub fn positional_nth(&self, i: usize) -> Option<&Expression> {
self.positional_iter().nth(i)
}
pub fn positional_len(&self) -> usize {
self.positional_iter().count()
}
/// Returns every argument to the rest parameter, as well as whether each argument
/// is spread or a normal positional argument (true for spread, false for normal)
pub fn rest_iter(&self, start: usize) -> impl Iterator<Item = (&Expression, bool)> {
// todo maybe rewrite to be more elegant or something
let args = self
.arguments
.iter()
.filter_map(|arg| match arg {
Argument::Named(_) => None,
Argument::Positional(positional) => Some((positional, false)),
Argument::Unknown(unknown) => Some((unknown, false)),
Argument::Spread(args) => Some((args, true)),
})
.collect::<Vec<_>>();
let spread_start = args.iter().position(|(_, spread)| *spread).unwrap_or(start);
args.into_iter().skip(start.min(spread_start))
}
pub fn get_parser_info(&self, name: &str) -> Option<&Expression> {
self.parser_info.get(name)
}
pub fn set_parser_info(&mut self, name: String, val: Expression) -> Option<Expression> {
self.parser_info.insert(name, val)
}
pub fn set_kth_argument(&mut self, k: usize, arg: Argument) -> bool {
self.arguments.get_mut(k).map(|a| *a = arg).is_some()
}
pub fn get_flag_expr(&self, flag_name: &str) -> Option<&Expression> {
for name in self.named_iter().rev() {
if flag_name == name.0.item {
return name.2.as_ref();
}
}
None
}
pub fn get_named_arg(&self, flag_name: &str) -> Option<Spanned<String>> {
for name in self.named_iter().rev() {
if flag_name == name.0.item {
return Some(name.0.clone());
}
}
None
}
/// Check if a boolean flag is set (i.e. `--bool` or `--bool=true`)
/// evaluating the expression after = as a constant command
pub fn has_flag_const(
&self,
working_set: &StateWorkingSet,
flag_name: &str,
) -> Result<bool, ShellError> {
for name in self.named_iter() {
if flag_name == name.0.item {
return if let Some(expr) = &name.2 {
// Check --flag=false
let result = eval_constant(working_set, expr)?;
match result {
Value::Bool { val, .. } => Ok(val),
_ => Err(ShellError::CantConvert {
to_type: "bool".into(),
from_type: result.get_type().to_string(),
span: result.span(),
help: Some("".into()),
}),
}
} else {
Ok(true)
};
}
}
Ok(false)
}
pub 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)
}
}
pub fn rest_const<T: FromValue>(
&self,
working_set: &StateWorkingSet,
starting_pos: usize,
) -> Result<Vec<T>, ShellError> {
let mut output = vec![];
for result in
self.rest_iter_flattened(starting_pos, |expr| eval_constant(working_set, expr))?
{
output.push(FromValue::from_value(result)?);
}
Ok(output)
}
pub fn rest_iter_flattened<F>(
&self,
start: usize,
mut eval: F,
) -> Result<Vec<Value>, ShellError>
where
F: FnMut(&Expression) -> Result<Value, ShellError>,
{
let mut output = Vec::new();
for (expr, spread) in self.rest_iter(start) {
let result = eval(expr)?;
if spread {
match result {
Value::List { mut vals, .. } => output.append(&mut vals),
Value::Nothing { .. } => (),
_ => return Err(ShellError::CannotSpreadAsList { span: expr.span }),
}
} else {
output.push(result);
}
}
Ok(output)
}
pub 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,
})
}
}
pub fn span(&self) -> Span {
self.head.merge(self.arguments_span())
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::engine::EngineState;
#[test]
fn argument_span_named() {
let engine_state = EngineState::new();
let mut working_set = StateWorkingSet::new(&engine_state);
let named = Spanned {
item: "named".to_string(),
span: Span::new(2, 3),
};
let short = Spanned {
item: "short".to_string(),
span: Span::new(5, 7),
};
let expr = Expression::garbage(&mut working_set, Span::new(11, 13));
let arg = Argument::Named((named.clone(), None, None));
assert_eq!(Span::new(2, 3), arg.span());
let arg = Argument::Named((named.clone(), Some(short.clone()), None));
assert_eq!(Span::new(2, 7), arg.span());
let arg = Argument::Named((named.clone(), None, Some(expr.clone())));
assert_eq!(Span::new(2, 13), arg.span());
let arg = Argument::Named((named.clone(), Some(short.clone()), Some(expr.clone())));
assert_eq!(Span::new(2, 13), arg.span());
}
#[test]
fn argument_span_positional() {
let engine_state = EngineState::new();
let mut working_set = StateWorkingSet::new(&engine_state);
let span = Span::new(2, 3);
let expr = Expression::garbage(&mut working_set, span);
let arg = Argument::Positional(expr);
assert_eq!(span, arg.span());
}
#[test]
fn argument_span_unknown() {
let engine_state = EngineState::new();
let mut working_set = StateWorkingSet::new(&engine_state);
let span = Span::new(2, 3);
let expr = Expression::garbage(&mut working_set, span);
let arg = Argument::Unknown(expr);
assert_eq!(span, arg.span());
}
#[test]
fn call_arguments_span() {
let engine_state = EngineState::new();
let mut working_set = StateWorkingSet::new(&engine_state);
let mut call = Call::new(Span::new(0, 1));
call.add_positional(Expression::garbage(&mut working_set, Span::new(2, 3)));
call.add_positional(Expression::garbage(&mut working_set, Span::new(5, 7)));
assert_eq!(Span::new(2, 7), call.arguments_span());
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/unit.rs | crates/nu-protocol/src/ast/unit.rs | use crate::{Filesize, FilesizeUnit, IntoValue, ShellError, Span, Value};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
use thiserror::Error;
pub const SUPPORTED_DURATION_UNITS: [&str; 9] =
["ns", "us", "Β΅s", "ms", "sec", "min", "hr", "day", "wk"];
/// The error returned when failing to parse a [`Unit`].
///
/// This occurs when the string being parsed does not exactly match the name of one of the
/// enum cases in [`Unit`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, Error)]
pub struct ParseUnitError(());
impl fmt::Display for ParseUnitError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "invalid file size or duration unit")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Unit {
Filesize(FilesizeUnit),
// Duration units
Nanosecond,
Microsecond,
Millisecond,
Second,
Minute,
Hour,
Day,
Week,
}
// TODO: something like `Filesize::from_unit` in the future?
fn duration_mul_and_check(size: i64, factor: i64, span: Span) -> Result<Value, ShellError> {
match size.checked_mul(factor) {
Some(val) => Ok(Value::duration(val, span)),
None => Err(ShellError::GenericError {
error: "duration too large".into(),
msg: "duration too large".into(),
span: Some(span),
help: None,
inner: vec![],
}),
}
}
impl Unit {
pub fn build_value(self, size: i64, span: Span) -> Result<Value, ShellError> {
match self {
Unit::Filesize(unit) => {
if let Some(filesize) = Filesize::from_unit(size, unit) {
Ok(filesize.into_value(span))
} else {
Err(ShellError::GenericError {
error: "filesize too large".into(),
msg: "filesize too large".into(),
span: Some(span),
help: None,
inner: vec![],
})
}
}
Unit::Nanosecond => Ok(Value::duration(size, span)),
Unit::Microsecond => duration_mul_and_check(size, 1000, span),
Unit::Millisecond => duration_mul_and_check(size, 1000 * 1000, span),
Unit::Second => duration_mul_and_check(size, 1000 * 1000 * 1000, span),
Unit::Minute => duration_mul_and_check(size, 1000 * 1000 * 1000 * 60, span),
Unit::Hour => duration_mul_and_check(size, 1000 * 1000 * 1000 * 60 * 60, span),
Unit::Day => duration_mul_and_check(size, 1000 * 1000 * 1000 * 60 * 60 * 24, span),
Unit::Week => duration_mul_and_check(size, 1000 * 1000 * 1000 * 60 * 60 * 24 * 7, span),
}
}
/// Returns the symbol [`str`] for a [`Unit`].
///
/// The returned string is the same exact string needed for a successful call to
/// [`parse`](str::parse) for a [`Unit`].
///
/// # Examples
/// ```
/// # use nu_protocol::{Unit, FilesizeUnit};
/// assert_eq!(Unit::Nanosecond.as_str(), "ns");
/// assert_eq!(Unit::Filesize(FilesizeUnit::B).as_str(), "B");
/// assert_eq!(Unit::Second.as_str().parse(), Ok(Unit::Second));
/// assert_eq!(Unit::Filesize(FilesizeUnit::KB).as_str().parse(), Ok(Unit::Filesize(FilesizeUnit::KB)));
/// ```
pub const fn as_str(&self) -> &'static str {
match self {
Unit::Filesize(u) => u.as_str(),
Unit::Nanosecond => "ns",
Unit::Microsecond => "us",
Unit::Millisecond => "ms",
Unit::Second => "sec",
Unit::Minute => "min",
Unit::Hour => "hr",
Unit::Day => "day",
Unit::Week => "wk",
}
}
}
impl FromStr for Unit {
type Err = ParseUnitError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Ok(filesize_unit) = FilesizeUnit::from_str(s) {
return Ok(Unit::Filesize(filesize_unit));
};
match s {
"ns" => Ok(Unit::Nanosecond),
"us" | "Β΅s" => Ok(Unit::Microsecond),
"ms" => Ok(Unit::Millisecond),
"sec" => Ok(Unit::Second),
"min" => Ok(Unit::Minute),
"hr" => Ok(Unit::Hour),
"day" => Ok(Unit::Day),
"wk" => Ok(Unit::Week),
_ => Err(ParseUnitError(())),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/import_pattern.rs | crates/nu-protocol/src/ast/import_pattern.rs | use serde::{Deserialize, Serialize};
use crate::{ModuleId, Span, VarId};
use std::collections::HashSet;
/// possible patterns after the first module level in an [`ImportPattern`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ImportPatternMember {
/// Wildcard import of items
Glob { span: Span },
/// single specific module or item
Name { name: Vec<u8>, span: Span },
/// list of items
List { names: Vec<(Vec<u8>, Span)> },
}
impl ImportPatternMember {
pub fn span(&self) -> Span {
match self {
ImportPatternMember::Glob { span } | ImportPatternMember::Name { span, .. } => *span,
ImportPatternMember::List { names } => {
let first = names
.first()
.map(|&(_, span)| span)
.unwrap_or(Span::unknown());
let last = names
.last()
.map(|&(_, span)| span)
.unwrap_or(Span::unknown());
Span::append(first, last)
}
}
}
}
/// The first item of a `use` statement needs to specify an explicit module
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportPatternHead {
pub name: Vec<u8>,
pub id: Option<ModuleId>,
pub span: Span,
}
/// The pattern specifying modules in a `use` statement
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportPattern {
pub head: ImportPatternHead,
pub members: Vec<ImportPatternMember>,
// communicate to eval which decls/aliases were hidden during `parse_hide()` so it does not
// interpret these as env var names:
pub hidden: HashSet<Vec<u8>>,
// information for the eval which const values to put into stack as variables
pub constants: Vec<VarId>,
}
impl ImportPattern {
pub fn new() -> Self {
ImportPattern {
head: ImportPatternHead {
name: vec![],
id: None,
span: Span::unknown(),
},
members: vec![],
hidden: HashSet::new(),
constants: vec![],
}
}
pub fn span(&self) -> Span {
Span::append(
self.head.span,
self.members
.last()
.map(ImportPatternMember::span)
.unwrap_or(self.head.span),
)
}
pub fn with_hidden(self, hidden: HashSet<Vec<u8>>) -> Self {
ImportPattern {
head: self.head,
members: self.members,
hidden,
constants: self.constants,
}
}
}
impl Default for ImportPattern {
fn default() -> Self {
Self::new()
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/match_pattern.rs | crates/nu-protocol/src/ast/match_pattern.rs | use super::Expression;
use crate::{Span, Value, VarId};
use serde::{Deserialize, Serialize};
/// AST Node for match arm with optional match guard
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MatchPattern {
pub pattern: Pattern,
pub guard: Option<Box<Expression>>,
pub span: Span,
}
impl MatchPattern {
pub fn variables(&self) -> Vec<VarId> {
self.pattern.variables()
}
}
/// AST Node for pattern matching rules
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Pattern {
/// Destructuring of records
Record(Vec<(String, MatchPattern)>),
/// List destructuring
List(Vec<MatchPattern>),
/// Matching against a literal (from expression result)
// TODO: it would be nice if this didn't depend on AST
// maybe const evaluation can get us to a Value instead?
Expression(Box<Expression>),
/// Matching against a literal (pure value)
Value(Value),
/// binding to a variable
Variable(VarId),
/// the `pattern1 \ pattern2` or-pattern
Or(Vec<MatchPattern>),
/// the `..$foo` pattern
Rest(VarId),
/// the `..` pattern
IgnoreRest,
/// the `_` pattern
IgnoreValue,
/// Failed parsing of a pattern
Garbage,
}
impl Pattern {
pub fn variables(&self) -> Vec<VarId> {
let mut output = vec![];
match self {
Pattern::Record(items) => {
for item in items {
output.append(&mut item.1.variables());
}
}
Pattern::List(items) => {
for item in items {
output.append(&mut item.variables());
}
}
Pattern::Variable(var_id) => output.push(*var_id),
Pattern::Or(patterns) => {
for pattern in patterns {
output.append(&mut pattern.variables());
}
}
Pattern::Rest(var_id) => output.push(*var_id),
Pattern::Expression(_)
| Pattern::Value(_)
| Pattern::IgnoreValue
| Pattern::Garbage
| Pattern::IgnoreRest => {}
}
output
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/table.rs | crates/nu-protocol/src/ast/table.rs | use super::Expression;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Table {
pub columns: Box<[Expression]>,
pub rows: Box<[Box<[Expression]>]>,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/keyword.rs | crates/nu-protocol/src/ast/keyword.rs | use super::Expression;
use crate::Span;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Keyword {
pub keyword: Box<[u8]>,
pub span: Span,
pub expr: Expression,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/block.rs | crates/nu-protocol/src/ast/block.rs | use super::Pipeline;
use crate::{OutDest, Signature, Span, Type, VarId, engine::StateWorkingSet, ir::IrBlock};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Block {
pub signature: Box<Signature>,
pub pipelines: Vec<Pipeline>,
pub captures: Vec<(VarId, Span)>,
pub redirect_env: bool,
/// The block compiled to IR instructions. Not available for subexpressions.
pub ir_block: Option<IrBlock>,
pub span: Option<Span>, // None option encodes no span to avoid using test_span()
}
impl Block {
pub fn len(&self) -> usize {
self.pipelines.len()
}
pub fn is_empty(&self) -> bool {
self.pipelines.is_empty()
}
pub fn pipe_redirection(
&self,
working_set: &StateWorkingSet,
) -> (Option<OutDest>, Option<OutDest>) {
if let Some(first) = self.pipelines.first() {
first.pipe_redirection(working_set)
} else {
(None, None)
}
}
}
impl Default for Block {
fn default() -> Self {
Self::new()
}
}
impl Block {
pub fn new() -> Self {
Self {
signature: Box::new(Signature::new("")),
pipelines: vec![],
captures: vec![],
redirect_env: false,
ir_block: None,
span: None,
}
}
pub fn new_with_capacity(capacity: usize) -> Self {
Self {
signature: Box::new(Signature::new("")),
pipelines: Vec::with_capacity(capacity),
captures: vec![],
redirect_env: false,
ir_block: None,
span: None,
}
}
pub fn output_type(&self) -> Type {
if let Some(last) = self.pipelines.last() {
if let Some(last) = last.elements.last() {
if last.redirection.is_some() {
Type::Any
} else {
last.expr.ty.clone()
}
} else {
Type::Nothing
}
} else {
Type::Nothing
}
}
/// Replace any `$in` variables in the initial element of pipelines within the block
pub fn replace_in_variable(
&mut self,
working_set: &mut StateWorkingSet<'_>,
new_var_id: VarId,
) {
for pipeline in self.pipelines.iter_mut() {
if let Some(element) = pipeline.elements.first_mut() {
element.replace_in_variable(working_set, new_var_id);
}
}
}
}
impl<T> From<T> for Block
where
T: Iterator<Item = Pipeline>,
{
fn from(pipelines: T) -> Self {
Self {
signature: Box::new(Signature::new("")),
pipelines: pipelines.collect(),
captures: vec![],
redirect_env: false,
ir_block: None,
span: None,
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/expression.rs | crates/nu-protocol/src/ast/expression.rs | use crate::{
BlockId, GetSpan, IN_VARIABLE_ID, Signature, Span, SpanId, Type, VarId,
ast::{Argument, Block, Expr, ExternalArgument, ImportPattern, MatchPattern, RecordItem},
engine::StateWorkingSet,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use super::ListItem;
/// Wrapper around [`Expr`]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Expression {
pub expr: Expr,
pub span: Span,
pub span_id: SpanId,
pub ty: Type,
}
impl Expression {
pub fn garbage(working_set: &mut StateWorkingSet, span: Span) -> Expression {
let span_id = working_set.add_span(span);
Expression {
expr: Expr::Garbage,
span,
span_id,
ty: Type::Any,
}
}
pub fn precedence(&self) -> u8 {
match &self.expr {
Expr::Operator(operator) => operator.precedence(),
_ => 0,
}
}
pub fn as_block(&self) -> Option<BlockId> {
match self.expr {
Expr::Block(block_id) => Some(block_id),
Expr::Closure(block_id) => Some(block_id),
_ => None,
}
}
pub fn as_row_condition_block(&self) -> Option<BlockId> {
match self.expr {
Expr::RowCondition(block_id) => Some(block_id),
_ => None,
}
}
pub fn as_match_block(&self) -> Option<&[(MatchPattern, Expression)]> {
match &self.expr {
Expr::MatchBlock(matches) => Some(matches),
_ => None,
}
}
pub fn as_signature(&self) -> Option<Box<Signature>> {
match &self.expr {
Expr::Signature(sig) => Some(sig.clone()),
_ => None,
}
}
pub fn as_keyword(&self) -> Option<&Expression> {
match &self.expr {
Expr::Keyword(kw) => Some(&kw.expr),
_ => None,
}
}
pub fn as_var(&self) -> Option<VarId> {
match self.expr {
Expr::Var(var_id) => Some(var_id),
Expr::VarDecl(var_id) => Some(var_id),
_ => None,
}
}
pub fn as_string(&self) -> Option<String> {
match &self.expr {
Expr::String(string) => Some(string.clone()),
_ => None,
}
}
pub fn as_filepath(&self) -> Option<(String, bool)> {
match &self.expr {
Expr::Filepath(string, quoted) => Some((string.clone(), *quoted)),
_ => None,
}
}
pub fn as_import_pattern(&self) -> Option<ImportPattern> {
match &self.expr {
Expr::ImportPattern(pattern) => Some(*pattern.clone()),
_ => None,
}
}
pub fn has_in_variable(&self, working_set: &StateWorkingSet) -> bool {
match &self.expr {
Expr::AttributeBlock(ab) => ab.item.has_in_variable(working_set),
Expr::BinaryOp(left, _, right) => {
left.has_in_variable(working_set) || right.has_in_variable(working_set)
}
Expr::UnaryNot(expr) => expr.has_in_variable(working_set),
Expr::Block(block_id) | Expr::Closure(block_id) => {
let block = working_set.get_block(*block_id);
block
.captures
.iter()
.any(|(var_id, _)| var_id == &IN_VARIABLE_ID)
|| block
.pipelines
.iter()
.flat_map(|pipeline| pipeline.elements.first())
.any(|element| element.has_in_variable(working_set))
}
Expr::Binary(_) => false,
Expr::Bool(_) => false,
Expr::Call(call) => {
for arg in &call.arguments {
match arg {
Argument::Positional(expr)
| Argument::Unknown(expr)
| Argument::Spread(expr) => {
if expr.has_in_variable(working_set) {
return true;
}
}
Argument::Named(named) => {
if let Some(expr) = &named.2
&& expr.has_in_variable(working_set)
{
return true;
}
}
}
}
false
}
Expr::CellPath(_) => false,
Expr::DateTime(_) => false,
Expr::ExternalCall(head, args) => {
if head.has_in_variable(working_set) {
return true;
}
for ExternalArgument::Regular(expr) | ExternalArgument::Spread(expr) in
args.as_ref()
{
if expr.has_in_variable(working_set) {
return true;
}
}
false
}
Expr::ImportPattern(_) => false,
Expr::Overlay(_) => false,
Expr::Filepath(_, _) => false,
Expr::Directory(_, _) => false,
Expr::Float(_) => false,
Expr::FullCellPath(full_cell_path) => {
if full_cell_path.head.has_in_variable(working_set) {
return true;
}
false
}
Expr::Garbage => false,
Expr::Nothing => false,
Expr::GlobPattern(_, _) => false,
Expr::Int(_) => false,
Expr::Keyword(kw) => kw.expr.has_in_variable(working_set),
Expr::List(list) => {
for item in list {
if item.expr().has_in_variable(working_set) {
return true;
}
}
false
}
Expr::StringInterpolation(items) | Expr::GlobInterpolation(items, _) => {
for i in items {
if i.has_in_variable(working_set) {
return true;
}
}
false
}
Expr::Operator(_) => false,
Expr::MatchBlock(_) => false,
Expr::Range(range) => {
if let Some(left) = &range.from
&& left.has_in_variable(working_set)
{
return true;
}
if let Some(middle) = &range.next
&& middle.has_in_variable(working_set)
{
return true;
}
if let Some(right) = &range.to
&& right.has_in_variable(working_set)
{
return true;
}
false
}
Expr::Record(items) => {
for item in items {
match item {
RecordItem::Pair(field_name, field_value) => {
if field_name.has_in_variable(working_set) {
return true;
}
if field_value.has_in_variable(working_set) {
return true;
}
}
RecordItem::Spread(_, record) => {
if record.has_in_variable(working_set) {
return true;
}
}
}
}
false
}
Expr::Signature(_) => false,
Expr::String(_) => false,
Expr::RawString(_) => false,
// A `$in` variable found within a `Collect` is local, as it's already been wrapped
// This is probably unlikely to happen anyway - the expressions are wrapped depth-first
Expr::Collect(_, _) => false,
Expr::RowCondition(block_id) | Expr::Subexpression(block_id) => {
let block = working_set.get_block(*block_id);
if let Some(pipeline) = block.pipelines.first() {
if let Some(expr) = pipeline.elements.first() {
expr.has_in_variable(working_set)
} else {
false
}
} else {
false
}
}
Expr::Table(table) => {
for header in table.columns.as_ref() {
if header.has_in_variable(working_set) {
return true;
}
}
for row in table.rows.as_ref() {
for cell in row.iter() {
if cell.has_in_variable(working_set) {
return true;
}
}
}
false
}
Expr::ValueWithUnit(value) => value.expr.has_in_variable(working_set),
Expr::Var(var_id) => *var_id == IN_VARIABLE_ID,
Expr::VarDecl(_) => false,
}
}
pub fn replace_span(
&mut self,
working_set: &mut StateWorkingSet,
replaced: Span,
new_span: Span,
) {
if replaced.contains_span(self.span) {
self.span = new_span;
}
match &mut self.expr {
Expr::AttributeBlock(ab) => ab.item.replace_span(working_set, replaced, new_span),
Expr::BinaryOp(left, _, right) => {
left.replace_span(working_set, replaced, new_span);
right.replace_span(working_set, replaced, new_span);
}
Expr::UnaryNot(expr) => {
expr.replace_span(working_set, replaced, new_span);
}
Expr::Block(block_id) => {
// We are cloning the Block itself, rather than the Arc around it.
let mut block = Block::clone(working_set.get_block(*block_id));
for pipeline in block.pipelines.iter_mut() {
for element in pipeline.elements.iter_mut() {
element.replace_span(working_set, replaced, new_span)
}
}
*block_id = working_set.add_block(Arc::new(block));
}
Expr::Closure(block_id) => {
let mut block = (**working_set.get_block(*block_id)).clone();
for pipeline in block.pipelines.iter_mut() {
for element in pipeline.elements.iter_mut() {
element.replace_span(working_set, replaced, new_span)
}
}
*block_id = working_set.add_block(Arc::new(block));
}
Expr::Binary(_) => {}
Expr::Bool(_) => {}
Expr::Call(call) => {
if replaced.contains_span(call.head) {
call.head = new_span;
}
for arg in call.arguments.iter_mut() {
match arg {
Argument::Positional(expr)
| Argument::Unknown(expr)
| Argument::Spread(expr) => {
expr.replace_span(working_set, replaced, new_span);
}
Argument::Named(named) => {
if let Some(expr) = &mut named.2 {
expr.replace_span(working_set, replaced, new_span);
}
}
}
}
}
Expr::CellPath(_) => {}
Expr::DateTime(_) => {}
Expr::ExternalCall(head, args) => {
head.replace_span(working_set, replaced, new_span);
for ExternalArgument::Regular(expr) | ExternalArgument::Spread(expr) in
args.as_mut()
{
expr.replace_span(working_set, replaced, new_span);
}
}
Expr::Filepath(_, _) => {}
Expr::Directory(_, _) => {}
Expr::Float(_) => {}
Expr::FullCellPath(full_cell_path) => {
full_cell_path
.head
.replace_span(working_set, replaced, new_span);
}
Expr::ImportPattern(_) => {}
Expr::Overlay(_) => {}
Expr::Garbage => {}
Expr::Nothing => {}
Expr::GlobPattern(_, _) => {}
Expr::MatchBlock(_) => {}
Expr::Int(_) => {}
Expr::Keyword(kw) => kw.expr.replace_span(working_set, replaced, new_span),
Expr::List(list) => {
for item in list {
item.expr_mut()
.replace_span(working_set, replaced, new_span);
}
}
Expr::Operator(_) => {}
Expr::Range(range) => {
if let Some(left) = &mut range.from {
left.replace_span(working_set, replaced, new_span)
}
if let Some(middle) = &mut range.next {
middle.replace_span(working_set, replaced, new_span)
}
if let Some(right) = &mut range.to {
right.replace_span(working_set, replaced, new_span)
}
}
Expr::Record(items) => {
for item in items {
match item {
RecordItem::Pair(field_name, field_value) => {
field_name.replace_span(working_set, replaced, new_span);
field_value.replace_span(working_set, replaced, new_span);
}
RecordItem::Spread(_, record) => {
record.replace_span(working_set, replaced, new_span);
}
}
}
}
Expr::Signature(_) => {}
Expr::String(_) => {}
Expr::RawString(_) => {}
Expr::StringInterpolation(items) | Expr::GlobInterpolation(items, _) => {
for i in items {
i.replace_span(working_set, replaced, new_span)
}
}
Expr::Collect(_, expr) => expr.replace_span(working_set, replaced, new_span),
Expr::RowCondition(block_id) | Expr::Subexpression(block_id) => {
let mut block = (**working_set.get_block(*block_id)).clone();
for pipeline in block.pipelines.iter_mut() {
for element in pipeline.elements.iter_mut() {
element.replace_span(working_set, replaced, new_span)
}
}
*block_id = working_set.add_block(Arc::new(block));
}
Expr::Table(table) => {
for header in table.columns.as_mut() {
header.replace_span(working_set, replaced, new_span)
}
for row in table.rows.as_mut() {
for cell in row.iter_mut() {
cell.replace_span(working_set, replaced, new_span)
}
}
}
Expr::ValueWithUnit(value) => value.expr.replace_span(working_set, replaced, new_span),
Expr::Var(_) => {}
Expr::VarDecl(_) => {}
}
}
pub fn replace_in_variable(&mut self, working_set: &mut StateWorkingSet, new_var_id: VarId) {
match &mut self.expr {
Expr::AttributeBlock(ab) => ab.item.replace_in_variable(working_set, new_var_id),
Expr::Bool(_) => {}
Expr::Int(_) => {}
Expr::Float(_) => {}
Expr::Binary(_) => {}
Expr::Range(range) => {
if let Some(from) = &mut range.from {
from.replace_in_variable(working_set, new_var_id);
}
if let Some(next) = &mut range.next {
next.replace_in_variable(working_set, new_var_id);
}
if let Some(to) = &mut range.to {
to.replace_in_variable(working_set, new_var_id);
}
}
Expr::Var(var_id) | Expr::VarDecl(var_id) => {
if *var_id == IN_VARIABLE_ID {
*var_id = new_var_id;
}
}
Expr::Call(call) => {
for arg in call.arguments.iter_mut() {
match arg {
Argument::Positional(expr)
| Argument::Unknown(expr)
| Argument::Named((_, _, Some(expr)))
| Argument::Spread(expr) => {
expr.replace_in_variable(working_set, new_var_id)
}
Argument::Named((_, _, None)) => {}
}
}
for expr in call.parser_info.values_mut() {
expr.replace_in_variable(working_set, new_var_id)
}
}
Expr::ExternalCall(head, args) => {
head.replace_in_variable(working_set, new_var_id);
for arg in args.iter_mut() {
match arg {
ExternalArgument::Regular(expr) | ExternalArgument::Spread(expr) => {
expr.replace_in_variable(working_set, new_var_id)
}
}
}
}
Expr::Operator(_) => {}
// `$in` in `Collect` has already been handled, so we don't need to check further
Expr::Collect(_, _) => {}
Expr::Block(block_id)
| Expr::Closure(block_id)
| Expr::RowCondition(block_id)
| Expr::Subexpression(block_id) => {
let mut block = Block::clone(working_set.get_block(*block_id));
block.replace_in_variable(working_set, new_var_id);
*working_set.get_block_mut(*block_id) = block;
}
Expr::UnaryNot(expr) => {
expr.replace_in_variable(working_set, new_var_id);
}
Expr::BinaryOp(lhs, op, rhs) => {
for expr in [lhs, op, rhs] {
expr.replace_in_variable(working_set, new_var_id);
}
}
Expr::MatchBlock(match_patterns) => {
for (_, expr) in match_patterns.iter_mut() {
expr.replace_in_variable(working_set, new_var_id);
}
}
Expr::List(items) => {
for item in items.iter_mut() {
match item {
ListItem::Item(expr) | ListItem::Spread(_, expr) => {
expr.replace_in_variable(working_set, new_var_id)
}
}
}
}
Expr::Table(table) => {
for col_expr in table.columns.iter_mut() {
col_expr.replace_in_variable(working_set, new_var_id);
}
for row in table.rows.iter_mut() {
for row_expr in row.iter_mut() {
row_expr.replace_in_variable(working_set, new_var_id);
}
}
}
Expr::Record(items) => {
for item in items.iter_mut() {
match item {
RecordItem::Pair(key, val) => {
key.replace_in_variable(working_set, new_var_id);
val.replace_in_variable(working_set, new_var_id);
}
RecordItem::Spread(_, expr) => {
expr.replace_in_variable(working_set, new_var_id)
}
}
}
}
Expr::Keyword(kw) => kw.expr.replace_in_variable(working_set, new_var_id),
Expr::ValueWithUnit(value_with_unit) => value_with_unit
.expr
.replace_in_variable(working_set, new_var_id),
Expr::DateTime(_) => {}
Expr::Filepath(_, _) => {}
Expr::Directory(_, _) => {}
Expr::GlobPattern(_, _) => {}
Expr::String(_) => {}
Expr::RawString(_) => {}
Expr::CellPath(_) => {}
Expr::FullCellPath(full_cell_path) => {
full_cell_path
.head
.replace_in_variable(working_set, new_var_id);
}
Expr::ImportPattern(_) => {}
Expr::Overlay(_) => {}
Expr::Signature(_) => {}
Expr::StringInterpolation(exprs) | Expr::GlobInterpolation(exprs, _) => {
for expr in exprs.iter_mut() {
expr.replace_in_variable(working_set, new_var_id);
}
}
Expr::Nothing => {}
Expr::Garbage => {}
}
}
pub fn new(working_set: &mut StateWorkingSet, expr: Expr, span: Span, ty: Type) -> Expression {
let span_id = working_set.add_span(span);
Expression {
expr,
span,
span_id,
ty,
}
}
pub fn new_existing(expr: Expr, span: Span, span_id: SpanId, ty: Type) -> Expression {
Expression {
expr,
span,
span_id,
ty,
}
}
pub fn new_unknown(expr: Expr, span: Span, ty: Type) -> Expression {
Expression {
expr,
span,
span_id: SpanId::new(0),
ty,
}
}
pub fn with_span_id(self, span_id: SpanId) -> Expression {
Expression {
expr: self.expr,
span: self.span,
span_id,
ty: self.ty,
}
}
pub fn span(&self, state: &impl GetSpan) -> Span {
state.get_span(self.span_id)
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/operator.rs | crates/nu-protocol/src/ast/operator.rs | use super::{Expr, Expression};
use crate::{ShellError, Span};
use serde::{Deserialize, Serialize};
use std::fmt;
use strum_macros::{EnumIter, EnumMessage};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
pub enum Comparison {
#[strum(message = "Equal to")]
Equal,
#[strum(message = "Not equal to")]
NotEqual,
#[strum(message = "Less than")]
LessThan,
#[strum(message = "Greater than")]
GreaterThan,
#[strum(message = "Less than or equal to")]
LessThanOrEqual,
#[strum(message = "Greater than or equal to")]
GreaterThanOrEqual,
#[strum(message = "Contains regex match")]
RegexMatch,
#[strum(message = "Does not contain regex match")]
NotRegexMatch,
#[strum(message = "Is a member of (doesn't use regex)")]
In,
#[strum(message = "Is not a member of (doesn't use regex)")]
NotIn,
#[strum(message = "Contains a value of (doesn't use regex)")]
Has,
#[strum(message = "Does not contain a value of (doesn't use regex)")]
NotHas,
#[strum(message = "Starts with")]
StartsWith,
#[strum(message = "Does not start with")]
NotStartsWith,
#[strum(message = "Ends with")]
EndsWith,
#[strum(message = "Does not end with")]
NotEndsWith,
}
impl Comparison {
pub const fn as_str(&self) -> &'static str {
match self {
Self::Equal => "==",
Self::NotEqual => "!=",
Self::LessThan => "<",
Self::GreaterThan => ">",
Self::LessThanOrEqual => "<=",
Self::GreaterThanOrEqual => ">=",
Self::RegexMatch => "=~",
Self::NotRegexMatch => "!~",
Self::In => "in",
Self::NotIn => "not-in",
Self::Has => "has",
Self::NotHas => "not-has",
Self::StartsWith => "starts-with",
Self::NotStartsWith => "not-starts-with",
Self::EndsWith => "ends-with",
Self::NotEndsWith => "not-ends-with",
}
}
}
impl AsRef<str> for Comparison {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for Comparison {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
pub enum Math {
#[strum(message = "Add (Plus)")]
Add,
#[strum(message = "Subtract (Minus)")]
Subtract,
#[strum(message = "Multiply")]
Multiply,
#[strum(message = "Divide")]
Divide,
#[strum(message = "Floor division")]
FloorDivide,
#[strum(message = "Floor division remainder (Modulo)")]
Modulo,
#[strum(message = "Power of")]
Pow,
#[strum(message = "Concatenates two lists, two strings, or two binary values")]
Concatenate,
}
impl Math {
pub const fn as_str(&self) -> &'static str {
match self {
Self::Add => "+",
Self::Subtract => "-",
Self::Multiply => "*",
Self::Divide => "/",
Self::FloorDivide => "//",
Self::Modulo => "mod",
Self::Pow => "**",
Self::Concatenate => "++",
}
}
}
impl AsRef<str> for Math {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for Math {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
pub enum Boolean {
#[strum(message = "Logical OR (short-circuiting)")]
Or,
#[strum(message = "Logical XOR")]
Xor,
#[strum(message = "Logical AND (short-circuiting)")]
And,
}
impl Boolean {
pub const fn as_str(&self) -> &'static str {
match self {
Self::Or => "or",
Self::Xor => "xor",
Self::And => "and",
}
}
}
impl AsRef<str> for Boolean {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for Boolean {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
pub enum Bits {
#[strum(message = "Bitwise OR")]
BitOr,
#[strum(message = "Bitwise exclusive OR")]
BitXor,
#[strum(message = "Bitwise AND")]
BitAnd,
#[strum(message = "Bitwise shift left")]
ShiftLeft,
#[strum(message = "Bitwise shift right")]
ShiftRight,
}
impl AsRef<str> for Bits {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Bits {
pub const fn as_str(&self) -> &'static str {
match self {
Self::BitOr => "bit-or",
Self::BitXor => "bit-xor",
Self::BitAnd => "bit-and",
Self::ShiftLeft => "bit-shl",
Self::ShiftRight => "bit-shr",
}
}
}
impl fmt::Display for Bits {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumIter, EnumMessage)]
pub enum Assignment {
#[strum(message = "Assigns a value to a variable.")]
Assign,
#[strum(message = "Adds a value to a variable.")]
AddAssign,
#[strum(message = "Subtracts a value from a variable.")]
SubtractAssign,
#[strum(message = "Multiplies a variable by a value")]
MultiplyAssign,
#[strum(message = "Divides a variable by a value.")]
DivideAssign,
#[strum(message = "Concatenates a variable with a list, string or binary.")]
ConcatenateAssign,
}
impl AsRef<str> for Assignment {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Assignment {
pub const fn as_str(&self) -> &'static str {
match self {
Self::Assign => "=",
Self::AddAssign => "+=",
Self::SubtractAssign => "-=",
Self::MultiplyAssign => "*=",
Self::DivideAssign => "/=",
Self::ConcatenateAssign => "++=",
}
}
}
impl fmt::Display for Assignment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Operator {
Comparison(Comparison),
Math(Math),
Boolean(Boolean),
Bits(Bits),
Assignment(Assignment),
}
impl Operator {
pub const fn as_str(&self) -> &'static str {
match self {
Self::Comparison(comparison) => comparison.as_str(),
Self::Math(math) => math.as_str(),
Self::Boolean(boolean) => boolean.as_str(),
Self::Bits(bits) => bits.as_str(),
Self::Assignment(assignment) => assignment.as_str(),
}
}
pub const fn precedence(&self) -> u8 {
match self {
Self::Math(Math::Pow) => 100,
Self::Math(Math::Multiply)
| Self::Math(Math::Divide)
| Self::Math(Math::Modulo)
| Self::Math(Math::FloorDivide) => 95,
Self::Math(Math::Add) | Self::Math(Math::Subtract) => 90,
Self::Bits(Bits::ShiftLeft) | Self::Bits(Bits::ShiftRight) => 85,
Self::Comparison(Comparison::NotRegexMatch)
| Self::Comparison(Comparison::RegexMatch)
| Self::Comparison(Comparison::StartsWith)
| Self::Comparison(Comparison::NotStartsWith)
| Self::Comparison(Comparison::EndsWith)
| Self::Comparison(Comparison::NotEndsWith)
| Self::Comparison(Comparison::LessThan)
| Self::Comparison(Comparison::LessThanOrEqual)
| Self::Comparison(Comparison::GreaterThan)
| Self::Comparison(Comparison::GreaterThanOrEqual)
| Self::Comparison(Comparison::Equal)
| Self::Comparison(Comparison::NotEqual)
| Self::Comparison(Comparison::In)
| Self::Comparison(Comparison::NotIn)
| Self::Comparison(Comparison::Has)
| Self::Comparison(Comparison::NotHas)
| Self::Math(Math::Concatenate) => 80,
Self::Bits(Bits::BitAnd) => 75,
Self::Bits(Bits::BitXor) => 70,
Self::Bits(Bits::BitOr) => 60,
Self::Boolean(Boolean::And) => 50,
Self::Boolean(Boolean::Xor) => 45,
Self::Boolean(Boolean::Or) => 40,
Self::Assignment(_) => 10,
}
}
}
impl fmt::Display for Operator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, EnumIter)]
pub enum RangeInclusion {
Inclusive,
RightExclusive,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RangeOperator {
pub inclusion: RangeInclusion,
pub span: Span,
pub next_op_span: Span,
}
impl fmt::Display for RangeOperator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.inclusion {
RangeInclusion::Inclusive => write!(f, ".."),
RangeInclusion::RightExclusive => write!(f, "..<"),
}
}
}
pub fn eval_operator(op: &Expression) -> Result<Operator, ShellError> {
match op {
Expression {
expr: Expr::Operator(operator),
..
} => Ok(*operator),
Expression { span, expr, .. } => Err(ShellError::UnknownOperator {
op_token: format!("{expr:?}"),
span: *span,
}),
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/mod.rs | crates/nu-protocol/src/ast/mod.rs | //! Types representing parsed Nushell code (the Abstract Syntax Tree)
mod attribute;
mod block;
mod call;
mod cell_path;
mod expr;
mod expression;
mod import_pattern;
mod keyword;
mod match_pattern;
mod operator;
mod pipeline;
mod range;
mod table;
mod traverse;
pub mod unit;
mod value_with_unit;
pub use attribute::*;
pub use block::*;
pub use call::*;
pub use cell_path::*;
pub use expr::*;
pub use expression::*;
pub use import_pattern::*;
pub use keyword::*;
pub use match_pattern::*;
pub use operator::*;
pub use pipeline::*;
pub use range::*;
pub use table::Table;
pub use traverse::*;
pub use unit::*;
pub use value_with_unit::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/traverse.rs | crates/nu-protocol/src/ast/traverse.rs | use crate::engine::StateWorkingSet;
use super::{
Block, Expr, Expression, ListItem, MatchPattern, Pattern, PipelineRedirection, RecordItem,
};
/// Result of find_map closure
#[derive(Default)]
pub enum FindMapResult<T> {
Found(T),
#[default]
Continue,
Stop,
}
/// Trait for traversing the AST
pub trait Traverse {
/// Generic function that do flat_map on an AST node.
/// Concatenates all recursive results on sub-expressions
/// into the `results` accumulator.
///
/// # Arguments
/// * `f` - function that generates leaf elements
/// * `results` - accumulator
fn flat_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F, results: &mut Vec<T>)
where
F: Fn(&'a Expression) -> Vec<T>;
/// Generic function that do find_map on an AST node.
/// Return the first result found by applying `f` on sub-expressions.
///
/// # Arguments
/// * `f` - function that overrides the default behavior
fn find_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F) -> Option<T>
where
F: Fn(&'a Expression) -> FindMapResult<T>;
}
impl Traverse for Block {
fn flat_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F, results: &mut Vec<T>)
where
F: Fn(&'a Expression) -> Vec<T>,
{
for pipeline in self.pipelines.iter() {
for element in pipeline.elements.iter() {
element.expr.flat_map(working_set, f, results);
if let Some(redir) = &element.redirection {
redir.flat_map(working_set, f, results);
};
}
}
}
fn find_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F) -> Option<T>
where
F: Fn(&'a Expression) -> FindMapResult<T>,
{
self.pipelines.iter().find_map(|pipeline| {
pipeline.elements.iter().find_map(|element| {
element.expr.find_map(working_set, f).or(element
.redirection
.as_ref()
.and_then(|redir| redir.find_map(working_set, f)))
})
})
}
}
impl Traverse for PipelineRedirection {
fn flat_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F, results: &mut Vec<T>)
where
F: Fn(&'a Expression) -> Vec<T>,
{
let mut recur = |expr: &'a Expression| expr.flat_map(working_set, f, results);
match self {
PipelineRedirection::Single { target, .. } => target.expr().map(recur),
PipelineRedirection::Separate { out, err } => {
out.expr().map(&mut recur);
err.expr().map(&mut recur)
}
};
}
fn find_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F) -> Option<T>
where
F: Fn(&'a Expression) -> FindMapResult<T>,
{
let recur = |expr: &'a Expression| expr.find_map(working_set, f);
match self {
PipelineRedirection::Single { target, .. } => target.expr().and_then(recur),
PipelineRedirection::Separate { out, err } => {
[out, err].iter().filter_map(|t| t.expr()).find_map(recur)
}
}
}
}
impl Traverse for Expression {
fn flat_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F, results: &mut Vec<T>)
where
F: Fn(&'a Expression) -> Vec<T>,
{
// leaf elements generated by `f` for this expression
results.extend(f(self));
let mut recur = |expr: &'a Expression| expr.flat_map(working_set, f, results);
match &self.expr {
Expr::RowCondition(block_id)
| Expr::Subexpression(block_id)
| Expr::Block(block_id)
| Expr::Closure(block_id) => {
let block = working_set.get_block(block_id.to_owned());
block.flat_map(working_set, f, results)
}
Expr::Range(range) => {
for sub_expr in [&range.from, &range.next, &range.to].into_iter().flatten() {
recur(sub_expr);
}
}
Expr::Call(call) => {
for arg in &call.arguments {
if let Some(sub_expr) = arg.expr() {
recur(sub_expr);
}
}
}
Expr::ExternalCall(head, args) => {
recur(head.as_ref());
for arg in args {
recur(arg.expr());
}
}
Expr::UnaryNot(expr) | Expr::Collect(_, expr) => recur(expr.as_ref()),
Expr::BinaryOp(lhs, op, rhs) => {
recur(lhs);
recur(op);
recur(rhs);
}
Expr::MatchBlock(matches) => {
for (pattern, expr) in matches {
pattern.flat_map(working_set, f, results);
expr.flat_map(working_set, f, results);
}
}
Expr::List(items) => {
for item in items {
match item {
ListItem::Item(expr) | ListItem::Spread(_, expr) => recur(expr),
}
}
}
Expr::Record(items) => {
for item in items {
match item {
RecordItem::Spread(_, expr) => recur(expr),
RecordItem::Pair(key, val) => {
recur(key);
recur(val);
}
}
}
}
Expr::Table(table) => {
for column in &table.columns {
recur(column);
}
for row in &table.rows {
for item in row {
recur(item);
}
}
}
Expr::ValueWithUnit(vu) => recur(&vu.expr),
Expr::FullCellPath(fcp) => recur(&fcp.head),
Expr::Keyword(kw) => recur(&kw.expr),
Expr::StringInterpolation(vec) | Expr::GlobInterpolation(vec, _) => {
for item in vec {
recur(item);
}
}
Expr::AttributeBlock(ab) => {
for attr in &ab.attributes {
recur(&attr.expr);
}
recur(&ab.item);
}
_ => (),
};
}
fn find_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F) -> Option<T>
where
F: Fn(&'a Expression) -> FindMapResult<T>,
{
// behavior overridden by f
match f(self) {
FindMapResult::Found(t) => Some(t),
FindMapResult::Stop => None,
FindMapResult::Continue => {
let recur = |expr: &'a Expression| expr.find_map(working_set, f);
match &self.expr {
Expr::RowCondition(block_id)
| Expr::Subexpression(block_id)
| Expr::Block(block_id)
| Expr::Closure(block_id) => {
let block = working_set.get_block(*block_id);
block.find_map(working_set, f)
}
Expr::Range(range) => [&range.from, &range.next, &range.to]
.iter()
.find_map(|e| e.as_ref().and_then(recur)),
Expr::Call(call) => call
.arguments
.iter()
.find_map(|arg| arg.expr().and_then(recur)),
Expr::ExternalCall(head, args) => {
recur(head.as_ref()).or(args.iter().find_map(|arg| recur(arg.expr())))
}
Expr::UnaryNot(expr) | Expr::Collect(_, expr) => recur(expr.as_ref()),
Expr::BinaryOp(lhs, op, rhs) => recur(lhs).or(recur(op)).or(recur(rhs)),
Expr::MatchBlock(matches) => matches.iter().find_map(|(pattern, expr)| {
pattern.find_map(working_set, f).or(recur(expr))
}),
Expr::List(items) => items.iter().find_map(|item| match item {
ListItem::Item(expr) | ListItem::Spread(_, expr) => recur(expr),
}),
Expr::Record(items) => items.iter().find_map(|item| match item {
RecordItem::Spread(_, expr) => recur(expr),
RecordItem::Pair(key, val) => [key, val].into_iter().find_map(recur),
}),
Expr::Table(table) => table
.columns
.iter()
.find_map(recur)
.or(table.rows.iter().find_map(|row| row.iter().find_map(recur))),
Expr::ValueWithUnit(vu) => recur(&vu.expr),
Expr::FullCellPath(fcp) => recur(&fcp.head),
Expr::Keyword(kw) => recur(&kw.expr),
Expr::StringInterpolation(vec) | Expr::GlobInterpolation(vec, _) => {
vec.iter().find_map(recur)
}
Expr::AttributeBlock(ab) => ab
.attributes
.iter()
.find_map(|attr| recur(&attr.expr))
.or_else(|| recur(&ab.item)),
_ => None,
}
}
}
}
}
impl Traverse for MatchPattern {
fn flat_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F, results: &mut Vec<T>)
where
F: Fn(&'a Expression) -> Vec<T>,
{
let mut recur_pattern =
|pattern: &'a MatchPattern| pattern.flat_map(working_set, f, results);
match &self.pattern {
Pattern::Expression(expr) => expr.flat_map(working_set, f, results),
Pattern::List(patterns) | Pattern::Or(patterns) => {
for pattern in patterns {
recur_pattern(pattern);
}
}
Pattern::Record(entries) => {
for (_, p) in entries {
recur_pattern(p);
}
}
_ => (),
};
if let Some(g) = self.guard.as_ref() {
g.flat_map(working_set, f, results);
}
}
fn find_map<'a, T, F>(&'a self, working_set: &'a StateWorkingSet, f: &F) -> Option<T>
where
F: Fn(&'a Expression) -> FindMapResult<T>,
{
let recur = |expr: &'a Expression| expr.find_map(working_set, f);
let recur_pattern = |pattern: &'a MatchPattern| pattern.find_map(working_set, f);
match &self.pattern {
Pattern::Expression(expr) => recur(expr),
Pattern::List(patterns) | Pattern::Or(patterns) => {
patterns.iter().find_map(recur_pattern)
}
Pattern::Record(entries) => entries.iter().find_map(|(_, p)| recur_pattern(p)),
_ => None,
}
.or(self.guard.as_ref().and_then(|g| recur(g)))
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/pipeline.rs | crates/nu-protocol/src/ast/pipeline.rs | use crate::{OutDest, Span, VarId, ast::Expression, engine::StateWorkingSet};
use serde::{Deserialize, Serialize};
use std::fmt::Display;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Eq, PartialEq)]
pub enum RedirectionSource {
Stdout,
Stderr,
StdoutAndStderr,
}
impl Display for RedirectionSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
RedirectionSource::Stdout => "stdout",
RedirectionSource::Stderr => "stderr",
RedirectionSource::StdoutAndStderr => "stdout and stderr",
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum RedirectionTarget {
File {
expr: Expression,
append: bool,
span: Span,
},
Pipe {
span: Span,
},
}
impl RedirectionTarget {
pub fn span(&self) -> Span {
match self {
RedirectionTarget::File { span, .. } | RedirectionTarget::Pipe { span } => *span,
}
}
pub fn expr(&self) -> Option<&Expression> {
match self {
RedirectionTarget::File { expr, .. } => Some(expr),
RedirectionTarget::Pipe { .. } => None,
}
}
pub fn has_in_variable(&self, working_set: &StateWorkingSet) -> bool {
self.expr().is_some_and(|e| e.has_in_variable(working_set))
}
pub fn replace_span(
&mut self,
working_set: &mut StateWorkingSet,
replaced: Span,
new_span: Span,
) {
match self {
RedirectionTarget::File { expr, .. } => {
expr.replace_span(working_set, replaced, new_span)
}
RedirectionTarget::Pipe { .. } => {}
}
}
pub fn replace_in_variable(
&mut self,
working_set: &mut StateWorkingSet<'_>,
new_var_id: VarId,
) {
match self {
RedirectionTarget::File { expr, .. } => {
expr.replace_in_variable(working_set, new_var_id)
}
RedirectionTarget::Pipe { .. } => {}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum PipelineRedirection {
Single {
source: RedirectionSource,
target: RedirectionTarget,
},
Separate {
out: RedirectionTarget,
err: RedirectionTarget,
},
}
impl PipelineRedirection {
pub fn replace_in_variable(
&mut self,
working_set: &mut StateWorkingSet<'_>,
new_var_id: VarId,
) {
match self {
PipelineRedirection::Single { source: _, target } => {
target.replace_in_variable(working_set, new_var_id)
}
PipelineRedirection::Separate { out, err } => {
out.replace_in_variable(working_set, new_var_id);
err.replace_in_variable(working_set, new_var_id);
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineElement {
pub pipe: Option<Span>,
pub expr: Expression,
pub redirection: Option<PipelineRedirection>,
}
impl PipelineElement {
pub fn has_in_variable(&self, working_set: &StateWorkingSet) -> bool {
self.expr.has_in_variable(working_set)
|| self.redirection.as_ref().is_some_and(|r| match r {
PipelineRedirection::Single { target, .. } => target.has_in_variable(working_set),
PipelineRedirection::Separate { out, err } => {
out.has_in_variable(working_set) || err.has_in_variable(working_set)
}
})
}
pub fn replace_span(
&mut self,
working_set: &mut StateWorkingSet,
replaced: Span,
new_span: Span,
) {
self.expr.replace_span(working_set, replaced, new_span);
if let Some(expr) = self.redirection.as_mut() {
match expr {
PipelineRedirection::Single { target, .. } => {
target.replace_span(working_set, replaced, new_span)
}
PipelineRedirection::Separate { out, err } => {
out.replace_span(working_set, replaced, new_span);
err.replace_span(working_set, replaced, new_span);
}
}
}
}
pub fn pipe_redirection(
&self,
working_set: &StateWorkingSet,
) -> (Option<OutDest>, Option<OutDest>) {
self.expr.expr.pipe_redirection(working_set)
}
pub fn replace_in_variable(
&mut self,
working_set: &mut StateWorkingSet<'_>,
new_var_id: VarId,
) {
self.expr.replace_in_variable(working_set, new_var_id);
if let Some(redirection) = &mut self.redirection {
redirection.replace_in_variable(working_set, new_var_id);
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Pipeline {
pub elements: Vec<PipelineElement>,
}
impl Default for Pipeline {
fn default() -> Self {
Self::new()
}
}
impl Pipeline {
pub fn new() -> Self {
Self { elements: vec![] }
}
pub fn from_vec(expressions: Vec<Expression>) -> Pipeline {
Self {
elements: expressions
.into_iter()
.enumerate()
.map(|(idx, expr)| PipelineElement {
pipe: if idx == 0 { None } else { Some(expr.span) },
expr,
redirection: None,
})
.collect(),
}
}
pub fn len(&self) -> usize {
self.elements.len()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn pipe_redirection(
&self,
working_set: &StateWorkingSet,
) -> (Option<OutDest>, Option<OutDest>) {
if let Some(first) = self.elements.first() {
first.pipe_redirection(working_set)
} else {
(None, None)
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ast/cell_path.rs | crates/nu-protocol/src/ast/cell_path.rs | use super::Expression;
use crate::{Span, casing::Casing};
use nu_utils::{escape_quote_string, needs_quoting};
use serde::{Deserialize, Serialize};
use std::{cmp::Ordering, fmt::Display};
/// One level of access of a [`CellPath`]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PathMember {
/// Accessing a member by string (i.e. columns of a table or [`Record`](crate::Record))
String {
val: String,
span: Span,
/// If marked as optional don't throw an error if not found but perform default handling
/// (e.g. return `Value::Nothing`)
optional: bool,
/// Affects column lookup
casing: Casing,
},
/// Accessing a member by index (i.e. row of a table or item in a list)
Int {
val: usize,
span: Span,
/// If marked as optional don't throw an error if not found but perform default handling
/// (e.g. return `Value::Nothing`)
optional: bool,
},
}
impl PathMember {
pub fn int(val: usize, optional: bool, span: Span) -> Self {
PathMember::Int {
val,
span,
optional,
}
}
pub fn string(val: String, optional: bool, casing: Casing, span: Span) -> Self {
PathMember::String {
val,
span,
optional,
casing,
}
}
pub fn test_int(val: usize, optional: bool) -> Self {
PathMember::Int {
val,
optional,
span: Span::test_data(),
}
}
pub fn test_string(val: String, optional: bool, casing: Casing) -> Self {
PathMember::String {
val,
optional,
casing,
span: Span::test_data(),
}
}
pub fn make_optional(&mut self) {
match self {
PathMember::String { optional, .. } => *optional = true,
PathMember::Int { optional, .. } => *optional = true,
}
}
pub fn make_insensitive(&mut self) {
match self {
PathMember::String { casing, .. } => *casing = Casing::Insensitive,
PathMember::Int { .. } => {}
}
}
pub fn span(&self) -> Span {
match self {
PathMember::String { span, .. } => *span,
PathMember::Int { span, .. } => *span,
}
}
}
impl PartialEq for PathMember {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(
Self::String {
val: l_val,
optional: l_opt,
..
},
Self::String {
val: r_val,
optional: r_opt,
..
},
) => l_val == r_val && l_opt == r_opt,
(
Self::Int {
val: l_val,
optional: l_opt,
..
},
Self::Int {
val: r_val,
optional: r_opt,
..
},
) => l_val == r_val && l_opt == r_opt,
_ => false,
}
}
}
impl PartialOrd for PathMember {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
match (self, other) {
(
PathMember::String {
val: l_val,
optional: l_opt,
..
},
PathMember::String {
val: r_val,
optional: r_opt,
..
},
) => {
let val_ord = Some(l_val.cmp(r_val));
if let Some(Ordering::Equal) = val_ord {
Some(l_opt.cmp(r_opt))
} else {
val_ord
}
}
(
PathMember::Int {
val: l_val,
optional: l_opt,
..
},
PathMember::Int {
val: r_val,
optional: r_opt,
..
},
) => {
let val_ord = Some(l_val.cmp(r_val));
if let Some(Ordering::Equal) = val_ord {
Some(l_opt.cmp(r_opt))
} else {
val_ord
}
}
(PathMember::Int { .. }, PathMember::String { .. }) => Some(Ordering::Greater),
(PathMember::String { .. }, PathMember::Int { .. }) => Some(Ordering::Less),
}
}
}
/// Represents the potentially nested access to fields/cells of a container type
///
/// In our current implementation for table access the order of row/column is commutative.
/// This limits the number of possible rows to select in one [`CellPath`] to 1 as it could
/// otherwise be ambiguous
///
/// ```nushell
/// col1.0
/// 0.col1
/// col2
/// 42
/// ```
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct CellPath {
pub members: Vec<PathMember>,
}
impl CellPath {
pub fn make_optional(&mut self) {
for member in &mut self.members {
member.make_optional();
}
}
pub fn make_insensitive(&mut self) {
for member in &mut self.members {
member.make_insensitive();
}
}
// Formats the cell-path as a column name, i.e. without quoting and optional markers ('?').
pub fn to_column_name(&self) -> String {
let mut s = String::new();
for member in &self.members {
match member {
PathMember::Int { val, .. } => {
s += &val.to_string();
}
PathMember::String { val, .. } => {
s += val;
}
}
s.push('.');
}
s.pop(); // Easier than checking whether to insert the '.' on every iteration.
s
}
}
impl Display for CellPath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "$")?;
for member in self.members.iter() {
match member {
PathMember::Int { val, optional, .. } => {
let question_mark = if *optional { "?" } else { "" };
write!(f, ".{val}{question_mark}")?
}
PathMember::String {
val,
optional,
casing,
..
} => {
let question_mark = if *optional { "?" } else { "" };
let exclamation_mark = if *casing == Casing::Insensitive {
"!"
} else {
""
};
let val = if needs_quoting(val) {
&escape_quote_string(val)
} else {
val
};
write!(f, ".{val}{exclamation_mark}{question_mark}")?
}
}
}
// Empty cell-paths are `$.` not `$`
if self.members.is_empty() {
write!(f, ".")?;
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FullCellPath {
pub head: Expression,
pub tail: Vec<PathMember>,
}
#[cfg(test)]
mod test {
use super::*;
use std::cmp::Ordering::Greater;
#[test]
fn path_member_partial_ord() {
assert_eq!(
Some(Greater),
PathMember::test_int(5, true).partial_cmp(&PathMember::test_string(
"e".into(),
true,
Casing::Sensitive
))
);
assert_eq!(
Some(Greater),
PathMember::test_int(5, true).partial_cmp(&PathMember::test_int(5, false))
);
assert_eq!(
Some(Greater),
PathMember::test_int(6, true).partial_cmp(&PathMember::test_int(5, true))
);
assert_eq!(
Some(Greater),
PathMember::test_string("e".into(), true, Casing::Sensitive).partial_cmp(
&PathMember::test_string("e".into(), false, Casing::Sensitive)
)
);
assert_eq!(
Some(Greater),
PathMember::test_string("f".into(), true, Casing::Sensitive).partial_cmp(
&PathMember::test_string("e".into(), true, Casing::Sensitive)
)
);
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/debugger/profiler.rs | crates/nu-protocol/src/debugger/profiler.rs | //! Nushell Profiler
//!
//! Profiler implements the Debugger trait and can be used via the `debug profile` command for
//! profiling Nushell code.
use crate::{
PipelineData, PipelineExecutionData, ShellError, Span, Value,
ast::{Block, Expr, PipelineElement},
debugger::Debugger,
engine::EngineState,
ir::IrBlock,
record,
};
use std::{borrow::Borrow, io::BufRead};
use web_time::Instant;
#[derive(Debug, Clone, Copy)]
struct ElementId(usize);
/// Stores profiling information about one pipeline element
#[derive(Debug, Clone)]
struct ElementInfo {
start: Instant,
duration_ns: i64,
depth: i64,
element_span: Span,
element_output: Option<Value>,
expr: Option<String>,
instruction: Option<(usize, String)>,
children: Vec<ElementId>,
}
impl ElementInfo {
pub fn new(depth: i64, element_span: Span) -> Self {
ElementInfo {
start: Instant::now(),
duration_ns: 0,
depth,
element_span,
element_output: None,
expr: None,
instruction: None,
children: vec![],
}
}
}
/// Whether [`Profiler`] should report duration as [`Value::Duration`]
#[derive(Debug, Clone, Copy)]
pub enum DurationMode {
Milliseconds,
Value,
}
/// Options for [`Profiler`]
#[derive(Debug, Clone)]
pub struct ProfilerOptions {
pub max_depth: i64,
pub collect_spans: bool,
pub collect_source: bool,
pub collect_expanded_source: bool,
pub collect_values: bool,
pub collect_exprs: bool,
pub collect_instructions: bool,
pub collect_lines: bool,
pub duration_mode: DurationMode,
}
/// Basic profiler, used in `debug profile`
#[derive(Debug, Clone)]
pub struct Profiler {
depth: i64,
opts: ProfilerOptions,
elements: Vec<ElementInfo>,
element_stack: Vec<ElementId>,
}
impl Profiler {
#[allow(clippy::too_many_arguments)]
pub fn new(opts: ProfilerOptions, span: Span) -> Self {
let first = ElementInfo {
start: Instant::now(),
duration_ns: 0,
depth: 0,
element_span: span,
element_output: opts.collect_values.then(|| Value::nothing(span)),
expr: opts.collect_exprs.then(|| "call".to_string()),
instruction: opts
.collect_instructions
.then(|| (0, "<start>".to_string())),
children: vec![],
};
Profiler {
depth: 0,
opts,
elements: vec![first],
element_stack: vec![ElementId(0)],
}
}
fn last_element_id(&self) -> Option<ElementId> {
self.element_stack.last().copied()
}
fn last_element_mut(&mut self) -> Option<&mut ElementInfo> {
self.last_element_id()
.and_then(|id| self.elements.get_mut(id.0))
}
}
impl Debugger for Profiler {
fn activate(&mut self) {
let Some(root_element) = self.last_element_mut() else {
eprintln!("Profiler Error: Missing root element.");
return;
};
root_element.start = Instant::now();
}
fn deactivate(&mut self) {
let Some(root_element) = self.last_element_mut() else {
eprintln!("Profiler Error: Missing root element.");
return;
};
root_element.duration_ns = root_element.start.elapsed().as_nanos() as i64;
}
fn enter_block(&mut self, _engine_state: &EngineState, _block: &Block) {
self.depth += 1;
}
fn leave_block(&mut self, _engine_state: &EngineState, _block: &Block) {
self.depth -= 1;
}
fn enter_element(&mut self, engine_state: &EngineState, element: &PipelineElement) {
if self.depth > self.opts.max_depth {
return;
}
let Some(parent_id) = self.last_element_id() else {
eprintln!("Profiler Error: Missing parent element ID.");
return;
};
let expr_opt = self
.opts
.collect_exprs
.then(|| expr_to_string(engine_state, &element.expr.expr));
let new_id = ElementId(self.elements.len());
let mut new_element = ElementInfo::new(self.depth, element.expr.span);
new_element.expr = expr_opt;
self.elements.push(new_element);
let Some(parent) = self.elements.get_mut(parent_id.0) else {
eprintln!("Profiler Error: Missing parent element.");
return;
};
parent.children.push(new_id);
self.element_stack.push(new_id);
}
fn leave_element(
&mut self,
_engine_state: &EngineState,
element: &PipelineElement,
result: &Result<PipelineData, ShellError>,
) {
if self.depth > self.opts.max_depth {
return;
}
let element_span = element.expr.span;
let out_opt = self.opts.collect_values.then(|| match result {
Ok(pipeline_data) => match pipeline_data {
PipelineData::Value(val, ..) => val.clone(),
PipelineData::ListStream(..) => Value::string("list stream", element_span),
PipelineData::ByteStream(..) => Value::string("byte stream", element_span),
_ => Value::nothing(element_span),
},
Err(e) => Value::error(e.clone(), element_span),
});
let Some(last_element) = self.last_element_mut() else {
eprintln!("Profiler Error: Missing last element.");
return;
};
last_element.duration_ns = last_element.start.elapsed().as_nanos() as i64;
last_element.element_output = out_opt;
self.element_stack.pop();
}
fn enter_instruction(
&mut self,
engine_state: &EngineState,
ir_block: &IrBlock,
instruction_index: usize,
_registers: &[PipelineExecutionData],
) {
if self.depth > self.opts.max_depth {
return;
}
let Some(parent_id) = self.last_element_id() else {
eprintln!("Profiler Error: Missing parent element ID.");
return;
};
let instruction = &ir_block.instructions[instruction_index];
let span = ir_block.spans[instruction_index];
let instruction_opt = self.opts.collect_instructions.then(|| {
(
instruction_index,
instruction
.display(engine_state, &ir_block.data)
.to_string(),
)
});
let new_id = ElementId(self.elements.len());
let mut new_element = ElementInfo::new(self.depth, span);
new_element.instruction = instruction_opt;
self.elements.push(new_element);
let Some(parent) = self.elements.get_mut(parent_id.0) else {
eprintln!("Profiler Error: Missing parent element.");
return;
};
parent.children.push(new_id);
self.element_stack.push(new_id);
}
fn leave_instruction(
&mut self,
_engine_state: &EngineState,
ir_block: &IrBlock,
instruction_index: usize,
registers: &[PipelineExecutionData],
error: Option<&ShellError>,
) {
if self.depth > self.opts.max_depth {
return;
}
let instruction = &ir_block.instructions[instruction_index];
let span = ir_block.spans[instruction_index];
let out_opt = self
.opts
.collect_values
.then(|| {
error
.map(Err)
.or_else(|| {
instruction
.output_register()
.map(|register| Ok(®isters[register.get() as usize]))
})
.map(|result| format_result(result.map(|r| &r.body), span))
})
.flatten();
let Some(last_element) = self.last_element_mut() else {
eprintln!("Profiler Error: Missing last element.");
return;
};
last_element.duration_ns = last_element.start.elapsed().as_nanos() as i64;
last_element.element_output = out_opt;
self.element_stack.pop();
}
fn report(&self, engine_state: &EngineState, profiler_span: Span) -> Result<Value, ShellError> {
Ok(Value::list(
collect_data(
engine_state,
self,
ElementId(0),
ElementId(0),
profiler_span,
)?,
profiler_span,
))
}
}
fn profiler_error(msg: impl Into<String>, span: Span) -> ShellError {
ShellError::GenericError {
error: "Profiler Error".to_string(),
msg: msg.into(),
span: Some(span),
help: None,
inner: vec![],
}
}
fn expr_to_string(engine_state: &EngineState, expr: &Expr) -> String {
match expr {
Expr::AttributeBlock(ab) => expr_to_string(engine_state, &ab.item.expr),
Expr::Binary(_) => "binary".to_string(),
Expr::BinaryOp(_, _, _) => "binary operation".to_string(),
Expr::Block(_) => "block".to_string(),
Expr::Bool(_) => "bool".to_string(),
Expr::Call(call) => {
let decl = engine_state.get_decl(call.decl_id);
if decl.name() == "collect" && call.head == Span::new(0, 0) {
"call (implicit collect)"
} else {
"call"
}
.to_string()
}
Expr::CellPath(_) => "cell path".to_string(),
Expr::Closure(_) => "closure".to_string(),
Expr::DateTime(_) => "datetime".to_string(),
Expr::Directory(_, _) => "directory".to_string(),
Expr::ExternalCall(_, _) => "external call".to_string(),
Expr::Filepath(_, _) => "filepath".to_string(),
Expr::Float(_) => "float".to_string(),
Expr::FullCellPath(full_cell_path) => {
let head = expr_to_string(engine_state, &full_cell_path.head.expr);
format!("full cell path ({head})")
}
Expr::Garbage => "garbage".to_string(),
Expr::GlobPattern(_, _) => "glob pattern".to_string(),
Expr::ImportPattern(_) => "import pattern".to_string(),
Expr::Int(_) => "int".to_string(),
Expr::Keyword(_) => "keyword".to_string(),
Expr::List(_) => "list".to_string(),
Expr::MatchBlock(_) => "match block".to_string(),
Expr::Nothing => "nothing".to_string(),
Expr::Operator(_) => "operator".to_string(),
Expr::Overlay(_) => "overlay".to_string(),
Expr::Range(_) => "range".to_string(),
Expr::Record(_) => "record".to_string(),
Expr::RowCondition(_) => "row condition".to_string(),
Expr::Signature(_) => "signature".to_string(),
Expr::String(_) | Expr::RawString(_) => "string".to_string(),
Expr::StringInterpolation(_) => "string interpolation".to_string(),
Expr::GlobInterpolation(_, _) => "glob interpolation".to_string(),
Expr::Collect(_, _) => "collect".to_string(),
Expr::Subexpression(_) => "subexpression".to_string(),
Expr::Table(_) => "table".to_string(),
Expr::UnaryNot(_) => "unary not".to_string(),
Expr::ValueWithUnit(_) => "value with unit".to_string(),
Expr::Var(_) => "var".to_string(),
Expr::VarDecl(_) => "var decl".to_string(),
}
}
fn format_result(
result: Result<&PipelineData, impl Borrow<ShellError>>,
element_span: Span,
) -> Value {
match result {
Ok(pipeline_data) => match pipeline_data {
PipelineData::Value(val, ..) => val.clone(),
PipelineData::ListStream(..) => Value::string("list stream", element_span),
PipelineData::ByteStream(..) => Value::string("byte stream", element_span),
_ => Value::nothing(element_span),
},
Err(e) => Value::error(e.borrow().clone(), element_span),
}
}
// Find a file name and a line number (indexed from 1) of a span
fn find_file_of_span(engine_state: &EngineState, span: Span) -> Option<(&str, usize)> {
for file in engine_state.files() {
if file.covered_span.contains_span(span) {
// count the number of lines between file start and the searched span start
let chunk =
engine_state.get_span_contents(Span::new(file.covered_span.start, span.start));
let nlines = chunk.lines().count();
// account for leading part of current line being counted as a separate line
let line_num = if chunk.last() == Some(&b'\n') {
nlines + 1
} else {
nlines
};
// first line has no previous line, clamp up to `1`
let line_num = usize::max(line_num, 1);
return Some((&file.name, line_num));
}
}
None
}
fn collect_data(
engine_state: &EngineState,
profiler: &Profiler,
element_id: ElementId,
parent_id: ElementId,
profiler_span: Span,
) -> Result<Vec<Value>, ShellError> {
let element = &profiler.elements[element_id.0];
let mut row = record! {
"depth" => Value::int(element.depth, profiler_span),
"id" => Value::int(element_id.0 as i64, profiler_span),
"parent_id" => Value::int(parent_id.0 as i64, profiler_span),
};
if profiler.opts.collect_lines {
if let Some((fname, line_num)) = find_file_of_span(engine_state, element.element_span) {
row.push("file", Value::string(fname, profiler_span));
row.push("line", Value::int(line_num as i64, profiler_span));
} else {
row.push("file", Value::nothing(profiler_span));
row.push("line", Value::nothing(profiler_span));
}
}
if profiler.opts.collect_spans {
let span_start = i64::try_from(element.element_span.start)
.map_err(|_| profiler_error("error converting span start to i64", profiler_span))?;
let span_end = i64::try_from(element.element_span.end)
.map_err(|_| profiler_error("error converting span end to i64", profiler_span))?;
row.push(
"span",
Value::record(
record! {
"start" => Value::int(span_start, profiler_span),
"end" => Value::int(span_end, profiler_span),
},
profiler_span,
),
);
}
if profiler.opts.collect_source {
let val = String::from_utf8_lossy(engine_state.get_span_contents(element.element_span));
let val = val.trim();
let nlines = val.lines().count();
let fragment = if profiler.opts.collect_expanded_source {
val.to_string()
} else {
let mut first_line = val.lines().next().unwrap_or("").to_string();
if nlines > 1 {
first_line.push_str(" ...");
}
first_line
};
row.push("source", Value::string(fragment, profiler_span));
}
if let Some(expr_string) = &element.expr {
row.push("expr", Value::string(expr_string.clone(), profiler_span));
}
if let Some((instruction_index, instruction)) = &element.instruction {
row.push(
"pc",
(*instruction_index)
.try_into()
.map(|index| Value::int(index, profiler_span))
.unwrap_or(Value::nothing(profiler_span)),
);
row.push("instruction", Value::string(instruction, profiler_span));
}
if let Some(val) = &element.element_output {
row.push("output", val.clone());
}
match profiler.opts.duration_mode {
DurationMode::Milliseconds => {
let val = Value::float(element.duration_ns as f64 / 1000.0 / 1000.0, profiler_span);
row.push("duration_ms", val);
}
DurationMode::Value => {
let val = Value::duration(element.duration_ns, profiler_span);
row.push("duration", val);
}
};
let mut rows = vec![Value::record(row, profiler_span)];
for child in &element.children {
let child_rows = collect_data(engine_state, profiler, *child, element_id, profiler_span)?;
rows.extend(child_rows);
}
Ok(rows)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/debugger/mod.rs | crates/nu-protocol/src/debugger/mod.rs | //! Module containing the trait to instrument the engine for debugging and profiling
pub mod debugger_trait;
pub mod profiler;
pub use debugger_trait::*;
pub use profiler::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/debugger/debugger_trait.rs | crates/nu-protocol/src/debugger/debugger_trait.rs | //! Traits related to debugging
//!
//! The purpose of DebugContext is achieving static dispatch on `eval_xxx()` calls.
//! The main Debugger trait is intended to be used as a trait object.
//!
//! The debugging information is stored in `EngineState` as the `debugger` field storing a `Debugger`
//! trait object behind `Arc` and `Mutex`. To evaluate something (e.g., a block), first create a
//! `Debugger` trait object (such as the `Profiler`). Then, add it to engine state via
//! `engine_state.activate_debugger()`. This sets the internal state of EngineState to the debugging
//! mode and calls `Debugger::activate()`. Now, you can call `eval_xxx::<WithDebug>()`. When you're
//! done, call `engine_state.deactivate_debugger()` which calls `Debugger::deactivate()`, sets the
//! EngineState into non-debugging mode, and returns the original mutated `Debugger` trait object.
//! (`NoopDebugger` is placed in its place inside `EngineState`.) After deactivating, you can call
//! `Debugger::report()` to get some output from the debugger, if necessary.
use crate::{
PipelineData, PipelineExecutionData, ShellError, Span, Value,
ast::{Block, PipelineElement},
engine::EngineState,
ir::IrBlock,
};
use std::{fmt::Debug, ops::DerefMut};
/// Trait used for static dispatch of `eval_xxx()` evaluator calls
///
/// DebugContext implements the same interface as Debugger (except activate() and deactivate(). It
/// is intended to be implemented only by two structs
/// * WithDebug which calls down to the Debugger methods
/// * WithoutDebug with default implementation, i.e., empty calls to be optimized away
pub trait DebugContext: Clone + Copy + Debug {
/// Called when the evaluator enters a block
#[allow(unused_variables)]
fn enter_block(engine_state: &EngineState, block: &Block) {}
/// Called when the evaluator leaves a block
#[allow(unused_variables)]
fn leave_block(engine_state: &EngineState, block: &Block) {}
/// Called when the AST evaluator enters a pipeline element
#[allow(unused_variables)]
fn enter_element(engine_state: &EngineState, element: &PipelineElement) {}
/// Called when the AST evaluator leaves a pipeline element
#[allow(unused_variables)]
fn leave_element(
engine_state: &EngineState,
element: &PipelineElement,
result: &Result<PipelineData, ShellError>,
) {
}
/// Called before the IR evaluator runs an instruction
#[allow(unused_variables)]
fn enter_instruction(
engine_state: &EngineState,
ir_block: &IrBlock,
instruction_index: usize,
registers: &[PipelineExecutionData],
) {
}
/// Called after the IR evaluator runs an instruction
#[allow(unused_variables)]
fn leave_instruction(
engine_state: &EngineState,
ir_block: &IrBlock,
instruction_index: usize,
registers: &[PipelineExecutionData],
error: Option<&ShellError>,
) {
}
}
/// Marker struct signalizing that evaluation should use a Debugger
///
/// Trait methods call to Debugger trait object inside the supplied EngineState.
#[derive(Clone, Copy, Debug)]
pub struct WithDebug;
impl DebugContext for WithDebug {
fn enter_block(engine_state: &EngineState, block: &Block) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger.deref_mut().enter_block(engine_state, block);
}
}
fn leave_block(engine_state: &EngineState, block: &Block) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger.deref_mut().leave_block(engine_state, block);
}
}
fn enter_element(engine_state: &EngineState, element: &PipelineElement) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger.deref_mut().enter_element(engine_state, element);
}
}
fn leave_element(
engine_state: &EngineState,
element: &PipelineElement,
result: &Result<PipelineData, ShellError>,
) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger
.deref_mut()
.leave_element(engine_state, element, result);
}
}
fn enter_instruction(
engine_state: &EngineState,
ir_block: &IrBlock,
instruction_index: usize,
registers: &[PipelineExecutionData],
) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger.deref_mut().enter_instruction(
engine_state,
ir_block,
instruction_index,
registers,
)
}
}
fn leave_instruction(
engine_state: &EngineState,
ir_block: &IrBlock,
instruction_index: usize,
registers: &[PipelineExecutionData],
error: Option<&ShellError>,
) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger.deref_mut().leave_instruction(
engine_state,
ir_block,
instruction_index,
registers,
error,
)
}
}
}
/// Marker struct signalizing that evaluation should NOT use a Debugger
///
/// Trait methods are empty calls to be optimized away.
#[derive(Clone, Copy, Debug)]
pub struct WithoutDebug;
impl DebugContext for WithoutDebug {}
/// Debugger trait that every debugger needs to implement.
///
/// By default, its methods are empty. Not every Debugger needs to implement all of them.
pub trait Debugger: Send + Debug {
/// Called by EngineState::activate_debugger().
///
/// Intended for initializing the debugger.
fn activate(&mut self) {}
/// Called by EngineState::deactivate_debugger().
///
/// Intended for wrapping up the debugger after a debugging session before returning back to
/// normal evaluation without debugging.
fn deactivate(&mut self) {}
/// Called when the evaluator enters a block
#[allow(unused_variables)]
fn enter_block(&mut self, engine_state: &EngineState, block: &Block) {}
/// Called when the evaluator leaves a block
#[allow(unused_variables)]
fn leave_block(&mut self, engine_state: &EngineState, block: &Block) {}
/// Called when the AST evaluator enters a pipeline element
#[allow(unused_variables)]
fn enter_element(&mut self, engine_state: &EngineState, pipeline_element: &PipelineElement) {}
/// Called when the AST evaluator leaves a pipeline element
#[allow(unused_variables)]
fn leave_element(
&mut self,
engine_state: &EngineState,
element: &PipelineElement,
result: &Result<PipelineData, ShellError>,
) {
}
/// Called before the IR evaluator runs an instruction
#[allow(unused_variables)]
fn enter_instruction(
&mut self,
engine_state: &EngineState,
ir_block: &IrBlock,
instruction_index: usize,
registers: &[PipelineExecutionData],
) {
}
/// Called after the IR evaluator runs an instruction
#[allow(unused_variables)]
fn leave_instruction(
&mut self,
engine_state: &EngineState,
ir_block: &IrBlock,
instruction_index: usize,
registers: &[PipelineExecutionData],
error: Option<&ShellError>,
) {
}
/// Create a final report as a Value
///
/// Intended to be called after deactivate()
#[allow(unused_variables)]
fn report(&self, engine_state: &EngineState, debugger_span: Span) -> Result<Value, ShellError> {
Ok(Value::nothing(debugger_span))
}
}
/// A debugger that does nothing
///
/// Used as a placeholder debugger when not debugging.
#[derive(Debug)]
pub struct NoopDebugger;
impl Debugger for NoopDebugger {}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/pipeline/byte_stream.rs | crates/nu-protocol/src/pipeline/byte_stream.rs | //! Module managing the streaming of raw bytes between pipeline elements
//!
//! This module also handles conversions the [`ShellError`] <-> [`io::Error`](std::io::Error),
//! so remember the usage of [`ShellErrorBridge`] where applicable.
#[cfg(feature = "os")]
use crate::process::{ChildPipe, ChildProcess};
use crate::{
IntRange, PipelineData, ShellError, Signals, Span, Type, Value,
shell_error::{bridge::ShellErrorBridge, io::IoError},
};
use nu_utils::SplitRead as SplitReadInner;
use serde::{Deserialize, Serialize};
use std::ops::Bound;
#[cfg(unix)]
use std::os::fd::OwnedFd;
#[cfg(windows)]
use std::os::windows::io::OwnedHandle;
use std::{
fmt::Debug,
fs::File,
io::{self, BufRead, BufReader, Cursor, ErrorKind, Read, Write},
process::Stdio,
};
/// The source of bytes for a [`ByteStream`].
///
/// Currently, there are only three possibilities:
/// 1. `Read` (any `dyn` type that implements [`Read`])
/// 2. [`File`]
/// 3. [`ChildProcess`]
pub enum ByteStreamSource {
Read(Box<dyn Read + Send + 'static>),
File(File),
#[cfg(feature = "os")]
Child(Box<ChildProcess>),
}
impl ByteStreamSource {
fn reader(self) -> Option<SourceReader> {
match self {
ByteStreamSource::Read(read) => Some(SourceReader::Read(read)),
ByteStreamSource::File(file) => Some(SourceReader::File(file)),
#[cfg(feature = "os")]
ByteStreamSource::Child(mut child) => child.stdout.take().map(|stdout| match stdout {
ChildPipe::Pipe(pipe) => SourceReader::File(convert_file(pipe)),
ChildPipe::Tee(tee) => SourceReader::Read(tee),
}),
}
}
/// Source is a `Child` or `File`, rather than `Read`. Currently affects trimming
#[cfg(feature = "os")]
pub fn is_external(&self) -> bool {
matches!(self, ByteStreamSource::Child(..))
}
#[cfg(not(feature = "os"))]
pub fn is_external(&self) -> bool {
// without os support we never have externals
false
}
}
impl Debug for ByteStreamSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ByteStreamSource::Read(_) => f.debug_tuple("Read").field(&"..").finish(),
ByteStreamSource::File(file) => f.debug_tuple("File").field(file).finish(),
#[cfg(feature = "os")]
ByteStreamSource::Child(child) => f.debug_tuple("Child").field(child).finish(),
}
}
}
enum SourceReader {
Read(Box<dyn Read + Send + 'static>),
File(File),
}
impl Read for SourceReader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self {
SourceReader::Read(reader) => reader.read(buf),
SourceReader::File(file) => file.read(buf),
}
}
}
impl Debug for SourceReader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SourceReader::Read(_) => f.debug_tuple("Read").field(&"..").finish(),
SourceReader::File(file) => f.debug_tuple("File").field(file).finish(),
}
}
}
/// Optional type color for [`ByteStream`], which determines type compatibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ByteStreamType {
/// Compatible with [`Type::Binary`], and should only be converted to binary, even when the
/// desired type is unknown.
Binary,
/// Compatible with [`Type::String`], and should only be converted to string, even when the
/// desired type is unknown.
///
/// This does not guarantee valid UTF-8 data, but it is conventionally so. Converting to
/// `String` still requires validation of the data.
String,
/// Unknown whether the stream should contain binary or string data. This usually is the result
/// of an external stream, e.g. an external command or file.
#[default]
Unknown,
}
impl ByteStreamType {
/// Returns the string that describes the byte stream type - i.e., the same as what `describe`
/// produces. This can be used in type mismatch error messages.
pub fn describe(self) -> &'static str {
match self {
ByteStreamType::Binary => "binary (stream)",
ByteStreamType::String => "string (stream)",
ByteStreamType::Unknown => "byte stream",
}
}
/// Returns true if the type is `Binary` or `Unknown`
pub fn is_binary_coercible(self) -> bool {
matches!(self, ByteStreamType::Binary | ByteStreamType::Unknown)
}
/// Returns true if the type is `String` or `Unknown`
pub fn is_string_coercible(self) -> bool {
matches!(self, ByteStreamType::String | ByteStreamType::Unknown)
}
}
impl From<ByteStreamType> for Type {
fn from(value: ByteStreamType) -> Self {
match value {
ByteStreamType::Binary => Type::Binary,
ByteStreamType::String => Type::String,
ByteStreamType::Unknown => Type::Any,
}
}
}
/// A potentially infinite, interruptible stream of bytes.
///
/// To create a [`ByteStream`], you can use any of the following methods:
/// - [`read`](ByteStream::read): takes any type that implements [`Read`].
/// - [`file`](ByteStream::file): takes a [`File`].
/// - [`from_iter`](ByteStream::from_iter): takes an [`Iterator`] whose items implement `AsRef<[u8]>`.
/// - [`from_result_iter`](ByteStream::from_result_iter): same as [`from_iter`](ByteStream::from_iter),
/// but each item is a `Result<T, ShellError>`.
/// - [`from_fn`](ByteStream::from_fn): uses a generator function to fill a buffer whenever it is
/// empty. This has high performance because it doesn't need to allocate for each chunk of data,
/// and can just reuse the same buffer.
///
/// Byte streams have a [type](.type_()) which is used to preserve type compatibility when they
/// are the result of an internal command. It is important that this be set to the correct value.
/// [`Unknown`](ByteStreamType::Unknown) is used only for external sources where the type can not
/// be inherently determined, and having it automatically act as a string or binary depending on
/// whether it parses as UTF-8 or not is desirable.
///
/// The data of a [`ByteStream`] can be accessed using one of the following methods:
/// - [`reader`](ByteStream::reader): returns a [`Read`]-able type to get the raw bytes in the stream.
/// - [`lines`](ByteStream::lines): splits the bytes on lines and returns an [`Iterator`]
/// where each item is a `Result<String, ShellError>`.
/// - [`chunks`](ByteStream::chunks): returns an [`Iterator`] of [`Value`]s where each value is
/// either a string or binary.
/// Try not to use this method if possible. Rather, please use [`reader`](ByteStream::reader)
/// (or [`lines`](ByteStream::lines) if it matches the situation).
///
/// Additionally, there are few methods to collect a [`ByteStream`] into memory:
/// - [`into_bytes`](ByteStream::into_bytes): collects all bytes into a [`Vec<u8>`].
/// - [`into_string`](ByteStream::into_string): collects all bytes into a [`String`], erroring if utf-8 decoding failed.
/// - [`into_value`](ByteStream::into_value): collects all bytes into a value typed appropriately
/// for the [type](.type_()) of this stream. If the type is [`Unknown`](ByteStreamType::Unknown),
/// it will produce a string value if the data is valid UTF-8, or a binary value otherwise.
///
/// There are also a few other methods to consume all the data of a [`ByteStream`]:
/// - [`drain`](ByteStream::drain): consumes all bytes and outputs nothing.
/// - [`write_to`](ByteStream::write_to): writes all bytes to the given [`Write`] destination.
/// - [`print`](ByteStream::print): a convenience wrapper around [`write_to`](ByteStream::write_to).
/// It prints all bytes to stdout or stderr.
///
/// Internally, [`ByteStream`]s currently come in three flavors according to [`ByteStreamSource`].
/// See its documentation for more information.
#[derive(Debug)]
pub struct ByteStream {
stream: ByteStreamSource,
span: Span,
signals: Signals,
type_: ByteStreamType,
known_size: Option<u64>,
caller_spans: Vec<Span>,
}
impl ByteStream {
/// Create a new [`ByteStream`] from a [`ByteStreamSource`].
pub fn new(
stream: ByteStreamSource,
span: Span,
signals: Signals,
type_: ByteStreamType,
) -> Self {
Self {
stream,
span,
signals,
type_,
known_size: None,
caller_spans: vec![],
}
}
/// Push a caller [`Span`] to the bytestream, it's useful to construct a backtrace.
pub fn push_caller_span(&mut self, span: Span) {
if span != self.span {
self.caller_spans.push(span)
}
}
/// Get all caller [`Span`], it's useful to construct a backtrace.
pub fn get_caller_spans(&self) -> &Vec<Span> {
&self.caller_spans
}
/// Create a [`ByteStream`] from an arbitrary reader. The type must be provided.
pub fn read(
reader: impl Read + Send + 'static,
span: Span,
signals: Signals,
type_: ByteStreamType,
) -> Self {
Self::new(
ByteStreamSource::Read(Box::new(reader)),
span,
signals,
type_,
)
}
pub fn skip(self, span: Span, n: u64) -> Result<Self, ShellError> {
let known_size = self.known_size.map(|len| len.saturating_sub(n));
if let Some(mut reader) = self.reader() {
// Copy the number of skipped bytes into the sink before proceeding
io::copy(&mut (&mut reader).take(n), &mut io::sink())
.map_err(|err| IoError::new(err, span, None))?;
Ok(
ByteStream::read(reader, span, Signals::empty(), ByteStreamType::Binary)
.with_known_size(known_size),
)
} else {
Err(ShellError::TypeMismatch {
err_message: "expected readable stream".into(),
span,
})
}
}
pub fn take(self, span: Span, n: u64) -> Result<Self, ShellError> {
let known_size = self.known_size.map(|s| s.min(n));
if let Some(reader) = self.reader() {
Ok(ByteStream::read(
reader.take(n),
span,
Signals::empty(),
ByteStreamType::Binary,
)
.with_known_size(known_size))
} else {
Err(ShellError::TypeMismatch {
err_message: "expected readable stream".into(),
span,
})
}
}
pub fn slice(
self,
val_span: Span,
call_span: Span,
range: IntRange,
) -> Result<Self, ShellError> {
if let Some(len) = self.known_size {
let start = range.absolute_start(len);
let stream = self.skip(val_span, start);
match range.absolute_end(len) {
Bound::Unbounded => stream,
Bound::Included(end) | Bound::Excluded(end) if end < start => {
stream.and_then(|s| s.take(val_span, 0))
}
Bound::Included(end) => {
let distance = end - start + 1;
stream.and_then(|s| s.take(val_span, distance.min(len)))
}
Bound::Excluded(end) => {
let distance = end - start;
stream.and_then(|s| s.take(val_span, distance.min(len)))
}
}
} else if range.is_relative() {
Err(ShellError::RelativeRangeOnInfiniteStream { span: call_span })
} else {
let start = range.start() as u64;
let stream = self.skip(val_span, start);
match range.distance() {
Bound::Unbounded => stream,
Bound::Included(distance) => stream.and_then(|s| s.take(val_span, distance + 1)),
Bound::Excluded(distance) => stream.and_then(|s| s.take(val_span, distance)),
}
}
}
/// Create a [`ByteStream`] from a string. The type of the stream is always `String`.
pub fn read_string(string: String, span: Span, signals: Signals) -> Self {
let len = string.len();
ByteStream::read(
Cursor::new(string.into_bytes()),
span,
signals,
ByteStreamType::String,
)
.with_known_size(Some(len as u64))
}
/// Create a [`ByteStream`] from a byte vector. The type of the stream is always `Binary`.
pub fn read_binary(bytes: Vec<u8>, span: Span, signals: Signals) -> Self {
let len = bytes.len();
ByteStream::read(Cursor::new(bytes), span, signals, ByteStreamType::Binary)
.with_known_size(Some(len as u64))
}
/// Create a [`ByteStream`] from a file.
///
/// The type is implicitly `Unknown`, as it's not typically known whether files will
/// return text or binary.
pub fn file(file: File, span: Span, signals: Signals) -> Self {
Self::new(
ByteStreamSource::File(file),
span,
signals,
ByteStreamType::Unknown,
)
}
/// Create a [`ByteStream`] from a child process's stdout and stderr.
///
/// The type is implicitly `Unknown`, as it's not typically known whether child processes will
/// return text or binary.
#[cfg(feature = "os")]
pub fn child(child: ChildProcess, span: Span) -> Self {
Self::new(
ByteStreamSource::Child(Box::new(child)),
span,
Signals::empty(),
ByteStreamType::Unknown,
)
}
/// Create a [`ByteStream`] that reads from stdin.
///
/// The type is implicitly `Unknown`, as it's not typically known whether stdin is text or
/// binary.
#[cfg(feature = "os")]
pub fn stdin(span: Span) -> Result<Self, ShellError> {
let stdin = os_pipe::dup_stdin().map_err(|err| IoError::new(err, span, None))?;
let source = ByteStreamSource::File(convert_file(stdin));
Ok(Self::new(
source,
span,
Signals::empty(),
ByteStreamType::Unknown,
))
}
#[cfg(not(feature = "os"))]
pub fn stdin(span: Span) -> Result<Self, ShellError> {
Err(ShellError::DisabledOsSupport {
msg: "Stdin is not supported".to_string(),
span,
})
}
/// Create a [`ByteStream`] from a generator function that writes data to the given buffer
/// when called, and returns `Ok(false)` on end of stream.
pub fn from_fn(
span: Span,
signals: Signals,
type_: ByteStreamType,
generator: impl FnMut(&mut Vec<u8>) -> Result<bool, ShellError> + Send + 'static,
) -> Self {
Self::read(
ReadGenerator {
buffer: Cursor::new(Vec::new()),
generator,
},
span,
signals,
type_,
)
}
pub fn with_type(mut self, type_: ByteStreamType) -> Self {
self.type_ = type_;
self
}
/// Create a new [`ByteStream`] from an [`Iterator`] of bytes slices.
///
/// The returned [`ByteStream`] will have a [`ByteStreamSource`] of `Read`.
pub fn from_iter<I>(iter: I, span: Span, signals: Signals, type_: ByteStreamType) -> Self
where
I: IntoIterator,
I::IntoIter: Send + 'static,
I::Item: AsRef<[u8]> + Default + Send + 'static,
{
let iter = iter.into_iter();
let cursor = Some(Cursor::new(I::Item::default()));
Self::read(ReadIterator { iter, cursor }, span, signals, type_)
}
/// Create a new [`ByteStream`] from an [`Iterator`] of [`Result`] bytes slices.
///
/// The returned [`ByteStream`] will have a [`ByteStreamSource`] of `Read`.
pub fn from_result_iter<I, T>(
iter: I,
span: Span,
signals: Signals,
type_: ByteStreamType,
) -> Self
where
I: IntoIterator<Item = Result<T, ShellError>>,
I::IntoIter: Send + 'static,
T: AsRef<[u8]> + Default + Send + 'static,
{
let iter = iter.into_iter();
let cursor = Some(Cursor::new(T::default()));
Self::read(ReadResultIterator { iter, cursor }, span, signals, type_)
}
/// Set the known size, in number of bytes, of the [`ByteStream`].
pub fn with_known_size(mut self, size: Option<u64>) -> Self {
self.known_size = size;
self
}
/// Get a reference to the inner [`ByteStreamSource`] of the [`ByteStream`].
pub fn source(&self) -> &ByteStreamSource {
&self.stream
}
/// Get a mutable reference to the inner [`ByteStreamSource`] of the [`ByteStream`].
pub fn source_mut(&mut self) -> &mut ByteStreamSource {
&mut self.stream
}
/// Returns the [`Span`] associated with the [`ByteStream`].
pub fn span(&self) -> Span {
self.span
}
/// Changes the [`Span`] associated with the [`ByteStream`].
pub fn with_span(mut self, span: Span) -> Self {
self.span = span;
self
}
/// Returns the [`ByteStreamType`] associated with the [`ByteStream`].
pub fn type_(&self) -> ByteStreamType {
self.type_
}
/// Returns the known size, in number of bytes, of the [`ByteStream`].
pub fn known_size(&self) -> Option<u64> {
self.known_size
}
/// Convert the [`ByteStream`] into its [`Reader`] which allows one to [`Read`] the raw bytes of the stream.
///
/// [`Reader`] is buffered and also implements [`BufRead`].
///
/// If the source of the [`ByteStream`] is [`ByteStreamSource::Child`] and the child has no stdout,
/// then the stream is considered empty and `None` will be returned.
pub fn reader(self) -> Option<Reader> {
let reader = self.stream.reader()?;
Some(Reader {
reader: BufReader::new(reader),
span: self.span,
signals: self.signals,
})
}
/// Convert the [`ByteStream`] into a [`Lines`] iterator where each element is a `Result<String, ShellError>`.
///
/// There is no limit on how large each line will be. Ending new lines (`\n` or `\r\n`) are
/// stripped from each line. If a line fails to be decoded as utf-8, then it will become a [`ShellError`].
///
/// If the source of the [`ByteStream`] is [`ByteStreamSource::Child`] and the child has no stdout,
/// then the stream is considered empty and `None` will be returned.
pub fn lines(self) -> Option<Lines> {
let reader = self.stream.reader()?;
Some(Lines {
reader: BufReader::new(reader),
span: self.span,
signals: self.signals,
})
}
/// Convert the [`ByteStream`] into a [`SplitRead`] iterator where each element is a `Result<String, ShellError>`.
///
/// Each call to [`next`](Iterator::next) reads the currently available data from the byte
/// stream source, until `delimiter` or the end of the stream is encountered.
///
/// If the source of the [`ByteStream`] is [`ByteStreamSource::Child`] and the child has no stdout,
/// then the stream is considered empty and `None` will be returned.
pub fn split(self, delimiter: Vec<u8>) -> Option<SplitRead> {
let reader = self.stream.reader()?;
Some(SplitRead::new(reader, delimiter, self.span, self.signals))
}
/// Convert the [`ByteStream`] into a [`Chunks`] iterator where each element is a `Result<Value, ShellError>`.
///
/// Each call to [`next`](Iterator::next) reads the currently available data from the byte stream source,
/// up to a maximum size. The values are typed according to the [type](.type_()) of the
/// stream, and if that type is [`Unknown`](ByteStreamType::Unknown), string values will be
/// produced as long as the stream continues to parse as valid UTF-8, but binary values will
/// be produced instead of the stream fails to parse as UTF-8 instead at any point.
/// Any and all newlines are kept intact in each chunk.
///
/// Where possible, prefer [`reader`](ByteStream::reader) or [`lines`](ByteStream::lines) over this method.
/// Those methods are more likely to be used in a semantically correct way
/// (and [`reader`](ByteStream::reader) is more efficient too).
///
/// If the source of the [`ByteStream`] is [`ByteStreamSource::Child`] and the child has no stdout,
/// then the stream is considered empty and `None` will be returned.
pub fn chunks(self) -> Option<Chunks> {
let reader = self.stream.reader()?;
Some(Chunks::new(reader, self.span, self.signals, self.type_))
}
/// Convert the [`ByteStream`] into its inner [`ByteStreamSource`].
pub fn into_source(self) -> ByteStreamSource {
self.stream
}
/// Attempt to convert the [`ByteStream`] into a [`Stdio`].
///
/// This will succeed if the [`ByteStreamSource`] of the [`ByteStream`] is either:
/// - [`File`](ByteStreamSource::File)
/// - [`Child`](ByteStreamSource::Child) and the child has a stdout that is `Some(ChildPipe::Pipe(..))`.
///
/// All other cases return an `Err` with the original [`ByteStream`] in it.
pub fn into_stdio(mut self) -> Result<Stdio, Self> {
match self.stream {
ByteStreamSource::Read(..) => Err(self),
ByteStreamSource::File(file) => Ok(file.into()),
#[cfg(feature = "os")]
ByteStreamSource::Child(child) => {
if let ChildProcess {
stdout: Some(ChildPipe::Pipe(stdout)),
stderr,
..
} = *child
{
debug_assert!(stderr.is_none(), "stderr should not exist");
Ok(stdout.into())
} else {
self.stream = ByteStreamSource::Child(child);
Err(self)
}
}
}
}
/// Attempt to convert the [`ByteStream`] into a [`ChildProcess`].
///
/// This will only succeed if the [`ByteStreamSource`] of the [`ByteStream`] is [`Child`](ByteStreamSource::Child).
/// All other cases return an `Err` with the original [`ByteStream`] in it.
#[cfg(feature = "os")]
pub fn into_child(self) -> Result<ChildProcess, Self> {
if let ByteStreamSource::Child(child) = self.stream {
Ok(*child)
} else {
Err(self)
}
}
/// Collect all the bytes of the [`ByteStream`] into a [`Vec<u8>`].
///
/// Any trailing new lines are kept in the returned [`Vec`].
pub fn into_bytes(self) -> Result<Vec<u8>, ShellError> {
// todo!() ctrlc
let from_io_error = IoError::factory(self.span, None);
match self.stream {
ByteStreamSource::Read(mut read) => {
let mut buf = Vec::new();
read.read_to_end(&mut buf).map_err(|err| {
match ShellErrorBridge::try_from(err) {
Ok(ShellErrorBridge(err)) => err,
Err(err) => ShellError::Io(from_io_error(err)),
}
})?;
Ok(buf)
}
ByteStreamSource::File(mut file) => {
let mut buf = Vec::new();
file.read_to_end(&mut buf).map_err(&from_io_error)?;
Ok(buf)
}
#[cfg(feature = "os")]
ByteStreamSource::Child(child) => child.into_bytes(),
}
}
/// Collect the stream into a `String` in-memory. This can only succeed if the data contained is
/// valid UTF-8.
///
/// The trailing new line (`\n` or `\r\n`), if any, is removed from the [`String`] prior to
/// being returned, if this is a stream coming from an external process or file.
///
/// If the [type](.type_()) is specified as `Binary`, this operation always fails, even if the
/// data would have been valid UTF-8.
pub fn into_string(self) -> Result<String, ShellError> {
let span = self.span;
if self.type_.is_string_coercible() {
let trim = self.stream.is_external();
let bytes = self.into_bytes()?;
let mut string = String::from_utf8(bytes).map_err(|err| ShellError::NonUtf8Custom {
span,
msg: err.to_string(),
})?;
if trim {
trim_end_newline(&mut string);
}
Ok(string)
} else {
Err(ShellError::TypeMismatch {
err_message: "expected string, but got binary".into(),
span,
})
}
}
/// Collect all the bytes of the [`ByteStream`] into a [`Value`].
///
/// If this is a `String` stream, the stream is decoded to UTF-8. If the stream came from an
/// external process or file, the trailing new line (`\n` or `\r\n`), if any, is removed from
/// the [`String`] prior to being returned.
///
/// If this is a `Binary` stream, a [`Value::Binary`] is returned with any trailing new lines
/// preserved.
///
/// If this is an `Unknown` stream, the behavior depends on whether the stream parses as valid
/// UTF-8 or not. If it does, this is uses the `String` behavior; if not, it uses the `Binary`
/// behavior.
pub fn into_value(self) -> Result<Value, ShellError> {
let span = self.span;
let trim = self.stream.is_external();
let value = match self.type_ {
// If the type is specified, then the stream should always become that type:
ByteStreamType::Binary => Value::binary(self.into_bytes()?, span),
ByteStreamType::String => Value::string(self.into_string()?, span),
// If the type is not specified, then it just depends on whether it parses or not:
ByteStreamType::Unknown => match String::from_utf8(self.into_bytes()?) {
Ok(mut str) => {
if trim {
trim_end_newline(&mut str);
}
Value::string(str, span)
}
Err(err) => Value::binary(err.into_bytes(), span),
},
};
Ok(value)
}
/// Consume and drop all bytes of the [`ByteStream`].
pub fn drain(self) -> Result<(), ShellError> {
match self.stream {
ByteStreamSource::Read(read) => {
copy_with_signals(read, io::sink(), self.span, &self.signals)?;
Ok(())
}
ByteStreamSource::File(_) => Ok(()),
#[cfg(feature = "os")]
ByteStreamSource::Child(child) => child.wait(),
}
}
/// Print all bytes of the [`ByteStream`] to stdout or stderr.
pub fn print(self, to_stderr: bool) -> Result<(), ShellError> {
if to_stderr {
self.write_to(&mut io::stderr())
} else {
self.write_to(&mut io::stdout())
}
}
/// Write all bytes of the [`ByteStream`] to `dest`.
pub fn write_to(self, dest: impl Write) -> Result<(), ShellError> {
let span = self.span;
let signals = &self.signals;
match self.stream {
ByteStreamSource::Read(read) => {
copy_with_signals(read, dest, span, signals)?;
}
ByteStreamSource::File(file) => {
copy_with_signals(file, dest, span, signals)?;
}
#[cfg(feature = "os")]
ByteStreamSource::Child(mut child) => {
// All `OutDest`s except `OutDest::PipeSeparate` will cause `stderr` to be `None`.
// Only `save`, `tee`, and `complete` set the stderr `OutDest` to `OutDest::PipeSeparate`,
// and those commands have proper simultaneous handling of stdout and stderr.
debug_assert!(child.stderr.is_none(), "stderr should not exist");
if let Some(stdout) = child.stdout.take() {
match stdout {
ChildPipe::Pipe(pipe) => {
copy_with_signals(pipe, dest, span, signals)?;
}
ChildPipe::Tee(tee) => {
copy_with_signals(tee, dest, span, signals)?;
}
}
}
child.wait()?;
}
}
Ok(())
}
}
impl From<ByteStream> for PipelineData {
fn from(stream: ByteStream) -> Self {
Self::byte_stream(stream, None)
}
}
struct ReadIterator<I>
where
I: Iterator,
I::Item: AsRef<[u8]>,
{
iter: I,
cursor: Option<Cursor<I::Item>>,
}
impl<I> Read for ReadIterator<I>
where
I: Iterator,
I::Item: AsRef<[u8]>,
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
while let Some(cursor) = self.cursor.as_mut() {
let read = cursor.read(buf)?;
if read == 0 {
self.cursor = self.iter.next().map(Cursor::new);
} else {
return Ok(read);
}
}
Ok(0)
}
}
struct ReadResultIterator<I, T>
where
I: Iterator<Item = Result<T, ShellError>>,
T: AsRef<[u8]>,
{
iter: I,
cursor: Option<Cursor<T>>,
}
impl<I, T> Read for ReadResultIterator<I, T>
where
I: Iterator<Item = Result<T, ShellError>>,
T: AsRef<[u8]>,
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
while let Some(cursor) = self.cursor.as_mut() {
let read = cursor.read(buf)?;
if read == 0 {
self.cursor = self
.iter
.next()
.transpose()
.map_err(ShellErrorBridge)?
.map(Cursor::new);
} else {
return Ok(read);
}
}
Ok(0)
}
}
pub struct Reader {
reader: BufReader<SourceReader>,
span: Span,
signals: Signals,
}
impl Reader {
pub fn span(&self) -> Span {
self.span
}
}
impl Read for Reader {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.signals.check(&self.span).map_err(ShellErrorBridge)?;
self.reader.read(buf)
}
}
impl BufRead for Reader {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
self.reader.fill_buf()
}
fn consume(&mut self, amt: usize) {
self.reader.consume(amt)
}
}
pub struct Lines {
reader: BufReader<SourceReader>,
span: Span,
signals: Signals,
}
impl Lines {
pub fn span(&self) -> Span {
self.span
}
}
impl Iterator for Lines {
type Item = Result<String, ShellError>;
fn next(&mut self) -> Option<Self::Item> {
if self.signals.interrupted() {
None
} else {
let mut buf = Vec::new();
match self.reader.read_until(b'\n', &mut buf) {
Ok(0) => None,
Ok(_) => {
let Ok(mut string) = String::from_utf8(buf) else {
return Some(Err(ShellError::NonUtf8 { span: self.span }));
};
trim_end_newline(&mut string);
Some(Ok(string))
}
Err(err) => Some(Err(IoError::new(err, self.span, None).into())),
}
}
}
}
pub struct SplitRead {
internal: SplitReadInner<BufReader<SourceReader>>,
span: Span,
signals: Signals,
}
impl SplitRead {
fn new(
reader: SourceReader,
delimiter: impl AsRef<[u8]>,
span: Span,
signals: Signals,
) -> Self {
Self {
internal: SplitReadInner::new(BufReader::new(reader), delimiter),
span,
signals,
}
}
pub fn span(&self) -> Span {
self.span
}
}
impl Iterator for SplitRead {
type Item = Result<Vec<u8>, ShellError>;
fn next(&mut self) -> Option<Self::Item> {
if self.signals.interrupted() {
return None;
}
self.internal.next().map(|r| {
r.map_err(|err| {
ShellError::Io(IoError::new_internal(
err,
"Could not get next value for SplitRead",
crate::location!(),
))
})
})
}
}
/// Turn a readable stream into [`Value`]s.
///
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/pipeline/handlers.rs | crates/nu-protocol/src/pipeline/handlers.rs | use std::fmt::Debug;
use std::sync::{Arc, Mutex};
use crate::{ShellError, SignalAction, engine::Sequence};
/// Handler is a closure that can be sent across threads and shared.
pub type Handler = Box<dyn Fn(SignalAction) + Send + Sync>;
/// Manages a collection of handlers.
#[derive(Clone)]
pub struct Handlers {
/// List of handler tuples containing an ID and the handler itself.
handlers: Arc<Mutex<Vec<(usize, Handler)>>>,
/// Sequence generator for unique IDs.
next_id: Arc<Sequence>,
}
impl Debug for Handlers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Handlers")
.field("next_id", &self.next_id)
.finish()
}
}
/// HandlerGuard that unregisters a handler when dropped.
#[derive(Clone)]
pub struct HandlerGuard {
/// Unique ID of the handler.
id: usize,
/// Reference to the handlers list.
handlers: Arc<Mutex<Vec<(usize, Handler)>>>,
}
impl Drop for HandlerGuard {
/// Drops the `Guard`, removing the associated handler from the list.
fn drop(&mut self) {
if let Ok(mut handlers) = self.handlers.lock() {
handlers.retain(|(id, _)| *id != self.id);
}
}
}
impl Debug for HandlerGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Guard").field("id", &self.id).finish()
}
}
impl Handlers {
pub fn new() -> Handlers {
let handlers = Arc::new(Mutex::new(vec![]));
let next_id = Arc::new(Sequence::default());
Handlers { handlers, next_id }
}
/// Registers a new handler and returns an RAII guard which will unregister the handler when
/// dropped.
pub fn register(&self, handler: Handler) -> Result<HandlerGuard, ShellError> {
let id = self.next_id.next()?;
if let Ok(mut handlers) = self.handlers.lock() {
handlers.push((id, handler));
}
Ok(HandlerGuard {
id,
handlers: Arc::clone(&self.handlers),
})
}
/// Registers a new handler which persists for the entire process lifetime.
///
/// Only use this for handlers which should exist for the lifetime of the program.
/// You should prefer to use `register` with a `HandlerGuard` when possible.
pub fn register_unguarded(&self, handler: Handler) -> Result<(), ShellError> {
let id = self.next_id.next()?;
if let Ok(mut handlers) = self.handlers.lock() {
handlers.push((id, handler));
}
Ok(())
}
/// Runs all registered handlers.
pub fn run(&self, action: SignalAction) {
if let Ok(handlers) = self.handlers.lock() {
for (_, handler) in handlers.iter() {
handler(action);
}
}
}
}
impl Default for Handlers {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
#[test]
/// Tests registering and running multiple handlers.
fn test_multiple_handlers() {
let handlers = Handlers::new();
let called1 = Arc::new(AtomicBool::new(false));
let called2 = Arc::new(AtomicBool::new(false));
let called1_clone = Arc::clone(&called1);
let called2_clone = Arc::clone(&called2);
let _guard1 = handlers.register(Box::new(move |_| {
called1_clone.store(true, Ordering::SeqCst);
}));
let _guard2 = handlers.register(Box::new(move |_| {
called2_clone.store(true, Ordering::SeqCst);
}));
handlers.run(SignalAction::Interrupt);
assert!(called1.load(Ordering::SeqCst));
assert!(called2.load(Ordering::SeqCst));
}
#[test]
/// Tests the dropping of a guard and ensuring the handler is unregistered.
fn test_guard_drop() {
let handlers = Handlers::new();
let called = Arc::new(AtomicBool::new(false));
let called_clone = Arc::clone(&called);
let guard = handlers.register(Box::new(move |_| {
called_clone.store(true, Ordering::Relaxed);
}));
// Ensure the handler is registered
assert_eq!(handlers.handlers.lock().unwrap().len(), 1);
drop(guard);
// Ensure the handler is removed after dropping the guard
assert_eq!(handlers.handlers.lock().unwrap().len(), 0);
handlers.run(SignalAction::Interrupt);
// Ensure the handler is not called after being dropped
assert!(!called.load(Ordering::Relaxed));
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/pipeline/list_stream.rs | crates/nu-protocol/src/pipeline/list_stream.rs | //! Module managing the streaming of individual [`Value`]s as a [`ListStream`] between pipeline
//! elements
//!
//! For more general infos regarding our pipelining model refer to [`PipelineData`]
use crate::{Config, PipelineData, ShellError, Signals, Span, Value};
use std::fmt::Debug;
pub type ValueIterator = Box<dyn Iterator<Item = Value> + Send + 'static>;
/// A potentially infinite, interruptible stream of [`Value`]s.
///
/// In practice, a "stream" here means anything which can be iterated and produces Values.
/// Like other iterators in Rust, observing values from this stream will drain the items
/// as you view them and the stream cannot be replayed.
pub struct ListStream {
stream: ValueIterator,
span: Span,
caller_spans: Vec<Span>,
}
impl ListStream {
/// Create a new [`ListStream`] from a [`Value`] `Iterator`.
pub fn new(
iter: impl Iterator<Item = Value> + Send + 'static,
span: Span,
signals: Signals,
) -> Self {
Self {
stream: Box::new(InterruptIter::new(iter, signals)),
span,
caller_spans: vec![],
}
}
/// Returns the [`Span`] associated with this [`ListStream`].
pub fn span(&self) -> Span {
self.span
}
/// Push a caller [`Span`] to the bytestream, it's useful to construct a backtrace.
pub fn push_caller_span(&mut self, span: Span) {
if span != self.span {
self.caller_spans.push(span)
}
}
/// Get all caller [`Span`], it's useful to construct a backtrace.
pub fn get_caller_spans(&self) -> &Vec<Span> {
&self.caller_spans
}
/// Changes the [`Span`] associated with this [`ListStream`].
pub fn with_span(mut self, span: Span) -> Self {
self.span = span;
self
}
/// Convert a [`ListStream`] into its inner [`Value`] `Iterator`.
pub fn into_inner(self) -> ValueIterator {
self.stream
}
/// Take a single value from the inner `Iterator`, modifying the stream.
pub fn next_value(&mut self) -> Option<Value> {
self.stream.next()
}
/// Converts each value in a [`ListStream`] into a string and then joins the strings together
/// using the given separator.
pub fn into_string(self, separator: &str, config: &Config) -> String {
self.into_iter()
.map(|val| val.to_expanded_string(", ", config))
.collect::<Vec<String>>()
.join(separator)
}
/// Collect the values of a [`ListStream`] into a list [`Value`].
///
/// If any of the values in the stream is a [Value::Error], its inner [ShellError] is returned.
pub fn into_value(self) -> Result<Value, ShellError> {
Ok(Value::list(
self.stream
.map(Value::unwrap_error)
.collect::<Result<_, _>>()?,
self.span,
))
}
/// Collect the values of a [`ListStream`] into a [`Value::List`], preserving [Value::Error]
/// items for debugging purposes.
pub fn into_debug_value(self) -> Value {
Value::list(self.stream.collect(), self.span)
}
/// Consume all values in the stream, returning an error if any of the values is a `Value::Error`.
pub fn drain(self) -> Result<(), ShellError> {
for next in self {
if let Value::Error { error, .. } = next {
return Err(*error);
}
}
Ok(())
}
/// Modify the inner iterator of a [`ListStream`] using a function.
///
/// This can be used to call any number of standard iterator functions on the [`ListStream`].
/// E.g., `take`, `filter`, `step_by`, and more.
///
/// ```
/// use nu_protocol::{ListStream, Signals, Span, Value};
///
/// let span = Span::unknown();
/// let stream = ListStream::new(std::iter::repeat(Value::int(0, span)), span, Signals::empty());
/// let new_stream = stream.modify(|iter| iter.take(100));
/// ```
pub fn modify<I>(self, f: impl FnOnce(ValueIterator) -> I) -> Self
where
I: Iterator<Item = Value> + Send + 'static,
{
Self {
stream: Box::new(f(self.stream)),
span: self.span,
caller_spans: self.caller_spans,
}
}
/// Create a new [`ListStream`] whose values are the results of applying the given function
/// to each of the values in the original [`ListStream`].
pub fn map(self, mapping: impl FnMut(Value) -> Value + Send + 'static) -> Self {
self.modify(|iter| iter.map(mapping))
}
}
impl Debug for ListStream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ListStream").finish()
}
}
impl IntoIterator for ListStream {
type Item = Value;
type IntoIter = IntoIter;
fn into_iter(self) -> Self::IntoIter {
IntoIter {
stream: self.into_inner(),
}
}
}
impl From<ListStream> for PipelineData {
fn from(stream: ListStream) -> Self {
Self::list_stream(stream, None)
}
}
pub struct IntoIter {
stream: ValueIterator,
}
impl Iterator for IntoIter {
type Item = Value;
fn next(&mut self) -> Option<Self::Item> {
self.stream.next()
}
}
struct InterruptIter<I: Iterator> {
iter: I,
signals: Signals,
}
impl<I: Iterator> InterruptIter<I> {
fn new(iter: I, signals: Signals) -> Self {
Self { iter, signals }
}
}
impl<I: Iterator> Iterator for InterruptIter<I> {
type Item = <I as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item> {
if self.signals.interrupted() {
None
} else {
self.iter.next()
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/pipeline/pipeline_data.rs | crates/nu-protocol/src/pipeline/pipeline_data.rs | #[cfg(feature = "os")]
use crate::process::ExitStatusFuture;
use crate::{
ByteStream, ByteStreamSource, ByteStreamType, Config, ListStream, OutDest, PipelineMetadata,
Range, ShellError, Signals, Span, Type, Value,
ast::{Call, PathMember},
engine::{EngineState, Stack},
location,
shell_error::{io::IoError, location::Location},
};
use std::{
borrow::Cow,
io::Write,
ops::Deref,
sync::{Arc, Mutex},
};
const LINE_ENDING_PATTERN: &[char] = &['\r', '\n'];
/// The foundational abstraction for input and output to commands
///
/// This represents either a single Value or a stream of values coming into the command or leaving a command.
///
/// A note on implementation:
///
/// We've tried a few variations of this structure. Listing these below so we have a record.
///
/// * We tried always assuming a stream in Nushell. This was a great 80% solution, but it had some rough edges.
/// Namely, how do you know the difference between a single string and a list of one string. How do you know
/// when to flatten the data given to you from a data source into the stream or to keep it as an unflattened
/// list?
///
/// * We tried putting the stream into Value. This had some interesting properties as now commands "just worked
/// on values", but lead to a few unfortunate issues.
///
/// The first is that you can't easily clone Values in a way that felt largely immutable. For example, if
/// you cloned a Value which contained a stream, and in one variable drained some part of it, then the second
/// variable would see different values based on what you did to the first.
///
/// To make this kind of mutation thread-safe, we would have had to produce a lock for the stream, which in
/// practice would have meant always locking the stream before reading from it. But more fundamentally, it
/// felt wrong in practice that observation of a value at runtime could affect other values which happen to
/// alias the same stream. By separating these, we don't have this effect. Instead, variables could get
/// concrete list values rather than streams, and be able to view them without non-local effects.
///
/// * A balance of the two approaches is what we've landed on: Values are thread-safe to pass, and we can stream
/// them into any sources. Streams are still available to model the infinite streams approach of original
/// Nushell.
#[derive(Debug)]
pub enum PipelineData {
Empty,
Value(Value, Option<PipelineMetadata>),
ListStream(ListStream, Option<PipelineMetadata>),
ByteStream(ByteStream, Option<PipelineMetadata>),
}
impl PipelineData {
pub const fn empty() -> PipelineData {
PipelineData::Empty
}
pub fn value(val: Value, metadata: impl Into<Option<PipelineMetadata>>) -> Self {
PipelineData::Value(val, metadata.into())
}
pub fn list_stream(stream: ListStream, metadata: impl Into<Option<PipelineMetadata>>) -> Self {
PipelineData::ListStream(stream, metadata.into())
}
pub fn byte_stream(stream: ByteStream, metadata: impl Into<Option<PipelineMetadata>>) -> Self {
PipelineData::ByteStream(stream, metadata.into())
}
pub fn metadata(&self) -> Option<PipelineMetadata> {
match self {
PipelineData::Empty => None,
PipelineData::Value(_, meta)
| PipelineData::ListStream(_, meta)
| PipelineData::ByteStream(_, meta) => meta.clone(),
}
}
pub fn set_metadata(mut self, metadata: Option<PipelineMetadata>) -> Self {
match &mut self {
PipelineData::Empty => {}
PipelineData::Value(_, meta)
| PipelineData::ListStream(_, meta)
| PipelineData::ByteStream(_, meta) => *meta = metadata,
}
self
}
pub fn is_nothing(&self) -> bool {
matches!(self, PipelineData::Value(Value::Nothing { .. }, ..))
|| matches!(self, PipelineData::Empty)
}
/// PipelineData doesn't always have a Span, but we can try!
pub fn span(&self) -> Option<Span> {
match self {
PipelineData::Empty => None,
PipelineData::Value(value, ..) => Some(value.span()),
PipelineData::ListStream(stream, ..) => Some(stream.span()),
PipelineData::ByteStream(stream, ..) => Some(stream.span()),
}
}
/// Change the span of the [`PipelineData`].
///
/// Returns `Value(Nothing)` with the given span if it was [`PipelineData::empty()`].
pub fn with_span(self, span: Span) -> Self {
match self {
PipelineData::Empty => PipelineData::value(Value::nothing(span), None),
PipelineData::Value(value, metadata) => {
PipelineData::value(value.with_span(span), metadata)
}
PipelineData::ListStream(stream, metadata) => {
PipelineData::list_stream(stream.with_span(span), metadata)
}
PipelineData::ByteStream(stream, metadata) => {
PipelineData::byte_stream(stream.with_span(span), metadata)
}
}
}
/// Get a type that is representative of the `PipelineData`.
///
/// The type returned here makes no effort to collect a stream, so it may be a different type
/// than would be returned by [`Value::get_type()`] on the result of
/// [`.into_value()`](Self::into_value).
///
/// Specifically, a `ListStream` results in `list<any>` rather than
/// the fully complete [`list`](Type::List) type (which would require knowing the contents),
/// and a `ByteStream` with [unknown](crate::ByteStreamType::Unknown) type results in
/// [`any`](Type::Any) rather than [`string`](Type::String) or [`binary`](Type::Binary).
pub fn get_type(&self) -> Type {
match self {
PipelineData::Empty => Type::Nothing,
PipelineData::Value(value, _) => value.get_type(),
PipelineData::ListStream(_, _) => Type::list(Type::Any),
PipelineData::ByteStream(stream, _) => stream.type_().into(),
}
}
/// Determine if the `PipelineData` is a [subtype](https://en.wikipedia.org/wiki/Subtyping) of `other`.
///
/// This check makes no effort to collect a stream, so it may be a different result
/// than would be returned by calling [`Value::is_subtype_of()`] on the result of
/// [`.into_value()`](Self::into_value).
///
/// A `ListStream` acts the same as an empty list type: it is a subtype of any [`list`](Type::List)
/// or [`table`](Type::Table) type. After converting to a value, it may become a more specific type.
/// For example, a `ListStream` is a subtype of `list<int>` and `list<string>`.
/// If calling [`.into_value()`](Self::into_value) results in a `list<int>`,
/// then the value would not be a subtype of `list<string>`, in contrast to the original `ListStream`.
///
/// A `ByteStream` is a subtype of [`string`](Type::String) if it is coercible into a string.
/// Likewise, a `ByteStream` is a subtype of [`binary`](Type::Binary) if it is coercible into a binary value.
pub fn is_subtype_of(&self, other: &Type) -> bool {
match (self, other) {
(_, Type::Any) => true,
(data, Type::OneOf(oneof)) => oneof.iter().any(|t| data.is_subtype_of(t)),
(PipelineData::Empty, Type::Nothing) => true,
(PipelineData::Value(val, ..), ty) => val.is_subtype_of(ty),
// a list stream could be a list with any type, including a table
(PipelineData::ListStream(..), Type::List(..) | Type::Table(..)) => true,
(PipelineData::ByteStream(stream, ..), Type::String)
if stream.type_().is_string_coercible() =>
{
true
}
(PipelineData::ByteStream(stream, ..), Type::Binary)
if stream.type_().is_binary_coercible() =>
{
true
}
(PipelineData::Empty, _) => false,
(PipelineData::ListStream(..), _) => false,
(PipelineData::ByteStream(..), _) => false,
}
}
pub fn into_value(self, span: Span) -> Result<Value, ShellError> {
match self {
PipelineData::Empty => Ok(Value::nothing(span)),
PipelineData::Value(value, ..) => {
if value.span() == Span::unknown() {
Ok(value.with_span(span))
} else {
Ok(value)
}
}
PipelineData::ListStream(stream, ..) => stream.into_value(),
PipelineData::ByteStream(stream, ..) => stream.into_value(),
}
}
/// Converts any `Value` variant that can be represented as a stream into its stream variant.
///
/// This means that lists and ranges are converted into list streams, and strings and binary are
/// converted into byte streams.
///
/// Returns an `Err` with the original stream if the variant couldn't be converted to a stream
/// variant. If the variant is already a stream variant, it is returned as-is.
pub fn try_into_stream(self, engine_state: &EngineState) -> Result<PipelineData, PipelineData> {
let span = self.span().unwrap_or(Span::unknown());
match self {
PipelineData::ListStream(..) | PipelineData::ByteStream(..) => Ok(self),
PipelineData::Value(Value::List { .. } | Value::Range { .. }, ref metadata) => {
let metadata = metadata.clone();
Ok(PipelineData::list_stream(
ListStream::new(self.into_iter(), span, engine_state.signals().clone()),
metadata,
))
}
PipelineData::Value(Value::String { val, .. }, metadata) => {
Ok(PipelineData::byte_stream(
ByteStream::read_string(val, span, engine_state.signals().clone()),
metadata,
))
}
PipelineData::Value(Value::Binary { val, .. }, metadata) => {
Ok(PipelineData::byte_stream(
ByteStream::read_binary(val, span, engine_state.signals().clone()),
metadata,
))
}
_ => Err(self),
}
}
/// Drain and write this [`PipelineData`] to `dest`.
///
/// Values are converted to bytes and separated by newlines if this is a `ListStream`.
pub fn write_to(self, mut dest: impl Write) -> Result<(), ShellError> {
match self {
PipelineData::Empty => Ok(()),
PipelineData::Value(value, ..) => {
let bytes = value_to_bytes(value)?;
dest.write_all(&bytes).map_err(|err| {
IoError::new_internal(
err,
"Could not write PipelineData to dest",
crate::location!(),
)
})?;
dest.flush().map_err(|err| {
IoError::new_internal(
err,
"Could not flush PipelineData to dest",
crate::location!(),
)
})?;
Ok(())
}
PipelineData::ListStream(stream, ..) => {
for value in stream {
let bytes = value_to_bytes(value)?;
dest.write_all(&bytes).map_err(|err| {
IoError::new_internal(
err,
"Could not write PipelineData to dest",
crate::location!(),
)
})?;
dest.write_all(b"\n").map_err(|err| {
IoError::new_internal(
err,
"Could not write linebreak after PipelineData to dest",
crate::location!(),
)
})?;
}
dest.flush().map_err(|err| {
IoError::new_internal(
err,
"Could not flush PipelineData to dest",
crate::location!(),
)
})?;
Ok(())
}
PipelineData::ByteStream(stream, ..) => stream.write_to(dest),
}
}
/// Drain this [`PipelineData`] according to the current stdout [`OutDest`]s in `stack`.
///
/// For [`OutDest::Pipe`] and [`OutDest::PipeSeparate`], this will return the [`PipelineData`]
/// as is. For [`OutDest::Value`], this will collect into a value and return it. For
/// [`OutDest::Print`], the [`PipelineData`] is drained and printed. Otherwise, the
/// [`PipelineData`] is drained, but only printed if it is the output of an external command.
pub fn drain_to_out_dests(
self,
engine_state: &EngineState,
stack: &mut Stack,
) -> Result<Self, ShellError> {
match stack.pipe_stdout().unwrap_or(&OutDest::Inherit) {
OutDest::Print => {
self.print_table(engine_state, stack, false, false)?;
Ok(Self::Empty)
}
OutDest::Pipe | OutDest::PipeSeparate => Ok(self),
OutDest::Value => {
let metadata = self.metadata();
let span = self.span().unwrap_or(Span::unknown());
self.into_value(span).map(|val| Self::Value(val, metadata))
}
OutDest::File(file) => {
self.write_to(file.as_ref())?;
Ok(Self::Empty)
}
OutDest::Null | OutDest::Inherit => {
self.drain()?;
Ok(Self::Empty)
}
}
}
pub fn drain(self) -> Result<(), ShellError> {
match self {
Self::Empty => Ok(()),
Self::Value(Value::Error { error, .. }, ..) => Err(*error),
Self::Value(..) => Ok(()),
Self::ListStream(stream, ..) => stream.drain(),
Self::ByteStream(stream, ..) => stream.drain(),
}
}
/// Try convert from self into iterator
///
/// It returns Err if the `self` cannot be converted to an iterator.
///
/// The `span` should be the span of the command or operation that would raise an error.
pub fn into_iter_strict(self, span: Span) -> Result<PipelineIterator, ShellError> {
Ok(PipelineIterator(match self {
PipelineData::Value(value, ..) => {
let val_span = value.span();
match value {
Value::List { vals, .. } => PipelineIteratorInner::ListStream(
ListStream::new(vals.into_iter(), val_span, Signals::empty()).into_iter(),
),
Value::Binary { val, .. } => PipelineIteratorInner::ListStream(
ListStream::new(
val.into_iter().map(move |x| Value::int(x as i64, val_span)),
val_span,
Signals::empty(),
)
.into_iter(),
),
Value::Range { val, .. } => PipelineIteratorInner::ListStream(
ListStream::new(
val.into_range_iter(val_span, Signals::empty()),
val_span,
Signals::empty(),
)
.into_iter(),
),
// Propagate errors by explicitly matching them before the final case.
Value::Error { error, .. } => return Err(*error),
other => {
return Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "list, binary, range, or byte stream".into(),
wrong_type: other.get_type().to_string(),
dst_span: span,
src_span: val_span,
});
}
}
}
PipelineData::ListStream(stream, ..) => {
PipelineIteratorInner::ListStream(stream.into_iter())
}
PipelineData::Empty => {
return Err(ShellError::OnlySupportsThisInputType {
exp_input_type: "list, binary, range, or byte stream".into(),
wrong_type: "null".into(),
dst_span: span,
src_span: span,
});
}
PipelineData::ByteStream(stream, ..) => {
if let Some(chunks) = stream.chunks() {
PipelineIteratorInner::ByteStream(chunks)
} else {
PipelineIteratorInner::Empty
}
}
}))
}
pub fn collect_string(self, separator: &str, config: &Config) -> Result<String, ShellError> {
match self {
PipelineData::Empty => Ok(String::new()),
PipelineData::Value(value, ..) => Ok(value.to_expanded_string(separator, config)),
PipelineData::ListStream(stream, ..) => Ok(stream.into_string(separator, config)),
PipelineData::ByteStream(stream, ..) => stream.into_string(),
}
}
/// Retrieves string from pipeline data.
///
/// As opposed to `collect_string` this raises error rather than converting non-string values.
/// The `span` will be used if `ListStream` is encountered since it doesn't carry a span.
pub fn collect_string_strict(
self,
span: Span,
) -> Result<(String, Span, Option<PipelineMetadata>), ShellError> {
match self {
PipelineData::Empty => Ok((String::new(), span, None)),
PipelineData::Value(Value::String { val, .. }, metadata) => Ok((val, span, metadata)),
PipelineData::Value(val, ..) => Err(ShellError::TypeMismatch {
err_message: "string".into(),
span: val.span(),
}),
PipelineData::ListStream(..) => Err(ShellError::TypeMismatch {
err_message: "string".into(),
span,
}),
PipelineData::ByteStream(stream, metadata) => {
let span = stream.span();
Ok((stream.into_string()?, span, metadata))
}
}
}
pub fn follow_cell_path(
self,
cell_path: &[PathMember],
head: Span,
) -> Result<Value, ShellError> {
match self {
// FIXME: there are probably better ways of doing this
PipelineData::ListStream(stream, ..) => Value::list(stream.into_iter().collect(), head)
.follow_cell_path(cell_path)
.map(Cow::into_owned),
PipelineData::Value(v, ..) => v.follow_cell_path(cell_path).map(Cow::into_owned),
PipelineData::Empty => Err(ShellError::IncompatiblePathAccess {
type_name: "empty pipeline".to_string(),
span: head,
}),
PipelineData::ByteStream(stream, ..) => Err(ShellError::IncompatiblePathAccess {
type_name: stream.type_().describe().to_owned(),
span: stream.span(),
}),
}
}
/// Simplified mapper to help with simple values also. For full iterator support use `.into_iter()` instead
pub fn map<F>(self, mut f: F, signals: &Signals) -> Result<PipelineData, ShellError>
where
Self: Sized,
F: FnMut(Value) -> Value + 'static + Send,
{
match self {
PipelineData::Value(value, metadata) => {
let span = value.span();
let pipeline = match value {
Value::List { vals, .. } => vals
.into_iter()
.map(f)
.into_pipeline_data(span, signals.clone()),
Value::Range { val, .. } => val
.into_range_iter(span, Signals::empty())
.map(f)
.into_pipeline_data(span, signals.clone()),
value => match f(value) {
Value::Error { error, .. } => return Err(*error),
v => v.into_pipeline_data(),
},
};
Ok(pipeline.set_metadata(metadata))
}
PipelineData::Empty => Ok(PipelineData::empty()),
PipelineData::ListStream(stream, metadata) => {
Ok(PipelineData::list_stream(stream.map(f), metadata))
}
PipelineData::ByteStream(stream, metadata) => {
Ok(f(stream.into_value()?).into_pipeline_data_with_metadata(metadata))
}
}
}
/// Simplified flatmapper. For full iterator support use `.into_iter()` instead
pub fn flat_map<U, F>(self, mut f: F, signals: &Signals) -> Result<PipelineData, ShellError>
where
Self: Sized,
U: IntoIterator<Item = Value> + 'static,
<U as IntoIterator>::IntoIter: 'static + Send,
F: FnMut(Value) -> U + 'static + Send,
{
match self {
PipelineData::Empty => Ok(PipelineData::empty()),
PipelineData::Value(value, metadata) => {
let span = value.span();
let pipeline = match value {
Value::List { vals, .. } => vals
.into_iter()
.flat_map(f)
.into_pipeline_data(span, signals.clone()),
Value::Range { val, .. } => val
.into_range_iter(span, Signals::empty())
.flat_map(f)
.into_pipeline_data(span, signals.clone()),
value => f(value)
.into_iter()
.into_pipeline_data(span, signals.clone()),
};
Ok(pipeline.set_metadata(metadata))
}
PipelineData::ListStream(stream, metadata) => Ok(PipelineData::list_stream(
stream.modify(|iter| iter.flat_map(f)),
metadata,
)),
PipelineData::ByteStream(stream, metadata) => {
// TODO: is this behavior desired / correct ?
let span = stream.span();
let iter = match String::from_utf8(stream.into_bytes()?) {
Ok(mut str) => {
str.truncate(str.trim_end_matches(LINE_ENDING_PATTERN).len());
f(Value::string(str, span))
}
Err(err) => f(Value::binary(err.into_bytes(), span)),
};
Ok(iter.into_iter().into_pipeline_data_with_metadata(
span,
signals.clone(),
metadata,
))
}
}
}
pub fn filter<F>(self, mut f: F, signals: &Signals) -> Result<PipelineData, ShellError>
where
Self: Sized,
F: FnMut(&Value) -> bool + 'static + Send,
{
match self {
PipelineData::Empty => Ok(PipelineData::empty()),
PipelineData::Value(value, metadata) => {
let span = value.span();
let pipeline = match value {
Value::List { vals, .. } => vals
.into_iter()
.filter(f)
.into_pipeline_data(span, signals.clone()),
Value::Range { val, .. } => val
.into_range_iter(span, Signals::empty())
.filter(f)
.into_pipeline_data(span, signals.clone()),
value => {
if f(&value) {
value.into_pipeline_data()
} else {
Value::nothing(span).into_pipeline_data()
}
}
};
Ok(pipeline.set_metadata(metadata))
}
PipelineData::ListStream(stream, metadata) => Ok(PipelineData::list_stream(
stream.modify(|iter| iter.filter(f)),
metadata,
)),
PipelineData::ByteStream(stream, metadata) => {
// TODO: is this behavior desired / correct ?
let span = stream.span();
let value = match String::from_utf8(stream.into_bytes()?) {
Ok(mut str) => {
str.truncate(str.trim_end_matches(LINE_ENDING_PATTERN).len());
Value::string(str, span)
}
Err(err) => Value::binary(err.into_bytes(), span),
};
let value = if f(&value) {
value
} else {
Value::nothing(span)
};
Ok(value.into_pipeline_data_with_metadata(metadata))
}
}
}
/// Try to convert Value from Value::Range to Value::List.
/// This is useful to expand Value::Range into array notation, specifically when
/// converting `to json` or `to nuon`.
/// `1..3 | to XX -> [1,2,3]`
pub fn try_expand_range(self) -> Result<PipelineData, ShellError> {
match self {
PipelineData::Value(v, metadata) => {
let span = v.span();
match v {
Value::Range { val, .. } => {
match *val {
Range::IntRange(range) => {
if range.is_unbounded() {
return Err(ShellError::GenericError {
error: "Cannot create range".into(),
msg: "Unbounded ranges are not allowed when converting to this format".into(),
span: Some(span),
help: Some("Consider using ranges with valid start and end point.".into()),
inner: vec![],
});
}
}
Range::FloatRange(range) => {
if range.is_unbounded() {
return Err(ShellError::GenericError {
error: "Cannot create range".into(),
msg: "Unbounded ranges are not allowed when converting to this format".into(),
span: Some(span),
help: Some("Consider using ranges with valid start and end point.".into()),
inner: vec![],
});
}
}
}
let range_values: Vec<Value> =
val.into_range_iter(span, Signals::empty()).collect();
Ok(PipelineData::value(Value::list(range_values, span), None))
}
x => Ok(PipelineData::value(x, metadata)),
}
}
_ => Ok(self),
}
}
/// Consume and print self data immediately, formatted using table command.
///
/// This does not respect the display_output hook. If a value is being printed out by a command,
/// this function should be used. Otherwise, `nu_cli::util::print_pipeline` should be preferred.
///
/// `no_newline` controls if we need to attach newline character to output.
/// `to_stderr` controls if data is output to stderr, when the value is false, the data is output to stdout.
pub fn print_table(
self,
engine_state: &EngineState,
stack: &mut Stack,
no_newline: bool,
to_stderr: bool,
) -> Result<(), ShellError> {
match self {
// Print byte streams directly as long as they aren't binary.
PipelineData::ByteStream(stream, ..) if stream.type_() != ByteStreamType::Binary => {
stream.print(to_stderr)
}
_ => {
// If the table function is in the declarations, then we can use it
// to create the table value that will be printed in the terminal
if let Some(decl_id) = engine_state.table_decl_id {
let command = engine_state.get_decl(decl_id);
if command.block_id().is_some() {
self.write_all_and_flush(engine_state, no_newline, to_stderr)
} else {
let call = Call::new(Span::new(0, 0));
let table = command.run(engine_state, stack, &(&call).into(), self)?;
table.write_all_and_flush(engine_state, no_newline, to_stderr)
}
} else {
self.write_all_and_flush(engine_state, no_newline, to_stderr)
}
}
}
}
/// Consume and print self data without any extra formatting.
///
/// This does not use the `table` command to format data, and also prints binary values and
/// streams in their raw format without generating a hexdump first.
///
/// `no_newline` controls if we need to attach newline character to output.
/// `to_stderr` controls if data is output to stderr, when the value is false, the data is output to stdout.
pub fn print_raw(
self,
engine_state: &EngineState,
no_newline: bool,
to_stderr: bool,
) -> Result<(), ShellError> {
let span = self.span();
if let PipelineData::Value(Value::Binary { val: bytes, .. }, _) = self {
if to_stderr {
write_all_and_flush(
bytes,
&mut std::io::stderr().lock(),
"stderr",
span,
engine_state.signals(),
)?;
} else {
write_all_and_flush(
bytes,
&mut std::io::stdout().lock(),
"stdout",
span,
engine_state.signals(),
)?;
}
Ok(())
} else {
self.write_all_and_flush(engine_state, no_newline, to_stderr)
}
}
fn write_all_and_flush(
self,
engine_state: &EngineState,
no_newline: bool,
to_stderr: bool,
) -> Result<(), ShellError> {
let span = self.span();
if let PipelineData::ByteStream(stream, ..) = self {
// Copy ByteStreams directly
stream.print(to_stderr)
} else {
let config = engine_state.get_config();
for item in self {
let mut out = if let Value::Error { error, .. } = item {
return Err(*error);
} else {
item.to_expanded_string("\n", config)
};
if !no_newline {
out.push('\n');
}
if to_stderr {
write_all_and_flush(
out,
&mut std::io::stderr().lock(),
"stderr",
span,
engine_state.signals(),
)?;
} else {
write_all_and_flush(
out,
&mut std::io::stdout().lock(),
"stdout",
span,
engine_state.signals(),
)?;
}
}
Ok(())
}
}
pub fn unsupported_input_error(
self,
expected_type: impl Into<String>,
span: Span,
) -> ShellError {
match self {
PipelineData::Empty => ShellError::PipelineEmpty { dst_span: span },
PipelineData::Value(value, ..) => ShellError::OnlySupportsThisInputType {
exp_input_type: expected_type.into(),
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | true |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/pipeline/mod.rs | crates/nu-protocol/src/pipeline/mod.rs | pub mod byte_stream;
mod handlers;
pub mod list_stream;
mod metadata;
mod out_dest;
mod pipeline_data;
mod signals;
pub use byte_stream::*;
pub use handlers::*;
pub use list_stream::*;
pub use metadata::*;
pub use out_dest::*;
pub use pipeline_data::*;
pub use signals::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/pipeline/out_dest.rs | crates/nu-protocol/src/pipeline/out_dest.rs | use std::{fs::File, io, process::Stdio, sync::Arc};
/// Describes where to direct the stdout or stderr output stream of external command to.
#[derive(Debug, Clone)]
pub enum OutDest {
/// Redirect the stdout and/or stderr of one command as the input for the next command in the pipeline.
///
/// The output pipe will be available as the `stdout` of [`ChildProcess`](crate::process::ChildProcess).
///
/// If stdout and stderr are both set to `Pipe`,
/// then they will combined into the `stdout` of [`ChildProcess`](crate::process::ChildProcess).
Pipe,
/// Redirect the stdout and/or stderr of one command as the input for the next command in the pipeline.
///
/// The output stream(s) will be available in the `stdout` or `stderr` of [`ChildProcess`](crate::process::ChildProcess).
///
/// This is similar to `Pipe` but will never combine stdout and stderr
/// or place an external command's stderr into `stdout` of [`ChildProcess`](crate::process::ChildProcess).
PipeSeparate,
/// Signifies the result of the pipeline will be immediately collected into a value after this command.
///
/// So, it is fine to collect the stream ahead of time in the current command.
Value,
/// Ignore output.
///
/// This will forward output to the null device for the platform.
Null,
/// Output to nushell's stdout or stderr (only for external commands).
///
/// This causes external commands to inherit nushell's stdout or stderr. This also causes
/// [`ListStream`](crate::ListStream)s to be drained, but not to be printed.
Inherit,
/// Print to nushell's stdout or stderr.
///
/// This is just like `Inherit`, except that [`ListStream`](crate::ListStream)s and
/// [`Value`](crate::Value)s are also printed.
Print,
/// Redirect output to a file.
File(Arc<File>), // Arc<File>, since we sometimes need to clone `OutDest` into iterators, etc.
}
impl From<File> for OutDest {
fn from(file: File) -> Self {
Arc::new(file).into()
}
}
impl From<Arc<File>> for OutDest {
fn from(file: Arc<File>) -> Self {
Self::File(file)
}
}
impl TryFrom<&OutDest> for Stdio {
type Error = io::Error;
fn try_from(out_dest: &OutDest) -> Result<Self, Self::Error> {
match out_dest {
OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value => Ok(Self::piped()),
OutDest::Null => Ok(Self::null()),
OutDest::Print | OutDest::Inherit => Ok(Self::inherit()),
OutDest::File(file) => Ok(file.try_clone()?.into()),
}
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/pipeline/metadata.rs | crates/nu-protocol/src/pipeline/metadata.rs | use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::Record;
/// Metadata that is valid for the whole [`PipelineData`](crate::PipelineData)
///
/// ## Custom Metadata
///
/// The `custom` field allows commands and plugins to attach arbitrary metadata to pipeline data.
/// To avoid key collisions, it is recommended to use namespaced keys with an underscore separator:
///
/// - `"http_response"` - HTTP response metadata (status, headers, etc.)
/// - `"polars_schema"` - DataFrame schema information
/// - `"custom_plugin_field"` - Plugin-specific metadata
///
/// This convention helps ensure different commands and plugins don't overwrite each other's metadata.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct PipelineMetadata {
pub data_source: DataSource,
pub content_type: Option<String>,
#[serde(default)]
pub custom: Record,
}
impl PipelineMetadata {
pub fn with_data_source(self, data_source: DataSource) -> Self {
Self {
data_source,
..self
}
}
pub fn with_content_type(self, content_type: Option<String>) -> Self {
Self {
content_type,
..self
}
}
/// Transform metadata for the `collect` operation.
///
/// After collecting a stream into a value, `FilePath` data sources are no longer meaningful
/// and should be converted to `None`. If all metadata fields become empty after this
/// transformation, returns `None` to avoid carrying around empty metadata.
pub fn for_collect(self) -> Option<Self> {
let Self {
data_source,
content_type,
custom,
} = self;
// Transform FilePath to None after collect
let data_source = match data_source {
DataSource::FilePath(_) => DataSource::None,
other => other,
};
// Return None if completely empty
if matches!(data_source, DataSource::None) && content_type.is_none() && custom.is_empty() {
None
} else {
Some(Self {
data_source,
content_type,
custom,
})
}
}
}
/// Describes where the particular [`PipelineMetadata`] originates.
///
/// This can either be a particular family of commands (useful so downstream commands can adjust
/// the presentation e.g. `Ls`) or the opened file to protect against overwrite-attempts properly.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub enum DataSource {
Ls,
HtmlThemes,
FilePath(PathBuf),
#[default]
None,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/pipeline/signals.rs | crates/nu-protocol/src/pipeline/signals.rs | use crate::{ShellError, Span};
use nu_glob::Interruptible;
use serde::{Deserialize, Serialize};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
/// Used to check for signals to suspend or terminate the execution of Nushell code.
///
/// For now, this struct only supports interruption (ctrl+c or SIGINT).
#[derive(Debug, Clone)]
pub struct Signals {
signals: Option<Arc<AtomicBool>>,
}
impl Signals {
/// A [`Signals`] that is not hooked up to any event/signals source.
///
/// So, this [`Signals`] will never be interrupted.
pub const EMPTY: Self = Signals { signals: None };
/// Create a new [`Signals`] with `ctrlc` as the interrupt source.
///
/// Once `ctrlc` is set to `true`, [`check`](Self::check) will error
/// and [`interrupted`](Self::interrupted) will return `true`.
pub fn new(ctrlc: Arc<AtomicBool>) -> Self {
Self {
signals: Some(ctrlc),
}
}
/// Create a [`Signals`] that is not hooked up to any event/signals source.
///
/// So, the returned [`Signals`] will never be interrupted.
///
/// This should only be used in test code, or if the stream/iterator being created
/// already has an underlying [`Signals`].
pub const fn empty() -> Self {
Self::EMPTY
}
/// Returns an `Err` if an interrupt has been triggered.
///
/// Otherwise, returns `Ok`.
#[inline]
pub fn check(&self, span: &Span) -> Result<(), ShellError> {
#[inline]
#[cold]
fn interrupt_error(span: &Span) -> Result<(), ShellError> {
Err(ShellError::Interrupted { span: *span })
}
if self.interrupted() {
interrupt_error(span)
} else {
Ok(())
}
}
/// Triggers an interrupt.
pub fn trigger(&self) {
if let Some(signals) = &self.signals {
signals.store(true, Ordering::Relaxed);
}
}
/// Returns whether an interrupt has been triggered.
#[inline]
pub fn interrupted(&self) -> bool {
self.signals
.as_deref()
.is_some_and(|b| b.load(Ordering::Relaxed))
}
pub(crate) fn is_empty(&self) -> bool {
self.signals.is_none()
}
pub fn reset(&self) {
if let Some(signals) = &self.signals {
signals.store(false, Ordering::Relaxed);
}
}
}
impl Interruptible for Signals {
#[inline]
fn interrupted(&self) -> bool {
self.interrupted()
}
}
/// The types of things that can be signaled. It's anticipated this will change as we learn more
/// about how we'd like signals to be handled.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SignalAction {
Interrupt,
Reset,
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/tests/into_config.rs | crates/nu-protocol/tests/into_config.rs | use nu_test_support::{nu, nu_repl_code};
#[test]
fn config_is_mutable() {
let actual = nu!(nu_repl_code(&[
r"$env.config = { ls: { clickable_links: true } }",
"$env.config.ls.clickable_links = false;",
"$env.config.ls.clickable_links"
]));
assert_eq!(actual.out, "false");
}
#[test]
fn config_preserved_after_do() {
let actual = nu!(nu_repl_code(&[
r"$env.config = { ls: { clickable_links: true } }",
"do -i { $env.config.ls.clickable_links = false }",
"$env.config.ls.clickable_links"
]));
assert_eq!(actual.out, "true");
}
#[test]
fn config_affected_when_mutated() {
let actual = nu!(nu_repl_code(&[
r#"$env.config = { filesize: { unit: binary } }"#,
r#"$env.config = { filesize: { unit: metric } }"#,
"20MB | into string"
]));
assert_eq!(actual.out, "20.0 MB");
}
#[test]
fn config_affected_when_deep_mutated() {
let actual = nu!(cwd: "crates/nu-utils/src/default_files", nu_repl_code(&[
r#"source default_config.nu"#,
r#"$env.config.filesize.unit = 'binary'"#,
r#"20MiB | into string"#]));
assert_eq!(actual.out, "20.0 MiB");
}
#[test]
fn config_add_unsupported_key() {
let actual = nu!(cwd: "crates/nu-utils/src/default_files", nu_repl_code(&[
r#"source default_config.nu"#,
r#"$env.config.foo = 2"#,
r#";"#]));
assert!(
actual
.err
.contains("Unknown config option: $env.config.foo")
);
}
#[test]
fn config_add_unsupported_type() {
let actual = nu!(cwd: "crates/nu-utils/src/default_files", nu_repl_code(&[r#"source default_config.nu"#,
r#"$env.config.ls = '' "#,
r#";"#]));
assert!(actual.err.contains("Type mismatch"));
}
#[test]
fn config_add_unsupported_value() {
let actual = nu!(cwd: "crates/nu-utils/src/default_files", nu_repl_code(&[r#"source default_config.nu"#,
r#"$env.config.history.file_format = ''"#,
r#";"#]));
assert!(actual.err.contains("Invalid value"));
assert!(actual.err.contains("expected 'sqlite' or 'plaintext'"));
}
#[test]
#[ignore = "Figure out how to make test_bins::nu_repl() continue execution after shell errors"]
fn config_unsupported_key_reverted() {
let actual = nu!(cwd: "crates/nu-utils/src/default_files", nu_repl_code(&[r#"source default_config.nu"#,
r#"$env.config.foo = 1"#,
r#"'foo' in $env.config"#]));
assert_eq!(actual.out, "false");
}
#[test]
#[ignore = "Figure out how to make test_bins::nu_repl() continue execution after shell errors"]
fn config_unsupported_type_reverted() {
let actual = nu!(cwd: "crates/nu-utils/src/default_files", nu_repl_code(&[r#" source default_config.nu"#,
r#"$env.config.ls = ''"#,
r#"$env.config.ls | describe"#]));
assert_eq!(actual.out, "record");
}
#[test]
#[ignore = "Figure out how to make test_bins::nu_repl() continue execution after errors"]
fn config_unsupported_value_reverted() {
let actual = nu!(cwd: "crates/nu-utils/src/default_files", nu_repl_code(&[r#" source default_config.nu"#,
r#"$env.config.history.file_format = 'plaintext'"#,
r#"$env.config.history.file_format = ''"#,
r#"$env.config.history.file_format | to json"#]));
assert_eq!(actual.out, "\"plaintext\"");
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/tests/test_value.rs | crates/nu-protocol/tests/test_value.rs | use nu_protocol::{
Config, Span, Value,
engine::{EngineState, Stack},
};
use rstest::rstest;
#[test]
fn test_comparison_nothing() {
let values = vec![
Value::test_int(1),
Value::test_string("string"),
Value::test_float(1.0),
];
let nothing = Value::nothing(Span::test_data());
for value in values {
assert!(matches!(
value.eq(Span::test_data(), ¬hing, Span::test_data()),
Ok(Value::Bool { val: false, .. })
));
assert!(matches!(
value.ne(Span::test_data(), ¬hing, Span::test_data()),
Ok(Value::Bool { val: true, .. })
));
assert!(matches!(
nothing.eq(Span::test_data(), &value, Span::test_data()),
Ok(Value::Bool { val: false, .. })
));
assert!(matches!(
nothing.ne(Span::test_data(), &value, Span::test_data()),
Ok(Value::Bool { val: true, .. })
));
}
}
#[test]
fn test_float_equality_comparison() {
let values = vec![
(
Value::test_float(0.30000000000000004),
Value::test_float(0.3),
),
(
Value::test_float(0.1),
#[allow(clippy::excessive_precision)]
Value::test_float(0.10000000000000001),
),
(
Value::test_float(1.0000000000000002),
Value::test_float(1.0),
),
(
Value::test_float(2.220446049250313e-16),
Value::test_float(0.0),
),
(Value::test_float(1e-16), Value::test_float(0.0)),
(
Value::test_float((1e16 + 1.0) - 1e16),
Value::test_float(0.0),
),
(
Value::test_float(10000000000000000.0),
Value::test_float(10000000000000002.0),
),
(
Value::test_float(9007199254740992.0),
Value::test_float(9007199254740993.0),
),
(
Value::test_float(4503599627370496.0),
Value::test_float(4503599627370497.0),
),
(
Value::test_float(1.7976931348623157e308),
Value::test_float(1.7976931348623155e308),
),
(
Value::test_float(1.0),
Value::test_float(0.9999999999999999),
),
(
#[allow(clippy::approx_constant)]
Value::test_float(3.141592653589793),
Value::test_float(3.1415926535897927),
),
];
for value in values {
assert!(matches!(
value.0.eq(Span::test_data(), &value.1, Span::test_data()),
Ok(Value::Bool { val: true, .. })
));
assert!(matches!(
value.1.eq(Span::test_data(), &value.0, Span::test_data()),
Ok(Value::Bool { val: true, .. })
));
}
}
#[rstest]
#[case(365 * 24 * 3600 * 1_000_000_000, "52wk 1day")]
#[case( (((((((7 + 2) * 24 + 3) * 60 + 4) * 60) + 5) * 1000 + 6) * 1000 + 7) * 1000 + 8,
"1wk 2day 3hr 4min 5sec 6ms 7Β΅s 8ns")]
fn test_duration_to_string(#[case] in_ns: i64, #[case] expected: &str) {
let dur = Value::test_duration(in_ns);
assert_eq!(
expected,
dur.to_expanded_string("", &Config::default()),
"expected != observed"
);
}
#[test]
fn test_case_insensitive_env_var() {
let mut engine_state = EngineState::new();
let stack = Stack::new();
for (name, value) in std::env::vars() {
engine_state.add_env_var(name, Value::test_string(value));
}
let path_lower = engine_state.get_env_var_insensitive("path");
let path_upper = engine_state.get_env_var_insensitive("PATH");
let path_mixed = engine_state.get_env_var_insensitive("PaTh");
assert_eq!(path_lower, path_upper);
assert_eq!(path_lower, path_mixed);
let stack_path_lower = stack.get_env_var_insensitive(&engine_state, "path");
let stack_path_upper = stack.get_env_var_insensitive(&engine_state, "PATH");
let stack_path_mixed = stack.get_env_var_insensitive(&engine_state, "PaTh");
assert_eq!(stack_path_lower, stack_path_upper);
assert_eq!(stack_path_lower, stack_path_mixed);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/tests/test_signature.rs | crates/nu-protocol/tests/test_signature.rs | use nu_protocol::{Flag, PositionalArg, Signature, SyntaxShape};
#[test]
fn test_signature() {
let signature = Signature::new("new_signature");
let from_build = Signature::build("new_signature");
// asserting partial eq implementation
assert_eq!(signature, from_build);
// constructing signature with description
let signature = Signature::new("signature").description("example description");
assert_eq!(signature.description, "example description".to_string())
}
#[test]
fn test_signature_chained() {
let signature = Signature::new("new_signature")
.description("description")
.required("required", SyntaxShape::String, "required description")
.optional("optional", SyntaxShape::String, "optional description")
.required_named(
"req-named",
SyntaxShape::String,
"required named description",
Some('r'),
)
.named("named", SyntaxShape::String, "named description", Some('n'))
.switch("switch", "switch description", None)
.rest("rest", SyntaxShape::String, "rest description");
assert_eq!(signature.required_positional.len(), 1);
assert_eq!(signature.optional_positional.len(), 1);
assert_eq!(signature.named.len(), 3);
assert!(signature.rest_positional.is_some());
assert_eq!(signature.get_shorts(), vec!['r', 'n']);
assert_eq!(signature.get_names(), vec!["req-named", "named", "switch"]);
assert_eq!(signature.num_positionals(), 2);
assert_eq!(
signature.get_positional(0),
Some(&PositionalArg {
name: "required".to_string(),
desc: "required description".to_string(),
shape: SyntaxShape::String,
var_id: None,
default_value: None,
completion: None,
})
);
assert_eq!(
signature.get_positional(1),
Some(&PositionalArg {
name: "optional".to_string(),
desc: "optional description".to_string(),
shape: SyntaxShape::String,
var_id: None,
default_value: None,
completion: None,
})
);
assert_eq!(
signature.get_positional(2),
Some(&PositionalArg {
name: "rest".to_string(),
desc: "rest description".to_string(),
shape: SyntaxShape::String,
var_id: None,
default_value: None,
completion: None,
})
);
assert_eq!(
signature.get_long_flag("req-named"),
Some(Flag {
long: "req-named".to_string(),
short: Some('r'),
arg: Some(SyntaxShape::String),
required: true,
desc: "required named description".to_string(),
var_id: None,
default_value: None,
completion: None,
})
);
assert_eq!(
signature.get_short_flag('r'),
Some(Flag {
long: "req-named".to_string(),
short: Some('r'),
arg: Some(SyntaxShape::String),
required: true,
desc: "required named description".to_string(),
var_id: None,
default_value: None,
completion: None,
})
);
}
#[test]
#[should_panic(expected = "There may be duplicate short flags for '-n'")]
fn test_signature_same_short() {
// Creating signature with same short name should panic
Signature::new("new_signature")
.required_named(
"required-named",
SyntaxShape::String,
"required named description",
Some('n'),
)
.named("named", SyntaxShape::String, "named description", Some('n'));
}
#[test]
#[should_panic(expected = "There may be duplicate name flags for '--name'")]
fn test_signature_same_name() {
// Creating signature with same short name should panic
Signature::new("new-signature")
.required_named(
"name",
SyntaxShape::String,
"required named description",
Some('r'),
)
.named("name", SyntaxShape::String, "named description", Some('n'));
}
#[test]
fn test_signature_round_trip() {
let signature = Signature::new("new_signature")
.description("description")
.required("first", SyntaxShape::String, "first required")
.required("second", SyntaxShape::Int, "second required")
.optional("optional", SyntaxShape::String, "optional description")
.required_named(
"req-named",
SyntaxShape::String,
"required named description",
Some('r'),
)
.named("named", SyntaxShape::String, "named description", Some('n'))
.switch("switch", "switch description", None)
.rest("rest", SyntaxShape::String, "rest description")
.category(nu_protocol::Category::Conversions);
let string = serde_json::to_string_pretty(&signature).unwrap();
let returned: Signature = serde_json::from_str(&string).unwrap();
assert_eq!(signature.name, returned.name);
assert_eq!(signature.description, returned.description);
assert_eq!(signature.extra_description, returned.extra_description);
assert_eq!(signature.is_filter, returned.is_filter);
assert_eq!(signature.category, returned.category);
signature
.required_positional
.iter()
.zip(returned.required_positional.iter())
.for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));
signature
.optional_positional
.iter()
.zip(returned.optional_positional.iter())
.for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));
signature
.named
.iter()
.zip(returned.named.iter())
.for_each(|(lhs, rhs)| assert_eq!(lhs, rhs));
assert_eq!(signature.rest_positional, returned.rest_positional,);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/tests/mod.rs | crates/nu-protocol/tests/mod.rs | mod pipeline;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/tests/test_config.rs | crates/nu-protocol/tests/test_config.rs | use nu_test_support::{nu, nu_repl_code};
#[test]
fn filesize_mb() {
let code = &[
r#"$env.config = { filesize: { unit: MB } }"#,
r#"20MB | into string"#,
];
let actual = nu!(nu_repl_code(code));
assert_eq!(actual.out, "20.0 MB");
}
#[test]
fn filesize_mib() {
let code = &[
r#"$env.config = { filesize: { unit: MiB } }"#,
r#"20MiB | into string"#,
];
let actual = nu!(nu_repl_code(code));
assert_eq!(actual.out, "20.0 MiB");
}
#[test]
fn filesize_format_decimal() {
let code = &[
r#"$env.config = { filesize: { unit: metric } }"#,
r#"[2MB 2GB 2TB] | into string | to nuon"#,
];
let actual = nu!(nu_repl_code(code));
assert_eq!(actual.out, r#"["2.0 MB", "2.0 GB", "2.0 TB"]"#);
}
#[test]
fn filesize_format_binary() {
let code = &[
r#"$env.config = { filesize: { unit: binary } }"#,
r#"[2MiB 2GiB 2TiB] | into string | to nuon"#,
];
let actual = nu!(nu_repl_code(code));
assert_eq!(actual.out, r#"["2.0 MiB", "2.0 GiB", "2.0 TiB"]"#);
}
#[test]
fn fancy_default_errors() {
let code = nu_repl_code(&[
"$env.config.use_ansi_coloring = true",
r#"def force_error [x] {
error make {
msg: "oh no!"
label: {
text: "here's the error"
span: (metadata $x).span
}
}
}"#,
r#"force_error "My error""#,
]);
let actual = nu!(format!("try {{ {code} }}"));
assert_eq!(
actual.err,
"Error: \u{1b}[31mnu::shell::error\u{1b}[0m\n\n \u{1b}[31mΓ\u{1b}[0m oh no!\n ββ[\u{1b}[36;1;4mline2:1:13\u{1b}[0m]\n \u{1b}[2m1\u{1b}[0m β force_error \"My error\"\n Β· \u{1b}[35;1m ββββββ¬ββββ\u{1b}[0m\n Β· \u{1b}[35;1mβ°ββ \u{1b}[35;1mhere's the error\u{1b}[0m\u{1b}[0m\n β°ββββ\n\n"
);
}
#[test]
fn narratable_errors() {
let code = nu_repl_code(&[
r#"$env.config = { error_style: "plain" }"#,
r#"def force_error [x] {
error make {
msg: "oh no!"
label: {
text: "here's the error"
span: (metadata $x).span
}
}
}"#,
r#"force_error "my error""#,
]);
let actual = nu!(format!("try {{ {code} }}"));
assert_eq!(
actual.err,
r#"Error: oh no!
Diagnostic severity: error
Begin snippet for line2 starting at line 1, column 1
snippet line 1: force_error "my error"
label at line 1, columns 13 to 22: here's the error
diagnostic code: nu::shell::error
"#,
);
}
#[test]
fn plugins() {
let code = &[
r#"$env.config = { plugins: { nu_plugin_config: { key: value } } }"#,
r#"$env.config.plugins"#,
];
let actual = nu!(nu_repl_code(code));
assert_eq!(actual.out, r#"{nu_plugin_config: {key: value}}"#);
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/tests/test_pipeline_data.rs | crates/nu-protocol/tests/test_pipeline_data.rs | use nu_protocol::{IntoPipelineData, Span, Value};
#[test]
fn test_convert_pipeline_data_to_value() {
// Setup PipelineData
let value_val = 10;
let value = Value::int(value_val, Span::new(1, 3));
let pipeline_data = value.into_pipeline_data();
// Test that conversion into Value is correct
let new_span = Span::new(5, 6);
let converted_value = pipeline_data.into_value(new_span);
assert_eq!(converted_value, Ok(Value::int(value_val, new_span)));
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/tests/pipeline/byte_stream.rs | crates/nu-protocol/tests/pipeline/byte_stream.rs | use nu_protocol::{ByteStream, IntRange, Signals, Span, Value, ast::RangeInclusion};
#[test]
pub fn test_simple_positive_slice_exclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(0, 5, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "Hello");
}
#[test]
pub fn test_simple_positive_slice_exclusive_streaming() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.with_known_size(None)
.slice(
Span::test_data(),
Span::test_data(),
create_range(0, 5, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "Hello");
}
#[test]
pub fn test_negative_start_exclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(-5, 11, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "World");
}
#[test]
pub fn test_negative_end_exclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(0, -6, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "Hello");
}
#[test]
pub fn test_negative_start_and_end_exclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(-5, -2, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "Wor");
}
#[test]
pub fn test_empty_slice_exclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(5, 5, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "");
}
#[test]
pub fn test_out_of_bounds_exclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(0, 20, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "Hello World");
}
#[test]
pub fn test_invalid_range_exclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(11, 5, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "");
}
#[test]
pub fn test_max_end_exclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(6, i64::MAX, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "World");
}
#[test]
pub fn test_simple_positive_slice_inclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(0, 5, RangeInclusion::RightExclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "Hello");
}
#[test]
pub fn test_negative_start_inclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(-5, 11, RangeInclusion::Inclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "World");
}
#[test]
pub fn test_negative_end_inclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(0, -7, RangeInclusion::Inclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "Hello");
}
#[test]
pub fn test_negative_start_and_end_inclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(-5, -1, RangeInclusion::Inclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "World");
}
#[test]
pub fn test_empty_slice_inclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(5, 5, RangeInclusion::Inclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, " ");
}
#[test]
pub fn test_out_of_bounds_inclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(0, 20, RangeInclusion::Inclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "Hello World");
}
#[test]
pub fn test_invalid_range_inclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(11, 5, RangeInclusion::Inclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "");
}
#[test]
pub fn test_max_end_inclusive() {
let data = b"Hello World".to_vec();
let stream = ByteStream::read_binary(data, Span::test_data(), Signals::empty());
let sliced = stream
.slice(
Span::test_data(),
Span::test_data(),
create_range(6, i64::MAX, RangeInclusion::Inclusive),
)
.unwrap();
let result = sliced.into_bytes().unwrap();
let result = String::from_utf8(result).unwrap();
assert_eq!(result, "World");
}
fn create_range(start: i64, end: i64, inclusion: RangeInclusion) -> IntRange {
IntRange::new(
Value::int(start, Span::unknown()),
Value::nothing(Span::test_data()),
Value::int(end, Span::unknown()),
inclusion,
Span::unknown(),
)
.unwrap()
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/tests/pipeline/mod.rs | crates/nu-protocol/tests/pipeline/mod.rs | mod byte_stream;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-plugin/src/lib.rs | crates/nu-cmd-plugin/src/lib.rs | //! Nushell commands for managing plugins.
mod commands;
mod default_context;
mod util;
pub use commands::*;
pub use default_context::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-plugin/src/default_context.rs | crates/nu-cmd-plugin/src/default_context.rs | use crate::*;
use nu_protocol::engine::{EngineState, StateWorkingSet};
pub fn add_plugin_command_context(mut engine_state: EngineState) -> EngineState {
let delta = {
let mut working_set = StateWorkingSet::new(&engine_state);
macro_rules! bind_command {
( $( $command:expr ),* $(,)? ) => {
$( working_set.add_decl(Box::new($command)); )*
};
}
bind_command!(
PluginAdd,
PluginCommand,
PluginList,
PluginRm,
PluginStop,
PluginUse,
);
working_set.render()
};
if let Err(err) = engine_state.merge_delta(delta) {
eprintln!("Error creating default context: {err:?}");
}
engine_state
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-plugin/src/util.rs | crates/nu-cmd-plugin/src/util.rs | #[allow(deprecated)]
use nu_engine::{command_prelude::*, current_dir};
use nu_protocol::{
PluginRegistryFile,
engine::StateWorkingSet,
shell_error::{
self,
io::{IoError, IoErrorExt, NotFound},
},
};
use std::{
fs::{self, File},
path::PathBuf,
};
fn get_plugin_registry_file_path(
engine_state: &EngineState,
stack: &mut Stack,
span: Span,
custom_path: &Option<Spanned<String>>,
) -> Result<PathBuf, ShellError> {
#[allow(deprecated)]
let cwd = current_dir(engine_state, stack)?;
if let Some(custom_path) = custom_path {
Ok(nu_path::expand_path_with(&custom_path.item, cwd, true))
} else {
engine_state
.plugin_path
.clone()
.ok_or_else(|| ShellError::GenericError {
error: "Plugin registry file not set".into(),
msg: "pass --plugin-config explicitly here".into(),
span: Some(span),
help: Some("you may be running `nu` with --no-config-file".into()),
inner: vec![],
})
}
}
pub(crate) fn read_plugin_file(
engine_state: &EngineState,
stack: &mut Stack,
span: Span,
custom_path: &Option<Spanned<String>>,
) -> Result<PluginRegistryFile, ShellError> {
let plugin_registry_file_path =
get_plugin_registry_file_path(engine_state, stack, span, custom_path)?;
let file_span = custom_path.as_ref().map(|p| p.span).unwrap_or(span);
// Try to read the plugin file if it exists
if fs::metadata(&plugin_registry_file_path).is_ok_and(|m| m.len() > 0) {
PluginRegistryFile::read_from(
File::open(&plugin_registry_file_path)
.map_err(|err| IoError::new(err, file_span, plugin_registry_file_path))?,
Some(file_span),
)
} else if let Some(path) = custom_path {
Err(ShellError::Io(IoError::new(
shell_error::io::ErrorKind::FileNotFound,
path.span,
PathBuf::from(&path.item),
)))
} else {
Ok(PluginRegistryFile::default())
}
}
pub(crate) fn modify_plugin_file(
engine_state: &EngineState,
stack: &mut Stack,
span: Span,
custom_path: &Option<Spanned<String>>,
operate: impl FnOnce(&mut PluginRegistryFile) -> Result<(), ShellError>,
) -> Result<(), ShellError> {
let plugin_registry_file_path =
get_plugin_registry_file_path(engine_state, stack, span, custom_path)?;
let file_span = custom_path.as_ref().map(|p| p.span).unwrap_or(span);
// Try to read the plugin file if it exists
let mut contents = if fs::metadata(&plugin_registry_file_path).is_ok_and(|m| m.len() > 0) {
PluginRegistryFile::read_from(
File::open(&plugin_registry_file_path)
.map_err(|err| IoError::new(err, file_span, plugin_registry_file_path.clone()))?,
Some(file_span),
)?
} else {
PluginRegistryFile::default()
};
// Do the operation
operate(&mut contents)?;
// Save the modified file on success
// First, ensure the parent directory exists
if let Some(parent_dir) = plugin_registry_file_path.parent() {
fs::create_dir_all(parent_dir).map_err(|err| {
IoError::new(
err.not_found_as(NotFound::Directory),
file_span,
parent_dir.to_path_buf(),
)
})?;
}
// Now create the file
contents.write_to(
File::create(&plugin_registry_file_path)
.map_err(|err| IoError::new(err, file_span, plugin_registry_file_path))?,
Some(span),
)?;
Ok(())
}
pub(crate) fn canonicalize_possible_filename_arg(
engine_state: &EngineState,
stack: &Stack,
arg: &str,
) -> PathBuf {
// This results in the best possible chance of a match with the plugin item
#[allow(deprecated)]
if let Ok(cwd) = nu_engine::current_dir(engine_state, stack) {
let path = nu_path::expand_path_with(arg, &cwd, true);
// Try to canonicalize
nu_path::locate_in_dirs(&path, &cwd, || get_plugin_dirs(engine_state, stack))
// If we couldn't locate it, return the expanded path alone
.unwrap_or(path)
} else {
arg.into()
}
}
pub(crate) fn get_plugin_dirs(
engine_state: &EngineState,
stack: &Stack,
) -> impl Iterator<Item = String> {
// Get the NU_PLUGIN_DIRS from the constant and/or env var
let working_set = StateWorkingSet::new(engine_state);
let dirs_from_const = working_set
.find_variable(b"$NU_PLUGIN_DIRS")
.and_then(|var_id| working_set.get_constant(var_id).ok())
.cloned() // TODO: avoid this clone
.into_iter()
.flat_map(|value| value.into_list().ok())
.flatten()
.flat_map(|list_item| list_item.coerce_into_string().ok());
let dirs_from_env = stack
.get_env_var(engine_state, "NU_PLUGIN_DIRS")
.cloned() // TODO: avoid this clone
.into_iter()
.flat_map(|value| value.into_list().ok())
.flatten()
.flat_map(|list_item| list_item.coerce_into_string().ok());
dirs_from_const.chain(dirs_from_env)
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-plugin/src/commands/mod.rs | crates/nu-cmd-plugin/src/commands/mod.rs | mod plugin;
pub use plugin::*;
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
nushell/nushell | https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-plugin/src/commands/plugin/use_.rs | crates/nu-cmd-plugin/src/commands/plugin/use_.rs | use nu_engine::command_prelude::*;
use nu_protocol::engine::CommandType;
#[derive(Clone)]
pub struct PluginUse;
impl Command for PluginUse {
fn name(&self) -> &str {
"plugin use"
}
fn description(&self) -> &str {
"Load a plugin from the plugin registry file into scope."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build(self.name())
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
.named(
"plugin-config",
SyntaxShape::Filepath,
"Use a plugin registry file other than the one set in `$nu.plugin-path`",
None,
)
.required(
"name",
SyntaxShape::String,
"The name, or filename, of the plugin to load.",
)
.category(Category::Plugin)
}
fn extra_description(&self) -> &str {
r#"
This command is a parser keyword. For details, check:
https://www.nushell.sh/book/thinking_in_nu.html
The plugin definition must be available in the plugin registry file at parse
time. Run `plugin add` first in the REPL to do this, or from a script consider
preparing a plugin registry file and passing `--plugin-config`, or using the
`--plugin` option to `nu` instead.
If the plugin was already loaded, this will reload the latest definition from
the registry file into scope.
Note that even if the plugin filename is specified, it will only be loaded if
it was already previously registered with `plugin add`.
"#
.trim()
}
fn search_terms(&self) -> Vec<&str> {
vec!["add", "register", "scope"]
}
fn command_type(&self) -> CommandType {
CommandType::Keyword
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
_call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(PipelineData::empty())
}
fn examples(&self) -> Vec<Example<'_>> {
vec![
Example {
description: "Load the commands for the `query` plugin from $nu.plugin-path",
example: r#"plugin use query"#,
result: None,
},
Example {
description: "Load the commands for the plugin with the filename `~/.cargo/bin/nu_plugin_query` from $nu.plugin-path",
example: r#"plugin use ~/.cargo/bin/nu_plugin_query"#,
result: None,
},
Example {
description: "Load the commands for the `query` plugin from a custom plugin registry file",
example: r#"plugin use --plugin-config local-plugins.msgpackz query"#,
result: None,
},
]
}
}
| rust | MIT | 6d3cb27fa40b324a1168c577aee7f3532a5e157e | 2026-01-04T15:32:17.606688Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.