|
| 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 | + |
| 9 | +def get_c_sourcefile(compile_commands, rustfile: Path) -> Path | None: |
| 10 | + c_file_guesses = [rustfile.with_suffix(".c"), rustfile.with_suffix(".C")] |
| 11 | + |
| 12 | + files = [Path(d["file"]) for d in compile_commands] |
| 13 | + |
| 14 | + for guess in c_file_guesses: |
| 15 | + if guess in files: |
| 16 | + return guess |
| 17 | + |
| 18 | + return None |
| 19 | + |
| 20 | + |
| 21 | +def get_rust_function_spans(rustfile: Path) -> list[dict[str, Any]]: |
| 22 | + LANGUAGE = Language(tsrust.language()) |
| 23 | + parser = Parser(LANGUAGE) |
| 24 | + |
| 25 | + if not rustfile.exists(): |
| 26 | + raise FileNotFoundError(f"{rustfile} does not exist") |
| 27 | + if not rustfile.is_file(): |
| 28 | + raise NotADirectoryError(f"{rustfile} is not a file") |
| 29 | + |
| 30 | + try: |
| 31 | + with open(rustfile, "rb") as rust_source: |
| 32 | + source_bytes = rust_source.read() |
| 33 | + except OSError as exc: |
| 34 | + logging.error(f"Failed to read Rust file {rustfile}: {exc}") |
| 35 | + return [] |
| 36 | + |
| 37 | + tree = parser.parse(source_bytes) |
| 38 | + |
| 39 | + functions = [] |
| 40 | + |
| 41 | + for node in tree.root_node.children: |
| 42 | + if node.type == 'function_item': |
| 43 | + name_node = node.child_by_field_name('name') |
| 44 | + func_name = (source_bytes[ |
| 45 | + name_node.start_byte: # type: ignore |
| 46 | + name_node.end_byte # type: ignore |
| 47 | + ].decode('utf-8')) |
| 48 | + |
| 49 | + functions.append({ |
| 50 | + "name": func_name, |
| 51 | + "start_line": node.start_point[0] + 1, # 0-indexed |
| 52 | + "end_line": node.end_point[0] + 1, # 0-indexed |
| 53 | + "start_byte": node.start_byte, |
| 54 | + "end_byte": node.end_byte |
| 55 | + }) |
| 56 | + |
| 57 | + return functions |
| 58 | + |
| 59 | + |
| 60 | +def get_c_functions_spans(compile_commands: dict[str, Any], c_file: Path): |
| 61 | + from .clang import get_c_ast_as_json, get_functions_from_clang_ast |
| 62 | + cmd = (c for c in compile_commands if c["file"] == str(c_file)) |
| 63 | + entry = next(cmd, None) |
| 64 | + |
| 65 | + assert entry is not None, f"No compile command entry for {c_file}" |
| 66 | + |
| 67 | + c_fn_asts = get_functions_from_clang_ast(get_c_ast_as_json(entry)) |
| 68 | + |
| 69 | + # print(json.dumps(c_fn_asts, indent=4)) |
| 70 | + |
| 71 | + functions = [] |
| 72 | + for fn in c_fn_asts: |
| 73 | + loc = fn["loc"] |
| 74 | + if "line" in loc and "col" in loc: |
| 75 | + functions.append({ |
| 76 | + "name": fn["name"], |
| 77 | + "start_line": loc["line"], |
| 78 | + "start_byte": fn["range"]["begin"]["offset"], |
| 79 | + "end_line": fn["range"]["end"]["line"], |
| 80 | + "end_byte": fn["range"]["end"]["offset"], |
| 81 | + }) |
| 82 | + |
| 83 | + return functions |
| 84 | + |
| 85 | + |
| 86 | +def get_function_span_pairs(compile_commands: dict[str, Any], rustfile: Path) -> list[tuple[dict[str, Any], dict[str, Any]]]: |
| 87 | + """Get pairs of Rust and C function spans for the given Rust file.""" |
| 88 | + |
| 89 | + rust_fn_spans = get_rust_function_spans(rustfile) |
| 90 | + c_file = get_c_sourcefile(compile_commands, rustfile) |
| 91 | + if not c_file: |
| 92 | + raise FileNotFoundError(f"No corresponding C source file found for {rustfile}") |
| 93 | + |
| 94 | + c_fn_spans = get_c_functions_spans(compile_commands, c_file) |
| 95 | + |
| 96 | + # TODO: handle cases where ordering or counts differ |
| 97 | + # A reasonable assumption is that we can still pair functions by name |
| 98 | + # which means that this tool needs to run fairly soon after transpilation |
| 99 | + assert len(c_fn_spans) == len(rust_fn_spans), "Mismatched number of functions between Rust and C source files" |
| 100 | + for rust_fn, c_fn in zip(rust_fn_spans, c_fn_spans): |
| 101 | + assert rust_fn['name'] == c_fn['name'] |
| 102 | + rust_fn['file'] = rustfile |
| 103 | + c_fn['file'] = c_file |
| 104 | + |
| 105 | + return list(zip(rust_fn_spans, c_fn_spans)) |
0 commit comments