| 13 | |
| 14 | |
| 15 | class CSharpCodeParser: |
| 16 | _parser: tree_sitter.Parser |
| 17 | _config: Dict |
| 18 | |
| 19 | def __init__(self, config: Dict) -> None: |
| 20 | self._config = config |
| 21 | self.initialize() |
| 22 | |
| 23 | self._parser = tree_sitter.Parser() |
| 24 | self._parser.set_language(tree_sitter.Language(self._c_sharp_library_path(), "c_sharp")) |
| 25 | |
| 26 | @classmethod |
| 27 | def initialize(cls) -> None: |
| 28 | c_sharp_library_path = cls._c_sharp_library_path() |
| 29 | if not os.path.exists(c_sharp_library_path): |
| 30 | c_sharp_library_folder_path = os.path.dirname(c_sharp_library_path) |
| 31 | log.debug(f"C# library not found at '{c_sharp_library_path}', building...") |
| 32 | |
| 33 | tree_sitter_csharp_folder_path = os.path.join(unifree.project_root, 'vendor', 'tree-sitter-c-sharp') |
| 34 | if not os.path.exists(tree_sitter_csharp_folder_path): |
| 35 | log.error(f"CSharp implementation of the tree sitter is not found at {tree_sitter_csharp_folder_path}") |
| 36 | raise RuntimeError(f"CSharp tree sitter not found in {tree_sitter_csharp_folder_path}") |
| 37 | |
| 38 | os.makedirs(c_sharp_library_folder_path, exist_ok=True) |
| 39 | tree_sitter.Language.build_library(c_sharp_library_path, [tree_sitter_csharp_folder_path]) |
| 40 | |
| 41 | def parse(self, file_path: str) -> tree_sitter.Tree: |
| 42 | if not os.path.exists(file_path) or not os.path.isfile(file_path): |
| 43 | raise RuntimeError(f"File {file_path} does not exist") |
| 44 | |
| 45 | with open(file_path, 'r') as source_file: |
| 46 | source_str = source_file.read() |
| 47 | if len(source_str) < 1: |
| 48 | raise RuntimeError(f"File {file_path} is empty") |
| 49 | |
| 50 | if self._config["source"]["csharp"]["convert_macros_to_comments"]: |
| 51 | source_str = self._replace_macros_with_comments(source_str) |
| 52 | |
| 53 | source_bytes = bytes(source_str, "utf8") |
| 54 | |
| 55 | try: |
| 56 | |
| 57 | result: tree_sitter.Tree = self._parser.parse(source_bytes) |
| 58 | if result.root_node: |
| 59 | return result |
| 60 | else: |
| 61 | raise RuntimeError(f"Failed to parse '{file_path}': no root node found") |
| 62 | |
| 63 | except Exception as ex: |
| 64 | raise RuntimeError(f"Failed to parse '{file_path}': threw exception while parsing", ex) |
| 65 | |
| 66 | @classmethod |
| 67 | def _c_sharp_library_path(cls) -> str: |
| 68 | c_sharp_library_folder_path = os.path.join(unifree.project_root, 'vendor', 'build', 'libraries') |
| 69 | return os.path.join(c_sharp_library_folder_path, 'c-sharp.so') |
| 70 | |
| 71 | def _replace_macros_with_comments(self, source_str): |
| 72 | result = '' |