main.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include <fstream>
  2. #include <filesystem>
  3. #include "pocketpy.h"
  4. #ifndef __EMSCRIPTEN__
  5. int main(int argc, char** argv){
  6. pkpy::VM* vm = pkpy_new_vm();
  7. pkpy::PyObject* input_f = vm->bind_builtin_func<0>("input", [](pkpy::VM* vm, pkpy::ArgsView args){
  8. // pkpy::getline() has bugs for PIPE input on Windows
  9. return VAR(pkpy::getline());
  10. });
  11. vm->_modules["sys"]->attr("stdin")->attr().set("readline", input_f);
  12. if(argc == 1){
  13. pkpy::REPL* repl = pkpy_new_repl(vm);
  14. bool need_more_lines = false;
  15. while(true){
  16. vm->_stdout(vm, need_more_lines ? "... " : ">>> ");
  17. bool eof = false;
  18. std::string line = pkpy::getline(&eof);
  19. if(eof) break;
  20. need_more_lines = pkpy_repl_input(repl, line.c_str());
  21. }
  22. pkpy_delete_vm(vm);
  23. return 0;
  24. }
  25. if(argc == 2){
  26. std::string argv_1 = argv[1];
  27. if(argv_1 == "-h" || argv_1 == "--help") goto __HELP;
  28. std::filesystem::path filepath(argv[1]);
  29. filepath = std::filesystem::absolute(filepath);
  30. if(!std::filesystem::exists(filepath)){
  31. std::cerr << "File not found: " << argv_1 << std::endl;
  32. return 2;
  33. }
  34. std::ifstream file(filepath);
  35. if(!file.is_open()){
  36. std::cerr << "Failed to open file: " << argv_1 << std::endl;
  37. return 3;
  38. }
  39. std::string src((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  40. file.close();
  41. // set parent path as cwd
  42. std::filesystem::current_path(filepath.parent_path());
  43. pkpy::PyObject* ret = nullptr;
  44. ret = vm->exec(src.c_str(), filepath.filename().string(), pkpy::EXEC_MODE);
  45. pkpy_delete_vm(vm);
  46. return ret != nullptr ? 0 : 1;
  47. }
  48. __HELP:
  49. std::cout << "Usage: pocketpy [filename]" << std::endl;
  50. return 0;
  51. }
  52. #endif