oxilean-parse 0.1.2

OxiLean parser - Concrete syntax to abstract syntax
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
//! Auto-generated module
//!
//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)

use super::functions::*;
use crate::tokens::Span;

/// A registry mapping `FileId` to file paths and source strings.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, Default)]
pub struct FileRegistry {
    entries: Vec<(FileId, String, String)>,
    next_id: u32,
}
impl FileRegistry {
    /// Create an empty registry.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
            next_id: 1,
        }
    }
    /// Register a new file, returning its `FileId`.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn register(&mut self, path: impl Into<String>, source: impl Into<String>) -> FileId {
        let id = FileId(self.next_id);
        self.next_id += 1;
        self.entries.push((id, path.into(), source.into()));
        id
    }
    /// Look up the source string for a file.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn source(&self, id: FileId) -> Option<&str> {
        self.entries
            .iter()
            .find(|(fid, _, _)| *fid == id)
            .map(|(_, _, src)| src.as_str())
    }
    /// Look up the path for a file.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn path(&self, id: FileId) -> Option<&str> {
        self.entries
            .iter()
            .find(|(fid, _, _)| *fid == id)
            .map(|(_, p, _)| p.as_str())
    }
    /// Number of registered files.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        self.entries.len()
    }
    /// `true` if no files are registered.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
    /// Extract text at a `FileSpan`.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn extract(&self, fspan: &FileSpan) -> &str {
        self.source(fspan.file)
            .and_then(|src| src.get(fspan.span.start..fspan.span.end))
            .unwrap_or("")
    }
}
/// A diagnostic span: a source span with severity and message.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct DiagnosticSpan {
    /// The source span.
    pub span: Span,
    /// Severity level.
    pub severity: SpanSeverity,
    /// Diagnostic message.
    #[allow(missing_docs)]
    pub message: String,
}
impl DiagnosticSpan {
    /// Create a new diagnostic span.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new(span: Span, severity: SpanSeverity, message: impl Into<String>) -> Self {
        Self {
            span,
            severity,
            message: message.into(),
        }
    }
    /// Create an error diagnostic.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn error(span: Span, message: impl Into<String>) -> Self {
        Self::new(span, SpanSeverity::Error, message)
    }
    /// Create a warning diagnostic.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn warning(span: Span, message: impl Into<String>) -> Self {
        Self::new(span, SpanSeverity::Warning, message)
    }
    /// Create an info diagnostic.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn info(span: Span, message: impl Into<String>) -> Self {
        Self::new(span, SpanSeverity::Info, message)
    }
    /// Format as a short string for display.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn format_short(&self) -> String {
        format!(
            "[{}] {}: {}",
            self.severity.label(),
            span_short(&self.span),
            self.message
        )
    }
}
/// A span paired with its provenance information.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct ProvenanceSpan {
    pub span: Span,
    pub origin: SpanOrigin,
}
impl ProvenanceSpan {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new(span: Span, origin: SpanOrigin) -> Self {
        Self { span, origin }
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn user(span: Span) -> Self {
        Self::new(span, SpanOrigin::UserSource)
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn synthetic() -> Self {
        Self::new(dummy_span(), SpanOrigin::Synthetic)
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn macro_expanded(span: Span, macro_name: impl Into<String>) -> Self {
        Self::new(
            span,
            SpanOrigin::MacroExpanded {
                macro_name: macro_name.into(),
            },
        )
    }
}
/// A collection of annotated spans.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, Default)]
pub struct SpanAnnotations {
    items: Vec<AnnotatedSpan>,
}
impl SpanAnnotations {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new() -> Self {
        Self::default()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn add(&mut self, a: AnnotatedSpan) {
        self.items.push(a);
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn annotate(&mut self, span: Span, text: impl Into<String>) {
        self.items.push(AnnotatedSpan::new(span, text));
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn at_offset(&self, offset: usize) -> Vec<&AnnotatedSpan> {
        self.items
            .iter()
            .filter(|a| span_contains(&a.span, offset))
            .collect()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn with_tag<'a>(&'a self, tag: &str) -> Vec<&'a AnnotatedSpan> {
        self.items
            .iter()
            .filter(|a| a.tag.as_deref() == Some(tag))
            .collect()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        self.items.len()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn sort_by_start(&mut self) {
        self.items.sort_by_key(|a| a.span.start);
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn iter(&self) -> impl Iterator<Item = &AnnotatedSpan> {
        self.items.iter()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn clear(&mut self) {
        self.items.clear();
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn merge(&mut self, other: SpanAnnotations) {
        self.items.extend(other.items);
    }
}
/// Incrementally build a `Span` from individual character positions.
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct SpanBuilder {
    start: usize,
    line: usize,
    column: usize,
}
impl SpanBuilder {
    /// Begin a new span at `start` (byte offset, 1-indexed line/col).
    #[allow(missing_docs)]
    pub fn new(start: usize, line: usize, column: usize) -> Self {
        Self {
            start,
            line,
            column,
        }
    }
    /// Finish the span at `end` (byte offset).
    #[allow(missing_docs)]
    pub fn finish(&self, end: usize) -> Span {
        Span::new(self.start, end, self.line, self.column)
    }
    /// Return the start byte offset.
    #[allow(missing_docs)]
    pub fn start(&self) -> usize {
        self.start
    }
    /// Return the start `SourcePos`.
    #[allow(missing_docs)]
    pub fn pos(&self) -> SourcePos {
        SourcePos::new(self.line, self.column)
    }
}
/// Convert a UTF-8 byte span to a UTF-16 code-unit span.
///
/// UTF-16 spans are used by LSP (Language Server Protocol).
#[allow(dead_code)]
#[allow(missing_docs)]
pub struct Utf16Span {
    /// Start UTF-16 code-unit index on the line.
    pub start_utf16: usize,
    /// End UTF-16 code-unit index on the line.
    pub end_utf16: usize,
    /// Line number (0-indexed for LSP).
    #[allow(missing_docs)]
    pub line: usize,
}
/// Statistics about a collection of spans.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, Default)]
pub struct SpanStats {
    pub count: usize,
    pub total_len: usize,
    pub min_len: usize,
    pub max_len: usize,
}
impl SpanStats {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn compute(spans: &[Span]) -> Self {
        if spans.is_empty() {
            return Self::default();
        }
        let count = spans.len();
        let lengths: Vec<usize> = spans.iter().map(span_len).collect();
        let total_len: usize = lengths.iter().sum();
        let min_len = *lengths.iter().min().unwrap_or(&0);
        let max_len = *lengths.iter().max().unwrap_or(&0);
        Self {
            count,
            total_len,
            min_len,
            max_len,
        }
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn avg_len(&self) -> usize {
        self.total_len.checked_div(self.count).unwrap_or(0)
    }
}
/// Identifies a source file by an integer ID.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FileId(pub u32);
impl FileId {
    /// The "unknown" / dummy file ID.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub const UNKNOWN: FileId = FileId(0);
    /// Create a new file ID.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new(id: u32) -> Self {
        FileId(id)
    }
    /// Returns the raw integer ID.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn raw(self) -> u32 {
        self.0
    }
}
/// A linear chain of spans.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, Default)]
pub struct SpanChain {
    spans: Vec<Span>,
}
impl SpanChain {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new() -> Self {
        Self::default()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn push(&mut self, span: Span) {
        self.spans.push(span);
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn total_span(&self) -> Option<Span> {
        merge_spans(&self.spans)
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        self.spans.len()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.spans.is_empty()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn iter(&self) -> impl Iterator<Item = &Span> {
        self.spans.iter()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn first(&self) -> Option<&Span> {
        self.spans.first()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn last(&self) -> Option<&Span> {
        self.spans.last()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn clear(&mut self) {
        self.spans.clear();
    }
}
/// A registry that maps string keys to `Span` values.
///
/// Useful for tracking where named items were defined in a source file.
#[derive(Clone, Debug, Default)]
#[allow(missing_docs)]
pub struct SpanRegistry {
    entries: std::collections::HashMap<String, Span>,
}
impl SpanRegistry {
    /// Create an empty registry.
    #[allow(missing_docs)]
    pub fn new() -> Self {
        Self {
            entries: std::collections::HashMap::new(),
        }
    }
    /// Register a span for `key`.
    #[allow(missing_docs)]
    pub fn register(&mut self, key: impl Into<String>, span: Span) {
        self.entries.insert(key.into(), span);
    }
    /// Look up the span for `key`.
    #[allow(missing_docs)]
    pub fn get(&self, key: &str) -> Option<&Span> {
        self.entries.get(key)
    }
    /// `true` if `key` is registered.
    #[allow(missing_docs)]
    pub fn contains(&self, key: &str) -> bool {
        self.entries.contains_key(key)
    }
    /// Number of registered entries.
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        self.entries.len()
    }
    /// `true` if empty.
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
    /// Iterate over all `(key, span)` pairs.
    #[allow(missing_docs)]
    pub fn iter(&self) -> impl Iterator<Item = (&String, &Span)> {
        self.entries.iter()
    }
    /// Remove an entry, returning its span.
    #[allow(missing_docs)]
    pub fn remove(&mut self, key: &str) -> Option<Span> {
        self.entries.remove(key)
    }
    /// Merge another registry into this one (other wins on conflict).
    #[allow(missing_docs)]
    pub fn merge(&mut self, other: SpanRegistry) {
        for (k, v) in other.entries {
            self.entries.insert(k, v);
        }
    }
}
/// A span together with a priority level.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct PrioritizedSpan {
    pub span: Span,
    pub priority: u32,
}
impl PrioritizedSpan {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new(span: Span, priority: u32) -> Self {
        Self { span, priority }
    }
}
/// A named source range: a label plus a span.
///
/// Used in diagnostics to annotate specific regions of source text.
#[derive(Clone, Debug, PartialEq)]
#[allow(missing_docs)]
pub struct LabeledSpan {
    /// Human-readable label for this region.
    pub label: String,
    /// The source span.
    pub span: Span,
}
impl LabeledSpan {
    /// Construct a new labeled span.
    #[allow(missing_docs)]
    pub fn new(label: impl Into<String>, span: Span) -> Self {
        Self {
            label: label.into(),
            span,
        }
    }
    /// Return the length of the underlying span.
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        span_len(&self.span)
    }
    /// `true` if the span is zero-length.
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}
/// A cursor that tracks the current byte position, line, and column while
/// scanning a source string.
#[derive(Clone, Debug)]
#[allow(missing_docs)]
pub struct SourceCursor<'a> {
    source: &'a str,
    pos: usize,
    line: usize,
    col: usize,
}
impl<'a> SourceCursor<'a> {
    /// Create a new cursor at the beginning of `source`.
    #[allow(missing_docs)]
    pub fn new(source: &'a str) -> Self {
        Self {
            source,
            pos: 0,
            line: 1,
            col: 1,
        }
    }
    /// Return the current byte position.
    #[allow(missing_docs)]
    pub fn pos(&self) -> usize {
        self.pos
    }
    /// Return the current `SourcePos` (1-indexed).
    #[allow(missing_docs)]
    pub fn source_pos(&self) -> SourcePos {
        SourcePos::new(self.line, self.col)
    }
    /// Return the current `Span` (zero-length, at the current position).
    #[allow(missing_docs)]
    pub fn current_span(&self) -> Span {
        Span::new(self.pos, self.pos, self.line, self.col)
    }
    /// `true` if the cursor is at the end of the source.
    #[allow(missing_docs)]
    pub fn is_eof(&self) -> bool {
        self.pos >= self.source.len()
    }
    /// Peek at the next character without advancing.
    #[allow(missing_docs)]
    pub fn peek(&self) -> Option<char> {
        self.source[self.pos..].chars().next()
    }
    /// Peek at the character `n` UTF-8 code points ahead.
    #[allow(missing_docs)]
    pub fn peek_ahead(&self, n: usize) -> Option<char> {
        self.source[self.pos..].chars().nth(n)
    }
    /// Advance by one character and return it.
    #[allow(missing_docs)]
    pub fn advance(&mut self) -> Option<char> {
        let ch = self.source[self.pos..].chars().next()?;
        self.pos += ch.len_utf8();
        if ch == '\n' {
            self.line += 1;
            self.col = 1;
        } else {
            self.col += 1;
        }
        Some(ch)
    }
    /// Advance while the predicate is true, returning the consumed substring.
    #[allow(missing_docs)]
    pub fn advance_while<F: Fn(char) -> bool>(&mut self, pred: F) -> &'a str {
        let start = self.pos;
        while let Some(ch) = self.peek() {
            if pred(ch) {
                self.advance();
            } else {
                break;
            }
        }
        &self.source[start..self.pos]
    }
    /// Consume exactly `n` bytes (assumes ASCII for simplicity).
    #[allow(missing_docs)]
    pub fn advance_bytes(&mut self, n: usize) {
        for _ in 0..n {
            self.advance();
        }
    }
    /// Create a `Span` starting at `start_pos` and ending at the current position.
    #[allow(missing_docs)]
    pub fn span_from(&self, start: usize, start_line: usize, start_col: usize) -> Span {
        Span::new(start, self.pos, start_line, start_col)
    }
    /// Return the remaining (unconsumed) source text.
    #[allow(missing_docs)]
    pub fn rest(&self) -> &'a str {
        &self.source[self.pos..]
    }
    /// Return the consumed source text.
    #[allow(missing_docs)]
    pub fn consumed(&self) -> &'a str {
        &self.source[..self.pos]
    }
}
/// A collection of diagnostics associated with a source file.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, Default)]
pub struct DiagnosticSet {
    diagnostics: Vec<DiagnosticSpan>,
}
impl DiagnosticSet {
    /// Create an empty set.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new() -> Self {
        Self::default()
    }
    /// Add a diagnostic.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn add(&mut self, d: DiagnosticSpan) {
        self.diagnostics.push(d);
    }
    /// Add an error.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn add_error(&mut self, span: Span, msg: impl Into<String>) {
        self.add(DiagnosticSpan::error(span, msg));
    }
    /// Add a warning.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn add_warning(&mut self, span: Span, msg: impl Into<String>) {
        self.add(DiagnosticSpan::warning(span, msg));
    }
    /// Add an info.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn add_info(&mut self, span: Span, msg: impl Into<String>) {
        self.add(DiagnosticSpan::info(span, msg));
    }
    /// Count diagnostics of a given severity.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn count_severity(&self, sev: &SpanSeverity) -> usize {
        self.diagnostics
            .iter()
            .filter(|d| &d.severity == sev)
            .count()
    }
    /// Total number of diagnostics.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        self.diagnostics.len()
    }
    /// Check if empty.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.diagnostics.is_empty()
    }
    /// Check if there are any errors.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn has_errors(&self) -> bool {
        self.diagnostics.iter().any(|d| d.severity.is_error())
    }
    /// Get all errors.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn errors(&self) -> Vec<&DiagnosticSpan> {
        self.diagnostics
            .iter()
            .filter(|d| d.severity.is_error())
            .collect()
    }
    /// Get all warnings.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn warnings(&self) -> Vec<&DiagnosticSpan> {
        self.diagnostics
            .iter()
            .filter(|d| matches!(d.severity, SpanSeverity::Warning))
            .collect()
    }
    /// Sort diagnostics by span start offset.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn sort_by_position(&mut self) {
        self.diagnostics.sort_by_key(|d| d.span.start);
    }
    /// Iterate over all diagnostics.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn iter(&self) -> impl Iterator<Item = &DiagnosticSpan> {
        self.diagnostics.iter()
    }
    /// Clear all diagnostics.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn clear(&mut self) {
        self.diagnostics.clear();
    }
    /// Merge another set into this one.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn merge(&mut self, other: DiagnosticSet) {
        self.diagnostics.extend(other.diagnostics);
    }
}
/// A span diff: describes changes between two spans.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub struct SpanDiff {
    /// The old span.
    pub old: Span,
    /// The new span.
    pub new: Span,
    /// The byte delta (positive = grew, negative = shrank).
    #[allow(missing_docs)]
    pub byte_delta: i64,
}
impl SpanDiff {
    /// Compute the diff between two spans.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn compute(old: Span, new: Span) -> Self {
        let byte_delta = new.end as i64 - old.end as i64;
        Self {
            old,
            new,
            byte_delta,
        }
    }
    /// Whether the span grew.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn grew(&self) -> bool {
        self.byte_delta > 0
    }
    /// Whether the span shrank.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn shrank(&self) -> bool {
        self.byte_delta < 0
    }
    /// Whether the span is unchanged.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn unchanged(&self) -> bool {
        self.byte_delta == 0
    }
}
/// Tracks how a set of spans evolve as edits are applied.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, Default)]
pub struct IncrementalSpanTracker {
    spans: Vec<Span>,
    edit_count: usize,
}
impl IncrementalSpanTracker {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new() -> Self {
        Self::default()
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn track(&mut self, span: Span) {
        self.spans.push(span);
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn apply_edit(&mut self, edit_start: usize, delta: i64) {
        shift_spans(&mut self.spans, edit_start, delta);
        self.edit_count += 1;
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn spans(&self) -> &[Span] {
        &self.spans
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn edit_count(&self) -> usize {
        self.edit_count
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn reset(&mut self) {
        self.spans.clear();
        self.edit_count = 0;
    }
}
/// A value paired with its source `Span`.
#[derive(Clone, Debug, PartialEq)]
#[allow(missing_docs)]
pub struct Spanned<T> {
    /// The value.
    pub value: T,
    /// The source span.
    pub span: Span,
}
impl<T> Spanned<T> {
    /// Wrap `value` at `span`.
    #[allow(missing_docs)]
    pub fn new(value: T, span: Span) -> Self {
        Self { value, span }
    }
    /// Map over the value, keeping the span.
    #[allow(missing_docs)]
    pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Spanned<U> {
        Spanned {
            value: f(self.value),
            span: self.span,
        }
    }
    /// Borrow the inner value.
    #[allow(clippy::should_implement_trait)]
    #[allow(missing_docs)]
    pub fn as_ref(&self) -> &T {
        &self.value
    }
    /// Consume and return the value, discarding the span.
    #[allow(missing_docs)]
    pub fn into_value(self) -> T {
        self.value
    }
}
/// The origin of a span.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, PartialEq)]
pub enum SpanOrigin {
    UserSource,
    MacroExpanded { macro_name: String },
    Elaborated,
    Synthetic,
}
impl SpanOrigin {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_user_source(&self) -> bool {
        matches!(self, SpanOrigin::UserSource)
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_synthetic(&self) -> bool {
        matches!(self, SpanOrigin::Synthetic)
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn kind_str(&self) -> &'static str {
        match self {
            SpanOrigin::UserSource => "user",
            SpanOrigin::MacroExpanded { .. } => "macro",
            SpanOrigin::Elaborated => "elab",
            SpanOrigin::Synthetic => "synthetic",
        }
    }
}
/// A span paired with a severity level, for diagnostics.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, PartialEq)]
pub enum SpanSeverity {
    /// Informational annotation.
    Info,
    /// A warning annotation.
    Warning,
    /// An error annotation.
    Error,
}
impl SpanSeverity {
    /// Returns `true` if this is an error severity.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_error(&self) -> bool {
        matches!(self, SpanSeverity::Error)
    }
    /// Short label string for this severity.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn label(&self) -> &'static str {
        match self {
            SpanSeverity::Info => "info",
            SpanSeverity::Warning => "warning",
            SpanSeverity::Error => "error",
        }
    }
}
/// A span paired with annotation text and optional tag.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, PartialEq)]
pub struct AnnotatedSpan {
    pub span: Span,
    pub annotation: String,
    pub tag: Option<String>,
}
impl AnnotatedSpan {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new(span: Span, annotation: impl Into<String>) -> Self {
        Self {
            span,
            annotation: annotation.into(),
            tag: None,
        }
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn with_tag(span: Span, annotation: impl Into<String>, tag: impl Into<String>) -> Self {
        Self {
            span,
            annotation: annotation.into(),
            tag: Some(tag.into()),
        }
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        span_len(&self.span)
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}
/// A half-open interval \[start, end) over span indices (for range operations).
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SpanRange {
    pub start_idx: usize,
    pub end_idx: usize,
}
impl SpanRange {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new(start_idx: usize, end_idx: usize) -> Self {
        Self { start_idx, end_idx }
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        self.end_idx.saturating_sub(self.start_idx)
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.start_idx >= self.end_idx
    }
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn contains(&self, idx: usize) -> bool {
        idx >= self.start_idx && idx < self.end_idx
    }
}
/// A span with a byte-level padding on each side.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug)]
pub struct PaddedSpan {
    pub inner: Span,
    pub left_pad: usize,
    pub right_pad: usize,
}
impl PaddedSpan {
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new(inner: Span, left_pad: usize, right_pad: usize) -> Self {
        Self {
            inner,
            left_pad,
            right_pad,
        }
    }
    /// Expand the inner span by the padding amounts, clamped to source bounds.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn expanded(&self, source_len: usize) -> Span {
        let start = self.inner.start.saturating_sub(self.left_pad);
        let end = (self.inner.end + self.right_pad).min(source_len);
        Span::new(start, end, self.inner.line, self.inner.column)
    }
}
/// A flat map from span start offsets to values.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, Default)]
pub struct SpanMap<V> {
    entries: Vec<(usize, V)>,
}
impl<V> SpanMap<V> {
    /// Create an empty map.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }
    /// Insert a value at `offset`.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn insert(&mut self, offset: usize, value: V) {
        self.entries.push((offset, value));
    }
    /// Look up the value at `offset`.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn get(&self, offset: usize) -> Option<&V> {
        self.entries
            .iter()
            .find(|(o, _)| *o == offset)
            .map(|(_, v)| v)
    }
    /// Number of entries.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        self.entries.len()
    }
    /// Check if empty.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
    /// Iterate over all entries.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn iter(&self) -> impl Iterator<Item = &(usize, V)> {
        self.entries.iter()
    }
}
/// A span that also carries a `FileId`, enabling multi-file diagnostics.
#[allow(dead_code)]
#[allow(missing_docs)]
#[derive(Clone, Debug, PartialEq)]
pub struct FileSpan {
    /// Which file this span belongs to.
    pub file: FileId,
    /// The span within that file.
    pub span: Span,
}
impl FileSpan {
    /// Create a new file span.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn new(file: FileId, span: Span) -> Self {
        Self { file, span }
    }
    /// Return the length in bytes.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn len(&self) -> usize {
        span_len(&self.span)
    }
    /// `true` if this is a zero-length span.
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Merge two `FileSpan`s (panics if they come from different files).
    #[allow(dead_code)]
    #[allow(missing_docs)]
    pub fn merge_with(&self, other: &FileSpan) -> FileSpan {
        assert_eq!(
            self.file, other.file,
            "cannot merge spans from different files"
        );
        FileSpan {
            file: self.file,
            span: self.span.merge(&other.span),
        }
    }
}
/// A line/column position in source text (1-indexed).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[allow(missing_docs)]
pub struct SourcePos {
    /// 1-indexed line number.
    pub line: usize,
    /// 1-indexed column number (byte offset within the line).
    pub col: usize,
}
impl SourcePos {
    /// Construct a new `SourcePos`.
    #[allow(missing_docs)]
    pub fn new(line: usize, col: usize) -> Self {
        Self { line, col }
    }
    /// The "beginning of file" position.
    #[allow(missing_docs)]
    pub fn start() -> Self {
        Self { line: 1, col: 1 }
    }
    /// Advance by one ASCII character (no newline).
    #[allow(missing_docs)]
    pub fn advance_col(&self) -> Self {
        Self {
            line: self.line,
            col: self.col + 1,
        }
    }
    /// Advance to the next line (column resets to 1).
    #[allow(missing_docs)]
    pub fn advance_line(&self) -> Self {
        Self {
            line: self.line + 1,
            col: 1,
        }
    }
    /// `true` if `other` is on the same line as `self`.
    #[allow(missing_docs)]
    pub fn same_line(&self, other: &SourcePos) -> bool {
        self.line == other.line
    }
}