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-cmd-lang/src/core_commands/while_.rs
crates/nu-cmd-lang/src/core_commands/while_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct While; impl Command for While { fn name(&self) -> &str { "while" } fn description(&self) -> &str { "Conditionally run a block in a loop." } fn signature(&self) -> nu_protocol::Signature { Signature::build("while") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required("cond", SyntaxShape::MathExpression, "Condition to check.") .required( "block", SyntaxShape::Block, "Block to loop if check succeeds.", ) .category(Category::Core) } fn search_terms(&self) -> Vec<&str> { vec!["loop"] } 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 'while' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Loop while a condition is true", example: "mut x = 0; while $x < 10 { $x = $x + 1 }", result: None, }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(While {}) } }
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/mod.rs
crates/nu-cmd-lang/src/core_commands/mod.rs
mod alias; mod attr; mod break_; mod collect; mod const_; mod continue_; mod def; mod describe; mod do_; mod echo; mod error; mod error_make; mod export; mod export_alias; mod export_const; mod export_def; mod export_extern; mod export_module; mod export_use; mod extern_; mod for_; mod hide; mod hide_env; mod if_; mod ignore; mod let_; mod loop_; mod match_; mod module; mod mut_; pub(crate) mod overlay; mod return_; mod scope; mod try_; mod use_; mod version; mod while_; pub use alias::Alias; pub use attr::*; pub use break_::Break; pub use collect::Collect; pub use const_::Const; pub use continue_::Continue; pub use def::Def; pub use describe::Describe; pub use do_::Do; pub use echo::Echo; pub use error::Error; pub use error_make::ErrorMake; pub use export::ExportCommand; pub use export_alias::ExportAlias; pub use export_const::ExportConst; pub use export_def::ExportDef; pub use export_extern::ExportExtern; pub use export_module::ExportModule; pub use export_use::ExportUse; pub use extern_::Extern; pub use for_::For; pub use hide::Hide; pub use hide_env::HideEnv; pub use if_::If; pub use ignore::Ignore; pub use let_::Let; pub use loop_::Loop; pub use match_::Match; pub use module::Module; pub use mut_::Mut; pub use overlay::*; pub use return_::Return; pub use scope::*; pub use try_::Try; pub use use_::Use; pub use version::{VERSION_NU_FEATURES, Version}; pub use while_::While;
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/alias.rs
crates/nu-cmd-lang/src/core_commands/alias.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Alias; impl Command for Alias { fn name(&self) -> &str { "alias" } fn description(&self) -> &str { "Alias a command (with optional flags) to a new name." } fn signature(&self) -> nu_protocol::Signature { Signature::build("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", example: "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/def.rs
crates/nu-cmd-lang/src/core_commands/def.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Def; impl Command for Def { fn name(&self) -> &str { "def" } fn description(&self) -> &str { "Define a custom command." } fn signature(&self) -> nu_protocol::Signature { Signature::build("def") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .required("def_name", SyntaxShape::String, "Command name.") .required("params", SyntaxShape::Signature, "Parameters.") .required("block", SyntaxShape::Closure(None), "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 command and run it", example: r#"def say-hi [] { echo 'hi' }; say-hi"#, result: Some(Value::test_string("hi")), }, Example { description: "Define a command and run it with parameter(s)", example: r#"def say-sth [sth: string] { echo $sth }; say-sth hi"#, result: Some(Value::test_string("hi")), }, Example { description: "Set environment variable by call a custom command", example: r#"def --env foo [] { $env.BAR = "BAZ" }; foo; $env.BAR"#, result: Some(Value::test_string("BAZ")), }, Example { description: "cd affects the environment, so '--env' is required to change directory from within a command", example: r#"def --env gohome [] { cd ~ }; gohome; $env.PWD == ('~' | path expand)"#, result: Some(Value::test_string("true")), }, Example { description: "Define a custom wrapper for an external command", example: r#"def --wrapped my-echo [...rest] { ^echo ...$rest }; my-echo -e 'spam\tspam'"#, result: Some(Value::test_string("spam\tspam")), }, Example { description: "Define a custom command with a type signature. Passing a non-int value will result in an error", example: r#"def only_int []: int -> int { $in }; 42 | only_int"#, result: Some(Value::test_int(42)), }, ] } }
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/for_.rs
crates/nu-cmd-lang/src/core_commands/for_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct For; impl Command for For { fn name(&self) -> &str { "for" } fn description(&self) -> &str { "Loop over a range." } fn signature(&self) -> nu_protocol::Signature { Signature::build("for") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required( "var_name", SyntaxShape::VarWithOptType, "Name of the looping variable.", ) .required( "range", SyntaxShape::Keyword(b"in".to_vec(), Box::new(SyntaxShape::Any)), "Range of the loop.", ) .required("block", SyntaxShape::Block, "The block to run.") .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 'for' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Print the square of each integer", example: "for x in [1 2 3] { print ($x * $x) }", result: None, }, Example { description: "Work with elements of a range", example: "for $x in 1..3 { print $x }", result: None, }, Example { description: "Number each item and print a message", example: r#"for $it in (['bob' 'fred'] | enumerate) { print $"($it.index) is ($it.item)" }"#, result: None, }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(For {}) } }
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.rs
crates/nu-cmd-lang/src/core_commands/export.rs
use nu_engine::{command_prelude::*, get_full_help}; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct ExportCommand; impl Command for ExportCommand { fn name(&self) -> &str { "export" } fn signature(&self) -> Signature { Signature::build("export") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .category(Category::Core) } fn description(&self) -> &str { "Export definitions or environment variables from a module." } 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(Value::string(get_full_help(self, engine_state, stack), call.head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Export a definition from a module", example: r#"module utils { export def my-command [] { "hello" } }; use utils my-command; my-command"#, result: Some(Value::test_string("hello")), }] } 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_use.rs
crates/nu-cmd-lang/src/core_commands/export_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 ExportUse; impl Command for ExportUse { fn name(&self) -> &str { "export use" } fn description(&self) -> &str { "Use definitions from a module and export them from this module." } fn signature(&self) -> nu_protocol::Signature { Signature::build("export use") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .required("module", SyntaxShape::String, "Module or module file.") .rest( "members", SyntaxShape::Any, "Which members of the module to import.", ) .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, 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: "Re-export a command from another module", example: r#"module spam { export def foo [] { "foo" } } module eggs { export use spam foo } use eggs foo foo "#, result: Some(Value::test_string("foo")), }] } 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/const_.rs
crates/nu-cmd-lang/src/core_commands/const_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Const; impl Command for Const { fn name(&self) -> &str { "const" } fn description(&self) -> &str { "Create a parse-time constant." } fn signature(&self) -> nu_protocol::Signature { Signature::build("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 search_terms(&self) -> Vec<&str> { vec!["set", "let"] } 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 'const' command: this code path should never be reached in IR mode" ); unreachable!() } fn run_const( &self, _working_set: &StateWorkingSet, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(PipelineData::empty()) } fn is_const(&self) -> bool { true } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create a new parse-time constant.", example: "const x = 10", result: None, }, Example { description: "Create a composite constant value", example: "const x = { a: 10, b: 20 }", result: None, }, ] } } #[cfg(test)] mod test { use nu_protocol::engine::CommandType; use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Const {}) } #[test] fn test_command_type() { assert!(matches!(Const.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/export_extern.rs
crates/nu-cmd-lang/src/core_commands/export_extern.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct ExportExtern; impl Command for ExportExtern { fn name(&self) -> &str { "export extern" } fn description(&self) -> &str { "Define an extern and export it from a module." } fn signature(&self) -> nu_protocol::Signature { Signature::build("export 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: "Export the signature for an external command", example: r#"export extern echo [text: string]"#, result: None, }] } fn search_terms(&self) -> Vec<&str> { vec!["signature", "module", "declare"] } }
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/loop_.rs
crates/nu-cmd-lang/src/core_commands/loop_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Loop; impl Command for Loop { fn name(&self) -> &str { "loop" } fn description(&self) -> &str { "Run a block in a loop." } fn signature(&self) -> nu_protocol::Signature { Signature::build("loop") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required("block", SyntaxShape::Block, "Block to loop.") .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 'loop' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Loop while a condition is true", example: "mut x = 0; loop { if $x > 10 { break }; $x = $x + 1 }; $x", result: Some(Value::test_int(11)), }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(Loop {}) } }
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/continue_.rs
crates/nu-cmd-lang/src/core_commands/continue_.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Continue; impl Command for Continue { fn name(&self) -> &str { "continue" } fn description(&self) -> &str { "Continue a loop from the next iteration." } fn signature(&self) -> nu_protocol::Signature { Signature::build("continue") .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 continue 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 'continue' command: this code path should never be reached in IR mode" ); unreachable!() } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Continue a loop from the next iteration", example: r#"for i in 1..10 { if $i == 5 { continue }; print $i }"#, 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/scope/externs.rs
crates/nu-cmd-lang/src/core_commands/scope/externs.rs
use nu_engine::{command_prelude::*, scope::ScopeData}; #[derive(Clone)] pub struct ScopeExterns; impl Command for ScopeExterns { fn name(&self) -> &str { "scope externs" } fn signature(&self) -> Signature { Signature::build("scope externs") .input_output_types(vec![(Type::Nothing, Type::Any)]) .allow_variants_without_examples(true) .category(Category::Core) } fn description(&self) -> &str { "Output info on the known externals in the current scope." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let mut scope_data = ScopeData::new(engine_state, stack); scope_data.populate_decls(); Ok(Value::list(scope_data.collect_externs(head), head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Show the known externals in the current scope", example: "scope externs", result: None, }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ScopeExterns {}) } }
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/scope/variables.rs
crates/nu-cmd-lang/src/core_commands/scope/variables.rs
use nu_engine::{command_prelude::*, scope::ScopeData}; #[derive(Clone)] pub struct ScopeVariables; impl Command for ScopeVariables { fn name(&self) -> &str { "scope variables" } fn signature(&self) -> Signature { Signature::build("scope variables") .input_output_types(vec![(Type::Nothing, Type::Any)]) .allow_variants_without_examples(true) .category(Category::Core) } fn description(&self) -> &str { "Output info on the variables in the current scope." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let mut scope_data = ScopeData::new(engine_state, stack); scope_data.populate_vars(); Ok(Value::list(scope_data.collect_vars(head), head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Show the variables in the current scope", example: "scope variables", result: None, }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ScopeVariables {}) } }
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/scope/command.rs
crates/nu-cmd-lang/src/core_commands/scope/command.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Scope; impl Command for Scope { fn name(&self) -> &str { "scope" } fn signature(&self) -> Signature { Signature::build("scope") .category(Category::Core) .input_output_types(vec![(Type::Nothing, Type::String)]) .allow_variants_without_examples(true) } fn description(&self) -> &str { "Commands for getting info about what is in scope." } 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/scope/modules.rs
crates/nu-cmd-lang/src/core_commands/scope/modules.rs
use nu_engine::{command_prelude::*, scope::ScopeData}; #[derive(Clone)] pub struct ScopeModules; impl Command for ScopeModules { fn name(&self) -> &str { "scope modules" } fn signature(&self) -> Signature { Signature::build("scope modules") .input_output_types(vec![(Type::Nothing, Type::Any)]) .allow_variants_without_examples(true) .category(Category::Core) } fn description(&self) -> &str { "Output info on the modules in the current scope." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let mut scope_data = ScopeData::new(engine_state, stack); scope_data.populate_modules(); Ok(Value::list(scope_data.collect_modules(head), head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Show the modules in the current scope", example: "scope modules", result: None, }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ScopeModules {}) } }
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/scope/commands.rs
crates/nu-cmd-lang/src/core_commands/scope/commands.rs
use nu_engine::{command_prelude::*, scope::ScopeData}; #[derive(Clone)] pub struct ScopeCommands; impl Command for ScopeCommands { fn name(&self) -> &str { "scope commands" } fn signature(&self) -> Signature { Signature::build("scope commands") .input_output_types(vec![(Type::Nothing, Type::List(Box::new(Type::Any)))]) .allow_variants_without_examples(true) .category(Category::Core) } fn description(&self) -> &str { "Output info on the commands in the current scope." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let mut scope_data = ScopeData::new(engine_state, stack); scope_data.populate_decls(); Ok(Value::list(scope_data.collect_commands(head), head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Show the commands in the current scope", example: "scope commands", result: None, }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ScopeCommands {}) } }
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/scope/mod.rs
crates/nu-cmd-lang/src/core_commands/scope/mod.rs
mod aliases; mod command; mod commands; mod engine_stats; mod externs; mod modules; mod variables; pub use aliases::*; pub use command::*; pub use commands::*; pub use engine_stats::*; pub use externs::*; pub use modules::*; pub use variables::*;
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/scope/engine_stats.rs
crates/nu-cmd-lang/src/core_commands/scope/engine_stats.rs
use nu_engine::{command_prelude::*, scope::ScopeData}; #[derive(Clone)] pub struct ScopeEngineStats; impl Command for ScopeEngineStats { fn name(&self) -> &str { "scope engine-stats" } fn signature(&self) -> Signature { Signature::build("scope engine-stats") .input_output_types(vec![(Type::Nothing, Type::Any)]) .allow_variants_without_examples(true) .category(Category::Core) } fn description(&self) -> &str { "Output stats on the engine in the current state." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let span = call.head; let scope_data = ScopeData::new(engine_state, stack); Ok(scope_data.collect_engine_state(span).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Show the stats on the current engine state", example: "scope engine-stats", result: None, }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ScopeEngineStats {}) } }
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/scope/aliases.rs
crates/nu-cmd-lang/src/core_commands/scope/aliases.rs
use nu_engine::{command_prelude::*, scope::ScopeData}; #[derive(Clone)] pub struct ScopeAliases; impl Command for ScopeAliases { fn name(&self) -> &str { "scope aliases" } fn signature(&self) -> Signature { Signature::build("scope aliases") .input_output_types(vec![(Type::Nothing, Type::Any)]) .allow_variants_without_examples(true) .category(Category::Core) } fn description(&self) -> &str { "Output info on the aliases in the current scope." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let head = call.head; let mut scope_data = ScopeData::new(engine_state, stack); scope_data.populate_decls(); Ok(Value::list(scope_data.collect_aliases(head), head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Show the aliases in the current scope", example: "scope aliases", result: None, }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(ScopeAliases {}) } }
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/overlay/use_.rs
crates/nu-cmd-lang/src/core_commands/overlay/use_.rs
use nu_engine::{ command_prelude::*, find_in_dirs_env, get_dirs_var_from_call, get_eval_block, redirect_env, }; use nu_parser::trim_quotes_str; use nu_protocol::{ModuleId, ast::Expr, engine::CommandType}; use std::path::Path; #[derive(Clone)] pub struct OverlayUse; impl Command for OverlayUse { fn name(&self) -> &str { "overlay use" } fn description(&self) -> &str { "Use definitions from a module as an overlay." } fn signature(&self) -> nu_protocol::Signature { Signature::build("overlay use") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required( "name", SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]), "Module name to use overlay for (`null` for no-op).", ) .optional( "as", SyntaxShape::Keyword(b"as".to_vec(), Box::new(SyntaxShape::String)), "`as` keyword followed by a new name.", ) .switch( "prefix", "Prepend module name to the imported commands and aliases", Some('p'), ) .switch( "reload", "If the overlay already exists, reload its definitions and environment.", Some('r'), ) .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, caller_stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let noop = call.get_parser_info(caller_stack, "noop"); if noop.is_some() { return Ok(PipelineData::empty()); } let name_arg: Spanned<String> = call.req(engine_state, caller_stack, 0)?; let name_arg_item = trim_quotes_str(&name_arg.item); let maybe_origin_module_id: Option<ModuleId> = if let Some(overlay_expr) = call.get_parser_info(caller_stack, "overlay_expr") { if let Expr::Overlay(module_id) = &overlay_expr.expr { *module_id } else { return Err(ShellError::NushellFailedSpanned { msg: "Not an overlay".to_string(), label: "requires an overlay (path or a string)".to_string(), span: overlay_expr.span, }); } } else { return Err(ShellError::NushellFailedSpanned { msg: "Missing positional".to_string(), label: "missing required overlay".to_string(), span: call.head, }); }; let overlay_name = if let Some(name) = call.opt(engine_state, caller_stack, 1)? { name } else if engine_state .find_overlay(name_arg_item.as_bytes()) .is_some() { name_arg_item.to_string() } else if let Some(os_str) = Path::new(name_arg_item).file_stem() { if let Some(name) = os_str.to_str() { name.to_string() } else { return Err(ShellError::NonUtf8 { span: name_arg.span, }); } } else { return Err(ShellError::OverlayNotFoundAtRuntime { overlay_name: (name_arg_item.to_string()), span: name_arg.span, }); }; if let Some(module_id) = maybe_origin_module_id { // Add environment variables only if (determined by parser): // a) adding a new overlay // b) refreshing an active overlay (the origin module changed) let module = engine_state.get_module(module_id); // in such case, should also make sure that PWD is not restored in old overlays. let cwd = caller_stack.get_env_var(engine_state, "PWD").cloned(); // Evaluate the export-env block (if any) and keep its environment if let Some(block_id) = module.env_block { let maybe_file_path_or_dir = find_in_dirs_env( name_arg_item, engine_state, caller_stack, get_dirs_var_from_call(caller_stack, call), )?; let block = engine_state.get_block(block_id); let mut callee_stack = caller_stack .gather_captures(engine_state, &block.captures) .reset_pipes(); if let Some(path) = &maybe_file_path_or_dir { // Set the currently evaluated directory, if the argument is a valid path let parent = if path.is_dir() { path.clone() } else { let mut parent = path.clone(); parent.pop(); 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); let _ = eval_block(engine_state, &mut callee_stack, block, input)?; // The export-env block should see the env vars *before* activating this overlay caller_stack.add_overlay(overlay_name); // make sure that PWD is not restored in old overlays. if let Some(cwd) = cwd { caller_stack.add_env_var("PWD".to_string(), cwd); } // Merge the block's environment to the current stack redirect_env(engine_state, caller_stack, &callee_stack); } else { caller_stack.add_overlay(overlay_name); // make sure that PWD is not restored in old overlays. if let Some(cwd) = cwd { caller_stack.add_env_var("PWD".to_string(), cwd); } } } else { caller_stack.add_overlay(overlay_name); caller_stack.update_config(engine_state)?; } Ok(PipelineData::empty()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Create an overlay from a module", example: r#"module spam { export def foo [] { "foo" } } overlay use spam foo"#, result: None, }, Example { description: "Create an overlay from a module and rename it", example: r#"module spam { export def foo [] { "foo" } } overlay use spam as spam_new foo"#, result: None, }, Example { description: "Create an overlay with a prefix", example: r#"'export def foo { "foo" }' overlay use --prefix spam spam foo"#, result: None, }, Example { description: "Create an overlay from a file", example: r#"'export-env { $env.FOO = "foo" }' | save spam.nu overlay use spam.nu $env.FOO"#, result: None, }, ] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(OverlayUse {}) } }
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/overlay/command.rs
crates/nu-cmd-lang/src/core_commands/overlay/command.rs
use nu_engine::{command_prelude::*, get_full_help}; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct Overlay; impl Command for Overlay { fn name(&self) -> &str { "overlay" } fn signature(&self) -> Signature { Signature::build("overlay") .category(Category::Core) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Commands for manipulating overlays." } fn extra_description(&self) -> &str { r#"This command is a parser keyword. For details, check: https://www.nushell.sh/book/thinking_in_nu.html You must use one of the following subcommands. Using this command as-is will only produce this help message."# } fn command_type(&self) -> CommandType { CommandType::Keyword } 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/overlay/hide.rs
crates/nu-cmd-lang/src/core_commands/overlay/hide.rs
use nu_engine::command_prelude::*; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct OverlayHide; impl Command for OverlayHide { fn name(&self) -> &str { "overlay hide" } fn description(&self) -> &str { "Hide an active overlay." } fn signature(&self) -> nu_protocol::Signature { Signature::build("overlay hide") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .optional("name", SyntaxShape::String, "Overlay to hide.") .switch( "keep-custom", "Keep all newly added commands and aliases in the next activated overlay.", Some('k'), ) .named( "keep-env", SyntaxShape::List(Box::new(SyntaxShape::String)), "List of environment variables to keep in the next activated overlay", Some('e'), ) .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> { let overlay_name: Spanned<String> = if let Some(name) = call.opt(engine_state, stack, 0)? { name } else { Spanned { item: stack.last_overlay_name()?, span: call.head, } }; if !stack.is_overlay_active(&overlay_name.item) { return Err(ShellError::OverlayNotFoundAtRuntime { overlay_name: overlay_name.item, span: overlay_name.span, }); } let keep_env: Option<Vec<Spanned<String>>> = call.get_flag(engine_state, stack, "keep-env")?; let env_vars_to_keep = if let Some(env_var_names_to_keep) = keep_env { let mut env_vars_to_keep = vec![]; for name in env_var_names_to_keep.into_iter() { match stack.get_env_var(engine_state, &name.item) { Some(val) => env_vars_to_keep.push((name.item, val.clone())), None => { return Err(ShellError::EnvVarNotFoundAtRuntime { envvar_name: name.item, span: name.span, }); } } } env_vars_to_keep } else { vec![] }; // also restore env vars which has been hidden let env_vars_to_restore = stack.get_hidden_env_vars(&overlay_name.item, engine_state); stack.remove_overlay(&overlay_name.item); for (name, val) in env_vars_to_restore { stack.add_env_var(name, val); } for (name, val) in env_vars_to_keep { stack.add_env_var(name, val); } stack.update_config(engine_state)?; Ok(PipelineData::empty()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Keep a custom command after hiding the overlay", example: r#"module spam { export def foo [] { "foo" } } overlay use spam def bar [] { "bar" } overlay hide spam --keep-custom bar "#, result: None, }, Example { description: "Hide an overlay created from a file", example: r#"'export alias f = "foo"' | save spam.nu overlay use spam.nu overlay hide spam"#, result: None, }, Example { description: "Hide the last activated overlay", example: r#"module spam { export-env { $env.FOO = "foo" } } overlay use spam overlay hide"#, result: None, }, Example { description: "Keep the current working directory when removing an overlay", example: r#"overlay new spam cd some-dir overlay hide --keep-env [ PWD ] spam"#, 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/overlay/list.rs
crates/nu-cmd-lang/src/core_commands/overlay/list.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct OverlayList; impl Command for OverlayList { fn name(&self) -> &str { "overlay list" } fn description(&self) -> &str { "List all overlays with their active status." } fn signature(&self) -> nu_protocol::Signature { Signature::build("overlay list") .category(Category::Core) .input_output_types(vec![( Type::Nothing, Type::Table( vec![ ("name".to_string(), Type::String), ("active".to_string(), Type::Bool), ] .into(), ), )]) } fn extra_description(&self) -> &str { "The overlays are listed in the order they were activated. Hidden overlays are listed first, followed by active overlays listed in the order that they were activated. `last` command will always give the top active overlay" } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { // get active overlay iterator let active_overlays = stack .active_overlays .iter() .map(|overlay| (overlay.clone(), true)); // Get all overlay names from engine state let output_rows: Vec<Value> = engine_state .scope .overlays .iter() .filter_map(|(name, _)| { let name = String::from_utf8_lossy(name).to_string(); if stack .active_overlays .iter() .any(|active_name| active_name == &name) { None } else { Some((name, false)) } }) .chain(active_overlays) .map(|(name, active)| { Value::record( record! { "name" => Value::string(name.to_owned(), call.head), "active" => Value::bool(active, call.head), }, call.head, ) }) .collect(); Ok(Value::list(output_rows, call.head).into_pipeline_data()) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "List all overlays with their active status", example: r#"module spam { export def foo [] { "foo" } } overlay use spam overlay list"#, result: Some(Value::test_list(vec![Value::test_record(record! { "name" => Value::test_string("spam"), "active" => Value::test_bool(true), })])), }, Example { description: "Get overlay status after hiding", example: r#"module spam { export def foo [] { "foo" } } overlay use spam overlay hide spam overlay list | where name == "spam""#, result: Some(Value::test_list(vec![Value::test_record(record! { "name" => Value::test_string("spam"), "active" => 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/overlay/mod.rs
crates/nu-cmd-lang/src/core_commands/overlay/mod.rs
mod command; mod hide; mod list; mod new; mod use_; pub use command::Overlay; pub use hide::OverlayHide; pub use list::OverlayList; pub use new::OverlayNew; pub use use_::OverlayUse;
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/overlay/new.rs
crates/nu-cmd-lang/src/core_commands/overlay/new.rs
use nu_engine::{command_prelude::*, redirect_env}; use nu_protocol::engine::CommandType; #[derive(Clone)] pub struct OverlayNew; impl Command for OverlayNew { fn name(&self) -> &str { "overlay new" } fn description(&self) -> &str { "Create an empty overlay." } fn signature(&self) -> nu_protocol::Signature { Signature::build("overlay new") .input_output_types(vec![(Type::Nothing, Type::Nothing)]) .allow_variants_without_examples(true) .required("name", SyntaxShape::String, "Name of the overlay.") .switch( "reload", "If the overlay already exists, reload its environment.", Some('r'), ) // TODO: // .switch( // "prefix", // "Prepend module name to the imported symbols", // Some('p'), // ) .category(Category::Core) } fn extra_description(&self) -> &str { r#"The command will first create an empty module, then add it as an overlay. 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> { let name_arg: Spanned<String> = call.req(engine_state, caller_stack, 0)?; let reload = call.has_flag(engine_state, caller_stack, "reload")?; if reload { let callee_stack = caller_stack.clone(); caller_stack.add_overlay(name_arg.item); redirect_env(engine_state, caller_stack, &callee_stack); } else { caller_stack.add_overlay(name_arg.item); } Ok(PipelineData::empty()) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Create an empty overlay", example: r#"overlay new spam"#, result: None, }] } } #[cfg(test)] mod test { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(OverlayNew {}) } }
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/attr/complete.rs
crates/nu-cmd-lang/src/core_commands/attr/complete.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct AttrComplete; impl Command for AttrComplete { fn name(&self) -> &str { "attr complete" } fn signature(&self) -> Signature { Signature::build("attr complete") .input_output_type(Type::Nothing, Type::String) .allow_variants_without_examples(true) .required( "completer", SyntaxShape::String, "Name of the completion command.", ) .category(Category::Core) } fn description(&self) -> &str { "Attribute for using another command as a completion source for all arguments." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let arg: Spanned<String> = call.req(engine_state, stack, 0)?; run_impl(arg) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let arg: Spanned<String> = call.req_const(working_set, 0)?; run_impl(arg) } fn is_const(&self) -> bool { true } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Use another command as completion source", example: "\ def complete-foo [spans: list<string>] {\n \ [bar baz qux spam eggs] | where $it not-in $spans\n\ }\n\n\ @complete 'complete-foo'\n\ def foo [...args] { $args }\ ", result: None, }] } } fn run_impl(Spanned { item, span }: Spanned<String>) -> Result<PipelineData, ShellError> { Ok(Value::string(item, span).into_pipeline_data()) } #[derive(Clone)] pub struct AttrCompleteExternal; impl Command for AttrCompleteExternal { fn name(&self) -> &str { "attr complete external" } fn signature(&self) -> Signature { Signature::build("attr complete external") .input_output_type(Type::Nothing, Type::Nothing) .allow_variants_without_examples(true) .category(Category::Core) } fn description(&self) -> &str { "Attribute for enabling use of the external completer for internal commands." } fn run( &self, _: &EngineState, _: &mut Stack, _: &Call, _: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(PipelineData::empty()) } fn run_const( &self, _: &StateWorkingSet, _: &Call, _: PipelineData, ) -> Result<PipelineData, ShellError> { Ok(PipelineData::empty()) } fn is_const(&self) -> bool { true } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Use the external completer for a wrapper command", example: "\ @complete external\n\ def --wrapped jc [...args] {\n \ ^jc ...$args | from json\n\ }\ ", 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/attr/search_terms.rs
crates/nu-cmd-lang/src/core_commands/attr/search_terms.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct AttrSearchTerms; impl Command for AttrSearchTerms { fn name(&self) -> &str { "attr search-terms" } fn signature(&self) -> Signature { Signature::build("attr search-terms") .input_output_type(Type::Nothing, Type::list(Type::String)) .allow_variants_without_examples(true) .rest("terms", SyntaxShape::String, "Search terms.") .category(Category::Core) } fn description(&self) -> &str { "Attribute for adding search terms to custom commands." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let args = call.rest(engine_state, stack, 0)?; Ok(Value::list(args, call.head).into_pipeline_data()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let args = call.rest_const(working_set, 0)?; Ok(Value::list(args, call.head).into_pipeline_data()) } fn is_const(&self) -> bool { true } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Add search terms to a custom command", example: r###"# Double numbers @search-terms multiply times def double []: [number -> number] { $in * 2 }"###, 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/attr/example.rs
crates/nu-cmd-lang/src/core_commands/attr/example.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct AttrExample; impl Command for AttrExample { fn name(&self) -> &str { "attr example" } // TODO: When const closure are available, switch to using them for the `example` argument // rather than a block. That should remove the need for `requires_ast_for_arguments` to be true fn signature(&self) -> Signature { Signature::build("attr example") .input_output_types(vec![( Type::Nothing, Type::Record( [ ("description".into(), Type::String), ("example".into(), Type::String), ] .into(), ), )]) .allow_variants_without_examples(true) .required( "description", SyntaxShape::String, "Description of the example.", ) .required( "example", SyntaxShape::OneOf(vec![SyntaxShape::Block, SyntaxShape::String]), "Example code snippet.", ) .named( "result", SyntaxShape::Any, "Expected output of example.", None, ) .category(Category::Core) } fn description(&self) -> &str { "Attribute for adding examples to custom commands." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let description: Spanned<String> = call.req(engine_state, stack, 0)?; let result: Option<Value> = call.get_flag(engine_state, stack, "result")?; let example_string: Result<String, _> = call.req(engine_state, stack, 1); let example_expr = call .positional_nth(stack, 1) .ok_or(ShellError::MissingParameter { param_name: "example".into(), span: call.head, })?; let working_set = StateWorkingSet::new(engine_state); attr_example_impl( example_expr, example_string, &working_set, call, description, result, ) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let description: Spanned<String> = call.req_const(working_set, 0)?; let result: Option<Value> = call.get_flag_const(working_set, "result")?; let example_string: Result<String, _> = call.req_const(working_set, 1); let example_expr = call.assert_ast_call()? .positional_nth(1) .ok_or(ShellError::MissingParameter { param_name: "example".into(), span: call.head, })?; attr_example_impl( example_expr, example_string, working_set, call, description, result, ) } fn is_const(&self) -> bool { true } fn requires_ast_for_arguments(&self) -> bool { true } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Add examples to custom command", example: r###"# Double numbers @example "double an int" { 2 | double } --result 4 @example "double a float" { 0.25 | double } --result 0.5 def double []: [number -> number] { $in * 2 }"###, result: None, }] } } fn attr_example_impl( example_expr: &nu_protocol::ast::Expression, example_string: Result<String, ShellError>, working_set: &StateWorkingSet<'_>, call: &Call<'_>, description: Spanned<String>, result: Option<Value>, ) -> Result<PipelineData, ShellError> { let example_content = match example_expr.as_block() { Some(block_id) => { let block = working_set.get_block(block_id); let contents = working_set.get_span_contents(block.span.expect("a block must have a span")); let contents = contents .strip_prefix(b"{") .and_then(|x| x.strip_suffix(b"}")) .unwrap_or(contents) .trim_ascii(); String::from_utf8_lossy(contents).into_owned() } None => example_string?, }; let mut rec = record! { "description" => Value::string(description.item, description.span), "example" => Value::string(example_content, example_expr.span), }; if let Some(result) = result { rec.push("result", result); } Ok(Value::record(rec, 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/attr/category.rs
crates/nu-cmd-lang/src/core_commands/attr/category.rs
use nu_engine::command_prelude::*; #[derive(Clone)] pub struct AttrCategory; impl Command for AttrCategory { fn name(&self) -> &str { "attr category" } fn signature(&self) -> Signature { Signature::build("attr category") .input_output_type(Type::Nothing, Type::String) .allow_variants_without_examples(true) .required( "category", SyntaxShape::String, "Category of the custom command.", ) .category(Category::Core) } fn description(&self) -> &str { "Attribute for adding a category to custom commands." } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let arg: String = call.req(engine_state, stack, 0)?; Ok(Value::string(arg, call.head).into_pipeline_data()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let arg: String = call.req_const(working_set, 0)?; Ok(Value::string(arg, call.head).into_pipeline_data()) } fn is_const(&self) -> bool { true } fn examples(&self) -> Vec<Example<'_>> { vec![Example { description: "Add a category to a custom command", example: r###"# Double numbers @category math def double []: [number -> number] { $in * 2 }"###, 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/attr/attr_.rs
crates/nu-cmd-lang/src/core_commands/attr/attr_.rs
use nu_engine::{command_prelude::*, get_full_help}; #[derive(Clone)] pub struct Attr; impl Command for Attr { fn name(&self) -> &str { "attr" } fn signature(&self) -> Signature { Signature::build("attr") .category(Category::Core) .input_output_types(vec![(Type::Nothing, Type::String)]) } fn description(&self) -> &str { "Various attributes for custom commands." } 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/attr/mod.rs
crates/nu-cmd-lang/src/core_commands/attr/mod.rs
mod attr_; mod category; mod complete; mod deprecated; mod example; mod search_terms; pub use attr_::Attr; pub use category::AttrCategory; pub use complete::{AttrComplete, AttrCompleteExternal}; pub use deprecated::AttrDeprecated; pub use example::AttrExample; pub use search_terms::AttrSearchTerms;
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/attr/deprecated.rs
crates/nu-cmd-lang/src/core_commands/attr/deprecated.rs
use nu_cmd_base::WrapCall; use nu_engine::command_prelude::*; #[derive(Clone)] pub struct AttrDeprecated; impl Command for AttrDeprecated { fn name(&self) -> &str { "attr deprecated" } fn signature(&self) -> Signature { Signature::build("attr deprecated") .input_output_type(Type::Nothing, Type::record()) .optional( "message", SyntaxShape::String, "Help message to include with deprecation warning.", ) .named( "flag", SyntaxShape::String, "Mark a flag as deprecated rather than the command", None, ) .named( "since", SyntaxShape::String, "Denote a version when this item was deprecated", Some('s'), ) .named( "remove", SyntaxShape::String, "Denote a version when this item will be removed", Some('r'), ) .param( Flag::new("report") .arg(SyntaxShape::String) .desc("How to warn about this item. One of: first (default), every") .completion(Completion::new_list(&["first", "every"])), ) .category(Category::Core) } fn description(&self) -> &str { "Attribute for marking a command or flag as deprecated." } fn extra_description(&self) -> &str { "\ Mark a command (default) or flag/switch (--flag) as deprecated. \ By default, only the first usage will trigger a deprecation warning.\n\ \n\ A help message can be included to provide more context for the deprecation, \ such as what to use as a replacement.\n\ \n\ Also consider setting the category to deprecated with @category deprecated\ " } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let call = WrapCall::Eval(engine_state, stack, call); Ok(deprecated_record(call)?.into_pipeline_data()) } fn run_const( &self, working_set: &StateWorkingSet, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { let call = WrapCall::ConstEval(working_set, call); Ok(deprecated_record(call)?.into_pipeline_data()) } fn is_const(&self) -> bool { true } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { description: "Add a deprecation warning to a custom command", example: r###"@deprecated def outdated [] {}"###, result: Some(Value::nothing(Span::test_data())), }, Example { description: "Add a deprecation warning with a custom message", example: r###"@deprecated "Use my-new-command instead." @category deprecated def my-old-command [] {}"###, result: Some(Value::string( "Use my-new-command instead.", Span::test_data(), )), }, ] } } fn deprecated_record(call: WrapCall) -> Result<Value, ShellError> { let (call, message): (_, Option<Spanned<String>>) = call.opt(0)?; let (call, flag): (_, Option<Spanned<String>>) = call.get_flag("flag")?; let (call, since): (_, Option<Spanned<String>>) = call.get_flag("since")?; let (call, remove): (_, Option<Spanned<String>>) = call.get_flag("remove")?; let (call, report): (_, Option<Spanned<String>>) = call.get_flag("report")?; let mut record = Record::new(); if let Some(message) = message { record.push("help", Value::string(message.item, message.span)) } if let Some(flag) = flag { record.push("flag", Value::string(flag.item, flag.span)) } if let Some(since) = since { record.push("since", Value::string(since.item, since.span)) } if let Some(remove) = remove { record.push("expected_removal", Value::string(remove.item, remove.span)) } let report = if let Some(Spanned { item, span }) = report { match item.as_str() { "every" => Value::string(item, span), "first" => Value::string(item, span), _ => { return Err(ShellError::IncorrectValue { msg: "The report mode must be one of: every, first".into(), val_span: span, call_span: call.head(), }); } } } else { Value::string("first", call.head()) }; record.push("report", report); Ok(Value::record(record, call.head())) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/tests/main.rs
crates/nu-cmd-lang/tests/main.rs
mod commands;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/tests/commands/mod.rs
crates/nu-cmd-lang/tests/commands/mod.rs
mod attr;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/tests/commands/attr/mod.rs
crates/nu-cmd-lang/tests/commands/attr/mod.rs
mod deprecated;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-cmd-lang/tests/commands/attr/deprecated.rs
crates/nu-cmd-lang/tests/commands/attr/deprecated.rs
use miette::{Diagnostic, LabeledSpan}; use nu_parser::parse; use nu_protocol::engine::StateWorkingSet; #[test] pub fn test_deprecated_attribute() { let engine_state = nu_cmd_lang::create_default_context(); let mut working_set = StateWorkingSet::new(&engine_state); // test deprecation with no message let source = br#" @deprecated def foo [] {} "#; let _ = parse(&mut working_set, None, source, false); // there should be no warning until the command is called assert!(working_set.parse_errors.is_empty()); assert!(working_set.parse_warnings.is_empty()); let source = b"foo"; let _ = parse(&mut working_set, None, source, false); // command called, there should be a deprecation warning assert!(working_set.parse_errors.is_empty()); assert!(!working_set.parse_warnings.is_empty()); let labels: Vec<LabeledSpan> = working_set.parse_warnings[0].labels().unwrap().collect(); let label = labels.first().unwrap().label().unwrap(); assert!(label.contains("foo is deprecated")); working_set.parse_warnings.clear(); // test deprecation with message let source = br#" @deprecated "Use new-command instead" def old-command [] {} old-command "#; let _ = parse(&mut working_set, None, source, false); assert!(working_set.parse_errors.is_empty()); assert!(!working_set.parse_warnings.is_empty()); let help = &working_set.parse_warnings[0].help().unwrap().to_string(); assert!(help.contains("Use new-command instead")); } #[test] pub fn test_deprecated_attribute_flag() { let engine_state = nu_cmd_lang::create_default_context(); let mut working_set = StateWorkingSet::new(&engine_state); let source = br#" @deprecated "Use foo instead of bar" --flag bar @deprecated "Use foo instead of baz" --flag baz def old-command [--foo, --bar, --baz] {} old-command --foo old-command --bar old-command --baz old-command --foo --bar --baz "#; let _ = parse(&mut working_set, None, source, false); assert!(working_set.parse_errors.is_empty()); assert!(!working_set.parse_warnings.is_empty()); let help = &working_set.parse_warnings[0].help().unwrap().to_string(); assert!(help.contains("Use foo instead of bar")); let help = &working_set.parse_warnings[1].help().unwrap().to_string(); assert!(help.contains("Use foo instead of baz")); let help = &working_set.parse_warnings[2].help().unwrap().to_string(); assert!(help.contains("Use foo instead of bar")); let help = &working_set.parse_warnings[3].help().unwrap().to_string(); assert!(help.contains("Use foo instead of baz")); } #[test] pub fn test_deprecated_attribute_since_remove() { let engine_state = nu_cmd_lang::create_default_context(); let mut working_set = StateWorkingSet::new(&engine_state); let source = br#" @deprecated --since 0.10000.0 --remove 1.0 def old-command [] {} old-command "#; let _ = parse(&mut working_set, None, source, false); assert!(working_set.parse_errors.is_empty()); assert!(!working_set.parse_warnings.is_empty()); let labels: Vec<LabeledSpan> = working_set.parse_warnings[0].labels().unwrap().collect(); let label = labels.first().unwrap().label().unwrap(); assert!(label.contains("0.10000.0")); assert!(label.contains("1.0")); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/cool_custom_value.rs
crates/nu_plugin_custom_values/src/cool_custom_value.rs
#![allow(clippy::result_large_err)] use nu_protocol::{ CustomValue, ShellError, Span, Type, Value, ast::{self, Math, Operator}, casing::Casing, }; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct CoolCustomValue { pub(crate) cool: String, } impl CoolCustomValue { pub fn new(content: &str) -> Self { Self { cool: content.to_owned(), } } pub fn into_value(self, span: Span) -> Value { Value::custom(Box::new(self), span) } pub fn try_from_value(value: &Value) -> Result<Self, ShellError> { let span = value.span(); match value { Value::Custom { val, .. } => { if let Some(cool) = val.as_any().downcast_ref::<Self>() { Ok(cool.clone()) } else { Err(ShellError::CantConvert { to_type: "cool".into(), from_type: "non-cool".into(), span, help: None, }) } } x => Err(ShellError::CantConvert { to_type: "cool".into(), from_type: x.get_type().to_string(), span, help: None, }), } } } #[typetag::serde] impl CustomValue for CoolCustomValue { fn clone_value(&self, span: Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { self.typetag_name().to_string() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::string( format!("I used to be a custom value! My data was ({})", self.cool), span, )) } fn follow_path_int( &self, _self_span: Span, index: usize, path_span: Span, optional: bool, ) -> Result<Value, ShellError> { match (index, optional) { (0, _) => Ok(Value::string(&self.cool, path_span)), (_, true) => Ok(Value::nothing(path_span)), _ => Err(ShellError::AccessBeyondEnd { max_idx: 0, span: path_span, }), } } fn follow_path_string( &self, self_span: Span, column_name: String, path_span: Span, optional: bool, casing: Casing, ) -> Result<Value, ShellError> { let column_name = match casing { Casing::Sensitive => column_name, Casing::Insensitive => column_name.to_lowercase(), }; match (column_name.as_str(), optional) { ("cool", _) => Ok(Value::string(&self.cool, path_span)), (_, true) => Ok(Value::nothing(path_span)), _ => Err(ShellError::CantFindColumn { col_name: column_name, span: Some(path_span), src_span: self_span, }), } } fn partial_cmp(&self, other: &Value) -> Option<Ordering> { if let Value::Custom { val, .. } = other { val.as_any() .downcast_ref() .and_then(|other: &CoolCustomValue| PartialOrd::partial_cmp(self, other)) } else { None } } fn operation( &self, lhs_span: Span, operator: ast::Operator, op_span: Span, right: &Value, ) -> Result<Value, ShellError> { match operator { // Append the string inside `cool` Operator::Math(Math::Concatenate) => { if let Some(right) = right .as_custom_value() .ok() .and_then(|c| c.as_any().downcast_ref::<CoolCustomValue>()) { Ok(Value::custom( Box::new(CoolCustomValue { cool: format!("{}{}", self.cool, right.cool), }), op_span, )) } else { Err(ShellError::OperatorUnsupportedType { op: Operator::Math(Math::Concatenate), unsupported: right.get_type(), op_span, unsupported_span: right.span(), help: None, }) } } _ => Err(ShellError::OperatorUnsupportedType { op: Operator::Math(Math::Concatenate), unsupported: Type::Custom(self.type_name().into()), op_span, unsupported_span: lhs_span, help: None, }), } } fn as_any(&self) -> &dyn std::any::Any { self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/second_custom_value.rs
crates/nu_plugin_custom_values/src/second_custom_value.rs
#![allow(clippy::result_large_err)] use nu_protocol::{CustomValue, ShellError, Span, Spanned, Value, shell_error::io::IoError}; use serde::{Deserialize, Serialize}; use std::{cmp::Ordering, path::Path}; #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] pub struct SecondCustomValue { pub(crate) something: String, } impl SecondCustomValue { pub fn new(content: &str) -> Self { Self { something: content.to_owned(), } } pub fn into_value(self, span: Span) -> Value { Value::custom(Box::new(self), span) } pub fn try_from_value(value: &Value) -> Result<Self, ShellError> { let span = value.span(); match value { Value::Custom { val, .. } => match val.as_any().downcast_ref::<Self>() { Some(value) => Ok(value.clone()), None => Err(ShellError::CantConvert { to_type: "cool".into(), from_type: "non-cool".into(), span, help: None, }), }, x => Err(ShellError::CantConvert { to_type: "cool".into(), from_type: x.get_type().to_string(), span, help: None, }), } } } #[typetag::serde] impl CustomValue for SecondCustomValue { fn clone_value(&self, span: nu_protocol::Span) -> Value { Value::custom(Box::new(self.clone()), span) } fn type_name(&self) -> String { self.typetag_name().to_string() } fn to_base_value(&self, span: nu_protocol::Span) -> Result<Value, ShellError> { Ok(Value::string( format!( "I used to be a DIFFERENT custom value! ({})", self.something ), span, )) } fn partial_cmp(&self, other: &Value) -> Option<Ordering> { if let Value::Custom { val, .. } = other { val.as_any() .downcast_ref() .and_then(|other: &SecondCustomValue| PartialOrd::partial_cmp(self, other)) } else { None } } fn as_any(&self) -> &dyn std::any::Any { self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn save(&self, path: Spanned<&Path>, _: Span, save_span: Span) -> Result<(), ShellError> { std::fs::write(path.item, &self.something).map_err(|err| { ShellError::Io(IoError::new_with_additional_context( err, save_span, path.item.to_owned(), format!("Could not save {}", self.type_name()), )) }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/update.rs
crates/nu_plugin_custom_values/src/update.rs
use crate::{ CustomValuePlugin, cool_custom_value::CoolCustomValue, second_custom_value::SecondCustomValue, }; use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, Example, LabeledError, ShellError, Signature, Span, Value}; pub struct Update; impl SimplePluginCommand for Update { type Plugin = CustomValuePlugin; fn name(&self) -> &str { "custom-value update" } fn description(&self) -> &str { "PluginSignature for a plugin that updates a custom value" } fn signature(&self) -> Signature { Signature::build(self.name()).category(Category::Experimental) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "custom-value generate | custom-value update", description: "Update a CoolCustomValue", result: Some(CoolCustomValue::new("abcxyz").into_value(Span::test_data())), }, Example { example: "custom-value generate2 | custom-value update", description: "Update a SecondCustomValue", result: Some(SecondCustomValue::new("xyzabc").into_value(Span::test_data())), }, ] } fn run( &self, _plugin: &CustomValuePlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { if let Ok(mut value) = CoolCustomValue::try_from_value(input) { value.cool += "xyz"; return Ok(value.into_value(call.head)); } if let Ok(mut value) = SecondCustomValue::try_from_value(input) { value.something += "abc"; return Ok(value.into_value(call.head)); } Err(ShellError::CantConvert { to_type: "cool or second".into(), from_type: "non-cool and non-second".into(), span: call.head, help: None, } .into()) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("custom_values", crate::CustomValuePlugin::new().into())? .test_command_examples(&Update) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/handle_update.rs
crates/nu_plugin_custom_values/src/handle_update.rs
use std::sync::atomic; use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{ LabeledError, ShellError, Signature, Spanned, SyntaxShape, Type, Value, engine::Closure, }; use crate::{CustomValuePlugin, handle_custom_value::HandleCustomValue}; pub struct HandleUpdate; impl SimplePluginCommand for HandleUpdate { type Plugin = CustomValuePlugin; fn name(&self) -> &str { "custom-value handle update" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type( Type::Custom("HandleCustomValue".into()), Type::Custom("HandleCustomValue".into()), ) .required( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "the closure to run on the value", ) } fn description(&self) -> &str { "Update the value in a handle and return a new handle with the result" } fn run( &self, plugin: &Self::Plugin, engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { let closure: Spanned<Closure> = call.req(0)?; if let Some(handle) = input .as_custom_value()? .as_any() .downcast_ref::<HandleCustomValue>() { // Find the handle let value = plugin .handles .lock() .map_err(|err| LabeledError::new(err.to_string()))? .get(&handle.0) .cloned(); if let Some(value) = value { // Call the closure with the value let new_value = engine.eval_closure(&closure, vec![value.clone()], Some(value))?; // Generate an id and store in the plugin. let new_id = plugin.counter.fetch_add(1, atomic::Ordering::Relaxed); plugin .handles .lock() .map_err(|err| LabeledError::new(err.to_string()))? .insert(new_id, new_value); Ok(Value::custom( Box::new(HandleCustomValue(new_id)), call.head, )) } else { Err(LabeledError::new("Handle expired") .with_label("this handle is no longer valid", input.span()) .with_help("the plugin may have exited, or there was a bug")) } } else { Err(ShellError::UnsupportedInput { msg: "requires HandleCustomValue".into(), input: format!("got {}", input.get_type()), msg_span: call.head, input_span: input.span(), } .into()) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/handle_get.rs
crates/nu_plugin_custom_values/src/handle_get.rs
use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{LabeledError, ShellError, Signature, Type, Value}; use crate::{CustomValuePlugin, handle_custom_value::HandleCustomValue}; pub struct HandleGet; impl SimplePluginCommand for HandleGet { type Plugin = CustomValuePlugin; fn name(&self) -> &str { "custom-value handle get" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Custom("HandleCustomValue".into()), Type::Any) } fn description(&self) -> &str { "Get a value previously stored in a handle" } fn run( &self, plugin: &Self::Plugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { if let Some(handle) = input .as_custom_value()? .as_any() .downcast_ref::<HandleCustomValue>() { // Find the handle let value = plugin .handles .lock() .map_err(|err| LabeledError::new(err.to_string()))? .get(&handle.0) .cloned(); if let Some(value) = value { Ok(value) } else { Err(LabeledError::new("Handle expired") .with_label("this handle is no longer valid", input.span()) .with_help("the plugin may have exited, or there was a bug")) } } else { Err(ShellError::UnsupportedInput { msg: "requires HandleCustomValue".into(), input: format!("got {}", input.get_type()), msg_span: call.head, input_span: input.span(), } .into()) } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/generate2.rs
crates/nu_plugin_custom_values/src/generate2.rs
use crate::{CustomValuePlugin, second_custom_value::SecondCustomValue}; use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, Example, LabeledError, Signature, Span, SyntaxShape, Value}; pub struct Generate2; impl SimplePluginCommand for Generate2 { type Plugin = CustomValuePlugin; fn name(&self) -> &str { "custom-value generate2" } fn description(&self) -> &str { "PluginSignature for a plugin that generates a different custom value" } fn signature(&self) -> Signature { Signature::build(self.name()) .optional( "closure", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])), "An optional closure to pass the custom value to", ) .category(Category::Experimental) } fn examples(&self) -> Vec<Example<'_>> { vec![ Example { example: "custom-value generate2", description: "Generate a new SecondCustomValue", result: Some(SecondCustomValue::new("xyz").into_value(Span::test_data())), }, Example { example: "custom-value generate2 { print }", description: "Generate a new SecondCustomValue and pass it to a closure", result: None, }, ] } fn run( &self, _plugin: &CustomValuePlugin, engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { let second_custom_value = SecondCustomValue::new("xyz").into_value(call.head); // If we were passed a closure, execute that instead if let Some(closure) = call.opt(0)? { let result = engine.eval_closure( &closure, vec![second_custom_value.clone()], Some(second_custom_value), )?; Ok(result) } else { Ok(second_custom_value) } } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("custom_values", crate::CustomValuePlugin::new().into())? .test_command_examples(&Generate2) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/update_arg.rs
crates/nu_plugin_custom_values/src/update_arg.rs
use crate::{CustomValuePlugin, update::Update}; use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, LabeledError, Signature, SyntaxShape, Value}; pub struct UpdateArg; impl SimplePluginCommand for UpdateArg { type Plugin = CustomValuePlugin; fn name(&self) -> &str { "custom-value update-arg" } fn description(&self) -> &str { "Updates a custom value as an argument" } fn signature(&self) -> Signature { Signature::build(self.name()) .required( "custom_value", SyntaxShape::Any, "the custom value to update", ) .category(Category::Experimental) } fn run( &self, plugin: &CustomValuePlugin, engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { SimplePluginCommand::run(&Update, plugin, engine, call, &call.req(0)?) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/handle_custom_value.rs
crates/nu_plugin_custom_values/src/handle_custom_value.rs
use nu_protocol::{CustomValue, LabeledError, ShellError, Span, Value}; use serde::{Deserialize, Serialize}; /// References a stored handle within the plugin #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HandleCustomValue(pub u64); impl HandleCustomValue { pub fn into_value(self, span: Span) -> Value { Value::custom(Box::new(self), span) } } #[typetag::serde] impl CustomValue for HandleCustomValue { fn clone_value(&self, span: Span) -> Value { self.clone().into_value(span) } fn type_name(&self) -> String { "HandleCustomValue".into() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Err(LabeledError::new("Unsupported operation") .with_label("can't call to_base_value() directly on this", span) .with_help("HandleCustomValue uses custom_value_to_base_value() on the plugin instead") .into()) } fn notify_plugin_on_drop(&self) -> bool { true } fn as_any(&self) -> &dyn std::any::Any { self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/handle_make.rs
crates/nu_plugin_custom_values/src/handle_make.rs
use std::sync::atomic; use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{LabeledError, Signature, Type, Value}; use crate::{CustomValuePlugin, handle_custom_value::HandleCustomValue}; pub struct HandleMake; impl SimplePluginCommand for HandleMake { type Plugin = CustomValuePlugin; fn name(&self) -> &str { "custom-value handle make" } fn signature(&self) -> Signature { Signature::build(self.name()) .input_output_type(Type::Any, Type::Custom("HandleCustomValue".into())) } fn description(&self) -> &str { "Store a value in plugin memory and return a handle to it" } fn run( &self, plugin: &Self::Plugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { // Generate an id and store in the plugin. let new_id = plugin.counter.fetch_add(1, atomic::Ordering::Relaxed); plugin .handles .lock() .map_err(|err| LabeledError::new(err.to_string()))? .insert(new_id, input.clone()); Ok(Value::custom( Box::new(HandleCustomValue(new_id)), call.head, )) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/main.rs
crates/nu_plugin_custom_values/src/main.rs
use std::{ collections::BTreeMap, sync::{Mutex, atomic::AtomicU64}, }; use handle_custom_value::HandleCustomValue; use nu_plugin::{EngineInterface, MsgPackSerializer, Plugin, PluginCommand, serve_plugin}; mod cool_custom_value; mod handle_custom_value; mod second_custom_value; mod drop_check; mod generate; mod generate2; mod handle_get; mod handle_make; mod handle_update; mod update; mod update_arg; use drop_check::{DropCheck, DropCheckValue}; use generate::Generate; use generate2::Generate2; use handle_get::HandleGet; use handle_make::HandleMake; use handle_update::HandleUpdate; use nu_protocol::{CustomValue, LabeledError, Spanned, Value}; use update::Update; use update_arg::UpdateArg; #[derive(Default)] pub struct CustomValuePlugin { counter: AtomicU64, handles: Mutex<BTreeMap<u64, Value>>, } impl CustomValuePlugin { pub fn new() -> Self { Self::default() } } impl Plugin for CustomValuePlugin { fn version(&self) -> String { env!("CARGO_PKG_VERSION").into() } fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { vec![ Box::new(Generate), Box::new(Generate2), Box::new(Update), Box::new(UpdateArg), Box::new(DropCheck), Box::new(HandleGet), Box::new(HandleMake), Box::new(HandleUpdate), ] } fn custom_value_to_base_value( &self, _engine: &EngineInterface, custom_value: Spanned<Box<dyn CustomValue>>, ) -> Result<Value, LabeledError> { // HandleCustomValue depends on the plugin state to get. if let Some(handle) = custom_value .item .as_any() .downcast_ref::<HandleCustomValue>() { Ok(self .handles .lock() .map_err(|err| LabeledError::new(err.to_string()))? .get(&handle.0) .cloned() .unwrap_or_else(|| Value::nothing(custom_value.span))) } else { custom_value .item .to_base_value(custom_value.span) .map_err(|err| err.into()) } } fn custom_value_dropped( &self, _engine: &EngineInterface, custom_value: Box<dyn CustomValue>, ) -> Result<(), LabeledError> { // This is how we implement our drop behavior. if let Some(drop_check) = custom_value.as_any().downcast_ref::<DropCheckValue>() { drop_check.notify(); } else if let Some(handle) = custom_value.as_any().downcast_ref::<HandleCustomValue>() && let Ok(mut handles) = self.handles.lock() { handles.remove(&handle.0); } Ok(()) } } fn main() { serve_plugin(&CustomValuePlugin::default(), MsgPackSerializer {}) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/drop_check.rs
crates/nu_plugin_custom_values/src/drop_check.rs
use crate::CustomValuePlugin; use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{ Category, CustomValue, LabeledError, ShellError, Signature, Span, SyntaxShape, Value, record, }; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct DropCheckValue { pub(crate) msg: String, } impl DropCheckValue { pub(crate) fn new(msg: String) -> DropCheckValue { DropCheckValue { msg } } pub(crate) fn into_value(self, span: Span) -> Value { Value::custom(Box::new(self), span) } pub(crate) fn notify(&self) { eprintln!("DropCheckValue was dropped: {}", self.msg); } } #[typetag::serde] impl CustomValue for DropCheckValue { fn clone_value(&self, span: Span) -> Value { self.clone().into_value(span) } fn type_name(&self) -> String { "DropCheckValue".into() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::record( record! { "msg" => Value::string(&self.msg, span) }, span, )) } fn as_any(&self) -> &dyn std::any::Any { self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn notify_plugin_on_drop(&self) -> bool { // This is what causes Nushell to let us know when the value is dropped true } } pub struct DropCheck; impl SimplePluginCommand for DropCheck { type Plugin = CustomValuePlugin; fn name(&self) -> &str { "custom-value drop-check" } fn description(&self) -> &str { "Generates a custom value that prints a message when dropped" } fn signature(&self) -> Signature { Signature::build(self.name()) .required("msg", SyntaxShape::String, "the message to print on drop") .category(Category::Experimental) } fn run( &self, _plugin: &Self::Plugin, _engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { Ok(DropCheckValue::new(call.req(0)?).into_value(call.head)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu_plugin_custom_values/src/generate.rs
crates/nu_plugin_custom_values/src/generate.rs
use crate::{CustomValuePlugin, cool_custom_value::CoolCustomValue}; use nu_plugin::{EngineInterface, EvaluatedCall, SimplePluginCommand}; use nu_protocol::{Category, Example, LabeledError, Signature, Span, Value}; pub struct Generate; impl SimplePluginCommand for Generate { type Plugin = CustomValuePlugin; fn name(&self) -> &str { "custom-value generate" } fn description(&self) -> &str { "PluginSignature for a plugin that generates a custom value" } fn signature(&self) -> Signature { Signature::build(self.name()).category(Category::Experimental) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "custom-value generate", description: "Generate a new CoolCustomValue", result: Some(CoolCustomValue::new("abc").into_value(Span::test_data())), }] } fn run( &self, _plugin: &CustomValuePlugin, _engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { Ok(CoolCustomValue::new("abc").into_value(call.head)) } } #[test] fn test_examples() -> Result<(), nu_protocol::ShellError> { use nu_plugin_test_support::PluginTest; PluginTest::new("custom_values", CustomValuePlugin::new().into())? .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-plugin-test-support/src/lib.rs
crates/nu-plugin-test-support/src/lib.rs
//! Test support for [Nushell](https://nushell.sh) plugins. //! //! # Example //! //! ```rust //! use std::sync::Arc; //! //! use nu_plugin::*; //! use nu_plugin_test_support::PluginTest; //! use nu_protocol::{ //! Example, IntoInterruptiblePipelineData, LabeledError, PipelineData, ShellError, Signals, //! Signature, Span, Type, Value, //! }; //! //! struct LowercasePlugin; //! struct Lowercase; //! //! impl PluginCommand for Lowercase { //! type Plugin = LowercasePlugin; //! //! fn name(&self) -> &str { //! "lowercase" //! } //! //! fn description(&self) -> &str { //! "Convert each string in a stream to lowercase" //! } //! //! fn signature(&self) -> Signature { //! Signature::build(self.name()).input_output_type( //! Type::List(Type::String.into()), //! Type::List(Type::String.into()), //! ) //! } //! //! fn examples(&self) -> Vec<Example<'_>> { //! vec![Example { //! example: r#"[Hello wORLD] | lowercase"#, //! description: "Lowercase a list of strings", //! result: Some(Value::test_list(vec![ //! Value::test_string("hello"), //! Value::test_string("world"), //! ])), //! }] //! } //! //! fn run( //! &self, //! _plugin: &LowercasePlugin, //! _engine: &EngineInterface, //! call: &EvaluatedCall, //! input: PipelineData, //! ) -> Result<PipelineData, LabeledError> { //! let span = call.head; //! Ok(input.map( //! move |value| { //! value //! .as_str() //! .map(|string| Value::string(string.to_lowercase(), span)) //! // Errors in a stream should be returned as values. //! .unwrap_or_else(|err| Value::error(err, span)) //! }, //! &Signals::empty(), //! )?) //! } //! } //! //! impl Plugin for LowercasePlugin { //! fn version(&self) -> String { //! env!("CARGO_PKG_VERSION").into() //! } //! //! fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin=Self>>> { //! vec![Box::new(Lowercase)] //! } //! } //! //! // #[test] //! fn test_examples() -> Result<(), ShellError> { //! PluginTest::new("lowercase", LowercasePlugin.into())? //! .test_command_examples(&Lowercase) //! } //! //! // #[test] //! fn test_lowercase() -> Result<(), ShellError> { //! let input = vec![Value::test_string("FooBar")].into_pipeline_data(Span::test_data(), Signals::empty()); //! let output = PluginTest::new("lowercase", LowercasePlugin.into())? //! .eval_with("lowercase", input)? //! .into_value(Span::test_data())?; //! //! assert_eq!( //! Value::test_list(vec![ //! Value::test_string("foobar") //! ]), //! output //! ); //! Ok(()) //! } //! # //! # test_examples().unwrap(); //! # test_lowercase().unwrap(); //! ``` mod diff; mod fake_persistent_plugin; mod fake_register; mod plugin_test; mod spawn_fake_plugin; pub use plugin_test::PluginTest;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/src/diff.rs
crates/nu-plugin-test-support/src/diff.rs
use std::fmt::Write; use nu_ansi_term::{Color, Style}; use similar::{ChangeTag, TextDiff}; /// Generate a stylized diff of different lines between two strings pub(crate) fn diff_by_line(old: &str, new: &str) -> String { let mut out = String::new(); let diff = TextDiff::from_lines(old, new); for change in diff.iter_all_changes() { let style = match change.tag() { ChangeTag::Equal => Style::new(), ChangeTag::Delete => Color::Red.into(), ChangeTag::Insert => Color::Green.into(), }; let _ = write!( out, "{}{}", style.paint(change.tag().to_string()), style.paint(change.value()), ); } out }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/src/fake_register.rs
crates/nu-plugin-test-support/src/fake_register.rs
use std::{ops::Deref, sync::Arc}; use nu_plugin::{Plugin, create_plugin_signature}; use nu_plugin_engine::PluginDeclaration; use nu_protocol::{RegisteredPlugin, ShellError, engine::StateWorkingSet}; use crate::{fake_persistent_plugin::FakePersistentPlugin, spawn_fake_plugin::spawn_fake_plugin}; /// Register all of the commands from the plugin into the [`StateWorkingSet`] pub fn fake_register( working_set: &mut StateWorkingSet, name: &str, plugin: Arc<impl Plugin + Send + 'static>, ) -> Result<Arc<FakePersistentPlugin>, ShellError> { let reg_plugin = spawn_fake_plugin(name, plugin.clone())?; let reg_plugin_clone = reg_plugin.clone(); for command in plugin.commands() { let signature = create_plugin_signature(command.deref()); let decl = PluginDeclaration::new(reg_plugin.clone(), signature); working_set.add_decl(Box::new(decl)); } let identity = reg_plugin.identity().clone(); working_set.find_or_create_plugin(&identity, move || reg_plugin); Ok(reg_plugin_clone) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/src/plugin_test.rs
crates/nu-plugin-test-support/src/plugin_test.rs
use std::{cmp::Ordering, convert::Infallible, sync::Arc}; use nu_ansi_term::Style; use nu_cmd_lang::create_default_context; use nu_engine::eval_block; use nu_parser::parse; use nu_plugin::{Plugin, PluginCommand}; use nu_plugin_engine::{PluginCustomValueWithSource, PluginSource, WithSource}; use nu_plugin_protocol::PluginCustomValue; use nu_protocol::{ CustomValue, Example, IntoSpanned as _, LabeledError, PipelineData, ShellError, Signals, Span, Value, debugger::WithoutDebug, engine::{EngineState, Stack, StateWorkingSet}, report_shell_error, }; use crate::{diff::diff_by_line, fake_register::fake_register}; /// An object through which plugins can be tested. pub struct PluginTest { engine_state: EngineState, source: Arc<PluginSource>, entry_num: usize, } impl PluginTest { /// Create a new test for the given `plugin` named `name`. /// /// # Example /// /// ```rust,no_run /// # use nu_plugin_test_support::PluginTest; /// # use nu_protocol::ShellError; /// # use nu_plugin::*; /// # fn test(MyPlugin: impl Plugin + Send + 'static) -> Result<PluginTest, ShellError> { /// PluginTest::new("my_plugin", MyPlugin.into()) /// # } /// ``` pub fn new( name: &str, plugin: Arc<impl Plugin + Send + 'static>, ) -> Result<PluginTest, ShellError> { let mut engine_state = create_default_context(); let mut working_set = StateWorkingSet::new(&engine_state); let reg_plugin = fake_register(&mut working_set, name, plugin)?; let source = Arc::new(PluginSource::new(reg_plugin)); engine_state.merge_delta(working_set.render())?; Ok(PluginTest { engine_state, source, entry_num: 1, }) } /// Get the [`EngineState`]. pub fn engine_state(&self) -> &EngineState { &self.engine_state } /// Get a mutable reference to the [`EngineState`]. pub fn engine_state_mut(&mut self) -> &mut EngineState { &mut self.engine_state } /// Make additional command declarations available for use by tests. /// /// This can be used to pull in commands from `nu-cmd-lang` for example, as required. pub fn add_decl( &mut self, decl: Box<dyn nu_protocol::engine::Command>, ) -> Result<&mut Self, ShellError> { let mut working_set = StateWorkingSet::new(&self.engine_state); working_set.add_decl(decl); self.engine_state.merge_delta(working_set.render())?; Ok(self) } /// Evaluate some Nushell source code with the plugin commands in scope with the given input to /// the pipeline. /// /// # Example /// /// ```rust,no_run /// # use nu_plugin_test_support::PluginTest; /// # use nu_protocol::{IntoInterruptiblePipelineData, ShellError, Signals, Span, Value}; /// # use nu_plugin::*; /// # fn test(MyPlugin: impl Plugin + Send + 'static) -> Result<(), ShellError> { /// let result = PluginTest::new("my_plugin", MyPlugin.into())? /// .eval_with( /// "my-command", /// vec![Value::test_int(42)].into_pipeline_data(Span::test_data(), Signals::empty()) /// )? /// .into_value(Span::test_data())?; /// assert_eq!(Value::test_string("42"), result); /// # Ok(()) /// # } /// ``` pub fn eval_with( &mut self, nu_source: &str, input: PipelineData, ) -> Result<PipelineData, ShellError> { let mut working_set = StateWorkingSet::new(&self.engine_state); let fname = format!("entry #{}", self.entry_num); self.entry_num += 1; // Parse the source code let block = parse(&mut working_set, Some(&fname), nu_source.as_bytes(), false); // Check for parse errors let error = if !working_set.parse_errors.is_empty() { // ShellError doesn't have ParseError, use LabeledError to contain it. let mut error = LabeledError::new("Example failed to parse"); error.inner.extend( working_set .parse_errors .iter() .map(|i| LabeledError::from_diagnostic(i).into()), ); Some(ShellError::LabeledError(error.into())) } else { None }; // Merge into state self.engine_state.merge_delta(working_set.render())?; // Return error if set. We merge the delta even if we have errors so that printing the error // based on the engine state still works. if let Some(error) = error { return Err(error); } // Serialize custom values in the input let source = self.source.clone(); let input = match input { input @ PipelineData::ByteStream(..) => input, input => input.map( move |mut value| { let result = PluginCustomValue::serialize_custom_values_in(&mut value) // Make sure to mark them with the source so they pass correctly, too. .and_then(|_| { PluginCustomValueWithSource::add_source_in(&mut value, &source) }); match result { Ok(()) => value, Err(err) => Value::error(err, value.span()), } }, &Signals::empty(), )?, }; // Eval the block with the input let mut stack = Stack::new().collect_value(); let data = eval_block::<WithoutDebug>(&self.engine_state, &mut stack, &block, input) .map(|p| p.body)?; match data { data @ PipelineData::ByteStream(..) => Ok(data), data => data.map( |mut value| { // Make sure to deserialize custom values let result = PluginCustomValueWithSource::remove_source_in(&mut value) .and_then(|_| PluginCustomValue::deserialize_custom_values_in(&mut value)); match result { Ok(()) => value, Err(err) => Value::error(err, value.span()), } }, &Signals::empty(), ), } } /// Evaluate some Nushell source code with the plugin commands in scope. /// /// # Example /// /// ```rust,no_run /// # use nu_plugin_test_support::PluginTest; /// # use nu_protocol::{ShellError, Span, Value, IntoInterruptiblePipelineData}; /// # use nu_plugin::*; /// # fn test(MyPlugin: impl Plugin + Send + 'static) -> Result<(), ShellError> { /// let result = PluginTest::new("my_plugin", MyPlugin.into())? /// .eval("42 | my-command")? /// .into_value(Span::test_data())?; /// assert_eq!(Value::test_string("42"), result); /// # Ok(()) /// # } /// ``` pub fn eval(&mut self, nu_source: &str) -> Result<PipelineData, ShellError> { self.eval_with(nu_source, PipelineData::empty()) } /// Test a list of plugin examples. Prints an error for each failing example. /// /// See [`.test_command_examples()`] for easier usage of this method on a command's examples. /// /// # Example /// /// ```rust,no_run /// # use nu_plugin_test_support::PluginTest; /// # use nu_protocol::{ShellError, Example, Value}; /// # use nu_plugin::*; /// # fn test(MyPlugin: impl Plugin + Send + 'static) -> Result<(), ShellError> { /// PluginTest::new("my_plugin", MyPlugin.into())? /// .test_examples(&[ /// Example { /// example: "my-command", /// description: "Run my-command", /// result: Some(Value::test_string("my-command output")), /// }, /// ]) /// # } /// ``` pub fn test_examples(&mut self, examples: &[Example]) -> Result<(), ShellError> { let mut failed = false; for example in examples { let bold = Style::new().bold(); let mut failed_header = || { failed = true; eprintln!("{} {}", bold.paint("Example:"), example.example); eprintln!("{} {}", bold.paint("Description:"), example.description); }; if let Some(expectation) = &example.result { match self.eval(example.example) { Ok(data) => { let mut value = data.into_value(Span::test_data())?; // Set all of the spans in the value to test_data() to avoid unnecessary // differences when printing let _: Result<(), Infallible> = value.recurse_mut(&mut |here| { here.set_span(Span::test_data()); Ok(()) }); // Check for equality with the result if !self.value_eq(expectation, &value)? { // If they're not equal, print a diff of the debug format let (expectation_formatted, value_formatted) = match (expectation, &value) { ( Value::Custom { val: ex_val, .. }, Value::Custom { val: v_val, .. }, ) => { // We have to serialize both custom values before handing them to the plugin let expectation_serialized = PluginCustomValue::serialize_from_custom_value( ex_val.as_ref(), expectation.span(), )? .with_source(self.source.clone()); let value_serialized = PluginCustomValue::serialize_from_custom_value( v_val.as_ref(), expectation.span(), )? .with_source(self.source.clone()); let persistent = self.source.persistent(None)?.get_plugin(None)?; let expectation_base = persistent .custom_value_to_base_value( expectation_serialized .into_spanned(expectation.span()), )?; let value_base = persistent.custom_value_to_base_value( value_serialized.into_spanned(value.span()), )?; ( format!("{expectation_base:#?}"), format!("{value_base:#?}"), ) } _ => (format!("{expectation:#?}"), format!("{value:#?}")), }; let diff = diff_by_line(&expectation_formatted, &value_formatted); failed_header(); eprintln!("{} {}", bold.paint("Result:"), diff); } } Err(err) => { // Report the error failed_header(); report_shell_error(None, &self.engine_state, &err); } } } } if !failed { Ok(()) } else { Err(ShellError::GenericError { error: "Some examples failed. See the error output for details".into(), msg: "".into(), span: None, help: None, inner: vec![], }) } } /// Test examples from a command. /// /// # Example /// /// ```rust,no_run /// # use nu_plugin_test_support::PluginTest; /// # use nu_protocol::ShellError; /// # use nu_plugin::*; /// # fn test(MyPlugin: impl Plugin + Send + 'static, MyCommand: impl PluginCommand) -> Result<(), ShellError> { /// PluginTest::new("my_plugin", MyPlugin.into())? /// .test_command_examples(&MyCommand) /// # } /// ``` pub fn test_command_examples( &mut self, command: &impl PluginCommand, ) -> Result<(), ShellError> { self.test_examples(&command.examples()) } /// This implements custom value comparison with `plugin.custom_value_partial_cmp()` to behave /// as similarly as possible to comparison in the engine. /// /// NOTE: Try to keep these reflecting the same comparison as `Value::partial_cmp` does under /// normal circumstances. Otherwise people will be very confused. fn value_eq(&self, a: &Value, b: &Value) -> Result<bool, ShellError> { match (a, b) { (Value::Custom { val, .. }, _) => { // We have to serialize both custom values before handing them to the plugin let serialized = PluginCustomValue::serialize_from_custom_value(val.as_ref(), a.span())? .with_source(self.source.clone()); let mut b_serialized = b.clone(); PluginCustomValue::serialize_custom_values_in(&mut b_serialized)?; PluginCustomValueWithSource::add_source_in(&mut b_serialized, &self.source)?; // Now get the plugin reference and execute the comparison let persistent = self.source.persistent(None)?.get_plugin(None)?; let ordering = persistent.custom_value_partial_cmp(serialized, b_serialized)?; Ok(matches!( ordering.map(Ordering::from), Some(Ordering::Equal) )) } // All container types need to be here except Closure. (Value::List { vals: a_vals, .. }, Value::List { vals: b_vals, .. }) => { // Must be the same length, with all elements equivalent Ok(a_vals.len() == b_vals.len() && { for (a_el, b_el) in a_vals.iter().zip(b_vals) { if !self.value_eq(a_el, b_el)? { return Ok(false); } } true }) } (Value::Record { val: a_rec, .. }, Value::Record { val: b_rec, .. }) => { // Must be the same length if a_rec.len() != b_rec.len() { return Ok(false); } // reorder cols and vals to make more logically compare. // more general, if two record have same col and values, // the order of cols shouldn't affect the equal property. let mut a_rec = a_rec.clone().into_owned(); let mut b_rec = b_rec.clone().into_owned(); a_rec.sort_cols(); b_rec.sort_cols(); // Check columns first for (a, b) in a_rec.columns().zip(b_rec.columns()) { if a != b { return Ok(false); } } // Then check the values for (a, b) in a_rec.values().zip(b_rec.values()) { if !self.value_eq(a, b)? { return Ok(false); } } // All equal, and same length Ok(true) } // Fall back to regular eq. _ => Ok(a == b), } } /// This implements custom value comparison with `plugin.custom_value_to_base_value()` to behave /// as similarly as possible to comparison in the engine. pub fn custom_value_to_base_value( &self, val: &dyn CustomValue, span: Span, ) -> Result<Value, ShellError> { let serialized = PluginCustomValue::serialize_from_custom_value(val, span)? .with_source(self.source.clone()); let persistent = self.source.persistent(None)?.get_plugin(None)?; persistent.custom_value_to_base_value(serialized.into_spanned(span)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/src/spawn_fake_plugin.rs
crates/nu-plugin-test-support/src/spawn_fake_plugin.rs
use std::sync::{Arc, mpsc}; use nu_plugin::Plugin; use nu_plugin_core::{InterfaceManager, PluginRead, PluginWrite}; use nu_plugin_engine::{PluginInterfaceManager, PluginSource}; use nu_plugin_protocol::{PluginInput, PluginOutput}; use nu_protocol::{PluginIdentity, ShellError, shell_error::io::IoError}; use crate::fake_persistent_plugin::FakePersistentPlugin; struct FakePluginRead<T>(mpsc::Receiver<T>); struct FakePluginWrite<T>(mpsc::Sender<T>); impl<T> PluginRead<T> for FakePluginRead<T> { fn read(&mut self) -> Result<Option<T>, ShellError> { Ok(self.0.recv().ok()) } } impl<T: Clone + Send> PluginWrite<T> for FakePluginWrite<T> { fn write(&self, data: &T) -> Result<(), ShellError> { self.0 .send(data.clone()) .map_err(|e| ShellError::GenericError { error: "Error sending data".to_string(), msg: e.to_string(), span: None, help: None, inner: vec![], }) } fn flush(&self) -> Result<(), ShellError> { Ok(()) } } fn fake_plugin_channel<T: Clone + Send>() -> (FakePluginRead<T>, FakePluginWrite<T>) { let (tx, rx) = mpsc::channel(); (FakePluginRead(rx), FakePluginWrite(tx)) } /// Spawn a plugin on another thread and return the registration pub(crate) fn spawn_fake_plugin( name: &str, plugin: Arc<impl Plugin + Send + 'static>, ) -> Result<Arc<FakePersistentPlugin>, ShellError> { let (input_read, input_write) = fake_plugin_channel::<PluginInput>(); let (output_read, output_write) = fake_plugin_channel::<PluginOutput>(); let identity = PluginIdentity::new_fake(name); let reg_plugin = Arc::new(FakePersistentPlugin::new(identity.clone())); let source = Arc::new(PluginSource::new(reg_plugin.clone())); // The fake plugin has no process ID, and we also don't set the garbage collector let mut manager = PluginInterfaceManager::new(source, None, input_write); // Set up the persistent plugin with the interface before continuing let interface = manager.get_interface(); interface.hello()?; reg_plugin.initialize(interface); // Start the interface reader on another thread std::thread::Builder::new() .name(format!("fake plugin interface reader ({name})")) .spawn(move || manager.consume_all(output_read).expect("Plugin read error")) .map_err(|err| { IoError::new_internal( err, format!("Could not spawn fake plugin interface reader ({name})"), nu_protocol::location!(), ) })?; // Start the plugin on another thread let name_string = name.to_owned(); std::thread::Builder::new() .name(format!("fake plugin runner ({name})")) .spawn(move || { nu_plugin::serve_plugin_io( &*plugin, &name_string, move || input_read, move || output_write, ) .expect("Plugin runner error") }) .map_err(|err| { IoError::new_internal( err, format!("Could not spawn fake plugin runner ({name})"), nu_protocol::location!(), ) })?; Ok(reg_plugin) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/src/fake_persistent_plugin.rs
crates/nu-plugin-test-support/src/fake_persistent_plugin.rs
use std::{ any::Any, sync::{Arc, OnceLock}, }; use nu_plugin_engine::{GetPlugin, PluginInterface}; use nu_protocol::{ PluginGcConfig, PluginIdentity, PluginMetadata, RegisteredPlugin, ShellError, engine::{EngineState, Stack}, }; pub struct FakePersistentPlugin { identity: PluginIdentity, plugin: OnceLock<PluginInterface>, } impl FakePersistentPlugin { pub fn new(identity: PluginIdentity) -> FakePersistentPlugin { FakePersistentPlugin { identity, plugin: OnceLock::new(), } } pub fn initialize(&self, interface: PluginInterface) { self.plugin.set(interface).unwrap_or_else(|_| { panic!("Tried to initialize an already initialized FakePersistentPlugin"); }) } } impl RegisteredPlugin for FakePersistentPlugin { fn identity(&self) -> &PluginIdentity { &self.identity } fn is_running(&self) -> bool { true } fn pid(&self) -> Option<u32> { None } fn metadata(&self) -> Option<PluginMetadata> { None } fn set_metadata(&self, _metadata: Option<PluginMetadata>) {} fn set_gc_config(&self, _gc_config: &PluginGcConfig) { // We don't have a GC } fn stop(&self) -> Result<(), ShellError> { // We can't stop Ok(()) } fn reset(&self) -> Result<(), ShellError> { // We can't stop Ok(()) } fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> { self } } impl GetPlugin for FakePersistentPlugin { fn get_plugin( self: Arc<Self>, _context: Option<(&EngineState, &mut Stack)>, ) -> Result<PluginInterface, ShellError> { self.plugin .get() .cloned() .ok_or_else(|| ShellError::PluginFailedToLoad { msg: "FakePersistentPlugin was not initialized".into(), }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/tests/main.rs
crates/nu-plugin-test-support/tests/main.rs
mod custom_value; mod hello; mod lowercase;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/tests/custom_value/mod.rs
crates/nu-plugin-test-support/tests/custom_value/mod.rs
use std::cmp::Ordering; use nu_plugin::{EngineInterface, EvaluatedCall, Plugin, SimplePluginCommand}; use nu_plugin_test_support::PluginTest; use nu_protocol::{ CustomValue, Example, LabeledError, PipelineData, ShellError, Signature, Span, Type, Value, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq)] struct CustomU32(u32); impl CustomU32 { pub fn into_value(self, span: Span) -> Value { Value::custom(Box::new(self), span) } } #[typetag::serde] impl CustomValue for CustomU32 { fn clone_value(&self, span: Span) -> Value { self.clone().into_value(span) } fn type_name(&self) -> String { "CustomU32".into() } fn to_base_value(&self, span: Span) -> Result<Value, ShellError> { Ok(Value::int(self.0 as i64, span)) } fn as_any(&self) -> &dyn std::any::Any { self } fn as_mut_any(&mut self) -> &mut dyn std::any::Any { self } fn partial_cmp(&self, other: &Value) -> Option<Ordering> { other .as_custom_value() .ok() .and_then(|cv| cv.as_any().downcast_ref::<CustomU32>()) .and_then(|other_u32| PartialOrd::partial_cmp(self, other_u32)) } } struct CustomU32Plugin; struct IntoU32; struct IntoIntFromU32; impl Plugin for CustomU32Plugin { fn version(&self) -> String { "0.0.0".into() } fn commands(&self) -> Vec<Box<dyn nu_plugin::PluginCommand<Plugin = Self>>> { vec![Box::new(IntoU32), Box::new(IntoIntFromU32)] } } impl SimplePluginCommand for IntoU32 { type Plugin = CustomU32Plugin; fn name(&self) -> &str { "into u32" } fn description(&self) -> &str { "Convert a number to a 32-bit unsigned integer" } fn signature(&self) -> Signature { Signature::build(self.name()).input_output_type(Type::Int, Type::Custom("CustomU32".into())) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "340 | into u32", description: "Make a u32", result: Some(CustomU32(340).into_value(Span::test_data())), }] } fn run( &self, _plugin: &Self::Plugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { let value: i64 = input.as_int()?; let value_u32 = u32::try_from(value).map_err(|err| { LabeledError::new(format!("Not a valid u32: {value}")) .with_label(err.to_string(), input.span()) })?; Ok(CustomU32(value_u32).into_value(call.head)) } } impl SimplePluginCommand for IntoIntFromU32 { type Plugin = CustomU32Plugin; fn name(&self) -> &str { "into int from u32" } fn description(&self) -> &str { "Turn a u32 back into a number" } fn signature(&self) -> Signature { Signature::build(self.name()).input_output_type(Type::Custom("CustomU32".into()), Type::Int) } fn run( &self, _plugin: &Self::Plugin, _engine: &EngineInterface, call: &EvaluatedCall, input: &Value, ) -> Result<Value, LabeledError> { let value: &CustomU32 = input .as_custom_value()? .as_any() .downcast_ref() .ok_or_else(|| ShellError::TypeMismatch { err_message: "expected CustomU32".into(), span: input.span(), })?; Ok(Value::int(value.0 as i64, call.head)) } } #[test] fn test_into_u32_examples() -> Result<(), ShellError> { PluginTest::new("custom_u32", CustomU32Plugin.into())?.test_command_examples(&IntoU32) } #[test] fn test_into_int_from_u32() -> Result<(), ShellError> { let result = PluginTest::new("custom_u32", CustomU32Plugin.into())? .eval_with( "into int from u32", PipelineData::value(CustomU32(42).into_value(Span::test_data()), None), )? .into_value(Span::test_data())?; assert_eq!(Value::test_int(42), result); Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/tests/hello/mod.rs
crates/nu-plugin-test-support/tests/hello/mod.rs
//! Extended from `nu-plugin` examples. use nu_plugin::*; use nu_plugin_test_support::PluginTest; use nu_protocol::{Example, LabeledError, ShellError, Signature, Type, Value}; struct HelloPlugin; struct Hello; impl Plugin for HelloPlugin { fn version(&self) -> String { "0.0.0".into() } fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { vec![Box::new(Hello)] } } impl SimplePluginCommand for Hello { type Plugin = HelloPlugin; fn name(&self) -> &str { "hello" } fn description(&self) -> &str { "Print a friendly greeting" } fn signature(&self) -> Signature { Signature::build(PluginCommand::name(self)).input_output_type(Type::Nothing, Type::String) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: "hello", description: "Print a friendly greeting", result: Some(Value::test_string("Hello, World!")), }] } fn run( &self, _plugin: &HelloPlugin, _engine: &EngineInterface, call: &EvaluatedCall, _input: &Value, ) -> Result<Value, LabeledError> { Ok(Value::string("Hello, World!".to_owned(), call.head)) } } #[test] fn test_specified_examples() -> Result<(), ShellError> { PluginTest::new("hello", HelloPlugin.into())?.test_command_examples(&Hello) } #[test] fn test_an_error_causing_example() -> Result<(), ShellError> { let result = PluginTest::new("hello", HelloPlugin.into())?.test_examples(&[Example { example: "hello --unknown-flag", description: "Run hello with an unknown flag", result: Some(Value::test_string("Hello, World!")), }]); assert!(result.is_err()); Ok(()) } #[test] fn test_an_example_with_the_wrong_result() -> Result<(), ShellError> { let result = PluginTest::new("hello", HelloPlugin.into())?.test_examples(&[Example { example: "hello", description: "Run hello but the example result is wrong", result: Some(Value::test_string("Goodbye, World!")), }]); assert!(result.is_err()); Ok(()) } #[test] fn test_requiring_nu_cmd_lang_commands() -> Result<(), ShellError> { use nu_protocol::Span; let result = PluginTest::new("hello", HelloPlugin.into())? .eval("do { let greeting = hello; $greeting }")? .into_value(Span::test_data())?; assert_eq!(Value::test_string("Hello, World!"), result); Ok(()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-plugin-test-support/tests/lowercase/mod.rs
crates/nu-plugin-test-support/tests/lowercase/mod.rs
use nu_plugin::*; use nu_plugin_test_support::PluginTest; use nu_protocol::{ Example, IntoInterruptiblePipelineData, LabeledError, PipelineData, ShellError, Signals, Signature, Span, Type, Value, }; struct LowercasePlugin; struct Lowercase; impl PluginCommand for Lowercase { type Plugin = LowercasePlugin; fn name(&self) -> &str { "lowercase" } fn description(&self) -> &str { "Convert each string in a stream to lowercase" } fn signature(&self) -> Signature { Signature::build(self.name()).input_output_type( Type::List(Type::String.into()), Type::List(Type::String.into()), ) } fn examples(&self) -> Vec<Example<'_>> { vec![Example { example: r#"[Hello wORLD] | lowercase"#, description: "Lowercase a list of strings", result: Some(Value::test_list(vec![ Value::test_string("hello"), Value::test_string("world"), ])), }] } fn run( &self, _plugin: &LowercasePlugin, _engine: &EngineInterface, call: &EvaluatedCall, input: PipelineData, ) -> Result<PipelineData, LabeledError> { let span = call.head; Ok(input.map( move |value| { value .as_str() .map(|string| Value::string(string.to_lowercase(), span)) // Errors in a stream should be returned as values. .unwrap_or_else(|err| Value::error(err, span)) }, &Signals::empty(), )?) } } impl Plugin for LowercasePlugin { fn version(&self) -> String { "0.0.0".into() } fn commands(&self) -> Vec<Box<dyn PluginCommand<Plugin = Self>>> { vec![Box::new(Lowercase)] } } #[test] fn test_lowercase_using_eval_with() -> Result<(), ShellError> { let result = PluginTest::new("lowercase", LowercasePlugin.into())?.eval_with( "lowercase", vec![Value::test_string("HeLlO wOrLd")] .into_pipeline_data(Span::test_data(), Signals::empty()), )?; assert_eq!( Value::test_list(vec![Value::test_string("hello world")]), result.into_value(Span::test_data())? ); Ok(()) } #[test] fn test_lowercase_examples() -> Result<(), ShellError> { PluginTest::new("lowercase", LowercasePlugin.into())?.test_command_examples(&Lowercase) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-glob/src/lib.rs
crates/nu-glob/src/lib.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Copyright 2022 The Nushell Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Support for matching file paths against Unix shell style patterns. //! //! The `glob` and `glob_with` functions allow querying the filesystem for all //! files that match a particular pattern (similar to the libc `glob` function). //! The methods on the `Pattern` type provide functionality for checking if //! individual paths match a particular pattern (similar to the libc `fnmatch` //! function). //! //! For consistency across platforms, and for Windows support, this module //! is implemented entirely in Rust rather than deferring to the libc //! `glob`/`fnmatch` functions. //! //! # Examples //! //! To print all jpg files in `/media/` and all of its subdirectories. //! //! ```rust,no_run //! use nu_glob::{glob, Uninterruptible}; //! //! for entry in glob("/media/**/*.jpg", Uninterruptible).expect("Failed to read glob pattern") { //! match entry { //! Ok(path) => println!("{:?}", path.display()), //! Err(e) => println!("{:?}", e), //! } //! } //! ``` //! //! To print all files containing the letter "a", case insensitive, in a `local` //! directory relative to the current working directory. This ignores errors //! instead of printing them. //! //! ```rust,no_run //! use nu_glob::{glob_with, MatchOptions, Uninterruptible}; //! //! let options = MatchOptions { //! case_sensitive: false, //! require_literal_separator: false, //! require_literal_leading_dot: false, //! recursive_match_hidden_dir: true, //! }; //! for entry in glob_with("local/*a*", options, Uninterruptible).unwrap() { //! if let Ok(path) = entry { //! println!("{:?}", path.display()) //! } //! } //! ``` #![doc( html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", html_root_url = "https://docs.rs/glob/0.3.1" )] #![deny(missing_docs)] #[cfg(test)] #[macro_use] extern crate doc_comment; #[cfg(test)] doctest!("../README.md"); use std::cmp; use std::cmp::Ordering; use std::error::Error; use std::fmt; use std::fs; use std::io; use std::path::{self, Component, Path, PathBuf}; use std::str::FromStr; use CharSpecifier::{CharRange, SingleChar}; use MatchResult::{EntirePatternDoesntMatch, Match, SubPatternDoesntMatch}; use PatternToken::AnyExcept; use PatternToken::{AnyChar, AnyRecursiveSequence, AnySequence, AnyWithin, Char}; /// A trait for types that can be periodically polled to check whether to cancel an operation. pub trait Interruptible { /// Returns whether the current operation should be cancelled. fn interrupted(&self) -> bool; } impl<I: Interruptible> Interruptible for &I { #[inline] fn interrupted(&self) -> bool { (*self).interrupted() } } /// A no-op implementor of [`Interruptible`] that always returns `false` for [`interrupted`](Interruptible::interrupted). pub struct Uninterruptible; impl Interruptible for Uninterruptible { #[inline] fn interrupted(&self) -> bool { false } } /// An iterator that yields `Path`s from the filesystem that match a particular /// pattern. /// /// Note that it yields `GlobResult` in order to report any `IoErrors` that may /// arise during iteration. If a directory matches but is unreadable, /// thereby preventing its contents from being checked for matches, a /// `GlobError` is returned to express this. /// /// See the `glob` function for more details. #[derive(Debug)] pub struct Paths<I = Uninterruptible> { dir_patterns: Vec<Pattern>, require_dir: bool, options: MatchOptions, todo: Vec<Result<(PathBuf, usize), GlobError>>, scope: Option<PathBuf>, interrupt: I, } impl Paths<Uninterruptible> { /// An iterator representing a single path. pub fn single(path: &Path, relative_to: &Path) -> Self { Paths { dir_patterns: vec![Pattern::new("*").expect("hard coded pattern")], require_dir: false, options: MatchOptions::default(), todo: vec![Ok((path.to_path_buf(), 0))], scope: Some(relative_to.into()), interrupt: Uninterruptible, } } } /// Return an iterator that produces all the `Path`s that match the given /// pattern using default match options, which may be absolute or relative to /// the current working directory. /// /// This may return an error if the pattern is invalid. /// /// This method uses the default match options and is equivalent to calling /// `glob_with(pattern, MatchOptions::default())`. Use `glob_with` directly if you /// want to use non-default match options. /// /// When iterating, each result is a `GlobResult` which expresses the /// possibility that there was an `IoError` when attempting to read the contents /// of the matched path. In other words, each item returned by the iterator /// will either be an `Ok(Path)` if the path matched, or an `Err(GlobError)` if /// the path (partially) matched _but_ its contents could not be read in order /// to determine if its contents matched. /// /// See the `Paths` documentation for more information. /// /// # Examples /// /// Consider a directory `/media/pictures` containing only the files /// `kittens.jpg`, `puppies.jpg` and `hamsters.gif`: /// /// ```rust,no_run /// use nu_glob::{glob, Uninterruptible}; /// /// for entry in glob("/media/pictures/*.jpg", Uninterruptible).unwrap() { /// match entry { /// Ok(path) => println!("{:?}", path.display()), /// /// // if the path matched but was unreadable, /// // thereby preventing its contents from matching /// Err(e) => println!("{:?}", e), /// } /// } /// ``` /// /// The above code will print: /// /// ```ignore /// /media/pictures/kittens.jpg /// /media/pictures/puppies.jpg /// ``` /// /// If you want to ignore unreadable paths, you can use something like /// `filter_map`: /// /// ```rust /// use nu_glob::{glob, Uninterruptible}; /// use std::result::Result; /// /// for path in glob("/media/pictures/*.jpg", Uninterruptible).unwrap().filter_map(Result::ok) { /// println!("{}", path.display()); /// } /// ``` /// Paths are yielded in alphabetical order. pub fn glob<I: Interruptible>(pattern: &str, interrupt: I) -> Result<Paths<I>, PatternError> { glob_with(pattern, MatchOptions::default(), interrupt) } /// Return an iterator that produces all the `Path`s that match the given /// pattern using the specified match options, which may be absolute or relative /// to the current working directory. /// /// This may return an error if the pattern is invalid. /// /// This function accepts Unix shell style patterns as described by /// `Pattern::new(..)`. The options given are passed through unchanged to /// `Pattern::matches_with(..)` with the exception that /// `require_literal_separator` is always set to `true` regardless of the value /// passed to this function. /// /// Paths are yielded in alphabetical order. pub fn glob_with<I: Interruptible>( pattern: &str, options: MatchOptions, interrupt: I, ) -> Result<Paths<I>, PatternError> { #[cfg(windows)] fn check_windows_verbatim(p: &Path) -> bool { match p.components().next() { Some(Component::Prefix(ref p)) => { // Allow VerbatimDisk paths. std canonicalize() generates them, and they work fine p.kind().is_verbatim() && !matches!(p.kind(), std::path::Prefix::VerbatimDisk(_)) } _ => false, } } #[cfg(not(windows))] fn check_windows_verbatim(_: &Path) -> bool { false } #[cfg(windows)] fn to_scope(p: &Path) -> PathBuf { // FIXME handle volume relative paths here p.to_path_buf() } #[cfg(not(windows))] fn to_scope(p: &Path) -> PathBuf { p.to_path_buf() } // make sure that the pattern is valid first, else early return with error Pattern::new(pattern)?; let mut components = Path::new(pattern).components().peekable(); while let Some(&Component::Prefix(..)) | Some(&Component::RootDir) = components.peek() { components.next(); } let rest = components.map(|s| s.as_os_str()).collect::<PathBuf>(); let normalized_pattern = Path::new(pattern).iter().collect::<PathBuf>(); let root_len = normalized_pattern .to_str() .expect("internal error: expected string") .len() - rest .to_str() .expect("internal error: expected string") .len(); let root = if root_len > 0 { Some(Path::new(&pattern[..root_len])) } else { None }; if root_len > 0 && check_windows_verbatim(root.expect("internal error: already checked for len > 0")) { // FIXME: How do we want to handle verbatim paths? I'm inclined to // return nothing, since we can't very well find all UNC shares with a // 1-letter server name. return Ok(Paths { dir_patterns: Vec::new(), require_dir: false, options, todo: Vec::new(), scope: None, interrupt, }); } let scope = root.map_or_else(|| PathBuf::from("."), to_scope); let mut dir_patterns = Vec::new(); let components = pattern[cmp::min(root_len, pattern.len())..].split_terminator(path::is_separator); for component in components { dir_patterns.push(Pattern::new(component)?); } if root_len == pattern.len() { dir_patterns.push(Pattern { original: "".to_string(), tokens: Vec::new(), is_recursive: false, }); } let last_is_separator = pattern.chars().next_back().map(path::is_separator); let require_dir = last_is_separator == Some(true); let todo = Vec::new(); Ok(Paths { dir_patterns, require_dir, options, todo, scope: Some(scope), interrupt, }) } /// Return an iterator that produces all the `Path`s that match the given /// pattern relative to a specified parent directory and using specified match options. /// Paths may be absolute or relative to the current working directory. /// /// This is provided primarily for testability, so multithreaded test runners can /// test pattern matches in different test directories at the same time without /// having to append the parent to the pattern under test. pub fn glob_with_parent<I: Interruptible>( pattern: &str, options: MatchOptions, parent: &Path, interrupt: I, ) -> Result<Paths<I>, PatternError> { match glob_with(pattern, options, interrupt) { Ok(mut p) => { p.scope = match p.scope { None => Some(parent.to_path_buf()), Some(s) if &s.to_string_lossy() == "." => Some(parent.to_path_buf()), Some(s) => Some(s), }; Ok(p) } Err(e) => Err(e), } } const GLOB_CHARS: &[char] = &['*', '?', '[']; /// Returns true if the given pattern is a glob, false if it's merely text to be /// matched exactly. /// /// ```rust /// assert!(nu_glob::is_glob("foo/*")); /// assert!(nu_glob::is_glob("foo/**/bar")); /// assert!(nu_glob::is_glob("foo?")); /// assert!(nu_glob::is_glob("foo[A]")); /// /// assert!(!nu_glob::is_glob("foo")); /// // nu_glob will ignore an unmatched ']' /// assert!(!nu_glob::is_glob("foo]")); /// // nu_glob doesn't expand {} /// assert!(!nu_glob::is_glob("foo.{txt,png}")); /// ``` pub fn is_glob(pattern: &str) -> bool { pattern.contains(GLOB_CHARS) } /// A glob iteration error. /// /// This is typically returned when a particular path cannot be read /// to determine if its contents match the glob pattern. This is possible /// if the program lacks the appropriate permissions, for example. #[derive(Debug)] pub struct GlobError { path: PathBuf, error: io::Error, } impl GlobError { /// The Path that the error corresponds to. pub fn path(&self) -> &Path { &self.path } /// The error in question. pub fn error(&self) -> &io::Error { &self.error } /// Consumes self, returning the _raw_ underlying `io::Error` pub fn into_error(self) -> io::Error { self.error } } impl Error for GlobError { #[allow(deprecated)] fn description(&self) -> &str { self.error.description() } fn cause(&self) -> Option<&dyn Error> { Some(&self.error) } } impl fmt::Display for GlobError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "attempting to read `{}` resulted in an error: {}", self.path.display(), self.error ) } } fn is_dir(p: &Path) -> bool { fs::metadata(p).map(|m| m.is_dir()).unwrap_or(false) } /// An alias for a glob iteration result. /// /// This represents either a matched path or a glob iteration error, /// such as failing to read a particular directory's contents. pub type GlobResult = Result<PathBuf, GlobError>; impl<I: Interruptible> Iterator for Paths<I> { type Item = GlobResult; fn next(&mut self) -> Option<GlobResult> { // the todo buffer hasn't been initialized yet, so it's done at this // point rather than in glob() so that the errors are unified that is, // failing to fill the buffer is an iteration error construction of the // iterator (i.e. glob()) only fails if it fails to compile the Pattern if let Some(scope) = self.scope.take() && !self.dir_patterns.is_empty() { // Shouldn't happen, but we're using -1 as a special index. assert!(self.dir_patterns.len() < !0); // if there's one prefilled result, take it, otherwise fill the todo buffer if self.todo.len() != 1 { fill_todo( &mut self.todo, &self.dir_patterns, 0, &scope, self.options, &self.interrupt, ); } } loop { if self.dir_patterns.is_empty() || self.todo.is_empty() { return None; } let (path, mut idx) = match self .todo .pop() .expect("internal error: already checked for non-empty") { Ok(pair) => pair, Err(e) => return Some(Err(e)), }; // idx -1: was already checked by fill_todo, maybe path was '.' or // '..' that we can't match here because of normalization. if idx == !0 { if self.require_dir && !is_dir(&path) { continue; } return Some(Ok(path)); } if self.dir_patterns[idx].is_recursive { let mut next = idx; // collapse consecutive recursive patterns while (next + 1) < self.dir_patterns.len() && self.dir_patterns[next + 1].is_recursive { next += 1; } if is_dir(&path) { // the path is a directory, check if matched according // to `hidden_dir_recursive` option. if !self.options.recursive_match_hidden_dir && path .file_name() .map(|name| name.to_string_lossy().starts_with('.')) .unwrap_or(false) { continue; } // push this directory's contents fill_todo( &mut self.todo, &self.dir_patterns, next, &path, self.options, &self.interrupt, ); if next == self.dir_patterns.len() - 1 { // pattern ends in recursive pattern, so return this // directory as a result return Some(Ok(path)); } else { // advanced to the next pattern for this path idx = next + 1; } } else if next == self.dir_patterns.len() - 1 { // not a directory and it's the last pattern, meaning no // match continue; } else { // advanced to the next pattern for this path idx = next + 1; } } // not recursive, so match normally if self.dir_patterns[idx].matches_with( { match path.file_name().and_then(|s| s.to_str()) { // FIXME (#9639): How do we handle non-utf8 filenames? // Ignore them for now; ideally we'd still match them // against a * None => { println!("warning: get non-utf8 filename {path:?}, ignored."); continue; } Some(x) => x, } }, self.options, ) { if idx == self.dir_patterns.len() - 1 { // it is not possible for a pattern to match a directory // *AND* its children so we don't need to check the // children if !self.require_dir || is_dir(&path) { return Some(Ok(path)); } } else { fill_todo( &mut self.todo, &self.dir_patterns, idx + 1, &path, self.options, &self.interrupt, ); } } } } } /// A pattern parsing error. #[derive(Debug)] pub struct PatternError { /// The approximate character index of where the error occurred. pub pos: usize, /// A message describing the error. pub msg: &'static str, } impl Error for PatternError { fn description(&self) -> &str { self.msg } } impl fmt::Display for PatternError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Pattern syntax error near position {}: {}", self.pos, self.msg ) } } /// A compiled Unix shell style pattern. /// /// - `?` matches any single character. /// /// - `*` matches any (possibly empty) sequence of characters. /// /// - `**` matches the current directory and arbitrary subdirectories. This /// sequence **must** form a single path component, so both `**a` and `b**` /// are invalid and will result in an error. A sequence of more than two /// consecutive `*` characters is also invalid. /// /// - `[...]` matches any character inside the brackets. Character sequences /// can also specify ranges of characters, as ordered by Unicode, so e.g. /// `[0-9]` specifies any character between 0 and 9 inclusive. An unclosed /// bracket is invalid. /// /// - `[!...]` is the negation of `[...]`, i.e. it matches any characters /// **not** in the brackets. /// /// - The metacharacters `?`, `*`, `[`, `]` can be matched by using brackets /// (e.g. `[?]`). When a `]` occurs immediately following `[` or `[!` then it /// is interpreted as being part of, rather then ending, the character set, so /// `]` and NOT `]` can be matched by `[]]` and `[!]]` respectively. The `-` /// character can be specified inside a character sequence pattern by placing /// it at the start or the end, e.g. `[abc-]`. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)] pub struct Pattern { original: String, tokens: Vec<PatternToken>, is_recursive: bool, } /// Show the original glob pattern. impl fmt::Display for Pattern { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.original.fmt(f) } } impl FromStr for Pattern { type Err = PatternError; fn from_str(s: &str) -> Result<Self, PatternError> { Self::new(s) } } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] enum PatternToken { Char(char), AnyChar, AnySequence, AnyRecursiveSequence, AnyWithin(Vec<CharSpecifier>), AnyExcept(Vec<CharSpecifier>), } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] enum CharSpecifier { SingleChar(char), CharRange(char, char), } #[derive(Copy, Clone, PartialEq)] enum MatchResult { Match, SubPatternDoesntMatch, EntirePatternDoesntMatch, } const ERROR_WILDCARDS: &str = "wildcards are either regular `*` or recursive `**`"; const ERROR_RECURSIVE_WILDCARDS: &str = "recursive wildcards must form a single path \ component"; const ERROR_INVALID_RANGE: &str = "invalid range pattern"; impl Pattern { /// This function compiles Unix shell style patterns. /// /// An invalid glob pattern will yield a `PatternError`. pub fn new(pattern: &str) -> Result<Self, PatternError> { let chars = pattern.chars().collect::<Vec<_>>(); let mut tokens = Vec::new(); let mut is_recursive = false; let mut i = 0; while i < chars.len() { match chars[i] { '?' => { tokens.push(AnyChar); i += 1; } '*' => { let old = i; while i < chars.len() && chars[i] == '*' { i += 1; } let count = i - old; match count.cmp(&2) { Ordering::Greater => { return Err(PatternError { pos: old + 2, msg: ERROR_WILDCARDS, }); } Ordering::Equal => { // ** can only be an entire path component // i.e. a/**/b is valid, but a**/b or a/**b is not // invalid matches are treated literally let is_valid = if i == 2 || path::is_separator(chars[i - count - 1]) { // it ends in a '/' if i < chars.len() && path::is_separator(chars[i]) { i += 1; true // or the pattern ends here // this enables the existing globbing mechanism } else if i == chars.len() { true // `**` ends in non-separator } else { return Err(PatternError { pos: i, msg: ERROR_RECURSIVE_WILDCARDS, }); } // `**` begins with non-separator } else { return Err(PatternError { pos: old - 1, msg: ERROR_RECURSIVE_WILDCARDS, }); }; if is_valid { // collapse consecutive AnyRecursiveSequence to a // single one let tokens_len = tokens.len(); if !(tokens_len > 1 && tokens[tokens_len - 1] == AnyRecursiveSequence) { is_recursive = true; tokens.push(AnyRecursiveSequence); } } } Ordering::Less => { tokens.push(AnySequence); } } } '[' => { if i + 4 <= chars.len() && chars[i + 1] == '!' { match chars[i + 3..].iter().position(|x| *x == ']') { None => (), Some(j) => { let chars = &chars[i + 2..i + 3 + j]; let cs = parse_char_specifiers(chars); tokens.push(AnyExcept(cs)); i += j + 4; continue; } } } else if i + 3 <= chars.len() && chars[i + 1] != '!' { match chars[i + 2..].iter().position(|x| *x == ']') { None => (), Some(j) => { let cs = parse_char_specifiers(&chars[i + 1..i + 2 + j]); tokens.push(AnyWithin(cs)); i += j + 3; continue; } } } // if we get here then this is not a valid range pattern return Err(PatternError { pos: i, msg: ERROR_INVALID_RANGE, }); } c => { tokens.push(Char(c)); i += 1; } } } Ok(Self { tokens, original: pattern.to_string(), is_recursive, }) } /// Escape metacharacters within the given string by surrounding them in /// brackets. The resulting string will, when compiled into a `Pattern`, /// match the input string and nothing else. pub fn escape(s: &str) -> String { let mut escaped = String::new(); for c in s.chars() { match c { // note that ! does not need escaping because it is only special // inside brackets '?' | '*' | '[' | ']' => { escaped.push('['); escaped.push(c); escaped.push(']'); } c => { escaped.push(c); } } } escaped } /// Return if the given `str` matches this `Pattern` using the default /// match options (i.e. `MatchOptions::default()`). /// /// # Examples /// /// ```rust /// use nu_glob::Pattern; /// /// assert!(Pattern::new("c?t").unwrap().matches("cat")); /// assert!(Pattern::new("k[!e]tteh").unwrap().matches("kitteh")); /// assert!(Pattern::new("d*g").unwrap().matches("doog")); /// ``` pub fn matches(&self, str: &str) -> bool { self.matches_with(str, MatchOptions::default()) } /// Return if the given `Path`, when converted to a `str`, matches this /// `Pattern` using the default match options (i.e. `MatchOptions::default()`). pub fn matches_path(&self, path: &Path) -> bool { // FIXME (#9639): This needs to handle non-utf8 paths path.to_str().is_some_and(|s| self.matches(s)) } /// Return if the given `str` matches this `Pattern` using the specified /// match options. pub fn matches_with(&self, str: &str, options: MatchOptions) -> bool { self.matches_from(true, str.chars(), 0, options) == Match } /// Return if the given `Path`, when converted to a `str`, matches this /// `Pattern` using the specified match options. pub fn matches_path_with(&self, path: &Path, options: MatchOptions) -> bool { // FIXME (#9639): This needs to handle non-utf8 paths path.to_str().is_some_and(|s| self.matches_with(s, options)) } /// Access the original glob pattern. pub fn as_str(&self) -> &str { &self.original } fn matches_from( &self, mut follows_separator: bool, mut file: std::str::Chars, i: usize, options: MatchOptions, ) -> MatchResult { for (ti, token) in self.tokens[i..].iter().enumerate() { match *token { AnySequence | AnyRecursiveSequence => { // ** must be at the start. debug_assert!(match *token { AnyRecursiveSequence => follows_separator, _ => true, }); // Empty match match self.matches_from(follows_separator, file.clone(), i + ti + 1, options) { SubPatternDoesntMatch => (), // keep trying m => return m, }; while let Some(c) = file.next() { if follows_separator && options.require_literal_leading_dot && c == '.' { return SubPatternDoesntMatch; } follows_separator = path::is_separator(c); match *token { AnyRecursiveSequence if !follows_separator => continue, AnySequence if options.require_literal_separator && follows_separator => { return SubPatternDoesntMatch; } _ => (), } match self.matches_from( follows_separator, file.clone(), i + ti + 1, options, ) { SubPatternDoesntMatch => (), // keep trying m => return m, } } } _ => { let c = match file.next() { Some(c) => c, None => return EntirePatternDoesntMatch, }; let is_sep = path::is_separator(c); if !match *token { AnyChar | AnyWithin(..) | AnyExcept(..) if (options.require_literal_separator && is_sep) || (follows_separator && options.require_literal_leading_dot && c == '.') => { false } AnyChar => true, AnyWithin(ref specifiers) => in_char_specifiers(specifiers, c, options), AnyExcept(ref specifiers) => !in_char_specifiers(specifiers, c, options), Char(c2) => chars_eq(c, c2, options.case_sensitive), AnySequence | AnyRecursiveSequence => unreachable!(), } { return SubPatternDoesntMatch; } follows_separator = is_sep; } } } // Iter is fused. if file.next().is_none() { Match } else { SubPatternDoesntMatch } } } // Fills `todo` with paths under `path` to be matched by `patterns[idx]`, // special-casing patterns to match `.` and `..`, and avoiding `readdir()` // calls when there are no metacharacters in the pattern. fn fill_todo(
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
true
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-json/src/ser.rs
crates/nu-json/src/ser.rs
//! Hjson Serialization //! //! This module provides for Hjson serialization with the type `Serializer`. use std::fmt::{Display, LowerExp}; use std::io; use std::num::FpCategory; use nu_utils::ObviousFloat; use super::error::{Error, ErrorCode, Result}; use serde::ser; /// A structure for serializing Rust values into Hjson. pub struct Serializer<W, F> { writer: W, formatter: F, } impl<'a, W> Serializer<W, HjsonFormatter<'a>> where W: io::Write, { /// Creates a new Hjson serializer. #[inline] pub fn new(writer: W) -> Self { Serializer::with_formatter(writer, HjsonFormatter::new()) } #[inline] pub fn with_indent(writer: W, indent: &'a [u8]) -> Self { Serializer::with_formatter(writer, HjsonFormatter::with_indent(indent)) } } impl<W, F> Serializer<W, F> where W: io::Write, F: Formatter, { /// Creates a new Hjson visitor whose output will be written to the writer /// specified. #[inline] pub fn with_formatter(writer: W, formatter: F) -> Self { Serializer { writer, formatter } } /// Unwrap the `Writer` from the `Serializer`. #[inline] pub fn into_inner(self) -> W { self.writer } } #[doc(hidden)] #[derive(Eq, PartialEq)] pub enum State { Empty, First, Rest, } #[doc(hidden)] pub struct Compound<'a, W, F> { ser: &'a mut Serializer<W, F>, state: State, } impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; type SerializeSeq = Compound<'a, W, F>; type SerializeTuple = Compound<'a, W, F>; type SerializeTupleStruct = Compound<'a, W, F>; type SerializeTupleVariant = Compound<'a, W, F>; type SerializeMap = Compound<'a, W, F>; type SerializeStruct = Compound<'a, W, F>; type SerializeStructVariant = Compound<'a, W, F>; #[inline] fn serialize_bool(self, value: bool) -> Result<()> { self.formatter.start_value(&mut self.writer)?; if value { self.writer.write_all(b"true").map_err(From::from) } else { self.writer.write_all(b"false").map_err(From::from) } } #[inline] fn serialize_i8(self, value: i8) -> Result<()> { self.formatter.start_value(&mut self.writer)?; write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_i16(self, value: i16) -> Result<()> { self.formatter.start_value(&mut self.writer)?; write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_i32(self, value: i32) -> Result<()> { self.formatter.start_value(&mut self.writer)?; write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_i64(self, value: i64) -> Result<()> { self.formatter.start_value(&mut self.writer)?; write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_u8(self, value: u8) -> Result<()> { self.formatter.start_value(&mut self.writer)?; write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_u16(self, value: u16) -> Result<()> { self.formatter.start_value(&mut self.writer)?; write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_u32(self, value: u32) -> Result<()> { self.formatter.start_value(&mut self.writer)?; write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_u64(self, value: u64) -> Result<()> { self.formatter.start_value(&mut self.writer)?; write!(&mut self.writer, "{value}").map_err(From::from) } #[inline] fn serialize_f32(self, value: f32) -> Result<()> { self.formatter.start_value(&mut self.writer)?; fmt_f32_or_null(&mut self.writer, if value == -0f32 { 0f32 } else { value }) } #[inline] fn serialize_f64(self, value: f64) -> Result<()> { self.formatter.start_value(&mut self.writer)?; fmt_f64_or_null(&mut self.writer, if value == -0f64 { 0f64 } else { value }) } #[inline] fn serialize_char(self, value: char) -> Result<()> { self.formatter.start_value(&mut self.writer)?; escape_char(&mut self.writer, value) } #[inline] fn serialize_str(self, value: &str) -> Result<()> { quote_str(&mut self.writer, &mut self.formatter, value) } #[inline] fn serialize_bytes(self, value: &[u8]) -> Result<()> { let mut seq = self.serialize_seq(Some(value.len()))?; for byte in value { ser::SerializeSeq::serialize_element(&mut seq, byte)? } ser::SerializeSeq::end(seq) } #[inline] fn serialize_unit(self) -> Result<()> { self.formatter.start_value(&mut self.writer)?; self.writer.write_all(b"null").map_err(From::from) } #[inline] fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { self.serialize_unit() } #[inline] fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result<()> { self.serialize_str(variant) } /// Serialize newtypes without an object wrapper. #[inline] fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { value.serialize(self) } #[inline] fn serialize_newtype_variant<T>( self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result<()> where T: ?Sized + ser::Serialize, { self.formatter.open(&mut self.writer, b'{')?; self.formatter.comma(&mut self.writer, true)?; escape_key(&mut self.writer, variant)?; self.formatter.colon(&mut self.writer)?; value.serialize(&mut *self)?; self.formatter.close(&mut self.writer, b'}') } #[inline] fn serialize_none(self) -> Result<()> { self.serialize_unit() } #[inline] fn serialize_some<V>(self, value: &V) -> Result<()> where V: ?Sized + ser::Serialize, { value.serialize(self) } #[inline] fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { let state = if len == Some(0) { self.formatter.start_value(&mut self.writer)?; self.writer.write_all(b"[]")?; State::Empty } else { self.formatter.open(&mut self.writer, b'[')?; State::First }; Ok(Compound { ser: self, state }) } #[inline] fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { self.serialize_seq(Some(len)) } #[inline] fn serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct> { self.serialize_seq(Some(len)) } #[inline] fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant> { self.formatter.open(&mut self.writer, b'{')?; self.formatter.comma(&mut self.writer, true)?; escape_key(&mut self.writer, variant)?; self.formatter.colon(&mut self.writer)?; self.serialize_seq(Some(len)) } #[inline] fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { let state = if len == Some(0) { self.formatter.start_value(&mut self.writer)?; self.writer.write_all(b"{}")?; State::Empty } else { self.formatter.open(&mut self.writer, b'{')?; State::First }; Ok(Compound { ser: self, state }) } #[inline] fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> { self.serialize_map(Some(len)) } #[inline] fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant> { self.formatter.open(&mut self.writer, b'{')?; self.formatter.comma(&mut self.writer, true)?; escape_key(&mut self.writer, variant)?; self.formatter.colon(&mut self.writer)?; self.serialize_map(Some(len)) } } impl<W, F> ser::SerializeSeq for Compound<'_, W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; fn serialize_element<T>(&mut self, value: &T) -> Result<()> where T: serde::Serialize + ?Sized, { self.ser .formatter .comma(&mut self.ser.writer, self.state == State::First)?; self.state = State::Rest; value.serialize(&mut *self.ser) } fn end(self) -> Result<Self::Ok> { match self.state { State::Empty => Ok(()), _ => self.ser.formatter.close(&mut self.ser.writer, b']'), } } } impl<W, F> ser::SerializeTuple for Compound<'_, W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; fn serialize_element<T>(&mut self, value: &T) -> Result<()> where T: serde::Serialize + ?Sized, { ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result<Self::Ok> { ser::SerializeSeq::end(self) } } impl<W, F> ser::SerializeTupleStruct for Compound<'_, W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; fn serialize_field<T>(&mut self, value: &T) -> Result<()> where T: serde::Serialize + ?Sized, { ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result<Self::Ok> { ser::SerializeSeq::end(self) } } impl<W, F> ser::SerializeTupleVariant for Compound<'_, W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; fn serialize_field<T>(&mut self, value: &T) -> Result<()> where T: serde::Serialize + ?Sized, { ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result<Self::Ok> { match self.state { State::Empty => {} _ => self.ser.formatter.close(&mut self.ser.writer, b']')?, } self.ser.formatter.close(&mut self.ser.writer, b'}') } } impl<W, F> ser::SerializeMap for Compound<'_, W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; fn serialize_key<T>(&mut self, key: &T) -> Result<()> where T: serde::Serialize + ?Sized, { self.ser .formatter .comma(&mut self.ser.writer, self.state == State::First)?; self.state = State::Rest; key.serialize(MapKeySerializer { ser: self.ser })?; self.ser.formatter.colon(&mut self.ser.writer) } fn serialize_value<T>(&mut self, value: &T) -> Result<()> where T: serde::Serialize + ?Sized, { value.serialize(&mut *self.ser) } fn end(self) -> Result<Self::Ok> { match self.state { State::Empty => Ok(()), _ => self.ser.formatter.close(&mut self.ser.writer, b'}'), } } } impl<W, F> ser::SerializeStruct for Compound<'_, W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> where T: serde::Serialize + ?Sized, { ser::SerializeMap::serialize_entry(self, key, value) } fn end(self) -> Result<Self::Ok> { ser::SerializeMap::end(self) } } impl<W, F> ser::SerializeStructVariant for Compound<'_, W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> where T: serde::Serialize + ?Sized, { ser::SerializeStruct::serialize_field(self, key, value) } fn end(self) -> Result<Self::Ok> { match self.state { State::Empty => {} _ => self.ser.formatter.close(&mut self.ser.writer, b'}')?, } self.ser.formatter.close(&mut self.ser.writer, b'}') } } struct MapKeySerializer<'a, W: 'a, F: 'a> { ser: &'a mut Serializer<W, F>, } impl<W, F> ser::Serializer for MapKeySerializer<'_, W, F> where W: io::Write, F: Formatter, { type Ok = (); type Error = Error; #[inline] fn serialize_str(self, value: &str) -> Result<()> { escape_key(&mut self.ser.writer, value) } type SerializeSeq = ser::Impossible<(), Error>; type SerializeTuple = ser::Impossible<(), Error>; type SerializeTupleStruct = ser::Impossible<(), Error>; type SerializeTupleVariant = ser::Impossible<(), Error>; type SerializeMap = ser::Impossible<(), Error>; type SerializeStruct = ser::Impossible<(), Error>; type SerializeStructVariant = ser::Impossible<(), Error>; fn serialize_bool(self, _value: bool) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_i8(self, _value: i8) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_i16(self, _value: i16) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_i32(self, _value: i32) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_i64(self, _value: i64) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_u8(self, _value: u8) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_u16(self, _value: u16) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_u32(self, _value: u32) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_u64(self, _value: u64) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_f32(self, _value: f32) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_f64(self, _value: f64) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_char(self, _value: char) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_bytes(self, _value: &[u8]) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_unit(self) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, ) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_newtype_struct<T>(self, _name: &'static str, _value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_newtype_variant<T>( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> Result<()> where T: ?Sized + ser::Serialize, { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_none(self) -> Result<()> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_some<T>(self, _value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeStruct> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeTupleStruct> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeTupleVariant> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant> { Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)) } } /// This trait abstracts away serializing the JSON control characters pub trait Formatter { /// Called when serializing a '{' or '['. fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()> where W: io::Write; /// Called when serializing a ','. fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()> where W: io::Write; /// Called when serializing a ':'. fn colon<W>(&mut self, writer: &mut W) -> Result<()> where W: io::Write; /// Called when serializing a '}' or ']'. fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()> where W: io::Write; /// Newline with indent. fn newline<W>(&mut self, writer: &mut W, add_indent: i32) -> Result<()> where W: io::Write; /// Start a value. fn start_value<W>(&mut self, writer: &mut W) -> Result<()> where W: io::Write; } struct HjsonFormatter<'a> { current_indent: usize, current_is_array: bool, stack: Vec<bool>, at_colon: bool, indent: &'a [u8], braces_same_line: bool, } impl Default for HjsonFormatter<'_> { fn default() -> Self { Self::new() } } impl<'a> HjsonFormatter<'a> { /// Construct a formatter that defaults to using two spaces for indentation. pub fn new() -> Self { HjsonFormatter::with_indent(b" ") } /// Construct a formatter that uses the `indent` string for indentation. pub fn with_indent(indent: &'a [u8]) -> Self { HjsonFormatter { current_indent: 0, current_is_array: false, stack: Vec::new(), at_colon: false, indent, braces_same_line: true, } } } impl Formatter for HjsonFormatter<'_> { fn open<W>(&mut self, writer: &mut W, ch: u8) -> Result<()> where W: io::Write, { if self.current_indent > 0 && !self.current_is_array && !self.braces_same_line { self.newline(writer, 0)?; } else { self.start_value(writer)?; } self.current_indent += 1; self.stack.push(self.current_is_array); self.current_is_array = ch == b'['; writer.write_all(&[ch]).map_err(From::from) } fn comma<W>(&mut self, writer: &mut W, first: bool) -> Result<()> where W: io::Write, { if !first { writer.write_all(b",\n")?; } else { writer.write_all(b"\n")?; } indent(writer, self.current_indent, self.indent) } fn colon<W>(&mut self, writer: &mut W) -> Result<()> where W: io::Write, { self.at_colon = !self.braces_same_line; writer .write_all(if self.braces_same_line { b": " } else { b":" }) .map_err(From::from) } fn close<W>(&mut self, writer: &mut W, ch: u8) -> Result<()> where W: io::Write, { self.current_indent -= 1; self.current_is_array = self.stack.pop().expect("Internal error: json parsing"); writer.write_all(b"\n")?; indent(writer, self.current_indent, self.indent)?; writer.write_all(&[ch]).map_err(From::from) } fn newline<W>(&mut self, writer: &mut W, add_indent: i32) -> Result<()> where W: io::Write, { self.at_colon = false; writer.write_all(b"\n")?; let ii = self.current_indent as i32 + add_indent; indent(writer, if ii < 0 { 0 } else { ii as usize }, self.indent) } fn start_value<W>(&mut self, writer: &mut W) -> Result<()> where W: io::Write, { if self.at_colon { self.at_colon = false; writer.write_all(b" ")? } Ok(()) } } /// Serializes and escapes a `&[u8]` into a Hjson string. #[inline] pub fn escape_bytes<W>(wr: &mut W, bytes: &[u8]) -> Result<()> where W: io::Write, { wr.write_all(b"\"")?; let mut start = 0; for (i, byte) in bytes.iter().enumerate() { let escaped = match *byte { b'"' => b"\\\"", b'\\' => b"\\\\", b'\x08' => b"\\b", b'\x0c' => b"\\f", b'\n' => b"\\n", b'\r' => b"\\r", b'\t' => b"\\t", _ => { continue; } }; if start < i { wr.write_all(&bytes[start..i])?; } wr.write_all(escaped)?; start = i + 1; } if start != bytes.len() { wr.write_all(&bytes[start..])?; } wr.write_all(b"\"")?; Ok(()) } /// Serializes and escapes a `&str` into a Hjson string. #[inline] pub fn quote_str<W, F>(wr: &mut W, formatter: &mut F, value: &str) -> Result<()> where W: io::Write, F: Formatter, { if value.is_empty() { formatter.start_value(wr)?; return escape_bytes(wr, value.as_bytes()); } formatter.start_value(wr)?; escape_bytes(wr, value.as_bytes()) } /// Serializes and escapes a `&str` into a Hjson key. #[inline] pub fn escape_key<W>(wr: &mut W, value: &str) -> Result<()> where W: io::Write, { escape_bytes(wr, value.as_bytes()) } #[inline] fn escape_char<W>(wr: &mut W, value: char) -> Result<()> where W: io::Write, { escape_bytes(wr, value.encode_utf8(&mut [0; 4]).as_bytes()) } fn fmt_f32_or_null<W>(wr: &mut W, value: f32) -> Result<()> where W: io::Write, { match value.classify() { FpCategory::Nan | FpCategory::Infinite => wr.write_all(b"null")?, _ => wr.write_all(fmt_small(ObviousFloat(value as f64)).as_bytes())?, } Ok(()) } fn fmt_f64_or_null<W>(wr: &mut W, value: f64) -> Result<()> where W: io::Write, { match value.classify() { FpCategory::Nan | FpCategory::Infinite => wr.write_all(b"null")?, _ => wr.write_all(fmt_small(ObviousFloat(value)).as_bytes())?, } Ok(()) } fn indent<W>(wr: &mut W, n: usize, s: &[u8]) -> Result<()> where W: io::Write, { for _ in 0..n { wr.write_all(s)?; } Ok(()) } // format similar to es6 fn fmt_small<N>(value: N) -> String where N: Display + LowerExp, { let f1 = value.to_string(); let f2 = format!("{value:e}"); if f1.len() <= f2.len() + 1 { f1 } else if !f2.contains("e-") { f2.replace('e', "e+") } else { f2 } } /// Encode the specified struct into a Hjson `[u8]` writer. #[inline] pub fn to_writer<W, T>(writer: &mut W, value: &T) -> Result<()> where W: io::Write, T: ser::Serialize, { let mut ser = Serializer::new(writer); value.serialize(&mut ser)?; Ok(()) } /// Encode the specified struct into a Hjson `[u8]` writer. #[inline] pub fn to_writer_with_tab_indentation<W, T>(writer: &mut W, value: &T, tabs: usize) -> Result<()> where W: io::Write, T: ser::Serialize, { let indent_string = "\t".repeat(tabs); let mut ser = Serializer::with_indent(writer, indent_string.as_bytes()); value.serialize(&mut ser)?; Ok(()) } /// Encode the specified struct into a Hjson `[u8]` writer. #[inline] pub fn to_writer_with_indent<W, T>(writer: &mut W, value: &T, indent: usize) -> Result<()> where W: io::Write, T: ser::Serialize, { let indent_string = " ".repeat(indent); let mut ser = Serializer::with_indent(writer, indent_string.as_bytes()); value.serialize(&mut ser)?; Ok(()) } /// Encode the specified struct into a Hjson `[u8]` buffer. #[inline] pub fn to_vec<T>(value: &T) -> Result<Vec<u8>> where T: ser::Serialize, { // We are writing to a Vec, which doesn't fail. So we can ignore // the error. let mut writer = Vec::with_capacity(128); to_writer(&mut writer, value)?; Ok(writer) } /// Encode the specified struct into a Hjson `[u8]` buffer. #[inline] pub fn to_vec_with_tab_indentation<T>(value: &T, tabs: usize) -> Result<Vec<u8>> where T: ser::Serialize, { // We are writing to a Vec, which doesn't fail. So we can ignore // the error. let mut writer = Vec::with_capacity(128); to_writer_with_tab_indentation(&mut writer, value, tabs)?; Ok(writer) } /// Encode the specified struct into a Hjson `[u8]` buffer. #[inline] pub fn to_vec_with_indent<T>(value: &T, indent: usize) -> Result<Vec<u8>> where T: ser::Serialize, { // We are writing to a Vec, which doesn't fail. So we can ignore // the error. let mut writer = Vec::with_capacity(128); to_writer_with_indent(&mut writer, value, indent)?; Ok(writer) } /// Encode the specified struct into a Hjson `String` buffer. #[inline] pub fn to_string<T>(value: &T) -> Result<String> where T: ser::Serialize, { let vec = to_vec(value)?; let string = String::from_utf8(vec)?; Ok(string) } /// Encode the specified struct into a Hjson `String` buffer. #[inline] pub fn to_string_with_indent<T>(value: &T, indent: usize) -> Result<String> where T: ser::Serialize, { let vec = to_vec_with_indent(value, indent)?; let string = String::from_utf8(vec)?; Ok(string) } /// Encode the specified struct into a Hjson `String` buffer. #[inline] pub fn to_string_with_tab_indentation<T>(value: &T, tabs: usize) -> Result<String> where T: ser::Serialize, { let vec = to_vec_with_tab_indentation(value, tabs)?; let string = String::from_utf8(vec)?; Ok(string) } /// Encode the specified struct into a Hjson `String` buffer. /// And remove all whitespace #[inline] pub fn to_string_raw<T>(value: &T) -> Result<String> where T: ser::Serialize, { let result = serde_json::to_string(value); match result { Ok(result_string) => Ok(result_string), Err(error) => Err(Error::Io(std::io::Error::from(error))), } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-json/src/builder.rs
crates/nu-json/src/builder.rs
use serde::ser; use crate::value::{self, Map, Value}; /// This structure provides a simple interface for constructing a JSON array. pub struct ArrayBuilder { array: Vec<Value>, } impl Default for ArrayBuilder { fn default() -> Self { Self::new() } } impl ArrayBuilder { /// Construct an `ObjectBuilder`. pub fn new() -> ArrayBuilder { ArrayBuilder { array: Vec::new() } } /// Return the constructed `Value`. pub fn unwrap(self) -> Value { Value::Array(self.array) } /// Insert a value into the array. pub fn push<T: ser::Serialize>(mut self, v: T) -> ArrayBuilder { self.array .push(value::to_value(&v).expect("failed to serialize")); self } /// Creates and passes an `ArrayBuilder` into a closure, then inserts the resulting array into /// this array. pub fn push_array<F>(mut self, f: F) -> ArrayBuilder where F: FnOnce(ArrayBuilder) -> ArrayBuilder, { let builder = ArrayBuilder::new(); self.array.push(f(builder).unwrap()); self } /// Creates and passes an `ArrayBuilder` into a closure, then inserts the resulting object into /// this array. pub fn push_object<F>(mut self, f: F) -> ArrayBuilder where F: FnOnce(ObjectBuilder) -> ObjectBuilder, { let builder = ObjectBuilder::new(); self.array.push(f(builder).unwrap()); self } } /// This structure provides a simple interface for constructing a JSON object. pub struct ObjectBuilder { object: Map<String, Value>, } impl Default for ObjectBuilder { fn default() -> Self { Self::new() } } impl ObjectBuilder { /// Construct an `ObjectBuilder`. pub fn new() -> ObjectBuilder { ObjectBuilder { object: Map::new() } } /// Return the constructed `Value`. pub fn unwrap(self) -> Value { Value::Object(self.object) } /// Insert a key-value pair into the object. pub fn insert<S, V>(mut self, key: S, value: V) -> ObjectBuilder where S: Into<String>, V: ser::Serialize, { self.object.insert( key.into(), value::to_value(&value).expect("failed to serialize"), ); self } /// Creates and passes an `ObjectBuilder` into a closure, then inserts the resulting array into /// this object. pub fn insert_array<S, F>(mut self, key: S, f: F) -> ObjectBuilder where S: Into<String>, F: FnOnce(ArrayBuilder) -> ArrayBuilder, { let builder = ArrayBuilder::new(); self.object.insert(key.into(), f(builder).unwrap()); self } /// Creates and passes an `ObjectBuilder` into a closure, then inserts the resulting object into /// this object. pub fn insert_object<S, F>(mut self, key: S, f: F) -> ObjectBuilder where S: Into<String>, F: FnOnce(ObjectBuilder) -> ObjectBuilder, { let builder = ObjectBuilder::new(); self.object.insert(key.into(), f(builder).unwrap()); self } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-json/src/lib.rs
crates/nu-json/src/lib.rs
#![doc = include_str!("../README.md")] pub use self::de::{ Deserializer, StreamDeserializer, from_iter, from_reader, from_slice, from_str, }; pub use self::error::{Error, ErrorCode, Result}; pub use self::ser::{ Serializer, to_string, to_string_raw, to_string_with_indent, to_string_with_tab_indentation, to_vec, to_writer, }; pub use self::value::{Map, Value, from_value, to_value}; pub mod builder; pub mod de; pub mod error; pub mod ser; mod util; pub mod value;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-json/src/value.rs
crates/nu-json/src/value.rs
#[cfg(not(feature = "preserve_order"))] use std::collections::{BTreeMap, btree_map}; #[cfg(feature = "preserve_order")] use linked_hash_map::LinkedHashMap; use std::fmt; use std::io; use std::str; use std::vec; use num_traits::NumCast; use serde::de; use serde::ser; use crate::error::{Error, ErrorCode}; type Result<T, E = Error> = std::result::Result<T, E>; /// Represents a key/value type. #[cfg(not(feature = "preserve_order"))] pub type Map<K, V> = BTreeMap<K, V>; /// Represents a key/value type. #[cfg(feature = "preserve_order")] pub type Map<K, V> = LinkedHashMap<K, V>; /// Represents the `IntoIter` type. #[cfg(not(feature = "preserve_order"))] pub type MapIntoIter<K, V> = btree_map::IntoIter<K, V>; /// Represents the IntoIter type. #[cfg(feature = "preserve_order")] pub type MapIntoIter<K, V> = linked_hash_map::IntoIter<K, V>; fn map_with_capacity<K: std::hash::Hash + Eq, V>(size: Option<usize>) -> Map<K, V> { #[cfg(not(feature = "preserve_order"))] { let _ = size; BTreeMap::new() } #[cfg(feature = "preserve_order")] { LinkedHashMap::with_capacity(size.unwrap_or(0)) } } /// Represents a Hjson/JSON value #[derive(Clone, PartialEq)] pub enum Value { /// Represents a JSON null value Null, /// Represents a JSON Boolean Bool(bool), /// Represents a JSON signed integer I64(i64), /// Represents a JSON unsigned integer U64(u64), /// Represents a JSON floating point number F64(f64), /// Represents a JSON string String(String), /// Represents a JSON array Array(Vec<Value>), /// Represents a JSON object Object(Map<String, Value>), } impl Value { /// If the `Value` is an Object, returns the value associated with the provided key. /// Otherwise, returns None. pub fn find<'a>(&'a self, key: &str) -> Option<&'a Value> { match *self { Value::Object(ref map) => map.get(key), _ => None, } } /// Attempts to get a nested Value Object for each key in `keys`. /// If any key is found not to exist, find_path will return None. /// Otherwise, it will return the `Value` associated with the final key. pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Value> { let mut target = self; for key in keys { match target.find(key) { Some(t) => { target = t; } None => return None, } } Some(target) } /// Looks up a value by a JSON Pointer. /// /// JSON Pointer defines a string syntax for identifying a specific value /// within a JavaScript Object Notation (JSON) document. /// /// A Pointer is a Unicode string with the reference tokens separated by `/`. /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The /// addressed value is returned and if there is no such value `None` is /// returned. /// /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). pub fn pointer<'a>(&'a self, pointer: &str) -> Option<&'a Value> { fn parse_index(s: &str) -> Option<usize> { if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) { return None; } s.parse().ok() } if pointer.is_empty() { return Some(self); } if !pointer.starts_with('/') { return None; } let mut target = self; for escaped_token in pointer.split('/').skip(1) { let token = escaped_token.replace("~1", "/").replace("~0", "~"); let target_opt = match *target { Value::Object(ref map) => map.get(&token[..]), Value::Array(ref list) => parse_index(&token[..]).and_then(|x| list.get(x)), _ => return None, }; if let Some(t) = target_opt { target = t; } else { return None; } } Some(target) } /// If the `Value` is an Object, performs a depth-first search until /// a value associated with the provided key is found. If no value is found /// or the `Value` is not an Object, returns None. pub fn search<'a>(&'a self, key: &str) -> Option<&'a Value> { match self { Value::Object(map) => map .get(key) .or_else(|| map.values().find_map(|v| v.search(key))), _ => None, } } /// Returns true if the `Value` is an Object. Returns false otherwise. pub fn is_object(&self) -> bool { self.as_object().is_some() } /// If the `Value` is an Object, returns the associated Map. /// Returns None otherwise. pub fn as_object(&self) -> Option<&Map<String, Value>> { match *self { Value::Object(ref map) => Some(map), _ => None, } } /// If the `Value` is an Object, returns the associated mutable Map. /// Returns None otherwise. pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> { match *self { Value::Object(ref mut map) => Some(map), _ => None, } } /// Returns true if the `Value` is an Array. Returns false otherwise. pub fn is_array(&self) -> bool { self.as_array().is_some() } /// If the `Value` is an Array, returns the associated vector. /// Returns None otherwise. pub fn as_array(&self) -> Option<&[Value]> { match self { Value::Array(array) => Some(array), _ => None, } } /// If the `Value` is an Array, returns the associated mutable vector. /// Returns None otherwise. pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { match self { Value::Array(list) => Some(list), _ => None, } } /// Returns true if the `Value` is a String. Returns false otherwise. pub fn is_string(&self) -> bool { self.as_str().is_some() } /// If the `Value` is a String, returns the associated str. /// Returns None otherwise. pub fn as_str(&self) -> Option<&str> { match self { Value::String(s) => Some(s), _ => None, } } /// Returns true if the `Value` is a Number. Returns false otherwise. pub fn is_number(&self) -> bool { matches!(self, Value::I64(_) | Value::U64(_) | Value::F64(_)) } /// Returns true if the `Value` is a i64. Returns false otherwise. pub fn is_i64(&self) -> bool { matches!(self, Value::I64(_)) } /// Returns true if the `Value` is a u64. Returns false otherwise. pub fn is_u64(&self) -> bool { matches!(self, Value::U64(_)) } /// Returns true if the `Value` is a f64. Returns false otherwise. pub fn is_f64(&self) -> bool { matches!(self, Value::F64(_)) } /// If the `Value` is a number, return or cast it to a i64. /// Returns None otherwise. pub fn as_i64(&self) -> Option<i64> { match *self { Value::I64(n) => Some(n), Value::U64(n) => NumCast::from(n), _ => None, } } /// If the `Value` is a number, return or cast it to a u64. /// Returns None otherwise. pub fn as_u64(&self) -> Option<u64> { match *self { Value::I64(n) => NumCast::from(n), Value::U64(n) => Some(n), _ => None, } } /// If the `Value` is a number, return or cast it to a f64. /// Returns None otherwise. pub fn as_f64(&self) -> Option<f64> { match *self { Value::I64(n) => NumCast::from(n), Value::U64(n) => NumCast::from(n), Value::F64(n) => Some(n), _ => None, } } /// Returns true if the `Value` is a Boolean. Returns false otherwise. pub fn is_boolean(&self) -> bool { self.as_bool().is_some() } /// If the `Value` is a Boolean, returns the associated bool. /// Returns None otherwise. pub fn as_bool(&self) -> Option<bool> { match *self { Value::Bool(b) => Some(b), _ => None, } } /// Returns true if the `Value` is a Null. Returns false otherwise. pub fn is_null(&self) -> bool { self.as_null().is_some() } /// If the `Value` is a Null, returns (). /// Returns None otherwise. pub fn as_null(&self) -> Option<()> { match self { Value::Null => Some(()), _ => None, } } fn as_unexpected(&self) -> de::Unexpected<'_> { match *self { Value::Null => de::Unexpected::Unit, Value::Bool(v) => de::Unexpected::Bool(v), Value::I64(v) => de::Unexpected::Signed(v), Value::U64(v) => de::Unexpected::Unsigned(v), Value::F64(v) => de::Unexpected::Float(v), Value::String(ref v) => de::Unexpected::Str(v), Value::Array(_) => de::Unexpected::Seq, Value::Object(_) => de::Unexpected::Map, } } } impl ser::Serialize for Value { #[inline] fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: ser::Serializer, { match *self { Value::Null => serializer.serialize_unit(), Value::Bool(v) => serializer.serialize_bool(v), Value::I64(v) => serializer.serialize_i64(v), Value::U64(v) => serializer.serialize_u64(v), Value::F64(v) => serializer.serialize_f64(v), Value::String(ref v) => serializer.serialize_str(v), Value::Array(ref v) => v.serialize(serializer), Value::Object(ref v) => v.serialize(serializer), } } } impl<'de> de::Deserialize<'de> for Value { #[inline] fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> where D: de::Deserializer<'de>, { struct ValueVisitor; impl<'de> de::Visitor<'de> for ValueVisitor { type Value = Value; fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("a json value") } #[inline] fn visit_bool<E>(self, value: bool) -> Result<Value, E> { Ok(Value::Bool(value)) } #[inline] fn visit_i64<E>(self, value: i64) -> Result<Value, E> { if value < 0 { Ok(Value::I64(value)) } else { Ok(Value::U64(value as u64)) } } #[inline] fn visit_u64<E>(self, value: u64) -> Result<Value, E> { Ok(Value::U64(value)) } #[inline] fn visit_f64<E>(self, value: f64) -> Result<Value, E> { Ok(Value::F64(value)) } #[inline] fn visit_str<E>(self, value: &str) -> Result<Value, E> where E: de::Error, { self.visit_string(String::from(value)) } #[inline] fn visit_string<E>(self, value: String) -> Result<Value, E> { Ok(Value::String(value)) } #[inline] fn visit_none<E>(self) -> Result<Value, E> { Ok(Value::Null) } #[inline] fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> where D: de::Deserializer<'de>, { de::Deserialize::deserialize(deserializer) } #[inline] fn visit_unit<E>(self) -> Result<Value, E> { Ok(Value::Null) } #[inline] fn visit_seq<A>(self, mut seq: A) -> Result<Value, A::Error> where A: de::SeqAccess<'de>, { let mut v = match seq.size_hint() { Some(cap) => Vec::with_capacity(cap), None => Vec::new(), }; while let Some(el) = seq.next_element()? { v.push(el) } Ok(Value::Array(v)) } #[inline] fn visit_map<A>(self, mut map: A) -> Result<Value, A::Error> where A: de::MapAccess<'de>, { let mut values = map_with_capacity(map.size_hint()); while let Some((k, v)) = map.next_entry()? { values.insert(k, v); } Ok(Value::Object(values)) } } deserializer.deserialize_any(ValueVisitor) } } struct WriterFormatter<'a, 'b: 'a> { inner: &'a mut fmt::Formatter<'b>, } impl io::Write for WriterFormatter<'_, '_> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { fn io_error<E>(_: E) -> io::Error { // Value does not matter because fmt::Debug and fmt::Display impls // below just map it to fmt::Error io::Error::other("fmt error") } let s = str::from_utf8(buf).map_err(io_error)?; self.inner.write_str(s).map_err(io_error)?; Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl fmt::Debug for Value { /// Serializes a Hjson value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut wr = WriterFormatter { inner: f }; super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error) } } impl fmt::Display for Value { /// Serializes a Hjson value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut wr = WriterFormatter { inner: f }; super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error) } } impl str::FromStr for Value { type Err = Error; fn from_str(s: &str) -> Result<Value> { super::de::from_str(s) } } /// Create a `serde::Serializer` that serializes a `Serialize`e into a `Value`. #[derive(Default)] pub struct Serializer; impl ser::Serializer for Serializer { type Ok = Value; type Error = Error; type SerializeSeq = SerializeVec; type SerializeTuple = SerializeVec; type SerializeTupleStruct = SerializeVec; type SerializeTupleVariant = SerializeTupleVariant; type SerializeMap = SerializeMap; type SerializeStruct = SerializeMap; type SerializeStructVariant = SerializeStructVariant; #[inline] fn serialize_bool(self, value: bool) -> Result<Value> { Ok(Value::Bool(value)) } #[inline] fn serialize_i8(self, value: i8) -> Result<Value> { self.serialize_i64(value as i64) } #[inline] fn serialize_i16(self, value: i16) -> Result<Value> { self.serialize_i64(value as i64) } #[inline] fn serialize_i32(self, value: i32) -> Result<Value> { self.serialize_i64(value as i64) } fn serialize_i64(self, value: i64) -> Result<Value> { let v = if value < 0 { Value::I64(value) } else { Value::U64(value as u64) }; Ok(v) } #[inline] fn serialize_u8(self, value: u8) -> Result<Value> { self.serialize_u64(value as u64) } #[inline] fn serialize_u16(self, value: u16) -> Result<Value> { self.serialize_u64(value as u64) } #[inline] fn serialize_u32(self, value: u32) -> Result<Value> { self.serialize_u64(value as u64) } #[inline] fn serialize_u64(self, value: u64) -> Result<Value> { Ok(Value::U64(value)) } #[inline] fn serialize_f32(self, value: f32) -> Result<Value> { self.serialize_f64(value as f64) } #[inline] fn serialize_f64(self, value: f64) -> Result<Value> { Ok(Value::F64(value)) } #[inline] fn serialize_char(self, value: char) -> Result<Value> { let mut s = String::new(); s.push(value); self.serialize_str(&s) } #[inline] fn serialize_str(self, value: &str) -> Result<Value> { Ok(Value::String(String::from(value))) } fn serialize_bytes(self, value: &[u8]) -> Result<Value> { let mut state = self.serialize_seq(Some(value.len()))?; for byte in value { ser::SerializeSeq::serialize_element(&mut state, byte)?; } ser::SerializeSeq::end(state) } #[inline] fn serialize_unit(self) -> Result<Value> { Ok(Value::Null) } #[inline] fn serialize_unit_struct(self, _name: &'static str) -> Result<Value> { self.serialize_unit() } #[inline] fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result<Value> { self.serialize_str(variant) } #[inline] fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Value> where T: ?Sized + ser::Serialize, { value.serialize(self) } fn serialize_newtype_variant<T>( self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result<Value> where T: ?Sized + ser::Serialize, { let mut values = Map::new(); values.insert(String::from(variant), to_value(&value)?); Ok(Value::Object(values)) } #[inline] fn serialize_none(self) -> Result<Value> { self.serialize_unit() } #[inline] fn serialize_some<V>(self, value: &V) -> Result<Value> where V: ?Sized + ser::Serialize, { value.serialize(self) } #[inline] fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { Ok(SerializeVec { vec: Vec::with_capacity(len.unwrap_or(0)), }) } #[inline] fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> { self.serialize_seq(Some(len)) } #[inline] fn serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeTupleStruct, Self::Error> { self.serialize_seq(Some(len)) } #[inline] fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeTupleVariant, Self::Error> { Ok(SerializeTupleVariant { name: variant, vec: Vec::with_capacity(len), }) } #[inline] fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { Ok(SerializeMap { map: map_with_capacity(len), next_key: None, }) } #[inline] fn serialize_struct( self, _name: &'static str, len: usize, ) -> Result<Self::SerializeStruct, Self::Error> { self.serialize_map(Some(len)) } #[inline] fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result<Self::SerializeStructVariant, Self::Error> { Ok(SerializeStructVariant { name: variant, map: map_with_capacity(Some(len)), }) } } #[doc(hidden)] pub struct SerializeVec { vec: Vec<Value>, } #[doc(hidden)] pub struct SerializeTupleVariant { name: &'static str, vec: Vec<Value>, } #[doc(hidden)] pub struct SerializeMap { map: Map<String, Value>, next_key: Option<String>, } #[doc(hidden)] pub struct SerializeStructVariant { name: &'static str, map: Map<String, Value>, } impl ser::SerializeSeq for SerializeVec { type Ok = Value; type Error = Error; fn serialize_element<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.vec.push(to_value(&value)?); Ok(()) } fn end(self) -> Result<Value> { Ok(Value::Array(self.vec)) } } impl ser::SerializeTuple for SerializeVec { type Ok = Value; type Error = Error; fn serialize_element<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result<Value> { ser::SerializeSeq::end(self) } } impl ser::SerializeTupleStruct for SerializeVec { type Ok = Value; type Error = Error; fn serialize_field<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result<Value> { ser::SerializeSeq::end(self) } } impl ser::SerializeTupleVariant for SerializeTupleVariant { type Ok = Value; type Error = Error; fn serialize_field<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.vec.push(to_value(&value)?); Ok(()) } fn end(self) -> Result<Value> { let mut object = Map::new(); object.insert(self.name.to_owned(), Value::Array(self.vec)); Ok(Value::Object(object)) } } impl ser::SerializeMap for SerializeMap { type Ok = Value; type Error = Error; fn serialize_key<T>(&mut self, key: &T) -> Result<()> where T: ?Sized + ser::Serialize, { match to_value(key)? { Value::String(s) => self.next_key = Some(s), _ => return Err(Error::Syntax(ErrorCode::KeyMustBeAString, 0, 0)), }; Ok(()) } fn serialize_value<T>(&mut self, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { let key = self.next_key.take(); // Panic because this indicates a bug in the program rather than an // expected failure. let key = key.expect("serialize_value called before serialize_key"); self.map.insert(key, to_value(value)?); Ok(()) } fn end(self) -> Result<Value> { Ok(Value::Object(self.map)) } } impl ser::SerializeStruct for SerializeMap { type Ok = Value; type Error = Error; fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { ser::SerializeMap::serialize_entry(self, key, value) } fn end(self) -> Result<Value> { ser::SerializeMap::end(self) } } impl ser::SerializeStructVariant for SerializeStructVariant { type Ok = Value; type Error = Error; fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + ser::Serialize, { self.map.insert(key.to_owned(), to_value(&value)?); Ok(()) } fn end(self) -> Result<Value> { let mut object = map_with_capacity(Some(1)); object.insert(self.name.to_owned(), Value::Object(self.map)); Ok(Value::Object(object)) } } impl<'de> de::Deserializer<'de> for Value { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { match self { Value::Null => visitor.visit_unit(), Value::Bool(v) => visitor.visit_bool(v), Value::I64(v) => visitor.visit_i64(v), Value::U64(v) => visitor.visit_u64(v), Value::F64(v) => visitor.visit_f64(v), Value::String(v) => visitor.visit_string(v), Value::Array(v) => visitor.visit_seq(SeqDeserializer { iter: v.into_iter(), }), Value::Object(v) => visitor.visit_map(MapDeserializer { iter: v.into_iter(), value: None, }), } } #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { match self { Value::Null => visitor.visit_none(), _ => visitor.visit_some(self), } } #[inline] fn deserialize_enum<V>( self, _name: &str, _variants: &'static [&'static str], visitor: V, ) -> Result<V::Value> where V: de::Visitor<'de>, { let (variant, value) = match self { Value::Object(value) => { let mut iter = value.into_iter(); let (variant, value) = match iter.next() { Some(v) => v, None => { return Err(de::Error::invalid_type( de::Unexpected::Map, &"map with a single key", )); } }; // enums are encoded in json as maps with a single key:value pair if iter.next().is_some() { return Err(de::Error::invalid_type( de::Unexpected::Map, &"map with a single key", )); } (variant, Some(value)) } Value::String(variant) => (variant, None), val => { return Err(de::Error::invalid_type( val.as_unexpected(), &"string or map", )); } }; visitor.visit_enum(EnumDeserializer { variant, value }) } #[inline] fn deserialize_newtype_struct<V>( self, _name: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: de::Visitor<'de>, { visitor.visit_newtype_struct(self) } serde::forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf unit unit_struct seq tuple tuple_struct map struct identifier ignored_any } } struct EnumDeserializer { variant: String, value: Option<Value>, } impl<'de> de::EnumAccess<'de> for EnumDeserializer { type Error = Error; type Variant = VariantDeserializer; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: de::DeserializeSeed<'de>, { let variant = de::IntoDeserializer::into_deserializer(self.variant); let visitor = VariantDeserializer { val: self.value }; seed.deserialize(variant).map(|v| (v, visitor)) } } struct VariantDeserializer { val: Option<Value>, } impl<'de> de::VariantAccess<'de> for VariantDeserializer { type Error = Error; fn unit_variant(self) -> Result<()> { match self.val { Some(val) => de::Deserialize::deserialize(val), None => Ok(()), } } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> where T: de::DeserializeSeed<'de>, { match self.val { Some(value) => seed.deserialize(value), None => Err(serde::de::Error::invalid_type( de::Unexpected::UnitVariant, &"newtype variant", )), } } fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let val = self.val.expect("val is missing"); if let Value::Array(fields) = val { visitor.visit_seq(SeqDeserializer { iter: fields.into_iter(), }) } else { Err(de::Error::invalid_type(val.as_unexpected(), &visitor)) } } fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { match self.val { Some(Value::Object(fields)) => visitor.visit_map(MapDeserializer { iter: fields.into_iter(), value: None, }), Some(other) => Err(de::Error::invalid_type( other.as_unexpected(), &"struct variant", )), None => Err(de::Error::invalid_type( de::Unexpected::UnitVariant, &"struct variant", )), } } } struct SeqDeserializer { iter: vec::IntoIter<Value>, } impl<'de> de::SeqAccess<'de> for SeqDeserializer { type Error = Error; fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> where T: de::DeserializeSeed<'de>, { match self.iter.next() { Some(value) => Ok(Some(seed.deserialize(value)?)), None => Ok(None), } } fn size_hint(&self) -> Option<usize> { match self.iter.size_hint() { (lower, Some(upper)) if lower == upper => Some(upper), _ => None, } } } struct MapDeserializer { iter: MapIntoIter<String, Value>, value: Option<Value>, } impl<'de> de::MapAccess<'de> for MapDeserializer { type Error = Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> where K: de::DeserializeSeed<'de>, { match self.iter.next() { Some((key, value)) => { self.value = Some(value); Ok(Some(seed.deserialize(Value::String(key))?)) } None => Ok(None), } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> where V: de::DeserializeSeed<'de>, { let value = self.value.take().expect("value is missing"); seed.deserialize(value) } fn size_hint(&self) -> Option<usize> { match self.iter.size_hint() { (lower, Some(upper)) if lower == upper => Some(upper), _ => None, } } } pub fn to_value<T>(value: &T) -> Result<Value> where T: ser::Serialize + ?Sized, { value.serialize(Serializer) } /// Shortcut function to decode a Hjson `Value` into a `T` pub fn from_value<T>(value: Value) -> Result<T> where T: de::DeserializeOwned, { de::Deserialize::deserialize(value) } /// A trait for converting values to Hjson pub trait ToJson { /// Converts the value of `self` to an instance of Hjson fn to_json(&self) -> Value; } impl<T: ?Sized> ToJson for T where T: ser::Serialize, { fn to_json(&self) -> Value { to_value(&self).expect("failed to serialize") } } #[cfg(test)] mod test { use super::Value; use crate::de::from_str; #[test] fn number_deserialize() { let v: Value = from_str("{\"a\":1}").unwrap(); let vo = v.as_object().unwrap(); assert_eq!(vo["a"].as_u64().unwrap(), 1); let v: Value = from_str("{\"a\":-1}").unwrap(); let vo = v.as_object().unwrap(); assert_eq!(vo["a"].as_i64().unwrap(), -1); let v: Value = from_str("{\"a\":1.1}").unwrap(); let vo = v.as_object().unwrap(); assert!((vo["a"].as_f64().unwrap() - 1.1).abs() < f64::EPSILON); let v: Value = from_str("{\"a\":-1.1}").unwrap(); let vo = v.as_object().unwrap(); assert!((vo["a"].as_f64().unwrap() + 1.1).abs() < f64::EPSILON); let v: Value = from_str("{\"a\":1e6}").unwrap(); let vo = v.as_object().unwrap(); assert!((vo["a"].as_f64().unwrap() - 1e6).abs() < f64::EPSILON); let v: Value = from_str("{\"a\":-1e6}").unwrap(); let vo = v.as_object().unwrap(); assert!((vo["a"].as_f64().unwrap() + 1e6).abs() < f64::EPSILON); } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-json/src/error.rs
crates/nu-json/src/error.rs
//! JSON Errors //! //! This module is centered around the `Error` and `ErrorCode` types, which represents all possible //! `serde_hjson` errors. use std::error; use std::fmt; use std::io; use std::result; use std::string::FromUtf8Error; use serde::de; use serde::ser; /// The errors that can arise while parsing a JSON stream. #[derive(Clone, PartialEq, Eq)] pub enum ErrorCode { /// Catchall for syntax error messages Custom(String), /// EOF while parsing a list. EofWhileParsingList, /// EOF while parsing an object. EofWhileParsingObject, /// EOF while parsing a string. EofWhileParsingString, /// EOF while parsing a JSON value. EofWhileParsingValue, /// Expected this character to be a `':'`. ExpectedColon, /// Expected this character to be either a `','` or a `]`. ExpectedListCommaOrEnd, /// Expected this character to be either a `','` or a `}`. ExpectedObjectCommaOrEnd, /// Expected to parse either a `true`, `false`, or a `null`. ExpectedSomeIdent, /// Expected this character to start a JSON value. ExpectedSomeValue, /// Invalid hex escape code. InvalidEscape, /// Invalid number. InvalidNumber, /// Invalid Unicode code point. InvalidUnicodeCodePoint, /// Object key is not a string. KeyMustBeAString, /// Lone leading surrogate in hex escape. LoneLeadingSurrogateInHexEscape, /// JSON has non-whitespace trailing characters after the value. TrailingCharacters, /// Unexpected end of hex escape. UnexpectedEndOfHexEscape, /// Found a punctuator character when expecting a quoteless string. PunctuatorInQlString, } impl fmt::Debug for ErrorCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //use std::fmt::Debug; match *self { ErrorCode::Custom(ref msg) => write!(f, "{msg}"), ErrorCode::EofWhileParsingList => "EOF while parsing a list".fmt(f), ErrorCode::EofWhileParsingObject => "EOF while parsing an object".fmt(f), ErrorCode::EofWhileParsingString => "EOF while parsing a string".fmt(f), ErrorCode::EofWhileParsingValue => "EOF while parsing a value".fmt(f), ErrorCode::ExpectedColon => "expected `:`".fmt(f), ErrorCode::ExpectedListCommaOrEnd => "expected `,` or `]`".fmt(f), ErrorCode::ExpectedObjectCommaOrEnd => "expected `,` or `}`".fmt(f), ErrorCode::ExpectedSomeIdent => "expected ident".fmt(f), ErrorCode::ExpectedSomeValue => "expected value".fmt(f), ErrorCode::InvalidEscape => "invalid escape".fmt(f), ErrorCode::InvalidNumber => "invalid number".fmt(f), ErrorCode::InvalidUnicodeCodePoint => "invalid Unicode code point".fmt(f), ErrorCode::KeyMustBeAString => "key must be a string".fmt(f), ErrorCode::LoneLeadingSurrogateInHexEscape => { "lone leading surrogate in hex escape".fmt(f) } ErrorCode::TrailingCharacters => "trailing characters".fmt(f), ErrorCode::UnexpectedEndOfHexEscape => "unexpected end of hex escape".fmt(f), ErrorCode::PunctuatorInQlString => { "found a punctuator character when expecting a quoteless string".fmt(f) } } } } /// This type represents all possible errors that can occur when serializing or deserializing a /// value into JSON. #[derive(Debug)] pub enum Error { /// The JSON value had some syntactic error. Syntax(ErrorCode, usize, usize), /// Some IO error occurred when serializing or deserializing a value. Io(io::Error), /// Some UTF8 error occurred while serializing or deserializing a value. FromUtf8(FromUtf8Error), } impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { match *self { Error::Io(ref error) => Some(error), Error::FromUtf8(ref error) => Some(error), _ => None, } } } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Error::Syntax(ref code, line, col) => { write!(fmt, "{code:?} at line {line} column {col}") } Error::Io(ref error) => fmt::Display::fmt(error, fmt), Error::FromUtf8(ref error) => fmt::Display::fmt(error, fmt), } } } impl From<io::Error> for Error { fn from(error: io::Error) -> Error { Error::Io(error) } } impl From<FromUtf8Error> for Error { fn from(error: FromUtf8Error) -> Error { Error::FromUtf8(error) } } impl de::Error for Error { fn custom<T: fmt::Display>(msg: T) -> Error { Error::Syntax(ErrorCode::Custom(msg.to_string()), 0, 0) } } impl ser::Error for Error { /// Raised when there is general error when deserializing a type. fn custom<T: fmt::Display>(msg: T) -> Error { Error::Syntax(ErrorCode::Custom(msg.to_string()), 0, 0) } } /// Helper alias for `Result` objects that return a JSON `Error`. pub type Result<T> = result::Result<T, Error>;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-json/src/util.rs
crates/nu-json/src/util.rs
use std::io; use std::str; use super::error::{Error, ErrorCode, Result}; pub struct StringReader<Iter: Iterator<Item = u8>> { iter: Iter, line: usize, col: usize, ch: Vec<u8>, } impl<Iter> StringReader<Iter> where Iter: Iterator<Item = u8>, { #[inline] pub fn new(iter: Iter) -> Self { StringReader { iter, line: 1, col: 0, ch: Vec::new(), } } fn next(&mut self) -> Option<io::Result<u8>> { match self.iter.next() { None => None, Some(b'\n') => { self.line += 1; self.col = 0; Some(Ok(b'\n')) } Some(c) => { self.col += 1; Some(Ok(c)) } } } pub fn pos(&mut self) -> (usize, usize) { (self.line, self.col) } pub fn eof(&mut self) -> Result<bool> { let ch = self.peek()?; Ok(matches!(ch, None | Some(b'\x00'))) } pub fn peek_next(&mut self, idx: usize) -> Result<Option<u8>> { while self.ch.len() <= idx { match self.next() { Some(Err(err)) => return Err(Error::Io(err)), Some(Ok(ch)) => self.ch.push(ch), None => return Ok(None), } } Ok(Some(self.ch[idx])) } pub fn peek(&mut self) -> Result<Option<u8>> { self.peek_next(0) } pub fn peek_or_null(&mut self) -> Result<u8> { Ok(self.peek()?.unwrap_or(b'\x00')) } pub fn eat_char(&mut self) -> u8 { self.ch.remove(0) } pub fn uneat_char(&mut self, ch: u8) { self.ch.insert(0, ch); } pub fn next_char(&mut self) -> Result<Option<u8>> { match self.ch.first() { Some(&ch) => { self.eat_char(); Ok(Some(ch)) } None => match self.next() { Some(Err(err)) => Err(Error::Io(err)), Some(Ok(ch)) => Ok(Some(ch)), None => Ok(None), }, } } pub fn next_char_or_null(&mut self) -> Result<u8> { Ok(self.next_char()?.unwrap_or(b'\x00')) } fn eat_line(&mut self) -> Result<()> { loop { match self.peek()? { Some(b'\n') | None => return Ok(()), _ => {} } self.eat_char(); } } pub fn parse_whitespace(&mut self) -> Result<()> { loop { match self.peek_or_null()? { b' ' | b'\n' | b'\t' | b'\r' => { self.eat_char(); } b'#' => self.eat_line()?, b'/' => { match self.peek_next(1)? { Some(b'/') => self.eat_line()?, Some(b'*') => { self.eat_char(); self.eat_char(); while !(self.peek()?.unwrap_or(b'*') == b'*' && self.peek_next(1)?.unwrap_or(b'/') == b'/') { self.eat_char(); } self.eat_char(); self.eat_char(); } Some(_) => { self.eat_char(); } None => return Err(self.error(ErrorCode::TrailingCharacters)), //todo } } _ => { return Ok(()); } } } } pub fn error(&mut self, reason: ErrorCode) -> Error { Error::Syntax(reason, self.line, self.col) } } pub enum Number { I64(i64), U64(u64), F64(f64), } pub struct ParseNumber<Iter: Iterator<Item = u8>> { rdr: StringReader<Iter>, result: Vec<u8>, } impl<Iter: Iterator<Item = u8>> ParseNumber<Iter> { #[inline] pub fn new(iter: Iter) -> Self { ParseNumber { rdr: StringReader::new(iter), result: Vec::new(), } } pub fn parse(&mut self, stop_at_next: bool) -> Result<Number> { match self.try_parse() { Ok(()) => { self.rdr.parse_whitespace()?; let mut ch = self.rdr.next_char_or_null()?; if stop_at_next { let ch2 = self.rdr.peek_or_null()?; // end scan if we find a punctuator character like ,}] or a comment if ch == b',' || ch == b'}' || ch == b']' || ch == b'#' || ch == b'/' && (ch2 == b'/' || ch2 == b'*') { ch = b'\x00'; } } match ch { b'\x00' => { let res = str::from_utf8(&self.result).expect("Internal error: json parsing"); let mut is_float = false; for ch in res.chars() { if ch == '.' || ch == 'e' || ch == 'E' { is_float = true; break; } } if !is_float { if res.starts_with('-') { if let Ok(n) = res.parse::<i64>() { return Ok(Number::I64(n)); } } else if let Ok(n) = res.parse::<u64>() { return Ok(Number::U64(n)); } } match res.parse::<f64>() { Ok(n) => Ok(Number::F64(n)), _ => Err(Error::Syntax(ErrorCode::InvalidNumber, 0, 0)), } } _ => Err(Error::Syntax(ErrorCode::InvalidNumber, 0, 0)), } } Err(e) => Err(e), } } fn try_parse(&mut self) -> Result<()> { if self.rdr.peek_or_null()? == b'-' { self.result.push(self.rdr.eat_char()); } let mut has_value = false; if self.rdr.peek_or_null()? == b'0' { self.result.push(self.rdr.eat_char()); has_value = true; // There can be only one leading '0'. if let b'0'..=b'9' = self.rdr.peek_or_null()? { return Err(Error::Syntax(ErrorCode::InvalidNumber, 0, 0)); } } loop { match self.rdr.peek_or_null()? { b'0'..=b'9' => { self.result.push(self.rdr.eat_char()); has_value = true; } b'.' => { if !has_value { return Err(Error::Syntax(ErrorCode::InvalidNumber, 0, 0)); } self.rdr.eat_char(); return self.try_decimal(); } b'e' | b'E' => { if !has_value { return Err(Error::Syntax(ErrorCode::InvalidNumber, 0, 0)); } self.rdr.eat_char(); return self.try_exponent(); } _ => { if !has_value { return Err(Error::Syntax(ErrorCode::InvalidNumber, 0, 0)); } return Ok(()); } } } } fn try_decimal(&mut self) -> Result<()> { self.result.push(b'.'); // Make sure a digit follows the decimal place. match self.rdr.next_char_or_null()? { c @ b'0'..=b'9' => { self.result.push(c); } _ => { return Err(Error::Syntax(ErrorCode::InvalidNumber, 0, 0)); } }; while let b'0'..=b'9' = self.rdr.peek_or_null()? { self.result.push(self.rdr.eat_char()); } match self.rdr.peek_or_null()? { b'e' | b'E' => { self.rdr.eat_char(); self.try_exponent() } _ => Ok(()), } } fn try_exponent(&mut self) -> Result<()> { self.result.push(b'e'); match self.rdr.peek_or_null()? { b'+' => { self.result.push(self.rdr.eat_char()); } b'-' => { self.result.push(self.rdr.eat_char()); } _ => {} }; // Make sure a digit follows the exponent place. match self.rdr.next_char_or_null()? { c @ b'0'..=b'9' => { self.result.push(c); } _ => { return Err(Error::Syntax(ErrorCode::InvalidNumber, 0, 0)); } }; while let b'0'..=b'9' = self.rdr.peek_or_null()? { self.result.push(self.rdr.eat_char()); } Ok(()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-json/src/de.rs
crates/nu-json/src/de.rs
//! Hjson Deserialization //! //! This module provides for Hjson deserialization with the type `Deserializer`. use super::error::{Error, ErrorCode, Result}; use super::util::StringReader; use super::util::{Number, ParseNumber}; use serde::de; use std::{ char, io, io::{BufReader, Read}, marker::PhantomData, str, }; enum State { Normal, Root, Keyname, } /// A structure that deserializes Hjson into Rust values. pub struct Deserializer<Iter: Iterator<Item = u8>> { rdr: StringReader<Iter>, str_buf: Vec<u8>, state: State, } impl<Iter> Deserializer<Iter> where Iter: Iterator<Item = u8>, { /// Creates the Hjson parser from an `std::iter::Iterator`. #[inline] pub fn new(rdr: Iter) -> Deserializer<Iter> { Deserializer { rdr: StringReader::new(rdr), str_buf: Vec::with_capacity(128), state: State::Normal, } } /// Creates the Hjson parser from an `std::iter::Iterator`. #[inline] pub fn new_for_root(rdr: Iter) -> Deserializer<Iter> { let mut res = Deserializer::new(rdr); res.state = State::Root; res } /// The `Deserializer::end` method should be called after a value has been fully deserialized. /// This allows the `Deserializer` to validate that the input stream is at the end or that it /// only has trailing whitespace. #[inline] pub fn end(&mut self) -> Result<()> { self.rdr.parse_whitespace()?; if self.rdr.eof()? { Ok(()) } else { Err(self.rdr.error(ErrorCode::TrailingCharacters)) } } fn is_punctuator_char(&self, ch: u8) -> bool { matches!(ch, b'{' | b'}' | b'[' | b']' | b',' | b':') } fn parse_keyname<'de, V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { // quotes for keys are optional in Hjson // unless they include {}[],: or whitespace. // assume whitespace was already eaten self.str_buf.clear(); let mut space: Option<usize> = None; loop { let ch = self.rdr.next_char_or_null()?; if ch == b':' { if self.str_buf.is_empty() { return Err(self.rdr.error(ErrorCode::Custom( "Found ':' but no key name (for an empty key name use quotes)".to_string(), ))); } else if space.is_some() && space.expect("Internal error: json parsing") != self.str_buf.len() { return Err(self.rdr.error(ErrorCode::Custom( "Found whitespace in your key name (use quotes to include)".to_string(), ))); } self.rdr.uneat_char(ch); let s = str::from_utf8(&self.str_buf).expect("Internal error: json parsing"); return visitor.visit_str(s); } else if ch <= b' ' { if ch == 0 { return Err(self.rdr.error(ErrorCode::EofWhileParsingObject)); } else if space.is_none() { space = Some(self.str_buf.len()); } } else if self.is_punctuator_char(ch) { return Err(self.rdr.error(ErrorCode::Custom("Found a punctuator where a key name was expected (check your syntax or use quotes if the key name includes {}[],: or whitespace)".to_string()))); } else { self.str_buf.push(ch); } } } fn parse_value<'de, V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.rdr.parse_whitespace()?; if self.rdr.eof()? { return Err(self.rdr.error(ErrorCode::EofWhileParsingValue)); } match self.state { State::Keyname => { self.state = State::Normal; return self.parse_keyname(visitor); } State::Root => { self.state = State::Normal; return self.visit_map(true, visitor); } _ => {} } match self.rdr.peek_or_null()? { /* b'-' => { self.rdr.eat_char(); self.parse_integer(false, visitor) } b'0' ... b'9' => { self.parse_integer(true, visitor) } */ b'"' => { self.rdr.eat_char(); self.parse_string()?; let s = str::from_utf8(&self.str_buf).expect("Internal error: json parsing"); visitor.visit_str(s) } b'[' => { self.rdr.eat_char(); let ret = visitor.visit_seq(SeqVisitor::new(self))?; self.rdr.parse_whitespace()?; match self.rdr.next_char()? { Some(b']') => Ok(ret), Some(_) => Err(self.rdr.error(ErrorCode::TrailingCharacters)), None => Err(self.rdr.error(ErrorCode::EofWhileParsingList)), } } b'{' => { self.rdr.eat_char(); self.visit_map(false, visitor) } b'\x00' => Err(self.rdr.error(ErrorCode::ExpectedSomeValue)), _ => self.parse_tfnns(visitor), } } fn visit_map<'de, V>(&mut self, root: bool, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { let ret = visitor.visit_map(MapVisitor::new(self, root))?; self.rdr.parse_whitespace()?; match self.rdr.next_char()? { Some(b'}') => { if !root { Ok(ret) } else { Err(self.rdr.error(ErrorCode::TrailingCharacters)) } // todo } Some(_) => Err(self.rdr.error(ErrorCode::TrailingCharacters)), None => { if root { Ok(ret) } else { Err(self.rdr.error(ErrorCode::EofWhileParsingObject)) } } } } fn parse_ident(&mut self, ident: &[u8]) -> Result<()> { for c in ident { if Some(*c) != self.rdr.next_char()? { return Err(self.rdr.error(ErrorCode::ExpectedSomeIdent)); } } Ok(()) } fn parse_tfnns<'de, V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { // Hjson strings can be quoteless // returns string, true, false, or null. self.str_buf.clear(); let first = self.rdr.peek()?.expect("Internal error: json parsing"); if self.is_punctuator_char(first) { return Err(self.rdr.error(ErrorCode::PunctuatorInQlString)); } loop { let ch = self.rdr.next_char_or_null()?; let is_eol = ch == b'\r' || ch == b'\n' || ch == b'\x00'; let is_comment = ch == b'#' || if ch == b'/' { let next = self.rdr.peek_or_null()?; next == b'/' || next == b'*' } else { false }; if is_eol || is_comment || ch == b',' || ch == b'}' || ch == b']' { let chf = self.str_buf[0]; match chf { b'f' => { if str::from_utf8(&self.str_buf) .expect("Internal error: json parsing") .trim() == "false" { self.rdr.uneat_char(ch); return visitor.visit_bool(false); } } b'n' => { if str::from_utf8(&self.str_buf) .expect("Internal error: json parsing") .trim() == "null" { self.rdr.uneat_char(ch); return visitor.visit_unit(); } } b't' => { if str::from_utf8(&self.str_buf) .expect("Internal error: json parsing") .trim() == "true" { self.rdr.uneat_char(ch); return visitor.visit_bool(true); } } _ => { if chf == b'-' || chf.is_ascii_digit() { let mut parser = ParseNumber::new(self.str_buf.iter().copied()); match parser.parse(false) { Ok(Number::F64(v)) => { self.rdr.uneat_char(ch); return visitor.visit_f64(v); } Ok(Number::U64(v)) => { self.rdr.uneat_char(ch); return visitor.visit_u64(v); } Ok(Number::I64(v)) => { self.rdr.uneat_char(ch); return visitor.visit_i64(v); } Err(_) => {} // not a number, continue } } } } if is_eol { // remove any whitespace at the end (ignored in quoteless strings) return visitor.visit_str( str::from_utf8(&self.str_buf) .expect("Internal error: json parsing") .trim(), ); } } self.str_buf.push(ch); if self.str_buf == b"'''" { return self.parse_ml_string(visitor); } } } fn decode_hex_escape(&mut self) -> Result<u16> { let mut i = 0; let mut n = 0u16; while i < 4 && !self.rdr.eof()? { n = match self.rdr.next_char_or_null()? { c @ b'0'..=b'9' => n * 16_u16 + ((c as u16) - (b'0' as u16)), b'a' | b'A' => n * 16_u16 + 10_u16, b'b' | b'B' => n * 16_u16 + 11_u16, b'c' | b'C' => n * 16_u16 + 12_u16, b'd' | b'D' => n * 16_u16 + 13_u16, b'e' | b'E' => n * 16_u16 + 14_u16, b'f' | b'F' => n * 16_u16 + 15_u16, _ => { return Err(self.rdr.error(ErrorCode::InvalidEscape)); } }; i += 1; } // Error out if we didn't parse 4 digits. if i != 4 { return Err(self.rdr.error(ErrorCode::InvalidEscape)); } Ok(n) } fn ml_skip_white(&mut self) -> Result<bool> { match self.rdr.peek_or_null()? { b' ' | b'\t' | b'\r' => { self.rdr.eat_char(); Ok(true) } _ => Ok(false), } } fn ml_skip_indent(&mut self, indent: usize) -> Result<()> { let mut skip = indent; while self.ml_skip_white()? && skip > 0 { skip -= 1; } Ok(()) } fn parse_ml_string<'de, V>(&mut self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.str_buf.clear(); // Parse a multiline string value. let mut triple = 0; // we are at ''' +1 - get indent let (_, col) = self.rdr.pos(); let indent = col - 4; // skip white/to (newline) while self.ml_skip_white()? {} if self.rdr.peek_or_null()? == b'\n' { self.rdr.eat_char(); self.ml_skip_indent(indent)?; } // When parsing multiline string values, we must look for ' characters. loop { if self.rdr.eof()? { return Err(self.rdr.error(ErrorCode::EofWhileParsingString)); } // todo error("Bad multiline string"); let ch = self.rdr.next_char_or_null()?; if ch == b'\'' { triple += 1; if triple == 3 { if self.str_buf.last() == Some(&b'\n') { self.str_buf.pop(); } let res = str::from_utf8(&self.str_buf).expect("Internal error: json parsing"); //todo if (self.str_buf.slice(-1) === '\n') self.str_buf=self.str_buf.slice(0, -1); // remove last EOL return visitor.visit_str(res); } else { continue; } } while triple > 0 { self.str_buf.push(b'\''); triple -= 1; } if ch != b'\r' { self.str_buf.push(ch); } if ch == b'\n' { self.ml_skip_indent(indent)?; } } } fn parse_string(&mut self) -> Result<()> { self.str_buf.clear(); loop { let ch = match self.rdr.next_char()? { Some(ch) => ch, None => { return Err(self.rdr.error(ErrorCode::EofWhileParsingString)); } }; match ch { b'"' => { return Ok(()); } b'\\' => { let ch = match self.rdr.next_char()? { Some(ch) => ch, None => { return Err(self.rdr.error(ErrorCode::EofWhileParsingString)); } }; match ch { b'"' => self.str_buf.push(b'"'), b'\\' => self.str_buf.push(b'\\'), b'/' => self.str_buf.push(b'/'), b'b' => self.str_buf.push(b'\x08'), b'f' => self.str_buf.push(b'\x0c'), b'n' => self.str_buf.push(b'\n'), b'r' => self.str_buf.push(b'\r'), b't' => self.str_buf.push(b'\t'), b'u' => { let c = match self.decode_hex_escape()? { 0xDC00..=0xDFFF => { return Err(self .rdr .error(ErrorCode::LoneLeadingSurrogateInHexEscape)); } // Non-BMP characters are encoded as a sequence of // two hex escapes, representing UTF-16 surrogates. n1 @ 0xD800..=0xDBFF => { match (self.rdr.next_char()?, self.rdr.next_char()?) { (Some(b'\\'), Some(b'u')) => (), _ => { return Err(self .rdr .error(ErrorCode::UnexpectedEndOfHexEscape)); } } let n2 = self.decode_hex_escape()?; if !(0xDC00..=0xDFFF).contains(&n2) { return Err(self .rdr .error(ErrorCode::LoneLeadingSurrogateInHexEscape)); } let n = ((((n1 - 0xD800) as u32) << 10) | (n2 - 0xDC00) as u32) + 0x1_0000; match char::from_u32(n) { Some(c) => c, None => { return Err(self .rdr .error(ErrorCode::InvalidUnicodeCodePoint)); } } } n => match char::from_u32(n as u32) { Some(c) => c, None => { return Err(self .rdr .error(ErrorCode::InvalidUnicodeCodePoint)); } }, }; self.str_buf.extend(c.encode_utf8(&mut [0; 4]).as_bytes()); } _ => { return Err(self.rdr.error(ErrorCode::InvalidEscape)); } } } ch => { self.str_buf.push(ch); } } } } fn parse_object_colon(&mut self) -> Result<()> { self.rdr.parse_whitespace()?; match self.rdr.next_char()? { Some(b':') => Ok(()), Some(_) => Err(self.rdr.error(ErrorCode::ExpectedColon)), None => Err(self.rdr.error(ErrorCode::EofWhileParsingObject)), } } } impl<'de, Iter> de::Deserializer<'de> for &mut Deserializer<Iter> where Iter: Iterator<Item = u8>, { type Error = Error; #[inline] fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { if let State::Root = self.state {} self.parse_value(visitor) } /// Parses a `null` as a None, and any other values as a `Some(...)`. #[inline] fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { self.rdr.parse_whitespace()?; match self.rdr.peek_or_null()? { b'n' => { self.rdr.eat_char(); self.parse_ident(b"ull")?; visitor.visit_none() } _ => visitor.visit_some(self), } } /// Parses a newtype struct as the underlying value. #[inline] fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { visitor.visit_newtype_struct(self) } serde::forward_to_deserialize_any! { bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf unit unit_struct seq tuple map tuple_struct struct enum identifier ignored_any } } struct SeqVisitor<'a, Iter: 'a + Iterator<Item = u8>> { de: &'a mut Deserializer<Iter>, } impl<'a, Iter: Iterator<Item = u8>> SeqVisitor<'a, Iter> { fn new(de: &'a mut Deserializer<Iter>) -> Self { SeqVisitor { de } } } impl<'de, Iter> de::SeqAccess<'de> for SeqVisitor<'_, Iter> where Iter: Iterator<Item = u8>, { type Error = Error; fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> where T: de::DeserializeSeed<'de>, { self.de.rdr.parse_whitespace()?; match self.de.rdr.peek()? { Some(b']') => { return Ok(None); } Some(_) => {} None => { return Err(self.de.rdr.error(ErrorCode::EofWhileParsingList)); } } let value = seed.deserialize(&mut *self.de)?; // in Hjson the comma is optional and trailing commas are allowed self.de.rdr.parse_whitespace()?; if self.de.rdr.peek()? == Some(b',') { self.de.rdr.eat_char(); self.de.rdr.parse_whitespace()?; } Ok(Some(value)) } } struct MapVisitor<'a, Iter: 'a + Iterator<Item = u8>> { de: &'a mut Deserializer<Iter>, first: bool, root: bool, } impl<'a, Iter: Iterator<Item = u8>> MapVisitor<'a, Iter> { fn new(de: &'a mut Deserializer<Iter>, root: bool) -> Self { MapVisitor { de, first: true, root, } } } impl<'de, Iter> de::MapAccess<'de> for MapVisitor<'_, Iter> where Iter: Iterator<Item = u8>, { type Error = Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> where K: de::DeserializeSeed<'de>, { self.de.rdr.parse_whitespace()?; if self.first { self.first = false; } else if self.de.rdr.peek()? == Some(b',') { // in Hjson the comma is optional and trailing commas are allowed self.de.rdr.eat_char(); self.de.rdr.parse_whitespace()?; } match self.de.rdr.peek()? { Some(b'}') => return Ok(None), // handled later for root Some(_) => {} None => { if self.root { return Ok(None); } else { return Err(self.de.rdr.error(ErrorCode::EofWhileParsingObject)); } } } match self.de.rdr.peek()? { Some(ch) => { self.de.state = if ch == b'"' { State::Normal } else { State::Keyname }; Ok(Some(seed.deserialize(&mut *self.de)?)) } None => Err(self.de.rdr.error(ErrorCode::EofWhileParsingValue)), } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> where V: de::DeserializeSeed<'de>, { self.de.parse_object_colon()?; seed.deserialize(&mut *self.de) } } impl<'de, Iter> de::VariantAccess<'de> for &mut Deserializer<Iter> where Iter: Iterator<Item = u8>, { type Error = Error; fn unit_variant(self) -> Result<()> { de::Deserialize::deserialize(self) } fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> where T: de::DeserializeSeed<'de>, { seed.deserialize(self) } fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { de::Deserializer::deserialize_any(self, visitor) } fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> where V: de::Visitor<'de>, { de::Deserializer::deserialize_any(self, visitor) } } ////////////////////////////////////////////////////////////////////////////// /// Iterator that deserializes a stream into multiple Hjson values. pub struct StreamDeserializer<T, Iter> where Iter: Iterator<Item = u8>, T: de::DeserializeOwned, { deser: Deserializer<Iter>, _marker: PhantomData<T>, } impl<T, Iter> StreamDeserializer<T, Iter> where Iter: Iterator<Item = u8>, T: de::DeserializeOwned, { /// Returns an `Iterator` of decoded Hjson values from an iterator over /// `Iterator<Item=u8>`. pub fn new(iter: Iter) -> StreamDeserializer<T, Iter> { StreamDeserializer { deser: Deserializer::new(iter), _marker: PhantomData, } } } impl<T, Iter> Iterator for StreamDeserializer<T, Iter> where Iter: Iterator<Item = u8>, T: de::DeserializeOwned, { type Item = Result<T>; fn next(&mut self) -> Option<Result<T>> { // skip whitespaces, if any // this helps with trailing whitespaces, since whitespaces between // values are handled for us. if let Err(e) = self.deser.rdr.parse_whitespace() { return Some(Err(e)); }; match self.deser.rdr.eof() { Ok(true) => None, Ok(false) => match de::Deserialize::deserialize(&mut self.deser) { Ok(v) => Some(Ok(v)), Err(e) => Some(Err(e)), }, Err(e) => Some(Err(e)), } } } ////////////////////////////////////////////////////////////////////////////// /// Decodes a Hjson value from an iterator over an iterator /// `Iterator<Item=u8>`. pub fn from_iter<I, T>(iter: I) -> Result<T> where I: Iterator<Item = io::Result<u8>>, T: de::DeserializeOwned, { let fold: io::Result<Vec<_>> = iter.collect(); if let Err(e) = fold { return Err(Error::Io(e)); } let bytes = fold.expect("Internal error: json parsing"); // deserialize tries first to decode with legacy support (new_for_root) // and then with the standard method if this fails. // todo: add compile switch // deserialize and make sure the whole stream has been consumed let mut de = Deserializer::new_for_root(bytes.iter().copied()); de::Deserialize::deserialize(&mut de) .and_then(|x| de.end().map(|()| x)) .or_else(|_| { let mut de2 = Deserializer::new(bytes.iter().copied()); de::Deserialize::deserialize(&mut de2).and_then(|x| de2.end().map(|()| x)) }) /* without legacy support: // deserialize and make sure the whole stream has been consumed let mut de = Deserializer::new(bytes.iter().map(|b| *b)); let value = match de::Deserialize::deserialize(&mut de) .and_then(|x| { try!(de.end()); Ok(x) }) { Ok(v) => Ok(v), Err(e) => Err(e), }; */ } /// Decodes a Hjson value from a `std::io::Read`. pub fn from_reader<R, T>(rdr: R) -> Result<T> where R: io::Read, T: de::DeserializeOwned, { // Use a buffered reader so that calling `.bytes()` is efficient and // doesn't trigger clippy's `unbuffered_bytes` lint when the input // comes from a non-memory source. from_iter(BufReader::new(rdr).bytes()) } /// Decodes a Hjson value from a byte slice `&[u8]`. pub fn from_slice<T>(v: &[u8]) -> Result<T> where T: de::DeserializeOwned, { from_iter(v.iter().map(|&byte| Ok(byte))) } /// Decodes a Hjson value from a `&str`. pub fn from_str<T>(s: &str) -> Result<T> where T: de::DeserializeOwned, { from_slice(s.as_bytes()) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-json/tests/main.rs
crates/nu-json/tests/main.rs
use nu_json::Value; use pretty_assertions::assert_eq; use rstest::rstest; use std::fs; use std::io; use std::path::{Path, PathBuf}; fn txt(text: String) -> String { let out = text; #[cfg(windows)] { out.replace("\r\n", "\n") } #[cfg(not(windows))] { out } } // This test will fail if/when `nu_test_support::fs::assets()`'s return value changes. #[rstest] fn assert_rstest_finds_assets(#[files("../../tests/assets/nu_json")] rstest_supplied: PathBuf) { // rstest::files runs paths through `fs::canonicalize`, which: // > On Windows, this converts the path to use extended length path syntax // So we make sure to canonicalize both paths. assert_eq!( fs::canonicalize(rstest_supplied).unwrap(), fs::canonicalize(nu_test_support::fs::assets().join("nu_json")).unwrap() ); } #[rstest] fn test_hjson_fails(#[files("../../tests/assets/nu_json/fail*_test.*")] file: PathBuf) { let contents = fs::read_to_string(file).unwrap(); let data: nu_json::Result<Value> = nu_json::from_str(&contents); assert!(data.is_err()); } #[rstest] fn test_hjson( #[files("../../tests/assets/nu_json/*_test.*")] #[exclude("fail*")] test_file: PathBuf, ) -> Result<(), Box<dyn std::error::Error>> { let name = test_file .file_stem() .and_then(|x| x.to_str()) .and_then(|x| x.strip_suffix("_test")) .unwrap(); let data: Value = nu_json::from_str(fs::read_to_string(&test_file)?.as_str())?; let r_json = get_content(get_result_path(&test_file, "json").as_deref().unwrap())?; // let r_hjson = get_content(get_result_path(&test_file, "hjson").as_deref().unwrap())?; let r_hjson = r_json.as_str(); let actual_json = serde_json::to_string_pretty(&data).map(get_fix(name))?; let actual_hjson = nu_json::to_string(&data).map(txt)?; assert_eq!(r_json, actual_json); assert_eq!(r_hjson, actual_hjson); Ok(()) } fn get_result_path(test_file: &Path, ext: &str) -> Option<PathBuf> { let name = test_file .file_stem() .and_then(|x| x.to_str()) .and_then(|x| x.strip_suffix("_test"))?; Some(test_file.with_file_name(format!("{name}_result.{ext}"))) } fn get_content(file: &Path) -> io::Result<String> { fs::read_to_string(file).map(txt) } // add fixes where rust's json differs from javascript fn get_fix(s: &str) -> fn(String) -> String { fn remove_negative_zero(json: String) -> String { json.replace(" -0,", " 0,") } fn positive_exp_add_sign(json: String) -> String { json.replace("1.23456789e34", "1.23456789e+34") .replace("2.3456789012e76", "2.3456789012e+76") } match s { "kan" => remove_negative_zero, "pass1" => positive_exp_add_sign, _ => std::convert::identity, } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/deprecation.rs
crates/nu-protocol/src/deprecation.rs
use crate::{FromValue, ParseWarning, ShellError, Type, Value, ast::Call}; // Make nu_protocol available in this namespace, consumers of this crate will // have this without such an export. // The `FromValue` derive macro fully qualifies paths to "nu_protocol". use crate::{self as nu_protocol, ReportMode, Span}; /// A entry which indicates that some part of, or all of, a command is deprecated /// /// Commands can implement [`Command::deprecation_info`](crate::engine::Command::deprecation_info) /// to return deprecation entries, which will cause a parse-time warning. /// Additionally, custom commands can use the `@deprecated` attribute to add a /// `DeprecationEntry`. #[derive(FromValue)] pub struct DeprecationEntry { /// The type of deprecation // might need to revisit this if we added additional DeprecationTypes #[nu_value(rename = "flag", default)] pub ty: DeprecationType, /// How this deprecation should be reported #[nu_value(rename = "report")] pub report_mode: ReportMode, /// When this deprecation started pub since: Option<String>, /// When this item is expected to be removed pub expected_removal: Option<String>, /// Help text, possibly including a suggestion for what to use instead pub help: Option<String>, } /// What this deprecation affects #[derive(Default)] pub enum DeprecationType { /// Deprecation of whole command #[default] Command, /// Deprecation of a flag/switch Flag(String), } impl FromValue for DeprecationType { fn from_value(v: Value) -> Result<Self, ShellError> { match v { Value::String { val, .. } => Ok(DeprecationType::Flag(val)), Value::Nothing { .. } => Ok(DeprecationType::Command), v => Err(ShellError::CantConvert { to_type: Self::expected_type().to_string(), from_type: v.get_type().to_string(), span: v.span(), help: None, }), } } fn expected_type() -> Type { Type::String } } impl FromValue for ReportMode { fn from_value(v: Value) -> Result<Self, ShellError> { let span = v.span(); let Value::String { val, .. } = v else { return Err(ShellError::CantConvert { to_type: Self::expected_type().to_string(), from_type: v.get_type().to_string(), span: v.span(), help: None, }); }; match val.as_str() { "first" => Ok(ReportMode::FirstUse), "every" => Ok(ReportMode::EveryUse), _ => Err(ShellError::InvalidValue { valid: "first or every".into(), actual: val, span, }), } } fn expected_type() -> Type { Type::String } } impl DeprecationEntry { fn check(&self, call: &Call) -> bool { match &self.ty { DeprecationType::Command => true, DeprecationType::Flag(flag) => { // Make sure we don't accidentally have dashes in the flag debug_assert!( !flag.starts_with('-'), "DeprecationEntry for {flag} should not include dashes in the flag name!" ); call.get_named_arg(flag).is_some() } } } fn type_name(&self) -> String { match &self.ty { DeprecationType::Command => "Command".to_string(), DeprecationType::Flag(_) => "Flag".to_string(), } } fn label(&self, command_name: &str) -> String { let name = match &self.ty { DeprecationType::Command => command_name, DeprecationType::Flag(flag) => &format!("{command_name} --{flag}"), }; let since = match &self.since { Some(since) => format!("was deprecated in {since}"), None => "is deprecated".to_string(), }; let removal = match &self.expected_removal { Some(expected) => format!("and will be removed in {expected}"), None => "and will be removed in a future release".to_string(), }; format!("{name} {since} {removal}.") } fn span(&self, call: &Call) -> Span { match &self.ty { DeprecationType::Command => call.span(), DeprecationType::Flag(flag) => call .get_named_arg(flag) .map(|arg| arg.span) .unwrap_or(Span::unknown()), } } pub fn parse_warning(self, command_name: &str, call: &Call) -> Option<ParseWarning> { if !self.check(call) { return None; } let dep_type = self.type_name(); let label = self.label(command_name); let span = self.span(call); let report_mode = self.report_mode; Some(ParseWarning::Deprecated { dep_type, label, span, report_mode, help: self.help, }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/parser_path.rs
crates/nu-protocol/src/parser_path.rs
use crate::{ FileId, engine::{StateWorkingSet, VirtualPath}, }; use std::{ ffi::OsStr, path::{Path, PathBuf}, }; /// An abstraction over a PathBuf that can have virtual paths (files and directories). Virtual /// paths always exist and represent a way to ship Nushell code inside the binary without requiring /// paths to be present in the file system. /// /// Created from VirtualPath found in the engine state. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum ParserPath { RealPath(PathBuf), VirtualFile(PathBuf, usize), VirtualDir(PathBuf, Vec<ParserPath>), } impl ParserPath { pub fn is_dir(&self) -> bool { match self { ParserPath::RealPath(p) => p.is_dir(), ParserPath::VirtualFile(..) => false, ParserPath::VirtualDir(..) => true, } } pub fn is_file(&self) -> bool { match self { ParserPath::RealPath(p) => p.is_file(), ParserPath::VirtualFile(..) => true, ParserPath::VirtualDir(..) => false, } } pub fn exists(&self) -> bool { match self { ParserPath::RealPath(p) => p.exists(), ParserPath::VirtualFile(..) => true, ParserPath::VirtualDir(..) => true, } } pub fn path(&self) -> &Path { match self { ParserPath::RealPath(p) => p, ParserPath::VirtualFile(p, _) => p, ParserPath::VirtualDir(p, _) => p, } } pub fn path_buf(self) -> PathBuf { match self { ParserPath::RealPath(p) => p, ParserPath::VirtualFile(p, _) => p, ParserPath::VirtualDir(p, _) => p, } } pub fn parent(&self) -> Option<&Path> { match self { ParserPath::RealPath(p) => p.parent(), ParserPath::VirtualFile(p, _) => p.parent(), ParserPath::VirtualDir(p, _) => p.parent(), } } pub fn read_dir(&self) -> Option<Vec<ParserPath>> { match self { ParserPath::RealPath(p) => p.read_dir().ok().map(|read_dir| { read_dir .flatten() .map(|dir_entry| ParserPath::RealPath(dir_entry.path())) .collect() }), ParserPath::VirtualFile(..) => None, ParserPath::VirtualDir(_, files) => Some(files.clone()), } } pub fn file_stem(&self) -> Option<&OsStr> { self.path().file_stem() } pub fn extension(&self) -> Option<&OsStr> { self.path().extension() } pub fn join(self, path: impl AsRef<Path>) -> ParserPath { match self { ParserPath::RealPath(p) => ParserPath::RealPath(p.join(path)), ParserPath::VirtualFile(p, file_id) => ParserPath::VirtualFile(p.join(path), file_id), ParserPath::VirtualDir(p, entries) => { let new_p = p.join(path); let mut pp = ParserPath::RealPath(new_p.clone()); for entry in entries { if new_p == entry.path() { pp = entry.clone(); } } pp } } } pub fn open<'a>( &'a self, working_set: &'a StateWorkingSet, ) -> std::io::Result<Box<dyn std::io::Read + 'a>> { match self { ParserPath::RealPath(p) => { std::fs::File::open(p).map(|f| Box::new(f) as Box<dyn std::io::Read>) } ParserPath::VirtualFile(_, file_id) => working_set .get_contents_of_file(FileId::new(*file_id)) .map(|bytes| Box::new(bytes) as Box<dyn std::io::Read>) .ok_or(std::io::ErrorKind::NotFound.into()), ParserPath::VirtualDir(..) => Err(std::io::ErrorKind::NotFound.into()), } } pub fn read<'a>(&'a self, working_set: &'a StateWorkingSet) -> Option<Vec<u8>> { self.open(working_set) .and_then(|mut reader| { let mut vec = vec![]; reader.read_to_end(&mut vec)?; Ok(vec) }) .ok() } pub fn from_virtual_path( working_set: &StateWorkingSet, name: &str, virtual_path: &VirtualPath, ) -> Self { match virtual_path { VirtualPath::File(file_id) => { ParserPath::VirtualFile(PathBuf::from(name), file_id.get()) } VirtualPath::Dir(entries) => ParserPath::VirtualDir( PathBuf::from(name), entries .iter() .map(|virtual_path_id| { let (virt_name, virt_path) = working_set.get_virtual_path(*virtual_path_id); ParserPath::from_virtual_path(working_set, virt_name, virt_path) }) .collect(), ), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/lib.rs
crates/nu-protocol/src/lib.rs
#![cfg_attr(not(feature = "os"), allow(unused))] #![doc = include_str!("../README.md")] mod alias; pub mod ast; pub mod casing; mod completion; pub mod config; pub mod debugger; mod deprecation; mod did_you_mean; pub mod engine; mod errors; pub mod eval_base; pub mod eval_const; mod example; mod id; pub mod ir; mod lev_distance; mod module; pub mod parser_path; mod pipeline; #[cfg(feature = "plugin")] mod plugin; #[cfg(feature = "os")] pub mod process; mod signature; pub mod span; mod syntax_shape; mod ty; mod value; pub use alias::*; pub use ast::unit::*; pub use completion::*; pub use config::*; pub use deprecation::*; pub use did_you_mean::did_you_mean; pub use engine::{ENV_VARIABLE_ID, IN_VARIABLE_ID, NU_VARIABLE_ID}; pub use errors::*; pub use example::*; pub use id::*; pub use lev_distance::levenshtein_distance; pub use module::*; pub use pipeline::*; #[cfg(feature = "plugin")] pub use plugin::*; pub use signature::*; pub use span::*; pub use syntax_shape::*; pub use ty::*; pub use value::*; pub use nu_derive_value::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/signature.rs
crates/nu-protocol/src/signature.rs
use crate::{ BlockId, DeclId, DeprecationEntry, Example, FromValue, IntoValue, PipelineData, ShellError, Span, SyntaxShape, Type, Value, VarId, engine::{Call, Command, CommandType, EngineState, Stack}, }; use nu_derive_value::FromValue as DeriveFromValue; use nu_utils::NuCow; use serde::{Deserialize, Serialize}; use std::fmt::Write; // Make nu_protocol available in this namespace, consumers of this crate will // have this without such an export. // The `FromValue` derive macro fully qualifies paths to "nu_protocol". use crate as nu_protocol; pub enum Parameter { Required(PositionalArg), Optional(PositionalArg), Rest(PositionalArg), Flag(Flag), } impl From<Flag> for Parameter { fn from(value: Flag) -> Self { Self::Flag(value) } } /// The signature definition of a named flag that either accepts a value or acts as a toggle flag #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Flag { pub long: String, pub short: Option<char>, pub arg: Option<SyntaxShape>, pub required: bool, pub desc: String, pub completion: Option<Completion>, // For custom commands pub var_id: Option<VarId>, pub default_value: Option<Value>, } impl Flag { #[inline] pub fn new(long: impl Into<String>) -> Self { Flag { long: long.into(), short: None, arg: None, required: false, desc: String::new(), completion: None, var_id: None, default_value: None, } } #[inline] pub fn short(self, short: char) -> Self { Self { short: Some(short), ..self } } #[inline] pub fn arg(self, arg: SyntaxShape) -> Self { Self { arg: Some(arg), ..self } } #[inline] pub fn required(self) -> Self { Self { required: true, ..self } } #[inline] pub fn desc(self, desc: impl Into<String>) -> Self { Self { desc: desc.into(), ..self } } #[inline] pub fn completion(self, completion: Completion) -> Self { Self { completion: Some(completion), ..self } } } /// The signature definition for a positional argument #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct PositionalArg { pub name: String, pub desc: String, pub shape: SyntaxShape, pub completion: Option<Completion>, // For custom commands pub var_id: Option<VarId>, pub default_value: Option<Value>, } impl PositionalArg { #[inline] pub fn new(name: impl Into<String>, shape: SyntaxShape) -> Self { Self { name: name.into(), desc: String::new(), shape, completion: None, var_id: None, default_value: None, } } #[inline] pub fn desc(self, desc: impl Into<String>) -> Self { Self { desc: desc.into(), ..self } } #[inline] pub fn completion(self, completion: Completion) -> Self { Self { completion: Some(completion), ..self } } #[inline] pub fn required(self) -> Parameter { Parameter::Required(self) } #[inline] pub fn optional(self) -> Parameter { Parameter::Optional(self) } #[inline] pub fn rest(self) -> Parameter { Parameter::Rest(self) } } #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub enum CommandWideCompleter { External, Command(DeclId), } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum Completion { Command(DeclId), List(NuCow<&'static [&'static str], Vec<String>>), } impl Completion { pub const fn new_list(list: &'static [&'static str]) -> Self { Self::List(NuCow::Borrowed(list)) } pub fn to_value(&self, engine_state: &EngineState, span: Span) -> Value { match self { Completion::Command(id) => engine_state .get_decl(*id) .name() .to_owned() .into_value(span), Completion::List(list) => match list { NuCow::Borrowed(list) => list .iter() .map(|&e| e.into_value(span)) .collect::<Vec<Value>>() .into_value(span), NuCow::Owned(list) => list .iter() .cloned() .map(|e| e.into_value(span)) .collect::<Vec<Value>>() .into_value(span), }, } } } /// Command categories #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum Category { Bits, Bytes, Chart, Conversions, Core, Custom(String), Database, Date, Debug, Default, Deprecated, Removed, Env, Experimental, FileSystem, Filters, Formats, Generators, Hash, History, Math, Misc, Network, Path, Platform, Plugin, Random, Shells, Strings, System, Viewers, } impl std::fmt::Display for Category { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let msg = match self { Category::Bits => "bits", Category::Bytes => "bytes", Category::Chart => "chart", Category::Conversions => "conversions", Category::Core => "core", Category::Custom(name) => name, Category::Database => "database", Category::Date => "date", Category::Debug => "debug", Category::Default => "default", Category::Deprecated => "deprecated", Category::Removed => "removed", Category::Env => "env", Category::Experimental => "experimental", Category::FileSystem => "filesystem", Category::Filters => "filters", Category::Formats => "formats", Category::Generators => "generators", Category::Hash => "hash", Category::History => "history", Category::Math => "math", Category::Misc => "misc", Category::Network => "network", Category::Path => "path", Category::Platform => "platform", Category::Plugin => "plugin", Category::Random => "random", Category::Shells => "shells", Category::Strings => "strings", Category::System => "system", Category::Viewers => "viewers", }; write!(f, "{msg}") } } pub fn category_from_string(category: &str) -> Category { match category { "bits" => Category::Bits, "bytes" => Category::Bytes, "chart" => Category::Chart, "conversions" => Category::Conversions, // Let's protect our own "core" commands by preventing scripts from having this category. "core" => Category::Custom("custom_core".to_string()), "database" => Category::Database, "date" => Category::Date, "debug" => Category::Debug, "default" => Category::Default, "deprecated" => Category::Deprecated, "removed" => Category::Removed, "env" => Category::Env, "experimental" => Category::Experimental, "filesystem" => Category::FileSystem, "filter" => Category::Filters, "formats" => Category::Formats, "generators" => Category::Generators, "hash" => Category::Hash, "history" => Category::History, "math" => Category::Math, "misc" => Category::Misc, "network" => Category::Network, "path" => Category::Path, "platform" => Category::Platform, "plugin" => Category::Plugin, "random" => Category::Random, "shells" => Category::Shells, "strings" => Category::Strings, "system" => Category::System, "viewers" => Category::Viewers, _ => Category::Custom(category.to_string()), } } /// Signature information of a [`Command`] #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Signature { pub name: String, pub description: String, pub extra_description: String, pub search_terms: Vec<String>, pub required_positional: Vec<PositionalArg>, pub optional_positional: Vec<PositionalArg>, pub rest_positional: Option<PositionalArg>, pub named: Vec<Flag>, pub input_output_types: Vec<(Type, Type)>, pub allow_variants_without_examples: bool, pub is_filter: bool, pub creates_scope: bool, pub allows_unknown_args: bool, pub complete: Option<CommandWideCompleter>, // Signature category used to classify commands stored in the list of declarations pub category: Category, } impl PartialEq for Signature { fn eq(&self, other: &Self) -> bool { self.name == other.name && self.description == other.description && self.required_positional == other.required_positional && self.optional_positional == other.optional_positional && self.rest_positional == other.rest_positional && self.is_filter == other.is_filter } } impl Eq for Signature {} impl Signature { /// Creates a new signature for a command with `name` pub fn new(name: impl Into<String>) -> Signature { Signature { name: name.into(), description: String::new(), extra_description: String::new(), search_terms: vec![], required_positional: vec![], optional_positional: vec![], rest_positional: None, input_output_types: vec![], allow_variants_without_examples: false, named: vec![], is_filter: false, creates_scope: false, category: Category::Default, allows_unknown_args: false, complete: None, } } /// Gets the input type from the signature /// /// If the input was unspecified or the signature has several different /// input types, [`Type::Any`] is returned. Otherwise, if the signature has /// one or same input types, this type is returned. // XXX: remove? pub fn get_input_type(&self) -> Type { match self.input_output_types.len() { 0 => Type::Any, 1 => self.input_output_types[0].0.clone(), _ => { let first = &self.input_output_types[0].0; if self .input_output_types .iter() .all(|(input, _)| input == first) { first.clone() } else { Type::Any } } } } /// Gets the output type from the signature /// /// If the output was unspecified or the signature has several different /// input types, [`Type::Any`] is returned. Otherwise, if the signature has /// one or same output types, this type is returned. // XXX: remove? pub fn get_output_type(&self) -> Type { match self.input_output_types.len() { 0 => Type::Any, 1 => self.input_output_types[0].1.clone(), _ => { let first = &self.input_output_types[0].1; if self .input_output_types .iter() .all(|(_, output)| output == first) { first.clone() } else { Type::Any } } } } /// Add a default help option to a signature pub fn add_help(mut self) -> Signature { // default help flag let flag = Flag { long: "help".into(), short: Some('h'), arg: None, desc: "Display the help message for this command".into(), required: false, var_id: None, default_value: None, completion: None, }; self.named.push(flag); self } /// Build an internal signature with default help option /// /// This is equivalent to `Signature::new(name).add_help()`. pub fn build(name: impl Into<String>) -> Signature { Signature::new(name.into()).add_help() } /// Add a description to the signature /// /// This should be a single sentence as it is the part shown for example in the completion /// menu. pub fn description(mut self, msg: impl Into<String>) -> Signature { self.description = msg.into(); self } /// Add an extra description to the signature. /// /// Here additional documentation can be added pub fn extra_description(mut self, msg: impl Into<String>) -> Signature { self.extra_description = msg.into(); self } /// Add search terms to the signature pub fn search_terms(mut self, terms: Vec<String>) -> Signature { self.search_terms = terms; self } /// Update signature's fields from a Command trait implementation pub fn update_from_command(mut self, command: &dyn Command) -> Signature { self.search_terms = command .search_terms() .into_iter() .map(|term| term.to_string()) .collect(); self.extra_description = command.extra_description().to_string(); self.description = command.description().to_string(); self } /// Allow unknown signature parameters pub fn allows_unknown_args(mut self) -> Signature { self.allows_unknown_args = true; self } pub fn param(mut self, param: impl Into<Parameter>) -> Self { let param: Parameter = param.into(); match param { Parameter::Flag(flag) => { if let Some(s) = flag.short { assert!( !self.get_shorts().contains(&s), "There may be duplicate short flags for '-{s}'" ); } let name = flag.long.as_str(); assert!( !self.get_names().contains(&name), "There may be duplicate name flags for '--{name}'" ); self.named.push(flag); } Parameter::Required(positional_arg) => { self.required_positional.push(positional_arg); } Parameter::Optional(positional_arg) => { self.optional_positional.push(positional_arg); } Parameter::Rest(positional_arg) => { assert!( self.rest_positional.is_none(), "Tried to set rest arguments more than once" ); self.rest_positional = Some(positional_arg); } } self } /// Add a required positional argument to the signature pub fn required( mut self, name: impl Into<String>, shape: impl Into<SyntaxShape>, desc: impl Into<String>, ) -> Signature { self.required_positional.push(PositionalArg { name: name.into(), desc: desc.into(), shape: shape.into(), var_id: None, default_value: None, completion: None, }); self } /// Add an optional positional argument to the signature pub fn optional( mut self, name: impl Into<String>, shape: impl Into<SyntaxShape>, desc: impl Into<String>, ) -> Signature { self.optional_positional.push(PositionalArg { name: name.into(), desc: desc.into(), shape: shape.into(), var_id: None, default_value: None, completion: None, }); self } /// Add a rest positional parameter /// /// Rest positionals (also called [rest parameters][rp]) are treated as /// optional: passing 0 arguments is a valid call. If the command requires /// at least one argument, it must be checked by the implementation. /// /// [rp]: https://www.nushell.sh/book/custom_commands.html#rest-parameters pub fn rest( mut self, name: &str, shape: impl Into<SyntaxShape>, desc: impl Into<String>, ) -> Signature { self.rest_positional = Some(PositionalArg { name: name.into(), desc: desc.into(), shape: shape.into(), var_id: None, default_value: None, completion: None, }); self } /// Is this command capable of operating on its input via cell paths? pub fn operates_on_cell_paths(&self) -> bool { self.required_positional .iter() .chain(self.rest_positional.iter()) .any(|pos| { matches!( pos, PositionalArg { shape: SyntaxShape::CellPath, .. } ) }) } /// Add an optional named flag argument to the signature pub fn named( mut self, name: impl Into<String>, shape: impl Into<SyntaxShape>, desc: impl Into<String>, short: Option<char>, ) -> Signature { let (name, s) = self.check_names(name, short); self.named.push(Flag { long: name, short: s, arg: Some(shape.into()), required: false, desc: desc.into(), var_id: None, default_value: None, completion: None, }); self } /// Add a required named flag argument to the signature pub fn required_named( mut self, name: impl Into<String>, shape: impl Into<SyntaxShape>, desc: impl Into<String>, short: Option<char>, ) -> Signature { let (name, s) = self.check_names(name, short); self.named.push(Flag { long: name, short: s, arg: Some(shape.into()), required: true, desc: desc.into(), var_id: None, default_value: None, completion: None, }); self } /// Add a switch to the signature pub fn switch( mut self, name: impl Into<String>, desc: impl Into<String>, short: Option<char>, ) -> Signature { let (name, s) = self.check_names(name, short); self.named.push(Flag { long: name, short: s, arg: None, required: false, desc: desc.into(), var_id: None, default_value: None, completion: None, }); self } /// Changes the input type of the command signature pub fn input_output_type(mut self, input_type: Type, output_type: Type) -> Signature { self.input_output_types.push((input_type, output_type)); self } /// Set the input-output type signature variants of the command pub fn input_output_types(mut self, input_output_types: Vec<(Type, Type)>) -> Signature { self.input_output_types = input_output_types; self } /// Changes the signature category pub fn category(mut self, category: Category) -> Signature { self.category = category; self } /// Sets that signature will create a scope as it parses pub fn creates_scope(mut self) -> Signature { self.creates_scope = true; self } // Is it allowed for the type signature to feature a variant that has no corresponding example? pub fn allow_variants_without_examples(mut self, allow: bool) -> Signature { self.allow_variants_without_examples = allow; self } /// A string rendering of the command signature /// /// If the command has flags, all of them will be shown together as /// `{flags}`. pub fn call_signature(&self) -> String { let mut one_liner = String::new(); one_liner.push_str(&self.name); one_liner.push(' '); // Note: the call signature needs flags first because on the nu commandline, // flags will precede the script file name. Flags for internal commands can come // either before or after (or around) positional parameters, so there isn't a strong // preference, so we default to the more constrained example. if self.named.len() > 1 { one_liner.push_str("{flags} "); } for positional in &self.required_positional { one_liner.push_str(&get_positional_short_name(positional, true)); } for positional in &self.optional_positional { one_liner.push_str(&get_positional_short_name(positional, false)); } if let Some(rest) = &self.rest_positional { let _ = write!(one_liner, "...{}", get_positional_short_name(rest, false)); } // if !self.subcommands.is_empty() { // one_liner.push_str("<subcommand> "); // } one_liner } /// Get list of the short-hand flags pub fn get_shorts(&self) -> Vec<char> { self.named.iter().filter_map(|f| f.short).collect() } /// Get list of the long-hand flags pub fn get_names(&self) -> Vec<&str> { self.named.iter().map(|f| f.long.as_str()).collect() } /// Checks if short or long options are already present /// /// ## Panics /// /// Panics if one of them is found. // XXX: return result instead of a panic fn check_names(&self, name: impl Into<String>, short: Option<char>) -> (String, Option<char>) { let s = short.inspect(|c| { assert!( !self.get_shorts().contains(c), "There may be duplicate short flags for '-{c}'" ); }); let name = { let name: String = name.into(); assert!( !self.get_names().contains(&name.as_str()), "There may be duplicate name flags for '--{name}'" ); name }; (name, s) } /// Returns an argument with the index `position` /// /// It will index, in order, required arguments, then optional, then the /// trailing `...rest` argument. pub fn get_positional(&self, position: usize) -> Option<&PositionalArg> { if position < self.required_positional.len() { self.required_positional.get(position) } else if position < (self.required_positional.len() + self.optional_positional.len()) { self.optional_positional .get(position - self.required_positional.len()) } else { self.rest_positional.as_ref() } } /// Returns the number of (optional) positional parameters in a signature /// /// This does _not_ include the `...rest` parameter, even if it's present. pub fn num_positionals(&self) -> usize { let mut total = self.required_positional.len() + self.optional_positional.len(); for positional in &self.required_positional { if let SyntaxShape::Keyword(..) = positional.shape { // Keywords have a required argument, so account for that total += 1; } } for positional in &self.optional_positional { if let SyntaxShape::Keyword(..) = positional.shape { // Keywords have a required argument, so account for that total += 1; } } total } /// Find the matching long flag pub fn get_long_flag(&self, name: &str) -> Option<Flag> { if name.is_empty() { return None; } for flag in &self.named { if flag.long == name { return Some(flag.clone()); } } None } /// Find the matching long flag pub fn get_short_flag(&self, short: char) -> Option<Flag> { for flag in &self.named { if let Some(short_flag) = &flag.short && *short_flag == short { return Some(flag.clone()); } } None } /// Set the filter flag for the signature pub fn filter(mut self) -> Signature { self.is_filter = true; self } /// Create a placeholder implementation of Command as a way to predeclare a definition's /// signature so other definitions can see it. This placeholder is later replaced with the /// full definition in a second pass of the parser. pub fn predeclare(self) -> Box<dyn Command> { Box::new(Predeclaration { signature: self }) } /// Combines a signature and a block into a runnable block pub fn into_block_command( self, block_id: BlockId, attributes: Vec<(String, Value)>, examples: Vec<CustomExample>, ) -> Box<dyn Command> { Box::new(BlockCommand { signature: self, block_id, attributes, examples, }) } } #[derive(Clone)] struct Predeclaration { signature: Signature, } impl Command for Predeclaration { fn name(&self) -> &str { &self.signature.name } fn signature(&self) -> Signature { self.signature.clone() } fn description(&self) -> &str { &self.signature.description } fn extra_description(&self) -> &str { &self.signature.extra_description } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<PipelineData, crate::ShellError> { panic!("Internal error: can't run a predeclaration without a body") } } fn get_positional_short_name(arg: &PositionalArg, is_required: bool) -> String { match &arg.shape { SyntaxShape::Keyword(name, ..) => { if is_required { format!("{} <{}> ", String::from_utf8_lossy(name), arg.name) } else { format!("({} <{}>) ", String::from_utf8_lossy(name), arg.name) } } _ => { if is_required { format!("<{}> ", arg.name) } else { format!("({}) ", arg.name) } } } } #[derive(Clone, DeriveFromValue)] pub struct CustomExample { pub example: String, pub description: String, pub result: Option<Value>, } impl CustomExample { pub fn to_example(&self) -> Example<'_> { Example { example: self.example.as_str(), description: self.description.as_str(), result: self.result.clone(), } } } #[derive(Clone)] struct BlockCommand { signature: Signature, block_id: BlockId, attributes: Vec<(String, Value)>, examples: Vec<CustomExample>, } impl Command for BlockCommand { fn name(&self) -> &str { &self.signature.name } fn signature(&self) -> Signature { self.signature.clone() } fn description(&self) -> &str { &self.signature.description } fn extra_description(&self) -> &str { &self.signature.extra_description } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &Call, _input: PipelineData, ) -> Result<crate::PipelineData, crate::ShellError> { Err(ShellError::GenericError { error: "Internal error: can't run custom command with 'run', use block_id".into(), msg: "".into(), span: None, help: None, inner: vec![], }) } fn command_type(&self) -> CommandType { CommandType::Custom } fn block_id(&self) -> Option<BlockId> { Some(self.block_id) } fn attributes(&self) -> Vec<(String, Value)> { self.attributes.clone() } fn examples(&self) -> Vec<Example<'_>> { self.examples .iter() .map(CustomExample::to_example) .collect() } fn search_terms(&self) -> Vec<&str> { self.signature .search_terms .iter() .map(String::as_str) .collect() } fn deprecation_info(&self) -> Vec<DeprecationEntry> { self.attributes .iter() .filter_map(|(key, value)| { (key == "deprecated") .then_some(value.clone()) .map(DeprecationEntry::from_value) .and_then(Result::ok) }) .collect() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/id.rs
crates/nu-protocol/src/id.rs
use std::any; use std::fmt::{Debug, Display, Error, Formatter}; use std::marker::PhantomData; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Id<M, V = usize> { inner: V, _phantom: PhantomData<M>, } impl<M, V> Id<M, V> { /// Creates a new `Id`. /// /// Using a distinct type like `Id` instead of `usize` helps us avoid mixing plain integers /// with identifiers. #[inline] pub const fn new(inner: V) -> Self { Self { inner, _phantom: PhantomData, } } } impl<M, V> Id<M, V> where V: Copy, { /// Returns the inner value. /// /// This requires an explicit call, ensuring we only use the raw value when intended. #[inline] pub const fn get(self) -> V { self.inner } } impl<M> Id<M, usize> { pub const ZERO: Self = Self::new(0); } impl<M, V> Debug for Id<M, V> where V: Display, { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let marker = any::type_name::<M>().split("::").last().expect("not empty"); write!(f, "{marker}Id({})", self.inner) } } impl<M, V> Serialize for Id<M, V> where V: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.inner.serialize(serializer) } } impl<'de, M, V> Deserialize<'de> for Id<M, V> where V: Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let inner = V::deserialize(deserializer)?; Ok(Self { inner, _phantom: PhantomData, }) } } pub mod marker { #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Var; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Decl; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Block; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Module; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Overlay; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct File; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct VirtualPath; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Span; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Reg; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Job; } pub type VarId = Id<marker::Var>; pub type DeclId = Id<marker::Decl>; pub type BlockId = Id<marker::Block>; pub type ModuleId = Id<marker::Module>; pub type OverlayId = Id<marker::Overlay>; pub type FileId = Id<marker::File>; pub type VirtualPathId = Id<marker::VirtualPath>; pub type SpanId = Id<marker::Span>; pub type JobId = Id<marker::Job>; /// An ID for an [IR](crate::ir) register. /// /// `%n` is a common shorthand for `RegId(n)`. /// /// Note: `%0` is allocated with the block input at the beginning of a compiled block. pub type RegId = Id<marker::Reg, u32>; impl Display for JobId { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.inner) } } impl Display for RegId { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "%{}", self.get()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/completion.rs
crates/nu-protocol/src/completion.rs
use crate::{DeclId, Span, Type, ast, engine::CommandType}; use serde::{Deserialize, Serialize}; /// A simple semantics suggestion just like nu_cli::SemanticSuggestion, but it /// derives `Serialize` and `Deserialize`, so plugins are allowed to use it /// to provide dynamic completion items. /// /// Why define a new one rather than put `nu_cli::SemanticSuggestion` here? /// /// If bringing `nu_cli::SemanticSuggestion` here, it brings reedline::Suggestion too, /// then it requires this crates depends on `reedline`, this is not good because /// protocol should not rely on a cli relative interface. #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct DynamicSuggestion { /// String replacement that will be introduced to the the buffer pub value: String, /// Optional description for the replacement pub description: Option<String>, /// Optional vector of strings in the suggestion. These can be used to /// represent examples coming from a suggestion pub extra: Option<Vec<String>>, /// Whether to append a space after selecting this suggestion. /// This helps to avoid that a completer repeats the complete suggestion. pub append_whitespace: bool, /// Indices of the graphemes in the suggestion that matched the typed text. /// Useful if using fuzzy matching. pub match_indices: Option<Vec<usize>>, /// Replacement span in the buffer, if any. pub span: Option<Span>, pub kind: Option<SuggestionKind>, } impl Default for DynamicSuggestion { fn default() -> Self { Self { append_whitespace: true, value: String::new(), description: None, extra: None, match_indices: None, kind: None, span: None, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SuggestionKind { Command(CommandType, Option<DeclId>), Value(Type), CellPath, Directory, File, Flag, Module, Operator, Variable, } /// A simple wrapper for [`ast::Call`] which contains additional context about completion. /// It's used only at nushell side, to avoid unnecessary clone. #[derive(Clone, Debug, PartialEq)] pub struct DynamicCompletionCallRef<'a> { /// the real call, which is generated during parse time. pub call: &'a ast::Call, /// Indicates if there is a placeholder in input buffer. pub strip: bool, /// The position in input buffer, which is useful to find placeholder from arguments. pub pos: usize, }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/module.rs
crates/nu-protocol/src/module.rs
use crate::{ BlockId, DeclId, FileId, ModuleId, ParseError, Span, Value, VarId, ast::ImportPatternMember, engine::StateWorkingSet, }; use crate::parser_path::ParserPath; use indexmap::IndexMap; pub struct ResolvedImportPattern { pub decls: Vec<(Vec<u8>, DeclId)>, pub modules: Vec<(Vec<u8>, ModuleId)>, pub constants: Vec<(Vec<u8>, VarId)>, /// TODO: for referencing module name as a record, e.g. `$module_name.const_name` /// values got multiple duplicates in memory. pub constant_values: Vec<(Vec<u8>, Value)>, } impl ResolvedImportPattern { pub fn new( decls: Vec<(Vec<u8>, DeclId)>, modules: Vec<(Vec<u8>, ModuleId)>, constants: Vec<(Vec<u8>, VarId)>, constant_values: Vec<(Vec<u8>, Value)>, ) -> Self { ResolvedImportPattern { decls, modules, constants, constant_values, } } } /// Collection of definitions that can be exported from a module #[derive(Debug, Clone)] pub struct Module { pub name: Vec<u8>, pub decls: IndexMap<Vec<u8>, DeclId>, pub submodules: IndexMap<Vec<u8>, ModuleId>, pub constants: IndexMap<Vec<u8>, VarId>, pub env_block: Option<BlockId>, // `export-env { ... }` block pub main: Option<DeclId>, // `export def main` pub span: Option<Span>, pub imported_modules: Vec<ModuleId>, // use other_module.nu pub file: Option<(ParserPath, FileId)>, } impl Module { pub fn new(name: Vec<u8>) -> Self { Module { name, decls: IndexMap::new(), submodules: IndexMap::new(), constants: IndexMap::new(), env_block: None, main: None, span: None, imported_modules: vec![], file: None, } } pub fn from_span(name: Vec<u8>, span: Span) -> Self { Module { name, decls: IndexMap::new(), submodules: IndexMap::new(), constants: IndexMap::new(), env_block: None, main: None, span: Some(span), imported_modules: vec![], file: None, } } pub fn name(&self) -> Vec<u8> { self.name.clone() } pub fn add_decl(&mut self, name: Vec<u8>, decl_id: DeclId) -> Option<DeclId> { self.decls.insert(name, decl_id) } pub fn add_submodule(&mut self, name: Vec<u8>, module_id: ModuleId) -> Option<ModuleId> { self.submodules.insert(name, module_id) } pub fn add_variable(&mut self, name: Vec<u8>, var_id: VarId) -> Option<VarId> { self.constants.insert(name, var_id) } pub fn add_env_block(&mut self, block_id: BlockId) { self.env_block = Some(block_id); } pub fn track_imported_modules(&mut self, module_id: &[ModuleId]) { for m in module_id { self.imported_modules.push(*m) } } pub fn has_decl(&self, name: &[u8]) -> bool { if name == self.name && self.main.is_some() { return true; } self.decls.contains_key(name) } /// Resolve `members` from given module, which is indicated by `self_id` to import. /// /// When resolving, all modules are recorded in `imported_modules`. pub fn resolve_import_pattern( &self, working_set: &StateWorkingSet, self_id: ModuleId, members: &[ImportPatternMember], name_override: Option<&[u8]>, // name under the module was stored (doesn't have to be the same as self.name) backup_span: Span, imported_modules: &mut Vec<ModuleId>, ) -> (ResolvedImportPattern, Vec<ParseError>) { imported_modules.push(self_id); let final_name = name_override.unwrap_or(&self.name).to_vec(); let (head, rest) = if let Some((head, rest)) = members.split_first() { (head, rest) } else { // Import pattern was just name without any members let mut decls = vec![]; let mut const_rows = vec![]; let mut errors = vec![]; for (_, id) in &self.submodules { let submodule = working_set.get_module(*id); let span = submodule.span.or(self.span).unwrap_or(backup_span); let (sub_results, sub_errors) = submodule.resolve_import_pattern( working_set, *id, &[], None, span, imported_modules, ); errors.extend(sub_errors); for (sub_name, sub_decl_id) in sub_results.decls { let mut new_name = final_name.clone(); new_name.push(b' '); new_name.extend(sub_name); decls.push((new_name, sub_decl_id)); } const_rows.extend(sub_results.constant_values); } decls.extend(self.decls_with_head(&final_name)); for (name, var_id) in self.consts() { match working_set.get_constant(var_id) { Ok(const_val) => const_rows.push((name, const_val.clone())), Err(err) => errors.push(err), } } let span = self.span.unwrap_or(backup_span); // only needs to bring `$module` with a record value if it defines any constants. let constant_values = if const_rows.is_empty() { vec![] } else { vec![( normalize_module_name(&final_name), Value::record( const_rows .into_iter() .map(|(name, val)| (String::from_utf8_lossy(&name).to_string(), val)) .collect(), span, ), )] }; return ( ResolvedImportPattern::new( decls, vec![(final_name.clone(), self_id)], vec![], constant_values, ), errors, ); }; match head { ImportPatternMember::Name { name, span } => { // raise errors if user wants to do something like this: // `use a b c`: but b is not a sub-module of a. let errors = if !rest.is_empty() && self.submodules.get(name).is_none() { vec![ParseError::WrongImportPattern( format!( "Trying to import something but the parent `{}` is not a module, maybe you want to try `use <module> [<name1>, <name2>]`", String::from_utf8_lossy(name) ), rest[0].span(), )] } else { vec![] }; if name == b"main" { if let Some(main_decl_id) = self.main { ( ResolvedImportPattern::new( vec![(final_name, main_decl_id)], vec![], vec![], vec![], ), errors, ) } else { ( ResolvedImportPattern::new(vec![], vec![], vec![], vec![]), vec![ParseError::ExportNotFound(*span)], ) } } else if let Some(decl_id) = self.decls.get(name) { ( ResolvedImportPattern::new( vec![(name.clone(), *decl_id)], vec![], vec![], vec![], ), errors, ) } else if let Some(var_id) = self.constants.get(name) { match working_set.get_constant(*var_id) { Ok(_) => ( ResolvedImportPattern::new( vec![], vec![], vec![(name.clone(), *var_id)], vec![], ), errors, ), Err(err) => ( ResolvedImportPattern::new(vec![], vec![], vec![], vec![]), vec![err], ), } } else if let Some(submodule_id) = self.submodules.get(name) { let submodule = working_set.get_module(*submodule_id); submodule.resolve_import_pattern( working_set, *submodule_id, rest, None, self.span.unwrap_or(backup_span), imported_modules, ) } else { ( ResolvedImportPattern::new(vec![], vec![], vec![], vec![]), vec![ParseError::ExportNotFound(*span)], ) } } ImportPatternMember::Glob { .. } => { let mut decls = vec![]; let mut submodules = vec![]; let mut constants = vec![]; let mut constant_values = vec![]; let mut errors = vec![]; for (_, id) in &self.submodules { let submodule = working_set.get_module(*id); let (sub_results, sub_errors) = submodule.resolve_import_pattern( working_set, *id, &[], None, self.span.unwrap_or(backup_span), imported_modules, ); decls.extend(sub_results.decls); submodules.extend(sub_results.modules); constants.extend(sub_results.constants); constant_values.extend(sub_results.constant_values); errors.extend(sub_errors); } decls.extend(self.decls()); for (name, var_id) in self.constants.iter() { match working_set.get_constant(*var_id) { Ok(_) => { constants.push((name.clone(), *var_id)); } Err(err) => { errors.push(err); } } } submodules.extend(self.submodules()); ( ResolvedImportPattern::new(decls, submodules, constants, constant_values), errors, ) } ImportPatternMember::List { names } => { let mut decls = vec![]; let mut modules = vec![]; let mut constants = vec![]; let mut constant_values = vec![]; let mut errors = vec![]; for (name, span) in names { if name == b"main" { if let Some(main_decl_id) = self.main { decls.push((final_name.clone(), main_decl_id)); } else { errors.push(ParseError::ExportNotFound(*span)); } } else if let Some(decl_id) = self.decls.get(name) { decls.push((name.clone(), *decl_id)); } else if let Some(var_id) = self.constants.get(name) { match working_set.get_constant(*var_id) { Ok(_) => constants.push((name.clone(), *var_id)), Err(err) => errors.push(err), } } else if let Some(submodule_id) = self.submodules.get(name) { let submodule = working_set.get_module(*submodule_id); let (sub_results, sub_errors) = submodule.resolve_import_pattern( working_set, *submodule_id, rest, None, self.span.unwrap_or(backup_span), imported_modules, ); decls.extend(sub_results.decls); modules.extend(sub_results.modules); constants.extend(sub_results.constants); constant_values.extend(sub_results.constant_values); errors.extend(sub_errors); } else { errors.push(ParseError::ExportNotFound(*span)); } } ( ResolvedImportPattern::new(decls, modules, constants, constant_values), errors, ) } } } pub fn decl_name_with_head(&self, name: &[u8], head: &[u8]) -> Option<Vec<u8>> { if self.has_decl(name) { let mut new_name = head.to_vec(); new_name.push(b' '); new_name.extend(name); Some(new_name) } else { None } } pub fn decls_with_head(&self, head: &[u8]) -> Vec<(Vec<u8>, DeclId)> { let mut result: Vec<(Vec<u8>, DeclId)> = self .decls .iter() .map(|(name, id)| { let mut new_name = head.to_vec(); new_name.push(b' '); new_name.extend(name); (new_name, *id) }) .collect(); if let Some(decl_id) = self.main { result.push((self.name.clone(), decl_id)); } result } pub fn consts(&self) -> Vec<(Vec<u8>, VarId)> { self.constants .iter() .map(|(name, id)| (name.to_vec(), *id)) .collect() } pub fn decl_names_with_head(&self, head: &[u8]) -> Vec<Vec<u8>> { let mut result: Vec<Vec<u8>> = self .decls .keys() .map(|name| { let mut new_name = head.to_vec(); new_name.push(b' '); new_name.extend(name); new_name }) .collect(); if self.main.is_some() { result.push(self.name.clone()); } result } pub fn decls(&self) -> Vec<(Vec<u8>, DeclId)> { let mut result: Vec<(Vec<u8>, DeclId)> = self .decls .iter() .map(|(name, id)| (name.clone(), *id)) .collect(); if let Some(decl_id) = self.main { result.push((self.name.clone(), decl_id)); } result } pub fn submodules(&self) -> Vec<(Vec<u8>, ModuleId)> { self.submodules .iter() .map(|(name, id)| (name.clone(), *id)) .collect() } pub fn decl_names(&self) -> Vec<Vec<u8>> { let mut result: Vec<Vec<u8>> = self.decls.keys().cloned().collect(); if self.main.is_some() { result.push(self.name.clone()); } result } } /// normalize module names for exporting as record constant fn normalize_module_name(bytes: &[u8]) -> Vec<u8> { bytes .iter() .map(|x| match is_identifier_byte(*x) { true => *x, false => b'_', }) .collect() } fn is_identifier_byte(b: u8) -> bool { b != b'.' && b != b'[' && b != b'(' && b != b'{' && b != b'+' && b != b'-' && b != b'*' && b != b'^' && b != b'/' && b != b'=' && b != b'!' && b != b'<' && b != b'>' && b != b'&' && b != b'|' }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/example.rs
crates/nu-protocol/src/example.rs
use crate::Value; #[cfg(feature = "plugin")] use serde::{Deserialize, Serialize}; #[derive(Debug)] pub struct Example<'a> { pub example: &'a str, pub description: &'a str, pub result: Option<Value>, } // PluginExample is somehow like struct `Example`, but it owned a String for `example` // and `description` fields, because these information is fetched from plugin, a third party // binary, nushell have no way to construct it directly. #[cfg(feature = "plugin")] #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PluginExample { pub example: String, pub description: String, pub result: Option<Value>, } #[cfg(feature = "plugin")] impl From<Example<'_>> for PluginExample { fn from(value: Example) -> Self { PluginExample { example: value.example.into(), description: value.description.into(), result: value.result, } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/span.rs
crates/nu-protocol/src/span.rs
//! [`Span`] to point to sections of source code and the [`Spanned`] wrapper type use crate::{FromValue, IntoValue, ShellError, SpanId, Value, record}; use miette::SourceSpan; use serde::{Deserialize, Serialize}; use std::{fmt, ops::Deref}; pub trait GetSpan { fn get_span(&self, span_id: SpanId) -> Span; } /// A spanned area of interest, generic over what kind of thing is of interest #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] pub struct Spanned<T> { pub item: T, pub span: Span, } impl<T> Spanned<T> { /// Map to a spanned reference of the inner type, i.e. `Spanned<T> -> Spanned<&T>`. pub fn as_ref(&self) -> Spanned<&T> { Spanned { item: &self.item, span: self.span, } } /// Map to a mutable reference of the inner type, i.e. `Spanned<T> -> Spanned<&mut T>`. pub fn as_mut(&mut self) -> Spanned<&mut T> { Spanned { item: &mut self.item, span: self.span, } } /// Map to the result of [`.deref()`](std::ops::Deref::deref) on the inner type. /// /// This can be used for example to turn `Spanned<Vec<T>>` into `Spanned<&[T]>`. pub fn as_deref(&self) -> Spanned<&<T as Deref>::Target> where T: Deref, { Spanned { item: self.item.deref(), span: self.span, } } /// Map the spanned item with a function. pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Spanned<U> { Spanned { item: f(self.item), span: self.span, } } } impl<T> Spanned<&T> where T: ToOwned + ?Sized, { /// Map the spanned to hold an owned value. pub fn to_owned(&self) -> Spanned<T::Owned> { Spanned { item: self.item.to_owned(), span: self.span, } } } impl<T> Spanned<T> where T: AsRef<str>, { /// Span the value as a string slice. pub fn as_str(&self) -> Spanned<&str> { Spanned { item: self.item.as_ref(), span: self.span, } } } impl<T, E> Spanned<Result<T, E>> { /// Move the `Result` to the outside, resulting in a spanned `Ok` or unspanned `Err`. pub fn transpose(self) -> Result<Spanned<T>, E> { match self { Spanned { item: Ok(item), span, } => Ok(Spanned { item, span }), Spanned { item: Err(err), span: _, } => Err(err), } } } // With both Display and Into<SourceSpan> implemented on Spanned, we can use Spanned<String> in an // error in one field instead of splitting it into two fields impl<T: fmt::Display> fmt::Display for Spanned<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.item, f) } } impl<T> From<Spanned<T>> for SourceSpan { fn from(value: Spanned<T>) -> Self { value.span.into() } } /// Helper trait to create [`Spanned`] more ergonomically. pub trait IntoSpanned: Sized { /// Wrap items together with a span into [`Spanned`]. /// /// # Example /// /// ``` /// # use nu_protocol::{Span, IntoSpanned}; /// # let span = Span::test_data(); /// let spanned = "Hello, world!".into_spanned(span); /// assert_eq!("Hello, world!", spanned.item); /// assert_eq!(span, spanned.span); /// ``` fn into_spanned(self, span: Span) -> Spanned<Self>; } impl<T> IntoSpanned for T { fn into_spanned(self, span: Span) -> Spanned<Self> { Spanned { item: self, span } } } /// Spans are a global offset across all seen files, which are cached in the engine's state. The start and /// end offset together make the inclusive start/exclusive end pair for where to underline to highlight /// a given point of interest. #[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct Span { pub start: usize, pub end: usize, } impl Span { pub fn new(start: usize, end: usize) -> Self { debug_assert!( end >= start, "Can't create a Span whose end < start, start={start}, end={end}" ); Self { start, end } } pub const fn unknown() -> Self { Self { start: 0, end: 0 } } /// Span for testing purposes. /// /// The provided span does not point into any known source but is unequal to [`Span::unknown()`]. /// /// Note: Only use this for test data, *not* live data, as it will point into unknown source /// when used in errors pub const fn test_data() -> Self { Self { start: usize::MAX / 2, end: usize::MAX / 2, } } pub fn offset(&self, offset: usize) -> Self { Self::new(self.start - offset, self.end - offset) } /// Return length of the slice. pub fn len(&self) -> usize { self.end - self.start } /// Indicate if slice has length 0. pub fn is_empty(&self) -> bool { self.start == self.end } /// Return another span fully inside the [`Span`]. /// /// `start` and `end` are relative to `self.start`, and must lie within the `Span`. /// In other words, both `start` and `end` must be `<= self.len()`. pub fn subspan(&self, offset_start: usize, offset_end: usize) -> Option<Self> { let len = self.len(); if offset_start > len || offset_end > len || offset_start > offset_end { None } else { Some(Self::new( self.start + offset_start, self.start + offset_end, )) } } /// Return two spans that split the ['Span'] at the given position. pub fn split_at(&self, offset: usize) -> Option<(Self, Self)> { if offset < self.len() { Some(( Self::new(self.start, self.start + offset), Self::new(self.start + offset, self.end), )) } else { None } } pub fn contains(&self, pos: usize) -> bool { self.start <= pos && pos < self.end } pub fn contains_span(&self, span: Self) -> bool { self.start <= span.start && span.end <= self.end && span.end != 0 } /// Point to the space just past this span, useful for missing values pub fn past(&self) -> Self { Self { start: self.end, end: self.end, } } /// Converts row and column in a String to a Span, assuming bytes (1-based rows) pub fn from_row_column(row: usize, col: usize, contents: &str) -> Span { let mut cur_row = 1; let mut cur_col = 1; for (offset, curr_byte) in contents.bytes().enumerate() { if curr_byte == b'\n' { cur_row += 1; cur_col = 1; } else if cur_row >= row && cur_col >= col { return Span::new(offset, offset); } else { cur_col += 1; } } Self { start: contents.len(), end: contents.len(), } } /// Returns the minimal [`Span`] that encompasses both of the given spans. /// /// The two `Spans` can overlap in the middle, /// but must otherwise be in order by satisfying: /// - `self.start <= after.start` /// - `self.end <= after.end` /// /// If this is not guaranteed to be the case, use [`Span::merge`] instead. pub fn append(self, after: Self) -> Self { debug_assert!( self.start <= after.start && self.end <= after.end, "Can't merge two Spans that are not in order" ); Self { start: self.start, end: after.end, } } /// Returns the minimal [`Span`] that encompasses both of the given spans. /// /// The spans need not be in order or have any relationship. /// /// [`Span::append`] is slightly more efficient if the spans are known to be in order. pub fn merge(self, other: Self) -> Self { Self { start: usize::min(self.start, other.start), end: usize::max(self.end, other.end), } } /// Returns the minimal [`Span`] that encompasses all of the spans in the given slice. /// /// The spans are assumed to be in order, that is, all consecutive spans must satisfy: /// - `spans[i].start <= spans[i + 1].start` /// - `spans[i].end <= spans[i + 1].end` /// /// (Two consecutive spans can overlap as long as the above is true.) /// /// Use [`Span::merge_many`] if the spans are not known to be in order. pub fn concat(spans: &[Self]) -> Self { // TODO: enable assert below // debug_assert!(!spans.is_empty()); debug_assert!(spans.windows(2).all(|spans| { let &[a, b] = spans else { return false; }; a.start <= b.start && a.end <= b.end })); Self { start: spans.first().map(|s| s.start).unwrap_or(0), end: spans.last().map(|s| s.end).unwrap_or(0), } } /// Returns the minimal [`Span`] that encompasses all of the spans in the given iterator. /// /// The spans need not be in order or have any relationship. /// /// [`Span::concat`] is more efficient if the spans are known to be in order. pub fn merge_many(spans: impl IntoIterator<Item = Self>) -> Self { spans .into_iter() .reduce(Self::merge) .unwrap_or(Self::unknown()) } } impl IntoValue for Span { fn into_value(self, span: Span) -> Value { let record = record! { "start" => Value::int(self.start as i64, self), "end" => Value::int(self.end as i64, self), }; record.into_value(span) } } impl FromValue for Span { fn from_value(value: Value) -> Result<Self, ShellError> { let rec = value.as_record(); match rec { Ok(val) => { let Some(pre_start) = val.get("start") else { return Err(ShellError::GenericError { error: "Unable to parse Span.".into(), msg: "`start` must be an `int`".into(), span: Some(value.span()), help: None, inner: vec![], }); }; let Some(pre_end) = val.get("end") else { return Err(ShellError::GenericError { error: "Unable to parse Span.".into(), msg: "`end` must be an `int`".into(), span: Some(value.span()), help: None, inner: vec![], }); }; let start = pre_start.as_int()? as usize; let end = pre_end.as_int()? as usize; if start <= end { Ok(Self::new(start, end)) } else { Err(ShellError::GenericError { error: "Unable to parse Span.".into(), msg: "`end` must not be less than `start`".into(), span: Some(value.span()), help: None, inner: vec![], }) } } _ => Err(ShellError::TypeMismatch { err_message: "Must be a record".into(), span: value.span(), }), } } } impl From<Span> for SourceSpan { fn from(s: Span) -> Self { Self::new(s.start.into(), s.end - s.start) } } /// An extension trait for [`Result`], which adds a span to the error type. /// /// This trait might be removed later, since the old [`Spanned<std::io::Error>`] to /// [`ShellError`](crate::ShellError) conversion was replaced by /// [`IoError`](crate::shell_error::io::IoError). pub trait ErrSpan { type Result; /// Adds the given span to the error type, turning it into a [`Spanned<E>`]. fn err_span(self, span: Span) -> Self::Result; } impl<T, E> ErrSpan for Result<T, E> { type Result = Result<T, Spanned<E>>; fn err_span(self, span: Span) -> Self::Result { self.map_err(|err| err.into_spanned(span)) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/alias.rs
crates/nu-protocol/src/alias.rs
use crate::{ PipelineData, ShellError, Signature, ast::Expression, engine::{Call, Command, CommandType, EngineState, Stack}, }; /// Command wrapper of an alias. /// /// Our current aliases are implemented as wrapping commands /// This has some limitations compared to text-substitution macro aliases but can reliably use more /// of our machinery #[derive(Clone)] pub struct Alias { pub name: String, /// Wrapped inner [`Command`]. `None` if alias of external call pub command: Option<Box<dyn Command>>, pub wrapped_call: Expression, pub description: String, pub extra_description: String, } impl Command for Alias { fn name(&self) -> &str { &self.name } fn signature(&self) -> Signature { if let Some(cmd) = &self.command { cmd.signature() } else { Signature::new(&self.name).allows_unknown_args() } } fn description(&self) -> &str { &self.description } fn extra_description(&self) -> &str { &self.extra_description } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, call: &Call, _input: PipelineData, ) -> Result<PipelineData, ShellError> { Err(ShellError::NushellFailedSpanned { msg: "Can't run alias directly. Unwrap it first".to_string(), label: "originates from here".to_string(), span: call.head, }) } fn command_type(&self) -> CommandType { CommandType::Alias } fn as_alias(&self) -> Option<&Alias> { Some(self) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/casing.rs
crates/nu-protocol/src/casing.rs
use std::cmp::Ordering; use nu_utils::IgnoreCaseExt; use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Serialize, Deserialize)] pub enum Casing { #[default] Sensitive, Insensitive, } pub(crate) mod private { pub trait Seal {} } pub trait CaseSensitivity: private::Seal + 'static { fn eq(lhs: &str, rhs: &str) -> bool; fn cmp(lhs: &str, rhs: &str) -> Ordering; } pub struct CaseSensitive; pub struct CaseInsensitive; impl private::Seal for CaseSensitive {} impl private::Seal for CaseInsensitive {} impl CaseSensitivity for CaseSensitive { #[inline] fn eq(lhs: &str, rhs: &str) -> bool { lhs == rhs } #[inline] fn cmp(lhs: &str, rhs: &str) -> Ordering { lhs.cmp(rhs) } } impl CaseSensitivity for CaseInsensitive { #[inline] fn eq(lhs: &str, rhs: &str) -> bool { lhs.eq_ignore_case(rhs) } #[inline] fn cmp(lhs: &str, rhs: &str) -> Ordering { lhs.cmp_ignore_case(rhs) } } /// Wraps `Self` in a type that affects the case sensitivity of operations /// /// Using methods of [`CaseSensitivity`] in `Wrapper` implementations are not mandotary. /// They are provided mostly for convenience and to have a common implementation for comparisons pub trait WrapCased { /// Wrapper type generic over case sensitivity. type Wrapper<S: CaseSensitivity>; fn case_sensitive(self) -> Self::Wrapper<CaseSensitive>; fn case_insensitive(self) -> Self::Wrapper<CaseInsensitive>; }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/eval_const.rs
crates/nu-protocol/src/eval_const.rs
//! Implementation of const-evaluation //! //! This enables you to assign `const`-constants and execute parse-time code dependent on this. //! e.g. `source $my_const` use crate::{ BlockId, Config, HistoryFileFormat, PipelineData, Record, ShellError, Span, Value, VarId, ast::{Assignment, Block, Call, Expr, Expression, ExternalArgument}, debugger::{DebugContext, WithoutDebug}, engine::{EngineState, StateWorkingSet}, eval_base::Eval, record, }; use nu_system::os_info::{get_kernel_version, get_os_arch, get_os_family, get_os_name}; use std::{ path::{Path, PathBuf}, sync::Arc, }; /// Create a Value for `$nu`. // Note: When adding new constants to $nu, please update the doc at https://nushell.sh/book/special_variables.html // or at least add a TODO/reminder issue in nushell.github.io so we don't lose track of it. pub(crate) fn create_nu_constant(engine_state: &EngineState, span: Span) -> Value { fn canonicalize_path(engine_state: &EngineState, path: &Path) -> PathBuf { #[allow(deprecated)] let cwd = engine_state.current_work_dir(); if path.exists() { match nu_path::canonicalize_with(path, cwd) { Ok(canon_path) => canon_path, Err(_) => path.to_owned(), } } else { path.to_owned() } } let mut record = Record::new(); let config_path = match nu_path::nu_config_dir() { Some(path) => Ok(canonicalize_path(engine_state, path.as_ref())), None => Err(Value::error(ShellError::ConfigDirNotFound { span }, span)), }; record.push( "default-config-dir", config_path.as_ref().map_or_else( |e| e.clone(), |path| Value::string(path.to_string_lossy(), span), ), ); record.push( "config-path", if let Some(path) = engine_state.get_config_path("config-path") { let canon_config_path = canonicalize_path(engine_state, path); Value::string(canon_config_path.to_string_lossy(), span) } else { config_path.clone().map_or_else( |e| e, |mut path| { path.push("config.nu"); let canon_config_path = canonicalize_path(engine_state, &path); Value::string(canon_config_path.to_string_lossy(), span) }, ) }, ); record.push( "env-path", if let Some(path) = engine_state.get_config_path("env-path") { let canon_env_path = canonicalize_path(engine_state, path); Value::string(canon_env_path.to_string_lossy(), span) } else { config_path.clone().map_or_else( |e| e, |mut path| { path.push("env.nu"); let canon_env_path = canonicalize_path(engine_state, &path); Value::string(canon_env_path.to_string_lossy(), span) }, ) }, ); record.push( "history-path", config_path.clone().map_or_else( |e| e, |mut path| { match engine_state.config.history.file_format { HistoryFileFormat::Sqlite => { path.push("history.sqlite3"); } HistoryFileFormat::Plaintext => { path.push("history.txt"); } } let canon_hist_path = canonicalize_path(engine_state, &path); Value::string(canon_hist_path.to_string_lossy(), span) }, ), ); record.push( "loginshell-path", config_path.clone().map_or_else( |e| e, |mut path| { path.push("login.nu"); let canon_login_path = canonicalize_path(engine_state, &path); Value::string(canon_login_path.to_string_lossy(), span) }, ), ); #[cfg(feature = "plugin")] { record.push( "plugin-path", if let Some(path) = &engine_state.plugin_path { let canon_plugin_path = canonicalize_path(engine_state, path); Value::string(canon_plugin_path.to_string_lossy(), span) } else { // If there are no signatures, we should still populate the plugin path config_path.clone().map_or_else( |e| e, |mut path| { path.push("plugin.msgpackz"); let canonical_plugin_path = canonicalize_path(engine_state, &path); Value::string(canonical_plugin_path.to_string_lossy(), span) }, ) }, ); } record.push( "home-dir", if let Some(path) = nu_path::home_dir() { let canon_home_path = canonicalize_path(engine_state, path.as_ref()); Value::string(canon_home_path.to_string_lossy(), span) } else { Value::error( ShellError::GenericError { error: "setting $nu.home-dir failed".into(), msg: "Could not get home directory".into(), span: Some(span), help: None, inner: vec![], }, span, ) }, ); record.push( "data-dir", if let Some(path) = nu_path::data_dir() { let mut canon_data_path = canonicalize_path(engine_state, path.as_ref()); canon_data_path.push("nushell"); Value::string(canon_data_path.to_string_lossy(), span) } else { Value::error( ShellError::GenericError { error: "setting $nu.data-dir failed".into(), msg: "Could not get data path".into(), span: Some(span), help: None, inner: vec![], }, span, ) }, ); record.push( "cache-dir", if let Some(path) = nu_path::cache_dir() { let mut canon_cache_path = canonicalize_path(engine_state, path.as_ref()); canon_cache_path.push("nushell"); Value::string(canon_cache_path.to_string_lossy(), span) } else { Value::error( ShellError::GenericError { error: "setting $nu.cache-dir failed".into(), msg: "Could not get cache path".into(), span: Some(span), help: None, inner: vec![], }, span, ) }, ); record.push( "vendor-autoload-dirs", Value::list( get_vendor_autoload_dirs(engine_state) .iter() .map(|path| Value::string(path.to_string_lossy(), span)) .collect(), span, ), ); record.push( "user-autoload-dirs", Value::list( get_user_autoload_dirs(engine_state) .iter() .map(|path| Value::string(path.to_string_lossy(), span)) .collect(), span, ), ); record.push("temp-dir", { let canon_temp_path = canonicalize_path(engine_state, &std::env::temp_dir()); Value::string(canon_temp_path.to_string_lossy(), span) }); record.push("pid", Value::int(std::process::id().into(), span)); record.push("os-info", { let ver = get_kernel_version(); Value::record( record! { "name" => Value::string(get_os_name(), span), "arch" => Value::string(get_os_arch(), span), "family" => Value::string(get_os_family(), span), "kernel_version" => Value::string(ver, span), }, span, ) }); record.push( "startup-time", Value::duration(engine_state.get_startup_time(), span), ); record.push( "is-interactive", Value::bool(engine_state.is_interactive, span), ); record.push("is-login", Value::bool(engine_state.is_login, span)); record.push( "history-enabled", Value::bool(engine_state.history_enabled, span), ); record.push( "current-exe", if let Ok(current_exe) = std::env::current_exe() { Value::string(current_exe.to_string_lossy(), span) } else { Value::error( ShellError::GenericError { error: "setting $nu.current-exe failed".into(), msg: "Could not get current executable path".into(), span: Some(span), help: None, inner: vec![], }, span, ) }, ); record.push("is-lsp", Value::bool(engine_state.is_lsp, span)); Value::record(record, span) } pub fn get_vendor_autoload_dirs(_engine_state: &EngineState) -> Vec<PathBuf> { // load order for autoload dirs // /Library/Application Support/nushell/vendor/autoload on macOS // <dir>/nushell/vendor/autoload for every dir in XDG_DATA_DIRS in reverse order on platforms other than windows. If XDG_DATA_DIRS is not set, it falls back to <PREFIX>/share if PREFIX ends in local, or <PREFIX>/local/share:<PREFIX>/share otherwise. If PREFIX is not set, fall back to /usr/local/share:/usr/share. // %ProgramData%\nushell\vendor\autoload on windows // NU_VENDOR_AUTOLOAD_DIR from compile time, if env var is set at compile time // <$nu.data_dir>/vendor/autoload // NU_VENDOR_AUTOLOAD_DIR at runtime, if env var is set let into_autoload_path_fn = |mut path: PathBuf| { path.push("nushell"); path.push("vendor"); path.push("autoload"); path }; let mut dirs = Vec::new(); let mut append_fn = |path: PathBuf| { if !dirs.contains(&path) { dirs.push(path) } }; #[cfg(target_os = "macos")] std::iter::once("/Library/Application Support") .map(PathBuf::from) .map(into_autoload_path_fn) .for_each(&mut append_fn); #[cfg(unix)] { use std::os::unix::ffi::OsStrExt; std::env::var_os("XDG_DATA_DIRS") .or_else(|| { option_env!("PREFIX").map(|prefix| { if prefix.ends_with("local") { std::ffi::OsString::from(format!("{prefix}/share")) } else { std::ffi::OsString::from(format!("{prefix}/local/share:{prefix}/share")) } }) }) .unwrap_or_else(|| std::ffi::OsString::from("/usr/local/share/:/usr/share/")) .as_encoded_bytes() .split(|b| *b == b':') .map(|split| into_autoload_path_fn(PathBuf::from(std::ffi::OsStr::from_bytes(split)))) .rev() .for_each(&mut append_fn); } #[cfg(target_os = "windows")] dirs_sys::known_folder(windows_sys::Win32::UI::Shell::FOLDERID_ProgramData) .into_iter() .map(into_autoload_path_fn) .for_each(&mut append_fn); if let Some(path) = option_env!("NU_VENDOR_AUTOLOAD_DIR") { append_fn(PathBuf::from(path)); } if let Some(data_dir) = nu_path::data_dir() { append_fn(into_autoload_path_fn(PathBuf::from(data_dir))); } if let Some(path) = std::env::var_os("NU_VENDOR_AUTOLOAD_DIR") { append_fn(PathBuf::from(path)); } dirs } pub fn get_user_autoload_dirs(_engine_state: &EngineState) -> Vec<PathBuf> { // User autoload directories - Currently just `autoload` in the default // configuration directory let mut dirs = Vec::new(); let mut append_fn = |path: PathBuf| { if !dirs.contains(&path) { dirs.push(path) } }; if let Some(config_dir) = nu_path::nu_config_dir() { append_fn(config_dir.join("autoload").into()); } dirs } fn eval_const_call( working_set: &StateWorkingSet, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let decl = working_set.get_decl(call.decl_id); if !decl.is_const() { return Err(ShellError::NotAConstCommand { span: call.head }); } if !decl.is_known_external() && call.named_iter().any(|(flag, _, _)| flag.item == "help") { // It would require re-implementing get_full_help() for const evaluation. Assuming that // getting help messages at parse-time is rare enough, we can simply disallow it. return Err(ShellError::NotAConstHelp { span: call.head }); } decl.run_const(working_set, &call.into(), input) } pub fn eval_const_subexpression( working_set: &StateWorkingSet, block: &Block, mut input: PipelineData, span: Span, ) -> Result<PipelineData, ShellError> { for pipeline in block.pipelines.iter() { for element in pipeline.elements.iter() { if element.redirection.is_some() { return Err(ShellError::NotAConstant { span }); } input = eval_constant_with_input(working_set, &element.expr, input)? } } Ok(input) } pub fn eval_constant_with_input( working_set: &StateWorkingSet, expr: &Expression, input: PipelineData, ) -> Result<PipelineData, ShellError> { match &expr.expr { Expr::Call(call) => eval_const_call(working_set, call, input), Expr::Subexpression(block_id) => { let block = working_set.get_block(*block_id); eval_const_subexpression(working_set, block, input, expr.span(&working_set)) } _ => eval_constant(working_set, expr).map(|v| PipelineData::value(v, None)), } } /// Evaluate a constant value at parse time pub fn eval_constant( working_set: &StateWorkingSet, expr: &Expression, ) -> Result<Value, ShellError> { // TODO: Allow debugging const eval <EvalConst as Eval>::eval::<WithoutDebug>(working_set, &mut (), expr) } struct EvalConst; impl Eval for EvalConst { type State<'a> = &'a StateWorkingSet<'a>; type MutState = (); fn get_config(state: Self::State<'_>, _: &mut ()) -> Arc<Config> { state.get_config().clone() } fn eval_var( working_set: &StateWorkingSet, _: &mut (), var_id: VarId, span: Span, ) -> Result<Value, ShellError> { match working_set.get_variable(var_id).const_val.as_ref() { Some(val) => Ok(val.clone()), None => Err(ShellError::NotAConstant { span }), } } fn eval_call<D: DebugContext>( working_set: &StateWorkingSet, _: &mut (), call: &Call, span: Span, ) -> Result<Value, ShellError> { // TODO: Allow debugging const eval // TODO: eval.rs uses call.head for the span rather than expr.span eval_const_call(working_set, call, PipelineData::empty())?.into_value(span) } fn eval_external_call( _: &StateWorkingSet, _: &mut (), _: &Expression, _: &[ExternalArgument], span: Span, ) -> Result<Value, ShellError> { // TODO: It may be more helpful to give not_a_const_command error Err(ShellError::NotAConstant { span }) } fn eval_collect<D: DebugContext>( _: &StateWorkingSet, _: &mut (), _var_id: VarId, expr: &Expression, ) -> Result<Value, ShellError> { Err(ShellError::NotAConstant { span: expr.span }) } fn eval_subexpression<D: DebugContext>( working_set: &StateWorkingSet, _: &mut (), block_id: BlockId, span: Span, ) -> Result<Value, ShellError> { // If parsing errors exist in the subexpression, don't bother to evaluate it. if working_set .parse_errors .iter() .any(|error| span.contains_span(error.span())) { return Err(ShellError::ParseErrorInConstant { span }); } // TODO: Allow debugging const eval let block = working_set.get_block(block_id); eval_const_subexpression(working_set, block, PipelineData::empty(), span)?.into_value(span) } fn regex_match( _: &StateWorkingSet, _op_span: Span, _: &Value, _: &Value, _: bool, expr_span: Span, ) -> Result<Value, ShellError> { Err(ShellError::NotAConstant { span: expr_span }) } fn eval_assignment<D: DebugContext>( _: &StateWorkingSet, _: &mut (), _: &Expression, _: &Expression, _: Assignment, _op_span: Span, expr_span: Span, ) -> Result<Value, ShellError> { // TODO: Allow debugging const eval Err(ShellError::NotAConstant { span: expr_span }) } fn eval_row_condition_or_closure( _: &StateWorkingSet, _: &mut (), _: BlockId, span: Span, ) -> Result<Value, ShellError> { Err(ShellError::NotAConstant { span }) } fn eval_overlay(_: &StateWorkingSet, span: Span) -> Result<Value, ShellError> { Err(ShellError::NotAConstant { span }) } fn unreachable(working_set: &StateWorkingSet, expr: &Expression) -> Result<Value, ShellError> { Err(ShellError::NotAConstant { span: expr.span(&working_set), }) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/eval_base.rs
crates/nu-protocol/src/eval_base.rs
//! Foundational [`Eval`] trait allowing dispatch between const-eval and regular evaluation use nu_path::expand_path; use crate::{ BlockId, Config, ENV_VARIABLE_ID, GetSpan, Range, Record, ShellError, Span, Value, VarId, ast::{ Assignment, Bits, Boolean, Call, Comparison, Expr, Expression, ExternalArgument, ListItem, Math, Operator, RecordItem, eval_operator, }, debugger::DebugContext, }; use std::{borrow::Cow, collections::HashMap, sync::Arc}; /// To share implementations for regular eval and const eval pub trait Eval { /// State that doesn't need to be mutated. /// EngineState for regular eval and StateWorkingSet for const eval type State<'a>: Copy + GetSpan; /// State that needs to be mutated. /// This is the stack for regular eval, and unused by const eval type MutState; fn eval<D: DebugContext>( state: Self::State<'_>, mut_state: &mut Self::MutState, expr: &Expression, ) -> Result<Value, ShellError> { let expr_span = expr.span(&state); match &expr.expr { Expr::AttributeBlock(ab) => Self::eval::<D>(state, mut_state, &ab.item), Expr::Bool(b) => Ok(Value::bool(*b, expr_span)), Expr::Int(i) => Ok(Value::int(*i, expr_span)), Expr::Float(f) => Ok(Value::float(*f, expr_span)), Expr::Binary(b) => Ok(Value::binary(b.clone(), expr_span)), Expr::Filepath(path, quoted) => { if *quoted { Ok(Value::string(path, expr_span)) } else { let path = expand_path(path, true); Ok(Value::string(path.to_string_lossy(), expr_span)) } } Expr::Directory(path, quoted) => { if path == "-" { Ok(Value::string("-", expr_span)) } else if *quoted { Ok(Value::string(path, expr_span)) } else { let path = expand_path(path, true); Ok(Value::string(path.to_string_lossy(), expr_span)) } } Expr::Var(var_id) => Self::eval_var(state, mut_state, *var_id, expr_span), Expr::CellPath(cell_path) => Ok(Value::cell_path(cell_path.clone(), expr_span)), Expr::FullCellPath(cell_path) => { let value = Self::eval::<D>(state, mut_state, &cell_path.head)?; // Cell paths are usually case-sensitive, but we give $env // special treatment. let tail = if cell_path.head.expr == Expr::Var(ENV_VARIABLE_ID) { let mut tail = cell_path.tail.clone(); if let Some(pm) = tail.first_mut() { pm.make_insensitive(); } Cow::Owned(tail) } else { Cow::Borrowed(&cell_path.tail) }; value.follow_cell_path(&tail).map(Cow::into_owned) } Expr::DateTime(dt) => Ok(Value::date(*dt, expr_span)), Expr::List(list) => { let mut output = vec![]; for item in list { match item { ListItem::Item(expr) => output.push(Self::eval::<D>(state, mut_state, expr)?), ListItem::Spread(_, expr) => match Self::eval::<D>(state, mut_state, expr)? { Value::List { vals, .. } => output.extend(vals), Value::Nothing { .. } => (), _ => return Err(ShellError::CannotSpreadAsList { span: expr_span }), }, } } Ok(Value::list(output, expr_span)) } Expr::Record(items) => { let mut record = Record::new(); let mut col_names = HashMap::new(); for item in items { match item { RecordItem::Pair(col, val) => { // avoid duplicate cols let col_name = Self::eval::<D>(state, mut_state, col)?.coerce_into_string()?; let col_span = col.span(&state); if let Some(orig_span) = col_names.get(&col_name) { return Err(ShellError::ColumnDefinedTwice { col_name, second_use: col_span, first_use: *orig_span, }); } else { col_names.insert(col_name.clone(), col_span); record.push(col_name, Self::eval::<D>(state, mut_state, val)?); } } RecordItem::Spread(_, inner) => { let inner_span = inner.span(&state); match Self::eval::<D>(state, mut_state, inner)? { Value::Record { val: inner_val, .. } => { for (col_name, val) in inner_val.into_owned() { if let Some(orig_span) = col_names.get(&col_name) { return Err(ShellError::ColumnDefinedTwice { col_name, second_use: inner_span, first_use: *orig_span, }); } else { col_names.insert(col_name.clone(), inner_span); record.push(col_name, val); } } } _ => { return Err(ShellError::CannotSpreadAsRecord { span: inner_span, }) } } } } } Ok(Value::record(record, expr_span)) } Expr::Table(table) => { let mut output_headers = vec![]; for expr in table.columns.as_ref() { let header = Self::eval::<D>(state, mut_state, expr)?.coerce_into_string()?; if let Some(idx) = output_headers .iter() .position(|existing| existing == &header) { let first_use = table.columns[idx].span(&state); return Err(ShellError::ColumnDefinedTwice { col_name: header, second_use: expr_span, first_use, }); } else { output_headers.push(header); } } let mut output_rows = vec![]; for val in table.rows.as_ref() { let record = output_headers.iter().zip(val.as_ref()).map(|(col, expr)| { Self::eval::<D>(state, mut_state, expr).map(|val| (col.clone(), val)) }).collect::<Result<_,_>>()?; output_rows.push(Value::record( record, expr_span, )); } Ok(Value::list(output_rows, expr_span)) } Expr::Keyword(kw) => Self::eval::<D>(state, mut_state, &kw.expr), Expr::String(s) | Expr::RawString(s) => Ok(Value::string(s.clone(), expr_span)), Expr::Nothing => Ok(Value::nothing(expr_span)), Expr::ValueWithUnit(value) => match Self::eval::<D>(state, mut_state, &value.expr)? { Value::Int { val, .. } => value.unit.item.build_value(val, value.unit.span), x => Err(ShellError::CantConvert { to_type: "unit value".into(), from_type: x.get_type().to_string(), span: value.expr.span(&state), help: None, }), }, Expr::Call(call) => Self::eval_call::<D>(state, mut_state, call, expr_span), Expr::ExternalCall(head, args) => { Self::eval_external_call(state, mut_state, head, args, expr_span) } Expr::Collect(var_id, expr) => { Self::eval_collect::<D>(state, mut_state, *var_id, expr) } Expr::Subexpression(block_id) => { Self::eval_subexpression::<D>(state, mut_state, *block_id, expr_span) } Expr::Range(range) => { let from = if let Some(f) = &range.from { Self::eval::<D>(state, mut_state, f)? } else { Value::nothing(expr_span) }; let next = if let Some(s) = &range.next { Self::eval::<D>(state, mut_state, s)? } else { Value::nothing(expr_span) }; let to = if let Some(t) = &range.to { Self::eval::<D>(state, mut_state, t)? } else { Value::nothing(expr_span) }; Ok(Value::range( Range::new(from, next, to, range.operator.inclusion, expr_span)?, expr_span, )) } Expr::UnaryNot(expr) => { let lhs = Self::eval::<D>(state, mut_state, expr)?; match lhs { Value::Bool { val, .. } => Ok(Value::bool(!val, expr_span)), other => Err(ShellError::TypeMismatch { err_message: format!("expected bool, found {}", other.get_type()), span: expr_span, }), } } Expr::BinaryOp(lhs, op, rhs) => { let op_span = op.span(&state); let op = eval_operator(op)?; match op { Operator::Boolean(boolean) => { let lhs = Self::eval::<D>(state, mut_state, lhs)?; match boolean { Boolean::And => { if lhs.is_false() { Ok(Value::bool(false, expr_span)) } else { let rhs = Self::eval::<D>(state, mut_state, rhs)?; lhs.and(op_span, &rhs, expr_span) } } Boolean::Or => { if lhs.is_true() { Ok(Value::bool(true, expr_span)) } else { let rhs = Self::eval::<D>(state, mut_state, rhs)?; lhs.or(op_span, &rhs, expr_span) } } Boolean::Xor => { let rhs = Self::eval::<D>(state, mut_state, rhs)?; lhs.xor(op_span, &rhs, expr_span) } } } Operator::Math(math) => { let lhs = Self::eval::<D>(state, mut_state, lhs)?; let rhs = Self::eval::<D>(state, mut_state, rhs)?; match math { Math::Add => lhs.add(op_span, &rhs, expr_span), Math::Subtract => lhs.sub(op_span, &rhs, expr_span), Math::Multiply => lhs.mul(op_span, &rhs, expr_span), Math::Divide => lhs.div(op_span, &rhs, expr_span), Math::FloorDivide => lhs.floor_div(op_span, &rhs, expr_span), Math::Modulo => lhs.modulo(op_span, &rhs, expr_span), Math::Pow => lhs.pow(op_span, &rhs, expr_span), Math::Concatenate => lhs.concat(op_span, &rhs, expr_span), } } Operator::Comparison(comparison) => { let lhs = Self::eval::<D>(state, mut_state, lhs)?; let rhs = Self::eval::<D>(state, mut_state, rhs)?; match comparison { Comparison::LessThan => lhs.lt(op_span, &rhs, expr_span), Comparison::LessThanOrEqual => lhs.lte(op_span, &rhs, expr_span), Comparison::GreaterThan => lhs.gt(op_span, &rhs, expr_span), Comparison::GreaterThanOrEqual => lhs.gte(op_span, &rhs, expr_span), Comparison::Equal => lhs.eq(op_span, &rhs, expr_span), Comparison::NotEqual => lhs.ne(op_span, &rhs, expr_span), Comparison::In => lhs.r#in(op_span, &rhs, expr_span), Comparison::NotIn => lhs.not_in(op_span, &rhs, expr_span), Comparison::Has => lhs.has(op_span, &rhs, expr_span), Comparison::NotHas => lhs.not_has(op_span, &rhs, expr_span), Comparison::StartsWith => lhs.starts_with(op_span, &rhs, expr_span), Comparison::NotStartsWith => lhs.not_starts_with(op_span, &rhs, expr_span), Comparison::EndsWith => lhs.ends_with(op_span, &rhs, expr_span), Comparison::NotEndsWith => lhs.not_ends_with(op_span, &rhs, expr_span), Comparison::RegexMatch => { Self::regex_match(state, op_span, &lhs, &rhs, false, expr_span) } Comparison::NotRegexMatch => { Self::regex_match(state, op_span, &lhs, &rhs, true, expr_span) } } } Operator::Bits(bits) => { let lhs = Self::eval::<D>(state, mut_state, lhs)?; let rhs = Self::eval::<D>(state, mut_state, rhs)?; match bits { Bits::BitAnd => lhs.bit_and(op_span, &rhs, expr_span), Bits::BitOr => lhs.bit_or(op_span, &rhs, expr_span), Bits::BitXor => lhs.bit_xor(op_span, &rhs, expr_span), Bits::ShiftLeft => lhs.bit_shl(op_span, &rhs, expr_span), Bits::ShiftRight => lhs.bit_shr(op_span, &rhs, expr_span), } } Operator::Assignment(assignment) => Self::eval_assignment::<D>( state, mut_state, lhs, rhs, assignment, op_span, expr_span ), } } Expr::RowCondition(block_id) | Expr::Closure(block_id) => { Self::eval_row_condition_or_closure(state, mut_state, *block_id, expr_span) } Expr::StringInterpolation(exprs) => { let config = Self::get_config(state, mut_state); let str = exprs .iter() .map(|expr| Self::eval::<D>(state, mut_state, expr).map(|v| v.to_expanded_string(", ", &config))) .collect::<Result<String, _>>()?; Ok(Value::string(str, expr_span)) } Expr::GlobInterpolation(exprs, quoted) => { let config = Self::get_config(state, mut_state); let str = exprs .iter() .map(|expr| Self::eval::<D>(state, mut_state, expr).map(|v| v.to_expanded_string(", ", &config))) .collect::<Result<String, _>>()?; Ok(Value::glob(str, *quoted, expr_span)) } Expr::Overlay(_) => Self::eval_overlay(state, expr_span), Expr::GlobPattern(pattern, quoted) => { // GlobPattern is similar to Filepath // But we don't want to expand path during eval time, it's required for `nu_engine::glob_from` to run correctly Ok(Value::glob(pattern, *quoted, expr_span)) } Expr::MatchBlock(_) // match blocks are handled by `match` | Expr::Block(_) // blocks are handled directly by core commands | Expr::VarDecl(_) | Expr::ImportPattern(_) | Expr::Signature(_) | Expr::Operator(_) | Expr::Garbage => Self::unreachable(state, expr), } } fn get_config(state: Self::State<'_>, mut_state: &mut Self::MutState) -> Arc<Config>; fn eval_var( state: Self::State<'_>, mut_state: &mut Self::MutState, var_id: VarId, span: Span, ) -> Result<Value, ShellError>; fn eval_call<D: DebugContext>( state: Self::State<'_>, mut_state: &mut Self::MutState, call: &Call, span: Span, ) -> Result<Value, ShellError>; fn eval_external_call( state: Self::State<'_>, mut_state: &mut Self::MutState, head: &Expression, args: &[ExternalArgument], span: Span, ) -> Result<Value, ShellError>; fn eval_collect<D: DebugContext>( state: Self::State<'_>, mut_state: &mut Self::MutState, var_id: VarId, expr: &Expression, ) -> Result<Value, ShellError>; fn eval_subexpression<D: DebugContext>( state: Self::State<'_>, mut_state: &mut Self::MutState, block_id: BlockId, span: Span, ) -> Result<Value, ShellError>; fn regex_match( state: Self::State<'_>, op_span: Span, lhs: &Value, rhs: &Value, invert: bool, expr_span: Span, ) -> Result<Value, ShellError>; #[allow(clippy::too_many_arguments)] fn eval_assignment<D: DebugContext>( state: Self::State<'_>, mut_state: &mut Self::MutState, lhs: &Expression, rhs: &Expression, assignment: Assignment, op_span: Span, expr_span: Span, ) -> Result<Value, ShellError>; fn eval_row_condition_or_closure( state: Self::State<'_>, mut_state: &mut Self::MutState, block_id: BlockId, span: Span, ) -> Result<Value, ShellError>; fn eval_overlay(state: Self::State<'_>, span: Span) -> Result<Value, ShellError>; /// For expressions that should never actually be evaluated fn unreachable(state: Self::State<'_>, expr: &Expression) -> Result<Value, ShellError>; }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ty.rs
crates/nu-protocol/src/ty.rs
use crate::SyntaxShape; use serde::{Deserialize, Serialize}; use std::fmt::Display; #[cfg(test)] use strum_macros::EnumIter; #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Hash, Ord, PartialOrd)] #[cfg_attr(test, derive(EnumIter))] pub enum Type { /// Top type, supertype of all types Any, Binary, Block, Bool, CellPath, Closure, Custom(Box<str>), Date, Duration, Error, Filesize, Float, Int, List(Box<Type>), #[default] Nothing, /// Supertype of Int and Float. Equivalent to `oneof<int, float>` Number, /// Supertype of all types it contains. OneOf(Box<[Type]>), Range, Record(Box<[(String, Type)]>), String, Glob, Table(Box<[(String, Type)]>), } impl Type { pub fn list(inner: Type) -> Self { Self::List(Box::new(inner)) } pub fn one_of(types: impl IntoIterator<Item = Type>) -> Self { Self::OneOf(types.into_iter().collect()) } pub fn record() -> Self { Self::Record([].into()) } pub fn table() -> Self { Self::Table([].into()) } pub fn custom(name: impl Into<Box<str>>) -> Self { Self::Custom(name.into()) } /// Determine of the [`Type`] is a [subtype](https://en.wikipedia.org/wiki/Subtyping) of `other`. /// /// This should only be used at parse-time. /// If you have a concrete [`Value`](crate::Value) or [`PipelineData`](crate::PipelineData), /// you should use their respective `is_subtype_of` methods instead. pub fn is_subtype_of(&self, other: &Type) -> bool { // Structural subtyping let is_subtype_collection = |this: &[(String, Type)], that: &[(String, Type)]| { if this.is_empty() || that.is_empty() { true } else if this.len() < that.len() { false } else { that.iter().all(|(col_y, ty_y)| { if let Some((_, ty_x)) = this.iter().find(|(col_x, _)| col_x == col_y) { ty_x.is_subtype_of(ty_y) } else { false } }) } }; match (self, other) { (t, u) if t == u => true, (_, Type::Any) => true, // We want `get`/`select`/etc to accept string and int values, so it's convenient to // use them with variables, without having to explicitly convert them into cell-paths (Type::String | Type::Int, Type::CellPath) => true, (Type::OneOf(oneof), Type::CellPath) => { oneof.iter().all(|t| t.is_subtype_of(&Type::CellPath)) } (Type::Float | Type::Int, Type::Number) => true, (Type::Glob, Type::String) | (Type::String, Type::Glob) => true, (Type::List(t), Type::List(u)) if t.is_subtype_of(u) => true, // List is covariant (Type::Record(this), Type::Record(that)) | (Type::Table(this), Type::Table(that)) => { is_subtype_collection(this, that) } (Type::Table(_), Type::List(that)) if matches!(**that, Type::Any) => true, (Type::Table(this), Type::List(that)) => { matches!(that.as_ref(), Type::Record(that) if is_subtype_collection(this, that)) } (Type::List(this), Type::Table(that)) => { matches!(this.as_ref(), Type::Record(this) if is_subtype_collection(this, that)) } (Type::OneOf(this), that @ Type::OneOf(_)) => { this.iter().all(|t| t.is_subtype_of(that)) } (this, Type::OneOf(that)) => that.iter().any(|t| this.is_subtype_of(t)), _ => false, } } /// Returns the supertype between `self` and `other`, or `Type::Any` if they're unrelated pub fn widen(self, other: Type) -> Type { /// Returns supertype of arguments without creating a `oneof`, or falling back to `any` /// (unless one or both of the arguments are `any`) fn flat_widen(lhs: Type, rhs: Type) -> Result<Type, (Type, Type)> { Ok(match (lhs, rhs) { (lhs, rhs) if lhs == rhs => lhs, (Type::Any, _) | (_, Type::Any) => Type::Any, // (int, int) and (float, float) cases are already handled by the first match arm ( Type::Int | Type::Float | Type::Number, Type::Int | Type::Float | Type::Number, ) => Type::Number, (Type::Glob, Type::String) | (Type::String, Type::Glob) => Type::String, (Type::Record(this), Type::Record(that)) => { Type::Record(widen_collection(this, that)) } (Type::Table(this), Type::Table(that)) => Type::Table(widen_collection(this, that)), (Type::List(list_item), Type::Table(table)) | (Type::Table(table), Type::List(list_item)) => { let item = match *list_item { Type::Record(record) => Type::Record(widen_collection(record, table)), list_item => Type::one_of([list_item, Type::Record(table)]), }; Type::List(Box::new(item)) } (Type::List(lhs), Type::List(rhs)) => Type::list(lhs.widen(*rhs)), (t, u) => return Err((t, u)), }) } fn widen_collection( lhs: Box<[(String, Type)]>, rhs: Box<[(String, Type)]>, ) -> Box<[(String, Type)]> { if lhs.is_empty() || rhs.is_empty() { return [].into(); } let (small, big) = match lhs.len() <= rhs.len() { true => (lhs, rhs), false => (rhs, lhs), }; small .into_iter() .filter_map(|(col, typ)| { big.iter() .find_map(|(b_col, b_typ)| (&col == b_col).then(|| b_typ.clone())) .map(|b_typ| (col, typ, b_typ)) }) .map(|(col, t, u)| (col, t.widen(u))) .collect() } fn oneof_add(oneof: &mut Vec<Type>, mut t: Type) { if oneof.contains(&t) { return; } for one in oneof.iter_mut() { match flat_widen(std::mem::replace(one, Type::Any), t) { Ok(one_t) => { *one = one_t; return; } Err((one_, t_)) => { *one = one_; t = t_; } } } oneof.push(t); } let tu = match flat_widen(self, other) { Ok(t) => return t, Err(tu) => tu, }; match tu { (Type::OneOf(ts), Type::OneOf(us)) => { let (big, small) = match ts.len() >= us.len() { true => (ts, us), false => (us, ts), }; let mut out = big.into_vec(); for t in small.into_iter() { oneof_add(&mut out, t); } Type::one_of(out) } (Type::OneOf(oneof), t) | (t, Type::OneOf(oneof)) => { let mut out = oneof.into_vec(); oneof_add(&mut out, t); Type::one_of(out) } (this, other) => Type::one_of([this, other]), } } /// Returns the supertype of all types within `it`. Short-circuits on, and falls back to, `Type::Any`. pub fn supertype_of(it: impl IntoIterator<Item = Type>) -> Option<Self> { let mut it = it.into_iter(); it.next().and_then(|head| { it.try_fold(head, |acc, e| match acc.widen(e) { Type::Any => None, r => Some(r), }) }) } pub fn is_numeric(&self) -> bool { matches!(self, Type::Int | Type::Float | Type::Number) } pub fn is_list(&self) -> bool { matches!(self, Type::List(_)) } /// Does this type represent a data structure containing values that can be addressed using 'cell paths'? pub fn accepts_cell_paths(&self) -> bool { matches!(self, Type::List(_) | Type::Record(_) | Type::Table(_)) } pub fn to_shape(&self) -> SyntaxShape { let mk_shape = |tys: &[(String, Type)]| { tys.iter() .map(|(key, val)| (key.clone(), val.to_shape())) .collect() }; match self { Type::Int => SyntaxShape::Int, Type::Float => SyntaxShape::Float, Type::Range => SyntaxShape::Range, Type::Bool => SyntaxShape::Boolean, Type::String => SyntaxShape::String, Type::Block => SyntaxShape::Block, // FIXME needs more accuracy Type::Closure => SyntaxShape::Closure(None), // FIXME needs more accuracy Type::CellPath => SyntaxShape::CellPath, Type::Duration => SyntaxShape::Duration, Type::Date => SyntaxShape::DateTime, Type::Filesize => SyntaxShape::Filesize, Type::List(x) => SyntaxShape::List(Box::new(x.to_shape())), Type::Number => SyntaxShape::Number, Type::OneOf(types) => SyntaxShape::OneOf(types.iter().map(Type::to_shape).collect()), Type::Nothing => SyntaxShape::Nothing, Type::Record(entries) => SyntaxShape::Record(mk_shape(entries)), Type::Table(columns) => SyntaxShape::Table(mk_shape(columns)), Type::Any => SyntaxShape::Any, Type::Error => SyntaxShape::Any, Type::Binary => SyntaxShape::Binary, Type::Custom(_) => SyntaxShape::Any, Type::Glob => SyntaxShape::GlobPattern, } } /// Get a string representation, without inner type specification of lists, /// tables and records (get `list` instead of `list<any>` pub fn get_non_specified_string(&self) -> String { match self { Type::Closure => String::from("closure"), Type::Bool => String::from("bool"), Type::Block => String::from("block"), Type::CellPath => String::from("cell-path"), Type::Date => String::from("datetime"), Type::Duration => String::from("duration"), Type::Filesize => String::from("filesize"), Type::Float => String::from("float"), Type::Int => String::from("int"), Type::Range => String::from("range"), Type::Record(_) => String::from("record"), Type::Table(_) => String::from("table"), Type::List(_) => String::from("list"), Type::Nothing => String::from("nothing"), Type::Number => String::from("number"), Type::OneOf(_) => String::from("oneof"), Type::String => String::from("string"), Type::Any => String::from("any"), Type::Error => String::from("error"), Type::Binary => String::from("binary"), Type::Custom(_) => String::from("custom"), Type::Glob => String::from("glob"), } } } impl Display for Type { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Type::Block => write!(f, "block"), Type::Closure => write!(f, "closure"), Type::Bool => write!(f, "bool"), Type::CellPath => write!(f, "cell-path"), Type::Date => write!(f, "datetime"), Type::Duration => write!(f, "duration"), Type::Filesize => write!(f, "filesize"), Type::Float => write!(f, "float"), Type::Int => write!(f, "int"), Type::Range => write!(f, "range"), Type::Record(fields) => { if fields.is_empty() { write!(f, "record") } else { write!( f, "record<{}>", fields .iter() .map(|(x, y)| format!("{x}: {y}")) .collect::<Vec<String>>() .join(", "), ) } } Type::Table(columns) => { if columns.is_empty() { write!(f, "table") } else { write!( f, "table<{}>", columns .iter() .map(|(x, y)| format!("{x}: {y}")) .collect::<Vec<String>>() .join(", ") ) } } Type::List(l) => write!(f, "list<{l}>"), Type::Nothing => write!(f, "nothing"), Type::Number => write!(f, "number"), Type::OneOf(types) => { write!(f, "oneof")?; let [first, rest @ ..] = &**types else { return Ok(()); }; write!(f, "<{first}")?; for t in rest { write!(f, ", {t}")?; } f.write_str(">") } Type::String => write!(f, "string"), Type::Any => write!(f, "any"), Type::Error => write!(f, "error"), Type::Binary => write!(f, "binary"), Type::Custom(custom) => write!(f, "{custom}"), Type::Glob => write!(f, "glob"), } } } /// Get a string nicely combining multiple types /// /// Helpful for listing types in errors pub fn combined_type_string(types: &[Type], join_word: &str) -> Option<String> { use std::fmt::Write as _; match types { [] => None, [one] => Some(one.to_string()), [one, two] => Some(format!("{one} {join_word} {two}")), [initial @ .., last] => { let mut out = String::new(); for ele in initial { let _ = write!(out, "{ele}, "); } let _ = write!(out, "{join_word} {last}"); Some(out) } } } #[cfg(test)] mod tests { use super::Type; use strum::IntoEnumIterator; mod subtype_relation { use super::*; #[test] fn test_reflexivity() { for ty in Type::iter() { assert!(ty.is_subtype_of(&ty)); } } #[test] fn test_any_is_top_type() { for ty in Type::iter() { assert!(ty.is_subtype_of(&Type::Any)); } } #[test] fn test_number_supertype() { assert!(Type::Int.is_subtype_of(&Type::Number)); assert!(Type::Float.is_subtype_of(&Type::Number)); } #[test] fn test_list_covariance() { for ty1 in Type::iter() { for ty2 in Type::iter() { let list_ty1 = Type::List(Box::new(ty1.clone())); let list_ty2 = Type::List(Box::new(ty2.clone())); assert_eq!(list_ty1.is_subtype_of(&list_ty2), ty1.is_subtype_of(&ty2)); } } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/lev_distance.rs
crates/nu-protocol/src/lev_distance.rs
// This file is copied from the rust compiler project: // https://github.com/rust-lang/rust/blob/cf9ed0dd5836201843d28bbad50abfbe1913af2a/compiler/rustc_span/src/lev_distance.rs#L1 // https://github.com/rust-lang/rust/blob/cf9ed0dd5836201843d28bbad50abfbe1913af2a/LICENSE-MIT // // - the rust compiler-specific symbol::Symbol has been replaced by &str // - unstable feature .then_some has been replaced by an if ... else expression //! Levenshtein distances. //! //! The [Levenshtein distance] is a metric for measuring the difference between two strings. //! //! [Levenshtein distance]: https://en.wikipedia.org/wiki/Levenshtein_distance use std::cmp; /// Finds the Levenshtein distance between two strings. /// /// Returns None if the distance exceeds the limit. pub fn lev_distance(a: &str, b: &str, limit: usize) -> Option<usize> { let n = a.chars().count(); let m = b.chars().count(); let min_dist = m.abs_diff(n); if min_dist > limit { return None; } if n == 0 || m == 0 { return Some(min_dist); } let mut dcol: Vec<_> = (0..=m).collect(); for (i, sc) in a.chars().enumerate() { let mut current = i; dcol[0] = current + 1; for (j, tc) in b.chars().enumerate() { let next = dcol[j + 1]; if sc == tc { dcol[j + 1] = current; } else { dcol[j + 1] = cmp::min(current, next); dcol[j + 1] = cmp::min(dcol[j + 1], dcol[j]) + 1; } current = next; } } if dcol[m] <= limit { Some(dcol[m]) } else { None } } /// Finds the Levenshtein distance between two strings. pub fn levenshtein_distance(a: &str, b: &str) -> usize { lev_distance(a, b, usize::MAX).unwrap_or(usize::MAX) } /// Provides a word similarity score between two words that accounts for substrings being more /// meaningful than a typical Levenshtein distance. The lower the score, the closer the match. /// 0 is an identical match. /// /// Uses the Levenshtein distance between the two strings and removes the cost of the length /// difference. If this is 0 then it is either a substring match or a full word match, in the /// substring match case we detect this and return `1`. To prevent finding meaningless substrings, /// eg. "in" in "shrink", we only perform this subtraction of length difference if one of the words /// is not greater than twice the length of the other. For cases where the words are close in size /// but not an exact substring then the cost of the length difference is discounted by half. /// /// Returns `None` if the distance exceeds the limit. pub fn lev_distance_with_substrings(a: &str, b: &str, limit: usize) -> Option<usize> { let n = a.chars().count(); let m = b.chars().count(); // Check one isn't less than half the length of the other. If this is true then there is a // big difference in length. let big_len_diff = (n * 2) < m || (m * 2) < n; let len_diff = m.abs_diff(n); let lev = lev_distance(a, b, limit + len_diff)?; // This is the crux, subtracting length difference means exact substring matches will now be 0 let score = lev - len_diff; // If the score is 0 but the words have different lengths then it's a substring match not a full // word match let score = if score == 0 && len_diff > 0 && !big_len_diff { 1 // Exact substring match, but not a total word match so return non-zero } else if !big_len_diff { // Not a big difference in length, discount cost of length difference score + len_diff.div_ceil(2) } else { // A big difference in length, add back the difference in length to the score score + len_diff }; if score <= limit { Some(score) } else { None } } /// Finds the best match for given word in the given iterator where substrings are meaningful. /// /// A version of [`find_best_match_for_name`] that uses [`lev_distance_with_substrings`] as the score /// for word similarity. This takes an optional distance limit which defaults to one-third of the /// given word. /// /// Besides the modified Levenshtein, we use case insensitive comparison to improve accuracy /// on an edge case with a lower(upper)case letters mismatch. pub fn find_best_match_for_name_with_substrings<'c>( candidates: &[&'c str], lookup: &str, dist: Option<usize>, ) -> Option<&'c str> { find_best_match_for_name_impl(true, candidates, lookup, dist) } /// Finds the best match for a given word in the given iterator. /// /// As a loose rule to avoid the obviously incorrect suggestions, it takes /// an optional limit for the maximum allowable edit distance, which defaults /// to one-third of the given word. /// /// Besides Levenshtein, we use case insensitive comparison to improve accuracy /// on an edge case with a lower(upper)case letters mismatch. #[allow(dead_code)] pub fn find_best_match_for_name<'c>( candidates: &[&'c str], lookup: &str, dist: Option<usize>, ) -> Option<&'c str> { find_best_match_for_name_impl(false, candidates, lookup, dist) } #[cold] fn find_best_match_for_name_impl<'c>( use_substring_score: bool, candidates: &[&'c str], lookup: &str, dist: Option<usize>, ) -> Option<&'c str> { let lookup_uppercase = lookup.to_uppercase(); // Priority of matches: // 1. Exact case insensitive match // 2. Levenshtein distance match // 3. Sorted word match if let Some(c) = candidates .iter() .find(|c| c.to_uppercase() == lookup_uppercase) { return Some(*c); } let mut dist = dist.unwrap_or_else(|| cmp::max(lookup.len(), 3) / 3); let mut best = None; for c in candidates { let lev_dist = if use_substring_score { lev_distance_with_substrings(lookup, c, dist) } else { lev_distance(lookup, c, dist) }; match lev_dist { Some(0) => return Some(*c), Some(d) => { dist = d - 1; best = Some(*c); } None => {} } } if best.is_some() { return best; } find_match_by_sorted_words(candidates, lookup) } fn find_match_by_sorted_words<'c>(iter_names: &[&'c str], lookup: &str) -> Option<&'c str> { iter_names.iter().fold(None, |result, candidate| { if sort_by_words(candidate) == sort_by_words(lookup) { Some(*candidate) } else { result } }) } fn sort_by_words(name: &str) -> String { let mut split_words: Vec<&str> = name.split('_').collect(); // We are sorting primitive &strs and can use unstable sort here. split_words.sort_unstable(); split_words.join("_") } // This file is copied from the rust compiler project: // https://github.com/rust-lang/rust/blob/cf9ed0dd5836201843d28bbad50abfbe1913af2a/compiler/rustc_span/src/lev_distance.rs#L1 // https://github.com/rust-lang/rust/blob/cf9ed0dd5836201843d28bbad50abfbe1913af2a/LICENSE-MIT // Permission is hereby granted, free of charge, to any // person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the // Software without restriction, including without // limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice // shall be included in all copies or substantial portions // of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // Footer
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/did_you_mean.rs
crates/nu-protocol/src/did_you_mean.rs
pub fn did_you_mean<'a, 'b, I, S>(possibilities: I, input: &'b str) -> Option<String> where I: IntoIterator<Item = &'a S>, S: AsRef<str> + 'a + ?Sized, { let possibilities: Vec<&str> = possibilities.into_iter().map(|s| s.as_ref()).collect(); let suggestion = crate::lev_distance::find_best_match_for_name_with_substrings(&possibilities, input, None) .map(|s| s.to_string()); if let Some(suggestion) = &suggestion && suggestion.len() == 1 && !suggestion.eq_ignore_ascii_case(input) { return None; } suggestion } #[cfg(test)] mod tests { use super::did_you_mean; #[test] fn did_you_mean_examples() { let all_cases = [ ( vec!["a", "b"], vec![ ("a", Some("a"), ""), ("A", Some("a"), ""), ( "c", None, "Not helpful to suggest an arbitrary choice when none are close", ), ( "ccccccccccccccccccccccc", None, "Not helpful to suggest an arbitrary choice when none are close", ), ], ), ( vec!["OS", "PWD", "PWDPWDPWDPWD"], vec![ ( "pwd", Some("PWD"), "Exact case insensitive match yields a match", ), ( "pwdpwdpwdpwd", Some("PWDPWDPWDPWD"), "Exact case insensitive match yields a match", ), ("PWF", Some("PWD"), "One-letter typo yields a match"), ("pwf", None, "Case difference plus typo yields no match"), ( "Xwdpwdpwdpwd", None, "Case difference plus typo yields no match", ), ], ), ( vec!["foo", "bar", "baz"], vec![ ("fox", Some("foo"), ""), ("FOO", Some("foo"), ""), ("FOX", None, ""), ( "ccc", None, "Not helpful to suggest an arbitrary choice when none are close", ), ( "zzz", None, "'baz' does share a character, but rustc rule is edit distance must be <= 1/3 of the length of the user input", ), ], ), ( vec!["aaaaaa"], vec![ ( "XXaaaa", Some("aaaaaa"), "Distance of 2 out of 6 chars: close enough to meet rustc's rule", ), ( "XXXaaa", None, "Distance of 3 out of 6 chars: not close enough to meet rustc's rule", ), ( "XaaaaX", Some("aaaaaa"), "Distance of 2 out of 6 chars: close enough to meet rustc's rule", ), ( "XXaaaaXX", None, "Distance of 4 out of 6 chars: not close enough to meet rustc's rule", ), ], ), ]; for (possibilities, cases) in all_cases { for (input, expected_suggestion, discussion) in cases { let suggestion = did_you_mean(&possibilities, input); assert_eq!( suggestion.as_deref(), expected_suggestion, "Expected the following reasoning to hold but it did not: '{discussion}'" ); } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/syntax_shape.rs
crates/nu-protocol/src/syntax_shape.rs
use crate::Type; use serde::{Deserialize, Serialize}; use std::fmt::Display; /// The syntactic shapes that describe how a sequence should be parsed. /// /// This extends beyond [`Type`] which describes how [`Value`](crate::Value)s are represented. /// `SyntaxShape`s can describe the parsing rules for arguments to a command. /// e.g. [`SyntaxShape::GlobPattern`]/[`SyntaxShape::Filepath`] serve the completer, /// but don't have an associated [`Value`](crate::Value) /// There are additional `SyntaxShape`s that only make sense in particular expressions or keywords #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum SyntaxShape { /// Any syntactic form is allowed Any, /// A binary literal Binary, /// A block is allowed, eg `{start this thing}` Block, /// A boolean value, eg `true` or `false` Boolean, /// A dotted path to navigate the table CellPath, /// A closure is allowed, eg `{|| start this thing}` Closure(Option<Vec<SyntaxShape>>), /// A datetime value, eg `2022-02-02` or `2019-10-12T07:20:50.52+00:00` DateTime, /// A directory is allowed Directory, /// A duration value is allowed, eg `19day` Duration, /// An error value Error, /// A general expression, eg `1 + 2` or `foo --bar` Expression, /// A (typically) string argument that follows external command argument parsing rules. /// /// Filepaths are expanded if unquoted, globs are allowed, and quotes embedded within unknown /// args are unquoted. ExternalArgument, /// A filepath is allowed Filepath, /// A filesize value is allowed, eg `10kb` Filesize, /// A floating point value, eg `1.0` Float, /// A dotted path including the variable to access items /// /// Fully qualified FullCellPath, /// A glob pattern is allowed, eg `foo*` GlobPattern, /// Only an integer value is allowed Int, /// A module path pattern used for imports ImportPattern, /// A specific match to a word or symbol Keyword(Vec<u8>, Box<SyntaxShape>), /// A list is allowed, eg `[first second]` List(Box<SyntaxShape>), /// A general math expression, eg `1 + 2` MathExpression, /// A block of matches, used by `match` MatchBlock, /// Nothing Nothing, /// Only a numeric (integer or float) value is allowed Number, /// One of a list of possible items, checked in order OneOf(Vec<SyntaxShape>), /// An operator, eg `+` Operator, /// A range is allowed (eg, `1..3`) Range, /// A record value, eg `{x: 1, y: 2}` Record(Vec<(String, SyntaxShape)>), /// A math expression which expands shorthand forms on the lefthand side, eg `foo > 1` /// The shorthand allows us to more easily reach columns inside of the row being passed in RowCondition, /// A signature for a definition, `[x:int, --foo]` Signature, /// Strings and string-like bare words are allowed String, /// A table is allowed, eg `[[first, second]; [1, 2]]` Table(Vec<(String, SyntaxShape)>), /// A variable with optional type, `x` or `x: int` VarWithOptType, } impl SyntaxShape { /// If possible provide the associated concrete [`Type`] /// /// Note: Some [`SyntaxShape`]s don't have a corresponding [`Value`](crate::Value) /// Here we currently return [`Type::Any`] /// /// ```rust /// use nu_protocol::{SyntaxShape, Type}; /// let non_value = SyntaxShape::ImportPattern; /// assert_eq!(non_value.to_type(), Type::Any); /// ``` pub fn to_type(&self) -> Type { let mk_ty = |tys: &[(String, SyntaxShape)]| { tys.iter() .map(|(key, val)| (key.clone(), val.to_type())) .collect() }; match self { SyntaxShape::Any => Type::Any, SyntaxShape::Block => Type::Block, SyntaxShape::Closure(_) => Type::Closure, SyntaxShape::Binary => Type::Binary, SyntaxShape::CellPath => Type::CellPath, SyntaxShape::DateTime => Type::Date, SyntaxShape::Duration => Type::Duration, SyntaxShape::Expression => Type::Any, SyntaxShape::ExternalArgument => Type::Any, SyntaxShape::Filepath => Type::String, SyntaxShape::Directory => Type::String, SyntaxShape::Float => Type::Float, SyntaxShape::Filesize => Type::Filesize, SyntaxShape::FullCellPath => Type::Any, SyntaxShape::GlobPattern => Type::Glob, SyntaxShape::Error => Type::Error, SyntaxShape::ImportPattern => Type::Any, SyntaxShape::Int => Type::Int, SyntaxShape::List(x) => { let contents = x.to_type(); Type::List(Box::new(contents)) } SyntaxShape::Keyword(_, expr) => expr.to_type(), SyntaxShape::MatchBlock => Type::Any, SyntaxShape::MathExpression => Type::Any, SyntaxShape::Nothing => Type::Nothing, SyntaxShape::Number => Type::Number, SyntaxShape::OneOf(types) => Type::one_of(types.iter().map(SyntaxShape::to_type)), SyntaxShape::Operator => Type::Any, SyntaxShape::Range => Type::Range, SyntaxShape::Record(entries) => Type::Record(mk_ty(entries)), SyntaxShape::RowCondition => Type::Bool, SyntaxShape::Boolean => Type::Bool, SyntaxShape::Signature => Type::Any, SyntaxShape::String => Type::String, SyntaxShape::Table(columns) => Type::Table(mk_ty(columns)), SyntaxShape::VarWithOptType => Type::Any, } } } impl Display for SyntaxShape { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mk_fmt = |tys: &[(String, SyntaxShape)]| -> String { tys.iter() .map(|(x, y)| format!("{x}: {y}")) .collect::<Vec<String>>() .join(", ") }; match self { SyntaxShape::Keyword(kw, shape) => { write!(f, "\"{}\" {}", String::from_utf8_lossy(kw), shape) } SyntaxShape::Any => write!(f, "any"), SyntaxShape::String => write!(f, "string"), SyntaxShape::CellPath => write!(f, "cell-path"), SyntaxShape::FullCellPath => write!(f, "cell-path"), SyntaxShape::Number => write!(f, "number"), SyntaxShape::Range => write!(f, "range"), SyntaxShape::Int => write!(f, "int"), SyntaxShape::Float => write!(f, "float"), SyntaxShape::Filepath => write!(f, "path"), SyntaxShape::Directory => write!(f, "directory"), SyntaxShape::GlobPattern => write!(f, "glob"), SyntaxShape::ImportPattern => write!(f, "import"), SyntaxShape::Block => write!(f, "block"), SyntaxShape::Closure(args) => { if let Some(args) = args { let arg_vec: Vec<_> = args.iter().map(|x| x.to_string()).collect(); let arg_string = arg_vec.join(", "); write!(f, "closure({arg_string})") } else { write!(f, "closure()") } } SyntaxShape::Binary => write!(f, "binary"), SyntaxShape::List(x) => write!(f, "list<{x}>"), SyntaxShape::Table(columns) => { if columns.is_empty() { write!(f, "table") } else { write!(f, "table<{}>", mk_fmt(columns)) } } SyntaxShape::Record(entries) => { if entries.is_empty() { write!(f, "record") } else { write!(f, "record<{}>", mk_fmt(entries)) } } SyntaxShape::Filesize => write!(f, "filesize"), SyntaxShape::Duration => write!(f, "duration"), SyntaxShape::DateTime => write!(f, "datetime"), SyntaxShape::Operator => write!(f, "operator"), SyntaxShape::RowCondition => write!( f, "oneof<condition, {}>", SyntaxShape::Closure(Some(vec![SyntaxShape::Any])) ), SyntaxShape::MathExpression => write!(f, "variable"), SyntaxShape::VarWithOptType => write!(f, "vardecl"), SyntaxShape::Signature => write!(f, "signature"), SyntaxShape::MatchBlock => write!(f, "match-block"), SyntaxShape::Expression => write!(f, "expression"), SyntaxShape::ExternalArgument => write!(f, "external-argument"), SyntaxShape::Boolean => write!(f, "bool"), SyntaxShape::Error => write!(f, "error"), SyntaxShape::OneOf(list) => { write!(f, "oneof")?; let [first, rest @ ..] = &**list else { return Ok(()); }; write!(f, "<{first}")?; for t in rest { write!(f, ", {t}")?; } f.write_str(">") } SyntaxShape::Nothing => write!(f, "nothing"), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/process/mod.rs
crates/nu-protocol/src/process/mod.rs
//! Handling of external subprocesses mod child; pub use child::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/process/child.rs
crates/nu-protocol/src/process/child.rs
use crate::{ ShellError, Span, byte_stream::convert_file, engine::{EngineState, FrozenJob, Job}, shell_error::io::IoError, }; use nu_system::{ExitStatus, ForegroundChild, ForegroundWaitStatus}; use os_pipe::PipeReader; use std::{ fmt::Debug, io::{self, Read}, sync::mpsc::{self, Receiver, RecvError, TryRecvError}, sync::{Arc, Mutex}, thread, }; /// Check the exit status of each pipeline element. /// /// This is used to implement pipefail. #[cfg(feature = "os")] pub fn check_exit_status_future( exit_status: Vec<Option<(Arc<Mutex<ExitStatusFuture>>, Span)>>, ) -> Result<(), ShellError> { for (future, span) in exit_status.into_iter().rev().flatten() { check_exit_status_future_ok(future, span)? } Ok(()) } fn check_exit_status_future_ok( exit_status_future: Arc<Mutex<ExitStatusFuture>>, span: Span, ) -> Result<(), ShellError> { let mut future = exit_status_future .lock() .expect("lock exit_status_future should success"); let exit_status = future.wait(span)?; check_ok(exit_status, false, span) } pub fn check_ok(status: ExitStatus, ignore_error: bool, span: Span) -> Result<(), ShellError> { match status { ExitStatus::Exited(exit_code) => { if ignore_error { Ok(()) } else if let Ok(exit_code) = exit_code.try_into() { Err(ShellError::NonZeroExitCode { exit_code, span }) } else { Ok(()) } } #[cfg(unix)] ExitStatus::Signaled { signal, core_dumped, } => { use nix::sys::signal::Signal; let sig = Signal::try_from(signal); if sig == Ok(Signal::SIGPIPE) || (ignore_error && !core_dumped) { // Processes often exit with SIGPIPE, but this is not an error condition. Ok(()) } else { let signal_name = sig.map(Signal::as_str).unwrap_or("unknown signal").into(); Err(if core_dumped { ShellError::CoreDumped { signal_name, signal, span, } } else { ShellError::TerminatedBySignal { signal_name, signal, span, } }) } } } } #[derive(Debug)] pub enum ExitStatusFuture { Finished(Result<ExitStatus, Box<ShellError>>), Running(Receiver<io::Result<ExitStatus>>), } impl ExitStatusFuture { pub fn wait(&mut self, span: Span) -> Result<ExitStatus, ShellError> { match self { ExitStatusFuture::Finished(Ok(status)) => Ok(*status), ExitStatusFuture::Finished(Err(err)) => Err(err.as_ref().clone()), ExitStatusFuture::Running(receiver) => { let code = match receiver.recv() { #[cfg(unix)] Ok(Ok( status @ ExitStatus::Signaled { core_dumped: true, .. }, )) => { check_ok(status, false, span)?; Ok(status) } Ok(Ok(status)) => Ok(status), Ok(Err(err)) => Err(ShellError::Io(IoError::new_with_additional_context( err, span, None, "failed to get exit code", ))), Err(err @ RecvError) => Err(ShellError::GenericError { error: err.to_string(), msg: "failed to get exit code".into(), span: span.into(), help: None, inner: vec![], }), }; *self = ExitStatusFuture::Finished(code.clone().map_err(Box::new)); code } } } fn try_wait(&mut self, span: Span) -> Result<Option<ExitStatus>, ShellError> { match self { ExitStatusFuture::Finished(Ok(code)) => Ok(Some(*code)), ExitStatusFuture::Finished(Err(err)) => Err(err.as_ref().clone()), ExitStatusFuture::Running(receiver) => { let code = match receiver.try_recv() { Ok(Ok(status)) => Ok(Some(status)), Ok(Err(err)) => Err(ShellError::GenericError { error: err.to_string(), msg: "failed to get exit code".to_string(), span: span.into(), help: None, inner: vec![], }), Err(TryRecvError::Disconnected) => Err(ShellError::GenericError { error: "receiver disconnected".to_string(), msg: "failed to get exit code".into(), span: span.into(), help: None, inner: vec![], }), Err(TryRecvError::Empty) => Ok(None), }; if let Some(code) = code.clone().transpose() { *self = ExitStatusFuture::Finished(code.map_err(Box::new)); } code } } } } pub enum ChildPipe { Pipe(PipeReader), Tee(Box<dyn Read + Send + 'static>), } impl Debug for ChildPipe { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ChildPipe").finish() } } impl From<PipeReader> for ChildPipe { fn from(pipe: PipeReader) -> Self { Self::Pipe(pipe) } } impl Read for ChildPipe { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { match self { ChildPipe::Pipe(pipe) => pipe.read(buf), ChildPipe::Tee(tee) => tee.read(buf), } } } #[derive(Debug)] pub struct ChildProcess { pub stdout: Option<ChildPipe>, pub stderr: Option<ChildPipe>, exit_status: Arc<Mutex<ExitStatusFuture>>, ignore_error: bool, span: Span, } /// A wrapper for a closure that runs once the shell finishes waiting on the process. pub struct PostWaitCallback(pub Box<dyn FnOnce(ForegroundWaitStatus) + Send>); impl PostWaitCallback { pub fn new<F>(f: F) -> Self where F: FnOnce(ForegroundWaitStatus) + Send + 'static, { PostWaitCallback(Box::new(f)) } /// Creates a PostWaitCallback that creates a frozen job in the job table /// if the incoming wait status indicates that the job was frozen. /// /// If `child_pid` is provided, the returned callback will also remove /// it from the pid list of the current running job. /// /// The given `tag` argument will be used as the tag for the newly created job table entry. pub fn for_job_control( engine_state: &EngineState, child_pid: Option<u32>, tag: Option<String>, ) -> Self { let this_job = engine_state.current_thread_job().cloned(); let jobs = engine_state.jobs.clone(); let is_interactive = engine_state.is_interactive; PostWaitCallback::new(move |status| { if let (Some(this_job), Some(child_pid)) = (this_job, child_pid) { this_job.remove_pid(child_pid); } if let ForegroundWaitStatus::Frozen(unfreeze) = status { let mut jobs = jobs.lock().expect("jobs lock is poisoned!"); let job_id = jobs.add_job(Job::Frozen(FrozenJob { unfreeze, tag })); if is_interactive { println!("\nJob {} is frozen", job_id.get()); } } }) } } impl Debug for PostWaitCallback { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "<wait_callback>") } } impl ChildProcess { pub fn new( mut child: ForegroundChild, reader: Option<PipeReader>, swap: bool, span: Span, callback: Option<PostWaitCallback>, ) -> Result<Self, ShellError> { let (stdout, stderr) = if let Some(combined) = reader { (Some(combined), None) } else { let stdout = child.as_mut().stdout.take().map(convert_file); let stderr = child.as_mut().stderr.take().map(convert_file); if swap { (stderr, stdout) } else { (stdout, stderr) } }; // Create a thread to wait for the exit status. let (exit_status_sender, exit_status) = mpsc::channel(); thread::Builder::new() .name("exit status waiter".into()) .spawn(move || { let matched = match child.wait() { // there are two possible outcomes when we `wait` for a process to finish: // 1. the process finishes as usual // 2. (unix only) the process gets signaled with SIGTSTP // // in the second case, although the process may still be alive in a // cryonic state, we explicitly treat as it has finished with exit code 0 // for the sake of the current pipeline Ok(wait_status) => { let next = match &wait_status { ForegroundWaitStatus::Frozen(_) => ExitStatus::Exited(0), ForegroundWaitStatus::Finished(exit_status) => *exit_status, }; if let Some(callback) = callback { (callback.0)(wait_status); } Ok(next) } Err(err) => Err(err), }; exit_status_sender.send(matched) }) .map_err(|err| { IoError::new_with_additional_context( err, span, None, "Could now spawn exit status waiter", ) })?; Ok(Self::from_raw(stdout, stderr, Some(exit_status), span)) } pub fn from_raw( stdout: Option<PipeReader>, stderr: Option<PipeReader>, exit_status: Option<Receiver<io::Result<ExitStatus>>>, span: Span, ) -> Self { Self { stdout: stdout.map(Into::into), stderr: stderr.map(Into::into), exit_status: Arc::new(Mutex::new( exit_status .map(ExitStatusFuture::Running) .unwrap_or(ExitStatusFuture::Finished(Ok(ExitStatus::Exited(0)))), )), ignore_error: false, span, } } pub fn ignore_error(&mut self, ignore: bool) -> &mut Self { self.ignore_error = ignore; self } pub fn span(&self) -> Span { self.span } pub fn into_bytes(self) -> Result<Vec<u8>, ShellError> { if self.stderr.is_some() { debug_assert!(false, "stderr should not exist"); return Err(ShellError::GenericError { error: "internal error".into(), msg: "stderr should not exist".into(), span: self.span.into(), help: None, inner: vec![], }); } let bytes = if let Some(stdout) = self.stdout { collect_bytes(stdout).map_err(|err| IoError::new(err, self.span, None))? } else { Vec::new() }; let mut exit_status = self .exit_status .lock() .expect("lock exit_status future should success"); check_ok(exit_status.wait(self.span)?, self.ignore_error, self.span)?; Ok(bytes) } pub fn wait(mut self) -> Result<(), ShellError> { let from_io_error = IoError::factory(self.span, None); if let Some(stdout) = self.stdout.take() { let stderr = self .stderr .take() .map(|stderr| { thread::Builder::new() .name("stderr consumer".into()) .spawn(move || consume_pipe(stderr)) }) .transpose() .map_err(&from_io_error)?; let res = consume_pipe(stdout); if let Some(handle) = stderr { handle .join() .map_err(|e| match e.downcast::<io::Error>() { Ok(io) => from_io_error(*io).into(), Err(err) => ShellError::GenericError { error: "Unknown error".into(), msg: format!("{err:?}"), span: Some(self.span), help: None, inner: Vec::new(), }, })? .map_err(&from_io_error)?; } res.map_err(&from_io_error)?; } else if let Some(stderr) = self.stderr.take() { consume_pipe(stderr).map_err(&from_io_error)?; } let mut exit_status = self .exit_status .lock() .expect("lock exit_status future should success"); check_ok(exit_status.wait(self.span)?, self.ignore_error, self.span) } pub fn try_wait(&mut self) -> Result<Option<ExitStatus>, ShellError> { let mut exit_status = self .exit_status .lock() .expect("lock exit_status future should success"); exit_status.try_wait(self.span) } pub fn wait_with_output(self) -> Result<ProcessOutput, ShellError> { let from_io_error = IoError::factory(self.span, None); let (stdout, stderr) = if let Some(stdout) = self.stdout { let stderr = self .stderr .map(|stderr| thread::Builder::new().spawn(move || collect_bytes(stderr))) .transpose() .map_err(&from_io_error)?; let stdout = collect_bytes(stdout).map_err(&from_io_error)?; let stderr = stderr .map(|handle| { handle.join().map_err(|e| match e.downcast::<io::Error>() { Ok(io) => from_io_error(*io).into(), Err(err) => ShellError::GenericError { error: "Unknown error".into(), msg: format!("{err:?}"), span: Some(self.span), help: None, inner: Vec::new(), }, }) }) .transpose()? .transpose() .map_err(&from_io_error)?; (Some(stdout), stderr) } else { let stderr = self .stderr .map(collect_bytes) .transpose() .map_err(&from_io_error)?; (None, stderr) }; let mut exit_status = self .exit_status .lock() .expect("lock exit_status future should success"); let exit_status = exit_status.wait(self.span)?; Ok(ProcessOutput { stdout, stderr, exit_status, }) } pub fn clone_exit_status_future(&self) -> Arc<Mutex<ExitStatusFuture>> { self.exit_status.clone() } } fn collect_bytes(pipe: ChildPipe) -> io::Result<Vec<u8>> { let mut buf = Vec::new(); match pipe { ChildPipe::Pipe(mut pipe) => pipe.read_to_end(&mut buf), ChildPipe::Tee(mut tee) => tee.read_to_end(&mut buf), }?; Ok(buf) } fn consume_pipe(pipe: ChildPipe) -> io::Result<()> { match pipe { ChildPipe::Pipe(mut pipe) => io::copy(&mut pipe, &mut io::sink()), ChildPipe::Tee(mut tee) => io::copy(&mut tee, &mut io::sink()), }?; Ok(()) } pub struct ProcessOutput { pub stdout: Option<Vec<u8>>, pub stderr: Option<Vec<u8>>, pub exit_status: ExitStatus, }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/plugin/signature.rs
crates/nu-protocol/src/plugin/signature.rs
use crate::{PluginExample, Signature}; use serde::{Deserialize, Serialize}; /// A simple wrapper for Signature that includes examples. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PluginSignature { pub sig: Signature, pub examples: Vec<PluginExample>, } impl PluginSignature { pub fn new(sig: Signature, examples: Vec<PluginExample>) -> Self { Self { sig, examples } } /// Build an internal signature with default help option pub fn build(name: impl Into<String>) -> PluginSignature { let sig = Signature::new(name.into()).add_help(); Self::new(sig, vec![]) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/plugin/registered.rs
crates/nu-protocol/src/plugin/registered.rs
use std::{any::Any, sync::Arc}; use crate::{Handlers, PluginGcConfig, PluginIdentity, PluginMetadata, ShellError}; /// Trait for plugins registered in the [`EngineState`](crate::engine::EngineState). pub trait RegisteredPlugin: Send + Sync { /// The identity of the plugin - its filename, shell, and friendly name. fn identity(&self) -> &PluginIdentity; /// True if the plugin is currently running. fn is_running(&self) -> bool; /// Process ID of the plugin executable, if running. fn pid(&self) -> Option<u32>; /// Get metadata for the plugin, if set. fn metadata(&self) -> Option<PluginMetadata>; /// Set metadata for the plugin. fn set_metadata(&self, metadata: Option<PluginMetadata>); /// Set garbage collection config for the plugin. fn set_gc_config(&self, gc_config: &PluginGcConfig); /// Stop the plugin. fn stop(&self) -> Result<(), ShellError>; /// Stop the plugin and reset any state so that we don't make any assumptions about the plugin /// next time it launches. This is used on `plugin add`. fn reset(&self) -> Result<(), ShellError>; /// Cast the pointer to an [`Any`] so that its concrete type can be retrieved. /// /// This is necessary in order to allow `nu_plugin` to handle the implementation details of /// plugins. fn as_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>; /// Give this plugin a chance to register for Ctrl-C signals. fn configure_signal_handler(self: Arc<Self>, _handler: &Handlers) -> Result<(), ShellError> { Ok(()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/plugin/mod.rs
crates/nu-protocol/src/plugin/mod.rs
mod identity; mod metadata; mod registered; mod registry_file; mod signature; pub use identity::*; pub use metadata::*; pub use registered::*; pub use registry_file::*; pub use signature::*;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/plugin/identity.rs
crates/nu-protocol/src/plugin/identity.rs
use std::path::{Path, PathBuf}; use crate::{ParseError, ShellError, Spanned}; /// Error when an invalid plugin filename was encountered. #[derive(Debug, Clone)] pub struct InvalidPluginFilename(PathBuf); impl std::fmt::Display for InvalidPluginFilename { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("invalid plugin filename") } } impl From<Spanned<InvalidPluginFilename>> for ParseError { fn from(error: Spanned<InvalidPluginFilename>) -> ParseError { ParseError::LabeledError( "Invalid plugin filename".into(), "must start with `nu_plugin_`".into(), error.span, ) } } impl From<Spanned<InvalidPluginFilename>> for ShellError { fn from(error: Spanned<InvalidPluginFilename>) -> ShellError { ShellError::GenericError { error: format!("Invalid plugin filename: {}", error.item.0.display()), msg: "not a valid plugin filename".into(), span: Some(error.span), help: Some("valid Nushell plugin filenames must start with `nu_plugin_`".into()), inner: vec![], } } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct PluginIdentity { /// The filename used to start the plugin filename: PathBuf, /// The shell used to start the plugin, if required shell: Option<PathBuf>, /// The friendly name of the plugin (e.g. `inc` for `C:\nu_plugin_inc.exe`) name: String, } impl PluginIdentity { /// Create a new plugin identity from a path to plugin executable and shell option. /// /// The `filename` must be an absolute path. Canonicalize before trying to construct the /// [`PluginIdentity`]. pub fn new( filename: impl Into<PathBuf>, shell: Option<PathBuf>, ) -> Result<PluginIdentity, InvalidPluginFilename> { let filename: PathBuf = filename.into(); // Must pass absolute path. if filename.is_relative() { return Err(InvalidPluginFilename(filename)); } let name = filename .file_stem() .map(|stem| stem.to_string_lossy().into_owned()) .and_then(|stem| stem.strip_prefix("nu_plugin_").map(|s| s.to_owned())) .ok_or_else(|| InvalidPluginFilename(filename.clone()))?; Ok(PluginIdentity { filename, shell, name, }) } /// The filename of the plugin executable. pub fn filename(&self) -> &Path { &self.filename } /// The shell command used by the plugin. pub fn shell(&self) -> Option<&Path> { self.shell.as_deref() } /// The name of the plugin, determined by the part of the filename after `nu_plugin_` excluding /// the extension. /// /// - `C:\nu_plugin_inc.exe` becomes `inc` /// - `/home/nu/.cargo/bin/nu_plugin_inc` becomes `inc` pub fn name(&self) -> &str { &self.name } /// Create a fake identity for testing. #[cfg(windows)] #[doc(hidden)] pub fn new_fake(name: &str) -> PluginIdentity { PluginIdentity::new(format!(r"C:\fake\path\nu_plugin_{name}.exe"), None) .expect("fake plugin identity path is invalid") } /// Create a fake identity for testing. #[cfg(not(windows))] #[doc(hidden)] pub fn new_fake(name: &str) -> PluginIdentity { PluginIdentity::new(format!(r"/fake/path/nu_plugin_{name}"), None) .expect("fake plugin identity path is invalid") } /// A command that could be used to add the plugin, for suggesting in errors. pub fn add_command(&self) -> String { if let Some(shell) = self.shell() { format!( "plugin add --shell '{}' '{}'", shell.display(), self.filename().display(), ) } else { format!("plugin add '{}'", self.filename().display()) } } /// A command that could be used to reload the plugin, for suggesting in errors. pub fn use_command(&self) -> String { format!("plugin use '{}'", self.name()) } } #[test] fn parses_name_from_path() { assert_eq!("test", PluginIdentity::new_fake("test").name()); assert_eq!("test_2", PluginIdentity::new_fake("test_2").name()); let absolute_path = if cfg!(windows) { r"C:\path\to\nu_plugin_foo.sh" } else { "/path/to/nu_plugin_foo.sh" }; assert_eq!( "foo", PluginIdentity::new(absolute_path, Some("sh".into())) .expect("should be valid") .name() ); // Relative paths should be invalid PluginIdentity::new("nu_plugin_foo.sh", Some("sh".into())).expect_err("should be invalid"); PluginIdentity::new("other", None).expect_err("should be invalid"); PluginIdentity::new("", None).expect_err("should be invalid"); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/plugin/metadata.rs
crates/nu-protocol/src/plugin/metadata.rs
use serde::{Deserialize, Serialize}; /// Metadata about the installed plugin. This is cached in the registry file along with the /// signatures. None of the metadata fields are required, and more may be added in the future. #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] #[non_exhaustive] pub struct PluginMetadata { /// The version of the plugin itself, as self-reported. pub version: Option<String>, } impl PluginMetadata { /// Create empty metadata. pub const fn new() -> PluginMetadata { PluginMetadata { version: None } } /// Set the version of the plugin on the metadata. A suggested way to construct this is: /// /// ```no_run /// # use nu_protocol::PluginMetadata; /// # fn example() -> PluginMetadata { /// PluginMetadata::new().with_version(env!("CARGO_PKG_VERSION")) /// # } /// ``` /// /// which will use the version of your plugin's crate from its `Cargo.toml` file. pub fn with_version(mut self, version: impl Into<String>) -> Self { self.version = Some(version.into()); self } } impl Default for PluginMetadata { fn default() -> Self { Self::new() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/plugin/registry_file/tests.rs
crates/nu-protocol/src/plugin/registry_file/tests.rs
use super::{PluginRegistryFile, PluginRegistryItem, PluginRegistryItemData}; use crate::{ Category, PluginExample, PluginMetadata, PluginSignature, ShellError, Signature, SyntaxShape, Type, Value, }; use pretty_assertions::assert_eq; use std::io::Cursor; fn foo_plugin() -> PluginRegistryItem { PluginRegistryItem { name: "foo".into(), filename: "/path/to/nu_plugin_foo".into(), shell: None, data: PluginRegistryItemData::Valid { metadata: PluginMetadata { version: Some("0.1.0".into()), }, commands: vec![PluginSignature { sig: Signature::new("foo") .input_output_type(Type::Int, Type::List(Box::new(Type::Int))) .category(Category::Experimental), examples: vec![PluginExample { example: "16 | foo".into(), description: "powers of two up to 16".into(), result: Some(Value::test_list(vec![ Value::test_int(2), Value::test_int(4), Value::test_int(8), Value::test_int(16), ])), }], }], }, } } fn bar_plugin() -> PluginRegistryItem { PluginRegistryItem { name: "bar".into(), filename: "/path/to/nu_plugin_bar".into(), shell: None, data: PluginRegistryItemData::Valid { metadata: PluginMetadata { version: Some("0.2.0".into()), }, commands: vec![PluginSignature { sig: Signature::new("bar") .description("overwrites files with random data") .switch("force", "ignore errors", Some('f')) .required( "path", SyntaxShape::Filepath, "file to overwrite with random data", ) .category(Category::Experimental), examples: vec![], }], }, } } #[test] fn roundtrip() -> Result<(), ShellError> { let mut plugin_registry_file = PluginRegistryFile { nushell_version: env!("CARGO_PKG_VERSION").to_owned(), plugins: vec![foo_plugin(), bar_plugin()], }; let mut output = vec![]; plugin_registry_file.write_to(&mut output, None)?; let read_file = PluginRegistryFile::read_from(Cursor::new(&output[..]), None)?; assert_eq!(plugin_registry_file, read_file); Ok(()) } #[test] fn roundtrip_invalid() -> Result<(), ShellError> { let mut plugin_registry_file = PluginRegistryFile { nushell_version: env!("CARGO_PKG_VERSION").to_owned(), plugins: vec![PluginRegistryItem { name: "invalid".into(), filename: "/path/to/nu_plugin_invalid".into(), shell: None, data: PluginRegistryItemData::Invalid, }], }; let mut output = vec![]; plugin_registry_file.write_to(&mut output, None)?; let read_file = PluginRegistryFile::read_from(Cursor::new(&output[..]), None)?; assert_eq!(plugin_registry_file, read_file); Ok(()) } #[test] fn upsert_new() { let mut file = PluginRegistryFile::new(); file.plugins.push(foo_plugin()); file.upsert_plugin(bar_plugin()); assert_eq!(2, file.plugins.len()); } #[test] fn upsert_replace() { let mut file = PluginRegistryFile::new(); file.plugins.push(foo_plugin()); let mut mutated_foo = foo_plugin(); mutated_foo.shell = Some("/bin/sh".into()); file.upsert_plugin(mutated_foo); assert_eq!(1, file.plugins.len()); assert_eq!(Some("/bin/sh".into()), file.plugins[0].shell); }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/plugin/registry_file/mod.rs
crates/nu-protocol/src/plugin/registry_file/mod.rs
use std::{ io::{Read, Write}, path::PathBuf, }; use serde::{Deserialize, Serialize}; use crate::{PluginIdentity, PluginMetadata, PluginSignature, ShellError, Span}; // This has a big impact on performance const BUFFER_SIZE: usize = 65536; // Chose settings at the low end, because we're just trying to get the maximum speed const COMPRESSION_QUALITY: u32 = 3; // 1 can be very bad const WIN_SIZE: u32 = 20; // recommended 20-22 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PluginRegistryFile { /// The Nushell version that last updated the file. pub nushell_version: String, /// The installed plugins. pub plugins: Vec<PluginRegistryItem>, } impl Default for PluginRegistryFile { fn default() -> Self { Self::new() } } impl PluginRegistryFile { /// Create a new, empty plugin registry file. pub fn new() -> PluginRegistryFile { PluginRegistryFile { nushell_version: env!("CARGO_PKG_VERSION").to_owned(), plugins: vec![], } } /// Read the plugin registry file from a reader, e.g. [`File`](std::fs::File). pub fn read_from( reader: impl Read, error_span: Option<Span>, ) -> Result<PluginRegistryFile, ShellError> { // Format is brotli compressed messagepack let brotli_reader = brotli::Decompressor::new(reader, BUFFER_SIZE); rmp_serde::from_read(brotli_reader).map_err(|err| ShellError::GenericError { error: format!("Failed to load plugin file: {err}"), msg: "plugin file load attempted here".into(), span: error_span, help: Some( "it may be corrupt. Try deleting it and registering your plugins again".into(), ), inner: vec![], }) } /// Write the plugin registry file to a writer, e.g. [`File`](std::fs::File). /// /// The `nushell_version` will be updated to the current version before writing. pub fn write_to( &mut self, writer: impl Write, error_span: Option<Span>, ) -> Result<(), ShellError> { // Update the Nushell version before writing env!("CARGO_PKG_VERSION").clone_into(&mut self.nushell_version); // Format is brotli compressed messagepack let mut brotli_writer = brotli::CompressorWriter::new(writer, BUFFER_SIZE, COMPRESSION_QUALITY, WIN_SIZE); rmp_serde::encode::write_named(&mut brotli_writer, self) .map_err(|err| err.to_string()) .and_then(|_| brotli_writer.flush().map_err(|err| err.to_string())) .map_err(|err| ShellError::GenericError { error: "Failed to save plugin file".into(), msg: "plugin file save attempted here".into(), span: error_span, help: Some(err.to_string()), inner: vec![], }) } /// Insert or update a plugin in the plugin registry file. pub fn upsert_plugin(&mut self, item: PluginRegistryItem) { if let Some(existing_item) = self.plugins.iter_mut().find(|p| p.name == item.name) { *existing_item = item; } else { self.plugins.push(item); // Sort the plugins for consistency self.plugins .sort_by(|item1, item2| item1.name.cmp(&item2.name)); } } } /// A single plugin definition from a [`PluginRegistryFile`]. /// /// Contains the information necessary for the [`PluginIdentity`], as well as possibly valid data /// about the plugin including the registered command signatures. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PluginRegistryItem { /// The name of the plugin, as would show in `plugin list`. This does not include the file /// extension or the `nu_plugin_` prefix. pub name: String, /// The path to the file. pub filename: PathBuf, /// The shell program used to run the plugin, if applicable. pub shell: Option<PathBuf>, /// Additional data that might be invalid so that we don't fail to load the whole plugin file /// if there's a deserialization error. #[serde(flatten)] pub data: PluginRegistryItemData, } impl PluginRegistryItem { /// Create a [`PluginRegistryItem`] from an identity, metadata, and signatures. pub fn new( identity: &PluginIdentity, metadata: PluginMetadata, mut commands: Vec<PluginSignature>, ) -> PluginRegistryItem { // Sort the commands for consistency commands.sort_by(|cmd1, cmd2| cmd1.sig.name.cmp(&cmd2.sig.name)); PluginRegistryItem { name: identity.name().to_owned(), filename: identity.filename().to_owned(), shell: identity.shell().map(|p| p.to_owned()), data: PluginRegistryItemData::Valid { metadata, commands }, } } } /// Possibly valid data about a plugin in a [`PluginRegistryFile`]. If deserialization fails, it will /// be `Invalid`. #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum PluginRegistryItemData { Valid { /// Metadata for the plugin, including its version. #[serde(default)] metadata: PluginMetadata, /// Signatures and examples for each command provided by the plugin. commands: Vec<PluginSignature>, }, #[serde( serialize_with = "serialize_invalid", deserialize_with = "deserialize_invalid" )] Invalid, } fn serialize_invalid<S>(serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { ().serialize(serializer) } fn deserialize_invalid<'de, D>(deserializer: D) -> Result<(), D::Error> where D: serde::Deserializer<'de>, { serde::de::IgnoredAny::deserialize(deserializer)?; Ok(()) } #[cfg(test)] mod tests;
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ir/call.rs
crates/nu-protocol/src/ir/call.rs
use std::sync::Arc; use crate::{ DeclId, ShellError, Span, Spanned, Value, ast::Expression, engine::{self, Argument, Stack}, }; use super::DataSlice; /// Contains the information for a call being made to a declared command. #[derive(Debug, Clone)] pub struct Call { /// The declaration ID of the command to be invoked. pub decl_id: DeclId, /// The span encompassing the command name, before the arguments. pub head: Span, /// The span encompassing the command name and all arguments. pub span: Span, /// The base index of the arguments for this call within the /// [argument stack](crate::engine::ArgumentStack). pub args_base: usize, /// The number of [`Argument`]s for the call. Note that this just counts the number of /// `Argument` entries on the stack, and has nothing to do with the actual number of positional /// or spread arguments. pub args_len: usize, } impl Call { /// Build a new call with arguments. pub fn build(decl_id: DeclId, head: Span) -> CallBuilder { CallBuilder { inner: Call { decl_id, head, span: head, args_base: 0, args_len: 0, }, } } /// Get the arguments for this call from the arguments stack. pub fn arguments<'a>(&self, stack: &'a Stack) -> &'a [Argument] { stack.arguments.get_args(self.args_base, self.args_len) } /// The span encompassing the arguments /// /// If there are no arguments the span covers where the first argument would exist /// /// If there are one or more arguments the span encompasses the start of the first argument to /// end of the last argument pub fn arguments_span(&self) -> Span { let past = self.head.past(); Span::new(past.start, self.span.end) } /// The number of named arguments, with or without values. pub fn named_len(&self, stack: &Stack) -> usize { self.arguments(stack) .iter() .filter(|arg| matches!(arg, Argument::Named { .. } | Argument::Flag { .. })) .count() } /// Iterate through named arguments, with or without values. pub fn named_iter<'a>( &'a self, stack: &'a Stack, ) -> impl Iterator<Item = (Spanned<&'a str>, Option<&'a Value>)> + 'a { self.arguments(stack).iter().filter_map( |arg: &Argument| -> Option<(Spanned<&str>, Option<&Value>)> { match arg { Argument::Flag { data, name, span, .. } => Some(( Spanned { item: std::str::from_utf8(&data[*name]).expect("invalid arg name"), span: *span, }, None, )), Argument::Named { data, name, span, val, .. } => Some(( Spanned { item: std::str::from_utf8(&data[*name]).expect("invalid arg name"), span: *span, }, Some(val), )), _ => None, } }, ) } /// Get a named argument's value by name. Returns [`None`] for named arguments with no value as /// well. pub fn get_named_arg<'a>(&self, stack: &'a Stack, flag_name: &str) -> Option<&'a Value> { // Optimized to avoid str::from_utf8() self.arguments(stack) .iter() .find_map(|arg: &Argument| -> Option<Option<&Value>> { match arg { Argument::Flag { data, name, .. } if &data[*name] == flag_name.as_bytes() => { Some(None) } Argument::Named { data, name, val, .. } if &data[*name] == flag_name.as_bytes() => Some(Some(val)), _ => None, } }) .flatten() } /// The number of positional arguments, excluding spread arguments. pub fn positional_len(&self, stack: &Stack) -> usize { self.arguments(stack) .iter() .filter(|arg| matches!(arg, Argument::Positional { .. })) .count() } /// Iterate through positional arguments. Does not include spread arguments. pub fn positional_iter<'a>(&self, stack: &'a Stack) -> impl Iterator<Item = &'a Value> { self.arguments(stack).iter().filter_map(|arg| match arg { Argument::Positional { val, .. } => Some(val), _ => None, }) } /// Get a positional argument by index. Does not include spread arguments. pub fn positional_nth<'a>(&self, stack: &'a Stack, index: usize) -> Option<&'a Value> { self.positional_iter(stack).nth(index) } /// Get the AST node for a positional argument by index. Not usually available unless the decl /// required it. pub fn positional_ast<'a>( &self, stack: &'a Stack, index: usize, ) -> Option<&'a Arc<Expression>> { self.arguments(stack) .iter() .filter_map(|arg| match arg { Argument::Positional { ast, .. } => Some(ast), _ => None, }) .nth(index) .and_then(|option| option.as_ref()) } /// Returns every argument to the rest parameter, as well as whether each argument /// is spread or a normal positional argument (true for spread, false for normal) pub fn rest_iter<'a>( &self, stack: &'a Stack, start: usize, ) -> impl Iterator<Item = (&'a Value, bool)> + 'a { self.arguments(stack) .iter() .filter_map(|arg| match arg { Argument::Positional { val, .. } => Some((val, false)), Argument::Spread { vals, .. } => Some((vals, true)), _ => None, }) .skip(start) } /// Returns all of the positional arguments including and after `start`, with spread arguments /// flattened into a single `Vec`. pub fn rest_iter_flattened( &self, stack: &Stack, start: usize, ) -> Result<Vec<Value>, ShellError> { let mut acc = vec![]; for (rest_val, spread) in self.rest_iter(stack, start) { if spread { match rest_val { Value::List { vals, .. } => acc.extend(vals.iter().cloned()), Value::Nothing { .. } => (), Value::Error { error, .. } => return Err(ShellError::clone(error)), _ => { return Err(ShellError::CannotSpreadAsList { span: rest_val.span(), }); } } } else { acc.push(rest_val.clone()); } } Ok(acc) } /// Get a parser info argument by name. pub fn get_parser_info<'a>(&self, stack: &'a Stack, name: &str) -> Option<&'a Expression> { self.arguments(stack) .iter() .find_map(|argument| match argument { Argument::ParserInfo { data, name: name_slice, info: expr, } if &data[*name_slice] == name.as_bytes() => Some(expr.as_ref()), _ => None, }) } /// Returns a span encompassing the entire call. pub fn span(&self) -> Span { self.span } /// Resets the [`Stack`] to its state before the call was made. pub fn leave(&self, stack: &mut Stack) { stack.arguments.leave_frame(self.args_base); } } /// Utility struct for building a [`Call`] with arguments on the [`Stack`]. pub struct CallBuilder { inner: Call, } impl CallBuilder { /// Add an argument to the [`Stack`] and reference it from the [`Call`]. pub fn add_argument(&mut self, stack: &mut Stack, argument: Argument) -> &mut Self { if self.inner.args_len == 0 { self.inner.args_base = stack.arguments.get_base(); } self.inner.args_len += 1; if let Some(span) = argument.span() { self.inner.span = self.inner.span.merge(span); } stack.arguments.push(argument); self } /// Add a positional argument to the [`Stack`] and reference it from the [`Call`]. pub fn add_positional(&mut self, stack: &mut Stack, span: Span, val: Value) -> &mut Self { self.add_argument( stack, Argument::Positional { span, val, ast: None, }, ) } /// Add a spread argument to the [`Stack`] and reference it from the [`Call`]. pub fn add_spread(&mut self, stack: &mut Stack, span: Span, vals: Value) -> &mut Self { self.add_argument( stack, Argument::Spread { span, vals, ast: None, }, ) } /// Add a flag (no-value named) argument to the [`Stack`] and reference it from the [`Call`]. pub fn add_flag( &mut self, stack: &mut Stack, name: impl AsRef<str>, short: impl AsRef<str>, span: Span, ) -> &mut Self { let (data, name, short) = data_from_name_and_short(name.as_ref(), short.as_ref()); self.add_argument( stack, Argument::Flag { data, name, short, span, }, ) } /// Add a named argument to the [`Stack`] and reference it from the [`Call`]. pub fn add_named( &mut self, stack: &mut Stack, name: impl AsRef<str>, short: impl AsRef<str>, span: Span, val: Value, ) -> &mut Self { let (data, name, short) = data_from_name_and_short(name.as_ref(), short.as_ref()); self.add_argument( stack, Argument::Named { data, name, short, span, val, ast: None, }, ) } /// Produce the finished [`Call`] from the builder. /// /// The call should be entered / run before any other calls are constructed, because the /// argument stack will be reset when they exit. pub fn finish(&self) -> Call { self.inner.clone() } /// Run a closure with the [`Call`] as an [`engine::Call`] reference, and then clean up the /// arguments that were added to the [`Stack`] after. /// /// For convenience. Calls [`Call::leave`] after the closure ends. pub fn with<T>( self, stack: &mut Stack, f: impl FnOnce(&mut Stack, &engine::Call<'_>) -> T, ) -> T { let call = engine::Call::from(&self.inner); let result = f(stack, &call); self.inner.leave(stack); result } } fn data_from_name_and_short(name: &str, short: &str) -> (Arc<[u8]>, DataSlice, DataSlice) { let data: Vec<u8> = name.bytes().chain(short.bytes()).collect(); let data: Arc<[u8]> = data.into(); let name = DataSlice { start: 0, len: name.len().try_into().expect("flag name too big"), }; let short = DataSlice { start: name.start.checked_add(name.len).expect("flag name too big"), len: short.len().try_into().expect("flag short name too big"), }; (data, name, short) }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ir/display.rs
crates/nu-protocol/src/ir/display.rs
use super::{DataSlice, Instruction, IrBlock, Literal, RedirectMode}; use crate::{DeclId, VarId, ast::Pattern, engine::EngineState}; use std::fmt::{self}; pub struct FmtIrBlock<'a> { pub(super) engine_state: &'a EngineState, pub(super) ir_block: &'a IrBlock, } impl fmt::Display for FmtIrBlock<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let plural = |count| if count == 1 { "" } else { "s" }; writeln!( f, "# {} register{}, {} instruction{}, {} byte{} of data", self.ir_block.register_count, plural(self.ir_block.register_count as usize), self.ir_block.instructions.len(), plural(self.ir_block.instructions.len()), self.ir_block.data.len(), plural(self.ir_block.data.len()), )?; if self.ir_block.file_count > 0 { writeln!( f, "# {} file{} used for redirection", self.ir_block.file_count, plural(self.ir_block.file_count as usize) )?; } for (index, instruction) in self.ir_block.instructions.iter().enumerate() { let formatted = format!( "{:-4}: {}", index, FmtInstruction { engine_state: self.engine_state, instruction, data: &self.ir_block.data, } ); let comment = &self.ir_block.comments[index]; if comment.is_empty() { writeln!(f, "{formatted}")?; } else { writeln!(f, "{formatted:40} # {comment}")?; } } Ok(()) } } pub struct FmtInstruction<'a> { pub(super) engine_state: &'a EngineState, pub(super) instruction: &'a Instruction, pub(super) data: &'a [u8], } impl fmt::Display for FmtInstruction<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { const WIDTH: usize = 22; match self.instruction { Instruction::Unreachable => { write!(f, "{:WIDTH$}", "unreachable") } Instruction::LoadLiteral { dst, lit } => { let lit = FmtLiteral { literal: lit, data: self.data, }; write!(f, "{:WIDTH$} {dst}, {lit}", "load-literal") } Instruction::LoadValue { dst, val } => { let val = val.to_debug_string(); write!(f, "{:WIDTH$} {dst}, {val}", "load-value") } Instruction::Move { dst, src } => { write!(f, "{:WIDTH$} {dst}, {src}", "move") } Instruction::Clone { dst, src } => { write!(f, "{:WIDTH$} {dst}, {src}", "clone") } Instruction::Collect { src_dst } => { write!(f, "{:WIDTH$} {src_dst}", "collect") } Instruction::Span { src_dst } => { write!(f, "{:WIDTH$} {src_dst}", "span") } Instruction::Drop { src } => { write!(f, "{:WIDTH$} {src}", "drop") } Instruction::Drain { src } => { write!(f, "{:WIDTH$} {src}", "drain") } Instruction::DrainIfEnd { src } => { write!(f, "{:WIDTH$} {src}", "drain-if-end") } Instruction::LoadVariable { dst, var_id } => { let var = FmtVar::new(self.engine_state, *var_id); write!(f, "{:WIDTH$} {dst}, {var}", "load-variable") } Instruction::StoreVariable { var_id, src } => { let var = FmtVar::new(self.engine_state, *var_id); write!(f, "{:WIDTH$} {var}, {src}", "store-variable") } Instruction::DropVariable { var_id } => { let var = FmtVar::new(self.engine_state, *var_id); write!(f, "{:WIDTH$} {var}", "drop-variable") } Instruction::LoadEnv { dst, key } => { let key = FmtData(self.data, *key); write!(f, "{:WIDTH$} {dst}, {key}", "load-env") } Instruction::LoadEnvOpt { dst, key } => { let key = FmtData(self.data, *key); write!(f, "{:WIDTH$} {dst}, {key}", "load-env-opt") } Instruction::StoreEnv { key, src } => { let key = FmtData(self.data, *key); write!(f, "{:WIDTH$} {key}, {src}", "store-env") } Instruction::PushPositional { src } => { write!(f, "{:WIDTH$} {src}", "push-positional") } Instruction::AppendRest { src } => { write!(f, "{:WIDTH$} {src}", "append-rest") } Instruction::PushFlag { name } => { let name = FmtData(self.data, *name); write!(f, "{:WIDTH$} {name}", "push-flag") } Instruction::PushShortFlag { short } => { let short = FmtData(self.data, *short); write!(f, "{:WIDTH$} {short}", "push-short-flag") } Instruction::PushNamed { name, src } => { let name = FmtData(self.data, *name); write!(f, "{:WIDTH$} {name}, {src}", "push-named") } Instruction::PushShortNamed { short, src } => { let short = FmtData(self.data, *short); write!(f, "{:WIDTH$} {short}, {src}", "push-short-named") } Instruction::PushParserInfo { name, info } => { let name = FmtData(self.data, *name); write!(f, "{:WIDTH$} {name}, {info:?}", "push-parser-info") } Instruction::RedirectOut { mode } => { write!(f, "{:WIDTH$} {mode}", "redirect-out") } Instruction::RedirectErr { mode } => { write!(f, "{:WIDTH$} {mode}", "redirect-err") } Instruction::CheckErrRedirected { src } => { write!(f, "{:WIDTH$} {src}", "check-err-redirected") } Instruction::OpenFile { file_num, path, append, } => { write!( f, "{:WIDTH$} file({file_num}), {path}, append = {append:?}", "open-file" ) } Instruction::WriteFile { file_num, src } => { write!(f, "{:WIDTH$} file({file_num}), {src}", "write-file") } Instruction::CloseFile { file_num } => { write!(f, "{:WIDTH$} file({file_num})", "close-file") } Instruction::Call { decl_id, src_dst } => { let decl = FmtDecl::new(self.engine_state, *decl_id); write!(f, "{:WIDTH$} {decl}, {src_dst}", "call") } Instruction::StringAppend { src_dst, val } => { write!(f, "{:WIDTH$} {src_dst}, {val}", "string-append") } Instruction::GlobFrom { src_dst, no_expand } => { let no_expand = if *no_expand { "no-expand" } else { "expand" }; write!(f, "{:WIDTH$} {src_dst}, {no_expand}", "glob-from",) } Instruction::ListPush { src_dst, item } => { write!(f, "{:WIDTH$} {src_dst}, {item}", "list-push") } Instruction::ListSpread { src_dst, items } => { write!(f, "{:WIDTH$} {src_dst}, {items}", "list-spread") } Instruction::RecordInsert { src_dst, key, val } => { write!(f, "{:WIDTH$} {src_dst}, {key}, {val}", "record-insert") } Instruction::RecordSpread { src_dst, items } => { write!(f, "{:WIDTH$} {src_dst}, {items}", "record-spread") } Instruction::Not { src_dst } => { write!(f, "{:WIDTH$} {src_dst}", "not") } Instruction::BinaryOp { lhs_dst, op, rhs } => { write!(f, "{:WIDTH$} {lhs_dst}, {op:?}, {rhs}", "binary-op") } Instruction::FollowCellPath { src_dst, path } => { write!(f, "{:WIDTH$} {src_dst}, {path}", "follow-cell-path") } Instruction::CloneCellPath { dst, src, path } => { write!(f, "{:WIDTH$} {dst}, {src}, {path}", "clone-cell-path") } Instruction::UpsertCellPath { src_dst, path, new_value, } => { write!( f, "{:WIDTH$} {src_dst}, {path}, {new_value}", "upsert-cell-path" ) } Instruction::Jump { index } => { write!(f, "{:WIDTH$} {index}", "jump") } Instruction::BranchIf { cond, index } => { write!(f, "{:WIDTH$} {cond}, {index}", "branch-if") } Instruction::BranchIfEmpty { src, index } => { write!(f, "{:WIDTH$} {src}, {index}", "branch-if-empty") } Instruction::Match { pattern, src, index, } => { let pattern = FmtPattern { engine_state: self.engine_state, pattern, }; write!(f, "{:WIDTH$} ({pattern}), {src}, {index}", "match") } Instruction::CheckMatchGuard { src } => { write!(f, "{:WIDTH$} {src}", "check-match-guard") } Instruction::Iterate { dst, stream, end_index, } => { write!(f, "{:WIDTH$} {dst}, {stream}, end {end_index}", "iterate") } Instruction::OnError { index } => { write!(f, "{:WIDTH$} {index}", "on-error") } Instruction::OnErrorInto { index, dst } => { write!(f, "{:WIDTH$} {index}, {dst}", "on-error-into") } Instruction::PopErrorHandler => { write!(f, "{:WIDTH$}", "pop-error-handler") } Instruction::ReturnEarly { src } => { write!(f, "{:WIDTH$} {src}", "return-early") } Instruction::Return { src } => { write!(f, "{:WIDTH$} {src}", "return") } } } } struct FmtDecl<'a>(DeclId, &'a str); impl<'a> FmtDecl<'a> { fn new(engine_state: &'a EngineState, decl_id: DeclId) -> Self { FmtDecl(decl_id, engine_state.get_decl(decl_id).name()) } } impl fmt::Display for FmtDecl<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "decl {} {:?}", self.0.get(), self.1) } } struct FmtVar<'a>(VarId, Option<&'a str>); impl<'a> FmtVar<'a> { fn new(engine_state: &'a EngineState, var_id: VarId) -> Self { // Search for the name of the variable let name: Option<&str> = engine_state .active_overlays(&[]) .flat_map(|overlay| overlay.vars.iter()) .find(|(_, v)| **v == var_id) .map(|(k, _)| std::str::from_utf8(k).unwrap_or("<utf-8 error>")); FmtVar(var_id, name) } } impl fmt::Display for FmtVar<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(name) = self.1 { write!(f, "var {} {:?}", self.0.get(), name) } else { write!(f, "var {}", self.0.get()) } } } impl fmt::Display for RedirectMode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { RedirectMode::Pipe => write!(f, "pipe"), RedirectMode::PipeSeparate => write!(f, "pipe separate"), RedirectMode::Value => write!(f, "value"), RedirectMode::Null => write!(f, "null"), RedirectMode::Inherit => write!(f, "inherit"), RedirectMode::Print => write!(f, "print"), RedirectMode::File { file_num } => write!(f, "file({file_num})"), RedirectMode::Caller => write!(f, "caller"), } } } struct FmtData<'a>(&'a [u8], DataSlice); impl fmt::Display for FmtData<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Ok(s) = std::str::from_utf8(&self.0[self.1]) { // Write as string write!(f, "{s:?}") } else { // Write as byte array write!(f, "0x{:x?}", self.0) } } } struct FmtLiteral<'a> { literal: &'a Literal, data: &'a [u8], } impl fmt::Display for FmtLiteral<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.literal { Literal::Bool(b) => write!(f, "bool({b:?})"), Literal::Int(i) => write!(f, "int({i:?})"), Literal::Float(fl) => write!(f, "float({fl:?})"), Literal::Filesize(q) => write!(f, "filesize({q}b)"), Literal::Duration(q) => write!(f, "duration({q}ns)"), Literal::Binary(b) => write!(f, "binary({})", FmtData(self.data, *b)), Literal::Block(id) => write!(f, "block({})", id.get()), Literal::Closure(id) => write!(f, "closure({})", id.get()), Literal::RowCondition(id) => write!(f, "row_condition({})", id.get()), Literal::Range { start, step, end, inclusion, } => write!(f, "range({start}, {step}, {end}, {inclusion:?})"), Literal::List { capacity } => write!(f, "list(capacity = {capacity})"), Literal::Record { capacity } => write!(f, "record(capacity = {capacity})"), Literal::Filepath { val, no_expand } => write!( f, "filepath({}, no_expand = {no_expand:?})", FmtData(self.data, *val) ), Literal::Directory { val, no_expand } => write!( f, "directory({}, no_expand = {no_expand:?})", FmtData(self.data, *val) ), Literal::GlobPattern { val, no_expand } => write!( f, "glob-pattern({}, no_expand = {no_expand:?})", FmtData(self.data, *val) ), Literal::String(s) => write!(f, "string({})", FmtData(self.data, *s)), Literal::RawString(rs) => write!(f, "raw-string({})", FmtData(self.data, *rs)), Literal::CellPath(p) => write!(f, "cell-path({p})"), Literal::Date(dt) => write!(f, "date({dt})"), Literal::Nothing => write!(f, "nothing"), } } } struct FmtPattern<'a> { engine_state: &'a EngineState, pattern: &'a Pattern, } impl fmt::Display for FmtPattern<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.pattern { Pattern::Record(bindings) => { f.write_str("{")?; for (name, pattern) in bindings { write!( f, "{}: {}", name, FmtPattern { engine_state: self.engine_state, pattern: &pattern.pattern, } )?; } f.write_str("}") } Pattern::List(bindings) => { f.write_str("[")?; for pattern in bindings { write!( f, "{}", FmtPattern { engine_state: self.engine_state, pattern: &pattern.pattern } )?; } f.write_str("]") } Pattern::Expression(expr) => { let string = String::from_utf8_lossy(self.engine_state.get_span_contents(expr.span)); f.write_str(&string) } Pattern::Value(value) => { f.write_str(&value.to_parsable_string(", ", &self.engine_state.config)) } Pattern::Variable(var_id) => { let variable = FmtVar::new(self.engine_state, *var_id); write!(f, "{variable}") } Pattern::Or(patterns) => { for (index, pattern) in patterns.iter().enumerate() { if index > 0 { f.write_str(" | ")?; } write!( f, "{}", FmtPattern { engine_state: self.engine_state, pattern: &pattern.pattern } )?; } Ok(()) } Pattern::Rest(var_id) => { let variable = FmtVar::new(self.engine_state, *var_id); write!(f, "..{variable}") } Pattern::IgnoreRest => f.write_str(".."), Pattern::IgnoreValue => f.write_str("_"), Pattern::Garbage => f.write_str("<garbage>"), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/ir/mod.rs
crates/nu-protocol/src/ir/mod.rs
use crate::{ BlockId, DeclId, Filesize, RegId, ShellError, Span, Value, VarId, ast::{CellPath, Expression, Operator, Pattern, RangeInclusion}, engine::EngineState, }; use chrono::{DateTime, FixedOffset}; use serde::{Deserialize, Serialize}; use std::{fmt, sync::Arc}; mod call; mod display; pub use call::*; pub use display::{FmtInstruction, FmtIrBlock}; #[derive(Clone, Serialize, Deserialize)] pub struct IrBlock { pub instructions: Vec<Instruction>, pub spans: Vec<Span>, #[serde(with = "serde_arc_u8_array")] pub data: Arc<[u8]>, pub ast: Vec<Option<IrAstRef>>, /// Additional information that can be added to help with debugging pub comments: Vec<Box<str>>, pub register_count: u32, pub file_count: u32, } impl fmt::Debug for IrBlock { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // the ast field is too verbose and doesn't add much f.debug_struct("IrBlock") .field("instructions", &self.instructions) .field("spans", &self.spans) .field("data", &self.data) .field("comments", &self.comments) .field("register_count", &self.register_count) .field("file_count", &self.file_count) .finish_non_exhaustive() } } impl IrBlock { /// Returns a value that can be formatted with [`Display`](std::fmt::Display) to show a detailed /// listing of the instructions contained within this [`IrBlock`]. pub fn display<'a>(&'a self, engine_state: &'a EngineState) -> FmtIrBlock<'a> { FmtIrBlock { engine_state, ir_block: self, } } } /// A slice into the `data` array of a block. This is a compact and cache-friendly way to store /// string data that a block uses. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct DataSlice { pub start: u32, pub len: u32, } impl DataSlice { /// A data slice that contains no data. This slice is always valid. pub const fn empty() -> DataSlice { DataSlice { start: 0, len: 0 } } } impl std::ops::Index<DataSlice> for [u8] { type Output = [u8]; fn index(&self, index: DataSlice) -> &Self::Output { &self[index.start as usize..(index.start as usize + index.len as usize)] } } /// A possible reference into the abstract syntax tree for an instruction. This is not present for /// most instructions and is just added when needed. #[derive(Debug, Clone)] pub struct IrAstRef(pub Arc<Expression>); impl Serialize for IrAstRef { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.as_ref().serialize(serializer) } } impl<'de> Deserialize<'de> for IrAstRef { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Expression::deserialize(deserializer).map(|expr| IrAstRef(Arc::new(expr))) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Instruction { /// Unreachable code path (error) Unreachable, /// Load a literal value into the `dst` register LoadLiteral { dst: RegId, lit: Literal }, /// Load a clone of a boxed value into the `dst` register (e.g. from const evaluation) LoadValue { dst: RegId, val: Box<Value> }, /// Move a register. Value is taken from `src` (used by this instruction). Move { dst: RegId, src: RegId }, /// Copy a register (must be a collected value). Value is still in `src` after this instruction. Clone { dst: RegId, src: RegId }, /// Collect a stream in a register to a value Collect { src_dst: RegId }, /// Change the span of the contents of a register to the span of this instruction. Span { src_dst: RegId }, /// Drop the value/stream in a register, without draining Drop { src: RegId }, /// Drain the value/stream in a register and discard (e.g. semicolon). /// /// If passed a stream from an external command, sets $env.LAST_EXIT_CODE to the resulting exit /// code, and invokes any available error handler with Empty, or if not available, returns an /// exit-code-only stream, leaving the block. Drain { src: RegId }, /// Drain the value/stream in a register and discard only if this is the last pipeline element. // TODO: see if it's possible to remove this DrainIfEnd { src: RegId }, /// Load the value of a variable into the `dst` register LoadVariable { dst: RegId, var_id: VarId }, /// Store the value of a variable from the `src` register StoreVariable { var_id: VarId, src: RegId }, /// Remove a variable from the stack, freeing up whatever resources were associated with it DropVariable { var_id: VarId }, /// Load the value of an environment variable into the `dst` register LoadEnv { dst: RegId, key: DataSlice }, /// Load the value of an environment variable into the `dst` register, or `Nothing` if it /// doesn't exist LoadEnvOpt { dst: RegId, key: DataSlice }, /// Store the value of an environment variable from the `src` register StoreEnv { key: DataSlice, src: RegId }, /// Add a positional arg to the next (internal) call. PushPositional { src: RegId }, /// Add a list of args to the next (internal) call (spread/rest). AppendRest { src: RegId }, /// Add a named arg with no value to the next (internal) call. PushFlag { name: DataSlice }, /// Add a short named arg with no value to the next (internal) call. PushShortFlag { short: DataSlice }, /// Add a named arg with a value to the next (internal) call. PushNamed { name: DataSlice, src: RegId }, /// Add a short named arg with a value to the next (internal) call. PushShortNamed { short: DataSlice, src: RegId }, /// Add parser info to the next (internal) call. PushParserInfo { name: DataSlice, info: Box<Expression>, }, /// Set the redirection for stdout for the next call (only). /// /// The register for a file redirection is not consumed. RedirectOut { mode: RedirectMode }, /// Set the redirection for stderr for the next call (only). /// /// The register for a file redirection is not consumed. RedirectErr { mode: RedirectMode }, /// Throw an error if stderr wasn't redirected in the given stream. `src` is preserved. CheckErrRedirected { src: RegId }, /// Open a file for redirection, pushing it onto the file stack. OpenFile { file_num: u32, path: RegId, append: bool, }, /// Write data from the register to a file. This is done to finish a file redirection, in case /// an internal command or expression was evaluated rather than an external one. WriteFile { file_num: u32, src: RegId }, /// Pop a file used for redirection from the file stack. CloseFile { file_num: u32 }, /// Make a call. The input is taken from `src_dst`, and the output is placed in `src_dst`, /// overwriting it. The argument stack is used implicitly and cleared when the call ends. Call { decl_id: DeclId, src_dst: RegId }, /// Append a value onto the end of a string. Uses `to_expanded_string(", ", ...)` on the value. /// Used for string interpolation literals. Not the same thing as the `++` operator. StringAppend { src_dst: RegId, val: RegId }, /// Convert a string into a glob. Used for glob interpolation and setting glob variables. If the /// value is already a glob, it won't be modified (`no_expand` will have no effect). GlobFrom { src_dst: RegId, no_expand: bool }, /// Push a value onto the end of a list. Used to construct list literals. ListPush { src_dst: RegId, item: RegId }, /// Spread a value onto the end of a list. Used to construct list literals. ListSpread { src_dst: RegId, items: RegId }, /// Insert a key-value pair into a record. Used to construct record literals. Raises an error if /// the key already existed in the record. RecordInsert { src_dst: RegId, key: RegId, val: RegId, }, /// Spread a record onto a record. Used to construct record literals. Any existing value for the /// key is overwritten. RecordSpread { src_dst: RegId, items: RegId }, /// Negate a boolean. Not { src_dst: RegId }, /// Do a binary operation on `lhs_dst` (left) and `rhs` (right) and write the result to /// `lhs_dst`. BinaryOp { lhs_dst: RegId, op: Operator, rhs: RegId, }, /// Follow a cell path on the value in `src_dst`, storing the result back to `src_dst` FollowCellPath { src_dst: RegId, path: RegId }, /// Clone the value at a cell path in `src`, storing the result to `dst`. The original value /// remains in `src`. Must be a collected value. CloneCellPath { dst: RegId, src: RegId, path: RegId }, /// Update/insert a cell path to `new_value` on the value in `src_dst`, storing the modified /// value back to `src_dst` UpsertCellPath { src_dst: RegId, path: RegId, new_value: RegId, }, /// Jump to an offset in this block Jump { index: usize }, /// Branch to an offset in this block if the value of the `cond` register is a true boolean, /// otherwise continue execution BranchIf { cond: RegId, index: usize }, /// Branch to an offset in this block if the value of the `src` register is Empty or Nothing, /// otherwise continue execution. The original value in `src` is preserved. BranchIfEmpty { src: RegId, index: usize }, /// Match a pattern on `src`. If the pattern matches, branch to `index` after having set any /// variables captured by the pattern. If the pattern doesn't match, continue execution. The /// original value is preserved in `src` through this instruction. Match { pattern: Box<Pattern>, src: RegId, index: usize, }, /// Check that a match guard is a boolean, throwing /// [`MatchGuardNotBool`](crate::ShellError::MatchGuardNotBool) if it isn't. Preserves `src`. CheckMatchGuard { src: RegId }, /// Iterate on register `stream`, putting the next value in `dst` if present, or jumping to /// `end_index` if the iterator is finished Iterate { dst: RegId, stream: RegId, end_index: usize, }, /// Push an error handler, without capturing the error value OnError { index: usize }, /// Push an error handler, capturing the error value into `dst`. If the error handler is not /// called, the register should be freed manually. OnErrorInto { index: usize, dst: RegId }, /// Pop an error handler. This is not necessary when control flow is directed to the error /// handler due to an error. PopErrorHandler, /// Return early from the block, raising a `ShellError::Return` instead. /// /// Collecting the value is unavoidable. ReturnEarly { src: RegId }, /// Return from the block with the value in the register Return { src: RegId }, } impl Instruction { /// Returns a value that can be formatted with [`Display`](std::fmt::Display) to show a detailed /// listing of the instruction. pub fn display<'a>( &'a self, engine_state: &'a EngineState, data: &'a [u8], ) -> FmtInstruction<'a> { FmtInstruction { engine_state, instruction: self, data, } } /// Get the output register, for instructions that produce some kind of immediate result. pub fn output_register(&self) -> Option<RegId> { match *self { Instruction::Unreachable => None, Instruction::LoadLiteral { dst, .. } => Some(dst), Instruction::LoadValue { dst, .. } => Some(dst), Instruction::Move { dst, .. } => Some(dst), Instruction::Clone { dst, .. } => Some(dst), Instruction::Collect { src_dst } => Some(src_dst), Instruction::Span { src_dst } => Some(src_dst), Instruction::Drop { .. } => None, Instruction::Drain { .. } => None, Instruction::DrainIfEnd { .. } => None, Instruction::LoadVariable { dst, .. } => Some(dst), Instruction::StoreVariable { .. } => None, Instruction::DropVariable { .. } => None, Instruction::LoadEnv { dst, .. } => Some(dst), Instruction::LoadEnvOpt { dst, .. } => Some(dst), Instruction::StoreEnv { .. } => None, Instruction::PushPositional { .. } => None, Instruction::AppendRest { .. } => None, Instruction::PushFlag { .. } => None, Instruction::PushShortFlag { .. } => None, Instruction::PushNamed { .. } => None, Instruction::PushShortNamed { .. } => None, Instruction::PushParserInfo { .. } => None, Instruction::RedirectOut { .. } => None, Instruction::RedirectErr { .. } => None, Instruction::CheckErrRedirected { .. } => None, Instruction::OpenFile { .. } => None, Instruction::WriteFile { .. } => None, Instruction::CloseFile { .. } => None, Instruction::Call { src_dst, .. } => Some(src_dst), Instruction::StringAppend { src_dst, .. } => Some(src_dst), Instruction::GlobFrom { src_dst, .. } => Some(src_dst), Instruction::ListPush { src_dst, .. } => Some(src_dst), Instruction::ListSpread { src_dst, .. } => Some(src_dst), Instruction::RecordInsert { src_dst, .. } => Some(src_dst), Instruction::RecordSpread { src_dst, .. } => Some(src_dst), Instruction::Not { src_dst } => Some(src_dst), Instruction::BinaryOp { lhs_dst, .. } => Some(lhs_dst), Instruction::FollowCellPath { src_dst, .. } => Some(src_dst), Instruction::CloneCellPath { dst, .. } => Some(dst), Instruction::UpsertCellPath { src_dst, .. } => Some(src_dst), Instruction::Jump { .. } => None, Instruction::BranchIf { .. } => None, Instruction::BranchIfEmpty { .. } => None, Instruction::Match { .. } => None, Instruction::CheckMatchGuard { .. } => None, Instruction::Iterate { dst, .. } => Some(dst), Instruction::OnError { .. } => None, Instruction::OnErrorInto { .. } => None, Instruction::PopErrorHandler => None, Instruction::ReturnEarly { .. } => None, Instruction::Return { .. } => None, } } /// Returns the branch target index of the instruction if this is a branching instruction. pub fn branch_target(&self) -> Option<usize> { match self { Instruction::Jump { index } => Some(*index), Instruction::BranchIf { cond: _, index } => Some(*index), Instruction::BranchIfEmpty { src: _, index } => Some(*index), Instruction::Match { pattern: _, src: _, index, } => Some(*index), Instruction::Iterate { dst: _, stream: _, end_index, } => Some(*end_index), Instruction::OnError { index } => Some(*index), Instruction::OnErrorInto { index, dst: _ } => Some(*index), _ => None, } } /// Sets the branch target of the instruction if this is a branching instruction. /// /// Returns `Err(target_index)` if it isn't a branching instruction. pub fn set_branch_target(&mut self, target_index: usize) -> Result<(), usize> { match self { Instruction::Jump { index } => *index = target_index, Instruction::BranchIf { cond: _, index } => *index = target_index, Instruction::BranchIfEmpty { src: _, index } => *index = target_index, Instruction::Match { pattern: _, src: _, index, } => *index = target_index, Instruction::Iterate { dst: _, stream: _, end_index, } => *end_index = target_index, Instruction::OnError { index } => *index = target_index, Instruction::OnErrorInto { index, dst: _ } => *index = target_index, _ => return Err(target_index), } Ok(()) } /// Check for an interrupt before certain instructions pub fn check_interrupt( &self, engine_state: &EngineState, span: &Span, ) -> Result<(), ShellError> { match self { Instruction::Jump { .. } | Instruction::Return { .. } => { engine_state.signals().check(span) } _ => Ok(()), } } } // This is to document/enforce the size of `Instruction` in bytes. // We should try to avoid increasing the size of `Instruction`, // and PRs that do so will have to change the number below so that it's noted in review. const _: () = assert!(std::mem::size_of::<Instruction>() <= 24); /// A literal value that can be embedded in an instruction. #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Literal { Bool(bool), Int(i64), Float(f64), Filesize(Filesize), Duration(i64), Binary(DataSlice), Block(BlockId), Closure(BlockId), RowCondition(BlockId), Range { start: RegId, step: RegId, end: RegId, inclusion: RangeInclusion, }, List { capacity: usize, }, Record { capacity: usize, }, Filepath { val: DataSlice, no_expand: bool, }, Directory { val: DataSlice, no_expand: bool, }, GlobPattern { val: DataSlice, no_expand: bool, }, String(DataSlice), RawString(DataSlice), CellPath(Box<CellPath>), Date(Box<DateTime<FixedOffset>>), Nothing, } /// A redirection mode for the next call. See [`OutDest`](crate::OutDest). /// /// This is generated by: /// /// 1. Explicit redirection in a [`PipelineElement`](crate::ast::PipelineElement), or /// 2. The [`pipe_redirection()`](crate::engine::Command::pipe_redirection) of the command being /// piped into. /// /// Not setting it uses the default, determined by [`Stack`](crate::engine::Stack). #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum RedirectMode { Pipe, PipeSeparate, Value, Null, Inherit, Print, /// Use the given numbered file. File { file_num: u32, }, /// Use the redirection mode requested by the caller, for a pre-return call. Caller, } /// Just a hack to allow `Arc<[u8]>` to be serialized and deserialized mod serde_arc_u8_array { use serde::{Deserialize, Serialize}; use std::sync::Arc; pub fn serialize<S>(data: &Arc<[u8]>, ser: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { data.as_ref().serialize(ser) } pub fn deserialize<'de, D>(de: D) -> Result<Arc<[u8]>, D::Error> where D: serde::Deserializer<'de>, { let data: Vec<u8> = Deserialize::deserialize(de)?; Ok(data.into()) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/config.rs
crates/nu-protocol/src/errors/config.rs
use std::hash::Hash; use crate::{ShellError, Span, Type}; use miette::Diagnostic; use thiserror::Error; /// The errors that may occur when updating the config #[derive(Clone, Debug, PartialEq, Error, Diagnostic)] pub enum ConfigError { #[error("Type mismatch at {path}")] #[diagnostic(code(nu::shell::type_mismatch))] TypeMismatch { path: String, expected: Type, actual: Type, #[label = "expected {expected}, but got {actual}"] span: Span, }, #[error("Invalid value for {path}")] #[diagnostic(code(nu::shell::invalid_value))] InvalidValue { path: String, valid: String, actual: String, #[label = "expected {valid}, but got {actual}"] span: Span, }, #[error("Unknown config option: {path}")] #[diagnostic(code(nu::shell::unknown_config_option))] UnknownOption { path: String, #[label("remove this")] span: Span, }, #[error("{path} requires a '{column}' column")] #[diagnostic(code(nu::shell::missing_required_column))] MissingRequiredColumn { path: String, column: &'static str, #[label("has no '{column}' column")] span: Span, }, #[error("{path} is deprecated")] #[diagnostic( code(nu::shell::deprecated_config_option), help("please {suggestion} instead") )] Deprecated { path: String, suggestion: &'static str, #[label("deprecated")] span: Span, }, // TODO: remove this #[error(transparent)] #[diagnostic(transparent)] ShellError(#[from] ShellError), } /// Warnings which don't prevent config from being loaded, but we should inform the user about #[derive(Clone, Debug, PartialEq, Error, Diagnostic)] #[diagnostic(severity(Warning))] pub enum ConfigWarning { #[error("Incompatible options")] #[diagnostic(code(nu::shell::incompatible_options), help("{help}"))] IncompatibleOptions { label: &'static str, #[label = "{label}"] span: Span, help: &'static str, }, } // To keep track of reported warnings impl Hash for ConfigWarning { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { match self { ConfigWarning::IncompatibleOptions { label, help, .. } => { label.hash(state); help.hash(state); } } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/short_handler.rs
crates/nu-protocol/src/errors/short_handler.rs
use std::fmt; use miette::{Diagnostic, ReportHandler}; /// A [`ReportHandler`] that renders errors as plain text without graphics. /// Designed for concise output that typically fits on a single line. #[derive(Debug, Clone)] pub struct ShortReportHandler {} impl ShortReportHandler { pub const fn new() -> Self { Self {} } } impl Default for ShortReportHandler { fn default() -> Self { Self::new() } } impl ShortReportHandler { /// Render a [`Diagnostic`]. This function is meant to be called /// by the toplevel [`ReportHandler`]. fn render_report( &self, f: &mut fmt::Formatter<'_>, diagnostic: &dyn Diagnostic, ) -> fmt::Result { write!(f, "{}: ", diagnostic)?; if let Some(labels) = diagnostic.labels() { let mut labels = labels .into_iter() .filter_map(|span| span.label().map(String::from)) .peekable(); while let Some(label) = labels.next() { let end_char = if labels.peek().is_some() { ", " } else { " " }; write!(f, "{}{}", label, end_char)?; } } if let Some(help) = diagnostic.help() { write!(f, "({})", help)?; } Ok(()) } } impl ReportHandler for ShortReportHandler { fn debug(&self, diagnostic: &dyn Diagnostic, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.render_report(f, diagnostic) } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/shell_warning.rs
crates/nu-protocol/src/errors/shell_warning.rs
use crate::Span; use miette::Diagnostic; use std::hash::Hash; use thiserror::Error; use crate::{ConfigWarning, ReportMode, Reportable}; #[derive(Clone, Debug, Error, Diagnostic)] #[diagnostic(severity(Warning))] pub enum ShellWarning { /// A parse-time deprecation. Indicates that something will be removed in a future release. /// /// Use [`ParseWarning::Deprecated`](crate::ParseWarning::Deprecated) if this is a deprecation /// which is detectable at parse-time. #[error("{dep_type} deprecated.")] #[diagnostic(code(nu::shell::deprecated))] Deprecated { dep_type: String, label: String, #[label("{label}")] span: Span, #[help] help: Option<String>, report_mode: ReportMode, }, /// Warnings reported while updating the config #[error("Encountered {} warnings(s) when updating config", warnings.len())] #[diagnostic(code(nu::shell::invalid_config))] InvalidConfig { #[related] warnings: Vec<ConfigWarning>, }, } impl Reportable for ShellWarning { fn report_mode(&self) -> ReportMode { match self { ShellWarning::Deprecated { report_mode, .. } => *report_mode, ShellWarning::InvalidConfig { .. } => ReportMode::FirstUse, } } } // To keep track of reported warnings impl Hash for ShellWarning { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { match self { ShellWarning::Deprecated { dep_type, label, .. } => { dep_type.hash(state); label.hash(state); } // We always report config warnings, so no hash necessary ShellWarning::InvalidConfig { .. } => (), } } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false
nushell/nushell
https://github.com/nushell/nushell/blob/6d3cb27fa40b324a1168c577aee7f3532a5e157e/crates/nu-protocol/src/errors/report_error.rs
crates/nu-protocol/src/errors/report_error.rs
//! This module manages the step of turning error types into printed error messages //! //! Relies on the `miette` crate for pretty layout use std::hash::{DefaultHasher, Hash, Hasher}; use crate::{ CompileError, Config, ErrorStyle, ParseError, ParseWarning, ShellError, ShellWarning, ShortReportHandler, engine::{EngineState, Stack, StateWorkingSet}, }; use miette::{ LabeledSpan, MietteHandlerOpts, NarratableReportHandler, ReportHandler, RgbColors, Severity, SourceCode, }; use serde::{Deserialize, Serialize}; use thiserror::Error; /// This error exists so that we can defer SourceCode handling. It simply /// forwards most methods, except for `.source_code()`, which we provide. #[derive(Error)] #[error("{diagnostic}")] struct CliError<'src> { stack: Option<&'src Stack>, diagnostic: &'src dyn miette::Diagnostic, working_set: &'src StateWorkingSet<'src>, // error code to use if `diagnostic` doesn't provide one default_code: Option<&'static str>, } impl<'src> CliError<'src> { pub fn new( stack: Option<&'src Stack>, diagnostic: &'src dyn miette::Diagnostic, working_set: &'src StateWorkingSet<'src>, default_code: Option<&'static str>, ) -> Self { CliError { stack, diagnostic, working_set, default_code, } } } /// A bloom-filter like structure to store the hashes of warnings, /// without actually permanently storing the entire warning in memory. /// May rarely result in warnings incorrectly being unreported upon hash collision. #[derive(Default)] pub struct ReportLog(Vec<u64>); /// How a warning/error should be reported #[derive(Debug, Clone, Copy, Serialize, Deserialize)] pub enum ReportMode { FirstUse, EveryUse, } /// For warnings/errors which have a ReportMode that dictates when they are reported pub trait Reportable { fn report_mode(&self) -> ReportMode; } /// Returns true if this warning should be reported fn should_show_reportable<R>(engine_state: &EngineState, reportable: &R) -> bool where R: Reportable + Hash, { match reportable.report_mode() { ReportMode::EveryUse => true, ReportMode::FirstUse => { let mut hasher = DefaultHasher::new(); reportable.hash(&mut hasher); let hash = hasher.finish(); let mut report_log = engine_state .report_log .lock() .expect("report log lock is poisioned"); match report_log.0.contains(&hash) { true => false, false => { report_log.0.push(hash); true } } } } } pub fn format_cli_error( stack: Option<&Stack>, working_set: &StateWorkingSet, error: &dyn miette::Diagnostic, default_code: Option<&'static str>, ) -> String { format!( "Error: {:?}", CliError::new(stack, error, working_set, default_code) ) } pub fn report_shell_error(stack: Option<&Stack>, engine_state: &EngineState, error: &ShellError) { if get_config(stack, engine_state) .display_errors .should_show(error) { let working_set = StateWorkingSet::new(engine_state); report_error(stack, &working_set, error, "nu::shell::error") } } pub fn report_shell_warning( stack: Option<&Stack>, engine_state: &EngineState, warning: &ShellWarning, ) { if should_show_reportable(engine_state, warning) { report_warning( stack, &StateWorkingSet::new(engine_state), warning, "nu::shell::warning", ); } } pub fn report_parse_error( stack: Option<&Stack>, working_set: &StateWorkingSet, error: &ParseError, ) { report_error(stack, working_set, error, "nu::parser::error"); } pub fn report_parse_warning( stack: Option<&Stack>, working_set: &StateWorkingSet, warning: &ParseWarning, ) { if should_show_reportable(working_set.permanent(), warning) { report_warning(stack, working_set, warning, "nu::parser::warning"); } } pub fn report_compile_error( stack: Option<&Stack>, working_set: &StateWorkingSet, error: &CompileError, ) { report_error(stack, working_set, error, "nu::compile::error"); } pub fn report_experimental_option_warning( stack: Option<&Stack>, working_set: &StateWorkingSet, warning: &dyn miette::Diagnostic, ) { report_warning( stack, working_set, warning, "nu::experimental_option::warning", ); } fn report_error( stack: Option<&Stack>, working_set: &StateWorkingSet, error: &dyn miette::Diagnostic, default_code: &'static str, ) { eprintln!( "Error: {:?}", CliError::new(stack, error, working_set, Some(default_code)) ); // reset vt processing, aka ansi because illbehaved externals can break it #[cfg(windows)] { let _ = nu_utils::enable_vt_processing(); } } fn report_warning( stack: Option<&Stack>, working_set: &StateWorkingSet, warning: &dyn miette::Diagnostic, default_code: &'static str, ) { eprintln!( "Warning: {:?}", CliError::new(stack, warning, working_set, Some(default_code)) ); // reset vt processing, aka ansi because illbehaved externals can break it #[cfg(windows)] { let _ = nu_utils::enable_vt_processing(); } } fn get_config<'a>(stack: Option<&'a Stack>, engine_state: &'a EngineState) -> &'a Config { stack .and_then(|s| s.config.as_deref()) .unwrap_or(engine_state.get_config()) } impl std::fmt::Debug for CliError<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let engine_state = self.working_set.permanent(); let config = get_config(self.stack, engine_state); let ansi_support = config.use_ansi_coloring.get(engine_state); let error_style = config.error_style; let miette_handler: Box<dyn ReportHandler> = match error_style { ErrorStyle::Short => Box::new(ShortReportHandler::new()), ErrorStyle::Plain => Box::new(NarratableReportHandler::new()), ErrorStyle::Fancy => Box::new( MietteHandlerOpts::new() // For better support of terminal themes use the ANSI coloring .rgb_colors(RgbColors::Never) // If ansi support is disabled in the config disable the eye-candy .color(ansi_support) .unicode(ansi_support) .terminal_links(ansi_support) .build(), ), }; // Ignore error to prevent format! panics. This can happen if span points at some // inaccessible location, for example by calling `report_error()` with wrong working set. let _ = miette_handler.debug(self, f); Ok(()) } } impl miette::Diagnostic for CliError<'_> { fn code<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> { self.diagnostic.code().or_else(|| { self.default_code .map(|code| Box::new(code) as Box<dyn std::fmt::Display>) }) } fn severity(&self) -> Option<Severity> { self.diagnostic.severity() } fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> { self.diagnostic.help() } fn url<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> { self.diagnostic.url() } fn labels<'a>(&'a self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + 'a>> { self.diagnostic.labels() } // Finally, we redirect the source_code method to our own source. fn source_code(&self) -> Option<&dyn SourceCode> { if let Some(source_code) = self.diagnostic.source_code() { Some(source_code) } else { Some(&self.working_set) } } fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn miette::Diagnostic> + 'a>> { self.diagnostic.related() } fn diagnostic_source(&self) -> Option<&dyn miette::Diagnostic> { self.diagnostic.diagnostic_source() } }
rust
MIT
6d3cb27fa40b324a1168c577aee7f3532a5e157e
2026-01-04T15:32:17.606688Z
false