synth.py

clew/synth.py

The parse-built front end: doxygen-shaped rows for languages doxygen cannot read.

_write_generation

int clew.synth._write_generation(sqlite3.Connection conn, str source_file, list rules, dict|None variables=None, bool root_has_cmake=False)

Write one CMake file's generation rules into generated_files .

clew/synth.py:382

Source · 47 lines
def _write_generation(
    conn: sqlite3.Connection,
    source_file: str,
    rules: list,
    variables: dict | None = None,
    root_has_cmake: bool = False,
) -> int:
    """A RULE WITH NO OUTPUT STILL WRITES ITS ROWS. `add_custom_target` names no OUTPUT — it is
    the aggregate forcing the rules above it to run — and its row carries `output_name = ''` so
    the target's DEPENDS are still readable while `generation_rule`'s lookup, which requires a
    non-empty name, cannot mistake it for a generated file.

    @brief Insert a file's generation rows.
    @return Rows written.
    @version 1
    """
    from .cmakeast import resolve_argument

    cmake_dir = source_file.rsplit("/", 1)[0] if "/" in source_file else ""
    rows = []
    for rule in rules:
        outputs = rule.get("outputs") or [{"literal": "", "name": ""}]
        for out in outputs:
            for role in ("command", "depends"):
                for arg in rule.get(role) or []:
                    rows.append(
                        (
                            out.get("name", ""),
                            out.get("literal", ""),
                            rule.get("kind", ""),
                            source_file,
                            int(rule.get("line") or 0),
                            role,
                            arg.get("name", ""),
                            arg.get("literal", ""),
                            1 if arg.get("unresolved") else 0,
                            ## 2.1: the path the build file alone settles, or "".
                            resolve_argument(
                                arg.get("literal", ""), cmake_dir, variables or {}, root_has_cmake
                            ),
                        )
                    )
    if rows:
        conn.executemany("INSERT INTO generated_files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", rows)
    return len(rows)

Activity · 12 steps
lines 398–398from .cmakeast import resolve_argumentlines 400–400cmake_dir = source_file.rsplit("/", 1)[0] if "/" in source_file else ""lines 401–401rows = []lines 402–402◇ for rule in ruleslines 403–403outputs = rule.get("outputs") or [{"literal": "", "name": ""}]lines 404–404◇ for out in outputslines 405–405◇ for role in ("command", "depends")lines 406–406◇ for arg in rule.get(role) or []lines 407–423rows.append( ( out.get("name", ""), out.get("literal", ""), rule.get("kind", ""), source_file, int(rule.get("line") or 0), role, arg.get("name", ""), arg.get("literal", ""), 1 if arg.get("unresolved") else 0, ## 2.1: the path the build file alone settles, or "". resolve_argument( arg.get("literal", ""), cmake_dir, variables or {}, root_has_cmake ), ) )lines 424–424◇ if rowslines 425–425conn.executemany("INSERT INTO generated_files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", rows)lines 426–426return len(rows)

Requirements

REQ-DDB-PIPE-012

claims

bool clew.synth.claims(str rel)

Whether a repo-relative path is one this front end claims.

clew/synth.py:258

Show on the map →

Called by _has_claimed_path, _needs_doxygen, register_paths, roots_matching_no_file_pattern, test_an_rst_file_gets_no_path_row, test_every_new_file_type_is_claimed_for_the_file_set, test_the_claimed_set_is_exactly_what_was_measured

Tested by

2 teststest_a_file_merely_ending_in_the_cmake_name_is_not_cmake, test_module_and_claims

Calls none

Source · 12 lines
def claims(rel: str) -> bool:
    """Every type this front end registers in `path`, whether or not it will carry
    symbols: a YAML file is claimed so that it is in the file set, and harvested by
    nothing.

    @brief Claimed-file-type test.
    """
    lower = rel.lower()
    name = PurePosixPath(lower).name
    return lower.endswith(CLAIMED_EXTS) or name in SCRIPT_NAMES or name in UNPARSED_NAMES

Activity · 3 steps
lines 265–265lower = rel.lower()lines 266–266name = PurePosixPath(lower).namelines 267–267return lower.endswith(CLAIMED_EXTS) or name in SCRIPT_NAMES or name in UNPARSED_NAMES

Flows

emit_definitions

tuple[int, int] clew.synth.emit_definitions(Path db_path, Path repo_root, Any cache=None)

Write every harvested JS/TS definition into the index.

clew/synth.py:441

Source · 56 lines
def emit_definitions(db_path: Path, repo_root: Path, cache: Any = None) -> tuple[int, int]:
    """@brief Turn the cached js_symbols payloads into rows."""
    from .ast_symbols import ensure_symbol_provenance

    conn = sqlite3.connect(str(db_path))
    try:
        ## BEFORE THE EARLY RETURN, and that placement is the whole point. An index of a repo
        ## with no claimed file type still ran this layer and found nothing, which is a different
        ## fact from the layer never having run — and the first version of this created the table
        ## AFTER the guard, so a C-only repository got no table and `generation_rule` could not
        ## tell the two apart. `test_fixture_fidelity` caught it.
        ensure_generated_files_table(conn)
        conn.execute("DELETE FROM generated_files")
        ensure_decl_extent_table(conn)
        conn.execute(f"DELETE FROM {DECL_EXTENT}")
        if not _has_claimed_path(conn):
            conn.commit()
            return 0, 0
        ensure_symbol_provenance(conn)
        generated_rows = 0
        writer = _Writer(conn)
        ## TWO STAGES, ONE WRITER. The refid key prefix differs per stage so a shell
        ## function and a JS function at the same line of two files cannot collide on the
        ## `refid.refid` UNIQUE constraint; the rows themselves are identical in shape.
        for harvester, prefix in (
            (js_symbol_harvester(), "js"),
            (script_symbol_harvester(), "script"),
        ):
            for path_rowid, payload in run_harvest(conn, repo_root, harvester, cache):
                if not payload:
                    continue
                writer.file(path_rowid, payload, prefix)
                if payload.get("generated"):
                    row = conn.execute(
                        "SELECT name FROM path WHERE rowid = ?", (path_rowid,)
                    ).fetchone()
                    generated_rows += _write_generation(
                        conn,
                        str(row[0]) if row else "",
                        payload["generated"],
                        payload.get("cmake_variables") or {},
                        (Path(repo_root) / "CMakeLists.txt").is_file(),
                    )
        writer.inheritance(declared_dependencies(conn, repo_root))
        conn.commit()
    finally:
        conn.close()
    logger.info(
        "parse front end: %d function(s), %d class(es), %d generation row(s)",
        writer.functions,
        writer.classes,
        generated_rows,
    )
    return writer.functions, writer.classes

Activity · 25 steps
lines 443–443from .ast_symbols import ensure_symbol_provenancelines 445–445conn = sqlite3.connect(str(db_path))lines 446–446trylines 452–452ensure_generated_files_table(conn)lines 453–453conn.execute("DELETE FROM generated_files")lines 454–454ensure_decl_extent_table(conn)lines 455–455conn.execute(f"DELETE FROM {DECL_EXTENT}")lines 456–456◇ if not _has_claimed_path(conn)lines 457–457conn.commit()lines 458–458return 0, 0lines 459–459ensure_symbol_provenance(conn)lines 460–460generated_rows = 0lines 461–461writer = _Writer(conn)lines 465–465◇ for harvester, prefix in (lines 469–469◇ for path_rowid, payload in run_harvest(conn, repo_root, harvester, cache)lines 470–470◇ if not payloadlines 471–471continuelines 472–472writer.file(path_rowid, payload, prefix)lines 473–473◇ if payload.get("generated")lines 474–476row = conn.execute( "SELECT name FROM path WHERE rowid = ?", (path_rowid,) ).fetchone()lines 477–483generated_rows += _write_generation( conn, str(row[0]) if row else "", payload["generated"], payload.get("cmake_variables") or {}, (Path(repo_root) / "CMakeLists.txt").is_file(), )lines 484–484writer.inheritance(declared_dependencies(conn, repo_root))lines 485–485conn.commit()lines 488–493logger.info( "parse front end: %d function(s), %d class(es), %d generation row(s)", writer.functions, writer.classes, generated_rows, )lines 494–494return writer.functions, writer.classes

Requirements

REQ-DDB-PIPE-012

ensure_generated_files_table

None clew.synth.ensure_generated_files_table(sqlite3.Connection conn)

Create the generated_files table if it is absent.

clew/synth.py:342

Show on the map →

Called by emit_definitions, record_self_declared

Calls none

Source · 32 lines
def ensure_generated_files_table(conn: sqlite3.Connection) -> None:
    """CREATED UNCONDITIONALLY, EVEN AT ZERO ROWS — the rule this codebase returns to most. An
    EMPTY table means the layer ran and this repository declares no generation rules; an ABSENT
    one means the layer never ran, and `query.corpus.generation_rule` reports None for both
    unless the table exists to tell them apart.

    ONE ROW PER (output, argument), not per rule, so a rule's arguments are queryable without
    parsing a packed column. The rule's own identity repeats across its rows, which is the shape
    `kconfig_gates` already uses and which `_compact_gate_panel` compacts on the wire rather than
    in storage.

    @brief Ensure the generation table exists.
    @version 1
    """
    conn.execute(
        "CREATE TABLE IF NOT EXISTS generated_files ("
        "  output_name    TEXT NOT NULL,"
        "  output_literal TEXT NOT NULL,"
        "  kind           TEXT NOT NULL,"
        "  source_file    TEXT NOT NULL,"
        "  source_line    INTEGER NOT NULL,"
        "  role           TEXT NOT NULL,"
        "  arg_name       TEXT NOT NULL,"
        "  arg_literal    TEXT NOT NULL,"
        "  unresolved     INTEGER NOT NULL DEFAULT 0,"
        ## 2.1: the argument as a repository-relative path, when the build file alone settles it.
        "  arg_resolved   TEXT NOT NULL DEFAULT '')"
    )
    conn.execute("CREATE INDEX IF NOT EXISTS idx_generated_output ON generated_files(output_name)")
    conn.execute("CREATE INDEX IF NOT EXISTS idx_generated_arg ON generated_files(arg_name)")

Activity · 3 steps
lines 356–369conn.execute( "CREATE TABLE IF NOT EXISTS generated_files (" " output_name TEXT NOT NULL," " output_literal TEXT NOT NULL," " kind TEXT NOT NULL," " source_file TEXT NOT NULL," " source_line INTEGER NOT NULL," " role TEXT NOT NULL," " arg_name TEXT NOT NULL," " arg_literal TEXT NOT NULL," " unresolved INTEGER NOT NULL DEFAULT 0," ## 2.1: the argument as a repository-relative path, when the build file alone settles it. " arg_resolved TEXT NOT NULL DEFAULT '')" )lines 370–370conn.execute("CREATE INDEX IF NOT EXISTS idx_generated_output ON generated_files(output_name)")lines 371–371conn.execute("CREATE INDEX IF NOT EXISTS idx_generated_arg ON generated_files(arg_name)")

Requirements

REQ-DDB-SCHEMA-014

harvest

Any clew.synth._JsSymbolHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's definitions.

clew/synth.py:171

Show on the map →

Called by none

Calls is_js_tree

Source · 6 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        from .jsast import harvest_definitions, is_js_tree

        return harvest_definitions(tree, src_bytes) if is_js_tree(tree) else {}

Activity · 2 steps
lines 172–172from .jsast import harvest_definitions, is_js_treelines 174–174return harvest_definitions(tree, src_bytes) if is_js_tree(tree) else {}
Any clew.synth._ScriptSymbolHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's definitions, and a CMake file's generation rules.

clew/synth.py:221

Show on the map →

Called by none

Calls harvest_generation, is_cmake_tree, is_sh_tree

Source · 21 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        from .cmakeast import harvest_definitions as cmake_definitions
        from .cmakeast import is_cmake_tree
        from .shast import harvest_definitions as sh_definitions
        from .shast import is_sh_tree

        if is_sh_tree(tree):
            return sh_definitions(tree, src_bytes)
        if is_cmake_tree(tree):
            from .cmakeast import harvest_generation

            ## GENERATION RULES RIDE IN THIS PAYLOAD rather than in a stage of their own, and the
            ## vocabulary argues it: `STAGE_SCRIPT_SYMBOLS` covers two languages in one partition
            ## because "every stage in this vocabulary is harvested over every indexed file, so a
            ## second partition would add an empty payload row per file per index — on a
            ## 40,000-file target that is 40,000 rows". Generation rules live only in CMake files,
            ## so a `generation` stage would store precisely that.
            return {**cmake_definitions(tree, src_bytes), **harvest_generation(tree, src_bytes)}
        return {}

Activity · 10 steps
lines 222–222from .cmakeast import harvest_definitions as cmake_definitionslines 223–223from .cmakeast import is_cmake_treelines 224–224from .shast import harvest_definitions as sh_definitionslines 225–225from .shast import is_sh_treelines 227–227◇ if is_sh_tree(tree)lines 228–228return sh_definitions(tree, src_bytes)lines 229–229◇ if is_cmake_tree(tree)lines 230–230from .cmakeast import harvest_generationlines 238–238return {**cmake_definitions(tree, src_bytes), **harvest_generation(tree, src_bytes)}lines 239–239return {}

Requirements

REQ-DDB-PIPE-012

js_symbol_harvester

Harvester clew.synth.js_symbol_harvester()

The JS/TS definitions stage's harvester.

clew/synth.py:181

Show on the map →

Called by _anchor_harvester, build_harvest_plan, emit_definitions

Calls none

Source · 5 lines
def js_symbol_harvester() -> Harvester:
    """@brief Build this stage's harvester."""
    return _JsSymbolHarvester()

Activity · 1 steps
lines 183–183return _JsSymbolHarvester()

Requirements

REQ-DDB-PIPE-012

register_paths

int clew.synth.register_paths(Path db_path, list[str] files)

Insert path rows for the JS/TS files of this build's scanned tree.

clew/synth.py:305

Source · 31 lines
def register_paths(db_path: Path, files: list[str]) -> int:
    """Rows already present (a doxygen that somehow saw the file) are left alone, so
    running this over any build is safe.

    @brief Put the JS/TS files into the harvest's file set.
    @return Rows inserted.
    """
    wanted = sorted(f for f in files if claims(f))
    if not wanted:
        return 0
    conn = sqlite3.connect(str(db_path))
    try:
        present = {r[0] for r in conn.execute("SELECT name FROM path")}
        new = [f for f in wanted if f not in present]
        ## `found` IS A MEASUREMENT AND IS WRITTEN AS ONE (C5). doxygen's own column means
        ## "resolved to content", `query.corpus._was_harvested` reads it, and
        ## `FileSubject.harvested` serves it — so a Perl script registered with `found = 1` would
        ## claim this toolchain parsed it, and would be indistinguishable from a C file it did.
        ## The honest row says: I know this file's name, I did not read it.
        conn.executemany(
            "INSERT INTO path (type, local, found, name) VALUES (?, 1, ?, ?)",
            [(_TYPE_FILE, 0 if unparsed_claims(f) else 1, f) for f in new],
        )
        conn.commit()
    finally:
        conn.close()
    if new:
        logger.info("parse front end: %d file(s) registered", len(new))
    return len(new)

Activity · 12 steps
lines 312–312wanted = sorted(f for f in files if claims(f))lines 313–313◇ if not wantedlines 314–314return 0lines 315–315conn = sqlite3.connect(str(db_path))lines 316–316trylines 317–317present = {r[0] for r in conn.execute("SELECT name FROM path")}lines 318–318new = [f for f in wanted if f not in present]lines 324–327conn.executemany( "INSERT INTO path (type, local, found, name) VALUES (?, 1, ?, ?)", [(_TYPE_FILE, 0 if unparsed_claims(f) else 1, f) for f in new], )lines 328–328conn.commit()lines 331–331◇ if newlines 332–332logger.info("parse front end: %d file(s) registered", len(new))lines 333–333return len(new)

Requirements

REQ-DDB-PIPE-012

render_doc

tuple[str, str] clew.synth.render_doc(str raw)

Render a raw JSDoc block as doxygen's brief / detailed description markup.

clew/synth.py:747

Source · 32 lines
def render_doc(raw: str) -> tuple[str, str]:
    """The summary (an explicit @brief, else the first paragraph) is the brief. The
    remaining prose paragraphs, the version simplesect `extract_version` reads, and every
    other tag as literal `@tag value` text form the detail. Text is HTML-escaped, because
    `strip_xml` would otherwise eat a `Map<string, T>` or a JSX example as markup.

    @brief JSDoc to doxygen description markup.
    @return The two description columns.
    """
    if not raw:
        return "", ""
    from .guard.parser import apply_autobrief, parse_doxygen_tags

    tags = parse_doxygen_tags(raw)
    explicit_brief = "brief" in tags
    apply_autobrief(raw, tags)
    brief = tags.pop("brief", [""])[0]
    paragraphs = _prose_paragraphs(raw)
    if not explicit_brief and paragraphs:
        paragraphs = paragraphs[1:]
    parts = [f"<para>{html.escape(p, quote=False)}</para>" for p in paragraphs]
    for version in tags.pop("version", []):
        parts.append(
            f'<para><simplesect kind="version"><para>{html.escape(version, quote=False)}'
            "</para>\n</simplesect>\n</para>"
        )
    for tag, values in tags.items():
        parts += [f"<para>@{tag} {html.escape(v, quote=False)}</para>" for v in values]
    brief_xml = f"<para>{html.escape(brief, quote=False)}</para>" if brief else ""
    return brief_xml, "\n".join(parts)

Activity · 17 steps
lines 756–756◇ if not rawlines 757–757return "", ""lines 758–758from .guard.parser import apply_autobrief, parse_doxygen_tagslines 760–760tags = parse_doxygen_tags(raw)lines 761–761explicit_brief = "brief" in tagslines 762–762apply_autobrief(raw, tags)lines 763–763brief = tags.pop("brief", [""])[0]lines 764–764paragraphs = _prose_paragraphs(raw)lines 765–765◇ if not explicit_brief and paragraphslines 766–766paragraphs = paragraphs[1:]lines 767–767parts = [f"<para>{html.escape(p, quote=False)}</para>" for p in paragraphs]lines 768–768◇ for version in tags.pop("version", [])lines 769–772parts.append( f'<para><simplesect kind="version"><para>{html.escape(version, quote=False)}' "</para>\n</simplesect>\n</para>" )lines 773–773◇ for tag, values in tags.items()lines 774–774parts += [f"<para>@{tag} {html.escape(v, quote=False)}</para>" for v in values]lines 775–775brief_xml = f"<para>{html.escape(brief, quote=False)}</para>" if brief else ""lines 776–776return brief_xml, "\n".join(parts)

Requirements

REQ-DDB-PIPE-012

script_symbol_harvester

Harvester clew.synth.script_symbol_harvester()

The shell/CMake definitions stage's harvester.

clew/synth.py:246

Source · 5 lines
def script_symbol_harvester() -> Harvester:
    """@brief Build this stage's harvester."""
    return _ScriptSymbolHarvester()

Activity · 1 steps
lines 248–248return _ScriptSymbolHarvester()

Requirements

REQ-DDB-PIPE-012