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-cli/src/completions/directory_completions.rs
crates/nu-cli/src/completions/directory_completions.rs
use crate::completions::{ Completer, CompletionOptions, completion_common::{AdjustView, adjust_if_intermediate, complete_item}, }; use nu_protocol::{ Span, SuggestionKind, engine::{EngineState, Stack, StateWorkingSet}, }; use reedline::Suggestion; use std::path::Path; use super::{SemanticSuggestion, completion_common::FileSuggestion}; pub struct DirectoryCompletion; impl Completer for DirectoryCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let AdjustView { prefix, span, .. } = adjust_if_intermediate(prefix.as_ref(), working_set, span); // Filter only the folders #[allow(deprecated)] let items: Vec<_> = directory_completion( span, &prefix, &working_set.permanent_state.current_work_dir(), options, working_set.permanent_state, stack, ) .into_iter() .map(move |x| SemanticSuggestion { suggestion: Suggestion { value: x.path, style: x.style, span: reedline::Span { start: x.span.start - offset, end: x.span.end - offset, }, ..Suggestion::default() }, kind: Some(SuggestionKind::Directory), }) .collect(); // Separate the results between hidden and non hidden let mut hidden: Vec<SemanticSuggestion> = vec![]; let mut non_hidden: Vec<SemanticSuggestion> = vec![]; for item in items.into_iter() { let item_path = Path::new(&item.suggestion.value); if let Some(value) = item_path.file_name() && let Some(value) = value.to_str() { if value.starts_with('.') { hidden.push(item); } else { non_hidden.push(item); } } } // Append the hidden folders to the non hidden vec to avoid creating a new vec non_hidden.append(&mut hidden); non_hidden } } pub fn directory_completion( span: nu_protocol::Span, partial: &str, cwd: &str, options: &CompletionOptions, engine_state: &EngineState, stack: &Stack, ) -> Vec<FileSuggestion> { complete_item(true, span, partial, &[cwd], options, engine_state, stack) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/dotnu_completions.rs
crates/nu-cli/src/completions/dotnu_completions.rs
use crate::completions::{ Completer, CompletionOptions, SemanticSuggestion, completion_common::FileSuggestion, completion_options::NuMatcher, }; use nu_path::expand_tilde; use nu_protocol::{ Span, SuggestionKind, engine::{Stack, StateWorkingSet, VirtualPath}, }; use reedline::Suggestion; use std::collections::{HashMap, HashSet}; use super::completion_common::{complete_item, surround_remove}; pub struct DotNuCompletion { /// e.g. use std/a<tab> pub std_virtual_path: bool, } impl Completer for DotNuCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let reedline_span = reedline::Span { start: span.start - offset, end: span.end - offset, }; // Modules that are already loaded go first let mut matcher = NuMatcher::new(&prefix, options, true); let mut modules_map = HashMap::new(); // TODO: inline-defined modules, e.g. `module foo {}; use foo<tab>` ? for overlay_frame in working_set.permanent_state.active_overlays(&[]) { modules_map.extend(&overlay_frame.modules); } for (module_name_bytes, module_id) in modules_map.into_iter() { let value = String::from_utf8_lossy(module_name_bytes).to_string(); let description = working_set.get_module_comments(*module_id).map(|spans| { spans .iter() .map(|sp| String::from_utf8_lossy(working_set.get_span_contents(*sp)).into()) .collect::<Vec<String>>() .join("\n") }); matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value, description, span: reedline_span, append_whitespace: true, ..Suggestion::default() }, kind: Some(SuggestionKind::Module), }); } // Add std virtual paths first if self.std_virtual_path { // Where we have '/' in the prefix, e.g. use std/l if let Some((base_dir, _)) = prefix.as_ref().rsplit_once("/") { let base_dir = surround_remove(base_dir); if let Some(VirtualPath::Dir(sub_paths)) = working_set.find_virtual_path(&base_dir) { for sub_vp_id in sub_paths { let (path, sub_vp) = working_set.get_virtual_path(*sub_vp_id); matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value: path.into(), span: reedline_span, append_whitespace: !matches!(sub_vp, VirtualPath::Dir(_)), ..Suggestion::default() }, kind: Some(SuggestionKind::Module), }); } } } else { for path in ["std", "std-rfc"] { matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value: path.into(), span: reedline_span, ..Suggestion::default() }, kind: Some(SuggestionKind::Module), }); } } } let mut all_results = matcher.suggestion_results(); // Fetch the lib dirs // NOTE: 2 ways to setup `NU_LIB_DIRS` // 1. `const NU_LIB_DIRS = [paths]`, equal to `nu -I paths` // 2. `$env.NU_LIB_DIRS = [paths]` let const_lib_dirs = working_set .find_variable(b"$NU_LIB_DIRS") .and_then(|vid| working_set.get_variable(vid).const_val.as_ref()); let env_lib_dirs = working_set.get_env_var("NU_LIB_DIRS"); let mut search_dirs = [const_lib_dirs, env_lib_dirs] .into_iter() .flatten() .flat_map(|lib_dirs| { lib_dirs .as_list() .into_iter() .flat_map(|it| it.iter().filter_map(|x| x.to_path().ok())) .map(expand_tilde) }) .collect::<HashSet<_>>(); if let Ok(cwd) = working_set.permanent_state.cwd(None) { search_dirs.insert(cwd.into_std_path_buf()); } // Fetch the files let module_file_results = complete_item( false, span, prefix.as_ref(), &search_dirs .iter() .filter_map(|d| d.to_str()) .collect::<Vec<_>>(), options, working_set.permanent_state, stack, ); all_results.extend( // Put files atop module_file_results .iter() // filtering the files that ends with .nu .filter(|it| { // for paths with spaces in them let path = it.path.trim_end_matches('`'); path.ends_with(".nu") }) // or directories .chain(module_file_results.iter().filter(|it| it.is_dir)) .map(|x: &FileSuggestion| SemanticSuggestion { suggestion: Suggestion { value: x.path.to_string(), style: x.style, span: reedline_span, append_whitespace: !x.is_dir, ..Suggestion::default() }, kind: Some(SuggestionKind::Module), }) .collect::<Vec<_>>(), ); all_results } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/base.rs
crates/nu-cli/src/completions/base.rs
use crate::completions::CompletionOptions; use nu_protocol::{ DynamicSuggestion, Span, SuggestionKind, engine::{Stack, StateWorkingSet}, }; use reedline::Suggestion; pub trait Completer { /// Fetch, filter, and sort completions #[allow(clippy::too_many_arguments)] fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion>; } #[derive(Debug, Default, PartialEq)] pub struct SemanticSuggestion { pub suggestion: Suggestion, pub kind: Option<SuggestionKind>, } impl SemanticSuggestion { pub fn from_dynamic_suggestion( suggestion: DynamicSuggestion, span: reedline::Span, style: Option<nu_ansi_term::Style>, ) -> Self { SemanticSuggestion { suggestion: Suggestion { value: suggestion.value, description: suggestion.description, extra: suggestion.extra, append_whitespace: suggestion.append_whitespace, match_indices: suggestion.match_indices, style, span, }, kind: suggestion.kind, } } } impl From<Suggestion> for SemanticSuggestion { fn from(suggestion: Suggestion) -> Self { Self { suggestion, ..Default::default() } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/variable_completions.rs
crates/nu-cli/src/completions/variable_completions.rs
use std::collections::HashMap; use crate::completions::{Completer, CompletionOptions, SemanticSuggestion}; use nu_protocol::{ ENV_VARIABLE_ID, IN_VARIABLE_ID, NU_VARIABLE_ID, Span, SuggestionKind, engine::{Stack, StateWorkingSet}, }; use reedline::Suggestion; use super::completion_options::NuMatcher; pub struct VariableCompletion; impl Completer for VariableCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, _stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut matcher = NuMatcher::new(prefix, options, true); let current_span = reedline::Span { start: span.start - offset, end: span.end - offset, }; // Variable completion (e.g: $en<tab> to complete $env) let mut variables = HashMap::new(); variables.insert("$nu".into(), &NU_VARIABLE_ID); variables.insert("$in".into(), &IN_VARIABLE_ID); variables.insert("$env".into(), &ENV_VARIABLE_ID); // TODO: The following can be refactored (see find_commands_by_predicate() used in // command_completions). let mut removed_overlays = vec![]; // Working set scope vars for scope_frame in working_set.delta.scope.iter().rev() { for overlay_frame in scope_frame.active_overlays(&mut removed_overlays).rev() { for (name, var_id) in &overlay_frame.vars { let name = String::from_utf8_lossy(name).to_string(); variables.insert(name, var_id); } } } // Permanent state vars // for scope in &self.engine_state.scope { for overlay_frame in working_set .permanent_state .active_overlays(&removed_overlays) .rev() { for (name, var_id) in &overlay_frame.vars { let name = String::from_utf8_lossy(name).to_string(); variables.insert(name, var_id); } } for (name, var_id) in variables { matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value: name, span: current_span, description: Some(working_set.get_variable(*var_id).ty.to_string()), ..Suggestion::default() }, kind: Some(SuggestionKind::Variable), }); } matcher.suggestion_results() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/file_completions.rs
crates/nu-cli/src/completions/file_completions.rs
use crate::completions::{ Completer, CompletionOptions, completion_common::{AdjustView, adjust_if_intermediate, complete_item}, }; use nu_protocol::{ Span, SuggestionKind, engine::{Stack, StateWorkingSet}, }; use reedline::Suggestion; use std::path::Path; use super::SemanticSuggestion; pub struct FileCompletion; impl Completer for FileCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let AdjustView { prefix, span, readjusted, } = adjust_if_intermediate(prefix.as_ref(), working_set, span); #[allow(deprecated)] let items: Vec<_> = complete_item( readjusted, span, &prefix, &[&working_set.permanent_state.current_work_dir()], options, working_set.permanent_state, stack, ) .into_iter() .map(move |x| SemanticSuggestion { suggestion: Suggestion { value: x.path, style: x.style, span: reedline::Span { start: x.span.start - offset, end: x.span.end - offset, }, ..Suggestion::default() }, kind: Some(if x.is_dir { SuggestionKind::Directory } else { SuggestionKind::File }), }) .collect(); // Sort results prioritizing the non hidden folders // Separate the results between hidden and non hidden let mut hidden: Vec<SemanticSuggestion> = vec![]; let mut non_hidden: Vec<SemanticSuggestion> = vec![]; for item in items.into_iter() { let item_path = Path::new(&item.suggestion.value); if let Some(value) = item_path.file_name() && let Some(value) = value.to_str() { if value.starts_with('.') { hidden.push(item); } else { non_hidden.push(item); } } } // Append the hidden folders to the non hidden vec to avoid creating a new vec non_hidden.append(&mut hidden); non_hidden } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/completion_options.rs
crates/nu-cli/src/completions/completion_options.rs
use nu_protocol::{CompletionAlgorithm, CompletionSort}; use nu_utils::IgnoreCaseExt; use nucleo_matcher::{ Config, Matcher, Utf32Str, pattern::{Atom, AtomKind, CaseMatching, Normalization}, }; use std::{borrow::Cow, fmt::Display}; use unicode_segmentation::UnicodeSegmentation; use super::SemanticSuggestion; /// Describes how suggestions should be matched. #[derive(Copy, Clone, Debug, PartialEq)] pub enum MatchAlgorithm { /// Only show suggestions which begin with the given input /// /// Example: /// "git switch" is matched by "git sw" Prefix, /// Only show suggestions which have a substring matching with the given input /// /// Example: /// "git checkout" is matched by "checkout" Substring, /// Only show suggestions which contain the input chars at any place /// /// Example: /// "git checkout" is matched by "gco" Fuzzy, } pub struct NuMatcher<'a, T> { options: &'a CompletionOptions, should_sort: bool, needle: String, state: State<T>, } enum State<T> { Unscored(Vec<UnscoredMatch<T>>), Fuzzy { matcher: Matcher, atom: Atom, matches: Vec<FuzzyMatch<T>>, }, } struct UnscoredMatch<T> { item: T, haystack: String, match_indices: Vec<usize>, } struct FuzzyMatch<T> { item: T, haystack: String, score: u16, match_indices: Vec<usize>, } const QUOTES: [char; 3] = ['"', '\'', '`']; /// Filters and sorts suggestions impl<T> NuMatcher<'_, T> { /// # Arguments /// /// * `needle` - The text to search for /// * `should_sort` - Should results be sorted? pub fn new( needle: impl AsRef<str>, options: &CompletionOptions, should_sort: bool, ) -> NuMatcher<'_, T> { // NOTE: Should match `'bar baz'` when completing `foo "b<tab>` // https://github.com/nushell/nushell/issues/16860#issuecomment-3402016955 let needle = needle.as_ref().trim_matches(QUOTES); match options.match_algorithm { MatchAlgorithm::Prefix | MatchAlgorithm::Substring => { let lowercase_needle = if options.case_sensitive { needle.to_owned() } else { needle.to_folded_case() }; NuMatcher { options, should_sort, needle: lowercase_needle, state: State::Unscored(Vec::new()), } } MatchAlgorithm::Fuzzy => { let atom = Atom::new( needle, if options.case_sensitive { CaseMatching::Respect } else { CaseMatching::Ignore }, Normalization::Smart, AtomKind::Fuzzy, false, ); NuMatcher { options, should_sort, needle: needle.to_owned(), state: State::Fuzzy { matcher: Matcher::new({ let mut cfg = Config::DEFAULT; cfg.prefer_prefix = true; cfg }), atom, matches: Vec::new(), }, } } } } /// Returns whether or not the haystack matches the needle. If it does, `item` is added /// to the list of matches (if given). /// /// Helper to avoid code duplication between [NuMatcher::add] and [NuMatcher::matches]. fn matches_aux(&mut self, orig_haystack: &str, item: Option<T>) -> Option<Vec<usize>> { let haystack = orig_haystack.trim_start_matches(QUOTES); let offset = orig_haystack.len() - haystack.len(); let haystack = haystack.trim_end_matches(QUOTES); match &mut self.state { State::Unscored(matches) => { let haystack_folded = if self.options.case_sensitive { Cow::Borrowed(haystack) } else { Cow::Owned(haystack.to_folded_case()) }; let match_start = match self.options.match_algorithm { MatchAlgorithm::Prefix => { if haystack_folded.starts_with(self.needle.as_str()) { Some(0) } else { None } } MatchAlgorithm::Substring => haystack_folded.find(self.needle.as_str()), _ => unreachable!("Only prefix and substring algorithms don't use score"), }; match_start.map(|byte_start| { let grapheme_start = haystack_folded[0..byte_start].graphemes(true).count(); // TODO this doesn't account for lowercasing changing the length of the haystack let grapheme_len = self.needle.graphemes(true).count(); let match_indices: Vec<usize> = (offset + grapheme_start..offset + grapheme_start + grapheme_len).collect(); if let Some(item) = item { matches.push(UnscoredMatch { item, haystack: haystack.to_string(), match_indices: match_indices.clone(), }); } match_indices }) } State::Fuzzy { matcher, atom, matches, } => { let mut haystack_buf = Vec::new(); let haystack_utf32 = Utf32Str::new(haystack, &mut haystack_buf); let mut indices = Vec::new(); let score = atom.indices(haystack_utf32, matcher, &mut indices)?; let indices: Vec<usize> = indices .iter() .map(|i| { offset + usize::try_from(*i).expect("should be on at least a 32-bit system") }) .collect(); if let Some(item) = item { matches.push(FuzzyMatch { item, haystack: haystack.to_string(), score, match_indices: indices.clone(), }); } Some(indices) } } } /// Add the given item if the given haystack matches the needle. /// /// Returns whether the item was added. pub fn add(&mut self, haystack: impl AsRef<str>, item: T) -> bool { self.matches_aux(haystack.as_ref(), Some(item)).is_some() } /// Check if the given haystack matches the needle without adding it as a result. /// /// Returns match indices if it matched, None if it didn't. pub fn check_match(&mut self, haystack: &str) -> Option<Vec<usize>> { self.matches_aux(haystack, None) } fn sort(&mut self) { match &mut self.state { State::Unscored(matches) => { matches.sort_by(|a, b| { let cmp_sensitive = a.haystack.cmp(&b.haystack); if self.options.case_sensitive { cmp_sensitive } else { a.haystack .to_folded_case() .cmp(&b.haystack.to_folded_case()) .then(cmp_sensitive) } }); } State::Fuzzy { matches, .. } => match self.options.sort { CompletionSort::Alphabetical => { matches.sort_by(|a, b| a.haystack.cmp(&b.haystack)); } CompletionSort::Smart => { matches.sort_by(|a, b| b.score.cmp(&a.score).then(a.haystack.cmp(&b.haystack))); } }, } } /// Sort and return all the matches, along with their match indices pub fn results(mut self) -> Vec<(T, Vec<usize>)> { if self.should_sort { self.sort(); } match self.state { State::Unscored(matches) => matches .into_iter() .map(|mat| (mat.item, mat.match_indices)) .collect::<Vec<_>>(), State::Fuzzy { matches, .. } => matches .into_iter() .map(|mat| (mat.item, mat.match_indices)) .collect::<Vec<_>>(), } } } impl NuMatcher<'_, SemanticSuggestion> { pub fn add_semantic_suggestion(&mut self, sugg: SemanticSuggestion) -> bool { let value = sugg.suggestion.value.to_string(); self.add(value, sugg) } /// Get all the items that matched (sorted) pub fn suggestion_results(self) -> Vec<SemanticSuggestion> { self.results() .into_iter() .map(|(mut sugg, indices)| { sugg.suggestion.match_indices = Some(indices); sugg }) .collect() } } impl From<CompletionAlgorithm> for MatchAlgorithm { fn from(value: CompletionAlgorithm) -> Self { match value { CompletionAlgorithm::Prefix => MatchAlgorithm::Prefix, CompletionAlgorithm::Substring => MatchAlgorithm::Substring, CompletionAlgorithm::Fuzzy => MatchAlgorithm::Fuzzy, } } } impl TryFrom<String> for MatchAlgorithm { type Error = InvalidMatchAlgorithm; fn try_from(value: String) -> Result<Self, Self::Error> { match value.as_str() { "prefix" => Ok(Self::Prefix), "substring" => Ok(Self::Substring), "fuzzy" => Ok(Self::Fuzzy), _ => Err(InvalidMatchAlgorithm::Unknown), } } } #[derive(Debug)] pub enum InvalidMatchAlgorithm { Unknown, } impl Display for InvalidMatchAlgorithm { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { InvalidMatchAlgorithm::Unknown => write!(f, "unknown match algorithm"), } } } impl std::error::Error for InvalidMatchAlgorithm {} #[derive(Clone)] pub struct CompletionOptions { pub case_sensitive: bool, pub match_algorithm: MatchAlgorithm, pub sort: CompletionSort, } impl Default for CompletionOptions { fn default() -> Self { Self { case_sensitive: true, match_algorithm: MatchAlgorithm::Prefix, sort: Default::default(), } } } #[cfg(test)] mod test { use rstest::rstest; use super::{CompletionOptions, MatchAlgorithm, NuMatcher}; #[rstest] #[case(MatchAlgorithm::Prefix, "example text", "", true)] #[case(MatchAlgorithm::Prefix, "example text", "examp", true)] #[case(MatchAlgorithm::Prefix, "example text", "text", false)] #[case(MatchAlgorithm::Substring, "example text", "", true)] #[case(MatchAlgorithm::Substring, "example text", "text", true)] #[case(MatchAlgorithm::Substring, "example text", "mplxt", false)] #[case(MatchAlgorithm::Fuzzy, "example text", "", true)] #[case(MatchAlgorithm::Fuzzy, "example text", "examp", true)] #[case(MatchAlgorithm::Fuzzy, "example text", "ext", true)] #[case(MatchAlgorithm::Fuzzy, "example text", "mplxt", true)] #[case(MatchAlgorithm::Fuzzy, "example text", "mpp", false)] fn match_algorithm_simple( #[case] match_algorithm: MatchAlgorithm, #[case] haystack: &str, #[case] needle: &str, #[case] should_match: bool, ) { let options = CompletionOptions { match_algorithm, ..Default::default() }; let mut matcher = NuMatcher::new(needle, &options, true); matcher.add(haystack, haystack); let results: Vec<_> = matcher.results().iter().map(|r| r.0).collect(); if should_match { assert_eq!(vec![haystack], results); } else { assert_ne!(vec![haystack], results); } } #[test] fn match_algorithm_fuzzy_sort_score() { let options = CompletionOptions { match_algorithm: MatchAlgorithm::Fuzzy, ..Default::default() }; let mut matcher = NuMatcher::new("fob", &options, true); for item in ["foo/bar", "fob", "foo bar"] { matcher.add(item, item); } // Sort by score, then in alphabetical order assert_eq!( vec![ ("fob", vec![0, 1, 2]), ("foo bar", vec![0, 1, 4]), ("foo/bar", vec![0, 1, 4]) ], matcher.results() ); } #[test] fn match_algorithm_fuzzy_sort_strip() { let options = CompletionOptions { match_algorithm: MatchAlgorithm::Fuzzy, ..Default::default() }; let mut matcher = NuMatcher::new("'love spaces' ", &options, true); for item in [ "'i love spaces'", "'i love spaces' so much", "'lovespaces' ", ] { matcher.add(item, item); } // Make sure the spaces are respected assert_eq!( vec![( "'i love spaces' so much", vec![3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] )], matcher.results() ); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/flag_completions.rs
crates/nu-cli/src/completions/flag_completions.rs
use crate::completions::{ Completer, CompletionOptions, SemanticSuggestion, completion_options::NuMatcher, }; use nu_protocol::{ DeclId, Span, SuggestionKind, engine::{Stack, StateWorkingSet}, }; use reedline::Suggestion; #[derive(Clone)] pub struct FlagCompletion { pub decl_id: DeclId, } impl Completer for FlagCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, _stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut matcher = NuMatcher::new(prefix, options, true); let mut add_suggestion = |value: String, description: String| { matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value, description: Some(description), span: reedline::Span { start: span.start - offset, end: span.end - offset, }, append_whitespace: true, ..Suggestion::default() }, kind: Some(SuggestionKind::Flag), }); }; let decl = working_set.get_decl(self.decl_id); let sig = decl.signature(); for named in &sig.named { if let Some(short) = named.short { let mut name = String::from("-"); name.push(short); add_suggestion(name, named.desc.clone()); } if named.long.is_empty() { continue; } add_suggestion(format!("--{}", named.long), named.desc.clone()); } matcher.suggestion_results() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/mod.rs
crates/nu-cli/src/completions/mod.rs
mod arg_value_completion; mod attribute_completions; mod base; mod cell_path_completions; mod command_completions; mod completer; mod completion_common; mod completion_options; mod custom_completions; mod directory_completions; mod dotnu_completions; mod exportable_completions; mod file_completions; mod flag_completions; mod operator_completions; mod static_completions; mod variable_completions; pub use arg_value_completion::ArgValueCompletion; pub use attribute_completions::{AttributableCompletion, AttributeCompletion}; pub use base::{Completer, SemanticSuggestion}; pub use cell_path_completions::CellPathCompletion; pub use command_completions::CommandCompletion; pub use completer::NuCompleter; pub use completion_options::{CompletionOptions, MatchAlgorithm}; pub use custom_completions::CustomCompletion; pub use directory_completions::DirectoryCompletion; pub use dotnu_completions::DotNuCompletion; pub use exportable_completions::ExportableCompletion; pub use file_completions::FileCompletion; pub use flag_completions::FlagCompletion; pub use nu_protocol::SuggestionKind; pub use operator_completions::OperatorCompletion; pub use static_completions::StaticCompletion; pub use variable_completions::VariableCompletion;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/command_completions.rs
crates/nu-cli/src/completions/command_completions.rs
use std::collections::HashSet; use crate::completions::{Completer, CompletionOptions}; use nu_protocol::{ Category, Span, SuggestionKind, engine::{CommandType, Stack, StateWorkingSet}, }; use reedline::Suggestion; use super::{SemanticSuggestion, completion_options::NuMatcher}; // TODO: Add a toggle for quoting multi word commands. Useful for: `which` and `attr complete` pub struct CommandCompletion { /// Whether to include internal commands pub internals: bool, /// Whether to include external commands pub externals: bool, } impl CommandCompletion { fn external_command_completion( &self, working_set: &StateWorkingSet, sugg_span: reedline::Span, internal_suggs: HashSet<String>, mut matcher: NuMatcher<SemanticSuggestion>, ) -> Vec<SemanticSuggestion> { let mut external_commands = HashSet::new(); let paths = working_set.permanent_state.get_env_var_insensitive("path"); if let Some((_, paths)) = paths && let Ok(paths) = paths.as_list() { for path in paths { let path = path.coerce_str().unwrap_or_default(); if let Ok(mut contents) = std::fs::read_dir(path.as_ref()) { while let Some(Ok(item)) = contents.next() { if working_set .permanent_state .config .completions .external .max_results <= external_commands.len() as i64 { break; } let Ok(name) = item.file_name().into_string() else { continue; }; // If there's an internal command with the same name, adds ^cmd to the // matcher so that both the internal and external command are included let value = if internal_suggs.contains(&name) { format!("^{name}") } else { name.clone() }; if external_commands.contains(&value) { continue; } // TODO: check name matching before a relative heavy IO involved // `is_executable` for performance consideration, should avoid // duplicated `match_aux` call for matched items in the future if matcher.check_match(&name).is_some() && is_executable::is_executable(item.path()) { external_commands.insert(value.clone()); matcher.add( name, SemanticSuggestion { suggestion: Suggestion { value, span: sugg_span, append_whitespace: true, ..Default::default() }, kind: Some(SuggestionKind::Command( CommandType::External, None, )), }, ); } } } } } matcher.suggestion_results() } } impl Completer for CommandCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, _stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut res = Vec::new(); let sugg_span = reedline::Span::new(span.start - offset, span.end - offset); let mut internal_suggs = HashSet::new(); if self.internals { let mut matcher = NuMatcher::new(prefix.as_ref(), options, true); working_set.traverse_commands(|name, decl_id| { let name = String::from_utf8_lossy(name); let command = working_set.get_decl(decl_id); if command.signature().category == Category::Removed { return; } let matched = matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value: name.to_string(), description: Some(command.description().to_string()), span: sugg_span, append_whitespace: true, ..Suggestion::default() }, kind: Some(SuggestionKind::Command( command.command_type(), Some(decl_id), )), }); if matched { internal_suggs.insert(name.to_string()); } }); res.extend(matcher.suggestion_results()); } if self.externals { let external_suggs = self.external_command_completion( working_set, sugg_span, internal_suggs, NuMatcher::new(prefix, options, true), ); res.extend(external_suggs); } res } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/attribute_completions.rs
crates/nu-cli/src/completions/attribute_completions.rs
use super::{SemanticSuggestion, completion_options::NuMatcher}; use crate::completions::{Completer, CompletionOptions}; use nu_protocol::{ Span, SuggestionKind, engine::{Stack, StateWorkingSet}, }; use reedline::Suggestion; pub struct AttributeCompletion; pub struct AttributableCompletion; impl Completer for AttributeCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, _stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut matcher = NuMatcher::new(prefix, options, true); let attr_commands = working_set.find_commands_by_predicate(|s| s.starts_with(b"attr "), true); for (decl_id, name, desc, ty) in attr_commands { let name = name.strip_prefix(b"attr ").unwrap_or(&name); matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value: String::from_utf8_lossy(name).into_owned(), description: desc, span: reedline::Span { start: span.start - offset, end: span.end - offset, }, append_whitespace: false, ..Default::default() }, kind: Some(SuggestionKind::Command(ty, Some(decl_id))), }); } matcher.suggestion_results() } } impl Completer for AttributableCompletion { fn fetch( &mut self, working_set: &StateWorkingSet, _stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut matcher = NuMatcher::new(prefix, options, true); for s in ["def", "extern", "export def", "export extern"] { let decl_id = working_set .find_decl(s.as_bytes()) .expect("internal error, builtin declaration not found"); let cmd = working_set.get_decl(decl_id); matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value: cmd.name().into(), description: Some(cmd.description().into()), span: reedline::Span { start: span.start - offset, end: span.end - offset, }, append_whitespace: true, ..Default::default() }, kind: Some(SuggestionKind::Command( cmd.command_type(), // for snippet completion in LSP working_set.find_decl(s.as_bytes()), )), }); } matcher.suggestion_results() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/cell_path_completions.rs
crates/nu-cli/src/completions/cell_path_completions.rs
use std::borrow::Cow; use crate::completions::{Completer, CompletionOptions, SemanticSuggestion}; use nu_engine::{column::get_columns, eval_variable}; use nu_protocol::{ ShellError, Span, SuggestionKind, Value, ast::{Expr, Expression, FullCellPath, PathMember}, engine::{Stack, StateWorkingSet}, eval_const::eval_constant, }; use reedline::Suggestion; use super::completion_options::NuMatcher; pub struct CellPathCompletion<'a> { pub full_cell_path: &'a FullCellPath, pub position: usize, } fn prefix_from_path_member(member: &PathMember, pos: usize) -> (String, Span) { let (prefix_str, start) = match member { PathMember::String { val, span, .. } => (val, span.start), PathMember::Int { val, span, .. } => (&val.to_string(), span.start), }; let prefix_str = prefix_str.get(..pos + 1 - start).unwrap_or(prefix_str); (prefix_str.to_string(), Span::new(start, pos + 1)) } impl Completer for CellPathCompletion<'_> { fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, _prefix: impl AsRef<str>, _span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut prefix_str = String::new(); // position at dots, e.g. `$env.config.<TAB>` let mut span = Span::new(self.position + 1, self.position + 1); let mut path_member_num_before_pos = 0; for member in self.full_cell_path.tail.iter() { if member.span().end <= self.position { path_member_num_before_pos += 1; } else if member.span().contains(self.position) { (prefix_str, span) = prefix_from_path_member(member, self.position); break; } } let current_span = reedline::Span { start: span.start - offset, end: span.end - offset, }; let mut matcher = NuMatcher::new(prefix_str, options, true); let path_members = self .full_cell_path .tail .get(0..path_member_num_before_pos) .unwrap_or_default(); let value = eval_cell_path( working_set, stack, &self.full_cell_path.head, path_members, span, ) .unwrap_or_default(); for suggestion in get_suggestions_by_value(&value, current_span) { matcher.add_semantic_suggestion(suggestion); } matcher.suggestion_results() } } /// Follow cell path to get the value /// NOTE: This is a relatively lightweight implementation, /// so it may fail to get the exact value when the expression is complicated. /// One failing example would be `[$foo].0` pub(crate) fn eval_cell_path( working_set: &StateWorkingSet, stack: &Stack, head: &Expression, path_members: &[PathMember], span: Span, ) -> Result<Value, ShellError> { // evaluate the head expression to get its value let head_value = if let Expr::Var(var_id) = head.expr { working_set .get_variable(var_id) .const_val .to_owned() .map_or_else( || eval_variable(working_set.permanent_state, stack, var_id, span), Ok, ) } else { eval_constant(working_set, head) }?; head_value .follow_cell_path(path_members) .map(Cow::into_owned) } fn get_suggestions_by_value( value: &Value, current_span: reedline::Span, ) -> Vec<SemanticSuggestion> { let to_suggestion = |s: String, v: Option<&Value>| { // Check if the string needs quoting let value = if s.is_empty() || s.chars() .any(|c: char| !(c.is_ascii_alphabetic() || ['_', '-'].contains(&c))) { format!("{s:?}") } else { s }; SemanticSuggestion { suggestion: Suggestion { value, span: current_span, description: v.map(|v| v.get_type().to_string()), ..Suggestion::default() }, kind: Some(SuggestionKind::CellPath), } }; match value { Value::Record { val, .. } => val .columns() .map(|s| to_suggestion(s.to_string(), val.get(s))) .collect(), Value::List { vals, .. } => get_columns(vals.as_slice()) .into_iter() .map(|s| { let sub_val = vals .first() .and_then(|v| v.as_record().ok()) .and_then(|rv| rv.get(&s)); to_suggestion(s, sub_val) }) .collect(), _ => vec![], } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/completer.rs
crates/nu-cli/src/completions/completer.rs
use crate::completions::{ ArgValueCompletion, AttributableCompletion, AttributeCompletion, CellPathCompletion, CommandCompletion, Completer, CompletionOptions, CustomCompletion, FileCompletion, FlagCompletion, OperatorCompletion, VariableCompletion, base::SemanticSuggestion, }; use nu_parser::parse; use nu_protocol::{ CommandWideCompleter, Completion, GetSpan, Signature, Span, ast::{ Argument, Block, Expr, Expression, FindMapResult, PipelineRedirection, RedirectionTarget, Traverse, }, engine::{ArgType, EngineState, Stack, StateWorkingSet}, }; use reedline::{Completer as ReedlineCompleter, Suggestion}; use std::borrow::Cow; use std::sync::Arc; use super::{StaticCompletion, custom_completions::CommandWideCompletion}; /// Used as the function `f` in find_map Traverse /// /// returns the inner-most pipeline_element of interest /// i.e. the one that contains given position and needs completion fn find_pipeline_element_by_position<'a>( expr: &'a Expression, working_set: &'a StateWorkingSet, pos: usize, ) -> FindMapResult<&'a Expression> { // skip the entire expression if the position is not in it if !expr.span.contains(pos) { return FindMapResult::Stop; } let closure = |expr: &'a Expression| find_pipeline_element_by_position(expr, working_set, pos); match &expr.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); // check redirection target for sub blocks before diving recursively into them check_redirection_in_block(block.as_ref(), pos) .map(FindMapResult::Found) .unwrap_or_default() } Expr::Call(call) => call .arguments .iter() .find_map(|arg| arg.expr().and_then(|e| e.find_map(working_set, &closure))) // if no inner call/external_call found, then this is the inner-most one .or(Some(expr)) .map(FindMapResult::Found) .unwrap_or_default(), Expr::ExternalCall(head, arguments) => arguments .iter() .find_map(|arg| arg.expr().find_map(working_set, &closure)) .or_else(|| { // For aliased external_call, the span of original external command head should fail the // contains(pos) check, thus avoiding recursion into its head expression. // See issue #7648 for details. let span = working_set.get_span(head.span_id); if span.contains(pos) { // This is for complicated external head expressions, e.g. `^(echo<tab> foo)` head.as_ref().find_map(working_set, &closure) } else { None } }) .or(Some(expr)) .map(FindMapResult::Found) .unwrap_or_default(), // complete the operator Expr::BinaryOp(lhs, _, rhs) => lhs .find_map(working_set, &closure) .or_else(|| rhs.find_map(working_set, &closure)) .or(Some(expr)) .map(FindMapResult::Found) .unwrap_or_default(), Expr::FullCellPath(fcp) => fcp .head .find_map(working_set, &closure) .map(FindMapResult::Found) // e.g. use std/util [<tab> .or_else(|| { (fcp.head.span.contains(pos) && matches!(fcp.head.expr, Expr::List(_))) .then_some(FindMapResult::Continue) }) .or(Some(FindMapResult::Found(expr))) .unwrap_or_default(), Expr::Var(_) => FindMapResult::Found(expr), Expr::AttributeBlock(ab) => ab .attributes .iter() .map(|attr| &attr.expr) .chain(Some(ab.item.as_ref())) .find_map(|expr| expr.find_map(working_set, &closure)) .or(Some(expr)) .map(FindMapResult::Found) .unwrap_or_default(), _ => FindMapResult::Continue, } } /// Helper function to extract file-path expression from redirection target fn check_redirection_target(target: &RedirectionTarget, pos: usize) -> Option<&Expression> { let expr = target.expr(); expr.and_then(|expression| { if let Expr::String(_) = expression.expr && expression.span.contains(pos) { expr } else { None } }) } /// For redirection target completion /// https://github.com/nushell/nushell/issues/16827 fn check_redirection_in_block(block: &Block, pos: usize) -> Option<&Expression> { block.pipelines.iter().find_map(|pipeline| { pipeline.elements.iter().find_map(|element| { element.redirection.as_ref().and_then(|redir| match redir { PipelineRedirection::Single { target, .. } => check_redirection_target(target, pos), PipelineRedirection::Separate { out, err } => check_redirection_target(out, pos) .or_else(|| check_redirection_target(err, pos)), }) }) }) } /// Before completion, an additional character `a` is added to the source as a placeholder for correct parsing results. /// This function helps to strip it fn strip_placeholder_if_any<'a>( working_set: &'a StateWorkingSet, span: &Span, strip: bool, ) -> (Span, &'a [u8]) { let new_span = if strip { let new_end = std::cmp::max(span.end - 1, span.start); Span::new(span.start, new_end) } else { span.to_owned() }; let prefix = working_set.get_span_contents(new_span); (new_span, prefix) } #[derive(Clone)] pub struct NuCompleter { engine_state: Arc<EngineState>, stack: Stack, } /// Common arguments required for Completer pub(crate) struct Context<'a> { pub working_set: &'a StateWorkingSet<'a>, pub span: Span, pub prefix: &'a [u8], pub offset: usize, } impl Context<'_> { pub(crate) fn new<'a>( working_set: &'a StateWorkingSet, span: Span, prefix: &'a [u8], offset: usize, ) -> Context<'a> { Context { working_set, span, prefix, offset, } } } impl NuCompleter { pub fn new(engine_state: Arc<EngineState>, stack: Arc<Stack>) -> Self { Self { engine_state, stack: Stack::with_parent(stack).reset_out_dest().collect_value(), } } pub fn fetch_completions_at(&self, line: &str, pos: usize) -> Vec<SemanticSuggestion> { let mut working_set = StateWorkingSet::new(&self.engine_state); let offset = working_set.next_span_start(); // TODO: Callers should be trimming the line themselves let line = if line.len() > pos { &line[..pos] } else { line }; let block = parse( &mut working_set, Some("completer"), // Add a placeholder `a` to the end format!("{line}a").as_bytes(), false, ); self.fetch_completions_by_block(block, &working_set, pos, offset, line, true) } /// For completion in LSP server. /// We don't truncate the contents in order /// to complete the definitions after the cursor. /// /// And we avoid the placeholder to reuse the parsed blocks /// cached while handling other LSP requests, e.g. diagnostics pub fn fetch_completions_within_file( &self, filename: &str, pos: usize, contents: &str, ) -> Vec<SemanticSuggestion> { let mut working_set = StateWorkingSet::new(&self.engine_state); let block = parse(&mut working_set, Some(filename), contents.as_bytes(), false); let Some(file_span) = working_set.get_span_for_filename(filename) else { return vec![]; }; let offset = file_span.start; self.fetch_completions_by_block(block.clone(), &working_set, pos, offset, contents, false) } fn fetch_completions_by_block( &self, block: Arc<Block>, working_set: &StateWorkingSet, pos: usize, offset: usize, contents: &str, extra_placeholder: bool, ) -> Vec<SemanticSuggestion> { // Adjust offset so that the spans of the suggestions will start at the right // place even with `only_buffer_difference: true` let mut pos_to_search = pos + offset; if !extra_placeholder { pos_to_search = pos_to_search.saturating_sub(1); } let Some(element_expression) = block .find_map(working_set, &|expr: &Expression| { find_pipeline_element_by_position(expr, working_set, pos_to_search) }) .or_else(|| check_redirection_in_block(block.as_ref(), pos_to_search)) else { return vec![]; }; // text of element_expression let start_offset = element_expression.span.start - offset; let Some(text) = contents.get(start_offset..pos) else { return vec![]; }; self.complete_by_expression( working_set, element_expression, offset, pos_to_search, text, extra_placeholder, ) } /// Complete given the expression of interest /// Usually, the expression is get from `find_pipeline_element_by_position` /// /// # Arguments /// * `offset` - start offset of current working_set span /// * `pos` - cursor position, should be > offset /// * `prefix_str` - all the text before the cursor, within the `element_expression` /// * `strip` - whether to strip the extra placeholder from a span fn complete_by_expression( &self, working_set: &StateWorkingSet, element_expression: &Expression, offset: usize, pos: usize, prefix_str: &str, strip: bool, ) -> Vec<SemanticSuggestion> { let mut suggestions: Vec<SemanticSuggestion> = vec![]; match &element_expression.expr { Expr::Var(_) => { return self.variable_names_completion_helper( working_set, element_expression.span, offset, strip, ); } Expr::FullCellPath(full_cell_path) => { // e.g. `$e<tab>` parsed as FullCellPath // but `$e.<tab>` without placeholder should be taken as cell_path if full_cell_path.tail.is_empty() && !prefix_str.ends_with('.') { return self.variable_names_completion_helper( working_set, element_expression.span, offset, strip, ); } else { let mut cell_path_completer = CellPathCompletion { full_cell_path, position: if strip { pos - 1 } else { pos }, }; let ctx = Context::new(working_set, Span::unknown(), &[], offset); return self.process_completion(&mut cell_path_completer, &ctx); } } Expr::BinaryOp(lhs, op, _) => { if op.span.contains(pos) { let mut operator_completions = OperatorCompletion { left_hand_side: lhs.as_ref(), }; let (new_span, prefix) = strip_placeholder_if_any(working_set, &op.span, strip); let ctx = Context::new(working_set, new_span, prefix, offset); let results = self.process_completion(&mut operator_completions, &ctx); if !results.is_empty() { return results; } } } Expr::AttributeBlock(ab) => { if let Some(span) = ab.attributes.iter().find_map(|attr| { let span = attr.expr.span; span.contains(pos).then_some(span) }) { let (new_span, prefix) = strip_placeholder_if_any(working_set, &span, strip); let ctx = Context::new(working_set, new_span, prefix, offset); return self.process_completion(&mut AttributeCompletion, &ctx); }; let span = ab.item.span; if span.contains(pos) { let (new_span, prefix) = strip_placeholder_if_any(working_set, &span, strip); let ctx = Context::new(working_set, new_span, prefix, offset); return self.process_completion(&mut AttributableCompletion, &ctx); } } // NOTE: user defined internal commands can have any length // e.g. `def "foo -f --ff bar"`, complete by line text // instead of relying on the parsing result in that case Expr::Call(_) | Expr::ExternalCall(_, _) => { let need_externals = !prefix_str.contains(' '); let need_internals = !prefix_str.starts_with('^'); let mut span = element_expression.span; if !need_internals { span.start += 1; }; suggestions.extend(self.command_completion_helper( working_set, span, offset, need_internals, need_externals, strip, )) } _ => (), } // unfinished argument completion for commands match &element_expression.expr { Expr::Call(call) => { let signature = working_set.get_decl(call.decl_id).signature(); // NOTE: the argument to complete is not necessarily the last one // for lsp completion, we don't trim the text, // so that `def`s after pos can be completed let mut positional_arg_index = 0; for (arg_idx, arg) in call.arguments.iter().enumerate() { let span = arg.span(); // Skip arguments before the cursor if !span.contains(pos) { match arg { Argument::Named(_) => (), _ => positional_arg_index += 1, } continue; } // Context defaults to the whole argument, needs adjustments for specific situations let (new_span, prefix) = strip_placeholder_if_any(working_set, &span, strip); let ctx = Context::new(working_set, new_span, prefix, offset); let flag_completion_helper = |ctx: Context| { let mut flag_completions = FlagCompletion { decl_id: call.decl_id, }; let mut res = self.process_completion(&mut flag_completions, &ctx); // For external command wrappers, which are parsed as internal calls, // also try command-wide completion for flag names // TODO: duplication? let command_wide_ctx = Context::new(working_set, span, b"", offset); res.extend( self.command_wide_completion_helper( &signature, element_expression, &command_wide_ctx, strip, ) .1, ); res }; // Basically 2 kinds of argument completions for now: // 1. Flag name: 2 sources combined: // * Signature based internal flags // * Command-wide external flags // 2. Flag value/positional: try the followings in order: // 1. Custom completion // 2. Command-wide completion // 3. Dynamic completion defined in trait `Command` // 4. Type-based default completion // 5. Fallback(file) completion match arg { // Flag value completion Argument::Named((name, short, Some(val))) if val.span.contains(pos) => { // for `--foo ..a|` and `--foo=..a|` (`|` represents the cursor), the // arg span should be trimmed: // - split the given span with `predicate` (b == '=' || b == ' '), and // take the rightmost part: // - "--foo ..a" => ["--foo", "..a"] => "..a" // - "--foo=..a" => ["--foo", "..a"] => "..a" // - strip placeholder (`a`) if present let mut new_span = val.span; if strip { new_span.end = new_span.end.saturating_sub(1); } let prefix = working_set.get_span_contents(new_span); let ctx = Context::new(working_set, new_span, prefix, offset); // If we're completing the value of the flag, // search for the matching custom completion decl_id (long or short) let flag = signature.get_long_flag(&name.item).or_else(|| { short.as_ref().and_then(|s| { signature.get_short_flag(s.item.chars().next().unwrap_or('_')) }) }); // Prioritize custom completion results over everything else if let Some(custom_completer) = flag.and_then(|f| f.completion) { suggestions.splice( 0..0, self.custom_completion_helper( custom_completer, prefix_str, &ctx, if strip { pos } else { pos + 1 }, ), ); // Fallback completion is already handled in `CustomCompletion` return suggestions; } // Try command-wide completion if specified by attributes // NOTE: `CommandWideCompletion` handles placeholder stripping internally let command_wide_ctx = Context::new(working_set, val.span, b"", offset); let (need_fallback, command_wide_res) = self .command_wide_completion_helper( &signature, element_expression, &command_wide_ctx, strip, ); suggestions.splice(0..0, command_wide_res); if !need_fallback { return suggestions; } let mut flag_value_completion = ArgValueCompletion { arg_type: ArgType::Flag(Cow::from(name.as_ref().item.as_str())), // flag value doesn't need to fallback, just fill a // temp value false. need_fallback: false, completer: self, call, arg_idx, pos, strip, }; suggestions.splice( 0..0, self.process_completion(&mut flag_value_completion, &ctx), ); return suggestions; } // Flag name completion Argument::Named((_, _, None)) => { suggestions.splice(0..0, flag_completion_helper(ctx)); } // Edge case of lsp completion where the cursor is at the flag name, // with a flag value next to it. Argument::Named((_, _, Some(val))) => { // Span/prefix calibration let mut new_span = Span::new(span.start, val.span.start); let raw_prefix = working_set.get_span_contents(new_span); let prefix = raw_prefix.trim_ascii_end(); let mut prefix = prefix.strip_suffix(b"=").unwrap_or(prefix); new_span.end = new_span .end .saturating_sub(raw_prefix.len() - prefix.len()) .max(span.start); // Currently never reachable if strip { new_span.end = new_span.end.saturating_sub(1).max(span.start); prefix = prefix[..prefix.len() - 1].as_ref(); } let ctx = Context::new(working_set, new_span, prefix, offset); suggestions.splice(0..0, flag_completion_helper(ctx)); } Argument::Unknown(_) if prefix.starts_with(b"-") => { suggestions.splice(0..0, flag_completion_helper(ctx)); } // only when `strip` == false Argument::Positional(_) if prefix == b"-" => { suggestions.splice(0..0, flag_completion_helper(ctx)); } Argument::Positional(_) => { // Prioritize custom completion results over everything else if let Some(custom_completer) = signature // For positional arguments, check PositionalArg // Find the right positional argument by index .get_positional(positional_arg_index) .and_then(|pos_arg| pos_arg.completion.clone()) { suggestions.splice( 0..0, self.custom_completion_helper( custom_completer, prefix_str, &ctx, if strip { pos } else { pos + 1 }, ), ); // Fallback completion is already handled in `CustomCompletion` return suggestions; } // Try command-wide completion if specified by attributes let command_wide_ctx = Context::new(working_set, span, b"", offset); let (need_fallback, command_wide_res) = self .command_wide_completion_helper( &signature, element_expression, &command_wide_ctx, strip, ); suggestions.splice(0..0, command_wide_res); if !need_fallback { return suggestions; } // Default argument value completion let mut positional_value_completion = ArgValueCompletion { // arg_type: ArgType::Positional(positional_arg_index - 1), arg_type: ArgType::Positional(positional_arg_index), need_fallback: suggestions.is_empty(), completer: self, call, arg_idx, pos, strip, }; suggestions.splice( 0..0, self.process_completion(&mut positional_value_completion, &ctx), ); return suggestions; } _ => (), } break; } } Expr::ExternalCall(head, arguments) => { for (i, arg) in arguments.iter().enumerate() { let span = arg.expr().span; if span.contains(pos) { // e.g. `sudo l<tab>` // HACK: judge by index 0 is not accurate if i == 0 { let external_cmd = working_set.get_span_contents(head.span); if external_cmd == b"sudo" || external_cmd == b"doas" { let commands = self.command_completion_helper( working_set, span, offset, true, true, strip, ); // flags of sudo/doas can still be completed by external completer if !commands.is_empty() { return commands; } } } // resort to external completer set in config let completion = self .engine_state .get_config() .completions .external .completer .as_ref() .map(|closure| { CommandWideCompletion::closure(closure, element_expression, strip) }); if let Some(mut completion) = completion { let ctx = Context::new(working_set, span, b"", offset); let results = self.process_completion(&mut completion, &ctx); // Prioritize external results over (sub)commands suggestions.splice(0..0, results); if !completion.need_fallback { return suggestions; } } // for external path arguments with spaces, please check issue #15790 if suggestions.is_empty() { let (new_span, prefix) = strip_placeholder_if_any(working_set, &span, strip); let ctx = Context::new(working_set, new_span, prefix, offset); return self.process_completion(&mut FileCompletion, &ctx); } break; } } } _ => (), } // if no suggestions yet, fallback to file completion if suggestions.is_empty() { let (new_span, prefix) = strip_placeholder_if_any(working_set, &element_expression.span, strip); let ctx = Context::new(working_set, new_span, prefix, offset); suggestions.extend(self.process_completion(&mut FileCompletion, &ctx)); } suggestions } fn variable_names_completion_helper( &self, working_set: &StateWorkingSet, span: Span, offset: usize, strip: bool, ) -> Vec<SemanticSuggestion> { let (new_span, prefix) = strip_placeholder_if_any(working_set, &span, strip); if !prefix.starts_with(b"$") { return vec![]; } let ctx = Context::new(working_set, new_span, prefix, offset); self.process_completion(&mut VariableCompletion, &ctx) } fn command_completion_helper( &self, working_set: &StateWorkingSet, span: Span, offset: usize, internals: bool, externals: bool, strip: bool, ) -> Vec<SemanticSuggestion> { let config = self.engine_state.get_config(); let mut command_completions = CommandCompletion { internals, externals: !internals || (externals && config.completions.external.enable), }; let (new_span, prefix) = strip_placeholder_if_any(working_set, &span, strip); let ctx = Context::new(working_set, new_span, prefix, offset); self.process_completion(&mut command_completions, &ctx) } fn custom_completion_helper( &self, custom_completion: Completion, input: &str, ctx: &Context, pos: usize, ) -> Vec<SemanticSuggestion> { match custom_completion { Completion::Command(decl_id) => { let mut completer = CustomCompletion::new(decl_id, input.into(), pos - ctx.offset, FileCompletion); self.process_completion(&mut completer, ctx) } Completion::List(list) => { let mut completer = StaticCompletion::new(list); self.process_completion(&mut completer, ctx) } } } fn command_wide_completion_helper( &self, signature: &Signature, element_expression: &Expression, ctx: &Context, strip: bool, ) -> (bool, Vec<SemanticSuggestion>) { let completion = match signature.complete { Some(CommandWideCompleter::Command(decl_id)) => { CommandWideCompletion::command(ctx.working_set, decl_id, element_expression, strip) } Some(CommandWideCompleter::External) => self .engine_state .get_config() .completions .external .completer .as_ref() .map(|closure| CommandWideCompletion::closure(closure, element_expression, strip)), None => None, }; if let Some(mut completion) = completion { let res = self.process_completion(&mut completion, ctx); (completion.need_fallback, res) } else { (true, vec![]) } } // Process the completion for a given completer pub(crate) fn process_completion<T: Completer>( &self, completer: &mut T, ctx: &Context, ) -> Vec<SemanticSuggestion> { let config = self.engine_state.get_config(); let options = CompletionOptions { case_sensitive: config.completions.case_sensitive, match_algorithm: config.completions.algorithm.into(), sort: config.completions.sort, }; completer.fetch( ctx.working_set, &self.stack, String::from_utf8_lossy(ctx.prefix), ctx.span, ctx.offset, &options, ) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/custom_completions.rs
crates/nu-cli/src/completions/custom_completions.rs
use crate::completions::{Completer, CompletionOptions, MatchAlgorithm, SemanticSuggestion}; use nu_color_config::{color_record_to_nustyle, lookup_ansi_color_style}; use nu_engine::{compile, eval_call}; use nu_parser::flatten_expression; use nu_protocol::{ BlockId, DeclId, GetSpan, IntoSpanned, PipelineData, Record, ShellError, Span, Spanned, SuggestionKind, Type, Value, VarId, ast::{Argument, Call, Expr, Expression}, debugger::WithoutDebug, engine::{Closure, EngineState, Stack, StateWorkingSet}, }; use nu_utils::SharedCow; use reedline::Suggestion; use std::{collections::HashMap, sync::Arc}; use super::completion_options::NuMatcher; fn map_value_completions<'a>( list: impl Iterator<Item = &'a Value>, span: Span, input_start: usize, offset: usize, ) -> Vec<SemanticSuggestion> { list.filter_map(move |x| { // Match for string values if let Ok(s) = x.coerce_string() { return Some(SemanticSuggestion { suggestion: Suggestion { value: s, span: reedline::Span { start: span.start - offset, end: span.end - offset, }, ..Suggestion::default() }, kind: Some(SuggestionKind::Value(x.get_type())), }); } // Match for record values if let Ok(record) = x.as_record() { let mut suggestion = Suggestion { value: String::from(""), span: reedline::Span { start: span.start - offset, end: span.end - offset, }, ..Suggestion::default() }; let mut value_type = Type::String; // Iterate the cols looking for `value` and `description` record.iter().for_each(|(key, value)| { match key.as_str() { "value" => { value_type = value.get_type(); if let Ok(val_str) = value.coerce_string() { suggestion.value = val_str; } } "description" => { if let Ok(desc_str) = value.coerce_string() { suggestion.description = Some(desc_str); } } "style" => { suggestion.style = match value { Value::String { val, .. } => Some(lookup_ansi_color_style(val)), Value::Record { .. } => Some(color_record_to_nustyle(value)), _ => None, }; } "span" => { if let Value::Record { val: span_rec, .. } = value { // TODO: error on invalid spans? if let Some(end) = read_span_field(span_rec, "end") { suggestion.span.end = suggestion.span.end.min(end + input_start); } if let Some(start) = read_span_field(span_rec, "start") { suggestion.span.start = start + input_start; } if suggestion.span.start > suggestion.span.end { suggestion.span.start = suggestion.span.end; log::error!( "Custom span start ({}) is greater than end ({})", suggestion.span.start, suggestion.span.end ); } } } _ => (), } }); return Some(SemanticSuggestion { suggestion, kind: Some(SuggestionKind::Value(value_type)), }); } None }) .collect() } fn read_span_field(span: &SharedCow<Record>, field: &str) -> Option<usize> { let Ok(val) = span.get(field)?.as_int() else { log::error!("Expected span field {field} to be int"); return None; }; let Ok(val) = usize::try_from(val) else { log::error!("Couldn't convert span {field} to usize"); return None; }; Some(val) } pub struct CustomCompletion<T: Completer> { decl_id: DeclId, line: String, line_pos: usize, fallback: T, } impl<T: Completer> CustomCompletion<T> { pub fn new(decl_id: DeclId, line: String, line_pos: usize, fallback: T) -> Self { Self { decl_id, line, line_pos, fallback, } } } impl<T: Completer> Completer for CustomCompletion<T> { fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, orig_options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { // Call custom declaration let mut stack_mut = stack.clone(); let mut eval = |engine_state: &EngineState| { eval_call::<WithoutDebug>( engine_state, &mut stack_mut, &Call { decl_id: self.decl_id, head: span, arguments: vec![ Argument::Positional(Expression::new_unknown( Expr::String(self.line.clone()), Span::unknown(), Type::String, )), Argument::Positional(Expression::new_unknown( Expr::Int(self.line_pos as i64), Span::unknown(), Type::Int, )), ], parser_info: HashMap::new(), }, PipelineData::empty(), ) }; let result = if self.decl_id.get() < working_set.permanent_state.num_decls() { eval(working_set.permanent_state) } else { let mut engine_state = working_set.permanent_state.clone(); let _ = engine_state.merge_delta(working_set.delta.clone()); eval(&engine_state) }; let mut completion_options = orig_options.clone(); let mut should_sort = true; let mut should_filter = true; // Parse result let suggestions = match result.and_then(|data| data.into_value(span)) { Ok(value) => match &value { Value::Record { val, .. } => { let completions = val .get("completions") .and_then(|val| { val.as_list().ok().map(|it| { map_value_completions( it.iter(), span, self.line_pos - self.line.len(), offset, ) }) }) .unwrap_or_default(); let options = val.get("options"); if let Some(Value::Record { val: options, .. }) = &options { if let Some(filter) = options.get("filter").and_then(|val| val.as_bool().ok()) { should_filter = filter; } if let Some(sort) = options.get("sort").and_then(|val| val.as_bool().ok()) { should_sort = sort; if should_sort && !should_filter { log::warn!("Sorting won't happen because filtering is disabled.") }; } if let Some(case_sensitive) = options .get("case_sensitive") .and_then(|val| val.as_bool().ok()) { completion_options.case_sensitive = case_sensitive; } let positional = options.get("positional").and_then(|val| val.as_bool().ok()); if positional.is_some() { log::warn!( "Use of the positional option is deprecated. Use the substring match algorithm instead." ); } if let Some(algorithm) = options .get("completion_algorithm") .and_then(|option| option.coerce_string().ok()) .and_then(|option| option.try_into().ok()) { completion_options.match_algorithm = algorithm; if let Some(false) = positional && completion_options.match_algorithm == MatchAlgorithm::Prefix { completion_options.match_algorithm = MatchAlgorithm::Substring } } } completions } Value::List { vals, .. } => map_value_completions( vals.iter(), span, self.line_pos - self.line.len(), offset, ), Value::Nothing { .. } => { return self.fallback.fetch( working_set, stack, prefix, span, offset, orig_options, ); } _ => { log::error!( "Custom completer returned invalid value of type {}", value.get_type() ); return vec![]; } }, Err(e) => { log::error!("Error getting custom completions: {e}"); return vec![]; } }; if !should_filter { return suggestions; } let mut matcher = NuMatcher::new(prefix, &completion_options, should_sort); for sugg in suggestions { matcher.add_semantic_suggestion(sugg); } matcher.suggestion_results() } } pub fn get_command_arguments( working_set: &StateWorkingSet<'_>, element_expression: &Expression, ) -> Spanned<Vec<Spanned<String>>> { let span = element_expression.span(&working_set); flatten_expression(working_set, element_expression) .iter() .map(|(span, _)| { String::from_utf8_lossy(working_set.get_span_contents(*span)) .into_owned() .into_spanned(*span) }) .collect::<Vec<_>>() .into_spanned(span) } pub struct CommandWideCompletion<'e> { block_id: BlockId, captures: Vec<(VarId, Value)>, expression: &'e Expression, strip: bool, pub need_fallback: bool, } impl<'a> CommandWideCompletion<'a> { pub fn command( working_set: &StateWorkingSet<'_>, decl_id: DeclId, expression: &'a Expression, strip: bool, ) -> Option<Self> { let block_id = (decl_id.get() < working_set.num_decls()) .then(|| working_set.get_decl(decl_id)) .and_then(|command| command.block_id())?; Some(Self { block_id, captures: vec![], expression, strip, need_fallback: false, }) } pub fn closure(closure: &'a Closure, expression: &'a Expression, strip: bool) -> Self { Self { block_id: closure.block_id, captures: closure.captures.clone(), expression, strip, need_fallback: false, } } } impl<'a> Completer for CommandWideCompletion<'a> { fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, _prefix: impl AsRef<str>, span: Span, offset: usize, _options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let Spanned { item: mut args, span: args_span, } = get_command_arguments(working_set, self.expression); let mut new_span = span; // strip the placeholder if self.strip && let Some(last) = args.last_mut() { last.item.pop(); new_span = Span::new(span.start, span.end.saturating_sub(1)); } let mut block = working_set.get_block(self.block_id).clone(); // LSP completion where custom def is parsed but not compiled if block.ir_block.is_none() && let Ok(ir_block) = compile(working_set, &block) { let mut new_block = (*block).clone(); new_block.ir_block = Some(ir_block); block = Arc::new(new_block); } let mut callee_stack = stack.captures_to_stack_preserve_out_dest(self.captures.clone()); if let Some(pos_arg) = block.signature.required_positional.first() && let Some(var_id) = pos_arg.var_id { callee_stack.add_var( var_id, Value::list( args.into_iter() .map(|Spanned { item, span }| Value::string(item, span)) .collect(), args_span, ), ); } let mut engine_state = working_set.permanent_state.clone(); let _ = engine_state.merge_delta(working_set.delta.clone()); let result = nu_engine::eval_block::<WithoutDebug>( &engine_state, &mut callee_stack, &block, PipelineData::empty(), ) .map(|p| p.body); let command_span = working_set.get_span(self.expression.span_id); if let Some(results) = convert_whole_command_completion_results(offset, new_span, result, command_span) { results } else { self.need_fallback = true; vec![] } } } /// Converts the output of the external completion closure and whole command custom completion /// commands' fn convert_whole_command_completion_results( offset: usize, span: Span, result: Result<PipelineData, nu_protocol::ShellError>, command_span: Span, ) -> Option<Vec<SemanticSuggestion>> { let value = match result.and_then(|pipeline_data| pipeline_data.into_value(span)) { Ok(value) => value, Err(err) => { log::error!( "{}", ShellError::GenericError { error: "nu::shell::completion".into(), msg: "failed to eval completer block".into(), span: None, help: None, inner: vec![err], } ); return Some(vec![]); } }; match value { Value::List { vals, .. } => Some(map_value_completions( vals.iter(), span, command_span.start - offset, offset, )), Value::Nothing { .. } => None, _ => { log::error!( "{}", ShellError::GenericError { error: "nu::shell::completion".into(), msg: "completer returned invalid value of type".into(), span: None, help: None, inner: vec![], }, ); Some(vec![]) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/exportable_completions.rs
crates/nu-cli/src/completions/exportable_completions.rs
use crate::completions::{ Completer, CompletionOptions, SemanticSuggestion, completion_common::surround_remove, completion_options::NuMatcher, }; use nu_protocol::{ ModuleId, Span, SuggestionKind, engine::{Stack, StateWorkingSet}, }; use reedline::Suggestion; pub struct ExportableCompletion<'a> { pub module_id: ModuleId, pub temp_working_set: Option<StateWorkingSet<'a>>, } /// If name contains space, wrap it in quotes fn wrapped_name(name: String) -> String { if !name.contains(' ') { return name; } if name.contains('\'') { format!("\"{}\"", name.replace('"', r#"\""#)) } else { format!("'{name}'") } } impl Completer for ExportableCompletion<'_> { fn fetch( &mut self, working_set: &StateWorkingSet, _stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut matcher = NuMatcher::<()>::new(surround_remove(prefix.as_ref()), options, true); let mut results = Vec::new(); let span = reedline::Span { start: span.start - offset, end: span.end - offset, }; // TODO: use matcher.add_lazy to lazy evaluate an item if it matches the prefix let mut add_suggestion = |value: String, description: Option<String>, extra: Option<Vec<String>>, match_indices: Vec<usize>, kind: SuggestionKind| { results.push(SemanticSuggestion { suggestion: Suggestion { value, span, description, extra, match_indices: Some(match_indices), ..Suggestion::default() }, kind: Some(kind), }); }; let working_set = self.temp_working_set.as_ref().unwrap_or(working_set); let module = working_set.get_module(self.module_id); for (name, decl_id) in &module.decls { let name = String::from_utf8_lossy(name).to_string(); if let Some(match_indices) = matcher.check_match(&name) { let cmd = working_set.get_decl(*decl_id); add_suggestion( wrapped_name(name), Some(cmd.description().to_string()), None, match_indices, // `None` here avoids arguments being expanded by snippet edit style for lsp SuggestionKind::Command(cmd.command_type(), None), ); } } for (name, module_id) in &module.submodules { let name = String::from_utf8_lossy(name).to_string(); if let Some(match_indices) = matcher.check_match(&name) { let comments = working_set.get_module_comments(*module_id).map(|spans| { spans .iter() .map(|sp| { String::from_utf8_lossy(working_set.get_span_contents(*sp)).into() }) .collect::<Vec<String>>() }); add_suggestion( wrapped_name(name), Some("Submodule".into()), comments, match_indices, SuggestionKind::Module, ); } } for (name, var_id) in &module.constants { let name = String::from_utf8_lossy(name).to_string(); if let Some(match_indices) = matcher.check_match(&name) { let var = working_set.get_variable(*var_id); add_suggestion( wrapped_name(name), var.const_val .as_ref() .and_then(|v| v.clone().coerce_into_string().ok()), None, match_indices, SuggestionKind::Variable, ); } } results } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/static_completions.rs
crates/nu-cli/src/completions/static_completions.rs
use crate::completions::{Completer, CompletionOptions, SemanticSuggestion}; use nu_protocol::{ Span, SuggestionKind, engine::{Stack, StateWorkingSet}, }; use nu_utils::NuCow; use reedline::Suggestion; use super::completion_options::NuMatcher; pub struct StaticCompletion { options: NuCow<&'static [&'static str], Vec<String>>, } impl StaticCompletion { pub fn new(options: NuCow<&'static [&'static str], Vec<String>>) -> Self { Self { options } } } impl Completer for StaticCompletion { fn fetch( &mut self, _working_set: &StateWorkingSet, _stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut matcher = NuMatcher::new(prefix, options, true); let current_span = reedline::Span { start: span.start - offset, end: span.end - offset, }; let mut add_suggestion = |option: &str| { matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value: option.to_owned(), span: current_span, description: None, ..Suggestion::default() }, kind: Some(SuggestionKind::Value(nu_protocol::Type::String)), }); }; match self.options { NuCow::Borrowed(b) => { for &option in b { add_suggestion(option); } } NuCow::Owned(ref o) => { for option in o { add_suggestion(option.as_str()); } } } matcher.suggestion_results() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/operator_completions.rs
crates/nu-cli/src/completions/operator_completions.rs
use crate::completions::{ Completer, CompletionOptions, SemanticSuggestion, completion_options::NuMatcher, }; use nu_protocol::{ ENV_VARIABLE_ID, Span, SuggestionKind, Type, Value, ast::{self, Comparison, Expr, Expression}, engine::{Stack, StateWorkingSet}, }; use reedline::Suggestion; use strum::{EnumMessage, IntoEnumIterator}; use super::cell_path_completions::eval_cell_path; #[derive(Clone)] pub struct OperatorCompletion<'a> { pub left_hand_side: &'a Expression, } struct OperatorItem { pub symbols: String, pub description: String, } fn operator_to_item<T: EnumMessage + AsRef<str>>(op: T) -> OperatorItem { OperatorItem { symbols: op.as_ref().into(), description: op.get_message().unwrap_or_default().into(), } } fn common_comparison_ops() -> Vec<OperatorItem> { vec![ operator_to_item(Comparison::In), operator_to_item(Comparison::NotIn), operator_to_item(Comparison::Equal), operator_to_item(Comparison::NotEqual), ] } fn all_ops_for_immutable() -> Vec<OperatorItem> { ast::Comparison::iter() .map(operator_to_item) .chain(ast::Math::iter().map(operator_to_item)) .chain(ast::Boolean::iter().map(operator_to_item)) .chain(ast::Bits::iter().map(operator_to_item)) .collect() } fn collection_comparison_ops() -> Vec<OperatorItem> { let mut ops = common_comparison_ops(); ops.push(operator_to_item(Comparison::Has)); ops.push(operator_to_item(Comparison::NotHas)); ops } fn number_comparison_ops() -> Vec<OperatorItem> { Comparison::iter() .filter(|op| { !matches!( op, Comparison::RegexMatch | Comparison::NotRegexMatch | Comparison::StartsWith | Comparison::NotStartsWith | Comparison::EndsWith | Comparison::NotEndsWith | Comparison::Has | Comparison::NotHas ) }) .map(operator_to_item) .collect() } fn math_ops() -> Vec<OperatorItem> { ast::Math::iter() .filter(|op| !matches!(op, ast::Math::Concatenate | ast::Math::Pow)) .map(operator_to_item) .collect() } fn bit_ops() -> Vec<OperatorItem> { ast::Bits::iter().map(operator_to_item).collect() } fn all_assignment_ops() -> Vec<OperatorItem> { ast::Assignment::iter().map(operator_to_item).collect() } fn numeric_assignment_ops() -> Vec<OperatorItem> { ast::Assignment::iter() .filter(|op| !matches!(op, ast::Assignment::ConcatenateAssign)) .map(operator_to_item) .collect() } fn concat_assignment_ops() -> Vec<OperatorItem> { vec![ operator_to_item(ast::Assignment::Assign), operator_to_item(ast::Assignment::ConcatenateAssign), ] } fn valid_int_ops() -> Vec<OperatorItem> { let mut ops = valid_float_ops(); ops.extend(bit_ops()); ops } fn valid_float_ops() -> Vec<OperatorItem> { let mut ops = valid_value_with_unit_ops(); ops.push(operator_to_item(ast::Math::Pow)); ops } fn valid_string_ops() -> Vec<OperatorItem> { let mut ops: Vec<OperatorItem> = Comparison::iter().map(operator_to_item).collect(); ops.push(operator_to_item(ast::Math::Concatenate)); ops.push(OperatorItem { symbols: "like".into(), description: Comparison::RegexMatch .get_message() .unwrap_or_default() .into(), }); ops.push(OperatorItem { symbols: "not-like".into(), description: Comparison::NotRegexMatch .get_message() .unwrap_or_default() .into(), }); ops } fn valid_list_ops() -> Vec<OperatorItem> { let mut ops = collection_comparison_ops(); ops.push(operator_to_item(ast::Math::Concatenate)); ops } fn valid_binary_ops() -> Vec<OperatorItem> { let mut ops = number_comparison_ops(); ops.extend(bit_ops()); ops.push(operator_to_item(ast::Math::Concatenate)); ops } fn valid_bool_ops() -> Vec<OperatorItem> { let mut ops: Vec<OperatorItem> = ast::Boolean::iter().map(operator_to_item).collect(); ops.extend(common_comparison_ops()); ops } fn valid_value_with_unit_ops() -> Vec<OperatorItem> { let mut ops = number_comparison_ops(); ops.extend(math_ops()); ops } fn ops_by_value(value: &Value, mutable: bool) -> Vec<OperatorItem> { let mut ops = match value { Value::Int { .. } => valid_int_ops(), Value::Float { .. } => valid_float_ops(), Value::String { .. } => valid_string_ops(), Value::Binary { .. } => valid_binary_ops(), Value::Bool { .. } => valid_bool_ops(), Value::Date { .. } => number_comparison_ops(), Value::Filesize { .. } | Value::Duration { .. } => valid_value_with_unit_ops(), Value::Range { .. } | Value::Record { .. } => collection_comparison_ops(), Value::List { .. } => valid_list_ops(), _ => all_ops_for_immutable(), }; if mutable { ops.extend(match value { Value::Int { .. } | Value::Float { .. } | Value::Filesize { .. } | Value::Duration { .. } => numeric_assignment_ops(), Value::String { .. } | Value::Binary { .. } | Value::List { .. } => { concat_assignment_ops() } Value::Bool { .. } | Value::Date { .. } | Value::Range { .. } | Value::Record { .. } => vec![operator_to_item(ast::Assignment::Assign)], _ => all_assignment_ops(), }) } ops } fn is_expression_mutable(expr: &Expr, working_set: &StateWorkingSet) -> bool { let Expr::FullCellPath(path) = expr else { return false; }; let Expr::Var(id) = path.head.expr else { return false; }; if id == ENV_VARIABLE_ID { return true; } let var = working_set.get_variable(id); var.mutable } impl Completer for OperatorCompletion<'_> { fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { let mut needs_assignment_ops = true; // Complete according expression type // TODO: type inference on self.left_hand_side to get more accurate completions let mut possible_operations: Vec<OperatorItem> = match &self.left_hand_side.ty { Type::Int | Type::Number => valid_int_ops(), Type::Float => valid_float_ops(), Type::String => valid_string_ops(), Type::Binary => valid_binary_ops(), Type::Bool => valid_bool_ops(), Type::Date => number_comparison_ops(), Type::Filesize | Type::Duration => valid_value_with_unit_ops(), Type::Record(_) | Type::Range => collection_comparison_ops(), Type::List(_) | Type::Table(_) => valid_list_ops(), // Unknown type, resort to evaluated values Type::Any => match &self.left_hand_side.expr { Expr::FullCellPath(path) => { // for `$ <tab>` if let Expr::Garbage = path.head.expr { return vec![]; } let value = eval_cell_path(working_set, stack, &path.head, &path.tail, path.head.span) .unwrap_or_default(); let mutable = is_expression_mutable(&self.left_hand_side.expr, working_set); // to avoid duplication needs_assignment_ops = false; ops_by_value(&value, mutable) } _ => all_ops_for_immutable(), }, _ => common_comparison_ops(), }; // If the left hand side is a variable, add assignment operators if mutable if needs_assignment_ops && is_expression_mutable(&self.left_hand_side.expr, working_set) { possible_operations.extend(match &self.left_hand_side.ty { Type::Int | Type::Float | Type::Number => numeric_assignment_ops(), Type::Filesize | Type::Duration => numeric_assignment_ops(), Type::String | Type::Binary | Type::List(_) => concat_assignment_ops(), Type::Any => all_assignment_ops(), _ => vec![operator_to_item(ast::Assignment::Assign)], }); } let mut matcher = NuMatcher::new(prefix, options, true); for OperatorItem { symbols, description, } in possible_operations { matcher.add_semantic_suggestion(SemanticSuggestion { suggestion: Suggestion { value: symbols.to_owned(), description: Some(description.to_owned()), span: reedline::Span::new(span.start - offset, span.end - offset), append_whitespace: true, ..Suggestion::default() }, kind: Some(SuggestionKind::Operator), }); } matcher.suggestion_results() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/completions/arg_value_completion.rs
crates/nu-cli/src/completions/arg_value_completion.rs
use crate::{ FileCompletion, NuCompleter, completions::{ CommandCompletion, Completer, CompletionOptions, DirectoryCompletion, DotNuCompletion, ExportableCompletion, SemanticSuggestion, completer::Context, completion_options::NuMatcher, }, }; use nu_parser::parse_module_file_or_dir; use nu_protocol::{ DynamicCompletionCallRef, Span, ast::{Argument, Call, Expr, Expression, ListItem}, engine::{ArgType, Stack, StateWorkingSet}, }; pub struct ArgValueCompletion<'a> { pub call: &'a Call, pub arg_type: ArgType<'a>, pub need_fallback: bool, pub completer: &'a NuCompleter, pub arg_idx: usize, pub pos: usize, pub strip: bool, } impl<'a> Completer for ArgValueCompletion<'a> { fn fetch( &mut self, working_set: &StateWorkingSet, stack: &Stack, prefix: impl AsRef<str>, span: Span, offset: usize, options: &CompletionOptions, ) -> Vec<SemanticSuggestion> { // if user input `--foo abc`, then the `prefix` here is abc. let mut matcher = NuMatcher::new(prefix.as_ref(), options, true); let decl = working_set.get_decl(self.call.decl_id); let mut stack = stack.to_owned(); let dynamic_completion_call = DynamicCompletionCallRef { call: self.call, strip: self.strip, pos: self.pos, }; match decl.get_dynamic_completion( working_set.permanent_state, &mut stack, dynamic_completion_call, &self.arg_type, #[expect(deprecated, reason = "internal usage")] nu_protocol::engine::ExperimentalMarker, ) { Ok(Some(items)) => { for i in items { let result_span = i.span.unwrap_or(span); let suggestion = SemanticSuggestion::from_dynamic_suggestion( i, reedline::Span { start: result_span.start - offset, end: result_span.end - offset, }, None, ); matcher.add_semantic_suggestion(suggestion); } return matcher.suggestion_results(); } Err(e) => { log::error!( "error on fetching dynamic suggestion on {} with {:?}: {e}", decl.name(), self.arg_type ); } // fallback to type based completion, file completion, etc. Ok(None) => (), } let command_head = decl.name(); let ctx = Context::new(working_set, span, prefix.as_ref().as_bytes(), offset); let expr = self .call .arguments .get(self.arg_idx) .expect("Argument index out of range") .expr() .map(|e| &e.expr); // TODO: Move command specific completion logic to its `get_dynamic_completion` if let ArgType::Positional(positional_arg_index) = self.arg_type { match command_head { // complete module file/directory "use" | "export use" | "overlay use" | "source-env" if positional_arg_index == 0 => { return self.completer.process_completion( &mut DotNuCompletion { std_virtual_path: command_head != "source-env", }, &ctx, ); } // NOTE: if module file already specified, // should parse it to get modules/commands/consts to complete "use" | "export use" => { let Some((module_name, span)) = self.call.arguments.iter().find_map(|arg| { if let Argument::Positional(Expression { expr: Expr::String(module_name), span, .. }) = arg { Some((module_name.as_bytes(), span)) } else { None } }) else { return vec![]; }; let (module_id, temp_working_set) = match working_set.find_module(module_name) { Some(module_id) => (module_id, None), None => { let mut temp_working_set = StateWorkingSet::new(working_set.permanent_state); let Some(module_id) = parse_module_file_or_dir( &mut temp_working_set, module_name, *span, None, ) else { return vec![]; }; (module_id, Some(temp_working_set)) } }; let mut exportable_completion = ExportableCompletion { module_id, temp_working_set, }; let mut complete_on_list_items = |items: &[ListItem]| -> Vec<SemanticSuggestion> { for item in items { let span = item.expr().span; if span.contains(self.pos) { let offset = span.start.saturating_sub(ctx.span.start); let end_offset = ctx .prefix .len() .min(self.pos.min(span.end) - ctx.span.start + 1); let new_ctx = Context::new( ctx.working_set, Span::new(span.start, ctx.span.end.min(span.end)), ctx.prefix.get(offset..end_offset).unwrap_or_default(), ctx.offset, ); return self .completer .process_completion(&mut exportable_completion, &new_ctx); } } vec![] }; return match expr { Some(Expr::String(_)) => self .completer .process_completion(&mut exportable_completion, &ctx), Some(Expr::FullCellPath(fcp)) => match &fcp.head.expr { Expr::List(items) => complete_on_list_items(items), _ => vec![], }, _ => vec![], }; } "which" => { let mut completer = CommandCompletion { internals: true, externals: true, }; return self.completer.process_completion(&mut completer, &ctx); } "attr complete" => { let mut completer = CommandCompletion { internals: true, externals: false, }; return self.completer.process_completion(&mut completer, &ctx); } _ => (), } }; // general positional arguments let file_completion_helper = || self.completer.process_completion(&mut FileCompletion, &ctx); match expr { Some(Expr::Directory(_, _)) => self .completer .process_completion(&mut DirectoryCompletion, &ctx), Some(Expr::Filepath(_, _)) | Some(Expr::GlobPattern(_, _)) => file_completion_helper(), // fallback to file completion if necessary _ if self.need_fallback => file_completion_helper(), _ => vec![], } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/menus/help_completions.rs
crates/nu-cli/src/menus/help_completions.rs
use nu_engine::documentation::{FormatterValue, HelpStyle, get_flags_section}; use nu_protocol::{Config, engine::EngineState, levenshtein_distance}; use nu_utils::IgnoreCaseExt; use reedline::{Completer, Suggestion}; use std::{fmt::Write, sync::Arc}; pub struct NuHelpCompleter { engine_state: Arc<EngineState>, config: Arc<Config>, } impl NuHelpCompleter { pub fn new(engine_state: Arc<EngineState>, config: Arc<Config>) -> Self { Self { engine_state, config, } } fn completion_helper(&self, line: &str, pos: usize) -> Vec<Suggestion> { let folded_line = line.to_folded_case(); let mut help_style = HelpStyle::default(); help_style.update_from_config(&self.engine_state, &self.config); let mut commands = self .engine_state .get_decls_sorted(false) .into_iter() .filter_map(|(_, decl_id)| { let decl = self.engine_state.get_decl(decl_id); (decl.name().to_folded_case().contains(&folded_line) || decl.description().to_folded_case().contains(&folded_line) || decl .search_terms() .into_iter() .any(|term| term.to_folded_case().contains(&folded_line)) || decl .extra_description() .to_folded_case() .contains(&folded_line)) .then_some(decl) }) .collect::<Vec<_>>(); commands.sort_by_cached_key(|decl| levenshtein_distance(line, decl.name())); commands .into_iter() .map(|decl| { let mut long_desc = String::new(); let description = decl.description(); if !description.is_empty() { long_desc.push_str(description); long_desc.push_str("\r\n\r\n"); } let extra_desc = decl.extra_description(); if !extra_desc.is_empty() { long_desc.push_str(extra_desc); long_desc.push_str("\r\n\r\n"); } let sig = decl.signature(); let _ = write!(long_desc, "Usage:\r\n > {}\r\n", sig.call_signature()); if !sig.named.is_empty() { long_desc.push_str(&get_flags_section(&sig, &help_style, |v| match v { FormatterValue::DefaultValue(value) => { value.to_parsable_string(", ", &self.config) } FormatterValue::CodeString(text) => text.to_string(), })) } if !sig.required_positional.is_empty() || !sig.optional_positional.is_empty() || sig.rest_positional.is_some() { long_desc.push_str("\r\nParameters:\r\n"); for positional in &sig.required_positional { let _ = write!(long_desc, " {}: {}\r\n", positional.name, positional.desc); } for positional in &sig.optional_positional { let opt_suffix = if let Some(value) = &positional.default_value { format!( " (optional, default: {})", &value.to_parsable_string(", ", &self.config), ) } else { (" (optional)").to_string() }; let _ = write!( long_desc, " (optional) {}: {}{}\r\n", positional.name, positional.desc, opt_suffix ); } if let Some(rest_positional) = &sig.rest_positional { let _ = write!( long_desc, " ...{}: {}\r\n", rest_positional.name, rest_positional.desc ); } } let extra: Vec<String> = decl .examples() .iter() .map(|example| example.example.replace('\n', "\r\n")) .collect(); Suggestion { value: decl.name().into(), description: Some(long_desc), extra: Some(extra), span: reedline::Span { start: pos - line.len(), end: pos, }, ..Suggestion::default() } }) .collect() } } impl Completer for NuHelpCompleter { fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> { self.completion_helper(line, pos) } } #[cfg(test)] mod test { use super::*; use rstest::rstest; #[rstest] #[case("who", 5, 8, &["whoami", "each"])] #[case("hash", 1, 5, &["hash", "hash md5", "hash sha256"])] #[case("into f", 0, 6, &["into float", "into filesize"])] #[case("into nonexistent", 0, 16, &[])] fn test_help_completer( #[case] line: &str, #[case] start: usize, #[case] end: usize, #[case] expected: &[&str], ) { let engine_state = nu_command::add_shell_command_context(nu_cmd_lang::create_default_context()); let config = engine_state.get_config().clone(); let mut completer = NuHelpCompleter::new(engine_state.into(), config); let suggestions = completer.complete(line, end); assert_eq!( expected.len(), suggestions.len(), "expected {:?}, got {:?}", expected, suggestions .iter() .map(|s| s.value.clone()) .collect::<Vec<_>>() ); for (exp, actual) in expected.iter().zip(suggestions) { assert_eq!(exp, &actual.value); assert_eq!(reedline::Span::new(start, end), actual.span); } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/menus/mod.rs
crates/nu-cli/src/menus/mod.rs
mod help_completions; mod menu_completions; pub use help_completions::NuHelpCompleter; pub use menu_completions::NuMenuCompleter;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/src/menus/menu_completions.rs
crates/nu-cli/src/menus/menu_completions.rs
use nu_engine::eval_block; use nu_protocol::{ BlockId, IntoPipelineData, Span, Value, debugger::WithoutDebug, engine::{EngineState, Stack}, }; use reedline::{Completer, Suggestion, menu_functions::parse_selection_char}; use std::sync::Arc; const SELECTION_CHAR: char = '!'; pub struct NuMenuCompleter { block_id: BlockId, span: Span, stack: Stack, engine_state: Arc<EngineState>, only_buffer_difference: bool, } impl NuMenuCompleter { pub fn new( block_id: BlockId, span: Span, stack: Stack, engine_state: Arc<EngineState>, only_buffer_difference: bool, ) -> Self { Self { block_id, span, stack: stack.reset_out_dest().collect_value(), engine_state, only_buffer_difference, } } } impl Completer for NuMenuCompleter { fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> { let parsed = parse_selection_char(line, SELECTION_CHAR); let block = self.engine_state.get_block(self.block_id); if let Some(buffer) = block.signature.get_positional(0) && let Some(buffer_id) = &buffer.var_id { let line_buffer = Value::string(parsed.remainder, self.span); self.stack.add_var(*buffer_id, line_buffer); } if let Some(position) = block.signature.get_positional(1) && let Some(position_id) = &position.var_id { let line_buffer = Value::int(pos as i64, self.span); self.stack.add_var(*position_id, line_buffer); } let input = Value::nothing(self.span).into_pipeline_data(); let res = eval_block::<WithoutDebug>(&self.engine_state, &mut self.stack, block, input) .map(|p| p.body); if let Ok(values) = res.and_then(|data| data.into_value(self.span)) { convert_to_suggestions(values, line, pos, self.only_buffer_difference) } else { Vec::new() } } } fn convert_to_suggestions( value: Value, line: &str, pos: usize, only_buffer_difference: bool, ) -> Vec<Suggestion> { match value { Value::Record { val, .. } => { let text = val .get("value") .and_then(|val| val.coerce_string().ok()) .unwrap_or_else(|| "No value key".to_string()); let description = val .get("description") .and_then(|val| val.coerce_string().ok()); let span = match val.get("span") { Some(Value::Record { val: span, .. }) => { let start = span.get("start").and_then(|val| val.as_int().ok()); let end = span.get("end").and_then(|val| val.as_int().ok()); match (start, end) { (Some(start), Some(end)) => { let start = start.min(end); reedline::Span { start: start as usize, end: end as usize, } } _ => reedline::Span { start: if only_buffer_difference { pos - line.len() } else { 0 }, end: if only_buffer_difference { pos } else { line.len() }, }, } } _ => reedline::Span { start: if only_buffer_difference { pos - line.len() } else { 0 }, end: if only_buffer_difference { pos } else { line.len() }, }, }; let extra = match val.get("extra") { Some(Value::List { vals, .. }) => { let extra: Vec<String> = vals .iter() .filter_map(|extra| match extra { Value::String { val, .. } => Some(val.clone()), _ => None, }) .collect(); Some(extra) } _ => None, }; vec![Suggestion { value: text, description, extra, span, ..Suggestion::default() }] } Value::List { vals, .. } => vals .into_iter() .flat_map(|val| convert_to_suggestions(val, line, pos, only_buffer_difference)) .collect(), _ => vec![Suggestion { value: format!("Not a record: {value:?}"), span: reedline::Span { start: if only_buffer_difference { pos - line.len() } else { 0 }, end: if only_buffer_difference { pos } else { line.len() }, }, ..Suggestion::default() }], } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/tests/main.rs
crates/nu-cli/tests/main.rs
mod commands; mod completions;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/tests/commands/history_import.rs
crates/nu-cli/tests/commands/history_import.rs
use nu_protocol::HistoryFileFormat; use nu_test_support::{Outcome, nu}; use reedline::{ FileBackedHistory, History, HistoryItem, HistoryItemId, ReedlineError, SearchQuery, SqliteBackedHistory, }; use rstest::rstest; use tempfile::TempDir; struct Test { cfg_dir: TempDir, } impl Test { fn new(history_format: &'static str) -> Self { let cfg_dir = tempfile::Builder::new() .prefix("history_import_test") .tempdir() .unwrap(); // Assigning to $env.config.history.file_format seems to work only in startup // configuration. std::fs::write( cfg_dir.path().join("env.nu"), format!("$env.config.history.file_format = {history_format:?}"), ) .unwrap(); Self { cfg_dir } } fn nu(&self, cmd: impl AsRef<str>) -> Outcome { let env = [( "XDG_CONFIG_HOME".to_string(), self.cfg_dir.path().to_str().unwrap().to_string(), )]; let env_config = self.cfg_dir.path().join("env.nu"); nu!(envs: env, env_config: env_config, cmd.as_ref()) } fn open_plaintext(&self) -> Result<FileBackedHistory, ReedlineError> { FileBackedHistory::with_file( 100, self.cfg_dir .path() .join("nushell") .join(HistoryFileFormat::Plaintext.default_file_name()), ) } fn open_sqlite(&self) -> Result<SqliteBackedHistory, ReedlineError> { SqliteBackedHistory::with_file( self.cfg_dir .path() .join("nushell") .join(HistoryFileFormat::Sqlite.default_file_name()), None, None, ) } fn open_backend(&self, format: HistoryFileFormat) -> Result<Box<dyn History>, ReedlineError> { fn boxed(be: impl History + 'static) -> Box<dyn History> { Box::new(be) } use HistoryFileFormat::*; match format { Plaintext => self.open_plaintext().map(boxed), Sqlite => self.open_sqlite().map(boxed), } } } enum HistorySource { Vec(Vec<HistoryItem>), Command(&'static str), } struct TestCase { dst_format: HistoryFileFormat, dst_history: Vec<HistoryItem>, src_history: HistorySource, want_history: Vec<HistoryItem>, } const EMPTY_TEST_CASE: TestCase = TestCase { dst_format: HistoryFileFormat::Plaintext, dst_history: Vec::new(), src_history: HistorySource::Vec(Vec::new()), want_history: Vec::new(), }; impl TestCase { fn run(self) { use HistoryFileFormat::*; let test = Test::new(match self.dst_format { Plaintext => "plaintext", Sqlite => "sqlite", }); save_all( &mut *test.open_backend(self.dst_format).unwrap(), self.dst_history, ) .unwrap(); let outcome = match self.src_history { HistorySource::Vec(src_history) => { let src_format = match self.dst_format { Plaintext => Sqlite, Sqlite => Plaintext, }; save_all(&mut *test.open_backend(src_format).unwrap(), src_history).unwrap(); test.nu("history import") } HistorySource::Command(cmd) => { let mut cmd = cmd.to_string(); cmd.push_str(" | history import"); test.nu(cmd) } }; assert!(outcome.status.success()); let got = query_all(&*test.open_backend(self.dst_format).unwrap()).unwrap(); // Compare just the commands first, for readability. fn commands_only(items: &[HistoryItem]) -> Vec<&str> { items .iter() .map(|item| item.command_line.as_str()) .collect() } assert_eq!(commands_only(&got), commands_only(&self.want_history)); // If commands match, compare full items. assert_eq!(got, self.want_history); } } fn query_all(history: &dyn History) -> Result<Vec<HistoryItem>, ReedlineError> { history.search(SearchQuery::everything( reedline::SearchDirection::Forward, None, )) } fn save_all(history: &mut dyn History, items: Vec<HistoryItem>) -> Result<(), ReedlineError> { for item in items { history.save(item)?; } Ok(()) } const EMPTY_ITEM: HistoryItem = HistoryItem { command_line: String::new(), id: None, start_timestamp: None, session_id: None, hostname: None, cwd: None, duration: None, exit_status: None, more_info: None, }; #[test] fn history_import_pipe_string() { TestCase { dst_format: HistoryFileFormat::Plaintext, src_history: HistorySource::Command("echo bar"), want_history: vec![HistoryItem { id: Some(HistoryItemId::new(0)), command_line: "bar".to_string(), ..EMPTY_ITEM }], ..EMPTY_TEST_CASE } .run(); } #[test] fn history_import_pipe_record() { TestCase { dst_format: HistoryFileFormat::Sqlite, src_history: HistorySource::Command("[[cwd command]; [/tmp some_command]]"), want_history: vec![HistoryItem { id: Some(HistoryItemId::new(1)), command_line: "some_command".to_string(), cwd: Some("/tmp".to_string()), ..EMPTY_ITEM }], ..EMPTY_TEST_CASE } .run(); } #[test] fn to_empty_plaintext() { TestCase { dst_format: HistoryFileFormat::Plaintext, src_history: HistorySource::Vec(vec![ HistoryItem { command_line: "foo".to_string(), ..EMPTY_ITEM }, HistoryItem { command_line: "bar".to_string(), ..EMPTY_ITEM }, ]), want_history: vec![ HistoryItem { id: Some(HistoryItemId::new(0)), command_line: "foo".to_string(), ..EMPTY_ITEM }, HistoryItem { id: Some(HistoryItemId::new(1)), command_line: "bar".to_string(), ..EMPTY_ITEM }, ], ..EMPTY_TEST_CASE } .run() } #[test] fn to_empty_sqlite() { TestCase { dst_format: HistoryFileFormat::Sqlite, src_history: HistorySource::Vec(vec![ HistoryItem { command_line: "foo".to_string(), ..EMPTY_ITEM }, HistoryItem { command_line: "bar".to_string(), ..EMPTY_ITEM }, ]), want_history: vec![ HistoryItem { id: Some(HistoryItemId::new(1)), command_line: "foo".to_string(), ..EMPTY_ITEM }, HistoryItem { id: Some(HistoryItemId::new(2)), command_line: "bar".to_string(), ..EMPTY_ITEM }, ], ..EMPTY_TEST_CASE } .run() } #[rstest] #[case::plaintext(HistoryFileFormat::Plaintext)] #[case::sqlite(HistoryFileFormat::Sqlite)] fn to_existing(#[case] dst_format: HistoryFileFormat) { TestCase { dst_format, dst_history: vec![ HistoryItem { id: Some(HistoryItemId::new(0)), command_line: "original-1".to_string(), ..EMPTY_ITEM }, HistoryItem { id: Some(HistoryItemId::new(1)), command_line: "original-2".to_string(), ..EMPTY_ITEM }, ], src_history: HistorySource::Vec(vec![HistoryItem { id: Some(HistoryItemId::new(1)), command_line: "new".to_string(), ..EMPTY_ITEM }]), want_history: vec![ HistoryItem { id: Some(HistoryItemId::new(0)), command_line: "original-1".to_string(), ..EMPTY_ITEM }, HistoryItem { id: Some(HistoryItemId::new(1)), command_line: "original-2".to_string(), ..EMPTY_ITEM }, HistoryItem { id: Some(HistoryItemId::new(2)), command_line: "new".to_string(), ..EMPTY_ITEM }, ], } .run() }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/tests/commands/mod.rs
crates/nu-cli/tests/commands/mod.rs
mod keybindings_list; mod nu_highlight; #[cfg(feature = "sqlite")] mod history_import;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/tests/commands/nu_highlight.rs
crates/nu-cli/tests/commands/nu_highlight.rs
use nu_test_support::nu; #[test] fn nu_highlight_not_expr() { let actual = nu!("'not false' | nu-highlight | ansi strip"); assert_eq!(actual.out, "not false"); } #[test] fn nu_highlight_where_row_condition() { let actual = nu!("'ls | where a b 12345(' | nu-highlight | ansi strip"); assert_eq!(actual.out, "ls | where a b 12345("); } #[test] fn nu_highlight_aliased_external_resolved() { let actual = nu!(r#"$env.config.highlight_resolved_externals = true $env.config.color_config.shape_external_resolved = '#ffffff' alias fff = ^rustc ('fff' | nu-highlight) has (ansi $env.config.color_config.shape_external_resolved)"#); assert_eq!(actual.out, "true"); } #[test] fn nu_highlight_aliased_external_unresolved() { let actual = nu!(r#"$env.config.highlight_resolved_externals = true $env.config.color_config.shape_external = '#ffffff' alias fff = ^nonexist ('fff' | nu-highlight) has (ansi $env.config.color_config.shape_external)"#); assert_eq!(actual.out, "true"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/tests/commands/keybindings_list.rs
crates/nu-cli/tests/commands/keybindings_list.rs
use nu_test_support::nu; #[test] fn not_empty() { let result = nu!("keybindings list | is-not-empty"); assert_eq!(result.out, "true"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/tests/completions/mod.rs
crates/nu-cli/tests/completions/mod.rs
pub mod support; use std::{ fs::{FileType, ReadDir, read_dir}, path::{MAIN_SEPARATOR, PathBuf}, sync::Arc, }; use nu_cli::NuCompleter; use nu_engine::eval_block; use nu_parser::parse; use nu_path::{AbsolutePathBuf, expand_tilde}; use nu_protocol::{ Config, ParseError, PipelineData, debugger::WithoutDebug, engine::StateWorkingSet, }; use nu_std::load_standard_library; use nu_test_support::fs; use reedline::{Completer, Span, Suggestion}; use rstest::{fixture, rstest}; use support::{ completions_helpers::{ new_dotnu_engine, new_engine_helper, new_external_engine, new_partial_engine, new_quote_engine, }, file, folder, match_suggestions, match_suggestions_by_string, new_engine, }; // Match a list of suggestions with the content of a directory. // This helper is for DotNutCompletion, so actually it only retrieves // *.nu files and subdirectories. pub fn match_dir_content_for_dotnu(dir: ReadDir, suggestions: &[Suggestion]) { let actual_dir_entries: Vec<_> = dir.filter_map(|c| c.ok()).collect(); let type_name_pairs: Vec<(FileType, String)> = actual_dir_entries .into_iter() .filter_map(|t| t.file_type().ok().zip(t.file_name().into_string().ok())) .collect(); let mut simple_dir_entries: Vec<&str> = type_name_pairs .iter() .filter_map(|(t, n)| { if t.is_dir() || n.ends_with(".nu") { Some(n.as_str()) } else { None } }) .collect(); simple_dir_entries.sort(); let mut pure_suggestions: Vec<&str> = suggestions .iter() .map(|s| { // The file names in suggestions contain some extra characters, // we clean them to compare more exactly with read_dir result. s.value .as_str() .trim_matches('`') .trim_start_matches("~") .trim_matches('/') .trim_matches('\\') }) .collect(); pure_suggestions.sort(); assert_eq!(simple_dir_entries, pure_suggestions); } #[fixture] fn completer() -> NuCompleter { // Create a new engine let (_, _, mut engine, mut stack) = new_engine(); // Add record value as example let record = "def tst [--mod -s] {}"; assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack).is_ok()); // Instantiate a new completer NuCompleter::new(Arc::new(engine), Arc::new(stack)) } #[fixture] fn completer_strings() -> NuCompleter { // Create a new engine let (_, _, mut engine, mut stack) = new_engine(); // Add record value as example let record = r#"def animals [] { ["cat", "dog", "eel" ] } def my-command [animal: string@animals] { print $animal }"#; assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack).is_ok()); // Instantiate a new completer NuCompleter::new(Arc::new(engine), Arc::new(stack)) } #[fixture] fn extern_completer() -> NuCompleter { // Create a new engine let (_, _, mut engine, mut stack) = new_engine(); // Add record value as example let record = r#" def animals [] { [ "cat", "dog", "eel" ] } def fruits [] { [ "apple", "banana" ] } def options [] { [ '"first item"', '"second item"', '"third item' ] } extern spam [ animal: string@animals fruit?: string@fruits ...rest: string@animals --foo (-f): string@animals -b: string@animals --options: string@options ] "#; assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack).is_ok()); // Instantiate a new completer NuCompleter::new(Arc::new(engine), Arc::new(stack)) } fn custom_completer_with_options( global_opts: &str, completer_opts: &str, completions: &[&str], ) -> NuCompleter { let (_, _, mut engine, mut stack) = new_engine(); let command = format!( r#" {} def comp [] {{ {{ completions: [{}], options: {{ {} }} }} }} def my-command [arg: string@comp] {{}}"#, global_opts, completions .iter() .map(|comp| format!("'{comp}'")) .collect::<Vec<_>>() .join(", "), completer_opts, ); assert!(support::merge_input(command.as_bytes(), &mut engine, &mut stack).is_ok()); NuCompleter::new(Arc::new(engine), Arc::new(stack)) } #[fixture] fn custom_completer() -> NuCompleter { // Create a new engine let (_, _, mut engine, mut stack) = new_engine(); // Add record value as example let record = r#" let external_completer = {|spans| $spans } $env.config.completions.external = { enable: true max_results: 100 completer: $external_completer } "#; assert!(support::merge_input(record.as_bytes(), &mut engine, &mut stack).is_ok()); // Instantiate a new completer NuCompleter::new(Arc::new(engine), Arc::new(stack)) } /// Use fuzzy completions but sort in alphabetical order #[fixture] fn fuzzy_alpha_sort_completer() -> NuCompleter { // Create a new engine let (_, _, mut engine, mut stack) = new_engine(); let config = r#" $env.config.completions.algorithm = "fuzzy" $env.config.completions.sort = "alphabetical" "#; assert!(support::merge_input(config.as_bytes(), &mut engine, &mut stack).is_ok()); // Instantiate a new completer NuCompleter::new(Arc::new(engine), Arc::new(stack)) } #[rstest] #[case::double_dash_long_flag("tst --", None, vec!["--help", "--mod"])] #[case::single_dash_all_flags("tst -", None, vec!["--help", "--mod", "-h", "-s"])] #[case::flags_after_cursor("tst -h", Some(5), vec!["--help", "--mod", "-h", "-s"])] #[case::flags_after_cursor_piped("tst -h | ls", Some(5), vec!["--help", "--mod", "-h", "-s"])] #[case::flags_in_nested_block1("somecmd | lines | each { tst - }", Some(30), vec!["--help", "--mod", "-h", "-s"])] #[case::flags_in_nested_block2("somecmd | lines | each { tst -}", Some(30), vec!["--help", "--mod", "-h", "-s"])] #[case::flags_in_incomplete_nested_block("somecmd | lines | each { tst -", None, vec!["--help", "--mod", "-h", "-s"])] #[case::flags_in_deeply_nested_block("somecmd | lines | each { print ([each (print) (tst -)]) }", Some(52), vec!["--help", "--mod", "-h", "-s"])] #[case::dynamic_long_flag_value("fake-cmd --flag ", None, vec!["flag:0", "flag:1", "flag:2"])] #[case::dynamic_short_flag_value("fake-cmd arg0:0 -f ", None, vec!["flag:0", "flag:1", "flag:2"])] #[case::dynamic_1st_positional("fake-cmd -f flag:0 ", None, vec!["arg0:0"])] #[case::dynamic_2nd_positional("fake-cmd -f flag:0 foo --unknown ", None, vec!["arg1:0", "arg1:1"])] fn misc_command_argument_completions( mut completer: NuCompleter, #[case] input: &str, #[case] pos: Option<usize>, #[case] expected: Vec<&str>, ) { let suggestions = completer.complete(input, pos.unwrap_or(input.len())); match_suggestions(&expected, &suggestions); } #[rstest] #[case::command_name("my-c", None, vec!["my-command"])] #[case::command_argument("my-command ", None, vec!["cat", "dog", "eel"])] #[case::command_argument_after_cursor("my-command c", Some(11), vec!["cat", "dog", "eel"])] #[case::command_argument_after_cursor_piped("my-command c | ls", Some(11), vec!["cat", "dog", "eel"])] fn misc_custom_completions( mut completer_strings: NuCompleter, #[case] input: &str, #[case] pos: Option<usize>, #[case] expected: Vec<&str>, ) { let suggestions = completer_strings.complete(input, pos.unwrap_or(input.len())); match_suggestions(&expected, &suggestions); } /// $env.config should be overridden by the custom completer's options #[test] fn customcompletions_override_options() { let mut completer = custom_completer_with_options( r#"$env.config.completions.algorithm = "fuzzy" $env.config.completions.case_sensitive = false"#, r#"completion_algorithm: "substring", case_sensitive: true, sort: true"#, &["Foo Abcdef", "Abcdef", "Acd Bar"], ); // sort: true should force sorting let expected: Vec<_> = vec!["Abcdef", "Foo Abcdef"]; let suggestions = completer.complete("my-command Abcd", 15); match_suggestions(&expected, &suggestions); // Custom options should make case-sensitive let suggestions = completer.complete("my-command aBcD", 15); assert!(suggestions.is_empty()); } /// $env.config should be inherited by the custom completer's options #[test] fn customcompletions_inherit_options() { let mut completer = custom_completer_with_options( r#"$env.config.completions.algorithm = "fuzzy" $env.config.completions.case_sensitive = false"#, "", &["Foo Abcdef", "Abcdef", "Acd Bar"], ); // Make sure matching is fuzzy let suggestions = completer.complete("my-command Acd", 14); let expected: Vec<_> = vec!["Acd Bar", "Abcdef", "Foo Abcdef"]; match_suggestions(&expected, &suggestions); // Custom options should make matching case insensitive let suggestions = completer.complete("my-command acd", 14); match_suggestions(&expected, &suggestions); } #[test] fn customcompletions_no_sort() { let mut completer = custom_completer_with_options( "", r#"completion_algorithm: "fuzzy", sort: false"#, &["zzzfoo", "foo", "not matched", "abcfoo"], ); let suggestions = completer.complete("my-command foo", 14); let expected_items = vec!["zzzfoo", "foo", "abcfoo"]; let expected_inds = vec![ Some(vec![3, 4, 5]), Some(vec![0, 1, 2]), Some(vec![3, 4, 5]), ]; match_suggestions(&expected_items, &suggestions); assert_eq!( expected_inds, suggestions .iter() .map(|s| s.match_indices.clone()) .collect::<Vec<_>>() ); } #[test] fn customcompletions_no_filter() { let mut completer = custom_completer_with_options( "", r#"filter: false"#, &["zzzfoo", "foo", "not matched", "abcfoo"], ); let suggestions = completer.complete("my-command foo", 14); let expected_items = vec!["zzzfoo", "foo", "not matched", "abcfoo"]; match_suggestions(&expected_items, &suggestions); } #[rstest] #[case::happy("{ start: 1, end: 14 }", (7, 20))] #[case::no_start("{ end: 14 }", (17, 20))] #[case::no_end("{ start: 1 }", (7, 23))] #[case::bad_start("{ start: 100 }", (23, 23))] #[case::bad_end("{ end: 100 }", (17, 23))] fn custom_completions_override_span( #[case] span_string: &str, #[case] expected_span: (usize, usize), ) { let (_, _, mut engine, mut stack) = new_engine(); let command = format!( r#" def comp [] {{ [{{ value: foobarbaz, span: {span_string} }}] }} def my-command [arg: string@comp] {{}}"# ); assert!(support::merge_input(command.as_bytes(), &mut engine, &mut stack).is_ok()); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); let completion_str = "foo | my-command foobar"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["foobarbaz"], &suggestions); let (start, end) = expected_span; assert_eq!(Span::new(start, end), suggestions[0].span); } #[rstest] /// Fallback to file completions if custom completer returns null #[case::fallback(r#" def comp [] { null } def my-command [arg: string@comp] {}"#, "my-command test", None, vec![folder("test_a"), file("test_a_symlink"), folder("test_b")], 4 )] /// Custom function arguments mixed with subcommands #[case::arguments_and_subcommands(r#" def foo [i: directory] {} def "foo test bar" [] {}"#, "foo test", None, vec![folder("test_a"), file("test_a_symlink"), folder("test_b"), "foo test bar".into()], 8 )] /// If argument type is something like int/string, complete only subcommands #[case::arguments_vs_subcommands(r#" def foo [i: string] {} def "foo test bar" [] {}"#, "foo test", None, vec!["foo test bar".into()], 8 )] /// Custom function flags mixed with subcommands #[case::flags_and_subcommands(r#" def foo [--test: directory] {} def "foo --test bar" [] {}"#, "foo --test", None, vec!["--test".into(), "foo --test bar".into()], 10 )] /// Flag value completion for directories #[case::flag_value_and_subcommands(r#" def foo [--test: directory] {} def "foo --test test" [] {}"#, "foo --test test", None, vec![folder("test_a"), file("test_a_symlink"), folder("test_b"), "foo --test test".into()], "foo --test test".len() )] // Directory only #[case::flag_value_respect_to_type(r#" def foo [--test: directory] {}"#, &format!("foo --test=directory_completion{MAIN_SEPARATOR}"), None, vec![folder(format!("directory_completion{MAIN_SEPARATOR}folder_inside_folder"))], format!("directory_completion{MAIN_SEPARATOR}").len() )] #[case::short_flag_value(r#" def foo [-t: directory] {}"#, &format!("foo -t directory_completion{MAIN_SEPARATOR}"), None, vec![folder(format!("directory_completion{MAIN_SEPARATOR}folder_inside_folder"))], format!("directory_completion{MAIN_SEPARATOR}").len() )] #[case::mixed_positional_and_flag1(r#" def foo [-t: directory, --path: path, pos: string, opt?: directory] {}"#, &format!("foo --path directory_completion{MAIN_SEPARATOR}"), None, vec![ folder(format!("directory_completion{MAIN_SEPARATOR}folder_inside_folder")), file(format!("directory_completion{MAIN_SEPARATOR}mod.nu")) ], format!("directory_completion{MAIN_SEPARATOR}").len() )] #[case::mixed_positional_and_flag2(r#" def foo [-t: directory, --path: path, pos: string, opt?: directory] {}"#, &format!("foo --path bar baz directory_completion{MAIN_SEPARATOR}"), None, vec![folder(format!("directory_completion{MAIN_SEPARATOR}folder_inside_folder"))], format!("directory_completion{MAIN_SEPARATOR}").len() )] #[case::mixed_positional_and_flag3(r#" def foo [-t: directory, --path: path, pos: string, opt?: directory] {}"#, &format!("foo --path bar baz qux -t directory_completion{MAIN_SEPARATOR}"), None, vec![folder(format!("directory_completion{MAIN_SEPARATOR}folder_inside_folder"))], format!("directory_completion{MAIN_SEPARATOR}").len() )] #[case::defined_inline( "", "export def say [ animal: string@[cat dog] ] { }; say ", None, vec!["cat".into(), "dog".into()], 0 )] #[case::short_flags( "def foo [-A, -B: string@[cat dog] ] {}", "foo -B ", None, vec!["cat".into(), "dog".into()], 0 )] #[case::flag_name_vs_value( "def foo [-A, -B: string@[cat dog] ] {}", "foo -B cat", Some("foo -B".len()), vec!["-B".into()], 2 )] fn command_argument_completions( #[case] command: &str, #[case] input: &str, #[case] pos: Option<usize>, #[case] expected: Vec<String>, #[case] span_size: usize, ) { let (_, _, mut engine, mut stack) = new_engine(); assert!(support::merge_input(command.as_bytes(), &mut engine, &mut stack).is_ok()); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); // `pos` defaults to `input.len()` if set to None let span_end = pos.unwrap_or(input.len()); let suggestions = completer.complete(input, span_end); match_suggestions_by_string(&expected, &suggestions); let last_res = suggestions.last().unwrap(); assert_eq!(last_res.span.start, span_end - span_size); assert_eq!(last_res.span.end, span_end); } #[rstest] #[case::list_flag_value1("foo --foo=", None, vec!["[f, bar]", "[f, baz]", "[foo]"])] #[case::list_flag_value2("foo --foo=[foo", None, vec!["[foo]"])] #[case::list_flag_value3("foo --foo [f, b", None, vec!["[f, bar]", "[f, baz]"])] #[case::positional1("foo [f, b", None, vec!["[f, bar]", "[f, baz]"])] #[case::positional2("foo [foo, b", Some("foo [foo".len()), vec!["[foo]"])] #[case::positional3("foo --foo [] [foo", None, vec!["[foo]"])] fn custom_completion_for_list_typed_argument( #[case] input: &str, #[case] pos: Option<usize>, #[case] expected: Vec<&str>, ) { let (_, _, mut engine, mut stack) = new_engine(); let command = /* lang=nu */ r#" def comp_foo [input pos] { ["[foo]", "[f, bar]", "[f, baz]"] } def foo [--foo: list<string>@comp_foo bar: list<string>@comp_foo] { } "#; assert!(support::merge_input(command.as_bytes(), &mut engine, &mut stack).is_ok()); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); // `pos` defaults to `input.len()` if set to None let span_end = pos.unwrap_or(input.len()); let suggestions = completer.complete(input, span_end); match_suggestions(&expected, &suggestions); } #[test] fn list_completions_defined_inline() { let (_, _, engine, stack) = new_engine(); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); let completion_str = /* lang=nu */ r#" export def say [ animal: string@[cat dog] ] { } say "#; let suggestions = completer.complete(completion_str, completion_str.len()); // including only subcommand completions let expected: Vec<_> = vec!["cat", "dog"]; match_suggestions(&expected, &suggestions); } #[test] fn list_completions_extern() { let (_, _, engine, stack) = new_engine(); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); let completion_str = /* lang=nu */ r#" export extern say [ animal: string@[cat dog] ] say "#; let suggestions = completer.complete(completion_str, completion_str.len()); // including only subcommand completions let expected: Vec<_> = vec!["cat", "dog"]; match_suggestions(&expected, &suggestions); } #[test] fn list_completions_from_constant_and_allows_record() { let (_, _, engine, stack) = new_engine(); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); let completion_str = /* lang=nu */ r#" const animals = [ cat {value: "dog"} ] export def say [ animal: string@$animals ] { } say "#; let suggestions = completer.complete(completion_str, completion_str.len()); // including only subcommand completions let expected: Vec<_> = vec!["cat", "dog"]; match_suggestions(&expected, &suggestions); } #[test] fn list_completions_invalid_type() { let (_, _, engine, _) = new_engine(); let record = /* lang=nu */ r#" const animals = {cat: "meow", dog: "woof!"} export def say [ animal: string@$animals ] { } "#; let mut working_set = StateWorkingSet::new(&engine); let _ = parse(&mut working_set, None, record.as_bytes(), false); assert!( working_set .parse_errors .iter() .any(|err| matches!(err, ParseError::OperatorUnsupportedType { .. })) ); } /// External command only if starts with `^` #[test] fn external_commands() { let engine = new_external_engine(); let mut completer = NuCompleter::new( Arc::new(engine), Arc::new(nu_protocol::engine::Stack::new()), ); let completion_str = "ls; ^sleep"; let suggestions = completer.complete(completion_str, completion_str.len()); #[cfg(windows)] let expected: Vec<_> = vec!["sleep.exe"]; #[cfg(not(windows))] let expected: Vec<_> = vec!["sleep"]; match_suggestions(&expected, &suggestions); let completion_str = "sleep"; let suggestions = completer.complete(completion_str, completion_str.len()); #[cfg(windows)] let expected: Vec<_> = vec!["sleep", "sleep.exe"]; #[cfg(not(windows))] let expected: Vec<_> = vec!["sleep", "^sleep"]; match_suggestions(&expected, &suggestions); } /// Disable external commands except for those start with `^` #[test] fn external_commands_disabled() { let mut engine = new_external_engine(); let mut config = Config::default(); config.completions.external.enable = false; engine.set_config(config); let stack = nu_protocol::engine::Stack::new(); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); let completion_str = "ls; ^sleep"; let suggestions = completer.complete(completion_str, completion_str.len()); #[cfg(windows)] let expected: Vec<_> = vec!["sleep.exe"]; #[cfg(not(windows))] let expected: Vec<_> = vec!["sleep"]; match_suggestions(&expected, &suggestions); let completion_str = "sleep"; let suggestions = completer.complete(completion_str, completion_str.len()); let expected: Vec<_> = vec!["sleep"]; match_suggestions(&expected, &suggestions); } /// Which completes both internals and externals #[test] fn which_command_completions() { let engine = new_external_engine(); let mut completer = NuCompleter::new( Arc::new(engine), Arc::new(nu_protocol::engine::Stack::new()), ); // flags let completion_str = "which --all"; let suggestions = completer.complete(completion_str, completion_str.len()); let expected: Vec<_> = vec!["--all"]; match_suggestions(&expected, &suggestions); // commands let completion_str = "which sleep"; let suggestions = completer.complete(completion_str, completion_str.len()); #[cfg(windows)] let expected: Vec<_> = vec!["sleep", "sleep.exe"]; #[cfg(not(windows))] let expected: Vec<_> = vec!["sleep", "^sleep"]; match_suggestions(&expected, &suggestions); } /// Suppress completions for invalid values #[test] fn customcompletions_invalid() { let (_, _, mut engine, mut stack) = new_engine(); let command = r#" def comp [] { 123 } def my-command [arg: string@comp] {}"#; assert!(support::merge_input(command.as_bytes(), &mut engine, &mut stack).is_ok()); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); let completion_str = "my-command foo"; let suggestions = completer.complete(completion_str, completion_str.len()); assert!(suggestions.is_empty()); } #[test] fn dont_use_dotnu_completions() { // Create a new engine let (_, _, engine, stack) = new_dotnu_engine(); // Instantiate a new completer let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); // Test nested nu script let completion_str = "go work use `./dir_module/"; let suggestions = completer.complete(completion_str, completion_str.len()); // including a plaintext file let expected: Vec<_> = vec![ "./dir_module/mod.nu", "./dir_module/plain.txt", "`./dir_module/sub module/`", ]; match_suggestions(&expected, &suggestions); } #[test] fn dotnu_completions() { // Create a new engine let (_, _, engine, stack) = new_dotnu_engine(); // Instantiate a new completer let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); // Flags should still be working let completion_str = "overlay use --"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["--help", "--prefix", "--reload"], &suggestions); // Test nested nu script #[cfg(windows)] let completion_str = "use `.\\dir_module\\"; #[cfg(not(windows))] let completion_str = "use `./dir_module/"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions( &vec![ #[cfg(windows)] ".\\dir_module\\mod.nu", #[cfg(windows)] "`.\\dir_module\\sub module\\`", #[cfg(not(windows))] "./dir_module/mod.nu", #[cfg(not(windows))] "`./dir_module/sub module/`", ], &suggestions, ); // Test nested nu script, with ending '`' #[cfg(windows)] let completion_str = "use `.\\dir_module\\sub module\\`"; #[cfg(not(windows))] let completion_str = "use `./dir_module/sub module/`"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions( &vec![ #[cfg(windows)] "`.\\dir_module\\sub module\\sub.nu`", #[cfg(not(windows))] "`./dir_module/sub module/sub.nu`", ], &suggestions, ); let mut expected = vec![ "asdf.nu", "bar.nu", "bat.nu", "baz.nu", "foo.nu", "spam.nu", "xyzzy.nu", #[cfg(windows)] "dir_module\\", #[cfg(not(windows))] "dir_module/", #[cfg(windows)] "lib-dir1\\", #[cfg(not(windows))] "lib-dir1/", #[cfg(windows)] "lib-dir2\\", #[cfg(not(windows))] "lib-dir2/", #[cfg(windows)] "lib-dir3\\", #[cfg(not(windows))] "lib-dir3/", ]; // Test source completion let completion_str = "source-env "; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&expected, &suggestions); // Test use completion expected.insert(0, "std-rfc"); expected.insert(0, "std"); let completion_str = "use "; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&expected, &suggestions); // Test overlay use completion let completion_str = "overlay use "; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&expected, &suggestions); // Test special paths #[cfg(windows)] { let completion_str = "use \\"; let dir_content = read_dir("\\").unwrap(); let suggestions = completer.complete(completion_str, completion_str.len()); match_dir_content_for_dotnu(dir_content, &suggestions); } let completion_str = "use /"; let suggestions = completer.complete(completion_str, completion_str.len()); let dir_content = read_dir("/").unwrap(); match_dir_content_for_dotnu(dir_content, &suggestions); let completion_str = "use ~"; let dir_content = read_dir(expand_tilde("~")).unwrap(); let suggestions = completer.complete(completion_str, completion_str.len()); match_dir_content_for_dotnu(dir_content, &suggestions); } // https://github.com/nushell/nushell/issues/17021 #[test] fn module_name_completions() { let (_, _, mut engine, mut stack) = new_dotnu_engine(); let code = r#"module "🤔🐘" { # module comment # another comment }"#; assert!(support::merge_input(code.as_bytes(), &mut engine, &mut stack).is_ok()); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); let completion_str = "use 🤔"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["🤔🐘"], &suggestions); assert_eq!( suggestions[0].description, Some("# module comment\n# another comment".into()) ); } #[test] fn dotnu_stdlib_completions() { let (_, _, mut engine, stack) = new_dotnu_engine(); assert!(load_standard_library(&mut engine).is_ok()); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); // `export use` should be recognized as command `export use` let completion_str = "export use std/ass"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["std/assert"], &suggestions); let completion_str = "use `std-rfc/cli"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["std-rfc/clip"], &suggestions); let completion_str = "use \"std"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["std", "std-rfc"], &suggestions); let completion_str = "overlay use 'std-rfc/cli"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["std-rfc/clip"], &suggestions); } #[test] fn exportable_completions() { let (_, _, mut engine, mut stack) = new_dotnu_engine(); let code = r#"export module "🤔🐘" { export const foo = "🤔🐘"; }"#; assert!(support::merge_input(code.as_bytes(), &mut engine, &mut stack).is_ok()); assert!(load_standard_library(&mut engine).is_ok()); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); let completion_str = "use std null"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["null-device", "null_device"], &suggestions); let completion_str = "export use std/assert eq"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["equal"], &suggestions); let completion_str = "use std/assert \"not eq"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["'not equal'"], &suggestions); let completion_str = "use std-rfc/clip ['prefi"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["prefix"], &suggestions); let completion_str = "use std/math [E, `TAU"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["TAU"], &suggestions); let completion_str = "use 🤔🐘 'foo"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["foo"], &suggestions); } #[test] fn dotnu_completions_const_nu_lib_dirs() { let (_, _, engine, stack) = new_dotnu_engine(); let mut completer = NuCompleter::new(Arc::new(engine), Arc::new(stack)); // file in `lib-dir1/`, set by `const NU_LIB_DIRS` let completion_str = "use xyzz"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["xyzzy.nu"], &suggestions); // file in `lib-dir2/`, set by `$env.NU_LIB_DIRS` let completion_str = "use asdf"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["asdf.nu"], &suggestions); // file in `lib-dir3/`, set by both, should not replicate let completion_str = "use spam"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["spam.nu"], &suggestions); // if `./` specified by user, file in `lib-dir*` should be ignored #[cfg(windows)] { let completion_str = "use .\\asdf"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec![".\\asdf.nu"], &suggestions); } let completion_str = "use ./asdf"; let suggestions = completer.complete(completion_str, completion_str.len()); match_suggestions(&vec!["./asdf.nu"], &suggestions); } #[test] fn external_completer_trailing_space() { // https://github.com/nushell/nushell/issues/6378 let block = "{|spans| $spans}"; let input = "gh alias "; let suggestions = run_external_completion(block, input); match_suggestions(&vec!["gh", "alias", ""], &suggestions); } #[test] fn external_completer_no_trailing_space() { let block = "{|spans| $spans}"; let input = "gh alias"; let suggestions = run_external_completion(block, input); assert_eq!(2, suggestions.len()); assert_eq!("gh", suggestions.first().unwrap().value); assert_eq!("alias", suggestions.get(1).unwrap().value); } #[test] fn external_completer_pass_flags() { let block = "{|spans| $spans}"; let input = "gh api --"; let suggestions = run_external_completion(block, input); assert_eq!(3, suggestions.len()); assert_eq!("gh", suggestions.first().unwrap().value); assert_eq!("api", suggestions.get(1).unwrap().value); assert_eq!("--", suggestions.get(2).unwrap().value); } /// Fallback to file completions when external completer returns null #[test] fn external_completer_fallback() { let block = "{|spans| null}"; let input = "foo test"; let expected = [folder("test_a"), file("test_a_symlink"), folder("test_b")]; let suggestions = run_external_completion(block, input); match_suggestions_by_string(&expected, &suggestions); // issue #15790 let input = "foo `dir with space/`"; let expected = vec!["`dir with space/bar baz`", "`dir with space/foo`"]; let suggestions = run_external_completion_within_pwd( block, input,
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/tests/completions/support/mod.rs
crates/nu-cli/tests/completions/support/mod.rs
pub mod completions_helpers; pub use completions_helpers::{ file, folder, match_suggestions, match_suggestions_by_string, merge_input, new_engine, };
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cli/tests/completions/support/completions_helpers.rs
crates/nu-cli/tests/completions/support/completions_helpers.rs
use nu_engine::eval_block; use nu_parser::parse; use nu_path::{AbsolutePathBuf, PathBuf}; use nu_protocol::{ DynamicCompletionCallRef, DynamicSuggestion, PipelineData, ShellError, Signature, Span, SyntaxShape, Value, debugger::WithoutDebug, engine::{ArgType, Command, EngineState, Stack, StateWorkingSet}, }; use nu_test_support::fs; use reedline::Suggestion; use std::path::MAIN_SEPARATOR; fn create_default_context() -> EngineState { nu_command::add_shell_command_context(nu_cmd_lang::create_default_context()) } // A fake cmd for testing. #[derive(Clone)] struct FakeCmd; impl Command for FakeCmd { fn name(&self) -> &str { "fake-cmd" } fn description(&self) -> &str { "a fake cmd completion for testing" } fn signature(&self) -> Signature { Signature::build(self.name()) .optional("second", SyntaxShape::String, "optional second") .required("first", SyntaxShape::String, "required integer value") .named( "flag", SyntaxShape::Int, "example flag which support auto completion", Some('f'), ) } #[expect(deprecated, reason = "example usage")] fn get_dynamic_completion( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: DynamicCompletionCallRef, arg_type: &ArgType, _experimental: nu_protocol::engine::ExperimentalMarker, ) -> Result<Option<Vec<DynamicSuggestion>>, ShellError> { Ok(match arg_type { ArgType::Positional(index) => { // be careful: Don't include any spaces for values. if *index == 0 { Some( (0..1) .map(|s| DynamicSuggestion { value: format!("arg0:{s}"), ..Default::default() }) .collect(), ) } else if *index == 1 { Some( (0..2) .map(|s| DynamicSuggestion { value: format!("arg1:{s}"), ..Default::default() }) .collect(), ) } else { None } } ArgType::Flag(flag_name) => match flag_name.as_ref() { "flag" => Some( (0..3) .map(|s| DynamicSuggestion { value: format!("flag:{s}"), ..Default::default() }) .collect(), ), _ => None, }, }) } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &nu_protocol::engine::Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(PipelineData::Empty) } } pub fn new_engine_helper(pwd: AbsolutePathBuf) -> (AbsolutePathBuf, String, EngineState, Stack) { let pwd_str = pwd .clone() .into_os_string() .into_string() .unwrap_or_default(); // Create a new engine with default context let mut engine_state = create_default_context(); // Add $nu engine_state.generate_nu_constant(); // New stack let mut stack = Stack::new(); // Add pwd as env var stack.add_env_var( "PWD".to_string(), Value::string(pwd_str.clone(), nu_protocol::Span::new(0, pwd_str.len())), ); stack.add_env_var( "TEST".to_string(), Value::string( "NUSHELL".to_string(), nu_protocol::Span::new(0, pwd_str.len()), ), ); #[cfg(windows)] stack.add_env_var( "Path".to_string(), Value::string( "c:\\some\\path;c:\\some\\other\\path".to_string(), nu_protocol::Span::new(0, pwd_str.len()), ), ); #[cfg(not(windows))] stack.add_env_var( "PATH".to_string(), Value::string( "/some/path:/some/other/path".to_string(), nu_protocol::Span::new(0, pwd_str.len()), ), ); // Merge environment into the permanent state let merge_result = engine_state.merge_env(&mut stack); assert!(merge_result.is_ok()); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(FakeCmd)); let delta = working_set.render(); let merge_result = engine_state.merge_delta(delta); assert!(merge_result.is_ok()); (pwd, pwd_str, engine_state, stack) } /// creates a new engine with the current path in the completions fixtures folder pub fn new_engine() -> (AbsolutePathBuf, String, EngineState, Stack) { new_engine_helper(fs::fixtures().join("completions")) } /// Adds pseudo PATH env for external completion tests pub fn new_external_engine() -> EngineState { let mut engine = create_default_context(); let dir = fs::fixtures().join("external_completions").join("path"); let dir_str = dir.to_string_lossy().to_string(); let span = nu_protocol::Span::new(0, dir_str.len()); engine.add_env_var( "PATH".to_string(), Value::list(vec![Value::string(dir_str, span)], span), ); engine } /// creates a new engine with the current path in the dotnu_completions fixtures folder pub fn new_dotnu_engine() -> (AbsolutePathBuf, String, EngineState, Stack) { // Target folder inside assets let dir = fs::fixtures().join("dotnu_completions"); let (dir, dir_str, mut engine_state, mut stack) = new_engine_helper(dir); let dir_span = nu_protocol::Span::new(0, dir_str.len()); // const $NU_LIB_DIRS let mut working_set = StateWorkingSet::new(&engine_state); let var_id = working_set.add_variable( b"$NU_LIB_DIRS".into(), Span::unknown(), nu_protocol::Type::List(Box::new(nu_protocol::Type::String)), false, ); working_set.set_variable_const_val( var_id, Value::test_list(vec![ Value::string(file(dir.join("lib-dir1")), dir_span), Value::string(file(dir.join("lib-dir3")), dir_span), ]), ); let _ = engine_state.merge_delta(working_set.render()); stack.add_env_var( "NU_LIB_DIRS".into(), Value::test_list(vec![ Value::string(file(dir.join("lib-dir2")), dir_span), Value::string(file(dir.join("lib-dir3")), dir_span), ]), ); // Merge environment into the permanent state let merge_result = engine_state.merge_env(&mut stack); assert!(merge_result.is_ok()); (dir, dir_str, engine_state, stack) } pub fn new_quote_engine() -> (AbsolutePathBuf, String, EngineState, Stack) { new_engine_helper(fs::fixtures().join("quoted_completions")) } pub fn new_partial_engine() -> (AbsolutePathBuf, String, EngineState, Stack) { new_engine_helper(fs::fixtures().join("partial_completions")) } /// match a list of suggestions with the expected values pub fn match_suggestions(expected: &Vec<&str>, suggestions: &Vec<Suggestion>) { let expected_len = expected.len(); let suggestions_len = suggestions.len(); if expected_len != suggestions_len { panic!( "\nexpected {expected_len} suggestions but got {suggestions_len}: \n\ Suggestions: {suggestions:#?} \n\ Expected: {expected:#?}\n" ) } let suggestions_str = suggestions .iter() .map(|it| it.value.as_str()) .collect::<Vec<_>>(); assert_eq!(expected, &suggestions_str); } /// match a list of suggestions with the expected values pub fn match_suggestions_by_string(expected: &[String], suggestions: &Vec<Suggestion>) { let expected = expected.iter().map(|it| it.as_str()).collect::<Vec<_>>(); match_suggestions(&expected, suggestions); } /// append the separator to the converted path pub fn folder(path: impl Into<PathBuf>) -> String { let mut converted_path = file(path); converted_path.push(MAIN_SEPARATOR); converted_path } /// convert a given path to string pub fn file(path: impl Into<PathBuf>) -> String { path.into().into_os_string().into_string().unwrap() } /// merge_input executes the given input into the engine /// and merges the state pub fn merge_input( input: &[u8], engine_state: &mut EngineState, stack: &mut Stack, ) -> Result<(), ShellError> { let (block, delta) = { let mut working_set = StateWorkingSet::new(engine_state); let block = parse(&mut working_set, None, input, false); assert!(working_set.parse_errors.is_empty()); (block, working_set.render()) }; engine_state.merge_delta(delta)?; assert!( eval_block::<WithoutDebug>( engine_state, stack, &block, PipelineData::value(Value::nothing(Span::unknown()), None), ) .is_ok() ); // Merge environment into the permanent state engine_state.merge_env(stack) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_stress_internals/src/main.rs
crates/nu_plugin_stress_internals/src/main.rs
use std::{ error::Error, ffi::OsStr, io::{BufRead, BufReader, Write}, }; use interprocess::local_socket::{ self, GenericFilePath, GenericNamespaced, ToFsName, ToNsName, traits::Stream, }; use serde::Deserialize; use serde_json::{Value, json}; #[derive(Debug)] struct Options { refuse_local_socket: bool, advertise_local_socket: bool, exit_before_hello: bool, exit_early: bool, wrong_version: bool, local_socket_path: Option<String>, } pub fn main() -> Result<(), Box<dyn Error>> { let args: Vec<String> = std::env::args().collect(); eprintln!("stress_internals: args: {args:?}"); // Parse options from environment variables fn has_env(var: &str) -> bool { std::env::var(var).is_ok() } let mut opts = Options { refuse_local_socket: has_env("STRESS_REFUSE_LOCAL_SOCKET"), advertise_local_socket: has_env("STRESS_ADVERTISE_LOCAL_SOCKET"), exit_before_hello: has_env("STRESS_EXIT_BEFORE_HELLO"), exit_early: has_env("STRESS_EXIT_EARLY"), wrong_version: has_env("STRESS_WRONG_VERSION"), local_socket_path: None, }; let (mut input, mut output): (Box<dyn BufRead>, Box<dyn Write>) = match args.get(1).map(|s| s.as_str()) { Some("--stdio") => ( Box::new(std::io::stdin().lock()), Box::new(std::io::stdout()), ), Some("--local-socket") => { opts.local_socket_path = Some(args[2].clone()); if opts.refuse_local_socket { std::process::exit(1) } else { let name = if cfg!(windows) { OsStr::new(&args[2]).to_ns_name::<GenericNamespaced>()? } else { OsStr::new(&args[2]).to_fs_name::<GenericFilePath>()? }; let in_socket = local_socket::Stream::connect(name.clone())?; let out_socket = local_socket::Stream::connect(name)?; (Box::new(BufReader::new(in_socket)), Box::new(out_socket)) } } None => { eprintln!("Run nu_plugin_stress_internals as a plugin from inside nushell"); std::process::exit(1) } _ => { eprintln!("Received args I don't understand: {args:?}"); std::process::exit(1) } }; // Send encoding format output.write_all(b"\x04json")?; output.flush()?; // Test exiting without `Hello` if opts.exit_before_hello { std::process::exit(1) } // Read `Hello` message let mut de = serde_json::Deserializer::from_reader(&mut input); let hello: Value = Value::deserialize(&mut de)?; assert!(hello.get("Hello").is_some()); // Send `Hello` message write( &mut output, &json!({ "Hello": { "protocol": "nu-plugin", "version": if opts.wrong_version { "0.0.0" } else { env!("CARGO_PKG_VERSION") }, "features": if opts.advertise_local_socket { vec![json!({"name": "LocalSocket"})] } else { vec![] }, } }), )?; if opts.exit_early { // Exit without handling anything other than Hello std::process::exit(0); } // Parse incoming messages loop { match Value::deserialize(&mut de) { Ok(message) => handle_message(&mut output, &opts, &message)?, Err(err) => { if err.is_eof() { break; } else if err.is_io() { std::process::exit(1); } else { return Err(err.into()); } } } } Ok(()) } fn handle_message( output: &mut impl Write, opts: &Options, message: &Value, ) -> Result<(), Box<dyn Error>> { if let Some(plugin_call) = message.get("Call") { let (id, plugin_call) = (&plugin_call[0], &plugin_call[1]); if plugin_call.as_str() == Some("Metadata") { write( output, &json!({ "CallResponse": [ id, { "Metadata": { "version": env!("CARGO_PKG_VERSION"), } } ] }), ) } else if plugin_call.as_str() == Some("Signature") { write( output, &json!({ "CallResponse": [ id, { "Signature": signatures(), } ] }), ) } else if let Some(call_info) = plugin_call.get("Run") { if call_info["name"].as_str() == Some("stress_internals") { // Just return debug of opts let return_value = json!({ "String": { "val": format!("{opts:?}"), "span": &call_info["call"]["head"], } }); write( output, &json!({ "CallResponse": [ id, { "PipelineData": { "Value": [return_value, null] } } ] }), ) } else { Err(format!("unknown call name: {call_info}").into()) } } else { Err(format!("unknown plugin call: {plugin_call}").into()) } } else if message.as_str() == Some("Goodbye") { std::process::exit(0); } else { Err(format!("unknown message: {message}").into()) } } fn signatures() -> Vec<Value> { vec![json!({ "sig": { "name": "stress_internals", "description": "Used to test behavior of plugin protocol", "extra_description": "", "search_terms": [], "required_positional": [], "optional_positional": [], "rest_positional": null, "named": [], "input_output_types": [], "allow_variants_without_examples": false, "is_filter": false, "creates_scope": false, "allows_unknown_args": false, "category": "Experimental", }, "examples": [], })] } fn write(output: &mut impl Write, value: &Value) -> Result<(), Box<dyn Error>> { serde_json::to_writer(&mut *output, value)?; output.write_all(b"\n")?; output.flush()?; Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/documentation.rs
crates/nu-engine/src/documentation.rs
use crate::eval_call; use fancy_regex::{Captures, Regex}; use nu_protocol::{ Category, Config, IntoPipelineData, PipelineData, PositionalArg, Signature, Span, SpanId, Spanned, SyntaxShape, Type, Value, ast::{Argument, Call, Expr, Expression, RecordItem}, debugger::WithoutDebug, engine::CommandType, engine::{Command, EngineState, Stack, UNKNOWN_SPAN_ID}, record, }; use nu_utils::terminal_size; use std::{ borrow::Cow, collections::HashMap, fmt::Write, sync::{Arc, LazyLock}, }; /// ANSI style reset const RESET: &str = "\x1b[0m"; /// ANSI set default color (as set in the terminal) const DEFAULT_COLOR: &str = "\x1b[39m"; /// ANSI set default dimmed const DEFAULT_DIMMED: &str = "\x1b[2;39m"; /// ANSI set default italic const DEFAULT_ITALIC: &str = "\x1b[3;39m"; pub fn get_full_help( command: &dyn Command, engine_state: &EngineState, stack: &mut Stack, ) -> String { // Precautionary step to capture any command output generated during this operation. We // internally call several commands (`table`, `ansi`, `nu-highlight`) and get their // `PipelineData` using this `Stack`, any other output should not be redirected like the main // execution. let stack = &mut stack.start_collect_value(); let nu_config = stack.get_config(engine_state); let sig = engine_state .get_signature(command) .update_from_command(command); // Create ansi colors let mut help_style = HelpStyle::default(); help_style.update_from_config(engine_state, &nu_config); let mut long_desc = String::new(); let desc = &sig.description; if !desc.is_empty() { long_desc.push_str(&highlight_code(desc, engine_state, stack)); long_desc.push_str("\n\n"); } let extra_desc = &sig.extra_description; if !extra_desc.is_empty() { long_desc.push_str(&highlight_code(extra_desc, engine_state, stack)); long_desc.push_str("\n\n"); } match command.command_type() { CommandType::Alias => get_alias_documentation( &mut long_desc, command, &sig, &help_style, engine_state, stack, ), _ => get_command_documentation( &mut long_desc, command, &sig, &nu_config, &help_style, engine_state, stack, ), }; if !nu_config.use_ansi_coloring.get(engine_state) { nu_utils::strip_ansi_string_likely(long_desc) } else { long_desc } } /// Syntax highlight code using the `nu-highlight` command if available fn try_nu_highlight( code_string: &str, reject_garbage: bool, engine_state: &EngineState, stack: &mut Stack, ) -> Option<String> { let highlighter = engine_state.find_decl(b"nu-highlight", &[])?; let decl = engine_state.get_decl(highlighter); let mut call = Call::new(Span::unknown()); if reject_garbage { call.add_named(( Spanned { item: "reject-garbage".into(), span: Span::unknown(), }, None, None, )); } decl.run( engine_state, stack, &(&call).into(), Value::string(code_string, Span::unknown()).into_pipeline_data(), ) .and_then(|pipe| pipe.into_value(Span::unknown())) .and_then(|val| val.coerce_into_string()) .ok() } /// Syntax highlight code using the `nu-highlight` command if available, falling back to the given string fn nu_highlight_string(code_string: &str, engine_state: &EngineState, stack: &mut Stack) -> String { try_nu_highlight(code_string, false, engine_state, stack) .unwrap_or_else(|| code_string.to_string()) } /// Apply code highlighting to code in a capture group fn highlight_capture_group( captures: &Captures, engine_state: &EngineState, stack: &mut Stack, ) -> String { let Some(content) = captures.get(1) else { // this shouldn't happen return String::new(); }; // Save current color config let config_old = stack.get_config(engine_state); let mut config = (*config_old).clone(); // Style externals and external arguments with fallback style, // so nu-highlight styles code which is technically valid syntax, // but not an internal command is highlighted with the fallback style let code_style = Value::record( record! { "attr" => Value::string("di", Span::unknown()), }, Span::unknown(), ); let color_config = &mut config.color_config; color_config.insert("shape_external".into(), code_style.clone()); color_config.insert("shape_external_resolved".into(), code_style.clone()); color_config.insert("shape_externalarg".into(), code_style); // Apply config with external argument style stack.config = Some(Arc::new(config)); // Highlight and reject invalid syntax let highlighted = try_nu_highlight(content.into(), true, engine_state, stack) // // Make highlighted string italic .map(|text| { let resets = text.match_indices(RESET).count(); // replace resets with reset + italic, so the whole string is italicized, excluding the final reset let text = text.replacen(RESET, &format!("{RESET}{DEFAULT_ITALIC}"), resets - 1); // start italicized format!("{DEFAULT_ITALIC}{text}") }); // Restore original config stack.config = Some(config_old); // Use fallback style if highlight failed/syntax was invalid highlighted.unwrap_or_else(|| highlight_fallback(content.into())) } /// Apply fallback code style fn highlight_fallback(text: &str) -> String { format!("{DEFAULT_DIMMED}{DEFAULT_ITALIC}{text}{RESET}") } /// Highlight code within backticks /// /// Will attempt to use nu-highlight, falling back to dimmed and italic on invalid syntax fn highlight_code<'a>( text: &'a str, engine_state: &EngineState, stack: &mut Stack, ) -> Cow<'a, str> { let config = stack.get_config(engine_state); if !config.use_ansi_coloring.get(engine_state) { return Cow::Borrowed(text); } // See [`tests::test_code_formatting`] for examples static PATTERN: &str = r"(?x) # verbose mode (?<![\p{Letter}\d]) # negative look-behind for alphanumeric: ensure backticks are not directly preceded by letter/number. ` ([^`\n]+?) # capture characters inside backticks, excluding backticks and newlines. ungreedy. ` (?![\p{Letter}\d]) # negative look-ahead for alphanumeric: ensure backticks are not directly followed by letter/number. "; static RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(PATTERN).expect("valid regex")); let do_try_highlight = |captures: &Captures| highlight_capture_group(captures, engine_state, stack); RE.replace_all(text, do_try_highlight) } fn get_alias_documentation( long_desc: &mut String, command: &dyn Command, sig: &Signature, help_style: &HelpStyle, engine_state: &EngineState, stack: &mut Stack, ) { let help_section_name = &help_style.section_name; let help_subcolor_one = &help_style.subcolor_one; let alias_name = &sig.name; long_desc.push_str(&format!( "{help_section_name}Alias{RESET}: {help_subcolor_one}{alias_name}{RESET}" )); long_desc.push_str("\n\n"); let Some(alias) = command.as_alias() else { // this is already checked in `help alias`, but just omit the expansion if this is somehow not actually an alias return; }; let alias_expansion = String::from_utf8_lossy(engine_state.get_span_contents(alias.wrapped_call.span)); long_desc.push_str(&format!( "{help_section_name}Expansion{RESET}:\n {}", nu_highlight_string(&alias_expansion, engine_state, stack) )); } fn get_command_documentation( long_desc: &mut String, command: &dyn Command, sig: &Signature, nu_config: &Config, help_style: &HelpStyle, engine_state: &EngineState, stack: &mut Stack, ) { let help_section_name = &help_style.section_name; let help_subcolor_one = &help_style.subcolor_one; let cmd_name = &sig.name; if !sig.search_terms.is_empty() { let _ = write!( long_desc, "{help_section_name}Search terms{RESET}: {help_subcolor_one}{}{RESET}\n\n", sig.search_terms.join(", "), ); } let _ = write!( long_desc, "{help_section_name}Usage{RESET}:\n > {}\n", sig.call_signature() ); // TODO: improve the subcommand name resolution // issues: // - Aliases are included // - https://github.com/nushell/nushell/issues/11657 // - Subcommands are included violating module scoping // - https://github.com/nushell/nushell/issues/11447 // - https://github.com/nushell/nushell/issues/11625 let mut subcommands = vec![]; let signatures = engine_state.get_signatures_and_declids(true); for (sig, decl_id) in signatures { let command_type = engine_state.get_decl(decl_id).command_type(); // Don't display removed/deprecated commands in the Subcommands list if sig.name.starts_with(&format!("{cmd_name} ")) && !matches!(sig.category, Category::Removed) { // If it's a plugin, alias, or custom command, display that information in the help if command_type == CommandType::Plugin || command_type == CommandType::Alias || command_type == CommandType::Custom { subcommands.push(format!( " {help_subcolor_one}{} {help_section_name}({}){RESET} - {}", sig.name, command_type, highlight_code(&sig.description, engine_state, stack) )); } else { subcommands.push(format!( " {help_subcolor_one}{}{RESET} - {}", sig.name, highlight_code(&sig.description, engine_state, stack) )); } } } if !subcommands.is_empty() { let _ = write!(long_desc, "\n{help_section_name}Subcommands{RESET}:\n"); subcommands.sort(); long_desc.push_str(&subcommands.join("\n")); long_desc.push('\n'); } if !sig.named.is_empty() { long_desc.push_str(&get_flags_section(sig, help_style, |v| match v { FormatterValue::DefaultValue(value) => nu_highlight_string( &value.to_parsable_string(", ", nu_config), engine_state, stack, ), FormatterValue::CodeString(text) => { highlight_code(text, engine_state, stack).to_string() } })) } if !sig.required_positional.is_empty() || !sig.optional_positional.is_empty() || sig.rest_positional.is_some() { let _ = write!(long_desc, "\n{help_section_name}Parameters{RESET}:\n"); for positional in &sig.required_positional { write_positional( long_desc, positional, PositionalKind::Required, help_style, nu_config, engine_state, stack, ); } for positional in &sig.optional_positional { write_positional( long_desc, positional, PositionalKind::Optional, help_style, nu_config, engine_state, stack, ); } if let Some(rest_positional) = &sig.rest_positional { write_positional( long_desc, rest_positional, PositionalKind::Rest, help_style, nu_config, engine_state, stack, ); } } fn get_term_width() -> usize { if let Ok((w, _h)) = terminal_size() { w as usize } else { 80 } } if !command.is_keyword() && !sig.input_output_types.is_empty() && let Some(decl_id) = engine_state.find_decl(b"table", &[]) { // FIXME: we may want to make this the span of the help command in the future let span = Span::unknown(); let mut vals = vec![]; for (input, output) in &sig.input_output_types { vals.push(Value::record( record! { "input" => Value::string(input.to_string(), span), "output" => Value::string(output.to_string(), span), }, span, )); } let caller_stack = &mut Stack::new().collect_value(); if let Ok(result) = eval_call::<WithoutDebug>( engine_state, caller_stack, &Call { decl_id, head: span, arguments: vec![Argument::Named(( Spanned { item: "width".to_string(), span: Span::unknown(), }, None, Some(Expression::new_unknown( Expr::Int(get_term_width() as i64 - 2), // padding, see below Span::unknown(), Type::Int, )), ))], parser_info: HashMap::new(), }, PipelineData::value(Value::list(vals, span), None), ) && let Ok((str, ..)) = result.collect_string_strict(span) { let _ = writeln!(long_desc, "\n{help_section_name}Input/output types{RESET}:"); for line in str.lines() { let _ = writeln!(long_desc, " {line}"); } } } let examples = command.examples(); if !examples.is_empty() { let _ = write!(long_desc, "\n{help_section_name}Examples{RESET}:"); } for example in examples { long_desc.push('\n'); long_desc.push_str(" "); long_desc.push_str(&highlight_code(example.description, engine_state, stack)); if !nu_config.use_ansi_coloring.get(engine_state) { let _ = write!(long_desc, "\n > {}\n", example.example); } else { let code_string = nu_highlight_string(example.example, engine_state, stack); let _ = write!(long_desc, "\n > {code_string}\n"); }; if let Some(result) = &example.result { let mut table_call = Call::new(Span::unknown()); if example.example.ends_with("--collapse") { // collapse the result table_call.add_named(( Spanned { item: "collapse".to_string(), span: Span::unknown(), }, None, None, )) } else { // expand the result table_call.add_named(( Spanned { item: "expand".to_string(), span: Span::unknown(), }, None, None, )) } table_call.add_named(( Spanned { item: "width".to_string(), span: Span::unknown(), }, None, Some(Expression::new_unknown( Expr::Int(get_term_width() as i64 - 2), Span::unknown(), Type::Int, )), )); let table = engine_state .find_decl("table".as_bytes(), &[]) .and_then(|decl_id| { engine_state .get_decl(decl_id) .run( engine_state, stack, &(&table_call).into(), PipelineData::value(result.clone(), None), ) .ok() }); for item in table.into_iter().flatten() { let _ = writeln!( long_desc, " {}", item.to_expanded_string("", nu_config) .trim_end() .trim_start_matches(|c: char| c.is_whitespace() && c != ' ') .replace('\n', "\n ") ); } } } long_desc.push('\n'); } fn update_ansi_from_config( ansi_code: &mut String, engine_state: &EngineState, nu_config: &Config, theme_component: &str, ) { if let Some(color) = &nu_config.color_config.get(theme_component) { let caller_stack = &mut Stack::new().collect_value(); let span = Span::unknown(); let span_id = UNKNOWN_SPAN_ID; let argument_opt = get_argument_for_color_value(nu_config, color, span, span_id); // Call ansi command using argument if let Some(argument) = argument_opt && let Some(decl_id) = engine_state.find_decl(b"ansi", &[]) && let Ok(result) = eval_call::<WithoutDebug>( engine_state, caller_stack, &Call { decl_id, head: span, arguments: vec![argument], parser_info: HashMap::new(), }, PipelineData::empty(), ) && let Ok((str, ..)) = result.collect_string_strict(span) { *ansi_code = str; } } } fn get_argument_for_color_value( nu_config: &Config, color: &Value, span: Span, span_id: SpanId, ) -> Option<Argument> { match color { Value::Record { val, .. } => { let record_exp: Vec<RecordItem> = (**val) .iter() .map(|(k, v)| { RecordItem::Pair( Expression::new_existing( Expr::String(k.clone()), span, span_id, Type::String, ), Expression::new_existing( Expr::String(v.clone().to_expanded_string("", nu_config)), span, span_id, Type::String, ), ) }) .collect(); Some(Argument::Positional(Expression::new_existing( Expr::Record(record_exp), Span::unknown(), UNKNOWN_SPAN_ID, Type::Record( [ ("fg".to_string(), Type::String), ("attr".to_string(), Type::String), ] .into(), ), ))) } Value::String { val, .. } => Some(Argument::Positional(Expression::new_existing( Expr::String(val.clone()), Span::unknown(), UNKNOWN_SPAN_ID, Type::String, ))), _ => None, } } /// Contains the settings for ANSI colors in help output /// /// By default contains a fixed set of (4-bit) colors /// /// Can reflect configuration using [`HelpStyle::update_from_config`] pub struct HelpStyle { section_name: String, subcolor_one: String, subcolor_two: String, } impl Default for HelpStyle { fn default() -> Self { HelpStyle { // default: green section_name: "\x1b[32m".to_string(), // default: cyan subcolor_one: "\x1b[36m".to_string(), // default: light blue subcolor_two: "\x1b[94m".to_string(), } } } impl HelpStyle { /// Pull colors from the [`Config`] /// /// Uses some arbitrary `shape_*` settings, assuming they are well visible in the terminal theme. /// /// Implementation detail: currently executes `ansi` command internally thus requiring the /// [`EngineState`] for execution. /// See <https://github.com/nushell/nushell/pull/10623> for details pub fn update_from_config(&mut self, engine_state: &EngineState, nu_config: &Config) { update_ansi_from_config( &mut self.section_name, engine_state, nu_config, "shape_string", ); update_ansi_from_config( &mut self.subcolor_one, engine_state, nu_config, "shape_external", ); update_ansi_from_config( &mut self.subcolor_two, engine_state, nu_config, "shape_block", ); } } #[derive(PartialEq)] enum PositionalKind { Required, Optional, Rest, } fn write_positional( long_desc: &mut String, positional: &PositionalArg, arg_kind: PositionalKind, help_style: &HelpStyle, nu_config: &Config, engine_state: &EngineState, stack: &mut Stack, ) { let help_subcolor_one = &help_style.subcolor_one; let help_subcolor_two = &help_style.subcolor_two; // Indentation long_desc.push_str(" "); if arg_kind == PositionalKind::Rest { long_desc.push_str("..."); } match &positional.shape { SyntaxShape::Keyword(kw, shape) => { let _ = write!( long_desc, "{help_subcolor_one}\"{}\" + {RESET}<{help_subcolor_two}{}{RESET}>", String::from_utf8_lossy(kw), shape, ); } _ => { let _ = write!( long_desc, "{help_subcolor_one}{}{RESET} <{help_subcolor_two}{}{RESET}>", positional.name, &positional.shape, ); } }; if !positional.desc.is_empty() || arg_kind == PositionalKind::Optional { let _ = write!( long_desc, ": {}", highlight_code(&positional.desc, engine_state, stack) ); } if arg_kind == PositionalKind::Optional { if let Some(value) = &positional.default_value { let _ = write!( long_desc, " (optional, default: {})", nu_highlight_string( &value.to_parsable_string(", ", nu_config), engine_state, stack ) ); } else { long_desc.push_str(" (optional)"); }; } long_desc.push('\n'); } /// Helper for `get_flags_section` /// /// The formatter with access to nu-highlight must be passed to `get_flags_section`, but it's not possible /// to pass separate closures since they both need `&mut Stack`, so this enum lets us differentiate between /// default values to be formatted and strings which might contain code in backticks to be highlighted. pub enum FormatterValue<'a> { /// Default value to be styled DefaultValue(&'a Value), /// String which might have code in backticks to be highlighted CodeString(&'a str), } fn write_flag_to_long_desc<F>( flag: &nu_protocol::Flag, long_desc: &mut String, help_subcolor_one: &str, help_subcolor_two: &str, formatter: &mut F, ) where F: FnMut(FormatterValue) -> String, { // Indentation long_desc.push_str(" "); // Short flag shown before long flag if let Some(short) = flag.short { let _ = write!(long_desc, "{help_subcolor_one}-{short}{RESET}"); if !flag.long.is_empty() { let _ = write!(long_desc, "{DEFAULT_COLOR},{RESET} "); } } if !flag.long.is_empty() { let _ = write!(long_desc, "{help_subcolor_one}--{}{RESET}", flag.long); } if flag.required { long_desc.push_str(" (required parameter)") } // Type/Syntax shape info if let Some(arg) = &flag.arg { let _ = write!(long_desc, " <{help_subcolor_two}{arg}{RESET}>"); } if !flag.desc.is_empty() { let _ = write!( long_desc, ": {}", &formatter(FormatterValue::CodeString(&flag.desc)) ); } if let Some(value) = &flag.default_value { let _ = write!( long_desc, " (default: {})", &formatter(FormatterValue::DefaultValue(value)) ); } long_desc.push('\n'); } pub fn get_flags_section<F>( signature: &Signature, help_style: &HelpStyle, mut formatter: F, // format default Value or text with code (because some calls cant access config or nu-highlight) ) -> String where F: FnMut(FormatterValue) -> String, { let help_section_name = &help_style.section_name; let help_subcolor_one = &help_style.subcolor_one; let help_subcolor_two = &help_style.subcolor_two; let mut long_desc = String::new(); let _ = write!(long_desc, "\n{help_section_name}Flags{RESET}:\n"); let help = signature.named.iter().find(|flag| flag.long == "help"); let required = signature.named.iter().filter(|flag| flag.required); let optional = signature .named .iter() .filter(|flag| !flag.required && flag.long != "help"); let flags = required.chain(help).chain(optional); for flag in flags { write_flag_to_long_desc( flag, &mut long_desc, help_subcolor_one, help_subcolor_two, &mut formatter, ); } long_desc } #[cfg(test)] mod tests { use nu_protocol::UseAnsiColoring; use super::*; #[test] fn test_code_formatting() { let mut engine_state = EngineState::new(); let mut stack = Stack::new(); // force coloring on for test let mut config = (*engine_state.config).clone(); config.use_ansi_coloring = UseAnsiColoring::True; engine_state.config = Arc::new(config); // using Cow::Owned here to mean a match, since the content changed, // and borrowed to mean not a match, since the content didn't change // match: typical example let haystack = "Run the `foo` command"; assert!(matches!( highlight_code(haystack, &engine_state, &mut stack), Cow::Owned(_) )); // no match: backticks preceded by alphanum let haystack = "foo`bar`"; assert!(matches!( highlight_code(haystack, &engine_state, &mut stack), Cow::Borrowed(_) )); // match: command at beginning of string is ok let haystack = "`my-command` is cool"; assert!(matches!( highlight_code(haystack, &engine_state, &mut stack), Cow::Owned(_) )); // match: preceded and followed by newline is ok let haystack = r" `command` "; assert!(matches!( highlight_code(haystack, &engine_state, &mut stack), Cow::Owned(_) )); // no match: newline between backticks let haystack = "// hello `beautiful \n world`"; assert!(matches!( highlight_code(haystack, &engine_state, &mut stack), Cow::Borrowed(_) )); // match: backticks followed by period, not letter/number let haystack = "try running `my cool command`."; assert!(matches!( highlight_code(haystack, &engine_state, &mut stack), Cow::Owned(_) )); // match: backticks enclosed by parenthesis, not letter/number let haystack = "a command (`my cool command`)."; assert!(matches!( highlight_code(haystack, &engine_state, &mut stack), Cow::Owned(_) )); // no match: only characters inside backticks are backticks // (the regex sees two backtick pairs with a single backtick inside, which doesn't qualify) let haystack = "```\ncode block\n```"; assert!(matches!( highlight_code(haystack, &engine_state, &mut stack), Cow::Borrowed(_) )); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/eval_ir.rs
crates/nu-engine/src/eval_ir.rs
use std::{borrow::Cow, fs::File, sync::Arc}; use nu_path::{expand_path, expand_path_with}; #[cfg(feature = "os")] use nu_protocol::process::check_exit_status_future; use nu_protocol::{ DeclId, ENV_VARIABLE_ID, Flag, IntoPipelineData, IntoSpanned, ListStream, OutDest, PipelineData, PipelineExecutionData, PositionalArg, Range, Record, RegId, ShellError, Signals, Signature, Span, Spanned, Type, Value, VarId, ast::{Bits, Block, Boolean, CellPath, Comparison, Math, Operator}, combined_type_string, debugger::DebugContext, engine::{ Argument, Closure, EngineState, ErrorHandler, Matcher, Redirection, Stack, StateWorkingSet, }, ir::{Call, DataSlice, Instruction, IrAstRef, IrBlock, Literal, RedirectMode}, shell_error::io::IoError, }; use nu_utils::IgnoreCaseExt; use crate::{ ENV_CONVERSIONS, convert_env_vars, eval::is_automatic_env_var, eval_block_with_early_return, }; pub fn eval_ir_block<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, block: &Block, input: PipelineData, ) -> Result<PipelineExecutionData, ShellError> { // Rust does not check recursion limits outside of const evaluation. // But nu programs run in the same process as the shell. // To prevent a stack overflow in user code from crashing the shell, // we limit the recursion depth of function calls. let maximum_call_stack_depth: u64 = engine_state.config.recursion_limit as u64; if stack.recursion_count > maximum_call_stack_depth { return Err(ShellError::RecursionLimitReached { recursion_limit: maximum_call_stack_depth, span: block.span, }); } if let Some(ir_block) = &block.ir_block { D::enter_block(engine_state, block); let args_base = stack.arguments.get_base(); let error_handler_base = stack.error_handlers.get_base(); // Allocate and initialize registers. I've found that it's not really worth trying to avoid // the heap allocation here by reusing buffers - our allocator is fast enough let mut registers = Vec::with_capacity(ir_block.register_count as usize); for _ in 0..ir_block.register_count { registers.push(PipelineExecutionData::empty()); } // Initialize file storage. let mut files = vec![None; ir_block.file_count as usize]; let result = eval_ir_block_impl::<D>( &mut EvalContext { engine_state, stack, data: &ir_block.data, block_span: &block.span, args_base, error_handler_base, redirect_out: None, redirect_err: None, matches: vec![], registers: &mut registers[..], files: &mut files[..], }, ir_block, input, ); stack.error_handlers.leave_frame(error_handler_base); stack.arguments.leave_frame(args_base); D::leave_block(engine_state, block); result } else { // FIXME blocks having IR should not be optional Err(ShellError::GenericError { error: "Can't evaluate block in IR mode".into(), msg: "block is missing compiled representation".into(), span: block.span, help: Some("the IrBlock is probably missing due to a compilation error".into()), inner: vec![], }) } } /// All of the pointers necessary for evaluation struct EvalContext<'a> { engine_state: &'a EngineState, stack: &'a mut Stack, data: &'a Arc<[u8]>, /// The span of the block block_span: &'a Option<Span>, /// Base index on the argument stack to reset to after a call args_base: usize, /// Base index on the error handler stack to reset to after a call error_handler_base: usize, /// State set by redirect-out redirect_out: Option<Redirection>, /// State set by redirect-err redirect_err: Option<Redirection>, /// Scratch space to use for `match` matches: Vec<(VarId, Value)>, /// Intermediate pipeline data storage used by instructions, indexed by RegId registers: &'a mut [PipelineExecutionData], /// Holds open files used by redirections files: &'a mut [Option<Arc<File>>], } impl<'a> EvalContext<'a> { /// Replace the contents of a register with a new value #[inline] fn put_reg(&mut self, reg_id: RegId, new_value: PipelineExecutionData) { // log::trace!("{reg_id} <- {new_value:?}"); self.registers[reg_id.get() as usize] = new_value; } /// Borrow the contents of a register. #[inline] fn borrow_reg(&self, reg_id: RegId) -> &PipelineData { &self.registers[reg_id.get() as usize] } /// Replace the contents of a register with `Empty` and then return the value that it contained #[inline] fn take_reg(&mut self, reg_id: RegId) -> PipelineExecutionData { // log::trace!("<- {reg_id}"); std::mem::replace( &mut self.registers[reg_id.get() as usize], PipelineExecutionData::empty(), ) } /// Clone data from a register. Must be collected first. fn clone_reg(&mut self, reg_id: RegId, error_span: Span) -> Result<PipelineData, ShellError> { // NOTE: here just clone the inner PipelineData // it's suitable for current usage. match &self.registers[reg_id.get() as usize].body { PipelineData::Empty => Ok(PipelineData::empty()), PipelineData::Value(val, meta) => Ok(PipelineData::value(val.clone(), meta.clone())), _ => Err(ShellError::IrEvalError { msg: "Must collect to value before using instruction that clones from a register" .into(), span: Some(error_span), }), } } /// Clone a value from a register. Must be collected first. fn clone_reg_value(&mut self, reg_id: RegId, fallback_span: Span) -> Result<Value, ShellError> { match self.clone_reg(reg_id, fallback_span)? { PipelineData::Empty => Ok(Value::nothing(fallback_span)), PipelineData::Value(val, _) => Ok(val), _ => unreachable!("clone_reg should never return stream data"), } } /// Take and implicitly collect a register to a value fn collect_reg(&mut self, reg_id: RegId, fallback_span: Span) -> Result<Value, ShellError> { // NOTE: in collect, it maybe good to pick the inner PipelineData // directly, and drop the ExitStatus queue. let data = self.take_reg(reg_id); #[cfg(feature = "os")] if nu_experimental::PIPE_FAIL.get() { check_exit_status_future(data.exit)? } let data = data.body; let span = data.span().unwrap_or(fallback_span); data.into_value(span) } /// Get a string from data or produce evaluation error if it's invalid UTF-8 fn get_str(&self, slice: DataSlice, error_span: Span) -> Result<&'a str, ShellError> { std::str::from_utf8(&self.data[slice]).map_err(|_| ShellError::IrEvalError { msg: format!("data slice does not refer to valid UTF-8: {slice:?}"), span: Some(error_span), }) } } /// Eval an IR block on the provided slice of registers. fn eval_ir_block_impl<D: DebugContext>( ctx: &mut EvalContext<'_>, ir_block: &IrBlock, input: PipelineData, ) -> Result<PipelineExecutionData, ShellError> { if !ctx.registers.is_empty() { ctx.registers[0] = PipelineExecutionData::from(input); } // Program counter, starts at zero. let mut pc = 0; let need_backtrace = ctx.engine_state.get_env_var("NU_BACKTRACE").is_some(); while pc < ir_block.instructions.len() { let instruction = &ir_block.instructions[pc]; let span = &ir_block.spans[pc]; let ast = &ir_block.ast[pc]; D::enter_instruction(ctx.engine_state, ir_block, pc, ctx.registers); let result = eval_instruction::<D>(ctx, instruction, span, ast, need_backtrace); D::leave_instruction( ctx.engine_state, ir_block, pc, ctx.registers, result.as_ref().err(), ); match result { Ok(InstructionResult::Continue) => { pc += 1; } Ok(InstructionResult::Branch(next_pc)) => { pc = next_pc; } Ok(InstructionResult::Return(reg_id)) => return Ok(ctx.take_reg(reg_id)), Err( err @ (ShellError::Return { .. } | ShellError::Continue { .. } | ShellError::Break { .. }), ) => { // These block control related errors should be passed through return Err(err); } Err(err) => { if let Some(error_handler) = ctx.stack.error_handlers.pop(ctx.error_handler_base) { // If an error handler is set, branch there prepare_error_handler(ctx, error_handler, Some(err.into_spanned(*span))); pc = error_handler.handler_index; } else if need_backtrace { let err = ShellError::into_chained(err, *span); return Err(err); } else { return Err(err); } } } } // Fell out of the loop, without encountering a Return. Err(ShellError::IrEvalError { msg: format!( "Program counter out of range (pc={pc}, len={len})", len = ir_block.instructions.len(), ), span: *ctx.block_span, }) } /// Prepare the context for an error handler fn prepare_error_handler( ctx: &mut EvalContext<'_>, error_handler: ErrorHandler, error: Option<Spanned<ShellError>>, ) { if let Some(reg_id) = error_handler.error_register { if let Some(error) = error { // Stack state has to be updated for stuff like LAST_EXIT_CODE ctx.stack.set_last_error(&error.item); // Create the error value and put it in the register ctx.put_reg( reg_id, PipelineExecutionData::from( error .item .into_full_value( &StateWorkingSet::new(ctx.engine_state), ctx.stack, error.span, ) .into_pipeline_data(), ), ); } else { // Set the register to empty ctx.put_reg(reg_id, PipelineExecutionData::empty()); } } } /// The result of performing an instruction. Describes what should happen next #[derive(Debug)] enum InstructionResult { Continue, Branch(usize), Return(RegId), } /// Perform an instruction fn eval_instruction<D: DebugContext>( ctx: &mut EvalContext<'_>, instruction: &Instruction, span: &Span, ast: &Option<IrAstRef>, need_backtrace: bool, ) -> Result<InstructionResult, ShellError> { use self::InstructionResult::*; // Check for interrupt if necessary instruction.check_interrupt(ctx.engine_state, span)?; // See the docs for `Instruction` for more information on what these instructions are supposed // to do. match instruction { Instruction::Unreachable => Err(ShellError::IrEvalError { msg: "Reached unreachable code".into(), span: Some(*span), }), Instruction::LoadLiteral { dst, lit } => load_literal(ctx, *dst, lit, *span), Instruction::LoadValue { dst, val } => { ctx.put_reg( *dst, PipelineExecutionData::from(Value::clone(val).into_pipeline_data()), ); Ok(Continue) } Instruction::Move { dst, src } => { let val = ctx.take_reg(*src); ctx.put_reg(*dst, val); Ok(Continue) } Instruction::Clone { dst, src } => { let data = ctx.clone_reg(*src, *span)?; ctx.put_reg(*dst, PipelineExecutionData::from(data)); Ok(Continue) } Instruction::Collect { src_dst } => { let data = ctx.take_reg(*src_dst); // NOTE: is it ok to just using `data.inner`? let value = collect(data.body, *span)?; ctx.put_reg(*src_dst, PipelineExecutionData::from(value)); Ok(Continue) } Instruction::Span { src_dst } => { let mut data = ctx.take_reg(*src_dst); data.body = data.body.with_span(*span); ctx.put_reg(*src_dst, data); Ok(Continue) } Instruction::Drop { src } => { ctx.take_reg(*src); Ok(Continue) } Instruction::Drain { src } => { let data = ctx.take_reg(*src); drain(ctx, data) } Instruction::DrainIfEnd { src } => { let data = ctx.take_reg(*src); let res = drain_if_end(ctx, data)?; ctx.put_reg(*src, PipelineExecutionData::from(res)); Ok(Continue) } Instruction::LoadVariable { dst, var_id } => { let value = get_var(ctx, *var_id, *span)?; ctx.put_reg( *dst, PipelineExecutionData::from(value.into_pipeline_data()), ); Ok(Continue) } Instruction::StoreVariable { var_id, src } => { let value = ctx.collect_reg(*src, *span)?; // Perform runtime type checking and conversion for variable assignment if nu_experimental::ENFORCE_RUNTIME_ANNOTATIONS.get() { let variable = ctx.engine_state.get_var(*var_id); let converted_value = check_assignment_type(value, &variable.ty)?; ctx.stack.add_var(*var_id, converted_value); } else { ctx.stack.add_var(*var_id, value); } Ok(Continue) } Instruction::DropVariable { var_id } => { ctx.stack.remove_var(*var_id); Ok(Continue) } Instruction::LoadEnv { dst, key } => { let key = ctx.get_str(*key, *span)?; if let Some(value) = get_env_var_case_insensitive(ctx, key) { let new_value = value.clone().into_pipeline_data(); ctx.put_reg(*dst, PipelineExecutionData::from(new_value)); Ok(Continue) } else { // FIXME: using the same span twice, shouldn't this really be // EnvVarNotFoundAtRuntime? There are tests that depend on CantFindColumn though... Err(ShellError::CantFindColumn { col_name: key.into(), span: Some(*span), src_span: *span, }) } } Instruction::LoadEnvOpt { dst, key } => { let key = ctx.get_str(*key, *span)?; let value = get_env_var_case_insensitive(ctx, key) .cloned() .unwrap_or(Value::nothing(*span)); ctx.put_reg( *dst, PipelineExecutionData::from(value.into_pipeline_data()), ); Ok(Continue) } Instruction::StoreEnv { key, src } => { let key = ctx.get_str(*key, *span)?; let value = ctx.collect_reg(*src, *span)?; let key = get_env_var_name_case_insensitive(ctx, key); if !is_automatic_env_var(&key) { let is_config = key == "config"; let update_conversions = key == ENV_CONVERSIONS; ctx.stack.add_env_var(key.into_owned(), value.clone()); if is_config { ctx.stack.update_config(ctx.engine_state)?; } if update_conversions { convert_env_vars(ctx.stack, ctx.engine_state, &value)?; } Ok(Continue) } else { Err(ShellError::AutomaticEnvVarSetManually { envvar_name: key.into(), span: *span, }) } } Instruction::PushPositional { src } => { let val = ctx.collect_reg(*src, *span)?.with_span(*span); ctx.stack.arguments.push(Argument::Positional { span: *span, val, ast: ast.clone().map(|ast_ref| ast_ref.0), }); Ok(Continue) } Instruction::AppendRest { src } => { let vals = ctx.collect_reg(*src, *span)?.with_span(*span); ctx.stack.arguments.push(Argument::Spread { span: *span, vals, ast: ast.clone().map(|ast_ref| ast_ref.0), }); Ok(Continue) } Instruction::PushFlag { name } => { let data = ctx.data.clone(); ctx.stack.arguments.push(Argument::Flag { data, name: *name, short: DataSlice::empty(), span: *span, }); Ok(Continue) } Instruction::PushShortFlag { short } => { let data = ctx.data.clone(); ctx.stack.arguments.push(Argument::Flag { data, name: DataSlice::empty(), short: *short, span: *span, }); Ok(Continue) } Instruction::PushNamed { name, src } => { let val = ctx.collect_reg(*src, *span)?.with_span(*span); let data = ctx.data.clone(); ctx.stack.arguments.push(Argument::Named { data, name: *name, short: DataSlice::empty(), span: *span, val, ast: ast.clone().map(|ast_ref| ast_ref.0), }); Ok(Continue) } Instruction::PushShortNamed { short, src } => { let val = ctx.collect_reg(*src, *span)?.with_span(*span); let data = ctx.data.clone(); ctx.stack.arguments.push(Argument::Named { data, name: DataSlice::empty(), short: *short, span: *span, val, ast: ast.clone().map(|ast_ref| ast_ref.0), }); Ok(Continue) } Instruction::PushParserInfo { name, info } => { let data = ctx.data.clone(); ctx.stack.arguments.push(Argument::ParserInfo { data, name: *name, info: info.clone(), }); Ok(Continue) } Instruction::RedirectOut { mode } => { ctx.redirect_out = eval_redirection(ctx, mode, *span, RedirectionStream::Out)?; Ok(Continue) } Instruction::RedirectErr { mode } => { ctx.redirect_err = eval_redirection(ctx, mode, *span, RedirectionStream::Err)?; Ok(Continue) } Instruction::CheckErrRedirected { src } => match ctx.borrow_reg(*src) { #[cfg(feature = "os")] PipelineData::ByteStream(stream, _) if matches!(stream.source(), nu_protocol::ByteStreamSource::Child(_)) => { Ok(Continue) } _ => Err(ShellError::GenericError { error: "Can't redirect stderr of internal command output".into(), msg: "piping stderr only works on external commands".into(), span: Some(*span), help: None, inner: vec![], }), }, Instruction::OpenFile { file_num, path, append, } => { let path = ctx.collect_reg(*path, *span)?; let file = open_file(ctx, &path, *append)?; ctx.files[*file_num as usize] = Some(file); Ok(Continue) } Instruction::WriteFile { file_num, src } => { let src = ctx.take_reg(*src); let file = ctx .files .get(*file_num as usize) .cloned() .flatten() .ok_or_else(|| ShellError::IrEvalError { msg: format!("Tried to write to file #{file_num}, but it is not open"), span: Some(*span), })?; let is_external = if let PipelineData::ByteStream(stream, ..) = &src.body { stream.source().is_external() } else { false }; if let Err(err) = src.body.write_to(file.as_ref()) { if is_external { ctx.stack.set_last_error(&err); } Err(err)? } else { Ok(Continue) } } Instruction::CloseFile { file_num } => { if ctx.files[*file_num as usize].take().is_some() { Ok(Continue) } else { Err(ShellError::IrEvalError { msg: format!("Tried to close file #{file_num}, but it is not open"), span: Some(*span), }) } } Instruction::Call { decl_id, src_dst } => { let input = ctx.take_reg(*src_dst); // take out exit status future first. let input_data = input.body; let mut result = eval_call::<D>(ctx, *decl_id, *span, input_data)?; if need_backtrace { match &mut result { PipelineData::ByteStream(s, ..) => s.push_caller_span(*span), PipelineData::ListStream(s, ..) => s.push_caller_span(*span), _ => (), }; } // After eval_call, attach result's exit_status_future // to `original_exit`, so all exit_status_future are tracked // in the new PipelineData, and wrap it into `PipelineExecutionData` #[cfg(feature = "os")] { let mut original_exit = input.exit; let result_exit_status_future = result.clone_exit_status_future().map(|f| (f, *span)); original_exit.push(result_exit_status_future); ctx.put_reg( *src_dst, PipelineExecutionData { body: result, exit: original_exit, }, ); } #[cfg(not(feature = "os"))] ctx.put_reg(*src_dst, PipelineExecutionData { body: result }); Ok(Continue) } Instruction::StringAppend { src_dst, val } => { let string_value = ctx.collect_reg(*src_dst, *span)?; let operand_value = ctx.collect_reg(*val, *span)?; let string_span = string_value.span(); let mut string = string_value.into_string()?; let operand = if let Value::String { val, .. } = operand_value { // Small optimization, so we don't have to copy the string *again* val } else { operand_value.to_expanded_string(", ", &ctx.stack.get_config(ctx.engine_state)) }; string.push_str(&operand); let new_string_value = Value::string(string, string_span); ctx.put_reg( *src_dst, PipelineExecutionData::from(new_string_value.into_pipeline_data()), ); Ok(Continue) } Instruction::GlobFrom { src_dst, no_expand } => { let string_value = ctx.collect_reg(*src_dst, *span)?; let glob_value = if let Value::Glob { .. } = string_value { // It already is a glob, so don't touch it. string_value } else { // Treat it as a string, then cast let string = string_value.into_string()?; Value::glob(string, *no_expand, *span) }; ctx.put_reg( *src_dst, PipelineExecutionData::from(glob_value.into_pipeline_data()), ); Ok(Continue) } Instruction::ListPush { src_dst, item } => { let list_value = ctx.collect_reg(*src_dst, *span)?; let item = ctx.collect_reg(*item, *span)?; let list_span = list_value.span(); let mut list = list_value.into_list()?; list.push(item); ctx.put_reg( *src_dst, PipelineExecutionData::from(Value::list(list, list_span).into_pipeline_data()), ); Ok(Continue) } Instruction::ListSpread { src_dst, items } => { let list_value = ctx.collect_reg(*src_dst, *span)?; let items = ctx.collect_reg(*items, *span)?; let list_span = list_value.span(); let items_span = items.span(); let items = match items { Value::List { vals, .. } => vals, Value::Nothing { .. } => Vec::new(), _ => return Err(ShellError::CannotSpreadAsList { span: items_span }), }; let mut list = list_value.into_list()?; list.extend(items); ctx.put_reg( *src_dst, PipelineExecutionData::from(Value::list(list, list_span).into_pipeline_data()), ); Ok(Continue) } Instruction::RecordInsert { src_dst, key, val } => { let record_value = ctx.collect_reg(*src_dst, *span)?; let key = ctx.collect_reg(*key, *span)?; let val = ctx.collect_reg(*val, *span)?; let record_span = record_value.span(); let mut record = record_value.into_record()?; let key = key.coerce_into_string()?; if let Some(old_value) = record.insert(&key, val) { return Err(ShellError::ColumnDefinedTwice { col_name: key, second_use: *span, first_use: old_value.span(), }); } ctx.put_reg( *src_dst, PipelineExecutionData::from( Value::record(record, record_span).into_pipeline_data(), ), ); Ok(Continue) } Instruction::RecordSpread { src_dst, items } => { let record_value = ctx.collect_reg(*src_dst, *span)?; let items = ctx.collect_reg(*items, *span)?; let record_span = record_value.span(); let items_span = items.span(); let mut record = record_value.into_record()?; let items = match items { Value::Record { val, .. } => val.into_owned(), Value::Nothing { .. } => Record::new(), _ => return Err(ShellError::CannotSpreadAsRecord { span: items_span }), }; // Not using .extend() here because it doesn't handle duplicates for (key, val) in items { if let Some(first_value) = record.insert(&key, val) { return Err(ShellError::ColumnDefinedTwice { col_name: key, second_use: *span, first_use: first_value.span(), }); } } ctx.put_reg( *src_dst, PipelineExecutionData::from( Value::record(record, record_span).into_pipeline_data(), ), ); Ok(Continue) } Instruction::Not { src_dst } => { let bool = ctx.collect_reg(*src_dst, *span)?; let negated = !bool.as_bool()?; ctx.put_reg( *src_dst, PipelineExecutionData::from(Value::bool(negated, bool.span()).into_pipeline_data()), ); Ok(Continue) } Instruction::BinaryOp { lhs_dst, op, rhs } => binary_op(ctx, *lhs_dst, op, *rhs, *span), Instruction::FollowCellPath { src_dst, path } => { let data = ctx.take_reg(*src_dst); let path = ctx.take_reg(*path); if let PipelineData::Value(Value::CellPath { val: path, .. }, _) = path.body { let value = data.body.follow_cell_path(&path.members, *span)?; ctx.put_reg( *src_dst, PipelineExecutionData::from(value.into_pipeline_data()), ); Ok(Continue) } else if let PipelineData::Value(Value::Error { error, .. }, _) = path.body { Err(*error) } else { Err(ShellError::TypeMismatch { err_message: "expected cell path".into(), span: path.span().unwrap_or(*span), }) } } Instruction::CloneCellPath { dst, src, path } => { let value = ctx.clone_reg_value(*src, *span)?; let path = ctx.take_reg(*path); if let PipelineData::Value(Value::CellPath { val: path, .. }, _) = path.body { let value = value.follow_cell_path(&path.members)?; ctx.put_reg( *dst, PipelineExecutionData::from(value.into_owned().into_pipeline_data()), ); Ok(Continue) } else if let PipelineData::Value(Value::Error { error, .. }, _) = path.body { Err(*error) } else { Err(ShellError::TypeMismatch { err_message: "expected cell path".into(), span: path.span().unwrap_or(*span), }) } } Instruction::UpsertCellPath { src_dst, path, new_value, } => { let data = ctx.take_reg(*src_dst); let metadata = data.metadata(); // Change the span because we're modifying it let mut value = data.body.into_value(*span)?; let path = ctx.take_reg(*path); let new_value = ctx.collect_reg(*new_value, *span)?; if let PipelineData::Value(Value::CellPath { val: path, .. }, _) = path.body { value.upsert_data_at_cell_path(&path.members, new_value)?; ctx.put_reg( *src_dst, PipelineExecutionData::from(value.into_pipeline_data_with_metadata(metadata)), ); Ok(Continue) } else if let PipelineData::Value(Value::Error { error, .. }, _) = path.body { Err(*error) } else { Err(ShellError::TypeMismatch { err_message: "expected cell path".into(), span: path.span().unwrap_or(*span), }) } } Instruction::Jump { index } => Ok(Branch(*index)), Instruction::BranchIf { cond, index } => { let data = ctx.take_reg(*cond); let data_span = data.span(); let val = match data.body { PipelineData::Value(Value::Bool { val, .. }, _) => val, PipelineData::Value(Value::Error { error, .. }, _) => { return Err(*error); } _ => { return Err(ShellError::TypeMismatch { err_message: "expected bool".into(), span: data_span.unwrap_or(*span), }); } }; if val { Ok(Branch(*index)) } else { Ok(Continue) } } Instruction::BranchIfEmpty { src, index } => { let is_empty = matches!( ctx.borrow_reg(*src), PipelineData::Empty | PipelineData::Value(Value::Nothing { .. }, _) ); if is_empty { Ok(Branch(*index)) } else { Ok(Continue) } } Instruction::Match { pattern, src, index, } => { let value = ctx.clone_reg_value(*src, *span)?;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/lib.rs
crates/nu-engine/src/lib.rs
#![doc = include_str!("../README.md")] mod call_ext; mod closure_eval; pub mod column; pub mod command_prelude; mod compile; pub mod documentation; pub mod env; mod eval; mod eval_helpers; mod eval_ir; pub mod exit; mod glob_from; pub mod scope; pub use call_ext::CallExt; pub use closure_eval::*; pub use column::get_columns; pub use compile::compile; pub use documentation::get_full_help; pub use env::*; pub use eval::{ eval_block, eval_block_with_early_return, eval_call, eval_expression, eval_expression_with_input, eval_subexpression, eval_variable, redirect_env, }; pub use eval_helpers::*; pub use eval_ir::eval_ir_block; pub use glob_from::glob_from;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/column.rs
crates/nu-engine/src/column.rs
use nu_protocol::Value; use std::collections::HashSet; pub fn get_columns(input: &[Value]) -> Vec<String> { let mut column_set = HashSet::new(); let mut columns = Vec::new(); for item in input { let Value::Record { val, .. } = item else { return vec![]; }; for col in val.columns() { if column_set.insert(col) { columns.push(col.to_string()); } } } columns } // If a column doesn't exist in the input, return it. pub fn nonexistent_column<'a, I>(inputs: &[String], columns: I) -> Option<String> where I: IntoIterator<Item = &'a String>, { let set: HashSet<&String> = HashSet::from_iter(columns); for input in inputs { if set.contains(input) { continue; } return Some(input.clone()); } None }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/call_ext.rs
crates/nu-engine/src/call_ext.rs
use crate::eval_expression; use nu_protocol::{ FromValue, ShellError, Span, Value, ast, debugger::WithoutDebug, engine::{self, EngineState, Stack, StateWorkingSet}, eval_const::eval_constant, ir, }; pub trait CallExt { /// Check if a boolean flag is set (i.e. `--bool` or `--bool=true`) fn has_flag( &self, engine_state: &EngineState, stack: &mut Stack, flag_name: &str, ) -> Result<bool, ShellError>; fn get_flag<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, name: &str, ) -> Result<Option<T>, ShellError>; /// Efficiently get the span of a flag argument fn get_flag_span(&self, stack: &Stack, name: &str) -> Option<Span>; fn rest<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, starting_pos: usize, ) -> Result<Vec<T>, ShellError>; fn opt<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, pos: usize, ) -> Result<Option<T>, ShellError>; fn opt_const<T: FromValue>( &self, working_set: &StateWorkingSet, pos: usize, ) -> Result<Option<T>, ShellError>; fn req<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, pos: usize, ) -> Result<T, ShellError>; fn req_parser_info<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, name: &str, ) -> Result<T, ShellError>; /// True if the command has any positional or rest arguments, excluding before the given index. fn has_positional_args(&self, stack: &Stack, starting_pos: usize) -> bool; } impl CallExt for ast::Call { fn has_flag( &self, engine_state: &EngineState, stack: &mut Stack, 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 stack = &mut stack.use_call_arg_out_dest(); let result = eval_expression::<WithoutDebug>(engine_state, stack, 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) } fn get_flag<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, name: &str, ) -> Result<Option<T>, ShellError> { if let Some(expr) = self.get_flag_expr(name) { let stack = &mut stack.use_call_arg_out_dest(); let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?; FromValue::from_value(result).map(Some) } else { Ok(None) } } fn get_flag_span(&self, _stack: &Stack, name: &str) -> Option<Span> { self.get_named_arg(name).map(|arg| arg.span) } fn rest<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, starting_pos: usize, ) -> Result<Vec<T>, ShellError> { let stack = &mut stack.use_call_arg_out_dest(); self.rest_iter_flattened(starting_pos, |expr| { eval_expression::<WithoutDebug>(engine_state, stack, expr) })? .into_iter() .map(FromValue::from_value) .collect() } fn opt<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, pos: usize, ) -> Result<Option<T>, ShellError> { if let Some(expr) = self.positional_nth(pos) { let stack = &mut stack.use_call_arg_out_dest(); let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?; FromValue::from_value(result).map(Some) } else { Ok(None) } } fn opt_const<T: FromValue>( &self, working_set: &StateWorkingSet, pos: usize, ) -> Result<Option<T>, ShellError> { if let Some(expr) = self.positional_nth(pos) { let result = eval_constant(working_set, expr)?; FromValue::from_value(result).map(Some) } else { Ok(None) } } fn req<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, pos: usize, ) -> Result<T, ShellError> { if let Some(expr) = self.positional_nth(pos) { let stack = &mut stack.use_call_arg_out_dest(); let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?; FromValue::from_value(result) } else if self.positional_len() == 0 { Err(ShellError::AccessEmptyContent { span: self.head }) } else { Err(ShellError::AccessBeyondEnd { max_idx: self.positional_len() - 1, span: self.head, }) } } fn req_parser_info<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, name: &str, ) -> Result<T, ShellError> { if let Some(expr) = self.get_parser_info(name) { let stack = &mut stack.use_call_arg_out_dest(); let result = eval_expression::<WithoutDebug>(engine_state, stack, expr)?; FromValue::from_value(result) } else if self.parser_info.is_empty() { Err(ShellError::AccessEmptyContent { span: self.head }) } else { Err(ShellError::AccessBeyondEnd { max_idx: self.parser_info.len() - 1, span: self.head, }) } } fn has_positional_args(&self, _stack: &Stack, starting_pos: usize) -> bool { self.rest_iter(starting_pos).next().is_some() } } impl CallExt for ir::Call { fn has_flag( &self, _engine_state: &EngineState, stack: &mut Stack, flag_name: &str, ) -> Result<bool, ShellError> { Ok(self .named_iter(stack) .find(|(name, _)| name.item == flag_name) .is_some_and(|(_, value)| { // Handle --flag=false !matches!(value, Some(Value::Bool { val: false, .. })) })) } fn get_flag<T: FromValue>( &self, _engine_state: &EngineState, stack: &mut Stack, name: &str, ) -> Result<Option<T>, ShellError> { if let Some(val) = self.get_named_arg(stack, name) { T::from_value(val.clone()).map(Some) } else { Ok(None) } } fn get_flag_span(&self, stack: &Stack, name: &str) -> Option<Span> { self.named_iter(stack) .find_map(|(i_name, _)| (i_name.item == name).then_some(i_name.span)) } fn rest<T: FromValue>( &self, _engine_state: &EngineState, stack: &mut Stack, starting_pos: usize, ) -> Result<Vec<T>, ShellError> { self.rest_iter_flattened(stack, starting_pos)? .into_iter() .map(T::from_value) .collect() } fn opt<T: FromValue>( &self, _engine_state: &EngineState, stack: &mut Stack, pos: usize, ) -> Result<Option<T>, ShellError> { self.positional_iter(stack) .nth(pos) .cloned() .map(T::from_value) .transpose() } fn opt_const<T: FromValue>( &self, _working_set: &StateWorkingSet, _pos: usize, ) -> Result<Option<T>, ShellError> { Err(ShellError::IrEvalError { msg: "const evaluation is not yet implemented on ir::Call".into(), span: Some(self.head), }) } fn req<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, pos: usize, ) -> Result<T, ShellError> { if let Some(val) = self.opt(engine_state, stack, pos)? { Ok(val) } else if self.positional_len(stack) == 0 { Err(ShellError::AccessEmptyContent { span: self.head }) } else { Err(ShellError::AccessBeyondEnd { max_idx: self.positional_len(stack) - 1, span: self.head, }) } } fn req_parser_info<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, name: &str, ) -> Result<T, ShellError> { // FIXME: this depends on the AST evaluator. We can fix this by making the parser info an // enum rather than using expressions. It's not clear that evaluation of this is ever really // needed. if let Some(expr) = self.get_parser_info(stack, name) { let expr = expr.clone(); let stack = &mut stack.use_call_arg_out_dest(); let result = eval_expression::<WithoutDebug>(engine_state, stack, &expr)?; FromValue::from_value(result) } else { Err(ShellError::CantFindColumn { col_name: name.into(), span: None, src_span: self.head, }) } } fn has_positional_args(&self, stack: &Stack, starting_pos: usize) -> bool { self.rest_iter(stack, starting_pos).next().is_some() } } macro_rules! proxy { ($self:ident . $method:ident ($($param:expr),*)) => (match &$self.inner { engine::CallImpl::AstRef(call) => call.$method($($param),*), engine::CallImpl::AstBox(call) => call.$method($($param),*), engine::CallImpl::IrRef(call) => call.$method($($param),*), engine::CallImpl::IrBox(call) => call.$method($($param),*), }) } impl CallExt for engine::Call<'_> { fn has_flag( &self, engine_state: &EngineState, stack: &mut Stack, flag_name: &str, ) -> Result<bool, ShellError> { proxy!(self.has_flag(engine_state, stack, flag_name)) } fn get_flag<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, name: &str, ) -> Result<Option<T>, ShellError> { proxy!(self.get_flag(engine_state, stack, name)) } fn get_flag_span(&self, stack: &Stack, name: &str) -> Option<Span> { proxy!(self.get_flag_span(stack, name)) } fn rest<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, starting_pos: usize, ) -> Result<Vec<T>, ShellError> { proxy!(self.rest(engine_state, stack, starting_pos)) } fn opt<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, pos: usize, ) -> Result<Option<T>, ShellError> { proxy!(self.opt(engine_state, stack, pos)) } fn opt_const<T: FromValue>( &self, working_set: &StateWorkingSet, pos: usize, ) -> Result<Option<T>, ShellError> { proxy!(self.opt_const(working_set, pos)) } fn req<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, pos: usize, ) -> Result<T, ShellError> { proxy!(self.req(engine_state, stack, pos)) } fn req_parser_info<T: FromValue>( &self, engine_state: &EngineState, stack: &mut Stack, name: &str, ) -> Result<T, ShellError> { proxy!(self.req_parser_info(engine_state, stack, name)) } fn has_positional_args(&self, stack: &Stack, starting_pos: usize) -> bool { proxy!(self.has_positional_args(stack, starting_pos)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/env.rs
crates/nu-engine/src/env.rs
use crate::ClosureEvalOnce; use nu_path::canonicalize_with; use nu_protocol::{ ShellError, Span, Type, Value, VarId, ast::Expr, engine::{Call, EngineState, Stack, StateWorkingSet}, shell_error::io::{IoError, IoErrorExt, NotFound}, }; use std::{ collections::HashMap, path::{Path, PathBuf}, sync::Arc, }; pub const ENV_CONVERSIONS: &str = "ENV_CONVERSIONS"; enum ConversionError { ShellError(ShellError), CellPathError, } impl From<ShellError> for ConversionError { fn from(value: ShellError) -> Self { Self::ShellError(value) } } /// Translate environment variables from Strings to Values. pub fn convert_env_vars( stack: &mut Stack, engine_state: &EngineState, conversions: &Value, ) -> Result<(), ShellError> { let conversions = conversions.as_record()?; for (key, conversion) in conversions.into_iter() { if let Some((case_preserve_env_name, val)) = stack.get_env_var_insensitive(engine_state, key) { match val.get_type() { Type::String => {} _ => continue, } let conversion = conversion .as_record()? .get("from_string") .ok_or(ShellError::MissingRequiredColumn { column: "from_string", span: conversion.span(), })? .as_closure()?; let new_val = ClosureEvalOnce::new(engine_state, stack, conversion.clone()) .debug(false) .run_with_value(val.clone())? .into_value(val.span())?; stack.add_env_var(case_preserve_env_name.to_string(), new_val); } } Ok(()) } /// Translate environment variables from Strings to Values. Requires config to be already set up in /// case the user defined custom env conversions in config.nu. /// /// It returns Option instead of Result since we do want to translate all the values we can and /// skip errors. This function is called in the main() so we want to keep running, we cannot just /// exit. pub fn convert_env_values( engine_state: &mut EngineState, stack: &mut Stack, ) -> Result<(), ShellError> { let mut error = None; let mut new_scope = HashMap::new(); let env_vars = engine_state.render_env_vars(); for (name, val) in env_vars { if let Value::String { .. } = val { // Only run from_string on string values match get_converted_value(engine_state, stack, name, val, "from_string") { Ok(v) => { let _ = new_scope.insert(name.to_string(), v); } Err(ConversionError::ShellError(e)) => error = error.or(Some(e)), Err(ConversionError::CellPathError) => { let _ = new_scope.insert(name.to_string(), val.clone()); } } } else { // Skip values that are already converted (not a string) let _ = new_scope.insert(name.to_string(), val.clone()); } } error = error.or_else(|| ensure_path(engine_state, stack)); if let Ok(last_overlay_name) = &stack.last_overlay_name() { if let Some(env_vars) = Arc::make_mut(&mut engine_state.env_vars).get_mut(last_overlay_name) { for (k, v) in new_scope { env_vars.insert(k, v); } } else { error = error.or_else(|| { Some(ShellError::NushellFailedHelp { msg: "Last active overlay not found in permanent state.".into(), help: "This error happened during the conversion of environment variables from strings to Nushell values.".into() }) }); } } else { error = error.or_else(|| { Some(ShellError::NushellFailedHelp { msg: "Last active overlay not found in stack.".into(), help: "This error happened during the conversion of environment variables from strings to Nushell values.".into() }) }); } if let Some(err) = error { Err(err) } else { Ok(()) } } /// Translate one environment variable from Value to String /// /// Returns Ok(None) if the env var is not pub fn env_to_string( env_name: &str, value: &Value, engine_state: &EngineState, stack: &Stack, ) -> Result<String, ShellError> { match get_converted_value(engine_state, stack, env_name, value, "to_string") { Ok(v) => Ok(v.coerce_into_string()?), Err(ConversionError::ShellError(e)) => Err(e), Err(ConversionError::CellPathError) => match value.coerce_string() { Ok(s) => Ok(s), Err(_) => { if env_name.to_lowercase() == "path" { // Try to convert PATH/Path list to a string match value { Value::List { vals, .. } => { let paths: Vec<String> = vals .iter() .filter_map(|v| v.coerce_str().ok()) .map(|s| nu_path::expand_tilde(&*s).to_string_lossy().into_owned()) .collect(); std::env::join_paths(paths.iter().map(AsRef::<str>::as_ref)) .map(|p| p.to_string_lossy().to_string()) .map_err(|_| ShellError::EnvVarNotAString { envvar_name: env_name.to_string(), span: value.span(), }) } _ => Err(ShellError::EnvVarNotAString { envvar_name: env_name.to_string(), span: value.span(), }), } } else { Err(ShellError::EnvVarNotAString { envvar_name: env_name.to_string(), span: value.span(), }) } } }, } } /// Translate all environment variables from Values to Strings pub fn env_to_strings( engine_state: &EngineState, stack: &Stack, ) -> Result<HashMap<String, String>, ShellError> { let env_vars = stack.get_env_vars(engine_state); let mut env_vars_str = HashMap::new(); for (env_name, val) in env_vars { match env_to_string(&env_name, &val, engine_state, stack) { Ok(val_str) => { env_vars_str.insert(env_name, val_str); } Err(ShellError::EnvVarNotAString { .. }) => {} // ignore non-string values Err(e) => return Err(e), } } Ok(env_vars_str) } /// Returns the current working directory as a String, which is guaranteed to be canonicalized. /// Unlike `current_dir_str_const()`, this also considers modifications to the current working directory made on the stack. /// /// Returns an error if $env.PWD doesn't exist, is not a String, or is not an absolute path. #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")] pub fn current_dir_str(engine_state: &EngineState, stack: &Stack) -> Result<String, ShellError> { #[allow(deprecated)] current_dir(engine_state, stack).map(|path| path.to_string_lossy().to_string()) } /// Returns the current working directory as a String, which is guaranteed to be canonicalized. /// /// Returns an error if $env.PWD doesn't exist, is not a String, or is not an absolute path. #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")] pub fn current_dir_str_const(working_set: &StateWorkingSet) -> Result<String, ShellError> { #[allow(deprecated)] current_dir_const(working_set).map(|path| path.to_string_lossy().to_string()) } /// Returns the current working directory, which is guaranteed to be canonicalized. /// Unlike `current_dir_const()`, this also considers modifications to the current working directory made on the stack. /// /// Returns an error if $env.PWD doesn't exist, is not a String, or is not an absolute path. #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")] pub fn current_dir(engine_state: &EngineState, stack: &Stack) -> Result<PathBuf, ShellError> { let cwd = engine_state.cwd(Some(stack))?; // `EngineState::cwd()` always returns absolute path. // We're using `canonicalize_with` instead of `fs::canonicalize()` because // we still need to simplify Windows paths. "." is safe because `cwd` should // be an absolute path already. canonicalize_with(&cwd, ".").map_err(|err| { ShellError::Io(IoError::new_internal_with_path( err.not_found_as(NotFound::Directory), "Could not canonicalize current dir", nu_protocol::location!(), PathBuf::from(cwd), )) }) } /// Returns the current working directory, which is guaranteed to be canonicalized. /// /// Returns an error if $env.PWD doesn't exist, is not a String, or is not an absolute path. #[deprecated(since = "0.92.3", note = "please use `EngineState::cwd()` instead")] pub fn current_dir_const(working_set: &StateWorkingSet) -> Result<PathBuf, ShellError> { let cwd = working_set.permanent_state.cwd(None)?; // `EngineState::cwd()` always returns absolute path. // We're using `canonicalize_with` instead of `fs::canonicalize()` because // we still need to simplify Windows paths. "." is safe because `cwd` should // be an absolute path already. canonicalize_with(&cwd, ".").map_err(|err| { ShellError::Io(IoError::new_internal_with_path( err.not_found_as(NotFound::Directory), "Could not canonicalize current dir", nu_protocol::location!(), PathBuf::from(cwd), )) }) } /// Get the contents of path environment variable as a list of strings pub fn path_str( engine_state: &EngineState, stack: &Stack, span: Span, ) -> Result<String, ShellError> { let (pathname, pathval) = match stack.get_env_var_insensitive(engine_state, "path") { Some((_, v)) => Ok((if cfg!(windows) { "Path" } else { "PATH" }, v)), None => Err(ShellError::EnvVarNotFoundAtRuntime { envvar_name: if cfg!(windows) { "Path".to_string() } else { "PATH".to_string() }, span, }), }?; env_to_string(pathname, pathval, engine_state, stack) } pub const DIR_VAR_PARSER_INFO: &str = "dirs_var"; pub fn get_dirs_var_from_call(stack: &Stack, call: &Call) -> Option<VarId> { call.get_parser_info(stack, DIR_VAR_PARSER_INFO) .and_then(|x| { if let Expr::Var(id) = x.expr { Some(id) } else { None } }) } /// This helper function is used to find files during eval /// /// First, the actual current working directory is selected as /// a) the directory of a file currently being parsed /// b) current working directory (PWD) /// /// Then, if the file is not found in the actual cwd, NU_LIB_DIRS is checked. /// If there is a relative path in NU_LIB_DIRS, it is assumed to be relative to the actual cwd /// determined in the first step. /// /// Always returns an absolute path pub fn find_in_dirs_env( filename: &str, engine_state: &EngineState, stack: &Stack, dirs_var: Option<VarId>, ) -> Result<Option<PathBuf>, ShellError> { // Choose whether to use file-relative or PWD-relative path let cwd = if let Some(pwd) = stack.get_env_var(engine_state, "FILE_PWD") { match env_to_string("FILE_PWD", pwd, engine_state, stack) { Ok(cwd) => { if Path::new(&cwd).is_absolute() { cwd } else { return Err(ShellError::GenericError { error: "Invalid current directory".into(), msg: format!( "The 'FILE_PWD' environment variable must be set to an absolute path. Found: '{cwd}'" ), span: Some(pwd.span()), help: None, inner: vec![], }); } } Err(e) => return Err(e), } } else { engine_state.cwd_as_string(Some(stack))? }; let check_dir = |lib_dirs: Option<&Value>| -> Option<PathBuf> { if let Ok(p) = canonicalize_with(filename, &cwd) { return Some(p); } let path = Path::new(filename); if !path.is_relative() { return None; } lib_dirs? .as_list() .ok()? .iter() .map(|lib_dir| -> Option<PathBuf> { let dir = lib_dir.to_path().ok()?; let dir_abs = canonicalize_with(dir, &cwd).ok()?; canonicalize_with(filename, dir_abs).ok() }) .find(Option::is_some) .flatten() }; let lib_dirs = dirs_var.and_then(|var_id| engine_state.get_var(var_id).const_val.as_ref()); // TODO: remove (see #8310) let lib_dirs_fallback = stack.get_env_var(engine_state, "NU_LIB_DIRS"); Ok(check_dir(lib_dirs).or_else(|| check_dir(lib_dirs_fallback))) } fn get_converted_value( engine_state: &EngineState, stack: &Stack, name: &str, orig_val: &Value, direction: &str, ) -> Result<Value, ConversionError> { let conversion = stack .get_env_var(engine_state, ENV_CONVERSIONS) .ok_or(ConversionError::CellPathError)? .as_record()? .get(name) .ok_or(ConversionError::CellPathError)? .as_record()? .get(direction) .ok_or(ConversionError::CellPathError)? .as_closure()?; Ok( ClosureEvalOnce::new(engine_state, stack, conversion.clone()) .debug(false) .run_with_value(orig_val.clone())? .into_value(orig_val.span())?, ) } fn ensure_path(engine_state: &EngineState, stack: &mut Stack) -> Option<ShellError> { let mut error = None; // If PATH/Path is still a string, force-convert it to a list if let Some((preserve_case_name, value)) = stack.get_env_var_insensitive(engine_state, "Path") { let span = value.span(); match value { Value::String { val, .. } => { // Force-split path into a list let paths = std::env::split_paths(val) .map(|p| Value::string(p.to_string_lossy().to_string(), span)) .collect(); stack.add_env_var(preserve_case_name.to_string(), Value::list(paths, span)); } Value::List { vals, .. } => { // Must be a list of strings if !vals.iter().all(|v| matches!(v, Value::String { .. })) { error = error.or_else(|| { Some(ShellError::GenericError { error: format!( "Incorrect {preserve_case_name} environment variable value" ), msg: format!("{preserve_case_name} must be a list of strings"), span: Some(span), help: None, inner: vec![], }) }); } } val => { // All other values are errors let span = val.span(); error = error.or_else(|| { Some(ShellError::GenericError { error: format!("Incorrect {preserve_case_name} environment variable value"), msg: format!("{preserve_case_name} must be a list of strings"), span: Some(span), help: None, inner: vec![], }) }); } } } error }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/scope.rs
crates/nu-engine/src/scope.rs
use nu_protocol::{ CommandWideCompleter, DeclId, ModuleId, Signature, Span, Type, Value, VarId, ast::Expr, engine::{Command, EngineState, Stack, Visibility}, record, }; use std::{cmp::Ordering, collections::HashMap}; pub struct ScopeData<'e, 's> { engine_state: &'e EngineState, stack: &'s Stack, vars_map: HashMap<&'e Vec<u8>, &'e VarId>, decls_map: HashMap<&'e Vec<u8>, &'e DeclId>, modules_map: HashMap<&'e Vec<u8>, &'e ModuleId>, visibility: Visibility, } impl<'e, 's> ScopeData<'e, 's> { pub fn new(engine_state: &'e EngineState, stack: &'s Stack) -> Self { Self { engine_state, stack, vars_map: HashMap::new(), decls_map: HashMap::new(), modules_map: HashMap::new(), visibility: Visibility::new(), } } pub fn populate_vars(&mut self) { for overlay_frame in self.engine_state.active_overlays(&[]) { self.vars_map.extend(&overlay_frame.vars); } } // decls include all commands, i.e., normal commands, aliases, and externals pub fn populate_decls(&mut self) { for overlay_frame in self.engine_state.active_overlays(&[]) { self.decls_map.extend(&overlay_frame.decls); self.visibility.merge_with(overlay_frame.visibility.clone()); } } pub fn populate_modules(&mut self) { for overlay_frame in self.engine_state.active_overlays(&[]) { self.modules_map.extend(&overlay_frame.modules); } } pub fn collect_vars(&self, span: Span) -> Vec<Value> { let mut vars = vec![]; for (var_name, var_id) in &self.vars_map { let var_name = Value::string(String::from_utf8_lossy(var_name).to_string(), span); let var = self.engine_state.get_var(**var_id); let var_type = Value::string(var.ty.to_string(), span); let is_const = Value::bool(var.const_val.is_some(), span); let var_value_result = self.stack.get_var(**var_id, span); // Skip variables that have no value in the stack and are not constants. // This ensures that variables deleted with unlet disappear from scope variables. if var_value_result.is_err() && var.const_val.is_none() { continue; } let var_value = var_value_result .ok() .or(var.const_val.clone()) .unwrap_or(Value::nothing(span)); let var_id_val = Value::int(var_id.get() as i64, span); vars.push(Value::record( record! { "name" => var_name, "type" => var_type, "value" => var_value, "is_const" => is_const, "var_id" => var_id_val, }, span, )); } sort_rows(&mut vars); vars } pub fn collect_commands(&self, span: Span) -> Vec<Value> { let mut commands = vec![]; for (command_name, decl_id) in &self.decls_map { if self.visibility.is_decl_id_visible(decl_id) && !self.engine_state.get_decl(**decl_id).is_alias() { let decl = self.engine_state.get_decl(**decl_id); let signature = decl.signature(); let examples = decl .examples() .into_iter() .map(|x| { Value::record( record! { "description" => Value::string(x.description, span), "example" => Value::string(x.example, span), "result" => x.result.unwrap_or(Value::nothing(span)).with_span(span), }, span, ) }) .collect(); let attributes = decl .attributes() .into_iter() .map(|(name, value)| { Value::record( record! { "name" => Value::string(name, span), "value" => value, }, span, ) }) .collect(); let record = record! { "name" => Value::string(String::from_utf8_lossy(command_name), span), "category" => Value::string(signature.category.to_string(), span), "signatures" => self.collect_signatures(&signature, span), "description" => Value::string(decl.description(), span), "examples" => Value::list(examples, span), "attributes" => Value::list(attributes, span), "type" => Value::string(decl.command_type().to_string(), span), "is_sub" => Value::bool(decl.is_sub(), span), "is_const" => Value::bool(decl.is_const(), span), "creates_scope" => Value::bool(signature.creates_scope, span), "extra_description" => Value::string(decl.extra_description(), span), "search_terms" => Value::string(decl.search_terms().join(", "), span), "complete" => match signature.complete { Some(CommandWideCompleter::Command(decl_id)) => Value::int(decl_id.get() as i64, span), Some(CommandWideCompleter::External) => Value::string("external", span), None => Value::nothing(span), }, "decl_id" => Value::int(decl_id.get() as i64, span), }; commands.push(Value::record(record, span)) } } sort_rows(&mut commands); commands } fn collect_signatures(&self, signature: &Signature, span: Span) -> Value { let mut sigs = signature .input_output_types .iter() .map(|(input_type, output_type)| { ( input_type.to_shape().to_string(), Value::list( self.collect_signature_entries(input_type, output_type, signature, span), span, ), ) }) .collect::<Vec<(String, Value)>>(); // Until we allow custom commands to have input and output types, let's just // make them Type::Any Type::Any so they can show up in our `scope commands` // a little bit better. If sigs is empty, we're pretty sure that we're dealing // with a custom command. if sigs.is_empty() { let any_type = &Type::Any; sigs.push(( any_type.to_shape().to_string(), Value::list( self.collect_signature_entries(any_type, any_type, signature, span), span, ), )); } sigs.sort_unstable_by(|(k1, _), (k2, _)| k1.cmp(k2)); // For most commands, input types are not repeated in // `input_output_types`, i.e. each input type has only one associated // output type. Furthermore, we want this to always be true. However, // there are currently some exceptions, such as `hash sha256` which // takes in string but may output string or binary depending on the // presence of the --binary flag. In such cases, the "special case" // signature usually comes later in the input_output_types, so this will // remove them from the record. sigs.dedup_by(|(k1, _), (k2, _)| k1 == k2); Value::record(sigs.into_iter().collect(), span) } fn collect_signature_entries( &self, input_type: &Type, output_type: &Type, signature: &Signature, span: Span, ) -> Vec<Value> { let mut sig_records = vec![]; // input sig_records.push(Value::record( record! { "parameter_name" => Value::nothing(span), "parameter_type" => Value::string("input", span), "syntax_shape" => Value::string(input_type.to_shape().to_string(), span), "is_optional" => Value::bool(false, span), "short_flag" => Value::nothing(span), "description" => Value::nothing(span), "completion" => Value::nothing(span), "parameter_default" => Value::nothing(span), }, span, )); // required_positional for req in &signature.required_positional { let completion = req .completion .as_ref() .map(|compl| compl.to_value(self.engine_state, span)) .unwrap_or(Value::nothing(span)); sig_records.push(Value::record( record! { "parameter_name" => Value::string(&req.name, span), "parameter_type" => Value::string("positional", span), "syntax_shape" => Value::string(req.shape.to_string(), span), "is_optional" => Value::bool(false, span), "short_flag" => Value::nothing(span), "description" => Value::string(&req.desc, span), "completion" => completion, "parameter_default" => Value::nothing(span), }, span, )); } // optional_positional for opt in &signature.optional_positional { let completion = opt .completion .as_ref() .map(|compl| compl.to_value(self.engine_state, span)) .unwrap_or(Value::nothing(span)); let default = if let Some(val) = &opt.default_value { val.clone() } else { Value::nothing(span) }; sig_records.push(Value::record( record! { "parameter_name" => Value::string(&opt.name, span), "parameter_type" => Value::string("positional", span), "syntax_shape" => Value::string(opt.shape.to_string(), span), "is_optional" => Value::bool(true, span), "short_flag" => Value::nothing(span), "description" => Value::string(&opt.desc, span), "completion" => completion, "parameter_default" => default, }, span, )); } // rest_positional if let Some(rest) = &signature.rest_positional { let name = if rest.name == "rest" { "" } else { &rest.name }; let completion = rest .completion .as_ref() .map(|compl| compl.to_value(self.engine_state, span)) .unwrap_or(Value::nothing(span)); sig_records.push(Value::record( record! { "parameter_name" => Value::string(name, span), "parameter_type" => Value::string("rest", span), "syntax_shape" => Value::string(rest.shape.to_string(), span), "is_optional" => Value::bool(true, span), "short_flag" => Value::nothing(span), "description" => Value::string(&rest.desc, span), "completion" => completion, // rest_positional does have default, but parser prohibits specifying it?! "parameter_default" => Value::nothing(span), }, span, )); } // named flags for named in &signature.named { let flag_type; // Skip the help flag if named.long == "help" { continue; } let completion = named .completion .as_ref() .map(|compl| compl.to_value(self.engine_state, span)) .unwrap_or(Value::nothing(span)); let shape = if let Some(arg) = &named.arg { flag_type = Value::string("named", span); Value::string(arg.to_string(), span) } else { flag_type = Value::string("switch", span); Value::nothing(span) }; let short_flag = if let Some(c) = named.short { Value::string(c, span) } else { Value::nothing(span) }; let default = if let Some(val) = &named.default_value { val.clone() } else { Value::nothing(span) }; sig_records.push(Value::record( record! { "parameter_name" => Value::string(&named.long, span), "parameter_type" => flag_type, "syntax_shape" => shape, "is_optional" => Value::bool(!named.required, span), "short_flag" => short_flag, "description" => Value::string(&named.desc, span), "completion" => completion, "parameter_default" => default, }, span, )); } // output sig_records.push(Value::record( record! { "parameter_name" => Value::nothing(span), "parameter_type" => Value::string("output", span), "syntax_shape" => Value::string(output_type.to_shape().to_string(), span), "is_optional" => Value::bool(false, span), "short_flag" => Value::nothing(span), "description" => Value::nothing(span), "completion" => Value::nothing(span), "parameter_default" => Value::nothing(span), }, span, )); sig_records } pub fn collect_externs(&self, span: Span) -> Vec<Value> { let mut externals = vec![]; for (command_name, decl_id) in &self.decls_map { let decl = self.engine_state.get_decl(**decl_id); if decl.is_known_external() { let record = record! { "name" => Value::string(String::from_utf8_lossy(command_name), span), "description" => Value::string(decl.description(), span), "decl_id" => Value::int(decl_id.get() as i64, span), }; externals.push(Value::record(record, span)) } } sort_rows(&mut externals); externals } pub fn collect_aliases(&self, span: Span) -> Vec<Value> { let mut aliases = vec![]; for (decl_name, decl_id) in self.engine_state.get_decls_sorted(false) { if self.visibility.is_decl_id_visible(&decl_id) { let decl = self.engine_state.get_decl(decl_id); if let Some(alias) = decl.as_alias() { let aliased_decl_id = if let Expr::Call(wrapped_call) = &alias.wrapped_call.expr { Value::int(wrapped_call.decl_id.get() as i64, span) } else { Value::nothing(span) }; let expansion = String::from_utf8_lossy( self.engine_state.get_span_contents(alias.wrapped_call.span), ); aliases.push(Value::record( record! { "name" => Value::string(String::from_utf8_lossy(&decl_name), span), "expansion" => Value::string(expansion, span), "description" => Value::string(alias.description(), span), "decl_id" => Value::int(decl_id.get() as i64, span), "aliased_decl_id" => aliased_decl_id, }, span, )); } } } sort_rows(&mut aliases); // aliases.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); aliases } fn collect_module(&self, module_name: &[u8], module_id: &ModuleId, span: Span) -> Value { let module = self.engine_state.get_module(*module_id); let all_decls = module.decls(); let mut export_commands: Vec<Value> = all_decls .iter() .filter_map(|(name_bytes, decl_id)| { let decl = self.engine_state.get_decl(*decl_id); if !decl.is_alias() && !decl.is_known_external() { Some(Value::record( record! { "name" => Value::string(String::from_utf8_lossy(name_bytes), span), "decl_id" => Value::int(decl_id.get() as i64, span), }, span, )) } else { None } }) .collect(); let mut export_aliases: Vec<Value> = all_decls .iter() .filter_map(|(name_bytes, decl_id)| { let decl = self.engine_state.get_decl(*decl_id); if decl.is_alias() { Some(Value::record( record! { "name" => Value::string(String::from_utf8_lossy(name_bytes), span), "decl_id" => Value::int(decl_id.get() as i64, span), }, span, )) } else { None } }) .collect(); let mut export_externs: Vec<Value> = all_decls .iter() .filter_map(|(name_bytes, decl_id)| { let decl = self.engine_state.get_decl(*decl_id); if decl.is_known_external() { Some(Value::record( record! { "name" => Value::string(String::from_utf8_lossy(name_bytes), span), "decl_id" => Value::int(decl_id.get() as i64, span), }, span, )) } else { None } }) .collect(); let mut export_submodules: Vec<Value> = module .submodules() .iter() .map(|(name_bytes, submodule_id)| self.collect_module(name_bytes, submodule_id, span)) .collect(); let mut export_consts: Vec<Value> = module .consts() .iter() .map(|(name_bytes, var_id)| { Value::record( record! { "name" => Value::string(String::from_utf8_lossy(name_bytes), span), "type" => Value::string(self.engine_state.get_var(*var_id).ty.to_string(), span), "var_id" => Value::int(var_id.get() as i64, span), }, span, ) }) .collect(); sort_rows(&mut export_commands); sort_rows(&mut export_aliases); sort_rows(&mut export_externs); sort_rows(&mut export_submodules); sort_rows(&mut export_consts); let (module_desc, module_extra_desc) = self .engine_state .build_module_desc(*module_id) .unwrap_or_default(); Value::record( record! { "name" => Value::string(String::from_utf8_lossy(module_name), span), "commands" => Value::list(export_commands, span), "aliases" => Value::list(export_aliases, span), "externs" => Value::list(export_externs, span), "submodules" => Value::list(export_submodules, span), "constants" => Value::list(export_consts, span), "has_env_block" => Value::bool(module.env_block.is_some(), span), "description" => Value::string(module_desc, span), "extra_description" => Value::string(module_extra_desc, span), "module_id" => Value::int(module_id.get() as i64, span), "file" => Value::string(module.file.clone().map_or("unknown".to_string(), |(p, _)| p.path().to_string_lossy().to_string()), span), }, span, ) } pub fn collect_modules(&self, span: Span) -> Vec<Value> { let mut modules = vec![]; for (module_name, module_id) in &self.modules_map { modules.push(self.collect_module(module_name, module_id, span)); } modules.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); modules } pub fn collect_engine_state(&self, span: Span) -> Value { let num_env_vars = self .engine_state .env_vars .values() .map(|overlay| overlay.len() as i64) .sum(); Value::record( record! { "source_bytes" => Value::int(self.engine_state.next_span_start() as i64, span), "num_vars" => Value::int(self.engine_state.num_vars() as i64, span), "num_decls" => Value::int(self.engine_state.num_decls() as i64, span), "num_blocks" => Value::int(self.engine_state.num_blocks() as i64, span), "num_modules" => Value::int(self.engine_state.num_modules() as i64, span), "num_env_vars" => Value::int(num_env_vars, span), }, span, ) } } fn sort_rows(decls: &mut [Value]) { decls.sort_by(|a, b| match (a, b) { (Value::Record { val: rec_a, .. }, Value::Record { val: rec_b, .. }) => { // Comparing the first value from the record // It is expected that the first value is the name of the entry (command, module, alias, etc.) match (rec_a.values().next(), rec_b.values().next()) { (Some(val_a), Some(val_b)) => match (val_a, val_b) { (Value::String { val: str_a, .. }, Value::String { val: str_b, .. }) => { str_a.cmp(str_b) } _ => Ordering::Equal, }, _ => Ordering::Equal, } } _ => Ordering::Equal, }); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/closure_eval.rs
crates/nu-engine/src/closure_eval.rs
use crate::{ EvalBlockWithEarlyReturnFn, eval_block_with_early_return, get_eval_block_with_early_return, }; use nu_protocol::{ IntoPipelineData, PipelineData, ShellError, Value, ast::Block, debugger::{WithDebug, WithoutDebug}, engine::{Closure, EngineState, EnvVars, Stack}, }; use std::{ borrow::Cow, collections::{HashMap, HashSet}, sync::Arc, }; fn eval_fn(debug: bool) -> EvalBlockWithEarlyReturnFn { if debug { eval_block_with_early_return::<WithDebug> } else { eval_block_with_early_return::<WithoutDebug> } } /// [`ClosureEval`] is used to repeatedly evaluate a closure with different values/inputs. /// /// [`ClosureEval`] has a builder API. /// It is first created via [`ClosureEval::new`], /// then has arguments added via [`ClosureEval::add_arg`], /// and then can be run using [`ClosureEval::run_with_input`]. /// /// ```no_run /// # use nu_protocol::{PipelineData, Value}; /// # use nu_engine::ClosureEval; /// # let engine_state = unimplemented!(); /// # let stack = unimplemented!(); /// # let closure = unimplemented!(); /// let mut closure = ClosureEval::new(engine_state, stack, closure); /// let iter = Vec::<Value>::new() /// .into_iter() /// .map(move |value| closure.add_arg(value).run_with_input(PipelineData::empty())); /// ``` /// /// Many closures follow a simple, common scheme where the pipeline input and the first argument are the same value. /// In this case, use [`ClosureEval::run_with_value`]: /// /// ```no_run /// # use nu_protocol::{PipelineData, Value}; /// # use nu_engine::ClosureEval; /// # let engine_state = unimplemented!(); /// # let stack = unimplemented!(); /// # let closure = unimplemented!(); /// let mut closure = ClosureEval::new(engine_state, stack, closure); /// let iter = Vec::<Value>::new() /// .into_iter() /// .map(move |value| closure.run_with_value(value)); /// ``` /// /// Environment isolation and other cleanup is handled by [`ClosureEval`], /// so nothing needs to be done following [`ClosureEval::run_with_input`] or [`ClosureEval::run_with_value`]. #[derive(Clone)] pub struct ClosureEval { engine_state: EngineState, stack: Stack, block: Arc<Block>, arg_index: usize, env_vars: Vec<Arc<EnvVars>>, env_hidden: Arc<HashMap<String, HashSet<String>>>, eval: EvalBlockWithEarlyReturnFn, } impl ClosureEval { /// Create a new [`ClosureEval`]. pub fn new(engine_state: &EngineState, stack: &Stack, closure: Closure) -> Self { let engine_state = engine_state.clone(); let stack = stack.captures_to_stack(closure.captures); let block = engine_state.get_block(closure.block_id).clone(); let env_vars = stack.env_vars.clone(); let env_hidden = stack.env_hidden.clone(); let eval = get_eval_block_with_early_return(&engine_state); Self { engine_state, stack, block, arg_index: 0, env_vars, env_hidden, eval, } } pub fn new_preserve_out_dest( engine_state: &EngineState, stack: &Stack, closure: Closure, ) -> Self { let engine_state = engine_state.clone(); let stack = stack.captures_to_stack_preserve_out_dest(closure.captures); let block = engine_state.get_block(closure.block_id).clone(); let env_vars = stack.env_vars.clone(); let env_hidden = stack.env_hidden.clone(); let eval = get_eval_block_with_early_return(&engine_state); Self { engine_state, stack, block, arg_index: 0, env_vars, env_hidden, eval, } } /// Sets whether to enable debugging when evaluating the closure. /// /// By default, this is controlled by the [`EngineState`] used to create this [`ClosureEval`]. pub fn debug(&mut self, debug: bool) -> &mut Self { self.eval = eval_fn(debug); self } fn try_add_arg(&mut self, value: Cow<Value>) { if let Some(var_id) = self .block .signature .get_positional(self.arg_index) .and_then(|var| var.var_id) { self.stack.add_var(var_id, value.into_owned()); self.arg_index += 1; } } /// Add an argument [`Value`] to the closure. /// /// Multiple [`add_arg`](Self::add_arg) calls can be chained together, /// but make sure that arguments are added based on their positional order. pub fn add_arg(&mut self, value: Value) -> &mut Self { self.try_add_arg(Cow::Owned(value)); self } /// Run the closure, passing the given [`PipelineData`] as input. /// /// Any arguments should be added beforehand via [`add_arg`](Self::add_arg). pub fn run_with_input(&mut self, input: PipelineData) -> Result<PipelineData, ShellError> { self.arg_index = 0; self.stack.with_env(&self.env_vars, &self.env_hidden); (self.eval)(&self.engine_state, &mut self.stack, &self.block, input).map(|p| p.body) } /// Run the closure using the given [`Value`] as both the pipeline input and the first argument. /// /// Using this function after or in combination with [`add_arg`](Self::add_arg) is most likely an error. /// This function is equivalent to `self.add_arg(value)` followed by `self.run_with_input(value.into_pipeline_data())`. pub fn run_with_value(&mut self, value: Value) -> Result<PipelineData, ShellError> { self.try_add_arg(Cow::Borrowed(&value)); self.run_with_input(value.into_pipeline_data()) } } /// [`ClosureEvalOnce`] is used to evaluate a closure a single time. /// /// [`ClosureEvalOnce`] has a builder API. /// It is first created via [`ClosureEvalOnce::new`], /// then has arguments added via [`ClosureEvalOnce::add_arg`], /// and then can be run using [`ClosureEvalOnce::run_with_input`]. /// /// ```no_run /// # use nu_protocol::{ListStream, PipelineData, PipelineIterator}; /// # use nu_engine::ClosureEvalOnce; /// # let engine_state = unimplemented!(); /// # let stack = unimplemented!(); /// # let closure = unimplemented!(); /// # let value = unimplemented!(); /// let result = ClosureEvalOnce::new(engine_state, stack, closure) /// .add_arg(value) /// .run_with_input(PipelineData::empty()); /// ``` /// /// Many closures follow a simple, common scheme where the pipeline input and the first argument are the same value. /// In this case, use [`ClosureEvalOnce::run_with_value`]: /// /// ```no_run /// # use nu_protocol::{PipelineData, PipelineIterator}; /// # use nu_engine::ClosureEvalOnce; /// # let engine_state = unimplemented!(); /// # let stack = unimplemented!(); /// # let closure = unimplemented!(); /// # let value = unimplemented!(); /// let result = ClosureEvalOnce::new(engine_state, stack, closure).run_with_value(value); /// ``` pub struct ClosureEvalOnce<'a> { engine_state: &'a EngineState, stack: Stack, block: &'a Block, arg_index: usize, eval: EvalBlockWithEarlyReturnFn, } impl<'a> ClosureEvalOnce<'a> { /// Create a new [`ClosureEvalOnce`]. pub fn new(engine_state: &'a EngineState, stack: &Stack, closure: Closure) -> Self { let block = engine_state.get_block(closure.block_id); let eval = get_eval_block_with_early_return(engine_state); Self { engine_state, stack: stack.captures_to_stack(closure.captures), block, arg_index: 0, eval, } } pub fn new_preserve_out_dest( engine_state: &'a EngineState, stack: &Stack, closure: Closure, ) -> Self { let block = engine_state.get_block(closure.block_id); let eval = get_eval_block_with_early_return(engine_state); Self { engine_state, stack: stack.captures_to_stack_preserve_out_dest(closure.captures), block, arg_index: 0, eval, } } /// Sets whether to enable debugging when evaluating the closure. /// /// By default, this is controlled by the [`EngineState`] used to create this [`ClosureEvalOnce`]. pub fn debug(mut self, debug: bool) -> Self { self.eval = eval_fn(debug); self } fn try_add_arg(&mut self, value: Cow<Value>) { if let Some(var_id) = self .block .signature .get_positional(self.arg_index) .and_then(|var| var.var_id) { self.stack.add_var(var_id, value.into_owned()); self.arg_index += 1; } } /// Add an argument [`Value`] to the closure. /// /// Multiple [`add_arg`](Self::add_arg) calls can be chained together, /// but make sure that arguments are added based on their positional order. pub fn add_arg(mut self, value: Value) -> Self { self.try_add_arg(Cow::Owned(value)); self } /// Run the closure, passing the given [`PipelineData`] as input. /// /// Any arguments should be added beforehand via [`add_arg`](Self::add_arg). pub fn run_with_input(mut self, input: PipelineData) -> Result<PipelineData, ShellError> { (self.eval)(self.engine_state, &mut self.stack, self.block, input).map(|p| p.body) } /// Run the closure using the given [`Value`] as both the pipeline input and the first argument. /// /// Using this function after or in combination with [`add_arg`](Self::add_arg) is most likely an error. /// This function is equivalent to `self.add_arg(value)` followed by `self.run_with_input(value.into_pipeline_data())`. pub fn run_with_value(mut self, value: Value) -> Result<PipelineData, ShellError> { self.try_add_arg(Cow::Borrowed(&value)); self.run_with_input(value.into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/eval_helpers.rs
crates/nu-engine/src/eval_helpers.rs
use crate::{ eval_block, eval_block_with_early_return, eval_expression, eval_expression_with_input, eval_ir_block, eval_subexpression, }; use nu_protocol::{ PipelineData, PipelineExecutionData, ShellError, Value, ast::{Block, Expression}, debugger::{WithDebug, WithoutDebug}, engine::{EngineState, Stack}, }; /// Type of eval_block() function pub type EvalBlockFn = fn(&EngineState, &mut Stack, &Block, PipelineData) -> Result<PipelineExecutionData, ShellError>; /// Type of eval_ir_block() function pub type EvalIrBlockFn = fn(&EngineState, &mut Stack, &Block, PipelineData) -> Result<PipelineExecutionData, ShellError>; /// Type of eval_block_with_early_return() function pub type EvalBlockWithEarlyReturnFn = fn(&EngineState, &mut Stack, &Block, PipelineData) -> Result<PipelineExecutionData, ShellError>; /// Type of eval_expression() function pub type EvalExpressionFn = fn(&EngineState, &mut Stack, &Expression) -> Result<Value, ShellError>; /// Type of eval_expression_with_input() function pub type EvalExpressionWithInputFn = fn(&EngineState, &mut Stack, &Expression, PipelineData) -> Result<PipelineData, ShellError>; /// Type of eval_subexpression() function pub type EvalSubexpressionFn = fn(&EngineState, &mut Stack, &Block, PipelineData) -> Result<PipelineData, ShellError>; /// Helper function to fetch `eval_block()` with the correct type parameter based on whether /// engine_state is configured with or without a debugger. pub fn get_eval_block(engine_state: &EngineState) -> EvalBlockFn { if engine_state.is_debugging() { eval_block::<WithDebug> } else { eval_block::<WithoutDebug> } } /// Helper function to fetch `eval_ir_block()` with the correct type parameter based on whether /// engine_state is configured with or without a debugger. pub fn get_eval_ir_block(engine_state: &EngineState) -> EvalIrBlockFn { if engine_state.is_debugging() { eval_ir_block::<WithDebug> } else { eval_ir_block::<WithoutDebug> } } /// Helper function to fetch `eval_block_with_early_return()` with the correct type parameter based /// on whether engine_state is configured with or without a debugger. pub fn get_eval_block_with_early_return(engine_state: &EngineState) -> EvalBlockWithEarlyReturnFn { if engine_state.is_debugging() { eval_block_with_early_return::<WithDebug> } else { eval_block_with_early_return::<WithoutDebug> } } /// Helper function to fetch `eval_expression()` with the correct type parameter based on whether /// engine_state is configured with or without a debugger. pub fn get_eval_expression(engine_state: &EngineState) -> EvalExpressionFn { if engine_state.is_debugging() { eval_expression::<WithDebug> } else { eval_expression::<WithoutDebug> } } /// Helper function to fetch `eval_expression_with_input()` with the correct type parameter based /// on whether engine_state is configured with or without a debugger. pub fn get_eval_expression_with_input(engine_state: &EngineState) -> EvalExpressionWithInputFn { if engine_state.is_debugging() { eval_expression_with_input::<WithDebug> } else { eval_expression_with_input::<WithoutDebug> } } /// Helper function to fetch `eval_subexpression()` with the correct type parameter based on whether /// engine_state is configured with or without a debugger. pub fn get_eval_subexpression(engine_state: &EngineState) -> EvalSubexpressionFn { if engine_state.is_debugging() { eval_subexpression::<WithDebug> } else { eval_subexpression::<WithoutDebug> } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/command_prelude.rs
crates/nu-engine/src/command_prelude.rs
pub use crate::CallExt; pub use nu_protocol::{ ByteStream, ByteStreamType, Category, Completion, ErrSpan, Example, Flag, IntoInterruptiblePipelineData, IntoPipelineData, IntoSpanned, IntoValue, PipelineData, PositionalArg, Record, ShellError, ShellWarning, Signature, Span, Spanned, SyntaxShape, Type, Value, ast::CellPath, engine::{Call, Command, EngineState, Stack, StateWorkingSet}, record, shell_error::{io::*, job::*}, };
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/eval.rs
crates/nu-engine/src/eval.rs
use crate::eval_ir::eval_ir_block; #[allow(deprecated)] use crate::get_full_help; use nu_protocol::{ BlockId, Config, ENV_VARIABLE_ID, IntoPipelineData, PipelineData, PipelineExecutionData, ShellError, Span, Value, VarId, ast::{Assignment, Block, Call, Expr, Expression, ExternalArgument, PathMember}, debugger::DebugContext, engine::{Closure, EngineState, Stack}, eval_base::Eval, }; use nu_utils::IgnoreCaseExt; use std::sync::Arc; pub fn eval_call<D: DebugContext>( engine_state: &EngineState, caller_stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { engine_state.signals().check(&call.head)?; let decl = engine_state.get_decl(call.decl_id); if !decl.is_known_external() && call.named_iter().any(|(flag, _, _)| flag.item == "help") { let help = get_full_help(decl, engine_state, caller_stack); Ok(Value::string(help, call.head).into_pipeline_data()) } else if let Some(block_id) = decl.block_id() { let block = engine_state.get_block(block_id); let mut callee_stack = caller_stack.gather_captures(engine_state, &block.captures); // Rust does not check recursion limits outside of const evaluation. // But nu programs run in the same process as the shell. // To prevent a stack overflow in user code from crashing the shell, // we limit the recursion depth of function calls. // Picked 50 arbitrarily, should work on all architectures. let maximum_call_stack_depth: u64 = engine_state.config.recursion_limit as u64; callee_stack.recursion_count += 1; if callee_stack.recursion_count > maximum_call_stack_depth { callee_stack.recursion_count = 0; return Err(ShellError::RecursionLimitReached { recursion_limit: maximum_call_stack_depth, span: block.span, }); } for (param_idx, (param, required)) in decl .signature() .required_positional .iter() .map(|p| (p, true)) .chain( decl.signature() .optional_positional .iter() .map(|p| (p, false)), ) .enumerate() { let var_id = param .var_id .expect("internal error: all custom parameters must have var_ids"); if let Some(arg) = call.positional_nth(param_idx) { let result = eval_expression::<D>(engine_state, caller_stack, arg)?; let param_type = param.shape.to_type(); if required && !result.is_subtype_of(&param_type) { return Err(ShellError::CantConvert { to_type: param.shape.to_type().to_string(), from_type: result.get_type().to_string(), span: result.span(), help: None, }); } callee_stack.add_var(var_id, result); } else if let Some(value) = &param.default_value { callee_stack.add_var(var_id, value.to_owned()); } else { callee_stack.add_var(var_id, Value::nothing(call.head)); } } if let Some(rest_positional) = decl.signature().rest_positional { let mut rest_items = vec![]; for result in call.rest_iter_flattened( decl.signature().required_positional.len() + decl.signature().optional_positional.len(), |expr| eval_expression::<D>(engine_state, caller_stack, expr), )? { rest_items.push(result); } let span = if let Some(rest_item) = rest_items.first() { rest_item.span() } else { call.head }; callee_stack.add_var( rest_positional .var_id .expect("Internal error: rest positional parameter lacks var_id"), Value::list(rest_items, span), ) } for named in decl.signature().named { if let Some(var_id) = named.var_id { let mut found = false; for call_named in call.named_iter() { if let (Some(spanned), Some(short)) = (&call_named.1, named.short) { if spanned.item == short.to_string() { if let Some(arg) = &call_named.2 { let result = eval_expression::<D>(engine_state, caller_stack, arg)?; callee_stack.add_var(var_id, result); } else if let Some(value) = &named.default_value { callee_stack.add_var(var_id, value.to_owned()); } else { callee_stack.add_var(var_id, Value::bool(true, call.head)) } found = true; } } else if call_named.0.item == named.long { if let Some(arg) = &call_named.2 { let result = eval_expression::<D>(engine_state, caller_stack, arg)?; callee_stack.add_var(var_id, result); } else if let Some(value) = &named.default_value { callee_stack.add_var(var_id, value.to_owned()); } else { callee_stack.add_var(var_id, Value::bool(true, call.head)) } found = true; } } if !found { if named.arg.is_none() { callee_stack.add_var(var_id, Value::bool(false, call.head)) } else if let Some(value) = named.default_value { callee_stack.add_var(var_id, value); } else { callee_stack.add_var(var_id, Value::nothing(call.head)) } } } } let result = eval_block_with_early_return::<D>(engine_state, &mut callee_stack, block, input) .map(|p| p.body); if block.redirect_env { redirect_env(engine_state, caller_stack, &callee_stack); } result } else { // We pass caller_stack here with the knowledge that internal commands // are going to be specifically looking for global state in the stack // rather than any local state. decl.run(engine_state, caller_stack, &call.into(), input) } } /// Redirect the environment from callee to the caller. pub fn redirect_env(engine_state: &EngineState, caller_stack: &mut Stack, callee_stack: &Stack) { // Grab all environment variables from the callee let caller_env_vars = caller_stack.get_env_var_names(engine_state); // remove env vars that are present in the caller but not in the callee // (the callee hid them) for var in caller_env_vars.iter() { if !callee_stack.has_env_var(engine_state, var) { caller_stack.remove_env_var(engine_state, var); } } // add new env vars from callee to caller for (var, value) in callee_stack.get_stack_env_vars() { caller_stack.add_env_var(var, value); } // set config to callee config, to capture any updates to that caller_stack.config.clone_from(&callee_stack.config); } fn eval_external( engine_state: &EngineState, stack: &mut Stack, head: &Expression, args: &[ExternalArgument], input: PipelineData, ) -> Result<PipelineData, ShellError> { let decl_id = engine_state .find_decl("run-external".as_bytes(), &[]) .ok_or(ShellError::ExternalNotSupported { span: head.span(&engine_state), })?; let command = engine_state.get_decl(decl_id); let mut call = Call::new(head.span(&engine_state)); call.add_positional(head.clone()); for arg in args { match arg { ExternalArgument::Regular(expr) => call.add_positional(expr.clone()), ExternalArgument::Spread(expr) => call.add_spread(expr.clone()), } } command.run(engine_state, stack, &(&call).into(), input) } pub fn eval_expression<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, expr: &Expression, ) -> Result<Value, ShellError> { let stack = &mut stack.start_collect_value(); <EvalRuntime as Eval>::eval::<D>(engine_state, stack, expr) } /// Checks the expression to see if it's a internal or external call. If so, passes the input /// into the call and gets out the result /// Otherwise, invokes the expression /// /// It returns PipelineData with a boolean flag, indicating if the external failed to run. /// The boolean flag **may only be true** for external calls, for internal calls, it always to be false. pub fn eval_expression_with_input<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, expr: &Expression, mut input: PipelineData, ) -> Result<PipelineData, ShellError> { match &expr.expr { Expr::Call(call) => { input = eval_call::<D>(engine_state, stack, call, input)?; } Expr::ExternalCall(head, args) => { input = eval_external(engine_state, stack, head, args, input)?; } Expr::Collect(var_id, expr) => { input = eval_collect::<D>(engine_state, stack, *var_id, expr, input)?; } Expr::Subexpression(block_id) => { let block = engine_state.get_block(*block_id); // FIXME: protect this collect with ctrl-c input = eval_subexpression::<D>(engine_state, stack, block, input)?; } Expr::FullCellPath(full_cell_path) => match &full_cell_path.head { Expression { expr: Expr::Subexpression(block_id), span, .. } => { let block = engine_state.get_block(*block_id); if !full_cell_path.tail.is_empty() { let stack = &mut stack.start_collect_value(); // FIXME: protect this collect with ctrl-c input = eval_subexpression::<D>(engine_state, stack, block, input)? .into_value(*span)? .follow_cell_path(&full_cell_path.tail)? .into_owned() .into_pipeline_data() } else { input = eval_subexpression::<D>(engine_state, stack, block, input)?; } } _ => { input = eval_expression::<D>(engine_state, stack, expr)?.into_pipeline_data(); } }, _ => { input = eval_expression::<D>(engine_state, stack, expr)?.into_pipeline_data(); } }; Ok(input) } pub fn eval_block<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, block: &Block, input: PipelineData, ) -> Result<PipelineExecutionData, ShellError> { let result = eval_ir_block::<D>(engine_state, stack, block, input); if let Err(err) = &result { stack.set_last_error(err); } result } pub fn eval_block_with_early_return<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, block: &Block, input: PipelineData, ) -> Result<PipelineExecutionData, ShellError> { match eval_block::<D>(engine_state, stack, block, input) { Err(ShellError::Return { span: _, value }) => Ok(PipelineExecutionData::from( PipelineData::value(*value, None), )), x => x, } } pub fn eval_collect<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, var_id: VarId, expr: &Expression, input: PipelineData, ) -> Result<PipelineData, ShellError> { // Evaluate the expression with the variable set to the collected input let span = input.span().unwrap_or(Span::unknown()); let metadata = input.metadata().and_then(|m| m.for_collect()); let input = input.into_value(span)?; stack.add_var(var_id, input.clone()); let result = eval_expression_with_input::<D>( engine_state, stack, expr, // We still have to pass it as input input.into_pipeline_data_with_metadata(metadata), ); stack.remove_var(var_id); result } pub fn eval_subexpression<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, block: &Block, input: PipelineData, ) -> Result<PipelineData, ShellError> { eval_block::<D>(engine_state, stack, block, input).map(|p| p.body) } pub fn eval_variable( engine_state: &EngineState, stack: &Stack, var_id: VarId, span: Span, ) -> Result<Value, ShellError> { match var_id { // $nu nu_protocol::NU_VARIABLE_ID => { if let Some(val) = engine_state.get_constant(var_id) { Ok(val.clone()) } else { Err(ShellError::VariableNotFoundAtRuntime { span }) } } // $env ENV_VARIABLE_ID => { let env_vars = stack.get_env_vars(engine_state); let env_columns = env_vars.keys(); let env_values = env_vars.values(); let mut pairs = env_columns .map(|x| x.to_string()) .zip(env_values.cloned()) .collect::<Vec<(String, Value)>>(); pairs.sort_by(|a, b| a.0.cmp(&b.0)); Ok(Value::record(pairs.into_iter().collect(), span)) } var_id => stack.get_var(var_id, span), } } struct EvalRuntime; impl Eval for EvalRuntime { type State<'a> = &'a EngineState; type MutState = Stack; fn get_config(engine_state: Self::State<'_>, stack: &mut Stack) -> Arc<Config> { stack.get_config(engine_state) } fn eval_var( engine_state: &EngineState, stack: &mut Stack, var_id: VarId, span: Span, ) -> Result<Value, ShellError> { eval_variable(engine_state, stack, var_id, span) } fn eval_call<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, call: &Call, _: Span, ) -> Result<Value, ShellError> { // FIXME: protect this collect with ctrl-c eval_call::<D>(engine_state, stack, call, PipelineData::empty())?.into_value(call.head) } fn eval_external_call( engine_state: &EngineState, stack: &mut Stack, head: &Expression, args: &[ExternalArgument], _: Span, ) -> Result<Value, ShellError> { let span = head.span(&engine_state); // FIXME: protect this collect with ctrl-c eval_external(engine_state, stack, head, args, PipelineData::empty())?.into_value(span) } fn eval_collect<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, var_id: VarId, expr: &Expression, ) -> Result<Value, ShellError> { // It's a little bizarre, but the expression can still have some kind of result even with // nothing input eval_collect::<D>(engine_state, stack, var_id, expr, PipelineData::empty())? .into_value(expr.span) } fn eval_subexpression<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, block_id: BlockId, span: Span, ) -> Result<Value, ShellError> { let block = engine_state.get_block(block_id); // FIXME: protect this collect with ctrl-c eval_subexpression::<D>(engine_state, stack, block, PipelineData::empty())?.into_value(span) } fn regex_match( engine_state: &EngineState, op_span: Span, lhs: &Value, rhs: &Value, invert: bool, expr_span: Span, ) -> Result<Value, ShellError> { lhs.regex_match(engine_state, op_span, rhs, invert, expr_span) } fn eval_assignment<D: DebugContext>( engine_state: &EngineState, stack: &mut Stack, lhs: &Expression, rhs: &Expression, assignment: Assignment, op_span: Span, _expr_span: Span, ) -> Result<Value, ShellError> { let rhs = eval_expression::<D>(engine_state, stack, rhs)?; let rhs = match assignment { Assignment::Assign => rhs, Assignment::AddAssign => { let lhs = eval_expression::<D>(engine_state, stack, lhs)?; lhs.add(op_span, &rhs, op_span)? } Assignment::SubtractAssign => { let lhs = eval_expression::<D>(engine_state, stack, lhs)?; lhs.sub(op_span, &rhs, op_span)? } Assignment::MultiplyAssign => { let lhs = eval_expression::<D>(engine_state, stack, lhs)?; lhs.mul(op_span, &rhs, op_span)? } Assignment::DivideAssign => { let lhs = eval_expression::<D>(engine_state, stack, lhs)?; lhs.div(op_span, &rhs, op_span)? } Assignment::ConcatenateAssign => { let lhs = eval_expression::<D>(engine_state, stack, lhs)?; lhs.concat(op_span, &rhs, op_span)? } }; match &lhs.expr { Expr::Var(var_id) | Expr::VarDecl(var_id) => { let var_info = engine_state.get_var(*var_id); if var_info.mutable { stack.add_var(*var_id, rhs); Ok(Value::nothing(lhs.span(&engine_state))) } else { Err(ShellError::AssignmentRequiresMutableVar { lhs_span: lhs.span(&engine_state), }) } } Expr::FullCellPath(cell_path) => { match &cell_path.head.expr { Expr::Var(var_id) | Expr::VarDecl(var_id) => { // The $env variable is considered "mutable" in Nushell. // As such, give it special treatment here. let is_env = var_id == &ENV_VARIABLE_ID; if is_env || engine_state.get_var(*var_id).mutable { let mut lhs = eval_expression::<D>(engine_state, stack, &cell_path.head)?; if is_env { // Reject attempts to assign to the entire $env if cell_path.tail.is_empty() { return Err(ShellError::CannotReplaceEnv { span: cell_path.head.span(&engine_state), }); } // Updating environment variables should be case-preserving, // so we need to figure out the original key before we do anything. let (key, span) = match &cell_path.tail[0] { PathMember::String { val, span, .. } => (val.to_string(), span), PathMember::Int { val, span, .. } => (val.to_string(), span), }; let original_key = if let Value::Record { val: record, .. } = &lhs { record .iter() .rev() .map(|(k, _)| k) .find(|x| x.eq_ignore_case(&key)) .cloned() .unwrap_or(key) } else { key }; // Retrieve the updated environment value. lhs.upsert_data_at_cell_path(&cell_path.tail, rhs)?; let value = lhs.follow_cell_path(&[{ let mut pm = cell_path.tail[0].clone(); pm.make_insensitive(); pm }])?; // Reject attempts to set automatic environment variables. if is_automatic_env_var(&original_key) { return Err(ShellError::AutomaticEnvVarSetManually { envvar_name: original_key, span: *span, }); } let is_config = original_key == "config"; stack.add_env_var(original_key, value.into_owned()); // Trigger the update to config, if we modified that. if is_config { stack.update_config(engine_state)?; } } else { lhs.upsert_data_at_cell_path(&cell_path.tail, rhs)?; stack.add_var(*var_id, lhs); } Ok(Value::nothing(cell_path.head.span(&engine_state))) } else { Err(ShellError::AssignmentRequiresMutableVar { lhs_span: lhs.span(&engine_state), }) } } _ => Err(ShellError::AssignmentRequiresVar { lhs_span: lhs.span(&engine_state), }), } } _ => Err(ShellError::AssignmentRequiresVar { lhs_span: lhs.span(&engine_state), }), } } fn eval_row_condition_or_closure( engine_state: &EngineState, stack: &mut Stack, block_id: BlockId, span: Span, ) -> Result<Value, ShellError> { let captures = engine_state .get_block(block_id) .captures .iter() .map(|(id, span)| { stack .get_var(*id, *span) .or_else(|_| { engine_state .get_var(*id) .const_val .clone() .ok_or(ShellError::VariableNotFoundAtRuntime { span: *span }) }) .map(|var| (*id, var)) }) .collect::<Result<_, _>>()?; Ok(Value::closure(Closure { block_id, captures }, span)) } fn eval_overlay(engine_state: &EngineState, span: Span) -> Result<Value, ShellError> { let name = String::from_utf8_lossy(engine_state.get_span_contents(span)).to_string(); Ok(Value::string(name, span)) } fn unreachable(engine_state: &EngineState, expr: &Expression) -> Result<Value, ShellError> { Ok(Value::nothing(expr.span(&engine_state))) } } /// Returns whether a string, when used as the name of an environment variable, /// is considered an automatic environment variable. /// /// An automatic environment variable cannot be assigned to by user code. /// Current there are three of them: $env.PWD, $env.FILE_PWD, $env.CURRENT_FILE pub(crate) fn is_automatic_env_var(var: &str) -> bool { let names = ["PWD", "FILE_PWD", "CURRENT_FILE"]; names.iter().any(|&name| { if cfg!(windows) { name.eq_ignore_case(var) } else { name.eq(var) } }) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/glob_from.rs
crates/nu-engine/src/glob_from.rs
use nu_glob::MatchOptions; use nu_path::{canonicalize_with, expand_path_with}; use nu_protocol::{NuGlob, ShellError, Signals, Span, Spanned, shell_error::io::IoError}; use std::{ fs, path::{Component, Path, PathBuf}, }; /// This function is like `nu_glob::glob` from the `glob` crate, except it is relative to a given cwd. /// /// It returns a tuple of two values: the first is an optional prefix that the expanded filenames share. /// This prefix can be removed from the front of each value to give an approximation of the relative path /// to the user /// /// The second of the two values is an iterator over the matching filepaths. #[allow(clippy::type_complexity)] pub fn glob_from( pattern: &Spanned<NuGlob>, cwd: &Path, span: Span, options: Option<MatchOptions>, signals: Signals, ) -> Result< ( Option<PathBuf>, Box<dyn Iterator<Item = Result<PathBuf, ShellError>> + Send>, ), ShellError, > { let no_glob_for_pattern = matches!(pattern.item, NuGlob::DoNotExpand(_)); let pattern_span = pattern.span; let (prefix, pattern) = if nu_glob::is_glob(pattern.item.as_ref()) { // Pattern contains glob, split it let mut p = PathBuf::new(); let path = PathBuf::from(&pattern.item.as_ref()); let components = path.components(); let mut counter = 0; for c in components { if let Component::Normal(os) = c && nu_glob::is_glob(os.to_string_lossy().as_ref()) { break; } p.push(c); counter += 1; } let mut just_pattern = PathBuf::new(); for c in counter..path.components().count() { if let Some(comp) = path.components().nth(c) { just_pattern.push(comp); } } if no_glob_for_pattern { just_pattern = PathBuf::from(nu_glob::Pattern::escape(&just_pattern.to_string_lossy())); } // Now expand `p` to get full prefix let path = expand_path_with(p, cwd, pattern.item.is_expand()); let escaped_prefix = PathBuf::from(nu_glob::Pattern::escape(&path.to_string_lossy())); (Some(path), escaped_prefix.join(just_pattern)) } else { let path = PathBuf::from(&pattern.item.as_ref()); let path = expand_path_with(path, cwd, pattern.item.is_expand()); let is_symlink = match fs::symlink_metadata(&path) { Ok(attr) => attr.file_type().is_symlink(), Err(_) => false, }; if is_symlink { (path.parent().map(|parent| parent.to_path_buf()), path) } else { let path = match canonicalize_with(path.clone(), cwd) { Ok(p) if nu_glob::is_glob(p.to_string_lossy().as_ref()) => { // our path might contain glob metacharacters too. // in such case, we need to escape our path to make // glob work successfully PathBuf::from(nu_glob::Pattern::escape(&p.to_string_lossy())) } Ok(p) => p, Err(err) => { return Err(IoError::new(err, pattern_span, path).into()); } }; (path.parent().map(|parent| parent.to_path_buf()), path) } }; let pattern = pattern.to_string_lossy().to_string(); let glob_options = options.unwrap_or_default(); let glob = nu_glob::glob_with(&pattern, glob_options, signals).map_err(|e| { nu_protocol::ShellError::GenericError { error: "Error extracting glob pattern".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], } })?; Ok(( prefix, Box::new(glob.map(move |x| match x { Ok(v) => Ok(v), Err(e) => Err(nu_protocol::ShellError::GenericError { error: "Error extracting glob pattern".into(), msg: e.to_string(), span: Some(span), help: None, inner: vec![], }), })), )) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/exit.rs
crates/nu-engine/src/exit.rs
use std::sync::atomic::Ordering; use nu_protocol::engine::EngineState; /// Exit the process or clean jobs if appropriate. /// /// Drops `tag` and exits the current process if there are no running jobs, or if `exit_warning_given` is true. /// When running in an interactive session, warns the user if there /// were jobs and sets `exit_warning_given` instead, returning `tag` itself in that case. /// // Currently, this `tag` argument exists mostly so that a LineEditor can be dropped before exiting the process. pub fn cleanup_exit<T>(tag: T, engine_state: &EngineState, exit_code: i32) -> T { let mut jobs = engine_state.jobs.lock().expect("failed to lock job table"); if engine_state.is_interactive && jobs.iter().next().is_some() && !engine_state.exit_warning_given.load(Ordering::SeqCst) { let job_count = jobs.iter().count(); println!("There are still background jobs running ({job_count})."); println!("Running `exit` a second time will kill all of them."); engine_state .exit_warning_given .store(true, Ordering::SeqCst); return tag; } let _ = jobs.kill_all(); drop(tag); std::process::exit(exit_code); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/compile/builder.rs
crates/nu-engine/src/compile/builder.rs
use nu_protocol::{ CompileError, IntoSpanned, RegId, Span, Spanned, ast::Pattern, ir::{DataSlice, Instruction, IrAstRef, IrBlock, Literal}, }; /// A label identifier. Only exists while building code. Replaced with the actual target. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct LabelId(pub usize); /// Builds [`IrBlock`]s progressively by consuming instructions and handles register allocation. #[derive(Debug)] pub(crate) struct BlockBuilder { pub(crate) block_span: Option<Span>, pub(crate) instructions: Vec<Instruction>, pub(crate) spans: Vec<Span>, /// The actual instruction index that a label refers to. While building IR, branch targets are /// specified as indices into this array rather than the true instruction index. This makes it /// easier to make modifications to code, as just this array needs to be changed, and it's also /// less error prone as during `finish()` we check to make sure all of the used labels have had /// an index actually set. pub(crate) labels: Vec<Option<usize>>, pub(crate) data: Vec<u8>, pub(crate) ast: Vec<Option<IrAstRef>>, pub(crate) comments: Vec<String>, pub(crate) register_allocation_state: Vec<bool>, pub(crate) file_count: u32, pub(crate) context_stack: ContextStack, } impl BlockBuilder { /// Starts a new block, with the first register (`%0`) allocated as input. pub(crate) fn new(block_span: Option<Span>) -> Self { BlockBuilder { block_span, instructions: vec![], spans: vec![], labels: vec![], data: vec![], ast: vec![], comments: vec![], register_allocation_state: vec![true], file_count: 0, context_stack: ContextStack::new(), } } /// Get the next unused register for code generation. pub(crate) fn next_register(&mut self) -> Result<RegId, CompileError> { if let Some(index) = self .register_allocation_state .iter_mut() .position(|is_allocated| { if !*is_allocated { *is_allocated = true; true } else { false } }) { Ok(RegId::new(index as u32)) } else if self.register_allocation_state.len() < (u32::MAX as usize - 2) { let reg_id = RegId::new(self.register_allocation_state.len() as u32); self.register_allocation_state.push(true); Ok(reg_id) } else { Err(CompileError::RegisterOverflow { block_span: self.block_span, }) } } /// Check if a register is initialized with a value. pub(crate) fn is_allocated(&self, reg_id: RegId) -> bool { self.register_allocation_state .get(reg_id.get() as usize) .is_some_and(|state| *state) } /// Mark a register as initialized. pub(crate) fn mark_register(&mut self, reg_id: RegId) -> Result<(), CompileError> { if let Some(is_allocated) = self .register_allocation_state .get_mut(reg_id.get() as usize) { *is_allocated = true; Ok(()) } else { Err(CompileError::RegisterOverflow { block_span: self.block_span, }) } } /// Mark a register as empty, so that it can be used again by something else. #[track_caller] pub(crate) fn free_register(&mut self, reg_id: RegId) -> Result<(), CompileError> { let index = reg_id.get() as usize; if self .register_allocation_state .get(index) .is_some_and(|is_allocated| *is_allocated) { self.register_allocation_state[index] = false; Ok(()) } else { log::warn!("register {reg_id} uninitialized, builder = {self:#?}"); Err(CompileError::RegisterUninitialized { reg_id, caller: std::panic::Location::caller().to_string(), }) } } /// Define a label, which can be used by branch instructions. The target can optionally be /// specified now. pub(crate) fn label(&mut self, target_index: Option<usize>) -> LabelId { let label_id = self.labels.len(); self.labels.push(target_index); LabelId(label_id) } /// Change the target of a label. pub(crate) fn set_label( &mut self, label_id: LabelId, target_index: usize, ) -> Result<(), CompileError> { *self .labels .get_mut(label_id.0) .ok_or(CompileError::UndefinedLabel { label_id: label_id.0, span: None, })? = Some(target_index); Ok(()) } /// Insert an instruction into the block, automatically marking any registers populated by /// the instruction, and freeing any registers consumed by the instruction. #[track_caller] pub(crate) fn push(&mut self, instruction: Spanned<Instruction>) -> Result<(), CompileError> { // Free read registers, and mark write registers. // // If a register is both read and written, it should be on both sides, so that we can verify // that the register was in the right state beforehand. let mut allocate = |read: &[RegId], write: &[RegId]| -> Result<(), CompileError> { for reg in read { self.free_register(*reg)?; } for reg in write { self.mark_register(*reg)?; } Ok(()) }; let allocate_result = match &instruction.item { Instruction::Unreachable => Ok(()), Instruction::LoadLiteral { dst, lit } => { allocate(&[], &[*dst]).and( // Free any registers on the literal match lit { Literal::Range { start, step, end, inclusion: _, } => allocate(&[*start, *step, *end], &[]), Literal::Bool(_) | Literal::Int(_) | Literal::Float(_) | Literal::Filesize(_) | Literal::Duration(_) | Literal::Binary(_) | Literal::Block(_) | Literal::Closure(_) | Literal::RowCondition(_) | Literal::List { capacity: _ } | Literal::Record { capacity: _ } | Literal::Filepath { val: _, no_expand: _, } | Literal::Directory { val: _, no_expand: _, } | Literal::GlobPattern { val: _, no_expand: _, } | Literal::String(_) | Literal::RawString(_) | Literal::CellPath(_) | Literal::Date(_) | Literal::Nothing => Ok(()), }, ) } Instruction::LoadValue { dst, val: _ } => allocate(&[], &[*dst]), Instruction::Move { dst, src } => allocate(&[*src], &[*dst]), Instruction::Clone { dst, src } => allocate(&[*src], &[*dst, *src]), Instruction::Collect { src_dst } => allocate(&[*src_dst], &[*src_dst]), Instruction::Span { src_dst } => allocate(&[*src_dst], &[*src_dst]), Instruction::Drop { src } => allocate(&[*src], &[]), Instruction::Drain { src } => allocate(&[*src], &[]), Instruction::DrainIfEnd { src } => allocate(&[*src], &[]), Instruction::LoadVariable { dst, var_id: _ } => allocate(&[], &[*dst]), Instruction::StoreVariable { var_id: _, src } => allocate(&[*src], &[]), Instruction::DropVariable { var_id: _ } => Ok(()), Instruction::LoadEnv { dst, key: _ } => allocate(&[], &[*dst]), Instruction::LoadEnvOpt { dst, key: _ } => allocate(&[], &[*dst]), Instruction::StoreEnv { key: _, src } => allocate(&[*src], &[]), Instruction::PushPositional { src } => allocate(&[*src], &[]), Instruction::AppendRest { src } => allocate(&[*src], &[]), Instruction::PushFlag { name: _ } => Ok(()), Instruction::PushShortFlag { short: _ } => Ok(()), Instruction::PushNamed { name: _, src } => allocate(&[*src], &[]), Instruction::PushShortNamed { short: _, src } => allocate(&[*src], &[]), Instruction::PushParserInfo { name: _, info: _ } => Ok(()), Instruction::RedirectOut { mode: _ } => Ok(()), Instruction::RedirectErr { mode: _ } => Ok(()), Instruction::CheckErrRedirected { src } => allocate(&[*src], &[*src]), Instruction::OpenFile { file_num: _, path, append: _, } => allocate(&[*path], &[]), Instruction::WriteFile { file_num: _, src } => allocate(&[*src], &[]), Instruction::CloseFile { file_num: _ } => Ok(()), Instruction::Call { decl_id: _, src_dst, } => allocate(&[*src_dst], &[*src_dst]), Instruction::StringAppend { src_dst, val } => allocate(&[*src_dst, *val], &[*src_dst]), Instruction::GlobFrom { src_dst, no_expand: _, } => allocate(&[*src_dst], &[*src_dst]), Instruction::ListPush { src_dst, item } => allocate(&[*src_dst, *item], &[*src_dst]), Instruction::ListSpread { src_dst, items } => { allocate(&[*src_dst, *items], &[*src_dst]) } Instruction::RecordInsert { src_dst, key, val } => { allocate(&[*src_dst, *key, *val], &[*src_dst]) } Instruction::RecordSpread { src_dst, items } => { allocate(&[*src_dst, *items], &[*src_dst]) } Instruction::Not { src_dst } => allocate(&[*src_dst], &[*src_dst]), Instruction::BinaryOp { lhs_dst, op: _, rhs, } => allocate(&[*lhs_dst, *rhs], &[*lhs_dst]), Instruction::FollowCellPath { src_dst, path } => { allocate(&[*src_dst, *path], &[*src_dst]) } Instruction::CloneCellPath { dst, src, path } => { allocate(&[*src, *path], &[*src, *dst]) } Instruction::UpsertCellPath { src_dst, path, new_value, } => allocate(&[*src_dst, *path, *new_value], &[*src_dst]), Instruction::Jump { index: _ } => Ok(()), Instruction::BranchIf { cond, index: _ } => allocate(&[*cond], &[]), Instruction::BranchIfEmpty { src, index: _ } => allocate(&[*src], &[*src]), Instruction::Match { pattern: _, src, index: _, } => allocate(&[*src], &[*src]), Instruction::CheckMatchGuard { src } => allocate(&[*src], &[*src]), Instruction::Iterate { dst, stream, end_index: _, } => allocate(&[*stream], &[*dst, *stream]), Instruction::OnError { index: _ } => Ok(()), Instruction::OnErrorInto { index: _, dst } => allocate(&[], &[*dst]), Instruction::PopErrorHandler => Ok(()), Instruction::ReturnEarly { src } => allocate(&[*src], &[]), Instruction::Return { src } => allocate(&[*src], &[]), }; // Add more context to the error match allocate_result { Ok(()) => (), Err(CompileError::RegisterUninitialized { reg_id, caller }) => { return Err(CompileError::RegisterUninitializedWhilePushingInstruction { reg_id, caller, instruction: format!("{:?}", instruction.item), span: instruction.span, }); } Err(err) => return Err(err), } self.instructions.push(instruction.item); self.spans.push(instruction.span); self.ast.push(None); self.comments.push(String::new()); Ok(()) } /// Set the AST of the last instruction. Separate method because it's rarely used. pub(crate) fn set_last_ast(&mut self, ast_ref: Option<IrAstRef>) { *self.ast.last_mut().expect("no last instruction") = ast_ref; } /// Add a comment to the last instruction. pub(crate) fn add_comment(&mut self, comment: impl std::fmt::Display) { add_comment( self.comments.last_mut().expect("no last instruction"), comment, ) } /// Load a register with a literal. pub(crate) fn load_literal( &mut self, reg_id: RegId, literal: Spanned<Literal>, ) -> Result<(), CompileError> { self.push( Instruction::LoadLiteral { dst: reg_id, lit: literal.item, } .into_spanned(literal.span), )?; Ok(()) } /// Allocate a new register and load a literal into it. pub(crate) fn literal(&mut self, literal: Spanned<Literal>) -> Result<RegId, CompileError> { let reg_id = self.next_register()?; self.load_literal(reg_id, literal)?; Ok(reg_id) } /// Deallocate a register and set it to `Empty`, if it is allocated pub(crate) fn drop_reg(&mut self, reg_id: RegId) -> Result<(), CompileError> { if self.is_allocated(reg_id) { // try using the block Span if available, since that's slightly more helpful than Span::unknown let span = self.block_span.unwrap_or(Span::unknown()); self.push(Instruction::Drop { src: reg_id }.into_spanned(span))?; } Ok(()) } /// Set a register to `Empty`, but mark it as in-use, e.g. for input pub(crate) fn load_empty(&mut self, reg_id: RegId) -> Result<(), CompileError> { self.drop_reg(reg_id)?; self.mark_register(reg_id) } /// Drain the stream in a register (fully consuming it) pub(crate) fn drain(&mut self, src: RegId, span: Span) -> Result<(), CompileError> { self.push(Instruction::Drain { src }.into_spanned(span)) } /// Add data to the `data` array and return a [`DataSlice`] referencing it. pub(crate) fn data(&mut self, data: impl AsRef<[u8]>) -> Result<DataSlice, CompileError> { let data = data.as_ref(); let start = self.data.len(); if data.is_empty() { Ok(DataSlice::empty()) } else if start + data.len() < u32::MAX as usize { let slice = DataSlice { start: start as u32, len: data.len() as u32, }; self.data.extend_from_slice(data); Ok(slice) } else { Err(CompileError::DataOverflow { block_span: self.block_span, }) } } /// Clone a register with a `clone` instruction. pub(crate) fn clone_reg(&mut self, src: RegId, span: Span) -> Result<RegId, CompileError> { let dst = self.next_register()?; self.push(Instruction::Clone { dst, src }.into_spanned(span))?; Ok(dst) } /// Add a `branch-if` instruction pub(crate) fn branch_if( &mut self, cond: RegId, label_id: LabelId, span: Span, ) -> Result<(), CompileError> { self.push( Instruction::BranchIf { cond, index: label_id.0, } .into_spanned(span), ) } /// Add a `branch-if-empty` instruction pub(crate) fn branch_if_empty( &mut self, src: RegId, label_id: LabelId, span: Span, ) -> Result<(), CompileError> { self.push( Instruction::BranchIfEmpty { src, index: label_id.0, } .into_spanned(span), ) } /// Add a `jump` instruction pub(crate) fn jump(&mut self, label_id: LabelId, span: Span) -> Result<(), CompileError> { self.push(Instruction::Jump { index: label_id.0 }.into_spanned(span)) } /// Add a `match` instruction pub(crate) fn r#match( &mut self, pattern: Pattern, src: RegId, label_id: LabelId, span: Span, ) -> Result<(), CompileError> { self.push( Instruction::Match { pattern: Box::new(pattern), src, index: label_id.0, } .into_spanned(span), ) } /// The index that the next instruction [`.push()`](Self::push)ed will have. pub(crate) fn here(&self) -> usize { self.instructions.len() } /// Allocate a new file number, for redirection. pub(crate) fn next_file_num(&mut self) -> Result<u32, CompileError> { let next = self.file_count; self.file_count = self .file_count .checked_add(1) .ok_or(CompileError::FileOverflow { block_span: self.block_span, })?; Ok(next) } /// Push a new loop state onto the builder. Creates new labels that must be set. pub(crate) fn begin_loop(&mut self) -> Loop { let loop_ = Loop { break_label: self.label(None), continue_label: self.label(None), }; self.context_stack.push_loop(loop_); loop_ } /// True if we are currently in a loop. pub(crate) fn is_in_loop(&self) -> bool { self.context_stack.is_in_loop() } /// Add a loop breaking jump instruction. pub(crate) fn push_break(&mut self, span: Span) -> Result<(), CompileError> { let loop_ = self .context_stack .current_loop() .ok_or_else(|| CompileError::NotInALoop { msg: "`break` called from outside of a loop".into(), span: Some(span), })?; self.jump(loop_.break_label, span) } /// Add a loop continuing jump instruction. pub(crate) fn push_continue(&mut self, span: Span) -> Result<(), CompileError> { let loop_ = self .context_stack .current_loop() .ok_or_else(|| CompileError::NotInALoop { msg: "`continue` called from outside of a loop".into(), span: Some(span), })?; self.jump(loop_.continue_label, span) } /// Pop the loop state. Checks that the loop being ended is the same one that was expected. pub(crate) fn end_loop(&mut self, loop_: Loop) -> Result<(), CompileError> { let context_block = self .context_stack .pop() .ok_or_else(|| CompileError::NotInALoop { msg: "end_loop() called outside of a loop".into(), span: None, })?; match context_block { ContextBlock::Loop(ended_loop) if ended_loop == loop_ => Ok(()), _ => Err(CompileError::IncoherentLoopState { block_span: self.block_span, }), } } /// Mark an unreachable code path. Produces an error at runtime if executed. #[allow(dead_code)] // currently unused, but might be used in the future. pub(crate) fn unreachable(&mut self, span: Span) -> Result<(), CompileError> { self.push(Instruction::Unreachable.into_spanned(span)) } /// Consume the builder and produce the final [`IrBlock`]. pub(crate) fn finish(mut self) -> Result<IrBlock, CompileError> { // Add comments to label targets for (index, label_target) in self.labels.iter().enumerate() { if let Some(label_target) = label_target { add_comment( &mut self.comments[*label_target], format_args!("label({index})"), ); } } // Populate the actual target indices of labels into the instructions for ((index, instruction), span) in self.instructions.iter_mut().enumerate().zip(&self.spans) { if let Some(label_id) = instruction.branch_target() { let target_index = self.labels.get(label_id).cloned().flatten().ok_or( CompileError::UndefinedLabel { label_id, span: Some(*span), }, )?; // Add a comment to the target index that we come from here add_comment( &mut self.comments[target_index], format_args!("from({index}:)"), ); instruction.set_branch_target(target_index).map_err(|_| { CompileError::SetBranchTargetOfNonBranchInstruction { instruction: format!("{instruction:?}"), span: *span, } })?; } } Ok(IrBlock { instructions: self.instructions, spans: self.spans, data: self.data.into(), ast: self.ast, comments: self.comments.into_iter().map(|s| s.into()).collect(), register_count: self .register_allocation_state .len() .try_into() .expect("register count overflowed in finish() despite previous checks"), file_count: self.file_count, }) } pub(crate) fn begin_try(&mut self) { self.context_stack.push_try(); } pub(crate) fn end_try(&mut self) -> Result<(), CompileError> { match self.context_stack.pop() { Some(ContextBlock::Try) => Ok(()), _ => Err(CompileError::NotInATry { msg: "end_try() called outside of a try block".into(), span: None, }), } } } /// Keeps track of the `break` and `continue` target labels for a loop. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct Loop { pub(crate) break_label: LabelId, pub(crate) continue_label: LabelId, } /// Blocks that modify/define behavior for the instructions they contain. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum ContextBlock { Loop(Loop), Try, } #[derive(Debug, Clone)] pub(crate) struct ContextStack(Vec<ContextBlock>); impl ContextStack { pub const fn new() -> Self { Self(Vec::new()) } pub fn push_loop(&mut self, r#loop: Loop) { self.0.push(ContextBlock::Loop(r#loop)); } pub fn push_try(&mut self) { self.0.push(ContextBlock::Try); } pub fn pop(&mut self) -> Option<ContextBlock> { self.0.pop() } pub fn current_loop(&self) -> Option<&Loop> { self.0.iter().rev().find_map(|cb| match cb { ContextBlock::Loop(r#loop) => Some(r#loop), _ => None, }) } pub fn try_block_depth_from_loop(&self) -> usize { self.0 .iter() .rev() .take_while(|&cb| matches!(cb, ContextBlock::Try)) .count() } pub fn is_in_loop(&self) -> bool { self.current_loop().is_some() } } /// Add a new comment to an existing one fn add_comment(comment: &mut String, new_comment: impl std::fmt::Display) { use std::fmt::Write; write!( comment, "{}{}", if comment.is_empty() { "" } else { ", " }, new_comment ) .expect("formatting failed"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/compile/call.rs
crates/nu-engine/src/compile/call.rs
use std::sync::Arc; use nu_protocol::{ IntoSpanned, RegId, Span, Spanned, ast::{Argument, Call, Expression, ExternalArgument}, engine::{ENV_VARIABLE_ID, IN_VARIABLE_ID, NU_VARIABLE_ID, StateWorkingSet}, ir::{Instruction, IrAstRef, Literal}, }; use super::{BlockBuilder, CompileError, RedirectModes, compile_expression, keyword::*}; pub(crate) fn compile_call( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { let decl = working_set.get_decl(call.decl_id); // Check if this call has --help - if so, just redirect to `help` if call.named_iter().any(|(name, _, _)| name.item == "help") { let name = working_set .find_decl_name(call.decl_id) // check for name in scope .and_then(|name| std::str::from_utf8(name).ok()) .unwrap_or(decl.name()); // fall back to decl's name return compile_help(working_set, builder, name.into_spanned(call.head), io_reg); } // Try to figure out if this is a keyword call like `if`, and handle those specially if decl.is_keyword() { match decl.name() { "if" => { return compile_if(working_set, builder, call, redirect_modes, io_reg); } "match" => { return compile_match(working_set, builder, call, redirect_modes, io_reg); } "const" | "export const" => { // This differs from the behavior of the const command, which adds the const value // to the stack. Since `load-variable` also checks `engine_state` for the variable // and will get a const value though, is it really necessary to do that? return builder.load_empty(io_reg); } "alias" | "export alias" => { // Alias does nothing return builder.load_empty(io_reg); } "let" | "mut" => { return compile_let(working_set, builder, call, redirect_modes, io_reg); } "try" => { return compile_try(working_set, builder, call, redirect_modes, io_reg); } "loop" => { return compile_loop(working_set, builder, call, redirect_modes, io_reg); } "while" => { return compile_while(working_set, builder, call, redirect_modes, io_reg); } "for" => { return compile_for(working_set, builder, call, redirect_modes, io_reg); } "break" => { return compile_break(working_set, builder, call, redirect_modes, io_reg); } "continue" => { return compile_continue(working_set, builder, call, redirect_modes, io_reg); } "return" => { return compile_return(working_set, builder, call, redirect_modes, io_reg); } "def" | "export def" => { return builder.load_empty(io_reg); } _ => (), } } // Special handling for builtin commands that have direct IR equivalents if decl.name() == "unlet" { return compile_unlet(working_set, builder, call, io_reg); } // Keep AST if the decl needs it. let requires_ast = decl.requires_ast_for_arguments(); // It's important that we evaluate the args first before trying to set up the argument // state for the call. // // We could technically compile anything that isn't another call safely without worrying about // the argument state, but we'd have to check all of that first and it just isn't really worth // it. enum CompiledArg<'a> { Positional(RegId, Span, Option<IrAstRef>), Named( &'a str, Option<&'a str>, Option<RegId>, Span, Option<IrAstRef>, ), Spread(RegId, Span, Option<IrAstRef>), } let mut compiled_args = vec![]; for arg in &call.arguments { let arg_reg = arg .expr() .map(|expr| { let arg_reg = builder.next_register()?; compile_expression( working_set, builder, expr, RedirectModes::value(arg.span()), None, arg_reg, )?; Ok(arg_reg) }) .transpose()?; let ast_ref = arg .expr() .filter(|_| requires_ast) .map(|expr| IrAstRef(Arc::new(expr.clone()))); match arg { Argument::Positional(_) | Argument::Unknown(_) => { compiled_args.push(CompiledArg::Positional( arg_reg.expect("expr() None in non-Named"), arg.span(), ast_ref, )) } Argument::Named((name, short, _)) => compiled_args.push(CompiledArg::Named( &name.item, short.as_ref().map(|spanned| spanned.item.as_str()), arg_reg, arg.span(), ast_ref, )), Argument::Spread(_) => compiled_args.push(CompiledArg::Spread( arg_reg.expect("expr() None in non-Named"), arg.span(), ast_ref, )), } } // Now that the args are all compiled, set up the call state (argument stack and redirections) for arg in compiled_args { match arg { CompiledArg::Positional(reg, span, ast_ref) => { builder.push(Instruction::PushPositional { src: reg }.into_spanned(span))?; builder.set_last_ast(ast_ref); } CompiledArg::Named(name, short, Some(reg), span, ast_ref) => { if !name.is_empty() { let name = builder.data(name)?; builder.push(Instruction::PushNamed { name, src: reg }.into_spanned(span))?; } else { let short = builder.data(short.unwrap_or(""))?; builder .push(Instruction::PushShortNamed { short, src: reg }.into_spanned(span))?; } builder.set_last_ast(ast_ref); } CompiledArg::Named(name, short, None, span, ast_ref) => { if !name.is_empty() { let name = builder.data(name)?; builder.push(Instruction::PushFlag { name }.into_spanned(span))?; } else { let short = builder.data(short.unwrap_or(""))?; builder.push(Instruction::PushShortFlag { short }.into_spanned(span))?; } builder.set_last_ast(ast_ref); } CompiledArg::Spread(reg, span, ast_ref) => { builder.push(Instruction::AppendRest { src: reg }.into_spanned(span))?; builder.set_last_ast(ast_ref); } } } // Add any parser info from the call for (name, info) in &call.parser_info { let name = builder.data(name)?; let info = Box::new(info.clone()); builder.push(Instruction::PushParserInfo { name, info }.into_spanned(call.head))?; } if let Some(mode) = redirect_modes.out { builder.push(mode.map(|mode| Instruction::RedirectOut { mode }))?; } if let Some(mode) = redirect_modes.err { builder.push(mode.map(|mode| Instruction::RedirectErr { mode }))?; } // The state is set up, so we can do the call into io_reg builder.push( Instruction::Call { decl_id: call.decl_id, src_dst: io_reg, } .into_spanned(call.head), )?; Ok(()) } pub(crate) fn compile_help( working_set: &StateWorkingSet<'_>, builder: &mut BlockBuilder, decl_name: Spanned<&str>, io_reg: RegId, ) -> Result<(), CompileError> { let help_command_id = working_set .find_decl(b"help") .ok_or_else(|| CompileError::MissingRequiredDeclaration { decl_name: "help".into(), span: decl_name.span, })?; let name_data = builder.data(decl_name.item)?; let name_literal = builder.literal(decl_name.map(|_| Literal::String(name_data)))?; builder.push(Instruction::PushPositional { src: name_literal }.into_spanned(decl_name.span))?; builder.push( Instruction::Call { decl_id: help_command_id, src_dst: io_reg, } .into_spanned(decl_name.span), )?; Ok(()) } pub(crate) fn compile_external_call( working_set: &StateWorkingSet, builder: &mut BlockBuilder, head: &Expression, args: &[ExternalArgument], redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pass everything to run-external let run_external_id = working_set .find_decl(b"run-external") .ok_or(CompileError::RunExternalNotFound { span: head.span })?; let mut call = Call::new(head.span); call.decl_id = run_external_id; call.arguments.push(Argument::Positional(head.clone())); for arg in args { match arg { ExternalArgument::Regular(expr) => { call.arguments.push(Argument::Positional(expr.clone())); } ExternalArgument::Spread(expr) => { call.arguments.push(Argument::Spread(expr.clone())); } } } compile_call(working_set, builder, &call, redirect_modes, io_reg) } pub(crate) fn compile_unlet( _working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, io_reg: RegId, ) -> Result<(), CompileError> { // unlet takes one or more positional arguments which should be variable references if call.positional_len() == 0 { return Err(CompileError::InvalidLiteral { msg: "unlet takes at least one argument".into(), span: call.head, }); } // Process each positional argument for i in 0..call.positional_len() { let Some(arg) = call.positional_nth(i) else { return Err(CompileError::InvalidLiteral { msg: "Expected positional argument".into(), span: call.head, }); }; // Extract variable ID from the expression // Handle both direct variable references (Expr::Var) and full cell paths (Expr::FullCellPath) // that represent simple variables (e.g., $var parsed as FullCellPath with empty tail). // This allows unlet to work with variables parsed in different contexts. let var_id = match &arg.expr { nu_protocol::ast::Expr::Var(var_id) => Some(*var_id), nu_protocol::ast::Expr::FullCellPath(cell_path) => { if cell_path.tail.is_empty() { match &cell_path.head.expr { nu_protocol::ast::Expr::Var(var_id) => Some(*var_id), _ => None, } } else { None } } _ => None, }; match var_id { Some(var_id) => { // Prevent deletion of built-in variables that are essential for nushell operation if var_id == NU_VARIABLE_ID || var_id == ENV_VARIABLE_ID || var_id == IN_VARIABLE_ID { // Determine the variable name for the error message let var_name = match var_id { NU_VARIABLE_ID => "nu", ENV_VARIABLE_ID => "env", IN_VARIABLE_ID => "in", _ => "unknown", // This should never happen due to the check above }; return Err(CompileError::InvalidLiteral { msg: format!( "'${}' is a built-in variable and cannot be deleted", var_name ), span: arg.span, }); } // Emit instruction to drop the variable builder.push(Instruction::DropVariable { var_id }.into_spanned(call.head))?; } None => { // Argument is not a valid variable reference return Err(CompileError::InvalidLiteral { msg: "Argument must be a variable reference like $x".into(), span: arg.span, }); } } } // Load empty value as the result builder.load_empty(io_reg)?; Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/compile/redirect.rs
crates/nu-engine/src/compile/redirect.rs
use nu_protocol::{ IntoSpanned, OutDest, RegId, Span, Spanned, ast::{Expression, RedirectionTarget}, engine::StateWorkingSet, ir::{Instruction, RedirectMode}, }; use super::{BlockBuilder, CompileError, compile_expression}; #[derive(Default, Clone)] pub(crate) struct RedirectModes { pub(crate) out: Option<Spanned<RedirectMode>>, pub(crate) err: Option<Spanned<RedirectMode>>, } impl RedirectModes { pub(crate) fn value(span: Span) -> Self { RedirectModes { out: Some(RedirectMode::Value.into_spanned(span)), err: None, } } pub(crate) fn caller(span: Span) -> RedirectModes { RedirectModes { out: Some(RedirectMode::Caller.into_spanned(span)), err: Some(RedirectMode::Caller.into_spanned(span)), } } } pub(crate) fn redirection_target_to_mode( working_set: &StateWorkingSet, builder: &mut BlockBuilder, target: &RedirectionTarget, ) -> Result<Spanned<RedirectMode>, CompileError> { Ok(match target { RedirectionTarget::File { expr, append, span: redir_span, } => { let file_num = builder.next_file_num()?; let path_reg = builder.next_register()?; compile_expression( working_set, builder, expr, RedirectModes::value(*redir_span), None, path_reg, )?; builder.push( Instruction::OpenFile { file_num, path: path_reg, append: *append, } .into_spanned(*redir_span), )?; RedirectMode::File { file_num }.into_spanned(*redir_span) } RedirectionTarget::Pipe { span } => RedirectMode::Pipe.into_spanned(*span), }) } pub(crate) fn redirect_modes_of_expression( working_set: &StateWorkingSet, expression: &Expression, redir_span: Span, ) -> Result<RedirectModes, CompileError> { let (out, err) = expression.expr.pipe_redirection(working_set); Ok(RedirectModes { out: out .map(|r| r.into_spanned(redir_span)) .map(out_dest_to_redirect_mode) .transpose()?, err: err .map(|r| r.into_spanned(redir_span)) .map(out_dest_to_redirect_mode) .transpose()?, }) } /// Finish the redirection for an expression, writing to and closing files as necessary pub(crate) fn finish_redirection( builder: &mut BlockBuilder, modes: RedirectModes, out_reg: RegId, ) -> Result<(), CompileError> { if let Some(Spanned { item: RedirectMode::File { file_num }, span, }) = modes.out { // If out is a file and err is a pipe, we must not consume the expression result - // that is actually the err, in that case. if !matches!( modes.err, Some(Spanned { item: RedirectMode::Pipe, .. }) ) { builder.push( Instruction::WriteFile { file_num, src: out_reg, } .into_spanned(span), )?; builder.load_empty(out_reg)?; } builder.push(Instruction::CloseFile { file_num }.into_spanned(span))?; } match modes.err { Some(Spanned { item: RedirectMode::File { file_num }, span, }) => { // Close the file, unless it's the same as out (in which case it was already closed) if !modes.out.is_some_and(|out_mode| match out_mode.item { RedirectMode::File { file_num: out_file_num, } => file_num == out_file_num, _ => false, }) { builder.push(Instruction::CloseFile { file_num }.into_spanned(span))?; } } Some(Spanned { item: RedirectMode::Pipe, span, }) => { builder.push(Instruction::CheckErrRedirected { src: out_reg }.into_spanned(span))?; } _ => (), } Ok(()) } pub(crate) fn out_dest_to_redirect_mode( out_dest: Spanned<OutDest>, ) -> Result<Spanned<RedirectMode>, CompileError> { let span = out_dest.span; out_dest .map(|out_dest| match out_dest { OutDest::Pipe => Ok(RedirectMode::Pipe), OutDest::PipeSeparate => Ok(RedirectMode::PipeSeparate), OutDest::Value => Ok(RedirectMode::Value), OutDest::Null => Ok(RedirectMode::Null), OutDest::Print => Ok(RedirectMode::Print), OutDest::Inherit => Err(CompileError::InvalidRedirectMode { span }), OutDest::File(_) => Err(CompileError::InvalidRedirectMode { span }), }) .transpose() }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/compile/keyword.rs
crates/nu-engine/src/compile/keyword.rs
use nu_protocol::{ IntoSpanned, RegId, Type, VarId, ast::{Block, Call, Expr, Expression}, engine::StateWorkingSet, ir::Instruction, }; use super::{BlockBuilder, CompileError, RedirectModes, compile_block, compile_expression}; /// Compile a call to `if` as a branch-if pub(crate) fn compile_if( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pseudocode: // // %io_reg <- <condition> // not %io_reg // branch-if %io_reg, FALSE // TRUE: ...<true_block>... // jump END // FALSE: ...<else_expr>... OR drop %io_reg // END: let invalid = || CompileError::InvalidKeywordCall { keyword: "if".into(), span: call.head, }; let condition = call.positional_nth(0).ok_or_else(invalid)?; let true_block_arg = call.positional_nth(1).ok_or_else(invalid)?; let else_arg = call.positional_nth(2); let true_block_id = true_block_arg.as_block().ok_or_else(invalid)?; let true_block = working_set.get_block(true_block_id); let true_label = builder.label(None); let false_label = builder.label(None); let end_label = builder.label(None); let not_condition_reg = { // Compile the condition first let condition_reg = builder.next_register()?; compile_expression( working_set, builder, condition, RedirectModes::value(condition.span), None, condition_reg, )?; // Negate the condition - we basically only want to jump if the condition is false builder.push( Instruction::Not { src_dst: condition_reg, } .into_spanned(call.head), )?; condition_reg }; // Set up a branch if the condition is false. builder.branch_if(not_condition_reg, false_label, call.head)?; builder.add_comment("if false"); // Compile the true case builder.set_label(true_label, builder.here())?; compile_block( working_set, builder, true_block, redirect_modes.clone(), Some(io_reg), io_reg, )?; // Add a jump over the false case builder.jump(end_label, else_arg.map(|e| e.span).unwrap_or(call.head))?; builder.add_comment("end if"); // On the else side now, assert that io_reg is still valid builder.set_label(false_label, builder.here())?; builder.mark_register(io_reg)?; if let Some(else_arg) = else_arg { let Expression { expr: Expr::Keyword(else_keyword), .. } = else_arg else { return Err(invalid()); }; if else_keyword.keyword.as_ref() != b"else" { return Err(invalid()); } let else_expr = &else_keyword.expr; match &else_expr.expr { Expr::Block(block_id) => { let false_block = working_set.get_block(*block_id); compile_block( working_set, builder, false_block, redirect_modes, Some(io_reg), io_reg, )?; } _ => { // The else case supports bare expressions too, not only blocks compile_expression( working_set, builder, else_expr, redirect_modes, Some(io_reg), io_reg, )?; } } } else { // We don't have an else expression/block, so just set io_reg = Empty builder.load_empty(io_reg)?; } // Set the end label builder.set_label(end_label, builder.here())?; Ok(()) } /// Compile a call to `match` pub(crate) fn compile_match( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pseudocode: // // %match_reg <- <match_expr> // collect %match_reg // match (pat1), %match_reg, PAT1 // MATCH2: match (pat2), %match_reg, PAT2 // FAIL: drop %io_reg // drop %match_reg // jump END // PAT1: %guard_reg <- <guard_expr> // check-match-guard %guard_reg // not %guard_reg // branch-if %guard_reg, MATCH2 // drop %match_reg // <...expr...> // jump END // PAT2: drop %match_reg // <...expr...> // jump END // END: let invalid = || CompileError::InvalidKeywordCall { keyword: "match".into(), span: call.head, }; let match_expr = call.positional_nth(0).ok_or_else(invalid)?; let match_block_arg = call.positional_nth(1).ok_or_else(invalid)?; let match_block = match_block_arg.as_match_block().ok_or_else(invalid)?; let match_reg = builder.next_register()?; // Evaluate the match expression (patterns will be checked against this). compile_expression( working_set, builder, match_expr, RedirectModes::value(match_expr.span), None, match_reg, )?; // Important to collect it first builder.push(Instruction::Collect { src_dst: match_reg }.into_spanned(match_expr.span))?; // Generate the `match` instructions. Guards are not used at this stage. let mut match_labels = Vec::with_capacity(match_block.len()); let mut next_labels = Vec::with_capacity(match_block.len()); let end_label = builder.label(None); for (pattern, _) in match_block { let match_label = builder.label(None); match_labels.push(match_label); builder.r#match( pattern.pattern.clone(), match_reg, match_label, pattern.span, )?; // Also add a label for the next match instruction or failure case next_labels.push(builder.label(Some(builder.here()))); } // Match fall-through to jump to the end, if no match builder.load_empty(io_reg)?; builder.drop_reg(match_reg)?; builder.jump(end_label, call.head)?; // Generate each of the match expressions. Handle guards here, if present. for (index, (pattern, expr)) in match_block.iter().enumerate() { let match_label = match_labels[index]; let next_label = next_labels[index]; // `io_reg` and `match_reg` are still valid at each of these branch targets builder.mark_register(io_reg)?; builder.mark_register(match_reg)?; // Set the original match instruction target here builder.set_label(match_label, builder.here())?; // Handle guard, if present if let Some(guard) = &pattern.guard { let guard_reg = builder.next_register()?; compile_expression( working_set, builder, guard, RedirectModes::value(guard.span), None, guard_reg, )?; builder .push(Instruction::CheckMatchGuard { src: guard_reg }.into_spanned(guard.span))?; builder.push(Instruction::Not { src_dst: guard_reg }.into_spanned(guard.span))?; // Branch to the next match instruction if the branch fails to match builder.branch_if( guard_reg, next_label, // Span the branch with the next pattern, or the head if this is the end match_block .get(index + 1) .map(|b| b.0.span) .unwrap_or(call.head), )?; builder.add_comment("if match guard false"); } // match_reg no longer needed, successful match builder.drop_reg(match_reg)?; // Execute match right hand side expression if let Expr::Block(block_id) = expr.expr { let block = working_set.get_block(block_id); compile_block( working_set, builder, block, redirect_modes.clone(), Some(io_reg), io_reg, )?; } else { compile_expression( working_set, builder, expr, redirect_modes.clone(), Some(io_reg), io_reg, )?; } // Jump to the end after the match logic is done builder.jump(end_label, call.head)?; builder.add_comment("end match"); } // Set the end destination builder.set_label(end_label, builder.here())?; Ok(()) } /// Compile a call to `let` or `mut` (just do store-variable) pub(crate) fn compile_let( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, _redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pseudocode: // // %io_reg <- ...<block>... <- %io_reg (if block provided) // store-variable $var, %io_reg let invalid = || CompileError::InvalidKeywordCall { keyword: "let".into(), span: call.head, }; let var_decl_arg = call.positional_nth(0).ok_or_else(invalid)?; let var_id = var_decl_arg.as_var().ok_or_else(invalid)?; // Handle the optional initial_value (expression after =) // Two cases: // 1. `let var = expr`: compile the expr block and store its result // 2. `let var` (at end of pipeline): use the pipeline input directly if let Some(block_arg) = call.positional_nth(1) { let block_id = block_arg.as_block().ok_or_else(invalid)?; let block = working_set.get_block(block_id); compile_block( working_set, builder, block, RedirectModes::value(call.head), Some(io_reg), io_reg, )?; } // If no initial_value provided, io_reg already contains the pipeline input to assign let variable = working_set.get_variable(var_id); // If the variable is a glob type variable, we should cast it with GlobFrom if variable.ty == Type::Glob { builder.push( Instruction::GlobFrom { src_dst: io_reg, no_expand: true, } .into_spanned(call.head), )?; } builder.push( Instruction::StoreVariable { var_id, src: io_reg, } .into_spanned(call.head), )?; builder.add_comment("let"); // Don't forget to set io_reg to Empty afterward, as that's the result of an assignment builder.load_empty(io_reg)?; Ok(()) } /// Compile a call to `try`, setting an error handler over the evaluated block pub(crate) fn compile_try( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pseudocode (literal block): // // on-error-into ERR, %io_reg // or without // %io_reg <- <...block...> <- %io_reg // write-to-out-dests %io_reg // pop-error-handler // jump END // ERR: clone %err_reg, %io_reg // store-variable $err_var, %err_reg // or without // %io_reg <- <...catch block...> <- %io_reg // set to empty if no catch block // END: // // with expression that can't be inlined: // // %closure_reg <- <catch_expr> // on-error-into ERR, %io_reg // %io_reg <- <...block...> <- %io_reg // write-to-out-dests %io_reg // pop-error-handler // jump END // ERR: clone %err_reg, %io_reg // push-positional %closure_reg // push-positional %err_reg // call "do", %io_reg // END: let invalid = || CompileError::InvalidKeywordCall { keyword: "try".into(), span: call.head, }; let block_arg = call.positional_nth(0).ok_or_else(invalid)?; let block_id = block_arg.as_block().ok_or_else(invalid)?; let block = working_set.get_block(block_id); let catch_expr = match call.positional_nth(1) { Some(kw_expr) => Some(kw_expr.as_keyword().ok_or_else(invalid)?), None => None, }; let catch_span = catch_expr.map(|e| e.span).unwrap_or(call.head); let err_label = builder.label(None); let end_label = builder.label(None); // We have two ways of executing `catch`: if it was provided as a literal, we can inline it. // Otherwise, we have to evaluate the expression and keep it as a register, and then call `do`. enum CatchType<'a> { Block { block: &'a Block, var_id: Option<VarId>, }, Closure { closure_reg: RegId, }, } let catch_type = catch_expr .map(|catch_expr| match catch_expr.as_block() { Some(block_id) => { let block = working_set.get_block(block_id); let var_id = block.signature.get_positional(0).and_then(|v| v.var_id); Ok(CatchType::Block { block, var_id }) } None => { // We have to compile the catch_expr and use it as a closure let closure_reg = builder.next_register()?; compile_expression( working_set, builder, catch_expr, RedirectModes::value(catch_expr.span), None, closure_reg, )?; Ok(CatchType::Closure { closure_reg }) } }) .transpose()?; // Put the error handler instruction. If we have a catch expression then we should capture the // error. if catch_type.is_some() { builder.push( Instruction::OnErrorInto { index: err_label.0, dst: io_reg, } .into_spanned(call.head), )? } else { // Otherwise, we don't need the error value. builder.push(Instruction::OnError { index: err_label.0 }.into_spanned(call.head))? }; builder.begin_try(); builder.add_comment("try"); // Compile the block compile_block( working_set, builder, block, redirect_modes.clone(), Some(io_reg), io_reg, )?; // Successful case: // - write to the current output destinations // - pop the error handler if let Some(mode) = redirect_modes.out { builder.push(mode.map(|mode| Instruction::RedirectOut { mode }))?; } if let Some(mode) = redirect_modes.err { builder.push(mode.map(|mode| Instruction::RedirectErr { mode }))?; } builder.push(Instruction::DrainIfEnd { src: io_reg }.into_spanned(call.head))?; builder.push(Instruction::PopErrorHandler.into_spanned(call.head))?; builder.end_try()?; // Jump over the failure case builder.jump(end_label, catch_span)?; // This is the error handler builder.set_label(err_label, builder.here())?; // Mark out register as likely not clean - state in error handler is not well defined builder.mark_register(io_reg)?; // Now compile whatever is necessary for the error handler match catch_type { Some(CatchType::Block { block, var_id }) => { // Error will be in io_reg builder.mark_register(io_reg)?; if let Some(var_id) = var_id { // Take a copy of the error as $err, since it will also be input let err_reg = builder.next_register()?; builder.push( Instruction::Clone { dst: err_reg, src: io_reg, } .into_spanned(catch_span), )?; builder.push( Instruction::StoreVariable { var_id, src: err_reg, } .into_spanned(catch_span), )?; } // Compile the block, now that the variable is set compile_block( working_set, builder, block, redirect_modes, Some(io_reg), io_reg, )?; } Some(CatchType::Closure { closure_reg }) => { // We should call `do`. Error will be in io_reg let do_decl_id = working_set.find_decl(b"do").ok_or_else(|| { CompileError::MissingRequiredDeclaration { decl_name: "do".into(), span: call.head, } })?; // Take a copy of io_reg, because we pass it both as an argument and input builder.mark_register(io_reg)?; let err_reg = builder.next_register()?; builder.push( Instruction::Clone { dst: err_reg, src: io_reg, } .into_spanned(catch_span), )?; // Push the closure and the error builder .push(Instruction::PushPositional { src: closure_reg }.into_spanned(catch_span))?; builder.push(Instruction::PushPositional { src: err_reg }.into_spanned(catch_span))?; // Call `$err | do $closure $err` builder.push( Instruction::Call { decl_id: do_decl_id, src_dst: io_reg, } .into_spanned(catch_span), )?; } None => { // Just set out to empty. builder.load_empty(io_reg)?; } } // This is the end - if we succeeded, should jump here builder.set_label(end_label, builder.here())?; Ok(()) } /// Compile a call to `loop` (via `jump`) pub(crate) fn compile_loop( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, _redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pseudocode: // // drop %io_reg // LOOP: %io_reg <- ...<block>... // drain %io_reg // jump %LOOP // END: drop %io_reg let invalid = || CompileError::InvalidKeywordCall { keyword: "loop".into(), span: call.head, }; let block_arg = call.positional_nth(0).ok_or_else(invalid)?; let block_id = block_arg.as_block().ok_or_else(invalid)?; let block = working_set.get_block(block_id); let loop_ = builder.begin_loop(); builder.load_empty(io_reg)?; builder.set_label(loop_.continue_label, builder.here())?; compile_block( working_set, builder, block, RedirectModes::default(), None, io_reg, )?; // Drain the output, just like for a semicolon builder.drain(io_reg, call.head)?; builder.jump(loop_.continue_label, call.head)?; builder.add_comment("loop"); builder.set_label(loop_.break_label, builder.here())?; builder.end_loop(loop_)?; // State of %io_reg is not necessarily well defined here due to control flow, so make sure it's // empty. builder.mark_register(io_reg)?; builder.load_empty(io_reg)?; Ok(()) } /// Compile a call to `while`, via branch instructions pub(crate) fn compile_while( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, _redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pseudocode: // // LOOP: %io_reg <- <condition> // branch-if %io_reg, TRUE // jump FALSE // TRUE: %io_reg <- ...<block>... // drain %io_reg // jump LOOP // FALSE: drop %io_reg let invalid = || CompileError::InvalidKeywordCall { keyword: "while".into(), span: call.head, }; let cond_arg = call.positional_nth(0).ok_or_else(invalid)?; let block_arg = call.positional_nth(1).ok_or_else(invalid)?; let block_id = block_arg.as_block().ok_or_else(invalid)?; let block = working_set.get_block(block_id); let loop_ = builder.begin_loop(); builder.set_label(loop_.continue_label, builder.here())?; let true_label = builder.label(None); compile_expression( working_set, builder, cond_arg, RedirectModes::value(call.head), None, io_reg, )?; builder.branch_if(io_reg, true_label, call.head)?; builder.add_comment("while"); builder.jump(loop_.break_label, call.head)?; builder.add_comment("end while"); builder.load_empty(io_reg)?; builder.set_label(true_label, builder.here())?; compile_block( working_set, builder, block, RedirectModes::default(), None, io_reg, )?; // Drain the result, just like for a semicolon builder.drain(io_reg, call.head)?; builder.jump(loop_.continue_label, call.head)?; builder.add_comment("while"); builder.set_label(loop_.break_label, builder.here())?; builder.end_loop(loop_)?; // State of %io_reg is not necessarily well defined here due to control flow, so make sure it's // empty. builder.mark_register(io_reg)?; builder.load_empty(io_reg)?; Ok(()) } /// Compile a call to `for` (via `iterate`) pub(crate) fn compile_for( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, _redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pseudocode: // // %stream_reg <- <in_expr> // LOOP: iterate %io_reg, %stream_reg, END // store-variable $var, %io_reg // %io_reg <- <...block...> // drain %io_reg // jump LOOP // END: drop %io_reg let invalid = || CompileError::InvalidKeywordCall { keyword: "for".into(), span: call.head, }; if call.get_named_arg("numbered").is_some() { // This is deprecated and we don't support it. return Err(invalid()); } let var_decl_arg = call.positional_nth(0).ok_or_else(invalid)?; let var_id = var_decl_arg.as_var().ok_or_else(invalid)?; let in_arg = call.positional_nth(1).ok_or_else(invalid)?; let in_expr = in_arg.as_keyword().ok_or_else(invalid)?; let block_arg = call.positional_nth(2).ok_or_else(invalid)?; let block_id = block_arg.as_block().ok_or_else(invalid)?; let block = working_set.get_block(block_id); // Ensure io_reg is marked so we don't use it builder.load_empty(io_reg)?; let stream_reg = builder.next_register()?; compile_expression( working_set, builder, in_expr, RedirectModes::caller(in_expr.span), None, stream_reg, )?; // Set up loop state let loop_ = builder.begin_loop(); builder.set_label(loop_.continue_label, builder.here())?; // This gets a value from the stream each time it's executed // io_reg basically will act as our scratch register here builder.push( Instruction::Iterate { dst: io_reg, stream: stream_reg, end_index: loop_.break_label.0, } .into_spanned(call.head), )?; builder.add_comment("for"); // Put the received value in the variable builder.push( Instruction::StoreVariable { var_id, src: io_reg, } .into_spanned(var_decl_arg.span), )?; builder.load_empty(io_reg)?; // Do the body of the block compile_block( working_set, builder, block, RedirectModes::default(), None, io_reg, )?; // Drain the output, just like for a semicolon builder.drain(io_reg, call.head)?; // Loop back to iterate to get the next value builder.jump(loop_.continue_label, call.head)?; // Set the end of the loop builder.set_label(loop_.break_label, builder.here())?; builder.end_loop(loop_)?; // We don't need stream_reg anymore, after the loop // io_reg may or may not be empty, so be sure it is builder.free_register(stream_reg)?; builder.mark_register(io_reg)?; builder.load_empty(io_reg)?; Ok(()) } /// Compile a call to `break`. pub(crate) fn compile_break( _working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, _redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { if !builder.is_in_loop() { return Err(CompileError::NotInALoop { msg: "'break' can only be used inside a loop".to_string(), span: Some(call.head), }); } builder.load_empty(io_reg)?; for _ in 0..builder.context_stack.try_block_depth_from_loop() { builder.push(Instruction::PopErrorHandler.into_spanned(call.head))?; } builder.push_break(call.head)?; builder.add_comment("break"); Ok(()) } /// Compile a call to `continue`. pub(crate) fn compile_continue( _working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, _redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { if !builder.is_in_loop() { return Err(CompileError::NotInALoop { msg: "'continue' can only be used inside a loop".to_string(), span: Some(call.head), }); } builder.load_empty(io_reg)?; for _ in 0..builder.context_stack.try_block_depth_from_loop() { builder.push(Instruction::PopErrorHandler.into_spanned(call.head))?; } builder.push_continue(call.head)?; builder.add_comment("continue"); Ok(()) } /// Compile a call to `return` as a `return-early` instruction. /// /// This is not strictly necessary, but it is more efficient. pub(crate) fn compile_return( working_set: &StateWorkingSet, builder: &mut BlockBuilder, call: &Call, _redirect_modes: RedirectModes, io_reg: RegId, ) -> Result<(), CompileError> { // Pseudocode: // // %io_reg <- <arg_expr> // return-early %io_reg if let Some(arg_expr) = call.positional_nth(0) { compile_expression( working_set, builder, arg_expr, RedirectModes::value(arg_expr.span), None, io_reg, )?; } else { builder.load_empty(io_reg)?; } // TODO: It would be nice if this could be `return` instead, but there is a little bit of // behaviour remaining that still depends on `ShellError::Return` builder.push(Instruction::ReturnEarly { src: io_reg }.into_spanned(call.head))?; // io_reg is supposed to remain allocated builder.load_empty(io_reg)?; Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/compile/expression.rs
crates/nu-engine/src/compile/expression.rs
use super::{ BlockBuilder, CompileError, RedirectModes, compile_binary_op, compile_block, compile_call, compile_external_call, compile_load_env, }; use nu_protocol::{ ENV_VARIABLE_ID, IntoSpanned, RegId, Span, Value, ast::{CellPath, Expr, Expression, ListItem, RecordItem, ValueWithUnit}, engine::StateWorkingSet, ir::{DataSlice, Instruction, Literal}, }; pub(crate) fn compile_expression( working_set: &StateWorkingSet, builder: &mut BlockBuilder, expr: &Expression, redirect_modes: RedirectModes, in_reg: Option<RegId>, out_reg: RegId, ) -> Result<(), CompileError> { let drop_input = |builder: &mut BlockBuilder| { if let Some(in_reg) = in_reg && in_reg != out_reg { builder.drop_reg(in_reg)?; } Ok(()) }; let lit = |builder: &mut BlockBuilder, literal: Literal| { drop_input(builder)?; builder .push( Instruction::LoadLiteral { dst: out_reg, lit: literal, } .into_spanned(expr.span), ) .map(|_| ()) }; let ignore = |builder: &mut BlockBuilder| { drop_input(builder)?; builder.load_empty(out_reg) }; let unexpected = |expr_name: &str| CompileError::UnexpectedExpression { expr_name: expr_name.into(), span: expr.span, }; let move_in_reg_to_out_reg = |builder: &mut BlockBuilder| { // Ensure that out_reg contains the input value, because a call only uses one register if let Some(in_reg) = in_reg { if in_reg != out_reg { // Have to move in_reg to out_reg so it can be used builder.push( Instruction::Move { dst: out_reg, src: in_reg, } .into_spanned(expr.span), )?; } } else { // Will have to initialize out_reg with Empty first builder.load_empty(out_reg)?; } Ok(()) }; match &expr.expr { Expr::AttributeBlock(ab) => compile_expression( working_set, builder, &ab.item, redirect_modes, in_reg, out_reg, ), Expr::Bool(b) => lit(builder, Literal::Bool(*b)), Expr::Int(i) => lit(builder, Literal::Int(*i)), Expr::Float(f) => lit(builder, Literal::Float(*f)), Expr::Binary(bin) => { let data_slice = builder.data(bin)?; lit(builder, Literal::Binary(data_slice)) } Expr::Range(range) => { // Compile the subexpressions of the range let compile_part = |builder: &mut BlockBuilder, part_expr: Option<&Expression>| -> Result<RegId, CompileError> { let reg = builder.next_register()?; if let Some(part_expr) = part_expr { compile_expression( working_set, builder, part_expr, RedirectModes::value(part_expr.span), None, reg, )?; } else { builder.load_literal(reg, Literal::Nothing.into_spanned(expr.span))?; } Ok(reg) }; drop_input(builder)?; let start = compile_part(builder, range.from.as_ref())?; let step = compile_part(builder, range.next.as_ref())?; let end = compile_part(builder, range.to.as_ref())?; // Assemble the range builder.load_literal( out_reg, Literal::Range { start, step, end, inclusion: range.operator.inclusion, } .into_spanned(expr.span), ) } Expr::Var(var_id) => { drop_input(builder)?; builder.push( Instruction::LoadVariable { dst: out_reg, var_id: *var_id, } .into_spanned(expr.span), )?; Ok(()) } Expr::VarDecl(_) => Err(unexpected("VarDecl")), Expr::Call(call) => { move_in_reg_to_out_reg(builder)?; compile_call(working_set, builder, call, redirect_modes, out_reg) } Expr::ExternalCall(head, args) => { move_in_reg_to_out_reg(builder)?; compile_external_call(working_set, builder, head, args, redirect_modes, out_reg) } Expr::Operator(_) => Err(unexpected("Operator")), Expr::RowCondition(block_id) => lit(builder, Literal::RowCondition(*block_id)), Expr::UnaryNot(subexpr) => { drop_input(builder)?; compile_expression( working_set, builder, subexpr, RedirectModes::value(subexpr.span), None, out_reg, )?; builder.push(Instruction::Not { src_dst: out_reg }.into_spanned(expr.span))?; Ok(()) } Expr::BinaryOp(lhs, op, rhs) => { if let Expr::Operator(operator) = op.expr { drop_input(builder)?; compile_binary_op( working_set, builder, lhs, operator.into_spanned(op.span), rhs, expr.span, out_reg, ) } else { Err(CompileError::UnsupportedOperatorExpression { span: op.span }) } } Expr::Collect(var_id, expr) => { let store_reg = if let Some(in_reg) = in_reg { // Collect, clone, store builder.push(Instruction::Collect { src_dst: in_reg }.into_spanned(expr.span))?; builder.clone_reg(in_reg, expr.span)? } else { // Just store nothing in the variable builder.literal(Literal::Nothing.into_spanned(Span::unknown()))? }; builder.push( Instruction::StoreVariable { var_id: *var_id, src: store_reg, } .into_spanned(expr.span), )?; compile_expression(working_set, builder, expr, redirect_modes, in_reg, out_reg)?; // Clean it up afterward builder.push(Instruction::DropVariable { var_id: *var_id }.into_spanned(expr.span))?; Ok(()) } Expr::Subexpression(block_id) => { let block = working_set.get_block(*block_id); compile_block(working_set, builder, block, redirect_modes, in_reg, out_reg) } Expr::Block(block_id) => lit(builder, Literal::Block(*block_id)), Expr::Closure(block_id) => lit(builder, Literal::Closure(*block_id)), Expr::MatchBlock(_) => Err(unexpected("MatchBlock")), // only for `match` keyword Expr::List(items) => { // Guess capacity based on items (does not consider spread as more than 1) lit( builder, Literal::List { capacity: items.len(), }, )?; for item in items { // Compile the expression of the item / spread let reg = builder.next_register()?; let expr = match item { ListItem::Item(expr) | ListItem::Spread(_, expr) => expr, }; compile_expression( working_set, builder, expr, RedirectModes::value(expr.span), None, reg, )?; match item { ListItem::Item(_) => { // Add each item using list-push builder.push( Instruction::ListPush { src_dst: out_reg, item: reg, } .into_spanned(expr.span), )?; } ListItem::Spread(spread_span, _) => { // Spread the list using list-spread builder.push( Instruction::ListSpread { src_dst: out_reg, items: reg, } .into_spanned(*spread_span), )?; } } } Ok(()) } Expr::Table(table) => { lit( builder, Literal::List { capacity: table.rows.len(), }, )?; // Evaluate the columns let column_registers = table .columns .iter() .map(|column| { let reg = builder.next_register()?; compile_expression( working_set, builder, column, RedirectModes::value(column.span), None, reg, )?; Ok(reg) }) .collect::<Result<Vec<RegId>, CompileError>>()?; // Build records for each row for row in table.rows.iter() { let row_reg = builder.next_register()?; builder.load_literal( row_reg, Literal::Record { capacity: table.columns.len(), } .into_spanned(expr.span), )?; for (column_reg, item) in column_registers.iter().zip(row.iter()) { let column_reg = builder.clone_reg(*column_reg, item.span)?; let item_reg = builder.next_register()?; compile_expression( working_set, builder, item, RedirectModes::value(item.span), None, item_reg, )?; builder.push( Instruction::RecordInsert { src_dst: row_reg, key: column_reg, val: item_reg, } .into_spanned(item.span), )?; } builder.push( Instruction::ListPush { src_dst: out_reg, item: row_reg, } .into_spanned(expr.span), )?; } // Free the column registers, since they aren't needed anymore for reg in column_registers { builder.drop_reg(reg)?; } Ok(()) } Expr::Record(items) => { lit( builder, Literal::Record { capacity: items.len(), }, )?; for item in items { match item { RecordItem::Pair(key, val) => { // Add each item using record-insert let key_reg = builder.next_register()?; let val_reg = builder.next_register()?; compile_expression( working_set, builder, key, RedirectModes::value(key.span), None, key_reg, )?; compile_expression( working_set, builder, val, RedirectModes::value(val.span), None, val_reg, )?; builder.push( Instruction::RecordInsert { src_dst: out_reg, key: key_reg, val: val_reg, } .into_spanned(expr.span), )?; } RecordItem::Spread(spread_span, expr) => { // Spread the expression using record-spread let reg = builder.next_register()?; compile_expression( working_set, builder, expr, RedirectModes::value(expr.span), None, reg, )?; builder.push( Instruction::RecordSpread { src_dst: out_reg, items: reg, } .into_spanned(*spread_span), )?; } } } Ok(()) } Expr::Keyword(kw) => { // keyword: just pass through expr, since commands that use it and are not being // specially handled already are often just positional anyway compile_expression( working_set, builder, &kw.expr, redirect_modes, in_reg, out_reg, ) } Expr::ValueWithUnit(value_with_unit) => { lit(builder, literal_from_value_with_unit(value_with_unit)?) } Expr::DateTime(dt) => lit(builder, Literal::Date(Box::new(*dt))), Expr::Filepath(path, no_expand) => { let val = builder.data(path)?; lit( builder, Literal::Filepath { val, no_expand: *no_expand, }, ) } Expr::Directory(path, no_expand) => { let val = builder.data(path)?; lit( builder, Literal::Directory { val, no_expand: *no_expand, }, ) } Expr::GlobPattern(path, no_expand) => { let val = builder.data(path)?; lit( builder, Literal::GlobPattern { val, no_expand: *no_expand, }, ) } Expr::String(s) => { let data_slice = builder.data(s)?; lit(builder, Literal::String(data_slice)) } Expr::RawString(rs) => { let data_slice = builder.data(rs)?; lit(builder, Literal::RawString(data_slice)) } Expr::CellPath(path) => lit(builder, Literal::CellPath(Box::new(path.clone()))), Expr::FullCellPath(full_cell_path) => { if matches!(full_cell_path.head.expr, Expr::Var(ENV_VARIABLE_ID)) { compile_load_env(builder, expr.span, &full_cell_path.tail, out_reg) } else { compile_expression( working_set, builder, &full_cell_path.head, // Only capture the output if there is a tail. This was a bit of a headscratcher // as the parser emits a FullCellPath with no tail for subexpressions in // general, which shouldn't be captured any differently than they otherwise // would be. if !full_cell_path.tail.is_empty() { RedirectModes::value(expr.span) } else { redirect_modes }, in_reg, out_reg, )?; // Only do the follow if this is actually needed if !full_cell_path.tail.is_empty() { let cell_path_reg = builder.literal( Literal::CellPath(Box::new(CellPath { members: full_cell_path.tail.clone(), })) .into_spanned(expr.span), )?; builder.push( Instruction::FollowCellPath { src_dst: out_reg, path: cell_path_reg, } .into_spanned(expr.span), )?; } Ok(()) } } Expr::ImportPattern(_) => Err(unexpected("ImportPattern")), Expr::Overlay(_) => Err(unexpected("Overlay")), Expr::Signature(_) => ignore(builder), // no effect Expr::StringInterpolation(exprs) | Expr::GlobInterpolation(exprs, _) => { let mut exprs_iter = exprs.iter().peekable(); if exprs_iter .peek() .is_some_and(|e| matches!(e.expr, Expr::String(..) | Expr::RawString(..))) { // If the first expression is a string or raw string literal, just take it and build // from that compile_expression( working_set, builder, exprs_iter.next().expect("peek() was Some"), RedirectModes::value(expr.span), None, out_reg, )?; } else { // Start with an empty string lit(builder, Literal::String(DataSlice::empty()))?; } // Compile each expression and append to out_reg for expr in exprs_iter { let scratch_reg = builder.next_register()?; compile_expression( working_set, builder, expr, RedirectModes::value(expr.span), None, scratch_reg, )?; builder.push( Instruction::StringAppend { src_dst: out_reg, val: scratch_reg, } .into_spanned(expr.span), )?; } // If it's a glob interpolation, change it to a glob if let Expr::GlobInterpolation(_, no_expand) = expr.expr { builder.push( Instruction::GlobFrom { src_dst: out_reg, no_expand, } .into_spanned(expr.span), )?; } Ok(()) } Expr::Nothing => lit(builder, Literal::Nothing), Expr::Garbage => Err(CompileError::Garbage { span: expr.span }), } } fn literal_from_value_with_unit(value_with_unit: &ValueWithUnit) -> Result<Literal, CompileError> { let Expr::Int(int_value) = value_with_unit.expr.expr else { return Err(CompileError::UnexpectedExpression { expr_name: format!("{:?}", value_with_unit.expr), span: value_with_unit.expr.span, }); }; match value_with_unit .unit .item .build_value(int_value, Span::unknown()) .map_err(|err| CompileError::InvalidLiteral { msg: err.to_string(), span: value_with_unit.expr.span, })? { Value::Filesize { val, .. } => Ok(Literal::Filesize(val)), Value::Duration { val, .. } => Ok(Literal::Duration(val)), other => Err(CompileError::InvalidLiteral { msg: format!("bad value returned by Unit::build_value(): {other:?}"), span: value_with_unit.unit.span, }), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/compile/operator.rs
crates/nu-engine/src/compile/operator.rs
use nu_protocol::{ ENV_VARIABLE_ID, IntoSpanned, RegId, Span, Spanned, Value, ast::{Assignment, Boolean, CellPath, Expr, Expression, Math, Operator, PathMember, Pattern}, engine::StateWorkingSet, ir::{Instruction, Literal}, }; use nu_utils::IgnoreCaseExt; use super::{BlockBuilder, CompileError, RedirectModes, compile_expression}; pub(crate) fn compile_binary_op( working_set: &StateWorkingSet, builder: &mut BlockBuilder, lhs: &Expression, op: Spanned<Operator>, rhs: &Expression, span: Span, out_reg: RegId, ) -> Result<(), CompileError> { if let Operator::Assignment(assign_op) = op.item { if let Some(decomposed_op) = decompose_assignment(assign_op) { // Compiling an assignment that uses a binary op with the existing value compile_binary_op( working_set, builder, lhs, decomposed_op.into_spanned(op.span), rhs, span, out_reg, )?; } else { // Compiling a plain assignment, where the current left-hand side value doesn't matter compile_expression( working_set, builder, rhs, RedirectModes::value(rhs.span), None, out_reg, )?; } compile_assignment(working_set, builder, lhs, op.span, out_reg)?; // Load out_reg with Nothing, as that's the result of an assignment builder.load_literal(out_reg, Literal::Nothing.into_spanned(op.span)) } else { // Not an assignment: just do the binary op let lhs_reg = out_reg; compile_expression( working_set, builder, lhs, RedirectModes::value(lhs.span), None, lhs_reg, )?; match op.item { // `and` / `or` are short-circuiting, use `match` to avoid running the RHS if LHS is // the correct value. Be careful to support and/or on non-boolean values Operator::Boolean(bool_op @ Boolean::And) | Operator::Boolean(bool_op @ Boolean::Or) => { // `and` short-circuits on false, and `or` short-circuits on true. let short_circuit_value = match bool_op { Boolean::And => false, Boolean::Or => true, Boolean::Xor => unreachable!(), }; // Before match against lhs_reg, it's important to collect it first to get a concrete value if there is a subexpression. builder.push(Instruction::Collect { src_dst: lhs_reg }.into_spanned(lhs.span))?; // Short-circuit to return `lhs_reg`. `match` op does not consume `lhs_reg`. let short_circuit_label = builder.label(None); builder.r#match( Pattern::Value(Value::bool(short_circuit_value, op.span)), lhs_reg, short_circuit_label, op.span, )?; // If the match failed then this was not the short-circuit value, so we have to run // the RHS expression let rhs_reg = builder.next_register()?; compile_expression( working_set, builder, rhs, RedirectModes::value(rhs.span), None, rhs_reg, )?; // It may seem intuitive that we can just return RHS here, but we do have to // actually execute the binary-op in case this is not a boolean builder.push( Instruction::BinaryOp { lhs_dst: lhs_reg, op: Operator::Boolean(bool_op), rhs: rhs_reg, } .into_spanned(op.span), )?; // In either the short-circuit case or other case, the result is in lhs_reg = // out_reg builder.set_label(short_circuit_label, builder.here())?; } _ => { // Any other operator, via `binary-op` let rhs_reg = builder.next_register()?; compile_expression( working_set, builder, rhs, RedirectModes::value(rhs.span), None, rhs_reg, )?; builder.push( Instruction::BinaryOp { lhs_dst: lhs_reg, op: op.item, rhs: rhs_reg, } .into_spanned(op.span), )?; } } if lhs_reg != out_reg { builder.push( Instruction::Move { dst: out_reg, src: lhs_reg, } .into_spanned(op.span), )?; } builder.push(Instruction::Span { src_dst: out_reg }.into_spanned(span))?; Ok(()) } } /// The equivalent plain operator to use for an assignment, if any pub(crate) fn decompose_assignment(assignment: Assignment) -> Option<Operator> { match assignment { Assignment::Assign => None, Assignment::AddAssign => Some(Operator::Math(Math::Add)), Assignment::SubtractAssign => Some(Operator::Math(Math::Subtract)), Assignment::MultiplyAssign => Some(Operator::Math(Math::Multiply)), Assignment::DivideAssign => Some(Operator::Math(Math::Divide)), Assignment::ConcatenateAssign => Some(Operator::Math(Math::Concatenate)), } } /// Compile assignment of the value in a register to a left-hand expression pub(crate) fn compile_assignment( working_set: &StateWorkingSet, builder: &mut BlockBuilder, lhs: &Expression, assignment_span: Span, rhs_reg: RegId, ) -> Result<(), CompileError> { match lhs.expr { Expr::Var(var_id) => { // Double check that the variable is supposed to be mutable if !working_set.get_variable(var_id).mutable { return Err(CompileError::AssignmentRequiresMutableVar { span: lhs.span }); } builder.push( Instruction::StoreVariable { var_id, src: rhs_reg, } .into_spanned(assignment_span), )?; Ok(()) } Expr::FullCellPath(ref path) => match (&path.head, &path.tail) { ( Expression { expr: Expr::Var(var_id), .. }, _, ) if *var_id == ENV_VARIABLE_ID => { // This will be an assignment to an environment variable. let Some(PathMember::String { val: key, .. }) = path.tail.first() else { return Err(CompileError::CannotReplaceEnv { span: lhs.span }); }; // Some env vars can't be set by Nushell code. const AUTOMATIC_NAMES: &[&str] = &["PWD", "FILE_PWD", "CURRENT_FILE"]; if AUTOMATIC_NAMES.iter().any(|name| key.eq_ignore_case(name)) { return Err(CompileError::AutomaticEnvVarSetManually { envvar_name: "PWD".into(), span: lhs.span, }); } let key_data = builder.data(key)?; let val_reg = if path.tail.len() > 1 { // Get the current value of the head and first tail of the path, from env let head_reg = builder.next_register()?; // We could use compile_load_env, but this shares the key data... // Always use optional, because it doesn't matter if it's already there builder.push( Instruction::LoadEnvOpt { dst: head_reg, key: key_data, } .into_spanned(lhs.span), )?; // Default to empty record so we can do further upserts let default_label = builder.label(None); let upsert_label = builder.label(None); builder.branch_if_empty(head_reg, default_label, assignment_span)?; builder.jump(upsert_label, assignment_span)?; builder.set_label(default_label, builder.here())?; builder.load_literal( head_reg, Literal::Record { capacity: 0 }.into_spanned(lhs.span), )?; // Do the upsert on the current value to incorporate rhs builder.set_label(upsert_label, builder.here())?; compile_upsert_cell_path( builder, (&path.tail[1..]).into_spanned(lhs.span), head_reg, rhs_reg, assignment_span, )?; head_reg } else { // Path has only one tail, so we don't need the current value to do an upsert, // just set it directly to rhs rhs_reg }; // Finally, store the modified env variable builder.push( Instruction::StoreEnv { key: key_data, src: val_reg, } .into_spanned(assignment_span), )?; Ok(()) } (_, tail) if tail.is_empty() => { // If the path tail is empty, we can really just treat this as if it were an // assignment to the head compile_assignment(working_set, builder, &path.head, assignment_span, rhs_reg) } _ => { // Just a normal assignment to some path let head_reg = builder.next_register()?; // Compile getting current value of the head expression compile_expression( working_set, builder, &path.head, RedirectModes::value(path.head.span), None, head_reg, )?; // Upsert the tail of the path into the old value of the head expression compile_upsert_cell_path( builder, path.tail.as_slice().into_spanned(lhs.span), head_reg, rhs_reg, assignment_span, )?; // Now compile the assignment of the updated value to the head compile_assignment(working_set, builder, &path.head, assignment_span, head_reg) } }, Expr::Garbage => Err(CompileError::Garbage { span: lhs.span }), _ => Err(CompileError::AssignmentRequiresVar { span: lhs.span }), } } /// Compile an upsert-cell-path instruction, with known literal members pub(crate) fn compile_upsert_cell_path( builder: &mut BlockBuilder, members: Spanned<&[PathMember]>, src_dst: RegId, new_value: RegId, span: Span, ) -> Result<(), CompileError> { let path_reg = builder.literal( Literal::CellPath( CellPath { members: members.item.to_vec(), } .into(), ) .into_spanned(members.span), )?; builder.push( Instruction::UpsertCellPath { src_dst, path: path_reg, new_value, } .into_spanned(span), )?; Ok(()) } /// Compile the correct sequence to get an environment variable + follow a path on it pub(crate) fn compile_load_env( builder: &mut BlockBuilder, span: Span, path: &[PathMember], out_reg: RegId, ) -> Result<(), CompileError> { match path { [] => builder.push( Instruction::LoadVariable { dst: out_reg, var_id: ENV_VARIABLE_ID, } .into_spanned(span), )?, [PathMember::Int { span, .. }, ..] => { return Err(CompileError::AccessEnvByInt { span: *span }); } [ PathMember::String { val: key, optional, .. }, tail @ .., ] => { let key = builder.data(key)?; builder.push(if *optional { Instruction::LoadEnvOpt { dst: out_reg, key }.into_spanned(span) } else { Instruction::LoadEnv { dst: out_reg, key }.into_spanned(span) })?; if !tail.is_empty() { let path = builder.literal( Literal::CellPath(Box::new(CellPath { members: tail.to_vec(), })) .into_spanned(span), )?; builder.push( Instruction::FollowCellPath { src_dst: out_reg, path, } .into_spanned(span), )?; } } } Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-engine/src/compile/mod.rs
crates/nu-engine/src/compile/mod.rs
use nu_protocol::{ CompileError, IntoSpanned, RegId, Span, ast::{Block, Expr, Pipeline, PipelineRedirection, RedirectionSource, RedirectionTarget}, engine::StateWorkingSet, ir::{Instruction, IrBlock, RedirectMode}, }; mod builder; mod call; mod expression; mod keyword; mod operator; mod redirect; use builder::BlockBuilder; use call::*; use expression::compile_expression; use operator::*; use redirect::*; const BLOCK_INPUT: RegId = RegId::new(0); /// Compile Nushell pipeline abstract syntax tree (AST) to internal representation (IR) instructions /// for evaluation. pub fn compile(working_set: &StateWorkingSet, block: &Block) -> Result<IrBlock, CompileError> { let mut builder = BlockBuilder::new(block.span); let span = block.span.unwrap_or(Span::unknown()); compile_block( working_set, &mut builder, block, RedirectModes::caller(span), Some(BLOCK_INPUT), BLOCK_INPUT, )?; // A complete block has to end with a `return` builder.push(Instruction::Return { src: BLOCK_INPUT }.into_spanned(span))?; builder.finish() } /// Compiles a [`Block`] in-place into an IR block. This can be used in a nested manner, for example /// by [`compile_if()`][keyword::compile_if], where the instructions for the blocks for the if/else /// are inlined into the top-level IR block. fn compile_block( working_set: &StateWorkingSet, builder: &mut BlockBuilder, block: &Block, redirect_modes: RedirectModes, in_reg: Option<RegId>, out_reg: RegId, ) -> Result<(), CompileError> { let span = block.span.unwrap_or(Span::unknown()); let mut redirect_modes = Some(redirect_modes); if !block.pipelines.is_empty() { let last_index = block.pipelines.len() - 1; for (index, pipeline) in block.pipelines.iter().enumerate() { compile_pipeline( working_set, builder, pipeline, span, // the redirect mode only applies to the last pipeline. if index == last_index { redirect_modes .take() .expect("should only take redirect_modes once") } else { RedirectModes::default() }, // input is only passed to the first pipeline. if index == 0 { in_reg } else { None }, out_reg, )?; if index != last_index { // Explicitly drain the out reg after each non-final pipeline, because that's how // the semicolon functions. if builder.is_allocated(out_reg) { builder.push(Instruction::Drain { src: out_reg }.into_spanned(span))?; } builder.load_empty(out_reg)?; } } Ok(()) } else if in_reg.is_none() { builder.load_empty(out_reg) } else { Ok(()) } } fn compile_pipeline( working_set: &StateWorkingSet, builder: &mut BlockBuilder, pipeline: &Pipeline, fallback_span: Span, redirect_modes: RedirectModes, in_reg: Option<RegId>, out_reg: RegId, ) -> Result<(), CompileError> { let mut iter = pipeline.elements.iter().peekable(); let mut in_reg = in_reg; let mut redirect_modes = Some(redirect_modes); while let Some(element) = iter.next() { let span = element.pipe.unwrap_or(fallback_span); // We have to get the redirection mode from either the explicit redirection in the pipeline // element, or from the next expression if it's specified there. If this is the last // element, then it's from whatever is passed in as the mode to use. let next_redirect_modes = if let Some(next_element) = iter.peek() { let mut modes = redirect_modes_of_expression(working_set, &next_element.expr, span)?; // If there's a next element with no inherent redirection we always pipe out *unless* // this is a single redirection of stderr to pipe (e>|) if modes.out.is_none() && !matches!( element.redirection, Some(PipelineRedirection::Single { source: RedirectionSource::Stderr, target: RedirectionTarget::Pipe { .. } }) ) { let pipe_span = next_element.pipe.unwrap_or(next_element.expr.span); modes.out = Some(RedirectMode::Pipe.into_spanned(pipe_span)); } modes } else { redirect_modes .take() .expect("should only take redirect_modes once") }; let spec_redirect_modes = match &element.redirection { Some(PipelineRedirection::Single { source, target }) => { let mode = redirection_target_to_mode(working_set, builder, target)?; match source { RedirectionSource::Stdout => RedirectModes { out: Some(mode), err: None, }, RedirectionSource::Stderr => RedirectModes { out: None, err: Some(mode), }, RedirectionSource::StdoutAndStderr => RedirectModes { out: Some(mode), err: Some(mode), }, } } Some(PipelineRedirection::Separate { out, err }) => { // In this case, out and err must not both be Pipe assert!( !matches!( (out, err), ( RedirectionTarget::Pipe { .. }, RedirectionTarget::Pipe { .. } ) ), "for Separate redirection, out and err targets must not both be Pipe" ); let out = redirection_target_to_mode(working_set, builder, out)?; let err = redirection_target_to_mode(working_set, builder, err)?; RedirectModes { out: Some(out), err: Some(err), } } None => RedirectModes { out: None, err: None, }, }; let redirect_modes = RedirectModes { out: spec_redirect_modes.out.or(next_redirect_modes.out), err: spec_redirect_modes.err.or(next_redirect_modes.err), }; compile_expression( working_set, builder, &element.expr, redirect_modes.clone(), in_reg, out_reg, )?; // Only clean up the redirection if current element is NOT // a nested eval expression, since this already cleans it. if !has_nested_eval_expr(&element.expr.expr) { // Clean up the redirection finish_redirection(builder, redirect_modes, out_reg)?; } // The next pipeline element takes input from this output in_reg = Some(out_reg); } Ok(()) } fn has_nested_eval_expr(expr: &Expr) -> bool { is_subexpression(expr) || is_block_call(expr) } fn is_block_call(expr: &Expr) -> bool { match expr { Expr::Call(inner) => inner .arguments .iter() .any(|arg| matches!(arg.expr().map(|e| &e.expr), Some(Expr::Block(..)))), _ => false, } } fn is_subexpression(expr: &Expr) -> bool { match expr { Expr::FullCellPath(inner) => { matches!(&inner.head.expr, &Expr::Subexpression(..)) } Expr::Subexpression(..) => true, _ => false, } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/lib.rs
crates/nu_plugin_example/src/lib.rs
use nu_plugin::{Plugin, PluginCommand}; mod commands; mod example; pub use commands::*; pub use example::ExamplePlugin; impl Plugin for ExamplePlugin { fn version(&self) -> String { env!("CARGO_PKG_VERSION").into() } fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { // This is a list of all of the commands you would like Nu to register when your plugin is // loaded. // // If it doesn't appear on this list, it won't be added. vec![ Box::new(Main), // Basic demos Box::new(One), Box::new(Two), Box::new(Three), // Engine interface demos Box::new(Config), Box::new(Env), Box::new(ViewSpan), Box::new(DisableGc), Box::new(Ctrlc), Box::new(CallDecl), // Stream demos Box::new(CollectBytes), Box::new(Echo), Box::new(ForEach), Box::new(Generate), Box::new(Seq), Box::new(Sum), // Auto completion demos Box::new(ArgCompletion), ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/example.rs
crates/nu_plugin_example/src/example.rs
use nu_plugin::EvaluatedCall; use nu_protocol::{LabeledError, Value}; pub struct ExamplePlugin; impl ExamplePlugin { pub fn print_values( &self, index: u32, call: &EvaluatedCall, input: &Value, ) -> Result<(), LabeledError> { // Note. When debugging your plugin, you may want to print something to the console // Use the eprintln macro to print your messages. Trying to print to stdout will // cause a decoding error for your message eprintln!("Calling test {index} signature"); eprintln!("value received {input:?}"); // To extract the arguments from the Call object you can use the functions req, has_flag, // opt, rest, and get_flag // // Note that plugin calls only accept simple arguments, this means that you can // pass to the plug in Int and String. This should be improved when the plugin has // the ability to call back to NuShell to extract more information // Keep this in mind when designing your plugin signatures let a: i64 = call.req(0)?; let b: String = call.req(1)?; let flag = call.has_flag("flag")?; let opt: Option<i64> = call.opt(2)?; let named: Option<String> = call.get_flag("named")?; let rest: Vec<String> = call.rest(3)?; eprintln!("Required values"); eprintln!("a: {a:}"); eprintln!("b: {b:}"); eprintln!("flag: {flag:}"); eprintln!("rest: {rest:?}"); if let Some(v) = opt { eprintln!("Found optional value opt: {v:}") } else { eprintln!("No optional value found") } if let Some(v) = named { eprintln!("Named value: {v:?}") } else { eprintln!("No named value found") } Ok(()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/main.rs
crates/nu_plugin_example/src/main.rs
use nu_plugin::{MsgPackSerializer, serve_plugin}; use nu_plugin_example::ExamplePlugin; fn main() { // When defining your plugin, you can select the Serializer that could be // used to encode and decode the messages. The available options are // MsgPackSerializer and JsonSerializer. Both are defined in the serializer // folder in nu-plugin. serve_plugin(&ExamplePlugin {}, MsgPackSerializer {}) // Note // When creating plugins in other languages one needs to consider how a plugin // is added and used in nushell. // The steps are: // - The plugin is register. In this stage nushell calls the binary file of // the plugin sending information using the encoded PluginCall::PluginSignature object. // Use this encoded data in your plugin to design the logic that will return // the encoded signatures. // Nushell is expecting and encoded PluginResponse::PluginSignature with all the // plugin signatures // - When calling the plugin, nushell sends to the binary file the encoded // PluginCall::CallInfo which has all the call information, such as the // values of the arguments, the name of the signature called and the input // from the pipeline. // Use this data to design your plugin login and to create the value that // will be sent to nushell // Nushell expects an encoded PluginResponse::Value from the plugin // - If an error needs to be sent back to nushell, one can encode PluginResponse::Error. // This is a labeled error that nushell can format for pretty printing }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/config.rs
crates/nu_plugin_example/src/commands/config.rs
use std::path::PathBuf; use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, FromValue, LabeledError, Signature, Spanned, Type, Value}; use crate::ExamplePlugin; pub struct Config; /// Example config struct. /// /// Using the `FromValue` derive macro, structs can be easily loaded from [`Value`]s, /// similar to serde's `Deserialize` macro. /// This is handy for plugin configs or piped data. /// All fields must implement [`FromValue`]. /// For [`Option`] fields, they can be omitted in the config. /// /// This example shows that nested and spanned data work too, so you can describe nested /// structures and get spans of values wrapped in [`Spanned`]. /// Since this config uses only `Option`s, no field is required in the config. #[allow(dead_code)] #[derive(Debug, FromValue)] struct PluginConfig { path: Option<Spanned<PathBuf>>, nested: Option<SubConfig>, } #[allow(dead_code)] #[derive(Debug, FromValue)] struct SubConfig { bool: bool, string: String, } impl SimplePluginCommand for Config { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example config" } fn description(&self) -> &str { "Show plugin configuration" } fn extra_description(&self) -> &str { "The configuration is set under $env.config.plugins.example" } fn signature(&self) -> Signature { Signature::build(self.name()) .category(Category::Experimental) .input_output_type(Type::Nothing, Type::table()) } fn search_terms(&self) -> Vec<&str> { vec!["example", "configuration"] } fn run( &self, _plugin: &ExamplePlugin, engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { let config = engine.get_plugin_config()?; match config { Some(value) => { let config = PluginConfig::from_value(value.clone())?; println!("got config {config:?}"); Ok(value) } None => Err(LabeledError::new("No config sent").with_label( "configuration for this plugin was not found in `$env.config.plugins.example`", call.head, )), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/view_span.rs
crates/nu_plugin_example/src/commands/view_span.rs
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, Example, LabeledError, Signature, Type, Value}; use crate::ExamplePlugin; /// `<value> | example view span` pub struct ViewSpan; impl SimplePluginCommand for ViewSpan { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example view span" } fn description(&self) -> &str { "Example command for looking up the contents of a parser span" } fn extra_description(&self) -> &str { "Shows the original source code of the expression that generated the value passed as input." } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Any, Type::String) .category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "('hello ' ++ 'world') | example view span", description: "Show the source code of the expression that generated a value", result: Some(Value::test_string("'hello ' ++ 'world'")), }] } fn run( &self, _plugin: &ExamplePlugin, engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { let contents = engine.get_span_contents(input.span())?; Ok(Value::string(String::from_utf8_lossy(&contents), call.head)) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("example", ExamplePlugin.into())?.test_command_examples(&ViewSpan) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/one.rs
crates/nu_plugin_example/src/commands/one.rs
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, Example, LabeledError, Signature, SyntaxShape, Value}; use crate::ExamplePlugin; pub struct One; impl SimplePluginCommand for One { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example one" } fn description(&self) -> &str { "Plugin test example 1. Returns Value::Nothing" } fn extra_description(&self) -> &str { "Extra description for example one" } fn signature(&self) -> Signature { // The signature defines the usage of the command inside Nu, and also automatically // generates its help page. Signature::build(self.name()) .required("a", SyntaxShape::Int, "required integer value") .required("b", SyntaxShape::String, "required string value") .switch("flag", "a flag for the signature", Some('f')) .optional("opt", SyntaxShape::Int, "Optional number") .named("named", SyntaxShape::String, "named string", Some('n')) .rest("rest", SyntaxShape::String, "rest value string") .category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "example one 3 bb", description: "running example with an int value and string value", result: None, }] } fn run( &self, plugin: &ExamplePlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { plugin.print_values(1, call, input)?; Ok(Value::nothing(call.head)) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("example", ExamplePlugin.into())?.test_command_examples(&One) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/for_each.rs
crates/nu_plugin_example/src/commands/for_each.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, SyntaxShape, Type}; use crate::ExamplePlugin; /// `<list> | example for-each { |value| ... }` pub struct ForEach; impl PluginCommand for ForEach { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example for-each" } fn description(&self) -> &str { "Example execution of a closure with a stream" } fn extra_description(&self) -> &str { "Prints each value the closure returns to stderr" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::list(Type::Any), Type::Nothing) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run for each input value", ) .category(Category::Experimental) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "ls | get name | example for-each { |f| ^file $f }", description: "example with an external command", result: None, }] } fn run( &self, _plugin: &ExamplePlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let closure = call.req(0)?; let config = engine.get_config()?; for value in input { let result = engine.eval_closure(&closure, vec![value.clone()], Some(value))?; eprintln!("{}", result.to_expanded_string(", ", &config)); } Ok(PipelineData::empty()) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("example", ExamplePlugin.into())?.test_command_examples(&ForEach) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/collect_bytes.rs
crates/nu_plugin_example/src/commands/collect_bytes.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ ByteStream, ByteStreamType, Category, Example, LabeledError, PipelineData, Signals, Signature, Type, Value, }; use crate::ExamplePlugin; /// `<list<string>> | example collect-bytes` pub struct CollectBytes; impl PluginCommand for CollectBytes { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example collect-bytes" } fn description(&self) -> &str { "Example transformer to byte stream" } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::List(Type::String.into()), Type::String), (Type::List(Type::Binary.into()), Type::Binary), ]) .category(Category::Experimental) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "[a b] | example collect-bytes", description: "collect strings into one stream", result: Some(Value::test_string("ab")), }] } fn run( &self, _plugin: &ExamplePlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { Ok(PipelineData::byte_stream( ByteStream::from_result_iter( input.into_iter().map(Value::coerce_into_binary), call.head, Signals::empty(), ByteStreamType::Unknown, ), None, )) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("example", ExamplePlugin.into())?.test_command_examples(&CollectBytes) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/disable_gc.rs
crates/nu_plugin_example/src/commands/disable_gc.rs
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, LabeledError, Signature, Value}; use crate::ExamplePlugin; pub struct DisableGc; impl SimplePluginCommand for DisableGc { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example disable-gc" } fn description(&self) -> &str { "Disable the plugin garbage collector for `example`" } fn extra_description(&self) -> &str { "\ Plugins are garbage collected by default after a period of inactivity. This behavior is configurable with `$env.config.plugin_gc.default`, or to change it specifically for the example plugin, use `$env.config.plugin_gc.plugins.example`. This command demonstrates how plugins can control this behavior and disable GC temporarily if they need to. It is still possible to stop the plugin explicitly using `plugin stop example`." } fn signature(&self) -> Signature { Signature::build(self.name()) .switch("reset", "Turn the garbage collector back on", None) .category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example", "gc", "plugin_gc", "garbage"] } fn run( &self, _plugin: &ExamplePlugin, engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { let disabled = !call.has_flag("reset")?; engine.set_gc_disabled(disabled)?; Ok(Value::string( format!( "The plugin garbage collector for `example` is now *{}*.", if disabled { "disabled" } else { "enabled" } ), call.head, )) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/three.rs
crates/nu_plugin_example/src/commands/three.rs
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, LabeledError, Signature, SyntaxShape, Value}; use crate::ExamplePlugin; pub struct Three; impl SimplePluginCommand for Three { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example three" } fn description(&self) -> &str { "Plugin test example 3. Returns labeled error" } fn signature(&self) -> Signature { // The signature defines the usage of the command inside Nu, and also automatically // generates its help page. Signature::build(self.name()) .required("a", SyntaxShape::Int, "required integer value") .required("b", SyntaxShape::String, "required string value") .switch("flag", "a flag for the signature", Some('f')) .optional("opt", SyntaxShape::Int, "Optional number") .named("named", SyntaxShape::String, "named string", Some('n')) .rest("rest", SyntaxShape::String, "rest value string") .category(Category::Experimental) } fn run( &self, plugin: &ExamplePlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { plugin.print_values(3, call, input)?; Err(LabeledError::new("ERROR from plugin") .with_label("error message pointing to call head span", call.head)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/env.rs
crates/nu_plugin_example/src/commands/env.rs
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, LabeledError, Signature, SyntaxShape, Type, Value}; use crate::ExamplePlugin; pub struct Env; impl SimplePluginCommand for Env { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example env" } fn description(&self) -> &str { "Get environment variable(s)" } fn extra_description(&self) -> &str { "Returns all environment variables if no name provided" } fn signature(&self) -> Signature { Signature::build(self.name()) .category(Category::Experimental) .optional( "name", SyntaxShape::String, "The name of the environment variable to get", ) .switch("cwd", "Get current working directory instead", None) .named( "set", SyntaxShape::Any, "Set an environment variable to the value", None, ) .input_output_type(Type::Nothing, Type::Any) } fn search_terms(&self) -> Vec<&str> { vec!["example", "env"] } fn run( &self, _plugin: &ExamplePlugin, engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { if call.has_flag("cwd")? { match call.get_flag_value("set") { None => { // Get working directory Ok(Value::string(engine.get_current_dir()?, call.head)) } Some(value) => Err(LabeledError::new("Invalid arguments") .with_label("--cwd can't be used with --set", value.span())), } } else if let Some(value) = call.get_flag_value("set") { // Set single env var let name = call.req::<String>(0)?; engine.add_env_var(name, value)?; Ok(Value::nothing(call.head)) } else if let Some(name) = call.opt::<String>(0)? { // Get single env var Ok(engine .get_env_var(name)? .unwrap_or(Value::nothing(call.head))) } else { // Get all env vars, converting the map to a record Ok(Value::record( engine.get_env_vars()?.into_iter().collect(), call.head, )) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/sum.rs
crates/nu_plugin_example/src/commands/sum.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, Span, Type, Value}; use crate::ExamplePlugin; /// `<list> | example sum` pub struct Sum; impl PluginCommand for Sum { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example sum" } fn description(&self) -> &str { "Example stream consumer for a list of values" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![ (Type::List(Type::Int.into()), Type::Int), (Type::List(Type::Float.into()), Type::Float), ]) .category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "example seq 1 5 | example sum", description: "sum values from 1 to 5", result: Some(Value::test_int(15)), }] } fn run( &self, _plugin: &ExamplePlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let mut acc = IntOrFloat::Int(0); for value in input { if let Ok(n) = value.as_int() { acc.add_i64(n); } else if let Ok(n) = value.as_float() { acc.add_f64(n); } else { return Err(LabeledError::new("Sum only accepts ints and floats") .with_label(format!("found {} in input", value.get_type()), value.span()) .with_label("can't be used here", call.head)); } } Ok(PipelineData::value(acc.to_value(call.head), None)) } } /// Accumulates numbers into either an int or a float. Changes type to float on the first /// float received. #[derive(Clone, Copy)] enum IntOrFloat { Int(i64), Float(f64), } impl IntOrFloat { pub(crate) fn add_i64(&mut self, n: i64) { match self { IntOrFloat::Int(v) => { *v += n; } IntOrFloat::Float(v) => { *v += n as f64; } } } pub(crate) fn add_f64(&mut self, n: f64) { match self { IntOrFloat::Int(v) => { *self = IntOrFloat::Float(*v as f64 + n); } IntOrFloat::Float(v) => { *v += n; } } } pub(crate) fn to_value(self, span: Span) -> Value { match self { IntOrFloat::Int(v) => Value::int(v, span), IntOrFloat::Float(v) => Value::float(v, span), } } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("example", ExamplePlugin.into())?.test_command_examples(&Sum) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/echo.rs
crates/nu_plugin_example/src/commands/echo.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, Example, LabeledError, PipelineData, Signature, Type, Value}; use crate::ExamplePlugin; /// `<list> | example echo` pub struct Echo; impl PluginCommand for Echo { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example echo" } fn description(&self) -> &str { "Example stream consumer that outputs the received input" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_types(vec![(Type::Any, Type::Any)]) .category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "example seq 1 5 | example echo", description: "echos the values from 1 to 5", result: Some(Value::test_list( (1..=5).map(Value::test_int).collect::<Vec<_>>(), )), }] } fn run( &self, _plugin: &ExamplePlugin, _engine: &EngineInterface, _call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { Ok(input) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("example", ExamplePlugin.into())?.test_command_examples(&Echo) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/mod.rs
crates/nu_plugin_example/src/commands/mod.rs
// `example` command - just suggests to call --help mod main; pub use main::Main; // Basic demos mod one; mod three; mod two; pub use one::One; pub use three::Three; pub use two::Two; // Engine interface demos mod call_decl; mod config; mod ctrlc; mod disable_gc; mod env; mod view_span; pub use call_decl::CallDecl; pub use config::Config; pub use ctrlc::Ctrlc; pub use disable_gc::DisableGc; pub use env::Env; pub use view_span::ViewSpan; // Stream demos mod collect_bytes; mod echo; mod for_each; mod generate; mod seq; mod sum; pub use collect_bytes::CollectBytes; pub use echo::Echo; pub use for_each::ForEach; pub use generate::Generate; pub use seq::Seq; pub use sum::Sum; // Flag auto completion demos mod arg_completion; pub use arg_completion::ArgCompletion;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/arg_completion.rs
crates/nu_plugin_example/src/commands/arg_completion.rs
use nu_plugin::{DynamicCompletionCall, EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, DynamicSuggestion, Example, LabeledError, PipelineData, Signature, Span, SyntaxShape, engine::ArgType, }; use std::time::{SystemTime, UNIX_EPOCH}; use crate::ExamplePlugin; /// `<list> | example sum` pub struct ArgCompletion; impl PluginCommand for ArgCompletion { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example arg-completion" } fn description(&self) -> &str { "It's a demo for arg completion, you can try to type `example arg-completion -f <tab>`to see what it returns" } fn signature(&self) -> Signature { Signature::build(self.name()) .optional("second", SyntaxShape::String, "optional second") .required("first", SyntaxShape::String, "required integer value") .named( "future-timestamp", SyntaxShape::Int, "example flag which support auto completion", Some('f'), ) .category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn examples(&self) -> Vec<Example<'_>> { vec![] } fn run( &self, _plugin: &ExamplePlugin, _engine: &EngineInterface, _call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { Ok(PipelineData::empty()) } #[expect(deprecated, reason = "internal usage")] fn get_dynamic_completion( &self, _plugin: &Self::Plugin, _engine: &EngineInterface, call: DynamicCompletionCall, arg_type: ArgType, _experimental: nu_protocol::engine::ExperimentalMarker, ) -> Option<Vec<DynamicSuggestion>> { match arg_type { ArgType::Flag(flag_name) => { // let's generate it dynamically. let start = SystemTime::now(); let since_the_epoch = start .duration_since(UNIX_EPOCH) .expect("time should go forward") .as_secs(); match flag_name.as_ref() { "future-timestamp" => Some( (since_the_epoch..since_the_epoch + 10) .map(|s| DynamicSuggestion { value: s.to_string(), ..Default::default() }) .collect(), ), _ => None, } } ArgType::Positional(index) => { // let's generate it dynamically too let start = SystemTime::now(); let since_the_epoch = start .duration_since(UNIX_EPOCH) .expect("time should go forward") .as_secs(); let head = call.call.span(); // be careful: Don't include any spaces for values. if index == 0 { // Just for fun :-) // assign span to head will replace the input buffer // to value `s`. // Try to play with `example arg-completion <tab>` then select // one item. Some( (since_the_epoch..since_the_epoch + 10) .map(|s| DynamicSuggestion { value: s.to_string(), span: Some(Span::new(head.start, head.end)), ..Default::default() }) .collect(), ) } else if index == 1 { Some( (since_the_epoch..since_the_epoch + 10) .map(|s| DynamicSuggestion { value: format!("arg1:{s}"), ..Default::default() }) .collect(), ) } else { None } } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/main.rs
crates/nu_plugin_example/src/commands/main.rs
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, LabeledError, Signature, Value}; use crate::ExamplePlugin; pub struct Main; impl SimplePluginCommand for Main { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example" } fn description(&self) -> &str { "Example commands for Nushell plugins" } fn extra_description(&self) -> &str { r#" The `example` plugin demonstrates usage of the Nushell plugin API. Several commands provided to test and demonstrate different capabilities of plugins exposed through the API. None of these commands are intended to be particularly useful. "# .trim() } fn signature(&self) -> Signature { Signature::build(self.name()).category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn run( &self, _plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { Ok(Value::string(engine.get_help()?, call.head)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/call_decl.rs
crates/nu_plugin_example/src/commands/call_decl.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ IntoSpanned, LabeledError, PipelineData, Record, Signature, Spanned, SyntaxShape, Value, }; use crate::ExamplePlugin; pub struct CallDecl; impl PluginCommand for CallDecl { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example call-decl" } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "name", SyntaxShape::String, "the name of the command to call", ) .optional( "named_args", SyntaxShape::Record(vec![]), "named arguments to pass to the command", ) .rest( "positional_args", SyntaxShape::Any, "positional arguments to pass to the command", ) } fn description(&self) -> &str { "Demonstrates calling other commands from plugins using `call_decl()`." } fn extra_description(&self) -> &str { " The arguments will not be typechecked at parse time. This command is for demonstration only, and should not be used for anything real. " .trim() } fn run( &self, _plugin: &ExamplePlugin, engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let name: Spanned<String> = call.req(0)?; let named_args: Option<Record> = call.opt(1)?; let positional_args: Vec<Value> = call.rest(2)?; let decl_id = engine.find_decl(&name.item)?.ok_or_else(|| { LabeledError::new(format!("Can't find `{}`", name.item)) .with_label("not in scope", name.span) })?; let mut new_call = EvaluatedCall::new(call.head); for (key, val) in named_args.into_iter().flatten() { new_call.add_named(key.into_spanned(val.span()), val); } for val in positional_args { new_call.add_positional(val); } let result = engine.call_decl(decl_id, new_call, input, true, false)?; Ok(result) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/seq.rs
crates/nu_plugin_example/src/commands/seq.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, LabeledError, ListStream, PipelineData, Signals, Signature, SyntaxShape, Type, Value, }; use crate::ExamplePlugin; /// `example seq <first> <last>` pub struct Seq; impl PluginCommand for Seq { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example seq" } fn description(&self) -> &str { "Example stream generator for a list of values" } fn signature(&self) -> Signature { Signature::build(self.name()) .required("first", SyntaxShape::Int, "first number to generate") .required("last", SyntaxShape::Int, "last number to generate") .input_output_type(Type::Nothing, Type::List(Type::Int.into())) .category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "example seq 1 3", description: "generate a sequence from 1 to 3", result: Some(Value::test_list(vec![ Value::test_int(1), Value::test_int(2), Value::test_int(3), ])), }] } fn run( &self, _plugin: &ExamplePlugin, _engine: &EngineInterface, call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { let head = call.head; let first: i64 = call.req(0)?; let last: i64 = call.req(1)?; let iter = (first..=last).map(move |number| Value::int(number, head)); Ok(ListStream::new(iter, head, Signals::empty()).into()) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("example", ExamplePlugin.into())?.test_command_examples(&Seq) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/ctrlc.rs
crates/nu_plugin_example/src/commands/ctrlc.rs
use std::sync::mpsc; use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{Category, LabeledError, PipelineData, Signature}; use crate::ExamplePlugin; /// `example ctrlc` pub struct Ctrlc; impl PluginCommand for Ctrlc { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example ctrlc" } fn description(&self) -> &str { "Example command that demonstrates registering an interrupt signal handler" } fn signature(&self) -> Signature { Signature::build(self.name()).category(Category::Experimental) } fn search_terms(&self) -> Vec<&str> { vec!["example"] } fn run( &self, _plugin: &ExamplePlugin, engine: &EngineInterface, _call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { let (sender, receiver) = mpsc::channel::<()>(); let _guard = engine.register_signal_handler(Box::new(move |_| { let _ = sender.send(()); })); eprintln!("interrupt status: {:?}", engine.signals().interrupted()); eprintln!("waiting for interrupt signal..."); receiver.recv().expect("handler went away"); eprintln!("interrupt status: {:?}", engine.signals().interrupted()); eprintln!("peace."); Ok(PipelineData::empty()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/two.rs
crates/nu_plugin_example/src/commands/two.rs
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, IntoValue, LabeledError, Signature, SyntaxShape, Value}; use crate::ExamplePlugin; pub struct Two; impl SimplePluginCommand for Two { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example two" } fn description(&self) -> &str { "Plugin test example 2. Returns list of records" } fn signature(&self) -> Signature { // The signature defines the usage of the command inside Nu, and also automatically // generates its help page. Signature::build(self.name()) .required("a", SyntaxShape::Int, "required integer value") .required("b", SyntaxShape::String, "required string value") .switch("flag", "a flag for the signature", Some('f')) .optional("opt", SyntaxShape::Int, "Optional number") .named("named", SyntaxShape::String, "named string", Some('n')) .rest("rest", SyntaxShape::String, "rest value string") .category(Category::Experimental) } fn run( &self, plugin: &ExamplePlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { plugin.print_values(2, call, input)?; // Use the IntoValue derive macro and trait to easily design output data. #[derive(IntoValue)] struct Output { one: i64, two: i64, three: i64, } let vals = (0..10i64) .map(|i| { Output { one: i, two: 2 * i, three: 3 * i, } .into_value(call.head) }) .collect(); Ok(Value::list(vals, call.head)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_example/src/commands/generate.rs
crates/nu_plugin_example/src/commands/generate.rs
use nu_plugin::{EngineInterface, EvaluatedCall, PluginCommand}; use nu_protocol::{ Category, Example, IntoInterruptiblePipelineData, LabeledError, PipelineData, Signals, Signature, SyntaxShape, Type, Value, }; use crate::ExamplePlugin; /// `example generate <initial> { |previous| {out: ..., next: ...} }` pub struct Generate; impl PluginCommand for Generate { type Plugin = ExamplePlugin; fn name(&self) -> &str { "example generate" } fn description(&self) -> &str { "Example execution of a closure to produce a stream" } fn extra_description(&self) -> &str { "See the builtin `generate` command" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Nothing, Type::list(Type::Any)) .required( "initial", SyntaxShape::Any, "The initial value to pass to the closure", ) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run to generate values", ) .category(Category::Experimental) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "example generate 0 { |i| if $i <= 10 { {out: $i, next: ($i + 2)} } }", description: "Generate a sequence of numbers", result: Some(Value::test_list( [0, 2, 4, 6, 8, 10] .into_iter() .map(Value::test_int) .collect(), )), }] } fn run( &self, _plugin: &ExamplePlugin, engine: &EngineInterface, call: &EvaluatedCall, _input: PipelineData, ) -> Result<PipelineData, LabeledError> { let head = call.head; let engine = engine.clone(); let initial: Value = call.req(0)?; let closure = call.req(1)?; let mut next = (!initial.is_nothing()).then_some(initial); Ok(std::iter::from_fn(move || { next.take() .and_then(|value| { engine .eval_closure(&closure, vec![value.clone()], Some(value)) .and_then(|record| { if record.is_nothing() { Ok(None) } else { let record = record.as_record()?; next = record.get("next").cloned(); Ok(record.get("out").cloned()) } }) .transpose() }) .map(|result| result.unwrap_or_else(|err| Value::error(err, head))) }) .into_pipeline_data(head, Signals::empty())) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_cmd_lang::If; use nu_plugin_test_support::PluginTest; PluginTest::new("example", ExamplePlugin.into())? .add_decl(Box::new(If))? .test_command_examples(&Generate) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/build.rs
crates/nu-cmd-lang/build.rs
use std::process::Command; fn main() { // Look up the current Git commit ourselves instead of relying on shadow_rs, // because shadow_rs does it in a really slow-to-compile way (it builds libgit2) // Allow overriding it with `NU_COMMIT_HASH` from outside, such as with nix. let hash = get_git_hash().unwrap_or( option_env!("NU_COMMIT_HASH") .unwrap_or_default() .to_string(), ); println!("cargo:rustc-env=NU_COMMIT_HASH={hash}"); shadow_rs::ShadowBuilder::builder() .build() .expect("shadow builder build should success"); } fn get_git_hash() -> Option<String> { Command::new("git") .args(["rev-parse", "HEAD"]) .output() .ok() .filter(|output| output.status.success()) .and_then(|output| String::from_utf8(output.stdout).ok()) .map(|hash| hash.trim().to_string()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/lib.rs
crates/nu-cmd-lang/src/lib.rs
#![cfg_attr(not(feature = "os"), allow(unused))] #![doc = include_str!("../README.md")] mod core_commands; mod default_context; pub mod example_support; mod example_test; #[cfg(test)] mod parse_const_test; pub use core_commands::*; pub use default_context::*; pub use example_support::*; #[cfg(test)] pub use example_test::test_examples;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/parse_const_test.rs
crates/nu-cmd-lang/src/parse_const_test.rs
use nu_protocol::{Span, engine::StateWorkingSet}; use quickcheck_macros::quickcheck; #[quickcheck] fn quickcheck_parse(data: String) -> bool { let (tokens, err) = nu_parser::lex(data.as_bytes(), 0, b"", b"", true); if err.is_none() { let context = crate::create_default_context(); { let mut working_set = StateWorkingSet::new(&context); let _ = working_set.add_file("quickcheck".into(), data.as_bytes()); let _ = nu_parser::parse_block(&mut working_set, &tokens, Span::new(0, 0), false, false); } } true }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/default_context.rs
crates/nu-cmd-lang/src/default_context.rs
use crate::*; use nu_protocol::engine::{EngineState, StateWorkingSet}; pub fn create_default_context() -> EngineState { let engine_state = EngineState::new(); add_default_context(engine_state) } pub fn add_default_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)); )* }; } // Core bind_command! { Alias, Attr, AttrCategory, AttrComplete, AttrCompleteExternal, AttrDeprecated, AttrExample, AttrSearchTerms, Break, Collect, Const, Continue, Def, Describe, Do, Echo, Error, ErrorMake, ExportAlias, ExportCommand, ExportConst, ExportDef, ExportExtern, ExportUse, ExportModule, Extern, For, Hide, HideEnv, If, Ignore, Overlay, OverlayUse, OverlayList, OverlayNew, OverlayHide, Let, Loop, Match, Module, Mut, Return, Scope, ScopeAliases, ScopeCommands, ScopeEngineStats, ScopeExterns, ScopeModules, ScopeVariables, Try, Use, Version, While, }; 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-lang/src/example_support.rs
crates/nu-cmd-lang/src/example_support.rs
use itertools::Itertools; use nu_engine::{command_prelude::*, compile}; use nu_protocol::{ Range, ast::Block, debugger::WithoutDebug, engine::StateWorkingSet, report_shell_error, }; use std::{ sync::Arc, {collections::HashSet, ops::Bound}, }; pub fn check_example_input_and_output_types_match_command_signature( example: &Example, cwd: &std::path::Path, engine_state: &mut Box<EngineState>, signature_input_output_types: &[(Type, Type)], signature_operates_on_cell_paths: bool, ) -> HashSet<(Type, Type)> { let mut witnessed_type_transformations = HashSet::<(Type, Type)>::new(); // Skip tests that don't have results to compare to if let Some(example_output) = example.result.as_ref() && let Some(example_input) = eval_pipeline_without_terminal_expression(example.example, cwd, engine_state) { let example_matches_signature = signature_input_output_types .iter() .any(|(sig_in_type, sig_out_type)| { example_input.is_subtype_of(sig_in_type) && example_output.is_subtype_of(sig_out_type) && { witnessed_type_transformations .insert((sig_in_type.clone(), sig_out_type.clone())); true } }); let example_input_type = example_input.get_type(); let example_output_type = example_output.get_type(); // The example type checks as a cell path operation if both: // 1. The command is declared to operate on cell paths. // 2. The example_input_type is list or record or table, and the example // output shape is the same as the input shape. let example_matches_signature_via_cell_path_operation = signature_operates_on_cell_paths && example_input_type.accepts_cell_paths() // TODO: This is too permissive; it should make use of the signature.input_output_types at least. && example_output_type.to_shape() == example_input_type.to_shape(); if !(example_matches_signature || example_matches_signature_via_cell_path_operation) { panic!( "The example `{}` demonstrates a transformation of type {:?} -> {:?}. \ However, this does not match the declared signature: {:?}.{} \ For this command `operates_on_cell_paths()` is {}.", example.example, example_input_type, example_output_type, signature_input_output_types, if signature_input_output_types.is_empty() { " (Did you forget to declare the input and output types for the command?)" } else { "" }, signature_operates_on_cell_paths ); }; }; witnessed_type_transformations } pub fn eval_pipeline_without_terminal_expression( src: &str, cwd: &std::path::Path, engine_state: &mut Box<EngineState>, ) -> Option<Value> { let (mut block, mut working_set) = parse(src, engine_state); if block.pipelines.len() == 1 { let n_expressions = block.pipelines[0].elements.len(); // Modify the block to remove the last element and recompile it { let mut_block = Arc::make_mut(&mut block); mut_block.pipelines[0].elements.truncate(n_expressions - 1); mut_block.ir_block = Some(compile(&working_set, mut_block).expect( "failed to compile block modified by eval_pipeline_without_terminal_expression", )); } working_set.add_block(block.clone()); engine_state .merge_delta(working_set.render()) .expect("failed to merge delta"); if !block.pipelines[0].elements.is_empty() { let empty_input = PipelineData::empty(); Some(eval_block(block, empty_input, cwd, engine_state)) } else { Some(Value::nothing(Span::test_data())) } } else { // E.g. multiple semicolon-separated statements None } } pub fn parse<'engine>( contents: &str, engine_state: &'engine EngineState, ) -> (Arc<Block>, StateWorkingSet<'engine>) { let mut working_set = StateWorkingSet::new(engine_state); let output = nu_parser::parse(&mut working_set, None, contents.as_bytes(), false); if let Some(err) = working_set.parse_errors.first() { panic!("test parse error in `{contents}`: {err:?}"); } if let Some(err) = working_set.compile_errors.first() { panic!("test compile error in `{contents}`: {err:?}"); } (output, working_set) } pub fn eval_block( block: Arc<Block>, input: PipelineData, cwd: &std::path::Path, engine_state: &EngineState, ) -> Value { let mut stack = Stack::new().collect_value(); stack.add_env_var("PWD".to_string(), Value::test_string(cwd.to_string_lossy())); nu_engine::eval_block::<WithoutDebug>(engine_state, &mut stack, &block, input) .map(|p| p.body) .and_then(|data| data.into_value(Span::test_data())) .unwrap_or_else(|err| { report_shell_error(None, engine_state, &err); panic!("test eval error in `{}`: {:?}", "TODO", err) }) } pub fn check_example_evaluates_to_expected_output( cmd_name: &str, example: &Example, cwd: &std::path::Path, engine_state: &mut Box<EngineState>, ) { let mut stack = Stack::new().collect_value(); // Set up PWD stack.add_env_var("PWD".to_string(), Value::test_string(cwd.to_string_lossy())); engine_state .merge_env(&mut stack) .expect("Error merging environment"); let empty_input = PipelineData::empty(); let result = eval(example.example, empty_input, cwd, engine_state); // Note. Value implements PartialEq for Bool, Int, Float, String and Block // If the command you are testing requires to compare another case, then // you need to define its equality in the Value struct if let Some(expected) = example.result.as_ref() { let expected = DebuggableValue(expected); let result = DebuggableValue(&result); assert_eq!( result, expected, "Error: The result of example '{}' for the command '{}' differs from the expected value.\n\nExpected: {:?}\nActual: {:?}\n", example.description, cmd_name, expected, result, ); } } pub fn check_all_signature_input_output_types_entries_have_examples( signature: Signature, witnessed_type_transformations: HashSet<(Type, Type)>, ) { let declared_type_transformations = HashSet::from_iter(signature.input_output_types); assert!( witnessed_type_transformations.is_subset(&declared_type_transformations), "This should not be possible (bug in test): the type transformations \ collected in the course of matching examples to the signature type map \ contain type transformations not present in the signature type map." ); if !signature.allow_variants_without_examples { assert_eq!( witnessed_type_transformations, declared_type_transformations, "There are entries in the signature type map which do not correspond to any example: \ {:?}", declared_type_transformations .difference(&witnessed_type_transformations) .map(|(s1, s2)| format!("{s1} -> {s2}")) .join(", ") ); } } fn eval( contents: &str, input: PipelineData, cwd: &std::path::Path, engine_state: &mut Box<EngineState>, ) -> Value { let (block, working_set) = parse(contents, engine_state); engine_state .merge_delta(working_set.render()) .expect("failed to merge delta"); eval_block(block, input, cwd, engine_state) } pub struct DebuggableValue<'a>(pub &'a Value); impl PartialEq for DebuggableValue<'_> { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl std::fmt::Debug for DebuggableValue<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self.0 { Value::Bool { val, .. } => { write!(f, "{val:?}") } Value::Int { val, .. } => { write!(f, "{val:?}") } Value::Float { val, .. } => { write!(f, "{val:?}f") } Value::Filesize { val, .. } => { write!(f, "Filesize({val:?})") } Value::Duration { val, .. } => { let duration = std::time::Duration::from_nanos(*val as u64); write!(f, "Duration({duration:?})") } Value::Date { val, .. } => { write!(f, "Date({val:?})") } Value::Range { val, .. } => match **val { Range::IntRange(range) => match range.end() { Bound::Included(end) => write!( f, "Range({:?}..{:?}, step: {:?})", range.start(), end, range.step(), ), Bound::Excluded(end) => write!( f, "Range({:?}..<{:?}, step: {:?})", range.start(), end, range.step(), ), Bound::Unbounded => { write!(f, "Range({:?}.., step: {:?})", range.start(), range.step()) } }, Range::FloatRange(range) => match range.end() { Bound::Included(end) => write!( f, "Range({:?}..{:?}, step: {:?})", range.start(), end, range.step(), ), Bound::Excluded(end) => write!( f, "Range({:?}..<{:?}, step: {:?})", range.start(), end, range.step(), ), Bound::Unbounded => { write!(f, "Range({:?}.., step: {:?})", range.start(), range.step()) } }, }, Value::String { val, .. } | Value::Glob { val, .. } => { write!(f, "{val:?}") } Value::Record { val, .. } => { write!(f, "{{")?; let mut first = true; for (col, value) in (&**val).into_iter() { if !first { write!(f, ", ")?; } first = false; write!(f, "{:?}: {:?}", col, DebuggableValue(value))?; } write!(f, "}}") } Value::List { vals, .. } => { write!(f, "[")?; for (i, value) in vals.iter().enumerate() { if i > 0 { write!(f, ", ")?; } write!(f, "{:?}", DebuggableValue(value))?; } write!(f, "]") } Value::Closure { val, .. } => { write!(f, "Closure({val:?})") } Value::Nothing { .. } => { write!(f, "Nothing") } Value::Error { error, .. } => { write!(f, "Error({error:?})") } Value::Binary { val, .. } => { write!(f, "Binary({val:?})") } Value::CellPath { val, .. } => { write!(f, "CellPath({:?})", val.to_string()) } Value::Custom { val, .. } => { write!(f, "CustomValue({val:?})") } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/example_test.rs
crates/nu-cmd-lang/src/example_test.rs
#[cfg(test)] use nu_protocol::engine::Command; #[cfg(test)] pub fn test_examples(cmd: impl Command + 'static) { test_examples::test_examples(cmd); } #[cfg(test)] mod test_examples { use crate::example_support::{ check_all_signature_input_output_types_entries_have_examples, check_example_evaluates_to_expected_output, check_example_input_and_output_types_match_command_signature, }; use crate::{ Break, Collect, Def, Describe, Echo, ExportCommand, ExportDef, If, Let, Module, Mut, Use, }; use nu_protocol::{ Type, Value, engine::{Command, EngineState, StateWorkingSet}, }; use std::collections::HashSet; pub fn test_examples(cmd: impl Command + 'static) { let examples = cmd.examples(); let signature = cmd.signature(); let mut engine_state = make_engine_state(cmd.clone_box()); let cwd = std::env::current_dir().expect("Could not get current working directory."); let mut witnessed_type_transformations = HashSet::<(Type, Type)>::new(); for example in examples { if example.result.is_none() { continue; } witnessed_type_transformations.extend( check_example_input_and_output_types_match_command_signature( &example, &cwd, &mut make_engine_state(cmd.clone_box()), &signature.input_output_types, signature.operates_on_cell_paths(), ), ); check_example_evaluates_to_expected_output( cmd.name(), &example, cwd.as_path(), &mut engine_state, ); } check_all_signature_input_output_types_entries_have_examples( signature, witnessed_type_transformations, ); } fn make_engine_state(cmd: Box<dyn Command>) -> Box<EngineState> { let mut engine_state = Box::new(EngineState::new()); let cwd = std::env::current_dir() .expect("Could not get current working directory.") .to_string_lossy() .to_string(); engine_state.add_env_var("PWD".to_string(), Value::test_string(cwd)); let delta = { // Base functions that are needed for testing // Try to keep this working set small to keep tests running as fast as possible let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Break)); working_set.add_decl(Box::new(Collect)); working_set.add_decl(Box::new(Def)); working_set.add_decl(Box::new(Describe)); working_set.add_decl(Box::new(Echo)); working_set.add_decl(Box::new(ExportCommand)); working_set.add_decl(Box::new(ExportDef)); working_set.add_decl(Box::new(If)); working_set.add_decl(Box::new(Let)); working_set.add_decl(Box::new(Module)); working_set.add_decl(Box::new(Mut)); working_set.add_decl(Box::new(Use)); // Adding the command that is being tested to the working set working_set.add_decl(cmd); working_set.render() }; engine_state.add_env_var("PWD".to_string(), Value::test_string(".")); engine_state .merge_delta(delta) .expect("Error merging delta"); engine_state } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/ignore.rs
crates/nu-cmd-lang/src/core_commands/ignore.rs
use nu_engine::command_prelude::*; use nu_protocol::{ByteStreamSource, OutDest, engine::StateWorkingSet}; #[derive(Clone)] pub struct Ignore; impl Command for Ignore { fn name(&self) -> &str { "ignore" } fn description(&self) -> &str { "Ignore the output of the previous command in the pipeline." } fn signature(&self) -> nu_protocol::Signature { Signature::build("ignore") .input_output_types(vec![(Type::Any, Type::Nothing)]) .category(Category::Core) } fn search_terms(&self) -> Vec<&str> { vec!["silent", "quiet", "out-null"] } fn is_const(&self) -> bool { true } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, mut input: PipelineData, ) -> Result<PipelineData, ShellError> { if let PipelineData::ByteStream(stream, _) = &mut input { #[cfg(feature = "os")] if let ByteStreamSource::Child(child) = stream.source_mut() { child.ignore_error(true); } } input.drain()?; Ok(PipelineData::empty()) } fn run_const( &self, _working_set: &StateWorkingSet, _call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { input.drain()?; Ok(PipelineData::empty()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Ignore the output of an echo command", example: "echo done | ignore", result: Some(Value::nothing(Span::test_data())), }] } fn pipe_redirection(&self) -> (Option<OutDest>, Option<OutDest>) { (Some(OutDest::Null), None) } } #[cfg(test)] mod test { #[test] fn test_examples() { use super::Ignore; use crate::test_examples; test_examples(Ignore {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/break_.rs
crates/nu-cmd-lang/src/core_commands/break_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Break; impl Command for Break { fn name(&self) -> &str { "break" } fn description(&self) -> &str { "Break a loop." } fn signature(&self) -> nu_protocol::Signature { Signature::build("break") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html break can only be used in while, loop, and for loops. It can not be used with each or other filter commands"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // This is compiled specially by the IR compiler. The code here is never used when // running in IR mode. eprintln!( "Tried to execute 'run' for the 'break' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Break out of a loop", example: r#"loop { break }"#, result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/if_.rs
crates/nu-cmd-lang/src/core_commands/if_.rs
use nu_engine::command_prelude::*; use nu_protocol::{ engine::{CommandType, StateWorkingSet}, eval_const::{eval_const_subexpression, eval_constant, eval_constant_with_input}, }; #[derive(Clone)] pub struct If; impl Command for If { fn name(&self) -> &str { "if" } fn description(&self) -> &str { "Conditionally run a block." } fn signature(&self) -> nu_protocol::Signature { Signature::build("if") .input_output_types(vec![(Type::Any, Type::Any)]) .required("cond", SyntaxShape::MathExpression, "Condition to check.") .required( "then_block", SyntaxShape::Block, "Block to run if check succeeds.", ) .optional( "else_expression", SyntaxShape::Keyword( b"else".to_vec(), Box::new(SyntaxShape::OneOf(vec![ SyntaxShape::Block, SyntaxShape::Expression, ])), ), "Expression or block to run when the condition is false.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn is_const(&self) -> bool { true } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let call = call.assert_ast_call()?; let cond = call.positional_nth(0).expect("checked through parser"); let then_expr = call.positional_nth(1).expect("checked through parser"); let then_block = then_expr .as_block() .ok_or_else(|| ShellError::TypeMismatch { err_message: "expected block".into(), span: then_expr.span, })?; let else_case = call.positional_nth(2); if eval_constant(working_set, cond)?.as_bool()? { let block = working_set.get_block(then_block); eval_const_subexpression(working_set, block, input, block.span.unwrap_or(call.head)) } else if let Some(else_case) = else_case { if let Some(else_expr) = else_case.as_keyword() { if let Some(block_id) = else_expr.as_block() { let block = working_set.get_block(block_id); eval_const_subexpression( working_set, block, input, block.span.unwrap_or(call.head), ) } else { eval_constant_with_input(working_set, else_expr, input) } } else { eval_constant_with_input(working_set, else_case, input) } } else { Ok(PipelineData::empty()) } } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // This is compiled specially by the IR compiler. The code here is never used when // running in IR mode. eprintln!( "Tried to execute 'run' for the 'if' command: this code path should never be reached in IR mode" ); unreachable!() } fn search_terms(&self) -> Vec<&str> { vec!["else", "conditional"] } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Output a value if a condition matches, otherwise return nothing", example: "if 2 < 3 { 'yes!' }", result: Some(Value::test_string("yes!")), }, Example { description: "Output a value if a condition matches, else return another value", example: "if 5 < 3 { 'yes!' } else { 'no!' }", result: Some(Value::test_string("no!")), }, Example { description: "Chain multiple if's together", example: "if 5 < 3 { 'yes!' } else if 4 < 5 { 'no!' } else { 'okay!' }", result: Some(Value::test_string("no!")), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(If {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/use_.rs
crates/nu-cmd-lang/src/core_commands/use_.rs
use nu_engine::{ command_prelude::*, find_in_dirs_env, get_dirs_var_from_call, get_eval_block, redirect_env, }; use nu_protocol::{ ast::{Expr, Expression}, engine::CommandType, }; #[derive(Clone)] pub struct Use; impl Command for Use { fn name(&self) -> &str { "use" } fn description(&self) -> &str { "Use definitions from a module, making them available in your shell." } fn signature(&self) -> nu_protocol::Signature { Signature::build("use") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required( "module", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]), "Module or module file (`null` for no-op).", ) .rest( "members", SyntaxShape::Any, "Which members of the module to import.", ) .category(Category::Core) } fn search_terms(&self) -> Vec<&str> { vec!["module", "import", "include", "scope"] } fn extra_description(&self) -> &str { r#"See `help std` for the standard library module. See `help modules` to list all available modules. This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn run( &self, engine_state: &EngineState, caller_stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { if call.get_parser_info(caller_stack, "noop").is_some() { return Ok(PipelineData::empty()); } let Some(Expression { expr: Expr::ImportPattern(import_pattern), .. }) = call.get_parser_info(caller_stack, "import_pattern") else { return Err(ShellError::GenericError { error: "Unexpected import".into(), msg: "import pattern not supported".into(), span: Some(call.head), help: None, inner: vec![], }); }; // Necessary so that we can modify the stack. let import_pattern = import_pattern.clone(); if let Some(module_id) = import_pattern.head.id { // Add constants for var_id in &import_pattern.constants { let var = engine_state.get_var(*var_id); if let Some(constval) = &var.const_val { caller_stack.add_var(*var_id, constval.clone()); } else { return Err(ShellError::NushellFailedSpanned { msg: "Missing Constant".to_string(), label: "constant not added by the parser".to_string(), span: var.declaration_span, }); } } // Evaluate the export-env block if there is one let module = engine_state.get_module(module_id); if let Some(block_id) = module.env_block { let block = engine_state.get_block(block_id); // See if the module is a file let module_arg_str = String::from_utf8_lossy( engine_state.get_span_contents(import_pattern.head.span), ); let maybe_file_path_or_dir = find_in_dirs_env( &module_arg_str, engine_state, caller_stack, get_dirs_var_from_call(caller_stack, call), )?; // module_arg_str maybe a directory, in this case // find_in_dirs_env returns a directory. let maybe_parent = maybe_file_path_or_dir.as_ref().and_then(|path| { if path.is_dir() { Some(path.to_path_buf()) } else { path.parent().map(|p| p.to_path_buf()) } }); let mut callee_stack = caller_stack .gather_captures(engine_state, &block.captures) .reset_pipes(); // If so, set the currently evaluated directory (file-relative PWD) if let Some(parent) = maybe_parent { let file_pwd = Value::string(parent.to_string_lossy(), call.head); callee_stack.add_env_var("FILE_PWD".to_string(), file_pwd); } if let Some(path) = maybe_file_path_or_dir { let module_file_path = if path.is_dir() { // the existence of `mod.nu` is verified in parsing time // so it's safe to use it here. Value::string(path.join("mod.nu").to_string_lossy(), call.head) } else { Value::string(path.to_string_lossy(), call.head) }; callee_stack.add_env_var("CURRENT_FILE".to_string(), module_file_path); } let eval_block = get_eval_block(engine_state); // Run the block (discard the result) let _ = eval_block(engine_state, &mut callee_stack, block, input)?; // Merge the block's environment to the current stack redirect_env(engine_state, caller_stack, &callee_stack); } } else { return Err(ShellError::GenericError { error: format!( "Could not import from '{}'", String::from_utf8_lossy(&import_pattern.head.name) ), msg: "module does not exist".to_string(), span: Some(import_pattern.head.span), help: None, inner: vec![], }); } Ok(PipelineData::empty()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Define a custom command in a module and call it", example: r#"module spam { export def foo [] { "foo" } }; use spam foo; foo"#, result: Some(Value::test_string("foo")), }, Example { description: "Define a custom command that participates in the environment in a module and call it", example: r#"module foo { export def --env bar [] { $env.FOO_BAR = "BAZ" } }; use foo bar; bar; $env.FOO_BAR"#, result: Some(Value::test_string("BAZ")), }, Example { description: "Use a plain module name to import its definitions qualified by the module name", example: r#"module spam { export def foo [] { "foo" }; export def bar [] { "bar" } }; use spam; (spam foo) + (spam bar)"#, result: Some(Value::test_string("foobar")), }, Example { description: "Specify * to use all definitions in a module", example: r#"module spam { export def foo [] { "foo" }; export def bar [] { "bar" } }; use spam *; (foo) + (bar)"#, result: Some(Value::test_string("foobar")), }, Example { description: "To use commands with spaces, like subcommands, surround them with quotes", example: r#"module spam { export def 'foo bar' [] { "baz" } }; use spam 'foo bar'; foo bar"#, result: Some(Value::test_string("baz")), }, Example { description: "To use multiple definitions from a module, wrap them in a list", example: r#"module spam { export def foo [] { "foo" }; export def 'foo bar' [] { "baz" } }; use spam ['foo', 'foo bar']; (foo) + (foo bar)"#, result: Some(Value::test_string("foobaz")), }, ] } } #[cfg(test)] mod test { #[test] fn test_examples() { use super::Use; use crate::test_examples; test_examples(Use {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/match_.rs
crates/nu-cmd-lang/src/core_commands/match_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Match; impl Command for Match { fn name(&self) -> &str { "match" } fn description(&self) -> &str { "Conditionally run a block on a matched value." } fn signature(&self) -> nu_protocol::Signature { Signature::build("match") .input_output_types(vec![(Type::Any, Type::Any)]) .required("value", SyntaxShape::Any, "Value to check.") .required( "match_block", SyntaxShape::MatchBlock, "Block to run if check succeeds.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // This is compiled specially by the IR compiler. The code here is never used when // running in IR mode. eprintln!( "Tried to execute 'run' for the 'match' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Match on a value", example: "match 3 { 1 => 'one', 2 => 'two', 3 => 'three' }", result: Some(Value::test_string("three")), }, Example { description: "Match against alternative values", example: "match 'three' { 1 | 'one' => '-', 2 | 'two' => '--', 3 | 'three' => '---' }", result: Some(Value::test_string("---")), }, Example { description: "Match on a value in range", example: "match 3 { 1..10 => 'yes!' }", result: Some(Value::test_string("yes!")), }, Example { description: "Match on a field in a record", example: "match {a: 100} { {a: $my_value} => { $my_value } }", result: Some(Value::test_int(100)), }, Example { description: "Match with a catch-all", example: "match 3 { 1 => { 'yes!' }, _ => { 'no!' } }", result: Some(Value::test_string("no!")), }, Example { description: "Match against a list", example: "match [1, 2, 3] { [$a, $b, $c] => { $a + $b + $c }, _ => 0 }", result: Some(Value::test_int(6)), }, Example { description: "Match against pipeline input", example: "{a: {b: 3}} | match $in {{a: { $b }} => ($b + 10) }", result: Some(Value::test_int(13)), }, Example { description: "Match with a guard", example: "match [1 2 3] { [$x, ..$y] if $x == 1 => { 'good list' }, _ => { 'not a very good list' } } ", result: Some(Value::test_string("good list")), }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Match {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/extern_.rs
crates/nu-cmd-lang/src/core_commands/extern_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Extern; impl Command for Extern { fn name(&self) -> &str { "extern" } fn description(&self) -> &str { "Define a signature for an external command." } fn signature(&self) -> nu_protocol::Signature { Signature::build("extern") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .required("def_name", SyntaxShape::String, "Definition name.") .required("params", SyntaxShape::Signature, "Parameters.") .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } 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: "Write a signature for an external command", example: r#"extern echo [text: string]"#, result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/export_def.rs
crates/nu-cmd-lang/src/core_commands/export_def.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct ExportDef; impl Command for ExportDef { fn name(&self) -> &str { "export def" } fn description(&self) -> &str { "Define a custom command and export it from a module." } fn signature(&self) -> nu_protocol::Signature { Signature::build("export def") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .required("def_name", SyntaxShape::String, "Command name.") .required("params", SyntaxShape::Signature, "Parameters.") .required("block", SyntaxShape::Block, "Body of the definition.") .switch("env", "keep the environment defined inside the command", None) .switch("wrapped", "treat unknown flags and arguments as strings (requires ...rest-like parameter in signature)", None) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } 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: "Define a custom command in a module and call it", example: r#"module spam { export def foo [] { "foo" } }; use spam foo; foo"#, result: Some(Value::test_string("foo")), }] } fn search_terms(&self) -> Vec<&str> { vec!["module"] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/export_module.rs
crates/nu-cmd-lang/src/core_commands/export_module.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct ExportModule; impl Command for ExportModule { fn name(&self) -> &str { "export module" } fn description(&self) -> &str { "Export a custom module from a module." } fn signature(&self) -> nu_protocol::Signature { Signature::build("export module") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required("module", SyntaxShape::String, "Module name or module path.") .optional( "block", SyntaxShape::Block, "Body of the module if 'module' parameter is not a path.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } 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: "Define a custom command in a submodule of a module and call it", example: r#"module spam { export module eggs { export def foo [] { "foo" } } } use spam eggs eggs foo"#, result: Some(Value::test_string("foo")), }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ExportModule {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/export_const.rs
crates/nu-cmd-lang/src/core_commands/export_const.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct ExportConst; impl Command for ExportConst { fn name(&self) -> &str { "export const" } fn description(&self) -> &str { "Use parse-time constant from a module and export them from this module." } fn signature(&self) -> nu_protocol::Signature { Signature::build("export const") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required("const_name", SyntaxShape::VarWithOptType, "Constant name.") .required( "initial_value", SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)), "Equals sign followed by constant value.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } 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: "Re-export a command from another module", example: r#"module spam { export const foo = 3; } module eggs { export use spam foo } use eggs foo foo "#, result: Some(Value::test_int(3)), }] } fn search_terms(&self) -> Vec<&str> { vec!["reexport", "import", "module"] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/hide_env.rs
crates/nu-cmd-lang/src/core_commands/hide_env.rs
use nu_engine::command_prelude::*; use nu_protocol::did_you_mean; #[derive(Clone)] pub struct HideEnv; impl Command for HideEnv { fn name(&self) -> &str { "hide-env" } fn signature(&self) -> nu_protocol::Signature { Signature::build("hide-env") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .rest( "name", SyntaxShape::String, "Environment variable names to hide.", ) .switch( "ignore-errors", "do not throw an error if an environment variable was not found", Some('i'), ) .category(Category::Core) } fn description(&self) -> &str { "Hide environment variables in the current scope." } fn search_terms(&self) -> Vec<&str> { vec!["unset", "drop"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let env_var_names: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?; let ignore_errors = call.has_flag(engine_state, stack, "ignore-errors")?; for name in env_var_names { if !stack.remove_env_var(engine_state, &name.item) && !ignore_errors { let all_names = stack.get_env_var_names(engine_state); if let Some(closest_match) = did_you_mean(&all_names, &name.item) { return Err(ShellError::DidYouMeanCustom { msg: format!("Environment variable '{}' not found", name.item), suggestion: closest_match, span: name.span, }); } else { return Err(ShellError::EnvVarNotFoundAtRuntime { envvar_name: name.item, span: name.span, }); } } } Ok(PipelineData::empty()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Hide an environment variable", example: r#"$env.HZ_ENV_ABC = 1; hide-env HZ_ENV_ABC; 'HZ_ENV_ABC' in $env"#, result: Some(Value::test_bool(false)), }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/return_.rs
crates/nu-cmd-lang/src/core_commands/return_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Return; impl Command for Return { fn name(&self) -> &str { "return" } fn description(&self) -> &str { "Return early from a custom command." } fn signature(&self) -> nu_protocol::Signature { Signature::build("return") .input_output_types(vec![(Type::Nothing, Type::Any)]) .optional( "return_value", SyntaxShape::Any, "Optional value to return.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // This is compiled specially by the IR compiler. The code here is never used when // running in IR mode. eprintln!( "Tried to execute 'run' for the 'return' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Return early", example: r#"def foo [] { return }"#, result: None, }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/version.rs
crates/nu-cmd-lang/src/core_commands/version.rs
use std::{borrow::Cow, sync::OnceLock}; use itertools::Itertools; use nu_engine::command_prelude::*; use nu_protocol::engine::StateWorkingSet; use shadow_rs::shadow; shadow!(build); /// Static container for the cargo features used by the `version` command. /// /// This `OnceLock` holds the features from `nu`. /// When you build `nu_cmd_lang`, Cargo doesn't pass along the same features that `nu` itself uses. /// By setting this static before calling `version`, you make it show `nu`'s features instead /// of `nu_cmd_lang`'s. /// /// Embedders can set this to any feature list they need, but in most cases you'll probably want to /// pass the cargo features of your host binary. /// /// # How to get cargo features in your build script /// /// In your binary's build script: /// ```rust,ignore /// // Re-export CARGO_CFG_FEATURE to the main binary. /// // It holds all the features that cargo sets for your binary as a comma-separated list. /// println!( /// "cargo:rustc-env=NU_FEATURES={}", /// std::env::var("CARGO_CFG_FEATURE").expect("set by cargo") /// ); /// ``` /// /// Then, before you call `version`: /// ```rust,ignore /// // This uses static strings, but since we're using `Cow`, you can also pass owned strings. /// let features = env!("NU_FEATURES") /// .split(',') /// .map(Cow::Borrowed) /// .collect(); /// /// nu_cmd_lang::VERSION_NU_FEATURES /// .set(features) /// .expect("couldn't set VERSION_NU_FEATURES"); /// ``` pub static VERSION_NU_FEATURES: OnceLock<Vec<Cow<'static, str>>> = OnceLock::new(); #[derive(Clone)] pub struct Version; impl Command for Version { fn name(&self) -> &str { "version" } fn signature(&self) -> Signature { Signature::build("version") .input_output_types(vec![(Type::Nothing, Type::record())]) .allow_variants_without_examples(true) .category(Category::Core) } fn description(&self) -> &str { "Display Nu version, and its build configuration." } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, _stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { version(engine_state, call.head) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { version(working_set.permanent(), call.head) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Display Nu version", example: "version", result: None, }] } } fn push_non_empty(record: &mut Record, name: &str, value: &str, span: Span) { if !value.is_empty() { record.push(name, Value::string(value, span)) } } pub fn version(engine_state: &EngineState, span: Span) -> Result<PipelineData, ShellError> { // Pre-allocate the arrays in the worst case (17 items): // - version // - major // - minor // - patch // - pre // - branch // - commit_hash // - build_os // - build_target // - rust_version // - rust_channel // - cargo_version // - build_time // - build_rust_channel // - allocator // - features // - installed_plugins let mut record = Record::with_capacity(17); record.push("version", Value::string(env!("CARGO_PKG_VERSION"), span)); push_version_numbers(&mut record, span); push_non_empty(&mut record, "pre", build::PKG_VERSION_PRE, span); record.push("branch", Value::string(build::BRANCH, span)); if let Some(commit_hash) = option_env!("NU_COMMIT_HASH") { record.push("commit_hash", Value::string(commit_hash, span)); } push_non_empty(&mut record, "build_os", build::BUILD_OS, span); push_non_empty(&mut record, "build_target", build::BUILD_TARGET, span); push_non_empty(&mut record, "rust_version", build::RUST_VERSION, span); push_non_empty(&mut record, "rust_channel", build::RUST_CHANNEL, span); push_non_empty(&mut record, "cargo_version", build::CARGO_VERSION, span); push_non_empty(&mut record, "build_time", build::BUILD_TIME, span); push_non_empty( &mut record, "build_rust_channel", build::BUILD_RUST_CHANNEL, span, ); record.push("allocator", Value::string(global_allocator(), span)); record.push( "features", Value::string( VERSION_NU_FEATURES .get() .as_ref() .map(|v| v.as_slice()) .unwrap_or_default() .iter() .filter(|f| !f.starts_with("dep:")) .join(", "), span, ), ); #[cfg(not(feature = "plugin"))] let _ = engine_state; #[cfg(feature = "plugin")] { // Get a list of plugin names and versions if present let installed_plugins = engine_state .plugins() .iter() .map(|x| { let name = x.identity().name(); if let Some(version) = x.metadata().and_then(|m| m.version) { format!("{name} {version}") } else { name.into() } }) .collect::<Vec<_>>(); record.push( "installed_plugins", Value::string(installed_plugins.join(", "), span), ); } record.push( "experimental_options", Value::string( nu_experimental::ALL .iter() .map(|option| format!("{}={}", option.identifier(), option.get())) .join(", "), span, ), ); Ok(Value::record(record, span).into_pipeline_data()) } /// Add version numbers as integers to the given record fn push_version_numbers(record: &mut Record, head: Span) { static VERSION_NUMBERS: OnceLock<(u8, u8, u8)> = OnceLock::new(); let &(major, minor, patch) = VERSION_NUMBERS.get_or_init(|| { ( build::PKG_VERSION_MAJOR.parse().expect("Always set"), build::PKG_VERSION_MINOR.parse().expect("Always set"), build::PKG_VERSION_PATCH.parse().expect("Always set"), ) }); record.push("major", Value::int(major.into(), head)); record.push("minor", Value::int(minor.into(), head)); record.push("patch", Value::int(patch.into(), head)); } fn global_allocator() -> &'static str { "standard" } #[cfg(test)] mod test { #[test] fn test_examples() { use super::Version; use crate::test_examples; test_examples(Version) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/mut_.rs
crates/nu-cmd-lang/src/core_commands/mut_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Mut; impl Command for Mut { fn name(&self) -> &str { "mut" } fn description(&self) -> &str { "Create a mutable variable and give it a value." } fn signature(&self) -> nu_protocol::Signature { Signature::build("mut") .input_output_types(vec![(Type::Any, Type::Nothing)]) .allow_variants_without_examples(true) .required("var_name", SyntaxShape::VarWithOptType, "Variable name.") .required( "initial_value", SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)), "Equals sign followed by value.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn search_terms(&self) -> Vec<&str> { vec!["set", "mutable"] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // This is compiled specially by the IR compiler. The code here is never used when // running in IR mode. eprintln!( "Tried to execute 'run' for the 'mut' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Set a mutable variable to a value, then update it", example: "mut x = 10; $x = 12", result: None, }, Example { description: "Upsert a value inside a mutable data structure", example: "mut a = {b:{c:1}}; $a.b.c = 2", result: None, }, Example { description: "Set a mutable variable to the result of an expression", example: "mut x = 10 + 100", result: None, }, Example { description: "Set a mutable variable based on the condition", example: "mut x = if false { -1 } else { 1 }", result: None, }, ] } } #[cfg(test)] mod test { use nu_protocol::engine::CommandType; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Mut {}) } #[test] fn test_command_type() { assert!(matches!(Mut.command_type(), CommandType::Keyword)); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/do_.rs
crates/nu-cmd-lang/src/core_commands/do_.rs
use nu_engine::{command_prelude::*, get_eval_block_with_early_return, redirect_env}; #[cfg(feature = "os")] use nu_protocol::process::{ChildPipe, ChildProcess}; use nu_protocol::{ ByteStream, ByteStreamSource, OutDest, engine::Closure, shell_error::io::IoError, }; use std::{ io::{Cursor, Read}, thread, }; #[derive(Clone)] pub struct Do; impl Command for Do { fn name(&self) -> &str { "do" } fn description(&self) -> &str { "Run a closure, providing it with the pipeline input." } fn signature(&self) -> Signature { Signature::build("do") .required("closure", SyntaxShape::Closure(None), "The closure to run.") .input_output_types(vec![(Type::Any, Type::Any)]) .switch( "ignore-errors", "ignore errors as the closure runs", Some('i'), ) .switch( "capture-errors", "catch errors as the closure runs, and return them", Some('c'), ) .switch( "env", "keep the environment defined inside the command", None, ) .rest( "rest", SyntaxShape::Any, "The parameter(s) for the closure.", ) .category(Category::Core) } fn run( &self, engine_state: &EngineState, caller_stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let block: Closure = call.req(engine_state, caller_stack, 0)?; let rest: Vec<Value> = call.rest(engine_state, caller_stack, 1)?; let ignore_all_errors = call.has_flag(engine_state, caller_stack, "ignore-errors")?; let capture_errors = call.has_flag(engine_state, caller_stack, "capture-errors")?; let has_env = call.has_flag(engine_state, caller_stack, "env")?; let mut callee_stack = caller_stack.captures_to_stack_preserve_out_dest(block.captures); let block = engine_state.get_block(block.block_id); bind_args_to(&mut callee_stack, &block.signature, rest, head)?; let eval_block_with_early_return = get_eval_block_with_early_return(engine_state); let result = eval_block_with_early_return(engine_state, &mut callee_stack, block, input) .map(|p| p.body); if has_env { // Merge the block's environment to the current stack redirect_env(engine_state, caller_stack, &callee_stack); } match result { Ok(PipelineData::ByteStream(stream, metadata)) if capture_errors => { let span = stream.span(); #[cfg(not(feature = "os"))] return Err(ShellError::DisabledOsSupport { msg: "Cannot create a thread to receive stdout message.".to_string(), span, }); #[cfg(feature = "os")] match stream.into_child() { Ok(mut child) => { // Use a thread to receive stdout message. // Or we may get a deadlock if child process sends out too much bytes to stderr. // // For example: in normal linux system, stderr pipe's limit is 65535 bytes. // if child process sends out 65536 bytes, the process will be hanged because no consumer // consumes the first 65535 bytes // So we need a thread to receive stdout message, then the current thread can continue to consume // stderr messages. let stdout_handler = child .stdout .take() .map(|mut stdout| { thread::Builder::new() .name("stdout consumer".to_string()) .spawn(move || { let mut buf = Vec::new(); stdout.read_to_end(&mut buf).map_err(|err| { IoError::new_internal( err, "Could not read stdout to end", nu_protocol::location!(), ) })?; Ok::<_, ShellError>(buf) }) .map_err(|err| IoError::new(err, head, None)) }) .transpose()?; // Intercept stderr so we can return it in the error if the exit code is non-zero. // The threading issues mentioned above dictate why we also need to intercept stdout. let stderr_msg = match child.stderr.take() { None => String::new(), Some(mut stderr) => { let mut buf = String::new(); stderr .read_to_string(&mut buf) .map_err(|err| IoError::new(err, span, None))?; buf } }; let stdout = if let Some(handle) = stdout_handler { match handle.join() { Err(err) => { return Err(ShellError::ExternalCommand { label: "Fail to receive external commands stdout message" .to_string(), help: format!("{err:?}"), span, }); } Ok(res) => Some(res?), } } else { None }; child.ignore_error(false); child.wait()?; let mut child = ChildProcess::from_raw(None, None, None, span); if let Some(stdout) = stdout { child.stdout = Some(ChildPipe::Tee(Box::new(Cursor::new(stdout)))); } if !stderr_msg.is_empty() { child.stderr = Some(ChildPipe::Tee(Box::new(Cursor::new(stderr_msg)))); } Ok(PipelineData::byte_stream( ByteStream::child(child, span), metadata, )) } Err(stream) => Ok(PipelineData::byte_stream(stream, metadata)), } } Ok(PipelineData::ByteStream(mut stream, metadata)) if ignore_all_errors && !matches!( caller_stack.stdout(), OutDest::Pipe | OutDest::PipeSeparate | OutDest::Value ) => { #[cfg(feature = "os")] if let ByteStreamSource::Child(child) = stream.source_mut() { child.ignore_error(true); } Ok(PipelineData::byte_stream(stream, metadata)) } Ok(PipelineData::Value(Value::Error { .. }, ..)) | Err(_) if ignore_all_errors => { Ok(PipelineData::empty()) } Ok(PipelineData::ListStream(stream, metadata)) if ignore_all_errors => { let stream = stream.map(move |value| { if let Value::Error { .. } = value { Value::nothing(head) } else { value } }); Ok(PipelineData::list_stream(stream, metadata)) } r => r, } } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Run the closure", example: r#"do { echo hello }"#, result: Some(Value::test_string("hello")), }, Example { description: "Run a stored first-class closure", example: r#"let text = "I am enclosed"; let hello = {|| echo $text}; do $hello"#, result: Some(Value::test_string("I am enclosed")), }, Example { description: "Run the closure and ignore both shell and external program errors", example: r#"do --ignore-errors { thisisnotarealcommand }"#, result: None, }, Example { description: "Abort the pipeline if a program returns a non-zero exit code", example: r#"do --capture-errors { nu --commands 'exit 1' } | myscarycommand"#, result: None, }, Example { description: "Run the closure with a positional, type-checked parameter", example: r#"do {|x:int| 100 + $x } 77"#, result: Some(Value::test_int(177)), }, Example { description: "Run the closure with pipeline input", example: r#"77 | do { 100 + $in }"#, result: Some(Value::test_int(177)), }, Example { description: "Run the closure with a default parameter value", example: r#"77 | do {|x=100| $x + $in }"#, result: Some(Value::test_int(177)), }, Example { description: "Run the closure with two positional parameters", example: r#"do {|x,y| $x + $y } 77 100"#, result: Some(Value::test_int(177)), }, Example { description: "Run the closure and keep changes to the environment", example: r#"do --env { $env.foo = 'bar' }; $env.foo"#, result: Some(Value::test_string("bar")), }, ] } } fn bind_args_to( stack: &mut Stack, signature: &Signature, args: Vec<Value>, head_span: Span, ) -> Result<(), ShellError> { let mut val_iter = args.into_iter(); for (param, required) in signature .required_positional .iter() .map(|p| (p, true)) .chain(signature.optional_positional.iter().map(|p| (p, false))) { let var_id = param .var_id .expect("internal error: all custom parameters must have var_ids"); if let Some(result) = val_iter.next() { let param_type = param.shape.to_type(); if !result.is_subtype_of(&param_type) { return Err(ShellError::CantConvert { to_type: param.shape.to_type().to_string(), from_type: result.get_type().to_string(), span: result.span(), help: None, }); } stack.add_var(var_id, result); } else if let Some(value) = &param.default_value { stack.add_var(var_id, value.to_owned()) } else if !required { stack.add_var(var_id, Value::nothing(head_span)) } else { return Err(ShellError::MissingParameter { param_name: param.name.to_string(), span: head_span, }); } } if let Some(rest_positional) = &signature.rest_positional { let mut rest_items = vec![]; for result in val_iter { rest_items.push(result); } let span = if let Some(rest_item) = rest_items.first() { rest_item.span() } else { head_span }; stack.add_var( rest_positional .var_id .expect("Internal error: rest positional parameter lacks var_id"), Value::list(rest_items, span), ) } Ok(()) } mod test { #[test] fn test_examples() { use super::Do; use crate::test_examples; test_examples(Do {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/collect.rs
crates/nu-cmd-lang/src/core_commands/collect.rs
use nu_engine::{command_prelude::*, get_eval_block, redirect_env}; use nu_protocol::engine::Closure; #[derive(Clone)] pub struct Collect; impl Command for Collect { fn name(&self) -> &str { "collect" } fn signature(&self) -> Signature { Signature::build("collect") .input_output_types(vec![(Type::Any, Type::Any)]) .optional( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "The closure to run once the stream is collected.", ) .switch( "keep-env", "let the closure affect environment variables", None, ) .category(Category::Filters) } fn description(&self) -> &str { "Collect a stream into a value." } fn extra_description(&self) -> &str { r#"If provided, run a closure with the collected value as input. The entire stream will be collected into one value in memory, so if the stream is particularly large, this can cause high memory usage."# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let closure: Option<Closure> = call.opt(engine_state, stack, 0)?; let metadata = input.metadata().and_then(|m| m.for_collect()); let input = input.into_value(call.head)?; let result; if let Some(closure) = closure { let block = engine_state.get_block(closure.block_id); let mut stack_captures = stack.captures_to_stack_preserve_out_dest(closure.captures.clone()); let mut saved_positional = None; if let Some(var) = block.signature.get_positional(0) && let Some(var_id) = &var.var_id { stack_captures.add_var(*var_id, input.clone()); saved_positional = Some(*var_id); } let eval_block = get_eval_block(engine_state); result = eval_block( engine_state, &mut stack_captures, block, input.into_pipeline_data_with_metadata(metadata), ) .map(|p| p.body); if call.has_flag(engine_state, stack, "keep-env")? { redirect_env(engine_state, stack, &stack_captures); // for when we support `data | let x = $in;` // remove the variables added earlier for (var_id, _) in closure.captures { stack_captures.remove_var(var_id); } if let Some(u) = saved_positional { stack_captures.remove_var(u); } // add any new variables to the stack stack.vars.extend(stack_captures.vars); } } else { result = Ok(input.into_pipeline_data_with_metadata(metadata)); } result } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Use the second value in the stream", example: "[1 2 3] | collect { |x| $x.1 }", result: Some(Value::test_int(2)), }, Example { description: "Read and write to the same file", example: "open file.txt | collect | save -f file.txt", result: None, }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Collect {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/module.rs
crates/nu-cmd-lang/src/core_commands/module.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Module; impl Command for Module { fn name(&self) -> &str { "module" } fn description(&self) -> &str { "Define a custom module." } fn signature(&self) -> nu_protocol::Signature { Signature::build("module") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required("module", SyntaxShape::String, "Module name or module path.") .optional( "block", SyntaxShape::Block, "Body of the module if 'module' parameter is not a module path.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } 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: "Define a custom command in a module and call it", example: r#"module spam { export def foo [] { "foo" } }; use spam foo; foo"#, result: Some(Value::test_string("foo")), }, Example { description: "Define an environment variable in a module", example: r#"module foo { export-env { $env.FOO = "BAZ" } }; use foo; $env.FOO"#, result: Some(Value::test_string("BAZ")), }, Example { description: "Define a custom command that participates in the environment in a module and call it", example: r#"module foo { export def --env bar [] { $env.FOO_BAR = "BAZ" } }; use foo bar; bar; $env.FOO_BAR"#, result: Some(Value::test_string("BAZ")), }, ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/hide.rs
crates/nu-cmd-lang/src/core_commands/hide.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Hide; impl Command for Hide { fn name(&self) -> &str { "hide" } fn signature(&self) -> nu_protocol::Signature { Signature::build("hide") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .required("module", SyntaxShape::String, "Module or module file.") .optional( "members", SyntaxShape::Any, "Which members of the module to hide.", ) .category(Category::Core) } fn description(&self) -> &str { "Hide definitions in the current scope." } fn extra_description(&self) -> &str { r#"Definitions are hidden by priority: First aliases, then custom commands. This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn search_terms(&self) -> Vec<&str> { vec!["unset"] } 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: "Hide the alias just defined", example: r#"alias lll = ls -l; hide lll"#, result: None, }, Example { description: "Hide a custom command", example: r#"def say-hi [] { echo 'Hi!' }; hide say-hi"#, result: None, }, ] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/try_.rs
crates/nu-cmd-lang/src/core_commands/try_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Try; impl Command for Try { fn name(&self) -> &str { "try" } fn description(&self) -> &str { "Try to run a block, if it fails optionally run a catch closure." } fn signature(&self) -> nu_protocol::Signature { Signature::build("try") .input_output_types(vec![(Type::Any, Type::Any)]) .required("try_block", SyntaxShape::Block, "Block to run.") .optional( "catch_closure", SyntaxShape::Keyword( b"catch".to_vec(), Box::new(SyntaxShape::OneOf(vec![ SyntaxShape::Closure(None), SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), ])), ), "Closure to run if try block fails.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // This is compiled specially by the IR compiler. The code here is never used when // running in IR mode. eprintln!( "Tried to execute 'run' for the 'try' command: this code path should never be reached in IR mode" ); unreachable!(); } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Try to run a division by zero", example: "try { 1 / 0 }", result: None, }, Example { description: "Try to run a division by zero and return a string instead", example: "try { 1 / 0 } catch { 'divided by zero' }", result: Some(Value::test_string("divided by zero")), }, Example { description: "Try to run a division by zero and report the message", example: "try { 1 / 0 } catch { |err| $err.msg }", result: None, }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Try {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/export_alias.rs
crates/nu-cmd-lang/src/core_commands/export_alias.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct ExportAlias; impl Command for ExportAlias { fn name(&self) -> &str { "export alias" } fn description(&self) -> &str { "Alias a command (with optional flags) to a new name and export it from a module." } fn signature(&self) -> nu_protocol::Signature { Signature::build("export alias") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .required("name", SyntaxShape::String, "Name of the alias.") .required( "initial_value", SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::Expression)), "Equals sign followed by value.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn search_terms(&self) -> Vec<&str> { vec!["abbr", "aka", "fn", "func", "function"] } 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: "Alias ll to ls -l and export it from a module", example: "module spam { export alias ll = ls -l }", result: Some(Value::nothing(Span::test_data())), }] } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/error_make.rs
crates/nu-cmd-lang/src/core_commands/error_make.rs
use nu_engine::command_prelude::*; use nu_protocol::{ErrorLabel, ErrorSource, FromValue, IntoValue, LabeledError}; #[derive(Clone)] pub struct ErrorMake; impl Command for ErrorMake { fn name(&self) -> &str { "error make" } fn signature(&self) -> Signature { Signature::build("error make") .category(Category::Core) .input_output_types(vec![ // original nothing input type (Type::Nothing, Type::Error), // "foo" | error make (Type::String, Type::Error), // {...} | error make // try {...} catch {error make} (Type::record(), Type::Error), ]) .optional( "error_struct", SyntaxShape::OneOf(vec![SyntaxShape::Record(vec![]), SyntaxShape::String]), "The error to create.", ) .switch("unspanned", "remove the labels from the error", Some('u')) } fn description(&self) -> &str { "Create an error." } fn extra_description(&self) -> &str { "Use either as a command with an `error_struct` or string as an input. The `error_struct` is detailed below: * `msg: string` (required) * `code: string` * `labels: table<error_label>` * `help: string` * `url: string` * `inner: table<error_struct>` * `src: src_record` The `error_label` should contain the following keys: * `text: string` * `span: record<start: int end: int>` External errors (referencing external sources, not the default nu spans) are created using the `src` column with the `src_record` record. This only changes where the labels are placed. For this, the `code` key is ignored, and will always be `nu::shell::outside`. Errors cannot use labels that reference both inside and outside sources, to do that use an `inner` error. * `name: string` - name of the source * `text: string` - the raw text to place the spans in * `path: string` - a file path to place the spans in Errors can be chained together using the `inner` key, and multiple spans can be specified to give more detailed error outputs. If a string is passed it will be the `msg` part of the `error_struct`. Errors can also be chained using `try {} catch {}`, allowing for related errors to be printed out more easily. The code block for `catch` passes a record of the `try` block's error into the catch block, which can be used in `error make` either as the input or as an argument. These will be added as `inner` errors to the most recent `error make`." } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create a simple, default error", example: "error make", result: None, }, Example { description: "Create a simple error from a string", example: "error make 'my error message'", result: None, }, Example { description: "Create a simple error from an `error_struct` record", example: "error make {msg: 'my error message'}", result: None, }, Example { description: "A complex error utilizing spans and inners", example: r#"def foo [x: int, y: int] { let z = $x + $y error make { msg: "an error for foo just occurred" labels: [ {text: "one" span: (metadata $x).span} {text: "two" span: (metadata $y).span} ] help: "some help for the user" inner: [ {msg: "an inner error" labels: [{text: "" span: (metadata $y).span}]} ] } }"#, result: None, }, Example { description: "Chain errors using a pipeline", example: r#"try {error make "foo"} catch {error make "bar"}"#, result: None, }, Example { description: "Chain errors using arguments (note the extra command in `catch`)", example: r#"try { error make "foo" } catch {|err| print 'We got an error that will be chained!' error make {msg: "bar" inner: [$err]} }"#, result: None, }, ] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let value = match call.opt(engine_state, stack, 0) { Ok(Some(v @ Value::Record { .. } | v @ Value::String { .. })) => v, Ok(_) => Value::string("originates from here", call.head), Err(e) => return Err(e), }; let show_labels: bool = !call.has_flag(engine_state, stack, "unspanned")?; let inners = match ErrorInfo::from_value(input.into_value(call.head)?) { Ok(v) => vec![v.into_value(call.head)], Err(_) => vec![], }; Err(match (inners, value) { (inner, Value::String { val, .. }) => ErrorInfo { msg: val, inner, ..ErrorInfo::default() } .labeled(call.head, show_labels), ( inner, Value::Record { val, internal_span, .. }, ) => { let mut ei = ErrorInfo::from_value((*val).clone().into_value(internal_span))?; ei.inner = [ei.inner, inner].concat(); ei.labeled(internal_span, show_labels) } (_, Value::Error { error, .. }) => *error, _ => todo!(), }) } } #[derive(Debug, Clone, IntoValue, FromValue)] struct ErrorInfo { msg: String, code: Option<String>, help: Option<String>, url: Option<String>, #[nu_value(default)] labels: Vec<ErrorLabel>, label: Option<ErrorLabel>, #[nu_value(default)] inner: Vec<Value>, raw: Option<Value>, src: Option<ErrorSource>, } impl Default for ErrorInfo { fn default() -> Self { Self { msg: "Originates from here".into(), code: Some("nu::shell::error".into()), help: None, url: None, labels: Vec::default(), label: None, inner: Vec::default(), raw: None, src: None, } } } impl ErrorInfo { pub fn labels(self) -> Vec<ErrorLabel> { match self.label { None => self.labels, Some(label) => [self.labels, vec![label]].concat(), } } pub fn labeled(self, span: Span, show_labels: bool) -> ShellError { let inner: Vec<ShellError> = self .inner .clone() .into_iter() .map(|i| match ErrorInfo::from_value(i) { Ok(e) => e.labeled(span, show_labels), Err(err) => err, }) .collect(); let labels = self.clone().labels(); match self { // External error with src code and url ErrorInfo { src: Some(src), url: Some(url), msg, help, raw: None, .. } => ShellError::OutsideSource { src: src.into(), labels: labels.into_iter().map(|l| l.into()).collect(), msg, url, help, inner, }, // External error with src code ErrorInfo { src: Some(src), msg, help, raw: None, .. } => ShellError::OutsideSourceNoUrl { src: src.into(), labels: labels.into_iter().map(|l| l.into()).collect(), msg, help, inner, }, // Normal error ei @ ErrorInfo { src: None, raw: None, .. } => LabeledError { labels: match (show_labels, labels.as_slice()) { (true, []) => vec![ErrorLabel { text: "".into(), span, }], (true, labels) => labels.to_vec(), (false, _) => vec![], } .into(), msg: ei.msg, code: ei.code, url: ei.url, help: ei.help, inner: inner.into(), } .into(), // Error error with a raw error value somewhere ErrorInfo { raw: Some(v), .. } => ShellError::from_value(v).unwrap_or_else(|e| e), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/echo.rs
crates/nu-cmd-lang/src/core_commands/echo.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct Echo; impl Command for Echo { fn name(&self) -> &str { "echo" } fn description(&self) -> &str { "Returns its arguments, ignoring the piped-in value." } fn signature(&self) -> Signature { Signature::build("echo") .input_output_types(vec![(Type::Nothing, Type::Any)]) .rest("rest", SyntaxShape::Any, "The values to echo.") .category(Category::Core) } fn extra_description(&self) -> &str { r#"Unlike `print`, which prints unstructured text to stdout, `echo` is like an identity function and simply returns its arguments. When given no arguments, it returns an empty string. When given one argument, it returns it as a nushell value. Otherwise, it returns a list of the arguments. There is usually little reason to use this over just writing the values as-is."# } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let args = call.rest(engine_state, stack, 0)?; echo_impl(args, call.head) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let args = call.rest_const(working_set, 0)?; echo_impl(args, call.head) } fn is_const(&self) -> bool { true } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Put a list of numbers in the pipeline. This is the same as [1 2 3].", example: "echo 1 2 3", result: Some(Value::list( vec![Value::test_int(1), Value::test_int(2), Value::test_int(3)], Span::test_data(), )), }, Example { description: "Returns the piped-in value, by using the special $in variable to obtain it.", example: "echo $in", result: None, }, ] } } fn echo_impl(mut args: Vec<Value>, head: Span) -> Result<PipelineData, ShellError> { let value = match args.len() { 0 => Value::string("", head), 1 => args.pop().expect("one element"), _ => Value::list(args, head), }; Ok(value.into_pipeline_data()) } #[cfg(test)] mod test { #[test] fn test_examples() { use super::Echo; use crate::test_examples; test_examples(Echo {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/error.rs
crates/nu-cmd-lang/src/core_commands/error.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Error; impl Command for Error { fn name(&self) -> &str { "error" } fn signature(&self) -> Signature { Signature::build("error") .category(Category::Core) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various commands for working with errors." } fn extra_description(&self) -> &str { "You must use one of the following subcommands. Using this command as-is will only produce this help message." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/describe.rs
crates/nu-cmd-lang/src/core_commands/describe.rs
use nu_engine::command_prelude::*; use nu_protocol::{ BlockId, ByteStreamSource, Category, PipelineMetadata, Signature, engine::{Closure, StateWorkingSet}, }; use std::any::type_name; #[derive(Clone)] pub struct Describe; impl Command for Describe { fn name(&self) -> &str { "describe" } fn description(&self) -> &str { "Describe the type and structure of the value(s) piped in." } fn signature(&self) -> Signature { Signature::build("describe") .input_output_types(vec![(Type::Any, Type::Any)]) .switch( "no-collect", "do not collect streams of structured data", Some('n'), ) .switch( "detailed", "show detailed information about the value", Some('d'), ) .category(Category::Core) } fn is_const(&self) -> bool { true } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let options = Options { no_collect: call.has_flag(engine_state, stack, "no-collect")?, detailed: call.has_flag(engine_state, stack, "detailed")?, }; run(Some(engine_state), call, input, options) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let options = Options { no_collect: call.has_flag_const(working_set, "no-collect")?, detailed: call.has_flag_const(working_set, "detailed")?, }; run(None, call, input, options) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Describe the type of a string", example: "'hello' | describe", result: Some(Value::test_string("string")), }, Example { description: "Describe the type of a record in a detailed way", example: "{shell:'true', uwu:true, features: {bugs:false, multiplatform:true, speed: 10}, fib: [1 1 2 3 5 8], on_save: {|x| $'Saving ($x)'}, first_commit: 2019-05-10, my_duration: (4min + 20sec)} | describe -d", result: Some(Value::test_record(record!( "type" => Value::test_string("record"), "detailed_type" => Value::test_string("record<shell: string, uwu: bool, features: record<bugs: bool, multiplatform: bool, speed: int>, fib: list<int>, on_save: closure, first_commit: datetime, my_duration: duration>"), "columns" => Value::test_record(record!( "shell" => Value::test_record(record!( "type" => Value::test_string("string"), "detailed_type" => Value::test_string("string"), "rust_type" => Value::test_string("&alloc::string::String"), "value" => Value::test_string("true"), )), "uwu" => Value::test_record(record!( "type" => Value::test_string("bool"), "detailed_type" => Value::test_string("bool"), "rust_type" => Value::test_string("bool"), "value" => Value::test_bool(true), )), "features" => Value::test_record(record!( "type" => Value::test_string("record"), "detailed_type" => Value::test_string("record<bugs: bool, multiplatform: bool, speed: int>"), "columns" => Value::test_record(record!( "bugs" => Value::test_record(record!( "type" => Value::test_string("bool"), "detailed_type" => Value::test_string("bool"), "rust_type" => Value::test_string("bool"), "value" => Value::test_bool(false), )), "multiplatform" => Value::test_record(record!( "type" => Value::test_string("bool"), "detailed_type" => Value::test_string("bool"), "rust_type" => Value::test_string("bool"), "value" => Value::test_bool(true), )), "speed" => Value::test_record(record!( "type" => Value::test_string("int"), "detailed_type" => Value::test_string("int"), "rust_type" => Value::test_string("i64"), "value" => Value::test_int(10), )), )), "rust_type" => Value::test_string("&nu_utils::shared_cow::SharedCow<nu_protocol::value::record::Record>"), )), "fib" => Value::test_record(record!( "type" => Value::test_string("list"), "detailed_type" => Value::test_string("list<int>"), "length" => Value::test_int(6), "rust_type" => Value::test_string("&mut alloc::vec::Vec<nu_protocol::value::Value>"), "value" => Value::test_list(vec![ Value::test_record(record!( "type" => Value::test_string("int"), "detailed_type" => Value::test_string("int"), "rust_type" => Value::test_string("i64"), "value" => Value::test_int(1), )), Value::test_record(record!( "type" => Value::test_string("int"), "detailed_type" => Value::test_string("int"), "rust_type" => Value::test_string("i64"), "value" => Value::test_int(1), )), Value::test_record(record!( "type" => Value::test_string("int"), "detailed_type" => Value::test_string("int"), "rust_type" => Value::test_string("i64"), "value" => Value::test_int(2), )), Value::test_record(record!( "type" => Value::test_string("int"), "detailed_type" => Value::test_string("int"), "rust_type" => Value::test_string("i64"), "value" => Value::test_int(3), )), Value::test_record(record!( "type" => Value::test_string("int"), "detailed_type" => Value::test_string("int"), "rust_type" => Value::test_string("i64"), "value" => Value::test_int(5), )), Value::test_record(record!( "type" => Value::test_string("int"), "detailed_type" => Value::test_string("int"), "rust_type" => Value::test_string("i64"), "value" => Value::test_int(8), ))] ), )), "on_save" => Value::test_record(record!( "type" => Value::test_string("closure"), "detailed_type" => Value::test_string("closure"), "rust_type" => Value::test_string("&alloc::boxed::Box<nu_protocol::engine::closure::Closure>"), "value" => Value::test_closure(Closure { block_id: BlockId::new(1), captures: vec![], }), "signature" => Value::test_record(record!( "name" => Value::test_string(""), "category" => Value::test_string("default"), )), )), "first_commit" => Value::test_record(record!( "type" => Value::test_string("datetime"), "detailed_type" => Value::test_string("datetime"), "rust_type" => Value::test_string("chrono::datetime::DateTime<chrono::offset::fixed::FixedOffset>"), "value" => Value::test_date("2019-05-10 00:00:00Z".parse().unwrap_or_default()), )), "my_duration" => Value::test_record(record!( "type" => Value::test_string("duration"), "detailed_type" => Value::test_string("duration"), "rust_type" => Value::test_string("i64"), "value" => Value::test_duration(260_000_000_000), )) )), "rust_type" => Value::test_string("&nu_utils::shared_cow::SharedCow<nu_protocol::value::record::Record>"), ))), }, Example { description: "Describe the type of a stream with detailed information", example: "[1 2 3] | each {|i| echo $i} | describe -d", result: None, // Give "Running external commands not supported" error // result: Some(Value::test_record(record!( // "type" => Value::test_string("stream"), // "origin" => Value::test_string("nushell"), // "subtype" => Value::test_record(record!( // "type" => Value::test_string("list"), // "length" => Value::test_int(3), // "values" => Value::test_list(vec![ // Value::test_string("int"), // Value::test_string("int"), // Value::test_string("int"), // ]) // )) // ))), }, Example { description: "Describe a stream of data, collecting it first", example: "[1 2 3] | each {|i| echo $i} | describe", result: None, // Give "Running external commands not supported" error // result: Some(Value::test_string("list<int> (stream)")), }, Example { description: "Describe the input but do not collect streams", example: "[1 2 3] | each {|i| echo $i} | describe --no-collect", result: None, // Give "Running external commands not supported" error // result: Some(Value::test_string("stream")), }, ] } fn search_terms(&self) -> Vec<&str> { vec!["type", "typeof", "info", "structure"] } } #[derive(Clone, Copy)] struct Options { no_collect: bool, detailed: bool, } fn run( engine_state: Option<&EngineState>, call: &Call, input: PipelineData, options: Options, ) -> Result<PipelineData, ShellError> { let head = call.head; let metadata = input.metadata(); let description = match input { PipelineData::ByteStream(stream, ..) => { let type_ = stream.type_().describe(); let description = if options.detailed { let origin = match stream.source() { ByteStreamSource::Read(_) => "unknown", ByteStreamSource::File(_) => "file", #[cfg(feature = "os")] ByteStreamSource::Child(_) => "external", }; Value::record( record! { "type" => Value::string("bytestream", head), "detailed_type" => Value::string(type_, head), "rust_type" => Value::string(type_of(&stream), head), "origin" => Value::string(origin, head), "metadata" => metadata_to_value(metadata, head), }, head, ) } else { Value::string(type_, head) }; if !options.no_collect { stream.drain()?; } description } PipelineData::ListStream(stream, ..) => { let type_ = type_of(&stream); if options.detailed { let subtype = if options.no_collect { Value::string("any", head) } else { describe_value(stream.into_debug_value(), head, engine_state) }; Value::record( record! { "type" => Value::string("stream", head), "detailed_type" => Value::string("list stream", head), "rust_type" => Value::string(type_, head), "origin" => Value::string("nushell", head), "subtype" => subtype, "metadata" => metadata_to_value(metadata, head), }, head, ) } else if options.no_collect { Value::string("stream", head) } else { let value = stream.into_debug_value(); let base_description = value.get_type().to_string(); Value::string(format!("{base_description} (stream)"), head) } } PipelineData::Value(value, ..) => { if !options.detailed { Value::string(value.get_type().to_string(), head) } else { describe_value(value, head, engine_state) } } PipelineData::Empty => Value::string(Type::Nothing.to_string(), head), }; Ok(description.into_pipeline_data()) } enum Description { Record(Record), } impl Description { fn into_value(self, span: Span) -> Value { match self { Description::Record(record) => Value::record(record, span), } } } fn describe_value(value: Value, head: Span, engine_state: Option<&EngineState>) -> Value { let Description::Record(record) = describe_value_inner(value, head, engine_state); Value::record(record, head) } fn type_of<T>(_: &T) -> String { type_name::<T>().to_string() } fn describe_value_inner( mut value: Value, head: Span, engine_state: Option<&EngineState>, ) -> Description { let value_type = value.get_type().to_string(); match value { Value::Bool { val, .. } => Description::Record(record! { "type" => Value::string("bool", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::Int { val, .. } => Description::Record(record! { "type" => Value::string("int", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::Float { val, .. } => Description::Record(record! { "type" => Value::string("float", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::Filesize { val, .. } => Description::Record(record! { "type" => Value::string("filesize", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::Duration { val, .. } => Description::Record(record! { "type" => Value::string("duration", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::Date { val, .. } => Description::Record(record! { "type" => Value::string("datetime", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::Range { ref val, .. } => Description::Record(record! { "type" => Value::string("range", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::String { ref val, .. } => Description::Record(record! { "type" => Value::string("string", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::Glob { ref val, .. } => Description::Record(record! { "type" => Value::string("glob", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::Nothing { .. } => Description::Record(record! { "type" => Value::string("nothing", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string("", head), "value" => value, }), Value::Record { ref val, .. } => { let mut columns = val.clone().into_owned(); for (_, val) in &mut columns { *val = describe_value_inner(std::mem::take(val), head, engine_state).into_value(head); } Description::Record(record! { "type" => Value::string("record", head), "detailed_type" => Value::string(value_type, head), "columns" => Value::record(columns.clone(), head), "rust_type" => Value::string(type_of(&val), head), }) } Value::List { ref mut vals, .. } => { for val in &mut *vals { *val = describe_value_inner(std::mem::take(val), head, engine_state).into_value(head); } Description::Record(record! { "type" => Value::string("list", head), "detailed_type" => Value::string(value_type, head), "length" => Value::int(vals.len() as i64, head), "rust_type" => Value::string(type_of(&vals), head), "value" => value, }) } Value::Closure { ref val, .. } => { let block = engine_state.map(|engine_state| engine_state.get_block(val.block_id)); let mut record = record! { "type" => Value::string("closure", head), "detailed_type" => Value::string(value_type, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }; if let Some(block) = block { record.push( "signature", Value::record( record! { "name" => Value::string(block.signature.name.clone(), head), "category" => Value::string(block.signature.category.to_string(), head), }, head, ), ); } Description::Record(record) } Value::Error { ref error, .. } => Description::Record(record! { "type" => Value::string("error", head), "detailed_type" => Value::string(value_type, head), "subtype" => Value::string(error.to_string(), head), "rust_type" => Value::string(type_of(&error), head), "value" => value, }), Value::Binary { ref val, .. } => Description::Record(record! { "type" => Value::string("binary", head), "detailed_type" => Value::string(value_type, head), "length" => Value::int(val.len() as i64, head), "rust_type" => Value::string(type_of(&val), head), "value" => value, }), Value::CellPath { ref val, .. } => Description::Record(record! { "type" => Value::string("cell-path", head), "detailed_type" => Value::string(value_type, head), "length" => Value::int(val.members.len() as i64, head), "rust_type" => Value::string(type_of(&val), head), "value" => value }), Value::Custom { ref val, .. } => Description::Record(record! { "type" => Value::string("custom", head), "detailed_type" => Value::string(value_type, head), "subtype" => Value::string(val.type_name(), head), "rust_type" => Value::string(type_of(&val), head), "value" => match val.to_base_value(head) { Ok(base_value) => base_value, Err(err) => Value::error(err, head), } }), } } fn metadata_to_value(metadata: Option<PipelineMetadata>, head: Span) -> Value { if let Some(metadata) = metadata { let data_source = Value::string(format!("{:?}", metadata.data_source), head); Value::record(record! { "data_source" => data_source }, head) } else { Value::nothing(head) } } #[cfg(test)] mod test { #[test] fn test_examples() { use super::Describe; use crate::test_examples; test_examples(Describe {}) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/src/core_commands/let_.rs
crates/nu-cmd-lang/src/core_commands/let_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Let; impl Command for Let { fn name(&self) -> &str { "let" } fn description(&self) -> &str { "Create a variable and give it a value." } fn signature(&self) -> nu_protocol::Signature { Signature::build("let") .input_output_types(vec![(Type::Any, Type::Nothing)]) .allow_variants_without_examples(true) .required("var_name", SyntaxShape::VarWithOptType, "Variable name.") .optional( "initial_value", SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)), "Equals sign followed by value.", ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html"# } fn command_type(&self) -> CommandType { CommandType::Keyword } fn search_terms(&self) -> Vec<&str> { vec!["set", "const"] } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // This is compiled specially by the IR compiler. The code here is never used when // running in IR mode. eprintln!( "Tried to execute 'run' for the 'let' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Set a variable to a value", example: "let x = 10", result: None, }, Example { description: "Set a variable to the result of an expression", example: "let x = 10 + 100", result: None, }, Example { description: "Set a variable based on the condition", example: "let x = if false { -1 } else { 1 }", result: None, }, Example { description: "Set a variable to the output of a pipeline", example: "ls | let files", result: None, }, ] } } #[cfg(test)] mod test { use nu_protocol::engine::CommandType; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Let {}) } #[test] fn test_command_type() { assert!(matches!(Let.command_type(), CommandType::Keyword)); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false