noyalib 0.0.2

A pure Rust YAML library with zero unsafe code and full serde integration
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
//! YAML 1.2 event-based parser.
//!
//! Converts a stream of [`Token`]s into parsing [`Event`]s.

// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 Noyalib. All rights reserved.

use crate::prelude::*;
use indexmap::IndexMap;

use super::scanner::{ScalarStyle, ScanError, Scanner, Span, TokenKind};

/// Parsing events emitted by the parser.
///
/// The lifetime `'a` allows `Scalar::value` to borrow directly from the input
/// when no escaping or line-folding was needed (plain scalar fast path).
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) enum Event<'a> {
    StreamStart,
    StreamEnd,
    DocumentStart,
    DocumentEnd,
    Alias {
        anchor: String,
        span: Span,
    },
    Scalar {
        value: Cow<'a, str>,
        style: ScalarStyle,
        anchor: Option<String>,
        tag: Option<(String, String)>,
        span: Span,
    },
    SequenceStart {
        anchor: Option<String>,
        tag: Option<(String, String)>,
        span: Span,
    },
    SequenceEnd {
        span: Span,
    },
    MappingStart {
        anchor: Option<String>,
        tag: Option<(String, String)>,
        span: Span,
    },
    MappingEnd {
        span: Span,
    },
}

/// Parser states.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    StreamStart,
    ImplicitDocumentStart,
    DocumentStart,
    DocumentContent,
    DocumentEnd,
    BlockNode,
    BlockSequenceFirstEntry,
    BlockSequenceEntry,
    IndentlessSequenceEntry,
    BlockMappingFirstKey,
    BlockMappingKey,
    BlockMappingValue,
    FlowSequenceFirstEntry,
    FlowSequenceEntry,
    FlowSequenceEntryMappingKey,
    FlowSequenceEntryMappingValue,
    FlowSequenceEntryMappingEnd,
    FlowMappingFirstKey,
    FlowMappingKey,
    FlowMappingValue,
    FlowMappingEmptyValue,
    End,
}

/// YAML event-based parser.
#[derive(Debug)]
pub(crate) struct Parser<'a> {
    scanner: Scanner<'a>,
    /// Parser state stack. Each `State` is a 1-byte enum; 16 slots inline
    /// is plenty for realistic nesting and costs just 16 bytes of stack,
    /// avoiding a heap allocation per parse.
    states: smallvec::SmallVec<[State; 16]>,
    state: State,
    /// Current peeked token kind + span (if any).
    current_kind: Option<TokenKind<'a>>,
    current_span: Span,
    has_current: bool,
    /// Anchor name registry.
    marks: IndexMap<String, usize>,
    next_anchor_id: usize,
    /// `true` once the first document in the stream has ended. Per
    /// YAML 1.2.2 §9.1.2, implicit documents are only allowed as the
    /// first document; any subsequent document must start with an
    /// explicit `---` (or follow `...`). Used to reject stray content
    /// at the end of a document (BS4K, KS4U-class).
    first_document_ended: bool,
}

impl<'a> Parser<'a> {
    pub(crate) fn new(input: &'a str) -> Self {
        Parser {
            scanner: Scanner::new(input),
            states: smallvec::SmallVec::new(),
            state: State::StreamStart,
            current_kind: None,
            current_span: Span::default(),
            has_current: false,
            marks: IndexMap::new(),
            next_anchor_id: 0,
            first_document_ended: false,
        }
    }

    /// Drain captured comments. Used by the public
    /// [`crate::load_comments`] API. Returns comments in source order.
    pub(crate) fn take_comments(&mut self) -> Vec<crate::comments::Comment> {
        self.scanner
            .take_comments()
            .into_iter()
            .map(|c| crate::comments::Comment {
                text: c.text,
                start: c.start,
                end: c.end,
                kind: if c.inline {
                    crate::comments::CommentKind::Inline
                } else {
                    crate::comments::CommentKind::Line
                },
            })
            .collect()
    }

    pub(crate) fn next_event(&mut self) -> Result<Event<'a>, ScanError> {
        match self.state {
            State::StreamStart => self.parse_stream_start(),
            State::ImplicitDocumentStart => self.parse_document_start(true),
            State::DocumentStart => self.parse_document_start(false),
            State::DocumentContent => self.parse_document_content(),
            State::DocumentEnd => self.parse_document_end(),
            State::BlockNode => self.parse_node(true, false),
            State::BlockSequenceFirstEntry => self.parse_block_sequence_entry(true),
            State::BlockSequenceEntry => self.parse_block_sequence_entry(false),
            State::IndentlessSequenceEntry => self.parse_indentless_sequence_entry(),
            State::BlockMappingFirstKey => self.parse_block_mapping_key(true),
            State::BlockMappingKey => self.parse_block_mapping_key(false),
            State::BlockMappingValue => self.parse_block_mapping_value(),
            State::FlowSequenceFirstEntry => self.parse_flow_sequence_entry(true),
            State::FlowSequenceEntry => self.parse_flow_sequence_entry(false),
            State::FlowSequenceEntryMappingKey => self.parse_flow_sequence_entry_mapping_key(),
            State::FlowSequenceEntryMappingValue => self.parse_flow_sequence_entry_mapping_value(),
            State::FlowSequenceEntryMappingEnd => self.parse_flow_sequence_entry_mapping_end(),
            State::FlowMappingFirstKey => self.parse_flow_mapping_key(true),
            State::FlowMappingKey => self.parse_flow_mapping_key(false),
            State::FlowMappingValue => self.parse_flow_mapping_value(false),
            State::FlowMappingEmptyValue => self.parse_flow_mapping_value(true),
            State::End => Err(ScanError {
                message: Cow::Borrowed("parser has already finished"),
                index: 0,
            }),
        }
    }

    /// Ensure the current token is buffered and return its kind + span.
    fn peek(&mut self) -> Result<(&TokenKind<'a>, Span), ScanError> {
        if !self.has_current {
            let t = self.scanner.next_token()?;
            self.current_kind = Some(t.kind);
            self.current_span = t.span;
            self.has_current = true;
        }
        Ok((
            self.current_kind
                .as_ref()
                .expect("internal: current_kind set by peek"),
            self.current_span,
        ))
    }

    /// Peek just the kind (for matching).
    ///
    /// NOTE: This clones the `TokenKind`, including any owned `String` in
    /// `Scalar`/`Anchor`/`Alias`/`Tag` variants. Prefer `peek_is()` or
    /// `take()` when you only need the discriminant or will consume the token.
    fn peek_kind(&mut self) -> Result<TokenKind<'a>, ScanError> {
        let (kind, _) = self.peek()?;
        Ok(kind.clone())
    }

    /// Check whether the peeked token matches a discriminant without cloning.
    #[inline]
    fn peek_is(&mut self, f: fn(&TokenKind<'_>) -> bool) -> Result<bool, ScanError> {
        let (kind, _) = self.peek()?;
        Ok(f(kind))
    }

    /// Consume the current token and return its kind + span.
    fn take(&mut self) -> Result<(TokenKind<'a>, Span), ScanError> {
        if self.has_current {
            self.has_current = false;
            Ok((
                self.current_kind
                    .take()
                    .expect("internal: current_kind set when has_current"),
                self.current_span,
            ))
        } else {
            let t = self.scanner.next_token()?;
            Ok((t.kind, t.span))
        }
    }

    /// Consume the current token, discarding it.
    fn skip(&mut self) -> Result<(), ScanError> {
        let _ = self.take()?;
        Ok(())
    }

    fn pop_state(&mut self) -> State {
        self.states.pop().unwrap_or(State::End)
    }

    fn empty_scalar(&self, span: Span) -> Event<'a> {
        Event::Scalar {
            value: Cow::Borrowed(""),
            style: ScalarStyle::Plain,
            anchor: None,
            tag: None,
            span,
        }
    }

    // ── State handlers ───────────────────────────────────────────────────

    fn parse_stream_start(&mut self) -> Result<Event<'a>, ScanError> {
        self.skip()?; // StreamStart
        self.state = State::ImplicitDocumentStart;
        Ok(Event::StreamStart)
    }

    fn parse_document_start(&mut self, implicit: bool) -> Result<Event<'a>, ScanError> {
        // Skip any document end markers (`...`).
        while self.peek_is(|k| matches!(k, TokenKind::DocumentEnd))? {
            self.skip()?;
        }

        if self.peek_is(|k| matches!(k, TokenKind::StreamEnd))? {
            self.skip()?;
            self.state = State::End;
            return Ok(Event::StreamEnd);
        }

        if self.peek_is(|k| matches!(k, TokenKind::DocumentStart))? {
            self.skip()?;
            self.state = State::DocumentContent;
            return Ok(Event::DocumentStart);
        }

        // YAML 1.2.2 §9.1.2: subsequent documents must begin with an
        // explicit `---`. Reaching this point with `first_document_ended`
        // means there is content after the first document but neither
        // a `---` indicator nor end-of-stream — that is stray and
        // invalid (BS4K, KS4U).
        if self.first_document_ended {
            let span = self.current_span;
            return Err(ScanError {
                message: Cow::Borrowed(
                    "stray content after document — subsequent documents must start with '---'",
                ),
                index: span.start,
            });
        }

        if implicit {
            self.state = State::BlockNode;
            self.states.push(State::DocumentEnd);
        } else {
            self.state = State::DocumentContent;
        }
        Ok(Event::DocumentStart)
    }

    fn parse_document_content(&mut self) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;
        if self.peek_is(|k| {
            matches!(
                k,
                TokenKind::DocumentEnd | TokenKind::DocumentStart | TokenKind::StreamEnd
            )
        })? {
            self.state = State::DocumentEnd;
            Ok(self.empty_scalar(span))
        } else {
            self.states.push(State::DocumentEnd);
            self.parse_node(true, false)
        }
    }

    fn parse_document_end(&mut self) -> Result<Event<'a>, ScanError> {
        let saw_explicit_end = self.peek_is(|k| matches!(k, TokenKind::DocumentEnd))?;
        if saw_explicit_end {
            self.skip()?;
        }
        self.marks.clear();
        self.next_anchor_id = 0;
        self.state = State::DocumentStart;
        // Only mark the "subsequent docs must be explicit" flag when
        // the current document ended *implicitly* (no `...`). A
        // bare implicit document after `...` is allowed (7Z25); only
        // stray content with no boundary at all is invalid (BS4K,
        // KS4U).
        if !saw_explicit_end {
            self.first_document_ended = true;
        }
        Ok(Event::DocumentEnd)
    }

    fn parse_node(&mut self, block: bool, indentless: bool) -> Result<Event<'a>, ScanError> {
        // Peek once to get the span; use take() to extract owned data only
        // when the token is actually consumed — avoids cloning Strings.
        let _ = self.peek()?;
        let span = self.current_span;

        let mut anchor: Option<String> = None;
        let mut tag: Option<(String, String)> = None;

        // Parse optional anchor — take() to move the Cow out; convert to owned
        // for the Event boundary.
        if self.peek_is(|k| matches!(k, TokenKind::Anchor(_)))? {
            if let (TokenKind::Anchor(name), _) = self.take()? {
                let owned = name.into_owned();
                let _ = self.marks.insert(owned.clone(), self.next_anchor_id);
                self.next_anchor_id += 1;
                anchor = Some(owned);
            }
            // Check for tag after anchor.
            if self.peek_is(|k| matches!(k, TokenKind::Tag(_, _)))? {
                if let (TokenKind::Tag(h, s), _) = self.take()? {
                    tag = Some((h.into_owned(), s.into_owned()));
                }
            }
        } else if self.peek_is(|k| matches!(k, TokenKind::Tag(_, _)))? {
            if let (TokenKind::Tag(h, s), _) = self.take()? {
                tag = Some((h.into_owned(), s.into_owned()));
            }
            // Check for anchor after tag.
            if self.peek_is(|k| matches!(k, TokenKind::Anchor(_)))? {
                if let (TokenKind::Anchor(name), _) = self.take()? {
                    let owned = name.into_owned();
                    let _ = self.marks.insert(owned.clone(), self.next_anchor_id);
                    self.next_anchor_id += 1;
                    anchor = Some(owned);
                }
            }
        }

        // Alias — take() moves the Cow; convert to owned for the Event.
        if self.peek_is(|k| matches!(k, TokenKind::Alias(_)))? {
            let (kind, alias_span) = self.take()?;
            if let TokenKind::Alias(name) = kind {
                self.state = self.pop_state();
                return Ok(Event::Alias {
                    anchor: name.into_owned(),
                    span: alias_span,
                });
            }
        }

        // Main node dispatch — take() for Scalar to move the String.
        let _ = self.peek()?;
        let tok_span = self.current_span;
        let kind_ref = self
            .current_kind
            .as_ref()
            .expect("internal: peek() above guarantees current_kind");

        match kind_ref {
            TokenKind::Scalar(_, _) => {
                let (kind, scalar_span) = self.take()?;
                if let TokenKind::Scalar(style, value) = kind {
                    self.state = self.pop_state();
                    Ok(Event::Scalar {
                        value,
                        style,
                        anchor,
                        tag,
                        span: scalar_span,
                    })
                } else {
                    crate::error::invariant_violated(
                        "outer match guarded TokenKind::Scalar; take() must return the same",
                    )
                }
            }
            TokenKind::FlowSequenceStart => {
                self.skip()?;
                self.state = State::FlowSequenceFirstEntry;
                Ok(Event::SequenceStart {
                    anchor,
                    tag,
                    span: tok_span,
                })
            }
            TokenKind::FlowMappingStart => {
                self.skip()?;
                self.state = State::FlowMappingFirstKey;
                Ok(Event::MappingStart {
                    anchor,
                    tag,
                    span: tok_span,
                })
            }
            TokenKind::BlockSequenceStart if block => {
                self.skip()?;
                self.state = State::BlockSequenceFirstEntry;
                Ok(Event::SequenceStart {
                    anchor,
                    tag,
                    span: tok_span,
                })
            }
            TokenKind::BlockMappingStart if block => {
                self.skip()?;
                self.state = State::BlockMappingFirstKey;
                Ok(Event::MappingStart {
                    anchor,
                    tag,
                    span: tok_span,
                })
            }
            // Indentless block sequence: `BlockEntry` without a preceding
            // `BlockSequenceStart` — the `-` is at the same indent as the
            // containing mapping key.
            TokenKind::BlockEntry if indentless || (anchor.is_some() || tag.is_some()) => {
                self.state = State::IndentlessSequenceEntry;
                Ok(Event::SequenceStart {
                    anchor,
                    tag,
                    span: tok_span,
                })
            }
            _ => {
                if anchor.is_some() || tag.is_some() {
                    self.state = self.pop_state();
                    Ok(Event::Scalar {
                        value: Cow::Borrowed(""),
                        style: ScalarStyle::Plain,
                        anchor,
                        tag,
                        span,
                    })
                } else if indentless {
                    self.state = self.pop_state();
                    Ok(self.empty_scalar(span))
                } else {
                    let kind = self.peek_kind()?;
                    Err(ScanError {
                        message: Cow::Owned(format!("expected a node but found {kind:?}")),
                        index: span.start,
                    })
                }
            }
        }
    }

    // ── Block sequences ──────────────────────────────────────────────────

    fn parse_block_sequence_entry(&mut self, _first: bool) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;

        if self.peek_is(|k| matches!(k, TokenKind::BlockEntry))? {
            self.skip()?;
            if self.peek_is(|k| matches!(k, TokenKind::BlockEntry | TokenKind::BlockEnd))? {
                self.state = State::BlockSequenceEntry;
                Ok(self.empty_scalar(span))
            } else {
                self.states.push(State::BlockSequenceEntry);
                self.parse_node(true, false)
            }
        } else if self.peek_is(|k| matches!(k, TokenKind::BlockEnd))? {
            self.skip()?;
            self.state = self.pop_state();
            Ok(Event::SequenceEnd { span })
        } else {
            Err(ScanError {
                message: Cow::Borrowed("expected block sequence entry or end"),
                index: span.start,
            })
        }
    }

    fn parse_indentless_sequence_entry(&mut self) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;

        if self.peek_is(|k| matches!(k, TokenKind::BlockEntry))? {
            self.skip()?;
            if self.peek_is(|k| {
                matches!(
                    k,
                    TokenKind::BlockEntry | TokenKind::Key | TokenKind::Value | TokenKind::BlockEnd
                )
            })? {
                self.state = State::IndentlessSequenceEntry;
                Ok(self.empty_scalar(span))
            } else {
                self.states.push(State::IndentlessSequenceEntry);
                self.parse_node(true, false)
            }
        } else {
            self.state = self.pop_state();
            Ok(Event::SequenceEnd { span })
        }
    }

    // ── Block mappings ───────────────────────────────────────────────────

    fn parse_block_mapping_key(&mut self, _first: bool) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;

        if self.peek_is(|k| matches!(k, TokenKind::Key))? {
            self.skip()?;
            if self
                .peek_is(|k| matches!(k, TokenKind::Key | TokenKind::Value | TokenKind::BlockEnd))?
            {
                self.state = State::BlockMappingValue;
                Ok(self.empty_scalar(span))
            } else {
                self.states.push(State::BlockMappingValue);
                self.parse_node(true, true)
            }
        } else if self.peek_is(|k| matches!(k, TokenKind::BlockEnd))? {
            self.skip()?;
            self.state = self.pop_state();
            Ok(Event::MappingEnd { span })
        } else if self.peek_is(|k| matches!(k, TokenKind::Value))? {
            // Bare `:` without `?` — implicit empty key.  Emit the empty key
            // scalar and transition to the value phase (which will consume `:`)
            self.state = State::BlockMappingValue;
            Ok(self.empty_scalar(span))
        } else if self.peek_is(|k| {
            matches!(
                k,
                TokenKind::BlockSequenceStart
                    | TokenKind::BlockEntry
                    | TokenKind::BlockMappingStart
            )
        })? {
            // Compact block collection as mapping value at the same indent level.
            // Treat as if we saw an implicit empty key followed by this value.
            // This handles patterns like: `key:\n- item` where `-` is at the same indent.
            self.state = self.pop_state();
            Ok(Event::MappingEnd { span })
        } else {
            Err(ScanError {
                message: Cow::Borrowed("expected block mapping key or end"),
                index: span.start,
            })
        }
    }

    fn parse_block_mapping_value(&mut self) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;

        if self.peek_is(|k| matches!(k, TokenKind::Value))? {
            self.skip()?;
            if self
                .peek_is(|k| matches!(k, TokenKind::Key | TokenKind::Value | TokenKind::BlockEnd))?
            {
                self.state = State::BlockMappingKey;
                Ok(self.empty_scalar(span))
            } else {
                self.states.push(State::BlockMappingKey);
                self.parse_node(true, true)
            }
        } else {
            self.state = State::BlockMappingKey;
            Ok(self.empty_scalar(span))
        }
    }

    // ── Flow sequences ───────────────────────────────────────────────────

    fn parse_flow_sequence_entry(&mut self, first: bool) -> Result<Event<'a>, ScanError> {
        if !first {
            let _ = self.peek()?;
            let span = self.current_span;
            if self.peek_is(|k| matches!(k, TokenKind::FlowEntry))? {
                self.skip()?;
            } else if !self.peek_is(|k| matches!(k, TokenKind::FlowSequenceEnd))? {
                return Err(ScanError {
                    message: Cow::Borrowed("expected ',' or ']' in flow sequence"),
                    index: span.start,
                });
            }
        }

        let _ = self.peek()?;
        let span = self.current_span;

        if self.peek_is(|k| matches!(k, TokenKind::FlowSequenceEnd))? {
            self.skip()?;
            self.state = self.pop_state();
            return Ok(Event::SequenceEnd { span });
        }

        if self.peek_is(|k| matches!(k, TokenKind::Key))? {
            self.skip()?;
            self.state = State::FlowSequenceEntryMappingKey;
            self.states.push(State::FlowSequenceEntry);
            return Ok(Event::MappingStart {
                anchor: None,
                tag: None,
                span,
            });
        }

        // A bare `Value` (`:`) without a preceding `Key` means an implicit
        // empty-key mapping pair, e.g. `[ : value ]` (CFD4). Start a
        // mapping and route through the *Key* phase so the empty key is
        // emitted as a scalar event before the value — otherwise the
        // loader sees a MappingStart followed directly by the value
        // and treats the value as the key (which then has no value),
        // producing "unexpected mapping end".
        if self.peek_is(|k| matches!(k, TokenKind::Value))? {
            self.state = State::FlowSequenceEntryMappingKey;
            self.states.push(State::FlowSequenceEntry);
            return Ok(Event::MappingStart {
                anchor: None,
                tag: None,
                span,
            });
        }

        self.states.push(State::FlowSequenceEntry);
        self.parse_node(false, false)
    }

    fn parse_flow_sequence_entry_mapping_key(&mut self) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;

        if self.peek_is(|k| {
            matches!(
                k,
                TokenKind::Value | TokenKind::FlowEntry | TokenKind::FlowSequenceEnd
            )
        })? {
            self.state = State::FlowSequenceEntryMappingValue;
            Ok(self.empty_scalar(span))
        } else {
            self.states.push(State::FlowSequenceEntryMappingValue);
            self.parse_node(false, false)
        }
    }

    fn parse_flow_sequence_entry_mapping_value(&mut self) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;

        if self.peek_is(|k| matches!(k, TokenKind::Value))? {
            self.skip()?;
            if !self.peek_is(|k| matches!(k, TokenKind::FlowEntry | TokenKind::FlowSequenceEnd))? {
                self.states.push(State::FlowSequenceEntryMappingEnd);
                return self.parse_node(false, false);
            }
        }

        self.state = State::FlowSequenceEntryMappingEnd;
        Ok(self.empty_scalar(span))
    }

    fn parse_flow_sequence_entry_mapping_end(&mut self) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;
        self.state = self.pop_state();
        Ok(Event::MappingEnd { span })
    }

    // ── Flow mappings ────────────────────────────────────────────────────

    fn parse_flow_mapping_key(&mut self, first: bool) -> Result<Event<'a>, ScanError> {
        if !first {
            let _ = self.peek()?;
            let span = self.current_span;
            if self.peek_is(|k| matches!(k, TokenKind::FlowEntry))? {
                self.skip()?;
            } else if !self.peek_is(|k| matches!(k, TokenKind::FlowMappingEnd))? {
                return Err(ScanError {
                    message: Cow::Borrowed("expected ',' or '}' in flow mapping"),
                    index: span.start,
                });
            }
        }

        let _ = self.peek()?;
        let span = self.current_span;

        if self.peek_is(|k| matches!(k, TokenKind::FlowMappingEnd))? {
            self.skip()?;
            self.state = self.pop_state();
            return Ok(Event::MappingEnd { span });
        }

        if self.peek_is(|k| matches!(k, TokenKind::Key))? {
            self.skip()?;
            let _ = self.peek()?;
            let next_span = self.current_span;
            if !self.peek_is(|k| {
                matches!(
                    k,
                    TokenKind::Value | TokenKind::FlowEntry | TokenKind::FlowMappingEnd
                )
            })? {
                self.states.push(State::FlowMappingValue);
                return self.parse_node(false, false);
            }
            self.state = State::FlowMappingValue;
            return Ok(self.empty_scalar(next_span));
        }

        // A bare `Value` (`:`) without a preceding `Key` means the key is
        // empty, e.g. `{ : bar }`.  Emit an empty scalar for the key and
        // proceed directly to the value phase.
        if self.peek_is(|k| matches!(k, TokenKind::Value))? {
            self.state = State::FlowMappingValue;
            return Ok(self.empty_scalar(span));
        }

        // Implicit key.
        self.states.push(State::FlowMappingEmptyValue);
        self.parse_node(false, false)
    }

    fn parse_flow_mapping_value(&mut self, empty: bool) -> Result<Event<'a>, ScanError> {
        let _ = self.peek()?;
        let span = self.current_span;

        if empty {
            self.state = State::FlowMappingKey;
            return Ok(self.empty_scalar(span));
        }

        if self.peek_is(|k| matches!(k, TokenKind::Value))? {
            self.skip()?;
            if !self.peek_is(|k| matches!(k, TokenKind::FlowEntry | TokenKind::FlowMappingEnd))? {
                self.states.push(State::FlowMappingKey);
                return self.parse_node(false, false);
            }
        }

        self.state = State::FlowMappingKey;
        Ok(self.empty_scalar(span))
    }
}