PageRenderTime 66ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/code/third_party/cpplint.py

https://bitbucket.org/hpsfo/hpsfo.bitbucket.org
Python | 3125 lines | 2491 code | 157 blank | 477 comment | 221 complexity | 0cb4f034f4b0e2e403e7ea9ad81c74f3 MD5 | raw file
Possible License(s): AGPL-3.0

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

  1. #!/usr/bin/python2.4
  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. Flags:
  101. output=vs7
  102. By default, the output is formatted to ease emacs parsing. Visual Studio
  103. compatible output (vs7) may also be used. Other formats are unsupported.
  104. verbose=#
  105. Specify a number 0-5 to restrict errors to certain verbosity levels.
  106. filter=-x,+y,...
  107. Specify a comma-separated list of category-filters to apply: only
  108. error messages whose category names pass the filters will be printed.
  109. (Category names are printed with the message and look like
  110. "[whitespace/indent]".) Filters are evaluated left to right.
  111. "-FOO" and "FOO" means "do not print categories that start with FOO".
  112. "+FOO" means "do print categories that start with FOO".
  113. Examples: --filter=-whitespace,+whitespace/braces
  114. --filter=whitespace,runtime/printf,+runtime/printf_format
  115. --filter=-,+build/include_what_you_use
  116. To see a list of all the categories used in cpplint, pass no arg:
  117. --filter=
  118. counting=total|toplevel|detailed
  119. The total number of errors found is always printed. If
  120. 'toplevel' is provided, then the count of errors in each of
  121. the top-level categories like 'build' and 'whitespace' will
  122. also be printed. If 'detailed' is provided, then a count
  123. is provided for each category like 'build/class'.
  124. """
  125. # We categorize each error message we print. Here are the categories.
  126. # We want an explicit list so we can list them all in cpplint --filter=.
  127. # If you add a new error message with a new category, add it to the list
  128. # here! cpplint_unittest.py should tell you if you forget to do this.
  129. # \ used for clearer layout -- pylint: disable-msg=C6013
  130. _ERROR_CATEGORIES = [
  131. 'build/class',
  132. 'build/deprecated',
  133. 'build/endif_comment',
  134. 'build/forward_decl',
  135. 'build/header_guard',
  136. 'build/include',
  137. 'build/include_alpha',
  138. 'build/include_order',
  139. 'build/include_what_you_use',
  140. 'build/namespaces',
  141. 'build/printf_format',
  142. 'build/storage_class',
  143. 'legal/copyright',
  144. 'readability/braces',
  145. 'readability/casting',
  146. 'readability/check',
  147. 'readability/constructors',
  148. 'readability/fn_size',
  149. 'readability/function',
  150. 'readability/multiline_comment',
  151. 'readability/multiline_string',
  152. 'readability/nolint',
  153. 'readability/streams',
  154. 'readability/todo',
  155. 'readability/utf8',
  156. 'runtime/arrays',
  157. 'runtime/casting',
  158. 'runtime/explicit',
  159. 'runtime/int',
  160. 'runtime/init',
  161. 'runtime/invalid_increment',
  162. 'runtime/member_string_references',
  163. 'runtime/memset',
  164. 'runtime/operator',
  165. 'runtime/printf',
  166. 'runtime/printf_format',
  167. 'runtime/references',
  168. 'runtime/rtti',
  169. 'runtime/sizeof',
  170. 'runtime/string',
  171. 'runtime/threadsafe_fn',
  172. 'runtime/virtual',
  173. 'whitespace/blank_line',
  174. 'whitespace/braces',
  175. 'whitespace/comma',
  176. 'whitespace/comments',
  177. 'whitespace/end_of_line',
  178. 'whitespace/ending_newline',
  179. 'whitespace/indent',
  180. 'whitespace/labels',
  181. 'whitespace/line_length',
  182. 'whitespace/newline',
  183. 'whitespace/operators',
  184. 'whitespace/parens',
  185. 'whitespace/semicolon',
  186. 'whitespace/tab',
  187. 'whitespace/todo'
  188. ]
  189. # The default state of the category filter. This is overrided by the --filter=
  190. # flag. By default all errors are on, so only add here categories that should be
  191. # off by default (i.e., categories that must be enabled by the --filter= flags).
  192. # All entries here should start with a '-' or '+', as in the --filter= flag.
  193. _DEFAULT_FILTERS = [ '-build/include_alpha' ]
  194. # We used to check for high-bit characters, but after much discussion we
  195. # decided those were OK, as long as they were in UTF-8 and didn't represent
  196. # hard-coded international strings, which belong in a seperate i18n file.
  197. # Headers that we consider STL headers.
  198. _STL_HEADERS = frozenset([
  199. 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception',
  200. 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set',
  201. 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'new',
  202. 'pair.h', 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack',
  203. 'stl_alloc.h', 'stl_relops.h', 'type_traits.h',
  204. 'utility', 'vector', 'vector.h',
  205. ])
  206. # Non-STL C++ system headers.
  207. _CPP_HEADERS = frozenset([
  208. 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype',
  209. 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath',
  210. 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef',
  211. 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype',
  212. 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream',
  213. 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip',
  214. 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream.h',
  215. 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
  216. 'numeric', 'ostream.h', 'parsestream.h', 'pfstream.h', 'PlotFile.h',
  217. 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h',
  218. 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
  219. 'stdiostream.h', 'streambuf.h', 'stream.h', 'strfile.h', 'string',
  220. 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray',
  221. ])
  222. # Assertion macros. These are defined in base/logging.h and
  223. # testing/base/gunit.h. Note that the _M versions need to come first
  224. # for substring matching to work.
  225. _CHECK_MACROS = [
  226. 'DCHECK', 'CHECK',
  227. 'EXPECT_TRUE_M', 'EXPECT_TRUE',
  228. 'ASSERT_TRUE_M', 'ASSERT_TRUE',
  229. 'EXPECT_FALSE_M', 'EXPECT_FALSE',
  230. 'ASSERT_FALSE_M', 'ASSERT_FALSE',
  231. ]
  232. # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
  233. _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
  234. for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
  235. ('>=', 'GE'), ('>', 'GT'),
  236. ('<=', 'LE'), ('<', 'LT')]:
  237. _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
  238. _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
  239. _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
  240. _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
  241. _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
  242. _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
  243. for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
  244. ('>=', 'LT'), ('>', 'LE'),
  245. ('<=', 'GT'), ('<', 'GE')]:
  246. _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
  247. _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
  248. _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
  249. _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
  250. # These constants define types of headers for use with
  251. # _IncludeState.CheckNextIncludeOrder().
  252. _C_SYS_HEADER = 1
  253. _CPP_SYS_HEADER = 2
  254. _LIKELY_MY_HEADER = 3
  255. _POSSIBLE_MY_HEADER = 4
  256. _OTHER_HEADER = 5
  257. _regexp_compile_cache = {}
  258. # Finds occurrences of NOLINT or NOLINT(...).
  259. _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?')
  260. # {str, set(int)}: a map from error categories to sets of linenumbers
  261. # on which those errors are expected and should be suppressed.
  262. _error_suppressions = {}
  263. def ParseNolintSuppressions(filename, raw_line, linenum, error):
  264. """Updates the global list of error-suppressions.
  265. Parses any NOLINT comments on the current line, updating the global
  266. error_suppressions store. Reports an error if the NOLINT comment
  267. was malformed.
  268. Args:
  269. filename: str, the name of the input file.
  270. raw_line: str, the line of input text, with comments.
  271. linenum: int, the number of the current line.
  272. error: function, an error handler.
  273. """
  274. # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
  275. m = _RE_SUPPRESSION.search(raw_line)
  276. if m:
  277. category = m.group(1)
  278. if category in (None, '(*)'): # => "suppress all"
  279. _error_suppressions.setdefault(None, set()).add(linenum)
  280. else:
  281. if category.startswith('(') and category.endswith(')'):
  282. category = category[1:-1]
  283. if category in _ERROR_CATEGORIES:
  284. _error_suppressions.setdefault(category, set()).add(linenum)
  285. else:
  286. error(filename, linenum, 'readability/nolint', 5,
  287. 'Unknown NOLINT error category: %s' % category)
  288. def ResetNolintSuppressions():
  289. "Resets the set of NOLINT suppressions to empty."
  290. _error_suppressions.clear()
  291. def IsErrorSuppressedByNolint(category, linenum):
  292. """Returns true if the specified error category is suppressed on this line.
  293. Consults the global error_suppressions map populated by
  294. ParseNolintSuppressions/ResetNolintSuppressions.
  295. Args:
  296. category: str, the category of the error.
  297. linenum: int, the current line number.
  298. Returns:
  299. bool, True iff the error should be suppressed due to a NOLINT comment.
  300. """
  301. return (linenum in _error_suppressions.get(category, set()) or
  302. linenum in _error_suppressions.get(None, set()))
  303. def Match(pattern, s):
  304. """Matches the string with the pattern, caching the compiled regexp."""
  305. # The regexp compilation caching is inlined in both Match and Search for
  306. # performance reasons; factoring it out into a separate function turns out
  307. # to be noticeably expensive.
  308. if not pattern in _regexp_compile_cache:
  309. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  310. return _regexp_compile_cache[pattern].match(s)
  311. def Search(pattern, s):
  312. """Searches the string for the pattern, caching the compiled regexp."""
  313. if not pattern in _regexp_compile_cache:
  314. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  315. return _regexp_compile_cache[pattern].search(s)
  316. class _IncludeState(dict):
  317. """Tracks line numbers for includes, and the order in which includes appear.
  318. As a dict, an _IncludeState object serves as a mapping between include
  319. filename and line number on which that file was included.
  320. Call CheckNextIncludeOrder() once for each header in the file, passing
  321. in the type constants defined above. Calls in an illegal order will
  322. raise an _IncludeError with an appropriate error message.
  323. """
  324. # self._section will move monotonically through this set. If it ever
  325. # needs to move backwards, CheckNextIncludeOrder will raise an error.
  326. _INITIAL_SECTION = 0
  327. _MY_H_SECTION = 1
  328. _C_SECTION = 2
  329. _CPP_SECTION = 3
  330. _OTHER_H_SECTION = 4
  331. _TYPE_NAMES = {
  332. _C_SYS_HEADER: 'C system header',
  333. _CPP_SYS_HEADER: 'C++ system header',
  334. _LIKELY_MY_HEADER: 'header this file implements',
  335. _POSSIBLE_MY_HEADER: 'header this file may implement',
  336. _OTHER_HEADER: 'other header',
  337. }
  338. _SECTION_NAMES = {
  339. _INITIAL_SECTION: "... nothing. (This can't be an error.)",
  340. _MY_H_SECTION: 'a header this file implements',
  341. _C_SECTION: 'C system header',
  342. _CPP_SECTION: 'C++ system header',
  343. _OTHER_H_SECTION: 'other header',
  344. }
  345. def __init__(self):
  346. dict.__init__(self)
  347. # The name of the current section.
  348. self._section = self._INITIAL_SECTION
  349. # The path of last found header.
  350. self._last_header = ''
  351. def CanonicalizeAlphabeticalOrder(self, header_path):
  352. """Returns a path canonicalized for alphabetical comparisson.
  353. - replaces "-" with "_" so they both cmp the same.
  354. - removes '-inl' since we don't require them to be after the main header.
  355. - lowercase everything, just in case.
  356. Args:
  357. header_path: Path to be canonicalized.
  358. Returns:
  359. Canonicalized path.
  360. """
  361. return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
  362. def IsInAlphabeticalOrder(self, header_path):
  363. """Check if a header is in alphabetical order with the previous header.
  364. Args:
  365. header_path: Header to be checked.
  366. Returns:
  367. Returns true if the header is in alphabetical order.
  368. """
  369. canonical_header = self.CanonicalizeAlphabeticalOrder(header_path)
  370. if self._last_header > canonical_header:
  371. return False
  372. self._last_header = canonical_header
  373. return True
  374. def CheckNextIncludeOrder(self, header_type):
  375. """Returns a non-empty error message if the next header is out of order.
  376. This function also updates the internal state to be ready to check
  377. the next include.
  378. Args:
  379. header_type: One of the _XXX_HEADER constants defined above.
  380. Returns:
  381. The empty string if the header is in the right order, or an
  382. error message describing what's wrong.
  383. """
  384. error_message = ('Found %s after %s' %
  385. (self._TYPE_NAMES[header_type],
  386. self._SECTION_NAMES[self._section]))
  387. last_section = self._section
  388. if header_type == _C_SYS_HEADER:
  389. if self._section <= self._C_SECTION:
  390. self._section = self._C_SECTION
  391. else:
  392. self._last_header = ''
  393. return error_message
  394. elif header_type == _CPP_SYS_HEADER:
  395. if self._section <= self._CPP_SECTION:
  396. self._section = self._CPP_SECTION
  397. else:
  398. self._last_header = ''
  399. return error_message
  400. elif header_type == _LIKELY_MY_HEADER:
  401. if self._section <= self._MY_H_SECTION:
  402. self._section = self._MY_H_SECTION
  403. else:
  404. self._section = self._OTHER_H_SECTION
  405. elif header_type == _POSSIBLE_MY_HEADER:
  406. if self._section <= self._MY_H_SECTION:
  407. self._section = self._MY_H_SECTION
  408. else:
  409. # This will always be the fallback because we're not sure
  410. # enough that the header is associated with this file.
  411. self._section = self._OTHER_H_SECTION
  412. else:
  413. assert header_type == _OTHER_HEADER
  414. self._section = self._OTHER_H_SECTION
  415. if last_section != self._section:
  416. self._last_header = ''
  417. return ''
  418. class _CppLintState(object):
  419. """Maintains module-wide state.."""
  420. def __init__(self):
  421. self.verbose_level = 1 # global setting.
  422. self.error_count = 0 # global count of reported errors
  423. # filters to apply when emitting error messages
  424. self.filters = _DEFAULT_FILTERS[:]
  425. self.counting = 'total' # In what way are we counting errors?
  426. self.errors_by_category = {} # string to int dict storing error counts
  427. # output format:
  428. # "emacs" - format that emacs can parse (default)
  429. # "vs7" - format that Microsoft Visual Studio 7 can parse
  430. self.output_format = 'emacs'
  431. def SetOutputFormat(self, output_format):
  432. """Sets the output format for errors."""
  433. self.output_format = output_format
  434. def SetVerboseLevel(self, level):
  435. """Sets the module's verbosity, and returns the previous setting."""
  436. last_verbose_level = self.verbose_level
  437. self.verbose_level = level
  438. return last_verbose_level
  439. def SetCountingStyle(self, counting_style):
  440. """Sets the module's counting options."""
  441. self.counting = counting_style
  442. def SetFilters(self, filters):
  443. """Sets the error-message filters.
  444. These filters are applied when deciding whether to emit a given
  445. error message.
  446. Args:
  447. filters: A string of comma-separated filters (eg "+whitespace/indent").
  448. Each filter should start with + or -; else we die.
  449. Raises:
  450. ValueError: The comma-separated filters did not all start with '+' or '-'.
  451. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
  452. """
  453. # Default filters always have less priority than the flag ones.
  454. self.filters = _DEFAULT_FILTERS[:]
  455. for filt in filters.split(','):
  456. clean_filt = filt.strip()
  457. if clean_filt:
  458. self.filters.append(clean_filt)
  459. for filt in self.filters:
  460. if not (filt.startswith('+') or filt.startswith('-')):
  461. raise ValueError('Every filter in --filters must start with + or -'
  462. ' (%s does not)' % filt)
  463. def ResetErrorCounts(self):
  464. """Sets the module's error statistic back to zero."""
  465. self.error_count = 0
  466. self.errors_by_category = {}
  467. def IncrementErrorCount(self, category):
  468. """Bumps the module's error statistic."""
  469. self.error_count += 1
  470. if self.counting in ('toplevel', 'detailed'):
  471. if self.counting != 'detailed':
  472. category = category.split('/')[0]
  473. if category not in self.errors_by_category:
  474. self.errors_by_category[category] = 0
  475. self.errors_by_category[category] += 1
  476. def PrintErrorCounts(self):
  477. """Print a summary of errors by category, and the total."""
  478. for category, count in self.errors_by_category.iteritems():
  479. sys.stderr.write('Category \'%s\' errors found: %d\n' %
  480. (category, count))
  481. sys.stderr.write('Total errors found: %d\n' % self.error_count)
  482. _cpplint_state = _CppLintState()
  483. def _OutputFormat():
  484. """Gets the module's output format."""
  485. return _cpplint_state.output_format
  486. def _SetOutputFormat(output_format):
  487. """Sets the module's output format."""
  488. _cpplint_state.SetOutputFormat(output_format)
  489. def _VerboseLevel():
  490. """Returns the module's verbosity setting."""
  491. return _cpplint_state.verbose_level
  492. def _SetVerboseLevel(level):
  493. """Sets the module's verbosity, and returns the previous setting."""
  494. return _cpplint_state.SetVerboseLevel(level)
  495. def _SetCountingStyle(level):
  496. """Sets the module's counting options."""
  497. _cpplint_state.SetCountingStyle(level)
  498. def _Filters():
  499. """Returns the module's list of output filters, as a list."""
  500. return _cpplint_state.filters
  501. def _SetFilters(filters):
  502. """Sets the module's error-message filters.
  503. These filters are applied when deciding whether to emit a given
  504. error message.
  505. Args:
  506. filters: A string of comma-separated filters (eg "whitespace/indent").
  507. Each filter should start with + or -; else we die.
  508. """
  509. _cpplint_state.SetFilters(filters)
  510. class _FunctionState(object):
  511. """Tracks current function name and the number of lines in its body."""
  512. _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
  513. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
  514. def __init__(self):
  515. self.in_a_function = False
  516. self.lines_in_function = 0
  517. self.current_function = ''
  518. def Begin(self, function_name):
  519. """Start analyzing function body.
  520. Args:
  521. function_name: The name of the function being tracked.
  522. """
  523. self.in_a_function = True
  524. self.lines_in_function = 0
  525. self.current_function = function_name
  526. def Count(self):
  527. """Count line in current function body."""
  528. if self.in_a_function:
  529. self.lines_in_function += 1
  530. def Check(self, error, filename, linenum):
  531. """Report if too many lines in function body.
  532. Args:
  533. error: The function to call with any errors found.
  534. filename: The name of the current file.
  535. linenum: The number of the line to check.
  536. """
  537. if Match(r'T(EST|est)', self.current_function):
  538. base_trigger = self._TEST_TRIGGER
  539. else:
  540. base_trigger = self._NORMAL_TRIGGER
  541. trigger = base_trigger * 2**_VerboseLevel()
  542. if self.lines_in_function > trigger:
  543. error_level = int(math.log(self.lines_in_function / base_trigger, 2))
  544. # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
  545. if error_level > 5:
  546. error_level = 5
  547. error(filename, linenum, 'readability/fn_size', error_level,
  548. 'Small and focused functions are preferred:'
  549. ' %s has %d non-comment lines'
  550. ' (error triggered by exceeding %d lines).' % (
  551. self.current_function, self.lines_in_function, trigger))
  552. def End(self):
  553. """Stop analizing function body."""
  554. self.in_a_function = False
  555. class _IncludeError(Exception):
  556. """Indicates a problem with the include order in a file."""
  557. pass
  558. class FileInfo:
  559. """Provides utility functions for filenames.
  560. FileInfo provides easy access to the components of a file's path
  561. relative to the project root.
  562. """
  563. def __init__(self, filename):
  564. self._filename = filename
  565. def FullName(self):
  566. """Make Windows paths like Unix."""
  567. return os.path.abspath(self._filename).replace('\\', '/')
  568. def RepositoryName(self):
  569. """FullName after removing the local path to the repository.
  570. If we have a real absolute path name here we can try to do something smart:
  571. detecting the root of the checkout and truncating /path/to/checkout from
  572. the name so that we get header guards that don't include things like
  573. "C:\Documents and Settings\..." or "/home/username/..." in them and thus
  574. people on different computers who have checked the source out to different
  575. locations won't see bogus errors.
  576. """
  577. fullname = self.FullName()
  578. if os.path.exists(fullname):
  579. project_dir = os.path.dirname(fullname)
  580. if os.path.exists(os.path.join(project_dir, ".svn")):
  581. # If there's a .svn file in the current directory, we recursively look
  582. # up the directory tree for the top of the SVN checkout
  583. root_dir = project_dir
  584. one_up_dir = os.path.dirname(root_dir)
  585. while os.path.exists(os.path.join(one_up_dir, ".svn")):
  586. root_dir = os.path.dirname(root_dir)
  587. one_up_dir = os.path.dirname(one_up_dir)
  588. prefix = os.path.commonprefix([root_dir, project_dir])
  589. return fullname[len(prefix) + 1:]
  590. # Not SVN? Try to find a git or hg top level directory by searching up
  591. # from the current path.
  592. root_dir = os.path.dirname(fullname)
  593. while (root_dir != os.path.dirname(root_dir) and
  594. not os.path.exists(os.path.join(root_dir, ".git")) and
  595. not os.path.exists(os.path.join(root_dir, ".hg"))):
  596. root_dir = os.path.dirname(root_dir)
  597. if (os.path.exists(os.path.join(root_dir, ".git")) or
  598. os.path.exists(os.path.join(root_dir, ".hg"))):
  599. prefix = os.path.commonprefix([root_dir, project_dir])
  600. return fullname[len(prefix) + 1:]
  601. # Don't know what to do; header guard warnings may be wrong...
  602. return fullname
  603. def Split(self):
  604. """Splits the file into the directory, basename, and extension.
  605. For 'chrome/browser/browser.cc', Split() would
  606. return ('chrome/browser', 'browser', '.cc')
  607. Returns:
  608. A tuple of (directory, basename, extension).
  609. """
  610. googlename = self.RepositoryName()
  611. project, rest = os.path.split(googlename)
  612. return (project,) + os.path.splitext(rest)
  613. def BaseName(self):
  614. """File base name - text after the final slash, before the final period."""
  615. return self.Split()[1]
  616. def Extension(self):
  617. """File extension - text following the final period."""
  618. return self.Split()[2]
  619. def NoExtension(self):
  620. """File has no source file extension."""
  621. return '/'.join(self.Split()[0:2])
  622. def IsSource(self):
  623. """File has a source file extension."""
  624. return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
  625. def _ShouldPrintError(category, confidence, linenum):
  626. """Returns true iff confidence >= verbose, category passes
  627. filter and is not NOLINT-suppressed."""
  628. # There are three ways we might decide not to print an error message:
  629. # a "NOLINT(category)" comment appears in the source,
  630. # the verbosity level isn't high enough, or the filters filter it out.
  631. if IsErrorSuppressedByNolint(category, linenum):
  632. return False
  633. if confidence < _cpplint_state.verbose_level:
  634. return False
  635. is_filtered = False
  636. for one_filter in _Filters():
  637. if one_filter.startswith('-'):
  638. if category.startswith(one_filter[1:]):
  639. is_filtered = True
  640. elif one_filter.startswith('+'):
  641. if category.startswith(one_filter[1:]):
  642. is_filtered = False
  643. else:
  644. assert False # should have been checked for in SetFilter.
  645. if is_filtered:
  646. return False
  647. return True
  648. def Error(filename, linenum, category, confidence, message):
  649. """Logs the fact we've found a lint error.
  650. We log where the error was found, and also our confidence in the error,
  651. that is, how certain we are this is a legitimate style regression, and
  652. not a misidentification or a use that's sometimes justified.
  653. False positives can be suppressed by the use of
  654. "cpplint(category)" comments on the offending line. These are
  655. parsed into _error_suppressions.
  656. Args:
  657. filename: The name of the file containing the error.
  658. linenum: The number of the line containing the error.
  659. category: A string used to describe the "category" this bug
  660. falls under: "whitespace", say, or "runtime". Categories
  661. may have a hierarchy separated by slashes: "whitespace/indent".
  662. confidence: A number from 1-5 representing a confidence score for
  663. the error, with 5 meaning that we are certain of the problem,
  664. and 1 meaning that it could be a legitimate construct.
  665. message: The error message.
  666. """
  667. if _ShouldPrintError(category, confidence, linenum):
  668. _cpplint_state.IncrementErrorCount(category)
  669. if _cpplint_state.output_format == 'vs7':
  670. sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
  671. filename, linenum, message, category, confidence))
  672. else:
  673. sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
  674. filename, linenum, message, category, confidence))
  675. # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard.
  676. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
  677. r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
  678. # Matches strings. Escape codes should already be removed by ESCAPES.
  679. _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
  680. # Matches characters. Escape codes should already be removed by ESCAPES.
  681. _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
  682. # Matches multi-line C++ comments.
  683. # This RE is a little bit more complicated than one might expect, because we
  684. # have to take care of space removals tools so we can handle comments inside
  685. # statements better.
  686. # The current rule is: We only clear spaces from both sides when we're at the
  687. # end of the line. Otherwise, we try to remove spaces from the right side,
  688. # if this doesn't work we try on left side but only if there's a non-character
  689. # on the right.
  690. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
  691. r"""(\s*/\*.*\*/\s*$|
  692. /\*.*\*/\s+|
  693. \s+/\*.*\*/(?=\W)|
  694. /\*.*\*/)""", re.VERBOSE)
  695. def IsCppString(line):
  696. """Does line terminate so, that the next symbol is in string constant.
  697. This function does not consider single-line nor multi-line comments.
  698. Args:
  699. line: is a partial line of code starting from the 0..n.
  700. Returns:
  701. True, if next character appended to 'line' is inside a
  702. string constant.
  703. """
  704. line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
  705. return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
  706. def FindNextMultiLineCommentStart(lines, lineix):
  707. """Find the beginning marker for a multiline comment."""
  708. while lineix < len(lines):
  709. if lines[lineix].strip().startswith('/*'):
  710. # Only return this marker if the comment goes beyond this line
  711. if lines[lineix].strip().find('*/', 2) < 0:
  712. return lineix
  713. lineix += 1
  714. return len(lines)
  715. def FindNextMultiLineCommentEnd(lines, lineix):
  716. """We are inside a comment, find the end marker."""
  717. while lineix < len(lines):
  718. if lines[lineix].strip().endswith('*/'):
  719. return lineix
  720. lineix += 1
  721. return len(lines)
  722. def RemoveMultiLineCommentsFromRange(lines, begin, end):
  723. """Clears a range of lines for multi-line comments."""
  724. # Having // dummy comments makes the lines non-empty, so we will not get
  725. # unnecessary blank line warnings later in the code.
  726. for i in range(begin, end):
  727. lines[i] = '// dummy'
  728. def RemoveMultiLineComments(filename, lines, error):
  729. """Removes multiline (c-style) comments from lines."""
  730. lineix = 0
  731. while lineix < len(lines):
  732. lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
  733. if lineix_begin >= len(lines):
  734. return
  735. lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
  736. if lineix_end >= len(lines):
  737. error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
  738. 'Could not find end of multi-line comment')
  739. return
  740. RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
  741. lineix = lineix_end + 1
  742. def CleanseComments(line):
  743. """Removes //-comments and single-line C-style /* */ comments.
  744. Args:
  745. line: A line of C++ source.
  746. Returns:
  747. The line with single-line comments removed.
  748. """
  749. commentpos = line.find('//')
  750. if commentpos != -1 and not IsCppString(line[:commentpos]):
  751. line = line[:commentpos]
  752. # get rid of /* ... */
  753. return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
  754. class CleansedLines(object):
  755. """Holds 3 copies of all lines with different preprocessing applied to them.
  756. 1) elided member contains lines without strings and comments,
  757. 2) lines member contains lines without comments, and
  758. 3) raw member contains all the lines without processing.
  759. All these three members are of <type 'list'>, and of the same length.
  760. """
  761. def __init__(self, lines):
  762. self.elided = []
  763. self.lines = []
  764. self.raw_lines = lines
  765. self.num_lines = len(lines)
  766. for linenum in range(len(lines)):
  767. self.lines.append(CleanseComments(lines[linenum]))
  768. elided = self._CollapseStrings(lines[linenum])
  769. self.elided.append(CleanseComments(elided))
  770. def NumLines(self):
  771. """Returns the number of lines represented."""
  772. return self.num_lines
  773. @staticmethod
  774. def _CollapseStrings(elided):
  775. """Collapses strings and chars on a line to simple "" or '' blocks.
  776. We nix strings first so we're not fooled by text like '"http://"'
  777. Args:
  778. elided: The line being processed.
  779. Returns:
  780. The line with collapsed strings.
  781. """
  782. if not _RE_PATTERN_INCLUDE.match(elided):
  783. # Remove escaped characters first to make quote/single quote collapsing
  784. # basic. Things that look like escaped characters shouldn't occur
  785. # outside of strings and chars.
  786. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
  787. elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
  788. elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
  789. return elided
  790. def CloseExpression(clean_lines, linenum, pos):
  791. """If input points to ( or { or [, finds the position that closes it.
  792. If lines[linenum][pos] points to a '(' or '{' or '[', finds the the
  793. linenum/pos that correspond to the closing of the expression.
  794. Args:
  795. clean_lines: A CleansedLines instance containing the file.
  796. linenum: The number of the line to check.
  797. pos: A position on the line.
  798. Returns:
  799. A tuple (line, linenum, pos) pointer *past* the closing brace, or
  800. (line, len(lines), -1) if we never find a close. Note we ignore
  801. strings and comments when matching; and the line we return is the
  802. 'cleansed' line at linenum.
  803. """
  804. line = clean_lines.elided[linenum]
  805. startchar = line[pos]
  806. if startchar not in '({[':
  807. return (line, clean_lines.NumLines(), -1)
  808. if startchar == '(': endchar = ')'
  809. if startchar == '[': endchar = ']'
  810. if startchar == '{': endchar = '}'
  811. num_open = line.count(startchar) - line.count(endchar)
  812. while linenum < clean_lines.NumLines() and num_open > 0:
  813. linenum += 1
  814. line = clean_lines.elided[linenum]
  815. num_open += line.count(startchar) - line.count(endchar)
  816. # OK, now find the endchar that actually got us back to even
  817. endpos = len(line)
  818. while num_open >= 0:
  819. endpos = line.rfind(')', 0, endpos)
  820. num_open -= 1 # chopped off another )
  821. return (line, linenum, endpos + 1)
  822. def CheckForCopyright(filename, lines, error):
  823. """Logs an error if no Copyright message appears at the top of the file."""
  824. # We'll say it should occur by line 10. Don't forget there's a
  825. # dummy line at the front.
  826. for line in xrange(1, min(len(lines), 11)):
  827. if re.search(r'Copyright', lines[line], re.I): break
  828. else: # means no copyright line was found
  829. error(filename, 0, 'legal/copyright', 5,
  830. 'No copyright message found. '
  831. 'You should have a line: "Copyright [year] <Copyright Owner>"')
  832. def GetHeaderGuardCPPVariable(filename):
  833. """Returns the CPP variable that should be used as a header guard.
  834. Args:
  835. filename: The name of a C++ header file.
  836. Returns:
  837. The CPP variable that should be used as a header guard in the
  838. named file.
  839. """
  840. # Restores original filename in case that cpplint is invoked from Emacs's
  841. # flymake.
  842. filename = re.sub(r'_flymake\.h$', '.h', filename)
  843. fileinfo = FileInfo(filename)
  844. return re.sub(r'[-./\s]', '_', fileinfo.RepositoryName()).upper() + '_'
  845. def CheckForHeaderGuard(filename, lines, error):
  846. """Checks that the file contains a header guard.
  847. Logs an error if no #ifndef header guard is present. For other
  848. headers, checks that the full pathname is used.
  849. Args:
  850. filename: The name of the C++ header file.
  851. lines: An array of strings, each representing a line of the file.
  852. error: The function to call with any errors found.
  853. """
  854. cppvar = GetHeaderGuardCPPVariable(filename)
  855. ifndef = None
  856. ifndef_linenum = 0
  857. define = None
  858. endif = None
  859. endif_linenum = 0
  860. for linenum, line in enumerate(lines):
  861. linesplit = line.split()
  862. if len(linesplit) >= 2:
  863. # find the first occurrence of #ifndef and #define, save arg
  864. if not ifndef and linesplit[0] == '#ifndef':
  865. # set ifndef to the header guard presented on the #ifndef line.
  866. ifndef = linesplit[1]
  867. ifndef_linenum = linenum
  868. if not define and linesplit[0] == '#define':
  869. define = linesplit[1]
  870. # find the last occurrence of #endif, save entire line
  871. if line.startswith('#endif'):
  872. endif = line
  873. endif_linenum = linenum
  874. if not ifndef or not define or ifndef != define:
  875. error(filename, 0, 'build/header_guard', 5,
  876. 'No #ifndef header guard found, suggested CPP variable is: %s' %
  877. cppvar)
  878. return
  879. # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
  880. # for backward compatibility.
  881. if ifndef != cppvar:
  882. error_level = 0
  883. if ifndef != cppvar + '_':
  884. error_level = 5
  885. ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum,
  886. error)
  887. error(filename, ifndef_linenum, 'build/header_guard', error_level,
  888. '#ifndef header guard has wrong style, please use: %s' % cppvar)
  889. if endif != ('#endif // %s' % cppvar):
  890. error_level = 0
  891. if endif != ('#endif // %s' % (cppvar + '_')):
  892. error_level = 5
  893. ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum,
  894. error)
  895. error(filename, endif_linenum, 'build/header_guard', error_level,
  896. '#endif line should be "#endif // %s"' % cppvar)
  897. def CheckForUnicodeReplacementCharacters(filename, lines, error):
  898. """Logs an error for each line containing Unicode replacement characters.
  899. These indicate that either the file contained invalid UTF-8 (likely)
  900. or Unicode replacement characters (which it shouldn't). Note that
  901. it's possible for this to throw off line numbering if the invalid
  902. UTF-8 occurred adjacent to a newline.
  903. Args:
  904. filename: The name of the current file.
  905. lines: An array of strings, each representing a line of the file.
  906. error: The function to call with any errors found.
  907. """
  908. for linenum, line in enumerate(lines):
  909. if u'\ufffd' in line:
  910. error(filename, linenum, 'readability/utf8', 5,
  911. 'Line contains invalid UTF-8 (or Unicode replacement character).')
  912. def CheckForNewlineAtEOF(filename, lines, error):
  913. """Logs an error if there is no newline char at the end of the file.
  914. Args:
  915. filename: The name of the current file.
  916. lines: An array of strings, each representing a line of the file.
  917. error: The function to call with any errors found.
  918. """
  919. # The array lines() was created by adding two newlines to the
  920. # original file (go figure), then splitting on \n.
  921. # To verify that the file ends in \n, we just have to make sure the
  922. # last-but-two element of lines() exists and is empty.
  923. if len(lines) < 3 or lines[-2]:
  924. error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
  925. 'Could not find a newline character at the end of the file.')
  926. def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
  927. """Logs an error if we see /* ... */ or "..." that extend past one line.
  928. /* ... */ comments are legit inside macros, for one line.
  929. Otherwise, we prefer // comments, so it's ok to warn about the
  930. other. Likewise, it's ok for strings to extend across multiple
  931. lines, as long as a line continuation character (backslash)
  932. terminates each line. Although not currently prohibited by the C++
  933. style guide, it's ugly and unnecessary. We don't do well with either
  934. in this lint program, so we warn about both.
  935. Args:
  936. filename: The name of the current file.
  937. clean_lines: A CleansedLines instance containing the file.
  938. linenum: The number of the line to check.
  939. error: The function to call with any errors found.
  940. """
  941. line = clean_lines.elided[linenum]
  942. # Remove all \\ (escaped backslashes) from the line. They are OK, and the
  943. # second (escaped) slash may trigger later \" detection erroneously.
  944. line = line.replace('\\\\', '')
  945. if line.count('/*') > line.count('*/'):
  946. error(filename, linenum, 'readability/multiline_comment', 5,
  947. 'Complex multi-line /*...*/-style comment found. '
  948. 'Lint may give bogus warnings. '
  949. 'Consider replacing these with //-style comments, '
  950. 'with #if 0...#endif, '
  951. 'or with more clearly structured multi-line comments.')
  952. if (line.count('"') - line.count('\\"')) % 2:
  953. error(filename, linenum, 'readability/multiline_string', 5,
  954. 'Multi-line string ("...") found. This lint script doesn\'t '
  955. 'do well with such strings, and may give bogus warnings. They\'re '
  956. 'ugly and unnecessary, and you should use concatenation instead".')
  957. threading_list = (
  958. ('asctime(', 'asctime_r('),
  959. ('ctime(', 'ctime_r('),
  960. ('getgrgid(', 'getgrgid_r('),
  961. ('getgrnam(', 'getgrnam_r('),
  962. ('getlogin(', 'getlogin_r('),
  963. ('getpwnam(', 'getpwnam_r('),
  964. ('getpwuid(', 'getpwuid_r('),
  965. ('gmtime(', 'gmtime_r('),
  966. ('localtime(', 'localtime_r('),
  967. ('rand(', 'rand_r('),
  968. ('readdir(', 'readdir_r('),
  969. ('strtok(', 'strtok_r('),
  970. ('ttyname(', 'ttyname_r('),
  971. )
  972. def CheckPosixThreading(filename, clean_lines, linenum, error):
  973. """Checks for calls to thread-unsafe functions.
  974. Much code has been originally written without consideration of
  975. multi-threading. Also, engineers are relying on their old experience;
  976. they have learned posix before threading extensions were added. These
  977. tests guide the engineers to use thread-safe functions (when using
  978. posix directly).
  979. Args:
  980. filename: The name of the current file.
  981. clean_lines: A CleansedLines instance containing the file.
  982. linenum: The number of the line to check.
  983. error: The function to call with any errors found.
  984. """
  985. line = clean_lines.elided[linenum]
  986. for single_thread_function, multithread_safe_function in threading_list:
  987. ix = line.find(single_thread_function)
  988. # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
  989. if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
  990. line[ix - 1] not in ('_', '.', '>'))):
  991. error(filename, linenum, 'runtime/threadsafe_fn', 2,
  992. 'Consider using ' + multithread_safe_function +
  993. '...) instead of ' + single_thread_function +
  994. '...) for improved thread safety.')
  995. # Matches invalid increment: *count++, which moves pointer instead of
  996. # incrementing a value.
  997. _RE_PATTERN_INVALID_INCREMENT = re.compile(
  998. r'^\s*\*\w+(\+\+|--);')
  999. def CheckInvalidIncrement(filename, clean_lines, linenum, error):
  1000. """Checks for invalid increment *count++.
  1001. For example following function:
  1002. void increment_counter(int* count) {
  1003. *count++;
  1004. }
  1005. is invalid, because it effectively does count++, moving pointer, and should
  1006. be replaced with ++*count, (*count)++ or *count += 1.
  1007. Args:
  1008. filename: The name of the current file.
  1009. clean_lines: A CleansedLines instance containing the file.
  1010. linenum: The number of the line to check.
  1011. error: The function to call with any errors found.
  1012. """
  1013. line = clean_lines.elided[linenum]
  1014. if _RE_PATTERN_INVALID_INCREMENT.match(line):
  1015. error(filename, linenum, 'runtime/invalid_increment', 5,
  1016. 'Changing pointer instead of value (or unused value of operator*).')
  1017. class _ClassInfo(object):
  1018. """Stores information about a class."""
  1019. def __init__(self, name, linenum):
  1020. self.name = name
  1021. self.linenum = linenum
  1022. self.seen_open_brace = False
  1023. self.is_derived = False
  1024. self.virtual_method_linenumber = None
  1025. self.has_virtual_destructor = False
  1026. self.brace_depth = 0
  1027. class _ClassState(object):
  1028. """Holds the current state of the parse relating to class declarations.
  1029. It maintains a stack of _ClassInfos representing the parser's guess
  1030. as to the current nesting of class declarations. The innermost class
  1031. is at the top (back) of the stack. Typically, the stack will either
  1032. be empty or have exactly one entry.
  1033. """
  1034. def __init__(self):
  1035. self.classinfo_stack = []
  1036. def CheckFinished(self, filename, error):
  1037. """Checks that all classes have been completely parsed.
  1038. Call this when all lines in a file have been processed.
  1039. Args:
  1040. filename: The name of the current file.
  1041. error: The function to call with any errors found.
  1042. """
  1043. if self.classinfo_stack:
  1044. # Note: This test can result in false positives if #ifdef constructs
  1045. # get in the way of brace matching. See the testBuildClass test in
  1046. # cpplint_unittest.py for an example of this.
  1047. error(filename, self.classinfo_stack[0].linenum, 'build/class', 5,
  1048. 'Failed to find complete declaration of class %s' %
  1049. self.classinfo_stack[0].name)
  1050. def CheckForNonStandardConstructs(filename, clean_lines, linenum,
  1051. class_state, error):
  1052. """Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
  1053. Complain about several constructs which gcc-2 accepts, but which are
  1054. not standard C++. Warning about these in lint is one way to ease the
  1055. transition to new compilers.
  1056. - put storage class first (e.g. "static const" instead of "const static").
  1057. - "%lld" instead of %qd" in printf-type functions.
  1058. - "%1$d" is non-standard in printf-type functions.
  1059. - "\%" is an undefined character escape sequence.
  1060. - text after #endif is not allowed.
  1061. - invalid inner-style forward declaration.
  1062. - >? and <? operators, and their >?= and <?= cousins.
  1063. - classes with virtual methods need virtual destructors (compiler warning
  1064. available, but not turned on yet.)
  1065. Additionally, check for constructor/destructor style violations and reference
  1066. members, as it is very convenient to do so while checking for
  1067. gcc-2 compliance.
  1068. Args:
  1069. filename: The name of the current file.
  1070. clean_lines: A CleansedLines instance containing the file.
  1071. linenum: The number of the line to check.
  1072. class_state: A _ClassState instance which maintains information about
  1073. the current stack of nested class declarations being parsed.
  1074. error: A callable to which errors are reported, which takes 4 arguments:
  1075. filename, line number, error level, and message
  1076. """
  1077. # Remove comments from the line, but leave in strings for now.
  1078. line = clean_lines.lines[linenum]
  1079. if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
  1080. error(filename, linenum, 'runtime/printf_format', 3,
  1081. '%q in format strings is deprecated. Use %ll instead.')
  1082. if Search(r'printf\s*\(.*".*%\d+\$', line):
  1083. error(filename, linenum, 'runtime/printf_format', 2,
  1084. '%N$ formats are unconventional. Try rewriting to avoid them.')
  1085. # Remove escaped backslashes before looking for undefined escapes.
  1086. line = line.replace('\\\\', '')
  1087. if Search(r'("|\').*\\(%|\[|\(|{)', line):
  1088. error(filename, linenum, 'build/printf_format', 3,
  1089. '%, [, (, and { are undefined character escapes. Unescape them.')
  1090. # For the rest, work with both comments and strings removed.
  1091. line = clean_lines.elided[linenum]
  1092. if Search(r'\b(const|volatile|void|char|short|int|long'
  1093. r'|float|double|signed|unsigned'
  1094. r'|schar|u?int8|u?int16|u?int32|u?int64)'
  1095. r'\s+(auto|register|static|extern|typedef)\b',
  1096. line):
  1097. error(filename, linenum, 'build/storage_class', 5,
  1098. 'Storage class (static, extern, typedef, etc) should be first.')
  1099. if Match(r'\s*#\s*endif\s*[^/\s]+', line):
  1100. error(filename, linenum, 'build/endif_comment', 5,
  1101. 'Uncommented text after #endif is non-standard. Use a comment.')
  1102. if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
  1103. error(filename, linenum, 'build/forward_decl', 5,
  1104. 'Inner-style forward declarations are invalid. Remove this line.')
  1105. if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',

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