PageRenderTime 38ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/contrib/bin/cpplint.py

https://bitbucket.org/vijaysm/libmesh
Python | 3363 lines | 2692 code | 155 blank | 516 comment | 237 complexity | 2c61f1237429fdb8083e08fbc4a32960 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, GPL-3.0, MPL-2.0-no-copyleft-exception, GPL-2.0
  1. #!/usr/bin/python
  2. #
  3. # Copyright (c) 2009 Google Inc. All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. # Here are some issues that I've had people identify in my code during reviews,
  31. # that I think are possible to flag automatically in a lint tool. If these were
  32. # caught by lint, it would save time both for myself and that of my reviewers.
  33. # Most likely, some of these are beyond the scope of the current lint framework,
  34. # but I think it is valuable to retain these wish-list items even if they cannot
  35. # be immediately implemented.
  36. #
  37. # Suggestions
  38. # -----------
  39. # - Check for no 'explicit' for multi-arg ctor
  40. # - Check for boolean assign RHS in parens
  41. # - Check for ctor initializer-list colon position and spacing
  42. # - Check that if there's a ctor, there should be a dtor
  43. # - Check accessors that return non-pointer member variables are
  44. # declared const
  45. # - Check accessors that return non-const pointer member vars are
  46. # *not* declared const
  47. # - Check for using public includes for testing
  48. # - Check for spaces between brackets in one-line inline method
  49. # - Check for no assert()
  50. # - Check for spaces surrounding operators
  51. # - Check for 0 in pointer context (should be NULL)
  52. # - Check for 0 in char context (should be '\0')
  53. # - Check for camel-case method name conventions for methods
  54. # that are not simple inline getters and setters
  55. # - Check that base classes have virtual destructors
  56. # put " // namespace" after } that closes a namespace, with
  57. # namespace's name after 'namespace' if it is named.
  58. # - Do not indent namespace contents
  59. # - Avoid inlining non-trivial constructors in header files
  60. # include base/basictypes.h if DISALLOW_EVIL_CONSTRUCTORS is used
  61. # - Check for old-school (void) cast for call-sites of functions
  62. # ignored return value
  63. # - Check gUnit usage of anonymous namespace
  64. # - Check for class declaration order (typedefs, consts, enums,
  65. # ctor(s?), dtor, friend declarations, methods, member vars)
  66. #
  67. """Does google-lint on c++ files.
  68. The goal of this script is to identify places in the code that *may*
  69. be in non-compliance with google style. It does not attempt to fix
  70. up these problems -- the point is to educate. It does also not
  71. attempt to find all problems, or to ensure that everything it does
  72. find is legitimately a problem.
  73. In particular, we can get very confused by /* and // inside strings!
  74. We do a small hack, which is to ignore //'s with "'s after them on the
  75. same line, but it is far from perfect (in either direction).
  76. """
  77. import codecs
  78. import getopt
  79. import math # for log
  80. import os
  81. import re
  82. import sre_compile
  83. import string
  84. import sys
  85. import unicodedata
  86. _USAGE = """
  87. Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
  88. [--counting=total|toplevel|detailed]
  89. <file> [file] ...
  90. The style guidelines this tries to follow are those in
  91. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
  92. Every problem is given a confidence score from 1-5, with 5 meaning we are
  93. certain of the problem, and 1 meaning it could be a legitimate construct.
  94. This will miss some errors, and is not a substitute for a code review.
  95. To suppress false-positive errors of a certain category, add a
  96. 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
  97. suppresses errors of all categories on that line.
  98. The files passed in will be linted; at least one file must be provided.
  99. Linted extensions are .cc, .cpp, and .h. Other file types will be ignored.
  100. [RHS 2012] - added support for .C
  101. Flags:
  102. output=vs7
  103. By default, the output is formatted to ease emacs parsing. Visual Studio
  104. compatible output (vs7) may also be used. Other formats are unsupported.
  105. verbose=#
  106. Specify a number 0-5 to restrict errors to certain verbosity levels.
  107. filter=-x,+y,...
  108. Specify a comma-separated list of category-filters to apply: only
  109. error messages whose category names pass the filters will be printed.
  110. (Category names are printed with the message and look like
  111. "[whitespace/indent]".) Filters are evaluated left to right.
  112. "-FOO" and "FOO" means "do not print categories that start with FOO".
  113. "+FOO" means "do print categories that start with FOO".
  114. Examples: --filter=-whitespace,+whitespace/braces
  115. --filter=whitespace,runtime/printf,+runtime/printf_format
  116. --filter=-,+build/include_what_you_use
  117. To see a list of all the categories used in cpplint, pass no arg:
  118. --filter=
  119. counting=total|toplevel|detailed
  120. The total number of errors found is always printed. If
  121. 'toplevel' is provided, then the count of errors in each of
  122. the top-level categories like 'build' and 'whitespace' will
  123. also be printed. If 'detailed' is provided, then a count
  124. is provided for each category like 'build/class'.
  125. """
  126. # We categorize each error message we print. Here are the categories.
  127. # We want an explicit list so we can list them all in cpplint --filter=.
  128. # If you add a new error message with a new category, add it to the list
  129. # here! cpplint_unittest.py should tell you if you forget to do this.
  130. # \ used for clearer layout -- pylint: disable-msg=C6013
  131. _ERROR_CATEGORIES = [
  132. 'build/class',
  133. 'build/deprecated',
  134. 'build/endif_comment',
  135. 'build/explicit_make_pair',
  136. 'build/forward_decl',
  137. 'build/header_guard',
  138. 'build/include',
  139. 'build/include_alpha',
  140. 'build/include_order',
  141. 'build/include_what_you_use',
  142. 'build/namespaces',
  143. 'build/printf_format',
  144. 'build/storage_class',
  145. 'legal/copyright',
  146. 'readability/braces',
  147. 'readability/casting',
  148. 'readability/check',
  149. 'readability/constructors',
  150. 'readability/fn_size',
  151. 'readability/function',
  152. 'readability/multiline_comment',
  153. 'readability/multiline_string',
  154. 'readability/nolint',
  155. 'readability/streams',
  156. 'readability/todo',
  157. 'readability/utf8',
  158. 'runtime/arrays',
  159. 'runtime/casting',
  160. 'runtime/explicit',
  161. 'runtime/int',
  162. 'runtime/init',
  163. 'runtime/invalid_increment',
  164. 'runtime/member_string_references',
  165. 'runtime/memset',
  166. 'runtime/operator',
  167. 'runtime/printf',
  168. 'runtime/printf_format',
  169. 'runtime/references',
  170. 'runtime/rtti',
  171. 'runtime/sizeof',
  172. 'runtime/string',
  173. 'runtime/threadsafe_fn',
  174. 'runtime/virtual',
  175. 'whitespace/blank_line',
  176. 'whitespace/braces',
  177. 'whitespace/comma',
  178. 'whitespace/comments',
  179. 'whitespace/end_of_line',
  180. 'whitespace/ending_newline',
  181. 'whitespace/indent',
  182. 'whitespace/labels',
  183. 'whitespace/line_length',
  184. 'whitespace/newline',
  185. 'whitespace/operators',
  186. 'whitespace/parens',
  187. 'whitespace/semicolon',
  188. 'whitespace/tab',
  189. 'whitespace/todo'
  190. ]
  191. # The default state of the category filter. This is overrided by the --filter=
  192. # flag. By default all errors are on, so only add here categories that should be
  193. # off by default (i.e., categories that must be enabled by the --filter= flags).
  194. # All entries here should start with a '-' or '+', as in the --filter= flag.
  195. _DEFAULT_FILTERS = ['-build/include_alpha']
  196. # We used to check for high-bit characters, but after much discussion we
  197. # decided those were OK, as long as they were in UTF-8 and didn't represent
  198. # hard-coded international strings, which belong in a separate i18n file.
  199. # Headers that we consider STL headers.
  200. _STL_HEADERS = frozenset([
  201. 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception',
  202. 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set',
  203. 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'new',
  204. 'pair.h', 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack',
  205. 'stl_alloc.h', 'stl_relops.h', 'type_traits.h',
  206. 'utility', 'vector', 'vector.h',
  207. ])
  208. # Non-STL C++ system headers.
  209. _CPP_HEADERS = frozenset([
  210. 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype',
  211. 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath',
  212. 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef',
  213. 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype',
  214. 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream',
  215. 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip',
  216. 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream',
  217. 'istream.h', 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
  218. 'numeric', 'ostream', 'ostream.h', 'parsestream.h', 'pfstream.h',
  219. 'PlotFile.h', 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h',
  220. 'ropeimpl.h', 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
  221. 'stdiostream.h', 'streambuf.h', 'stream.h', 'strfile.h', 'string',
  222. 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray',
  223. ])
  224. # Assertion macros. These are defined in base/logging.h and
  225. # testing/base/gunit.h. Note that the _M versions need to come first
  226. # for substring matching to work.
  227. _CHECK_MACROS = [
  228. 'DCHECK', 'CHECK',
  229. 'EXPECT_TRUE_M', 'EXPECT_TRUE',
  230. 'ASSERT_TRUE_M', 'ASSERT_TRUE',
  231. 'EXPECT_FALSE_M', 'EXPECT_FALSE',
  232. 'ASSERT_FALSE_M', 'ASSERT_FALSE',
  233. ]
  234. # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
  235. _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
  236. for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
  237. ('>=', 'GE'), ('>', 'GT'),
  238. ('<=', 'LE'), ('<', 'LT')]:
  239. _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
  240. _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
  241. _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
  242. _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
  243. _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
  244. _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
  245. for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
  246. ('>=', 'LT'), ('>', 'LE'),
  247. ('<=', 'GT'), ('<', 'GE')]:
  248. _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
  249. _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
  250. _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
  251. _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
  252. # These constants define types of headers for use with
  253. # _IncludeState.CheckNextIncludeOrder().
  254. _C_SYS_HEADER = 1
  255. _CPP_SYS_HEADER = 2
  256. _LIKELY_MY_HEADER = 3
  257. _POSSIBLE_MY_HEADER = 4
  258. _OTHER_HEADER = 5
  259. _regexp_compile_cache = {}
  260. # Finds occurrences of NOLINT or NOLINT(...).
  261. _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?')
  262. # {str, set(int)}: a map from error categories to sets of linenumbers
  263. # on which those errors are expected and should be suppressed.
  264. _error_suppressions = {}
  265. def ParseNolintSuppressions(filename, raw_line, linenum, error):
  266. """Updates the global list of error-suppressions.
  267. Parses any NOLINT comments on the current line, updating the global
  268. error_suppressions store. Reports an error if the NOLINT comment
  269. was malformed.
  270. Args:
  271. filename: str, the name of the input file.
  272. raw_line: str, the line of input text, with comments.
  273. linenum: int, the number of the current line.
  274. error: function, an error handler.
  275. """
  276. # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
  277. matched = _RE_SUPPRESSION.search(raw_line)
  278. if matched:
  279. category = matched.group(1)
  280. if category in (None, '(*)'): # => "suppress all"
  281. _error_suppressions.setdefault(None, set()).add(linenum)
  282. else:
  283. if category.startswith('(') and category.endswith(')'):
  284. category = category[1:-1]
  285. if category in _ERROR_CATEGORIES:
  286. _error_suppressions.setdefault(category, set()).add(linenum)
  287. else:
  288. error(filename, linenum, 'readability/nolint', 5,
  289. 'Unknown NOLINT error category: %s' % category)
  290. def ResetNolintSuppressions():
  291. "Resets the set of NOLINT suppressions to empty."
  292. _error_suppressions.clear()
  293. def IsErrorSuppressedByNolint(category, linenum):
  294. """Returns true if the specified error category is suppressed on this line.
  295. Consults the global error_suppressions map populated by
  296. ParseNolintSuppressions/ResetNolintSuppressions.
  297. Args:
  298. category: str, the category of the error.
  299. linenum: int, the current line number.
  300. Returns:
  301. bool, True iff the error should be suppressed due to a NOLINT comment.
  302. """
  303. return (linenum in _error_suppressions.get(category, set()) or
  304. linenum in _error_suppressions.get(None, set()))
  305. def Match(pattern, s):
  306. """Matches the string with the pattern, caching the compiled regexp."""
  307. # The regexp compilation caching is inlined in both Match and Search for
  308. # performance reasons; factoring it out into a separate function turns out
  309. # to be noticeably expensive.
  310. if not pattern in _regexp_compile_cache:
  311. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  312. return _regexp_compile_cache[pattern].match(s)
  313. def Search(pattern, s):
  314. """Searches the string for the pattern, caching the compiled regexp."""
  315. if not pattern in _regexp_compile_cache:
  316. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  317. return _regexp_compile_cache[pattern].search(s)
  318. class _IncludeState(dict):
  319. """Tracks line numbers for includes, and the order in which includes appear.
  320. As a dict, an _IncludeState object serves as a mapping between include
  321. filename and line number on which that file was included.
  322. Call CheckNextIncludeOrder() once for each header in the file, passing
  323. in the type constants defined above. Calls in an illegal order will
  324. raise an _IncludeError with an appropriate error message.
  325. """
  326. # self._section will move monotonically through this set. If it ever
  327. # needs to move backwards, CheckNextIncludeOrder will raise an error.
  328. _INITIAL_SECTION = 0
  329. _MY_H_SECTION = 1
  330. _C_SECTION = 2
  331. _CPP_SECTION = 3
  332. _OTHER_H_SECTION = 4
  333. _TYPE_NAMES = {
  334. _C_SYS_HEADER: 'C system header',
  335. _CPP_SYS_HEADER: 'C++ system header',
  336. _LIKELY_MY_HEADER: 'header this file implements',
  337. _POSSIBLE_MY_HEADER: 'header this file may implement',
  338. _OTHER_HEADER: 'other header',
  339. }
  340. _SECTION_NAMES = {
  341. _INITIAL_SECTION: "... nothing. (This can't be an error.)",
  342. _MY_H_SECTION: 'a header this file implements',
  343. _C_SECTION: 'C system header',
  344. _CPP_SECTION: 'C++ system header',
  345. _OTHER_H_SECTION: 'other header',
  346. }
  347. def __init__(self):
  348. dict.__init__(self)
  349. # The name of the current section.
  350. self._section = self._INITIAL_SECTION
  351. # The path of last found header.
  352. self._last_header = ''
  353. def CanonicalizeAlphabeticalOrder(self, header_path):
  354. """Returns a path canonicalized for alphabetical comparison.
  355. - replaces "-" with "_" so they both cmp the same.
  356. - removes '-inl' since we don't require them to be after the main header.
  357. - lowercase everything, just in case.
  358. Args:
  359. header_path: Path to be canonicalized.
  360. Returns:
  361. Canonicalized path.
  362. """
  363. return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
  364. def IsInAlphabeticalOrder(self, header_path):
  365. """Check if a header is in alphabetical order with the previous header.
  366. Args:
  367. header_path: Header to be checked.
  368. Returns:
  369. Returns true if the header is in alphabetical order.
  370. """
  371. canonical_header = self.CanonicalizeAlphabeticalOrder(header_path)
  372. if self._last_header > canonical_header:
  373. return False
  374. self._last_header = canonical_header
  375. return True
  376. def CheckNextIncludeOrder(self, header_type):
  377. """Returns a non-empty error message if the next header is out of order.
  378. This function also updates the internal state to be ready to check
  379. the next include.
  380. Args:
  381. header_type: One of the _XXX_HEADER constants defined above.
  382. Returns:
  383. The empty string if the header is in the right order, or an
  384. error message describing what's wrong.
  385. """
  386. error_message = ('Found %s after %s' %
  387. (self._TYPE_NAMES[header_type],
  388. self._SECTION_NAMES[self._section]))
  389. last_section = self._section
  390. if header_type == _C_SYS_HEADER:
  391. if self._section <= self._C_SECTION:
  392. self._section = self._C_SECTION
  393. else:
  394. self._last_header = ''
  395. return error_message
  396. elif header_type == _CPP_SYS_HEADER:
  397. if self._section <= self._CPP_SECTION:
  398. self._section = self._CPP_SECTION
  399. else:
  400. self._last_header = ''
  401. return error_message
  402. elif header_type == _LIKELY_MY_HEADER:
  403. if self._section <= self._MY_H_SECTION:
  404. self._section = self._MY_H_SECTION
  405. else:
  406. self._section = self._OTHER_H_SECTION
  407. elif header_type == _POSSIBLE_MY_HEADER:
  408. if self._section <= self._MY_H_SECTION:
  409. self._section = self._MY_H_SECTION
  410. else:
  411. # This will always be the fallback because we're not sure
  412. # enough that the header is associated with this file.
  413. self._section = self._OTHER_H_SECTION
  414. else:
  415. assert header_type == _OTHER_HEADER
  416. self._section = self._OTHER_H_SECTION
  417. if last_section != self._section:
  418. self._last_header = ''
  419. return ''
  420. class _CppLintState(object):
  421. """Maintains module-wide state.."""
  422. def __init__(self):
  423. self.verbose_level = 1 # global setting.
  424. self.error_count = 0 # global count of reported errors
  425. # filters to apply when emitting error messages
  426. self.filters = _DEFAULT_FILTERS[:]
  427. self.counting = 'total' # In what way are we counting errors?
  428. self.errors_by_category = {} # string to int dict storing error counts
  429. # output format:
  430. # "emacs" - format that emacs can parse (default)
  431. # "vs7" - format that Microsoft Visual Studio 7 can parse
  432. self.output_format = 'emacs'
  433. def SetOutputFormat(self, output_format):
  434. """Sets the output format for errors."""
  435. self.output_format = output_format
  436. def SetVerboseLevel(self, level):
  437. """Sets the module's verbosity, and returns the previous setting."""
  438. last_verbose_level = self.verbose_level
  439. self.verbose_level = level
  440. return last_verbose_level
  441. def SetCountingStyle(self, counting_style):
  442. """Sets the module's counting options."""
  443. self.counting = counting_style
  444. def SetFilters(self, filters):
  445. """Sets the error-message filters.
  446. These filters are applied when deciding whether to emit a given
  447. error message.
  448. Args:
  449. filters: A string of comma-separated filters (eg "+whitespace/indent").
  450. Each filter should start with + or -; else we die.
  451. Raises:
  452. ValueError: The comma-separated filters did not all start with '+' or '-'.
  453. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
  454. """
  455. # Default filters always have less priority than the flag ones.
  456. self.filters = _DEFAULT_FILTERS[:]
  457. for filt in filters.split(','):
  458. clean_filt = filt.strip()
  459. if clean_filt:
  460. self.filters.append(clean_filt)
  461. for filt in self.filters:
  462. if not (filt.startswith('+') or filt.startswith('-')):
  463. raise ValueError('Every filter in --filters must start with + or -'
  464. ' (%s does not)' % filt)
  465. def ResetErrorCounts(self):
  466. """Sets the module's error statistic back to zero."""
  467. self.error_count = 0
  468. self.errors_by_category = {}
  469. def IncrementErrorCount(self, category):
  470. """Bumps the module's error statistic."""
  471. self.error_count += 1
  472. if self.counting in ('toplevel', 'detailed'):
  473. if self.counting != 'detailed':
  474. category = category.split('/')[0]
  475. if category not in self.errors_by_category:
  476. self.errors_by_category[category] = 0
  477. self.errors_by_category[category] += 1
  478. def PrintErrorCounts(self):
  479. """Print a summary of errors by category, and the total."""
  480. for category, count in self.errors_by_category.iteritems():
  481. sys.stderr.write('Category \'%s\' errors found: %d\n' %
  482. (category, count))
  483. sys.stderr.write('Total errors found: %d\n' % self.error_count)
  484. _cpplint_state = _CppLintState()
  485. def _OutputFormat():
  486. """Gets the module's output format."""
  487. return _cpplint_state.output_format
  488. def _SetOutputFormat(output_format):
  489. """Sets the module's output format."""
  490. _cpplint_state.SetOutputFormat(output_format)
  491. def _VerboseLevel():
  492. """Returns the module's verbosity setting."""
  493. return _cpplint_state.verbose_level
  494. def _SetVerboseLevel(level):
  495. """Sets the module's verbosity, and returns the previous setting."""
  496. return _cpplint_state.SetVerboseLevel(level)
  497. def _SetCountingStyle(level):
  498. """Sets the module's counting options."""
  499. _cpplint_state.SetCountingStyle(level)
  500. def _Filters():
  501. """Returns the module's list of output filters, as a list."""
  502. return _cpplint_state.filters
  503. def _SetFilters(filters):
  504. """Sets the module's error-message filters.
  505. These filters are applied when deciding whether to emit a given
  506. error message.
  507. Args:
  508. filters: A string of comma-separated filters (eg "whitespace/indent").
  509. Each filter should start with + or -; else we die.
  510. """
  511. _cpplint_state.SetFilters(filters)
  512. class _FunctionState(object):
  513. """Tracks current function name and the number of lines in its body."""
  514. _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
  515. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
  516. def __init__(self):
  517. self.in_a_function = False
  518. self.lines_in_function = 0
  519. self.current_function = ''
  520. def Begin(self, function_name):
  521. """Start analyzing function body.
  522. Args:
  523. function_name: The name of the function being tracked.
  524. """
  525. self.in_a_function = True
  526. self.lines_in_function = 0
  527. self.current_function = function_name
  528. def Count(self):
  529. """Count line in current function body."""
  530. if self.in_a_function:
  531. self.lines_in_function += 1
  532. def Check(self, error, filename, linenum):
  533. """Report if too many lines in function body.
  534. Args:
  535. error: The function to call with any errors found.
  536. filename: The name of the current file.
  537. linenum: The number of the line to check.
  538. """
  539. if Match(r'T(EST|est)', self.current_function):
  540. base_trigger = self._TEST_TRIGGER
  541. else:
  542. base_trigger = self._NORMAL_TRIGGER
  543. trigger = base_trigger * 2**_VerboseLevel()
  544. if self.lines_in_function > trigger:
  545. error_level = int(math.log(self.lines_in_function / base_trigger, 2))
  546. # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
  547. if error_level > 5:
  548. error_level = 5
  549. error(filename, linenum, 'readability/fn_size', error_level,
  550. 'Small and focused functions are preferred:'
  551. ' %s has %d non-comment lines'
  552. ' (error triggered by exceeding %d lines).' % (
  553. self.current_function, self.lines_in_function, trigger))
  554. def End(self):
  555. """Stop analyzing function body."""
  556. self.in_a_function = False
  557. class _IncludeError(Exception):
  558. """Indicates a problem with the include order in a file."""
  559. pass
  560. class FileInfo:
  561. """Provides utility functions for filenames.
  562. FileInfo provides easy access to the components of a file's path
  563. relative to the project root.
  564. """
  565. def __init__(self, filename):
  566. self._filename = filename
  567. def FullName(self):
  568. """Make Windows paths like Unix."""
  569. return os.path.abspath(self._filename).replace('\\', '/')
  570. def RepositoryName(self):
  571. """FullName after removing the local path to the repository.
  572. If we have a real absolute path name here we can try to do something smart:
  573. detecting the root of the checkout and truncating /path/to/checkout from
  574. the name so that we get header guards that don't include things like
  575. "C:\Documents and Settings\..." or "/home/username/..." in them and thus
  576. people on different computers who have checked the source out to different
  577. locations won't see bogus errors.
  578. """
  579. fullname = self.FullName()
  580. if os.path.exists(fullname):
  581. project_dir = os.path.dirname(fullname)
  582. if os.path.exists(os.path.join(project_dir, ".svn")):
  583. # If there's a .svn file in the current directory, we recursively look
  584. # up the directory tree for the top of the SVN checkout
  585. root_dir = project_dir
  586. one_up_dir = os.path.dirname(root_dir)
  587. while os.path.exists(os.path.join(one_up_dir, ".svn")):
  588. root_dir = os.path.dirname(root_dir)
  589. one_up_dir = os.path.dirname(one_up_dir)
  590. prefix = os.path.commonprefix([root_dir, project_dir])
  591. return fullname[len(prefix) + 1:]
  592. # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
  593. # searching up from the current path.
  594. root_dir = os.path.dirname(fullname)
  595. while (root_dir != os.path.dirname(root_dir) and
  596. not os.path.exists(os.path.join(root_dir, ".git")) and
  597. not os.path.exists(os.path.join(root_dir, ".hg")) and
  598. not os.path.exists(os.path.join(root_dir, ".svn"))):
  599. root_dir = os.path.dirname(root_dir)
  600. if (os.path.exists(os.path.join(root_dir, ".git")) or
  601. os.path.exists(os.path.join(root_dir, ".hg")) or
  602. os.path.exists(os.path.join(root_dir, ".svn"))):
  603. prefix = os.path.commonprefix([root_dir, project_dir])
  604. return fullname[len(prefix) + 1:]
  605. # Don't know what to do; header guard warnings may be wrong...
  606. return fullname
  607. def Split(self):
  608. """Splits the file into the directory, basename, and extension.
  609. For 'chrome/browser/browser.cc', Split() would
  610. return ('chrome/browser', 'browser', '.cc')
  611. Returns:
  612. A tuple of (directory, basename, extension).
  613. """
  614. googlename = self.RepositoryName()
  615. project, rest = os.path.split(googlename)
  616. return (project,) + os.path.splitext(rest)
  617. def BaseName(self):
  618. """File base name - text after the final slash, before the final period."""
  619. return self.Split()[1]
  620. def Extension(self):
  621. """File extension - text following the final period."""
  622. return self.Split()[2]
  623. def NoExtension(self):
  624. """File has no source file extension."""
  625. return '/'.join(self.Split()[0:2])
  626. def IsSource(self):
  627. """File has a source file extension."""
  628. return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx', 'C')
  629. def _ShouldPrintError(category, confidence, linenum):
  630. """If confidence >= verbose, category passes filter and is not suppressed."""
  631. # There are three ways we might decide not to print an error message:
  632. # a "NOLINT(category)" comment appears in the source,
  633. # the verbosity level isn't high enough, or the filters filter it out.
  634. if IsErrorSuppressedByNolint(category, linenum):
  635. return False
  636. if confidence < _cpplint_state.verbose_level:
  637. return False
  638. is_filtered = False
  639. for one_filter in _Filters():
  640. if one_filter.startswith('-'):
  641. if category.startswith(one_filter[1:]):
  642. is_filtered = True
  643. elif one_filter.startswith('+'):
  644. if category.startswith(one_filter[1:]):
  645. is_filtered = False
  646. else:
  647. assert False # should have been checked for in SetFilter.
  648. if is_filtered:
  649. return False
  650. return True
  651. def Error(filename, linenum, category, confidence, message):
  652. """Logs the fact we've found a lint error.
  653. We log where the error was found, and also our confidence in the error,
  654. that is, how certain we are this is a legitimate style regression, and
  655. not a misidentification or a use that's sometimes justified.
  656. False positives can be suppressed by the use of
  657. "cpplint(category)" comments on the offending line. These are
  658. parsed into _error_suppressions.
  659. Args:
  660. filename: The name of the file containing the error.
  661. linenum: The number of the line containing the error.
  662. category: A string used to describe the "category" this bug
  663. falls under: "whitespace", say, or "runtime". Categories
  664. may have a hierarchy separated by slashes: "whitespace/indent".
  665. confidence: A number from 1-5 representing a confidence score for
  666. the error, with 5 meaning that we are certain of the problem,
  667. and 1 meaning that it could be a legitimate construct.
  668. message: The error message.
  669. """
  670. if _ShouldPrintError(category, confidence, linenum):
  671. _cpplint_state.IncrementErrorCount(category)
  672. if _cpplint_state.output_format == 'vs7':
  673. sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
  674. filename, linenum, message, category, confidence))
  675. else:
  676. sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
  677. filename, linenum, message, category, confidence))
  678. # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard.
  679. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
  680. r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
  681. # Matches strings. Escape codes should already be removed by ESCAPES.
  682. _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
  683. # Matches characters. Escape codes should already be removed by ESCAPES.
  684. _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
  685. # Matches multi-line C++ comments.
  686. # This RE is a little bit more complicated than one might expect, because we
  687. # have to take care of space removals tools so we can handle comments inside
  688. # statements better.
  689. # The current rule is: We only clear spaces from both sides when we're at the
  690. # end of the line. Otherwise, we try to remove spaces from the right side,
  691. # if this doesn't work we try on left side but only if there's a non-character
  692. # on the right.
  693. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
  694. r"""(\s*/\*.*\*/\s*$|
  695. /\*.*\*/\s+|
  696. \s+/\*.*\*/(?=\W)|
  697. /\*.*\*/)""", re.VERBOSE)
  698. def IsCppString(line):
  699. """Does line terminate so, that the next symbol is in string constant.
  700. This function does not consider single-line nor multi-line comments.
  701. Args:
  702. line: is a partial line of code starting from the 0..n.
  703. Returns:
  704. True, if next character appended to 'line' is inside a
  705. string constant.
  706. """
  707. line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
  708. return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
  709. def FindNextMultiLineCommentStart(lines, lineix):
  710. """Find the beginning marker for a multiline comment."""
  711. while lineix < len(lines):
  712. if lines[lineix].strip().startswith('/*'):
  713. # Only return this marker if the comment goes beyond this line
  714. if lines[lineix].strip().find('*/', 2) < 0:
  715. return lineix
  716. lineix += 1
  717. return len(lines)
  718. def FindNextMultiLineCommentEnd(lines, lineix):
  719. """We are inside a comment, find the end marker."""
  720. while lineix < len(lines):
  721. if lines[lineix].strip().endswith('*/'):
  722. return lineix
  723. lineix += 1
  724. return len(lines)
  725. def RemoveMultiLineCommentsFromRange(lines, begin, end):
  726. """Clears a range of lines for multi-line comments."""
  727. # Having // dummy comments makes the lines non-empty, so we will not get
  728. # unnecessary blank line warnings later in the code.
  729. for i in range(begin, end):
  730. lines[i] = '// dummy'
  731. def RemoveMultiLineComments(filename, lines, error):
  732. """Removes multiline (c-style) comments from lines."""
  733. lineix = 0
  734. while lineix < len(lines):
  735. lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
  736. if lineix_begin >= len(lines):
  737. return
  738. lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
  739. if lineix_end >= len(lines):
  740. error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
  741. 'Could not find end of multi-line comment')
  742. return
  743. RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
  744. lineix = lineix_end + 1
  745. def CleanseComments(line):
  746. """Removes //-comments and single-line C-style /* */ comments.
  747. Args:
  748. line: A line of C++ source.
  749. Returns:
  750. The line with single-line comments removed.
  751. """
  752. commentpos = line.find('//')
  753. if commentpos != -1 and not IsCppString(line[:commentpos]):
  754. line = line[:commentpos].rstrip()
  755. # get rid of /* ... */
  756. return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
  757. class CleansedLines(object):
  758. """Holds 3 copies of all lines with different preprocessing applied to them.
  759. 1) elided member contains lines without strings and comments,
  760. 2) lines member contains lines without comments, and
  761. 3) raw member contains all the lines without processing.
  762. All these three members are of <type 'list'>, and of the same length.
  763. """
  764. def __init__(self, lines):
  765. self.elided = []
  766. self.lines = []
  767. self.raw_lines = lines
  768. self.num_lines = len(lines)
  769. for linenum in range(len(lines)):
  770. self.lines.append(CleanseComments(lines[linenum]))
  771. elided = self._CollapseStrings(lines[linenum])
  772. self.elided.append(CleanseComments(elided))
  773. def NumLines(self):
  774. """Returns the number of lines represented."""
  775. return self.num_lines
  776. @staticmethod
  777. def _CollapseStrings(elided):
  778. """Collapses strings and chars on a line to simple "" or '' blocks.
  779. We nix strings first so we're not fooled by text like '"http://"'
  780. Args:
  781. elided: The line being processed.
  782. Returns:
  783. The line with collapsed strings.
  784. """
  785. if not _RE_PATTERN_INCLUDE.match(elided):
  786. # Remove escaped characters first to make quote/single quote collapsing
  787. # basic. Things that look like escaped characters shouldn't occur
  788. # outside of strings and chars.
  789. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
  790. elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
  791. elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
  792. return elided
  793. def CloseExpression(clean_lines, linenum, pos):
  794. """If input points to ( or { or [, finds the position that closes it.
  795. If lines[linenum][pos] points to a '(' or '{' or '[', finds the
  796. linenum/pos that correspond to the closing of the expression.
  797. Args:
  798. clean_lines: A CleansedLines instance containing the file.
  799. linenum: The number of the line to check.
  800. pos: A position on the line.
  801. Returns:
  802. A tuple (line, linenum, pos) pointer *past* the closing brace, or
  803. (line, len(lines), -1) if we never find a close. Note we ignore
  804. strings and comments when matching; and the line we return is the
  805. 'cleansed' line at linenum.
  806. """
  807. line = clean_lines.elided[linenum]
  808. startchar = line[pos]
  809. if startchar not in '({[':
  810. return (line, clean_lines.NumLines(), -1)
  811. if startchar == '(': endchar = ')'
  812. if startchar == '[': endchar = ']'
  813. if startchar == '{': endchar = '}'
  814. num_open = line.count(startchar) - line.count(endchar)
  815. while linenum < clean_lines.NumLines() and num_open > 0:
  816. linenum += 1
  817. line = clean_lines.elided[linenum]
  818. num_open += line.count(startchar) - line.count(endchar)
  819. # OK, now find the endchar that actually got us back to even
  820. endpos = len(line)
  821. while num_open >= 0:
  822. endpos = line.rfind(')', 0, endpos)
  823. num_open -= 1 # chopped off another )
  824. return (line, linenum, endpos + 1)
  825. def CheckForCopyright(filename, lines, error):
  826. """Logs an error if no Copyright message appears at the top of the file."""
  827. # We'll say it should occur by line 10. Don't forget there's a
  828. # dummy line at the front.
  829. for line in xrange(1, min(len(lines), 11)):
  830. if re.search(r'Copyright', lines[line], re.I): break
  831. else: # means no copyright line was found
  832. error(filename, 0, 'legal/copyright', 5,
  833. 'No copyright message found. '
  834. 'You should have a line: "Copyright [year] <Copyright Owner>"')
  835. def GetHeaderGuardCPPVariable(filename):
  836. """Returns the CPP variable that should be used as a header guard.
  837. Args:
  838. filename: The name of a C++ header file.
  839. Returns:
  840. The CPP variable that should be used as a header guard in the
  841. named file.
  842. """
  843. # Restores original filename in case that cpplint is invoked from Emacs's
  844. # flymake.
  845. filename = re.sub(r'_flymake\.h$', '.h', filename)
  846. fileinfo = FileInfo(filename)
  847. return re.sub(r'[-./\s]', '_', fileinfo.RepositoryName()).upper() + '_'
  848. def CheckForHeaderGuard(filename, lines, error):
  849. """Checks that the file contains a header guard.
  850. Logs an error if no #ifndef header guard is present. For other
  851. headers, checks that the full pathname is used.
  852. Args:
  853. filename: The name of the C++ header file.
  854. lines: An array of strings, each representing a line of the file.
  855. error: The function to call with any errors found.
  856. """
  857. cppvar = GetHeaderGuardCPPVariable(filename)
  858. ifndef = None
  859. ifndef_linenum = 0
  860. define = None
  861. endif = None
  862. endif_linenum = 0
  863. for linenum, line in enumerate(lines):
  864. linesplit = line.split()
  865. if len(linesplit) >= 2:
  866. # find the first occurrence of #ifndef and #define, save arg
  867. if not ifndef and linesplit[0] == '#ifndef':
  868. # set ifndef to the header guard presented on the #ifndef line.
  869. ifndef = linesplit[1]
  870. ifndef_linenum = linenum
  871. if not define and linesplit[0] == '#define':
  872. define = linesplit[1]
  873. # find the last occurrence of #endif, save entire line
  874. if line.startswith('#endif'):
  875. endif = line
  876. endif_linenum = linenum
  877. if not ifndef:
  878. error(filename, 0, 'build/header_guard', 5,
  879. 'No #ifndef header guard found, suggested CPP variable is: %s' %
  880. cppvar)
  881. return
  882. if not define:
  883. error(filename, 0, 'build/header_guard', 5,
  884. 'No #define header guard found, suggested CPP variable is: %s' %
  885. cppvar)
  886. return
  887. # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
  888. # for backward compatibility.
  889. if ifndef != cppvar:
  890. error_level = 0
  891. if ifndef != cppvar + '_':
  892. error_level = 5
  893. ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum,
  894. error)
  895. error(filename, ifndef_linenum, 'build/header_guard', error_level,
  896. '#ifndef header guard has wrong style, please use: %s' % cppvar)
  897. if define != ifndef:
  898. error(filename, 0, 'build/header_guard', 5,
  899. '#ifndef and #define don\'t match, suggested CPP variable is: %s' %
  900. cppvar)
  901. return
  902. if endif != ('#endif // %s' % cppvar):
  903. error_level = 0
  904. if endif != ('#endif // %s' % (cppvar + '_')):
  905. error_level = 5
  906. ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum,
  907. error)
  908. error(filename, endif_linenum, 'build/header_guard', error_level,
  909. '#endif line should be "#endif // %s"' % cppvar)
  910. def CheckForUnicodeReplacementCharacters(filename, lines, error):
  911. """Logs an error for each line containing Unicode replacement characters.
  912. These indicate that either the file contained invalid UTF-8 (likely)
  913. or Unicode replacement characters (which it shouldn't). Note that
  914. it's possible for this to throw off line numbering if the invalid
  915. UTF-8 occurred adjacent to a newline.
  916. Args:
  917. filename: The name of the current file.
  918. lines: An array of strings, each representing a line of the file.
  919. error: The function to call with any errors found.
  920. """
  921. for linenum, line in enumerate(lines):
  922. if u'\ufffd' in line:
  923. error(filename, linenum, 'readability/utf8', 5,
  924. 'Line contains invalid UTF-8 (or Unicode replacement character).')
  925. def CheckForNewlineAtEOF(filename, lines, error):
  926. """Logs an error if there is no newline char at the end of the file.
  927. Args:
  928. filename: The name of the current file.
  929. lines: An array of strings, each representing a line of the file.
  930. error: The function to call with any errors found.
  931. """
  932. # The array lines() was created by adding two newlines to the
  933. # original file (go figure), then splitting on \n.
  934. # To verify that the file ends in \n, we just have to make sure the
  935. # last-but-two element of lines() exists and is empty.
  936. if len(lines) < 3 or lines[-2]:
  937. error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
  938. 'Could not find a newline character at the end of the file.')
  939. def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
  940. """Logs an error if we see /* ... */ or "..." that extend past one line.
  941. /* ... */ comments are legit inside macros, for one line.
  942. Otherwise, we prefer // comments, so it's ok to warn about the
  943. other. Likewise, it's ok for strings to extend across multiple
  944. lines, as long as a line continuation character (backslash)
  945. terminates each line. Although not currently prohibited by the C++
  946. style guide, it's ugly and unnecessary. We don't do well with either
  947. in this lint program, so we warn about both.
  948. Args:
  949. filename: The name of the current file.
  950. clean_lines: A CleansedLines instance containing the file.
  951. linenum: The number of the line to check.
  952. error: The function to call with any errors found.
  953. """
  954. line = clean_lines.elided[linenum]
  955. # Remove all \\ (escaped backslashes) from the line. They are OK, and the
  956. # second (escaped) slash may trigger later \" detection erroneously.
  957. line = line.replace('\\\\', '')
  958. if line.count('/*') > line.count('*/'):
  959. error(filename, linenum, 'readability/multiline_comment', 5,
  960. 'Complex multi-line /*...*/-style comment found. '
  961. 'Lint may give bogus warnings. '
  962. 'Consider replacing these with //-style comments, '
  963. 'with #if 0...#endif, '
  964. 'or with more clearly structured multi-line comments.')
  965. if (line.count('"') - line.count('\\"')) % 2:
  966. error(filename, linenum, 'readability/multiline_string', 5,
  967. 'Multi-line string ("...") found. This lint script doesn\'t '
  968. 'do well with such strings, and may give bogus warnings. They\'re '
  969. 'ugly and unnecessary, and you should use concatenation instead".')
  970. threading_list = (
  971. ('asctime(', 'asctime_r('),
  972. ('ctime(', 'ctime_r('),
  973. ('getgrgid(', 'getgrgid_r('),
  974. ('getgrnam(', 'getgrnam_r('),
  975. ('getlogin(', 'getlogin_r('),
  976. ('getpwnam(', 'getpwnam_r('),
  977. ('getpwuid(', 'getpwuid_r('),
  978. ('gmtime(', 'gmtime_r('),
  979. ('localtime(', 'localtime_r('),
  980. ('rand(', 'rand_r('),
  981. ('readdir(', 'readdir_r('),
  982. ('strtok(', 'strtok_r('),
  983. ('ttyname(', 'ttyname_r('),
  984. )
  985. def CheckPosixThreading(filename, clean_lines, linenum, error):
  986. """Checks for calls to thread-unsafe functions.
  987. Much code has been originally written without consideration of
  988. multi-threading. Also, engineers are relying on their old experience;
  989. they have learned posix before threading extensions were added. These
  990. tests guide the engineers to use thread-safe functions (when using
  991. posix directly).
  992. Args:
  993. filename: The name of the current file.
  994. clean_lines: A CleansedLines instance containing the file.
  995. linenum: The number of the line to check.
  996. error: The function to call with any errors found.
  997. """
  998. line = clean_lines.elided[linenum]
  999. for single_thread_function, multithread_safe_function in threading_list:
  1000. ix = line.find(single_thread_function)
  1001. # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
  1002. if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
  1003. line[ix - 1] not in ('_', '.', '>'))):
  1004. error(filename, linenum, 'runtime/threadsafe_fn', 2,
  1005. 'Consider using ' + multithread_safe_function +
  1006. '...) instead of ' + single_thread_function +
  1007. '...) for improved thread safety.')
  1008. # Matches invalid increment: *count++, which moves pointer instead of
  1009. # incrementing a value.
  1010. _RE_PATTERN_INVALID_INCREMENT = re.compile(
  1011. r'^\s*\*\w+(\+\+|--);')
  1012. def CheckInvalidIncrement(filename, clean_lines, linenum, error):
  1013. """Checks for invalid increment *count++.
  1014. For example following function:
  1015. void increment_counter(int* count) {
  1016. *count++;
  1017. }
  1018. is invalid, because it effectively does count++, moving pointer, and should
  1019. be replaced with ++*count, (*count)++ or *count += 1.
  1020. Args:
  1021. filename: The name of the current file.
  1022. clean_lines: A CleansedLines instance containing the file.
  1023. linenum: The number of the line to check.
  1024. error: The function to call with any errors found.
  1025. """
  1026. line = clean_lines.elided[linenum]
  1027. if _RE_PATTERN_INVALID_INCREMENT.match(line):
  1028. error(filename, linenum, 'runtime/invalid_increment', 5,
  1029. 'Changing pointer instead of value (or unused value of operator*).')
  1030. class _ClassInfo(object):
  1031. """Stores information about a class."""
  1032. def __init__(self, name, clean_lines, linenum):
  1033. self.name = name
  1034. self.linenum = linenum
  1035. self.seen_open_brace = False
  1036. self.is_derived = False
  1037. self.virtual_method_linenumber = None
  1038. self.has_virtual_destructor = False
  1039. self.brace_depth = 0
  1040. # Try to find the end of the class. This will be confused by things like:
  1041. # class A {
  1042. # } *x = { ...
  1043. #
  1044. # But it's still good enough for CheckSectionSpacing.
  1045. self.last_line = 0
  1046. depth = 0
  1047. for i in range(linenum, clean_lines.NumLines()):
  1048. line = clean_lines.lines[i]
  1049. depth += line.count('{') - line.count('}')
  1050. if not depth:
  1051. self.last_line = i
  1052. break
  1053. class _ClassState(object):
  1054. """Holds the current state of the parse relating to class declarations.
  1055. It maintains a stack of _ClassInfos representing the parser's guess
  1056. as to the current nesting of class declarations. The innermost class
  1057. is at the top (back) of the stack. Typically, the stack will either
  1058. be empty or have exactly one entry.
  1059. """
  1060. def __init__(self):
  1061. self.classinfo_stack = []
  1062. def CheckFinished(self, filename, error):
  1063. """Checks that all classes have been completely parsed.
  1064. Call this when all lines in a file have been processed.
  1065. Args:
  1066. filename: The name of the current file.
  1067. error: The function to call with any errors found.
  1068. """
  1069. if self.classinfo_stack:
  1070. # Note: This test can result in false positives if #ifdef constructs
  1071. # get in the way of brace matching. See the testBuildClass test in
  1072. # cpplint_unittest.py for an example of this.
  1073. error(filename, self.classinfo_stack[0].linenum, 'build/class', 5,
  1074. 'Failed to find complete declaration of class %s' %
  1075. self.classinfo_stack[0].name)
  1076. def CheckForNonStandardConstructs(filename, clean_lines, linenum,
  1077. class_state, error):
  1078. """Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
  1079. Complain about several constructs which gcc-2 accepts, but which are
  1080. not standard C++. Warning about these in lint is one way to ease the
  1081. transition to new compilers.
  1082. - put storage class first (e.g. "static const" instead of "const static").
  1083. - "%lld" instead of %qd" in printf-type functions.
  1084. - "%1$d" is non-standard in printf-type functions.
  1085. - "\%" is an undefined character escape sequence.
  1086. - text after #endif is not allowed.
  1087. - invalid inner-style forward declaration.
  1088. - >? and <? operators, and their >?= and <?= cousins.
  1089. - classes with virtual methods need virtual destructors (compiler warning
  1090. available, but not turned on yet.)
  1091. Additionally, check for constructor/destructor style violations and reference
  1092. members, as it is very convenient to do so while checking for
  1093. gcc-2 compliance.
  1094. Args:
  1095. filename: The name of the current file.
  1096. clean_lines: A CleansedLines instance containing the file.
  1097. linenum: The number of the line to check.
  1098. class_state: A _ClassState instance which maintains information about
  1099. the current stack of nested class declarations being parsed.
  1100. error: A callable to which errors are reported, which takes 4 arguments:
  1101. filename, line number, error level, and message
  1102. """
  1103. # Remove comments from the line, but leave in strings for now.
  1104. line = clean_lines.lines[linenum]
  1105. if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
  1106. error(filename, linenum, 'runtime/printf_format', 3,
  1107. '%q in format strings is deprecated. Use %ll instead.')
  1108. if Search(r'printf\s*\(.*".*%\d+\$', line):
  1109. error(filename, linenum, 'runtime/printf_format', 2,
  1110. '%N$ formats are unconventional. Try rewriting to avoid them.')
  1111. # Remove escaped backslashes before looking for undefined escapes.
  1112. line = line.replace('\\\\', '')
  1113. if Search(r'("|\').*\\(%|\[|\(|{)', line):
  1114. error(filename, linenum, 'build/printf_format', 3,
  1115. '%, [, (, and { are undefined character escapes. Unescape them.')
  1116. # For the rest, work with both comments and strings removed.
  1117. line = clean_lines.elided[linenum]
  1118. if Search(r'\b(const|volatile|void|char|short|int|long'
  1119. r'|float|double|signed|unsigned'
  1120. r'|schar|u?int8|u?int16|u?int32|u?int64)'
  1121. r'\s+(auto|register|static|extern|typedef)\b',
  1122. line):
  1123. error(filename, linenum, 'build/storage_class', 5,
  1124. 'Storage class (static, extern, typedef, etc) should be first.')
  1125. if Match(r'\s*#\s*endif\s*[^/\s]+', line):
  1126. error(filename, linenum, 'build/endif_comment', 5,
  1127. 'Uncommented text after #endif is non-standard. Use a comment.')
  1128. if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
  1129. error(filename, linenum, 'build/forward_decl', 5,
  1130. 'Inner-style forward declarations are invalid. Remove this line.')
  1131. if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
  1132. line):
  1133. error(filename, linenum, 'build/deprecated', 3,
  1134. '>? and <? (max and min) operators are non-standard and deprecated.')
  1135. if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
  1136. # TODO(unknown): Could it be expanded safely to arbitrary references,
  1137. # without triggering too many false positives? The first
  1138. # attempt triggered 5 warnings for mostly benign code in the regtest, hence
  1139. # the restriction.
  1140. # Here's the original regexp, for the reference:
  1141. # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
  1142. # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
  1143. error(filename, linenum, 'runtime/member_string_references', 2,
  1144. 'const string& members are dangerous. It is much better to use '
  1145. 'alternatives, such as pointers or simple constants.')
  1146. # Track class entry and exit, and attempt to find cases within the
  1147. # class declaration that don't meet the C++ style
  1148. # guidelines. Tracking is very dependent on the code matching Google
  1149. # style guidelines, but it seems to perform well enough in testing
  1150. # to be a worthwhile addition to the checks.
  1151. classinfo_stack = class_state.classinfo_stack
  1152. # Look for a class declaration. The regexp accounts for decorated classes
  1153. # such as in:
  1154. # class LOCKABLE API Object {
  1155. # };
  1156. class_decl_match = Match(
  1157. r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
  1158. '(class|struct)\s+([A-Z_]+\s+)*(\w+(::\w+)*)', line)
  1159. if class_decl_match:
  1160. classinfo_stack.append(_ClassInfo(
  1161. class_decl_match.group(4), clean_lines, linenum))
  1162. # Everything else in this function uses the top of the stack if it's
  1163. # not empty.
  1164. if not classinfo_stack:
  1165. return
  1166. classinfo = classinfo_stack[-1]
  1167. # If the opening brace hasn't been seen look for it and also
  1168. # parent class declarations.
  1169. if not classinfo.seen_open_brace:
  1170. # If the line has a ';' in it, assume it's a forward declaration or
  1171. # a single-line class declaration, which we won't process.
  1172. if line.find(';') != -1:
  1173. classinfo_stack.pop()
  1174. return
  1175. classinfo.seen_open_brace = (line.find('{') != -1)
  1176. # Look for a bare ':'
  1177. if Search('(^|[^:]):($|[^:])', line):
  1178. classinfo.is_derived = True
  1179. if not classinfo.seen_open_brace:
  1180. return # Everything else in this function is for after open brace
  1181. # The class may have been declared with namespace or classname qualifiers.
  1182. # The constructor and destructor will not have those qualifiers.
  1183. base_classname = classinfo.name.split('::')[-1]
  1184. # Look for single-argument constructors that aren't marked explicit.
  1185. # Technically a valid construct, but against style.
  1186. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
  1187. % re.escape(base_classname),
  1188. line)
  1189. if (args and
  1190. args.group(1) != 'void' and
  1191. not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname),
  1192. args.group(1).strip())):
  1193. error(filename, linenum, 'runtime/explicit', 5,
  1194. 'Single-argument constructors should be marked explicit.')
  1195. # Look for methods declared virtual.
  1196. if Search(r'\bvirtual\b', line):
  1197. classinfo.virtual_method_linenumber = linenum
  1198. # Only look for a destructor declaration on the same line. It would
  1199. # be extremely unlikely for the destructor declaration to occupy
  1200. # more than one line.
  1201. if Search(r'~%s\s*\(' % base_classname, line):
  1202. classinfo.has_virtual_destructor = True
  1203. # Look for class end.
  1204. brace_depth = classinfo.brace_depth
  1205. brace_depth = brace_depth + line.count('{') - line.count('}')
  1206. if brace_depth <= 0:
  1207. classinfo = classinfo_stack.pop()
  1208. # Try to detect missing virtual destructor declarations.
  1209. # For now, only warn if a non-derived class with virtual methods lacks
  1210. # a virtual destructor. This is to make it less likely that people will
  1211. # declare derived virtual destructors without declaring the base
  1212. # destructor virtual.
  1213. if ((classinfo.virtual_method_linenumber is not None) and
  1214. (not classinfo.has_virtual_destructor) and
  1215. (not classinfo.is_derived)): # Only warn for base classes
  1216. error(filename, classinfo.linenum, 'runtime/virtual', 4,
  1217. 'The class %s probably needs a virtual destructor due to '
  1218. 'having virtual method(s), one declared at line %d.'
  1219. % (classinfo.name, classinfo.virtual_method_linenumber))
  1220. else:
  1221. classinfo.brace_depth = brace_depth
  1222. def CheckSpacingForFunctionCall(filename, line, linenum, error):
  1223. """Checks for the correctness of various spacing around function calls.
  1224. Args:
  1225. filename: The name of the current file.
  1226. line: The text of the line to check.
  1227. linenum: The number of the line to check.
  1228. error: The function to call with any errors found.
  1229. """
  1230. # Since function calls often occur inside if/for/while/switch
  1231. # expressions - which have their own, more liberal conventions - we
  1232. # first see if we should be looking inside such an expression for a
  1233. # function call, to which we can apply more strict standards.
  1234. fncall = line # if there's no control flow construct, look at whole line
  1235. for pattern in (r'\bif\s*\((.*)\)\s*{',
  1236. r'\bfor\s*\((.*)\)\s*{',
  1237. r'\bwhile\s*\((.*)\)\s*[{;]',
  1238. r'\bswitch\s*\((.*)\)\s*{'):
  1239. match = Search(pattern, line)
  1240. if match:
  1241. fncall = match.group(1) # look inside the parens for function calls
  1242. break
  1243. # Except in if/for/while/switch, there should never be space
  1244. # immediately inside parens (eg "f( 3, 4 )"). We make an exception
  1245. # for nested parens ( (a+b) + c ). Likewise, there should never be
  1246. # a space before a ( when it's a function argument. I assume it's a
  1247. # function argument when the char before the whitespace is legal in
  1248. # a function name (alnum + _) and we're not starting a macro. Also ignore
  1249. # pointers and references to arrays and functions coz they're too tricky:
  1250. # we use a very simple way to recognize these:
  1251. # " (something)(maybe-something)" or
  1252. # " (something)(maybe-something," or
  1253. # " (something)[something]"
  1254. # Note that we assume the contents of [] to be short enough that
  1255. # they'll never need to wrap.
  1256. if ( # Ignore control structures.
  1257. not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and
  1258. # Ignore pointers/references to functions.
  1259. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
  1260. # Ignore pointers/references to arrays.
  1261. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
  1262. if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
  1263. error(filename, linenum, 'whitespace/parens', 4,
  1264. 'Extra space after ( in function call')
  1265. elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
  1266. error(filename, linenum, 'whitespace/parens', 2,
  1267. 'Extra space after (')
  1268. if (Search(r'\w\s+\(', fncall) and
  1269. not Search(r'#\s*define|typedef', fncall)):
  1270. error(filename, linenum, 'whitespace/parens', 4,
  1271. 'Extra space before ( in function call')
  1272. # If the ) is followed only by a newline or a { + newline, assume it's
  1273. # part of a control statement (if/while/etc), and don't complain
  1274. if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
  1275. # If the closing parenthesis is preceded by only whitespaces,
  1276. # try to give a more descriptive error message.
  1277. if Search(r'^\s+\)', fncall):
  1278. error(filename, linenum, 'whitespace/parens', 2,
  1279. 'Closing ) should be moved to the previous line')
  1280. else:
  1281. error(filename, linenum, 'whitespace/parens', 2,
  1282. 'Extra space before )')
  1283. def IsBlankLine(line):
  1284. """Returns true if the given line is blank.
  1285. We consider a line to be blank if the line is empty or consists of
  1286. only white spaces.
  1287. Args:
  1288. line: A line of a string.
  1289. Returns:
  1290. True, if the given line is blank.
  1291. """
  1292. return not line or line.isspace()
  1293. def CheckForFunctionLengths(filename, clean_lines, linenum,
  1294. function_state, error):
  1295. """Reports for long function bodies.
  1296. For an overview why this is done, see:
  1297. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
  1298. Uses a simplistic algorithm assuming other style guidelines
  1299. (especially spacing) are followed.
  1300. Only checks unindented functions, so class members are unchecked.
  1301. Trivial bodies are unchecked, so constructors with huge initializer lists
  1302. may be missed.
  1303. Blank/comment lines are not counted so as to avoid encouraging the removal
  1304. of vertical space and comments just to get through a lint check.
  1305. NOLINT *on the last line of a function* disables this check.
  1306. Args:
  1307. filename: The name of the current file.
  1308. clean_lines: A CleansedLines instance containing the file.
  1309. linenum: The number of the line to check.
  1310. function_state: Current function name and lines in body so far.
  1311. error: The function to call with any errors found.
  1312. """
  1313. lines = clean_lines.lines
  1314. line = lines[linenum]
  1315. raw = clean_lines.raw_lines
  1316. raw_line = raw[linenum]
  1317. joined_line = ''
  1318. starting_func = False
  1319. regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
  1320. match_result = Match(regexp, line)
  1321. if match_result:
  1322. # If the name is all caps and underscores, figure it's a macro and
  1323. # ignore it, unless it's TEST or TEST_F.
  1324. function_name = match_result.group(1).split()[-1]
  1325. if function_name == 'TEST' or function_name == 'TEST_F' or (
  1326. not Match(r'[A-Z_]+$', function_name)):
  1327. starting_func = True
  1328. if starting_func:
  1329. body_found = False
  1330. for start_linenum in xrange(linenum, clean_lines.NumLines()):
  1331. start_line = lines[start_linenum]
  1332. joined_line += ' ' + start_line.lstrip()
  1333. if Search(r'(;|})', start_line): # Declarations and trivial functions
  1334. body_found = True
  1335. break # ... ignore
  1336. elif Search(r'{', start_line):
  1337. body_found = True
  1338. function = Search(r'((\w|:)*)\(', line).group(1)
  1339. if Match(r'TEST', function): # Handle TEST... macros
  1340. parameter_regexp = Search(r'(\(.*\))', joined_line)
  1341. if parameter_regexp: # Ignore bad syntax
  1342. function += parameter_regexp.group(1)
  1343. else:
  1344. function += '()'
  1345. function_state.Begin(function)
  1346. break
  1347. if not body_found:
  1348. # No body for the function (or evidence of a non-function) was found.
  1349. error(filename, linenum, 'readability/fn_size', 5,
  1350. 'Lint failed to find start of function body.')
  1351. elif Match(r'^\}\s*$', line): # function end
  1352. function_state.Check(error, filename, linenum)
  1353. function_state.End()
  1354. elif not Match(r'^\s*$', line):
  1355. function_state.Count() # Count non-blank/non-comment lines.
  1356. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
  1357. def CheckComment(comment, filename, linenum, error):
  1358. """Checks for common mistakes in TODO comments.
  1359. Args:
  1360. comment: The text of the comment from the line in question.
  1361. filename: The name of the current file.
  1362. linenum: The number of the line to check.
  1363. error: The function to call with any errors found.
  1364. """
  1365. match = _RE_PATTERN_TODO.match(comment)
  1366. if match:
  1367. # One whitespace is correct; zero whitespace is handled elsewhere.
  1368. leading_whitespace = match.group(1)
  1369. if len(leading_whitespace) > 1:
  1370. error(filename, linenum, 'whitespace/todo', 2,
  1371. 'Too many spaces before TODO')
  1372. username = match.group(2)
  1373. if not username:
  1374. error(filename, linenum, 'readability/todo', 2,
  1375. 'Missing username in TODO; it should look like '
  1376. '"// TODO(my_username): Stuff."')
  1377. middle_whitespace = match.group(3)
  1378. # Comparisons made explicit for correctness -- pylint: disable-msg=C6403
  1379. if middle_whitespace != ' ' and middle_whitespace != '':
  1380. error(filename, linenum, 'whitespace/todo', 2,
  1381. 'TODO(my_username) should be followed by a space')
  1382. def CheckSpacing(filename, clean_lines, linenum, error):
  1383. """Checks for the correctness of various spacing issues in the code.
  1384. Things we check for: spaces around operators, spaces after
  1385. if/for/while/switch, no spaces around parens in function calls, two
  1386. spaces between code and comment, don't start a block with a blank
  1387. line, don't end a function with a blank line, don't add a blank line
  1388. after public/protected/private, don't have too many blank lines in a row.
  1389. Args:
  1390. filename: The name of the current file.
  1391. clean_lines: A CleansedLines instance containing the file.
  1392. linenum: The number of the line to check.
  1393. error: The function to call with any errors found.
  1394. """
  1395. raw = clean_lines.raw_lines
  1396. line = raw[linenum]
  1397. # Before nixing comments, check if the line is blank for no good
  1398. # reason. This includes the first line after a block is opened, and
  1399. # blank lines at the end of a function (ie, right before a line like '}'
  1400. if IsBlankLine(line):
  1401. elided = clean_lines.elided
  1402. prev_line = elided[linenum - 1]
  1403. prevbrace = prev_line.rfind('{')
  1404. # TODO(unknown): Don't complain if line before blank line, and line after,
  1405. # both start with alnums and are indented the same amount.
  1406. # This ignores whitespace at the start of a namespace block
  1407. # because those are not usually indented.
  1408. if (prevbrace != -1 and prev_line[prevbrace:].find('}') == -1
  1409. and prev_line[:prevbrace].find('namespace') == -1):
  1410. # OK, we have a blank line at the start of a code block. Before we
  1411. # complain, we check if it is an exception to the rule: The previous
  1412. # non-empty line has the parameters of a function header that are indented
  1413. # 4 spaces (because they did not fit in a 80 column line when placed on
  1414. # the same line as the function name). We also check for the case where
  1415. # the previous line is indented 6 spaces, which may happen when the
  1416. # initializers of a constructor do not fit into a 80 column line.
  1417. exception = False
  1418. if Match(r' {6}\w', prev_line): # Initializer list?
  1419. # We are looking for the opening column of initializer list, which
  1420. # should be indented 4 spaces to cause 6 space indentation afterwards.
  1421. search_position = linenum-2
  1422. while (search_position >= 0
  1423. and Match(r' {6}\w', elided[search_position])):
  1424. search_position -= 1
  1425. exception = (search_position >= 0
  1426. and elided[search_position][:5] == ' :')
  1427. else:
  1428. # Search for the function arguments or an initializer list. We use a
  1429. # simple heuristic here: If the line is indented 4 spaces; and we have a
  1430. # closing paren, without the opening paren, followed by an opening brace
  1431. # or colon (for initializer lists) we assume that it is the last line of
  1432. # a function header. If we have a colon indented 4 spaces, it is an
  1433. # initializer list.
  1434. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
  1435. prev_line)
  1436. or Match(r' {4}:', prev_line))
  1437. if not exception:
  1438. error(filename, linenum, 'whitespace/blank_line', 2,
  1439. 'Blank line at the start of a code block. Is this needed?')
  1440. # This doesn't ignore whitespace at the end of a namespace block
  1441. # because that is too hard without pairing open/close braces;
  1442. # however, a special exception is made for namespace closing
  1443. # brackets which have a comment containing "namespace".
  1444. #
  1445. # Also, ignore blank lines at the end of a block in a long if-else
  1446. # chain, like this:
  1447. # if (condition1) {
  1448. # // Something followed by a blank line
  1449. #
  1450. # } else if (condition2) {
  1451. # // Something else
  1452. # }
  1453. if linenum + 1 < clean_lines.NumLines():
  1454. next_line = raw[linenum + 1]
  1455. if (next_line
  1456. and Match(r'\s*}', next_line)
  1457. and next_line.find('namespace') == -1
  1458. and next_line.find('} else ') == -1):
  1459. error(filename, linenum, 'whitespace/blank_line', 3,
  1460. 'Blank line at the end of a code block. Is this needed?')
  1461. matched = Match(r'\s*(public|protected|private):', prev_line)
  1462. if matched:
  1463. error(filename, linenum, 'whitespace/blank_line', 3,
  1464. 'Do not leave a blank line after "%s:"' % matched.group(1))
  1465. # Next, we complain if there's a comment too near the text
  1466. commentpos = line.find('//')
  1467. if commentpos != -1:
  1468. # Check if the // may be in quotes. If so, ignore it
  1469. # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
  1470. if (line.count('"', 0, commentpos) -
  1471. line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
  1472. # Allow one space for new scopes, two spaces otherwise:
  1473. if (not Match(r'^\s*{ //', line) and
  1474. ((commentpos >= 1 and
  1475. line[commentpos-1] not in string.whitespace) or
  1476. (commentpos >= 2 and
  1477. line[commentpos-2] not in string.whitespace))):
  1478. error(filename, linenum, 'whitespace/comments', 2,
  1479. 'At least two spaces is best between code and comments')
  1480. # There should always be a space between the // and the comment
  1481. commentend = commentpos + 2
  1482. if commentend < len(line) and not line[commentend] == ' ':
  1483. # but some lines are exceptions -- e.g. if they're big
  1484. # comment delimiters like:
  1485. # //----------------------------------------------------------
  1486. # or are an empty C++ style Doxygen comment, like:
  1487. # ///
  1488. # or they begin with multiple slashes followed by a space:
  1489. # //////// Header comment
  1490. match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
  1491. Search(r'^/$', line[commentend:]) or
  1492. Search(r'^/+ ', line[commentend:]))
  1493. if not match:
  1494. error(filename, linenum, 'whitespace/comments', 4,
  1495. 'Should have a space between // and comment')
  1496. CheckComment(line[commentpos:], filename, linenum, error)
  1497. line = clean_lines.elided[linenum] # get rid of comments and strings
  1498. # Don't try to do spacing checks for operator methods
  1499. line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
  1500. # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
  1501. # Otherwise not. Note we only check for non-spaces on *both* sides;
  1502. # sometimes people put non-spaces on one side when aligning ='s among
  1503. # many lines (not that this is behavior that I approve of...)
  1504. if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
  1505. error(filename, linenum, 'whitespace/operators', 4,
  1506. 'Missing spaces around =')
  1507. # It's ok not to have spaces around binary operators like + - * /, but if
  1508. # there's too little whitespace, we get concerned. It's hard to tell,
  1509. # though, so we punt on this one for now. TODO.
  1510. # You should always have whitespace around binary operators.
  1511. # Alas, we can't test < or > because they're legitimately used sans spaces
  1512. # (a->b, vector<int> a). The only time we can tell is a < with no >, and
  1513. # only if it's not template params list spilling into the next line.
  1514. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
  1515. if not match:
  1516. # Note that while it seems that the '<[^<]*' term in the following
  1517. # regexp could be simplified to '<.*', which would indeed match
  1518. # the same class of strings, the [^<] means that searching for the
  1519. # regexp takes linear rather than quadratic time.
  1520. if not Search(r'<[^<]*,\s*$', line): # template params spill
  1521. match = Search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line)
  1522. if match:
  1523. error(filename, linenum, 'whitespace/operators', 3,
  1524. 'Missing spaces around %s' % match.group(1))
  1525. # We allow no-spaces around << and >> when used like this: 10<<20, but
  1526. # not otherwise (particularly, not when used as streams)
  1527. match = Search(r'[^0-9\s](<<|>>)[^0-9\s]', line)
  1528. if match:
  1529. error(filename, linenum, 'whitespace/operators', 3,
  1530. 'Missing spaces around %s' % match.group(1))
  1531. # There shouldn't be space around unary operators
  1532. match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
  1533. if match:
  1534. error(filename, linenum, 'whitespace/operators', 4,
  1535. 'Extra space for operator %s' % match.group(1))
  1536. # A pet peeve of mine: no spaces after an if, while, switch, or for
  1537. match = Search(r' (if\(|for\(|while\(|switch\()', line)
  1538. if match:
  1539. error(filename, linenum, 'whitespace/parens', 5,
  1540. 'Missing space before ( in %s' % match.group(1))
  1541. # For if/for/while/switch, the left and right parens should be
  1542. # consistent about how many spaces are inside the parens, and
  1543. # there should either be zero or one spaces inside the parens.
  1544. # We don't want: "if ( foo)" or "if ( foo )".
  1545. # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  1546. match = Search(r'\b(if|for|while|switch)\s*'
  1547. r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
  1548. line)
  1549. if match:
  1550. if len(match.group(2)) != len(match.group(4)):
  1551. if not (match.group(3) == ';' and
  1552. len(match.group(2)) == 1 + len(match.group(4)) or
  1553. not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
  1554. error(filename, linenum, 'whitespace/parens', 5,
  1555. 'Mismatching spaces inside () in %s' % match.group(1))
  1556. if not len(match.group(2)) in [0, 1]:
  1557. error(filename, linenum, 'whitespace/parens', 5,
  1558. 'Should have zero or one spaces inside ( and ) in %s' %
  1559. match.group(1))
  1560. # You should always have a space after a comma (either as fn arg or operator)
  1561. if Search(r',[^\s]', line):
  1562. error(filename, linenum, 'whitespace/comma', 3,
  1563. 'Missing space after ,')
  1564. # You should always have a space after a semicolon
  1565. # except for few corner cases
  1566. # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
  1567. # space after ;
  1568. if Search(r';[^\s};\\)/]', line):
  1569. error(filename, linenum, 'whitespace/semicolon', 3,
  1570. 'Missing space after ;')
  1571. # Next we will look for issues with function calls.
  1572. CheckSpacingForFunctionCall(filename, line, linenum, error)
  1573. # Except after an opening paren, or after another opening brace (in case of
  1574. # an initializer list, for instance), you should have spaces before your
  1575. # braces. And since you should never have braces at the beginning of a line,
  1576. # this is an easy test.
  1577. if Search(r'[^ ({]{', line):
  1578. error(filename, linenum, 'whitespace/braces', 5,
  1579. 'Missing space before {')
  1580. # Make sure '} else {' has spaces.
  1581. if Search(r'}else', line):
  1582. error(filename, linenum, 'whitespace/braces', 5,
  1583. 'Missing space before else')
  1584. # You shouldn't have spaces before your brackets, except maybe after
  1585. # 'delete []' or 'new char * []'.
  1586. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
  1587. error(filename, linenum, 'whitespace/braces', 5,
  1588. 'Extra space before [')
  1589. # You shouldn't have a space before a semicolon at the end of the line.
  1590. # There's a special case for "for" since the style guide allows space before
  1591. # the semicolon there.
  1592. if Search(r':\s*;\s*$', line):
  1593. error(filename, linenum, 'whitespace/semicolon', 5,
  1594. 'Semicolon defining empty statement. Use { } instead.')
  1595. elif Search(r'^\s*;\s*$', line):
  1596. error(filename, linenum, 'whitespace/semicolon', 5,
  1597. 'Line contains only semicolon. If this should be an empty statement, '
  1598. 'use { } instead.')
  1599. elif (Search(r'\s+;\s*$', line) and
  1600. not Search(r'\bfor\b', line)):
  1601. error(filename, linenum, 'whitespace/semicolon', 5,
  1602. 'Extra space before last semicolon. If this should be an empty '
  1603. 'statement, use { } instead.')
  1604. def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
  1605. """Checks for additional blank line issues related to sections.
  1606. Currently the only thing checked here is blank line before protected/private.
  1607. Args:
  1608. filename: The name of the current file.
  1609. clean_lines: A CleansedLines instance containing the file.
  1610. class_info: A _ClassInfo objects.
  1611. linenum: The number of the line to check.
  1612. error: The function to call with any errors found.
  1613. """
  1614. # Skip checks if the class is small, where small means 25 lines or less.
  1615. # 25 lines seems like a good cutoff since that's the usual height of
  1616. # terminals, and any class that can't fit in one screen can't really
  1617. # be considered "small".
  1618. #
  1619. # Also skip checks if we are on the first line. This accounts for
  1620. # classes that look like
  1621. # class Foo { public: ... };
  1622. #
  1623. # If we didn't find the end of the class, last_line would be zero,
  1624. # and the check will be skipped by the first condition.
  1625. if (class_info.last_line - class_info.linenum <= 24 or
  1626. linenum <= class_info.linenum):
  1627. return
  1628. matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
  1629. if matched:
  1630. # Issue warning if the line before public/protected/private was
  1631. # not a blank line, but don't do this if the previous line contains
  1632. # "class" or "struct". This can happen two ways:
  1633. # - We are at the beginning of the class.
  1634. # - We are forward-declaring an inner class that is semantically
  1635. # private, but needed to be public for implementation reasons.
  1636. prev_line = clean_lines.lines[linenum - 1]
  1637. if (not IsBlankLine(prev_line) and
  1638. not Search(r'\b(class|struct)\b', prev_line)):
  1639. # Try a bit harder to find the beginning of the class. This is to
  1640. # account for multi-line base-specifier lists, e.g.:
  1641. # class Derived
  1642. # : public Base {
  1643. end_class_head = class_info.linenum
  1644. for i in range(class_info.linenum, linenum):
  1645. if Search(r'\{\s*$', clean_lines.lines[i]):
  1646. end_class_head = i
  1647. break
  1648. if end_class_head < linenum - 1:
  1649. error(filename, linenum, 'whitespace/blank_line', 3,
  1650. '"%s:" should be preceded by a blank line' % matched.group(1))
  1651. def GetPreviousNonBlankLine(clean_lines, linenum):
  1652. """Return the most recent non-blank line and its line number.
  1653. Args:
  1654. clean_lines: A CleansedLines instance containing the file contents.
  1655. linenum: The number of the line to check.
  1656. Returns:
  1657. A tuple with two elements. The first element is the contents of the last
  1658. non-blank line before the current line, or the empty string if this is the
  1659. first non-blank line. The second is the line number of that line, or -1
  1660. if this is the first non-blank line.
  1661. """
  1662. prevlinenum = linenum - 1
  1663. while prevlinenum >= 0:
  1664. prevline = clean_lines.elided[prevlinenum]
  1665. if not IsBlankLine(prevline): # if not a blank line...
  1666. return (prevline, prevlinenum)
  1667. prevlinenum -= 1
  1668. return ('', -1)
  1669. def CheckBraces(filename, clean_lines, linenum, error):
  1670. """Looks for misplaced braces (e.g. at the end of line).
  1671. Args:
  1672. filename: The name of the current file.
  1673. clean_lines: A CleansedLines instance containing the file.
  1674. linenum: The number of the line to check.
  1675. error: The function to call with any errors found.
  1676. """
  1677. line = clean_lines.elided[linenum] # get rid of comments and strings
  1678. if Match(r'\s*{\s*$', line):
  1679. # We allow an open brace to start a line in the case where someone
  1680. # is using braces in a block to explicitly create a new scope,
  1681. # which is commonly used to control the lifetime of
  1682. # stack-allocated variables. We don't detect this perfectly: we
  1683. # just don't complain if the last non-whitespace character on the
  1684. # previous non-blank line is ';', ':', '{', or '}'.
  1685. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  1686. if not Search(r'[;:}{]\s*$', prevline):
  1687. error(filename, linenum, 'whitespace/braces', 4,
  1688. '{ should almost always be at the end of the previous line')
  1689. # An else clause should be on the same line as the preceding closing brace.
  1690. if Match(r'\s*else\s*', line):
  1691. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  1692. if Match(r'\s*}\s*$', prevline):
  1693. error(filename, linenum, 'whitespace/newline', 4,
  1694. 'An else should appear on the same line as the preceding }')
  1695. # If braces come on one side of an else, they should be on both.
  1696. # However, we have to worry about "else if" that spans multiple lines!
  1697. if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
  1698. if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
  1699. # find the ( after the if
  1700. pos = line.find('else if')
  1701. pos = line.find('(', pos)
  1702. if pos > 0:
  1703. (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
  1704. if endline[endpos:].find('{') == -1: # must be brace after if
  1705. error(filename, linenum, 'readability/braces', 5,
  1706. 'If an else has a brace on one side, it should have it on both')
  1707. else: # common case: else not followed by a multi-line if
  1708. error(filename, linenum, 'readability/braces', 5,
  1709. 'If an else has a brace on one side, it should have it on both')
  1710. # Likewise, an else should never have the else clause on the same line
  1711. if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
  1712. error(filename, linenum, 'whitespace/newline', 4,
  1713. 'Else clause should never be on same line as else (use 2 lines)')
  1714. # In the same way, a do/while should never be on one line
  1715. if Match(r'\s*do [^\s{]', line):
  1716. error(filename, linenum, 'whitespace/newline', 4,
  1717. 'do/while clauses should not be on a single line')
  1718. # Braces shouldn't be followed by a ; unless they're defining a struct
  1719. # or initializing an array.
  1720. # We can't tell in general, but we can for some common cases.
  1721. prevlinenum = linenum
  1722. while True:
  1723. (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum)
  1724. if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'):
  1725. line = prevline + line
  1726. else:
  1727. break
  1728. if (Search(r'{.*}\s*;', line) and
  1729. line.count('{') == line.count('}') and
  1730. not Search(r'struct|class|enum|\s*=\s*{', line)):
  1731. error(filename, linenum, 'readability/braces', 4,
  1732. "You don't need a ; after a }")
  1733. def ReplaceableCheck(operator, macro, line):
  1734. """Determine whether a basic CHECK can be replaced with a more specific one.
  1735. For example suggest using CHECK_EQ instead of CHECK(a == b) and
  1736. similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE.
  1737. Args:
  1738. operator: The C++ operator used in the CHECK.
  1739. macro: The CHECK or EXPECT macro being called.
  1740. line: The current source line.
  1741. Returns:
  1742. True if the CHECK can be replaced with a more specific one.
  1743. """
  1744. # This matches decimal and hex integers, strings, and chars (in that order).
  1745. match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')'
  1746. # Expression to match two sides of the operator with something that
  1747. # looks like a literal, since CHECK(x == iterator) won't compile.
  1748. # This means we can't catch all the cases where a more specific
  1749. # CHECK is possible, but it's less annoying than dealing with
  1750. # extraneous warnings.
  1751. match_this = (r'\s*' + macro + r'\((\s*' +
  1752. match_constant + r'\s*' + operator + r'[^<>].*|'
  1753. r'.*[^<>]' + operator + r'\s*' + match_constant +
  1754. r'\s*\))')
  1755. # Don't complain about CHECK(x == NULL) or similar because
  1756. # CHECK_EQ(x, NULL) won't compile (requires a cast).
  1757. # Also, don't complain about more complex boolean expressions
  1758. # involving && or || such as CHECK(a == b || c == d).
  1759. return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line)
  1760. def CheckCheck(filename, clean_lines, linenum, error):
  1761. """Checks the use of CHECK and EXPECT macros.
  1762. Args:
  1763. filename: The name of the current file.
  1764. clean_lines: A CleansedLines instance containing the file.
  1765. linenum: The number of the line to check.
  1766. error: The function to call with any errors found.
  1767. """
  1768. # Decide the set of replacement macros that should be suggested
  1769. raw_lines = clean_lines.raw_lines
  1770. current_macro = ''
  1771. for macro in _CHECK_MACROS:
  1772. if raw_lines[linenum].find(macro) >= 0:
  1773. current_macro = macro
  1774. break
  1775. if not current_macro:
  1776. # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
  1777. return
  1778. line = clean_lines.elided[linenum] # get rid of comments and strings
  1779. # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc.
  1780. for operator in ['==', '!=', '>=', '>', '<=', '<']:
  1781. if ReplaceableCheck(operator, current_macro, line):
  1782. error(filename, linenum, 'readability/check', 2,
  1783. 'Consider using %s instead of %s(a %s b)' % (
  1784. _CHECK_REPLACEMENT[current_macro][operator],
  1785. current_macro, operator))
  1786. break
  1787. def GetLineWidth(line):
  1788. """Determines the width of the line in column positions.
  1789. Args:
  1790. line: A string, which may be a Unicode string.
  1791. Returns:
  1792. The width of the line in column positions, accounting for Unicode
  1793. combining characters and wide characters.
  1794. """
  1795. if isinstance(line, unicode):
  1796. width = 0
  1797. for uc in unicodedata.normalize('NFC', line):
  1798. if unicodedata.east_asian_width(uc) in ('W', 'F'):
  1799. width += 2
  1800. elif not unicodedata.combining(uc):
  1801. width += 1
  1802. return width
  1803. else:
  1804. return len(line)
  1805. def CheckStyle(filename, clean_lines, linenum, file_extension, class_state,
  1806. error):
  1807. """Checks rules from the 'C++ style rules' section of cppguide.html.
  1808. Most of these rules are hard to test (naming, comment style), but we
  1809. do what we can. In particular we check for 2-space indents, line lengths,
  1810. tab usage, spaces inside code, etc.
  1811. Args:
  1812. filename: The name of the current file.
  1813. clean_lines: A CleansedLines instance containing the file.
  1814. linenum: The number of the line to check.
  1815. file_extension: The extension (without the dot) of the filename.
  1816. error: The function to call with any errors found.
  1817. """
  1818. raw_lines = clean_lines.raw_lines
  1819. line = raw_lines[linenum]
  1820. if line.find('\t') != -1:
  1821. error(filename, linenum, 'whitespace/tab', 1,
  1822. 'Tab found; better to use spaces')
  1823. # One or three blank spaces at the beginning of the line is weird; it's
  1824. # hard to reconcile that with 2-space indents.
  1825. # NOTE: here are the conditions rob pike used for his tests. Mine aren't
  1826. # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
  1827. # if(RLENGTH > 20) complain = 0;
  1828. # if(match($0, " +(error|private|public|protected):")) complain = 0;
  1829. # if(match(prev, "&& *$")) complain = 0;
  1830. # if(match(prev, "\\|\\| *$")) complain = 0;
  1831. # if(match(prev, "[\",=><] *$")) complain = 0;
  1832. # if(match($0, " <<")) complain = 0;
  1833. # if(match(prev, " +for \\(")) complain = 0;
  1834. # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
  1835. initial_spaces = 0
  1836. cleansed_line = clean_lines.elided[linenum]
  1837. while initial_spaces < len(line) and line[initial_spaces] == ' ':
  1838. initial_spaces += 1
  1839. if line and line[-1].isspace():
  1840. error(filename, linenum, 'whitespace/end_of_line', 4,
  1841. 'Line ends in whitespace. Consider deleting these extra spaces.')
  1842. # There are certain situations we allow one space, notably for labels
  1843. elif ((initial_spaces == 1 or initial_spaces == 3) and
  1844. not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
  1845. error(filename, linenum, 'whitespace/indent', 3,
  1846. 'Weird number of spaces at line-start. '
  1847. 'Are you using a 2-space indent?')
  1848. # Labels should always be indented at least one space.
  1849. elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$',
  1850. line):
  1851. error(filename, linenum, 'whitespace/labels', 4,
  1852. 'Labels should always be indented at least one space. '
  1853. 'If this is a member-initializer list in a constructor or '
  1854. 'the base class list in a class definition, the colon should '
  1855. 'be on the following line.')
  1856. # Check if the line is a header guard.
  1857. is_header_guard = False
  1858. if file_extension == 'h':
  1859. cppvar = GetHeaderGuardCPPVariable(filename)
  1860. if (line.startswith('#ifndef %s' % cppvar) or
  1861. line.startswith('#define %s' % cppvar) or
  1862. line.startswith('#endif // %s' % cppvar)):
  1863. is_header_guard = True
  1864. # #include lines and header guards can be long, since there's no clean way to
  1865. # split them.
  1866. #
  1867. # URLs can be long too. It's possible to split these, but it makes them
  1868. # harder to cut&paste.
  1869. #
  1870. # The "$Id:...$" comment may also get very long without it being the
  1871. # developers fault.
  1872. if (not line.startswith('#include') and not is_header_guard and
  1873. not Match(r'^\s*//.*http(s?)://\S*$', line) and
  1874. not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
  1875. line_width = GetLineWidth(line)
  1876. if line_width > 100:
  1877. error(filename, linenum, 'whitespace/line_length', 4,
  1878. 'Lines should very rarely be longer than 100 characters')
  1879. elif line_width > 80:
  1880. error(filename, linenum, 'whitespace/line_length', 2,
  1881. 'Lines should be <= 80 characters long')
  1882. if (cleansed_line.count(';') > 1 and
  1883. # for loops are allowed two ;'s (and may run over two lines).
  1884. cleansed_line.find('for') == -1 and
  1885. (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
  1886. GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
  1887. # It's ok to have many commands in a switch case that fits in 1 line
  1888. not ((cleansed_line.find('case ') != -1 or
  1889. cleansed_line.find('default:') != -1) and
  1890. cleansed_line.find('break;') != -1)):
  1891. error(filename, linenum, 'whitespace/newline', 4,
  1892. 'More than one command on the same line')
  1893. # Some more style checks
  1894. CheckBraces(filename, clean_lines, linenum, error)
  1895. CheckSpacing(filename, clean_lines, linenum, error)
  1896. CheckCheck(filename, clean_lines, linenum, error)
  1897. if class_state and class_state.classinfo_stack:
  1898. CheckSectionSpacing(filename, clean_lines,
  1899. class_state.classinfo_stack[-1], linenum, error)
  1900. _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
  1901. _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
  1902. # Matches the first component of a filename delimited by -s and _s. That is:
  1903. # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
  1904. # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
  1905. # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
  1906. # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
  1907. _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
  1908. def _DropCommonSuffixes(filename):
  1909. """Drops common suffixes like _test.cc or -inl.h from filename.
  1910. For example:
  1911. >>> _DropCommonSuffixes('foo/foo-inl.h')
  1912. 'foo/foo'
  1913. >>> _DropCommonSuffixes('foo/bar/foo.cc')
  1914. 'foo/bar/foo'
  1915. >>> _DropCommonSuffixes('foo/foo_internal.h')
  1916. 'foo/foo'
  1917. >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
  1918. 'foo/foo_unusualinternal'
  1919. Args:
  1920. filename: The input filename.
  1921. Returns:
  1922. The filename with the common suffix removed.
  1923. """
  1924. for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
  1925. 'inl.h', 'impl.h', 'internal.h'):
  1926. if (filename.endswith(suffix) and len(filename) > len(suffix) and
  1927. filename[-len(suffix) - 1] in ('-', '_')):
  1928. return filename[:-len(suffix) - 1]
  1929. return os.path.splitext(filename)[0]
  1930. def _IsTestFilename(filename):
  1931. """Determines if the given filename has a suffix that identifies it as a test.
  1932. Args:
  1933. filename: The input filename.
  1934. Returns:
  1935. True if 'filename' looks like a test, False otherwise.
  1936. """
  1937. if (filename.endswith('_test.cc') or
  1938. filename.endswith('_unittest.cc') or
  1939. filename.endswith('_regtest.cc')):
  1940. return True
  1941. else:
  1942. return False
  1943. def _ClassifyInclude(fileinfo, include, is_system):
  1944. """Figures out what kind of header 'include' is.
  1945. Args:
  1946. fileinfo: The current file cpplint is running over. A FileInfo instance.
  1947. include: The path to a #included file.
  1948. is_system: True if the #include used <> rather than "".
  1949. Returns:
  1950. One of the _XXX_HEADER constants.
  1951. For example:
  1952. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
  1953. _C_SYS_HEADER
  1954. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
  1955. _CPP_SYS_HEADER
  1956. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
  1957. _LIKELY_MY_HEADER
  1958. >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
  1959. ... 'bar/foo_other_ext.h', False)
  1960. _POSSIBLE_MY_HEADER
  1961. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
  1962. _OTHER_HEADER
  1963. """
  1964. # This is a list of all standard c++ header files, except
  1965. # those already checked for above.
  1966. is_stl_h = include in _STL_HEADERS
  1967. is_cpp_h = is_stl_h or include in _CPP_HEADERS
  1968. if is_system:
  1969. if is_cpp_h:
  1970. return _CPP_SYS_HEADER
  1971. else:
  1972. return _C_SYS_HEADER
  1973. # If the target file and the include we're checking share a
  1974. # basename when we drop common extensions, and the include
  1975. # lives in . , then it's likely to be owned by the target file.
  1976. target_dir, target_base = (
  1977. os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
  1978. include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
  1979. if target_base == include_base and (
  1980. include_dir == target_dir or
  1981. include_dir == os.path.normpath(target_dir + '/../public')):
  1982. return _LIKELY_MY_HEADER
  1983. # If the target and include share some initial basename
  1984. # component, it's possible the target is implementing the
  1985. # include, so it's allowed to be first, but we'll never
  1986. # complain if it's not there.
  1987. target_first_component = _RE_FIRST_COMPONENT.match(target_base)
  1988. include_first_component = _RE_FIRST_COMPONENT.match(include_base)
  1989. if (target_first_component and include_first_component and
  1990. target_first_component.group(0) ==
  1991. include_first_component.group(0)):
  1992. return _POSSIBLE_MY_HEADER
  1993. return _OTHER_HEADER
  1994. def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
  1995. """Check rules that are applicable to #include lines.
  1996. Strings on #include lines are NOT removed from elided line, to make
  1997. certain tasks easier. However, to prevent false positives, checks
  1998. applicable to #include lines in CheckLanguage must be put here.
  1999. Args:
  2000. filename: The name of the current file.
  2001. clean_lines: A CleansedLines instance containing the file.
  2002. linenum: The number of the line to check.
  2003. include_state: An _IncludeState instance in which the headers are inserted.
  2004. error: The function to call with any errors found.
  2005. """
  2006. fileinfo = FileInfo(filename)
  2007. line = clean_lines.lines[linenum]
  2008. # "include" should use the new style "foo/bar.h" instead of just "bar.h"
  2009. if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
  2010. error(filename, linenum, 'build/include', 4,
  2011. 'Include the directory when naming .h files')
  2012. # we shouldn't include a file more than once. actually, there are a
  2013. # handful of instances where doing so is okay, but in general it's
  2014. # not.
  2015. match = _RE_PATTERN_INCLUDE.search(line)
  2016. if match:
  2017. include = match.group(2)
  2018. is_system = (match.group(1) == '<')
  2019. if include in include_state:
  2020. error(filename, linenum, 'build/include', 4,
  2021. '"%s" already included at %s:%s' %
  2022. (include, filename, include_state[include]))
  2023. else:
  2024. include_state[include] = linenum
  2025. # We want to ensure that headers appear in the right order:
  2026. # 1) for foo.cc, foo.h (preferred location)
  2027. # 2) c system files
  2028. # 3) cpp system files
  2029. # 4) for foo.cc, foo.h (deprecated location)
  2030. # 5) other google headers
  2031. #
  2032. # We classify each include statement as one of those 5 types
  2033. # using a number of techniques. The include_state object keeps
  2034. # track of the highest type seen, and complains if we see a
  2035. # lower type after that.
  2036. error_message = include_state.CheckNextIncludeOrder(
  2037. _ClassifyInclude(fileinfo, include, is_system))
  2038. if error_message:
  2039. error(filename, linenum, 'build/include_order', 4,
  2040. '%s. Should be: %s.h, c system, c++ system, other.' %
  2041. (error_message, fileinfo.BaseName()))
  2042. if not include_state.IsInAlphabeticalOrder(include):
  2043. error(filename, linenum, 'build/include_alpha', 4,
  2044. 'Include "%s" not in alphabetical order' % include)
  2045. # Look for any of the stream classes that are part of standard C++.
  2046. match = _RE_PATTERN_INCLUDE.match(line)
  2047. if match:
  2048. include = match.group(2)
  2049. if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
  2050. # Many unit tests use cout, so we exempt them.
  2051. if not _IsTestFilename(filename):
  2052. error(filename, linenum, 'readability/streams', 3,
  2053. 'Streams are highly discouraged.')
  2054. def _GetTextInside(text, start_pattern):
  2055. """Retrieves all the text between matching open and close parentheses.
  2056. Given a string of lines and a regular expression string, retrieve all the text
  2057. following the expression and between opening punctuation symbols like
  2058. (, [, or {, and the matching close-punctuation symbol. This properly nested
  2059. occurrences of the punctuations, so for the text like
  2060. printf(a(), b(c()));
  2061. a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
  2062. start_pattern must match string having an open punctuation symbol at the end.
  2063. Args:
  2064. text: The lines to extract text. Its comments and strings must be elided.
  2065. It can be single line and can span multiple lines.
  2066. start_pattern: The regexp string indicating where to start extracting
  2067. the text.
  2068. Returns:
  2069. The extracted text.
  2070. None if either the opening string or ending punctuation could not be found.
  2071. """
  2072. # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
  2073. # rewritten to use _GetTextInside (and use inferior regexp matching today).
  2074. # Give opening punctuations to get the matching close-punctuations.
  2075. matching_punctuation = {'(': ')', '{': '}', '[': ']'}
  2076. closing_punctuation = set(matching_punctuation.itervalues())
  2077. # Find the position to start extracting text.
  2078. match = re.search(start_pattern, text, re.M)
  2079. if not match: # start_pattern not found in text.
  2080. return None
  2081. start_position = match.end(0)
  2082. assert start_position > 0, (
  2083. 'start_pattern must ends with an opening punctuation.')
  2084. assert text[start_position - 1] in matching_punctuation, (
  2085. 'start_pattern must ends with an opening punctuation.')
  2086. # Stack of closing punctuations we expect to have in text after position.
  2087. punctuation_stack = [matching_punctuation[text[start_position - 1]]]
  2088. position = start_position
  2089. while punctuation_stack and position < len(text):
  2090. if text[position] == punctuation_stack[-1]:
  2091. punctuation_stack.pop()
  2092. elif text[position] in closing_punctuation:
  2093. # A closing punctuation without matching opening punctuations.
  2094. return None
  2095. elif text[position] in matching_punctuation:
  2096. punctuation_stack.append(matching_punctuation[text[position]])
  2097. position += 1
  2098. if punctuation_stack:
  2099. # Opening punctuations left without matching close-punctuations.
  2100. return None
  2101. # punctuations match.
  2102. return text[start_position:position - 1]
  2103. def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state,
  2104. error):
  2105. """Checks rules from the 'C++ language rules' section of cppguide.html.
  2106. Some of these rules are hard to test (function overloading, using
  2107. uint32 inappropriately), but we do the best we can.
  2108. Args:
  2109. filename: The name of the current file.
  2110. clean_lines: A CleansedLines instance containing the file.
  2111. linenum: The number of the line to check.
  2112. file_extension: The extension (without the dot) of the filename.
  2113. include_state: An _IncludeState instance in which the headers are inserted.
  2114. error: The function to call with any errors found.
  2115. """
  2116. # If the line is empty or consists of entirely a comment, no need to
  2117. # check it.
  2118. line = clean_lines.elided[linenum]
  2119. if not line:
  2120. return
  2121. match = _RE_PATTERN_INCLUDE.search(line)
  2122. if match:
  2123. CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
  2124. return
  2125. # Create an extended_line, which is the concatenation of the current and
  2126. # next lines, for more effective checking of code that may span more than one
  2127. # line.
  2128. if linenum + 1 < clean_lines.NumLines():
  2129. extended_line = line + clean_lines.elided[linenum + 1]
  2130. else:
  2131. extended_line = line
  2132. # Make Windows paths like Unix.
  2133. fullname = os.path.abspath(filename).replace('\\', '/')
  2134. # TODO(unknown): figure out if they're using default arguments in fn proto.
  2135. # Check for non-const references in functions. This is tricky because &
  2136. # is also used to take the address of something. We allow <> for templates,
  2137. # (ignoring whatever is between the braces) and : for classes.
  2138. # These are complicated re's. They try to capture the following:
  2139. # paren (for fn-prototype start), typename, &, varname. For the const
  2140. # version, we're willing for const to be before typename or after
  2141. # Don't check the implementation on same line.
  2142. fnline = line.split('{', 1)[0]
  2143. if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) >
  2144. len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?'
  2145. r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) +
  2146. len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+',
  2147. fnline))):
  2148. # We allow non-const references in a few standard places, like functions
  2149. # called "swap()" or iostream operators like "<<" or ">>".
  2150. if not Search(
  2151. r'(swap|Swap|operator[<>][<>])\s*\(\s*(?:[\w:]|<.*>)+\s*&',
  2152. fnline):
  2153. error(filename, linenum, 'runtime/references', 2,
  2154. 'Is this a non-const reference? '
  2155. 'If so, make const or use a pointer.')
  2156. # Check to see if they're using an conversion function cast.
  2157. # I just try to capture the most common basic types, though there are more.
  2158. # Parameterless conversion functions, such as bool(), are allowed as they are
  2159. # probably a member operator declaration or default constructor.
  2160. match = Search(
  2161. r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
  2162. r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line)
  2163. if match:
  2164. # gMock methods are defined using some variant of MOCK_METHODx(name, type)
  2165. # where type may be float(), int(string), etc. Without context they are
  2166. # virtually indistinguishable from int(x) casts. Likewise, gMock's
  2167. # MockCallback takes a template parameter of the form return_type(arg_type),
  2168. # which looks much like the cast we're trying to detect.
  2169. if (match.group(1) is None and # If new operator, then this isn't a cast
  2170. not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
  2171. Match(r'^\s*MockCallback<.*>', line))):
  2172. error(filename, linenum, 'readability/casting', 4,
  2173. 'Using deprecated casting style. '
  2174. 'Use static_cast<%s>(...) instead' %
  2175. match.group(2))
  2176. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  2177. 'static_cast',
  2178. r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
  2179. # This doesn't catch all cases. Consider (const char * const)"hello".
  2180. #
  2181. # (char *) "foo" should always be a const_cast (reinterpret_cast won't
  2182. # compile).
  2183. if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  2184. 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
  2185. pass
  2186. else:
  2187. # Check pointer casts for other than string constants
  2188. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  2189. 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
  2190. # In addition, we look for people taking the address of a cast. This
  2191. # is dangerous -- casts can assign to temporaries, so the pointer doesn't
  2192. # point where you think.
  2193. if Search(
  2194. r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line):
  2195. error(filename, linenum, 'runtime/casting', 4,
  2196. ('Are you taking an address of a cast? '
  2197. 'This is dangerous: could be a temp var. '
  2198. 'Take the address before doing the cast, rather than after'))
  2199. # Check for people declaring static/global STL strings at the top level.
  2200. # This is dangerous because the C++ language does not guarantee that
  2201. # globals with constructors are initialized before the first access.
  2202. match = Match(
  2203. r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
  2204. line)
  2205. # Make sure it's not a function.
  2206. # Function template specialization looks like: "string foo<Type>(...".
  2207. # Class template definitions look like: "string Foo<Type>::Method(...".
  2208. if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)',
  2209. match.group(3)):
  2210. error(filename, linenum, 'runtime/string', 4,
  2211. 'For a static/global string constant, use a C style string instead: '
  2212. '"%schar %s[]".' %
  2213. (match.group(1), match.group(2)))
  2214. # Check that we're not using RTTI outside of testing code.
  2215. if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename):
  2216. error(filename, linenum, 'runtime/rtti', 5,
  2217. 'Do not use dynamic_cast<>. If you need to cast within a class '
  2218. "hierarchy, use static_cast<> to upcast. Google doesn't support "
  2219. 'RTTI.')
  2220. if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
  2221. error(filename, linenum, 'runtime/init', 4,
  2222. 'You seem to be initializing a member variable with itself.')
  2223. if file_extension == 'h':
  2224. # TODO(unknown): check that 1-arg constructors are explicit.
  2225. # How to tell it's a constructor?
  2226. # (handled in CheckForNonStandardConstructs for now)
  2227. # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
  2228. # (level 1 error)
  2229. pass
  2230. # Check if people are using the verboten C basic types. The only exception
  2231. # we regularly allow is "unsigned short port" for port.
  2232. if Search(r'\bshort port\b', line):
  2233. if not Search(r'\bunsigned short port\b', line):
  2234. error(filename, linenum, 'runtime/int', 4,
  2235. 'Use "unsigned short" for ports, not "short"')
  2236. else:
  2237. match = Search(r'\b(short|long(?! +double)|long long)\b', line)
  2238. if match:
  2239. error(filename, linenum, 'runtime/int', 4,
  2240. 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
  2241. # When snprintf is used, the second argument shouldn't be a literal.
  2242. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
  2243. if match and match.group(2) != '0':
  2244. # If 2nd arg is zero, snprintf is used to calculate size.
  2245. error(filename, linenum, 'runtime/printf', 3,
  2246. 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
  2247. 'to snprintf.' % (match.group(1), match.group(2)))
  2248. # Check if some verboten C functions are being used.
  2249. if Search(r'\bsprintf\b', line):
  2250. error(filename, linenum, 'runtime/printf', 5,
  2251. 'Never use sprintf. Use snprintf instead.')
  2252. match = Search(r'\b(strcpy|strcat)\b', line)
  2253. if match:
  2254. error(filename, linenum, 'runtime/printf', 4,
  2255. 'Almost always, snprintf is better than %s' % match.group(1))
  2256. if Search(r'\bsscanf\b', line):
  2257. error(filename, linenum, 'runtime/printf', 1,
  2258. 'sscanf can be ok, but is slow and can overflow buffers.')
  2259. # Check if some verboten operator overloading is going on
  2260. # TODO(unknown): catch out-of-line unary operator&:
  2261. # class X {};
  2262. # int operator&(const X& x) { return 42; } // unary operator&
  2263. # The trick is it's hard to tell apart from binary operator&:
  2264. # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
  2265. if Search(r'\boperator\s*&\s*\(\s*\)', line):
  2266. error(filename, linenum, 'runtime/operator', 4,
  2267. 'Unary operator& is dangerous. Do not use it.')
  2268. # Check for suspicious usage of "if" like
  2269. # } if (a == b) {
  2270. if Search(r'\}\s*if\s*\(', line):
  2271. error(filename, linenum, 'readability/braces', 4,
  2272. 'Did you mean "else if"? If not, start a new line for "if".')
  2273. # Check for potential format string bugs like printf(foo).
  2274. # We constrain the pattern not to pick things like DocidForPrintf(foo).
  2275. # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
  2276. # TODO(sugawarayu): Catch the following case. Need to change the calling
  2277. # convention of the whole function to process multiple line to handle it.
  2278. # printf(
  2279. # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
  2280. printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
  2281. if printf_args:
  2282. match = Match(r'([\w.\->()]+)$', printf_args)
  2283. if match:
  2284. function_name = re.search(r'\b((?:string)?printf)\s*\(',
  2285. line, re.I).group(1)
  2286. error(filename, linenum, 'runtime/printf', 4,
  2287. 'Potential format string bug. Do %s("%%s", %s) instead.'
  2288. % (function_name, match.group(1)))
  2289. # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
  2290. match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
  2291. if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
  2292. error(filename, linenum, 'runtime/memset', 4,
  2293. 'Did you mean "memset(%s, 0, %s)"?'
  2294. % (match.group(1), match.group(2)))
  2295. if Search(r'\busing namespace\b', line):
  2296. error(filename, linenum, 'build/namespaces', 5,
  2297. 'Do not use namespace using-directives. '
  2298. 'Use using-declarations instead.')
  2299. # Detect variable-length arrays.
  2300. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
  2301. if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
  2302. match.group(3).find(']') == -1):
  2303. # Split the size using space and arithmetic operators as delimiters.
  2304. # If any of the resulting tokens are not compile time constants then
  2305. # report the error.
  2306. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
  2307. is_const = True
  2308. skip_next = False
  2309. for tok in tokens:
  2310. if skip_next:
  2311. skip_next = False
  2312. continue
  2313. if Search(r'sizeof\(.+\)', tok): continue
  2314. if Search(r'arraysize\(\w+\)', tok): continue
  2315. tok = tok.lstrip('(')
  2316. tok = tok.rstrip(')')
  2317. if not tok: continue
  2318. if Match(r'\d+', tok): continue
  2319. if Match(r'0[xX][0-9a-fA-F]+', tok): continue
  2320. if Match(r'k[A-Z0-9]\w*', tok): continue
  2321. if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
  2322. if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
  2323. # A catch all for tricky sizeof cases, including 'sizeof expression',
  2324. # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
  2325. # requires skipping the next token because we split on ' ' and '*'.
  2326. if tok.startswith('sizeof'):
  2327. skip_next = True
  2328. continue
  2329. is_const = False
  2330. break
  2331. if not is_const:
  2332. error(filename, linenum, 'runtime/arrays', 1,
  2333. 'Do not use variable-length arrays. Use an appropriately named '
  2334. "('k' followed by CamelCase) compile-time constant for the size.")
  2335. # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
  2336. # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
  2337. # in the class declaration.
  2338. match = Match(
  2339. (r'\s*'
  2340. r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
  2341. r'\(.*\);$'),
  2342. line)
  2343. if match and linenum + 1 < clean_lines.NumLines():
  2344. next_line = clean_lines.elided[linenum + 1]
  2345. # We allow some, but not all, declarations of variables to be present
  2346. # in the statement that defines the class. The [\w\*,\s]* fragment of
  2347. # the regular expression below allows users to declare instances of
  2348. # the class or pointers to instances, but not less common types such
  2349. # as function pointers or arrays. It's a tradeoff between allowing
  2350. # reasonable code and avoiding trying to parse more C++ using regexps.
  2351. if not Search(r'^\s*}[\w\*,\s]*;', next_line):
  2352. error(filename, linenum, 'readability/constructors', 3,
  2353. match.group(1) + ' should be the last thing in the class')
  2354. # Check for use of unnamed namespaces in header files. Registration
  2355. # macros are typically OK, so we allow use of "namespace {" on lines
  2356. # that end with backslashes.
  2357. if (file_extension == 'h'
  2358. and Search(r'\bnamespace\s*{', line)
  2359. and line[-1] != '\\'):
  2360. error(filename, linenum, 'build/namespaces', 4,
  2361. 'Do not use unnamed namespaces in header files. See '
  2362. 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
  2363. ' for more information.')
  2364. def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
  2365. error):
  2366. """Checks for a C-style cast by looking for the pattern.
  2367. This also handles sizeof(type) warnings, due to similarity of content.
  2368. Args:
  2369. filename: The name of the current file.
  2370. linenum: The number of the line to check.
  2371. line: The line of code to check.
  2372. raw_line: The raw line of code to check, with comments.
  2373. cast_type: The string for the C++ cast to recommend. This is either
  2374. reinterpret_cast, static_cast, or const_cast, depending.
  2375. pattern: The regular expression used to find C-style casts.
  2376. error: The function to call with any errors found.
  2377. Returns:
  2378. True if an error was emitted.
  2379. False otherwise.
  2380. """
  2381. match = Search(pattern, line)
  2382. if not match:
  2383. return False
  2384. # e.g., sizeof(int)
  2385. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
  2386. if sizeof_match:
  2387. error(filename, linenum, 'runtime/sizeof', 1,
  2388. 'Using sizeof(type). Use sizeof(varname) instead if possible')
  2389. return True
  2390. remainder = line[match.end(0):]
  2391. # The close paren is for function pointers as arguments to a function.
  2392. # eg, void foo(void (*bar)(int));
  2393. # The semicolon check is a more basic function check; also possibly a
  2394. # function pointer typedef.
  2395. # eg, void foo(int); or void foo(int) const;
  2396. # The equals check is for function pointer assignment.
  2397. # eg, void *(*foo)(int) = ...
  2398. # The > is for MockCallback<...> ...
  2399. #
  2400. # Right now, this will only catch cases where there's a single argument, and
  2401. # it's unnamed. It should probably be expanded to check for multiple
  2402. # arguments with some unnamed.
  2403. function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder)
  2404. if function_match:
  2405. if (not function_match.group(3) or
  2406. function_match.group(3) == ';' or
  2407. ('MockCallback<' not in raw_line and
  2408. '/*' not in raw_line)):
  2409. error(filename, linenum, 'readability/function', 3,
  2410. 'All parameters should be named in a function')
  2411. return True
  2412. # At this point, all that should be left is actual casts.
  2413. error(filename, linenum, 'readability/casting', 4,
  2414. 'Using C-style cast. Use %s<%s>(...) instead' %
  2415. (cast_type, match.group(1)))
  2416. return True
  2417. _HEADERS_CONTAINING_TEMPLATES = (
  2418. ('<deque>', ('deque',)),
  2419. ('<functional>', ('unary_function', 'binary_function',
  2420. 'plus', 'minus', 'multiplies', 'divides', 'modulus',
  2421. 'negate',
  2422. 'equal_to', 'not_equal_to', 'greater', 'less',
  2423. 'greater_equal', 'less_equal',
  2424. 'logical_and', 'logical_or', 'logical_not',
  2425. 'unary_negate', 'not1', 'binary_negate', 'not2',
  2426. 'bind1st', 'bind2nd',
  2427. 'pointer_to_unary_function',
  2428. 'pointer_to_binary_function',
  2429. 'ptr_fun',
  2430. 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
  2431. 'mem_fun_ref_t',
  2432. 'const_mem_fun_t', 'const_mem_fun1_t',
  2433. 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
  2434. 'mem_fun_ref',
  2435. )),
  2436. ('<limits>', ('numeric_limits',)),
  2437. ('<list>', ('list',)),
  2438. ('<map>', ('map', 'multimap',)),
  2439. ('<memory>', ('allocator',)),
  2440. ('<queue>', ('queue', 'priority_queue',)),
  2441. ('<set>', ('set', 'multiset',)),
  2442. ('<stack>', ('stack',)),
  2443. ('<string>', ('char_traits', 'basic_string',)),
  2444. ('<utility>', ('pair',)),
  2445. ('<vector>', ('vector',)),
  2446. # gcc extensions.
  2447. # Note: std::hash is their hash, ::hash is our hash
  2448. ('<hash_map>', ('hash_map', 'hash_multimap',)),
  2449. ('<hash_set>', ('hash_set', 'hash_multiset',)),
  2450. ('<slist>', ('slist',)),
  2451. )
  2452. _RE_PATTERN_STRING = re.compile(r'\bstring\b')
  2453. _re_pattern_algorithm_header = []
  2454. for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
  2455. 'transform'):
  2456. # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
  2457. # type::max().
  2458. _re_pattern_algorithm_header.append(
  2459. (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
  2460. _template,
  2461. '<algorithm>'))
  2462. _re_pattern_templates = []
  2463. for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
  2464. for _template in _templates:
  2465. _re_pattern_templates.append(
  2466. (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
  2467. _template + '<>',
  2468. _header))
  2469. def FilesBelongToSameModule(filename_cc, filename_h):
  2470. """Check if these two filenames belong to the same module.
  2471. The concept of a 'module' here is a as follows:
  2472. foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
  2473. same 'module' if they are in the same directory.
  2474. some/path/public/xyzzy and some/path/internal/xyzzy are also considered
  2475. to belong to the same module here.
  2476. If the filename_cc contains a longer path than the filename_h, for example,
  2477. '/absolute/path/to/base/sysinfo.cc', and this file would include
  2478. 'base/sysinfo.h', this function also produces the prefix needed to open the
  2479. header. This is used by the caller of this function to more robustly open the
  2480. header file. We don't have access to the real include paths in this context,
  2481. so we need this guesswork here.
  2482. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
  2483. according to this implementation. Because of this, this function gives
  2484. some false positives. This should be sufficiently rare in practice.
  2485. Args:
  2486. filename_cc: is the path for the .cc file
  2487. filename_h: is the path for the header path
  2488. Returns:
  2489. Tuple with a bool and a string:
  2490. bool: True if filename_cc and filename_h belong to the same module.
  2491. string: the additional prefix needed to open the header file.
  2492. """
  2493. if not filename_cc.endswith('.cc'):
  2494. return (False, '')
  2495. filename_cc = filename_cc[:-len('.cc')]
  2496. if filename_cc.endswith('_unittest'):
  2497. filename_cc = filename_cc[:-len('_unittest')]
  2498. elif filename_cc.endswith('_test'):
  2499. filename_cc = filename_cc[:-len('_test')]
  2500. filename_cc = filename_cc.replace('/public/', '/')
  2501. filename_cc = filename_cc.replace('/internal/', '/')
  2502. if not filename_h.endswith('.h'):
  2503. return (False, '')
  2504. filename_h = filename_h[:-len('.h')]
  2505. if filename_h.endswith('-inl'):
  2506. filename_h = filename_h[:-len('-inl')]
  2507. filename_h = filename_h.replace('/public/', '/')
  2508. filename_h = filename_h.replace('/internal/', '/')
  2509. files_belong_to_same_module = filename_cc.endswith(filename_h)
  2510. common_path = ''
  2511. if files_belong_to_same_module:
  2512. common_path = filename_cc[:-len(filename_h)]
  2513. return files_belong_to_same_module, common_path
  2514. def UpdateIncludeState(filename, include_state, io=codecs):
  2515. """Fill up the include_state with new includes found from the file.
  2516. Args:
  2517. filename: the name of the header to read.
  2518. include_state: an _IncludeState instance in which the headers are inserted.
  2519. io: The io factory to use to read the file. Provided for testability.
  2520. Returns:
  2521. True if a header was succesfully added. False otherwise.
  2522. """
  2523. headerfile = None
  2524. try:
  2525. headerfile = io.open(filename, 'r', 'utf8', 'replace')
  2526. except IOError:
  2527. return False
  2528. linenum = 0
  2529. for line in headerfile:
  2530. linenum += 1
  2531. clean_line = CleanseComments(line)
  2532. match = _RE_PATTERN_INCLUDE.search(clean_line)
  2533. if match:
  2534. include = match.group(2)
  2535. # The value formatting is cute, but not really used right now.
  2536. # What matters here is that the key is in include_state.
  2537. include_state.setdefault(include, '%s:%d' % (filename, linenum))
  2538. return True
  2539. def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
  2540. io=codecs):
  2541. """Reports for missing stl includes.
  2542. This function will output warnings to make sure you are including the headers
  2543. necessary for the stl containers and functions that you use. We only give one
  2544. reason to include a header. For example, if you use both equal_to<> and
  2545. less<> in a .h file, only one (the latter in the file) of these will be
  2546. reported as a reason to include the <functional>.
  2547. Args:
  2548. filename: The name of the current file.
  2549. clean_lines: A CleansedLines instance containing the file.
  2550. include_state: An _IncludeState instance.
  2551. error: The function to call with any errors found.
  2552. io: The IO factory to use to read the header file. Provided for unittest
  2553. injection.
  2554. """
  2555. required = {} # A map of header name to linenumber and the template entity.
  2556. # Example of required: { '<functional>': (1219, 'less<>') }
  2557. for linenum in xrange(clean_lines.NumLines()):
  2558. line = clean_lines.elided[linenum]
  2559. if not line or line[0] == '#':
  2560. continue
  2561. # String is special -- it is a non-templatized type in STL.
  2562. matched = _RE_PATTERN_STRING.search(line)
  2563. if matched:
  2564. # Don't warn about strings in non-STL namespaces:
  2565. # (We check only the first match per line; good enough.)
  2566. prefix = line[:matched.start()]
  2567. if prefix.endswith('std::') or not prefix.endswith('::'):
  2568. required['<string>'] = (linenum, 'string')
  2569. for pattern, template, header in _re_pattern_algorithm_header:
  2570. if pattern.search(line):
  2571. required[header] = (linenum, template)
  2572. # The following function is just a speed up, no semantics are changed.
  2573. if not '<' in line: # Reduces the cpu time usage by skipping lines.
  2574. continue
  2575. for pattern, template, header in _re_pattern_templates:
  2576. if pattern.search(line):
  2577. required[header] = (linenum, template)
  2578. # The policy is that if you #include something in foo.h you don't need to
  2579. # include it again in foo.cc. Here, we will look at possible includes.
  2580. # Let's copy the include_state so it is only messed up within this function.
  2581. include_state = include_state.copy()
  2582. # Did we find the header for this file (if any) and succesfully load it?
  2583. header_found = False
  2584. # Use the absolute path so that matching works properly.
  2585. abs_filename = FileInfo(filename).FullName()
  2586. # For Emacs's flymake.
  2587. # If cpplint is invoked from Emacs's flymake, a temporary file is generated
  2588. # by flymake and that file name might end with '_flymake.cc'. In that case,
  2589. # restore original file name here so that the corresponding header file can be
  2590. # found.
  2591. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
  2592. # instead of 'foo_flymake.h'
  2593. abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
  2594. # include_state is modified during iteration, so we iterate over a copy of
  2595. # the keys.
  2596. header_keys = include_state.keys()
  2597. for header in header_keys:
  2598. (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
  2599. fullpath = common_path + header
  2600. if same_module and UpdateIncludeState(fullpath, include_state, io):
  2601. header_found = True
  2602. # If we can't find the header file for a .cc, assume it's because we don't
  2603. # know where to look. In that case we'll give up as we're not sure they
  2604. # didn't include it in the .h file.
  2605. # TODO(unknown): Do a better job of finding .h files so we are confident that
  2606. # not having the .h file means there isn't one.
  2607. if filename.endswith('.cc') and not header_found:
  2608. return
  2609. # All the lines have been processed, report the errors found.
  2610. for required_header_unstripped in required:
  2611. template = required[required_header_unstripped][1]
  2612. if required_header_unstripped.strip('<>"') not in include_state:
  2613. error(filename, required[required_header_unstripped][0],
  2614. 'build/include_what_you_use', 4,
  2615. 'Add #include ' + required_header_unstripped + ' for ' + template)
  2616. _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
  2617. def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
  2618. """Check that make_pair's template arguments are deduced.
  2619. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
  2620. specified explicitly, and such use isn't intended in any case.
  2621. Args:
  2622. filename: The name of the current file.
  2623. clean_lines: A CleansedLines instance containing the file.
  2624. linenum: The number of the line to check.
  2625. error: The function to call with any errors found.
  2626. """
  2627. raw = clean_lines.raw_lines
  2628. line = raw[linenum]
  2629. match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
  2630. if match:
  2631. error(filename, linenum, 'build/explicit_make_pair',
  2632. 4, # 4 = high confidence
  2633. 'Omit template arguments from make_pair OR use pair directly OR'
  2634. ' if appropriate, construct a pair directly')
  2635. def ProcessLine(filename, file_extension,
  2636. clean_lines, line, include_state, function_state,
  2637. class_state, error, extra_check_functions=[]):
  2638. """Processes a single line in the file.
  2639. Args:
  2640. filename: Filename of the file that is being processed.
  2641. file_extension: The extension (dot not included) of the file.
  2642. clean_lines: An array of strings, each representing a line of the file,
  2643. with comments stripped.
  2644. line: Number of line being processed.
  2645. include_state: An _IncludeState instance in which the headers are inserted.
  2646. function_state: A _FunctionState instance which counts function lines, etc.
  2647. class_state: A _ClassState instance which maintains information about
  2648. the current stack of nested class declarations being parsed.
  2649. error: A callable to which errors are reported, which takes 4 arguments:
  2650. filename, line number, error level, and message
  2651. extra_check_functions: An array of additional check functions that will be
  2652. run on each source line. Each function takes 4
  2653. arguments: filename, clean_lines, line, error
  2654. """
  2655. raw_lines = clean_lines.raw_lines
  2656. ParseNolintSuppressions(filename, raw_lines[line], line, error)
  2657. CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
  2658. CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
  2659. CheckStyle(filename, clean_lines, line, file_extension, class_state, error)
  2660. CheckLanguage(filename, clean_lines, line, file_extension, include_state,
  2661. error)
  2662. CheckForNonStandardConstructs(filename, clean_lines, line,
  2663. class_state, error)
  2664. CheckPosixThreading(filename, clean_lines, line, error)
  2665. CheckInvalidIncrement(filename, clean_lines, line, error)
  2666. CheckMakePairUsesDeduction(filename, clean_lines, line, error)
  2667. for check_fn in extra_check_functions:
  2668. check_fn(filename, clean_lines, line, error)
  2669. def ProcessFileData(filename, file_extension, lines, error,
  2670. extra_check_functions=[]):
  2671. """Performs lint checks and reports any errors to the given error function.
  2672. Args:
  2673. filename: Filename of the file that is being processed.
  2674. file_extension: The extension (dot not included) of the file.
  2675. lines: An array of strings, each representing a line of the file, with the
  2676. last element being empty if the file is terminated with a newline.
  2677. error: A callable to which errors are reported, which takes 4 arguments:
  2678. filename, line number, error level, and message
  2679. extra_check_functions: An array of additional check functions that will be
  2680. run on each source line. Each function takes 4
  2681. arguments: filename, clean_lines, line, error
  2682. """
  2683. lines = (['// marker so line numbers and indices both start at 1'] + lines +
  2684. ['// marker so line numbers end in a known way'])
  2685. include_state = _IncludeState()
  2686. function_state = _FunctionState()
  2687. class_state = _ClassState()
  2688. ResetNolintSuppressions()
  2689. CheckForCopyright(filename, lines, error)
  2690. if file_extension == 'h':
  2691. CheckForHeaderGuard(filename, lines, error)
  2692. RemoveMultiLineComments(filename, lines, error)
  2693. clean_lines = CleansedLines(lines)
  2694. for line in xrange(clean_lines.NumLines()):
  2695. ProcessLine(filename, file_extension, clean_lines, line,
  2696. include_state, function_state, class_state, error,
  2697. extra_check_functions)
  2698. class_state.CheckFinished(filename, error)
  2699. CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
  2700. # We check here rather than inside ProcessLine so that we see raw
  2701. # lines rather than "cleaned" lines.
  2702. CheckForUnicodeReplacementCharacters(filename, lines, error)
  2703. CheckForNewlineAtEOF(filename, lines, error)
  2704. def ProcessFile(filename, vlevel, extra_check_functions=[]):
  2705. """Does google-lint on a single file.
  2706. Args:
  2707. filename: The name of the file to parse.
  2708. vlevel: The level of errors to report. Every error of confidence
  2709. >= verbose_level will be reported. 0 is a good default.
  2710. extra_check_functions: An array of additional check functions that will be
  2711. run on each source line. Each function takes 4
  2712. arguments: filename, clean_lines, line, error
  2713. """
  2714. _SetVerboseLevel(vlevel)
  2715. try:
  2716. # Support the UNIX convention of using "-" for stdin. Note that
  2717. # we are not opening the file with universal newline support
  2718. # (which codecs doesn't support anyway), so the resulting lines do
  2719. # contain trailing '\r' characters if we are reading a file that
  2720. # has CRLF endings.
  2721. # If after the split a trailing '\r' is present, it is removed
  2722. # below. If it is not expected to be present (i.e. os.linesep !=
  2723. # '\r\n' as in Windows), a warning is issued below if this file
  2724. # is processed.
  2725. if filename == '-':
  2726. lines = codecs.StreamReaderWriter(sys.stdin,
  2727. codecs.getreader('utf8'),
  2728. codecs.getwriter('utf8'),
  2729. 'replace').read().split('\n')
  2730. else:
  2731. lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
  2732. carriage_return_found = False
  2733. # Remove trailing '\r'.
  2734. for linenum in range(len(lines)):
  2735. if lines[linenum].endswith('\r'):
  2736. lines[linenum] = lines[linenum].rstrip('\r')
  2737. carriage_return_found = True
  2738. except IOError:
  2739. sys.stderr.write(
  2740. "Skipping input '%s': Can't open for reading\n" % filename)
  2741. return
  2742. # Note, if no dot is found, this will give the entire filename as the ext.
  2743. file_extension = filename[filename.rfind('.') + 1:]
  2744. # When reading from stdin, the extension is unknown, so no cpplint tests
  2745. # should rely on the extension.
  2746. if (filename != '-' and file_extension != 'cc' and file_extension != 'h'
  2747. and file_extension != 'cpp' and file_extension != 'C'):
  2748. sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename)
  2749. else:
  2750. ProcessFileData(filename, file_extension, lines, Error,
  2751. extra_check_functions)
  2752. if carriage_return_found and os.linesep != '\r\n':
  2753. # Use 0 for linenum since outputting only one error for potentially
  2754. # several lines.
  2755. Error(filename, 0, 'whitespace/newline', 1,
  2756. 'One or more unexpected \\r (^M) found;'
  2757. 'better to use only a \\n')
  2758. sys.stderr.write('Done processing %s\n' % filename)
  2759. def PrintUsage(message):
  2760. """Prints a brief usage string and exits, optionally with an error message.
  2761. Args:
  2762. message: The optional error message.
  2763. """
  2764. sys.stderr.write(_USAGE)
  2765. if message:
  2766. sys.exit('\nFATAL ERROR: ' + message)
  2767. else:
  2768. sys.exit(1)
  2769. def PrintCategories():
  2770. """Prints a list of all the error-categories used by error messages.
  2771. These are the categories used to filter messages via --filter.
  2772. """
  2773. sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
  2774. sys.exit(0)
  2775. def ParseArguments(args):
  2776. """Parses the command line arguments.
  2777. This may set the output format and verbosity level as side-effects.
  2778. Args:
  2779. args: The command line arguments:
  2780. Returns:
  2781. The list of filenames to lint.
  2782. """
  2783. try:
  2784. (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
  2785. 'counting=',
  2786. 'filter='])
  2787. except getopt.GetoptError:
  2788. PrintUsage('Invalid arguments.')
  2789. verbosity = _VerboseLevel()
  2790. output_format = _OutputFormat()
  2791. filters = ''
  2792. counting_style = ''
  2793. for (opt, val) in opts:
  2794. if opt == '--help':
  2795. PrintUsage(None)
  2796. elif opt == '--output':
  2797. if not val in ('emacs', 'vs7'):
  2798. PrintUsage('The only allowed output formats are emacs and vs7.')
  2799. output_format = val
  2800. elif opt == '--verbose':
  2801. verbosity = int(val)
  2802. elif opt == '--filter':
  2803. filters = val
  2804. if not filters:
  2805. PrintCategories()
  2806. elif opt == '--counting':
  2807. if val not in ('total', 'toplevel', 'detailed'):
  2808. PrintUsage('Valid counting options are total, toplevel, and detailed')
  2809. counting_style = val
  2810. if not filenames:
  2811. PrintUsage('No files were specified.')
  2812. _SetOutputFormat(output_format)
  2813. _SetVerboseLevel(verbosity)
  2814. _SetFilters(filters)
  2815. _SetCountingStyle(counting_style)
  2816. return filenames
  2817. def main():
  2818. filenames = ParseArguments(sys.argv[1:])
  2819. # Change stderr to write with replacement characters so we don't die
  2820. # if we try to print something containing non-ASCII characters.
  2821. sys.stderr = codecs.StreamReaderWriter(sys.stderr,
  2822. codecs.getreader('utf8'),
  2823. codecs.getwriter('utf8'),
  2824. 'replace')
  2825. _cpplint_state.ResetErrorCounts()
  2826. for filename in filenames:
  2827. ProcessFile(filename, _cpplint_state.verbose_level)
  2828. _cpplint_state.PrintErrorCounts()
  2829. sys.exit(_cpplint_state.error_count > 0)
  2830. if __name__ == '__main__':
  2831. main()