A VM test script and `lib/k3s.py` share one namespace, so a step that assigns `pod = ...` replaces the library's `pod()` for every later call and the test dies mid-run with `TypeError: 'dict' object is not callable`. `ty` and `ruff --select F` accept a module-level rebinding, so this cost a full VM round on #6947. `vm-test-shadow-scan.py` parses the script and fails when a name bound at module level (assignment, `for` or `with` target, `import ... as`, walrus, `except ... as`) is also a module-level `def`. It looks into `with`, `if`, `for`, `while` and `try` bodies, where `with subtest(...)` steps live, and not into function or comprehension bodies. Every `vm-test-typecheck-<name>` runs it on the script alone. `vm-test-typecheck-shadow-control` passes only when it rejects each form of rebinding and accepts the same names where they are local. The one existing case, `sources` in `k8s-services`, is renamed `cred_sources`. Closes #6951
83 lines
3 KiB
Python
83 lines
3 KiB
Python
"""Fail when a VM test script rebinds a function it defines.
|
|
|
|
A VM test script is one module: `lib/k3s.py` and the test's own helpers are
|
|
concatenated in front of the steps, and every `with subtest(...)` body runs in
|
|
that module's namespace. A step that assigns `pod = ...` replaces the library's
|
|
`pod()` for every later call, and the test dies mid-run with
|
|
`TypeError: 'dict' object is not callable`. `ty` and `ruff --select F` don't see
|
|
it, because a rebinding at module level is legal Python.
|
|
|
|
The scan names every module-level binding (assignment, `for`/`with`/`except`
|
|
target, walrus, `import ... as`) whose name is also a module-level `def`. It
|
|
looks into blocks that share the module's namespace (`with`, `if`, `for`,
|
|
`while`, `try`), and not into function, class or comprehension bodies, whose
|
|
bindings are local.
|
|
|
|
Usage: shadow-scan.py <script>
|
|
"""
|
|
|
|
import ast
|
|
import sys
|
|
|
|
# Bodies that open a namespace of their own: what is bound inside is local.
|
|
SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)
|
|
COMPREHENSIONS = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
|
|
|
|
|
|
def module_level(node):
|
|
"""Yield `node`'s descendants that run in the module's namespace.
|
|
|
|
A `def` or `class` is yielded itself (its name is bound here), its body is
|
|
not entered.
|
|
"""
|
|
for child in ast.iter_child_nodes(node):
|
|
yield child
|
|
if not isinstance(child, SCOPES + COMPREHENSIONS):
|
|
yield from module_level(child)
|
|
|
|
|
|
def bindings(tree):
|
|
"""Map each name bound at module level to the lines that bind it."""
|
|
bound: dict[str, list[int]] = {}
|
|
for node in module_level(tree):
|
|
names = []
|
|
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
|
names = [node.id]
|
|
elif isinstance(node, ast.Import | ast.ImportFrom):
|
|
names = [(a.asname or a.name).split(".")[0] for a in node.names]
|
|
elif isinstance(node, ast.ExceptHandler) and node.name:
|
|
names = [node.name]
|
|
for name in names:
|
|
bound.setdefault(name, []).append(node.lineno)
|
|
return bound
|
|
|
|
|
|
def functions(tree):
|
|
"""Map each module-level `def` name to its line."""
|
|
return {
|
|
node.name: node.lineno
|
|
for node in module_level(tree)
|
|
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef)
|
|
}
|
|
|
|
|
|
def main(path: str) -> int:
|
|
with open(path) as f:
|
|
tree = ast.parse(f.read(), path)
|
|
defined = functions(tree)
|
|
failed = False
|
|
for name, lines in sorted(bindings(tree).items()):
|
|
if name in defined:
|
|
for line in lines:
|
|
print(
|
|
f"{path}:{line}: `{name}` is bound at module level, shadowing "
|
|
f"the function `{name}` defined at line {defined[name]}; every "
|
|
f"later call of it fails. Rename the variable.",
|
|
file=sys.stderr,
|
|
)
|
|
failed = True
|
|
return 1 if failed else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv[1]))
|