Skip to main content

ctl_input/
entries.rs

1//! The top-level entries of a text, each with the byte range of its value,
2//! how the value is written and, for a string, its text.
3//!
4//! A caller that reads a mapping it did not write, such as the front matter of
5//! a Markdown file, learns where each value sits and what it reads as, with no
6//! scanner of its own. The tree gives the spans and the style, and the
7//! text's format decides what a scalar reads as.
8
9use std::ops::Range;
10
11use super::format::{Format, Reading, Resolved, Wanted};
12use super::tree::{Node, NodeKind, ScalarStyle, ScalarSyntax};
13use super::{Input, InputError, Raise, limits};
14
15/// How the value of an [`Entry`] is written.
16///
17/// Non-exhaustive: a later release can name another way to write a value.
18/// TOML writes a string four ways, which map onto the first two quoted forms
19/// and the two multi-line ones, and writes a number, a boolean or a date as
20/// [`Written::Plain`].
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum Written {
24    /// A YAML plain scalar, a TOML number, boolean or date, or a JSON number,
25    /// boolean or null.
26    Plain,
27    /// A single-quoted YAML scalar, or a TOML literal string `'…'`.
28    SingleQuoted,
29    /// A double-quoted YAML scalar, a TOML basic string `"…"`, or a JSON
30    /// string.
31    DoubleQuoted,
32    /// A YAML literal block scalar, `|`.
33    Literal,
34    /// A YAML folded block scalar, `>`.
35    Folded,
36    /// A TOML multi-line basic string, `"""…"""`.
37    MultilineBasic,
38    /// A TOML multi-line literal string, `'''…'''`.
39    MultilineLiteral,
40    /// A YAML alias, `*name`.
41    Alias,
42    /// A YAML sequence or mapping, a TOML array or table, or a JSON array or
43    /// object.
44    Collection,
45}
46
47/// One entry of the top-level mapping or table of a text.
48///
49/// Non-exhaustive: a later release can add a field.
50#[derive(Clone, Debug, PartialEq, Eq)]
51#[non_exhaustive]
52pub struct Entry {
53    /// The key, as the parser read it: quotes and escapes resolved. A YAML key
54    /// that is a number, a boolean or a null is its text as written.
55    pub key: String,
56    /// The bytes of the value in [`Input::text`], as written. A quoted string
57    /// includes its quotes and a block scalar its header. An anchor or a tag
58    /// before a YAML value is outside it, and an alias is `*name`.
59    pub value: Range<usize>,
60    /// How the value is written.
61    pub written: Written,
62    /// The text of the value, when the parser reads it as a string, and `None`
63    /// for a number, a boolean, a null, a date, a collection or an alias to
64    /// one. A YAML alias to a string, and a scalar under `!!str`, hold the
65    /// string.
66    pub string: Option<String>,
67}
68
69impl Input {
70    /// The entries of the text's top-level mapping or table, in the order
71    /// written.
72    ///
73    /// An entry whose key is a YAML sequence, mapping or alias is left out, and
74    /// the entries around it keep their own ranges. A text whose root is no
75    /// mapping, such as a sequence or a scalar, has no entries.
76    ///
77    /// The listing refuses nothing that YAML allows, so a key written twice,
78    /// a merge key (`<<`) and a `.inf` or `.NaN` are entries like the rest,
79    /// where [`Input::parse`] refuses them. The text must pass the limits in
80    /// force, as [`Input::parse`] holds it to, and the input reads the tree
81    /// that [`Input::place`] keeps.
82    ///
83    /// ```
84    /// # #[cfg(feature = "yaml")]
85    /// # {
86    /// use ctl_input::Input;
87    ///
88    /// let input = Input::new("page.yaml", "title: A page\nyear: 2026\n");
89    /// let entries = input.top_level()?;
90    /// let title = &entries[0];
91    /// assert_eq!(title.key, "title");
92    /// assert_eq!(&input.text()[title.value.clone()], "A page");
93    /// assert_eq!(title.string.as_deref(), Some("A page"));
94    /// assert_eq!(entries[1].string, None);
95    /// # }
96    /// # Ok::<(), ctl_input::InputError>(())
97    /// ```
98    ///
99    /// # Errors
100    ///
101    /// An [`InputError`] with the problem and its line, as [`Input::parse`]
102    /// gives, for a text its format refuses or that goes past a limit.
103    pub fn top_level(&self) -> Result<Vec<Entry>, InputError> {
104        let limits = limits::effective(&self.limits);
105        self.fits(&limits, Raise::FOR_TEXT)?;
106        let read = self
107            .kept
108            .tree(self.format, &self.text, &limits, Reading::Listing);
109        let tree = read
110            .as_ref()
111            .as_ref()
112            .map_err(|refusal| self.refused(refusal, Raise::FOR_TEXT))?;
113        Ok(entries(tree, self.format))
114    }
115}
116
117/// The entries of the mapping `root`, or none when it is no mapping.
118fn entries(root: &Node, format: &dyn Format) -> Vec<Entry> {
119    let NodeKind::Mapping(pairs) = root.kind() else {
120        return Vec::new();
121    };
122    pairs
123        .iter()
124        .filter_map(|(key, value)| entry(key, value, format))
125        .collect()
126}
127
128/// The entry of `key` and `value`, unless the key is no scalar the text
129/// wrote: a sequence, a mapping, an alias, or a null written as nothing.
130fn entry(key: &Node, value: &Node, format: &dyn Format) -> Option<Entry> {
131    let NodeKind::Scalar(name) = key.kind() else {
132        return None;
133    };
134    if key.used_at().is_some() || key.span().is_empty() {
135        return None;
136    }
137    let (range, written) = match value.used_at() {
138        Some(alias) => (alias, Written::Alias),
139        None => (value.span(), written_as(value)),
140    };
141    Some(Entry {
142        key: name.value().to_owned(),
143        value: range,
144        written,
145        string: string_of(value, format),
146    })
147}
148
149/// How `value` is written.
150fn written_as(value: &Node) -> Written {
151    match value.kind() {
152        NodeKind::Scalar(scalar) => match scalar.style() {
153            ScalarStyle::Plain => Written::Plain,
154            ScalarStyle::SingleQuoted => Written::SingleQuoted,
155            ScalarStyle::DoubleQuoted => Written::DoubleQuoted,
156            ScalarStyle::Literal => Written::Literal,
157            ScalarStyle::Folded => Written::Folded,
158            ScalarStyle::MultilineBasic => Written::MultilineBasic,
159            ScalarStyle::MultilineLiteral => Written::MultilineLiteral,
160        },
161        NodeKind::Sequence(_) | NodeKind::Mapping(_) => Written::Collection,
162    }
163}
164
165/// The text of `value` when its format reads it as a string. A TOML datetime
166/// is a date, not a string, though its format can read its text.
167fn string_of(value: &Node, format: &dyn Format) -> Option<String> {
168    let NodeKind::Scalar(scalar) = value.kind() else {
169        return None;
170    };
171    if scalar.syntax() == Some(ScalarSyntax::Datetime) {
172        return None;
173    }
174    match format.resolve(scalar, value.tag(), Wanted::Any) {
175        Ok(Resolved::Str(text)) => Some(text.into_owned()),
176        Ok(
177            Resolved::Null
178            | Resolved::Bool(_)
179            | Resolved::Int(_)
180            | Resolved::Uint(_)
181            | Resolved::Float(_),
182        )
183        | Err(_) => None,
184    }
185}