main.cpp 1.7 KB

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