wright/parser/
whitespace.rs

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
//! Utilities for parsing through whitespace.

use super::{
    error::{ParserError, ParserErrorKind},
    Parser,
};
use crate::lexer::token::TokenTy;

/// Consume and ignore a [TokenTy::Whitespace] from the front of the [Parser].
/// If there is not one, do nothing.
pub fn optional_whitespace(parser: &mut Parser) {
    parser.next_if_is(TokenTy::Whitespace);
}

/// Require a whitespace from the [Parser]. Do not advance if the next [Token] is not a whitespace.
///
/// [Token]: crate::lexer::token::Token
pub fn require_whitespace(parser: &mut Parser) -> Result<(), ParserError> {
    if parser.next_if_is(TokenTy::Whitespace).is_none() {
        Err(ParserError {
            kind: ParserErrorKind::ExpectedWhitespace,
            location: parser
                .peek_fragment()
                .cloned()
                .unwrap_or(parser.lexer().remaining.clone()),
            help: None,
        })
    } else {
        Ok(())
    }
}