-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathamplenet_lexer.py
More file actions
106 lines (76 loc) · 1.54 KB
/
Copy pathamplenet_lexer.py
File metadata and controls
106 lines (76 loc) · 1.54 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
import ply.lex as lex
# Reserved words
from file_reader import read_file
reserved_words = {
'connect': 'CONNECT',
'client': 'CLIENT',
'open': 'OPEN',
'send': 'SEND',
'external': 'EXTERNAL',
'default': 'DEFAULT'
}
# TOKENS
tokens = [
'MESSAGE',
'IP',
'NUMBER',
'LB',
'RB',
'EXCLAMATION',
'ID',
'SEMICOLON',
] + list(reserved_words.values())
# REGULAR EXPRESSION RULES
# Left bracket
t_LB = r'\['
# Right bracket
t_RB = r'\]'
# Exclamation point
t_EXCLAMATION = r'!'
# Semicolon
t_SEMICOLON = r';'
# Comments
def t_COMMENTS(t):
r'\(.*\)'
pass
# Match IP addresses
def t_IP(t):
r'\d+\.\d+\.\d+\.\d+'
t.value = str(t.value)
return t
# Match numbers
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
# Match a message
def t_MESSAGE(t):
r'\<(.)+\>'
return t
# Match an identifier
def t_ID(t):
r'[a-zA-Z-_][a-zA-Z-_0-9]*'
if t.value in reserved_words:
t.type = reserved_words[t.value]
return t
# Define a rule so we can track line numbers
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
# Characters to ignore
t_ignore = ' \t'
# Error rule
def t_error(t):
print("ERROR: Illegal character '%s', at position %s, %s." %
(t.value[0], t.lineno, t.lexpos))
t.lexer.skip(1)
# Build the lexer
lexer = lex.lex()
if __name__ == '__main__':
# Read the input
lexer.input(read_file("tests/test.txt"))
while True:
tok = lexer.token()
if not tok:
break
print(tok)