diff --git a/README.md b/README.md index 622f774..9f24fb2 100644 --- a/README.md +++ b/README.md @@ -5,3 +5,5 @@ ### a nut #### a nut + +test \ No newline at end of file diff --git a/chipnut/commands/compiler.py b/chipnut/commands/compiler.py index ed448d7..601f562 100644 --- a/chipnut/commands/compiler.py +++ b/chipnut/commands/compiler.py @@ -19,6 +19,76 @@ class CompileContext: entry_path: Path output_name: str +class BuildError(Exception): + pass + +class AstParser: + def __init__(self, file: Path): + self.file = self.read_file(file) + self.labels = [] + + def read_file(self, file: Path) -> str: + with file.open("r") as f: + return f.read() + + def parse_labels(self): + self.labels = [] + current_label = None + current_sub_label = None + + for line in self.file.splitlines(): + stripped_line = line.strip() + + if stripped_line.endswith(":"): + label_name = stripped_line[:-1].strip() + if not label_name: + continue + + if label_name.startswith("."): + if current_label is None: + raise BuildError(f"Sub-label '{label_name}:' found before any parent label.") + + sub_label_name = label_name[1:].strip() + if not sub_label_name: + continue + + current_sub_label = { + "name": sub_label_name, + "lines": [], + } + current_label["sub_labels"].append(current_sub_label) + continue + + if current_label is not None: + self.labels.append(current_label) + + current_label = { + "name": label_name, + "lines": [], + "sub_labels": [], + } + current_sub_label = None + continue + + if current_label is None: + continue + + if stripped_line == "": + continue + + if current_sub_label is not None: + current_sub_label["lines"].append(stripped_line) + else: + current_label["lines"].append(stripped_line) + + if current_label is not None: + self.labels.append(current_label) + + return self.labels + + def parse(self): + return self.parse_labels() + class Compiler: def __init__(self, context: CompileContext):