| 1 |
""" |
| 2 |
Symbol tabling building. |
| 3 |
""" |
| 4 |
|
| 5 |
from pypy.interpreter.astcompiler import ast, consts, misc |
| 6 |
from pypy.interpreter.pyparser.error import SyntaxError |
| 7 |
|
| 8 |
|
| 9 |
SYM_BLANK = 0 |
| 10 |
SYM_GLOBAL = 1 |
| 11 |
SYM_ASSIGNED = 2 |
| 12 |
SYM_PARAM = 2 << 1 |
| 13 |
SYM_NONLOCAL = 2 << 2 |
| 14 |
SYM_USED = 2 << 3 |
| 15 |
SYM_ANNOTATED = 2 << 4 |
| 16 |
SYM_COMP_ITER = 2 << 5 |
| 17 |
SYM_BOUND = (SYM_PARAM | SYM_ASSIGNED) |
| 18 |
|
| 19 |
|
| 20 |
SCOPE_UNKNOWN = 0 |
| 21 |
SCOPE_GLOBAL_IMPLICIT = 1 |
| 22 |
SCOPE_GLOBAL_EXPLICIT = 2 |
| 23 |
SCOPE_LOCAL = 3 |
| 24 |
SCOPE_FREE = 4 |
| 25 |
SCOPE_CELL = 5 |
| 26 |
SCOPE_CELL_CLASS = 6 |
| 27 |
|
| 28 |
|
| 29 |
class Scope(object): |
| 30 |
|
| 31 |
can_be_optimized = False |
| 32 |
is_coroutine = False |
| 33 |
|
| 34 |
def __init__(self, name, lineno=0, col_offset=0): |
| 35 |
self.lineno = lineno |
| 36 |
self.col_offset = col_offset |
| 37 |
self.parent = None |
| 38 |
self.name = name |
| 39 |
self.optimized = False |
| 40 |
self.symbols = None |
| 41 |
self.roles = {} |
| 42 |
self.varnames = [] |
| 43 |
self.children = [] |
| 44 |
self.free_vars = [] |
| 45 |
self.temp_name_counter = 1 |
| 46 |
self.has_free = False |
| 47 |
self.child_has_free = False |
| 48 |
self.nested = False |
| 49 |
self.doc_removable = False |
| 50 |
self.contains_annotated = False |
| 51 |
self.nonlocal_directives = {} |
| 52 |
self._in_try_body_depth = 0 |
| 53 |
self.comp_iter_target = False |
| 54 |
self.comp_iter_expr = 0 |
| 55 |
|
| 56 |
def error(self, msg, ast_node): |
| 57 |
if ast_node is None: |
| 58 |
lineno = self.lineno |
| 59 |
col_offset = self.col_offset + 1 |
| 60 |
end_lineno = end_col_offset = 0 |
| 61 |
else: |
| 62 |
lineno = ast_node.lineno |
| 63 |
col_offset = ast_node.col_offset + 1 |
| 64 |
end_lineno = ast_node.end_lineno |
| 65 |
end_col_offset = ast_node.end_col_offset + 1 |
| 66 |
raise SyntaxError( |
| 67 |
msg, lineno, col_offset, |
| 68 |
end_lineno=end_lineno, end_offset=end_col_offset) |
| 69 |
|
| 70 |
def lookup(self, name): |
| 71 |
"""Find the scope of identifier 'name'.""" |
| 72 |
return self.symbols.get(self.mangle(name), SCOPE_UNKNOWN) |
| 73 |
|
| 74 |
def lookup_role(self, name): |
| 75 |
return self.roles.get(self.mangle(name), SYM_BLANK) |
| 76 |
|
| 77 |
def new_temporary_name(self): |
| 78 |
"""Return the next temporary name. |
| 79 |
|
| 80 |
This must be in sync with PythonCodeGenerator's counter. |
| 81 |
""" |
| 82 |
self.note_symbol("_[%d]" % (self.temp_name_counter,), SYM_ASSIGNED) |
| 83 |
self.temp_name_counter += 1 |
| 84 |
|
| 85 |
def note_symbol(self, identifier, role, ast_node=None): |
| 86 |
"""Record that identifier occurs in this scope.""" |
| 87 |
mangled = self.mangle(identifier) |
| 88 |
new_role = role |
| 89 |
if mangled in self.roles: |
| 90 |
old_role = self.roles[mangled] |
| 91 |
if old_role & SYM_PARAM and role & SYM_PARAM: |
| 92 |
err = "duplicate argument '%s' in function definition" % \ |
| 93 |
(identifier,) |
| 94 |
self.error(err, ast_node) |
| 95 |
new_role |= old_role |
| 96 |
if self.comp_iter_target: |
| 97 |
if new_role & (SYM_GLOBAL | SYM_NONLOCAL): |
| 98 |
self.error( |
| 99 |
"comprehension inner loop cannot rebind assignment expression target '%s'" % identifier, |
| 100 |
ast_node) |
| 101 |
new_role |= SYM_COMP_ITER |
| 102 |
self.roles[mangled] = new_role |
| 103 |
if role & SYM_PARAM: |
| 104 |
self.varnames.append(mangled) |
| 105 |
return mangled |
| 106 |
|
| 107 |
def note_try_start(self, try_node): |
| 108 |
"""Called when a try is found, before visiting the body.""" |
| 109 |
self._in_try_body_depth += 1 |
| 110 |
|
| 111 |
def note_try_end(self, try_node): |
| 112 |
"""Called after visiting a try body.""" |
| 113 |
self._in_try_body_depth -= 1 |
| 114 |
|
| 115 |
def note_yield(self, yield_node): |
| 116 |
"""Called when a yield is found.""" |
| 117 |
self.error("'yield' outside function", yield_node) |
| 118 |
|
| 119 |
def note_yieldFrom(self, yieldFrom_node): |
| 120 |
"""Called when a yield from is found.""" |
| 121 |
self.error("'yield' outside function", yieldFrom_node) |
| 122 |
|
| 123 |
def note_await(self, await_node): |
| 124 |
"""Called when await is found.""" |
| 125 |
self.error("'await' outside function", await_node) |
| 126 |
|
| 127 |
def note_return(self, ret): |
| 128 |
"""Called when a return statement is found.""" |
| 129 |
pass |
| 130 |
|
| 131 |
def note_import_star(self, imp): |
| 132 |
"""Called when a star import is found.""" |
| 133 |
return False |
| 134 |
|
| 135 |
def mangle(self, name): |
| 136 |
if self.parent: |
| 137 |
return self.parent.mangle(name) |
| 138 |
else: |
| 139 |
return name |
| 140 |
|
| 141 |
def add_child(self, child_scope): |
| 142 |
"""Note a new child scope.""" |
| 143 |
child_scope.parent = self |
| 144 |
self.children.append(child_scope) |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
child_scope.comp_iter_expr = self.comp_iter_expr |
| 149 |
|
| 150 |
def _finalize_name(self, name, flags, local, bound, free, globs): |
| 151 |
"""Decide on the scope of a name.""" |
| 152 |
if flags & SYM_GLOBAL: |
| 153 |
self.symbols[name] = SCOPE_GLOBAL_EXPLICIT |
| 154 |
globs[name] = None |
| 155 |
if bound: |
| 156 |
try: |
| 157 |
del bound[name] |
| 158 |
except KeyError: |
| 159 |
pass |
| 160 |
elif flags & SYM_NONLOCAL: |
| 161 |
if name not in bound: |
| 162 |
err = "no binding for nonlocal '%s' found" % (name,) |
| 163 |
self.error(err, self.nonlocal_directives.get(name, None)) |
| 164 |
self.symbols[name] = SCOPE_FREE |
| 165 |
self.free_vars.append(name) |
| 166 |
free[name] = None |
| 167 |
self.has_free = True |
| 168 |
elif flags & (SYM_BOUND | SYM_ANNOTATED): |
| 169 |
self.symbols[name] = SCOPE_LOCAL |
| 170 |
local[name] = None |
| 171 |
try: |
| 172 |
del globs[name] |
| 173 |
except KeyError: |
| 174 |
pass |
| 175 |
elif bound and name in bound: |
| 176 |
self.symbols[name] = SCOPE_FREE |
| 177 |
self.free_vars.append(name) |
| 178 |
free[name] = None |
| 179 |
self.has_free = True |
| 180 |
elif name in globs: |
| 181 |
self.symbols[name] = SCOPE_GLOBAL_IMPLICIT |
| 182 |
else: |
| 183 |
if self.nested: |
| 184 |
self.has_free = True |
| 185 |
self.symbols[name] = SCOPE_GLOBAL_IMPLICIT |
| 186 |
|
| 187 |
def _pass_on_bindings(self, local, bound, globs, new_bound, new_globs): |
| 188 |
"""Allow child scopes to see names bound here and in outer scopes.""" |
| 189 |
new_globs.update(globs) |
| 190 |
if bound: |
| 191 |
new_bound.update(bound) |
| 192 |
|
| 193 |
def _finalize_cells(self, free): |
| 194 |
"""Hook for FunctionScope.""" |
| 195 |
pass |
| 196 |
|
| 197 |
def _check_optimization(self): |
| 198 |
pass |
| 199 |
|
| 200 |
_hide_bound_from_nested_scopes = False |
| 201 |
|
| 202 |
def finalize(self, bound, free, globs): |
| 203 |
"""Enter final bookeeping data in to self.symbols.""" |
| 204 |
self.symbols = {} |
| 205 |
local = {} |
| 206 |
new_globs = {} |
| 207 |
new_bound = {} |
| 208 |
new_free = {} |
| 209 |
if self._hide_bound_from_nested_scopes: |
| 210 |
self._pass_on_bindings(local, bound, globs, new_bound, new_globs) |
| 211 |
for name, flags in self.roles.iteritems(): |
| 212 |
self._finalize_name(name, flags, local, bound, free, globs) |
| 213 |
if not self._hide_bound_from_nested_scopes: |
| 214 |
self._pass_on_bindings(local, bound, globs, new_bound, new_globs) |
| 215 |
else: |
| 216 |
self._pass_special_names(local, new_bound) |
| 217 |
child_frees = {} |
| 218 |
for child in self.children: |
| 219 |
|
| 220 |
|
| 221 |
child_free = new_free.copy() |
| 222 |
child.finalize(new_bound.copy(), child_free, new_globs.copy()) |
| 223 |
child_frees.update(child_free) |
| 224 |
if child.has_free or child.child_has_free: |
| 225 |
self.child_has_free = True |
| 226 |
new_free.update(child_frees) |
| 227 |
self._finalize_cells(new_free) |
| 228 |
for name in new_free: |
| 229 |
try: |
| 230 |
role_here = self.roles[name] |
| 231 |
except KeyError: |
| 232 |
if bound and name in bound: |
| 233 |
self.symbols[name] = SCOPE_FREE |
| 234 |
self.free_vars.append(name) |
| 235 |
else: |
| 236 |
if role_here & (SYM_BOUND | SYM_GLOBAL) and \ |
| 237 |
self._hide_bound_from_nested_scopes and \ |
| 238 |
not role_here & SYM_NONLOCAL: |
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
self.free_vars.append(name) |
| 245 |
self._check_optimization() |
| 246 |
free.update(new_free) |
| 247 |
|
| 248 |
|
| 249 |
class ModuleScope(Scope): |
| 250 |
|
| 251 |
def __init__(self, allow_top_level_await=False): |
| 252 |
Scope.__init__(self, "<top-level>") |
| 253 |
self.allow_top_level_await = allow_top_level_await |
| 254 |
|
| 255 |
def note_await(self, await_node): |
| 256 |
if not self.allow_top_level_await: |
| 257 |
Scope.note_await(self, await_node) |
| 258 |
|
| 259 |
class FunctionScope(Scope): |
| 260 |
|
| 261 |
can_be_optimized = True |
| 262 |
|
| 263 |
def __init__(self, name, lineno, col_offset): |
| 264 |
Scope.__init__(self, name, lineno, col_offset) |
| 265 |
self.has_variable_arg = False |
| 266 |
self.has_keywords_arg = False |
| 267 |
self.is_generator = False |
| 268 |
self.yield_node = None |
| 269 |
self.has_yield_inside_try = False |
| 270 |
self.optimized = True |
| 271 |
self.return_with_value = False |
| 272 |
self.import_star = None |
| 273 |
|
| 274 |
def note_symbol(self, identifier, role, ast_node=None): |
| 275 |
|
| 276 |
if role == SYM_USED and identifier == 'super': |
| 277 |
self.note_symbol('__class__', SYM_USED, ast_node) |
| 278 |
return Scope.note_symbol(self, identifier, role, ast_node) |
| 279 |
|
| 280 |
def note_yield(self, yield_node): |
| 281 |
self.is_generator = True |
| 282 |
self.yield_node = yield_node |
| 283 |
if self._in_try_body_depth > 0: |
| 284 |
self.has_yield_inside_try = True |
| 285 |
|
| 286 |
def note_yieldFrom(self, yield_node): |
| 287 |
self.is_generator = True |
| 288 |
self.yield_node = yield_node |
| 289 |
if self._in_try_body_depth > 0: |
| 290 |
self.has_yield_inside_try = True |
| 291 |
|
| 292 |
def note_await(self, await_node): |
| 293 |
self.is_coroutine = True |
| 294 |
|
| 295 |
def note_return(self, ret): |
| 296 |
if ret.value: |
| 297 |
self.return_with_value = True |
| 298 |
self.ret = ret |
| 299 |
|
| 300 |
def note_import_star(self, imp): |
| 301 |
return True |
| 302 |
|
| 303 |
def note_variable_arg(self, vararg): |
| 304 |
self.has_variable_arg = True |
| 305 |
|
| 306 |
def note_keywords_arg(self, kwarg): |
| 307 |
self.has_keywords_arg = True |
| 308 |
|
| 309 |
def add_child(self, child_scope): |
| 310 |
Scope.add_child(self, child_scope) |
| 311 |
child_scope.nested = True |
| 312 |
|
| 313 |
def _pass_on_bindings(self, local, bound, globs, new_bound, new_globs): |
| 314 |
new_bound.update(local) |
| 315 |
Scope._pass_on_bindings(self, local, bound, globs, new_bound, |
| 316 |
new_globs) |
| 317 |
|
| 318 |
def _finalize_cells(self, free): |
| 319 |
for name, role in self.symbols.iteritems(): |
| 320 |
if role == SCOPE_LOCAL and name in free: |
| 321 |
self.symbols[name] = SCOPE_CELL |
| 322 |
del free[name] |
| 323 |
|
| 324 |
def _check_optimization(self): |
| 325 |
if (self.has_free or self.child_has_free) and not self.optimized: |
| 326 |
raise AssertionError("unknown reason for unoptimization") |
| 327 |
|
| 328 |
|
| 329 |
class AsyncFunctionScope(FunctionScope): |
| 330 |
|
| 331 |
def __init__(self, name, lineno, col_offset): |
| 332 |
FunctionScope.__init__(self, name, lineno, col_offset) |
| 333 |
self.is_coroutine = True |
| 334 |
|
| 335 |
def note_yieldFrom(self, yield_node): |
| 336 |
self.error("'yield from' inside async function", yield_node) |
| 337 |
|
| 338 |
|
| 339 |
class ComprehensionScope(FunctionScope): |
| 340 |
pass |
| 341 |
|
| 342 |
class ClassScope(Scope): |
| 343 |
|
| 344 |
_hide_bound_from_nested_scopes = True |
| 345 |
|
| 346 |
def __init__(self, clsdef): |
| 347 |
Scope.__init__(self, clsdef.name, clsdef.lineno, clsdef.col_offset) |
| 348 |
|
| 349 |
def mangle(self, name): |
| 350 |
return misc.mangle(name, self.name) |
| 351 |
|
| 352 |
def _pass_special_names(self, local, new_bound): |
| 353 |
|
| 354 |
new_bound['__class__'] = None |
| 355 |
|
| 356 |
def _finalize_cells(self, free): |
| 357 |
for name, role in self.symbols.iteritems(): |
| 358 |
if role == SCOPE_LOCAL and name in free and name == '__class__': |
| 359 |
self.symbols[name] = SCOPE_CELL_CLASS |
| 360 |
del free[name] |
| 361 |
|
| 362 |
|
| 363 |
class SymtableBuilder(ast.GenericASTVisitor): |
| 364 |
"""Find symbol information from AST.""" |
| 365 |
|
| 366 |
def __init__(self, space, module, compile_info): |
| 367 |
self.space = space |
| 368 |
self.module = module |
| 369 |
self.compile_info = compile_info |
| 370 |
self.scopes = {} |
| 371 |
self.scope = None |
| 372 |
self.stack = [] |
| 373 |
allow_top_level_await = compile_info.flags & consts.PyCF_ALLOW_TOP_LEVEL_AWAIT |
| 374 |
top = ModuleScope(allow_top_level_await=allow_top_level_await) |
| 375 |
self.globs = top.roles |
| 376 |
self.push_scope(top, module) |
| 377 |
try: |
| 378 |
module.walkabout(self) |
| 379 |
top.finalize(None, {}, {}) |
| 380 |
except SyntaxError as e: |
| 381 |
e.filename = compile_info.filename |
| 382 |
raise |
| 383 |
self.pop_scope() |
| 384 |
assert not self.stack |
| 385 |
|
| 386 |
def error(self, msg, node): |
| 387 |
|
| 388 |
raise SyntaxError(msg, node.lineno, node.col_offset + 1, |
| 389 |
filename=self.compile_info.filename, |
| 390 |
end_lineno=node.end_lineno, |
| 391 |
end_offset=node.end_col_offset + 1) |
| 392 |
|
| 393 |
def push_scope(self, scope, node): |
| 394 |
"""Push a child scope.""" |
| 395 |
if self.stack: |
| 396 |
self.stack[-1].add_child(scope) |
| 397 |
self.stack.append(scope) |
| 398 |
self.scopes[node] = scope |
| 399 |
|
| 400 |
self.scope = scope |
| 401 |
|
| 402 |
def pop_scope(self): |
| 403 |
self.stack.pop() |
| 404 |
if self.stack: |
| 405 |
self.scope = self.stack[-1] |
| 406 |
else: |
| 407 |
self.scope = None |
| 408 |
|
| 409 |
def find_scope(self, scope_node): |
| 410 |
"""Lookup the scope for a given AST node.""" |
| 411 |
return self.scopes[scope_node] |
| 412 |
|
| 413 |
def implicit_arg(self, pos): |
| 414 |
"""Note a implicit arg for implicit tuple unpacking.""" |
| 415 |
name = ".%d" % (pos,) |
| 416 |
self.note_symbol(name, SYM_PARAM) |
| 417 |
|
| 418 |
def note_symbol(self, identifier, role, ast_node=None): |
| 419 |
"""Note the identifer on the current scope.""" |
| 420 |
mangled = self.scope.note_symbol(identifier, role, ast_node) |
| 421 |
if role & SYM_GLOBAL: |
| 422 |
if mangled in self.globs: |
| 423 |
role |= self.globs[mangled] |
| 424 |
self.globs[mangled] = role |
| 425 |
|
| 426 |
def visit_FunctionDef(self, func): |
| 427 |
self.note_symbol(func.name, SYM_ASSIGNED) |
| 428 |
|
| 429 |
args = func.args |
| 430 |
assert isinstance(args, ast.arguments) |
| 431 |
self.visit_sequence(args.defaults) |
| 432 |
self.visit_kwonlydefaults(args.kw_defaults) |
| 433 |
self._visit_annotations(func) |
| 434 |
self.visit_sequence(func.decorator_list) |
| 435 |
new_scope = FunctionScope(func.name, func.lineno, func.col_offset) |
| 436 |
self.push_scope(new_scope, func) |
| 437 |
func.args.walkabout(self) |
| 438 |
self.visit_sequence(func.body) |
| 439 |
self.pop_scope() |
| 440 |
|
| 441 |
def visit_AsyncFunctionDef(self, func): |
| 442 |
self.note_symbol(func.name, SYM_ASSIGNED) |
| 443 |
|
| 444 |
args = func.args |
| 445 |
assert isinstance(args, ast.arguments) |
| 446 |
self.visit_sequence(args.defaults) |
| 447 |
self.visit_kwonlydefaults(args.kw_defaults) |
| 448 |
self._visit_annotations(func) |
| 449 |
self.visit_sequence(func.decorator_list) |
| 450 |
new_scope = AsyncFunctionScope(func.name, func.lineno, func.col_offset) |
| 451 |
self.push_scope(new_scope, func) |
| 452 |
func.args.walkabout(self) |
| 453 |
self.visit_sequence(func.body) |
| 454 |
self.pop_scope() |
| 455 |
|
| 456 |
def visit_Await(self, aw): |
| 457 |
self.scope.note_await(aw) |
| 458 |
ast.GenericASTVisitor.visit_Await(self, aw) |
| 459 |
|
| 460 |
def visit_Return(self, ret): |
| 461 |
self.scope.note_return(ret) |
| 462 |
ast.GenericASTVisitor.visit_Return(self, ret) |
| 463 |
|
| 464 |
def visit_AnnAssign(self, assign): |
| 465 |
|
| 466 |
if not isinstance(self.scope, FunctionScope): |
| 467 |
self.scope.contains_annotated = True |
| 468 |
target = assign.target |
| 469 |
if isinstance(target, ast.Name): |
| 470 |
name = target.id |
| 471 |
old_role = self.scope.lookup_role(name) |
| 472 |
if assign.simple and self.scope is not self.stack[0]: |
| 473 |
if old_role & SYM_GLOBAL: |
| 474 |
self.error( |
| 475 |
"annotated name '%s' can't be global" % name, |
| 476 |
assign) |
| 477 |
if old_role & SYM_NONLOCAL: |
| 478 |
self.error( |
| 479 |
"annotated name '%s' can't be nonlocal" % name, |
| 480 |
assign) |
| 481 |
scope = SYM_BLANK |
| 482 |
if assign.simple: |
| 483 |
scope |= SYM_ANNOTATED |
| 484 |
if assign.value: |
| 485 |
scope |= SYM_ASSIGNED |
| 486 |
if scope: |
| 487 |
self.note_symbol(name, scope) |
| 488 |
else: |
| 489 |
target.walkabout(self) |
| 490 |
if assign.value is not None: |
| 491 |
assign.value.walkabout(self) |
| 492 |
if assign.annotation is not None: |
| 493 |
assign.annotation.walkabout(self) |
| 494 |
|
| 495 |
def visit_ClassDef(self, clsdef): |
| 496 |
self.note_symbol(clsdef.name, SYM_ASSIGNED) |
| 497 |
self.visit_sequence(clsdef.bases) |
| 498 |
self.visit_sequence(clsdef.keywords) |
| 499 |
self.visit_sequence(clsdef.decorator_list) |
| 500 |
self.push_scope(ClassScope(clsdef), clsdef) |
| 501 |
self.note_symbol('__class__', SYM_ASSIGNED) |
| 502 |
self.note_symbol('__locals__', SYM_PARAM) |
| 503 |
self.visit_sequence(clsdef.body) |
| 504 |
self.pop_scope() |
| 505 |
|
| 506 |
def visit_ImportFrom(self, imp): |
| 507 |
for alias in imp.names: |
| 508 |
node = self._visit_alias(alias) |
| 509 |
if node: |
| 510 |
if self.scope.note_import_star(imp): |
| 511 |
msg = "import * only allowed at module level" |
| 512 |
self.error(msg, node) |
| 513 |
|
| 514 |
def _visit_alias(self, alias): |
| 515 |
assert isinstance(alias, ast.alias) |
| 516 |
if alias.asname: |
| 517 |
store_name = alias.asname |
| 518 |
else: |
| 519 |
store_name = alias.name |
| 520 |
if store_name == "*": |
| 521 |
return alias |
| 522 |
dot = store_name.find(".") |
| 523 |
if dot > 0: |
| 524 |
store_name = store_name[:dot] |
| 525 |
self.note_symbol(store_name, SYM_ASSIGNED) |
| 526 |
return None |
| 527 |
|
| 528 |
def visit_alias(self, alias): |
| 529 |
self._visit_alias(alias) |
| 530 |
|
| 531 |
def visit_ExceptHandler(self, handler): |
| 532 |
if handler.name: |
| 533 |
self.note_symbol(handler.name, SYM_ASSIGNED) |
| 534 |
ast.GenericASTVisitor.visit_ExceptHandler(self, handler) |
| 535 |
|
| 536 |
def visit_Yield(self, yie): |
| 537 |
self.scope.note_yield(yie) |
| 538 |
ast.GenericASTVisitor.visit_Yield(self, yie) |
| 539 |
|
| 540 |
def visit_YieldFrom(self, yfr): |
| 541 |
self.scope.note_yieldFrom(yfr) |
| 542 |
ast.GenericASTVisitor.visit_YieldFrom(self, yfr) |
| 543 |
|
| 544 |
def visit_Global(self, glob): |
| 545 |
for name in glob.names: |
| 546 |
old_role = self.scope.lookup_role(name) |
| 547 |
if (self.scope._hide_bound_from_nested_scopes and |
| 548 |
name == '__class__'): |
| 549 |
msg = ("'global __class__' inside a class statement is not " |
| 550 |
"implemented in PyPy") |
| 551 |
self.error(msg, glob) |
| 552 |
if old_role & SYM_PARAM: |
| 553 |
msg = "name '%s' is parameter and global" % (name,) |
| 554 |
self.error(msg, glob) |
| 555 |
if old_role & SYM_NONLOCAL: |
| 556 |
msg = "name '%s' is nonlocal and global" % (name,) |
| 557 |
self.error(msg, glob) |
| 558 |
|
| 559 |
if old_role & (SYM_USED | SYM_ASSIGNED | SYM_ANNOTATED): |
| 560 |
if old_role & SYM_ASSIGNED: |
| 561 |
msg = "name '%s' is assigned to before global declaration"\ |
| 562 |
% (name,) |
| 563 |
elif old_role & SYM_ANNOTATED: |
| 564 |
msg = "annotated name '%s' can't be global" \ |
| 565 |
% (name,) |
| 566 |
else: |
| 567 |
msg = "name '%s' is used prior to global declaration" % \ |
| 568 |
(name,) |
| 569 |
self.error(msg, glob) |
| 570 |
self.note_symbol(name, SYM_GLOBAL) |
| 571 |
|
| 572 |
def visit_Nonlocal(self, nonl): |
| 573 |
for name in nonl.names: |
| 574 |
old_role = self.scope.lookup_role(name) |
| 575 |
msg = "" |
| 576 |
if old_role & SYM_GLOBAL: |
| 577 |
msg = "name '%s' is nonlocal and global" % (name,) |
| 578 |
if old_role & SYM_PARAM: |
| 579 |
msg = "name '%s' is parameter and nonlocal" % (name,) |
| 580 |
if isinstance(self.scope, ModuleScope): |
| 581 |
msg = "nonlocal declaration not allowed at module level" |
| 582 |
if old_role & SYM_ANNOTATED: |
| 583 |
msg = "annotated name '%s' can't be nonlocal" \ |
| 584 |
% (name,) |
| 585 |
if msg is not "": |
| 586 |
self.error(msg, nonl) |
| 587 |
|
| 588 |
if (old_role & (SYM_USED | SYM_ASSIGNED) and not |
| 589 |
(name == '__class__' and |
| 590 |
self.scope._hide_bound_from_nested_scopes)): |
| 591 |
if old_role & SYM_ASSIGNED: |
| 592 |
msg = "name '%s' is assigned to before nonlocal declaration" \ |
| 593 |
% (name,) |
| 594 |
else: |
| 595 |
msg = "name '%s' is used prior to nonlocal declaration" % \ |
| 596 |
(name,) |
| 597 |
self.error(msg, nonl) |
| 598 |
|
| 599 |
self.note_symbol(name, SYM_NONLOCAL) |
| 600 |
if name not in self.scope.nonlocal_directives: |
| 601 |
self.scope.nonlocal_directives[name] = nonl |
| 602 |
|
| 603 |
def visit_Lambda(self, lamb): |
| 604 |
args = lamb.args |
| 605 |
assert isinstance(args, ast.arguments) |
| 606 |
self.visit_sequence(args.defaults) |
| 607 |
self.visit_kwonlydefaults(args.kw_defaults) |
| 608 |
new_scope = FunctionScope("<lambda>", lamb.lineno, lamb.col_offset) |
| 609 |
self.push_scope(new_scope, lamb) |
| 610 |
lamb.args.walkabout(self) |
| 611 |
lamb.body.walkabout(self) |
| 612 |
self.pop_scope() |
| 613 |
|
| 614 |
def visit_comprehension(self, comp): |
| 615 |
self.scope.comp_iter_target = True |
| 616 |
comp.target.walkabout(self) |
| 617 |
self.scope.comp_iter_target = False |
| 618 |
self.scope.comp_iter_expr += 1 |
| 619 |
comp.iter.walkabout(self) |
| 620 |
self.scope.comp_iter_expr -= 1 |
| 621 |
self.visit_sequence(comp.ifs) |
| 622 |
if comp.is_async: |
| 623 |
self.scope.note_await(comp) |
| 624 |
|
| 625 |
def _visit_comprehension(self, node, kind, comps, *consider): |
| 626 |
outer = comps[0] |
| 627 |
assert isinstance(outer, ast.comprehension) |
| 628 |
self.scope.comp_iter_expr += 1 |
| 629 |
outer.iter.walkabout(self) |
| 630 |
self.scope.comp_iter_expr -= 1 |
| 631 |
new_scope = ComprehensionScope("<genexpr>", node.lineno, node.col_offset) |
| 632 |
self.push_scope(new_scope, node) |
| 633 |
self.implicit_arg(0) |
| 634 |
new_scope.is_coroutine |= outer.is_async |
| 635 |
new_scope.comp_iter_target = True |
| 636 |
outer.target.walkabout(self) |
| 637 |
new_scope.comp_iter_target = False |
| 638 |
self.visit_sequence(outer.ifs) |
| 639 |
self.visit_sequence(comps[1:]) |
| 640 |
for item in list(consider): |
| 641 |
item.walkabout(self) |
| 642 |
self.pop_scope() |
| 643 |
|
| 644 |
if new_scope.is_generator: |
| 645 |
msg = "'yield' inside %s" % kind |
| 646 |
space = self.space |
| 647 |
assert new_scope.yield_node is not None |
| 648 |
self.error(msg, new_scope.yield_node) |
| 649 |
|
| 650 |
new_scope.is_generator |= isinstance(node, ast.GeneratorExp) |
| 651 |
is_async = new_scope.is_coroutine and not new_scope.is_generator |
| 652 |
|
| 653 |
|
| 654 |
self.scope.is_coroutine |= is_async |
| 655 |
|
| 656 |
def visit_ListComp(self, listcomp): |
| 657 |
self._visit_comprehension(listcomp, "list comprehension", listcomp.generators, listcomp.elt) |
| 658 |
|
| 659 |
def visit_GeneratorExp(self, genexp): |
| 660 |
self._visit_comprehension(genexp, "generator expression", genexp.generators, genexp.elt) |
| 661 |
|
| 662 |
def visit_SetComp(self, setcomp): |
| 663 |
self._visit_comprehension(setcomp, "set comprehension", setcomp.generators, setcomp.elt) |
| 664 |
|
| 665 |
def visit_DictComp(self, dictcomp): |
| 666 |
self._visit_comprehension(dictcomp, "dict comprehension", dictcomp.generators, |
| 667 |
dictcomp.value, dictcomp.key) |
| 668 |
|
| 669 |
def visit_With(self, wih): |
| 670 |
self.scope.new_temporary_name() |
| 671 |
self.visit_sequence(wih.items) |
| 672 |
self.scope.note_try_start(wih) |
| 673 |
self.visit_sequence(wih.body) |
| 674 |
self.scope.note_try_end(wih) |
| 675 |
|
| 676 |
def visit_withitem(self, witem): |
| 677 |
witem.context_expr.walkabout(self) |
| 678 |
if witem.optional_vars: |
| 679 |
witem.optional_vars.walkabout(self) |
| 680 |
|
| 681 |
def visit_AsyncWith(self, aw): |
| 682 |
self.scope.new_temporary_name() |
| 683 |
self.visit_sequence(aw.items) |
| 684 |
self.scope.note_try_start(aw) |
| 685 |
self.visit_sequence(aw.body) |
| 686 |
self.scope.note_try_end(aw) |
| 687 |
|
| 688 |
def visit_arguments(self, arguments): |
| 689 |
scope = self.scope |
| 690 |
assert isinstance(scope, FunctionScope) |
| 691 |
if arguments.posonlyargs: |
| 692 |
self._handle_params(arguments.posonlyargs, True) |
| 693 |
if arguments.args: |
| 694 |
self._handle_params(arguments.args, True) |
| 695 |
if arguments.kwonlyargs: |
| 696 |
self._handle_params(arguments.kwonlyargs, True) |
| 697 |
if arguments.vararg: |
| 698 |
self.check_forbidden_name(arguments.vararg.arg, arguments.vararg) |
| 699 |
self.note_symbol(arguments.vararg.arg, SYM_PARAM, arguments.vararg) |
| 700 |
scope.note_variable_arg(arguments.vararg) |
| 701 |
if arguments.kwarg: |
| 702 |
self.check_forbidden_name(arguments.kwarg.arg, arguments.kwarg) |
| 703 |
self.note_symbol(arguments.kwarg.arg, SYM_PARAM, arguments.kwarg) |
| 704 |
scope.note_keywords_arg(arguments.kwarg) |
| 705 |
|
| 706 |
def check_forbidden_name(self, name, node): |
| 707 |
if misc.check_forbidden_name(self.space, name): |
| 708 |
self.error( |
| 709 |
"cannot assign to " + name, |
| 710 |
node) |
| 711 |
|
| 712 |
def _handle_params(self, params, is_toplevel): |
| 713 |
for param in params: |
| 714 |
assert isinstance(param, ast.arg) |
| 715 |
arg = param.arg |
| 716 |
self.check_forbidden_name(arg, param) |
| 717 |
self.note_symbol(arg, SYM_PARAM, param) |
| 718 |
|
| 719 |
def _visit_annotations(self, func): |
| 720 |
args = func.args |
| 721 |
assert isinstance(args, ast.arguments) |
| 722 |
if args.posonlyargs: |
| 723 |
self._visit_arg_annotations(args.posonlyargs) |
| 724 |
if args.args: |
| 725 |
self._visit_arg_annotations(args.args) |
| 726 |
if args.vararg: |
| 727 |
self._visit_arg_annotation(args.vararg) |
| 728 |
if args.kwarg: |
| 729 |
self._visit_arg_annotation(args.kwarg) |
| 730 |
if args.kwonlyargs: |
| 731 |
self._visit_arg_annotations(args.kwonlyargs) |
| 732 |
if func.returns: |
| 733 |
func.returns.walkabout(self) |
| 734 |
|
| 735 |
def _visit_arg_annotations(self, args): |
| 736 |
for arg in args: |
| 737 |
assert isinstance(arg, ast.arg) |
| 738 |
self._visit_arg_annotation(arg) |
| 739 |
|
| 740 |
def _visit_arg_annotation(self, arg): |
| 741 |
if arg.annotation: |
| 742 |
arg.annotation.walkabout(self) |
| 743 |
|
| 744 |
def visit_Name(self, name): |
| 745 |
if name.ctx == ast.Load: |
| 746 |
role = SYM_USED |
| 747 |
else: |
| 748 |
role = SYM_ASSIGNED |
| 749 |
self.note_symbol(name.id, role, name) |
| 750 |
|
| 751 |
def visit_Try(self, node): |
| 752 |
self.scope.note_try_start(node) |
| 753 |
self.visit_sequence(node.body) |
| 754 |
self.scope.note_try_end(node) |
| 755 |
self.visit_sequence(node.handlers) |
| 756 |
self.visit_sequence(node.orelse) |
| 757 |
self.visit_sequence(node.finalbody) |
| 758 |
|
| 759 |
def visit_NamedExpr(self, node): |
| 760 |
scope = self.scope |
| 761 |
target = node.target |
| 762 |
assert isinstance(target, ast.Name) |
| 763 |
name = target.id |
| 764 |
if scope.comp_iter_expr > 0: |
| 765 |
self.error( |
| 766 |
"assignment expression cannot be used in a comprehension iterable expression", |
| 767 |
node) |
| 768 |
if isinstance(scope, ComprehensionScope): |
| 769 |
for i in range(len(self.stack) - 1, -1, -1): |
| 770 |
parent = self.stack[i] |
| 771 |
if isinstance(parent, ComprehensionScope): |
| 772 |
if parent.lookup_role(name) & SYM_COMP_ITER: |
| 773 |
self.error( |
| 774 |
"assignment expression cannot rebind comprehension iteration variable '%s'" % name, |
| 775 |
node) |
| 776 |
continue |
| 777 |
|
| 778 |
if isinstance(parent, FunctionScope): |
| 779 |
parent.note_symbol(name, SYM_ASSIGNED, node) |
| 780 |
if parent.lookup_role(name) & SYM_GLOBAL: |
| 781 |
flag = SYM_GLOBAL |
| 782 |
else: |
| 783 |
flag = SYM_NONLOCAL |
| 784 |
scope.note_symbol(name, flag, node) |
| 785 |
break |
| 786 |
elif isinstance(parent, ModuleScope): |
| 787 |
parent.note_symbol(name, SYM_GLOBAL, node) |
| 788 |
scope.note_symbol(name, SYM_GLOBAL, node) |
| 789 |
elif isinstance(parent, ClassScope): |
| 790 |
self.error( |
| 791 |
"assignment expression within a comprehension cannot be used in a class body", |
| 792 |
node) |
| 793 |
|
| 794 |
node.target.walkabout(self) |
| 795 |
node.value.walkabout(self) |
| 796 |
|
| 797 |
def visit_MatchAs(self, match_as): |
| 798 |
if match_as.name: |
| 799 |
self.note_symbol(match_as.name, SYM_ASSIGNED, match_as) |
| 800 |
if match_as.pattern: |
| 801 |
match_as.pattern.walkabout(self) |
| 802 |
|
| 803 |
def visit_MatchStar(self, match_star): |
| 804 |
if match_star.name: |
| 805 |
self.note_symbol(match_star.name, SYM_ASSIGNED, match_star) |