main.cpp 2.1 KB

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