yaml-rt-core 0.1.0

Dependency-free YAML 1.2.2 lossless parser and editor core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use crate::{NodeId, SemanticKind, YamlDoc, YamlError, YamlScalarStyle};

/// A parsed YAML value document containing exactly one root node.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct YamlFragment {
    doc: YamlDoc,
    root: NodeId,
}

impl YamlFragment {
    /// Parses an owned YAML value.
    pub fn parse_owned(input: String) -> Result<Self, FragmentError> {
        let doc = YamlDoc::parse_owned(input).map_err(FragmentError::from)?;
        if doc.document_count() != 1 {
            return Err(FragmentError::new(format!(
                "a YAML value must contain exactly one document, found {}",
                doc.document_count()
            )));
        }
        let root = doc
            .document_root(0)
            .map_err(FragmentError::from)?
            .ok_or_else(|| FragmentError::new("a YAML value must contain one root node"))?;
        let fragment = Self { doc, root };
        fragment.validate_alias_scope()?;
        Ok(fragment)
    }

    /// Parses a borrowed YAML value.
    pub fn parse(input: &str) -> Result<Self, FragmentError> {
        Self::parse_owned(input.to_owned())
    }

    /// Returns the fragment's parsed document.
    #[must_use]
    pub fn document(&self) -> &YamlDoc {
        &self.doc
    }

    /// Returns the fragment root node.
    #[must_use]
    pub const fn root(&self) -> NodeId {
        self.root
    }

    /// Returns the root as minimally de-indented standalone YAML.
    pub fn to_yaml(&self) -> Result<String, FragmentError> {
        self.doc
            .extract_node(self.root)
            .map_err(FragmentError::from)
    }

    pub(crate) fn contains_anchor(&self) -> bool {
        self.subtree_nodes()
            .any(|node| self.doc.anchor(node).is_some())
    }

    pub(crate) fn from_document_node(doc: &YamlDoc, root: NodeId) -> Result<Self, FragmentError> {
        doc.node(root)
            .ok_or_else(|| FragmentError::new("fragment source node is missing"))?;
        Ok(Self {
            doc: doc.clone(),
            root,
        })
    }

    pub(crate) fn prepared(&self, target: &YamlDoc) -> Result<Self, FragmentError> {
        let mut used = target.anchor_names();
        let mut renamed = BTreeMap::new();
        for node in self.subtree_nodes() {
            let Some(name) = self.doc.anchor(node) else {
                continue;
            };
            if used.insert(name.to_owned()) {
                continue;
            }
            let mut suffix = 1_u64;
            let replacement = loop {
                let candidate = format!("{name}_{suffix}");
                if used.insert(candidate.clone()) {
                    break candidate;
                }
                suffix = suffix.saturating_add(1);
            };
            renamed.insert(name.to_owned(), replacement);
        }
        if renamed.is_empty() {
            return Ok(self.clone());
        }

        let mut doc = self.doc.clone();
        let nodes = self.subtree_nodes().collect::<Vec<_>>();
        for node in nodes {
            let Some(properties) = doc.semantics.properties(node) else {
                continue;
            };
            if let Some(span) = properties.anchor {
                let old = doc.source.slice(span);
                if let Some(new) = renamed.get(old) {
                    doc.queue_edit(span, new.clone())
                        .map_err(FragmentError::from)?;
                }
            }
            if let Some(span) = properties.alias {
                let old = doc.source.slice(span);
                if let Some(new) = renamed.get(old) {
                    doc.queue_edit(span, new.clone())
                        .map_err(FragmentError::from)?;
                }
            }
        }
        doc.commit_edits().map_err(FragmentError::from)?;
        let root = doc
            .document_root(0)
            .map_err(FragmentError::from)?
            .ok_or_else(|| FragmentError::new("prepared fragment lost its root node"))?;
        Ok(Self { doc, root })
    }

    pub(crate) fn render_flow(&self, target: &YamlDoc) -> Result<String, FragmentError> {
        let prepared = self.prepared(target)?;
        prepared.render_node_flow(prepared.root, 0)
    }

    fn render_node_flow(&self, node: NodeId, depth: usize) -> Result<String, FragmentError> {
        if depth > 1024 {
            return Err(FragmentError::new(
                "fragment rendering recursion limit exceeded",
            ));
        }
        match self.doc.semantic_kind(node) {
            Some(SemanticKind::Alias) => Ok(format!(
                "*{}",
                self.doc.alias_name(node).unwrap_or_default()
            )),
            Some(SemanticKind::Scalar { style }) => {
                let prefix = self.property_prefix(node);
                if matches!(style, YamlScalarStyle::Literal | YamlScalarStyle::Folded)
                    || self
                        .doc
                        .node(node)
                        .is_some_and(|node| node.span().is_empty())
                {
                    let value = self.doc.scalar_value(node).map_err(FragmentError::from)?;
                    Ok(format!("{prefix}{}", quote_string(&value)))
                } else {
                    let source = self.doc.extract_node(node).map_err(FragmentError::from)?;
                    if source.contains(['\n', '\r']) {
                        let value = self.doc.scalar_value(node).map_err(FragmentError::from)?;
                        Ok(format!("{prefix}{}", quote_string(&value)))
                    } else {
                        Ok(source)
                    }
                }
            }
            Some(SemanticKind::Sequence { .. }) => {
                let mut output = self.property_prefix(node);
                output.push('[');
                for (index, item) in self.doc.sequence_items(node).enumerate() {
                    if index > 0 {
                        output.push_str(", ");
                    }
                    output.push_str(&self.render_node_flow(item, depth + 1)?);
                }
                output.push(']');
                Ok(output)
            }
            Some(SemanticKind::Mapping { .. }) => {
                let mut output = self.property_prefix(node);
                output.push('{');
                for (index, (key, value)) in self.doc.mapping_entries(node).enumerate() {
                    if index > 0 {
                        output.push_str(", ");
                    }
                    output.push_str(&self.render_node_flow(key, depth + 1)?);
                    output.push_str(": ");
                    output.push_str(&self.render_node_flow(value, depth + 1)?);
                }
                output.push('}');
                Ok(output)
            }
            Some(SemanticKind::Document) | None => {
                Err(FragmentError::new("cannot render unknown YAML node"))
            }
        }
    }

    fn property_prefix(&self, node: NodeId) -> String {
        let mut prefix = String::new();
        if let Some(tag) = self.doc.raw_tag(node) {
            prefix.push_str(tag);
            prefix.push(' ');
        }
        if let Some(anchor) = self.doc.anchor(node) {
            prefix.push('&');
            prefix.push_str(anchor);
            prefix.push(' ');
        }
        prefix
    }

    fn subtree_nodes(&self) -> impl Iterator<Item = NodeId> + '_ {
        let span = self.doc.node(self.root).map(|node| node.span());
        self.doc
            .nodes
            .iter()
            .enumerate()
            .map(|(index, _)| NodeId::from_usize(index))
            .filter(move |node| {
                let Some(root_span) = span else {
                    return false;
                };
                self.doc.node(*node).is_some_and(|node| {
                    node.span().start >= root_span.start && node.span().end <= root_span.end
                })
            })
    }

    fn validate_alias_scope(&self) -> Result<(), FragmentError> {
        let root_span = self
            .doc
            .node(self.root)
            .map(|node| node.span())
            .ok_or_else(|| FragmentError::new("fragment root node is missing"))?;
        for node in self.subtree_nodes() {
            if !matches!(self.doc.semantic_kind(node), Some(SemanticKind::Alias)) {
                continue;
            }
            let target = self.doc.resolve_alias(node).ok_or_else(|| {
                FragmentError::new(format!(
                    "unresolved value alias `*{}`",
                    self.doc.alias_name(node).unwrap_or_default()
                ))
            })?;
            let target_span = self
                .doc
                .node(target)
                .map(|node| node.span())
                .ok_or_else(|| FragmentError::new("alias target is missing"))?;
            if target_span.start < root_span.start || target_span.end > root_span.end {
                return Err(FragmentError::new(
                    "a value alias cannot reference a node outside the value root",
                ));
            }
        }
        Ok(())
    }
}

impl YamlDoc {
    /// Extracts one semantic node as valid standalone YAML where possible.
    pub fn extract_node(&self, node: NodeId) -> Result<String, YamlError> {
        let node = self.expect_node(node)?;
        let source = self.source.slice(node.span);
        let line_start = self.source.as_str()[..node.span.start as usize]
            .rfind(['\n', '\r'])
            .map_or(0, |index| index + 1);
        let base_indent = self.source.as_str()[line_start..node.span.start as usize]
            .bytes()
            .take_while(|byte| *byte == b' ')
            .count();
        Ok(deindent_continuation_lines(source, base_indent))
    }

    pub(crate) fn anchor_names(&self) -> BTreeSet<String> {
        self.nodes
            .iter()
            .enumerate()
            .filter_map(|(index, _)| self.anchor(NodeId::from_usize(index)).map(str::to_owned))
            .collect()
    }
}

fn deindent_continuation_lines(source: &str, indent: usize) -> String {
    if indent == 0 || !source.contains(['\n', '\r']) {
        return source.to_owned();
    }
    let bytes = source.as_bytes();
    let mut output = String::with_capacity(source.len());
    let mut position = 0;
    let mut first = true;
    while position < bytes.len() {
        if !first {
            let mut removed = 0;
            while removed < indent && bytes.get(position) == Some(&b' ') {
                position += 1;
                removed += 1;
            }
        }
        first = false;
        let line_end = source[position..]
            .find(['\n', '\r'])
            .map_or(source.len(), |offset| position + offset);
        output.push_str(&source[position..line_end]);
        position = line_end;
        if bytes.get(position) == Some(&b'\r') {
            output.push('\r');
            position += 1;
            if bytes.get(position) == Some(&b'\n') {
                output.push('\n');
                position += 1;
            }
        } else if bytes.get(position) == Some(&b'\n') {
            output.push('\n');
            position += 1;
        }
    }
    output
}

pub(crate) fn indent_text(source: &str, indent: usize) -> String {
    if indent == 0 || source.is_empty() {
        return source.to_owned();
    }
    let prefix = " ".repeat(indent);
    let mut output = String::with_capacity(source.len() + prefix.len());
    let mut at_line_start = true;
    for character in source.chars() {
        if at_line_start && !matches!(character, '\r' | '\n') {
            output.push_str(&prefix);
            at_line_start = false;
        }
        output.push(character);
        if character == '\n' || character == '\r' {
            at_line_start = true;
        }
    }
    output
}

pub(crate) fn quote_string(value: &str) -> String {
    let mut output = String::from("\"");
    for character in value.chars() {
        match character {
            '"' => output.push_str("\\\""),
            '\\' => output.push_str("\\\\"),
            '\n' => output.push_str("\\n"),
            '\r' => output.push_str("\\r"),
            '\t' => output.push_str("\\t"),
            character if character.is_control() => {
                output.push_str(&format!("\\u{:04X}", u32::from(character)));
            }
            character => output.push(character),
        }
    }
    output.push('"');
    output
}

/// Failure to parse, validate, or render a YAML fragment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FragmentError {
    message: String,
}

impl FragmentError {
    pub(crate) fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for FragmentError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for FragmentError {}

impl From<YamlError> for FragmentError {
    fn from(error: YamlError) -> Self {
        Self::new(error.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fragment_requires_one_nonempty_document() {
        assert!(YamlFragment::parse("").is_err());
        assert!(YamlFragment::parse("--- a\n--- b\n").is_err());
        assert!(YamlFragment::parse("[a, b]").is_ok());
    }

    #[test]
    fn extraction_deindents_nested_block_nodes() {
        let doc = YamlDoc::parse("outer:\n  one: 1\n  two:\n    - a\n    - b\n").unwrap();
        let node = doc
            .get_mapping_value(doc.document_root_mapping(0).unwrap(), "outer")
            .unwrap()
            .unwrap();
        assert_eq!(
            doc.extract_node(node).unwrap(),
            "one: 1\ntwo:\n  - a\n  - b"
        );
    }

    #[test]
    fn rejects_unresolved_value_aliases() {
        assert!(YamlFragment::parse("*outside").is_err());
    }

    #[test]
    fn flow_rendering_normalizes_block_collections_only() {
        let fragment = YamlFragment::parse("one:\n  - a\n  - b\n").unwrap();
        let target = YamlDoc::parse("target: []\n").unwrap();
        assert_eq!(fragment.render_flow(&target).unwrap(), "{one: [a, b]}");
    }
}