wright/parser/literal/
boolean.rs

1//! Boolean literal parsing logic.
2
3use crate::{
4    ast::literal::BooleanLiteral,
5    lexer::token::TokenTy,
6    parser::{
7        Parser,
8        error::{ParserError, ParserErrorKind},
9    },
10};
11
12impl BooleanLiteral {
13    /// Parse a boolean literal from the given [Parser].
14    pub fn parse(parser: &mut Parser) -> Result<Self, ParserError> {
15        if let Some(token) = parser.next_if_is(TokenTy::KwTrue) {
16            return Ok(BooleanLiteral {
17                fragment: token.fragment,
18                value: true,
19            });
20        }
21
22        if let Some(token) = parser.next_if_is(TokenTy::KwFalse) {
23            return Ok(BooleanLiteral {
24                fragment: token.fragment,
25                value: false,
26            });
27        }
28
29        Err(ParserErrorKind::ExpectedBooleanLiteral.at(parser.peek_fragment_or_rest_cloned()))
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use crate::{ast::literal::BooleanLiteral, lexer::Lexer, parser::Parser};
36
37    #[test]
38    fn works() {
39        for s in ["true", "false"] {
40            let mut p = Parser::new(Lexer::new_test(s));
41
42            assert!(BooleanLiteral::parse(&mut p).is_ok());
43        }
44    }
45}