serde-saphyr 0.0.27

YAML (de)serializer for Serde, emphasizing panic-free parsing and good error reporting
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
use std::borrow::Cow;
#[cfg(feature = "properties")]
use std::collections::HashMap;
use std::mem;
#[cfg(feature = "properties")]
use std::rc::Rc;

use granit_parser::ScalarStyle;

use super::error::Error;
use super::events::{Ev, Events, ReplayEvents};
use super::options::MergeKeyPolicy;
use super::tags::SfTag;
use crate::location::Location;
use crate::parse_scalars::scalar_is_nullish;

pub(super) fn simple_tagged_enum_name(
    raw_tag: &Option<Cow<'_, str>>,
    tag: &SfTag,
) -> Option<String> {
    if !matches!(tag, SfTag::Other) {
        return None;
    }

    let raw = raw_tag.as_deref()?;
    let mut candidate =
        if let Some(inner) = raw.strip_prefix("!<").and_then(|s| s.strip_suffix('>')) {
            inner
        } else {
            raw
        };

    if let Some(stripped) = candidate.strip_prefix("tag:yaml.org,2002:") {
        candidate = stripped;
    }

    candidate = candidate.trim_start_matches('!');

    if candidate.is_empty() || candidate.contains([':', '!']) {
        return None;
    }

    Some(candidate.to_owned())
}

/// Canonical fingerprint of a YAML node for duplicate-key detection.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
pub(super) enum KeyFingerprint {
    /// Scalar fingerprint (value plus optional tag).
    Scalar { value: String, tag: SfTag },
    /// Sequence fingerprint (ordered fingerprints of children).
    Sequence(Vec<KeyFingerprint>),
    /// Mapping fingerprint (ordered list of `(key, value)` fingerprints).
    Mapping(Vec<(KeyFingerprint, KeyFingerprint)>),
    /// Should not be used, arises after taking the value away
    #[default]
    Default,
}

pub(super) fn canonical_scalar_key_tag(tag: SfTag) -> SfTag {
    if tag.can_parse_into_string() || tag == SfTag::NonSpecific {
        SfTag::String
    } else {
        tag
    }
}

impl KeyFingerprint {
    /// If this fingerprint represents a string-like scalar, return its value.
    ///
    /// Returns:
    /// - `Some(&str)` when the scalar can be parsed into string (and is not `!!binary`).
    /// - `None` for non-string scalars or containers.
    ///
    /// Used by:
    /// - Error messages to print a friendly duplicate key like `duplicate mapping key: foo`.
    pub(super) fn stringy_scalar_value(&self) -> Option<&str> {
        match self {
            KeyFingerprint::Scalar { value, tag } => {
                if tag.can_parse_into_string() && tag != &SfTag::Binary {
                    Some(value.as_str())
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

/// from_slice_multiple captured YAML node used to buffer keys/values and process merge keys.
///
/// Fields:
/// - `fingerprint`: canonical representation for duplicate detection.
/// - `events`: exact event slice that replays the node on demand.
/// - `location`: start location of the node (for diagnostics).
///
/// Comments are not part of `KeyNode`; callers that buffer a node and later
/// replay it must capture any relevant comment metadata alongside the node.
pub(super) enum KeyNode<'a> {
    Fingerprinted {
        fingerprint: KeyFingerprint,
        events: Vec<Ev<'a>>,
        location: Location,
    },
    Scalar {
        events: Vec<Ev<'a>>,
        location: Location,
    },
}

impl<'a> KeyNode<'a> {
    pub(super) fn fingerprint(&self) -> Cow<'_, KeyFingerprint> {
        match self {
            KeyNode::Fingerprinted { fingerprint, .. } => Cow::Borrowed(fingerprint),
            KeyNode::Scalar { events, .. } => {
                if let Some(Ev::Scalar { tag, value, .. }) = events.first() {
                    Cow::Owned(KeyFingerprint::Scalar {
                        tag: canonical_scalar_key_tag(*tag),
                        value: value.to_string(),
                    })
                } else {
                    unreachable!()
                }
            }
        }
    }

    pub(super) fn events(&self) -> &[Ev<'a>] {
        match self {
            KeyNode::Fingerprinted { events, .. } => events,
            KeyNode::Scalar { events, .. } => events,
        }
    }

    pub(super) fn take_events(&mut self) -> Vec<Ev<'a>> {
        match self {
            KeyNode::Fingerprinted { events, .. } => mem::take(events),
            KeyNode::Scalar { events, .. } => mem::take(events),
        }
    }

    pub(super) fn take_fingerprint(&mut self) -> KeyFingerprint {
        match self {
            KeyNode::Fingerprinted { fingerprint, .. } => mem::take(fingerprint),
            KeyNode::Scalar { .. } => self.fingerprint().into_owned(),
        }
    }

    pub(super) fn location(&self) -> Location {
        let location = match self {
            KeyNode::Fingerprinted { location, .. } => location,
            KeyNode::Scalar { location, .. } => location,
        };
        *location
    }
}

/// from_slice_multiple pending key/value pair to be injected into the current mapping.
///
/// Produced by:
/// - Merge (`<<`) processing and by scanning the current mapping fields.
pub(super) struct PendingEntry<'a> {
    pub(super) key: KeyNode<'a>,
    pub(super) value: KeyNode<'a>,
    /// Where the key/value pair is referenced/used in YAML.
    ///
    /// For merge-derived entries, this is the `<<` entry location.
    pub(super) reference_location: Location,
    /// Comments that visually belong to this key/value field.
    ///
    /// For replayed entries these are comments captured at the use site while
    /// scanning the containing map. Definition-site comments inside an anchored
    /// mapping are not reconstructed from the recorded event buffer.
    pub(super) field_comments: Vec<String>,
    /// Same-line comments after the key/value separator.
    pub(super) value_separator_comments: Vec<String>,
    /// Comments immediately above the value node.
    pub(super) value_comments: Vec<String>,
}

/// Return the span lengths of key and value for a one-entry map encoded in `events`.
/// The expected layout is: MapStart, <key node>, <value node>, MapEnd.
/// On success returns (key_start, key_end, val_start, val_end) as indices into events.
pub(super) fn one_entry_map_spans<'a>(events: &[Ev<'a>]) -> Option<(usize, usize, usize, usize)> {
    if events.len() < 4 {
        return None;
    }
    match events.first()? {
        Ev::MapStart { .. } => {}
        _ => return None,
    }
    match events.last()? {
        Ev::MapEnd { .. } => {}
        _ => return None,
    }
    // Cursor over the interior
    let mut i = 1; // after MapStart
    let key_start = i;
    i += skip_one_node_len(events, i)?;
    let key_end = i;
    let val_start = i;
    i += skip_one_node_len(events, i)?;
    let val_end = i;
    if i != events.len() - 1 {
        return None;
    }
    Some((key_start, key_end, val_start, val_end))
}

/// Skip one complete node in `events` starting at index `i`, returning the number of
/// events consumed. Returns None if the slice is malformed.
pub(super) fn skip_one_node_len<'a>(events: &[Ev<'a>], mut i: usize) -> Option<usize> {
    match events.get(i)? {
        Ev::Scalar { .. } => Some(1),
        Ev::SeqStart { .. } => {
            let start = i;
            let mut depth = 1i32;
            i += 1;
            while i < events.len() {
                match events.get(i)? {
                    Ev::SeqStart { .. } => depth += 1,
                    Ev::SeqEnd { .. } => {
                        depth -= 1;
                        if depth == 0 {
                            return Some(i - start + 1);
                        }
                    }
                    Ev::MapStart { .. } => depth += 1,
                    Ev::MapEnd { .. } => {
                        depth -= 1;
                    }
                    Ev::Scalar { .. } => {}
                    Ev::Taken { .. } => return None,
                }
                i += 1;
            }
            None
        }
        Ev::MapStart { .. } => {
            let start = i;
            let mut depth = 1i32;
            i += 1;
            while i < events.len() {
                match events.get(i)? {
                    Ev::MapStart { .. } => depth += 1,
                    Ev::MapEnd { .. } => {
                        depth -= 1;
                        if depth == 0 {
                            return Some(i - start + 1);
                        }
                    }
                    Ev::SeqStart { .. } => depth += 1,
                    Ev::SeqEnd { .. } => {
                        depth -= 1;
                    }
                    Ev::Scalar { .. } => {}
                    Ev::Taken { .. } => return None,
                }
                i += 1;
            }
            None
        }
        Ev::SeqEnd { .. } | Ev::MapEnd { .. } => None,
        Ev::Taken { .. } => None,
    }
}

/// Capture a complete node (scalar/sequence/mapping) from an `Events` source,
/// returning both a fingerprint (for duplicate checks) and a replayable buffer.
/// This is recursive function.
///
/// This records only `Ev` values. Since `Ev` does not carry comments, callers
/// must claim comment hooks before capture when comments should survive later
/// replay.
///
/// Arguments:
/// - `ev`: event source supporting lookahead and consumption.
///
/// Returns:
/// - `Ok(KeyNode)` describing the captured subtree.
/// - `Err(Error)` on structural errors or EOF.
///
/// Called by:
/// - Mapping deserialization to stage keys and values, and by merge processing.
pub(super) fn capture_node<'a>(ev: &mut dyn Events<'a>) -> Result<KeyNode<'a>, Error> {
    let Some(event) = ev.next()? else {
        return Err(Error::eof().with_location(ev.last_location()));
    };

    match event {
        Ev::Scalar {
            value,
            tag,
            raw_tag,
            style,
            anchor,
            location,
        } => {
            let scalar_ev = Ev::Scalar {
                value,
                tag,
                raw_tag,
                style,
                anchor,
                location,
            };
            Ok(KeyNode::Scalar {
                events: vec![scalar_ev],
                location,
            })
        }
        Ev::SeqStart {
            anchor,
            tag,
            raw_tag,
            location,
        } => {
            let mut events = vec![Ev::SeqStart {
                anchor,
                tag,
                raw_tag,
                location,
            }];
            let mut elements = Vec::new();
            loop {
                match ev.peek()? {
                    Some(Ev::SeqEnd { location: end_loc }) => {
                        let end_loc = *end_loc;
                        let _ = ev.next()?;
                        events.push(Ev::SeqEnd { location: end_loc });
                        break;
                    }
                    Some(_) => {
                        let mut child = capture_node(ev)?; // recursive
                        let fp = child.take_fingerprint();
                        let child_events = child.take_events();
                        elements.push(fp);
                        events.reserve(child_events.len());
                        events.extend(child_events);
                    }
                    None => {
                        return Err(Error::eof().with_location(ev.last_location()));
                    }
                }
            }
            Ok(KeyNode::Fingerprinted {
                fingerprint: KeyFingerprint::Sequence(elements),
                events,
                location,
            })
        }
        Ev::MapStart { anchor, location } => {
            let mut events = vec![Ev::MapStart { anchor, location }];
            let mut entries = Vec::new();
            loop {
                match ev.peek()? {
                    Some(Ev::MapEnd { location: end_loc }) => {
                        let end_loc = *end_loc;
                        let _ = ev.next()?;
                        events.push(Ev::MapEnd { location: end_loc });
                        break;
                    }
                    Some(_) => {
                        let mut key = capture_node(ev)?; // recursive
                        let key_fp = key.take_fingerprint();
                        let mut value = capture_node(ev)?; // recursive
                        let value_fp = value.take_fingerprint();
                        entries.push((key_fp, value_fp));
                        let key_events = key.take_events();
                        let value_events = value.take_events();
                        events.reserve(key_events.len() + value_events.len());
                        events.extend(key_events);
                        events.extend(value_events);
                    }
                    None => {
                        return Err(Error::eof().with_location(ev.last_location()));
                    }
                }
            }
            Ok(KeyNode::Fingerprinted {
                fingerprint: KeyFingerprint::Mapping(entries),
                events,
                location,
            })
        }
        Ev::SeqEnd { location } | Ev::MapEnd { location } => {
            Err(Error::UnexpectedContainerEndWhileReadingKeyNode { location })
        }
        Ev::Taken { location } => Err(Error::unexpected("consumed event").with_location(location)),
    }
}

/// Return the simple YAML tag name for a node that can act as an enum variant selector.
pub(super) fn simple_tagged_node_name(event: &Ev<'_>) -> Option<(String, Location)> {
    match event {
        Ev::Scalar {
            tag,
            raw_tag,
            location,
            ..
        }
        | Ev::SeqStart {
            tag,
            raw_tag,
            location,
            ..
        } => simple_tagged_enum_name(raw_tag, tag).map(|name| (name, *location)),
        _ => None,
    }
}

/// Remove the YAML tag from the payload node after it has been promoted to a map key.
pub(super) fn strip_root_tag_for_externally_tagged_payload<'a>(events: &mut [Ev<'a>]) {
    match events.first_mut() {
        Some(Ev::Scalar { tag, raw_tag, .. }) => {
            *tag = SfTag::None;
            *raw_tag = None;
        }
        Some(Ev::SeqStart { tag, raw_tag, .. }) => {
            *tag = SfTag::None;
            *raw_tag = None;
        }
        _ => {}
    }
}

/// Encode a YAML tag-selected enum variant as the Serde externally-tagged map form.
///
/// Arguments:
/// - `variant`: enum variant name extracted from the YAML tag, for example `Expression`.
/// - `tag_location`: source location of the tagged YAML node.
/// - `payload_events`: captured events for the YAML node after the root tag was stripped.
///
/// Returns:
/// - A synthetic one-entry mapping equivalent to `{ Variant: payload }`.
pub(super) fn externally_tagged_payload_as_map_events<'a>(
    variant: String,
    tag_location: Location,
    mut payload_events: Vec<Ev<'a>>,
) -> Vec<Ev<'a>> {
    let end_location = payload_events
        .last()
        .map(Ev::location)
        .unwrap_or(tag_location);

    let mut events = Vec::with_capacity(payload_events.len() + 3);
    events.push(Ev::MapStart {
        anchor: 0,
        location: tag_location,
    });
    events.push(Ev::Scalar {
        value: Cow::Owned(variant),
        tag: SfTag::String,
        raw_tag: None,
        style: ScalarStyle::Plain,
        anchor: 0,
        location: tag_location,
    });
    events.append(&mut payload_events);
    events.push(Ev::MapEnd {
        location: end_location,
    });
    events
}

/// Capture `!Variant payload` as a synthetic `{ Variant: payload }` event buffer.
pub(super) fn capture_simple_tagged_node_as_map_events<'a>(
    ev: &mut dyn Events<'a>,
) -> Result<Option<Vec<Ev<'a>>>, Error> {
    let Some((variant, tag_location)) = ev.peek()?.and_then(|event| simple_tagged_node_name(event))
    else {
        return Ok(None);
    };

    let mut payload_node = capture_node(ev)?;
    let mut payload_events = payload_node.take_events();
    strip_root_tag_for_externally_tagged_payload(&mut payload_events);

    Ok(Some(externally_tagged_payload_as_map_events(
        variant,
        tag_location,
        payload_events,
    )))
}

/// True if `node` is the YAML merge key (`<<`) as an untagged plain scalar.
///
/// Used by:
/// - Mapping deserialization to trigger merge value expansion.
#[inline]
pub(super) fn is_merge_key(node: &KeyNode) -> bool {
    let events = node.events();
    if events.len() != 1 {
        return false;
    }
    events.first().is_some_and(is_merge_key_event)
}

#[inline]
pub(super) fn is_merge_key_event(event: &Ev<'_>) -> bool {
    matches!(
        event,
        Ev::Scalar {
            value,
            tag,
            style: ScalarStyle::Plain,
            ..
        } if tag == &SfTag::None && value.as_ref() == "<<"
    )
}

pub(super) fn validate_no_merge_keys_in_node_events(events: &[Ev<'_>]) -> Result<(), Error> {
    fn eof_location(events: &[Ev<'_>]) -> Location {
        events.last().map(Ev::location).unwrap_or(Location::UNKNOWN)
    }

    fn visit_node(events: &[Ev<'_>], mut index: usize) -> Result<usize, Error> {
        match events.get(index) {
            Some(Ev::Scalar { .. }) => Ok(index + 1),
            Some(Ev::SeqStart { .. }) => {
                index += 1;
                loop {
                    match events.get(index) {
                        Some(Ev::SeqEnd { .. }) => return Ok(index + 1),
                        Some(Ev::MapEnd { location }) => {
                            return Err(Error::UnexpectedContainerEndWhileSkippingNode {
                                location: *location,
                            });
                        }
                        Some(_) => index = visit_node(events, index)?,
                        None => return Err(Error::eof().with_location(eof_location(events))),
                    }
                }
            }
            Some(Ev::MapStart { .. }) => {
                index += 1;
                loop {
                    match events.get(index) {
                        Some(Ev::MapEnd { .. }) => return Ok(index + 1),
                        Some(Ev::SeqEnd { location }) => {
                            return Err(Error::UnexpectedContainerEndWhileSkippingNode {
                                location: *location,
                            });
                        }
                        Some(event) => {
                            if is_merge_key_event(event) {
                                return Err(Error::MergeKeyNotAllowed {
                                    location: event.location(),
                                });
                            }
                            index = visit_node(events, index)?;
                            index = visit_node(events, index)?;
                        }
                        None => return Err(Error::eof().with_location(eof_location(events))),
                    }
                }
            }
            Some(Ev::SeqEnd { location } | Ev::MapEnd { location }) => {
                Err(Error::UnexpectedContainerEndWhileSkippingNode {
                    location: *location,
                })
            }
            Some(Ev::Taken { location }) => {
                Err(Error::unexpected("consumed event").with_location(*location))
            }
            None => Err(Error::eof().with_location(eof_location(events))),
        }
    }

    let next = visit_node(events, 0)?;
    if next == events.len() {
        Ok(())
    } else {
        Err(Error::unexpected("single YAML node").with_location(events[next].location()))
    }
}

/// Expand a merge value node into a queue of `PendingEntry`s in correct order.
///
/// Arguments:
/// - `events`: recorded events that make up the merge value (mapping or sequence of mappings).
/// - `location`: start location of the merge value (for diagnostics).
///
/// Returns:
/// - `Ok(Vec<PendingEntry>)` entries to be enqueued into the current map in merge order.
/// - `Err(Error)` if the merge value is not a mapping/sequence-of-mappings.
///
/// Called by:
/// - Mapping deserialization when encountering `<<: value`.
pub(super) fn pending_entries_from_events<'a>(
    events: Vec<Ev<'a>>,
    location: Location,
    reference_location: Location,
    merge_keys: MergeKeyPolicy,
    #[cfg(feature = "properties")] property_map: Option<Rc<HashMap<String, String>>>,
) -> Result<Vec<PendingEntry<'a>>, Error> {
    let mut replay = ReplayEvents::with_reference(
        events,
        reference_location,
        #[cfg(feature = "properties")]
        property_map.clone(),
    );
    match replay.peek()? {
        Some(Ev::Scalar { value, style, .. }) if scalar_is_nullish(value.as_ref(), style) => {
            Ok(Vec::new())
        }
        Some(Ev::Scalar { location, .. }) => Err(Error::MergeValueNotMapOrSeqOfMaps {
            location: *location,
        }),
        Some(Ev::MapStart { .. }) => {
            collect_entries_from_map(&mut replay, reference_location, merge_keys)
        }
        Some(Ev::SeqStart { .. }) => {
            let mut batches = Vec::new();
            let _ = replay.next()?; // consume SeqStart
            loop {
                match replay.peek()? {
                    Some(Ev::SeqEnd { .. }) => {
                        let _ = replay.next()?;
                        break;
                    }
                    Some(_) => {
                        // Preserve per-element use-site location. If the element comes from alias
                        // replay (`*m1`), its events are definition-site, but `referenced` should
                        // point at the alias token.
                        let _ = replay.peek()?;
                        let element_ref_loc = replay.reference_location();
                        let mut element = capture_node(&mut replay)?;
                        batches.push(pending_entries_from_events(
                            element.take_events(),
                            element.location(),
                            element_ref_loc,
                            merge_keys,
                            #[cfg(feature = "properties")]
                            property_map.clone(),
                        )?); // recursive
                    }
                    None => {
                        return Err(Error::eof().with_location(replay.last_location()));
                    }
                }
            }

            let mut merged = Vec::new();
            while let Some(mut nested) = batches.pop() {
                merged.append(&mut nested);
            }
            Ok(merged)
        }
        Some(other) => Err(Error::MergeValueNotMapOrSeqOfMaps {
            location: other.location(),
        }),
        None => Err(Error::eof().with_location(location)),
    }
}

/// Expand a merge value node directly from a live `Events` source.
///
/// This is used for `<<: value` handling in streaming map deserialization. Unlike
/// `pending_entries_from_events` (which works over a pre-recorded buffer), this
/// function can preserve per-element use-site locations for sequence merges like:
///
/// ```yaml
/// <<: [*m1, *m2]
/// ```
///
/// because `Events::reference_location()` can still observe the alias token
/// locations while the replay injection frame is active.
pub(super) fn pending_entries_from_live_events<'a>(
    ev: &mut dyn Events<'a>,
    merge_reference_location: Location,
    merge_keys: MergeKeyPolicy,
) -> Result<Vec<PendingEntry<'a>>, Error> {
    #[cfg(feature = "properties")]
    let property_map = ev.property_map().map(Rc::clone);
    match ev.peek()? {
        Some(Ev::Scalar { value, style, .. }) if scalar_is_nullish(value.as_ref(), style) => {
            let _ = ev.next()?;
            Ok(Vec::new())
        }
        Some(Ev::Scalar { location, .. }) => Err(Error::MergeValueNotMapOrSeqOfMaps {
            location: *location,
        }),
        Some(Ev::MapStart { .. }) => {
            let mut node = capture_node(ev)?;
            pending_entries_from_events(
                node.take_events(),
                node.location(),
                merge_reference_location,
                merge_keys,
                #[cfg(feature = "properties")]
                property_map,
            )
        }
        Some(Ev::SeqStart { .. }) => {
            let _ = ev.next()?; // consume SeqStart
            let mut batches = Vec::new();
            loop {
                match ev.peek()? {
                    Some(Ev::SeqEnd { .. }) => {
                        let _ = ev.next()?;
                        break;
                    }
                    Some(_) => {
                        let _ = ev.peek()?;
                        let element_ref_loc = ev.reference_location();
                        let mut element = capture_node(ev)?;
                        batches.push(pending_entries_from_events(
                            element.take_events(),
                            element.location(),
                            element_ref_loc,
                            merge_keys,
                            #[cfg(feature = "properties")]
                            property_map.clone(),
                        )?);
                    }
                    None => return Err(Error::eof().with_location(ev.last_location())),
                }
            }
            let mut merged = Vec::new();
            while let Some(mut nested) = batches.pop() {
                merged.append(&mut nested);
            }
            Ok(merged)
        }
        Some(other) => Err(Error::MergeValueNotMapOrSeqOfMaps {
            location: other.location(),
        }),
        None => Err(Error::eof().with_location(ev.last_location())),
    }
}

/// Collect `(key,value)` entries from a mapping at the current position.
///
/// Arguments:
/// - `ev`: event source currently positioned at `MapStart`.
///
/// Returns:
/// - All entries from that mapping, with any nested merges expanded in-order.
///
/// Called by:
/// - Merge expansion (`pending_entries_from_events`) and map scanning.
pub(super) fn collect_entries_from_map<'a>(
    ev: &mut dyn Events<'a>,
    reference_location: Location,
    merge_keys: MergeKeyPolicy,
) -> Result<Vec<PendingEntry<'a>>, Error> {
    let Some(Ev::MapStart { .. }) = ev.next()? else {
        return Err(Error::MergeValueNotMapOrSeqOfMaps {
            location: ev.last_location(),
        });
    };

    let mut fields = Vec::new();
    let mut merges = Vec::new();

    loop {
        match ev.peek()? {
            Some(Ev::MapEnd { .. }) => {
                let _ = ev.next()?;
                break;
            }
            Some(_) => {
                let key_comments = ev.take_leading_comments_for_next_node()?;
                let key = capture_node(ev)?;
                if is_merge_key(&key) {
                    match merge_keys {
                        MergeKeyPolicy::Merge => {
                            // Preserve where the merge value is referenced (use-site). For alias
                            // merges inside merged mappings, node locations point at the anchored
                            // mapping, but we want `referenced` to point at the alias token.
                            let _ = ev.peek()?;
                            let merge_ref_loc = ev.reference_location();
                            merges.push(pending_entries_from_live_events(
                                ev,
                                merge_ref_loc,
                                merge_keys,
                            )?);
                            continue;
                        }
                        MergeKeyPolicy::AsOrdinary => {}
                        MergeKeyPolicy::Error => {
                            return Err(Error::MergeKeyNotAllowed {
                                location: key.location(),
                            });
                        }
                    }
                }
                let field_comments = key_comments;
                let value_separator_comments = ev.take_separator_comments_before_mapping_value()?;
                let value_comments = ev.take_leading_comments_for_next_node()?;
                let value = capture_node(ev)?;
                fields.push(PendingEntry {
                    key,
                    value,
                    reference_location,
                    field_comments,
                    value_separator_comments,
                    value_comments,
                });
            }
            None => {
                return Err(Error::eof().with_location(ev.last_location()));
            }
        }
    }

    let mut entries = fields;
    while let Some(mut nested) = merges.pop() {
        entries.append(&mut nested);
    }
    Ok(entries)
}