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.

clew/guard/checks.py:487

Show on the map →

Called by _check_one_version, _pair_copies, _similarity

Calls none

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
lines 488–488return "\n".join(lines[func.def_line : func.body_end + 1])

Flows

_brief_hint

str clew.guard.checks._brief_hint(str file_path)

How to supply a missing brief, in the file's own convention.

clew/guard/checks.py:69

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
lines 70–70◇ if Path(file_path).suffix.lower() in (".rs", ".py", *_JS_SUFFIXES)lines 71–71return "start the doc comment with a summary sentence, or add '@brief <description>'"lines 72–72return "add '@brief <description>' to the doxygen comment"

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.

clew/guard/checks.py:1303

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
lines 1304–1304◇ if not get_validate(config).get("bus")lines 1305–1305return set()lines 1306–1306return _event_tags(config)

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.

clew/guard/checks.py:1383

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
lines 1386–1386◇ if not vocabularylines 1387–1387return []lines 1388–1388line = func.doxygen.start_line + 1 if func.doxygen else func.def_line + 1lines 1389–1403return [ 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 ]

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.

clew/guard/checks.py:1153

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
lines 1154–1154block_text = _extract_file_block_text(lines, block_start)lines 1155–1155from .parser import parse_doxygen_tagslines 1157–1157tags = parse_doxygen_tags(block_text)lines 1158–1158violations: list[Violation] = []lines 1159–1159required = {"file": "@file", "brief": "@brief", "version": "@version"}lines 1160–1160◇ if Path(file_path).suffix.lower() in _JS_SUFFIXESlines 1164–1164◇ if any(tag in tags for tag in _JSDOC_FILE_TAGS)lines 1165–1165del required["file"]lines 1166–1166elselines 1167–1167required["file"] = "@fileoverview (or @file / @overview / @module)"lines 1168–1168◇ if lines[block_start].strip().startswith(_RUST_FILE_DOC_STARTS)lines 1171–1171from .parser import apply_autobrieflines 1173–1173apply_autobrief(block_text, tags)lines 1174–1174del required["file"]lines 1175–1175◇ for tag_key, tag_name in required.items()lines 1176–1176◇ if tag_key not in tagslines 1177–1184violations.append( Violation( file=file_path, line=block_start + 1, check="presence", message=f"File-level doxygen missing {tag_name} tag in '{file_path}'", ) )lines 1185–1185return violations

Requirements

REQ-DDB-GUARD-006

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.

clew/guard/checks.py:510

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
lines 517–522◇ if (lines 524–524return Nonelines 526–526version_value = func.doxygen.tags.get(ctx.tag_key, [""])[0]lines 527–527head_version_value = head_func.doxygen.tags.get(ctx.tag_key, [""])[0]lines 529–529◇ if version_value == head_version_valuelines 530–536return 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", )lines 539–539marker_match = re.search(r"\[(\w+)\]$", version_value.strip())lines 540–540invalid_marker = bool(marker_match) and marker_match.group(1) != "reviewed"lines 541–554return ( 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 )

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.

clew/guard/checks.py:1365

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
lines 1368–1368from fnmatch import fnmatchcaselines 1370–1370◇ if any(fnmatchcase(func.name, g) for g in handlers)lines 1371–1371return Truelines 1372–1372◇ if call is Nonelines 1373–1373return Falselines 1374–1374body = "\n".join(lines[func.def_line + 1 : func.body_end + 1])lines 1375–1375return call.search(body) is not None

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.

clew/guard/checks.py:1216

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
lines 1217–1217first = lines[start].strip()lines 1218–1218quote = first[:3]lines 1219–1219opened = first[3:]lines 1220–1220◇ if quote in openedlines 1221–1221return opened.split(quote, 1)[0]lines 1222–1222body = [opened]lines 1223–1223◇ for line in lines[start + 1 : start + _DOCSTRING_MAX_LINES]lines 1224–1224◇ if quote in linelines 1225–1225body.append(line.split(quote, 1)[0])lines 1226–1226breaklines 1227–1227body.append(line)lines 1228–1228return "\n".join(body)

Flows

_edit_distance

int clew.guard.checks._edit_distance(str a, str b)

Compute Levenshtein edit distance between two strings.

clew/guard/checks.py:922

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
lines 923–923◇ if len(a) < len(b)lines 924–924return _edit_distance(b, a)lines 925–925prev = list(range(len(b) + 1))lines 926–926◇ for i, ca in enumerate(a)lines 927–927curr = [i + 1] + [0] * len(b)lines 928–928◇ for j, cb in enumerate(b)lines 929–929cost = 0 if ca == cb else 1lines 930–930curr[j + 1] = min(curr[j] + 1, prev[j + 1] + 1, prev[j] + cost)lines 931–931prev = currlines 932–932return prev[len(b)]

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.

clew/guard/checks.py:1292

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
lines 1293–1293declared = config.get("event_tags")lines 1294–1294return {str(t).lower() for t in declared} if declared else set(DEFAULT_EVENT_TAG_NAMES)

Flows

_exemption_hint

str clew.guard.checks._exemption_hint()

Render the exemption tags for an error message, derived from the set.

clew/guard/checks.py:314

Source · 4 lines
def _exemption_hint() -> str:
    return ", ".join(f"@{t}" for t in sorted(EXEMPTION_TAGS))

Activity · 1 steps
lines 315–315return ", ".join(f"@{t}" for t in sorted(EXEMPTION_TAGS))

Flows

_extract_file_block_text

str clew.guard.checks._extract_file_block_text(list[str] lines, int start)

clew/guard/checks.py:1196

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
lines 1197–1197◇ if lines[start].strip().startswith(_DOCSTRING_QUOTES)lines 1198–1198return _docstring_block(lines, start)lines 1199–1199block_lines: list[str] = []lines 1200–1200◇ for i in range(start, min(start + 30, len(lines)))lines 1201–1201block_lines.append(lines[i])lines 1202–1202◇ if "*/" in lines[i] or (i > start and not lines[i].strip().startswith(("*", "#", "//")))lines 1203–1203breaklines 1204–1204return "\n".join(block_lines)

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.

clew/guard/checks.py:1257

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
lines 1263–1263skip_prefixes = ("#include", "#pragma", "#ifndef", "#define") + _JS_PROLOGUE_PREFIXESlines 1264–1264doxygen_starts = doxygen_starts or ("/**", "///", "## @", '"""')lines 1265–1265◇ for i, line in enumerate(lines)lines 1266–1266stripped = line.strip()lines 1267–1267◇ if not stripped or any(stripped.startswith(p) for p in skip_prefixes)lines 1268–1268continuelines 1269–1269◇ if any(stripped.startswith(s) for s in doxygen_starts)lines 1270–1270return ilines 1271–1271return Nonelines 1272–1272return None

Requirements

REQ-DDB-GUARD-006

Flows

_first_code_line

int clew.guard.checks._first_code_line(list[str] lines)

Find the first non-blank, non-preprocessor line number.

clew/guard/checks.py:1279

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
lines 1280–1280◇ for i, line in enumerate(lines)lines 1281–1281◇ if line.strip()lines 1282–1282return i + 1lines 1283–1283return 1

Flows

_has_active_requirements

bool clew.guard.checks._has_active_requirements(dict[str, Any] config)

Check if any requirements pass the version gate filter.

clew/guard/checks.py:332

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
lines 333–333from .impact import filter_requirements_by_version, load_requirements_fulllines 335–335full = load_requirements_full(config)lines 336–336filtered = filter_requirements_by_version(full, config)lines 337–337return bool(filtered)

Flows

_has_version_gate

bool clew.guard.checks._has_version_gate(dict[str, Any] config)

Check if version gate is configured.

clew/guard/checks.py:322

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
lines 323–326return bool( get_validate(config).get("current_version") and get_requirements(config).get("version_field") )

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).

clew/guard/checks.py:407

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
lines 410–410index: dict[tuple[str | None, str, str], list[Function]] = {}lines 411–411◇ for f in functionslines 412–412index.setdefault((f.enclosing_class, f.name, f.signature), []).append(f)lines 413–413return index

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.

clew/guard/checks.py:246

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
lines 247–247signature: list[str] = []lines 248–248◇ for idx in range(func.def_line, min(func.def_line + 12, len(lines)))lines 249–249signature.append(lines[idx])lines 250–250◇ if "{" in lines[idx] or lines[idx].rstrip().endswith(";")lines 251–251breaklines 252–252text = " ".join(signature).split("{", 1)[0]lines 253–253return "->" not in text or bool(_RUST_UNIT_RETURN.search(text + "{"))

Requirements

REQ-DDB-GUARD-005

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.

clew/guard/checks.py:264

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
lines 265–265◇ if func.returns_void is not Nonelines 266–266return func.returns_voidlines 267–267◇ if func.def_line < len(lines) and _RUST_FN_RE.search(lines[func.def_line])lines 268–268return _is_rust_unit_fn(func, lines)lines 269–269◇ for offset in range(3)lines 270–270idx = func.def_line + offsetlines 271–271◇ if idx >= len(lines)lines 272–272breaklines 273–273line = lines[idx]lines 274–274name_pos = line.find(func.name)lines 275–275◇ if name_pos < 0 or (name_pos == 0 and offset == 0)lines 276–276continuelines 277–277prefix = " ".join([*lines[func.def_line : idx], line[:name_pos]])lines 278–278is_c_void = bool(_VOID_PATTERNS.search(prefix))lines 279–279is_python_none = bool(_PYTHON_NONE_RETURN.search(line))lines 280–280is_python_untyped = line.strip().startswith("def ") and "->" not in linelines 281–281return is_c_void or is_python_none or is_python_untypedlines 282–282return False

Requirements

REQ-DDB-GUARD-005

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.

clew/guard/checks.py:426

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
lines 429–429taken = {id(h) for h in paired.values()}lines 430–430head_by_name: dict[tuple[str | None, str], list[Function]] = {}lines 431–431◇ for h in head_functionslines 432–432head_by_name.setdefault((h.enclosing_class, h.name), []).append(h)lines 433–433current_by_name: dict[tuple[str | None, str], list[Function]] = {}lines 434–434◇ for f in functionslines 435–435current_by_name.setdefault((f.enclosing_class, f.name), []).append(f)lines 436–436added: dict[int, Function] = {}lines 437–437◇ for key, (func,) in ((k, v) for k, v in current_by_name.items() if len(v) == 1)lines 438–438head = head_by_name.get(key, [])lines 439–439◇ if id(func) not in paired and len(head) == 1 and id(head[0]) not in takenlines 440–440added[id(func)] = head[0]lines 441–441return added

Requirements

REQ-DDB-GUARD-002

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.

clew/guard/checks.py:451

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
lines 454–454◇ if len(current) == len(head)lines 455–455return {id(c): h for c, h in zip(current, head)}lines 456–456pairs: dict[int, Function] = {}lines 457–457free = list(head)lines 458–458◇ for func in currentlines 459–459text = _body_text(func, ctx.lines)lines 460–460same = next((h for h in free if _body_text(h, ctx.head_lines) == text), None)lines 461–461◇ if same is not Nonelines 462–462pairs[id(func)] = samelines 463–463free.remove(same)lines 464–464◇ for func in (c for c in current if id(c) not in pairs)lines 465–465◇ if not freelines 466–466breaklines 467–467best = max(free, key=lambda h, f=func: _similarity(f, h, ctx))lines 468–468pairs[id(func)] = bestlines 469–469free.remove(best)lines 470–470return pairs

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.

clew/guard/checks.py:227

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
lines 228–228ext = Path(file_path).suffixlines 229–229◇ for lang_config in validate.get("languages", {}).values()lines 230–230◇ if isinstance(lang_config, dict) and ext in lang_config.get("extensions", [])lines 231–231◇ if "require_return" in lang_configlines 232–232return bool(lang_config["require_return"])lines 233–233breaklines 234–234return bool(validate.get("presence", {}).get("require_return", True))

Requirements

REQ-DDB-GUARD-005

Flows

_suggest_file_skeleton

str clew.guard.checks._suggest_file_skeleton(str file_path)

Build a language-appropriate file-level doxygen skeleton suggestion.

clew/guard/checks.py:49

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
lines 50–50◇ if Path(file_path).suffix.lower() in _JS_SUFFIXESlines 51–54return ( "'/** @fileoverview <desc> @brief <desc> @version 1.0 */' " "(JSDoc; @file, @overview and @module are accepted too)" )lines 55–55◇ if Path(file_path).suffix.lower() == ".rs"lines 56–56return "'//! <summary sentence>' / '//! @version 1' (inner doc, before first item)"lines 57–57◇ if Path(file_path).suffix.lower() == ".py"lines 58–61return ( "'## @file' / '## @brief <desc>' / '## @version 1.0' " "(two-hash style, before first code)" )lines 62–62return "/** @file @brief <desc> @version 1.0 */ before first code"

Flows

_suggest_skeleton

str clew.guard.checks._suggest_skeleton(str file_path, *bool with_return=False)

Build a language-appropriate doxygen skeleton suggestion.

clew/guard/checks.py:35

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
lines 36–36return_tag = " @return <description>" if with_return else ""lines 37–37◇ if Path(file_path).suffix.lower() == ".rs"lines 38–38return f"'/// <summary sentence>' then '/// @version 1{return_tag}' (above the fn)"lines 39–39◇ if Path(file_path).suffix.lower() in _JS_SUFFIXESlines 40–40return f"'/** <summary sentence> @version 1{return_tag} */' (JSDoc, above the function)"lines 41–41◇ if Path(file_path).suffix.lower() == ".py"lines 42–42return f"'## @brief <description> @version 1.0{return_tag}' (two-hash style, above the def)"lines 43–43return f"'/** @brief <description> @version 1.0{return_tag} */' before function"

Flows

_suggest_tag

str | None clew.guard.checks._suggest_tag(str unknown, AbstractSet[str] known)

Find the closest known tag name using edit distance.

clew/guard/checks.py:908

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
lines 909–909best_tag = Nonelines 910–910best_dist = 3lines 911–911◇ for tag in knownlines 912–912dist = _edit_distance(unknown, tag)lines 913–913◇ if dist < best_distlines 914–914best_dist = distlines 915–915best_tag = taglines 916–916return best_tag

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).

clew/guard/checks.py:940

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
lines 941–951return 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" ), )

Requirements

REQ-DDB-GUARD-027

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.

clew/guard/checks.py:648

Show on the map →

Called by check_tags

Calls none

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
lines 655–655violations: list[Violation] = []lines 656–656line = func.doxygen.start_line + 1 if func.doxygen else func.def_line + 1lines 659–659pattern = rules.get("pattern")lines 660–660◇ if pattern and not re.match(pattern, value)lines 661–672violations.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}'" ), ) )lines 675–675require_prefix = rules.get("require_prefix")lines 676–676◇ if require_prefix and not any(value.startswith(p) for p in require_prefix)lines 677–688violations.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}" ), ) )lines 691–691require_contains = rules.get("require_contains")lines 692–692◇ if require_contains and require_contains not in valuelines 693–704violations.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}'" ), ) )lines 706–706return violations

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.

clew/guard/checks.py:1322

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
lines 1328–1328bus = get_validate(config).get("bus")lines 1329–1329◇ if not buslines 1330–1330return []lines 1331–1331tags = _bus_tags(config)lines 1332–1332vocabulary = set(bus.get("vocabulary") or ())lines 1333–1333handlers = tuple(bus.get("handlers") or ())lines 1334–1334senders = tuple(bus.get("senders") or ())lines 1335–1335call = re.compile(r"\b(?:%s)\s*\(" % "|".join(map(re.escape, senders))) if senders else Nonelines 1336–1336violations: list[Violation] = []lines 1337–1337◇ for func in functionslines 1338–1338◇ if func.doxygen is None or func.name in senderslines 1339–1339continuelines 1340–1340present = {t: v for t, v in func.doxygen.tags.items() if t in tags}lines 1341–1341violations.extend(_bus_vocabulary(func, file_path, present, vocabulary))lines 1342–1342◇ if present or EXEMPTION_TAGS & set(func.doxygen.tags)lines 1343–1343continuelines 1344–1344◇ if _crosses_bus(func, lines, handlers, call)lines 1345–1357violations.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()})" ), ) )lines 1358–1358return violations

Requirements

REQ-DDB-GUARD-026

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.

clew/guard/checks.py:869

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
lines 874–874◇ if func.doxygen is Nonelines 875–875return []lines 876–876◇ if not get_validate(config).get("duplicate_tags_error", True)lines 877–877return []lines 879–879violations: list[Violation] = []lines 880–880◇ for tag_name, values in func.doxygen.tags.items()lines 881–881◇ if tag_name in _SINGLE_VALUED_TAGS and len(values) > 1lines 882–889logger.warning( "Duplicate @%s in %s() at %s:%d — values: %r", tag_name, func.name, file_path, func.doxygen.start_line + 1, values, )lines 890–901violations.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" ), ) )lines 902–902return violations

Requirements

REQ-DDB-GUARD-007

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.

clew/guard/checks.py:833

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
lines 836–836◇ if func.doxygen is None or get_validate(config).get("exemption_reason") != "required"lines 837–837return []lines 838–851return [ 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]) ]

Requirements

REQ-DDB-GUARD-001

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.

clew/guard/checks.py:1051

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
lines 1057–1057from ..failuremodes import TAGlines 1059–1059◇ if func.doxygen is None or mode_ids is Nonelines 1060–1060return []lines 1061–1074return [ 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 ]

Requirements

REQ-DDB-GUARD-001

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.

clew/guard/checks.py:1084

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
lines 1090–1090from ..wiki.flowchart import markerlines 1092–1092◇ if mode_ids is Nonelines 1093–1093return []lines 1094–1094out: list[Violation] = []lines 1096–1096◇ for index in range(func.def_line, min(func.body_end + 1, len(lines)))lines 1097–1097mode = marker(lines[index])lines 1098–1098◇ if mode is not None and mode not in mode_idslines 1099–1111out.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" ), ) )lines 1112–1112return out

Requirements

REQ-DDB-GUARD-001

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.

clew/guard/checks.py:1119

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
lines 1124–1124validate = get_validate(config)lines 1125–1125presence_config = validate.get("presence", {})lines 1126–1126◇ if not presence_config.get("require_file_doxygen", False)lines 1127–1127return []lines 1129–1129lines = content.splitlines()lines 1130–1130rust = Path(file_path).suffix == ".rs"lines 1131–1131block_line = _find_file_doxygen_start(lines, _RUST_FILE_DOC_STARTS if rust else None)lines 1132–1132◇ if block_line is Nonelines 1133–1133first_code = _first_code_line(lines)lines 1134–1144return [ 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)}" ), ) ]lines 1146–1146return _check_file_block_tags(file_path, lines, block_line)

Requirements

REQ-DDB-GUARD-006

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.

clew/guard/checks.py:99

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
lines 105–105validate = get_validate(config)lines 106–106presence_config = validate.get("presence", {})lines 108–108◇ if not presence_config.get("require_doxygen", True)lines 109–109return []lines 111–111version_config = validate.get("version", {})lines 112–112require_version = version_config.get("require_present", True)lines 113–113version_key = version_config.get("tag", "@version").lstrip("@")lines 115–115source_lines = content.splitlines() if content is not None else Nonelines 116–116violations: list[Violation] = []lines 118–118◇ for func in functionslines 119–119◇ if func.doxygen is Nonelines 120–122needs_return = bool( source_lines is not None and not _is_void_function(func, source_lines) )lines 123–134violations.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)}" ), ) )lines 135–135continuelines 137–137◇ if "brief" not in func.doxygen.tagslines 138–149violations.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)}" ), ) )lines 155–155◇ if require_version and version_key not in func.doxygen.tagslines 156–167violations.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" ), ) )lines 169–169return violations

Requirements

REQ-DDB-GUARD-001

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.

clew/guard/checks.py:807

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
lines 808–808◇ if func.doxygen is Nonelines 809–809return []lines 810–823return [ 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 ]

Requirements

REQ-DDB-GUARD-001

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.

clew/guard/checks.py:346

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
lines 351–351req_config = get_requirements(config)lines 352–352◇ if not req_config or not req_config.get("file")lines 353–353return []lines 356–356◇ if _has_version_gate(config) and not _has_active_requirements(config)lines 357–357return []lines 359–359req_file = req_config["file"]lines 360–360violations: list[Violation] = []lines 361–361◇ for func in functionslines 362–362◇ if func.doxygen is Nonelines 363–363continuelines 366–366◇ if func.is_constructor() or func.is_destructor() or func.is_declarationlines 367–367continuelines 369–369tags = func.doxygen.tagslines 370–370has_req = bool(tags.get("req"))lines 371–371has_exemption = bool(EXEMPTION_TAGS & set(tags.keys()))lines 373–373◇ if not has_req and not has_exemptionlines 374–386violations.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()})" ), ) )lines 388–388return violations

Requirements

REQ-DDB-GUARD-004

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.

clew/guard/checks.py:1005

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
lines 1013–1013◇ if func.doxygen is None or req_ids is Nonelines 1014–1014return []lines 1016–1016validate_config = get_validate(config)lines 1017–1017tag_config = validate_config.get("tags", {}).get("req", {})lines 1018–1018◇ if not tag_config.get("cross_reference", True)lines 1019–1019return []lines 1021–1021violations: list[Violation] = []lines 1022–1022◇ for req_id in func.doxygen.tags.get("req", [])lines 1023–1023◇ if not req_idslines 1026–1026violations.append(_uncheckable(func, file_path, req_id))lines 1027–1027◇ elif req_id not in req_idslines 1028–1039violations.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" ), ) )lines 1040–1040return violations

Requirements

REQ-DDB-GUARD-001

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.

clew/guard/checks.py:181

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
lines 187–187validate = get_validate(config)lines 188–188◇ if not _require_return(validate, file_path)lines 189–189return []lines 191–191lines = content.splitlines()lines 192–192violations: list[Violation] = []lines 193–193◇ for func in functionslines 194–194◇ if func.doxygen is Nonelines 195–195continuelines 196–196◇ if func.is_constructor() or func.is_destructor()lines 197–197continuelines 198–198tags = func.doxygen.tagslines 199–199◇ if EXEMPTION_TAGS & set(tags.keys())lines 200–200continuelines 201–201◇ if tags.get("return") or tags.get("returns")lines 202–202continuelines 203–203◇ if _is_void_function(func, lines)lines 204–204continuelines 205–216violations.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" ), ) )lines 217–217return violations

Requirements

REQ-DDB-GUARD-005

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).

clew/guard/checks.py:960

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
lines 970–970from ..requirements import link_idslines 972–972out: list[Violation] = []lines 973–973◇ for req_id, row in rows.items()lines 974–974◇ for target in link_ids(row)lines 975–975◇ if target in known or target.split(":", 1)[-1] in knownlines 976–976continuelines 977–977◇ if uncheckedlines 978–983logger.warning( "%s satisfies %s: unchecked — parent catalogue(s) %s not present here", req_id, target, ", ".join(unchecked), )lines 984–984continuelines 985–995out.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)" ), ) )lines 996–996return out

Requirements

REQ-DDB-SCHEMA-015

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.

clew/guard/checks.py:618

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
lines 623–623validate = get_validate(config)lines 624–624tag_rules = validate.get("tags", {})lines 626–626◇ if not tag_ruleslines 627–627return []lines 629–629violations: list[Violation] = []lines 631–631◇ for func in functionslines 632–632◇ if func.doxygen is Nonelines 633–633continuelines 635–635◇ for tag_name, rules in tag_rules.items()lines 636–636tag_values = func.doxygen.tags.get(tag_name, [])lines 638–638◇ for value in tag_valueslines 639–639violations.extend(_validate_tag_value(file_path, func, tag_name, value, rules))lines 641–641return violations

Requirements

REQ-DDB-GUARD-003

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.

clew/guard/checks.py:758

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
lines 763–763◇ if func.doxygen is Nonelines 764–764return []lines 766–766validate_config = get_validate(config)lines 767–767◇ if not validate_config.get("known_tags_warn", True)lines 768–768return []lines 770–770extra = set(validate_config.get("extra_tags", []))lines 771–777known = ( _KNOWN_TAGS | extra | set(validate_config.get("tags", {}).keys()) | _event_tags(config) | ({"node"} if config.get("wiki_sources") else set()) )lines 779–779violations: list[Violation] = []lines 780–780◇ for tag_name in func.doxygen.tagslines 783–786◇ if (lines 788–788suggestion = _suggest_tag(tag_name, known)lines 789–789hint = f" — did you mean @{suggestion}?" if suggestion else ""lines 790–798violations.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}", ) )lines 799–799return violations

Requirements

REQ-DDB-GUARD-001

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.

clew/guard/checks.py:572

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

Activity · 20 steps
lines 580–580validate = get_validate(config)lines 581–581version_config = validate.get("version", {})lines 583–583◇ if not version_config.get("require_increment_on_change", True)lines 584–584return []lines 586–586◇ if head_functions is None or head_content is Nonelines 588–588return []lines 590–590version_tag = version_config.get("tag", "@version")lines 591–597ctx = VersionCheckContext( file_path=file_path, tag_key=version_tag.lstrip("@"), version_tag=version_tag, lines=content.splitlines(), head_lines=head_content.splitlines(), )lines 598–598head_index = _index_by_identity(head_functions)lines 599–599current_index = _index_by_identity(functions)lines 601–601paired: dict[int, Function] = {}lines 602–602◇ for key, copies in current_index.items()lines 603–603paired.update(_pair_copies(copies, head_index.get(key, []), ctx))lines 604–604paired.update(_pair_by_name(functions, head_functions, paired))lines 606–606violations: list[Violation] = []lines 607–607◇ for func in functionslines 608–608violation = _check_one_version(func, paired.get(id(func)), ctx)lines 609–609◇ if violation is not Nonelines 610–610violations.append(violation)lines 612–612return violations

Requirements

REQ-DDB-GUARD-002

Flows