Created
October 14, 2022 06:26
-
-
Save t3rmin4t0r/ab0a390148417381a0d8ce081a95bc83 to your computer and use it in GitHub Desktop.
Recursive descent parser example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Literal(object): | |
def __init__(self, c): | |
self.literal = c | |
def append(self, c): | |
self.literal += c | |
def __repr__(self): | |
return ("<Literal '%s'>" % self.literal) | |
class Nested(object): | |
def __init__(self, children): | |
self.children = children | |
def append(self, child): | |
self.children.append(child) | |
def __repr__(self): | |
return ("<Nested %s>" % self.children) | |
def parseinner(it): | |
items = [] | |
for c in it: | |
if c == '(': | |
result,closed = parseinner(it) | |
if not closed: | |
pass # weird | |
items.append(result) | |
elif c == ')': | |
return (Nested(items), True) | |
else: | |
if items and type(items[-1]) is Literal: | |
items[-1].append(c) | |
else: | |
items.append(Literal(c)) | |
return (items, False) | |
def parse(s): | |
it = iter(s) | |
return parseinner(it)[0] | |
s = "foo(bar(baz))blim" | |
print(parse(s)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment