| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- #include <fstream>
- #include <filesystem>
- #include "pocketpy.h"
- std::string f_input(){
- return pkpy::platform_getline();
- }
- #define ABS_PATH(x) std::filesystem::absolute(x).c_str()
- int main(int argc, char** argv){
- #if _WIN32
- SetConsoleOutputCP(CP_UTF8);
- void* p = LoadLibraryA(ABS_PATH("pocketpy.dll"));
- #elif __linux__
- void* p = dlopen(ABS_PATH("libpocketpy.so"), RTLD_NOW | RTLD_GLOBAL);
- #elif __APPLE__
- void* p = dlopen(ABS_PATH("libpocketpy.dylib"), RTLD_NOW | RTLD_GLOBAL);
- #endif
- if(p == nullptr){
- std::cerr << "unable to load dynamic library" << std::endl;
- return 1;
- }
- pkpy::VM* vm = pkpy_new_vm();
- pkpy::_bind(vm, vm->builtins, "input() -> str", &f_input);
- if(argc == 1){
- pkpy::REPL* repl = pkpy_new_repl(vm);
- bool need_more_lines = false;
- while(true){
- vm->_stdout(vm, need_more_lines ? "... " : ">>> ");
- bool eof = false;
- std::string line = pkpy::platform_getline(&eof);
- if(eof) break;
- need_more_lines = pkpy_repl_input(repl, line.c_str());
- }
- pkpy_delete_vm(vm);
- return 0;
- }
-
- if(argc == 2){
- std::string argv_1 = argv[1];
- if(argv_1 == "-h" || argv_1 == "--help") goto __HELP;
- std::filesystem::path filepath(argv[1]);
- filepath = std::filesystem::absolute(filepath);
- if(!std::filesystem::exists(filepath)){
- std::cerr << "File not found: " << argv_1 << std::endl;
- return 2;
- }
- std::ifstream file(filepath);
- if(!file.is_open()){
- std::cerr << "Failed to open file: " << argv_1 << std::endl;
- return 3;
- }
- std::string src((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
- file.close();
- // set parent path as cwd
- std::filesystem::current_path(filepath.parent_path());
- pkpy::PyObject* ret = nullptr;
- ret = vm->exec(src.c_str(), filepath.filename().string(), pkpy::EXEC_MODE);
- pkpy_delete_vm(vm);
- return ret != nullptr ? 0 : 1;
- }
- __HELP:
- std::cout << "Usage: pocketpy [filename]" << std::endl;
- return 0;
- }
|