ast_includes.py

clew/ast_includes.py

Every C/C++ `#include`, read from the parse and resolved to an indexed file (T3; 2.0.0).

ensure_ast_includes_table

None clew.ast_includes.ensure_ast_includes_table(sqlite3.Connection conn)

Create the ast_includes table.

clew/ast_includes.py:92

Show on the map →

Called by import_ast_includes, schema_db

Calls none

Source · 18 lines
def ensure_ast_includes_table(conn: sqlite3.Connection) -> None:
    """Created unconditionally, so a tree with no `#include` yields an EMPTY table, not an absent
    one. @brief Create the table. @return None."""
    conn.executescript(
        """
        CREATE TABLE IF NOT EXISTS ast_includes (
          src_id INTEGER NOT NULL REFERENCES path(rowid),
          dst_id INTEGER REFERENCES path(rowid),
          spec TEXT NOT NULL,
          local INTEGER NOT NULL,
          line INTEGER NOT NULL,
          UNIQUE(src_id, line)
        );
        CREATE INDEX IF NOT EXISTS idx_ast_includes_dst ON ast_includes(dst_id);
        """
    )

Activity · 1 steps
lines 95–107conn.executescript( """ CREATE TABLE IF NOT EXISTS ast_includes ( src_id INTEGER NOT NULL REFERENCES path(rowid), dst_id INTEGER REFERENCES path(rowid), spec TEXT NOT NULL, local INTEGER NOT NULL, line INTEGER NOT NULL, UNIQUE(src_id, line) ); CREATE INDEX IF NOT EXISTS idx_ast_includes_dst ON ast_includes(dst_id); """ )

Requirements

REQ-DDB-INDEX-010

harvest

Any clew.ast_includes._IncludesHarvester.harvest(self, Any tree, bytes src_bytes)

Harvest one file's include directives.

clew/ast_includes.py:60

Show on the map →

Called by none

Calls none

Source · 18 lines
    def harvest(self, tree: Any, src_bytes: bytes) -> Any:
        """@brief Walk one file's `#include`s. @return Entries."""
        found: list[list[Any]] = []
        stack = [tree.root_node]
        while stack:
            node = stack.pop()
            stack.extend(node.children)
            if node.type != _INCLUDE_NODE:
                continue
            path = node.child_by_field_name("path")
            if path is None or path.type not in (_QUOTED, _SYSTEM):
                continue
            spec = path.text.decode("utf-8", "replace")[1:-1].strip()
            if spec:
                found.append([spec, 1 if path.type == _QUOTED else 0, node.start_point[0] + 1])
        return found

Activity · 14 steps
lines 62–62found: list[list[Any]] = []lines 63–63stack = [tree.root_node]lines 64–64◇ while stacklines 65–65node = stack.pop()lines 66–66stack.extend(node.children)lines 67–67◇ if node.type != _INCLUDE_NODElines 68–68continuelines 69–69path = node.child_by_field_name("path")lines 70–70◇ if path is None or path.type not in (_QUOTED, _SYSTEM)lines 71–71continuelines 72–72spec = path.text.decode("utf-8", "replace")[1:-1].strip()lines 73–73◇ if speclines 74–74found.append([spec, 1 if path.type == _QUOTED else 0, node.start_point[0] + 1])lines 75–75return found

Requirements

REQ-DDB-INDEX-010

import_ast_includes

int clew.ast_includes.import_ast_includes(Path db_path, Path repo_root, IndexCache|None cache=None)

Record every indexed file's #include directives.

clew/ast_includes.py:238

Source · 19 lines
def import_ast_includes(db_path: Path, repo_root: Path, cache: IndexCache | None = None) -> int:
    """@brief Fill ast_includes. @return Row count."""
    conn = sqlite3.connect(str(db_path))
    try:
        ensure_ast_includes_table(conn)
        conn.execute("DELETE FROM ast_includes")
        resolver, names = _resolver(conn)
        rows = [
            row
            for src, payload in run_harvest(conn, repo_root, includes_harvester(), cache)
            for row in _rows(resolver, src, names.get(src, ""), payload)
        ]
        conn.executemany(_INSERT, rows)
        conn.commit()
    finally:
        conn.close()
    resolved = sum(1 for r in rows if r[1] is not None)
    logger.info("includes: %d directive(s), %d resolved to an indexed file", len(rows), resolved)
    return len(rows)

1 more lines, not shown

Activity · 11 steps
lines 240–240conn = sqlite3.connect(str(db_path))lines 241–241trylines 242–242ensure_ast_includes_table(conn)lines 243–243conn.execute("DELETE FROM ast_includes")lines 244–244resolver, names = _resolver(conn)lines 245–249rows = [ row for src, payload in run_harvest(conn, repo_root, includes_harvester(), cache) for row in _rows(resolver, src, names.get(src, ""), payload) ]lines 250–250conn.executemany(_INSERT, rows)lines 251–251conn.commit()lines 254–254resolved = sum(1 for r in rows if r[1] is not None)lines 255–255logger.info("includes: %d directive(s), %d resolved to an indexed file", len(rows), resolved)lines 256–256return len(rows)

Requirements

REQ-DDB-INDEX-010

includes_harvester

Harvester clew.ast_includes.includes_harvester()

The include stage's harvester.

clew/ast_includes.py:82

Source · 5 lines
def includes_harvester() -> Harvester:
    """ONE CONSTRUCTION SITE, shared with the plan's parse pass. @brief Build it. @return It."""
    return _IncludesHarvester()

Activity · 1 steps
lines 84–84return _IncludesHarvester()

Requirements

REQ-DDB-INDEX-010

refresh_ast_includes

int clew.ast_includes.refresh_ast_includes(sqlite3.Connection conn, Path repo_root, IndexCache cache, dict[str, int] files)

Rewrite the edited files' #include rows (the fast tier).

clew/ast_includes.py:203

Show on the map →

Called by _apply

Calls _harvest_one_file, _resolver, _rows, includes_harvester

Source · 27 lines
def refresh_ast_includes(
    conn: sqlite3.Connection, repo_root: Path, cache: IndexCache, files: dict[str, int]
) -> int:
    """EXACT, NOT APPROXIMATE (T3 served, 2.0.0). The fast tier runs only when the file set is
    unchanged, so every spec resolves against the same paths a full build would see; only the
    edited files' own directives can differ, and those are re-read here. NOT
    `ensure_ast_includes_table`: its `executescript` would COMMIT mid-transaction, and an index
    without the table never ran the layer.

    @brief Refresh edited files' includes.
    @return Rows written.
    """
    from .harvest import HarvestTally, _harvest_one_file

    if conn.execute("SELECT 1 FROM sqlite_master WHERE name = 'ast_includes'").fetchone() is None:
        return 0
    resolver, _names = _resolver(conn)
    written = 0
    for rel, rowid in files.items():
        conn.execute("DELETE FROM ast_includes WHERE src_id = ?", (rowid,))
        payload = _harvest_one_file(
            rel, repo_root / rel, includes_harvester(), {}, cache, HarvestTally()
        )
        written += conn.executemany(_INSERT, _rows(resolver, rowid, rel, payload)).rowcount
    return written

Activity · 10 steps
lines 215–215from .harvest import HarvestTally, _harvest_one_filelines 217–217◇ if conn.execute("SELECT 1 FROM sqlite_master WHERE name = 'ast_includes'").fetchone() is Nonelines 218–218return 0lines 219–219resolver, _names = _resolver(conn)lines 220–220written = 0lines 221–221◇ for rel, rowid in files.items()lines 222–222conn.execute("DELETE FROM ast_includes WHERE src_id = ?", (rowid,))lines 223–225payload = _harvest_one_file( rel, repo_root / rel, includes_harvester(), {}, cache, HarvestTally() )lines 226–226written += conn.executemany(_INSERT, _rows(resolver, rowid, rel, payload)).rowcountlines 227–227return written

Requirements

REQ-DDB-INDEX-010

resolve

int | None clew.ast_includes.IncludeResolver.resolve(self, str spec, bool quoted, str includer)

Resolve one spec from one including file.

clew/ast_includes.py:136

Show on the map →

Called by none

Calls none

Source · 10 lines
    def resolve(self, spec: str, quoted: bool, includer: str) -> int | None:
        """@brief Resolve a spec. @return Rowid or None."""
        if quoted:
            beside = posixpath.normpath(posixpath.join(posixpath.dirname(includer), spec))
            if beside in self.by_name:
                return self.by_name[beside]
        candidates = self.by_suffix.get(posixpath.normpath(spec), [])
        return candidates[0] if len(candidates) == 1 else None

Activity · 6 steps
lines 138–138◇ if quotedlines 139–139beside = posixpath.normpath(posixpath.join(posixpath.dirname(includer), spec))lines 140–140◇ if beside in self.by_namelines 141–141return self.by_name[beside]lines 142–142candidates = self.by_suffix.get(posixpath.normpath(spec), [])lines 143–143return candidates[0] if len(candidates) == 1 else None

Requirements

REQ-DDB-INDEX-010