deser-yaml 0.10.1

YAML support for deser
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
//! The YAML parser: turns tokens into [`Event`]s.
//!
//! This is a state machine with an explicit stack so that deeply nested
//! documents do not consume native stack space.
use std::borrow::Cow;

use deser_core::{Error, ErrorKind};

use crate::event::{Event, EventKind, Mark, Props, ScalarStyle};
use crate::scanner::{Scanner, Token, TokenKind, TokenType};

#[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,
}

pub(crate) struct Parser<'a> {
    scanner: Scanner<'a>,
    state: State,
    states: Vec<State>,
    /// The tag handles of the current document.
    tag_handles: Vec<(Cow<'a, str>, Cow<'a, str>)>,
    /// The end of the last event.  Block collections end there.
    last_end: Mark,
}

impl<'a> Parser<'a> {
    pub(crate) fn new(input: &'a str) -> Parser<'a> {
        Parser {
            scanner: Scanner::new(input),
            state: State::StreamStart,
            states: Vec::new(),
            tag_handles: Vec::new(),
            last_end: Mark::default(),
        }
    }

    /// Returns the next event.
    ///
    /// After [`EventKind::StreamEnd`] or an error, no more events must be
    /// requested.
    pub(crate) fn next_event(&mut self) -> Result<Event<'a>, Error> {
        let event = self.parse_event()?;
        self.last_end = event.end;
        Ok(event)
    }

    fn parse_event(&mut self) -> Result<Event<'a>, Error> {
        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 => panic!("next_event called after the end of the stream"),
        }
    }

    // -- helpers ----------------------------------------------------------

    fn peek(&mut self) -> Result<TokenType, Error> {
        self.scanner.peek_type()
    }

    fn peek_mark(&mut self) -> Result<Mark, Error> {
        Ok(self.scanner.peek_token()?.start)
    }

    fn next(&mut self) -> Token<'a> {
        self.scanner.next_token()
    }

    fn pop_state(&mut self) {
        self.state = self.states.pop().unwrap();
    }

    fn event(kind: EventKind<'a>, start: Mark, end: Mark) -> Result<Event<'a>, Error> {
        Ok(Event { kind, start, end })
    }

    fn empty_scalar(mark: Mark, props: Props<'a>) -> Result<Event<'a>, Error> {
        Self::event(
            EventKind::Scalar {
                props,
                style: ScalarStyle::Plain,
                value: Cow::Borrowed(""),
            },
            mark,
            mark,
        )
    }

    fn error<T>(&mut self, msg: &str) -> Result<T, Error> {
        let mark = self.peek_mark()?;
        Err(syntax_error(mark, msg))
    }

    // -- stream and documents ---------------------------------------------

    fn parse_stream_start(&mut self) -> Result<Event<'a>, Error> {
        self.peek()?;
        let token = self.next();
        debug_assert_eq!(token.kind, TokenKind::StreamStart);
        self.state = State::ImplicitDocumentStart;
        Self::event(EventKind::StreamStart, token.start, token.end)
    }

    /// Parses the start of a document.  `implicit` is `true` if a bare
    /// document (without `---`) is allowed here: at the start of the stream
    /// and after a document end marker.
    fn parse_document_start(&mut self, implicit: bool) -> Result<Event<'a>, Error> {
        let mut implicit = implicit;
        // extra document end markers
        while self.peek()? == TokenType::DocumentEnd {
            self.next();
            implicit = true;
        }

        match self.peek()? {
            TokenType::StreamEnd => {
                let token = self.next();
                self.state = State::End;
                Self::event(EventKind::StreamEnd, token.start, token.end)
            }
            TokenType::VersionDirective
            | TokenType::TagDirective
            | TokenType::ReservedDirective
            | TokenType::DocumentStart => {
                let start = self.peek_mark()?;
                if self.peek()? != TokenType::DocumentStart && !implicit {
                    return self.error("missing document end marker before directive");
                }
                let version = self.parse_directives()?;
                if self.peek()? != TokenType::DocumentStart {
                    return self.error("did not find expected <document start>");
                }
                let token = self.next();
                self.states.push(State::DocumentEnd);
                self.state = State::DocumentContent;
                Self::event(
                    EventKind::DocumentStart {
                        explicit: true,
                        version,
                    },
                    start,
                    token.end,
                )
            }
            _ if implicit => {
                let mark = self.peek_mark()?;
                self.reset_tag_handles();
                self.states.push(State::DocumentEnd);
                self.state = State::BlockNode;
                Self::event(
                    EventKind::DocumentStart {
                        explicit: false,
                        version: None,
                    },
                    mark,
                    mark,
                )
            }
            _ => self.error("did not find expected <document start>"),
        }
    }

    fn reset_tag_handles(&mut self) {
        self.tag_handles.clear();
        self.tag_handles
            .push((Cow::Borrowed("!"), Cow::Borrowed("!")));
        self.tag_handles
            .push((Cow::Borrowed("!!"), Cow::Borrowed("tag:yaml.org,2002:")));
    }

    /// Parses the directives of a document and returns the version.
    fn parse_directives(&mut self) -> Result<Option<(u32, u32)>, Error> {
        self.reset_tag_handles();
        let mut version = None;
        let mut custom_handles = Vec::new();
        loop {
            match self.peek()? {
                TokenType::VersionDirective => {
                    let token = self.next();
                    if version.is_some() {
                        return Err(syntax_error(token.start, "duplicate %YAML directive"));
                    }
                    if let TokenKind::VersionDirective(major, minor) = token.kind {
                        if major != 1 {
                            return Err(syntax_error(
                                token.start,
                                "incompatible YAML document version",
                            ));
                        }
                        version = Some((major, minor));
                    }
                }
                TokenType::TagDirective => {
                    let token = self.next();
                    if let TokenKind::TagDirective(handle, prefix) = token.kind {
                        if custom_handles.contains(&handle) {
                            return Err(syntax_error(token.start, "duplicate %TAG directive"));
                        }
                        custom_handles.push(handle.clone());
                        self.tag_handles.retain(|(h, _)| *h != handle);
                        self.tag_handles.push((handle, prefix));
                    }
                }
                TokenType::ReservedDirective => {
                    self.next();
                }
                _ => return Ok(version),
            }
        }
    }

    fn parse_document_content(&mut self) -> Result<Event<'a>, Error> {
        match self.peek()? {
            TokenType::VersionDirective
            | TokenType::TagDirective
            | TokenType::ReservedDirective
            | TokenType::DocumentStart
            | TokenType::DocumentEnd
            | TokenType::StreamEnd => {
                let mark = self.peek_mark()?;
                self.pop_state();
                Self::empty_scalar(mark, Props::default())
            }
            _ => self.parse_node(true, false),
        }
    }

    fn parse_document_end(&mut self) -> Result<Event<'a>, Error> {
        let start = self.peek_mark()?;
        let mut end = start;
        let explicit = self.peek()? == TokenType::DocumentEnd;
        if explicit {
            end = self.next().end;
            self.state = State::ImplicitDocumentStart;
        } else {
            // without a document end marker, only an explicit document
            // (or the end of the stream) may follow
            match self.peek()? {
                TokenType::DocumentStart | TokenType::StreamEnd => {}
                TokenType::VersionDirective
                | TokenType::TagDirective
                | TokenType::ReservedDirective => {
                    return self.error("missing document end marker before directive");
                }
                _ => return self.error("did not find expected <document start>"),
            }
            self.state = State::DocumentStart;
        }
        Self::event(EventKind::DocumentEnd { explicit }, start, end)
    }

    // -- nodes ------------------------------------------------------------

    fn resolve_tag(
        &self,
        handle: Cow<'a, str>,
        suffix: Cow<'a, str>,
        mark: Mark,
    ) -> Result<Cow<'a, str>, Error> {
        if handle.is_empty() {
            // verbatim
            return Ok(suffix);
        }
        if handle == "!" && suffix.is_empty() {
            return Ok(Cow::Borrowed("!"));
        }
        for (h, prefix) in &self.tag_handles {
            if *h == handle {
                return Ok(Cow::Owned(format!("{}{}", prefix, suffix)));
            }
        }
        Err(syntax_error(mark, "found undefined tag handle"))
    }

    fn parse_node(&mut self, block: bool, indentless_sequence: bool) -> Result<Event<'a>, Error> {
        if self.peek()? == TokenType::Alias {
            let token = self.next();
            self.pop_state();
            if let TokenKind::Alias(anchor) = token.kind {
                return Self::event(EventKind::Alias { anchor }, token.start, token.end);
            }
            unreachable!();
        }

        let start = self.peek_mark()?;
        let mut props = Props::default();
        let mut has_props = false;
        loop {
            match self.peek()? {
                TokenType::Anchor => {
                    if props.anchor.is_some() {
                        return self.error("a node can only have one anchor");
                    }
                    if let TokenKind::Anchor(name) = self.next().kind {
                        props.anchor = Some(name);
                    }
                }
                TokenType::Tag => {
                    if props.tag.is_some() {
                        return self.error("a node can only have one tag");
                    }
                    let token = self.next();
                    if let TokenKind::Tag(handle, suffix) = token.kind {
                        props.tag = Some(self.resolve_tag(handle, suffix, token.start)?);
                    }
                }
                _ => break,
            }
            has_props = true;
        }

        let mark = self.peek_mark()?;
        match self.peek()? {
            TokenType::BlockEntry if indentless_sequence => {
                self.state = State::IndentlessSequenceEntry;
                Self::event(EventKind::SequenceStart { props, flow: false }, start, mark)
            }
            TokenType::Scalar => {
                let token = self.next();
                self.pop_state();
                if let TokenKind::Scalar(style, value) = token.kind {
                    return Self::event(
                        EventKind::Scalar {
                            props,
                            style,
                            value,
                        },
                        start,
                        token.end,
                    );
                }
                unreachable!();
            }
            TokenType::FlowSequenceStart => {
                self.state = State::FlowSequenceFirstEntry;
                Self::event(EventKind::SequenceStart { props, flow: true }, start, mark)
            }
            TokenType::FlowMappingStart => {
                self.state = State::FlowMappingFirstKey;
                Self::event(EventKind::MappingStart { props, flow: true }, start, mark)
            }
            TokenType::BlockSequenceStart if block => {
                self.state = State::BlockSequenceFirstEntry;
                Self::event(EventKind::SequenceStart { props, flow: false }, start, mark)
            }
            TokenType::BlockMappingStart if block => {
                self.state = State::BlockMappingFirstKey;
                Self::event(EventKind::MappingStart { props, flow: false }, start, mark)
            }
            TokenType::Alias if has_props => self.error("an alias cannot have properties"),
            _ if has_props => {
                self.pop_state();
                Self::empty_scalar(mark, props)
            }
            _ => self.error("did not find expected node content"),
        }
    }

    // -- block collections ------------------------------------------------

    fn parse_block_sequence_entry(&mut self, first: bool) -> Result<Event<'a>, Error> {
        if first {
            let token = self.next();
            debug_assert_eq!(token.kind, TokenKind::BlockSequenceStart);
        }
        match self.peek()? {
            TokenType::BlockEntry => {
                let token = self.next();
                match self.peek()? {
                    TokenType::BlockEntry | TokenType::BlockEnd => {
                        self.state = State::BlockSequenceEntry;
                        Self::empty_scalar(token.end, Props::default())
                    }
                    _ => {
                        self.states.push(State::BlockSequenceEntry);
                        self.parse_node(true, false)
                    }
                }
            }
            TokenType::BlockEnd => {
                self.next();
                self.pop_state();
                Self::event(EventKind::SequenceEnd, self.last_end, self.last_end)
            }
            _ => self.error("did not find expected '-' indicator"),
        }
    }

    fn parse_indentless_sequence_entry(&mut self) -> Result<Event<'a>, Error> {
        if self.peek()? == TokenType::BlockEntry {
            let token = self.next();
            match self.peek()? {
                TokenType::BlockEntry | TokenType::Key | TokenType::Value | TokenType::BlockEnd => {
                    self.state = State::IndentlessSequenceEntry;
                    Self::empty_scalar(token.end, Props::default())
                }
                _ => {
                    self.states.push(State::IndentlessSequenceEntry);
                    self.parse_node(true, false)
                }
            }
        } else {
            self.pop_state();
            Self::event(EventKind::SequenceEnd, self.last_end, self.last_end)
        }
    }

    fn parse_block_mapping_key(&mut self, first: bool) -> Result<Event<'a>, Error> {
        if first {
            let token = self.next();
            debug_assert_eq!(token.kind, TokenKind::BlockMappingStart);
        }
        match self.peek()? {
            TokenType::Key => {
                let token = self.next();
                match self.peek()? {
                    TokenType::Key | TokenType::Value | TokenType::BlockEnd => {
                        self.state = State::BlockMappingValue;
                        Self::empty_scalar(token.end, Props::default())
                    }
                    _ => {
                        self.states.push(State::BlockMappingValue);
                        self.parse_node(true, true)
                    }
                }
            }
            TokenType::Value => {
                let mark = self.peek_mark()?;
                self.state = State::BlockMappingValue;
                Self::empty_scalar(mark, Props::default())
            }
            TokenType::BlockEnd => {
                self.next();
                self.pop_state();
                Self::event(EventKind::MappingEnd, self.last_end, self.last_end)
            }
            _ => self.error("did not find expected key"),
        }
    }

    fn parse_block_mapping_value(&mut self) -> Result<Event<'a>, Error> {
        if self.peek()? == TokenType::Value {
            let token = self.next();
            match self.peek()? {
                TokenType::Key | TokenType::Value | TokenType::BlockEnd => {
                    self.state = State::BlockMappingKey;
                    Self::empty_scalar(token.end, Props::default())
                }
                _ => {
                    self.states.push(State::BlockMappingKey);
                    self.parse_node(true, true)
                }
            }
        } else {
            let mark = self.peek_mark()?;
            self.state = State::BlockMappingKey;
            Self::empty_scalar(mark, Props::default())
        }
    }

    // -- flow collections -------------------------------------------------

    fn parse_flow_sequence_entry(&mut self, first: bool) -> Result<Event<'a>, Error> {
        if first {
            self.next();
        }
        if self.peek()? != TokenType::FlowSequenceEnd {
            if !first {
                if self.peek()? == TokenType::FlowEntry {
                    self.next();
                } else {
                    return self.error("did not find expected ',' or ']'");
                }
            }
            match self.peek()? {
                TokenType::Key => {
                    let token = self.next();
                    self.state = State::FlowSequenceEntryMappingKey;
                    return Self::event(
                        EventKind::MappingStart {
                            props: Props::default(),
                            flow: true,
                        },
                        token.start,
                        token.end,
                    );
                }
                TokenType::Value => {
                    // a single pair with an empty key
                    let mark = self.peek_mark()?;
                    self.state = State::FlowSequenceEntryMappingKey;
                    return Self::event(
                        EventKind::MappingStart {
                            props: Props::default(),
                            flow: true,
                        },
                        mark,
                        mark,
                    );
                }
                TokenType::FlowSequenceEnd => {}
                _ => {
                    self.states.push(State::FlowSequenceEntry);
                    return self.parse_node(false, false);
                }
            }
        }
        let token = self.next();
        self.pop_state();
        Self::event(EventKind::SequenceEnd, token.start, token.end)
    }

    fn parse_flow_sequence_entry_mapping_key(&mut self) -> Result<Event<'a>, Error> {
        match self.peek()? {
            TokenType::Value | TokenType::FlowEntry | TokenType::FlowSequenceEnd => {
                let mark = self.peek_mark()?;
                self.state = State::FlowSequenceEntryMappingValue;
                Self::empty_scalar(mark, Props::default())
            }
            _ => {
                self.states.push(State::FlowSequenceEntryMappingValue);
                self.parse_node(false, false)
            }
        }
    }

    fn parse_flow_sequence_entry_mapping_value(&mut self) -> Result<Event<'a>, Error> {
        if self.peek()? == TokenType::Value {
            let token = self.next();
            match self.peek()? {
                TokenType::FlowEntry | TokenType::FlowSequenceEnd => {
                    self.state = State::FlowSequenceEntryMappingEnd;
                    Self::empty_scalar(token.end, Props::default())
                }
                _ => {
                    self.states.push(State::FlowSequenceEntryMappingEnd);
                    self.parse_node(false, false)
                }
            }
        } else {
            let mark = self.peek_mark()?;
            self.state = State::FlowSequenceEntryMappingEnd;
            Self::empty_scalar(mark, Props::default())
        }
    }

    fn parse_flow_sequence_entry_mapping_end(&mut self) -> Result<Event<'a>, Error> {
        let mark = self.peek_mark()?;
        self.state = State::FlowSequenceEntry;
        Self::event(EventKind::MappingEnd, mark, mark)
    }

    fn parse_flow_mapping_key(&mut self, first: bool) -> Result<Event<'a>, Error> {
        if first {
            self.next();
        }
        if self.peek()? != TokenType::FlowMappingEnd {
            if !first {
                if self.peek()? == TokenType::FlowEntry {
                    self.next();
                } else {
                    return self.error("did not find expected ',' or '}'");
                }
            }
            match self.peek()? {
                TokenType::Key => {
                    let token = self.next();
                    return match self.peek()? {
                        TokenType::Value | TokenType::FlowEntry | TokenType::FlowMappingEnd => {
                            self.state = State::FlowMappingValue;
                            Self::empty_scalar(token.end, Props::default())
                        }
                        _ => {
                            self.states.push(State::FlowMappingValue);
                            self.parse_node(false, false)
                        }
                    };
                }
                TokenType::Value => {
                    let mark = self.peek_mark()?;
                    self.state = State::FlowMappingValue;
                    return Self::empty_scalar(mark, Props::default());
                }
                TokenType::FlowMappingEnd => {}
                _ => {
                    self.states.push(State::FlowMappingEmptyValue);
                    return self.parse_node(false, false);
                }
            }
        }
        let token = self.next();
        self.pop_state();
        Self::event(EventKind::MappingEnd, token.start, token.end)
    }

    fn parse_flow_mapping_value(&mut self, empty: bool) -> Result<Event<'a>, Error> {
        let mark = self.peek_mark()?;
        if empty {
            self.state = State::FlowMappingKey;
            return Self::empty_scalar(mark, Props::default());
        }
        if self.peek()? == TokenType::Value {
            let token = self.next();
            match self.peek()? {
                TokenType::FlowEntry | TokenType::FlowMappingEnd => {
                    self.state = State::FlowMappingKey;
                    Self::empty_scalar(token.end, Props::default())
                }
                _ => {
                    self.states.push(State::FlowMappingKey);
                    self.parse_node(false, false)
                }
            }
        } else {
            self.state = State::FlowMappingKey;
            Self::empty_scalar(mark, Props::default())
        }
    }
}

/// Creates an error for a problem at a position that is not a syntax
/// error (for instance an invalid value).
#[cold]
pub(crate) fn error_at(mark: Mark, msg: &str) -> Error {
    Error::with_position(
        ErrorKind::Syntax,
        msg.to_string(),
        mark.offset,
        mark.line + 1,
        mark.column + 1,
    )
}

#[cold]
pub(crate) fn syntax_error(mark: Mark, msg: &str) -> Error {
    Error::with_position(
        ErrorKind::Syntax,
        format!("syntax error: {}", msg),
        mark.offset,
        mark.line + 1,
        mark.column + 1,
    )
}