rust-parser-combinator/src/lib.rs
2022-10-16 19:21:43 -07:00

53 lines
1.3 KiB
Rust

#![allow(dead_code)] //TODO eventually turn this off
mod bnf;
mod choice;
mod combinators;
mod parser;
mod primitives;
mod sequence;
pub use parser::{ParseResult, Parser};
#[cfg(test)]
mod tests {
use super::*;
use crate::choice::choice;
use crate::primitives::literal;
use std::collections::HashMap;
#[test]
fn test_parsing() {
let output = literal("a")("a yolo");
assert_eq!(output.unwrap(), ("a", " yolo"));
}
/*
* JSON BNF
* <JSON> ::= <value>
<value> ::= <object> | <array> | <boolean> | <string> | <number> | <null>
<array> ::= "[" [<value>] {"," <value>}* "]"
<object> ::= "{" [<property>] {"," <property>}* "}"
<property> ::= <string> ":" <value>
*/
#[derive(Debug, Clone, PartialEq)]
enum JsonValue {
Null,
Bool(bool),
Str(String),
Num(f64),
Array(Vec<JsonValue>),
Object(HashMap<String, JsonValue>),
}
#[test]
fn parse_json() {
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));
let json_value = choice(json_null, choice(json_true, json_false));
assert_eq!(json_value.parse("true"), Ok((JsonValue::Bool(true), "")));
}
}