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

1284 lines
40 KiB

  1. /*
  2. unicode_format.h -- implementation of str.format().
  3. */
  4. /************************************************************************/
  5. /*********** Global data structures and forward declarations *********/
  6. /************************************************************************/
  7. /*
  8. A SubString consists of the characters between two string or
  9. unicode pointers.
  10. */
  11. typedef struct {
  12. PyObject *str; /* borrowed reference */
  13. Py_ssize_t start, end;
  14. } SubString;
  15. typedef enum {
  16. ANS_INIT,
  17. ANS_AUTO,
  18. ANS_MANUAL
  19. } AutoNumberState; /* Keep track if we're auto-numbering fields */
  20. /* Keeps track of our auto-numbering state, and which number field we're on */
  21. typedef struct {
  22. AutoNumberState an_state;
  23. int an_field_number;
  24. } AutoNumber;
  25. /* forward declaration for recursion */
  26. static PyObject *
  27. build_string(SubString *input, PyObject *args, PyObject *kwargs,
  28. int recursion_depth, AutoNumber *auto_number);
  29. /************************************************************************/
  30. /************************** Utility functions ************************/
  31. /************************************************************************/
  32. static void
  33. AutoNumber_Init(AutoNumber *auto_number)
  34. {
  35. auto_number->an_state = ANS_INIT;
  36. auto_number->an_field_number = 0;
  37. }
  38. /* fill in a SubString from a pointer and length */
  39. Py_LOCAL_INLINE(void)
  40. SubString_init(SubString *str, PyObject *s, Py_ssize_t start, Py_ssize_t end)
  41. {
  42. str->str = s;
  43. str->start = start;
  44. str->end = end;
  45. }
  46. /* return a new string. if str->str is NULL, return None */
  47. Py_LOCAL_INLINE(PyObject *)
  48. SubString_new_object(SubString *str)
  49. {
  50. if (str->str == NULL) {
  51. Py_INCREF(Py_None);
  52. return Py_None;
  53. }
  54. return PyUnicode_Substring(str->str, str->start, str->end);
  55. }
  56. /* return a new string. if str->str is NULL, return a new empty string */
  57. Py_LOCAL_INLINE(PyObject *)
  58. SubString_new_object_or_empty(SubString *str)
  59. {
  60. if (str->str == NULL) {
  61. return PyUnicode_New(0, 0);
  62. }
  63. return SubString_new_object(str);
  64. }
  65. /* Return 1 if an error has been detected switching between automatic
  66. field numbering and manual field specification, else return 0. Set
  67. ValueError on error. */
  68. static int
  69. autonumber_state_error(AutoNumberState state, int field_name_is_empty)
  70. {
  71. if (state == ANS_MANUAL) {
  72. if (field_name_is_empty) {
  73. PyErr_SetString(PyExc_ValueError, "cannot switch from "
  74. "manual field specification to "
  75. "automatic field numbering");
  76. return 1;
  77. }
  78. }
  79. else {
  80. if (!field_name_is_empty) {
  81. PyErr_SetString(PyExc_ValueError, "cannot switch from "
  82. "automatic field numbering to "
  83. "manual field specification");
  84. return 1;
  85. }
  86. }
  87. return 0;
  88. }
  89. /************************************************************************/
  90. /*********** Format string parsing -- integers and identifiers *********/
  91. /************************************************************************/
  92. static Py_ssize_t
  93. get_integer(const SubString *str)
  94. {
  95. Py_ssize_t accumulator = 0;
  96. Py_ssize_t digitval;
  97. Py_ssize_t i;
  98. /* empty string is an error */
  99. if (str->start >= str->end)
  100. return -1;
  101. for (i = str->start; i < str->end; i++) {
  102. digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ_CHAR(str->str, i));
  103. if (digitval < 0)
  104. return -1;
  105. /*
  106. Detect possible overflow before it happens:
  107. accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if
  108. accumulator > (PY_SSIZE_T_MAX - digitval) / 10.
  109. */
  110. if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) {
  111. PyErr_Format(PyExc_ValueError,
  112. "Too many decimal digits in format string");
  113. return -1;
  114. }
  115. accumulator = accumulator * 10 + digitval;
  116. }
  117. return accumulator;
  118. }
  119. /************************************************************************/
  120. /******** Functions to get field objects and specification strings ******/
  121. /************************************************************************/
  122. /* do the equivalent of obj.name */
  123. static PyObject *
  124. getattr(PyObject *obj, SubString *name)
  125. {
  126. PyObject *newobj;
  127. PyObject *str = SubString_new_object(name);
  128. if (str == NULL)
  129. return NULL;
  130. newobj = PyObject_GetAttr(obj, str);
  131. Py_DECREF(str);
  132. return newobj;
  133. }
  134. /* do the equivalent of obj[idx], where obj is a sequence */
  135. static PyObject *
  136. getitem_sequence(PyObject *obj, Py_ssize_t idx)
  137. {
  138. return PySequence_GetItem(obj, idx);
  139. }
  140. /* do the equivalent of obj[idx], where obj is not a sequence */
  141. static PyObject *
  142. getitem_idx(PyObject *obj, Py_ssize_t idx)
  143. {
  144. PyObject *newobj;
  145. PyObject *idx_obj = PyLong_FromSsize_t(idx);
  146. if (idx_obj == NULL)
  147. return NULL;
  148. newobj = PyObject_GetItem(obj, idx_obj);
  149. Py_DECREF(idx_obj);
  150. return newobj;
  151. }
  152. /* do the equivalent of obj[name] */
  153. static PyObject *
  154. getitem_str(PyObject *obj, SubString *name)
  155. {
  156. PyObject *newobj;
  157. PyObject *str = SubString_new_object(name);
  158. if (str == NULL)
  159. return NULL;
  160. newobj = PyObject_GetItem(obj, str);
  161. Py_DECREF(str);
  162. return newobj;
  163. }
  164. typedef struct {
  165. /* the entire string we're parsing. we assume that someone else
  166. is managing its lifetime, and that it will exist for the
  167. lifetime of the iterator. can be empty */
  168. SubString str;
  169. /* index to where we are inside field_name */
  170. Py_ssize_t index;
  171. } FieldNameIterator;
  172. static int
  173. FieldNameIterator_init(FieldNameIterator *self, PyObject *s,
  174. Py_ssize_t start, Py_ssize_t end)
  175. {
  176. SubString_init(&self->str, s, start, end);
  177. self->index = start;
  178. return 1;
  179. }
  180. static int
  181. _FieldNameIterator_attr(FieldNameIterator *self, SubString *name)
  182. {
  183. Py_UCS4 c;
  184. name->str = self->str.str;
  185. name->start = self->index;
  186. /* return everything until '.' or '[' */
  187. while (self->index < self->str.end) {
  188. c = PyUnicode_READ_CHAR(self->str.str, self->index++);
  189. switch (c) {
  190. case '[':
  191. case '.':
  192. /* backup so that we this character will be seen next time */
  193. self->index--;
  194. break;
  195. default:
  196. continue;
  197. }
  198. break;
  199. }
  200. /* end of string is okay */
  201. name->end = self->index;
  202. return 1;
  203. }
  204. static int
  205. _FieldNameIterator_item(FieldNameIterator *self, SubString *name)
  206. {
  207. int bracket_seen = 0;
  208. Py_UCS4 c;
  209. name->str = self->str.str;
  210. name->start = self->index;
  211. /* return everything until ']' */
  212. while (self->index < self->str.end) {
  213. c = PyUnicode_READ_CHAR(self->str.str, self->index++);
  214. switch (c) {
  215. case ']':
  216. bracket_seen = 1;
  217. break;
  218. default:
  219. continue;
  220. }
  221. break;
  222. }
  223. /* make sure we ended with a ']' */
  224. if (!bracket_seen) {
  225. PyErr_SetString(PyExc_ValueError, "Missing ']' in format string");
  226. return 0;
  227. }
  228. /* end of string is okay */
  229. /* don't include the ']' */
  230. name->end = self->index-1;
  231. return 1;
  232. }
  233. /* returns 0 on error, 1 on non-error termination, and 2 if it returns a value */
  234. static int
  235. FieldNameIterator_next(FieldNameIterator *self, int *is_attribute,
  236. Py_ssize_t *name_idx, SubString *name)
  237. {
  238. /* check at end of input */
  239. if (self->index >= self->str.end)
  240. return 1;
  241. switch (PyUnicode_READ_CHAR(self->str.str, self->index++)) {
  242. case '.':
  243. *is_attribute = 1;
  244. if (_FieldNameIterator_attr(self, name) == 0)
  245. return 0;
  246. *name_idx = -1;
  247. break;
  248. case '[':
  249. *is_attribute = 0;
  250. if (_FieldNameIterator_item(self, name) == 0)
  251. return 0;
  252. *name_idx = get_integer(name);
  253. if (*name_idx == -1 && PyErr_Occurred())
  254. return 0;
  255. break;
  256. default:
  257. /* Invalid character follows ']' */
  258. PyErr_SetString(PyExc_ValueError, "Only '.' or '[' may "
  259. "follow ']' in format field specifier");
  260. return 0;
  261. }
  262. /* empty string is an error */
  263. if (name->start == name->end) {
  264. PyErr_SetString(PyExc_ValueError, "Empty attribute in format string");
  265. return 0;
  266. }
  267. return 2;
  268. }
  269. /* input: field_name
  270. output: 'first' points to the part before the first '[' or '.'
  271. 'first_idx' is -1 if 'first' is not an integer, otherwise
  272. it's the value of first converted to an integer
  273. 'rest' is an iterator to return the rest
  274. */
  275. static int
  276. field_name_split(PyObject *str, Py_ssize_t start, Py_ssize_t end, SubString *first,
  277. Py_ssize_t *first_idx, FieldNameIterator *rest,
  278. AutoNumber *auto_number)
  279. {
  280. Py_UCS4 c;
  281. Py_ssize_t i = start;
  282. int field_name_is_empty;
  283. int using_numeric_index;
  284. /* find the part up until the first '.' or '[' */
  285. while (i < end) {
  286. switch (c = PyUnicode_READ_CHAR(str, i++)) {
  287. case '[':
  288. case '.':
  289. /* backup so that we this character is available to the
  290. "rest" iterator */
  291. i--;
  292. break;
  293. default:
  294. continue;
  295. }
  296. break;
  297. }
  298. /* set up the return values */
  299. SubString_init(first, str, start, i);
  300. FieldNameIterator_init(rest, str, i, end);
  301. /* see if "first" is an integer, in which case it's used as an index */
  302. *first_idx = get_integer(first);
  303. if (*first_idx == -1 && PyErr_Occurred())
  304. return 0;
  305. field_name_is_empty = first->start >= first->end;
  306. /* If the field name is omitted or if we have a numeric index
  307. specified, then we're doing numeric indexing into args. */
  308. using_numeric_index = field_name_is_empty || *first_idx != -1;
  309. /* We always get here exactly one time for each field we're
  310. processing. And we get here in field order (counting by left
  311. braces). So this is the perfect place to handle automatic field
  312. numbering if the field name is omitted. */
  313. /* Check if we need to do the auto-numbering. It's not needed if
  314. we're called from string.Format routines, because it's handled
  315. in that class by itself. */
  316. if (auto_number) {
  317. /* Initialize our auto numbering state if this is the first
  318. time we're either auto-numbering or manually numbering. */
  319. if (auto_number->an_state == ANS_INIT && using_numeric_index)
  320. auto_number->an_state = field_name_is_empty ?
  321. ANS_AUTO : ANS_MANUAL;
  322. /* Make sure our state is consistent with what we're doing
  323. this time through. Only check if we're using a numeric
  324. index. */
  325. if (using_numeric_index)
  326. if (autonumber_state_error(auto_number->an_state,
  327. field_name_is_empty))
  328. return 0;
  329. /* Zero length field means we want to do auto-numbering of the
  330. fields. */
  331. if (field_name_is_empty)
  332. *first_idx = (auto_number->an_field_number)++;
  333. }
  334. return 1;
  335. }
  336. /*
  337. get_field_object returns the object inside {}, before the
  338. format_spec. It handles getindex and getattr lookups and consumes
  339. the entire input string.
  340. */
  341. static PyObject *
  342. get_field_object(SubString *input, PyObject *args, PyObject *kwargs,
  343. AutoNumber *auto_number)
  344. {
  345. PyObject *obj = NULL;
  346. int ok;
  347. int is_attribute;
  348. SubString name;
  349. SubString first;
  350. Py_ssize_t index;
  351. FieldNameIterator rest;
  352. if (!field_name_split(input->str, input->start, input->end, &first,
  353. &index, &rest, auto_number)) {
  354. goto error;
  355. }
  356. if (index == -1) {
  357. /* look up in kwargs */
  358. PyObject *key = SubString_new_object(&first);
  359. if (key == NULL)
  360. goto error;
  361. /* Use PyObject_GetItem instead of PyDict_GetItem because this
  362. code is no longer just used with kwargs. It might be passed
  363. a non-dict when called through format_map. */
  364. if ((kwargs == NULL) || (obj = PyObject_GetItem(kwargs, key)) == NULL) {
  365. PyErr_SetObject(PyExc_KeyError, key);
  366. Py_DECREF(key);
  367. goto error;
  368. }
  369. Py_DECREF(key);
  370. }
  371. else {
  372. /* If args is NULL, we have a format string with a positional field
  373. with only kwargs to retrieve it from. This can only happen when
  374. used with format_map(), where positional arguments are not
  375. allowed. */
  376. if (args == NULL) {
  377. PyErr_SetString(PyExc_ValueError, "Format string contains "
  378. "positional fields");
  379. goto error;
  380. }
  381. /* look up in args */
  382. obj = PySequence_GetItem(args, index);
  383. if (obj == NULL)
  384. goto error;
  385. }
  386. /* iterate over the rest of the field_name */
  387. while ((ok = FieldNameIterator_next(&rest, &is_attribute, &index,
  388. &name)) == 2) {
  389. PyObject *tmp;
  390. if (is_attribute)
  391. /* getattr lookup "." */
  392. tmp = getattr(obj, &name);
  393. else
  394. /* getitem lookup "[]" */
  395. if (index == -1)
  396. tmp = getitem_str(obj, &name);
  397. else
  398. if (PySequence_Check(obj))
  399. tmp = getitem_sequence(obj, index);
  400. else
  401. /* not a sequence */
  402. tmp = getitem_idx(obj, index);
  403. if (tmp == NULL)
  404. goto error;
  405. /* assign to obj */
  406. Py_DECREF(obj);
  407. obj = tmp;
  408. }
  409. /* end of iterator, this is the non-error case */
  410. if (ok == 1)
  411. return obj;
  412. error:
  413. Py_XDECREF(obj);
  414. return NULL;
  415. }
  416. /************************************************************************/
  417. /***************** Field rendering functions **************************/
  418. /************************************************************************/
  419. /*
  420. render_field() is the main function in this section. It takes the
  421. field object and field specification string generated by
  422. get_field_and_spec, and renders the field into the output string.
  423. render_field calls fieldobj.__format__(format_spec) method, and
  424. appends to the output.
  425. */
  426. static int
  427. render_field(PyObject *fieldobj, SubString *format_spec, _PyUnicodeWriter *writer)
  428. {
  429. int ok = 0;
  430. PyObject *result = NULL;
  431. PyObject *format_spec_object = NULL;
  432. int (*formatter) (_PyUnicodeWriter*, PyObject *, PyObject *, Py_ssize_t, Py_ssize_t) = NULL;
  433. int err;
  434. /* If we know the type exactly, skip the lookup of __format__ and just
  435. call the formatter directly. */
  436. if (PyUnicode_CheckExact(fieldobj))
  437. formatter = _PyUnicode_FormatAdvancedWriter;
  438. else if (PyLong_CheckExact(fieldobj))
  439. formatter = _PyLong_FormatAdvancedWriter;
  440. else if (PyFloat_CheckExact(fieldobj))
  441. formatter = _PyFloat_FormatAdvancedWriter;
  442. else if (PyComplex_CheckExact(fieldobj))
  443. formatter = _PyComplex_FormatAdvancedWriter;
  444. if (formatter) {
  445. /* we know exactly which formatter will be called when __format__ is
  446. looked up, so call it directly, instead. */
  447. err = formatter(writer, fieldobj, format_spec->str,
  448. format_spec->start, format_spec->end);
  449. return (err == 0);
  450. }
  451. else {
  452. /* We need to create an object out of the pointers we have, because
  453. __format__ takes a string/unicode object for format_spec. */
  454. if (format_spec->str)
  455. format_spec_object = PyUnicode_Substring(format_spec->str,
  456. format_spec->start,
  457. format_spec->end);
  458. else
  459. format_spec_object = PyUnicode_New(0, 0);
  460. if (format_spec_object == NULL)
  461. goto done;
  462. result = PyObject_Format(fieldobj, format_spec_object);
  463. }
  464. if (result == NULL)
  465. goto done;
  466. if (_PyUnicodeWriter_WriteStr(writer, result) == -1)
  467. goto done;
  468. ok = 1;
  469. done:
  470. Py_XDECREF(format_spec_object);
  471. Py_XDECREF(result);
  472. return ok;
  473. }
  474. static int
  475. parse_field(SubString *str, SubString *field_name, SubString *format_spec,
  476. int *format_spec_needs_expanding, Py_UCS4 *conversion)
  477. {
  478. /* Note this function works if the field name is zero length,
  479. which is good. Zero length field names are handled later, in
  480. field_name_split. */
  481. Py_UCS4 c = 0;
  482. /* initialize these, as they may be empty */
  483. *conversion = '\0';
  484. SubString_init(format_spec, NULL, 0, 0);
  485. /* Search for the field name. it's terminated by the end of
  486. the string, or a ':' or '!' */
  487. field_name->str = str->str;
  488. field_name->start = str->start;
  489. while (str->start < str->end) {
  490. switch ((c = PyUnicode_READ_CHAR(str->str, str->start++))) {
  491. case '{':
  492. PyErr_SetString(PyExc_ValueError, "unexpected '{' in field name");
  493. return 0;
  494. case '[':
  495. for (; str->start < str->end; str->start++)
  496. if (PyUnicode_READ_CHAR(str->str, str->start) == ']')
  497. break;
  498. continue;
  499. case '}':
  500. case ':':
  501. case '!':
  502. break;
  503. default:
  504. continue;
  505. }
  506. break;
  507. }
  508. field_name->end = str->start - 1;
  509. if (c == '!' || c == ':') {
  510. Py_ssize_t count;
  511. /* we have a format specifier and/or a conversion */
  512. /* don't include the last character */
  513. /* see if there's a conversion specifier */
  514. if (c == '!') {
  515. /* there must be another character present */
  516. if (str->start >= str->end) {
  517. PyErr_SetString(PyExc_ValueError,
  518. "end of string while looking for conversion "
  519. "specifier");
  520. return 0;
  521. }
  522. *conversion = PyUnicode_READ_CHAR(str->str, str->start++);
  523. if (str->start < str->end) {
  524. c = PyUnicode_READ_CHAR(str->str, str->start++);
  525. if (c == '}')
  526. return 1;
  527. if (c != ':') {
  528. PyErr_SetString(PyExc_ValueError,
  529. "expected ':' after conversion specifier");
  530. return 0;
  531. }
  532. }
  533. }
  534. format_spec->str = str->str;
  535. format_spec->start = str->start;
  536. count = 1;
  537. while (str->start < str->end) {
  538. switch ((c = PyUnicode_READ_CHAR(str->str, str->start++))) {
  539. case '{':
  540. *format_spec_needs_expanding = 1;
  541. count++;
  542. break;
  543. case '}':
  544. count--;
  545. if (count == 0) {
  546. format_spec->end = str->start - 1;
  547. return 1;
  548. }
  549. break;
  550. default:
  551. break;
  552. }
  553. }
  554. PyErr_SetString(PyExc_ValueError, "unmatched '{' in format spec");
  555. return 0;
  556. }
  557. else if (c != '}') {
  558. PyErr_SetString(PyExc_ValueError, "expected '}' before end of string");
  559. return 0;
  560. }
  561. return 1;
  562. }
  563. /************************************************************************/
  564. /******* Output string allocation and escape-to-markup processing ******/
  565. /************************************************************************/
  566. /* MarkupIterator breaks the string into pieces of either literal
  567. text, or things inside {} that need to be marked up. it is
  568. designed to make it easy to wrap a Python iterator around it, for
  569. use with the Formatter class */
  570. typedef struct {
  571. SubString str;
  572. } MarkupIterator;
  573. static int
  574. MarkupIterator_init(MarkupIterator *self, PyObject *str,
  575. Py_ssize_t start, Py_ssize_t end)
  576. {
  577. SubString_init(&self->str, str, start, end);
  578. return 1;
  579. }
  580. /* returns 0 on error, 1 on non-error termination, and 2 if it got a
  581. string (or something to be expanded) */
  582. static int
  583. MarkupIterator_next(MarkupIterator *self, SubString *literal,
  584. int *field_present, SubString *field_name,
  585. SubString *format_spec, Py_UCS4 *conversion,
  586. int *format_spec_needs_expanding)
  587. {
  588. int at_end;
  589. Py_UCS4 c = 0;
  590. Py_ssize_t start;
  591. Py_ssize_t len;
  592. int markup_follows = 0;
  593. /* initialize all of the output variables */
  594. SubString_init(literal, NULL, 0, 0);
  595. SubString_init(field_name, NULL, 0, 0);
  596. SubString_init(format_spec, NULL, 0, 0);
  597. *conversion = '\0';
  598. *format_spec_needs_expanding = 0;
  599. *field_present = 0;
  600. /* No more input, end of iterator. This is the normal exit
  601. path. */
  602. if (self->str.start >= self->str.end)
  603. return 1;
  604. start = self->str.start;
  605. /* First read any literal text. Read until the end of string, an
  606. escaped '{' or '}', or an unescaped '{'. In order to never
  607. allocate memory and so I can just pass pointers around, if
  608. there's an escaped '{' or '}' then we'll return the literal
  609. including the brace, but no format object. The next time
  610. through, we'll return the rest of the literal, skipping past
  611. the second consecutive brace. */
  612. while (self->str.start < self->str.end) {
  613. switch (c = PyUnicode_READ_CHAR(self->str.str, self->str.start++)) {
  614. case '{':
  615. case '}':
  616. markup_follows = 1;
  617. break;
  618. default:
  619. continue;
  620. }
  621. break;
  622. }
  623. at_end = self->str.start >= self->str.end;
  624. len = self->str.start - start;
  625. if ((c == '}') && (at_end ||
  626. (c != PyUnicode_READ_CHAR(self->str.str,
  627. self->str.start)))) {
  628. PyErr_SetString(PyExc_ValueError, "Single '}' encountered "
  629. "in format string");
  630. return 0;
  631. }
  632. if (at_end && c == '{') {
  633. PyErr_SetString(PyExc_ValueError, "Single '{' encountered "
  634. "in format string");
  635. return 0;
  636. }
  637. if (!at_end) {
  638. if (c == PyUnicode_READ_CHAR(self->str.str, self->str.start)) {
  639. /* escaped } or {, skip it in the input. there is no
  640. markup object following us, just this literal text */
  641. self->str.start++;
  642. markup_follows = 0;
  643. }
  644. else
  645. len--;
  646. }
  647. /* record the literal text */
  648. literal->str = self->str.str;
  649. literal->start = start;
  650. literal->end = start + len;
  651. if (!markup_follows)
  652. return 2;
  653. /* this is markup; parse the field */
  654. *field_present = 1;
  655. if (!parse_field(&self->str, field_name, format_spec,
  656. format_spec_needs_expanding, conversion))
  657. return 0;
  658. return 2;
  659. }
  660. /* do the !r or !s conversion on obj */
  661. static PyObject *
  662. do_conversion(PyObject *obj, Py_UCS4 conversion)
  663. {
  664. /* XXX in pre-3.0, do we need to convert this to unicode, since it
  665. might have returned a string? */
  666. switch (conversion) {
  667. case 'r':
  668. return PyObject_Repr(obj);
  669. case 's':
  670. return PyObject_Str(obj);
  671. case 'a':
  672. return PyObject_ASCII(obj);
  673. default:
  674. if (conversion > 32 && conversion < 127) {
  675. /* It's the ASCII subrange; casting to char is safe
  676. (assuming the execution character set is an ASCII
  677. superset). */
  678. PyErr_Format(PyExc_ValueError,
  679. "Unknown conversion specifier %c",
  680. (char)conversion);
  681. } else
  682. PyErr_Format(PyExc_ValueError,
  683. "Unknown conversion specifier \\x%x",
  684. (unsigned int)conversion);
  685. return NULL;
  686. }
  687. }
  688. /* given:
  689. {field_name!conversion:format_spec}
  690. compute the result and write it to output.
  691. format_spec_needs_expanding is an optimization. if it's false,
  692. just output the string directly, otherwise recursively expand the
  693. format_spec string.
  694. field_name is allowed to be zero length, in which case we
  695. are doing auto field numbering.
  696. */
  697. static int
  698. output_markup(SubString *field_name, SubString *format_spec,
  699. int format_spec_needs_expanding, Py_UCS4 conversion,
  700. _PyUnicodeWriter *writer, PyObject *args, PyObject *kwargs,
  701. int recursion_depth, AutoNumber *auto_number)
  702. {
  703. PyObject *tmp = NULL;
  704. PyObject *fieldobj = NULL;
  705. SubString expanded_format_spec;
  706. SubString *actual_format_spec;
  707. int result = 0;
  708. /* convert field_name to an object */
  709. fieldobj = get_field_object(field_name, args, kwargs, auto_number);
  710. if (fieldobj == NULL)
  711. goto done;
  712. if (conversion != '\0') {
  713. tmp = do_conversion(fieldobj, conversion);
  714. if (tmp == NULL || PyUnicode_READY(tmp) == -1)
  715. goto done;
  716. /* do the assignment, transferring ownership: fieldobj = tmp */
  717. Py_DECREF(fieldobj);
  718. fieldobj = tmp;
  719. tmp = NULL;
  720. }
  721. /* if needed, recurively compute the format_spec */
  722. if (format_spec_needs_expanding) {
  723. tmp = build_string(format_spec, args, kwargs, recursion_depth-1,
  724. auto_number);
  725. if (tmp == NULL || PyUnicode_READY(tmp) == -1)
  726. goto done;
  727. /* note that in the case we're expanding the format string,
  728. tmp must be kept around until after the call to
  729. render_field. */
  730. SubString_init(&expanded_format_spec, tmp, 0, PyUnicode_GET_LENGTH(tmp));
  731. actual_format_spec = &expanded_format_spec;
  732. }
  733. else
  734. actual_format_spec = format_spec;
  735. if (render_field(fieldobj, actual_format_spec, writer) == 0)
  736. goto done;
  737. result = 1;
  738. done:
  739. Py_XDECREF(fieldobj);
  740. Py_XDECREF(tmp);
  741. return result;
  742. }
  743. /*
  744. do_markup is the top-level loop for the format() method. It
  745. searches through the format string for escapes to markup codes, and
  746. calls other functions to move non-markup text to the output,
  747. and to perform the markup to the output.
  748. */
  749. static int
  750. do_markup(SubString *input, PyObject *args, PyObject *kwargs,
  751. _PyUnicodeWriter *writer, int recursion_depth, AutoNumber *auto_number)
  752. {
  753. MarkupIterator iter;
  754. int format_spec_needs_expanding;
  755. int result;
  756. int field_present;
  757. SubString literal;
  758. SubString field_name;
  759. SubString format_spec;
  760. Py_UCS4 conversion;
  761. MarkupIterator_init(&iter, input->str, input->start, input->end);
  762. while ((result = MarkupIterator_next(&iter, &literal, &field_present,
  763. &field_name, &format_spec,
  764. &conversion,
  765. &format_spec_needs_expanding)) == 2) {
  766. if (literal.end != literal.start) {
  767. if (!field_present && iter.str.start == iter.str.end)
  768. writer->overallocate = 0;
  769. if (_PyUnicodeWriter_WriteSubstring(writer, literal.str,
  770. literal.start, literal.end) < 0)
  771. return 0;
  772. }
  773. if (field_present) {
  774. if (iter.str.start == iter.str.end)
  775. writer->overallocate = 0;
  776. if (!output_markup(&field_name, &format_spec,
  777. format_spec_needs_expanding, conversion, writer,
  778. args, kwargs, recursion_depth, auto_number))
  779. return 0;
  780. }
  781. }
  782. return result;
  783. }
  784. /*
  785. build_string allocates the output string and then
  786. calls do_markup to do the heavy lifting.
  787. */
  788. static PyObject *
  789. build_string(SubString *input, PyObject *args, PyObject *kwargs,
  790. int recursion_depth, AutoNumber *auto_number)
  791. {
  792. _PyUnicodeWriter writer;
  793. /* check the recursion level */
  794. if (recursion_depth <= 0) {
  795. PyErr_SetString(PyExc_ValueError,
  796. "Max string recursion exceeded");
  797. return NULL;
  798. }
  799. _PyUnicodeWriter_Init(&writer);
  800. writer.overallocate = 1;
  801. writer.min_length = PyUnicode_GET_LENGTH(input->str) + 100;
  802. if (!do_markup(input, args, kwargs, &writer, recursion_depth,
  803. auto_number)) {
  804. _PyUnicodeWriter_Dealloc(&writer);
  805. return NULL;
  806. }
  807. return _PyUnicodeWriter_Finish(&writer);
  808. }
  809. /************************************************************************/
  810. /*********** main routine ***********************************************/
  811. /************************************************************************/
  812. /* this is the main entry point */
  813. static PyObject *
  814. do_string_format(PyObject *self, PyObject *args, PyObject *kwargs)
  815. {
  816. SubString input;
  817. /* PEP 3101 says only 2 levels, so that
  818. "{0:{1}}".format('abc', 's') # works
  819. "{0:{1:{2}}}".format('abc', 's', '') # fails
  820. */
  821. int recursion_depth = 2;
  822. AutoNumber auto_number;
  823. if (PyUnicode_READY(self) == -1)
  824. return NULL;
  825. AutoNumber_Init(&auto_number);
  826. SubString_init(&input, self, 0, PyUnicode_GET_LENGTH(self));
  827. return build_string(&input, args, kwargs, recursion_depth, &auto_number);
  828. }
  829. static PyObject *
  830. do_string_format_map(PyObject *self, PyObject *obj)
  831. {
  832. return do_string_format(self, NULL, obj);
  833. }
  834. /************************************************************************/
  835. /*********** formatteriterator ******************************************/
  836. /************************************************************************/
  837. /* This is used to implement string.Formatter.vparse(). It exists so
  838. Formatter can share code with the built in unicode.format() method.
  839. It's really just a wrapper around MarkupIterator that is callable
  840. from Python. */
  841. typedef struct {
  842. PyObject_HEAD
  843. PyObject *str;
  844. MarkupIterator it_markup;
  845. } formatteriterobject;
  846. static void
  847. formatteriter_dealloc(formatteriterobject *it)
  848. {
  849. Py_XDECREF(it->str);
  850. PyObject_FREE(it);
  851. }
  852. /* returns a tuple:
  853. (literal, field_name, format_spec, conversion)
  854. literal is any literal text to output. might be zero length
  855. field_name is the string before the ':'. might be None
  856. format_spec is the string after the ':'. mibht be None
  857. conversion is either None, or the string after the '!'
  858. */
  859. static PyObject *
  860. formatteriter_next(formatteriterobject *it)
  861. {
  862. SubString literal;
  863. SubString field_name;
  864. SubString format_spec;
  865. Py_UCS4 conversion;
  866. int format_spec_needs_expanding;
  867. int field_present;
  868. int result = MarkupIterator_next(&it->it_markup, &literal, &field_present,
  869. &field_name, &format_spec, &conversion,
  870. &format_spec_needs_expanding);
  871. /* all of the SubString objects point into it->str, so no
  872. memory management needs to be done on them */
  873. assert(0 <= result && result <= 2);
  874. if (result == 0 || result == 1)
  875. /* if 0, error has already been set, if 1, iterator is empty */
  876. return NULL;
  877. else {
  878. PyObject *literal_str = NULL;
  879. PyObject *field_name_str = NULL;
  880. PyObject *format_spec_str = NULL;
  881. PyObject *conversion_str = NULL;
  882. PyObject *tuple = NULL;
  883. literal_str = SubString_new_object(&literal);
  884. if (literal_str == NULL)
  885. goto done;
  886. field_name_str = SubString_new_object(&field_name);
  887. if (field_name_str == NULL)
  888. goto done;
  889. /* if field_name is non-zero length, return a string for
  890. format_spec (even if zero length), else return None */
  891. format_spec_str = (field_present ?
  892. SubString_new_object_or_empty :
  893. SubString_new_object)(&format_spec);
  894. if (format_spec_str == NULL)
  895. goto done;
  896. /* if the conversion is not specified, return a None,
  897. otherwise create a one length string with the conversion
  898. character */
  899. if (conversion == '\0') {
  900. conversion_str = Py_None;
  901. Py_INCREF(conversion_str);
  902. }
  903. else
  904. conversion_str = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
  905. &conversion, 1);
  906. if (conversion_str == NULL)
  907. goto done;
  908. tuple = PyTuple_Pack(4, literal_str, field_name_str, format_spec_str,
  909. conversion_str);
  910. done:
  911. Py_XDECREF(literal_str);
  912. Py_XDECREF(field_name_str);
  913. Py_XDECREF(format_spec_str);
  914. Py_XDECREF(conversion_str);
  915. return tuple;
  916. }
  917. }
  918. static PyMethodDef formatteriter_methods[] = {
  919. {NULL, NULL} /* sentinel */
  920. };
  921. static PyTypeObject PyFormatterIter_Type = {
  922. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  923. "formatteriterator", /* tp_name */
  924. sizeof(formatteriterobject), /* tp_basicsize */
  925. 0, /* tp_itemsize */
  926. /* methods */
  927. (destructor)formatteriter_dealloc, /* tp_dealloc */
  928. 0, /* tp_print */
  929. 0, /* tp_getattr */
  930. 0, /* tp_setattr */
  931. 0, /* tp_reserved */
  932. 0, /* tp_repr */
  933. 0, /* tp_as_number */
  934. 0, /* tp_as_sequence */
  935. 0, /* tp_as_mapping */
  936. 0, /* tp_hash */
  937. 0, /* tp_call */
  938. 0, /* tp_str */
  939. PyObject_GenericGetAttr, /* tp_getattro */
  940. 0, /* tp_setattro */
  941. 0, /* tp_as_buffer */
  942. Py_TPFLAGS_DEFAULT, /* tp_flags */
  943. 0, /* tp_doc */
  944. 0, /* tp_traverse */
  945. 0, /* tp_clear */
  946. 0, /* tp_richcompare */
  947. 0, /* tp_weaklistoffset */
  948. PyObject_SelfIter, /* tp_iter */
  949. (iternextfunc)formatteriter_next, /* tp_iternext */
  950. formatteriter_methods, /* tp_methods */
  951. 0,
  952. };
  953. /* unicode_formatter_parser is used to implement
  954. string.Formatter.vformat. it parses a string and returns tuples
  955. describing the parsed elements. It's a wrapper around
  956. stringlib/string_format.h's MarkupIterator */
  957. static PyObject *
  958. formatter_parser(PyObject *ignored, PyObject *self)
  959. {
  960. formatteriterobject *it;
  961. if (!PyUnicode_Check(self)) {
  962. PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name);
  963. return NULL;
  964. }
  965. if (PyUnicode_READY(self) == -1)
  966. return NULL;
  967. it = PyObject_New(formatteriterobject, &PyFormatterIter_Type);
  968. if (it == NULL)
  969. return NULL;
  970. /* take ownership, give the object to the iterator */
  971. Py_INCREF(self);
  972. it->str = self;
  973. /* initialize the contained MarkupIterator */
  974. MarkupIterator_init(&it->it_markup, (PyObject*)self, 0, PyUnicode_GET_LENGTH(self));
  975. return (PyObject *)it;
  976. }
  977. /************************************************************************/
  978. /*********** fieldnameiterator ******************************************/
  979. /************************************************************************/
  980. /* This is used to implement string.Formatter.vparse(). It parses the
  981. field name into attribute and item values. It's a Python-callable
  982. wrapper around FieldNameIterator */
  983. typedef struct {
  984. PyObject_HEAD
  985. PyObject *str;
  986. FieldNameIterator it_field;
  987. } fieldnameiterobject;
  988. static void
  989. fieldnameiter_dealloc(fieldnameiterobject *it)
  990. {
  991. Py_XDECREF(it->str);
  992. PyObject_FREE(it);
  993. }
  994. /* returns a tuple:
  995. (is_attr, value)
  996. is_attr is true if we used attribute syntax (e.g., '.foo')
  997. false if we used index syntax (e.g., '[foo]')
  998. value is an integer or string
  999. */
  1000. static PyObject *
  1001. fieldnameiter_next(fieldnameiterobject *it)
  1002. {
  1003. int result;
  1004. int is_attr;
  1005. Py_ssize_t idx;
  1006. SubString name;
  1007. result = FieldNameIterator_next(&it->it_field, &is_attr,
  1008. &idx, &name);
  1009. if (result == 0 || result == 1)
  1010. /* if 0, error has already been set, if 1, iterator is empty */
  1011. return NULL;
  1012. else {
  1013. PyObject* result = NULL;
  1014. PyObject* is_attr_obj = NULL;
  1015. PyObject* obj = NULL;
  1016. is_attr_obj = PyBool_FromLong(is_attr);
  1017. if (is_attr_obj == NULL)
  1018. goto done;
  1019. /* either an integer or a string */
  1020. if (idx != -1)
  1021. obj = PyLong_FromSsize_t(idx);
  1022. else
  1023. obj = SubString_new_object(&name);
  1024. if (obj == NULL)
  1025. goto done;
  1026. /* return a tuple of values */
  1027. result = PyTuple_Pack(2, is_attr_obj, obj);
  1028. done:
  1029. Py_XDECREF(is_attr_obj);
  1030. Py_XDECREF(obj);
  1031. return result;
  1032. }
  1033. }
  1034. static PyMethodDef fieldnameiter_methods[] = {
  1035. {NULL, NULL} /* sentinel */
  1036. };
  1037. static PyTypeObject PyFieldNameIter_Type = {
  1038. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1039. "fieldnameiterator", /* tp_name */
  1040. sizeof(fieldnameiterobject), /* tp_basicsize */
  1041. 0, /* tp_itemsize */
  1042. /* methods */
  1043. (destructor)fieldnameiter_dealloc, /* tp_dealloc */
  1044. 0, /* tp_print */
  1045. 0, /* tp_getattr */
  1046. 0, /* tp_setattr */
  1047. 0, /* tp_reserved */
  1048. 0, /* tp_repr */
  1049. 0, /* tp_as_number */
  1050. 0, /* tp_as_sequence */
  1051. 0, /* tp_as_mapping */
  1052. 0, /* tp_hash */
  1053. 0, /* tp_call */
  1054. 0, /* tp_str */
  1055. PyObject_GenericGetAttr, /* tp_getattro */
  1056. 0, /* tp_setattro */
  1057. 0, /* tp_as_buffer */
  1058. Py_TPFLAGS_DEFAULT, /* tp_flags */
  1059. 0, /* tp_doc */
  1060. 0, /* tp_traverse */
  1061. 0, /* tp_clear */
  1062. 0, /* tp_richcompare */
  1063. 0, /* tp_weaklistoffset */
  1064. PyObject_SelfIter, /* tp_iter */
  1065. (iternextfunc)fieldnameiter_next, /* tp_iternext */
  1066. fieldnameiter_methods, /* tp_methods */
  1067. 0};
  1068. /* unicode_formatter_field_name_split is used to implement
  1069. string.Formatter.vformat. it takes an PEP 3101 "field name", and
  1070. returns a tuple of (first, rest): "first", the part before the
  1071. first '.' or '['; and "rest", an iterator for the rest of the field
  1072. name. it's a wrapper around stringlib/string_format.h's
  1073. field_name_split. The iterator it returns is a
  1074. FieldNameIterator */
  1075. static PyObject *
  1076. formatter_field_name_split(PyObject *ignored, PyObject *self)
  1077. {
  1078. SubString first;
  1079. Py_ssize_t first_idx;
  1080. fieldnameiterobject *it;
  1081. PyObject *first_obj = NULL;
  1082. PyObject *result = NULL;
  1083. if (!PyUnicode_Check(self)) {
  1084. PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name);
  1085. return NULL;
  1086. }
  1087. if (PyUnicode_READY(self) == -1)
  1088. return NULL;
  1089. it = PyObject_New(fieldnameiterobject, &PyFieldNameIter_Type);
  1090. if (it == NULL)
  1091. return NULL;
  1092. /* take ownership, give the object to the iterator. this is
  1093. just to keep the field_name alive */
  1094. Py_INCREF(self);
  1095. it->str = self;
  1096. /* Pass in auto_number = NULL. We'll return an empty string for
  1097. first_obj in that case. */
  1098. if (!field_name_split((PyObject*)self, 0, PyUnicode_GET_LENGTH(self),
  1099. &first, &first_idx, &it->it_field, NULL))
  1100. goto done;
  1101. /* first becomes an integer, if possible; else a string */
  1102. if (first_idx != -1)
  1103. first_obj = PyLong_FromSsize_t(first_idx);
  1104. else
  1105. /* convert "first" into a string object */
  1106. first_obj = SubString_new_object(&first);
  1107. if (first_obj == NULL)
  1108. goto done;
  1109. /* return a tuple of values */
  1110. result = PyTuple_Pack(2, first_obj, it);
  1111. done:
  1112. Py_XDECREF(it);
  1113. Py_XDECREF(first_obj);
  1114. return result;
  1115. }