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