Created
May 19, 2026 12:09
-
-
Save LukasWoodtli/fd44927b1e7a98fbaf2f265e7d59928e to your computer and use it in GitHub Desktop.
Parse Rust source from Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| # Inspired by https://stackoverflow.com/a | |
| # Posted by s-m-e | |
| # Retrieved 2025-12-04, License - CC BY-SA 4.0 | |
| # | |
| # Extended by L. Woodtli | |
| import os | |
| import sys | |
| from pathlib import Path | |
| import tree_sitter_rust as tsrust | |
| from tree_sitter import Language, Parser | |
| def get_struct_name(node): | |
| struct_name = [n.text for n in node.children if n.type == 'type_identifier'] | |
| assert len(struct_name) == 1 | |
| return f"Struct name: {struct_name[0]}" | |
| def get_function_name(node): | |
| function_name = [n.text for n in node.children if n.type == 'identifier'] | |
| assert len(function_name) == 1 | |
| return f"Function: {function_name[0]}" | |
| def get_struct_and_function_names(node): | |
| items = [] | |
| for node in node.root_node.children: | |
| if node.type == 'struct_item': | |
| n = get_struct_name(node) | |
| items.append(n) | |
| elif node.type == 'function_item': | |
| n = get_function_name(node) | |
| items.append(n) | |
| return items | |
| def parse_rust_files(dir): | |
| output = "" | |
| for dir_path, _dir_names, file_names in os.walk(dir): | |
| if 'target' in dir_path: | |
| continue | |
| for file_name in file_names: | |
| if file_name.endswith(".rs"): | |
| file_path = os.path.join(dir_path, file_name) | |
| with open(file_path, mode = "rb") as f: | |
| raw = f.read() | |
| parser = Parser(Language(tsrust.language())) | |
| tree = parser.parse(raw) | |
| output += f"File: {file_path}\n" | |
| names = get_struct_and_function_names(tree) | |
| output += "\n".join(names) | |
| output += "\n\n" | |
| return output | |
| if __name__ == "__main__": | |
| dir = sys.argv[1] | |
| print(parse_rust_files(dir)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment