blob: 0e3f160a73485f5c3d32f71664cd59b4e89ea456 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovskyda9f0922014-05-13 08:44:45 +03007 * Copyright (c) 2014 Paul Sokolovsky
Damien George04b91472014-05-03 23:27:38 +01008 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 */
27
Damien George66028ab2014-01-03 14:03:48 +000028#include <stdio.h>
Damien George66028ab2014-01-03 14:03:48 +000029#include <string.h>
30#include <assert.h>
31
Damien George51dfcb42015-01-01 20:27:54 +000032#include "py/nlr.h"
33#include "py/compile.h"
34#include "py/objmodule.h"
Damien George6810f2c2016-11-16 11:55:41 +110035#include "py/persistentcode.h"
Damien George51dfcb42015-01-01 20:27:54 +000036#include "py/runtime.h"
37#include "py/builtin.h"
Paul Sokolovsky640e0b22015-01-20 11:52:12 +020038#include "py/frozenmod.h"
Damien George66028ab2014-01-03 14:03:48 +000039
Paul Sokolovskye0813292014-04-11 23:08:29 +030040#if 0 // print debugging info
41#define DEBUG_PRINT (1)
42#define DEBUG_printf DEBUG_printf
43#else // don't print debugging info
Damien George7860c2a2014-11-05 21:16:41 +000044#define DEBUG_PRINT (0)
Paul Sokolovskye0813292014-04-11 23:08:29 +030045#define DEBUG_printf(...) (void)0
46#endif
47
Damien Georgee09ffa12014-02-05 23:57:48 +000048#define PATH_SEP_CHAR '/'
49
Damien George78d702c2014-12-09 16:19:48 +000050#if MICROPY_MODULE_WEAK_LINKS
Damien Georgecbf76742015-11-27 13:38:15 +000051STATIC const mp_rom_map_elem_t mp_builtin_module_weak_links_table[] = {
Damien George78d702c2014-12-09 16:19:48 +000052 MICROPY_PORT_BUILTIN_MODULE_WEAK_LINKS
53};
54
55STATIC MP_DEFINE_CONST_MAP(mp_builtin_module_weak_links_map, mp_builtin_module_weak_links_table);
56#endif
57
Paul Sokolovskye5a37592014-10-25 21:04:13 +030058bool mp_obj_is_package(mp_obj_t module) {
59 mp_obj_t dest[2];
60 mp_load_method_maybe(module, MP_QSTR___path__, dest);
61 return dest[0] != MP_OBJ_NULL;
62}
63
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030064// Stat either frozen or normal module by a given path
65// (whatever is available, if at all).
66STATIC mp_import_stat_t mp_import_stat_any(const char *path) {
Damien George274952a2016-05-23 12:42:23 +010067 #if MICROPY_MODULE_FROZEN
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030068 mp_import_stat_t st = mp_frozen_stat(path);
69 if (st != MP_IMPORT_STAT_NO_EXIST) {
70 return st;
71 }
Paul Sokolovsky8a2970e2016-05-21 22:23:08 +030072 #endif
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030073 return mp_import_stat(path);
74}
75
Damien Georged9047d32016-12-13 15:09:48 +110076STATIC mp_import_stat_t stat_file_py_or_mpy(vstr_t *path) {
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030077 mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
Damien Georgee09ffa12014-02-05 23:57:48 +000078 if (stat == MP_IMPORT_STAT_FILE) {
79 return stat;
Paul Sokolovskyd720ab52014-01-20 00:03:34 +020080 }
Damien George432e8272015-11-02 21:57:42 +000081
82 #if MICROPY_PERSISTENT_CODE_LOAD
83 vstr_ins_byte(path, path->len - 2, 'm');
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030084 stat = mp_import_stat_any(vstr_null_terminated_str(path));
Damien George432e8272015-11-02 21:57:42 +000085 if (stat == MP_IMPORT_STAT_FILE) {
86 return stat;
87 }
88 #endif
89
Damien Georgee09ffa12014-02-05 23:57:48 +000090 return MP_IMPORT_STAT_NO_EXIST;
91}
Paul Sokolovskyd720ab52014-01-20 00:03:34 +020092
Damien Georged9047d32016-12-13 15:09:48 +110093STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) {
94 mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
95 DEBUG_printf("stat %s: %d\n", vstr_str(path), stat);
96 if (stat == MP_IMPORT_STAT_DIR) {
97 return stat;
98 }
99
100 // not a directory, add .py and try as a file
101 vstr_add_str(path, ".py");
102 return stat_file_py_or_mpy(path);
103}
104
Damien George8a0801a2014-06-11 19:55:46 +0100105STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *dest) {
Damien Georgeee3fd462014-05-24 23:03:12 +0100106#if MICROPY_PY_SYS
Sven Wegener238ab502014-11-05 21:02:33 +0100107 // extract the list of paths
108 mp_uint_t path_num;
109 mp_obj_t *path_items;
Paul Sokolovsky5500cde2014-04-13 06:43:18 +0300110 mp_obj_list_get(mp_sys_path, &path_num, &path_items);
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200111
112 if (path_num == 0) {
Sven Wegener238ab502014-11-05 21:02:33 +0100113#endif
Damien Georged17926d2014-03-30 13:35:08 +0100114 // mp_sys_path is empty, so just use the given file name
Damien Georgee09ffa12014-02-05 23:57:48 +0000115 vstr_add_strn(dest, file_str, file_len);
116 return stat_dir_or_file(dest);
Sven Wegener238ab502014-11-05 21:02:33 +0100117#if MICROPY_PY_SYS
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200118 } else {
Damien Georgee09ffa12014-02-05 23:57:48 +0000119 // go through each path looking for a directory or file
Damien George42f3de92014-10-03 17:44:14 +0000120 for (mp_uint_t i = 0; i < path_num; i++) {
Damien Georgee09ffa12014-02-05 23:57:48 +0000121 vstr_reset(dest);
Damien Georged182b982014-08-30 14:19:41 +0100122 mp_uint_t p_len;
Damien George698ec212014-02-08 18:17:23 +0000123 const char *p = mp_obj_str_get_data(path_items[i], &p_len);
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200124 if (p_len > 0) {
Damien George698ec212014-02-08 18:17:23 +0000125 vstr_add_strn(dest, p, p_len);
Damien Georgee09ffa12014-02-05 23:57:48 +0000126 vstr_add_char(dest, PATH_SEP_CHAR);
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200127 }
Damien Georgee09ffa12014-02-05 23:57:48 +0000128 vstr_add_strn(dest, file_str, file_len);
129 mp_import_stat_t stat = stat_dir_or_file(dest);
130 if (stat != MP_IMPORT_STAT_NO_EXIST) {
131 return stat;
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200132 }
133 }
Damien Georgee09ffa12014-02-05 23:57:48 +0000134
135 // could not find a directory or file
136 return MP_IMPORT_STAT_NO_EXIST;
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200137 }
Sven Wegener238ab502014-11-05 21:02:33 +0100138#endif
Damien Georgee09ffa12014-02-05 23:57:48 +0000139}
140
Damien Georgedd5353a2015-12-18 12:35:44 +0000141#if MICROPY_ENABLE_COMPILER
Paul Sokolovsky640e0b22015-01-20 11:52:12 +0200142STATIC void do_load_from_lexer(mp_obj_t module_obj, mp_lexer_t *lex, const char *fname) {
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200143
Damien George66028ab2014-01-03 14:03:48 +0000144 if (lex == NULL) {
Damien Georgee09ffa12014-02-05 23:57:48 +0000145 // we verified the file exists using stat, but lexer could still fail
Damien George1e9a92f2014-11-06 17:36:16 +0000146 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100147 mp_raise_msg(&mp_type_ImportError, "module not found");
Damien George1e9a92f2014-11-06 17:36:16 +0000148 } else {
149 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError,
Paul Sokolovsky640e0b22015-01-20 11:52:12 +0200150 "no module named '%s'", fname));
Damien George1e9a92f2014-11-06 17:36:16 +0000151 }
Damien George66028ab2014-01-03 14:03:48 +0000152 }
153
Paul Sokolovskyd0f5e612014-07-25 11:00:15 +0300154 #if MICROPY_PY___FILE__
Damien Georgea4c52c52014-12-05 19:35:18 +0000155 qstr source_name = lex->source_name;
Damien Georgec4d08682014-10-05 20:13:34 +0100156 mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
Paul Sokolovskyd0f5e612014-07-25 11:00:15 +0300157 #endif
Damien George66028ab2014-01-03 14:03:48 +0000158
Damien Georgec4d08682014-10-05 20:13:34 +0100159 // parse, compile and execute the module in its context
160 mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj);
161 mp_parse_compile_execute(lex, MP_PARSE_FILE_INPUT, mod_globals, mod_globals);
Damien Georgee09ffa12014-02-05 23:57:48 +0000162}
Damien Georgedd5353a2015-12-18 12:35:44 +0000163#endif
Damien Georgee09ffa12014-02-05 23:57:48 +0000164
Damien George0a2e9652016-01-31 22:24:16 +0000165#if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_MODULE_FROZEN_MPY
Damien George432e8272015-11-02 21:57:42 +0000166STATIC void do_execute_raw_code(mp_obj_t module_obj, mp_raw_code_t *raw_code) {
167 #if MICROPY_PY___FILE__
168 // TODO
169 //qstr source_name = lex->source_name;
170 //mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
171 #endif
172
173 // execute the module in its context
174 mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj);
175
176 // save context
177 mp_obj_dict_t *volatile old_globals = mp_globals_get();
178 mp_obj_dict_t *volatile old_locals = mp_locals_get();
179
180 // set new context
181 mp_globals_set(mod_globals);
182 mp_locals_set(mod_globals);
183
184 nlr_buf_t nlr;
185 if (nlr_push(&nlr) == 0) {
186 mp_obj_t module_fun = mp_make_function_from_raw_code(raw_code, MP_OBJ_NULL, MP_OBJ_NULL);
187 mp_call_function_0(module_fun);
188
189 // finish nlr block, restore context
190 nlr_pop();
191 mp_globals_set(old_globals);
192 mp_locals_set(old_locals);
193 } else {
194 // exception; restore context and re-raise same exception
195 mp_globals_set(old_globals);
196 mp_locals_set(old_locals);
Damien George999cedb2015-11-27 17:01:44 +0000197 nlr_jump(nlr.ret_val);
Damien George432e8272015-11-02 21:57:42 +0000198 }
199}
200#endif
201
Paul Sokolovsky640e0b22015-01-20 11:52:12 +0200202STATIC void do_load(mp_obj_t module_obj, vstr_t *file) {
Damien George274952a2016-05-23 12:42:23 +0100203 #if MICROPY_MODULE_FROZEN || MICROPY_PERSISTENT_CODE_LOAD || MICROPY_ENABLE_COMPILER
Damien George827b0f72015-01-29 13:57:23 +0000204 char *file_str = vstr_null_terminated_str(file);
Damien George0a2e9652016-01-31 22:24:16 +0000205 #endif
Damien Georgedd5353a2015-12-18 12:35:44 +0000206
Damien George274952a2016-05-23 12:42:23 +0100207 // If we support frozen modules (either as str or mpy) then try to find the
208 // requested filename in the list of frozen module filenames.
209 #if MICROPY_MODULE_FROZEN
210 void *modref;
211 int frozen_type = mp_find_frozen_module(file_str, file->len, &modref);
212 #endif
213
214 // If we support frozen str modules and the compiler is enabled, and we
215 // found the filename in the list of frozen files, then load and execute it.
216 #if MICROPY_MODULE_FROZEN_STR
217 if (frozen_type == MP_FROZEN_STR) {
218 do_load_from_lexer(module_obj, modref, file_str);
219 return;
220 }
221 #endif
222
223 // If we support frozen mpy modules and we found a corresponding file (and
224 // its data) in the list of frozen files, execute it.
225 #if MICROPY_MODULE_FROZEN_MPY
226 if (frozen_type == MP_FROZEN_MPY) {
227 do_execute_raw_code(module_obj, modref);
228 return;
229 }
230 #endif
231
232 // If we support loading .mpy files then check if the file extension is of
233 // the correct format and, if so, load and execute the file.
Damien George432e8272015-11-02 21:57:42 +0000234 #if MICROPY_PERSISTENT_CODE_LOAD
235 if (file_str[file->len - 3] == 'm') {
236 mp_raw_code_t *raw_code = mp_raw_code_load_file(file_str);
237 do_execute_raw_code(module_obj, raw_code);
Damien Georgedd5353a2015-12-18 12:35:44 +0000238 return;
239 }
Damien George432e8272015-11-02 21:57:42 +0000240 #endif
Damien Georgedd5353a2015-12-18 12:35:44 +0000241
Damien George274952a2016-05-23 12:42:23 +0100242 // If we can compile scripts then load the file and compile and execute it.
Damien Georgedd5353a2015-12-18 12:35:44 +0000243 #if MICROPY_ENABLE_COMPILER
Damien George432e8272015-11-02 21:57:42 +0000244 {
Damien George274952a2016-05-23 12:42:23 +0100245 mp_lexer_t *lex = mp_lexer_new_from_file(file_str);
246 do_load_from_lexer(module_obj, lex, file_str);
247 return;
Damien George432e8272015-11-02 21:57:42 +0000248 }
Damien George274952a2016-05-23 12:42:23 +0100249 #endif
250
251 // If we get here then the file was not frozen and we can't compile scripts.
Damien Georgedd5353a2015-12-18 12:35:44 +0000252 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError,
253 "script compilation not supported"));
Paul Sokolovsky640e0b22015-01-20 11:52:12 +0200254}
255
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200256STATIC void chop_component(const char *start, const char **end) {
257 const char *p = *end;
258 while (p > start) {
259 if (*--p == '.') {
260 *end = p;
261 return;
262 }
263 }
264 *end = p;
265}
266
Damien George4b72b3a2016-01-03 14:21:40 +0000267mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye0813292014-04-11 23:08:29 +0300268#if DEBUG_PRINT
Damien Georgeeaaebf32014-09-23 10:59:05 +0100269 DEBUG_printf("__import__:\n");
Damien George42f3de92014-10-03 17:44:14 +0000270 for (mp_uint_t i = 0; i < n_args; i++) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100271 DEBUG_printf(" ");
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200272 mp_obj_print(args[i], PRINT_REPR);
Damien Georgeeaaebf32014-09-23 10:59:05 +0100273 DEBUG_printf("\n");
Damien Georgee09ffa12014-02-05 23:57:48 +0000274 }
Paul Sokolovskye0813292014-04-11 23:08:29 +0300275#endif
Damien Georgee09ffa12014-02-05 23:57:48 +0000276
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300277 mp_obj_t module_name = args[0];
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200278 mp_obj_t fromtuple = mp_const_none;
Damien George42f3de92014-10-03 17:44:14 +0000279 mp_int_t level = 0;
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200280 if (n_args >= 4) {
281 fromtuple = args[3];
Paul Sokolovskyfeacaa12014-02-21 01:15:20 +0200282 if (n_args >= 5) {
283 level = MP_OBJ_SMALL_INT_VALUE(args[4]);
284 }
285 }
286
Damien Georged182b982014-08-30 14:19:41 +0100287 mp_uint_t mod_len;
288 const char *mod_str = mp_obj_str_get_data(module_name, &mod_len);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300289
Paul Sokolovskyfeacaa12014-02-21 01:15:20 +0200290 if (level != 0) {
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300291 // What we want to do here is to take name of current module,
292 // chop <level> trailing components, and concatenate with passed-in
293 // module name, thus resolving relative import name into absolue.
294 // This even appears to be correct per
295 // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
296 // "Relative imports use a module's __name__ attribute to determine that
297 // module's position in the package hierarchy."
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200298 level--;
Damien George999cedb2015-11-27 17:01:44 +0000299 mp_obj_t this_name_q = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___name__));
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300300 assert(this_name_q != MP_OBJ_NULL);
Paul Sokolovsky9780e552015-06-29 00:21:36 +0300301 #if MICROPY_CPYTHON_COMPAT
302 if (MP_OBJ_QSTR_VALUE(this_name_q) == MP_QSTR___main__) {
303 // This is a module run by -m command-line switch, get its real name from backup attribute
Damien George999cedb2015-11-27 17:01:44 +0000304 this_name_q = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
Paul Sokolovsky9780e552015-06-29 00:21:36 +0300305 }
306 #endif
Damien George999cedb2015-11-27 17:01:44 +0000307 mp_map_t *globals_map = &mp_globals_get()->map;
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200308 mp_map_elem_t *elem = mp_map_lookup(globals_map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP);
309 bool is_pkg = (elem != NULL);
310
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300311#if DEBUG_PRINT
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200312 DEBUG_printf("Current module/package: ");
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300313 mp_obj_print(this_name_q, PRINT_REPR);
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200314 DEBUG_printf(", is_package: %d", is_pkg);
Damien Georgeeaaebf32014-09-23 10:59:05 +0100315 DEBUG_printf("\n");
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300316#endif
317
Damien Georged182b982014-08-30 14:19:41 +0100318 mp_uint_t this_name_l;
319 const char *this_name = mp_obj_str_get_data(this_name_q, &this_name_l);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300320
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200321 const char *p = this_name + this_name_l;
322 if (!is_pkg) {
323 // We have module, but relative imports are anchored at package, so
324 // go there.
325 chop_component(this_name, &p);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300326 }
327
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200328
329 uint dots_seen = 0;
330 while (level--) {
331 chop_component(this_name, &p);
332 dots_seen++;
333 }
334
335 if (dots_seen == 0 && level >= 1) {
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300336 // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
337 // "If the module's name does not contain any package information
338 // (e.g. it is set to '__main__') then relative imports are
339 // resolved as if the module were a top level module, regardless
340 // of where the module is actually located on the file system."
341 // Supposedly this if catches this condition and resolve it properly
342 // TODO: But nobody knows for sure. This condition happens when
343 // package's __init__.py does something like "import .submod". So,
344 // maybe we should check for package here? But quote above doesn't
345 // talk about packages, it talks about dot-less module names.
Paul Sokolovsky078172d2015-02-16 12:10:13 +0200346 DEBUG_printf("Warning: no dots in current module name and level>0\n");
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300347 p = this_name + this_name_l;
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200348 } else if (level != -1) {
Damien George7d0d7212016-10-17 12:17:37 +1100349 mp_raise_msg(&mp_type_ImportError, "invalid relative import");
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300350 }
351
Damien George963a5a32015-01-16 17:47:07 +0000352 uint new_mod_l = (mod_len == 0 ? (size_t)(p - this_name) : (size_t)(p - this_name) + 1 + mod_len);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300353 char *new_mod = alloca(new_mod_l);
354 memcpy(new_mod, this_name, p - this_name);
355 if (mod_len != 0) {
356 new_mod[p - this_name] = '.';
357 memcpy(new_mod + (p - this_name) + 1, mod_str, mod_len);
358 }
359
360 qstr new_mod_q = qstr_from_strn(new_mod, new_mod_l);
Paul Sokolovskyc4045f52015-06-27 00:34:53 +0300361 DEBUG_printf("Resolved base name for relative import: '%s'\n", qstr_str(new_mod_q));
362 if (new_mod_q == MP_QSTR_) {
Damien George63e291d2017-01-16 16:21:04 +1100363 mp_raise_msg(&mp_type_ValueError, "cannot perform relative import");
Paul Sokolovskyc4045f52015-06-27 00:34:53 +0300364 }
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300365 module_name = MP_OBJ_NEW_QSTR(new_mod_q);
366 mod_str = new_mod;
367 mod_len = new_mod_l;
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200368 }
369
Damien Georgee09ffa12014-02-05 23:57:48 +0000370 // check if module already exists
Paul Sokolovsky80648922015-01-21 23:14:46 +0200371 qstr module_name_qstr = mp_obj_str_get_qstr(module_name);
372 mp_obj_t module_obj = mp_module_get(module_name_qstr);
Damien Georgee09ffa12014-02-05 23:57:48 +0000373 if (module_obj != MP_OBJ_NULL) {
Paul Sokolovskye0813292014-04-11 23:08:29 +0300374 DEBUG_printf("Module already loaded\n");
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200375 // If it's not a package, return module right away
376 char *p = strchr(mod_str, '.');
377 if (p == NULL) {
378 return module_obj;
379 }
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200380 // If fromlist is not empty, return leaf module
381 if (fromtuple != mp_const_none) {
382 return module_obj;
383 }
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200384 // Otherwise, we need to return top-level package
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200385 qstr pkg_name = qstr_from_strn(mod_str, p - mod_str);
Damien Georgecaac5422014-03-25 14:18:18 +0000386 return mp_module_get(pkg_name);
Damien Georgee09ffa12014-02-05 23:57:48 +0000387 }
Paul Sokolovskye0813292014-04-11 23:08:29 +0300388 DEBUG_printf("Module not yet loaded\n");
Damien Georgee09ffa12014-02-05 23:57:48 +0000389
Damien Georgee09ffa12014-02-05 23:57:48 +0000390 uint last = 0;
Damien George58ebde42014-05-21 20:32:59 +0100391 VSTR_FIXED(path, MICROPY_ALLOC_PATH_MAX)
Damien Georgee09ffa12014-02-05 23:57:48 +0000392 module_obj = MP_OBJ_NULL;
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200393 mp_obj_t top_module_obj = MP_OBJ_NULL;
394 mp_obj_t outer_module_obj = MP_OBJ_NULL;
Damien Georgee09ffa12014-02-05 23:57:48 +0000395 uint i;
396 for (i = 1; i <= mod_len; i++) {
397 if (i == mod_len || mod_str[i] == '.') {
398 // create a qstr for the module name up to this depth
399 qstr mod_name = qstr_from_strn(mod_str, i);
Paul Sokolovskye0813292014-04-11 23:08:29 +0300400 DEBUG_printf("Processing module: %s\n", qstr_str(mod_name));
Paul Sokolovsky078172d2015-02-16 12:10:13 +0200401 DEBUG_printf("Previous path: =%.*s=\n", vstr_len(&path), vstr_str(&path));
Damien Georgee09ffa12014-02-05 23:57:48 +0000402
403 // find the file corresponding to the module name
404 mp_import_stat_t stat;
Damien George354d15a2014-02-06 21:11:19 +0000405 if (vstr_len(&path) == 0) {
Damien Georgee09ffa12014-02-05 23:57:48 +0000406 // first module in the dotted-name; search for a directory or file
Damien George354d15a2014-02-06 21:11:19 +0000407 stat = find_file(mod_str, i, &path);
Damien Georgee09ffa12014-02-05 23:57:48 +0000408 } else {
409 // latter module in the dotted-name; append to path
Damien George354d15a2014-02-06 21:11:19 +0000410 vstr_add_char(&path, PATH_SEP_CHAR);
411 vstr_add_strn(&path, mod_str + last, i - last);
412 stat = stat_dir_or_file(&path);
Damien Georgee09ffa12014-02-05 23:57:48 +0000413 }
Damien George0d3cb672015-01-28 23:43:01 +0000414 DEBUG_printf("Current path: %.*s\n", vstr_len(&path), vstr_str(&path));
Damien Georgee09ffa12014-02-05 23:57:48 +0000415
Damien Georgee09ffa12014-02-05 23:57:48 +0000416 if (stat == MP_IMPORT_STAT_NO_EXIST) {
Damien Georgec14a8162014-10-12 11:46:04 +0100417 #if MICROPY_MODULE_WEAK_LINKS
418 // check if there is a weak link to this module
419 if (i == mod_len) {
Damien George78d702c2014-12-09 16:19:48 +0000420 mp_map_elem_t *el = mp_map_lookup((mp_map_t*)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(mod_name), MP_MAP_LOOKUP);
Damien Georgec14a8162014-10-12 11:46:04 +0100421 if (el == NULL) {
422 goto no_exist;
423 }
424 // found weak linked module
425 module_obj = el->value;
426 } else {
427 no_exist:
428 #else
429 {
430 #endif
431 // couldn't find the file, so fail
Damien George1e9a92f2014-11-06 17:36:16 +0000432 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100433 mp_raise_msg(&mp_type_ImportError, "module not found");
Damien George1e9a92f2014-11-06 17:36:16 +0000434 } else {
435 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError,
Damien George044c4732015-04-11 13:03:37 +0100436 "no module named '%q'", mod_name));
Damien George1e9a92f2014-11-06 17:36:16 +0000437 }
Damien Georgec14a8162014-10-12 11:46:04 +0100438 }
439 } else {
440 // found the file, so get the module
441 module_obj = mp_module_get(mod_name);
Damien Georgee09ffa12014-02-05 23:57:48 +0000442 }
443
Damien Georgee09ffa12014-02-05 23:57:48 +0000444 if (module_obj == MP_OBJ_NULL) {
445 // module not already loaded, so load it!
446
447 module_obj = mp_obj_new_module(mod_name);
448
Paul Sokolovskye5035122014-10-25 21:16:24 +0300449 // if args[3] (fromtuple) has magic value False, set up
450 // this module for command-line "-m" option (set module's
451 // name to __main__ instead of real name).
452 if (i == mod_len && fromtuple == mp_const_false) {
Damien George999cedb2015-11-27 17:01:44 +0000453 mp_obj_module_t *o = MP_OBJ_TO_PTR(module_obj);
454 mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
Paul Sokolovsky9780e552015-06-29 00:21:36 +0300455 #if MICROPY_CPYTHON_COMPAT
Delio Brignoli21c719b2016-08-22 12:28:22 +0200456 // Store module as "__main__" in the dictionary of loaded modules (returned by sys.modules).
Paul Sokolovsky7ea3fa22016-09-20 17:55:42 +0300457 mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_loaded_modules_dict)), MP_OBJ_NEW_QSTR(MP_QSTR___main__), module_obj);
Paul Sokolovsky9780e552015-06-29 00:21:36 +0300458 // Store real name in "__main__" attribute. Choosen semi-randonly, to reuse existing qstr's.
Damien George999cedb2015-11-27 17:01:44 +0000459 mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___main__), MP_OBJ_NEW_QSTR(mod_name));
Paul Sokolovsky9780e552015-06-29 00:21:36 +0300460 #endif
Paul Sokolovskye5035122014-10-25 21:16:24 +0300461 }
462
Damien Georgee09ffa12014-02-05 23:57:48 +0000463 if (stat == MP_IMPORT_STAT_DIR) {
Damien George0d3cb672015-01-28 23:43:01 +0000464 DEBUG_printf("%.*s is dir\n", vstr_len(&path), vstr_str(&path));
Chris Angelicodaf973a2014-06-06 03:51:03 +1000465 // https://docs.python.org/3/reference/import.html
Paul Sokolovskyf9589d22014-05-10 18:46:02 +0300466 // "Specifically, any module that contains a __path__ attribute is considered a package."
Damien George2617eeb2014-05-25 22:27:57 +0100467 mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path), false));
Damien Georgeb528e9a2017-01-08 20:17:23 +1100468 size_t orig_path_len = path.len;
Damien George354d15a2014-02-06 21:11:19 +0000469 vstr_add_char(&path, PATH_SEP_CHAR);
470 vstr_add_str(&path, "__init__.py");
Damien Georged9047d32016-12-13 15:09:48 +1100471 if (stat_file_py_or_mpy(&path) != MP_IMPORT_STAT_FILE) {
Paul Sokolovskyae184cb2016-07-02 14:45:49 +0300472 //mp_warning("%s is imported as namespace package", vstr_str(&path));
Paul Sokolovskya5854d22014-04-15 01:23:40 +0300473 } else {
474 do_load(module_obj, &path);
Damien Georgee09ffa12014-02-05 23:57:48 +0000475 }
Damien Georgeb528e9a2017-01-08 20:17:23 +1100476 path.len = orig_path_len;
Damien Georgee09ffa12014-02-05 23:57:48 +0000477 } else { // MP_IMPORT_STAT_FILE
Damien George354d15a2014-02-06 21:11:19 +0000478 do_load(module_obj, &path);
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200479 // TODO: We cannot just break here, at the very least, we must execute
480 // trailer code below. But otherwise if there're remaining components,
481 // that would be (??) object path within module, not modules path within FS.
482 // break;
Damien Georgee09ffa12014-02-05 23:57:48 +0000483 }
484 }
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200485 if (outer_module_obj != MP_OBJ_NULL) {
486 qstr s = qstr_from_strn(mod_str + last, i - last);
Damien Georged17926d2014-03-30 13:35:08 +0100487 mp_store_attr(outer_module_obj, s, module_obj);
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200488 }
489 outer_module_obj = module_obj;
490 if (top_module_obj == MP_OBJ_NULL) {
491 top_module_obj = module_obj;
492 }
493 last = i + 1;
Damien Georgee09ffa12014-02-05 23:57:48 +0000494 }
495 }
496
497 if (i < mod_len) {
498 // we loaded a package, now need to load objects from within that package
499 // TODO
500 assert(0);
501 }
502
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200503 // If fromlist is not empty, return leaf module
504 if (fromtuple != mp_const_none) {
505 return module_obj;
506 }
507 // Otherwise, we need to return top-level package
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200508 return top_module_obj;
Damien George66028ab2014-01-03 14:03:48 +0000509}
Paul Sokolovsky1d938c92014-02-04 00:46:17 +0200510MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin___import___obj, 1, 5, mp_builtin___import__);