Forbid raw Serial.* method calls in enforced example sketches.
| 95 | |
| 96 | |
| 97 | class ExampleSerialChecker(FileContentChecker): |
| 98 | """Forbid raw Serial.* method calls in enforced example sketches.""" |
| 99 | |
| 100 | def __init__(self) -> None: |
| 101 | self.violations: dict[str, list[tuple[int, str]]] = {} |
| 102 | |
| 103 | def should_process_file(self, file_path: str) -> bool: |
| 104 | if not file_path.endswith((".cpp", ".h", ".hpp", ".ino")): |
| 105 | return False |
| 106 | if not _enforced_for(file_path): |
| 107 | return False |
| 108 | return True |
| 109 | |
| 110 | def check_file_content(self, file_content: FileContent) -> list[str]: |
| 111 | violations: list[tuple[int, str]] = [] |
| 112 | in_multiline_comment = False |
| 113 | |
| 114 | for line_number, line in enumerate(file_content.lines, 1): |
| 115 | stripped = line.strip() |
| 116 | |
| 117 | # Track multi-line comment state. |
| 118 | if "/*" in line: |
| 119 | in_multiline_comment = True |
| 120 | if "*/" in line: |
| 121 | in_multiline_comment = False |
| 122 | continue |
| 123 | |
| 124 | if in_multiline_comment: |
| 125 | continue |
| 126 | |
| 127 | if stripped.startswith("//"): |
| 128 | continue |
| 129 | |
| 130 | code_part = line.split("//")[0] |
| 131 | comment_part = line[len(code_part) :].lower() |
| 132 | |
| 133 | # Fast pre-check. |
| 134 | if "Serial." not in code_part: |
| 135 | continue |
| 136 | |
| 137 | match = SERIAL_METHOD_PATTERN.search(code_part) |
| 138 | if not match: |
| 139 | continue |
| 140 | |
| 141 | method = match.group(1) |
| 142 | |
| 143 | if method in ALLOWED_METHODS: |
| 144 | continue |
| 145 | |
| 146 | if method not in FORBIDDEN_METHODS: |
| 147 | # Some other Serial.<method>(...) — leave alone for now. |
| 148 | continue |
| 149 | |
| 150 | if OPT_OUT_MARKER in comment_part: |
| 151 | continue |
| 152 | |
| 153 | replacement = SUGGESTED_REPLACEMENT.get(method, "an fl:: variant") |
| 154 | violations.append( |
no outgoing calls