Skip to content

Commit

Permalink
Merge pull request uutils#5408 from Luv-Ray/fix-expr-syntex-error
Browse files Browse the repository at this point in the history
`expr`: fix expr syntax error
  • Loading branch information
cakebaker authored Oct 15, 2023
2 parents 89b03ae + 6ef5b27 commit 569b0a9
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 9 deletions.
13 changes: 4 additions & 9 deletions src/uu/expr/src/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

// spell-checker:ignore (ToDO) paren

use num_bigint::BigInt;

#[derive(Debug, Clone)]
pub enum Token {
Value {
Expand Down Expand Up @@ -59,11 +57,8 @@ impl Token {
}
}

fn is_a_number(&self) -> bool {
match self {
Self::Value { value, .. } => value.parse::<BigInt>().is_ok(),
_ => false,
}
fn is_a_value(&self) -> bool {
matches!(*self, Self::Value { .. })
}

fn is_a_close_paren(&self) -> bool {
Expand Down Expand Up @@ -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
};
Expand Down
25 changes: 25 additions & 0 deletions tests/by-util/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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"]];
Expand Down

0 comments on commit 569b0a9

Please sign in to comment.