Debian Codegraph @

pypy/objspace/std/newformat.py

raw symbols SCIP
1 """The unicode/str format() method"""
2
3 import math
4 import sys
5 import string
6
7 from pypy.interpreter.error import OperationError, oefmt
8 from rpython.rlib import rstring, rlocale, rfloat, jit, rutf8
9 from rpython.rlib.objectmodel import specialize
10 from rpython.rlib.rfloat import formatd
11 from rpython.rlib.rarithmetic import r_uint, intmask
12 from pypy.interpreter.signature import Signature
13
14 @specialize.argtype(1)
15 @jit.elidable
16 def _parse_int(space, s, start, end):
17 """Parse a number and check for overflows"""
18 result = 0
19 i = start
20 while i < end:
21 digit = ord(s[i]) - ord('0')
22 if 0 <= digit <= 9:
23 if result > (sys.maxint - digit) / 10:
24 raise oefmt(space.w_ValueError,
25 "too many decimal digits in format string")
26 result = result * 10 + digit
27 else:
28 break
29 i += 1
30 if i == start:
31 result = -1
32 return result, i
33
34
35 # Auto number state
36 ANS_INIT = 1
37 ANS_AUTO = 2
38 ANS_MANUAL = 3
39
40
41 format_signature = Signature([], 'args', 'kwargs')
42
43
44 def make_template_formatting_class(for_unicode):
45 class TemplateFormatter(object):
46 is_unicode = for_unicode
47
48 if for_unicode:
49 def wrap(self, u):
50 lgt = rutf8.check_utf8(u, True)
51 return self.space.newutf8(u, lgt)
52 else:
53 def wrap(self, s):
54 return self.space.newbytes(s)
55
56 parser_list_w = None
57
58 def __init__(self, space, template):
59 self.space = space
60 self.template = template
61
62 def build(self, args, w_kwargs):
63 self.args = args
64 self.w_kwargs = w_kwargs
65 self.auto_numbering = 0
66 self.auto_numbering_state = ANS_INIT
67 return self._build_string(0, len(self.template), 2)
68
69 def _build_string(self, start, end, level):
70 space = self.space
71 out = rstring.StringBuilder()
72 if not level:
73 raise oefmt(space.w_ValueError, "Recursion depth exceeded")
74 level -= 1
75 s = self.template
76 return self._do_build_string(start, end, level, out, s)
77
78 @jit.look_inside_iff(lambda self, start, end, level, out, s: jit.isconstant(s))
79 def _do_build_string(self, start, end, level, out, s):
80 space = self.space
81 last_literal = i = start
82 while i < end:
83 c = s[i]
84 i += 1
85 if c == "{" or c == "}":
86 at_end = i == end
87 # Find escaped "{" and "}"
88 markup_follows = True
89 if c == "}":
90 if at_end or s[i] != "}":
91 raise oefmt(space.w_ValueError, "Single '}' encountered in format string")
92 i += 1
93 markup_follows = False
94 if c == "{":
95 if at_end:
96 raise oefmt(space.w_ValueError, "Single '{' encountered in format string")
97 if s[i] == "{":
98 i += 1
99 markup_follows = False
100 # Attach literal data, ending with { or }
101 out.append_slice(s, last_literal, i - 1)
102 if not markup_follows:
103 if self.parser_list_w is not None:
104 end_literal = i - 1
105 assert end_literal > last_literal
106 literal = self.template[last_literal:end_literal]
107 w_entry = space.newtuple([
108 self.wrap(literal),
109 space.w_None, space.w_None, space.w_None])
110 self.parser_list_w.append(w_entry)
111 self.last_end = i
112 last_literal = i
113 continue
114 nested = 1
115 field_start = i
116 recursive = False
117 in_second_part = False
118 while i < end:
119 c = s[i]
120 if c == "{":
121 recursive = True
122 nested += 1
123 elif c == "}":
124 nested -= 1
125 if not nested:
126 break
127 elif c == "[" and not in_second_part:
128 i += 1
129 while i < end and s[i] != "]":
130 i += 1
131 continue
132 elif c == ':' or c == '!':
133 in_second_part = True
134 i += 1
135 if nested:
136 raise oefmt(space.w_ValueError, "expected '}' before end of string")
137 rendered = self._render_field(field_start, i, recursive, level)
138 out.append(rendered)
139 i += 1
140 last_literal = i
141
142 out.append_slice(s, last_literal, end)
143 return out.build()
144
145 # This is only ever called if we're already unrolling _do_build_string
146 @jit.unroll_safe
147 def _parse_field(self, start, end):
148 s = self.template
149 # Find ":" or "!"
150 i = start
151 while i < end:
152 c = s[i]
153 if c == ":" or c == "!":
154 end_name = i
155 if c == "!":
156 i += 1
157 if i == end:
158 raise oefmt(self.space.w_ValueError,
159 "end of string while looking for "
160 "conversion specifier")
161 conversion = s[i]
162 i += 1
163 if i < end:
164 if s[i] != ':':
165 raise oefmt(self.space.w_ValueError,
166 "expected ':' after conversion "
167 "specifier")
168 i += 1
169 else:
170 conversion = None
171 i += 1
172 return s[start:end_name], conversion, i
173 elif c == "[":
174 while i + 1 < end and s[i + 1] != "]":
175 i += 1
176 elif c == "{":
177 raise oefmt(self.space.w_ValueError,
178 "unexpected '{' in field name")
179 i += 1
180 return s[start:end], None, end
181
182 @jit.unroll_safe
183 def _get_argument(self, name):
184 # First, find the argument.
185 space = self.space
186 i = 0
187 end = len(name)
188 while i < end:
189 c = name[i]
190 if c == "[" or c == ".":
191 break
192 i += 1
193 empty = not i
194 if empty:
195 index = -1
196 else:
197 index, stop = _parse_int(self.space, name, 0, i)
198 if stop != i:
199 index = -1
200 use_numeric = empty or index != -1
201 if self.auto_numbering_state == ANS_INIT and use_numeric:
202 if empty:
203 self.auto_numbering_state = ANS_AUTO
204 else:
205 self.auto_numbering_state = ANS_MANUAL
206 if use_numeric:
207 if self.auto_numbering_state == ANS_MANUAL:
208 if empty:
209 raise oefmt(space.w_ValueError,
210 "switching from manual to automatic "
211 "numbering")
212 elif not empty:
213 raise oefmt(space.w_ValueError,
214 "switching from automatic to manual numbering")
215 if empty:
216 index = self.auto_numbering
217 self.auto_numbering += 1
218 if index == -1:
219 kwarg = name[:i]
220 if self.is_unicode:
221 w_kwarg = space.newtext(kwarg)
222 else:
223 w_kwarg = space.newbytes(kwarg)
224 w_arg = space.getitem(self.w_kwargs, w_kwarg)
225 else:
226 if self.args is None:
227 raise oefmt(space.w_ValueError,
228 "Format string contains positional fields")
229 try:
230 w_arg = self.args[index]
231 except IndexError:
232 raise oefmt(space.w_IndexError,
233 "out of range: index %d but only %d argument%s",
234 index, len(self.args),
235 "s" if len(self.args) != 1 else "")
236 return self._resolve_lookups(w_arg, name, i, end)
237
238 @jit.unroll_safe
239 def _resolve_lookups(self, w_obj, name, start, end):
240 # Resolve attribute and item lookups.
241 space = self.space
242 i = start
243 while i < end:
244 c = name[i]
245 if c == ".":
246 i += 1
247 start = i
248 while i < end:
249 c = name[i]
250 if c == "[" or c == ".":
251 break
252 i += 1
253 if start == i:
254 raise oefmt(space.w_ValueError,
255 "Empty attribute in format string")
256 w_attr = self.wrap(name[start:i])
257 if w_obj is not None:
258 w_obj = space.getattr(w_obj, w_attr)
259 else:
260 self.parser_list_w.append(space.newtuple2(
261 space.w_True, w_attr))
262 elif c == "[":
263 got_bracket = False
264 i += 1
265 start = i
266 while i < end:
267 c = name[i]
268 if c == "]":
269 got_bracket = True
270 break
271 i += 1
272 if not got_bracket:
273 raise oefmt(space.w_ValueError, "Missing ']'")
274 index, reached = _parse_int(self.space, name, start, i)
275 if index != -1 and reached == i:
276 w_item = space.newint(index)
277 else:
278 w_item = self.wrap(name[start:i])
279 i += 1 # Skip "]"
280 if w_obj is not None:
281 w_obj = space.getitem(w_obj, w_item)
282 else:
283 self.parser_list_w.append(space.newtuple2(
284 space.w_False, w_item))
285 else:
286 raise oefmt(space.w_ValueError,
287 "Only '[' and '.' may follow ']'")
288 return w_obj
289
290 def formatter_field_name_split(self):
291 space = self.space
292 name = self.template
293 i = 0
294 end = len(name)
295 while i < end:
296 c = name[i]
297 if c == "[" or c == ".":
298 break
299 i += 1
300 if i == 0:
301 index = -1
302 else:
303 index, stop = _parse_int(self.space, name, 0, i)
304 if stop != i:
305 index = -1
306 if index >= 0:
307 w_first = space.newint(index)
308 else:
309 w_first = self.wrap(name[:i])
310 #
311 self.parser_list_w = []
312 self._resolve_lookups(None, name, i, end)
313 #
314 return space.newtuple2(w_first,
315 space.iter(space.newlist(self.parser_list_w)))
316
317 def _convert(self, w_obj, conversion):
318 space = self.space
319 conv = conversion[0]
320 if conv == "r":
321 return space.repr(w_obj)
322 elif conv == "s":
323 if self.is_unicode:
324 return space.call_function(space.w_unicode, w_obj)
325 return space.str(w_obj)
326 elif conv == "a":
327 from pypy.objspace.std.unicodeobject import ascii_from_object
328 return ascii_from_object(space, w_obj)
329 else:
330 raise oefmt(space.w_ValueError, "invalid conversion")
331
332 def _render_field(self, start, end, recursive, level):
333 name, conversion, spec_start = self._parse_field(start, end)
334 spec = self.template[spec_start:end]
335 #
336 if self.parser_list_w is not None:
337 # used from formatter_parser()
338 if level == 1: # ignore recursive calls
339 space = self.space
340 startm1 = start - 1
341 assert startm1 >= self.last_end
342 if conversion is None:
343 w_conversion = space.w_None
344 else:
345 w_conversion = self.wrap(conversion)
346 w_entry = space.newtuple([
347 self.wrap(self.template[self.last_end:startm1]),
348 self.wrap(name),
349 self.wrap(spec),
350 w_conversion])
351 self.parser_list_w.append(w_entry)
352 self.last_end = end + 1
353 return ""
354 #
355 w_obj = self._get_argument(name)
356 if conversion is not None:
357 w_obj = self._convert(w_obj, conversion)
358 if recursive:
359 spec = self._build_string(spec_start, end, level)
360 w_rendered = self.space.format(w_obj, self.wrap(spec))
361 if self.is_unicode:
362 w_rendered = self.space.unicode_from_object(w_rendered)
363 return self.space.utf8_w(w_rendered)
364 else:
365 return self.space.bytes_w(w_rendered)
366
367 def formatter_parser(self):
368 self.parser_list_w = []
369 self.last_end = 0
370 self._build_string(0, len(self.template), 2)
371 #
372 space = self.space
373 if self.last_end < len(self.template):
374 w_lastentry = space.newtuple([
375 self.wrap(self.template[self.last_end:]),
376 space.w_None,
377 space.w_None,
378 space.w_None])
379 self.parser_list_w.append(w_lastentry)
380 return space.iter(space.newlist(self.parser_list_w))
381 return TemplateFormatter
382
383 str_template_formatter = make_template_formatting_class(for_unicode=False)
384 unicode_template_formatter = make_template_formatting_class(for_unicode=True)
385
386
387 def format_method(space, w_string, args, w_kwargs, is_unicode):
388 if is_unicode:
389 template = unicode_template_formatter(space,
390 space.utf8_w(w_string))
391 r = template.build(args, w_kwargs)
392 lgt = rutf8.check_utf8(r, True)
393 return space.newutf8(r, lgt)
394 else:
395 template = str_template_formatter(space, space.bytes_w(w_string))
396 return space.newbytes(template.build(args, w_kwargs))
397
398
399 class NumberSpec(object):
400 pass
401
402
403 class BaseFormatter(object):
404 def format_int_or_long(self, w_num, kind):
405 raise NotImplementedError
406
407 def format_float(self, w_num):
408 raise NotImplementedError
409
410 def format_complex(self, w_num):
411 raise NotImplementedError
412
413
414 INT_KIND = 1
415 LONG_KIND = 2
416
417 NO_LOCALE = 1
418 DEFAULT_LOCALE = 2
419 CURRENT_LOCALE = 3
420
421 LONG_DIGITS = string.digits + string.ascii_lowercase
422
423 def make_formatting_class(for_unicode):
424 class Formatter(BaseFormatter):
425 """__format__ implementation for builtin types."""
426
427 if for_unicode:
428 def wrap(self, u):
429 lgt = rutf8.check_utf8(u, True)
430 return self.space.newutf8(u, lgt)
431 else:
432 def wrap(self, s):
433 return self.space.newbytes(s)
434
435 is_unicode = for_unicode
436 _grouped_digits = None
437
438 def __init__(self, space, spec):
439 self.space = space
440 self.spec = spec
441 self.w_obj = space.w_None
442
443 def _is_alignment(self, c):
444 return (c == "<" or
445 c == ">" or
446 c == "=" or
447 c == "^")
448
449 def _is_sign(self, c):
450 return (c == " " or
451 c == "+" or
452 c == "-")
453
454 def _parse_spec(self, default_type, default_align):
455 space = self.space
456 self._fill_char = self._lit(" ")[0]
457 self._align = default_align
458 self._alternate = False
459 self._sign = "\0"
460 self._zeros = False # do we have the 3.11 z specifier
461 self._thousands_sep = "\0"
462 self._precision = -1
463 the_type = default_type
464 spec = self.spec
465 if not spec:
466 return True
467 length = len(spec)
468 i = 0
469 got_align = True
470 got_fill_char = False
471 # The single character could be utf8-encoded unicode
472 if self.is_unicode:
473 after_i = rutf8.next_codepoint_pos(spec, i)
474 else:
475 after_i = i + 1
476 if length - i >= 2 and self._is_alignment(spec[after_i]):
477 self._align = spec[after_i]
478 self._fill_char = spec[i:after_i]
479 got_fill_char = True
480 i = after_i + 1
481 elif length - i >= 1 and self._is_alignment(spec[i]):
482 self._align = spec[i]
483 i += 1
484 else:
485 got_align = False
486 if length - i >= 1 and self._is_sign(spec[i]):
487 self._sign = spec[i]
488 i += 1
489 if length - i >= 1 and spec[i] == 'z':
490 self._zeros = True
491 i += 1
492 if length - i >= 1 and spec[i] == "#":
493 self._alternate = True
494 i += 1
495 if not got_fill_char and length - i >= 1 and spec[i] == "0":
496 self._fill_char = self._lit("0")[0]
497 if not got_align and default_align == '>':
498 self._align = "="
499 i += 1
500 self._width, i = _parse_int(self.space, spec, i, length)
501 if length != i and spec[i] == ",":
502 self._thousands_sep = ","
503 i += 1
504 if length != i and spec[i] == "_":
505 if self._thousands_sep != "\0":
506 raise oefmt(
507 space.w_ValueError, "Cannot specify both ',' and '_'.")
508 self._thousands_sep = "_"
509 i += 1
510 if length != i and spec[i] == ",":
511 raise oefmt(
512 space.w_ValueError, "Cannot specify both ',' and '_'.")
513 if length != i and spec[i] == ".":
514 i += 1
515 self._precision, i = _parse_int(self.space, spec, i, length)
516 if self._precision == -1:
517 raise oefmt(space.w_ValueError, "no precision given")
518 if length - i > 1:
519 raise oefmt(space.w_ValueError, "Invalid format specifier '%8' for object of type '%T'", spec, self.w_obj)
520 if length - i == 1:
521 presentation_type = spec[i]
522 if self.is_unicode:
523 try:
524 rutf8.check_utf8(spec[i], True)
525 the_type = spec[i][0]
526 except rutf8.CheckError:
527 raise oefmt(space.w_ValueError,
528 "invalid presentation type")
529 else:
530 the_type = presentation_type
531 i += 1
532 self._type = the_type
533 if self._thousands_sep != "\0":
534 tp = self._type
535 if (tp == "d" or
536 tp == "e" or
537 tp == "f" or
538 tp == "g" or
539 tp == "E" or
540 tp == "G" or
541 tp == "%" or
542 tp == "F" or
543 tp == "\0"):
544 # ok
545 pass
546 elif self._thousands_sep == "_" and (
547 tp == "b" or
548 tp == "o" or
549 tp == "x" or
550 tp == "X"):
551 pass # ok
552 else:
553 raise oefmt(space.w_ValueError,
554 "Cannot specify '%s' with '%s'.",
555 self._thousands_sep, tp)
556 return False
557
558 def _calc_padding(self, string, length):
559 """compute left and right padding, return total width of string"""
560 if self._width != -1 and length < self._width:
561 total = self._width
562 else:
563 total = length
564 align = self._align
565 if align == ">":
566 left = total - length
567 elif align == "^":
568 left = (total - length) / 2
569 elif align == "<" or align == "=":
570 left = 0
571 else:
572 raise AssertionError("shouldn't be here")
573 right = total - length - left
574 self._left_pad = left
575 self._right_pad = right
576 return total
577
578 def _lit(self, s):
579 assert len(s) == 1
580 if self.is_unicode:
581 return rutf8.unichr_as_utf8(ord(s[0]))
582 else:
583 return s
584
585 def _pad(self, string):
586 builder = self._builder()
587 builder.append_multiple_char(self._fill_char, self._left_pad)
588 builder.append(string)
589 builder.append_multiple_char(self._fill_char, self._right_pad)
590 return builder.build()
591
592 def _builder(self):
593 if self.is_unicode:
594 return rutf8.Utf8StringBuilder()
595 else:
596 return rstring.StringBuilder()
597
598 def _unknown_presentation(self, w_val):
599 raise oefmt(self.space.w_ValueError,
600 "Unknown format code '%s' for object of type '%T'", self._type, w_val)
601
602 def format_string(self, w_string):
603 space = self.space
604 if not space.is_w(space.type(w_string), space.w_unicode):
605 w_string = space.str(w_string)
606 string = space.utf8_w(w_string)
607 if self._parse_spec("s", "<"):
608 return self.wrap(string)
609 if self._type != "s":
610 self._unknown_presentation(w_string)
611 if self._sign != "\0":
612 if self._sign == " ":
613 raise oefmt(space.w_ValueError,
614 "Space not allowed in string format specifier")
615 raise oefmt(space.w_ValueError,
616 "Sign not allowed in string format specifier")
617 if self._alternate:
618 raise oefmt(space.w_ValueError,
619 "Alternate form (#) not allowed in string format "
620 "specifier")
621 if self._align == "=":
622 raise oefmt(space.w_ValueError,
623 "'=' alignment not allowed in string format "
624 "specifier")
625 if self._zeros:
626 raise oefmt(space.w_ValueError, "Negative zero coercion (z) not allowed")
627 length = space.len_w(w_string)
628 precision = self._precision
629 if precision != -1 and length >= precision:
630 assert precision >= 0
631 length = precision
632 if for_unicode:
633 w_slice = space.newslice(
634 space.newint(0), space.newint(precision), space.w_None)
635 w_string = space.getitem(w_string, w_slice)
636 string = space.utf8_w(w_string)
637 else:
638 string = string[:precision]
639 self._calc_padding(string, length)
640 return self.wrap(self._pad(string))
641
642 def _get_locale(self, tp):
643 if tp == "n":
644 dec, thousands, grouping = rlocale.numeric_formatting()
645 elif self._thousands_sep != "\0":
646 thousands = self._thousands_sep
647 dec = "."
648 grouping = "\3"
649 if tp in "boxX":
650 assert self._thousands_sep == "_"
651 grouping = "\4"
652 else:
653 dec = "."
654 thousands = ""
655 grouping = "\xFF" # special value to mean 'stop'
656 self._loc_dec = dec
657 self._loc_thousands = thousands
658 self._loc_grouping = grouping
659
660 def _calc_num_width(self, n_prefix, sign_char, to_number, n_number,
661 n_remainder, has_dec, digits):
662 """Calculate widths of all parts of formatted number.
663
664 Output will look like:
665
666 <lpadding> <sign> <prefix> <spadding> <grouped_digits> <decimal>
667 <remainder> <rpadding>
668
669 sign is computed from self._sign, and the sign of the number
670 prefix is given
671 digits is known
672 """
673 spec = NumberSpec()
674 spec.n_digits = n_number - n_remainder - has_dec
675 spec.n_prefix = n_prefix
676 spec.n_lpadding = 0
677 spec.n_decimal = int(has_dec)
678 spec.n_remainder = n_remainder
679 spec.n_spadding = 0
680 spec.n_rpadding = 0
681 spec.n_min_width = 0
682 spec.n_total = 0
683 spec.sign = "\0"
684 spec.n_sign = 0
685 sign = self._sign
686 if sign == "+":
687 spec.n_sign = 1
688 spec.sign = "-" if sign_char == "-" else "+"
689 elif sign == " ":
690 spec.n_sign = 1
691 spec.sign = "-" if sign_char == "-" else " "
692 elif sign_char == "-":
693 spec.n_sign = 1
694 spec.sign = "-"
695 extra_length = (spec.n_sign + spec.n_prefix + spec.n_decimal +
696 spec.n_remainder) # Not padding or digits
697 if self._fill_char == "0" and self._align == "=":
698 spec.n_min_width = self._width - extra_length
699 if self._loc_thousands and spec.n_digits:
700 self._grouped_digits = self._group_digits(digits[to_number:],
701 spec.n_min_width,
702 spec.n_digits,
703 self._loc_grouping,
704 self._loc_thousands)
705 n_grouped_digits = len(self._grouped_digits)
706 else:
707 n_grouped_digits = spec.n_digits
708 n_padding = self._width - (extra_length + n_grouped_digits)
709 if n_padding > 0:
710 align = self._align
711 if align == "<":
712 spec.n_rpadding = n_padding
713 elif align == ">":
714 spec.n_lpadding = n_padding
715 elif align == "^":
716 spec.n_lpadding = n_padding // 2
717 spec.n_rpadding = n_padding - spec.n_lpadding
718 elif align == "=":
719 spec.n_spadding = n_padding
720 else:
721 raise AssertionError("shouldn't reach")
722 spec.n_total = spec.n_lpadding + spec.n_sign + spec.n_prefix + \
723 spec.n_spadding + n_grouped_digits + \
724 spec.n_decimal + spec.n_remainder + spec.n_rpadding
725 return spec
726
727 @staticmethod
728 @jit.elidable
729 def _fill_digits(buf, digits, d_state, n_chars, n_zeros,
730 thousands_sep):
731 if thousands_sep:
732 buf.append(thousands_sep)
733 for i in range(d_state - 1, d_state - n_chars - 1, -1):
734 buf.append(digits[i])
735 for i in range(n_zeros):
736 buf.append("0")
737
738 @staticmethod
739 @jit.elidable
740 def _group_digits(digits, min_width, left, loc_grouping, loc_thousands):
741 buf = []
742 grouping = loc_grouping
743 grouping_state = 0
744 n_ts = rutf8.codepoints_in_utf8(loc_thousands)
745 need_separator = False
746 done = False
747 previous = 0
748 while True:
749 if grouping_state >= len(grouping):
750 group = previous # end of string
751 else:
752 # else, get the next value from the string
753 group = ord(grouping[grouping_state])
754 if group == 0xFF: # special value to mean 'stop'
755 break
756 grouping_state += 1
757 previous = group
758 #
759 final_grouping = min(group, max(left, max(min_width, 1)))
760 n_zeros = max(0, final_grouping - left)
761 n_chars = max(0, min(left, final_grouping))
762 ts = loc_thousands if need_separator else None
763 Formatter._fill_digits(buf, digits, left, n_chars, n_zeros, ts)
764 need_separator = True
765 left -= n_chars
766 min_width -= final_grouping
767 if left <= 0 and min_width <= 0:
768 done = True
769 break
770 min_width -= n_ts
771 if not done:
772 group = max(max(left, min_width), 1)
773 n_zeros = max(0, group - left)
774 n_chars = max(0, min(left, group))
775 ts = loc_thousands if need_separator else None
776 Formatter._fill_digits(buf, digits, left, n_chars, n_zeros, ts)
777 buf.reverse()
778 return "".join(buf)
779
780 def _upcase_string(self, s):
781 return s.upper()
782
783 def _fill_number(self, spec, num, to_digits, to_prefix, fill_char,
784 to_remainder, upper, grouped_digits=None):
785 out = self._builder()
786 if spec.n_lpadding:
787 out.append_multiple_char(fill_char, spec.n_lpadding)
788 if spec.n_sign:
789 sign = self._lit(spec.sign)
790 out.append(sign)
791 if spec.n_prefix:
792 pref = num[to_prefix:to_prefix + spec.n_prefix]
793 if upper:
794 pref = self._upcase_string(pref)
795 out.append(pref)
796 if spec.n_spadding:
797 out.append_multiple_char(fill_char, spec.n_spadding)
798 if spec.n_digits != 0:
799 if self._loc_thousands:
800 if grouped_digits is not None:
801 digits = grouped_digits
802 else:
803 digits = self._grouped_digits
804 assert digits is not None
805 else:
806 stop = to_digits + spec.n_digits
807 assert stop >= 0
808 digits = num[to_digits:stop]
809 if upper:
810 digits = self._upcase_string(digits)
811 out.append(digits)
812 if spec.n_decimal:
813 out.append(self._lit(self._loc_dec)[0])
814 if spec.n_remainder:
815 out.append(num[to_remainder:])
816 if spec.n_rpadding:
817 out.append_multiple_char(fill_char, spec.n_rpadding)
818 #if complex, need to call twice - just retun the buffer
819 return out.build()
820
821 def _format_int_or_long(self, w_num, kind):
822 space = self.space
823 if self._precision != -1:
824 raise oefmt(space.w_ValueError,
825 "Precision not allowed in integer format specifier")
826 if self.spec == 'z':
827 raise oefmt(space.w_ValueError,
828 "Negative zero coercion (z) not allowed in integer"
829 " format specifier")
830 sign_char = "\0"
831 tp = self._type
832 if tp == "c":
833 if self._sign != "\0":
834 raise oefmt(space.w_ValueError,
835 "Sign not allowed with integer format specifier 'c'")
836 if self._alternate:
837 raise oefmt(space.w_ValueError,
838 "Alternate form (#) not allowed "
839 "with 'c' presentation type")
840 value = space.int_w(w_num)
841 max_char = 0x10FFFF if self.is_unicode else 0xFF
842 if not (0 <= value <= max_char):
843 raise oefmt(space.w_OverflowError,
844 "%%c arg not in range(%s)",
845 hex(max_char))
846 if self.is_unicode:
847 result = rutf8.unichr_as_utf8(value)
848 else:
849 result = chr(value)
850 n_digits = 1
851 n_remainder = 1
852 to_remainder = 0
853 n_prefix = 0
854 to_prefix = 0
855 to_numeric = 0
856 else:
857 if tp == "b":
858 base = 2
859 skip_leading = 2
860 elif tp == "o":
861 base = 8
862 skip_leading = 2
863 elif tp == "x" or tp == "X":
864 base = 16
865 skip_leading = 2
866 elif tp == "n" or tp == "d":
867 base = 10
868 skip_leading = 0
869 else:
870 raise AssertionError("shouldn't reach")
871 if kind == INT_KIND:
872 result = self._int_to_base(base, space.int_w(w_num))
873 else:
874 result = self._long_to_base(base, space.bigint_w(w_num))
875 n_prefix = skip_leading if self._alternate else 0
876 to_prefix = 0
877 if result[0] == "-":
878 sign_char = "-"
879 skip_leading += 1
880 to_prefix += 1
881 n_digits = len(result) - skip_leading
882 n_remainder = 0
883 to_remainder = 0
884 to_numeric = skip_leading
885 self._get_locale(tp)
886 spec = self._calc_num_width(n_prefix, sign_char, to_numeric, n_digits,
887 n_remainder, False, result)
888 fill = self._fill_char
889 upper = self._type == "X"
890 return self.wrap(self._fill_number(spec, result, to_numeric,
891 to_prefix, fill, to_remainder, upper))
892
893 def _long_to_base(self, base, value):
894 prefix = ""
895 if base == 2:
896 prefix = "0b"
897 elif base == 8:
898 prefix = "0o"
899 elif base == 16:
900 prefix = "0x"
901 as_str = value.format(LONG_DIGITS[:base], prefix)
902 if self.is_unicode:
903 return rutf8.decode_latin_1(as_str)
904 return as_str
905
906 @staticmethod
907 @jit.elidable
908 def _int_to_base(base, value):
909 if base == 10:
910 return str(value)
911 # This part is slow.
912 negative = value < 0
913 base = r_uint(base)
914 value = r_uint(value)
915 if negative: # change the sign on the unsigned number: otherwise,
916 value = -value # we'd risk overflow if value==-sys.maxint-1
917 #
918 buf = ["\0"] * (8 * 8 + 6) # Too much on 32 bit, but who cares?
919 i = len(buf) - 1
920 while True:
921 div = value // base # unsigned
922 mod = value - div * base # unsigned, always in range(0,base)
923 digit = intmask(mod)
924 digit += ord("0") if digit < 10 else ord("a") - 10
925 buf[i] = chr(digit)
926 value = div # unsigned
927 i -= 1
928 if not value:
929 break
930 if base == r_uint(2):
931 buf[i] = "b"
932 buf[i - 1] = "0"
933 elif base == r_uint(8):
934 buf[i] = "o"
935 buf[i - 1] = "0"
936 elif base == r_uint(16):
937 buf[i] = "x"
938 buf[i - 1] = "0"
939 else:
940 buf[i] = "#"
941 buf[i - 1] = chr(ord("0") + intmask(base % r_uint(10)))
942 if base > r_uint(10):
943 buf[i - 2] = chr(ord("0") + intmask(base // r_uint(10)))
944 i -= 1
945 i -= 1
946 if negative:
947 i -= 1
948 buf[i] = "-"
949 assert i >= 0
950 return "".join(buf[i:])
951
952 def format_int_or_long(self, w_num, kind):
953 space = self.space
954 if self._parse_spec("d", ">"):
955 if self.is_unicode:
956 return space.call_function(space.w_unicode, w_num)
957 return self.space.str(w_num)
958 tp = self._type
959 if (tp == "b" or
960 tp == "c" or
961 tp == "d" or
962 tp == "o" or
963 tp == "x" or
964 tp == "X" or
965 tp == "n"):
966 if self._zeros:
967 raise oefmt(space.w_ValueError, "Negative zero coercion (z) not allowed")
968 return self._format_int_or_long(w_num, kind)
969 elif (tp == "e" or
970 tp == "E" or
971 tp == "f" or
972 tp == "F" or
973 tp == "g" or
974 tp == "G" or
975 tp == "%"):
976 w_float = space.float(w_num)
977 return self._format_float(w_float)
978 else:
979 self._unknown_presentation(w_num)
980
981 def _parse_number(self, s, i):
982 """Determine if s has a decimal point, and the index of the first #
983 after the decimal, or the end of the number."""
984 length = len(s)
985 while i < length and "0" <= s[i] <= "9":
986 i += 1
987 rest = i
988 dec_point = i < length and s[i] == "."
989 if dec_point:
990 rest += 1
991 #differs from CPython method - CPython sets n_remainder
992 return dec_point, rest
993
994 def _format_float(self, w_float):
995 """helper for format_float"""
996 space = self.space
997 flags = 0
998 default_precision = 6
999 if self._alternate:
1000 flags |= rfloat.DTSF_ALT
1001 if self._zeros:
1002 flags |= rfloat.DTSF_NO_NEG_0
1003
1004 tp = self._type
1005 self._get_locale(tp)
1006 if tp == "\0":
1007 flags |= rfloat.DTSF_ADD_DOT_0
1008 tp = "r"
1009 default_precision = 0
1010 elif tp == "n":
1011 tp = "g"
1012 value = space.float_w(w_float)
1013 if tp == "%":
1014 tp = "f"
1015 value *= 100
1016 add_pct = True
1017 else:
1018 add_pct = False
1019 if self._precision == -1:
1020 self._precision = default_precision
1021 elif tp == "r":
1022 tp = "g"
1023 result, special = rfloat.double_to_string(value, tp,
1024 self._precision, flags)
1025 if add_pct:
1026 result += "%"
1027 n_digits = len(result)
1028 if result[0] == "-":
1029 sign = "-"
1030 to_number = 1
1031 n_digits -= 1
1032 else:
1033 sign = "\0"
1034 to_number = 0
1035 have_dec_point, to_remainder = self._parse_number(result, to_number)
1036 n_remainder = len(result) - to_remainder
1037 if self.is_unicode:
1038 digits = rutf8.decode_latin_1(result)
1039 else:
1040 digits = result
1041 spec = self._calc_num_width(0, sign, to_number, n_digits,
1042 n_remainder, have_dec_point, digits)
1043 fill = self._fill_char
1044 return self.wrap(self._fill_number(spec, digits, to_number, 0,
1045 fill, to_remainder, False))
1046
1047 def format_float(self, w_float):
1048 space = self.space
1049 if self._parse_spec("\0", ">"):
1050 if self.is_unicode:
1051 return space.call_function(space.w_unicode, w_float)
1052 return space.str(w_float)
1053 tp = self._type
1054 if (tp == "\0" or
1055 tp == "e" or
1056 tp == "E" or
1057 tp == "f" or
1058 tp == "F" or
1059 tp == "g" or
1060 tp == "G" or
1061 tp == "n" or
1062 tp == "%"):
1063 return self._format_float(w_float)
1064 self._unknown_presentation(w_float)
1065
1066 def _format_complex(self, w_complex):
1067 flags = 0
1068 space = self.space
1069 tp = self._type
1070 self._get_locale(tp)
1071 default_precision = 6
1072 if self._align == "=":
1073 # '=' alignment is invalid
1074 raise oefmt(space.w_ValueError,
1075 "'=' alignment flag is not allowed in complex "
1076 "format specifier")
1077 if self._fill_char == "0":
1078 # zero padding is invalid
1079 raise oefmt(space.w_ValueError,
1080 "Zero padding is not allowed in complex format "
1081 "specifier")
1082 if self._alternate:
1083 flags |= rfloat.DTSF_ALT
1084 if self._zeros:
1085 flags |= rfloat.DTSF_NO_NEG_0
1086
1087 skip_re = 0
1088 add_parens = 0
1089 if tp == "\0":
1090 #should mirror str() output
1091 tp = "r"
1092 default_precision = 0
1093 #test if real part is non-zero
1094 if (w_complex.realval == 0 and
1095 math.copysign(1., w_complex.realval) == 1.):
1096 skip_re = 1
1097 else:
1098 add_parens = 1
1099
1100 if tp == "n":
1101 #same as 'g' except for locale, taken care of later
1102 tp = "g"
1103
1104 #check if precision not set
1105 if self._precision == -1:
1106 self._precision = default_precision
1107 elif tp == "r":
1108 tp = "g"
1109
1110 #in CPython it's named 're' - clashes with re module
1111 re_num, special = rfloat.double_to_string(w_complex.realval, tp, self._precision, flags)
1112 im_num, special = rfloat.double_to_string(w_complex.imagval, tp, self._precision, flags)
1113 n_re_digits = len(re_num)
1114 n_im_digits = len(im_num)
1115
1116 to_real_number = 0
1117 to_imag_number = 0
1118 re_sign = im_sign = ''
1119 #if a sign character is in the output, remember it and skip
1120 if re_num[0] == "-":
1121 re_sign = "-"
1122 to_real_number = 1
1123 n_re_digits -= 1
1124 if im_num[0] == "-":
1125 im_sign = "-"
1126 to_imag_number = 1
1127 n_im_digits -= 1
1128
1129 #turn off padding - do it after number composition
1130 #calc_num_width uses self._width, so assign to temporary variable,
1131 #calculate width of real and imag parts, then reassign padding, align
1132 tmp_fill_char = self._fill_char
1133 tmp_align = self._align
1134 tmp_width = self._width
1135 self._fill_char = "\0"
1136 self._align = "<"
1137 self._width = -1
1138
1139 #determine if we have remainder, might include dec or exponent or both
1140 re_have_dec, re_remainder_ptr = self._parse_number(re_num,
1141 to_real_number)
1142 im_have_dec, im_remainder_ptr = self._parse_number(im_num,
1143 to_imag_number)
1144
1145 if self.is_unicode:
1146 re_num = rutf8.decode_latin_1(re_num)
1147 im_num = rutf8.decode_latin_1(im_num)
1148
1149 #set remainder, in CPython _parse_number sets this
1150 #using n_re_digits causes tests to fail
1151 re_n_remainder = len(re_num) - re_remainder_ptr
1152 im_n_remainder = len(im_num) - im_remainder_ptr
1153 re_spec = self._calc_num_width(0, re_sign, to_real_number, n_re_digits,
1154 re_n_remainder, re_have_dec,
1155 re_num)
1156
1157 #capture grouped digits b/c _fill_number reads from self._grouped_digits
1158 #self._grouped_digits will get overwritten in imaginary calc_num_width
1159 re_grouped_digits = self._grouped_digits
1160 if not skip_re:
1161 self._sign = "+"
1162 im_spec = self._calc_num_width(0, im_sign, to_imag_number, n_im_digits,
1163 im_n_remainder, im_have_dec,
1164 im_num)
1165
1166 im_grouped_digits = self._grouped_digits
1167 if skip_re:
1168 re_spec.n_total = 0
1169
1170 #reassign width, alignment, fill character
1171 self._align = tmp_align
1172 self._width = tmp_width
1173 self._fill_char = tmp_fill_char
1174
1175 #compute L and R padding - stored in self._left_pad and self._right_pad
1176 self._calc_padding("", re_spec.n_total + im_spec.n_total + 1 +
1177 add_parens * 2)
1178
1179 out = self._builder()
1180 fill = self._fill_char
1181
1182 #compose the string
1183 #add left padding
1184 out.append_multiple_char(fill, self._left_pad)
1185 if add_parens:
1186 out.append(self._lit('(')[0])
1187
1188 #if the no. has a real component, add it
1189 if not skip_re:
1190 out.append(self._fill_number(re_spec, re_num, to_real_number, 0,
1191 fill, re_remainder_ptr, False,
1192 re_grouped_digits))
1193
1194 #add imaginary component
1195 out.append(self._fill_number(im_spec, im_num, to_imag_number, 0,
1196 fill, im_remainder_ptr, False,
1197 im_grouped_digits))
1198
1199 #add 'j' character
1200 out.append(self._lit('j')[0])
1201
1202 if add_parens:
1203 out.append(self._lit(')')[0])
1204
1205 #add right padding
1206 out.append_multiple_char(fill, self._right_pad)
1207
1208 return self.wrap(out.build())
1209
1210
1211 def format_complex(self, w_complex):
1212 """return the string representation of a complex number"""
1213 space = self.space
1214 #parse format specification, set associated variables
1215 if self._parse_spec("\0", ">"):
1216 return space.str(w_complex)
1217 tp = self._type
1218 if (tp == "\0" or
1219 tp == "e" or
1220 tp == "E" or
1221 tp == "f" or
1222 tp == "F" or
1223 tp == "g" or
1224 tp == "G" or
1225 tp == "n"):
1226 return self._format_complex(w_complex)
1227 self._unknown_presentation(w_complex)
1228 return Formatter
1229
1230 unicode_formatter = make_formatting_class(for_unicode=True)
1231
1232
1233 @specialize.arg(2)
1234 def run_formatter(space, w_format_spec, meth, w_obj, *args):
1235 formatter = unicode_formatter(space, space.utf8_w(w_format_spec))
1236 formatter.w_obj = w_obj
1237 return getattr(formatter, meth)(w_obj, *args)