Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(arithmetic): support explicit base#literal in arithmetic #388

Merged
merged 1 commit into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading