main.c 2.3 KB

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