serde-saphyr 0.0.19

YAML (de)serializer for Serde, emphasizing panic-free parsing and good error reporting
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
//! `miette` integration.
//!
//! This module is feature-gated behind the `miette` feature.

use std::fmt;
use std::sync::Arc;

use miette::{Diagnostic, LabeledSpan, NamedSource, SourceSpan};

use crate::Error;
use crate::Location;
use crate::{MessageFormatter, RenderOptions};
use crate::de_snipped::sanitize_terminal_snippet_preserve_len;
#[cfg(any(feature = "garde", feature = "validator"))]
use crate::location::Locations;
#[cfg(feature = "garde")]
use crate::path_map::path_key_from_garde;
#[cfg(any(feature = "garde", feature = "validator"))]
use crate::path_map::{PathKey, PathMap, format_path_with_resolved_leaf};

#[cfg(feature = "validator")]
use validator::{ValidationErrors, ValidationErrorsKind};

/// Convert a deserialization [`Error`] into a `miette::Report`.
///
/// This function takes the YAML `source` and a display `file` name/path.
///
/// # Example
///
/// ```rust,no_run
/// let yaml = "definitely\n";
///
/// let err = serde_saphyr::from_str::<bool>(yaml).expect_err("bool parse error expected");
/// let report = serde_saphyr::miette::to_miette_report(&err, yaml, "config.yaml");
///
/// // `Debug` formatting uses miette's graphical reporter.
/// eprintln!("{report:?}");
/// ```
///
/// Notes:
/// - `serde-saphyr::Error` intentionally does not retain the full input text.
///   This helper owns a copy of `source` to build a standalone `miette::Report`.
/// - If the error has no known location/span, the report will not include labels.
pub fn to_miette_report(err: &Error, source: &str, file: &str) -> miette::Report {
    to_miette_report_with_formatter(err, source, file, RenderOptions::default().formatter)
}

pub fn to_miette_report_with_formatter(
    err: &Error,
    source: &str,
    file: &str,
    formatter: &dyn MessageFormatter,
) -> miette::Report {
    let sanitized_source = sanitize_terminal_snippet_preserve_len(source.to_owned());
    let src = Arc::new(NamedSource::new(file, sanitized_source));
    let diag = build_diagnostic(err.without_snippet(), src, formatter);
    miette::Report::new(diag)
}

#[derive(Clone, Debug)]
struct ErrorDiagnostic {
    message: String,
    src: Arc<NamedSource<String>>,
    labels: Vec<LabeledSpan>,
    related: Vec<ErrorDiagnostic>,
}

impl fmt::Display for ErrorDiagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for ErrorDiagnostic {}

impl Diagnostic for ErrorDiagnostic {
    fn source_code(&self) -> Option<&dyn miette::SourceCode> {
        Some(&*self.src)
    }

    fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
        if self.labels.is_empty() {
            None
        } else {
            Some(Box::new(self.labels.clone().into_iter()))
        }
    }

    fn related(&self) -> Option<Box<dyn Iterator<Item = &dyn Diagnostic> + '_>> {
        if self.related.is_empty() {
            return None;
        }
        Some(Box::new(self.related.iter().map(|d| d as &dyn Diagnostic)))
    }
}

fn build_diagnostic(
    err: &Error,
    src: Arc<NamedSource<String>>,
    formatter: &dyn MessageFormatter,
) -> ErrorDiagnostic {
    match err {
        #[cfg(feature = "garde")]
        Error::ValidationError { report, locations } => {
            let mut related = Vec::new();
            for (path, entry) in report.iter() {
                let path_key = path_key_from_garde(path);
                related.push(build_validation_entry_diagnostic(
                    &src,
                    &path_key,
                    &entry.to_string(),
                    locations,
                ));
            }

            ErrorDiagnostic {
                message: format!(
                    "validation failed{}",
                    if related.len() == 1 {
                        ""
                    } else {
                        " (multiple errors)"
                    }
                ),
                src,
                labels: Vec::new(),
                related,
            }
        }

        #[cfg(feature = "garde")]
        Error::ValidationErrors { errors } => {
            let mut related = Vec::new();
            for e in errors {
                related.push(build_diagnostic(
                    e.without_snippet(),
                    Arc::clone(&src),
                    formatter,
                ));
            }

            ErrorDiagnostic {
                message: format!("validation failed for {} document(s)", errors.len()),
                src,
                labels: Vec::new(),
                related,
            }
        }

        #[cfg(feature = "validator")]
        Error::ValidatorError { errors, locations } => {
            let entries = collect_validator_entries(errors);
            let mut related = Vec::new();

            for (path, entry) in entries {
                related.push(build_validation_entry_diagnostic(
                    &src, &path, &entry, locations,
                ));
            }

            ErrorDiagnostic {
                message: format!(
                    "validation failed{}",
                    if related.len() == 1 {
                        ""
                    } else {
                        " (multiple errors)"
                    }
                ),
                src,
                labels: Vec::new(),
                related,
            }
        }

        #[cfg(feature = "validator")]
        Error::ValidatorErrors { errors } => {
            let mut related = Vec::new();
            for e in errors {
                related.push(build_diagnostic(
                    e.without_snippet(),
                    Arc::clone(&src),
                    formatter,
                ));
            }

            ErrorDiagnostic {
                message: format!("validation failed for {} document(s)", errors.len()),
                src,
                labels: Vec::new(),
                related,
            }
        }

        Error::WithSnippet { error, .. } => {
            build_diagnostic(error.without_snippet(), src, formatter)
        }

        Error::AliasError { msg: _, locations } => {
            let labels = build_alias_labels(
                &src,
                locations.reference_location,
                locations.defined_location,
            );

            ErrorDiagnostic {
                message: formatter.format_message(err).into_owned(),
                src,
                labels,
                related: Vec::new(),
            }
        }

        other => {
            let mut labels = Vec::new();
            if let Some(loc) = other.location()
                && let Some(span) = to_source_span(&src, &loc)
            {
                labels.push(LabeledSpan::new_with_span(
                    Some(formatter.format_message(other).into_owned()),
                    span,
                ));
            }

            ErrorDiagnostic {
                message: formatter.format_message(other).into_owned(),
                src,
                labels,
                related: Vec::new(),
            }
        }
    }
}

#[cfg(any(feature = "garde", feature = "validator"))]
fn build_validation_entry_diagnostic(
    src: &Arc<NamedSource<String>>,
    path_key: &PathKey,
    entry: &str,
    locations: &PathMap,
) -> ErrorDiagnostic {
    let original_leaf = path_key
        .leaf_string()
        .unwrap_or_else(|| "<root>".to_string());

    let (locs, resolved_leaf) = locations
        .search(path_key)
        .or_else(|| {
            // If the exact path isn't recorded (common when custom deserialization transforms the
            // YAML shape, e.g. sequence -> map keyed by derived IDs), fall back to the nearest
            // ancestor path that has a known location so we can still render a useful snippet.
            let mut p = path_key.parent();
            while let Some(cur) = p {
                if let Some(found) = locations.search(&cur) {
                    return Some(found);
                }
                p = cur.parent();
            }
            None
        })
        .unwrap_or((Locations::UNKNOWN, original_leaf));

    let ref_loc = locs.reference_location;
    let def_loc = locs.defined_location;

    let resolved_path = format_path_with_resolved_leaf(path_key, &resolved_leaf);
    let base_msg = format!("validation error: {entry} for `{resolved_path}`");

    let labels = build_validation_labels(src, ref_loc, def_loc);

    ErrorDiagnostic {
        message: base_msg,
        src: Arc::clone(src),
        labels,
        related: Vec::new(),
    }
}

#[cfg(any(feature = "garde", feature = "validator"))]
fn build_validation_labels(
    src: &Arc<NamedSource<String>>,
    ref_loc: Location,
    def_loc: Location,
) -> Vec<LabeledSpan> {
    let mut labels = Vec::new();

    // Primary label: use-site (alias/merge) if known, otherwise definition.
    if ref_loc != Location::UNKNOWN {
        if let Some(span) = to_source_span(src, &ref_loc) {
            labels.push(LabeledSpan::new_with_span(
                Some("the value is used here".to_owned()),
                span,
            ));
        }
    } else if def_loc != Location::UNKNOWN
        && let Some(span) = to_source_span(src, &def_loc)
    {
        labels.push(LabeledSpan::new_with_span(
            Some("defined here".to_owned()),
            span,
        ));
    }

    // Secondary label: definition site when it is distinct and known.
    if def_loc != Location::UNKNOWN
        && def_loc != ref_loc
        && let Some(span) = to_source_span(src, &def_loc)
    {
        labels.push(LabeledSpan::new_with_span(
            Some("defined here".to_owned()),
            span,
        ));
    }

    labels
}

/// Build labels for an alias error with both reference and defined locations.
fn build_alias_labels(
    src: &Arc<NamedSource<String>>,
    ref_loc: Location,
    def_loc: Location,
) -> Vec<LabeledSpan> {
    let mut labels = Vec::new();

    // Primary label: use-site (alias) if known, otherwise definition.
    if ref_loc != Location::UNKNOWN {
        if let Some(span) = to_source_span(src, &ref_loc) {
            labels.push(LabeledSpan::new_with_span(
                Some("the value is used here".to_owned()),
                span,
            ));
        }
    } else if def_loc != Location::UNKNOWN
        && let Some(span) = to_source_span(src, &def_loc)
    {
        labels.push(LabeledSpan::new_with_span(
            Some("defined here".to_owned()),
            span,
        ));
    }

    // Secondary label: definition site when it is distinct and known.
    if def_loc != Location::UNKNOWN
        && def_loc != ref_loc
        && let Some(span) = to_source_span(src, &def_loc)
    {
        labels.push(LabeledSpan::new_with_span(
            Some("anchor defined here".to_owned()),
            span,
        ));
    }

    labels
}

#[cfg(feature = "validator")]
fn collect_validator_entries(errors: &ValidationErrors) -> Vec<(PathKey, String)> {
    let mut out = Vec::new();
    let root = PathKey::empty();
    collect_validator_entries_inner(errors, &root, &mut out);
    out
}

#[cfg(feature = "validator")]
fn collect_validator_entries_inner(
    errors: &ValidationErrors,
    path: &PathKey,
    out: &mut Vec<(PathKey, String)>,
) {
    for (field, kind) in errors.errors() {
        let field_path = path.clone().join(field.as_ref());
        match kind {
            ValidationErrorsKind::Field(entries) => {
                for entry in entries {
                    out.push((field_path.clone(), entry.to_string()));
                }
            }
            ValidationErrorsKind::Struct(inner) => {
                collect_validator_entries_inner(inner, &field_path, out);
            }
            ValidationErrorsKind::List(list) => {
                for (idx, inner) in list {
                    let index_path = field_path.clone().join(*idx);
                    collect_validator_entries_inner(inner, &index_path, out);
                }
            }
        }
    }
}

fn to_source_span(src: &NamedSource<String>, location: &Location) -> Option<SourceSpan> {
    if *location == Location::UNKNOWN {
        return None;
    }

    let (byte_off, mut byte_len): (usize, usize) = if let (Some(off), Some(len)) = (
        location.span().byte_offset(),
        location.span().byte_len(),
    ) {
        (off as usize, len as usize)
    } else {
        // The parser provides character-based offsets/lengths, while miette expects
        // byte offsets into the UTF-8 source. Convert here using the available source.
        fn char_range_to_byte_range(
            s: &str,
            char_offset: usize,
            char_len: usize,
        ) -> Option<(usize, usize)> {
            // Start byte index for the given character offset
            let start_byte = if char_offset == 0 {
                0
            } else {
                s.char_indices().nth(char_offset).map(|(i, _)| i)?
            };

            // End in characters (exclusive)
            let end_char = char_offset.saturating_add(char_len);

            // If end past the last char, clamp to the end of the string in bytes
            let end_byte = match s.char_indices().nth(end_char) {
                Some((i, _)) => i,
                None => s.len(),
            };

            Some((start_byte, end_byte.saturating_sub(start_byte)))
        }

        let char_off = location.span().offset() as usize;
        let mut char_len = location.span().len() as usize;
        if char_len == 0 {
            char_len = 1;
        }

        char_range_to_byte_range(src.inner(), char_off, char_len)?
    };

    if byte_len == 0 {
        byte_len = 1;
    }

    // Clamp to the actual input, to avoid panics and invalid spans.
    let src_len = src.inner().len();
    if byte_off > src_len {
        return None;
    }
    byte_len = byte_len.min(src_len.saturating_sub(byte_off));

    Some(SourceSpan::new(byte_off.into(), byte_len))
}


#[cfg(all(test, feature = "miette"))]
mod tests {
    use super::*;

    #[test]
    fn basic_error_has_primary_label_span() {
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("input.yaml", "a: definitely\n".to_owned()));
        let err = Error::Message {
            msg: "invalid bool".to_owned(),
            location: Location {
                line: 1,
                column: 4,
                span: crate::Span { byte_info: (0, 0), 
                    offset: "a: definitely\n".find("definitely").unwrap() as crate::location::SpanIndex,
                    len: 3,
                },
            },
        };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        let labels: Vec<_> = diag.labels().unwrap().collect();
        assert_eq!(labels.len(), 1);
        assert_eq!(
            labels[0].inner().offset(),
            err.location().unwrap().span().offset() as usize
        );
    }

    #[test]
    fn non_ascii_prefix_char_offsets_convert_to_byte_offsets() {
        // Three Greek letters (non-ASCII, multi-byte in UTF-8) followed by ASCII "def".
        let yaml = "αβγdef\n";
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("input.yaml", yaml.to_owned()));

        let ascii_slice = "def";
        let byte_off = yaml.find(ascii_slice).expect("substring present");
        // Character-based offset for the start of "def"
        let char_off = yaml[..byte_off].chars().count();

        let err = Error::Message {
            msg: "invalid".to_owned(),
            location: Location {
                line: 1,
                // Column is 1-indexed and character-based; set consistently with the span
                column: (char_off as u32) + 1,
                span: crate::Span { byte_info: (0, 0), 
                    offset: char_off as crate::location::SpanIndex,
                    len: ascii_slice.len() as crate::location::SpanIndex,
                },
            },
        };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        let labels: Vec<_> = diag.labels().unwrap().collect();
        assert_eq!(labels.len(), 1);
        // miette expects byte offsets; ensure we converted from chars to bytes correctly
        assert_eq!(labels[0].inner().offset(), byte_off);
        assert_eq!(labels[0].inner().len(), ascii_slice.len());
    }

    #[test]
    fn non_ascii_token_itself_converts_correctly() {
        let yaml = "a: áé\n"; // value contains two non-ASCII letters
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("input.yaml", yaml.to_owned()));

        let value_chars = "áé";
        let start_byte = yaml.find(value_chars).unwrap();
        let start_char = yaml[..start_byte].chars().count();

        // Span over the two non-ASCII characters in character units
        let err = Error::Message {
            msg: "invalid".to_owned(),
            location: Location {
                line: 1,
                column: (start_char as u32) + 1,
                span: crate::Span { byte_info: (0, 0), 
                    offset: start_char as crate::location::SpanIndex,
                    len: value_chars.chars().count() as crate::location::SpanIndex,
                },
            },
        };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        let labels: Vec<_> = diag.labels().unwrap().collect();
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].inner().offset(), start_byte);
        assert_eq!(labels[0].inner().len(), value_chars.len()); // bytes
    }

    #[test]
    fn zero_length_span_highlights_one_char() {
        let yaml = "key: value\n";
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("input.yaml", yaml.to_owned()));
        let start_byte = yaml.find("value").unwrap();
        let start_char = yaml[..start_byte].chars().count();

        // Zero-length in characters
        let err = Error::Message {
            msg: "invalid".to_owned(),
            location: Location {
                line: 1,
                column: (start_char as u32) + 1,
                span: crate::Span { byte_info: (0, 0), 
                    offset: start_char as crate::location::SpanIndex,
                    len: 0,
                },
            },
        };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        let labels: Vec<_> = diag.labels().unwrap().collect();
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].inner().offset(), start_byte);
        assert_eq!(labels[0].inner().len(), 1);
    }

    #[test]
    fn span_past_end_is_clamped() {
        let yaml = "hello"; // 5 bytes, 5 chars
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("input.yaml", yaml.to_owned()));
        // Start at char 3 (the 'l'), but ask for a very long span
        let start_char = 3usize;
        let start_byte = yaml.char_indices().nth(start_char).map(|(i, _)| i).unwrap();

        let err = Error::Message {
            msg: "invalid".to_owned(),
            location: Location {
                line: 1,
                column: (start_char as u32) + 1,
                span: crate::Span { byte_info: (0, 0), 
                    offset: start_char as crate::location::SpanIndex,
                    len: 1000,
                },
            },
        };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        let labels: Vec<_> = diag.labels().unwrap().collect();
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].inner().offset(), start_byte);
        // Clamped to end of string
        assert_eq!(labels[0].inner().len(), yaml.len() - start_byte);
    }

    #[test]
    fn multiline_offset_after_newline() {
        let yaml = "α\nβ\nxyz\n"; // 1-char lines, then ascii line
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("input.yaml", yaml.to_owned()));
        let target = "xyz";
        let start_byte = yaml.find(target).unwrap();
        let start_char = yaml[..start_byte].chars().count();

        let err = Error::Message {
            msg: "invalid".to_owned(),
            location: Location {
                line: 3,
                column: 1,
                span: crate::Span { byte_info: (0, 0), 
                    offset: start_char as crate::location::SpanIndex,
                    len: target.chars().count() as crate::location::SpanIndex,
                },
            },
        };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        let labels: Vec<_> = diag.labels().unwrap().collect();
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].inner().offset(), start_byte);
        assert_eq!(labels[0].inner().len(), target.len());
    }

    #[cfg(feature = "validator")]
    #[test]
    fn validator_validation_error_has_use_and_definition_labels() {
        use validator::Validate;

        #[derive(Debug, Validate)]
        struct Cfg {
            #[validate(length(min = 2))]
            second_string: String,
        }

        let cfg = Cfg {
            second_string: "x".to_owned(),
        };
        let errors = cfg.validate().expect_err("validation error expected");

        // Simulate the alias case:
        // - use-site is at `secondString: *A`
        // - definition-site is at `firstString: &A "x"`
        let yaml = "\nfirstString: &A \"x\"\nsecondString: *A\n";
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("config.yaml", yaml.to_owned()));

        let use_offset = yaml.find("*A").unwrap();
        let def_offset = yaml.find("\"x\"").unwrap();

        let referenced_loc = Location {
            line: 3,
            column: 15,
            span: crate::Span { byte_info: (0, 0), 
                offset: use_offset as crate::location::SpanIndex,
                len: 2,
            },
        };
        let defined_loc = Location {
            line: 2,
            column: 18,
            span: crate::Span { byte_info: (0, 0), 
                offset: def_offset as crate::location::SpanIndex,
                len: 3,
            },
        };

        let mut locations = PathMap::new();

        // Validation path uses snake_case (`second_string`), but the YAML key is camelCase.
        // We insert the recorded YAML spelling so `PathMap::search()` resolves the leaf.
        let yaml_path = PathKey::empty().join("secondString");
        locations.insert(
            yaml_path,
            Locations {
                reference_location: referenced_loc,
                defined_location: defined_loc,
            },
        );

        let err = Error::ValidatorError { errors, locations };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        assert_eq!(diag.message, "validation failed");
        assert_eq!(diag.related.len(), 1);

        let labels = &diag.related[0].labels;
        assert_eq!(labels.len(), 2, "expected 2 labels, got: {labels:?}");

        let label_debug = format!("{labels:?}");
        assert!(
            label_debug.contains("the value is used here"),
            "expected use-site label, got: {label_debug}"
        );
        assert!(
            label_debug.contains("defined here"),
            "expected definition-site label, got: {label_debug}"
        );
    }

    #[cfg(feature = "garde")]
    #[test]
    fn garde_validation_error_has_use_and_definition_labels() {
        use garde::Validate;

        #[derive(Debug, Validate)]
        struct Cfg {
            #[garde(length(min = 2))]
            second_string: String,
        }

        let cfg = Cfg {
            second_string: "x".to_owned(),
        };
        let report = cfg.validate().expect_err("validation error expected");

        // Simulate the alias case:
        // - use-site is at `secondString: *A`
        // - definition-site is at `firstString: &A "x"`
        let yaml = "\nfirstString: &A \"x\"\nsecondString: *A\n";
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("config.yaml", yaml.to_owned()));

        let use_offset = yaml.find("*A").unwrap();
        let def_offset = yaml.find("\"x\"").unwrap();

        let referenced_loc = Location {
            line: 3,
            column: 15,
            span: crate::Span { byte_info: (0, 0), 
                offset: use_offset as crate::location::SpanIndex,
                len: 2,
            },
        };
        let defined_loc = Location {
            line: 2,
            column: 18,
            span: crate::Span { byte_info: (0, 0), 
                offset: def_offset as crate::location::SpanIndex,
                len: 3,
            },
        };

        let mut locations = PathMap::new();

        // Validation path uses snake_case (`second_string`), but the YAML key is camelCase.
        // We insert the recorded YAML spelling so `PathMap::search()` resolves the leaf.
        let yaml_path = PathKey::empty().join("secondString");
        locations.insert(
            yaml_path,
            Locations {
                reference_location: referenced_loc,
                defined_location: defined_loc,
            },
        );

        let err = Error::ValidationError { report, locations };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        assert_eq!(diag.message, "validation failed");
        assert_eq!(diag.related.len(), 1);

        let labels = &diag.related[0].labels;
        assert_eq!(labels.len(), 2, "expected 2 labels, got: {labels:?}");

        let label_debug = format!("{labels:?}");
        assert!(
            label_debug.contains("the value is used here"),
            "expected use-site label, got: {label_debug}"
        );
        assert!(
            label_debug.contains("defined here"),
            "expected definition-site label, got: {label_debug}"
        );
    }

    #[test]
    fn alias_error_has_use_and_definition_labels() {
        use crate::location::Locations;

        // Simulate an alias error where:
        // - use-site is at `value: *anchor`
        // - definition-site is at `anchor: &anchor "bad"`
        let yaml = "anchor: &a \"bad\"\nvalue: *a\n";
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("config.yaml", yaml.to_owned()));

        let use_offset = yaml.find("*a").unwrap();
        let def_offset = yaml.find("\"bad\"").unwrap();

        let referenced_loc = Location {
            line: 2,
            column: 8,
            span: crate::Span { byte_info: (0, 0), 
                offset: use_offset as crate::location::SpanIndex,
                len: 2,
            },
        };
        let defined_loc = Location {
            line: 1,
            column: 13,
            span: crate::Span { byte_info: (0, 0), 
                offset: def_offset as crate::location::SpanIndex,
                len: 5,
            },
        };

        let err = Error::AliasError {
            msg: "invalid value for alias".to_owned(),
            locations: Locations {
                reference_location: referenced_loc,
                defined_location: defined_loc,
            },
        };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        assert_eq!(diag.message, "invalid value for alias (defined at line 1, column 13)");

        let labels = &diag.labels;
        assert_eq!(labels.len(), 2, "expected 2 labels, got: {labels:?}");

        let label_debug = format!("{labels:?}");
        assert!(
            label_debug.contains("the value is used here"),
            "expected use-site label, got: {label_debug}"
        );
        assert!(
            label_debug.contains("anchor defined here"),
            "expected definition-site label, got: {label_debug}"
        );
    }

    #[test]
    fn alias_error_with_same_locations_has_single_label() {
        use crate::location::Locations;

        let yaml = "value: \"bad\"\n";
        let src: Arc<NamedSource<String>> =
            Arc::new(NamedSource::new("config.yaml", yaml.to_owned()));

        let offset = yaml.find("\"bad\"").unwrap();
        let loc = Location {
            line: 1,
            column: 8,
            span: crate::Span { byte_info: (0, 0), 
                offset: offset as crate::location::SpanIndex,
                len: 5,
            },
        };

        let err = Error::AliasError {
            msg: "invalid value".to_owned(),
            locations: Locations {
                reference_location: loc,
                defined_location: loc,
            },
        };

        let diag = build_diagnostic(&err, Arc::clone(&src), RenderOptions::default().formatter);
        assert_eq!(diag.message, "invalid value");

        // When both locations are the same, should only have one label
        let labels = &diag.labels;
        assert_eq!(labels.len(), 1, "expected 1 label when locations are same, got: {labels:?}");
    }
}