ctl_input/format.rs
1//! The input format interface: what a format reads a text into, and how it
2//! reads one scalar for the type a field needs.
3//!
4//! The built-in formats, [`YAML`] with `yaml`, [`JSON`] with `json` and
5//! [`TOML`] with `toml`, and a format a CLI writes are the same kind of thing:
6//! a [`Format`] in a [`Formats`](crate::Formats) registry. [`Format::read`]
7//! turns text into the [located tree](crate::tree), and [`Format::resolve`]
8//! gives each scalar its meaning, so every format keeps its own scalar rules.
9#![cfg_attr(
10 not(feature = "yaml"),
11 doc = "",
12 doc = "[`YAML`]: crate#cargo-features"
13)]
14#![cfg_attr(
15 not(feature = "json"),
16 doc = "",
17 doc = "[`JSON`]: crate#cargo-features"
18)]
19#![cfg_attr(
20 not(feature = "toml"),
21 doc = "",
22 doc = "[`TOML`]: crate#cargo-features"
23)]
24
25use std::borrow::Cow;
26use std::error::Error;
27use std::fmt;
28use std::ops::Range;
29
30use super::Limits;
31#[cfg(feature = "json")]
32pub use super::json_format::{JSON, Json};
33use super::messages::{EnglishMessages, Messages, messages};
34#[cfg(feature = "toml")]
35pub use super::toml_format::{TOML, Toml};
36use super::tree::{Node, Scalar, Tag};
37#[cfg(feature = "yaml")]
38pub use super::yaml_format::{YAML, Yaml};
39
40/// A way to write input, read into the located tree.
41///
42/// The trait is object safe: [`Formats`](crate::Formats) holds
43/// `&'static dyn Format`, as ctl-core's output registry does.
44///
45/// ```
46/// # #[cfg(feature = "yaml")]
47/// # {
48/// use ctl_input::Limits;
49/// use ctl_input::format::{Format, Reading, YAML};
50///
51/// let formats: Vec<&'static dyn Format> = vec![&YAML];
52/// let tree = formats[0].read("a: 1\n", &Limits::NONE, Reading::Strict)?;
53/// assert_eq!(tree.span(), 0..4);
54/// # }
55/// # Ok::<(), ctl_input::format::Refusal>(())
56/// ```
57pub trait Format: Sync {
58 /// The name the registry finds the format by, such as `yaml`.
59 fn name(&self) -> &'static str;
60
61 /// The file extensions the format reads, in lower case and without the
62 /// dot, such as `yaml` and `yml`.
63 fn extensions(&self) -> &'static [&'static str];
64
65 /// Read `text` into the tree, under `limits`.
66 ///
67 /// The read refuses a second document and anything past a limit, and
68 /// `reading` says whether it also refuses duplicate and merge keys. A
69 /// format with aliases expands each one while it reads, so the tree holds
70 /// no alias node.
71 ///
72 /// # Errors
73 ///
74 /// A [`Refusal`] naming the fault and where it is.
75 fn read(&self, text: &str, limits: &Limits, reading: Reading) -> Result<Node, Refusal>;
76
77 /// Read one `scalar`, with the `tag` its node carries, as the type a
78 /// field `wanted`.
79 ///
80 /// This applies the rules of a [`Reading::Strict`] read, whichever
81 /// reading built the tree: YAML, for one, refuses `.inf` and `.nan` for
82 /// [`Wanted::Any`]. A listing asks of each value only whether it is text,
83 /// with [`Wanted::Str`].
84 ///
85 /// # Errors
86 ///
87 /// A [`Mismatch`] when the scalar cannot be read as `wanted`.
88 fn resolve<'a>(
89 &self,
90 scalar: &'a Scalar,
91 tag: Option<&Tag>,
92 wanted: Wanted,
93 ) -> Result<Resolved<'a>, Mismatch>;
94}
95
96/// What a [`Format::read`] refuses besides syntax.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub enum Reading {
99 /// A config or any text the caller validates: a duplicate key and a merge
100 /// key are refused.
101 Strict,
102 /// A listing of a text the caller did not write, such as the front matter
103 /// of a Markdown file: a duplicate key and a merge key stay as ordinary
104 /// entries.
105 Listing,
106}
107
108/// The type a field needs a scalar read as.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum Wanted {
112 /// Whatever the scalar is, as a typeless read sees it.
113 Any,
114 /// A boolean.
115 Bool,
116 /// An integer.
117 Int,
118 /// A floating-point number.
119 Float,
120 /// A string.
121 Str,
122 /// A null.
123 Null,
124}
125
126/// A scalar read for the type a field needs.
127#[derive(Clone, Debug, PartialEq)]
128#[non_exhaustive]
129pub enum Resolved<'a> {
130 /// A null.
131 Null,
132 /// A boolean.
133 Bool(bool),
134 /// An integer that fits `i128`.
135 Int(i128),
136 /// An integer above `i128::MAX`.
137 Uint(u128),
138 /// A floating-point number.
139 Float(f64),
140 /// A string, borrowed from the scalar, or owned when the format decodes
141 /// it, as YAML decodes a `!!binary` scalar.
142 Str(Cow<'a, str>),
143}
144
145/// A scalar the format cannot read as the type a field wanted.
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub struct Mismatch {
148 wanted: Wanted,
149 detail: Option<String>,
150}
151
152impl Mismatch {
153 /// A scalar that is not a `wanted`.
154 #[must_use]
155 pub fn new(wanted: Wanted) -> Self {
156 Self {
157 wanted,
158 detail: None,
159 }
160 }
161
162 /// This mismatch with the format's own words for why the scalar is not a
163 /// `wanted`, such as a YAML float that is not finite.
164 #[must_use]
165 pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
166 self.detail = Some(detail.into());
167 self
168 }
169
170 /// The type the field wanted.
171 #[must_use]
172 pub fn wanted(&self) -> Wanted {
173 self.wanted
174 }
175
176 /// The format's own words for why the scalar is not a
177 /// [`wanted`](Self::wanted), when it gave any. A typeless read has no type
178 /// to name, so the Deserializer words its refusal from this.
179 #[must_use]
180 pub fn detail(&self) -> Option<&str> {
181 self.detail.as_deref()
182 }
183}
184
185impl fmt::Display for Mismatch {
186 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
187 formatter.write_str(match self.wanted {
188 Wanted::Any => "expected a value",
189 Wanted::Bool => "expected true or false",
190 Wanted::Int => "expected an integer",
191 Wanted::Float => "expected a float",
192 Wanted::Str => "expected text",
193 Wanted::Null => "expected null",
194 })
195 }
196}
197
198impl Error for Mismatch {}
199
200/// Why a [`Format::read`] refused a text, and where.
201#[derive(Clone, Debug, PartialEq, Eq)]
202pub struct Refusal {
203 fault: Fault,
204 span: Option<Range<usize>>,
205 defined_at: Option<Range<usize>>,
206}
207
208impl Refusal {
209 /// A refusal for `fault`, at `span` when the format knows where.
210 /// `defined_at` is set when the fault arose in a node an alias replayed:
211 /// `span` is then the alias, and `defined_at` where the node is written.
212 #[must_use]
213 pub fn new(fault: Fault, span: Option<Range<usize>>, defined_at: Option<Range<usize>>) -> Self {
214 Self {
215 fault,
216 span,
217 defined_at,
218 }
219 }
220
221 /// What is wrong.
222 #[must_use]
223 pub fn fault(&self) -> &Fault {
224 &self.fault
225 }
226
227 /// The bytes of the text the fault is at, when known. A fault the parser
228 /// places only by line and column, such as a YAML scanner error, has an
229 /// empty span at that place.
230 #[must_use]
231 pub fn span(&self) -> Option<Range<usize>> {
232 self.span.clone()
233 }
234
235 /// Where the node an alias replayed is written, when the fault arose in
236 /// one.
237 #[must_use]
238 pub fn defined_at(&self) -> Option<Range<usize>> {
239 self.defined_at.clone()
240 }
241}
242
243/// The wording [`set_messages`](crate::set_messages) installed, or the English
244/// default.
245impl fmt::Display for Refusal {
246 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
247 formatter.write_str(&messages().message(&self.fault))
248 }
249}
250
251impl Error for Refusal {}
252
253/// What a read of a text or of a typed value found wrong.
254///
255/// Each variant is one problem type, and [`Messages`] words it.
256/// A problem in a node an alias replayed is a [`Refusal`] with
257/// [`Refusal::defined_at`] set, not a variant of its own.
258#[derive(Clone, Debug, PartialEq, Eq)]
259#[non_exhaustive]
260pub enum Fault {
261 /// The text is not valid in the format.
262 Syntax {
263 /// What the format's parser says is wrong.
264 detail: String,
265 },
266 /// A key written twice in one mapping: under [`Reading::Strict`] in YAML
267 /// and JSON, and under either reading in TOML, whose syntax forbids it.
268 DuplicateKey {
269 /// The key.
270 key: String,
271 },
272 /// A YAML merge key (`<<`), under [`Reading::Strict`].
273 MergeKey,
274 /// The text went past a limit.
275 Limit {
276 /// The [`Limits`] field.
277 name: &'static str,
278 /// The value in force.
279 value: String,
280 /// Where a person raises it.
281 raise: Raise,
282 },
283 /// The whole text is longer than `max_reader_input_bytes` allows.
284 TooLarge {
285 /// The length of the text, in bytes.
286 bytes: u64,
287 /// The value of `max_reader_input_bytes` in force.
288 limit: u64,
289 /// Where a person raises it.
290 raise: Raise,
291 },
292 /// A node of another kind than the type being read needs, such as a
293 /// sequence where a struct is read.
294 ExpectedKind {
295 /// What the type needs, such as `a mapping`.
296 expected: String,
297 /// What the node is, such as `a sequence`.
298 found: String,
299 },
300 /// A value the type refuses: a scalar the format cannot read as the type
301 /// the field needs, a number out of range, or the text of an error the
302 /// type's own `Deserialize` raised.
303 InvalidValue {
304 /// Why the value is refused.
305 detail: String,
306 },
307 /// A key a struct does not have, under `deny_unknown_fields`.
308 UnknownField {
309 /// The key.
310 field: String,
311 /// The keys the struct has.
312 expected: Vec<&'static str>,
313 },
314 /// A variant an enum does not have.
315 UnknownVariant {
316 /// The variant as written.
317 variant: String,
318 /// The variants the enum has.
319 expected: Vec<&'static str>,
320 },
321 /// A field a struct needs and its mapping lacks.
322 MissingField {
323 /// The field.
324 field: &'static str,
325 },
326}
327
328/// Where a person raises a limit a text went past.
329#[derive(Clone, Copy, Debug, PartialEq, Eq)]
330#[non_exhaustive]
331pub enum Raise {
332 /// In the repository's file of limits.
333 #[cfg(feature = "yaml")]
334 InRepository,
335 /// In the tool's process default, for the repository's file of limits
336 /// itself, which is read before any repository override applies.
337 #[cfg(feature = "yaml")]
338 InProcess,
339 /// Nowhere the user can reach: a build without `yaml` reads no
340 /// repository file, so only the tool sets limits.
341 #[cfg(not(feature = "yaml"))]
342 InTool,
343}
344
345impl Fault {
346 /// A [`Fault::Limit`] for a text of a CLI's own format that went past
347 /// the limit `name` of the value `value`, worded as it is for a text in
348 /// memory: where a person raises it is the same as for the built-in
349 /// formats.
350 #[must_use]
351 #[expect(
352 clippy::needless_pass_by_value,
353 reason = "a caller hands over the number or text it has, as it would to Into"
354 )]
355 pub fn limit(name: &'static str, value: impl ToString) -> Self {
356 Self::Limit {
357 name,
358 value: value.to_string(),
359 raise: Raise::FOR_TEXT,
360 }
361 }
362}
363
364impl Raise {
365 /// Where a limit hit by a CLI's own text is raised.
366 #[cfg(feature = "yaml")]
367 pub(crate) const FOR_TEXT: Self = Self::InRepository;
368 /// Where a limit hit by a CLI's own text is raised.
369 #[cfg(not(feature = "yaml"))]
370 pub(crate) const FOR_TEXT: Self = Self::InTool;
371}
372
373impl fmt::Display for Fault {
374 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
375 formatter.write_str(&EnglishMessages.message(self))
376 }
377}
378
379#[cfg(test)]
380mod tests {
381 use super::{Mismatch, Wanted};
382
383 #[test]
384 fn a_mismatch_says_what_was_expected() {
385 let expected = [
386 (Wanted::Any, "expected a value"),
387 (Wanted::Bool, "expected true or false"),
388 (Wanted::Int, "expected an integer"),
389 (Wanted::Float, "expected a float"),
390 (Wanted::Str, "expected text"),
391 (Wanted::Null, "expected null"),
392 ];
393 for (wanted, message) in expected {
394 assert_eq!(Mismatch::new(wanted).to_string(), message);
395 }
396 }
397}