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