rust-parser-combinator/src/lib.rs

52 lines
1.3 KiB
Rust
Raw Normal View History

2022-10-15 23:36:04 -07:00
#![feature(assert_matches)]
#![allow(dead_code)] //TODO eventually turn this off
type ParseResult<I, O, E> = Result<(O, I), E>;
trait Parser<I, O, E> {
fn parse(&self, input: I) -> ParseResult<I, O, E>;
}
2022-10-15 23:41:22 -07:00
impl<I, O, E, F> Parser<I, O, E> for F
where
F: Fn(I) -> ParseResult<I, O, E>,
{
2022-10-15 23:36:04 -07:00
fn parse(&self, input: I) -> ParseResult<I, O, E> {
self(input)
}
}
2022-10-15 23:41:22 -07:00
fn literal(expected: &'static str) -> impl Fn(&str) -> ParseResult<&str, &str, &str> {
2022-10-15 23:36:04 -07:00
move |input| match input.get(0..expected.len()) {
2022-10-15 23:41:22 -07:00
Some(next) if next == expected => Ok((expected, &input[expected.len()..])),
_ => Err(input),
2022-10-15 23:36:04 -07:00
}
2022-10-10 00:13:39 -07:00
}
2022-10-15 23:41:22 -07:00
fn map<P, F, I, O1, O2, E>(parser: P, map_fn: F) -> impl Parser<I, O2, E>
where
P: Parser<I, O1, E>,
F: Fn(O1) -> O2,
{
move |input| parser.parse(input).map(|(result, rest)| (map_fn(result), rest))
}
2022-10-10 00:13:39 -07:00
#[cfg(test)]
mod tests {
use super::*;
2022-10-15 23:36:04 -07:00
use std::assert_matches::assert_matches;
2022-10-10 00:13:39 -07:00
#[test]
2022-10-15 23:41:22 -07:00
fn test_parsing() {
2022-10-15 23:36:04 -07:00
let output = literal("a")("a yolo");
2022-10-15 23:41:22 -07:00
assert_matches!(output.unwrap(), ("a", " yolo"));
}
#[test]
fn test_map() {
let lit_a = literal("a");
let output = map(lit_a, |s| s.to_uppercase()).parse("a yolo");
assert_matches!(output.unwrap(), (s, " yolo") if s == "A");
2022-10-10 00:13:39 -07:00
}
}