Skip to main content

ctl_input/
toml_format.rs

1//! The TOML [`Format`]: the `toml` crate's span-carrying tree becomes the
2//! located tree, each scalar carrying the type its syntax gave it, and each
3//! scalar resolves by that type.
4
5use std::borrow::Cow;
6use std::ops::Range;
7
8use toml::Spanned;
9use toml::de::{DeInteger, DeString, DeTable, DeValue};
10
11use super::exceeded::Exceeded;
12use super::format::{Fault, Format, Mismatch, Raise, Reading, Refusal, Resolved, Wanted};
13use super::limits::{Bounds, Limits};
14use super::tree::{Node, NodeKind, Scalar, ScalarStyle, ScalarSyntax, Tag};
15
16/// TOML, read by the `toml` crate. Its extension is `toml`.
17#[derive(Clone, Copy, Debug)]
18pub struct Toml;
19
20/// The TOML format, for [`Formats::add`](crate::Formats::add).
21pub static TOML: Toml = Toml;
22
23/// What the `toml` crate's parser says of a key written twice, at the repeated
24/// key. The error carries no kind to match instead.
25const REPEATED_KEY: &str = "duplicate key";
26
27impl Format for Toml {
28    fn name(&self) -> &'static str {
29        "toml"
30    }
31
32    fn extensions(&self) -> &'static [&'static str] {
33        &["toml"]
34    }
35
36    /// TOML forbids a duplicate key and has no merge key, so both readings give
37    /// the same tree or refuse the same text.
38    fn read(&self, text: &str, limits: &Limits, _reading: Reading) -> Result<Node, Refusal> {
39        let bounds = limits.bounds();
40        if text.len() > bounds.input_bytes {
41            let exceeded = Exceeded::input_bytes(bounds.input_bytes, Raise::FOR_TEXT);
42            return Err(Refusal::new(exceeded.fault(), None, None));
43        }
44        let root = DeTable::parse(text).map_err(|error| {
45            let span = error.span();
46            let fault = if error.message() == REPEATED_KEY {
47                let written = span.clone().and_then(|at| text.get(at)).unwrap_or_default();
48                Fault::DuplicateKey {
49                    key: key_name(written),
50                }
51            } else {
52                Fault::Syntax {
53                    detail: error.message().to_owned(),
54                }
55            };
56            Refusal::new(fault, span, None)
57        })?;
58        let tree = table(text, root.span(), root.get_ref());
59        Measure::new(bounds, Raise::FOR_TEXT)
60            .node(&tree, 1)
61            .map_err(|refused| Refusal::new(refused.exceeded.fault(), Some(refused.at), None))?;
62        Ok(tree)
63    }
64
65    /// Resolves by the type the scalar's syntax gave it, and never by its
66    /// text. A scalar that carries no syntax, such as one another format built,
67    /// is text.
68    fn resolve<'a>(
69        &self,
70        scalar: &'a Scalar,
71        _tag: Option<&Tag>,
72        wanted: Wanted,
73    ) -> Result<Resolved<'a>, Mismatch> {
74        let text = scalar.value();
75        let resolved = match (scalar.syntax().unwrap_or(ScalarSyntax::Text), wanted) {
76            (ScalarSyntax::Text | ScalarSyntax::Datetime, Wanted::Any | Wanted::Str) => {
77                Some(Resolved::Str(Cow::Borrowed(text)))
78            }
79            (ScalarSyntax::Boolean, Wanted::Any | Wanted::Bool) => {
80                Some(Resolved::Bool(text == "true"))
81            }
82            (ScalarSyntax::Integer, Wanted::Any | Wanted::Int) => integer(text),
83            (ScalarSyntax::Integer, Wanted::Float) => {
84                integer(text).and_then(|_| text.parse().ok().map(Resolved::Float))
85            }
86            (ScalarSyntax::Float, Wanted::Any | Wanted::Float) => float(text),
87            _ => None,
88        };
89        resolved.ok_or(Mismatch::new(wanted))
90    }
91}
92
93/// The name of the key written as `written`, as TOML reads it, without quotes
94/// or escapes: the last key of the dotted path the `toml` crate builds from
95/// `written = 0`. Text that reads as no key is returned as written.
96fn key_name(written: &str) -> String {
97    let entry = format!("{written} = 0");
98    let Ok(root) = DeTable::parse(&entry) else {
99        return written.to_owned();
100    };
101    let mut name = None;
102    let mut level = root.get_ref();
103    while let Some((key, value)) = level.iter().next() {
104        name = Some(key.get_ref().to_string());
105        let DeValue::Table(inner) = value.get_ref() else {
106            break;
107        };
108        level = inner;
109    }
110    name.unwrap_or_else(|| written.to_owned())
111}
112
113/// The integer a canonical integer text spells: an `i128`, or a `u128` above
114/// it. A text no `u128` holds is no integer.
115fn integer(text: &str) -> Option<Resolved<'static>> {
116    text.parse()
117        .map(Resolved::Int)
118        .or_else(|_| text.parse().map(Resolved::Uint))
119        .ok()
120}
121
122/// The float a float's text spells. An overflow to infinity is refused unless
123/// the text spells infinity, as the `toml` crate refuses it.
124fn float(text: &str) -> Option<Resolved<'static>> {
125    text.parse::<f64>()
126        .ok()
127        .filter(|value| !value.is_infinite() || text.contains("inf"))
128        .map(Resolved::Float)
129}
130
131/// The mapping for `table`, its entries in the order written: a parsed table
132/// iterates by key, not by position.
133fn table(text: &str, span: Range<usize>, table: &DeTable<'_>) -> Node {
134    let mut entries: Vec<_> = table.iter().collect();
135    entries.sort_unstable_by_key(|(key, _)| key.span().start);
136    Node::mapping(
137        span,
138        entries
139            .into_iter()
140            .map(|(key, value)| (key_node(text, key), value_node(text, value)))
141            .collect(),
142    )
143}
144
145/// A key as a scalar of its processed text.
146fn key_node(text: &str, key: &Spanned<DeString<'_>>) -> Node {
147    let span = key.span();
148    let style = style(text, &span);
149    let scalar = Scalar::new(key.get_ref().to_string(), style).with_syntax(ScalarSyntax::Text);
150    Node::scalar(span, scalar)
151}
152
153/// The node for a value, with the type its syntax gave it. An integer is its
154/// canonical decimal text, so a hex `0xff` is `255`; one no `u128` holds keeps
155/// its written digits and radix prefix, which no integer reads. A datetime is
156/// its text.
157fn value_node(text: &str, value: &Spanned<DeValue<'_>>) -> Node {
158    let span = value.span();
159    let plain = |written: String, syntax: ScalarSyntax| {
160        let scalar = Scalar::new(written, ScalarStyle::Plain).with_syntax(syntax);
161        Node::scalar(span.clone(), scalar)
162    };
163    match value.get_ref() {
164        DeValue::Table(entries) => table(text, span.clone(), entries),
165        DeValue::Array(items) => Node::sequence(
166            span.clone(),
167            items.iter().map(|item| value_node(text, item)).collect(),
168        ),
169        DeValue::String(string) => {
170            let scalar =
171                Scalar::new(string.to_string(), style(text, &span)).with_syntax(ScalarSyntax::Text);
172            Node::scalar(span.clone(), scalar)
173        }
174        DeValue::Integer(integer) => plain(canonical(integer), ScalarSyntax::Integer),
175        DeValue::Float(number) => plain(number.as_str().to_owned(), ScalarSyntax::Float),
176        DeValue::Boolean(boolean) => plain(boolean.to_string(), ScalarSyntax::Boolean),
177        DeValue::Datetime(datetime) => plain(datetime.to_string(), ScalarSyntax::Datetime),
178    }
179}
180
181/// The decimal text of an integer, from an `i128` or else a `u128`, or its
182/// written digits with their radix prefix when no `u128` holds it.
183fn canonical(integer: &DeInteger<'_>) -> String {
184    let (digits, radix) = (integer.as_str(), integer.radix());
185    i128::from_str_radix(digits, radix)
186        .map(|number| number.to_string())
187        .or_else(|_| u128::from_str_radix(digits, radix).map(|number| number.to_string()))
188        .unwrap_or_else(|_| integer.to_string())
189}
190
191/// How the string or key written at `span` is quoted, from its first bytes.
192fn style(text: &str, span: &Range<usize>) -> ScalarStyle {
193    let written = text.get(span.clone()).unwrap_or_default();
194    if written.starts_with("\"\"\"") {
195        ScalarStyle::MultilineBasic
196    } else if written.starts_with("'''") {
197        ScalarStyle::MultilineLiteral
198    } else if written.starts_with('"') {
199        ScalarStyle::DoubleQuoted
200    } else if written.starts_with('\'') {
201        ScalarStyle::SingleQuoted
202    } else {
203        ScalarStyle::Plain
204    }
205}
206
207/// A limit a tree went past, and where in the text.
208struct Refused {
209    exceeded: Exceeded,
210    at: Range<usize>,
211}
212
213/// Walks the tree in the order it was written, counting depth and nodes
214/// against the limits in force. `max_depth` is YAML's rule too: a table or
215/// an array is one level, and the root table is the first.
216struct Measure {
217    max_depth: usize,
218    max_nodes: usize,
219    nodes: usize,
220    raise: Raise,
221}
222
223impl Measure {
224    /// A count at zero nodes under `bounds`.
225    fn new(bounds: Bounds, raise: Raise) -> Self {
226        Self {
227            max_depth: bounds.depth,
228            max_nodes: bounds.nodes,
229            nodes: 0,
230            raise,
231        }
232    }
233
234    /// A node at `depth`, then its children in the order they were written.
235    fn node(&mut self, node: &Node, depth: usize) -> Result<(), Refused> {
236        let span = node.span();
237        match node.kind() {
238            NodeKind::Mapping(entries) => {
239                self.container(&span, depth)?;
240                entries
241                    .iter()
242                    .try_for_each(|(_, value)| self.node(value, depth + 1))
243            }
244            NodeKind::Sequence(items) => {
245                self.container(&span, depth)?;
246                items.iter().try_for_each(|item| self.node(item, depth + 1))
247            }
248            NodeKind::Scalar(_) => self.count(&span),
249        }
250    }
251
252    /// A table or an array: one level deeper, and one node.
253    fn container(&mut self, span: &Range<usize>, depth: usize) -> Result<(), Refused> {
254        if depth > self.max_depth {
255            return Err(self.refuse("max_depth", self.max_depth, span));
256        }
257        self.count(span)
258    }
259
260    fn count(&mut self, span: &Range<usize>) -> Result<(), Refused> {
261        self.nodes += 1;
262        if self.nodes > self.max_nodes {
263            return Err(self.refuse("max_nodes", self.max_nodes, span));
264        }
265        Ok(())
266    }
267
268    fn refuse(&self, field: &'static str, limit: usize, span: &Range<usize>) -> Refused {
269        Refused {
270            exceeded: Exceeded::new(field, limit, self.raise),
271            at: span.clone(),
272        }
273    }
274}