3 # Copyright 2008 Google Inc. All Rights Reserved.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 """Generate Google Mock classes from base classes.
19 This program will read in a C++ source file and output the Google Mock
20 classes for the specified classes. If no class is specified, all
21 classes in the source file are emitted.
24 gmock_class.py header-file.h [ClassName]...
26 Output is sent to stdout.
36 # Preserve compatibility with Python 2.3.
44 _VERSION = (1, 0, 1) # The version of this script.
45 # How many spaces to indent. Can set me with the INDENT environment variable.
49 def _RenderType(ast_type):
50 """Renders the potentially recursively templated type into a string.
53 ast_type: The AST of the type.
56 Rendered string of the type.
58 # Add modifiers like 'const'.
60 if ast_type.modifiers:
61 modifiers = ' '.join(ast_type.modifiers) + ' '
62 return_type = modifiers + ast_type.name
63 if ast_type.templated_types:
64 # Collect template args.
66 for arg in ast_type.templated_types:
67 rendered_arg = _RenderType(arg)
68 template_args.append(rendered_arg)
69 return_type += '<' + ', '.join(template_args) + '>'
72 if ast_type.reference:
77 def _GenerateArg(source):
78 """Strips out comments, default arguments, and redundant spaces from a single argument.
81 source: A string for a single argument.
84 Rendered string of the argument.
86 # Remove end of line comments before eliminating newlines.
87 arg = re.sub(r'//.*', '', source)
89 # Remove c-style comments.
90 arg = re.sub(r'/\*.*\*/', '', arg)
92 # Remove default arguments.
93 arg = re.sub(r'=.*', '', arg)
95 # Collapse spaces and newlines into a single space.
96 arg = re.sub(r'\s+', ' ', arg)
100 def _EscapeForMacro(s):
101 """Escapes a string for use as an argument to a C++ macro."""
108 elif c == ',' and paren_count == 0:
113 def _GenerateMethods(output_lines, source, class_node):
115 ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | ast.FUNCTION_OVERRIDE)
116 ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
117 indent = ' ' * _INDENT
119 for node in class_node.body:
120 # We only care about virtual functions.
121 if (isinstance(node, ast.Function) and node.modifiers & function_type and
122 not node.modifiers & ctor_or_dtor):
123 # Pick out all the elements we need from the original function.
124 modifiers = 'override'
125 if node.modifiers & ast.FUNCTION_CONST:
126 modifiers = 'const, ' + modifiers
130 return_type = _EscapeForMacro(_RenderType(node.return_type))
133 for p in node.parameters:
134 arg = _GenerateArg(source[p.start:p.end])
136 args.append(_EscapeForMacro(arg))
138 # Create the mock method definition.
139 output_lines.extend([
140 '%sMOCK_METHOD(%s, %s, (%s), (%s));' %
141 (indent, return_type, node.name, ', '.join(args), modifiers)
145 def _GenerateMocks(filename, source, ast_list, desired_class_names):
146 processed_class_names = set()
148 for node in ast_list:
149 if (isinstance(node, ast.Class) and node.body and
150 # desired_class_names being None means that all classes are selected.
151 (not desired_class_names or node.name in desired_class_names)):
152 class_name = node.name
153 parent_name = class_name
154 processed_class_names.add(class_name)
156 # Add namespace before the class.
157 if class_node.namespace:
158 lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
161 # Add template args for templated classes.
162 if class_node.templated_types:
163 # TODO(paulchang): Handle non-type template arguments (e.g.
164 # template<typename T, int N>).
166 # class_node.templated_types is an OrderedDict from strings to a tuples.
167 # The key is the name of the template, and the value is
168 # (type_name, default). Both type_name and default could be None.
169 template_args = class_node.templated_types.keys()
170 template_decls = ['typename ' + arg for arg in template_args]
171 lines.append('template <' + ', '.join(template_decls) + '>')
172 parent_name += '<' + ', '.join(template_args) + '>'
174 # Add the class prolog.
175 lines.append('class Mock%s : public %s {' # }
176 % (class_name, parent_name))
177 lines.append('%spublic:' % (' ' * (_INDENT // 2)))
179 # Add all the methods.
180 _GenerateMethods(lines, source, class_node)
184 # If there are no virtual methods, no need for a public label.
188 # Only close the class if there really is a class.
190 lines.append('') # Add an extra newline.
192 # Close the namespace.
193 if class_node.namespace:
194 for i in range(len(class_node.namespace) - 1, -1, -1):
195 lines.append('} // namespace %s' % class_node.namespace[i])
196 lines.append('') # Add an extra newline.
198 if desired_class_names:
199 missing_class_name_list = list(desired_class_names - processed_class_names)
200 if missing_class_name_list:
201 missing_class_name_list.sort()
202 sys.stderr.write('Class(es) not found in %s: %s\n' %
203 (filename, ', '.join(missing_class_name_list)))
204 elif not processed_class_names:
205 sys.stderr.write('No class found in %s\n' % filename)
210 def main(argv=sys.argv):
212 sys.stderr.write('Google Mock Class Generator v%s\n\n' %
213 '.'.join(map(str, _VERSION)))
214 sys.stderr.write(__doc__)
219 _INDENT = int(os.environ['INDENT'])
223 sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
226 desired_class_names = None # None means all classes in the source file.
228 desired_class_names = set(argv[2:])
229 source = utils.ReadFile(filename)
233 builder = ast.BuilderFromSource(source, filename)
235 entire_ast = filter(None, builder.Generate())
236 except KeyboardInterrupt:
239 # An error message was already printed since we couldn't parse.
242 lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
243 sys.stdout.write('\n'.join(lines))
246 if __name__ == '__main__':