PageRenderTime 75ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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. '%, …

Large files files are truncated, but you can click here to view the full file