main.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include <fstream>
  2. #include "pocketpy.h"
  3. //#define PK_DEBUG_TIME
  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. #ifdef PK_DEBUG_TIME
  13. std::cout << title << ": " << elapsed << " s" << std::endl;
  14. #endif
  15. }
  16. };
  17. #if defined(__EMSCRIPTEN__) || defined(__wasm__) || defined(__wasm32__) || defined(__wasm64__)
  18. // these code is for demo use, feel free to modify it
  19. REPL* _repl;
  20. extern "C" {
  21. __EXPORT
  22. void repl_start(){
  23. VM* vm = pkpy_new_vm(true);
  24. _repl = pkpy_new_repl(vm, false);
  25. }
  26. __EXPORT
  27. bool repl_input(const char* line){
  28. return pkpy_repl_input(_repl, line);
  29. }
  30. }
  31. #else
  32. int main(int argc, char** argv){
  33. if(argc == 1){
  34. VM* vm = pkpy_new_vm(true);
  35. REPL repl(vm);
  36. while(true){
  37. std::string line;
  38. std::getline(std::cin, line);
  39. repl.input(line);
  40. }
  41. return 0;
  42. }
  43. if(argc == 2){
  44. std::string filename = argv[1];
  45. if(filename == "-h" || filename == "--help") goto __HELP;
  46. std::ifstream file(filename);
  47. if(!file.is_open()){
  48. std::cerr << "File not found: " << filename << std::endl;
  49. return 1;
  50. }
  51. std::string src((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  52. ThreadedVM* vm = pkpy_new_tvm(true);
  53. _Code code;
  54. Timer("Compile time").run([&]{
  55. code = compile(vm, src.c_str(), filename);
  56. });
  57. if(code == nullptr) return 1;
  58. //std::cout << code->toString() << std::endl;
  59. Timer("Running time").run([=]{
  60. vm->exec(code);
  61. });
  62. // for(auto& kv : _strIntern)
  63. // std::cout << kv.first << ", ";
  64. // Timer("Running time").run([=]{
  65. // vm->startExec(code);
  66. // while(pkpy_tvm_get_state(vm) != THREAD_FINISHED){
  67. // if(pkpy_tvm_get_state(vm) == THREAD_SUSPENDED){
  68. // std::string line;
  69. // std::getline(std::cin, line);
  70. // pkpy_tvm_write_stdin(vm, line.c_str());
  71. // pkpy_tvm_resume(vm);
  72. // }
  73. // }
  74. // });
  75. return 0;
  76. }
  77. __HELP:
  78. std::cout << "Usage: pocketpy [filename]" << std::endl;
  79. return 0;
  80. }
  81. #endif