/Python/bltinmodule.c

http://unladen-swallow.googlecode.com/ · C · 3422 lines · 2905 code · 391 blank · 126 comment · 790 complexity · b632a8d2725a3ea6685f72dcf2483fb7 MD5 · raw file

Large files are truncated click here to view the full file

  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,