elna/cli/cl.cpp

81 lines
2.4 KiB
C++
Raw Normal View History

2024-03-07 09:15:11 +01:00
#include "elna/cli/cl.hpp"
#include "elna/backend/target.hpp"
2024-03-14 08:52:45 +01:00
#include "elna/source/semantic.hpp"
2024-03-07 09:15:11 +01:00
#include <cstddef>
#include <fstream>
2024-03-09 08:36:07 +01:00
#include <iostream>
2024-03-07 09:15:11 +01:00
namespace elna::cli
{
std::string read_source(const char *source)
2024-03-07 09:15:11 +01:00
{
constexpr std::size_t buffer_size = 4096;
2024-03-07 09:15:11 +01:00
std::ifstream input_stream{ source, std::ios::binary | std::ios::in };
std::string output;
if (input_stream.fail())
{
throw std::ios_base::failure("File does not exist");
}
while (true)
{
const std::size_t old_size = output.size();
output.resize(old_size + buffer_size);
input_stream.read(&output[old_size], buffer_size);
if (input_stream.eof())
{
output.resize(old_size + input_stream.gcount());
break;
}
else if (input_stream.fail())
{
throw std::ios_base::failure("Unable to complete reading the source file");
}
}
return output;
}
2024-03-07 09:15:11 +01:00
void print_error(const std::unique_ptr<source::error>& compile_error)
{
std::cerr << compile_error->path().string() << ":"
<< compile_error->line() << ':' << compile_error->column()
<< ": " << compile_error->what() << std::endl;
2024-03-07 09:15:11 +01:00
}
int compile(const std::filesystem::path& in_file, const std::filesystem::path& out_file)
{
std::string source_text;
try
{
source_text = read_source(in_file.c_str());
}
catch (std::ios_base::failure&)
2024-03-07 09:15:11 +01:00
{
return 3;
}
size_t tokensCount{ 0 };
auto lex_result = source::lex(source_text, in_file);
2024-03-07 09:15:11 +01:00
if (lex_result.has_errors())
{
print_errors(lex_result.errors().cbegin(), lex_result.errors().cend());
2024-03-07 09:15:11 +01:00
return 1;
}
2024-03-23 14:53:26 +01:00
source::parser parser{ std::move(lex_result.success()) };
auto ast = parser.parse();
2024-03-07 09:15:11 +01:00
if (ast == nullptr)
{
print_errors(parser.errors().cbegin(), parser.errors().cend());
2024-03-07 09:15:11 +01:00
return 2;
}
auto global_scope = std::make_shared<source::symbol_table>();
source::name_analysis_visitor(global_scope).visit(ast.get());
2024-03-23 14:53:26 +01:00
source::type_analysis_visitor().visit(ast.get());
source::allocator_visitor(global_scope).visit(ast.get());
riscv::riscv32_elf(ast.get(), global_scope, out_file);
2024-03-07 09:15:11 +01:00
return 0;
}
}