main.c 2.4 KB

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