serde-saphyr 0.0.23

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
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
use crate::Location;
use crate::de_error::{Error, MessageFormatter, UserMessageFormatter};
use crate::localizer::{ExternalMessage, Localizer};

use std::borrow::Cow;

#[cfg(any(feature = "garde", feature = "validator"))]
use crate::{
    Locations, localizer::ExternalMessageSource, path_map::format_path_with_resolved_leaf,
};

/// Default developer-oriented message formatter.
///
/// This formatter at places produces recommendations on how to adjust settings and API
/// calls for the parsing to work, so normally should not be user-facing. Use UserMessageFormatter
/// for user-facing content, or implement custom MessageFormatter for full control over output.
#[derive(Debug, Default, Clone, Copy)]
pub struct DefaultMessageFormatter;

/// Alias for the default developer-oriented formatter.
pub type DeveloperMessageFormatter = DefaultMessageFormatter;

fn default_format_message<'a>(formatter: &dyn MessageFormatter, err: &'a Error) -> Cow<'a, str> {
    match err {
        Error::WithSnippet { error, .. } => default_format_message(formatter, error),
        Error::ExternalMessage {
            source,
            msg,
            code,
            params,
            ..
        } => {
            let l10n = formatter.localizer();
            l10n.override_external_message(ExternalMessage {
                source: *source,
                original: msg.as_str(),
                code: code.as_deref(),
                params,
            })
            .unwrap_or(Cow::Borrowed(msg.as_str()))
        }
        Error::Message { msg, .. }
        | Error::HookError { msg, .. }
        | Error::SerdeVariantId { msg, .. } => Cow::Borrowed(msg.as_str()),
        Error::UnresolvedProperty { name, .. } => Cow::Owned(format!("missing property `{name}`")),
        Error::InvalidPropertyName { name, .. } => Cow::Owned(format!("Invalid name: '{name}'")),
        Error::Eof { .. } => Cow::Borrowed("unexpected end of input"),
        Error::MultipleDocuments { hint, .. } => {
            Cow::Owned(format!("multiple YAML documents detected; {hint}"))
        }
        Error::Unexpected { expected, .. } => {
            Cow::Owned(format!("unexpected event: expected {expected}"))
        }
        Error::MergeValueNotMapOrSeqOfMaps { .. } => {
            Cow::Borrowed("YAML merge value must be mapping or sequence of mappings")
        }
        Error::InvalidBinaryBase64 { .. } => Cow::Borrowed("invalid !!binary base64"),
        Error::InvalidUtf8Input => Cow::Borrowed("input is not valid UTF-8"),
        Error::BinaryNotUtf8 { .. } => Cow::Borrowed(
            "!!binary scalar is not valid UTF-8 so cannot be stored into string. \
                 If you just use !!binary for documentation/annotation, set ignore_binary_tag_for_string in Options",
        ),
        Error::TaggedScalarCannotDeserializeIntoString { .. } => {
            Cow::Borrowed("cannot deserialize tagged scalar into string")
        }
        Error::UnexpectedSequenceEnd { .. } => Cow::Borrowed("unexpected sequence end"),
        Error::UnexpectedMappingEnd { .. } => Cow::Borrowed("unexpected mapping end"),
        Error::InvalidBooleanStrict { .. } => {
            Cow::Borrowed("invalid boolean (strict mode expects true/false)")
        }
        Error::InvalidCharNull { .. } => {
            Cow::Borrowed("invalid char: cannot deserialize null; use Option<char>")
        }
        Error::InvalidCharNotSingleScalar { .. } => {
            Cow::Borrowed("invalid char: expected a single Unicode scalar value")
        }
        Error::NullIntoString { .. } => {
            Cow::Borrowed("cannot deserialize null into string; use Option<String>")
        }
        Error::BytesNotSupportedMissingBinaryTag { .. } => {
            Cow::Borrowed("bytes not supported (missing !!binary tag)")
        }
        Error::UnexpectedValueForUnit { .. } => Cow::Borrowed("unexpected value for unit"),
        Error::ExpectedEmptyMappingForUnitStruct { .. } => {
            Cow::Borrowed("expected empty mapping for unit struct")
        }
        Error::UnexpectedContainerEndWhileSkippingNode { .. } => {
            Cow::Borrowed("unexpected container end while skipping node")
        }
        Error::InternalSeedReusedForMapKey { .. } => {
            Cow::Borrowed("internal error: seed reused for map key")
        }
        Error::ValueRequestedBeforeKey { .. } => Cow::Borrowed("value requested before key"),
        Error::ExpectedStringKeyForExternallyTaggedEnum { .. } => {
            Cow::Borrowed("expected string key for externally tagged enum")
        }
        Error::ExternallyTaggedEnumExpectedScalarOrMapping { .. } => {
            Cow::Borrowed("externally tagged enum expected scalar or mapping")
        }
        Error::UnexpectedValueForUnitEnumVariant { .. } => {
            Cow::Borrowed("unexpected value for unit enum variant")
        }
        Error::AliasReplayCounterOverflow { .. } => Cow::Borrowed("alias replay counter overflow"),
        Error::AliasReplayLimitExceeded {
            total_replayed_events,
            max_total_replayed_events,
            ..
        } => Cow::Owned(format!(
            "alias replay limit exceeded: total_replayed_events={total_replayed_events} > {max_total_replayed_events}"
        )),
        Error::AliasExpansionLimitExceeded {
            anchor_id,
            expansions,
            max_expansions_per_anchor,
            ..
        } => Cow::Owned(format!(
            "alias expansion limit exceeded for anchor id {anchor_id}: {expansions} > {max_expansions_per_anchor}"
        )),
        Error::AliasReplayStackDepthExceeded {
            depth, max_depth, ..
        } => Cow::Owned(format!(
            "alias replay stack depth exceeded: depth={depth} > {max_depth}"
        )),
        Error::FoldedBlockScalarMustIndentContent { .. } => {
            Cow::Borrowed("folded block scalars must indent their content")
        }
        Error::InternalDepthUnderflow { .. } => Cow::Borrowed("internal depth underflow"),
        Error::InternalRecursionStackEmpty { .. } => {
            Cow::Borrowed("internal recursion stack empty")
        }
        Error::RecursiveReferencesRequireWeakTypes { .. } => {
            Cow::Borrowed("recursive references require weak recursion types")
        }
        Error::InvalidScalar { ty, .. } => Cow::Owned(format!("invalid {ty}")),
        Error::SerdeInvalidType {
            unexpected,
            expected,
            ..
        } => Cow::Owned(format!("invalid type: {unexpected}, expected {expected}")),
        Error::SerdeInvalidValue {
            unexpected,
            expected,
            ..
        } => Cow::Owned(format!("invalid value: {unexpected}, expected {expected}")),
        Error::SerdeUnknownVariant {
            variant, expected, ..
        } => Cow::Owned(format!(
            "unknown variant `{variant}`, expected one of {}",
            expected.join(", ")
        )),
        Error::SerdeUnknownField {
            field, expected, ..
        } => Cow::Owned(format!(
            "unknown field `{field}`, expected one of {}",
            expected.join(", ")
        )),
        Error::SerdeMissingField { field, .. } => Cow::Owned(format!("missing field `{field}`")),
        Error::UnexpectedContainerEndWhileReadingKeyNode { .. } => {
            Cow::Borrowed("unexpected container end while reading key")
        }
        Error::DuplicateMappingKey { key, .. } => match key {
            Some(k) => Cow::Owned(format!(
                "duplicate mapping key: {k}, set DuplicateKeyPolicy in Options if acceptable"
            )),
            None => Cow::Borrowed(
                "duplicate mapping key, set DuplicateKeyPolicy in Options if acceptable",
            ),
        },
        Error::TaggedEnumMismatch { tagged, target, .. } => Cow::Owned(format!(
            "tagged enum `{tagged}` does not match target enum `{target}`",
        )),
        Error::ExpectedMappingEndAfterEnumVariantValue { .. } => {
            Cow::Borrowed("expected end of mapping after enum variant value")
        }
        Error::ContainerEndMismatch { .. } => Cow::Borrowed("list or mapping end with no start"),
        Error::UnknownAnchor { .. } => Cow::Borrowed("alias references unknown anchor"),
        Error::CyclicInclude { id, stack, .. } => {
            let mut full_msg = format!("cyclic include detected: {id}");
            if !stack.is_empty() {
                full_msg.push_str("\nwhile processing include from ");
                full_msg.push_str(&stack.join(" -> "));
            }
            Cow::Owned(full_msg)
        }
        Error::UnsupportedIncludeForm { .. } => {
            Cow::Borrowed("!include currently only supports the scalar form: !include <path>")
        }
        Error::ResolverError {
            target,
            error,
            stack,
            ..
        } => {
            let mut full_msg = format!("failed to resolve include {target:?}");
            if !stack.is_empty() {
                full_msg.push_str("\nwhile processing include from ");
                full_msg.push_str(&stack.join(" -> "));
            }
            full_msg.push('\n');
            let msg = match error {
                crate::input_source::IncludeResolveError::Io(e) => e.to_string(),
                crate::input_source::IncludeResolveError::Message(m) => m.clone(),
                crate::input_source::IncludeResolveError::SizeLimitExceeded(size, limit) => {
                    format!("include size {size} bytes exceeds remaining size limit {limit} bytes")
                }
                crate::input_source::IncludeResolveError::FileInclude(problem) => {
                    match &**problem {
                        crate::input_source::ResolveProblem::ResolveFailed {
                            spec,
                            base_dir,
                            err,
                        } => {
                            format!(
                                "failed to resolve include '{}' from '{}': {}",
                                spec, base_dir, err
                            )
                        }
                        crate::input_source::ResolveProblem::TargetNotRegularFile { target } => {
                            format!("include target '{}' is not a regular file", target)
                        }
                        crate::input_source::ResolveProblem::TargetIsRootFile { spec } => {
                            format!(
                                "include target '{}' resolves to the configured root file itself",
                                spec
                            )
                        }
                        crate::input_source::ResolveProblem::ParentIdNotAbsoluteCanonical {
                            parent_id,
                        } => {
                            format!(
                                "SafeFileResolver expected parent include id to be an absolute canonical path, got '{}'",
                                parent_id
                            )
                        }
                        crate::input_source::ResolveProblem::ParentResolveFailed {
                            parent_id,
                            from_name,
                            err,
                        } => {
                            format!(
                                "failed to resolve parent include source '{}' (from '{}'): {}",
                                parent_id, from_name, err
                            )
                        }
                        crate::input_source::ResolveProblem::ParentNotRegularFile { parent } => {
                            format!("include parent '{}' is not a regular file", parent)
                        }
                        crate::input_source::ResolveProblem::ParentHasNoDirectory { parent } => {
                            format!(
                                "include parent '{}' does not have a parent directory",
                                parent
                            )
                        }
                        crate::input_source::ResolveProblem::ResolvesOutsideRoot { spec, root } => {
                            format!(
                                "include '{}' resolves outside the configured root '{}'",
                                spec, root
                            )
                        }
                        crate::input_source::ResolveProblem::TraversesSymlink { spec } => {
                            format!(
                                "include '{}' traverses a symlink, which is disabled by policy",
                                spec
                            )
                        }
                        crate::input_source::ResolveProblem::AbsolutePathNotAllowed { spec } => {
                            format!("absolute include paths are not allowed: {}", spec)
                        }
                        crate::input_source::ResolveProblem::EmptyPath => {
                            "include path must not be empty".to_string()
                        }
                        crate::input_source::ResolveProblem::InvalidExtension { spec } => {
                            format!(
                                "include target '{}' does not have a valid YAML extension (.yml or .yaml)",
                                spec
                            )
                        }
                        crate::input_source::ResolveProblem::HiddenFile { spec } => {
                            format!(
                                "include target '{}' is a hidden file, which is not allowed",
                                spec
                            )
                        }
                        crate::input_source::ResolveProblem::EmptyFragment => {
                            "include fragment must not be empty".to_string()
                        }
                        crate::input_source::ResolveProblem::FragmentContainsHash { spec } => {
                            format!("include fragment must not contain '#': {}", spec)
                        }
                    }
                }
            };
            full_msg.push_str(&msg);
            Cow::Owned(full_msg)
        }
        Error::Budget { breach, .. } => Cow::Owned(format!("budget breached: {breach:?}")),
        Error::QuotingRequired { value, .. } => {
            Cow::Owned(format!("The string value [{value}] must be quoted"))
        }
        Error::CannotBorrowTransformedString { reason, .. } => Cow::Owned(format!(
            "input does not contain value verbatim so cannot deserialize into &str ({reason}); use String or Cow<str> instead",
        )),
        Error::IndentationError {
            required, actual, ..
        } => Cow::Owned(format!(
            "indentation error: expected {required}, found {actual} spaces"
        )),
        Error::IOError { cause } => Cow::Owned(format!("IO error: {cause}")),
        Error::AliasError { msg, locations } => {
            let l10n = formatter.localizer();
            let ref_loc = locations.reference_location;
            let def_loc = locations.defined_location;
            match (ref_loc, def_loc) {
                (Location::UNKNOWN, Location::UNKNOWN) => Cow::Borrowed(msg.as_str()),
                (r, d) if r != Location::UNKNOWN && (d == Location::UNKNOWN || d == r) => {
                    Cow::Borrowed(msg.as_str())
                }
                (_r, d) => Cow::Owned(format!("{msg}{}", l10n.alias_defined_at(d))),
            }
        }

        #[cfg(feature = "garde")]
        Error::ValidationError { issues, locations } => {
            let l10n = formatter.localizer();

            let mut lines = Vec::with_capacity(issues.len());
            for issue in issues {
                let entry = issue.display_entry_overridden(l10n, ExternalMessageSource::Garde);
                let path_key = &issue.path;
                let original_leaf = path_key
                    .leaf_string()
                    .unwrap_or_else(|| l10n.root_path_label().into_owned());

                let (locs, resolved_leaf) = locations
                    .search(path_key)
                    .unwrap_or((Locations::UNKNOWN, original_leaf));

                let loc = if locs.reference_location != Location::UNKNOWN {
                    locs.reference_location
                } else {
                    locs.defined_location
                };

                let resolved_path = format_path_with_resolved_leaf(path_key, &resolved_leaf);

                lines.push(l10n.validation_issue_line(
                    &resolved_path,
                    &entry,
                    (loc != Location::UNKNOWN).then_some(loc),
                ));
            }
            Cow::Owned(l10n.join_validation_issues(&lines))
        }
        #[cfg(feature = "garde")]
        Error::ValidationErrors { errors } => Cow::Owned(format!(
            "validation failed for {} document(s)",
            errors.len()
        )),
        #[cfg(feature = "validator")]
        Error::ValidatorError { issues, locations } => {
            let l10n = formatter.localizer();

            let mut lines = Vec::with_capacity(issues.len());
            for issue in issues {
                let entry = issue.display_entry_overridden(l10n, ExternalMessageSource::Validator);
                let path_key = &issue.path;
                let original_leaf = path_key
                    .leaf_string()
                    .unwrap_or_else(|| l10n.root_path_label().into_owned());

                let (locs, resolved_leaf) = locations
                    .search(path_key)
                    .unwrap_or((Locations::UNKNOWN, original_leaf));

                let loc = if locs.reference_location != Location::UNKNOWN {
                    locs.reference_location
                } else {
                    locs.defined_location
                };

                let resolved_path = format_path_with_resolved_leaf(path_key, &resolved_leaf);

                lines.push(l10n.validation_issue_line(
                    &resolved_path,
                    &entry,
                    (loc != Location::UNKNOWN).then_some(loc),
                ));
            }
            Cow::Owned(l10n.join_validation_issues(&lines))
        }
        #[cfg(feature = "validator")]
        Error::ValidatorErrors { errors } => Cow::Owned(format!(
            "validation failed for {} document(s)",
            errors.len()
        )),
    }
}

impl MessageFormatter for DefaultMessageFormatter {
    fn format_message<'a>(&self, err: &'a Error) -> Cow<'a, str> {
        default_format_message(self, err)
    }
}

pub struct DefaultMessageFormatterWithLocalizer<'a> {
    localizer: &'a dyn Localizer,
}

impl MessageFormatter for DefaultMessageFormatterWithLocalizer<'_> {
    fn localizer(&self) -> &dyn Localizer {
        self.localizer
    }

    fn format_message<'a>(&self, err: &'a Error) -> Cow<'a, str> {
        default_format_message(self, err)
    }
}

impl DefaultMessageFormatter {
    /// Return a formatter that uses a custom [`Localizer`].
    ///
    /// This allows reusing the built-in developer-oriented messages while customizing
    /// wording that is produced outside `format_message` (location suffixes, validation
    /// issue composition, snippet labels, etc.).
    pub fn with_localizer<'a>(
        &self,
        localizer: &'a dyn Localizer,
    ) -> DefaultMessageFormatterWithLocalizer<'a> {
        DefaultMessageFormatterWithLocalizer { localizer }
    }
}

fn user_format_message<'a>(formatter: &dyn MessageFormatter, err: &'a Error) -> Cow<'a, str> {
    if let Error::WithSnippet { error, .. } = err {
        return user_format_message(formatter, error);
    }

    match err {
        // handled by early return above
        Error::WithSnippet { .. } => unreachable!(),

        Error::Eof { .. } => Cow::Borrowed("unexpected end of file"),
        Error::MultipleDocuments { .. } => {
            Cow::Borrowed("only single YAML document expected but multiple found")
        }
        Error::InvalidUtf8Input => Cow::Borrowed("YAML parser input is not valid UTF-8"),
        Error::BinaryNotUtf8 { .. } => {
            Cow::Borrowed("!!binary scalar is not valid UTF-8 so cannot be stored into string.")
        }
        Error::InvalidBooleanStrict { .. } => {
            Cow::Borrowed("invalid boolean (true or false expected)")
        }
        Error::NullIntoString { .. } | Error::InvalidCharNull { .. } => {
            Cow::Borrowed("null is not allowed here")
        }
        Error::InvalidCharNotSingleScalar { .. } => {
            Cow::Borrowed("only single character allowed here")
        }
        Error::BytesNotSupportedMissingBinaryTag { .. } => Cow::Borrowed("missing !!binary tag"),
        Error::ExpectedEmptyMappingForUnitStruct { .. } => {
            Cow::Borrowed("expected empty mapping here")
        }
        Error::UnexpectedContainerEndWhileSkippingNode { .. } => {
            Cow::Borrowed("unexpected container end")
        }
        Error::AliasReplayCounterOverflow { .. } => {
            Cow::Borrowed("YAML document too large or too complex")
        }
        Error::AliasReplayLimitExceeded {
            total_replayed_events,
            max_total_replayed_events,
            ..
        } => Cow::Owned(format!(
            "YAML document too large or too complex: total_replayed_events={total_replayed_events} > {max_total_replayed_events}"
        )),
        Error::AliasExpansionLimitExceeded {
            anchor_id,
            expansions,
            max_expansions_per_anchor,
            ..
        } => Cow::Owned(format!(
            "YAML document too large or too complex: anchor id {anchor_id}: {expansions} > {max_expansions_per_anchor}"
        )),
        Error::AliasReplayStackDepthExceeded {
            depth, max_depth, ..
        } => Cow::Owned(format!(
            "YAML document too large or too complex: depth={depth} > {max_depth}"
        )),
        Error::UnknownAnchor { .. } => Cow::Borrowed("reference to unknown value"),
        Error::CyclicInclude { .. } => Cow::Borrowed("cyclic include detected"),
        Error::UnsupportedIncludeForm { .. } => {
            Cow::Borrowed("!include currently only supports the scalar form: !include <path>")
        }
        Error::ResolverError { .. } => Cow::Borrowed("failed to resolve include"),
        Error::RecursiveReferencesRequireWeakTypes { .. } => {
            Cow::Borrowed("Recursive reference not allowed here")
        }
        Error::DuplicateMappingKey { key, .. } => match key {
            Some(k) => Cow::Owned(format!("duplicate mapping key: {k} not allowed here")),
            None => Cow::Borrowed("duplicate mapping key not allowed here"),
        },
        Error::QuotingRequired { .. } => Cow::Borrowed("value requires quoting"),
        Error::Budget { breach, .. } => Cow::Owned(format!(
            "YAML document too large or too complex: limits breached: {breach:?}"
        )),
        Error::CannotBorrowTransformedString { .. } => {
            Cow::Borrowed("Only single string with no escape sequences is allowed here")
        }
        Error::IndentationError {
            required, actual, ..
        } => Cow::Owned(format!(
            "incorrect indentation: expected {required}, found {actual} spaces"
        )),

        // All cases when the standard message is good enough.
        _ => default_format_message(formatter, err),
    }
}

impl MessageFormatter for UserMessageFormatter {
    fn format_message<'a>(&self, err: &'a Error) -> Cow<'a, str> {
        user_format_message(self, err)
    }
}

pub struct UserMessageFormatterWithLocalizer<'a> {
    localizer: &'a dyn Localizer,
}

impl MessageFormatter for UserMessageFormatterWithLocalizer<'_> {
    fn localizer(&self) -> &dyn Localizer {
        self.localizer
    }

    fn format_message<'a>(&self, err: &'a Error) -> Cow<'a, str> {
        user_format_message(self, err)
    }
}

impl UserMessageFormatter {
    /// Return a formatter that uses a custom [`Localizer`].
    ///
    /// This allows reusing the built-in user-facing messages while customizing wording
    /// that is produced outside `format_message` (location suffixes, validation issue
    /// composition, snippet labels, etc.).
    pub fn with_localizer<'a>(
        &self,
        localizer: &'a dyn Localizer,
    ) -> UserMessageFormatterWithLocalizer<'a> {
        UserMessageFormatterWithLocalizer { localizer }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Location;
    use crate::de_error::{Error, MessageFormatter, TransformReason};
    use crate::location::Locations;

    fn loc() -> Location {
        Location::UNKNOWN
    }

    // -----------------------------------------------------------------------
    // DefaultMessageFormatter – uncovered arms
    // -----------------------------------------------------------------------

    #[test]
    fn default_with_snippet_delegates() {
        let formatter = DefaultMessageFormatter;
        let inner = Error::Eof { location: loc() };
        let err = Error::WithSnippet {
            regions: vec![],
            crop_radius: 3,
            error: Box::new(inner),
        };
        assert_eq!(formatter.format_message(&err), "unexpected end of input");
    }

    #[test]
    fn default_hook_error() {
        let formatter = DefaultMessageFormatter;
        let err = Error::HookError {
            msg: "hook msg".to_owned(),
            location: loc(),
        };
        assert_eq!(formatter.format_message(&err), "hook msg");
    }

    #[test]
    fn default_serde_variant_id() {
        let formatter = DefaultMessageFormatter;
        let err = Error::SerdeVariantId {
            msg: "variant id msg".to_owned(),
            location: loc(),
        };
        assert_eq!(formatter.format_message(&err), "variant id msg");
    }

    #[test]
    fn default_invalid_binary_base64() {
        let formatter = DefaultMessageFormatter;
        let err = Error::InvalidBinaryBase64 { location: loc() };
        assert_eq!(formatter.format_message(&err), "invalid !!binary base64");
    }

    #[test]
    fn default_unexpected_sequence_end() {
        let formatter = DefaultMessageFormatter;
        let err = Error::UnexpectedSequenceEnd { location: loc() };
        assert_eq!(formatter.format_message(&err), "unexpected sequence end");
    }

    #[test]
    fn default_unexpected_mapping_end() {
        let formatter = DefaultMessageFormatter;
        let err = Error::UnexpectedMappingEnd { location: loc() };
        assert_eq!(formatter.format_message(&err), "unexpected mapping end");
    }

    #[test]
    fn default_unexpected_container_end_while_skipping() {
        let formatter = DefaultMessageFormatter;
        let err = Error::UnexpectedContainerEndWhileSkippingNode { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "unexpected container end while skipping node"
        );
    }

    #[test]
    fn default_internal_seed_reused() {
        let formatter = DefaultMessageFormatter;
        let err = Error::InternalSeedReusedForMapKey { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "internal error: seed reused for map key"
        );
    }

    #[test]
    fn default_value_requested_before_key() {
        let formatter = DefaultMessageFormatter;
        let err = Error::ValueRequestedBeforeKey { location: loc() };
        assert_eq!(formatter.format_message(&err), "value requested before key");
    }

    #[test]
    fn default_alias_replay_counter_overflow() {
        let formatter = DefaultMessageFormatter;
        let err = Error::AliasReplayCounterOverflow { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "alias replay counter overflow"
        );
    }

    #[test]
    fn default_folded_block_scalar() {
        let formatter = DefaultMessageFormatter;
        let err = Error::FoldedBlockScalarMustIndentContent { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "folded block scalars must indent their content"
        );
    }

    #[test]
    fn default_internal_depth_underflow() {
        let formatter = DefaultMessageFormatter;
        let err = Error::InternalDepthUnderflow { location: loc() };
        assert_eq!(formatter.format_message(&err), "internal depth underflow");
    }

    #[test]
    fn default_internal_recursion_stack_empty() {
        let formatter = DefaultMessageFormatter;
        let err = Error::InternalRecursionStackEmpty { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "internal recursion stack empty"
        );
    }

    #[test]
    fn default_recursive_references_require_weak_types() {
        let formatter = DefaultMessageFormatter;
        let err = Error::RecursiveReferencesRequireWeakTypes { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "recursive references require weak recursion types"
        );
    }

    #[test]
    fn default_serde_invalid_value() {
        let formatter = DefaultMessageFormatter;
        let err = Error::SerdeInvalidValue {
            unexpected: "null".to_owned(),
            expected: "string".to_owned(),
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("invalid value"), "got: {msg}");
        assert!(msg.contains("null"), "got: {msg}");
        assert!(msg.contains("string"), "got: {msg}");
    }

    #[test]
    fn default_serde_unknown_variant() {
        let formatter = DefaultMessageFormatter;
        let err = Error::SerdeUnknownVariant {
            variant: "foo".to_owned(),
            expected: vec!["bar", "baz"],
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("unknown variant"), "got: {msg}");
        assert!(msg.contains("foo"), "got: {msg}");
    }

    #[test]
    fn default_serde_unknown_field() {
        let formatter = DefaultMessageFormatter;
        let err = Error::SerdeUnknownField {
            field: "xyz".to_owned(),
            expected: vec!["a", "b"],
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("unknown field"), "got: {msg}");
        assert!(msg.contains("xyz"), "got: {msg}");
    }

    #[test]
    fn default_unexpected_container_end_while_reading_key() {
        let formatter = DefaultMessageFormatter;
        let err = Error::UnexpectedContainerEndWhileReadingKeyNode { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "unexpected container end while reading key"
        );
    }

    #[test]
    fn default_expected_mapping_end_after_enum_variant() {
        let formatter = DefaultMessageFormatter;
        let err = Error::ExpectedMappingEndAfterEnumVariantValue { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "expected end of mapping after enum variant value"
        );
    }

    #[test]
    fn default_container_end_mismatch() {
        let formatter = DefaultMessageFormatter;
        let err = Error::ContainerEndMismatch { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "list or mapping end with no start"
        );
    }

    #[test]
    fn default_io_error() {
        let formatter = DefaultMessageFormatter;
        let err = Error::IOError {
            cause: std::io::Error::other("disk full"),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("IO error"), "got: {msg}");
        assert!(msg.contains("disk full"), "got: {msg}");
    }

    #[test]
    fn default_unresolved_property() {
        let formatter = DefaultMessageFormatter;
        let err = Error::UnresolvedProperty {
            name: "MISSING".to_owned(),
            location: loc(),
        };
        assert_eq!(formatter.format_message(&err), "missing property `MISSING`");
    }

    #[test]
    fn default_invalid_property_name() {
        let formatter = DefaultMessageFormatter;
        let err = Error::InvalidPropertyName {
            name: "${ab-cd}".to_owned(),
            location: loc(),
        };
        assert_eq!(formatter.format_message(&err), "Invalid name: '${ab-cd}'");
    }

    #[test]
    fn default_alias_error_both_unknown() {
        let formatter = DefaultMessageFormatter;
        let err = Error::AliasError {
            msg: "alias msg".to_owned(),
            locations: Locations::UNKNOWN,
        };
        assert_eq!(formatter.format_message(&err), "alias msg");
    }

    #[test]
    fn default_alias_error_ref_known_def_unknown() {
        let formatter = DefaultMessageFormatter;
        let ref_loc = Location::new(1, 0);
        let err = Error::AliasError {
            msg: "alias msg".to_owned(),
            locations: Locations {
                reference_location: ref_loc,
                defined_location: Location::UNKNOWN,
            },
        };
        // r != UNKNOWN and d == UNKNOWN → returns msg as-is
        assert_eq!(formatter.format_message(&err), "alias msg");
    }

    #[test]
    fn default_alias_error_both_known_different() {
        let formatter = DefaultMessageFormatter;
        let ref_loc = Location::new(1, 0);
        let def_loc = Location::new(5, 0);
        let err = Error::AliasError {
            msg: "alias msg".to_owned(),
            locations: Locations {
                reference_location: ref_loc,
                defined_location: def_loc,
            },
        };
        // _r != UNKNOWN, d != UNKNOWN, d != r → appends defined-at suffix
        let msg = formatter.format_message(&err);
        assert!(msg.starts_with("alias msg"), "got: {msg}");
    }

    // -----------------------------------------------------------------------
    // UserMessageFormatter – all arms
    // -----------------------------------------------------------------------

    #[test]
    fn user_with_snippet_delegates() {
        let formatter = UserMessageFormatter;
        let inner = Error::Eof { location: loc() };
        let err = Error::WithSnippet {
            regions: vec![],
            crop_radius: 3,
            error: Box::new(inner),
        };
        assert_eq!(formatter.format_message(&err), "unexpected end of file");
    }

    #[test]
    fn user_eof() {
        let formatter = UserMessageFormatter;
        let err = Error::Eof { location: loc() };
        assert_eq!(formatter.format_message(&err), "unexpected end of file");
    }

    #[test]
    fn user_multiple_documents() {
        let formatter = UserMessageFormatter;
        let err = Error::MultipleDocuments {
            hint: "use from_str_multidoc",
            location: loc(),
        };
        assert_eq!(
            formatter.format_message(&err),
            "only single YAML document expected but multiple found"
        );
    }

    #[test]
    fn user_invalid_utf8_input() {
        let formatter = UserMessageFormatter;
        let err = Error::InvalidUtf8Input;
        assert_eq!(
            formatter.format_message(&err),
            "YAML parser input is not valid UTF-8"
        );
    }

    #[test]
    fn user_binary_not_utf8() {
        let formatter = UserMessageFormatter;
        let err = Error::BinaryNotUtf8 { location: loc() };
        assert!(formatter.format_message(&err).contains("!!binary"));
    }

    #[test]
    fn user_invalid_boolean_strict() {
        let formatter = UserMessageFormatter;
        let err = Error::InvalidBooleanStrict { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "invalid boolean (true or false expected)"
        );
    }

    #[test]
    fn user_null_into_string() {
        let formatter = UserMessageFormatter;
        let err = Error::NullIntoString { location: loc() };
        assert_eq!(formatter.format_message(&err), "null is not allowed here");
    }

    #[test]
    fn user_invalid_char_null() {
        let formatter = UserMessageFormatter;
        let err = Error::InvalidCharNull { location: loc() };
        assert_eq!(formatter.format_message(&err), "null is not allowed here");
    }

    #[test]
    fn user_invalid_char_not_single_scalar() {
        let formatter = UserMessageFormatter;
        let err = Error::InvalidCharNotSingleScalar { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "only single character allowed here"
        );
    }

    #[test]
    fn user_bytes_not_supported_missing_binary_tag() {
        let formatter = UserMessageFormatter;
        let err = Error::BytesNotSupportedMissingBinaryTag { location: loc() };
        assert_eq!(formatter.format_message(&err), "missing !!binary tag");
    }

    #[test]
    fn user_expected_empty_mapping_for_unit_struct() {
        let formatter = UserMessageFormatter;
        let err = Error::ExpectedEmptyMappingForUnitStruct { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "expected empty mapping here"
        );
    }

    #[test]
    fn user_unexpected_container_end_while_skipping() {
        let formatter = UserMessageFormatter;
        let err = Error::UnexpectedContainerEndWhileSkippingNode { location: loc() };
        assert_eq!(formatter.format_message(&err), "unexpected container end");
    }

    #[test]
    fn user_alias_replay_counter_overflow() {
        let formatter = UserMessageFormatter;
        let err = Error::AliasReplayCounterOverflow { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "YAML document too large or too complex"
        );
    }

    #[test]
    fn user_alias_replay_limit_exceeded() {
        let formatter = UserMessageFormatter;
        let err = Error::AliasReplayLimitExceeded {
            total_replayed_events: 1000,
            max_total_replayed_events: 500,
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("too large or too complex"), "got: {msg}");
        assert!(msg.contains("1000"), "got: {msg}");
    }

    #[test]
    fn user_alias_expansion_limit_exceeded() {
        let formatter = UserMessageFormatter;
        let err = Error::AliasExpansionLimitExceeded {
            anchor_id: 7,
            expansions: 200,
            max_expansions_per_anchor: 100,
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("too large or too complex"), "got: {msg}");
        assert!(msg.contains("7"), "got: {msg}");
    }

    #[test]
    fn user_alias_replay_stack_depth_exceeded() {
        let formatter = UserMessageFormatter;
        let err = Error::AliasReplayStackDepthExceeded {
            depth: 50,
            max_depth: 20,
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("too large or too complex"), "got: {msg}");
        assert!(msg.contains("50"), "got: {msg}");
    }

    #[test]
    fn user_unknown_anchor() {
        let formatter = UserMessageFormatter;
        let err = Error::UnknownAnchor { location: loc() };
        assert_eq!(formatter.format_message(&err), "reference to unknown value");
    }

    #[test]
    fn user_recursive_references_require_weak_types() {
        let formatter = UserMessageFormatter;
        let err = Error::RecursiveReferencesRequireWeakTypes { location: loc() };
        assert_eq!(
            formatter.format_message(&err),
            "Recursive reference not allowed here"
        );
    }

    #[test]
    fn user_duplicate_mapping_key_with_key() {
        let formatter = UserMessageFormatter;
        let err = Error::DuplicateMappingKey {
            key: Some("mykey".to_owned()),
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("mykey"), "got: {msg}");
        assert!(msg.contains("duplicate"), "got: {msg}");
    }

    #[test]
    fn user_duplicate_mapping_key_without_key() {
        let formatter = UserMessageFormatter;
        let err = Error::DuplicateMappingKey {
            key: None,
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("duplicate"), "got: {msg}");
    }

    #[test]
    fn user_quoting_required() {
        let formatter = UserMessageFormatter;
        let err = Error::QuotingRequired {
            value: "yes".to_owned(),
            location: loc(),
        };
        assert_eq!(formatter.format_message(&err), "value requires quoting");
    }

    #[test]
    fn user_budget() {
        use crate::budget::BudgetBreach;
        let formatter = UserMessageFormatter;
        let err = Error::Budget {
            breach: BudgetBreach::Events { events: 9999 },
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("too large or too complex"), "got: {msg}");
    }

    #[test]
    fn user_cannot_borrow_transformed_string() {
        let formatter = UserMessageFormatter;
        let err = Error::CannotBorrowTransformedString {
            reason: TransformReason::EscapeSequence,
            location: loc(),
        };
        assert_eq!(
            formatter.format_message(&err),
            "Only single string with no escape sequences is allowed here"
        );
    }

    #[test]
    fn user_falls_through_to_default_for_unhandled() {
        // SerdeInvalidType is not explicitly handled by user_format_message → falls through to default
        let formatter = UserMessageFormatter;
        let err = Error::SerdeInvalidType {
            unexpected: "seq".to_owned(),
            expected: "map".to_owned(),
            location: loc(),
        };
        let msg = formatter.format_message(&err);
        assert!(msg.contains("invalid type"), "got: {msg}");
    }

    // -----------------------------------------------------------------------
    // UserMessageFormatterWithLocalizer
    // -----------------------------------------------------------------------

    #[test]
    fn user_with_localizer_delegates() {
        use crate::localizer::DefaultEnglishLocalizer;
        let localizer = DefaultEnglishLocalizer;
        let formatter = UserMessageFormatter.with_localizer(&localizer);
        let err = Error::Eof { location: loc() };
        assert_eq!(formatter.format_message(&err), "unexpected end of file");
    }

    // -----------------------------------------------------------------------
    // DefaultMessageFormatterWithLocalizer
    // -----------------------------------------------------------------------

    #[test]
    fn default_with_localizer_delegates() {
        use crate::localizer::DefaultEnglishLocalizer;
        let localizer = DefaultEnglishLocalizer;
        let formatter = DefaultMessageFormatter.with_localizer(&localizer);
        let err = Error::Eof { location: loc() };
        assert_eq!(formatter.format_message(&err), "unexpected end of input");
    }
}