Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
442 lines
17 KiB
Python
442 lines
17 KiB
Python
"""Module tree and name-resolution model of one Rust crate, enough to expand `use super::*;` into explicit imports.
|
|
|
|
This is a one-off refactoring aid (STRA-338 debt (c)); it is not part of the product and not committed.
|
|
"""
|
|
import os
|
|
import pathlib
|
|
import re
|
|
|
|
IDENT = r"(?:r#)?[A-Za-z_][A-Za-z0-9_]*"
|
|
OPAQUE = None # a glob that cannot be resolved inside the crate (external crate, enum variants)
|
|
|
|
|
|
_OS = r'target_os = "(?:linux|windows)"'
|
|
SUPPORTED_GATE = re.compile(
|
|
rf'all\(any\({_OS}, {_OS}\), target_(?:arch = "x86_64"|pointer_width = "64")\)|any\({_OS}, {_OS}\)'
|
|
)
|
|
|
|
# a name declared under different `cfg` attributes (or under one and without): it cannot be imported by one cfg
|
|
MIXED_CFG = "<mixed cfg>"
|
|
|
|
|
|
def merge_cfg(old, new):
|
|
"""The cfg of a name seen with `old` (None: not seen) and again with `new`: equal ones agree, others are mixed."""
|
|
if old is None or old == new:
|
|
return new
|
|
return MIXED_CFG
|
|
|
|
|
|
def cfg_text(raw_text, stripped, start, head):
|
|
"""The `#[cfg(..)]` attributes (supported-target gate removed) of the statement that starts at `start`, as text
|
|
('' when it has none); `stripped` is `strip_code(raw_text, keep_offsets=True)`, so offsets agree."""
|
|
head_start = stripped.index(head, start) if head else start
|
|
found = re.findall(r"#\[cfg\([^\n]*?\)\]", raw_text[start:head_start])
|
|
return normalize_cfg("\n".join(found)).strip()
|
|
|
|
|
|
def normalize_cfg(text):
|
|
"""`text` with the crate-wide gate of the supported targets (Linux or Windows on x86_64, true wherever the crate builds)
|
|
replaced by `true`, so that it is not mistaken for a platform difference; `cfg(true)` attributes are dropped."""
|
|
text = SUPPORTED_GATE.sub("true", text)
|
|
text = re.sub(r"(?<=all\()true, ", "", text)
|
|
text = re.sub(r", true(?=[,)])", "", text)
|
|
return re.sub(r"#\[cfg\(true\)\]", "", text)
|
|
|
|
|
|
def has_cfg(attrs):
|
|
"""True when the attribute text carries a `cfg(` that really conditions the item (the supported-target gate does not)."""
|
|
return "cfg(" in normalize_cfg(attrs)
|
|
|
|
|
|
def _blank(text, i, j):
|
|
"""Spaces for text[i:j], newlines kept."""
|
|
return "".join(ch if ch == "\n" else " " for ch in text[i:j])
|
|
|
|
|
|
def _quoted(text, i, j):
|
|
"""The string literal text[i:j] as quotes around spaces (newlines kept): the same length."""
|
|
return '"' + _blank(text, i + 1, j - 1) + '"' if j - i >= 2 else _blank(text, i, j)
|
|
|
|
|
|
def strip_code(text, keep_offsets=False):
|
|
"""The text with comments, string and char literals blanked (newlines kept) so structure can be scanned.
|
|
With `keep_offsets` every character keeps its offset (blanked ones become spaces), so a span found in the result
|
|
can be cut out of the original text."""
|
|
out = []
|
|
i, n = 0, len(text)
|
|
while i < n:
|
|
c = text[i]
|
|
two = text[i : i + 2]
|
|
if two == "//":
|
|
j = text.find("\n", i)
|
|
j = n if j < 0 else j
|
|
if keep_offsets:
|
|
out.append(" " * (j - i))
|
|
i = j
|
|
continue
|
|
if two == "/*":
|
|
depth, j = 1, i + 2
|
|
while j < n and depth:
|
|
if text.startswith("/*", j):
|
|
depth, j = depth + 1, j + 2
|
|
elif text.startswith("*/", j):
|
|
depth, j = depth - 1, j + 2
|
|
else:
|
|
j += 1
|
|
out.append(_blank(text, i, j) if keep_offsets else "\n" * text.count("\n", i, j))
|
|
i = j
|
|
continue
|
|
raw = re.match(r'(?:b?r)(#*)"', text[i : i + 12]) if c in "rb" else None
|
|
if raw and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_")):
|
|
end = '"' + raw.group(1)
|
|
j = text.find(end, i + raw.end())
|
|
j = n if j < 0 else j + len(end)
|
|
out.append(_blank(text, i, j) if keep_offsets else '""' + "\n" * text.count("\n", i, j))
|
|
i = j
|
|
continue
|
|
if c == '"' or (c == "b" and text[i : i + 2] == 'b"'):
|
|
j = i + (2 if c == "b" else 1)
|
|
while j < n and text[j] != '"':
|
|
j += 2 if text[j] == "\\" else 1
|
|
j = min(j + 1, n)
|
|
out.append(_quoted(text, i, j) if keep_offsets else '""' + "\n" * text.count("\n", i, j))
|
|
i = j
|
|
continue
|
|
if c == "'":
|
|
if text[i + 1 : i + 2] == "\\":
|
|
j = text.find("'", i + 2)
|
|
j = n if j < 0 else j + 1
|
|
out.append("'" + " " * (j - i - 2) + "'" if keep_offsets else "' '")
|
|
i = j
|
|
continue
|
|
if text[i + 2 : i + 3] == "'":
|
|
out.append("' '")
|
|
i += 3
|
|
continue
|
|
out.append(c)
|
|
i += 1
|
|
return "".join(out)
|
|
|
|
|
|
def _skip_balanced(s, i, open_c, close_c):
|
|
depth = 0
|
|
while i < len(s):
|
|
if s[i] == open_c:
|
|
depth += 1
|
|
elif s[i] == close_c:
|
|
depth -= 1
|
|
if depth == 0:
|
|
return i + 1
|
|
i += 1
|
|
return len(s)
|
|
|
|
|
|
def statements(stripped):
|
|
"""Top-level statements of a stripped source: (attrs text, head text, start offset, end offset)."""
|
|
out = []
|
|
i, n = 0, len(stripped)
|
|
while i < n:
|
|
while i < n and stripped[i].isspace():
|
|
i += 1
|
|
if i >= n:
|
|
break
|
|
start = i
|
|
attrs = []
|
|
while stripped.startswith("#", i):
|
|
j = i + 1
|
|
if stripped.startswith("!", j):
|
|
j += 1
|
|
if j < n and stripped[j] == "[":
|
|
k = _skip_balanced(stripped, j, "[", "]")
|
|
attrs.append(stripped[i:k])
|
|
i = k
|
|
while i < n and stripped[i].isspace():
|
|
i += 1
|
|
else:
|
|
break
|
|
head_start = i
|
|
is_use = re.match(r"(?:pub\s*(?:\([^)]*\))?\s+)?use\b", stripped[i : i + 60])
|
|
j = i
|
|
while j < n:
|
|
c = stripped[j]
|
|
if c == ";":
|
|
j += 1
|
|
break
|
|
if c == "{" and not is_use:
|
|
j = _skip_balanced(stripped, j, "{", "}")
|
|
# `struct X {..}` / `fn ..{..}` end at the closing brace; `impl`, `mod` too
|
|
break
|
|
if c == "{" and is_use:
|
|
j = _skip_balanced(stripped, j, "{", "}")
|
|
continue
|
|
if c == "(":
|
|
j = _skip_balanced(stripped, j, "(", ")")
|
|
continue
|
|
if c == "[":
|
|
j = _skip_balanced(stripped, j, "[", "]")
|
|
continue
|
|
j += 1
|
|
out.append(("\n".join(attrs), stripped[head_start:j], start, j))
|
|
i = j
|
|
return out
|
|
|
|
|
|
ITEM_RE = re.compile(
|
|
r"^(pub(?:\s*\([^)]*\))?\s+)?"
|
|
r"(?:(?:unsafe|async|const|default)\s+|extern\s*(?:\"\"\s*)?)*"
|
|
rf"(fn|struct|enum|trait|union|type|const|static|mod)\s+({IDENT})"
|
|
)
|
|
|
|
|
|
def parse_use_tree(text):
|
|
"""[(path segments, alias or None, is_glob)] of the text after `use`, without the trailing `;`."""
|
|
s = text.strip()
|
|
pos = 0
|
|
|
|
def skip_ws():
|
|
nonlocal pos
|
|
while pos < len(s) and s[pos].isspace():
|
|
pos += 1
|
|
|
|
def parse(prefix):
|
|
nonlocal pos
|
|
results = []
|
|
skip_ws()
|
|
if s.startswith("::", pos):
|
|
pos += 2
|
|
path = list(prefix)
|
|
while True:
|
|
skip_ws()
|
|
if s.startswith("{", pos):
|
|
pos += 1
|
|
while True:
|
|
skip_ws()
|
|
if s.startswith("}", pos):
|
|
pos += 1
|
|
break
|
|
results += parse(path)
|
|
skip_ws()
|
|
if s.startswith(",", pos):
|
|
pos += 1
|
|
return results
|
|
if s.startswith("*", pos):
|
|
pos += 1
|
|
return results + [(path, None, True)]
|
|
m = re.compile(IDENT).match(s, pos)
|
|
if not m:
|
|
return results
|
|
pos = m.end()
|
|
path = path + [m.group(0)]
|
|
skip_ws()
|
|
if s.startswith("::", pos):
|
|
pos += 2
|
|
continue
|
|
alias = None
|
|
if re.compile(r"as\b").match(s, pos):
|
|
pos += 2
|
|
skip_ws()
|
|
m2 = re.compile(IDENT).match(s, pos) or re.compile(r"_").match(s, pos)
|
|
alias = m2.group(0)
|
|
pos = m2.end()
|
|
return results + [(path, alias, False)]
|
|
|
|
return parse([])
|
|
|
|
|
|
class Module:
|
|
def __init__(self, crate, file, parent, name):
|
|
self.crate, self.file, self.parent, self.name = crate, file, parent, name
|
|
self.children = {}
|
|
self.decl_attrs = {}
|
|
self._parsed = None
|
|
|
|
@property
|
|
def text(self):
|
|
return self.file.read_text(encoding="utf-8")
|
|
|
|
def _mark(self, name, cfg):
|
|
"""Record that `name` is declared under `cfg` (a second, different cfg makes it mixed)."""
|
|
self.conditional[name] = merge_cfg(self.conditional.get(name), cfg)
|
|
|
|
def parsed(self):
|
|
"""(items {name: is_pub}, uses [(name, is_pub, path)], globs [(path, is_pub)])"""
|
|
if self._parsed:
|
|
return self._parsed
|
|
items, uses, globs, self.anon, self.conditional = {}, [], [], [], {}
|
|
raw_text = self.text
|
|
kept = strip_code(raw_text, keep_offsets=True)
|
|
for attrs, head, start, _ in statements(kept):
|
|
cfg = cfg_text(raw_text, kept, start, head)
|
|
m = re.match(r"(pub\s*(?:\([^)]*\))?\s+)?use\b(.*?);?\s*$", head, re.S)
|
|
if m:
|
|
is_pub = bool(m.group(1))
|
|
for path, alias, is_glob in parse_use_tree(m.group(2)):
|
|
if is_glob:
|
|
globs.append((path, is_pub))
|
|
elif path:
|
|
name = alias or path[-1]
|
|
if name == "self" and len(path) > 1:
|
|
name = path[-2]
|
|
if name != "_":
|
|
uses.append((name, is_pub, path))
|
|
if cfg:
|
|
self._mark(name, cfg)
|
|
elif path[0] not in ("super", "self"):
|
|
self.anon.append(("::".join(path), is_pub))
|
|
continue
|
|
if re.match(r"(?:unsafe\s+)?extern\s*(?:\"\"\s*)?\{", head):
|
|
for vis, kind, name in re.findall(
|
|
rf"(pub(?:\s*\([^)]*\))?\s+)?(?:safe\s+|unsafe\s+)?(fn|static)\s+({IDENT})", head
|
|
):
|
|
items[name.removeprefix("r#")] = (bool(vis), kind)
|
|
if cfg:
|
|
self._mark(name.removeprefix("r#"), cfg)
|
|
continue
|
|
macro = re.match(rf"({IDENT}(?:::{IDENT})*)\s*!\s*[(\[{{]", head)
|
|
if macro and macro.group(1) != "macro_rules":
|
|
# an item-defining macro call: every constant-like name and every named item inside may be a definition
|
|
for name in re.findall(r"\b([A-Z][A-Z0-9_]{2,})\b", head):
|
|
items[name] = (True, "macro")
|
|
if cfg:
|
|
self._mark(name, cfg)
|
|
for kind, name in re.findall(rf"\b(fn|struct|enum|const|static|trait|type|mod)\s+({IDENT})", head):
|
|
items[name] = (True, "macro")
|
|
if cfg:
|
|
self._mark(name, cfg)
|
|
continue
|
|
m = ITEM_RE.match(head)
|
|
if m and m.group(3) != "_":
|
|
items[m.group(3).removeprefix("r#")] = (bool(m.group(1)), m.group(2))
|
|
if cfg:
|
|
self._mark(m.group(3).removeprefix("r#"), cfg)
|
|
self._parsed = (items, uses, globs)
|
|
return self._parsed
|
|
|
|
|
|
class Crate:
|
|
def __init__(self, root_dir):
|
|
self.root_dir = pathlib.Path(root_dir)
|
|
self.by_file = {}
|
|
self.root = None
|
|
src = self.root_dir / "src"
|
|
# ROOT_FILE (relative to the crate directory) names another crate root, such as `src/bin/tool/main.rs`
|
|
roots = [os.environ["ROOT_FILE"]] if os.environ.get("ROOT_FILE") else ["src/lib.rs", "src/main.rs"]
|
|
for name in roots:
|
|
if (self.root_dir / name).exists():
|
|
self.root = self._add((self.root_dir / name).resolve(), None, "crate")
|
|
break
|
|
self._ns_cache = {}
|
|
|
|
def _add(self, file, parent, name, via_path=False):
|
|
mod = Module(self, file, parent, name)
|
|
self.by_file[file] = mod
|
|
stripped_raw = file.read_text(encoding="utf-8")
|
|
mod_rs_like = via_path or file.name in ("lib.rs", "main.rs", "mod.rs")
|
|
stem_dir = file.parent if mod_rs_like else file.parent / file.stem
|
|
lines = stripped_raw.split("\n")
|
|
attrs = []
|
|
for line in lines:
|
|
t = line.strip()
|
|
if t.startswith("#["):
|
|
attrs.append(t)
|
|
continue
|
|
m = re.match(rf"(?:pub(?:\s*\([^)]*\))?\s+)?mod\s+({IDENT})\s*;", t)
|
|
if m:
|
|
child_name = m.group(1)
|
|
path_attr = next((re.search(r'path\s*=\s*"([^"]+)"', a) for a in attrs if "path" in a), None)
|
|
if path_attr:
|
|
cand = [(file.parent / path_attr.group(1)).resolve()]
|
|
else:
|
|
cand = [stem_dir / f"{child_name}.rs", stem_dir / child_name / "mod.rs"]
|
|
target = next((c for c in cand if c.exists()), None)
|
|
if target is not None and target not in self.by_file:
|
|
child = self._add(target.resolve(), mod, child_name, via_path=bool(path_attr))
|
|
mod.children[child_name] = child
|
|
mod.decl_attrs[child_name] = " ".join(attrs)
|
|
elif target is not None:
|
|
mod.children[child_name] = self.by_file[target.resolve()]
|
|
mod.decl_attrs[child_name] = " ".join(attrs)
|
|
if t and not t.startswith("//"):
|
|
attrs = []
|
|
return mod
|
|
|
|
def resolve_module(self, mod, path):
|
|
"""The module a glob/use path names, relative to `mod`; None when it leaves the crate or names a non-module."""
|
|
cur, segs = mod, list(path)
|
|
if segs and segs[0] == "crate":
|
|
cur, segs = self.root, segs[1:]
|
|
while segs and segs[0] in ("super", "self"):
|
|
if segs[0] == "super":
|
|
cur = cur.parent if cur else None
|
|
if cur is None:
|
|
return None
|
|
segs = segs[1:]
|
|
for seg in segs:
|
|
if cur is None or seg not in cur.children:
|
|
return None
|
|
cur = cur.children[seg]
|
|
return cur
|
|
|
|
def is_ancestor(self, anc, mod):
|
|
while mod is not None:
|
|
if mod is anc:
|
|
return True
|
|
mod = mod.parent
|
|
return False
|
|
|
|
def names(self, mod, full, _stack=()):
|
|
"""{name: (may_be_a_trait, cfg text)} visible in `mod` to its descendants (`full`) or to outsiders
|
|
(pub-ish only); OPAQUE when a glob cannot be resolved. A name may be a trait when it is a trait item or an
|
|
imported CamelCase name: a trait in scope is used by method calls without ever being written. A name is
|
|
conditional when its declaration carries a `cfg` attribute: the second member is that cfg text ('' when none)."""
|
|
key = (mod.file, full)
|
|
if key in self._ns_cache:
|
|
return self._ns_cache[key]
|
|
if key in _stack:
|
|
return {}
|
|
stack = _stack + (key,)
|
|
items, uses, globs = mod.parsed()
|
|
cond = mod.conditional
|
|
out = {n: (kind == "trait", cond.get(n, "")) for n, (is_pub, kind) in items.items() if full or is_pub}
|
|
for n, is_pub, _ in uses:
|
|
if full or is_pub:
|
|
old = out.get(n)
|
|
here = (n[:1].isupper(), cond.get(n, ""))
|
|
out[n] = here if old is None else (old[0] or here[0], merge_cfg(old[1], here[1]))
|
|
for n in mod.children:
|
|
if full:
|
|
out.setdefault(n, (False, ""))
|
|
result = out
|
|
for path, is_pub in globs:
|
|
if not (full or is_pub):
|
|
continue
|
|
target = self.resolve_module(mod, path)
|
|
if target is None:
|
|
result = OPAQUE
|
|
break
|
|
inner = self.names(target, full and self.is_ancestor(target, mod), stack)
|
|
if inner is OPAQUE:
|
|
result = OPAQUE
|
|
break
|
|
result = dict(result)
|
|
for n, (may, conditional) in inner.items():
|
|
old = result.get(n)
|
|
result[n] = (may, conditional) if old is None else (old[0] or may, merge_cfg(old[1], conditional))
|
|
self._ns_cache[key] = result
|
|
return result
|
|
|
|
def anon_paths(self, mod, full, _stack=()):
|
|
"""Trait paths imported as `use path as _;` in `mod` and in the modules its globs reach (a set of strings)."""
|
|
key = (mod.file, full, "anon")
|
|
if key in _stack:
|
|
return set()
|
|
mod.parsed()
|
|
out = {p for p, is_pub in mod.anon if full or is_pub}
|
|
for path, is_pub in mod.parsed()[2]:
|
|
if not (full or is_pub):
|
|
continue
|
|
target = self.resolve_module(mod, path)
|
|
if target is not None:
|
|
out |= self.anon_paths(target, full and self.is_ancestor(target, mod), _stack + (key,))
|
|
return out
|