main.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <fstream>
  2. #include <filesystem>
  3. #include "pocketpy/pocketpy.h"
  4. #ifndef __EMSCRIPTEN__
  5. int main(int argc, char** argv){
  6. pkpy::VM* vm = pkpy_new_vm();
  7. vm->bind_builtin_func<0>("input", [](pkpy::VM* vm, pkpy::ArgsView args){
  8. // pkpy::getline() has bugs for PIPE input on Windows
  9. return VAR(pkpy::getline());
  10. });
  11. // vm->bind(vm->builtins, "test_sum(a: int, b: int, *args, x=5)",
  12. // "Test function for summing up numbers.",
  13. // [](pkpy::VM* vm, pkpy::ArgsView args){
  14. // PK_ASSERT(args.size() == 4);
  15. // int sum = 0;
  16. // sum += pkpy::CAST(int, args[0]);
  17. // sum += pkpy::CAST(int, args[1]);
  18. // pkpy::Tuple& t = pkpy::CAST(pkpy::Tuple&, args[2]);
  19. // for(pkpy::PyObject* ob: t){
  20. // sum += pkpy::CAST(int, ob);
  21. // }
  22. // sum *= pkpy::CAST(int, args[3]);
  23. // return VAR(sum);
  24. // });
  25. if(argc == 1){
  26. pkpy::REPL* repl = pkpy_new_repl(vm);
  27. bool need_more_lines = false;
  28. while(true){
  29. vm->_stdout(vm, need_more_lines ? "... " : ">>> ");
  30. bool eof = false;
  31. std::string line = pkpy::getline(&eof);
  32. if(eof) break;
  33. need_more_lines = pkpy_repl_input(repl, line.c_str());
  34. }
  35. pkpy_delete_vm(vm);
  36. return 0;
  37. }
  38. if(argc == 2){
  39. std::string argv_1 = argv[1];
  40. if(argv_1 == "-h" || argv_1 == "--help") goto __HELP;
  41. std::filesystem::path filepath(argv[1]);
  42. filepath = std::filesystem::absolute(filepath);
  43. if(!std::filesystem::exists(filepath)){
  44. std::cerr << "File not found: " << argv_1 << std::endl;
  45. return 2;
  46. }
  47. std::ifstream file(filepath);
  48. if(!file.is_open()){
  49. std::cerr << "Failed to open file: " << argv_1 << std::endl;
  50. return 3;
  51. }
  52. std::string src((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  53. file.close();
  54. // set parent path as cwd
  55. std::filesystem::current_path(filepath.parent_path());
  56. pkpy::PyObject* ret = nullptr;
  57. ret = vm->exec(src.c_str(), filepath.filename().string(), pkpy::EXEC_MODE);
  58. pkpy_delete_vm(vm);
  59. return ret != nullptr ? 0 : 1;
  60. }
  61. __HELP:
  62. std::cout << "Usage: pocketpy [filename]" << std::endl;
  63. return 0;
  64. }
  65. #endif