feat(parser): Impl parser for basic functionality

This commit is contained in:
2026-05-09 11:20:26 +08:00
parent 3cb698cc5d
commit 567057fd76
6 changed files with 815 additions and 33 deletions
+46 -9
View File
@@ -1,8 +1,5 @@
#[derive(Debug, Clone, Copy)]
pub struct Span {
start: usize,
end: usize,
}
use crate::{diagnostic::span::Span, frontend::types::{TokenValue, TypeIdent}};
pub struct CompileUnit {
pub global_decls: Vec<GlobalDeclStmt>,
}
@@ -12,9 +9,14 @@ pub enum GlobalDeclStmt {
}
pub struct VarDeclStmt {
pub values: Vec<VarDeclStmtValue>,
pub span: Span,
}
pub struct VarDeclStmtValue {
pub name: String,
pub var_type: Type,
pub span: Span,
}
pub struct FuncDeclStmt {
@@ -35,6 +37,16 @@ pub enum Statement {
Expr(Expr),
VarDecl(VarDeclStmt),
}
impl Statement {
pub fn span(&self) -> Span {
match self {
Statement::Return(s) => s.span,
Statement::Block(s) => s.span,
Statement::Expr(s) => s.span,
Statement::VarDecl(s) => s.span,
}
}
}
pub struct ReturnStmt {
pub value: Option<Expr>,
pub span: Span,
@@ -63,13 +75,38 @@ pub enum BinaryOp {
Equal, NotEqual, Less, LessEqual, Greater, GreaterEqual,
}
impl BinaryOp {
pub fn from_token_value(token_value: &TokenValue) -> Option<Self> {
match token_value {
TokenValue::Plus => Some(BinaryOp::Add),
TokenValue::Minus => Some(BinaryOp::Sub),
TokenValue::Star => Some(BinaryOp::Mul),
TokenValue::Slash => Some(BinaryOp::Div),
TokenValue::Percent => Some(BinaryOp::Mod),
TokenValue::DoubleEqual => Some(BinaryOp::Equal),
TokenValue::NotEqual => Some(BinaryOp::NotEqual),
TokenValue::Less => Some(BinaryOp::Less),
TokenValue::LessEqual => Some(BinaryOp::LessEqual),
TokenValue::Greater => Some(BinaryOp::Greater),
TokenValue::GreaterEqual => Some(BinaryOp::GreaterEqual),
_ => None,
}
}
}
pub enum Type {
Int,
Void,
}
impl From<TypeIdent> for Type {
fn from(value: TypeIdent) -> Self {
match value {
TypeIdent::Int => Type::Int,
TypeIdent::Void => Type::Void,
}
}
}
pub struct Param {
name: String,
param_type: Type,
span: Span,
pub name: String,
pub param_type: Type,
pub span: Span,
}