1
/*
2
 * Hurl (https://hurl.dev)
3
 * Copyright (C) 2024 Orange
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 *          http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 *
17
 */
18
use crate::ast::{JsonListElement, JsonObjectElement, JsonValue, SourceInfo, Template};
19
use crate::combinator::{choice, non_recover, ParseError as ParseErrorTrait};
20
use crate::parser::primitives::{boolean, hex_digit, literal, try_literal};
21
use crate::parser::template::EncodedString;
22
use crate::parser::{templatize, JsonErrorVariant, ParseError, ParseErrorKind, ParseResult};
23
use crate::reader::{Pos, Reader};
24

            
25
use super::placeholder;
26

            
27
27670
pub fn parse(reader: &mut Reader) -> ParseResult<JsonValue> {
28
27670
    choice(
29
27670
        &[
30
27670
            null_value,
31
27670
            boolean_value,
32
27670
            string_value,
33
27670
            number_value,
34
27670
            expression_value,
35
27670
            list_value,
36
27670
            object_value,
37
27670
        ],
38
27670
        reader,
39
27670
    )
40
}
41

            
42
/// Helper for parse, but already knowing that we are inside a JSON body.
43
2760
fn parse_in_json(reader: &mut Reader) -> ParseResult<JsonValue> {
44
2760
    if let Some(c) = reader.peek() {
45
2760
        if c == ',' {
46
            let kind = ParseErrorKind::Json(JsonErrorVariant::EmptyElement);
47
            return Err(ParseError::new(reader.cursor().pos, false, kind));
48
        }
49
    }
50
2760
    match parse(reader) {
51
2720
        Ok(r) => Ok(r),
52
        // The only error that is recoverable is caused by reaching object_value try_literal('{'),
53
        // but this is not recoverable in this case, because we already know that we are in a JSON
54
        // body. So, we change the error to CannotResolve for the object found.
55
40
        Err(e) => match e {
56
            ParseError {
57
                recoverable: true, ..
58
            } => {
59
15
                let kind = ParseErrorKind::Json(JsonErrorVariant::ExpectingElement);
60
15
                Err(ParseError::new(e.pos, false, kind))
61
            }
62
25
            _ => Err(ParseError::new(e.pos, false, e.kind)),
63
        },
64
    }
65
}
66

            
67
27690
pub fn null_value(reader: &mut Reader) -> ParseResult<JsonValue> {
68
27690
    try_literal("null", reader)?;
69
40
    Ok(JsonValue::Null)
70
}
71

            
72
27660
pub fn boolean_value(reader: &mut Reader) -> ParseResult<JsonValue> {
73
27660
    let value = boolean(reader)?;
74
80
    Ok(JsonValue::Boolean(value))
75
}
76

            
77
27560
fn string_value(reader: &mut Reader) -> ParseResult<JsonValue> {
78
27560
    let template = string_template(reader)?;
79
940
    Ok(JsonValue::String(template))
80
}
81

            
82
29360
fn string_template(reader: &mut Reader) -> ParseResult<Template> {
83
29360
    try_literal("\"", reader)?;
84
2750
    let delimiter = Some('"');
85
2750
    let mut chars = vec![];
86
2750
    let start = reader.cursor();
87
    loop {
88
23730
        if reader.peek() == Some('"') || reader.is_eof() {
89
2740
            break;
90
        }
91
20990
        let char = any_char(reader)?;
92
20980
        chars.push(char);
93
    }
94
2740
    let end = reader.cursor();
95
2740

            
96
2740
    let encoded_string = EncodedString {
97
2740
        source_info: SourceInfo::new(start.pos, end.pos),
98
2740
        chars,
99
2740
    };
100
2740
    literal("\"", reader)?;
101
2740
    let elements = templatize(encoded_string)?;
102

            
103
2740
    let template = Template {
104
2740
        delimiter,
105
2740
        elements,
106
2740
        source_info: SourceInfo::new(start.pos, end.pos),
107
2740
    };
108
2740
    Ok(template)
109
}
110

            
111
20990
fn any_char(reader: &mut Reader) -> ParseResult<(char, String, Pos)> {
112
20990
    let start = reader.cursor();
113
20990
    match escape_char(reader) {
114
295
        Ok(c) => Ok((c, reader.read_from(start.index), start.pos)),
115
20695
        Err(e) => {
116
20695
            if e.recoverable {
117
20685
                reader.seek(start);
118
20685
                match reader.read() {
119
                    None => {
120
                        let kind = ParseErrorKind::Expecting {
121
                            value: "char".to_string(),
122
                        };
123
                        Err(ParseError::new(start.pos, true, kind))
124
                    }
125
20685
                    Some(c) => {
126
20685
                        if ['\\', '\x08', '\n', '\x0c', '\r', '\t'].contains(&c) {
127
                            let kind = ParseErrorKind::Expecting {
128
                                value: "char".to_string(),
129
                            };
130
                            Err(ParseError::new(start.pos, true, kind))
131
                        } else {
132
20685
                            Ok((c, reader.read_from(start.index), start.pos))
133
                        }
134
                    }
135
                }
136
            } else {
137
10
                Err(e)
138
            }
139
        }
140
    }
141
}
142

            
143
20990
fn escape_char(reader: &mut Reader) -> ParseResult<char> {
144
20990
    try_literal("\\", reader)?;
145
305
    let start = reader.cursor();
146
305
    match reader.read() {
147
120
        Some('"') => Ok('"'),
148
5
        Some('\\') => Ok('\\'),
149
        Some('/') => Ok('/'),
150
        Some('b') => Ok('\x08'),
151
165
        Some('n') => Ok('\n'),
152
        Some('f') => Ok('\x0c'),
153
        Some('r') => Ok('\r'),
154
        Some('t') => Ok('\t'),
155
15
        Some('u') => unicode(reader),
156
        _ => Err(ParseError::new(
157
            start.pos,
158
            false,
159
            ParseErrorKind::EscapeChar,
160
        )),
161
    }
162
}
163

            
164
15
fn unicode(reader: &mut Reader) -> ParseResult<char> {
165
15
    let start = reader.cursor();
166
15
    let cp1 = hex_value(reader)?;
167
10
    let cp = if is_surrogate(cp1) {
168
10
        literal("\\u", reader)?;
169
10
        let start = reader.cursor();
170
10
        let cp2 = hex_value(reader)?;
171
10
        match cp_surrogate_pair(cp1, cp2) {
172
5
            None => return Err(ParseError::new(start.pos, false, ParseErrorKind::Unicode)),
173
5
            Some(cp) => cp,
174
        }
175
    } else {
176
        cp1
177
    };
178
5
    let c = match char::from_u32(cp) {
179
        None => return Err(ParseError::new(start.pos, false, ParseErrorKind::Unicode)),
180
5
        Some(c) => c,
181
5
    };
182
5
    Ok(c)
183
}
184

            
185
// 0xd800-0xdc00 encodes the high 10 bits of a pair.
186
// 0xdc00-0xe000 encodes the low 10 bits of a pair.
187
// the value is those 20 bits plus 0x10000.
188
const SURR1: u32 = 0xd800;
189
const SURR2: u32 = 0xdc00;
190
const SURR3: u32 = 0xe000;
191
const SURR_SELF: u32 = 0x10000;
192

            
193
/// Returns whether the specified Unicode code point can appear in a surrogate pair.
194
10
fn is_surrogate(cp: u32) -> bool {
195
10
    (SURR1..SURR3).contains(&cp)
196
}
197

            
198
10
fn cp_surrogate_pair(cp1: u32, cp2: u32) -> Option<u32> {
199
10
    if (SURR1..SURR2).contains(&cp1) && (SURR2..SURR3).contains(&cp2) {
200
5
        Some(((cp1 - SURR1) << 10) | ((cp2 - SURR2) + SURR_SELF))
201
    } else {
202
5
        None
203
    }
204
}
205

            
206
25
fn hex_value(reader: &mut Reader) -> ParseResult<u32> {
207
25
    let digit1 = non_recover(hex_digit, reader)?;
208
25
    let digit2 = non_recover(hex_digit, reader)?;
209
25
    let digit3 = non_recover(hex_digit, reader)?;
210
25
    let digit4 = non_recover(hex_digit, reader)?;
211
20
    let value = digit1 * (16 * 16 * 16) + digit2 * (16 * 16) + digit3 * 16 + digit4;
212
20
    Ok(value)
213
}
214

            
215
26645
pub fn number_value(reader: &mut Reader) -> ParseResult<JsonValue> {
216
26645
    let sign = match try_literal("-", reader) {
217
26605
        Err(_) => String::new(),
218
40
        Ok(_) => "-".to_string(),
219
    };
220
26645
    let int = integer(reader)?;
221
970
    let frac = fraction(reader)?;
222
970
    let exp = exponent(reader)?;
223
970
    Ok(JsonValue::Number(format!("{sign}{int}{frac}{exp}")))
224
}
225

            
226
26645
fn integer(reader: &mut Reader) -> ParseResult<String> {
227
26645
    let start = reader.cursor();
228
26645
    match try_literal("0", reader) {
229
        Err(_) => {
230
31503
            let digits = reader.read_while(|c| c.is_ascii_digit());
231
26425
            if digits.is_empty() {
232
25675
                let kind = ParseErrorKind::Expecting {
233
25675
                    value: "number".to_string(),
234
25675
                };
235
25675
                Err(ParseError::new(start.pos, true, kind))
236
            } else {
237
750
                Ok(digits)
238
            }
239
        }
240
220
        Ok(_) => Ok("0".to_string()),
241
    }
242
}
243

            
244
970
fn fraction(reader: &mut Reader) -> ParseResult<String> {
245
970
    match try_literal(".", reader) {
246
        Ok(_) => {
247
3825
            let digits = reader.read_while(|c| c.is_ascii_digit());
248
575
            if digits.is_empty() {
249
                let kind = ParseErrorKind::Expecting {
250
                    value: "digits".to_string(),
251
                };
252
                Err(ParseError::new(reader.cursor().pos, false, kind))
253
            } else {
254
575
                Ok(format!(".{digits}"))
255
            }
256
        }
257
395
        Err(_) => Ok(String::new()),
258
    }
259
}
260

            
261
970
fn exponent(reader: &mut Reader) -> ParseResult<String> {
262
970
    if reader.peek() == Some('e') || reader.peek() == Some('E') {
263
5
        reader.read();
264
5
        let exponent_sign = match try_literal("-", reader) {
265
            Ok(_) => "-".to_string(),
266
5
            Err(_) => match try_literal("+", reader) {
267
                Ok(_) => "+".to_string(),
268
5
                Err(_) => String::new(),
269
            },
270
        };
271
21
        let exponent_digits = reader.read_while(|c| c.is_ascii_digit());
272
5
        Ok(format!("e{exponent_sign}{exponent_digits}"))
273
    } else {
274
965
        Ok(String::new())
275
    }
276
}
277

            
278
25650
fn expression_value(reader: &mut Reader) -> ParseResult<JsonValue> {
279
25650
    let exp = placeholder::parse(reader)?;
280
50
    Ok(JsonValue::Placeholder(exp))
281
}
282

            
283
25600
fn list_value(reader: &mut Reader) -> ParseResult<JsonValue> {
284
25600
    try_literal("[", reader)?;
285
345
    let space0 = whitespace(reader);
286
345
    let mut elements = vec![];
287
345

            
288
345
    // at least one element
289
345
    if reader.peek() != Some(']') {
290
305
        let first_element = list_element(reader)?;
291
305
        elements.push(first_element);
292

            
293
        loop {
294
960
            if reader.peek() == Some(']') {
295
295
                break;
296
            }
297
665
            // Reports "expecting ']'" in case the user forgot to add the last ']', e.g
298
665
            // `[1, 2`
299
665
            if reader.peek() != Some(',') {
300
                break;
301
            }
302
665
            // The reader advances after literal(","), so this saves its position to report an
303
665
            // error in case it happens.
304
665
            let save = reader.cursor();
305
665
            literal(",", reader)?;
306
            // If there is one more comma, e.g. [1, 2,], it's better to report to the user because
307
            // this occurrence is common.
308
2108
            if reader.peek_if(|c| !is_whitespace(c)) == Some(']') {
309
5
                let kind = ParseErrorKind::Json(JsonErrorVariant::TrailingComma);
310
5
                return Err(ParseError::new(save.pos, false, kind));
311
            }
312
660
            let element = list_element(reader)?;
313
655
            elements.push(element);
314
        }
315
    }
316
335
    literal("]", reader)?;
317

            
318
335
    Ok(JsonValue::List { space0, elements })
319
}
320

            
321
965
fn list_element(reader: &mut Reader) -> ParseResult<JsonListElement> {
322
965
    let space0 = whitespace(reader);
323
965
    let value = parse_in_json(reader)?;
324
960
    let space1 = whitespace(reader);
325
960
    Ok(JsonListElement {
326
960
        space0,
327
960
        value,
328
960
        space1,
329
960
    })
330
}
331

            
332
25295
pub fn object_value(reader: &mut Reader) -> ParseResult<JsonValue> {
333
25295
    try_literal("{", reader)?;
334
750
    let space0 = whitespace(reader);
335
750
    let mut elements = vec![];
336
750
    if reader.peek() != Some('}') {
337
715
        let first_element = object_element(reader)?;
338
675
        elements.push(first_element);
339

            
340
        loop {
341
1760
            if reader.peek() == Some('}') {
342
670
                break;
343
            }
344
1090
            // Reports "expecting '}'" in case the user forgot to add the last '}', e.g
345
1090
            // `{"name": "abc"`
346
1090
            if reader.peek() != Some(',') {
347
                break;
348
            }
349
1090
            // The reader advances after literal(","), so this saves its position to report an
350
1090
            // error in case it happens.
351
1090
            let save = reader.cursor();
352
1090
            literal(",", reader)?;
353
            // If there is one more comma, e.g. {"a": "b",}, it's better to report to the user
354
            // because this occurrence is common.
355
7088
            if reader.peek_if(|c| !is_whitespace(c)) == Some('}') {
356
5
                let kind = ParseErrorKind::Json(JsonErrorVariant::TrailingComma);
357
5
                return Err(ParseError::new(save.pos, false, kind));
358
            }
359
1085
            let element = object_element(reader)?;
360
1085
            elements.push(element);
361
        }
362
    }
363

            
364
    // at least one element
365

            
366
705
    literal("}", reader)?;
367

            
368
705
    Ok(JsonValue::Object { space0, elements })
369
}
370

            
371
1800
fn key(reader: &mut Reader) -> ParseResult<Template> {
372
1800
    let name = string_template(reader).map_err(|e| e.to_non_recoverable())?;
373
1800
    Ok(name)
374
}
375

            
376
1800
fn object_element(reader: &mut Reader) -> ParseResult<JsonObjectElement> {
377
1800
    let space0 = whitespace(reader);
378
    //literal("\"", reader)?;
379
1800
    let name = key(reader)?;
380
    //literal("\"", reader)?;
381
1800
    let space1 = whitespace(reader);
382
1800
    literal(":", reader)?;
383
1800
    let save = reader.cursor();
384
1800
    let space2 = whitespace(reader);
385
1800
    // Checks if there is no element after ':'. In this case, a special error must be reported
386
1800
    // because this is a common occurrence.
387
1800
    let next_char = reader.peek();
388
1800
    // Comparing to None because `next_char` can be EOF.
389
1800
    if next_char == Some('}') || next_char.is_none() {
390
5
        let kind = ParseErrorKind::Json(JsonErrorVariant::EmptyElement);
391
5
        return Err(ParseError::new(save.pos, false, kind));
392
    }
393
1795
    let value = parse_in_json(reader)?;
394
1760
    let space3 = whitespace(reader);
395
1760
    Ok(JsonObjectElement {
396
1760
        space0,
397
1760
        name,
398
1760
        space1,
399
1760
        space2,
400
1760
        value,
401
1760
        space3,
402
1760
    })
403
}
404

            
405
35060
fn is_whitespace(c: char) -> bool {
406
35060
    c == ' ' || c == '\t' || c == '\n' || c == '\r'
407
}
408

            
409
10180
fn whitespace(reader: &mut Reader) -> String {
410
10180
    reader.read_while(is_whitespace)
411
}
412

            
413
#[cfg(test)]
414
mod tests {
415
    use super::*;
416
    use crate::ast::*;
417

            
418
    #[test]
419
    fn test_parse_error() {
420
        let mut reader = Reader::new("{ \"a\":\n}");
421
        let error = parse(&mut reader).err().unwrap();
422
        assert_eq!(error.pos, Pos { line: 1, column: 7 });
423
        assert_eq!(
424
            error.kind,
425
            ParseErrorKind::Json(JsonErrorVariant::EmptyElement)
426
        );
427
        assert!(!error.recoverable);
428

            
429
        let mut reader = Reader::new("[0,1,]");
430
        let error = parse(&mut reader).err().unwrap();
431
        assert_eq!(error.pos, Pos { line: 1, column: 5 });
432
        assert_eq!(
433
            error.kind,
434
            ParseErrorKind::Json(JsonErrorVariant::TrailingComma),
435
        );
436
        assert!(!error.recoverable);
437
    }
438

            
439
    #[test]
440
    fn test_null_value() {
441
        let mut reader = Reader::new("null");
442
        assert_eq!(null_value(&mut reader).unwrap(), JsonValue::Null);
443
        assert_eq!(reader.cursor().index, 4);
444

            
445
        let mut reader = Reader::new("true");
446
        let error = null_value(&mut reader).err().unwrap();
447
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
448
        assert_eq!(
449
            error.kind,
450
            ParseErrorKind::Expecting {
451
                value: "null".to_string()
452
            }
453
        );
454
        assert!(error.recoverable);
455
    }
456

            
457
    #[test]
458
    fn test_integer() {
459
        let mut reader = Reader::new("0");
460
        assert_eq!(integer(&mut reader).unwrap(), "0".to_string());
461
        assert_eq!(reader.cursor().index, 1);
462

            
463
        let mut reader = Reader::new("123");
464
        assert_eq!(integer(&mut reader).unwrap(), "123".to_string());
465
        assert_eq!(reader.cursor().index, 3);
466

            
467
        let mut reader = Reader::new("0123");
468
        assert_eq!(integer(&mut reader).unwrap(), "0".to_string());
469
        assert_eq!(reader.cursor().index, 1);
470
    }
471

            
472
    #[test]
473
    fn test_fraction() {
474
        let mut reader = Reader::new(".5");
475
        assert_eq!(fraction(&mut reader).unwrap(), ".5".to_string());
476
        assert_eq!(reader.cursor().index, 2);
477
    }
478

            
479
    #[test]
480
    fn test_exponent() {
481
        let mut reader = Reader::new("e2");
482
        assert_eq!(exponent(&mut reader).unwrap(), "e2".to_string());
483
        assert_eq!(reader.cursor().index, 2);
484
    }
485

            
486
    #[test]
487
    fn test_boolean_value() {
488
        let mut reader = Reader::new("true");
489
        assert_eq!(
490
            boolean_value(&mut reader).unwrap(),
491
            JsonValue::Boolean(true)
492
        );
493
        assert_eq!(reader.cursor().index, 4);
494

            
495
        let mut reader = Reader::new("1");
496
        let error = boolean_value(&mut reader).err().unwrap();
497
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
498
        assert_eq!(
499
            error.kind,
500
            ParseErrorKind::Expecting {
501
                value: "true|false".to_string()
502
            }
503
        );
504
        assert!(error.recoverable);
505
    }
506

            
507
    pub fn json_hello_world_value() -> JsonValue {
508
        // "hello\u0020{{name}}!"
509
        JsonValue::String(Template {
510
            delimiter: Some('"'),
511
            elements: vec![
512
                TemplateElement::String {
513
                    value: "Hello ".to_string(),
514
                    encoded: "Hello\\u0020".to_string(),
515
                },
516
                TemplateElement::Placeholder(Placeholder {
517
                    space0: Whitespace {
518
                        value: String::new(),
519
                        source_info: SourceInfo::new(Pos::new(1, 15), Pos::new(1, 15)),
520
                    },
521
                    expr: Expr {
522
                        kind: ExprKind::Variable(Variable {
523
                            name: "name".to_string(),
524
                            source_info: SourceInfo::new(Pos::new(1, 15), Pos::new(1, 19)),
525
                        }),
526
                        source_info: SourceInfo::new(Pos::new(1, 15), Pos::new(1, 19)),
527
                    },
528
                    space1: Whitespace {
529
                        value: String::new(),
530
                        source_info: SourceInfo::new(Pos::new(1, 19), Pos::new(1, 19)),
531
                    },
532
                }),
533
                TemplateElement::String {
534
                    value: "!".to_string(),
535
                    encoded: "!".to_string(),
536
                },
537
            ],
538
            source_info: SourceInfo::new(Pos::new(1, 2), Pos::new(1, 22)),
539
        })
540
    }
541

            
542
    #[test]
543
    fn test_string_value() {
544
        let mut reader = Reader::new("\"\"");
545
        assert_eq!(
546
            string_value(&mut reader).unwrap(),
547
            JsonValue::String(Template {
548
                delimiter: Some('"'),
549
                elements: vec![],
550
                source_info: SourceInfo::new(Pos::new(1, 2), Pos::new(1, 2)),
551
            })
552
        );
553
        assert_eq!(reader.cursor().index, 2);
554

            
555
        let mut reader = Reader::new("\"Hello\\u0020{{name}}!\"");
556
        assert_eq!(string_value(&mut reader).unwrap(), json_hello_world_value());
557
        assert_eq!(reader.cursor().index, 22);
558

            
559
        let mut reader = Reader::new("\"{}\"");
560
        assert_eq!(
561
            string_value(&mut reader).unwrap(),
562
            JsonValue::String(Template {
563
                delimiter: Some('"'),
564
                elements: vec![TemplateElement::String {
565
                    value: "{}".to_string(),
566
                    encoded: "{}".to_string(),
567
                }],
568
                source_info: SourceInfo::new(Pos::new(1, 2), Pos::new(1, 4)),
569
            })
570
        );
571
        assert_eq!(reader.cursor().index, 4);
572
    }
573

            
574
    #[test]
575
    fn test_string_value_error() {
576
        let mut reader = Reader::new("1");
577
        let error = string_value(&mut reader).err().unwrap();
578
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
579
        assert_eq!(
580
            error.kind,
581
            ParseErrorKind::Expecting {
582
                value: "\"".to_string()
583
            }
584
        );
585
        assert!(error.recoverable);
586

            
587
        let mut reader = Reader::new("\"1");
588
        let error = string_value(&mut reader).err().unwrap();
589
        assert_eq!(error.pos, Pos { line: 1, column: 3 });
590
        assert_eq!(
591
            error.kind,
592
            ParseErrorKind::Expecting {
593
                value: "\"".to_string()
594
            }
595
        );
596
        assert!(!error.recoverable);
597

            
598
        let mut reader = Reader::new("\"{{x\"");
599
        let error = string_value(&mut reader).err().unwrap();
600
        assert_eq!(error.pos, Pos { line: 1, column: 5 });
601
        assert_eq!(
602
            error.kind,
603
            ParseErrorKind::Expecting {
604
                value: "}}".to_string()
605
            }
606
        );
607
        assert!(!error.recoverable);
608
    }
609

            
610
    #[test]
611
    fn test_any_char() {
612
        let mut reader = Reader::new("a");
613
        assert_eq!(
614
            any_char(&mut reader).unwrap(),
615
            ('a', "a".to_string(), Pos { line: 1, column: 1 })
616
        );
617
        assert_eq!(reader.cursor().index, 1);
618

            
619
        let mut reader = Reader::new(" ");
620
        assert_eq!(
621
            any_char(&mut reader).unwrap(),
622
            (' ', " ".to_string(), Pos { line: 1, column: 1 })
623
        );
624
        assert_eq!(reader.cursor().index, 1);
625

            
626
        let mut reader = Reader::new("\\u0020 ");
627
        assert_eq!(
628
            any_char(&mut reader).unwrap(),
629
            (' ', "\\u0020".to_string(), Pos { line: 1, column: 1 })
630
        );
631
        assert_eq!(reader.cursor().index, 6);
632

            
633
        let mut reader = Reader::new("\\t");
634
        assert_eq!(
635
            any_char(&mut reader).unwrap(),
636
            ('\t', "\\t".to_string(), Pos { line: 1, column: 1 })
637
        );
638
        assert_eq!(reader.cursor().index, 2);
639

            
640
        let mut reader = Reader::new("#");
641
        assert_eq!(
642
            any_char(&mut reader).unwrap(),
643
            ('#', "#".to_string(), Pos { line: 1, column: 1 })
644
        );
645
        assert_eq!(reader.cursor().index, 1);
646
    }
647

            
648
    #[test]
649
    fn test_any_char_error() {
650
        let mut reader = Reader::new("");
651
        let error = any_char(&mut reader).err().unwrap();
652
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
653
        assert!(error.recoverable);
654

            
655
        let mut reader = Reader::new("\t");
656
        let error = any_char(&mut reader).err().unwrap();
657
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
658
        assert!(error.recoverable);
659
    }
660

            
661
    #[test]
662
    fn test_escape_char() {
663
        let mut reader = Reader::new("\\n");
664
        assert_eq!(escape_char(&mut reader).unwrap(), '\n');
665
        assert_eq!(reader.cursor().index, 2);
666

            
667
        let mut reader = Reader::new("\\u000a");
668
        assert_eq!(escape_char(&mut reader).unwrap(), '\n');
669
        assert_eq!(reader.cursor().index, 6);
670

            
671
        let mut reader = Reader::new("x");
672
        let error = escape_char(&mut reader).err().unwrap();
673
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
674
        assert_eq!(
675
            error.kind,
676
            ParseErrorKind::Expecting {
677
                value: "\\".to_string()
678
            }
679
        );
680
        assert!(error.recoverable);
681
        assert_eq!(reader.cursor().index, 0);
682
    }
683

            
684
    #[test]
685
    fn test_unicode() {
686
        let mut reader = Reader::new("000a");
687
        assert_eq!(unicode(&mut reader).unwrap(), '\n');
688
        assert_eq!(reader.cursor().index, 4);
689

            
690
        let mut reader = Reader::new("c350");
691
        assert_eq!(unicode(&mut reader).unwrap(), '썐');
692
        assert_eq!(reader.cursor().index, 4);
693

            
694
        let mut reader = Reader::new("d83c\\udf78");
695
        assert_eq!(unicode(&mut reader).unwrap(), '🍸');
696
        assert_eq!(reader.cursor().index, 10);
697

            
698
        let mut reader = Reader::new("d800");
699
        let error = unicode(&mut reader).unwrap_err();
700
        assert_eq!(error.pos, Pos { line: 1, column: 5 });
701
        assert_eq!(
702
            error.kind,
703
            ParseErrorKind::Expecting {
704
                value: "\\u".to_string()
705
            }
706
        );
707
        assert!(!error.recoverable);
708

            
709
        let mut reader = Reader::new("d800\\ud800");
710
        let error = unicode(&mut reader).unwrap_err();
711
        assert_eq!(error.pos, Pos { line: 1, column: 7 });
712
        assert_eq!(error.kind, ParseErrorKind::Unicode);
713
        assert!(!error.recoverable);
714
    }
715

            
716
    #[test]
717
    fn test_hex_value() {
718
        let mut reader = Reader::new("0020x");
719
        assert_eq!(hex_value(&mut reader).unwrap(), 32);
720

            
721
        let mut reader = Reader::new("d800");
722
        assert_eq!(hex_value(&mut reader).unwrap(), 55296);
723

            
724
        let mut reader = Reader::new("x");
725
        let error = hex_value(&mut reader).unwrap_err();
726
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
727
        assert_eq!(error.kind, ParseErrorKind::HexDigit);
728
        assert!(!error.recoverable);
729
    }
730

            
731
    #[test]
732
    fn test_number_value() {
733
        let mut reader = Reader::new("100");
734
        assert_eq!(
735
            number_value(&mut reader).unwrap(),
736
            JsonValue::Number("100".to_string())
737
        );
738
        assert_eq!(reader.cursor().index, 3);
739

            
740
        let mut reader = Reader::new("1.333");
741
        assert_eq!(
742
            number_value(&mut reader).unwrap(),
743
            JsonValue::Number("1.333".to_string())
744
        );
745
        assert_eq!(reader.cursor().index, 5);
746

            
747
        let mut reader = Reader::new("-1");
748
        assert_eq!(
749
            number_value(&mut reader).unwrap(),
750
            JsonValue::Number("-1".to_string())
751
        );
752
        assert_eq!(reader.cursor().index, 2);
753

            
754
        let mut reader = Reader::new("00");
755
        assert_eq!(
756
            number_value(&mut reader).unwrap(),
757
            JsonValue::Number("0".to_string())
758
        );
759
        assert_eq!(reader.cursor().index, 1);
760

            
761
        let mut reader = Reader::new("1e0");
762
        assert_eq!(
763
            number_value(&mut reader).unwrap(),
764
            JsonValue::Number("1e0".to_string())
765
        );
766
        assert_eq!(reader.cursor().index, 3);
767

            
768
        let mut reader = Reader::new("1e005");
769
        assert_eq!(
770
            number_value(&mut reader).unwrap(),
771
            JsonValue::Number("1e005".to_string())
772
        );
773
        assert_eq!(reader.cursor().index, 5);
774

            
775
        let mut reader = Reader::new("1e-005");
776
        assert_eq!(
777
            number_value(&mut reader).unwrap(),
778
            JsonValue::Number("1e-005".to_string())
779
        );
780
        assert_eq!(reader.cursor().index, 6);
781
    }
782

            
783
    #[test]
784
    fn test_number_value_error() {
785
        let mut reader = Reader::new("true");
786
        let error = number_value(&mut reader).err().unwrap();
787
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
788
        assert_eq!(
789
            error.kind,
790
            ParseErrorKind::Expecting {
791
                value: "number".to_string()
792
            }
793
        );
794
        assert!(error.recoverable);
795

            
796
        let mut reader = Reader::new("1.x");
797
        let error = number_value(&mut reader).err().unwrap();
798
        assert_eq!(error.pos, Pos { line: 1, column: 3 });
799
        assert_eq!(
800
            error.kind,
801
            ParseErrorKind::Expecting {
802
                value: "digits".to_string()
803
            }
804
        );
805
        assert!(!error.recoverable);
806
    }
807

            
808
    #[test]
809
    fn test_expression_value() {
810
        let mut reader = Reader::new("{{n}}");
811
        assert_eq!(
812
            expression_value(&mut reader).unwrap(),
813
            JsonValue::Placeholder(Placeholder {
814
                space0: Whitespace {
815
                    value: String::new(),
816
                    source_info: SourceInfo::new(Pos::new(1, 3), Pos::new(1, 3))
817
                },
818
                expr: Expr {
819
                    kind: ExprKind::Variable(Variable {
820
                        name: "n".to_string(),
821
                        source_info: SourceInfo::new(Pos::new(1, 3), Pos::new(1, 4))
822
                    }),
823
                    source_info: SourceInfo::new(Pos::new(1, 3), Pos::new(1, 4))
824
                },
825
                space1: Whitespace {
826
                    value: String::new(),
827
                    source_info: SourceInfo::new(Pos::new(1, 4), Pos::new(1, 4))
828
                }
829
            })
830
        );
831
        assert_eq!(reader.cursor().index, 5);
832
    }
833

            
834
    #[test]
835
    fn test_list_value() {
836
        let mut reader = Reader::new("[]");
837
        assert_eq!(
838
            list_value(&mut reader).unwrap(),
839
            JsonValue::List {
840
                space0: String::new(),
841
                elements: vec![]
842
            }
843
        );
844
        assert_eq!(reader.cursor().index, 2);
845

            
846
        let mut reader = Reader::new("[ ]");
847
        assert_eq!(
848
            list_value(&mut reader).unwrap(),
849
            JsonValue::List {
850
                space0: " ".to_string(),
851
                elements: vec![]
852
            }
853
        );
854
        assert_eq!(reader.cursor().index, 3);
855

            
856
        let mut reader = Reader::new("[true, false]");
857
        assert_eq!(
858
            list_value(&mut reader).unwrap(),
859
            JsonValue::List {
860
                space0: String::new(),
861
                elements: vec![
862
                    JsonListElement {
863
                        space0: String::new(),
864
                        value: JsonValue::Boolean(true),
865
                        space1: String::new(),
866
                    },
867
                    JsonListElement {
868
                        space0: String::from(" "),
869
                        value: JsonValue::Boolean(false),
870
                        space1: String::new(),
871
                    }
872
                ],
873
            }
874
        );
875
        assert_eq!(reader.cursor().index, 13);
876
    }
877

            
878
    #[test]
879
    fn test_list_error() {
880
        let mut reader = Reader::new("true");
881
        let error = list_value(&mut reader).err().unwrap();
882
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
883
        assert_eq!(
884
            error.kind,
885
            ParseErrorKind::Expecting {
886
                value: "[".to_string()
887
            }
888
        );
889
        assert!(error.recoverable);
890

            
891
        let mut reader = Reader::new("[1, 2,]");
892
        let error = list_value(&mut reader).err().unwrap();
893
        assert_eq!(error.pos, Pos { line: 1, column: 6 });
894
        assert_eq!(
895
            error.kind,
896
            ParseErrorKind::Json(JsonErrorVariant::TrailingComma),
897
        );
898
        assert!(!error.recoverable);
899
    }
900

            
901
    #[test]
902
    fn test_list_element() {
903
        let mut reader = Reader::new("true");
904
        assert_eq!(
905
            list_element(&mut reader).unwrap(),
906
            JsonListElement {
907
                space0: String::new(),
908
                value: JsonValue::Boolean(true),
909
                space1: String::new(),
910
            }
911
        );
912
        assert_eq!(reader.cursor().index, 4);
913
    }
914

            
915
    #[test]
916
    fn test_object_value() {
917
        let mut reader = Reader::new("{}");
918
        assert_eq!(
919
            object_value(&mut reader).unwrap(),
920
            JsonValue::Object {
921
                space0: String::new(),
922
                elements: vec![]
923
            }
924
        );
925
        assert_eq!(reader.cursor().index, 2);
926

            
927
        let mut reader = Reader::new("{ }");
928
        assert_eq!(
929
            object_value(&mut reader).unwrap(),
930
            JsonValue::Object {
931
                space0: " ".to_string(),
932
                elements: vec![]
933
            }
934
        );
935
        assert_eq!(reader.cursor().index, 3);
936

            
937
        let mut reader = Reader::new("{\n  \"a\": true\n}");
938
        assert_eq!(
939
            object_value(&mut reader).unwrap(),
940
            JsonValue::Object {
941
                space0: "\n  ".to_string(),
942
                elements: vec![JsonObjectElement {
943
                    space0: String::new(),
944
                    name: Template {
945
                        delimiter: Some('"'),
946
                        elements: vec![TemplateElement::String {
947
                            value: "a".to_string(),
948
                            encoded: "a".to_string()
949
                        }],
950
                        source_info: SourceInfo::new(Pos::new(2, 4), Pos::new(2, 5))
951
                    },
952
                    space1: String::new(),
953
                    space2: " ".to_string(),
954
                    value: JsonValue::Boolean(true),
955
                    space3: "\n".to_string(),
956
                }],
957
            }
958
        );
959
        assert_eq!(reader.cursor().index, 15);
960

            
961
        let mut reader = Reader::new("true");
962
        let error = object_value(&mut reader).err().unwrap();
963
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
964
        assert_eq!(
965
            error.kind,
966
            ParseErrorKind::Expecting {
967
                value: "{".to_string()
968
            }
969
        );
970
        assert!(error.recoverable);
971
    }
972

            
973
    #[test]
974
    fn test_object_error() {
975
        let mut reader = Reader::new("{ \"a\":\n}");
976
        let error = object_value(&mut reader).err().unwrap();
977
        assert_eq!(error.pos, Pos { line: 1, column: 7 });
978
        assert_eq!(
979
            error.kind,
980
            ParseErrorKind::Json(JsonErrorVariant::EmptyElement)
981
        );
982
        assert!(!error.recoverable);
983
    }
984

            
985
    #[test]
986
    fn test_object_element() {
987
        let mut reader = Reader::new("\"a\": true");
988
        assert_eq!(
989
            object_element(&mut reader).unwrap(),
990
            JsonObjectElement {
991
                space0: String::new(),
992
                name: Template {
993
                    delimiter: Some('"'),
994
                    elements: vec![TemplateElement::String {
995
                        value: "a".to_string(),
996
                        encoded: "a".to_string()
997
                    }],
998
                    source_info: SourceInfo::new(Pos::new(1, 2), Pos::new(1, 3))
999
                },
                space1: String::new(),
                space2: " ".to_string(),
                value: JsonValue::Boolean(true),
                space3: String::new(),
            }
        );
        assert_eq!(reader.cursor().index, 9);
    }
    #[test]
    fn test_object_element_error() {
        let mut reader = Reader::new(":");
        let error = object_element(&mut reader).err().unwrap();
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
        assert_eq!(
            error.kind,
            ParseErrorKind::Expecting {
                value: "\"".to_string()
            }
        );
        assert!(!error.recoverable);
        let mut reader = Reader::new("\"name\":\n");
        let error = object_element(&mut reader).err().unwrap();
        assert_eq!(error.pos, Pos { line: 1, column: 8 });
        assert_eq!(
            error.kind,
            ParseErrorKind::Json(JsonErrorVariant::EmptyElement),
        );
        assert!(!error.recoverable);
    }
    #[test]
    fn test_whitespace() {
        let mut reader = Reader::new("");
        assert_eq!(whitespace(&mut reader), String::new());
        assert_eq!(reader.cursor().index, 0);
        let mut reader = Reader::new(" x");
        assert_eq!(whitespace(&mut reader), " ".to_string());
        assert_eq!(reader.cursor().index, 1);
        let mut reader = Reader::new("\n  x");
        assert_eq!(whitespace(&mut reader), "\n  ".to_string());
        assert_eq!(reader.cursor().index, 3);
    }
}