• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2#
3# Copyright 2008 Google Inc.  All Rights Reserved.
4#
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
8#
9#      http://www.apache.org/licenses/LICENSE-2.0
10#
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.
16
17"""Generate Google Mock classes from base classes.
18
19This program will read in a C++ source file and output the Google Mock
20classes for the specified classes.  If no class is specified, all
21classes in the source file are emitted.
22
23Usage:
24  gmock_class.py header-file.h [ClassName]...
25
26Output is sent to stdout.
27"""
28
29import os
30import re
31import sys
32
33from cpp import ast
34from cpp import utils
35
36# Preserve compatibility with Python 2.3.
37try:
38  _dummy = set
39except NameError:
40  import sets
41
42  set = sets.Set
43
44_VERSION = (1, 0, 1)  # The version of this script.
45# How many spaces to indent.  Can set me with the INDENT environment variable.
46_INDENT = 2
47
48
49def _RenderType(ast_type):
50  """Renders the potentially recursively templated type into a string.
51
52  Args:
53    ast_type: The AST of the type.
54
55  Returns:
56    Rendered string of the type.
57  """
58  # Add modifiers like 'const'.
59  modifiers = ''
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.
65    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) + '>'
70  if ast_type.pointer:
71    return_type += '*'
72  if ast_type.reference:
73    return_type += '&'
74  return return_type
75
76
77def _GenerateArg(source):
78  """Strips out comments, default arguments, and redundant spaces from a single argument.
79
80  Args:
81    source: A string for a single argument.
82
83  Returns:
84    Rendered string of the argument.
85  """
86  # Remove end of line comments before eliminating newlines.
87  arg = re.sub(r'//.*', '', source)
88
89  # Remove c-style comments.
90  arg = re.sub(r'/\*.*\*/', '', arg)
91
92  # Remove default arguments.
93  arg = re.sub(r'=.*', '', arg)
94
95  # Collapse spaces and newlines into a single space.
96  arg = re.sub(r'\s+', ' ', arg)
97  return arg.strip()
98
99
100def _EscapeForMacro(s):
101  """Escapes a string for use as an argument to a C++ macro."""
102  paren_count = 0
103  for c in s:
104    if c == '(':
105      paren_count += 1
106    elif c == ')':
107      paren_count -= 1
108    elif c == ',' and paren_count == 0:
109      return '(' + s + ')'
110  return s
111
112
113def _GenerateMethods(output_lines, source, class_node):
114  function_type = (
115      ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | ast.FUNCTION_OVERRIDE)
116  ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
117  indent = ' ' * _INDENT
118
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
127
128      return_type = 'void'
129      if node.return_type:
130        return_type = _EscapeForMacro(_RenderType(node.return_type))
131
132      args = []
133      for p in node.parameters:
134        arg = _GenerateArg(source[p.start:p.end])
135        if arg != 'void':
136          args.append(_EscapeForMacro(arg))
137
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)
142      ])
143
144
145def _GenerateMocks(filename, source, ast_list, desired_class_names):
146  processed_class_names = set()
147  lines = []
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)
155      class_node = node
156      # Add namespace before the class.
157      if class_node.namespace:
158        lines.extend(['namespace %s {' % n for n in class_node.namespace])  # }
159        lines.append('')
160
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>).
165
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) + '>'
173
174      # Add the class prolog.
175      lines.append('class Mock%s : public %s {'  # }
176                   % (class_name, parent_name))
177      lines.append('%spublic:' % (' ' * (_INDENT // 2)))
178
179      # Add all the methods.
180      _GenerateMethods(lines, source, class_node)
181
182      # Close the class.
183      if lines:
184        # If there are no virtual methods, no need for a public label.
185        if len(lines) == 2:
186          del lines[-1]
187
188        # Only close the class if there really is a class.
189        lines.append('};')
190        lines.append('')  # Add an extra newline.
191
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.
197
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)
206
207  return lines
208
209
210def main(argv=sys.argv):
211  if len(argv) < 2:
212    sys.stderr.write('Google Mock Class Generator v%s\n\n' %
213                     '.'.join(map(str, _VERSION)))
214    sys.stderr.write(__doc__)
215    return 1
216
217  global _INDENT
218  try:
219    _INDENT = int(os.environ['INDENT'])
220  except KeyError:
221    pass
222  except:
223    sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
224
225  filename = argv[1]
226  desired_class_names = None  # None means all classes in the source file.
227  if len(argv) >= 3:
228    desired_class_names = set(argv[2:])
229  source = utils.ReadFile(filename)
230  if source is None:
231    return 1
232
233  builder = ast.BuilderFromSource(source, filename)
234  try:
235    entire_ast = filter(None, builder.Generate())
236  except KeyboardInterrupt:
237    return
238  except:
239    # An error message was already printed since we couldn't parse.
240    sys.exit(1)
241  else:
242    lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
243    sys.stdout.write('\n'.join(lines))
244
245
246if __name__ == '__main__':
247  main(sys.argv)
248