]> sigrok.org Git - libsigrok.git/blob - bindings/cxx/enums.py
90120d7f9fe85c43146a300ba17901c692657b8d
[libsigrok.git] / bindings / cxx / enums.py
1 ##
2 ## This file is part of the libsigrok project.
3 ##
4 ## Copyright (C) 2014 Martin Ling <martin-sigrok@earth.li>
5 ##
6 ## This program is free software: you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation, either version 3 of the License, or
9 ## (at your option) any later version.
10 ##
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ## GNU General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 ##
19
20 from __future__ import print_function
21 from xml.etree import ElementTree
22 from collections import OrderedDict
23 import sys, os, re
24
25 index_file = sys.argv[1]
26
27 # Get directory this script is in.
28 dirname = os.path.dirname(os.path.realpath(__file__))
29
30 outdirname = "bindings/cxx"
31 if not os.path.exists(os.path.join(outdirname, 'include/libsigrokcxx')):
32     os.makedirs(os.path.join(outdirname, 'include/libsigrokcxx'))
33
34 mapping = dict([
35     ('sr_loglevel', ('LogLevel', 'Log verbosity level')),
36     ('sr_packettype', ('PacketType', 'Type of datafeed packet')),
37     ('sr_mq', ('Quantity', 'Measured quantity')),
38     ('sr_unit', ('Unit', 'Unit of measurement')),
39     ('sr_mqflag', ('QuantityFlag', 'Flag applied to measured quantity')),
40     ('sr_configkey', ('ConfigKey', 'Configuration key')),
41     ('sr_datatype', ('DataType', 'Configuration data type')),
42     ('sr_channeltype', ('ChannelType', 'Channel type')),
43     ('sr_trigger_matches', ('TriggerMatchType', 'Trigger match type')),
44     ('sr_output_flag', ('OutputFlag', 'Flag applied to output modules'))])
45
46 index = ElementTree.parse(index_file)
47
48 # Build mapping between class names and enumerations.
49
50 classes = OrderedDict()
51
52 for compound in index.findall('compound'):
53     if compound.attrib['kind'] != 'file':
54         continue
55     filename = os.path.join(
56         os.path.dirname(index_file),
57         '%s.xml' % compound.attrib['refid'])
58     doc = ElementTree.parse(filename)
59     for section in doc.find('compounddef').findall('sectiondef'):
60         if section.attrib["kind"] != 'enum':
61             continue
62         for member in section.findall('memberdef'):
63             if member.attrib["kind"] != 'enum':
64                 continue
65             name = member.find('name').text
66             if name in mapping:
67                 classes[member] = mapping[name]
68
69 header = open(os.path.join(outdirname, 'include/libsigrokcxx/enums.hpp'), 'w')
70 code = open(os.path.join(outdirname, 'enums.cpp'), 'w')
71 swig = open(os.path.join(dirname, '../swig/enums.i'), 'w')
72
73 for file in (header, code):
74     print("/* Generated file - edit enums.py instead! */", file=file)
75
76 # Template for beginning of class declaration and public members.
77 header_public_template = """
78 /** {brief} */
79 class SR_API {classname} : public EnumValue<{classname}, enum {enumname}>
80 {{
81 public:
82 """
83
84 # Template for beginning of private members.
85 header_private_template = """
86 protected:
87     {classname}(enum {enumname} id, const char name[]) : EnumValue(id, name) {{}}
88 """
89
90 def get_text(node):
91     return str.join('\n\n',
92         [p.text.rstrip() for p in node.findall('para')])
93
94 for enum, (classname, classbrief) in classes.items():
95
96     enum_name = enum.find('name').text
97     members = enum.findall('enumvalue')
98     member_names = [m.find('name').text for m in members]
99     trimmed_names = [re.sub("^SR_[A-Z]+_", "", n) for n in member_names]
100     briefs = [get_text(m.find('briefdescription')) for m in members]
101
102     # Begin class and public declarations
103     print(header_public_template.format(
104         brief=classbrief, classname=classname, enumname=enum_name), file=header)
105
106     # Declare public pointers for each enum value
107     for trimmed_name, brief in zip(trimmed_names, briefs):
108         if brief:
109             print('\t/** %s */' % brief, file=header)
110         print('\tstatic const %s * const %s;' % (
111             classname, trimmed_name), file=header)
112
113     # Declare additional methods if present
114     filename = os.path.join(dirname, "%s_methods.hpp" % classname)
115     if os.path.exists(filename):
116         print(str.join('', open(filename).readlines()), file=header)
117
118     # Begin private declarations
119     print(header_private_template.format(
120         classname=classname, enumname=enum_name), file=header)
121
122     # Declare private constants for each enum value
123     for trimmed_name in trimmed_names:
124         print('\tstatic const %s _%s;' % (classname, trimmed_name), file=header)
125
126     # End class declaration
127     print('};', file=header)
128
129     # Define private constants for each enum value
130     for name, trimmed_name in zip(member_names, trimmed_names):
131         print('const %s %s::_%s = %s(%s, "%s");' % (
132             classname, classname, trimmed_name, classname, name, trimmed_name),
133             file=code)
134
135     # Define public pointers for each enum value
136     for trimmed_name in trimmed_names:
137         print('const %s * const %s::%s = &%s::_%s;' % (
138             classname, classname, trimmed_name, classname, trimmed_name),
139             file=code)
140
141     # Define map of enum values to constants
142     print('template<> const SR_API std::map<const enum %s, const %s * const> EnumValue<%s, enum %s>::_values = {' % (
143         enum_name, classname, classname, enum_name), file=code)
144     for name, trimmed_name in zip(member_names, trimmed_names):
145         print('\t{%s, %s::%s},' % (name, classname, trimmed_name), file=code)
146     print('};', file=code)
147
148     # Define additional methods if present
149     filename = os.path.join(dirname, "%s_methods.cpp" % classname)
150     if os.path.exists(filename):
151         print(str.join('', open(filename).readlines()), file=code)
152
153     # Map EnumValue::id() and EnumValue::name() as SWIG attributes.
154     print('%%attribute(sigrok::%s, int, id, id);' % classname, file=swig)
155     print('%%attributestring(sigrok::%s, std::string, name, name);' % classname,
156         file=swig)
157
158     # Instantiate EnumValue template for SWIG
159     print('%%template(EnumValue%s) sigrok::EnumValue<sigrok::%s, enum %s>;' % (
160         classname, classname, enum_name), file=swig)
161
162     # Apply any language-specific extras.
163     print('%%enumextras(%s);' % classname, file=swig)
164
165     # Declare additional attributes if present
166     filename = os.path.join(dirname, "%s_methods.i" % classname)
167     if os.path.exists(filename):
168         print(str.join('', open(filename).readlines()), file=swig)