main.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #if _WIN32
  9. SetConsoleOutputCP(CP_UTF8);
  10. // implicitly load pocketpy.dll in current directory
  11. #elif __linux__
  12. dlopen("libpocketpy.so", RTLD_NOW | RTLD_GLOBAL);
  13. #elif __APPLE__
  14. dlopen("libpocketpy.dylib", RTLD_NOW | RTLD_GLOBAL);
  15. #endif
  16. pkpy::VM* vm = pkpy_new_vm();
  17. pkpy::_bind(vm, vm->builtins, "input() -> str", &f_input);
  18. if(argc == 1){
  19. pkpy::REPL* repl = pkpy_new_repl(vm);
  20. bool need_more_lines = false;
  21. while(true){
  22. vm->_stdout(vm, need_more_lines ? "... " : ">>> ");
  23. bool eof = false;
  24. std::string line = pkpy::platform_getline(&eof);
  25. if(eof) break;
  26. need_more_lines = pkpy_repl_input(repl, line.c_str());
  27. }
  28. pkpy_delete_vm(vm);
  29. return 0;
  30. }
  31. if(argc == 2){
  32. std::string argv_1 = argv[1];
  33. if(argv_1 == "-h" || argv_1 == "--help") goto __HELP;
  34. std::filesystem::path filepath(argv[1]);
  35. filepath = std::filesystem::absolute(filepath);
  36. if(!std::filesystem::exists(filepath)){
  37. std::cerr << "File not found: " << argv_1 << std::endl;
  38. return 2;
  39. }
  40. std::ifstream file(filepath);
  41. if(!file.is_open()){
  42. std::cerr << "Failed to open file: " << argv_1 << std::endl;
  43. return 3;
  44. }
  45. std::string src((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  46. file.close();
  47. // set parent path as cwd
  48. std::filesystem::current_path(filepath.parent_path());
  49. pkpy::PyObject* ret = nullptr;
  50. ret = vm->exec(src.c_str(), filepath.filename().string(), pkpy::EXEC_MODE);
  51. pkpy_delete_vm(vm);
  52. return ret != nullptr ? 0 : 1;
  53. }
  54. __HELP:
  55. std::cout << "Usage: pocketpy [filename]" << std::endl;
  56. return 0;
  57. }