serde_saphyr/de/localizer.rs
1//! Localization / wording customization.
2//!
3//! The [`Localizer`] trait is the central hook for customizing *crate-authored wording*.
4//! It is intentionally designed to be low-boilerplate:
5//!
6//! - Every method has a reasonable English default.
7//! - You can override only the pieces you care about, while inheriting all other defaults.
8//!
9//! This crate may also show *external* message text coming from dependencies (for example
10//! `granit-parser` scan errors, or validator messages). Where such texts are used, the
11//! rendering pipeline should provide a best-effort opportunity to override them via
12//! [`Localizer::override_external_message`].
13//!
14//! ## Example: override a single phrase
15//!
16//! ```rust
17//! use serde_saphyr::{Error, Location};
18//! use serde_saphyr::localizer::{Localizer, DEFAULT_ENGLISH_LOCALIZER};
19//! use std::borrow::Cow;
20//!
21//! /// A wrapper that overrides only location suffix wording, delegating everything else.
22//! struct Pirate<'a> {
23//! base: &'a dyn Localizer,
24//! }
25//!
26//! impl Localizer for Pirate<'_> {
27//! fn attach_location<'b>(&self, base: Cow<'b, str>, loc: Location) -> Cow<'b, str> {
28//! if loc == Location::UNKNOWN {
29//! return base;
30//! }
31//! // Note: you can also delegate to `self.base.attach_location(...)` if you want.
32//! Cow::Owned(format!(
33//! "{base}. Bug lurks on line {}, then {} runes in",
34//! loc.line(),
35//! loc.column()
36//! ))
37//! }
38//! }
39//!
40//! // This snippet shows the customization building blocks; the crate's rendering APIs
41//! // obtain a `Localizer` via the `MessageFormatter`.
42//! # let _ = (Error::InvalidUtf8Input, &DEFAULT_ENGLISH_LOCALIZER);
43//! ```
44
45use crate::Location;
46use granit_parser::ScanError;
47use std::borrow::Cow;
48
49/// Where an “external” message comes from.
50///
51/// External messages are those primarily produced by dependencies (parser / validators).
52#[non_exhaustive]
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub enum ExternalMessageSource {
55 /// Text produced by the immediate YAML parser, with its structured error.
56 Parser(ScanError),
57 /// Text produced by `garde` validation rules.
58 Garde,
59 /// Text produced by `validator` validation rules.
60 Validator,
61}
62
63/// A best-effort description of an external message.
64///
65/// The crate should pass as much stable metadata as it has (e.g. `code` and `params` for
66/// `validator`) so the localizer can override *specific* messages without string matching.
67#[non_exhaustive]
68#[derive(Debug, Clone)]
69pub struct ExternalMessage<'a> {
70 pub source: ExternalMessageSource,
71 /// The original text as provided by the external library.
72 pub original: &'a str,
73 /// Stable-ish identifier when available (e.g. validator error code).
74 pub code: Option<&'a str>,
75 /// Optional structured parameters when available.
76 pub params: &'a [(String, String)],
77}
78
79impl<'a> ExternalMessage<'a> {
80 /// Construct an external message with no code or structured parameters.
81 #[must_use]
82 pub fn new(source: ExternalMessageSource, original: &'a str) -> Self {
83 Self {
84 source,
85 original,
86 code: None,
87 params: &[],
88 }
89 }
90
91 /// Attach a dependency-provided message code.
92 #[must_use]
93 pub fn with_code(mut self, code: &'a str) -> Self {
94 self.code = Some(code);
95 self
96 }
97
98 /// Attach structured dependency-provided message parameters.
99 #[must_use]
100 pub fn with_params(mut self, params: &'a [(String, String)]) -> Self {
101 self.params = params;
102 self
103 }
104}
105
106/// All crate-authored wording customization points.
107///
108/// Implementors should typically override *only a few* methods.
109/// Everything else should default to English (via the default method bodies).
110pub trait Localizer {
111 // ---------------- Common tiny building blocks ----------------
112
113 /// Attach a location suffix to `base`.
114 ///
115 /// Renderers must use this instead of hard-coding English wording like
116 /// `" at line X, column Y"`.
117 ///
118 /// Default:
119 /// - If `loc == Location::UNKNOWN`: returns `base` unchanged.
120 /// - Otherwise: returns `"{base} at line {line}, column {column}"`.
121 fn attach_location<'a>(&self, base: Cow<'a, str>, loc: Location) -> Cow<'a, str> {
122 if loc == Location::UNKNOWN {
123 base
124 } else {
125 Cow::Owned(format!(
126 "{base} at line {}, column {}",
127 loc.line, loc.column
128 ))
129 }
130 }
131
132 /// Label used when a path has no leaf.
133 ///
134 /// Default `<root>`
135 fn root_path_label(&self) -> Cow<'static, str> {
136 Cow::Borrowed("<root>")
137 }
138
139 /// Suffix for alias-related errors when a distinct defined-location is available.
140 ///
141 /// Default wording matches the crate's historical English output:
142 /// `" (defined at line X, column Y)"`.
143 ///
144 /// Default: `format!(" (defined at line {line}, column {column})", ...)`.
145 fn alias_defined_at(&self, defined: Location) -> String {
146 format!(
147 " (defined at line {}, column {})",
148 defined.line, defined.column
149 )
150 }
151
152 // ---------------- Validation (plain text) glue ----------------
153
154 /// Render one validation issue line.
155 ///
156 /// The crate provides `resolved_path`, `entry` and the chosen `loc`.
157 ///
158 /// Default:
159 /// - Base text: `"validation error at {resolved_path}: {entry}"`.
160 /// - If `loc` is `Some` and not `Location::UNKNOWN`, appends a location suffix via
161 /// [`Localizer::attach_location`].
162 fn validation_issue_line(
163 &self,
164 resolved_path: &str,
165 entry: &str,
166 loc: Option<Location>,
167 ) -> String {
168 let base = format!("validation error at {resolved_path}: {entry}");
169 match loc {
170 Some(l) if l != Location::UNKNOWN => {
171 self.attach_location(Cow::Owned(base), l).into_owned()
172 }
173 _ => base,
174 }
175 }
176
177 /// Join multiple validation issues into one message.
178 ///
179 /// Default: joins `lines` with a single newline (`"\n"`).
180 fn join_validation_issues(&self, lines: &[String]) -> String {
181 lines.join("\n")
182 }
183
184 // ---------------- Validation snippets / diagnostic labels ----------------
185
186 /// Label used for a snippet window when the location is known and considered the
187 /// “definition” site.
188 ///
189 /// Default: `"(defined)"`.
190 fn defined(&self) -> Cow<'static, str> {
191 Cow::Borrowed("(defined)")
192 }
193
194 /// Label used for a snippet window when we only have a “defined here” location.
195 ///
196 /// Default: `"(defined here)"`.
197 fn defined_here(&self) -> Cow<'static, str> {
198 Cow::Borrowed("(defined here)")
199 }
200
201 /// Label used for the primary snippet window when an aliased/anchored value is used
202 /// at a different location than where it was defined.
203 ///
204 /// Default: `"the value is used here"`.
205 fn value_used_here(&self) -> Cow<'static, str> {
206 Cow::Borrowed("the value is used here")
207 }
208
209 /// Label used for the secondary snippet window that points at the anchor definition.
210 ///
211 /// Default: `"defined here"`.
212 fn defined_window(&self) -> Cow<'static, str> {
213 Cow::Borrowed("defined here")
214 }
215
216 /// Compose the base validation message used in snippet rendering.
217 ///
218 /// Default: `"validation error: {entry} for `{`resolved_path`}`"`.
219 fn validation_base_message(&self, entry: &str, resolved_path: &str) -> String {
220 format!("validation error: {entry} for `{resolved_path}`")
221 }
222
223 /// Compose the “invalid here” prefix for the primary snippet message.
224 ///
225 /// Default: `"invalid here, {base}"`.
226 fn invalid_here(&self, base: &str) -> String {
227 format!("invalid here, {base}")
228 }
229
230 /// Intro line printed between the primary and secondary snippet windows for
231 /// anchor/alias (“indirect value”) cases.
232 ///
233 /// Default:
234 /// `" | This value comes indirectly from the anchor at line {line} column {column}:"`.
235 fn value_comes_from_the_anchor(&self, def: Location) -> String {
236 format!(
237 " | This value comes indirectly from the anchor at line {} column {}:",
238 def.line, def.column
239 )
240 }
241
242 // ---------------- External overrides ----------------
243
244 /// Optional hook to override the location prefix used for snippet titles
245 ///
246 /// Default:
247 /// - If `loc == Location::UNKNOWN`: returns an empty string.
248 /// - Otherwise: returns `"line {line} column {column}"`.
249 fn snippet_location_prefix(&self, loc: Location) -> String {
250 if loc == Location::UNKNOWN {
251 String::new()
252 } else {
253 format!("line {} column {}", loc.line(), loc.column())
254 }
255 }
256
257 /// Best-effort hook to override/translate dependency-provided message text.
258 ///
259 /// Default: returns `None` (keep the external message as-is).
260 fn override_external_message<'a>(&self, _msg: ExternalMessage<'a>) -> Option<Cow<'a, str>> {
261 None
262 }
263}
264
265/// Default English localizer used by the crate.
266#[derive(Debug, Default, Clone, Copy)]
267pub struct DefaultEnglishLocalizer;
268
269impl Localizer for DefaultEnglishLocalizer {}
270
271/// A single shared instance of the default English localizer.
272///
273/// This avoids repeated instantiation and provides a convenient reference for wrappers.
274pub static DEFAULT_ENGLISH_LOCALIZER: DefaultEnglishLocalizer = DefaultEnglishLocalizer;