granit_parser/lib.rs
1// Copyright 2015, Yuheng Chen.
2// Copyright 2023, Ethiraric.
3// See the LICENSE file at the top-level directory of this distribution.
4
5//! YAML 1.2 parser implementation in pure Rust.
6//!
7//! `granit-parser` is a low-level event parser. It reads YAML input and yields a stream of
8//! [`Event`] values paired with their source [`Span`].
9//! With the default `comments` feature, comments are emitted as `Event::Comment`. They
10//! are presentation metadata, not YAML data nodes, so consumers building YAML value trees should
11//! ignore them.
12//!
13//! Add it to your project:
14//!
15//! ```sh
16//! cargo add granit-parser
17//! ```
18//!
19//! # Usage
20//!
21//! ```rust
22//! # fn main() -> Result<(), granit_parser::ScanError> {
23//! # #[cfg(feature = "comments")]
24//! # {
25//! use granit_parser::{Event, Parser, Placement};
26//!
27//! let yaml = r#"# header
28//! items: # inline
29//! - milk
30//! - bread
31//! "#;
32//! let mut comments = Vec::new();
33//!
34//! for next in Parser::new_from_str(yaml) {
35//! let (event, span) = next?;
36//! if let Event::Comment { value: text, placement, .. } = event {
37//! comments.push((
38//! text.into_owned(),
39//! placement,
40//! span.slice(yaml).unwrap().to_owned(),
41//! ));
42//! }
43//! }
44//!
45//! assert_eq!(
46//! comments,
47//! [
48//! (" header".to_owned(), Placement::Above, "# header".to_owned()),
49//! (" inline".to_owned(), Placement::Right, "# inline".to_owned()),
50//! ]
51//! );
52//! # }
53//! # Ok(())
54//! # }
55//! ```
56//!
57//! For comment events, the companion [`Span`] covers the whole source comment, including `#` and
58//! excluding the line break. With [`Parser::new_from_str`], [`Span::slice`] returns that source
59//! comment text.
60//!
61//! # Anchor and tag source metadata
62//!
63//! Set [`Options::emit_anchor_events`] to receive [`Event::Anchor`] with the assigned ID and
64//! original name, without `&`. Its companion span covers the complete `&name` token. This event
65//! immediately follows the anchored scalar or collection start, before any collection children.
66//! It is presentation metadata, so [`Event::is_node`] returns `false`. Its source range precedes
67//! the node content even though the event follows the node. Emission defaults to `false`, leaving
68//! existing event streams unchanged.
69//!
70//! The adjacency guarantee applies within each [`Parser`]. With [`ParserStack`], consume pending
71//! anchor metadata before pushing another source if relying on adjacency in the combined stream.
72//!
73//! Resolved [`Event::Alias`] events carry the target ID and a complete `*name` token span. An
74//! unresolved alias can instead be exposed through [`Options::emit_unresolved_aliases`]. Explicit
75//! tags remain on node events; [`Span::tag_span`] preserves their complete raw token, including
76//! verbatim notation and percent escapes that normalized tag helpers may not reproduce.
77//!
78//! ```rust
79//! use std::collections::BTreeMap;
80//! use granit_parser::{Event, Parser};
81//!
82//! let yaml = "message: &msg !note hello\ncopy: *msg\nexample: \"&msg is just text\"\n";
83//! let options = granit_parser::options! { emit_anchor_events: true };
84//! let mut anchors = BTreeMap::new();
85//! for result in Parser::new_from_str_with_options(yaml, options) {
86//! let (event, span) = result?;
87//! if let Some(tag_span) = span.tag_span() {
88//! assert_eq!(tag_span.slice(yaml), Some("!note"));
89//! }
90//! match event {
91//! Event::Anchor { anchor_id: id, name, .. } => {
92//! assert_eq!(span.slice(yaml), Some("&msg"));
93//! anchors.insert(id, (name, span));
94//! }
95//! Event::Alias { anchor_id: id, .. } => {
96//! let (name, definition_span) = &anchors[&id];
97//! assert_eq!(name, "msg");
98//! assert_eq!(definition_span.slice(yaml), Some("&msg"));
99//! assert_eq!(span.slice(yaml), Some("*msg"));
100//! }
101//! _ => {}
102//! }
103//! }
104//! assert_eq!(anchors.len(), 1); // The quoted text does not define an anchor.
105//! # Ok::<(), granit_parser::ScanError>(())
106//! ```
107//!
108//! # Limits
109//!
110//! [`Options::strict_indentation`] enables strict YAML indentation for flow collections and
111//! quoted scalars. It defaults to `false` for compatibility with `PyYAML` and ruamel.yaml,
112//! accepting under-indented flow entries, delimiters, and quoted scalar continuations.
113//! [`Options`] also controls comment emission and limits on buffered comments,
114//! simple-key lookahead, directive retention, and flow- and block-collection nesting. With the
115//! `comments` feature, comment tokens and events are emitted by default; setting
116//! `Options::emit_comments` to `false`
117//! recognizes and validates comments without capturing their text or emitting them. The defaults
118//! allow 96 buffered comment events, 1024 characters of simple-key lookahead, 1024 bytes of retained
119//! directive data, 16 reserved-directive parameters, 255 nested flow collections, and 255 nested
120//! block collections.
121//! Existing constructors use these defaults.
122//! Without the `comments` feature, comment capture and emission are compiled out of scanners,
123//! parsers, and parser stacks. YAML comments are still skipped and validated.
124//! [`Options::emit_comments`] remains available and defaults to `true` with the feature enabled
125//! and `false` without it. Setting it to `true` has no effect without the feature.
126//! [`Parser::new_from_str_with_options`], [`Parser::new_from_iter_with_options`],
127//! [`Parser::new_from_fallible_iter_with_options`], [`Parser::with_options`],
128//! [`Scanner::with_options`], and [`ParserStack::with_options`] accept customized options created
129//! with [`options!`].
130//!
131//! Tooling can set [`Options::emit_unresolved_aliases`] to `true` to receive
132//! [`Event::UnresolvedAlias`] nodes and continue structural parsing when an anchor is missing.
133//! These references remain invalid YAML and must be handled by the consumer. The option defaults
134//! to `false`, preserving the [`ErrorKind::UnknownAnchor`] error and termination.
135//!
136//! # Features
137//! **Note:** This crate's MSRV is `1.81.0`.
138//!
139//! #### `comments` (enabled by default)
140//! Enables scanner comment tokens, parser comment events, and their capture, placement, buffering,
141//! and continuation state. Without it, scanners skip comments without retaining their text, and
142//! comment-specific state is compiled out. YAML comment syntax and source positions are still
143//! validated and tracked.
144//!
145//! `Comment`, `Placement`, `TokenType::Comment`, `Event::Comment`, `ErrorKind::TooManyComments`,
146//! `Options::max_buffered_comment_events`, and `Input::may_contain_comments` are available only
147//! with this feature.
148//!
149//! #### `extended_details` (disabled by default)
150//! Adds block-scalar header syntax and the document-end `explicit` flag. Their fields,
151//! accessors, builders, and metadata capture are compiled out without the feature. Decoded
152//! values, event spans, style classification, and omitted-scalar identity remain available.
153//! `BlockScalarSyntax` and `Chomping` are public only with this feature.
154//!
155//! Basic constructors have the same signatures in either configuration. Synthetic block styles
156//! start with unknown syntax (`None`); opt-in `with_*` methods attach known metadata.
157//!
158//! #### `test_equality` (disabled by default)
159//! Enables `PartialEq` and `Eq` for parser output in regression tests. Equality ignores optional
160//! `extended_details` metadata: synthetic values may lack source information, and another
161//! dependency enabling its capture must not change comparisons. Tests of source syntax should
162//! compare those fields explicitly. This feature does not enable `extended_details`, hashing,
163//! or ordering. Classify variants with `matches!` and `{ .. }` in application code so future
164//! metadata fields do not alter those checks.
165//!
166//! #### `error_messages` (enabled by default)
167//! Provides human-readable text through [`ErrorKind`]'s `Display` implementation and
168//! [`ScanError::info`]. Disabling this feature makes both render an empty string while retaining
169//! machine-readable error kinds and source markers.
170//!
171//! #### `std`
172//! Retains the original `std::io::Error` inside [`InputIoError`] when constructed through
173//! `InputIoError::from_io` or its `From<std::io::Error>` implementation. Without this feature,
174//! [`InputIoError::from_message`] remains available for portable `no_std` error reporting.
175//!
176//! #### `debug_prints`
177//! Enables the `debug` module and usage of debug prints in the scanner and the parser. Do not
178//! enable if you are consuming the crate rather than working on it as this can significantly
179//! decrease performance. Output remains opt-in behind a local compile-time toggle in
180//! `src/debug.rs`.
181//!
182//! This feature does not raise the MSRV further.
183//!
184//! This feature enables `std` and is _not_ `no_std` compatible.
185
186#![forbid(unsafe_code)]
187#![warn(missing_docs, clippy::pedantic)]
188#![no_std]
189
190extern crate alloc;
191
192#[cfg(feature = "std")]
193extern crate std;
194
195mod char_traits;
196#[macro_use]
197mod debug;
198mod error;
199pub mod input;
200mod macros;
201mod options;
202mod parser;
203mod parser_stack;
204mod scalar_style;
205mod scanner;
206
207pub use crate::error::{ErrorKind, InputIoError, ScanError};
208pub use crate::input::{str::StrInput, BorrowedInput, BufferedInput, FallibleBufferedInput, Input};
209pub use crate::options::Options;
210pub use crate::parser::{
211 Event, EventReceiver, ParseResult, Parser, ParserTrait, SpannedEventReceiver, StructureStyle,
212 Tag, TryEventReceiver, TryLoadError, TrySpannedEventReceiver, YamlVersion,
213};
214pub use crate::parser_stack::{
215 ParserStack, ReplayParser, SourceId, SourceIds, SourceNames, Sourced,
216};
217pub use crate::scalar_style::ScalarKind;
218#[cfg(feature = "extended_details")]
219pub use crate::scalar_style::{BlockScalarSyntax, Chomping};
220#[cfg(feature = "comments")]
221pub use crate::scanner::{Comment, Placement};
222pub use crate::scanner::{Marker, ScalarStyle, Scanner, Span, Token, TokenType};
223
224// The README demonstrates the opt-in metadata API. Test its examples with that feature enabled
225// without duplicating the README in the rendered crate-level documentation.
226#[cfg(all(doctest, feature = "extended_details"))]
227#[doc = include_str!("../README.md")]
228mod readme_doctests {}
229
230// Verify the feature-disabled public API without adding these checks to rendered documentation.
231#[cfg(all(doctest, not(feature = "comments")))]
232/// ```compile_fail
233/// use granit_parser::Comment;
234/// ```
235/// ```compile_fail
236/// use granit_parser::Placement;
237/// ```
238/// ```compile_fail
239/// let _ = granit_parser::Event::Comment;
240/// ```
241/// ```compile_fail
242/// let _ = granit_parser::TokenType::Comment;
243/// ```
244/// ```compile_fail
245/// let _ = granit_parser::Options::default().max_buffered_comment_events;
246/// ```
247/// ```compile_fail
248/// let _ = granit_parser::ErrorKind::TooManyComments;
249/// ```
250/// ```compile_fail
251/// use granit_parser::{Input, StrInput};
252/// let _ = <StrInput<'_> as Input>::may_contain_comments(&StrInput::new(""));
253/// ```
254mod comments_disabled_doctests {}
255
256// Verify that additional source-detail APIs are absent from ordinary builds.
257#[cfg(all(doctest, not(feature = "extended_details")))]
258/// ```compile_fail
259/// use granit_parser::BlockScalarSyntax;
260/// ```
261/// ```compile_fail
262/// use granit_parser::Chomping;
263/// ```
264/// ```compile_fail
265/// let _ = granit_parser::ScalarStyle::literal().block_syntax();
266/// ```
267mod extended_details_disabled_doctests {}