forked from tpircher-zz/pycrc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crc_parser.py
418 lines (356 loc) · 13.3 KB
/
crc_parser.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# -*- coding: Latin-1 -*-
# pycrc -- parametrisable CRC calculation utility and C source code generator
#
# Copyright (c) 2006-2012 Thomas Pircher <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Macro Language parser for pycrc.
use as follows:
import sys
from crc_opt import Options
from crc_parser import MacroParser
opt = Options()
opt.parse(sys.argv[1:])
mp = MacroParser(opt)
if mp.parse("Test 1 2 3"):
print(mp.out_str)
"""
from crc_symtable import SymbolTable
from crc_lexer import Lexer
import re
import sys
# Class ParseError
###############################################################################
class ParseError(Exception):
"""
The exception class for the parser.
"""
# Class constructor
###############################################################################
def __init__(self, reason):
self.reason = reason
# function __str__
###############################################################################
def __str__(self):
return self.reason
# Class MacroParser
###############################################################################
class MacroParser(object):
"""
The macro language parser and code generator class.
"""
re_is_int = re.compile("^[-+]?[0-9]+$")
#re_is_hex = re.compile("^(0[xX])?[0-9a-fA-F]+$")
re_is_hex = re.compile("^0[xX][0-9a-fA-F]+$")
opt = None
sym = None
lex = Lexer()
# Class constructor
###############################################################################
def __init__(self, opt):
self.opt = opt
self.sym = SymbolTable(opt)
self.out_str = None
# function parse
#
# The used grammar is:
# data: /* empty */
# | data GIBBERISH
# | data IDENTIFIER
# | data '{:' data ':}'
# | data if_block
# ;
#
# if_block: IF '(' exp_or ')' '{:' data ':}' elif_blocks else_block
# ;
#
# elif_blocks: /* empty */
# | elif_blocks ELIF '(' exp_or ')' '{:' data ':}'
# ;
#
# else_block: /* empty */
# | ELSE '{:' data ':}'
# ;
#
# exp_or: exp_and
# | exp_or TOK_OR exp_and
# ;
#
# exp_and: term
# | exp_and TOK_AND exp_comparison
# ;
#
# exp_comparison: term TOK_COMPARISON term
# ;
#
# term: LITERAL
# | IDENTIFIER
# | '(' exp_or ')'
# ;
###############################################################################
def parse(self, in_str):
"""
Parse a macro string.
"""
self.lex.set_str(in_str)
self.out_str = ""
self._parse_data(do_print = True)
tok = self.lex.peek()
if tok != self.lex.tok_EOF:
raise ParseError("%s: error: misaligned closing block '%s'" % (sys.argv[0], self.lex.text))
# function _parse_data
###############################################################################
def _parse_data(self, do_print):
"""
Private top-level parsing function.
"""
tok = self.lex.peek()
while tok != self.lex.tok_EOF:
if tok == self.lex.tok_gibberish:
self._parse_gibberish(do_print)
elif tok == self.lex.tok_block_open:
self._parse_data_block(do_print)
elif tok == self.lex.tok_identifier and self.lex.text == "if":
self._parse_if_block(do_print)
elif tok == self.lex.tok_identifier:
self._parse_identifier(do_print)
elif tok == self.lex.tok_block_close:
return
else:
raise ParseError("%s: error: wrong token '%s'" % (sys.argv[0], self.lex.text))
tok = self.lex.peek()
# function _parse_gibberish
###############################################################################
def _parse_gibberish(self, do_print):
"""
Parse gibberish.
Actually, just print the characters in 'text' if do_print is True.
"""
if do_print:
self.out_str = self.out_str + self.lex.text
self.lex.advance()
# function _parse_identifier
###############################################################################
def _parse_identifier(self, do_print):
"""
Parse an identifier.
"""
try:
sym_value = self.sym.getTerminal(self.lex.text)
except LookupError:
raise ParseError("%s: error: unknown terminal '%s'" % (sys.argv[0], self.lex.text))
self.lex.advance()
if do_print:
self.lex.prepend(sym_value)
# function _parse_if_block
###############################################################################
def _parse_if_block(self, do_print):
"""
Parse an if block.
"""
# parse the expression following the 'if' and the associated block.
exp_res = self._parse_conditional_block(do_print)
do_print = do_print and not exp_res
# try $elif
tok = self.lex.peek()
while tok == self.lex.tok_identifier and self.lex.text == "elif":
exp_res = self._parse_conditional_block(do_print)
do_print = do_print and not exp_res
tok = self.lex.peek()
# try $else
if tok == self.lex.tok_identifier and self.lex.text == "else":
# get rid of the tok_identifier, 'else' and following spaces
self.lex.advance()
self.lex.delete_spaces()
# expect a data block
self._parse_data_block(do_print)
# function _parse_conditional_block
###############################################################################
def _parse_conditional_block(self, do_print):
"""
Parse a conditional block (such as $if or $elif).
Return the truth value of the expression.
"""
# get rid of the tok_identifier, 'if' or 'elif'
self.lex.advance()
self.lex.set_state(self.lex.state_expr)
# expect an open parenthesis
tok = self.lex.peek()
if tok != self.lex.tok_par_open:
raise ParseError("%s: error: open parenthesis expected: '%s'" % (sys.argv[0], self.lex.text))
self.lex.advance()
# parse the boolean expression
exp_res = self._parse_exp_or()
# expect a closed parenthesis
tok = self.lex.peek()
if tok != self.lex.tok_par_close:
raise ParseError("%s: error: closed parenthesis expected: '%s'" % (sys.argv[0], self.lex.text))
self.lex.advance()
# get rid of eventual spaces, and switch back to gibberish.
self.lex.delete_spaces()
self.lex.set_state(self.lex.state_gibberish)
# expect a data block
self._parse_data_block(do_print and exp_res)
# get rid of eventual spaces
# but only if followed by $if, $else or $elif
self.lex.delete_spaces(skip_unconditional = False)
return exp_res
# function _parse_data_block
###############################################################################
def _parse_data_block(self, do_print):
"""
Parse a data block.
"""
# expect an open block
tok = self.lex.peek()
if tok != self.lex.tok_block_open:
raise ParseError("%s: error: open block expected: '%s'" % (sys.argv[0], self.lex.text))
self.lex.advance(skip_nl = True)
# more data follows...
self._parse_data(do_print)
# expect a closed block
tok = self.lex.peek()
if tok != self.lex.tok_block_close:
raise ParseError("%s: error: closed block expected: '%s'" % (sys.argv[0], self.lex.text))
self.lex.advance(skip_nl = True)
# function _parse_exp_or
###############################################################################
def _parse_exp_or(self):
"""
Parse a boolean 'or' expression.
"""
ret = False
while True:
ret = self._parse_exp_and() or ret
# is the expression terminated?
tok = self.lex.peek()
if tok == self.lex.tok_par_close:
return ret
# expect an 'or' token.
elif tok == self.lex.tok_or:
self.lex.advance()
# everything else is the end of the expression.
# Let the caling function worry about error reporting.
else:
return ret
return False
# function _parse_exp_and
###############################################################################
def _parse_exp_and(self):
"""
Parse a boolean 'and' expression.
"""
ret = True
while True:
ret = self._parse_exp_comparison() and ret
# is the expression terminated?
tok = self.lex.peek()
if tok == self.lex.tok_par_close:
return ret
# expect an 'and' token.
elif tok == self.lex.tok_and:
self.lex.advance()
# everything else is a parse error.
else:
return ret
return False
# function _parse_exp_comparison
###############################################################################
def _parse_exp_comparison(self):
"""
Parse a boolean comparison.
"""
# left hand side of the comparison
lhs = self._parse_exp_term()
# expect a comparison
tok = self.lex.peek()
if tok != self.lex.tok_op:
raise ParseError("%s: error: operator expected: '%s'" % (sys.argv[0], self.lex.text))
operator = self.lex.text
self.lex.advance()
# right hand side of the comparison
rhs = self._parse_exp_term()
# if both operands ar numbers, convert them
num_l = self._get_num(lhs)
num_r = self._get_num(rhs)
if num_l != None and num_r != None:
lhs = num_l
rhs = num_r
# now calculate the result of the comparison, whatever that means
if operator == "<=":
ret = lhs <= rhs
elif operator == "<":
ret = lhs < rhs
elif operator == "==":
ret = lhs == rhs
elif operator == "!=":
ret = lhs != rhs
elif operator == ">=":
ret = lhs >= rhs
elif operator == ">":
ret = lhs > rhs
else:
raise ParseError("%s: error: unknow operator: '%s'" % (sys.argv[0], self.lex.text))
return ret
# function _parse_exp_term
###############################################################################
def _parse_exp_term(self):
"""
Parse a terminal.
"""
tok = self.lex.peek()
# identifier
if tok == self.lex.tok_identifier:
try:
ret = self.sym.getTerminal(self.lex.text)
except LookupError:
raise ParseError("%s: error: unknown terminal '%s'" % (sys.argv[0], self.lex.text))
if ret == None:
ret = "Undefined"
# string
elif tok == self.lex.tok_str:
ret = self.lex.text
# number
elif tok == self.lex.tok_num:
ret = self.lex.text
# parenthesised expression
elif tok == self.lex.tok_par_open:
self.lex.advance()
ret = self._parse_exp_or()
tok = self.lex.peek()
if tok != self.lex.tok_par_close:
raise ParseError("%s: error: closed parenthesis expected: '%s'" % (sys.argv[0], self.lex.text))
self.lex.advance()
return ret
# function _get_num
###############################################################################
def _get_num(self, in_str):
"""
Check if in_str is a number and return the numeric value.
"""
ret = None
if in_str != None:
m = self.re_is_int.match(in_str)
if m != None:
ret = int(in_str)
m = self.re_is_hex.match(in_str)
if m != None:
ret = int(in_str, 16)
return ret