-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcfunctionwrapper.py
293 lines (234 loc) · 10.6 KB
/
cfunctionwrapper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import loadpath
import os
import sys
import texttemplates
import getopt
from cpp import ast
from cfwclasses import *
import yaml
PATH_SEPARATOR = ';' if os.name == 'nt' else ':'
BASE_INCLUDE = 'CWrappers'
USAGE = 'Usage:\n\n' + __file__ + ''' functionList [-i include_path] [-n] [-b base_namespace]
[-m mock_namespace] [-c component_namespace] [-p funcPrefix]
[-s component_suffix]'''
DESCRIPTION = '''
Generate C++ C-function wrapper classes
Precondition: The INCLUDE environment variable must be set
-n = Disable generateGmock
function_file [Required] Path to a file containing a list of C function
names to wrap
include_path [Default: The INCLUDE environment variable] C compiler
include path. This should be a list of directories
separated by ';' on Windows and ':' on Unix
generateGmock [Default: True] Whether or not to generate GMock style
mock classes
base_namespace [Default: ''] Base class namespace
mock_namespace [Default: 'Mock'] Name of mock namespace. Fully qualified
namespace will become base_namespace::mock_namespace
component_namespace [Default: 'Component'] Name of component namespace. Fully
qualified namespace will become
base_namespace::component_namespace
funcPrefix [Default: 'my'] Prefix to wrapper functions. This is used
to prevent colliding with the wrapped C function
component_suffix [Default: 'Wrapper'] Suffix that will be appended to class
names of generated Component classes
'''
def generate(function_file, include_path = '', generateGmock=True, base_namespace = '', mock_namespace = 'Mock', component_namespace = 'Component', funcPrefix='my', component_suffix = 'Wrapper'):
if include_path == '':
include_path = getIncludeEnvVar()
fullComponentNamespace = getFullyQualifiedName((base_namespace, component_namespace))
fullMockNamespace = getFullyQualifiedName((base_namespace, mock_namespace))
full_interface_dir = os.path.join(BASE_INCLUDE, os.path.normpath(getPathFromNamespace(base_namespace)))
full_component_dir = os.path.join(BASE_INCLUDE, os.path.normpath(getPathFromNamespace(fullComponentNamespace)))
full_mock_dir = os.path.join(BASE_INCLUDE, os.path.normpath(getPathFromNamespace(fullMockNamespace)))
mkdirIfNotExist(full_interface_dir)
mkdirIfNotExist(full_component_dir)
if generateGmock:
mkdirIfNotExist(full_mock_dir)
configuration = yaml.load(open(function_file, 'rt').read())
print('Parsing files')
prototypes, found_files = getFunctionASTs(include_path, configuration['Functions'])
interface_classes = ''
component_classes = ''
print('Generating wrappers')
wrappers = []
for prototype in prototypes:
wrapper = FunctionWrapper(prototype, base_namespace, component_namespace, mock_namespace, funcPrefix, component_suffix)
wrappers.append(wrapper)
interface_classes += wrapper.interface_class()
component_classes += wrapper.component_class()
aggregates = []
for aggregate in configuration['Aggregators']:
name = aggregate['name']
functions = aggregate['functions']
ag_wrappers = []
for wrapper in wrappers:
if wrapper.prototype.function_name() in functions:
ag_wrappers.append(wrapper)
aggregator = FunctionAggregate(name, base_namespace, component_suffix, component_namespace, mock_namespace)
aggregator.wrappers = ag_wrappers
aggregates.append(aggregator)
master = FunctionAggregate('MasterC', base_namespace, component_suffix, component_namespace, mock_namespace)
master.wrappers = wrappers
aggregates.append(master)
mock_classes = ''
for aggregate in aggregates:
print('Generating {0} interface'.format(aggregate.name))
interface_classes += aggregate.interface_aggregate()
print('Generating {0} wrapper component'.format(aggregate.name))
component_classes += aggregate.component_aggregate()
if generateGmock:
print('Generating {0} mock wrapper'.format(aggregate.name))
mock_classes += aggregate.mock_aggregate()
interface_file = os.path.join(full_interface_dir, 'ICWrappers.h')
print('Generating interface file {0}'.format(interface_file))
with open(interface_file, 'wt') as file:
file.write(texttemplates.INTERFACE_FILE_TEMPLATE.format(
getHeaderGuard(base_namespace),
getIncludes(found_files),
getNamespaceHierarchy(
collectInterfaceNames(prototypes, aggregates),
base_namespace),
interface_classes))
component_file = os.path.join(full_component_dir, 'CWrappers.h')
print('Generating component file {0}'.format(component_file))
with open(component_file, 'wt') as file:
file.write(texttemplates.COMPONENT_FILE_TEMPLATE.format(
getHeaderGuard(fullComponentNamespace),
getIncludes(found_files),
getPathFromNamespace(base_namespace),
getNamespaceHierarchy(
getComponentDefinitions(prototypes, aggregates, component_suffix),
fullComponentNamespace),
component_classes))
if not generateGmock:
return
mock_file = os.path.join(full_mock_dir, 'CWrappers.h')
print('Generating mock file {0}'.format(mock_file))
with open(mock_file, 'wt') as file:
file.write(texttemplates.GMOCK_FILE_TEMPLATE.format(
getHeaderGuard(fullMockNamespace),
getPathFromNamespace(base_namespace),
mock_classes))
print('Done!')
def getIncludeEnvVar():
try:
include_path = os.environ['INCLUDE']
except KeyError:
raise Exception("You must either specify include_path or define the INCLUDE environment variable")
return include_path
def mkdirIfNotExist(path):
if not os.path.exists(path):
os.makedirs(path)
def getFunctions(function_file):
with open(function_file, 'rt') as file:
return list(map(lambda x : x.strip().split(' '), file.readlines()))
def getFunctionASTs(include_path, functionsToWrap):
filesToFind = []
funcsToFind = []
for item in functionsToWrap:
func = item['name']
real_loc = item['real_header']
include = item['include_header']
if (real_loc, include) not in filesToFind:
filesToFind.append((real_loc, include))
if func not in funcsToFind:
funcsToFind.append(func)
includeDirs = include_path.split(PATH_SEPARATOR)
includeDirs.remove(includeDirs[len(includeDirs)-1])
prototypes = []
foundFiles = []
for fileName, include in filesToFind:
for dir in includeDirs:
filePath = os.path.join(dir, fileName)
if not os.path.exists(filePath):
continue
foundFiles.append(include)
source = open(filePath, 'rt').read()
builder = ast.BuilderFromSource(source, filePath)
entire_ast = filter(None, builder.Generate())
original_stderr = sys.stderr
sys.stderr = NullDevice()
for tree in entire_ast:
try:
if type(tree) != ast.Function or tree.name not in funcsToFind:
continue
prototypes.append(FunctionPrototype(tree))
except AssertionError:
pass
except:
print('I did my best, but I can go no further. Hopefully the collected ASTs are sufficient for your needs')
sys.stderr = original_stderr
return prototypes, foundFiles
def getFullyQualifiedName(namespaces):
return '::'.join(namespaces)
def collectInterfaceNames(prototypes, aggregators):
names = []
for prototype in prototypes:
names.append(INTERFACE_PREFIX + prototype.function_name())
for aggregate in aggregators:
names.append(aggregate.interface_name())
return names
def getComponentDefinitions(prototypes, aggregators, component_suffix, indent = 4):
names = []
for prototype in prototypes:
names.append(prototype.function_name() + component_suffix)
for aggregate in aggregators:
names.append(aggregate.component_name())
return names
def getHeaderGuard(namespace):
return '_'.join(namespace.split('::')).upper()
def getIncludes(includes):
return '\n'.join(list(map(lambda x : '#include <{0}>'.format(x), includes)))
def getPathFromNamespace(namespace):
return '/'.join(namespace.split('::'))
def getNamespaceHierarchy(classes, hierarchy):
namespaces = hierarchy.split('::')
ns_template = 'namespace {0}\n'
class_template = 'class {0};'
hierarchy = ''
ident = 0
tab = 4
for namespace in namespaces:
hierarchy += ' ' * ident + ns_template.format(namespace)
hierarchy += ' ' * ident + '{\n'
ident += tab
hierarchy += ' ' * ident
hierarchy += str('\n' + ' ' * ident).join(list(map(lambda x : class_template.format(x), classes)))
hierarchy += '\n'
ident -= tab
for namespace in namespaces:
hierarchy += ' ' * (ident) + '}\n'
ident -= tab
return hierarchy
def usage():
print(USAGE + '\n' + DESCRIPTION)
if __name__ == '__main__':
try:
filename = sys.argv[1]
except:
usage()
if (len(sys.argv) > 2):
try:
opts, args = getopt.getopt(sys.argv[2:], 'i:nb:m:c:p:s:', ['include_path=', 'disableGMock', 'base_namespace=', 'mock_namespace=', 'component_namespace=', 'funcPrefix=', 'component_suffix='])
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
kwargs = {}
for o, a in opts:
if o in ('-i', '--include_path'):
kwargs['include_path'] = a
elif o in ('-n', '--disableGMock'):
kwargs['generateGmock'] = False
elif o in ('-b', '--base_namespace'):
kwargs['base_namespace'] = a
elif o in ('-m', '--mock_namespace'):
kwargs['mock_namespace'] = a
elif o in ('-c', '--component_namespace'):
kwargs['component_namespace'] = a
elif o in ('-p', '--funcPrefix'):
kwargs['funcPrefix'] = a
elif o in ('-s', '--component_suffix'):
kwargs['component_suffix'] = a
generate(filename, **kwargs)