apiref.py

clew/wiki/apiref.py

The public-API reference: one page per declared public header, from the index (PAPI, 2.0.0).

api_html

str clew.wiki.apiref.api_html(str rel, list[Symbol] symbols, list[ClassInfo] classes=())

One header's reference page body.

clew/wiki/apiref.py:331

Source · 34 lines
def api_html(rel: str, symbols: list[Symbol], classes: list[ClassInfo] = ()) -> str:
    """CLASS MEMBERS GO UNDER THEIR CLASS (a symbol whose scope names a class declared here); the
    rest by kind; enum values under their enum.

    @brief Render a header.
    @return HTML.
    """
    class_names = {c.name for c in classes} | {
        s.scope for s in symbols if s.scope and s.kind != "enumvalue" and "::" in s.scope
    }
    top = [s for s in symbols if s.scope not in class_names and s.kind != "enumvalue"]
    values = {}
    for s in symbols:
        if s.kind == "enumvalue":
            values.setdefault(s.scope, []).append(s)
    parts = [f'<p class="where"><code>{escape(rel)}</code></p>']
    for kind, heading in _SECTIONS:
        items = [s for s in top if s.kind == kind]
        if items:
            parts.append(f"<h2>{heading}</h2>" + "".join(_entry(s, values) for s in items))
    info = {c.name: c for c in classes}
    for scope in sorted(class_names):
        members = [s for s in symbols if s.scope == scope]
        if not members and scope not in info:
            continue
        c = info.get(scope)
        brief = f"<p>{escape(c.brief)}</p>" if c and c.brief else ""
        parts.append(
            f'<h2 class="api-class" id="api-{escape(scope)}"><code>{escape(scope)}</code></h2>'
            f"{brief}{_hierarchy(c)}" + "".join(_entry(s, values) for s in members)
        )
    return "".join(parts)

Activity · 20 steps
lines 338–340class_names = {c.name for c in classes} | { s.scope for s in symbols if s.scope and s.kind != "enumvalue" and "::" in s.scope }lines 341–341top = [s for s in symbols if s.scope not in class_names and s.kind != "enumvalue"]lines 342–342values = {}lines 343–343◇ for s in symbolslines 344–344◇ if s.kind == "enumvalue"lines 345–345values.setdefault(s.scope, []).append(s)lines 346–346parts = [f'<p class="where"><code>{escape(rel)}</code></p>']lines 347–347◇ for kind, heading in _SECTIONSlines 348–348items = [s for s in top if s.kind == kind]lines 349–349◇ if itemslines 350–350parts.append(f"<h2>{heading}</h2>" + "".join(_entry(s, values) for s in items))lines 351–351info = {c.name: c for c in classes}lines 352–352◇ for scope in sorted(class_names)lines 353–353members = [s for s in symbols if s.scope == scope]lines 354–354◇ if not members and scope not in infolines 355–355continuelines 356–356c = info.get(scope)lines 357–357brief = f"<p>{escape(c.brief)}</p>" if c and c.brief else ""lines 358–361parts.append( f'<h2 class="api-class" id="api-{escape(scope)}"><code>{escape(scope)}</code></h2>' f"{brief}{_hierarchy(c)}" + "".join(_entry(s, values) for s in members) )lines 362–362return "".join(parts)

Requirements

REQ-DDB-WIKI-053

api_pages

str clew.wiki.apiref.api_pages(Path db, tuple[str,...] globs, Path source, tuple[str,...] tags=())

Write the API tab: an index of headers and a page per header.

clew/wiki/apiref.py:404

Source · 49 lines
def api_pages(db: Path, globs: tuple[str, ...], source: Path, tags: tuple[str, ...] = ()) -> str:
    """@brief Write api.md and api-*.md. @return Page name or ""."""
    import re

    from ..query._common import connect

    with connect(db) as conn:
        headers = header_symbols(conn, globs, tags)
        classes = {
            rel: header_classes(conn, rel, {s.scope for s in syms if s.scope})
            for rel, syms in headers.items()
        }
    if not headers:
        return ""
    items = []
    for rel, symbols in headers.items():
        name = "api-" + re.sub(r"[^A-Za-z0-9]+", "-", rel).strip("-")
        text = [
            "---",
            "orphan: true",
            "---",
            "",
            f"# {rel}",
            "",
            "```{raw} html",
            '<p class="crumbs"><a href="api.html">← API</a></p>',
            api_html(rel, symbols, classes[rel]),
            "```",
            "",
        ]
        (Path(source) / f"{name}.md").write_text("\n".join(text), encoding="utf-8")
        items.append(
            f'<li><a href="{name}.html"><code>{escape(rel)}</code></a> · {len(symbols)} symbols</li>'
        )
    index = [
        "# API",
        "",
        f"The public API: {len(headers)} declared public headers (`wiki.api`), from the index. "
        "Private members and `\\internal`-documented symbols are left out.",
        "",
        "```{raw} html",
        f'<ul class="api-headers">{"".join(items)}</ul>',
        "```",
        "",
    ]
    (Path(source) / "api.md").write_text("\n".join(index), encoding="utf-8")
    return "api"

Activity · 16 steps
lines 406–406import relines 408–408from ..query._common import connectlines 410–410with connect(db) as connlines 411–411headers = header_symbols(conn, globs, tags)lines 412–415classes = { rel: header_classes(conn, rel, {s.scope for s in syms if s.scope}) for rel, syms in headers.items() }lines 416–416◇ if not headerslines 417–417return ""lines 418–418items = []lines 419–419◇ for rel, symbols in headers.items()lines 420–420name = "api-" + re.sub(r"[^A-Za-z0-9]+", "-", rel).strip("-")lines 421–433text = [ "---", "orphan: true", "---", "", f"# {rel}", "", "```{raw} html", '<p class="crumbs"><a href="api.html">← API</a></p>', api_html(rel, symbols, classes[rel]), "```", "", ]lines 434–434(Path(source) / f"{name}.md").write_text("\n".join(text), encoding="utf-8")lines 435–437items.append( f'<li><a href="{name}.html"><code>{escape(rel)}</code></a> · {len(symbols)} symbols</li>' )lines 438–448index = [ "# API", "", f"The public API: {len(headers)} declared public headers (`wiki.api`), from the index. " "Private members and `\\internal`-documented symbols are left out.", "", "```{raw} html", f'<ul class="api-headers">{"".join(items)}</ul>', "```", "", ]lines 449–449(Path(source) / "api.md").write_text("\n".join(index), encoding="utf-8")lines 450–450return "api"

Requirements

REQ-DDB-WIKI-053

doc_text

str clew.wiki.apiref.doc_text(str xml)

A doc comment's prose: doxygen XML removed, and the guard's traceability tags with it.

clew/wiki/apiref.py:182

Source · 21 lines
def doc_text(xml: str) -> str:
    """FOUND ON ENTROPIC'S INDEX: `@req REQ-TYPE-002` and the `@version` simplesect read as API
    prose. Traceability belongs to the requirement pages; an API reader gets the description.

    @brief Clean a description.
    @return Text.
    """
    import xml.etree.ElementTree as ET

    from ..query._common import strip_xml

    ## ENTROPIC'S AUDIT OF f6ff1f7c: a regex tag-strip ate `< 2)` and `<bool>` — code text doxygen
    ## stored verbatim. Parsed after `_well_formed`, so text stays text; the strip is the fallback.
    source = _VERSION_SECT.sub("", xml or "")
    try:
        text = " ".join(ET.fromstring(f"<root>{_well_formed(source)}</root>").itertext())
    except ET.ParseError:
        text = strip_xml(source)
    return " ".join(_GUARD_TAG.sub("", text).split())

Activity · 8 steps
lines 189–189import xml.etree.ElementTree as ETlines 191–191from ..query._common import strip_xmllines 195–195source = _VERSION_SECT.sub("", xml or "")lines 196–196trylines 197–197text = " ".join(ET.fromstring(f"<root>{_well_formed(source)}</root>").itertext())lines 198–198except ET.ParseErrorlines 199–199text = strip_xml(source)lines 200–200return " ".join(_GUARD_TAG.sub("", text).split())

Requirements

REQ-DDB-WIKI-053

header_symbols

dict[str, list[Symbol]] clew.wiki.apiref.header_symbols(Any conn, tuple[str,...] globs, tuple[str,...] tags=())

Each declared public header's public symbols, from the index.

clew/wiki/apiref.py:103

Source · 43 lines
def header_symbols(
    conn: Any, globs: tuple[str, ...], tags: tuple[str, ...] = ()
) -> dict[str, list[Symbol]]:
    """@brief Read the API. @return Symbols by header."""
    if not globs:
        return {}
    out: dict[str, list[Symbol]] = {}
    for rowid, rel in conn.execute("SELECT rowid, name FROM path WHERE type = 1 ORDER BY name"):
        if not any(fnmatch.fnmatch(rel, g) for g in globs):
            continue
        rows = conn.execute(
            "SELECT kind, name, COALESCE(scope, ''), COALESCE(definition, ''), "
            "COALESCE(argsstring, ''), COALESCE(initializer, ''), COALESCE(briefdescription, ''), "
            "COALESCE(detaileddescription, ''), line, COALESCE(type, '') FROM memberdef "
            "WHERE file_id = ? AND COALESCE(prot, 0) = ? ORDER BY line",
            (rowid, _PUBLIC),
        )
        symbols = []
        for kind, name, scope, definition, args, value, brief, detail, line, type_ in rows:
            if "<internal>" in detail:
                continue
            doc = parse_doc(detail, tags)
            if kind == "function":
                doc = _with_definition(conn, doc, name, scope, rowid, tags)
            sig = _signature(kind, definition, args, type_, name)
            symbols.append(
                Symbol(
                    kind,
                    name,
                    scope,
                    sig,
                    doc_text(brief),
                    doc.prose,
                    int(line or 0),
                    value.strip(),
                    doc,
                )
            )
        if symbols:
            out[str(rel)] = symbols
    return out

Activity · 19 steps
lines 107–107◇ if not globslines 108–108return {}lines 109–109out: dict[str, list[Symbol]] = {}lines 110–110◇ for rowid, rel in conn.execute("SELECT rowid, name FROM path WHERE type = 1 ORDER BY name")lines 111–111◇ if not any(fnmatch.fnmatch(rel, g) for g in globs)lines 112–112continuelines 113–119rows = conn.execute( "SELECT kind, name, COALESCE(scope, ''), COALESCE(definition, ''), " "COALESCE(argsstring, ''), COALESCE(initializer, ''), COALESCE(briefdescription, ''), " "COALESCE(detaileddescription, ''), line, COALESCE(type, '') FROM memberdef " "WHERE file_id = ? AND COALESCE(prot, 0) = ? ORDER BY line", (rowid, _PUBLIC), )lines 120–120symbols = []lines 121–121◇ for kind, name, scope, definition, args, value, brief, detail, line, type_ in rowslines 122–122◇ if "<internal>" in detaillines 123–123continuelines 124–124doc = parse_doc(detail, tags)lines 125–125◇ if kind == "function"lines 126–126doc = _with_definition(conn, doc, name, scope, rowid, tags)lines 127–127sig = _signature(kind, definition, args, type_, name)lines 128–140symbols.append( Symbol( kind, name, scope, sig, doc_text(brief), doc.prose, int(line or 0), value.strip(), doc, ) )lines 141–141◇ if symbolslines 142–142out[str(rel)] = symbolslines 143–143return out

Requirements

REQ-DDB-WIKI-053

parse_doc

Doc clew.wiki.apiref.parse_doc(str xml, tuple[str,...] tags=())

Parse doxygen's description XML into labelled parts (entropic's gaps 1 and 2).

clew/wiki/apiref.py:461

Source · 50 lines
def parse_doc(xml: str, tags: tuple[str, ...] = ()) -> Doc:
    """Doxygen stores parameters, the return and return values as `<parameterlist>` and
    `<simplesect kind="return">`; they are read as structure rather than flattened into prose. A
    declaration's block and its definition's often repeat the return: identical ones collapse. A
    fragment that will not parse falls back to the flat text, never to nothing.

    @brief Structure a description.
    @return Doc.
    """
    import xml.etree.ElementTree as ET

    try:
        root = ET.fromstring(f"<root>{_well_formed(xml)}</root>")
    except ET.ParseError:
        return Doc(prose=doc_text(xml))
    params: list[tuple[str, str, str]] = []
    retvals: list[tuple[str, str]] = []
    throws: list[tuple[str, str]] = []
    found: list[tuple[str, str]] = []

    ## ENTROPIC'S AUDIT (33 cases): with no ALIASES, doxygen runs a declared `@threadsafety` into
    ## the paragraph before it — a parameter's or the return's — so every part is split too.
    def split(text: str) -> str:
        clean, fields = _fields(text, tags)
        found.extend(fields)
        return clean

    for plist in root.iter("parameterlist"):
        bucket = {"retval": retvals, "exception": throws}.get(plist.get("kind", ""))
        for item in plist.iter("parameteritem"):
            text = split(_flat(item.find("parameterdescription")))
            for name in item.iter("parametername"):
                label = "".join(name.itertext()).strip()
                if bucket is None:
                    params.append((label, name.get("direction", ""), text))
                else:
                    bucket.append((label, text))
    returns = [split(_flat(s)) for s in root.iter("simplesect") if s.get("kind") == "return"]
    _drop(root, {"parameterlist", "simplesect"})
    prose = split(" ".join("".join(root.itertext()).split()))
    return Doc(
        prose=prose,
        params=tuple(dict.fromkeys(params)),
        returns=_distinct(returns),
        retvals=tuple(dict.fromkeys(retvals)),
        fields=tuple(dict.fromkeys(found)),
        throws=tuple(dict.fromkeys(throws)),
    )

Activity · 24 steps
lines 470–470import xml.etree.ElementTree as ETlines 472–472trylines 473–473root = ET.fromstring(f"<root>{_well_formed(xml)}</root>")lines 474–474except ET.ParseErrorlines 475–475return Doc(prose=doc_text(xml))lines 476–476params: list[tuple[str, str, str]] = []lines 477–477retvals: list[tuple[str, str]] = []lines 478–478throws: list[tuple[str, str]] = []lines 479–479found: list[tuple[str, str]] = []lines 483–486def split(text: str) -> str: clean, fields = _fields(text, tags) found.extend(fields) return cleanlines 488–488◇ for plist in root.iter("parameterlist")lines 489–489bucket = {"retval": retvals, "exception": throws}.get(plist.get("kind", ""))lines 490–490◇ for item in plist.iter("parameteritem")lines 491–491text = split(_flat(item.find("parameterdescription")))lines 492–492◇ for name in item.iter("parametername")lines 493–493label = "".join(name.itertext()).strip()lines 494–494◇ if bucket is Nonelines 495–495params.append((label, name.get("direction", ""), text))lines 496–496elselines 497–497bucket.append((label, text))lines 498–498returns = [split(_flat(s)) for s in root.iter("simplesect") if s.get("kind") == "return"]lines 499–499_drop(root, {"parameterlist", "simplesect"})lines 500–500prose = split(" ".join("".join(root.itertext()).split()))lines 501–508return Doc( prose=prose, params=tuple(dict.fromkeys(params)), returns=_distinct(returns), retvals=tuple(dict.fromkeys(retvals)), fields=tuple(dict.fromkeys(found)), throws=tuple(dict.fromkeys(throws)), )

Requirements

REQ-DDB-WIKI-053