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 and a boolean to indicate whether we have multiple args 57 (which is not handled correctly). 58 """ 59 has_multiarg_error = False 60 # Add modifiers like 'const'. 61 modifiers = '' 62 if ast_type.modifiers: 63 modifiers = ' '.join(ast_type.modifiers) + ' ' 64 return_type = modifiers + ast_type.name 65 if ast_type.templated_types: 66 # Collect template args. 67 template_args = [] 68 for arg in ast_type.templated_types: 69 rendered_arg, e = _RenderType(arg) 70 if e: has_multiarg_error = True 71 template_args.append(rendered_arg) 72 return_type += '<' + ', '.join(template_args) + '>' 73 # We are actually not handling multi-template-args correctly. So mark it. 74 if len(template_args) > 1: 75 has_multiarg_error = True 76 if ast_type.pointer: 77 return_type += '*' 78 if ast_type.reference: 79 return_type += '&' 80 return return_type, has_multiarg_error 81 82 83def _GetNumParameters(parameters, source): 84 num_parameters = len(parameters) 85 if num_parameters == 1: 86 first_param = parameters[0] 87 if source[first_param.start:first_param.end].strip() == 'void': 88 # We must treat T(void) as a function with no parameters. 89 return 0 90 return num_parameters 91 92 93def _GenerateMethods(output_lines, source, class_node): 94 function_type = (ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL | 95 ast.FUNCTION_OVERRIDE) 96 ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR 97 indent = ' ' * _INDENT 98 99 for node in class_node.body: 100 # We only care about virtual functions. 101 if (isinstance(node, ast.Function) and 102 node.modifiers & function_type and 103 not node.modifiers & ctor_or_dtor): 104 # Pick out all the elements we need from the original function. 105 const = '' 106 if node.modifiers & ast.FUNCTION_CONST: 107 const = 'CONST_' 108 num_parameters = _GetNumParameters(node.parameters, source) 109 return_type = 'void' 110 if node.return_type: 111 return_type, has_multiarg_error = _RenderType(node.return_type) 112 if has_multiarg_error: 113 for line in [ 114 '// The following line won\'t really compile, as the return', 115 '// type has multiple template arguments. To fix it, use a', 116 '// typedef for the return type.']: 117 output_lines.append(indent + line) 118 tmpl = '' 119 if class_node.templated_types: 120 tmpl = '_T' 121 mock_method_macro = 'MOCK_%sMETHOD%d%s' % (const, num_parameters, tmpl) 122 123 args = '' 124 if node.parameters: 125 # Get the full text of the parameters from the start 126 # of the first parameter to the end of the last parameter. 127 start = node.parameters[0].start 128 end = node.parameters[-1].end 129 # Remove // comments. 130 args_strings = re.sub(r'//.*', '', source[start:end]) 131 # Remove /* comments */. 132 args_strings = re.sub(r'/\*.*\*/', '', args_strings) 133 # Remove default arguments. 134 args_strings = re.sub(r'=.*,', ',', args_strings) 135 args_strings = re.sub(r'=.*', '', args_strings) 136 # Condense multiple spaces and eliminate newlines putting the 137 # parameters together on a single line. Ensure there is a 138 # space in an argument which is split by a newline without 139 # intervening whitespace, e.g.: int\nBar 140 args = re.sub(' +', ' ', args_strings.replace('\n', ' ')) 141 142 # Create the mock method definition. 143 output_lines.extend(['%s%s(%s,' % (indent, mock_method_macro, node.name), 144 '%s%s(%s));' % (indent * 3, return_type, args)]) 145 146 147def _GenerateMocks(filename, source, ast_list, desired_class_names): 148 processed_class_names = set() 149 lines = [] 150 for node in ast_list: 151 if (isinstance(node, ast.Class) and node.body and 152 # desired_class_names being None means that all classes are selected. 153 (not desired_class_names or node.name in desired_class_names)): 154 class_name = node.name 155 parent_name = class_name 156 processed_class_names.add(class_name) 157 class_node = node 158 # Add namespace before the class. 159 if class_node.namespace: 160 lines.extend(['namespace %s {' % n for n in class_node.namespace]) # } 161 lines.append('') 162 163 # Add template args for templated classes. 164 if class_node.templated_types: 165 # TODO(paulchang): The AST doesn't preserve template argument order, 166 # so we have to make up names here. 167 # TODO(paulchang): Handle non-type template arguments (e.g. 168 # template<typename T, int N>). 169 template_arg_count = len(class_node.templated_types.keys()) 170 template_args = ['T%d' % n for n in range(template_arg_count)] 171 template_decls = ['typename ' + arg for arg in template_args] 172 lines.append('template <' + ', '.join(template_decls) + '>') 173 parent_name += '<' + ', '.join(template_args) + '>' 174 175 # Add the class prolog. 176 lines.append('class Mock%s : public %s {' # } 177 % (class_name, parent_name)) 178 lines.append('%spublic:' % (' ' * (_INDENT // 2))) 179 180 # Add all the methods. 181 _GenerateMethods(lines, source, class_node) 182 183 # Close the class. 184 if lines: 185 # If there are no virtual methods, no need for a public label. 186 if len(lines) == 2: 187 del lines[-1] 188 189 # Only close the class if there really is a class. 190 lines.append('};') 191 lines.append('') # Add an extra newline. 192 193 # Close the namespace. 194 if class_node.namespace: 195 for i in range(len(class_node.namespace) - 1, -1, -1): 196 lines.append('} // namespace %s' % class_node.namespace[i]) 197 lines.append('') # Add an extra newline. 198 199 if desired_class_names: 200 missing_class_name_list = list(desired_class_names - processed_class_names) 201 if missing_class_name_list: 202 missing_class_name_list.sort() 203 sys.stderr.write('Class(es) not found in %s: %s\n' % 204 (filename, ', '.join(missing_class_name_list))) 205 elif not processed_class_names: 206 sys.stderr.write('No class found in %s\n' % filename) 207 208 return lines 209 210 211def main(argv=sys.argv): 212 if len(argv) < 2: 213 sys.stderr.write('Google Mock Class Generator v%s\n\n' % 214 '.'.join(map(str, _VERSION))) 215 sys.stderr.write(__doc__) 216 return 1 217 218 global _INDENT 219 try: 220 _INDENT = int(os.environ['INDENT']) 221 except KeyError: 222 pass 223 except: 224 sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT')) 225 226 filename = argv[1] 227 desired_class_names = None # None means all classes in the source file. 228 if len(argv) >= 3: 229 desired_class_names = set(argv[2:]) 230 source = utils.ReadFile(filename) 231 if source is None: 232 return 1 233 234 builder = ast.BuilderFromSource(source, filename) 235 try: 236 entire_ast = filter(None, builder.Generate()) 237 except KeyboardInterrupt: 238 return 239 except: 240 # An error message was already printed since we couldn't parse. 241 sys.exit(1) 242 else: 243 lines = _GenerateMocks(filename, source, entire_ast, desired_class_names) 244 sys.stdout.write('\n'.join(lines)) 245 246 247if __name__ == '__main__': 248 main(sys.argv) 249