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::error::*;
21
use crate::parser::primitives::*;
22
use crate::parser::template::*;
23
use crate::parser::ParseResult;
24
use crate::reader::{Pos, Reader};
25

            
26
use super::placeholder;
27

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
216
26570
pub fn number_value(reader: &mut Reader) -> ParseResult<JsonValue> {
217
26570
    let start = reader.cursor();
218

            
219
26570
    let sign = match try_literal("-", reader) {
220
26530
        Err(_) => String::new(),
221
40
        Ok(_) => "-".to_string(),
222
    };
223

            
224
26570
    let integer = match try_literal("0", reader) {
225
        Err(_) => {
226
31418
            let digits = reader.read_while(|c| c.is_ascii_digit());
227
26350
            if digits.is_empty() {
228
25600
                let kind = ParseErrorKind::Expecting {
229
25600
                    value: "number".to_string(),
230
25600
                };
231
25600
                return Err(ParseError::new(start.pos, true, kind));
232
            } else {
233
750
                digits
234
            }
235
        }
236
220
        Ok(_) => "0".to_string(),
237
    };
238

            
239
970
    let fraction = match try_literal(".", reader) {
240
        Ok(_) => {
241
3825
            let digits = reader.read_while(|c| c.is_ascii_digit());
242
575
            if digits.is_empty() {
243
                let kind = ParseErrorKind::Expecting {
244
                    value: "digits".to_string(),
245
                };
246
                return Err(ParseError::new(reader.cursor().pos, false, kind));
247
            } else {
248
575
                format!(".{digits}")
249
            }
250
        }
251
395
        Err(_) => String::new(),
252
    };
253

            
254
970
    let exponent = if reader.peek() == Some('e') || reader.peek() == Some('E') {
255
5
        reader.read();
256
5
        let exponent_sign = match try_literal("-", reader) {
257
            Ok(_) => "-".to_string(),
258
5
            Err(_) => match try_literal("+", reader) {
259
                Ok(_) => "+".to_string(),
260
5
                Err(_) => String::new(),
261
            },
262
        };
263
21
        let exponent_digits = reader.read_while(|c| c.is_ascii_digit());
264
5
        format!("e{exponent_sign}{exponent_digits}")
265
    } else {
266
965
        String::new()
267
    };
268

            
269
970
    Ok(JsonValue::Number(format!(
270
970
        "{sign}{integer}{fraction}{exponent}"
271
970
    )))
272
}
273

            
274
25575
fn expression_value(reader: &mut Reader) -> ParseResult<JsonValue> {
275
25575
    let exp = placeholder::parse(reader)?;
276
50
    Ok(JsonValue::Placeholder(exp))
277
}
278

            
279
25525
fn list_value(reader: &mut Reader) -> ParseResult<JsonValue> {
280
25525
    try_literal("[", reader)?;
281
345
    let space0 = whitespace(reader);
282
345
    let mut elements = vec![];
283
345

            
284
345
    // at least one element
285
345
    if reader.peek() != Some(']') {
286
305
        let first_element = list_element(reader)?;
287
305
        elements.push(first_element);
288

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

            
314
335
    Ok(JsonValue::List { space0, elements })
315
}
316

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

            
328
25220
pub fn object_value(reader: &mut Reader) -> ParseResult<JsonValue> {
329
25220
    try_literal("{", reader)?;
330
730
    let space0 = whitespace(reader);
331
730
    let mut elements = vec![];
332
730
    if reader.peek() != Some('}') {
333
695
        let first_element = object_element(reader)?;
334
655
        elements.push(first_element);
335

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

            
360
    // at least one element
361

            
362
685
    literal("}", reader)?;
363

            
364
685
    Ok(JsonValue::Object { space0, elements })
365
}
366

            
367
1780
fn key(reader: &mut Reader) -> ParseResult<Template> {
368
1780
    let name = string_template(reader).map_err(|e| e.to_non_recoverable())?;
369
1780
    Ok(name)
370
}
371

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

            
401
34885
fn is_whitespace(c: char) -> bool {
402
34885
    c == ' ' || c == '\t' || c == '\n' || c == '\r'
403
}
404

            
405
10080
fn whitespace(reader: &mut Reader) -> String {
406
10080
    reader.read_while(is_whitespace)
407
}
408

            
409
#[cfg(test)]
410
mod tests {
411
    use super::*;
412
    use crate::ast::*;
413

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

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

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

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

            
453
    #[test]
454
    fn test_boolean_value() {
455
        let mut reader = Reader::new("true");
456
        assert_eq!(
457
            boolean_value(&mut reader).unwrap(),
458
            JsonValue::Boolean(true)
459
        );
460
        assert_eq!(reader.cursor().index, 4);
461

            
462
        let mut reader = Reader::new("1");
463
        let error = boolean_value(&mut reader).err().unwrap();
464
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
465
        assert_eq!(
466
            error.kind,
467
            ParseErrorKind::Expecting {
468
                value: "true|false".to_string()
469
            }
470
        );
471
        assert!(error.recoverable);
472
    }
473

            
474
    pub fn json_hello_world_value() -> JsonValue {
475
        // "hello\u0020{{name}}!"
476
        JsonValue::String(Template {
477
            delimiter: Some('"'),
478
            elements: vec![
479
                TemplateElement::String {
480
                    value: "Hello ".to_string(),
481
                    encoded: "Hello\\u0020".to_string(),
482
                },
483
                TemplateElement::Placeholder(Placeholder {
484
                    space0: Whitespace {
485
                        value: String::new(),
486
                        source_info: SourceInfo::new(Pos::new(1, 15), Pos::new(1, 15)),
487
                    },
488
                    expr: Expr {
489
                        kind: ExprKind::Variable(Variable {
490
                            name: "name".to_string(),
491
                            source_info: SourceInfo::new(Pos::new(1, 15), Pos::new(1, 19)),
492
                        }),
493
                        source_info: SourceInfo::new(Pos::new(1, 15), Pos::new(1, 19)),
494
                    },
495
                    space1: Whitespace {
496
                        value: String::new(),
497
                        source_info: SourceInfo::new(Pos::new(1, 19), Pos::new(1, 19)),
498
                    },
499
                }),
500
                TemplateElement::String {
501
                    value: "!".to_string(),
502
                    encoded: "!".to_string(),
503
                },
504
            ],
505
            source_info: SourceInfo::new(Pos::new(1, 2), Pos::new(1, 22)),
506
        })
507
    }
508

            
509
    #[test]
510
    fn test_string_value() {
511
        let mut reader = Reader::new("\"\"");
512
        assert_eq!(
513
            string_value(&mut reader).unwrap(),
514
            JsonValue::String(Template {
515
                delimiter: Some('"'),
516
                elements: vec![],
517
                source_info: SourceInfo::new(Pos::new(1, 2), Pos::new(1, 2)),
518
            })
519
        );
520
        assert_eq!(reader.cursor().index, 2);
521

            
522
        let mut reader = Reader::new("\"Hello\\u0020{{name}}!\"");
523
        assert_eq!(string_value(&mut reader).unwrap(), json_hello_world_value());
524
        assert_eq!(reader.cursor().index, 22);
525

            
526
        let mut reader = Reader::new("\"{}\"");
527
        assert_eq!(
528
            string_value(&mut reader).unwrap(),
529
            JsonValue::String(Template {
530
                delimiter: Some('"'),
531
                elements: vec![TemplateElement::String {
532
                    value: "{}".to_string(),
533
                    encoded: "{}".to_string(),
534
                }],
535
                source_info: SourceInfo::new(Pos::new(1, 2), Pos::new(1, 4)),
536
            })
537
        );
538
        assert_eq!(reader.cursor().index, 4);
539
    }
540

            
541
    #[test]
542
    fn test_string_value_error() {
543
        let mut reader = Reader::new("1");
544
        let error = string_value(&mut reader).err().unwrap();
545
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
546
        assert_eq!(
547
            error.kind,
548
            ParseErrorKind::Expecting {
549
                value: "\"".to_string()
550
            }
551
        );
552
        assert!(error.recoverable);
553

            
554
        let mut reader = Reader::new("\"1");
555
        let error = string_value(&mut reader).err().unwrap();
556
        assert_eq!(error.pos, Pos { line: 1, column: 3 });
557
        assert_eq!(
558
            error.kind,
559
            ParseErrorKind::Expecting {
560
                value: "\"".to_string()
561
            }
562
        );
563
        assert!(!error.recoverable);
564

            
565
        let mut reader = Reader::new("\"{{x\"");
566
        let error = string_value(&mut reader).err().unwrap();
567
        assert_eq!(error.pos, Pos { line: 1, column: 5 });
568
        assert_eq!(
569
            error.kind,
570
            ParseErrorKind::Expecting {
571
                value: "}}".to_string()
572
            }
573
        );
574
        assert!(!error.recoverable);
575
    }
576

            
577
    #[test]
578
    fn test_any_char() {
579
        let mut reader = Reader::new("a");
580
        assert_eq!(
581
            any_char(&mut reader).unwrap(),
582
            ('a', "a".to_string(), Pos { line: 1, column: 1 })
583
        );
584
        assert_eq!(reader.cursor().index, 1);
585

            
586
        let mut reader = Reader::new(" ");
587
        assert_eq!(
588
            any_char(&mut reader).unwrap(),
589
            (' ', " ".to_string(), Pos { line: 1, column: 1 })
590
        );
591
        assert_eq!(reader.cursor().index, 1);
592

            
593
        let mut reader = Reader::new("\\u0020 ");
594
        assert_eq!(
595
            any_char(&mut reader).unwrap(),
596
            (' ', "\\u0020".to_string(), Pos { line: 1, column: 1 })
597
        );
598
        assert_eq!(reader.cursor().index, 6);
599

            
600
        let mut reader = Reader::new("\\t");
601
        assert_eq!(
602
            any_char(&mut reader).unwrap(),
603
            ('\t', "\\t".to_string(), Pos { line: 1, column: 1 })
604
        );
605
        assert_eq!(reader.cursor().index, 2);
606

            
607
        let mut reader = Reader::new("#");
608
        assert_eq!(
609
            any_char(&mut reader).unwrap(),
610
            ('#', "#".to_string(), Pos { line: 1, column: 1 })
611
        );
612
        assert_eq!(reader.cursor().index, 1);
613
    }
614

            
615
    #[test]
616
    fn test_any_char_error() {
617
        let mut reader = Reader::new("");
618
        let error = any_char(&mut reader).err().unwrap();
619
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
620
        assert!(error.recoverable);
621

            
622
        let mut reader = Reader::new("\t");
623
        let error = any_char(&mut reader).err().unwrap();
624
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
625
        assert!(error.recoverable);
626
    }
627

            
628
    #[test]
629
    fn test_escape_char() {
630
        let mut reader = Reader::new("\\n");
631
        assert_eq!(escape_char(&mut reader).unwrap(), '\n');
632
        assert_eq!(reader.cursor().index, 2);
633

            
634
        let mut reader = Reader::new("\\u000a");
635
        assert_eq!(escape_char(&mut reader).unwrap(), '\n');
636
        assert_eq!(reader.cursor().index, 6);
637

            
638
        let mut reader = Reader::new("x");
639
        let error = escape_char(&mut reader).err().unwrap();
640
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
641
        assert_eq!(
642
            error.kind,
643
            ParseErrorKind::Expecting {
644
                value: "\\".to_string()
645
            }
646
        );
647
        assert!(error.recoverable);
648
        assert_eq!(reader.cursor().index, 0);
649
    }
650

            
651
    #[test]
652
    fn test_unicode() {
653
        let mut reader = Reader::new("000a");
654
        assert_eq!(unicode(&mut reader).unwrap(), '\n');
655
        assert_eq!(reader.cursor().index, 4);
656

            
657
        let mut reader = Reader::new("c350");
658
        assert_eq!(unicode(&mut reader).unwrap(), '썐');
659
        assert_eq!(reader.cursor().index, 4);
660

            
661
        let mut reader = Reader::new("d83c\\udf78");
662
        assert_eq!(unicode(&mut reader).unwrap(), '🍸');
663
        assert_eq!(reader.cursor().index, 10);
664

            
665
        let mut reader = Reader::new("d800");
666
        let error = unicode(&mut reader).unwrap_err();
667
        assert_eq!(error.pos, Pos { line: 1, column: 5 });
668
        assert_eq!(
669
            error.kind,
670
            ParseErrorKind::Expecting {
671
                value: "\\u".to_string()
672
            }
673
        );
674
        assert!(!error.recoverable);
675

            
676
        let mut reader = Reader::new("d800\\ud800");
677
        let error = unicode(&mut reader).unwrap_err();
678
        assert_eq!(error.pos, Pos { line: 1, column: 7 });
679
        assert_eq!(error.kind, ParseErrorKind::Unicode);
680
        assert!(!error.recoverable);
681
    }
682

            
683
    #[test]
684
    fn test_hex_value() {
685
        let mut reader = Reader::new("0020x");
686
        assert_eq!(hex_value(&mut reader).unwrap(), 32);
687

            
688
        let mut reader = Reader::new("d800");
689
        assert_eq!(hex_value(&mut reader).unwrap(), 55296);
690

            
691
        let mut reader = Reader::new("x");
692
        let error = hex_value(&mut reader).unwrap_err();
693
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
694
        assert_eq!(error.kind, ParseErrorKind::HexDigit);
695
        assert!(!error.recoverable);
696
    }
697

            
698
    #[test]
699
    fn test_number_value() {
700
        let mut reader = Reader::new("100");
701
        assert_eq!(
702
            number_value(&mut reader).unwrap(),
703
            JsonValue::Number("100".to_string())
704
        );
705
        assert_eq!(reader.cursor().index, 3);
706

            
707
        let mut reader = Reader::new("1.333");
708
        assert_eq!(
709
            number_value(&mut reader).unwrap(),
710
            JsonValue::Number("1.333".to_string())
711
        );
712
        assert_eq!(reader.cursor().index, 5);
713

            
714
        let mut reader = Reader::new("-1");
715
        assert_eq!(
716
            number_value(&mut reader).unwrap(),
717
            JsonValue::Number("-1".to_string())
718
        );
719
        assert_eq!(reader.cursor().index, 2);
720

            
721
        let mut reader = Reader::new("00");
722
        assert_eq!(
723
            number_value(&mut reader).unwrap(),
724
            JsonValue::Number("0".to_string())
725
        );
726
        assert_eq!(reader.cursor().index, 1);
727

            
728
        let mut reader = Reader::new("1e0");
729
        assert_eq!(
730
            number_value(&mut reader).unwrap(),
731
            JsonValue::Number("1e0".to_string())
732
        );
733
        assert_eq!(reader.cursor().index, 3);
734

            
735
        let mut reader = Reader::new("1e005");
736
        assert_eq!(
737
            number_value(&mut reader).unwrap(),
738
            JsonValue::Number("1e005".to_string())
739
        );
740
        assert_eq!(reader.cursor().index, 5);
741

            
742
        let mut reader = Reader::new("1e-005");
743
        assert_eq!(
744
            number_value(&mut reader).unwrap(),
745
            JsonValue::Number("1e-005".to_string())
746
        );
747
        assert_eq!(reader.cursor().index, 6);
748
    }
749

            
750
    #[test]
751
    fn test_number_value_error() {
752
        let mut reader = Reader::new("true");
753
        let error = number_value(&mut reader).err().unwrap();
754
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
755
        assert_eq!(
756
            error.kind,
757
            ParseErrorKind::Expecting {
758
                value: "number".to_string()
759
            }
760
        );
761
        assert!(error.recoverable);
762

            
763
        let mut reader = Reader::new("1.x");
764
        let error = number_value(&mut reader).err().unwrap();
765
        assert_eq!(error.pos, Pos { line: 1, column: 3 });
766
        assert_eq!(
767
            error.kind,
768
            ParseErrorKind::Expecting {
769
                value: "digits".to_string()
770
            }
771
        );
772
        assert!(!error.recoverable);
773
    }
774

            
775
    #[test]
776
    fn test_expression_value() {
777
        let mut reader = Reader::new("{{n}}");
778
        assert_eq!(
779
            expression_value(&mut reader).unwrap(),
780
            JsonValue::Placeholder(Placeholder {
781
                space0: Whitespace {
782
                    value: String::new(),
783
                    source_info: SourceInfo::new(Pos::new(1, 3), Pos::new(1, 3))
784
                },
785
                expr: Expr {
786
                    kind: ExprKind::Variable(Variable {
787
                        name: "n".to_string(),
788
                        source_info: SourceInfo::new(Pos::new(1, 3), Pos::new(1, 4))
789
                    }),
790
                    source_info: SourceInfo::new(Pos::new(1, 3), Pos::new(1, 4))
791
                },
792
                space1: Whitespace {
793
                    value: String::new(),
794
                    source_info: SourceInfo::new(Pos::new(1, 4), Pos::new(1, 4))
795
                }
796
            })
797
        );
798
        assert_eq!(reader.cursor().index, 5);
799
    }
800

            
801
    #[test]
802
    fn test_list_value() {
803
        let mut reader = Reader::new("[]");
804
        assert_eq!(
805
            list_value(&mut reader).unwrap(),
806
            JsonValue::List {
807
                space0: String::new(),
808
                elements: vec![]
809
            }
810
        );
811
        assert_eq!(reader.cursor().index, 2);
812

            
813
        let mut reader = Reader::new("[ ]");
814
        assert_eq!(
815
            list_value(&mut reader).unwrap(),
816
            JsonValue::List {
817
                space0: " ".to_string(),
818
                elements: vec![]
819
            }
820
        );
821
        assert_eq!(reader.cursor().index, 3);
822

            
823
        let mut reader = Reader::new("[true, false]");
824
        assert_eq!(
825
            list_value(&mut reader).unwrap(),
826
            JsonValue::List {
827
                space0: String::new(),
828
                elements: vec![
829
                    JsonListElement {
830
                        space0: String::new(),
831
                        value: JsonValue::Boolean(true),
832
                        space1: String::new(),
833
                    },
834
                    JsonListElement {
835
                        space0: String::from(" "),
836
                        value: JsonValue::Boolean(false),
837
                        space1: String::new(),
838
                    }
839
                ],
840
            }
841
        );
842
        assert_eq!(reader.cursor().index, 13);
843
    }
844

            
845
    #[test]
846
    fn test_list_error() {
847
        let mut reader = Reader::new("true");
848
        let error = list_value(&mut reader).err().unwrap();
849
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
850
        assert_eq!(
851
            error.kind,
852
            ParseErrorKind::Expecting {
853
                value: "[".to_string()
854
            }
855
        );
856
        assert!(error.recoverable);
857

            
858
        let mut reader = Reader::new("[1, 2,]");
859
        let error = list_value(&mut reader).err().unwrap();
860
        assert_eq!(error.pos, Pos { line: 1, column: 6 });
861
        assert_eq!(
862
            error.kind,
863
            ParseErrorKind::Json(JsonErrorVariant::TrailingComma),
864
        );
865
        assert!(!error.recoverable);
866
    }
867

            
868
    #[test]
869
    fn test_list_element() {
870
        let mut reader = Reader::new("true");
871
        assert_eq!(
872
            list_element(&mut reader).unwrap(),
873
            JsonListElement {
874
                space0: String::new(),
875
                value: JsonValue::Boolean(true),
876
                space1: String::new(),
877
            }
878
        );
879
        assert_eq!(reader.cursor().index, 4);
880
    }
881

            
882
    #[test]
883
    fn test_object_value() {
884
        let mut reader = Reader::new("{}");
885
        assert_eq!(
886
            object_value(&mut reader).unwrap(),
887
            JsonValue::Object {
888
                space0: String::new(),
889
                elements: vec![]
890
            }
891
        );
892
        assert_eq!(reader.cursor().index, 2);
893

            
894
        let mut reader = Reader::new("{ }");
895
        assert_eq!(
896
            object_value(&mut reader).unwrap(),
897
            JsonValue::Object {
898
                space0: " ".to_string(),
899
                elements: vec![]
900
            }
901
        );
902
        assert_eq!(reader.cursor().index, 3);
903

            
904
        let mut reader = Reader::new("{\n  \"a\": true\n}");
905
        assert_eq!(
906
            object_value(&mut reader).unwrap(),
907
            JsonValue::Object {
908
                space0: "\n  ".to_string(),
909
                elements: vec![JsonObjectElement {
910
                    space0: String::new(),
911
                    name: Template {
912
                        delimiter: Some('"'),
913
                        elements: vec![TemplateElement::String {
914
                            value: "a".to_string(),
915
                            encoded: "a".to_string()
916
                        }],
917
                        source_info: SourceInfo::new(Pos::new(2, 4), Pos::new(2, 5))
918
                    },
919
                    space1: String::new(),
920
                    space2: " ".to_string(),
921
                    value: JsonValue::Boolean(true),
922
                    space3: "\n".to_string(),
923
                }],
924
            }
925
        );
926
        assert_eq!(reader.cursor().index, 15);
927

            
928
        let mut reader = Reader::new("true");
929
        let error = object_value(&mut reader).err().unwrap();
930
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
931
        assert_eq!(
932
            error.kind,
933
            ParseErrorKind::Expecting {
934
                value: "{".to_string()
935
            }
936
        );
937
        assert!(error.recoverable);
938
    }
939

            
940
    #[test]
941
    fn test_object_error() {
942
        let mut reader = Reader::new("{ \"a\":\n}");
943
        let error = object_value(&mut reader).err().unwrap();
944
        assert_eq!(error.pos, Pos { line: 1, column: 7 });
945
        assert_eq!(
946
            error.kind,
947
            ParseErrorKind::Json(JsonErrorVariant::EmptyElement)
948
        );
949
        assert!(!error.recoverable);
950
    }
951

            
952
    #[test]
953
    fn test_object_element() {
954
        let mut reader = Reader::new("\"a\": true");
955
        assert_eq!(
956
            object_element(&mut reader).unwrap(),
957
            JsonObjectElement {
958
                space0: String::new(),
959
                name: Template {
960
                    delimiter: Some('"'),
961
                    elements: vec![TemplateElement::String {
962
                        value: "a".to_string(),
963
                        encoded: "a".to_string()
964
                    }],
965
                    source_info: SourceInfo::new(Pos::new(1, 2), Pos::new(1, 3))
966
                },
967
                space1: String::new(),
968
                space2: " ".to_string(),
969
                value: JsonValue::Boolean(true),
970
                space3: String::new(),
971
            }
972
        );
973
        assert_eq!(reader.cursor().index, 9);
974
    }
975

            
976
    #[test]
977
    fn test_object_element_error() {
978
        let mut reader = Reader::new(":");
979
        let error = object_element(&mut reader).err().unwrap();
980
        assert_eq!(error.pos, Pos { line: 1, column: 1 });
981
        assert_eq!(
982
            error.kind,
983
            ParseErrorKind::Expecting {
984
                value: "\"".to_string()
985
            }
986
        );
987
        assert!(!error.recoverable);
988

            
989
        let mut reader = Reader::new("\"name\":\n");
990
        let error = object_element(&mut reader).err().unwrap();
991
        assert_eq!(error.pos, Pos { line: 1, column: 8 });
992
        assert_eq!(
993
            error.kind,
994
            ParseErrorKind::Json(JsonErrorVariant::EmptyElement),
995
        );
996
        assert!(!error.recoverable);
997
    }
998

            
999
    #[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);
    }
}