main.cpp 1.7 KB

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