Debian Codegraph @

pypy/objspace/std/formatting.py

raw symbols SCIP
1 """String formatting routines"""
2 import math
3 import sys
4
5 from rpython.rlib import jit, rutf8
6 from rpython.rlib.objectmodel import specialize
7 from rpython.rlib.rarithmetic import INT_MAX, r_uint
8 from rpython.rlib.rfloat import DTSF_ALT, formatd
9 from rpython.rlib.rstring import StringBuilder
10 from rpython.rlib.unroll import unrolling_iterable
11 from rpython.tool.sourcetools import func_with_new_name
12
13 from pypy.interpreter.error import OperationError, oefmt
14
15
16 class BaseStringFormatter(object):
17 def __init__(self, space, values_w, w_valuedict):
18 self.space = space
19 self.fmtpos = 0
20 self.values_w = values_w
21 self.values_pos = 0
22 self.w_valuedict = w_valuedict
23
24 def forward(self):
25 # move current position forward
26 self.fmtpos += 1
27
28 def nextinputvalue(self):
29 # return the next value in the tuple of input arguments
30 try:
31 w_result = self.values_w[self.values_pos]
32 except IndexError:
33 raise oefmt(self.space.w_TypeError,
34 "not enough arguments for format string")
35 else:
36 self.values_pos += 1
37 return w_result
38
39 def checkconsumed(self):
40 if self.values_pos < len(self.values_w) and self.w_valuedict is None:
41 raise oefmt(self.space.w_TypeError,
42 "not all arguments converted during string formatting")
43
44 def std_wp_int(self, r, prefix=''):
45 # use self.prec to add some '0' on the left of the number
46 if self.prec >= 0:
47 if self.prec > 1000:
48 raise oefmt(self.space.w_OverflowError,
49 "formatted integer is too long (precision too "
50 "large?)")
51 sign = r[0] == '-'
52 padding = self.prec - (len(r)-int(sign))
53 if padding > 0:
54 if sign:
55 r = '-' + '0'*padding + r[1:]
56 else:
57 r = '0'*padding + r
58 self.std_wp_number(r, prefix)
59
60 def fmt_d(self, w_value):
61 "d% formatting"
62 r = int_num_helper(self.space, w_value)
63 self.std_wp_int(r)
64
65 def fmt_i(self, w_value):
66 "i% formatting"
67 r = int_num_helper(self.space, w_value, fmt_for_error="%i")
68 self.std_wp_int(r)
69
70 def fmt_u(self, w_value):
71 "u% formatting"
72 r = int_num_helper(self.space, w_value, fmt_for_error="%u")
73 self.std_wp_int(r)
74
75 def fmt_x(self, w_value):
76 "hex formatting"
77 r = hex_num_helper(self.space, w_value)
78 if self.f_alt:
79 prefix = '0x'
80 else:
81 prefix = ''
82 self.std_wp_int(r, prefix)
83
84 def fmt_X(self, w_value):
85 "HEX formatting"
86 r = hex_num_helper(self.space, w_value, fmt_for_error='%X')
87 if self.f_alt:
88 prefix = '0X'
89 else:
90 prefix = ''
91 self.std_wp_int(r.upper(), prefix)
92
93 def fmt_o(self, w_value):
94 "oct formatting"
95 r = oct_num_helper(self.space, w_value)
96 if self.f_alt:
97 prefix = '0o'
98 else:
99 prefix = ''
100 self.std_wp_int(r, prefix)
101
102 def fmt_e(self, w_value):
103 self.format_float(w_value, 'e')
104
105 def fmt_f(self, w_value):
106 self.format_float(w_value, 'f')
107
108 def fmt_g(self, w_value):
109 self.format_float(w_value, 'g')
110
111 def fmt_E(self, w_value):
112 self.format_float(w_value, 'E')
113
114 def fmt_F(self, w_value):
115 self.format_float(w_value, 'F')
116
117 def fmt_G(self, w_value):
118 self.format_float(w_value, 'G')
119
120 def format_float(self, w_value, char):
121 space = self.space
122 x = space.float_w(maybe_float(space, w_value))
123 if math.isnan(x):
124 if char in 'EFG':
125 r = 'NAN'
126 else:
127 r = 'nan'
128 elif math.isinf(x):
129 if x < 0:
130 if char in 'EFG':
131 r = '-INF'
132 else:
133 r = '-inf'
134 else:
135 if char in 'EFG':
136 r = 'INF'
137 else:
138 r = 'inf'
139 else:
140 prec = self.prec
141 if prec < 0:
142 prec = 6
143 if char in 'fF' and x/1e25 > 1e25:
144 char = chr(ord(char) + 1) # 'f' => 'g'
145 flags = 0
146 if self.f_alt:
147 flags |= DTSF_ALT
148 r = formatd(x, char, prec, flags)
149 self.std_wp_number(r)
150
151 def std_wp_number(self, r, prefix=''):
152 raise NotImplementedError
153
154 def make_formatter_subclass(do_unicode):
155 # to build two subclasses of the BaseStringFormatter class,
156 # each one getting its own subtle differences and RPython types.
157
158 class StringFormatter(BaseStringFormatter):
159 def __init__(self, space, fmt, values_w, w_valuedict):
160 BaseStringFormatter.__init__(self, space, values_w, w_valuedict)
161 self.fmt = fmt # always a string, if unicode, utf8 encoded
162
163 def peekchr(self):
164 # Return the 'current' character. Note that this returns utf8
165 # encoded part, but this is ok since we only need one-character
166 # comparisons
167 try:
168 return self.fmt[self.fmtpos]
169 except IndexError:
170 raise oefmt(self.space.w_ValueError, "incomplete format")
171
172 # Only shows up if we've already started inlining format(), so just
173 # unconditionally unroll this.
174 @jit.unroll_safe
175 def getmappingkey(self):
176 # return the mapping key in a '%(key)s' specifier
177 fmt = self.fmt
178 i = self.fmtpos + 1 # first character after '('
179 i0 = i
180 pcount = 1
181 while 1:
182 try:
183 c = fmt[i]
184 except IndexError:
185 space = self.space
186 raise oefmt(space.w_ValueError, "incomplete format key")
187 if c == ')':
188 pcount -= 1
189 if pcount == 0:
190 break
191 elif c == '(':
192 pcount += 1
193 i += 1
194 self.fmtpos = i + 1 # first character after ')'
195 return fmt[i0:i]
196
197 def getmappingvalue(self, key):
198 # return the value corresponding to a key in the input dict
199 space = self.space
200 if self.w_valuedict is None:
201 raise oefmt(space.w_TypeError, "format requires a mapping")
202 if do_unicode:
203 lgt = rutf8.check_utf8(key, True)
204 w_key = space.newutf8(key, lgt)
205 else:
206 w_key = space.newbytes(key)
207 return space.getitem(self.w_valuedict, w_key)
208
209 def parse_fmt(self):
210 if self.peekchr() == '(':
211 w_value = self.getmappingvalue(self.getmappingkey())
212 else:
213 w_value = None
214
215 self.peel_flags()
216
217 self.width = self.peel_num('width', sys.maxint)
218 if self.width < 0:
219 # this can happen: '%*s' % (-5, "hi")
220 self.f_ljust = True
221 self.width = -self.width
222
223 if self.peekchr() == '.':
224 self.forward()
225 self.prec = self.peel_num('precision', INT_MAX)
226 if self.prec < 0:
227 self.prec = 0 # this can happen: '%.*f' % (-5, 3)
228 else:
229 self.prec = -1
230
231 c = self.peekchr()
232 if c == 'h' or c == 'l' or c == 'L':
233 self.forward()
234
235 return w_value
236
237 # Same as getmappingkey
238 @jit.unroll_safe
239 def peel_flags(self):
240 self.f_ljust = False
241 self.f_sign = False
242 self.f_blank = False
243 self.f_alt = False
244 self.f_zero = False
245 while True:
246 c = self.peekchr()
247 if c == '-':
248 self.f_ljust = True
249 elif c == '+':
250 self.f_sign = True
251 elif c == ' ':
252 self.f_blank = True
253 elif c == '#':
254 self.f_alt = True
255 elif c == '0':
256 self.f_zero = True
257 else:
258 break
259 self.forward()
260
261 # Same as getmappingkey
262 @jit.unroll_safe
263 def peel_num(self, name, maxval):
264 space = self.space
265 c = self.peekchr()
266 if c == '*':
267 self.forward()
268 w_value = self.nextinputvalue()
269 if name == 'width':
270 return space.int_w(w_value)
271 elif name == 'precision':
272 return space.c_int_w(w_value)
273 else:
274 assert False
275 result = 0
276 while True:
277 digit = ord(c) - ord('0')
278 if not (0 <= digit <= 9):
279 break
280 if result > (maxval - digit) / 10:
281 raise oefmt(space.w_ValueError, "%s too big", name)
282 result = result * 10 + digit
283 self.forward()
284 c = self.peekchr()
285 return result
286
287 @jit.look_inside_iff(lambda self: jit.isconstant(self.fmt))
288 def format(self):
289 lgt = len(self.fmt) + 4 * len(self.values_w) + 10
290 result = StringBuilder(lgt)
291 self.result = result
292 while True:
293 # fast path: consume as many characters as possible
294 fmt = self.fmt
295 i = i0 = self.fmtpos
296 while i < len(fmt):
297 if fmt[i] == '%':
298 break
299 i += 1
300 else:
301 result.append_slice(fmt, i0, len(fmt))
302 break # end of 'fmt' string
303 result.append_slice(fmt, i0, i)
304 self.fmtpos = i + 1
305
306 c = self.peekchr()
307 if c == '%':
308 self.forward()
309 self.result.append('%')
310 continue
311
312 # interpret the next formatter
313 w_value = self.parse_fmt()
314 c = self.peekchr()
315 self.forward()
316 if c == '%':
317 # if we get here there were extra characters between the
318 # two %, forbidden now
319 self.two_percent_error(i + 1)
320 continue
321
322 # first check whether it's a invalid char, *then* call
323 # nextinputvalue, otherwise the error generated by
324 # nextinputvalue can cover that of unknown_fmtchar
325 for c1 in FORMATTER_CHARS:
326 if c == c1:
327 break
328 else:
329 self.unknown_fmtchar()
330 if w_value is None:
331 w_value = self.nextinputvalue()
332
333 # dispatch on the formatter
334 # (this turns into a switch after translation)
335 for c1 in FORMATTER_CHARS:
336 if c == c1:
337 # 'c1' is an annotation constant here,
338 # so this getattr() is ok
339 do_fmt = getattr(self, 'fmt_' + c1)
340 do_fmt(w_value)
341 break
342
343 self.checkconsumed()
344 return result.build()
345
346 def _get_error_info(self, pos):
347 space = self.space
348 if do_unicode:
349 cp = rutf8.codepoint_at_pos(self.fmt, pos)
350 pos = rutf8.codepoints_in_utf8(self.fmt, 0, pos)
351 w_s = space.newutf8(rutf8.unichr_as_utf8(r_uint(cp),
352 allow_surrogates=True), 1)
353 else:
354 cp = ord(self.fmt[pos])
355 w_s = space.newbytes(chr(cp))
356 return w_s, pos, cp
357
358 def two_percent_error(self, pos):
359 space = self.space
360 w_s, pos, cp = self._get_error_info(pos)
361 raise oefmt(space.w_ValueError,
362 # hahahaha
363 "extra character %R (%s) before escaped '%%' at index %d, use '%%%%'",
364 w_s, hex(cp), pos)
365
366 def unknown_fmtchar(self):
367 space = self.space
368 w_s, pos, cp = self._get_error_info(self.fmtpos - 1)
369 raise oefmt(space.w_ValueError,
370 "unsupported format character %R (%s) at index %d",
371 w_s, hex(cp), pos)
372
373 @specialize.arg(2)
374 def std_wp(self, r, is_string=False):
375 # r is utf8-encoded unicode
376 length = rutf8.codepoints_in_utf8(r)
377 if do_unicode and is_string:
378 # convert string to unicode using the default encoding
379 r = self.space.utf8_w(self.space.newbytes(r))
380 prec = self.prec
381 if prec == -1 and self.width == 0:
382 # fast path
383 self.result.append(r)
384 return
385 if prec >= 0 and prec < length:
386 length = prec # ignore the end of the string if too long
387 padding = self.width - length
388 if do_unicode:
389 # XXX could use W_UnicodeObject.descr_getslice, but that would
390 # require a refactor to use the w_val, not r
391 length = rutf8._pos_at_index(r, length)
392 result = self.result
393 if padding < 0:
394 padding = 0
395 assert padding >= 0
396 if not self.f_ljust and padding > 0:
397 result.append_multiple_char(' ', padding)
398 # add any padding at the left of 'r'
399 padding = 0
400 result.append_slice(r, 0, length) # add 'r' itself
401 if padding > 0:
402 result.append_multiple_char(' ', padding)
403 # add any remaining padding at the right
404
405 def std_wp_number(self, r, prefix=''):
406 result = self.result
407 if len(prefix) == 0 and len(r) >= self.width:
408 # this is strictly a fast path: no prefix, and no padding
409 # needed. It is more efficient code both in the non-jit
410 # case (less testing stuff) and in the jit case (uses only
411 # result.append(), and no startswith() if not f_sign and
412 # not f_blank).
413 if self.f_sign and not r.startswith('-'):
414 result.append('+')
415 elif self.f_blank and not r.startswith('-'):
416 result.append(' ')
417 result.append(r)
418 return
419 # add a '+' or ' ' sign if necessary
420 sign = r.startswith('-')
421 if not sign:
422 if self.f_sign:
423 r = '+' + r
424 sign = True
425 elif self.f_blank:
426 r = ' ' + r
427 sign = True
428 # do the padding requested by self.width and the flags,
429 # without building yet another RPython string but directly
430 # by pushing the pad character into self.result
431 padding = self.width - len(r) - len(prefix)
432 if padding <= 0:
433 padding = 0
434
435 if self.f_ljust:
436 padnumber = '<'
437 elif self.f_zero:
438 padnumber = '0'
439 else:
440 padnumber = '>'
441
442 assert padding >= 0
443 if padnumber == '>':
444 result.append_multiple_char(' ', padding)
445 # pad with spaces on the left
446 if sign:
447 result.append(r[0]) # the sign
448 result.append(prefix) # the prefix
449 if padnumber == '0':
450 result.append_multiple_char('0', padding)
451 # pad with zeroes
452 result.append_slice(r, int(sign), len(r))
453 # the rest of the number
454 if padnumber == '<': # spaces on the right
455 result.append_multiple_char(' ', padding)
456
457 def string_formatting(self, w_value):
458 space = self.space
459 w_impl = space.lookup(w_value, '__str__')
460 if w_impl is None:
461 raise oefmt(space.w_TypeError,
462 "operand does not support unary str")
463 w_result = space.get_and_call_function(w_impl, w_value)
464 if space.isinstance_w(w_result, space.w_unicode):
465 raise NeedUnicodeFormattingError
466 return space.bytes_w(w_result)
467
468 def fmt_s(self, w_value):
469 if not do_unicode:
470 # on bytes, %s is equivalent to %b
471 self.fmt_b(w_value)
472 return
473 space = self.space
474 got_unicode = space.isinstance_w(w_value, space.w_unicode)
475 if not got_unicode:
476 w_value = space.call_function(space.w_unicode, w_value)
477 else:
478 from pypy.objspace.std.unicodeobject import unicode_from_object
479 w_value = unicode_from_object(space, w_value)
480 s = space.utf8_w(w_value)
481 self.std_wp(s, False)
482
483 def fmt_r(self, w_value):
484 if not do_unicode:
485 # on bytes, %r is equivalent to %a
486 self.fmt_a(w_value)
487 else:
488 # on unicodes, %r calls repr(), which typically returns
489 # arbitrary unicode chars if w_value is an arbitrary unicode
490 # string
491 w_value = self.space.repr(w_value)
492 self.std_wp(self.space.utf8_w(w_value))
493
494 def fmt_a(self, w_value):
495 from pypy.objspace.std.unicodeobject import ascii_from_object
496 w_value = ascii_from_object(self.space, w_value)
497 # %a calls ascii(), which should return an ascii unicode string
498 if do_unicode:
499 value = self.space.utf8_w(w_value)
500 else:
501 value = self.space.text_w(w_value)
502 self.std_wp(value)
503
504 def fmt_c(self, w_value):
505 self.prec = -1 # just because
506 space = self.space
507 try:
508 w_value = space.index(w_value)
509 except OperationError as operr:
510 if not operr.match(space, space.w_TypeError):
511 raise
512 else:
513 n = space.int_w(w_value)
514 if do_unicode:
515 try:
516 c = rutf8.unichr_as_utf8(r_uint(n),
517 allow_surrogates=True)
518 except rutf8.OutOfRange:
519 raise oefmt(space.w_OverflowError,
520 "unicode character code out of range")
521 self.std_wp(c, False)
522 else:
523 try:
524 s = chr(n)
525 except ValueError:
526 raise oefmt(space.w_OverflowError,
527 "character code not in range(256)")
528 self.std_wp(s, True)
529 return
530 if not do_unicode:
531 if space.isinstance_w(w_value, space.w_bytes):
532 s = space.bytes_w(w_value)
533 elif space.isinstance_w(w_value, space.w_bytearray):
534 s = w_value.buffer_w(space, 0).as_str()
535 else:
536 s = ''
537 if len(s) == 1:
538 self.std_wp(s)
539 return
540 raise oefmt(space.w_TypeError, "%c requires int or single byte")
541 else:
542 if space.isinstance_w(w_value, space.w_unicode):
543 ustr = space.utf8_w(w_value)
544 if space.len_w(w_value) == 1:
545 self.std_wp(ustr)
546 return
547 raise oefmt(space.w_TypeError, "%c requires int or char")
548
549 def fmt_b(self, w_value):
550 if do_unicode:
551 self.unknown_fmtchar()
552 space = self.space
553 # follow logic in cpython bytesobject.c format_obj
554 if space.isinstance_w(w_value, space.w_bytes):
555 self.std_wp(space.bytes_w(w_value))
556 return
557 if space.isinstance_w(w_value, space.w_bytearray):
558 buf = w_value.buffer_w(space, 0)
559 # convert the array of the buffer to a py 2 string
560 self.std_wp(buf.as_str())
561 return
562
563 w_bytes_method = space.lookup(w_value, "__bytes__")
564 if w_bytes_method is not None:
565 w_bytes = space.get_and_call_function(w_bytes_method, w_value)
566 if not space.isinstance_w(w_bytes, space.w_bytes):
567 raise oefmt(space.w_TypeError,
568 "__bytes__ returned non-bytes (type '%T')", w_bytes)
569 self.std_wp(space.bytes_w(w_bytes))
570 return
571 if space.isinstance_w(w_value, space.w_memoryview):
572 buf = w_value.buffer_w(space, 0)
573 # convert the array of the buffer to a py 2 string
574 self.std_wp(buf.as_str())
575 return
576
577 raise oefmt(space.w_TypeError,
578 "requires bytes, or an object that "
579 "implements __bytes__, not '%T'", w_value)
580
581 return StringFormatter
582
583
584 class NeedUnicodeFormattingError(Exception):
585 pass
586
587 StringFormatter = make_formatter_subclass(do_unicode=False)
588 UnicodeFormatter = make_formatter_subclass(do_unicode=True)
589 UnicodeFormatter.__name__ = 'UnicodeFormatter'
590
591
592 # an "unrolling" list of all the known format characters,
593 # collected from which fmt_X() functions are defined in the class
594 FORMATTER_CHARS = unrolling_iterable(
595 [_name[-1] for _name in dir(StringFormatter)
596 if len(_name) == 5 and _name.startswith('fmt_')])
597
598 FORMAT_STR = 0
599 FORMAT_UNICODE = 1
600 FORMAT_BYTES = 2
601 FORMAT_BYTEARRAY = 3
602
603 def format(space, w_fmt, values_w, w_valuedict, fmt_type):
604 "Entry point"
605 if fmt_type != FORMAT_UNICODE:
606 if fmt_type == FORMAT_BYTEARRAY:
607 fmt = w_fmt.buffer_w(space, 0).as_str()
608 else:
609 fmt = space.bytes_w(w_fmt)
610 formatter = StringFormatter(space, fmt, values_w, w_valuedict)
611 try:
612 result = formatter.format()
613 except NeedUnicodeFormattingError:
614 assert 0, "unreachable on python 3"
615 else:
616 if fmt_type == FORMAT_BYTES:
617 return space.newbytes(result)
618 elif fmt_type == FORMAT_BYTEARRAY:
619 return _bytearray_from_bytes(space, result)
620 return space.newbytes(result)
621 assert space.isinstance_w(w_fmt, space.w_unicode)
622 fmt = space.utf8_w(w_fmt)
623 formatter = UnicodeFormatter(space, fmt, values_w, w_valuedict)
624 result = formatter.format()
625 # this can force strings, not sure if it's a problem or not
626 lgt = rutf8.codepoints_in_utf8(result)
627 return space.newutf8(result, lgt)
628
629 # in its own function to make the JIT look into format above
630 def _bytearray_from_bytes(space, result):
631 return space.newbytearray([c for c in result])
632
633 def mod_format(space, w_format, w_values, fmt_type=FORMAT_STR):
634 from pypy.objspace.std.tupleobject import W_AbstractTupleObject
635 if space.isinstance_w(w_values, space.w_tuple):
636 assert isinstance(w_values, W_AbstractTupleObject)
637 # bug-to-bug cpython compatibility: intentionally not using the space
638 # methods, to not pick up __iter__ of tuple subclasses, issue #3555
639 values_w = w_values.tolist()
640 return format(space, w_format, values_w, None, fmt_type)
641 else:
642 # we check directly for dict to avoid obscure checking
643 # in simplest case
644 if space.isinstance_w(w_values, space.w_dict) or \
645 _looks_like_a_mapping(space, w_values, fmt_type):
646 return format(space, w_format, [w_values], w_values, fmt_type)
647 else:
648 return format(space, w_format, [w_values], None, fmt_type)
649
650 def _looks_like_a_mapping(space, w_x, fmt_type):
651 if not space.lookup(w_x, '__getitem__'):
652 return False
653 if space.isinstance_w(w_x, space.w_unicode):
654 return False
655 if fmt_type != FORMAT_UNICODE: # (S6) in http://bugs.python.org/issue28885
656 if (space.isinstance_w(w_x, space.w_bytes) or
657 space.isinstance_w(w_x, space.w_bytearray)):
658 return False
659 return True
660
661 # ____________________________________________________________
662 # Formatting helpers
663
664 def maybe_int(space, w_value):
665 # make sure that w_value is a wrapped integer
666 return space.int(w_value)
667
668 def maybe_index(space, w_value):
669 return space.index(w_value)
670
671 def maybe_float(space, w_value):
672 # make sure that w_value is a wrapped float
673 return space.float(w_value)
674
675 def format_num_helper_generator(fmt, digits, decoder=maybe_int,
676 expect_text="a real number"):
677 def format_num_helper(space, w_value, fmt_for_error=fmt):
678 if not space.isinstance_w(w_value, space.w_int):
679 try:
680 w_value = decoder(space, w_value)
681 except OperationError as operr:
682 if not operr.match(space, space.w_TypeError):
683 raise
684 raise oefmt(space.w_TypeError,
685 "%s format: %s is required, not %T",
686 fmt_for_error, expect_text, w_value)
687 try:
688 value = space.int_w(w_value)
689 return fmt % (value,)
690 except OperationError as operr:
691 if not operr.match(space, space.w_OverflowError):
692 raise
693 num = space.bigint_w(w_value)
694 return num.format(digits)
695 return func_with_new_name(format_num_helper,
696 'base%d_num_helper' % len(digits))
697
698 int_num_helper = format_num_helper_generator('%d', '0123456789')
699 oct_num_helper = format_num_helper_generator('%o', '01234567',
700 decoder=maybe_index, expect_text="an integer")
701 hex_num_helper = format_num_helper_generator('%x', '0123456789abcdef',
702 decoder=maybe_index, expect_text="an integer")