-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokens.py
165 lines (127 loc) · 2.13 KB
/
tokens.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
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
164
165
class ParsingError(Exception):
pass
# List of token names
tokens = (
'LPAREN',
'RPAREN',
'COMMA',
'SHARP',
'LBRACKET',
'RBRACKET',
'LBRACE',
'RBRACE',
'POWER',
'MULT',
'DIV',
'INTDIV',
'MOD',
'ADD',
'SUB',
'USUB',
'IN',
'CONS',
'NOT',
'AND',
'OR',
'LT',
'LE',
'EQ',
'NE',
'GE',
'GT',
'INTEGER',
'REAL',
'BOOLEAN',
'STRING',
'SEMICOLON',
'PRINT',
'VARIABLE',
'ASSIGN',
'IF',
'ELSE',
'WHILE',
'FUNCTION'
)
t_SEMICOLON = r'\s*;\s*'
t_LPAREN = r'\s*\(\s*'
t_RPAREN = r'\s*\)\s*'
t_COMMA = r'\s*\,\s*'
t_SHARP = r'\s*\#\s*'
t_LBRACKET = r'\s*\[\s*'
t_RBRACKET = r'\s*\]\s*'
t_LBRACE = r'\s*{\s*'
t_RBRACE = r'\s*}\s*'
t_POWER = r'\s*\*\*\s*'
t_MULT = r'\s*\*\s*'
t_DIV = r'\s*\/\s*'
t_ADD = r'\s*\+\s*'
t_SUB = r'\s*\-\ +'
t_USUB = r'\s*\-'
t_CONS = r'\s*::\s*'
t_ASSIGN = r'\s*=\s*'
t_LT = r'\s*<\s*'
t_LE = r'\s*<=\s*'
t_EQ = r'\s*==\s*'
t_NE = r'\s*<>\s*'
t_GE = r'\s*>=\s*'
t_GT = r'\s*>\s*'
t_VARIABLE = r'[a-zA-Z][a-zA-Z0-9_]*'
t_ignore = '\n'
# Keywords
def t_PRINT(t):
r'print\s*\('
return t
def t_IF(t):
r'if\s*\('
return t
def t_ELSE(t):
r'\s*else\s*'
return t
def t_WHILE(t):
r'while\s*\('
return t
def t_FUNCTION(t):
r'\s*fun\s*'
return t
def t_INTDIV(t):
r'\s*div\s*'
return t
def t_MOD(t):
r'\s*mod\s*'
return t
def t_IN(t):
r'\s*in\s*'
return t
def t_NOT(t):
r'\s*not\s*'
return t
def t_OR(t):
r'\s*orelse\s*'
return t
def t_AND(t):
r'\s*andalso\s*'
return t
def t_REAL(t):
r'((\d+\.\d*)|(\d*\.\d+))(e-?\d+)?'
t.value = float(t.value)
return t
def t_INTEGER(t):
r'\d+'
t.value = int(t.value)
return t
def t_BOOLEAN(t):
r'(True) | (False)'
t.value = eval(t.value)
return t
def t_STRING(t):
r'(\"[^\"]*\")|(\'[^\']*\')'
t.value = t.value[1: -1]
return t
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(t):
if t.value[0].strip() == '':
t.lexer.skip(1)
else:
raise ParsingError("SYNTAX ERROR")