-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlibucomm_parse.py
341 lines (267 loc) · 8.43 KB
/
libucomm_parse.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
#!/usr/bin/python3
from pyparsing import *
BUILTIN_TYPES = {
'uint8_t': 1,
'int8_t': 1,
'uint16_t': 2,
'int16_t': 2,
'uint32_t': 4,
'int32_t': 4,
}
def registerParseAction(cls):
cls.grammar.setParseAction(cls.parse)
class UnknownTypeError(Exception):
def __init__(self, type):
super(UnknownTypeError, self).__init__("Unknown type '%s'" % type)
self.type = type
class Identifier:
grammar = Word(alphas, alphanums + '_')
class Member:
grammar = (
Identifier.grammar("type")
+ Identifier.grammar("name")
+ Optional(Literal('[') + Optional(CharsNotIn(']'))("size") + Literal(']'))("array")
+ Suppress(';')
)
def __init__(self, type, name, array=False, array_size=None):
self.name = name
self.type = type
self.array = array
self.array_size = array_size
def isPOD(self):
if self.array and not self.array_size:
return False
if self.type in BUILTIN_TYPES:
return True
return self.type.isPOD()
def size(self):
c = ""
if self.array and self.array_size:
c = "(" + self.array_size + ") * "
if self.type in BUILTIN_TYPES:
return c + str(BUILTIN_TYPES[self.type])
return c + "(" + self.type.podSize() + ")"
def __str__(self):
s = self.type + " " + self.name
if self.array:
s += "[]"
return s
def definition(self, last=False):
if self.array:
if self.type not in BUILTIN_TYPES and not self.type.isPOD():
raise RuntimeError("Arrays of non-POD structs are not allowed")
if self.array_size:
# Known array size
return str(self.type) + " " + self.name + "[" + self.array_size + "] = {};"
else:
# Dynamic array
last = str(last).lower()
return "uc::List< uc::IOInstance<IO, %s>, %s > %s;" % (
last, self.type, self.name
)
else:
return str(self.type) + " " + self.name + "{0};"
def resolveType(self, types):
if self.type in BUILTIN_TYPES:
return
try:
self.type = types[self.type]
except KeyError:
raise UnknownTypeError(self.type)
@classmethod
def parse(cls, parse_result):
array = False
array_size = None
if parse_result.array:
array = True
array_size = parse_result.size
return cls(parse_result.type, parse_result.name, array, array_size)
registerParseAction(Member)
class Custom:
content = Forward()
content << (
(CharsNotIn('{}'))
| (Literal('{') + ZeroOrMore(content) + Literal('}'))
)
grammar = (
Suppress('custom')
+ Suppress('{')
+ ZeroOrMore(content)
+ Suppress('}')
)
def __init__(self, content):
self.content = content
def __str__(self):
return ' '.join(self.content)
@classmethod
def parse(cls, parse_result):
return cls(parse_result)
registerParseAction(Custom)
class Struct:
grammar = (
(Literal('struct') | Literal('msg'))('type')
+ Identifier.grammar("name")
+ Suppress('{')
+ ZeroOrMore(Member.grammar)("members")
+ Suppress('}')
+ Suppress(';')
)
def __init__(self, type, name, members):
self.type = type
self.name = name
self.members = list(members)
def __str__(self):
return self.name
def setMsgID(self, id):
self.msgID = id
def definition(self):
code = [
'struct %s' % self.name,
'{',
'\tenum',
'\t{',
'\t\tIS_POD = %d,' % self.isPOD(),
'\t\tPOD_SIZE = %s,' % self.podSize(),
'\t};',
'',
]
if self.type == 'msg':
code += [
'\tenum',
'\t{',
'\t\tMSG_CODE = %d' % self.msgID,
'\t};',
'',
]
if self.podMembers:
code += [
'\tstruct',
'\t{',
'\n'.join(['\t\t' + m.definition() for m in self.podMembers]),
'\t} __attribute__((packed));',
]
for i, m in enumerate(self.nonPODMembers):
last = i == len(self.nonPODMembers)-1
code += [
'\t' + m.definition(last)
]
code += [
'',
self.def_serialize(),
self.def_deserialize(),
]
if self.isPOD():
code.append('} __attribute__((packed));')
else:
code.append('};')
return '\n'.join(code)
def podSize(self):
podMembers = [ m for m in self.members if m.isPOD() ]
if len(self.podMembers) == 0:
return "0"
else:
return ' + '.join([ "(" + m.size() + ")" for m in podMembers ])
def isPOD(self):
for m in self.members:
if not m.isPOD():
return False
return True
def def_serialize(self):
code = [
'inline bool serialize(typename IO::Handler* output) const',
'{',
]
if self.podSize() != "0":
code += [
'\tRETURN_IF_ERROR(output->write(this, %s));' % self.podSize(),
]
code += ['\tRETURN_IF_ERROR(%s.serialize(output));' % m.name for m in self.nonPODMembers]
code += [
'\treturn true;',
'}',
]
return ''.join([ '\t' + i + '\n' for i in code])
def def_deserialize(self):
code = [
'inline bool deserialize(typename IO::Reader* input)',
'{',
]
if self.podSize() != "0":
code += [
'\tRETURN_IF_ERROR(input->read(this, %s));' % self.podSize(),
]
for i, m in enumerate(self.nonPODMembers):
last = 'false'
if i == len(self.nonPODMembers)-1:
last = 'true'
code.append('\tRETURN_IF_ERROR(%s.deserialize(input));' % m.name)
code += [
'\treturn true;',
'}',
]
return ''.join([ '\t' + i + '\n' for i in code])
def resolveTypes(self, types):
self.podMembers = []
self.nonPODMembers = []
for m in self.members:
m.resolveType(types)
if m.isPOD():
self.podMembers.append(m)
else:
self.nonPODMembers.append(m)
@classmethod
def parse(cls, parse_result):
return cls(parse_result.type, parse_result.name, parse_result.members)
registerParseAction(Struct)
class Grammar:
def __init__(self):
self.document = ZeroOrMore(Struct.grammar | Custom.grammar)
class Parser:
def __init__(self, grammar):
self.grammar = grammar
def parse(self, string):
# Strip comments
content = ""
for line in string.split('\n'):
pos = line.find('//')
if pos < 0:
content += line + '\n'
else:
content += line[0:pos] + '\n'
ret = self.grammar.document.parseString(content, True)
types = {}
structs = [ s for s in ret if isinstance(s, Struct) ]
custom_areas = [ s for s in ret if isinstance(s, Custom) ]
for struct in structs:
if struct.name in types:
raise RuntimeError("Struct '%s' is defined multiple times" % struct.name)
types[struct.name] = struct
print('#include <stdint.h>')
print('#include <stdlib.h>')
print('#include <libucomm/list.h>')
print
print('// Start custom area')
for custom in custom_areas:
print(custom)
print('// End custom area')
print
print('template<class IO>')
print('class Proto')
print('{')
print('public:')
msg_counter = 0
for struct in structs:
struct.resolveTypes(types)
if struct.type == 'msg':
struct.setMsgID(msg_counter)
msg_counter += 1
print(struct.definition() + "\n")
print('};')
class Generator:
def __init__(self):
pass
if __name__ == "__main__":
import sys
grammar = Grammar()
parser = Parser(grammar)
parser.parse(open(sys.argv[1]).read())