| 1 |
from pypy.interpreter.astcompiler import ast, consts |
| 2 |
from pypy.interpreter.pyparser import parsestring, error as parseerror |
| 3 |
from pypy.interpreter import error |
| 4 |
from rpython.rlib.rstring import StringBuilder |
| 5 |
from rpython.rlib.rutf8 import codepoints_in_utf8 |
| 6 |
|
| 7 |
from rpython.rlib.objectmodel import specialize |
| 8 |
|
| 9 |
@specialize.arg(0) |
| 10 |
def build(cls, *args): |
| 11 |
token = args[-1] |
| 12 |
newargs = args[:-1] + (token.lineno, token.column, |
| 13 |
token.end_lineno, token.end_column) |
| 14 |
return cls(*newargs) |
| 15 |
|
| 16 |
@specialize.arg(0) |
| 17 |
def build_tokens(cls, *args): |
| 18 |
tokens = args[-1] |
| 19 |
newargs = args[:-1] + (tokens[0].lineno, tokens[0].column, |
| 20 |
tokens[-1].end_lineno, tokens[-1].end_column) |
| 21 |
return cls(*newargs) |
| 22 |
|
| 23 |
def add_constant_string(astbuilder, joined_pieces, w_string, token, |
| 24 |
kind=None): |
| 25 |
space = astbuilder.space |
| 26 |
is_unicode = space.isinstance_w(w_string, space.w_unicode) |
| 27 |
|
| 28 |
start_lineno = token.lineno |
| 29 |
start_column = token.column |
| 30 |
end_lineno = token.end_lineno |
| 31 |
end_column = token.end_column |
| 32 |
if joined_pieces: |
| 33 |
prev = joined_pieces[-1] |
| 34 |
if isinstance(prev, ast.Constant): |
| 35 |
if is_unicode is space.isinstance_w(prev.value, space.w_unicode): |
| 36 |
w_string = space.add(prev.value, w_string) |
| 37 |
start_lineno = joined_pieces[-1].lineno |
| 38 |
start_column = joined_pieces[-1].col_offset |
| 39 |
del joined_pieces[-1] |
| 40 |
joined_pieces.append(ast.Constant(w_string, space.newtext_or_none(kind), |
| 41 |
start_lineno, start_column, end_lineno, end_column)) |
| 42 |
|
| 43 |
def f_string_compile(astbuilder, source, token, fstr, start_offset, nextchar): |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
from pypy.interpreter.pyparser import pyparse |
| 49 |
|
| 50 |
|
| 51 |
for c in source: |
| 52 |
if c not in ' \t\n\r\v\f': |
| 53 |
break |
| 54 |
else: |
| 55 |
if nextchar == '}': |
| 56 |
msg = "f-string: empty expression not allowed" |
| 57 |
else: |
| 58 |
msg = "f-string: expression required before '%s'" % nextchar |
| 59 |
astbuilder.raise_syntax_error_known_location(msg, token) |
| 60 |
|
| 61 |
assert isinstance(source, str) |
| 62 |
|
| 63 |
paren_source = '(%s)' % source |
| 64 |
|
| 65 |
lineno = 0 |
| 66 |
column_offset = 0 |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
if fstr.token: |
| 76 |
token = fstr.token |
| 77 |
lineno = token.lineno - 1 |
| 78 |
value = token.value |
| 79 |
if value is not None: |
| 80 |
offset = start_offset + fstr.content_offset |
| 81 |
assert offset >= 0 |
| 82 |
after_last_nl = max(0, value.rfind('\n', 0, offset) + 1) |
| 83 |
column_offset = offset - after_last_nl + token.column |
| 84 |
lineno += value.count('\n', 0, after_last_nl) |
| 85 |
|
| 86 |
info = pyparse.CompileInfo("<fstring>", "eval", |
| 87 |
consts.PyCF_SOURCE_IS_UTF8 | |
| 88 |
consts.PyCF_IGNORE_COOKIE, |
| 89 |
optimize=astbuilder.compile_info.optimize) |
| 90 |
try: |
| 91 |
ast = astbuilder.recursive_parse_to_ast(paren_source, info) |
| 92 |
except parseerror.SyntaxError as e: |
| 93 |
|
| 94 |
if e.lineno == 1: |
| 95 |
e.offset += column_offset - 1 |
| 96 |
e.lineno += lineno |
| 97 |
e.text = None |
| 98 |
e.msg = "f-string: " + e.msg |
| 99 |
raise |
| 100 |
|
| 101 |
fixup_fstring_positions(ast, lineno, column_offset - 1) |
| 102 |
return ast |
| 103 |
|
| 104 |
def fixup_fstring_positions(ast, line_offset, column_offset): |
| 105 |
visitor = FixPosVisitor(line_offset, column_offset) |
| 106 |
ast.walkabout(visitor) |
| 107 |
|
| 108 |
class FixPosVisitor(ast.GenericASTVisitor): |
| 109 |
def __init__(self, line_offset, column_offset): |
| 110 |
self.line_offset = line_offset |
| 111 |
self.column_offset = column_offset |
| 112 |
|
| 113 |
def visited(self, node): |
| 114 |
if isinstance(node, ast.stmt) or isinstance(node, ast.expr): |
| 115 |
if node.lineno == 1: |
| 116 |
node.col_offset += self.column_offset |
| 117 |
node.end_col_offset += self.column_offset |
| 118 |
node.lineno += self.line_offset |
| 119 |
node.end_lineno += self.line_offset |
| 120 |
|
| 121 |
|
| 122 |
def unexpected_end_of_string(astbuilder, tok): |
| 123 |
astbuilder.raise_syntax_error_known_location("f-string: expecting '}'", tok) |
| 124 |
|
| 125 |
|
| 126 |
def fstring_find_expr(astbuilder, fstr, token, rec): |
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
conversion = -1 |
| 132 |
format_spec = None |
| 133 |
expr_text = None |
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
quote_char = 0 |
| 139 |
|
| 140 |
|
| 141 |
string_type = 0 |
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
parenstack = [] |
| 146 |
|
| 147 |
|
| 148 |
if rec >= 2: |
| 149 |
astbuilder.raise_syntax_error_known_location("f-string: expressions nested too deeply", token) |
| 150 |
|
| 151 |
|
| 152 |
|
| 153 |
s = fstr.unparsed |
| 154 |
i = fstr.current_index |
| 155 |
assert s[i] == '{' |
| 156 |
i += 1 |
| 157 |
|
| 158 |
expr_start = i |
| 159 |
while i < len(s): |
| 160 |
|
| 161 |
|
| 162 |
if quote_char: |
| 163 |
assert string_type == 1 or string_type == 3 |
| 164 |
else: |
| 165 |
assert string_type == 0 |
| 166 |
|
| 167 |
ch = s[i] |
| 168 |
|
| 169 |
if ch == '\\': |
| 170 |
|
| 171 |
|
| 172 |
astbuilder.raise_syntax_error_known_location("f-string expression part " |
| 173 |
"cannot include a backslash", token) |
| 174 |
|
| 175 |
if quote_char: |
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
if ord(ch) == quote_char: |
| 180 |
|
| 181 |
|
| 182 |
if string_type == 3: |
| 183 |
if i + 2 < len(s) and s[i + 1] == s[i + 2] == ch: |
| 184 |
|
| 185 |
i += 3 |
| 186 |
string_type = 0 |
| 187 |
quote_char = 0 |
| 188 |
continue |
| 189 |
else: |
| 190 |
|
| 191 |
i += 1 |
| 192 |
string_type = 0 |
| 193 |
quote_char = 0 |
| 194 |
continue |
| 195 |
elif ch == "'" or ch == '"': |
| 196 |
|
| 197 |
if i + 2 < len(s) and s[i + 1] == s[i + 2] == ch: |
| 198 |
string_type = 3 |
| 199 |
i += 2 |
| 200 |
else: |
| 201 |
|
| 202 |
string_type = 1 |
| 203 |
|
| 204 |
quote_char = ord(ch) |
| 205 |
elif ch in "[{(": |
| 206 |
parenstack.append(ch) |
| 207 |
elif ch == '#': |
| 208 |
|
| 209 |
|
| 210 |
astbuilder.raise_syntax_error_known_location("f-string expression part cannot include '#'", |
| 211 |
token) |
| 212 |
elif not parenstack and ch in ":}!=<>": |
| 213 |
|
| 214 |
|
| 215 |
if i + 1 < len(s): |
| 216 |
nextch = s[i + 1] |
| 217 |
if ch in '!=<>' and nextch == '=': |
| 218 |
|
| 219 |
i += 2 |
| 220 |
continue |
| 221 |
|
| 222 |
|
| 223 |
if ch in "<>": |
| 224 |
i += 1 |
| 225 |
continue |
| 226 |
|
| 227 |
break |
| 228 |
elif ch in ']})': |
| 229 |
if not parenstack: |
| 230 |
astbuilder.raise_syntax_error_known_location("f-string: unmatched '%s'" % ch, token) |
| 231 |
opening = parenstack.pop() |
| 232 |
if not ((opening == '(' and ch ==')') or |
| 233 |
(opening == '[' and ch ==']') or |
| 234 |
(opening == '{' and ch =='}')): |
| 235 |
astbuilder.raise_syntax_error_known_location("f-string: closing parenthesis '%s' " |
| 236 |
"does not match opening parenthesis '%s'" |
| 237 |
% (ch, opening), token) |
| 238 |
|
| 239 |
|
| 240 |
i += 1 |
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
if quote_char: |
| 247 |
astbuilder.raise_syntax_error_known_location("f-string: unterminated string", token) |
| 248 |
|
| 249 |
if parenstack: |
| 250 |
opening = parenstack[-1] |
| 251 |
astbuilder.raise_syntax_error_known_location("f-string: unmatched '%s'" % opening, |
| 252 |
token) |
| 253 |
|
| 254 |
if i >= len(s): |
| 255 |
unexpected_end_of_string(astbuilder, token) |
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
expr = f_string_compile(astbuilder, s[expr_start:i], token, fstr, expr_start, nextchar=s[i]) |
| 261 |
assert isinstance(expr, ast.Expression) |
| 262 |
|
| 263 |
|
| 264 |
if s[i] == '=': |
| 265 |
astbuilder.check_version( |
| 266 |
(3, 8), |
| 267 |
"f-string: self documenting expressions are", |
| 268 |
token |
| 269 |
) |
| 270 |
i += 1 |
| 271 |
if i >= len(s): |
| 272 |
unexpected_end_of_string(astbuilder, token) |
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
while s[i].isspace(): |
| 277 |
i += 1 |
| 278 |
if i >= len(s): |
| 279 |
unexpected_end_of_string(astbuilder, token) |
| 280 |
|
| 281 |
expr_text = s[expr_start:i] |
| 282 |
|
| 283 |
|
| 284 |
if s[i] == '!': |
| 285 |
i += 1 |
| 286 |
if i >= len(s): |
| 287 |
unexpected_end_of_string(astbuilder, token) |
| 288 |
|
| 289 |
conversion = ord(s[i]) |
| 290 |
i += 1 |
| 291 |
if conversion not in (ord('s'), ord('r'), ord('a')): |
| 292 |
astbuilder.raise_syntax_error_known_location("f-string: invalid conversion character: " |
| 293 |
"expected 's', 'r', or 'a'", token) |
| 294 |
|
| 295 |
|
| 296 |
if i >= len(s): |
| 297 |
unexpected_end_of_string(astbuilder, token) |
| 298 |
if s[i] == ':': |
| 299 |
i += 1 |
| 300 |
if i >= len(s): |
| 301 |
unexpected_end_of_string(astbuilder, token) |
| 302 |
fstr.current_index = i |
| 303 |
subpieces = [] |
| 304 |
parse_f_string(astbuilder, subpieces, fstr, token, rec + 1) |
| 305 |
format_spec = f_string_to_ast_node(astbuilder, subpieces, [token]) |
| 306 |
i = fstr.current_index |
| 307 |
|
| 308 |
if i >= len(s) or s[i] != '}': |
| 309 |
unexpected_end_of_string(astbuilder, token) |
| 310 |
|
| 311 |
w_expr_text = None |
| 312 |
if expr_text is not None: |
| 313 |
|
| 314 |
|
| 315 |
if format_spec is None and conversion == -1: |
| 316 |
conversion = ord('r') |
| 317 |
|
| 318 |
w_expr_text = astbuilder.space.newtext(expr_text) |
| 319 |
|
| 320 |
|
| 321 |
i += 1 |
| 322 |
fstr.current_index = i |
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
return build(ast.FormattedValue, expr.body, conversion, format_spec, |
| 327 |
token), w_expr_text |
| 328 |
|
| 329 |
|
| 330 |
def fstring_find_literal(astbuilder, fstr, token, rec): |
| 331 |
space = astbuilder.space |
| 332 |
raw = fstr.raw_mode |
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
s = fstr.unparsed |
| 337 |
literal_start = fstr.current_index |
| 338 |
assert literal_start >= 0 |
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
i = literal_start |
| 344 |
builder = StringBuilder() |
| 345 |
while i < len(s): |
| 346 |
ch = s[i] |
| 347 |
i += 1 |
| 348 |
if not raw and ch == '\\' and i < len(s): |
| 349 |
ch = s[i] |
| 350 |
i += 1 |
| 351 |
if ch == 'N': |
| 352 |
if i < len(s) and s[i] == '{': |
| 353 |
while i < len(s) and s[i] != '}': |
| 354 |
i += 1 |
| 355 |
if i < len(s): |
| 356 |
i += 1 |
| 357 |
continue |
| 358 |
elif i < len(s): |
| 359 |
i += 1 |
| 360 |
break |
| 361 |
if ch == '{': |
| 362 |
msg = "invalid escape sequence '%s'" |
| 363 |
astbuilder.deprecation_warn(msg % ch, token) |
| 364 |
if ch == '{' or ch == '}': |
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
if rec == 0 and i < len(s) and s[i] == ch: |
| 369 |
assert 0 <= i <= len(s) |
| 370 |
builder.append(s[literal_start:i]) |
| 371 |
i += 1 |
| 372 |
literal_start = i |
| 373 |
elif rec == 0 and ch == '}': |
| 374 |
i -= 1 |
| 375 |
assert i >= 0 |
| 376 |
fstr.current_index = i |
| 377 |
|
| 378 |
|
| 379 |
astbuilder.raise_syntax_error_known_location("f-string: single '}' is not allowed", |
| 380 |
token) |
| 381 |
else: |
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
i -= 1 |
| 386 |
break |
| 387 |
assert 0 <= i <= len(s) |
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
builder.append(s[literal_start:i]) |
| 393 |
|
| 394 |
fstr.current_index = i |
| 395 |
literal = builder.build() |
| 396 |
lgt = codepoints_in_utf8(literal) |
| 397 |
if not raw and '\\' in literal: |
| 398 |
literal = parsestring.decode_unicode_utf8(space, literal, 0, |
| 399 |
len(literal)) |
| 400 |
literal, lgt, pos = parsestring.decode_unicode_escape(space, literal, astbuilder, token) |
| 401 |
return space.newtext(literal, lgt) |
| 402 |
|
| 403 |
|
| 404 |
def fstring_find_literal_and_expr(astbuilder, fstr, token, rec): |
| 405 |
|
| 406 |
|
| 407 |
w_u = fstring_find_literal(astbuilder, fstr, token, rec) |
| 408 |
|
| 409 |
s = fstr.unparsed |
| 410 |
i = fstr.current_index |
| 411 |
if i >= len(s) or s[i] == '}': |
| 412 |
|
| 413 |
|
| 414 |
expr, w_expr_text = None, None |
| 415 |
else: |
| 416 |
|
| 417 |
assert s[i] == '{' |
| 418 |
expr, w_expr_text = fstring_find_expr(astbuilder, fstr, token, rec) |
| 419 |
return w_u, expr, w_expr_text |
| 420 |
|
| 421 |
|
| 422 |
def parse_f_string(astbuilder, joined_pieces, fstr, token, rec=0): |
| 423 |
|
| 424 |
|
| 425 |
|
| 426 |
space = astbuilder.space |
| 427 |
while True: |
| 428 |
w_u, expr, w_expr_text = fstring_find_literal_and_expr(astbuilder, fstr, |
| 429 |
token, rec) |
| 430 |
|
| 431 |
|
| 432 |
add_constant_string(astbuilder, joined_pieces, w_u, token) |
| 433 |
if expr is None: |
| 434 |
break |
| 435 |
if w_expr_text is not None: |
| 436 |
add_constant_string(astbuilder, joined_pieces, w_expr_text, token) |
| 437 |
joined_pieces.append(expr) |
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
if rec == 0 and fstr.current_index < len(fstr.unparsed) - 1: |
| 442 |
astbuilder.raise_syntax_error_known_location("f-string: unexpected end of string", token) |
| 443 |
|
| 444 |
if rec != 0 and (fstr.current_index >= len(fstr.unparsed) or |
| 445 |
fstr.unparsed[fstr.current_index] != '}'): |
| 446 |
astbuilder.raise_syntax_error_known_location("f-string: expecting '}'", token) |
| 447 |
|
| 448 |
|
| 449 |
def f_string_to_ast_node(astbuilder, joined_pieces, tokens): |
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
space = astbuilder.space |
| 455 |
values = [node for node in joined_pieces |
| 456 |
if not isinstance(node, ast.Constant) |
| 457 |
or space.is_true(node.value)] |
| 458 |
return build_tokens(ast.JoinedStr, values, tokens) |
| 459 |
|
| 460 |
|
| 461 |
def string_parse_literal(astbuilder, tokens): |
| 462 |
space = astbuilder.space |
| 463 |
encoding = astbuilder.compile_info.encoding |
| 464 |
joined_pieces = [] |
| 465 |
fmode = False |
| 466 |
for i in range(len(tokens)): |
| 467 |
token = tokens[i] |
| 468 |
try: |
| 469 |
child_str = token.value |
| 470 |
w_next = parsestring.parsestr( |
| 471 |
space, encoding, child_str, token, |
| 472 |
astbuilder) |
| 473 |
if not isinstance(w_next, parsestring.W_FString): |
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
kind = "u" if child_str[0] == "u" else None |
| 478 |
add_constant_string(astbuilder, joined_pieces, |
| 479 |
w_next, token, kind) |
| 480 |
else: |
| 481 |
parse_f_string(astbuilder, joined_pieces, w_next, token) |
| 482 |
fmode = True |
| 483 |
|
| 484 |
except error.OperationError as e: |
| 485 |
if e.match(space, space.w_UnicodeDecodeError): |
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
e.normalize_exception(space) |
| 490 |
w_exc = e.get_w_value(space) |
| 491 |
w_encoding = space.getattr(w_exc, space.newtext('encoding')) |
| 492 |
if space.text_w(w_encoding) == 'utf-8': |
| 493 |
w_obj = space.getattr(w_exc, space.newtext('object')) |
| 494 |
w_start = space.getattr(w_exc, space.newtext('start')) |
| 495 |
bad_bytes = space.bytes_w(w_obj) |
| 496 |
start_pos = space.int_w(w_start) |
| 497 |
if 0 <= start_pos < len(bad_bytes): |
| 498 |
bad_byte = ord(bad_bytes[start_pos]) |
| 499 |
else: |
| 500 |
bad_byte = 0x80 |
| 501 |
hex_byte = hex(bad_byte)[2:] |
| 502 |
if len(hex_byte) < 2: |
| 503 |
hex_byte = '0' + hex_byte |
| 504 |
errmsg = "Non-UTF-8 code starting with '\\x" + hex_byte + "'" |
| 505 |
raise astbuilder.raise_syntax_error_known_location(errmsg, token) |
| 506 |
|
| 507 |
if e.match(space, space.w_UnicodeError): |
| 508 |
kind = '(unicode error) ' |
| 509 |
elif e.match(space, space.w_ValueError): |
| 510 |
kind = '(value error) ' |
| 511 |
elif e.match(space, space.w_SyntaxError): |
| 512 |
kind = '' |
| 513 |
else: |
| 514 |
raise |
| 515 |
|
| 516 |
|
| 517 |
e.normalize_exception(space) |
| 518 |
errmsg = space.text_w(space.str(e.get_w_value(space))) |
| 519 |
raise astbuilder.raise_syntax_error_known_location('%s%s' % (kind, errmsg), token) |
| 520 |
|
| 521 |
if not fmode and len(joined_pieces) == 1: |
| 522 |
return joined_pieces[0] |
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
for node in joined_pieces: |
| 528 |
if isinstance(node, ast.Constant) and space.isinstance_w(node.value, space.w_bytes): |
| 529 |
astbuilder.raise_syntax_error_known_location( |
| 530 |
"cannot mix bytes and nonbytes literals", |
| 531 |
node) |
| 532 |
assert fmode |
| 533 |
result = f_string_to_ast_node(astbuilder, joined_pieces, tokens) |
| 534 |
astbuilder.check_version( |
| 535 |
(3, 6), |
| 536 |
"Format strings are", |
| 537 |
result |
| 538 |
) |
| 539 |
return result |