symbols.py¶
clew/wiki/symbols.py
Symbol pages (round 3, P1f; round 4, R3).
_activity
str clew.wiki.symbols._activity(Path repo_root, Definition d, str name)
A function's activity diagram, folded, on its own page (P5.5).
Source · 20 lines
def _activity(repo_root: Path, d: Definition, name: str) -> str:
"""ONE PER FUNCTION (owner Q/A 2026-11-20): a test's call-flow box links here with the lines it
executed (`?lit=`), and `clew.js` lights them, so no test page carries its own copy. Folded like
the body, and withheld with it under `exclude_bodies`: it shows the statements.
@brief Activity diagram block.
@return HTML.
"""
from .activity import activity_svg, steps_of
lines = _lines(repo_root, d)
steps = steps_of(lines, d.file, d.start) if lines else []
if not steps:
return ""
return (
f'<details class="activity" id="act-{anchor(name)}"><summary>Activity · '
f"{len(steps)} steps</summary><figure>{activity_svg(steps, name)}</figure></details>"
)
Activity · 6 steps
Requirements
Flows
_definitions
list[Definition] clew.wiki.symbols._definitions(Any conn, set[tuple[str, str]] keys)
Every definition of each referenced (function, file).
Called by symbol_pages, test_a_long_signature_still_bundles_its_body, test_an_out_of_line_definition_keeps_its_body_start
Calls none
Source · 32 lines
def _definitions(conn: Any, keys: set[tuple[str, str]]) -> list[Definition]:
"""@brief Resolve keys. @return Definitions."""
out = []
for name, rel in sorted(keys):
rows = conn.execute(
"SELECT m.rowid, m.definition, m.argsstring, m.briefdescription, m.bodystart, "
"m.bodyend, m.line, COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) = m.file_id "
"FROM memberdef m JOIN path p ON p.rowid = "
"COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) "
"WHERE m.kind = 'function' AND m.name = ? AND p.name = ? ORDER BY m.line",
(name, rel),
).fetchall()
for rowid, definition, args, brief, start, end, line, same_file in rows:
## W-11 (owner review 2026-11-22): THE EXTENT STARTS AT THE DECLARATION when it is in
## the body's own file. `bodystart` alone began past a multi-line signature, so 598
## sections read as stale. Out of line (declared in a header), the body start stands.
if same_file and line and start and int(line) < int(start):
start = line
out.append(
Definition(
int(rowid),
name,
rel,
f"{definition or ''}{args or ''}".strip(),
" ".join(re.sub(r"<[^>]+>", " ", str(brief or "")).split()),
int(start or line or 0),
int(end or 0),
)
)
return out
Activity · 8 steps
Flows
_file_header
str clew.wiki.symbols._file_header(str rel, str doc)
A file page's header: its path, then its documented purpose's first sentence.
Called by symbol_pages, test_a_file_page_names_the_file_and_says_what_it_is_for
Calls none
Source · 12 lines
def _file_header(rel: str, doc: str) -> str:
"""E-20: the h1 is the file's name; this follows it. A file with no documented purpose says only
where it is.
@brief File header.
@return HTML.
"""
out = f'<p class="sym-path"><code>{escape(rel)}</code></p>'
first = re.split(r"(?<=[.!?])\s", " ".join(doc.split()), maxsplit=1)[0] if doc.strip() else ""
return out + (f'<p class="sym-purpose">{escape(first)}</p>' if first else "")
Activity · 3 steps
Flows
_near
str clew.wiki.symbols._near(Definition d, _Edges graph, set[tuple[str, str]] written, set|None tests=None)
A definition's place on the web, and its neighbours linked when they have sections.
Source · 26 lines
def _near(
d: Definition, graph: _Edges, written: set[tuple[str, str]], tests: set | None = None
) -> str:
"""E-20 (UX review, owner Q/A 2026-11-22): product callers and the tests that call it are listed
apart, the tests folded under their count.
@brief Neighbours.
@return HTML.
"""
from urllib.parse import quote
web = f"map.html#n={quote(d.name)}@{quote(d.file)}"
product, testing = _split_callers(graph.around(d.rowid, "callers"), tests or set())
tested = (
f'<p><b>Tested by</b> <details class="more"><summary>{len(testing)} tests</summary>'
f"{_names(testing, written)}</details></p>"
if testing
else ""
)
return (
f'<div class="near"><p><a href="{web}">Show on the map →</a></p>'
f"<p><b>Called by</b> {_names(product, written)}</p>{tested}"
f"<p><b>Calls</b> {_names(graph.around(d.rowid, 'callees'), written)}</p></div>"
)
Activity · 5 steps
Flows
_owners_by_file
dict[str, list[str]] clew.wiki.symbols._owners_by_file(Any conn, set[str] files, Any rules)
Each written file's owners, unless the audience withholds them.
Source · 15 lines
def _owners_by_file(conn: Any, files: set[str], rules: Any) -> dict[str, list[str]]:
"""P5 (2.0.0): the owners layer on the page a reader opens to ask who to talk to. Empty under
`exclude_owners`. @brief Read owners. @return Map."""
from ..query.corpus import file_owners
if getattr(rules, "exclude_owners", False):
return {}
out = {}
for rel in files:
names = list(dict.fromkeys(o.owner for o in file_owners(conn, rel) or ()))
if names:
out[rel] = names
return out
Activity · 9 steps
Flows
_owners_line
list[str] clew.wiki.symbols._owners_line(list[str]|None names)
The owners line at the top of a file page.
Source · 9 lines
def _owners_line(names: list[str] | None) -> list[str]:
"""@brief Owners line. @return Lines."""
if not names:
return []
return [
f'<p class="owners">Owners: {", ".join(f"<code>{escape(n)}</code>" for n in names)}</p>'
]
Activity · 3 steps
Flows
_path
list[str] clew.wiki.symbols._path(_Edges graph, int start, set[tuple[str, str]] targets, int depth=_PATH_DEPTH)
The shortest call path from a test to any implementer of a requirement.
Source · 26 lines
def _path(
graph: _Edges, start: int, targets: set[tuple[str, str]], depth: int = _PATH_DEPTH
) -> list[str]:
"""BREADTH-FIRST over resolved calls, at most `_PATH_DEPTH` hops: the path a reader can walk
from the test to the code it reaches.
@brief Path.
@return Names.
"""
goal = {r for key in targets for r in graph.rowids(key)}
prev: dict[int, int] = {start: start}
frontier = [start]
for _ in range(depth):
nxt = []
for node in frontier:
for callee in sorted(graph.callees.get(node, ())):
if callee in prev:
continue
prev[callee] = node
if callee in goal:
return _unwind(graph, prev, callee)
nxt.append(callee)
frontier = nxt
return []
Activity · 15 steps
Flows
_section
str clew.wiki.symbols._section(str name, list[Definition] defs, _Edges graph, set[tuple[str, str]] written, dict[str, Any] ctx, Path repo_root)
One name's section: every definition of it in the file.
Called by symbol_pages
Calls _activity, _near, _test_block, anchor, md_title, source_url
Source · 51 lines
def _section(
name: str,
defs: list[Definition],
graph: _Edges,
written: set[tuple[str, str]],
ctx: dict[str, Any],
repo_root: Path,
) -> str:
"""@brief Section. @return HTML."""
from .htmltable import md_title, source_url
key = (name, defs[0].file)
reqs = sorted(set(ctx["req_of"].get(key, ())))
flows = sorted((p for p in ctx["flows"] if key in p.functions), key=lambda p: p.title)
parts = [f'<section class="symbol" id="{anchor(name)}"><h2><code>{escape(name)}</code></h2>']
for d in defs:
url = source_url(ctx["template"], ctx["commit"], d.file, max(d.start, 1))
where = f"{escape(d.file)}:{d.start}"
if url:
where = f'<a href="{escape(url)}">{where}</a>'
parts.append(
f'<pre class="sig">{escape(d.signature or name)}</pre>'
+ (f"<p>{escape(d.brief)}</p>" if d.brief else "")
+ f'<p class="where">{where}</p>'
+ _near(d, graph, written, set(ctx.get("test_keys", ())))
)
if key in ctx.get("test_keys", ()):
parts.append(_test_block(d, graph, ctx, repo_root))
if not ctx["rules"].exclude_bodies:
parts.append(_body(repo_root, d, ctx))
parts.append(_activity(repo_root, d, name))
if reqs:
parts.append(
"<h4>Requirements</h4><p>"
+ " ".join(
f'<a class="req-badge" href="requirements.html#{escape(r)}">{escape(r)}</a>'
for r in reqs
)
+ "</p>"
)
if flows:
parts.append(
'<h4>Flows</h4><ul class="modal-list">'
+ "".join(
f'<li><a href="{escape(p.name)}.html">{md_title(p.title)}</a></li>' for p in flows
)
+ "</ul>"
)
return "".join(parts) + "</section>"
Activity · 21 steps
Flows
_split_callers
tuple[list, list] clew.wiki.symbols._split_callers(Any pairs, set tests)
Callers split into product code and the tests that call it.
Source · 6 lines
def _split_callers(pairs: Any, tests: set) -> tuple[list, list]:
"""@brief Split callers. @return Pair."""
pairs = list(pairs)
return [p for p in pairs if tuple(p) not in tests], [p for p in pairs if tuple(p) in tests]
Activity · 2 steps
Flows
_test_block
str clew.wiki.symbols._test_block(Definition d, _Edges graph, dict[str, Any] ctx, Path repo_root)
What a test tests: its assertions, result, verified requirements and call paths.
Source · 26 lines
def _test_block(d: Definition, graph: _Edges, ctx: dict[str, Any], repo_root: Path) -> str:
"""ASSERTIONS ARE SOURCE TEXT, withheld under `exclude_bodies`; the verified requirements and
paths are the index's facts and stay.
@brief Test block.
@return HTML.
"""
from .testfacts import assertions, verifies_block
facts = ctx["tests"][d.name]
paths = {
req: _path(
graph, d.rowid, ctx["implementers"].get(req, set()), ctx.get("path_depth", _PATH_DEPTH)
)
for req, _kind in facts.verifies
}
out = verifies_block(facts, {r: p for r, p in paths.items() if p})
lines = _lines(repo_root, d)
if lines and not ctx["rules"].exclude_bodies:
found = assertions(lines)
if found:
items = "".join(f"<li><code>{escape(a)}</code></li>" for a in found)
out = f'<h4>Checks</h4><ul class="asserts">{items}</ul>' + out
return f'<div class="test-facts">{out}</div>'
Activity · 11 steps
Flows
_unwind
list[str] clew.wiki.symbols._unwind(_Edges graph, dict[int, int] prev, int end)
The names along a found path.
Source · 8 lines
def _unwind(graph: _Edges, prev: dict[int, int], end: int) -> list[str]:
"""@brief Unwind. @return Names."""
out = [end]
while prev[out[-1]] != out[-1]:
out.append(prev[out[-1]])
return [graph.names[r][0] for r in reversed(out)]
Activity · 4 steps
Flows
_write_objects
None clew.wiki.symbols._write_objects(Path source, list[tuple[str, str]] written)
The symbol sections, as the clew Sphinx domain lists them in objects.inv.
Source · 10 lines
def _write_objects(source: Path, written: list[tuple[str, str]]) -> None:
"""S8 (2.0.0): see `_sphinxsymbols`. @brief Write the object list. @return None."""
import json
from ._sphinxsymbols import OBJECTS_FILE
rows = [{"name": n, "file": f, "page": page_for(f), "anchor": anchor(n)} for n, f in written]
(source / OBJECTS_FILE).write_text(json.dumps(rows, separators=(",", ":")), encoding="utf-8")
Activity · 4 steps
Flows
anchor
str clew.wiki.symbols.anchor(str name)
A section's id.
Called by _activity, _callflow, _section, _write_objects, feature_pages, symbol_href, write_quick_views
Tested by
Calls none
Source · 5 lines
def anchor(name: str) -> str:
"""@brief Anchor id. @return Id."""
return "s-" + re.sub(r"[^\w.-]", "_", name)
Activity · 1 steps
Flows
page_for
str clew.wiki.symbols.page_for(str rel)
The page a file's symbols live on.
Source · 5 lines
def page_for(rel: str) -> str:
"""@brief Page name. @return Name."""
return "sym-" + re.sub(r"[^A-Za-z0-9]+", "-", rel).strip("-")
Activity · 1 steps
Requirements
Flows
symbol_href
str clew.wiki.symbols.symbol_href(str name, str rel)
A symbol's section link.
Called by _callflow, _functions, _names, _source_page, feature_pages, flow_page, link, link, symbol_pages, write_quick_views
Source · 10 lines
def symbol_href(name: str, rel: str) -> str:
"""ONE SECTION PER NAME PER FILE, holding every definition of it — so a link never needs to
know which of several same-named definitions it means.
@brief Href.
@return Href.
"""
return f"{page_for(rel)}.html#{anchor(name)}"
Activity · 1 steps
Requirements
Flows
symbol_pages
dict[tuple[str, str], str] clew.wiki.symbols.symbol_pages(Path db, Path repo_root, set[tuple[str, str]] keys, dict[str, Any] ctx, Path source)
Write a page per file holding the referenced symbols.
Called by _build_site
Calls _definitions, _file_header, _owners_by_file, _owners_line, _section, _write_objects, connect, page_for, symbol_href, table_exists, test_functions
Source · 46 lines
def symbol_pages(
db: Path, repo_root: Path, keys: set[tuple[str, str]], ctx: dict[str, Any], source: Path
) -> dict[tuple[str, str], str]:
"""@brief Write sym-*.md. @return Hrefs."""
with connect(db) as conn:
tests = test_functions(conn, set(ctx.get("tests") or {}))
defs = _definitions(conn, keys | tests)
graph = _Edges(conn)
owned = _owners_by_file(conn, {d.file for d in defs}, ctx["rules"])
## E-20: each file's own documented purpose, for its page's header.
purposes = (
dict(conn.execute("SELECT file_path, doc FROM file_docs"))
if table_exists(conn, "file_docs")
else {}
)
ctx = {**ctx, "test_keys": tests}
by_file: dict[str, dict[str, list[Definition]]] = defaultdict(lambda: defaultdict(list))
for d in defs:
by_file[d.file][d.name].append(d)
written = {(n, f) for f, names in by_file.items() for n in names}
for rel, names in sorted(by_file.items()):
sections = [
_section(name, names[name], graph, written, ctx, Path(repo_root))
for name in sorted(names)
]
text = [
"---",
"orphan: true",
"---",
"",
f"# {rel.rsplit('/', 1)[-1]}",
"",
"```{raw} html",
## UX review E-20 (owner Q/A 2026-11-22): the file's name as the title, then its path and
## what it is for — the page used to open on a small grey path chip.
_file_header(rel, str(purposes.get(rel) or "")),
*_owners_line(owned.get(rel)),
*sections,
"```",
"",
]
(Path(source) / f"{page_for(rel)}.md").write_text("\n".join(text), encoding="utf-8")
_write_objects(Path(source), sorted(written, key=lambda k: (k[1], k[0])))
return {key: symbol_href(*key) for key in written}
Activity · 17 steps
Requirements
Flows
test_functions
set[tuple[str, str]] clew.wiki.symbols.test_functions(Any conn, set[str] names)
The test functions the evidence names, found in test code.
Source · 20 lines
def test_functions(conn: Any, names: set[str]) -> set[tuple[str, str]]:
"""A NAME OUTSIDE TEST CODE is not that test: a scenario title or a Catch2 string name has no
function of that name, and a namesake in product code is not the test.
@brief Resolve tests.
@return Keys.
"""
if not names or not table_exists(conn, "test_scope"):
return set()
scope = {r for (r,) in conn.execute("SELECT path_rowid FROM test_scope")}
out = set()
for name, rel, prow in conn.execute(
"SELECT m.name, p.name, p.rowid FROM memberdef m JOIN path p ON p.rowid = "
"COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) WHERE m.kind = 'function'"
):
if name in names and int(prow) in scope:
out.add((str(name), str(rel)))
return out