| 1 |
#!/usr/bin/env python3 |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import argparse |
| 5 |
import os |
| 6 |
import re |
| 7 |
import sys |
| 8 |
import tempfile |
| 9 |
from concurrent.futures import ThreadPoolExecutor, as_completed |
| 10 |
from pathlib import Path |
| 11 |
from re import Pattern |
| 12 |
|
| 13 |
""" |
| 14 |
Borrow-ref C API linter (Python version). |
| 15 |
|
| 16 |
- Recursively scans source files under --root (default: numpy) |
| 17 |
- Matches suspicious CPython C-API calls as whole identifiers |
| 18 |
- Skips: |
| 19 |
- lines with '// noqa: borrowed-ref OK' or |
| 20 |
'// noqa: borrowed-ref - manual fix needed' |
| 21 |
- line comments (// ...) |
| 22 |
- block comments (/* ... */), even when they span lines |
| 23 |
- Prints findings and exits 1 if any issues found, else 0 |
| 24 |
""" |
| 25 |
|
| 26 |
def strip_comments(line: str, in_block: bool) -> tuple[str, bool]: |
| 27 |
""" |
| 28 |
Return (code_without_comments, updated_in_block). |
| 29 |
Removes // line comments and /* ... */ block comments (non-nesting, C-style). |
| 30 |
""" |
| 31 |
i = 0 |
| 32 |
out_parts: list[str] = [] |
| 33 |
n = len(line) |
| 34 |
|
| 35 |
while i < n: |
| 36 |
if in_block: |
| 37 |
end = line.find("*/", i) |
| 38 |
if end == -1: |
| 39 |
# Entire remainder is inside a block comment. |
| 40 |
return ("".join(out_parts), True) |
| 41 |
i = end + 2 |
| 42 |
in_block = False |
| 43 |
continue |
| 44 |
|
| 45 |
# Not in block: look for next // or /* from current i |
| 46 |
sl = line.find("//", i) |
| 47 |
bl = line.find("/*", i) |
| 48 |
|
| 49 |
if sl != -1 and (bl == -1 or sl < bl): |
| 50 |
# Line comment starts first: take code up to '//' and stop |
| 51 |
out_parts.append(line[i:sl]) |
| 52 |
return ("".join(out_parts), in_block) |
| 53 |
|
| 54 |
if bl != -1: |
| 55 |
# Block comment starts: take code up to '/*', then enter block |
| 56 |
out_parts.append(line[i:bl]) |
| 57 |
i = bl + 2 |
| 58 |
in_block = True |
| 59 |
continue |
| 60 |
|
| 61 |
# No more comments |
| 62 |
out_parts.append(line[i:]) |
| 63 |
break |
| 64 |
|
| 65 |
return ("".join(out_parts), in_block) |
| 66 |
|
| 67 |
def iter_source_files(root: Path, exts: set[str], excludes: set[str]) -> list[Path]: |
| 68 |
""" |
| 69 |
Return a list of source files under 'root', where filenames end with any of the |
| 70 |
extensions in 'exts' (e.g., '.c.src', '.c', '.h'). |
| 71 |
Excludes directories whose names are in 'excludes'. |
| 72 |
""" |
| 73 |
results: list[Path] = [] |
| 74 |
|
| 75 |
for dirpath, dirnames, filenames in os.walk(root): |
| 76 |
# Prune excluded directories |
| 77 |
dirnames[:] = [d for d in dirnames if d not in excludes] |
| 78 |
for fn in filenames: |
| 79 |
# endswith handles mult-suffice patterns, e.g., .c.src |
| 80 |
if any(fn.endswith(ext) for ext in exts): |
| 81 |
results.append(Path(dirpath) / fn) |
| 82 |
return results |
| 83 |
|
| 84 |
def build_func_rx(funcs: tuple[str, ...]) -> Pattern[str]: |
| 85 |
return re.compile(r"(?<!\w)(?:" + "|".join(map(re.escape, funcs)) + r")(?!\w)") |
| 86 |
|
| 87 |
def scan_file( |
| 88 |
path: Path, |
| 89 |
func_rx: Pattern[str], |
| 90 |
noqa_markers: tuple[str, ...] |
| 91 |
) -> list[tuple[str, int, str, str]]: |
| 92 |
""" |
| 93 |
Scan a single file. |
| 94 |
Returns list of (func_name, line_number, path_str, raw_line_str). |
| 95 |
""" |
| 96 |
hits: list[tuple[str, int, str, str]] = [] |
| 97 |
in_block = False |
| 98 |
noqa_set = set(noqa_markers) |
| 99 |
|
| 100 |
try: |
| 101 |
with path.open("r", encoding="utf-8", errors="ignore") as f: |
| 102 |
for lineno, raw in enumerate(f, 1): |
| 103 |
# Skip if approved by noqa markers |
| 104 |
if any(mark in raw for mark in noqa_set): |
| 105 |
continue |
| 106 |
|
| 107 |
# Remove comments; if nothing remains, skip |
| 108 |
code, in_block = strip_comments(raw.rstrip("\n"), in_block) |
| 109 |
if not code.strip(): |
| 110 |
continue |
| 111 |
|
| 112 |
# Find all suspicious calls in non-comment code |
| 113 |
for m in func_rx.finditer(code): |
| 114 |
hits.append((m.group(0), lineno, str(path), raw.rstrip("\n"))) |
| 115 |
except FileNotFoundError: |
| 116 |
# File may have disappeared; ignore gracefully |
| 117 |
pass |
| 118 |
return hits |
| 119 |
|
| 120 |
|
| 121 |
def main(argv: list[str] | None = None) -> int: |
| 122 |
# List of suspicious function calls: |
| 123 |
suspicious_funcs: tuple[str, ...] = ( |
| 124 |
"PyList_GetItem", |
| 125 |
"PyDict_GetItem", |
| 126 |
"PyDict_GetItemWithError", |
| 127 |
"PyDict_GetItemString", |
| 128 |
"PyDict_SetDefault", |
| 129 |
"PyDict_Next", |
| 130 |
"PyWeakref_GetObject", |
| 131 |
"PyWeakref_GET_OBJECT", |
| 132 |
"PyList_GET_ITEM", |
| 133 |
"_PyDict_GetItemStringWithError", |
| 134 |
"PySequence_Fast" |
| 135 |
) |
| 136 |
func_rx = build_func_rx(suspicious_funcs) |
| 137 |
noqa_markers = ( |
| 138 |
"noqa: borrowed-ref OK", |
| 139 |
"noqa: borrowed-ref - manual fix needed" |
| 140 |
) |
| 141 |
default_exts = {".c", ".h", ".c.src", ".cpp"} |
| 142 |
default_excludes = {"pythoncapi-compat"} |
| 143 |
|
| 144 |
ap = argparse.ArgumentParser(description="Borrow-ref C API linter (Python).") |
| 145 |
ap.add_argument( |
| 146 |
"--quiet", |
| 147 |
action="store_true", |
| 148 |
help="Suppress normal output; exit status alone indicates result (useful\ |
| 149 |
for CI).", |
| 150 |
) |
| 151 |
ap.add_argument( |
| 152 |
"-j", "--jobs", |
| 153 |
type=int, |
| 154 |
default=0, |
| 155 |
help="Number of worker threads (0=auto, 1=sequential).", |
| 156 |
) |
| 157 |
ap.add_argument( |
| 158 |
"--root", |
| 159 |
default="numpy", |
| 160 |
type=str, |
| 161 |
help="Root directory to scan (default: numpy)" |
| 162 |
) |
| 163 |
ap.add_argument( |
| 164 |
"--ext", |
| 165 |
action="append", |
| 166 |
default=None, |
| 167 |
help=f"File extension(s) to include (repeatable). Defaults to {default_exts}", |
| 168 |
) |
| 169 |
ap.add_argument( |
| 170 |
"--exclude", |
| 171 |
action="append", |
| 172 |
default=None, |
| 173 |
help=f"Directory name(s) to exclude (repeatable). Default: {default_excludes}", |
| 174 |
) |
| 175 |
args = ap.parse_args(argv) |
| 176 |
|
| 177 |
if args.ext: |
| 178 |
exts = {e if e.startswith(".") else f".{e}" for e in args.ext} |
| 179 |
else: |
| 180 |
exts = set(default_exts) |
| 181 |
excludes = set(args.exclude) if args.exclude else set(default_excludes) |
| 182 |
|
| 183 |
root = Path(args.root) |
| 184 |
if not root.exists(): |
| 185 |
print(f"error: root '{root}' does not exist", file=sys.stderr) |
| 186 |
return 2 |
| 187 |
|
| 188 |
files = sorted(iter_source_files(root, exts, excludes), key=str) |
| 189 |
|
| 190 |
# Determine concurrency: auto picks a reasonable cap for I/O-bound work |
| 191 |
if args.jobs is None or args.jobs <= 0: |
| 192 |
max_workers = min(32, (os.cpu_count() or 1) * 5) |
| 193 |
else: |
| 194 |
max_workers = max(1, args.jobs) |
| 195 |
print(f'Scanning {len(files)} C/C++ source files...\n') |
| 196 |
|
| 197 |
# Output file (mirrors your shell behavior) |
| 198 |
tmpdir = Path(".tmp") |
| 199 |
tmpdir.mkdir(exist_ok=True) |
| 200 |
|
| 201 |
findings = 0 |
| 202 |
|
| 203 |
# Run the scanning in parallel; only the main thread writes the report |
| 204 |
all_hits: list[tuple[str, int, str, str]] = [] |
| 205 |
if max_workers == 1: |
| 206 |
for p in files: |
| 207 |
all_hits.extend(scan_file(p, func_rx, noqa_markers)) |
| 208 |
else: |
| 209 |
with ThreadPoolExecutor(max_workers=max_workers) as ex: |
| 210 |
fut_to_file = {ex.submit(scan_file, p, func_rx, noqa_markers): |
| 211 |
p for p in files} |
| 212 |
for fut in as_completed(fut_to_file): |
| 213 |
try: |
| 214 |
all_hits.extend(fut.result()) |
| 215 |
except Exception as e: |
| 216 |
print(f'Failed to scan {fut_to_file[fut]}: {e}') |
| 217 |
|
| 218 |
# Sort for deterministic output: by path, then line number |
| 219 |
all_hits.sort(key=lambda t: (t[2], t[1])) |
| 220 |
|
| 221 |
# There no hits, linter passed |
| 222 |
if not all_hits: |
| 223 |
if not args.quiet: |
| 224 |
print("All checks passed! C API borrow-ref linter found no issues.\n") |
| 225 |
return 0 |
| 226 |
|
| 227 |
# There are some linter failures: create a log file |
| 228 |
with tempfile.NamedTemporaryFile( |
| 229 |
prefix="c_api_usage_report.", |
| 230 |
suffix=".txt", |
| 231 |
dir=tmpdir, |
| 232 |
mode="w+", |
| 233 |
encoding="utf-8", |
| 234 |
delete=False, |
| 235 |
) as out: |
| 236 |
report_path = Path(out.name) |
| 237 |
out.write("Running Suspicious C API usage report workflow...\n\n") |
| 238 |
for func, lineo, pstr, raw in all_hits: |
| 239 |
findings += 1 |
| 240 |
out.write(f"Found suspicious call to {func} in file: {pstr}\n") |
| 241 |
out.write(f" -> {pstr}:{lineo}a:{raw}\n") |
| 242 |
out.write("Recommendation:\n") |
| 243 |
out.write( |
| 244 |
"If this use is intentional and safe, add " |
| 245 |
"'// noqa: borrowed-ref OK' on the same line " |
| 246 |
"to silence this warning.\n" |
| 247 |
) |
| 248 |
out.write( |
| 249 |
"Otherwise, consider replacing the call " |
| 250 |
"with a thread-safe API function.\n\n" |
| 251 |
) |
| 252 |
|
| 253 |
out.flush() |
| 254 |
if not args.quiet: |
| 255 |
out.seek(0) |
| 256 |
sys.stdout.write(out.read()) |
| 257 |
print(f"Report written to: {report_path}\n\n\ |
| 258 |
C API borrow-ref linter FAILED.") |
| 259 |
|
| 260 |
return 1 |
| 261 |
|
| 262 |
|
| 263 |
if __name__ == "__main__": |
| 264 |
|
| 265 |
sys.exit(main()) |