PageRenderTime 75ms CodeModel.GetById 21ms 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
  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*)?',
  1106. line):
  1107. error(filename, linenum, 'build/deprecated', 3,
  1108. '>? and <? (max and min) operators are non-standard and deprecated.')
  1109. if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
  1110. # TODO(unknown): Could it be expanded safely to arbitrary references,
  1111. # without triggering too many false positives? The first
  1112. # attempt triggered 5 warnings for mostly benign code in the regtest, hence
  1113. # the restriction.
  1114. # Here's the original regexp, for the reference:
  1115. # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
  1116. # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
  1117. error(filename, linenum, 'runtime/member_string_references', 2,
  1118. 'const string& members are dangerous. It is much better to use '
  1119. 'alternatives, such as pointers or simple constants.')
  1120. # Track class entry and exit, and attempt to find cases within the
  1121. # class declaration that don't meet the C++ style
  1122. # guidelines. Tracking is very dependent on the code matching Google
  1123. # style guidelines, but it seems to perform well enough in testing
  1124. # to be a worthwhile addition to the checks.
  1125. classinfo_stack = class_state.classinfo_stack
  1126. # Look for a class declaration
  1127. class_decl_match = Match(
  1128. r'\s*(template\s*<[\w\s<>,:]*>\s*)?(class|struct)\s+(\w+(::\w+)*)', line)
  1129. if class_decl_match:
  1130. classinfo_stack.append(_ClassInfo(class_decl_match.group(3), linenum))
  1131. # Everything else in this function uses the top of the stack if it's
  1132. # not empty.
  1133. if not classinfo_stack:
  1134. return
  1135. classinfo = classinfo_stack[-1]
  1136. # If the opening brace hasn't been seen look for it and also
  1137. # parent class declarations.
  1138. if not classinfo.seen_open_brace:
  1139. # If the line has a ';' in it, assume it's a forward declaration or
  1140. # a single-line class declaration, which we won't process.
  1141. if line.find(';') != -1:
  1142. classinfo_stack.pop()
  1143. return
  1144. classinfo.seen_open_brace = (line.find('{') != -1)
  1145. # Look for a bare ':'
  1146. if Search('(^|[^:]):($|[^:])', line):
  1147. classinfo.is_derived = True
  1148. if not classinfo.seen_open_brace:
  1149. return # Everything else in this function is for after open brace
  1150. # The class may have been declared with namespace or classname qualifiers.
  1151. # The constructor and destructor will not have those qualifiers.
  1152. base_classname = classinfo.name.split('::')[-1]
  1153. # Look for single-argument constructors that aren't marked explicit.
  1154. # Technically a valid construct, but against style.
  1155. args = Match(r'(?<!explicit)\s+%s\s*\(([^,()]+)\)'
  1156. % re.escape(base_classname),
  1157. line)
  1158. if (args and
  1159. args.group(1) != 'void' and
  1160. not Match(r'(const\s+)?%s\s*&' % re.escape(base_classname),
  1161. args.group(1).strip())):
  1162. error(filename, linenum, 'runtime/explicit', 5,
  1163. 'Single-argument constructors should be marked explicit.')
  1164. # Look for methods declared virtual.
  1165. if Search(r'\bvirtual\b', line):
  1166. classinfo.virtual_method_linenumber = linenum
  1167. # Only look for a destructor declaration on the same line. It would
  1168. # be extremely unlikely for the destructor declaration to occupy
  1169. # more than one line.
  1170. if Search(r'~%s\s*\(' % base_classname, line):
  1171. classinfo.has_virtual_destructor = True
  1172. # Look for class end.
  1173. brace_depth = classinfo.brace_depth
  1174. brace_depth = brace_depth + line.count('{') - line.count('}')
  1175. if brace_depth <= 0:
  1176. classinfo = classinfo_stack.pop()
  1177. # Try to detect missing virtual destructor declarations.
  1178. # For now, only warn if a non-derived class with virtual methods lacks
  1179. # a virtual destructor. This is to make it less likely that people will
  1180. # declare derived virtual destructors without declaring the base
  1181. # destructor virtual.
  1182. if ((classinfo.virtual_method_linenumber is not None) and
  1183. (not classinfo.has_virtual_destructor) and
  1184. (not classinfo.is_derived)): # Only warn for base classes
  1185. error(filename, classinfo.linenum, 'runtime/virtual', 4,
  1186. 'The class %s probably needs a virtual destructor due to '
  1187. 'having virtual method(s), one declared at line %d.'
  1188. % (classinfo.name, classinfo.virtual_method_linenumber))
  1189. else:
  1190. classinfo.brace_depth = brace_depth
  1191. def CheckSpacingForFunctionCall(filename, line, linenum, error):
  1192. """Checks for the correctness of various spacing around function calls.
  1193. Args:
  1194. filename: The name of the current file.
  1195. line: The text of the line to check.
  1196. linenum: The number of the line to check.
  1197. error: The function to call with any errors found.
  1198. """
  1199. # Since function calls often occur inside if/for/while/switch
  1200. # expressions - which have their own, more liberal conventions - we
  1201. # first see if we should be looking inside such an expression for a
  1202. # function call, to which we can apply more strict standards.
  1203. fncall = line # if there's no control flow construct, look at whole line
  1204. for pattern in (r'\bif\s*\((.*)\)\s*{',
  1205. r'\bfor\s*\((.*)\)\s*{',
  1206. r'\bwhile\s*\((.*)\)\s*[{;]',
  1207. r'\bswitch\s*\((.*)\)\s*{'):
  1208. match = Search(pattern, line)
  1209. if match:
  1210. fncall = match.group(1) # look inside the parens for function calls
  1211. break
  1212. # Except in if/for/while/switch, there should never be space
  1213. # immediately inside parens (eg "f( 3, 4 )"). We make an exception
  1214. # for nested parens ( (a+b) + c ). Likewise, there should never be
  1215. # a space before a ( when it's a function argument. I assume it's a
  1216. # function argument when the char before the whitespace is legal in
  1217. # a function name (alnum + _) and we're not starting a macro. Also ignore
  1218. # pointers and references to arrays and functions coz they're too tricky:
  1219. # we use a very simple way to recognize these:
  1220. # " (something)(maybe-something)" or
  1221. # " (something)(maybe-something," or
  1222. # " (something)[something]"
  1223. # Note that we assume the contents of [] to be short enough that
  1224. # they'll never need to wrap.
  1225. if ( # Ignore control structures.
  1226. not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and
  1227. # Ignore pointers/references to functions.
  1228. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
  1229. # Ignore pointers/references to arrays.
  1230. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
  1231. if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
  1232. error(filename, linenum, 'whitespace/parens', 4,
  1233. 'Extra space after ( in function call')
  1234. elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
  1235. error(filename, linenum, 'whitespace/parens', 2,
  1236. 'Extra space after (')
  1237. if (Search(r'\w\s+\(', fncall) and
  1238. not Search(r'#\s*define|typedef', fncall)):
  1239. error(filename, linenum, 'whitespace/parens', 4,
  1240. 'Extra space before ( in function call')
  1241. # If the ) is followed only by a newline or a { + newline, assume it's
  1242. # part of a control statement (if/while/etc), and don't complain
  1243. if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
  1244. error(filename, linenum, 'whitespace/parens', 2,
  1245. 'Extra space before )')
  1246. def IsBlankLine(line):
  1247. """Returns true if the given line is blank.
  1248. We consider a line to be blank if the line is empty or consists of
  1249. only white spaces.
  1250. Args:
  1251. line: A line of a string.
  1252. Returns:
  1253. True, if the given line is blank.
  1254. """
  1255. return not line or line.isspace()
  1256. def CheckForFunctionLengths(filename, clean_lines, linenum,
  1257. function_state, error):
  1258. """Reports for long function bodies.
  1259. For an overview why this is done, see:
  1260. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
  1261. Uses a simplistic algorithm assuming other style guidelines
  1262. (especially spacing) are followed.
  1263. Only checks unindented functions, so class members are unchecked.
  1264. Trivial bodies are unchecked, so constructors with huge initializer lists
  1265. may be missed.
  1266. Blank/comment lines are not counted so as to avoid encouraging the removal
  1267. of vertical space and commments just to get through a lint check.
  1268. NOLINT *on the last line of a function* disables this check.
  1269. Args:
  1270. filename: The name of the current file.
  1271. clean_lines: A CleansedLines instance containing the file.
  1272. linenum: The number of the line to check.
  1273. function_state: Current function name and lines in body so far.
  1274. error: The function to call with any errors found.
  1275. """
  1276. lines = clean_lines.lines
  1277. line = lines[linenum]
  1278. raw = clean_lines.raw_lines
  1279. raw_line = raw[linenum]
  1280. joined_line = ''
  1281. starting_func = False
  1282. regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
  1283. match_result = Match(regexp, line)
  1284. if match_result:
  1285. # If the name is all caps and underscores, figure it's a macro and
  1286. # ignore it, unless it's TEST or TEST_F.
  1287. function_name = match_result.group(1).split()[-1]
  1288. if function_name == 'TEST' or function_name == 'TEST_F' or (
  1289. not Match(r'[A-Z_]+$', function_name)):
  1290. starting_func = True
  1291. if starting_func:
  1292. body_found = False
  1293. for start_linenum in xrange(linenum, clean_lines.NumLines()):
  1294. start_line = lines[start_linenum]
  1295. joined_line += ' ' + start_line.lstrip()
  1296. if Search(r'(;|})', start_line): # Declarations and trivial functions
  1297. body_found = True
  1298. break # ... ignore
  1299. elif Search(r'{', start_line):
  1300. body_found = True
  1301. function = Search(r'((\w|:)*)\(', line).group(1)
  1302. if Match(r'TEST', function): # Handle TEST... macros
  1303. parameter_regexp = Search(r'(\(.*\))', joined_line)
  1304. if parameter_regexp: # Ignore bad syntax
  1305. function += parameter_regexp.group(1)
  1306. else:
  1307. function += '()'
  1308. function_state.Begin(function)
  1309. break
  1310. if not body_found:
  1311. # No body for the function (or evidence of a non-function) was found.
  1312. error(filename, linenum, 'readability/fn_size', 5,
  1313. 'Lint failed to find start of function body.')
  1314. elif Match(r'^\}\s*$', line): # function end
  1315. function_state.Check(error, filename, linenum)
  1316. function_state.End()
  1317. elif not Match(r'^\s*$', line):
  1318. function_state.Count() # Count non-blank/non-comment lines.
  1319. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
  1320. def CheckComment(comment, filename, linenum, error):
  1321. """Checks for common mistakes in TODO comments.
  1322. Args:
  1323. comment: The text of the comment from the line in question.
  1324. filename: The name of the current file.
  1325. linenum: The number of the line to check.
  1326. error: The function to call with any errors found.
  1327. """
  1328. match = _RE_PATTERN_TODO.match(comment)
  1329. if match:
  1330. # One whitespace is correct; zero whitespace is handled elsewhere.
  1331. leading_whitespace = match.group(1)
  1332. if len(leading_whitespace) > 1:
  1333. error(filename, linenum, 'whitespace/todo', 2,
  1334. 'Too many spaces before TODO')
  1335. username = match.group(2)
  1336. if not username:
  1337. error(filename, linenum, 'readability/todo', 2,
  1338. 'Missing username in TODO; it should look like '
  1339. '"// TODO(my_username): Stuff."')
  1340. middle_whitespace = match.group(3)
  1341. # Comparisons made explicit for correctness -- pylint: disable-msg=C6403
  1342. if middle_whitespace != ' ' and middle_whitespace != '':
  1343. error(filename, linenum, 'whitespace/todo', 2,
  1344. 'TODO(my_username) should be followed by a space')
  1345. def CheckSpacing(filename, clean_lines, linenum, error):
  1346. """Checks for the correctness of various spacing issues in the code.
  1347. Things we check for: spaces around operators, spaces after
  1348. if/for/while/switch, no spaces around parens in function calls, two
  1349. spaces between code and comment, don't start a block with a blank
  1350. line, don't end a function with a blank line, don't have too many
  1351. blank lines in a row.
  1352. Args:
  1353. filename: The name of the current file.
  1354. clean_lines: A CleansedLines instance containing the file.
  1355. linenum: The number of the line to check.
  1356. error: The function to call with any errors found.
  1357. """
  1358. raw = clean_lines.raw_lines
  1359. line = raw[linenum]
  1360. # Before nixing comments, check if the line is blank for no good
  1361. # reason. This includes the first line after a block is opened, and
  1362. # blank lines at the end of a function (ie, right before a line like '}'
  1363. if IsBlankLine(line):
  1364. elided = clean_lines.elided
  1365. prev_line = elided[linenum - 1]
  1366. prevbrace = prev_line.rfind('{')
  1367. # TODO(unknown): Don't complain if line before blank line, and line after,
  1368. # both start with alnums and are indented the same amount.
  1369. # This ignores whitespace at the start of a namespace block
  1370. # because those are not usually indented.
  1371. if (prevbrace != -1 and prev_line[prevbrace:].find('}') == -1
  1372. and prev_line[:prevbrace].find('namespace') == -1):
  1373. # OK, we have a blank line at the start of a code block. Before we
  1374. # complain, we check if it is an exception to the rule: The previous
  1375. # non-empty line has the paramters of a function header that are indented
  1376. # 4 spaces (because they did not fit in a 80 column line when placed on
  1377. # the same line as the function name). We also check for the case where
  1378. # the previous line is indented 6 spaces, which may happen when the
  1379. # initializers of a constructor do not fit into a 80 column line.
  1380. exception = False
  1381. if Match(r' {6}\w', prev_line): # Initializer list?
  1382. # We are looking for the opening column of initializer list, which
  1383. # should be indented 4 spaces to cause 6 space indentation afterwards.
  1384. search_position = linenum-2
  1385. while (search_position >= 0
  1386. and Match(r' {6}\w', elided[search_position])):
  1387. search_position -= 1
  1388. exception = (search_position >= 0
  1389. and elided[search_position][:5] == ' :')
  1390. else:
  1391. # Search for the function arguments or an initializer list. We use a
  1392. # simple heuristic here: If the line is indented 4 spaces; and we have a
  1393. # closing paren, without the opening paren, followed by an opening brace
  1394. # or colon (for initializer lists) we assume that it is the last line of
  1395. # a function header. If we have a colon indented 4 spaces, it is an
  1396. # initializer list.
  1397. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
  1398. prev_line)
  1399. or Match(r' {4}:', prev_line))
  1400. if not exception:
  1401. error(filename, linenum, 'whitespace/blank_line', 2,
  1402. 'Blank line at the start of a code block. Is this needed?')
  1403. # This doesn't ignore whitespace at the end of a namespace block
  1404. # because that is too hard without pairing open/close braces;
  1405. # however, a special exception is made for namespace closing
  1406. # brackets which have a comment containing "namespace".
  1407. #
  1408. # Also, ignore blank lines at the end of a block in a long if-else
  1409. # chain, like this:
  1410. # if (condition1) {
  1411. # // Something followed by a blank line
  1412. #
  1413. # } else if (condition2) {
  1414. # // Something else
  1415. # }
  1416. if linenum + 1 < clean_lines.NumLines():
  1417. next_line = raw[linenum + 1]
  1418. if (next_line
  1419. and Match(r'\s*}', next_line)
  1420. and next_line.find('namespace') == -1
  1421. and next_line.find('} else ') == -1):
  1422. error(filename, linenum, 'whitespace/blank_line', 3,
  1423. 'Blank line at the end of a code block. Is this needed?')
  1424. # Next, we complain if there's a comment too near the text
  1425. commentpos = line.find('//')
  1426. if commentpos != -1:
  1427. # Check if the // may be in quotes. If so, ignore it
  1428. # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
  1429. if (line.count('"', 0, commentpos) -
  1430. line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
  1431. # Allow one space for new scopes, two spaces otherwise:
  1432. if (not Match(r'^\s*{ //', line) and
  1433. ((commentpos >= 1 and
  1434. line[commentpos-1] not in string.whitespace) or
  1435. (commentpos >= 2 and
  1436. line[commentpos-2] not in string.whitespace))):
  1437. error(filename, linenum, 'whitespace/comments', 2,
  1438. 'At least two spaces is best between code and comments')
  1439. # There should always be a space between the // and the comment
  1440. commentend = commentpos + 2
  1441. if commentend < len(line) and not line[commentend] == ' ':
  1442. # but some lines are exceptions -- e.g. if they're big
  1443. # comment delimiters like:
  1444. # //----------------------------------------------------------
  1445. # or are an empty C++ style Doxygen comment, like:
  1446. # ///
  1447. # or they begin with multiple slashes followed by a space:
  1448. # //////// Header comment
  1449. match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
  1450. Search(r'^/$', line[commentend:]) or
  1451. Search(r'^/+ ', line[commentend:]))
  1452. if not match:
  1453. error(filename, linenum, 'whitespace/comments', 4,
  1454. 'Should have a space between // and comment')
  1455. CheckComment(line[commentpos:], filename, linenum, error)
  1456. line = clean_lines.elided[linenum] # get rid of comments and strings
  1457. # Don't try to do spacing checks for operator methods
  1458. line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
  1459. # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
  1460. # Otherwise not. Note we only check for non-spaces on *both* sides;
  1461. # sometimes people put non-spaces on one side when aligning ='s among
  1462. # many lines (not that this is behavior that I approve of...)
  1463. if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
  1464. error(filename, linenum, 'whitespace/operators', 4,
  1465. 'Missing spaces around =')
  1466. # It's ok not to have spaces around binary operators like + - * /, but if
  1467. # there's too little whitespace, we get concerned. It's hard to tell,
  1468. # though, so we punt on this one for now. TODO.
  1469. # You should always have whitespace around binary operators.
  1470. # Alas, we can't test < or > because they're legitimately used sans spaces
  1471. # (a->b, vector<int> a). The only time we can tell is a < with no >, and
  1472. # only if it's not template params list spilling into the next line.
  1473. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
  1474. if not match:
  1475. # Note that while it seems that the '<[^<]*' term in the following
  1476. # regexp could be simplified to '<.*', which would indeed match
  1477. # the same class of strings, the [^<] means that searching for the
  1478. # regexp takes linear rather than quadratic time.
  1479. if not Search(r'<[^<]*,\s*$', line): # template params spill
  1480. match = Search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line)
  1481. if match:
  1482. error(filename, linenum, 'whitespace/operators', 3,
  1483. 'Missing spaces around %s' % match.group(1))
  1484. # We allow no-spaces around << and >> when used like this: 10<<20, but
  1485. # not otherwise (particularly, not when used as streams)
  1486. match = Search(r'[^0-9\s](<<|>>)[^0-9\s]', line)
  1487. if match:
  1488. error(filename, linenum, 'whitespace/operators', 3,
  1489. 'Missing spaces around %s' % match.group(1))
  1490. # There shouldn't be space around unary operators
  1491. match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
  1492. if match:
  1493. error(filename, linenum, 'whitespace/operators', 4,
  1494. 'Extra space for operator %s' % match.group(1))
  1495. # A pet peeve of mine: no spaces after an if, while, switch, or for
  1496. match = Search(r' (if\(|for\(|while\(|switch\()', line)
  1497. if match:
  1498. error(filename, linenum, 'whitespace/parens', 5,
  1499. 'Missing space before ( in %s' % match.group(1))
  1500. # For if/for/while/switch, the left and right parens should be
  1501. # consistent about how many spaces are inside the parens, and
  1502. # there should either be zero or one spaces inside the parens.
  1503. # We don't want: "if ( foo)" or "if ( foo )".
  1504. # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  1505. match = Search(r'\b(if|for|while|switch)\s*'
  1506. r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
  1507. line)
  1508. if match:
  1509. if len(match.group(2)) != len(match.group(4)):
  1510. if not (match.group(3) == ';' and
  1511. len(match.group(2)) == 1 + len(match.group(4)) or
  1512. not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
  1513. error(filename, linenum, 'whitespace/parens', 5,
  1514. 'Mismatching spaces inside () in %s' % match.group(1))
  1515. if not len(match.group(2)) in [0, 1]:
  1516. error(filename, linenum, 'whitespace/parens', 5,
  1517. 'Should have zero or one spaces inside ( and ) in %s' %
  1518. match.group(1))
  1519. # You should always have a space after a comma (either as fn arg or operator)
  1520. if Search(r',[^\s]', line):
  1521. error(filename, linenum, 'whitespace/comma', 3,
  1522. 'Missing space after ,')
  1523. # Next we will look for issues with function calls.
  1524. CheckSpacingForFunctionCall(filename, line, linenum, error)
  1525. # Except after an opening paren, you should have spaces before your braces.
  1526. # And since you should never have braces at the beginning of a line, this is
  1527. # an easy test.
  1528. if Search(r'[^ (]{', line):
  1529. error(filename, linenum, 'whitespace/braces', 5,
  1530. 'Missing space before {')
  1531. # Make sure '} else {' has spaces.
  1532. if Search(r'}else', line):
  1533. error(filename, linenum, 'whitespace/braces', 5,
  1534. 'Missing space before else')
  1535. # You shouldn't have spaces before your brackets, except maybe after
  1536. # 'delete []' or 'new char * []'.
  1537. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
  1538. error(filename, linenum, 'whitespace/braces', 5,
  1539. 'Extra space before [')
  1540. # You shouldn't have a space before a semicolon at the end of the line.
  1541. # There's a special case for "for" since the style guide allows space before
  1542. # the semicolon there.
  1543. if Search(r':\s*;\s*$', line):
  1544. error(filename, linenum, 'whitespace/semicolon', 5,
  1545. 'Semicolon defining empty statement. Use { } instead.')
  1546. elif Search(r'^\s*;\s*$', line):
  1547. error(filename, linenum, 'whitespace/semicolon', 5,
  1548. 'Line contains only semicolon. If this should be an empty statement, '
  1549. 'use { } instead.')
  1550. elif (Search(r'\s+;\s*$', line) and
  1551. not Search(r'\bfor\b', line)):
  1552. error(filename, linenum, 'whitespace/semicolon', 5,
  1553. 'Extra space before last semicolon. If this should be an empty '
  1554. 'statement, use { } instead.')
  1555. def GetPreviousNonBlankLine(clean_lines, linenum):
  1556. """Return the most recent non-blank line and its line number.
  1557. Args:
  1558. clean_lines: A CleansedLines instance containing the file contents.
  1559. linenum: The number of the line to check.
  1560. Returns:
  1561. A tuple with two elements. The first element is the contents of the last
  1562. non-blank line before the current line, or the empty string if this is the
  1563. first non-blank line. The second is the line number of that line, or -1
  1564. if this is the first non-blank line.
  1565. """
  1566. prevlinenum = linenum - 1
  1567. while prevlinenum >= 0:
  1568. prevline = clean_lines.elided[prevlinenum]
  1569. if not IsBlankLine(prevline): # if not a blank line...
  1570. return (prevline, prevlinenum)
  1571. prevlinenum -= 1
  1572. return ('', -1)
  1573. def CheckBraces(filename, clean_lines, linenum, error):
  1574. """Looks for misplaced braces (e.g. at the end of line).
  1575. Args:
  1576. filename: The name of the current file.
  1577. clean_lines: A CleansedLines instance containing the file.
  1578. linenum: The number of the line to check.
  1579. error: The function to call with any errors found.
  1580. """
  1581. line = clean_lines.elided[linenum] # get rid of comments and strings
  1582. if Match(r'\s*{\s*$', line):
  1583. # We allow an open brace to start a line in the case where someone
  1584. # is using braces in a block to explicitly create a new scope,
  1585. # which is commonly used to control the lifetime of
  1586. # stack-allocated variables. We don't detect this perfectly: we
  1587. # just don't complain if the last non-whitespace character on the
  1588. # previous non-blank line is ';', ':', '{', or '}'.
  1589. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  1590. if not Search(r'[;:}{]\s*$', prevline):
  1591. error(filename, linenum, 'whitespace/braces', 4,
  1592. '{ should almost always be at the end of the previous line')
  1593. # An else clause should be on the same line as the preceding closing brace.
  1594. if Match(r'\s*else\s*', line):
  1595. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  1596. if Match(r'\s*}\s*$', prevline):
  1597. error(filename, linenum, 'whitespace/newline', 4,
  1598. 'An else should appear on the same line as the preceding }')
  1599. # If braces come on one side of an else, they should be on both.
  1600. # However, we have to worry about "else if" that spans multiple lines!
  1601. if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
  1602. if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
  1603. # find the ( after the if
  1604. pos = line.find('else if')
  1605. pos = line.find('(', pos)
  1606. if pos > 0:
  1607. (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
  1608. if endline[endpos:].find('{') == -1: # must be brace after if
  1609. error(filename, linenum, 'readability/braces', 5,
  1610. 'If an else has a brace on one side, it should have it on both')
  1611. else: # common case: else not followed by a multi-line if
  1612. error(filename, linenum, 'readability/braces', 5,
  1613. 'If an else has a brace on one side, it should have it on both')
  1614. # Likewise, an else should never have the else clause on the same line
  1615. if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
  1616. error(filename, linenum, 'whitespace/newline', 4,
  1617. 'Else clause should never be on same line as else (use 2 lines)')
  1618. # In the same way, a do/while should never be on one line
  1619. if Match(r'\s*do [^\s{]', line):
  1620. error(filename, linenum, 'whitespace/newline', 4,
  1621. 'do/while clauses should not be on a single line')
  1622. # Braces shouldn't be followed by a ; unless they're defining a struct
  1623. # or initializing an array.
  1624. # We can't tell in general, but we can for some common cases.
  1625. prevlinenum = linenum
  1626. while True:
  1627. (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum)
  1628. if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'):
  1629. line = prevline + line
  1630. else:
  1631. break
  1632. if (Search(r'{.*}\s*;', line) and
  1633. line.count('{') == line.count('}') and
  1634. not Search(r'struct|class|enum|\s*=\s*{', line)):
  1635. error(filename, linenum, 'readability/braces', 4,
  1636. "You don't need a ; after a }")
  1637. def ReplaceableCheck(operator, macro, line):
  1638. """Determine whether a basic CHECK can be replaced with a more specific one.
  1639. For example suggest using CHECK_EQ instead of CHECK(a == b) and
  1640. similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE.
  1641. Args:
  1642. operator: The C++ operator used in the CHECK.
  1643. macro: The CHECK or EXPECT macro being called.
  1644. line: The current source line.
  1645. Returns:
  1646. True if the CHECK can be replaced with a more specific one.
  1647. """
  1648. # This matches decimal and hex integers, strings, and chars (in that order).
  1649. match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')'
  1650. # Expression to match two sides of the operator with something that
  1651. # looks like a literal, since CHECK(x == iterator) won't compile.
  1652. # This means we can't catch all the cases where a more specific
  1653. # CHECK is possible, but it's less annoying than dealing with
  1654. # extraneous warnings.
  1655. match_this = (r'\s*' + macro + r'\((\s*' +
  1656. match_constant + r'\s*' + operator + r'[^<>].*|'
  1657. r'.*[^<>]' + operator + r'\s*' + match_constant +
  1658. r'\s*\))')
  1659. # Don't complain about CHECK(x == NULL) or similar because
  1660. # CHECK_EQ(x, NULL) won't compile (requires a cast).
  1661. # Also, don't complain about more complex boolean expressions
  1662. # involving && or || such as CHECK(a == b || c == d).
  1663. return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line)
  1664. def CheckCheck(filename, clean_lines, linenum, error):
  1665. """Checks the use of CHECK and EXPECT macros.
  1666. Args:
  1667. filename: The name of the current file.
  1668. clean_lines: A CleansedLines instance containing the file.
  1669. linenum: The number of the line to check.
  1670. error: The function to call with any errors found.
  1671. """
  1672. # Decide the set of replacement macros that should be suggested
  1673. raw_lines = clean_lines.raw_lines
  1674. current_macro = ''
  1675. for macro in _CHECK_MACROS:
  1676. if raw_lines[linenum].find(macro) >= 0:
  1677. current_macro = macro
  1678. break
  1679. if not current_macro:
  1680. # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
  1681. return
  1682. line = clean_lines.elided[linenum] # get rid of comments and strings
  1683. # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc.
  1684. for operator in ['==', '!=', '>=', '>', '<=', '<']:
  1685. if ReplaceableCheck(operator, current_macro, line):
  1686. error(filename, linenum, 'readability/check', 2,
  1687. 'Consider using %s instead of %s(a %s b)' % (
  1688. _CHECK_REPLACEMENT[current_macro][operator],
  1689. current_macro, operator))
  1690. break
  1691. def GetLineWidth(line):
  1692. """Determines the width of the line in column positions.
  1693. Args:
  1694. line: A string, which may be a Unicode string.
  1695. Returns:
  1696. The width of the line in column positions, accounting for Unicode
  1697. combining characters and wide characters.
  1698. """
  1699. if isinstance(line, unicode):
  1700. width = 0
  1701. for c in unicodedata.normalize('NFC', line):
  1702. if unicodedata.east_asian_width(c) in ('W', 'F'):
  1703. width += 2
  1704. elif not unicodedata.combining(c):
  1705. width += 1
  1706. return width
  1707. else:
  1708. return len(line)
  1709. def CheckStyle(filename, clean_lines, linenum, file_extension, error):
  1710. """Checks rules from the 'C++ style rules' section of cppguide.html.
  1711. Most of these rules are hard to test (naming, comment style), but we
  1712. do what we can. In particular we check for 2-space indents, line lengths,
  1713. tab usage, spaces inside code, etc.
  1714. Args:
  1715. filename: The name of the current file.
  1716. clean_lines: A CleansedLines instance containing the file.
  1717. linenum: The number of the line to check.
  1718. file_extension: The extension (without the dot) of the filename.
  1719. error: The function to call with any errors found.
  1720. """
  1721. raw_lines = clean_lines.raw_lines
  1722. line = raw_lines[linenum]
  1723. if line.find('\t') != -1:
  1724. error(filename, linenum, 'whitespace/tab', 1,
  1725. 'Tab found; better to use spaces')
  1726. # One or three blank spaces at the beginning of the line is weird; it's
  1727. # hard to reconcile that with 2-space indents.
  1728. # NOTE: here are the conditions rob pike used for his tests. Mine aren't
  1729. # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
  1730. # if(RLENGTH > 20) complain = 0;
  1731. # if(match($0, " +(error|private|public|protected):")) complain = 0;
  1732. # if(match(prev, "&& *$")) complain = 0;
  1733. # if(match(prev, "\\|\\| *$")) complain = 0;
  1734. # if(match(prev, "[\",=><] *$")) complain = 0;
  1735. # if(match($0, " <<")) complain = 0;
  1736. # if(match(prev, " +for \\(")) complain = 0;
  1737. # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
  1738. initial_spaces = 0
  1739. cleansed_line = clean_lines.elided[linenum]
  1740. while initial_spaces < len(line) and line[initial_spaces] == ' ':
  1741. initial_spaces += 1
  1742. if line and line[-1].isspace():
  1743. error(filename, linenum, 'whitespace/end_of_line', 4,
  1744. 'Line ends in whitespace. Consider deleting these extra spaces.')
  1745. # There are certain situations we allow one space, notably for labels
  1746. elif ((initial_spaces == 1 or initial_spaces == 3) and
  1747. not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
  1748. error(filename, linenum, 'whitespace/indent', 3,
  1749. 'Weird number of spaces at line-start. '
  1750. 'Are you using a 2-space indent?')
  1751. # Labels should always be indented at least one space.
  1752. elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$',
  1753. line):
  1754. error(filename, linenum, 'whitespace/labels', 4,
  1755. 'Labels should always be indented at least one space. '
  1756. 'If this is a member-initializer list in a constructor or '
  1757. 'the base class list in a class definition, the colon should '
  1758. 'be on the following line.')
  1759. # Check if the line is a header guard.
  1760. is_header_guard = False
  1761. if file_extension == 'h':
  1762. cppvar = GetHeaderGuardCPPVariable(filename)
  1763. if (line.startswith('#ifndef %s' % cppvar) or
  1764. line.startswith('#define %s' % cppvar) or
  1765. line.startswith('#endif // %s' % cppvar)):
  1766. is_header_guard = True
  1767. # #include lines and header guards can be long, since there's no clean way to
  1768. # split them.
  1769. #
  1770. # URLs can be long too. It's possible to split these, but it makes them
  1771. # harder to cut&paste.
  1772. if (not line.startswith('#include') and not is_header_guard and
  1773. not Match(r'^\s*//.*http(s?)://\S*$', line)):
  1774. line_width = GetLineWidth(line)
  1775. if line_width > 100:
  1776. error(filename, linenum, 'whitespace/line_length', 4,
  1777. 'Lines should very rarely be longer than 100 characters')
  1778. elif line_width > 80:
  1779. error(filename, linenum, 'whitespace/line_length', 2,
  1780. 'Lines should be <= 80 characters long')
  1781. if (cleansed_line.count(';') > 1 and
  1782. # for loops are allowed two ;'s (and may run over two lines).
  1783. cleansed_line.find('for') == -1 and
  1784. (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
  1785. GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
  1786. # It's ok to have many commands in a switch case that fits in 1 line
  1787. not ((cleansed_line.find('case ') != -1 or
  1788. cleansed_line.find('default:') != -1) and
  1789. cleansed_line.find('break;') != -1)):
  1790. error(filename, linenum, 'whitespace/newline', 4,
  1791. 'More than one command on the same line')
  1792. # Some more style checks
  1793. CheckBraces(filename, clean_lines, linenum, error)
  1794. CheckSpacing(filename, clean_lines, linenum, error)
  1795. CheckCheck(filename, clean_lines, linenum, error)
  1796. _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
  1797. _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
  1798. # Matches the first component of a filename delimited by -s and _s. That is:
  1799. # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
  1800. # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
  1801. # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
  1802. # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
  1803. _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
  1804. def _DropCommonSuffixes(filename):
  1805. """Drops common suffixes like _test.cc or -inl.h from filename.
  1806. For example:
  1807. >>> _DropCommonSuffixes('foo/foo-inl.h')
  1808. 'foo/foo'
  1809. >>> _DropCommonSuffixes('foo/bar/foo.cc')
  1810. 'foo/bar/foo'
  1811. >>> _DropCommonSuffixes('foo/foo_internal.h')
  1812. 'foo/foo'
  1813. >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
  1814. 'foo/foo_unusualinternal'
  1815. Args:
  1816. filename: The input filename.
  1817. Returns:
  1818. The filename with the common suffix removed.
  1819. """
  1820. for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
  1821. 'inl.h', 'impl.h', 'internal.h'):
  1822. if (filename.endswith(suffix) and len(filename) > len(suffix) and
  1823. filename[-len(suffix) - 1] in ('-', '_')):
  1824. return filename[:-len(suffix) - 1]
  1825. return os.path.splitext(filename)[0]
  1826. def _IsTestFilename(filename):
  1827. """Determines if the given filename has a suffix that identifies it as a test.
  1828. Args:
  1829. filename: The input filename.
  1830. Returns:
  1831. True if 'filename' looks like a test, False otherwise.
  1832. """
  1833. if (filename.endswith('_test.cc') or
  1834. filename.endswith('_unittest.cc') or
  1835. filename.endswith('_regtest.cc')):
  1836. return True
  1837. else:
  1838. return False
  1839. def _ClassifyInclude(fileinfo, include, is_system):
  1840. """Figures out what kind of header 'include' is.
  1841. Args:
  1842. fileinfo: The current file cpplint is running over. A FileInfo instance.
  1843. include: The path to a #included file.
  1844. is_system: True if the #include used <> rather than "".
  1845. Returns:
  1846. One of the _XXX_HEADER constants.
  1847. For example:
  1848. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
  1849. _C_SYS_HEADER
  1850. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
  1851. _CPP_SYS_HEADER
  1852. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
  1853. _LIKELY_MY_HEADER
  1854. >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
  1855. ... 'bar/foo_other_ext.h', False)
  1856. _POSSIBLE_MY_HEADER
  1857. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
  1858. _OTHER_HEADER
  1859. """
  1860. # This is a list of all standard c++ header files, except
  1861. # those already checked for above.
  1862. is_stl_h = include in _STL_HEADERS
  1863. is_cpp_h = is_stl_h or include in _CPP_HEADERS
  1864. if is_system:
  1865. if is_cpp_h:
  1866. return _CPP_SYS_HEADER
  1867. else:
  1868. return _C_SYS_HEADER
  1869. # If the target file and the include we're checking share a
  1870. # basename when we drop common extensions, and the include
  1871. # lives in . , then it's likely to be owned by the target file.
  1872. target_dir, target_base = (
  1873. os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
  1874. include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
  1875. if target_base == include_base and (
  1876. include_dir == target_dir or
  1877. include_dir == os.path.normpath(target_dir + '/../public')):
  1878. return _LIKELY_MY_HEADER
  1879. # If the target and include share some initial basename
  1880. # component, it's possible the target is implementing the
  1881. # include, so it's allowed to be first, but we'll never
  1882. # complain if it's not there.
  1883. target_first_component = _RE_FIRST_COMPONENT.match(target_base)
  1884. include_first_component = _RE_FIRST_COMPONENT.match(include_base)
  1885. if (target_first_component and include_first_component and
  1886. target_first_component.group(0) ==
  1887. include_first_component.group(0)):
  1888. return _POSSIBLE_MY_HEADER
  1889. return _OTHER_HEADER
  1890. def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
  1891. """Check rules that are applicable to #include lines.
  1892. Strings on #include lines are NOT removed from elided line, to make
  1893. certain tasks easier. However, to prevent false positives, checks
  1894. applicable to #include lines in CheckLanguage must be put here.
  1895. Args:
  1896. filename: The name of the current file.
  1897. clean_lines: A CleansedLines instance containing the file.
  1898. linenum: The number of the line to check.
  1899. include_state: An _IncludeState instance in which the headers are inserted.
  1900. error: The function to call with any errors found.
  1901. """
  1902. fileinfo = FileInfo(filename)
  1903. line = clean_lines.lines[linenum]
  1904. # "include" should use the new style "foo/bar.h" instead of just "bar.h"
  1905. if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
  1906. error(filename, linenum, 'build/include', 4,
  1907. 'Include the directory when naming .h files')
  1908. # we shouldn't include a file more than once. actually, there are a
  1909. # handful of instances where doing so is okay, but in general it's
  1910. # not.
  1911. match = _RE_PATTERN_INCLUDE.search(line)
  1912. if match:
  1913. include = match.group(2)
  1914. is_system = (match.group(1) == '<')
  1915. if include in include_state:
  1916. error(filename, linenum, 'build/include', 4,
  1917. '"%s" already included at %s:%s' %
  1918. (include, filename, include_state[include]))
  1919. else:
  1920. include_state[include] = linenum
  1921. # We want to ensure that headers appear in the right order:
  1922. # 1) for foo.cc, foo.h (preferred location)
  1923. # 2) c system files
  1924. # 3) cpp system files
  1925. # 4) for foo.cc, foo.h (deprecated location)
  1926. # 5) other google headers
  1927. #
  1928. # We classify each include statement as one of those 5 types
  1929. # using a number of techniques. The include_state object keeps
  1930. # track of the highest type seen, and complains if we see a
  1931. # lower type after that.
  1932. error_message = include_state.CheckNextIncludeOrder(
  1933. _ClassifyInclude(fileinfo, include, is_system))
  1934. if error_message:
  1935. error(filename, linenum, 'build/include_order', 4,
  1936. '%s. Should be: %s.h, c system, c++ system, other.' %
  1937. (error_message, fileinfo.BaseName()))
  1938. if not include_state.IsInAlphabeticalOrder(include):
  1939. error(filename, linenum, 'build/include_alpha', 4,
  1940. 'Include "%s" not in alphabetical order' % include)
  1941. # Look for any of the stream classes that are part of standard C++.
  1942. match = _RE_PATTERN_INCLUDE.match(line)
  1943. if match:
  1944. include = match.group(2)
  1945. if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
  1946. # Many unit tests use cout, so we exempt them.
  1947. if not _IsTestFilename(filename):
  1948. error(filename, linenum, 'readability/streams', 3,
  1949. 'Streams are highly discouraged.')
  1950. def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state,
  1951. error):
  1952. """Checks rules from the 'C++ language rules' section of cppguide.html.
  1953. Some of these rules are hard to test (function overloading, using
  1954. uint32 inappropriately), but we do the best we can.
  1955. Args:
  1956. filename: The name of the current file.
  1957. clean_lines: A CleansedLines instance containing the file.
  1958. linenum: The number of the line to check.
  1959. file_extension: The extension (without the dot) of the filename.
  1960. include_state: An _IncludeState instance in which the headers are inserted.
  1961. error: The function to call with any errors found.
  1962. """
  1963. # If the line is empty or consists of entirely a comment, no need to
  1964. # check it.
  1965. line = clean_lines.elided[linenum]
  1966. if not line:
  1967. return
  1968. match = _RE_PATTERN_INCLUDE.search(line)
  1969. if match:
  1970. CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
  1971. return
  1972. # Create an extended_line, which is the concatenation of the current and
  1973. # next lines, for more effective checking of code that may span more than one
  1974. # line.
  1975. if linenum + 1 < clean_lines.NumLines():
  1976. extended_line = line + clean_lines.elided[linenum + 1]
  1977. else:
  1978. extended_line = line
  1979. # Make Windows paths like Unix.
  1980. fullname = os.path.abspath(filename).replace('\\', '/')
  1981. # TODO(unknown): figure out if they're using default arguments in fn proto.
  1982. # Check for non-const references in functions. This is tricky because &
  1983. # is also used to take the address of something. We allow <> for templates,
  1984. # (ignoring whatever is between the braces) and : for classes.
  1985. # These are complicated re's. They try to capture the following:
  1986. # paren (for fn-prototype start), typename, &, varname. For the const
  1987. # version, we're willing for const to be before typename or after
  1988. # Don't check the implemention on same line.
  1989. fnline = line.split('{', 1)[0]
  1990. if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) >
  1991. len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?'
  1992. r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) +
  1993. len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+',
  1994. fnline))):
  1995. # We allow non-const references in a few standard places, like functions
  1996. # called "swap()" or iostream operators like "<<" or ">>".
  1997. if not Search(
  1998. r'(swap|Swap|operator[<>][<>])\s*\(\s*(?:[\w:]|<.*>)+\s*&',
  1999. fnline):
  2000. error(filename, linenum, 'runtime/references', 2,
  2001. 'Is this a non-const reference? '
  2002. 'If so, make const or use a pointer.')
  2003. # Check to see if they're using an conversion function cast.
  2004. # I just try to capture the most common basic types, though there are more.
  2005. # Parameterless conversion functions, such as bool(), are allowed as they are
  2006. # probably a member operator declaration or default constructor.
  2007. match = Search(
  2008. r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
  2009. r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line)
  2010. if match:
  2011. # gMock methods are defined using some variant of MOCK_METHODx(name, type)
  2012. # where type may be float(), int(string), etc. Without context they are
  2013. # virtually indistinguishable from int(x) casts.
  2014. if (match.group(1) is None and # If new operator, then this isn't a cast
  2015. not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line)):
  2016. error(filename, linenum, 'readability/casting', 4,
  2017. 'Using deprecated casting style. '
  2018. 'Use static_cast<%s>(...) instead' %
  2019. match.group(2))
  2020. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  2021. 'static_cast',
  2022. r'\((int|float|double|bool|char|u?int(16|32|64))\)',
  2023. error)
  2024. # This doesn't catch all cases. Consider (const char * const)"hello".
  2025. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  2026. 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
  2027. # In addition, we look for people taking the address of a cast. This
  2028. # is dangerous -- casts can assign to temporaries, so the pointer doesn't
  2029. # point where you think.
  2030. if Search(
  2031. r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line):
  2032. error(filename, linenum, 'runtime/casting', 4,
  2033. ('Are you taking an address of a cast? '
  2034. 'This is dangerous: could be a temp var. '
  2035. 'Take the address before doing the cast, rather than after'))
  2036. # Check for people declaring static/global STL strings at the top level.
  2037. # This is dangerous because the C++ language does not guarantee that
  2038. # globals with constructors are initialized before the first access.
  2039. match = Match(
  2040. r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
  2041. line)
  2042. # Make sure it's not a function.
  2043. # Function template specialization looks like: "string foo<Type>(...".
  2044. # Class template definitions look like: "string Foo<Type>::Method(...".
  2045. if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)',
  2046. match.group(3)):
  2047. error(filename, linenum, 'runtime/string', 4,
  2048. 'For a static/global string constant, use a C style string instead: '
  2049. '"%schar %s[]".' %
  2050. (match.group(1), match.group(2)))
  2051. # Check that we're not using RTTI outside of testing code.
  2052. if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename):
  2053. error(filename, linenum, 'runtime/rtti', 5,
  2054. 'Do not use dynamic_cast<>. If you need to cast within a class '
  2055. "hierarchy, use static_cast<> to upcast. Google doesn't support "
  2056. 'RTTI.')
  2057. if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
  2058. error(filename, linenum, 'runtime/init', 4,
  2059. 'You seem to be initializing a member variable with itself.')
  2060. if file_extension == 'h':
  2061. # TODO(unknown): check that 1-arg constructors are explicit.
  2062. # How to tell it's a constructor?
  2063. # (handled in CheckForNonStandardConstructs for now)
  2064. # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
  2065. # (level 1 error)
  2066. pass
  2067. # Check if people are using the verboten C basic types. The only exception
  2068. # we regularly allow is "unsigned short port" for port.
  2069. if Search(r'\bshort port\b', line):
  2070. if not Search(r'\bunsigned short port\b', line):
  2071. error(filename, linenum, 'runtime/int', 4,
  2072. 'Use "unsigned short" for ports, not "short"')
  2073. else:
  2074. match = Search(r'\b(short|long(?! +double)|long long)\b', line)
  2075. if match:
  2076. error(filename, linenum, 'runtime/int', 4,
  2077. 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
  2078. # When snprintf is used, the second argument shouldn't be a literal.
  2079. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
  2080. if match and match.group(2) != '0':
  2081. # If 2nd arg is zero, snprintf is used to calculate size.
  2082. error(filename, linenum, 'runtime/printf', 3,
  2083. 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
  2084. 'to snprintf.' % (match.group(1), match.group(2)))
  2085. # Check if some verboten C functions are being used.
  2086. if Search(r'\bsprintf\b', line):
  2087. error(filename, linenum, 'runtime/printf', 5,
  2088. 'Never use sprintf. Use snprintf instead.')
  2089. match = Search(r'\b(strcpy|strcat)\b', line)
  2090. if match:
  2091. error(filename, linenum, 'runtime/printf', 4,
  2092. 'Almost always, snprintf is better than %s' % match.group(1))
  2093. if Search(r'\bsscanf\b', line):
  2094. error(filename, linenum, 'runtime/printf', 1,
  2095. 'sscanf can be ok, but is slow and can overflow buffers.')
  2096. # Check if some verboten operator overloading is going on
  2097. # TODO(unknown): catch out-of-line unary operator&:
  2098. # class X {};
  2099. # int operator&(const X& x) { return 42; } // unary operator&
  2100. # The trick is it's hard to tell apart from binary operator&:
  2101. # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
  2102. if Search(r'\boperator\s*&\s*\(\s*\)', line):
  2103. error(filename, linenum, 'runtime/operator', 4,
  2104. 'Unary operator& is dangerous. Do not use it.')
  2105. # Check for suspicious usage of "if" like
  2106. # } if (a == b) {
  2107. if Search(r'\}\s*if\s*\(', line):
  2108. error(filename, linenum, 'readability/braces', 4,
  2109. 'Did you mean "else if"? If not, start a new line for "if".')
  2110. # Check for potential format string bugs like printf(foo).
  2111. # We constrain the pattern not to pick things like DocidForPrintf(foo).
  2112. # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
  2113. match = re.search(r'\b((?:string)?printf)\s*\(([\w.\->()]+)\)', line, re.I)
  2114. if match:
  2115. error(filename, linenum, 'runtime/printf', 4,
  2116. 'Potential format string bug. Do %s("%%s", %s) instead.'
  2117. % (match.group(1), match.group(2)))
  2118. # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
  2119. match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
  2120. if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
  2121. error(filename, linenum, 'runtime/memset', 4,
  2122. 'Did you mean "memset(%s, 0, %s)"?'
  2123. % (match.group(1), match.group(2)))
  2124. if Search(r'\busing namespace\b', line):
  2125. error(filename, linenum, 'build/namespaces', 5,
  2126. 'Do not use namespace using-directives. '
  2127. 'Use using-declarations instead.')
  2128. # Detect variable-length arrays.
  2129. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
  2130. if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
  2131. match.group(3).find(']') == -1):
  2132. # Split the size using space and arithmetic operators as delimiters.
  2133. # If any of the resulting tokens are not compile time constants then
  2134. # report the error.
  2135. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
  2136. is_const = True
  2137. skip_next = False
  2138. for tok in tokens:
  2139. if skip_next:
  2140. skip_next = False
  2141. continue
  2142. if Search(r'sizeof\(.+\)', tok): continue
  2143. if Search(r'arraysize\(\w+\)', tok): continue
  2144. tok = tok.lstrip('(')
  2145. tok = tok.rstrip(')')
  2146. if not tok: continue
  2147. if Match(r'\d+', tok): continue
  2148. if Match(r'0[xX][0-9a-fA-F]+', tok): continue
  2149. if Match(r'k[A-Z0-9]\w*', tok): continue
  2150. if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
  2151. if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
  2152. # A catch all for tricky sizeof cases, including 'sizeof expression',
  2153. # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
  2154. # requires skipping the next token becasue we split on ' ' and '*'.
  2155. if tok.startswith('sizeof'):
  2156. skip_next = True
  2157. continue
  2158. is_const = False
  2159. break
  2160. if not is_const:
  2161. error(filename, linenum, 'runtime/arrays', 1,
  2162. 'Do not use variable-length arrays. Use an appropriately named '
  2163. "('k' followed by CamelCase) compile-time constant for the size.")
  2164. # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
  2165. # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
  2166. # in the class declaration.
  2167. match = Match(
  2168. (r'\s*'
  2169. r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
  2170. r'\(.*\);$'),
  2171. line)
  2172. if match and linenum + 1 < clean_lines.NumLines():
  2173. next_line = clean_lines.elided[linenum + 1]
  2174. if not Search(r'^\s*};', next_line):
  2175. error(filename, linenum, 'readability/constructors', 3,
  2176. match.group(1) + ' should be the last thing in the class')
  2177. # Check for use of unnamed namespaces in header files. Registration
  2178. # macros are typically OK, so we allow use of "namespace {" on lines
  2179. # that end with backslashes.
  2180. if (file_extension == 'h'
  2181. and Search(r'\bnamespace\s*{', line)
  2182. and line[-1] != '\\'):
  2183. error(filename, linenum, 'build/namespaces', 4,
  2184. 'Do not use unnamed namespaces in header files. See '
  2185. 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
  2186. ' for more information.')
  2187. def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
  2188. error):
  2189. """Checks for a C-style cast by looking for the pattern.
  2190. This also handles sizeof(type) warnings, due to similarity of content.
  2191. Args:
  2192. filename: The name of the current file.
  2193. linenum: The number of the line to check.
  2194. line: The line of code to check.
  2195. raw_line: The raw line of code to check, with comments.
  2196. cast_type: The string for the C++ cast to recommend. This is either
  2197. reinterpret_cast or static_cast, depending.
  2198. pattern: The regular expression used to find C-style casts.
  2199. error: The function to call with any errors found.
  2200. """
  2201. match = Search(pattern, line)
  2202. if not match:
  2203. return
  2204. # e.g., sizeof(int)
  2205. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
  2206. if sizeof_match:
  2207. error(filename, linenum, 'runtime/sizeof', 1,
  2208. 'Using sizeof(type). Use sizeof(varname) instead if possible')
  2209. return
  2210. remainder = line[match.end(0):]
  2211. # The close paren is for function pointers as arguments to a function.
  2212. # eg, void foo(void (*bar)(int));
  2213. # The semicolon check is a more basic function check; also possibly a
  2214. # function pointer typedef.
  2215. # eg, void foo(int); or void foo(int) const;
  2216. # The equals check is for function pointer assignment.
  2217. # eg, void *(*foo)(int) = ...
  2218. #
  2219. # Right now, this will only catch cases where there's a single argument, and
  2220. # it's unnamed. It should probably be expanded to check for multiple
  2221. # arguments with some unnamed.
  2222. function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)))', remainder)
  2223. if function_match:
  2224. if (not function_match.group(3) or
  2225. function_match.group(3) == ';' or
  2226. raw_line.find('/*') < 0):
  2227. error(filename, linenum, 'readability/function', 3,
  2228. 'All parameters should be named in a function')
  2229. return
  2230. # At this point, all that should be left is actual casts.
  2231. error(filename, linenum, 'readability/casting', 4,
  2232. 'Using C-style cast. Use %s<%s>(...) instead' %
  2233. (cast_type, match.group(1)))
  2234. _HEADERS_CONTAINING_TEMPLATES = (
  2235. ('<deque>', ('deque',)),
  2236. ('<functional>', ('unary_function', 'binary_function',
  2237. 'plus', 'minus', 'multiplies', 'divides', 'modulus',
  2238. 'negate',
  2239. 'equal_to', 'not_equal_to', 'greater', 'less',
  2240. 'greater_equal', 'less_equal',
  2241. 'logical_and', 'logical_or', 'logical_not',
  2242. 'unary_negate', 'not1', 'binary_negate', 'not2',
  2243. 'bind1st', 'bind2nd',
  2244. 'pointer_to_unary_function',
  2245. 'pointer_to_binary_function',
  2246. 'ptr_fun',
  2247. 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
  2248. 'mem_fun_ref_t',
  2249. 'const_mem_fun_t', 'const_mem_fun1_t',
  2250. 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
  2251. 'mem_fun_ref',
  2252. )),
  2253. ('<limits>', ('numeric_limits',)),
  2254. ('<list>', ('list',)),
  2255. ('<map>', ('map', 'multimap',)),
  2256. ('<memory>', ('allocator',)),
  2257. ('<queue>', ('queue', 'priority_queue',)),
  2258. ('<set>', ('set', 'multiset',)),
  2259. ('<stack>', ('stack',)),
  2260. ('<string>', ('char_traits', 'basic_string',)),
  2261. ('<utility>', ('pair',)),
  2262. ('<vector>', ('vector',)),
  2263. # gcc extensions.
  2264. # Note: std::hash is their hash, ::hash is our hash
  2265. ('<hash_map>', ('hash_map', 'hash_multimap',)),
  2266. ('<hash_set>', ('hash_set', 'hash_multiset',)),
  2267. ('<slist>', ('slist',)),
  2268. )
  2269. _HEADERS_ACCEPTED_BUT_NOT_PROMOTED = {
  2270. # We can trust with reasonable confidence that map gives us pair<>, too.
  2271. 'pair<>': ('map', 'multimap', 'hash_map', 'hash_multimap')
  2272. }
  2273. _RE_PATTERN_STRING = re.compile(r'\bstring\b')
  2274. _re_pattern_algorithm_header = []
  2275. for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
  2276. 'transform'):
  2277. # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
  2278. # type::max().
  2279. _re_pattern_algorithm_header.append(
  2280. (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
  2281. _template,
  2282. '<algorithm>'))
  2283. _re_pattern_templates = []
  2284. for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
  2285. for _template in _templates:
  2286. _re_pattern_templates.append(
  2287. (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
  2288. _template + '<>',
  2289. _header))
  2290. def FilesBelongToSameModule(filename_cc, filename_h):
  2291. """Check if these two filenames belong to the same module.
  2292. The concept of a 'module' here is a as follows:
  2293. foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
  2294. same 'module' if they are in the same directory.
  2295. some/path/public/xyzzy and some/path/internal/xyzzy are also considered
  2296. to belong to the same module here.
  2297. If the filename_cc contains a longer path than the filename_h, for example,
  2298. '/absolute/path/to/base/sysinfo.cc', and this file would include
  2299. 'base/sysinfo.h', this function also produces the prefix needed to open the
  2300. header. This is used by the caller of this function to more robustly open the
  2301. header file. We don't have access to the real include paths in this context,
  2302. so we need this guesswork here.
  2303. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
  2304. according to this implementation. Because of this, this function gives
  2305. some false positives. This should be sufficiently rare in practice.
  2306. Args:
  2307. filename_cc: is the path for the .cc file
  2308. filename_h: is the path for the header path
  2309. Returns:
  2310. Tuple with a bool and a string:
  2311. bool: True if filename_cc and filename_h belong to the same module.
  2312. string: the additional prefix needed to open the header file.
  2313. """
  2314. if not filename_cc.endswith('.cc'):
  2315. return (False, '')
  2316. filename_cc = filename_cc[:-len('.cc')]
  2317. if filename_cc.endswith('_unittest'):
  2318. filename_cc = filename_cc[:-len('_unittest')]
  2319. elif filename_cc.endswith('_test'):
  2320. filename_cc = filename_cc[:-len('_test')]
  2321. filename_cc = filename_cc.replace('/public/', '/')
  2322. filename_cc = filename_cc.replace('/internal/', '/')
  2323. if not filename_h.endswith('.h'):
  2324. return (False, '')
  2325. filename_h = filename_h[:-len('.h')]
  2326. if filename_h.endswith('-inl'):
  2327. filename_h = filename_h[:-len('-inl')]
  2328. filename_h = filename_h.replace('/public/', '/')
  2329. filename_h = filename_h.replace('/internal/', '/')
  2330. files_belong_to_same_module = filename_cc.endswith(filename_h)
  2331. common_path = ''
  2332. if files_belong_to_same_module:
  2333. common_path = filename_cc[:-len(filename_h)]
  2334. return files_belong_to_same_module, common_path
  2335. def UpdateIncludeState(filename, include_state, io=codecs):
  2336. """Fill up the include_state with new includes found from the file.
  2337. Args:
  2338. filename: the name of the header to read.
  2339. include_state: an _IncludeState instance in which the headers are inserted.
  2340. io: The io factory to use to read the file. Provided for testability.
  2341. Returns:
  2342. True if a header was succesfully added. False otherwise.
  2343. """
  2344. headerfile = None
  2345. try:
  2346. headerfile = io.open(filename, 'r', 'utf8', 'replace')
  2347. except IOError:
  2348. return False
  2349. linenum = 0
  2350. for line in headerfile:
  2351. linenum += 1
  2352. clean_line = CleanseComments(line)
  2353. match = _RE_PATTERN_INCLUDE.search(clean_line)
  2354. if match:
  2355. include = match.group(2)
  2356. # The value formatting is cute, but not really used right now.
  2357. # What matters here is that the key is in include_state.
  2358. include_state.setdefault(include, '%s:%d' % (filename, linenum))
  2359. return True
  2360. def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
  2361. io=codecs):
  2362. """Reports for missing stl includes.
  2363. This function will output warnings to make sure you are including the headers
  2364. necessary for the stl containers and functions that you use. We only give one
  2365. reason to include a header. For example, if you use both equal_to<> and
  2366. less<> in a .h file, only one (the latter in the file) of these will be
  2367. reported as a reason to include the <functional>.
  2368. Args:
  2369. filename: The name of the current file.
  2370. clean_lines: A CleansedLines instance containing the file.
  2371. include_state: An _IncludeState instance.
  2372. error: The function to call with any errors found.
  2373. io: The IO factory to use to read the header file. Provided for unittest
  2374. injection.
  2375. """
  2376. required = {} # A map of header name to linenumber and the template entity.
  2377. # Example of required: { '<functional>': (1219, 'less<>') }
  2378. for linenum in xrange(clean_lines.NumLines()):
  2379. line = clean_lines.elided[linenum]
  2380. if not line or line[0] == '#':
  2381. continue
  2382. # String is special -- it is a non-templatized type in STL.
  2383. m = _RE_PATTERN_STRING.search(line)
  2384. if m:
  2385. # Don't warn about strings in non-STL namespaces:
  2386. # (We check only the first match per line; good enough.)
  2387. prefix = line[:m.start()]
  2388. if prefix.endswith('std::') or not prefix.endswith('::'):
  2389. required['<string>'] = (linenum, 'string')
  2390. for pattern, template, header in _re_pattern_algorithm_header:
  2391. if pattern.search(line):
  2392. required[header] = (linenum, template)
  2393. # The following function is just a speed up, no semantics are changed.
  2394. if not '<' in line: # Reduces the cpu time usage by skipping lines.
  2395. continue
  2396. for pattern, template, header in _re_pattern_templates:
  2397. if pattern.search(line):
  2398. required[header] = (linenum, template)
  2399. # The policy is that if you #include something in foo.h you don't need to
  2400. # include it again in foo.cc. Here, we will look at possible includes.
  2401. # Let's copy the include_state so it is only messed up within this function.
  2402. include_state = include_state.copy()
  2403. # Did we find the header for this file (if any) and succesfully load it?
  2404. header_found = False
  2405. # Use the absolute path so that matching works properly.
  2406. abs_filename = os.path.abspath(filename)
  2407. # For Emacs's flymake.
  2408. # If cpplint is invoked from Emacs's flymake, a temporary file is generated
  2409. # by flymake and that file name might end with '_flymake.cc'. In that case,
  2410. # restore original file name here so that the corresponding header file can be
  2411. # found.
  2412. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
  2413. # instead of 'foo_flymake.h'
  2414. abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
  2415. # include_state is modified during iteration, so we iterate over a copy of
  2416. # the keys.
  2417. for header in include_state.keys(): #NOLINT
  2418. (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
  2419. fullpath = common_path + header
  2420. if same_module and UpdateIncludeState(fullpath, include_state, io):
  2421. header_found = True
  2422. # If we can't find the header file for a .cc, assume it's because we don't
  2423. # know where to look. In that case we'll give up as we're not sure they
  2424. # didn't include it in the .h file.
  2425. # TODO(unknown): Do a better job of finding .h files so we are confident that
  2426. # not having the .h file means there isn't one.
  2427. if filename.endswith('.cc') and not header_found:
  2428. return
  2429. # All the lines have been processed, report the errors found.
  2430. for required_header_unstripped in required:
  2431. template = required[required_header_unstripped][1]
  2432. if template in _HEADERS_ACCEPTED_BUT_NOT_PROMOTED:
  2433. headers = _HEADERS_ACCEPTED_BUT_NOT_PROMOTED[template]
  2434. if [True for header in headers if header in include_state]:
  2435. continue
  2436. if required_header_unstripped.strip('<>"') not in include_state:
  2437. error(filename, required[required_header_unstripped][0],
  2438. 'build/include_what_you_use', 4,
  2439. 'Add #include ' + required_header_unstripped + ' for ' + template)
  2440. def ProcessLine(filename, file_extension,
  2441. clean_lines, line, include_state, function_state,
  2442. class_state, error):
  2443. """Processes a single line in the file.
  2444. Args:
  2445. filename: Filename of the file that is being processed.
  2446. file_extension: The extension (dot not included) of the file.
  2447. clean_lines: An array of strings, each representing a line of the file,
  2448. with comments stripped.
  2449. line: Number of line being processed.
  2450. include_state: An _IncludeState instance in which the headers are inserted.
  2451. function_state: A _FunctionState instance which counts function lines, etc.
  2452. class_state: A _ClassState instance which maintains information about
  2453. the current stack of nested class declarations being parsed.
  2454. error: A callable to which errors are reported, which takes 4 arguments:
  2455. filename, line number, error level, and message
  2456. """
  2457. raw_lines = clean_lines.raw_lines
  2458. ParseNolintSuppressions(filename, raw_lines[line], line, error)
  2459. CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
  2460. CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
  2461. CheckStyle(filename, clean_lines, line, file_extension, error)
  2462. CheckLanguage(filename, clean_lines, line, file_extension, include_state,
  2463. error)
  2464. CheckForNonStandardConstructs(filename, clean_lines, line,
  2465. class_state, error)
  2466. CheckPosixThreading(filename, clean_lines, line, error)
  2467. CheckInvalidIncrement(filename, clean_lines, line, error)
  2468. def ProcessFileData(filename, file_extension, lines, error):
  2469. """Performs lint checks and reports any errors to the given error function.
  2470. Args:
  2471. filename: Filename of the file that is being processed.
  2472. file_extension: The extension (dot not included) of the file.
  2473. lines: An array of strings, each representing a line of the file, with the
  2474. last element being empty if the file is termined with a newline.
  2475. error: A callable to which errors are reported, which takes 4 arguments:
  2476. """
  2477. lines = (['// marker so line numbers and indices both start at 1'] + lines +
  2478. ['// marker so line numbers end in a known way'])
  2479. include_state = _IncludeState()
  2480. function_state = _FunctionState()
  2481. class_state = _ClassState()
  2482. ResetNolintSuppressions()
  2483. CheckForCopyright(filename, lines, error)
  2484. if file_extension == 'h':
  2485. CheckForHeaderGuard(filename, lines, error)
  2486. RemoveMultiLineComments(filename, lines, error)
  2487. clean_lines = CleansedLines(lines)
  2488. for line in xrange(clean_lines.NumLines()):
  2489. ProcessLine(filename, file_extension, clean_lines, line,
  2490. include_state, function_state, class_state, error)
  2491. class_state.CheckFinished(filename, error)
  2492. CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
  2493. # We check here rather than inside ProcessLine so that we see raw
  2494. # lines rather than "cleaned" lines.
  2495. CheckForUnicodeReplacementCharacters(filename, lines, error)
  2496. CheckForNewlineAtEOF(filename, lines, error)
  2497. def ProcessFile(filename, vlevel):
  2498. """Does google-lint on a single file.
  2499. Args:
  2500. filename: The name of the file to parse.
  2501. vlevel: The level of errors to report. Every error of confidence
  2502. >= verbose_level will be reported. 0 is a good default.
  2503. """
  2504. _SetVerboseLevel(vlevel)
  2505. try:
  2506. # Support the UNIX convention of using "-" for stdin. Note that
  2507. # we are not opening the file with universal newline support
  2508. # (which codecs doesn't support anyway), so the resulting lines do
  2509. # contain trailing '\r' characters if we are reading a file that
  2510. # has CRLF endings.
  2511. # If after the split a trailing '\r' is present, it is removed
  2512. # below. If it is not expected to be present (i.e. os.linesep !=
  2513. # '\r\n' as in Windows), a warning is issued below if this file
  2514. # is processed.
  2515. if filename == '-':
  2516. lines = codecs.StreamReaderWriter(sys.stdin,
  2517. codecs.getreader('utf8'),
  2518. codecs.getwriter('utf8'),
  2519. 'replace').read().split('\n')
  2520. else:
  2521. lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
  2522. carriage_return_found = False
  2523. # Remove trailing '\r'.
  2524. for linenum in range(len(lines)):
  2525. if lines[linenum].endswith('\r'):
  2526. lines[linenum] = lines[linenum].rstrip('\r')
  2527. carriage_return_found = True
  2528. except IOError:
  2529. sys.stderr.write(
  2530. "Skipping input '%s': Can't open for reading\n" % filename)
  2531. return
  2532. # Note, if no dot is found, this will give the entire filename as the ext.
  2533. file_extension = filename[filename.rfind('.') + 1:]
  2534. # When reading from stdin, the extension is unknown, so no cpplint tests
  2535. # should rely on the extension.
  2536. if filename != '-' and (file_extension not in ['h', 'c', 'cc', 'cpp']):
  2537. sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename)
  2538. else:
  2539. ProcessFileData(filename, file_extension, lines, Error)
  2540. if carriage_return_found and os.linesep != '\r\n':
  2541. # Use 0 for linenum since outputing only one error for potentially
  2542. # several lines.
  2543. Error(filename, 0, 'whitespace/newline', 1,
  2544. 'One or more unexpected \\r (^M) found;'
  2545. 'better to use only a \\n')
  2546. sys.stderr.write('Done processing %s\n' % filename)
  2547. def PrintUsage(message):
  2548. """Prints a brief usage string and exits, optionally with an error message.
  2549. Args:
  2550. message: The optional error message.
  2551. """
  2552. sys.stderr.write(_USAGE)
  2553. if message:
  2554. sys.exit('\nFATAL ERROR: ' + message)
  2555. else:
  2556. sys.exit(1)
  2557. def PrintCategories():
  2558. """Prints a list of all the error-categories used by error messages.
  2559. These are the categories used to filter messages via --filter.
  2560. """
  2561. sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
  2562. sys.exit(0)
  2563. def ParseArguments(args):
  2564. """Parses the command line arguments.
  2565. This may set the output format and verbosity level as side-effects.
  2566. Args:
  2567. args: The command line arguments:
  2568. Returns:
  2569. The list of filenames to lint.
  2570. """
  2571. try:
  2572. (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
  2573. 'counting=',
  2574. 'filter='])
  2575. except getopt.GetoptError:
  2576. PrintUsage('Invalid arguments.')
  2577. verbosity = _VerboseLevel()
  2578. output_format = _OutputFormat()
  2579. filters = ''
  2580. counting_style = ''
  2581. for (opt, val) in opts:
  2582. if opt == '--help':
  2583. PrintUsage(None)
  2584. elif opt == '--output':
  2585. if not val in ('emacs', 'vs7'):
  2586. PrintUsage('The only allowed output formats are emacs and vs7.')
  2587. output_format = val
  2588. elif opt == '--verbose':
  2589. verbosity = int(val)
  2590. elif opt == '--filter':
  2591. filters = val
  2592. if not filters:
  2593. PrintCategories()
  2594. elif opt == '--counting':
  2595. if val not in ('total', 'toplevel', 'detailed'):
  2596. PrintUsage('Valid counting options are total, toplevel, and detailed')
  2597. counting_style = val
  2598. if not filenames:
  2599. PrintUsage('No files were specified.')
  2600. _SetOutputFormat(output_format)
  2601. _SetVerboseLevel(verbosity)
  2602. _SetFilters(filters)
  2603. _SetCountingStyle(counting_style)
  2604. return filenames
  2605. def main():
  2606. filenames = ParseArguments(sys.argv[1:])
  2607. # Change stderr to write with replacement characters so we don't die
  2608. # if we try to print something containing non-ASCII characters.
  2609. sys.stderr = codecs.StreamReaderWriter(sys.stderr,
  2610. codecs.getreader('utf8'),
  2611. codecs.getwriter('utf8'),
  2612. 'replace')
  2613. _cpplint_state.ResetErrorCounts()
  2614. for filename in filenames:
  2615. ProcessFile(filename, _cpplint_state.verbose_level)
  2616. _cpplint_state.PrintErrorCounts()
  2617. sys.exit(_cpplint_state.error_count > 0)
  2618. if __name__ == '__main__':
  2619. main()