|
| 1 | +#include "lightstorm/compiler/compiler.h" |
| 2 | +#include <cassert> |
| 3 | +#include <iostream> |
| 4 | +#include <mruby.h> |
| 5 | +#include <mruby/compile.h> |
| 6 | + |
| 7 | +using namespace lightstorm; |
| 8 | + |
| 9 | +extern "C" { |
| 10 | +void mrb_codedump_all(mrb_state *, struct RProc *); |
| 11 | +} |
| 12 | + |
| 13 | +void Compiler::compileSourceFile(const std::filesystem::path &file_path) { |
| 14 | + assert(exists(file_path) && "Cannot compile file"); |
| 15 | + mrb_state *mrb = mrb_open(); |
| 16 | + assert(mrb && "Out of memory?"); |
| 17 | + mrbc_context *mrbc = mrbc_context_new(mrb); |
| 18 | + assert(mrbc && "Out of memory?"); |
| 19 | + mrbc_filename(mrb, mrbc, file_path.c_str()); |
| 20 | + mrbc->capture_errors = TRUE; |
| 21 | + mrbc->no_optimize = TRUE; |
| 22 | + |
| 23 | + FILE *f = fopen(file_path.c_str(), "r"); |
| 24 | + assert(f && "No file?"); |
| 25 | + |
| 26 | + struct mrb_parser_state *p = mrb_parse_file(mrb, f, mrbc); |
| 27 | + |
| 28 | + if (!p) { |
| 29 | + /* only occur when memory ran out */ |
| 30 | + std::cerr << "Failed to create parser state (out of memory)\n"; |
| 31 | + fclose(f); |
| 32 | + mrbc_context_free(mrb, mrbc); |
| 33 | + mrb_close(mrb); |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + if (0 < p->nerr) { |
| 38 | + /* parse error */ |
| 39 | + std::cerr << file_path.c_str() << ":" << p->error_buffer[0].lineno << ": " |
| 40 | + << p->error_buffer[0].message << "\n"; |
| 41 | + fclose(f); |
| 42 | + mrb_parser_free(p); |
| 43 | + mrbc_context_free(mrb, mrbc); |
| 44 | + mrb_close(mrb); |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + struct RProc *proc = mrb_generate_code(mrb, p); |
| 49 | + mrb_codedump_all(mrb, proc); |
| 50 | + |
| 51 | + fclose(f); |
| 52 | + mrb_parser_free(p); |
| 53 | + mrbc_context_free(mrb, mrbc); |
| 54 | + mrb_close(mrb); |
| 55 | +} |
0 commit comments