diff options
Diffstat (limited to 'src/scripting.c')
-rw-r--r-- | src/scripting.c | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/src/scripting.c b/src/scripting.c new file mode 100644 index 0000000..af5d993 --- /dev/null +++ b/src/scripting.c @@ -0,0 +1,87 @@ +#include "scripting.h" + +void handle_tcc_error(void* opaque, const char* msg) +{ + TraceLog(LOG_ERROR, msg); +} + +void initScripting(SldjScripting* scripting) +{ + scripting->state = tcc_new(); + scripting->lineScanner = NULL; + scripting->fileBuf = NULL; + + if (!scripting->state) + { + TraceLog(LOG_ERROR, "Could not open tcc state"); + return; + } + + tcc_set_error_func(scripting->state, stderr, handle_tcc_error); +} + +void closeScripting(SldjScripting* scripting) +{ + tcc_delete(scripting->state); + + if (scripting->fileBuf != NULL) + { + free(scripting->fileBuf); + } +} + +void compileScript(SldjScripting* scripting, const char filePath[SLDJ_NAMEMAX]) +{ + // Get file size. + struct stat fileState; + + if (stat(filePath, &fileState) < 0) + { + TraceLog(LOG_ERROR, strerror(errno)); + return; + } + + scripting->fileSize = fileState.st_size; + + // Load file information into a buffer. + if (scripting->fileBuf == NULL) + { + scripting->fileBuf = (char*)malloc(scripting->fileSize); + } else { + scripting->fileBuf = (char*)realloc(scripting->fileBuf, scripting->fileSize); + } + + if (scripting->fileBuf == NULL) + { + TraceLog(LOG_ERROR, strerror(errno)); + return; + } + + FILE* file = fopen(filePath, "r"); + + if (file == NULL) + { + TraceLog(LOG_ERROR, strerror(errno)); + return; + } + + fread(scripting->fileBuf, scripting->fileSize, 1, file); + scripting->fileBuf[scripting->fileSize - 1] = '\0'; + fclose(file); + + // Compile shit now. + tcc_set_output_type(scripting->state, TCC_OUTPUT_MEMORY); + + if (tcc_compile_string(scripting->state, scripting->fileBuf) == -1) + { + return; + } + + if (tcc_relocate(scripting->state) < 0) + { + return; + } + + scripting->lineScanner = tcc_get_symbol(scripting->state, "lineScanner"); +} + |