]> sigrok.org Git - libsigrok.git/blob - bindings/cxx/enums.py
C++: Declare namespace in enums.hpp so it can be used independently.
[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"
31 if not os.path.exists(os.path.join(outdirname, 'cxx/include/libsigrokcxx')):
32     os.makedirs(os.path.join(outdirname, 'cxx/include/libsigrokcxx'))
33 if not os.path.exists(os.path.join(outdirname, 'swig')):
34     os.makedirs(os.path.join(outdirname, 'swig'))
35
36 mapping = dict([
37     ('sr_loglevel', ('LogLevel', 'Log verbosity level')),
38     ('sr_packettype', ('PacketType', 'Type of datafeed packet')),
39     ('sr_mq', ('Quantity', 'Measured quantity')),
40     ('sr_unit', ('Unit', 'Unit of measurement')),
41     ('sr_mqflag', ('QuantityFlag', 'Flag applied to measured quantity')),
42     ('sr_configkey', ('ConfigKey', 'Configuration key')),
43     ('sr_datatype', ('DataType', 'Configuration data type')),
44     ('sr_channeltype', ('ChannelType', 'Channel type')),
45     ('sr_trigger_matches', ('TriggerMatchType', 'Trigger match type')),
46     ('sr_output_flag', ('OutputFlag', 'Flag applied to output modules'))])
47
48 index = ElementTree.parse(index_file)
49
50 # Build mapping between class names and enumerations.
51
52 classes = OrderedDict()
53
54 for compound in index.findall('compound'):
55     if compound.attrib['kind'] != 'file':
56         continue
57     filename = os.path.join(
58         os.path.dirname(index_file),
59         '%s.xml' % compound.attrib['refid'])
60     doc = ElementTree.parse(filename)
61     for section in doc.find('compounddef').findall('sectiondef'):
62         if section.attrib["kind"] != 'enum':
63             continue
64         for member in section.findall('memberdef'):
65             if member.attrib["kind"] != 'enum':
66                 continue
67             name = member.find('name').text
68             if name in mapping:
69                 classes[member] = mapping[name]
70
71 header = open(os.path.join(outdirname, 'cxx/include/libsigrokcxx/enums.hpp'), 'w')
72 code = open(os.path.join(outdirname, 'cxx/enums.cpp'), 'w')
73 swig = open(os.path.join(outdirname, 'swig/enums.i'), 'w')
74
75 for file in (header, code):
76     print("/* Generated file - edit enums.py instead! */", file=file)
77
78 print("namespace sigrok {", file=header)
79
80 # Template for beginning of class declaration and public members.
81 header_public_template = """
82 /** {brief} */
83 class SR_API {classname} : public EnumValue<{classname}, enum {enumname}>
84 {{
85 public:
86 """
87
88 # Template for beginning of private members.
89 header_private_template = """
90 protected:
91     {classname}(enum {enumname} id, const char name[]) : EnumValue(id, name) {{}}
92 """
93
94 def get_text(node):
95     return str.join('\n\n',
96         [p.text.rstrip() for p in node.findall('para')])
97
98 for enum, (classname, classbrief) in classes.items():
99
100     enum_name = enum.find('name').text
101     members = enum.findall('enumvalue')
102     member_names = [m.find('name').text for m in members]
103     trimmed_names = [re.sub("^SR_[A-Z]+_", "", n) for n in member_names]
104     briefs = [get_text(m.find('briefdescription')) for m in members]
105
106     # Begin class and public declarations
107     print(header_public_template.format(
108         brief=classbrief, classname=classname, enumname=enum_name), file=header)
109
110     # Declare public pointers for each enum value
111     for trimmed_name, brief in zip(trimmed_names, briefs):
112         if brief:
113             print('\t/** %s */' % brief, file=header)
114         print('\tstatic const %s * const %s;' % (
115             classname, trimmed_name), file=header)
116
117     # Declare additional methods if present
118     filename = os.path.join(dirname, "%s_methods.hpp" % classname)
119     if os.path.exists(filename):
120         print(str.join('', open(filename).readlines()), file=header)
121
122     # Begin private declarations
123     print(header_private_template.format(
124         classname=classname, enumname=enum_name), file=header)
125
126     # Declare private constants for each enum value
127     for trimmed_name in trimmed_names:
128         print('\tstatic const %s _%s;' % (classname, trimmed_name), file=header)
129
130     # End class declaration
131     print('};', file=header)
132
133     # Define private constants for each enum value
134     for name, trimmed_name in zip(member_names, trimmed_names):
135         print('const %s %s::_%s = %s(%s, "%s");' % (
136             classname, classname, trimmed_name, classname, name, trimmed_name),
137             file=code)
138
139     print('%%typemap(javacode) sigrok::%s %%{' % classname, file=swig)
140
141     # Define public pointers for each enum value
142     for trimmed_name in trimmed_names:
143         print('const %s * const %s::%s = &%s::_%s;' % (
144             classname, classname, trimmed_name, classname, trimmed_name),
145             file=code)
146         print('public static final %s %s = new %s(classesJNI.%s_%s_get(), false);' % (
147             classname, trimmed_name, classname, classname, trimmed_name),
148             file=swig)
149
150     print ('%}', file=swig)
151
152
153     # Define map of enum values to constants
154     print('template<> const SR_API std::map<const enum %s, const %s * const> EnumValue<%s, enum %s>::_values = {' % (
155         enum_name, classname, classname, enum_name), file=code)
156     for name, trimmed_name in zip(member_names, trimmed_names):
157         print('\t{%s, %s::%s},' % (name, classname, trimmed_name), file=code)
158     print('};', file=code)
159
160     # Define additional methods if present
161     filename = os.path.join(dirname, "%s_methods.cpp" % classname)
162     if os.path.exists(filename):
163         print(str.join('', open(filename).readlines()), file=code)
164
165     # Map EnumValue::id() and EnumValue::name() as SWIG attributes.
166     print('%%attribute(sigrok::%s, int, id, id);' % classname, file=swig)
167     print('%%attributestring(sigrok::%s, std::string, name, name);' % classname,
168         file=swig)
169
170     # Instantiate EnumValue template for SWIG
171     print('%%template(EnumValue%s) sigrok::EnumValue<sigrok::%s, enum %s>;' % (
172         classname, classname, enum_name), file=swig)
173
174     # Apply any language-specific extras.
175     print('%%enumextras(%s);' % classname, file=swig)
176
177     # Declare additional attributes if present
178     filename = os.path.join(dirname, "%s_methods.i" % classname)
179     if os.path.exists(filename):
180         print(str.join('', open(filename).readlines()), file=swig)
181
182 print("}", file=header)