rust-parser-combinator/src/lib.rs

36 lines
872 B
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>;
}
impl<I, O, E, F> Parser<I, O, E> for F where F: Fn(I) -> ParseResult<I, O, E> {
fn parse(&self, input: I) -> ParseResult<I, O, E> {
self(input)
}
}
fn literal(expected: &'static str) -> impl Fn(&str) -> ParseResult<&str, (), &str> {
move |input| match input.get(0..expected.len()) {
Some(next) if next == expected =>
Ok(((), &input[expected.len()..])),
_ => Err(input)
}
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:36:04 -07:00
fn parsing() {
let output = literal("a")("a yolo");
assert_matches!(output.unwrap(), ((), " yolo"));
2022-10-10 00:13:39 -07:00
}
}