Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(238)

Side by Side Diff: testing/gmock/scripts/generator/cpp/gmock_class.py

Issue 6241018: Pull in gmock through DEPS (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/testing
Patch Set: don't use svn mirror for now Created 9 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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
19 This program will read in a C++ source file and output the Google Mock
20 classes for the specified classes. If no class is specified, all
21 classes in the source file are emitted.
22
23 Usage:
24 gmock_class.py header-file.h [ClassName]...
25
26 Output is sent to stdout.
27 """
28
29 __author__ = 'nnorwitz@google.com (Neal Norwitz)'
30
31
32 import os
33 import re
34 import sets
35 import sys
36
37 from cpp import ast
38 from cpp import utils
39
40 _VERSION = (1, 0, 1) # The version of this script.
41 # How many spaces to indent. Can set me with the INDENT environment variable.
42 _INDENT = 2
43
44
45 def _GenerateMethods(output_lines, source, class_node):
46 function_type = ast.FUNCTION_VIRTUAL | ast.FUNCTION_PURE_VIRTUAL
47 ctor_or_dtor = ast.FUNCTION_CTOR | ast.FUNCTION_DTOR
48
49 for node in class_node.body:
50 # We only care about virtual functions.
51 if (isinstance(node, ast.Function) and
52 node.modifiers & function_type and
53 not node.modifiers & ctor_or_dtor):
54 # Pick out all the elements we need from the original function.
55 const = ''
56 if node.modifiers & ast.FUNCTION_CONST:
57 const = 'CONST_'
58 return_type = 'void'
59 if node.return_type:
60 # Add modifiers like 'const'.
61 modifiers = ''
62 if node.return_type.modifiers:
63 modifiers = ' '.join(node.return_type.modifiers) + ' '
64 return_type = modifiers + node.return_type.name
65 if node.return_type.pointer:
66 return_type += '*'
67 if node.return_type.reference:
68 return_type += '&'
69 prefix = 'MOCK_%sMETHOD%d' % (const, len(node.parameters))
70 args = ''
71 if node.parameters:
72 # Get the full text of the parameters from the start
73 # of the first parameter to the end of the last parameter.
74 start = node.parameters[0].start
75 end = node.parameters[-1].end
76 # Remove // comments.
77 args_strings = re.sub(r'//.*', '', source[start:end])
78 # Condense multiple spaces and eliminate newlines putting the
79 # parameters together on a single line. Ensure there is a
80 # space in an argument which is split by a newline without
81 # intervening whitespace, e.g.: int\nBar
82 args = re.sub(' +', ' ', args_strings.replace('\n', ' '))
83
84 # Create the prototype.
85 indent = ' ' * _INDENT
86 line = ('%s%s(%s,\n%s%s(%s));' %
87 (indent, prefix, node.name, indent*3, return_type, args))
88 output_lines.append(line)
89
90
91 def _GenerateMocks(filename, source, ast_list, desired_class_names):
92 processed_class_names = sets.Set()
93 lines = []
94 for node in ast_list:
95 if (isinstance(node, ast.Class) and node.body and
96 # desired_class_names being None means that all classes are selected.
97 (not desired_class_names or node.name in desired_class_names)):
98 class_name = node.name
99 processed_class_names.add(class_name)
100 class_node = node
101 # Add namespace before the class.
102 if class_node.namespace:
103 lines.extend(['namespace %s {' % n for n in class_node.namespace]) # }
104 lines.append('')
105
106 # Add the class prolog.
107 lines.append('class Mock%s : public %s {' % (class_name, class_name)) # }
108 lines.append('%spublic:' % (' ' * (_INDENT // 2)))
109
110 # Add all the methods.
111 _GenerateMethods(lines, source, class_node)
112
113 # Close the class.
114 if lines:
115 # If there are no virtual methods, no need for a public label.
116 if len(lines) == 2:
117 del lines[-1]
118
119 # Only close the class if there really is a class.
120 lines.append('};')
121 lines.append('') # Add an extra newline.
122
123 # Close the namespace.
124 if class_node.namespace:
125 for i in range(len(class_node.namespace)-1, -1, -1):
126 lines.append('} // namespace %s' % class_node.namespace[i])
127 lines.append('') # Add an extra newline.
128
129 if desired_class_names:
130 missing_class_name_list = list(desired_class_names - processed_class_names)
131 if missing_class_name_list:
132 missing_class_name_list.sort()
133 sys.stderr.write('Class(es) not found in %s: %s\n' %
134 (filename, ', '.join(missing_class_name_list)))
135 elif not processed_class_names:
136 sys.stderr.write('No class found in %s\n' % filename)
137
138 return lines
139
140
141 def main(argv=sys.argv):
142 if len(argv) < 2:
143 sys.stderr.write('Google Mock Class Generator v%s\n\n' %
144 '.'.join(map(str, _VERSION)))
145 sys.stderr.write(__doc__)
146 return 1
147
148 global _INDENT
149 try:
150 _INDENT = int(os.environ['INDENT'])
151 except KeyError:
152 pass
153 except:
154 sys.stderr.write('Unable to use indent of %s\n' % os.environ.get('INDENT'))
155
156 filename = argv[1]
157 desired_class_names = None # None means all classes in the source file.
158 if len(argv) >= 3:
159 desired_class_names = sets.Set(argv[2:])
160 source = utils.ReadFile(filename)
161 if source is None:
162 return 1
163
164 builder = ast.BuilderFromSource(source, filename)
165 try:
166 entire_ast = filter(None, builder.Generate())
167 except KeyboardInterrupt:
168 return
169 except:
170 # An error message was already printed since we couldn't parse.
171 pass
172 else:
173 lines = _GenerateMocks(filename, source, entire_ast, desired_class_names)
174 sys.stdout.write('\n'.join(lines))
175
176
177 if __name__ == '__main__':
178 main(sys.argv)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698