main.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <iostream>
  2. #include <fstream>
  3. #include "pocketpy.h"
  4. //#define PK_DEBUG_TIME
  5. struct Timer{
  6. const char* title;
  7. Timer(const char* title) : title(title) {}
  8. void run(std::function<void()> f){
  9. auto start = std::chrono::high_resolution_clock::now();
  10. f();
  11. auto end = std::chrono::high_resolution_clock::now();
  12. double elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() / 1000000.0;
  13. #ifdef PK_DEBUG_TIME
  14. std::cout << title << ": " << elapsed << " s" << std::endl;
  15. #endif
  16. }
  17. };
  18. VM* newVM(){
  19. VM* vm = pkpy_new_vm([](const VM* vm, const char* str) {
  20. std::cout << str;
  21. std::cout.flush();
  22. }, [](const VM* vm, const char* str) {
  23. std::cerr << str;
  24. std::cerr.flush();
  25. });
  26. return vm;
  27. }
  28. #if defined(__EMSCRIPTEN__) || defined(__wasm__) || defined(__wasm32__) || defined(__wasm64__)
  29. // these code is for demo use, feel free to modify it
  30. REPL* _repl;
  31. extern "C" {
  32. __EXPORT
  33. void repl_start(){
  34. _repl = pkpy_new_repl(newVM(), false);
  35. }
  36. __EXPORT
  37. bool repl_input(const char* line){
  38. return pkpy_input_repl(_repl, line);
  39. }
  40. }
  41. #else
  42. int main(int argc, char** argv){
  43. if(argc == 1){
  44. REPL repl(newVM());
  45. while(true){
  46. std::string line;
  47. std::getline(std::cin, line);
  48. repl.input(line);
  49. }
  50. return 0;
  51. }
  52. if(argc == 2){
  53. std::string filename = argv[1];
  54. if(filename == "-h" || filename == "--help") goto __HELP;
  55. std::ifstream file(filename);
  56. if(!file.is_open()){
  57. std::cerr << "File not found: " << filename << std::endl;
  58. return 1;
  59. }
  60. std::string src((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  61. VM* vm = newVM();
  62. _Code code;
  63. Timer("Compile time").run([&]{
  64. code = compile(vm, src.c_str(), filename);
  65. });
  66. if(code == nullptr) return 1;
  67. //std::cout << code->toString() << std::endl;
  68. Timer("Running time").run([=]{
  69. vm->exec(code);
  70. });
  71. return 0;
  72. }
  73. __HELP:
  74. std::cout << "Usage: pocketpy [filename]" << std::endl;
  75. return 0;
  76. }
  77. #endif