added tests for the stringification of the program

This commit is contained in:
Karma Riuk
2025-07-08 11:18:54 +02:00
parent 902f5a16df
commit 83df4955d4
7 changed files with 61 additions and 0 deletions

View File

@@ -8,6 +8,12 @@
namespace ast {
struct program : public node {
std::vector<statement*> statements;
program() {}
program(std::vector<statement*> statements)
: statements(std::move(statements)) {};
std::string token_literal() const override;
virtual std::string str() const override;

View File

@@ -22,6 +22,8 @@ namespace ast {
if (expression != nullptr)
ss << expression->str();
ss << ';';
return ss.str();
};
} // namespace ast

View File

@@ -8,6 +8,11 @@ namespace ast {
name(nullptr),
value(nullptr) {}
let_stmt::let_stmt(token::token token, identifier* name, expression* value)
: token(std::move(token)),
name(name),
value(value) {}
std::string let_stmt::token_literal() const {
return token.literal;
}
@@ -24,6 +29,8 @@ namespace ast {
if (value != nullptr)
ss << value->str();
ss << ';';
return ss.str();
};
} // namespace ast

View File

@@ -7,6 +7,7 @@
namespace ast {
struct let_stmt : statement {
let_stmt(token::token token);
let_stmt(token::token token, identifier* name, expression* value);
token::token token;
identifier* name;

View File

@@ -7,6 +7,10 @@ namespace ast {
: token(std::move(token)),
value(nullptr) {}
return_stmt::return_stmt(token::token token, expression* value)
: token(std::move(token)),
value(value) {}
std::string return_stmt::token_literal() const {
return token.literal;
}
@@ -22,6 +26,8 @@ namespace ast {
if (value != nullptr)
ss << value->str();
ss << ';';
return ss.str();
};
} // namespace ast

View File

@@ -6,6 +6,7 @@
namespace ast {
struct return_stmt : statement {
return_stmt(token::token token);
return_stmt(token::token token, expression* value);
token::token token;
expression* value;

38
test/program.cpp Normal file
View File

@@ -0,0 +1,38 @@
#include "ast/program.hpp"
#include "ast/ast.hpp"
#include "ast/statements/let.hpp"
#include "ast/statements/return.hpp"
#include "token/type.hpp"
#include <doctest.h>
TEST_SUITE("Program") {
TEST_CASE("Let string") {
ast::program program({new ast::let_stmt(
token::token(token::type::LET, "let"),
new ast::identifier(
token::token(token::type::IDENTIFIER, "myVar"),
"myVar"
),
new ast::identifier(
token::token(token::type::IDENTIFIER, "anotherVar"),
"anotherVar"
)
)});
CHECK(program.str() == "let myVar = anotherVar;");
}
TEST_CASE("Return string") {
ast::program program({new ast::return_stmt(
token::token(token::type::RETURN, "return"),
new ast::identifier(
token::token(token::type::IDENTIFIER, "myVar"),
"myVar"
)
)});
CHECK(program.str() == "return myVar;");
}
}