Debian Codegraph @

contrib/cgreen-mocker/cgreen-mocker.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # -----------------------------------------------------------------
3 # cgreen-mocker.py
4 #
5 # Create Cgreen mocks from extern declarations of functions,
6 # typically in a header file.
7 #
8 # Usage:
9 # cgreen-mocker.py { <cpp_directive> } <headerfile>
10 #
11 # <cpp_directive>: any 'cpp' directive but most useful is e.g.
12 # "-I <directory>" to ensure cpp finds files.
13 #
14 # <headerfile>: file with function declarations that you want
15 # to mock
16 #
17 # Simplistically adapted from pycparser example: func_defs.py
18 #
19 # Since it uses pycparser it will only handle C functions and you will
20 # probably need the pycparsers "fake_libc_include" to avoid parsing
21 # the whole world of libc headers. To use it, make a soft link with
22 # the name 'pycparser' in the directory you are running this from, or
23 # in the directory of 'cgreen-mocker' itself, to the top directory of
24 # the pycparser source, and cgreen-mocker will pick it up
25 # automatically. Or you can point to it using a command line
26 # 'cpp_directive' arg.
27 #
28 # Thanks to @gardenia for the pointer to pycparser!
29 #
30 # https://github.com/eliben/pycparser
31 #
32 # (C) 2016, Thomas Nilefalk
33 #
34 # Using pycparser for printing out all the functions defined in a
35 # C file.
36 #
37 # PyCParser - Copyright (C) 2008-2015, Eli Bendersky
38 # License: BSD
39 # -----------------------------------------------------------------
40 from __future__ import print_function
41 from pycparser.plyparser import ParseError
42 from pycparser import c_parser, c_ast, parse_file, c_generator
43 from functools import reduce
44 from packaging import version
45 import sys
46 import os
47 import pycparser
48
49 # This is not required if you've installed pycparser into
50 # your site-packages/ with setup.py
51 sys.path.extend(['.', '..'])
52
53 # Print on stderr
54
55
56 def eprint(*args, **kwargs):
57 print(*args, file=sys.stderr, **kwargs)
58
59 # A visitor for FuncDef nodes that prints the
60 # Cgreen mock equivalent of the function
61
62
63 class FuncDefVisitor(c_ast.NodeVisitor):
64 def __init__(self, filename):
65 self._types = {}
66 self.filename = filename
67
68 def visit_FuncDecl(self, node):
69 if node.coord.file == self.filename:
70 # Only consider definitions that are in the processed file
71 generator = c_generator.CGenerator()
72 try:
73 print(generator.visit(node), end="")
74 print(" { ")
75 self.should_return(node)
76 print("mock(%s);" % ", ".join(arg_list(node.args)))
77 print("}")
78 print()
79 except Exception as e:
80 print("ERROR: {} - Unexpected AST @ {}:{}:{}:".format(e, node.coord.file,
81 node.coord.line, node.coord.column))
82 node.show()
83 return
84
85 def visit_Typedef(self, node):
86 self._types[node.name] = {
87 'is_pointer': isinstance(node.type, c_ast.PtrDecl),
88 }
89 if self._types[node.name]['is_pointer']:
90 self._types[node.name]['to_class'] = node.type.type.type.names
91 else:
92 self._types[node.name]['to_class'] = None
93
94 def should_return(self, node):
95 generator = c_generator.CGenerator()
96 type = node.type
97 if is_double_decl(node):
98 print(" return unbox_double(", end="")
99 elif not is_void_decl(node):
100 print(" return %s(" %
101 ("*" if self.is_return_struct_by_value(node) else ""), end="")
102 print(generator.visit(node.type), end="")
103 if version.parse(pycparser.__version__) <= version.parse('2.19') \
104 and isinstance(node.type, c_ast.PtrDecl) \
105 or self.is_return_struct_by_value(node):
106 print(" *", end="")
107 print(") ", end="")
108 else:
109 print(" ", end="")
110
111 def is_return_struct_by_value(self, node):
112 type = node.type
113 return not isinstance(type, c_ast.PtrDecl) and type.type.names[0] in self._types and not self._types[type.type.names[0]]['is_pointer']
114
115 def is_return_by_value_pointer(self, node):
116 type = node.type
117 return not isinstance(type, c_ast.PtrDecl) and self._types[type.type.names[0]]['is_pointer']
118
119
120 def arg_list(args):
121 if args != None and len(args.params) > 0:
122 return [el for el in map(parameter_name_or_box_double,
123 filter(lambda x: not is_ellipsis_param(x),
124 args.params))
125 if el is not None]
126 else:
127 return []
128
129
130 def parameter_name_or_box_double(node):
131 if is_double_decl(node):
132 return "box_double({})".format(node.name)
133 else:
134 return node.name
135
136
137 def is_void_decl(node):
138 type = node.type
139 return isinstance(type, c_ast.TypeDecl) and type.type.names == ['void']
140
141
142 def is_double_decl(node):
143 type = node.type
144 return isinstance(type, c_ast.TypeDecl) and type.type.names == ['double']
145
146
147 def is_ellipsis_param(node):
148 return isinstance(node, c_ast.EllipsisParam)
149
150
151 def show_func_defs(args):
152 # Note that cpp is used. Provide a path to your own cpp or
153 # make sure one exists in PATH.
154
155 pycparser_path = None
156 # Try to find a fake_libc
157 # In current directory?
158 if verbose:
159 eprint("Called in {0}".format(
160 os.path.abspath(os.path.dirname(sys.argv[0]))))
161 eprint("Looking for fake_lib in current directory...")
162 if os.path.isdir('pycparser'):
163 pycparser_path = r'./pycparser'
164 else:
165 this_script = os.path.abspath(__file__)
166 if verbose:
167 eprint(
168 "Looking for fake_lib in directory of script ({0})...".format(this_script))
169 # Look in the directory of this script
170 while os.path.islink(this_script):
171 # If the script is a symlink, resolve it first, recursively...
172 # Note: can only handle absolute symlinks?
173 this_script = os.readlink(this_script)
174 if verbose:
175 eprint(
176 "Script was a symlink, resolving it to '{0}'...".format(this_script))
177 if os.path.isdir(os.path.join(os.path.dirname(this_script),
178 'pycparser')):
179 # Yes, there is a pycparser symlink here
180 pycparser_path = os.path.join(os.path.dirname(this_script),
181 'pycparser')
182
183 if pycparser_path:
184 pycparser_lib = reduce(
185 os.path.join, [pycparser_path, 'utils', 'fake_libc_include'])
186 if verbose:
187 print("/* Generated with cgreen-mocker and pycparser's fake_libc from %s */" %
188 (pycparser_path))
189 elif verbose:
190 eprint("Not found")
191
192 try:
193 options = [
194 '-I'+pycparser_lib] if pycparser_path else []
195 if add_gnuisms:
196 # And add some common GNUisms
197 options = options + [
198 r'-D__gnuc_va_list(c)=',
199 r'-D__attribute__(x)=',
200 r'-D__extension__=',
201 r'-D__restrict=',
202 r'-D__inline='
203 ]
204 if verbose:
205 eprint("Parsing with options = {0}".format(options))
206 cpp_args = list(filter(None, options))
207 ast = parse_file(args[-1], use_cpp=True,
208 cpp_args=cpp_args + args[0:-1])
209 except ParseError as e:
210 print("ERROR: {} - C99 parse error".format(e))
211 return
212
213 print('/* -*- c -*-*/') # Suggest c-mode for Emacs
214 print('#include "%s"' % args[len(args)-1])
215 print('#include <cgreen/mocks.h>')
216 print()
217 v = FuncDefVisitor(args[-1])
218 v.visit(ast)
219
220
221 def usage():
222 print("""
223 Usage:
224 cgreen-mocker.py { <cpp_directive> } <headerfile>
225
226 <cpp_directive>: any 'cpp' directive but most useful are e.g.
227 "-I <directory>" to ensure cpp finds files and
228 "-D <define>" to create an inline define
229
230 <headerfile>: file with function declarations that you want
231 to mock
232
233 Cgreen-mocker takes a header file and generates cgreen mocks for
234 all functions in it. It will print the generated mocks to standard
235 output so you can inspect it, or pipe it to a file that can be
236 compiled and linked with your tests.
237
238 The mocker will only handle functions that are declared in the
239 header file you provide. This is based on the presumtion that the
240 header file represents functions in a unit. Aggregating functions
241 from multiple units into a single header for convenience is not
242 supported. Also the mocker cannot handle data declarations (yet?).
243
244 If your header does not name some arguments you will not be able
245 to use those arguments in 'expect when' statements, of course.
246
247 Cgreen-mocker will only generate mocks for the external functions
248 in the file you give as an argument, not those in included files.
249
250 If cgreen-mocker encounters parse errors and they look like
251 gnu-isms you should get a copy of the source for pycparser (on
252 which cgreen-mocker is built). In it you will find a
253 'fake_libc_include' which help. Create a symbolic link named
254 'pycparser' that links to the root of pycparser source and
255 cgreen-mocker will find it itself.
256
257 You can find pycparser at https://github.com/eliben/pycparser
258
259 """)
260
261
262 if __name__ == "__main__":
263 if len(sys.argv) <= 1:
264 usage()
265 exit(-1)
266 if '-v' in sys.argv:
267 verbose = True
268 sys.argv.remove('-v')
269 else:
270 verbose = False
271 if '-gnu' in sys.argv:
272 add_gnuisms = True
273 sys.argv.remove('-gnu')
274 else:
275 add_gnuisms = False
276 show_func_defs(sys.argv[1:])