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.

1469 lines
46 KiB

  1. /* implements the unicode (as opposed to string) version of the
  2. built-in formatters for string, int, float. that is, the versions
  3. of int.__float__, etc., that take and return unicode objects */
  4. #include "Python.h"
  5. #include <locale.h>
  6. /* Raises an exception about an unknown presentation type for this
  7. * type. */
  8. static void
  9. unknown_presentation_type(Py_UCS4 presentation_type,
  10. const char* type_name)
  11. {
  12. /* %c might be out-of-range, hence the two cases. */
  13. if (presentation_type > 32 && presentation_type < 128)
  14. PyErr_Format(PyExc_ValueError,
  15. "Unknown format code '%c' "
  16. "for object of type '%.200s'",
  17. (char)presentation_type,
  18. type_name);
  19. else
  20. PyErr_Format(PyExc_ValueError,
  21. "Unknown format code '\\x%x' "
  22. "for object of type '%.200s'",
  23. (unsigned int)presentation_type,
  24. type_name);
  25. }
  26. static void
  27. invalid_comma_type(Py_UCS4 presentation_type)
  28. {
  29. if (presentation_type > 32 && presentation_type < 128)
  30. PyErr_Format(PyExc_ValueError,
  31. "Cannot specify ',' with '%c'.",
  32. (char)presentation_type);
  33. else
  34. PyErr_Format(PyExc_ValueError,
  35. "Cannot specify ',' with '\\x%x'.",
  36. (unsigned int)presentation_type);
  37. }
  38. /*
  39. get_integer consumes 0 or more decimal digit characters from an
  40. input string, updates *result with the corresponding positive
  41. integer, and returns the number of digits consumed.
  42. returns -1 on error.
  43. */
  44. static int
  45. get_integer(PyObject *str, Py_ssize_t *pos, Py_ssize_t end,
  46. Py_ssize_t *result)
  47. {
  48. Py_ssize_t accumulator, digitval;
  49. int numdigits;
  50. accumulator = numdigits = 0;
  51. for (;;(*pos)++, numdigits++) {
  52. if (*pos >= end)
  53. break;
  54. digitval = Py_UNICODE_TODECIMAL(PyUnicode_READ_CHAR(str, *pos));
  55. if (digitval < 0)
  56. break;
  57. /*
  58. Detect possible overflow before it happens:
  59. accumulator * 10 + digitval > PY_SSIZE_T_MAX if and only if
  60. accumulator > (PY_SSIZE_T_MAX - digitval) / 10.
  61. */
  62. if (accumulator > (PY_SSIZE_T_MAX - digitval) / 10) {
  63. PyErr_Format(PyExc_ValueError,
  64. "Too many decimal digits in format string");
  65. return -1;
  66. }
  67. accumulator = accumulator * 10 + digitval;
  68. }
  69. *result = accumulator;
  70. return numdigits;
  71. }
  72. /************************************************************************/
  73. /*********** standard format specifier parsing **************************/
  74. /************************************************************************/
  75. /* returns true if this character is a specifier alignment token */
  76. Py_LOCAL_INLINE(int)
  77. is_alignment_token(Py_UCS4 c)
  78. {
  79. switch (c) {
  80. case '<': case '>': case '=': case '^':
  81. return 1;
  82. default:
  83. return 0;
  84. }
  85. }
  86. /* returns true if this character is a sign element */
  87. Py_LOCAL_INLINE(int)
  88. is_sign_element(Py_UCS4 c)
  89. {
  90. switch (c) {
  91. case ' ': case '+': case '-':
  92. return 1;
  93. default:
  94. return 0;
  95. }
  96. }
  97. typedef struct {
  98. Py_UCS4 fill_char;
  99. Py_UCS4 align;
  100. int alternate;
  101. Py_UCS4 sign;
  102. Py_ssize_t width;
  103. int thousands_separators;
  104. Py_ssize_t precision;
  105. Py_UCS4 type;
  106. } InternalFormatSpec;
  107. #if 0
  108. /* Occassionally useful for debugging. Should normally be commented out. */
  109. static void
  110. DEBUG_PRINT_FORMAT_SPEC(InternalFormatSpec *format)
  111. {
  112. printf("internal format spec: fill_char %d\n", format->fill_char);
  113. printf("internal format spec: align %d\n", format->align);
  114. printf("internal format spec: alternate %d\n", format->alternate);
  115. printf("internal format spec: sign %d\n", format->sign);
  116. printf("internal format spec: width %zd\n", format->width);
  117. printf("internal format spec: thousands_separators %d\n",
  118. format->thousands_separators);
  119. printf("internal format spec: precision %zd\n", format->precision);
  120. printf("internal format spec: type %c\n", format->type);
  121. printf("\n");
  122. }
  123. #endif
  124. /*
  125. ptr points to the start of the format_spec, end points just past its end.
  126. fills in format with the parsed information.
  127. returns 1 on success, 0 on failure.
  128. if failure, sets the exception
  129. */
  130. static int
  131. parse_internal_render_format_spec(PyObject *format_spec,
  132. Py_ssize_t start, Py_ssize_t end,
  133. InternalFormatSpec *format,
  134. char default_type,
  135. char default_align)
  136. {
  137. Py_ssize_t pos = start;
  138. /* end-pos is used throughout this code to specify the length of
  139. the input string */
  140. #define READ_spec(index) PyUnicode_READ_CHAR(format_spec, index)
  141. Py_ssize_t consumed;
  142. int align_specified = 0;
  143. format->fill_char = '\0';
  144. format->align = default_align;
  145. format->alternate = 0;
  146. format->sign = '\0';
  147. format->width = -1;
  148. format->thousands_separators = 0;
  149. format->precision = -1;
  150. format->type = default_type;
  151. /* If the second char is an alignment token,
  152. then parse the fill char */
  153. if (end-pos >= 2 && is_alignment_token(READ_spec(pos+1))) {
  154. format->align = READ_spec(pos+1);
  155. format->fill_char = READ_spec(pos);
  156. align_specified = 1;
  157. pos += 2;
  158. }
  159. else if (end-pos >= 1 && is_alignment_token(READ_spec(pos))) {
  160. format->align = READ_spec(pos);
  161. align_specified = 1;
  162. ++pos;
  163. }
  164. /* Parse the various sign options */
  165. if (end-pos >= 1 && is_sign_element(READ_spec(pos))) {
  166. format->sign = READ_spec(pos);
  167. ++pos;
  168. }
  169. /* If the next character is #, we're in alternate mode. This only
  170. applies to integers. */
  171. if (end-pos >= 1 && READ_spec(pos) == '#') {
  172. format->alternate = 1;
  173. ++pos;
  174. }
  175. /* The special case for 0-padding (backwards compat) */
  176. if (format->fill_char == '\0' && end-pos >= 1 && READ_spec(pos) == '0') {
  177. format->fill_char = '0';
  178. if (!align_specified) {
  179. format->align = '=';
  180. }
  181. ++pos;
  182. }
  183. consumed = get_integer(format_spec, &pos, end, &format->width);
  184. if (consumed == -1)
  185. /* Overflow error. Exception already set. */
  186. return 0;
  187. /* If consumed is 0, we didn't consume any characters for the
  188. width. In that case, reset the width to -1, because
  189. get_integer() will have set it to zero. -1 is how we record
  190. that the width wasn't specified. */
  191. if (consumed == 0)
  192. format->width = -1;
  193. /* Comma signifies add thousands separators */
  194. if (end-pos && READ_spec(pos) == ',') {
  195. format->thousands_separators = 1;
  196. ++pos;
  197. }
  198. /* Parse field precision */
  199. if (end-pos && READ_spec(pos) == '.') {
  200. ++pos;
  201. consumed = get_integer(format_spec, &pos, end, &format->precision);
  202. if (consumed == -1)
  203. /* Overflow error. Exception already set. */
  204. return 0;
  205. /* Not having a precision after a dot is an error. */
  206. if (consumed == 0) {
  207. PyErr_Format(PyExc_ValueError,
  208. "Format specifier missing precision");
  209. return 0;
  210. }
  211. }
  212. /* Finally, parse the type field. */
  213. if (end-pos > 1) {
  214. /* More than one char remain, invalid conversion spec. */
  215. PyErr_Format(PyExc_ValueError, "Invalid conversion specification");
  216. return 0;
  217. }
  218. if (end-pos == 1) {
  219. format->type = READ_spec(pos);
  220. ++pos;
  221. }
  222. /* Do as much validating as we can, just by looking at the format
  223. specifier. Do not take into account what type of formatting
  224. we're doing (int, float, string). */
  225. if (format->thousands_separators) {
  226. switch (format->type) {
  227. case 'd':
  228. case 'e':
  229. case 'f':
  230. case 'g':
  231. case 'E':
  232. case 'G':
  233. case '%':
  234. case 'F':
  235. case '\0':
  236. /* These are allowed. See PEP 378.*/
  237. break;
  238. default:
  239. invalid_comma_type(format->type);
  240. return 0;
  241. }
  242. }
  243. if (format->fill_char > 127 || format->align > 127 ||
  244. format->sign > 127) {
  245. PyErr_SetString(PyExc_ValueError, "fill character too large");
  246. return 0;
  247. }
  248. return 1;
  249. }
  250. /* Calculate the padding needed. */
  251. static void
  252. calc_padding(Py_ssize_t nchars, Py_ssize_t width, Py_UCS4 align,
  253. Py_ssize_t *n_lpadding, Py_ssize_t *n_rpadding,
  254. Py_ssize_t *n_total)
  255. {
  256. if (width >= 0) {
  257. if (nchars > width)
  258. *n_total = nchars;
  259. else
  260. *n_total = width;
  261. }
  262. else {
  263. /* not specified, use all of the chars and no more */
  264. *n_total = nchars;
  265. }
  266. /* Figure out how much leading space we need, based on the
  267. aligning */
  268. if (align == '>')
  269. *n_lpadding = *n_total - nchars;
  270. else if (align == '^')
  271. *n_lpadding = (*n_total - nchars) / 2;
  272. else if (align == '<' || align == '=')
  273. *n_lpadding = 0;
  274. else {
  275. /* We should never have an unspecified alignment. */
  276. *n_lpadding = 0;
  277. assert(0);
  278. }
  279. *n_rpadding = *n_total - nchars - *n_lpadding;
  280. }
  281. /* Do the padding, and return a pointer to where the caller-supplied
  282. content goes. */
  283. static Py_ssize_t
  284. fill_padding(PyObject *s, Py_ssize_t start, Py_ssize_t nchars,
  285. Py_UCS4 fill_char, Py_ssize_t n_lpadding,
  286. Py_ssize_t n_rpadding)
  287. {
  288. /* Pad on left. */
  289. if (n_lpadding)
  290. PyUnicode_Fill(s, start, start + n_lpadding, fill_char);
  291. /* Pad on right. */
  292. if (n_rpadding)
  293. PyUnicode_Fill(s, start + nchars + n_lpadding,
  294. start + nchars + n_lpadding + n_rpadding, fill_char);
  295. /* Pointer to the user content. */
  296. return start + n_lpadding;
  297. }
  298. /************************************************************************/
  299. /*********** common routines for numeric formatting *********************/
  300. /************************************************************************/
  301. /* Locale type codes. */
  302. #define LT_CURRENT_LOCALE 0
  303. #define LT_DEFAULT_LOCALE 1
  304. #define LT_NO_LOCALE 2
  305. /* Locale info needed for formatting integers and the part of floats
  306. before and including the decimal. Note that locales only support
  307. 8-bit chars, not unicode. */
  308. typedef struct {
  309. char *decimal_point;
  310. char *thousands_sep;
  311. char *grouping;
  312. } LocaleInfo;
  313. /* describes the layout for an integer, see the comment in
  314. calc_number_widths() for details */
  315. typedef struct {
  316. Py_ssize_t n_lpadding;
  317. Py_ssize_t n_prefix;
  318. Py_ssize_t n_spadding;
  319. Py_ssize_t n_rpadding;
  320. char sign;
  321. Py_ssize_t n_sign; /* number of digits needed for sign (0/1) */
  322. Py_ssize_t n_grouped_digits; /* Space taken up by the digits, including
  323. any grouping chars. */
  324. Py_ssize_t n_decimal; /* 0 if only an integer */
  325. Py_ssize_t n_remainder; /* Digits in decimal and/or exponent part,
  326. excluding the decimal itself, if
  327. present. */
  328. /* These 2 are not the widths of fields, but are needed by
  329. STRINGLIB_GROUPING. */
  330. Py_ssize_t n_digits; /* The number of digits before a decimal
  331. or exponent. */
  332. Py_ssize_t n_min_width; /* The min_width we used when we computed
  333. the n_grouped_digits width. */
  334. } NumberFieldWidths;
  335. /* Given a number of the form:
  336. digits[remainder]
  337. where ptr points to the start and end points to the end, find where
  338. the integer part ends. This could be a decimal, an exponent, both,
  339. or neither.
  340. If a decimal point is present, set *has_decimal and increment
  341. remainder beyond it.
  342. Results are undefined (but shouldn't crash) for improperly
  343. formatted strings.
  344. */
  345. static void
  346. parse_number(PyObject *s, Py_ssize_t pos, Py_ssize_t end,
  347. Py_ssize_t *n_remainder, int *has_decimal)
  348. {
  349. Py_ssize_t remainder;
  350. while (pos<end && isdigit(PyUnicode_READ_CHAR(s, pos)))
  351. ++pos;
  352. remainder = pos;
  353. /* Does remainder start with a decimal point? */
  354. *has_decimal = pos<end && PyUnicode_READ_CHAR(s, remainder) == '.';
  355. /* Skip the decimal point. */
  356. if (*has_decimal)
  357. remainder++;
  358. *n_remainder = end - remainder;
  359. }
  360. /* not all fields of format are used. for example, precision is
  361. unused. should this take discrete params in order to be more clear
  362. about what it does? or is passing a single format parameter easier
  363. and more efficient enough to justify a little obfuscation? */
  364. static Py_ssize_t
  365. calc_number_widths(NumberFieldWidths *spec, Py_ssize_t n_prefix,
  366. Py_UCS4 sign_char, PyObject *number, Py_ssize_t n_start,
  367. Py_ssize_t n_end, Py_ssize_t n_remainder,
  368. int has_decimal, const LocaleInfo *locale,
  369. const InternalFormatSpec *format)
  370. {
  371. Py_ssize_t n_non_digit_non_padding;
  372. Py_ssize_t n_padding;
  373. spec->n_digits = n_end - n_start - n_remainder - (has_decimal?1:0);
  374. spec->n_lpadding = 0;
  375. spec->n_prefix = n_prefix;
  376. spec->n_decimal = has_decimal ? strlen(locale->decimal_point) : 0;
  377. spec->n_remainder = n_remainder;
  378. spec->n_spadding = 0;
  379. spec->n_rpadding = 0;
  380. spec->sign = '\0';
  381. spec->n_sign = 0;
  382. /* the output will look like:
  383. | |
  384. | <lpadding> <sign> <prefix> <spadding> <grouped_digits> <decimal> <remainder> <rpadding> |
  385. | |
  386. sign is computed from format->sign and the actual
  387. sign of the number
  388. prefix is given (it's for the '0x' prefix)
  389. digits is already known
  390. the total width is either given, or computed from the
  391. actual digits
  392. only one of lpadding, spadding, and rpadding can be non-zero,
  393. and it's calculated from the width and other fields
  394. */
  395. /* compute the various parts we're going to write */
  396. switch (format->sign) {
  397. case '+':
  398. /* always put a + or - */
  399. spec->n_sign = 1;
  400. spec->sign = (sign_char == '-' ? '-' : '+');
  401. break;
  402. case ' ':
  403. spec->n_sign = 1;
  404. spec->sign = (sign_char == '-' ? '-' : ' ');
  405. break;
  406. default:
  407. /* Not specified, or the default (-) */
  408. if (sign_char == '-') {
  409. spec->n_sign = 1;
  410. spec->sign = '-';
  411. }
  412. }
  413. /* The number of chars used for non-digits and non-padding. */
  414. n_non_digit_non_padding = spec->n_sign + spec->n_prefix + spec->n_decimal +
  415. spec->n_remainder;
  416. /* min_width can go negative, that's okay. format->width == -1 means
  417. we don't care. */
  418. if (format->fill_char == '0' && format->align == '=')
  419. spec->n_min_width = format->width - n_non_digit_non_padding;
  420. else
  421. spec->n_min_width = 0;
  422. if (spec->n_digits == 0)
  423. /* This case only occurs when using 'c' formatting, we need
  424. to special case it because the grouping code always wants
  425. to have at least one character. */
  426. spec->n_grouped_digits = 0;
  427. else
  428. spec->n_grouped_digits = _PyUnicode_InsertThousandsGrouping(
  429. NULL, PyUnicode_1BYTE_KIND, NULL, 0, NULL,
  430. spec->n_digits, spec->n_min_width,
  431. locale->grouping, locale->thousands_sep);
  432. /* Given the desired width and the total of digit and non-digit
  433. space we consume, see if we need any padding. format->width can
  434. be negative (meaning no padding), but this code still works in
  435. that case. */
  436. n_padding = format->width -
  437. (n_non_digit_non_padding + spec->n_grouped_digits);
  438. if (n_padding > 0) {
  439. /* Some padding is needed. Determine if it's left, space, or right. */
  440. switch (format->align) {
  441. case '<':
  442. spec->n_rpadding = n_padding;
  443. break;
  444. case '^':
  445. spec->n_lpadding = n_padding / 2;
  446. spec->n_rpadding = n_padding - spec->n_lpadding;
  447. break;
  448. case '=':
  449. spec->n_spadding = n_padding;
  450. break;
  451. case '>':
  452. spec->n_lpadding = n_padding;
  453. break;
  454. default:
  455. /* Shouldn't get here, but treat it as '>' */
  456. spec->n_lpadding = n_padding;
  457. assert(0);
  458. break;
  459. }
  460. }
  461. return spec->n_lpadding + spec->n_sign + spec->n_prefix +
  462. spec->n_spadding + spec->n_grouped_digits + spec->n_decimal +
  463. spec->n_remainder + spec->n_rpadding;
  464. }
  465. /* Fill in the digit parts of a numbers's string representation,
  466. as determined in calc_number_widths().
  467. Return -1 on error, or 0 on success. */
  468. static int
  469. fill_number(PyObject *out, Py_ssize_t pos, const NumberFieldWidths *spec,
  470. PyObject *digits, Py_ssize_t d_start, Py_ssize_t d_end,
  471. PyObject *prefix, Py_ssize_t p_start,
  472. Py_UCS4 fill_char,
  473. LocaleInfo *locale, int toupper)
  474. {
  475. /* Used to keep track of digits, decimal, and remainder. */
  476. Py_ssize_t d_pos = d_start;
  477. unsigned int kind = PyUnicode_KIND(out);
  478. void *data = PyUnicode_DATA(out);
  479. #ifndef NDEBUG
  480. Py_ssize_t r;
  481. #endif
  482. if (spec->n_lpadding) {
  483. PyUnicode_Fill(out, pos, pos + spec->n_lpadding, fill_char);
  484. pos += spec->n_lpadding;
  485. }
  486. if (spec->n_sign == 1) {
  487. PyUnicode_WRITE(kind, data, pos++, spec->sign);
  488. }
  489. if (spec->n_prefix) {
  490. if (PyUnicode_CopyCharacters(out, pos,
  491. prefix, p_start,
  492. spec->n_prefix) < 0)
  493. return -1;
  494. if (toupper) {
  495. Py_ssize_t t;
  496. for (t = 0; t < spec->n_prefix; t++) {
  497. Py_UCS4 c = PyUnicode_READ(kind, data, pos + t);
  498. if (c > 127) {
  499. PyErr_SetString(PyExc_SystemError, "prefix not ASCII");
  500. return -1;
  501. }
  502. PyUnicode_WRITE(kind, data, pos + t, Py_TOUPPER(c));
  503. }
  504. }
  505. pos += spec->n_prefix;
  506. }
  507. if (spec->n_spadding) {
  508. PyUnicode_Fill(out, pos, pos + spec->n_spadding, fill_char);
  509. pos += spec->n_spadding;
  510. }
  511. /* Only for type 'c' special case, it has no digits. */
  512. if (spec->n_digits != 0) {
  513. /* Fill the digits with InsertThousandsGrouping. */
  514. char *pdigits;
  515. if (PyUnicode_READY(digits))
  516. return -1;
  517. pdigits = PyUnicode_DATA(digits);
  518. if (PyUnicode_KIND(digits) < kind) {
  519. pdigits = _PyUnicode_AsKind(digits, kind);
  520. if (pdigits == NULL)
  521. return -1;
  522. }
  523. #ifndef NDEBUG
  524. r =
  525. #endif
  526. _PyUnicode_InsertThousandsGrouping(
  527. out, kind,
  528. (char*)data + kind * pos,
  529. spec->n_grouped_digits,
  530. pdigits + kind * d_pos,
  531. spec->n_digits, spec->n_min_width,
  532. locale->grouping, locale->thousands_sep);
  533. #ifndef NDEBUG
  534. assert(r == spec->n_grouped_digits);
  535. #endif
  536. if (PyUnicode_KIND(digits) < kind)
  537. PyMem_Free(pdigits);
  538. d_pos += spec->n_digits;
  539. }
  540. if (toupper) {
  541. Py_ssize_t t;
  542. for (t = 0; t < spec->n_grouped_digits; t++) {
  543. Py_UCS4 c = PyUnicode_READ(kind, data, pos + t);
  544. if (c > 127) {
  545. PyErr_SetString(PyExc_SystemError, "non-ascii grouped digit");
  546. return -1;
  547. }
  548. PyUnicode_WRITE(kind, data, pos + t, Py_TOUPPER(c));
  549. }
  550. }
  551. pos += spec->n_grouped_digits;
  552. if (spec->n_decimal) {
  553. Py_ssize_t t;
  554. for (t = 0; t < spec->n_decimal; ++t)
  555. PyUnicode_WRITE(kind, data, pos + t,
  556. locale->decimal_point[t]);
  557. pos += spec->n_decimal;
  558. d_pos += 1;
  559. }
  560. if (spec->n_remainder) {
  561. if (PyUnicode_CopyCharacters(out, pos, digits, d_pos, spec->n_remainder) < 0)
  562. return -1;
  563. pos += spec->n_remainder;
  564. d_pos += spec->n_remainder;
  565. }
  566. if (spec->n_rpadding) {
  567. PyUnicode_Fill(out, pos, pos + spec->n_rpadding, fill_char);
  568. pos += spec->n_rpadding;
  569. }
  570. return 0;
  571. }
  572. static char no_grouping[1] = {CHAR_MAX};
  573. /* Find the decimal point character(s?), thousands_separator(s?), and
  574. grouping description, either for the current locale if type is
  575. LT_CURRENT_LOCALE, a hard-coded locale if LT_DEFAULT_LOCALE, or
  576. none if LT_NO_LOCALE. */
  577. static void
  578. get_locale_info(int type, LocaleInfo *locale_info)
  579. {
  580. switch (type) {
  581. case LT_CURRENT_LOCALE: {
  582. struct lconv *locale_data = localeconv();
  583. locale_info->decimal_point = locale_data->decimal_point;
  584. locale_info->thousands_sep = locale_data->thousands_sep;
  585. locale_info->grouping = locale_data->grouping;
  586. break;
  587. }
  588. case LT_DEFAULT_LOCALE:
  589. locale_info->decimal_point = ".";
  590. locale_info->thousands_sep = ",";
  591. locale_info->grouping = "\3"; /* Group every 3 characters. The
  592. (implicit) trailing 0 means repeat
  593. infinitely. */
  594. break;
  595. case LT_NO_LOCALE:
  596. locale_info->decimal_point = ".";
  597. locale_info->thousands_sep = "";
  598. locale_info->grouping = no_grouping;
  599. break;
  600. default:
  601. assert(0);
  602. }
  603. }
  604. /************************************************************************/
  605. /*********** string formatting ******************************************/
  606. /************************************************************************/
  607. static PyObject *
  608. format_string_internal(PyObject *value, const InternalFormatSpec *format)
  609. {
  610. Py_ssize_t lpad;
  611. Py_ssize_t rpad;
  612. Py_ssize_t total;
  613. Py_ssize_t pos;
  614. Py_ssize_t len = PyUnicode_GET_LENGTH(value);
  615. PyObject *result = NULL;
  616. int maxchar = 127;
  617. /* sign is not allowed on strings */
  618. if (format->sign != '\0') {
  619. PyErr_SetString(PyExc_ValueError,
  620. "Sign not allowed in string format specifier");
  621. goto done;
  622. }
  623. /* alternate is not allowed on strings */
  624. if (format->alternate) {
  625. PyErr_SetString(PyExc_ValueError,
  626. "Alternate form (#) not allowed in string format "
  627. "specifier");
  628. goto done;
  629. }
  630. /* '=' alignment not allowed on strings */
  631. if (format->align == '=') {
  632. PyErr_SetString(PyExc_ValueError,
  633. "'=' alignment not allowed "
  634. "in string format specifier");
  635. goto done;
  636. }
  637. /* if precision is specified, output no more that format.precision
  638. characters */
  639. if (format->precision >= 0 && len >= format->precision) {
  640. len = format->precision;
  641. }
  642. calc_padding(len, format->width, format->align, &lpad, &rpad, &total);
  643. /* allocate the resulting string */
  644. result = PyUnicode_New(total, maxchar);
  645. if (result == NULL)
  646. goto done;
  647. /* Write into that space. First the padding. */
  648. pos = fill_padding(result, 0, len,
  649. format->fill_char=='\0'?' ':format->fill_char,
  650. lpad, rpad);
  651. /* Then the source string. */
  652. if (PyUnicode_CopyCharacters(result, pos, value, 0, len) < 0)
  653. Py_CLEAR(result);
  654. done:
  655. return result;
  656. }
  657. /************************************************************************/
  658. /*********** long formatting ********************************************/
  659. /************************************************************************/
  660. typedef PyObject*
  661. (*IntOrLongToString)(PyObject *value, int base);
  662. static PyObject *
  663. format_int_or_long_internal(PyObject *value, const InternalFormatSpec *format,
  664. IntOrLongToString tostring)
  665. {
  666. PyObject *result = NULL;
  667. int maxchar = 127;
  668. PyObject *tmp = NULL;
  669. Py_ssize_t inumeric_chars;
  670. Py_UCS4 sign_char = '\0';
  671. Py_ssize_t n_digits; /* count of digits need from the computed
  672. string */
  673. Py_ssize_t n_remainder = 0; /* Used only for 'c' formatting, which
  674. produces non-digits */
  675. Py_ssize_t n_prefix = 0; /* Count of prefix chars, (e.g., '0x') */
  676. Py_ssize_t n_total;
  677. Py_ssize_t prefix;
  678. NumberFieldWidths spec;
  679. long x;
  680. int err;
  681. /* Locale settings, either from the actual locale or
  682. from a hard-code pseudo-locale */
  683. LocaleInfo locale;
  684. /* no precision allowed on integers */
  685. if (format->precision != -1) {
  686. PyErr_SetString(PyExc_ValueError,
  687. "Precision not allowed in integer format specifier");
  688. goto done;
  689. }
  690. /* special case for character formatting */
  691. if (format->type == 'c') {
  692. /* error to specify a sign */
  693. if (format->sign != '\0') {
  694. PyErr_SetString(PyExc_ValueError,
  695. "Sign not allowed with integer"
  696. " format specifier 'c'");
  697. goto done;
  698. }
  699. /* taken from unicodeobject.c formatchar() */
  700. /* Integer input truncated to a character */
  701. /* XXX: won't work for int */
  702. x = PyLong_AsLong(value);
  703. if (x == -1 && PyErr_Occurred())
  704. goto done;
  705. if (x < 0 || x > 0x10ffff) {
  706. PyErr_SetString(PyExc_OverflowError,
  707. "%c arg not in range(0x110000) "
  708. "(wide Python build)");
  709. goto done;
  710. }
  711. tmp = PyUnicode_FromOrdinal(x);
  712. inumeric_chars = 0;
  713. n_digits = 1;
  714. if (x > maxchar)
  715. maxchar = x;
  716. /* As a sort-of hack, we tell calc_number_widths that we only
  717. have "remainder" characters. calc_number_widths thinks
  718. these are characters that don't get formatted, only copied
  719. into the output string. We do this for 'c' formatting,
  720. because the characters are likely to be non-digits. */
  721. n_remainder = 1;
  722. }
  723. else {
  724. int base;
  725. int leading_chars_to_skip = 0; /* Number of characters added by
  726. PyNumber_ToBase that we want to
  727. skip over. */
  728. /* Compute the base and how many characters will be added by
  729. PyNumber_ToBase */
  730. switch (format->type) {
  731. case 'b':
  732. base = 2;
  733. leading_chars_to_skip = 2; /* 0b */
  734. break;
  735. case 'o':
  736. base = 8;
  737. leading_chars_to_skip = 2; /* 0o */
  738. break;
  739. case 'x':
  740. case 'X':
  741. base = 16;
  742. leading_chars_to_skip = 2; /* 0x */
  743. break;
  744. default: /* shouldn't be needed, but stops a compiler warning */
  745. case 'd':
  746. case 'n':
  747. base = 10;
  748. break;
  749. }
  750. /* The number of prefix chars is the same as the leading
  751. chars to skip */
  752. if (format->alternate)
  753. n_prefix = leading_chars_to_skip;
  754. /* Do the hard part, converting to a string in a given base */
  755. tmp = tostring(value, base);
  756. if (tmp == NULL || PyUnicode_READY(tmp) == -1)
  757. goto done;
  758. inumeric_chars = 0;
  759. n_digits = PyUnicode_GET_LENGTH(tmp);
  760. prefix = inumeric_chars;
  761. /* Is a sign character present in the output? If so, remember it
  762. and skip it */
  763. if (PyUnicode_READ_CHAR(tmp, inumeric_chars) == '-') {
  764. sign_char = '-';
  765. ++prefix;
  766. ++leading_chars_to_skip;
  767. }
  768. /* Skip over the leading chars (0x, 0b, etc.) */
  769. n_digits -= leading_chars_to_skip;
  770. inumeric_chars += leading_chars_to_skip;
  771. }
  772. /* Determine the grouping, separator, and decimal point, if any. */
  773. get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
  774. (format->thousands_separators ?
  775. LT_DEFAULT_LOCALE :
  776. LT_NO_LOCALE),
  777. &locale);
  778. /* Calculate how much memory we'll need. */
  779. n_total = calc_number_widths(&spec, n_prefix, sign_char, tmp, inumeric_chars,
  780. inumeric_chars + n_digits, n_remainder, 0, &locale, format);
  781. /* Allocate the memory. */
  782. result = PyUnicode_New(n_total, maxchar);
  783. if (!result)
  784. goto done;
  785. /* Populate the memory. */
  786. err = fill_number(result, 0, &spec,
  787. tmp, inumeric_chars, inumeric_chars + n_digits,
  788. tmp, prefix,
  789. format->fill_char == '\0' ? ' ' : format->fill_char,
  790. &locale, format->type == 'X');
  791. if (err)
  792. Py_CLEAR(result);
  793. done:
  794. Py_XDECREF(tmp);
  795. return result;
  796. }
  797. /************************************************************************/
  798. /*********** float formatting *******************************************/
  799. /************************************************************************/
  800. static PyObject*
  801. strtounicode(char *charbuffer, Py_ssize_t len)
  802. {
  803. return PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, charbuffer, len);
  804. }
  805. /* much of this is taken from unicodeobject.c */
  806. static PyObject *
  807. format_float_internal(PyObject *value,
  808. const InternalFormatSpec *format)
  809. {
  810. char *buf = NULL; /* buffer returned from PyOS_double_to_string */
  811. Py_ssize_t n_digits;
  812. Py_ssize_t n_remainder;
  813. Py_ssize_t n_total;
  814. int has_decimal;
  815. double val;
  816. Py_ssize_t precision = format->precision;
  817. Py_ssize_t default_precision = 6;
  818. Py_UCS4 type = format->type;
  819. int add_pct = 0;
  820. Py_ssize_t index;
  821. NumberFieldWidths spec;
  822. int flags = 0;
  823. PyObject *result = NULL;
  824. int maxchar = 127;
  825. Py_UCS4 sign_char = '\0';
  826. int float_type; /* Used to see if we have a nan, inf, or regular float. */
  827. PyObject *unicode_tmp = NULL;
  828. int err;
  829. /* Locale settings, either from the actual locale or
  830. from a hard-code pseudo-locale */
  831. LocaleInfo locale;
  832. if (format->alternate)
  833. flags |= Py_DTSF_ALT;
  834. if (type == '\0') {
  835. /* Omitted type specifier. Behaves in the same way as repr(x)
  836. and str(x) if no precision is given, else like 'g', but with
  837. at least one digit after the decimal point. */
  838. flags |= Py_DTSF_ADD_DOT_0;
  839. type = 'r';
  840. default_precision = 0;
  841. }
  842. if (type == 'n')
  843. /* 'n' is the same as 'g', except for the locale used to
  844. format the result. We take care of that later. */
  845. type = 'g';
  846. val = PyFloat_AsDouble(value);
  847. if (val == -1.0 && PyErr_Occurred())
  848. goto done;
  849. if (type == '%') {
  850. type = 'f';
  851. val *= 100;
  852. add_pct = 1;
  853. }
  854. if (precision < 0)
  855. precision = default_precision;
  856. else if (type == 'r')
  857. type = 'g';
  858. /* Cast "type", because if we're in unicode we need to pass a
  859. 8-bit char. This is safe, because we've restricted what "type"
  860. can be. */
  861. buf = PyOS_double_to_string(val, (char)type, precision, flags,
  862. &float_type);
  863. if (buf == NULL)
  864. goto done;
  865. n_digits = strlen(buf);
  866. if (add_pct) {
  867. /* We know that buf has a trailing zero (since we just called
  868. strlen() on it), and we don't use that fact any more. So we
  869. can just write over the trailing zero. */
  870. buf[n_digits] = '%';
  871. n_digits += 1;
  872. }
  873. /* Since there is no unicode version of PyOS_double_to_string,
  874. just use the 8 bit version and then convert to unicode. */
  875. unicode_tmp = strtounicode(buf, n_digits);
  876. if (unicode_tmp == NULL)
  877. goto done;
  878. index = 0;
  879. /* Is a sign character present in the output? If so, remember it
  880. and skip it */
  881. if (PyUnicode_READ_CHAR(unicode_tmp, index) == '-') {
  882. sign_char = '-';
  883. ++index;
  884. --n_digits;
  885. }
  886. /* Determine if we have any "remainder" (after the digits, might include
  887. decimal or exponent or both (or neither)) */
  888. parse_number(unicode_tmp, index, index + n_digits, &n_remainder, &has_decimal);
  889. /* Determine the grouping, separator, and decimal point, if any. */
  890. get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
  891. (format->thousands_separators ?
  892. LT_DEFAULT_LOCALE :
  893. LT_NO_LOCALE),
  894. &locale);
  895. /* Calculate how much memory we'll need. */
  896. n_total = calc_number_widths(&spec, 0, sign_char, unicode_tmp, index,
  897. index + n_digits, n_remainder, has_decimal,
  898. &locale, format);
  899. /* Allocate the memory. */
  900. result = PyUnicode_New(n_total, maxchar);
  901. if (result == NULL)
  902. goto done;
  903. /* Populate the memory. */
  904. err = fill_number(result, 0, &spec,
  905. unicode_tmp, index, index + n_digits,
  906. NULL, 0,
  907. format->fill_char == '\0' ? ' ' : format->fill_char,
  908. &locale, 0);
  909. if (err)
  910. Py_CLEAR(result);
  911. done:
  912. PyMem_Free(buf);
  913. Py_DECREF(unicode_tmp);
  914. return result;
  915. }
  916. /************************************************************************/
  917. /*********** complex formatting *****************************************/
  918. /************************************************************************/
  919. static PyObject *
  920. format_complex_internal(PyObject *value,
  921. const InternalFormatSpec *format)
  922. {
  923. double re;
  924. double im;
  925. char *re_buf = NULL; /* buffer returned from PyOS_double_to_string */
  926. char *im_buf = NULL; /* buffer returned from PyOS_double_to_string */
  927. InternalFormatSpec tmp_format = *format;
  928. Py_ssize_t n_re_digits;
  929. Py_ssize_t n_im_digits;
  930. Py_ssize_t n_re_remainder;
  931. Py_ssize_t n_im_remainder;
  932. Py_ssize_t n_re_total;
  933. Py_ssize_t n_im_total;
  934. int re_has_decimal;
  935. int im_has_decimal;
  936. Py_ssize_t precision = format->precision;
  937. Py_ssize_t default_precision = 6;
  938. Py_UCS4 type = format->type;
  939. Py_ssize_t i_re;
  940. Py_ssize_t i_im;
  941. NumberFieldWidths re_spec;
  942. NumberFieldWidths im_spec;
  943. int flags = 0;
  944. PyObject *result = NULL;
  945. int maxchar = 127;
  946. int rkind;
  947. void *rdata;
  948. Py_ssize_t index;
  949. Py_UCS4 re_sign_char = '\0';
  950. Py_UCS4 im_sign_char = '\0';
  951. int re_float_type; /* Used to see if we have a nan, inf, or regular float. */
  952. int im_float_type;
  953. int add_parens = 0;
  954. int skip_re = 0;
  955. Py_ssize_t lpad;
  956. Py_ssize_t rpad;
  957. Py_ssize_t total;
  958. PyObject *re_unicode_tmp = NULL;
  959. PyObject *im_unicode_tmp = NULL;
  960. int err;
  961. /* Locale settings, either from the actual locale or
  962. from a hard-code pseudo-locale */
  963. LocaleInfo locale;
  964. /* Zero padding is not allowed. */
  965. if (format->fill_char == '0') {
  966. PyErr_SetString(PyExc_ValueError,
  967. "Zero padding is not allowed in complex format "
  968. "specifier");
  969. goto done;
  970. }
  971. /* Neither is '=' alignment . */
  972. if (format->align == '=') {
  973. PyErr_SetString(PyExc_ValueError,
  974. "'=' alignment flag is not allowed in complex format "
  975. "specifier");
  976. goto done;
  977. }
  978. re = PyComplex_RealAsDouble(value);
  979. if (re == -1.0 && PyErr_Occurred())
  980. goto done;
  981. im = PyComplex_ImagAsDouble(value);
  982. if (im == -1.0 && PyErr_Occurred())
  983. goto done;
  984. if (format->alternate)
  985. flags |= Py_DTSF_ALT;
  986. if (type == '\0') {
  987. /* Omitted type specifier. Should be like str(self). */
  988. type = 'r';
  989. default_precision = 0;
  990. if (re == 0.0 && copysign(1.0, re) == 1.0)
  991. skip_re = 1;
  992. else
  993. add_parens = 1;
  994. }
  995. if (type == 'n')
  996. /* 'n' is the same as 'g', except for the locale used to
  997. format the result. We take care of that later. */
  998. type = 'g';
  999. if (precision < 0)
  1000. precision = default_precision;
  1001. else if (type == 'r')
  1002. type = 'g';
  1003. /* Cast "type", because if we're in unicode we need to pass a
  1004. 8-bit char. This is safe, because we've restricted what "type"
  1005. can be. */
  1006. re_buf = PyOS_double_to_string(re, (char)type, precision, flags,
  1007. &re_float_type);
  1008. if (re_buf == NULL)
  1009. goto done;
  1010. im_buf = PyOS_double_to_string(im, (char)type, precision, flags,
  1011. &im_float_type);
  1012. if (im_buf == NULL)
  1013. goto done;
  1014. n_re_digits = strlen(re_buf);
  1015. n_im_digits = strlen(im_buf);
  1016. /* Since there is no unicode version of PyOS_double_to_string,
  1017. just use the 8 bit version and then convert to unicode. */
  1018. re_unicode_tmp = strtounicode(re_buf, n_re_digits);
  1019. if (re_unicode_tmp == NULL)
  1020. goto done;
  1021. i_re = 0;
  1022. im_unicode_tmp = strtounicode(im_buf, n_im_digits);
  1023. if (im_unicode_tmp == NULL)
  1024. goto done;
  1025. i_im = 0;
  1026. /* Is a sign character present in the output? If so, remember it
  1027. and skip it */
  1028. if (PyUnicode_READ_CHAR(re_unicode_tmp, i_re) == '-') {
  1029. re_sign_char = '-';
  1030. ++i_re;
  1031. --n_re_digits;
  1032. }
  1033. if (PyUnicode_READ_CHAR(im_unicode_tmp, i_im) == '-') {
  1034. im_sign_char = '-';
  1035. ++i_im;
  1036. --n_im_digits;
  1037. }
  1038. /* Determine if we have any "remainder" (after the digits, might include
  1039. decimal or exponent or both (or neither)) */
  1040. parse_number(re_unicode_tmp, i_re, i_re + n_re_digits,
  1041. &n_re_remainder, &re_has_decimal);
  1042. parse_number(im_unicode_tmp, i_im, i_im + n_im_digits,
  1043. &n_im_remainder, &im_has_decimal);
  1044. /* Determine the grouping, separator, and decimal point, if any. */
  1045. get_locale_info(format->type == 'n' ? LT_CURRENT_LOCALE :
  1046. (format->thousands_separators ?
  1047. LT_DEFAULT_LOCALE :
  1048. LT_NO_LOCALE),
  1049. &locale);
  1050. /* Turn off any padding. We'll do it later after we've composed
  1051. the numbers without padding. */
  1052. tmp_format.fill_char = '\0';
  1053. tmp_format.align = '<';
  1054. tmp_format.width = -1;
  1055. /* Calculate how much memory we'll need. */
  1056. n_re_total = calc_number_widths(&re_spec, 0, re_sign_char, re_unicode_tmp,
  1057. i_re, i_re + n_re_digits, n_re_remainder,
  1058. re_has_decimal, &locale, &tmp_format);
  1059. /* Same formatting, but always include a sign, unless the real part is
  1060. * going to be omitted, in which case we use whatever sign convention was
  1061. * requested by the original format. */
  1062. if (!skip_re)
  1063. tmp_format.sign = '+';
  1064. n_im_total = calc_number_widths(&im_spec, 0, im_sign_char, im_unicode_tmp,
  1065. i_im, i_im + n_im_digits, n_im_remainder,
  1066. im_has_decimal, &locale, &tmp_format);
  1067. if (skip_re)
  1068. n_re_total = 0;
  1069. /* Add 1 for the 'j', and optionally 2 for parens. */
  1070. calc_padding(n_re_total + n_im_total + 1 + add_parens * 2,
  1071. format->width, format->align, &lpad, &rpad, &total);
  1072. result = PyUnicode_New(total, maxchar);
  1073. if (result == NULL)
  1074. goto done;
  1075. rkind = PyUnicode_KIND(result);
  1076. rdata = PyUnicode_DATA(result);
  1077. /* Populate the memory. First, the padding. */
  1078. index = fill_padding(result, 0,
  1079. n_re_total + n_im_total + 1 + add_parens * 2,
  1080. format->fill_char=='\0' ? ' ' : format->fill_char,
  1081. lpad, rpad);
  1082. if (add_parens)
  1083. PyUnicode_WRITE(rkind, rdata, index++, '(');
  1084. if (!skip_re) {
  1085. err = fill_number(result, index, &re_spec,
  1086. re_unicode_tmp, i_re, i_re + n_re_digits,
  1087. NULL, 0,
  1088. 0,
  1089. &locale, 0);
  1090. if (err) {
  1091. Py_CLEAR(result);
  1092. goto done;
  1093. }
  1094. index += n_re_total;
  1095. }
  1096. err = fill_number(result, index, &im_spec,
  1097. im_unicode_tmp, i_im, i_im + n_im_digits,
  1098. NULL, 0,
  1099. 0,
  1100. &locale, 0);
  1101. if (err) {
  1102. Py_CLEAR(result);
  1103. goto done;
  1104. }
  1105. index += n_im_total;
  1106. PyUnicode_WRITE(rkind, rdata, index++, 'j');
  1107. if (add_parens)
  1108. PyUnicode_WRITE(rkind, rdata, index++, ')');
  1109. done:
  1110. PyMem_Free(re_buf);
  1111. PyMem_Free(im_buf);
  1112. Py_XDECREF(re_unicode_tmp);
  1113. Py_XDECREF(im_unicode_tmp);
  1114. return result;
  1115. }
  1116. /************************************************************************/
  1117. /*********** built in formatters ****************************************/
  1118. /************************************************************************/
  1119. PyObject *
  1120. _PyUnicode_FormatAdvanced(PyObject *obj,
  1121. PyObject *format_spec,
  1122. Py_ssize_t start, Py_ssize_t end)
  1123. {
  1124. InternalFormatSpec format;
  1125. PyObject *result;
  1126. /* check for the special case of zero length format spec, make
  1127. it equivalent to str(obj) */
  1128. if (start == end)
  1129. return PyObject_Str(obj);
  1130. /* parse the format_spec */
  1131. if (!parse_internal_render_format_spec(format_spec, start, end,
  1132. &format, 's', '<'))
  1133. return NULL;
  1134. /* type conversion? */
  1135. switch (format.type) {
  1136. case 's':
  1137. /* no type conversion needed, already a string. do the formatting */
  1138. result = format_string_internal(obj, &format);
  1139. if (result != NULL)
  1140. assert(_PyUnicode_CheckConsistency(result, 1));
  1141. break;
  1142. default:
  1143. /* unknown */
  1144. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  1145. result = NULL;
  1146. }
  1147. return result;
  1148. }
  1149. static PyObject*
  1150. format_int_or_long(PyObject* obj, PyObject* format_spec,
  1151. Py_ssize_t start, Py_ssize_t end,
  1152. IntOrLongToString tostring)
  1153. {
  1154. PyObject *result = NULL;
  1155. PyObject *tmp = NULL;
  1156. InternalFormatSpec format;
  1157. /* check for the special case of zero length format spec, make
  1158. it equivalent to str(obj) */
  1159. if (start == end) {
  1160. result = PyObject_Str(obj);
  1161. goto done;
  1162. }
  1163. /* parse the format_spec */
  1164. if (!parse_internal_render_format_spec(format_spec, start, end,
  1165. &format, 'd', '>'))
  1166. goto done;
  1167. /* type conversion? */
  1168. switch (format.type) {
  1169. case 'b':
  1170. case 'c':
  1171. case 'd':
  1172. case 'o':
  1173. case 'x':
  1174. case 'X':
  1175. case 'n':
  1176. /* no type conversion needed, already an int (or long). do
  1177. the formatting */
  1178. result = format_int_or_long_internal(obj, &format, tostring);
  1179. break;
  1180. case 'e':
  1181. case 'E':
  1182. case 'f':
  1183. case 'F':
  1184. case 'g':
  1185. case 'G':
  1186. case '%':
  1187. /* convert to float */
  1188. tmp = PyNumber_Float(obj);
  1189. if (tmp == NULL)
  1190. goto done;
  1191. result = format_float_internal(tmp, &format);
  1192. break;
  1193. default:
  1194. /* unknown */
  1195. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  1196. goto done;
  1197. }
  1198. done:
  1199. Py_XDECREF(tmp);
  1200. return result;
  1201. }
  1202. /* Need to define long_format as a function that will convert a long
  1203. to a string. In 3.0, _PyLong_Format has the correct signature. */
  1204. #define long_format _PyLong_Format
  1205. PyObject *
  1206. _PyLong_FormatAdvanced(PyObject *obj,
  1207. PyObject *format_spec,
  1208. Py_ssize_t start, Py_ssize_t end)
  1209. {
  1210. return format_int_or_long(obj, format_spec, start, end,
  1211. long_format);
  1212. }
  1213. PyObject *
  1214. _PyFloat_FormatAdvanced(PyObject *obj,
  1215. PyObject *format_spec,
  1216. Py_ssize_t start, Py_ssize_t end)
  1217. {
  1218. PyObject *result = NULL;
  1219. InternalFormatSpec format;
  1220. /* check for the special case of zero length format spec, make
  1221. it equivalent to str(obj) */
  1222. if (start == end) {
  1223. result = PyObject_Str(obj);
  1224. goto done;
  1225. }
  1226. /* parse the format_spec */
  1227. if (!parse_internal_render_format_spec(format_spec, start, end,
  1228. &format, '\0', '>'))
  1229. goto done;
  1230. /* type conversion? */
  1231. switch (format.type) {
  1232. case '\0': /* No format code: like 'g', but with at least one decimal. */
  1233. case 'e':
  1234. case 'E':
  1235. case 'f':
  1236. case 'F':
  1237. case 'g':
  1238. case 'G':
  1239. case 'n':
  1240. case '%':
  1241. /* no conversion, already a float. do the formatting */
  1242. result = format_float_internal(obj, &format);
  1243. break;
  1244. default:
  1245. /* unknown */
  1246. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  1247. goto done;
  1248. }
  1249. done:
  1250. return result;
  1251. }
  1252. PyObject *
  1253. _PyComplex_FormatAdvanced(PyObject *obj,
  1254. PyObject *format_spec,
  1255. Py_ssize_t start, Py_ssize_t end)
  1256. {
  1257. PyObject *result = NULL;
  1258. InternalFormatSpec format;
  1259. /* check for the special case of zero length format spec, make
  1260. it equivalent to str(obj) */
  1261. if (start == end) {
  1262. result = PyObject_Str(obj);
  1263. goto done;
  1264. }
  1265. /* parse the format_spec */
  1266. if (!parse_internal_render_format_spec(format_spec, start, end,
  1267. &format, '\0', '>'))
  1268. goto done;
  1269. /* type conversion? */
  1270. switch (format.type) {
  1271. case '\0': /* No format code: like 'g', but with at least one decimal. */
  1272. case 'e':
  1273. case 'E':
  1274. case 'f':
  1275. case 'F':
  1276. case 'g':
  1277. case 'G':
  1278. case 'n':
  1279. /* no conversion, already a complex. do the formatting */
  1280. result = format_complex_internal(obj, &format);
  1281. break;
  1282. default:
  1283. /* unknown */
  1284. unknown_presentation_type(format.type, obj->ob_type->tp_name);
  1285. goto done;
  1286. }
  1287. done:
  1288. return result;
  1289. }