53 lines
1.2 KiB
C++
53 lines
1.2 KiB
C++
#include "Compiler.hpp"
|
|
#include "lib/opcodes.hpp"
|
|
|
|
namespace roza
|
|
{
|
|
/*explicit*/ Compiler::Compiler(StatusLog& log)
|
|
: m_log { log }
|
|
{
|
|
}
|
|
|
|
/*virtual*/ Compiler::~Compiler()
|
|
{
|
|
}
|
|
|
|
std::shared_ptr<Program> Compiler::compile(std::shared_ptr<Node> root)
|
|
{
|
|
auto program = std::make_shared<Program>();
|
|
compile_node(root, program);
|
|
return program;
|
|
}
|
|
|
|
void Compiler::compile_node(std::shared_ptr<Node> root, std::shared_ptr<Program> prog)
|
|
{
|
|
switch (root->type())
|
|
{
|
|
case NODE_INT: {
|
|
auto value = std::make_shared<Value>(std::stoi(root->repr()), root->loc());
|
|
prog->push_instr(OP_PUSH_CONST, prog->push_value(value));
|
|
} break;
|
|
|
|
case NODE_PROG: {
|
|
compile_children(root, prog);
|
|
} break;
|
|
|
|
case NODE_INSTR: {
|
|
compile_children(root, prog);
|
|
prog->push_instr(OP_POP);
|
|
} break;
|
|
|
|
default:
|
|
m_log.fatal(root->loc(), "cannot compile node '" + root->string() + "'.");
|
|
}
|
|
}
|
|
|
|
void Compiler::compile_children(std::shared_ptr<Node> root, std::shared_ptr<Program> prog)
|
|
{
|
|
for (size_t i=0; i<root->size(); i++)
|
|
{
|
|
compile_node(root->child(i), prog);
|
|
}
|
|
}
|
|
}
|