main.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <fstream>
  2. #include <functional>
  3. #include "pocketpy.h"
  4. struct Timer{
  5. const char* title;
  6. Timer(const char* title) : title(title) {}
  7. void run(std::function<void()> f){
  8. auto start = std::chrono::high_resolution_clock::now();
  9. f();
  10. auto end = std::chrono::high_resolution_clock::now();
  11. double elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000000.0;
  12. std::cout << title << ": " << elapsed << " s" << std::endl;
  13. }
  14. };
  15. #ifndef __NO_MAIN
  16. int main(int argc, char** argv){
  17. VM* vm = pkpy_new_vm(true);
  18. pkpy_vm_bind__f_str__(vm, "builtins", "input", [](VM* vm){
  19. static std::string line;
  20. std::getline(std::cin, line);
  21. return line.c_str();
  22. });
  23. if(argc == 1){
  24. REPL repl(vm);
  25. int result = -1;
  26. while(true){
  27. (*vm->_stdout) << (result==0 ? "... " : ">>> ");
  28. std::string line;
  29. std::getline(std::cin, line);
  30. result = pkpy_repl_input(&repl, line.c_str());
  31. }
  32. pkpy_delete(vm);
  33. return 0;
  34. }
  35. if(argc == 2){
  36. std::string filename = argv[1];
  37. if(filename == "-h" || filename == "--help") goto __HELP;
  38. std::ifstream file(filename);
  39. if(!file.is_open()){
  40. std::cerr << "File not found: " << filename << std::endl;
  41. return 1;
  42. }
  43. std::string src((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  44. PyVarOrNull ret = nullptr;
  45. if(filename.find("1.py") != std::string::npos || filename.find("2.py") != std::string::npos){
  46. Timer("Running time").run([&]{
  47. ret = vm->exec(src.c_str(), filename, EXEC_MODE);
  48. });
  49. }else{
  50. ret = vm->exec(src.c_str(), filename, EXEC_MODE);
  51. }
  52. pkpy_delete(vm);
  53. return ret != nullptr ? 0 : 1;
  54. }
  55. __HELP:
  56. std::cout << "Usage: pocketpy [filename]" << std::endl;
  57. return 0;
  58. }
  59. #endif