android: vulkan: add support for libmesa_vulkan_util
[mesa.git] / src / vulkan / util / gen_enum_to_str.py
1 # encoding=utf-8
2 # Copyright © 2017 Intel Corporation
3
4 # Permission is hereby granted, free of charge, to any person obtaining a copy
5 # of this software and associated documentation files (the "Software"), to deal
6 # in the Software without restriction, including without limitation the rights
7 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 # copies of the Software, and to permit persons to whom the Software is
9 # furnished to do so, subject to the following conditions:
10
11 # The above copyright notice and this permission notice shall be included in
12 # all copies or substantial portions of the Software.
13
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 # SOFTWARE.
21
22 """Create enum to string functions for vulking using vk.xml."""
23
24 from __future__ import print_function
25 import argparse
26 import os
27 import textwrap
28 import xml.etree.cElementTree as et
29
30 from mako.template import Template
31
32 VK_XML = os.path.join(os.path.dirname(__file__), '..', 'registry', 'vk.xml')
33
34 COPYRIGHT = textwrap.dedent(u"""\
35 * Copyright © 2017 Intel Corporation
36 *
37 * Permission is hereby granted, free of charge, to any person obtaining a copy
38 * of this software and associated documentation files (the "Software"), to deal
39 * in the Software without restriction, including without limitation the rights
40 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
41 * copies of the Software, and to permit persons to whom the Software is
42 * furnished to do so, subject to the following conditions:
43 *
44 * The above copyright notice and this permission notice shall be included in
45 * all copies or substantial portions of the Software.
46 *
47 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
48 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
49 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
50 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
51 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
52 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
53 * SOFTWARE.""")
54
55 C_TEMPLATE = Template(textwrap.dedent(u"""\
56 /* Autogenerated file -- do not edit
57 * generated by ${file}
58 *
59 ${copyright}
60 */
61
62 #include <vulkan/vulkan.h>
63 #include "util/macros.h"
64 #include "vk_enum_to_str.h"
65
66 % for enum in enums:
67
68 const char *
69 vk_${enum.name[2:]}_to_str(${enum.name} input)
70 {
71 switch(input) {
72 % for v in enum.values:
73 case ${v}:
74 return "${v}";
75 % endfor
76 default:
77 unreachable("Undefined enum value.");
78 }
79 }
80 %endfor"""),
81 output_encoding='utf-8')
82
83 H_TEMPLATE = Template(textwrap.dedent(u"""\
84 /* Autogenerated file -- do not edit
85 * generated by ${file}
86 *
87 ${copyright}
88 */
89
90 #ifndef MESA_VK_ENUM_TO_STR_H
91 #define MESA_VK_ENUM_TO_STR_H
92
93 #include <vulkan/vulkan.h>
94
95 % for enum in enums:
96 const char * vk_${enum.name[2:]}_to_str(${enum.name} input);
97 % endfor
98
99 #endif"""),
100 output_encoding='utf-8')
101
102
103 class EnumFactory(object):
104 """Factory for creating enums."""
105
106 def __init__(self, type_):
107 self.registry = {}
108 self.type = type_
109
110 def __call__(self, name):
111 try:
112 return self.registry[name]
113 except KeyError:
114 n = self.registry[name] = self.type(name)
115 return n
116
117
118 class VkEnum(object):
119 """Simple struct-like class representing a single Vulkan Enum."""
120
121 def __init__(self, name, values=None):
122 self.name = name
123 self.values = values or []
124
125
126 def xml_parser(filename):
127 """Parse the XML file and return parsed data.
128
129 This parser is a memory efficient iterative XML parser that returns a list
130 of VkEnum objects.
131 """
132 efactory = EnumFactory(VkEnum)
133
134 with open(filename, 'rb') as f:
135 context = iter(et.iterparse(f, events=('start', 'end')))
136
137 # This gives the root element, since goal is to iterate over the
138 # elements without building a tree, this allows the root to be cleared
139 # (erase the elements) after the children have been processed.
140 _, root = next(context)
141
142 for event, elem in context:
143 if event == 'end' and elem.tag == 'enums':
144 type_ = elem.attrib.get('type')
145 if type_ == 'enum':
146 enum = efactory(elem.attrib['name'])
147 enum.values.extend([e.attrib['name'] for e in elem
148 if e.tag == 'enum'])
149 elif event == 'end' and elem.tag == 'extension':
150 if elem.attrib['supported'] != 'vulkan':
151 continue
152 for e in elem.findall('.//enum[@extends][@offset]'):
153 enum = efactory(e.attrib['extends'])
154 enum.values.append(e.attrib['name'])
155
156 root.clear()
157
158 return efactory.registry.values()
159
160
161 def main():
162 parser = argparse.ArgumentParser()
163 parser.add_argument('--outdir',
164 help='Directory to put the generated files in',
165 required=True)
166
167 args = parser.parse_args()
168
169 enums = xml_parser(VK_XML)
170 for template, file_ in [(C_TEMPLATE, os.path.join(args.outdir, 'vk_enum_to_str.c')),
171 (H_TEMPLATE, os.path.join(args.outdir, 'vk_enum_to_str.h'))]:
172 with open(file_, 'wb') as f:
173 f.write(template.render(
174 file=os.path.basename(__file__),
175 enums=enums,
176 copyright=COPYRIGHT))
177
178
179 if __name__ == '__main__':
180 main()