-
Notifications
You must be signed in to change notification settings - Fork 19
/
json_grammar.rs
107 lines (96 loc) · 3.03 KB
/
json_grammar.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use crate::json_grammar_trait::*;
use parol_runtime::Result;
use std::fmt::{Debug, Display, Error, Formatter};
impl Display for Json<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> {
write!(f, "{}", self.value)
}
}
impl Display for Value<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> {
match self {
Value::String(v) => write!(f, "{}", v.string.string.text()),
Value::Number(v) => write!(f, "{}", v.number.number.text()),
Value::Object(v) => write!(f, "{{{}}}", v.object.object_suffix),
Value::Array(v) => write!(f, "[{}]", v.array.array_suffix),
Value::True(_) => write!(f, "true"),
Value::False(_) => write!(f, "false"),
Value::Null(_) => write!(f, "null"),
}
}
}
impl Display for ObjectSuffix<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> {
match self {
ObjectSuffix::PairObjectListRBrace(o) => write!(
f,
"{}{}",
o.pair,
o.object_list
.iter()
.map(|e| format!("{}", e))
.collect::<Vec<std::string::String>>()
.join("")
),
ObjectSuffix::RBrace(_) => Ok(()),
}
}
}
impl Display for ObjectList<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> {
write!(f, ", {}", self.pair)
}
}
impl Display for ArraySuffix<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> {
match self {
ArraySuffix::ValueArrayListRBracket(a) => write!(
f,
"{}{}",
a.value,
a.array_list
.iter()
.map(|e| format!("{}", e))
.collect::<Vec<std::string::String>>()
.join("")
),
ArraySuffix::RBracket(_) => Ok(()),
}
}
}
impl Display for ArrayList<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> {
write!(f, ", {}", self.value)
}
}
impl Display for Pair<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> {
write!(f, "{}: {}", self.string.string.text(), self.value)
}
}
///
/// Data structure used to build up a json structure during parsing
///
#[derive(Debug, Default)]
pub struct JsonGrammar<'t> {
pub json: Option<Json<'t>>,
}
impl Display for JsonGrammar<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::result::Result<(), Error> {
match &self.json {
Some(json) => write!(f, "{}", json),
None => write!(f, "No parse result"),
}
}
}
impl JsonGrammar<'_> {
pub fn new() -> Self {
JsonGrammar::default()
}
}
impl<'t> JsonGrammarTrait<'t> for JsonGrammar<'t> {
fn json(&mut self, arg: &Json<'t>) -> Result<()> {
self.json = Some(arg.clone());
Ok(())
}
}