rust-parser-combinator/src/lib.rs

66 lines
1.7 KiB
Rust
Raw Normal View History

2022-10-15 23:36:04 -07:00
#![allow(dead_code)] //TODO eventually turn this off
2022-10-16 01:37:51 -07:00
mod bnf;
2022-10-16 19:21:43 -07:00
mod choice;
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 19:21:43 -07:00
pub use parser::{ParseResult, Parser};
2022-10-16 01:29:48 -07:00
2022-10-10 00:13:39 -07:00
#[cfg(test)]
mod tests {
use super::*;
2022-10-16 19:21:43 -07:00
use crate::choice::choice;
2022-10-17 00:47:19 -07:00
use crate::primitives::{any_char, literal, literal_char, one_of, pred};
2022-10-16 21:36:23 -07:00
use crate::sequence::seq;
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-16 19:21:43 -07:00
assert_eq!(output.unwrap(), ("a", " yolo"));
2022-10-16 01:29:48 -07:00
}
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 19:21:43 -07:00
#[derive(Debug, Clone, PartialEq)]
2022-10-16 01:42:03 -07:00
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);
2022-10-16 21:36:23 -07:00
let json_bool = choice((
literal("true").to(JsonValue::Bool(true)),
literal("false").to(JsonValue::Bool(false)),
));
2022-10-16 01:36:20 -07:00
2022-10-17 00:47:19 -07:00
let digit = one_of("1234567890");
2022-10-17 00:49:13 -07:00
assert_eq!(digit.parse("3"), Ok(("3", "")));
2022-10-17 00:47:19 -07:00
2022-10-16 21:36:23 -07:00
let json_string = seq((
literal_char('"'),
pred(any_char, |ch| *ch != '"'),
literal_char('"'),
))
.map(|(_, s, _)| JsonValue::Str(s.to_string()));
let json_value = choice((json_null, json_bool, json_string));
2022-10-16 01:36:20 -07:00
2022-10-16 19:21:43 -07:00
assert_eq!(json_value.parse("true"), Ok((JsonValue::Bool(true), "")));
2022-10-16 01:36:20 -07:00
}
2022-10-10 00:13:39 -07:00
}