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), Identifier(String),
} }
#[derive(Debug, Clone, Serialize)]
pub enum BinaryOp {
Plus,
Minus,
Multiply,
Divide,
}
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", content = "value")] #[serde(tag = "type", content = "value")]
pub enum TopLevel { pub enum TopLevel {
@@ -34,7 +42,9 @@ pub enum TopLevel {
#[serde(tag = "type", content = "value")] #[serde(tag = "type", content = "value")]
pub enum Postfix { pub enum Postfix {
FieldAccess(String), FieldAccess(String),
FunctionCall(Vec<Expression>), Call(Vec<Expression>),
Index(Expression),
Binary(BinaryOp, Expression),
} }
#[derive(Debug, Clone, Serialize)] #[derive(Debug, Clone, Serialize)]
+10 -5
View File
@@ -95,13 +95,18 @@ primary = {
} }
postfix = { postfix = {
("." ~ identifier) field_px
| ("(" ~ (expr ~ ("," ~ expr)*)? ~ ")") | call_px
| ("[" ~ expr ~ "]") | index_px
| ("++" | "--") | binary_px
| (("+" | "-" | "*" | "/" | "%") ~ primary)
} }
field_px = { "." ~ identifier }
call_px = { "(" ~ (expr ~ ("," ~ expr)*)? ~ ")" }
index_px = { "[" ~ expr ~ "]" }
binary_px = { bin_op ~ expr }
bin_op = { "+" | "-" | "*" | "/" | "%" }
expr = { expr = {
primary ~ postfix* primary ~ postfix*
} }
+27 -11
View File
@@ -320,18 +320,34 @@ impl Expression {
impl Postfix { impl Postfix {
pub fn from_pair(pair: pest::iterators::Pair<Rule>) -> Self { pub fn from_pair(pair: pest::iterators::Pair<Rule>) -> Self {
match pair.as_rule() { match pair.as_rule() {
Rule::postfix => { Rule::postfix => Postfix::from_pair(pair.into_inner().next().unwrap()),
let inner = pair.into_inner();
if let Some(field) = inner.peek() { Rule::field_px => {
if field.as_rule() == Rule::identifier { let field_name = pair.into_inner().next().unwrap().as_str().to_string();
Postfix::FieldAccess(field.as_str().to_string()) Postfix::FieldAccess(field_name)
} else {
Postfix::FunctionCall(inner.map(|p| Expression::from_pair(p)).collect())
}
} 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()), _ => unimplemented!("Postfix parsing not implemented yet {:?}", pair.as_rule()),
} }
} }