main.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. // void LineProfiler__tracefunc(py_Frame* frame, enum py_TraceEvent event);
  25. static char buf[2048];
  26. int main(int argc, char** argv) {
  27. #if _WIN32
  28. SetConsoleCP(CP_UTF8);
  29. SetConsoleOutputCP(CP_UTF8);
  30. #endif
  31. bool profile = false;
  32. const char* filename = NULL;
  33. for(int i = 1; i < argc; i++) {
  34. if(strcmp(argv[i], "--profile") == 0) {
  35. profile = true;
  36. continue;
  37. }
  38. if(filename == NULL) {
  39. filename = argv[i];
  40. continue;
  41. }
  42. printf("Usage: pocketpy [--profile] filename\n");
  43. }
  44. py_initialize();
  45. py_sys_setargv(argc, argv);
  46. assert(!profile); // not implemented yet
  47. // if(profile) py_sys_settrace(LineProfiler__tracefunc, true);
  48. if(filename == NULL) {
  49. printf("pocketpy " PK_VERSION " (" __DATE__ ", " __TIME__ ") ");
  50. printf("[%d bit] on %s", (int)(sizeof(void*) * 8), PY_SYS_PLATFORM_STRING);
  51. #ifndef NDEBUG
  52. printf(" (DEBUG)");
  53. #endif
  54. printf("\n");
  55. printf("https://github.com/pocketpy/pocketpy\n");
  56. printf("Type \"exit()\" to exit.\n");
  57. while(true) {
  58. int size = py_replinput(buf, sizeof(buf));
  59. if(size == -1) { // Ctrl-D (i.e. EOF)
  60. printf("\n");
  61. break;
  62. }
  63. assert(size < sizeof(buf));
  64. if(size >= 0) {
  65. py_StackRef p0 = py_peek(0);
  66. if(!py_exec(buf, "<stdin>", SINGLE_MODE, NULL)) {
  67. py_printexc();
  68. py_clearexc(p0);
  69. }
  70. }
  71. }
  72. } else {
  73. char* source = read_file(filename);
  74. if(source) {
  75. if(!py_exec(source, filename, EXEC_MODE, NULL)) py_printexc();
  76. PK_FREE(source);
  77. }
  78. }
  79. int code = py_checkexc(false) ? 1 : 0;
  80. py_finalize();
  81. return code;
  82. }