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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
//! Provides the core JSON-parsing functionality.
use crate::error::{ParseError, TracebackError};
use crate::Value;
use std::borrow::Borrow;
use std::iter::Peekable;
use std::str::Chars;
const MAX_DEPTH: usize = 256;
impl Value {
/// Parse a string into a JSON value.
///
/// If unsuccessful, returns a `TracebackError`, giving information about the location of the syntax error within the JSON string.
///
/// ## Usage
/// ```
/// let value = Value::parse("[1, 2, 3]");
/// ```
pub fn parse(s: impl AsRef<str>) -> Result<Self, TracebackError> {
let chars = s.as_ref().chars();
let mut parser = Parser::new(chars, MAX_DEPTH);
let value = parser.parse_value()?;
parser.expect_eof()?;
Ok(value)
}
/// Parse a string into a JSON value with the specified maximum recursion depth.
///
/// If unsuccessful, returns a `TracebackError`, giving information about the location of the syntax error within the JSON string.
///
/// ## Usage
/// ```
/// let value = Value::parse_max_depth("[1, 2, 3]", 8);
/// ```
pub fn parse_max_depth(s: impl AsRef<str>, max_depth: usize) -> Result<Self, TracebackError> {
let chars = s.as_ref().chars();
let mut parser = Parser::new(chars, max_depth);
let value = parser.parse_value()?;
parser.expect_eof()?;
Ok(value)
}
}
/// Encapsulates the internal state of the parsing process.
struct Parser<'a> {
chars: Peekable<Chars<'a>>,
depth: usize,
max_depth: usize,
line: usize,
column: usize,
next_line: usize,
next_column: usize,
}
impl<'a> Parser<'a> {
/// Initialise a new parser.
fn new(chars: Chars<'a>, max_depth: usize) -> Self {
Self {
chars: chars.peekable(),
depth: 0,
max_depth,
line: 1,
column: 1,
next_line: 1,
next_column: 1,
}
}
/// Get the next character to be parsed.
fn next(&mut self) -> Result<char, TracebackError> {
if let Some(c) = self.chars.next() {
self.line = self.next_line;
self.column = self.next_column;
if c == '\n' {
self.next_line += 1;
self.next_column = 0;
} else if c != '\r' {
self.next_column += 1;
}
return Ok(c);
}
Err(self.traceback(ParseError::UnexpectedEOF))
}
/// Convert a regular parsing error into a traceback error containing the location of the error.
fn traceback(&self, e: ParseError) -> TracebackError {
TracebackError {
line: self.line,
column: self.column,
kind: e,
}
}
/// Attempt to parse a value from the character stream.
fn parse_value(&mut self) -> Result<Value, TracebackError> {
self.flush_whitespace();
match self.next() {
Ok('"') => self.parse_string(),
Ok('[') => self.parse_array(),
Ok('{') => self.parse_object(),
Ok(c) => self.parse_literal(c),
Err(e) => Err(e),
}
}
/// Attempt to parse a string from the character stream.
fn parse_string(&mut self) -> Result<Value, TracebackError> {
let mut string = String::with_capacity(256);
let mut backslash = false;
loop {
let c = self.next()?;
if backslash {
match c {
'"' => string.push(0x22 as char),
'\\' => string.push(0x5c as char),
'/' => string.push(0x2f as char),
'b' => string.push(0x08 as char),
'f' => string.push(0x0c as char),
'n' => string.push(0x0a as char),
'r' => string.push(0x0d as char),
't' => string.push(0x09 as char),
'u' => {
let hex: String = [self.next()?, self.next()?, self.next()?, self.next()?]
.iter()
.collect();
let code = u16::from_str_radix(&hex, 16)
.map_err(|_| self.traceback(ParseError::InvalidEscapeSequence))?;
let new_char = if let Some(new_char) = char::from_u32(code as u32) {
new_char
} else {
quiet_assert(
self.next()? == '\\' && self.next()? == 'u',
self.traceback(ParseError::InvalidEscapeSequence),
)?;
let hex: String =
[self.next()?, self.next()?, self.next()?, self.next()?]
.iter()
.collect();
let code_2 = u16::from_str_radix(&hex, 16)
.map_err(|_| self.traceback(ParseError::InvalidEscapeSequence))?;
char::decode_utf16([code, code_2])
.next()
.ok_or_else(|| self.traceback(ParseError::InvalidEscapeSequence))?
.map_err(|_| self.traceback(ParseError::InvalidEscapeSequence))?
};
string.push(new_char);
}
_ => return Err(self.traceback(ParseError::InvalidEscapeSequence)),
}
backslash = false;
} else if c == '\\' {
backslash = true;
} else if c == '"' {
break;
} else {
match c as u32 {
0x20..=0x21 | 0x23..=0x5b | 0x5d..=0x10ffff => string.push(c),
_ => return Err(self.traceback(ParseError::InvalidToken)),
}
}
}
Ok(Value::String(string))
}
/// Attempt to parse an array from the character stream.
fn parse_array(&mut self) -> Result<Value, TracebackError> {
self.inc_depth()?;
let mut array: Vec<Value> = Vec::with_capacity(16);
loop {
self.flush_whitespace();
match self.chars.peek() {
Some(&']') => {
if array.is_empty() {
break;
} else {
return Err(self.traceback(ParseError::TrailingComma));
}
}
Some(_) => array.push(self.parse_value()?),
None => return Err(self.traceback(ParseError::UnexpectedEOF)),
}
self.flush_whitespace();
match self.chars.peek() {
Some(&',') => (),
Some(&']') => break,
Some(_) => return Err(self.traceback(ParseError::InvalidToken)),
None => return Err(self.traceback(ParseError::UnexpectedEOF)),
}
self.next()?;
}
self.next()?;
self.dec_depth();
Ok(Value::Array(array))
}
/// Attempt to parse an object from the character stream.
fn parse_object(&mut self) -> Result<Value, TracebackError> {
self.inc_depth()?;
let mut object: Vec<(String, Value)> = Vec::with_capacity(16);
let mut trailing_comma = false;
loop {
self.flush_whitespace();
match self.chars.peek() {
Some(&'}') => {
if trailing_comma {
return Err(self.traceback(ParseError::TrailingComma));
} else {
break;
}
}
Some(&',') => {
if trailing_comma {
return Err(self.traceback(ParseError::InvalidToken));
} else {
trailing_comma = true;
if object.is_empty() {
return Err(self.traceback(ParseError::InvalidToken));
}
self.next()?;
}
}
Some(_) => {
trailing_comma = false;
let string_start = self.next()?;
quiet_assert(
string_start == '"',
self.traceback(ParseError::InvalidToken),
)?;
let key = self.parse_string()?.as_str().unwrap().to_string();
self.flush_whitespace();
let sep = self.next()?;
quiet_assert(sep == ':', self.traceback(ParseError::InvalidToken))?;
self.flush_whitespace();
let value = self.parse_value()?;
object.push((key, value));
}
None => return Err(self.traceback(ParseError::UnexpectedEOF)),
}
}
self.next()?;
self.dec_depth();
Ok(Value::Object(object))
}
/// Attempt to parse a literal from the character stream.
fn parse_literal(&mut self, c: char) -> Result<Value, TracebackError> {
let mut string = String::from(c);
while self.chars.peek().map_or(false, |&c| is_literal(c)) {
string.push(self.next().unwrap());
}
match string.as_str() {
"null" => Ok(Value::Null),
"true" => Ok(Value::Bool(true)),
"false" => Ok(Value::Bool(false)),
number => Ok(Value::Number(
number
.parse()
.map_err(|_| self.traceback(ParseError::InvalidToken))?,
)),
}
}
/// Assert that there are no more characters to be parsed, or return an error.
fn expect_eof(&mut self) -> Result<(), TracebackError> {
self.flush_whitespace();
match self.chars.peek() {
Some(_) => Err(self.traceback(ParseError::InvalidToken)),
None => Ok(()),
}
}
/// Fast-forward the iterator until the next character is not whitespace.
fn flush_whitespace(&mut self) {
while self.chars.peek().map_or(false, is_whitespace) {
self.next().ok();
}
}
fn inc_depth(&mut self) -> Result<(), TracebackError> {
if self.depth == self.max_depth {
Err(self.traceback(ParseError::RecursionDepthExceeded))
} else {
self.depth += 1;
Ok(())
}
}
fn dec_depth(&mut self) {
self.depth -= 1;
}
}
/// Assert a condition, or return an error.
fn quiet_assert(condition: bool, error: TracebackError) -> Result<(), TracebackError> {
if condition {
Ok(())
} else {
Err(error)
}
}
/// Check whether a character is whitespace according to the specification.
fn is_whitespace(c: impl Borrow<char>) -> bool {
matches!(c.borrow(), ' ' | '\t' | '\n' | '\r')
}
/// Check whether the character is reserved.
fn is_literal(c: impl Borrow<char>) -> bool {
let c = c.borrow();
!is_whitespace(c) && *c != ',' && *c != '}' && *c != ']'
}