yamled 0.0.13

Format-preserving YAML edits: change what you meant, keep every other byte
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::collections::BTreeSet;
use std::ops::Range;

use granit_parser::{Event, Parser, ScalarStyle, StructureStyle};

use crate::text::{LF, block_header, line_end, line_start, trim_end};
use crate::{Error, Path, Segment};

/// How a node is written in the source.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Style {
    /// A plain scalar: `value`.
    Plain,
    /// A single-quoted scalar: `'value'`.
    SingleQuoted,
    /// A double-quoted scalar: `"value"`.
    DoubleQuoted,
    /// A literal block scalar: `|`.
    Literal,
    /// A folded block scalar: `>`.
    Folded,
    /// An alias to an anchored node: `*name`.
    Alias,
    /// A sequence written one `- ` item per line.
    BlockSequence,
    /// A sequence written as `[a, b]`.
    FlowSequence,
    /// A mapping written one `key: value` per line.
    BlockMapping,
    /// A mapping written as `{k: v}`.
    FlowMapping,
}

impl Style {
    pub(crate) const fn is_block_collection(self) -> bool {
        matches!(self, Self::BlockSequence | Self::BlockMapping)
    }

    #[cfg(feature = "serde")]
    pub(crate) const fn is_scalar(self) -> bool {
        matches!(
            self,
            Self::Plain | Self::SingleQuoted | Self::DoubleQuoted | Self::Literal | Self::Folded
        )
    }
}

/// A byte range in the source, with the line and column where it starts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Location {
    /// First byte.
    pub start: usize,
    /// One past the last byte.
    pub end: usize,
    /// 1-based line of `start`.
    pub line: usize,
    /// 1-based column of `start`, counted in characters.
    pub column: usize,
}

impl Location {
    pub(crate) fn of(source: &str, range: Range<usize>) -> Self {
        let line = source[..range.start].matches(LF).count() + 1;
        let column = source[line_start(source, range.start)..range.start]
            .chars()
            .count()
            + 1;
        Self {
            start: range.start,
            end: range.end,
            line,
            column,
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct Key {
    pub(crate) text: String,
    pub(crate) range: Range<usize>,
}

#[derive(Clone, Debug)]
pub(crate) struct Node {
    pub(crate) value: Range<usize>,
    pub(crate) key: Option<Key>,
    pub(crate) style: Style,
    pub(crate) parent: Option<usize>,
    pub(crate) children: Vec<usize>,
}

/// Every node of one document, in an arena whose first entry is the root.
#[derive(Clone, Debug)]
pub(crate) struct Index {
    pub(crate) nodes: Vec<Node>,
    comment_lines: BTreeSet<usize>,
}

struct Frame {
    node: usize,
    pending_key: Option<Key>,
    expect_key: bool,
    flow: bool,
}

/// The state of one pass over the parser's events.
#[derive(Default)]
struct Builder {
    nodes: Vec<Node>,
    stack: Vec<Frame>,
    comment_lines: BTreeSet<usize>,
    documents: usize,
}

impl Builder {
    /// Index one parser event.
    ///
    /// An unresolved alias is indexed as an alias. [`Index::build`] parses
    /// with granit-parser's default options, which refuse an unknown alias
    /// as a parse error, so the event arrives only if those options change.
    /// It then occupies a node position, and granit-parser asks a consumer
    /// to keep it as a node. An anchor event is metadata after the node it
    /// names, which the index already holds. `Event` is non-exhaustive, so
    /// the last arm takes a variant a later granit-parser adds; it carries
    /// nothing the index tracks until this match names it.
    fn event(
        &mut self,
        source: &str,
        event: Event<'_>,
        start: usize,
        end: usize,
    ) -> Result<(), Error> {
        match event {
            Event::DocumentStart(..) => {
                self.documents += 1;
                if self.documents > 1 {
                    return Err(Error::Unsupported {
                        path: Path::root(),
                        what: "edit a stream of several documents",
                    });
                }
            }
            Event::Comment(..) => {
                let line = line_start(source, start);
                if source[line..start].trim().is_empty() {
                    self.comment_lines.insert(line);
                }
            }
            Event::Scalar(text, style, _, _) => {
                self.scalar(source, text.into_owned(), style, start, end);
            }
            Event::Alias(_) | Event::UnresolvedAlias(_) => {
                let alias = Node::leaf(start..end, Style::Alias);
                if self.in_key_position() {
                    self.detach_key(alias);
                } else {
                    self.attach(alias);
                }
            }
            Event::SequenceStart(structure, ..) => self.open(false, structure, start),
            Event::MappingStart(structure, ..) => self.open(true, structure, start),
            Event::SequenceEnd | Event::MappingEnd => {
                if let Some(frame) = self.stack.pop()
                    && frame.flow
                {
                    self.nodes[frame.node].value.end = end;
                }
            }
            Event::StreamStart | Event::StreamEnd | Event::DocumentEnd | Event::Anchor(..) => {}
            #[expect(
                clippy::match_same_arms,
                reason = "Event is non-exhaustive; a later variant carries nothing this index tracks"
            )]
            _ => {}
        }
        Ok(())
    }

    fn scalar(&mut self, source: &str, text: String, style: ScalarStyle, start: usize, end: usize) {
        if let Some(top) = self.stack.last_mut()
            && top.expect_key
        {
            top.pending_key = Some(Key {
                text,
                range: start..end,
            });
            top.expect_key = false;
            return;
        }
        let range = match style {
            ScalarStyle::Literal | ScalarStyle::Folded => match block_header(source, start) {
                Some(header) => header..block_end(source, header, end),
                None => start..trim_end(source, start, end),
            },
            ScalarStyle::Plain | ScalarStyle::SingleQuoted | ScalarStyle::DoubleQuoted => {
                start..trim_end(source, start, end)
            }
        };
        self.attach(Node::leaf(range, scalar_style(style)));
    }

    fn open(&mut self, mapping: bool, structure: StructureStyle, start: usize) {
        let flow = matches!(structure, StructureStyle::Flow);
        let style = match (mapping, flow) {
            (true, true) => Style::FlowMapping,
            (true, false) => Style::BlockMapping,
            (false, true) => Style::FlowSequence,
            (false, false) => Style::BlockSequence,
        };
        let leaf = Node::leaf(start..start, style);
        let node = if self.in_key_position() {
            self.detach_key(leaf)
        } else {
            self.attach(leaf)
        };
        self.stack.push(Frame {
            node,
            pending_key: None,
            expect_key: mapping,
            flow,
        });
    }

    /// Whether the next node is the key of a mapping entry.
    fn in_key_position(&self) -> bool {
        self.stack.last().is_some_and(|top| top.expect_key)
    }

    /// Holds a node that is the key of a mapping entry and is not a scalar,
    /// such as `? [a, b]` or `*alias :`, in the arena and in no entry.
    /// The value after it becomes an entry with no key text, which a lookup
    /// by key never finds and `Node::entries` leaves out.
    fn detach_key(&mut self, mut node: Node) -> usize {
        let id = self.nodes.len();
        if let Some(top) = self.stack.last_mut() {
            node.parent = Some(top.node);
            top.expect_key = false;
        }
        self.nodes.push(node);
        id
    }

    fn attach(&mut self, mut node: Node) -> usize {
        let id = self.nodes.len();
        if let Some(top) = self.stack.last_mut() {
            node.parent = Some(top.node);
            node.key = top.pending_key.take();
            top.expect_key = matches!(
                self.nodes[top.node].style,
                Style::BlockMapping | Style::FlowMapping
            );
            self.nodes[top.node].children.push(id);
        }
        self.nodes.push(node);
        id
    }

    /// A block collection ends at the end of its last value. The parser
    /// reports a later end: the start of the next token after any blank
    /// lines and comments.
    fn finish(mut self) -> Index {
        for node in (0..self.nodes.len()).rev() {
            if self.nodes[node].style.is_block_collection()
                && let Some(end) = self.nodes[node]
                    .children
                    .iter()
                    .map(|&child| self.nodes[child].value.end)
                    .max()
            {
                self.nodes[node].value.end = end;
            }
        }
        Index {
            nodes: self.nodes,
            comment_lines: self.comment_lines,
        }
    }
}

impl Node {
    fn leaf(value: Range<usize>, style: Style) -> Self {
        Self {
            value,
            key: None,
            style,
            parent: None,
            children: Vec::new(),
        }
    }
}

impl Index {
    /// Index one document. The parse is also the validity check every edit
    /// relies on, which is why an edit rebuilds the whole index.
    pub(crate) fn build(source: &str) -> Result<Self, Error> {
        let mut builder = Builder::default();
        for next in Parser::new_from_str(source) {
            let (event, span) = next.map_err(|error| Error::Parse {
                line: error.marker().line(),
                column: error.marker().col() + 1,
                message: error.info(),
            })?;
            let start = span.start.byte_offset().unwrap_or(0);
            let end = span.end.byte_offset().unwrap_or(start);
            builder.event(source, event, start, end)?;
        }
        Ok(builder.finish())
    }

    /// The node a path leads to. A key segment that is a number addresses an
    /// index on a sequence, and an index segment addresses its spelling on a
    /// mapping, so a JSON pointer resolves without knowing the shape first.
    pub(crate) fn find(&self, path: &Path) -> Option<usize> {
        self.walk(path).ok()
    }

    /// How far a path resolves: the node reached and how many segments it
    /// consumed.
    pub(crate) fn walk(&self, path: &Path) -> Result<usize, (usize, usize)> {
        if self.nodes.is_empty() {
            return Err((0, 0));
        }
        let mut at = 0;
        for (depth, segment) in path.segments().iter().enumerate() {
            let node = &self.nodes[at];
            let child = match (node.style, segment) {
                (Style::BlockMapping | Style::FlowMapping, Segment::Key(key)) => {
                    self.child_by_key(at, key)
                }
                (Style::BlockMapping | Style::FlowMapping, Segment::Index(index)) => {
                    self.child_by_key(at, &index.to_string())
                }
                (Style::BlockSequence | Style::FlowSequence, Segment::Index(index)) => {
                    node.children.get(*index).copied()
                }
                (Style::BlockSequence | Style::FlowSequence, Segment::Key(key)) => key
                    .parse::<usize>()
                    .ok()
                    .and_then(|index| node.children.get(index).copied()),
                _ => None,
            };
            match child {
                Some(child) => at = child,
                None => return Err((at, depth)),
            }
        }
        Ok(at)
    }

    fn child_by_key(&self, node: usize, key: &str) -> Option<usize> {
        self.nodes[node].children.iter().copied().find(|&child| {
            self.nodes[child]
                .key
                .as_ref()
                .is_some_and(|k| k.text == key)
        })
    }

    /// Where a node's entry begins: its key for a mapping value, else its
    /// value. A sequence item's dash sits on the same line.
    pub(crate) fn entry_start(&self, node: usize) -> usize {
        let node = &self.nodes[node];
        node.key
            .as_ref()
            .map_or(node.value.start, |key| key.range.start)
    }

    /// The first byte a node owns: the start of its entry's line, moved up
    /// over comment lines that sit directly above it.
    pub(crate) fn owned_start(&self, source: &str, node: usize) -> usize {
        let mut start = line_start(source, self.entry_start(node));
        while start > 0 {
            let previous = line_start(source, start - 1);
            if self.comment_lines.contains(&previous) {
                start = previous;
            } else {
                break;
            }
        }
        start
    }
}

/// Where a block scalar's last content line ends. The parser's span runs on
/// to the next token, over blank lines and the next line's indentation. A
/// line is content when it holds text, or holds only spaces that reach past
/// the text's indentation; a block with no content ends at its header.
fn block_end(source: &str, header: usize, span_end: usize) -> usize {
    let header_end = header
        + source[header..]
            .find(char::is_whitespace)
            .unwrap_or(source.len() - header);
    let body = line_end(source, header_end);
    let region = source.get(body..span_end).unwrap_or_default();
    let Some(indent) = region
        .lines()
        .find(|line| !line.trim().is_empty())
        .map(|line| line.len() - line.trim_start().len())
    else {
        return header_end;
    };
    let mut end = header_end;
    let mut at = body;
    for line in region.split_inclusive(LF) {
        let content = line.trim_end_matches(LF);
        if !content.trim().is_empty() || content.len() > indent {
            end = at + content.len();
        }
        at += line.len();
    }
    end
}

fn scalar_style(style: ScalarStyle) -> Style {
    match style {
        ScalarStyle::SingleQuoted => Style::SingleQuoted,
        ScalarStyle::DoubleQuoted => Style::DoubleQuoted,
        ScalarStyle::Literal => Style::Literal,
        ScalarStyle::Folded => Style::Folded,
        ScalarStyle::Plain => Style::Plain,
    }
}

#[cfg(test)]
mod tests {
    use std::borrow::Cow;

    use granit_parser::{Event, StructureStyle};

    use super::{Builder, Style};

    #[test]
    fn an_unresolved_alias_is_indexed_as_an_alias() {
        let source = "[*missing]";
        let mut builder = Builder::default();
        let events = [
            (Event::SequenceStart(StructureStyle::Flow, 0, None), 0, 1),
            (Event::UnresolvedAlias(Cow::Borrowed("missing")), 1, 9),
            (Event::SequenceEnd, 9, 10),
        ];
        for (event, start, end) in events {
            builder.event(source, event, start, end).unwrap();
        }
        let index = builder.finish();
        let styles: Vec<Style> = index.nodes.iter().map(|node| node.style).collect();
        assert_eq!(styles, [Style::FlowSequence, Style::Alias]);
        assert_eq!(index.nodes[0].children, [1]);
        assert_eq!(&source[index.nodes[1].value.clone()], "*missing");
    }
}