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      mock_method_macro = 'MOCK_%sMETHOD%d' % (const, len(node.parameters))
86      args = ''
87      if node.parameters:
88        # Get the full text of the parameters from the start
89        # of the first parameter to the end of the last parameter.
90        start = node.parameters[0].start
91        end = node.parameters[-1].end
92        # Remove // comments.
93        args_strings = re.sub(r'//.*', '', source[start:end])
94        # Condense multiple spaces and eliminate newlines putting the
95        # parameters together on a single line.  Ensure there is a
96        # space in an argument which is split by a newline without
97        # intervening whitespace, e.g.: int\nBar
98        args = re.sub('  +', ' ', args_strings.replace('\n', ' '))
99
100      # Create the mock method definition.
101      output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name),
102                           '%s%s(%s));' % (indent*3, return_type, args)])
103
104
105def _GenerateMocks(filename, source, ast_list, desired_class_names):
106  processed_class_names = set()
107  lines = []
108  for node in ast_list:
109    if (isinstance(node, ast.Class) and node.body and
110        # desired_class_names being None means that all classes are selected.
111        (not desired_class_names or node.name in desired_class_names)):
112      class_name = node.name
113      processed_class_names.add(class_name)
114      class_node = node
115      # Add namespace before the class.
116      if class_node.namespace:
117        lines.extend(['namespace %s {' % n for n in class_node.namespace])  # }
118        lines.append('')
119
120      # Add the class prolog.
121      lines.append('class Mock%s : public %s {' % (class_name, class_name))  # }
122      lines.append('%spublic:' % (' ' * (_INDENT // 2)))
123
124      # Add all the methods.
125      _GenerateMethods(lines, source, class_node)
126
127      # Close the class.
128      if lines:
129        # If there are no virtual methods, no need for a public label.
130        if len(lines) == 2:
131          del lines[-1]
132
133        # Only close the class if there really is a class.
134        lines.append('};')
135        lines.append('')  # Add an extra newline.
136
137      # Close the namespace.
138      if class_node.namespace:
139        for i in range(len(class_node.namespace)-1, -1, -1):
140          lines.append('}  // namespace %s' % class_node.namespace[i])
141        lines.append('')  # Add an extra newline.
142
143  if desired_class_names:
144    missing_class_name_list = list(desired_class_names - processed_class_names)
145    if missing_class_name_list:
146      missing_class_name_list.sort()
147      sys.stderr.write('Class(es) not found in %s: %s\n' %
148                       (filename, ', '.join(missing_class_name_list)))
149  elif not processed_class_names:
150    sys.stderr.write('No class found in %s\n' % filename)
151
152  return lines
153
154
155def main(argv=sys.argv):
156  if len(argv) < 2:
157    sys.stderr.write('Google Mock Class Generator v%s\n\n' %
158                     '.'.join(map(str, _VERSION)))
159    sys.stderr.write(__doc__)
160    return 1
161
162  global _INDENT
163  try:
164    _INDENT = int(os.environ['INDENT'])
165  except KeyError:
166    pass
167  except:
168    sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
169
170  filename = argv[1]
171  desired_class_names = None  # None means all classes in the source file.
172  if len(argv) >= 3:
173    desired_class_names = set(argv[2:])
174  source = utils.ReadFile(filename)
175  if source is None:
176    return 1
177
178  builder = ast.BuilderFromSource(source, filename)
179  try:
180    entire_ast = filter(None, builder.Generate())
181  except KeyboardInterrupt:
182    return
183  except:
184    # An error message was already printed since we couldn't parse.
185    pass
186  else:
187    lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
188    sys.stdout.write('\n'.join(lines))
189
190
191if __name__ == '__main__':
192  main(sys.argv)
193