Cosmo/src/main.c

109 lines
2.6 KiB
C
Raw Normal View History

2020-10-28 05:16:30 +00:00
#include "cosmo.h"
#include "cchunk.h"
#include "cdebug.h"
#include "cvm.h"
#include "cparse.h"
#include "cbaselib.h"
#include "cmem.h"
static bool _ACTIVE = false;
2020-10-28 23:38:50 +00:00
CValue cosmoB_quitRepl(CState *state, int nargs, CValue *args) {
2020-10-28 23:38:50 +00:00
_ACTIVE = false;
return cosmoV_newNil(); // we don't return anything
2020-10-28 23:38:50 +00:00
}
static void interpret(CState *state, const char* script) {
2020-10-28 05:16:30 +00:00
// cosmoP_compileString pushes the result onto the stack (NIL or COBJ_FUNCTION)
CObjFunction* func = cosmoP_compileString(state, script);
if (func != NULL) {
disasmChunk(&func->chunk, "_main", 0);
COSMOVMRESULT res = cosmoV_call(state, 0); // 0 args being passed
2020-10-28 05:16:30 +00:00
if (res == COSMOVM_RUNTIME_ERR)
state->panic = false; // so our repl isn't broken
2020-10-28 05:16:30 +00:00
}
}
static void repl() {
char line[1024];
2020-10-28 23:38:50 +00:00
_ACTIVE = true;
2020-10-28 05:16:30 +00:00
2020-10-28 23:38:50 +00:00
CState *state = cosmoV_newState();
cosmoB_loadlibrary(state);
// TODO: there's gotta be a better way to do this
cosmoV_register(state, "quit", cosmoV_newObj(cosmoO_newCFunction(state, cosmoB_quitRepl)));
while (_ACTIVE) {
2020-10-28 05:16:30 +00:00
printf("> ");
if (!fgets(line, sizeof(line), stdin)) { // better than gets()
printf("\n> ");
break;
}
2020-10-28 23:38:50 +00:00
interpret(state, line);
2020-10-28 05:16:30 +00:00
}
2020-10-28 23:38:50 +00:00
cosmoV_freeState(state);
2020-10-28 05:16:30 +00:00
}
static char *readFile(const char* path) {
FILE* file = fopen(path, "rb");
if (file == NULL) {
fprintf(stderr, "Could not open file \"%s\".\n", path);
exit(74);
}
// first, we need to know how big our file is
fseek(file, 0L, SEEK_END);
size_t fileSize = ftell(file);
rewind(file);
char *buffer = (char*)malloc(fileSize + 1); // make room for the null byte
if (buffer == NULL) {
fprintf(stderr, "failed to allocate!");
exit(1);
}
size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);
if (bytesRead < fileSize) {
printf("failed to read file \"%s\"!\n", path);
exit(74);
}
buffer[bytesRead] = '\0'; // place our null terminator
// close the file handler and return the script buffer
fclose(file);
return buffer;
}
static void runFile(const char* fileName) {
char* script = readFile(fileName);
2020-10-28 23:38:50 +00:00
CState *state = cosmoV_newState();
cosmoB_loadlibrary(state);
2020-10-28 05:16:30 +00:00
2020-10-28 23:38:50 +00:00
interpret(state, script);
cosmoV_freeState(state);
2020-10-28 05:16:30 +00:00
free(script);
}
int main(int argc, const char *argv[]) {
if (argc == 1) {
repl();
} else if (argc >= 2) { // they passed a file (or more lol)
for (int i = 1; i < argc; i++) {
runFile(argv[i]);
}
}
return 0;
}