from __future__ import annotations import argparse import re import sys from pathlib import Path SOURCE_SUFFIXES = {".f90", ".c", ".h", ".py"} FORTRAN_ROUTINE = re.compile( r"^\s*(?:recursive\s+)?(?:subroutine|function|integer\s+function|" r"logical\s+function|real\s*\([^)]*\)\s+function|" r"type\s*\([^)]*\)\s+function)\s+([a-zA-Z_]\w*)", re.IGNORECASE, ) PYTHON_FUNCTION = re.compile(r"^(?P\s*)def\s+(?P[a-zA-Z_]\w*)\s*\(") C_FUNCTION = re.compile( r"^\s*(?:static\s+)?(?:int|void|double|float|char|long|short|size_t|" r"bool)\s+([a-zA-Z_]\w*)\s*\([^;]*\)\s*\{?\s*$" ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Check FemLite source size limits.") parser.add_argument("repo_root") parser.add_argument("--warn-file-lines", type=int, default=1500) parser.add_argument("--max-file-lines", type=int, default=2000) parser.add_argument("--warn-routine-lines", type=int, default=100) parser.add_argument("--max-routine-lines", type=int, default=128) parser.add_argument("--exceptions", default="") return parser.parse_args() def source_files(repo_root: Path) -> list[Path]: files: list[Path] = [] for folder in ("src", "tests", "tools"): root = repo_root / folder if not root.exists(): continue for path in root.rglob("*"): if path.is_file() and path.suffix.lower() in SOURCE_SUFFIXES: files.append(path) return sorted(files) def fortran_routines(lines: list[str]) -> list[tuple[str, int, int]]: starts: list[tuple[str, int]] = [] for line_no, line in enumerate(lines, start=1): match = FORTRAN_ROUTINE.match(line) if match: starts.append((match.group(1), line_no)) routines: list[tuple[str, int, int]] = [] for index, (name, start) in enumerate(starts): end = starts[index + 1][1] - 1 if index + 1 < len(starts) else len(lines) routines.append((name, start, end - start + 1)) return routines def python_functions(lines: list[str]) -> list[tuple[str, int, int]]: routines: list[tuple[str, int, int]] = [] for line_no, line in enumerate(lines, start=1): match = PYTHON_FUNCTION.match(line) if not match: continue indent = len(match.group("indent")) end = len(lines) for next_no in range(line_no + 1, len(lines) + 1): next_line = lines[next_no - 1] if len(next_line.strip()) == 0: continue next_indent = len(next_line) - len(next_line.lstrip()) if next_indent <= indent: end = next_no - 1 break routines.append((match.group("name"), line_no, end - line_no + 1)) return routines def c_functions(lines: list[str]) -> list[tuple[str, int, int]]: routines: list[tuple[str, int, int]] = [] line_no = 1 while line_no <= len(lines): match = C_FUNCTION.match(lines[line_no - 1]) if not match: line_no += 1 continue depth = lines[line_no - 1].count("{") - lines[line_no - 1].count("}") end = line_no while end < len(lines) and depth > 0: end += 1 depth += lines[end - 1].count("{") - lines[end - 1].count("}") routines.append((match.group(1), line_no, end - line_no + 1)) line_no = end + 1 return routines def routines_for(path: Path, lines: list[str]) -> list[tuple[str, int, int]]: suffix = path.suffix.lower() if suffix == ".f90": return fortran_routines(lines) if suffix == ".py": return python_functions(lines) if suffix in {".c", ".h"}: return c_functions(lines) return [] def load_exceptions(repo_root: Path, relpath: str) -> dict[tuple[str, str, str], str]: exceptions: dict[tuple[str, str, str], str] = {} if not relpath: return exceptions path = repo_root / relpath if not path.exists(): return exceptions for raw_line in path.read_text(encoding="utf-8").splitlines(): line = raw_line.strip() if not line or line.startswith("#"): continue parts = line.split("|", 3) if len(parts) != 4: raise ValueError(f"bad exception line in {path}: {raw_line}") kind, source_path, name, reason = (part.strip() for part in parts) if not reason: raise ValueError(f"missing exception reason in {path}: {raw_line}") exceptions[(kind, source_path.replace("\\", "/"), name)] = reason return exceptions def exception_reason( exceptions: dict[tuple[str, str, str], str], kind: str, relative: Path, name: str = "", ) -> str: return exceptions.get((kind, relative.as_posix(), name), "") def main() -> int: args = parse_args() repo_root = Path(args.repo_root).resolve() violations: list[str] = [] warnings: list[str] = [] exceptions = load_exceptions(repo_root, args.exceptions) used_exceptions: set[tuple[str, str, str]] = set() for path in source_files(repo_root): lines = path.read_text(encoding="utf-8").splitlines() relative = path.relative_to(repo_root) file_reason = exception_reason(exceptions, "file", relative) if len(lines) > args.max_file_lines: message = f"{relative}: file has {len(lines)} lines, hard limit is {args.max_file_lines}" if file_reason: used_exceptions.add(("file", relative.as_posix(), "")) warnings.append(f"{message}; exception: {file_reason}") else: violations.append(message) elif len(lines) > args.warn_file_lines: warnings.append( f"{relative}: file has {len(lines)} lines, review target is " f"{args.warn_file_lines}" ) for name, start, count in routines_for(path, lines): routine_reason = exception_reason(exceptions, "routine", relative, name) if count > args.max_routine_lines: message = ( f"{relative}:{start}: {name} has {count} lines, " f"hard limit is {args.max_routine_lines}" ) if routine_reason: used_exceptions.add(("routine", relative.as_posix(), name)) warnings.append(f"{message}; exception: {routine_reason}") else: violations.append(message) elif count > args.warn_routine_lines: warnings.append( f"{relative}:{start}: {name} has {count} lines, review target " f"is {args.warn_routine_lines}" ) for kind, source_path, name in sorted(set(exceptions) - used_exceptions): violations.append( f"stale source size exception: {kind}|{source_path}|{name} " "does not match a current hard-threshold item" ) if violations: print("Source size limit violations:") for violation in violations: print(f" {violation}") if warnings: print("Source size warnings:") for warning in warnings: print(f" {warning}") return 1 print( "Source size limits passed: " f"files require review above {args.warn_file_lines} lines and " f"exceptions above {args.max_file_lines}; " f"routines target {args.warn_routine_lines} lines and require " f"exceptions above {args.max_routine_lines}" ) if warnings: print("Source size warnings:") for warning in warnings: print(f" {warning}") return 0 if __name__ == "__main__": sys.exit(main())