Files
greptimedb/scripts/check-snafu.py
dennis zhuang 0f6a9b3d6e chore: catch unused snafu variants shadowed by other crates and remove them (#10826)
* chore: catch unused snafu variants shadowed by other crates and remove them

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix: count shorthand variant constructions in error files as uses

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

* fix: parse nested expressions and literals when telling variant constructions from patterns

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>

---------

Signed-off-by: Dennis Zhuang <killme2008@gmail.com>
2026-12-02 12:18:45 +00:00

191 lines
6.8 KiB
Python

# Copyright 2023 Greptime Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
from multiprocessing import Pool
ENUM_PATTERN = re.compile(r"\benum\s+(\w+)")
# The display arguments may contain `)` inside string literals.
VARIANT_PATTERN = re.compile(
r'#\[snafu\(display\((?:"(?:\\.|[^"\\])*"|[^"])*?\)\)\]\s*(?:#\[[^\]]*\]\s*)*(\w+)\s*\{'
)
def find_rust_files(directory):
rust_files = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".rs"):
rust_files.append(os.path.abspath(os.path.join(root, file)))
return rust_files
def crate_of(path):
"""Returns the (root directory, library name) of the crate that contains `path`."""
directory = os.path.dirname(os.path.abspath(path))
while not os.path.exists(os.path.join(directory, "Cargo.toml")):
directory = os.path.dirname(directory)
with open(os.path.join(directory, "Cargo.toml"), "r") as file:
name = re.search(r'^name\s*=\s*"([^"]+)"', file.read(), re.MULTILINE).group(1)
return directory, name.replace("-", "_")
def extract_variants(file_content):
"""Yields (enum, variant) for every variant with a snafu display."""
enums = [(m.start(), m.group(1)) for m in ENUM_PATTERN.finditer(file_content)]
for m in VARIANT_PATTERN.finditer(file_content):
enum = [name for start, name in enums if start < m.start()][-1]
yield enum, m.group(1)
def error_module_paths(crate_name, content):
"""Returns the paths through which `content` refers to `crate_name`'s error module."""
paths = [f"{crate_name}::error"]
for m in re.finditer(
rf"\buse\s+{crate_name}::(?:error(?:\s+as\s+(\w+))?\s*;|error::\{{\s*self\b(?:\s+as\s+(\w+))?"
rf"|\{{[^}}]*\berror\b(?:\s+as\s+(\w+))?)",
content,
):
paths.append(next((alias for alias in m.groups() if alias), "error"))
return paths
LITERAL_PATTERN = re.compile(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])\'')
def struct_body(content, open_brace):
"""Splits the struct body starting at `open_brace` into its top-level fields.
Returns the fields and the index of the closing brace, or None if the body is unclosed.
String and char literals are skipped, so braces and commas inside them do not count.
"""
fields, field, depth, i = [], "", 0, open_brace
while i < len(content):
literal = LITERAL_PATTERN.match(content, i)
if literal:
field += literal.group()
i = literal.end()
continue
c = content[i]
if c in "{([":
depth += 1
elif c in "})]":
depth -= 1
if depth == 0:
fields.append(field.strip())
return [f for f in fields if f], i
if depth == 1 and c in "{,":
if c == ",":
fields.append(field.strip())
field = ""
else:
field += c
i += 1
return None
def builds_variant(enum, variant, content):
"""Returns whether `content` builds `variant` with a struct expression, not a pattern."""
for m in re.finditer(rf"\b(?:{enum}|Self)::{variant}\s*\{{", content):
body = struct_body(content, m.end() - 1)
if body is None:
continue
fields, close = body
# An alternative of an or-pattern is always followed by `|`, `=>` or a guard.
after = content[close + 1 :].lstrip()
is_pattern = (fields and fields[-1] == "..") or after.startswith(
("=>", "|", "if ")
)
if not is_pattern:
return True
return False
def is_used(error_file, enum, variant, crate, rust_files_content):
crate_root, crate_name = crate
# Match arms in the error file are not uses, but a helper there may build the variant, and a
# macro may take it, e.g. `define_from_tonic_status!(Error, X)`.
error_file_content = rust_files_content[error_file]
if re.search(
rf"\b{variant}Snafu\b|\b{enum},\s*{variant}\b", error_file_content
) or builds_variant(enum, variant, error_file_content):
return True
crate_uses = re.compile(rf"\b({variant}Snafu|{enum}::{variant}|Self::{variant})\b")
imported_selector = re.compile(
rf"\b{crate_name}::error::\{{[^}}]*\b{variant}Snafu\b"
)
for path, content in rust_files_content.items():
if path == error_file or variant not in content:
continue
if path.startswith(crate_root + os.sep):
if crate_uses.search(content):
return True
continue
# Other crates may define variants with the same names, so a use there must go through
# this crate's error module: an imported selector, a path, or `Self::X` in a `From` impl.
if crate_name not in content:
continue
if imported_selector.search(content):
return True
modules = "|".join(map(re.escape, error_module_paths(crate_name, content)))
if re.search(
rf"\b(?:{modules})::(?:{variant}Snafu|{enum}::{variant})\b", content
):
return True
if f"for {crate_name}::error::{enum}" in content and re.search(
rf"\bSelf::{variant}\b", content
):
return True
return False
def main():
# Read all rust files into memory once
rust_files_content = {}
for rust_file in find_rust_files("."):
with open(rust_file, "r") as file:
rust_files_content[rust_file] = file.read()
variants = []
for path, content in rust_files_content.items():
if os.path.basename(path) == "error.rs":
crate = crate_of(path)
for enum, variant in extract_variants(content):
variants.append((path, enum, variant, crate))
with Pool() as pool:
results = pool.starmap(
is_used,
[
(error_file, enum, variant, crate, rust_files_content)
for error_file, enum, variant, crate in variants
],
)
unused_snafu = [
(error_file, variant)
for (error_file, _, variant, _), found in zip(variants, results)
if not found
]
if unused_snafu:
print("Unused error variants:")
for error_file, variant in unused_snafu:
print(f"{os.path.relpath(error_file)}: {variant}")
raise SystemExit(1)
if __name__ == "__main__":
main()