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