forked from kylemartinezolodin/Programming-Languages
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.py
More file actions
69 lines (54 loc) · 2.04 KB
/
Copy pathparse.py
File metadata and controls
69 lines (54 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import sys
from lexer import *
# Parser object keeps track of current token and checks if the code matches the grammar.
class Parser:
def __init__(self, lexer):
self.lexer = lexer
self.curToken = None
self.peekToken = None
self.nextToken()
self.nextToken() # Call this twice to initialize current and peek.
# Return true if the current token matches.
def checkToken(self, kind):
return kind == self.curToken.kind
# Return true if the next token matches.
def checkPeek(self, kind):
return kind == self.peekToken.kind
# Try to match current token. If not, error. Advances the current token.
def match(self, kind):
if not self.checkToken(kind):
self.abort("Expected " + kind.name + ", got " + self.curToken.kind.name)
self.nextToken()
# Advances the current token.
def nextToken(self):
self.curToken = self.peekToken
self.peekToken = self.lexer.getToken()
# No need to worry about passing the EOF, lexer handles that
def abort(self, message):
sys.exit("Error. " + message)
def program(self):
print("PROGRAM")
# Parse all the statements in the program.
while not self.checkToken(TokenType.EOF):
self.statement()
def nl(self):
print("NEWLINE")
# Require at least one newline.
self.match(TokenType.NEWLINE)
# But we will allow extra newlines too, of course.
while self.checkToken(TokenType.NEWLINE):
self.nextToken()
def statement(self):
# Check the first token to see what kind of statement this is.
# "PRINT" (expression | string)
if self.checkToken(TokenType.PRINT):
print("STATEMENT-PRINT")
self.nextToken()
if self.checkToken(TokenType.STRING):
# Simple string.
self.nextToken()
else:
# Expect an expression.
self.expression()
# Newline.
self.nl()