mirror of
https://github.com/nushell/nushell.git
synced 2026-11-26 03:25:39 +08:00
## Description This follows #18808, #18813, #18967, #19351, #19462 and #19638. Since #19638, commands run only from compiled code. The keyword commands that read the parser's extra data for a call, and `explain`, still evaluated parser expressions with the AST evaluator. This PR moves both off it, deletes the evaluator, and removes the last parser `Expression` from IR. Each phase is its own commit, and the last commit fixes review findings in 6a and 6b. - **Typed parser info (6a).** `Instruction::PushParserInfo` carried a parser `Expression` that `source`, `source-env` and `run` evaluated to get back a block id or a path. It now carries a `ParserInfo` value that the compiler builds once. `source-env` also uses the path the parser found, instead of looking the file up again when it runs. - **`explain` runs no code (5a).** A literal, a constant or a bare variable still shows its value. Any other argument shows its source text and the type the parser gave it. - **AST evaluator deleted (5b).** `eval_expression` and its helpers are gone, 383 of `eval.rs`'s 847 lines. Const evaluation is the only `Eval` implementation left. - **Match guards on the arm (6b).** The guard moves from `MatchPattern`, which every nested pattern carried, to a new `MatchArm { pattern, guard, body }`. Capture discovery, `$in` handling and highlighting all skipped guards before. They visit them now. ## User-facing changes (Release notes) - `explain` no longer evaluates arguments. A literal, a constant or a bare variable shows its value, and anything else shows its source text, so `$r.a` shows `$r.a` instead of `1`. Arguments that used to show an empty name or an error show their source. - `view ir` shows parser info as values such as `block(305)` or `import "assert" ["equal"]` instead of a debug dump. `view ir --json` and `ast --json` change shape for parser info and match arms. - A closure whose match guard reads an outside variable now captures it. `$in` works in a guard, and as a bare `=> $in` arm body inside a closure. All of these used to fail with `Variable not found`. - A match guard inside a closure can no longer read a `mut` variable from outside it, the same rule an `if` condition there already follows. Scripts that did this break. Copy the value into a `let` first. - The REPL and `nu-highlight` color match guards. - `source-env` sets `$env.FILE_PWD` and `$env.CURRENT_FILE` from the file the parser read. They no longer contain `..`, and a `cd` before `source-env` no longer changes them. ## Additional notes
4843 lines
156 KiB
Rust
4843 lines
156 KiB
Rust
use nu_parser::*;
|
|
use nu_protocol::{
|
|
DeclId, FilesizeUnit, ParseError, Signature, Span, SyntaxShape, Type, Unit, Value,
|
|
ast::{Argument, Expr, Expression, ExternalArgument, PathMember, Range, Traverse},
|
|
engine::{Command, EngineState, Stack, StateWorkingSet},
|
|
};
|
|
use rstest::rstest;
|
|
use std::ops::ControlFlow;
|
|
|
|
use mock::{
|
|
Alias, AttrEcho, Const, Def, Extern, IfMocked, Let, LsCustom, LsTest, MatchMocked, Mut,
|
|
ToCustom, Where,
|
|
};
|
|
|
|
fn test_int(
|
|
test_tag: &str, // name of sub-test
|
|
test: &[u8], // input expression
|
|
expected_val: Expr, // (usually Expr::{Int,String, Float}, not ::BinOp...
|
|
expected_err: Option<&str>,
|
|
) // substring in error text
|
|
{
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, test, true);
|
|
|
|
let err = working_set.parse_errors.first();
|
|
|
|
if let Some(err_pat) = expected_err {
|
|
if let Some(parse_err) = err {
|
|
let act_err = format!("{parse_err:?}");
|
|
assert!(
|
|
act_err.contains(err_pat),
|
|
"{test_tag}: expected err to contain {err_pat}, but actual error was {act_err}"
|
|
);
|
|
} else {
|
|
assert!(
|
|
err.is_some(),
|
|
"{test_tag}: expected err containing {err_pat}, but no error returned"
|
|
);
|
|
}
|
|
} else {
|
|
assert!(err.is_none(), "{test_tag}: unexpected error {err:#?}");
|
|
assert_eq!(block.len(), 1, "{test_tag}: result block length > 1");
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(
|
|
pipeline.len(),
|
|
1,
|
|
"{test_tag}: got multiple result expressions, expected 1"
|
|
);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
compare_rhs_binary_op(test_tag, &expected_val, &element.expr.expr);
|
|
}
|
|
}
|
|
|
|
fn compare_rhs_binary_op(
|
|
test_tag: &str,
|
|
expected: &Expr, // the rhs expr we hope to see (::Int, ::Float, not ::B)
|
|
observed: &Expr, // the Expr actually provided: can be ::Int, ::Float, ::String,
|
|
// or ::BinOp (in which case rhs is checked), or ::Call (in which case cmd is checked)
|
|
) {
|
|
match observed {
|
|
Expr::Int(..) | Expr::Float(..) | Expr::String(..) => {
|
|
assert_eq!(
|
|
expected, observed,
|
|
"{test_tag}: Expected: {expected:#?}, observed {observed:#?}"
|
|
);
|
|
}
|
|
Expr::BinaryOp(_, _, e) => {
|
|
let observed_expr = &e.expr;
|
|
// can't pattern match Box<Foo>, but can match the box, then deref in separate statement.
|
|
assert_eq!(
|
|
expected, observed_expr,
|
|
"{test_tag}: Expected: {expected:#?}, observed: {observed:#?}"
|
|
)
|
|
}
|
|
Expr::ExternalCall(e, _) => {
|
|
let observed_expr = &e.expr;
|
|
assert_eq!(
|
|
expected, observed_expr,
|
|
"{test_tag}: Expected: {expected:#?}, observed: {observed_expr:#?}"
|
|
)
|
|
}
|
|
_ => {
|
|
panic!("{test_tag}: Unexpected Expr:: variant returned, observed {observed:#?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
pub fn multi_test_parse_int() {
|
|
struct Test<'a>(&'a str, &'a [u8], Expr, Option<&'a str>);
|
|
|
|
// use test expression of form '0 + x' to force parse() to parse x as numeric.
|
|
// if expression were just 'x', parse() would try other items that would mask the error we're looking for.
|
|
let tests = vec![
|
|
Test("binary literal int", b"0 + 0b0", Expr::Int(0), None),
|
|
Test(
|
|
"binary literal invalid digits",
|
|
b"0 + 0b2",
|
|
Expr::Int(0),
|
|
Some("invalid digits for radix 2"),
|
|
),
|
|
Test("octal literal int", b"0 + 0o1", Expr::Int(1), None),
|
|
Test(
|
|
"octal literal int invalid digits",
|
|
b"0 + 0o8",
|
|
Expr::Int(0),
|
|
Some("invalid digits for radix 8"),
|
|
),
|
|
Test(
|
|
"octal literal int truncated",
|
|
b"0 + 0o",
|
|
Expr::Int(0),
|
|
Some("invalid digits for radix 8"),
|
|
),
|
|
Test("hex literal int", b"0 + 0x2", Expr::Int(2), None),
|
|
Test(
|
|
"hex literal int invalid digits",
|
|
b"0 + 0x0aq",
|
|
Expr::Int(0),
|
|
Some("invalid digits for radix 16"),
|
|
),
|
|
Test(
|
|
"hex literal with 'e' not mistaken for float",
|
|
b"0 + 0x00e0",
|
|
Expr::Int(0xe0),
|
|
None,
|
|
),
|
|
// decimal (rad10) literal is anything that starts with
|
|
// optional sign then a digit.
|
|
Test("rad10 literal int", b"0 + 42", Expr::Int(42), None),
|
|
Test(
|
|
"rad10 with leading + sign",
|
|
b"0 + -42",
|
|
Expr::Int(-42),
|
|
None,
|
|
),
|
|
Test("rad10 with leading - sign", b"0 + +42", Expr::Int(42), None),
|
|
Test(
|
|
"flag char is string, not (invalid) int",
|
|
b"-x",
|
|
Expr::String("-x".into()),
|
|
None,
|
|
),
|
|
Test(
|
|
"keyword parameter is string",
|
|
b"--exact",
|
|
Expr::String("--exact".into()),
|
|
None,
|
|
),
|
|
Test(
|
|
"ranges or relative paths not confused for int",
|
|
b"./a/b",
|
|
Expr::GlobPattern("./a/b".into(), false),
|
|
None,
|
|
),
|
|
Test(
|
|
"semver data not confused for int",
|
|
b"'1.0.1'",
|
|
Expr::String("1.0.1".into()),
|
|
None,
|
|
),
|
|
];
|
|
|
|
for test in tests {
|
|
test_int(test.0, test.1, test.2, test.3);
|
|
}
|
|
}
|
|
|
|
#[ignore]
|
|
#[test]
|
|
pub fn multi_test_parse_number() {
|
|
struct Test<'a>(&'a str, &'a [u8], Expr, Option<&'a str>);
|
|
|
|
// use test expression of form '0 + x' to force parse() to parse x as numeric.
|
|
// if expression were just 'x', parse() would try other items that would mask the error we're looking for.
|
|
let tests = vec![
|
|
Test("float decimal", b"0 + 43.5", Expr::Float(43.5), None),
|
|
//Test("float with leading + sign", b"0 + +41.7", Expr::Float(-41.7), None),
|
|
Test(
|
|
"float with leading - sign",
|
|
b"0 + -41.7",
|
|
Expr::Float(-41.7),
|
|
None,
|
|
),
|
|
Test(
|
|
"float scientific notation",
|
|
b"0 + 3e10",
|
|
Expr::Float(3.00e10),
|
|
None,
|
|
),
|
|
Test(
|
|
"float decimal literal invalid digits",
|
|
b"0 + .3foo",
|
|
Expr::Int(0),
|
|
Some("invalid digits"),
|
|
),
|
|
Test(
|
|
"float scientific notation literal invalid digits",
|
|
b"0 + 3e0faa",
|
|
Expr::Int(0),
|
|
Some("invalid digits"),
|
|
),
|
|
Test(
|
|
// odd that error is unsupportedOperation, but it does fail.
|
|
"decimal literal int 2 leading signs",
|
|
b"0 + --9",
|
|
Expr::Int(0),
|
|
Some("UnsupportedOperation"),
|
|
),
|
|
//Test(
|
|
// ".<string> should not be taken as float",
|
|
// b"abc + .foo",
|
|
// Expr::String("..".into()),
|
|
// None,
|
|
//),
|
|
];
|
|
|
|
for test in tests {
|
|
test_int(test.0, test.1, test.2, test.3);
|
|
}
|
|
}
|
|
|
|
#[ignore]
|
|
#[test]
|
|
fn test_parse_any() {
|
|
let test = b"1..10";
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, test, true);
|
|
|
|
match (block, working_set.parse_errors.first()) {
|
|
(_, Some(e)) => {
|
|
println!("test: {test:?}, error: {e:#?}");
|
|
}
|
|
(b, None) => {
|
|
println!("test: {test:?}, parse: {b:#?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_int() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"3", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::Int(3));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_int_with_underscores() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"420_69_2023", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::Int(420692023));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_filesize() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"95307.27MiB", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let Expr::ValueWithUnit(value) = &element.expr.expr else {
|
|
panic!("should be a ValueWithUnit");
|
|
};
|
|
|
|
assert_eq!(value.expr.expr, Expr::Int(99_936_915_947));
|
|
assert_eq!(value.unit.item, Unit::Filesize(FilesizeUnit::B));
|
|
}
|
|
|
|
// Whole-number literals must convert exactly (see issue #10612). Both types are
|
|
// backed by an `i64`, but the literal used to go through an `f64`, which
|
|
// silently rounded large values (e.g. `6504534684301572998b` became
|
|
// `6504534684301573120`). `KB`, `MB`, `us` and `min` go through the unit
|
|
// conversion multiply.
|
|
#[rstest]
|
|
#[case(
|
|
b"6504534684301572998b",
|
|
6504534684301572998,
|
|
Unit::Filesize(FilesizeUnit::B)
|
|
)]
|
|
#[case(b"-6504534684301572998b", -6504534684301572998, Unit::Filesize(FilesizeUnit::B))]
|
|
#[case(
|
|
b"9007199254740993KB",
|
|
9007199254740993000,
|
|
Unit::Filesize(FilesizeUnit::B)
|
|
)]
|
|
#[case(
|
|
b"9007199254741MB",
|
|
9_007_199_254_741_000_000,
|
|
Unit::Filesize(FilesizeUnit::B)
|
|
)]
|
|
#[case(b"8191PiB", 8191 * 1024_i64.pow(5), Unit::Filesize(FilesizeUnit::B))]
|
|
#[case(b"6504534684301572998ns", 6504534684301572998, Unit::Nanosecond)]
|
|
#[case(b"9007199254740993us", 9007199254740993000, Unit::Nanosecond)]
|
|
#[case(b"-153722867min", -153722867 * 60_000_000_000, Unit::Nanosecond)]
|
|
fn parse_unit_integer_is_exact(#[case] input: &[u8], #[case] expected: i64, #[case] unit: Unit) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, input, true);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
let element = &block.pipelines[0].elements[0];
|
|
let Expr::ValueWithUnit(value) = &element.expr.expr else {
|
|
panic!("should be a ValueWithUnit");
|
|
};
|
|
|
|
assert_eq!(value.expr.expr, Expr::Int(expected));
|
|
assert_eq!(value.unit.item, unit);
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_non_utf8_fails() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
// Panic when parsing units was triggered by non-UTF8 characters
|
|
// due to bad handling via `String::from_utf8_lossy`
|
|
//
|
|
// See https://github.com/nushell/nushell/pull/16355
|
|
let _block = parse(&mut working_set, None, b"0\xffB", true);
|
|
|
|
// Asserting on the exact error doesn't make as much sense as
|
|
assert!(!working_set.parse_errors.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_cell_path() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_variable(
|
|
"foo".to_string().into_bytes(),
|
|
Span::test_data(),
|
|
nu_protocol::Type::record(),
|
|
false,
|
|
);
|
|
|
|
let block = parse(&mut working_set, None, b"$foo.bar.baz", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
if let Expr::FullCellPath(b) = &element.expr.expr {
|
|
assert!(matches!(b.head.expr, Expr::Var(_)));
|
|
if let [a, b] = &b.tail[..] {
|
|
if let PathMember::String { val, optional, .. } = a {
|
|
assert_eq!(val, "bar");
|
|
assert_eq!(optional, &false);
|
|
} else {
|
|
panic!("wrong type")
|
|
}
|
|
|
|
if let PathMember::String { val, optional, .. } = b {
|
|
assert_eq!(val, "baz");
|
|
assert_eq!(optional, &false);
|
|
} else {
|
|
panic!("wrong type")
|
|
}
|
|
} else {
|
|
panic!("cell path tail is unexpected")
|
|
}
|
|
} else {
|
|
panic!("Not a cell path");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_cell_path_optional() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_variable(
|
|
"foo".to_string().into_bytes(),
|
|
Span::test_data(),
|
|
nu_protocol::Type::record(),
|
|
false,
|
|
);
|
|
|
|
let block = parse(&mut working_set, None, b"$foo.bar?.baz", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
if let Expr::FullCellPath(b) = &element.expr.expr {
|
|
assert!(matches!(b.head.expr, Expr::Var(_)));
|
|
if let [a, b] = &b.tail[..] {
|
|
if let PathMember::String { val, optional, .. } = a {
|
|
assert_eq!(val, "bar");
|
|
assert_eq!(optional, &true);
|
|
} else {
|
|
panic!("wrong type")
|
|
}
|
|
|
|
if let PathMember::String { val, optional, .. } = b {
|
|
assert_eq!(val, "baz");
|
|
assert_eq!(optional, &false);
|
|
} else {
|
|
panic!("wrong type")
|
|
}
|
|
} else {
|
|
panic!("cell path tail is unexpected")
|
|
}
|
|
} else {
|
|
panic!("Not a cell path");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_binary_with_hex_format() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"0x[13]", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::Binary(vec![0x13]));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_binary_with_incomplete_hex_format() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"0x[3]", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::Binary(vec![0x03]));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_binary_with_binary_format() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"0b[1010 1000]", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::Binary(vec![0b10101000]));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_binary_with_incomplete_binary_format() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"0b[10]", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::Binary(vec![0b00000010]));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_binary_with_octal_format() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"0o[250]", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::Binary(vec![0o250]));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_binary_with_incomplete_octal_format() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"0o[2]", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::Binary(vec![0o2]));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_binary_with_invalid_octal_format() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"0o[90]", true);
|
|
|
|
assert_eq!(working_set.parse_errors.len(), 1);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::InvalidBinaryString(_, _))
|
|
));
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert!(!matches!(element.expr.expr, Expr::Binary(_)));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_binary_with_multi_byte_char() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
// found using fuzzing, Rust can panic if you slice into this string
|
|
let contents = b"0x[\xEF\xBF\xBD]";
|
|
let block = parse(&mut working_set, None, contents, true);
|
|
|
|
assert_eq!(working_set.parse_errors.len(), 1);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::InvalidBinaryString(_, _))
|
|
));
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert!(!matches!(element.expr.expr, Expr::Binary(_)))
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo").named("--jazz", SyntaxShape::Int, "Jazz!!.", Some('j'));
|
|
working_set.add_decl(sig.predeclare());
|
|
|
|
let block = parse(&mut working_set, None, b"foo", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
if let Expr::Call(call) = &element.expr.expr {
|
|
assert_eq!(call.decl_id, DeclId::new(0));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_missing_flag_arg() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo").named("jazz", SyntaxShape::Int, "Jazz!!.", Some('j'));
|
|
working_set.add_decl(sig.predeclare());
|
|
|
|
parse(&mut working_set, None, b"foo --jazz", true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::MissingFlagParam(..))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_missing_short_flag_arg() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo").named("--jazz", SyntaxShape::Int, "Jazz!!.", Some('j'));
|
|
working_set.add_decl(sig.predeclare());
|
|
|
|
parse(&mut working_set, None, b"foo -j", true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::MissingFlagParam(..))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_short_flag_batch_arg_allowed() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo")
|
|
.named("--jazz", SyntaxShape::Int, "Jazz!!.", Some('j'))
|
|
.switch("--math", "Math!!.", Some('m'));
|
|
working_set.add_decl(sig.predeclare());
|
|
|
|
let block = parse(&mut working_set, None, b"foo -mj 10", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
if let Expr::Call(call) = &element.expr.expr {
|
|
assert_eq!(call.decl_id, DeclId::new(0));
|
|
assert_eq!(call.arguments.len(), 2);
|
|
matches!(call.arguments[0], Argument::Named((_, None, None)));
|
|
matches!(call.arguments[1], Argument::Named((_, None, Some(_))));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_short_flag_batch_arg_disallowed() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo")
|
|
.named("--jazz", SyntaxShape::Int, "Jazz!!.", Some('j'))
|
|
.switch("--math", "Math!!.", Some('m'));
|
|
working_set.add_decl(sig.predeclare());
|
|
|
|
parse(&mut working_set, None, b"foo -jm 10", true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::OnlyLastFlagInBatchCanTakeArg(..))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_short_flag_batch_disallow_multiple_args() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo")
|
|
.named("--math", SyntaxShape::Int, "Math!!.", Some('m'))
|
|
.named("--jazz", SyntaxShape::Int, "Jazz!!.", Some('j'));
|
|
working_set.add_decl(sig.predeclare());
|
|
|
|
parse(&mut working_set, None, b"foo -mj 10 20", true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::OnlyLastFlagInBatchCanTakeArg(..))
|
|
));
|
|
}
|
|
|
|
/// A flag written with more than one byte doesn't move where the batch ends: `-j` isn't last.
|
|
#[test]
|
|
pub fn parse_call_short_flag_batch_arg_disallowed_after_a_multibyte_flag() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo")
|
|
.switch("--eh", "Eh.", Some('é'))
|
|
.named("--jazz", SyntaxShape::Int, "Jazz!!.", Some('j'))
|
|
.switch("--math", "Math!!.", Some('m'));
|
|
working_set.add_decl(sig.predeclare());
|
|
|
|
parse(&mut working_set, None, "foo -éjm 10".as_bytes(), true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::OnlyLastFlagInBatchCanTakeArg(..))
|
|
));
|
|
}
|
|
|
|
/// A known external's program reads the rest of `-j8` as the value of `-j`, so the word goes to
|
|
/// it as written, and the next word stays an argument of its own. The word is a flag word, so
|
|
/// the `int` rest parameter doesn't reject it.
|
|
#[rstest]
|
|
#[case::value_flag("-Zscript")]
|
|
#[case::after_a_switch("-vj8")]
|
|
#[case::before_a_switch("-Zv")]
|
|
fn extern_forwards_a_short_flag_with_an_attached_value(#[case] word: &str) {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let source = format!(
|
|
"extern cmd [-Z: string, --jobs(-j): int, --verbose(-v), ...rest: int]; cmd {word} 1"
|
|
);
|
|
let block = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
let Expr::Call(call) = &block.pipelines[1].elements[0].expr.expr else {
|
|
panic!("expected a call");
|
|
};
|
|
let [Argument::Unknown(flags), Argument::Positional(next)] = call.arguments.as_slice() else {
|
|
panic!("expected the word and `1`, got {:?}", call.arguments);
|
|
};
|
|
assert!(
|
|
matches!(&flags.expr, Expr::String(s) if s == word),
|
|
"{:?}",
|
|
flags.expr
|
|
);
|
|
assert_eq!(working_set.get_span_contents(next.span), b"1");
|
|
}
|
|
|
|
/// An attached value is checked against the flag's type, as `-j abc` is, even though the word
|
|
/// goes to the program as written.
|
|
#[test]
|
|
fn extern_checks_the_type_of_an_attached_value() {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
parse(
|
|
&mut working_set,
|
|
None,
|
|
b"extern cmd [--jobs(-j): int, --verbose(-v), ...rest]; cmd -vjabc",
|
|
false,
|
|
);
|
|
|
|
let [err] = working_set.parse_errors.as_slice() else {
|
|
panic!("expected one error, got {:?}", working_set.parse_errors);
|
|
};
|
|
assert_eq!(working_set.get_span_contents(err.span()), b"abc");
|
|
}
|
|
|
|
/// `-inf` with a value flag `-i` is that flag and its value, as the program reads it, even where
|
|
/// a number could go.
|
|
#[test]
|
|
fn extern_forwards_an_attached_value_that_spells_a_number() {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"extern cmd [-i: string, n?: number]; cmd -inf",
|
|
false,
|
|
);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
let Expr::Call(call) = &block.pipelines[1].elements[0].expr.expr else {
|
|
panic!("expected a call");
|
|
};
|
|
let [Argument::Unknown(word)] = call.arguments.as_slice() else {
|
|
panic!("expected only the word, got {:?}", call.arguments);
|
|
};
|
|
assert_eq!(working_set.get_span_contents(word.span), b"-inf");
|
|
}
|
|
|
|
/// `-1e5` starts with `1`, which isn't a flag, so it stays a number even though `-e` takes a value.
|
|
#[test]
|
|
fn extern_number_with_a_value_flag_letter_stays_a_number() {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"extern cmd [-e: string, n: number]; cmd -1e5",
|
|
false,
|
|
);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
let Expr::Call(call) = &block.pipelines[1].elements[0].expr.expr else {
|
|
panic!("expected a call");
|
|
};
|
|
let [Argument::Positional(n)] = call.arguments.as_slice() else {
|
|
panic!("expected only `n`, got {:?}", call.arguments);
|
|
};
|
|
assert_eq!(n.expr, Expr::Float(-1e5));
|
|
}
|
|
|
|
/// A value that starts with `$` or `(` reads differently inside the word than on its own, so it
|
|
/// isn't checked: `-Z$x` reaches the program as written, and `-Z(1 + 2)` as `-Z3`.
|
|
#[rstest]
|
|
#[case::variable("-Z$undefined")]
|
|
#[case::subexpression("-Z(1 + 2)")]
|
|
fn extern_does_not_check_an_attached_value_spelled_with_code(#[case] word: &str) {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let source = format!("extern cmd [-Z: string, ...rest]; cmd {word}");
|
|
let block = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
let Expr::Call(call) = &block.pipelines[1].elements[0].expr.expr else {
|
|
panic!("expected a call");
|
|
};
|
|
let [Argument::Unknown(arg)] = call.arguments.as_slice() else {
|
|
panic!("expected only the word, got {:?}", call.arguments);
|
|
};
|
|
assert_eq!(working_set.get_span_contents(arg.span), word.as_bytes());
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_unknown_shorthand() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo").switch("--jazz", "Jazz!!.", Some('j'));
|
|
working_set.add_decl(sig.predeclare());
|
|
parse(&mut working_set, None, b"foo -mj", true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::UnknownFlag(..))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_extra_positional() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo").switch("--jazz", "Jazz!!.", Some('j'));
|
|
working_set.add_decl(sig.predeclare());
|
|
parse(&mut working_set, None, b"foo -j 100", true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::ExtraPositional(..))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_missing_req_positional() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo").required("jazz", SyntaxShape::Int, "Jazz!!.");
|
|
working_set.add_decl(sig.predeclare());
|
|
parse(&mut working_set, None, b"foo", true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::MissingPositional(..))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_call_missing_req_flag() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let sig = Signature::build("foo").required_named("--jazz", SyntaxShape::Int, "Jazz!!.", None);
|
|
working_set.add_decl(sig.predeclare());
|
|
parse(&mut working_set, None, b"foo", true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::MissingRequiredFlag(..))
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_attribute_block_check_spans() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let source = b"
|
|
@foo a 1 2
|
|
@bar b 3 4
|
|
echo baz
|
|
";
|
|
let block = parse(&mut working_set, None, source, true);
|
|
|
|
// There SHOULD be errors here, we're using nonexistent commands
|
|
assert!(!working_set.parse_errors.is_empty());
|
|
|
|
assert_eq!(block.len(), 1);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let Expr::AttributeBlock(ab) = &element.expr.expr else {
|
|
panic!("Couldn't parse attribute block");
|
|
};
|
|
|
|
assert_eq!(
|
|
working_set.get_span_contents(ab.attributes[0].expr.span),
|
|
b"foo a 1 2"
|
|
);
|
|
assert_eq!(
|
|
working_set.get_span_contents(ab.attributes[1].expr.span),
|
|
b"bar b 3 4"
|
|
);
|
|
assert_eq!(working_set.get_span_contents(ab.item.span), b"echo baz");
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_attributes_check_values() {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let source = br#"
|
|
@echo "hello world"
|
|
@echo 42
|
|
def foo [] {}
|
|
"#;
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
let decl_id = working_set.find_decl(b"foo").unwrap();
|
|
let cmd = working_set.get_decl(decl_id);
|
|
let attributes = cmd.attributes();
|
|
|
|
let (name, val) = &attributes[0];
|
|
assert_eq!(name, "echo");
|
|
assert_eq!(val.as_str(), Ok("hello world"));
|
|
|
|
let (name, val) = &attributes[1];
|
|
assert_eq!(name, "echo");
|
|
assert_eq!(val.as_int(), Ok(42));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_attributes_alias() {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(Alias));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let source = br#"
|
|
alias "attr test" = attr echo
|
|
|
|
@test null
|
|
def foo [] {}
|
|
"#;
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
let decl_id = working_set.find_decl(b"foo").unwrap();
|
|
let cmd = working_set.get_decl(decl_id);
|
|
let attributes = cmd.attributes();
|
|
|
|
let (name, val) = &attributes[0];
|
|
assert_eq!(name, "test");
|
|
assert!(val.is_nothing());
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_attributes_external_alias() {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(Alias));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let source = br#"
|
|
alias "attr test" = ^echo
|
|
|
|
@test null
|
|
def foo [] {}
|
|
"#;
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(!working_set.parse_errors.is_empty());
|
|
|
|
let ParseError::ParseTimeEval { report, error, .. } = &working_set.parse_errors[0] else {
|
|
panic!("Expected ParseTimeEval");
|
|
};
|
|
|
|
assert!(report.contains("nu::shell::not_a_const_command"));
|
|
assert!(matches!(
|
|
**error,
|
|
nu_protocol::ShellError::NotAConstCommand { .. }
|
|
));
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::double_space("foo bar")]
|
|
#[case::leading_space(" foo")]
|
|
#[case::trailing_space("foo ")]
|
|
#[case::tab("foo\tbar")]
|
|
#[case::hex("0x10")]
|
|
#[case::binary("0b101")]
|
|
#[case::octal("0o17")]
|
|
#[case::digit_separator("1_2")]
|
|
#[case::float_digit_separator("1.2_345")]
|
|
#[case::hex_digit_separator("0x_10")]
|
|
#[case::out_of_range("0x10000000000000000")]
|
|
#[case::leading_separator("_1")]
|
|
#[case::signed_hex("-0x10")]
|
|
#[case::signed_separator("+1_2")]
|
|
#[case::filesize_with_separator("1_0kb")]
|
|
#[case::duration("1sec")]
|
|
#[case::datetime("2020-01-01")]
|
|
#[case::range("1..2")]
|
|
#[case::head_word_is_a_number("1 2")]
|
|
#[case::head_word_is_a_filesize("1kb 2")]
|
|
#[case::escaped_number("0x\\u{31}0")]
|
|
#[case::binary_literal("0x[FF]")]
|
|
pub fn parse_rejects_uncallable_command_names(#[case] name: &str) {
|
|
// https://github.com/nushell/nushell/issues/15539
|
|
// https://github.com/nushell/nushell/issues/16815
|
|
// A call is looked up by its words joined with single spaces, so a name with any other
|
|
// whitespace could never be called. A name that the call site reads as a value is shadowed
|
|
// by that value, so it could never be called either: a number, a filesize, a duration, a
|
|
// datetime and a range all win at the call site.
|
|
let first_error = |source: &str| {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(Alias));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
working_set.parse_errors.first().cloned()
|
|
};
|
|
|
|
// Backticks don't decode escapes, so a backtick name with an escape in it is a bare word.
|
|
let backtick = !name.contains('\\');
|
|
for source in [
|
|
format!("def \"{name}\" [] {{}}"),
|
|
format!("extern \"{name}\" []"),
|
|
]
|
|
.into_iter()
|
|
.chain(backtick.then(|| format!("def `{name}` [] {{}}")))
|
|
{
|
|
assert!(
|
|
matches!(
|
|
first_error(&source),
|
|
Some(ParseError::CommandDefNotValid(_))
|
|
),
|
|
"{source:?}"
|
|
);
|
|
}
|
|
|
|
for source in [format!("alias \"{name}\" = attr echo")]
|
|
.into_iter()
|
|
.chain(backtick.then(|| format!("alias `{name}` = attr echo")))
|
|
{
|
|
assert!(
|
|
matches!(first_error(&source), Some(ParseError::AliasNotValid(_))),
|
|
"{source:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::hex_without_digits("0xZZ", "0xZZ")]
|
|
#[case::binary_without_digits("0b2", "0b2")]
|
|
#[case::octal_without_digits("0o18", "0o18")]
|
|
#[case::bare_prefix("0x", "0x")]
|
|
#[case::value_in_a_later_word("foo 0x10", "foo 0x10")]
|
|
#[case::escaped_name("foo\\u{2D}bar", "foo-bar")]
|
|
#[case::float_spelling_infinity("infinity", "infinity")]
|
|
#[case::float_spelling_inf("INF", "INF")]
|
|
#[case::float_spelling_nan("Nan", "Nan")]
|
|
pub fn parse_accepts_bare_word_names_that_are_not_values(#[case] name: &str, #[case] call: &str) {
|
|
// https://github.com/nushell/nushell/issues/16815
|
|
// These are read as bare words rather than as values, so they name a command that can still
|
|
// be called. The call has to come back as a call to that declaration, not as the value the
|
|
// name looks like.
|
|
// The name is the name as it is written in the definition; the call is the name the
|
|
// declaration is registered under, which for a name written with escapes is the decoded
|
|
// name, because a bare word does not decode escapes.
|
|
let call_of = |source: &str| {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(Alias));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
|
|
// The built-in declarations have to be permanent for the `def` keyword to be found,
|
|
// and the declaration itself has to be permanent for the call to find it.
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, format!("{call}\n").as_bytes(), true);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{name:?}: {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
|
|
let decl_id = working_set.find_decl(call.as_bytes());
|
|
let pipeline = block
|
|
.pipelines
|
|
.last()
|
|
.expect("the call should be a pipeline");
|
|
match &pipeline.elements[0].expr.expr {
|
|
Expr::Call(call) => (call.decl_id, decl_id),
|
|
other => panic!("{name:?} should parse as a call, got {other:?}"),
|
|
}
|
|
};
|
|
|
|
let (call_decl, decl_id) = call_of(&format!("def \"{name}\" [] {{}}\n"));
|
|
assert_eq!(
|
|
call_decl,
|
|
decl_id.unwrap_or_else(|| panic!("{name:?} should be declared")),
|
|
"{name:?}"
|
|
);
|
|
|
|
// An alias is expanded into its body, so the call is to the body rather than to the
|
|
// alias, but it still has to be a call.
|
|
let (_, decl_id) = call_of(&format!("alias \"{name}\" = attr echo hi\n"));
|
|
assert!(decl_id.is_some(), "{name:?} should be declared");
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_accepts_single_spaces_in_command_names() {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(Alias));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let source = br#"
|
|
def "foo bar" [] {}
|
|
alias "foo bar baz" = attr echo
|
|
"#;
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
assert!(working_set.find_decl(b"foo bar").is_some());
|
|
assert!(working_set.find_decl(b"foo bar baz").is_some());
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_aliased_variable_in() {
|
|
// https://github.com/nushell/nushell/issues/13706
|
|
// https://github.com/nushell/nushell/issues/17538
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Alias));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
|
|
let source = b"alias e = attr echo ($in)";
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let source = b"1 | e";
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_if_in_const_expression() {
|
|
// https://github.com/nushell/nushell/issues/15321
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Const));
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(IfMocked));
|
|
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let source = b"const foo = if t";
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(!working_set.parse_errors.is_empty());
|
|
let ParseError::MissingPositional(error, _, _) = &working_set.parse_errors[0] else {
|
|
panic!("Expected MissingPositional");
|
|
};
|
|
|
|
assert!(error.contains("cond"));
|
|
|
|
working_set.parse_errors = Vec::new();
|
|
let source = b"def a [n= (if ]";
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(!working_set.parse_errors.is_empty());
|
|
match &working_set.parse_errors[0] {
|
|
ParseError::UnexpectedEof(error, _) => assert!(error.contains(')')),
|
|
ParseError::Unclosed(delim, ..) => assert!(delim.contains(')')),
|
|
ParseError::Unbalanced(_, close, ..) => assert!(close.contains(']') || close.contains(')')),
|
|
other => panic!("Expected UnexpectedEof/Unclosed/Unbalanced, got {other:?}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_percent_prefixed_internal_call() {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(LsTest));
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, b"%ls", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
let element = &pipeline.elements[0];
|
|
|
|
match &element.expr.expr {
|
|
Expr::Call(call) => {
|
|
let decl = working_set.get_decl(call.decl_id);
|
|
assert_eq!(decl.name(), "ls");
|
|
}
|
|
other => {
|
|
panic!("Expected internal call, got: {other:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_percent_prefixed_dynamic_dispatch() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"%('echo') hello", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
let element = &pipeline.elements[0];
|
|
|
|
match &element.expr.expr {
|
|
Expr::Call(call) => {
|
|
// Check that the call has the percent_forced_builtin marker
|
|
assert!(call.parser_info.contains_key("percent_forced_builtin"));
|
|
}
|
|
other => {
|
|
panic!("Expected internal call with percent marker, got: {other:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_percent_prefixed_dynamic_dispatch_bare_var() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"%$cmd hello", true);
|
|
|
|
assert!(
|
|
working_set
|
|
.parse_errors
|
|
.iter()
|
|
.any(|err| matches!(err, ParseError::VariableNotFound(..)))
|
|
);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
let element = &pipeline.elements[0];
|
|
|
|
match &element.expr.expr {
|
|
Expr::Call(call) => {
|
|
assert!(call.parser_info.contains_key("percent_forced_builtin"));
|
|
}
|
|
other => {
|
|
panic!("Expected internal call with percent marker, got: {other:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_percent_prefixed_dynamic_dispatch_with_spaced_head() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"% ('echo') hello", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
let element = &pipeline.elements[0];
|
|
|
|
match &element.expr.expr {
|
|
Expr::Call(call) => {
|
|
assert!(call.parser_info.contains_key("percent_forced_builtin"));
|
|
}
|
|
other => {
|
|
panic!("Expected internal call with percent marker, got: {other:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_percent_prefixed_dynamic_dispatch_with_spread_arg() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"%('echo') ...$args", true);
|
|
|
|
assert!(
|
|
working_set
|
|
.parse_errors
|
|
.iter()
|
|
.any(|err| matches!(err, ParseError::VariableNotFound(..)))
|
|
);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
let element = &pipeline.elements[0];
|
|
|
|
match &element.expr.expr {
|
|
Expr::Call(call) => {
|
|
assert!(call.parser_info.contains_key("percent_forced_builtin"));
|
|
assert!(matches!(call.arguments.first(), Some(Argument::Spread(_))));
|
|
}
|
|
other => {
|
|
panic!("Expected internal call with percent marker, got: {other:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_caret_prefixed_call_forces_external_parse() {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(LsTest));
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, b"^ls", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
let element = &pipeline.elements[0];
|
|
|
|
assert!(matches!(element.expr.expr, Expr::ExternalCall(..)));
|
|
}
|
|
|
|
#[test]
|
|
fn parse_percent_prefixed_prefers_builtin_when_custom_shadows_name() {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(LsTest));
|
|
working_set.add_decl(Box::new(LsCustom));
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, b"%ls", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
let element = &pipeline.elements[0];
|
|
|
|
match &element.expr.expr {
|
|
Expr::Call(call) => {
|
|
let decl = working_set.get_decl(call.decl_id);
|
|
assert_eq!(decl.name(), "ls");
|
|
assert_eq!(
|
|
decl.command_type(),
|
|
nu_protocol::engine::CommandType::Builtin
|
|
);
|
|
}
|
|
other => {
|
|
panic!("Expected internal call, got: {other:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_percent_prefixed_unknown_command_does_not_fallback_to_external() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, b"%nu --version", true);
|
|
|
|
assert!(!working_set.parse_errors.is_empty());
|
|
assert!(
|
|
working_set.parse_errors.iter().any(|err| {
|
|
matches!(
|
|
err,
|
|
ParseError::LabeledErrorWithHelp { error, .. }
|
|
if error.contains("percent sigil requires a built-in command")
|
|
)
|
|
}),
|
|
"Unexpected parse errors: {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
|
|
// Keep expression shape for completion while retaining parse-time failure semantics.
|
|
let pipeline = &block.pipelines[0];
|
|
let element = &pipeline.elements[0];
|
|
assert!(matches!(element.expr.expr, Expr::ExternalCall(..)));
|
|
}
|
|
|
|
fn test_external_call(input: &str, tag: &str, f: impl FnOnce(&Expression, &[ExternalArgument])) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, input.as_bytes(), true);
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{tag}: errors: {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(1, pipeline.len());
|
|
let element = &pipeline.elements[0];
|
|
match &element.expr.expr {
|
|
Expr::ExternalCall(name, args) => f(name, args),
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in pipeline: {other:?}");
|
|
}
|
|
}
|
|
}
|
|
|
|
fn check_external_call_interpolation(
|
|
tag: &str,
|
|
subexpr_count: usize,
|
|
quoted: bool,
|
|
expr: &Expression,
|
|
) -> bool {
|
|
match &expr.expr {
|
|
Expr::StringInterpolation(exprs) => {
|
|
assert!(quoted, "{tag}: quoted");
|
|
assert_eq!(expr.ty, Type::String, "{tag}: expr.ty");
|
|
assert_eq!(subexpr_count, exprs.len(), "{tag}: subexpr_count");
|
|
true
|
|
}
|
|
Expr::GlobInterpolation(exprs, is_quoted) => {
|
|
assert_eq!(quoted, *is_quoted, "{tag}: quoted");
|
|
assert_eq!(expr.ty, Type::Glob, "{tag}: expr.ty");
|
|
assert_eq!(subexpr_count, exprs.len(), "{tag}: subexpr_count");
|
|
true
|
|
}
|
|
_ => false,
|
|
}
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("foo-external-call", "foo-external-call", "bare word")]
|
|
#[case("^foo-external-call", "foo-external-call", "bare word with caret")]
|
|
#[case(
|
|
"foo/external-call",
|
|
"foo/external-call",
|
|
"bare word with forward slash"
|
|
)]
|
|
#[case(
|
|
"^foo/external-call",
|
|
"foo/external-call",
|
|
"bare word with forward slash and caret"
|
|
)]
|
|
#[case(r"foo\external-call", r"foo\external-call", "bare word with backslash")]
|
|
#[case(
|
|
r"^foo\external-call",
|
|
r"foo\external-call",
|
|
"bare word with backslash and caret"
|
|
)]
|
|
#[case("`foo external call`", "foo external call", "backtick quote")]
|
|
#[case(
|
|
"^`foo external call`",
|
|
"foo external call",
|
|
"backtick quote with caret"
|
|
)]
|
|
#[case(
|
|
"`foo/external call`",
|
|
"foo/external call",
|
|
"backtick quote with forward slash"
|
|
)]
|
|
#[case(
|
|
"^`foo/external call`",
|
|
"foo/external call",
|
|
"backtick quote with forward slash and caret"
|
|
)]
|
|
#[case(
|
|
r"`foo\external call`",
|
|
r"foo\external call",
|
|
"backtick quote with backslash"
|
|
)]
|
|
#[case(
|
|
r"^`foo\external call`",
|
|
r"foo\external call",
|
|
"backtick quote with backslash and caret"
|
|
)]
|
|
pub fn test_external_call_head_glob(
|
|
#[case] input: &str,
|
|
#[case] expected: &str,
|
|
#[case] tag: &str,
|
|
) {
|
|
test_external_call(input, tag, |name, args| {
|
|
match &name.expr {
|
|
Expr::GlobPattern(string, is_quoted) => {
|
|
assert_eq!(expected, string, "{tag}: incorrect name");
|
|
assert!(!*is_quoted);
|
|
}
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in command name position: {other:?}");
|
|
}
|
|
}
|
|
assert_eq!(0, args.len());
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(
|
|
"^r#'foo-external-call'#",
|
|
"foo-external-call",
|
|
"raw string with caret"
|
|
)]
|
|
#[case(
|
|
"^r#'foo/external-call'#",
|
|
"foo/external-call",
|
|
"raw string with forward slash and caret"
|
|
)]
|
|
#[case(
|
|
r##"^r#'foo\external-call'#"##,
|
|
r"foo\external-call",
|
|
"raw string with backslash and caret"
|
|
)]
|
|
pub fn test_external_call_head_raw_string(
|
|
#[case] input: &str,
|
|
#[case] expected: &str,
|
|
#[case] tag: &str,
|
|
) {
|
|
test_external_call(input, tag, |name, args| {
|
|
match &name.expr {
|
|
Expr::RawString(string) => {
|
|
assert_eq!(expected, string, "{tag}: incorrect name");
|
|
}
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in command name position: {other:?}");
|
|
}
|
|
}
|
|
assert_eq!(0, args.len());
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("^'foo external call'", "foo external call", "single quote with caret")]
|
|
#[case(
|
|
"^'foo/external call'",
|
|
"foo/external call",
|
|
"single quote with forward slash and caret"
|
|
)]
|
|
#[case(
|
|
r"^'foo\external call'",
|
|
r"foo\external call",
|
|
"single quote with backslash and caret"
|
|
)]
|
|
#[case(
|
|
r#"^"foo external call""#,
|
|
"foo external call",
|
|
"double quote with caret"
|
|
)]
|
|
#[case(
|
|
r#"^"foo/external call""#,
|
|
"foo/external call",
|
|
"double quote with forward slash and caret"
|
|
)]
|
|
#[case(
|
|
r#"^"foo\\external call""#,
|
|
r#"foo\external call"#,
|
|
"double quote with backslash and caret"
|
|
)]
|
|
pub fn test_external_call_head_string(
|
|
#[case] input: &str,
|
|
#[case] expected: &str,
|
|
#[case] tag: &str,
|
|
) {
|
|
test_external_call(input, tag, |name, args| {
|
|
match &name.expr {
|
|
Expr::String(string) => {
|
|
assert_eq!(expected, string);
|
|
}
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in command name position: {other:?}");
|
|
}
|
|
}
|
|
assert_eq!(0, args.len());
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("~/.foo/(1)", 2, false, "unquoted interpolated string")]
|
|
#[case(
|
|
r"~\.foo(2)\(1)",
|
|
4,
|
|
false,
|
|
"unquoted interpolated string with backslash"
|
|
)]
|
|
#[case("^~/.foo/(1)", 2, false, "unquoted interpolated string with caret")]
|
|
#[case(r#"^$"~/.foo/(1)""#, 2, true, "quoted interpolated string with caret")]
|
|
pub fn test_external_call_head_interpolated_string(
|
|
#[case] input: &str,
|
|
#[case] subexpr_count: usize,
|
|
#[case] quoted: bool,
|
|
#[case] tag: &str,
|
|
) {
|
|
test_external_call(input, tag, |name, args| {
|
|
if !check_external_call_interpolation(tag, subexpr_count, quoted, name) {
|
|
panic!("{tag}: Unexpected expression in command name position: {name:?}");
|
|
}
|
|
assert_eq!(0, args.len());
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("^foo foo-external-call", "foo-external-call", "bare word")]
|
|
#[case(
|
|
"^foo foo/external-call",
|
|
"foo/external-call",
|
|
"bare word with forward slash"
|
|
)]
|
|
#[case(
|
|
r"^foo foo\external-call",
|
|
r"foo\external-call",
|
|
"bare word with backslash"
|
|
)]
|
|
#[case(
|
|
"^foo `foo external call`",
|
|
"foo external call",
|
|
"backtick quote with caret"
|
|
)]
|
|
#[case(
|
|
"^foo `foo/external call`",
|
|
"foo/external call",
|
|
"backtick quote with forward slash"
|
|
)]
|
|
#[case(
|
|
r"^foo `foo\external call`",
|
|
r"foo\external call",
|
|
"backtick quote with backslash"
|
|
)]
|
|
#[case(
|
|
r#"^foo --flag="value""#,
|
|
"--flag=value",
|
|
"flag value with double quote"
|
|
)]
|
|
#[case("^foo --flag='value'", "--flag=value", "flag value with single quote")]
|
|
#[case(
|
|
"^foo `hello world`",
|
|
"hello world",
|
|
"value is surrounded by backtick quote"
|
|
)]
|
|
#[case(
|
|
r#"^foo `"hello world"`"#,
|
|
"\"hello world\"",
|
|
"value is surrounded by backtick quote, with inner double quote"
|
|
)]
|
|
#[case(
|
|
"^foo `'hello world'`",
|
|
"'hello world'",
|
|
"value is surrounded by backtick quote, with inner single quote"
|
|
)]
|
|
pub fn test_external_call_arg_glob(#[case] input: &str, #[case] expected: &str, #[case] tag: &str) {
|
|
test_external_call(input, tag, |name, args| {
|
|
match &name.expr {
|
|
Expr::GlobPattern(string, _) => {
|
|
assert_eq!("foo", string, "{tag}: incorrect name");
|
|
}
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in command name position: {other:?}");
|
|
}
|
|
}
|
|
assert_eq!(1, args.len());
|
|
match &args[0] {
|
|
ExternalArgument::Regular(expr) => match &expr.expr {
|
|
Expr::GlobPattern(string, is_quoted) => {
|
|
assert_eq!(expected, string, "{tag}: incorrect arg");
|
|
assert!(!*is_quoted);
|
|
}
|
|
other => {
|
|
panic!("Unexpected expression in command arg position: {other:?}")
|
|
}
|
|
},
|
|
other @ ExternalArgument::Spread(..) => {
|
|
panic!("Unexpected external spread argument in command arg position: {other:?}")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("^foo r#'foo-external-call'#", "foo-external-call", "raw string")]
|
|
#[case(
|
|
"^foo r#'foo/external-call'#",
|
|
"foo/external-call",
|
|
"raw string with forward slash"
|
|
)]
|
|
#[case(
|
|
r##"^foo r#'foo\external-call'#"##,
|
|
r"foo\external-call",
|
|
"raw string with backslash"
|
|
)]
|
|
pub fn test_external_call_arg_raw_string(
|
|
#[case] input: &str,
|
|
#[case] expected: &str,
|
|
#[case] tag: &str,
|
|
) {
|
|
test_external_call(input, tag, |name, args| {
|
|
match &name.expr {
|
|
Expr::GlobPattern(string, _) => {
|
|
assert_eq!("foo", string, "{tag}: incorrect name");
|
|
}
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in command name position: {other:?}");
|
|
}
|
|
}
|
|
assert_eq!(1, args.len());
|
|
match &args[0] {
|
|
ExternalArgument::Regular(expr) => match &expr.expr {
|
|
Expr::RawString(string) => {
|
|
assert_eq!(expected, string, "{tag}: incorrect arg");
|
|
}
|
|
other => {
|
|
panic!("Unexpected expression in command arg position: {other:?}")
|
|
}
|
|
},
|
|
other @ ExternalArgument::Spread(..) => {
|
|
panic!("Unexpected external spread argument in command arg position: {other:?}")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("^foo 'foo external call'", "foo external call", "single quote")]
|
|
#[case(
|
|
"^foo 'foo/external call'",
|
|
"foo/external call",
|
|
"single quote with forward slash"
|
|
)]
|
|
#[case(
|
|
r"^foo 'foo\external call'",
|
|
r"foo\external call",
|
|
"single quote with backslash"
|
|
)]
|
|
#[case(r#"^foo "foo external call""#, "foo external call", "double quote")]
|
|
#[case(
|
|
r#"^foo "foo/external call""#,
|
|
"foo/external call",
|
|
"double quote with forward slash"
|
|
)]
|
|
#[case(
|
|
r#"^foo "foo\\external call""#,
|
|
r#"foo\external call"#,
|
|
"double quote with backslash"
|
|
)]
|
|
#[case("^foo '{a:1}'", "{a:1}", "quoted record-like string")]
|
|
pub fn test_external_call_arg_string(
|
|
#[case] input: &str,
|
|
#[case] expected: &str,
|
|
#[case] tag: &str,
|
|
) {
|
|
test_external_call(input, tag, |name, args| {
|
|
match &name.expr {
|
|
Expr::GlobPattern(string, _) => {
|
|
assert_eq!("foo", string, "{tag}: incorrect name");
|
|
}
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in command name position: {other:?}");
|
|
}
|
|
}
|
|
assert_eq!(1, args.len());
|
|
match &args[0] {
|
|
ExternalArgument::Regular(expr) => match &expr.expr {
|
|
Expr::String(string) => {
|
|
assert_eq!(expected, string, "{tag}: incorrect arg");
|
|
}
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in command arg position: {other:?}")
|
|
}
|
|
},
|
|
other @ ExternalArgument::Spread(..) => {
|
|
panic!(
|
|
"{tag}: Unexpected external spread argument in command arg position: {other:?}"
|
|
)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("^foo ~/.foo/(1)", 2, false, "unquoted interpolated string")]
|
|
#[case(r#"^foo $"~/.foo/(1)""#, 2, true, "quoted interpolated string")]
|
|
pub fn test_external_call_arg_interpolated_string(
|
|
#[case] input: &str,
|
|
#[case] subexpr_count: usize,
|
|
#[case] quoted: bool,
|
|
#[case] tag: &str,
|
|
) {
|
|
test_external_call(input, tag, |name, args| {
|
|
match &name.expr {
|
|
Expr::GlobPattern(string, _) => {
|
|
assert_eq!("foo", string, "{tag}: incorrect name");
|
|
}
|
|
other => {
|
|
panic!("{tag}: Unexpected expression in command name position: {other:?}");
|
|
}
|
|
}
|
|
assert_eq!(1, args.len());
|
|
match &args[0] {
|
|
ExternalArgument::Regular(expr) => {
|
|
if !check_external_call_interpolation(tag, subexpr_count, quoted, expr) {
|
|
panic!("Unexpected expression in command arg position: {expr:?}")
|
|
}
|
|
}
|
|
other @ ExternalArgument::Spread(..) => {
|
|
panic!("Unexpected external spread argument in command arg position: {other:?}")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(r#"^foo {|my_var| $"($my_var)" }"#)]
|
|
#[case(r#"^foo { |my_var| $"($my_var)" }"#)]
|
|
#[case("^foo { 42 }")]
|
|
fn test_external_call_arg_closure(#[case] input: &str) {
|
|
test_external_call(input, "closure argument", |_, args| {
|
|
assert_eq!(1, args.len());
|
|
assert!(matches!(
|
|
&args[0],
|
|
ExternalArgument::Regular(Expression {
|
|
expr: Expr::Closure(_),
|
|
..
|
|
})
|
|
));
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("^foo {a: 1}")]
|
|
#[case("^foo {}")]
|
|
#[case("^foo {a:1,b:'c',c:'d'}")]
|
|
#[case(r#"^foo {a:1,b:"c",c:"d"}"#)]
|
|
#[case(r#"^foo {a:1,b:'c',c:"d"}"#)]
|
|
#[case("^foo {a: 1, b: 'c', c: 'd'}")]
|
|
#[case(r#"^foo {a: 1, b: "c", c: "d"}"#)]
|
|
#[case(r#"^foo {a: 1, b: 'c', c: "d"}"#)]
|
|
#[case(r#"^foo {"key with spaces": "value"}"#)]
|
|
#[case(r#"^foo {outer: {inner: "value"}}"#)]
|
|
#[case(r#"^foo {items: [1 "two" true]}"#)]
|
|
fn test_external_call_arg_record(#[case] input: &str) {
|
|
test_external_call(input, "record argument", |_, args| {
|
|
assert_eq!(1, args.len());
|
|
let ExternalArgument::Regular(expr) = &args[0] else {
|
|
panic!("Expected a regular external argument")
|
|
};
|
|
let is_record = match &expr.expr {
|
|
Expr::Record(_) => true,
|
|
Expr::FullCellPath(path) => matches!(path.head.expr, Expr::Record(_)),
|
|
_ => false,
|
|
};
|
|
assert!(is_record, "Expected a record expression, found {expr:?}");
|
|
})
|
|
}
|
|
|
|
#[test]
|
|
fn test_external_call_argument_spread() {
|
|
let input = "^foo ...[a b c]";
|
|
let tag = "spread";
|
|
|
|
test_external_call(input, tag, |name, args| {
|
|
match &name.expr {
|
|
Expr::GlobPattern(string, _) => {
|
|
assert_eq!("foo", string, "incorrect name");
|
|
}
|
|
other => {
|
|
panic!("Unexpected expression in command name position: {other:?}");
|
|
}
|
|
}
|
|
assert_eq!(1, args.len());
|
|
match &args[0] {
|
|
ExternalArgument::Spread(expr) => match &expr.expr {
|
|
Expr::List(items) => {
|
|
assert_eq!(3, items.len());
|
|
// that's good enough, don't really need to go so deep into it...
|
|
}
|
|
other => {
|
|
panic!("Unexpected expression in command arg position: {other:?}")
|
|
}
|
|
},
|
|
other @ ExternalArgument::Regular(..) => {
|
|
panic!("Unexpected external regular argument in command arg position: {other:?}")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
#[test]
|
|
fn test_nothing_comparison_eq() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, b"2 == null", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert!(matches!(&element.expr.expr, Expr::BinaryOp(..)));
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(b"let a o> file = 1")]
|
|
#[case(b"mut a o> file = 1")]
|
|
fn test_redirection_inside_letmut_no_panic(#[case] phase: &[u8]) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(Let));
|
|
working_set.add_decl(Box::new(Mut));
|
|
|
|
parse(&mut working_set, None, phase, true);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(b"let a = 1 err> /dev/null")]
|
|
#[case(b"let a = 1 out> /dev/null")]
|
|
#[case(b"let a = 1 out+err> /dev/null")]
|
|
#[case(b"mut a = 1 err> /dev/null")]
|
|
#[case(b"mut a = 1 out> /dev/null")]
|
|
#[case(b"mut a = 1 out+err> /dev/null")]
|
|
fn test_redirection_with_letmut(#[case] phase: &[u8]) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(Let));
|
|
working_set.add_decl(Box::new(Mut));
|
|
|
|
let block = parse(&mut working_set, None, phase, true);
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"parse errors: {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
assert_eq!(1, block.pipelines[0].elements.len());
|
|
|
|
let element = &block.pipelines[0].elements[0];
|
|
assert!(element.redirection.is_none()); // it should be in the let block, not here
|
|
|
|
if let Expr::Call(call) = &element.expr.expr {
|
|
let arg = call.positional_iter().nth(1).expect("no positional args");
|
|
let block_id = arg.as_block().expect("arg 1 is not a block");
|
|
let block = working_set.get_block(block_id);
|
|
let inner_element = &block.pipelines[0].elements[0];
|
|
assert!(inner_element.redirection.is_some());
|
|
} else {
|
|
panic!("expected Call: {:?}", block.pipelines[0].elements[0])
|
|
}
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(b"o>")]
|
|
#[case(b"o>>")]
|
|
#[case(b"e>")]
|
|
#[case(b"e>>")]
|
|
#[case(b"o+e>")]
|
|
#[case(b"o+e>>")]
|
|
#[case(b"e>|")]
|
|
#[case(b"o+e>|")]
|
|
#[case(b"|o>")]
|
|
#[case(b"|o>>")]
|
|
#[case(b"|e>")]
|
|
#[case(b"|e>>")]
|
|
#[case(b"|o+e>")]
|
|
#[case(b"|o+e>>")]
|
|
#[case(b"|e>|")]
|
|
#[case(b"|o+e>|")]
|
|
#[case(b"e> file")]
|
|
#[case(b"e>> file")]
|
|
#[case(b"o> file")]
|
|
#[case(b"o>> file")]
|
|
#[case(b"o+e> file")]
|
|
#[case(b"o+e>> file")]
|
|
#[case(b"|e> file")]
|
|
#[case(b"|e>> file")]
|
|
#[case(b"|o> file")]
|
|
#[case(b"|o>> file")]
|
|
#[case(b"|o+e> file")]
|
|
#[case(b"|o+e>> file")]
|
|
fn test_redirecting_nothing(#[case] text: &[u8]) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, text, true);
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::UnexpectedRedirection { .. })
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn test_nothing_comparison_neq() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, b"2 != null", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert!(matches!(&element.expr.expr, Expr::BinaryOp(..)));
|
|
}
|
|
|
|
mod string {
|
|
use super::*;
|
|
|
|
#[test]
|
|
pub fn parse_string() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"\"hello nushell\"", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
assert_eq!(element.expr.expr, Expr::String("hello nushell".to_string()))
|
|
}
|
|
|
|
mod interpolation {
|
|
use nu_protocol::Span;
|
|
|
|
use super::*;
|
|
|
|
#[test]
|
|
pub fn parse_string_interpolation() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"$\"hello (39 + 3)\"", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let subexprs: Vec<&Expr> = match &element.expr.expr {
|
|
Expr::StringInterpolation(expressions) => {
|
|
expressions.iter().map(|e| &e.expr).collect()
|
|
}
|
|
_ => panic!("Expected an `Expr::StringInterpolation`"),
|
|
};
|
|
|
|
assert_eq!(subexprs.len(), 2);
|
|
|
|
assert_eq!(subexprs[0], &Expr::String("hello ".to_string()));
|
|
|
|
assert!(matches!(subexprs[1], &Expr::FullCellPath(..)));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_string_interpolation_escaped_parenthesis() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"$\"hello \\(39 + 3)\"", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let subexprs: Vec<&Expr> = match &element.expr.expr {
|
|
Expr::StringInterpolation(expressions) => {
|
|
expressions.iter().map(|e| &e.expr).collect()
|
|
}
|
|
_ => panic!("Expected an `Expr::StringInterpolation`"),
|
|
};
|
|
|
|
assert_eq!(subexprs.len(), 1);
|
|
|
|
assert_eq!(subexprs[0], &Expr::String("hello (39 + 3)".to_string()));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_string_interpolation_escaped_backslash_before_parenthesis() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"$\"hello \\\\(39 + 3)\"", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let subexprs: Vec<&Expr> = match &element.expr.expr {
|
|
Expr::StringInterpolation(expressions) => {
|
|
expressions.iter().map(|e| &e.expr).collect()
|
|
}
|
|
_ => panic!("Expected an `Expr::StringInterpolation`"),
|
|
};
|
|
|
|
assert_eq!(subexprs.len(), 2);
|
|
|
|
assert_eq!(subexprs[0], &Expr::String("hello \\".to_string()));
|
|
|
|
assert!(matches!(subexprs[1], &Expr::FullCellPath(..)));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_string_interpolation_backslash_count_reset_by_expression() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"$\"\\(1 + 3)\\(7 - 5)\"", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let subexprs: Vec<&Expr> = match &element.expr.expr {
|
|
Expr::StringInterpolation(expressions) => {
|
|
expressions.iter().map(|e| &e.expr).collect()
|
|
}
|
|
_ => panic!("Expected an `Expr::StringInterpolation`"),
|
|
};
|
|
|
|
assert_eq!(subexprs.len(), 1);
|
|
assert_eq!(subexprs[0], &Expr::String("(1 + 3)(7 - 5)".to_string()));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_string_interpolation_bare() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"\"\" ++ foo(1 + 3)bar(7 - 5)",
|
|
true,
|
|
);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let subexprs: Vec<&Expr> = match &element.expr.expr {
|
|
Expr::BinaryOp(_, _, rhs) => match &rhs.expr {
|
|
Expr::StringInterpolation(expressions) => {
|
|
expressions.iter().map(|e| &e.expr).collect()
|
|
}
|
|
_ => panic!("Expected an `Expr::StringInterpolation`"),
|
|
},
|
|
_ => panic!("Expected an `Expr::BinaryOp`"),
|
|
};
|
|
|
|
assert_eq!(subexprs.len(), 4);
|
|
|
|
assert_eq!(subexprs[0], &Expr::String("foo".to_string()));
|
|
assert!(matches!(subexprs[1], &Expr::FullCellPath(..)));
|
|
assert_eq!(subexprs[2], &Expr::String("bar".to_string()));
|
|
assert!(matches!(subexprs[3], &Expr::FullCellPath(..)));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_string_interpolation_bare_starting_subexpr() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"\"\" ++ (1 + 3)foo(7 - 5)bar",
|
|
true,
|
|
);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let subexprs: Vec<&Expr> = match &element.expr.expr {
|
|
Expr::BinaryOp(_, _, rhs) => match &rhs.expr {
|
|
Expr::StringInterpolation(expressions) => {
|
|
expressions.iter().map(|e| &e.expr).collect()
|
|
}
|
|
_ => panic!("Expected an `Expr::StringInterpolation`"),
|
|
},
|
|
_ => panic!("Expected an `Expr::BinaryOp`"),
|
|
};
|
|
|
|
assert_eq!(subexprs.len(), 4);
|
|
|
|
assert!(matches!(subexprs[0], &Expr::FullCellPath(..)));
|
|
assert_eq!(subexprs[1], &Expr::String("foo".to_string()));
|
|
assert!(matches!(subexprs[2], &Expr::FullCellPath(..)));
|
|
assert_eq!(subexprs[3], &Expr::String("bar".to_string()));
|
|
}
|
|
|
|
/// PR with summary of the issue: https://github.com/nushell/nushell/pull/16235
|
|
/// Release Notes Mention: https://www.nushell.sh/blog/2025-07-23-nushell_0_106_0.html#regression-bare-word-interpolation-on-both-sides-does-not-work-toc
|
|
#[test]
|
|
pub fn parse_string_interpolation_bare_starting_and_ending_subexpr() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"(100 + 20 + 3)/bar/(300 + 20 + 1)",
|
|
true,
|
|
);
|
|
|
|
assert!(working_set.parse_errors.is_empty(),);
|
|
|
|
let [pipeline] = block.pipelines.as_slice() else {
|
|
panic!("expected 1 pipeline")
|
|
};
|
|
let [element] = pipeline.elements.as_slice() else {
|
|
panic!("expected 1 pipeline element")
|
|
};
|
|
assert!(element.redirection.is_none());
|
|
|
|
let Expr::StringInterpolation(expressions) = &element.expr.expr else {
|
|
panic!("Expected an `Expr::StringInterpolation`")
|
|
};
|
|
let subexprs: Vec<_> = expressions.iter().map(|e| &e.expr).collect();
|
|
|
|
let [
|
|
Expr::FullCellPath(..),
|
|
Expr::String(s),
|
|
Expr::FullCellPath(..),
|
|
] = subexprs.as_slice()
|
|
else {
|
|
panic!("AST does not have the expected structure")
|
|
};
|
|
assert_eq!(s, "/bar/");
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_string_interpolation_bare_starting_subexpr_external_arg() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"^echo ($nu.home-dir)/path", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let subexprs: Vec<&Expr> = match &element.expr.expr {
|
|
Expr::ExternalCall(_, args) => match &args[0] {
|
|
ExternalArgument::Regular(expression) => match &expression.expr {
|
|
Expr::StringInterpolation(expressions) => {
|
|
expressions.iter().map(|e| &e.expr).collect()
|
|
}
|
|
_ => panic!("Expected an `ExternalArgument::Regular`"),
|
|
},
|
|
_ => panic!("Expected an `Expr::StringInterpolation`"),
|
|
},
|
|
_ => panic!("Expected an `Expr::BinaryOp`"),
|
|
};
|
|
|
|
assert_eq!(subexprs.len(), 2);
|
|
|
|
assert!(matches!(subexprs[0], &Expr::FullCellPath(..)));
|
|
assert_eq!(subexprs[1], &Expr::String("/path".to_string()));
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_nested_expressions() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_variable(
|
|
"foo".to_string().into_bytes(),
|
|
Span::new(0, 0),
|
|
nu_protocol::Type::CellPath,
|
|
false,
|
|
);
|
|
|
|
parse(
|
|
&mut working_set,
|
|
None,
|
|
br#"
|
|
$"(($foo))"
|
|
"#,
|
|
true,
|
|
);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_path_expression() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_variable(
|
|
"foo".to_string().into_bytes(),
|
|
Span::new(0, 0),
|
|
nu_protocol::Type::CellPath,
|
|
false,
|
|
);
|
|
|
|
parse(
|
|
&mut working_set,
|
|
None,
|
|
br#"
|
|
$"Hello ($foo.bar)"
|
|
"#,
|
|
true,
|
|
);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_string_interpolation_unclosed_subexpression() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"$\"foo (2 + 3\"", true);
|
|
assert_eq!(block.len(), 1);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
|
|
let subexprs: Vec<&Expr> = match &element.expr.expr {
|
|
Expr::StringInterpolation(expressions) => {
|
|
expressions.iter().map(|e| &e.expr).collect()
|
|
}
|
|
_ => panic!("Expected an `Expr::StringInterpolation`"),
|
|
};
|
|
|
|
assert_eq!(subexprs.len(), 2);
|
|
|
|
assert!(working_set.parse_errors.iter().any(
|
|
|err| matches!(err, ParseError::Unclosed(delimiter, ..) if *delimiter == ")")
|
|
));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_raw_string_as_external_argument() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"^echo r#'text'#", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1);
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
if let Expr::ExternalCall(_, args) = &element.expr.expr
|
|
&& let [ExternalArgument::Regular(expr)] = args.as_ref()
|
|
{
|
|
assert_eq!(expr.expr, Expr::RawString("text".into()));
|
|
return;
|
|
}
|
|
|
|
panic!("wrong expression: {:?}", element.expr.expr)
|
|
}
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(b"let a = }")]
|
|
#[case(b"mut a = }")]
|
|
#[case(b"let a = | }")]
|
|
#[case(b"mut a = | }")]
|
|
fn test_semi_open_brace(#[case] phrase: &[u8]) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
// this should not panic
|
|
let _block = parse(&mut working_set, None, phrase, true);
|
|
}
|
|
|
|
mod range {
|
|
use super::*;
|
|
use nu_protocol::ast::{RangeInclusion, RangeOperator};
|
|
|
|
#[rstest]
|
|
#[case(b"0..10", RangeInclusion::Inclusive, "inclusive")]
|
|
#[case(b"0..=10", RangeInclusion::Inclusive, "=inclusive")]
|
|
#[case(b"0..<10", RangeInclusion::RightExclusive, "exclusive")]
|
|
#[case(b"10..0", RangeInclusion::Inclusive, "reverse inclusive")]
|
|
#[case(b"10..=0", RangeInclusion::Inclusive, "reverse =inclusive")]
|
|
#[case(
|
|
b"(3 - 3)..<(8 + 2)",
|
|
RangeInclusion::RightExclusive,
|
|
"subexpression exclusive"
|
|
)]
|
|
#[case(
|
|
b"(3 - 3)..(8 + 2)",
|
|
RangeInclusion::Inclusive,
|
|
"subexpression inclusive"
|
|
)]
|
|
#[case(
|
|
b"(3 - 3)..=(8 + 2)",
|
|
RangeInclusion::Inclusive,
|
|
"subexpression =inclusive"
|
|
)]
|
|
#[case(b"-10..-3", RangeInclusion::Inclusive, "negative inclusive")]
|
|
#[case(b"-10..=-3", RangeInclusion::Inclusive, "negative =inclusive")]
|
|
#[case(b"-10..<-3", RangeInclusion::RightExclusive, "negative exclusive")]
|
|
|
|
fn parse_bounded_range(
|
|
#[case] phrase: &[u8],
|
|
#[case] inclusion: RangeInclusion,
|
|
#[case] tag: &str,
|
|
) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, phrase, true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1, "{tag}: block length");
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1, "{tag}: expression length");
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
if let Expr::Range(range) = &element.expr.expr {
|
|
if let Range {
|
|
from: Some(_),
|
|
next: None,
|
|
to: Some(_),
|
|
operator:
|
|
RangeOperator {
|
|
inclusion: the_inclusion,
|
|
..
|
|
},
|
|
} = range.as_ref()
|
|
{
|
|
assert_eq!(
|
|
*the_inclusion, inclusion,
|
|
"{tag}: wrong RangeInclusion {the_inclusion:?}"
|
|
);
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
}
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
};
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(
|
|
b"let a = 2; $a..10",
|
|
RangeInclusion::Inclusive,
|
|
"variable start inclusive"
|
|
)]
|
|
#[case(
|
|
b"let a = 2; $a..=10",
|
|
RangeInclusion::Inclusive,
|
|
"variable start =inclusive"
|
|
)]
|
|
#[case(
|
|
b"let a = 2; $a..<($a + 10)",
|
|
RangeInclusion::RightExclusive,
|
|
"subexpression variable exclusive"
|
|
)]
|
|
fn parse_variable_range(
|
|
#[case] phrase: &[u8],
|
|
#[case] inclusion: RangeInclusion,
|
|
#[case] tag: &str,
|
|
) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Let));
|
|
|
|
let block = parse(&mut working_set, None, phrase, true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 2, "{tag} block len 2");
|
|
|
|
let pipeline = &block.pipelines[1];
|
|
assert_eq!(pipeline.len(), 1, "{tag}: expression length 1");
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
if let Expr::Range(range) = &element.expr.expr {
|
|
if let Range {
|
|
from: Some(_),
|
|
next: None,
|
|
to: Some(_),
|
|
operator:
|
|
RangeOperator {
|
|
inclusion: the_inclusion,
|
|
..
|
|
},
|
|
} = range.as_ref()
|
|
{
|
|
assert_eq!(
|
|
*the_inclusion, inclusion,
|
|
"{tag}: wrong RangeInclusion {the_inclusion:?}"
|
|
);
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
}
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
};
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(b"0..", RangeInclusion::Inclusive, "right unbounded")]
|
|
#[case(b"0..=", RangeInclusion::Inclusive, "right unbounded =inclusive")]
|
|
#[case(b"0..<", RangeInclusion::RightExclusive, "right unbounded")]
|
|
|
|
fn parse_right_unbounded_range(
|
|
#[case] phrase: &[u8],
|
|
#[case] inclusion: RangeInclusion,
|
|
#[case] tag: &str,
|
|
) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, phrase, true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1, "{tag}: block len 1");
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1, "{tag}: expression length");
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
if let Expr::Range(range) = &element.expr.expr {
|
|
if let Range {
|
|
from: Some(_),
|
|
next: None,
|
|
to: None,
|
|
operator:
|
|
RangeOperator {
|
|
inclusion: the_inclusion,
|
|
..
|
|
},
|
|
} = range.as_ref()
|
|
{
|
|
assert_eq!(
|
|
*the_inclusion, inclusion,
|
|
"{tag}: wrong RangeInclusion {the_inclusion:?}"
|
|
);
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
}
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
};
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(b"..10", RangeInclusion::Inclusive, "left unbounded inclusive")]
|
|
#[case(b"..=10", RangeInclusion::Inclusive, "left unbounded =inclusive")]
|
|
#[case(b"..<10", RangeInclusion::RightExclusive, "left unbounded exclusive")]
|
|
|
|
fn parse_left_unbounded_range(
|
|
#[case] phrase: &[u8],
|
|
#[case] inclusion: RangeInclusion,
|
|
#[case] tag: &str,
|
|
) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, phrase, true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1, "{tag}: block len 1");
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1, "{tag}: expression length");
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
if let Expr::Range(range) = &element.expr.expr {
|
|
if let Range {
|
|
from: None,
|
|
next: None,
|
|
to: Some(_),
|
|
operator:
|
|
RangeOperator {
|
|
inclusion: the_inclusion,
|
|
..
|
|
},
|
|
} = range.as_ref()
|
|
{
|
|
assert_eq!(
|
|
*the_inclusion, inclusion,
|
|
"{tag}: wrong RangeInclusion {the_inclusion:?}"
|
|
);
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
}
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
};
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(b"2.0..4.0..10.0", RangeInclusion::Inclusive, "float inclusive")]
|
|
#[case(b"2.0..4.0..=10.0", RangeInclusion::Inclusive, "float =inclusive")]
|
|
#[case(b"2.0..4.0..<10.0", RangeInclusion::RightExclusive, "float exclusive")]
|
|
|
|
fn parse_float_range(
|
|
#[case] phrase: &[u8],
|
|
#[case] inclusion: RangeInclusion,
|
|
#[case] tag: &str,
|
|
) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, phrase, true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1, "{tag}: block length 1");
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 1, "{tag}: expression length");
|
|
let element = &pipeline.elements[0];
|
|
assert!(element.redirection.is_none());
|
|
if let Expr::Range(range) = &element.expr.expr {
|
|
if let Range {
|
|
from: Some(_),
|
|
next: Some(_),
|
|
to: Some(_),
|
|
operator:
|
|
RangeOperator {
|
|
inclusion: the_inclusion,
|
|
..
|
|
},
|
|
} = range.as_ref()
|
|
{
|
|
assert_eq!(
|
|
*the_inclusion, inclusion,
|
|
"{tag}: wrong RangeInclusion {the_inclusion:?}"
|
|
);
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
}
|
|
} else {
|
|
panic!("{tag}: expression mismatch.")
|
|
};
|
|
}
|
|
|
|
#[test]
|
|
fn bad_parse_does_crash() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let _ = parse(&mut working_set, None, b"(0)..\"a\"", true);
|
|
|
|
assert!(!working_set.parse_errors.is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn vars_not_read_as_units() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let _ = parse(&mut working_set, None, b"0..<$day", true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("(to-custom)..")]
|
|
#[case("..(to-custom)")]
|
|
#[case("(to-custom)..0")]
|
|
#[case("..(to-custom)..0")]
|
|
#[case("(to-custom)..0..")]
|
|
#[case("(to-custom)..0..1")]
|
|
#[case("0..(to-custom)")]
|
|
#[case("0..(to-custom)..")]
|
|
#[case("0..(to-custom)..1")]
|
|
#[case("..1..(to-custom)")]
|
|
#[case("0..1..(to-custom)")]
|
|
fn type_mismatch_errors(#[case] code: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(ToCustom));
|
|
|
|
let _ = parse(&mut working_set, None, code.as_bytes(), true);
|
|
|
|
assert!(matches!(
|
|
&working_set.parse_errors[..],
|
|
[ParseError::OperatorUnsupportedType { .. }]
|
|
),);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("true or ((to-custom) < (to-custom))")]
|
|
#[case("true and ((to-custom) == (to-custom))")]
|
|
#[case("true or ((to-custom) in (to-custom))")]
|
|
fn custom_comparison_is_usable_as_bool(#[case] code: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(ToCustom));
|
|
|
|
let _ = parse(&mut working_set, None, code.as_bytes(), true);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"Errors: {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn raw_custom_is_not_a_bool_for_or() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(ToCustom));
|
|
|
|
let _ = parse(&mut working_set, None, b"true or (to-custom)", true);
|
|
|
|
assert!(matches!(
|
|
&working_set.parse_errors[..],
|
|
[ParseError::OperatorIncompatibleTypes { .. }]
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn dont_mess_with_external_calls() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(ToCustom));
|
|
|
|
let result = parse(&mut working_set, None, b"../foo", true);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"Errors: {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
let expr = &result.pipelines[0].elements[0].expr.expr;
|
|
assert!(
|
|
matches!(expr, Expr::ExternalCall(..)),
|
|
"Should've been parsed as a call"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod mock {
|
|
use super::*;
|
|
use nu_engine::CallExt;
|
|
use nu_protocol::{
|
|
Category, IntoPipelineData, PipelineData, ShellError, Type, Value,
|
|
engine::{Call, 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 run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
|
|
fn run_const(
|
|
&self,
|
|
_working_set: &StateWorkingSet,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
Ok(PipelineData::empty())
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Let;
|
|
|
|
impl Command for Let {
|
|
fn name(&self) -> &str {
|
|
"let"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Create a variable and give it a value."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build("let")
|
|
.required("var_name", SyntaxShape::VarWithOptType, "Variable name.")
|
|
.required(
|
|
"initial_value",
|
|
SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)),
|
|
"Equals sign followed by value.",
|
|
)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Mut;
|
|
|
|
impl Command for Mut {
|
|
fn name(&self) -> &str {
|
|
"mut"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock mut command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build("mut")
|
|
.required("var_name", SyntaxShape::VarWithOptType, "Variable name.")
|
|
.required(
|
|
"initial_value",
|
|
SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)),
|
|
"Equals sign followed by value.",
|
|
)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
#[derive(Clone)]
|
|
pub struct LsTest;
|
|
|
|
impl Command for LsTest {
|
|
fn name(&self) -> &str {
|
|
"ls"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock ls command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name()).category(Category::Default)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct LsCustom;
|
|
|
|
impl Command for LsCustom {
|
|
fn name(&self) -> &str {
|
|
"ls"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock custom ls command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name()).category(Category::Default)
|
|
}
|
|
|
|
fn command_type(&self) -> CommandType {
|
|
CommandType::Custom
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Def;
|
|
|
|
impl Command for Def {
|
|
fn name(&self) -> &str {
|
|
"def"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock def command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build("def")
|
|
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
|
|
.required("def_name", SyntaxShape::String, "Definition name.")
|
|
.required("params", SyntaxShape::Signature, "Parameters.")
|
|
.required(
|
|
"body",
|
|
SyntaxShape::Closure(None),
|
|
"Body of the definition.",
|
|
)
|
|
.category(Category::Core)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Extern;
|
|
|
|
impl Command for Extern {
|
|
fn name(&self) -> &str {
|
|
"extern"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock extern command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build("extern")
|
|
.input_output_types(vec![(Type::Nothing, Type::Nothing)])
|
|
.required("def_name", SyntaxShape::String, "Definition name.")
|
|
.required("params", SyntaxShape::ExternalSignature, "Parameters.")
|
|
.category(Category::Core)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Alias;
|
|
|
|
impl Command for Alias {
|
|
fn name(&self) -> &str {
|
|
"alias"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock alias command."
|
|
}
|
|
|
|
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 run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct AttrEcho;
|
|
|
|
impl Command for AttrEcho {
|
|
fn name(&self) -> &str {
|
|
"attr echo"
|
|
}
|
|
|
|
fn signature(&self) -> Signature {
|
|
Signature::build("attr echo").required(
|
|
"value",
|
|
SyntaxShape::Any,
|
|
"Value to store as an attribute.",
|
|
)
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Add an arbitrary value as an attribute to a command"
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
engine_state: &EngineState,
|
|
stack: &mut Stack,
|
|
call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
let value: Value = call.req(engine_state, stack, 0)?;
|
|
Ok(value.into_pipeline_data())
|
|
}
|
|
|
|
fn is_const(&self) -> bool {
|
|
true
|
|
}
|
|
|
|
fn run_const(
|
|
&self,
|
|
working_set: &StateWorkingSet,
|
|
stack: &mut Stack,
|
|
call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
let value: Value = call.req_const(working_set, stack, 0)?;
|
|
Ok(value.into_pipeline_data())
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct GroupBy;
|
|
|
|
impl Command for GroupBy {
|
|
fn name(&self) -> &str {
|
|
"group-by"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock group-by command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name())
|
|
.required("column", SyntaxShape::String, "Column name.")
|
|
.category(Category::Default)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct ToCustom;
|
|
|
|
impl Command for ToCustom {
|
|
fn name(&self) -> &str {
|
|
"to-custom"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock converter command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name())
|
|
.input_output_type(Type::Any, Type::Custom("custom".into()))
|
|
.category(Category::Custom("custom".into()))
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct GroupByCustom;
|
|
|
|
impl Command for GroupByCustom {
|
|
fn name(&self) -> &str {
|
|
"group-by"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock custom group-by command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name())
|
|
.required("column", SyntaxShape::String, "Column name.")
|
|
.required("other", SyntaxShape::String, "Other value.")
|
|
.input_output_type(Type::Custom("custom".into()), Type::Custom("custom".into()))
|
|
.category(Category::Custom("custom".into()))
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct AggCustom;
|
|
|
|
impl Command for AggCustom {
|
|
fn name(&self) -> &str {
|
|
"agg"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock custom agg command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name())
|
|
.required("operation", SyntaxShape::String, "Operation.")
|
|
.input_output_type(Type::Custom("custom".into()), Type::Custom("custom".into()))
|
|
.category(Category::Custom("custom".into()))
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct AggMin;
|
|
|
|
impl Command for AggMin {
|
|
fn name(&self) -> &str {
|
|
"min"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock custom min command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name()).category(Category::Custom("custom".into()))
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct WithColumn;
|
|
|
|
impl Command for WithColumn {
|
|
fn name(&self) -> &str {
|
|
"with-column"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock custom with-column command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name())
|
|
.rest("operation", SyntaxShape::Any, "operation")
|
|
.input_output_type(Type::Custom("custom".into()), Type::Custom("custom".into()))
|
|
.category(Category::Custom("custom".into()))
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Collect;
|
|
|
|
impl Command for Collect {
|
|
fn name(&self) -> &str {
|
|
"collect"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock custom collect command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build(self.name())
|
|
.input_output_type(Type::Custom("custom".into()), Type::Custom("custom".into()))
|
|
.category(Category::Custom("custom".into()))
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct IfMocked;
|
|
|
|
impl Command for IfMocked {
|
|
fn name(&self) -> &str {
|
|
"if"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock if command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build("if")
|
|
.required("cond", SyntaxShape::MathExpression, "Condition to check.")
|
|
.required(
|
|
"then_block",
|
|
SyntaxShape::Block,
|
|
"Block to run if check succeeds.",
|
|
)
|
|
.optional(
|
|
"else_expression",
|
|
SyntaxShape::Keyword(
|
|
b"else".to_vec(),
|
|
Box::new(SyntaxShape::OneOf(vec![
|
|
SyntaxShape::Block,
|
|
SyntaxShape::Expression,
|
|
])),
|
|
),
|
|
"Expression or block to run if check fails.",
|
|
)
|
|
.category(Category::Core)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
|
|
fn command_type(&self) -> CommandType {
|
|
CommandType::Keyword
|
|
}
|
|
|
|
fn is_const(&self) -> bool {
|
|
true
|
|
}
|
|
|
|
fn run_const(
|
|
&self,
|
|
_working_set: &StateWorkingSet,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
panic!("Should not be called!")
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct MatchMocked;
|
|
|
|
impl Command for MatchMocked {
|
|
fn name(&self) -> &str {
|
|
"match"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Conditionally run a block on a matched value."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build("match")
|
|
.input_output_types(vec![(Type::Any, Type::Any)])
|
|
.required("value", SyntaxShape::Any, "Value to check.")
|
|
.required(
|
|
"match_block",
|
|
SyntaxShape::MatchBlock,
|
|
"Block to run if check succeeds.",
|
|
)
|
|
.category(Category::Core)
|
|
}
|
|
|
|
fn command_type(&self) -> CommandType {
|
|
CommandType::Keyword
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Where;
|
|
|
|
impl Command for Where {
|
|
fn name(&self) -> &str {
|
|
"where"
|
|
}
|
|
|
|
fn description(&self) -> &str {
|
|
"Mock `where` command."
|
|
}
|
|
|
|
fn signature(&self) -> nu_protocol::Signature {
|
|
Signature::build("where")
|
|
.input_output_types(vec![
|
|
(
|
|
Type::List(Box::new(Type::Any)),
|
|
Type::List(Box::new(Type::Any)),
|
|
),
|
|
(Type::table(), Type::table()),
|
|
(Type::Range, Type::Any),
|
|
])
|
|
.required(
|
|
"condition",
|
|
SyntaxShape::RowCondition,
|
|
"Filter row condition or closure.",
|
|
)
|
|
.allow_variants_without_examples(true)
|
|
.category(Category::Filters)
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_engine_state: &EngineState,
|
|
_stack: &mut Stack,
|
|
_call: &Call,
|
|
_input: PipelineData,
|
|
) -> Result<PipelineData, ShellError> {
|
|
todo!()
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod input_types {
|
|
use super::*;
|
|
use mock::*;
|
|
use nu_protocol::ast::Argument;
|
|
|
|
fn add_declarations(engine_state: &mut EngineState) {
|
|
let delta = {
|
|
let mut working_set = StateWorkingSet::new(engine_state);
|
|
working_set.add_decl(Box::new(Let));
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(AggCustom));
|
|
working_set.add_decl(Box::new(GroupByCustom));
|
|
working_set.add_decl(Box::new(GroupBy));
|
|
working_set.add_decl(Box::new(LsTest));
|
|
working_set.add_decl(Box::new(ToCustom));
|
|
working_set.add_decl(Box::new(AggMin));
|
|
working_set.add_decl(Box::new(Collect));
|
|
working_set.add_decl(Box::new(WithColumn));
|
|
working_set.add_decl(Box::new(IfMocked));
|
|
working_set.add_decl(Box::new(MatchMocked));
|
|
working_set.add_decl(Box::new(Mut));
|
|
|
|
working_set.render()
|
|
};
|
|
|
|
engine_state
|
|
.merge_delta(delta)
|
|
.expect("Error merging delta");
|
|
}
|
|
|
|
#[test]
|
|
fn call_non_custom_types_test() {
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let input = "ls | group-by name";
|
|
|
|
let block = parse(&mut working_set, None, input.as_bytes(), true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 2);
|
|
assert!(pipeline.elements[0].redirection.is_none());
|
|
assert!(pipeline.elements[1].redirection.is_none());
|
|
|
|
match &pipeline.elements[0].expr.expr {
|
|
Expr::Call(call) => {
|
|
let expected_id = working_set.find_decl(b"ls").unwrap();
|
|
assert_eq!(call.decl_id, expected_id)
|
|
}
|
|
_ => panic!("Expected expression Call not found"),
|
|
}
|
|
|
|
match &pipeline.elements[1].expr.expr {
|
|
Expr::Call(call) => {
|
|
let expected_id = working_set.find_decl(b"group-by").unwrap();
|
|
assert_eq!(call.decl_id, expected_id)
|
|
}
|
|
_ => panic!("Expected expression Call not found"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn nested_operations_test() {
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
|
|
let (block, delta) = {
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let input = r#"ls | to-custom | group-by name other | agg ("b" | min)"#;
|
|
let block = parse(&mut working_set, None, input.as_bytes(), true);
|
|
|
|
(block, working_set.render())
|
|
};
|
|
|
|
engine_state.merge_delta(delta).unwrap();
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert!(pipeline.elements[3].redirection.is_none());
|
|
match &pipeline.elements[3].expr.expr {
|
|
Expr::Call(call) => {
|
|
let arg = &call.arguments[0];
|
|
match arg {
|
|
Argument::Positional(a) => match &a.expr {
|
|
Expr::FullCellPath(path) => match &path.head.expr {
|
|
Expr::Subexpression(id) => {
|
|
let block = engine_state.get_block(*id);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.len(), 2);
|
|
assert!(pipeline.elements[1].redirection.is_none());
|
|
|
|
match &pipeline.elements[1].expr.expr {
|
|
Expr::Call(call) => {
|
|
let working_set = StateWorkingSet::new(&engine_state);
|
|
let expected_id = working_set.find_decl(b"min").unwrap();
|
|
assert_eq!(call.decl_id, expected_id)
|
|
}
|
|
_ => panic!("Expected expression Call not found"),
|
|
}
|
|
}
|
|
_ => panic!("Expected Subexpression not found"),
|
|
},
|
|
_ => panic!("Expected FullCellPath not found"),
|
|
},
|
|
_ => panic!("Expected Argument Positional not found"),
|
|
}
|
|
}
|
|
_ => panic!("Expected expression Call not found"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn call_with_list_test() {
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let input = r#"[[a b]; [1 2] [3 4]] | to-custom | with-column [ ("a" | min) ("b" | min) ] | collect"#;
|
|
|
|
let block = parse(&mut working_set, None, input.as_bytes(), true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 1);
|
|
|
|
let pipeline = &block.pipelines[0];
|
|
assert!(pipeline.elements[2].redirection.is_none());
|
|
assert!(pipeline.elements[3].redirection.is_none());
|
|
|
|
match &pipeline.elements[2].expr.expr {
|
|
Expr::Call(call) => {
|
|
let expected_id = working_set.find_decl(b"with-column").unwrap();
|
|
assert_eq!(call.decl_id, expected_id)
|
|
}
|
|
_ => panic!("Expected expression Call not found"),
|
|
}
|
|
|
|
match &pipeline.elements[3].expr.expr {
|
|
Expr::Call(call) => {
|
|
let expected_id = working_set.find_decl(b"collect").unwrap();
|
|
assert_eq!(call.decl_id, expected_id)
|
|
}
|
|
_ => panic!("Expected expression Call not found"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn comments_within_blocks_test() {
|
|
// https://github.com/nushell/nushell/issues/15305
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let input = "def dummy []: int -> int { $in }";
|
|
parse(&mut working_set, None, input.as_bytes(), true);
|
|
|
|
for prefix in ["let ", "mut ", "mut foo = 1; $"] {
|
|
let input = format!(
|
|
"{prefix}foo = 1 |
|
|
# comment
|
|
dummy"
|
|
);
|
|
let block = parse(&mut working_set, None, input.as_bytes(), true);
|
|
let last_expr = &block.pipelines.last().unwrap().elements[0].expr.expr;
|
|
let block_expr = match last_expr {
|
|
Expr::Call(call) => {
|
|
assert_eq!(call.arguments.len(), 2);
|
|
call.arguments[1].expr().unwrap()
|
|
}
|
|
Expr::BinaryOp(_, _, rhs) => rhs.as_ref(),
|
|
_ => panic!("Unexpected expression: {last_expr:?}"),
|
|
};
|
|
let block_id = match block_expr.expr {
|
|
Expr::Block(block_id) | Expr::Subexpression(block_id) => block_id,
|
|
_ => panic!("Unexpected expression: {block_expr:?}"),
|
|
};
|
|
let rhs_expr = working_set.get_block(block_id);
|
|
assert_eq!(rhs_expr.pipelines.len(), 1);
|
|
assert_eq!(rhs_expr.pipelines[0].elements.len(), 2);
|
|
assert!(working_set.parse_errors.is_empty());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn operations_within_blocks_test() {
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let inputs = vec![
|
|
"let a = 'b'; ($a == 'b') or ($a == 'b')",
|
|
"let a = 'b'; ($a == 'b') or ($a == 'b') and ($a == 'b')",
|
|
"let a = 1; ($a == 1) or ($a == 2) and ($a == 3)",
|
|
"let a = 'b'; if ($a == 'b') or ($a == 'b') { true } else { false }",
|
|
"let a = 1; if ($a == 1) or ($a > 0) { true } else { false }",
|
|
];
|
|
|
|
for input in inputs {
|
|
let block = parse(&mut working_set, None, input.as_bytes(), true);
|
|
|
|
assert!(working_set.parse_errors.is_empty());
|
|
assert_eq!(block.len(), 2, "testing: {input}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn closure_in_block_position_errors_correctly() {
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let inputs = ["if true { || print hi }", "if true { |x| $x }"];
|
|
|
|
for input in inputs {
|
|
parse(&mut working_set, None, input.as_bytes(), true);
|
|
assert!(
|
|
matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::Mismatch(_, _, _))
|
|
),
|
|
"testing: {input}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn else_errors_correctly() {
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"if false { 'a' } else { $foo }",
|
|
true,
|
|
);
|
|
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::VariableNotFound(_, _))
|
|
));
|
|
|
|
let element = &block
|
|
.pipelines
|
|
.first()
|
|
.unwrap()
|
|
.elements
|
|
.first()
|
|
.unwrap()
|
|
.expr;
|
|
let Expr::Call(call) = &element.expr else {
|
|
panic!("Expected Expr::Call, but found {:?}", element.expr);
|
|
};
|
|
let Expr::Keyword(else_kwd) = &call
|
|
.arguments
|
|
.get(2)
|
|
.expect("This call of `if` should have 3 arguments")
|
|
.expr()
|
|
.unwrap()
|
|
.expr
|
|
else {
|
|
panic!("Expected Expr::Keyword");
|
|
};
|
|
assert!(!matches!(else_kwd.expr.expr, Expr::Garbage))
|
|
}
|
|
|
|
#[test]
|
|
fn else_if_errors_correctly() {
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
parse(
|
|
&mut working_set,
|
|
None,
|
|
b"if false { 'a' } else $foo { 'b' }",
|
|
true,
|
|
);
|
|
|
|
assert!(matches!(
|
|
working_set.parse_errors.first(),
|
|
Some(ParseError::VariableNotFound(_, _))
|
|
));
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::input_output(b"def q []: int -> int {1}", false)]
|
|
#[case::input_output(b"def q [x: bool]: int -> int {2}", false)]
|
|
#[case::input_output(b"def q []: string -> string {'qwe'}", false)]
|
|
#[case::input_output(b"def q []: nothing -> nothing {null}", false)]
|
|
#[case::input_output(b"def q []: list<string> -> list<string> {[]}", false)]
|
|
#[case::input_output(
|
|
b"def q []: record<a: int b: int> -> record<c: int e: int> {{c: 1 e: 1}}",
|
|
false
|
|
)]
|
|
#[case::input_output(
|
|
b"def q []: table<a: int b: int> -> table<c: int e: int> {[{c: 1 e: 1}]}",
|
|
false
|
|
)]
|
|
#[case::input_output(
|
|
b"def q []: nothing -> record<c: record<a: int b: int> e: int> {{c: {a: 1 b: 2} e: 1}}",
|
|
false
|
|
)]
|
|
#[case::input_output_pass_through(b"def q []: int -> int {}", false)]
|
|
#[case::input_output_pass_through(b"def q []: string -> string {}", false)]
|
|
#[case::input_output_pass_through(b"def q []: [int -> int, string -> string] {}", false)]
|
|
#[case::input_output_pass_through(b"def q []: [int -> string, string -> int] {}", true)]
|
|
#[case::input_output_pass_through(
|
|
b"def q []: record<a: int, b: string> -> record<a: int, b: string> {}",
|
|
false
|
|
)]
|
|
#[case::input_output_pass_through_incorrect(b"def q []: int -> nothing {}", true)]
|
|
#[case::input_output_pass_through_incorrect(b"def q []: nothing -> int {}", true)]
|
|
#[case::input_output(b"def q []: nothing -> list<string {[]}", true)]
|
|
#[case::input_output(b"def q []: nothing -> record<c: int e: int {{c: 1 e: 1}}", true)]
|
|
#[case::input_output(b"def q []: record<c: int e: int -> record<a: int> {{a: 1}}", true)]
|
|
#[case::input_output(b"def q []: nothing -> record<a: record<a: int> {{a: {a: 1}}}", true)]
|
|
#[case::input_output(b"def q []: int []}", true)]
|
|
#[case::input_output(b"def q []: bool {[]", true)]
|
|
// Type signature variants with whitespace between inputs and `:`
|
|
#[case::input_output(b"def q [] : int -> int {1}", false)]
|
|
#[case::input_output(b"def q [x: bool] : int -> int {2}", false)]
|
|
#[case::input_output(b"def q []\t : string -> string {'qwe'}", false)]
|
|
#[case::input_output(b"def q [] \t : nothing -> nothing {null}", false)]
|
|
#[case::input_output(b"def q [] \t: list<string> -> list<string> {[]}", false)]
|
|
#[case::input_output(
|
|
b"def q []\t: record<a: int b: int> -> record<c: int e: int> {{c: 1 e: 1}}",
|
|
false
|
|
)]
|
|
#[case::input_output(
|
|
b"def q [] : table<a: int b: int> -> table<c: int e: int> {[{c: 1 e: 1}]}",
|
|
false
|
|
)]
|
|
#[case::input_output(
|
|
b"def q [] : nothing -> record<c: record<a: int b: int> e: int> {{c: {a: 1 b: 2} e: 1}}",
|
|
false
|
|
)]
|
|
#[case::input_output(b"def q [] : nothing -> list<string {[]}", true)]
|
|
#[case::input_output(b"def q [] : nothing -> record<c: int e: int {{c: 1 e: 1}}", true)]
|
|
#[case::input_output(b"def q [] : record<c: int e: int -> record<a: int> {{a: 1}}", true)]
|
|
#[case::input_output(b"def q [] : nothing -> record<a: record<a: int> {{a: {a: 1}}}", true)]
|
|
#[case::input_output(b"def q [] : int []}", true)]
|
|
#[case::input_output(b"def q [] : bool {[]", true)]
|
|
// No input-output type signature
|
|
#[case::input_output(b"def qq [] {[]}", false)]
|
|
#[case::input_output(b"def q [] []}", true)]
|
|
#[case::input_output(b"def q [] {", true)]
|
|
#[case::input_output(b"def q []: []}", true)]
|
|
#[case::input_output(b"def q [] int {}", true)]
|
|
#[case::input_output(b"def q [x: string, y: int] {{c: 1 e: 1}}", false)]
|
|
#[case::input_output(b"def q [x: string, y: int]: {}", true)]
|
|
#[case::input_output(b"def q [x: string, y: int] {a: {a: 1}}", true)]
|
|
#[case::input_output(b"def foo {3}", true)]
|
|
#[case::vardecl(b"let a: int = 1", false)]
|
|
#[case::vardecl(b"let a: string = 'qwe'", false)]
|
|
#[case::vardecl(b"let a: nothing = null", false)]
|
|
#[case::vardecl(b"let a: list<string> = []", false)]
|
|
#[case::vardecl(b"let a: record<a: int b: int> = {a: 1 b: 1}", false)]
|
|
#[case::vardecl(
|
|
b"let a: record<c: record<a: int b: int> e: int> = {c: {a: 1 b: 2} e: 1}",
|
|
false
|
|
)]
|
|
#[case::vardecl(b"let a: table<a: int b: int> = [[a b]; [1 1]]", false)]
|
|
#[case::vardecl(b"let a: list<string asd> = []", true)]
|
|
#[case::vardecl(b"let a: record<a: int b: record<a: int> = {a: 1 b: {a: 1}}", true)]
|
|
#[case::opt_param_is_nullable(b"def f [p?: int] { mut x = $p; $x = null }", false)]
|
|
#[case::flag_with_type_is_nullable(b"def f [--flag: int] { mut x = $flag; $x = null }", false)]
|
|
#[case::opt_param_with_default_is_not_nullable(
|
|
b"def f [p?: int = 42] { mut x = $p; $x = null }",
|
|
true
|
|
)]
|
|
#[case::flag_with_type_and_default_is_not_nullable(
|
|
b"def f [--flag: int = 42] { mut x = $flag; $x = null }",
|
|
true
|
|
)]
|
|
#[case::multiple_output_command_to_variable_oneof(
|
|
br#"
|
|
def str-or-int []: [nothing -> int, nothing -> string] { if (random bool) { 42 } else { "hello" } }
|
|
mut x = str-or-int
|
|
$x = "string"
|
|
$x = 42
|
|
"#,
|
|
false
|
|
)]
|
|
#[case::multiple_output_command_to_variable_not_any(
|
|
br#"
|
|
def str-or-int []: [nothing -> int, nothing -> string] { if (random bool) { 42 } else { "hello" } }
|
|
mut x = str-or-int
|
|
$x = [1 2 3]
|
|
"#,
|
|
true
|
|
)]
|
|
fn test_type_annotations(#[case] phrase: &[u8], #[case] expect_errors: bool) {
|
|
let mut engine_state = EngineState::new();
|
|
add_declarations(&mut engine_state);
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
// this should not panic
|
|
let _block = parse(&mut working_set, None, phrase, false);
|
|
// check that no parse errors happened
|
|
assert_eq!(
|
|
!working_set.parse_errors.is_empty(),
|
|
expect_errors,
|
|
"Got errors {:?}",
|
|
working_set.parse_errors
|
|
)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod operator {
|
|
use super::*;
|
|
|
|
#[rstest]
|
|
#[case(br#""abc" < "bca""#, "string < string")]
|
|
#[case(br#""abc" <= "bca""#, "string <= string")]
|
|
#[case(br#""abc" > "bca""#, "string > string")]
|
|
#[case(br#""abc" >= "bca""#, "string >= string")]
|
|
fn parse_comparison_operators_with_string_and_string(
|
|
#[case] expr: &[u8],
|
|
#[case] test_tag: &str,
|
|
) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
parse(&mut working_set, None, expr, false);
|
|
assert_eq!(
|
|
working_set.parse_errors.len(),
|
|
0,
|
|
"{test_tag}: expected to be parsed successfully, but failed."
|
|
);
|
|
}
|
|
}
|
|
|
|
mod record {
|
|
use super::*;
|
|
|
|
use nu_protocol::ast::RecordItem;
|
|
|
|
#[rstest]
|
|
#[case(b"{ :: x }", "Invalid literal")] // Key is bare colon
|
|
#[case(b"{ a: x:y }", "Invalid literal")] // Value is bare word with colon
|
|
#[case(b"{ a: x('y'):z }", "Invalid literal")] // Value is bare string interpolation with colon
|
|
#[case(b"{ ;: x }", "Unexpected token in record")] // Key is a non-item token
|
|
#[case(b"{ a: || }", "Unexpected token in record value")] // Value is a non-item token
|
|
fn refuse_confusing_record(#[case] expr: &[u8], #[case] error: &str) {
|
|
dbg!(String::from_utf8_lossy(expr));
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
parse(&mut working_set, None, expr, false);
|
|
assert_eq!(
|
|
working_set.parse_errors.first().map(|e| e.to_string()),
|
|
Some(error.to_string())
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case(b"{ a: 2024-07-23T22:54:54.532100627+02:00 b:xy }")]
|
|
fn parse_datetime_in_record(#[case] expr: &[u8]) {
|
|
dbg!(String::from_utf8_lossy(expr));
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, expr, false);
|
|
assert!(working_set.parse_errors.is_empty());
|
|
let pipeline_el_expr = &block
|
|
.pipelines
|
|
.first()
|
|
.unwrap()
|
|
.elements
|
|
.first()
|
|
.unwrap()
|
|
.expr
|
|
.expr;
|
|
dbg!(pipeline_el_expr);
|
|
match pipeline_el_expr {
|
|
Expr::FullCellPath(v) => match &v.head.expr {
|
|
Expr::Record(fields) => assert!(matches!(
|
|
fields[0],
|
|
RecordItem::Pair(_, Expression { ty: Type::Date, .. })
|
|
)),
|
|
_ => panic!("Expected record head"),
|
|
},
|
|
_ => panic!("Expected full cell path"),
|
|
}
|
|
}
|
|
|
|
/// Regression test for https://github.com/nushell/nushell/issues/15243
|
|
#[test]
|
|
fn record_terminate_loop() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
parse(&mut working_set, None, b"{a:b}/", false);
|
|
assert_eq!(
|
|
working_set.parse_errors.first().map(|e| e.to_string()),
|
|
Some("Invalid characters after closing delimiter".to_string())
|
|
);
|
|
}
|
|
|
|
/// https://github.com/nushell/nushell/issues/16713
|
|
#[test]
|
|
fn garbage_span_of_incomplete_math_op() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let block = parse(&mut working_set, None, b"$ a", false);
|
|
let pipeline_el_expr = &block
|
|
.pipelines
|
|
.first()
|
|
.unwrap()
|
|
.elements
|
|
.first()
|
|
.unwrap()
|
|
.expr
|
|
.expr;
|
|
let Expr::BinaryOp(_, op, rhs) = pipeline_el_expr else {
|
|
panic!("Expected Expr::BinaryOp, but found {pipeline_el_expr:?}");
|
|
};
|
|
assert_ne!(op.span, rhs.span)
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn parse_let_in_pipeline() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
// This should parse without errors
|
|
let block = parse(&mut working_set, None, b"ls | let files", true);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"Parse errors: {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
|
|
// Check that we have a pipeline with two elements
|
|
assert_eq!(block.pipelines.len(), 1);
|
|
let pipeline = &block.pipelines[0];
|
|
assert_eq!(pipeline.elements.len(), 2);
|
|
|
|
// Both elements should be external calls since ls and let are not declared
|
|
assert!(matches!(
|
|
pipeline.elements[0].expr.expr,
|
|
Expr::ExternalCall(_, _)
|
|
));
|
|
assert!(matches!(
|
|
pipeline.elements[1].expr.expr,
|
|
Expr::ExternalCall(_, _)
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn empty_closure_as_row_condition() {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Where));
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, b"[0 1 2] | where {}", true);
|
|
|
|
assert_eq!(working_set.parse_errors.as_slice(), &[]);
|
|
let [pipeline] = block.pipelines.as_slice() else {
|
|
panic!("Expected exactly one pipeline")
|
|
};
|
|
let [_, where_call] = pipeline.elements.as_slice() else {
|
|
panic!("Expected exactly two pipeline elements")
|
|
};
|
|
let Expr::Call(where_call) = &where_call.expr.expr else {
|
|
panic!("Expected a call expression")
|
|
};
|
|
let [Argument::Positional(arg)] = where_call.arguments.as_slice() else {
|
|
panic!("Expected exactly one positional argument and no other argument")
|
|
};
|
|
assert!(matches!(arg.expr, Expr::RowCondition(_) | Expr::Closure(_)))
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("if true { 2 }", &[Type::Int, Type::Nothing])]
|
|
#[case("if true { 2 } else { 'foo' }", &[Type::Int, Type::String])]
|
|
#[case("
|
|
def erase []: any -> any {}
|
|
def foo []: [int -> string, list<int> -> list<string>] { erase }
|
|
|
|
[1, 2, 3] | if true { foo } else { }
|
|
",
|
|
&[Type::list(Type::String), Type::list(Type::Int)]
|
|
)]
|
|
#[case(r#"
|
|
match 1 {
|
|
1 => 1,
|
|
2 => "foo",
|
|
3 => [1, 2, 3],
|
|
}
|
|
"#,
|
|
&[Type::Int, Type::String, Type::list(Type::Int), Type::Nothing]
|
|
)]
|
|
fn conditional_branch_types(#[case] code: &str, #[case] expected_tys: &[Type]) {
|
|
use nu_protocol::TypeSet;
|
|
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(IfMocked));
|
|
working_set.add_decl(Box::new(MatchMocked));
|
|
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
|
|
let block = parse(&mut working_set, None, code.as_bytes(), true);
|
|
|
|
assert_eq!(working_set.parse_errors.as_slice(), &[]);
|
|
|
|
let expected_ty = expected_tys
|
|
.iter()
|
|
.cloned()
|
|
.reduce(Type::union)
|
|
.expect("at least one type should have been expected");
|
|
|
|
let out_ty = block.output_type();
|
|
|
|
assert_eq!(out_ty, expected_ty);
|
|
}
|
|
|
|
fn engine_with_def_and_extern() -> EngineState {
|
|
let mut engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(Extern));
|
|
let _ = engine_state.merge_delta(working_set.render());
|
|
|
|
engine_state
|
|
}
|
|
|
|
/// Whether a signature was reported as having more than one default value.
|
|
fn reports_extra_default_value(working_set: &StateWorkingSet) -> bool {
|
|
working_set.parse_errors.iter().any(|error| {
|
|
matches!(error, ParseError::LabeledErrorWithHelp { error, .. }
|
|
if error == "A positional parameter or flag can have at most one default value.")
|
|
})
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::positional("def cmd [arg = 1 = 2] { $arg }")]
|
|
#[case::flag("def cmd [--flag = 1 = 2] { $flag }")]
|
|
#[case::typed("def cmd [arg: int = 1 = 2 = 3] { $arg }")]
|
|
// The first argument's default must not make the second one's count as extra.
|
|
#[case::second_param("def cmd [a = 1, b = 2 = 3] { $a }")]
|
|
#[case::extern_positional("extern cmd [arg = 1 = 2]")]
|
|
#[case::extern_flag("extern cmd [--flag = 1 = 2]")]
|
|
#[case::closure("{|a = 1 = 2| $a}")]
|
|
fn rejects_multiple_default_values(#[case] source: &str) {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert!(
|
|
reports_extra_default_value(&working_set),
|
|
"expected extra default value diagnostic, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
// The value of a rejected extra default must be skipped rather than parsed as
|
|
// a new parameter, so only the duplicate default diagnostic is reported.
|
|
#[rstest]
|
|
#[case::positional("def cmd [a = 1 = 2] { $a }")]
|
|
#[case::flag("def cmd [--flag = 1 = 2] { $flag }")]
|
|
#[case::extern_positional("extern cmd [a = 1 = 2]")]
|
|
#[case::closure("{|a = 1 = 2| $a}")]
|
|
fn extra_default_value_reports_a_single_error(#[case] source: &str) {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert_eq!(
|
|
working_set.parse_errors.len(),
|
|
1,
|
|
"expected exactly one error, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
assert!(
|
|
reports_extra_default_value(&working_set),
|
|
"expected extra default value diagnostic, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn extra_default_value_keeps_the_first_default_and_adds_no_parameter() {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, b"def cmd [a = 1 = 2] { $a }", false);
|
|
|
|
let decl_id = working_set
|
|
.find_decl(b"cmd")
|
|
.expect("`cmd` should be declared");
|
|
let signature = working_set.get_decl(decl_id).signature();
|
|
|
|
assert!(
|
|
signature.required_positional.is_empty(),
|
|
"{:?}",
|
|
signature.required_positional
|
|
);
|
|
assert_eq!(signature.optional_positional.len(), 1);
|
|
let arg = &signature.optional_positional[0];
|
|
assert_eq!(arg.name, "a");
|
|
assert!(
|
|
matches!(arg.default_value, Some(Value::Int { val: 1, .. })),
|
|
"{:?}",
|
|
arg.default_value
|
|
);
|
|
}
|
|
|
|
/// Names of all positional parameters in declaration order: required, then
|
|
/// optional, then rest.
|
|
fn positional_names(signature: &Signature) -> Vec<&str> {
|
|
signature
|
|
.required_positional
|
|
.iter()
|
|
.chain(&signature.optional_positional)
|
|
.chain(&signature.rest_positional)
|
|
.map(|arg| arg.name.as_str())
|
|
.collect()
|
|
}
|
|
|
|
// A malformed parameter is reported once, and the tokens following the error
|
|
// must not be parsed as new parameters.
|
|
#[rstest]
|
|
#[case::extra_default("def cmd [a = 1 = 2] { $a }", &["a"])]
|
|
#[case::extra_defaults("def cmd [a = 1 = 2 = 3] { $a }", &["a"])]
|
|
#[case::type_after_default("def cmd [a = 1 : string] { $a }", &["a"])]
|
|
#[case::type_after_extra_default("def cmd [a = 1 = 2 : int] { $a }", &["a"])]
|
|
#[case::leading_default("def cmd [= 1] { 1 }", &[])]
|
|
#[case::leading_default_then_param("def cmd [= 1, b = 2] { $b }", &["b"])]
|
|
#[case::missing_extra_default("def cmd [a = 1 = , b = 3] { $b }", &["a", "b"])]
|
|
#[case::missing_extra_default_typed("def cmd [a = 1 =, b: int = 3] { $b }", &["a", "b"])]
|
|
#[case::invalid_short_flag_default("def cmd [--a(-bc) = 1] { }", &[])]
|
|
// `extern` signatures always get an implicit `args` rest parameter.
|
|
#[case::extern_leading_default("extern cmd [= 1]", &["args"])]
|
|
#[case::extern_type_after_default("extern cmd [a = 1 : string]", &["a", "args"])]
|
|
fn malformed_signature_reports_one_error_without_inventing_params(
|
|
#[case] source: &str,
|
|
#[case] expected_names: &[&str],
|
|
) {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert_eq!(
|
|
working_set.parse_errors.len(),
|
|
1,
|
|
"expected exactly one error, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
let decl_id = working_set
|
|
.find_decl(b"cmd")
|
|
.expect("`cmd` should be declared");
|
|
let signature = working_set.get_decl(decl_id).signature();
|
|
assert_eq!(positional_names(&signature), expected_names);
|
|
}
|
|
|
|
// A flag whose declaration failed must not let its `:`/`=` modify the
|
|
// previous parameter.
|
|
#[test]
|
|
fn failed_flag_does_not_modify_previous_param() {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"def cmd [x: int = 1, --a(-bc): string = 2] { $x }",
|
|
false,
|
|
);
|
|
|
|
assert_eq!(
|
|
working_set.parse_errors.len(),
|
|
1,
|
|
"expected exactly one error, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
let decl_id = working_set
|
|
.find_decl(b"cmd")
|
|
.expect("`cmd` should be declared");
|
|
let signature = working_set.get_decl(decl_id).signature();
|
|
assert_eq!(signature.optional_positional.len(), 1);
|
|
let arg = &signature.optional_positional[0];
|
|
assert_eq!(arg.name, "x");
|
|
assert_eq!(arg.shape, SyntaxShape::Int);
|
|
assert!(
|
|
matches!(arg.default_value, Some(Value::Int { val: 1, .. })),
|
|
"{:?}",
|
|
arg.default_value
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::type_after_default("{|a = 1 : string| $a}")]
|
|
#[case::leading_default("{|= 1| 1}")]
|
|
#[case::missing_extra_default("{|a = 1 = , b = 2| $b}")]
|
|
fn malformed_closure_signature_reports_one_error(#[case] source: &str) {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert_eq!(
|
|
working_set.parse_errors.len(),
|
|
1,
|
|
"expected exactly one error, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
// A type annotation after a default value (`: string`) should also be rejected;
|
|
// it was previously accepted silently because the parse mode reset to `Arg`
|
|
// after a default value.
|
|
#[rstest]
|
|
#[case::positional("def cmd [a = 1 : string] { $a }")]
|
|
#[case::typed("def cmd [a: int = 1 : string] { $a }")]
|
|
#[case::flag("def cmd [--f = 1 : string] { $f }")]
|
|
fn rejects_type_annotation_after_default_value(#[case] source: &str) {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert!(
|
|
working_set
|
|
.parse_errors
|
|
.iter()
|
|
.any(|error| matches!(error, ParseError::Expected("type", _))),
|
|
"expected Expected(\"type\") error, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::positional("def cmd [arg = 1] { $arg }")]
|
|
#[case::flag("def cmd [--flag = 1] { $flag }")]
|
|
#[case::distinct_params("def cmd [a = 1, b = 2] { $a }")]
|
|
// Commas between arguments are optional, so this is still two arguments with
|
|
// one default each rather than one argument with two defaults.
|
|
#[case::no_comma("def cmd [a = 1 b = 2] { $a }")]
|
|
#[case::extern_positional("extern cmd [arg = 1]")]
|
|
#[case::extern_flag("extern cmd [--flag = 1]")]
|
|
#[case::closure("{|a = 1| $a}")]
|
|
fn accepts_a_single_default_value(#[case] source: &str) {
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::def_single(b"def cmd [...rest = 1] { $rest }")]
|
|
#[case::extern_single(b"extern cmd [...rest = 1]")]
|
|
fn rest_positional_default_is_not_reported_as_a_duplicate(#[case] source: &[u8]) {
|
|
// A single default on a rest positional should not trigger the duplicate
|
|
// default value diagnostic. For `def`, the rest param gets its own
|
|
// `AssignmentMismatch` error; for `extern`, defaults aren't stored in the
|
|
// AST so nothing reports it (pre-existing behavior).
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(
|
|
!reports_extra_default_value(&working_set),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::def_duplicate(b"def cmd [...rest = 1 = 2] { $rest }")]
|
|
#[case::extern_duplicate(b"extern cmd [...rest = 1 = 2]")]
|
|
fn rest_positional_duplicate_default_is_reported(#[case] source: &[u8]) {
|
|
// Duplicate defaults on a rest positional should be caught even for
|
|
// extern commands, where defaults aren't stored in the AST.
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source, false);
|
|
|
|
assert!(
|
|
reports_extra_default_value(&working_set),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn default_before_any_argument_is_reported_as_an_error() {
|
|
// An `=` with no preceding parameter is an error: `def cmd [= 1, arg = 2]`
|
|
// used to silently drop the `= 1` before this change.
|
|
let engine_state = engine_with_def_and_extern();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"def cmd [= 1, arg = 2] { $arg }",
|
|
false,
|
|
);
|
|
|
|
assert!(
|
|
!working_set.parse_errors.is_empty(),
|
|
"expected an error for a default value with no parameter, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::malformed_table("[a b c; [1 2 3]]")]
|
|
#[case::between_items("[1; 2]")]
|
|
#[case::before_newline("[1;\n2]")]
|
|
#[case::before_variable("[1; $undefined]")]
|
|
#[case::leading("[;1]")]
|
|
#[case::trailing("[1;]")]
|
|
#[case::empty("[;]")]
|
|
#[case::repeated("[1;; 2]")]
|
|
#[case::nested_list("[[1; 2]]")]
|
|
#[case::external_argument("^foo [1; 2]")]
|
|
#[case::table_header("[[a; b]; [1]]")]
|
|
#[case::table_row("[[a b]; [1 2; 3 4]]")]
|
|
fn reject_invalid_list_semicolons(#[case] source: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
let error = working_set
|
|
.parse_errors
|
|
.first()
|
|
.expect("a semicolon in a list must produce a parse error");
|
|
assert!(
|
|
matches!(error, ParseError::LabeledErrorWithHelp { error, .. }
|
|
if error == "Unexpected semicolon in list"),
|
|
"unexpected diagnostic: {error:?}"
|
|
);
|
|
assert_eq!(working_set.get_span_contents(error.span()), b";");
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::plain("[[a b];]")]
|
|
#[case::whitespace("[[a b]; \n]")]
|
|
#[case::comment("[[a b]; # no rows\n]")]
|
|
#[case::empty_header("[[];]")]
|
|
fn table_without_rows_reports_missing_row(#[case] source: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert!(
|
|
matches!(
|
|
working_set.parse_errors.as_slice(),
|
|
[ParseError::Expected("table row", _)]
|
|
),
|
|
"unexpected diagnostics: {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
|
|
let span = working_set.parse_errors[0].span();
|
|
assert_eq!(span.start, span.end);
|
|
assert!(span.start > 0);
|
|
assert_eq!(
|
|
working_set.get_span_contents(Span::new(span.start - 1, span.start)),
|
|
b";"
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::double_quoted(r#"["a;b" 2]"#)]
|
|
#[case::single_quoted("['a;b' 2]")]
|
|
#[case::backtick_quoted("[`a;b` 2]")]
|
|
#[case::raw_string("[r#'a;b'# 2]")]
|
|
#[case::interpolation(r#"[$"(1; 2)" 3]"#)]
|
|
#[case::comment("[1 # ; ignored\n 2]")]
|
|
#[case::subexpression("[(1; 2) 3]")]
|
|
#[case::closure("[{1; 2} 3]")]
|
|
#[case::nested_table("[[[a]; [1]] 2]")]
|
|
#[case::table_separator("[[a]; [1]]")]
|
|
#[case::table_quoted_header(r#"[["a;b"]; [1]]"#)]
|
|
#[case::table_subexpression_cell("[[a]; [(1; 2)]]")]
|
|
#[case::table_nested_table_cell("[[a]; [[[b]; [1]]]]")]
|
|
fn accept_valid_list_semicolons(#[case] source: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::between_items("[1; 2]")]
|
|
#[case::before_newline("[1;\n2]")]
|
|
#[case::leading("[;1]")]
|
|
#[case::trailing("[1;]")]
|
|
#[case::empty("[;]")]
|
|
#[case::repeated("[1;; 2]")]
|
|
#[case::nested_list("[[1; 2]]")]
|
|
#[case::nested_record("[{a: [1; 2]}]")]
|
|
#[case::ignore_rest("[1 ..; 2]")]
|
|
#[case::capture_rest("[1 ..$rest; 2]")]
|
|
fn reject_invalid_list_pattern_semicolons(#[case] pattern: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(MatchMocked));
|
|
let source = format!("match [] {{ {pattern} => true, _ => false }}");
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
let error = working_set
|
|
.parse_errors
|
|
.first()
|
|
.expect("a semicolon in a list pattern must produce a parse error");
|
|
assert!(
|
|
matches!(error, ParseError::LabeledErrorWithHelp { error, .. }
|
|
if error == "Unexpected semicolon in list pattern"),
|
|
"unexpected diagnostic: {error:?}"
|
|
);
|
|
assert_eq!(working_set.get_span_contents(error.span()), b";");
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::double_quoted(r#"["a;b" 2]"#)]
|
|
#[case::single_quoted("['a;b' 2]")]
|
|
#[case::backtick_quoted("[`a;b` 2]")]
|
|
#[case::raw_string("[r#'a;b'# 2]")]
|
|
#[case::comment("[1 # ; ignored\n 2]")]
|
|
#[case::constant_subexpression("[(1; 2)]")]
|
|
#[case::nested_list(r#"[["a;b"]]"#)]
|
|
#[case::nested_record(r#"[{a: "b;c"}]"#)]
|
|
#[case::ignore_rest("[1 ..]")]
|
|
#[case::capture_rest("[1 ..$rest]")]
|
|
fn accept_valid_list_pattern_semicolons(#[case] pattern: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(MatchMocked));
|
|
let source = format!("match [] {{ {pattern} => true, _ => false }}");
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
}
|
|
|
|
/// A second `..` or `..$name` in one list pattern gives one error at the extra rest. The arm
|
|
/// body can still use the extra rest's variable without also getting "Variable not found".
|
|
#[rstest]
|
|
#[case::ignore("[.., 2, ..] => true", "..")]
|
|
#[case::capture("[..$a, 2, ..$b] => $b", "..$b")]
|
|
fn reject_second_list_pattern_rest(#[case] arm: &str, #[case] extra_rest: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(MatchMocked));
|
|
let source = format!("match [] {{ {arm}, _ => false }}");
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
|
|
let [error] = working_set.parse_errors.as_slice() else {
|
|
panic!(
|
|
"expected one parse error, got {:?}",
|
|
working_set.parse_errors
|
|
);
|
|
};
|
|
assert!(
|
|
matches!(error, ParseError::LabeledErrorWithHelp { error, .. }
|
|
if error == "`..` can only be used once per list pattern"),
|
|
"unexpected diagnostic: {error:?}"
|
|
);
|
|
assert_eq!(
|
|
working_set.get_span_contents(error.span()),
|
|
extra_rest.as_bytes()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn record_semicolon_gives_separator_help() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"{ show_banner: false; table_mode: rounded }",
|
|
false,
|
|
);
|
|
assert!(!working_set.parse_errors.is_empty());
|
|
let err = format!("{:?}", working_set.parse_errors[0]);
|
|
assert!(
|
|
err.contains("semicolon")
|
|
|| err.contains("`;`")
|
|
|| err.contains("Record")
|
|
|| err.contains("record"),
|
|
"expected record separator help, got {err}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn explicit_record_invalid_value_token_errors() {
|
|
// Record context must reject non-item tokens as values (not silent parse).
|
|
// Nested `{ show_banner false }` can still parse as a closure; the
|
|
// refuse_confusing_record suite covers more shapes — this guards the
|
|
// value-token path with an assertion.
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
let _ = parse(&mut working_set, None, b"{ a: || }", false);
|
|
assert!(
|
|
!working_set.parse_errors.is_empty(),
|
|
"expected parse error for invalid record value token"
|
|
);
|
|
let err = working_set.parse_errors[0].to_string();
|
|
assert!(
|
|
err.contains("Unexpected token") || err.contains("record"),
|
|
"expected record value token error, got {err}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn empty_and_complete_lines_error_kinds() {
|
|
// Complete inputs should not leave Unclosed/UnexpectedEof hanging; incomplete
|
|
// open blocks should.
|
|
let engine_state = EngineState::new();
|
|
|
|
let mut empty = StateWorkingSet::new(&engine_state);
|
|
parse(&mut empty, None, b"", false);
|
|
assert!(
|
|
empty.parse_errors.is_empty(),
|
|
"empty source should not produce parse errors, got {:?}",
|
|
empty.parse_errors
|
|
);
|
|
|
|
let mut one = StateWorkingSet::new(&engine_state);
|
|
parse(&mut one, None, b"1", false);
|
|
assert!(
|
|
one.parse_errors.is_empty(),
|
|
"literal `1` should parse cleanly, got {:?}",
|
|
one.parse_errors
|
|
);
|
|
|
|
let mut unclosed = StateWorkingSet::new(&engine_state);
|
|
parse(&mut unclosed, None, b"def f [] {", false);
|
|
assert!(
|
|
unclosed
|
|
.parse_errors
|
|
.iter()
|
|
.any(|e| matches!(e, ParseError::Unclosed(..) | ParseError::UnexpectedEof(..))),
|
|
"open block should be Unclosed/UnexpectedEof, got {:?}",
|
|
unclosed.parse_errors
|
|
);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case::quoted_name("\"foo\"")]
|
|
#[case::backtick_name("`foo`")]
|
|
#[case::escaped_name("\"foo\\u{2D}bar\"")]
|
|
pub fn parse_name_check_leaves_no_file_in_the_state(#[case] name: &str) {
|
|
// The name check reads the head word of the name, to see whether the call site would read
|
|
// that word as a value. It has to read it without leaving a file in the state it checks.
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(Def));
|
|
working_set.add_decl(Box::new(Alias));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
|
|
let _ = parse(
|
|
&mut working_set,
|
|
None,
|
|
format!("def {name} [] {{}}").as_bytes(),
|
|
false,
|
|
);
|
|
|
|
let left = working_set
|
|
.files()
|
|
.filter(|file| file.name.starts_with("command name"))
|
|
.map(|file| file.name.to_string())
|
|
.collect::<Vec<_>>();
|
|
|
|
assert!(left.is_empty(), "{name:?} left {left:?} in the state");
|
|
}
|
|
|
|
#[test]
|
|
pub fn parse_name_check_leaves_no_block_in_the_state() {
|
|
// A range bound such as `(foo)` is parsed as a subexpression, which adds a block. The name
|
|
// check must not leave that block in the state it checks.
|
|
let blocks_after = |source: &str| {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(Alias));
|
|
working_set.add_decl(Box::new(AttrEcho));
|
|
let _ = parse(&mut working_set, None, source.as_bytes(), false);
|
|
working_set.num_blocks()
|
|
};
|
|
|
|
assert_eq!(
|
|
blocks_after(r#"alias "x..(foo)" = attr echo"#),
|
|
blocks_after("alias foo = attr echo"),
|
|
);
|
|
}
|
|
|
|
/// A match block's type includes `nothing` unless an arm matches every value. A guarded `_` can
|
|
/// still fall through, so it doesn't count.
|
|
#[rstest]
|
|
#[case::wildcard("_ => 1", "int")]
|
|
#[case::variable("$x => 1", "int")]
|
|
#[case::guarded_wildcard("_ if false => 1", "oneof<int, nothing>")]
|
|
fn match_block_type_with_a_guard(#[case] arm: &str, #[case] ty: &str) {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(MatchMocked));
|
|
let source = format!("match 1 {{ {arm} }}");
|
|
let block = parse(&mut working_set, None, source.as_bytes(), false);
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
|
|
let Expr::Call(call) = &block.pipelines[0].elements[0].expr.expr else {
|
|
panic!("expected a call to `match`");
|
|
};
|
|
let match_block = call.positional_iter().nth(1).expect("a match block");
|
|
assert_eq!(match_block.ty.to_string(), ty);
|
|
}
|
|
|
|
/// `Traverse` reaches the expression in a match guard.
|
|
#[test]
|
|
fn traverse_reaches_a_match_guard() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(MatchMocked));
|
|
let block = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"match 1 { $x if $x > 0 => 1 }",
|
|
false,
|
|
);
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
|
|
let is_comparison = |expr: &Expression| matches!(expr.expr, Expr::BinaryOp(..));
|
|
let found = block.find_map(&working_set, &|expr| {
|
|
if is_comparison(expr) {
|
|
ControlFlow::Break(Some(expr.span))
|
|
} else {
|
|
ControlFlow::Continue(())
|
|
}
|
|
});
|
|
let mut all = vec![];
|
|
block.flat_map(
|
|
&working_set,
|
|
&|expr| {
|
|
if is_comparison(expr) {
|
|
vec![expr.span]
|
|
} else {
|
|
vec![]
|
|
}
|
|
},
|
|
&mut all,
|
|
);
|
|
|
|
let guard: &[u8] = b"$x > 0";
|
|
assert_eq!(
|
|
found.map(|span| working_set.get_span_contents(span)),
|
|
Some(guard)
|
|
);
|
|
assert_eq!(
|
|
all.iter()
|
|
.map(|span| working_set.get_span_contents(*span))
|
|
.collect::<Vec<_>>(),
|
|
[guard]
|
|
);
|
|
}
|
|
|
|
/// Flattening (what the highlighter colors) covers a match guard, in source order.
|
|
#[test]
|
|
fn flatten_includes_a_match_guard() {
|
|
let engine_state = EngineState::new();
|
|
let mut working_set = StateWorkingSet::new(&engine_state);
|
|
working_set.add_decl(Box::new(MatchMocked));
|
|
let block = parse(
|
|
&mut working_set,
|
|
None,
|
|
b"match 1 { $x if $x > 0 => 1 }",
|
|
false,
|
|
);
|
|
assert!(
|
|
working_set.parse_errors.is_empty(),
|
|
"{:?}",
|
|
working_set.parse_errors
|
|
);
|
|
|
|
let shapes: Vec<_> = flatten_block(&working_set, &block)
|
|
.into_iter()
|
|
.map(|(span, shape)| {
|
|
(
|
|
String::from_utf8_lossy(working_set.get_span_contents(span)).into_owned(),
|
|
shape.as_str().to_string(),
|
|
)
|
|
})
|
|
.collect();
|
|
let expected = [
|
|
("match", "shape_internalcall"),
|
|
("1", "shape_int"),
|
|
("$x", "shape_vardecl"),
|
|
("$x", "shape_variable"),
|
|
(">", "shape_operator"),
|
|
("0", "shape_int"),
|
|
("1", "shape_int"),
|
|
]
|
|
.map(|(text, shape)| (text.to_string(), shape.to_string()));
|
|
assert_eq!(shapes, expected);
|
|
}
|