PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
audit_function_docs.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""!
3@file audit_function_docs.py
4@brief Audits C and Python function documentation coverage across the repository.
5
6This script enforces the repository's function-level documentation contract for:
7
8- public C declarations in `include/`,
9- C definitions in `src/` and `tests/c/`,
10- Python functions in `picurv_cli/`, `generators/`, and `tests/`.
11
12It is intentionally lightweight. The C side uses signature scanning instead of a
13full parser, while the Python side uses `ast`. It checks both coverage and a
14minimum usefulness contract: a comment must say what the function does, rather
15than merely labelling it as a helper or implementation.
16"""
17
18from __future__ import annotations
19
20import ast
21import re
22import sys
23from dataclasses import dataclass
24from pathlib import Path
25
26
27REPO_ROOT = Path(__file__).resolve().parents[2]
28
29C_HEADER_DIRS = (REPO_ROOT / "include",)
30C_SOURCE_DIRS = (REPO_ROOT / "src", REPO_ROOT / "tests" / "c")
31PYTHON_DIRS = (
32 REPO_ROOT / "picurv_cli",
33 REPO_ROOT / "generators",
34 REPO_ROOT / "tests",
35)
36PYTHON_EXTRA_FILES = (
37 REPO_ROOT / "picurv_cli" / "picurv",
38 REPO_ROOT / "generators" / "grid.gen",
39 REPO_ROOT / "generators" / "profile.gen",
40 REPO_ROOT / "generators" / "ic.gen",
41 REPO_ROOT / "generators" / "plot.gen",
42)
43
44C_DECL_START_RE = re.compile(
45 r"^\s*(?!typedef\b)(?!if\b)(?!for\b)(?!while\b)(?!switch\b)(?!return\b)(?!else\b)"
46 r"(?:extern\s+)?(?:static\s+)?(?:inline\s+)?(?:const\s+)?(?:unsigned\s+|signed\s+)?"
47 r"(?:[A-Za-z_][A-Za-z0-9_]*\s+)+(?:\*\s*)*"
48 r"([A-Za-z_][A-Za-z0-9_]*)\s*\‍("
49)
50C_PARAM_RE = re.compile(r"@param(?:\[[^\]]+\])?\s+([A-Za-z_][A-Za-z0-9_]*)")
51GENERIC_DESCRIPTION_RE = re.compile(
52 r"(?:a |an |the )?(?:public interface|helper function|implementation of|internal helper|"
53 r"routine|function|test helper|utility function|helper routine)\.?$",
54 re.IGNORECASE,
55)
56STUB_IMPLEMENTATION_RE = re.compile(
57 r"(?:internal )?helper implementation\s*:", re.IGNORECASE
58)
59GENERIC_PUBLIC_PARAM_RE = re.compile(
60 r"@param(?:\[[^\]]+\])?\s+[A-Za-z_][A-Za-z0-9_]*\s+"
61 r"(?:parameter|argument)\b.*\bpassed to\b|"
62 r"@param(?:\[[^\]]+\])?\s+[A-Za-z_][A-Za-z0-9_]*\s+(?:output:|the)\s*$",
63 re.IGNORECASE | re.MULTILINE,
64)
65
66
67def _has_specific_description(comment: str) -> bool:
68 """!
69 @brief Report whether a function comment contains a non-stub description.
70 @param[in] comment Attached C comment or Python docstring to examine.
71 @return `True` when the description is not a known placeholder or label.
72
73 The audit deliberately uses conservative, transparent heuristics instead of
74 attempting to judge prose. It rejects descriptions that only classify a
75 symbol (for example, "helper function") and comments with no prose beyond
76 Doxygen tags. Reviewers remain responsible for domain correctness.
77 """
78
79 brief = re.search(r"@brief\s+([^\n*]+)", comment, re.IGNORECASE)
80 prose = brief.group(1) if brief else comment
81 prose = re.sub(r"@(?:param|return|file|details|note|warning)\b[^\n]*", "", prose)
82 prose = re.sub(r"[/!*`#]", " ", prose)
83 words = re.findall(r"[A-Za-z][A-Za-z0-9_-]*", prose)
84 if len(words) < 3:
85 return False
86 normalized = prose.strip()
87 return (
88 GENERIC_DESCRIPTION_RE.fullmatch(normalized) is None
89 and STUB_IMPLEMENTATION_RE.match(normalized) is None
90 )
91
92
93@dataclass(frozen=True)
95 """!
96 @brief Represents one audit failure.
97 @param[in] path Repository-relative path containing the failure.
98 @param[in] line 1-based source line associated with the failure.
99 @param[in] symbol Function symbol being audited.
100 @param[in] message Human-readable failure description.
101 """
102
103 path: str
104 line: int
105 symbol: str
106 message: str
107
108
109def _iter_c_files(directories: tuple[Path, ...]) -> list[Path]:
110 """!
111 @brief Returns all C or header files below the configured directories.
112 @param[in] directories Root directories to scan.
113 @return Sorted list of matching file paths.
114 """
115
116 files: list[Path] = []
117 for directory in directories:
118 if not directory.exists():
119 continue
120 files.extend(sorted(path for path in directory.rglob("*") if path.suffix in {".c", ".h"}))
121 return sorted(files)
122
123
124def _iter_python_files() -> list[Path]:
125 """!
126 @brief Returns all Python source files covered by the audit.
127 @return Sorted list of Python-backed source files.
128 """
129
130 files: set[Path] = set()
131 for directory in PYTHON_DIRS:
132 if not directory.exists():
133 continue
134 files.update(path for path in directory.rglob("*.py"))
135
136 for path in PYTHON_EXTRA_FILES:
137 if path.exists():
138 files.add(path)
139
140 return sorted(files)
141
142
143def _read_lines(path: Path) -> list[str]:
144 """!
145 @brief Reads a text file into a list of lines.
146 @param[in] path Path to read.
147 @return File contents split into lines without trailing newline markers.
148 """
149
150 return path.read_text(encoding="utf-8", errors="ignore").splitlines()
151
152
153def _relative_path(path: Path) -> str:
154 """!
155 @brief Returns a repository-relative path string.
156 @param[in] path Absolute or repository-local path.
157 @return POSIX-style repository-relative path.
158 """
159
160 return path.relative_to(REPO_ROOT).as_posix()
161
162
163def _find_attached_comment_block(lines: list[str], start_line: int,
164 require_doxygen: bool) -> tuple[int, int] | None:
165 """!
166 @brief Finds the documentation block immediately attached to a declaration or definition.
167 @param[in] lines File content lines.
168 @param[in] start_line 0-based line index where the symbol begins.
169 @param[in] require_doxygen Require a Doxygen `/**` block instead of allowing a
170 regular `/*` implementation comment.
171 @return `(start, end)` line indices for the attached block, or `None`.
172 """
173
174 probe = start_line - 1
175 while probe >= 0 and lines[probe].strip() == "":
176 probe -= 1
177
178 if probe < 0 or "*/" not in lines[probe]:
179 if probe >= 0 and not require_doxygen and lines[probe].lstrip().startswith("//"):
180 end = probe
181 while probe >= 0 and lines[probe].lstrip().startswith("//"):
182 probe -= 1
183 return probe + 1, end
184 return None
185
186 end = probe
187 marker = "/**" if require_doxygen else "/*"
188 while probe >= 0 and marker not in lines[probe]:
189 probe -= 1
190
191 if probe < 0:
192 return None
193
194 return probe, end
195
196
197def _split_c_parameters(signature: str) -> list[str]:
198 """!
199 @brief Splits a C signature parameter list into parameter names.
200 @param[in] signature Full function signature text.
201 @return Ordered list of parameter names excluding `void` and variadics.
202 """
203
204 start = signature.find("(")
205 end = signature.rfind(")")
206 if start < 0 or end < 0 or end <= start:
207 return []
208
209 raw = signature[start + 1:end]
210 params: list[str] = []
211 depth = 0
212 current: list[str] = []
213 for char in raw:
214 if char == "," and depth == 0:
215 params.append("".join(current).strip())
216 current = []
217 continue
218 current.append(char)
219 if char in "([{":
220 depth += 1
221 elif char in ")]}":
222 depth -= 1
223 if current:
224 params.append("".join(current).strip())
225
226 names: list[str] = []
227 for param in params:
228 if not param or param == "void" or param == "...":
229 continue
230
231 clean = re.sub(r"\b(const|volatile|restrict|extern|static|register|inline)\b", "", param)
232 clean = clean.strip()
233 match = re.search(r"([A-Za-z_][A-Za-z0-9_]*)\s*(?:\[[^\]]*\]\s*)*$", clean)
234 if match:
235 names.append(match.group(1))
236
237 return names
238
239
240def _c_return_type(signature: str, symbol: str) -> str:
241 """!
242 @brief Extracts the declared C return type prefix for one signature.
243 @param[in] signature Full function signature text.
244 @param[in] symbol Function name contained in the signature.
245 @return Normalized return-type prefix.
246 """
247
248 prefix = signature.split(symbol, 1)[0]
249 return " ".join(prefix.split())
250
251
252def _return_tag_required(return_type: str) -> bool:
253 """!
254 @brief Reports whether a Doxygen `@return` tag is required for a C symbol.
255 @param[in] return_type Normalized return-type prefix.
256 @return `True` when the symbol does not return `void`.
257 """
258
259 stripped = return_type.replace("extern ", "").replace("static ", "").replace("inline ", "").strip()
260 return not stripped.startswith("void")
261
262
263def _collect_c_signatures(path: Path, require_terminator: str) -> list[tuple[int, str, str]]:
264 """!
265 @brief Collects C signatures from a header or source file.
266 @param[in] path File to scan.
267 @param[in] require_terminator Expected signature terminator, either `;` or `{`.
268 @return List of `(start_line, symbol, signature_text)` tuples.
269 """
270
271 lines = _read_lines(path)
272 signatures: list[tuple[int, str, str]] = []
273 line_index = 0
274 in_block_comment = False
275
276 while line_index < len(lines):
277 stripped = lines[line_index].lstrip()
278 if in_block_comment:
279 if "*/" in lines[line_index]:
280 in_block_comment = False
281 line_index += 1
282 continue
283
284 if "/*" in lines[line_index]:
285 if "*/" not in lines[line_index]:
286 in_block_comment = True
287 line_index += 1
288 continue
289
290 if stripped.startswith(("#", "/*", "*", "//")) or "(" not in lines[line_index]:
291 line_index += 1
292 continue
293
294 match = C_DECL_START_RE.match(lines[line_index])
295 if not match:
296 line_index += 1
297 continue
298
299 symbol = match.group(1)
300 start_line = line_index
301 signature = lines[line_index].rstrip()
302 while line_index + 1 < len(lines) and require_terminator not in signature and ";" not in signature:
303 line_index += 1
304 signature += " " + lines[line_index].strip()
305
306 if require_terminator == ";" and ";" in signature:
307 signatures.append((start_line, symbol, signature))
308 elif require_terminator == "{" and "{" in signature and ";" not in signature.split("{", 1)[0]:
309 signatures.append((start_line, symbol, signature))
310
311 line_index += 1
312
313 return signatures
314
315
316def _audit_c_header(path: Path) -> list[AuditFinding]:
317 """!
318 @brief Audits public C declarations in one header file.
319 @param[in] path Header file to scan.
320 @return Findings emitted for the header.
321 """
322
323 findings: list[AuditFinding] = []
324 lines = _read_lines(path)
325 for start_line, symbol, signature in _collect_c_signatures(path, ";"):
326 block_range = _find_attached_comment_block(lines, start_line, require_doxygen=True)
327 if block_range is None:
328 findings.append(AuditFinding(_relative_path(path), start_line + 1, symbol, "missing attached Doxygen block"))
329 continue
330
331 block = "\n".join(lines[block_range[0]:block_range[1] + 1])
332 if "@brief" not in block:
333 findings.append(AuditFinding(_relative_path(path), start_line + 1, symbol, "missing @brief tag"))
334 elif not _has_specific_description(block):
335 findings.append(
337 _relative_path(path), start_line + 1, symbol,
338 "stub @brief; describe the function's result, state change, or numerical role",
339 )
340 )
341 if GENERIC_PUBLIC_PARAM_RE.search(block):
342 findings.append(
344 _relative_path(path), start_line + 1, symbol,
345 "generic @param; describe the input, output, ownership, or numerical meaning",
346 )
347 )
348
349 declared_params = _split_c_parameters(signature)
350 documented_params = set(C_PARAM_RE.findall(block))
351 if set(declared_params) != documented_params:
352 findings.append(
354 _relative_path(path),
355 start_line + 1,
356 symbol,
357 f"documented @param names {sorted(documented_params)} do not match declaration {declared_params}",
358 )
359 )
360
361 if _return_tag_required(_c_return_type(signature, symbol)) and "@return" not in block:
362 findings.append(AuditFinding(_relative_path(path), start_line + 1, symbol, "missing @return tag"))
363
364 return findings
365
366
367def _audit_c_source(path: Path, public_symbols: set[str]) -> list[AuditFinding]:
368 """!
369 @brief Audits function definitions in one C source file.
370 @param[in] path Source file to scan.
371 @param[in] public_symbols Symbols with canonical public-header documentation.
372 @return Findings emitted for the source file.
373 """
374
375 findings: list[AuditFinding] = []
376 lines = _read_lines(path)
377 for start_line, symbol, _signature in _collect_c_signatures(path, "{"):
378 # Public declarations own the rendered API contract. Allow regular
379 # implementation comments here so Doxygen does not merge a second,
380 # partial parameter list from the definition and emit false warnings.
381 block_range = _find_attached_comment_block(lines, start_line, require_doxygen=False)
382 if block_range is None:
383 findings.append(AuditFinding(_relative_path(path), start_line + 1, symbol, "missing attached Doxygen block"))
384 continue
385
386 block = "\n".join(lines[block_range[0]:block_range[1] + 1])
387 # A public declaration's Doxygen block is the canonical user-facing
388 # description. Definitions of private helpers have no such contract,
389 # so their attached implementation comment must stand on its own.
390 if symbol not in public_symbols and not _has_specific_description(block):
391 findings.append(
393 _relative_path(path), start_line + 1, symbol,
394 "stub implementation comment; explain the function's computation or state change",
395 )
396 )
397
398 return findings
399
400
401def _python_parameter_names(node: ast.FunctionDef | ast.AsyncFunctionDef) -> list[str]:
402 """!
403 @brief Returns the meaningful Python parameter names for one function node.
404 @param[in] node Function AST node.
405 @return Ordered list of parameters expected in `@param` tags.
406 """
407
408 names = [arg.arg for arg in node.args.posonlyargs + node.args.args + node.args.kwonlyargs]
409 names = [name for name in names if name not in {"self", "cls"}]
410 if node.args.vararg is not None:
411 names.append(node.args.vararg.arg)
412 if node.args.kwarg is not None:
413 names.append(node.args.kwarg.arg)
414 return names
415
416
417def _python_requires_return(node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
418 """!
419 @brief Reports whether one Python function should document a return value.
420 @param[in] node Function AST node.
421 @return `True` when the function returns a non-`None` value.
422 """
423
424 for child in ast.walk(node):
425 if isinstance(child, ast.Return) and child.value is not None:
426 if isinstance(child.value, ast.Constant) and child.value.value is None:
427 continue
428 return True
429 return False
430
431
432def _audit_python_file(path: Path) -> list[AuditFinding]:
433 """!
434 @brief Audits Python function docstrings in one file.
435 @param[in] path Python source file to scan.
436 @return Findings emitted for the Python file.
437 """
438
439 findings: list[AuditFinding] = []
440 source = path.read_text(encoding="utf-8")
441 tree = ast.parse(source, filename=str(path))
442
443 for node in ast.walk(tree):
444 if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
445 continue
446
447 docstring = ast.get_docstring(node)
448 if docstring is None:
449 findings.append(AuditFinding(_relative_path(path), node.lineno, node.name, "missing Python docstring"))
450 continue
451
452 if "@brief" not in docstring:
453 findings.append(AuditFinding(_relative_path(path), node.lineno, node.name, "missing @brief tag"))
454 elif not _has_specific_description(docstring):
455 findings.append(
457 _relative_path(path), node.lineno, node.name,
458 "stub @brief; explain the function's result, state change, or validation role",
459 )
460 )
461
462 declared_params = _python_parameter_names(node)
463 documented_params = set(re.findall(r"@param(?:\[[^\]]+\])?\s+([A-Za-z_][A-Za-z0-9_]*)", docstring))
464 if set(declared_params) != documented_params:
465 findings.append(
467 _relative_path(path),
468 node.lineno,
469 node.name,
470 f"documented @param names {sorted(documented_params)} do not match declaration {declared_params}",
471 )
472 )
473
474 if _python_requires_return(node) and "@return" not in docstring:
475 findings.append(AuditFinding(_relative_path(path), node.lineno, node.name, "missing @return tag"))
476
477 return findings
478
479
480def _collect_findings() -> list[AuditFinding]:
481 """!
482 @brief Runs the full repository documentation audit.
483 @return Sorted list of all findings emitted by the audit.
484 """
485
486 findings: list[AuditFinding] = []
487 header_files = _iter_c_files(C_HEADER_DIRS)
488 public_symbols = {
489 symbol
490 for path in header_files
491 for _line, symbol, _signature in _collect_c_signatures(path, ";")
492 }
493 for path in header_files:
494 findings.extend(_audit_c_header(path))
495 for path in _iter_c_files(C_SOURCE_DIRS):
496 if path.suffix == ".c":
497 findings.extend(_audit_c_source(path, public_symbols))
498 for path in _iter_python_files():
499 findings.extend(_audit_python_file(path))
500
501 return sorted(findings, key=lambda item: (item.path, item.line, item.symbol, item.message))
502
503
504def _print_findings(findings: list[AuditFinding]) -> None:
505 """!
506 @brief Prints findings in a grep-friendly format.
507 @param[in] findings Findings to render.
508 """
509
510 for finding in findings:
511 print(f"{finding.path}:{finding.line}: {finding.symbol}: {finding.message}")
512
513
514def main() -> int:
515 """!
516 @brief Runs the repository function documentation audit from the command line.
517 @return Process exit status.
518 """
519
520 findings = _collect_findings()
521 if findings:
522 _print_findings(findings)
523 print(f"\nFound {len(findings)} documentation issue(s).", file=sys.stderr)
524 return 1
525
526 print("Function documentation audit passed.")
527 return 0
528
529
530if __name__ == "__main__":
531 raise SystemExit(main())
Represents one audit failure.
list[str] _python_parameter_names(ast.FunctionDef|ast.AsyncFunctionDef node)
Returns the meaningful Python parameter names for one function node.
list[Path] _iter_c_files(tuple[Path,...] directories)
Returns all C or header files below the configured directories.
list[str] _read_lines(Path path)
Reads a text file into a list of lines.
tuple[int, int]|None _find_attached_comment_block(list[str] lines, int start_line, bool require_doxygen)
Finds the documentation block immediately attached to a declaration or definition.
list[AuditFinding] _audit_python_file(Path path)
Audits Python function docstrings in one file.
str _c_return_type(str signature, str symbol)
Extracts the declared C return type prefix for one signature.
str _relative_path(Path path)
Returns a repository-relative path string.
list[Path] _iter_python_files()
Returns all Python source files covered by the audit.
bool _return_tag_required(str return_type)
Reports whether a Doxygen @return tag is required for a C symbol.
list[AuditFinding] _audit_c_source(Path path, set[str] public_symbols)
Audits function definitions in one C source file.
list[str] _split_c_parameters(str signature)
Splits a C signature parameter list into parameter names.
bool _python_requires_return(ast.FunctionDef|ast.AsyncFunctionDef node)
Reports whether one Python function should document a return value.
None _print_findings(list[AuditFinding] findings)
Prints findings in a grep-friendly format.
list[tuple[int, str, str]] _collect_c_signatures(Path path, str require_terminator)
Collects C signatures from a header or source file.
list[AuditFinding] _collect_findings()
Runs the full repository documentation audit.
list[AuditFinding] _audit_c_header(Path path)
Audits public C declarations in one header file.
bool _has_specific_description(str comment)
Report whether a function comment contains a non-stub description.
int main()
Runs the repository function documentation audit from the command line.