Split code generation from the ui

This commit is contained in:
2024-03-07 09:15:11 +01:00
parent 4dbf3ddb47
commit fe805ca893
26 changed files with 279 additions and 336 deletions

52
cli/cl.cpp Normal file
View File

@ -0,0 +1,52 @@
#include "elna/cli/cl.hpp"
#include "elna/backend/target.hpp"
#include <cstddef>
#include <fstream>
#include <sstream>
namespace elna::cli
{
char *readSource(const char *source)
{
const std::size_t bufferSize = 255;
std::ifstream input_stream{ source };
std::stringstream buffer;
buffer << input_stream.rdbuf();
input_stream.close();
std::string contents = buffer.str();
char *result = reinterpret_cast<char *>(malloc(contents.size() + 1));
std::copy(std::cbegin(contents), std::cend(contents), result);
result[contents.size()] = '\0';
return result;
}
int compile(const std::filesystem::path& in_file, const std::filesystem::path& out_file)
{
auto sourceText = readSource(in_file.c_str());
if (sourceText == nullptr)
{
return 3;
}
size_t tokensCount{ 0 };
auto lex_result = source::lex(sourceText);
free(sourceText);
if (lex_result.has_errors())
{
for (const auto& compile_error : lex_result.errors())
{
printf("%lu:%lu: %s\n", compile_error.line(), compile_error.column(), compile_error.what());
}
return 1;
}
auto ast = source::parser(lex_result.success()).parse();
if (ast == nullptr)
{
return 2;
}
backend::riscv32_elf(ast.get(), out_file);
return 0;
}
}

47
cli/main.cpp Normal file
View File

@ -0,0 +1,47 @@
#include "elna/cli/cl.hpp"
#include <filesystem>
#include <iostream>
#include <boost/program_options.hpp>
int main(int argc, char **argv)
{
boost::program_options::options_description visible{ "Allowed options" };
boost::program_options::options_description description;
boost::program_options::positional_options_description positional;
boost::program_options::variables_map variables_map;
visible.add_options()
("help", "Print this help message")
("output,o", boost::program_options::value<std::filesystem::path>(), "Output object file")
;
description.add_options()
("input", boost::program_options::value<std::filesystem::path>()->required())
;
description.add(visible);
positional.add("input", 1);
auto parsed = boost::program_options::command_line_parser(argc, argv)
.options(description).positional(positional)
.run();
boost::program_options::store(parsed, variables_map);
boost::program_options::notify(variables_map);
if (variables_map.count("help"))
{
std::cout << description << std::endl;
return 0;
}
const auto in_file = variables_map["input"].as<std::filesystem::path>();
std::filesystem::path out_file;
if (variables_map.count("output"))
{
out_file = variables_map["output"].as<std::filesystem::path>();
}
else
{
out_file = in_file.filename().replace_extension(".o");
}
return elna::cli::compile(in_file, out_file);
}