Skip to main content

rlsp_yaml_parser/
lib.rs

1// SPDX-License-Identifier: MIT
2
3mod chars;
4pub mod encoding;
5mod error;
6mod event;
7mod event_iter;
8pub(crate) mod lexer;
9pub mod limits;
10mod lines;
11pub mod loader;
12pub mod node;
13mod pos;
14pub use error::Error;
15pub use event::{Chomp, CollectionStyle, Event, ScalarStyle};
16pub use lines::{BreakType, Line, LineBuffer};
17pub use loader::{LoadError, LoadMode, Loader, LoaderBuilder, LoaderOptions, load};
18pub use node::{Document, Node};
19pub use pos::{Pos, Span};
20
21pub use limits::{
22    MAX_ANCHOR_NAME_BYTES, MAX_COLLECTION_DEPTH, MAX_COMMENT_LEN, MAX_DIRECTIVES_PER_DOC,
23    MAX_RESOLVED_TAG_LEN, MAX_TAG_HANDLE_BYTES, MAX_TAG_LEN,
24};
25use std::collections::VecDeque;
26
27use event_iter::{CollectionEntry, DirectiveScope, IterState, PendingAnchor, PendingTag};
28
29use lexer::Lexer;
30
31/// Parse a YAML string into a lazy event stream.
32///
33/// The iterator yields <code>Result<([Event], [Span]), [Error]></code> items.
34/// The first event is always [`Event::StreamStart`] and the last is always
35/// [`Event::StreamEnd`].
36///
37/// # Example
38///
39/// ```
40/// use rlsp_yaml_parser::{parse_events, Event};
41///
42/// let events: Vec<_> = parse_events("").collect();
43/// assert!(matches!(events.first(), Some(Ok((Event::StreamStart, _)))));
44/// assert!(matches!(events.last(), Some(Ok((Event::StreamEnd, _)))));
45/// ```
46pub fn parse_events(input: &str) -> impl Iterator<Item = Result<(Event<'_>, Span), Error>> + '_ {
47    EventIter::new(input)
48}
49
50// ---------------------------------------------------------------------------
51// Iterator implementation
52// ---------------------------------------------------------------------------
53
54/// Lazy iterator that yields events by walking a [`Lexer`].
55struct EventIter<'input> {
56    lexer: Lexer<'input>,
57    state: IterState,
58    /// Queued events to emit before resuming normal state dispatch.
59    ///
60    /// Used when a single parse step must produce multiple consecutive events —
61    /// e.g. `SequenceStart` before the first item, or multiple close events
62    /// when a dedent closes several nested collections at once.
63    queue: VecDeque<(Event<'input>, Span)>,
64    /// Stack of open block collections (sequences and mappings).
65    ///
66    /// Each entry records whether the open collection is a sequence or a
67    /// mapping, its indentation column, and (for mappings) whether the next
68    /// expected node is a key or a value.  The combined length of this stack
69    /// is bounded by [`MAX_COLLECTION_DEPTH`].
70    coll_stack: Vec<CollectionEntry>,
71    /// A pending anchor that has been scanned but not yet attached to a node
72    /// event.  The [`PendingAnchor`] variant encodes both the anchor name and
73    /// whether it was standalone (applies to the next node of any type) or
74    /// inline (applies to the key scalar, not the enclosing mapping).
75    pending_anchor: Option<PendingAnchor<'input>>,
76    /// A pending tag that has been scanned but not yet attached to a node event.
77    ///
78    /// Tags in YAML precede the node they annotate (YAML 1.2 §6.8.1).  After
79    /// scanning `!tag`, `!!tag`, `!<uri>`, or `!`, the parser stores the tag
80    /// here and attaches it to the next `Scalar`, `SequenceStart`, or
81    /// `MappingStart` event.
82    ///
83    /// Tags are resolved against the current directive scope at scan time:
84    /// - `!<URI>`  → stored as `Cow::Borrowed("URI")` (verbatim, no change)
85    /// - `!!suffix` → resolved via `!!` handle (default: `tag:yaml.org,2002:suffix`)
86    /// - `!suffix` → stored as `Cow::Borrowed("!suffix")` (local tag, no expansion)
87    /// - `!`       → stored as `Cow::Borrowed("!")`
88    /// - `!handle!suffix` → resolved via `%TAG !handle! prefix` directive
89    ///
90    /// The [`PendingTag`] variant encodes both the resolved tag string and
91    /// whether it was standalone (applies to the next node of any type) or
92    /// inline (applies to the key scalar, not the enclosing mapping).
93    pending_tag: Option<PendingTag<'input>>,
94    /// Directive scope for the current document.
95    ///
96    /// Accumulated from `%YAML` and `%TAG` directives seen in `BetweenDocs`
97    /// state.  Reset at document boundaries.
98    directive_scope: DirectiveScope,
99    /// Set to `true` once the root node of the current document has been
100    /// fully emitted (a scalar at the top level, or a collection after its
101    /// closing event empties `coll_stack`).
102    ///
103    /// Used to detect invalid extra content after the document root, such as
104    /// `foo:\n  bar\ninvalid` where `invalid` appears after the root mapping
105    /// closes.  Reset to `false` at each document boundary.
106    root_node_emitted: bool,
107    /// Set to `true` after consuming a `? ` explicit key indicator whose key
108    /// content will appear on the NEXT line (i.e., `had_key_inline = false`).
109    /// Cleared when the key content is processed.
110    ///
111    /// Used to allow a block sequence indicator on a line following `? ` to be
112    /// treated as the explicit key's content rather than triggering the
113    /// "invalid block sequence entry" guard.
114    explicit_key_pending: bool,
115    /// When a tag or anchor appears inline on a physical line (e.g. `!!str &a key:`),
116    /// the key content is prepended as a synthetic line with the key's column as its
117    /// indent.  This field records the indent of the ORIGINAL physical line so that
118    /// `handle_mapping_entry` can open the mapping at the correct (original) indent
119    /// rather than the synthetic line's offset.
120    property_origin_indent: Option<usize>,
121}
122
123impl EventIter<'_> {
124    /// Current combined collection depth (sequences + mappings).
125    const fn collection_depth(&self) -> usize {
126        self.coll_stack.len()
127    }
128}
129
130/// Build an empty plain scalar event.
131pub(crate) const fn empty_scalar_event<'input>() -> Event<'input> {
132    Event::Scalar {
133        value: std::borrow::Cow::Borrowed(""),
134        style: ScalarStyle::Plain,
135        anchor: None,
136        tag: None,
137    }
138}
139
140/// Build a span that covers exactly the 3-byte document marker at `marker_pos`.
141pub(crate) const fn marker_span(marker_pos: Pos) -> Span {
142    Span {
143        start: marker_pos,
144        end: Pos {
145            byte_offset: marker_pos.byte_offset + 3,
146            line: marker_pos.line,
147            column: marker_pos.column + 3,
148        },
149    }
150}
151
152/// Build a zero-width span at `pos`.
153pub(crate) const fn zero_span(pos: Pos) -> Span {
154    Span {
155        start: pos,
156        end: pos,
157    }
158}