refactor: remove furc for later remake

This commit is contained in:
2026-08-04 12:51:47 +02:00
parent 549af109b9
commit 224468446d
31 changed files with 95 additions and 4989 deletions
-251
View File
@@ -1,251 +0,0 @@
#include "furc/ast/declaration.hpp"
#include "furc/ast/expression.hpp"
#include "furc/ast/node.hpp"
#include "furc/ast/program.hpp"
#include "furc/ast/statement.hpp"
#include <ostream>
namespace furc::ast {
std::ostream& operator<<(std::ostream& os, const error& error) {
return os << error.location << ": ERROR: unknown";
}
bool expression_node::equal(const node& rhs) const {
return expression_type() == dynamic_cast<const expression_node&>(rhs).expression_type();
}
void var_read_expression_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& var_read_expression_node::print(std::ostream& os) const {
return os << m_name;
}
bool var_read_expression_node::equal(const node& rhsNode) const {
const auto& rhs = dynamic_cast<const var_read_expression_node&>(rhsNode);
return expression_node::equal(rhsNode) && m_name == rhs.m_name;
}
std::ostream& operator<<(std::ostream& os, unaryop_expression_node_t type) {
switch (type) {
case unaryop_expression_node_t::Positive: return os << "+";
case unaryop_expression_node_t::Negative: return os << "-";
case unaryop_expression_node_t::PrefixIncrement:
case unaryop_expression_node_t::PostfixIncrement: return os << "++";
case unaryop_expression_node_t::PrefixDecrement:
case unaryop_expression_node_t::PostfixDecrement: return os << "--";
case unaryop_expression_node_t::Pointerof: return os << "pointerof";
case unaryop_expression_node_t::Sizeof: return os << "sizeof";
}
return os;
}
void unary_op_expression_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& unary_op_expression_node::print(std::ostream& os) const {
if (m_node == nullptr) return os;
switch (m_type) {
case unaryop_expression_node_t::Positive:
case unaryop_expression_node_t::Negative:
case unaryop_expression_node_t::PrefixIncrement:
case unaryop_expression_node_t::PrefixDecrement: return os << '(' << m_type << *m_node << ')';
case unaryop_expression_node_t::PostfixIncrement:
case unaryop_expression_node_t::PostfixDecrement: return os << '(' << *m_node << m_type << ')';
case unaryop_expression_node_t::Pointerof: return os << "pointerof " << *m_node;
case unaryop_expression_node_t::Sizeof: return os << "sizeof " << *m_node;
}
return os;
}
bool unary_op_expression_node::equal(const node& rhsNode) const {
const auto& rhs = dynamic_cast<const unary_op_expression_node&>(rhsNode);
return expression_node::equal(rhsNode) && m_type == rhs.m_type && m_node == rhs.m_node;
}
std::ostream& operator<<(std::ostream& os, binop_expression_node_t type) {
switch (type) {
default:
case binop_expression_node_t::None: return os;
case binop_expression_node_t::Add: return os << '+';
case binop_expression_node_t::Sub: return os << '-';
case binop_expression_node_t::Mul: return os << '*';
case binop_expression_node_t::Div: return os << '/';
case binop_expression_node_t::Mod: return os << '%';
case binop_expression_node_t::Equal: return os << "==";
case binop_expression_node_t::NotEqual: return os << "!=";
case binop_expression_node_t::LessThan: return os << '<';
case binop_expression_node_t::GreaterThan: return os << '>';
case binop_expression_node_t::LessEqual: return os << "<=";
case binop_expression_node_t::GreaterEqual: return os << ">=";
}
}
void binary_op_expression_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& binary_op_expression_node::print(std::ostream& os) const {
if (m_type == binop_expression_node_t::None) return os;
return os << '(' << *m_lhs << ' ' << m_type << ' ' << *m_rhs << ')';
}
bool binary_op_expression_node::equal(const node& rhsNode) const {
const auto& rhs = dynamic_cast<const binary_op_expression_node&>(rhsNode);
return expression_node::equal(rhsNode) && m_type == rhs.m_type && m_lhs == rhs.m_lhs && m_rhs == rhs.m_rhs;
}
void var_assign_expression_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& var_assign_expression_node::print(std::ostream& os) const {
return os << '(' << *m_lhs << ' ' << m_compound << "= " << *m_rhs << ')';
}
bool var_assign_expression_node::equal(const node& rhsNode) const {
const auto& rhs = dynamic_cast<const var_assign_expression_node&>(rhsNode);
return expression_node::equal(rhsNode) && m_compound == rhs.m_compound && m_lhs == rhs.m_lhs && m_rhs == rhs.m_rhs;
}
void function_call_expression_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& function_call_expression_node::print(std::ostream& os) const {
os << *m_func << '(';
bool first = true;
for (const auto& arg : m_args) {
if (!first) os << ", ";
first = false;
os << *arg;
}
return os << ')';
}
bool function_call_expression_node::equal(const node& rhsNode) const {
const auto& rhs = dynamic_cast<const function_call_expression_node&>(rhsNode);
return expression_node::equal(rhsNode) && m_func == rhs.m_func && m_args == rhs.m_args;
}
bool declaration_node::equal(const node& rhs) const {
return declaration_type() == dynamic_cast<const declaration_node&>(rhs).declaration_type();
}
void function_declaration_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& function_declaration_node::print(std::ostream& os) const {
return os << "function " << p_name << " declaration";
}
bool function_declaration_node::equal(const node& rhs) const {
return declaration_node::equal(rhs) && p_name == dynamic_cast<const function_declaration_node&>(rhs).p_name;
}
void function_definition_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& function_definition_node::print(std::ostream& os) const {
function_declaration_node::print(os);
os << ":\n";
for (const auto& entry : m_body.statements)
os << entry << '\n';
return os << m_body.end << ": " << p_name << " end";
}
bool function_definition_node::equal(const node& rhs) const {
return function_declaration_node::equal(rhs) && m_body == dynamic_cast<const function_definition_node&>(rhs).m_body;
}
bool statement_node::equal(const node& rhs) const {
return statement_type() == dynamic_cast<const statement_node&>(rhs).statement_type();
}
void return_statement_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& return_statement_node::print(std::ostream& os) const {
os << "return statement";
if (m_value.has_value()) return os << ' ' << *m_value.value();
return os;
}
bool return_statement_node::equal(const node& rhs) const {
return statement_node::equal(rhs) && m_value == dynamic_cast<const return_statement_node&>(rhs).m_value;
}
void if_statement_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& if_statement_node::print(std::ostream& os) const {
os << "if " << *m_cond << ", then:\n";
os << m_then;
if (m_else.has_value()) os << *m_else.value();
return os;
}
bool if_statement_node::equal(const node& rhsNode) const {
const auto& rhs = dynamic_cast<const if_statement_node&>(rhsNode);
return statement_node::equal(rhs) && m_cond == rhs.m_cond && m_then == rhs.m_then && m_else == rhs.m_else;
}
void compound_statement_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& compound_statement_node::print(std::ostream& os) const {
return os << m_body;
}
bool compound_statement_node::equal(const node& rhs) const {
return statement_node::equal(rhs) && m_body == dynamic_cast<const compound_statement_node&>(rhs).m_body;
}
void while_statement_node::accept(visitor& visitor) const {
visitor.visit(*this);
}
std::ostream& while_statement_node::print(std::ostream& os) const {
return os << m_body;
}
bool while_statement_node::equal(const node& rhs) const {
return statement_node::equal(rhs) && m_body == dynamic_cast<const while_statement_node&>(rhs).m_body;
}
void program_node::accept(visitor& visitor) const {
for (const auto& decl : m_declarations) {
decl->accept(visitor);
}
}
std::ostream& program_node::print(std::ostream& os) const {
os << "program:";
for (const auto& handle : m_declarations) {
os << '\n' << handle;
}
return os;
}
bool program_node::equal(const node& rhs) const {
return m_declarations == dynamic_cast<const program_node&>(rhs).m_declarations;
}
std::ostream& operator<<(std::ostream& os, const body& body) {
os << "body:";
for (const auto& stmt : body.statements) {
os << '\n' << stmt;
}
return os;
}
} // namespace furc::ast
-196
View File
@@ -1,196 +0,0 @@
#include "furc/back/furvm.hpp"
#include "furlang/ir/function.hpp"
#include "furlang/ir/instruction.hpp"
#include "furvm/function.hpp"
#include "furvm/fwd.hpp"
#include <furvm/instruction.hpp>
#include <stdexcept>
namespace furc::back {
furvm::mod furvm_generator::generate(furlang::ir::mod& mod) {
furvm::mod vmMod;
for (const auto& function : mod.functions()) {
generate_function(vmMod, *function);
}
return vmMod;
}
void furvm_generator::generate_function(furvm::mod& mod, const furlang::ir::function& function) {
furvm::function_sig signature; // TODO: Complete
switch (function.type()) {
case furlang::ir::function_t::Normal: {
if (function.access() == furlang::ir::function_access_t::Public)
mod.emplace_function(function.name(), std::move(signature), mod.bytecode().size()).dispatch();
else
mod.emplace_function(std::move(signature), mod.bytecode().size()).dispatch();
function_context ctx;
for (furlang::ir::block_index idx = 0; idx < function.blocks().size(); ++idx) {
if (auto it = ctx.incompleteJumps.find(idx); it != ctx.incompleteJumps.end()) {
for (std::size_t offset : it->second) {
mod.bytecode()[offset] = mod.bytecode().size() - offset - 1;
}
ctx.incompleteJumps.erase(it);
}
ctx.blockOffsets[idx] = mod.bytecode().size();
for (const auto& instr : function.blocks()[idx]->instructions())
generate_instruction(mod, ctx, *instr);
generate_instruction(mod, ctx, *function.blocks()[idx]->exit());
}
} break;
case furlang::ir::function_t::Import: {
throw std::runtime_error("unimplemented");
// mod.emplace_function_private(function.name(), function.param_count(), mod.bytecode().size()).dispatch();
} break;
case furlang::ir::function_t::Native: {
if (function.access() == furlang::ir::function_access_t::Public)
mod.emplace_function(function.name(), std::move(signature), function.name()).dispatch();
else
mod.emplace_function(std::move(signature), function.name()).dispatch();
} break;
}
}
static inline furvm::instruction_t op_type(furlang::ir::instruction_t type) {
switch (type) {
// Unary
case furlang::ir::instruction_t::Pointerof: return furvm::instruction_t::Pointerof;
case furlang::ir::instruction_t::Sizeof: return furvm::instruction_t::Sizeof;
// Binary
case furlang::ir::instruction_t::Add: return furvm::instruction_t::Add;
case furlang::ir::instruction_t::Sub: return furvm::instruction_t::Sub;
case furlang::ir::instruction_t::Mul: return furvm::instruction_t::Mul;
case furlang::ir::instruction_t::Div: return furvm::instruction_t::Div;
case furlang::ir::instruction_t::Mod: return furvm::instruction_t::Mod;
case furlang::ir::instruction_t::Eq: return furvm::instruction_t::Equals;
case furlang::ir::instruction_t::NotEq: return furvm::instruction_t::NotEquals;
case furlang::ir::instruction_t::LessThan: return furvm::instruction_t::LessThan;
case furlang::ir::instruction_t::GreaterThan: return furvm::instruction_t::GreaterThan;
case furlang::ir::instruction_t::LessEq: return furvm::instruction_t::LessEqual;
case furlang::ir::instruction_t::GreaterEq: return furvm::instruction_t::GreaterEqual;
default: throw std::runtime_error("unreachable");
}
}
void furvm_generator::generate_instruction(furvm::mod& mod,
function_context& ctx,
const furlang::ir::instruction& instr) {
for (const auto& operand : instr.sources())
generate_operand(mod, ctx, *operand);
switch (instr.type()) {
case furlang::ir::instruction_t::Assign: {
if (ctx.variables.find(instr.destination().reg()) == ctx.variables.end()) {
ctx.variables[instr.destination().reg()] = ctx.variableCounter++;
}
auto var = ctx.variables[instr.destination().reg()];
mod.bytecode().push_back(static_cast<furvm::byte>(furvm::instruction_t::Store));
mod.bytecode().push_back((var >> 0) & 0xFF);
mod.bytecode().push_back((var >> 8) & 0xFF);
static_assert(sizeof(var) == 2, "sizeof(furvm::variable_t) has changed");
} break;
case furlang::ir::instruction_t::Add:
case furlang::ir::instruction_t::Sub:
case furlang::ir::instruction_t::Mul:
case furlang::ir::instruction_t::Div:
case furlang::ir::instruction_t::Mod:
case furlang::ir::instruction_t::Eq:
case furlang::ir::instruction_t::NotEq:
case furlang::ir::instruction_t::LessThan:
case furlang::ir::instruction_t::GreaterThan:
case furlang::ir::instruction_t::LessEq:
case furlang::ir::instruction_t::GreaterEq: {
mod.bytecode().push_back(static_cast<furvm::byte>(op_type(instr.type())));
if (ctx.variables.find(instr.destination().reg()) == ctx.variables.end()) {
ctx.variables[instr.destination().reg()] = ctx.variableCounter++;
}
auto var = ctx.variables[instr.destination().reg()];
mod.bytecode().push_back(static_cast<furvm::byte>(furvm::instruction_t::Store));
mod.bytecode().push_back((var >> 0) & 0xFF);
mod.bytecode().push_back((var >> 8) & 0xFF);
static_assert(sizeof(var) == 2, "sizeof(furvm::variable_t) has changed");
} break;
case furlang::ir::instruction_t::Pointerof:
case furlang::ir::instruction_t::Sizeof: {
mod.bytecode().push_back(static_cast<furvm::byte>(op_type(instr.type())));
if (ctx.variables.find(instr.destination().reg()) == ctx.variables.end()) {
ctx.variables[instr.destination().reg()] = ctx.variableCounter++;
}
auto var = ctx.variables[instr.destination().reg()];
mod.bytecode().push_back(static_cast<furvm::byte>(furvm::instruction_t::Store));
mod.bytecode().push_back((var >> 0) & 0xFF);
mod.bytecode().push_back((var >> 8) & 0xFF);
static_assert(sizeof(var) == 2, "sizeof(furvm::variable_t) has changed");
} break;
case furlang::ir::instruction_t::Branch: {
const auto& branch = dynamic_cast<const furlang::ir::branch_instruction&>(instr);
generate_jump(mod, ctx, branch.block(), false);
} break;
case furlang::ir::instruction_t::BranchCond: {
const auto& branch = dynamic_cast<const furlang::ir::branch_cond_instruction&>(instr);
generate_jump(mod, ctx, branch.if_block(), true);
generate_jump(mod, ctx, branch.else_block(), false);
} break;
case furlang::ir::instruction_t::Return: {
mod.bytecode().push_back(static_cast<furvm::byte>(furvm::instruction_t::Return));
} break;
case furlang::ir::instruction_t::Call: {
const auto& call = dynamic_cast<const furlang::ir::call_instruction&>(instr);
// TODO: Implement a queue for unknown functions
furvm::function_id func = mod.function_at(call.name(), furvm::function_sig{}).id(); // TODO: Complete
mod.bytecode().push_back(static_cast<furvm::byte>(furvm::instruction_t::Call));
mod.bytecode().push_back((func >> 0) & 0xFF);
mod.bytecode().push_back((func >> 8) & 0xFF);
} break;
case furlang::ir::instruction_t::Alloca: throw std::runtime_error("unimplemented instruction");
case furlang::ir::instruction_t::Phi: throw std::runtime_error("unreachable");
}
}
void furvm_generator::generate_operand(furvm::mod& mod, function_context& ctx, const furlang::ir::operand& operand) {
switch (operand.type()) {
case furlang::ir::operand_t::Register: {
if (ctx.variables.find(operand.reg()) == ctx.variables.end()) throw std::runtime_error("unregistered register");
auto var = ctx.variables[operand.reg()];
mod.bytecode().push_back(static_cast<furvm::byte>(furvm::instruction_t::Load));
mod.bytecode().push_back((var >> 0) & 0xFF);
mod.bytecode().push_back((var >> 8) & 0xFF);
static_assert(sizeof(var) == 2, "sizeof(furvm::variable_t) has changed");
} break;
case furlang::ir::operand_t::Integer: {
mod.bytecode().push_back(static_cast<furvm::byte>(furvm::instruction_t::PushS32));
mod.bytecode().push_back(operand.integer());
} break;
case furlang::ir::operand_t::Variable:
case furlang::ir::operand_t::String: throw std::runtime_error("unimplemented operand");
case furlang::ir::operand_t::None: throw std::runtime_error("unreachable");
}
}
void furvm_generator::generate_jump(furvm::mod& mod,
function_context& ctx,
furlang::ir::block_index block,
bool conditional) {
mod.bytecode().push_back(
static_cast<furvm::byte>(conditional ? furvm::instruction_t::JumpNotZero : furvm::instruction_t::Jump));
if (auto it = ctx.blockOffsets.find(block); it != ctx.blockOffsets.end()) {
mod.bytecode().push_back(it->second - mod.bytecode().size() - 1);
} else {
ctx.incompleteJumps[block].push_back(mod.bytecode().size());
mod.bytecode().push_back(0);
}
}
} // namespace furc::back
-232
View File
@@ -1,232 +0,0 @@
#include "furc/front/ir_generator.hpp"
#include "furc/ast/declaration.hpp" // IWYU pragma: keep
#include "furc/ast/expression.hpp" // IWYU pragma: keep
#include "furc/ast/literal.hpp" // IWYU pragma: keep
#include "furc/ast/statement.hpp" // IWYU pragma: keep
#include "furlang/ir/function.hpp"
#include "furlang/ir/instruction.hpp"
#include "furlang/ir/operand.hpp"
#include <cassert>
#include <memory>
#include <stdexcept>
#include <vector>
namespace furc::front {
namespace {
namespace ir = furlang::ir;
}
void ir_generator::visit(const ast::function_definition_node& funcDef) {
furlang::ir::function_access_t access = (funcDef.access() == ast::declaration_access_t::Public)
? furlang::ir::function_access_t::Public
: furlang::ir::function_access_t::Private;
m_currentFunction = std::make_unique<furlang::ir::function>(std::string(funcDef.name()), access, 0);
push_block();
for (const auto& stmt : funcDef.body().statements) {
stmt.value()->accept(*this);
}
m_currentBlock->emplace<ir::return_instruction>();
m_module.push(std::move(m_currentFunction));
}
void ir_generator::visit(const ast::function_declaration_node& funcDecl) {
if (funcDecl.type() == ast::function_declaration_node_t::Normal) return;
furlang::ir::function_t type = funcDecl.type() == ast::function_declaration_node_t::Import
? furlang::ir::function_t::Import
: furlang::ir::function_t::Native;
furlang::ir::function_access_t access = (funcDecl.access() == ast::declaration_access_t::Public)
? furlang::ir::function_access_t::Public
: furlang::ir::function_access_t::Private;
m_module.push(
std::make_unique<furlang::ir::function>(std::string(funcDecl.name()), access, funcDecl.params().size(), type));
}
void ir_generator::visit(const ast::return_statement_node& returnStmt) {
if (returnStmt.value().has_value()) {
returnStmt.value().value()->accept(*this);
push<ir::return_instruction>(ir::operand::new_reg(m_registerCounter - 1));
} else {
push<ir::return_instruction>();
}
}
void ir_generator::visit(const ast::if_statement_node& node) {
node.cond()->accept(*this);
ir_register cond = m_registerCounter - 1;
push<ir::branch_cond_instruction>(ir::operand::new_reg(cond),
m_currentFunction->blocks().size(),
m_currentFunction->blocks().size() + 1);
push_block(); // then block
node.then()->accept(*this);
if (node.elze().has_value()) {
m_currentBlock->emplace<ir::branch_instruction>(m_currentFunction->blocks().size() + 1);
push_block(); // else block
node.elze().value()->accept(*this);
}
m_currentBlock->emplace<ir::branch_instruction>(m_currentFunction->blocks().size());
push_block(); // merge block
}
void ir_generator::visit(const ast::while_statement_node& node) {
node.condition()->accept(*this);
ir_register cond = m_registerCounter - 1;
std::shared_ptr<ir::block> entry = m_currentBlock;
ir::block_index headerIdx = m_currentFunction->blocks().size();
push_block(false); // loop header
push<ir::branch_instruction>(m_currentFunction->blocks().size());
push_block(); // loop condition
node.condition()->accept(*this);
std::shared_ptr<ir::block> condBlock = m_currentBlock;
ir_register cond2 = m_registerCounter - 1;
push_block(false); // loop body
node.body()->accept(*this);
push<ir::branch_instruction>(headerIdx);
entry->emplace<ir::branch_cond_instruction>(ir::operand::new_reg(cond),
headerIdx,
m_currentFunction->blocks().size());
condBlock->emplace<ir::branch_cond_instruction>(ir::operand::new_reg(cond2),
m_currentFunction->blocks().size() - 1,
m_currentFunction->blocks().size());
push_block(); // merge block
}
void ir_generator::visit(const ast::compound_statement_node& node) {
for (const auto& stmt : node.body().statements) {
stmt.value()->accept(*this);
}
}
void ir_generator::visit(const ast::string_literal_node& node) {
push<furlang::ir::assign_instruction>(ir::operand::new_string(node.value()),
ir::operand::new_reg(m_registerCounter++));
}
void ir_generator::visit(const ast::integer_literal_node& node) {
push<furlang::ir::assign_instruction>(ir::operand::new_integer(node.value()),
ir::operand::new_reg(m_registerCounter++));
}
void ir_generator::visit(const ast::var_read_expression_node& node) {
if (auto it = m_variables.find(node.get_name()); it != m_variables.end()) {
push<furlang::ir::assign_instruction>(ir::operand::new_reg(it->second),
ir::operand::new_reg(m_registerCounter++));
} else {
throw std::runtime_error("unknown variable");
}
}
static inline furlang::ir::instruction_t unary_op_instruction_t(ast::unaryop_expression_node_t type) {
switch (type) {
case ast::unaryop_expression_node_t::Pointerof: return furlang::ir::instruction_t::Pointerof;
case ast::unaryop_expression_node_t::Sizeof: return furlang::ir::instruction_t::Sizeof;
default: throw std::runtime_error("unimplemented");
}
}
void ir_generator::visit(const ast::unary_op_expression_node& node) {
node.get_node()->accept(*this);
ir_register src = m_registerCounter - 1;
ir_register dst = m_registerCounter++;
push<furlang::ir::unary_instruction>(unary_op_instruction_t(node.type()),
ir::operand::new_reg(src),
ir::operand::new_reg(dst));
}
static inline furlang::ir::instruction_t binary_op_instruction_t(ast::binop_expression_node_t type) {
switch (type) {
case ast::binop_expression_node_t::Add: return furlang::ir::instruction_t::Add;
case ast::binop_expression_node_t::Sub: return furlang::ir::instruction_t::Sub;
case ast::binop_expression_node_t::Mul: return furlang::ir::instruction_t::Mul;
case ast::binop_expression_node_t::Div: return furlang::ir::instruction_t::Div;
case ast::binop_expression_node_t::Mod: return furlang::ir::instruction_t::Mod;
case ast::binop_expression_node_t::Equal: return furlang::ir::instruction_t::Eq;
case ast::binop_expression_node_t::NotEqual: return furlang::ir::instruction_t::NotEq;
case ast::binop_expression_node_t::LessThan: return furlang::ir::instruction_t::LessThan;
case ast::binop_expression_node_t::GreaterThan: return furlang::ir::instruction_t::GreaterThan;
case ast::binop_expression_node_t::LessEqual: return furlang::ir::instruction_t::LessEq;
case ast::binop_expression_node_t::GreaterEqual: return furlang::ir::instruction_t::GreaterEq;
case ast::binop_expression_node_t::None:
default: throw std::runtime_error("unreachable");
}
}
void ir_generator::visit(const ast::binary_op_expression_node& node) {
node.lhs()->accept(*this);
ir_register lhs = m_registerCounter - 1;
node.rhs()->accept(*this);
ir_register rhs = m_registerCounter - 1;
ir_register dst = m_registerCounter++;
push<furlang::ir::binary_instruction>(binary_op_instruction_t(node.type()),
ir::operand::new_reg(lhs),
ir::operand::new_reg(rhs),
ir::operand::new_reg(dst));
}
void ir_generator::visit(const ast::var_assign_expression_node& node) {
node.rhs()->accept(*this);
ir_register rhs = m_registerCounter - 1;
assert(node.lhs()->expression_type() == ast::expression_node_t::VarRead);
auto lhs = std::dynamic_pointer_cast<ast::var_read_expression_node>(node.lhs());
ir_register reg = m_registerCounter++;
auto compound = node.compound();
if (compound != ast::binop_expression_node_t::None) {
push<ir::binary_instruction>(binary_op_instruction_t(compound),
ir::operand::new_reg(reg),
ir::operand::new_reg(rhs),
ir::operand::new_reg(reg));
} else {
push<ir::assign_instruction>(ir::operand::new_reg(rhs), ir::operand::new_reg(reg));
}
if (auto it = m_variables.find(lhs->get_name()); it != m_variables.end()) {
push<ir::assign_instruction>(ir::operand::new_reg(reg), ir::operand::new_reg(it->second));
} else {
m_variables[lhs->get_name()] = reg;
}
}
void ir_generator::visit(const ast::function_call_expression_node& node) {
std::vector<ir::operand> args;
args.reserve(node.args().size());
for (const auto& arg : node.args()) {
arg->accept(*this);
args.push_back(ir::operand::new_reg(m_registerCounter - 1));
}
if (node.func()->expression_type() != ast::expression_node_t::VarRead)
throw std::runtime_error("invalid function call left-hand-side expression");
push<ir::call_instruction>(dynamic_cast<const ast::var_read_expression_node&>(*node.func()).get_name(),
ir::operand::new_reg(m_registerCounter++),
std::move(args));
}
furlang::ir::block_index ir_generator::push_block(bool validate) {
if (validate && !m_currentFunction->blocks().empty() && !m_currentFunction->blocks().back()->has_exit()) {
throw std::runtime_error(
"block " + std::to_string(m_currentFunction->blocks().size() - 1) + " is lacking an exit");
}
ir::block_index index = m_currentFunction->blocks().size();
m_currentBlock = m_currentFunction->push();
return index;
}
} // namespace furc::front
-200
View File
@@ -1,200 +0,0 @@
#include "furc/front/lexer.hpp"
#include "furc/front/token.hpp"
#include <cctype>
#include <limits>
#include <map>
#include <string>
#include <unordered_map>
namespace furc::front {
using namespace std::string_literals;
lexer::lexer(std::string_view filename, std::string_view content)
: m_filename(filename), m_content(content) {}
token_r lexer::next_token() {
skip_spaces();
while (m_cursor + 2 <= m_content.size() && m_content[m_cursor] == '/') {
if (m_content[m_cursor + 1] == '/') {
m_cursor += 2;
while (m_content[m_cursor] != '\n') {
next();
}
} else if (m_content[m_cursor + 1] == '*') {
m_cursor += 2;
while (m_cursor + 2 < m_content.size()) {
if (m_content[m_cursor + 1] == '*') {
next();
} else if (m_content[m_cursor + 0] != '*' || m_content[m_cursor + 1] != '/') {
next();
next();
} else {
break;
}
}
if (m_cursor + 2 >= m_content.size()) {
next();
return token_r(
token_error{ current_location(), token_error_t::UnexpectedEof, "before enclosing `*/`" });
}
m_cursor += 2;
} else {
break;
}
skip_spaces();
}
location location = current_location();
switch (get()) {
case '"': {
std::size_t begin = ++m_cursor;
while (m_cursor < m_content.size() && m_content[m_cursor] != '"')
++m_cursor;
if (m_cursor >= m_content.size()) {
return token_r(token_error{ current_location(), token_error_t::UnexpectedEof, "before enclosing '\"'" });
}
++m_cursor;
return { location, token_t::String, m_content.substr(begin, m_cursor - begin - 1) };
}
case std::char_traits<char>::eof(): return token_r(token_error{ current_location(), token_error_t::EndOfFile });
default: {
if (std::isdigit(get()) != 0) {
integer_token integer = 0;
integer_token max = std::numeric_limits<integer_token>::max();
integer_token upperBound = max / 10;
std::size_t start = m_cursor;
while (std::isdigit(get()) != 0) {
integer_token digit = get() - '0';
if (integer > upperBound || integer == upperBound && (integer - upperBound + digit) > (max % 10)) {
while (std::isdigit(get()) != 0)
++m_cursor;
return token_r(token_error{ location,
token_error_t::IntegerOverflow,
std::string(m_content.substr(start, m_cursor - start)) });
}
integer *= 10;
integer += digit;
++m_cursor;
}
return { location, integer };
}
if (std::isalnum(get()) != 0 || get() == '_') {
std::size_t start = m_cursor++;
while (std::isalnum(get()) != 0 || get() == '_')
next();
std::string_view value = m_content.substr(start, m_cursor - start);
static std::unordered_map<std::string_view, keyword_token> s_keywords = {
{ "func", keyword_token::Func },
{ "return", keyword_token::Return },
{ "if", keyword_token::If },
{ "else", keyword_token::Else },
{ "while", keyword_token::While },
{ "import", keyword_token::Import },
{ "native", keyword_token::Native },
{ "public", keyword_token::Public },
{ "private", keyword_token::Private },
{ "pointerof", keyword_token::Pointerof },
{ "sizeof", keyword_token::Sizeof },
{ "int32", keyword_token::Int32 },
};
if (auto it = s_keywords.find(value); it != s_keywords.end()) return { location, it->second };
return { location, token_t::Identifier, value };
}
struct compare {
bool operator()(const std::string_view& lhs, const std::string_view& rhs) const {
if (lhs.size() != rhs.size()) return lhs.size() > rhs.size();
return lhs < rhs;
}
};
static std::map<std::string_view, token_t, compare> s_tokens = {
{ "(", token_t::LParen },
{ ")", token_t::RParen },
{ "{", token_t::LBrace },
{ "}", token_t::RBrace },
{ "[", token_t::LBracket },
{ "]", token_t::RBracket },
{ ";", token_t::Semicolon },
{ ":", token_t::Colon },
{ ",", token_t::Comma },
{ ".", token_t::Dot },
{ "+", token_t::Plus },
{ "-", token_t::Minus },
{ "*", token_t::Star },
{ "/", token_t::Slash },
{ "%", token_t::Percent },
{ "++", token_t::DPlus },
{ "--", token_t::DMinus },
{ "=", token_t::Eq },
{ "+=", token_t::PlusEq },
{ "-=", token_t::MinusEq },
{ "*=", token_t::StarEq },
{ "/=", token_t::SlashEq },
{ "%=", token_t::PercentEq },
{ "==", token_t::DEq },
{ "!=", token_t::NotEq },
{ "<", token_t::LessThan },
{ ">", token_t::GreaterThan },
{ "<=", token_t::LessEq },
{ ">=", token_t::GreaterEq },
{ "->", token_t::SlimArrow },
{ "=>", token_t::FatArrow },
};
token_t type = token_t::None;
std::size_t length = 1;
while (m_cursor + length <= m_content.size()) {
auto it = s_tokens.find(m_content.substr(m_cursor, length));
if (it == s_tokens.end()) break;
type = it->second;
++length;
}
if (type != token_t::None) {
m_cursor += length - 1;
return { location, type };
}
return token_r(
token_error{ location, token_error_t::UnexpectedCharacter, std::string(m_content.substr(m_cursor, 1)) });
}
}
}
void lexer::next() {
if (m_cursor >= m_content.size()) return;
char ch = get();
++m_cursor;
if (ch == '\n') {
++m_row;
m_lineStart = m_cursor;
}
}
char lexer::get(std::size_t offset) const {
if (m_cursor + offset < m_content.size()) return m_content[m_cursor + offset];
return std::char_traits<char>::eof();
}
void lexer::skip_spaces() {
while (std::isspace(get()) != 0)
next();
}
location lexer::current_location() {
return { m_filename, m_row, m_cursor - m_lineStart };
}
} // namespace furc::front
-587
View File
@@ -1,587 +0,0 @@
#include "furc/front/parser.hpp"
#include "furc/ast/declaration.hpp" // IWYU pragma: keep
#include "furc/ast/expression.hpp" // IWYU pragma: keep
#include "furc/ast/fwd.hpp"
#include "furc/ast/literal.hpp" // IWYU pragma: keep
#include "furc/ast/program.hpp" // IWYU pragma: keep
#include "furc/ast/statement.hpp" // IWYU pragma: keep
#include "furc/front/token.hpp"
#include <fstream>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
namespace furc::front {
using namespace std::string_literals;
parser::parser(furlang::arena& arena, std::string_view filename, std::string_view content)
: m_filename(filename), m_content(content), m_lexer(m_filename, m_content), m_arena(&arena) {}
parser::parser(furlang::arena& arena, std::string_view filename)
: m_filename(filename), m_arena(&arena) {
std::ifstream file(m_filename, std::ios_base::binary | std::ios_base::ate);
if (!file.is_open()) throw std::runtime_error("failed to open file "s.append(m_filename));
std::streampos size = file.tellg();
file.seekg(0);
m_content.resize(size);
file.read(m_content.data(), size);
m_lexer = { filename, m_content };
}
ast::program_node_r parser::parse() & {
auto program = m_arena->allocate_shared<ast::program_node>(location{ m_filename });
while (peek_token().has_value()) {
auto decl = parse_declaration();
if (decl.has_error()) return ast::program_node_r(ast::error{ decl.error().location });
program->push(std::move(decl.value()));
}
return program;
}
ast::type_r parser::parse_type() {
auto token = eat_token(token_t::Keyword);
if (token.has_error() || token.value()->keyword != keyword_token::Int32)
return ast::type_r(ast::error{ token.error().location });
return ast::type("" + token.value()->keyword);
}
ast::declaration_node_r parser::parse_declaration() {
const auto& first = peek_token();
if (first.has_error()) return ast::declaration_node_r(ast::error{ first.error().location });
switch (first->type) {
case token_t::Keyword: {
token firstToken = *first;
ast::declaration_access_t accessOverride = ast::declaration_access_t::Implicit;
switch ((*first)->keyword) {
default: break;
case keyword_token::Public:
case keyword_token::Private: {
if ((*first)->keyword == keyword_token::Public) accessOverride = ast::declaration_access_t::Public;
if ((*first)->keyword == keyword_token::Private) accessOverride = ast::declaration_access_t::Private;
auto kw = eat_token(token_t::Keyword);
if (kw.has_error()) return ast::declaration_node_r(ast::error{ kw.error().location });
firstToken = *kw;
} break;
}
ast::function_declaration_node_t funcDeclType{};
auto kw = next_token();
if (kw.has_error()) return ast::declaration_node_r(ast::error{ kw.error().location });
firstToken = *kw;
switch (firstToken->keyword) {
case keyword_token::Import:
case keyword_token::Native: {
funcDeclType = (firstToken->keyword == keyword_token::Import) ? ast::function_declaration_node_t::Import
: ast::function_declaration_node_t::Native;
auto kw = eat_token(token_t::Keyword);
if (kw.has_error()) return ast::declaration_node_r(ast::error{ kw.error().location });
firstToken = *kw;
if (firstToken.value.keyword != keyword_token::Func)
return ast::declaration_node_r(ast::error{ firstToken.location });
}
case keyword_token::Func: {
auto name = eat_token(token_t::Identifier);
if (name.has_error()) return ast::declaration_node_r(ast::error{ name.error().location });
auto tok = eat_token(token_t::LParen);
if (tok.has_error()) return ast::declaration_node_r(ast::error{ tok.error().location });
std::vector<ast::function_declaration_param> params;
if (peek_token().has_value() && peek_token()->type != token_t::RParen) {
while (true) {
auto name = eat_token(token_t::Identifier);
if (name.has_error()) return ast::declaration_node_r(ast::error{ name.error().location });
auto colon = eat_token(token_t::Colon);
if (colon.has_error()) return ast::declaration_node_r(ast::error{ colon.error().location });
auto type = parse_type();
if (type.has_error()) return ast::declaration_node_r(ast::error{ type.error().location });
params.push_back(
ast::function_declaration_param{ std::string(name->value.string), std::move(*type) });
auto comma = eat_token(token_t::Comma);
if (comma.has_error()) break;
}
}
tok = eat_token(token_t::RParen);
if (tok.has_error()) return ast::declaration_node_r(ast::error{ tok.error().location });
std::optional<ast::type> returnType;
if (peek_token().has_value() && peek_token()->type == token_t::SlimArrow) {
auto tok = next_token();
auto type = parse_type();
if (type.has_error()) return ast::declaration_node_r(ast::error{ tok->location });
returnType = *type;
}
auto access = (funcDeclType == ast::function_declaration_node_t::Import)
? ast::declaration_access_t::Private
: accessOverride;
if (access == ast::declaration_access_t::Implicit) access = ast::declaration_access_t::Public;
if (!ast::same_access(accessOverride, access)) return ast::declaration_node_r(ast::error{ tok->location });
const auto& peek = peek_token();
if (peek.has_error()) return ast::declaration_node_r(ast::error{ peek.error().location });
switch (peek->type) {
case token_t::LBrace: {
ast::body_r body = parse_body();
if (body.has_error()) return ast::declaration_node_r(ast::error{ body.error().location });
if (funcDeclType != ast::function_declaration_node_t::Normal)
return ast::declaration_node_r(ast::error{ body->begin });
return m_arena->allocate_shared<ast::function_definition_node>(firstToken.location,
access,
name->value.string,
std::move(returnType),
std::move(params),
std::move(body.value()));
}
case token_t::Semicolon: {
m_peekBuffer.clear();
return m_arena->allocate_shared<ast::function_declaration_node>(firstToken.location,
access,
name->value.string,
std::move(returnType),
std::move(params),
funcDeclType);
}
default: return ast::declaration_node_r(ast::error{ tok->location });
}
}
default: return ast::declaration_node_r(ast::error{ firstToken.location });
}
}
case token_t::None:
case token_t::Identifier:
case token_t::Integer:
case token_t::LParen:
case token_t::RParen:
case token_t::LBrace:
case token_t::RBrace:
case token_t::LBracket:
case token_t::RBracket:
case token_t::Semicolon:
case token_t::Colon:
default: {
return ast::declaration_node_r(ast::error{ first->location });
}
}
}
ast::statement_node_r parser::parse_statement() {
const auto& tok = peek_token();
if (tok.has_error()) return ast::statement_node_r(ast::error{ tok.error().location });
auto location = tok->location;
switch (tok->type) {
case token_t::Keyword: {
switch (tok->value.keyword) {
case keyword_token::Return: {
auto tok = next_token();
if (peek_token()->type == token_t::Semicolon) {
next_token();
return m_arena->allocate_shared<ast::return_statement_node>(location);
}
auto value = parse_expression();
auto err = eat_token(token_t::Semicolon);
if (err.has_error()) return ast::statement_node_r(ast::error{ err.error().location });
return m_arena->allocate_shared<ast::return_statement_node>(location, std::move(value.value()));
}
case keyword_token::If: {
auto tok = next_token();
auto err = eat_token(token_t::LParen);
if (err.has_error()) return ast::statement_node_r(ast::error{ err.error().location });
auto cond = parse_expression();
err = eat_token(token_t::RParen);
if (err.has_error()) return ast::statement_node_r(ast::error{ err.error().location });
auto then = parse_statement();
if (then.has_error()) return ast::statement_node_r(ast::error{ then.error().location });
if (peek_token().has_value() && peek_token()->type == token_t::Keyword &&
peek_token()->value.keyword == keyword_token::Else) {
next_token();
auto elseBody = parse_statement();
if (elseBody.has_error()) return ast::statement_node_r(ast::error{ elseBody.error().location });
return m_arena->allocate_shared<ast::if_statement_node>(location,
std::move(cond.value()),
std::move(then.value()),
std::move(elseBody.value()));
}
return m_arena->allocate_shared<ast::if_statement_node>(location,
std::move(cond.value()),
std::move(then.value()));
}
case keyword_token::While: {
auto tok = next_token();
auto err = eat_token(token_t::LParen);
if (err.has_error()) return ast::statement_node_r(ast::error{ err.error().location });
auto cond = parse_expression();
if (cond.has_error()) return ast::statement_node_r(ast::error{ cond.error().location });
err = eat_token(token_t::RParen);
if (err.has_error()) return ast::statement_node_r(ast::error{ err.error().location });
auto body = parse_statement();
if (body.has_error()) return ast::statement_node_r(ast::error{ body.error().location });
return m_arena->allocate_shared<ast::while_statement_node>(location,
std::move(cond.value()),
std::move(body.value()));
}
case keyword_token::None:
case keyword_token::Func:
default: break;
}
}
case token_t::LBrace: {
auto body = parse_body();
if (body.has_error()) return ast::statement_node_r(ast::error{ body.error().location });
return m_arena->allocate_shared<ast::compound_statement_node>(location, std::move(body.value()));
}
default: break;
}
auto declaration = parse_declaration();
if (declaration.has_value()) return std::move(*declaration);
auto expression = parse_expression();
if (expression.has_value()) {
auto semi = eat_token(token_t::Semicolon);
if (semi.has_error()) return ast::statement_node_r(ast::error{ semi.error().location });
return std::move(*expression);
}
auto token = next_token();
return ast::statement_node_r(ast::error{ token->location });
}
ast::expression_node_r parser::parse_expression(std::uint32_t precedence) {
auto expr = parse_expression_unary(precedence);
if (expr.has_error()) {
return ast::expression_node_r(ast::error{ expr.error().location });
}
return parse_expression_rhs(std::move(expr.value()), precedence);
}
ast::expression_node_r parser::parse_expression_primary() {
const auto& tok = peek_token();
switch (tok->type) {
case token_t::Identifier: {
auto tok = next_token();
if (tok.has_error()) return ast::expression_node_r(ast::error{ tok.error().location });
return m_arena->allocate_shared<ast::var_read_expression_node>(tok->location, (*tok)->string);
}
case token_t::LParen: {
auto tok = next_token();
auto node = parse_expression();
auto err = eat_token(token_t::RParen);
if (err.has_error()) return ast::expression_node_r(ast::error{ err.error().location });
return node;
}
case token_t::String: {
auto tok = next_token();
if (tok.has_error()) return ast::expression_node_r(ast::error{ tok.error().location });
return m_arena->allocate_shared<ast::string_literal_node>(tok->location, (*tok)->string);
}
case token_t::Integer: {
auto tok = next_token();
if (tok.has_error()) return ast::expression_node_r(ast::error{ tok.error().location });
return m_arena->allocate_shared<ast::integer_literal_node>(tok->location, (*tok)->integer);
}
default: {
return ast::expression_node_r(ast::error{ tok->location });
}
}
}
struct unaryop_info {
ast::unaryop_expression_node_t type;
std::uint32_t precedence;
};
static inline std::optional<unaryop_info> get_unaryop_info(const token_r& token) {
static std::unordered_map<token_t, unaryop_info> s_prefixes = {
{ token_t::Plus, unaryop_info{ ast::unaryop_expression_node_t::Positive, 2 } },
{ token_t::Minus, unaryop_info{ ast::unaryop_expression_node_t::Negative, 2 } },
{ token_t::DPlus, unaryop_info{ ast::unaryop_expression_node_t::PrefixIncrement, 2 } },
{ token_t::DMinus, unaryop_info{ ast::unaryop_expression_node_t::PrefixDecrement, 2 } },
};
static std::unordered_map<keyword_token, unaryop_info> s_keywords = {
{ keyword_token::Pointerof, unaryop_info{ ast::unaryop_expression_node_t::Pointerof, 2 } },
{ keyword_token::Sizeof, unaryop_info{ ast::unaryop_expression_node_t::Sizeof, 2 } },
};
if (token->type == token_t::Keyword) {
auto it = s_keywords.find(token->value.keyword);
if (it == s_keywords.end()) return {};
return it->second;
}
auto it = s_prefixes.find(token->type);
if (it == s_prefixes.end()) return {};
return it->second;
}
ast::expression_node_r parser::parse_expression_unary(std::uint32_t precedence) {
std::shared_ptr<ast::unary_op_expression_node> result;
while (true) {
auto opt = get_unaryop_info(peek_token());
if (!opt.has_value()) break;
unaryop_info current = opt.value();
if (current.precedence >= precedence) break;
auto token = next_token();
ast::expression_node_p expression;
opt = get_unaryop_info(peek_token());
if (opt.has_value()) {
auto next = opt.value();
auto expr = parse_expression_unary(current.precedence + 1);
if (expr.has_error()) {
return ast::expression_node_r(ast::error{ expr.error().location });
}
expression = std::move(std::move(expr.value()));
}
result = m_arena->allocate_shared<ast::unary_op_expression_node>(token->location,
current.type,
std::move(expression));
}
if (result == nullptr) return parse_expression_primary();
if (result->get_node() == nullptr) {
auto expr = parse_expression_primary();
if (expr.has_error()) {
return ast::expression_node_r(ast::error{ expr.error().location });
}
result->set_node(std::move(std::move(expr.value())));
}
return result;
}
enum class associativity {
Left,
Right,
};
enum class rhsop_info_t {
Unaryop,
Binop,
Assignment,
FuncCall,
};
struct rhsop_info {
rhsop_info_t type;
std::uint32_t precedence;
associativity associativity;
union {
ast::unaryop_expression_node_t unary;
ast::binop_expression_node_t binary;
ast::binop_expression_node_t assignment;
};
bool has_rhs() const { return type == rhsop_info_t::Binop || type == rhsop_info_t::Assignment; }
static rhsop_info create(ast::unaryop_expression_node_t type, std::uint32_t precedence) {
rhsop_info info{};
info.type = rhsop_info_t::Unaryop;
info.precedence = precedence;
info.associativity = associativity::Left;
info.unary = type;
return info;
}
static rhsop_info create(ast::binop_expression_node_t type,
std::uint32_t precedence,
enum associativity associativity) {
rhsop_info info{};
info.type = rhsop_info_t::Binop;
info.precedence = precedence;
info.associativity = associativity;
info.binary = type;
return info;
}
static rhsop_info create(ast::binop_expression_node_t compound = ast::binop_expression_node_t::None) {
rhsop_info info{};
info.type = rhsop_info_t::Assignment;
info.precedence = 14;
info.associativity = associativity::Right;
info.assignment = compound;
return info;
}
static rhsop_info create_function_call() {
rhsop_info info{};
info.type = rhsop_info_t::FuncCall;
info.precedence = 1;
info.associativity = associativity::Left;
return info;
}
};
ast::expression_node_r parser::parse_expression_rhs(ast::expression_node_p&& init, std::uint32_t precedence) {
static std::unordered_map<token_t, rhsop_info> s_rhsops = {
{ token_t::Plus, rhsop_info::create(ast::binop_expression_node_t::Add, 5, associativity::Left) },
{ token_t::Minus, rhsop_info::create(ast::binop_expression_node_t::Sub, 5, associativity::Left) },
{ token_t::Star, rhsop_info::create(ast::binop_expression_node_t::Mul, 4, associativity::Left) },
{ token_t::Slash, rhsop_info::create(ast::binop_expression_node_t::Div, 4, associativity::Left) },
{ token_t::Percent, rhsop_info::create(ast::binop_expression_node_t::Mod, 5, associativity::Left) },
{ token_t::DPlus, rhsop_info::create(ast::unaryop_expression_node_t::PostfixIncrement, 1) },
{ token_t::DMinus, rhsop_info::create(ast::unaryop_expression_node_t::PostfixDecrement, 1) },
{ token_t::DMinus, rhsop_info::create(ast::unaryop_expression_node_t::PostfixDecrement, 1) },
{ token_t::Eq, rhsop_info::create() },
{ token_t::PlusEq, rhsop_info::create(ast::binop_expression_node_t::Add) },
{ token_t::MinusEq, rhsop_info::create(ast::binop_expression_node_t::Sub) },
{ token_t::StarEq, rhsop_info::create(ast::binop_expression_node_t::Mul) },
{ token_t::SlashEq, rhsop_info::create(ast::binop_expression_node_t::Div) },
{ token_t::PercentEq, rhsop_info::create(ast::binop_expression_node_t::Mod) },
{ token_t::DEq, rhsop_info::create(ast::binop_expression_node_t::Equal, 10, associativity::Left) },
{ token_t::NotEq, rhsop_info::create(ast::binop_expression_node_t::NotEqual, 10, associativity::Left) },
{ token_t::LessThan, rhsop_info::create(ast::binop_expression_node_t::LessThan, 9, associativity::Left) },
{ token_t::GreaterThan, rhsop_info::create(ast::binop_expression_node_t::GreaterThan, 9, associativity::Left) },
{ token_t::LessEq, rhsop_info::create(ast::binop_expression_node_t::LessEqual, 9, associativity::Left) },
{ token_t::GreaterEq, rhsop_info::create(ast::binop_expression_node_t::GreaterEqual, 9, associativity::Left) },
{ token_t::LParen, rhsop_info::create_function_call() },
};
ast::expression_node_p lhs = std::move(init);
while (peek_token().has_value()) {
auto it = s_rhsops.find(peek_token()->type);
if (it == s_rhsops.end()) return lhs;
rhsop_info current = it->second;
if (current.precedence >= precedence) return lhs;
auto opToken = next_token();
ast::expression_node_p rhs;
std::vector<ast::expression_node_p> params;
if (current.has_rhs()) {
auto expr = parse_expression_unary(current.precedence + 1); // unary prefix is always right-associative
if (expr.has_error()) {
return ast::expression_node_r(ast::error{ expr.error().location });
}
rhs = std::move(expr.value());
} else if (current.type == rhsop_info_t::FuncCall && peek_token().has_value()) {
if (peek_token()->type != token_t::RParen) {
while (true) {
auto expr = parse_expression_unary(16);
if (expr.has_error()) {
return ast::expression_node_r(ast::error{ expr.error().location });
}
params.emplace_back(std::move(expr.value()));
if (eat_token(token_t::Comma).has_error()) break;
}
}
auto enclosing = eat_token(token_t::RParen);
if (enclosing.has_error()) return ast::expression_node_r(ast::error{ enclosing.error().location });
}
auto nextIt = s_rhsops.find(peek_token()->type);
if (nextIt != s_rhsops.end()) {
rhsop_info next = nextIt->second;
auto expr = std::move(parse_expression_rhs(std::move(rhs),
current.precedence + static_cast<std::uint32_t>(current.associativity == associativity::Right)));
if (expr.has_error()) {
return ast::expression_node_r(ast::error{ expr.error().location });
}
if (current.type != rhsop_info_t::Unaryop) {
rhs = std::move(expr.value());
} else {
lhs = std::move(expr.value());
}
}
switch (current.type) {
case rhsop_info_t::Unaryop:
lhs = m_arena->allocate_shared<ast::unary_op_expression_node>(opToken->location,
current.unary,
std::move(lhs));
break;
case rhsop_info_t::Binop:
lhs = m_arena->allocate_shared<ast::binary_op_expression_node>(opToken->location,
current.binary,
std::move(lhs),
std::move(rhs));
break;
case rhsop_info_t::Assignment:
lhs = m_arena->allocate_shared<ast::var_assign_expression_node>(opToken->location,
current.assignment,
std::move(lhs),
std::move(rhs));
break;
case rhsop_info_t::FuncCall:
lhs = m_arena->allocate_shared<ast::function_call_expression_node>(opToken->location,
std::move(lhs),
std::move(params));
break;
}
}
return lhs;
}
ast::body_r parser::parse_body() {
ast::body body;
auto begin = eat_token(token_t::LBrace);
if (begin.has_error()) return ast::body_r(ast::error{ begin.error().location });
body.begin = begin->location;
while (!peek_token().has_error() && peek_token()->type != token_t::None && peek_token()->type != token_t::RBrace) {
body.statements.push_back(parse_statement());
}
auto end = eat_token(token_t::RBrace);
if (end.has_error()) return ast::body_r(ast::error{ end.error().location });
body.end = end->location;
return body;
}
token_r parser::next_token() {
if (!m_peekBuffer.empty()) {
auto token = std::move(m_peekBuffer.back());
m_peekBuffer.pop_back();
return token;
}
return m_lexer.next_token();
}
const token_r& parser::peek_token() {
if (m_peekBuffer.empty()) {
auto token = m_lexer.next_token();
return m_peekBuffer.emplace_back(std::move(token));
}
return m_peekBuffer.front();
}
token_r parser::eat_token(token_t type) {
if (const auto& token = peek_token(); token.has_error() || peek_token()->type != type) {
if (token.has_error()) return token;
if (token->type == token_t::None)
return token_r(token_error{ token->location, token_error_t::UnexpectedToken, ", expected " + type });
return token_r(
token_error{ token->location, token_error_t::UnexpectedToken, ""s + token->type + ", expected " + type });
}
return next_token();
}
} // namespace furc::front
-605
View File
@@ -1,605 +0,0 @@
#include "furc/front/post_process.hpp"
#include "furlang/ir/function.hpp"
#include "furlang/ir/instruction.hpp"
#include "furlang/ir/operand.hpp"
#include <algorithm>
#include <cstdint>
#include <limits>
#include <memory>
#include <queue>
#include <set>
#include <stack>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace furc::front {
using block_idx = furlang::ir::block_index;
using register_t = furlang::ir::register_t;
using register_op = furlang::ir::register_operand;
static constexpr block_idx INVALID_BLOCK = std::numeric_limits<block_idx>::max();
struct block_info {
std::size_t rpoIndex{ 0 };
std::vector<block_idx> predecessors;
std::vector<block_idx> successors;
block_idx idom = INVALID_BLOCK;
std::vector<block_idx> doms;
std::unordered_set<block_idx> domFrontiers;
};
struct register_info {
std::unordered_set<block_idx> defSites;
std::stack<register_t> renameStack;
std::uint32_t nextVersion{ 0 };
};
struct function_context {
explicit function_context(furlang::ir::function* function)
: function(function) {
build_cfg();
compute_rpo();
}
void build_cfg() {
for (block_idx idx = 0; idx < function->blocks().size(); ++idx) {
const auto& block = function->blocks()[idx];
for (const auto& instr : block->instructions()) {
for (const auto& operand : instr->sources()) {
if (operand->type() != furlang::ir::operand_t::Register) continue;
auto reg = operand->reg();
if (registers[reg].defSites.find(idx) != registers[reg].defSites.end()) continue;
globalRegisters.insert(reg);
}
}
for (const auto& instr : block->instructions()) {
if (!instr->has_destination() || instr->destination().type() != furlang::ir::operand_t::Register)
continue;
auto reg = instr->destination().reg();
registers[reg].defSites.insert(idx);
}
for (const auto& operand : block->exit()->sources()) {
if (operand->type() != furlang::ir::operand_t::Register) continue;
auto reg = operand->reg();
if (registers[reg].defSites.find(idx) != registers[reg].defSites.end()) continue;
globalRegisters.insert(reg);
}
const auto& exit = block->exit();
switch (exit->type()) {
case furlang::ir::instruction_t::Branch: {
const auto& br = dynamic_cast<const furlang::ir::branch_instruction&>(*exit);
blocks[br.block()].predecessors.push_back(idx);
blocks[idx].successors.push_back(br.block());
} break;
case furlang::ir::instruction_t::BranchCond: {
const auto& br = dynamic_cast<const furlang::ir::branch_cond_instruction&>(*exit);
blocks[br.if_block()].predecessors.push_back(idx);
blocks[br.else_block()].predecessors.push_back(idx);
blocks[idx].successors.push_back(br.if_block());
blocks[idx].successors.push_back(br.else_block());
} break;
default: break;
}
}
}
void compute_rpo() {
std::unordered_set<block_idx> visited;
auto dfs = [&](auto& self, block_idx block) -> void {
visited.insert(block);
for (auto succ : blocks[block].successors) {
if (visited.find(succ) != visited.end()) continue;
self(self, succ);
}
rpoOrder.push_back(block);
};
if (!function->blocks().empty()) dfs(dfs, 0);
std::reverse(rpoOrder.begin(), rpoOrder.end());
for (std::size_t i = 0; i < rpoOrder.size(); ++i) {
blocks[rpoOrder[i]].rpoIndex = i;
}
}
void compute_dominance() {
if (rpoOrder.empty()) return;
const block_idx entry = rpoOrder.front();
blocks[entry].idom = entry;
bool changed = true;
while (changed) {
changed = false;
for (block_idx idx : rpoOrder) {
if (idx == entry) continue;
block_idx newIdom = INVALID_BLOCK;
bool found = false;
for (auto pred : blocks[idx].predecessors) {
if (blocks[pred].idom == INVALID_BLOCK) continue;
if (found) {
newIdom = intersect(pred, newIdom);
} else {
newIdom = pred;
found = true;
}
}
if (blocks[idx].idom != newIdom) {
blocks[idx].idom = newIdom;
changed = true;
}
}
}
for (auto idx : rpoOrder) {
if (idx == entry) continue;
const block_idx parent = blocks[idx].idom;
if (parent != INVALID_BLOCK) blocks[parent].doms.push_back(idx);
}
for (auto idx : rpoOrder) {
if (blocks[idx].predecessors.size() < 2) continue;
for (auto cur : blocks[idx].predecessors) {
while (cur != blocks[idx].idom) {
blocks[cur].domFrontiers.insert(idx);
cur = blocks[cur].idom;
}
}
}
}
furlang::ir::function* function;
std::vector<block_idx> rpoOrder;
std::unordered_map<block_idx, block_info> blocks;
std::unordered_map<register_t, register_info> registers;
std::unordered_set<register_t> globalRegisters;
private:
block_idx intersect(block_idx block1, block_idx block2) {
while (block1 != block2) {
while (blocks[block1].rpoIndex > blocks[block2].rpoIndex)
block1 = blocks[block1].idom;
while (blocks[block2].rpoIndex > blocks[block1].rpoIndex)
block2 = blocks[block2].idom;
}
return block1;
}
};
static void ssa_stage_rename_block(function_context& ctx,
block_idx idx,
std::unordered_map<register_t, std::uint32_t>& regVers,
std::unordered_map<register_t, std::stack<std::uint32_t>>& regVerStacks) {
std::unordered_map<register_t, std::uint32_t> pushed;
const auto& block = ctx.function->blocks()[idx];
auto it = block->instructions().begin();
for (; it != block->instructions().end(); ++it) {
auto& instr = *it;
if (instr->type() != furlang::ir::instruction_t::Phi) break;
const register_t orig = instr->destination().reg();
const std::uint32_t newVer = regVers[orig]++;
instr->destination().reg().ver = newVer;
regVerStacks[orig].push(newVer);
++pushed[orig];
}
for (; it != block->instructions().end(); ++it) {
auto& instr = *it;
for (auto& operand : instr->sources()) {
if (operand->type() != furlang::ir::operand_t::Register) continue;
const register_t orig = operand->reg();
if (regVerStacks[orig].empty()) continue;
operand->reg().ver = regVerStacks[orig].top();
}
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
const register_t orig = instr->destination().reg();
const std::uint32_t newVer = regVers[orig]++;
instr->destination().reg().ver = newVer;
regVerStacks[orig].push(newVer);
++pushed[orig];
}
}
for (auto& operand : block->exit()->sources()) {
if (operand->type() != furlang::ir::operand_t::Register) continue;
const auto orig = operand->reg();
if (regVerStacks[orig].empty()) continue;
operand->reg().ver = regVerStacks[orig].top();
}
for (auto succIdx : ctx.blocks[idx].successors) {
const auto& succ = ctx.function->blocks()[succIdx];
for (auto& instr : succ->instructions()) {
if (instr->type() != furlang::ir::instruction_t::Phi) break;
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(*instr);
for (auto& pair : phi.labels()) {
if (pair.second != idx) continue;
auto orig = pair.first.reg();
if (auto it = regVerStacks.find(orig); it != regVerStacks.end())
pair.first.reg().ver = it->second.top();
}
}
}
for (const auto& child : ctx.blocks[idx].doms) {
ssa_stage_rename_block(ctx, child, regVers, regVerStacks);
}
for (const auto& [reg, count] : pushed) {
for (std::size_t i = 0; i < count; ++i)
regVerStacks[reg].pop();
}
}
static void ssa_stage(function_context& ctx) {
ctx.compute_dominance();
std::vector<block_idx> worklist;
for (const auto& [reg, info] : ctx.registers) {
if (info.defSites.size() < 2 || ctx.globalRegisters.find(reg) == ctx.globalRegisters.end()) continue;
worklist.clear();
worklist.insert(worklist.end(), info.defSites.begin(), info.defSites.end());
std::unordered_set<block_idx> added;
while (!worklist.empty()) {
const auto idx = worklist.back();
worklist.pop_back();
for (auto frontier : ctx.blocks[idx].domFrontiers) {
if (added.find(frontier) != added.end()) continue;
added.insert(frontier);
const auto& target = ctx.function->blocks()[frontier];
const auto& preds = ctx.blocks[frontier].predecessors;
auto instr = std::make_unique<furlang::ir::phi_instruction>(reg);
for (auto pred : preds) {
instr->labels().emplace_back(furlang::ir::operand::new_reg(reg), pred);
}
target->instructions().emplace(target->instructions().begin(), std::move(instr));
if (info.defSites.find(frontier) == info.defSites.end()) worklist.push_back(frontier);
}
}
}
std::unordered_map<register_t, std::uint32_t> regVers;
std::unordered_map<register_t, std::stack<std::uint32_t>> regVerStacks;
ssa_stage_rename_block(ctx, ctx.rpoOrder.front(), regVers, regVerStacks);
}
static void dessa_stage(function_context& ctx) {
for (block_idx idx = 0; idx < ctx.function->blocks().size(); ++idx) {
const auto& block = ctx.function->blocks()[idx];
auto& instrs = block->instructions();
for (auto it = instrs.begin(); it != instrs.end() && (*it)->type() == furlang::ir::instruction_t::Phi;
it = instrs.erase(it)) {
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(**it);
auto dstReg = phi.destination().reg();
for (auto& [srcOp, label] : phi.labels()) {
ctx.function->blocks()[label]->instructions().push_back(
std::make_unique<furlang::ir::assign_instruction>(furlang::ir::operand::new_reg(srcOp.reg()),
furlang::ir::operand::new_reg(dstReg)));
}
}
}
}
struct sccp_lattice {
enum lattice_t { // NOLINT
Top,
Constant,
Bottom,
} type = Top;
std::uint64_t constant = 0;
bool operator==(const sccp_lattice& other) const {
return type == other.type && (type != Constant || constant == other.constant);
}
bool operator!=(const sccp_lattice& other) const { return !this->operator==(other); }
};
sccp_lattice sccp_stage_get_lattice(std::unordered_map<register_op, sccp_lattice>& latticeValues,
const furlang::ir::operand& op) {
if (op.type() == furlang::ir::operand_t::Integer) {
sccp_lattice lat;
lat.type = sccp_lattice::Constant;
lat.constant = op.integer();
return lat;
}
if (op.type() == furlang::ir::operand_t::Register) {
auto reg = op.reg();
if (auto it = latticeValues.find(reg); it != latticeValues.end()) return it->second;
return { sccp_lattice::Top };
}
return { sccp_lattice::Bottom };
};
static void sccp_stage(function_context& ctx) {
using lattice = sccp_lattice;
std::unordered_map<register_op, lattice> latticeValues;
std::unordered_map<register_t, std::vector<furlang::ir::instruction*>> edges;
std::unordered_set<block_idx> execBlocks;
std::set<std::pair<block_idx, block_idx>> execEdges;
std::queue<std::pair<block_idx, block_idx>> cfgWorklist;
std::queue<furlang::ir::instruction*> ssaWorklist;
std::unordered_map<furlang::ir::instruction*, block_idx> blockMap;
for (block_idx idx = 0; idx < ctx.function->blocks().size(); ++idx) {
const auto& block = ctx.function->blocks()[idx];
auto& instrs = block->instructions();
for (auto it = instrs.begin(); it != instrs.end(); ++it) {
const auto& instr = *it;
blockMap[instr.get()] = idx;
for (const auto& op : instr->sources()) {
if (op->type() != furlang::ir::operand_t::Register) continue;
edges[op->reg()].push_back(instr.get());
}
}
blockMap[block->exit().get()] = idx;
for (const auto& op : block->exit()->sources()) {
if (op->type() != furlang::ir::operand_t::Register) continue;
edges[op->reg()].push_back(block->exit().get());
}
}
cfgWorklist.push({ 0, 0 });
while (!cfgWorklist.empty() || !ssaWorklist.empty()) {
if (!cfgWorklist.empty()) {
auto edge = cfgWorklist.front();
cfgWorklist.pop();
block_idx from = edge.first;
block_idx to = edge.second;
if (execEdges.count(edge) != 0) continue;
execEdges.insert(edge);
bool firstVisit = (execBlocks.find(to) == execBlocks.end());
execBlocks.insert(to);
const auto& block = ctx.function->blocks()[to];
if (firstVisit) {
for (auto& instr : block->instructions()) {
ssaWorklist.push(instr.get());
}
ssaWorklist.push(block->exit().get());
} else {
for (auto& instr : block->instructions()) {
if (instr->type() != furlang::ir::instruction_t::Phi) break;
ssaWorklist.push(instr.get());
}
}
}
if (!ssaWorklist.empty()) {
auto* instr = ssaWorklist.front();
ssaWorklist.pop();
block_idx blockIdx = blockMap[instr];
if (execBlocks.find(blockIdx) == execBlocks.end()) continue;
lattice newLat = { lattice::Top };
switch (instr->type()) {
case furlang::ir::instruction_t::Phi: {
auto& phi = dynamic_cast<furlang::ir::phi_instruction&>(*instr);
for (const auto& [op, label] : phi.labels()) {
if (execEdges.count({ label, blockIdx }) == 0) continue;
lattice opLat = sccp_stage_get_lattice(latticeValues, op);
if (opLat.type == lattice::Bottom) newLat.type = lattice::Bottom;
if (opLat.type == lattice::Constant) {
if (newLat.type == lattice::Top) {
newLat = opLat;
} else if (newLat.type == lattice::Constant && newLat.constant != opLat.constant) {
newLat.type = lattice::Bottom;
}
}
}
} break;
case furlang::ir::instruction_t::Assign: {
newLat = sccp_stage_get_lattice(latticeValues, *instr->sources().front());
} break;
case furlang::ir::instruction_t::Add:
case furlang::ir::instruction_t::Sub:
case furlang::ir::instruction_t::Mul:
case furlang::ir::instruction_t::Div:
case furlang::ir::instruction_t::Mod:
case furlang::ir::instruction_t::Eq:
case furlang::ir::instruction_t::NotEq:
case furlang::ir::instruction_t::LessThan:
case furlang::ir::instruction_t::GreaterThan:
case furlang::ir::instruction_t::LessEq:
case furlang::ir::instruction_t::GreaterEq: {
lattice lhs = sccp_stage_get_lattice(latticeValues, *instr->sources()[0]);
lattice rhs = sccp_stage_get_lattice(latticeValues, *instr->sources()[1]);
if (lhs.type == lattice::Bottom || rhs.type == lattice::Bottom) {
newLat.type = lattice::Bottom;
} else if (lhs.type == lattice::Constant && rhs.type == lattice::Constant) {
newLat.type = lattice::Constant;
switch (instr->type()) {
case furlang::ir::instruction_t::Add: newLat.constant = lhs.constant + rhs.constant; break;
case furlang::ir::instruction_t::Sub: newLat.constant = lhs.constant - rhs.constant; break;
case furlang::ir::instruction_t::Mul: newLat.constant = lhs.constant * rhs.constant; break;
case furlang::ir::instruction_t::Div: newLat.constant = lhs.constant / rhs.constant; break;
case furlang::ir::instruction_t::Mod: newLat.constant = lhs.constant % rhs.constant; break;
case furlang::ir::instruction_t::Eq:
newLat.constant = (lhs.constant == rhs.constant) ? 1 : 0;
break;
case furlang::ir::instruction_t::NotEq:
newLat.constant = (lhs.constant != rhs.constant) ? 1 : 0;
break;
case furlang::ir::instruction_t::LessThan:
newLat.constant = (lhs.constant < rhs.constant) ? 1 : 0;
break;
case furlang::ir::instruction_t::GreaterThan:
newLat.constant = (lhs.constant > rhs.constant) ? 1 : 0;
break;
case furlang::ir::instruction_t::LessEq:
newLat.constant = (lhs.constant <= rhs.constant) ? 1 : 0;
break;
case furlang::ir::instruction_t::GreaterEq:
newLat.constant = (lhs.constant >= rhs.constant) ? 1 : 0;
break;
default: throw std::runtime_error("unreachable");
}
}
} break;
default: break;
}
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
auto dst = instr->destination().reg();
if (!(latticeValues[dst] == newLat)) {
latticeValues[dst] = newLat;
for (auto* uInstr : edges[dst])
ssaWorklist.push(uInstr);
}
}
if (instr == ctx.function->blocks()[blockIdx]->exit().get()) {
auto* exit = ctx.function->blocks()[blockIdx]->exit().get();
if (exit->type() == furlang::ir::instruction_t::Branch) {
auto& br = dynamic_cast<furlang::ir::branch_instruction&>(*exit);
cfgWorklist.push({ blockIdx, br.block() });
} else if (exit->type() == furlang::ir::instruction_t::BranchCond) {
auto& br = dynamic_cast<furlang::ir::branch_cond_instruction&>(*exit);
lattice cond = sccp_stage_get_lattice(latticeValues, *exit->sources()[0]);
if (cond.type == lattice::Constant) {
if (cond.constant != 0)
cfgWorklist.push({ blockIdx, br.if_block() });
else
cfgWorklist.push({ blockIdx, br.else_block() });
} else {
cfgWorklist.push({ blockIdx, br.if_block() });
cfgWorklist.push({ blockIdx, br.else_block() });
}
}
}
}
}
for (block_idx i = 0; i < ctx.function->blocks().size(); ++i) {
if (execBlocks.find(i) == execBlocks.end()) {
ctx.function->blocks()[i]->instructions().clear();
continue;
}
const auto& block = ctx.function->blocks()[i];
for (auto& instr : block->instructions()) {
for (auto& op : instr->sources()) {
if (op->type() != furlang::ir::operand_t::Register) continue;
auto reg = op->reg();
if (latticeValues[reg].type != lattice::Constant) continue;
*op = furlang::ir::operand::new_integer(latticeValues[reg].constant);
}
}
auto* exit = block->exit().get();
if (exit->type() != furlang::ir::instruction_t::BranchCond) continue;
auto& br = dynamic_cast<furlang::ir::branch_cond_instruction&>(*exit);
lattice cond = sccp_stage_get_lattice(latticeValues, *exit->sources()[0]);
if (cond.type != lattice::Constant) continue;
block_idx target = (cond.constant != 0) ? br.if_block() : br.else_block();
block->exit() = std::make_unique<furlang::ir::branch_instruction>(target);
}
}
static void adce_stage(function_context& ctx) {
std::unordered_map<register_op, furlang::ir::instruction*> defMap;
std::unordered_set<furlang::ir::instruction*> alive;
std::queue<furlang::ir::instruction*> worklist;
for (block_idx blockIdx = 0; blockIdx < ctx.function->blocks().size(); ++blockIdx) {
const auto& block = ctx.function->blocks()[blockIdx];
for (auto& instr : block->instructions()) {
if (instr->has_destination() && instr->destination().type() == furlang::ir::operand_t::Register) {
defMap[instr->destination().reg()] = instr.get();
}
if (instr->type() == furlang::ir::instruction_t::Call) {
// TODO: Check if the function has side effects
if (alive.insert(instr.get()).second) worklist.push(instr.get());
}
}
auto* exit = block->exit().get();
alive.insert(exit);
worklist.push(exit);
}
while (!worklist.empty()) {
const auto* instr = worklist.front();
worklist.pop();
for (const auto& op : instr->sources()) {
if (op->type() != furlang::ir::operand_t::Register) continue;
auto src = op->reg();
if (defMap.find(src) == defMap.end()) continue;
auto* defInstr = defMap[src];
if (alive.insert(defInstr).second) {
worklist.push(defInstr);
}
}
}
for (block_idx blockIdx = 0; blockIdx < ctx.function->blocks().size(); ++blockIdx) {
const auto& block = ctx.function->blocks()[blockIdx];
auto& instrs = block->instructions();
auto it = instrs.begin();
while (it != instrs.end()) {
it = (alive.find(it->get()) != alive.end()) ? it + 1 : instrs.erase(it);
}
}
}
void post_process::process(furlang::ir::mod& mod) {
for (const auto& func : mod.functions()) {
if (!func || func->blocks().empty()) continue;
function_context ctx{ func.get() };
for (const auto& stage : m_stages) {
switch (stage) {
case Ssa: ssa_stage(ctx); break;
case Sccp: sccp_stage(ctx); break;
case Adce: adce_stage(ctx); break;
case DeSsa: dessa_stage(ctx); break;
}
}
}
}
} // namespace furc::front
+2 -84
View File
@@ -1,89 +1,7 @@
#ifndef LIBFURC
#include "furc/ast/program.hpp"
#include "furc/back/furvm.hpp"
#include "furc/front/ir_generator.hpp"
#include "furc/front/parser.hpp"
#include "furc/front/post_process.hpp"
#include "furlang/arena.hpp"
#include <fstream>
#include <furvm/furvm.hpp>
#include <iostream>
int main(void) {
try {
std::string programStr = R"(
private native func print(value: int32);
std::cout << "Farewell, stasiu!\n";
func main() -> int32 {
x = 0;
y = 10;
z = 1;
while (x < y) {
x = x + z;
}
print(sizeof x);
}
)";
furlang::arena arena{};
furc::front::parser parser(arena, "<TEMP>", programStr);
furc::front::ir_generator generator;
auto programResult = parser.parse();
if (programResult.has_error()) {
std::cerr << programResult.error() << '\n';
return 1;
}
const auto& program = *programResult;
program->accept(generator);
auto mod = std::move(generator.move_module());
furc::front::post_process postProcess;
postProcess.push_stage(furc::front::post_process::Ssa);
postProcess.push_stage(furc::front::post_process::Sccp);
postProcess.push_stage(furc::front::post_process::Adce);
postProcess.push_stage(furc::front::post_process::DeSsa);
postProcess.process(mod);
std::cout << "Generated IR:\n";
for (const auto& function : mod.functions()) {
std::cout << function->name() << ":\n";
furlang::ir::block_index blockIndex = 0;
for (const auto& block : function->blocks()) {
std::cout << " # block " << blockIndex++ << '\n';
for (const auto& instruction : block->instructions()) {
std::cout << " " << *instruction << '\n';
}
std::cout << " " << *block->exit() << '\n';
}
}
auto context = std::make_shared<furvm::context>();
auto furvmMod = context->emplace("main", furc::back::furvm_generator::generate(mod));
std::ofstream file("./a.fmod", std::ios::binary);
furvmMod->serialize(file);
file.close();
furvmMod->set_native_function("print",
[](furvm::executor& executor) { std::cout << executor.load_thing(0)->integer() << '\n'; });
furvm::executor_h executor = context->emplace_executor(context);
executor->push_frame(furvmMod, *furvmMod->function_at("main", furvm::function_sig{}));
std::cout << "--- Interpreting:\n";
while ((executor->flags() & furvm::executor_flags::Done) != furvm::executor_flags::Done) {
executor->step();
}
return 0;
} catch (...) {
std::cerr << "Caught an exception in main!\n";
return 1;
}
return 0;
}
#endif // LIBFURC