Lesson 6 of 9 · 21m
Runtime Errors and Debuggability
Make failures useful: stack traces, source spans, error taxonomy, and the interpreter instrumentation users will thank you for.
A language implementation can be correct and still be unusable. The difference is what happens when a program fails. If users see TypeError: unsupported operand from your host Python process, you have not built a language; you have built a leakage layer over one.
One error type for language failures
class LangError(Exception):
def __init__(self, message, span, kind="runtime"):
super().__init__(message)
self.message = message
self.span = span
self.kind = kind
self.frames = []Use it for user-program failures. Host exceptions escaping to the top are implementation bugs. Do not wrap them in friendly language errors — detect them with assertions and fix them.
Errors need locations and frames
Push a frame when entering a function, pop it when leaving, and attach the active chain when an error escapes:
error: undefined variable 'reult'
--> examples/report.lang:18:14
|
18 | total = total + reult
| ^^^^^
|
note: called from compute_totals at examples/report.lang:11:5This is not polish. Error quality is part of the language. A precise span beats a clever rewrite of the message every time.
Separate who can fix what
Syntax errors mean malformed source. Name and type errors mean the program is well-formed but invalid. Runtime failures are events such as division by zero or missing files. Implementation bugs are broken invariants in your interpreter. Expose the first three cleanly; never train users to report the fourth as normal behavior.
Decide hostile-input behavior early
Even a toy language needs limits if it runs untrusted input: maximum call depth, allocation count, and execution steps. Recursion depth matters first because host-language recursion often kills the process before your language-level check fires. Step counters are crude but effective for demos and sandboxes.
Field notes
- Include columns, not only line numbers. Editors and users both need precision.
- Raise errors to one top-level reporter; printing deep inside evaluation makes output ordering impossible to reason about.
- Keep diagnostics deterministic. Object addresses and hash-order output make tests flaky.
- A
--traceflag that logs calls and returns is crude, fast to build, and invaluable.
Was this lesson helpful?