-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path02_parser.py
More file actions
163 lines (124 loc) · 4.78 KB
/
Copy path02_parser.py
File metadata and controls
163 lines (124 loc) · 4.78 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
class LexicalError(Exception):
pass
class ParsingError(Exception):
pass
class TokenType:
INTEGER = "INTEGER"
PLUS = "PLUS"
MINUS = "MINUS"
EOF = "EOF" # Означає кінець вхідного рядка
class Token:
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
return f"Token({self.type}, {repr(self.value)})"
class Lexer:
def __init__(self, text):
self.text = text
self.pos = 0
self.current_char = self.text[self.pos]
def advance(self):
"""Переміщуємо 'вказівник' на наступний символ вхідного рядка"""
self.pos += 1
if self.pos > len(self.text) - 1:
self.current_char = None # Означає кінець введення
else:
self.current_char = self.text[self.pos]
def skip_whitespace(self):
"""Пропускаємо пробільні символи."""
while self.current_char is not None and self.current_char.isspace():
self.advance()
def integer(self):
"""Повертаємо ціле число, зібране з послідовності цифр."""
result = ""
while self.current_char is not None and self.current_char.isdigit():
result += self.current_char
self.advance()
return int(result)
def get_next_token(self):
"""Лексичний аналізатор, що розбиває вхідний рядок на токени."""
while self.current_char is not None:
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char.isdigit():
return Token(TokenType.INTEGER, self.integer())
if self.current_char == "+":
self.advance()
return Token(TokenType.PLUS, "+")
if self.current_char == "-":
self.advance()
return Token(TokenType.MINUS, "-")
raise LexicalError("Помилка лексичного аналізу")
return Token(TokenType.EOF, None)
class AST:
pass
class BinOp(AST):
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
class Num(AST):
def __init__(self, token):
self.token = token
self.value = token.value
class Parser:
def __init__(self, lexer):
self.lexer = lexer
self.current_token = self.lexer.get_next_token()
def error(self):
raise ParsingError("Помилка синтаксичного аналізу")
def eat(self, token_type):
"""
Порівнюємо поточний токен з очікуваним токеном і, якщо вони збігаються,
'поглинаємо' його і переходимо до наступного токена.
"""
if self.current_token.type == token_type:
self.current_token = self.lexer.get_next_token()
else:
self.error()
def term(self):
"""Парсер для 'term' правил граматики. У нашому випадку - це цілі числа."""
token = self.current_token
self.eat(TokenType.INTEGER)
return Num(token)
def expr(self):
"""Парсер для арифметичних виразів."""
node = self.term()
while self.current_token.type in (TokenType.PLUS, TokenType.MINUS):
token = self.current_token
if token.type == TokenType.PLUS:
self.eat(TokenType.PLUS)
elif token.type == TokenType.MINUS:
self.eat(TokenType.MINUS)
node = BinOp(left=node, op=token, right=self.term())
return node
def print_ast(node, level=0):
indent = " " * level
if isinstance(node, Num):
print(f"{indent}Num({node.value})")
elif isinstance(node, BinOp):
print(f"{indent}BinOp:")
print(f"{indent} left: ")
print_ast(node.left, level + 2)
print(f"{indent} op: {node.op.type}")
print(f"{indent} right: ")
print_ast(node.right, level + 2)
else:
print(f"{indent}Unknown node type: {type(node)}")
def main():
while True:
try:
text = input('Введіть вираз (або "exit" для виходу): ')
if text.lower() == "exit":
print("Вихід із програми.")
break
lexer = Lexer(text)
parser = Parser(lexer)
tree = parser.expr()
print_ast(tree)
except Exception as e:
print(e)
if __name__ == "__main__":
main()