如何在Rust中为自己的解析器编写组合器?

时间:2020-02-11 17:01:52

标签: parsing types rust composition

this video的启发,我认为一个小的解析器组合器库将是学习字符串,借用和在Rust中键入的一种好方法-到目前为止。

我设法让一个字符解析器和一个数字解析器可以工作:

pub enum Parsed<'a, T> {
    Some(T, &'a str),
    None(&'a str),
}

impl<T> Parsed<'_, T> {
    // I was neither sure with the third & before the T...
    pub fn unwrap(&self) -> (&T, &str) {
        match self {
            // ... nor with the first one here.
            Parsed::Some(head, tail) => (&head, &tail),
            _ => panic!("Called unwrap on nothing."),
        }
    // But this was the only way that I came up with that compiled.
    }

    pub fn is_none(&self) -> bool {
        match self {
            Parsed::None(_) => true,
            _ => false,
        }
    }
}

pub fn parse<T>(what: fn(&str) -> Parsed<T>, input: &str) -> Parsed<T> {
    what(input)
}

pub fn char(input: &str) -> Parsed<char> {
    match input.chars().next() {
        Some(c) => Parsed::Some(c, &input[1..]),
        None => Parsed::None(input),
    }
}

pub fn digit(input: &str) -> Parsed<u8> {
    match input.chars().next() {
        Some(d @ '0'..='9') => Parsed::Some(d as u8 - ('0' as u8), &input[1..]),
        _ => Parsed::None(input),
    }
}

然后我想转向组合器,在这里some可以获取给定解析器的任意数量的匹配项。那一个让我难受。这是我刚开始可以完成一些单元测试的版本:

pub fn some<T>(input: &str, parser: fn(&str) -> Parsed<T>) -> Parsed<Vec<T>> {
    let mut re = Vec::new();
    let mut pos = input;
    loop {
        match parser(pos) {
            Parsed::Some(head, tail) => {
                re.push(head);
                pos = tail;
            }
            Parsed::None(_) => break,
        }
    }
    Parsed::Some(re, pos)
}

但是要能够与parse::parse一起使用,它只需要一个解析器函数并返回一个。我尝试了很多变体:

  • fn(&str) -> Parsed<T>作为返回类型
  • impl Fn(&str) -> Parsed<T>作为返回类型
  • impl FnOnce(&str) -> Parsed<T>作为返回类型
  • 几个for<'r> something,编译器吐出来的,我什至都不明白
  • 将代码打包到一个闭包中,并在有和没有move的情况下返回该代码

Rust总是有至少一行不满意。现在我不知道该怎么办了。测试代码如下:


#[test]
fn test() {
    assert_eq!(char("foo").unwrap(), (&'f', "oo"));
    assert!(parse(digit, "foo").is_none());
    assert_eq!(parse(digit, "9foo").unwrap(), (&9, "foo"));
    assert_eq!(
        parse(some(digit), "12space").unwrap(),
        (&vec![1, 2], "space")
    );
}

这是指向playground的链接。

1 个答案:

答案 0 :(得分:1)

通过返回闭包,返回实现Fn*特征之一的匿名类型:

fn some<T>(parser: impl Fn(&str) -> Parsed<T>) -> impl FnOnce(&str) -> Parsed<Vec<T>> {
    move |input| {
        let mut re = Vec::new();
        let mut pos = input;
        loop {
            match parser(pos) {
                Parsed::Some(head, tail) => {
                    re.push(head);
                    pos = tail;
                }
                Parsed::None(_) => break,
            }
        }
        Parsed::Some(re, pos)
    }
}

Playground

请注意,我已从函数指针切换为参数的通用类型:

fn some<T>(parser: fn(&str) -> Parsed<T>) // before
fn some<T>(parser: impl Fn(&str) -> Parsed<T>) // after

我主张对您的所有功能执行此操作,以便您拥有一致且可连接的API。 这是许多解析库(包括我自己的peresil)采用的模式。

另请参阅: