From 8e2bc3a7f7f8fc3b52c0eb78b72183a20daf3be9 Mon Sep 17 00:00:00 2001 From: Sofia Date: Thu, 9 Apr 2026 17:52:11 +0300 Subject: [PATCH] Add addition binop --- src/ast.cpp | 11 ++++++++++- src/ast.h | 1 + src/codegen.cpp | 14 +++++++------- src/parsing.cpp | 4 ++++ test.c | 4 ++-- 5 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/ast.cpp b/src/ast.cpp index e1978d6..3c2147e 100644 --- a/src/ast.cpp +++ b/src/ast.cpp @@ -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 "??"; } diff --git a/src/ast.h b/src/ast.h index 1d64766..6ff69cd 100644 --- a/src/ast.h +++ b/src/ast.h @@ -10,6 +10,7 @@ namespace AST { enum class BinOp { Assignment, + Add, }; int operator_precedence(BinOp& op); diff --git a/src/codegen.cpp b/src/codegen.cpp index 451ea25..ecc23b1 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -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"); } diff --git a/src/parsing.cpp b/src/parsing.cpp index f03903d..fdd9d08 100644 --- a/src/parsing.cpp +++ b/src/parsing.cpp @@ -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"); } diff --git a/test.c b/test.c index fec75fc..c2af6f2 100644 --- a/test.c +++ b/test.c @@ -1,5 +1,5 @@ int main() { int a = 5; - a = 15; - return a; + a = 15 + 20; + return a + 30; } \ No newline at end of file