wright/parser/ty/
primitive.rs

1//! Parsing for primitive type signatures.
2
3use crate::{
4    ast::ty::{AtomicTy, AtomicTyVariant},
5    lexer::token::TokenTy,
6    parser::{
7        Parser,
8        error::{ParserError, ParserErrorKind},
9    },
10};
11
12impl AtomicTy {
13    /// Parse an atomic primitive type from souce or error with [ParserErrorKind::ExpectedAtomicTypeSignature]
14    /// and no progress made on the given [Parser].
15    #[rustfmt::skip]
16    pub fn parse(parser: &mut Parser) -> Result<Self, ParserError> {
17
18        // Local function reused by the match block below to shorten unwrapping a fragment and initializing the new 
19        // value once a match has been found.
20        fn accept(variant: AtomicTyVariant, parser: &mut Parser) -> Result<AtomicTy, ParserError> {
21            Ok(AtomicTy { variant, matching_source: parser.next_token().unwrap().unwrap().fragment })
22        }
23
24        match parser.peek_variant() {
25            Some(TokenTy::KwBool) => accept(AtomicTyVariant::Bool, parser),
26            Some(TokenTy::KwChar) => accept(AtomicTyVariant::Char, parser),
27            Some(TokenTy::KwU8  ) => accept(AtomicTyVariant::U8,   parser),
28            Some(TokenTy::KwI8  ) => accept(AtomicTyVariant::I8,   parser),
29            Some(TokenTy::KwU16 ) => accept(AtomicTyVariant::U16,  parser),
30            Some(TokenTy::KwI16 ) => accept(AtomicTyVariant::I16,  parser),
31            Some(TokenTy::KwU32 ) => accept(AtomicTyVariant::U32,  parser),
32            Some(TokenTy::KwI32 ) => accept(AtomicTyVariant::I32,  parser),
33            Some(TokenTy::KwF32 ) => accept(AtomicTyVariant::F32,  parser),
34            Some(TokenTy::KwU64 ) => accept(AtomicTyVariant::U64,  parser),
35            Some(TokenTy::KwI64 ) => accept(AtomicTyVariant::I64,  parser),
36            Some(TokenTy::KwF64 ) => accept(AtomicTyVariant::F64,  parser),
37            _ => Err(ParserErrorKind::ExpectedAtomicTypeSignature.at(parser.peek_fragment_or_rest_cloned())),
38        }
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use crate::{
45        ast::ty::{AtomicTy, AtomicTyVariant},
46        lexer::Lexer,
47        parser::Parser,
48    };
49
50    #[test]
51    fn test_bool() {
52        let mut parser = Parser::new(Lexer::new_test("bool"));
53        let atomic_ty = AtomicTy::parse(&mut parser).unwrap();
54        assert_eq!(atomic_ty.matching_source.as_str(), "bool");
55        assert_eq!(atomic_ty.variant, AtomicTyVariant::Bool);
56    }
57}