main.cpp 2.2 KB

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