-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlex.py
129 lines (111 loc) · 1.99 KB
/
lex.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
__author__ = 'Alexandre'
import ply.lex as lex
reserved_words = (
'color',
'point',
'line',
'circle',
'rect',
'ellipse',
'customshape',
'text',
'rotate',
'scale',
'translate',
'hide',
'if',
'while',
'for',
'step',
'apply',
'rgb',
'hex',
'name',
'x',
'y',
'p1',
'p2',
'fill_color',
'border_color',
'width',
'c',
'r',
'border_width',
'o',
'height',
'rx',
'ry',
'p',
'close',
'content',
'font',
'size',
'angle',
'sx',
'sy',
'h',
)
tokens = (
'INTEGER',
'BOOLEAN',
'STRING',
'ADD_OP',
'MUL_OP',
'COND_OP',
'IDENTIFIER'
) + tuple(map(lambda s:s.upper(),reserved_words))
literals = '():,;={}'
def t_INTEGER(token):
r'[+-]?\d+'
try:
token.value = int(token.value)
except ValueError:
print ("Line %d: Problem while parsing %s!" % (token.lineno,token.value))
token.value = 0
return token
def t_BOOLEAN(token):
r'(YES|NO)'
try:
token.value = token.value == 'YES'
except ValueError:
print ("Line %d: Problem while parsing %s!" % (token.lineno,token.value))
token.value = 0
return token
def t_STRING(token):
r'"(?:[^"\\]|\\.)*"'
try:
token.value = str(token.value)[1:-1]
except ValueError:
print ("Line %d: Problem while parsing %s!" % (token.lineno,token.value))
token.value = ""
return token
def t_ADD_OP(token):
r'[+-]'
return token
def t_MUL_OP(token):
r'[*/%]'
return token
def t_COND_OP(token):
r'(==|<=|>=|<|>)'
return token
def t_IDENTIFIER(token):
r'[A-Za-z_]\w*'
if token.value in reserved_words:
token.type = token.value.upper()
return token
def t_newline(token):
r'\n+'
token.lexer.lineno += len(token.value)
t_ignore = ' \t'
def t_error(token):
print ("Illegal character '%s'" % repr(token.value[0]))
token.lexer.skip(1)
lex.lex()
if __name__ == "__main__":
import sys
prog = open(sys.argv[1]).read()
lex.input(prog)
while 1:
tok = lex.token()
if not tok: break
print ("line %d: %s(%s)" % (tok.lineno, tok.type, tok.value))