Add AstParser class for label parsing and error handling
This commit is contained in:
parent
2300c37fde
commit
ca88d40ae2
@ -19,6 +19,76 @@ class CompileContext:
|
|||||||
entry_path: Path
|
entry_path: Path
|
||||||
output_name: str
|
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:
|
class Compiler:
|
||||||
def __init__(self, context: CompileContext):
|
def __init__(self, context: CompileContext):
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user