main.cpp 2.1 KB

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