main.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #include <string.h>
  5. #include "pocketpy.h"
  6. #ifdef _WIN32
  7. #define WIN32_LEAN_AND_MEAN
  8. #include <windows.h>
  9. #endif
  10. static char* read_file(const char* path) {
  11. FILE* file = fopen(path, "rb");
  12. if(file == NULL) {
  13. printf("Error: file not found\n");
  14. return NULL;
  15. }
  16. fseek(file, 0, SEEK_END);
  17. long size = ftell(file);
  18. fseek(file, 0, SEEK_SET);
  19. char* buffer = PK_MALLOC(size + 1);
  20. size = fread(buffer, 1, size, file);
  21. buffer[size] = 0;
  22. return buffer;
  23. }
  24. static char buf[2048];
  25. int main(int argc, char** argv) {
  26. #if _WIN32
  27. SetConsoleCP(CP_UTF8);
  28. SetConsoleOutputCP(CP_UTF8);
  29. #endif
  30. bool profile = false;
  31. const char* filename = NULL;
  32. for(int i = 1; i < argc; i++) {
  33. if(strcmp(argv[i], "--profile") == 0) {
  34. profile = true;
  35. continue;
  36. }
  37. if(filename == NULL) {
  38. filename = argv[i];
  39. continue;
  40. }
  41. printf("Usage: pocketpy [--profile] filename\n");
  42. }
  43. py_initialize();
  44. py_sys_setargv(argc, argv);
  45. if(profile) py_sys_settrace(py_LineProfiler_tracefunc, true);
  46. if(filename == NULL) {
  47. printf("pocketpy " PK_VERSION " (" __DATE__ ", " __TIME__ ") ");
  48. printf("[%d bit] on %s", (int)(sizeof(void*) * 8), PY_SYS_PLATFORM_STRING);
  49. #ifndef NDEBUG
  50. printf(" (DEBUG)");
  51. #endif
  52. printf("\n");
  53. printf("https://github.com/pocketpy/pocketpy\n");
  54. printf("Type \"exit()\" to exit.\n");
  55. while(true) {
  56. int size = py_replinput(buf, sizeof(buf));
  57. if(size == -1) { // Ctrl-D (i.e. EOF)
  58. printf("\n");
  59. break;
  60. }
  61. assert(size < sizeof(buf));
  62. if(size >= 0) {
  63. py_StackRef p0 = py_peek(0);
  64. if(!py_exec(buf, "<stdin>", SINGLE_MODE, NULL)) {
  65. py_printexc();
  66. py_clearexc(p0);
  67. }
  68. }
  69. }
  70. } else {
  71. char* source = read_file(filename);
  72. if(source) {
  73. if(!py_exec(source, filename, EXEC_MODE, NULL)) py_printexc();
  74. PK_FREE(source);
  75. }
  76. }
  77. int code = py_checkexc(false) ? 1 : 0;
  78. py_finalize();
  79. return code;
  80. }