Skip to content

Instantly share code, notes, and snippets.

@t3rmin4t0r
Created October 14, 2022 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t3rmin4t0r/ab0a390148417381a0d8ce081a95bc83 to your computer and use it in GitHub Desktop.
Save t3rmin4t0r/ab0a390148417381a0d8ce081a95bc83 to your computer and use it in GitHub Desktop.
Recursive descent parser example
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