roan_ast/parser/mod.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 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
mod expressions;
mod statements;
use crate::{
lexer::token::{Token, TokenKind},
Ast,
};
use anyhow::Result;
use roan_error::error::RoanError::ExpectedToken;
use tracing::debug;
#[derive(Debug, PartialEq, Eq)]
pub enum ParseContext {
Normal,
IfCondition,
WhileCondition,
}
/// A parser that converts a list of tokens into an Abstract Syntax Tree (AST).
///
/// This struct takes tokens generated by the lexer and produces an AST,
/// which represents the structure of the source code in a tree format.
#[derive(Debug)]
pub struct Parser {
/// A list of tokens to be parsed.
pub tokens: Vec<Token>,
/// The current index of the token being processed.
pub current: usize,
/// The current context stack for parsing.
pub context_stack: Vec<ParseContext>,
}
impl Parser {
/// Creates a new `Parser` instance with a set of tokens to parse.
///
/// # Arguments
/// * `tokens` - The list of tokens generated by the lexer.
///
/// # Returns
/// * A new `Parser` instance ready to parse the tokens.
pub fn new(tokens: Vec<Token>) -> Self {
Self {
tokens,
current: 0,
context_stack: vec![ParseContext::Normal],
}
}
/// Returns a reference to the current parser context.
///
/// # Panics
///
/// This function will panic if the `context_stack` is empty. However, this condition
/// should never happen because the context stack should always have at least one context.
pub fn current_context(&self) -> &ParseContext {
self.context_stack
.last()
.expect("Parser context stack should never be empty")
}
/// Pushes a new context onto the context stack.
///
/// # Parameters
///
/// - `context`: The `ParseContext` to be pushed onto the stack.
pub fn push_context(&mut self, context: ParseContext) {
debug!("Pushing context: {:?}", context);
self.context_stack.push(context);
}
/// Pops the current context off the context stack.
pub fn pop_context(&mut self) {
debug!("Popping context: {:?}", self.current_context());
self.context_stack.pop();
}
/// Checks if the current context matches a given context.
///
/// # Parameters
///
/// - `context`: A reference to a `ParseContext` to compare with the current context.
///
/// # Returns
///
/// `true` if the current context is equal to the given context, `false` otherwise.
pub fn is_context(&self, context: &ParseContext) -> bool {
debug!(
"Checking context: {:?} == {:?}",
self.current_context(),
context
);
self.current_context() == context
}
}
impl Parser {
/// Parses the list of tokens and constructs an AST.
///
/// This method will continue parsing tokens until the end of the token stream
/// (or an EOF token) is encountered. Each token sequence is turned into a statement
/// and added to the AST.
///
/// # Returns
/// * `Ok(Ast)` - If the parsing is successful and an AST is created.
/// * `Err` - If an error occurs during parsing.
pub fn parse(&mut self) -> Result<Ast> {
let mut ast = Ast::new();
// Parse tokens into statements until EOF is reached
while !self.is_eof() {
// Parse a statement, if successful, add it to the AST
let stmt = self.parse_stmt()?;
if let Some(stmt) = stmt {
ast.stmts.push(stmt);
}
}
Ok(ast)
}
/// Consumes the current token and advances to the next token in the stream.
///
/// # Returns
/// * The previous token that was consumed.
pub fn consume(&mut self) -> Token {
if !self.is_eof() {
self.current += 1;
}
self.previous()
}
/// Retrieves the previous token.
///
/// # Panics
/// This function will panic if there are no previous tokens.
pub fn previous(&self) -> Token {
assert!(self.current > 0);
self.tokens[self.current - 1].clone()
}
/// Peeks at the current token without consuming it.
///
/// # Returns
/// * A copy of the current token.
pub fn peek(&self) -> Token {
self.tokens[self.current].clone()
}
/// Peeks at the next token without consuming the current one.
///
/// # Returns
/// * A copy of the next token.
pub fn peek_next(&self) -> Token {
self.tokens[self.current + 1].clone()
}
/// Checks if the current token is the end of file (EOF).
///
/// # Returns
/// * `true` if the current token is EOF, otherwise `false`.
pub fn is_eof(&self) -> bool {
self.current >= self.tokens.len() || self.peek().kind == TokenKind::EOF
}
/// Consumes the current token if it matches the specified `TokenKind`.
///
/// # Arguments
/// * `kind` - The kind of token to check.
pub fn possible_check(&mut self, kind: TokenKind) {
if self.peek().kind == kind {
self.consume();
}
}
/// Expects the current token to be of a specific `TokenKind` and consumes it.
///
/// If the token matches the expected kind, it is consumed and returned.
/// If not, an error is raised indicating the expected token.
///
/// # Arguments
/// * `kind` - The expected kind of the current token.
///
/// # Returns
/// * `Ok(Token)` - The token that was consumed.
/// * `Err` - An error if the current token is not of the expected kind.
pub fn expect(&mut self, kind: TokenKind) -> Result<Token> {
let token = self.peek();
debug!("Expected token: {:?}, found: {:?}", kind, token.kind);
if token.kind == kind {
Ok(self.consume())
} else {
Err(ExpectedToken(
kind.to_string(),
format!("Expected token of kind: {}", kind),
token.span.clone(),
)
.into())
}
}
}