You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3361 lines
131 KiB

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