checks.py¶
clew/guard/checks.py
Validation checks for doxygen comments.
_body_text
str clew.guard.checks._body_text(Function func, list[str] lines)
Extract a function's definition-through-body source text.
Source · 4 lines
def _body_text(func: Function, lines: list[str]) -> str:
return "\n".join(lines[func.def_line : func.body_end + 1])
Activity · 1 steps
Flows
_brief_hint
str clew.guard.checks._brief_hint(str file_path)
How to supply a missing brief, in the file's own convention.
Source · 6 lines
def _brief_hint(file_path: str) -> str:
if Path(file_path).suffix.lower() in (".rs", ".py", *_JS_SUFFIXES):
return "start the doc comment with a summary sentence, or add '@brief <description>'"
return "add '@brief <description>' to the doxygen comment"
Activity · 3 steps
Flows
_bus_tags
set[str] clew.guard.checks._bus_tags(dict[str, Any] config)
The bus tags a configuration enforces; empty when no validate.bus section exists.
Source · 6 lines
def _bus_tags(config: dict[str, Any]) -> set[str]:
if not get_validate(config).get("bus"):
return set()
return _event_tags(config)
Activity · 3 steps
Flows
_bus_vocabulary
list[Violation] clew.guard.checks._bus_vocabulary(Function func, str file_path, dict[str, list[str]] present, set[str] vocabulary)
Violations for bus tags naming a bus outside the vocabulary.
Source · 21 lines
def _bus_vocabulary(
func: Function, file_path: str, present: dict[str, list[str]], vocabulary: set[str]
) -> list[Violation]:
if not vocabulary:
return []
line = func.doxygen.start_line + 1 if func.doxygen else func.def_line + 1
return [
Violation(
file=file_path,
line=line,
check="bus",
qualified=func.qualified,
message=(
f"@{tag} {value!r} in {func.name}() names bus {value.split()[0] if value.split() else ''!r}, "
f"not in validate.bus.vocabulary ({', '.join(sorted(vocabulary))})"
),
)
for tag, values in present.items()
for value in values
if not value.split() or value.split()[0] not in vocabulary
]1 more lines, not shown
Activity · 4 steps
Flows
_check_file_block_tags
list[Violation] clew.guard.checks._check_file_block_tags(str file_path, list[str] lines, int block_start)
Check required tags in a file-level doxygen block.
Called by check_file_presence
Calls _extract_file_block_text, apply_autobrief, parse_doxygen_tags
Source · 35 lines
def _check_file_block_tags(file_path: str, lines: list[str], block_start: int) -> list[Violation]:
block_text = _extract_file_block_text(lines, block_start)
from .parser import parse_doxygen_tags
tags = parse_doxygen_tags(block_text)
violations: list[Violation] = []
required = {"file": "@file", "brief": "@brief", "version": "@version"}
if Path(file_path).suffix.lower() in _JS_SUFFIXES:
## ANY OF JSDOC'S FOUR, not the C spelling. `@file` stays in the mapping so a file
## naming none of them still reports a missing tag — widening which tags count must
## not make the check vacuous.
if any(tag in tags for tag in _JSDOC_FILE_TAGS):
del required["file"]
else:
required["file"] = "@fileoverview (or @file / @overview / @module)"
if lines[block_start].strip().startswith(_RUST_FILE_DOC_STARTS):
# A Rust inner doc comment documents its module by construction, so @file would
# restate the syntax; and its summary paragraph is the brief, as for items.
from .parser import apply_autobrief
apply_autobrief(block_text, tags)
del required["file"]
for tag_key, tag_name in required.items():
if tag_key not in tags:
violations.append(
Violation(
file=file_path,
line=block_start + 1,
check="presence",
message=f"File-level doxygen missing {tag_name} tag in '{file_path}'",
)
)
return violations
Activity · 18 steps
Requirements
Flows
_check_one_version
Violation | None clew.guard.checks._check_one_version(Function func, Function|None head_func, VersionCheckContext ctx)
Check one function's @version against its HEAD counterpart.
Source · 47 lines
def _check_one_version(
func: Function,
head_func: Function | None,
ctx: VersionCheckContext,
) -> Violation | None:
# Written as a single direct condition (not hoisted to a variable) so type checkers
# can narrow func.doxygen / head_func.doxygen to non-None for the rest of the function.
if (
func.doxygen is None
or ctx.tag_key not in func.doxygen.tags
or head_func is None
or head_func.doxygen is None
or _body_text(func, ctx.lines) == _body_text(head_func, ctx.head_lines)
):
return None
version_value = func.doxygen.tags.get(ctx.tag_key, [""])[0]
head_version_value = head_func.doxygen.tags.get(ctx.tag_key, [""])[0]
if version_value == head_version_value:
return Violation(
file=ctx.file_path,
line=func.def_line + 1,
check="version",
qualified=func.qualified,
message=f"Function '{func.name}' body changed but {ctx.version_tag} was not updated",
)
# Version was bumped — validate the optional marker (only [reviewed] is valid).
marker_match = re.search(r"\[(\w+)\]$", version_value.strip())
invalid_marker = bool(marker_match) and marker_match.group(1) != "reviewed"
return (
Violation(
file=ctx.file_path,
line=func.def_line + 1,
check="version",
qualified=func.qualified,
message=(
f"Function '{func.name}' has unrecognized version marker "
f"'[{marker_match.group(1)}]' (use [reviewed])"
),
)
if invalid_marker and marker_match
else None
)
Activity · 9 steps
Flows
_crosses_bus
bool clew.guard.checks._crosses_bus(Function func, list[str] lines, tuple[str,...] handlers, re.Pattern[str]|None call)
Whether a function is in the bus rule's scope.
Source · 13 lines
def _crosses_bus(
func: Function, lines: list[str], handlers: tuple[str, ...], call: re.Pattern[str] | None
) -> bool:
from fnmatch import fnmatchcase
if any(fnmatchcase(func.name, g) for g in handlers):
return True
if call is None:
return False
body = "\n".join(lines[func.def_line + 1 : func.body_end + 1])
return call.search(body) is not None
Activity · 7 steps
Flows
_docstring_block
str clew.guard.checks._docstring_block(list[str] lines, int start)
A module docstring's text, from its opening quotes to its closing ones.
Source · 18 lines
def _docstring_block(lines: list[str], start: int) -> str:
first = lines[start].strip()
quote = first[:3]
opened = first[3:]
if quote in opened:
return opened.split(quote, 1)[0]
body = [opened]
for line in lines[start + 1 : start + _DOCSTRING_MAX_LINES]:
if quote in line:
body.append(line.split(quote, 1)[0])
break
body.append(line)
return "\n".join(body)
# In Rust only an INNER doc comment documents the file (its module): `///` and `/**` at the
# top of a file document the first item, so reading them as the file block reports an
# item's doc as a file block missing @file.Activity · 12 steps
Flows
_edit_distance
int clew.guard.checks._edit_distance(str a, str b)
Compute Levenshtein edit distance between two strings.
Source · 13 lines
def _edit_distance(a: str, b: str) -> int:
if len(a) < len(b):
return _edit_distance(b, a)
prev = list(range(len(b) + 1))
for i, ca in enumerate(a):
curr = [i + 1] + [0] * len(b)
for j, cb in enumerate(b):
cost = 0 if ca == cb else 1
curr[j + 1] = min(curr[j] + 1, prev[j + 1] + 1, prev[j] + cost)
prev = curr
return prev[len(b)]
Activity · 10 steps
Flows
_event_tags
set[str] clew.guard.checks._event_tags(dict[str, Any] config)
The event vocabulary: the declaration's event_tags: , else the index's built-in one.
Source · 5 lines
def _event_tags(config: dict[str, Any]) -> set[str]:
declared = config.get("event_tags")
return {str(t).lower() for t in declared} if declared else set(DEFAULT_EVENT_TAG_NAMES)
Activity · 2 steps
Flows
_exemption_hint
str clew.guard.checks._exemption_hint()
Render the exemption tags for an error message, derived from the set.
Source · 4 lines
def _exemption_hint() -> str:
return ", ".join(f"@{t}" for t in sorted(EXEMPTION_TAGS))
Activity · 1 steps
Flows
_extract_file_block_text
str clew.guard.checks._extract_file_block_text(list[str] lines, int start)
Source · 11 lines
def _extract_file_block_text(lines: list[str], start: int) -> str:
if lines[start].strip().startswith(_DOCSTRING_QUOTES):
return _docstring_block(lines, start)
block_lines: list[str] = []
for i in range(start, min(start + 30, len(lines))):
block_lines.append(lines[i])
if "*/" in lines[i] or (i > start and not lines[i].strip().startswith(("*", "#", "//"))):
break
return "\n".join(block_lines)
Activity · 8 steps
Flows
_find_file_doxygen_start
int | None clew.guard.checks._find_file_doxygen_start(list[str] lines, tuple[str,...]|None doxygen_starts=None)
Find the line index of the file-level doxygen block start.
Source · 18 lines
def _find_file_doxygen_start(
lines: list[str], doxygen_starts: tuple[str, ...] | None = None
) -> int | None:
## `#!` and the `use strict` directives join the C preprocessor lines: all of them
## legally sit ABOVE a file's doc block, and stopping at one reports a documented file as
## undocumented (group A, 1.1.0 merge review).
skip_prefixes = ("#include", "#pragma", "#ifndef", "#define") + _JS_PROLOGUE_PREFIXES
doxygen_starts = doxygen_starts or ("/**", "///", "## @", '"""')
for i, line in enumerate(lines):
stripped = line.strip()
if not stripped or any(stripped.startswith(p) for p in skip_prefixes):
continue
if any(stripped.startswith(s) for s in doxygen_starts):
return i
return None
return None
Activity · 10 steps
Requirements
Flows
_first_code_line
int clew.guard.checks._first_code_line(list[str] lines)
Find the first non-blank, non-preprocessor line number.
Source · 7 lines
def _first_code_line(lines: list[str]) -> int:
for i, line in enumerate(lines):
if line.strip():
return i + 1
return 1
Activity · 4 steps
Flows
_has_active_requirements
bool clew.guard.checks._has_active_requirements(dict[str, Any] config)
Check if any requirements pass the version gate filter.
Called by check_req_coverage
Calls filter_requirements_by_version, load_requirements_full
Source · 8 lines
def _has_active_requirements(config: dict[str, Any]) -> bool:
from .impact import filter_requirements_by_version, load_requirements_full
full = load_requirements_full(config)
filtered = filter_requirements_by_version(full, config)
return bool(filtered)
Activity · 4 steps
Flows
_has_version_gate
bool clew.guard.checks._has_version_gate(dict[str, Any] config)
Check if version gate is configured.
Source · 7 lines
def _has_version_gate(config: dict[str, Any]) -> bool:
return bool(
get_validate(config).get("current_version")
and get_requirements(config).get("version_field")
)
Activity · 1 steps
Flows
_index_by_identity
dict[tuple[str | None, str, str], list[Function]] clew.guard.checks._index_by_identity(list[Function] functions)
Build a lookup of HEAD functions keyed by (enclosing_class, name, signature).
Source · 9 lines
def _index_by_identity(
functions: list[Function],
) -> dict[tuple[str | None, str, str], list[Function]]:
index: dict[tuple[str | None, str, str], list[Function]] = {}
for f in functions:
index.setdefault((f.enclosing_class, f.name, f.signature), []).append(f)
return index
Activity · 4 steps
Flows
_is_rust_unit_fn
bool clew.guard.checks._is_rust_unit_fn(Function func, list[str] lines)
Whether a Rust function returns unit, read from its signature text.
Source · 10 lines
def _is_rust_unit_fn(func: Function, lines: list[str]) -> bool:
signature: list[str] = []
for idx in range(func.def_line, min(func.def_line + 12, len(lines))):
signature.append(lines[idx])
if "{" in lines[idx] or lines[idx].rstrip().endswith(";"):
break
text = " ".join(signature).split("{", 1)[0]
return "->" not in text or bool(_RUST_UNIT_RETURN.search(text + "{"))
Activity · 7 steps
Requirements
Flows
_is_void_function
bool clew.guard.checks._is_void_function(Function func, list[str] lines)
Check if a function returns void based on its definition lines.
Source · 33 lines
def _is_void_function(func: Function, lines: list[str]) -> bool:
if func.returns_void is not None:
return func.returns_void
if func.def_line < len(lines) and _RUST_FN_RE.search(lines[func.def_line]):
return _is_rust_unit_fn(func, lines)
for offset in range(3):
idx = func.def_line + offset
if idx >= len(lines):
break
line = lines[idx]
name_pos = line.find(func.name)
if name_pos < 0 or (name_pos == 0 and offset == 0):
continue
prefix = " ".join([*lines[func.def_line : idx], line[:name_pos]])
is_c_void = bool(_VOID_PATTERNS.search(prefix))
is_python_none = bool(_PYTHON_NONE_RETURN.search(line))
is_python_untyped = line.strip().startswith("def ") and "->" not in line
return is_c_void or is_python_none or is_python_untyped
return False
# Tags that exempt a function from requiring @req. These are tool vocabulary, not
# doxygen commands.
#
# "internal" was previously in this set, overloading doxygen's \internal — which, with
# INTERNAL_DOCS off, suppresses everything after it in the block. Since this tool kept
# parsing tags after it, a block written to satisfy the gate silently lost its @return
# in generated documentation. Exemption now uses a tool-owned tag that doxygen has no
# meaning for; \internal remains recognised (see _KNOWN_TAGS) so a project using it for
# its real purpose is not flagged, it simply no longer grants an exemption.
#
# 2.0.0 (PG1, OWNER: "a hard cut of doxygen-guard priors — clew only"): the doxygen-guard-era
# `dg_internal` FOLDS INTO `utility`. Never back into `internal`, for the reason above.Activity · 18 steps
Requirements
Flows
_pair_by_name
dict[int, Function] clew.guard.checks._pair_by_name(list[Function] functions, list[Function] head_functions, dict[int, Function] paired)
Pair a function left unmatched by identity with its HEAD self, by name, if unambiguous.
Source · 18 lines
def _pair_by_name(
functions: list[Function], head_functions: list[Function], paired: dict[int, Function]
) -> dict[int, Function]:
taken = {id(h) for h in paired.values()}
head_by_name: dict[tuple[str | None, str], list[Function]] = {}
for h in head_functions:
head_by_name.setdefault((h.enclosing_class, h.name), []).append(h)
current_by_name: dict[tuple[str | None, str], list[Function]] = {}
for f in functions:
current_by_name.setdefault((f.enclosing_class, f.name), []).append(f)
added: dict[int, Function] = {}
for key, (func,) in ((k, v) for k, v in current_by_name.items() if len(v) == 1):
head = head_by_name.get(key, [])
if id(func) not in paired and len(head) == 1 and id(head[0]) not in taken:
added[id(func)] = head[0]
return added
Activity · 13 steps
Requirements
Flows
_pair_copies
dict[int, Function] clew.guard.checks._pair_copies(list[Function] current, list[Function] head, VersionCheckContext ctx)
Pair one identity's current copies with its HEAD copies.
Source · 22 lines
def _pair_copies(
current: list[Function], head: list[Function], ctx: VersionCheckContext
) -> dict[int, Function]:
if len(current) == len(head):
return {id(c): h for c, h in zip(current, head)}
pairs: dict[int, Function] = {}
free = list(head)
for func in current:
text = _body_text(func, ctx.lines)
same = next((h for h in free if _body_text(h, ctx.head_lines) == text), None)
if same is not None:
pairs[id(func)] = same
free.remove(same)
for func in (c for c in current if id(c) not in pairs):
if not free:
break
best = max(free, key=lambda h, f=func: _similarity(f, h, ctx))
pairs[id(func)] = best
free.remove(best)
return pairs
Activity · 17 steps
Flows
_require_return
bool clew.guard.checks._require_return(dict[str, Any] validate, str file_path)
Whether @return is required for this file: the language's own setting, else the global one.
Source · 11 lines
def _require_return(validate: dict[str, Any], file_path: str) -> bool:
ext = Path(file_path).suffix
for lang_config in validate.get("languages", {}).values():
if isinstance(lang_config, dict) and ext in lang_config.get("extensions", []):
if "require_return" in lang_config:
return bool(lang_config["require_return"])
break
return bool(validate.get("presence", {}).get("require_return", True))
# A Rust signature returns `()` when it has no `->`, or an explicit `-> ()`.Activity · 7 steps
Requirements
Flows
_suggest_file_skeleton
str clew.guard.checks._suggest_file_skeleton(str file_path)
Build a language-appropriate file-level doxygen skeleton suggestion.
Source · 16 lines
def _suggest_file_skeleton(file_path: str) -> str:
if Path(file_path).suffix.lower() in _JS_SUFFIXES:
return (
"'/** @fileoverview <desc> @brief <desc> @version 1.0 */' "
"(JSDoc; @file, @overview and @module are accepted too)"
)
if Path(file_path).suffix.lower() == ".rs":
return "'//! <summary sentence>' / '//! @version 1' (inner doc, before first item)"
if Path(file_path).suffix.lower() == ".py":
return (
"'## @file' / '## @brief <desc>' / '## @version 1.0' "
"(two-hash style, before first code)"
)
return "/** @file @brief <desc> @version 1.0 */ before first code"
Activity · 7 steps
Flows
_suggest_skeleton
str clew.guard.checks._suggest_skeleton(str file_path, *bool with_return=False)
Build a language-appropriate doxygen skeleton suggestion.
Source · 11 lines
def _suggest_skeleton(file_path: str, *, with_return: bool = False) -> str:
return_tag = " @return <description>" if with_return else ""
if Path(file_path).suffix.lower() == ".rs":
return f"'/// <summary sentence>' then '/// @version 1{return_tag}' (above the fn)"
if Path(file_path).suffix.lower() in _JS_SUFFIXES:
return f"'/** <summary sentence> @version 1{return_tag} */' (JSDoc, above the function)"
if Path(file_path).suffix.lower() == ".py":
return f"'## @brief <description> @version 1.0{return_tag}' (two-hash style, above the def)"
return f"'/** @brief <description> @version 1.0{return_tag} */' before function"
Activity · 8 steps
Flows
_suggest_tag
str | None clew.guard.checks._suggest_tag(str unknown, AbstractSet[str] known)
Find the closest known tag name using edit distance.
Source · 11 lines
def _suggest_tag(unknown: str, known: AbstractSet[str]) -> str | None:
best_tag = None
best_dist = 3
for tag in known:
dist = _edit_distance(unknown, tag)
if dist < best_dist:
best_dist = dist
best_tag = tag
return best_tag
Activity · 8 steps
Flows
_uncheckable
Violation clew.guard.checks._uncheckable(Function func, str file_path, str req_id)
A tag that cannot be checked because no catalogue is declared (GH #68).
Source · 14 lines
def _uncheckable(func: Function, file_path: str, req_id: str) -> Violation:
return Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="tag",
qualified=func.qualified,
message=(
f"@req {req_id} in {func.name}() cannot be checked: no requirements catalog is "
"declared; name one under impact.requirements (file or external), or set "
"validate.tags.req.cross_reference: false"
),
)
Activity · 1 steps
Requirements
Flows
_validate_tag_value
list[Violation] clew.guard.checks._validate_tag_value(str file_path, Function func, str tag_name, str value, dict[str, Any] rules)
Check one tag value against pattern, prefix, and contains rules.
Source · 65 lines
def _validate_tag_value(
file_path: str,
func: Function,
tag_name: str,
value: str,
rules: dict[str, Any],
) -> list[Violation]:
violations: list[Violation] = []
line = func.doxygen.start_line + 1 if func.doxygen else func.def_line + 1
# Check pattern match
pattern = rules.get("pattern")
if pattern and not re.match(pattern, value):
violations.append(
Violation(
file=file_path,
line=line,
check="tag",
qualified=func.qualified,
message=(
f"Function '{func.name}' @{tag_name} value '{value}' "
f"does not match pattern '{pattern}'"
),
)
)
# Check required prefix
require_prefix = rules.get("require_prefix")
if require_prefix and not any(value.startswith(p) for p in require_prefix):
violations.append(
Violation(
file=file_path,
line=line,
check="tag",
qualified=func.qualified,
message=(
f"Function '{func.name}' @{tag_name} value '{value}' "
f"does not start with any required prefix: {require_prefix}"
),
)
)
# Check required contains
require_contains = rules.get("require_contains")
if require_contains and require_contains not in value:
violations.append(
Violation(
file=file_path,
line=line,
check="tag",
qualified=func.qualified,
message=(
f"Function '{func.name}' @{tag_name} value '{value}' "
f"does not contain '{require_contains}'"
),
)
)
return violations
# Vocabulary this tool acts on, plus standard doxygen commands. The diagram-generation
# tags (sends, receives, calls, dispatch_key, send_source, receive_source, participant,
# loop, group, after) were removed with the tracer: a tag the tool cannot act on is an
# unknown tag. Repos still carrying them should list them under validate.extra_tags.Activity · 12 steps
Flows
check_bus_tags
list[Violation] clew.guard.checks.check_bus_tags(list[Function] functions, str file_path, dict[str, Any] config, list[str] lines)
Verify that functions crossing a bus carry a bus tag naming a known bus.
Called by validate_file
Tested by
Calls _bus_tags, _bus_vocabulary, _crosses_bus, _exemption_hint, get_validate
Source · 39 lines
def check_bus_tags(
functions: list[Function],
file_path: str,
config: dict[str, Any],
lines: list[str],
) -> list[Violation]:
bus = get_validate(config).get("bus")
if not bus:
return []
tags = _bus_tags(config)
vocabulary = set(bus.get("vocabulary") or ())
handlers = tuple(bus.get("handlers") or ())
senders = tuple(bus.get("senders") or ())
call = re.compile(r"\b(?:%s)\s*\(" % "|".join(map(re.escape, senders))) if senders else None
violations: list[Violation] = []
for func in functions:
if func.doxygen is None or func.name in senders:
continue
present = {t: v for t, v in func.doxygen.tags.items() if t in tags}
violations.extend(_bus_vocabulary(func, file_path, present, vocabulary))
if present or EXEMPTION_TAGS & set(func.doxygen.tags):
continue
if _crosses_bus(func, lines, handlers, call):
violations.append(
Violation(
file=file_path,
line=func.def_line + 1,
check="bus",
qualified=func.qualified,
message=(
f"Function '{func.name}' crosses a bus but carries no bus tag "
f"({', '.join(f'@{t}' for t in sorted(tags))}) and no exemption "
f"({_exemption_hint()})"
),
)
)
return violations
Activity · 19 steps
Requirements
Flows
check_duplicate_tags
list[Violation] clew.guard.checks.check_duplicate_tags(Function func, str file_path, dict[str, Any] config)
Flag single-valued doxygen tags that appear more than once in one block.
Called by validate_file
Tested by 9 tests
test_check_can_be_disabled, test_clean_block_passes, test_duplicate_brief_flagged, test_duplicate_file_tag_flagged, test_duplicate_return_flagged, test_multiple_version_entries_are_legal, test_repeatable_tags_are_not_flagged, test_stacked_blocks_flag_the_single_valued_tags, test_undocumented_function_is_not_flagged
Calls get_validate
Source · 36 lines
def check_duplicate_tags(
func: Function,
file_path: str,
config: dict[str, Any],
) -> list[Violation]:
if func.doxygen is None:
return []
if not get_validate(config).get("duplicate_tags_error", True):
return []
violations: list[Violation] = []
for tag_name, values in func.doxygen.tags.items():
if tag_name in _SINGLE_VALUED_TAGS and len(values) > 1:
logger.warning(
"Duplicate @%s in %s() at %s:%d — values: %r",
tag_name,
func.name,
file_path,
func.doxygen.start_line + 1,
values,
)
violations.append(
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="tag",
qualified=func.qualified,
message=(
f"@{tag_name} appears {len(values)} times in {func.name}() — "
f"only the first is used; remove the extras"
),
)
)
return violations
Activity · 10 steps
Requirements
Flows
check_exemption_reasons
list[Violation] clew.guard.checks.check_exemption_reasons(Function func, str file_path, dict[str, Any] config)
When validate.exemption_reason is required , refuse an exemption tag with no reason.
Source · 28 lines
def check_exemption_reasons(
func: Function, file_path: str, config: dict[str, Any]
) -> list[Violation]:
if func.doxygen is None or get_validate(config).get("exemption_reason") != "required":
return []
return [
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="tag",
qualified=func.qualified,
message=(
f"@{tag} in {func.name}() needs a one-line reason "
f"(validate.exemption_reason is required): `@{tag} <why this has no requirement>`"
),
)
for tag in sorted(EXEMPTION_TAGS & set(func.doxygen.tags))
if not any(v.strip() for v in func.doxygen.tags[tag])
]
# Tags that describe the function as a whole. A second occurrence is not additive:
# downstream readers take tags[name][0], so a duplicate is silently ignored and can
# carry a different value than the author intended.
#
# "version" is deliberately absent. Doxygen permits multiple \version entries, which
# accumulate into one paragraph — flagging them rejected legal doxygen. That was a
# regression introduced with this check in 1.3.0.Activity · 3 steps
Requirements
Flows
check_fails_when_exists
list[Violation] clew.guard.checks.check_fails_when_exists(Function func, str file_path, dict[str, Any] config, set[str]|None mode_ids=None)
Each @fails_when id must be a failure mode the catalogue declares.
Source · 26 lines
def check_fails_when_exists(
func: Function,
file_path: str,
config: dict[str, Any],
mode_ids: set[str] | None = None,
) -> list[Violation]:
from ..failuremodes import TAG
if func.doxygen is None or mode_ids is None:
return []
return [
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="tag",
qualified=func.qualified,
message=(
f"@{TAG} {mode} in {func.name}() names no failure mode the requirements catalogue "
"declares — add it under that requirement's `failure_modes`, or correct the id"
),
)
for mode in func.doxygen.tags.get(TAG, [])
if mode not in mode_ids
]
Activity · 4 steps
Requirements
Flows
check_fails_when_markers
list[Violation] clew.guard.checks.check_fails_when_markers(Function func, str file_path, list[str] lines, set[str]|None mode_ids=None)
Each inline fails_when: marker in a function's body must name a declared mode.
Source · 31 lines
def check_fails_when_markers(
func: Function,
file_path: str,
lines: list[str],
mode_ids: set[str] | None = None,
) -> list[Violation]:
from ..wiki.flowchart import marker
if mode_ids is None:
return []
out: list[Violation] = []
## The parser's lines are 0-based (`check_req_exists` reports `start_line + 1` likewise).
for index in range(func.def_line, min(func.body_end + 1, len(lines))):
mode = marker(lines[index])
if mode is not None and mode not in mode_ids:
out.append(
Violation(
file=file_path,
line=index + 1,
check="tag",
qualified=func.qualified,
message=(
f"fails_when: {mode} in {func.name}() names no failure mode the "
"requirements catalogue declares — add it under a requirement's "
"`failure_modes`, or correct the id"
),
)
)
return out
Activity · 9 steps
Requirements
Flows
check_file_presence
list[Violation] clew.guard.checks.check_file_presence(str file_path, str content, dict[str, Any] config)
Check for file-level doxygen documentation block.
Called by validate_file
Tested by 14 tests
test_a_docstring_missing_a_tag_is_still_reported, test_a_js_file_with_no_file_tag_at_all_still_fails, test_a_one_line_docstring_is_one_block, test_a_shebang_does_not_hide_the_file_block, test_a_use_strict_prologue_does_not_hide_the_file_block, test_an_undocumented_js_file_is_told_the_jsdoc_spelling, test_c_file_missing_tags_fails, test_c_file_with_complete_block_passes, test_c_file_without_file_block_fails, test_disabled_by_default, test_every_jsdoc_file_tag_the_index_accepts_is_accepted, test_include_guards_skipped
Calls _check_file_block_tags, _find_file_doxygen_start, _first_code_line, _suggest_file_skeleton, get_validate
Source · 30 lines
def check_file_presence(
file_path: str,
content: str,
config: dict[str, Any],
) -> list[Violation]:
validate = get_validate(config)
presence_config = validate.get("presence", {})
if not presence_config.get("require_file_doxygen", False):
return []
lines = content.splitlines()
rust = Path(file_path).suffix == ".rs"
block_line = _find_file_doxygen_start(lines, _RUST_FILE_DOC_STARTS if rust else None)
if block_line is None:
first_code = _first_code_line(lines)
return [
Violation(
file=file_path,
line=first_code,
check="presence",
message=(
f"File '{file_path}' has no file-level doxygen block"
f" — add {_suggest_file_skeleton(file_path)}"
),
)
]
return _check_file_block_tags(file_path, lines, block_line)
Activity · 11 steps
Requirements
Flows
check_presence
list[Violation] clew.guard.checks.check_presence(list[Function] functions, str file_path, dict[str, Any] config, str|None content=None)
Verify every function has a doxygen comment with @brief and the revision tag.
Called by validate_file
Tested by 15 tests
test_configured_tag_satisfies_presence, test_default_remains_version, test_line_numbers_1_indexed, test_missing_both_tags, test_missing_brief, test_missing_brief_has_fix_hint, test_missing_configured_tag_is_reported_by_that_name, test_missing_doxygen, test_missing_doxygen_has_fix_hint, test_missing_version, test_multiple_functions, test_no_violations_when_documented
Calls _brief_hint, _is_void_function, _suggest_skeleton, get_validate
Source · 73 lines
def check_presence(
functions: list[Function],
file_path: str,
config: dict[str, Any],
content: str | None = None,
) -> list[Violation]:
validate = get_validate(config)
presence_config = validate.get("presence", {})
if not presence_config.get("require_doxygen", True):
return []
version_config = validate.get("version", {})
require_version = version_config.get("require_present", True)
version_key = version_config.get("tag", "@version").lstrip("@")
source_lines = content.splitlines() if content is not None else None
violations: list[Violation] = []
for func in functions:
if func.doxygen is None:
needs_return = bool(
source_lines is not None and not _is_void_function(func, source_lines)
)
violations.append(
Violation(
file=file_path,
line=func.def_line + 1,
check="presence",
qualified=func.qualified,
message=(
f"Function '{func.name}' has no doxygen comment"
f" — add {_suggest_skeleton(file_path, with_return=needs_return)}"
),
)
)
continue
if "brief" not in func.doxygen.tags:
violations.append(
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="presence",
qualified=func.qualified,
message=(
f"Function '{func.name}' doxygen missing @brief tag"
f" — {_brief_hint(file_path)}"
),
)
)
# Honour the configured tag. This was hardcoded to "version", so setting
# validate.version.tag produced a presence violation demanding @version plus an
# unknown-tag violation for the configured name — the documented escape hatch
# for projects that use doxygen's \version idiomatically did not work.
if require_version and version_key not in func.doxygen.tags:
violations.append(
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="presence",
qualified=func.qualified,
message=(
f"Function '{func.name}' doxygen missing @{version_key} tag"
f" — add '@{version_key} 1.0' to the doxygen comment"
),
)
)
return violations
Activity · 19 steps
Requirements
Flows
check_removed_tags
list[Violation] clew.guard.checks.check_removed_tags(Function func, str file_path, dict[str, Any] config)
Refuse a tag removed in 2.0.0, naming its replacement.
Source · 19 lines
def check_removed_tags(func: Function, file_path: str, config: dict[str, Any]) -> list[Violation]:
if func.doxygen is None:
return []
return [
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="tag",
qualified=func.qualified,
message=(
f"@{tag} in {func.name}() was removed in clew 2.0.0 — use @{REMOVED_TAGS[tag]} "
"(the doxygen-guard tag is not read)"
),
)
for tag in func.doxygen.tags
if tag in REMOVED_TAGS
]
Activity · 3 steps
Requirements
Flows
check_req_coverage
list[Violation] clew.guard.checks.check_req_coverage(list[Function] functions, str file_path, dict[str, Any] config)
Verify functions have requirement or exemption tags when requirements are configured.
Called by validate_file
Tested by
Calls _exemption_hint, _has_active_requirements, _has_version_gate, get_requirements
Source · 45 lines
def check_req_coverage(
functions: list[Function],
file_path: str,
config: dict[str, Any],
) -> list[Violation]:
req_config = get_requirements(config)
if not req_config or not req_config.get("file"):
return []
# If version gate is configured, check if any active requirements exist
if _has_version_gate(config) and not _has_active_requirements(config):
return []
req_file = req_config["file"]
violations: list[Violation] = []
for func in functions:
if func.doxygen is None:
continue
## A DECLARATION'S OBLIGATION IS ITS DEFINITION'S (2.0.0, PG2): one function, so a header
## does not need its @req written twice; its block's own tags are still checked.
if func.is_constructor() or func.is_destructor() or func.is_declaration:
continue
tags = func.doxygen.tags
has_req = bool(tags.get("req"))
has_exemption = bool(EXEMPTION_TAGS & set(tags.keys()))
if not has_req and not has_exemption:
violations.append(
Violation(
file=file_path,
line=func.def_line + 1,
check="coverage",
qualified=func.qualified,
message=(
f"Function '{func.name}' has no @req tag "
f"(see {req_file}) and no exemption "
f"({_exemption_hint()})"
),
)
)
return violations
Activity · 18 steps
Requirements
Flows
check_req_exists
list[Violation] clew.guard.checks.check_req_exists(Function func, str file_path, dict[str, Any] config, set[str]|None req_ids=None)
Cross-validate requirement tag references against the requirements file.
Source · 38 lines
def check_req_exists(
func: Function,
file_path: str,
config: dict[str, Any],
req_ids: set[str] | None = None,
) -> list[Violation]:
# ABSENCE IS NOT EMPTINESS: None means the caller supplied no catalogue information (skip);
# an EMPTY set means the catalogues were looked for and none exists (GH #68).
if func.doxygen is None or req_ids is None:
return []
validate_config = get_validate(config)
tag_config = validate_config.get("tags", {}).get("req", {})
if not tag_config.get("cross_reference", True):
return []
violations: list[Violation] = []
for req_id in func.doxygen.tags.get("req", []):
if not req_ids:
# GH #68: NO CATALOGUE AT ALL used to pass every tag unchecked. A tag that cannot be
# checked is now said to be one.
violations.append(_uncheckable(func, file_path, req_id))
elif req_id not in req_ids:
violations.append(
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="tag",
qualified=func.qualified,
message=(
f"@req {req_id} in {func.name}() not found in requirements file"
f" — verify the ID or add it to the requirements"
),
)
)
return violations
Activity · 13 steps
Requirements
Flows
check_return_presence
list[Violation] clew.guard.checks.check_return_presence(list[Function] functions, str file_path, dict[str, Any] config, str content)
Verify non-void functions have @return or @returns tag.
Called by validate_file
Tested by
Source · 39 lines
def check_return_presence(
functions: list[Function],
file_path: str,
config: dict[str, Any],
content: str,
) -> list[Violation]:
validate = get_validate(config)
if not _require_return(validate, file_path):
return []
lines = content.splitlines()
violations: list[Violation] = []
for func in functions:
if func.doxygen is None:
continue
if func.is_constructor() or func.is_destructor():
continue
tags = func.doxygen.tags
if EXEMPTION_TAGS & set(tags.keys()):
continue
if tags.get("return") or tags.get("returns"):
continue
if _is_void_function(func, lines):
continue
violations.append(
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="presence",
qualified=func.qualified,
message=(
f"Function '{func.name}' doxygen missing @return tag"
" — add '@return <description>' to the doxygen comment"
),
)
)
return violations
Activity · 19 steps
Requirements
Flows
check_satisfies
list[Violation] clew.guard.checks.check_satisfies(dict[str, dict[str, str]] rows, set[str] known, str catalog_file, list[str]|None unchecked=None)
A catalogue entry's satisfies ids that no catalogue holds (GH #68).
Source · 39 lines
def check_satisfies(
rows: dict[str, dict[str, str]],
known: set[str],
catalog_file: str,
unchecked: list[str] | None = None,
) -> list[Violation]:
"""A link names an id in the local or an external catalogue; `<catalog>:<id>` resolves by
its id. Anything else is a broken edge in the requirement tree — unless a PARENT catalogue
could not be read here (`unchecked`), when it may be that parent's: reported unchecked, a
warning naming the parents, never a violation (#73 item 3)."""
from ..requirements import link_ids
out: list[Violation] = []
for req_id, row in rows.items():
for target in link_ids(row):
if target in known or target.split(":", 1)[-1] in known:
continue
if unchecked:
logger.warning(
"%s satisfies %s: unchecked — parent catalogue(s) %s not present here",
req_id,
target,
", ".join(unchecked),
)
continue
out.append(
Violation(
file=catalog_file,
line=1,
check="tag",
message=(
f"{req_id} satisfies {target}, which no requirements catalogue holds "
"(local or impact.requirements.external)"
),
)
)
return out
Activity · 11 steps
Requirements
Flows
check_tags
list[Violation] clew.guard.checks.check_tags(list[Function] functions, str file_path, dict[str, Any] config)
Check that doxygen tags match configured patterns, prefixes, and markers.
Source · 26 lines
def check_tags(
functions: list[Function],
file_path: str,
config: dict[str, Any],
) -> list[Violation]:
validate = get_validate(config)
tag_rules = validate.get("tags", {})
if not tag_rules:
return []
violations: list[Violation] = []
for func in functions:
if func.doxygen is None:
continue
for tag_name, rules in tag_rules.items():
tag_values = func.doxygen.tags.get(tag_name, [])
for value in tag_values:
violations.extend(_validate_tag_value(file_path, func, tag_name, value, rules))
return violations
Activity · 13 steps
Requirements
Flows
check_unknown_tags
list[Violation] clew.guard.checks.check_unknown_tags(Function func, str file_path, dict[str, Any] config)
Check for unknown tags with Levenshtein-based suggestions.
Called by _unknown_tags, validate_file
Tested by 13 tests
test_a_doxygen_command_is_a_known_tag, test_a_typo_of_an_enforced_tag_is_still_caught, test_bus_tags_are_known_tags_when_configured, test_dg_internal_is_left_to_the_removal_check, test_disabled_by_config, test_extra_tags_accepted, test_guard_knows_the_tag_and_refuses_an_undeclared_id, test_internal_is_still_a_recognised_tag, test_known_tag_no_violation, test_levenshtein_suggestion, test_retired_tags_can_be_readmitted_via_extra_tags, test_retired_tracer_tags_are_unknown
Calls _event_tags, _suggest_tag, get_validate
Source · 44 lines
def check_unknown_tags(
func: Function,
file_path: str,
config: dict[str, Any],
) -> list[Violation]:
if func.doxygen is None:
return []
validate_config = get_validate(config)
if not validate_config.get("known_tags_warn", True):
return []
extra = set(validate_config.get("extra_tags", []))
known = (
_KNOWN_TAGS
| extra
| set(validate_config.get("tags", {}).keys())
| _event_tags(config)
| ({"node"} if config.get("wiki_sources") else set())
)
violations: list[Violation] = []
for tag_name in func.doxygen.tags:
## A removed tag is `check_removed_tags`' to refuse, once, with its replacement. A doxygen
## command is known (PG7) but never a SUGGESTION: "did you mean @tparam?" helps nobody.
if (
tag_name not in known
and tag_name not in REMOVED_TAGS
and tag_name not in DOXYGEN_COMMANDS
):
suggestion = _suggest_tag(tag_name, known)
hint = f" — did you mean @{suggestion}?" if suggestion else ""
violations.append(
Violation(
file=file_path,
line=func.doxygen.start_line + 1,
check="tag",
qualified=func.qualified,
message=f"Unknown tag @{tag_name} in {func.name}(){hint}",
)
)
return violations
Activity · 14 steps
Requirements
Flows
check_version_staleness
list[Violation] clew.guard.checks.check_version_staleness(list[Function] functions, str file_path, dict[str, Any] config, str content, list[Function]|None head_functions, str|None head_content)
Detect stale @version tags when function bodies have changed since HEAD.
Called by _stale, validate_file
Tested by 17 tests
test_body_changed_version_bumped, test_body_changed_version_not_updated, test_body_unchanged_no_violation, test_modified_overload_flags_only_that_overload, test_new_function_not_in_head_skipped, test_new_function_same_name_different_body_shape_still_new, test_no_doxygen_skipped, test_no_head_functions_no_violation, test_no_version_tag_skipped, test_reviewed_marker_clears_staleness, test_stale_version_detected, test_staleness_detects_an_unbumped_rust_body
Calls _check_one_version, _index_by_identity, _pair_by_name, _pair_copies, get_validate
Source · 43 lines
def check_version_staleness(
functions: list[Function],
file_path: str,
config: dict[str, Any],
content: str,
head_functions: list[Function] | None,
head_content: str | None,
) -> list[Violation]:
validate = get_validate(config)
version_config = validate.get("version", {})
if not version_config.get("require_increment_on_change", True):
return []
if head_functions is None or head_content is None:
# No HEAD to compare against (new file, or git unavailable) — nothing is stale.
return []
version_tag = version_config.get("tag", "@version")
ctx = VersionCheckContext(
file_path=file_path,
tag_key=version_tag.lstrip("@"),
version_tag=version_tag,
lines=content.splitlines(),
head_lines=head_content.splitlines(),
)
head_index = _index_by_identity(head_functions)
current_index = _index_by_identity(functions)
paired: dict[int, Function] = {}
for key, copies in current_index.items():
paired.update(_pair_copies(copies, head_index.get(key, []), ctx))
paired.update(_pair_by_name(functions, head_functions, paired))
violations: list[Violation] = []
for func in functions:
violation = _check_one_version(func, paired.get(id(func)), ctx)
if violation is not None:
violations.append(violation)
return violations