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 .
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
Requirements
claims
bool clew.synth.claims(str rel)
Whether a repo-relative path is one this front end claims.
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
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
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.
Called by _links, run_real_stages
Tested by
Calls _has_claimed_path, _write_generation, declared_dependencies, ensure_decl_extent_table, ensure_generated_files_table, ensure_symbol_provenance, js_symbol_harvester, run_harvest, script_symbol_harvester
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
Requirements
ensure_generated_files_table
None clew.synth.ensure_generated_files_table(sqlite3.Connection conn)
Create the generated_files table if it is absent.
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
Requirements
harvest
Any clew.synth._JsSymbolHarvester.harvest(self, Any tree, bytes src_bytes)
Harvest one file's definitions.
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
Any clew.synth._ScriptSymbolHarvester.harvest(self, Any tree, bytes src_bytes)
Harvest one file's definitions, and a CMake file's generation rules.
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
Requirements
js_symbol_harvester
Harvester clew.synth.js_symbol_harvester()
The JS/TS definitions stage's harvester.
Source · 5 lines
def js_symbol_harvester() -> Harvester:
"""@brief Build this stage's harvester."""
return _JsSymbolHarvester()
Activity · 1 steps
Requirements
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.
Called by _links, run_real_stages
Tested by 7 tests
test_a_documented_file_is_not_displaced_by_a_name_only_match, test_a_registered_file_is_findable_in_the_default_corpus, test_an_unparsed_file_is_registered_as_known_but_unread, test_shell_and_cmake_definitions_become_rows, test_the_data_files_are_in_the_file_set_with_no_symbols, test_the_registered_file_answers_as_a_file_subject, test_the_shell_doc_block_reaches_the_row
Calls claims, unparsed_claims
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
Requirements
render_doc
tuple[str, str] clew.synth.render_doc(str raw)
Render a raw JSDoc block as doxygen's brief / detailed description markup.
Called by _compound, _function
Tested by
Calls _prose_paragraphs, apply_autobrief, parse_doxygen_tags
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
Requirements
script_symbol_harvester
Harvester clew.synth.script_symbol_harvester()
The shell/CMake definitions stage's harvester.
Source · 5 lines
def script_symbol_harvester() -> Harvester:
"""@brief Build this stage's harvester."""
return _ScriptSymbolHarvester()