PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/py3k/Objects/moduleobject.c

https://github.com/jcsalterego/py3k-atsign
C | 414 lines | 356 code | 36 blank | 22 comment | 102 complexity | 394ab6184869b931cd576bf6d85dd1c4 MD5 | raw file
Possible License(s): 0BSD
  1. /* Module object implementation */
  2. #include "Python.h"
  3. #include "structmember.h"
  4. static Py_ssize_t max_module_number;
  5. typedef struct {
  6. PyObject_HEAD
  7. PyObject *md_dict;
  8. struct PyModuleDef *md_def;
  9. void *md_state;
  10. } PyModuleObject;
  11. static PyMemberDef module_members[] = {
  12. {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
  13. {0}
  14. };
  15. static PyTypeObject moduledef_type = {
  16. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  17. "moduledef", /* tp_name */
  18. sizeof(struct PyModuleDef), /* tp_size */
  19. 0, /* tp_itemsize */
  20. };
  21. PyObject *
  22. PyModule_New(const char *name)
  23. {
  24. PyModuleObject *m;
  25. PyObject *nameobj;
  26. m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
  27. if (m == NULL)
  28. return NULL;
  29. m->md_def = NULL;
  30. m->md_state = NULL;
  31. nameobj = PyUnicode_FromString(name);
  32. m->md_dict = PyDict_New();
  33. if (m->md_dict == NULL || nameobj == NULL)
  34. goto fail;
  35. if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0)
  36. goto fail;
  37. if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0)
  38. goto fail;
  39. if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0)
  40. goto fail;
  41. Py_DECREF(nameobj);
  42. PyObject_GC_Track(m);
  43. return (PyObject *)m;
  44. fail:
  45. Py_XDECREF(nameobj);
  46. Py_DECREF(m);
  47. return NULL;
  48. }
  49. static char api_version_warning[] =
  50. "Python C API version mismatch for module %.100s:\
  51. This Python has API version %d, module %.100s has version %d.";
  52. PyObject *
  53. PyModule_Create2(struct PyModuleDef* module, int module_api_version)
  54. {
  55. PyObject *d, *v, *n;
  56. PyMethodDef *ml;
  57. const char* name;
  58. PyModuleObject *m;
  59. if (!Py_IsInitialized())
  60. Py_FatalError("Interpreter not initialized (version mismatch?)");
  61. if (PyType_Ready(&moduledef_type) < 0)
  62. return NULL;
  63. if (module->m_base.m_index == 0) {
  64. max_module_number++;
  65. Py_REFCNT(module) = 1;
  66. Py_TYPE(module) = &moduledef_type;
  67. module->m_base.m_index = max_module_number;
  68. }
  69. name = module->m_name;
  70. if (module_api_version != PYTHON_API_VERSION) {
  71. char message[512];
  72. PyOS_snprintf(message, sizeof(message),
  73. api_version_warning, name,
  74. PYTHON_API_VERSION, name,
  75. module_api_version);
  76. if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1))
  77. return NULL;
  78. }
  79. /* Make sure name is fully qualified.
  80. This is a bit of a hack: when the shared library is loaded,
  81. the module name is "package.module", but the module calls
  82. PyModule_Create*() with just "module" for the name. The shared
  83. library loader squirrels away the true name of the module in
  84. _Py_PackageContext, and PyModule_Create*() will substitute this
  85. (if the name actually matches).
  86. */
  87. if (_Py_PackageContext != NULL) {
  88. char *p = strrchr(_Py_PackageContext, '.');
  89. if (p != NULL && strcmp(module->m_name, p+1) == 0) {
  90. name = _Py_PackageContext;
  91. _Py_PackageContext = NULL;
  92. }
  93. }
  94. if ((m = (PyModuleObject*)PyModule_New(name)) == NULL)
  95. return NULL;
  96. if (module->m_size > 0) {
  97. m->md_state = PyMem_MALLOC(module->m_size);
  98. if (!m->md_state) {
  99. PyErr_NoMemory();
  100. Py_DECREF(m);
  101. return NULL;
  102. }
  103. memset(m->md_state, 0, module->m_size);
  104. }
  105. d = PyModule_GetDict((PyObject*)m);
  106. if (module->m_methods != NULL) {
  107. n = PyUnicode_FromString(name);
  108. if (n == NULL)
  109. return NULL;
  110. for (ml = module->m_methods; ml->ml_name != NULL; ml++) {
  111. if ((ml->ml_flags & METH_CLASS) ||
  112. (ml->ml_flags & METH_STATIC)) {
  113. PyErr_SetString(PyExc_ValueError,
  114. "module functions cannot set"
  115. " METH_CLASS or METH_STATIC");
  116. Py_DECREF(n);
  117. return NULL;
  118. }
  119. v = PyCFunction_NewEx(ml, (PyObject*)m, n);
  120. if (v == NULL) {
  121. Py_DECREF(n);
  122. return NULL;
  123. }
  124. if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
  125. Py_DECREF(v);
  126. Py_DECREF(n);
  127. return NULL;
  128. }
  129. Py_DECREF(v);
  130. }
  131. Py_DECREF(n);
  132. }
  133. if (module->m_doc != NULL) {
  134. v = PyUnicode_FromString(module->m_doc);
  135. if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
  136. Py_XDECREF(v);
  137. return NULL;
  138. }
  139. Py_DECREF(v);
  140. }
  141. m->md_def = module;
  142. return (PyObject*)m;
  143. }
  144. PyObject *
  145. PyModule_GetDict(PyObject *m)
  146. {
  147. PyObject *d;
  148. if (!PyModule_Check(m)) {
  149. PyErr_BadInternalCall();
  150. return NULL;
  151. }
  152. d = ((PyModuleObject *)m) -> md_dict;
  153. if (d == NULL)
  154. ((PyModuleObject *)m) -> md_dict = d = PyDict_New();
  155. return d;
  156. }
  157. const char *
  158. PyModule_GetName(PyObject *m)
  159. {
  160. PyObject *d;
  161. PyObject *nameobj;
  162. if (!PyModule_Check(m)) {
  163. PyErr_BadArgument();
  164. return NULL;
  165. }
  166. d = ((PyModuleObject *)m)->md_dict;
  167. if (d == NULL ||
  168. (nameobj = PyDict_GetItemString(d, "__name__")) == NULL ||
  169. !PyUnicode_Check(nameobj))
  170. {
  171. PyErr_SetString(PyExc_SystemError, "nameless module");
  172. return NULL;
  173. }
  174. return _PyUnicode_AsString(nameobj);
  175. }
  176. const char *
  177. PyModule_GetFilename(PyObject *m)
  178. {
  179. PyObject *d;
  180. PyObject *fileobj;
  181. if (!PyModule_Check(m)) {
  182. PyErr_BadArgument();
  183. return NULL;
  184. }
  185. d = ((PyModuleObject *)m)->md_dict;
  186. if (d == NULL ||
  187. (fileobj = PyDict_GetItemString(d, "__file__")) == NULL ||
  188. !PyUnicode_Check(fileobj))
  189. {
  190. PyErr_SetString(PyExc_SystemError, "module filename missing");
  191. return NULL;
  192. }
  193. return _PyUnicode_AsString(fileobj);
  194. }
  195. PyModuleDef*
  196. PyModule_GetDef(PyObject* m)
  197. {
  198. if (!PyModule_Check(m)) {
  199. PyErr_BadArgument();
  200. return NULL;
  201. }
  202. return ((PyModuleObject *)m)->md_def;
  203. }
  204. void*
  205. PyModule_GetState(PyObject* m)
  206. {
  207. if (!PyModule_Check(m)) {
  208. PyErr_BadArgument();
  209. return NULL;
  210. }
  211. return ((PyModuleObject *)m)->md_state;
  212. }
  213. void
  214. _PyModule_Clear(PyObject *m)
  215. {
  216. /* To make the execution order of destructors for global
  217. objects a bit more predictable, we first zap all objects
  218. whose name starts with a single underscore, before we clear
  219. the entire dictionary. We zap them by replacing them with
  220. None, rather than deleting them from the dictionary, to
  221. avoid rehashing the dictionary (to some extent). */
  222. Py_ssize_t pos;
  223. PyObject *key, *value;
  224. PyObject *d;
  225. d = ((PyModuleObject *)m)->md_dict;
  226. if (d == NULL)
  227. return;
  228. /* First, clear only names starting with a single underscore */
  229. pos = 0;
  230. while (PyDict_Next(d, &pos, &key, &value)) {
  231. if (value != Py_None && PyUnicode_Check(key)) {
  232. const char *s = _PyUnicode_AsString(key);
  233. if (s[0] == '_' && s[1] != '_') {
  234. if (Py_VerboseFlag > 1)
  235. PySys_WriteStderr("# clear[1] %s\n", s);
  236. PyDict_SetItem(d, key, Py_None);
  237. }
  238. }
  239. }
  240. /* Next, clear all names except for __builtins__ */
  241. pos = 0;
  242. while (PyDict_Next(d, &pos, &key, &value)) {
  243. if (value != Py_None && PyUnicode_Check(key)) {
  244. const char *s = _PyUnicode_AsString(key);
  245. if (s[0] != '_' || strcmp(s, "__builtins__") != 0) {
  246. if (Py_VerboseFlag > 1)
  247. PySys_WriteStderr("# clear[2] %s\n", s);
  248. PyDict_SetItem(d, key, Py_None);
  249. }
  250. }
  251. }
  252. /* Note: we leave __builtins__ in place, so that destructors
  253. of non-global objects defined in this module can still use
  254. builtins, in particularly 'None'. */
  255. }
  256. /* Methods */
  257. static int
  258. module_init(PyModuleObject *m, PyObject *args, PyObject *kwds)
  259. {
  260. static char *kwlist[] = {"name", "doc", NULL};
  261. PyObject *dict, *name = Py_None, *doc = Py_None;
  262. if (!PyArg_ParseTupleAndKeywords(args, kwds, "U|O:module.__init__",
  263. kwlist, &name, &doc))
  264. return -1;
  265. dict = m->md_dict;
  266. if (dict == NULL) {
  267. dict = PyDict_New();
  268. if (dict == NULL)
  269. return -1;
  270. m->md_dict = dict;
  271. }
  272. if (PyDict_SetItemString(dict, "__name__", name) < 0)
  273. return -1;
  274. if (PyDict_SetItemString(dict, "__doc__", doc) < 0)
  275. return -1;
  276. return 0;
  277. }
  278. static void
  279. module_dealloc(PyModuleObject *m)
  280. {
  281. PyObject_GC_UnTrack(m);
  282. if (m->md_def && m->md_def->m_free)
  283. m->md_def->m_free(m);
  284. if (m->md_dict != NULL) {
  285. _PyModule_Clear((PyObject *)m);
  286. Py_DECREF(m->md_dict);
  287. }
  288. if (m->md_state != NULL)
  289. PyMem_FREE(m->md_state);
  290. Py_TYPE(m)->tp_free((PyObject *)m);
  291. }
  292. static PyObject *
  293. module_repr(PyModuleObject *m)
  294. {
  295. const char *name;
  296. const char *filename;
  297. name = PyModule_GetName((PyObject *)m);
  298. if (name == NULL) {
  299. PyErr_Clear();
  300. name = "?";
  301. }
  302. filename = PyModule_GetFilename((PyObject *)m);
  303. if (filename == NULL) {
  304. PyErr_Clear();
  305. return PyUnicode_FromFormat("<module '%s' (built-in)>", name);
  306. }
  307. return PyUnicode_FromFormat("<module '%s' from '%s'>", name, filename);
  308. }
  309. static int
  310. module_traverse(PyModuleObject *m, visitproc visit, void *arg)
  311. {
  312. if (m->md_def && m->md_def->m_traverse) {
  313. int res = m->md_def->m_traverse((PyObject*)m, visit, arg);
  314. if (res)
  315. return res;
  316. }
  317. Py_VISIT(m->md_dict);
  318. return 0;
  319. }
  320. static int
  321. module_clear(PyModuleObject *m)
  322. {
  323. if (m->md_def && m->md_def->m_clear) {
  324. int res = m->md_def->m_clear((PyObject*)m);
  325. if (res)
  326. return res;
  327. }
  328. Py_CLEAR(m->md_dict);
  329. return 0;
  330. }
  331. PyDoc_STRVAR(module_doc,
  332. "module(name[, doc])\n\
  333. \n\
  334. Create a module object.\n\
  335. The name must be a string; the optional doc argument can have any type.");
  336. PyTypeObject PyModule_Type = {
  337. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  338. "module", /* tp_name */
  339. sizeof(PyModuleObject), /* tp_size */
  340. 0, /* tp_itemsize */
  341. (destructor)module_dealloc, /* tp_dealloc */
  342. 0, /* tp_print */
  343. 0, /* tp_getattr */
  344. 0, /* tp_setattr */
  345. 0, /* tp_reserved */
  346. (reprfunc)module_repr, /* tp_repr */
  347. 0, /* tp_as_number */
  348. 0, /* tp_as_sequence */
  349. 0, /* tp_as_mapping */
  350. 0, /* tp_hash */
  351. 0, /* tp_call */
  352. 0, /* tp_str */
  353. PyObject_GenericGetAttr, /* tp_getattro */
  354. PyObject_GenericSetAttr, /* tp_setattro */
  355. 0, /* tp_as_buffer */
  356. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  357. Py_TPFLAGS_BASETYPE, /* tp_flags */
  358. module_doc, /* tp_doc */
  359. (traverseproc)module_traverse, /* tp_traverse */
  360. (inquiry)module_clear, /* tp_clear */
  361. 0, /* tp_richcompare */
  362. 0, /* tp_weaklistoffset */
  363. 0, /* tp_iter */
  364. 0, /* tp_iternext */
  365. 0, /* tp_methods */
  366. module_members, /* tp_members */
  367. 0, /* tp_getset */
  368. 0, /* tp_base */
  369. 0, /* tp_dict */
  370. 0, /* tp_descr_get */
  371. 0, /* tp_descr_set */
  372. offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
  373. (initproc)module_init, /* tp_init */
  374. PyType_GenericAlloc, /* tp_alloc */
  375. PyType_GenericNew, /* tp_new */
  376. PyObject_GC_Del, /* tp_free */
  377. };