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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
pub mod expression;
pub mod function;
pub mod program;
pub mod statement;

use crate::lexer::tokens::Token;
use std::iter::Peekable;
use std::vec::IntoIter;

type TokenIter = Peekable<IntoIter<Token>>;

/// A parser that generates an abstract syntax tree, modeled by a yot [`Program`].
///
/// [`Program`]: program/struct.Program.html
pub struct Parser {
    /// The [`Token`]s generated by the [`Lexer`].
    ///
    /// [`Token`]: ../lexer/tokens/enum.Token.html
    /// [`Lexer`]: ../lexer/struct.Lexer.html
    tokens: TokenIter,
}

impl Parser {
    /// Creates a parser from an iterator of [`Token`]s.
    ///
    /// [`Token`]: ../lexer/tokens/enum.Token.html
    pub fn new(tokens: TokenIter) -> Self {
        Parser { tokens }
    }

    /// Peeks at the next token and check if it's a particular symbol.
    ///
    /// If the next token is a symbol and matches the argument, the token will be consumed.
    ///
    /// # Arguments
    /// * `symbol` - The particular symbol that will be checked against.
    fn next_symbol_is(&mut self, symbol: &str) -> bool {
        match self.tokens.peek() {
            Some(Token::Symbol(s)) if s == symbol => {
                self.tokens.next(); // Eat symbol
                true
            }
            _ => false,
        }
    }
}

/// Peeks at the next token and returns the name of the identifier if it is one.
///
/// If the next token is not an identifier, it will return Err.
#[macro_export]
macro_rules! peek_identifier_or_err {
    ($self:ident) => {
        match $self.tokens.peek() {
            Some(Token::Identifier(name)) => String::from(name),
            _ => return Err("Expected an identifier"),
        };
    };
}

/// Peeks at the next token and returns the value of the literal if it is one.
///
/// If the next token is not an literal, it will return Err.
#[macro_export]
macro_rules! peek_literal_or_err {
    ($self:ident) => {
        match $self.tokens.peek() {
            Some(Token::Literal(value)) => value.clone(),
            _ => return Err("Expected a literal"),
        };
    };
}

/// Peeks at the next token and returns the symbol if it is one.
///
/// If the next token is not an symbol, it will return Err.
#[macro_export]
macro_rules! peek_symbol_or_err {
    ($self:ident) => {
        match $self.tokens.peek() {
            Some(Token::Symbol(s)) => String::from(s),
            _ => return Err("Expected a symbol"),
        };
    };
}