Debian Codegraph @

pypy/interpreter/astcompiler/fstring.py

raw symbols SCIP
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 # Implement implicit string concatenation.
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 # Note: a f-string is kept as a single literal up to here.
45 # At this point only, we recursively call the AST compiler
46 # on all the '{expr}' parts. The 'expr' part is not parsed
47 # or even tokenized together with the rest of the source code!
48 from pypy.interpreter.pyparser import pyparse
49
50 # complain if 'source' is only whitespace or an empty string
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) # utf-8 encoded
62
63 paren_source = '(%s)' % source # to deal with whitespace at the start of source
64
65 lineno = 0
66 column_offset = 0
67 # overview:
68 # here's the input, after the | in a simple case, no newlines:
69 # |a + f" ??? {x}"
70 # offset of the f" that starts the f-string is fstr.stnode.get_column()
71 # offset of the start of the content of the f-string is +
72 # fstr.content_offset
73 # offset of the content of the {curly parens} we are parsing now is
74 # start_offset
75 if fstr.token:
76 token = fstr.token
77 lineno = token.lineno - 1 # one-based
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 # same logic as fixup_fstring_positions
94 if e.lineno == 1:
95 e.offset += column_offset - 1
96 e.lineno += lineno
97 e.text = None # better to get it from the source
98 e.msg = "f-string: " + e.msg
99 raise
100 # column_offset - 1 to exclude prefixed ( in paren_source
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 # Parse the f-string at fstr.current_index. We know it starts an
128 # expression (so it must be at '{'). Returns the FormattedValue node,
129 # which includes the expression, conversion character, and
130 # format_spec expression.
131 conversion = -1 # the conversion char. -1 if not specified.
132 format_spec = None
133 expr_text = None # Stores the text representation of the expression part
134 # in order to be used for f-string debugging (f'{x = }')
135
136 # 0 if we're not in a string, else the quote char we're trying to
137 # match (single or double quote).
138 quote_char = 0
139
140 # If we're inside a string, 1=normal, 3=triple-quoted.
141 string_type = 0
142
143 # Keep track of nesting level for braces/parens/brackets in
144 # expressions.
145 parenstack = []
146
147 # Can only nest one level deep.
148 if rec >= 2:
149 astbuilder.raise_syntax_error_known_location("f-string: expressions nested too deeply", token)
150
151 # The first char must be a left brace, or we wouldn't have gotten
152 # here. Skip over it.
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 # Loop invariants.
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 # Nowhere inside an expression is a backslash allowed.
169 if ch == '\\':
170 # Error: can't include a backslash character, inside
171 # parens or strings or not.
172 astbuilder.raise_syntax_error_known_location("f-string expression part "
173 "cannot include a backslash", token)
174
175 if quote_char:
176 # We're inside a string. See if we're at the end.
177 # <a long comment goes here about how we're duplicating
178 # some existing logic>
179 if ord(ch) == quote_char:
180 # Does this match the string_type (single or triple
181 # quoted)?
182 if string_type == 3:
183 if i + 2 < len(s) and s[i + 1] == s[i + 2] == ch:
184 # We're at the end of a triple quoted string.
185 i += 3
186 string_type = 0
187 quote_char = 0
188 continue
189 else:
190 # We're at the end of a normal string.
191 i += 1
192 string_type = 0
193 quote_char = 0
194 continue
195 elif ch == "'" or ch == '"':
196 # Is this a triple quoted string?
197 if i + 2 < len(s) and s[i + 1] == s[i + 2] == ch:
198 string_type = 3
199 i += 2
200 else:
201 # Start of a normal string.
202 string_type = 1
203 # Start looking for the end of the string.
204 quote_char = ord(ch)
205 elif ch in "[{(":
206 parenstack.append(ch)
207 elif ch == '#':
208 # Error: can't include a comment character, inside parens
209 # or not.
210 astbuilder.raise_syntax_error_known_location("f-string expression part cannot include '#'",
211 token)
212 elif not parenstack and ch in ":}!=<>":
213 # First, test for the special case of comparison operators
214 # that also contains equal sign ("!="/">="/"=="/"<=").
215 if i + 1 < len(s):
216 nextch = s[i + 1]
217 if ch in '!=<>' and nextch == '=':
218 # This is an operator, just skip it.
219 i += 2
220 continue
221 # don't get out of the loop for just < or > if they are single
222 # chars (ie not part of a two-char token).
223 if ch in "<>":
224 i += 1
225 continue
226 # Normal way out of this loop.
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 #else:
239 # This isn't a conversion character, just continue.
240 i += 1
241
242 # If we leave this loop in a string or with mismatched parens, we
243 # don't care. We'll get a syntax error when compiling the
244 # expression. But, we can produce a better error message, so
245 # let's just do that.
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 # Compile the expression as soon as possible, so we show errors
258 # related to the expression before errors related to the
259 # conversion or format_spec.
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 # Check for the equal sign (debugging expr)
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 # The whitespace after the equal sign (f'{x= }') can be
275 # safely ignored (since it will be preserved in expr_text).
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 # Check for a conversion char, if present.
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 # Check for the format spec, if present.
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 # If there are no format spec and conversion, debugging exprs will
314 # default to using !r for their conversion.
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 # We're at a right brace. Consume it.
321 i += 1
322 fstr.current_index = i
323
324 # And now create the FormattedValue node that represents this
325 # entire expression with the conversion and format spec.
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 # Return the next literal part. Updates the current index inside 'fstr'.
335 # Differs from CPython: this version handles double-braces on its own.
336 s = fstr.unparsed
337 literal_start = fstr.current_index
338 assert literal_start >= 0
339
340 # Get any literal string. It ends when we hit an un-doubled left
341 # brace (which isn't part of a unicode name escape such as
342 # "\N{EULER CONSTANT}"), or the end of the string.
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 # Check for doubled braces, but only at the top level. If
366 # we checked at every level, then f'{0:{3}}' would fail
367 # with the two closing braces.
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 # skip over the second brace
372 literal_start = i
373 elif rec == 0 and ch == '}':
374 i -= 1
375 assert i >= 0
376 fstr.current_index = i
377 # Where a single '{' is the start of a new expression, a
378 # single '}' is not allowed.
379 astbuilder.raise_syntax_error_known_location("f-string: single '}' is not allowed",
380 token)
381 else:
382 # We're either at a '{', which means we're starting another
383 # expression; or a '}', which means we're at the end of this
384 # f-string (for a nested format_spec).
385 i -= 1
386 break
387 assert 0 <= i <= len(s)
388 # this is in theory true as well, for valid strings:
389 # assert i == len(s) or s[i] == '{' or s[i] == '}'
390 # but for mal-formed escapes it can be false. in that case the
391 # decode_unicode_escape call below produces an error
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 # Return a tuple with the next literal part as a W_Unicode, and optionally the
406 # following expression node. Updates the current index inside 'fstr'.
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 # We're at the end of the string or the end of a nested
413 # f-string: no expression.
414 expr, w_expr_text = None, None
415 else:
416 # We must now be the start of an expression, on a '{'.
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 # In our case, parse_f_string() and fstring_find_literal_and_expr()
424 # could be merged into a single function with a clearer logic. It's
425 # done this way to follow CPython's source code more closely.
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 # add the literal part
432 add_constant_string(astbuilder, joined_pieces, w_u, token)
433 if expr is None:
434 break # We're done with this f-string.
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 # If recurse_lvl is zero, then we must be at the end of the
440 # string. Otherwise, we must be at a right brace.
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 # Remove empty Strs, but always return an ast.JoinedStr object.
451 # In this way it cannot be grabbed later for being used as a
452 # docstring. In codegen.py we still special-case length-1 lists
453 # and avoid calling "BUILD_STRING 1" in this case.
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 # u'' prefix can not be combined with
475 # any other specifier, so it's safe to
476 # check the initial letter for determining.
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 # Produce CPython-compatible message: "Non-UTF-8 code starting with '\xNN'"
487 # only when the error is from UTF-8 decoding of source content,
488 # not from other codecs (e.g. unicodeescape).
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 # fall through to generic unicode error handling for other codecs
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 # Unicode/ValueError/SyntaxError (without position information) in
516 # literal: turn into SyntaxError with position information
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: # <= the common path
522 return joined_pieces[0] # ast.Constant or FormattedValue
523
524 # with more than one piece, it is a combination of ast.Constant[str]
525 # and FormattedValue pieces --- if there is a bytes value, then we got
526 # an invalid mixture of bytes and unicode literals
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