textparse

textparse Documentation Actions Status License

A Rust library to declaratively implement parsers that are based on Packrat Parsing.

Examples

The following code implements a parser for a JSON subset format: ```rust use textparse::{ components::{ Char, Eos, Items, NonEmpty, SkipWhitespaces, StartsWith, StaticStr, Until, While, }, Parse, ParseError, ParseResult, Parser, Position, Span, };

[derive(Clone, Span, Parse)]

struct JsonValue(WithoutWhitespaces);

[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)]

[parse(name = "null")]

struct JsonNull(StartsWith);

[derive(Clone, Span, Parse)]

[parse(name = "a JSON string")]

struct JsonString(Char<'"'>, Until>, Char<'"'>);

[derive(Clone, Span, Parse)]

[parse(name = "a JSON number")]

struct JsonNumber(NonEmpty>);

[derive(Clone, Span, Parse)]

[parse(name = "a JSON array")]

struct JsonArray(Char<'['>, Csv, Char<']'>);

[derive(Clone, Span, Parse)]

[parse(name = "a JSON object")]

struct JsonObject(Char<'{'>, Csv, Char<'}'>);

[derive(Clone, Span, Parse)]

struct JsonObjectItem(WithoutWhitespaces, Char<':'>, JsonValue);

[derive(Clone, Span, Parse)]

struct Csv(Items>);

[derive(Clone, Span, Parse)]

struct WithoutWhitespaces(SkipWhitespaces, T, SkipWhitespaces);

struct Null; impl StaticStr for Null { fn static_str() -> &'static str { "null" } }

[derive(Debug, Clone, Span)]

struct Digit(Position, Position); impl Parse for Digit { fn parse(parser: &mut Parser) -> ParseResult { parser .peekchar() .filter(|c| c.isasciidigit()) .okor(ParseError)?; let (start, end) = parser.consume_chars(1); Ok(Self(start, end)) } } ```

You can run the above parser via examples/checkjson.rs as follows: ```console $ echo '["foo",null,{"key": "value"}, 123]' | cargo run --example checkjson OK: the input string is a JSON text.

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