|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Apply Slither naming-convention fixes from slither-report.json (dry-run safe: writes files).""" |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import re |
| 7 | +import sys |
| 8 | +from collections import defaultdict |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +REPORT = Path("slither-report.json") |
| 12 | +ROOT = Path(__file__).resolve().parents[1] |
| 13 | + |
| 14 | + |
| 15 | +def word_repl(text: str, old: str, new: str) -> str: |
| 16 | + pat = re.compile(r"(?<![a-zA-Z0-9_])" + re.escape(old) + r"(?![a-zA-Z0-9_])") |
| 17 | + return pat.sub(new, text) |
| 18 | + |
| 19 | + |
| 20 | +def to_mixed_case_from_caps(name: str) -> str: |
| 21 | + """MY_UINT -> myUint, DOMAIN_SEPARATOR handled elsewhere.""" |
| 22 | + if "_" in name: |
| 23 | + parts = [p for p in name.split("_") if p] |
| 24 | + if not parts: |
| 25 | + return name.lower() |
| 26 | + head = parts[0].lower() |
| 27 | + tail = "".join(p.capitalize() for p in parts[1:]) |
| 28 | + return head + tail |
| 29 | + if len(name) == 1: |
| 30 | + return name.lower() |
| 31 | + return name[0].lower() + name[1:] |
| 32 | + |
| 33 | + |
| 34 | +def suggest_new_name(name: str, contract: str | None) -> str: |
| 35 | + if name.startswith("_"): |
| 36 | + return name[1:] |
| 37 | + if name == "DOMAIN_SEPARATOR": |
| 38 | + return "domainSeparator" |
| 39 | + if name == "A" and contract == "StableSwapAMM": |
| 40 | + return "amplificationCoefficient" |
| 41 | + if name.isupper() or (len(name) > 1 and name[0].isupper() and "_" in name): |
| 42 | + return to_mixed_case_from_caps(name) |
| 43 | + return name |
| 44 | + |
| 45 | + |
| 46 | +def main() -> int: |
| 47 | + if not REPORT.exists(): |
| 48 | + print("Missing slither-report.json — run: bash scripts/slither-summary.sh", file=sys.stderr) |
| 49 | + return 1 |
| 50 | + |
| 51 | + data = json.loads(REPORT.read_text(encoding="utf-8")) |
| 52 | + detectors = data["results"]["detectors"] |
| 53 | + |
| 54 | + # (relative_path, start_line, end_line) -> {old: new} |
| 55 | + ranges: dict[tuple[str, int, int], dict[str, str]] = defaultdict(dict) |
| 56 | + function_renames: dict[tuple[str, str], str] = {} # (file, old_fn) -> new_fn |
| 57 | + |
| 58 | + for det in detectors: |
| 59 | + if det["check"] != "naming-convention": |
| 60 | + continue |
| 61 | + el0 = det["elements"][0] |
| 62 | + etype = el0["type"] |
| 63 | + |
| 64 | + if etype == "function": |
| 65 | + fname = el0["name"] |
| 66 | + rel = el0["source_mapping"]["filename_short"] |
| 67 | + new_fn = fname.replace("_UNOPTIMIZED", "Unoptimized") |
| 68 | + if new_fn != fname: |
| 69 | + function_renames[(rel, fname)] = new_fn |
| 70 | + continue |
| 71 | + |
| 72 | + if etype != "variable": |
| 73 | + continue |
| 74 | + |
| 75 | + name = el0["name"] |
| 76 | + rel = el0["source_mapping"]["filename_short"] |
| 77 | + if rel.startswith("src/hacks/"): |
| 78 | + continue |
| 79 | + |
| 80 | + parent = el0.get("type_specific_fields", {}).get("parent", {}) |
| 81 | + contract_name = None |
| 82 | + if parent.get("type") == "contract": |
| 83 | + contract_name = parent.get("name") |
| 84 | + lines = parent["source_mapping"].get("lines", []) |
| 85 | + elif parent.get("type") == "function": |
| 86 | + gp = parent.get("type_specific_fields", {}).get("parent", {}) |
| 87 | + if gp.get("type") == "contract": |
| 88 | + contract_name = gp.get("name") |
| 89 | + lines = parent["source_mapping"].get("lines", []) |
| 90 | + else: |
| 91 | + lines = [] |
| 92 | + |
| 93 | + if not lines: |
| 94 | + continue |
| 95 | + |
| 96 | + lo, hi = min(lines), max(lines) |
| 97 | + new_name = suggest_new_name(name, contract_name) |
| 98 | + if new_name == name: |
| 99 | + continue |
| 100 | + |
| 101 | + bucket = ranges[(rel, lo, hi)] |
| 102 | + if name in bucket and bucket[name] != new_name: |
| 103 | + print(f"Conflict {rel} L{lo}-{hi}: {name} -> {bucket[name]} vs {new_name}", file=sys.stderr) |
| 104 | + return 2 |
| 105 | + bucket[name] = new_name |
| 106 | + |
| 107 | + # Apply function renames file-wise (full file) |
| 108 | + by_file_fn: dict[str, dict[str, str]] = defaultdict(dict) |
| 109 | + for (rel, old), new in function_renames.items(): |
| 110 | + by_file_fn[rel][old] = new |
| 111 | + |
| 112 | + for rel, mapping in by_file_fn.items(): |
| 113 | + path = ROOT / rel |
| 114 | + text = path.read_text(encoding="utf-8") |
| 115 | + for old, new in sorted(mapping.items(), key=lambda x: len(x[0]), reverse=True): |
| 116 | + text = word_repl(text, old, new) |
| 117 | + path.write_text(text, encoding="utf-8", newline="\n") |
| 118 | + print(f"renamed functions in {rel}: {mapping}") |
| 119 | + |
| 120 | + # Apply variable renames per function range |
| 121 | + by_path: dict[str, list[tuple[int, int, dict[str, str]]]] = defaultdict(list) |
| 122 | + for (rel, lo, hi), mapping in ranges.items(): |
| 123 | + if not mapping: |
| 124 | + continue |
| 125 | + by_path[rel].append((lo, hi, mapping)) |
| 126 | + |
| 127 | + for rel, chunks in by_path.items(): |
| 128 | + path = ROOT / rel |
| 129 | + lines = path.read_text(encoding="utf-8").split("\n") |
| 130 | + # process smaller inner ranges first if nested? sort by span length ascending |
| 131 | + chunks.sort(key=lambda x: (x[1] - x[0], x[0])) |
| 132 | + for lo, hi, mapping in chunks: |
| 133 | + segment = "\n".join(lines[lo - 1 : hi]) |
| 134 | + for old, new in sorted(mapping.items(), key=lambda x: len(x[0]), reverse=True): |
| 135 | + segment = word_repl(segment, old, new) |
| 136 | + new_lines = segment.split("\n") |
| 137 | + lines[lo - 1 : hi] = new_lines |
| 138 | + path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") |
| 139 | + print(f"updated {rel} ({len(chunks)} span(s))") |
| 140 | + |
| 141 | + return 0 |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == "__main__": |
| 145 | + raise SystemExit(main()) |
0 commit comments