Skip to main content

brush_parser/
arithmetic.rs

1//! Parser for shell arithmetic expressions.
2
3use crate::ast;
4use crate::error;
5
6/// Parses a shell arithmetic expression.
7///
8/// # Arguments
9///
10/// * `input` - The arithmetic expression to parse, in string form.
11pub fn parse(input: &str) -> Result<ast::ArithmeticExpr, error::WordParseError> {
12    cacheable_parse(input)
13}
14
15#[cached::macros::cached(max_size = 64, key = "String", convert = r#"{ input.to_owned() }"#)]
16fn cacheable_parse(input: &str) -> Result<ast::ArithmeticExpr, error::WordParseError> {
17    tracing::debug!(target: "arithmetic", "parsing arithmetic expression: '{input}'");
18    arithmetic::full_expression(input)
19        .map_err(|e| error::WordParseError::ArithmeticExpression(e.into()))
20}
21
22peg::parser! {
23    grammar arithmetic() for str {
24        // An expression holding nothing but whitespace evaluates to 0, wherever it came from:
25        // `$(( ))`, `let ''`, or a blank array subscript.
26        pub(crate) rule full_expression() -> ast::ArithmeticExpr =
27            _ ![_] { ast::ArithmeticExpr::Literal(0) } /
28            _ e:expression() _ { e }
29
30        pub(crate) rule expression() -> ast::ArithmeticExpr = precedence!{
31            x:(@) _ "," _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::Comma, Box::new(x), Box::new(y)) }
32            --
33            x:assignment() { x }
34        }
35
36        // Assignment sits outside the precedence table below. As in bash, only a variable
37        // or array element can be assigned to, so something like `-x = 1` or `(x) = 1` is
38        // an error instead of an assignment nested inside a unary or binary operator.
39        rule assignment() -> ast::ArithmeticExpr =
40            x:lvalue() _ op:assignment_operator() _ y:assignment() {
41                match op {
42                    Some(op) => ast::ArithmeticExpr::BinaryAssignment(op, x, Box::new(y)),
43                    None => ast::ArithmeticExpr::Assignment(x, Box::new(y)),
44                }
45            } /
46            conditional()
47
48        rule assignment_operator() -> Option<ast::BinaryOperator> =
49            "*=" { Some(ast::BinaryOperator::Multiply) } /
50            "/=" { Some(ast::BinaryOperator::Divide) } /
51            "%=" { Some(ast::BinaryOperator::Modulo) } /
52            "+=" { Some(ast::BinaryOperator::Add) } /
53            "-=" { Some(ast::BinaryOperator::Subtract) } /
54            "<<=" { Some(ast::BinaryOperator::ShiftLeft) } /
55            ">>=" { Some(ast::BinaryOperator::ShiftRight) } /
56            "&=" { Some(ast::BinaryOperator::BitwiseAnd) } /
57            "|=" { Some(ast::BinaryOperator::BitwiseOr) } /
58            "^=" { Some(ast::BinaryOperator::BitwiseXor) } /
59            "=" !"=" { None }
60
61        rule conditional() -> ast::ArithmeticExpr = precedence!{
62            x:@ _ "?" _ y:expression() _ ":" _ z:(@) { ast::ArithmeticExpr::Conditional(Box::new(x), Box::new(y), Box::new(z)) }
63            --
64            x:(@) _ "||" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::LogicalOr, Box::new(x), Box::new(y)) }
65            --
66            x:(@) _ "&&" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::LogicalAnd, Box::new(x), Box::new(y)) }
67            --
68            x:(@) _ "|" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::BitwiseOr, Box::new(x), Box::new(y)) }
69            --
70            x:(@) _ "^" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::BitwiseXor, Box::new(x), Box::new(y)) }
71            --
72            x:(@) _ "&" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::BitwiseAnd, Box::new(x), Box::new(y)) }
73            --
74            x:(@) _ "==" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::Equals, Box::new(x), Box::new(y)) }
75            x:(@) _ "!=" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::NotEquals, Box::new(x), Box::new(y)) }
76            --
77            x:(@) _ "<" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::LessThan, Box::new(x), Box::new(y)) }
78            x:(@) _ ">" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::GreaterThan, Box::new(x), Box::new(y)) }
79            x:(@) _ "<=" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::LessThanOrEqualTo, Box::new(x), Box::new(y)) }
80            x:(@) _ ">=" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::GreaterThanOrEqualTo, Box::new(x), Box::new(y)) }
81            --
82            x:(@) _ "<<" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::ShiftLeft, Box::new(x), Box::new(y)) }
83            x:(@) _ ">>" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::ShiftRight, Box::new(x), Box::new(y)) }
84            --
85            x:(@) _ "+" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::Add, Box::new(x), Box::new(y)) }
86            x:(@) _ "-" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::Subtract, Box::new(x), Box::new(y)) }
87            --
88            x:(@) _ "*" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::Multiply, Box::new(x), Box::new(y)) }
89            x:(@) _ "%" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::Modulo, Box::new(x), Box::new(y)) }
90            x:(@) _ "/" _ y:@ { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::Divide, Box::new(x), Box::new(y)) }
91            --
92            x:@ _ "**" _ y:(@) { ast::ArithmeticExpr::BinaryOp(ast::BinaryOperator::Power, Box::new(x), Box::new(y)) }
93            --
94            "!" _ x:(@) { ast::ArithmeticExpr::UnaryOp(ast::UnaryOperator::LogicalNot, Box::new(x)) }
95            "~" _ x:(@) { ast::ArithmeticExpr::UnaryOp(ast::UnaryOperator::BitwiseNot, Box::new(x)) }
96            --
97            // NOTE: We add negative lookahead to avoid ambiguity with the pre-increment/pre-decrement operators.
98            "+" !['+'] _ x:(@) { ast::ArithmeticExpr::UnaryOp(ast::UnaryOperator::UnaryPlus, Box::new(x)) }
99            "-" !['-'] _ x:(@) { ast::ArithmeticExpr::UnaryOp(ast::UnaryOperator::UnaryMinus, Box::new(x)) }
100            --
101            "++" _ x:lvalue() { ast::ArithmeticExpr::UnaryAssignment(ast::UnaryAssignmentOperator::PrefixIncrement, x) }
102            "--" _ x:lvalue() { ast::ArithmeticExpr::UnaryAssignment(ast::UnaryAssignmentOperator::PrefixDecrement, x) }
103            --
104            x:lvalue() _ "++" { ast::ArithmeticExpr::UnaryAssignment(ast::UnaryAssignmentOperator::PostfixIncrement, x) }
105            x:lvalue() _ "--" { ast::ArithmeticExpr::UnaryAssignment(ast::UnaryAssignmentOperator::PostfixDecrement, x) }
106            --
107            n:literal_number() { ast::ArithmeticExpr::Literal(n) }
108            l:lvalue() { ast::ArithmeticExpr::Reference(l) }
109            "(" _ expr:expression() _ ")" { expr }
110        }
111
112        rule lvalue() -> ast::ArithmeticTarget =
113            name:variable_name() "[" index:expression() "]" {
114                ast::ArithmeticTarget::ArrayElement(name.to_owned(), Box::new(index))
115            } /
116            name:variable_name() {
117                ast::ArithmeticTarget::Variable(name.to_owned())
118            }
119
120        rule variable_name() -> &'input str =
121            $(['a'..='z' | 'A'..='Z' | '_'](['a'..='z' | 'A'..='Z' | '_' | '0'..='9']*))
122
123        rule _() -> () = quiet!{[' ' | '\t' | '\n' | '\r']*} {}
124
125        rule literal_number() -> i64 =
126            // Literal with explicit radix (format: <base>#<literal>)
127            radix:decimal_literal() "#" s:$(['0'..='9' | 'a'..='z' | 'A'..='Z' | '@' | '_']+) {?
128                parse_shell_literal_number(s, radix.cast_unsigned())
129            } /
130            // Hex literal
131            "0" ['x' | 'X'] s:$(['0'..='9' | 'a'..='f' | 'A'..='F']*) {?
132                i64::from_str_radix(s, 16).or(Err("i64"))
133            } /
134            // Octal literal
135            s:$("0" ['0'..='8']*) {?
136                i64::from_str_radix(s, 8).or(Err("i64"))
137            } /
138            // Decimal literal
139            decimal_literal()
140
141        rule decimal_literal() -> i64 =
142            s:$(['1'..='9'] ['0'..='9']*) {?
143                // Parse as u64 first, then cast to i64. This handles values like
144                // 9223372036854775808 (i64::MAX + 1) which is needed for INT64_MIN
145                // when preceded by unary minus: -(9223372036854775808) wraps to i64::MIN.
146                s.parse::<u64>().map(|v| v.cast_signed()).or(Err("i64"))
147            }
148    }
149}
150
151fn parse_shell_literal_number(s: &str, radix: u64) -> Result<i64, &'static str> {
152    if !(2..=64).contains(&radix) {
153        return Err("invalid base");
154    }
155
156    // For bases <= 36: case-insensitive (a-z and A-Z both map to 10-35)
157    // For bases > 36 (bash extension):
158    //   0-9 = 0-9, a-z = 10-35, A-Z = 36-61, @ = 62, _ = 63
159    let mut result: i64 = 0;
160
161    for ch in s.chars() {
162        let digit_val = if radix <= 36 {
163            match ch {
164                '0'..='9' => (ch as u64) - ('0' as u64),
165                'a'..='z' => (ch as u64) - ('a' as u64) + 10,
166                'A'..='Z' => (ch as u64) - ('A' as u64) + 10,
167                _ => return Err("invalid digit"),
168            }
169        } else {
170            match ch {
171                '0'..='9' => (ch as u64) - ('0' as u64),
172                'a'..='z' => (ch as u64) - ('a' as u64) + 10,
173                'A'..='Z' => (ch as u64) - ('A' as u64) + 36,
174                '@' => 62,
175                '_' => 63,
176                _ => return Err("invalid digit"),
177            }
178        };
179
180        if digit_val >= radix {
181            return Err("value too great for base");
182        }
183
184        result = result
185            .wrapping_mul(radix.cast_signed())
186            .wrapping_add(digit_val.cast_signed());
187    }
188
189    Ok(result)
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195
196    #[test]
197    fn parse_blank_expression_yields_zero() {
198        for input in ["", " ", "\t", " \n "] {
199            assert!(
200                matches!(parse(input), Ok(ast::ArithmeticExpr::Literal(0))),
201                "expected 0 for {input:?}"
202            );
203        }
204    }
205
206    #[test]
207    fn parse_rejects_an_incomplete_expression() {
208        assert!(parse("1 +").is_err());
209    }
210}