Coverage for src/renaissance/utils/cst_utils.py: 100%
34 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-16 16:04 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-16 16:04 +0000
1# Copyright (C) 2024-2026 TNO
2#
3# Licensed under the terms specified in the LICENSE file in the root directory
4# of this repository, also available at:
5# https://github.com/TNO/Renaissance.Py/blob/main/LICENSE
7"""Helpers over the libcst tree of one module: its top-level statements, the names they read or bind and the comment trailing a line."""
9from collections.abc import Iterator
11import libcst as cst
14def module_statements(module: cst.Module) -> Iterator[cst.BaseSmallStatement | cst.BaseCompoundStatement]:
15 """Yield the module's top-level statements in order, one per small statement of a line like `a = 1; b = 2`."""
16 for statement in module.body:
17 if isinstance(statement, cst.SimpleStatementLine):
18 yield from statement.body
19 else:
20 yield statement
23def trailing_of_sole_statement(module: cst.Module, statement: cst.BaseSmallStatement) -> cst.TrailingWhitespace | None:
24 """Return the whitespace and comment trailing the line of statement in module, or None if the line holds others."""
25 for line in module.body:
26 if isinstance(line, cst.SimpleStatementLine) and len(line.body) == 1 and line.body[0] is statement:
27 return line.trailing_whitespace
28 return None
31class _NameCollector(cst.CSTVisitor):
32 """Collect the names an expression reads: every `Name` except an attribute's or a keyword argument's own name."""
34 def __init__(self) -> None:
35 """Start with no names collected."""
36 super().__init__()
37 self.names: set[str] = set()
39 def visit_Name(self, node: cst.Name) -> None: # noqa: N802 - libcst dispatches on this exact name
40 """Record the name."""
41 self.names.add(node.value)
43 def visit_Attribute(self, node: cst.Attribute) -> bool: # noqa: N802 - libcst dispatches on this exact name
44 """Visit only the attribute's object: in `np.integer`, `integer` is not a name read here."""
45 node.value.visit(self)
46 return False
48 def visit_Arg(self, node: cst.Arg) -> bool: # noqa: N802 - libcst dispatches on this exact name
49 """Visit only the argument's value, not the keyword it is passed as."""
50 node.value.visit(self)
51 return False
54def names_read_by(node: cst.CSTNode) -> set[str]:
55 """Return every name `node` reads, built-ins included; attribute names and keyword argument names are not reads."""
56 collector = _NameCollector()
57 node.visit(collector)
58 return collector.names
61def assigned_names(statement: cst.Assign | cst.AnnAssign) -> set[str]:
62 """Return every name an assignment's targets use, including inside tuple or list targets."""
63 targets = [target.target for target in statement.targets] if isinstance(statement, cst.Assign) else [statement.target]
64 collector = _NameCollector()
65 for target in targets:
66 target.visit(collector)
67 return collector.names