use pest::Parser;
use pest::iterators::Pair;
use pest_derive::Parser;
use thiserror::Error;
#[derive(Parser)]
#[grammar = "./json.pest"]
pub struct JSONParser {}
#[derive(Debug, Error)]
pub enum JSONError {
#[error("Failed to read file {0}")]
IO(#[from] std::io::Error),
#[error("Failed to parse float {0}")]
ParseFloat(#[from] std::num::ParseFloatError),
#[error("Pest parse error: {0}")]
Pest(#[from] Box<pest::error::Error<Rule>>),
#[error("Unexpected parser structure")]
Unexpected,
}
impl From<pest::error::Error<Rule>> for JSONError {
fn from(err: pest::error::Error<Rule>) -> Self{
JSONError::Pest(Box::new(err))
}
}
#[derive(Debug)]
pub enum JSONValue<'a> {
Object(Vec<(&'a str, JSONValue<'a>)>),
Array(Vec<JSONValue<'a>>),
String(&'a str),
Number(f64),
Boolean(bool),
Null,
}
pub fn parse_json_file(input: &str) -> Result<JSONValue<'_>, JSONError> {
let json = JSONParser::parse(Rule::file, input)?
.next()
.ok_or(JSONError::Unexpected)?;
fn parse_value(pair: Pair<Rule>) -> JSONValue {
match pair.as_rule() {
Rule::object => JSONValue::Object(
pair.into_inner()
.map(|pair| {
let mut pair_rules = pair.into_inner();
let pair_name = pair_rules
.next()
.unwrap()
.into_inner()
.next()
.unwrap()
.as_str();
let pair_value = parse_value(pair_rules.next().unwrap());
(pair_name, pair_value)
})
.collect(),
),
Rule::array => {
JSONValue::Array(pair.into_inner().map(|value| parse_value(value)).collect())
}
Rule::string => JSONValue::String(pair.into_inner().next().unwrap().as_str()),
Rule::number => JSONValue::Number(pair.as_str().parse::<f64>().unwrap()),
Rule::boolean => JSONValue::Boolean(pair.as_str().parse().unwrap()),
Rule::null => JSONValue::Null,
Rule::file
| Rule::char
| Rule::exp
| Rule::frac
| Rule::inner
| Rule::int
| Rule::EOI
| Rule::value
| Rule::pair
| Rule::WHITESPACE => unreachable!(),
}
}
Ok(parse_value(json))
}
pub fn serialize_jsonvalue(val: &JSONValue) -> String {
use JSONValue::*;
match val {
Object(o) => {
let contents: Vec<_> = o
.iter()
.map(|(name, value)| format!("\"{}\":{}", name, serialize_jsonvalue(value)))
.collect();
format!("{{{}}}", contents.join(","))
}
Array(a) => {
let contents: Vec<_> = a.iter().map(serialize_jsonvalue).collect();
format!("[{}]", contents.join(","))
}
String(s) => format!("\"{}\"", s),
Number(n) => format!("{}", n),
Boolean(b) => format!("{}", b),
Null => "null".to_string(),
}
}
pub const RULE_FILE: Rule = Rule::file;
pub const RULE_OBJECT: Rule = Rule::object;
pub const RULE_ARRAY: Rule = Rule::array;
pub const RULE_PAIR: Rule = Rule::pair;
pub const RULE_VALUE: Rule = Rule::value;
pub const RULE_STRING: Rule = Rule::string;
pub const RULE_NUMBER: Rule = Rule::number;
pub const RULE_BOOLEAN: Rule = Rule::boolean;
pub const RULE_NULL: Rule = Rule::null;
pub const RULE_WHITESPACE: Rule = Rule::WHITESPACE;
pub const RULE_INT: Rule = Rule::int;
pub const RULE_FRAC: Rule = Rule::frac;
pub const RULE_EXP: Rule = Rule::exp;
pub const RULE_INNER: Rule = Rule::inner;
pub const RULE_CHAR: Rule = Rule::char;