Build a Streaming Lisp-Style Expression Reader with Exact Error Positions
StringsModel answerLast updated
Write a single-pass reader for a small Lisp-like syntax with integers, symbols and nested lists, reporting the first error with a clear message and exact character index.
Build a reader for a tiny Lisp-like notation. It must scan the text once, left to right, using a moving position in the string. Splitting the whole input into pieces (for example with split()) is not allowed. The focus is on failing well: at the first bad spot, stop and report what is wrong and at which character index.
Working grammar
- Whitespace (space, tab,
\r,\n) separates elements and is otherwise ignored. - Integer: an optional
-followed by one or more decimal digits (42,-7). - Symbol: starts with an ASCII letter or one of
+ - * / _, followed by any number of ASCII letters, digits, or+ - * / _(x,add,+,set_value). A token that fits the integer rule is an integer, not a symbol. - List:
(, zero or more expressions separated by whitespace,). A parenthesis also terminates an atom, so(a(b))is valid. - Any other character (
#,",@, ...) is invalid. A token starting with a digit that is not a full integer (such as12ab) is invalid. - Output: integers become integers, symbols become strings, lists become lists.
(add 1 (neg x))gives["add", 1, ["neg", "x"]]. - The input contains exactly one expression, optionally surrounded by whitespace. Anything after it is an error.
- Every error must state the problem and the character index.
Decide, and state, how you report errors (exception vs. returned value), whether partial results are returned (they should not be), and whether an index is enough or line/column is wanted.
Part 1: a lone atom
Parse an input that is a single atom, optionally padded with whitespace. " -15 " gives -15, "add" gives "add". "12ab", "a#b" and empty input are errors. Design the atom reader so it can be called in the middle of a longer input.
Part 2: a flat list
Accept a parenthesized list of atoms: (add 1 -2 x) gives ["add", 1, -2, "x"], () gives []. The parser must stop at the first problem with a clear message for at least: (a # b), (ab#), (12ab), (a b, ) and (a b) c. Nested lists may be rejected at this stage.
Part 3: arbitrary nesting
Allow lists inside lists at any depth: (define (square x) (* x x)) gives ["define", ["square", "x"], ["*", "x", "x"]]. Still one pass, and every Part 2 error must still be detected with a correct index at any depth, including a deeply nested list that is never closed.
Discuss: how deep can nesting go (recursion limit vs. explicit stack), and which ( an unclosed-list error should point to.
Expected
Working code for all three parts, a set of tests covering valid inputs and each error class (including inside nested lists), and the complexity of your approach.
Hints
Hint 1
Keep one cursor (an index into the string) shared by every routine. Each routine reads from the cursor and leaves it just past what it consumed.
Hint 2
Write the atom reader to consume characters until whitespace, `(`, `)` or end of input, then classify the token: integer, symbol, or invalid. Report invalid characters at their own index and malformed tokens at the token start.
Hint 3
Use two mutually recursive routines: `parse_expr` (skips whitespace, dispatches on `(`, `)`, or atom start) and `parse_list` (loops until `)`). Check for trailing input only once, at the top level after the single expression. For an unclosed list, remember the index of its opening `(`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a small parser object holding the string s and a cursor i. Every routine starts at i and leaves i just past what it consumed, so no backtracking and no splitting are needed. Errors are raised as a ParseError(message, index); raising guarantees we never return a half-built result.
Design decisions
- Errors as exceptions: this gives early exit from deep recursion with no result-threading. The exception carries
index. - Index only: a character index is enough for the exercise; line and column can be derived from it afterwards by counting newlines up to the index.
- Single expression: after the top-level expression, skip whitespace and require end of input.
- Atom boundary: an atom ends at whitespace,
(,)or end of input. This is what makes(a(b))legal.
Code
class ParseError(Exception):
def __init__(self, msg, index):
super().__init__(f"{msg} at index {index}")
self.msg, self.index = msg, index
WS = " \t\r\n"
SYM_START = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-*/_")
SYM_REST = SYM_START | set("0123456789")
class Parser:
def __init__(self, s):
self.s, self.i = s, 0
def skip_ws(self):
while self.i < len(self.s) and self.s[self.i] in WS:
self.i += 1
def parse_atom(self):
s, start = self.s, self.i
j = start
while j < len(s) and s[j] not in WS and s[j] not in "()":
j += 1
tok = s[start:j]
# integer?
body = tok[1:] if tok[:1] == "-" else tok
if body.isascii() and body.isdigit():
self.i = j
return int(tok)
# symbol?
if tok[0] in SYM_START:
for k, ch in enumerate(tok):
if ch not in SYM_REST:
raise ParseError(f"invalid character {ch!r}", start + k)
self.i = j
return tok
if tok[0].isdigit():
raise ParseError(f"malformed number {tok!r}", start)
raise ParseError(f"invalid character {tok[0]!r}", start)
def parse_expr(self):
self.skip_ws()
if self.i >= len(self.s):
raise ParseError("unexpected end of input", self.i)
c = self.s[self.i]
if c == "(":
return self.parse_list()
if c == ")":
raise ParseError("unexpected ')'", self.i)
return self.parse_atom()
def parse_list(self):
open_at = self.i
self.i += 1 # consume '('
items = []
while True:
self.skip_ws()
if self.i >= len(self.s):
raise ParseError("unclosed '('", open_at)
if self.s[self.i] == ")":
self.i += 1
return items
items.append(self.parse_expr())
def parse(s):
p = Parser(s)
value = p.parse_expr()
p.skip_ws()
if p.i != len(s):
raise ParseError("unexpected trailing input", p.i)
return value
The - edge case: - alone is a symbol (body is empty, so it is not an integer, and - is a valid symbol start). -7 is an integer. -a is a symbol. 12ab starts with a digit, is not an integer, and is not a valid symbol start, so it is reported as malformed at the token start.
Error behavior on the required cases
| Input | Result |
|---|---|
(a # b) | invalid character '#' at index 3 |
(ab#) | invalid character '#' at index 3 |
(12ab) | malformed number '12ab' at index 1 |
(a b | unclosed ( at index 0 |
) | unexpected ) at index 0 |
(a b) c | unexpected trailing input at index 6 |
"" | unexpected end of input at index 0 |
For nested input like (a (b (c d), the innermost unclosed list is reported first because the loop of the deepest list hits end of input first; it points at that list's own ( (index 6 here). Reporting the outermost unclosed ( instead is a valid alternative, but you need to state the choice; the innermost one is what a single-pass parser naturally finds.
Staging across the three parts
- Part 1:
parse_atomplus a top-level check for trailing input. - Part 2: add
parse_list, which callsparse_expr(restrict it to atoms if nesting must be rejected). - Part 3: nothing new in the structure;
parse_listandparse_expralready call each other. Errors stay correct at depth because the index is absolute in the original string, not relative to a sublist.
Complexity
Each character is examined a constant number of times, so time is O(n). Space is O(d) for recursion depth d plus the output.
Deep nesting
Python's default recursion limit (about 1000) breaks on inputs like 100,000 nested parentheses. Options: raise the limit (risky, can crash the interpreter), reject depth above a configured maximum with a clear ParseError (good for untrusted input), or convert to an explicit stack of partially built lists plus their opening indices. The explicit-stack version loops over characters: on ( push a new list and its index; on ) pop, and append to the parent (or finish); on an atom append to the top; at end of input, a non-empty stack means unclosed, pointing at the top entry's index.
Tests to write
- Valid:
42," -15 ",add,+,(),(a(b)),(define (square x) (* x x)), input with tabs and newlines. - Errors: each row in the table above, plus
a#b,1-2,(a (b #)),(a (b),((,()), and(a) (b). - Assert both the message category and the exact index.
Common mistakes
- Using
split()or a regex tokenizer pass, which violates the one-pass requirement. - Treating
12abas the integer12followed by symbolab. - Forgetting that
(and)end an atom, which makes(a(b))fail. - Returning a partial list on error instead of aborting.
- Reporting indices relative to a sublist, or the index after the cursor has already advanced past the bad character.
- Checking trailing input inside the list loop rather than once at the top level, so
)and(a b) cget confusing messages. - Parsing
-followed by non-digits as a broken number instead of a symbol.