elna/cli/cl.cpp

53 lines
1.5 KiB
C++
Raw Normal View History

2024-03-07 09:15:11 +01:00
#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;
}
}