granit_parser/input.rs
1//! Utilities to create a source of input to the parser.
2//!
3//! [`Input`] must be implemented for the parser to fetch input. Make sure your needs aren't
4//! covered by the [`BufferedInput`].
5
6use alloc::string::String;
7
8pub(crate) mod buffered;
9pub(crate) mod str;
10
11#[allow(clippy::module_name_repetitions)]
12pub use buffered::BufferedInput;
13
14/// A trait for inputs that can provide borrowed slices with a specific lifetime.
15///
16/// This trait enables zero-copy (`Cow::Borrowed`) token values for inputs that keep a stable
17/// backing string. The key difference from [`Input::slice_bytes`] is that this method returns
18/// a slice with the input's original lifetime `'a`, not tied to `&self`.
19///
20/// For inputs that support zero-copy (like [`str::StrInput`]), this returns `Some(&'a str)`.
21/// For streaming inputs that don't have stable backing storage, this returns `None`.
22pub trait BorrowedInput<'a>: Input {
23 /// Return a borrowed slice of the underlying source between two byte offsets.
24 ///
25 /// Unlike [`Input::slice_bytes`], this returns a slice with the input's lifetime `'a`,
26 /// allowing the slice to outlive the borrow of `&self`.
27 ///
28 /// `start` and `end` are byte offsets as returned by [`Input::byte_offset`]. The interval is
29 /// half-open: `[start, end)`.
30 ///
31 /// Returns `None` if the input does not support zero-copy slicing.
32 #[must_use]
33 fn slice_borrowed(&self, start: usize, end: usize) -> Option<&'a str>;
34}
35
36pub use crate::char_traits::{
37 is_alpha, is_blank, is_blank_or_breakz, is_break, is_breakz, is_digit, is_flow, is_z,
38};
39
40/// Interface for a source of characters.
41///
42/// Hiding the input's implementation behind this trait allows input-specific optimizations, such
43/// as using `str` methods instead of manually transferring one `char` at a time to a buffer.
44/// Implementations with stable backing storage can also return borrowed `&str` slices and avoid
45/// allocating token values.
46pub trait Input {
47 /// A hint to the input source that we will need to read `count` characters.
48 ///
49 /// If the input is exhausted, `\0` can be used to pad the last characters and later returned.
50 /// The characters must not be consumed, but may be placed in an internal buffer.
51 ///
52 /// This method may be a no-op if buffering yields no performance improvement.
53 ///
54 /// Implementers of [`Input`] must _not_ load more than `count` characters into the buffer. The
55 /// parser tracks how many characters are loaded in the buffer and acts accordingly.
56 fn lookahead(&mut self, count: usize);
57
58 /// Return the number of buffered characters in `self`.
59 #[must_use]
60 fn buflen(&self) -> usize;
61
62 /// Return the maximum number of characters this input can buffer for lookahead.
63 #[must_use]
64 fn bufmaxlen(&self) -> usize;
65
66 /// Return whether the lookahead buffer is empty.
67 #[inline]
68 #[must_use]
69 fn buf_is_empty(&self) -> bool {
70 self.buflen() == 0
71 }
72
73 /// Read a character from the input stream and return it directly.
74 ///
75 /// The internal buffer (if any) is bypassed.
76 #[must_use]
77 fn raw_read_ch(&mut self) -> char;
78
79 /// Read a non-breakz character from the input stream and return it directly.
80 ///
81 /// The internal buffer (if any) is bypassed.
82 ///
83 /// If the next character is a breakz, it is either not consumed or placed into the buffer (if
84 /// any).
85 #[must_use]
86 fn raw_read_non_breakz_ch(&mut self) -> Option<char>;
87
88 /// Consume the next character.
89 fn skip(&mut self);
90
91 /// Consume the next `count` characters.
92 fn skip_n(&mut self, count: usize);
93
94 /// Return the next character, without consuming it.
95 ///
96 /// Users of the [`Input`] must make sure that the character has been loaded through a prior
97 /// call to [`Input::lookahead`]. Implementors of [`Input`] may assume that a valid call to
98 /// [`Input::lookahead`] has been made beforehand.
99 ///
100 /// # Return
101 /// If the input source is not exhausted, returns the next character to be fed into the
102 /// scanner. Otherwise, returns `\0`.
103 #[must_use]
104 fn peek(&self) -> char;
105
106 /// Return the `n`-th character in the buffer, without consuming it.
107 ///
108 /// This function assumes that the `n`-th character in the input has already been fetched through
109 /// [`Input::lookahead`].
110 #[must_use]
111 fn peek_nth(&self, n: usize) -> char;
112
113 /// Return the current byte offset in the underlying source, if available.
114 ///
115 /// This is an *optional* capability that enables zero-copy (`Cow::Borrowed`) token values
116 /// for inputs that keep a stable backing string (notably [`str::StrInput`]).
117 ///
118 /// The returned value (when `Some`) is the number of bytes that have been consumed so far,
119 /// i.e. an offset into the original source string.
120 ///
121 /// # Correctness contract
122 /// Implementations returning `Some(_)` must satisfy all of the following:
123 ///
124 /// - The offset is a valid UTF-8 boundary in the underlying source.
125 /// - The offset is monotonically non-decreasing as characters are consumed.
126 /// - The underlying source is stable for the duration of parsing (no reallocation/mutation)
127 /// so that slices returned by [`Input::slice_bytes`] remain valid.
128 ///
129 /// Inputs that cannot provide stable slicing (e.g. stream/iterator inputs) must return
130 /// `None`.
131 #[inline]
132 #[must_use]
133 fn byte_offset(&self) -> Option<usize> {
134 None
135 }
136
137 /// Return a borrowed slice of the underlying source between two byte offsets.
138 ///
139 /// This is an *optional* capability used to produce `Cow::Borrowed` values without
140 /// allocating.
141 ///
142 /// `start` and `end` are byte offsets as returned by [`Input::byte_offset`]. The interval is
143 /// half-open: `[start, end)`.
144 ///
145 /// # Correctness contract
146 /// Implementations returning `Some(&str)` must ensure:
147 ///
148 /// - `start <= end`.
149 /// - Both offsets are valid UTF-8 boundaries.
150 /// - The returned `&str` is a view into the stable underlying source associated with this
151 /// input.
152 ///
153 /// Implementations that return `None` from [`Input::byte_offset`] must also return `None`
154 /// here.
155 #[inline]
156 #[must_use]
157 fn slice_bytes(&self, _start: usize, _end: usize) -> Option<&str> {
158 None
159 }
160
161 /// Look for the next character and return it.
162 ///
163 /// The character is not consumed.
164 /// Equivalent to calling [`Input::lookahead`] and [`Input::peek`].
165 #[inline]
166 #[must_use]
167 fn look_ch(&mut self) -> char {
168 self.lookahead(1);
169 self.peek()
170 }
171
172 /// Return whether the next character in the input source is equal to `c`.
173 ///
174 /// This function assumes that the next character in the input has already been fetched through
175 /// [`Input::lookahead`].
176 #[inline]
177 #[must_use]
178 fn next_char_is(&self, c: char) -> bool {
179 self.peek() == c
180 }
181
182 /// Return whether the `n`-th character in the input source is equal to `c`.
183 ///
184 /// This function assumes that the `n`-th character in the input has already been fetched through
185 /// [`Input::lookahead`].
186 #[inline]
187 #[must_use]
188 fn nth_char_is(&self, n: usize, c: char) -> bool {
189 self.peek_nth(n) == c
190 }
191
192 /// Return whether the next 2 characters in the input source match the given characters.
193 ///
194 /// This function assumes that the next 2 characters in the input have already been fetched
195 /// through [`Input::lookahead`].
196 #[inline]
197 #[must_use]
198 fn next_2_are(&self, c1: char, c2: char) -> bool {
199 assert!(self.buflen() >= 2);
200 self.peek() == c1 && self.peek_nth(1) == c2
201 }
202
203 /// Return whether the next 3 characters in the input source match the given characters.
204 ///
205 /// This function assumes that the next 3 characters in the input have already been fetched
206 /// through [`Input::lookahead`].
207 #[inline]
208 #[must_use]
209 fn next_3_are(&self, c1: char, c2: char, c3: char) -> bool {
210 assert!(self.buflen() >= 3);
211 self.peek() == c1 && self.peek_nth(1) == c2 && self.peek_nth(2) == c3
212 }
213
214 /// Check whether the next characters correspond to a document indicator.
215 ///
216 /// This function assumes that the next 4 characters in the input have already been fetched
217 /// through [`Input::lookahead`].
218 #[inline]
219 #[must_use]
220 fn next_is_document_indicator(&self) -> bool {
221 assert!(self.buflen() >= 4);
222 is_blank_or_breakz(self.peek_nth(3))
223 && (self.next_3_are('.', '.', '.') || self.next_3_are('-', '-', '-'))
224 }
225
226 /// Check whether the next characters correspond to a start of document.
227 ///
228 /// This function assumes that the next 4 characters in the input have already been fetched
229 /// through [`Input::lookahead`].
230 #[inline]
231 #[must_use]
232 fn next_is_document_start(&self) -> bool {
233 assert!(self.buflen() >= 4);
234 self.next_3_are('-', '-', '-') && is_blank_or_breakz(self.peek_nth(3))
235 }
236
237 /// Check whether the next characters correspond to an end of document.
238 ///
239 /// This function assumes that the next 4 characters in the input have already been fetched
240 /// through [`Input::lookahead`].
241 #[inline]
242 #[must_use]
243 fn next_is_document_end(&self) -> bool {
244 assert!(self.buflen() >= 4);
245 self.next_3_are('.', '.', '.') && is_blank_or_breakz(self.peek_nth(3))
246 }
247
248 /// Skip YAML whitespace up to the end of the current line.
249 ///
250 /// Inline comments are consumed only after at least one preceding YAML whitespace character.
251 ///
252 /// # Return
253 /// Return a tuple with the number of characters that were consumed and the result of skipping
254 /// whitespace. The number of characters returned can be used to advance the index and column,
255 /// since no end-of-line character will be consumed.
256 /// See [`SkipTabs`] for more details on the success variant.
257 ///
258 /// # Errors
259 /// Errors if a comment is encountered but it was not preceded by a whitespace. In that event,
260 /// the first tuple element will contain the number of characters consumed prior to reaching
261 /// the `#`.
262 fn skip_ws_to_eol(&mut self, skip_tabs: SkipTabs) -> (usize, Result<SkipTabs, &'static str>) {
263 let mut encountered_tab = false;
264 let mut has_yaml_ws = false;
265 let mut chars_consumed = 0;
266 loop {
267 match self.look_ch() {
268 ' ' => {
269 has_yaml_ws = true;
270 self.skip();
271 }
272 '\t' if skip_tabs != SkipTabs::No => {
273 encountered_tab = true;
274 self.skip();
275 }
276 // YAML comments must be preceded by whitespace.
277 '#' if !encountered_tab && !has_yaml_ws => {
278 return (
279 chars_consumed,
280 Err("comments must be separated from other tokens by whitespace"),
281 );
282 }
283 '#' => {
284 self.skip(); // Skip over '#'
285 while !is_breakz(self.look_ch()) {
286 self.skip();
287 chars_consumed += 1;
288 }
289 }
290 _ => break,
291 }
292 chars_consumed += 1;
293 }
294
295 (
296 chars_consumed,
297 Ok(SkipTabs::Result(encountered_tab, has_yaml_ws)),
298 )
299 }
300
301 /// Check whether the next characters may be part of a plain scalar.
302 ///
303 /// This function assumes we are not given a blankz character.
304 #[allow(clippy::inline_always)]
305 #[inline(always)]
306 fn next_can_be_plain_scalar(&self, in_flow: bool) -> bool {
307 let nc = self.peek_nth(1);
308 match self.peek() {
309 // indicators can end a plain scalar, see 7.3.3. Plain Style
310 ':' if is_blank_or_breakz(nc) || (in_flow && is_flow(nc)) => false,
311 c if in_flow && is_flow(c) => false,
312 _ => true,
313 }
314 }
315
316 /// Check whether the next character is [a blank] or [a break].
317 ///
318 /// The character must have previously been fetched through [`lookahead`]
319 ///
320 /// # Return
321 /// Returns true if the character is [a blank] or [a break], false otherwise.
322 ///
323 /// [`lookahead`]: Input::lookahead
324 /// [a blank]: is_blank
325 /// [a break]: is_break
326 #[inline]
327 fn next_is_blank_or_break(&self) -> bool {
328 is_blank(self.peek()) || is_break(self.peek())
329 }
330
331 /// Check whether the next character is [a blank] or [a breakz].
332 ///
333 /// The character must have previously been fetched through [`lookahead`]
334 ///
335 /// # Return
336 /// Returns true if the character is [a blank] or [a break], false otherwise.
337 ///
338 /// [`lookahead`]: Input::lookahead
339 /// [a blank]: is_blank
340 /// [a breakz]: is_breakz
341 #[inline]
342 fn next_is_blank_or_breakz(&self) -> bool {
343 is_blank(self.peek()) || is_breakz(self.peek())
344 }
345
346 /// Check whether the next character is [a blank].
347 ///
348 /// The character must have previously been fetched through [`lookahead`]
349 ///
350 /// # Return
351 /// Returns true if the character is [a blank], false otherwise.
352 ///
353 /// [`lookahead`]: Input::lookahead
354 /// [a blank]: is_blank
355 #[inline]
356 fn next_is_blank(&self) -> bool {
357 is_blank(self.peek())
358 }
359
360 /// Check whether the next character is [a break].
361 ///
362 /// The character must have previously been fetched through [`lookahead`]
363 ///
364 /// # Return
365 /// Returns true if the character is [a break], false otherwise.
366 ///
367 /// [`lookahead`]: Input::lookahead
368 /// [a break]: is_break
369 #[inline]
370 fn next_is_break(&self) -> bool {
371 is_break(self.peek())
372 }
373
374 /// Check whether the next character is [a breakz].
375 ///
376 /// The character must have previously been fetched through [`lookahead`]
377 ///
378 /// # Return
379 /// Returns true if the character is [a breakz], false otherwise.
380 ///
381 /// [`lookahead`]: Input::lookahead
382 /// [a breakz]: is_breakz
383 #[inline]
384 fn next_is_breakz(&self) -> bool {
385 is_breakz(self.peek())
386 }
387
388 /// Check whether the next character is [a z].
389 ///
390 /// The character must have previously been fetched through [`lookahead`]
391 ///
392 /// # Return
393 /// Returns true if the character is [a z], false otherwise.
394 ///
395 /// [`lookahead`]: Input::lookahead
396 /// [a z]: is_z
397 #[inline]
398 fn next_is_z(&self) -> bool {
399 is_z(self.peek())
400 }
401
402 /// Check whether the next character is [a flow].
403 ///
404 /// The character must have previously been fetched through [`lookahead`]
405 ///
406 /// # Return
407 /// Returns true if the character is [a flow], false otherwise.
408 ///
409 /// [`lookahead`]: Input::lookahead
410 /// [a flow]: is_flow
411 #[inline]
412 fn next_is_flow(&self) -> bool {
413 is_flow(self.peek())
414 }
415
416 /// Check whether the next character is [a digit].
417 ///
418 /// The character must have previously been fetched through [`lookahead`]
419 ///
420 /// # Return
421 /// Returns true if the character is [a digit], false otherwise.
422 ///
423 /// [`lookahead`]: Input::lookahead
424 /// [a digit]: is_digit
425 #[inline]
426 fn next_is_digit(&self) -> bool {
427 is_digit(self.peek())
428 }
429
430 /// Check whether the next character is [a letter].
431 ///
432 /// The character must have previously been fetched through [`lookahead`]
433 ///
434 /// # Return
435 /// Returns true if the character is [a letter], false otherwise.
436 ///
437 /// [`lookahead`]: Input::lookahead
438 /// [a letter]: is_alpha
439 #[inline]
440 fn next_is_alpha(&self) -> bool {
441 is_alpha(self.peek())
442 }
443
444 /// Skip characters from the input until a [breakz] is found.
445 ///
446 /// The characters are consumed from the input.
447 ///
448 /// # Return
449 /// Return the number of characters that were consumed. The number of characters returned can
450 /// be used to advance the index and column, since no end-of-line character will be consumed.
451 ///
452 /// [breakz]: is_breakz
453 #[inline]
454 fn skip_while_non_breakz(&mut self) -> usize {
455 let mut count = 0;
456 while !is_breakz(self.look_ch()) {
457 count += 1;
458 self.skip();
459 }
460 count
461 }
462
463 /// Skip characters from the input while [blanks] are found.
464 ///
465 /// The characters are consumed from the input.
466 ///
467 /// # Return
468 /// Return the number of characters that were consumed. The number of characters returned can
469 /// be used to advance the index and column, since no end-of-line character will be consumed.
470 ///
471 /// [blanks]: is_blank
472 fn skip_while_blank(&mut self) -> usize {
473 let mut n_bytes = 0;
474 while is_blank(self.look_ch()) {
475 n_bytes += self.peek().len_utf8();
476 self.skip();
477 }
478 n_bytes
479 }
480
481 /// Fetch characters from the input while we encounter letters and store them in `out`.
482 ///
483 /// The characters are consumed from the input.
484 ///
485 /// # Return
486 /// Return the number of characters that were consumed. The number of characters returned can
487 /// be used to advance the index and column, since no end-of-line character will be consumed.
488 fn fetch_while_is_alpha(&mut self, out: &mut String) -> usize {
489 let mut n_bytes = 0;
490 while is_alpha(self.look_ch()) {
491 let c = self.peek();
492 n_bytes += c.len_utf8();
493 out.push(c);
494 self.skip();
495 }
496 n_bytes
497 }
498
499 /// Fetch characters as long as they satisfy `is_yaml_non_space(c)`.
500 ///
501 /// The characters are consumed from the input.
502 ///
503 /// # Return
504 /// Return the number of characters that were consumed. The number of characters returned can
505 /// be used to advance the index and column, since no end-of-line character will be consumed.
506 fn fetch_while_is_yaml_non_space(&mut self, out: &mut String) -> usize {
507 let mut chars_consumed = 0;
508 loop {
509 let c = self.look_ch();
510 if !crate::char_traits::is_yaml_non_space(c) || is_z(c) {
511 break;
512 }
513 let c = self.peek();
514 out.push(c);
515 self.skip();
516 chars_consumed += 1;
517 }
518 chars_consumed
519 }
520
521 /// Fetch a chunk of plain scalar characters.
522 ///
523 /// This optimization method allows the input to batch process characters.
524 /// Returns (stopped, `chars_consumed`).
525 /// stopped is true if the chunk ended because of a non-plain-scalar character.
526 fn fetch_plain_scalar_chunk(
527 &mut self,
528 out: &mut String,
529 count: usize,
530 flow_level_gt_0: bool,
531 ) -> (bool, usize) {
532 let mut chars_consumed = 0;
533 for _ in 0..count {
534 self.lookahead(1);
535 if self.next_is_blank_or_breakz() || !self.next_can_be_plain_scalar(flow_level_gt_0) {
536 return (true, chars_consumed);
537 }
538 out.push(self.peek());
539 self.skip();
540 chars_consumed += 1;
541 }
542 (false, chars_consumed)
543 }
544}
545
546/// Behavior to adopt regarding treating tabs as whitespace.
547///
548/// Although tab is valid YAML whitespace, it does not always behave the same as a space.
549#[derive(Copy, Clone, Eq, PartialEq)]
550pub enum SkipTabs {
551 /// Skip all tabs as whitespace.
552 Yes,
553 /// Don't skip any tab. Return from the function when encountering one.
554 No,
555 /// Return value from the function.
556 Result(
557 /// Whether tabs were encountered.
558 bool,
559 /// Whether at least one valid YAML whitespace character has been encountered.
560 bool,
561 ),
562}
563
564impl SkipTabs {
565 /// Whether tabs were found while skipping whitespace.
566 ///
567 /// This function must be called after a call to `skip_ws_to_eol`.
568 #[must_use]
569 pub fn found_tabs(self) -> bool {
570 matches!(self, SkipTabs::Result(true, _))
571 }
572
573 /// Whether a valid YAML whitespace has been found in skipped-over content.
574 ///
575 /// This function must be called after a call to `skip_ws_to_eol`.
576 #[must_use]
577 pub fn has_valid_yaml_ws(self) -> bool {
578 matches!(self, SkipTabs::Result(_, true))
579 }
580}
581
582#[cfg(test)]
583mod tests {
584 use super::{Input, SkipTabs};
585
586 struct MinimalInput;
587
588 impl Input for MinimalInput {
589 fn lookahead(&mut self, _count: usize) {}
590
591 fn buflen(&self) -> usize {
592 0
593 }
594
595 fn bufmaxlen(&self) -> usize {
596 0
597 }
598
599 fn raw_read_ch(&mut self) -> char {
600 '\0'
601 }
602
603 fn raw_read_non_breakz_ch(&mut self) -> Option<char> {
604 None
605 }
606
607 fn skip(&mut self) {}
608
609 fn skip_n(&mut self, _count: usize) {}
610
611 fn peek(&self) -> char {
612 '\0'
613 }
614
615 fn peek_nth(&self, _n: usize) -> char {
616 '\0'
617 }
618 }
619
620 #[test]
621 fn default_slice_bytes_returns_none() {
622 let mut input = MinimalInput;
623
624 input.lookahead(4);
625 assert_eq!(input.buflen(), 0);
626 assert_eq!(input.bufmaxlen(), 0);
627 assert_eq!(input.raw_read_ch(), '\0');
628 assert_eq!(input.raw_read_non_breakz_ch(), None);
629 input.skip();
630 input.skip_n(2);
631 assert_eq!(input.peek(), '\0');
632 assert_eq!(input.peek_nth(1), '\0');
633 assert_eq!(input.byte_offset(), None);
634 assert_eq!(input.slice_bytes(0, 0), None);
635 }
636
637 #[test]
638 fn default_skip_ws_to_eol_rejects_unseparated_comment() {
639 let mut input = super::buffered::BufferedInput::new("#comment\n".chars());
640
641 let (consumed, result) = input.skip_ws_to_eol(SkipTabs::Yes);
642
643 assert_eq!(consumed, 0);
644 assert_eq!(
645 result.err(),
646 Some("comments must be separated from other tokens by whitespace")
647 );
648 assert_eq!(input.peek(), '#');
649 }
650}