3@file audit_function_docs.py
4@brief Audits C and Python function documentation coverage across the repository.
6This script enforces the repository's function-level documentation contract for:
8- public C declarations in `include/`,
9- C definitions in `src/` and `tests/c/`,
10- Python functions in `picurv_cli/`, `generators/`, and `tests/`.
12It is intentionally lightweight. The C side uses signature scanning instead of a
13full parser, while the Python side uses `ast`.
16from __future__
import annotations
21from dataclasses
import dataclass
22from pathlib
import Path
25REPO_ROOT = Path(__file__).resolve().parents[2]
27C_HEADER_DIRS = (REPO_ROOT /
"include",)
28C_SOURCE_DIRS = (REPO_ROOT /
"src", REPO_ROOT /
"tests" /
"c")
29PYTHON_DIRS = (REPO_ROOT /
"picurv_cli", REPO_ROOT /
"tests")
31 REPO_ROOT /
"picurv_cli" /
"picurv",
32 REPO_ROOT /
"generators" /
"grid.gen",
33 REPO_ROOT /
"generators" /
"profile.gen",
34 REPO_ROOT /
"generators" /
"ic.gen",
35 REPO_ROOT /
"generators" /
"plot.gen",
38C_DECL_START_RE = re.compile(
39 r"^\s*(?!typedef\b)(?!if\b)(?!for\b)(?!while\b)(?!switch\b)(?!return\b)(?!else\b)"
40 r"(?:extern\s+)?(?:static\s+)?(?:inline\s+)?(?:const\s+)?(?:unsigned\s+|signed\s+)?"
41 r"(?:[A-Za-z_][A-Za-z0-9_]*\s+)+(?:\*\s*)*"
42 r"([A-Za-z_][A-Za-z0-9_]*)\s*\("
44C_PARAM_RE = re.compile(
r"@param(?:\[[^\]]+\])?\s+([A-Za-z_][A-Za-z0-9_]*)")
47@dataclass(frozen=True)
50 @brief Represents one audit failure.
51 @param[in] path Repository-relative path containing the failure.
52 @param[in] line 1-based source line associated with the failure.
53 @param[in] symbol Function symbol being audited.
54 @param[in] message Human-readable failure description.
65 @brief Returns all C or header files below the configured directories.
66 @param[in] directories Root directories to scan.
67 @return Sorted list of matching file paths.
70 files: list[Path] = []
71 for directory
in directories:
72 if not directory.exists():
74 files.extend(sorted(path
for path
in directory.rglob(
"*")
if path.suffix
in {
".c",
".h"}))
80 @brief Returns all Python source files covered by the audit.
81 @return Sorted list of Python-backed source files.
84 files: set[Path] = set()
85 for directory
in PYTHON_DIRS:
86 if not directory.exists():
88 files.update(path
for path
in directory.rglob(
"*.py"))
90 for path
in PYTHON_EXTRA_FILES:
99 @brief Reads a text file into a list of lines.
100 @param[in] path Path to read.
101 @return File contents split into lines without trailing newline markers.
104 return path.read_text(encoding=
"utf-8", errors=
"ignore").splitlines()
109 @brief Returns a repository-relative path string.
110 @param[in] path Absolute or repository-local path.
111 @return POSIX-style repository-relative path.
114 return path.relative_to(REPO_ROOT).as_posix()
119 @brief Finds the Doxygen block immediately attached to a declaration or definition.
120 @param[in] lines File content lines.
121 @param[in] start_line 0-based line index where the symbol begins.
122 @return `(start, end)` line indices for the attached block, or `None`.
125 probe = start_line - 1
126 while probe >= 0
and lines[probe].strip() ==
"":
129 if probe < 0
or "*/" not in lines[probe]:
133 while probe >= 0
and "/**" not in lines[probe]:
144 @brief Splits a C signature parameter list into parameter names.
145 @param[in] signature Full function signature text.
146 @return Ordered list of parameter names excluding `void` and variadics.
149 start = signature.find(
"(")
150 end = signature.rfind(
")")
151 if start < 0
or end < 0
or end <= start:
154 raw = signature[start + 1:end]
155 params: list[str] = []
157 current: list[str] = []
159 if char ==
"," and depth == 0:
160 params.append(
"".join(current).strip())
169 params.append(
"".join(current).strip())
171 names: list[str] = []
173 if not param
or param ==
"void" or param ==
"...":
176 clean = re.sub(
r"\b(const|volatile|restrict|extern|static|register|inline)\b",
"", param)
177 clean = clean.strip()
178 match = re.search(
r"([A-Za-z_][A-Za-z0-9_]*)\s*(?:\[[^\]]*\]\s*)*$", clean)
180 names.append(match.group(1))
187 @brief Extracts the declared C return type prefix for one signature.
188 @param[in] signature Full function signature text.
189 @param[in] symbol Function name contained in the signature.
190 @return Normalized return-type prefix.
193 prefix = signature.split(symbol, 1)[0]
194 return " ".join(prefix.split())
199 @brief Reports whether a Doxygen `@return` tag is required for a C symbol.
200 @param[in] return_type Normalized return-type prefix.
201 @return `True` when the symbol does not return `void`.
204 stripped = return_type.replace(
"extern ",
"").replace(
"static ",
"").replace(
"inline ",
"").strip()
205 return not stripped.startswith(
"void")
210 @brief Collects C signatures from a header or source file.
211 @param[in] path File to scan.
212 @param[in] require_terminator Expected signature terminator, either `;` or `{`.
213 @return List of `(start_line, symbol, signature_text)` tuples.
217 signatures: list[tuple[int, str, str]] = []
219 in_block_comment =
False
221 while line_index < len(lines):
222 stripped = lines[line_index].lstrip()
224 if "*/" in lines[line_index]:
225 in_block_comment =
False
229 if "/*" in lines[line_index]:
230 if "*/" not in lines[line_index]:
231 in_block_comment =
True
235 if stripped.startswith((
"#",
"/*",
"*",
"//"))
or "(" not in lines[line_index]:
239 match = C_DECL_START_RE.match(lines[line_index])
244 symbol = match.group(1)
245 start_line = line_index
246 signature = lines[line_index].rstrip()
247 while line_index + 1 < len(lines)
and require_terminator
not in signature
and ";" not in signature:
249 signature +=
" " + lines[line_index].strip()
251 if require_terminator ==
";" and ";" in signature:
252 signatures.append((start_line, symbol, signature))
253 elif require_terminator ==
"{" and "{" in signature
and ";" not in signature.split(
"{", 1)[0]:
254 signatures.append((start_line, symbol, signature))
263 @brief Audits public C declarations in one header file.
264 @param[in] path Header file to scan.
265 @return Findings emitted for the header.
268 findings: list[AuditFinding] = []
272 if block_range
is None:
276 block =
"\n".join(lines[block_range[0]:block_range[1] + 1])
277 if "@brief" not in block:
281 documented_params = set(C_PARAM_RE.findall(block))
282 if set(declared_params) != documented_params:
288 f
"documented @param names {sorted(documented_params)} do not match declaration {declared_params}",
300 @brief Audits function definitions in one C source file.
301 @param[in] path Source file to scan.
302 @return Findings emitted for the source file.
305 findings: list[AuditFinding] = []
309 if block_range
is None:
313 block =
"\n".join(lines[block_range[0]:block_range[1] + 1])
314 if "@brief" not in block:
322 @brief Returns the meaningful Python parameter names for one function node.
323 @param[in] node Function AST node.
324 @return Ordered list of parameters expected in `@param` tags.
327 names = [arg.arg
for arg
in node.args.posonlyargs + node.args.args + node.args.kwonlyargs]
328 names = [name
for name
in names
if name
not in {
"self",
"cls"}]
329 if node.args.vararg
is not None:
330 names.append(node.args.vararg.arg)
331 if node.args.kwarg
is not None:
332 names.append(node.args.kwarg.arg)
338 @brief Reports whether one Python function should document a return value.
339 @param[in] node Function AST node.
340 @return `True` when the function returns a non-`None` value.
343 for child
in ast.walk(node):
344 if isinstance(child, ast.Return)
and child.value
is not None:
345 if isinstance(child.value, ast.Constant)
and child.value.value
is None:
353 @brief Audits Python function docstrings in one file.
354 @param[in] path Python source file to scan.
355 @return Findings emitted for the Python file.
358 findings: list[AuditFinding] = []
359 source = path.read_text(encoding=
"utf-8")
360 tree = ast.parse(source, filename=str(path))
362 for node
in ast.walk(tree):
363 if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
366 docstring = ast.get_docstring(node)
367 if docstring
is None:
371 if "@brief" not in docstring:
375 documented_params = set(re.findall(
r"@param(?:\[[^\]]+\])?\s+([A-Za-z_][A-Za-z0-9_]*)", docstring))
376 if set(declared_params) != documented_params:
382 f
"documented @param names {sorted(documented_params)} do not match declaration {declared_params}",
394 @brief Runs the full repository documentation audit.
395 @return Sorted list of all findings emitted by the audit.
398 findings: list[AuditFinding] = []
402 if path.suffix ==
".c":
407 return sorted(findings, key=
lambda item: (item.path, item.line, item.symbol, item.message))
412 @brief Prints findings in a grep-friendly format.
413 @param[in] findings Findings to render.
416 for finding
in findings:
417 print(f
"{finding.path}:{finding.line}: {finding.symbol}: {finding.message}")
422 @brief Runs the repository function documentation audit from the command line.
423 @return Process exit status.
429 print(f
"\nFound {len(findings)} documentation issue(s).", file=sys.stderr)
432 print(
"Function documentation audit passed.")
436if __name__ ==
"__main__":
437 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.
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[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[AuditFinding] _audit_c_source(Path path)
Audits function definitions in one C source file.
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.
tuple[int, int]|None _find_attached_doxygen_block(list[str] lines, int start_line)
Finds the Doxygen block immediately attached to a declaration or definition.
list[AuditFinding] _audit_c_header(Path path)
Audits public C declarations in one header file.
int main()
Runs the repository function documentation audit from the command line.