main.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // custom config to enable `vm->_ceval_on_step` and handle KeyboardInterrupt
  2. #define PK_USER_CONFIG_H
  3. #include "pocketpy.h"
  4. #include <thread>
  5. #include <atomic>
  6. #include <iostream>
  7. #include <signal.h>
  8. using namespace pkpy;
  9. class MyVM: public VM{
  10. public:
  11. // use atomic to protect the flag
  12. std::atomic<bool> _flag = false;
  13. MyVM(): VM(){
  14. this->_ceval_on_step = [](VM* _vm, Frame* frame, Bytecode bc){
  15. MyVM* vm = (MyVM*)_vm;
  16. if(vm->_flag){
  17. vm->_flag = false;
  18. vm->KeyboardInterrupt();
  19. }
  20. };
  21. }
  22. void KeyboardInterrupt(){
  23. _error("KeyboardInterrupt", "");
  24. }
  25. };
  26. MyVM* vm;
  27. void set_the_flag_handler(int _){
  28. vm->_flag = true;
  29. }
  30. int main(){
  31. signal(SIGINT, set_the_flag_handler);
  32. vm = new MyVM();
  33. REPL* repl = new REPL(vm);
  34. bool need_more_lines = false;
  35. while(true){
  36. std::cout << (need_more_lines ? "... " : ">>> ");
  37. std::string line;
  38. std::getline(std::cin, line);
  39. vm->_flag = false; // reset the flag before each input
  40. // here I use linux signal to interrupt the vm
  41. // you can run this line in a thread for more flexibility
  42. need_more_lines = repl->input(line);
  43. }
  44. delete repl;
  45. delete vm;
  46. return 0;
  47. }