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
29__author__ = 'nnorwitz@google.com (Neal Norwitz)'
30
31
32import os
33import re
34import sys
35
36from cpp import ast
37from cpp import utils
38
39# Preserve compatibility with Python 2.3.
40try:
41  _dummy = set
42except NameError:
43  import sets
44  set = sets.Set
45
46_VERSION = (1, 0, 1)  # The version of this script.
47# How many spaces to indent.  Can set me with the INDENT environment variable.
48_INDENT = 2
49
50
51def _GenerateMethods(output_lines, source, class_node):
52  function_type = ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL
53  ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
54  indent = ' ' * _INDENT
55
56  for node in class_node.body:
57    # We only care about virtual functions.
58    if (isinstance(node, ast.Function) and
59        node.modifiers & function_type and
60        not node.modifiers & ctor_or_dtor):
61      # Pick out all the elements we need from the original function.
62      const = ''
63      if node.modifiers & ast.FUNCTION_CONST:
64        const = 'CONST_'
65      return_type = 'void'
66      if node.return_type:
67        # Add modifiers like 'const'.
68        modifiers = ''
69        if node.return_type.modifiers:
70          modifiers = ' '.join(node.return_type.modifiers) + ' '
71        return_type = modifiers + node.return_type.name
72        template_args = [arg.name for arg in node.return_type.templated_types]
73        if template_args:
74          return_type += '<' + ', '.join(template_args) + '>'
75          if len(template_args) > 1:
76            for line in [
77                '// The following line won\'t really compile, as the return',
78                '// type has multiple template arguments.  To fix it, use a',
79                '// typedef for the return type.']:
80              output_lines.append(indent + line)
81        if node.return_type.pointer:
82          return_type += '*'
83        if node.return_type.reference:
84          return_type += '&'
85        num_parameters = len(node.parameters)
86        if len(node.parameters) == 1:
87          first_param = node.parameters[0]
88          if source[first_param.start:first_param.end].strip() == 'void':
89            # We must treat T(void) as a function with no parameters.
90            num_parameters = 0
91      mock_method_macro = 'MOCK_%sMETHOD%d' % (const, num_parameters)
92      args = ''
93      if node.parameters:
94        # Due to the parser limitations, it is impossible to keep comments
95        # while stripping the default parameters.  When defaults are
96        # present, we choose to strip them and comments (and produce
97        # compilable code).
98        # TODO(nnorwitz@google.com): Investigate whether it is possible to
99        # preserve parameter name when reconstructing parameter text from
100        # the AST.
101        if len([param for param in node.parameters if param.default]) > 0:
102          args = ', '.join(param.type.name for param in node.parameters)
103        else:
104          # Get the full text of the parameters from the start
105          # of the first parameter to the end of the last parameter.
106          start = node.parameters[0].start
107          end = node.parameters[-1].end
108          # Remove // comments.
109          args_strings = re.sub(r'//.*', '', source[start:end])
110          # Condense multiple spaces and eliminate newlines putting the
111          # parameters together on a single line.  Ensure there is a
112          # space in an argument which is split by a newline without
113          # intervening whitespace, e.g.: int\nBar
114          args = re.sub('  +', ' ', args_strings.replace('\n', ' '))
115
116      # Create the mock method definition.
117      output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name),
118                           '%s%s(%s));' % (indent*3, return_type, args)])
119
120
121def _GenerateMocks(filename, source, ast_list, desired_class_names):
122  processed_class_names = set()
123  lines = []
124  for node in ast_list:
125    if (isinstance(node, ast.Class) and node.body and
126        # desired_class_names being None means that all classes are selected.
127        (not desired_class_names or node.name in desired_class_names)):
128      class_name = node.name
129      processed_class_names.add(class_name)
130      class_node = node
131      # Add namespace before the class.
132      if class_node.namespace:
133        lines.extend(['namespace %s {' % n for n in class_node.namespace])  # }
134        lines.append('')
135
136      # Add the class prolog.
137      lines.append('class Mock%s : public %s {' % (class_name, class_name))  # }
138      lines.append('%spublic:' % (' ' * (_INDENT // 2)))
139
140      # Add all the methods.
141      _GenerateMethods(lines, source, class_node)
142
143      # Close the class.
144      if lines:
145        # If there are no virtual methods, no need for a public label.
146        if len(lines) == 2:
147          del lines[-1]
148
149        # Only close the class if there really is a class.
150        lines.append('};')
151        lines.append('')  # Add an extra newline.
152
153      # Close the namespace.
154      if class_node.namespace:
155        for i in range(len(class_node.namespace)-1, -1, -1):
156          lines.append('}  // namespace %s' % class_node.namespace[i])
157        lines.append('')  # Add an extra newline.
158
159  if desired_class_names:
160    missing_class_name_list = list(desired_class_names - processed_class_names)
161    if missing_class_name_list:
162      missing_class_name_list.sort()
163      sys.stderr.write('Class(es) not found in %s: %s\n' %
164                       (filename, ', '.join(missing_class_name_list)))
165  elif not processed_class_names:
166    sys.stderr.write('No class found in %s\n' % filename)
167
168  return lines
169
170
171def main(argv=sys.argv):
172  if len(argv) < 2:
173    sys.stderr.write('Google Mock Class Generator v%s\n\n' %
174                     '.'.join(map(str, _VERSION)))
175    sys.stderr.write(__doc__)
176    return 1
177
178  global _INDENT
179  try:
180    _INDENT = int(os.environ['INDENT'])
181  except KeyError:
182    pass
183  except:
184    sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
185
186  filename = argv[1]
187  desired_class_names = None  # None means all classes in the source file.
188  if len(argv) >= 3:
189    desired_class_names = set(argv[2:])
190  source = utils.ReadFile(filename)
191  if source is None:
192    return 1
193
194  builder = ast.BuilderFromSource(source, filename)
195  try:
196    entire_ast = filter(None, builder.Generate())
197  except KeyboardInterrupt:
198    return
199  except:
200    # An error message was already printed since we couldn't parse.
201    pass
202  else:
203    lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
204    sys.stdout.write('\n'.join(lines))
205
206
207if __name__ == '__main__':
208  main(sys.argv)
209