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.

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