105 lines
2.3 KiB
C
105 lines
2.3 KiB
C
#include <compiler/fzl_gen.h>
|
|
#include <compiler/fzl_writer.h>
|
|
#include <compiler/internals/writer.h>
|
|
#include <compiler/utils/fzl_const_pool.h>
|
|
#include <stddef.h>
|
|
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
char wrlast_err[256];
|
|
|
|
fzl_writer_t *fzl_mkwriter(const char *filepath)
|
|
{
|
|
if (strlen(filepath) < 1)
|
|
return nullptr;
|
|
|
|
fzl_writer_t *writer = malloc(sizeof(fzl_writer_t));
|
|
if (!writer)
|
|
return nullptr;
|
|
|
|
writer->filepath = filepath;
|
|
|
|
return writer;
|
|
}
|
|
|
|
int fzl_write(fzl_writer_t *writer, fzl_gen_t *gen)
|
|
{
|
|
if (!writer || !gen)
|
|
return -1;
|
|
|
|
FILE *fd = fopen(writer->filepath, "wb");
|
|
if (!fd)
|
|
{
|
|
snprintf(wrlast_err, sizeof(wrlast_err), "failed to open '%s' to write",
|
|
writer->filepath);
|
|
return -1;
|
|
}
|
|
|
|
constexpr char hdr[5] = {'F', 'Z', 'L', 0x0, 0x2};
|
|
fwrite(hdr, sizeof(char), 5, fd);
|
|
fwrite(&gen->consts->size, sizeof(uint16_t), 1, fd);
|
|
fwrite(&gen->extern_libs_count, sizeof(uint16_t), 1, fd);
|
|
fwrite(&gen->extern_types_count, sizeof(uint16_t), 1, fd);
|
|
fwrite(&gen->extern_fns_count, sizeof(uint16_t), 1, fd);
|
|
fwrite(&gen->ops_count, sizeof(size_t), 1, fd);
|
|
|
|
bool result = wr_consts(fd, gen->consts);
|
|
if (!result)
|
|
{
|
|
snprintf(wrlast_err, sizeof(wrlast_err), "failed to write constants table");
|
|
fclose(fd);
|
|
return -1;
|
|
}
|
|
|
|
result = wr_extern_libs(fd, gen->extern_libs, gen->extern_libs_count);
|
|
if (!result)
|
|
{
|
|
snprintf(wrlast_err, sizeof(wrlast_err),
|
|
"failed to write external lib names");
|
|
fclose(fd);
|
|
return -1;
|
|
}
|
|
|
|
result = wr_extern_types(fd, gen->extern_types, gen->extern_types_count);
|
|
if (!result)
|
|
{
|
|
snprintf(wrlast_err, sizeof(wrlast_err),
|
|
"failed to write extern lib types");
|
|
fclose(fd);
|
|
return -1;
|
|
}
|
|
|
|
result = wr_extern_fns(fd, gen->extern_fns, gen->extern_fns_count);
|
|
if (!result)
|
|
{
|
|
snprintf(wrlast_err, sizeof(wrlast_err),
|
|
"failed to write extern lib functions");
|
|
fclose(fd);
|
|
return -1;
|
|
}
|
|
|
|
result = wr_ops(fd, gen->ops, gen->ops_count);
|
|
if (!result)
|
|
{
|
|
snprintf(wrlast_err, sizeof(wrlast_err), "failed to write opcodes");
|
|
fclose(fd);
|
|
return -1;
|
|
}
|
|
|
|
fclose(fd);
|
|
|
|
return 0;
|
|
}
|
|
|
|
char *fzl_writer_geterror() { return wrlast_err; }
|
|
|
|
void fzl_freewriter(fzl_writer_t *writer)
|
|
{
|
|
if (!writer)
|
|
return;
|
|
|
|
free(writer);
|
|
}
|