/Objects/stringlib/string_format.h

http://unladen-swallow.googlecode.com/ · C Header · 1275 lines · 839 code · 172 blank · 264 comment · 174 complexity · 3c585a51defc041fe51620131e5655d0 MD5 · raw file

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