-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.py
46 lines (38 loc) · 872 Bytes
/
lexer.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
from ply import lex
class Lexer:
tokens = [
'IF', 'WHILE', 'PRINT',
'LRB', 'RRB', 'LCB', 'RCB',
'INTEGER', 'SUM', 'SUB', 'MUL', 'DIV',
'LT', 'GT', 'SEMICOLON'
]
# COLONS
t_SEMICOLON = r';'
# BRACKETS
t_LRB = r'\('
t_RRB = r'\)'
t_LCB = r'\{'
t_RCB = r'\}'
# OPERATOR
t_SUM = r'\+'
t_SUB = r'\-'
t_MUL = r'\*'
t_DIV = r'\/'
t_LT = r'\<'
t_GT = r'\>'
# KW
t_IF = r'if'
t_WHILE = r'while'
t_PRINT = r'print'
def t_INTEGER(self, t):
r'(\d+)'
return t
def t_newline(self, t):
r'\n+'
t.lexer.lineno += len(t.value)
t_ignore = '\n \t'
def t_error(self, t):
raise Exception('Error at', t.value)
def build(self, **kwargs):
self.lexer = lex.lex(module=self, **kwargs)
return self.lexer