PageRenderTime 65ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/googlemock/scripts/gmock_doctor.py

https://gitlab.com/CORP-RESELLER/googletest
Python | 640 lines | 609 code | 1 blank | 30 comment | 3 complexity | 1a4e999ca122b169f88f27dcaed0a4fa MD5 | raw file
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2008, Google Inc.
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. #
  10. # * Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # * Redistributions in binary form must reproduce the above
  13. # copyright notice, this list of conditions and the following disclaimer
  14. # in the documentation and/or other materials provided with the
  15. # distribution.
  16. # * Neither the name of Google Inc. nor the names of its
  17. # contributors may be used to endorse or promote products derived from
  18. # this software without specific prior written permission.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. """Converts compiler's errors in code using Google Mock to plain English."""
  32. __author__ = 'wan@google.com (Zhanyong Wan)'
  33. import re
  34. import sys
  35. _VERSION = '1.0.3'
  36. _EMAIL = 'googlemock@googlegroups.com'
  37. _COMMON_GMOCK_SYMBOLS = [
  38. # Matchers
  39. '_',
  40. 'A',
  41. 'AddressSatisfies',
  42. 'AllOf',
  43. 'An',
  44. 'AnyOf',
  45. 'ContainerEq',
  46. 'Contains',
  47. 'ContainsRegex',
  48. 'DoubleEq',
  49. 'ElementsAre',
  50. 'ElementsAreArray',
  51. 'EndsWith',
  52. 'Eq',
  53. 'Field',
  54. 'FloatEq',
  55. 'Ge',
  56. 'Gt',
  57. 'HasSubstr',
  58. 'IsInitializedProto',
  59. 'Le',
  60. 'Lt',
  61. 'MatcherCast',
  62. 'Matches',
  63. 'MatchesRegex',
  64. 'NanSensitiveDoubleEq',
  65. 'NanSensitiveFloatEq',
  66. 'Ne',
  67. 'Not',
  68. 'NotNull',
  69. 'Pointee',
  70. 'Property',
  71. 'Ref',
  72. 'ResultOf',
  73. 'SafeMatcherCast',
  74. 'StartsWith',
  75. 'StrCaseEq',
  76. 'StrCaseNe',
  77. 'StrEq',
  78. 'StrNe',
  79. 'Truly',
  80. 'TypedEq',
  81. 'Value',
  82. # Actions
  83. 'Assign',
  84. 'ByRef',
  85. 'DeleteArg',
  86. 'DoAll',
  87. 'DoDefault',
  88. 'IgnoreResult',
  89. 'Invoke',
  90. 'InvokeArgument',
  91. 'InvokeWithoutArgs',
  92. 'Return',
  93. 'ReturnNew',
  94. 'ReturnNull',
  95. 'ReturnRef',
  96. 'SaveArg',
  97. 'SetArgReferee',
  98. 'SetArgPointee',
  99. 'SetArgumentPointee',
  100. 'SetArrayArgument',
  101. 'SetErrnoAndReturn',
  102. 'Throw',
  103. 'WithArg',
  104. 'WithArgs',
  105. 'WithoutArgs',
  106. # Cardinalities
  107. 'AnyNumber',
  108. 'AtLeast',
  109. 'AtMost',
  110. 'Between',
  111. 'Exactly',
  112. # Sequences
  113. 'InSequence',
  114. 'Sequence',
  115. # Misc
  116. 'DefaultValue',
  117. 'Mock',
  118. ]
  119. # Regex for matching source file path and line number in the compiler's errors.
  120. _GCC_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(\d+:)?\s+'
  121. _CLANG_FILE_LINE_RE = r'(?P<file>.*):(?P<line>\d+):(?P<column>\d+):\s+'
  122. _CLANG_NON_GMOCK_FILE_LINE_RE = (
  123. r'(?P<file>.*[/\\^](?!gmock-)[^/\\]+):(?P<line>\d+):(?P<column>\d+):\s+')
  124. def _FindAllMatches(regex, s):
  125. """Generates all matches of regex in string s."""
  126. r = re.compile(regex)
  127. return r.finditer(s)
  128. def _GenericDiagnoser(short_name, long_name, diagnoses, msg):
  129. """Diagnoses the given disease by pattern matching.
  130. Can provide different diagnoses for different patterns.
  131. Args:
  132. short_name: Short name of the disease.
  133. long_name: Long name of the disease.
  134. diagnoses: A list of pairs (regex, pattern for formatting the diagnosis
  135. for matching regex).
  136. msg: Compiler's error messages.
  137. Yields:
  138. Tuples of the form
  139. (short name of disease, long name of disease, diagnosis).
  140. """
  141. for regex, diagnosis in diagnoses:
  142. if re.search(regex, msg):
  143. diagnosis = '%(file)s:%(line)s:' + diagnosis
  144. for m in _FindAllMatches(regex, msg):
  145. yield (short_name, long_name, diagnosis % m.groupdict())
  146. def _NeedToReturnReferenceDiagnoser(msg):
  147. """Diagnoses the NRR disease, given the error messages by the compiler."""
  148. gcc_regex = (r'In member function \'testing::internal::ReturnAction<R>.*\n'
  149. + _GCC_FILE_LINE_RE + r'instantiated from here\n'
  150. r'.*gmock-actions\.h.*error: creating array with negative size')
  151. clang_regex = (r'error:.*array.*negative.*\r?\n'
  152. r'(.*\n)*?' +
  153. _CLANG_NON_GMOCK_FILE_LINE_RE +
  154. r'note: in instantiation of function template specialization '
  155. r'\'testing::internal::ReturnAction<(?P<type>.*)>'
  156. r'::operator Action<.*>\' requested here')
  157. clang11_re = (r'use_ReturnRef_instead_of_Return_to_return_a_reference.*'
  158. r'(.*\n)*?' + _CLANG_NON_GMOCK_FILE_LINE_RE)
  159. diagnosis = """
  160. You are using a Return() action in a function that returns a reference to
  161. %(type)s. Please use ReturnRef() instead."""
  162. return _GenericDiagnoser('NRR', 'Need to Return Reference',
  163. [(clang_regex, diagnosis),
  164. (clang11_re, diagnosis % {'type': 'a type'}),
  165. (gcc_regex, diagnosis % {'type': 'a type'})],
  166. msg)
  167. def _NeedToReturnSomethingDiagnoser(msg):
  168. """Diagnoses the NRS disease, given the error messages by the compiler."""
  169. gcc_regex = (_GCC_FILE_LINE_RE + r'(instantiated from here\n.'
  170. r'*gmock.*actions\.h.*error: void value not ignored)'
  171. r'|(error: control reaches end of non-void function)')
  172. clang_regex1 = (_CLANG_FILE_LINE_RE +
  173. r'error: cannot initialize return object '
  174. r'of type \'Result\' \(aka \'(?P<return_type>.*)\'\) '
  175. r'with an rvalue of type \'void\'')
  176. clang_regex2 = (_CLANG_FILE_LINE_RE +
  177. r'error: cannot initialize return object '
  178. r'of type \'(?P<return_type>.*)\' '
  179. r'with an rvalue of type \'void\'')
  180. diagnosis = """
  181. You are using an action that returns void, but it needs to return
  182. %(return_type)s. Please tell it *what* to return. Perhaps you can use
  183. the pattern DoAll(some_action, Return(some_value))?"""
  184. return _GenericDiagnoser(
  185. 'NRS',
  186. 'Need to Return Something',
  187. [(gcc_regex, diagnosis % {'return_type': '*something*'}),
  188. (clang_regex1, diagnosis),
  189. (clang_regex2, diagnosis)],
  190. msg)
  191. def _NeedToReturnNothingDiagnoser(msg):
  192. """Diagnoses the NRN disease, given the error messages by the compiler."""
  193. gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
  194. r'.*gmock-actions\.h.*error: instantiation of '
  195. r'\'testing::internal::ReturnAction<R>::Impl<F>::value_\' '
  196. r'as type \'void\'')
  197. clang_regex1 = (r'error: field has incomplete type '
  198. r'\'Result\' \(aka \'void\'\)(\r)?\n'
  199. r'(.*\n)*?' +
  200. _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
  201. r'of function template specialization '
  202. r'\'testing::internal::ReturnAction<(?P<return_type>.*)>'
  203. r'::operator Action<void \(.*\)>\' requested here')
  204. clang_regex2 = (r'error: field has incomplete type '
  205. r'\'Result\' \(aka \'void\'\)(\r)?\n'
  206. r'(.*\n)*?' +
  207. _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
  208. r'of function template specialization '
  209. r'\'testing::internal::DoBothAction<.*>'
  210. r'::operator Action<(?P<return_type>.*) \(.*\)>\' '
  211. r'requested here')
  212. diagnosis = """
  213. You are using an action that returns %(return_type)s, but it needs to return
  214. void. Please use a void-returning action instead.
  215. All actions but the last in DoAll(...) must return void. Perhaps you need
  216. to re-arrange the order of actions in a DoAll(), if you are using one?"""
  217. return _GenericDiagnoser(
  218. 'NRN',
  219. 'Need to Return Nothing',
  220. [(gcc_regex, diagnosis % {'return_type': '*something*'}),
  221. (clang_regex1, diagnosis),
  222. (clang_regex2, diagnosis)],
  223. msg)
  224. def _IncompleteByReferenceArgumentDiagnoser(msg):
  225. """Diagnoses the IBRA disease, given the error messages by the compiler."""
  226. gcc_regex = (_GCC_FILE_LINE_RE + r'instantiated from here\n'
  227. r'.*gtest-printers\.h.*error: invalid application of '
  228. r'\'sizeof\' to incomplete type \'(?P<type>.*)\'')
  229. clang_regex = (r'.*gtest-printers\.h.*error: invalid application of '
  230. r'\'sizeof\' to an incomplete type '
  231. r'\'(?P<type>.*)( const)?\'\r?\n'
  232. r'(.*\n)*?' +
  233. _CLANG_NON_GMOCK_FILE_LINE_RE +
  234. r'note: in instantiation of member function '
  235. r'\'testing::internal2::TypeWithoutFormatter<.*>::'
  236. r'PrintValue\' requested here')
  237. diagnosis = """
  238. In order to mock this function, Google Mock needs to see the definition
  239. of type "%(type)s" - declaration alone is not enough. Either #include
  240. the header that defines it, or change the argument to be passed
  241. by pointer."""
  242. return _GenericDiagnoser('IBRA', 'Incomplete By-Reference Argument Type',
  243. [(gcc_regex, diagnosis),
  244. (clang_regex, diagnosis)],
  245. msg)
  246. def _OverloadedFunctionMatcherDiagnoser(msg):
  247. """Diagnoses the OFM disease, given the error messages by the compiler."""
  248. gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
  249. r'call to \'Truly\(<unresolved overloaded function type>\)')
  250. clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function for '
  251. r'call to \'Truly')
  252. diagnosis = """
  253. The argument you gave to Truly() is an overloaded function. Please tell
  254. your compiler which overloaded version you want to use.
  255. For example, if you want to use the version whose signature is
  256. bool Foo(int n);
  257. you should write
  258. Truly(static_cast<bool (*)(int n)>(Foo))"""
  259. return _GenericDiagnoser('OFM', 'Overloaded Function Matcher',
  260. [(gcc_regex, diagnosis),
  261. (clang_regex, diagnosis)],
  262. msg)
  263. def _OverloadedFunctionActionDiagnoser(msg):
  264. """Diagnoses the OFA disease, given the error messages by the compiler."""
  265. gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for call to '
  266. r'\'Invoke\(<unresolved overloaded function type>')
  267. clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching '
  268. r'function for call to \'Invoke\'\r?\n'
  269. r'(.*\n)*?'
  270. r'.*\bgmock-generated-actions\.h:\d+:\d+:\s+'
  271. r'note: candidate template ignored:\s+'
  272. r'couldn\'t infer template argument \'FunctionImpl\'')
  273. diagnosis = """
  274. Function you are passing to Invoke is overloaded. Please tell your compiler
  275. which overloaded version you want to use.
  276. For example, if you want to use the version whose signature is
  277. bool MyFunction(int n, double x);
  278. you should write something like
  279. Invoke(static_cast<bool (*)(int n, double x)>(MyFunction))"""
  280. return _GenericDiagnoser('OFA', 'Overloaded Function Action',
  281. [(gcc_regex, diagnosis),
  282. (clang_regex, diagnosis)],
  283. msg)
  284. def _OverloadedMethodActionDiagnoser(msg):
  285. """Diagnoses the OMA disease, given the error messages by the compiler."""
  286. gcc_regex = (_GCC_FILE_LINE_RE + r'error: no matching function for '
  287. r'call to \'Invoke\(.+, <unresolved overloaded function '
  288. r'type>\)')
  289. clang_regex = (_CLANG_FILE_LINE_RE + r'error: no matching function '
  290. r'for call to \'Invoke\'\r?\n'
  291. r'(.*\n)*?'
  292. r'.*\bgmock-generated-actions\.h:\d+:\d+: '
  293. r'note: candidate function template not viable: '
  294. r'requires .*, but 2 (arguments )?were provided')
  295. diagnosis = """
  296. The second argument you gave to Invoke() is an overloaded method. Please
  297. tell your compiler which overloaded version you want to use.
  298. For example, if you want to use the version whose signature is
  299. class Foo {
  300. ...
  301. bool Bar(int n, double x);
  302. };
  303. you should write something like
  304. Invoke(foo, static_cast<bool (Foo::*)(int n, double x)>(&Foo::Bar))"""
  305. return _GenericDiagnoser('OMA', 'Overloaded Method Action',
  306. [(gcc_regex, diagnosis),
  307. (clang_regex, diagnosis)],
  308. msg)
  309. def _MockObjectPointerDiagnoser(msg):
  310. """Diagnoses the MOP disease, given the error messages by the compiler."""
  311. gcc_regex = (_GCC_FILE_LINE_RE + r'error: request for member '
  312. r'\'gmock_(?P<method>.+)\' in \'(?P<mock_object>.+)\', '
  313. r'which is of non-class type \'(.*::)*(?P<class_name>.+)\*\'')
  314. clang_regex = (_CLANG_FILE_LINE_RE + r'error: member reference type '
  315. r'\'(?P<class_name>.*?) *\' is a pointer; '
  316. r'(did you mean|maybe you meant) to use \'->\'\?')
  317. diagnosis = """
  318. The first argument to ON_CALL() and EXPECT_CALL() must be a mock *object*,
  319. not a *pointer* to it. Please write '*(%(mock_object)s)' instead of
  320. '%(mock_object)s' as your first argument.
  321. For example, given the mock class:
  322. class %(class_name)s : public ... {
  323. ...
  324. MOCK_METHOD0(%(method)s, ...);
  325. };
  326. and the following mock instance:
  327. %(class_name)s* mock_ptr = ...
  328. you should use the EXPECT_CALL like this:
  329. EXPECT_CALL(*mock_ptr, %(method)s(...));"""
  330. return _GenericDiagnoser(
  331. 'MOP',
  332. 'Mock Object Pointer',
  333. [(gcc_regex, diagnosis),
  334. (clang_regex, diagnosis % {'mock_object': 'mock_object',
  335. 'method': 'method',
  336. 'class_name': '%(class_name)s'})],
  337. msg)
  338. def _NeedToUseSymbolDiagnoser(msg):
  339. """Diagnoses the NUS disease, given the error messages by the compiler."""
  340. gcc_regex = (_GCC_FILE_LINE_RE + r'error: \'(?P<symbol>.+)\' '
  341. r'(was not declared in this scope|has not been declared)')
  342. clang_regex = (_CLANG_FILE_LINE_RE +
  343. r'error: (use of undeclared identifier|unknown type name|'
  344. r'no template named) \'(?P<symbol>[^\']+)\'')
  345. diagnosis = """
  346. '%(symbol)s' is defined by Google Mock in the testing namespace.
  347. Did you forget to write
  348. using testing::%(symbol)s;
  349. ?"""
  350. for m in (list(_FindAllMatches(gcc_regex, msg)) +
  351. list(_FindAllMatches(clang_regex, msg))):
  352. symbol = m.groupdict()['symbol']
  353. if symbol in _COMMON_GMOCK_SYMBOLS:
  354. yield ('NUS', 'Need to Use Symbol', diagnosis % m.groupdict())
  355. def _NeedToUseReturnNullDiagnoser(msg):
  356. """Diagnoses the NRNULL disease, given the error messages by the compiler."""
  357. gcc_regex = ('instantiated from \'testing::internal::ReturnAction<R>'
  358. '::operator testing::Action<Func>\(\) const.*\n' +
  359. _GCC_FILE_LINE_RE + r'instantiated from here\n'
  360. r'.*error: no matching function for call to \'ImplicitCast_\('
  361. r'(:?long )?int&\)')
  362. clang_regex = (r'\bgmock-actions.h:.* error: no matching function for '
  363. r'call to \'ImplicitCast_\'\r?\n'
  364. r'(.*\n)*?' +
  365. _CLANG_NON_GMOCK_FILE_LINE_RE + r'note: in instantiation '
  366. r'of function template specialization '
  367. r'\'testing::internal::ReturnAction<(int|long)>::operator '
  368. r'Action<(?P<type>.*)\(\)>\' requested here')
  369. diagnosis = """
  370. You are probably calling Return(NULL) and the compiler isn't sure how to turn
  371. NULL into %(type)s. Use ReturnNull() instead.
  372. Note: the line number may be off; please fix all instances of Return(NULL)."""
  373. return _GenericDiagnoser(
  374. 'NRNULL', 'Need to use ReturnNull',
  375. [(clang_regex, diagnosis),
  376. (gcc_regex, diagnosis % {'type': 'the right type'})],
  377. msg)
  378. def _TypeInTemplatedBaseDiagnoser(msg):
  379. """Diagnoses the TTB disease, given the error messages by the compiler."""
  380. # This version works when the type is used as the mock function's return
  381. # type.
  382. gcc_4_3_1_regex_type_in_retval = (
  383. r'In member function \'int .*\n' + _GCC_FILE_LINE_RE +
  384. r'error: a function call cannot appear in a constant-expression')
  385. gcc_4_4_0_regex_type_in_retval = (
  386. r'error: a function call cannot appear in a constant-expression'
  387. + _GCC_FILE_LINE_RE + r'error: template argument 1 is invalid\n')
  388. # This version works when the type is used as the mock function's sole
  389. # parameter type.
  390. gcc_regex_type_of_sole_param = (
  391. _GCC_FILE_LINE_RE +
  392. r'error: \'(?P<type>.+)\' was not declared in this scope\n'
  393. r'.*error: template argument 1 is invalid\n')
  394. # This version works when the type is used as a parameter of a mock
  395. # function that has multiple parameters.
  396. gcc_regex_type_of_a_param = (
  397. r'error: expected `;\' before \'::\' token\n'
  398. + _GCC_FILE_LINE_RE +
  399. r'error: \'(?P<type>.+)\' was not declared in this scope\n'
  400. r'.*error: template argument 1 is invalid\n'
  401. r'.*error: \'.+\' was not declared in this scope')
  402. clang_regex_type_of_retval_or_sole_param = (
  403. _CLANG_FILE_LINE_RE +
  404. r'error: use of undeclared identifier \'(?P<type>.*)\'\n'
  405. r'(.*\n)*?'
  406. r'(?P=file):(?P=line):\d+: error: '
  407. r'non-friend class member \'Result\' cannot have a qualified name'
  408. )
  409. clang_regex_type_of_a_param = (
  410. _CLANG_FILE_LINE_RE +
  411. r'error: C\+\+ requires a type specifier for all declarations\n'
  412. r'(.*\n)*?'
  413. r'(?P=file):(?P=line):(?P=column): error: '
  414. r'C\+\+ requires a type specifier for all declarations'
  415. )
  416. clang_regex_unknown_type = (
  417. _CLANG_FILE_LINE_RE +
  418. r'error: unknown type name \'(?P<type>[^\']+)\''
  419. )
  420. diagnosis = """
  421. In a mock class template, types or typedefs defined in the base class
  422. template are *not* automatically visible. This is how C++ works. Before
  423. you can use a type or typedef named %(type)s defined in base class Base<T>, you
  424. need to make it visible. One way to do it is:
  425. typedef typename Base<T>::%(type)s %(type)s;"""
  426. for diag in _GenericDiagnoser(
  427. 'TTB', 'Type in Template Base',
  428. [(gcc_4_3_1_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
  429. (gcc_4_4_0_regex_type_in_retval, diagnosis % {'type': 'Foo'}),
  430. (gcc_regex_type_of_sole_param, diagnosis),
  431. (gcc_regex_type_of_a_param, diagnosis),
  432. (clang_regex_type_of_retval_or_sole_param, diagnosis),
  433. (clang_regex_type_of_a_param, diagnosis % {'type': 'Foo'})],
  434. msg):
  435. yield diag
  436. # Avoid overlap with the NUS pattern.
  437. for m in _FindAllMatches(clang_regex_unknown_type, msg):
  438. type_ = m.groupdict()['type']
  439. if type_ not in _COMMON_GMOCK_SYMBOLS:
  440. yield ('TTB', 'Type in Template Base', diagnosis % m.groupdict())
  441. def _WrongMockMethodMacroDiagnoser(msg):
  442. """Diagnoses the WMM disease, given the error messages by the compiler."""
  443. gcc_regex = (_GCC_FILE_LINE_RE +
  444. r'.*this_method_does_not_take_(?P<wrong_args>\d+)_argument.*\n'
  445. r'.*\n'
  446. r'.*candidates are.*FunctionMocker<[^>]+A(?P<args>\d+)\)>')
  447. clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
  448. r'error:.*array.*negative.*r?\n'
  449. r'(.*\n)*?'
  450. r'(?P=file):(?P=line):(?P=column): error: too few arguments '
  451. r'to function call, expected (?P<args>\d+), '
  452. r'have (?P<wrong_args>\d+)')
  453. clang11_re = (_CLANG_NON_GMOCK_FILE_LINE_RE +
  454. r'.*this_method_does_not_take_'
  455. r'(?P<wrong_args>\d+)_argument.*')
  456. diagnosis = """
  457. You are using MOCK_METHOD%(wrong_args)s to define a mock method that has
  458. %(args)s arguments. Use MOCK_METHOD%(args)s (or MOCK_CONST_METHOD%(args)s,
  459. MOCK_METHOD%(args)s_T, MOCK_CONST_METHOD%(args)s_T as appropriate) instead."""
  460. return _GenericDiagnoser('WMM', 'Wrong MOCK_METHODn Macro',
  461. [(gcc_regex, diagnosis),
  462. (clang11_re, diagnosis % {'wrong_args': 'm',
  463. 'args': 'n'}),
  464. (clang_regex, diagnosis)],
  465. msg)
  466. def _WrongParenPositionDiagnoser(msg):
  467. """Diagnoses the WPP disease, given the error messages by the compiler."""
  468. gcc_regex = (_GCC_FILE_LINE_RE +
  469. r'error:.*testing::internal::MockSpec<.* has no member named \''
  470. r'(?P<method>\w+)\'')
  471. clang_regex = (_CLANG_NON_GMOCK_FILE_LINE_RE +
  472. r'error: no member named \'(?P<method>\w+)\' in '
  473. r'\'testing::internal::MockSpec<.*>\'')
  474. diagnosis = """
  475. The closing parenthesis of ON_CALL or EXPECT_CALL should be *before*
  476. ".%(method)s". For example, you should write:
  477. EXPECT_CALL(my_mock, Foo(_)).%(method)s(...);
  478. instead of:
  479. EXPECT_CALL(my_mock, Foo(_).%(method)s(...));"""
  480. return _GenericDiagnoser('WPP', 'Wrong Parenthesis Position',
  481. [(gcc_regex, diagnosis),
  482. (clang_regex, diagnosis)],
  483. msg)
  484. _DIAGNOSERS = [
  485. _IncompleteByReferenceArgumentDiagnoser,
  486. _MockObjectPointerDiagnoser,
  487. _NeedToReturnNothingDiagnoser,
  488. _NeedToReturnReferenceDiagnoser,
  489. _NeedToReturnSomethingDiagnoser,
  490. _NeedToUseReturnNullDiagnoser,
  491. _NeedToUseSymbolDiagnoser,
  492. _OverloadedFunctionActionDiagnoser,
  493. _OverloadedFunctionMatcherDiagnoser,
  494. _OverloadedMethodActionDiagnoser,
  495. _TypeInTemplatedBaseDiagnoser,
  496. _WrongMockMethodMacroDiagnoser,
  497. _WrongParenPositionDiagnoser,
  498. ]
  499. def Diagnose(msg):
  500. """Generates all possible diagnoses given the compiler error message."""
  501. msg = re.sub(r'\x1b\[[^m]*m', '', msg) # Strips all color formatting.
  502. # Assuming the string is using the UTF-8 encoding, replaces the left and
  503. # the right single quote characters with apostrophes.
  504. msg = re.sub(r'(\xe2\x80\x98|\xe2\x80\x99)', "'", msg)
  505. diagnoses = []
  506. for diagnoser in _DIAGNOSERS:
  507. for diag in diagnoser(msg):
  508. diagnosis = '[%s - %s]\n%s' % diag
  509. if not diagnosis in diagnoses:
  510. diagnoses.append(diagnosis)
  511. return diagnoses
  512. def main():
  513. print ('Google Mock Doctor v%s - '
  514. 'diagnoses problems in code using Google Mock.' % _VERSION)
  515. if sys.stdin.isatty():
  516. print ('Please copy and paste the compiler errors here. Press c-D when '
  517. 'you are done:')
  518. else:
  519. print ('Waiting for compiler errors on stdin . . .')
  520. msg = sys.stdin.read().strip()
  521. diagnoses = Diagnose(msg)
  522. count = len(diagnoses)
  523. if not count:
  524. print ("""
  525. Your compiler complained:
  526. 8<------------------------------------------------------------
  527. %s
  528. ------------------------------------------------------------>8
  529. Uh-oh, I'm not smart enough to figure out what the problem is. :-(
  530. However...
  531. If you send your source code and the compiler's error messages to
  532. %s, you can be helped and I can get smarter --
  533. win-win for us!""" % (msg, _EMAIL))
  534. else:
  535. print ('------------------------------------------------------------')
  536. print ('Your code appears to have the following',)
  537. if count > 1:
  538. print ('%s diseases:' % (count,))
  539. else:
  540. print ('disease:')
  541. i = 0
  542. for d in diagnoses:
  543. i += 1
  544. if count > 1:
  545. print ('\n#%s:' % (i,))
  546. print (d)
  547. print ("""
  548. How did I do? If you think I'm wrong or unhelpful, please send your
  549. source code and the compiler's error messages to %s.
  550. Then you can be helped and I can get smarter -- I promise I won't be upset!""" %
  551. _EMAIL)
  552. if __name__ == '__main__':
  553. main()