"""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 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) def _attribute_end(text, i): """The index after the `#[...]` or `#![...]` attribute that starts at `i` (strings inside are skipped), or `i`.""" j = i + (2 if text.startswith("#![", i) else 1) if text[j : j + 1] != "[": return i depth = 0 while j < len(text): c = text[j] if c == '"': j += 1 while j < len(text) and text[j] != '"': j += 2 if text[j] == "\\" else 1 elif c == "[": depth += 1 elif c == "]": depth -= 1 if depth == 0: return j + 1 j += 1 return i def strip_code(text, keep_attr_strings=False): """The text with comments, string and char literals blanked (newlines kept) so structure can be scanned. With `keep_attr_strings` the text of attributes stays as written (`cfg(feature = "x")` keeps its string).""" out = [] i, n = 0, len(text) while i < n: c = text[i] two = text[i : i + 2] if keep_attr_strings and c == "#" and (text.startswith("#[", i) or text.startswith("#![", i)): end = _attribute_end(text, i) if end > i: out.append(text[i:end]) i = end continue if two == "//": j = text.find("\n", i) i = n if j < 0 else 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("\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('""' + "\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('""' + "\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("' '") 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+(?:mut\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([]) def cfg_exprs(attrs): """The whitespace-free expressions of the `#[cfg(...)]` attributes in `attrs` (a set of strings).""" out = set() for m in re.finditer(r"(? [set of cfg expressions of one declaration, ...] self.arch_glob = False # `use std::arch::::*;` seen by `Crate.names` @property def text(self): return self.file.read_text(encoding="utf-8") 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 = {}, [], [], [], set() self.cond_cfgs = {} def mark(name, attrs): if "cfg(" in attrs: self.conditional.add(name) self.cond_cfgs.setdefault(name, []).append(cfg_exprs(attrs)) for attrs, head, _, _ in statements(strip_code(self.text, True)): 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)) mark(name, attrs) 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+(?:mut\s+)?({IDENT})", head ): items[name.removeprefix("r#")] = (bool(vis), kind) mark(name.removeprefix("r#"), attrs) 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") mark(name, attrs) for kind, name in re.findall(rf"\b(fn|struct|enum|const|static|trait|type|mod)\s+({IDENT})", head): items[name] = (True, "macro") mark(name, attrs) 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)) mark(m.group(3).removeprefix("r#"), attrs) 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" for name in ("lib.rs", "main.rs"): if (src / name).exists(): self.root = self._add((src / 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 = [] line_no = -1 while line_no + 1 < len(lines): line_no += 1 t = lines[line_no].strip() if t.startswith("#["): while t.count("[") > t.count("]") and line_no + 1 < len(lines): line_no += 1 t += " " + lines[line_no].strip() 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: return None nxt = cur.children.get(seg) or self._child_through_globs(cur, seg, set()) if nxt is None: return None cur = nxt return cur def _child_through_globs(self, mod, seg, seen): """The module `seg` that `mod` sees through its `use path::*;` globs (a child of the glob target), or None.""" if mod.file in seen: return None seen.add(mod.file) for path, _ in mod.parsed()[2]: target = self.resolve_module(mod, path) if path[:1] in (["super"], ["self"], ["crate"]) or path[0] in mod.children else None if target is None or target.file in seen: continue if seg in target.children: return target.children[seg] found = self._child_through_globs(target, seg, seen) if found is not None: return found return None def is_ancestor(self, anc, mod): while mod is not None: if mod is anc: return True mod = mod.parent return False def maybe_trait_use(self, mod, name, path): """Whether an imported name may be a trait that method calls use without writing it: a CamelCase or CONSTANT-like name whose definition is not found (an external crate) or is a trait.""" if not name[:1].isupper(): return False kind = self.resolve_kind(mod, path, 0) return kind is None or kind == "trait" def resolve_kind(self, mod, path, depth): """The item kind ('struct', 'trait', 'const', ...) a `use` path of this crate ends at, or None when it leaves the crate, ends in a glob or macro, or cannot be followed.""" if depth > 8 or len(path) < 2: return None target = self.resolve_module(mod, path[:-1]) if target is None: return None items, uses, _ = target.parsed() last = path[-1] if last in items: kind = items[last][1] return None if kind == "macro" else kind for n, _, inner in uses: if n == last: return self.resolve_kind(target, inner, depth + 1) return None def names(self, mod, full, _stack=()): """{name: (may_be_a_trait, is_conditional)} 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.""" 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", n in cond) for n, (is_pub, kind) in items.items() if full or is_pub} for n, is_pub, path in uses: if full or is_pub: old = out.get(n, (False, False)) out[n] = (old[0] or self.maybe_trait_use(mod, n, path), old[1] or n in cond) for n in mod.children: if full: out.setdefault(n, (False, 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 and path[:2] in (["std", "arch"], ["core", "arch"]): mod.arch_glob = True # the CPU intrinsics: files name them, they are not listed here continue 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, (False, False)) result[n] = (old[0] or may, old[1] or 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