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
use crate::error::{Error, ErrorType};
use crate::json::{general_tokens::*, ParseTokens, StackTokens, JSON};
use crate::scanner::Scanner;
// Given the json_document structure where the iterator index is in the
// start of a Unicode escape sequence values, i.e. X in \uXXXX,
// get the decimal representation of the escape sequence.
fn parse_escape_sequence(
index_start: usize,
scanner: &mut Scanner,
) -> Result<u32, Error> {
// The decimal representation of the Unicode escape sequence.
let mut uffff: u32 = 0;
// Unicode escape sequence is defined
// as \uxxxx, where x is ASCII Hex value.
for _ in 0..4 {
let next = scanner.next();
if next.is_none() {
return Err(Error::new(
ErrorType::E104,
index_start,
scanner.current().index + 1,
));
}
if !scanner.current().character.is_ascii_hexdigit() {
// Invalid character found in Unicode escape sequence.
return Err(Error::new(
ErrorType::E117,
index_start,
scanner.current().index + 1,
));
}
let hex = scanner.current().character.to_digit(16).unwrap();
uffff = uffff * 16 + hex
}
// Return the decimal value of the Unicode escape sequence.
Ok(uffff)
}
fn validate(
json_document: &mut JSON,
scanner: &mut Scanner,
) -> Result<(usize, String), ()> {
// Save the position of the first character.
// This will help us set a range that will highlight the whole incorrect value
// in case of an error.
//
// Example:
//
// ```rust
// // Invalid `"unterminated` root value in JSON document.
// let text: &str = "\"unterminated";
// let errors = jsonprima::validate(&text);
// println!("{:#?}", errors); // => [("E104", 0, 13)]
// ```
let index_start = scanner.current().index;
// The parsed string value which will be returned by this function.
let mut string_value: Vec<char> = Vec::new();
// Parse all characters as string values until quotation mark.
loop {
scanner.next().ok_or_else(|| {
// No more characters to parse.
let err = Error::new(ErrorType::E104, index_start, scanner.current().index + 1);
json_document.errors.push(err);
})?;
// End of string reached. We have successfully parse the JSON string.
if scanner.current().character == '"' {
json_document.last_parsed_token = Some(ParseTokens::String);
return Ok((index_start, string_value.into_iter().collect::<String>()));
}
// In case the character is not closing quotation mark and exists,
// validate it based on the rules of RFC 8259.
match scanner.current().character {
'\\' => {
// Start of escape character.
// Read the next character to find out more.
scanner.next().ok_or_else(|| {
// No more characters to parse.
let err = Error::new(ErrorType::E104, index_start, scanner.current().index + 1);
json_document.errors.push(err);
})?;
match scanner.current().character {
// Valid escape character sequence.
'/' => {
string_value.push('/');
continue;
}
'\\' => {
string_value.push('\\');
continue;
}
'"' => {
string_value.push('"');
continue;
}
'b' => {
string_value.push('\x08');
continue;
}
'f' => {
string_value.push('\x0C');
continue;
}
'n' => {
string_value.push('\n');
continue;
}
'r' => {
string_value.push('\r');
continue;
}
't' => {
string_value.push('\t');
continue;
}
// Start of Unicode escape sequence.
'u' => {
// Unicode escape sequences can form a surrogate pair.
// Parse the first escape sequence
// and if is invalid we assume that is part of
// a surrogate pair and we parse the next one.
// If the second escape sequence forms an invalid
// surrogate pair then we return with an error.
// If the first escape sequence is valid, then we
// do not have to parse the second, as it is not a
// surrogate pair.
let high_surrogate: u32 = parse_escape_sequence(index_start, scanner)
.or_else(|err| {
json_document.errors.push(err);
Err(())
})?;
// Check parsed Unicode value.
match std::char::from_u32(high_surrogate) {
// We successfully parsed the Unicode
// escaped sequence, no surrogate pair.
Some(val) => {
string_value.push(val);
continue;
}
None => {
// We couldn't parse the Unicode escape
// sequence. This most likely means that
// is part of a surrogate pair.
// Start parsing the next Unicode escape sequence,
// as low surrogate pair.
scanner.next().ok_or_else(|| {
// Invalid Unicode escape sequence in second surrogate pair.
let err =
Error::new(ErrorType::E119, index_start, scanner.current().index + 1);
json_document.errors.push(err);
})?;
if scanner.current().character != '\\' {
let err =
Error::new(ErrorType::E119, index_start, scanner.current().index + 1);
json_document.errors.push(err);
return Err(());
}
scanner.next().ok_or_else(|| {
// Invalid Unicode escape sequence in second surrogate pair.
let err =
Error::new(ErrorType::E119, index_start, scanner.current().index + 1);
json_document.errors.push(err);
})?;
if scanner.current().character != 'u' {
let err =
Error::new(ErrorType::E119, index_start, scanner.current().index + 1);
json_document.errors.push(err);
return Err(());
}
let low_surrogate: u32 = parse_escape_sequence(index_start, scanner)
.or_else(|err| {
json_document.errors.push(err);
Err(())
})?;
// Borrowed from https://stackoverflow.com/a/23920015
let unicode_value = (high_surrogate << 10) + low_surrogate - 0x35f_dc00;
match std::char::from_u32(unicode_value) {
Some(val) => {
string_value.push(val);
continue;
}
None => {
// Invalid Unicode character in JSON string.
let err = Error::new(
ErrorType::E118,
index_start,
scanner.current().index + 1,
);
json_document.errors.push(err);
return Err(());
}
}
}
}
}
HORIZONTAL_TAB | NEW_LINE | CARRIAGE_RETURN => {
// Raw use of control characters in JSON string.
let err =
Error::new(ErrorType::E101, index_start, scanner.current().index + 1);
json_document.errors.push(err);
return Err(());
}
_ => {
// Invalid escape character in JSON string.
let err =
Error::new(ErrorType::E116, index_start, scanner.current().index + 1);
json_document.errors.push(err);
return Err(());
}
}
}
HORIZONTAL_TAB | NEW_LINE | CARRIAGE_RETURN => {
// Raw use of control characters in JSON string.
let err = Error::new(ErrorType::E101, index_start, scanner.current().index + 1);
json_document.errors.push(err);
return Err(());
}
// Valid non escape or control character.
val => {
string_value.push(val);
continue;
}
}
}
}
pub fn validate_string(
json_document: &mut JSON,
scanner: &mut Scanner,
) -> Result<(), ()> {
match &json_document.last_parsed_token {
Some(last_parsed_token) => match last_parsed_token {
ParseTokens::BeginObject
| ParseTokens::ValueSeparator
| ParseTokens::NameSeparator
| ParseTokens::BeginArray => match json_document.stack.last() {
Some(token) => match token {
StackTokens::NameSeparator => {
json_document.stack.pop();
json_document.object_has_valid_member = true;
match validate(json_document, scanner) {
Ok(_) => Ok(()),
Err(_) => Err(()),
}
}
StackTokens::BeginObject => {
json_document.object_has_valid_member = false;
match validate(json_document, scanner) {
Ok((index_start, val)) => {
if json_document
.object_member_names
.last_mut()
.unwrap()
.contains(&val)
{
let last_parsed_index = scanner.current().index;
let err =
Error::new(ErrorType::E144, index_start, last_parsed_index + 1);
json_document.errors.push(err);
Err(())
} else {
json_document
.object_member_names
.last_mut()
.unwrap()
.push(val);
Ok(())
}
}
Err(_) => Err(()),
}
}
StackTokens::BeginArray => match validate(json_document, scanner) {
Ok(_) => Ok(()),
Err(_) => Err(()),
},
},
None => match validate(json_document, scanner) {
Ok(_) => Ok(()),
Err(_) => Err(()),
},
},
// Illegal string after structural token. Expected comma or colon.
_ => {
let last_parsed_index = scanner.current().index;
let err = Error::new(ErrorType::E114, last_parsed_index, last_parsed_index + 1);
json_document.errors.push(err);
Err(())
}
},
None => {
json_document.root_value_parsed = true;
match validate(json_document, scanner) {
Ok(_) => Ok(()),
Err(_) => Err(()),
}
}
}
}