PageRenderTime 74ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/Python/bltinmodule.c

http://unladen-swallow.googlecode.com/
C | 3422 lines | 2905 code | 391 blank | 126 comment | 788 complexity | b632a8d2725a3ea6685f72dcf2483fb7 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. /* Built-in functions */
  2. #include "Python.h"
  3. #include "Python-ast.h"
  4. #include "node.h"
  5. #include "code.h"
  6. #include "eval.h"
  7. #include "frameobject.h"
  8. #include <ctype.h>
  9. #ifdef RISCOS
  10. #include "unixstuff.h"
  11. #endif
  12. /* The default encoding used by the platform file system APIs
  13. Can remain NULL for all platforms that don't have such a concept
  14. */
  15. #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
  16. const char *Py_FileSystemDefaultEncoding = "mbcs";
  17. #elif defined(__APPLE__)
  18. const char *Py_FileSystemDefaultEncoding = "utf-8";
  19. #else
  20. const char *Py_FileSystemDefaultEncoding = NULL; /* use default */
  21. #endif
  22. /* Forward */
  23. static PyObject *filterstring(PyObject *, PyObject *);
  24. #ifdef Py_USING_UNICODE
  25. static PyObject *filterunicode(PyObject *, PyObject *);
  26. #endif
  27. static PyObject *filtertuple (PyObject *, PyObject *);
  28. static PyObject *
  29. builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
  30. {
  31. static char *kwlist[] = {"name", "globals", "locals", "fromlist",
  32. "level", 0};
  33. char *name;
  34. PyObject *globals = NULL;
  35. PyObject *locals = NULL;
  36. PyObject *fromlist = NULL;
  37. int level = -1;
  38. if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
  39. kwlist, &name, &globals, &locals, &fromlist, &level))
  40. return NULL;
  41. return PyImport_ImportModuleLevel(name, globals, locals,
  42. fromlist, level);
  43. }
  44. PyDoc_STRVAR(import_doc,
  45. "__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module\n\
  46. \n\
  47. Import a module. The globals are only used to determine the context;\n\
  48. they are not modified. The locals are currently unused. The fromlist\n\
  49. should be a list of names to emulate ``from name import ...'', or an\n\
  50. empty list to emulate ``import name''.\n\
  51. When importing a module from a package, note that __import__('A.B', ...)\n\
  52. returns package A when fromlist is empty, but its submodule B when\n\
  53. fromlist is not empty. Level is used to determine whether to perform \n\
  54. absolute or relative imports. -1 is the original strategy of attempting\n\
  55. both absolute and relative imports, 0 is absolute, a positive number\n\
  56. is the number of parent directories to search relative to the current module.");
  57. static PyObject *
  58. builtin_abs(PyObject *self, PyObject *v)
  59. {
  60. return PyNumber_Absolute(v);
  61. }
  62. PyDoc_STRVAR(abs_doc,
  63. "abs(number) -> number\n\
  64. \n\
  65. Return the absolute value of the argument.");
  66. static PyObject *
  67. builtin_all(PyObject *self, PyObject *v)
  68. {
  69. PyObject *it, *item;
  70. PyObject *(*iternext)(PyObject *);
  71. int cmp;
  72. it = PyObject_GetIter(v);
  73. if (it == NULL)
  74. return NULL;
  75. iternext = *Py_TYPE(it)->tp_iternext;
  76. for (;;) {
  77. item = iternext(it);
  78. if (item == NULL)
  79. break;
  80. cmp = PyObject_IsTrue(item);
  81. Py_DECREF(item);
  82. if (cmp < 0) {
  83. Py_DECREF(it);
  84. return NULL;
  85. }
  86. if (cmp == 0) {
  87. Py_DECREF(it);
  88. Py_RETURN_FALSE;
  89. }
  90. }
  91. Py_DECREF(it);
  92. if (PyErr_Occurred()) {
  93. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  94. PyErr_Clear();
  95. else
  96. return NULL;
  97. }
  98. Py_RETURN_TRUE;
  99. }
  100. PyDoc_STRVAR(all_doc,
  101. "all(iterable) -> bool\n\
  102. \n\
  103. Return True if bool(x) is True for all values x in the iterable.");
  104. static PyObject *
  105. builtin_any(PyObject *self, PyObject *v)
  106. {
  107. PyObject *it, *item;
  108. PyObject *(*iternext)(PyObject *);
  109. int cmp;
  110. it = PyObject_GetIter(v);
  111. if (it == NULL)
  112. return NULL;
  113. iternext = *Py_TYPE(it)->tp_iternext;
  114. for (;;) {
  115. item = iternext(it);
  116. if (item == NULL)
  117. break;
  118. cmp = PyObject_IsTrue(item);
  119. Py_DECREF(item);
  120. if (cmp < 0) {
  121. Py_DECREF(it);
  122. return NULL;
  123. }
  124. if (cmp == 1) {
  125. Py_DECREF(it);
  126. Py_RETURN_TRUE;
  127. }
  128. }
  129. Py_DECREF(it);
  130. if (PyErr_Occurred()) {
  131. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  132. PyErr_Clear();
  133. else
  134. return NULL;
  135. }
  136. Py_RETURN_FALSE;
  137. }
  138. PyDoc_STRVAR(any_doc,
  139. "any(iterable) -> bool\n\
  140. \n\
  141. Return True if bool(x) is True for any x in the iterable.");
  142. static PyObject *
  143. builtin_apply(PyObject *self, PyObject *func, PyObject *alist, PyObject *kwdict)
  144. {
  145. PyObject *t = NULL, *retval = NULL;
  146. if (PyErr_WarnPy3k("apply() not supported in 3.x; "
  147. "use func(*args, **kwargs)", 1) < 0)
  148. return NULL;
  149. if (alist != NULL) {
  150. if (!PyTuple_Check(alist)) {
  151. if (!PySequence_Check(alist)) {
  152. PyErr_Format(PyExc_TypeError,
  153. "apply() arg 2 expected sequence, found %s",
  154. alist->ob_type->tp_name);
  155. return NULL;
  156. }
  157. t = PySequence_Tuple(alist);
  158. if (t == NULL)
  159. return NULL;
  160. alist = t;
  161. }
  162. }
  163. if (kwdict != NULL && !PyDict_Check(kwdict)) {
  164. PyErr_Format(PyExc_TypeError,
  165. "apply() arg 3 expected dictionary, found %s",
  166. kwdict->ob_type->tp_name);
  167. goto finally;
  168. }
  169. retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
  170. finally:
  171. Py_XDECREF(t);
  172. return retval;
  173. }
  174. PyDoc_STRVAR(apply_doc,
  175. "apply(object[, args[, kwargs]]) -> value\n\
  176. \n\
  177. Call a callable object with positional arguments taken from the tuple args,\n\
  178. and keyword arguments taken from the optional dictionary kwargs.\n\
  179. Note that classes are callable, as are instances with a __call__() method.\n\
  180. \n\
  181. Deprecated since release 2.3. Instead, use the extended call syntax:\n\
  182. function(*args, **keywords).");
  183. static PyObject *
  184. builtin_bin(PyObject *self, PyObject *v)
  185. {
  186. return PyNumber_ToBase(v, 2);
  187. }
  188. PyDoc_STRVAR(bin_doc,
  189. "bin(number) -> string\n\
  190. \n\
  191. Return the binary representation of an integer or long integer.");
  192. static PyObject *
  193. builtin_buildclass(PyObject *self, PyObject *name, PyObject *bases,
  194. PyObject *methods)
  195. {
  196. PyObject *metaclass = NULL, *result, *base;
  197. if (PyDict_Check(methods))
  198. metaclass = PyDict_GetItemString(methods, "__metaclass__");
  199. if (metaclass != NULL)
  200. Py_INCREF(metaclass);
  201. else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
  202. base = PyTuple_GET_ITEM(bases, 0);
  203. metaclass = PyObject_GetAttrString(base, "__class__");
  204. if (metaclass == NULL) {
  205. PyErr_Clear();
  206. metaclass = (PyObject *)base->ob_type;
  207. Py_INCREF(metaclass);
  208. }
  209. }
  210. else {
  211. PyObject *g = PyEval_GetGlobals();
  212. if (g != NULL && PyDict_Check(g))
  213. metaclass = PyDict_GetItemString(g, "__metaclass__");
  214. if (metaclass == NULL)
  215. metaclass = (PyObject *) &PyClass_Type;
  216. Py_INCREF(metaclass);
  217. }
  218. result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods,
  219. NULL);
  220. Py_DECREF(metaclass);
  221. if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
  222. /* A type error here likely means that the user passed
  223. in a base that was not a class (such the random module
  224. instead of the random.random type). Help them out
  225. by augmenting the error message with more information.*/
  226. PyObject *ptype, *pvalue, *ptraceback;
  227. PyErr_Fetch(&ptype, &pvalue, &ptraceback);
  228. if (PyString_Check(pvalue)) {
  229. PyObject *newmsg;
  230. newmsg = PyString_FromFormat(
  231. "Error when calling the metaclass bases\n"
  232. " %s",
  233. PyString_AS_STRING(pvalue));
  234. if (newmsg != NULL) {
  235. Py_DECREF(pvalue);
  236. pvalue = newmsg;
  237. }
  238. }
  239. PyErr_Restore(ptype, pvalue, ptraceback);
  240. }
  241. return result;
  242. }
  243. PyDoc_STRVAR(buildclass_doc,
  244. "#@buildclass(name, bases, methods) -> class\n\
  245. \n\
  246. Build a class. For internal use only.");
  247. static PyObject *
  248. builtin_callable(PyObject *self, PyObject *v)
  249. {
  250. if (PyErr_WarnPy3k("callable() not supported in 3.x; "
  251. "use hasattr(o, '__call__')", 1) < 0)
  252. return NULL;
  253. return PyBool_FromLong((long)PyCallable_Check(v));
  254. }
  255. PyDoc_STRVAR(callable_doc,
  256. "callable(object) -> bool\n\
  257. \n\
  258. Return whether the object is callable (i.e., some kind of function).\n\
  259. Note that classes are callable, as are instances with a __call__() method.");
  260. static PyObject *
  261. builtin_displayhook(PyObject *self, PyObject *args)
  262. {
  263. PyObject *displayhook, *result;
  264. displayhook = PySys_GetObject("displayhook");
  265. if (displayhook == NULL) {
  266. PyErr_SetString(PyExc_RuntimeError, "lost sys.displayhook");
  267. return NULL;
  268. }
  269. result = PyEval_CallObject(displayhook, args);
  270. Py_XDECREF(result);
  271. if (result == NULL)
  272. return NULL;
  273. Py_RETURN_NONE;
  274. }
  275. PyDoc_STRVAR(displayhook_doc,
  276. "#@displayhook(object) -> None\n\
  277. \n\
  278. Print an object using sys.displayhook(). For internal use only.");
  279. static PyObject *
  280. builtin_exec(PyObject *self, PyObject *prog, PyObject *globals,
  281. PyObject *locals)
  282. {
  283. int n;
  284. PyObject *v, *builtins_dict;
  285. PyFrameObject *f;
  286. int plain = 0;
  287. if (globals == NULL)
  288. globals = Py_None;
  289. if (locals == NULL)
  290. locals = Py_None;
  291. f = PyThreadState_Get()->frame;
  292. if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
  293. ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
  294. /* Backward compatibility hack */
  295. globals = PyTuple_GetItem(prog, 1);
  296. if (n == 3)
  297. locals = PyTuple_GetItem(prog, 2);
  298. prog = PyTuple_GetItem(prog, 0);
  299. }
  300. if (globals == Py_None) {
  301. globals = PyEval_GetGlobals();
  302. if (locals == Py_None) {
  303. locals = PyEval_GetLocals();
  304. plain = 1;
  305. }
  306. if (!globals || !locals) {
  307. PyErr_SetString(PyExc_SystemError,
  308. "globals and locals cannot be NULL");
  309. return NULL;
  310. }
  311. }
  312. else if (locals == Py_None)
  313. locals = globals;
  314. if (!PyString_Check(prog) &&
  315. !PyUnicode_Check(prog) &&
  316. !PyCode_Check(prog) &&
  317. !PyFile_Check(prog)) {
  318. PyErr_SetString(PyExc_TypeError,
  319. "exec: arg 1 must be a string, file, or code object");
  320. return NULL;
  321. }
  322. if (!PyDict_Check(globals)) {
  323. PyErr_SetString(PyExc_TypeError,
  324. "exec: arg 2 must be a dictionary or None");
  325. return NULL;
  326. }
  327. if (!PyMapping_Check(locals)) {
  328. PyErr_SetString(PyExc_TypeError,
  329. "exec: arg 3 must be a mapping or None");
  330. return NULL;
  331. }
  332. builtins_dict = PyDict_GetItemString(globals, "__builtins__");
  333. if (builtins_dict == NULL)
  334. PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
  335. if (PyCode_Check(prog)) {
  336. if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
  337. PyErr_SetString(PyExc_TypeError,
  338. "code object passed to exec may not contain free variables");
  339. return NULL;
  340. }
  341. v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
  342. }
  343. else if (PyFile_Check(prog)) {
  344. FILE *fp = PyFile_AsFile(prog);
  345. char *name = PyString_AsString(PyFile_Name(prog));
  346. PyCompilerFlags cf;
  347. if (name == NULL)
  348. return NULL;
  349. cf.cf_flags = 0;
  350. if (PyEval_MergeCompilerFlags(&cf))
  351. v = PyRun_FileFlags(fp, name, Py_file_input, globals,
  352. locals, &cf);
  353. else
  354. v = PyRun_File(fp, name, Py_file_input, globals,
  355. locals);
  356. }
  357. else {
  358. PyObject *tmp = NULL;
  359. char *str;
  360. PyCompilerFlags cf;
  361. cf.cf_flags = 0;
  362. #ifdef Py_USING_UNICODE
  363. if (PyUnicode_Check(prog)) {
  364. tmp = PyUnicode_AsUTF8String(prog);
  365. if (tmp == NULL)
  366. return NULL;
  367. prog = tmp;
  368. cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
  369. }
  370. #endif
  371. if (PyString_AsStringAndSize(prog, &str, NULL))
  372. return NULL;
  373. if (PyEval_MergeCompilerFlags(&cf))
  374. v = PyRun_StringFlags(str, Py_file_input, globals,
  375. locals, &cf);
  376. else
  377. v = PyRun_String(str, Py_file_input, globals, locals);
  378. Py_XDECREF(tmp);
  379. }
  380. if (plain)
  381. PyFrame_LocalsToFast(f, 0);
  382. if (v == NULL)
  383. return NULL;
  384. Py_DECREF(v);
  385. Py_RETURN_NONE;
  386. }
  387. PyDoc_STRVAR(exec_doc,
  388. "#@exec(program, [globals, [locals]]) -> None\n\
  389. \n\
  390. Execute Python code. For internal use only.");
  391. static PyObject *
  392. builtin_filter(PyObject *self, PyObject *func, PyObject *seq)
  393. {
  394. PyObject *result, *it, *arg;
  395. Py_ssize_t len; /* guess for result list size */
  396. register Py_ssize_t j;
  397. /* Strings and tuples return a result of the same type. */
  398. if (PyString_Check(seq))
  399. return filterstring(func, seq);
  400. #ifdef Py_USING_UNICODE
  401. if (PyUnicode_Check(seq))
  402. return filterunicode(func, seq);
  403. #endif
  404. if (PyTuple_Check(seq))
  405. return filtertuple(func, seq);
  406. /* Pre-allocate argument list tuple. */
  407. arg = PyTuple_New(1);
  408. if (arg == NULL)
  409. return NULL;
  410. /* Get iterator. */
  411. it = PyObject_GetIter(seq);
  412. if (it == NULL)
  413. goto Fail_arg;
  414. /* Guess a result list size. */
  415. len = _PyObject_LengthHint(seq, 8);
  416. if (len == -1)
  417. goto Fail_it;
  418. /* Get a result list. */
  419. if (PyList_Check(seq) && seq->ob_refcnt == 1) {
  420. /* Eww - can modify the list in-place. */
  421. Py_INCREF(seq);
  422. result = seq;
  423. }
  424. else {
  425. result = PyList_New(len);
  426. if (result == NULL)
  427. goto Fail_it;
  428. }
  429. /* Build the result list. */
  430. j = 0;
  431. for (;;) {
  432. PyObject *item;
  433. int ok;
  434. item = PyIter_Next(it);
  435. if (item == NULL) {
  436. if (PyErr_Occurred())
  437. goto Fail_result_it;
  438. break;
  439. }
  440. if (func == (PyObject *)&PyBool_Type || func == Py_None) {
  441. ok = PyObject_IsTrue(item);
  442. }
  443. else {
  444. PyObject *good;
  445. PyTuple_SET_ITEM(arg, 0, item);
  446. good = PyObject_Call(func, arg, NULL);
  447. PyTuple_SET_ITEM(arg, 0, NULL);
  448. if (good == NULL) {
  449. Py_DECREF(item);
  450. goto Fail_result_it;
  451. }
  452. ok = PyObject_IsTrue(good);
  453. Py_DECREF(good);
  454. }
  455. if (ok) {
  456. if (j < len)
  457. PyList_SET_ITEM(result, j, item);
  458. else {
  459. int status = PyList_Append(result, item);
  460. Py_DECREF(item);
  461. if (status < 0)
  462. goto Fail_result_it;
  463. }
  464. ++j;
  465. }
  466. else
  467. Py_DECREF(item);
  468. }
  469. /* Cut back result list if len is too big. */
  470. if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
  471. goto Fail_result_it;
  472. Py_DECREF(it);
  473. Py_DECREF(arg);
  474. return result;
  475. Fail_result_it:
  476. Py_DECREF(result);
  477. Fail_it:
  478. Py_DECREF(it);
  479. Fail_arg:
  480. Py_DECREF(arg);
  481. return NULL;
  482. }
  483. PyDoc_STRVAR(filter_doc,
  484. "filter(function or None, sequence) -> list, tuple, or string\n"
  485. "\n"
  486. "Return those items of sequence for which function(item) is true. If\n"
  487. "function is None, return the items that are true. If sequence is a tuple\n"
  488. "or string, return the same type, else return a list.");
  489. static PyObject *
  490. builtin_format(PyObject *self, PyObject *value, PyObject *format_spec)
  491. {
  492. return PyObject_Format(value, format_spec);
  493. }
  494. PyDoc_STRVAR(format_doc,
  495. "format(value[, format_spec]) -> string\n\
  496. \n\
  497. Returns value.__format__(format_spec)\n\
  498. format_spec defaults to \"\"");
  499. static PyObject *
  500. builtin_chr(PyObject *self, PyObject *arg)
  501. {
  502. char s[1];
  503. long x = PyInt_AsLong(arg);
  504. if (x == -1 && PyErr_Occurred())
  505. return NULL;
  506. if (x < 0 || x >= 256) {
  507. PyErr_SetString(PyExc_ValueError,
  508. "chr() arg not in range(256)");
  509. return NULL;
  510. }
  511. s[0] = (char)x;
  512. return PyString_FromStringAndSize(s, 1);
  513. }
  514. PyDoc_STRVAR(chr_doc,
  515. "chr(i) -> character\n\
  516. \n\
  517. Return a string of one character with ordinal i; 0 <= i < 256.");
  518. #ifdef Py_USING_UNICODE
  519. static PyObject *
  520. builtin_unichr(PyObject *self, PyObject *arg)
  521. {
  522. int x = _PyInt_AsInt(arg);
  523. if (x == -1 && PyErr_Occurred())
  524. return NULL;
  525. return PyUnicode_FromOrdinal(x);
  526. }
  527. PyDoc_STRVAR(unichr_doc,
  528. "unichr(i) -> Unicode character\n\
  529. \n\
  530. Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
  531. #endif
  532. static PyObject *
  533. builtin_cmp(PyObject *self, PyObject *a, PyObject *b)
  534. {
  535. int c;
  536. if (PyObject_Cmp(a, b, &c) < 0)
  537. return NULL;
  538. return PyInt_FromLong((long)c);
  539. }
  540. PyDoc_STRVAR(cmp_doc,
  541. "cmp(x, y) -> integer\n\
  542. \n\
  543. Return negative if x<y, zero if x==y, positive if x>y.");
  544. static PyObject *
  545. builtin_coerce(PyObject *self, PyObject *v, PyObject *w)
  546. {
  547. PyObject *res;
  548. if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
  549. return NULL;
  550. if (PyNumber_Coerce(&v, &w) < 0)
  551. return NULL;
  552. res = PyTuple_Pack(2, v, w);
  553. Py_DECREF(v);
  554. Py_DECREF(w);
  555. return res;
  556. }
  557. PyDoc_STRVAR(coerce_doc,
  558. "coerce(x, y) -> (x1, y1)\n\
  559. \n\
  560. Return a tuple consisting of the two numeric arguments converted to\n\
  561. a common type, using the same rules as used by arithmetic operations.\n\
  562. If coercion is not possible, raise TypeError.");
  563. static PyObject *
  564. builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
  565. {
  566. char *str;
  567. char *filename;
  568. char *startstr;
  569. int mode = -1;
  570. int dont_inherit = 0;
  571. int supplied_flags = 0;
  572. PyCompilerFlags cf;
  573. PyObject *result = NULL, *cmd, *tmp = NULL;
  574. Py_ssize_t length;
  575. static char *kwlist[] = {"source", "filename", "mode", "flags",
  576. "dont_inherit", NULL};
  577. int start[] = {Py_file_input, Py_eval_input, Py_single_input};
  578. if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
  579. kwlist, &cmd, &filename, &startstr,
  580. &supplied_flags, &dont_inherit))
  581. return NULL;
  582. cf.cf_flags = supplied_flags;
  583. if (supplied_flags &
  584. ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
  585. {
  586. PyErr_SetString(PyExc_ValueError,
  587. "compile(): unrecognised flags");
  588. return NULL;
  589. }
  590. /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
  591. if (!dont_inherit) {
  592. PyEval_MergeCompilerFlags(&cf);
  593. }
  594. if (strcmp(startstr, "exec") == 0)
  595. mode = 0;
  596. else if (strcmp(startstr, "eval") == 0)
  597. mode = 1;
  598. else if (strcmp(startstr, "single") == 0)
  599. mode = 2;
  600. else {
  601. PyErr_SetString(PyExc_ValueError,
  602. "compile() arg 3 must be 'exec', 'eval' or 'single'");
  603. return NULL;
  604. }
  605. if (PyAST_Check(cmd)) {
  606. if (supplied_flags & PyCF_ONLY_AST) {
  607. Py_INCREF(cmd);
  608. result = cmd;
  609. }
  610. else {
  611. PyArena *arena;
  612. mod_ty mod;
  613. arena = PyArena_New();
  614. mod = PyAST_obj2mod(cmd, arena, mode);
  615. if (mod == NULL) {
  616. PyArena_Free(arena);
  617. return NULL;
  618. }
  619. result = (PyObject*)PyAST_Compile(mod, filename,
  620. &cf, arena);
  621. PyArena_Free(arena);
  622. }
  623. return result;
  624. }
  625. #ifdef Py_USING_UNICODE
  626. if (PyUnicode_Check(cmd)) {
  627. tmp = PyUnicode_AsUTF8String(cmd);
  628. if (tmp == NULL)
  629. return NULL;
  630. cmd = tmp;
  631. cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
  632. }
  633. #endif
  634. if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
  635. goto cleanup;
  636. if ((size_t)length != strlen(str)) {
  637. PyErr_SetString(PyExc_TypeError,
  638. "compile() expected string without null bytes");
  639. goto cleanup;
  640. }
  641. result = Py_CompileStringFlags(str, filename, start[mode], &cf);
  642. cleanup:
  643. Py_XDECREF(tmp);
  644. return result;
  645. }
  646. PyDoc_STRVAR(compile_doc,
  647. "compile(source, filename, mode[, flags[, dont_inherit]]) -> code object\n\
  648. \n\
  649. Compile the source string (a Python module, statement or expression)\n\
  650. into a code object that can be executed by the exec statement or eval().\n\
  651. The filename will be used for run-time error messages.\n\
  652. The mode must be 'exec' to compile a module, 'single' to compile a\n\
  653. single (interactive) statement, or 'eval' to compile an expression.\n\
  654. The flags argument, if present, controls which future statements influence\n\
  655. the compilation of the code.\n\
  656. The dont_inherit argument, if non-zero, stops the compilation inheriting\n\
  657. the effects of any future statements in effect in the code calling\n\
  658. compile; if absent or zero these statements do influence the compilation,\n\
  659. in addition to any features explicitly specified.");
  660. static PyObject *
  661. builtin_dir(PyObject *self, PyObject *arg)
  662. {
  663. return PyObject_Dir(arg);
  664. }
  665. PyDoc_STRVAR(dir_doc,
  666. "dir([object]) -> list of strings\n"
  667. "\n"
  668. "If called without an argument, return the names in the current scope.\n"
  669. "Else, return an alphabetized list of names comprising (some of) the attributes\n"
  670. "of the given object, and of attributes reachable from it.\n"
  671. "If the object supplies a method named __dir__, it will be used; otherwise\n"
  672. "the default dir() logic is used and returns:\n"
  673. " for a module object: the module's attributes.\n"
  674. " for a class object: its attributes, and recursively the attributes\n"
  675. " of its bases.\n"
  676. " for any other object: its attributes, its class's attributes, and\n"
  677. " recursively the attributes of its class's base classes.");
  678. static PyObject *
  679. builtin_divmod(PyObject *self, PyObject *v, PyObject *w)
  680. {
  681. return PyNumber_Divmod(v, w);
  682. }
  683. PyDoc_STRVAR(divmod_doc,
  684. "divmod(x, y) -> (div, mod)\n\
  685. \n\
  686. Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
  687. static PyObject *
  688. builtin_eval(PyObject *self, PyObject *cmd, PyObject *globals, PyObject *locals)
  689. {
  690. PyObject *result, *tmp = NULL;
  691. char *str;
  692. PyCompilerFlags cf;
  693. if (globals == Py_None)
  694. globals = NULL;
  695. if (locals == Py_None)
  696. locals = NULL;
  697. if (locals != NULL && !PyMapping_Check(locals)) {
  698. PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
  699. return NULL;
  700. }
  701. if (globals != NULL && !PyDict_Check(globals)) {
  702. PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
  703. "globals must be a real dict; try eval(expr, {}, mapping)"
  704. : "globals must be a dict");
  705. return NULL;
  706. }
  707. if (globals == NULL) {
  708. globals = PyEval_GetGlobals();
  709. if (locals == NULL)
  710. locals = PyEval_GetLocals();
  711. }
  712. else if (locals == NULL)
  713. locals = globals;
  714. if (globals == NULL || locals == NULL) {
  715. PyErr_SetString(PyExc_TypeError,
  716. "eval must be given globals and locals "
  717. "when called without a frame");
  718. return NULL;
  719. }
  720. if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
  721. if (PyDict_SetItemString(globals, "__builtins__",
  722. PyEval_GetBuiltins()) != 0)
  723. return NULL;
  724. }
  725. if (PyCode_Check(cmd)) {
  726. if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
  727. PyErr_SetString(PyExc_TypeError,
  728. "code object passed to eval() may not contain free variables");
  729. return NULL;
  730. }
  731. return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
  732. }
  733. if (!PyString_Check(cmd) &&
  734. !PyUnicode_Check(cmd)) {
  735. PyErr_SetString(PyExc_TypeError,
  736. "eval() arg 1 must be a string or code object");
  737. return NULL;
  738. }
  739. cf.cf_flags = 0;
  740. #ifdef Py_USING_UNICODE
  741. if (PyUnicode_Check(cmd)) {
  742. tmp = PyUnicode_AsUTF8String(cmd);
  743. if (tmp == NULL)
  744. return NULL;
  745. cmd = tmp;
  746. cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
  747. }
  748. #endif
  749. if (PyString_AsStringAndSize(cmd, &str, NULL)) {
  750. Py_XDECREF(tmp);
  751. return NULL;
  752. }
  753. while (*str == ' ' || *str == '\t')
  754. str++;
  755. (void)PyEval_MergeCompilerFlags(&cf);
  756. result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
  757. Py_XDECREF(tmp);
  758. return result;
  759. }
  760. PyDoc_STRVAR(eval_doc,
  761. "eval(source[, globals[, locals]]) -> value\n\
  762. \n\
  763. Evaluate the source in the context of globals and locals.\n\
  764. The source may be a string representing a Python expression\n\
  765. or a code object as returned by compile().\n\
  766. The globals must be a dictionary and locals can be any mapping,\n\
  767. defaulting to the current globals and locals.\n\
  768. If only globals is given, locals defaults to it.\n");
  769. static PyObject *
  770. builtin_execfile(PyObject *self, PyObject *args)
  771. {
  772. char *filename;
  773. PyObject *globals = Py_None, *locals = Py_None;
  774. PyObject *res;
  775. FILE* fp = NULL;
  776. PyCompilerFlags cf;
  777. int exists;
  778. if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
  779. 1) < 0)
  780. return NULL;
  781. if (!PyArg_ParseTuple(args, "s|O!O:execfile",
  782. &filename,
  783. &PyDict_Type, &globals,
  784. &locals))
  785. return NULL;
  786. if (locals != Py_None && !PyMapping_Check(locals)) {
  787. PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
  788. return NULL;
  789. }
  790. if (globals == Py_None) {
  791. globals = PyEval_GetGlobals();
  792. if (locals == Py_None)
  793. locals = PyEval_GetLocals();
  794. }
  795. else if (locals == Py_None)
  796. locals = globals;
  797. if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
  798. if (PyDict_SetItemString(globals, "__builtins__",
  799. PyEval_GetBuiltins()) != 0)
  800. return NULL;
  801. }
  802. exists = 0;
  803. /* Test for existence or directory. */
  804. #if defined(PLAN9)
  805. {
  806. Dir *d;
  807. if ((d = dirstat(filename))!=nil) {
  808. if(d->mode & DMDIR)
  809. werrstr("is a directory");
  810. else
  811. exists = 1;
  812. free(d);
  813. }
  814. }
  815. #elif defined(RISCOS)
  816. if (object_exists(filename)) {
  817. if (isdir(filename))
  818. errno = EISDIR;
  819. else
  820. exists = 1;
  821. }
  822. #else /* standard Posix */
  823. {
  824. struct stat s;
  825. if (stat(filename, &s) == 0) {
  826. if (S_ISDIR(s.st_mode))
  827. # if defined(PYOS_OS2) && defined(PYCC_VACPP)
  828. errno = EOS2ERR;
  829. # else
  830. errno = EISDIR;
  831. # endif
  832. else
  833. exists = 1;
  834. }
  835. }
  836. #endif
  837. if (exists) {
  838. Py_BEGIN_ALLOW_THREADS
  839. fp = fopen(filename, "r" PY_STDIOTEXTMODE);
  840. Py_END_ALLOW_THREADS
  841. if (fp == NULL) {
  842. exists = 0;
  843. }
  844. }
  845. if (!exists) {
  846. PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
  847. return NULL;
  848. }
  849. cf.cf_flags = 0;
  850. if (PyEval_MergeCompilerFlags(&cf))
  851. res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
  852. locals, 1, &cf);
  853. else
  854. res = PyRun_FileEx(fp, filename, Py_file_input, globals,
  855. locals, 1);
  856. return res;
  857. }
  858. PyDoc_STRVAR(execfile_doc,
  859. "execfile(filename[, globals[, locals]])\n\
  860. \n\
  861. Read and execute a Python script from a file.\n\
  862. The globals and locals are dictionaries, defaulting to the current\n\
  863. globals and locals. If only globals is given, locals defaults to it.");
  864. static PyObject *
  865. builtin_getattr(PyObject *self, PyObject *v, PyObject *name, PyObject *dflt)
  866. {
  867. PyObject *result;
  868. #ifdef Py_USING_UNICODE
  869. if (PyUnicode_Check(name)) {
  870. name = _PyUnicode_AsDefaultEncodedString(name, NULL);
  871. if (name == NULL)
  872. return NULL;
  873. }
  874. #endif
  875. if (!PyString_Check(name)) {
  876. PyErr_SetString(PyExc_TypeError,
  877. "getattr(): attribute name must be string");
  878. return NULL;
  879. }
  880. result = PyObject_GetAttr(v, name);
  881. if (result == NULL && dflt != NULL &&
  882. PyErr_ExceptionMatches(PyExc_AttributeError))
  883. {
  884. PyErr_Clear();
  885. Py_INCREF(dflt);
  886. result = dflt;
  887. }
  888. return result;
  889. }
  890. PyDoc_STRVAR(getattr_doc,
  891. "getattr(object, name[, default]) -> value\n\
  892. \n\
  893. Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.\n\
  894. When a default argument is given, it is returned when the attribute doesn't\n\
  895. exist; without it, an exception is raised in that case.");
  896. static PyObject *
  897. builtin_globals(PyObject *self)
  898. {
  899. PyObject *d;
  900. d = PyEval_GetGlobals();
  901. Py_XINCREF(d);
  902. return d;
  903. }
  904. PyDoc_STRVAR(globals_doc,
  905. "globals() -> dictionary\n\
  906. \n\
  907. Return the dictionary containing the current scope's global variables.");
  908. static PyObject *
  909. builtin_hasattr(PyObject *self, PyObject *v, PyObject *name)
  910. {
  911. #ifdef Py_USING_UNICODE
  912. if (PyUnicode_Check(name)) {
  913. name = _PyUnicode_AsDefaultEncodedString(name, NULL);
  914. if (name == NULL)
  915. return NULL;
  916. }
  917. #endif
  918. if (!PyString_Check(name)) {
  919. PyErr_SetString(PyExc_TypeError,
  920. "hasattr(): attribute name must be string");
  921. return NULL;
  922. }
  923. v = PyObject_GetAttr(v, name);
  924. if (v == NULL) {
  925. if (!PyErr_ExceptionMatches(PyExc_Exception))
  926. return NULL;
  927. else {
  928. PyErr_Clear();
  929. Py_INCREF(Py_False);
  930. return Py_False;
  931. }
  932. }
  933. Py_DECREF(v);
  934. Py_INCREF(Py_True);
  935. return Py_True;
  936. }
  937. PyDoc_STRVAR(hasattr_doc,
  938. "hasattr(object, name) -> bool\n\
  939. \n\
  940. Return whether the object has an attribute with the given name.\n\
  941. (This is done by calling getattr(object, name) and catching exceptions.)");
  942. static PyObject *
  943. builtin_id(PyObject *self, PyObject *v)
  944. {
  945. return PyLong_FromVoidPtr(v);
  946. }
  947. PyDoc_STRVAR(id_doc,
  948. "id(object) -> integer\n\
  949. \n\
  950. Return the identity of an object. This is guaranteed to be unique among\n\
  951. simultaneously existing objects. (Hint: it's the object's memory address.)");
  952. static PyObject *
  953. builtin_import_from(PyObject *self, PyObject *module, PyObject *name)
  954. {
  955. PyObject *obj = PyObject_GetAttr(module, name);
  956. if (obj == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
  957. PyErr_Format(PyExc_ImportError,
  958. "cannot import name %.230s",
  959. PyString_AsString(name));
  960. }
  961. return obj;
  962. }
  963. PyDoc_STRVAR(import_from_doc,
  964. "#@import_from(module, attr_name) -> object\n\
  965. \n\
  966. Simulate the removed IMPORT_FROM opcode. Internal use only.");
  967. /* Helper for builtin_import_star below. */
  968. static int
  969. import_all_from(PyObject *locals, PyObject *v)
  970. {
  971. PyObject *all = PyObject_GetAttrString(v, "__all__");
  972. PyObject *dict, *name, *value;
  973. int skip_leading_underscores = 0;
  974. int pos, err;
  975. if (all == NULL) {
  976. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  977. return -1; /* Unexpected error */
  978. PyErr_Clear();
  979. dict = PyObject_GetAttrString(v, "__dict__");
  980. if (dict == NULL) {
  981. if (!PyErr_ExceptionMatches(PyExc_AttributeError))
  982. return -1;
  983. PyErr_SetString(PyExc_ImportError,
  984. "from-import-* object has no __dict__ and no __all__");
  985. return -1;
  986. }
  987. all = PyMapping_Keys(dict);
  988. Py_DECREF(dict);
  989. if (all == NULL)
  990. return -1;
  991. skip_leading_underscores = 1;
  992. }
  993. for (pos = 0, err = 0; ; pos++) {
  994. name = PySequence_GetItem(all, pos);
  995. if (name == NULL) {
  996. if (!PyErr_ExceptionMatches(PyExc_IndexError))
  997. err = -1;
  998. else
  999. PyErr_Clear();
  1000. break;
  1001. }
  1002. if (skip_leading_underscores &&
  1003. PyString_Check(name) &&
  1004. PyString_AS_STRING(name)[0] == '_')
  1005. {
  1006. Py_DECREF(name);
  1007. continue;
  1008. }
  1009. value = PyObject_GetAttr(v, name);
  1010. if (value == NULL)
  1011. err = -1;
  1012. else if (PyDict_CheckExact(locals))
  1013. err = PyDict_SetItem(locals, name, value);
  1014. else
  1015. err = PyObject_SetItem(locals, name, value);
  1016. Py_DECREF(name);
  1017. Py_XDECREF(value);
  1018. if (err != 0)
  1019. break;
  1020. }
  1021. Py_DECREF(all);
  1022. return err;
  1023. }
  1024. static PyObject *
  1025. builtin_import_star(PyObject *self, PyObject *module)
  1026. {
  1027. int err;
  1028. PyObject *locals;
  1029. PyFrameObject *frame = PyThreadState_Get()->frame;
  1030. PyFrame_FastToLocals(frame);
  1031. if ((locals = frame->f_locals) == NULL) {
  1032. PyErr_SetString(PyExc_SystemError,
  1033. "no locals found during 'import *'");
  1034. return NULL;
  1035. }
  1036. err = import_all_from(locals, module);
  1037. PyFrame_LocalsToFast(frame, 0);
  1038. if (err)
  1039. return NULL;
  1040. Py_RETURN_NONE;
  1041. }
  1042. PyDoc_STRVAR(import_star_doc,
  1043. "#@import_star(module) -> None\n\
  1044. \n\
  1045. Implement 'from foo import *'. Internal use only.");
  1046. static PyObject *
  1047. builtin_make_function(PyObject *self, PyObject *args)
  1048. {
  1049. PyFrameObject *frame;
  1050. PyObject *code_obj, *func;
  1051. int i, n = PyTuple_Size(args);
  1052. frame = PyThreadState_Get()->frame;
  1053. code_obj = PyTuple_GetItem(args, 0);
  1054. if (code_obj == NULL)
  1055. return NULL;
  1056. if (!PyCode_Check(code_obj)) {
  1057. PyErr_Format(PyExc_TypeError,
  1058. "first argument must be a code object, not %.200s",
  1059. code_obj->ob_type->tp_name);
  1060. return NULL;
  1061. }
  1062. func = PyFunction_New(code_obj, frame->f_globals);
  1063. if (func == NULL)
  1064. return NULL;
  1065. if (n > 1) {
  1066. PyObject *default_obj;
  1067. PyObject *defaults = PyTuple_New(n - 1);
  1068. if (defaults == NULL) {
  1069. Py_DECREF(func);
  1070. return NULL;
  1071. }
  1072. for (i = 1; i < n; i++) {
  1073. default_obj = PyTuple_GET_ITEM(args, i);
  1074. Py_INCREF(default_obj);
  1075. PyTuple_SET_ITEM(defaults, i - 1, default_obj);
  1076. }
  1077. if (PyFunction_SetDefaults(func, defaults)) {
  1078. Py_DECREF(defaults);
  1079. Py_DECREF(func);
  1080. return NULL;
  1081. }
  1082. Py_DECREF(defaults);
  1083. }
  1084. return func;
  1085. }
  1086. PyDoc_STRVAR(make_function_doc,
  1087. "#@make_function(code_obj, *default_args) -> function\n\
  1088. \n\
  1089. Build a function object. Internal use only.");
  1090. static PyObject *
  1091. builtin_map(PyObject *self, PyObject *args)
  1092. {
  1093. typedef struct {
  1094. PyObject *it; /* the iterator object */
  1095. int saw_StopIteration; /* bool: did the iterator end? */
  1096. } sequence;
  1097. PyObject *func, *result;
  1098. sequence *seqs = NULL, *sqp;
  1099. Py_ssize_t n, len;
  1100. register int i, j;
  1101. n = PyTuple_Size(args);
  1102. if (n < 2) {
  1103. PyErr_SetString(PyExc_TypeError,
  1104. "map() requires at least two args");
  1105. return NULL;
  1106. }
  1107. func = PyTuple_GetItem(args, 0);
  1108. n--;
  1109. if (func == Py_None) {
  1110. if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
  1111. "use list(...)", 1) < 0)
  1112. return NULL;
  1113. if (n == 1) {
  1114. /* map(None, S) is the same as list(S). */
  1115. return PySequence_List(PyTuple_GetItem(args, 1));
  1116. }
  1117. }
  1118. /* Get space for sequence descriptors. Must NULL out the iterator
  1119. * pointers so that jumping to Fail_2 later doesn't see trash.
  1120. */
  1121. if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
  1122. PyErr_NoMemory();
  1123. return NULL;
  1124. }
  1125. for (i = 0; i < n; ++i) {
  1126. seqs[i].it = (PyObject*)NULL;
  1127. seqs[i].saw_StopIteration = 0;
  1128. }
  1129. /* Do a first pass to obtain iterators for the arguments, and set len
  1130. * to the largest of their lengths.
  1131. */
  1132. len = 0;
  1133. for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
  1134. PyObject *curseq;
  1135. Py_ssize_t curlen;
  1136. /* Get iterator. */
  1137. curseq = PyTuple_GetItem(args, i+1);
  1138. sqp->it = PyObject_GetIter(curseq);
  1139. if (sqp->it == NULL) {
  1140. static char errmsg[] =
  1141. "argument %d to map() must support iteration";
  1142. char errbuf[sizeof(errmsg) + 25];
  1143. PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
  1144. PyErr_SetString(PyExc_TypeError, errbuf);
  1145. goto Fail_2;
  1146. }
  1147. /* Update len. */
  1148. curlen = _PyObject_LengthHint(curseq, 8);
  1149. if (curlen > len)
  1150. len = curlen;
  1151. }
  1152. /* Get space for the result list. */
  1153. if ((result = (PyObject *) PyList_New(len)) == NULL)
  1154. goto Fail_2;
  1155. /* Iterate over the sequences until all have stopped. */
  1156. for (i = 0; ; ++i) {
  1157. PyObject *alist, *item=NULL, *value;
  1158. int numactive = 0;
  1159. if (func == Py_None && n == 1)
  1160. alist = NULL;
  1161. else if ((alist = PyTuple_New(n)) == NULL)
  1162. goto Fail_1;
  1163. for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
  1164. if (sqp->saw_StopIteration) {
  1165. Py_INCREF(Py_None);
  1166. item = Py_None;
  1167. }
  1168. else {
  1169. item = PyIter_Next(sqp->it);
  1170. if (item)
  1171. ++numactive;
  1172. else {
  1173. if (PyErr_Occurred()) {
  1174. Py_XDECREF(alist);
  1175. goto Fail_1;
  1176. }
  1177. Py_INCREF(Py_None);
  1178. item = Py_None;
  1179. sqp->saw_StopIteration = 1;
  1180. }
  1181. }
  1182. if (alist)
  1183. PyTuple_SET_ITEM(alist, j, item);
  1184. else
  1185. break;
  1186. }
  1187. if (!alist)
  1188. alist = item;
  1189. if (numactive == 0) {
  1190. Py_DECREF(alist);
  1191. break;
  1192. }
  1193. if (func == Py_None)
  1194. value = alist;
  1195. else {
  1196. value = PyEval_CallObject(func, alist);
  1197. Py_DECREF(alist);
  1198. if (value == NULL)
  1199. goto Fail_1;
  1200. }
  1201. if (i >= len) {
  1202. int status = PyList_Append(result, value);
  1203. Py_DECREF(value);
  1204. if (status < 0)
  1205. goto Fail_1;
  1206. }
  1207. else if (PyList_SetItem(result, i, value) < 0)
  1208. goto Fail_1;
  1209. }
  1210. if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
  1211. goto Fail_1;
  1212. goto Succeed;
  1213. Fail_1:
  1214. Py_DECREF(result);
  1215. Fail_2:
  1216. result = NULL;
  1217. Succeed:
  1218. assert(seqs);
  1219. for (i = 0; i < n; ++i)
  1220. Py_XDECREF(seqs[i].it);
  1221. PyMem_DEL(seqs);
  1222. return result;
  1223. }
  1224. PyDoc_STRVAR(map_doc,
  1225. "map(function, sequence[, sequence, ...]) -> list\n\
  1226. \n\
  1227. Return a list of the results of applying the function to the items of\n\
  1228. the argument sequence(s). If more than one sequence is given, the\n\
  1229. function is called with an argument list consisting of the corresponding\n\
  1230. item of each sequence, substituting None for missing values when not all\n\
  1231. sequences have the same length. If the function is None, return a list of\n\
  1232. the items of the sequence (or a list of tuples if more than one sequence).");
  1233. static PyObject *
  1234. builtin_next(PyObject *self, PyObject *it, PyObject *dflt)
  1235. {
  1236. PyObject *res;
  1237. if (!PyIter_Check(it)) {
  1238. PyErr_Format(PyExc_TypeError,
  1239. "%.200s object is not an iterator",
  1240. it->ob_type->tp_name);
  1241. return NULL;
  1242. }
  1243. res = (*it->ob_type->tp_iternext)(it);
  1244. if (res != NULL) {
  1245. return res;
  1246. } else if (dflt != NULL) {
  1247. if (PyErr_Occurred()) {
  1248. if (!PyErr_ExceptionMatches(PyExc_StopIteration))
  1249. return NULL;
  1250. PyErr_Clear();
  1251. }
  1252. Py_INCREF(dflt);
  1253. return dflt;
  1254. } else if (PyErr_Occurred()) {
  1255. return NULL;
  1256. } else {
  1257. PyErr_SetNone(PyExc_StopIteration);
  1258. return NULL;
  1259. }
  1260. }
  1261. PyDoc_STRVAR(next_doc,
  1262. "next(iterator[, default])\n\
  1263. \n\
  1264. Return the next item from the iterator. If default is given and the iterator\n\
  1265. is exhausted, it is returned instead of raising StopIteration.");
  1266. static PyObject *
  1267. builtin_setattr(PyObject *self, PyObject *v, PyObject *name, PyObject *value)
  1268. {
  1269. if (PyObject_SetAttr(v, name, value) != 0)
  1270. return NULL;
  1271. Py_INCREF(Py_None);
  1272. return Py_None;
  1273. }
  1274. PyDoc_STRVAR(setattr_doc,
  1275. "setattr(object, name, value)\n\
  1276. \n\
  1277. Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
  1278. ``x.y = v''.");
  1279. static PyObject *
  1280. builtin_delattr(PyObject *self, PyObject *v, PyObject *name)
  1281. {
  1282. if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
  1283. return NULL;
  1284. Py_INCREF(Py_None);
  1285. return Py_None;
  1286. }
  1287. PyDoc_STRVAR(delattr_doc,
  1288. "delattr(object, name)\n\
  1289. \n\
  1290. Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
  1291. ``del x.y''.");
  1292. static PyObject *
  1293. builtin_hash(PyObject *self, PyObject *v)
  1294. {
  1295. long x;
  1296. x = PyObject_Hash(v);
  1297. if (x == -1)
  1298. return NULL;
  1299. return PyInt_FromLong(x);
  1300. }
  1301. PyDoc_STRVAR(hash_doc,
  1302. "hash(object) -> integer\n\
  1303. \n\
  1304. Return a hash value for the object. Two objects with the same value have\n\
  1305. the same hash value. The reverse is not necessarily true, but likely.");
  1306. static PyObject *
  1307. builtin_hex(PyObject *self, PyObject *v)
  1308. {
  1309. PyNumberMethods *nb;
  1310. PyObject *res;
  1311. if ((nb = v->ob_type->tp_as_number) == NULL ||
  1312. nb->nb_hex == NULL) {
  1313. PyErr_SetString(PyExc_TypeError,
  1314. "hex() argument can't be converted to hex");
  1315. return NULL;
  1316. }
  1317. res = (*nb->nb_hex)(v);
  1318. if (res && !PyString_Check(res)) {
  1319. PyErr_Format(PyExc_TypeError,
  1320. "__hex__ returned non-string (type %.200s)",
  1321. res->ob_type->tp_name);
  1322. Py_DECREF(res);
  1323. return NULL;
  1324. }
  1325. return res;
  1326. }
  1327. PyDoc_STRVAR(hex_doc,
  1328. "hex(number) -> string\n\
  1329. \n\
  1330. Return the hexadecimal representation of an integer or long integer.");
  1331. static PyObject *builtin_raw_input(PyObject *, PyObject *);
  1332. static PyObject *
  1333. builtin_input(PyObject *self, PyObject *v)
  1334. {
  1335. PyObject *line;
  1336. char *str;
  1337. PyObject *res;
  1338. PyObject *globals, *locals;
  1339. PyCompilerFlags cf;
  1340. line = builtin_raw_input(self, v);
  1341. if (line == NULL)
  1342. return line;
  1343. if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
  1344. return NULL;
  1345. while (*str == ' ' || *str == '\t')
  1346. str++;
  1347. globals = PyEval_GetGlobals();
  1348. locals = PyEval_GetLocals();
  1349. if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
  1350. if (PyDict_SetItemString(globals, "__builtins__",
  1351. PyEval_GetBuiltins()) != 0)
  1352. return NULL;
  1353. }
  1354. cf.cf_flags = 0;
  1355. PyEval_MergeCompilerFlags(&cf);
  1356. res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
  1357. Py_DECREF(line);
  1358. return res;
  1359. }
  1360. PyDoc_STRVAR(input_doc,
  1361. "input([prompt]) -> value\n\
  1362. \n\
  1363. Equivalent to eval(raw_input(prompt)).");
  1364. static PyObject *
  1365. builtin_intern(PyObject *self, PyObject *s)
  1366. {
  1367. if (!PyString_Check(s)) {
  1368. PyErr_Format(PyExc_TypeError,
  1369. "intern() argument 1 must be string, not %.200s",
  1370. Py_TYPE(s)->tp_name);
  1371. return NULL;
  1372. }
  1373. if (!PyString_CheckExact(s)) {
  1374. PyErr_SetString(PyExc_TypeError,
  1375. "can't intern subclass of string");
  1376. return NULL;
  1377. }
  1378. Py_INCREF(s);
  1379. PyString_InternInPlace(&s);
  1380. return s;
  1381. }
  1382. PyDoc_STRVAR(intern_doc,
  1383. "intern(string) -> string\n\
  1384. \n\
  1385. ``Intern'' the given string. This enters the string in the (global)\n\
  1386. table of interned strings whose purpose is to speed up dictionary lookups.\n\
  1387. Return the string itself or the previously interned string object with the\n\
  1388. same value.");
  1389. static PyObject *
  1390. builtin_iter(PyObject *self, PyObject *v, PyObject *w)
  1391. {
  1392. if (w == NULL)
  1393. return PyObject_GetIter(v);
  1394. if (!PyCallable_Check(v)) {
  1395. PyErr_SetString(PyExc_TypeError,
  1396. "iter(v, w): v must be callable");
  1397. return NULL;
  1398. }
  1399. return PyCallIter_New(v, w);
  1400. }
  1401. PyDoc_STRVAR(iter_doc,
  1402. "iter(collection) -> iterator\n\
  1403. iter(callable, sentinel) -> iterator\n\
  1404. \n\
  1405. Get an iterator from an object. In the first form, the argument must\n\
  1406. supply its own iterator, or be a sequence.\n\
  1407. In the second form, the callable is called until it returns the sentinel.");
  1408. PyObject *
  1409. _PyBuiltin_Len(PyObject *self, PyObject *v)
  1410. {
  1411. Py_ssize_t res;
  1412. res = PyObject_Size(v);
  1413. if (res < 0 && PyErr_Occurred())
  1414. return NULL;
  1415. return PyInt_FromSsize_t(res);
  1416. }
  1417. PyDoc_STRVAR(len_doc,
  1418. "len(object) -> integer\n\
  1419. \n\
  1420. Return the number of items of a sequence or mapping.");
  1421. static PyObject *
  1422. builtin_locals(PyObject *self)
  1423. {
  1424. PyObject *d;
  1425. d = PyEval_GetLocals();
  1426. Py_XINCREF(d);
  1427. return d;
  1428. }
  1429. PyDoc_STRVAR(locals_doc,
  1430. "locals() -> dictionary\n\
  1431. \n\
  1432. Update and return a dictionary containing the current scope's local variables.");
  1433. static PyObject *
  1434. min_max(PyObject *args, PyObject *kwds, int op)
  1435. {
  1436. PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
  1437. const char *name = op == Py_LT ? "min" : "max";
  1438. if (PyTuple_Size(args) > 1)
  1439. v = args;
  1440. else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
  1441. return NULL;
  1442. if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
  1443. keyfunc = PyDict_GetItemString(kwds, "key");
  1444. if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
  1445. PyErr_Format(PyExc_TypeError,
  1446. "%s() got an unexpected keyword argument", name);
  1447. return NULL;
  1448. }
  1449. Py_INCREF(keyfunc);
  1450. }
  1451. it = PyObject_GetIter(v);
  1452. if (it == NULL) {
  1453. Py_XDECREF(keyfunc);
  1454. return NULL;
  1455. }
  1456. maxitem = NULL; /* the result */
  1457. maxval = NULL; /* the value associated with the result */
  1458. while (( item = PyIter_Next(it) )) {
  1459. /* get the value from the key function */
  1460. if (keyfunc != NULL) {
  1461. val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
  1462. if (val == NULL)
  1463. goto Fail_it_item;
  1464. }
  1465. /* no key function; the value is the item */
  1466. else {
  1467. val = item;
  1468. Py_INCREF(val);
  1469. }
  1470. /* maximum value and item are unset; set them */
  1471. if (maxval == NULL) {
  1472. maxitem = item;
  1473. maxval = val;
  1474. }
  1475. /* maximum value and item are set; update them as necessary */
  1476. else {
  1477. int cmp = PyObject_RichCompareBool(val, maxval, op);
  1478. if (cmp < 0)
  1479. goto Fail_it_item_and_val;
  1480. else if (cmp > 0) {
  1481. Py_DECREF(maxval);
  1482. Py_DECREF(maxitem);
  1483. maxval = val;
  1484. maxitem = item;
  1485. }
  1486. else {
  1487. Py_DECREF(item);
  1488. Py_DECREF(val);
  1489. }
  1490. }
  1491. }
  1492. if (PyErr_Occurred())
  1493. goto Fail_it;
  1494. if (maxval == NULL) {
  1495. PyErr_Format(PyExc_ValueError,
  1496. "%s() arg is an empty sequence", name);
  1497. assert(maxitem == NULL);
  1498. }
  1499. else
  1500. Py_DECREF(maxval);
  1501. Py_DECREF(it);
  1502. Py_XDECREF(keyfunc);
  1503. return maxitem;
  1504. Fail_it_item_and_val:
  1505. Py_DECREF(val);
  1506. Fail_it_item:
  1507. Py_DECREF(item);
  1508. Fail_it:
  1509. Py_XDECREF(maxval);
  1510. Py_XDECREF(maxitem);
  1511. Py_DECREF(it);
  1512. Py_XDECREF(keyfunc);
  1513. return NULL;
  1514. }
  1515. static PyObject *
  1516. builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
  1517. {
  1518. return min_max(args, kwds, Py_LT);
  1519. }
  1520. PyDoc_STRVAR(min_doc,
  1521. "min(iterable[, key=func]) -> value\n\
  1522. min(a, b, c, ...[, key=func]) -> value\n\
  1523. \n\
  1524. With a single iterable argument, return its smallest item.\n\
  1525. With two or more arguments, return the smallest argument.");
  1526. static PyObject *
  1527. builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
  1528. {
  1529. return min_max(args, kwds, Py_GT);
  1530. }
  1531. PyDoc_STRVAR(max_doc,
  1532. "max(iterable[, key=func]) -> value\n\
  1533. max(a, b, c, ...[, key=func]) -> value\n\
  1534. \n\
  1535. With a single iterable argument, return its largest item.\n\
  1536. With two or more arguments, return the largest argument.");
  1537. static PyObject *
  1538. builtin_oct(PyObject *self, PyObject *v)
  1539. {
  1540. PyNumberMethods *nb;
  1541. PyObject *res;
  1542. if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
  1543. nb->nb_oct == NULL) {
  1544. PyErr_SetString(PyExc_TypeError,
  1545. "oct() argument can't be converted to oct");
  1546. return NULL;
  1547. }
  1548. res = (*nb->nb_oct)(v);
  1549. if (res && !PyString_Check(res)) {
  1550. PyErr_Format(PyExc_TypeError,
  1551. "__oct__ returned non-string (type %.200s)",
  1552. res->ob_type->tp_name);
  1553. Py_DECREF(res);
  1554. return NULL;
  1555. }
  1556. return res;
  1557. }
  1558. PyDoc_STRVAR(oct_doc,
  1559. "oct(number) -> string\n\
  1560. \n\
  1561. Return the octal representation of an integer or long integer.");
  1562. static PyObject *
  1563. builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
  1564. {
  1565. return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
  1566. }
  1567. PyDoc_STRVAR(open_doc,
  1568. "open(name[, mode[, buffering]]) -> file object\n\
  1569. \n\
  1570. Open a file using the file() type, returns a file object. This is the\n\
  1571. preferred way to open a file.");
  1572. static PyObject *
  1573. builtin_ord(PyObject *self, PyObject* obj)
  1574. {
  1575. long ord;
  1576. Py_ssize_t size;
  1577. if (PyString_Check(obj)) {
  1578. size = PyString_GET_SIZE(obj);
  1579. if (size == 1) {
  1580. ord = (long)((unsigned char)*PyString_AS_STRING(obj));
  1581. return PyInt_FromLong(ord);
  1582. }
  1583. } else if (PyByteArray_Check(obj)) {
  1584. size = PyByteArray_GET_SIZE(obj);
  1585. if (size == 1) {
  1586. ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
  1587. return PyInt_FromLong(ord);
  1588. }
  1589. #ifdef Py_USING_UNICODE
  1590. } else if (PyUnicode_Check(obj)) {
  1591. size = PyUnicode_GET_SIZE(obj);
  1592. if (size == 1) {
  1593. ord = (long)*PyUnicode_AS_UNICODE(obj);
  1594. return PyInt_FromLong(ord);
  1595. }
  1596. #endif
  1597. } else {
  1598. PyErr_Format(PyExc_TypeError,
  1599. "ord() expected string of length 1, but " \
  1600. "%.200s found", obj->ob_type->tp_name);
  1601. return NULL;
  1602. }
  1603. PyErr_Format(PyExc_TypeError,
  1604. "ord() expected a character, "
  1605. "but string of length %zd found",
  1606. size);
  1607. return NULL;
  1608. }
  1609. PyDoc_STRVAR(ord_doc,
  1610. "ord(c) -> integer\n\
  1611. \n\
  1612. Return the integer ordinal of a one-character string.");
  1613. static PyObject *
  1614. builtin_pow(PyObject *self, PyObject *v, PyObject *w, PyObject *z)
  1615. {
  1616. if (z == NULL)
  1617. z = Py_None;
  1618. return PyNumber_Power(v, w, z);
  1619. }
  1620. PyDoc_STRVAR(pow_doc,
  1621. "pow(x, y[, z]) -> number\n\
  1622. \n\
  1623. With two arguments, equivalent to x**y. With three arguments,\n\
  1624. equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
  1625. static PyObject *
  1626. builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
  1627. {
  1628. static char *kwlist[] = {"sep", "end", "file", 0};
  1629. static PyObject *dummy_args = NULL;
  1630. static PyObject *unicode_newline = NULL, *unicode_space = NULL;
  1631. static PyObject *str_newline = NULL, *str_space = NULL;
  1632. PyObject *newline, *space;
  1633. PyObject *sep = NULL, *end = NULL, *file = NULL;
  1634. int i, err, use_unicode = 0;
  1635. if (dummy_args == NULL) {
  1636. if (!(dummy_args = PyTuple_New(0)))
  1637. return NULL;
  1638. }
  1639. if (str_newline == NULL) {
  1640. str_newline = PyString_FromString("\n");
  1641. if (str_newline == NULL)
  1642. return NULL;
  1643. str_space = PyString_FromString(" ");
  1644. if (str_space == NULL) {
  1645. Py_CLEAR(str_newline);
  1646. return NULL;
  1647. }
  1648. unicode_newline = PyUnicode_FromString("\n");
  1649. if (unicode_newline == NULL) {
  1650. Py_CLEAR(str_newline);
  1651. Py_CLEAR(str_space);
  1652. return NULL;
  1653. }
  1654. unicode_space = PyUnicode_FromString(" ");
  1655. if (unicode_space == NULL) {
  1656. Py_CLEAR(str_newline);
  1657. Py_CLEAR(str_space);
  1658. Py_CLEAR(unicode_space);
  1659. return NULL;
  1660. }
  1661. }
  1662. if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
  1663. kwlist, &sep, &end, &file))
  1664. return NULL;
  1665. if (file == NULL || file == Py_None) {
  1666. file = PySys_GetObject("stdout");
  1667. /* sys.stdout may be None when FILE* stdout isn't connected */
  1668. if (file == Py_None)
  1669. Py_RETURN_NONE;
  1670. }
  1671. if (sep == Py_None) {
  1672. sep = NULL;
  1673. }
  1674. else if (sep) {
  1675. if (PyUnicode_Check(sep)) {
  1676. use_unicode = 1;
  1677. }
  1678. else if (!PyString_Check(sep)) {
  1679. PyErr_Format(PyExc_TypeError,
  1680. "sep must be None, str or unicode, not %.200s",
  1681. sep->ob_type->tp_name);
  1682. return NULL;
  1683. }
  1684. }
  1685. if (end == Py_None)
  1686. end = NULL;
  1687. else if (end) {
  1688. if (PyUnicode_Check(end)) {
  1689. use_unicode = 1;
  1690. }
  1691. else if (!PyString_Check(end)) {
  1692. PyErr_Format(PyExc_TypeError,
  1693. "end must be None, str or unicode, not %.200s",
  1694. end->ob_type->tp_name);
  1695. return NULL;
  1696. }
  1697. }
  1698. if (!use_unicode) {
  1699. for (i = 0; i < PyTuple_Size(args); i++) {
  1700. if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
  1701. use_unicode = 1;
  1702. break;
  1703. }
  1704. }
  1705. }
  1706. if (use_unicode) {
  1707. newline = unicode_newline;
  1708. space = unicode_space;
  1709. }
  1710. else {
  1711. newline = str_newline;
  1712. space = str_space;
  1713. }
  1714. for (i = 0; i < PyTuple_Size(args); i++) {
  1715. if (i > 0) {
  1716. if (sep == NULL)
  1717. err = PyFile_WriteObject(space, file,
  1718. Py_PRINT_RAW);
  1719. else
  1720. err = PyFile_WriteObject(sep, file,
  1721. Py_PRINT_RAW);
  1722. if (err)
  1723. return NULL;
  1724. }
  1725. err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
  1726. Py_PRINT_RAW);
  1727. if (err)
  1728. return NULL;
  1729. }
  1730. if (end == NULL)
  1731. err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
  1732. else
  1733. err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
  1734. if (err)
  1735. return NULL;
  1736. Py_RETURN_NONE;
  1737. }
  1738. PyDoc_STRVAR(print_doc,
  1739. "print(value, ..., sep=' ', end='\\n', file=sys.stdout)\n\
  1740. \n\
  1741. Prints the values to a stream, or to sys.stdout by default.\n\
  1742. Optional keyword arguments:\n\
  1743. file: a file-like object (stream); defaults to the current sys.stdout.\n\
  1744. sep: string inserted between values, default a space.\n\
  1745. end: string appended after the last value, default a newline.");
  1746. static void
  1747. print_stmt_set_softspace(PyObject *obj, PyObject *file)
  1748. {
  1749. if (PyString_Check(obj)) {
  1750. char *s = PyString_AS_STRING(obj);
  1751. Py_ssize_t len = PyString_GET_SIZE(obj);
  1752. if (len == 0 || !isspace(Py_CHARMASK(s[len-1])) || s[len-1] == ' ')
  1753. PyFile_SoftSpace(file, 1);
  1754. }
  1755. #ifdef Py_USING_UNICODE
  1756. else if (PyUnicode_Check(obj)) {
  1757. Py_UNICODE *s = PyUnicode_AS_UNICODE(obj);
  1758. Py_ssize_t len = PyUnicode_GET_SIZE(obj);
  1759. if (len == 0 || !Py_UNICODE_ISSPACE(s[len-1]) || s[len-1] == ' ')
  1760. PyFile_SoftSpace(file, 1);
  1761. }
  1762. #endif
  1763. else
  1764. PyFile_SoftSpace(file, 1);
  1765. }
  1766. /* This is the builtin_print() function above, but with support for all the
  1767. * softspace stuff needed to implement the print statement.
  1768. */
  1769. static PyObject *
  1770. builtin_print_stmt(PyObject *self, PyObject *args, PyObject *kwds)
  1771. {
  1772. static char *kwlist[] = {"end", "file", 0};
  1773. static PyObject *dummy_args;
  1774. PyObject *end = NULL, *file = NULL, *to_print;
  1775. int i, err = 0;
  1776. if (dummy_args == NULL) {
  1777. if ((dummy_args = PyTuple_New(0)) == NULL)
  1778. return NULL;
  1779. }
  1780. if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OO:print_stmt",
  1781. kwlist, &end, &file))
  1782. return NULL;
  1783. if (file == NULL || file == Py_None) {
  1784. file = PySys_GetObject("stdout");
  1785. /* sys.stdout may be None when FILE* stdout isn't connected */
  1786. if (file == Py_None)
  1787. Py_RETURN_NONE;
  1788. else if (file == NULL) {
  1789. PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
  1790. return NULL;
  1791. }
  1792. }
  1793. if (end && end != Py_None && !PyString_Check(end) &&
  1794. !PyUnicode_Check(end)) {
  1795. PyErr_Format(PyExc_TypeError,
  1796. "end must be None, str or unicode, not %.200s",
  1797. end->ob_type->tp_name);
  1798. return NULL;
  1799. }
  1800. /* PyFile_SoftSpace() can exececute arbitrary code
  1801. if sys.stdout is an instance with a __getattr__.
  1802. If __getattr__ raises an exception, w will
  1803. be freed, so we need to prevent that temporarily. */
  1804. Py_INCREF(file);
  1805. if (PyTuple_Size(args) > 0 && PyFile_SoftSpace(file, 0)) {
  1806. if (PyFile_WriteString(" ", file))
  1807. goto on_error;
  1808. }
  1809. for (i = 0; i < PyTuple_Size(args); i++) {
  1810. if (i > 0 && PyFile_SoftSpace(file, 0)) {
  1811. if (PyFile_WriteString(" ", file))
  1812. goto on_error;
  1813. }
  1814. to_print = PyTuple_GetItem(args, i);
  1815. err = PyFile_WriteObject(to_print, file, Py_PRINT_RAW);
  1816. if (err)
  1817. goto on_error;
  1818. print_stmt_set_softspace(to_print, file);
  1819. }
  1820. if (end == NULL || end == Py_None) {
  1821. err = PyFile_WriteString("\n", file);
  1822. PyFile_SoftSpace(file, 0);
  1823. } else if (PyString_Check(end) && PyString_Size(end) == 0) {
  1824. /* Adjust softspace appropriately based on the last item in
  1825. the tuple. */
  1826. if (PyTuple_Size(args)) {
  1827. Py_ssize_t last_idx = PyTuple_Size(args) - 1;
  1828. PyObject *last_obj = PyTuple_GetItem(args, last_idx);
  1829. if (!last_obj)
  1830. goto on_error;
  1831. print_stmt_set_softspace(last_obj, file);
  1832. }
  1833. } else {
  1834. err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
  1835. print_stmt_set_softspace(end, file);
  1836. }
  1837. Py_DECREF(file);
  1838. if (err)
  1839. return NULL;
  1840. Py_RETURN_NONE;
  1841. on_error:
  1842. Py_DECREF(file);
  1843. return NULL;
  1844. }
  1845. /* Return number of items in range (lo, hi, step), when arguments are
  1846. * PyInt or PyLong objects. step > 0 required. Return a value < 0 if
  1847. * & only if the true value is too large to fit in a signed long.
  1848. * Arguments MUST return 1 with either PyInt_Check() or
  1849. * PyLong_Check(). Return -1 when there is an error.
  1850. */
  1851. static long
  1852. get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
  1853. {
  1854. /* -------------------------------------------------------------
  1855. Algorithm is equal to that of get_len_of_range(), but it operates
  1856. on PyObjects (which are assumed to be PyLong or PyInt objects).
  1857. ---------------------------------------------------------------*/
  1858. long n;
  1859. PyObject *diff = NULL;
  1860. PyObject *one = NULL;
  1861. PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
  1862. /* holds sub-expression evaluations */
  1863. /* if (lo >= hi), return length of 0. */
  1864. if (PyObject_Compare(lo, hi) >= 0)
  1865. return 0;
  1866. if ((one = PyLong_FromLong(1L)) == NULL)
  1867. goto Fail;
  1868. if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
  1869. goto Fail;
  1870. if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
  1871. goto Fail;
  1872. if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
  1873. goto Fail;
  1874. if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
  1875. goto Fail;
  1876. n = PyLong_AsLong(tmp3);
  1877. if (PyErr_Occurred()) { /* Check for Overflow */
  1878. PyErr_Clear();
  1879. goto Fail;
  1880. }
  1881. Py_DECREF(tmp3);
  1882. Py_DECREF(tmp2);
  1883. Py_DECREF(diff);
  1884. Py_DECREF(tmp1);
  1885. Py_DECREF(one);
  1886. return n;
  1887. Fail:
  1888. Py_XDECREF(tmp3);
  1889. Py_XDECREF(tmp2);
  1890. Py_XDECREF(diff);
  1891. Py_XDECREF(tmp1);
  1892. Py_XDECREF(one);
  1893. return -1;
  1894. }
  1895. /* An extension of builtin_range() that handles the case when PyLong
  1896. * arguments are given. */
  1897. static PyObject *
  1898. handle_range_longs(PyObject *self, PyObject *args)
  1899. {
  1900. PyObject *ilow;
  1901. PyObject *ihigh = NULL;
  1902. PyObject *istep = NULL;
  1903. PyObject *curnum = NULL;
  1904. PyObject *v = NULL;
  1905. long bign;
  1906. int i, n;
  1907. int cmp_result;
  1908. PyObject *zero = PyLong_FromLong(0);
  1909. if (zero == NULL)
  1910. return NULL;
  1911. if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
  1912. Py_DECREF(zero);
  1913. return NULL;
  1914. }
  1915. /* Figure out which way we were called, supply defaults, and be
  1916. * sure to incref everything so that the decrefs at the end
  1917. * are correct.
  1918. */
  1919. assert(ilow != NULL);
  1920. if (ihigh == NULL) {
  1921. /* only 1 arg -- it's the upper limit */
  1922. ihigh = ilow;
  1923. ilow = NULL;
  1924. }
  1925. assert(ihigh != NULL);
  1926. Py_INCREF(ihigh);
  1927. /* ihigh correct now; do ilow */
  1928. if (ilow == NULL)
  1929. ilow = zero;
  1930. Py_INCREF(ilow);
  1931. /* ilow and ihigh correct now; do istep */
  1932. if (istep == NULL) {
  1933. istep = PyLong_FromLong(1L);
  1934. if (istep == NULL)
  1935. goto Fail;
  1936. }
  1937. else {
  1938. Py_INCREF(istep);
  1939. }
  1940. if (!PyInt_Check(ilow) && !PyLong_Check(ilow)) {
  1941. PyErr_Format(PyExc_TypeError,
  1942. "range() integer start argument expected, got %s.",
  1943. ilow->ob_type->tp_name);
  1944. goto Fail;
  1945. }
  1946. if (!PyInt_Check(ihigh) && !PyLong_Check(ihigh)) {
  1947. PyErr_Format(PyExc_TypeError,
  1948. "range() integer end argument expected, got %s.",
  1949. ihigh->ob_type->tp_name);
  1950. goto Fail;
  1951. }
  1952. if (!PyInt_Check(istep) && !PyLong_Check(istep)) {
  1953. PyErr_Format(PyExc_TypeError,
  1954. "range() integer step argument expected, got %s.",
  1955. istep->ob_type->tp_name);
  1956. goto Fail;
  1957. }
  1958. if (PyObject_Cmp(istep, zero, &cmp_result) == -1)
  1959. goto Fail;
  1960. if (cmp_result == 0) {
  1961. PyErr_SetString(PyExc_ValueError,
  1962. "range() step argument must not be zero");
  1963. goto Fail;
  1964. }
  1965. if (cmp_result > 0)
  1966. bign = get_len_of_range_longs(ilow, ihigh, istep);
  1967. else {
  1968. PyObject *neg_istep = PyNumber_Negative(istep);
  1969. if (neg_istep == NULL)
  1970. goto Fail;
  1971. bign = get_len_of_range_longs(ihigh, ilow, neg_istep);
  1972. Py_DECREF(neg_istep);
  1973. }
  1974. n = (int)bign;
  1975. if (bign < 0 || (long)n != bign) {
  1976. PyErr_SetString(PyExc_OverflowError,
  1977. "range() result has too many items");
  1978. goto Fail;
  1979. }
  1980. v = PyList_New(n);
  1981. if (v == NULL)
  1982. goto Fail;
  1983. curnum = ilow;
  1984. Py_INCREF(curnum);
  1985. for (i = 0; i < n; i++) {
  1986. PyObject *w = PyNumber_Long(curnum);
  1987. PyObject *tmp_num;
  1988. if (w == NULL)
  1989. goto Fail;
  1990. PyList_SET_ITEM(v, i, w);
  1991. tmp_num = PyNumber_Add(curnum, istep);
  1992. if (tmp_num == NULL)
  1993. goto Fail;
  1994. Py_DECREF(curnum);
  1995. curnum = tmp_num;
  1996. }
  1997. Py_DECREF(ilow);
  1998. Py_DECREF(ihigh);
  1999. Py_DECREF(istep);
  2000. Py_DECREF(zero);
  2001. Py_DECREF(curnum);
  2002. return v;
  2003. Fail:
  2004. Py_DECREF(ilow);
  2005. Py_DECREF(ihigh);
  2006. Py_XDECREF(istep);
  2007. Py_DECREF(zero);
  2008. Py_XDECREF(curnum);
  2009. Py_XDECREF(v);
  2010. return NULL;
  2011. }
  2012. /* Return number of items in range/xrange (lo, hi, step). step > 0
  2013. * required. Return a value < 0 if & only if the true value is too
  2014. * large to fit in a signed long.
  2015. */
  2016. static long
  2017. get_len_of_range(long lo, long hi, long step)
  2018. {
  2019. /* -------------------------------------------------------------
  2020. If lo >= hi, the range is empty.
  2021. Else if n values are in the range, the last one is
  2022. lo + (n-1)*step, which must be <= hi-1. Rearranging,
  2023. n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
  2024. the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
  2025. the RHS is non-negative and so truncation is the same as the
  2026. floor. Letting M be the largest positive long, the worst case
  2027. for the RHS numerator is hi=M, lo=-M-1, and then
  2028. hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
  2029. precision to compute the RHS exactly.
  2030. ---------------------------------------------------------------*/
  2031. long n = 0;
  2032. if (lo < hi) {
  2033. unsigned long uhi = (unsigned long)hi;
  2034. unsigned long ulo = (unsigned long)lo;
  2035. unsigned long diff = uhi - ulo - 1;
  2036. n = (long)(diff / (unsigned long)step + 1);
  2037. }
  2038. return n;
  2039. }
  2040. static PyObject *
  2041. builtin_range(PyObject *self, PyObject *args)
  2042. {
  2043. long ilow = 0, ihigh = 0, istep = 1;
  2044. long bign;
  2045. int i, n;
  2046. PyObject *v;
  2047. if (PyTuple_Size(args) <= 1) {
  2048. if (!PyArg_ParseTuple(args,
  2049. "l;range() requires 1-3 int arguments",
  2050. &ihigh)) {
  2051. PyErr_Clear();
  2052. return handle_range_longs(self, args);
  2053. }
  2054. }
  2055. else {
  2056. if (!PyArg_ParseTuple(args,
  2057. "ll|l;range() requires 1-3 int arguments",
  2058. &ilow, &ihigh, &istep)) {
  2059. PyErr_Clear();
  2060. return handle_range_longs(self, args);
  2061. }
  2062. }
  2063. if (istep == 0) {
  2064. PyErr_SetString(PyExc_ValueError,
  2065. "range() step argument must not be zero");
  2066. return NULL;
  2067. }
  2068. if (istep > 0)
  2069. bign = get_len_of_range(ilow, ihigh, istep);
  2070. else
  2071. bign = get_len_of_range(ihigh, ilow, -istep);
  2072. n = (int)bign;
  2073. if (bign < 0 || (long)n != bign) {
  2074. PyErr_SetString(PyExc_OverflowError,
  2075. "range() result has too many items");
  2076. return NULL;
  2077. }
  2078. v = PyList_New(n);
  2079. if (v == NULL)
  2080. return NULL;
  2081. for (i = 0; i < n; i++) {
  2082. PyObject *w = PyInt_FromLong(ilow);
  2083. if (w == NULL) {
  2084. Py_DECREF(v);
  2085. return NULL;
  2086. }
  2087. PyList_SET_ITEM(v, i, w);
  2088. ilow += istep;
  2089. }
  2090. return v;
  2091. }
  2092. PyDoc_STRVAR(range_doc,
  2093. "range([start,] stop[, step]) -> list of integers\n\
  2094. \n\
  2095. Return a list containing an arithmetic progression of integers.\n\
  2096. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.\n\
  2097. When step is given, it specifies the increment (or decrement).\n\
  2098. For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!\n\
  2099. These are exactly the valid indices for a list of 4 elements.");
  2100. static PyObject *
  2101. builtin_raw_input(PyObject *self, PyObject *v)
  2102. {
  2103. PyObject *fin = PySys_GetObject("stdin");
  2104. PyObject *fout = PySys_GetObject("stdout");
  2105. if (fin == NULL) {
  2106. PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
  2107. return NULL;
  2108. }
  2109. if (fout == NULL) {
  2110. PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
  2111. return NULL;
  2112. }
  2113. if (PyFile_SoftSpace(fout, 0)) {
  2114. if (PyFile_WriteString(" ", fout) != 0)
  2115. return NULL;
  2116. }
  2117. if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
  2118. && isatty(fileno(PyFile_AsFile(fin)))
  2119. && isatty(fileno(PyFile_AsFile(fout)))) {
  2120. PyObject *po;
  2121. char *prompt;
  2122. char *s;
  2123. PyObject *result;
  2124. if (v != NULL) {
  2125. po = PyObject_Str(v);
  2126. if (po == NULL)
  2127. return NULL;
  2128. prompt = PyString_AsString(po);
  2129. if (prompt == NULL)
  2130. return NULL;
  2131. }
  2132. else {
  2133. po = NULL;
  2134. prompt = "";
  2135. }
  2136. s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
  2137. prompt);
  2138. Py_XDECREF(po);
  2139. if (s == NULL) {
  2140. if (!PyErr_Occurred())
  2141. PyErr_SetNone(PyExc_KeyboardInterrupt);
  2142. return NULL;
  2143. }
  2144. if (*s == '\0') {
  2145. PyErr_SetNone(PyExc_EOFError);
  2146. result = NULL;
  2147. }
  2148. else { /* strip trailing '\n' */
  2149. size_t len = strlen(s);
  2150. if (len > PY_SSIZE_T_MAX) {
  2151. PyErr_SetString(PyExc_OverflowError,
  2152. "[raw_]input: input too long");
  2153. result = NULL;
  2154. }
  2155. else {
  2156. result = PyString_FromStringAndSize(s, len-1);
  2157. }
  2158. }
  2159. PyMem_FREE(s);
  2160. return result;
  2161. }
  2162. if (v != NULL) {
  2163. if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
  2164. return NULL;
  2165. }
  2166. return PyFile_GetLine(fin, -1);
  2167. }
  2168. PyDoc_STRVAR(raw_input_doc,
  2169. "raw_input([prompt]) -> string\n\
  2170. \n\
  2171. Read a string from standard input. The trailing newline is stripped.\n\
  2172. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.\n\
  2173. On Unix, GNU readline is used if enabled. The prompt string, if given,\n\
  2174. is printed without a trailing newline before reading.");
  2175. static PyObject *
  2176. builtin_reduce(PyObject *self, PyObject *args)
  2177. {
  2178. static PyObject *functools_reduce = NULL;
  2179. if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
  2180. "use functools.reduce()", 1) < 0)
  2181. return NULL;
  2182. if (functools_reduce == NULL) {
  2183. PyObject *functools = PyImport_ImportModule("functools");
  2184. if (functools == NULL)
  2185. return NULL;
  2186. functools_reduce = PyObject_GetAttrString(functools, "reduce");
  2187. Py_DECREF(functools);
  2188. if (functools_reduce == NULL)
  2189. return NULL;
  2190. }
  2191. return PyObject_Call(functools_reduce, args, NULL);
  2192. }
  2193. PyDoc_STRVAR(reduce_doc,
  2194. "reduce(function, sequence[, initial]) -> value\n\
  2195. \n\
  2196. Apply a function of two arguments cumulatively to the items of a sequence,\n\
  2197. from left to right, so as to reduce the sequence to a single value.\n\
  2198. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
  2199. ((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
  2200. of the sequence in the calculation, and serves as a default when the\n\
  2201. sequence is empty.");
  2202. static PyObject *
  2203. builtin_reload(PyObject *self, PyObject *v)
  2204. {
  2205. if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
  2206. 1) < 0)
  2207. return NULL;
  2208. return PyImport_ReloadModule(v);
  2209. }
  2210. PyDoc_STRVAR(reload_doc,
  2211. "reload(module) -> module\n\
  2212. \n\
  2213. Reload the module. The module must have been successfully imported before.");
  2214. static PyObject *
  2215. builtin_repr(PyObject *self, PyObject *v)
  2216. {
  2217. return PyObject_Repr(v);
  2218. }
  2219. PyDoc_STRVAR(repr_doc,
  2220. "repr(object) -> string\n\
  2221. \n\
  2222. Return the canonical string representation of the object.\n\
  2223. For most object types, eval(repr(object)) == object.");
  2224. static PyObject *
  2225. builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
  2226. {
  2227. double number;
  2228. double f;
  2229. int ndigits = 0;
  2230. int i;
  2231. static char *kwlist[] = {"number", "ndigits", 0};
  2232. if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|i:round",
  2233. kwlist, &number, &ndigits))
  2234. return NULL;
  2235. f = 1.0;
  2236. i = abs(ndigits);
  2237. while (--i >= 0)
  2238. f = f*10.0;
  2239. if (ndigits < 0)
  2240. number /= f;
  2241. else
  2242. number *= f;
  2243. if (number >= 0.0)
  2244. number = floor(number + 0.5);
  2245. else
  2246. number = ceil(number - 0.5);
  2247. if (ndigits < 0)
  2248. number *= f;
  2249. else
  2250. number /= f;
  2251. return PyFloat_FromDouble(number);
  2252. }
  2253. PyDoc_STRVAR(round_doc,
  2254. "round(number[, ndigits]) -> floating point number\n\
  2255. \n\
  2256. Round a number to a given precision in decimal digits (default 0 digits).\n\
  2257. This always returns a floating point number. Precision may be negative.");
  2258. static PyObject *
  2259. builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
  2260. {
  2261. PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
  2262. PyObject *callable;
  2263. static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
  2264. int reverse;
  2265. /* args 1-4 should match listsort in Objects/listobject.c */
  2266. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
  2267. kwlist, &seq, &compare, &keyfunc, &reverse))
  2268. return NULL;
  2269. newlist = PySequence_List(seq);
  2270. if (newlist == NULL)
  2271. return NULL;
  2272. callable = PyObject_GetAttrString(newlist, "sort");
  2273. if (callable == NULL) {
  2274. Py_DECREF(newlist);
  2275. return NULL;
  2276. }
  2277. newargs = PyTuple_GetSlice(args, 1, 4);
  2278. if (newargs == NULL) {
  2279. Py_DECREF(newlist);
  2280. Py_DECREF(callable);
  2281. return NULL;
  2282. }
  2283. v = PyObject_Call(callable, newargs, kwds);
  2284. Py_DECREF(newargs);
  2285. Py_DECREF(callable);
  2286. if (v == NULL) {
  2287. Py_DECREF(newlist);
  2288. return NULL;
  2289. }
  2290. Py_DECREF(v);
  2291. return newlist;
  2292. }
  2293. PyDoc_STRVAR(sorted_doc,
  2294. "sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list");
  2295. static PyObject *
  2296. builtin_vars(PyObject *self, PyObject *v)
  2297. {
  2298. PyObject *d;
  2299. if (v == NULL) {
  2300. d = PyEval_GetLocals();
  2301. if (d == NULL) {
  2302. if (!PyErr_Occurred())
  2303. PyErr_SetString(PyExc_SystemError,
  2304. "vars(): no locals!?");
  2305. }
  2306. else
  2307. Py_INCREF(d);
  2308. }
  2309. else {
  2310. d = PyObject_GetAttrString(v, "__dict__");
  2311. if (d == NULL) {
  2312. PyErr_SetString(PyExc_TypeError,
  2313. "vars() argument must have __dict__ attribute");
  2314. return NULL;
  2315. }
  2316. }
  2317. return d;
  2318. }
  2319. PyDoc_STRVAR(vars_doc,
  2320. "vars([object]) -> dictionary\n\
  2321. \n\
  2322. Without arguments, equivalent to locals().\n\
  2323. With an argument, equivalent to object.__dict__.");
  2324. static PyObject*
  2325. builtin_sum(PyObject *self, PyObject *seq, PyObject *result)
  2326. {
  2327. PyObject *temp, *item, *iter;
  2328. iter = PyObject_GetIter(seq);
  2329. if (iter == NULL)
  2330. return NULL;
  2331. if (result == NULL) {
  2332. result = PyInt_FromLong(0);
  2333. if (result == NULL) {
  2334. Py_DECREF(iter);
  2335. return NULL;
  2336. }
  2337. } else {
  2338. /* reject string values for 'start' parameter */
  2339. if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
  2340. PyErr_SetString(PyExc_TypeError,
  2341. "sum() can't sum strings [use ''.join(seq) instead]");
  2342. Py_DECREF(iter);
  2343. return NULL;
  2344. }
  2345. Py_INCREF(result);
  2346. }
  2347. #ifndef SLOW_SUM
  2348. /* Fast addition by keeping temporary sums in C instead of new Python objects.
  2349. Assumes all inputs are the same type. If the assumption fails, default
  2350. to the more general routine.
  2351. */
  2352. if (PyInt_CheckExact(result)) {
  2353. long i_result = PyInt_AS_LONG(result);
  2354. Py_DECREF(result);
  2355. result = NULL;
  2356. while(result == NULL) {
  2357. item = PyIter_Next(iter);
  2358. if (item == NULL) {
  2359. Py_DECREF(iter);
  2360. if (PyErr_Occurred())
  2361. return NULL;
  2362. return PyInt_FromLong(i_result);
  2363. }
  2364. if (PyInt_CheckExact(item)) {
  2365. long b = PyInt_AS_LONG(item);
  2366. long x = i_result + b;
  2367. if ((x^i_result) >= 0 || (x^b) >= 0) {
  2368. i_result = x;
  2369. Py_DECREF(item);
  2370. continue;
  2371. }
  2372. }
  2373. /* Either overflowed or is not an int. Restore real objects and process normally */
  2374. result = PyInt_FromLong(i_result);
  2375. temp = PyNumber_Add(result, item);
  2376. Py_DECREF(result);
  2377. Py_DECREF(item);
  2378. result = temp;
  2379. if (result == NULL) {
  2380. Py_DECREF(iter);
  2381. return NULL;
  2382. }
  2383. }
  2384. }
  2385. if (PyFloat_CheckExact(result)) {
  2386. double f_result = PyFloat_AS_DOUBLE(result);
  2387. Py_DECREF(result);
  2388. result = NULL;
  2389. while(result == NULL) {
  2390. item = PyIter_Next(iter);
  2391. if (item == NULL) {
  2392. Py_DECREF(iter);
  2393. if (PyErr_Occurred())
  2394. return NULL;
  2395. return PyFloat_FromDouble(f_result);
  2396. }
  2397. if (PyFloat_CheckExact(item)) {
  2398. PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
  2399. f_result += PyFloat_AS_DOUBLE(item);
  2400. PyFPE_END_PROTECT(f_result)
  2401. Py_DECREF(item);
  2402. continue;
  2403. }
  2404. if (PyInt_CheckExact(item)) {
  2405. PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
  2406. f_result += (double)PyInt_AS_LONG(item);
  2407. PyFPE_END_PROTECT(f_result)
  2408. Py_DECREF(item);
  2409. continue;
  2410. }
  2411. result = PyFloat_FromDouble(f_result);
  2412. temp = PyNumber_Add(result, item);
  2413. Py_DECREF(result);
  2414. Py_DECREF(item);
  2415. result = temp;
  2416. if (result == NULL) {
  2417. Py_DECREF(iter);
  2418. return NULL;
  2419. }
  2420. }
  2421. }
  2422. #endif
  2423. for(;;) {
  2424. item = PyIter_Next(iter);
  2425. if (item == NULL) {
  2426. /* error, or end-of-sequence */
  2427. if (PyErr_Occurred()) {
  2428. Py_DECREF(result);
  2429. result = NULL;
  2430. }
  2431. break;
  2432. }
  2433. temp = PyNumber_Add(result, item);
  2434. Py_DECREF(result);
  2435. Py_DECREF(item);
  2436. result = temp;
  2437. if (result == NULL)
  2438. break;
  2439. }
  2440. Py_DECREF(iter);
  2441. return result;
  2442. }
  2443. PyDoc_STRVAR(sum_doc,
  2444. "sum(sequence[, start]) -> value\n\
  2445. \n\
  2446. Returns the sum of a sequence of numbers (NOT strings) plus the value\n\
  2447. of parameter 'start' (which defaults to 0). When the sequence is\n\
  2448. empty, returns start.");
  2449. static PyObject *
  2450. builtin_isinstance(PyObject *self, PyObject *inst, PyObject *cls)
  2451. {
  2452. int retval;
  2453. retval = PyObject_IsInstance(inst, cls);
  2454. if (retval < 0)
  2455. return NULL;
  2456. return PyBool_FromLong(retval);
  2457. }
  2458. PyDoc_STRVAR(isinstance_doc,
  2459. "isinstance(object, class-or-type-or-tuple) -> bool\n\
  2460. \n\
  2461. Return whether an object is an instance of a class or of a subclass thereof.\n\
  2462. With a type as second argument, return whether that is the object's type.\n\
  2463. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\n\
  2464. isinstance(x, A) or isinstance(x, B) or ... (etc.).");
  2465. static PyObject *
  2466. builtin_issubclass(PyObject *self, PyObject *derived, PyObject *cls)
  2467. {
  2468. int retval;
  2469. retval = PyObject_IsSubclass(derived, cls);
  2470. if (retval < 0)
  2471. return NULL;
  2472. return PyBool_FromLong(retval);
  2473. }
  2474. PyDoc_STRVAR(issubclass_doc,
  2475. "issubclass(C, B) -> bool\n\
  2476. \n\
  2477. Return whether class C is a subclass (i.e., a derived class) of class B.\n\
  2478. When using a tuple as the second argument issubclass(X, (A, B, ...)),\n\
  2479. is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
  2480. static PyObject*
  2481. builtin_zip(PyObject *self, PyObject *args)
  2482. {
  2483. PyObject *ret;
  2484. const Py_ssize_t itemsize = PySequence_Length(args);
  2485. Py_ssize_t i;
  2486. PyObject *itlist; /* tuple of iterators */
  2487. Py_ssize_t len; /* guess at result length */
  2488. if (itemsize == 0)
  2489. return PyList_New(0);
  2490. /* args must be a tuple */
  2491. assert(PyTuple_Check(args));
  2492. /* Guess at result length: the shortest of the input lengths.
  2493. If some argument refuses to say, we refuse to guess too, lest
  2494. an argument like xrange(sys.maxint) lead us astray.*/
  2495. len = -1; /* unknown */
  2496. for (i = 0; i < itemsize; ++i) {
  2497. PyObject *item = PyTuple_GET_ITEM(args, i);
  2498. Py_ssize_t thislen = _PyObject_LengthHint(item, -1);
  2499. if (thislen < 0) {
  2500. len = -1;
  2501. break;
  2502. }
  2503. else if (len < 0 || thislen < len)
  2504. len = thislen;
  2505. }
  2506. /* allocate result list */
  2507. if (len < 0)
  2508. len = 10; /* arbitrary */
  2509. if ((ret = PyList_New(len)) == NULL)
  2510. return NULL;
  2511. /* obtain iterators */
  2512. itlist = PyTuple_New(itemsize);
  2513. if (itlist == NULL)
  2514. goto Fail_ret;
  2515. for (i = 0; i < itemsize; ++i) {
  2516. PyObject *item = PyTuple_GET_ITEM(args, i);
  2517. PyObject *it = PyObject_GetIter(item);
  2518. if (it == NULL) {
  2519. if (PyErr_ExceptionMatches(PyExc_TypeError))
  2520. PyErr_Format(PyExc_TypeError,
  2521. "zip argument #%zd must support iteration",
  2522. i+1);
  2523. goto Fail_ret_itlist;
  2524. }
  2525. PyTuple_SET_ITEM(itlist, i, it);
  2526. }
  2527. /* build result into ret list */
  2528. for (i = 0; ; ++i) {
  2529. int j;
  2530. PyObject *next = PyTuple_New(itemsize);
  2531. if (!next)
  2532. goto Fail_ret_itlist;
  2533. for (j = 0; j < itemsize; j++) {
  2534. PyObject *it = PyTuple_GET_ITEM(itlist, j);
  2535. PyObject *item = PyIter_Next(it);
  2536. if (!item) {
  2537. if (PyErr_Occurred()) {
  2538. Py_DECREF(ret);
  2539. ret = NULL;
  2540. }
  2541. Py_DECREF(next);
  2542. Py_DECREF(itlist);
  2543. goto Done;
  2544. }
  2545. PyTuple_SET_ITEM(next, j, item);
  2546. }
  2547. if (i < len)
  2548. PyList_SET_ITEM(ret, i, next);
  2549. else {
  2550. int status = PyList_Append(ret, next);
  2551. Py_DECREF(next);
  2552. ++len;
  2553. if (status < 0)
  2554. goto Fail_ret_itlist;
  2555. }
  2556. }
  2557. Done:
  2558. if (ret != NULL && i < len) {
  2559. /* The list is too big. */
  2560. if (PyList_SetSlice(ret, i, len, NULL) < 0)
  2561. return NULL;
  2562. }
  2563. return ret;
  2564. Fail_ret_itlist:
  2565. Py_DECREF(itlist);
  2566. Fail_ret:
  2567. Py_DECREF(ret);
  2568. return NULL;
  2569. }
  2570. PyDoc_STRVAR(zip_doc,
  2571. "zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\
  2572. \n\
  2573. Return a list of tuples, where each tuple contains the i-th element\n\
  2574. from each of the argument sequences. The returned list is truncated\n\
  2575. in length to the length of the shortest argument sequence.");
  2576. static PyMethodDef builtin_methods[] = {
  2577. {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
  2578. {"abs", builtin_abs, METH_O, abs_doc},
  2579. {"all", builtin_all, METH_O, all_doc},
  2580. {"any", builtin_any, METH_O, any_doc},
  2581. {"apply", (PyCFunction)builtin_apply, METH_ARG_RANGE,
  2582. apply_doc, /*min_arity=*/1, /*max_arity=*/3},
  2583. {"bin", builtin_bin, METH_O, bin_doc},
  2584. {"callable", builtin_callable, METH_O, callable_doc},
  2585. {"chr", (PyCFunction)builtin_chr, METH_ARG_RANGE,
  2586. chr_doc, /*min_arity=*/1, /*max_arity=*/1},
  2587. {"cmp", (PyCFunction)builtin_cmp, METH_ARG_RANGE,
  2588. cmp_doc, /*min_arity=*/2, /*max_arity=*/2},
  2589. {"coerce", (PyCFunction)builtin_coerce, METH_ARG_RANGE,
  2590. coerce_doc, /*min_arity=*/2, /*max_arity=*/2},
  2591. {"compile", (PyCFunction)builtin_compile,
  2592. METH_VARARGS | METH_KEYWORDS, compile_doc},
  2593. {"delattr", (PyCFunction)builtin_delattr, METH_ARG_RANGE,
  2594. delattr_doc, /*min_arity=*/2, /*max_arity=*/2},
  2595. {"dir", (PyCFunction)builtin_dir, METH_ARG_RANGE,
  2596. dir_doc, /*min_arity=*/0, /*max_arity=*/1},
  2597. {"divmod", (PyCFunction)builtin_divmod, METH_ARG_RANGE,
  2598. divmod_doc, /*min_arity=*/2, /*max_arity=*/2},
  2599. {"eval", (PyCFunction)builtin_eval, METH_ARG_RANGE,
  2600. eval_doc, /*min_arity=*/1, /*max_arity=*/3},
  2601. {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
  2602. {"filter", (PyCFunction)builtin_filter, METH_ARG_RANGE,
  2603. filter_doc, /*min_arity=*/2, /*max_arity=*/2},
  2604. {"format", (PyCFunction)builtin_format, METH_ARG_RANGE,
  2605. format_doc, /*min_arity=*/1, /*max_arity=*/2},
  2606. {"getattr", (PyCFunction)builtin_getattr, METH_ARG_RANGE,
  2607. getattr_doc, /*min_arity=*/2, /*max_arity=*/3},
  2608. {"globals", (PyCFunction)builtin_globals, METH_NOARGS,
  2609. globals_doc},
  2610. {"hasattr", (PyCFunction)builtin_hasattr, METH_ARG_RANGE,
  2611. hasattr_doc, /*min_arity=*/2, /*max_arity=*/2},
  2612. {"hash", builtin_hash, METH_O, hash_doc},
  2613. {"hex", builtin_hex, METH_O, hex_doc},
  2614. {"id", builtin_id, METH_O, id_doc},
  2615. {"input", builtin_input, METH_ARG_RANGE, input_doc, 0, 1},
  2616. {"intern", (PyCFunction)builtin_intern, METH_ARG_RANGE,
  2617. intern_doc, /*min_arity=*/1, /*max_arity=*/1},
  2618. {"isinstance", (PyCFunction)builtin_isinstance, METH_ARG_RANGE,
  2619. isinstance_doc, /*min_arity=*/2, /*max_arity=*/2},
  2620. {"issubclass", (PyCFunction)builtin_issubclass, METH_ARG_RANGE,
  2621. issubclass_doc, /*min_arity=*/2, /*max_arity=*/2},
  2622. {"iter", (PyCFunction)builtin_iter, METH_ARG_RANGE,
  2623. iter_doc, /*min_arity=*/1, /*max_arity=*/2},
  2624. {"len", _PyBuiltin_Len, METH_O, len_doc},
  2625. {"locals", (PyCFunction)builtin_locals, METH_NOARGS,
  2626. locals_doc},
  2627. {"map", builtin_map, METH_VARARGS, map_doc},
  2628. {"max", (PyCFunction)builtin_max,
  2629. METH_VARARGS | METH_KEYWORDS, max_doc},
  2630. {"min", (PyCFunction)builtin_min,
  2631. METH_VARARGS | METH_KEYWORDS, min_doc},
  2632. {"next", (PyCFunction)builtin_next, METH_ARG_RANGE,
  2633. next_doc, /*min_arity=*/1, /*max_arity=*/2},
  2634. {"oct", builtin_oct, METH_O, oct_doc},
  2635. {"open", (PyCFunction)builtin_open,
  2636. METH_VARARGS | METH_KEYWORDS, open_doc},
  2637. {"ord", builtin_ord, METH_O, ord_doc},
  2638. {"pow", (PyCFunction)builtin_pow, METH_ARG_RANGE,
  2639. pow_doc, /*min_arity=*/2, /*max_arity=*/3},
  2640. {"print", (PyCFunction)builtin_print,
  2641. METH_VARARGS | METH_KEYWORDS, print_doc},
  2642. {"range", builtin_range, METH_VARARGS, range_doc},
  2643. {"raw_input", (PyCFunction)builtin_raw_input, METH_ARG_RANGE,
  2644. raw_input_doc, /*min_arity=*/0, /*max_arity=*/1},
  2645. {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
  2646. {"reload", builtin_reload, METH_O, reload_doc},
  2647. {"repr", builtin_repr, METH_O, repr_doc},
  2648. {"round", (PyCFunction)builtin_round,
  2649. METH_VARARGS | METH_KEYWORDS, round_doc},
  2650. {"setattr", (PyCFunction)builtin_setattr, METH_ARG_RANGE,
  2651. setattr_doc, /*min_arity=*/3, /*max_arity=*/3},
  2652. {"sorted", (PyCFunction)builtin_sorted,
  2653. METH_VARARGS | METH_KEYWORDS, sorted_doc},
  2654. {"sum", (PyCFunction)builtin_sum, METH_ARG_RANGE,
  2655. sum_doc, /*min_arity=*/1, /*max_arity=*/2},
  2656. #ifdef Py_USING_UNICODE
  2657. {"unichr", (PyCFunction)builtin_unichr, METH_ARG_RANGE,
  2658. unichr_doc, /*min_arity=*/1, /*max_arity=*/1},
  2659. #endif
  2660. {"vars", (PyCFunction)builtin_vars, METH_ARG_RANGE,
  2661. vars_doc, /*min_arity=*/0, /*max_arity=*/1},
  2662. {"zip", builtin_zip, METH_VARARGS, zip_doc},
  2663. /* The following built-in functions are for internal use only. */
  2664. {"#@buildclass", (PyCFunction)builtin_buildclass, METH_ARG_RANGE,
  2665. buildclass_doc, /*min_arity=*/3, /*max_arity=*/3},
  2666. {"#@displayhook", builtin_displayhook, METH_VARARGS,
  2667. displayhook_doc},
  2668. {"#@exec", (PyCFunction)builtin_exec, METH_ARG_RANGE,
  2669. exec_doc, /*min_arity=*/1, /*max_arity=*/3},
  2670. {"#@import_from", (PyCFunction)builtin_import_from,
  2671. METH_ARG_RANGE, import_from_doc, /*min_arity=*/2, /*max_arity=*/2},
  2672. {"#@import_star", (PyCFunction)builtin_import_star, METH_O,
  2673. import_star_doc},
  2674. {"#@locals", (PyCFunction)builtin_locals, METH_NOARGS,
  2675. locals_doc},
  2676. {"#@make_function", builtin_make_function, METH_VARARGS,
  2677. make_function_doc},
  2678. {"#@print_stmt", (PyCFunction)builtin_print_stmt,
  2679. METH_VARARGS | METH_KEYWORDS, print_doc},
  2680. {NULL, NULL},
  2681. };
  2682. PyDoc_STRVAR(builtin_doc,
  2683. "Built-in functions, exceptions, and other objects.\n\
  2684. \n\
  2685. Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
  2686. PyObject *
  2687. _PyBuiltin_Init(void)
  2688. {
  2689. PyObject *mod, *dict, *debug;
  2690. mod = Py_InitModule4("__builtin__", builtin_methods,
  2691. builtin_doc, (PyObject *)NULL,
  2692. PYTHON_API_VERSION);
  2693. if (mod == NULL)
  2694. return NULL;
  2695. dict = PyModule_GetDict(mod);
  2696. #ifdef Py_TRACE_REFS
  2697. /* __builtin__ exposes a number of statically allocated objects
  2698. * that, before this code was added in 2.3, never showed up in
  2699. * the list of "all objects" maintained by Py_TRACE_REFS. As a
  2700. * result, programs leaking references to None and False (etc)
  2701. * couldn't be diagnosed by examining sys.getobjects(0).
  2702. */
  2703. #define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
  2704. #else
  2705. #define ADD_TO_ALL(OBJECT) (void)0
  2706. #endif
  2707. #define SETBUILTIN(NAME, OBJECT) \
  2708. if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
  2709. return NULL; \
  2710. ADD_TO_ALL(OBJECT)
  2711. SETBUILTIN("None", Py_None);
  2712. SETBUILTIN("Ellipsis", Py_Ellipsis);
  2713. SETBUILTIN("NotImplemented", Py_NotImplemented);
  2714. SETBUILTIN("False", Py_False);
  2715. SETBUILTIN("True", Py_True);
  2716. SETBUILTIN("basestring", &PyBaseString_Type);
  2717. SETBUILTIN("bool", &PyBool_Type);
  2718. /* SETBUILTIN("memoryview", &PyMemoryView_Type); */
  2719. SETBUILTIN("bytearray", &PyByteArray_Type);
  2720. SETBUILTIN("bytes", &PyString_Type);
  2721. SETBUILTIN("buffer", &PyBuffer_Type);
  2722. SETBUILTIN("classmethod", &PyClassMethod_Type);
  2723. #ifndef WITHOUT_COMPLEX
  2724. SETBUILTIN("complex", &PyComplex_Type);
  2725. #endif
  2726. SETBUILTIN("dict", &PyDict_Type);
  2727. SETBUILTIN("enumerate", &PyEnum_Type);
  2728. SETBUILTIN("file", &PyFile_Type);
  2729. SETBUILTIN("float", &PyFloat_Type);
  2730. SETBUILTIN("frozenset", &PyFrozenSet_Type);
  2731. SETBUILTIN("property", &PyProperty_Type);
  2732. SETBUILTIN("int", &PyInt_Type);
  2733. SETBUILTIN("list", &PyList_Type);
  2734. SETBUILTIN("long", &PyLong_Type);
  2735. SETBUILTIN("object", &PyBaseObject_Type);
  2736. SETBUILTIN("reversed", &PyReversed_Type);
  2737. SETBUILTIN("set", &PySet_Type);
  2738. SETBUILTIN("slice", &PySlice_Type);
  2739. SETBUILTIN("staticmethod", &PyStaticMethod_Type);
  2740. SETBUILTIN("str", &PyString_Type);
  2741. SETBUILTIN("super", &PySuper_Type);
  2742. SETBUILTIN("tuple", &PyTuple_Type);
  2743. SETBUILTIN("type", &PyType_Type);
  2744. SETBUILTIN("xrange", &PyRange_Type);
  2745. #ifdef Py_USING_UNICODE
  2746. SETBUILTIN("unicode", &PyUnicode_Type);
  2747. #endif
  2748. debug = PyBool_FromLong(Py_OptimizeFlag == 0);
  2749. if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
  2750. Py_XDECREF(debug);
  2751. return NULL;
  2752. }
  2753. Py_XDECREF(debug);
  2754. return mod;
  2755. #undef ADD_TO_ALL
  2756. #undef SETBUILTIN
  2757. }
  2758. /* Helper for filter(): filter a tuple through a function */
  2759. static PyObject *
  2760. filtertuple(PyObject *func, PyObject *tuple)
  2761. {
  2762. PyObject *result;
  2763. Py_ssize_t i, j;
  2764. Py_ssize_t len = PyTuple_Size(tuple);
  2765. if (len == 0) {
  2766. if (PyTuple_CheckExact(tuple))
  2767. Py_INCREF(tuple);
  2768. else
  2769. tuple = PyTuple_New(0);
  2770. return tuple;
  2771. }
  2772. if ((result = PyTuple_New(len)) == NULL)
  2773. return NULL;
  2774. for (i = j = 0; i < len; ++i) {
  2775. PyObject *item, *good;
  2776. int ok;
  2777. if (tuple->ob_type->tp_as_sequence &&
  2778. tuple->ob_type->tp_as_sequence->sq_item) {
  2779. item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
  2780. if (item == NULL)
  2781. goto Fail_1;
  2782. } else {
  2783. PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
  2784. goto Fail_1;
  2785. }
  2786. if (func == Py_None) {
  2787. Py_INCREF(item);
  2788. good = item;
  2789. }
  2790. else {
  2791. PyObject *arg = PyTuple_Pack(1, item);
  2792. if (arg == NULL) {
  2793. Py_DECREF(item);
  2794. goto Fail_1;
  2795. }
  2796. good = PyEval_CallObject(func, arg);
  2797. Py_DECREF(arg);
  2798. if (good == NULL) {
  2799. Py_DECREF(item);
  2800. goto Fail_1;
  2801. }
  2802. }
  2803. ok = PyObject_IsTrue(good);
  2804. Py_DECREF(good);
  2805. if (ok) {
  2806. if (PyTuple_SetItem(result, j++, item) < 0)
  2807. goto Fail_1;
  2808. }
  2809. else
  2810. Py_DECREF(item);
  2811. }
  2812. if (_PyTuple_Resize(&result, j) < 0)
  2813. return NULL;
  2814. return result;
  2815. Fail_1:
  2816. Py_DECREF(result);
  2817. return NULL;
  2818. }
  2819. /* Helper for filter(): filter a string through a function */
  2820. static PyObject *
  2821. filterstring(PyObject *func, PyObject *strobj)
  2822. {
  2823. PyObject *result;
  2824. Py_ssize_t i, j;
  2825. Py_ssize_t len = PyString_Size(strobj);
  2826. Py_ssize_t outlen = len;
  2827. if (func == Py_None) {
  2828. /* If it's a real string we can return the original,
  2829. * as no character is ever false and __getitem__
  2830. * does return this character. If it's a subclass
  2831. * we must go through the __getitem__ loop */
  2832. if (PyString_CheckExact(strobj)) {
  2833. Py_INCREF(strobj);
  2834. return strobj;
  2835. }
  2836. }
  2837. if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
  2838. return NULL;
  2839. for (i = j = 0; i < len; ++i) {
  2840. PyObject *item;
  2841. int ok;
  2842. item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
  2843. if (item == NULL)
  2844. goto Fail_1;
  2845. if (func==Py_None) {
  2846. ok = 1;
  2847. } else {
  2848. PyObject *arg, *good;
  2849. arg = PyTuple_Pack(1, item);
  2850. if (arg == NULL) {
  2851. Py_DECREF(item);
  2852. goto Fail_1;
  2853. }
  2854. good = PyEval_CallObject(func, arg);
  2855. Py_DECREF(arg);
  2856. if (good == NULL) {
  2857. Py_DECREF(item);
  2858. goto Fail_1;
  2859. }
  2860. ok = PyObject_IsTrue(good);
  2861. Py_DECREF(good);
  2862. }
  2863. if (ok) {
  2864. Py_ssize_t reslen;
  2865. if (!PyString_Check(item)) {
  2866. PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
  2867. " __getitem__ returned different type");
  2868. Py_DECREF(item);
  2869. goto Fail_1;
  2870. }
  2871. reslen = PyString_GET_SIZE(item);
  2872. if (reslen == 1) {
  2873. PyString_AS_STRING(result)[j++] =
  2874. PyString_AS_STRING(item)[0];
  2875. } else {
  2876. /* do we need more space? */
  2877. Py_ssize_t need = j;
  2878. /* calculate space requirements while checking for overflow */
  2879. if (need > PY_SSIZE_T_MAX - reslen) {
  2880. Py_DECREF(item);
  2881. goto Fail_1;
  2882. }
  2883. need += reslen;
  2884. if (need > PY_SSIZE_T_MAX - len) {
  2885. Py_DECREF(item);
  2886. goto Fail_1;
  2887. }
  2888. need += len;
  2889. if (need <= i) {
  2890. Py_DECREF(item);
  2891. goto Fail_1;
  2892. }
  2893. need = need - i - 1;
  2894. assert(need >= 0);
  2895. assert(outlen >= 0);
  2896. if (need > outlen) {
  2897. /* overallocate, to avoid reallocations */
  2898. if (outlen > PY_SSIZE_T_MAX / 2) {
  2899. Py_DECREF(item);
  2900. return NULL;
  2901. }
  2902. if (need<2*outlen) {
  2903. need = 2*outlen;
  2904. }
  2905. if (_PyString_Resize(&result, need)) {
  2906. Py_DECREF(item);
  2907. return NULL;
  2908. }
  2909. outlen = need;
  2910. }
  2911. memcpy(
  2912. PyString_AS_STRING(result) + j,
  2913. PyString_AS_STRING(item),
  2914. reslen
  2915. );
  2916. j += reslen;
  2917. }
  2918. }
  2919. Py_DECREF(item);
  2920. }
  2921. if (j < outlen)
  2922. _PyString_Resize(&result, j);
  2923. return result;
  2924. Fail_1:
  2925. Py_DECREF(result);
  2926. return NULL;
  2927. }
  2928. #ifdef Py_USING_UNICODE
  2929. /* Helper for filter(): filter a Unicode object through a function */
  2930. static PyObject *
  2931. filterunicode(PyObject *func, PyObject *strobj)
  2932. {
  2933. PyObject *result;
  2934. register Py_ssize_t i, j;
  2935. Py_ssize_t len = PyUnicode_GetSize(strobj);
  2936. Py_ssize_t outlen = len;
  2937. if (func == Py_None) {
  2938. /* If it's a real string we can return the original,
  2939. * as no character is ever false and __getitem__
  2940. * does return this character. If it's a subclass
  2941. * we must go through the __getitem__ loop */
  2942. if (PyUnicode_CheckExact(strobj)) {
  2943. Py_INCREF(strobj);
  2944. return strobj;
  2945. }
  2946. }
  2947. if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
  2948. return NULL;
  2949. for (i = j = 0; i < len; ++i) {
  2950. PyObject *item, *arg, *good;
  2951. int ok;
  2952. item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
  2953. if (item == NULL)
  2954. goto Fail_1;
  2955. if (func == Py_None) {
  2956. ok = 1;
  2957. } else {
  2958. arg = PyTuple_Pack(1, item);
  2959. if (arg == NULL) {
  2960. Py_DECREF(item);
  2961. goto Fail_1;
  2962. }
  2963. good = PyEval_CallObject(func, arg);
  2964. Py_DECREF(arg);
  2965. if (good == NULL) {
  2966. Py_DECREF(item);
  2967. goto Fail_1;
  2968. }
  2969. ok = PyObject_IsTrue(good);
  2970. Py_DECREF(good);
  2971. }
  2972. if (ok) {
  2973. Py_ssize_t reslen;
  2974. if (!PyUnicode_Check(item)) {
  2975. PyErr_SetString(PyExc_TypeError,
  2976. "can't filter unicode to unicode:"
  2977. " __getitem__ returned different type");
  2978. Py_DECREF(item);
  2979. goto Fail_1;
  2980. }
  2981. reslen = PyUnicode_GET_SIZE(item);
  2982. if (reslen == 1)
  2983. PyUnicode_AS_UNICODE(result)[j++] =
  2984. PyUnicode_AS_UNICODE(item)[0];
  2985. else {
  2986. /* do we need more space? */
  2987. Py_ssize_t need = j + reslen + len - i - 1;
  2988. /* check that didnt overflow */
  2989. if ((j > PY_SSIZE_T_MAX - reslen) ||
  2990. ((j + reslen) > PY_SSIZE_T_MAX - len) ||
  2991. ((j + reslen + len) < i) ||
  2992. ((j + reslen + len - i) <= 0)) {
  2993. Py_DECREF(item);
  2994. return NULL;
  2995. }
  2996. assert(need >= 0);
  2997. assert(outlen >= 0);
  2998. if (need > outlen) {
  2999. /* overallocate,
  3000. to avoid reallocations */
  3001. if (need < 2 * outlen) {
  3002. if (outlen > PY_SSIZE_T_MAX / 2) {
  3003. Py_DECREF(item);
  3004. return NULL;
  3005. } else {
  3006. need = 2 * outlen;
  3007. }
  3008. }
  3009. if (PyUnicode_Resize(
  3010. &result, need) < 0) {
  3011. Py_DECREF(item);
  3012. goto Fail_1;
  3013. }
  3014. outlen = need;
  3015. }
  3016. memcpy(PyUnicode_AS_UNICODE(result) + j,
  3017. PyUnicode_AS_UNICODE(item),
  3018. reslen*sizeof(Py_UNICODE));
  3019. j += reslen;
  3020. }
  3021. }
  3022. Py_DECREF(item);
  3023. }
  3024. if (j < outlen)
  3025. PyUnicode_Resize(&result, j);
  3026. return result;
  3027. Fail_1:
  3028. Py_DECREF(result);
  3029. return NULL;
  3030. }
  3031. #endif