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.

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