PageRenderTime 70ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/scripts/cpplint.py

https://bitbucket.org/etterth/logcabin
Python | 3134 lines | 2620 code | 133 blank | 381 comment | 204 complexity | eb35b73d1ffd31484da0155ff9e772af MD5 | raw file
Possible License(s): 0BSD

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

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

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