main.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "common.h"
  2. #include "vm.h"
  3. static void repl();
  4. static void runFile(const char *);
  5. static char *readFile(const char *path);
  6. /*!
  7. * @brief 程序主入口
  8. * @param argc
  9. * @param argv
  10. * @return
  11. */
  12. int main(int argc, char *argv[]) {
  13. initVM();
  14. if (argc == 1) {
  15. repl();
  16. } else if (argc == 2) {
  17. runFile(argv[1]);
  18. } else {
  19. fprintf(stderr, "Usage: clox [path]\n");
  20. exit(64);
  21. }
  22. freeVM();
  23. return 0;
  24. }
  25. static void runFile(const char *path) {
  26. char *source = readFile(path);
  27. InterpretResult result = interpret(source);
  28. free(source);
  29. if (result == INTERPRET_COMPILE_ERROR) exit(65);
  30. if (result == INTERPRET_RUNTIME_ERROR) exit(70);
  31. }
  32. /// \brief 读取整个文件
  33. /// \param path 文件路径
  34. /// \return byteBuffer
  35. static char *readFile(const char *path) {
  36. FILE *file = fopen(path, "rb");
  37. if (file == NULL) {
  38. fprintf(stderr, "Could not open file \"%s\".\n", path);
  39. exit(74);
  40. }
  41. fseek(file, 0L, SEEK_END);
  42. size_t fileSize = ftell(file);
  43. rewind(file);
  44. char *buffer = (char *) malloc(fileSize + 1);
  45. if (buffer == NULL) {
  46. fprintf(stderr, "Not enough memory to read \"%s\".\n", path);
  47. exit(74);
  48. }
  49. size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);
  50. if (bytesRead < fileSize) {
  51. fprintf(stderr, "Could not read file \"%s\".\n", path);
  52. exit(74);
  53. }
  54. buffer[bytesRead] = '\0';
  55. fclose(file);
  56. return buffer;
  57. }
  58. static void repl() {
  59. char line[1024];
  60. for (;;) {
  61. printf("> ");
  62. if (!fgets(line, sizeof(line), stdin)) {
  63. printf("\n");
  64. break;
  65. }
  66. interpret(line);
  67. }
  68. }