Skip to content

Commit

Permalink
feat(arithmetic): support explicit base#literal in arithmetic
Browse files Browse the repository at this point in the history
  • Loading branch information
reubeno committed Feb 20, 2025
1 parent e4e94cb commit 8b4f552
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
28 changes: 24 additions & 4 deletions brush-parser/src/arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,29 @@ peg::parser! {
rule _() -> () = quiet!{[' ' | '\t' | '\n' | '\r']*} {}

rule literal_number() -> i64 =
// TODO: handle explicit radix (e.g., <base>#<literal>) for bases 2 through 64
"0" ['x' | 'X'] s:$(['0'..='9' | 'a'..='f' | 'A'..='F']*) {? i64::from_str_radix(s, 16).or(Err("i64")) } /
s:$("0" ['0'..='8']*) {? i64::from_str_radix(s, 8).or(Err("i64")) } /
s:$(['1'..='9'] ['0'..='9']*) {? s.parse().or(Err("i64")) }
// Literal with explicit radix (format: <base>#<literal>)
radix:decimal_literal() "#" s:$(['0'..='9' | 'a'..='z' | 'A'..='Z']+) {?
// TODO: Support bases larger than 36. from_str_radix can't handle that.
if radix < 2 || radix > 36 {
return Err("invalid base");
}

i64::from_str_radix(s, radix as u32).or(Err("i64"))
} /
// Hex literal
"0" ['x' | 'X'] s:$(['0'..='9' | 'a'..='f' | 'A'..='F']*) {?
i64::from_str_radix(s, 16).or(Err("i64"))
} /
// Octal literal
s:$("0" ['0'..='8']*) {?
i64::from_str_radix(s, 8).or(Err("i64"))
} /
// Decimal literal
decimal_literal()

rule decimal_literal() -> i64 =
s:$(['1'..='9'] ['0'..='9']*) {?
s.parse().or(Err("i64"))
}
}
}
12 changes: 12 additions & 0 deletions brush-shell/tests/cases/arithmetic.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ cases:
echo "$((0x10))"
echo "$((0x010))"
- name: "Arithmetic literals with explicit bases"
stdin: |
echo "$((2#1010))"
echo "$((8#16))"
echo "$((16#faf))"
echo "$((36#vvv))"
- name: "Arithmetic literals with base 64 encoding"
known_failure: true # Not currently handled.
stdin: |
echo "$((64#zzz))"
- name: "Parentheses"
stdin: |
echo "$(((10)))"
Expand Down

0 comments on commit 8b4f552

Please sign in to comment.