serde-saphyr 2.0.0

YAML (de)serializer for Serde, emphasizing panic-free parsing, fast builds and good error reporting. Supports properties, include, tag and comment capture
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
use std::borrow::Cow;
#[cfg(feature = "properties")]
use std::cell::{Cell, RefCell};
#[cfg(feature = "properties")]
use std::collections::HashMap;
use std::mem;
use std::ops::{Deref, DerefMut};
#[cfg(feature = "properties")]
use std::rc::Rc;

use granit_parser::ScalarStyle;
use smallvec::{SmallVec, smallvec};

use super::error::Error;
#[cfg(feature = "properties")]
use super::options::PropertySyntax;
use super::tags::SfTag;
#[cfg(feature = "properties")]
use crate::Budget;
#[cfg(feature = "properties")]
use crate::budget::BudgetBreach;
use crate::location::{Location, Locations};

/// Property interpolation configuration and aggregate work shared by live and replay sources.
#[cfg(feature = "properties")]
#[derive(Clone)]
pub(crate) struct PropertyInterpolation {
    property_map: Option<Rc<HashMap<String, String>>>,
    syntax: PropertySyntax,
    max_expansion_depth: usize,
    max_total_work: usize,
    total_work: Rc<Cell<usize>>,
    breach: Rc<RefCell<Option<BudgetBreach>>>,
}

#[cfg(feature = "properties")]
impl PropertyInterpolation {
    pub(super) fn new(
        property_map: Option<Rc<HashMap<String, String>>>,
        syntax: PropertySyntax,
        budget: Option<&Budget>,
    ) -> Self {
        let (max_expansion_depth, max_total_work) =
            budget.map_or((usize::MAX, usize::MAX), |budget| {
                (
                    budget.max_property_expansion_depth,
                    budget.max_total_property_interpolation_work,
                )
            });
        let property_map = property_map
            .or_else(|| (syntax == PropertySyntax::DockerCompose).then(|| Rc::new(HashMap::new())));
        Self {
            property_map,
            syntax,
            max_expansion_depth,
            max_total_work,
            total_work: Rc::new(Cell::new(0)),
            breach: Rc::new(RefCell::new(None)),
        }
    }

    pub(super) fn for_key(&self) -> Self {
        let mut properties = self.clone();
        if properties.syntax == PropertySyntax::DockerCompose {
            // Nested deserializers for sequence/mapping keys share this replay source.
            properties.property_map = None;
        }
        properties
    }

    pub(super) fn property_map(&self) -> Option<&Rc<HashMap<String, String>>> {
        self.property_map.as_ref()
    }

    pub(super) fn syntax(&self) -> PropertySyntax {
        self.syntax
    }

    pub(super) fn max_expansion_depth(&self) -> usize {
        self.max_expansion_depth
    }

    pub(super) fn max_total_work(&self) -> usize {
        self.max_total_work
    }

    pub(super) fn total_work(&self) -> &Cell<usize> {
        self.total_work.as_ref()
    }

    pub(super) fn record_breach(&self, breach: BudgetBreach) {
        let mut recorded = self.breach.borrow_mut();
        if recorded.is_none() {
            *recorded = Some(breach);
        }
    }

    pub(super) fn breach(&self) -> Option<BudgetBreach> {
        self.breach.borrow().clone()
    }
}

/// Attach both reference and defined locations to an error for alias replay scenarios.
/// When a real alias reference and its definition are known and different, wraps the error
/// in `Error::AliasError` to report both. A merge use-site alone is not an alias reference.
///
/// During alias replay, errors may already have a location attached (the anchor's definition
/// location from the replayed events). We still want to create an `Error::AliasError` with both
/// locations when the reference (alias) and defined (anchor) locations differ.
/// Reuse an existing wrapper for the same alias use, updating its definition to the outer
/// anchor location as the error propagates through nested containers.
#[inline]
#[allow(deprecated)] // Keep populating msg for existing message-based alias handlers.
pub(super) fn attach_alias_locations_if_missing(
    mut err: Error,
    alias_reference_location: Option<Location>,
    defined_location: Location,
) -> Error {
    let reference_location = alias_reference_location.unwrap_or(defined_location);
    // If both locations are known and different, wrap the error in AliasError to show both.
    // This applies even if the error already has a location (from replayed anchor events),
    // because we want to show where the alias was used, not just where the anchor was defined.
    if reference_location != Location::UNKNOWN
        && defined_location != Location::UNKNOWN
        && reference_location != defined_location
    {
        if let Error::AliasError { locations, .. } = &mut err
            && locations.reference_location == reference_location
        {
            locations.defined_location = defined_location;
            return err;
        }
        Error::AliasError {
            msg: err.to_string(),
            error: Box::new(err),
            locations: Locations {
                reference_location,
                defined_location,
            },
        }
    } else if err.location().is_some() {
        // Error already has a location and we don't have dual locations to add
        err
    } else {
        // Fall back to single location (prefer reference, then defined)
        let loc = if reference_location == Location::UNKNOWN {
            defined_location
        } else {
            reference_location
        };
        err.with_location(loc)
    }
}

/// Our simplified owned event kind that we feed into Serde.
///
/// This intentionally carries semantic YAML node data, anchors, tags, style, and
/// locations, but not presentation metadata such as comments. Live streams expose
/// comments through the `Events` comment hooks; replay streams can only preserve
/// comments that callers captured separately before buffering/replay.
#[derive(Clone, Debug)]
pub(crate) enum Ev<'a> {
    /// Scalar value from YAML (text), with optional tag and style.
    Scalar {
        value: Cow<'a, str>,
        tag: SfTag,
        raw_tag: Option<Cow<'a, str>>,
        style: ScalarStyle,
        /// Numeric anchor id (0 if none) attached to this scalar node.
        anchor: usize,
        location: Location,
    },
    /// Start of a sequence (`[` / `-`-list).
    SeqStart {
        anchor: usize,
        tag: SfTag,
        raw_tag: Option<Cow<'a, str>>,
        location: Location,
    },
    /// End of a sequence.
    SeqEnd { location: Location },
    /// Start of a mapping (`{` or block mapping).
    MapStart {
        anchor: usize,
        tag: SfTag,
        raw_tag: Option<Cow<'a, str>>,
        location: Location,
    },
    /// End of a mapping.
    MapEnd { location: Location },
    /// A reference into an anchor whose definition is still being recorded.
    /// Buffering preserves this event until a recursive wrapper can register its placeholder.
    RecursiveAlias { anchor: usize, location: Location },
    /// The event has been taken from the array, with only its location remaining.
    /// This should not appear in the event stream and is reserved for internal container state.
    Taken { location: Location },
}

impl Default for Ev<'_> {
    // Used for optimization
    fn default() -> Self {
        Ev::Taken {
            location: Location::UNKNOWN,
        }
    }
}

impl Ev<'_> {
    /// Get the source location attached to this event.
    ///
    /// Returns:
    /// - `Location` recorded when the event was produced.
    ///
    /// Used by:
    /// - Error reporting and "last seen location" tracking.
    pub(crate) fn location(&self) -> Location {
        match self {
            Ev::Scalar { location, .. }
            | Ev::SeqStart { location, .. }
            | Ev::SeqEnd { location }
            | Ev::MapStart { location, .. }
            | Ev::MapEnd { location }
            | Ev::RecursiveAlias { location, .. }
            | Ev::Taken { location } => *location,
        }
    }

    /// Bytes that an [`Ev::clone`] must allocate for owned string payloads.
    pub(crate) fn owned_payload_bytes(&self) -> usize {
        match self {
            Ev::Scalar { value, raw_tag, .. } => {
                let value_bytes = match value {
                    Cow::Borrowed(_) => 0,
                    Cow::Owned(value) => value.len(),
                };
                let raw_tag_bytes = match raw_tag {
                    Some(Cow::Owned(raw_tag)) => raw_tag.len(),
                    Some(Cow::Borrowed(_)) | None => 0,
                };
                value_bytes.saturating_add(raw_tag_bytes)
            }
            Ev::SeqStart { raw_tag, .. } | Ev::MapStart { raw_tag, .. } => match raw_tag {
                Some(Cow::Owned(raw_tag)) => raw_tag.len(),
                Some(Cow::Borrowed(_)) | None => 0,
            },
            Ev::SeqEnd { .. }
            | Ev::MapEnd { .. }
            | Ev::RecursiveAlias { .. }
            | Ev::Taken { .. } => 0,
        }
    }

    /// Clear the YAML tag attached to a scalar or container-start event.
    pub(super) fn strip_node_tag(&mut self) -> bool {
        match self {
            Ev::Scalar { tag, raw_tag, .. }
            | Ev::SeqStart { tag, raw_tag, .. }
            | Ev::MapStart { tag, raw_tag, .. } => {
                *tag = SfTag::None;
                *raw_tag = None;
                true
            }
            Ev::SeqEnd { .. }
            | Ev::MapEnd { .. }
            | Ev::RecursiveAlias { .. }
            | Ev::Taken { .. } => false,
        }
    }

    /// Resolve a recursive reference only when consuming events for a typed value.
    pub(super) fn resolve_recursive_alias(&mut self) -> Result<(), Error> {
        if let Self::RecursiveAlias { anchor, location } = *self {
            if !crate::anchor_store::recursive_anchor_in_progress(anchor)
                && !crate::anchor_store::recursive_anchor_registered(anchor)
            {
                return Err(Error::RecursiveReferencesRequireWeakTypes { location });
            }
            // Weak recursion wrappers only need the anchor id and consume this placeholder.
            *self = Self::Scalar {
                value: Cow::Borrowed(""),
                tag: SfTag::Null,
                raw_tag: None,
                style: ScalarStyle::Plain,
                anchor,
                location,
            };
        }
        Ok(())
    }
}

/// Why a node is being replayed somewhere other than its definition.
///
/// Alias provenance is independent from source coordinates: ordinary buffering and inline
/// merges can change the current use-site without introducing an alias token.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum NodeOrigin {
    #[default]
    Direct,
    Alias(Location),
    Merge(Location),
}

/// Captured events and their per-event origins.
///
/// Ordinary events need no extra allocation. Non-direct origins are indexed separately so
/// that buffering an ordinary container does not erase any aliases nested inside it.
#[derive(Debug, Default)]
pub(super) struct RecordedEvents<'a> {
    events: Vec<Ev<'a>>,
    origins: SmallVec<[(usize, NodeOrigin); 1]>,
}

impl<'a> RecordedEvents<'a> {
    pub(super) fn new() -> Self {
        Self::default()
    }

    pub(super) fn from_event(event: Ev<'a>, origin: NodeOrigin) -> Self {
        Self {
            events: vec![event],
            origins: if origin == NodeOrigin::Direct {
                SmallVec::new()
            } else {
                smallvec![(0, origin)]
            },
        }
    }

    pub(super) fn reserve(&mut self, additional: usize) {
        self.events.reserve(additional);
    }

    pub(super) fn push(&mut self, event: Ev<'a>, origin: NodeOrigin) {
        if origin != NodeOrigin::Direct {
            self.origins.push((self.events.len(), origin));
        }
        self.events.push(event);
    }

    pub(super) fn extend(&mut self, mut other: Self) {
        let offset = self.events.len();
        self.origins.extend(
            other
                .origins
                .drain(..)
                .map(|(index, origin)| (offset + index, origin)),
        );
        self.events.append(&mut other.events);
    }

    pub(super) fn origin(&self, index: usize) -> NodeOrigin {
        self.origins
            .binary_search_by_key(&index, |(index, _)| *index)
            .map_or(NodeOrigin::Direct, |index| self.origins[index].1)
    }
}

impl<'a> From<Vec<Ev<'a>>> for RecordedEvents<'a> {
    fn from(events: Vec<Ev<'a>>) -> Self {
        Self {
            events,
            origins: SmallVec::new(),
        }
    }
}

impl<'a> Deref for RecordedEvents<'a> {
    type Target = [Ev<'a>];

    fn deref(&self) -> &Self::Target {
        &self.events
    }
}

impl DerefMut for RecordedEvents<'_> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.events
    }
}

/// `from_slice_multiple` location-free representation of events for duplicate-key comparison.
/// Source of events with lookahead and alias-injection.
pub(crate) trait Events<'de> {
    /// Switch between recording recursive references and resolving them for typed values.
    /// Returns the previous mode so nested captures can restore it.
    fn defer_recursive_aliases(&mut self, defer: bool) -> bool;

    /// Pull the next event from the stream.
    ///
    /// Returns:
    /// - `Ok(Some(Ev))` for a real event,
    /// - `Ok(None)` at true end-of-stream,
    /// - `Err(Error)` on parser/structure failure.
    ///
    /// Called by:
    /// - The streaming deserializer (`Deser`) and helper scanners.
    fn next(&mut self) -> Result<Option<Ev<'de>>, Error>;

    /// Peek at the next event without consuming it.
    ///
    /// Returns:
    /// - `Ok(Some(&Ev))` with the event reference,
    /// - `Ok(None)` at end-of-stream,
    /// - `Err(Error)` on error.
    ///
    /// Called by:
    /// - Lookahead logic (merge, container boundaries, option/unit handling).
    fn peek(&mut self) -> Result<Option<&Ev<'de>>, Error>;

    /// Strip the tag from the node currently exposed by [`Self::peek`].
    ///
    /// This lets typed enum handling reinterpret a YAML tag as the enum variant while
    /// continuing to deserialize the payload directly from the original event source.
    fn strip_peeked_node_tag(&mut self) -> Result<(), Error>;

    /// Last location that `next` or `peek` has observed.
    ///
    /// Used by:
    /// - Error paths to attach a reasonable position when nothing else is available.
    fn last_location(&self) -> Location;

    /// Location of the *reference* to the next node (use-site).
    ///
    /// This is the key primitive that enables `Spanned<T>` to report two different
    /// locations:
    /// - **referenced**: where the value is *used* in the YAML (the use-site)
    /// - **defined**: where the value is *defined* (the definition-site; typically
    ///   the node's own [`Ev::location`])
    ///
    /// Contract
    /// - For a normal (non-alias) stream, `reference_location()` should be the
    ///   same as `peek()?.map(|ev| ev.location())`.
    /// - While replaying an alias (`*a`), the *events* come from the anchored
    ///   definition buffer, so their `Ev::location()` points at the definition-site.
    ///   In that situation, `reference_location()` must instead return the location
    ///   of the alias token `*a` (the use-site), so callers can attribute values to
    ///   where they were referenced.
    /// - During merge expansion (`<<: *m`), merge-derived entries should also
    ///   carry a use-site location (usually the `<<` entry / alias token) even
    ///   though the actual scalar nodes being replayed come from the merged mapping.
    ///
    /// Subtlety: this method is used *together with* `peek()`.
    /// Consumers typically do `peek()` (to ensure the next node is available), then
    /// call `reference_location()` and/or `Ev::location()` for the same node.
    /// Implementations therefore must keep the necessary context alive at least
    /// until the node is consumed.
    fn reference_location(&self) -> Location;

    /// Provenance of the node currently exposed by `peek`, preserved through buffering.
    fn node_origin(&self) -> NodeOrigin {
        NodeOrigin::Direct
    }

    /// Actual alias token responsible for the next node, if any.
    ///
    /// A merge reference must not cause an alias error merely because its coordinates differ
    /// from the definition. Call this after `peek`, before consuming the node.
    fn alias_reference_location(&self) -> Option<Location> {
        match self.node_origin() {
            NodeOrigin::Alias(location) => Some(location),
            NodeOrigin::Direct | NodeOrigin::Merge(_) => None,
        }
    }

    /// Take comments immediately above the next data node.
    ///
    /// Implementations may fill lookahead while doing this. The default is empty
    /// for replay buffers that do not carry presentation metadata. If a caller
    /// needs comments for a captured node, it must take them from the live stream
    /// before calling `capture_node` and carry them separately.
    fn take_leading_comments_for_next_node(&mut self) -> Result<Vec<Cow<'de, str>>, Error> {
        Ok(Vec::new())
    }

    /// Take same-line comments after a mapping key/value separator.
    ///
    /// This is the `# comment` in `key: # comment`, separated from comments
    /// immediately above the value node so nested containers do not treat the
    /// separator comment as a child-key comment.
    fn take_separator_comments_before_mapping_value(
        &mut self,
    ) -> Result<Vec<Cow<'de, str>>, Error> {
        Ok(Vec::new())
    }

    /// Take same-line comments after a block sequence item marker.
    ///
    /// This is the `# comment` in `- # comment`, separated from ordinary
    /// trailing comments after the previous sequence value.
    fn take_separator_comments_before_sequence_item_value(
        &mut self,
    ) -> Result<Vec<Cow<'de, str>>, Error> {
        Ok(Vec::new())
    }

    /// Take same-line comments immediately after the node that was just deserialized.
    #[cfg(feature = "comments")]
    fn take_trailing_comments_after_node(&mut self) -> Result<Vec<Cow<'de, str>>, Error> {
        Ok(Vec::new())
    }

    /// Get the original input string for zero-copy borrowing.
    ///
    /// Returns `Some(&str)` when the input is available for borrowing (string-based parsing),
    /// or `None` when borrowing is not possible (reader-based parsing or replay buffers).
    ///
    /// Used by:
    /// - The deserializer to return borrowed `&str` references when possible.
    ///
    /// This is used by string deserialization to return borrowed scalars when possible.
    fn input_for_borrowing(&self) -> Option<&'de str> {
        None // Default: borrowing not supported
    }

    #[cfg(feature = "properties")]
    fn property_interpolation(&self) -> &PropertyInterpolation;
}

/// Keep recursive aliases intact while buffering, including lookahead and comment hooks.
pub(super) fn with_deferred_recursive_aliases<'de, T>(
    ev: &mut dyn Events<'de>,
    capture: impl FnOnce(&mut dyn Events<'de>) -> Result<T, Error>,
) -> Result<T, Error> {
    let previous = ev.defer_recursive_aliases(true);
    let result = capture(ev);
    ev.defer_recursive_aliases(previous);
    result
}

#[cold]
pub(super) fn eof_with_loc(events: &dyn Events<'_>) -> Error {
    Error::eof().with_location(events.last_location())
}

/// Event source that replays a pre-recorded buffer.
///
/// Replay buffers preserve event origins but not comments. Comment hooks therefore use
/// the trait defaults; use-site comments must be passed separately by map/sequence access.
pub(super) struct ReplayEvents<'a> {
    buf: RecordedEvents<'a>,
    defer_recursive_aliases: bool,
    /// Index of the next event to yield (`0..=buf.len()`).
    idx: usize,
    /// Merge use-site applied to ordinary replayed nodes. Captured aliases retain their
    /// own use-site and provenance instead of inheriting this non-alias override.
    ref_override: Option<Location>,

    #[cfg(feature = "properties")]
    property_interpolation: PropertyInterpolation,
}

impl<'a> ReplayEvents<'a> {
    /// Create a replay source over `buf`, initially positioned at index 0.
    ///
    /// Arguments:
    /// - `buf`: previously captured events.
    ///
    /// Called by:
    /// - Merge expansion and recorded key/value deserialization.
    pub(super) fn new(
        buf: impl Into<RecordedEvents<'a>>,
        #[cfg(feature = "properties")] property_interpolation: PropertyInterpolation,
    ) -> Self {
        Self {
            buf: buf.into(),
            defer_recursive_aliases: false,
            idx: 0,
            ref_override: None,
            #[cfg(feature = "properties")]
            property_interpolation,
        }
    }

    /// Replay merge-derived nodes at a merge use-site without inventing alias provenance.
    /// Captured aliases keep their original use-site, including aliases nested in an inline
    /// merge. Definition locations on the events themselves remain unchanged.
    pub(super) fn with_reference(
        buf: impl Into<RecordedEvents<'a>>,
        reference: Location,
        #[cfg(feature = "properties")] property_interpolation: PropertyInterpolation,
    ) -> Self {
        Self {
            buf: buf.into(),
            defer_recursive_aliases: false,
            idx: 0,
            ref_override: Some(reference),
            #[cfg(feature = "properties")]
            property_interpolation,
        }
    }
}

impl<'a> Events<'a> for ReplayEvents<'a> {
    fn defer_recursive_aliases(&mut self, defer: bool) -> bool {
        mem::replace(&mut self.defer_recursive_aliases, defer)
    }

    /// See [`Events::next`]. Replays and advances the internal index.
    fn next(&mut self) -> Result<Option<Ev<'a>>, Error> {
        if self.idx >= self.buf.len() {
            return Ok(None);
        }
        if !self.defer_recursive_aliases {
            self.buf[self.idx].resolve_recursive_alias()?;
        }
        let location = self.buf[self.idx].location();
        // Flag as taken to avoid unexpected reuse.
        let ev = mem::replace(&mut self.buf[self.idx], Ev::Taken { location });
        self.idx += 1;
        Ok(Some(ev))
    }

    fn peek(&mut self) -> Result<Option<&Ev<'a>>, Error> {
        if !self.defer_recursive_aliases
            && let Some(ev) = self.buf.get_mut(self.idx)
        {
            ev.resolve_recursive_alias()?;
        }
        Ok(self.buf.get(self.idx))
    }

    fn strip_peeked_node_tag(&mut self) -> Result<(), Error> {
        let location = self
            .buf
            .get(self.idx)
            .map_or_else(|| self.last_location(), Ev::location);
        match self.buf.get_mut(self.idx) {
            Some(event) => event
                .strip_node_tag()
                .then_some(())
                .ok_or_else(|| Error::unexpected("tagged node").with_location(location)),
            None => Err(Error::unexpected("tagged node").with_location(location)),
        }
    }

    fn last_location(&self) -> Location {
        let last = self.idx.saturating_sub(1);
        self.buf.get(last).map_or(Location::UNKNOWN, Ev::location)
    }

    fn reference_location(&self) -> Location {
        match self.node_origin() {
            NodeOrigin::Alias(location) | NodeOrigin::Merge(location) => location,
            NodeOrigin::Direct => self
                .buf
                .get(self.idx)
                .map_or_else(|| self.last_location(), Ev::location),
        }
    }

    fn node_origin(&self) -> NodeOrigin {
        let origin = self.buf.origin(self.idx);
        match (origin, self.ref_override) {
            (NodeOrigin::Alias(_), _) => origin,
            (_, Some(reference)) => NodeOrigin::Merge(reference),
            (_, None) => origin,
        }
    }

    #[cfg(feature = "properties")]
    fn property_interpolation(&self) -> &PropertyInterpolation {
        &self.property_interpolation
    }
}

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

    fn scalar(location: Location) -> Ev<'static> {
        Ev::Scalar {
            value: Cow::Borrowed("value"),
            tag: SfTag::None,
            raw_tag: None,
            style: ScalarStyle::Plain,
            anchor: 0,
            location,
        }
    }

    fn replay(
        events: RecordedEvents<'static>,
        reference: Option<Location>,
    ) -> ReplayEvents<'static> {
        #[cfg(feature = "properties")]
        let properties = PropertyInterpolation::new(None, PropertySyntax::Braced, None);
        match reference {
            Some(reference) => ReplayEvents::with_reference(
                events,
                reference,
                #[cfg(feature = "properties")]
                properties,
            ),
            None => ReplayEvents::new(
                events,
                #[cfg(feature = "properties")]
                properties,
            ),
        }
    }

    #[test]
    fn recorded_origins_follow_events_when_buffers_are_joined() {
        let location = Location::new(1, 1);
        let alias = NodeOrigin::Alias(Location::new(4, 3));
        let merge = NodeOrigin::Merge(Location::new(7, 5));
        let mut prefix = RecordedEvents::from(vec![scalar(location)]);
        let mut suffix = RecordedEvents::new();
        suffix.push(scalar(location), alias);
        suffix.push(scalar(location), NodeOrigin::Direct);
        suffix.push(scalar(location), merge);
        prefix.extend(suffix);

        assert_eq!(prefix.len(), 4);
        assert_eq!(prefix.origin(0), NodeOrigin::Direct);
        assert_eq!(prefix.origin(1), alias);
        assert_eq!(prefix.origin(2), NodeOrigin::Direct);
        assert_eq!(prefix.origin(3), merge);
        assert_eq!(prefix.origin(4), NodeOrigin::Direct);
        assert_eq!(prefix.origins.len(), 2);
    }

    #[test]
    fn replay_keeps_each_direct_location_and_nested_alias_origin() {
        let first = Location::new(1, 1);
        let defined = Location::new(2, 3);
        let alias = Location::new(5, 7);
        let last = Location::new(8, 9);
        let mut events = RecordedEvents::new();
        events.push(scalar(first), NodeOrigin::Direct);
        events.push(scalar(defined), NodeOrigin::Alias(alias));
        events.push(scalar(last), NodeOrigin::Direct);
        let mut replay = replay(events, None);

        assert_eq!(replay.reference_location(), first);
        assert_eq!(replay.alias_reference_location(), None);
        replay.next().unwrap();
        assert_eq!(replay.peek().unwrap().unwrap().location(), defined);
        assert_eq!(replay.reference_location(), alias);
        assert_eq!(replay.alias_reference_location(), Some(alias));
        replay.next().unwrap();
        assert_eq!(replay.reference_location(), last);
        assert_eq!(replay.alias_reference_location(), None);
    }

    #[test]
    fn merge_reference_is_not_an_alias_and_does_not_replace_captured_aliases() {
        let defined = Location::new(1, 1);
        let alias = Location::new(3, 5);
        let merge = Location::new(6, 2);
        let mut events = RecordedEvents::new();
        events.push(scalar(defined), NodeOrigin::Direct);
        events.push(scalar(defined), NodeOrigin::Alias(alias));
        let mut replay = replay(events, Some(merge));

        assert_eq!(replay.node_origin(), NodeOrigin::Merge(merge));
        assert_eq!(replay.reference_location(), merge);
        assert_eq!(replay.alias_reference_location(), None);
        let error = attach_alias_locations_if_missing(
            Error::msg("invalid value"),
            replay.alias_reference_location(),
            defined,
        );
        assert!(!matches!(error, Error::AliasError { .. }));
        assert_eq!(error.location(), Some(defined));

        replay.next().unwrap();
        assert_eq!(replay.node_origin(), NodeOrigin::Alias(alias));
        assert_eq!(replay.reference_location(), alias);
        assert_eq!(replay.alias_reference_location(), Some(alias));
        let error = attach_alias_locations_if_missing(
            Error::msg("invalid value"),
            replay.alias_reference_location(),
            defined,
        );
        assert!(matches!(error, Error::AliasError { .. }));
    }
}