ayaml 0.1.3

A safe, pure-Rust YAML parser, event stream, value model, Serde layer, and emitter
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Composition: turn a spanned event stream into `Value`s.
//!
//! The composer resolves scalars, builds ordered mappings and sequences,
//! registers anchors, materializes aliases within the alias budget, and
//! rejects duplicate mapping keys. Merge keys are deliberately not applied
//! here; an explicit adapter owns that behavior.
//!
//! Open collections live on an explicit stack, so nesting costs heap rather
//! than native stack. An anchor records where its node sits in the
//! tree being built, plus the node's size estimate and nesting height, so a
//! node is copied only when an alias materializes it.

use std::collections::HashMap;

use crate::error::{Error, ErrorKind};
use crate::event::{Anchor, Event};
use crate::limits::{AliasBudget, Limits};
use crate::mapping::Mapping;
use crate::resolver::resolve_scalar;
use crate::span::Span;
use crate::tag::{Tag, TaggedValue};
use crate::value::Value;

/// Compose every document in an event stream.
pub(crate) fn compose_documents(
    events: &[Event<'_>],
    input_len: usize,
    limits: &Limits,
) -> Result<Vec<Value>, Error> {
    compose_documents_with_budget(
        events.iter().cloned(),
        input_len,
        limits,
        &mut AliasBudget::default(),
    )
}

/// Compose every document in an event stream, charging aliases to a budget
/// that the caller keeps across calls.
pub(crate) fn compose_documents_with_budget<'a>(
    events: impl IntoIterator<Item = Event<'a>>,
    input_len: usize,
    limits: &Limits,
    budget: &mut AliasBudget,
) -> Result<Vec<Value>, Error> {
    let mut composer = StreamingComposer::with_budget(limits.clone(), input_len, *budget);
    for event in events {
        composer.event(event)?;
    }
    let (documents, spent) = composer.finish_with_budget()?;
    *budget = spent;
    Ok(documents)
}

/// Tag a collection. A core tag on a collection names a node of another kind, or restates its
/// kind, and is dropped; a custom tag is kept.
fn apply_tag(tag: Option<&Tag>, value: Value) -> Value {
    match tag {
        Some(tag) if !tag.is_core_collection() && !tag.is_core_scalar() => {
            Value::from(TaggedValue::new(tag.clone(), value))
        }
        _ => value,
    }
}

/// The size estimate of a scalar's value. Collections and aliases are summed
/// bottom-up by the composer instead.
fn estimate_size(value: &Value, node_cost: usize) -> usize {
    match value {
        Value::Null | Value::Bool(_) | Value::Number(_) => node_cost,
        Value::String(text) => node_cost.saturating_add(text.len()),
        Value::Sequence(sequence) => sequence.iter().fold(node_cost, |size, item| {
            size.saturating_add(estimate_size(item, node_cost))
        }),
        Value::Mapping(mapping) => mapping.iter().fold(node_cost, |size, (key, value)| {
            size.saturating_add(estimate_size(key, node_cost))
                .saturating_add(estimate_size(value, node_cost))
        }),
        Value::Tagged(tagged) => node_cost
            .saturating_add(tagged.tag.text_len())
            .saturating_add(estimate_size(&tagged.value, node_cost)),
    }
}

/// The anchors of the document being read, each with the nearest preceding node that
/// has it. A collection's anchor comes before its content, so from its start until its
/// end the collection is the nearest node for that anchor. No finished value can stand
/// for it yet, so an alias there is rejected, even when an earlier node has the anchor.
#[derive(Debug)]
pub(crate) struct Anchors<T> {
    nodes: HashMap<String, AnchorNode<T>>,
}

#[derive(Debug)]
enum AnchorNode<T> {
    /// A collection with this anchor hasn't ended.
    Open,
    Finished(T),
}

impl<T> Anchors<T> {
    pub(crate) fn new() -> Self {
        Self {
            nodes: HashMap::new(),
        }
    }

    /// Forget every anchor at the start of a document.
    pub(crate) fn clear(&mut self) {
        self.nodes.clear();
    }

    fn set(&mut self, anchor: &str, node: AnchorNode<T>) {
        match self.nodes.get_mut(anchor) {
            Some(entry) => *entry = node,
            None => {
                self.nodes.insert(anchor.to_owned(), node);
            }
        }
    }

    /// A collection with this anchor has started.
    pub(crate) fn open(&mut self, anchor: &str) {
        self.set(anchor, AnchorNode::Open);
    }

    /// A scalar with this anchor has been read.
    pub(crate) fn define(&mut self, anchor: &str, value: T) {
        self.set(anchor, AnchorNode::Finished(value));
    }

    /// A collection with this anchor has ended. A node inside it with the same anchor
    /// comes later in the document, so it stays the nearest: in `&x {k: &x v}`, `*x` is
    /// `v`.
    pub(crate) fn close(&mut self, anchor: &str, value: T) {
        if let Some(entry) = self.nodes.get_mut(anchor)
            && matches!(entry, AnchorNode::Open)
        {
            *entry = AnchorNode::Finished(value);
        }
    }

    /// The node an alias at this point refers to, or the message to reject it with.
    pub(crate) fn resolve(&self, anchor: &str) -> Result<&T, &'static str> {
        match self.nodes.get(anchor) {
            Some(AnchorNode::Finished(value)) => Ok(value),
            Some(AnchorNode::Open) => Err("an alias cannot refer to a collection that contains it"),
            None => Err("unknown anchor"),
        }
    }
}

/// One step from a collection to a child: a sequence item, or a mapping
/// entry's key or value, by position.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
    Item(usize),
    Key(usize),
    Value(usize),
}

/// Where an anchored node sits in the document being built, from the root
/// collection down, with its size estimate and nesting height.
#[derive(Clone, Debug)]
struct AnchorDef {
    path: Vec<Step>,
    size: usize,
    height: usize,
}

enum Frame<'a> {
    Sequence {
        tag: Option<Tag>,
        anchor: Option<Anchor<'a>>,
        items: Vec<Value>,
        span: Span,
        size: usize,
        height: usize,
    },
    Mapping {
        tag: Option<Tag>,
        anchor: Option<Anchor<'a>>,
        mapping: Mapping,
        pending_key: Option<(Value, Span)>,
        span: Span,
        size: usize,
        height: usize,
    },
}

impl Frame<'_> {
    /// Where the next finished child goes.
    fn position(&self) -> Step {
        match self {
            Self::Sequence { items, .. } => Step::Item(items.len()),
            Self::Mapping {
                mapping,
                pending_key: None,
                ..
            } => Step::Key(mapping.len()),
            Self::Mapping { mapping, .. } => Step::Value(mapping.len()),
        }
    }

    /// A finished child.
    fn child(&self, step: Step) -> Option<&Value> {
        match (self, step) {
            (Self::Sequence { items, .. }, Step::Item(index)) => items.get(index),
            (
                Self::Mapping {
                    mapping,
                    pending_key,
                    ..
                },
                Step::Key(index),
            ) => match mapping.get_index(index) {
                Some((key, _)) => Some(key),
                None if index == mapping.len() => pending_key.as_ref().map(|(key, _)| key),
                None => None,
            },
            (Self::Mapping { mapping, .. }, Step::Value(index)) => {
                mapping.get_index(index).map(|(_, value)| value)
            }
            _ => None,
        }
    }
}

/// A finished child of a finished collection, looking through tags.
fn child_of(mut value: &Value, step: Step) -> Option<&Value> {
    while let Value::Tagged(tagged) = value {
        value = &tagged.value;
    }
    match (value, step) {
        (Value::Sequence(items), Step::Item(index)) => items.get(index),
        (Value::Mapping(mapping), Step::Key(index)) => mapping.get_index(index).map(|(key, _)| key),
        (Value::Mapping(mapping), Step::Value(index)) => {
            mapping.get_index(index).map(|(_, value)| value)
        }
        _ => None,
    }
}

/// The value nesting height: the collections on its deepest path.
fn value_height(value: &Value) -> usize {
    match value {
        Value::Sequence(items) => 1 + items.iter().map(value_height).max().unwrap_or(0),
        Value::Mapping(mapping) => {
            1 + mapping
                .iter()
                .map(|(key, value)| value_height(key).max(value_height(value)))
                .max()
                .unwrap_or(0)
        }
        Value::Tagged(tagged) => value_height(&tagged.value),
        _ => 0,
    }
}

/// Event-driven composer behind `parse_value`, `parse_documents`, and the
/// document cursor.
pub(crate) struct StreamingComposer<'a> {
    limits: Limits,
    input_len: usize,
    anchors: Anchors<AnchorDef>,
    documents: Vec<Value>,
    document: Option<Value>,
    stack: Vec<Frame<'a>>,
    budget: AliasBudget,
}

impl<'a> StreamingComposer<'a> {
    pub(crate) fn new(limits: Limits, input_len: usize) -> Self {
        Self::with_budget(limits, input_len, AliasBudget::default())
    }

    pub(crate) fn with_budget(limits: Limits, input_len: usize, budget: AliasBudget) -> Self {
        Self {
            limits,
            input_len,
            anchors: Anchors::new(),
            documents: Vec::new(),
            document: None,
            stack: Vec::new(),
            budget,
        }
    }

    pub(crate) fn event(&mut self, event: Event<'a>) -> Result<(), Error> {
        match event {
            Event::StreamStart { .. } | Event::StreamEnd { .. } | Event::Directive { .. } => {}
            Event::DocumentStart { .. } => {
                if !self.stack.is_empty() {
                    return Err(Error::new(
                        ErrorKind::Composition,
                        "document started inside a collection",
                    ));
                }
                // Anchors are scoped to a document; an alias may not see a
                // definition from an earlier document.
                self.anchors.clear();
                self.document = None;
            }
            Event::DocumentEnd { span, .. } => {
                if !self.stack.is_empty() {
                    return Err(self.error_at(span, "document ended inside a collection"));
                }
                let value = self.document.take().unwrap_or(Value::Null);
                self.documents.push(value);
            }
            Event::Scalar {
                value,
                style,
                tag,
                anchor,
                span,
                ..
            } => {
                let resolved = resolve_scalar(value.as_ref(), style, tag.as_ref())
                    .map_err(|error| error.with_span(span))?;
                let size = estimate_size(&resolved, self.limits.node_cost_bytes);
                let height = value_height(&resolved);
                self.record_anchor(anchor.as_ref(), size, height, Anchors::define);
                self.feed(resolved, span, size, height)?;
            }
            Event::Alias { anchor, span } => {
                let definition = self
                    .anchors
                    .resolve(anchor.as_str())
                    .cloned()
                    .map_err(|message| self.error_at(span, message))?;
                // Charge before cloning: the clone is the allocation this
                // budget exists to bound.
                self.budget
                    .charge(&self.limits, self.input_len, definition.size)
                    .map_err(|error| error.with_span(span))?;
                // The alias nests its target here, so the target's
                // collections count toward the depth.
                if definition.height > 0 {
                    self.limits
                        .check_depth(self.stack.len() + definition.height)
                        .map_err(|error| Error::from(error).with_span(span))?;
                }
                let value = self
                    .anchored(&definition.path)
                    .cloned()
                    .ok_or_else(|| self.error_at(span, "unknown anchor"))?;
                self.feed(value, span, definition.size, definition.height)?;
            }
            Event::SequenceStart {
                tag, anchor, span, ..
            } => {
                self.limits
                    .check_depth(self.stack.len() + 1)
                    .map_err(|error| Error::from(error).with_span(span))?;
                if let Some(anchor) = &anchor {
                    self.anchors.open(anchor.as_str());
                }
                self.stack.push(Frame::Sequence {
                    tag,
                    anchor,
                    items: Vec::new(),
                    span,
                    size: self.limits.node_cost_bytes,
                    height: 0,
                });
            }
            Event::SequenceEnd { span } => {
                let Some(Frame::Sequence {
                    tag,
                    anchor,
                    items,
                    span: start_span,
                    size,
                    height,
                }) = self.stack.pop()
                else {
                    return Err(self.error_at(span, "unexpected sequence end"));
                };
                let (value, size) =
                    self.finish_collection(tag.as_ref(), Value::Sequence(items), size);
                self.record_anchor(anchor.as_ref(), size, height + 1, Anchors::close);
                self.feed(value, start_span, size, height + 1)?;
            }
            Event::MappingStart {
                tag, anchor, span, ..
            } => {
                self.limits
                    .check_depth(self.stack.len() + 1)
                    .map_err(|error| Error::from(error).with_span(span))?;
                if let Some(anchor) = &anchor {
                    self.anchors.open(anchor.as_str());
                }
                self.stack.push(Frame::Mapping {
                    tag,
                    anchor,
                    mapping: Mapping::new(),
                    pending_key: None,
                    span,
                    size: self.limits.node_cost_bytes,
                    height: 0,
                });
            }
            Event::MappingEnd { span } => {
                let Some(Frame::Mapping {
                    tag,
                    anchor,
                    mapping,
                    pending_key,
                    span: start_span,
                    size,
                    height,
                }) = self.stack.pop()
                else {
                    return Err(self.error_at(span, "unexpected mapping end"));
                };
                if let Some((key, key_span)) = pending_key {
                    return Err(Error::new(
                        ErrorKind::Composition,
                        format!("mapping key without value: {key:?}"),
                    )
                    .with_span(key_span));
                }
                let (value, size) =
                    self.finish_collection(tag.as_ref(), Value::Mapping(mapping), size);
                self.record_anchor(anchor.as_ref(), size, height + 1, Anchors::close);
                self.feed(value, start_span, size, height + 1)?;
            }
        }
        Ok(())
    }

    pub(crate) fn finish(self) -> Result<Vec<Value>, Error> {
        self.finish_with_budget().map(|(documents, _)| documents)
    }

    /// Finish the stream and hand back the alias budget it spent.
    pub(crate) fn finish_with_budget(self) -> Result<(Vec<Value>, AliasBudget), Error> {
        if !self.stack.is_empty() {
            return Err(Error::new(
                ErrorKind::Composition,
                "unterminated collection at end of stream",
            ));
        }
        Ok((self.documents, self.budget))
    }

    /// Tag a finished collection; a tag adds one node and its text to the size estimate.
    fn finish_collection(&self, tag: Option<&Tag>, value: Value, size: usize) -> (Value, usize) {
        let value = apply_tag(tag, value);
        let size = match &value {
            Value::Tagged(tagged) => size
                .saturating_add(self.limits.node_cost_bytes)
                .saturating_add(tagged.tag.text_len()),
            _ => size,
        };
        (value, size)
    }

    fn feed(&mut self, value: Value, span: Span, size: usize, height: usize) -> Result<(), Error> {
        match self.stack.last_mut() {
            Some(Frame::Sequence {
                items,
                size: total,
                height: deepest,
                ..
            }) => {
                *total = total.saturating_add(size);
                *deepest = (*deepest).max(height);
                items.push(value);
            }
            Some(Frame::Mapping {
                mapping,
                pending_key,
                size: total,
                height: deepest,
                ..
            }) => {
                *total = total.saturating_add(size);
                *deepest = (*deepest).max(height);
                if let Some((key, key_span)) = pending_key.take() {
                    if mapping.contains_key(&key) {
                        return Err(Error::new(
                            ErrorKind::DuplicateKey,
                            format!("duplicate mapping key: {}", crate::value::key_text(&key)),
                        )
                        .with_span(key_span));
                    }
                    mapping.insert(key, value);
                } else {
                    *pending_key = Some((value, span));
                }
            }
            None => {
                if self.document.is_some() {
                    return Err(self.error_at(span, "multiple root nodes in one document"));
                }
                self.document = Some(value);
            }
        }
        Ok(())
    }

    /// Note an anchored node about to be fed: its position is where each open collection
    /// will put its next child.
    fn record_anchor(
        &mut self,
        anchor: Option<&Anchor<'a>>,
        size: usize,
        height: usize,
        record: fn(&mut Anchors<AnchorDef>, &str, AnchorDef),
    ) {
        if let Some(anchor) = anchor {
            let path = self.stack.iter().map(Frame::position).collect();
            let definition = AnchorDef { path, size, height };
            record(&mut self.anchors, anchor.as_str(), definition);
        }
    }

    /// The finished node at `path`. The path's first steps run through the
    /// open collections; once a step leaves the open child, it reaches a
    /// finished value, and the rest of the path descends inside it.
    fn anchored(&self, path: &[Step]) -> Option<&Value> {
        for (depth, step) in path.iter().enumerate() {
            let frame = self.stack.get(depth)?;
            if depth + 1 < self.stack.len() && frame.position() == *step {
                continue;
            }
            let mut value = frame.child(*step)?;
            for step in &path[depth + 1..] {
                value = child_of(value, *step)?;
            }
            return Some(value);
        }
        None
    }

    #[allow(
        clippy::unused_self,
        reason = "the method is part of a uniform grammar or diagnostic surface"
    )]
    fn error_at(&self, span: Span, message: impl Into<String>) -> Error {
        Error::new(ErrorKind::Composition, message).with_span(span)
    }
}

#[cfg(test)]
mod tests {
    use super::compose_documents;
    use crate::error::ErrorKind;
    use crate::limits::Limits;
    use crate::parser::parse_events;
    use crate::value::Value;

    fn compose(input: &str) -> Value {
        let events = parse_events(input, &Limits::default()).expect("parse");
        compose_documents(&events, input.len(), &Limits::default())
            .expect("compose")
            .into_iter()
            .next()
            .expect("document")
    }

    #[test]
    fn composes_scalars_sequences_and_mappings() {
        let value = compose("name: ayaml\nitems:\n  - one\n  - two\n");
        assert_eq!(value["name"], Value::from("ayaml"));
        assert_eq!(value["items"][0], Value::from("one"));
        assert_eq!(value["items"][1], Value::from("two"));
    }

    fn fixture(name: &str) -> Option<String> {
        let root =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/compat");
        std::fs::read_to_string(root.join(name)).ok()
    }

    #[test]
    fn compatibility_scalars_and_tags() {
        let Some(input) = fixture("scalar-tags-merges-aliases.yml") else {
            return;
        };
        let value = compose(&input);
        assert_eq!(value["plain_bool_word"], Value::from("yes"));
        assert_eq!(value["legacy_octal"], Value::from("0123"));
        assert_eq!(value["binary"].as_u64(), Some(3));
        assert_eq!(value["hex"].as_u64(), Some(31));
        assert_eq!(value["exponent"].as_f64(), Some(1000.0));
        assert!(value["null_value"].is_null());
        assert_eq!(value["core_string"], Value::from("123"));
        assert!(value["tagged"].is_tagged());
        assert_eq!(value["alias"], value["base"]);
        assert_eq!(value["merged"]["<<"], value["base"]);
    }

    #[test]
    fn duplicate_keys_are_rejected() {
        let input = "a: 1\na: 2\n";
        let events = parse_events(input, &Limits::default()).expect("parse");
        let error =
            compose_documents(&events, input.len(), &Limits::default()).expect_err("duplicate");
        assert_eq!(error.kind(), ErrorKind::DuplicateKey);
    }

    #[test]
    fn aliases_are_materialized_and_budgeted() {
        let input = "base: &b {x: 1}\nuse: *b\n";
        let value = compose(input);
        assert_eq!(value["use"], value["base"]);

        let events = parse_events(input, &Limits::default()).expect("parse");
        let limits = Limits {
            max_alias_expansion_bytes: 0,
            ..Limits::default()
        };
        let error = compose_documents(&events, input.len(), &limits).expect_err("budget");
        assert_eq!(error.kind(), ErrorKind::Limit);
    }

    #[test]
    fn anchors_are_scoped_to_their_document() {
        let input = "---\na: &x 1\n---\nb: *x\n";
        let limits = Limits {
            max_documents: 2,
            ..Limits::default()
        };
        let events = parse_events(input, &limits).expect("parse");
        let error = compose_documents(&events, input.len(), &limits).expect_err("cross-document");
        assert_eq!(error.kind(), ErrorKind::Composition);
        assert!(error.message().contains("unknown anchor"));
    }

    #[test]
    fn aliases_before_their_anchor_are_rejected() {
        let input = "a: *missing\n";
        let events = parse_events(input, &Limits::default()).expect("parse");
        let error = compose_documents(&events, input.len(), &Limits::default()).expect_err("alias");
        assert_eq!(error.kind(), ErrorKind::Composition);
        assert!(error.message().contains("unknown anchor"));
    }

    #[test]
    fn multiple_documents_compose_in_order() {
        let input = "a: 1\n---\nb: 2\n";
        let limits = Limits {
            max_documents: 2,
            ..Limits::default()
        };
        let events = parse_events(input, &limits).expect("parse");
        let documents = compose_documents(&events, input.len(), &limits).expect("compose");
        assert_eq!(documents.len(), 2);
        assert_eq!(documents[0]["a"].as_u64(), Some(1));
        assert_eq!(documents[1]["b"].as_u64(), Some(2));
    }

    #[test]
    fn toolchain_fixture_composes() {
        let Some(input) = fixture("toolchain-pins.yml") else {
            return;
        };
        let value = compose(&input);
        assert_eq!(value["version"].as_u64(), Some(1));
        assert!(value["facts"].is_sequence());
        assert!(value["rules"].is_sequence());
    }
}