Add addition binop

This commit is contained in:
Sofia 2026-04-09 17:52:11 +03:00
parent 43abaa4a46
commit 8e2bc3a7f7
5 changed files with 24 additions and 10 deletions

View File

@ -4,13 +4,22 @@
namespace AST {
int operator_precedence(BinOp& op) {
return 0;
switch (op) {
case BinOp::Assignment:
return 1000;
case BinOp::Add:
return 10;
default:
return 1000;
}
}
std::string format_operator(BinOp& op) {
switch (op) {
case BinOp::Assignment:
return "=";
case BinOp::Add:
return "+";
default:
return "??";
}

View File

@ -10,6 +10,7 @@
namespace AST {
enum class BinOp {
Assignment,
Add,
};
int operator_precedence(BinOp& op);

View File

@ -38,17 +38,17 @@ namespace AST {
codegen::StackValue BinaryOperationExpression::codegen(codegen::Builder& builder, codegen::Scope& scope) {
auto lvalued = scope.with_lvalue();
auto lhs = this->m_lhs->codegen(builder, lvalued);
auto lhs = this->m_lhs->codegen(builder, this->m_binop == BinOp::Assignment ? lvalued : scope);
auto rhs = this->m_rhs->codegen(builder, scope);
switch (this->m_binop) {
case BinOp::Assignment:
builder.builder->CreateStore(rhs.value, lhs.value, false);
if (scope.is_lvalue) {
return lhs;
}
else {
return rhs;
}
return rhs;
case BinOp::Add:
return codegen::StackValue{
builder.builder->CreateAdd(lhs.value, rhs.value, "add"),
lhs.ty
};
default:
throw std::runtime_error("invalid binop");
}

View File

@ -54,6 +54,10 @@ namespace parsing {
stream.m_position = inner.m_position;
return new AST::BinOp{ AST::BinOp::Assignment };
}
if (token.content == "+") {
stream.m_position = inner.m_position;
return new AST::BinOp{ AST::BinOp::Add };
}
throw std::runtime_error("Expected binop");
}

4
test.c
View File

@ -1,5 +1,5 @@
int main() {
int a = 5;
a = 15;
return a;
a = 15 + 20;
return a + 30;
}