2022-02-28 19:51:47 +01:00
|
|
|
# According to Crafting Interpreters, the only two primitives that a
|
|
|
|
# scanner/lexer needs are peek and advance; other functions (e.g. match) are
|
|
|
|
# nice-to-haves.
|
|
|
|
class Scanner(object):
|
2022-02-28 20:59:55 +01:00
|
|
|
def __init__(self, chars):
|
2022-02-28 19:51:47 +01:00
|
|
|
self.i = 0
|
2022-02-28 20:59:55 +01:00
|
|
|
self.chars = chars
|
2022-02-28 19:51:47 +01:00
|
|
|
|
|
|
|
def exhausted(self):
|
2022-02-28 20:59:55 +01:00
|
|
|
return self.i >= len(self.chars)
|
2022-02-28 19:51:47 +01:00
|
|
|
|
|
|
|
def peek(self, n=0):
|
2022-02-28 20:59:55 +01:00
|
|
|
return self.chars[self.i + n] if self.i in range(0, len(self.chars)) else '\0'
|
2022-02-28 19:51:47 +01:00
|
|
|
|
|
|
|
def advance(self):
|
|
|
|
result = self.peek()
|
|
|
|
self.i += 1
|
|
|
|
return result
|
|
|
|
|
|
|
|
def match(self, x):
|
|
|
|
if self.exhausted():
|
|
|
|
return False
|
|
|
|
if self.peek() == x:
|
|
|
|
self.advance()
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|