Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mesa
Path: blob/21.2-virgl/src/asahi/lib/gen_pack.py
4560 views
1
#encoding=utf-8
2
3
# Copyright (C) 2016 Intel Corporation
4
# Copyright (C) 2016 Broadcom
5
# Copyright (C) 2020 Collabora, Ltd.
6
#
7
# Permission is hereby granted, free of charge, to any person obtaining a
8
# copy of this software and associated documentation files (the "Software"),
9
# to deal in the Software without restriction, including without limitation
10
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
11
# and/or sell copies of the Software, and to permit persons to whom the
12
# Software is furnished to do so, subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice (including the next
15
# paragraph) shall be included in all copies or substantial portions of the
16
# Software.
17
#
18
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24
# IN THE SOFTWARE.
25
26
import xml.parsers.expat
27
import sys
28
import operator
29
from functools import reduce
30
31
global_prefix = "agx"
32
33
pack_header = """
34
/* Generated code, see midgard.xml and gen_pack_header.py
35
*
36
* Packets, enums and structures for Panfrost.
37
*
38
* This file has been generated, do not hand edit.
39
*/
40
41
#ifndef AGX_PACK_H
42
#define AGX_PACK_H
43
44
#include <stdio.h>
45
#include <stdint.h>
46
#include <stdbool.h>
47
#include <assert.h>
48
#include <math.h>
49
#include <inttypes.h>
50
#include "util/macros.h"
51
#include "util/u_math.h"
52
53
#define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
54
55
static inline uint64_t
56
__gen_uint(uint64_t v, uint32_t start, uint32_t end)
57
{
58
#ifndef NDEBUG
59
const int width = end - start + 1;
60
if (width < 64) {
61
const uint64_t max = (1ull << width) - 1;
62
assert(v <= max);
63
}
64
#endif
65
66
return v << start;
67
}
68
69
static inline uint32_t
70
__gen_sint(int32_t v, uint32_t start, uint32_t end)
71
{
72
#ifndef NDEBUG
73
const int width = end - start + 1;
74
if (width < 64) {
75
const int64_t max = (1ll << (width - 1)) - 1;
76
const int64_t min = -(1ll << (width - 1));
77
assert(min <= v && v <= max);
78
}
79
#endif
80
81
return (((uint32_t) v) << start) & ((2ll << end) - 1);
82
}
83
84
static inline uint64_t
85
__gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
86
{
87
uint64_t val = 0;
88
const int width = end - start + 1;
89
const uint64_t mask = (width == 64 ? ~0 : (1ull << width) - 1 );
90
91
for (unsigned byte = start / 8; byte <= end / 8; byte++) {
92
val |= ((uint64_t) cl[byte]) << ((byte - start / 8) * 8);
93
}
94
95
return (val >> (start % 8)) & mask;
96
}
97
98
static inline uint64_t
99
__gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
100
{
101
int size = end - start + 1;
102
int64_t val = __gen_unpack_uint(cl, start, end);
103
104
/* Get the sign bit extended. */
105
return (val << (64 - size)) >> (64 - size);
106
}
107
108
#define agx_prepare(dst, T) \\
109
*(dst) = (struct AGX_ ## T){ AGX_ ## T ## _header }
110
111
#define agx_pack(dst, T, name) \\
112
for (struct AGX_ ## T name = { AGX_ ## T ## _header }, \\
113
*_loop_terminate = (void *) (dst); \\
114
__builtin_expect(_loop_terminate != NULL, 1); \\
115
({ AGX_ ## T ## _pack((uint32_t *) (dst), &name); \\
116
_loop_terminate = NULL; }))
117
118
#define agx_unpack(fp, src, T, name) \\
119
struct AGX_ ## T name; \\
120
AGX_ ## T ## _unpack(fp, (uint8_t *)(src), &name)
121
122
#define agx_print(fp, T, var, indent) \\
123
AGX_ ## T ## _print(fp, &(var), indent)
124
125
#define agx_pixel_format_print(fp, format) do {\\
126
fprintf(fp, "%*sFormat: ", indent, ""); \\
127
\\
128
if (agx_channels_as_str((enum agx_channels)(format & 0x7F))) \\
129
fputs(agx_channels_as_str((enum agx_channels)(format & 0x7F)), fp); \\
130
else \\
131
fprintf(fp, "unknown channels %02X", format & 0x7F); \\
132
\\
133
fputs(" ", fp); \\
134
\\
135
if (agx_texture_type_as_str((enum agx_texture_type)(format >> 7))) \\
136
fputs(agx_texture_type_as_str((enum agx_texture_type)(format >> 7)), fp); \\
137
else \\
138
fprintf(fp, "unknown type %02X", format >> 7); \\
139
\\
140
fputs("\\n", fp); \\
141
} while(0) \\
142
143
"""
144
145
def to_alphanum(name):
146
substitutions = {
147
' ': '_',
148
'/': '_',
149
'[': '',
150
']': '',
151
'(': '',
152
')': '',
153
'-': '_',
154
':': '',
155
'.': '',
156
',': '',
157
'=': '',
158
'>': '',
159
'#': '',
160
'&': '',
161
'*': '',
162
'"': '',
163
'+': '',
164
'\'': '',
165
}
166
167
for i, j in substitutions.items():
168
name = name.replace(i, j)
169
170
return name
171
172
def safe_name(name):
173
name = to_alphanum(name)
174
if not name[0].isalpha():
175
name = '_' + name
176
177
return name
178
179
def prefixed_upper_name(prefix, name):
180
if prefix:
181
name = prefix + "_" + name
182
return safe_name(name).upper()
183
184
def enum_name(name):
185
return "{}_{}".format(global_prefix, safe_name(name)).lower()
186
187
def num_from_str(num_str):
188
if num_str.lower().startswith('0x'):
189
return int(num_str, base=16)
190
else:
191
assert(not num_str.startswith('0') and 'octals numbers not allowed')
192
return int(num_str)
193
194
MODIFIERS = ["shr", "minus", "align", "log2"]
195
196
def parse_modifier(modifier):
197
if modifier is None:
198
return None
199
200
for mod in MODIFIERS:
201
if modifier[0:len(mod)] == mod:
202
if mod == "log2":
203
assert(len(mod) == len(modifier))
204
return [mod]
205
206
if modifier[len(mod)] == '(' and modifier[-1] == ')':
207
ret = [mod, int(modifier[(len(mod) + 1):-1])]
208
if ret[0] == 'align':
209
align = ret[1]
210
# Make sure the alignment is a power of 2
211
assert(align > 0 and not(align & (align - 1)));
212
213
return ret
214
215
print("Invalid modifier")
216
assert(False)
217
218
class Field(object):
219
def __init__(self, parser, attrs):
220
self.parser = parser
221
if "name" in attrs:
222
self.name = safe_name(attrs["name"]).lower()
223
self.human_name = attrs["name"]
224
225
if ":" in str(attrs["start"]):
226
(word, bit) = attrs["start"].split(":")
227
self.start = (int(word) * 32) + int(bit)
228
else:
229
self.start = int(attrs["start"])
230
231
self.end = self.start + int(attrs["size"]) - 1
232
self.type = attrs["type"]
233
234
if self.type == 'bool' and self.start != self.end:
235
print("#error Field {} has bool type but more than one bit of size".format(self.name));
236
237
if "prefix" in attrs:
238
self.prefix = safe_name(attrs["prefix"]).upper()
239
else:
240
self.prefix = None
241
242
if "exact" in attrs:
243
self.exact = int(attrs["exact"])
244
else:
245
self.exact = None
246
247
self.default = attrs.get("default")
248
249
# Map enum values
250
if self.type in self.parser.enums and self.default is not None:
251
self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
252
253
self.modifier = parse_modifier(attrs.get("modifier"))
254
255
def emit_template_struct(self, dim):
256
if self.type == 'address':
257
type = 'uint64_t'
258
elif self.type == 'bool':
259
type = 'bool'
260
elif self.type == 'float':
261
type = 'float'
262
elif self.type in ['uint', 'hex'] and self.end - self.start > 32:
263
type = 'uint64_t'
264
elif self.type == 'int':
265
type = 'int32_t'
266
elif self.type in ['uint', 'uint/float', 'Pixel Format', 'hex']:
267
type = 'uint32_t'
268
elif self.type in self.parser.structs:
269
type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
270
elif self.type in self.parser.enums:
271
type = 'enum ' + enum_name(self.type)
272
else:
273
print("#error unhandled type: %s" % self.type)
274
type = "uint32_t"
275
276
print(" %-36s %s%s;" % (type, self.name, dim))
277
278
for value in self.values:
279
name = prefixed_upper_name(self.prefix, value.name)
280
print("#define %-40s %d" % (name, value.value))
281
282
def overlaps(self, field):
283
return self != field and max(self.start, field.start) <= min(self.end, field.end)
284
285
class Group(object):
286
def __init__(self, parser, parent, start, count, label):
287
self.parser = parser
288
self.parent = parent
289
self.start = start
290
self.count = count
291
self.label = label
292
self.size = 0
293
self.length = 0
294
self.fields = []
295
296
def get_length(self):
297
# Determine number of bytes in this group.
298
calculated = max(field.end // 8 for field in self.fields) + 1 if len(self.fields) > 0 else 0
299
if self.length > 0:
300
assert(self.length >= calculated)
301
else:
302
self.length = calculated
303
return self.length
304
305
306
def emit_template_struct(self, dim):
307
if self.count == 0:
308
print(" /* variable length fields follow */")
309
else:
310
if self.count > 1:
311
dim = "%s[%d]" % (dim, self.count)
312
313
if len(self.fields) == 0:
314
print(" int dummy;")
315
316
for field in self.fields:
317
if field.exact is not None:
318
continue
319
320
field.emit_template_struct(dim)
321
322
class Word:
323
def __init__(self):
324
self.size = 32
325
self.contributors = []
326
327
class FieldRef:
328
def __init__(self, field, path, start, end):
329
self.field = field
330
self.path = path
331
self.start = start
332
self.end = end
333
334
def collect_fields(self, fields, offset, path, all_fields):
335
for field in fields:
336
field_path = '{}{}'.format(path, field.name)
337
field_offset = offset + field.start
338
339
if field.type in self.parser.structs:
340
sub_struct = self.parser.structs[field.type]
341
self.collect_fields(sub_struct.fields, field_offset, field_path + '.', all_fields)
342
continue
343
344
start = field_offset
345
end = offset + field.end
346
all_fields.append(self.FieldRef(field, field_path, start, end))
347
348
def collect_words(self, fields, offset, path, words):
349
for field in fields:
350
field_path = '{}{}'.format(path, field.name)
351
start = offset + field.start
352
353
if field.type in self.parser.structs:
354
sub_fields = self.parser.structs[field.type].fields
355
self.collect_words(sub_fields, start, field_path + '.', words)
356
continue
357
358
end = offset + field.end
359
contributor = self.FieldRef(field, field_path, start, end)
360
first_word = contributor.start // 32
361
last_word = contributor.end // 32
362
for b in range(first_word, last_word + 1):
363
if not b in words:
364
words[b] = self.Word()
365
words[b].contributors.append(contributor)
366
367
def emit_pack_function(self):
368
self.get_length()
369
370
words = {}
371
self.collect_words(self.fields, 0, '', words)
372
373
# Validate the modifier is lossless
374
for field in self.fields:
375
if field.modifier is None:
376
continue
377
378
assert(field.exact is None)
379
380
if field.modifier[0] == "shr":
381
shift = field.modifier[1]
382
mask = hex((1 << shift) - 1)
383
print(" assert((values->{} & {}) == 0);".format(field.name, mask))
384
elif field.modifier[0] == "minus":
385
print(" assert(values->{} >= {});".format(field.name, field.modifier[1]))
386
elif field.modifier[0] == "log2":
387
print(" assert(util_is_power_of_two_nonzero(values->{}));".format(field.name))
388
389
for index in range(self.length // 4):
390
# Handle MBZ words
391
if not index in words:
392
print(" cl[%2d] = 0;" % index)
393
continue
394
395
word = words[index]
396
397
word_start = index * 32
398
399
v = None
400
prefix = " cl[%2d] =" % index
401
402
for contributor in word.contributors:
403
field = contributor.field
404
name = field.name
405
start = contributor.start
406
end = contributor.end
407
contrib_word_start = (start // 32) * 32
408
start -= contrib_word_start
409
end -= contrib_word_start
410
411
value = str(field.exact) if field.exact is not None else "values->{}".format(contributor.path)
412
if field.modifier is not None:
413
if field.modifier[0] == "shr":
414
value = "{} >> {}".format(value, field.modifier[1])
415
elif field.modifier[0] == "minus":
416
value = "{} - {}".format(value, field.modifier[1])
417
elif field.modifier[0] == "align":
418
value = "ALIGN_POT({}, {})".format(value, field.modifier[1])
419
elif field.modifier[0] == "log2":
420
value = "util_logbase2({})".format(value)
421
422
if field.type in ["uint", "hex", "Pixel Format", "address"]:
423
s = "__gen_uint(%s, %d, %d)" % \
424
(value, start, end)
425
elif field.type in self.parser.enums:
426
s = "__gen_uint(%s, %d, %d)" % \
427
(value, start, end)
428
elif field.type == "int":
429
s = "__gen_sint(%s, %d, %d)" % \
430
(value, start, end)
431
elif field.type == "bool":
432
s = "__gen_uint(%s, %d, %d)" % \
433
(value, start, end)
434
elif field.type == "float":
435
assert(start == 0 and end == 31)
436
s = "__gen_uint(fui({}), 0, 32)".format(value)
437
else:
438
s = "#error unhandled field {}, type {}".format(contributor.path, field.type)
439
440
if not s == None:
441
shift = word_start - contrib_word_start
442
if shift:
443
s = "%s >> %d" % (s, shift)
444
445
if contributor == word.contributors[-1]:
446
print("%s %s;" % (prefix, s))
447
else:
448
print("%s %s |" % (prefix, s))
449
prefix = " "
450
451
continue
452
453
# Given a field (start, end) contained in word `index`, generate the 32-bit
454
# mask of present bits relative to the word
455
def mask_for_word(self, index, start, end):
456
field_word_start = index * 32
457
start -= field_word_start
458
end -= field_word_start
459
# Cap multiword at one word
460
start = max(start, 0)
461
end = min(end, 32 - 1)
462
count = (end - start + 1)
463
return (((1 << count) - 1) << start)
464
465
def emit_unpack_function(self):
466
# First, verify there is no garbage in unused bits
467
words = {}
468
self.collect_words(self.fields, 0, '', words)
469
470
for index in range(self.length // 4):
471
base = index * 32
472
word = words.get(index, self.Word())
473
masks = [self.mask_for_word(index, c.start, c.end) for c in word.contributors]
474
mask = reduce(lambda x,y: x | y, masks, 0)
475
476
ALL_ONES = 0xffffffff
477
478
if mask != ALL_ONES:
479
TMPL = ' if (((const uint32_t *) cl)[{}] & {}) fprintf(fp, "XXX: Unknown field of {} unpacked at word {}: got %X, bad mask %X\\n", ((const uint32_t *) cl)[{}], ((const uint32_t *) cl)[{}] & {});'
480
print(TMPL.format(index, hex(mask ^ ALL_ONES), self.label, index, index, index, hex(mask ^ ALL_ONES)))
481
482
fieldrefs = []
483
self.collect_fields(self.fields, 0, '', fieldrefs)
484
for fieldref in fieldrefs:
485
field = fieldref.field
486
convert = None
487
488
args = []
489
args.append('cl')
490
args.append(str(fieldref.start))
491
args.append(str(fieldref.end))
492
493
if field.type in set(["uint", "uint/float", "address", "Pixel Format", "hex"]) | self.parser.enums:
494
convert = "__gen_unpack_uint"
495
elif field.type == "int":
496
convert = "__gen_unpack_sint"
497
elif field.type == "bool":
498
convert = "__gen_unpack_uint"
499
elif field.type == "float":
500
convert = "__gen_unpack_float"
501
else:
502
s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
503
504
suffix = ""
505
prefix = ""
506
if field.modifier:
507
if field.modifier[0] == "minus":
508
suffix = " + {}".format(field.modifier[1])
509
elif field.modifier[0] == "shr":
510
suffix = " << {}".format(field.modifier[1])
511
if field.modifier[0] == "log2":
512
prefix = "1 << "
513
514
decoded = '{}{}({}){}'.format(prefix, convert, ', '.join(args), suffix)
515
516
print(' values->{} = {};'.format(fieldref.path, decoded))
517
if field.modifier and field.modifier[0] == "align":
518
mask = hex(field.modifier[1] - 1)
519
print(' assert(!(values->{} & {}));'.format(fieldref.path, mask))
520
521
def emit_print_function(self):
522
for field in self.fields:
523
convert = None
524
name, val = field.human_name, 'values->{}'.format(field.name)
525
526
if field.type in self.parser.structs:
527
pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
528
print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
529
print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
530
elif field.type == "address":
531
# TODO resolve to name
532
print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
533
elif field.type in self.parser.enums:
534
print(' if ({}_as_str({}))'.format(enum_name(field.type), val))
535
print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
536
print(' else')
537
print(' fprintf(fp, "%*s{}: unknown %X (XXX)\\n", indent, "", {});'.format(name, val))
538
elif field.type == "int":
539
print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
540
elif field.type == "bool":
541
print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
542
elif field.type == "float":
543
print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
544
elif field.type in ["uint", "hex"] and (field.end - field.start) >= 32:
545
print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
546
elif field.type == "hex":
547
print(' fprintf(fp, "%*s{}: 0x%" PRIx32 "\\n", indent, "", {});'.format(name, val))
548
elif field.type in "Pixel Format":
549
print(' agx_pixel_format_print(fp, {});'.format(val))
550
elif field.type == "uint/float":
551
print(' fprintf(fp, "%*s{}: 0x%X (%f)\\n", indent, "", {}, uif({}));'.format(name, val, val))
552
else:
553
print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
554
555
class Value(object):
556
def __init__(self, attrs):
557
self.name = attrs["name"]
558
self.value = int(attrs["value"], 0)
559
560
class Parser(object):
561
def __init__(self):
562
self.parser = xml.parsers.expat.ParserCreate()
563
self.parser.StartElementHandler = self.start_element
564
self.parser.EndElementHandler = self.end_element
565
566
self.struct = None
567
self.structs = {}
568
# Set of enum names we've seen.
569
self.enums = set()
570
571
def gen_prefix(self, name):
572
return '{}_{}'.format(global_prefix.upper(), name)
573
574
def start_element(self, name, attrs):
575
if name == "agxml":
576
print(pack_header)
577
elif name == "struct":
578
name = attrs["name"]
579
self.no_direct_packing = attrs.get("no-direct-packing", False)
580
object_name = self.gen_prefix(safe_name(name.upper()))
581
self.struct = object_name
582
583
self.group = Group(self, None, 0, 1, name)
584
if "size" in attrs:
585
self.group.length = int(attrs["size"])
586
self.group.align = int(attrs["align"]) if "align" in attrs else None
587
self.structs[attrs["name"]] = self.group
588
elif name == "field":
589
self.group.fields.append(Field(self, attrs))
590
self.values = []
591
elif name == "enum":
592
self.values = []
593
self.enum = safe_name(attrs["name"])
594
self.enums.add(attrs["name"])
595
if "prefix" in attrs:
596
self.prefix = attrs["prefix"]
597
else:
598
self.prefix= None
599
elif name == "value":
600
self.values.append(Value(attrs))
601
602
def end_element(self, name):
603
if name == "struct":
604
self.emit_struct()
605
self.struct = None
606
self.group = None
607
elif name == "field":
608
self.group.fields[-1].values = self.values
609
elif name == "enum":
610
self.emit_enum()
611
self.enum = None
612
elif name == "agxml":
613
print('#endif')
614
615
def emit_header(self, name):
616
default_fields = []
617
for field in self.group.fields:
618
if not type(field) is Field:
619
continue
620
if field.default is not None:
621
default_fields.append(" .{} = {}".format(field.name, field.default))
622
elif field.type in self.structs:
623
default_fields.append(" .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
624
625
print('#define %-40s\\' % (name + '_header'))
626
if default_fields:
627
print(", \\\n".join(default_fields))
628
else:
629
print(' 0')
630
print('')
631
632
def emit_template_struct(self, name, group):
633
print("struct %s {" % name)
634
group.emit_template_struct("")
635
print("};\n")
636
637
def emit_pack_function(self, name, group):
638
print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
639
(name, ' ' * (len(name) + 6), name))
640
641
group.emit_pack_function()
642
643
print("}\n\n")
644
645
print('#define {} {}'.format (name + "_LENGTH", self.group.length))
646
if self.group.align != None:
647
print('#define {} {}'.format (name + "_ALIGN", self.group.align))
648
print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
649
650
def emit_unpack_function(self, name, group):
651
print("static inline void")
652
print("%s_unpack(FILE *fp, const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
653
(name.upper(), ' ' * (len(name) + 8), name))
654
655
group.emit_unpack_function()
656
657
print("}\n")
658
659
def emit_print_function(self, name, group):
660
print("static inline void")
661
print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
662
663
group.emit_print_function()
664
665
print("}\n")
666
667
def emit_struct(self):
668
name = self.struct
669
670
self.emit_template_struct(self.struct, self.group)
671
self.emit_header(name)
672
if self.no_direct_packing == False:
673
self.emit_pack_function(self.struct, self.group)
674
self.emit_unpack_function(self.struct, self.group)
675
self.emit_print_function(self.struct, self.group)
676
677
def enum_prefix(self, name):
678
return
679
680
def emit_enum(self):
681
e_name = enum_name(self.enum)
682
prefix = e_name if self.enum != 'Format' else global_prefix
683
print('enum {} {{'.format(e_name))
684
685
for value in self.values:
686
name = '{}_{}'.format(prefix, value.name)
687
name = safe_name(name).upper()
688
print(' % -36s = %6d,' % (name, value.value))
689
print('};\n')
690
691
print("static inline const char *")
692
print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
693
print(" switch (imm) {")
694
for value in self.values:
695
name = '{}_{}'.format(prefix, value.name)
696
name = safe_name(name).upper()
697
print(' case {}: return "{}";'.format(name, value.name))
698
print(' default: break;')
699
print(" }")
700
print(" return NULL;")
701
print("}\n")
702
703
def parse(self, filename):
704
file = open(filename, "rb")
705
self.parser.ParseFile(file)
706
file.close()
707
708
if len(sys.argv) < 2:
709
print("No input xml file specified")
710
sys.exit(1)
711
712
input_file = sys.argv[1]
713
714
p = Parser()
715
p.parse(input_file)
716
717