Checker for function-local static variables in header files.
| 41 | |
| 42 | |
| 43 | class StaticInHeaderChecker(FileContentChecker): |
| 44 | """Checker for function-local static variables in header files.""" |
| 45 | |
| 46 | # Pre-compiled regexes (class-level to avoid re-compilation per file) |
| 47 | _INLINE_FUNC_PATTERN = re.compile(r"\w+\s*\([^)]*\)\s*\{") |
| 48 | _TEMPLATE_PATTERN = re.compile(r"^\s*template\s*<") |
| 49 | _STATIC_VAR_PATTERN = re.compile( |
| 50 | r"\bstatic\s+" # "static" keyword |
| 51 | r"(?:const\s+)?" # optional "const" |
| 52 | r"[\w:]+(?:<[^>]+>)?\s+" # type (with optional template args) |
| 53 | r"\w+\s*" # variable name |
| 54 | r"[=({]" # followed by =, (, or { |
| 55 | ) |
| 56 | _STATIC_FUNC_PATTERN = re.compile( |
| 57 | r"static\s+[\w:]+(?:<[^>]+>)?\s+\w+\s*\([^)]*\)\s*\{" |
| 58 | ) |
| 59 | |
| 60 | def __init__(self): |
| 61 | self.violations: dict[str, list[tuple[int, str]]] = {} |
| 62 | |
| 63 | def should_process_file(self, file_path: str) -> bool: |
| 64 | """Only process header files (.h, .hpp).""" |
| 65 | # Only check header files |
| 66 | if not file_path.endswith((".h", ".hpp")): |
| 67 | return False |
| 68 | |
| 69 | # Exclude .cpp.hpp files (unity build implementation files, not traditional headers) |
| 70 | if file_path.endswith(".cpp.hpp"): |
| 71 | return False |
| 72 | |
| 73 | # Check if file is in excluded list |
| 74 | if any(file_path.endswith(excluded) for excluded in EXCLUDED_FILES): |
| 75 | return False |
| 76 | |
| 77 | return True |
| 78 | |
| 79 | def check_file_content(self, file_content: FileContent) -> list[str]: |
| 80 | """Check header file for function-local static variables.""" |
| 81 | # Fast file-level check: skip if "static" not in file at all |
| 82 | if "static" not in file_content.content: |
| 83 | return [] |
| 84 | |
| 85 | violations: list[tuple[int, str]] = [] |
| 86 | in_multiline_comment = False |
| 87 | brace_depth = 0 # Track brace nesting level |
| 88 | in_function = False # Are we inside a function implementation? |
| 89 | in_template_function = False # Are we inside a template function? |
| 90 | |
| 91 | for line_number, line in enumerate(file_content.lines, 1): |
| 92 | stripped = line.strip() |
| 93 | |
| 94 | # Track multi-line comment state |
| 95 | if "/*" in line: |
| 96 | in_multiline_comment = True |
| 97 | if "*/" in line: |
| 98 | in_multiline_comment = False |
| 99 | continue |
| 100 |