blob: 97c1789f84ed3ca331313402e18db58ee4e48a71 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
Alexander Steffen55f33242017-06-30 09:22:17 +02002 * This file is part of the MicroPython project, http://micropython.org/
Damien George04b91472014-05-03 23:27:38 +01003 *
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/compile.h"
33#include "py/objmodule.h"
Damien George6810f2c2016-11-16 11:55:41 +110034#include "py/persistentcode.h"
Damien George51dfcb42015-01-01 20:27:54 +000035#include "py/runtime.h"
36#include "py/builtin.h"
Paul Sokolovsky640e0b22015-01-20 11:52:12 +020037#include "py/frozenmod.h"
Damien George66028ab2014-01-03 14:03:48 +000038
Stefan Naumannace9fb52017-07-24 18:55:14 +020039#if MICROPY_DEBUG_VERBOSE // print debugging info
Paul Sokolovskye0813292014-04-11 23:08:29 +030040#define DEBUG_PRINT (1)
41#define DEBUG_printf DEBUG_printf
42#else // don't print debugging info
Damien George7860c2a2014-11-05 21:16:41 +000043#define DEBUG_PRINT (0)
Paul Sokolovskye0813292014-04-11 23:08:29 +030044#define DEBUG_printf(...) (void)0
45#endif
46
Damien Georgee09ffa12014-02-05 23:57:48 +000047#define PATH_SEP_CHAR '/'
48
Paul Sokolovskye5a37592014-10-25 21:04:13 +030049bool mp_obj_is_package(mp_obj_t module) {
50 mp_obj_t dest[2];
51 mp_load_method_maybe(module, MP_QSTR___path__, dest);
52 return dest[0] != MP_OBJ_NULL;
53}
54
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030055// Stat either frozen or normal module by a given path
56// (whatever is available, if at all).
57STATIC mp_import_stat_t mp_import_stat_any(const char *path) {
Damien George274952a2016-05-23 12:42:23 +010058 #if MICROPY_MODULE_FROZEN
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030059 mp_import_stat_t st = mp_frozen_stat(path);
60 if (st != MP_IMPORT_STAT_NO_EXIST) {
61 return st;
62 }
Paul Sokolovsky8a2970e2016-05-21 22:23:08 +030063 #endif
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030064 return mp_import_stat(path);
65}
66
Damien Georged9047d32016-12-13 15:09:48 +110067STATIC mp_import_stat_t stat_file_py_or_mpy(vstr_t *path) {
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030068 mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
Damien Georgee09ffa12014-02-05 23:57:48 +000069 if (stat == MP_IMPORT_STAT_FILE) {
70 return stat;
Paul Sokolovskyd720ab52014-01-20 00:03:34 +020071 }
Damien George432e8272015-11-02 21:57:42 +000072
73 #if MICROPY_PERSISTENT_CODE_LOAD
74 vstr_ins_byte(path, path->len - 2, 'm');
Paul Sokolovskyfb742cd2016-05-21 21:33:42 +030075 stat = mp_import_stat_any(vstr_null_terminated_str(path));
Damien George432e8272015-11-02 21:57:42 +000076 if (stat == MP_IMPORT_STAT_FILE) {
77 return stat;
78 }
79 #endif
80
Damien Georgee09ffa12014-02-05 23:57:48 +000081 return MP_IMPORT_STAT_NO_EXIST;
82}
Paul Sokolovskyd720ab52014-01-20 00:03:34 +020083
Damien Georged9047d32016-12-13 15:09:48 +110084STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) {
85 mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
86 DEBUG_printf("stat %s: %d\n", vstr_str(path), stat);
87 if (stat == MP_IMPORT_STAT_DIR) {
88 return stat;
89 }
90
91 // not a directory, add .py and try as a file
92 vstr_add_str(path, ".py");
93 return stat_file_py_or_mpy(path);
94}
95
Damien George8a0801a2014-06-11 19:55:46 +010096STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *dest) {
Damien Georgeee3fd462014-05-24 23:03:12 +010097#if MICROPY_PY_SYS
Sven Wegener238ab502014-11-05 21:02:33 +010098 // extract the list of paths
Damien George6213ad72017-03-25 19:35:08 +110099 size_t path_num;
Sven Wegener238ab502014-11-05 21:02:33 +0100100 mp_obj_t *path_items;
Paul Sokolovsky5500cde2014-04-13 06:43:18 +0300101 mp_obj_list_get(mp_sys_path, &path_num, &path_items);
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200102
103 if (path_num == 0) {
Sven Wegener238ab502014-11-05 21:02:33 +0100104#endif
Damien Georged17926d2014-03-30 13:35:08 +0100105 // mp_sys_path is empty, so just use the given file name
Damien Georgee09ffa12014-02-05 23:57:48 +0000106 vstr_add_strn(dest, file_str, file_len);
107 return stat_dir_or_file(dest);
Sven Wegener238ab502014-11-05 21:02:33 +0100108#if MICROPY_PY_SYS
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200109 } else {
Damien Georgee09ffa12014-02-05 23:57:48 +0000110 // go through each path looking for a directory or file
Damien George7bd10c12017-07-04 23:44:22 +1000111 for (size_t i = 0; i < path_num; i++) {
Damien Georgee09ffa12014-02-05 23:57:48 +0000112 vstr_reset(dest);
Damien George6b341072017-03-25 19:48:18 +1100113 size_t p_len;
Damien George698ec212014-02-08 18:17:23 +0000114 const char *p = mp_obj_str_get_data(path_items[i], &p_len);
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200115 if (p_len > 0) {
Damien George698ec212014-02-08 18:17:23 +0000116 vstr_add_strn(dest, p, p_len);
Damien Georgee09ffa12014-02-05 23:57:48 +0000117 vstr_add_char(dest, PATH_SEP_CHAR);
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200118 }
Damien Georgee09ffa12014-02-05 23:57:48 +0000119 vstr_add_strn(dest, file_str, file_len);
120 mp_import_stat_t stat = stat_dir_or_file(dest);
121 if (stat != MP_IMPORT_STAT_NO_EXIST) {
122 return stat;
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200123 }
124 }
Damien Georgee09ffa12014-02-05 23:57:48 +0000125
126 // could not find a directory or file
127 return MP_IMPORT_STAT_NO_EXIST;
Paul Sokolovskye11b17c2014-02-05 00:47:06 +0200128 }
Sven Wegener238ab502014-11-05 21:02:33 +0100129#endif
Damien Georgee09ffa12014-02-05 23:57:48 +0000130}
131
Damien Georgedd5353a2015-12-18 12:35:44 +0000132#if MICROPY_ENABLE_COMPILER
Damien George18310342017-03-14 11:16:31 +1100133STATIC void do_load_from_lexer(mp_obj_t module_obj, mp_lexer_t *lex) {
Paul Sokolovskyd0f5e612014-07-25 11:00:15 +0300134 #if MICROPY_PY___FILE__
Damien Georgea4c52c52014-12-05 19:35:18 +0000135 qstr source_name = lex->source_name;
Damien Georgec4d08682014-10-05 20:13:34 +0100136 mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
Paul Sokolovskyd0f5e612014-07-25 11:00:15 +0300137 #endif
Damien George66028ab2014-01-03 14:03:48 +0000138
Damien Georgec4d08682014-10-05 20:13:34 +0100139 // parse, compile and execute the module in its context
140 mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj);
141 mp_parse_compile_execute(lex, MP_PARSE_FILE_INPUT, mod_globals, mod_globals);
Damien Georgee09ffa12014-02-05 23:57:48 +0000142}
Damien Georgedd5353a2015-12-18 12:35:44 +0000143#endif
Damien Georgee09ffa12014-02-05 23:57:48 +0000144
Damien George0a2e9652016-01-31 22:24:16 +0000145#if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_MODULE_FROZEN_MPY
Damien George432e8272015-11-02 21:57:42 +0000146STATIC void do_execute_raw_code(mp_obj_t module_obj, mp_raw_code_t *raw_code) {
147 #if MICROPY_PY___FILE__
148 // TODO
149 //qstr source_name = lex->source_name;
150 //mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
151 #endif
152
153 // execute the module in its context
154 mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj);
155
156 // save context
157 mp_obj_dict_t *volatile old_globals = mp_globals_get();
158 mp_obj_dict_t *volatile old_locals = mp_locals_get();
159
160 // set new context
161 mp_globals_set(mod_globals);
162 mp_locals_set(mod_globals);
163
164 nlr_buf_t nlr;
165 if (nlr_push(&nlr) == 0) {
166 mp_obj_t module_fun = mp_make_function_from_raw_code(raw_code, MP_OBJ_NULL, MP_OBJ_NULL);
167 mp_call_function_0(module_fun);
168
169 // finish nlr block, restore context
170 nlr_pop();
171 mp_globals_set(old_globals);
172 mp_locals_set(old_locals);
173 } else {
174 // exception; restore context and re-raise same exception
175 mp_globals_set(old_globals);
176 mp_locals_set(old_locals);
Damien George999cedb2015-11-27 17:01:44 +0000177 nlr_jump(nlr.ret_val);
Damien George432e8272015-11-02 21:57:42 +0000178 }
179}
180#endif
181
Paul Sokolovsky640e0b22015-01-20 11:52:12 +0200182STATIC void do_load(mp_obj_t module_obj, vstr_t *file) {
Damien George274952a2016-05-23 12:42:23 +0100183 #if MICROPY_MODULE_FROZEN || MICROPY_PERSISTENT_CODE_LOAD || MICROPY_ENABLE_COMPILER
Damien George827b0f72015-01-29 13:57:23 +0000184 char *file_str = vstr_null_terminated_str(file);
Damien George0a2e9652016-01-31 22:24:16 +0000185 #endif
Damien Georgedd5353a2015-12-18 12:35:44 +0000186
Damien George274952a2016-05-23 12:42:23 +0100187 // If we support frozen modules (either as str or mpy) then try to find the
188 // requested filename in the list of frozen module filenames.
189 #if MICROPY_MODULE_FROZEN
190 void *modref;
191 int frozen_type = mp_find_frozen_module(file_str, file->len, &modref);
192 #endif
193
194 // If we support frozen str modules and the compiler is enabled, and we
195 // found the filename in the list of frozen files, then load and execute it.
196 #if MICROPY_MODULE_FROZEN_STR
197 if (frozen_type == MP_FROZEN_STR) {
Damien George18310342017-03-14 11:16:31 +1100198 do_load_from_lexer(module_obj, modref);
Damien George274952a2016-05-23 12:42:23 +0100199 return;
200 }
201 #endif
202
203 // If we support frozen mpy modules and we found a corresponding file (and
204 // its data) in the list of frozen files, execute it.
205 #if MICROPY_MODULE_FROZEN_MPY
206 if (frozen_type == MP_FROZEN_MPY) {
207 do_execute_raw_code(module_obj, modref);
208 return;
209 }
210 #endif
211
212 // If we support loading .mpy files then check if the file extension is of
213 // the correct format and, if so, load and execute the file.
Damien George432e8272015-11-02 21:57:42 +0000214 #if MICROPY_PERSISTENT_CODE_LOAD
215 if (file_str[file->len - 3] == 'm') {
216 mp_raw_code_t *raw_code = mp_raw_code_load_file(file_str);
217 do_execute_raw_code(module_obj, raw_code);
Damien Georgedd5353a2015-12-18 12:35:44 +0000218 return;
219 }
Damien George432e8272015-11-02 21:57:42 +0000220 #endif
Damien Georgedd5353a2015-12-18 12:35:44 +0000221
Damien George274952a2016-05-23 12:42:23 +0100222 // If we can compile scripts then load the file and compile and execute it.
Damien Georgedd5353a2015-12-18 12:35:44 +0000223 #if MICROPY_ENABLE_COMPILER
Damien George432e8272015-11-02 21:57:42 +0000224 {
Damien George274952a2016-05-23 12:42:23 +0100225 mp_lexer_t *lex = mp_lexer_new_from_file(file_str);
Damien George18310342017-03-14 11:16:31 +1100226 do_load_from_lexer(module_obj, lex);
Damien George274952a2016-05-23 12:42:23 +0100227 return;
Damien George432e8272015-11-02 21:57:42 +0000228 }
Tom Collins145796f2017-06-30 16:23:29 -0700229 #else
Damien George274952a2016-05-23 12:42:23 +0100230
231 // If we get here then the file was not frozen and we can't compile scripts.
Damien George48d867b2017-06-15 11:54:41 +1000232 mp_raise_msg(&mp_type_ImportError, "script compilation not supported");
Tom Collins145796f2017-06-30 16:23:29 -0700233 #endif
Paul Sokolovsky640e0b22015-01-20 11:52:12 +0200234}
235
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200236STATIC void chop_component(const char *start, const char **end) {
237 const char *p = *end;
238 while (p > start) {
239 if (*--p == '.') {
240 *end = p;
241 return;
242 }
243 }
244 *end = p;
245}
246
Damien George4b72b3a2016-01-03 14:21:40 +0000247mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye0813292014-04-11 23:08:29 +0300248#if DEBUG_PRINT
Damien Georgeeaaebf32014-09-23 10:59:05 +0100249 DEBUG_printf("__import__:\n");
Damien George7bd10c12017-07-04 23:44:22 +1000250 for (size_t i = 0; i < n_args; i++) {
Damien Georgeeaaebf32014-09-23 10:59:05 +0100251 DEBUG_printf(" ");
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200252 mp_obj_print(args[i], PRINT_REPR);
Damien Georgeeaaebf32014-09-23 10:59:05 +0100253 DEBUG_printf("\n");
Damien Georgee09ffa12014-02-05 23:57:48 +0000254 }
Paul Sokolovskye0813292014-04-11 23:08:29 +0300255#endif
Damien Georgee09ffa12014-02-05 23:57:48 +0000256
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300257 mp_obj_t module_name = args[0];
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200258 mp_obj_t fromtuple = mp_const_none;
Damien George42f3de92014-10-03 17:44:14 +0000259 mp_int_t level = 0;
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200260 if (n_args >= 4) {
261 fromtuple = args[3];
Paul Sokolovskyfeacaa12014-02-21 01:15:20 +0200262 if (n_args >= 5) {
263 level = MP_OBJ_SMALL_INT_VALUE(args[4]);
Damien George2f7fad62017-01-16 16:54:56 +1100264 if (level < 0) {
265 mp_raise_ValueError(NULL);
266 }
Paul Sokolovskyfeacaa12014-02-21 01:15:20 +0200267 }
268 }
269
Damien George6b341072017-03-25 19:48:18 +1100270 size_t mod_len;
Damien Georged182b982014-08-30 14:19:41 +0100271 const char *mod_str = mp_obj_str_get_data(module_name, &mod_len);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300272
Paul Sokolovskyfeacaa12014-02-21 01:15:20 +0200273 if (level != 0) {
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300274 // What we want to do here is to take name of current module,
275 // chop <level> trailing components, and concatenate with passed-in
Ville Skyttäca16c382017-05-29 10:08:14 +0300276 // module name, thus resolving relative import name into absolute.
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300277 // This even appears to be correct per
278 // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
279 // "Relative imports use a module's __name__ attribute to determine that
280 // module's position in the package hierarchy."
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200281 level--;
Damien George999cedb2015-11-27 17:01:44 +0000282 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 +0300283 assert(this_name_q != MP_OBJ_NULL);
Paul Sokolovsky9780e552015-06-29 00:21:36 +0300284 #if MICROPY_CPYTHON_COMPAT
285 if (MP_OBJ_QSTR_VALUE(this_name_q) == MP_QSTR___main__) {
286 // This is a module run by -m command-line switch, get its real name from backup attribute
Damien George999cedb2015-11-27 17:01:44 +0000287 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 +0300288 }
289 #endif
Damien George999cedb2015-11-27 17:01:44 +0000290 mp_map_t *globals_map = &mp_globals_get()->map;
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200291 mp_map_elem_t *elem = mp_map_lookup(globals_map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP);
292 bool is_pkg = (elem != NULL);
293
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300294#if DEBUG_PRINT
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200295 DEBUG_printf("Current module/package: ");
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300296 mp_obj_print(this_name_q, PRINT_REPR);
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200297 DEBUG_printf(", is_package: %d", is_pkg);
Damien Georgeeaaebf32014-09-23 10:59:05 +0100298 DEBUG_printf("\n");
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300299#endif
300
Damien George6b341072017-03-25 19:48:18 +1100301 size_t this_name_l;
Damien Georged182b982014-08-30 14:19:41 +0100302 const char *this_name = mp_obj_str_get_data(this_name_q, &this_name_l);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300303
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200304 const char *p = this_name + this_name_l;
305 if (!is_pkg) {
306 // We have module, but relative imports are anchored at package, so
307 // go there.
308 chop_component(this_name, &p);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300309 }
310
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200311 while (level--) {
312 chop_component(this_name, &p);
Paul Sokolovsky9e6c8292015-02-16 12:10:13 +0200313 }
314
Damien George2f7fad62017-01-16 16:54:56 +1100315 // We must have some component left over to import from
316 if (p == this_name) {
317 mp_raise_ValueError("cannot perform relative import");
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300318 }
319
Damien George963a5a32015-01-16 17:47:07 +0000320 uint new_mod_l = (mod_len == 0 ? (size_t)(p - this_name) : (size_t)(p - this_name) + 1 + mod_len);
Damien George1e5a33d2017-11-26 23:37:19 +1100321 char *new_mod = mp_local_alloc(new_mod_l);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300322 memcpy(new_mod, this_name, p - this_name);
323 if (mod_len != 0) {
324 new_mod[p - this_name] = '.';
325 memcpy(new_mod + (p - this_name) + 1, mod_str, mod_len);
326 }
327
328 qstr new_mod_q = qstr_from_strn(new_mod, new_mod_l);
Damien George1e5a33d2017-11-26 23:37:19 +1100329 mp_local_free(new_mod);
Paul Sokolovskyc4045f52015-06-27 00:34:53 +0300330 DEBUG_printf("Resolved base name for relative import: '%s'\n", qstr_str(new_mod_q));
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300331 module_name = MP_OBJ_NEW_QSTR(new_mod_q);
Damien George1e5a33d2017-11-26 23:37:19 +1100332 mod_str = qstr_str(new_mod_q);
Paul Sokolovskya5afc902014-04-12 17:46:54 +0300333 mod_len = new_mod_l;
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200334 }
335
Damien Georgee09ffa12014-02-05 23:57:48 +0000336 // check if module already exists
Paul Sokolovsky80648922015-01-21 23:14:46 +0200337 qstr module_name_qstr = mp_obj_str_get_qstr(module_name);
338 mp_obj_t module_obj = mp_module_get(module_name_qstr);
Damien Georgee09ffa12014-02-05 23:57:48 +0000339 if (module_obj != MP_OBJ_NULL) {
Paul Sokolovskye0813292014-04-11 23:08:29 +0300340 DEBUG_printf("Module already loaded\n");
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200341 // If it's not a package, return module right away
342 char *p = strchr(mod_str, '.');
343 if (p == NULL) {
344 return module_obj;
345 }
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200346 // If fromlist is not empty, return leaf module
347 if (fromtuple != mp_const_none) {
348 return module_obj;
349 }
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200350 // Otherwise, we need to return top-level package
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200351 qstr pkg_name = qstr_from_strn(mod_str, p - mod_str);
Damien Georgecaac5422014-03-25 14:18:18 +0000352 return mp_module_get(pkg_name);
Damien Georgee09ffa12014-02-05 23:57:48 +0000353 }
Paul Sokolovskye0813292014-04-11 23:08:29 +0300354 DEBUG_printf("Module not yet loaded\n");
Damien Georgee09ffa12014-02-05 23:57:48 +0000355
Damien Georgee09ffa12014-02-05 23:57:48 +0000356 uint last = 0;
Damien George58ebde42014-05-21 20:32:59 +0100357 VSTR_FIXED(path, MICROPY_ALLOC_PATH_MAX)
Damien Georgee09ffa12014-02-05 23:57:48 +0000358 module_obj = MP_OBJ_NULL;
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200359 mp_obj_t top_module_obj = MP_OBJ_NULL;
360 mp_obj_t outer_module_obj = MP_OBJ_NULL;
Damien Georgee09ffa12014-02-05 23:57:48 +0000361 uint i;
362 for (i = 1; i <= mod_len; i++) {
363 if (i == mod_len || mod_str[i] == '.') {
364 // create a qstr for the module name up to this depth
365 qstr mod_name = qstr_from_strn(mod_str, i);
Paul Sokolovskye0813292014-04-11 23:08:29 +0300366 DEBUG_printf("Processing module: %s\n", qstr_str(mod_name));
Paul Sokolovsky078172d2015-02-16 12:10:13 +0200367 DEBUG_printf("Previous path: =%.*s=\n", vstr_len(&path), vstr_str(&path));
Damien Georgee09ffa12014-02-05 23:57:48 +0000368
369 // find the file corresponding to the module name
370 mp_import_stat_t stat;
Damien George354d15a2014-02-06 21:11:19 +0000371 if (vstr_len(&path) == 0) {
Damien Georgee09ffa12014-02-05 23:57:48 +0000372 // first module in the dotted-name; search for a directory or file
Damien George354d15a2014-02-06 21:11:19 +0000373 stat = find_file(mod_str, i, &path);
Damien Georgee09ffa12014-02-05 23:57:48 +0000374 } else {
375 // latter module in the dotted-name; append to path
Damien George354d15a2014-02-06 21:11:19 +0000376 vstr_add_char(&path, PATH_SEP_CHAR);
377 vstr_add_strn(&path, mod_str + last, i - last);
378 stat = stat_dir_or_file(&path);
Damien Georgee09ffa12014-02-05 23:57:48 +0000379 }
Damien George0d3cb672015-01-28 23:43:01 +0000380 DEBUG_printf("Current path: %.*s\n", vstr_len(&path), vstr_str(&path));
Damien Georgee09ffa12014-02-05 23:57:48 +0000381
Damien Georgee09ffa12014-02-05 23:57:48 +0000382 if (stat == MP_IMPORT_STAT_NO_EXIST) {
Damien Georgec14a8162014-10-12 11:46:04 +0100383 #if MICROPY_MODULE_WEAK_LINKS
384 // check if there is a weak link to this module
385 if (i == mod_len) {
Damien George78d702c2014-12-09 16:19:48 +0000386 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 +0100387 if (el == NULL) {
388 goto no_exist;
389 }
390 // found weak linked module
391 module_obj = el->value;
Damien Georgef1c9e772017-03-06 16:46:34 +1100392 if (MICROPY_MODULE_BUILTIN_INIT) {
393 // look for __init__ and call it if it exists
394 // Note: this code doesn't work fully correctly because it allows the
395 // __init__ function to be called twice if the module is imported by its
396 // non-weak-link name. Also, this code is duplicated in objmodule.c.
397 mp_obj_t dest[2];
398 mp_load_method_maybe(el->value, MP_QSTR___init__, dest);
399 if (dest[0] != MP_OBJ_NULL) {
400 mp_call_method_n_kw(0, 0, dest);
401 // register module so __init__ is not called again
402 mp_module_register(mod_name, el->value);
403 }
404 }
Damien Georgec14a8162014-10-12 11:46:04 +0100405 } else {
406 no_exist:
407 #else
408 {
409 #endif
410 // couldn't find the file, so fail
Damien George1e9a92f2014-11-06 17:36:16 +0000411 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Damien George7d0d7212016-10-17 12:17:37 +1100412 mp_raise_msg(&mp_type_ImportError, "module not found");
Damien George1e9a92f2014-11-06 17:36:16 +0000413 } else {
414 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError,
Damien George044c4732015-04-11 13:03:37 +0100415 "no module named '%q'", mod_name));
Damien George1e9a92f2014-11-06 17:36:16 +0000416 }
Damien Georgec14a8162014-10-12 11:46:04 +0100417 }
418 } else {
419 // found the file, so get the module
420 module_obj = mp_module_get(mod_name);
Damien Georgee09ffa12014-02-05 23:57:48 +0000421 }
422
Damien Georgee09ffa12014-02-05 23:57:48 +0000423 if (module_obj == MP_OBJ_NULL) {
424 // module not already loaded, so load it!
425
426 module_obj = mp_obj_new_module(mod_name);
427
Paul Sokolovskye5035122014-10-25 21:16:24 +0300428 // if args[3] (fromtuple) has magic value False, set up
429 // this module for command-line "-m" option (set module's
Paul Sokolovskyedc02bd2017-05-09 14:22:21 +0300430 // name to __main__ instead of real name). Do this only
431 // for *modules* however - packages never have their names
432 // replaced, instead they're -m'ed using a special __main__
433 // submodule in them. (This all apparently is done to not
434 // touch package name itself, which is important for future
435 // imports).
436 if (i == mod_len && fromtuple == mp_const_false && stat != MP_IMPORT_STAT_DIR) {
Damien George999cedb2015-11-27 17:01:44 +0000437 mp_obj_module_t *o = MP_OBJ_TO_PTR(module_obj);
438 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 +0300439 #if MICROPY_CPYTHON_COMPAT
Delio Brignoli21c719b2016-08-22 12:28:22 +0200440 // Store module as "__main__" in the dictionary of loaded modules (returned by sys.modules).
Paul Sokolovsky7ea3fa22016-09-20 17:55:42 +0300441 mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_loaded_modules_dict)), MP_OBJ_NEW_QSTR(MP_QSTR___main__), module_obj);
Ville Skyttäca16c382017-05-29 10:08:14 +0300442 // Store real name in "__main__" attribute. Chosen semi-randonly, to reuse existing qstr's.
Damien George999cedb2015-11-27 17:01:44 +0000443 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 +0300444 #endif
Paul Sokolovskye5035122014-10-25 21:16:24 +0300445 }
446
Damien Georgee09ffa12014-02-05 23:57:48 +0000447 if (stat == MP_IMPORT_STAT_DIR) {
Damien George0d3cb672015-01-28 23:43:01 +0000448 DEBUG_printf("%.*s is dir\n", vstr_len(&path), vstr_str(&path));
Chris Angelicodaf973a2014-06-06 03:51:03 +1000449 // https://docs.python.org/3/reference/import.html
Paul Sokolovskyf9589d22014-05-10 18:46:02 +0300450 // "Specifically, any module that contains a __path__ attribute is considered a package."
Damien George46017592017-11-16 13:17:51 +1100451 mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path)));
Damien Georgeb528e9a2017-01-08 20:17:23 +1100452 size_t orig_path_len = path.len;
Damien George354d15a2014-02-06 21:11:19 +0000453 vstr_add_char(&path, PATH_SEP_CHAR);
454 vstr_add_str(&path, "__init__.py");
Damien Georged9047d32016-12-13 15:09:48 +1100455 if (stat_file_py_or_mpy(&path) != MP_IMPORT_STAT_FILE) {
Paul Sokolovskyae184cb2016-07-02 14:45:49 +0300456 //mp_warning("%s is imported as namespace package", vstr_str(&path));
Paul Sokolovskya5854d22014-04-15 01:23:40 +0300457 } else {
458 do_load(module_obj, &path);
Damien Georgee09ffa12014-02-05 23:57:48 +0000459 }
Damien Georgeb528e9a2017-01-08 20:17:23 +1100460 path.len = orig_path_len;
Damien Georgee09ffa12014-02-05 23:57:48 +0000461 } else { // MP_IMPORT_STAT_FILE
Damien George354d15a2014-02-06 21:11:19 +0000462 do_load(module_obj, &path);
Damien Georged23834b2017-01-16 16:40:47 +1100463 // This should be the last component in the import path. If there are
464 // remaining components then it's an ImportError because the current path
465 // (the module that was just loaded) is not a package. This will be caught
466 // on the next iteration because the file will not exist.
Damien Georgee09ffa12014-02-05 23:57:48 +0000467 }
468 }
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200469 if (outer_module_obj != MP_OBJ_NULL) {
470 qstr s = qstr_from_strn(mod_str + last, i - last);
Damien Georged17926d2014-03-30 13:35:08 +0100471 mp_store_attr(outer_module_obj, s, module_obj);
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200472 }
473 outer_module_obj = module_obj;
474 if (top_module_obj == MP_OBJ_NULL) {
475 top_module_obj = module_obj;
476 }
477 last = i + 1;
Damien Georgee09ffa12014-02-05 23:57:48 +0000478 }
479 }
480
Paul Sokolovskyfb7f9432014-02-20 00:29:54 +0200481 // If fromlist is not empty, return leaf module
482 if (fromtuple != mp_const_none) {
483 return module_obj;
484 }
485 // Otherwise, we need to return top-level package
Paul Sokolovsky91ba7a52014-02-16 02:53:44 +0200486 return top_module_obj;
Damien George66028ab2014-01-03 14:03:48 +0000487}
Paul Sokolovsky1d938c92014-02-04 00:46:17 +0200488MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin___import___obj, 1, 5, mp_builtin___import__);