builtinimport.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013-2019 Damien P. George
  7. * Copyright (c) 2014 Paul Sokolovsky
  8. * Copyright (c) 2021 Jim Mussared
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11. * of this software and associated documentation files (the "Software"), to deal
  12. * in the Software without restriction, including without limitation the rights
  13. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. * copies of the Software, and to permit persons to whom the Software is
  15. * furnished to do so, subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software.
  19. *
  20. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. * THE SOFTWARE.
  27. */
  28. #include <stdio.h>
  29. #include <string.h>
  30. #include <assert.h>
  31. #include "py/compile.h"
  32. #include "py/objmodule.h"
  33. #include "py/persistentcode.h"
  34. #include "py/runtime.h"
  35. #include "py/builtin.h"
  36. #include "py/frozenmod.h"
  37. #if MICROPY_DEBUG_VERBOSE // print debugging info
  38. #define DEBUG_PRINT (1)
  39. #define DEBUG_printf DEBUG_printf
  40. #else // don't print debugging info
  41. #define DEBUG_PRINT (0)
  42. #define DEBUG_printf(...) (void)0
  43. #endif
  44. #if MICROPY_ENABLE_EXTERNAL_IMPORT
  45. // Must be a string of one byte.
  46. #define PATH_SEP_CHAR "/"
  47. // Virtual sys.path entry that maps to the frozen modules.
  48. #define MP_FROZEN_PATH_PREFIX ".frozen/"
  49. // Wrapper for mp_import_stat (which is provided by the port, and typically
  50. // uses mp_vfs_import_stat) to also search frozen modules. Given an exact
  51. // path to a file or directory (e.g. "foo/bar", foo/bar.py" or "foo/bar.mpy"),
  52. // will return whether the path is a file, directory, or doesn't exist.
  53. static mp_import_stat_t stat_path(vstr_t *path) {
  54. const char *str = vstr_null_terminated_str(path);
  55. #if MICROPY_MODULE_FROZEN
  56. // Only try and load as a frozen module if it starts with .frozen/.
  57. const int frozen_path_prefix_len = strlen(MP_FROZEN_PATH_PREFIX);
  58. if (strncmp(str, MP_FROZEN_PATH_PREFIX, frozen_path_prefix_len) == 0) {
  59. // Just stat (which is the return value), don't get the data.
  60. return mp_find_frozen_module(str + frozen_path_prefix_len, NULL, NULL);
  61. }
  62. #endif
  63. return mp_import_stat(str);
  64. }
  65. // Stat a given filesystem path to a .py file. If the file does not exist,
  66. // then attempt to stat the corresponding .mpy file, and update the path
  67. // argument. This is the logic that makes .py files take precedent over .mpy
  68. // files. This uses stat_path above, rather than mp_import_stat directly, so
  69. // that the .frozen path prefix is handled.
  70. static mp_import_stat_t stat_file_py_or_mpy(vstr_t *path) {
  71. mp_import_stat_t stat = stat_path(path);
  72. if (stat == MP_IMPORT_STAT_FILE) {
  73. return stat;
  74. }
  75. #if MICROPY_PERSISTENT_CODE_LOAD
  76. // Didn't find .py -- try the .mpy instead by inserting an 'm' into the '.py'.
  77. // Note: There's no point doing this if it's a frozen path, but adding the check
  78. // would be extra code, and no harm letting mp_find_frozen_module fail instead.
  79. vstr_ins_byte(path, path->len - 2, 'm');
  80. stat = stat_path(path);
  81. if (stat == MP_IMPORT_STAT_FILE) {
  82. return stat;
  83. }
  84. #endif
  85. return MP_IMPORT_STAT_NO_EXIST;
  86. }
  87. // Given an import path (e.g. "foo/bar"), try and find "foo/bar" (a directory)
  88. // or "foo/bar.(m)py" in either the filesystem or frozen modules. If the
  89. // result is a file, the path argument will be updated to include the file
  90. // extension.
  91. static mp_import_stat_t stat_module(vstr_t *path) {
  92. mp_import_stat_t stat = stat_path(path);
  93. DEBUG_printf("stat %s: %d\n", vstr_str(path), stat);
  94. if (stat == MP_IMPORT_STAT_DIR) {
  95. return stat;
  96. }
  97. // Not a directory, add .py and try as a file.
  98. vstr_add_str(path, ".py");
  99. return stat_file_py_or_mpy(path);
  100. }
  101. // Given a top-level module name, try and find it in each of the sys.path
  102. // entries. Note: On success, the dest argument will be updated to the matching
  103. // path (i.e. "<entry>/mod_name(.py)").
  104. static mp_import_stat_t stat_top_level(qstr mod_name, vstr_t *dest) {
  105. DEBUG_printf("stat_top_level: '%s'\n", qstr_str(mod_name));
  106. #if MICROPY_PY_SYS
  107. size_t path_num;
  108. mp_obj_t *path_items;
  109. mp_obj_get_array(mp_sys_path, &path_num, &path_items);
  110. // go through each sys.path entry, trying to import "<entry>/<mod_name>".
  111. for (size_t i = 0; i < path_num; i++) {
  112. vstr_reset(dest);
  113. size_t p_len;
  114. const char *p = mp_obj_str_get_data(path_items[i], &p_len);
  115. if (p_len > 0) {
  116. // Add the path separator (unless the entry is "", i.e. cwd).
  117. vstr_add_strn(dest, p, p_len);
  118. vstr_add_char(dest, PATH_SEP_CHAR[0]);
  119. }
  120. vstr_add_str(dest, qstr_str(mod_name));
  121. mp_import_stat_t stat = stat_module(dest);
  122. if (stat != MP_IMPORT_STAT_NO_EXIST) {
  123. return stat;
  124. }
  125. }
  126. // sys.path was empty or no matches, do not search the filesystem or
  127. // frozen code.
  128. return MP_IMPORT_STAT_NO_EXIST;
  129. #else
  130. // mp_sys_path is not enabled, so just stat the given path directly.
  131. vstr_add_str(dest, qstr_str(mod_name));
  132. return stat_module(dest);
  133. #endif
  134. }
  135. #if MICROPY_MODULE_FROZEN_STR || MICROPY_ENABLE_COMPILER
  136. static void do_load_from_lexer(mp_module_context_t *context, mp_lexer_t *lex) {
  137. #if MICROPY_PY___FILE__
  138. qstr source_name = lex->source_name;
  139. mp_store_attr(MP_OBJ_FROM_PTR(&context->module), MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
  140. #endif
  141. // parse, compile and execute the module in its context
  142. mp_obj_dict_t *mod_globals = context->module.globals;
  143. mp_parse_compile_execute(lex, MP_PARSE_FILE_INPUT, mod_globals, mod_globals);
  144. }
  145. #endif
  146. #if (MICROPY_HAS_FILE_READER && MICROPY_PERSISTENT_CODE_LOAD) || MICROPY_MODULE_FROZEN_MPY
  147. static void do_execute_proto_fun(const mp_module_context_t *context, mp_proto_fun_t proto_fun, qstr source_name) {
  148. #if MICROPY_PY___FILE__
  149. mp_store_attr(MP_OBJ_FROM_PTR(&context->module), MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
  150. #else
  151. (void)source_name;
  152. #endif
  153. // execute the module in its context
  154. mp_obj_dict_t *mod_globals = context->module.globals;
  155. // save context
  156. nlr_jump_callback_node_globals_locals_t ctx;
  157. ctx.globals = mp_globals_get();
  158. ctx.locals = mp_locals_get();
  159. // set new context
  160. mp_globals_set(mod_globals);
  161. mp_locals_set(mod_globals);
  162. // set exception handler to restore context if an exception is raised
  163. nlr_push_jump_callback(&ctx.callback, mp_globals_locals_set_from_nlr_jump_callback);
  164. // make and execute the function
  165. mp_obj_t module_fun = mp_make_function_from_proto_fun(proto_fun, context, NULL);
  166. mp_call_function_0(module_fun);
  167. // deregister exception handler and restore context
  168. nlr_pop_jump_callback(true);
  169. }
  170. #endif
  171. static void do_load(mp_module_context_t *module_obj, vstr_t *file) {
  172. #if MICROPY_MODULE_FROZEN || MICROPY_ENABLE_COMPILER || (MICROPY_PERSISTENT_CODE_LOAD && MICROPY_HAS_FILE_READER)
  173. const char *file_str = vstr_null_terminated_str(file);
  174. #endif
  175. // If we support frozen modules (either as str or mpy) then try to find the
  176. // requested filename in the list of frozen module filenames.
  177. #if MICROPY_MODULE_FROZEN
  178. void *modref;
  179. int frozen_type;
  180. const int frozen_path_prefix_len = strlen(MP_FROZEN_PATH_PREFIX);
  181. if (strncmp(file_str, MP_FROZEN_PATH_PREFIX, frozen_path_prefix_len) == 0) {
  182. mp_find_frozen_module(file_str + frozen_path_prefix_len, &frozen_type, &modref);
  183. // If we support frozen str modules and the compiler is enabled, and we
  184. // found the filename in the list of frozen files, then load and execute it.
  185. #if MICROPY_MODULE_FROZEN_STR
  186. if (frozen_type == MP_FROZEN_STR) {
  187. do_load_from_lexer(module_obj, modref);
  188. return;
  189. }
  190. #endif
  191. // If we support frozen mpy modules and we found a corresponding file (and
  192. // its data) in the list of frozen files, execute it.
  193. #if MICROPY_MODULE_FROZEN_MPY
  194. if (frozen_type == MP_FROZEN_MPY) {
  195. const mp_frozen_module_t *frozen = modref;
  196. module_obj->constants = frozen->constants;
  197. #if MICROPY_PY___FILE__
  198. qstr frozen_file_qstr = qstr_from_str(file_str + frozen_path_prefix_len);
  199. #else
  200. qstr frozen_file_qstr = MP_QSTRnull;
  201. #endif
  202. do_execute_proto_fun(module_obj, frozen->proto_fun, frozen_file_qstr);
  203. return;
  204. }
  205. #endif
  206. }
  207. #endif // MICROPY_MODULE_FROZEN
  208. qstr file_qstr = qstr_from_str(file_str);
  209. // If we support loading .mpy files then check if the file extension is of
  210. // the correct format and, if so, load and execute the file.
  211. #if MICROPY_HAS_FILE_READER && MICROPY_PERSISTENT_CODE_LOAD
  212. if (file_str[file->len - 3] == 'm') {
  213. mp_compiled_module_t cm;
  214. cm.context = module_obj;
  215. mp_raw_code_load_file(file_qstr, &cm);
  216. do_execute_proto_fun(cm.context, cm.rc, file_qstr);
  217. return;
  218. }
  219. #endif
  220. // If we can compile scripts then load the file and compile and execute it.
  221. #if MICROPY_ENABLE_COMPILER
  222. {
  223. mp_lexer_t *lex = mp_lexer_new_from_file(file_qstr);
  224. do_load_from_lexer(module_obj, lex);
  225. return;
  226. }
  227. #else
  228. // If we get here then the file was not frozen and we can't compile scripts.
  229. mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("script compilation not supported"));
  230. #endif
  231. }
  232. // Convert a relative (to the current module) import, going up "level" levels,
  233. // into an absolute import.
  234. static void evaluate_relative_import(mp_int_t level, const char **module_name, size_t *module_name_len) {
  235. // What we want to do here is to take the name of the current module,
  236. // remove <level> trailing components, and concatenate the passed-in
  237. // module name.
  238. // For example, level=3, module_name="foo.bar", __name__="a.b.c.d" --> "a.foo.bar"
  239. // "Relative imports use a module's __name__ attribute to determine that
  240. // module's position in the package hierarchy."
  241. // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
  242. mp_obj_t current_module_name_obj = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___name__));
  243. assert(current_module_name_obj != MP_OBJ_NULL);
  244. #if MICROPY_MODULE_OVERRIDE_MAIN_IMPORT && MICROPY_CPYTHON_COMPAT
  245. if (MP_OBJ_QSTR_VALUE(current_module_name_obj) == MP_QSTR___main__) {
  246. // This is a module loaded by -m command-line switch (e.g. unix port),
  247. // and so its __name__ has been set to "__main__". Get its real name
  248. // that we stored during import in the __main__ attribute.
  249. current_module_name_obj = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
  250. }
  251. #endif
  252. // If we have a __path__ in the globals dict, then we're a package.
  253. bool is_pkg = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP);
  254. #if DEBUG_PRINT
  255. DEBUG_printf("Current module/package: ");
  256. mp_obj_print_helper(MICROPY_DEBUG_PRINTER, current_module_name_obj, PRINT_REPR);
  257. DEBUG_printf(", is_package: %d", is_pkg);
  258. DEBUG_printf("\n");
  259. #endif
  260. size_t current_module_name_len;
  261. const char *current_module_name = mp_obj_str_get_data(current_module_name_obj, &current_module_name_len);
  262. const char *p = current_module_name + current_module_name_len;
  263. if (is_pkg) {
  264. // If we're evaluating relative to a package, then take off one fewer
  265. // level (i.e. the relative search starts inside the package, rather
  266. // than as a sibling of the package).
  267. --level;
  268. }
  269. // Walk back 'level' dots (or run out of path).
  270. while (level && p > current_module_name) {
  271. if (*--p == '.') {
  272. --level;
  273. }
  274. }
  275. // We must have some component left over to import from.
  276. if (p == current_module_name) {
  277. mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("can't perform relative import"));
  278. }
  279. // New length is len("<chopped path>.<module_name>"). Note: might be one byte
  280. // more than we need if module_name is empty (for the extra . we will
  281. // append).
  282. uint new_module_name_len = (size_t)(p - current_module_name) + 1 + *module_name_len;
  283. char *new_mod = mp_local_alloc(new_module_name_len);
  284. memcpy(new_mod, current_module_name, p - current_module_name);
  285. // Only append ".<module_name>" if there was one).
  286. if (*module_name_len != 0) {
  287. new_mod[p - current_module_name] = '.';
  288. memcpy(new_mod + (p - current_module_name) + 1, *module_name, *module_name_len);
  289. } else {
  290. --new_module_name_len;
  291. }
  292. // Copy into a QSTR.
  293. qstr new_mod_q = qstr_from_strn(new_mod, new_module_name_len);
  294. mp_local_free(new_mod);
  295. DEBUG_printf("Resolved base name for relative import: '%s'\n", qstr_str(new_mod_q));
  296. *module_name = qstr_str(new_mod_q);
  297. *module_name_len = new_module_name_len;
  298. }
  299. typedef struct _nlr_jump_callback_node_unregister_module_t {
  300. nlr_jump_callback_node_t callback;
  301. qstr name;
  302. } nlr_jump_callback_node_unregister_module_t;
  303. static void unregister_module_from_nlr_jump_callback(void *ctx_in) {
  304. nlr_jump_callback_node_unregister_module_t *ctx = ctx_in;
  305. mp_map_t *mp_loaded_modules_map = &MP_STATE_VM(mp_loaded_modules_dict).map;
  306. mp_map_lookup(mp_loaded_modules_map, MP_OBJ_NEW_QSTR(ctx->name), MP_MAP_LOOKUP_REMOVE_IF_FOUND);
  307. }
  308. // Load a module at the specified absolute path, possibly as a submodule of the given outer module.
  309. // full_mod_name: The full absolute path up to this level (e.g. "foo.bar.baz").
  310. // level_mod_name: The final component of the path (e.g. "baz").
  311. // outer_module_obj: The parent module (we need to store this module as an
  312. // attribute on it) (or MP_OBJ_NULL for top-level).
  313. // override_main: Whether to set the __name__ to "__main__" (and use __main__
  314. // for the actual path).
  315. static mp_obj_t process_import_at_level(qstr full_mod_name, qstr level_mod_name, mp_obj_t outer_module_obj, bool override_main) {
  316. // Immediately return if the module at this level is already loaded.
  317. mp_map_elem_t *elem;
  318. #if MICROPY_PY_SYS
  319. // If sys.path is empty, the intention is to force using a built-in. This
  320. // means we should also ignore any loaded modules with the same name
  321. // which may have come from the filesystem.
  322. size_t path_num;
  323. mp_obj_t *path_items;
  324. mp_obj_get_array(mp_sys_path, &path_num, &path_items);
  325. if (path_num)
  326. #endif
  327. {
  328. elem = mp_map_lookup(&MP_STATE_VM(mp_loaded_modules_dict).map, MP_OBJ_NEW_QSTR(full_mod_name), MP_MAP_LOOKUP);
  329. if (elem) {
  330. return elem->value;
  331. }
  332. }
  333. VSTR_FIXED(path, MICROPY_ALLOC_PATH_MAX);
  334. mp_import_stat_t stat = MP_IMPORT_STAT_NO_EXIST;
  335. mp_obj_t module_obj;
  336. if (outer_module_obj == MP_OBJ_NULL) {
  337. // First module in the dotted-name path.
  338. DEBUG_printf("Searching for top-level module\n");
  339. // An import of a non-extensible built-in will always bypass the
  340. // filesystem. e.g. `import micropython` or `import pyb`. So try and
  341. // match a non-extensible built-ins first.
  342. module_obj = mp_module_get_builtin(level_mod_name, false);
  343. if (module_obj != MP_OBJ_NULL) {
  344. return module_obj;
  345. }
  346. // Next try the filesystem. Search for a directory or file relative to
  347. // all the locations in sys.path.
  348. stat = stat_top_level(level_mod_name, &path);
  349. // If filesystem failed, now try and see if it matches an extensible
  350. // built-in module.
  351. if (stat == MP_IMPORT_STAT_NO_EXIST) {
  352. module_obj = mp_module_get_builtin(level_mod_name, true);
  353. if (module_obj != MP_OBJ_NULL) {
  354. return module_obj;
  355. }
  356. }
  357. } else {
  358. DEBUG_printf("Searching for sub-module\n");
  359. #if MICROPY_MODULE_BUILTIN_SUBPACKAGES
  360. // If the outer module is a built-in (because its map is in ROM), then
  361. // treat it like a package if it contains this submodule in its
  362. // globals dict.
  363. mp_obj_module_t *mod = MP_OBJ_TO_PTR(outer_module_obj);
  364. if (mod->globals->map.is_fixed) {
  365. elem = mp_map_lookup(&mod->globals->map, MP_OBJ_NEW_QSTR(level_mod_name), MP_MAP_LOOKUP);
  366. // Also verify that the entry in the globals dict is in fact a module.
  367. if (elem && mp_obj_is_type(elem->value, &mp_type_module)) {
  368. return elem->value;
  369. }
  370. }
  371. #endif
  372. // If the outer module is a package, it will have __path__ set.
  373. // We can use that as the path to search inside.
  374. mp_obj_t dest[2];
  375. mp_load_method_maybe(outer_module_obj, MP_QSTR___path__, dest);
  376. if (dest[0] != MP_OBJ_NULL) {
  377. // e.g. __path__ will be "<matched search path>/foo/bar"
  378. vstr_add_str(&path, mp_obj_str_get_str(dest[0]));
  379. // Add the level module name to the path to get "<matched search path>/foo/bar/baz".
  380. vstr_add_char(&path, PATH_SEP_CHAR[0]);
  381. vstr_add_str(&path, qstr_str(level_mod_name));
  382. stat = stat_module(&path);
  383. }
  384. }
  385. // Not already loaded, and not a built-in, so look at the stat result from the filesystem/frozen.
  386. if (stat == MP_IMPORT_STAT_NO_EXIST) {
  387. // Not found -- fail.
  388. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  389. mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("module not found"));
  390. #else
  391. mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("no module named '%q'"), full_mod_name);
  392. #endif
  393. }
  394. // Module was found on the filesystem/frozen, try and load it.
  395. DEBUG_printf("Found path to load: %.*s\n", (int)vstr_len(&path), vstr_str(&path));
  396. // Prepare for loading from the filesystem. Create a new shell module
  397. // and register it in sys.modules. Also make sure we remove it if
  398. // there is any problem below.
  399. module_obj = mp_obj_new_module(full_mod_name);
  400. nlr_jump_callback_node_unregister_module_t ctx;
  401. ctx.name = full_mod_name;
  402. nlr_push_jump_callback(&ctx.callback, unregister_module_from_nlr_jump_callback);
  403. #if MICROPY_MODULE_OVERRIDE_MAIN_IMPORT
  404. // If this module is being loaded via -m on unix, then
  405. // override __name__ to "__main__". Do this only for *modules*
  406. // however - packages never have their names replaced, instead
  407. // they're -m'ed using a special __main__ submodule in them. (This all
  408. // apparently is done to not touch the package name itself, which is
  409. // important for future imports).
  410. if (override_main && stat != MP_IMPORT_STAT_DIR) {
  411. mp_obj_module_t *o = MP_OBJ_TO_PTR(module_obj);
  412. mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
  413. #if MICROPY_CPYTHON_COMPAT
  414. // Store module as "__main__" in the dictionary of loaded modules (returned by sys.modules).
  415. mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_loaded_modules_dict)), MP_OBJ_NEW_QSTR(MP_QSTR___main__), module_obj);
  416. // Store real name in "__main__" attribute. Need this for
  417. // resolving relative imports later. "__main__ was chosen
  418. // semi-randonly, to reuse existing qstr's.
  419. mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___main__), MP_OBJ_NEW_QSTR(full_mod_name));
  420. #endif
  421. }
  422. #endif // MICROPY_MODULE_OVERRIDE_MAIN_IMPORT
  423. if (stat == MP_IMPORT_STAT_DIR) {
  424. // Directory (i.e. a package).
  425. DEBUG_printf("%.*s is dir\n", (int)vstr_len(&path), vstr_str(&path));
  426. // Store the __path__ attribute onto this module.
  427. // https://docs.python.org/3/reference/import.html
  428. // "Specifically, any module that contains a __path__ attribute is considered a package."
  429. // This gets used later to locate any subpackages of this module.
  430. mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path)));
  431. size_t orig_path_len = path.len;
  432. vstr_add_str(&path, PATH_SEP_CHAR "__init__.py");
  433. // execute "path/__init__.py" (if available).
  434. if (stat_file_py_or_mpy(&path) == MP_IMPORT_STAT_FILE) {
  435. do_load(MP_OBJ_TO_PTR(module_obj), &path);
  436. } else {
  437. // No-op. Nothing to load.
  438. // mp_warning("%s is imported as namespace package", vstr_str(&path));
  439. }
  440. // Remove /__init__.py suffix from path.
  441. path.len = orig_path_len;
  442. } else { // MP_IMPORT_STAT_FILE
  443. // File -- execute "path.(m)py".
  444. do_load(MP_OBJ_TO_PTR(module_obj), &path);
  445. // Note: This should be the last component in the import path. If
  446. // there are remaining components then in the next call to
  447. // process_import_at_level will detect that it doesn't have
  448. // a __path__ attribute, and not attempt to stat it.
  449. }
  450. if (outer_module_obj != MP_OBJ_NULL) {
  451. // If it's a sub-module then make it available on the parent module.
  452. mp_store_attr(outer_module_obj, level_mod_name, module_obj);
  453. }
  454. nlr_pop_jump_callback(false);
  455. return module_obj;
  456. }
  457. mp_obj_t mp_builtin___import___default(size_t n_args, const mp_obj_t *args) {
  458. #if DEBUG_PRINT
  459. DEBUG_printf("__import__:\n");
  460. for (size_t i = 0; i < n_args; i++) {
  461. DEBUG_printf(" ");
  462. mp_obj_print_helper(MICROPY_DEBUG_PRINTER, args[i], PRINT_REPR);
  463. DEBUG_printf("\n");
  464. }
  465. #endif
  466. // This is the import path, with any leading dots stripped.
  467. // "import foo.bar" --> module_name="foo.bar"
  468. // "from foo.bar import baz" --> module_name="foo.bar"
  469. // "from . import foo" --> module_name=""
  470. // "from ...foo.bar import baz" --> module_name="foo.bar"
  471. mp_obj_t module_name_obj = args[0];
  472. // These are the imported names.
  473. // i.e. "from foo.bar import baz, zap" --> fromtuple=("baz", "zap",)
  474. // Note: There's a special case on the Unix port, where this is set to mp_const_false which means that it's __main__.
  475. mp_obj_t fromtuple = mp_const_none;
  476. // Level is the number of leading dots in a relative import.
  477. // i.e. "from . import foo" --> level=1
  478. // i.e. "from ...foo.bar import baz" --> level=3
  479. mp_int_t level = 0;
  480. if (n_args >= 4) {
  481. fromtuple = args[3];
  482. if (n_args >= 5) {
  483. level = MP_OBJ_SMALL_INT_VALUE(args[4]);
  484. if (level < 0) {
  485. mp_raise_ValueError(NULL);
  486. }
  487. }
  488. }
  489. size_t module_name_len;
  490. const char *module_name = mp_obj_str_get_data(module_name_obj, &module_name_len);
  491. if (level != 0) {
  492. // Turn "foo.bar" with level=3 into "<current module 3 components>.foo.bar".
  493. // Current module name is extracted from globals().__name__.
  494. evaluate_relative_import(level, &module_name, &module_name_len);
  495. // module_name is now an absolute module path.
  496. }
  497. if (module_name_len == 0) {
  498. mp_raise_ValueError(NULL);
  499. }
  500. DEBUG_printf("Starting module search for '%s'\n", module_name);
  501. mp_obj_t top_module_obj = MP_OBJ_NULL;
  502. mp_obj_t outer_module_obj = MP_OBJ_NULL;
  503. // Iterate the absolute path, finding the end of each component of the path.
  504. // foo.bar.baz
  505. // ^ ^ ^
  506. size_t current_component_start = 0;
  507. for (size_t i = 1; i <= module_name_len; i++) {
  508. if (i == module_name_len || module_name[i] == '.') {
  509. // The module name up to this depth (e.g. foo.bar.baz).
  510. qstr full_mod_name = qstr_from_strn(module_name, i);
  511. // The current level name (e.g. baz).
  512. qstr level_mod_name = qstr_from_strn(module_name + current_component_start, i - current_component_start);
  513. DEBUG_printf("Processing module: '%s' at level '%s'\n", qstr_str(full_mod_name), qstr_str(level_mod_name));
  514. #if MICROPY_MODULE_OVERRIDE_MAIN_IMPORT
  515. // On unix, if this is being loaded via -m (indicated by sentinel
  516. // fromtuple=mp_const_false), then handle that if it's the final
  517. // component.
  518. bool override_main = (i == module_name_len && fromtuple == mp_const_false);
  519. #else
  520. bool override_main = false;
  521. #endif
  522. // Import this module.
  523. mp_obj_t module_obj = process_import_at_level(full_mod_name, level_mod_name, outer_module_obj, override_main);
  524. // Set this as the parent module, and remember the top-level module if it's the first.
  525. outer_module_obj = module_obj;
  526. if (top_module_obj == MP_OBJ_NULL) {
  527. top_module_obj = module_obj;
  528. }
  529. current_component_start = i + 1;
  530. }
  531. }
  532. if (fromtuple != mp_const_none) {
  533. // If fromtuple is not empty, return leaf module
  534. return outer_module_obj;
  535. } else {
  536. // Otherwise, we need to return top-level package
  537. return top_module_obj;
  538. }
  539. }
  540. #else // MICROPY_ENABLE_EXTERNAL_IMPORT
  541. mp_obj_t mp_builtin___import___default(size_t n_args, const mp_obj_t *args) {
  542. // Check that it's not a relative import.
  543. if (n_args >= 5 && MP_OBJ_SMALL_INT_VALUE(args[4]) != 0) {
  544. mp_raise_NotImplementedError(MP_ERROR_TEXT("relative import"));
  545. }
  546. // Check if the module is already loaded.
  547. mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_VM(mp_loaded_modules_dict).map, args[0], MP_MAP_LOOKUP);
  548. if (elem) {
  549. return elem->value;
  550. }
  551. // Try the name directly as a non-extensible built-in (e.g. `micropython`).
  552. qstr module_name_qstr = mp_obj_str_get_qstr(args[0]);
  553. mp_obj_t module_obj = mp_module_get_builtin(module_name_qstr, false);
  554. if (module_obj != MP_OBJ_NULL) {
  555. return module_obj;
  556. }
  557. // Now try as an extensible built-in (e.g. `time`).
  558. module_obj = mp_module_get_builtin(module_name_qstr, true);
  559. if (module_obj != MP_OBJ_NULL) {
  560. return module_obj;
  561. }
  562. // Couldn't find the module, so fail
  563. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  564. mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("module not found"));
  565. #else
  566. mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("no module named '%q'"), module_name_qstr);
  567. #endif
  568. }
  569. #endif // MICROPY_ENABLE_EXTERNAL_IMPORT
  570. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin___import___obj, 1, 5, mp_builtin___import__);