Damien George | 66028ab | 2014-01-03 14:03:48 +0000 | [diff] [blame^] | 1 | #include <stdint.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <stdio.h> |
| 4 | #include <stdarg.h> |
| 5 | #include <string.h> |
| 6 | #include <assert.h> |
| 7 | |
| 8 | #include "nlr.h" |
| 9 | #include "misc.h" |
| 10 | #include "mpconfig.h" |
| 11 | #include "lexer.h" |
| 12 | #include "lexerunix.h" |
| 13 | #include "parse.h" |
| 14 | #include "compile.h" |
| 15 | #include "obj.h" |
| 16 | #include "runtime0.h" |
| 17 | #include "runtime.h" |
| 18 | #include "map.h" |
| 19 | #include "builtin.h" |
| 20 | |
| 21 | mp_obj_t mp_builtin___import__(int n, mp_obj_t *args) { |
| 22 | /* |
| 23 | printf("import:\n"); |
| 24 | for (int i = 0; i < n; i++) { |
| 25 | printf(" "); |
| 26 | mp_obj_print(args[i]); |
| 27 | printf("\n"); |
| 28 | } |
| 29 | */ |
| 30 | |
| 31 | // find the file to import |
| 32 | qstr mod_name = mp_obj_get_qstr(args[0]); |
| 33 | mp_lexer_t *lex = mp_import_open_file(mod_name); |
| 34 | if (lex == NULL) { |
| 35 | // TODO handle lexer error correctly |
| 36 | return mp_const_none; |
| 37 | } |
| 38 | |
| 39 | // create a new module object |
| 40 | mp_obj_t module_obj = mp_obj_new_module(mp_obj_get_qstr(args[0])); |
| 41 | |
| 42 | // save the old context |
| 43 | mp_map_t *old_locals = rt_locals_get(); |
| 44 | mp_map_t *old_globals = rt_globals_get(); |
| 45 | |
| 46 | // set the new context |
| 47 | rt_locals_set(mp_obj_module_get_globals(module_obj)); |
| 48 | rt_globals_set(mp_obj_module_get_globals(module_obj)); |
| 49 | |
| 50 | // parse the imported script |
| 51 | mp_parse_node_t pn = mp_parse(lex, MP_PARSE_FILE_INPUT); |
| 52 | mp_lexer_free(lex); |
| 53 | |
| 54 | if (pn == MP_PARSE_NODE_NULL) { |
| 55 | // TODO handle parse error correctly |
| 56 | rt_locals_set(old_locals); |
| 57 | rt_globals_set(old_globals); |
| 58 | return mp_const_none; |
| 59 | } |
| 60 | |
| 61 | if (!mp_compile(pn, false)) { |
| 62 | // TODO handle compile error correctly |
| 63 | rt_locals_set(old_locals); |
| 64 | rt_globals_set(old_globals); |
| 65 | return mp_const_none; |
| 66 | } |
| 67 | |
| 68 | // complied successfully, execute it |
| 69 | mp_obj_t module_fun = rt_make_function_from_id(1); // TODO we should return from mp_compile the unique_code_id for the module |
| 70 | nlr_buf_t nlr; |
| 71 | if (nlr_push(&nlr) == 0) { |
| 72 | rt_call_function_0(module_fun); |
| 73 | nlr_pop(); |
| 74 | } else { |
| 75 | // exception; restore context and re-raise same exception |
| 76 | rt_locals_set(old_locals); |
| 77 | rt_globals_set(old_globals); |
| 78 | nlr_jump(nlr.ret_val); |
| 79 | } |
| 80 | rt_locals_set(old_locals); |
| 81 | rt_globals_set(old_globals); |
| 82 | |
| 83 | return module_obj; |
| 84 | } |