Checker class for .cpp file includes.
| 8 | |
| 9 | |
| 10 | class CppIncludeChecker(FileContentChecker): |
| 11 | """Checker class for .cpp file includes.""" |
| 12 | |
| 13 | # Pre-compiled regex for #include with .cpp extension (class-level) |
| 14 | _CPP_INCLUDE_PATTERN = re.compile(r'#include\s+[<"]([^>"]+\.cpp)[>"]') |
| 15 | |
| 16 | def __init__(self): |
| 17 | self.violations: dict[str, list[tuple[int, str]]] = {} |
| 18 | |
| 19 | def should_process_file(self, file_path: str) -> bool: |
| 20 | """Check if file should be processed for .cpp includes.""" |
| 21 | # Check file extension |
| 22 | if not file_path.endswith((".cpp", ".h", ".hpp", ".ino")): |
| 23 | return False |
| 24 | |
| 25 | # Check if file is in excluded list |
| 26 | if any(file_path.endswith(excluded) for excluded in EXCLUDED_FILES): |
| 27 | return False |
| 28 | |
| 29 | return True |
| 30 | |
| 31 | def check_file_content(self, file_content: FileContent) -> list[str]: |
| 32 | """Check file content for .cpp file includes.""" |
| 33 | # Unity build aggregator files are exempt — they exist solely to |
| 34 | # #include other .cpp files into a single translation unit. |
| 35 | for line in file_content.lines[:5]: |
| 36 | if "// ok cpp include" in line.lower(): |
| 37 | return [] |
| 38 | |
| 39 | violations: list[tuple[int, str]] = [] |
| 40 | in_multiline_comment = False |
| 41 | |
| 42 | # Check each line for .cpp includes |
| 43 | for line_number, line in enumerate(file_content.lines, 1): |
| 44 | stripped = line.strip() |
| 45 | |
| 46 | # Track multi-line comment state |
| 47 | if "/*" in line: |
| 48 | in_multiline_comment = True |
| 49 | if "*/" in line: |
| 50 | in_multiline_comment = False |
| 51 | continue # Skip the line with closing */ |
| 52 | |
| 53 | # Skip if we're inside a multi-line comment |
| 54 | if in_multiline_comment: |
| 55 | continue |
| 56 | |
| 57 | # Skip single-line comment lines |
| 58 | if stripped.startswith("//"): |
| 59 | continue |
| 60 | |
| 61 | # Remove single-line comment portion before checking |
| 62 | code_part = line.split("//")[0] |
| 63 | |
| 64 | # Check for .cpp includes in code portion |
| 65 | match = self._CPP_INCLUDE_PATTERN.search(code_part) |
| 66 | if match: |
| 67 | cpp_file = match.group(1) |