code_text.py¶
clew/code_text.py
THE CODE-TEXT CORPUS: full-text over every indexed function's body.
_file_hits
list[CodeHit] clew.code_text._file_hits(sqlite3.Connection conn, str query, list[str] tokens, int limit, Path|None repo_root)
Files whose file-scope text holds every word, as kind: "file" hits.
Source · 30 lines
def _file_hits(
conn: sqlite3.Connection, query: str, tokens: list[str], limit: int, repo_root: Path | None
) -> list[CodeHit]:
"""A FILE HIT IS A DOSSIER SUBJECT: `name` and `file` are the repo-relative path, which
`dossier` accepts, and `line`/`snippet` point at the first matching line.
@brief Search the file-scope corpus.
@return Hits.
"""
rows = conn.execute(
f"SELECT p.name FROM {FILE_TABLE} JOIN path p ON p.rowid = {FILE_TABLE}.rowid "
f"WHERE {FILE_TABLE} MATCH ? LIMIT ?",
(query, max(1, limit)),
).fetchall()
hits = []
for (name,) in rows:
line, snippet = _first_match(repo_root, str(name), 1, 10**9, tokens)
hits.append(
CodeHit(
name=str(name),
definition="",
kind="file",
file=str(name),
line=line,
snippet=snippet,
)
)
return hits
Activity · 6 steps
Flows
_first_match
tuple[int, str] clew.code_text._first_match(Path|None repo_root, str rel, int start, int end, list[str] tokens)
Version 2: finds the snippet line by stem, as the match was made.
Source · 15 lines
def _first_match(
repo_root: Path | None, rel: str, start: int, end: int, tokens: list[str]
) -> tuple[int, str]:
"""THE LINE IS FOUND BY STEM, as the match was: `retries` matched through porter stemming,
and the line says `retry`, so a token is compared by a prefix that drops a short suffix.
@brief Locate the matching line. @return (line number, stripped line).
"""
lines = _lines(repo_root / rel) if repo_root is not None else None
lowered = [t.lower()[: max(4, len(t) - 3)] for t in tokens]
for number in range(start, min(end, len(lines or [])) + 1):
text = (lines or [])[number - 1]
if any(t in text.lower() for t in lowered):
return number, text.strip()
return start, ""1 more lines, not shown
Activity · 7 steps
Flows
_has_table
bool clew.code_text._has_table(sqlite3.Connection conn, str name)
Whether a table exists.
Source · 5 lines
def _has_table(conn: sqlite3.Connection, name: str) -> bool:
"""@brief Table presence. @return True when present."""
return bool(conn.execute("SELECT 1 FROM sqlite_master WHERE name = ?", (name,)).fetchone())
Activity · 1 steps
Flows
_match_query
str clew.code_text._match_query(list[str] tokens)
The FTS expression for a word list: each word whole (stemmed) or as a prefix.
Source · 9 lines
def _match_query(tokens: list[str]) -> str:
"""ONE SPELLING for the search and its count, so the total counts what the search matches.
@brief Build the MATCH expression.
@return Text.
"""
return " AND ".join(f'("{t}" OR "{t}"*)' for t in tokens)
Activity · 1 steps
Flows
code_text_rows
list[tuple[Any, ...]] clew.code_text.code_text_rows(sqlite3.Connection conn, str|None rel=None)
Every row the code corpus indexes, or one file's, each file's in rowid order.
Source · 19 lines
def code_text_rows(conn: sqlite3.Connection, rel: str | None = None) -> list[tuple[Any, ...]]:
"""ONE DEFINITION OF THE ROW SET, read by the full stage and by the fast tier, and ORDERED BY
ROWID within a file so both build the same spans key for it (1.3.5). The previous order was
whatever the query plan produced, which a per-file query would not have reproduced.
@brief The corpus rows.
@return Rows.
@version 1
"""
rows = conn.execute(
"SELECT m.rowid, p.name, m.bodystart, m.bodyend, m.name FROM memberdef m "
"JOIN path p ON p.rowid = COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) "
"WHERE m.kind = 'function' AND m.bodystart > 0 AND m.bodyend >= m.bodystart"
).fetchall() + _binding_rows(conn)
if rel is not None:
rows = [r for r in rows if str(r[1]) == rel]
return sorted(rows, key=lambda r: (str(r[1]), int(r[0])))
Activity · 4 steps
Requirements
count_code
int clew.code_text.count_code(sqlite3.Connection conn, str text)
How many units search_code would return with no limit.
Source · 26 lines
def count_code(conn: sqlite3.Connection, text: str) -> int:
"""T1 (2.0.0): the same MATCH and the same joins as `search_code`, counted, so a cut reply can
state its total. Called only when a reply filled its limit; the common path pays nothing.
@brief Count code-corpus matches.
@return Count.
"""
tokens = _QUERY_WORD.findall(text)
if not tokens or not _has_table(conn, TABLE):
return 0
query = _match_query(tokens)
total = conn.execute(
f"SELECT COUNT(*) FROM {TABLE} JOIN memberdef m ON m.rowid = {TABLE}.rowid "
"JOIN path p ON p.rowid = COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) "
f"WHERE {TABLE} MATCH ?",
(query,),
).fetchone()[0]
if _has_table(conn, FILE_TABLE):
total += conn.execute(
f"SELECT COUNT(*) FROM {FILE_TABLE} JOIN path p ON p.rowid = {FILE_TABLE}.rowid "
f"WHERE {FILE_TABLE} MATCH ?",
(query,),
).fetchone()[0]
return int(total)
Activity · 8 steps
Requirements
Flows
file_code_texts
list[str] | None clew.code_text.file_code_texts(IndexCache|None cache, Path repo_root, str rel, list[tuple[Any,...]] file_rows)
One file's indexed texts, memoized on its content and spans.
Called by record_code_text, refresh_code_text
Calls _file_texts, memoized, spans_key
Source · 22 lines
def file_code_texts(
cache: IndexCache | None, repo_root: Path, rel: str, file_rows: list[tuple[Any, ...]]
) -> list[str] | None:
"""MEMOIZED ON THE FILE'S CONTENT AND ITS SPANS (1.3.4): splitting every identifier of every
body into parts was the stage's cost.
@brief Cut and annotate one file, cache-first.
@return Texts or None.
@version 1
"""
spans = [(int(r[2]), int(r[3]), r[4] == MODULE_CALLER) for r in file_rows]
return memoized(
cache,
rel,
repo_root / rel,
"code_text",
CODE_TEXT_STAGE_VERSION,
spans_key(file_rows),
lambda: _file_texts(repo_root / rel, spans),
)
Activity · 2 steps
Requirements
file_scope_text
str clew.code_text.file_scope_text(IndexCache|None cache, Path repo_root, str rel, list[tuple[Any,...]] file_rows)
One file's text outside its function bodies, with identifier parts, cache-first.
Called by _record_file_scope, _refresh_file_scope
Calls _outside, memoized, spans_key
Source · 22 lines
def file_scope_text(
cache: IndexCache | None, repo_root: Path, rel: str, file_rows: list[tuple[Any, ...]]
) -> str:
"""KEYED BY THE FILE'S CONTENT AND ITS FUNCTION SPANS, like `file_code_texts`: what is "outside
every function" depends on where the index says the functions are.
@brief File-scope text for one file.
@return Text.
@version 1
"""
spans = [(int(r[2]), int(r[3])) for r in file_rows if r[4] != MODULE_CALLER]
return memoized(
cache,
rel,
repo_root / rel,
"code_text_files",
CODE_TEXT_STAGE_VERSION,
spans_key(file_rows),
lambda: _outside(repo_root / rel, spans),
)
Activity · 2 steps
Requirements
search_code
list[CodeHit] | None clew.code_text.search_code(sqlite3.Connection conn, str text, int limit, Path|None repo_root=None)
Version 5: a query word also matches as a prefix ( MBEDTLS_ERR_ finds its family).
Source · 69 lines
def search_code(
conn: sqlite3.Connection, text: str, limit: int, repo_root: Path | None = None
) -> list[CodeHit] | None:
"""EVERY WORD MUST APPEAR IN ONE BODY, as the other text corpora match. The SMALLEST
containing body ranks first: a nested closure's words are also in its enclosing function, and
the innermost function that holds them is the answer.
THE SNIPPET IS READ FROM THE FILE NOW, not stored: the table holds only the inverted index
(contentless, no positions), which is what kept the corpus from multiplying the database —
measured on mattermost-mobile, storing the text took the index from 8.4 MB to 45 MB. It also
means a snippet is the file as it is, not as it was when the index was built.
@brief Search function bodies.
@return Hits or None.
@version 1
"""
if not _has_table(conn, TABLE):
return None
## A MEMBER ACCESS MATCHES ITS PARTS: the tokenizer splits `props.failed` at the dot, so a
## quoted token became a phrase, which a `detail=none` table refuses — inside the tool.
tokens = _QUERY_WORD.findall(text)
if not tokens:
return []
## EACH WORD MATCHES WHOLE (through the stemmer, so `retries` finds `retry`) OR AS A PREFIX,
## so a family named by its prefix — `MBEDTLS_ERR_`, `mbedtls_ct_` — finds its members. A
## prefix term is not stemmed, which is why both forms are asked.
query = _match_query(tokens)
## A BINDING'S SPAN is its declaration line through its recorded end; a function's is its body.
start, end, extent = "m.bodystart", "m.bodyend", ""
if _has_table(conn, DECL_EXTENT):
start = "(CASE WHEN m.bodystart > 0 THEN m.bodystart ELSE m.line END)"
end = "COALESCE(e.end_line, m.bodyend)"
extent = f"LEFT JOIN {DECL_EXTENT} e ON e.memberdef_rowid = m.rowid "
order = f"({end} - {start})"
if _has_table(conn, "test_scope"):
order = f"{_TEST_LAST}, {order}"
## WHOLE WORDS FIRST (2.1, found replaying mattermost Q3): a body holding every word itself
## ranks before one that matched only as a prefix (`NavigationHeaderTitle` for
## `NavigationHeader`). Ranked, never dropped: the prefix family stays in the reply.
exact = " AND ".join(f'"{t}"' for t in tokens)
order = f"({TABLE}.rowid IN (SELECT rowid FROM {TABLE} WHERE {TABLE} MATCH ?)) DESC, {order}"
rows = conn.execute(
f"SELECT m.name, m.definition, m.kind, p.name, {start}, {end} "
f"FROM {TABLE} JOIN memberdef m ON m.rowid = {TABLE}.rowid {extent}"
"JOIN path p ON p.rowid = COALESCE(NULLIF(m.bodyfile_id, 0), m.file_id) "
f"WHERE {TABLE} MATCH ? ORDER BY {order} LIMIT ?",
(query, exact, max(1, limit)),
).fetchall()
hits = []
for name, definition, kind, file, start, end in rows:
line, snippet = _first_match(repo_root, str(file), int(start), int(end), tokens)
hits.append(
CodeHit(
name=str(name),
definition=str(definition or ""),
kind=str(kind),
file=str(file),
line=line,
snippet=snippet,
)
)
## FILE-SCOPE MATCHES AFTER FUNCTION MATCHES (1.3.10): a function is the more specific
## answer; a file hit is for text no function holds — a preprocessor line, a file-scope
## declaration. Absent table (an index from before the layer): function hits only.
if len(hits) < limit and _has_table(conn, FILE_TABLE):
hits.extend(_file_hits(conn, query, tokens, limit - len(hits), repo_root))
return hits