#json-parser #spans #packrat #json-text #white-space #position #items

textparse

一个基于Packrat解析的声明式解析器库

3个不稳定版本

0.1.0 2022年12月25日
0.0.2 2022年11月21日
0.0.1 2022年11月7日

2639解析器实现

每月下载量 43
用于 2 个crate(通过 ffmml

MIT/Apache

29KB
781

textparse

textparse Documentation Actions Status License

一个基于Packrat解析的声明式解析器Rust库。

示例

以下代码实现了一个JSON子集格式的解析器

use textparse::{
    components::{AnyChar, Char, Digit, Eos, Items, NonEmpty, Not, Str, While, Whitespace},
    Parse, Parser, Position, Span,
};

#[derive(Clone, Span, Parse)]
struct JsonValue(WithoutWhitespaces<JsonValueInner>);

#[derive(Clone, Span, Parse)]
#[parse(name = "a JSON value")]
enum JsonValueInner {
    Null(JsonNull),
    String(JsonString),
    Number(JsonNumber),
    Array(JsonArray),
    Object(JsonObject),
}

#[derive(Clone, Span, Parse)]
struct JsonNull(Str<'n', 'u', 'l', 'l'>);

#[derive(Clone, Span, Parse)]
#[parse(name = "a JSON string")]
struct JsonString(Char<'"'>, While<(Not<Char<'"'>>, AnyChar)>, Char<'"'>);

#[derive(Clone, Span, Parse)]
#[parse(name = "a JSON number")]
struct JsonNumber(NonEmpty<While<Digit>>);

#[derive(Clone, Span, Parse)]
#[parse(name = "a JSON array")]
struct JsonArray(Char<'['>, Csv<JsonValue>, Char<']'>);

#[derive(Clone, Span, Parse)]
#[parse(name = "a JSON object")]
struct JsonObject(Char<'{'>, Csv<JsonObjectItem>, Char<'}'>);

#[derive(Clone, Span, Parse)]
struct JsonObjectItem(WithoutWhitespaces<JsonString>, Char<':'>, JsonValue);

#[derive(Clone, Span, Parse)]
struct Csv<T>(Items<T, Char<','>>);

#[derive(Clone, Span, Parse)]
struct WithoutWhitespaces<T>(While<Whitespace>, T, While<Whitespace>);

您可以通过以下方式运行上述解析器:examples/check_json.rs

$ echo '["foo",null,{"key": "value"}, 123]' | cargo run --example check_json
OK: the input string is a JSON text.

$ echo '["foo" null]' | cargo run --example check_json
Error: expected one of ',', or ']'
  --> <STDIN>:1:8
  |
1 | ["foo" null]
  |        ^ expected one of ',', or ']'

依赖项

~3.5MB
~74K SLoC