6 个版本

0.3.0 2023年3月5日
0.2.1 2022年2月16日
0.1.2 2022年1月4日
0.1.1 2021年12月11日

#1518 in 数据结构

MIT/Apache

18KB
431

sexpr_parser

泛型 S-Expression 解析器。

需要将 S-Expression 字符串解析成自己的数据结构?没问题!只需实现 SexprFactory 特性并调用 parse 函数。

示例

假设 S你的 数据结构,而 SF 是一个知道如何构建 S 的值的类型。以下是解析它的方法

use sexpr_parser::{parse, Parser};

assert_eq!(
    SF.parse("(hello . \"world\")"),
    Ok(SF.pair(SF.symbol("hello"), SF.string("world")))
);

为了使此操作生效,为 SF 实现一个 SexprFactory 特性


use sexpr_parser::SexprFactory;

/// Your amazing S-expression data structure
#[derive(Debug, PartialEq)]
enum S {
    Nil,
    Int(i64),
    Float(f64),
    Symbol(String),
    String(String),
    Pair(Box<(S, S)>),
}

struct SF;

impl SexprFactory for SF {
    type Sexpr = S;
    type Integer = i64;
    type Float = f64;

    fn int(&mut self, x: i64) -> S {
        S::Int(x)
    }

    fn float(&mut self, x: f64) -> Self::Sexpr {
        S::Float(x)
    }

    fn symbol(&mut self, x: &str) -> Self::Sexpr {
        S::Symbol(x.to_string())
    }

    fn string(&mut self, x: &str) -> Self::Sexpr {
        S::String(x.to_string())
    }

    fn list(&mut self, x: Vec<Self::Sexpr>) -> Self::Sexpr {
        let mut tail = S::Nil;
        for item in x.into_iter().rev() {
            tail = S::pair(item, tail)
        }
        tail
    }

    fn pair(&mut self, a: Self::Sexpr, b: Self::Sexpr) -> Self::Sexpr {
        S::Pair(Box::new((a, b)))
    }
}

请注意,您甚至可以使用第三方数据结构而不是您自己的 S。您需要做的就是定义和实现一个工厂结构。

无运行时依赖