#include #include "LLVMVisitor.h" LLVMVisitor::LLVMVisitor(const char* fileName) : outFile(std::ofstream(fileName)), reg() { if (!outFile.is_open()) throw std::runtime_error("Couldn't open file for writing!"); outFile << "define i32 @main() {\n"; } void LLVMVisitor::finalizeFile() { outFile << "ret i32 0\n}\n"; } std::string LLVMVisitor::Visit(const Integer& vint) { return std::to_string(vint.get_value()); } std::string LLVMVisitor::Visit(const Float& vfloat) { return std::to_string(vfloat.get_value()); } void f_add(std::string reg, std::string first, std::string second, std::ofstream& of) { of << reg << " = add i32 " << first << ", " << second << "\n"; } void f_sub(std::string reg, std::string first, std::string second, std::ofstream& of) { of << reg << " = sub i32 " << first << ", " << second << "\n"; } std::string LLVMVisitor::rightAssoc(BiFout f, const BuiltInFunction& bfun, unsigned i) { std::string leftArg = bfun.get_args()[i]->Visit(*this); std::string rightArg; if (bfun.get_args().size() - 2 == i) rightArg = bfun.get_args()[i+1]->Visit(*this); else rightArg = rightAssoc(f, bfun, i+1); std::string valRegister = *(reg++); f(valRegister, leftArg, rightArg, outFile); return valRegister; } std::string LLVMVisitor::Visit(const BuiltInFunction& bfun) { if (bfun.get_name() == "+") return rightAssoc(f_add, bfun); if (bfun.get_name() == "-") return rightAssoc(f_sub, bfun); return ""; }