c-compiler/src/ast.cpp
2026-04-14 15:55:13 +03:00

137 lines
3.7 KiB
C++

#include "ast.h"
#include <sstream>
namespace AST {
std::string IntLiteralExpression::formatted() {
std::stringstream out{ "" };
out << this->m_value;
return out.str();
}
std::string StringLiteralExpression::formatted() {
std::stringstream out{ "" };
out << "\"" << this->m_value << "\"";
return out.str();
}
std::string ValueReferenceExpression::formatted() {
return this->m_name;
}
std::string BinaryOperationExpression::formatted() {
std::stringstream out{ "" };
out << this->m_lhs->formatted();
out << " " << format_operator(this->m_binop) << " ";
out << this->m_rhs->formatted();
return out.str();
}
std::string FunctionCallExpression::formatted() {
std::stringstream out{ "" };
out << this->m_fn_expr->formatted() << "(";
int counter = 0;
for (auto& arg : this->m_args) {
if (counter++ > 0)
out << ", ";
out << arg->formatted();
}
out << ")";
return out.str();
}
std::string CastExpression::formatted() {
std::stringstream out{ "" };
out << "(" << this->m_ty->formatted() << ")";
out << this->m_expr->formatted();
return out.str();
}
std::string RefExpression::formatted() {
std::stringstream out{ "" };
out << "&" << this->m_expr->formatted();
return out.str();
}
std::string DerefExpression::formatted() {
std::stringstream out{ "" };
out << "*" << this->m_expr->formatted();
return out.str();
}
std::string IndexAccessExpression::formatted() {
std::stringstream out{ "" };
out << this->m_expr->formatted();
out << "[" << this->m_num << "]";
return out.str();
}
std::string ExpressionStatement::formatted() {
std::stringstream out{ "" };
out << this->m_expr->formatted();
out << ";";
return out.str();
}
std::string IfStatement::formatted() {
std::stringstream out{ "" };
out << "if ";
out << "(" << this->m_condition->formatted() << ")";
out << "\n then " << this->m_then->formatted();
if (this->m_else.has_value())
out << "\n else " << (*this->m_else)->formatted();
return out.str();
}
std::string ReturnStatement::formatted() {
std::stringstream out{ "" };
out << "return ";
out << this->m_expr->formatted();
out << ";";
return out.str();
}
std::string InitializationStatement::formatted() {
std::stringstream out{ "" };
out << this->m_type->formatted() << " " << this->m_name;
if (this->m_expr) {
out << " = " << this->m_expr->get()->formatted();
}
out << ";";
return out.str();
}
std::string Function::formatted() {
std::stringstream out{ "" };
out << this->m_name;
out << "(";
int counter = 0;
for (auto& param : this->m_params) {
if (counter++ > 0)
out << ", ";
out << param.second->formatted();
if (param.first) {
out << " " << *param.first;
}
}
if (this->m_is_vararg) {
if (counter > 0)
out << ", ";
out << "...";
}
out << ") -> ";
out << this->m_return_ty->formatted();
if (this->m_statements) {
out << " {\n";
for (auto& statement : *this->m_statements) {
out << " " << statement->formatted() << "\n";
}
out << "}";
}
return out.str();
}
}