You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

897 lines
27 KiB

36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
PEP 227 implementation The majority of the changes are in the compiler. The mainloop changes primarily to implement the new opcodes and to pass a function's closure to eval_code2(). Frames and functions got new slots to hold the closure. Include/compile.h Add co_freevars and co_cellvars slots to code objects. Update PyCode_New() to take freevars and cellvars as arguments Include/funcobject.h Add func_closure slot to function objects. Add GetClosure()/SetClosure() functions (and corresponding macros) for getting at the closure. Include/frameobject.h PyFrame_New() now takes a closure. Include/opcode.h Add four new opcodes: MAKE_CLOSURE, LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF. Remove comment about old requirement for opcodes to fit in 7 bits. compile.c Implement changes to code objects for co_freevars and co_cellvars. Modify symbol table to use st_cur_name (string object for the name of the current scope) and st_cur_children (list of nested blocks). Also define st_nested, which might more properly be called st_cur_nested. Add several DEF_XXX flags to track def-use information for free variables. New or modified functions of note: com_make_closure(struct compiling *, PyCodeObject *) Emit LOAD_CLOSURE opcodes as needed to pass cells for free variables into nested scope. com_addop_varname(struct compiling *, int, char *) Emits opcodes for LOAD_DEREF and STORE_DEREF. get_ref_type(struct compiling *, char *name) Return NAME_CLOSURE if ref type is FREE or CELL symtable_load_symbols(struct compiling *) Decides what variables are cell or free based on def-use info. Can now raise SyntaxError if nested scopes are mixed with exec or from blah import *. make_scope_info(PyObject *, PyObject *, int, int) Helper functions for symtable scope stack. symtable_update_free_vars(struct symtable *) After a code block has been analyzed, it must check each of its children for free variables that are not defined in the block. If a variable is free in a child and not defined in the parent, then it is defined by block the enclosing the current one or it is a global. This does the right logic. symtable_add_use() is now a macro for symtable_add_def() symtable_assign(struct symtable *, node *) Use goto instead of for (;;) Fixed bug in symtable where name of keyword argument in function call was treated as assignment in the scope of the call site. Ex: def f(): g(a=2) # a was considered a local of f ceval.c eval_code2() now take one more argument, a closure. Implement LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF, MAKE_CLOSURE> Also: When name error occurs for global variable, report that the name was global in the error mesage. Objects/frameobject.c Initialize f_closure to be a tuple containing space for cellvars and freevars. f_closure is NULL if neither are present. Objects/funcobject.c Add support for func_closure. Python/import.c Change the magic number. Python/marshal.c Track changes to code objects.
25 years ago
PEP 227 implementation The majority of the changes are in the compiler. The mainloop changes primarily to implement the new opcodes and to pass a function's closure to eval_code2(). Frames and functions got new slots to hold the closure. Include/compile.h Add co_freevars and co_cellvars slots to code objects. Update PyCode_New() to take freevars and cellvars as arguments Include/funcobject.h Add func_closure slot to function objects. Add GetClosure()/SetClosure() functions (and corresponding macros) for getting at the closure. Include/frameobject.h PyFrame_New() now takes a closure. Include/opcode.h Add four new opcodes: MAKE_CLOSURE, LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF. Remove comment about old requirement for opcodes to fit in 7 bits. compile.c Implement changes to code objects for co_freevars and co_cellvars. Modify symbol table to use st_cur_name (string object for the name of the current scope) and st_cur_children (list of nested blocks). Also define st_nested, which might more properly be called st_cur_nested. Add several DEF_XXX flags to track def-use information for free variables. New or modified functions of note: com_make_closure(struct compiling *, PyCodeObject *) Emit LOAD_CLOSURE opcodes as needed to pass cells for free variables into nested scope. com_addop_varname(struct compiling *, int, char *) Emits opcodes for LOAD_DEREF and STORE_DEREF. get_ref_type(struct compiling *, char *name) Return NAME_CLOSURE if ref type is FREE or CELL symtable_load_symbols(struct compiling *) Decides what variables are cell or free based on def-use info. Can now raise SyntaxError if nested scopes are mixed with exec or from blah import *. make_scope_info(PyObject *, PyObject *, int, int) Helper functions for symtable scope stack. symtable_update_free_vars(struct symtable *) After a code block has been analyzed, it must check each of its children for free variables that are not defined in the block. If a variable is free in a child and not defined in the parent, then it is defined by block the enclosing the current one or it is a global. This does the right logic. symtable_add_use() is now a macro for symtable_add_def() symtable_assign(struct symtable *, node *) Use goto instead of for (;;) Fixed bug in symtable where name of keyword argument in function call was treated as assignment in the scope of the call site. Ex: def f(): g(a=2) # a was considered a local of f ceval.c eval_code2() now take one more argument, a closure. Implement LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF, MAKE_CLOSURE> Also: When name error occurs for global variable, report that the name was global in the error mesage. Objects/frameobject.c Initialize f_closure to be a tuple containing space for cellvars and freevars. f_closure is NULL if neither are present. Objects/funcobject.c Add support for func_closure. Python/import.c Change the magic number. Python/marshal.c Track changes to code objects.
25 years ago
PEP 227 implementation The majority of the changes are in the compiler. The mainloop changes primarily to implement the new opcodes and to pass a function's closure to eval_code2(). Frames and functions got new slots to hold the closure. Include/compile.h Add co_freevars and co_cellvars slots to code objects. Update PyCode_New() to take freevars and cellvars as arguments Include/funcobject.h Add func_closure slot to function objects. Add GetClosure()/SetClosure() functions (and corresponding macros) for getting at the closure. Include/frameobject.h PyFrame_New() now takes a closure. Include/opcode.h Add four new opcodes: MAKE_CLOSURE, LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF. Remove comment about old requirement for opcodes to fit in 7 bits. compile.c Implement changes to code objects for co_freevars and co_cellvars. Modify symbol table to use st_cur_name (string object for the name of the current scope) and st_cur_children (list of nested blocks). Also define st_nested, which might more properly be called st_cur_nested. Add several DEF_XXX flags to track def-use information for free variables. New or modified functions of note: com_make_closure(struct compiling *, PyCodeObject *) Emit LOAD_CLOSURE opcodes as needed to pass cells for free variables into nested scope. com_addop_varname(struct compiling *, int, char *) Emits opcodes for LOAD_DEREF and STORE_DEREF. get_ref_type(struct compiling *, char *name) Return NAME_CLOSURE if ref type is FREE or CELL symtable_load_symbols(struct compiling *) Decides what variables are cell or free based on def-use info. Can now raise SyntaxError if nested scopes are mixed with exec or from blah import *. make_scope_info(PyObject *, PyObject *, int, int) Helper functions for symtable scope stack. symtable_update_free_vars(struct symtable *) After a code block has been analyzed, it must check each of its children for free variables that are not defined in the block. If a variable is free in a child and not defined in the parent, then it is defined by block the enclosing the current one or it is a global. This does the right logic. symtable_add_use() is now a macro for symtable_add_def() symtable_assign(struct symtable *, node *) Use goto instead of for (;;) Fixed bug in symtable where name of keyword argument in function call was treated as assignment in the scope of the call site. Ex: def f(): g(a=2) # a was considered a local of f ceval.c eval_code2() now take one more argument, a closure. Implement LOAD_CLOSURE, LOAD_DEREF, STORE_DEREF, MAKE_CLOSURE> Also: When name error occurs for global variable, report that the name was global in the error mesage. Objects/frameobject.c Initialize f_closure to be a tuple containing space for cellvars and freevars. f_closure is NULL if neither are present. Objects/funcobject.c Add support for func_closure. Python/import.c Change the magic number. Python/marshal.c Track changes to code objects.
25 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
  1. /* Function object implementation */
  2. #include "Python.h"
  3. #include "code.h"
  4. #include "eval.h"
  5. #include "structmember.h"
  6. PyObject *
  7. PyFunction_New(PyObject *code, PyObject *globals)
  8. {
  9. PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
  10. &PyFunction_Type);
  11. static PyObject *__name__ = 0;
  12. if (op != NULL) {
  13. PyObject *doc;
  14. PyObject *consts;
  15. PyObject *module;
  16. op->func_weakreflist = NULL;
  17. Py_INCREF(code);
  18. op->func_code = code;
  19. Py_INCREF(globals);
  20. op->func_globals = globals;
  21. op->func_name = ((PyCodeObject *)code)->co_name;
  22. Py_INCREF(op->func_name);
  23. op->func_defaults = NULL; /* No default arguments */
  24. op->func_closure = NULL;
  25. consts = ((PyCodeObject *)code)->co_consts;
  26. if (PyTuple_Size(consts) >= 1) {
  27. doc = PyTuple_GetItem(consts, 0);
  28. if (!PyString_Check(doc) && !PyUnicode_Check(doc))
  29. doc = Py_None;
  30. }
  31. else
  32. doc = Py_None;
  33. Py_INCREF(doc);
  34. op->func_doc = doc;
  35. op->func_dict = NULL;
  36. op->func_module = NULL;
  37. /* __module__: If module name is in globals, use it.
  38. Otherwise, use None.
  39. */
  40. if (!__name__) {
  41. __name__ = PyString_InternFromString("__name__");
  42. if (!__name__) {
  43. Py_DECREF(op);
  44. return NULL;
  45. }
  46. }
  47. module = PyDict_GetItem(globals, __name__);
  48. if (module) {
  49. Py_INCREF(module);
  50. op->func_module = module;
  51. }
  52. }
  53. else
  54. return NULL;
  55. _PyObject_GC_TRACK(op);
  56. return (PyObject *)op;
  57. }
  58. PyObject *
  59. PyFunction_GetCode(PyObject *op)
  60. {
  61. if (!PyFunction_Check(op)) {
  62. PyErr_BadInternalCall();
  63. return NULL;
  64. }
  65. return ((PyFunctionObject *) op) -> func_code;
  66. }
  67. PyObject *
  68. PyFunction_GetGlobals(PyObject *op)
  69. {
  70. if (!PyFunction_Check(op)) {
  71. PyErr_BadInternalCall();
  72. return NULL;
  73. }
  74. return ((PyFunctionObject *) op) -> func_globals;
  75. }
  76. PyObject *
  77. PyFunction_GetModule(PyObject *op)
  78. {
  79. if (!PyFunction_Check(op)) {
  80. PyErr_BadInternalCall();
  81. return NULL;
  82. }
  83. return ((PyFunctionObject *) op) -> func_module;
  84. }
  85. PyObject *
  86. PyFunction_GetDefaults(PyObject *op)
  87. {
  88. if (!PyFunction_Check(op)) {
  89. PyErr_BadInternalCall();
  90. return NULL;
  91. }
  92. return ((PyFunctionObject *) op) -> func_defaults;
  93. }
  94. int
  95. PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
  96. {
  97. if (!PyFunction_Check(op)) {
  98. PyErr_BadInternalCall();
  99. return -1;
  100. }
  101. if (defaults == Py_None)
  102. defaults = NULL;
  103. else if (defaults && PyTuple_Check(defaults)) {
  104. Py_INCREF(defaults);
  105. }
  106. else {
  107. PyErr_SetString(PyExc_SystemError, "non-tuple default args");
  108. return -1;
  109. }
  110. Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
  111. ((PyFunctionObject *) op) -> func_defaults = defaults;
  112. return 0;
  113. }
  114. PyObject *
  115. PyFunction_GetClosure(PyObject *op)
  116. {
  117. if (!PyFunction_Check(op)) {
  118. PyErr_BadInternalCall();
  119. return NULL;
  120. }
  121. return ((PyFunctionObject *) op) -> func_closure;
  122. }
  123. int
  124. PyFunction_SetClosure(PyObject *op, PyObject *closure)
  125. {
  126. if (!PyFunction_Check(op)) {
  127. PyErr_BadInternalCall();
  128. return -1;
  129. }
  130. if (closure == Py_None)
  131. closure = NULL;
  132. else if (PyTuple_Check(closure)) {
  133. Py_INCREF(closure);
  134. }
  135. else {
  136. PyErr_Format(PyExc_SystemError,
  137. "expected tuple for closure, got '%.100s'",
  138. closure->ob_type->tp_name);
  139. return -1;
  140. }
  141. Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
  142. ((PyFunctionObject *) op) -> func_closure = closure;
  143. return 0;
  144. }
  145. /* Methods */
  146. #define OFF(x) offsetof(PyFunctionObject, x)
  147. static PyMemberDef func_memberlist[] = {
  148. {"func_closure", T_OBJECT, OFF(func_closure),
  149. RESTRICTED|READONLY},
  150. {"__closure__", T_OBJECT, OFF(func_closure),
  151. RESTRICTED|READONLY},
  152. {"func_doc", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
  153. {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
  154. {"func_globals", T_OBJECT, OFF(func_globals),
  155. RESTRICTED|READONLY},
  156. {"__globals__", T_OBJECT, OFF(func_globals),
  157. RESTRICTED|READONLY},
  158. {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED},
  159. {NULL} /* Sentinel */
  160. };
  161. static int
  162. restricted(void)
  163. {
  164. if (!PyEval_GetRestricted())
  165. return 0;
  166. PyErr_SetString(PyExc_RuntimeError,
  167. "function attributes not accessible in restricted mode");
  168. return 1;
  169. }
  170. static PyObject *
  171. func_get_dict(PyFunctionObject *op)
  172. {
  173. if (restricted())
  174. return NULL;
  175. if (op->func_dict == NULL) {
  176. op->func_dict = PyDict_New();
  177. if (op->func_dict == NULL)
  178. return NULL;
  179. }
  180. Py_INCREF(op->func_dict);
  181. return op->func_dict;
  182. }
  183. static int
  184. func_set_dict(PyFunctionObject *op, PyObject *value)
  185. {
  186. PyObject *tmp;
  187. if (restricted())
  188. return -1;
  189. /* It is illegal to del f.func_dict */
  190. if (value == NULL) {
  191. PyErr_SetString(PyExc_TypeError,
  192. "function's dictionary may not be deleted");
  193. return -1;
  194. }
  195. /* Can only set func_dict to a dictionary */
  196. if (!PyDict_Check(value)) {
  197. PyErr_SetString(PyExc_TypeError,
  198. "setting function's dictionary to a non-dict");
  199. return -1;
  200. }
  201. tmp = op->func_dict;
  202. Py_INCREF(value);
  203. op->func_dict = value;
  204. Py_XDECREF(tmp);
  205. return 0;
  206. }
  207. static PyObject *
  208. func_get_code(PyFunctionObject *op)
  209. {
  210. if (restricted())
  211. return NULL;
  212. Py_INCREF(op->func_code);
  213. return op->func_code;
  214. }
  215. static int
  216. func_set_code(PyFunctionObject *op, PyObject *value)
  217. {
  218. PyObject *tmp;
  219. Py_ssize_t nfree, nclosure;
  220. if (restricted())
  221. return -1;
  222. /* Not legal to del f.func_code or to set it to anything
  223. * other than a code object. */
  224. if (value == NULL || !PyCode_Check(value)) {
  225. PyErr_SetString(PyExc_TypeError,
  226. "__code__ must be set to a code object");
  227. return -1;
  228. }
  229. nfree = PyCode_GetNumFree((PyCodeObject *)value);
  230. nclosure = (op->func_closure == NULL ? 0 :
  231. PyTuple_GET_SIZE(op->func_closure));
  232. if (nclosure != nfree) {
  233. PyErr_Format(PyExc_ValueError,
  234. "%s() requires a code object with %zd free vars,"
  235. " not %zd",
  236. PyString_AsString(op->func_name),
  237. nclosure, nfree);
  238. return -1;
  239. }
  240. tmp = op->func_code;
  241. Py_INCREF(value);
  242. op->func_code = value;
  243. Py_DECREF(tmp);
  244. return 0;
  245. }
  246. static PyObject *
  247. func_get_name(PyFunctionObject *op)
  248. {
  249. Py_INCREF(op->func_name);
  250. return op->func_name;
  251. }
  252. static int
  253. func_set_name(PyFunctionObject *op, PyObject *value)
  254. {
  255. PyObject *tmp;
  256. if (restricted())
  257. return -1;
  258. /* Not legal to del f.func_name or to set it to anything
  259. * other than a string object. */
  260. if (value == NULL || !PyString_Check(value)) {
  261. PyErr_SetString(PyExc_TypeError,
  262. "__name__ must be set to a string object");
  263. return -1;
  264. }
  265. tmp = op->func_name;
  266. Py_INCREF(value);
  267. op->func_name = value;
  268. Py_DECREF(tmp);
  269. return 0;
  270. }
  271. static PyObject *
  272. func_get_defaults(PyFunctionObject *op)
  273. {
  274. if (restricted())
  275. return NULL;
  276. if (op->func_defaults == NULL) {
  277. Py_INCREF(Py_None);
  278. return Py_None;
  279. }
  280. Py_INCREF(op->func_defaults);
  281. return op->func_defaults;
  282. }
  283. static int
  284. func_set_defaults(PyFunctionObject *op, PyObject *value)
  285. {
  286. PyObject *tmp;
  287. if (restricted())
  288. return -1;
  289. /* Legal to del f.func_defaults.
  290. * Can only set func_defaults to NULL or a tuple. */
  291. if (value == Py_None)
  292. value = NULL;
  293. if (value != NULL && !PyTuple_Check(value)) {
  294. PyErr_SetString(PyExc_TypeError,
  295. "__defaults__ must be set to a tuple object");
  296. return -1;
  297. }
  298. tmp = op->func_defaults;
  299. Py_XINCREF(value);
  300. op->func_defaults = value;
  301. Py_XDECREF(tmp);
  302. return 0;
  303. }
  304. static PyGetSetDef func_getsetlist[] = {
  305. {"func_code", (getter)func_get_code, (setter)func_set_code},
  306. {"__code__", (getter)func_get_code, (setter)func_set_code},
  307. {"func_defaults", (getter)func_get_defaults,
  308. (setter)func_set_defaults},
  309. {"__defaults__", (getter)func_get_defaults,
  310. (setter)func_set_defaults},
  311. {"func_dict", (getter)func_get_dict, (setter)func_set_dict},
  312. {"__dict__", (getter)func_get_dict, (setter)func_set_dict},
  313. {"func_name", (getter)func_get_name, (setter)func_set_name},
  314. {"__name__", (getter)func_get_name, (setter)func_set_name},
  315. {NULL} /* Sentinel */
  316. };
  317. PyDoc_STRVAR(func_doc,
  318. "function(code, globals[, name[, argdefs[, closure]]])\n\
  319. \n\
  320. Create a function object from a code object and a dictionary.\n\
  321. The optional name string overrides the name from the code object.\n\
  322. The optional argdefs tuple specifies the default argument values.\n\
  323. The optional closure tuple supplies the bindings for free variables.");
  324. /* func_new() maintains the following invariants for closures. The
  325. closure must correspond to the free variables of the code object.
  326. if len(code.co_freevars) == 0:
  327. closure = NULL
  328. else:
  329. len(closure) == len(code.co_freevars)
  330. for every elt in closure, type(elt) == cell
  331. */
  332. static PyObject *
  333. func_new(PyTypeObject* type, PyObject* args, PyObject* kw)
  334. {
  335. PyCodeObject *code;
  336. PyObject *globals;
  337. PyObject *name = Py_None;
  338. PyObject *defaults = Py_None;
  339. PyObject *closure = Py_None;
  340. PyFunctionObject *newfunc;
  341. Py_ssize_t nfree, nclosure;
  342. static char *kwlist[] = {"code", "globals", "name",
  343. "argdefs", "closure", 0};
  344. if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function",
  345. kwlist,
  346. &PyCode_Type, &code,
  347. &PyDict_Type, &globals,
  348. &name, &defaults, &closure))
  349. return NULL;
  350. if (name != Py_None && !PyString_Check(name)) {
  351. PyErr_SetString(PyExc_TypeError,
  352. "arg 3 (name) must be None or string");
  353. return NULL;
  354. }
  355. if (defaults != Py_None && !PyTuple_Check(defaults)) {
  356. PyErr_SetString(PyExc_TypeError,
  357. "arg 4 (defaults) must be None or tuple");
  358. return NULL;
  359. }
  360. nfree = PyTuple_GET_SIZE(code->co_freevars);
  361. if (!PyTuple_Check(closure)) {
  362. if (nfree && closure == Py_None) {
  363. PyErr_SetString(PyExc_TypeError,
  364. "arg 5 (closure) must be tuple");
  365. return NULL;
  366. }
  367. else if (closure != Py_None) {
  368. PyErr_SetString(PyExc_TypeError,
  369. "arg 5 (closure) must be None or tuple");
  370. return NULL;
  371. }
  372. }
  373. /* check that the closure is well-formed */
  374. nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
  375. if (nfree != nclosure)
  376. return PyErr_Format(PyExc_ValueError,
  377. "%s requires closure of length %zd, not %zd",
  378. PyString_AS_STRING(code->co_name),
  379. nfree, nclosure);
  380. if (nclosure) {
  381. Py_ssize_t i;
  382. for (i = 0; i < nclosure; i++) {
  383. PyObject *o = PyTuple_GET_ITEM(closure, i);
  384. if (!PyCell_Check(o)) {
  385. return PyErr_Format(PyExc_TypeError,
  386. "arg 5 (closure) expected cell, found %s",
  387. o->ob_type->tp_name);
  388. }
  389. }
  390. }
  391. newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
  392. globals);
  393. if (newfunc == NULL)
  394. return NULL;
  395. if (name != Py_None) {
  396. Py_INCREF(name);
  397. Py_DECREF(newfunc->func_name);
  398. newfunc->func_name = name;
  399. }
  400. if (defaults != Py_None) {
  401. Py_INCREF(defaults);
  402. newfunc->func_defaults = defaults;
  403. }
  404. if (closure != Py_None) {
  405. Py_INCREF(closure);
  406. newfunc->func_closure = closure;
  407. }
  408. return (PyObject *)newfunc;
  409. }
  410. static void
  411. func_dealloc(PyFunctionObject *op)
  412. {
  413. _PyObject_GC_UNTRACK(op);
  414. if (op->func_weakreflist != NULL)
  415. PyObject_ClearWeakRefs((PyObject *) op);
  416. Py_DECREF(op->func_code);
  417. Py_DECREF(op->func_globals);
  418. Py_XDECREF(op->func_module);
  419. Py_DECREF(op->func_name);
  420. Py_XDECREF(op->func_defaults);
  421. Py_XDECREF(op->func_doc);
  422. Py_XDECREF(op->func_dict);
  423. Py_XDECREF(op->func_closure);
  424. PyObject_GC_Del(op);
  425. }
  426. static PyObject*
  427. func_repr(PyFunctionObject *op)
  428. {
  429. return PyString_FromFormat("<function %s at %p>",
  430. PyString_AsString(op->func_name),
  431. op);
  432. }
  433. static int
  434. func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
  435. {
  436. Py_VISIT(f->func_code);
  437. Py_VISIT(f->func_globals);
  438. Py_VISIT(f->func_module);
  439. Py_VISIT(f->func_defaults);
  440. Py_VISIT(f->func_doc);
  441. Py_VISIT(f->func_name);
  442. Py_VISIT(f->func_dict);
  443. Py_VISIT(f->func_closure);
  444. return 0;
  445. }
  446. static PyObject *
  447. function_call(PyObject *func, PyObject *arg, PyObject *kw)
  448. {
  449. PyObject *result;
  450. PyObject *argdefs;
  451. PyObject *kwtuple = NULL;
  452. PyObject **d, **k;
  453. Py_ssize_t nk, nd;
  454. argdefs = PyFunction_GET_DEFAULTS(func);
  455. if (argdefs != NULL && PyTuple_Check(argdefs)) {
  456. d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
  457. nd = PyTuple_GET_SIZE(argdefs);
  458. }
  459. else {
  460. d = NULL;
  461. nd = 0;
  462. }
  463. if (kw != NULL && PyDict_Check(kw)) {
  464. Py_ssize_t pos, i;
  465. nk = PyDict_Size(kw);
  466. kwtuple = PyTuple_New(2*nk);
  467. if (kwtuple == NULL)
  468. return NULL;
  469. k = &PyTuple_GET_ITEM(kwtuple, 0);
  470. pos = i = 0;
  471. while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) {
  472. Py_INCREF(k[i]);
  473. Py_INCREF(k[i+1]);
  474. i += 2;
  475. }
  476. nk = i/2;
  477. }
  478. else {
  479. k = NULL;
  480. nk = 0;
  481. }
  482. result = PyEval_EvalCodeEx(
  483. (PyCodeObject *)PyFunction_GET_CODE(func),
  484. PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
  485. &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg),
  486. k, nk, d, nd,
  487. PyFunction_GET_CLOSURE(func));
  488. Py_XDECREF(kwtuple);
  489. return result;
  490. }
  491. /* Bind a function to an object */
  492. static PyObject *
  493. func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
  494. {
  495. if (obj == Py_None)
  496. obj = NULL;
  497. return PyMethod_New(func, obj, type);
  498. }
  499. PyTypeObject PyFunction_Type = {
  500. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  501. "function",
  502. sizeof(PyFunctionObject),
  503. 0,
  504. (destructor)func_dealloc, /* tp_dealloc */
  505. 0, /* tp_print */
  506. 0, /* tp_getattr */
  507. 0, /* tp_setattr */
  508. 0, /* tp_compare */
  509. (reprfunc)func_repr, /* tp_repr */
  510. 0, /* tp_as_number */
  511. 0, /* tp_as_sequence */
  512. 0, /* tp_as_mapping */
  513. 0, /* tp_hash */
  514. function_call, /* tp_call */
  515. 0, /* tp_str */
  516. PyObject_GenericGetAttr, /* tp_getattro */
  517. PyObject_GenericSetAttr, /* tp_setattro */
  518. 0, /* tp_as_buffer */
  519. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  520. func_doc, /* tp_doc */
  521. (traverseproc)func_traverse, /* tp_traverse */
  522. 0, /* tp_clear */
  523. 0, /* tp_richcompare */
  524. offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
  525. 0, /* tp_iter */
  526. 0, /* tp_iternext */
  527. 0, /* tp_methods */
  528. func_memberlist, /* tp_members */
  529. func_getsetlist, /* tp_getset */
  530. 0, /* tp_base */
  531. 0, /* tp_dict */
  532. func_descr_get, /* tp_descr_get */
  533. 0, /* tp_descr_set */
  534. offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
  535. 0, /* tp_init */
  536. 0, /* tp_alloc */
  537. func_new, /* tp_new */
  538. };
  539. /* Class method object */
  540. /* A class method receives the class as implicit first argument,
  541. just like an instance method receives the instance.
  542. To declare a class method, use this idiom:
  543. class C:
  544. def f(cls, arg1, arg2, ...): ...
  545. f = classmethod(f)
  546. It can be called either on the class (e.g. C.f()) or on an instance
  547. (e.g. C().f()); the instance is ignored except for its class.
  548. If a class method is called for a derived class, the derived class
  549. object is passed as the implied first argument.
  550. Class methods are different than C++ or Java static methods.
  551. If you want those, see static methods below.
  552. */
  553. typedef struct {
  554. PyObject_HEAD
  555. PyObject *cm_callable;
  556. } classmethod;
  557. static void
  558. cm_dealloc(classmethod *cm)
  559. {
  560. _PyObject_GC_UNTRACK((PyObject *)cm);
  561. Py_XDECREF(cm->cm_callable);
  562. Py_TYPE(cm)->tp_free((PyObject *)cm);
  563. }
  564. static int
  565. cm_traverse(classmethod *cm, visitproc visit, void *arg)
  566. {
  567. Py_VISIT(cm->cm_callable);
  568. return 0;
  569. }
  570. static int
  571. cm_clear(classmethod *cm)
  572. {
  573. Py_CLEAR(cm->cm_callable);
  574. return 0;
  575. }
  576. static PyObject *
  577. cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  578. {
  579. classmethod *cm = (classmethod *)self;
  580. if (cm->cm_callable == NULL) {
  581. PyErr_SetString(PyExc_RuntimeError,
  582. "uninitialized classmethod object");
  583. return NULL;
  584. }
  585. if (type == NULL)
  586. type = (PyObject *)(Py_TYPE(obj));
  587. return PyMethod_New(cm->cm_callable,
  588. type, (PyObject *)(Py_TYPE(type)));
  589. }
  590. static int
  591. cm_init(PyObject *self, PyObject *args, PyObject *kwds)
  592. {
  593. classmethod *cm = (classmethod *)self;
  594. PyObject *callable;
  595. if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
  596. return -1;
  597. if (!_PyArg_NoKeywords("classmethod", kwds))
  598. return -1;
  599. Py_INCREF(callable);
  600. cm->cm_callable = callable;
  601. return 0;
  602. }
  603. static PyMemberDef cm_memberlist[] = {
  604. {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
  605. {NULL} /* Sentinel */
  606. };
  607. PyDoc_STRVAR(classmethod_doc,
  608. "classmethod(function) -> method\n\
  609. \n\
  610. Convert a function to be a class method.\n\
  611. \n\
  612. A class method receives the class as implicit first argument,\n\
  613. just like an instance method receives the instance.\n\
  614. To declare a class method, use this idiom:\n\
  615. \n\
  616. class C:\n\
  617. def f(cls, arg1, arg2, ...): ...\n\
  618. f = classmethod(f)\n\
  619. \n\
  620. It can be called either on the class (e.g. C.f()) or on an instance\n\
  621. (e.g. C().f()). The instance is ignored except for its class.\n\
  622. If a class method is called for a derived class, the derived class\n\
  623. object is passed as the implied first argument.\n\
  624. \n\
  625. Class methods are different than C++ or Java static methods.\n\
  626. If you want those, see the staticmethod builtin.");
  627. PyTypeObject PyClassMethod_Type = {
  628. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  629. "classmethod",
  630. sizeof(classmethod),
  631. 0,
  632. (destructor)cm_dealloc, /* tp_dealloc */
  633. 0, /* tp_print */
  634. 0, /* tp_getattr */
  635. 0, /* tp_setattr */
  636. 0, /* tp_compare */
  637. 0, /* tp_repr */
  638. 0, /* tp_as_number */
  639. 0, /* tp_as_sequence */
  640. 0, /* tp_as_mapping */
  641. 0, /* tp_hash */
  642. 0, /* tp_call */
  643. 0, /* tp_str */
  644. PyObject_GenericGetAttr, /* tp_getattro */
  645. 0, /* tp_setattro */
  646. 0, /* tp_as_buffer */
  647. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  648. classmethod_doc, /* tp_doc */
  649. (traverseproc)cm_traverse, /* tp_traverse */
  650. (inquiry)cm_clear, /* tp_clear */
  651. 0, /* tp_richcompare */
  652. 0, /* tp_weaklistoffset */
  653. 0, /* tp_iter */
  654. 0, /* tp_iternext */
  655. 0, /* tp_methods */
  656. cm_memberlist, /* tp_members */
  657. 0, /* tp_getset */
  658. 0, /* tp_base */
  659. 0, /* tp_dict */
  660. cm_descr_get, /* tp_descr_get */
  661. 0, /* tp_descr_set */
  662. 0, /* tp_dictoffset */
  663. cm_init, /* tp_init */
  664. PyType_GenericAlloc, /* tp_alloc */
  665. PyType_GenericNew, /* tp_new */
  666. PyObject_GC_Del, /* tp_free */
  667. };
  668. PyObject *
  669. PyClassMethod_New(PyObject *callable)
  670. {
  671. classmethod *cm = (classmethod *)
  672. PyType_GenericAlloc(&PyClassMethod_Type, 0);
  673. if (cm != NULL) {
  674. Py_INCREF(callable);
  675. cm->cm_callable = callable;
  676. }
  677. return (PyObject *)cm;
  678. }
  679. /* Static method object */
  680. /* A static method does not receive an implicit first argument.
  681. To declare a static method, use this idiom:
  682. class C:
  683. def f(arg1, arg2, ...): ...
  684. f = staticmethod(f)
  685. It can be called either on the class (e.g. C.f()) or on an instance
  686. (e.g. C().f()); the instance is ignored except for its class.
  687. Static methods in Python are similar to those found in Java or C++.
  688. For a more advanced concept, see class methods above.
  689. */
  690. typedef struct {
  691. PyObject_HEAD
  692. PyObject *sm_callable;
  693. } staticmethod;
  694. static void
  695. sm_dealloc(staticmethod *sm)
  696. {
  697. _PyObject_GC_UNTRACK((PyObject *)sm);
  698. Py_XDECREF(sm->sm_callable);
  699. Py_TYPE(sm)->tp_free((PyObject *)sm);
  700. }
  701. static int
  702. sm_traverse(staticmethod *sm, visitproc visit, void *arg)
  703. {
  704. Py_VISIT(sm->sm_callable);
  705. return 0;
  706. }
  707. static int
  708. sm_clear(staticmethod *sm)
  709. {
  710. Py_XDECREF(sm->sm_callable);
  711. sm->sm_callable = NULL;
  712. return 0;
  713. }
  714. static PyObject *
  715. sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  716. {
  717. staticmethod *sm = (staticmethod *)self;
  718. if (sm->sm_callable == NULL) {
  719. PyErr_SetString(PyExc_RuntimeError,
  720. "uninitialized staticmethod object");
  721. return NULL;
  722. }
  723. Py_INCREF(sm->sm_callable);
  724. return sm->sm_callable;
  725. }
  726. static int
  727. sm_init(PyObject *self, PyObject *args, PyObject *kwds)
  728. {
  729. staticmethod *sm = (staticmethod *)self;
  730. PyObject *callable;
  731. if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
  732. return -1;
  733. if (!_PyArg_NoKeywords("staticmethod", kwds))
  734. return -1;
  735. Py_INCREF(callable);
  736. sm->sm_callable = callable;
  737. return 0;
  738. }
  739. static PyMemberDef sm_memberlist[] = {
  740. {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
  741. {NULL} /* Sentinel */
  742. };
  743. PyDoc_STRVAR(staticmethod_doc,
  744. "staticmethod(function) -> method\n\
  745. \n\
  746. Convert a function to be a static method.\n\
  747. \n\
  748. A static method does not receive an implicit first argument.\n\
  749. To declare a static method, use this idiom:\n\
  750. \n\
  751. class C:\n\
  752. def f(arg1, arg2, ...): ...\n\
  753. f = staticmethod(f)\n\
  754. \n\
  755. It can be called either on the class (e.g. C.f()) or on an instance\n\
  756. (e.g. C().f()). The instance is ignored except for its class.\n\
  757. \n\
  758. Static methods in Python are similar to those found in Java or C++.\n\
  759. For a more advanced concept, see the classmethod builtin.");
  760. PyTypeObject PyStaticMethod_Type = {
  761. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  762. "staticmethod",
  763. sizeof(staticmethod),
  764. 0,
  765. (destructor)sm_dealloc, /* tp_dealloc */
  766. 0, /* tp_print */
  767. 0, /* tp_getattr */
  768. 0, /* tp_setattr */
  769. 0, /* tp_compare */
  770. 0, /* tp_repr */
  771. 0, /* tp_as_number */
  772. 0, /* tp_as_sequence */
  773. 0, /* tp_as_mapping */
  774. 0, /* tp_hash */
  775. 0, /* tp_call */
  776. 0, /* tp_str */
  777. PyObject_GenericGetAttr, /* tp_getattro */
  778. 0, /* tp_setattro */
  779. 0, /* tp_as_buffer */
  780. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  781. staticmethod_doc, /* tp_doc */
  782. (traverseproc)sm_traverse, /* tp_traverse */
  783. (inquiry)sm_clear, /* tp_clear */
  784. 0, /* tp_richcompare */
  785. 0, /* tp_weaklistoffset */
  786. 0, /* tp_iter */
  787. 0, /* tp_iternext */
  788. 0, /* tp_methods */
  789. sm_memberlist, /* tp_members */
  790. 0, /* tp_getset */
  791. 0, /* tp_base */
  792. 0, /* tp_dict */
  793. sm_descr_get, /* tp_descr_get */
  794. 0, /* tp_descr_set */
  795. 0, /* tp_dictoffset */
  796. sm_init, /* tp_init */
  797. PyType_GenericAlloc, /* tp_alloc */
  798. PyType_GenericNew, /* tp_new */
  799. PyObject_GC_Del, /* tp_free */
  800. };
  801. PyObject *
  802. PyStaticMethod_New(PyObject *callable)
  803. {
  804. staticmethod *sm = (staticmethod *)
  805. PyType_GenericAlloc(&PyStaticMethod_Type, 0);
  806. if (sm != NULL) {
  807. Py_INCREF(callable);
  808. sm->sm_callable = callable;
  809. }
  810. return (PyObject *)sm;
  811. }