2022-10-15 23:36:04 -07:00
|
|
|
#![feature(assert_matches)]
|
|
|
|
#![allow(dead_code)] //TODO eventually turn this off
|
2022-10-16 01:37:51 -07:00
|
|
|
mod bnf;
|
2022-10-16 19:16:21 -07:00
|
|
|
mod combinators;
|
2022-10-16 18:57:10 -07:00
|
|
|
mod parser;
|
2022-10-16 19:07:58 -07:00
|
|
|
mod primitives;
|
2022-10-16 17:33:10 -07:00
|
|
|
mod sequence;
|
2022-10-16 01:37:51 -07:00
|
|
|
|
2022-10-16 18:57:10 -07:00
|
|
|
use parser::{ParseResult, Parser};
|
2022-10-16 00:30:06 -07:00
|
|
|
|
2022-10-16 01:29:48 -07:00
|
|
|
fn choice<P1, P2, I, O, E>(parser1: P1, parser2: P2) -> impl Parser<I, O, E>
|
|
|
|
where
|
|
|
|
P1: Parser<I, O, E>,
|
|
|
|
P2: Parser<I, O, E>,
|
|
|
|
I: Copy,
|
|
|
|
{
|
|
|
|
move |input| match parser1.parse(input) {
|
|
|
|
ok @ Ok(..) => ok,
|
|
|
|
Err(_e) => parser2.parse(input),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-10 00:13:39 -07:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2022-10-16 19:16:21 -07:00
|
|
|
use crate::combinators::one_or_more;
|
2022-10-16 19:07:58 -07:00
|
|
|
use crate::primitives::literal;
|
2022-10-15 23:36:04 -07:00
|
|
|
use std::assert_matches::assert_matches;
|
2022-10-16 01:42:03 -07:00
|
|
|
use std::collections::HashMap;
|
2022-10-10 00:13:39 -07:00
|
|
|
|
|
|
|
#[test]
|
2022-10-15 23:41:22 -07:00
|
|
|
fn test_parsing() {
|
2022-10-15 23:36:04 -07:00
|
|
|
let output = literal("a")("a yolo");
|
2022-10-15 23:41:22 -07:00
|
|
|
assert_matches!(output.unwrap(), ("a", " yolo"));
|
|
|
|
}
|
|
|
|
|
2022-10-16 01:29:48 -07:00
|
|
|
#[test]
|
|
|
|
fn test_choice() {
|
|
|
|
let p = choice(literal("gnostika").to(1), one_or_more(literal(" ")).to(2));
|
|
|
|
assert_eq!(p.parse("gnostika twentynine"), Ok((1, " twentynine")));
|
|
|
|
}
|
2022-10-16 01:36:20 -07:00
|
|
|
|
|
|
|
/*
|
|
|
|
* JSON BNF
|
|
|
|
* <JSON> ::= <value>
|
|
|
|
<value> ::= <object> | <array> | <boolean> | <string> | <number> | <null>
|
|
|
|
<array> ::= "[" [<value>] {"," <value>}* "]"
|
|
|
|
<object> ::= "{" [<property>] {"," <property>}* "}"
|
|
|
|
<property> ::= <string> ":" <value>
|
|
|
|
*/
|
2022-10-16 01:42:03 -07:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
enum JsonValue {
|
|
|
|
Null,
|
|
|
|
Bool(bool),
|
|
|
|
Str(String),
|
|
|
|
Num(f64),
|
|
|
|
Array(Vec<JsonValue>),
|
|
|
|
Object(HashMap<String, JsonValue>),
|
|
|
|
}
|
2022-10-16 01:36:20 -07:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn parse_json() {
|
2022-10-16 01:42:03 -07:00
|
|
|
let json_null = literal("null").to(JsonValue::Null);
|
|
|
|
let json_true = literal("true").to(JsonValue::Bool(true));
|
|
|
|
let json_false = literal("false").to(JsonValue::Bool(false));
|
2022-10-16 01:36:20 -07:00
|
|
|
|
|
|
|
let json_value = choice(json_null, choice(json_true, json_false));
|
|
|
|
|
2022-10-16 01:42:03 -07:00
|
|
|
assert_matches!(json_value.parse("true"), Ok((JsonValue::Bool(true), "")));
|
2022-10-16 01:36:20 -07:00
|
|
|
}
|
2022-10-10 00:13:39 -07:00
|
|
|
}
|