python scripts: Generate file header with #include statements

This commit is contained in:
Harald Welte 2017-01-22 23:35:25 +01:00
parent 78ced2084d
commit d248204bb7
2 changed files with 34 additions and 11 deletions

View File

@ -20,7 +20,7 @@
from optparse import OptionParser
import pprint
from pycparser import c_parser, c_ast, parse_file
from value_string import export_value_str
from value_string import *
class EnumValStrVisitor(c_ast.NodeVisitor):
"Generate a 'struct value_string' from an enum"
@ -30,7 +30,7 @@ class EnumValStrVisitor(c_ast.NodeVisitor):
vdict = {}
for val in elist.enumerators:
vdict[val.name] = val.name
export_value_str(name, vdict, sort_key=None)
wr.export_value_str(name, vdict, sort_key=None)
class EnumValuePrinter(c_ast.NodeVisitor):
def visit_Enum(self, node):
@ -49,11 +49,19 @@ class EnumValuePrinter(c_ast.NodeVisitor):
parser = OptionParser()
parser.add_option("-f", "--flavor", dest="flavor", default='osmocom',
help="Flavor of generated C (osmocom, wireshark)")
parser.add_option("-w", "--weak-symbol", dest="weak", default=True,
help="Generate weak symbols")
(options, args) = parser.parse_args()
filename = args[0]
ast = parse_file(filename, use_cpp=True)
wr = ValueStringWriter(flavor=options.flavor, weak=options.weak,
includes=[filename])
wr.export_header()
v = EnumValStrVisitor()
#v = EnumValuePrinter()
v.visit(ast)

View File

@ -17,13 +17,28 @@
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
class ValueStringWriter(object):
def __init__(self, flavor='osmocom', weak=False, includes=[]):
self.flavor = flavor
self.weak = weak
self.includes = includes
def export_value_str(name, vals, flavor='osmocom', sort_key=int):
if flavor == 'osmocom':
print("const struct value_string %s[] = {" % name);
elif flavor == 'wireshark':
print("const value_string %s[] = {" % name);
for v in sorted(vals.iterkeys(), key=sort_key):
print("\t{ %s, \"%s\" }," % (v, vals[v]));
print("\t{ 0, NULL }")
print("};");
def export_value_str(self, name, vals, sort_key=int):
if self.weak:
print("__attribute__((weak))")
if self.flavor == 'osmocom':
print("const struct value_string %s[] = {" % name);
elif self.flavor == 'wireshark':
print("const value_string %s[] = {" % name);
for v in sorted(vals.iterkeys(), key=sort_key):
print("\t{ %s, \"%s\" }," % (v, vals[v]));
print("\t{ 0, NULL }")
print("};");
def export_header(self):
print("/* GENERATED FILE, DO NOT EDIT */")
if self.flavor == 'osmocom':
print("#include <osmocom/core/utils.h>")
for i in self.includes:
print('#include "%s"' % i)
print("")