gmock_class.py 8.1 KB

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