mp_flipper_compiler.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <string.h>
  2. #include "py/mperrno.h"
  3. #include "py/compile.h"
  4. #include "py/runtime.h"
  5. #include "py/persistentcode.h"
  6. #include "py/gc.h"
  7. #include "py/stackctrl.h"
  8. #include "shared/runtime/gchelper.h"
  9. #include "mp_flipper_runtime.h"
  10. #include "mp_flipper_compiler.h"
  11. #include "mp_flipper_halport.h"
  12. void mp_flipper_exec_str(const char* code) {
  13. nlr_buf_t nlr;
  14. if(nlr_push(&nlr) == 0) {
  15. // Compile, parse and execute the given string
  16. mp_lexer_t* lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, code, strlen(code), 0);
  17. mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(lex->source_name));
  18. mp_parse_tree_t parse_tree = mp_parse(lex, MP_PARSE_FILE_INPUT);
  19. mp_obj_t module_fun = mp_compile(&parse_tree, lex->source_name, true);
  20. mp_call_function_0(module_fun);
  21. nlr_pop();
  22. } else {
  23. // Uncaught exception: print it out.
  24. mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val);
  25. }
  26. }
  27. void mp_flipper_exec_py_file(const char* file_path) {
  28. nlr_buf_t nlr;
  29. if(nlr_push(&nlr) == 0) {
  30. do {
  31. // check if file exists
  32. if(mp_flipper_import_stat(file_path) == MP_FLIPPER_IMPORT_STAT_NO_EXIST) {
  33. mp_raise_OSError_with_filename(MP_ENOENT, file_path);
  34. break;
  35. }
  36. // Compile, parse and execute the given file
  37. mp_lexer_t* lex = mp_lexer_new_from_file(qstr_from_str(file_path));
  38. mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(lex->source_name));
  39. mp_parse_tree_t parse_tree = mp_parse(lex, MP_PARSE_FILE_INPUT);
  40. mp_obj_t module_fun = mp_compile(&parse_tree, lex->source_name, false);
  41. mp_call_function_0(module_fun);
  42. } while(false);
  43. nlr_pop();
  44. } else {
  45. // Uncaught exception: print it out.
  46. mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val);
  47. }
  48. }