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.

1384 lines
42 KiB

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