futilehdl/src/parser/literals.rs

55 lines
1.3 KiB
Rust
Raw Normal View History

2021-12-30 19:46:28 +00:00
use nom::{
2022-02-02 00:41:19 +00:00
branch::alt,
bytes::complete::tag,
character::complete::{alpha1, alphanumeric1, char, multispace0, one_of},
2022-02-01 01:00:27 +00:00
combinator::{map, recognize},
2022-02-02 00:41:19 +00:00
error::ParseError,
2021-12-30 19:46:28 +00:00
multi::{many0, many1},
2022-02-02 00:41:19 +00:00
sequence::{delimited, pair, preceded, terminated},
2021-12-30 19:46:28 +00:00
};
2022-01-04 19:05:10 +00:00
use crate::parser::{IResult, Span};
2021-12-30 19:46:28 +00:00
2022-01-05 01:09:08 +00:00
pub fn hexadecimal(input: Span) -> IResult<Span, u64> {
2022-02-01 01:00:27 +00:00
map(
2021-12-30 19:46:28 +00:00
preceded(
2022-01-04 18:09:33 +00:00
char('h'),
2021-12-30 19:46:28 +00:00
recognize(many1(terminated(
one_of("0123456789abcdefABCDEF"),
many0(char('_')),
))),
),
2022-02-01 01:00:27 +00:00
|out: Span| {
2022-02-01 18:46:06 +00:00
u64::from_str_radix(&str::replace(out.fragment(), "_", ""), 16)
.expect("error parsing literal")
2022-02-01 01:00:27 +00:00
},
2021-12-30 19:46:28 +00:00
)(input)
}
2022-02-02 00:41:19 +00:00
pub fn ws0<'a, F: 'a, O, E: ParseError<Span<'a>>>(
inner: F,
) -> impl FnMut(Span<'a>) -> IResult<Span<'a>, O, E>
where
F: FnMut(Span<'a>) -> IResult<Span<'a>, O, E>,
{
delimited(multispace0, inner, multispace0)
}
pub fn identifier(input: Span) -> IResult<Span, Span> {
recognize(pair(
alt((alpha1, tag("_"))),
many0(alt((alphanumeric1, tag("_")))),
))(input)
}
2021-12-30 19:46:28 +00:00
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_hex() {
2022-01-04 19:05:10 +00:00
assert_eq!(hexadecimal("hfF".into()).unwrap().1, 0xff);
assert_eq!(hexadecimal("hF".into()).unwrap().1, 0xf);
2021-12-30 19:46:28 +00:00
}
}