Files
leleka/scripts/archcheck/rustsource.py
T
Pavlo Ratushnyi 219238cd08 architecture gate: read the whole file after a cfg(test) mod declaration, find static cells by type, 64 new exceptions with reasons (STRA-338)
The scanner stopped at the first '#[cfg(test)] mod x;' of a file, so the code below was invisible. It now skips only the item under a test-only cfg (an inline mod body, a declaration, a fn, a use; any(test, feature) is not test-only) and reads on.

process-global counted the type name OnceLock/LazyLock/OnceCell, which also matched instance fields (six exceptions existed only for that) and missed Atomic*, Mutex, RwLock, Once, Cell and RefCell statics, thread_local! included. It now counts a static whose type is a cell or a workspace type that holds one (derived per crate and its dependencies), and static mut. Eight exceptions that only excused instance fields go; the rest of the file's hits are re-judged.

Newly visible: 123 static cells in 58 files, 15 allow(unused_imports) in 6 files and the engine settings::process() cell (read at about 78 sites). Each gets an exception whose reason starts kept: (the boundary that forces it) or debt: (what removes it); the settings cell is the largest debt and is not removed here because the engine does not compile on Windows. Entries 173 -> 229, baseline stays empty. 11 new self-tests (39 in all).
2026-11-24 08:51:58 +01:00

144 lines
5.7 KiB
Python

"""Reading Rust source text for the gate: which lines are production code and which items exist only for tests."""
import re
_CFG_ATTRIBUTE = re.compile(r"#!?\[\s*cfg\s*\(")
_TOKEN = re.compile(r'[A-Za-z_][A-Za-z0-9_]*|"[^"]*"|[(),=]')
def requires_test(block):
"""True when an attribute (or a run of attributes) has a `#[cfg(...)]` that holds only under `cfg(test)`: `test`
itself or an `all(...)` with `test` among its terms. `any(test, feature = "x")` and `not(test)` hold in
production builds too, so they are not test-only."""
for found in _CFG_ATTRIBUTE.finditer(block):
tokens = _TOKEN.findall(block[found.end():])
flags, _ = _arguments(tokens, 0)
if flags and flags[0]:
return True
return False
def _predicate(tokens, pos):
"""(holds only under test, next position) for the cfg predicate that starts at tokens[pos]."""
name = tokens[pos]
pos += 1
following = tokens[pos] if pos < len(tokens) else ""
if following == "(":
flags, pos = _arguments(tokens, pos + 1)
if name == "all":
return any(flags), pos
return (name == "any" and bool(flags) and all(flags)), pos
if following == "=":
return False, pos + 2
return name == "test", pos
def _arguments(tokens, pos):
"""([test-only flag per argument], position after the closing parenthesis)."""
flags = []
while pos < len(tokens) and tokens[pos] != ")":
flag, pos = _predicate(tokens, pos)
flags.append(flag)
if pos < len(tokens) and tokens[pos] == ",":
pos += 1
return flags, pos + 1
def _unbalanced(text):
return text.count("[") > text.count("]") or text.count("(") > text.count(")")
def _attributes(lines, index):
"""(attribute text, index after the attribute lines) for the run of `#[...]` attributes that starts at `index`;
comment lines inside the run are passed over. ("", index) when `index` starts no attribute."""
parts = []
cursor = index
while cursor < len(lines):
stripped = lines[cursor].strip()
if stripped.startswith("#[") or stripped.startswith("#![") or (parts and _unbalanced(" ".join(parts))):
parts.append(stripped)
elif not (parts and stripped.startswith("//")):
break
cursor += 1
return " ".join(parts), (cursor if parts else index)
def _indent(line):
return len(line) - len(line.lstrip())
def _block_end(lines, opening, indent):
"""Index after the closing `}` at `indent` of the block that ends line `opening`; just after `opening` when no such
line exists (the body then stays visible to the counters instead of being hidden)."""
for index in range(opening + 1, len(lines)):
if _indent(lines[index]) == indent and lines[index].lstrip().startswith("}"):
return index + 1
return opening + 1
def item_end(lines, head, indent):
"""Index after the item whose first line is `head`: a `...;` item, a one-line `{}` item or a `{ ... }` block closed
at `indent`."""
for index in range(head, len(lines)):
text = lines[index].rstrip()
if text.endswith(";") or text.endswith("}"):
return index + 1
if text.endswith("{"):
return _block_end(lines, index, indent)
return head + 1
def production_lines(text):
"""The lines of a file that are not test code, comment lines dropped. An item under a test-only `#[cfg(...)]` (an
inline `mod x { ... }`, a `mod x;` declaration, a `fn`, a `use`) is skipped as a whole and the code after it counts
again; a file that starts with `#![cfg(test)]` has none."""
lines = text.splitlines()
kept = []
index = 0
while index < len(lines):
attributes, after = _attributes(lines, index)
if attributes and requires_test(attributes):
if lines[index].lstrip().startswith("#!["):
return []
index = item_end(lines, after, _indent(lines[index]))
continue
if not lines[index].lstrip().startswith("//"):
kept.append(lines[index])
index += 1
return kept
# the standard and common interior-mutable types: a `static` of one of them is process state
CELL_PRIMITIVES = (r"Atomic[A-Z]\w*", "Mutex", "RwLock", "Once", "OnceLock", "OnceCell", "LazyLock", "LazyCell", "Lazy",
"Cell", "RefCell", "UnsafeCell", "SyncUnsafeCell")
_TYPE_ITEM = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|enum|union|type)\s+(\w+)")
def type_definitions(text):
"""{type name: the text of its definition} for the struct, enum, union and type alias items of production code."""
rows = production_lines(text)
found = {}
for index, row in enumerate(rows):
declared = _TYPE_ITEM.match(row)
if declared:
body = "\n".join(rows[index:item_end(rows, index, _indent(row))])
found[declared.group(1)] = found.get(declared.group(1), "") + body
return found
def cell_holders(definitions):
"""Names of the types that hold interior-mutable state: one whose definition names a cell primitive or another
holder. `static X: Holder` is a process global just like `static X: Mutex<_>`; an instance field of the same type is
not. `definitions` is {type name: definition text}."""
holders = set()
while True:
word = re.compile(cell_alternation(holders))
added = {name for name, body in definitions.items() if name not in holders and word.search(body)}
if not added:
return holders
holders |= added
def cell_alternation(holders):
"""The regex group that `{cell_types}` in an architecture.json pattern stands for: a cell primitive or a holder."""
return r"\b(?:" + "|".join(list(CELL_PRIMITIVES) + sorted(map(re.escape, holders))) + r")\b"