]> sigrok.org Git - libsigrok.git/blob - bindings/cxx/enums.py
C++ bindings: Attach documentation to enum wrapper classes.
[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 xml.etree import ElementTree
21 from collections import OrderedDict
22 import sys, os, re
23
24 index_file = sys.argv[1]
25
26 # Get directory this script is in.
27 dirname = os.path.dirname(os.path.realpath(__file__))
28
29 mapping = dict([
30     ('sr_loglevel', ('LogLevel', 'Log verbosity level')),
31     ('sr_packettype', ('PacketType', 'Type of datafeed packet')),
32     ('sr_mq', ('Quantity', 'Measured quantity')),
33     ('sr_unit', ('Unit', 'Unit of measurement')),
34     ('sr_mqflag', ('QuantityFlag', 'Flag applied to measured quantity')),
35     ('sr_configkey', ('ConfigKey', 'Configuration key')),
36     ('sr_datatype', ('DataType', 'Configuration data type')),
37     ('sr_channeltype', ('ChannelType', 'Channel type')),
38     ('sr_trigger_matches', ('TriggerMatchType', 'Trigger match type'))])
39
40 index = ElementTree.parse(index_file)
41
42 # Build mapping between class names and enumerations.
43
44 classes = OrderedDict()
45
46 for compound in index.findall('compound'):
47     if compound.attrib['kind'] != 'file':
48         continue
49     filename = os.path.join(
50         os.path.dirname(index_file),
51         '%s.xml' % compound.attrib['refid'])
52     doc = ElementTree.parse(filename)
53     for section in doc.find('compounddef').findall('sectiondef'):
54         if section.attrib["kind"] != 'enum':
55             continue
56         for member in section.findall('memberdef'):
57             if member.attrib["kind"] != 'enum':
58                 continue
59             name = member.find('name').text
60             if name in mapping:
61                 classes[member] = mapping[name]
62
63 header = open(os.path.join(dirname, 'include/libsigrok/enums.hpp'), 'w')
64 code = open(os.path.join(dirname, 'enums.cpp'), 'w')
65
66 for file in (header, code):
67     print >> file, "/* Generated file - edit enums.py instead! */"
68
69 # Template for beginning of class declaration and public members.
70 header_public_template = """
71 /** {brief} */
72 class SR_API {classname} : public EnumValue<enum {enumname}>
73 {{
74 public:
75     static const {classname} *get(int id);
76 """
77
78 # Template for beginning of private members.
79 header_private_template = """
80 private:
81     static const std::map<enum {enumname}, const {classname} *> values;
82     {classname}(enum {enumname} id, const char name[]);
83 """
84
85 # Template for class method definitions.
86 code_template = """
87 {classname}::{classname}(enum {enumname} id, const char name[]) :
88     EnumValue<enum {enumname}>(id, name)
89 {{
90 }}
91
92 const {classname} *{classname}::get(int id)
93 {{
94     return {classname}::values.at(static_cast<{enumname}>(id));
95 }}
96 """
97
98 def get_text(node):
99     return str.join('\n\n',
100         [p.text.rstrip() for p in node.findall('para')])
101
102 for enum, (classname, classbrief) in classes.items():
103
104     enum_name = enum.find('name').text
105     members = enum.findall('enumvalue')
106     member_names = [m.find('name').text for m in members]
107     trimmed_names = [re.sub("^SR_[A-Z]+_", "", n) for n in member_names]
108     briefs = [get_text(m.find('briefdescription')) for m in members]
109
110     # Begin class and public declarations
111     print >> header, header_public_template.format(
112         brief=classbrief, classname=classname, enumname=enum_name)
113
114     # Declare public pointers for each enum value
115     for trimmed_name, brief in zip(trimmed_names, briefs):
116         if brief:
117             print >> header, '\t/** %s */' % brief
118         print >> header, '\tstatic const %s * const %s;' % (
119             classname, trimmed_name)
120
121     # Declare additional methods if present
122     filename = os.path.join(dirname, "%s_methods.hpp" % classname)
123     if os.path.exists(filename):
124         print >> header, str.join('', open(filename).readlines())
125
126     # Begin private declarations
127     print >> header, header_private_template.format(
128         classname=classname, enumname=enum_name)
129
130     # Declare private constants for each enum value
131     for trimmed_name in trimmed_names:
132         print >> header, '\tstatic const %s _%s;' % (classname, trimmed_name)
133
134     # End class declaration
135     print >> header, '};'
136
137     # Begin class code
138     print >> code, code_template.format(
139         classname=classname, enumname=enum_name)
140
141     # Define private constants for each enum value
142     for name, trimmed_name in zip(member_names, trimmed_names):
143         print >> code, 'const %s %s::_%s = %s(%s, "%s");' % (
144             classname, classname, trimmed_name, classname, name, trimmed_name)
145
146     # Define public pointers for each enum value
147     for trimmed_name in trimmed_names:
148         print >> code, 'const %s * const %s::%s = &%s::_%s;' % (
149             classname, classname, trimmed_name, classname, trimmed_name)
150
151     # Define map of enum values to constants
152     print >> code, 'const std::map<enum %s, const %s *> %s::values = {' % (
153         enum_name, classname, classname)
154     for name, trimmed_name in zip(member_names, trimmed_names):
155         print >> code, '\t{%s, %s::%s},' % (name, classname, trimmed_name)
156     print >> code, '};'
157
158     # Define additional methods if present
159     filename = os.path.join(dirname, "%s_methods.cpp" % classname)
160     if os.path.exists(filename):
161         print >> code, str.join('', open(filename).readlines())