-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLexericalAnalysis.py
105 lines (86 loc) · 2.12 KB
/
LexericalAnalysis.py
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
# Copyright Joan Montas
# All rights reserved.
# License under GNU General Public License v3.0
from ply import lex
class LexicalAnalyzer:
def __init__(self):
self.functions = {
"sin": "SIN",
"cos": "COS",
"tan": "TAN",
"sec": "SEC",
"csc": "CSC",
"cot": "COT",
"arcsine": "ARCSINE",
"arccosine": "ARCCOSINE",
"arctan": "ARCTAN",
"sec2": "SEC2",
"csc2": "CSC2",
}
self.constant = {"e": "EULER"}
self.tokens = (
(
"NUMBER",
"VARIABLE",
"CONSTANT",
"FUNCTION",
"PLUS",
"MINUS",
"TIMES",
"DIVIDE",
"POWER",
"LPAREN",
"RPAREN",
)
+ tuple(self.functions.values())
+ tuple(self.constant.values())
)
self.lexer = lex.lex(module=self)
def t_IDENT(self, t):
r"[a-zA-Z_]+"
if t.value in self.functions:
t.type = "FUNCTION"
elif t.value in self.constant:
t.type = "CONSTANT"
else:
t.type = "VARIABLE"
self.test = t
return t
def t_NUMBER(self, t):
r"\d+"
t.value = int(t.value)
return t
def t_PLUS(self, t):
r"\+"
return t
def t_MINUS(self, t):
r"-"
return t
def t_TIMES(self, t):
r"\*"
return t
def t_DIVIDE(self, t):
r"/"
return t
def t_POWER(self, t):
r"\^"
return t
def t_LPAREN(self, t):
r"\("
return t
def t_RPAREN(self, t):
r"\)"
return t
t_ignore = " \t"
def t_error(self, t):
print(f"Illegal character '{t.value[0]}'")
t.lexer.skip(1)
if __name__ == "__main__":
l = LexicalAnalyzer()
test_input = "(e ^ 2) + cos(x)"
l.lexer.input(test_input)
while True:
token = l.lexer.token()
if not token:
break
print(token)