builtinimport.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. * Copyright (c) 2014 Paul Sokolovsky
  8. *
  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. #include <stdio.h>
  28. #include <string.h>
  29. #include <assert.h>
  30. #include "py/compile.h"
  31. #include "py/objmodule.h"
  32. #include "py/persistentcode.h"
  33. #include "py/runtime.h"
  34. #include "py/builtin.h"
  35. #include "py/frozenmod.h"
  36. #if MICROPY_DEBUG_VERBOSE // print debugging info
  37. #define DEBUG_PRINT (1)
  38. #define DEBUG_printf DEBUG_printf
  39. #else // don't print debugging info
  40. #define DEBUG_PRINT (0)
  41. #define DEBUG_printf(...) (void)0
  42. #endif
  43. #if MICROPY_ENABLE_EXTERNAL_IMPORT
  44. #define PATH_SEP_CHAR '/'
  45. bool mp_obj_is_package(mp_obj_t module) {
  46. mp_obj_t dest[2];
  47. mp_load_method_maybe(module, MP_QSTR___path__, dest);
  48. return dest[0] != MP_OBJ_NULL;
  49. }
  50. // Stat either frozen or normal module by a given path
  51. // (whatever is available, if at all).
  52. STATIC mp_import_stat_t mp_import_stat_any(const char *path) {
  53. #if MICROPY_MODULE_FROZEN
  54. mp_import_stat_t st = mp_frozen_stat(path);
  55. if (st != MP_IMPORT_STAT_NO_EXIST) {
  56. return st;
  57. }
  58. #endif
  59. return mp_import_stat(path);
  60. }
  61. STATIC mp_import_stat_t stat_file_py_or_mpy(vstr_t *path) {
  62. mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
  63. if (stat == MP_IMPORT_STAT_FILE) {
  64. return stat;
  65. }
  66. #if MICROPY_PERSISTENT_CODE_LOAD
  67. vstr_ins_byte(path, path->len - 2, 'm');
  68. stat = mp_import_stat_any(vstr_null_terminated_str(path));
  69. if (stat == MP_IMPORT_STAT_FILE) {
  70. return stat;
  71. }
  72. #endif
  73. return MP_IMPORT_STAT_NO_EXIST;
  74. }
  75. STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) {
  76. mp_import_stat_t stat = mp_import_stat_any(vstr_null_terminated_str(path));
  77. DEBUG_printf("stat %s: %d\n", vstr_str(path), stat);
  78. if (stat == MP_IMPORT_STAT_DIR) {
  79. return stat;
  80. }
  81. // not a directory, add .py and try as a file
  82. vstr_add_str(path, ".py");
  83. return stat_file_py_or_mpy(path);
  84. }
  85. STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *dest) {
  86. #if MICROPY_PY_SYS
  87. // extract the list of paths
  88. size_t path_num;
  89. mp_obj_t *path_items;
  90. mp_obj_list_get(mp_sys_path, &path_num, &path_items);
  91. if (path_num == 0) {
  92. #endif
  93. // mp_sys_path is empty, so just use the given file name
  94. vstr_add_strn(dest, file_str, file_len);
  95. return stat_dir_or_file(dest);
  96. #if MICROPY_PY_SYS
  97. } else {
  98. // go through each path looking for a directory or file
  99. for (size_t i = 0; i < path_num; i++) {
  100. vstr_reset(dest);
  101. size_t p_len;
  102. const char *p = mp_obj_str_get_data(path_items[i], &p_len);
  103. if (p_len > 0) {
  104. vstr_add_strn(dest, p, p_len);
  105. vstr_add_char(dest, PATH_SEP_CHAR);
  106. }
  107. vstr_add_strn(dest, file_str, file_len);
  108. mp_import_stat_t stat = stat_dir_or_file(dest);
  109. if (stat != MP_IMPORT_STAT_NO_EXIST) {
  110. return stat;
  111. }
  112. }
  113. // could not find a directory or file
  114. return MP_IMPORT_STAT_NO_EXIST;
  115. }
  116. #endif
  117. }
  118. #if MICROPY_ENABLE_COMPILER
  119. STATIC void do_load_from_lexer(mp_obj_t module_obj, mp_lexer_t *lex) {
  120. #if MICROPY_PY___FILE__
  121. qstr source_name = lex->source_name;
  122. mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
  123. #endif
  124. // parse, compile and execute the module in its context
  125. mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj);
  126. mp_parse_compile_execute(lex, MP_PARSE_FILE_INPUT, mod_globals, mod_globals);
  127. }
  128. #endif
  129. #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_MODULE_FROZEN_MPY
  130. STATIC void do_execute_raw_code(mp_obj_t module_obj, mp_raw_code_t *raw_code) {
  131. #if MICROPY_PY___FILE__
  132. // TODO
  133. //qstr source_name = lex->source_name;
  134. //mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name));
  135. #endif
  136. // execute the module in its context
  137. mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj);
  138. // save context
  139. mp_obj_dict_t *volatile old_globals = mp_globals_get();
  140. mp_obj_dict_t *volatile old_locals = mp_locals_get();
  141. // set new context
  142. mp_globals_set(mod_globals);
  143. mp_locals_set(mod_globals);
  144. nlr_buf_t nlr;
  145. if (nlr_push(&nlr) == 0) {
  146. mp_obj_t module_fun = mp_make_function_from_raw_code(raw_code, MP_OBJ_NULL, MP_OBJ_NULL);
  147. mp_call_function_0(module_fun);
  148. // finish nlr block, restore context
  149. nlr_pop();
  150. mp_globals_set(old_globals);
  151. mp_locals_set(old_locals);
  152. } else {
  153. // exception; restore context and re-raise same exception
  154. mp_globals_set(old_globals);
  155. mp_locals_set(old_locals);
  156. nlr_jump(nlr.ret_val);
  157. }
  158. }
  159. #endif
  160. STATIC void do_load(mp_obj_t module_obj, vstr_t *file) {
  161. #if MICROPY_MODULE_FROZEN || MICROPY_PERSISTENT_CODE_LOAD || MICROPY_ENABLE_COMPILER
  162. char *file_str = vstr_null_terminated_str(file);
  163. #endif
  164. // If we support frozen modules (either as str or mpy) then try to find the
  165. // requested filename in the list of frozen module filenames.
  166. #if MICROPY_MODULE_FROZEN
  167. void *modref;
  168. int frozen_type = mp_find_frozen_module(file_str, file->len, &modref);
  169. #endif
  170. // If we support frozen str modules and the compiler is enabled, and we
  171. // found the filename in the list of frozen files, then load and execute it.
  172. #if MICROPY_MODULE_FROZEN_STR
  173. if (frozen_type == MP_FROZEN_STR) {
  174. do_load_from_lexer(module_obj, modref);
  175. return;
  176. }
  177. #endif
  178. // If we support frozen mpy modules and we found a corresponding file (and
  179. // its data) in the list of frozen files, execute it.
  180. #if MICROPY_MODULE_FROZEN_MPY
  181. if (frozen_type == MP_FROZEN_MPY) {
  182. do_execute_raw_code(module_obj, modref);
  183. return;
  184. }
  185. #endif
  186. // If we support loading .mpy files then check if the file extension is of
  187. // the correct format and, if so, load and execute the file.
  188. #if MICROPY_PERSISTENT_CODE_LOAD
  189. if (file_str[file->len - 3] == 'm') {
  190. mp_raw_code_t *raw_code = mp_raw_code_load_file(file_str);
  191. do_execute_raw_code(module_obj, raw_code);
  192. return;
  193. }
  194. #endif
  195. // If we can compile scripts then load the file and compile and execute it.
  196. #if MICROPY_ENABLE_COMPILER
  197. {
  198. mp_lexer_t *lex = mp_lexer_new_from_file(file_str);
  199. do_load_from_lexer(module_obj, lex);
  200. return;
  201. }
  202. #else
  203. // If we get here then the file was not frozen and we can't compile scripts.
  204. mp_raise_msg(&mp_type_ImportError, "script compilation not supported");
  205. #endif
  206. }
  207. STATIC void chop_component(const char *start, const char **end) {
  208. const char *p = *end;
  209. while (p > start) {
  210. if (*--p == '.') {
  211. *end = p;
  212. return;
  213. }
  214. }
  215. *end = p;
  216. }
  217. mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
  218. #if DEBUG_PRINT
  219. DEBUG_printf("__import__:\n");
  220. for (size_t i = 0; i < n_args; i++) {
  221. DEBUG_printf(" ");
  222. mp_obj_print(args[i], PRINT_REPR);
  223. DEBUG_printf("\n");
  224. }
  225. #endif
  226. mp_obj_t module_name = args[0];
  227. mp_obj_t fromtuple = mp_const_none;
  228. mp_int_t level = 0;
  229. if (n_args >= 4) {
  230. fromtuple = args[3];
  231. if (n_args >= 5) {
  232. level = MP_OBJ_SMALL_INT_VALUE(args[4]);
  233. if (level < 0) {
  234. mp_raise_ValueError(NULL);
  235. }
  236. }
  237. }
  238. size_t mod_len;
  239. const char *mod_str = mp_obj_str_get_data(module_name, &mod_len);
  240. if (level != 0) {
  241. // What we want to do here is to take name of current module,
  242. // chop <level> trailing components, and concatenate with passed-in
  243. // module name, thus resolving relative import name into absolute.
  244. // This even appears to be correct per
  245. // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name
  246. // "Relative imports use a module's __name__ attribute to determine that
  247. // module's position in the package hierarchy."
  248. level--;
  249. mp_obj_t this_name_q = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___name__));
  250. assert(this_name_q != MP_OBJ_NULL);
  251. #if MICROPY_CPYTHON_COMPAT
  252. if (MP_OBJ_QSTR_VALUE(this_name_q) == MP_QSTR___main__) {
  253. // This is a module run by -m command-line switch, get its real name from backup attribute
  254. this_name_q = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
  255. }
  256. #endif
  257. mp_map_t *globals_map = &mp_globals_get()->map;
  258. mp_map_elem_t *elem = mp_map_lookup(globals_map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP);
  259. bool is_pkg = (elem != NULL);
  260. #if DEBUG_PRINT
  261. DEBUG_printf("Current module/package: ");
  262. mp_obj_print(this_name_q, PRINT_REPR);
  263. DEBUG_printf(", is_package: %d", is_pkg);
  264. DEBUG_printf("\n");
  265. #endif
  266. size_t this_name_l;
  267. const char *this_name = mp_obj_str_get_data(this_name_q, &this_name_l);
  268. const char *p = this_name + this_name_l;
  269. if (!is_pkg) {
  270. // We have module, but relative imports are anchored at package, so
  271. // go there.
  272. chop_component(this_name, &p);
  273. }
  274. while (level--) {
  275. chop_component(this_name, &p);
  276. }
  277. // We must have some component left over to import from
  278. if (p == this_name) {
  279. mp_raise_ValueError("cannot perform relative import");
  280. }
  281. uint new_mod_l = (mod_len == 0 ? (size_t)(p - this_name) : (size_t)(p - this_name) + 1 + mod_len);
  282. char *new_mod = mp_local_alloc(new_mod_l);
  283. memcpy(new_mod, this_name, p - this_name);
  284. if (mod_len != 0) {
  285. new_mod[p - this_name] = '.';
  286. memcpy(new_mod + (p - this_name) + 1, mod_str, mod_len);
  287. }
  288. qstr new_mod_q = qstr_from_strn(new_mod, new_mod_l);
  289. mp_local_free(new_mod);
  290. DEBUG_printf("Resolved base name for relative import: '%s'\n", qstr_str(new_mod_q));
  291. module_name = MP_OBJ_NEW_QSTR(new_mod_q);
  292. mod_str = qstr_str(new_mod_q);
  293. mod_len = new_mod_l;
  294. }
  295. // check if module already exists
  296. qstr module_name_qstr = mp_obj_str_get_qstr(module_name);
  297. mp_obj_t module_obj = mp_module_get(module_name_qstr);
  298. if (module_obj != MP_OBJ_NULL) {
  299. DEBUG_printf("Module already loaded\n");
  300. // If it's not a package, return module right away
  301. char *p = strchr(mod_str, '.');
  302. if (p == NULL) {
  303. return module_obj;
  304. }
  305. // If fromlist is not empty, return leaf module
  306. if (fromtuple != mp_const_none) {
  307. return module_obj;
  308. }
  309. // Otherwise, we need to return top-level package
  310. qstr pkg_name = qstr_from_strn(mod_str, p - mod_str);
  311. return mp_module_get(pkg_name);
  312. }
  313. DEBUG_printf("Module not yet loaded\n");
  314. uint last = 0;
  315. VSTR_FIXED(path, MICROPY_ALLOC_PATH_MAX)
  316. module_obj = MP_OBJ_NULL;
  317. mp_obj_t top_module_obj = MP_OBJ_NULL;
  318. mp_obj_t outer_module_obj = MP_OBJ_NULL;
  319. uint i;
  320. for (i = 1; i <= mod_len; i++) {
  321. if (i == mod_len || mod_str[i] == '.') {
  322. // create a qstr for the module name up to this depth
  323. qstr mod_name = qstr_from_strn(mod_str, i);
  324. DEBUG_printf("Processing module: %s\n", qstr_str(mod_name));
  325. DEBUG_printf("Previous path: =%.*s=\n", vstr_len(&path), vstr_str(&path));
  326. // find the file corresponding to the module name
  327. mp_import_stat_t stat;
  328. if (vstr_len(&path) == 0) {
  329. // first module in the dotted-name; search for a directory or file
  330. stat = find_file(mod_str, i, &path);
  331. } else {
  332. // latter module in the dotted-name; append to path
  333. vstr_add_char(&path, PATH_SEP_CHAR);
  334. vstr_add_strn(&path, mod_str + last, i - last);
  335. stat = stat_dir_or_file(&path);
  336. }
  337. DEBUG_printf("Current path: %.*s\n", vstr_len(&path), vstr_str(&path));
  338. if (stat == MP_IMPORT_STAT_NO_EXIST) {
  339. #if MICROPY_MODULE_WEAK_LINKS
  340. // check if there is a weak link to this module
  341. if (i == mod_len) {
  342. 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);
  343. if (el == NULL) {
  344. goto no_exist;
  345. }
  346. // found weak linked module
  347. module_obj = el->value;
  348. mp_module_call_init(mod_name, module_obj);
  349. } else {
  350. no_exist:
  351. #else
  352. {
  353. #endif
  354. // couldn't find the file, so fail
  355. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  356. mp_raise_msg(&mp_type_ImportError, "module not found");
  357. } else {
  358. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError,
  359. "no module named '%q'", mod_name));
  360. }
  361. }
  362. } else {
  363. // found the file, so get the module
  364. module_obj = mp_module_get(mod_name);
  365. }
  366. if (module_obj == MP_OBJ_NULL) {
  367. // module not already loaded, so load it!
  368. module_obj = mp_obj_new_module(mod_name);
  369. // if args[3] (fromtuple) has magic value False, set up
  370. // this module for command-line "-m" option (set module's
  371. // name to __main__ instead of real name). Do this only
  372. // for *modules* however - packages never have their names
  373. // replaced, instead they're -m'ed using a special __main__
  374. // submodule in them. (This all apparently is done to not
  375. // touch package name itself, which is important for future
  376. // imports).
  377. if (i == mod_len && fromtuple == mp_const_false && stat != MP_IMPORT_STAT_DIR) {
  378. mp_obj_module_t *o = MP_OBJ_TO_PTR(module_obj);
  379. mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
  380. #if MICROPY_CPYTHON_COMPAT
  381. // Store module as "__main__" in the dictionary of loaded modules (returned by sys.modules).
  382. mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_loaded_modules_dict)), MP_OBJ_NEW_QSTR(MP_QSTR___main__), module_obj);
  383. // Store real name in "__main__" attribute. Chosen semi-randonly, to reuse existing qstr's.
  384. mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___main__), MP_OBJ_NEW_QSTR(mod_name));
  385. #endif
  386. }
  387. if (stat == MP_IMPORT_STAT_DIR) {
  388. DEBUG_printf("%.*s is dir\n", vstr_len(&path), vstr_str(&path));
  389. // https://docs.python.org/3/reference/import.html
  390. // "Specifically, any module that contains a __path__ attribute is considered a package."
  391. mp_store_attr(module_obj, MP_QSTR___path__, mp_obj_new_str(vstr_str(&path), vstr_len(&path)));
  392. size_t orig_path_len = path.len;
  393. vstr_add_char(&path, PATH_SEP_CHAR);
  394. vstr_add_str(&path, "__init__.py");
  395. if (stat_file_py_or_mpy(&path) != MP_IMPORT_STAT_FILE) {
  396. //mp_warning("%s is imported as namespace package", vstr_str(&path));
  397. } else {
  398. do_load(module_obj, &path);
  399. }
  400. path.len = orig_path_len;
  401. } else { // MP_IMPORT_STAT_FILE
  402. do_load(module_obj, &path);
  403. // This should be the last component in the import path. If there are
  404. // remaining components then it's an ImportError because the current path
  405. // (the module that was just loaded) is not a package. This will be caught
  406. // on the next iteration because the file will not exist.
  407. }
  408. }
  409. if (outer_module_obj != MP_OBJ_NULL) {
  410. qstr s = qstr_from_strn(mod_str + last, i - last);
  411. mp_store_attr(outer_module_obj, s, module_obj);
  412. }
  413. outer_module_obj = module_obj;
  414. if (top_module_obj == MP_OBJ_NULL) {
  415. top_module_obj = module_obj;
  416. }
  417. last = i + 1;
  418. }
  419. }
  420. // If fromlist is not empty, return leaf module
  421. if (fromtuple != mp_const_none) {
  422. return module_obj;
  423. }
  424. // Otherwise, we need to return top-level package
  425. return top_module_obj;
  426. }
  427. #else // MICROPY_ENABLE_EXTERNAL_IMPORT
  428. mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) {
  429. // Check that it's not a relative import
  430. if (n_args >= 5 && MP_OBJ_SMALL_INT_VALUE(args[4]) != 0) {
  431. mp_raise_NotImplementedError("relative import");
  432. }
  433. // Check if module already exists, and return it if it does
  434. qstr module_name_qstr = mp_obj_str_get_qstr(args[0]);
  435. mp_obj_t module_obj = mp_module_get(module_name_qstr);
  436. if (module_obj != MP_OBJ_NULL) {
  437. return module_obj;
  438. }
  439. #if MICROPY_MODULE_WEAK_LINKS
  440. // Check if there is a weak link to this module
  441. mp_map_elem_t *el = mp_map_lookup((mp_map_t*)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(module_name_qstr), MP_MAP_LOOKUP);
  442. if (el != NULL) {
  443. // Found weak-linked module
  444. mp_module_call_init(module_name_qstr, el->value);
  445. return el->value;
  446. }
  447. #endif
  448. // Couldn't find the module, so fail
  449. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  450. mp_raise_msg(&mp_type_ImportError, "module not found");
  451. } else {
  452. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError,
  453. "no module named '%q'", module_name_qstr));
  454. }
  455. }
  456. #endif // MICROPY_ENABLE_EXTERNAL_IMPORT
  457. MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin___import___obj, 1, 5, mp_builtin___import__);