move Expr out of parser
This commit is contained in:
parent
99be8a16c7
commit
a3d9723a36
4 changed files with 49 additions and 47 deletions
|
|
@ -1,4 +1,4 @@
|
|||
use crate::parser::{BinaryOp, Expr, UnaryOp};
|
||||
use crate::expr::{BinaryOp, Expr, UnaryOp};
|
||||
|
||||
pub struct Evaluator {
|
||||
ast: Expr
|
||||
|
|
|
|||
45
src/expr.rs
Normal file
45
src/expr.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
#[derive(Debug, Clone)]
|
||||
pub enum BinaryOp {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Mod
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum UnaryOp {
|
||||
Neg
|
||||
}
|
||||
|
||||
pub fn prefix_bp(op: &UnaryOp) -> u8 {
|
||||
match op {
|
||||
UnaryOp::Neg => 5
|
||||
}
|
||||
}
|
||||
|
||||
pub fn infix_bp(op: &BinaryOp) -> (u8, u8) {
|
||||
match op {
|
||||
BinaryOp::Add | BinaryOp::Sub => (1, 2),
|
||||
BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => (3, 4)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Expr {
|
||||
Number(i64),
|
||||
Ident(String),
|
||||
EOL,
|
||||
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>
|
||||
},
|
||||
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
right: Box<Expr>
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
use std::{fs::File, io::Read};
|
||||
|
||||
mod token;
|
||||
mod expr;
|
||||
mod lexer;
|
||||
use lexer::Lexer;
|
||||
mod parser;
|
||||
|
|
@ -30,7 +31,7 @@ fn main() -> std::io::Result<()> {
|
|||
loop {
|
||||
let parsed = parser.parse();
|
||||
match parsed {
|
||||
parser::Expr::EOL => break,
|
||||
expr::Expr::EOL => break,
|
||||
_ => {
|
||||
println!("AST: {:?}", parsed);
|
||||
let eval = Evaluator::new(parsed);
|
||||
|
|
|
|||
|
|
@ -1,49 +1,5 @@
|
|||
use crate::token::Token;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum BinaryOp {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Mod
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum UnaryOp {
|
||||
Neg
|
||||
}
|
||||
|
||||
fn prefix_bp(op: &UnaryOp) -> u8 {
|
||||
match op {
|
||||
UnaryOp::Neg => 5
|
||||
}
|
||||
}
|
||||
|
||||
fn infix_bp(op: &BinaryOp) -> (u8, u8) {
|
||||
match op {
|
||||
BinaryOp::Add | BinaryOp::Sub => (1, 2),
|
||||
BinaryOp::Mul | BinaryOp::Div | BinaryOp::Mod => (3, 4)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Expr {
|
||||
Number(i64),
|
||||
Ident(String),
|
||||
EOL,
|
||||
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>
|
||||
},
|
||||
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
right: Box<Expr>
|
||||
}
|
||||
}
|
||||
use crate::expr::{Expr, UnaryOp, BinaryOp, infix_bp, prefix_bp};
|
||||
|
||||
pub struct Parser {
|
||||
tokens: Vec<Token>,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue