main.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <fstream>
  2. #include <filesystem>
  3. #include "pocketpy.h"
  4. #ifdef _WIN32
  5. #include <Windows.h>
  6. std::string getline(bool* eof=nullptr) {
  7. HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
  8. std::wstringstream wss;
  9. WCHAR buf;
  10. DWORD read;
  11. while (ReadConsoleW(hStdin, &buf, 1, &read, NULL) && buf != L'\n') {
  12. if(eof && buf == L'\x1A') *eof = true; // Ctrl+Z
  13. wss << buf;
  14. }
  15. std::wstring wideInput = wss.str();
  16. int length = WideCharToMultiByte(CP_UTF8, 0, wideInput.c_str(), (int)wideInput.length(), NULL, 0, NULL, NULL);
  17. std::string output;
  18. output.resize(length);
  19. WideCharToMultiByte(CP_UTF8, 0, wideInput.c_str(), (int)wideInput.length(), &output[0], length, NULL, NULL);
  20. return output;
  21. }
  22. #else
  23. std::string getline(bool* eof=nullptr){
  24. std::string line;
  25. if(!std::getline(std::cin, line)){
  26. if(eof) *eof = true;
  27. }
  28. return line;
  29. }
  30. #endif
  31. #ifndef __EMSCRIPTEN__
  32. int main(int argc, char** argv){
  33. pkpy::VM* vm = pkpy_new_vm(true);
  34. vm->bind_builtin_func<0>("input", [](pkpy::VM* vm, pkpy::Args& args){
  35. return VAR(getline());
  36. });
  37. if(argc == 1){
  38. pkpy::REPL* repl = pkpy_new_repl(vm);
  39. bool need_more_lines = false;
  40. while(true){
  41. (*vm->_stdout) << (need_more_lines ? "... " : ">>> ");
  42. bool eof = false;
  43. std::string line = getline(&eof);
  44. if(eof) break;
  45. need_more_lines = pkpy_repl_input(repl, line.c_str());
  46. }
  47. pkpy_delete(vm);
  48. return 0;
  49. }
  50. if(argc == 2){
  51. std::string argv_1 = argv[1];
  52. if(argv_1 == "-h" || argv_1 == "--help") goto __HELP;
  53. std::filesystem::path filepath(argv[1]);
  54. filepath = std::filesystem::absolute(filepath);
  55. if(!std::filesystem::exists(filepath)){
  56. std::cerr << "File not found: " << argv_1 << std::endl;
  57. return 2;
  58. }
  59. std::ifstream file(filepath);
  60. if(!file.is_open()){
  61. std::cerr << "Failed to open file: " << argv_1 << std::endl;
  62. return 3;
  63. }
  64. std::string src((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  65. file.close();
  66. // set parent path as cwd
  67. std::filesystem::current_path(filepath.parent_path());
  68. pkpy::PyObject* ret = nullptr;
  69. ret = vm->exec(src.c_str(), argv_1, pkpy::EXEC_MODE);
  70. pkpy_delete(vm);
  71. return ret != nullptr ? 0 : 1;
  72. }
  73. __HELP:
  74. std::cout << "Usage: pocketpy [filename]" << std::endl;
  75. return 0;
  76. }
  77. #endif