Working binary operations

This commit is contained in:
2026-04-14 05:03:12 +02:00
parent 5a52582977
commit 7b8010abbb
3 changed files with 48 additions and 17 deletions
+11 -1
View File
@@ -12,6 +12,14 @@ pub enum TypeExpr {
Identifier(String),
}
#[derive(Debug, Clone, Serialize)]
pub enum BinaryOp {
Plus,
Minus,
Multiply,
Divide,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", content = "value")]
pub enum TopLevel {
@@ -34,7 +42,9 @@ pub enum TopLevel {
#[serde(tag = "type", content = "value")]
pub enum Postfix {
FieldAccess(String),
FunctionCall(Vec<Expression>),
Call(Vec<Expression>),
Index(Expression),
Binary(BinaryOp, Expression),
}
#[derive(Debug, Clone, Serialize)]
+10 -5
View File
@@ -95,13 +95,18 @@ primary = {
}
postfix = {
("." ~ identifier)
| ("(" ~ (expr ~ ("," ~ expr)*)? ~ ")")
| ("[" ~ expr ~ "]")
| ("++" | "--")
| (("+" | "-" | "*" | "/" | "%") ~ primary)
field_px
| call_px
| index_px
| binary_px
}
field_px = { "." ~ identifier }
call_px = { "(" ~ (expr ~ ("," ~ expr)*)? ~ ")" }
index_px = { "[" ~ expr ~ "]" }
binary_px = { bin_op ~ expr }
bin_op = { "+" | "-" | "*" | "/" | "%" }
expr = {
primary ~ postfix*
}
+25 -9
View File
@@ -320,18 +320,34 @@ impl Expression {
impl Postfix {
pub fn from_pair(pair: pest::iterators::Pair<Rule>) -> Self {
match pair.as_rule() {
Rule::postfix => {
let inner = pair.into_inner();
if let Some(field) = inner.peek() {
if field.as_rule() == Rule::identifier {
Postfix::FieldAccess(field.as_str().to_string())
} else {
Postfix::FunctionCall(inner.map(|p| Expression::from_pair(p)).collect())
Rule::postfix => Postfix::from_pair(pair.into_inner().next().unwrap()),
Rule::field_px => {
let field_name = pair.into_inner().next().unwrap().as_str().to_string();
Postfix::FieldAccess(field_name)
}
} else {
Postfix::FunctionCall(vec![])
Rule::call_px => Postfix::Call(pair.into_inner().map(Expression::from_pair).collect()),
Rule::index_px => {
Postfix::Index(Expression::from_pair(pair.into_inner().next().unwrap()))
}
Rule::binary_px => {
let mut inner = pair.into_inner();
let op_pair = inner.next().unwrap();
let op = match op_pair.as_str() {
"+" => BinaryOp::Plus,
"-" => BinaryOp::Minus,
"*" => BinaryOp::Multiply,
"/" => BinaryOp::Divide,
_ => {
unimplemented!("Binary operator not implemented yet: {}", op_pair.as_str())
}
};
Postfix::Binary(op, Expression::from_pair(inner.next().unwrap()))
}
_ => unimplemented!("Postfix parsing not implemented yet {:?}", pair.as_rule()),
}
}