| 1 |
""" Base class with all the support code of the rpython peg parser """ |
| 2 |
|
| 3 |
import io |
| 4 |
import os |
| 5 |
import sys |
| 6 |
|
| 7 |
from pypy.interpreter.pyparser.pygram import tokens |
| 8 |
from pypy.interpreter.pyparser.parser import Token |
| 9 |
from pypy.interpreter.pyparser import pytokenizer as tokenize, pytoken |
| 10 |
from pypy.interpreter.pyparser.error import SyntaxError, IndentationError |
| 11 |
|
| 12 |
from pypy.interpreter.astcompiler import ast |
| 13 |
from pypy.interpreter.astcompiler.astbuilder import parse_number |
| 14 |
from pypy.interpreter.astcompiler import asthelpers |
| 15 |
from pypy.interpreter.astcompiler import consts, misc |
| 16 |
|
| 17 |
from rpython.rlib.objectmodel import specialize |
| 18 |
|
| 19 |
Load = ast.Load |
| 20 |
Store = ast.Store |
| 21 |
Del = ast.Del |
| 22 |
|
| 23 |
class BaseMemoEntry(object): |
| 24 |
_attrs_ = ['endmark', 'next'] |
| 25 |
def __init__(self, endmark, next): |
| 26 |
self.endmark = endmark |
| 27 |
self.next = next |
| 28 |
|
| 29 |
def find_memo(tok, cls): |
| 30 |
memo = tok.memo |
| 31 |
while memo: |
| 32 |
if type(memo) is cls: |
| 33 |
return memo |
| 34 |
memo = memo.next |
| 35 |
return None |
| 36 |
|
| 37 |
def shorttok(tok): |
| 38 |
return "%-25.25s" % ("%s.%s: %s:%r" % (tok.lineno, tok.column, tok.token_type, tok.value)) |
| 39 |
|
| 40 |
def log_start(self, method_name): |
| 41 |
fill = " " * self._level |
| 42 |
print "%s%s() .... (looking at %s)" % (fill, method_name, self.showpeek()) |
| 43 |
self._level += 1 |
| 44 |
|
| 45 |
def log_end(self, method_name, result): |
| 46 |
self._level -= 1 |
| 47 |
fill = " " * self._level |
| 48 |
print "%s... %s(%s) --> %s" % (fill, method_name, result) |
| 49 |
|
| 50 |
def make_memo_class(method_name): |
| 51 |
class MemoEntry(BaseMemoEntry): |
| 52 |
_attrs_ = ['tree'] |
| 53 |
def __init__(self, tree, endmark, next): |
| 54 |
BaseMemoEntry.__init__(self, endmark, next) |
| 55 |
self.tree = tree |
| 56 |
MemoEntry.__name__ += "_" + "method_name" |
| 57 |
return MemoEntry |
| 58 |
|
| 59 |
def memoize(method): |
| 60 |
"""Memoize a symbol method.""" |
| 61 |
method_name = method.__name__ |
| 62 |
MemoEntry = make_memo_class(method_name) |
| 63 |
|
| 64 |
def memoize_wrapper(self): |
| 65 |
tok = self.peek() |
| 66 |
memo = find_memo(tok, MemoEntry) |
| 67 |
|
| 68 |
fill = '' |
| 69 |
if memo: |
| 70 |
assert isinstance(memo, MemoEntry) |
| 71 |
self._reset(memo.endmark) |
| 72 |
return memo.tree |
| 73 |
|
| 74 |
verbose = self._verbose |
| 75 |
if verbose: |
| 76 |
fill = " " * self._level |
| 77 |
print "%s%s() .... (looking at %s)" % (fill, method_name, self.showpeek()) |
| 78 |
self._level += 1 |
| 79 |
tree = method(self) |
| 80 |
if verbose: |
| 81 |
self._level -= 1 |
| 82 |
print "%s... %s() --> %s" % (fill, method_name, tree) |
| 83 |
endmark = self._mark() |
| 84 |
tok.memo = MemoEntry(tree, endmark, tok.memo) |
| 85 |
return tree |
| 86 |
|
| 87 |
memoize_wrapper.__wrapped__ = method |
| 88 |
return memoize_wrapper |
| 89 |
|
| 90 |
|
| 91 |
def memoize_left_rec(method): |
| 92 |
"""Memoize a left-recursive symbol method.""" |
| 93 |
method_name = method.__name__ |
| 94 |
MemoEntry = make_memo_class(method_name) |
| 95 |
|
| 96 |
def memoize_left_rec_wrapper(self): |
| 97 |
mark = self._mark() |
| 98 |
tok = self.peek() |
| 99 |
memo = find_memo(tok, MemoEntry) |
| 100 |
|
| 101 |
if memo: |
| 102 |
assert isinstance(memo, MemoEntry) |
| 103 |
self._reset(memo.endmark) |
| 104 |
return memo.tree |
| 105 |
fill = " " * self._level |
| 106 |
|
| 107 |
verbose = self._verbose |
| 108 |
if verbose: |
| 109 |
print "%s%s .... (looking at %s)" % (fill, method_name, self.showpeek()) |
| 110 |
self._level += 1 |
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
memo = tok.memo = MemoEntry(None, mark, tok.memo) |
| 122 |
lastresult, lastmark = None, mark |
| 123 |
depth = 0 |
| 124 |
if verbose: |
| 125 |
print "%sRecursive %s at %s depth %s" % (fill, method_name, mark, depth) |
| 126 |
|
| 127 |
while True: |
| 128 |
self._reset(mark) |
| 129 |
self.in_recursive_rule += 1 |
| 130 |
try: |
| 131 |
result = method(self) |
| 132 |
finally: |
| 133 |
self.in_recursive_rule -= 1 |
| 134 |
endmark = self._mark() |
| 135 |
depth += 1 |
| 136 |
if verbose: |
| 137 |
print "%sRecursive %s at %s depth %s: %.200s to %s" % (fill, method_name, mark, depth, result, endmark) |
| 138 |
if not result: |
| 139 |
if verbose: |
| 140 |
print "%sFail with %.200s to %s" % (fill, lastresult, lastmark) |
| 141 |
break |
| 142 |
if endmark <= lastmark: |
| 143 |
if verbose: |
| 144 |
print "%sBailing with %.200s to %s" % (fill, lastresult, lastmark) |
| 145 |
break |
| 146 |
memo.tree, memo.endmark = lastresult, lastmark = result, endmark |
| 147 |
|
| 148 |
self._reset(lastmark) |
| 149 |
tree = lastresult |
| 150 |
|
| 151 |
self._level -= 1 |
| 152 |
if verbose: |
| 153 |
print "%s... %s() --> %s [cached]" % (fill, method_name, tree) |
| 154 |
if tree: |
| 155 |
endmark = self._mark() |
| 156 |
else: |
| 157 |
endmark = mark |
| 158 |
self._reset(endmark) |
| 159 |
memo.tree, memo.endmark = tree, endmark |
| 160 |
return tree |
| 161 |
|
| 162 |
memoize_left_rec_wrapper.__wrapped__ = method |
| 163 |
return memoize_left_rec_wrapper |
| 164 |
|
| 165 |
def without_invalid(func): |
| 166 |
def without_invalid_wrapper(self): |
| 167 |
old = self.call_invalid_rules |
| 168 |
try: |
| 169 |
return func(self) |
| 170 |
finally: |
| 171 |
self.call_invalid_rules = old |
| 172 |
without_invalid_wrapper.func_name = func.func_name + "_without_invalid_wrapper" |
| 173 |
return without_invalid_wrapper |
| 174 |
|
| 175 |
def isspace(s): |
| 176 |
res = True |
| 177 |
for c in s: |
| 178 |
if not c.isspace(): |
| 179 |
res = False |
| 180 |
return res |
| 181 |
|
| 182 |
class NameDefaultPair(object): |
| 183 |
def __init__(self, arg, value): |
| 184 |
self.arg = arg |
| 185 |
self.value = value |
| 186 |
|
| 187 |
class StarEtc(object): |
| 188 |
def __init__(self, vararg, kwonlyargs, kwarg): |
| 189 |
self.vararg = vararg |
| 190 |
self.kwonlyargs = kwonlyargs |
| 191 |
self.kwarg = kwarg |
| 192 |
|
| 193 |
class SlashWithDefault(object): |
| 194 |
def __init__(self, plain_names, names_with_defaults): |
| 195 |
self.plain_names = plain_names |
| 196 |
self.names_with_defaults = names_with_defaults |
| 197 |
|
| 198 |
class DictDisplaysEntry(object): |
| 199 |
def __init__(self, key, value): |
| 200 |
self.key = key |
| 201 |
self.value = value |
| 202 |
|
| 203 |
class CmpopExprPair(object): |
| 204 |
def __init__(self, cmpop, expr): |
| 205 |
self.cmpop = cmpop |
| 206 |
self.expr = expr |
| 207 |
|
| 208 |
class KeyPatternPair(object): |
| 209 |
def __init__(self, keyword, pattern): |
| 210 |
self.keyword = keyword |
| 211 |
self.pattern = pattern |
| 212 |
|
| 213 |
class Parser: |
| 214 |
"""Parsing base class.""" |
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
def __init__(self, space, tokenlist, compile_info, verbose=False): |
| 221 |
|
| 222 |
self._tokens = [] |
| 223 |
self._lines = {} |
| 224 |
self._path = "" |
| 225 |
self.type_ignores = [] |
| 226 |
self.compile_info = compile_info |
| 227 |
self._warnings = [] |
| 228 |
for tok in tokenlist: |
| 229 |
|
| 230 |
if tok.token_type == tokens.TYPE_IGNORE: |
| 231 |
self.type_ignores.append(tok) |
| 232 |
continue |
| 233 |
if tok.token_type in (tokens.NL, tokens.COMMENT): |
| 234 |
continue |
| 235 |
if tok.token_type == tokens.ERRORTOKEN and isspace(tok.value): |
| 236 |
continue |
| 237 |
if tok.token_type == tokens.WARNING: |
| 238 |
self._warnings.append(tok) |
| 239 |
continue |
| 240 |
if ( |
| 241 |
tok.token_type == tokens.NEWLINE |
| 242 |
and self._tokens |
| 243 |
and self._tokens[-1].token_type == tokens.NEWLINE |
| 244 |
): |
| 245 |
continue |
| 246 |
if tok.token_type == tokens.NAME: |
| 247 |
index = self.KEYWORD_INDICES.get(tok.value, -1) |
| 248 |
if index != -1: |
| 249 |
tok.token_type = index |
| 250 |
tok.memo = None |
| 251 |
self._tokens.append(tok) |
| 252 |
if not self._path and tok.line and tok.lineno not in self._lines: |
| 253 |
self._lines[tok.lineno] = tok.line |
| 254 |
self._index = 0 |
| 255 |
self._highwatermark = 0 |
| 256 |
|
| 257 |
|
| 258 |
self._verbose = verbose |
| 259 |
self._level = 0 |
| 260 |
self._cache = {} |
| 261 |
|
| 262 |
|
| 263 |
self.in_recursive_rule = 0 |
| 264 |
|
| 265 |
self.call_invalid_rules = False |
| 266 |
|
| 267 |
self.py_version = (3, compile_info.feature_version) |
| 268 |
self.space = space |
| 269 |
|
| 270 |
def parse_meth_or_raise(self, meth): |
| 271 |
res = meth(self) |
| 272 |
if res is None: |
| 273 |
tok = self.diagnose() |
| 274 |
if self.compile_info.flags & consts.PyCF_ALLOW_INCOMPLETE_INPUT: |
| 275 |
if self.compile_info.source_ends_with_newline: |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
if (self._highwatermark >= len(self._tokens) - 1 and |
| 282 |
not self._eval_invalid_with_trailing_newline()): |
| 283 |
self.raise_syntax_error_known_location("incomplete input", tok) |
| 284 |
elif (self.compile_info.flags & consts.PyCF_DONT_IMPLY_DEDENT or |
| 285 |
self.compile_info.mode == "eval"): |
| 286 |
|
| 287 |
|
| 288 |
for index in range(self._highwatermark, len(self._tokens)): |
| 289 |
typ = self._tokens[index].token_type |
| 290 |
if (typ != tokens.ENDMARKER and typ != tokens.NEWLINE and |
| 291 |
typ != tokens.DEDENT): |
| 292 |
break |
| 293 |
else: |
| 294 |
if not self._eval_invalid_with_trailing_newline(): |
| 295 |
self.raise_syntax_error_known_location("incomplete input", tok) |
| 296 |
self.reset() |
| 297 |
self.call_invalid_rules = True |
| 298 |
meth(self) |
| 299 |
|
| 300 |
if tok.token_type == tokens.INDENT: |
| 301 |
self.raise_indentation_error("unexpected indent") |
| 302 |
self.raise_syntax_error_known_location("invalid syntax", tok) |
| 303 |
assert res |
| 304 |
|
| 305 |
for tok in self._warnings: |
| 306 |
self.syntax_warn(tok.value, tok) |
| 307 |
return res |
| 308 |
|
| 309 |
def recursive_parse_to_ast(self, str, info): |
| 310 |
from pypy.interpreter.pyparser import pytokenizer as tokenize |
| 311 |
from pypy.interpreter.pyparser import rpypegparse |
| 312 |
tokenlist = tokenize.generate_tokens(str.splitlines(True), 0) |
| 313 |
parser = rpypegparse.PythonParser(self.space, tokenlist, self.compile_info, verbose=False) |
| 314 |
return parser.parse_meth_or_raise(rpypegparse.PythonParser.eval) |
| 315 |
|
| 316 |
def deprecation_warn(self, msg, tok): |
| 317 |
"""Emit a DeprecationWarning (used for invalid escape sequences in strings).""" |
| 318 |
if self.call_invalid_rules: |
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
return |
| 323 |
from pypy.interpreter import error |
| 324 |
from pypy.module._warnings.interp_warnings import warn_explicit |
| 325 |
space = self.space |
| 326 |
try: |
| 327 |
warn_explicit( |
| 328 |
space, space.newtext(msg), |
| 329 |
space.w_DeprecationWarning, |
| 330 |
space.newtext(self.compile_info.filename), |
| 331 |
tok.lineno, |
| 332 |
space.w_None, |
| 333 |
space.w_None, |
| 334 |
space.w_None, |
| 335 |
space.w_None, |
| 336 |
) |
| 337 |
except error.OperationError as e: |
| 338 |
if e.match(space, space.w_DeprecationWarning): |
| 339 |
start_lineno, start_col_offset = self.extract_pos_start(tok) |
| 340 |
end_lineno, end_col_offset = self.extract_pos_end(tok) |
| 341 |
self._raise_syntax_error(msg, start_lineno, start_col_offset, |
| 342 |
end_lineno, end_col_offset) |
| 343 |
else: |
| 344 |
raise |
| 345 |
|
| 346 |
def syntax_warn(self, msg, tok): |
| 347 |
"""Emit a SyntaxWarning (used for invalid numeric literals).""" |
| 348 |
if self.call_invalid_rules: |
| 349 |
return |
| 350 |
from pypy.interpreter import error |
| 351 |
from pypy.module._warnings.interp_warnings import warn_explicit |
| 352 |
space = self.space |
| 353 |
try: |
| 354 |
warn_explicit( |
| 355 |
space, space.newtext(msg), |
| 356 |
space.w_SyntaxWarning, |
| 357 |
space.newtext(self.compile_info.filename), |
| 358 |
tok.lineno, |
| 359 |
space.w_None, |
| 360 |
space.w_None, |
| 361 |
space.w_None, |
| 362 |
space.w_None, |
| 363 |
) |
| 364 |
except error.OperationError as e: |
| 365 |
if e.match(space, space.w_SyntaxWarning): |
| 366 |
self.raise_syntax_error_known_location(msg, tok) |
| 367 |
else: |
| 368 |
raise |
| 369 |
|
| 370 |
|
| 371 |
def parse(self, entry): |
| 372 |
res = entry() |
| 373 |
if res is not None: |
| 374 |
return res |
| 375 |
self.reset() |
| 376 |
self.call_invalid_rules = True |
| 377 |
entry() |
| 378 |
|
| 379 |
def reset(self): |
| 380 |
self._index = 0 |
| 381 |
self._highwatermark = 0 |
| 382 |
|
| 383 |
self._verbose = False |
| 384 |
self._level = 0 |
| 385 |
self._cache = {} |
| 386 |
for tok in self._tokens: |
| 387 |
tok.memo = None |
| 388 |
self.in_recursive_rule = 0 |
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
|
| 393 |
def _mark(self): |
| 394 |
return self._index |
| 395 |
|
| 396 |
def getnext(self): |
| 397 |
"""Return the next token and updates the index.""" |
| 398 |
cached = not self._index == len(self._tokens) |
| 399 |
tok = self.peek() |
| 400 |
self._index += 1 |
| 401 |
self._highwatermark = max(self._highwatermark, self._index) |
| 402 |
if self._verbose: |
| 403 |
self.report(cached, False) |
| 404 |
return tok |
| 405 |
|
| 406 |
def peek(self): |
| 407 |
"""Return the next token *without* updating the index.""" |
| 408 |
assert self._index < len(self._tokens) |
| 409 |
return self._tokens[self._index] |
| 410 |
|
| 411 |
def diagnose(self): |
| 412 |
|
| 413 |
if self._highwatermark >= len(self._tokens): |
| 414 |
self._highwatermark = len(self._tokens) - 1 |
| 415 |
return self._tokens[self._highwatermark] |
| 416 |
|
| 417 |
def _eval_invalid_with_trailing_newline(self): |
| 418 |
"""In eval mode, if the source ended with a newline and the parse |
| 419 |
consumed at least one token, the input is definitively invalid syntax, |
| 420 |
not incomplete. Unclosed-bracket cases are already caught by the |
| 421 |
tokenizer (TokenError) before the parser runs, so no bracket scan is |
| 422 |
needed here. |
| 423 |
CPython: compile("9+\\n", "eval", PyCF_ALLOW_INCOMPLETE_INPUT) raises |
| 424 |
"invalid syntax"; compile("9+", ...) raises "incomplete input". |
| 425 |
codeop appends "\\n" and retries, so this distinction matters. |
| 426 |
""" |
| 427 |
return (self.compile_info.source_ends_with_newline and |
| 428 |
self.compile_info.mode == "eval" and |
| 429 |
self._highwatermark > 0) |
| 430 |
|
| 431 |
def get_last_non_whitespace_token(self): |
| 432 |
tok = self._tokens[0] |
| 433 |
for index in range(self._index - 1, -1, -1): |
| 434 |
tok = self._tokens[index] |
| 435 |
if tok.token_type != tokens.ENDMARKER and ( |
| 436 |
tok.token_type < tokens.NEWLINE or tok.token_type > tokens.DEDENT |
| 437 |
): |
| 438 |
break |
| 439 |
return tok |
| 440 |
|
| 441 |
def get_lines(self, line_numbers): |
| 442 |
"""Retrieve source lines corresponding to line numbers.""" |
| 443 |
if self._lines: |
| 444 |
lines = self._lines |
| 445 |
else: |
| 446 |
|
| 447 |
return [] |
| 448 |
|
| 449 |
return [lines.get(n, "?\n") for n in line_numbers] |
| 450 |
|
| 451 |
def _reset(self, index): |
| 452 |
if index == self._index: |
| 453 |
return |
| 454 |
assert 0 <= index <= len(self._tokens), (index, len(self._tokens)) |
| 455 |
old_index = self._index |
| 456 |
self._index = index |
| 457 |
if self._verbose: |
| 458 |
self.report(True, index < old_index) |
| 459 |
|
| 460 |
def report(self, cached, back): |
| 461 |
if back: |
| 462 |
fill = "-" * self._index + "-" |
| 463 |
elif cached: |
| 464 |
fill = "-" * self._index + ">" |
| 465 |
else: |
| 466 |
fill = "-" * self._index + "*" |
| 467 |
if self._index == 0: |
| 468 |
print("%s (Bof)" % fill) |
| 469 |
else: |
| 470 |
tok = self._tokens[self._index - 1] |
| 471 |
print "%s %s" % (fill, shorttok(tok)) |
| 472 |
|
| 473 |
|
| 474 |
def start(self): |
| 475 |
pass |
| 476 |
|
| 477 |
def showpeek(self): |
| 478 |
tok = self.peek() |
| 479 |
return shorttok(tok) |
| 480 |
|
| 481 |
def name(self): |
| 482 |
tok = self.peek() |
| 483 |
if tok.token_type == tokens.NAME: |
| 484 |
self.getnext() |
| 485 |
return ast.Name( |
| 486 |
id=self.new_identifier(tok.value), |
| 487 |
ctx=Load, |
| 488 |
lineno=tok.lineno, |
| 489 |
col_offset=tok.column, |
| 490 |
end_lineno=tok.end_lineno, |
| 491 |
end_col_offset=tok.end_column, |
| 492 |
) |
| 493 |
return None |
| 494 |
|
| 495 |
def number(self): |
| 496 |
tok = self.peek() |
| 497 |
if tok.token_type == tokens.NUMBER: |
| 498 |
return self.getnext() |
| 499 |
return None |
| 500 |
|
| 501 |
def string(self): |
| 502 |
tok = self.peek() |
| 503 |
if tok.token_type == tokens.STRING: |
| 504 |
return self.getnext() |
| 505 |
return None |
| 506 |
|
| 507 |
def op(self): |
| 508 |
tok = self.peek() |
| 509 |
if tok.token_type == tokens.OP: |
| 510 |
return self.getnext() |
| 511 |
return None |
| 512 |
|
| 513 |
def type_comment(self): |
| 514 |
tok = self.peek() |
| 515 |
space = self.space |
| 516 |
if tok.token_type == tokens.TYPE_COMMENT: |
| 517 |
return space.newtext(self.getnext().value) |
| 518 |
return None |
| 519 |
|
| 520 |
def soft_keyword(self): |
| 521 |
tok = self.peek() |
| 522 |
if tok.token_type == tokens.NAME and tok.value in self.SOFT_KEYWORDS: |
| 523 |
self.getnext() |
| 524 |
return ast.Name( |
| 525 |
id=self.new_identifier(tok.value), |
| 526 |
ctx=Load, |
| 527 |
lineno=tok.lineno, |
| 528 |
col_offset=tok.column, |
| 529 |
end_lineno=tok.end_lineno, |
| 530 |
end_col_offset=tok.end_column, |
| 531 |
) |
| 532 |
return None |
| 533 |
|
| 534 |
def expect(self, type): |
| 535 |
tok = self.peek() |
| 536 |
if tok.value == type: |
| 537 |
return self.getnext() |
| 538 |
if type in pytoken.python_opmap: |
| 539 |
if tok.token_type == pytoken.python_opmap[type]: |
| 540 |
return self.getnext() |
| 541 |
if type in pytoken.python_tokens: |
| 542 |
if tok.token_type == pytoken.python_tokens[type]: |
| 543 |
return self.getnext() |
| 544 |
if tok.token_type == tokens.OP and tok.value == type: |
| 545 |
return self.getnext() |
| 546 |
return None |
| 547 |
|
| 548 |
def expect_type(self, type): |
| 549 |
tok = self.peek() |
| 550 |
if tok.token_type == type: |
| 551 |
return self.getnext() |
| 552 |
|
| 553 |
def expect_forced(self, res, expectation): |
| 554 |
if res is None: |
| 555 |
self.raise_syntax_error("expected " + expectation) |
| 556 |
return res |
| 557 |
|
| 558 |
def positive_lookahead(self, func, *args): |
| 559 |
mark = self._mark() |
| 560 |
ok = func(self, *args) |
| 561 |
self._reset(mark) |
| 562 |
return ok |
| 563 |
|
| 564 |
@specialize.arg(1) |
| 565 |
def negative_lookahead(self, func, *args): |
| 566 |
mark = self._mark() |
| 567 |
ok = func(self, *args) |
| 568 |
self._reset(mark) |
| 569 |
return not ok |
| 570 |
|
| 571 |
@specialize.argtype(3) |
| 572 |
def check_version(self, min_version, error_msg, node): |
| 573 |
"""Check that the python version is high enough for a rule to apply. |
| 574 |
|
| 575 |
""" |
| 576 |
if (self.py_version[0] > min_version[0] or |
| 577 |
(self.py_version[0] == min_version[0] and |
| 578 |
self.py_version[1] >= min_version[1])): |
| 579 |
return node |
| 580 |
else: |
| 581 |
self.raise_syntax_error_known_location( |
| 582 |
"%s only supported in Python %s and above." % (error_msg, min_version), |
| 583 |
node) |
| 584 |
|
| 585 |
def check_version_for_parenthesized_with(self, a, opt, node): |
| 586 |
"""Only version-gate parenthesized with when it's genuinely the new |
| 587 |
syntax: multiple items or a trailing comma. A single expression in |
| 588 |
parens without trailing comma is just expression grouping, valid in |
| 589 |
all Python versions (gh-115881).""" |
| 590 |
if opt or len(a) > 1: |
| 591 |
return self.check_version( |
| 592 |
(3, 9), "Parenthesized with items", node) |
| 593 |
return node |
| 594 |
|
| 595 |
def raise_indentation_error(self, msg): |
| 596 |
"""Raise an indentation error.""" |
| 597 |
if (self.compile_info.flags & consts.PyCF_ALLOW_INCOMPLETE_INPUT and |
| 598 |
msg.startswith("expected an indented block")): |
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
|
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
for index in range(self._index, len(self._tokens)): |
| 608 |
typ = self._tokens[index].token_type |
| 609 |
if (typ != tokens.ENDMARKER and typ != tokens.NEWLINE and |
| 610 |
typ != tokens.DEDENT): |
| 611 |
break |
| 612 |
else: |
| 613 |
msg = "incomplete input" |
| 614 |
self._raise_syntax_error(msg, cls=IndentationError) |
| 615 |
|
| 616 |
def get_expr_name(self, node): |
| 617 |
"""Get a descriptive name for an expression.""" |
| 618 |
return node._get_descr(self.space) |
| 619 |
|
| 620 |
def raise_syntax_error_if_invalid_target(self, node, assignment_type): |
| 621 |
what = self._get_invalid_target(node, assignment_type) |
| 622 |
if what is None: |
| 623 |
return None |
| 624 |
elif assignment_type == "delete": |
| 625 |
msg = "cannot delete " + self.get_expr_name(what) |
| 626 |
else: |
| 627 |
assert assignment_type in ("assign", "for") |
| 628 |
msg = "cannot assign to " + self.get_expr_name(what) |
| 629 |
self.raise_syntax_error_known_location(msg, what) |
| 630 |
|
| 631 |
def _get_invalid_target(self, node, assignment_type): |
| 632 |
def loop(self, lst, assignment_type): |
| 633 |
for elt in lst: |
| 634 |
elt = self._get_invalid_target(elt, assignment_type) |
| 635 |
if elt is not None: |
| 636 |
return elt |
| 637 |
return None |
| 638 |
if isinstance(node, ast.List): |
| 639 |
if node.elts is None: |
| 640 |
return None |
| 641 |
return loop(self, node.elts, assignment_type) |
| 642 |
elif isinstance(node, ast.Tuple): |
| 643 |
if node.elts is None: |
| 644 |
return None |
| 645 |
return loop(self, node.elts, assignment_type) |
| 646 |
elif isinstance(node, ast.Starred): |
| 647 |
if assignment_type == "delete": |
| 648 |
return node |
| 649 |
return self._get_invalid_target(node.value, assignment_type) |
| 650 |
elif isinstance(node, ast.Compare): |
| 651 |
if assignment_type == "for": |
| 652 |
if node.ops[0] == ast.In: |
| 653 |
return self._get_invalid_target(node.left, "assign") |
| 654 |
return None |
| 655 |
return node |
| 656 |
elif isinstance(node, ast.Name): |
| 657 |
return None |
| 658 |
elif isinstance(node, ast.Subscript): |
| 659 |
return None |
| 660 |
elif isinstance(node, ast.Attribute): |
| 661 |
return None |
| 662 |
else: |
| 663 |
return node |
| 664 |
|
| 665 |
|
| 666 |
def set_expr_context(self, node, context): |
| 667 |
"""make a copy of node, changing context""" |
| 668 |
return node.set_context_copy(context) |
| 669 |
|
| 670 |
def extract_id(self, name): |
| 671 |
if name is None: |
| 672 |
return None |
| 673 |
assert isinstance(name, ast.Name) |
| 674 |
return name.id |
| 675 |
|
| 676 |
def parse_number(self, tok): |
| 677 |
from pypy.interpreter import error |
| 678 |
if "_" in tok.value: |
| 679 |
self.check_version((3, 6), "Underscores in numeric literals are", tok) |
| 680 |
try: |
| 681 |
return parse_number(self.space, tok.value) |
| 682 |
except error.OperationError as e: |
| 683 |
if not e.match(self.space, self.space.w_ValueError): |
| 684 |
raise |
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
msg = self.space.text_w(e.get_w_value(self.space)) |
| 689 |
msg += (" - Consider hexadecimal for huge integer literals " |
| 690 |
"to avoid decimal conversion limits.") |
| 691 |
self.raise_syntax_error_known_location(msg, tok) |
| 692 |
|
| 693 |
def get_last(self, l): |
| 694 |
if not l: |
| 695 |
return None |
| 696 |
return l[-1] |
| 697 |
|
| 698 |
def check_last_keyword_no_arg(self, args): |
| 699 |
if not args.keywords: |
| 700 |
return False |
| 701 |
kw = args.keywords[-1] |
| 702 |
assert isinstance(kw, ast.keyword) |
| 703 |
return kw.arg is None |
| 704 |
|
| 705 |
def new_identifier(self, name): |
| 706 |
return misc.new_identifier(self.space, name) |
| 707 |
|
| 708 |
def ensure_real(self, tok): |
| 709 |
w_number = self.parse_number(tok) |
| 710 |
if self.space.is_w(self.space.type(w_number), self.space.w_complex): |
| 711 |
self.raise_syntax_error("real number required in complex literal") |
| 712 |
return w_number |
| 713 |
|
| 714 |
def ensure_imaginary(self, tok): |
| 715 |
w_number = self.parse_number(tok) |
| 716 |
if not self.space.is_w(self.space.type(w_number), self.space.w_complex): |
| 717 |
self.raise_syntax_error("imaginary number required in complex literal") |
| 718 |
return w_number |
| 719 |
|
| 720 |
def generate_ast_for_string(self, tokens): |
| 721 |
"""Generate AST nodes for strings.""" |
| 722 |
from pypy.interpreter.astcompiler.fstring import string_parse_literal |
| 723 |
return string_parse_literal(self, tokens) |
| 724 |
|
| 725 |
def extract_import_level(self, tokens): |
| 726 |
"""Extract the relative import level from the tokens preceding the module name. |
| 727 |
|
| 728 |
'.' count for one and '...' for 3. |
| 729 |
|
| 730 |
""" |
| 731 |
level = 0 |
| 732 |
for t in tokens: |
| 733 |
if t.value == ".": |
| 734 |
level += 1 |
| 735 |
else: |
| 736 |
level += 3 |
| 737 |
return level |
| 738 |
|
| 739 |
def set_decorators(self, |
| 740 |
target, |
| 741 |
decorators |
| 742 |
): |
| 743 |
"""Set the decorators on a function or class definition.""" |
| 744 |
|
| 745 |
if isinstance(target, ast.FunctionDef): |
| 746 |
return ast.FunctionDef( |
| 747 |
target.name, |
| 748 |
target.args, |
| 749 |
target.body, |
| 750 |
decorators, |
| 751 |
target.returns, |
| 752 |
target.type_comment, |
| 753 |
*target.location()) |
| 754 |
elif isinstance(target, ast.AsyncFunctionDef): |
| 755 |
return ast.AsyncFunctionDef( |
| 756 |
target.name, |
| 757 |
target.args, |
| 758 |
target.body, |
| 759 |
decorators, |
| 760 |
target.returns, |
| 761 |
target.type_comment, |
| 762 |
*target.location()) |
| 763 |
else: |
| 764 |
assert isinstance(target, ast.ClassDef) |
| 765 |
return ast.ClassDef( |
| 766 |
target.name, |
| 767 |
target.bases, |
| 768 |
target.keywords, |
| 769 |
target.body, |
| 770 |
decorators, |
| 771 |
*target.location()) |
| 772 |
return target |
| 773 |
|
| 774 |
def get_comparison_ops(self, pairs): |
| 775 |
return [p.cmpop for p in pairs] |
| 776 |
|
| 777 |
def get_comparators(self, pairs): |
| 778 |
return [p.expr for p in pairs] |
| 779 |
|
| 780 |
def get_pattern_keys(self, pairs): |
| 781 |
return [p.keyword for p in pairs] |
| 782 |
|
| 783 |
def get_patterns(self, pairs): |
| 784 |
return [p.pattern for p in pairs] |
| 785 |
|
| 786 |
def get_pattern_names(self, pairs): |
| 787 |
res = [None] * len(pairs) |
| 788 |
for i, p in enumerate(pairs): |
| 789 |
key = p.keyword |
| 790 |
assert isinstance(key, ast.Name) |
| 791 |
res[i] = key.id |
| 792 |
return res |
| 793 |
|
| 794 |
def set_arg_type_comment(self, arg, type_comment): |
| 795 |
if type_comment is None: |
| 796 |
return arg |
| 797 |
return ast.arg( |
| 798 |
arg.arg, |
| 799 |
arg.annotation, |
| 800 |
type_comment, |
| 801 |
*arg.location()) |
| 802 |
|
| 803 |
def name_default_pair(self, arg, value, type_comment): |
| 804 |
arg = self.set_arg_type_comment(arg, type_comment) |
| 805 |
return NameDefaultPair(arg, value) |
| 806 |
|
| 807 |
def make_star_etc(self, a, b, c): |
| 808 |
return StarEtc(a, b, c) |
| 809 |
|
| 810 |
def make_slash_with_default(self, plain_names, names_with_default): |
| 811 |
return SlashWithDefault(plain_names, names_with_default) |
| 812 |
|
| 813 |
def dict_display_entry(self, key, value): |
| 814 |
return DictDisplaysEntry(key, value) |
| 815 |
|
| 816 |
def cmpop_expr_pair(self, cmpop, expr): |
| 817 |
return CmpopExprPair(cmpop, expr) |
| 818 |
|
| 819 |
def key_pattern_pair(self, keyword, pattern): |
| 820 |
return KeyPatternPair(keyword, pattern) |
| 821 |
|
| 822 |
def dummy_name(self, *args): |
| 823 |
return ast.Name( |
| 824 |
id="dummy%s" % (len(args), ), |
| 825 |
ctx=Load, |
| 826 |
lineno=1, |
| 827 |
col_offset=0, |
| 828 |
end_lineno=1, |
| 829 |
end_col_offset=0, |
| 830 |
) |
| 831 |
|
| 832 |
def get_names(self, names_with_defaults): |
| 833 |
if names_with_defaults is None: |
| 834 |
return [] |
| 835 |
return [p.arg for p in names_with_defaults] |
| 836 |
|
| 837 |
def get_defaults(self, names_with_defaults): |
| 838 |
if names_with_defaults is None: |
| 839 |
return [] |
| 840 |
return [p.value for p in names_with_defaults] |
| 841 |
|
| 842 |
def make_posonlyargs(self, slash_without_default, slash_with_default): |
| 843 |
if slash_without_default is not None: |
| 844 |
return slash_without_default |
| 845 |
elif slash_with_default is not None: |
| 846 |
names = self.get_names(slash_with_default.names_with_defaults) |
| 847 |
return slash_with_default.plain_names + names |
| 848 |
else: |
| 849 |
return [] |
| 850 |
|
| 851 |
def make_posargs(self, plain_names, names_with_default): |
| 852 |
if plain_names is None: |
| 853 |
plain_names = [] |
| 854 |
names = self.get_names(names_with_default) |
| 855 |
return plain_names + names |
| 856 |
|
| 857 |
def make_arguments(self, |
| 858 |
slash_without_default, |
| 859 |
slash_with_default, |
| 860 |
plain_names, |
| 861 |
names_with_default, |
| 862 |
star_etc, |
| 863 |
): |
| 864 |
"""Build a function definition arguments.""" |
| 865 |
if slash_without_default or slash_with_default: |
| 866 |
if slash_without_default: |
| 867 |
arg = slash_without_default[-1] |
| 868 |
else: |
| 869 |
assert slash_with_default |
| 870 |
arg = slash_with_default.names_with_defaults[-1].arg |
| 871 |
self.check_version( |
| 872 |
(3, 8), "Positional only arguments are", arg) |
| 873 |
posonlyargs = self.make_posonlyargs( |
| 874 |
slash_without_default, slash_with_default) |
| 875 |
posargs = self.make_posargs(plain_names, names_with_default) |
| 876 |
|
| 877 |
posdefaults = (self.get_defaults(slash_with_default.names_with_defaults) |
| 878 |
if slash_with_default else []) |
| 879 |
posdefaults.extend(self.get_defaults(names_with_default)) |
| 880 |
|
| 881 |
vararg = star_etc.vararg if star_etc else None |
| 882 |
|
| 883 |
kwonlyargs = self.get_names(star_etc.kwonlyargs) if star_etc else [] |
| 884 |
kwdefaults = self.get_defaults(star_etc.kwonlyargs) if star_etc else [] |
| 885 |
kwarg = star_etc.kwarg if star_etc else None |
| 886 |
|
| 887 |
return ast.arguments( |
| 888 |
posonlyargs=posonlyargs if posonlyargs else None, |
| 889 |
args=posargs if posargs else None, |
| 890 |
defaults=posdefaults if posdefaults else None, |
| 891 |
vararg=vararg, |
| 892 |
kwonlyargs=kwonlyargs if kwonlyargs else None, |
| 893 |
kw_defaults=kwdefaults if kwdefaults else None, |
| 894 |
kwarg=kwarg |
| 895 |
) |
| 896 |
|
| 897 |
def _raise_syntax_error( |
| 898 |
self, |
| 899 |
message, |
| 900 |
start_lineno=-1, |
| 901 |
start_col_offset=-1, |
| 902 |
end_lineno=-1, |
| 903 |
end_col_offset=-1, |
| 904 |
cls=SyntaxError, |
| 905 |
): |
| 906 |
line_from_token = start_lineno == -1 and end_lineno == -1 |
| 907 |
tok = self.diagnose() |
| 908 |
if start_lineno == -1: |
| 909 |
start_lineno = tok.lineno |
| 910 |
start_col_offset = tok.column |
| 911 |
if end_lineno == -1: |
| 912 |
if tok.end_lineno != -1: |
| 913 |
end_lineno = tok.end_lineno |
| 914 |
end_col_offset = tok.end_column |
| 915 |
else: |
| 916 |
end_lineno = start_lineno |
| 917 |
end_col_offset = start_col_offset |
| 918 |
|
| 919 |
if line_from_token: |
| 920 |
line = tok.line |
| 921 |
else: |
| 922 |
line = "".join( |
| 923 |
self.get_lines(range(start_lineno, end_lineno + 1)) |
| 924 |
) |
| 925 |
raise cls( |
| 926 |
message, |
| 927 |
start_lineno, start_col_offset + 1, line, self.compile_info.filename, |
| 928 |
end_lineno=end_lineno, end_offset=end_col_offset + 1 |
| 929 |
) |
| 930 |
|
| 931 |
@specialize.argtype(1) |
| 932 |
def extract_pos_start(self, node_or_tok): |
| 933 |
if isinstance(node_or_tok, ast.AST): |
| 934 |
return node_or_tok.lineno, node_or_tok.col_offset |
| 935 |
else: |
| 936 |
assert isinstance(node_or_tok, Token) |
| 937 |
return node_or_tok.lineno, node_or_tok.column |
| 938 |
|
| 939 |
@specialize.argtype(1) |
| 940 |
def extract_pos_end(self, node_or_tok): |
| 941 |
if isinstance(node_or_tok, ast.AST): |
| 942 |
return node_or_tok.end_lineno, node_or_tok.end_col_offset |
| 943 |
else: |
| 944 |
assert isinstance(node_or_tok, Token) |
| 945 |
return node_or_tok.end_lineno, node_or_tok.end_column |
| 946 |
|
| 947 |
@specialize.argtype(2, 3) |
| 948 |
def raise_syntax_error_known_range( |
| 949 |
self, |
| 950 |
message, |
| 951 |
start_node_or_tok, |
| 952 |
end_node_or_tok, |
| 953 |
): |
| 954 |
start_lineno, start_col_offset = self.extract_pos_start(start_node_or_tok) |
| 955 |
end_lineno, end_col_offset = self.extract_pos_end(end_node_or_tok) |
| 956 |
self._raise_syntax_error(message, start_lineno, start_col_offset, end_lineno, end_col_offset) |
| 957 |
|
| 958 |
@specialize.argtype(2) |
| 959 |
def raise_syntax_error_starting_from( |
| 960 |
self, |
| 961 |
message, |
| 962 |
start_node_or_tok, |
| 963 |
): |
| 964 |
start_lineno, start_col_offset = self.extract_pos_start(start_node_or_tok) |
| 965 |
self._raise_syntax_error(message, start_lineno, start_col_offset, -1, -1) |
| 966 |
|
| 967 |
def raise_syntax_error(self, message): |
| 968 |
self._raise_syntax_error(message) |
| 969 |
|
| 970 |
@specialize.argtype(2) |
| 971 |
def raise_syntax_error_known_location( |
| 972 |
self, |
| 973 |
message, |
| 974 |
node_or_tok, |
| 975 |
): |
| 976 |
"""Raise a syntax error that occured at a given AST node or Token.""" |
| 977 |
start_lineno, start_col_offset = self.extract_pos_start(node_or_tok) |
| 978 |
end_lineno, end_col_offset = self.extract_pos_end(node_or_tok) |
| 979 |
|
| 980 |
|
| 981 |
if end_lineno > start_lineno: |
| 982 |
start_lineno = end_lineno |
| 983 |
start_col_offset = end_col_offset |
| 984 |
self._raise_syntax_error(message, start_lineno, start_col_offset, end_lineno, end_col_offset) |
| 985 |
|
| 986 |
def make_type_ignores(self): |
| 987 |
type_ignores = [] |
| 988 |
for type_ignore in self.type_ignores: |
| 989 |
tag = self.space.newtext(type_ignore.value) |
| 990 |
type_ignores.append(ast.TypeIgnore(type_ignore.lineno, tag)) |
| 991 |
return type_ignores |
| 992 |
|
| 993 |
def check_barry(self, tok): |
| 994 |
flufl = self.compile_info.flags & consts.CO_FUTURE_BARRY_AS_BDFL |
| 995 |
if flufl and tok.value == '!=': |
| 996 |
self.raise_syntax_error_known_location("with Barry as BDFL, use '<>' instead of '!='", tok) |
| 997 |
elif not flufl and tok.value == '<>': |
| 998 |
self.raise_syntax_error_known_location('invalid syntax', tok) |
| 999 |
return tok |
| 1000 |
|
| 1001 |
def kwarg_illegal_assignment(self, a, b): |
| 1002 |
space = self.space |
| 1003 |
if isinstance(a, ast.Constant): |
| 1004 |
if space.is_w(a.value, space.w_True): |
| 1005 |
error = "True" |
| 1006 |
elif space.is_w(a.value, space.w_False): |
| 1007 |
error = "False" |
| 1008 |
elif space.is_w(a.value, space.w_None): |
| 1009 |
error = "None" |
| 1010 |
else: |
| 1011 |
error = None |
| 1012 |
if error is not None: |
| 1013 |
self.raise_syntax_error_known_range( |
| 1014 |
"cannot assign to " + error, a, b, |
| 1015 |
) |
| 1016 |
self.raise_syntax_error_known_range( |
| 1017 |
'expression cannot contain assignment, perhaps you meant "=="?', a, b, |
| 1018 |
) |
| 1019 |
|
| 1020 |
def get_last_comprehension_item(self, comp): |
| 1021 |
assert isinstance(comp, ast.comprehension) |
| 1022 |
if comp.ifs: |
| 1023 |
return comp.ifs[-1] |
| 1024 |
else: |
| 1025 |
return comp.iter |
| 1026 |
|
| 1027 |
def check_nonparen_genexp_in_call(self, msg, a, b): |
| 1028 |
assert isinstance(a, ast.Call) |
| 1029 |
if len(a.args) > 1: |
| 1030 |
self.raise_syntax_error_known_range( |
| 1031 |
msg, |
| 1032 |
a.args[-1], |
| 1033 |
self.get_last_comprehension_item(b[-1])) |
| 1034 |
return None |
| 1035 |
|
| 1036 |
def check_legacy_stmt(self, a): |
| 1037 |
return isinstance(a, ast.Name) and a.id in ('exec', 'print') |
| 1038 |
|
| 1039 |
|
| 1040 |
def revdbmetavar(self, num, lineno, col_offset, end_lineno, end_col_offset): |
| 1041 |
if not self.space.config.translation.reverse_debugger: |
| 1042 |
self._raise_syntax_error("Unknown character", lineno, col_offset, end_lineno, end_col_offset) |
| 1043 |
return ast.RevDBMetaVar(num, lineno, col_offset, end_lineno, end_col_offset) |
| 1044 |
|