2022-02-28 21:01:08 +01:00
|
|
|
class Parser(object):
|
|
|
|
def __init__(self, tokens):
|
|
|
|
self.tokens = tokens
|
|
|
|
self.i = 0
|
|
|
|
|
2022-03-01 03:02:31 +01:00
|
|
|
def exhausted(self):
|
|
|
|
return self.i >= len(self.tokens)
|
2022-02-28 21:01:08 +01:00
|
|
|
|
2022-03-01 03:02:31 +01:00
|
|
|
def peek(self, n=0):
|
|
|
|
return self.tokens[self.i + n]
|
2022-02-28 21:01:08 +01:00
|
|
|
|
2022-03-01 03:02:31 +01:00
|
|
|
def advance(self):
|
2022-02-28 21:01:08 +01:00
|
|
|
if not self.exhausted():
|
|
|
|
self.i += 1
|
2022-03-01 03:02:31 +01:00
|
|
|
return self.peek(n=-1)
|
2022-02-28 21:01:08 +01:00
|
|
|
|
|
|
|
def match(self, xs):
|
2022-03-01 03:02:31 +01:00
|
|
|
if self.peek() in xs:
|
|
|
|
self.advance()
|
2022-02-28 21:01:08 +01:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2022-03-01 03:02:31 +01:00
|
|
|
def test(self, predicate):
|
|
|
|
return predicate(self.tokens, self.i)
|
2022-02-28 21:01:08 +01:00
|
|
|
|
2022-03-01 03:02:31 +01:00
|
|
|
def expect(self, predicate):
|
|
|
|
if self.exhausted():
|
|
|
|
raise Exception("Unexpected EOL")
|
|
|
|
if predicate(self.peek()):
|
|
|
|
return self.advance()
|
|
|
|
raise Exception("Unexpected token: \"{}\"".format(self.peek()))
|