summaryrefslogtreecommitdiffstats
path: root/src/vulkan/util/gen_enum_to_str.py
blob: 5357278ded109abe6765d76df9d19189b87b597f (plain)
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# encoding=utf-8
# Copyright © 2017 Intel Corporation

# 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.

"""Create enum to string functions for vulkan using vk.xml."""

from __future__ import print_function
import argparse
import os
import textwrap
import xml.etree.cElementTree as et

from mako.template import Template

COPYRIGHT = textwrap.dedent(u"""\
    * Copyright © 2017 Intel Corporation
    *
    * 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.""")

C_TEMPLATE = Template(textwrap.dedent(u"""\
    /* Autogenerated file -- do not edit
     * generated by ${file}
     *
     ${copyright}
     */

    #include <string.h>
    #include <vulkan/vulkan.h>
    #include <vulkan/vk_android_native_buffer.h>
    #include "util/macros.h"
    #include "vk_enum_to_str.h"

    % for enum in enums:

      % if enum.guard:
#ifdef ${enum.guard}
      % endif
    const char *
    vk_${enum.name[2:]}_to_str(${enum.name} input)
    {
        switch(input) {
        % for v in sorted(enum.values.keys()):
            % if enum.values[v] in FOREIGN_ENUM_VALUES:

            #pragma GCC diagnostic push
            #pragma GCC diagnostic ignored "-Wswitch"
            % endif
            case ${v}:
                return "${enum.values[v]}";
            % if enum.values[v] in FOREIGN_ENUM_VALUES:
            #pragma GCC diagnostic pop

            % endif
        % endfor
        default:
            unreachable("Undefined enum value.");
        }
    }

      % if enum.guard:
#endif
      % endif
    %endfor

    size_t vk_structure_type_size(const struct VkBaseInStructure *item)
    {
        switch(item->sType) {
    % for struct in structs:
        % if struct.extension is not None and struct.extension.define is not None:
    #ifdef ${struct.extension.define}
        case ${struct.stype}: return sizeof(${struct.name});
    #endif
        % else:
        case ${struct.stype}: return sizeof(${struct.name});
        % endif
    %endfor
        default:
            unreachable("Undefined struct type.");
        }
    }

    void vk_load_instance_commands(VkInstance instance,
                                   PFN_vkGetInstanceProcAddr gpa,
                                   struct vk_instance_dispatch_table *table)
    {
        memset(table, 0, sizeof(*table));
        table->GetInstanceProcAddr = gpa;
    % for cmd in commands:
        % if not cmd.device_entrypoint and cmd.name != 'vkGetInstanceProcAddr':
            % if cmd.extension is not None and cmd.extension.define is not None:
    #ifdef ${cmd.extension.define}
        table->${cmd.name[2:]} = (PFN_${cmd.name}) gpa(instance, "${cmd.name}");
    #endif
            % else:
        table->${cmd.name[2:]} = (PFN_${cmd.name}) gpa(instance, "${cmd.name}");
            % endif
        % endif
    %endfor
    }

    void vk_load_device_commands(VkDevice device,
                                 PFN_vkGetDeviceProcAddr gpa,
                                 struct vk_device_dispatch_table *table)
    {
        memset(table, 0, sizeof(*table));
        table->GetDeviceProcAddr = gpa;
    % for cmd in commands:
        % if cmd.device_entrypoint and cmd.name != 'vkGetDeviceProcAddr':
            % if cmd.extension is not None and cmd.extension.define is not None:
    #ifdef ${cmd.extension.define}
        table->${cmd.name[2:]} = (PFN_${cmd.name}) gpa(device, "${cmd.name}");
    #endif
            % else:
        table->${cmd.name[2:]} = (PFN_${cmd.name}) gpa(device, "${cmd.name}");
            % endif
        % endif
    %endfor
    }
    """),
    output_encoding='utf-8')

H_TEMPLATE = Template(textwrap.dedent(u"""\
    /* Autogenerated file -- do not edit
     * generated by ${file}
     *
     ${copyright}
     */

    #ifndef MESA_VK_ENUM_TO_STR_H
    #define MESA_VK_ENUM_TO_STR_H

    #include <vulkan/vulkan.h>
    #include <vulkan/vk_android_native_buffer.h>

    #ifdef __cplusplus
    extern "C" {
    #endif

    % for ext in extensions:
    #define _${ext.name}_number (${ext.number})
    % endfor

    % for enum in enums:
      % if enum.guard:
#ifdef ${enum.guard}
      % endif
    const char * vk_${enum.name[2:]}_to_str(${enum.name} input);
      % if enum.guard:
#endif
      % endif
    % endfor

    size_t vk_structure_type_size(const struct VkBaseInStructure *item);

    struct vk_instance_dispatch_table {
        PFN_vkGetInstanceProcAddr GetInstanceProcAddr;
    % for cmd in commands:
        % if not cmd.device_entrypoint and cmd.name != 'vkGetInstanceProcAddr':
            % if cmd.extension is not None and cmd.extension.define is not None:
    #ifdef ${cmd.extension.define}
        PFN_${cmd.name} ${cmd.name[2:]};
    #endif
            % else:
        PFN_${cmd.name} ${cmd.name[2:]};
            % endif
        % endif
    %endfor
    };

    struct vk_device_dispatch_table {
        PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
    % for cmd in commands:
        % if cmd.device_entrypoint and cmd.name != 'vkGetDeviceProcAddr':
            % if cmd.extension is not None and cmd.extension.define is not None:
    #ifdef ${cmd.extension.define}
        PFN_${cmd.name} ${cmd.name[2:]};
    #endif
            % else:
        PFN_${cmd.name} ${cmd.name[2:]};
            % endif
        % endif
    %endfor
    };

    void vk_load_instance_commands(VkInstance instance, PFN_vkGetInstanceProcAddr gpa, struct vk_instance_dispatch_table *table);
    void vk_load_device_commands(VkDevice device, PFN_vkGetDeviceProcAddr gpa, struct vk_device_dispatch_table *table);

    #ifdef __cplusplus
    } /* extern "C" */
    #endif

    #endif"""),
    output_encoding='utf-8')

# These enums are defined outside their respective enum blocks, and thus cause
# -Wswitch warnings.
FOREIGN_ENUM_VALUES = [
    "VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID",
]


class NamedFactory(object):
    """Factory for creating enums."""

    def __init__(self, type_):
        self.registry = {}
        self.type = type_

    def __call__(self, name, **kwargs):
        try:
            return self.registry[name]
        except KeyError:
            n = self.registry[name] = self.type(name, **kwargs)
        return n

    def get(self, name):
        return self.registry.get(name)


class VkExtension(object):
    """Simple struct-like class representing extensions"""

    def __init__(self, name, number=None, define=None):
        self.name = name
        self.number = number
        self.define = define


class VkEnum(object):
    """Simple struct-like class representing a single Vulkan Enum."""

    def __init__(self, name, values=None):
        self.name = name
        self.extension = None
        # Maps numbers to names
        self.values = values or dict()
        self.name_to_value = dict()
        self.guard = None

    def add_value(self, name, value=None,
                  extnum=None, offset=None,
                  error=False):
        assert value is not None or extnum is not None
        if value is None:
            value = 1000000000 + (extnum - 1) * 1000 + offset
            if error:
                value = -value

        self.name_to_value[name] = value
        if value not in self.values:
            self.values[value] = name
        elif len(self.values[value]) > len(name):
            self.values[value] = name

    def add_value_from_xml(self, elem, extension=None):
        self.extension = extension
        if 'value' in elem.attrib:
            self.add_value(elem.attrib['name'],
                           value=int(elem.attrib['value'], base=0))
        elif 'alias' in elem.attrib:
            self.add_value(elem.attrib['name'],
                           value=self.name_to_value[elem.attrib['alias']])
        else:
            error = 'dir' in elem.attrib and elem.attrib['dir'] == '-'
            if 'extnumber' in elem.attrib:
                extnum = int(elem.attrib['extnumber'])
            else:
                extnum = extension.number
            self.add_value(elem.attrib['name'],
                           extnum=extnum,
                           offset=int(elem.attrib['offset']),
                           error=error)

    def set_guard(self, g):
        self.guard = g


class VkCommand(object):
    """Simple struct-like class representing a single Vulkan command"""

    def __init__(self, name, device_entrypoint=False):
        self.name = name
        self.device_entrypoint = device_entrypoint
        self.extension = None


class VkChainStruct(object):
    """Simple struct-like class representing a single Vulkan struct identified with a VkStructureType"""
    def __init__(self, name, stype):
        self.name = name
        self.stype = stype
        self.extension = None


def struct_get_stype(xml_node):
    for member in xml_node.findall('./member'):
        name = member.findall('./name')
        if len(name) > 0 and name[0].text == "sType":
            return member.get('values')
    return None


def parse_xml(cmd_factory, enum_factory, ext_factory, struct_factory, filename):
    """Parse the XML file. Accumulate results into the factories.

    This parser is a memory efficient iterative XML parser that returns a list
    of VkEnum objects.
    """

    xml = et.parse(filename)

    for enum_type in xml.findall('./enums[@type="enum"]'):
        enum = enum_factory(enum_type.attrib['name'])
        for value in enum_type.findall('./enum'):
            enum.add_value_from_xml(value)

    for value in xml.findall('./feature/require/enum[@extends]'):
        enum = enum_factory.get(value.attrib['extends'])
        if enum is not None:
            enum.add_value_from_xml(value)

    for command in xml.findall('./commands/command'):
        name = command.find('./proto/name')
        first_arg = command.find('./param/type')
        # Some commands are alias KHR -> nonKHR, ignore those
        if name is not None:
            cmd_factory(name.text,
                        device_entrypoint=(first_arg.text in ('VkDevice', 'VkCommandBuffer', 'VkQueue')))

    for struct_type in xml.findall('./types/type[@category="struct"]'):
        name = struct_type.attrib['name']
        stype = struct_get_stype(struct_type)
        if stype is not None:
            struct_factory(name, stype=stype)

    platform_define = {}
    for platform in xml.findall('./platforms/platform'):
        name = platform.attrib['name']
        define = platform.attrib['protect']
        platform_define[name] = define

    for ext_elem in xml.findall('./extensions/extension[@supported="vulkan"]'):
        define = None
        if "platform" in ext_elem.attrib:
            define = platform_define[ext_elem.attrib['platform']]
        extension = ext_factory(ext_elem.attrib['name'],
                                number=int(ext_elem.attrib['number']),
                                define=define)

        for value in ext_elem.findall('./require/enum[@extends]'):
            enum = enum_factory.get(value.attrib['extends'])
            if enum is not None:
                enum.add_value_from_xml(value, extension)
        for t in ext_elem.findall('./require/type'):
            struct = struct_factory.get(t.attrib['name'])
            if struct is not None:
                struct.extension = extension

        if define:
            for value in ext_elem.findall('./require/type[@name]'):
                enum = enum_factory.get(value.attrib['name'])
                if enum is not None:
                    enum.set_guard(define)

        for t in ext_elem.findall('./require/command'):
            command = cmd_factory.get(t.attrib['name'])
            if command is not None:
                command.extension = extension


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--xml', required=True,
                        help='Vulkan API XML files',
                        action='append',
                        dest='xml_files')
    parser.add_argument('--outdir',
                        help='Directory to put the generated files in',
                        required=True)

    args = parser.parse_args()

    command_factory = NamedFactory(VkCommand)
    enum_factory = NamedFactory(VkEnum)
    ext_factory = NamedFactory(VkExtension)
    struct_factory = NamedFactory(VkChainStruct)
    for filename in args.xml_files:
        parse_xml(command_factory, enum_factory, ext_factory, struct_factory, filename)
    commands = sorted(command_factory.registry.values(), key=lambda e: e.name)
    enums = sorted(enum_factory.registry.values(), key=lambda e: e.name)
    extensions = sorted(ext_factory.registry.values(), key=lambda e: e.name)
    structs = sorted(struct_factory.registry.values(), key=lambda e: e.name)

    for template, file_ in [(C_TEMPLATE, os.path.join(args.outdir, 'vk_enum_to_str.c')),
                            (H_TEMPLATE, os.path.join(args.outdir, 'vk_enum_to_str.h'))]:
        with open(file_, 'wb') as f:
            f.write(template.render(
                file=os.path.basename(__file__),
                commands=commands,
                enums=enums,
                extensions=extensions,
                structs=structs,
                copyright=COPYRIGHT,
                FOREIGN_ENUM_VALUES=FOREIGN_ENUM_VALUES))


if __name__ == '__main__':
    main()