builtinimport.c 18 KB

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