|
| 1 | +import logging |
| 2 | +from pathlib import Path |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +import tree_sitter_rust as tsrust |
| 6 | +from tree_sitter import Language, Parser |
| 7 | + |
| 8 | +def get_c_sourcefile(compile_commands, rustfile: Path) -> Path | None: |
| 9 | + c_file_guesses = [rustfile.with_suffix(".c"), rustfile.with_suffix(".C")] |
| 10 | + |
| 11 | + files = [Path(d["file"]) for d in compile_commands] |
| 12 | + |
| 13 | + for guess in c_file_guesses: |
| 14 | + if guess in files: |
| 15 | + return guess |
| 16 | + |
| 17 | + return None |
| 18 | + |
| 19 | + |
| 20 | +def get_rust_function_spans(rustfile: Path) -> list[dict[str, Any]]: |
| 21 | + LANGUAGE = Language(tsrust.language()) |
| 22 | + parser = Parser(LANGUAGE) |
| 23 | + |
| 24 | + if not rustfile.exists(): |
| 25 | + raise FileNotFoundError(f"{rustfile} does not exist") |
| 26 | + if not rustfile.is_file(): |
| 27 | + raise NotADirectoryError(f"{rustfile} is not a file") |
| 28 | + |
| 29 | + try: |
| 30 | + with open(rustfile, "rb") as rust_source: |
| 31 | + source_bytes = rust_source.read() |
| 32 | + except OSError as exc: |
| 33 | + logging.error(f"Failed to read Rust file {rustfile}: {exc}") |
| 34 | + return [] |
| 35 | + |
| 36 | + tree = parser.parse(source_bytes) |
| 37 | + |
| 38 | + functions = [] |
| 39 | + |
| 40 | + for node in tree.root_node.children: |
| 41 | + if node.type == 'function_item': |
| 42 | + name_node = node.child_by_field_name('name') |
| 43 | + func_name = (source_bytes[ |
| 44 | + name_node.start_byte: # type: ignore |
| 45 | + name_node.end_byte # type: ignore |
| 46 | + ].decode('utf-8')) |
| 47 | + |
| 48 | + functions.append({ |
| 49 | + "name": func_name, |
| 50 | + "start_line": node.start_point[0] + 1, # 0-indexed |
| 51 | + "end_line": node.end_point[0] + 1, # 0-indexed |
| 52 | + "start_byte": node.start_byte, |
| 53 | + "end_byte": node.end_byte |
| 54 | + }) |
| 55 | + |
| 56 | + return functions |
| 57 | + |
| 58 | + |
| 59 | +def get_c_functions_spans(compile_commands, c_file: Path): |
| 60 | + from .clang import get_c_ast_as_json, get_functions_from_clang_ast |
| 61 | + cmd = (c for c in compile_commands if c["file"] == str(c_file)) |
| 62 | + entry = next(cmd, None) |
| 63 | + |
| 64 | + assert entry is not None, f"No compile command entry for {c_file}" |
| 65 | + |
| 66 | + c_fn_asts = get_functions_from_clang_ast(get_c_ast_as_json(entry)) |
| 67 | + |
| 68 | + functions = [] |
| 69 | + for fn in c_fn_asts: |
| 70 | + loc = fn["loc"] |
| 71 | + if "line" in loc and "col" in loc and "file" in loc: |
| 72 | + functions.append({ |
| 73 | + "name": fn["name"], |
| 74 | + "start_line": loc["line"], |
| 75 | + "start_byte": fn["range"]["begin"]["offset"], |
| 76 | + "end_line": fn["range"]["end"]["line"], |
| 77 | + "end_byte": fn["range"]["end"]["offset"], |
| 78 | + }) |
| 79 | + |
| 80 | + |
0 commit comments