diff --git a/src/ast/expressions/infix.cpp b/src/ast/expressions/infix.cpp new file mode 100644 index 0000000..5ce1c75 --- /dev/null +++ b/src/ast/expressions/infix.cpp @@ -0,0 +1,19 @@ +#include "infix.hpp" + +#include "token/token.hpp" + +namespace ast { + + std::string infix_expr::token_literal() const { + return token.literal; + } + + std::string infix_expr::str() const { + return left->str() + token.literal + right->str(); + } + + infix_expr::~infix_expr() { + delete left; + delete right; + }; +} // namespace ast diff --git a/src/ast/expressions/infix.hpp b/src/ast/expressions/infix.hpp new file mode 100644 index 0000000..5338c16 --- /dev/null +++ b/src/ast/expressions/infix.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "ast/ast.hpp" +#include "token/token.hpp" + +namespace ast { + struct infix_expr : expression { + token::token token; + expression* left; + std::string op; + expression* right; + + std::string token_literal() const override; + std::string str() const override; + ~infix_expr(); + }; +} // namespace ast diff --git a/test/parser/expression.cpp b/test/parser/expression.cpp index fe1d207..b513811 100644 --- a/test/parser/expression.cpp +++ b/test/parser/expression.cpp @@ -1,4 +1,5 @@ #include "ast/expressions/identifier.hpp" +#include "ast/expressions/infix.hpp" #include "ast/expressions/integer.hpp" #include "ast/expressions/prefix.hpp" #include "utils.hpp" @@ -69,5 +70,32 @@ TEST_SUITE("Parser: expression") { #undef CASE } + TEST_CASE_FIXTURE( + ParserFixture, + "Simple expression statement with infix between integers" + ) { +#define CASE(name, input, _left, _op, _right) \ + SUBCASE(name) { \ + setup(input); \ + REQUIRE(program->statements.size() == 1); \ + ast::expression_stmt* expression_stmt = \ + cast(program->statements[0]); \ + \ + ast::infix_expr* infix_expr = \ + cast(expression_stmt->expression); \ + \ + test_integer_literal(infix_expr->left, _left); \ + REQUIRE(infix_expr->op == _op); \ + test_integer_literal(infix_expr->right, _right); \ + } + CASE("Infix: '+'", "5 + 5;", 5, "+", 5); + CASE("Infix: '-'", "5- 5;", 5, "-", 5); + CASE("Infix: '*'", "15 *5;", 15, "*", 5); + CASE("Infix: '/'", "15 / 5;", 15, "/", 5); + CASE("Infix: '<'", "15 < 15;", 15, "<", 15); + CASE("Infix: '>'", "25 > 15;", 25, ">", 15); + CASE("Infix: '=='", "5 == 5;", 5, "==", 5); + CASE("Infix: '!='", "15 == 5;", 15, "!=", 5); +#undef CASE } }