alpha2-diagnose 0.10.0

Format-neutral document diagnostics for alpha2: a document tree, a JSON reader that recovers, a schema walker, advice and fixes.
Documentation
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
//! JSON text to a tree. Valid JSON is read as written and gives no diagnostic; what a model
//! commonly writes instead is recovered and reported, most with a certain fix.

use std::fmt::Write as _;

use crate::codes::{
    SYNTAX_BYTE_ORDER_MARK, SYNTAX_CODE_FENCE, SYNTAX_COMMENT, SYNTAX_CONTROL_CHARACTER,
    SYNTAX_CUT, SYNTAX_FOREIGN_LITERAL, SYNTAX_INVALID_ESCAPE, SYNTAX_LONE_SURROGATE,
    SYNTAX_MISSING_COMMA, SYNTAX_NOT_FINITE, SYNTAX_NUMBER_SPELLING, SYNTAX_SINGLE_QUOTES,
    SYNTAX_SURROUNDING_TEXT, SYNTAX_TOO_DEEP, SYNTAX_TRAILING_COMMA, SYNTAX_UNQUOTED_KEY,
    SYNTAX_UNREADABLE,
};
use crate::diagnostic::{Diagnostic, Edit, Fix};
use crate::path::{Path, Segment};
use crate::tree::{Entry, Node, Number, Span, Value};
use crate::write::quote;

use super::Read;

const LITERALS: [&str; 9] = [
    "true",
    "false",
    "null",
    "True",
    "False",
    "None",
    "NaN",
    "Infinity",
    "undefined",
];

/// The deepest nesting of arrays and objects read, as `serde_json` accepts.
pub const MAX_DEPTH: usize = 127;

/// Reads `text` as JSON. Diagnostics are placed under `root`.
#[must_use]
pub fn json(text: &str, root: &Path) -> Read {
    let mut reader = Reader {
        text,
        bytes: text.as_bytes(),
        at: 0,
        line: 1,
        column: 1,
        start: 0,
        end: text.len(),
        diagnostics: Vec::new(),
        incomplete: Vec::new(),
    };
    let tree = reader.document(root);
    let mut diagnostics = reader.diagnostics;
    if let Some(tree) = &tree {
        for diagnostic in &mut diagnostics {
            while tree.at(&diagnostic.path).is_none() {
                let Some(parent) = diagnostic.path.parent() else {
                    break;
                };
                diagnostic.path = parent;
            }
        }
    }
    Read {
        tree,
        diagnostics,
        incomplete: reader.incomplete,
    }
}

enum Hex {
    End,
    Invalid,
    Value(u32),
}

enum Parsed {
    Done(Node),
    Stopped(Option<Node>),
}

#[derive(Clone, Copy)]
struct Mark {
    at: usize,
    line: u32,
    column: u32,
}

struct Reader<'a> {
    text: &'a str,
    bytes: &'a [u8],
    at: usize,
    line: u32,
    column: u32,
    start: usize,
    end: usize,
    diagnostics: Vec<Diagnostic>,
    incomplete: Vec<Path>,
}

fn is_identifier_start(byte: u8) -> bool {
    byte.is_ascii_alphabetic() || byte == b'_' || byte == b'$'
}

fn is_identifier(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
}

fn is_delimiter(byte: Option<u8>) -> bool {
    byte.is_none_or(|byte| {
        matches!(
            byte,
            b' ' | b'\t' | b'\n' | b'\r' | b',' | b']' | b'}' | b':' | b'/'
        )
    })
}

impl Reader<'_> {
    fn peek(&self) -> Option<u8> {
        (self.at < self.end).then(|| self.bytes[self.at])
    }

    fn peek_at(&self, ahead: usize) -> Option<u8> {
        let at = self.at + ahead;
        (at < self.end).then(|| self.bytes[at])
    }

    fn bump(&mut self) {
        let byte = self.bytes[self.at];
        self.at += 1;
        if byte == b'\n' {
            self.line += 1;
            self.column = 1;
        } else if byte & 0xC0 != 0x80 {
            self.column += 1;
        }
    }

    fn bump_n(&mut self, count: usize) {
        for _ in 0..count {
            self.bump();
        }
    }

    const fn mark(&self) -> Mark {
        Mark {
            at: self.at,
            line: self.line,
            column: self.column,
        }
    }

    fn reset(&mut self, mark: Mark) {
        self.at = mark.at;
        self.line = mark.line;
        self.column = mark.column;
    }

    fn span_from(&self, mark: Mark) -> Span {
        Span {
            offset: mark.at,
            length: self.at - mark.at,
            line: mark.line,
            column: mark.column,
        }
    }

    const fn here(&self) -> Span {
        Span {
            offset: self.at,
            length: 0,
            line: self.line,
            column: self.column,
        }
    }

    fn report(&mut self, diagnostic: Diagnostic) {
        self.diagnostics.push(diagnostic);
    }

    fn document(&mut self, root: &Path) -> Option<Node> {
        if self.text.starts_with('\u{feff}') {
            let span = Span {
                offset: 0,
                length: 3,
                line: 1,
                column: 1,
            };
            self.report(
                Diagnostic::new(
                    &SYNTAX_BYTE_ORDER_MARK,
                    root.clone(),
                    "The text starts with a byte-order mark, which JSON readers refuse.",
                )
                .at(Some(span))
                .fix(Fix::certain(
                    "remove the byte-order mark",
                    vec![remove(0, 3)],
                )),
            );
            self.bump_n(3);
            self.column = 1;
            self.start = 3;
        }
        self.skip_space();
        if !self.at_value_start() {
            self.surroundings(root);
        }
        self.skip_space_and_comments(root);
        if self.peek().is_none() {
            let span = self.here();
            self.report(
                Diagnostic::new(
                    &SYNTAX_UNREADABLE,
                    root.clone(),
                    "The text holds no document.",
                )
                .at(Some(span))
                .data(Node::map([("expected", Node::text("a value"))])),
            );
            return None;
        }
        let parsed = self.value(&mut root.clone(), 0);
        let tree = match parsed {
            Parsed::Done(node) => Some(node),
            Parsed::Stopped(node) => return node,
        };
        self.skip_space_and_comments(root);
        if self.at < self.end {
            self.trailing_text(root);
        }
        tree
    }

    fn at_value_start(&self) -> bool {
        match self.peek() {
            Some(b'{' | b'[' | b'"' | b'\'' | b'-' | b'+' | b'.' | b'0'..=b'9') => true,
            Some(byte) if is_identifier_start(byte) => {
                let start = self.at;
                let mut end = start;
                while end < self.end && is_identifier(self.bytes[end]) {
                    end += 1;
                }
                let word = &self.text[start..end];
                if end == self.end {
                    return LITERALS.iter().any(|literal| literal.starts_with(word));
                }
                LITERALS.contains(&word) && is_delimiter(self.bytes.get(end).copied())
            }
            _ => false,
        }
    }

    fn surroundings(&mut self, root: &Path) {
        let rest = &self.text[self.at..self.end];
        let fence = rest
            .match_indices("```")
            .map(|(offset, _)| self.at + offset)
            .find(|&offset| offset == 0 || self.bytes[offset - 1] == b'\n');
        let first_bracket = rest.find(['{', '[']).map(|offset| self.at + offset);
        if let Some(open) = fence
            && first_bracket.is_none_or(|bracket| open < bracket)
        {
            let content = self.text[open..]
                .find('\n')
                .map_or(self.end, |line_end| open + line_end + 1);
            let close = self.text[content..self.end]
                .match_indices("```")
                .map(|(offset, _)| content + offset)
                .find(|&offset| self.bytes[offset - 1] == b'\n')
                .unwrap_or(self.end);
            self.bump_n(open - self.at);
            let fence_start = self.mark();
            self.report(
                Diagnostic::new(
                    &SYNTAX_CODE_FENCE,
                    root.clone(),
                    "The document is wrapped in a Markdown code fence; send the JSON alone.",
                )
                .at(Some(Span {
                    offset: open,
                    length: content - open,
                    line: fence_start.line,
                    column: fence_start.column,
                }))
                .fix(Fix::certain(
                    "remove the code fence and the text around it",
                    vec![
                        remove(close, self.text.len() - close),
                        remove(self.start, content - self.start),
                    ],
                )),
            );
            self.bump_n(content - self.at);
            self.end = close;
            return;
        }
        let Some(start) = first_bracket else {
            return;
        };
        let mark = self.mark();
        self.report(
            Diagnostic::new(
                &SYNTAX_SURROUNDING_TEXT,
                root.clone(),
                "Text that is not JSON comes before the document.",
            )
            .at(Some(Span {
                offset: mark.at,
                length: start - mark.at,
                line: mark.line,
                column: mark.column,
            }))
            .fix(Fix::certain(
                "remove the text before the document",
                vec![remove(self.start, start - self.start)],
            )),
        );
        self.bump_n(start - self.at);
    }

    fn trailing_text(&mut self, root: &Path) {
        let mark = self.mark();
        let length = self.end - self.at;
        self.report(
            Diagnostic::new(
                &SYNTAX_SURROUNDING_TEXT,
                root.clone(),
                "Text that is not part of the document follows it.",
            )
            .at(Some(Span {
                offset: mark.at,
                length,
                line: mark.line,
                column: mark.column,
            }))
            .fix(Fix::certain(
                "remove the text after the document",
                vec![remove(mark.at, length)],
            )),
        );
        self.at = self.end;
    }

    fn skip_space(&mut self) {
        while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.peek() {
            self.bump();
        }
    }

    fn skip_space_and_comments(&mut self, path: &Path) -> bool {
        loop {
            self.skip_space();
            match (self.peek(), self.peek_at(1)) {
                (Some(b'/'), Some(b'/')) => {
                    let mark = self.mark();
                    while self.peek().is_some_and(|byte| byte != b'\n') {
                        self.bump();
                    }
                    self.comment(path, mark);
                }
                (Some(b'/'), Some(b'*')) => {
                    let mark = self.mark();
                    self.bump_n(2);
                    let closed = loop {
                        match (self.peek(), self.peek_at(1)) {
                            (Some(b'*'), Some(b'/')) => {
                                self.bump_n(2);
                                break true;
                            }
                            (Some(_), _) => self.bump(),
                            (None, _) => break false,
                        }
                    };
                    if !closed {
                        return false;
                    }
                    self.comment(path, mark);
                }
                _ => return true,
            }
        }
    }

    fn comment(&mut self, path: &Path, mark: Mark) {
        let span = self.span_from(mark);
        self.report(
            Diagnostic::new(
                &SYNTAX_COMMENT,
                path.clone(),
                "JSON has no comments; this one has to go.",
            )
            .at(Some(span))
            .fix(Fix::certain(
                "remove the comment",
                vec![remove(span.offset, span.length)],
            )),
        );
    }

    fn cut(&mut self, path: &Path, dropped: Option<&str>) {
        let span = self.here();
        let mut message = format!("The text ends inside {path}");
        if let Some(dropped) = dropped {
            let _ = write!(message, ", in the middle of {dropped}");
        }
        message.push_str("; what was open is closed here to check the rest.");
        let mut data = vec![("open", Node::text(path.to_string()))];
        if let Some(dropped) = dropped {
            data.push(("dropped", Node::text(dropped)));
        }
        self.report(
            Diagnostic::new(&SYNTAX_CUT, path.clone(), message)
                .at(Some(span))
                .data(Node::map(data)),
        );
    }

    fn unreadable(&mut self, path: &Path, expected: &str) {
        let mut span = self.here();
        let found = match self.text[self.at..self.end].chars().next() {
            Some(char) => {
                span.length = char.len_utf8();
                format!("{char:?}")
            }
            None => "the end of the text".to_owned(),
        };
        self.report(
            Diagnostic::new(
                &SYNTAX_UNREADABLE,
                path.clone(),
                format!(
                    "Expected {expected} but found {found}; the text cannot be read from here on."
                ),
            )
            .at(Some(span))
            .data(Node::map([
                ("expected", Node::text(expected)),
                ("found", Node::text(found)),
            ])),
        );
    }

    fn value(&mut self, path: &mut Path, depth: usize) -> Parsed {
        let mark = self.mark();
        match self.peek() {
            None => {
                self.cut(path, None);
                Parsed::Stopped(None)
            }
            Some(b'{') => self.object(path, depth + 1),
            Some(b'[') => self.array(path, depth + 1),
            Some(quote @ (b'"' | b'\'')) => {
                let text = if quote == b'"' {
                    self.string(path, b'"')
                } else {
                    self.single_quoted(path, mark)
                };
                if let Some(text) = text {
                    Parsed::Done(spanned(Value::Text(text), self.span_from(mark)))
                } else {
                    self.cut(path, Some("a string"));
                    Parsed::Stopped(None)
                }
            }
            Some(b'-' | b'+' | b'.' | b'0'..=b'9') => self.number(path),
            Some(byte) if is_identifier_start(byte) => self.literal(path),
            Some(_) => {
                self.unreadable(path, "a value");
                Parsed::Stopped(None)
            }
        }
    }

    fn object(&mut self, path: &mut Path, depth: usize) -> Parsed {
        let mark = self.mark();
        if depth > MAX_DEPTH {
            self.too_deep(path);
            return Parsed::Stopped(None);
        }
        self.bump();
        let mut entries: Vec<Entry> = Vec::new();
        let mut previous_end: Option<usize> = None;
        let stopped = loop {
            if !self.space(path) {
                break true;
            }
            match self.peek() {
                None => {
                    self.cut(path, None);
                    break true;
                }
                Some(b'}') => {
                    self.bump();
                    break false;
                }
                Some(b'"' | b'\'') => {}
                Some(byte) if is_identifier_start(byte) => {}
                Some(_) => {
                    self.unreadable(path, "a key or `}`");
                    break true;
                }
            }
            if let Some(end) = previous_end.take() {
                self.missing_comma(path, end);
            }
            let key_mark = self.mark();
            let Some(key) = self.key(path) else {
                self.cut(path, Some("a key"));
                break true;
            };
            let key_span = self.span_from(key_mark);
            if !self.space(path) {
                break true;
            }
            match self.peek() {
                Some(b':') => self.bump(),
                None => {
                    self.cut(path, Some(&format!("the entry {}", quote(&key))));
                    break true;
                }
                Some(_) => {
                    self.unreadable(path, "`:` after the key");
                    break true;
                }
            }
            if !self.space(path) {
                break true;
            }
            path.push(Segment::Key(key.clone()));
            let parsed = self.value(path, depth);
            path.pop();
            match parsed {
                Parsed::Done(value) => {
                    previous_end = value.span.map(|span| span.end());
                    entries.push(Entry {
                        key,
                        key_span: Some(key_span),
                        value,
                    });
                }
                Parsed::Stopped(value) => {
                    if let Some(value) = value {
                        entries.push(Entry {
                            key,
                            key_span: Some(key_span),
                            value,
                        });
                    }
                    break true;
                }
            }
            if !self.separator(path, b'}', &mut previous_end) {
                break true;
            }
        };
        let node = Node {
            value: Value::Map(entries),
            span: Some(self.span_from(mark)),
        };
        if stopped {
            self.incomplete.push(path.clone());
            Parsed::Stopped(Some(node))
        } else {
            Parsed::Done(node)
        }
    }

    fn array(&mut self, path: &mut Path, depth: usize) -> Parsed {
        let mark = self.mark();
        if depth > MAX_DEPTH {
            self.too_deep(path);
            return Parsed::Stopped(None);
        }
        self.bump();
        let mut items: Vec<Node> = Vec::new();
        let mut previous_end: Option<usize> = None;
        let stopped = loop {
            if !self.space(path) {
                break true;
            }
            match self.peek() {
                None => {
                    self.cut(path, None);
                    break true;
                }
                Some(b']') => {
                    self.bump();
                    break false;
                }
                Some(_) if self.at_value_start() => {}
                Some(_) => {
                    self.unreadable(path, "a value or `]`");
                    break true;
                }
            }
            if let Some(end) = previous_end.take() {
                self.missing_comma(path, end);
            }
            path.push(Segment::Index(items.len()));
            let parsed = self.value(path, depth);
            path.pop();
            match parsed {
                Parsed::Done(value) => {
                    previous_end = value.span.map(|span| span.end());
                    items.push(value);
                }
                Parsed::Stopped(value) => {
                    items.extend(value);
                    break true;
                }
            }
            if !self.separator(path, b']', &mut previous_end) {
                break true;
            }
        };
        let node = Node {
            value: Value::List(items),
            span: Some(self.span_from(mark)),
        };
        if stopped {
            self.incomplete.push(path.clone());
            Parsed::Stopped(Some(node))
        } else {
            Parsed::Done(node)
        }
    }

    fn space(&mut self, path: &Path) -> bool {
        let closed = self.skip_space_and_comments(path);
        if !closed {
            self.cut(path, Some("a comment"));
        }
        closed
    }

    fn separator(&mut self, path: &Path, close: u8, previous_end: &mut Option<usize>) -> bool {
        if !self.space(path) {
            return false;
        }
        if self.peek() == Some(b',') {
            *previous_end = None;
            let comma = self.mark();
            self.bump();
            if !self.space(path) {
                return false;
            }
            if self.peek() == Some(close) {
                self.trailing_comma(path, comma);
            }
        }
        true
    }

    fn too_deep(&mut self, path: &Path) {
        let mut span = self.here();
        span.length = 1;
        self.report(
            Diagnostic::new(
                &SYNTAX_TOO_DEEP,
                path.clone(),
                format!("Arrays and objects nest deeper than {MAX_DEPTH} levels here."),
            )
            .at(Some(span))
            .data(Node::map([("maximum", Node::from(MAX_DEPTH))])),
        );
    }

    fn trailing_comma(&mut self, path: &Path, comma: Mark) {
        let span = Span {
            offset: comma.at,
            length: 1,
            line: comma.line,
            column: comma.column,
        };
        self.report(
            Diagnostic::new(
                &SYNTAX_TRAILING_COMMA,
                path.clone(),
                "A comma follows the last entry; JSON allows none there.",
            )
            .at(Some(span))
            .fix(Fix::certain("remove the comma", vec![remove(comma.at, 1)])),
        );
    }

    fn missing_comma(&mut self, path: &Path, previous_end: usize) {
        let span = self.here();
        self.report(
            Diagnostic::new(
                &SYNTAX_MISSING_COMMA,
                path.clone(),
                "A comma is missing between two entries.",
            )
            .at(Some(span))
            .fix(Fix::certain(
                "add a comma",
                vec![Edit::Text {
                    offset: previous_end,
                    length: 0,
                    replacement: ",".into(),
                }],
            )),
        );
    }

    fn key(&mut self, path: &Path) -> Option<String> {
        let mark = self.mark();
        match self.peek()? {
            b'"' => self.string(path, b'"'),
            b'\'' => self.single_quoted(path, mark),
            _ => {
                while self.peek().is_some_and(is_identifier) {
                    self.bump();
                }
                let key = self.text[mark.at..self.at].to_owned();
                let span = self.span_from(mark);
                self.report(
                    Diagnostic::new(
                        &SYNTAX_UNQUOTED_KEY,
                        path.clone(),
                        format!("The key {key} has no quotes; JSON keys are strings."),
                    )
                    .at(Some(span))
                    .fix(Fix::certain(
                        format!("write the key as {}", quote(&key)),
                        vec![replace_text(span, quote(&key))],
                    )),
                );
                Some(key)
            }
        }
    }

    fn single_quoted(&mut self, path: &Path, mark: Mark) -> Option<String> {
        let text = self.string(path, b'\'')?;
        let span = self.span_from(mark);
        self.report(
            Diagnostic::new(
                &SYNTAX_SINGLE_QUOTES,
                path.clone(),
                "A string is in single quotes; JSON strings use double quotes.",
            )
            .at(Some(span))
            .fix(Fix::certain(
                "use double quotes",
                vec![replace_text(span, quote(&text))],
            )),
        );
        Some(text)
    }

    fn string(&mut self, path: &Path, close: u8) -> Option<String> {
        let open = self.mark();
        self.bump();
        let mut text = String::new();
        let mut controls = Vec::new();
        let mut escapes = Vec::new();
        let mut surrogates = Vec::new();
        loop {
            let byte = self.peek()?;
            if byte == close {
                self.bump();
                break;
            }
            match byte {
                b'\\' => {
                    let mark = self.mark();
                    self.bump();
                    self.escape(&mut text, mark, close, &mut escapes, &mut surrogates)?;
                }
                0x00..=0x1F => {
                    let mark = self.mark();
                    self.bump();
                    let span = self.span_from(mark);
                    controls.push(replace_text(
                        span,
                        quote(&char::from(byte).to_string())
                            .trim_matches('"')
                            .to_owned(),
                    ));
                    text.push(char::from(byte));
                }
                _ => {
                    let start = self.at;
                    while self
                        .peek()
                        .is_some_and(|byte| byte != close && byte != b'\\' && byte >= 0x20)
                    {
                        self.bump();
                    }
                    text.push_str(&self.text[start..self.at]);
                }
            }
        }
        let span = self.span_from(open);
        if !controls.is_empty() {
            self.report(
                Diagnostic::new(
                    &SYNTAX_CONTROL_CHARACTER,
                    path.clone(),
                    "A string holds a raw control character, such as a line break; JSON writes it escaped.",
                )
                .at(Some(span))
                .fix(Fix::certain("escape the control characters", controls)),
            );
        }
        if !escapes.is_empty() {
            let diagnostic = Diagnostic::new(
                &SYNTAX_INVALID_ESCAPE,
                path.clone(),
                "A string holds an escape JSON does not define; the character after the backslash is kept.",
            )
            .at(Some(span));
            let all_quotes = escapes.iter().all(|(_, quote)| *quote);
            let edits = escapes.into_iter().map(|(edit, _)| edit).collect();
            self.report(if all_quotes {
                diagnostic.fix(Fix::certain("remove the backslashes", edits))
            } else {
                diagnostic
            });
        }
        if !surrogates.is_empty() {
            self.report(
                Diagnostic::new(
                    &SYNTAX_LONE_SURROGATE,
                    path.clone(),
                    "A string escapes half of a UTF-16 surrogate pair, which is no character.",
                )
                .at(Some(span)),
            );
        }
        Some(text)
    }

    fn escape(
        &mut self,
        text: &mut String,
        mark: Mark,
        close: u8,
        escapes: &mut Vec<(Edit, bool)>,
        surrogates: &mut Vec<Span>,
    ) -> Option<()> {
        let byte = self.peek()?;
        let simple = match byte {
            b'"' => Some('"'),
            b'\\' => Some('\\'),
            b'/' => Some('/'),
            b'b' => Some('\u{8}'),
            b'f' => Some('\u{c}'),
            b'n' => Some('\n'),
            b'r' => Some('\r'),
            b't' => Some('\t'),
            _ => None,
        };
        if let Some(char) = simple {
            self.bump();
            text.push(char);
            return Some(());
        }
        if byte == b'u' {
            self.bump();
            let first = match self.hex4() {
                Hex::End => return None,
                Hex::Value(value) => value,
                Hex::Invalid => {
                    escapes.push((
                        Edit::Text {
                            offset: mark.at,
                            length: 1,
                            replacement: String::new(),
                        },
                        false,
                    ));
                    text.push('u');
                    return Some(());
                }
            };
            if (0xD800..0xDC00).contains(&first) {
                if self.peek() == Some(b'\\') && self.peek_at(1) == Some(b'u') {
                    let resume = self.mark();
                    self.bump_n(2);
                    if let Hex::Value(second) = self.hex4()
                        && (0xDC00..0xE000).contains(&second)
                    {
                        let code = 0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00);
                        text.push(char::from_u32(code).unwrap_or('\u{fffd}'));
                        return Some(());
                    }
                    self.reset(resume);
                }
                surrogates.push(self.span_from(mark));
                text.push('\u{fffd}');
            } else if (0xDC00..0xE000).contains(&first) {
                surrogates.push(self.span_from(mark));
                text.push('\u{fffd}');
            } else {
                text.push(char::from_u32(first).unwrap_or('\u{fffd}'));
            }
            return Some(());
        }
        let char = self.text[self.at..].chars().next()?;
        self.bump_n(char.len_utf8());
        escapes.push((
            Edit::Text {
                offset: mark.at,
                length: 1,
                replacement: String::new(),
            },
            close == b'"' && char == '\'',
        ));
        text.push(char);
        Some(())
    }

    fn hex4(&mut self) -> Hex {
        let mut value = 0;
        for _ in 0..4 {
            let Some(byte) = self.peek() else {
                return Hex::End;
            };
            let Some(digit) = char::from(byte).to_digit(16) else {
                return Hex::Invalid;
            };
            self.bump();
            value = value * 16 + digit;
        }
        Hex::Value(value)
    }

    fn number(&mut self, path: &Path) -> Parsed {
        let mark = self.mark();
        let mut sign = "";
        match self.peek() {
            Some(b'-') => {
                sign = "-";
                self.bump();
            }
            Some(b'+') => self.bump(),
            _ => {}
        }
        if self.peek().is_some_and(is_identifier_start) {
            let word_start = self.at;
            while self.peek().is_some_and(is_identifier) {
                self.bump();
            }
            if &self.text[word_start..self.at] == "Infinity" && is_delimiter(self.peek()) {
                return Parsed::Done(self.not_finite(path, mark, &format!("{sign}Infinity")));
            }
            self.reset(mark);
            self.unreadable(path, "a number");
            return Parsed::Stopped(None);
        }
        let digits_start = self.at;
        while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
            self.bump();
        }
        let integer = &self.text[digits_start..self.at];
        let mut fraction = None;
        if self.peek() == Some(b'.') {
            self.bump();
            let start = self.at;
            while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
                self.bump();
            }
            fraction = Some(&self.text[start..self.at]);
        }
        let mut exponent = None;
        if matches!(self.peek(), Some(b'e' | b'E')) {
            let before = self.mark();
            self.bump();
            let mut exponent_sign = "";
            if let Some(byte @ (b'+' | b'-')) = self.peek() {
                exponent_sign = if byte == b'-' { "-" } else { "+" };
                self.bump();
            }
            let start = self.at;
            while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
                self.bump();
            }
            if self.at == start {
                self.reset(before);
            } else {
                exponent = Some((exponent_sign, &self.text[start..self.at]));
            }
        }
        if (integer.is_empty() && fraction.is_none_or(str::is_empty)) || !is_delimiter(self.peek())
        {
            self.reset(mark);
            self.unreadable(path, "a number");
            return Parsed::Stopped(None);
        }
        self.finish_number(path, mark, sign, integer, fraction, exponent)
    }

    fn finish_number(
        &mut self,
        path: &Path,
        mark: Mark,
        sign: &str,
        integer: &str,
        fraction: Option<&str>,
        exponent: Option<(&str, &str)>,
    ) -> Parsed {
        let span = self.span_from(mark);
        let written = &self.text[span.offset..span.end()];
        let trimmed = integer.trim_start_matches('0');
        let mut spelling = format!("{sign}{}", if trimmed.is_empty() { "0" } else { trimmed });
        if let Some(fraction) = fraction {
            spelling.push('.');
            spelling.push_str(if fraction.is_empty() { "0" } else { fraction });
        }
        if let Some((exponent_sign, digits)) = exponent {
            spelling.push('e');
            spelling.push_str(exponent_sign);
            spelling.push_str(digits);
        }
        let number = if let Some(number) = Number::parse(written) {
            number
        } else {
            let number = Number::parse(&spelling).unwrap_or_else(|| Number::integer(0));
            self.report(
                Diagnostic::new(
                    &SYNTAX_NUMBER_SPELLING,
                    path.clone(),
                    format!("The number {written} is not spelt as JSON spells numbers."),
                )
                .at(Some(span))
                .fix(Fix::certain(
                    format!("write it as {spelling}"),
                    vec![replace_text(span, spelling.clone())],
                )),
            );
            number
        };
        Parsed::Done(Node {
            value: Value::Number(number),
            span: Some(span),
        })
    }

    fn not_finite(&mut self, path: &Path, mark: Mark, word: &str) -> Node {
        let span = self.span_from(mark);
        self.report(
            Diagnostic::new(
                &SYNTAX_NOT_FINITE,
                path.clone(),
                format!("{word} is not a number JSON can write."),
            )
            .at(Some(span))
            .help("write a finite number, or leave the field out if it has a default"),
        );
        Node {
            value: Value::Number(Number::not_finite(word.trim_start_matches('+'))),
            span: Some(span),
        }
    }

    fn literal(&mut self, path: &Path) -> Parsed {
        let mark = self.mark();
        while self.peek().is_some_and(is_identifier) {
            self.bump();
        }
        let word = &self.text[mark.at..self.at];
        if self.peek().is_none() && !matches!(word, "true" | "false" | "null") {
            let complete = matches!(word, "True" | "False" | "None" | "NaN" | "Infinity");
            if !complete {
                self.cut(path, Some("a literal"));
                return Parsed::Stopped(None);
            }
        }
        if !is_delimiter(self.peek()) {
            self.reset(mark);
            self.unreadable(path, "a value");
            return Parsed::Stopped(None);
        }
        let span = self.span_from(mark);
        let (value, json) = match word {
            "true" => return Parsed::Done(spanned(Value::Bool(true), span)),
            "false" => return Parsed::Done(spanned(Value::Bool(false), span)),
            "null" => return Parsed::Done(spanned(Value::Null, span)),
            "True" => (Value::Bool(true), Some("true")),
            "False" => (Value::Bool(false), Some("false")),
            "None" => (Value::Null, Some("null")),
            "undefined" => (Value::Null, None),
            "NaN" | "Infinity" => {
                let word = word.to_owned();
                return Parsed::Done(self.not_finite(path, mark, &word));
            }
            _ => {
                self.reset(mark);
                self.unreadable(path, "a value");
                return Parsed::Stopped(None);
            }
        };
        let mut diagnostic = Diagnostic::new(
            &SYNTAX_FOREIGN_LITERAL,
            path.clone(),
            format!("{word} is not a JSON literal."),
        )
        .at(Some(span));
        diagnostic = match json {
            Some(json) => diagnostic.fix(Fix::certain(
                format!("write {json}"),
                vec![replace_text(span, json.to_owned())],
            )),
            None => diagnostic.help("JSON has no undefined; leave the entry out or write null"),
        };
        self.report(diagnostic);
        Parsed::Done(spanned(value, span))
    }
}

const fn spanned(value: Value, span: Span) -> Node {
    Node {
        value,
        span: Some(span),
    }
}

const fn remove(offset: usize, length: usize) -> Edit {
    Edit::Text {
        offset,
        length,
        replacement: String::new(),
    }
}

const fn replace_text(span: Span, replacement: String) -> Edit {
    Edit::Text {
        offset: span.offset,
        length: span.length,
        replacement,
    }
}