Merge pull request #5408 from Luv-Ray/fix-expr-syntex-error

`expr`: fix expr syntax error
This commit is contained in:
Daniel Hofstetter 2023-10-15 15:34:57 +02:00 committed by GitHub
commit 569b0a9b38
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 9 deletions

View file

@ -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::<BigInt>().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
};

View file

@ -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"]];