|
| 1 | +import os |
| 2 | + |
| 3 | +import lark |
| 4 | + |
| 5 | + |
| 6 | +class LinkerScriptParser: |
| 7 | + def __init__(self, linker_script_content: str) -> None: |
| 8 | + self.linker_script_content = linker_script_content |
| 9 | + self.ast = self._parse() |
| 10 | + |
| 11 | + @staticmethod |
| 12 | + def from_file(linker_script_path: str): |
| 13 | + with open(linker_script_path) as f: |
| 14 | + return LinkerScriptParser(f.read()) |
| 15 | + |
| 16 | + @staticmethod |
| 17 | + def from_string(linker_script_content: str): |
| 18 | + return LinkerScriptParser(linker_script_content) |
| 19 | + |
| 20 | + def _parse(self): |
| 21 | + with open(os.path.join(os.path.dirname(__file__), "linker_script.lark")) as f: |
| 22 | + parser = lark.Lark(f.read()) |
| 23 | + return parser.parse(self.linker_script_content) |
| 24 | + |
| 25 | + def _get_ast_data(self, tree, name): |
| 26 | + node = next(tree.find_data(name), None) |
| 27 | + return node.children[0].value if node else None |
| 28 | + |
| 29 | + def get_memory_regions(self): |
| 30 | + memory_regions = [] |
| 31 | + for mem_def in self.ast.find_data("memory_def"): |
| 32 | + memory_regions.append( |
| 33 | + { |
| 34 | + "name": self._get_ast_data(mem_def, "memory_name"), |
| 35 | + "attr": self._get_ast_data(mem_def, "memory_attr"), |
| 36 | + "origin": self._get_ast_data(mem_def, "memory_origin"), |
| 37 | + "length": self._get_ast_data(mem_def, "memory_length"), |
| 38 | + } |
| 39 | + ) |
| 40 | + return memory_regions |
| 41 | + |
| 42 | + def get_sections(self): |
| 43 | + sections = [] |
| 44 | + for section_def in self.ast.find_data("section_def"): |
| 45 | + sections.append( |
| 46 | + { |
| 47 | + "name": self._get_ast_data(section_def, "section_name"), |
| 48 | + "addr": self._get_ast_data(section_def, "section_addr"), |
| 49 | + "region": self._get_ast_data(section_def, "section_region"), |
| 50 | + "lma_region": self._get_ast_data(section_def, "section_lma_region"), |
| 51 | + } |
| 52 | + ) |
| 53 | + return sections |
0 commit comments