ctl_core/input.rs
1//! Declared input: read a file, parse it, validate it once, and report every
2//! problem on its file and line.
3//!
4//! Each format is its own feature. `input-yaml` parses YAML with
5//! `serde-saphyr`, and `input-toml` parses TOML with the `toml` crate; neither
6//! needs the other. `validate` adds `Input::check` and `Input::load`, which
7//! validate with garde, and `input` is `input-yaml` with `validate`. This is
8//! the one boundary where a CLI's config enters. Downstream code keeps the
9//! validated type and never checks it again.
10//!
11//! A check that runs after the read, such as one that needs a file the config
12//! names, places its problem with a [`FieldPath`] and [`Input::problem_at`],
13//! the way the loader places garde's.
14//!
15//! A text's [`Format`] is chosen, never guessed. [`Input::open`] reads it from
16//! the file's extension, and [`Input::new_with_format`] takes it for text in
17//! memory. With `input-yaml`, `Input::new` and `Input::read` are YAML.
18//!
19//! ```
20//! # #[cfg(feature = "input")]
21//! # {
22//! use ctl_core::input::Input;
23//! use serde::Deserialize;
24//!
25//! #[derive(Debug, Deserialize)]
26//! struct Config {
27//! name: String,
28//! }
29//!
30//! let config: Config = Input::new("toy.yaml", "name: release\n").parse()?;
31//! assert_eq!(config.name, "release");
32//!
33//! let error = Input::new("toy.yaml", "name: a\nname: b\n")
34//! .parse::<Config>()
35//! .unwrap_err();
36//! assert!(error.to_string().starts_with("toy.yaml"));
37//! # }
38//! # Ok::<(), ctl_core::input::InputError>(())
39//! ```
40
41use std::path::Path;
42use std::{fmt, io};
43
44#[cfg(feature = "validate")]
45use garde::Validate;
46use serde::de::DeserializeOwned;
47
48mod entries;
49mod field_path;
50mod limits;
51#[cfg(feature = "input-toml")]
52mod toml_entries;
53#[cfg(feature = "input-toml")]
54mod toml_text;
55#[cfg(feature = "input-yaml")]
56mod yaml_entries;
57#[cfg(feature = "input-yaml")]
58mod yaml_text;
59
60pub use entries::{Entry, Written};
61pub use field_path::{FieldPath, Place, Step};
62use limits::{Exceeded, Raise};
63pub use limits::{Limits, set_default_limits};
64#[cfg(feature = "input-yaml")]
65pub use limits::{Loosened, REPO_FILE, use_repo_limits};
66
67/// What a placing answers with for a key of the path: where its value starts,
68/// or where the key itself is written.
69#[derive(Clone, Copy)]
70enum At {
71 Value,
72 Key,
73}
74
75/// How a text is written.
76///
77/// Non-exhaustive: each variant exists only with its format's feature.
78/// Cargo unifies features across a build, so a caller's `match` needs a
79/// wildcard arm.
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum Format {
83 /// YAML, read by serde-saphyr and placed by yamled.
84 #[cfg(feature = "input-yaml")]
85 Yaml,
86 /// TOML, read and placed by the `toml` crate.
87 #[cfg(feature = "input-toml")]
88 Toml,
89}
90
91impl Format {
92 /// The format a file's extension names, compared without regard to case:
93 /// `.toml` is TOML, and `.yaml` and `.yml` are YAML.
94 ///
95 /// # Errors
96 ///
97 /// An [`InputError`] with no line for any other extension or none, naming
98 /// the extension and the accepted ones. One naming the feature for an
99 /// extension whose format's feature is off.
100 pub fn of(path: &Path) -> Result<Self, InputError> {
101 let name = path.display().to_string();
102 let extension = path
103 .extension()
104 .map(|extension| extension.to_string_lossy().to_ascii_lowercase());
105 match extension.as_deref() {
106 #[cfg(feature = "input-yaml")]
107 Some("yaml" | "yml") => Ok(Self::Yaml),
108 #[cfg(not(feature = "input-yaml"))]
109 Some(yaml @ ("yaml" | "yml")) => Err(InputError::whole(
110 name,
111 format!("`.{yaml}` needs ctl-core's input-yaml feature; {ACCEPTED}"),
112 )),
113 #[cfg(feature = "input-toml")]
114 Some("toml") => Ok(Self::Toml),
115 #[cfg(not(feature = "input-toml"))]
116 Some("toml") => Err(InputError::whole(
117 name,
118 format!("`.toml` needs ctl-core's input-toml feature; {ACCEPTED}"),
119 )),
120 Some(other) => Err(InputError::whole(
121 name,
122 format!("unsupported extension .{other}; {ACCEPTED}"),
123 )),
124 None => Err(InputError::whole(
125 name,
126 format!("no file extension; {ACCEPTED}"),
127 )),
128 }
129 }
130}
131
132/// What a refusal tells a person to name the file: the extensions this build
133/// reads.
134#[cfg(all(feature = "input-yaml", feature = "input-toml"))]
135const ACCEPTED: &str = "name the file *.toml, *.yaml, or *.yml";
136#[cfg(all(feature = "input-yaml", not(feature = "input-toml")))]
137const ACCEPTED: &str = "name the file *.yaml or *.yml";
138#[cfg(all(feature = "input-toml", not(feature = "input-yaml")))]
139const ACCEPTED: &str = "name the file *.toml";
140
141/// A named text, ready to parse and validate.
142///
143/// The name is usually the file's path, and appears in every problem. Build
144/// one with [`Input::new_with_format`] for text in memory, or [`Input::open`]
145/// for a file. With `input-yaml`, `Input::new` and `Input::read` build a YAML
146/// one.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub struct Input {
149 name: String,
150 text: String,
151 lines_before: usize,
152 limits: Limits,
153 format: Format,
154 /// The schema fields serde flattens into their parents, which
155 /// [`Input::flattened`] declares.
156 #[cfg(feature = "validate")]
157 flattened: Vec<FieldPath>,
158 /// The YAML document that placing reads, built on first use.
159 #[cfg(feature = "input-yaml")]
160 yaml_document: yaml_text::Located,
161}
162
163/// Why an input was refused: every problem found, each placed on a line when
164/// the text allows it.
165///
166/// `Display` prints one problem per line as `name:line:column: field: message`,
167/// leaving out what is not known.
168///
169/// A file that could not be read keeps its [`io::ErrorKind`], which
170/// [`Self::io_failure`] returns. So a caller can treat a missing file apart
171/// from a refused one. A field can join this type in a minor release.
172#[derive(Clone, Debug, PartialEq, Eq)]
173#[non_exhaustive]
174pub struct InputError {
175 /// The input's name, usually its path.
176 pub name: String,
177 /// What is wrong, in the order found.
178 pub problems: Vec<Problem>,
179 /// The I/O failure, for an input that could not be read.
180 io_failure: Option<io::ErrorKind>,
181}
182
183/// One thing wrong with an input.
184#[derive(Clone, Debug, PartialEq, Eq)]
185pub struct Problem {
186 /// 1-based line, when known.
187 pub line: Option<usize>,
188 /// 1-based column, when known.
189 pub column: Option<usize>,
190 /// The field it concerns, as garde names it (`packages[1].name`); empty
191 /// for a problem with the whole text.
192 pub field: String,
193 /// What a person changes to fix it.
194 pub message: String,
195}
196
197impl Input {
198 /// A YAML input from text already in memory, whatever the extension of
199 /// `name`. Set another format with [`Input::format`].
200 #[cfg(feature = "input-yaml")]
201 #[must_use]
202 pub fn new(name: impl Into<String>, text: impl Into<String>) -> Self {
203 Self::new_with_format(name, text, Format::Yaml)
204 }
205
206 /// An input of `format` from text already in memory, whatever the
207 /// extension of `name`. It needs only `format`'s feature, so a build
208 /// without YAML builds text in memory with it.
209 #[must_use]
210 pub fn new_with_format(
211 name: impl Into<String>,
212 text: impl Into<String>,
213 format: Format,
214 ) -> Self {
215 Self {
216 name: name.into(),
217 text: text.into(),
218 lines_before: 0,
219 limits: Limits::NONE,
220 format,
221 #[cfg(feature = "validate")]
222 flattened: Vec::new(),
223 #[cfg(feature = "input-yaml")]
224 yaml_document: yaml_text::Located::default(),
225 }
226 }
227
228 /// Read a YAML file, named by its path, whatever its extension.
229 ///
230 /// # Errors
231 ///
232 /// An [`InputError`] with the I/O failure.
233 #[cfg(feature = "input-yaml")]
234 pub fn read(path: &Path) -> Result<Self, InputError> {
235 let (name, text) = read_text(path)?;
236 Ok(Self::new(name, text))
237 }
238
239 /// Read a file and take its [`Format`] from its extension, as
240 /// [`Format::of`] does. The extension is checked before the file is read.
241 ///
242 /// # Errors
243 ///
244 /// An [`InputError`] for an extension [`Format::of`] refuses, or with the
245 /// I/O failure.
246 pub fn open(path: &Path) -> Result<Self, InputError> {
247 let format = Format::of(path)?;
248 let (name, text) = read_text(path)?;
249 Ok(Self::new_with_format(name, text, format))
250 }
251
252 /// Set how the text is written, over what the constructor took.
253 #[must_use]
254 pub fn format(mut self, format: Format) -> Self {
255 self.format = format;
256 self
257 }
258
259 /// The name given at construction, usually the file's path.
260 #[must_use]
261 pub fn name(&self) -> &str {
262 &self.name
263 }
264
265 /// The text as read, unchanged.
266 #[must_use]
267 pub fn text(&self) -> &str {
268 &self.text
269 }
270
271 /// Split YAML frontmatter from a Markdown body.
272 ///
273 /// The frontmatter is the text between a first line of `---` and the next
274 /// line of `---`. It is YAML whatever this input's format, and problems in
275 /// it keep the line numbers of the whole file. The second item is the body
276 /// after the closing line. Returns `None` when the text does not start with
277 /// a `---` line, or never closes it.
278 #[cfg(feature = "input-yaml")]
279 #[must_use]
280 pub fn frontmatter(&self) -> Option<(Self, &str)> {
281 let text = self.text.strip_prefix('\u{feff}').unwrap_or(&self.text);
282 let rest = text
283 .strip_prefix("---\n")
284 .or_else(|| text.strip_prefix("---\r\n"))?;
285 let mut offset = 0;
286 for line in rest.split_inclusive('\n') {
287 if line.trim_end() == "---" {
288 let matter = Self {
289 name: self.name.clone(),
290 text: rest[..offset].to_owned(),
291 lines_before: self.lines_before + 1,
292 limits: self.limits.clone(),
293 format: Format::Yaml,
294 #[cfg(feature = "validate")]
295 flattened: self.flattened.clone(),
296 yaml_document: yaml_text::Located::default(),
297 };
298 return Some((matter, &rest[offset + line.len()..]));
299 }
300 offset += line.len();
301 }
302 None
303 }
304
305 /// Override limits for this input alone, above every other tier. See
306 /// [`Limits`] for the order.
307 #[must_use]
308 pub fn limits(mut self, limits: Limits) -> Self {
309 self.limits = limits;
310 self
311 }
312
313 /// Declare that the schema field at `field` is flattened into its parent
314 /// with `#[serde(flatten)]`, so the file writes its entries directly under
315 /// the parent.
316 ///
317 /// garde names the field in each problem's path all the same, and serde
318 /// gives no sign of the flattening at run time, so the schema declares it.
319 /// [`Input::check`] then drops the field's step from each garde path whose
320 /// leading steps are `field`, before it places the problem and prints its
321 /// field. `field` is written in the schema's terms, the way garde names it,
322 /// and each call adds one field. A declaration that matches no garde path
323 /// changes nothing. [`Input::place`], [`Input::place_key`], and
324 /// [`Input::problem_at`] take paths in the file's terms, so a declaration
325 /// does not touch them.
326 ///
327 /// # Examples
328 ///
329 /// verctl's `assets` holds its targets in a flattened map field `targets`.
330 /// Without the declaration, the problem prints as
331 /// `assets.targets.linux-x64.files` and sits on the line below `assets:`.
332 ///
333 /// ```
334 /// # #[cfg(feature = "input")]
335 /// # {
336 /// use std::collections::BTreeMap;
337 ///
338 /// use ctl_core::input::{FieldPath, Input};
339 /// use ctl_core::validate::at_least_one;
340 /// use garde::Validate;
341 /// use serde::Deserialize;
342 ///
343 /// #[derive(Debug, Deserialize, Validate)]
344 /// struct Config {
345 /// #[garde(dive)]
346 /// assets: Assets,
347 /// }
348 ///
349 /// #[derive(Debug, Deserialize, Validate)]
350 /// struct Assets {
351 /// #[serde(flatten)]
352 /// #[garde(dive)]
353 /// targets: BTreeMap<String, Target>,
354 /// }
355 ///
356 /// #[derive(Debug, Deserialize, Validate)]
357 /// struct Target {
358 /// #[garde(custom(at_least_one("file")))]
359 /// files: Vec<String>,
360 /// }
361 ///
362 /// let error = Input::new("ver.yaml", "assets:\n linux-x64:\n files: []\n")
363 /// .flattened(FieldPath::root().key("assets").key("targets"))
364 /// .load::<Config>()
365 /// .unwrap_err();
366 /// assert_eq!(
367 /// error.to_string(),
368 /// "ver.yaml:3:12: assets.linux-x64.files: must declare at least one file"
369 /// );
370 /// # }
371 /// ```
372 #[cfg(feature = "validate")]
373 #[must_use]
374 pub fn flattened(mut self, field: FieldPath) -> Self {
375 self.flattened.push(field);
376 self
377 }
378
379 /// `path` without the step of each declared flattened field it passes
380 /// through, or `None` when it passes through none.
381 #[cfg(feature = "validate")]
382 fn unflatten(&self, path: &FieldPath) -> Option<FieldPath> {
383 let positions: Vec<usize> = self
384 .flattened
385 .iter()
386 .filter(|field| path.starts_with(field))
387 .filter_map(|field| field.steps().len().checked_sub(1))
388 .collect();
389 (!positions.is_empty()).then(|| path.without(&positions))
390 }
391
392 /// Parse the text into `T`, without validating it.
393 ///
394 /// In YAML only `true` and `false` are booleans, and a duplicate key or a
395 /// merge key (`<<`) is refused. In TOML the format itself refuses a
396 /// duplicate key.
397 ///
398 /// The text must fit the limits in force, decided field by field through
399 /// the tiers [`Limits`] lists. TOML reads only `max_reader_input_bytes`,
400 /// `max_depth`, and `max_nodes`, because the other fields name YAML
401 /// syntax.
402 ///
403 /// # Errors
404 ///
405 /// An [`InputError`] with the parser's problem and its line. A limit
406 /// problem names the limit, its value, and where to raise it, or, without
407 /// `input-yaml`, that the tool sets it.
408 pub fn parse<T: DeserializeOwned>(&self) -> Result<T, InputError> {
409 self.parse_within(&limits::effective(&self.limits), Raise::FOR_TEXT)
410 }
411
412 /// [`Self::parse`] under exactly `limits`, whatever the tiers say.
413 fn parse_within<T: DeserializeOwned>(
414 &self,
415 limits: &Limits,
416 raise: Raise,
417 ) -> Result<T, InputError> {
418 self.fits(limits, raise)?;
419 match self.format {
420 #[cfg(feature = "input-yaml")]
421 Format::Yaml => yaml_text::parse(self, &limits.budget(), raise),
422 #[cfg(feature = "input-toml")]
423 Format::Toml => toml_text::parse(self, limits.bounds(), raise),
424 }
425 }
426
427 /// Whether the text is within the size `limits` allow.
428 fn fits(&self, limits: &Limits, raise: Raise) -> Result<(), InputError> {
429 let bounds = limits.bounds();
430 if self.text.len() > bounds.input_bytes {
431 return Err(InputError::whole(
432 self.name.clone(),
433 format!(
434 "is {} bytes, which {}",
435 self.text.len(),
436 Exceeded::input_bytes(bounds.input_bytes, raise)
437 ),
438 ));
439 }
440 Ok(())
441 }
442
443 /// Validate a parsed `value` against `context`.
444 ///
445 /// Each of garde's problems lands on the line of the field it names, or
446 /// of its nearest written ancestor. The place comes from the parts of
447 /// garde's path through [`Input::place`], so a key that holds a `.` is
448 /// found as one key. `Problem::field` is garde's printed path, for display
449 /// only. A path through a field [`Input::flattened`] declares loses that
450 /// field's step, and its `Problem::field` is the shorter path as
451 /// [`FieldPath`] prints it.
452 ///
453 /// # Errors
454 ///
455 /// An [`InputError`] with every problem garde reports.
456 #[cfg(feature = "validate")]
457 pub fn check<T: Validate + ?Sized>(
458 &self,
459 value: &T,
460 context: &T::Context,
461 ) -> Result<(), InputError> {
462 let Err(report) = value.validate_with(context) else {
463 return Ok(());
464 };
465 let reported: Vec<_> = report
466 .iter()
467 .map(|(path, error)| {
468 let steps = FieldPath::from(path);
469 let (field, steps) = match self.unflatten(&steps) {
470 Some(kept) => (kept.to_string(), kept),
471 None => (path.to_string(), steps),
472 };
473 (field, steps, error.message().to_owned())
474 })
475 .collect();
476 let paths: Vec<_> = reported.iter().map(|(_, path, _)| path.clone()).collect();
477 let places = self.places(&paths, At::Value);
478 let problems = reported
479 .into_iter()
480 .zip(places)
481 .map(|((field, _, message), place)| Problem {
482 line: place.map(|at| at.line),
483 column: place.map(|at| at.column),
484 field,
485 message,
486 })
487 .collect();
488 Err(InputError::of(self.name.clone(), problems))
489 }
490
491 /// Where `path` is written in the text, or where its nearest written
492 /// ancestor is.
493 ///
494 /// The line counts the whole file, so a frontmatter input adds the lines
495 /// before it. A path the text lacks gives the place of the last step that
496 /// exists, and a caller that needs an exact hit compares the result with
497 /// the place of the path's parent. `None` when the text does not parse.
498 ///
499 /// `None` too when the text goes past the limits in force, as
500 /// [`Input::parse`] would refuse it, so placing never parses a text the
501 /// limits keep out. A YAML input checks `max_reader_input_bytes`,
502 /// `max_depth` and `max_nodes` before it hands the text to yamled, which
503 /// has no budget. A TOML input checks `max_reader_input_bytes`, and
504 /// the parse of its tree is the one [`Input::parse`] does first.
505 ///
506 /// A YAML input parses its text for the first placing and keeps the
507 /// result, so [`Input::check`] and later calls read one document. A TOML
508 /// input parses its text on each call.
509 ///
510 /// ```
511 /// # #[cfg(feature = "input-yaml")]
512 /// # {
513 /// use ctl_core::input::{FieldPath, Input};
514 ///
515 /// let input = Input::new("app.yaml", "files:\n 'docs/**/*.md':\n label: ''\n");
516 /// let path = FieldPath::root()
517 /// .key("files")
518 /// .key("docs/**/*.md")
519 /// .key("label");
520 /// let at = input.place(&path).map(|at| (at.line, at.column));
521 /// assert_eq!(at, Some((3, 12)));
522 /// # }
523 /// ```
524 #[must_use]
525 pub fn place(&self, path: &FieldPath) -> Option<Place> {
526 self.places(std::slice::from_ref(path), At::Value)
527 .pop()
528 .flatten()
529 }
530
531 /// Where the last step of `path` is written as a key, or where its nearest
532 /// written ancestor's key is.
533 ///
534 /// [`Input::place`] gives where a value starts. For a scalar or a flow
535 /// value that is the line of the key, and for a block mapping or a block
536 /// list it is the first line below it. A fault about the key itself, such
537 /// as a key that names nothing, belongs on the key, and this finds it.
538 ///
539 /// A step that is an index has no key, and neither has the root, so they
540 /// give the place of their value, as `place` does. A path the text lacks
541 /// gives the key of the last step that exists. The line counts the whole
542 /// file, `None` is for a text that does not parse or goes past the limits,
543 /// and a YAML document is built once and shared with [`Input::place`].
544 ///
545 /// ```
546 /// # #[cfg(feature = "input-yaml")]
547 /// # {
548 /// use ctl_core::input::{FieldPath, Input};
549 ///
550 /// let input = Input::new("app.yaml", "files:\n 'docs/**/*.md':\n label: ''\n");
551 /// let glob = FieldPath::root().key("files").key("docs/**/*.md");
552 /// let value = input.place(&glob).map(|at| (at.line, at.column));
553 /// let key = input.place_key(&glob).map(|at| (at.line, at.column));
554 /// assert_eq!(value, Some((3, 5)));
555 /// assert_eq!(key, Some((2, 3)));
556 /// # }
557 /// ```
558 #[must_use]
559 pub fn place_key(&self, path: &FieldPath) -> Option<Place> {
560 self.places(std::slice::from_ref(path), At::Key)
561 .pop()
562 .flatten()
563 }
564
565 /// A [`Problem`] for `path` with `message`, placed as [`Input::place`]
566 /// places it, with the path printed as garde prints a field.
567 ///
568 /// A CLI uses it for a check that runs after the read, such as one that
569 /// needs a file the config names.
570 #[must_use]
571 pub fn problem_at(&self, path: &FieldPath, message: impl Into<String>) -> Problem {
572 let place = self.place(path);
573 Problem {
574 line: place.map(|at| at.line),
575 column: place.map(|at| at.column),
576 field: path.to_string(),
577 message: message.into(),
578 }
579 }
580
581 /// The place of each path, with the frontmatter lines added.
582 fn places(&self, paths: &[FieldPath], at: At) -> Vec<Option<Place>> {
583 let limits = limits::effective(&self.limits);
584 if self.text.len() > limits.bounds().input_bytes {
585 return vec![None; paths.len()];
586 }
587 let found = match self.format {
588 #[cfg(feature = "input-yaml")]
589 Format::Yaml => yaml_text::places(self, &limits, paths, at),
590 #[cfg(feature = "input-toml")]
591 Format::Toml => toml_text::places(&self.text, paths, at),
592 };
593 found
594 .into_iter()
595 .map(|at| at.map(|(line, column)| Place::new(line + self.lines_before, column)))
596 .collect()
597 }
598
599 /// Parse the text into `T`, then validate it with `T`'s default context.
600 ///
601 /// # Errors
602 ///
603 /// As [`Input::parse`] and [`Input::check`].
604 #[cfg(feature = "validate")]
605 pub fn load<T>(&self) -> Result<T, InputError>
606 where
607 T: DeserializeOwned + Validate,
608 T::Context: Default,
609 {
610 let value = self.parse::<T>()?;
611 self.check(&value, &T::Context::default())?;
612 Ok(value)
613 }
614}
615
616/// The file at `path`, named by its path, or the I/O failure.
617fn read_text(path: &Path) -> Result<(String, String), InputError> {
618 let name = path.display().to_string();
619 match std::fs::read_to_string(path) {
620 Ok(text) => Ok((name, text)),
621 Err(error) => Err(InputError::unread(name, &error)),
622 }
623}
624
625impl InputError {
626 /// A refusal of the whole input, not placed on a line.
627 fn whole(name: String, message: String) -> Self {
628 Self::of(
629 name,
630 vec![Problem {
631 line: None,
632 column: None,
633 field: String::new(),
634 message,
635 }],
636 )
637 }
638
639 /// The input `name` could not be read: the failure's text is the one
640 /// problem, and its `io::ErrorKind` is kept.
641 fn unread(name: String, error: &io::Error) -> Self {
642 Self {
643 io_failure: Some(error.kind()),
644 ..Self::whole(name, error.to_string())
645 }
646 }
647
648 /// The problems found in the input `name`, with no I/O failure.
649 const fn of(name: String, problems: Vec<Problem>) -> Self {
650 Self {
651 name,
652 problems,
653 io_failure: None,
654 }
655 }
656
657 /// The I/O failure when the file could not be read, such as
658 /// [`io::ErrorKind::NotFound`]. `None` when the text was read and refused.
659 #[must_use]
660 pub const fn io_failure(&self) -> Option<io::ErrorKind> {
661 self.io_failure
662 }
663}
664
665/// One problem per line: `name:line:column: field: message`, leaving out
666/// what is not known.
667impl fmt::Display for InputError {
668 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
669 for (index, problem) in self.problems.iter().enumerate() {
670 if index > 0 {
671 writeln!(formatter)?;
672 }
673 write!(formatter, "{}", self.name)?;
674 if let Some(line) = problem.line {
675 write!(formatter, ":{line}")?;
676 if let Some(column) = problem.column {
677 write!(formatter, ":{column}")?;
678 }
679 }
680 if problem.field.is_empty() {
681 write!(formatter, ": {}", problem.message)?;
682 } else {
683 write!(formatter, ": {}: {}", problem.field, problem.message)?;
684 }
685 }
686 Ok(())
687 }
688}
689
690impl std::error::Error for InputError {}