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(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//! # Limits
62//!
63//! [`Options::strict_indentation`] enables strict YAML indentation for flow collections. It
64//! defaults to `false` for compatibility with `PyYAML` and ruamel.yaml, accepting under-indented flow entries
65//! and delimiters. [`Options`] also controls comment emission and limits on buffered comments,
66//! simple-key lookahead, directive retention, and flow- and block-collection nesting. With the
67//! `comments` feature, comment tokens and events are emitted by default; setting
68//! `Options::emit_comments` to `false`
69//! recognizes and validates comments without capturing their text or emitting them. The defaults
70//! allow 96 buffered comment events, 1024 characters of simple-key lookahead, 1024 bytes of retained
71//! directive data, 16 reserved-directive parameters, 255 nested flow collections, and 255 nested
72//! block collections.
73//! Existing constructors use these defaults.
74//! Without the `comments` feature, comment capture and emission are compiled out of scanners,
75//! parsers, and parser stacks. YAML comments are still skipped and validated.
76//! [`Options::emit_comments`] remains available and defaults to `true` with the feature enabled
77//! and `false` without it. Setting it to `true` has no effect without the feature.
78//! [`Parser::new_from_str_with_options`], [`Parser::new_from_iter_with_options`],
79//! [`Parser::new_from_fallible_iter_with_options`], [`Parser::with_options`],
80//! [`Scanner::with_options`], and [`ParserStack::with_options`] accept customized options created
81//! with [`options!`].
82//!
83//! # Features
84//! **Note:** This crate's MSRV is `1.81.0`.
85//!
86//! #### `comments` (enabled by default)
87//! Enables scanner comment tokens, parser comment events, and their capture, placement, buffering,
88//! and continuation state. Without it, scanners skip comments without retaining their text, and
89//! comment-specific state is compiled out. YAML comment syntax and source positions are still
90//! validated and tracked.
91//!
92//! `Comment`, `Placement`, `TokenType::Comment`, `Event::Comment`, `ErrorKind::TooManyComments`,
93//! `Options::max_buffered_comment_events`, and `Input::may_contain_comments` are available only
94//! with this feature.
95//!
96//! #### `error_messages` (enabled by default)
97//! Provides human-readable text through [`ErrorKind`]'s `Display` implementation and
98//! [`ScanError::info`]. Disabling this feature makes both render an empty string while retaining
99//! machine-readable error kinds and source markers.
100//!
101//! #### `std`
102//! Retains the original `std::io::Error` inside [`InputIoError`] when constructed through
103//! `InputIoError::from_io` or its `From<std::io::Error>` implementation. Without this feature,
104//! [`InputIoError::from_message`] remains available for portable `no_std` error reporting.
105//!
106//! #### `debug_prints`
107//! Enables the `debug` module and usage of debug prints in the scanner and the parser. Do not
108//! enable if you are consuming the crate rather than working on it as this can significantly
109//! decrease performance. Output remains opt-in behind a local compile-time toggle in
110//! `src/debug.rs`.
111//!
112//! This feature does not raise the MSRV further.
113//!
114//! This feature enables `std` and is _not_ `no_std` compatible.
115
116#![forbid(unsafe_code)]
117#![warn(missing_docs, clippy::pedantic)]
118#![no_std]
119
120extern crate alloc;
121
122#[cfg(feature = "std")]
123extern crate std;
124
125mod char_traits;
126#[macro_use]
127mod debug;
128mod error;
129pub mod input;
130mod macros;
131mod options;
132mod parser;
133mod parser_stack;
134mod scanner;
135
136pub use crate::error::{ErrorKind, InputIoError, ScanError};
137pub use crate::input::{str::StrInput, BorrowedInput, BufferedInput, FallibleBufferedInput, Input};
138pub use crate::options::Options;
139pub use crate::parser::{
140 Event, EventReceiver, ParseResult, Parser, ParserTrait, SpannedEventReceiver, StructureStyle,
141 Tag, TryEventReceiver, TryLoadError, TrySpannedEventReceiver, YamlVersion,
142};
143pub use crate::parser_stack::{ParserStack, ReplayParser};
144#[cfg(feature = "comments")]
145pub use crate::scanner::{Comment, Placement};
146pub use crate::scanner::{Marker, ScalarStyle, Scanner, Span, Token, TokenType};
147
148// Keep every Rust example in the package README covered by `cargo test --doc` without duplicating
149// the README in the rendered crate-level documentation.
150#[cfg(doctest)]
151#[doc = include_str!("../README.md")]
152mod readme_doctests {}
153
154// Verify the feature-disabled public API without adding these checks to rendered documentation.
155#[cfg(all(doctest, not(feature = "comments")))]
156/// ```compile_fail
157/// use granit_parser::Comment;
158/// ```
159/// ```compile_fail
160/// use granit_parser::Placement;
161/// ```
162/// ```compile_fail
163/// let _ = granit_parser::Event::Comment;
164/// ```
165/// ```compile_fail
166/// let _ = granit_parser::TokenType::Comment;
167/// ```
168/// ```compile_fail
169/// let _ = granit_parser::Options::default().max_buffered_comment_events;
170/// ```
171/// ```compile_fail
172/// let _ = granit_parser::ErrorKind::TooManyComments;
173/// ```
174/// ```compile_fail
175/// use granit_parser::{Input, StrInput};
176/// let _ = <StrInput<'_> as Input>::may_contain_comments(&StrInput::new(""));
177/// ```
178mod comments_disabled_doctests {}