main.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. std::atomic<bool> _flag = false;
  12. MyVM(): VM(){
  13. this->_ceval_on_step = [](VM* _vm, Frame* frame, Bytecode bc){
  14. MyVM* vm = (MyVM*)_vm;
  15. if(vm->_flag){
  16. vm->_flag = false;
  17. vm->KeyboardInterrupt();
  18. }
  19. };
  20. }
  21. void KeyboardInterrupt(){
  22. _error("KeyboardInterrupt", "");
  23. }
  24. };
  25. MyVM* vm;
  26. void set_the_flag_handler(int _){
  27. vm->_flag = true;
  28. }
  29. int main(){
  30. signal(SIGINT, set_the_flag_handler);
  31. vm = new MyVM();
  32. REPL* repl = new REPL(vm);
  33. bool need_more_lines = false;
  34. while(true){
  35. std::cout << (need_more_lines ? "... " : ">>> ");
  36. std::string line;
  37. std::getline(std::cin, line);
  38. vm->_flag = false; // reset the flag before each input
  39. // here I use linux signal to interrupt the vm
  40. // you can run this line in a thread for more flexibility
  41. need_more_lines = repl->input(line);
  42. }
  43. delete vm;
  44. return 0;
  45. }