ctl_input/tree.rs
1//! The located tree every [format](crate::format::Format) reads a text into.
2//!
3//! A node keeps the bytes of the text it was written in, so a problem found
4//! later, in any format, is placed from the tree alone. A scalar keeps its
5//! processed value and the style it was written in, and a mapping keeps its
6//! key nodes beside its value nodes, in the order written.
7//!
8//! A format that expands aliases while it reads builds no alias node: a node
9//! it replays keeps the span of the node it copies, and
10//! [`Node::used_at`] holds where the alias was written.
11//!
12//! Every type is read-only and non-exhaustive, so a format outside this crate
13//! builds nodes through [`Node::scalar`], [`Node::sequence`],
14//! [`Node::mapping`], [`Scalar::new`] and [`Tag::new`], and a later release
15//! can add a field.
16
17use std::ops::Range;
18
19use super::{At, Step};
20
21/// One node of a text: its bytes, the alias that replayed it, its tag and what
22/// it holds.
23#[derive(Clone, Debug, PartialEq, Eq)]
24#[non_exhaustive]
25pub struct Node {
26 span: Range<usize>,
27 used_at: Option<Range<usize>>,
28 tag: Option<Tag>,
29 kind: NodeKind,
30}
31
32/// What a [`Node`] holds.
33#[derive(Clone, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum NodeKind {
36 /// A scalar, with its processed value and style.
37 Scalar(Scalar),
38 /// The items of a sequence or array, in the order written.
39 Sequence(Vec<Node>),
40 /// The entries of a mapping or table, as a key node and a value node, in
41 /// the order written.
42 Mapping(Vec<(Node, Node)>),
43}
44
45/// A scalar's processed value and how it was written.
46///
47/// The value has its escapes, folding and chomping applied, as a `String`
48/// field receives it.
49#[derive(Clone, Debug, PartialEq, Eq)]
50#[non_exhaustive]
51pub struct Scalar {
52 value: String,
53 style: ScalarStyle,
54 syntax: Option<ScalarSyntax>,
55}
56
57/// How a scalar is written.
58///
59/// A TOML basic string is [`Self::DoubleQuoted`], a literal string
60/// [`Self::SingleQuoted`], and a TOML number, boolean or datetime
61/// [`Self::Plain`]. A JSON string and each JSON key are
62/// [`Self::DoubleQuoted`], and a JSON number, `true`, `false` and `null` are
63/// [`Self::Plain`].
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub enum ScalarStyle {
67 /// No quotes: a YAML plain scalar, a bare TOML key, or a TOML number,
68 /// boolean or datetime.
69 Plain,
70 /// A YAML single-quoted scalar, or a TOML literal string `'…'`.
71 SingleQuoted,
72 /// A YAML double-quoted scalar, or a TOML basic string `"…"`.
73 DoubleQuoted,
74 /// A YAML literal block scalar, `|`.
75 Literal,
76 /// A YAML folded block scalar, `>`.
77 Folded,
78 /// A TOML multi-line basic string, `"""…"""`.
79 MultilineBasic,
80 /// A TOML multi-line literal string, `'''…'''`.
81 MultilineLiteral,
82}
83
84/// The type a format's syntax gave a scalar, for a format that types a value by
85/// how it is written, such as TOML and JSON.
86///
87/// A format whose scalar rules read the text, such as YAML, sets none, and
88/// [`Scalar::syntax`] is `None`.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90#[non_exhaustive]
91pub enum ScalarSyntax {
92 /// Text: a string, or a key.
93 Text,
94 /// An integer, as its canonical decimal text.
95 Integer,
96 /// A floating-point number.
97 Float,
98 /// A boolean, as `true` or `false`.
99 Boolean,
100 /// A date, a time or both, as its text.
101 Datetime,
102 /// A null, as `null`.
103 Null,
104}
105
106/// The tag written on a node, in the spelling of serde-saphyr's `Tagged`:
107/// `!override` for a local tag, and the resolved handle and suffix otherwise,
108/// such as `tag:yaml.org,2002:str` for `!!str`.
109#[derive(Clone, Debug, PartialEq, Eq)]
110pub struct Tag(String);
111
112impl Node {
113 /// A scalar node written at `span`.
114 #[must_use]
115 pub fn scalar(span: Range<usize>, scalar: Scalar) -> Self {
116 Self::of(span, NodeKind::Scalar(scalar))
117 }
118
119 /// A sequence node written at `span`, with its items in the order
120 /// written.
121 #[must_use]
122 pub fn sequence(span: Range<usize>, items: Vec<Self>) -> Self {
123 Self::of(span, NodeKind::Sequence(items))
124 }
125
126 /// A mapping node written at `span`, with its key and value nodes in the
127 /// order written.
128 #[must_use]
129 pub fn mapping(span: Range<usize>, entries: Vec<(Self, Self)>) -> Self {
130 Self::of(span, NodeKind::Mapping(entries))
131 }
132
133 fn of(span: Range<usize>, kind: NodeKind) -> Self {
134 Self {
135 span,
136 used_at: None,
137 tag: None,
138 kind,
139 }
140 }
141
142 /// This node with the tag written on it.
143 #[must_use]
144 pub fn with_tag(mut self, tag: Tag) -> Self {
145 self.tag = Some(tag);
146 self
147 }
148
149 /// This node as replayed by the alias written at `used_at`.
150 #[must_use]
151 pub fn with_used_at(mut self, used_at: Range<usize>) -> Self {
152 self.used_at = Some(used_at);
153 self
154 }
155
156 /// The bytes of the node in the text, quotes and block indicators
157 /// included, so `text[node.span()]` is its source. A node an alias
158 /// replayed has the span of the node it copies.
159 ///
160 /// Two nodes have a span that is not their own source. A TOML table opened
161 /// by a `[header]` or by a dotted key spans that header or key, and a YAML
162 /// empty value, as in `b:`, has an empty span and the value `~`.
163 #[must_use]
164 pub fn span(&self) -> Range<usize> {
165 self.span.clone()
166 }
167
168 /// The span of the outermost alias that replayed this node, the one
169 /// written where the value is used. Every node beneath a replayed node
170 /// inherits it, and it is `None` for a node no alias replayed.
171 #[must_use]
172 pub fn used_at(&self) -> Option<Range<usize>> {
173 self.used_at.clone()
174 }
175
176 /// The tag written on the node, if any.
177 #[must_use]
178 pub fn tag(&self) -> Option<&Tag> {
179 self.tag.as_ref()
180 }
181
182 /// What the node holds.
183 #[must_use]
184 pub fn kind(&self) -> &NodeKind {
185 &self.kind
186 }
187
188 /// The span of the value `steps` reach, or of the last step that exists.
189 /// With [`At::Key`], the span of the key node that names it; an index
190 /// step and the root have no key, so they give their value.
191 ///
192 /// A key step matches the first entry, in the order written, whose key
193 /// node is a scalar with exactly that value, and that no alias wrote.
194 ///
195 /// A node an alias replayed sits where the alias is written, and so does
196 /// every node beneath it, because the text holds no other place for them.
197 /// A path stops at the replayed node, so a path through it gives that
198 /// node's place, and with [`At::Key`] the key of its entry.
199 pub(crate) fn nearest(&self, steps: &[Step], at: At) -> Range<usize> {
200 let mut found = self;
201 let mut key = None;
202 for step in steps {
203 if found.used_at.is_some() {
204 break;
205 }
206 let next = match (&found.kind, step) {
207 (NodeKind::Mapping(entries), Step::Key(name)) => entries
208 .iter()
209 .find(|(entry, _)| entry.names(name))
210 .map(|(entry, value)| (value, Some(entry))),
211 (NodeKind::Sequence(items), Step::Index(index)) => {
212 items.get(*index).map(|value| (value, None))
213 }
214 (NodeKind::Scalar(_) | NodeKind::Mapping(_), _)
215 | (NodeKind::Sequence(_), Step::Key(_)) => None,
216 };
217 let Some((next, named)) = next else { break };
218 (found, key) = (next, named);
219 }
220 match at {
221 At::Value => found.written_at(),
222 At::Key => key.unwrap_or(found).written_at(),
223 }
224 }
225
226 /// Where the node is written: the alias that replayed it, or its own
227 /// bytes.
228 fn written_at(&self) -> Range<usize> {
229 self.used_at.clone().unwrap_or_else(|| self.span())
230 }
231
232 /// Whether this node is a scalar the text wrote whose value is exactly
233 /// `name`: a key an alias wrote is no name a path can reach.
234 fn names(&self, name: &str) -> bool {
235 self.used_at.is_none()
236 && matches!(&self.kind, NodeKind::Scalar(scalar) if scalar.value == name)
237 }
238}
239
240impl Scalar {
241 /// A scalar with its processed `value`, written in `style`, with no
242 /// syntax type.
243 #[must_use]
244 pub fn new(value: impl Into<String>, style: ScalarStyle) -> Self {
245 Self {
246 value: value.into(),
247 style,
248 syntax: None,
249 }
250 }
251
252 /// This scalar with the type its format's syntax gave it.
253 #[must_use]
254 pub fn with_syntax(mut self, syntax: ScalarSyntax) -> Self {
255 self.syntax = Some(syntax);
256 self
257 }
258
259 /// The processed value.
260 #[must_use]
261 pub fn value(&self) -> &str {
262 &self.value
263 }
264
265 /// How the scalar was written.
266 #[must_use]
267 pub fn style(&self) -> ScalarStyle {
268 self.style
269 }
270
271 /// The type the format's syntax gave the scalar, if the format types a
272 /// value that way.
273 #[must_use]
274 pub fn syntax(&self) -> Option<ScalarSyntax> {
275 self.syntax
276 }
277}
278
279impl Tag {
280 /// A tag in the spelling described on [`Tag`].
281 #[must_use]
282 pub fn new(spelling: impl Into<String>) -> Self {
283 Self(spelling.into())
284 }
285
286 /// The spelling the tag was built with.
287 #[must_use]
288 pub fn as_str(&self) -> &str {
289 &self.0
290 }
291}
292
293/// The 1-based line and column, counted in characters, of byte `offset` in
294/// `text`. An offset past the end, as at an unclosed array, is the end.
295///
296/// A leading byte order mark (U+FEFF) is no column, as the YAML parser counts.
297pub(crate) fn position(text: &str, offset: usize) -> (usize, usize) {
298 let (text, offset) = match text.strip_prefix('\u{feff}') {
299 Some(rest) => (rest, offset.saturating_sub('\u{feff}'.len_utf8())),
300 None => (text, offset),
301 };
302 let before = String::from_utf8_lossy(&text.as_bytes()[..offset.min(text.len())]);
303 let line = before.split('\n').count();
304 let column = 1 + before
305 .rsplit('\n')
306 .next()
307 .map_or(0, |last| last.chars().count());
308 (line, column)
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314
315 fn plain(span: Range<usize>, value: &str) -> Node {
316 Node::scalar(span, Scalar::new(value, ScalarStyle::Plain))
317 }
318
319 /// `a: [x, y]` as a format would build it.
320 fn tree() -> Node {
321 let list = Node::sequence(3..9, vec![plain(4..5, "x"), plain(7..8, "y")]);
322 Node::mapping(0..9, vec![(plain(0..1, "a"), list)])
323 }
324
325 #[test]
326 fn a_path_gives_its_value_or_its_key() {
327 let steps = [Step::Key("a".to_owned()), Step::Index(1)];
328 assert_eq!(tree().nearest(&steps, At::Value), 7..8);
329 assert_eq!(tree().nearest(&steps, At::Key), 7..8);
330 assert_eq!(tree().nearest(&steps[..1], At::Key), 0..1);
331 assert_eq!(tree().nearest(&[], At::Key), 0..9);
332 }
333
334 #[test]
335 fn a_missing_step_gives_the_last_one_that_exists() {
336 let steps = [Step::Key("a".to_owned()), Step::Key("b".to_owned())];
337 assert_eq!(tree().nearest(&steps, At::Value), 3..9);
338 assert_eq!(tree().nearest(&steps, At::Key), 0..1);
339 }
340
341 #[test]
342 fn a_position_counts_characters() {
343 assert_eq!(position("é: 1\nb", 6), (2, 1));
344 assert_eq!(position("é: 1\nb", 3), (1, 3));
345 }
346
347 #[test]
348 fn a_leading_byte_order_mark_is_no_column() {
349 let text = "\u{feff}a: 1\nb";
350 assert_eq!(position(text, 0), (1, 1));
351 assert_eq!(position(text, 3), (1, 1));
352 assert_eq!(position(text, 6), (1, 4));
353 assert_eq!(position(text, 8), (2, 1));
354 }
355}