|
| 1 | +"""Parse Python API invocations for staged kernel versions with Tree-sitter. |
| 2 | +
|
| 3 | +The parser builds an import alias map for each file and keeps only calls whose |
| 4 | +root name resolves to an imported module. A call such as `np.mean(x)` after |
| 5 | +`import numpy as np` becomes the qualified name `numpy.mean`, while calls to |
| 6 | +local functions and methods on local variables are excluded. Tree-sitter |
| 7 | +tolerates broken code blocks, so partial notebooks still yield calls from the |
| 8 | +cells that parse. |
| 9 | +
|
| 10 | +Outputs, written to the stage directory: |
| 11 | +- `nodes_api_call.parquet` with the qualified call name as `Id` and the |
| 12 | + top-level library as `Library`. |
| 13 | +- `edges_kernel_version_calls_api_call.parquet` linking kernel versions to the |
| 14 | + API calls they make. |
| 15 | +- `edges_api_call_in_library.parquet` linking API calls to staged libraries. |
| 16 | +
|
| 17 | +Run `parse_imports.py` first; the library edge endpoints are validated against |
| 18 | +`nodes_library.parquet` so no staged edge points to a missing library node. |
| 19 | +""" |
| 20 | + |
| 21 | +from __future__ import annotations |
| 22 | + |
| 23 | +import argparse |
| 24 | +from pathlib import Path |
| 25 | +from typing import Iterator |
| 26 | + |
| 27 | +import polars as pl |
| 28 | +import tree_sitter_python |
| 29 | +from tree_sitter import Language, Node, Parser |
| 30 | + |
| 31 | +from parse_imports import ( |
| 32 | + DEFAULT_CODE_DIR, |
| 33 | + DEFAULT_STAGE_DIR, |
| 34 | + candidate_paths, |
| 35 | + code_text, |
| 36 | + load_kernel_version_ids, |
| 37 | +) |
| 38 | + |
| 39 | +PYTHON_SUFFIXES = {".py", ".ipynb"} |
| 40 | + |
| 41 | +_PARSER = Parser(Language(tree_sitter_python.language())) |
| 42 | + |
| 43 | + |
| 44 | +def parse_args() -> argparse.Namespace: |
| 45 | + parser = argparse.ArgumentParser(description=__doc__) |
| 46 | + parser.add_argument("--code-dir", type=Path, default=DEFAULT_CODE_DIR) |
| 47 | + parser.add_argument("--stage-dir", type=Path, default=DEFAULT_STAGE_DIR) |
| 48 | + return parser.parse_args() |
| 49 | + |
| 50 | + |
| 51 | +def _text(node: Node) -> str: |
| 52 | + return (node.text or b"").decode("utf-8", errors="ignore") |
| 53 | + |
| 54 | + |
| 55 | +def _walk(root: Node) -> Iterator[Node]: |
| 56 | + stack = [root] |
| 57 | + while stack: |
| 58 | + node = stack.pop() |
| 59 | + yield node |
| 60 | + stack.extend(node.named_children) |
| 61 | + |
| 62 | + |
| 63 | +def _aliased_import_parts(node: Node) -> tuple[str, str] | None: |
| 64 | + """Return (alias, name) for an `aliased_import` node, or None if malformed.""" |
| 65 | + name = node.child_by_field_name("name") |
| 66 | + alias = node.child_by_field_name("alias") |
| 67 | + if name is None or alias is None: |
| 68 | + return None |
| 69 | + return _text(alias), _text(name) |
| 70 | + |
| 71 | + |
| 72 | +def _collect_import_statement(node: Node, aliases: dict[str, str]) -> None: |
| 73 | + for child in node.named_children: |
| 74 | + if child.type == "dotted_name": |
| 75 | + top = _text(child).split(".", maxsplit=1)[0] |
| 76 | + aliases[top] = top |
| 77 | + elif child.type == "aliased_import": |
| 78 | + parts = _aliased_import_parts(child) |
| 79 | + if parts is not None: |
| 80 | + aliases[parts[0]] = parts[1] |
| 81 | + |
| 82 | + |
| 83 | +def _collect_import_from_statement(node: Node, aliases: dict[str, str]) -> None: |
| 84 | + module = node.child_by_field_name("module_name") |
| 85 | + if module is None or module.type != "dotted_name": |
| 86 | + return |
| 87 | + module_name = _text(module) |
| 88 | + for child in node.named_children: |
| 89 | + if child.id == module.id: |
| 90 | + continue |
| 91 | + if child.type == "dotted_name": |
| 92 | + aliases[_text(child)] = f"{module_name}.{_text(child)}" |
| 93 | + elif child.type == "aliased_import": |
| 94 | + parts = _aliased_import_parts(child) |
| 95 | + if parts is not None: |
| 96 | + aliases[parts[0]] = f"{module_name}.{parts[1]}" |
| 97 | + |
| 98 | + |
| 99 | +def _aliases_from_root(root: Node) -> dict[str, str]: |
| 100 | + aliases: dict[str, str] = {} |
| 101 | + for node in _walk(root): |
| 102 | + if node.type == "import_statement": |
| 103 | + _collect_import_statement(node, aliases) |
| 104 | + elif node.type == "import_from_statement": |
| 105 | + _collect_import_from_statement(node, aliases) |
| 106 | + return aliases |
| 107 | + |
| 108 | + |
| 109 | +def import_aliases(text: str) -> dict[str, str]: |
| 110 | + """Map each locally bound import name to the qualified name it stands for.""" |
| 111 | + tree = _PARSER.parse(text.encode("utf-8")) |
| 112 | + return _aliases_from_root(tree.root_node) |
| 113 | + |
| 114 | + |
| 115 | +def _call_chain(node: Node | None) -> list[str] | None: |
| 116 | + """Return the dotted name chain of a call target, or None if it is not one.""" |
| 117 | + if node is None: |
| 118 | + return None |
| 119 | + if node.type == "identifier": |
| 120 | + return [_text(node)] |
| 121 | + if node.type == "attribute": |
| 122 | + base = _call_chain(node.child_by_field_name("object")) |
| 123 | + attribute = node.child_by_field_name("attribute") |
| 124 | + if base is None or attribute is None: |
| 125 | + return None |
| 126 | + return [*base, _text(attribute)] |
| 127 | + return None |
| 128 | + |
| 129 | + |
| 130 | +def api_calls(text: str) -> set[str]: |
| 131 | + """Return the qualified names of calls that resolve to an imported module.""" |
| 132 | + tree = _PARSER.parse(text.encode("utf-8")) |
| 133 | + root = tree.root_node |
| 134 | + aliases = _aliases_from_root(root) |
| 135 | + calls: set[str] = set() |
| 136 | + for node in _walk(root): |
| 137 | + if node.type != "call": |
| 138 | + continue |
| 139 | + chain = _call_chain(node.child_by_field_name("function")) |
| 140 | + if not chain: |
| 141 | + continue |
| 142 | + head, *rest = chain |
| 143 | + if head not in aliases: |
| 144 | + continue |
| 145 | + calls.add(".".join([aliases[head], *rest])) |
| 146 | + return calls |
| 147 | + |
| 148 | + |
| 149 | +def library_of(qualified_name: str) -> str: |
| 150 | + """Return the lowercased top-level library of a qualified call name.""" |
| 151 | + return qualified_name.split(".", maxsplit=1)[0].lower() |
| 152 | + |
| 153 | + |
| 154 | +def load_staged_library_ids(stage_dir: Path) -> set[str]: |
| 155 | + path = stage_dir / "nodes_library.parquet" |
| 156 | + if not path.exists(): |
| 157 | + raise SystemExit(f"missing {path} (run `parse_imports.py` on this stage directory first)") |
| 158 | + return set(pl.read_parquet(path, columns=["Id"])["Id"].cast(pl.Utf8)) |
| 159 | + |
| 160 | + |
| 161 | +def main() -> None: |
| 162 | + args = parse_args() |
| 163 | + wanted_ids = load_kernel_version_ids(args.stage_dir) |
| 164 | + staged_libraries = load_staged_library_ids(args.stage_dir) |
| 165 | + rows: list[tuple[str, str]] = [] |
| 166 | + |
| 167 | + for kernel_version_id in sorted(wanted_ids, key=int): |
| 168 | + for path in candidate_paths(args.code_dir, kernel_version_id): |
| 169 | + if path.suffix.lower() not in PYTHON_SUFFIXES or not path.exists(): |
| 170 | + continue |
| 171 | + try: |
| 172 | + text = code_text(path) |
| 173 | + except OSError: |
| 174 | + continue |
| 175 | + for call in api_calls(text): |
| 176 | + rows.append((kernel_version_id, call)) |
| 177 | + |
| 178 | + calls = pl.DataFrame( |
| 179 | + rows, |
| 180 | + schema={"KernelVersionId": pl.Utf8, "ApiCall": pl.Utf8}, |
| 181 | + orient="row", |
| 182 | + ) |
| 183 | + calls = calls.unique().sort(["KernelVersionId", "ApiCall"]) |
| 184 | + |
| 185 | + nodes = ( |
| 186 | + calls.select(pl.col("ApiCall").alias("Id")) |
| 187 | + .unique() |
| 188 | + .with_columns(pl.col("Id").map_elements(library_of, return_dtype=pl.Utf8).alias("Library")) |
| 189 | + .sort("Id") |
| 190 | + ) |
| 191 | + nodes.write_parquet(args.stage_dir / "nodes_api_call.parquet") |
| 192 | + |
| 193 | + calls.rename( |
| 194 | + {"KernelVersionId": "from_kernel_version_id", "ApiCall": "to_api_call_id"} |
| 195 | + ).write_parquet(args.stage_dir / "edges_kernel_version_calls_api_call.parquet") |
| 196 | + |
| 197 | + in_library = ( |
| 198 | + nodes.filter(pl.col("Library").is_in(sorted(staged_libraries))) |
| 199 | + .select( |
| 200 | + pl.col("Id").alias("from_api_call_id"), |
| 201 | + pl.col("Library").alias("to_library_id"), |
| 202 | + ) |
| 203 | + .sort("from_api_call_id") |
| 204 | + ) |
| 205 | + in_library.write_parquet(args.stage_dir / "edges_api_call_in_library.parquet") |
| 206 | + |
| 207 | + print( |
| 208 | + f"Wrote {nodes.height} API call nodes, {calls.height} call edges, " |
| 209 | + f"and {in_library.height} library edges" |
| 210 | + ) |
| 211 | + |
| 212 | + |
| 213 | +if __name__ == "__main__": |
| 214 | + main() |
0 commit comments