wright/parser/
identifier.rs1use super::{
4 Parser,
5 error::{ParserError, ParserErrorKind},
6};
7use crate::{ast::identifier::Identifier, lexer::token::TokenTy};
8
9impl Identifier {
10 pub fn parse(parser: &mut Parser) -> Result<Self, ParserError> {
12 parser
13 .next_if_is(TokenTy::Identifier)
14 .map(|token| Identifier {
15 fragment: token.fragment,
16 })
17 .ok_or_else(|| {
18 ParserErrorKind::ExpectedIdentifier.at(parser.peek_fragment_or_rest_cloned())
19 })
20 }
21}
22
23#[cfg(test)]
24mod tests {
25 use crate::{
26 ast::identifier::Identifier,
27 lexer::Lexer,
28 parser::{Parser, error::ParserErrorKind},
29 };
30
31 #[test]
32 fn test_parse_ident() {
33 let mut parser = Parser::new(Lexer::new_test("source"));
34 let ident = Identifier::parse(&mut parser).unwrap();
35 assert_eq!(ident.fragment.as_str(), "source");
36 assert_eq!(parser.lexer().remaining.len(), 0);
37 }
38
39 #[test]
40 fn test_parse_ident_fail() {
41 for fail in ["12", "+", " ", " test", "_", "record"] {
42 let mut parser = Parser::new(Lexer::new_test(&fail));
43 let error = Identifier::parse(&mut parser).unwrap_err();
44 assert_eq!(error.kind, ParserErrorKind::ExpectedIdentifier);
45 }
46 }
47}