| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- #include "common.h"
- #include "vm.h"
- static void repl();
- static void runFile(const char *);
- static char *readFile(const char *path);
- /*!
- * @brief 程序主入口
- * @param argc
- * @param argv
- * @return
- */
- int main(int argc, char *argv[]) {
- initVM();
- if (argc == 1) {
- repl();
- } else if (argc == 2) {
- runFile(argv[1]);
- } else {
- fprintf(stderr, "Usage: clox [path]\n");
- exit(64);
- }
- freeVM();
- return 0;
- }
- static void runFile(const char *path) {
- char *source = readFile(path);
- InterpretResult result = interpret(source);
- free(source);
- if (result == INTERPRET_COMPILE_ERROR) exit(65);
- if (result == INTERPRET_RUNTIME_ERROR) exit(70);
- }
- /// \brief 读取整个文件
- /// \param path 文件路径
- /// \return byteBuffer
- 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);
- }
- fseek(file, 0L, SEEK_END);
- size_t fileSize = ftell(file);
- rewind(file);
- char *buffer = (char *) malloc(fileSize + 1);
- if (buffer == NULL) {
- fprintf(stderr, "Not enough memory to read \"%s\".\n", path);
- exit(74);
- }
- size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);
- if (bytesRead < fileSize) {
- fprintf(stderr, "Could not read file \"%s\".\n", path);
- exit(74);
- }
- buffer[bytesRead] = '\0';
- fclose(file);
- return buffer;
- }
- static void repl() {
- char line[1024];
- for (;;) {
- printf("> ");
- if (!fgets(line, sizeof(line), stdin)) {
- printf("\n");
- break;
- }
- interpret(line);
- }
- }
|