1#!/usr/bin/env python
2# Copyright (c) 2016 Google Inc.
3
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""Generates the vendor tool table from the SPIR-V XML registry."""
16
17import errno
18import os.path
19import xml.etree.ElementTree
20
21
22def mkdir_p(directory):
23    """Make the directory, and all its ancestors as required.  Any of the
24    directories are allowed to already exist.
25    This is compatible with Python down to 3.0.
26    """
27
28    if directory == "":
29        # We're being asked to make the current directory.
30        return
31
32    try:
33        os.makedirs(directory)
34    except OSError as e:
35        if e.errno == errno.EEXIST and os.path.isdir(directory):
36            pass
37        else:
38            raise
39
40
41def generate_vendor_table(registry):
42    """Returns a list of C style initializers for the registered vendors
43    and their tools.
44
45    Args:
46      registry: The SPIR-V XMLregistry as an xml.ElementTree
47    """
48
49    lines = []
50    for ids in registry.iter('ids'):
51        if 'vendor' == ids.attrib['type']:
52            for an_id in ids.iter('id'):
53                value = an_id.attrib['value']
54                vendor = an_id.attrib['vendor']
55                if 'tool' in an_id.attrib:
56                    tool = an_id.attrib['tool']
57                    vendor_tool = vendor + ' ' + tool
58                else:
59                    tool = ''
60                    vendor_tool = vendor
61                line = '{' + '{}, "{}", "{}", "{}"'.format(value,
62                                                           vendor,
63                                                           tool,
64                                                           vendor_tool) + '},'
65                lines.append(line)
66    return '\n'.join(lines)
67
68
69def main():
70    import argparse
71    parser = argparse.ArgumentParser(description=
72                                     'Generate tables from SPIR-V XML registry')
73    parser.add_argument('--xml', metavar='<path>',
74                        type=str, required=True,
75                        help='SPIR-V XML Registry file')
76    parser.add_argument('--generator-output', metavar='<path>',
77                        type=str, required=True,
78                        help='output file for SPIR-V generators table')
79    args = parser.parse_args()
80
81    with open(args.xml) as xml_in:
82       registry = xml.etree.ElementTree.fromstring(xml_in.read())
83
84    mkdir_p(os.path.dirname(args.generator_output))
85    with open(args.generator_output, 'w') as f:
86      f.write(generate_vendor_table(registry))
87
88
89if __name__ == '__main__':
90    main()
91