Files
bucky/src/ast.rs
Jooris Hadeler 93f08d1944 feat: Add parsing for expressions.
This commit adds support for parsing expression using the pratt parsing
approach.
2026-03-12 12:14:00 +01:00

126 lines
2.2 KiB
Rust

use std::fmt::Debug;
use crate::token::Span;
/// The [Phase] trait is used for type state. The AST can be in one of multiple
/// type states:
/// 1. [Parsed] - AST that was produced through parsing.
pub trait Phase {
type ExtraData: PartialEq + Debug;
}
/// See [Phase] for more information.
#[derive(Debug)]
pub struct Parsed;
impl Phase for Parsed {
type ExtraData = ();
}
pub type ParsedExpression = Expression<Parsed>;
/// This represents an expression in the source code. It holds the
/// [ExpressionKind], the [Span] and extra information according to the [Phase].
#[derive(Debug, PartialEq)]
pub struct Expression<P: Phase> {
pub kind: ExpressionKind<P>,
pub span: Span,
pub extra: P::ExtraData,
}
/// Represents the different kinds of [Expression]s, e.g. literals, unary or
/// binary expressions.
#[derive(Debug, PartialEq)]
pub enum ExpressionKind<P: Phase> {
Identifier(String),
LitString(String),
LitInteger(u64),
LitBool(bool),
Unary {
op: UnaryOp,
op_span: Span,
operand: Box<Expression<P>>,
},
Binary {
op: BinaryOp,
op_span: Span,
left: Box<Expression<P>>,
right: Box<Expression<P>>,
},
Call {
func: Box<Expression<P>>,
args: Vec<Expression<P>>,
},
Index {
expr: Box<Expression<P>>,
index: Box<Expression<P>>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
/// Bitwise Not
BitNot,
/// Logical Not
Not,
/// Negate
Neg,
/// Address Of
AddrOf,
/// Deref
Deref,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
/// Addition
Add,
/// Subtraction
Sub,
/// Multiplication
Mul,
/// Division
Div,
/// Remainder
Rem,
/// Bitwise And
BitAnd,
/// Bitwise Or
BitOr,
/// Bitwise Xor
BitXor,
/// Bitwise Shift Left
BitShl,
/// Bitwise Shift Right
BitShr,
/// Logical And
And,
/// Logical Or
Or,
/// Equal
Eq,
/// Not Equal
Ne,
/// Less than
Lt,
/// Less than or Equal
Le,
/// Greater than
Gt,
/// Greater than or Equal
Ge,
/// Assign
Assign,
/// Member Access
Dot,
}