Parser

Struct Parser 

Source
pub struct Parser {
    pub tokens: Vec<Token>,
    pub current: usize,
    pub context_stack: Vec<ParseContext>,
}
Expand description

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.

Fields§

§tokens: Vec<Token>

A list of tokens to be parsed.

§current: usize

The current index of the token being processed.

§context_stack: Vec<ParseContext>

The current context stack for parsing.

Implementations§

Source§

impl Parser

Source

pub fn parse_expr(&mut self) -> Result<Expr, Error>

Parses any expression, starting with an assignment.

This method serves as the entry point for expression parsing.

§Returns
  • Ok(Expr): The parsed expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn expression_stmt(&mut self) -> Result<Stmt, Error>

Parses an expression statement.

This method parses an expression and checks for a semicolon to terminate the statement.

§Returns
  • Ok(Stmt): The expression statement if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_binary_expression(&mut self) -> Result<Expr, Error>

Parses a binary expression.

This method first parses a unary expression and then handles the binary operators in the expression.

§Returns
  • Ok(Expr): The parsed binary expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_binary_expression_recurse( &mut self, left: Expr, precedence: u8, ) -> Result<Expr, Error>

Parses binary expressions recursively, handling operator precedence and associativity.

This method continues to parse binary expressions until no further valid operators are found.

§Parameters
  • left: The left-hand side expression.
  • precedence: The precedence of the operator being processed.
§Returns
  • Ok(Expr): The final parsed expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_unary_operator(&mut self) -> Option<UnOperator>

Attempts to parse a unary operator.

This method checks the next token to see if it’s a unary operator and returns it if found.

§Returns
  • Some(UnOperator): The parsed unary operator if found.
  • None: If no unary operator is found.
Source

pub fn parse_unary_expression(&mut self) -> Result<Expr, Error>

Parses a unary expression, handling unary operators.

This method checks for a unary operator and processes the operand accordingly.

§Returns
  • Ok(Expr): The parsed unary expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_access_expression(&mut self) -> Result<Expr, Error>

Parses an access expression.

Source

pub fn parse_struct_constructor( &mut self, identifier: Token, ) -> Result<Expr, Error>

Parses a struct constructor expression.

This method expects an identifier followed by a left brace and a list of field assignments.

§Parameters
  • identifier: The token representing the struct name.
§Returns
  • Ok(Expr): The parsed struct constructor expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_primary_expression(&mut self) -> Result<Expr, Error>

Parses a primary expression, such as literals, identifiers, or parenthesized expressions.

§Returns
  • Ok(Expr): The parsed primary expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_then_else_expr(&mut self, condition: Expr) -> Result<Expr, Error>

Parses a then-else expression.

This method expects an identifier followed by a then keyword and two expressions.

§Parameters
  • identifier: The token representing the identifier.
§Returns
  • Ok(Expr): The parsed then-else expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_call_expr(&mut self, callee: Token) -> Result<Expr, Error>

Parses a function call expression.

This method expects an identifier followed by parentheses containing arguments.

§Parameters
  • callee: The token representing the function name.
§Returns
  • Ok(Expr): The parsed call expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_optional_type_annotation( &mut self, ) -> Result<Option<TypeAnnotation>, Error>

Parses an optional type annotation.

This method checks for a colon followed by a type annotation and parses it if present.

§Returns
  • Ok(Some(TypeAnnotation)): The parsed type annotation if present.
  • Ok(None): If no type annotation is present.
Source

pub fn parse_vector(&mut self) -> Result<Expr, Error>

Parses a vector expression.

This method expects a left bracket followed by a list of expressions and a closing right bracket.

§Returns
  • Ok(Expr): The parsed vector expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source

pub fn parse_assignment(&mut self) -> Result<Expr, Error>

Parses an assignment expression.

This method checks for an identifier followed by an equals sign and an expression.

§Returns
  • Ok(Expr): The parsed assignment expression if successful.
  • Err(anyhow::Error): An error if parsing fails.
Source§

impl Parser

Source

pub fn parse_stmt(&mut self) -> Result<Option<Stmt>, Error>

Parses a statement from the tokens.

This method checks the type of token to determine the kind of statement it should create. It supports function declarations, variable assignments, control flow, and more.

§Returns
  • Ok(Some(Stmt)): A parsed statement.
  • Ok(None): If the token is a comment or semicolon.
  • Err: If there is a parsing error.
Source

pub fn parse_impl( &mut self, impl_keyword: Token, ident: Token, ) -> Result<Stmt, Error>

Parses an impl block for implementing a struct.

An impl block is used to implement methods for a struct.

§Returns
  • Ok(Stmt): An impl block.
  • Err: If there is a parsing error.
Source

pub fn parse_trait_impl( &mut self, impl_keyword: Token, ident: Token, ) -> Result<Stmt, Error>

Parses an impl block for implementing a trait.

An impl block is used to implement methods for a trait.

§Returns
  • Ok(Stmt): An impl block.
  • Err: If there is a parsing error.
Source

pub fn parse_pub(&mut self, expected: TokenKind) -> Result<(Token, bool), Error>

Parses a ‘pub’ keyword (if present) followed by an identifier.

Source

pub fn parse_trait(&mut self) -> Result<Stmt, Error>

Parses a trait declaration.

A trait declaration defines a new interface that can be implemented by other types.

§Returns
  • Ok(Stmt): A trait declaration.
  • Err: If there is a parsing error.
Source

pub fn parse_const(&mut self) -> Result<Stmt, Error>

Parses an expression statement.

An expression statement is a statement that consists of an expression followed by a semicolon.

§Returns
  • Stmt: An expression statement.
  • Err: If there is a parsing error.
Source

pub fn parse_struct(&mut self) -> Result<Stmt, Error>

Parses a struct declaration.

A struct declaration defines a new data structure with named fields.

§Returns
  • Ok(Stmt): A struct declaration.
  • Err: If there is a parsing error.
Source

pub fn parse_while(&mut self) -> Result<Option<Stmt>, Error>

Parses a while statement.

A while statement is used to execute a block of code repeatedly as long as a condition is true.

§Returns
  • Ok(Stmt): A while statement.
  • Err: If there is a parsing error.
Source

pub fn parse_throw(&mut self) -> Result<Stmt, Error>

Parses a throw statement.

A throw statement is used to raise an exception.

§Returns
  • Ok(Stmt): A throw statement.
  • Err: If there is a parsing error.
Source

pub fn parse_try(&mut self) -> Result<Stmt, Error>

Parses a try statement with a catch block.

The try statement lets you catch exceptions and handle errors in a safe way.

§Returns
  • Ok(Stmt): A try-catch statement.
  • Err: If there is a parsing error.
Source

pub fn parse_return(&mut self) -> Result<Option<Stmt>, Error>

Parses a return statement.

The return statement is used to return a value from a function.

§Returns
  • Ok(Some(Stmt)): A return statement with or without a value.
  • Err: If there is a parsing error.
Source

pub fn parse_let(&mut self) -> Result<Stmt, Error>

Parses a let statement.

A let statement declares a new variable with an optional type annotation.

§Returns
  • Ok(Stmt): A variable declaration statement.
  • Err: If there is a parsing error.
Source

pub fn parse_if(&mut self) -> Result<Stmt, Error>

Parses an if statement with optional else if and else blocks.

An if statement is used for conditional logic.

§Returns
  • Ok(Stmt): An if statement with possible elseif and else blocks.
  • Err: If there is a parsing error.
Source

pub fn parse_use(&mut self) -> Result<Stmt, Error>

Parses a use statement for importing modules.

A use statement allows importing items from other modules or files.

§Returns
  • Ok(Stmt): A use statement.
  • Err: If there is a parsing error.
Source

pub fn is_nullable(&mut self) -> bool

Checks if the next token is a question mark and consumes it.

Source

pub fn parse_type_annotation(&mut self) -> Result<TypeAnnotation, Error>

Parses a type annotation following a variable or parameter.

§Returns
  • Ok(TypeAnnotation): A parsed type annotation.
  • Err: If there is a parsing error.
Source

pub fn parse_return_type(&mut self) -> Result<Option<FunctionType>, Error>

Parses the return type of function.

§Returns
  • Ok(Some(FunctionType)): If the return type is parsed.
  • Ok(None): If no return type is provided.
  • Err: If the syntax is incorrect.
Source

pub fn validate_type_name(token: Token) -> Result<(), Error>

Validates if the provided string is valid type name.

§Returns
  • Ok(()): If the type name is valid.
  • Err: If the type name is invalid.
Source

pub fn parse_block(&mut self) -> Result<Block, Error>

Parses a block of statements enclosed by curly braces {}.

A block is a group of statements that are executed in sequence.

§Returns
  • Ok(Block): A parsed block of statements.
  • Err: If there is a parsing error.
Source

pub fn parse_fn(&mut self) -> Result<Stmt, Error>

Parses a function declaration.

A function declaration defines a new function, including its parameters, return type, and body.

§Returns
  • Ok(Stmt): A function declaration.
  • Err: If there is a parsing error.
Source§

impl Parser

Source

pub fn new(tokens: Vec<Token>) -> 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.
Source

pub fn current_context(&self) -> &ParseContext

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.

Source

pub fn push_context(&mut self, context: ParseContext)

Pushes a new context onto the context stack.

§Parameters
  • context: The ParseContext to be pushed onto the stack.
Source

pub fn pop_context(&mut self)

Pops the current context off the context stack.

Source

pub fn is_context(&self, context: &ParseContext) -> bool

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.

Source§

impl Parser

Source

pub fn parse(&mut self) -> Result<Ast, Error>

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.
Source

pub fn consume(&mut self) -> Token

Consumes the current token and advances to the next token in the stream.

§Returns
  • The previous token that was consumed.
Source

pub fn previous(&self) -> Token

Retrieves the previous token.

§Panics

This function will panic if there are no previous tokens.

Source

pub fn peek(&self) -> Token

Peeks at the current token without consuming it.

§Returns
  • A copy of the current token.
Source

pub fn peek_next(&self) -> Token

Peeks at the next token without consuming the current one.

§Returns
  • A copy of the next token.
Source

pub fn is_eof(&self) -> bool

Checks if the current token is the end of file (EOF).

§Returns
  • true if the current token is EOF, otherwise false.
Source

pub fn possible_check(&mut self, kind: TokenKind)

Consumes the current token if it matches the specified TokenKind.

§Arguments
  • kind - The kind of token to check.
Source

pub fn expect(&mut self, kind: TokenKind) -> Result<Token, Error>

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.

Trait Implementations§

Source§

impl Debug for Parser

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Parser

§

impl RefUnwindSafe for Parser

§

impl Send for Parser

§

impl Sync for Parser

§

impl Unpin for Parser

§

impl UnwindSafe for Parser

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more