From 7db84038389e73166a1ec26ea135fb2563c66e2a Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 14 Nov 2026 11:51:52 +0100 Subject: [PATCH] Explicit imports in leleka-gguf and leleka-cpu-kernels; explicit_imports.py: cfg-gated names, platform files, glob module paths, trait resolution; rename_module.py Co-Authored-By: Claude Sonnet 5.5 --- crates/cpu-kernels/src/dispatch.rs | 3 +- crates/cpu-kernels/src/isa.rs | 3 +- crates/gguf/src/error.rs | 3 +- crates/gguf/src/file.rs | 3 +- crates/gguf/src/reader.rs | 3 +- crates/gguf/src/tensor_type.rs | 3 - crates/gguf/src/value.rs | 3 - scripts/dev/explicit_imports.py | 131 +++++++++++++++++++++++++-- scripts/dev/rename_module.py | 139 +++++++++++++++++++++++++++++ scripts/dev/rust_modtree.py | 133 +++++++++++++++++++++++---- scripts/dev/wsl-cargo.sh | 2 +- 11 files changed, 381 insertions(+), 45 deletions(-) create mode 100644 scripts/dev/rename_module.py diff --git a/crates/cpu-kernels/src/dispatch.rs b/crates/cpu-kernels/src/dispatch.rs index 11601451..82a45872 100644 --- a/crates/cpu-kernels/src/dispatch.rs +++ b/crates/cpu-kernels/src/dispatch.rs @@ -1,7 +1,6 @@ //! The table of kernel entry points for one level, and the checked calls through it. -#[allow(unused_imports)] -use super::*; +use super::{AttnShape, DispatchError, ISA_ENV, Isa, KernelError, Q8rRef, ScoreSpec, fmt}; pub(super) type DotI8 = fn(&[i8], &[i8]) -> Result; pub(super) type DotI4 = fn(&[u8], &[i8]) -> Result; diff --git a/crates/cpu-kernels/src/isa.rs b/crates/cpu-kernels/src/isa.rs index c28c89e1..22ab0be3 100644 --- a/crates/cpu-kernels/src/isa.rs +++ b/crates/cpu-kernels/src/isa.rs @@ -1,7 +1,6 @@ //! The kernel levels, their names and CPU support, and the error of choosing one. -#[allow(unused_imports)] -use super::*; +use super::fmt; /// Name of the environment variable that forces a kernel level. pub const ISA_ENV: &str = "LELEKA_CPU_ISA"; diff --git a/crates/gguf/src/error.rs b/crates/gguf/src/error.rs index 52900c69..07f1e1ca 100644 --- a/crates/gguf/src/error.rs +++ b/crates/gguf/src/error.rs @@ -1,7 +1,6 @@ //! The error of reading a GGUF file. -#[allow(unused_imports)] -use super::*; +use super::fmt; #[derive(Clone, Debug, Eq, PartialEq)] pub enum GgufError { diff --git a/crates/gguf/src/file.rs b/crates/gguf/src/file.rs index 3b6738e3..cd729cad 100644 --- a/crates/gguf/src/file.rs +++ b/crates/gguf/src/file.rs @@ -1,7 +1,6 @@ //! The parsed GGUF file: header, metadata, tensor table and the reading of them. -#[allow(unused_imports)] -use super::*; +use super::{DEFAULT_ALIGNMENT, GgufError, HashSet, Limits, Read, Reader, TensorInfo, TensorType, Value}; /// A validated GGUF header. #[derive(Clone, Debug)] diff --git a/crates/gguf/src/reader.rs b/crates/gguf/src/reader.rs index 21a56cff..df2d391d 100644 --- a/crates/gguf/src/reader.rs +++ b/crates/gguf/src/reader.rs @@ -1,7 +1,6 @@ //! The bounded reader that parses the bytes of a GGUF file. -#[allow(unused_imports)] -use super::*; +use super::{GgufError, Limits, Read, Value}; pub(super) struct Reader { pub(super) inner: R, diff --git a/crates/gguf/src/tensor_type.rs b/crates/gguf/src/tensor_type.rs index a00f7bc9..21bfde5e 100644 --- a/crates/gguf/src/tensor_type.rs +++ b/crates/gguf/src/tensor_type.rs @@ -1,8 +1,5 @@ //! The tensor types of GGUF with their codes, names and block geometry. -#[allow(unused_imports)] -use super::*; - /// Tensor element types, with the numeric codes of ggml (`enum ggml_type`). #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum TensorType { diff --git a/crates/gguf/src/value.rs b/crates/gguf/src/value.rs index 50d1cfe0..cf5e55fe 100644 --- a/crates/gguf/src/value.rs +++ b/crates/gguf/src/value.rs @@ -1,8 +1,5 @@ //! A metadata value of a GGUF file. -#[allow(unused_imports)] -use super::*; - /// A metadata value. #[derive(Clone, Debug, PartialEq)] pub enum Value { diff --git a/scripts/dev/explicit_imports.py b/scripts/dev/explicit_imports.py index 2d343f8f..4a93c652 100644 --- a/scripts/dev/explicit_imports.py +++ b/scripts/dev/explicit_imports.py @@ -11,6 +11,7 @@ crate takes minutes per round. Offline refactoring aid (STRA-338 debt (c)); not """ import collections import json +import os import pathlib import posixpath import re @@ -20,10 +21,10 @@ import sys import tempfile sys.path.insert(0, str(pathlib.Path(__file__).parent)) -from rust_modtree import IDENT, OPAQUE, Crate, statements, strip_code # noqa: E402 +from rust_modtree import IDENT, OPAQUE, Crate, _attribute_end, _skip_balanced, cfg_exprs, statements, strip_code # noqa: E402 GLOB_RE = re.compile(r"^#\[allow\(unused_imports\)\]\s*\nuse super::\*;[ \t]*\n", re.M) -USE_SUPER_RE = re.compile(r"(?m)^(?:// used only with some cargo features of this crate\n#\[allow\(unused_imports\)\]\n)?(?:#\[cfg\(test\)\]\n)?use super::(?:\{[^}]*\}|[A-Za-z_]\w*);\n") +USE_SUPER_RE = re.compile(r"(?m)^(?:// used only with some cargo features[^\n]*\n(?:#\[cfg\([^\n]*\)\]\n)?#\[allow\(unused_imports\)\]\n)?(?:#\[cfg\(test\)\]\n)?use super::(?:\{[^}]*\}|[A-Za-z_]\w*);\n") HEADER_RE = re.compile(r"\A((?://![^\n]*\n)+)") PLATFORM_CFG = re.compile( r"cfg\([^\n]*(windows|macos|miri|target_feature|not\((?:target_|windows|unix|miri)" @@ -268,6 +269,11 @@ class Plan: self.skipped = {} self._macro_cache = {} self.imports = {} # file -> {name: 'normal' | 'test'} + self.platform_files = set() # platform-cfg files expanded anyway (--platform-residual): unused names stay + self.platform_residual = False + self._cond_index = None + self._platform_cache = {} + self.cfg_names = collections.defaultdict(dict) # file -> {name: cfg expression its import needs} def candidates(self): return [f for f, t in self.texts.items() if GLOB_RE.search(t) and self.crate.by_file[f].parent is not None] @@ -276,7 +282,9 @@ class Plan: mod = self.crate.by_file[f] decl = mod.parent.decl_attrs.get(mod.name, "") if PLATFORM_CFG.search(decl) or PLATFORM_CFG.search(self.texts[f]): - return "platform cfg" + if not self.platform_residual: + return "platform cfg" + self.platform_files.add(f) if f.name == "tests.rs" or f.name.endswith("_tests.rs"): return "test module" if self.crate.names(mod.parent, True) is OPAQUE: @@ -354,11 +362,92 @@ class Plan: continue wanted |= {n for n, (may_be_trait, _) in parent_names.items() if may_be_trait} needs[f] = {n for n in wanted if n in parent_names and n not in self._own_names(mod)} - if any(parent_names[n][1] for n in needs[f]): - self.blocked.add(f) + for n in sorted(needs[f]): + if parent_names[n][1] and not self.cond_implied(mod, n): + expr = self.cond_expression(n) + if expr is None: + self.blocked.add(f) + else: + self.cfg_names[f][n] = expr needs[f] |= {"@anon:" + p for p in orig.anon_paths(mod.parent, True) if p not in self._own_anon(mod)} return needs + def platform_tokens(self, f): + """Identifiers of the items of `f` that sit under a platform cfg (all of them when the module itself does): + the names that only code of another target uses.""" + if f in self._platform_cache: + return self._platform_cache[f] + mod = self.crate.by_file[f] + decl = mod.parent.decl_attrs.get(mod.name, "") if mod.parent else "" + stripped = strip_code(self.texts[f], True) + out = set() + if PLATFORM_CFG.search(decl): + out = set(re.findall(IDENT, stripped)) + for m in re.finditer(r"#\[cfg\(", stripped): + end = _attribute_end(stripped, m.start()) + if not PLATFORM_CFG.search(stripped[m.start() : end]): + continue + j = end + while j < len(stripped): + c = stripped[j] + if c == "{": + j = _skip_balanced(stripped, j, "{", "}") + break + if c == ";": + j += 1 + break + j += 1 + out |= set(re.findall(IDENT, stripped[end:j])) + self._platform_cache[f] = out + return out + + def cond_declarations(self, name): + """[set of cfg expressions] of every conditional declaration of `name` in the crate.""" + if self._cond_index is None: + self._cond_index = collections.defaultdict(list) + for mod in self.crate.by_file.values(): + mod.parsed() + for n, decls in mod.cond_cfgs.items(): + self._cond_index[n] += decls + return self._cond_index.get(name, []) + + def cond_expression(self, name): + """The cfg expression under which `name` exists in the parent: its declaration's attributes (all of them), + or `any(...)` of several declarations; None when unknown.""" + decls = self.cond_declarations(name) + if not decls: + return None + parts = [] + for decl in decls: + expr = "all(" + ", ".join(sorted(decl)) + ")" if len(decl) > 1 else next(iter(decl)) if decl else None + if expr is None: + return None + if expr not in parts: + parts.append(expr) + return parts[0] if len(parts) == 1 else "any(" + ", ".join(parts) + ")" + + def chain_cfgs(self, mod): + """The cfg expressions of the `mod x;` declarations from the crate root down to `mod`.""" + out = set() + while mod is not None and mod.parent is not None: + out |= cfg_exprs(mod.parent.decl_attrs.get(mod.name, "")) + mod = mod.parent + return out + + def cond_implied(self, mod, name): + """True when a module compiled only under the cfg of one declaration of `name` may import it without a cfg: + every cfg expression of that declaration is on the module's declaration chain (or, when it names cargo + features, every feature of it is: the platform terms of a feature gate are shared by the whole tree).""" + chain = self.chain_cfgs(mod) + chain_features = set(re.findall(r'feature="([^"]+)"', " ".join(chain))) + for decl in self.cond_declarations(name): + if decl <= chain: + return True + features = set(re.findall(r'feature="([^"]+)"', " ".join(decl))) + if features and features <= chain_features and "not(" not in " ".join(decl): + return True + return False + def _globs_super(self, f): return bool(re.search(r"^\s*use super::\*;", self.texts[f], re.M)) @@ -391,10 +480,23 @@ class Plan: test = [n for n in test if not n.startswith("@anon:")] block = "".join(f"use {n[6:]} as _;" + chr(10) for n in anon_normal) block += "".join("#[cfg(test)]" + chr(10) + f"use {n[6:]} as _;" + chr(10) for n in anon_test) - block += (pack_use_fixed(normal) if normal else "") + (pack_use_fixed(test, True) if test else "") + gated = self.cfg_names.get(f, {}) + plain = lambda names: [n for n in names if n not in gated] + block += (pack_use_fixed(plain(normal)) if plain(normal) else "") + ( + pack_use_fixed(plain(test), True) if plain(test) else "" + ) + for expr in sorted(set(gated.values())): + for names, prefix in ((normal, f"#[cfg({expr})]"), (test, f"#[cfg(all(test, {expr}))]")): + group = [n for n in names if gated.get(n) == expr] + if group: + block += prefix + chr(10) + pack_use_fixed(group) if residual: - note = "// used only with some cargo features of this crate" + chr(10) - block += note + "#[allow(unused_imports)]" + chr(10) + pack_use_fixed(residual) + note = "// used only with some cargo features or targets of this crate" + chr(10) + block += note + "#[allow(unused_imports)]" + chr(10) + pack_use_fixed(plain(residual)) + for expr in sorted(set(gated.values())): + group = [n for n in residual if gated.get(n) == expr] + if group: + block += note + f"#[cfg({expr})]" + chr(10) + "#[allow(unused_imports)]" + chr(10) + pack_use_fixed(group) if getattr(self, "prune", False): matches = list(USE_SUPER_RE.finditer(text)) for index in reversed(range(len(matches))): @@ -402,6 +504,9 @@ class Plan: text = text[: m.start()] + (block if index == 0 else "") + text[m.end() :] else: text = GLOB_RE.sub(lambda _: block, text, count=1) + if not block: + # nothing left to import: drop the blank line the removed pair leaves behind as well + text = re.sub(chr(10) * 3 + "+", chr(10) * 2, text, count=1) mod = self.crate.by_file[f] parent = mod.parent.name if mod.parent else "crate" stripped = strip_code(text) @@ -440,6 +545,7 @@ def main(): features = "--features-all" in sys.argv dry = "--dry-run" in sys.argv plan = Plan(wt, crate_dir) + plan.platform_residual = "--platform-residual" in sys.argv if "--headers-only" in sys.argv: plan.write() print(f"{package}: headers rewritten, imports untouched", flush=True) @@ -532,7 +638,10 @@ def main(): test_only = plan.is_test_only(f) a_unused = test_only or all(name in fl.get(r, ()) for fl in a_flags) b_unused = all(name in fl.get(r, ()) for fl in b_flags) - if a_unused and b_unused: + if a_unused and b_unused and f in plan.platform_files and imp[name] != "residual" and name in plan.platform_tokens(f) and name[:1].isupper(): + imp[name] = "residual" # probably used by code of another target: keep, under a narrow allow + changed = True + elif a_unused and b_unused and imp[name] != "residual": del imp[name] changed = True elif a_unused and not test_only and imp[name] == "normal": @@ -554,6 +663,10 @@ def main(): moved += 1 plan.write() print(f"{moved} imports used only with some features kept under a narrow allow", flush=True) + for f in plan.platform_files: + low = sorted(n for n in plan.platform_tokens(f) if n in plan.crate.by_file[f].parsed()[0] or n in plan.crate.by_file[f].children) + if low: + print(" REVIEW platform-cfg file", rel(f)) left = {f: r for f, r in skipped.items()} print(json.dumps({rel(f): r for f, r in left.items()}, indent=0)[:3000]) WORK.mkdir(parents=True, exist_ok=True) diff --git a/scripts/dev/rename_module.py b/scripts/dev/rename_module.py new file mode 100644 index 00000000..0f69f72c --- /dev/null +++ b/scripts/dev/rename_module.py @@ -0,0 +1,139 @@ +"""Rename Rust modules to what they hold, with `git mv`, and update the `mod` declaration, the `#[path]` attribute, the paths +that name the module and the doc comment of the file (STRA-338 debt (c), names). + +Usage: python scripts/dev/rename_module.py WORKTREE CRATE_DIR MAPPING.tsv [--dry-run] + +MAPPING.tsv: one module per line, tab separated: `old module path below src/` (for example `governor/governor_methods`), the new +module name (one identifier), and the new doc lines of the file (`//!` text, lines separated by ` || `). Modules are renamed in +the listed order; list a child before its parent when both change. Offline refactoring aid; not part of the product. +""" +import pathlib +import re +import subprocess +import sys + +IDENT = r"[A-Za-z_][A-Za-z0-9_]*" +GENERATED = re.compile(r"Split out of|Moved out of|Groups the submodules|Methods of `|Defines `|Implements `|Functions: `|Items of the parent") + + +def git_mv(wt, src, dst): + dst.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(["git", "mv", str(src.relative_to(wt)), str(dst.relative_to(wt))], cwd=wt, check=True) + + +def module_files(src_dir, rel): + """(file, owned dir or None) of the module `rel` (`a/b` -> a/b.rs or a/b/mod.rs).""" + base = src_dir / rel + if (base.with_suffix(".rs")).is_file(): + f = base.with_suffix(".rs") + return f, (base if base.is_dir() else None) + if (base / "mod.rs").is_file(): + return base / "mod.rs", base + raise SystemExit(f"module not found: {rel}") + + +def parent_file(src_dir, rel): + parts = rel.split("/") + if len(parts) == 1: + for name in ("lib.rs", "main.rs"): + if (src_dir / name).is_file(): + return src_dir / name + parent = "/".join(parts[:-1]) + f, _ = module_files(src_dir, parent) + return f + + +def new_doc(text, doc_lines): + """The file text with its leading `//!` block replaced by `doc_lines`, when that block is the generated one.""" + lines = text.split("\n") + end = 0 + while end < len(lines) and lines[end].startswith("//!"): + end += 1 + block = "\n".join(lines[:end]) + if end and not GENERATED.search(block): + return text # a person wrote it: keep + body = "\n".join(lines[end:]) + return "\n".join("//! " + ln for ln in doc_lines) + "\n" + body + + +def rewrite_references(files, old, new): + changed = [] + ref = [ + (re.compile(rf"\b{old}::"), f"{new}::"), + (re.compile(rf"::{old}\b(?!\s*\()"), f"::{new}"), + (re.compile(rf"\bmod\s+{old}\b"), f"mod {new}"), + (re.compile(rf"\buse\s+{old}\b"), f"use {new}"), + ] + use_stmt = re.compile(r"(?ms)^\s*(?:pub(?:\([^)]*\))?\s+)?use\s[^;]*;") + for f in files: + text = f.read_text(encoding="utf-8") + out = text + for rx, repl in ref: + out = rx.sub(repl, out) + + def in_use(m): + return re.sub(rf"(?#\[path\s*=\s*\"(?P[^\"]+)\"\]\s*\n\s*)?(?Ppub(?:\([^)]*\))?\s+)?mod\s+{old}\s*;", parent_text + ) + if not decl: + raise SystemExit(f"no `mod {old};` in {parent}") + target_dir = f.parent + new_file = f.with_name(new + ".rs") if f.name != "mod.rs" else f + print(f" {f.relative_to(wt).as_posix()} -> {new_file.relative_to(wt).as_posix()}") + if decl.group("path"): + path = decl.group("path") + new_path = re.sub(rf"{re.escape(old)}(\.rs)$", rf"{new}\1", path) if path.endswith(old + ".rs") else path + new_file = (parent.parent / new_path).resolve() if path.endswith(old + ".rs") else new_file + f_actual = (parent.parent / path).resolve() + if f_actual != f.resolve(): + raise SystemExit(f"{path} does not name {f}") + if dry: + return [] + if f.name != "mod.rs": + git_mv(wt, f, new_file) + if owned is not None and owned.is_dir(): + git_mv(wt, owned, owned.with_name(new)) + else: + git_mv(wt, owned, owned.with_name(new)) + new_file = owned.with_name(new) / "mod.rs" + text = parent_text + repl = decl.group(0) + repl = re.sub(rf"\bmod\s+{old}\b", f"mod {new}", repl) + if decl.group("path"): + repl = repl.replace(decl.group("path"), new_path) + parent.write_text(text.replace(decl.group(0), repl, 1), encoding="utf-8", newline="\n") + body = new_file.read_text(encoding="utf-8") + if doc_lines: + new_file.write_text(new_doc(body, doc_lines), encoding="utf-8", newline="\n") + files = [p for p in crate_dir.rglob("*.rs") if "target" not in p.parts] + return rewrite_references(files, old, new) + + +def main(): + wt, crate_dir, mapping = (pathlib.Path(a).resolve() for a in sys.argv[1:4]) + dry = "--dry-run" in sys.argv + for line in mapping.read_text(encoding="utf-8").splitlines(): + if not line.strip() or line.startswith("#"): + continue + rel, new, *doc = line.split("\t") + doc_lines = [d.strip() for d in doc[0].split(" || ")] if doc and doc[0].strip() else [] + rename_one(wt, crate_dir, rel, new, doc_lines, dry) + + +if __name__ == "__main__": + main() diff --git a/scripts/dev/rust_modtree.py b/scripts/dev/rust_modtree.py index c3da93b5..44f4bd66 100644 --- a/scripts/dev/rust_modtree.py +++ b/scripts/dev/rust_modtree.py @@ -9,13 +9,42 @@ 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 strip_code(text): - """The text with comments, string and char literals blanked (newlines kept) so structure can be scanned.""" +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 @@ -189,12 +218,26 @@ def parse_use_tree(text): 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, ...] @property def text(self): @@ -205,7 +248,14 @@ class Module: if self._parsed: return self._parsed items, uses, globs, self.anon, self.conditional = {}, [], [], [], set() - for attrs, head, _, _ in statements(strip_code(self.text)): + 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)) @@ -218,8 +268,7 @@ class Module: name = path[-2] if name != "_": uses.append((name, is_pub, path)) - if "cfg(" in attrs: - self.conditional.add(name) + mark(name, attrs) elif path[0] not in ("super", "self"): self.anon.append(("::".join(path), is_pub)) continue @@ -228,26 +277,22 @@ class Module: rf"(pub(?:\s*\([^)]*\))?\s+)?(?:safe\s+|unsafe\s+)?(fn|static)\s+({IDENT})", head ): items[name.removeprefix("r#")] = (bool(vis), kind) - if "cfg(" in attrs: - self.conditional.add(name.removeprefix("r#")) + 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") - if "cfg(" in attrs: - self.conditional.add(name) + 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") - if "cfg(" in attrs: - self.conditional.add(name) + 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)) - if "cfg(" in attrs: - self.conditional.add(m.group(3).removeprefix("r#")) + mark(m.group(3).removeprefix("r#"), attrs) self._parsed = (items, uses, globs) return self._parsed @@ -272,9 +317,14 @@ class Crate: 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() + 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) @@ -309,11 +359,30 @@ class Crate: return None segs = segs[1:] for seg in segs: - if cur is None or seg not in cur.children: + if cur is None: return None - cur = cur.children[seg] + 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: @@ -321,6 +390,32 @@ class Crate: 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 @@ -335,10 +430,10 @@ class Crate: 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, _ in uses: + for n, is_pub, path in uses: if full or is_pub: old = out.get(n, (False, False)) - out[n] = (old[0] or n[:1].isupper(), old[1] or n in cond) + 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)) diff --git a/scripts/dev/wsl-cargo.sh b/scripts/dev/wsl-cargo.sh index 18e1aead..ba3fe6f9 100644 --- a/scripts/dev/wsl-cargo.sh +++ b/scripts/dev/wsl-cargo.sh @@ -4,4 +4,4 @@ log="$1"; shift root="$(cd "$(dirname "$0")/../.." && pwd)" wslroot="/mnt/$(echo "${root}" | sed -E 's#^/([a-zA-Z])/#\L\1/#')" -MSYS_NO_PATHCONV=1 wsl -d Ubuntu -e bash -lc "source ~/.cargo/env; cd '${wslroot}'; export CARGO_INCREMENTAL=0 CARGO_TARGET_DIR=\$PWD/target/wsl; cargo $* > '${wslroot}/${log}' 2>&1; echo \"EXIT \$?\" >> '${wslroot}/${log}'" +MSYS_NO_PATHCONV=1 wsl -d Ubuntu -e bash -lc "source ~/.cargo/env; cd '${wslroot}'; export CARGO_INCREMENTAL=0 CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4} CARGO_TARGET_DIR=\$PWD/target/wsl; cargo $* > '${wslroot}/${log}' 2>&1; echo \"EXIT \$?\" >> '${wslroot}/${log}'"