diff --git a/src/uu/expr/src/tokens.rs b/src/uu/expr/src/tokens.rs index 3c5cac060f9..f499881c138 100644 --- a/src/uu/expr/src/tokens.rs +++ b/src/uu/expr/src/tokens.rs @@ -16,8 +16,6 @@ // spell-checker:ignore (ToDO) paren -use num_bigint::BigInt; - #[derive(Debug, Clone)] pub enum Token { Value { @@ -59,11 +57,8 @@ impl Token { } } - fn is_a_number(&self) -> bool { - match self { - Self::Value { value, .. } => value.parse::().is_ok(), - _ => false, - } + fn is_a_value(&self) -> bool { + matches!(*self, Self::Value { .. }) } fn is_a_close_paren(&self) -> bool { @@ -131,14 +126,14 @@ fn maybe_dump_tokens_acc(tokens_acc: &[(usize, Token)]) { } fn push_token_if_not_escaped(acc: &mut Vec<(usize, Token)>, tok_idx: usize, token: Token, s: &str) { - // Smells heuristics... :( + // `+` may be escaped such as `expr + 1` and `expr 1 + + 1` let prev_is_plus = match acc.last() { None => false, Some(t) => t.1.is_infix_plus(), }; let should_use_as_escaped = if prev_is_plus && acc.len() >= 2 { let pre_prev = &acc[acc.len() - 2]; - !(pre_prev.1.is_a_number() || pre_prev.1.is_a_close_paren()) + !(pre_prev.1.is_a_value() || pre_prev.1.is_a_close_paren()) } else { prev_is_plus }; diff --git a/tests/by-util/test_expr.rs b/tests/by-util/test_expr.rs index 3f403c7ea37..d4cca43a28b 100644 --- a/tests/by-util/test_expr.rs +++ b/tests/by-util/test_expr.rs @@ -138,6 +138,11 @@ fn test_or() { .args(&["0", "|", "10", "/", "5"]) .succeeds() .stdout_only("2\n"); + + new_ucmd!() + .args(&["12", "|", "9a", "+", "1"]) + .succeeds() + .stdout_only("12\n"); } #[test] @@ -276,6 +281,26 @@ fn test_invalid_substr() { .stdout_only("\n"); } +#[test] +fn test_escape() { + new_ucmd!().args(&["+", "1"]).succeeds().stdout_only("1\n"); + + new_ucmd!() + .args(&["1", "+", "+", "1"]) + .succeeds() + .stdout_only("2\n"); + + new_ucmd!() + .args(&["2", "*", "+", "3"]) + .succeeds() + .stdout_only("6\n"); + + new_ucmd!() + .args(&["(", "1", ")", "+", "1"]) + .succeeds() + .stdout_only("2\n"); +} + #[test] fn test_invalid_syntax() { let invalid_syntaxes = [["12", "12"], ["12", "|"], ["|", "12"]];