another small update to error reporting

This commit is contained in:
IgorCielniak
2026-01-09 12:33:55 +01:00
parent 95f6c1dac5
commit 315ad9ef77

41
main.py
View File

@@ -37,6 +37,10 @@ class CompileError(Exception):
"""Raised when IR cannot be turned into assembly.""" """Raised when IR cannot be turned into assembly."""
class CompileTimeError(ParseError):
"""Raised when a compile-time word fails with context."""
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# Tokenizer / Reader # Tokenizer / Reader
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -447,6 +451,7 @@ class Parser:
self.custom_prelude = None self.custom_prelude = None
self.custom_bss = None self.custom_bss = None
try:
while not self._eof(): while not self._eof():
token = self._consume() token = self._consume()
self._last_token = token self._last_token = token
@@ -498,6 +503,15 @@ class Parser:
if self._maybe_expand_macro(token): if self._maybe_expand_macro(token):
continue continue
self._handle_token(token) self._handle_token(token)
except ParseError:
raise
except Exception as exc:
tok = self._last_token
if tok is None:
raise ParseError(f"unexpected error during parse: {exc}") from None
raise ParseError(
f"unexpected error near '{tok.lexeme}' at {tok.line}:{tok.column}: {exc}"
) from None
if self.macro_recording is not None: if self.macro_recording is not None:
raise ParseError("unterminated macro definition (missing ';')") raise ParseError("unterminated macro definition (missing ';')")
@@ -654,10 +668,12 @@ class Parser:
def _execute_immediate_word(self, word: Word) -> None: def _execute_immediate_word(self, word: Word) -> None:
try: try:
self.compile_time_vm.invoke(word) self.compile_time_vm.invoke(word)
except CompileTimeError:
raise
except ParseError: except ParseError:
raise raise
except Exception as exc: # pragma: no cover - defensive except Exception as exc: # pragma: no cover - defensive
raise ParseError(f"compile-time word '{word.name}' failed: {exc}") from exc raise CompileTimeError(f"compile-time word '{word.name}' failed: {exc}") from None
def _handle_macro_recording(self, token: Token) -> bool: def _handle_macro_recording(self, token: Token) -> bool:
if self.macro_recording is None: if self.macro_recording is None:
@@ -981,12 +997,14 @@ class CompileTimeVM:
self.return_stack: List[Any] = [] self.return_stack: List[Any] = []
self.loop_stack: List[Dict[str, Any]] = [] self.loop_stack: List[Dict[str, Any]] = []
self._handles = _CTHandleTable() self._handles = _CTHandleTable()
self.call_stack: List[str] = []
def reset(self) -> None: def reset(self) -> None:
self.stack.clear() self.stack.clear()
self.return_stack.clear() self.return_stack.clear()
self.loop_stack.clear() self.loop_stack.clear()
self._handles.clear() self._handles.clear()
self.call_stack.clear()
def push(self, value: Any) -> None: def push(self, value: Any) -> None:
self.stack.append(value) self.stack.append(value)
@@ -1057,6 +1075,8 @@ class CompileTimeVM:
self._call_word(word) self._call_word(word)
def _call_word(self, word: Word) -> None: def _call_word(self, word: Word) -> None:
self.call_stack.append(word.name)
try:
definition = word.definition definition = word.definition
prefer_definition = word.compile_time_override or (isinstance(definition, Definition) and (word.immediate or word.compile_only)) prefer_definition = word.compile_time_override or (isinstance(definition, Definition) and (word.immediate or word.compile_only))
if not prefer_definition and word.compile_time_intrinsic is not None: if not prefer_definition and word.compile_time_intrinsic is not None:
@@ -1068,6 +1088,16 @@ class CompileTimeVM:
self._run_asm_definition(word) self._run_asm_definition(word)
return return
self._execute_nodes(definition.body) self._execute_nodes(definition.body)
except CompileTimeError:
raise
except ParseError as exc:
raise CompileTimeError(f"{exc}\ncompile-time stack: {' -> '.join(self.call_stack)}") from None
except Exception as exc:
raise CompileTimeError(
f"compile-time failure in '{word.name}': {exc}\ncompile-time stack: {' -> '.join(self.call_stack)}"
) from None
finally:
self.call_stack.pop()
def _run_asm_definition(self, word: Word) -> None: def _run_asm_definition(self, word: Word) -> None:
definition = word.definition definition = word.definition
@@ -1895,7 +1925,7 @@ class Assembler:
builder.emit(" mov [r12], rax") builder.emit(" mov [r12], rax")
return return
raise CompileError(f"unsupported op {node!r}") raise CompileError(f"unsupported op {node!r}{ctx()}")
def _emit_wordref(self, name: str, builder: FunctionEmitter) -> None: def _emit_wordref(self, name: str, builder: FunctionEmitter) -> None:
word = self.dictionary.lookup(name) word = self.dictionary.lookup(name)
@@ -3302,7 +3332,14 @@ def cli(argv: Sequence[str]) -> int:
parser.error("the following arguments are required: source") parser.error("the following arguments are required: source")
compiler = Compiler(include_paths=[Path("."), Path("./stdlib"), *args.include_paths]) compiler = Compiler(include_paths=[Path("."), Path("./stdlib"), *args.include_paths])
try:
emission = compiler.compile_file(args.source) emission = compiler.compile_file(args.source)
except (ParseError, CompileError, CompileTimeError) as exc:
print(f"[error] {exc}")
return 1
except Exception as exc:
print(f"[error] unexpected failure: {exc}")
return 1
args.temp_dir.mkdir(parents=True, exist_ok=True) args.temp_dir.mkdir(parents=True, exist_ok=True)
asm_path = args.temp_dir / (args.source.stem + ".asm") asm_path = args.temp_dir / (args.source.stem + ".asm")