blob: 33576e3f0e9febf2b1b6c1c5dff7079bf71ee18d [file] [log] [blame]
Damien George66028ab2014-01-03 14:03:48 +00001#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"
Damien George66028ab2014-01-03 14:03:48 +000014#include "obj.h"
Damien George1fb03172014-01-03 14:22:03 +000015#include "compile.h"
Damien George66028ab2014-01-03 14:03:48 +000016#include "runtime0.h"
17#include "runtime.h"
18#include "map.h"
19#include "builtin.h"
20
Damien George23005372014-01-13 19:39:01 +000021mp_obj_t mp_builtin___import__(int n_args, mp_obj_t *args) {
Damien George66028ab2014-01-03 14:03:48 +000022 /*
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
Damien Georgeeb7bfcb2014-01-04 15:57:35 +000061 mp_obj_t module_fun = mp_compile(pn, false);
62
63 if (module_fun == mp_const_none) {
Damien George66028ab2014-01-03 14:03:48 +000064 // TODO handle compile error correctly
65 rt_locals_set(old_locals);
66 rt_globals_set(old_globals);
67 return mp_const_none;
68 }
69
70 // complied successfully, execute it
Damien George66028ab2014-01-03 14:03:48 +000071 nlr_buf_t nlr;
72 if (nlr_push(&nlr) == 0) {
73 rt_call_function_0(module_fun);
74 nlr_pop();
75 } else {
76 // exception; restore context and re-raise same exception
77 rt_locals_set(old_locals);
78 rt_globals_set(old_globals);
79 nlr_jump(nlr.ret_val);
80 }
81 rt_locals_set(old_locals);
82 rt_globals_set(old_globals);
83
84 return module_obj;
85}