PageRenderTime 95ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/remake/cpplint.py

https://github.com/luke7/ITL
Python | 4753 lines | 3880 code | 166 blank | 707 comment | 288 complexity | 4c352fb5ac970e046cd768c12eb384e0 MD5 | raw file
  1. #!/usr/bin/python
  2. #
  3. # Copyright (c) 2009 Google Inc. All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Does google-lint on c++ files.
  31. The goal of this script is to identify places in the code that *may*
  32. be in non-compliance with google style. It does not attempt to fix
  33. up these problems -- the point is to educate. It does also not
  34. attempt to find all problems, or to ensure that everything it does
  35. find is legitimately a problem.
  36. In particular, we can get very confused by /* and // inside strings!
  37. We do a small hack, which is to ignore //'s with "'s after them on the
  38. same line, but it is far from perfect (in either direction).
  39. """
  40. import codecs
  41. import copy
  42. import getopt
  43. import math # for log
  44. import os
  45. import re
  46. import sre_compile
  47. import string
  48. import sys
  49. import unicodedata
  50. _USAGE = """
  51. Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
  52. [--counting=total|toplevel|detailed] [--root=subdir]
  53. [--linelength=digits]
  54. <file> [file] ...
  55. The style guidelines this tries to follow are those in
  56. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
  57. Every problem is given a confidence score from 1-5, with 5 meaning we are
  58. certain of the problem, and 1 meaning it could be a legitimate construct.
  59. This will miss some errors, and is not a substitute for a code review.
  60. To suppress false-positive errors of a certain category, add a
  61. 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
  62. suppresses errors of all categories on that line.
  63. The files passed in will be linted; at least one file must be provided.
  64. Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
  65. extensions with the --extensions flag.
  66. Flags:
  67. output=vs7
  68. By default, the output is formatted to ease emacs parsing. Visual Studio
  69. compatible output (vs7) may also be used. Other formats are unsupported.
  70. verbose=#
  71. Specify a number 0-5 to restrict errors to certain verbosity levels.
  72. filter=-x,+y,...
  73. Specify a comma-separated list of category-filters to apply: only
  74. error messages whose category names pass the filters will be printed.
  75. (Category names are printed with the message and look like
  76. "[whitespace/indent]".) Filters are evaluated left to right.
  77. "-FOO" and "FOO" means "do not print categories that start with FOO".
  78. "+FOO" means "do print categories that start with FOO".
  79. Examples: --filter=-whitespace,+whitespace/braces
  80. --filter=whitespace,runtime/printf,+runtime/printf_format
  81. --filter=-,+build/include_what_you_use
  82. To see a list of all the categories used in cpplint, pass no arg:
  83. --filter=
  84. counting=total|toplevel|detailed
  85. The total number of errors found is always printed. If
  86. 'toplevel' is provided, then the count of errors in each of
  87. the top-level categories like 'build' and 'whitespace' will
  88. also be printed. If 'detailed' is provided, then a count
  89. is provided for each category like 'build/class'.
  90. root=subdir
  91. The root directory used for deriving header guard CPP variable.
  92. By default, the header guard CPP variable is calculated as the relative
  93. path to the directory that contains .git, .hg, or .svn. When this flag
  94. is specified, the relative path is calculated from the specified
  95. directory. If the specified directory does not exist, this flag is
  96. ignored.
  97. Examples:
  98. Assuing that src/.git exists, the header guard CPP variables for
  99. src/chrome/browser/ui/browser.h are:
  100. No flag => CHROME_BROWSER_UI_BROWSER_H_
  101. --root=chrome => BROWSER_UI_BROWSER_H_
  102. --root=chrome/browser => UI_BROWSER_H_
  103. linelength=digits
  104. This is the allowed line length for the project. The default value is
  105. 80 characters.
  106. Examples:
  107. --linelength=120
  108. extensions=extension,extension,...
  109. The allowed file extensions that cpplint will check
  110. Examples:
  111. --extensions=hpp,cpp
  112. """
  113. # We categorize each error message we print. Here are the categories.
  114. # We want an explicit list so we can list them all in cpplint --filter=.
  115. # If you add a new error message with a new category, add it to the list
  116. # here! cpplint_unittest.py should tell you if you forget to do this.
  117. _ERROR_CATEGORIES = [
  118. 'build/class',
  119. 'build/deprecated',
  120. 'build/endif_comment',
  121. 'build/explicit_make_pair',
  122. 'build/forward_decl',
  123. 'build/header_guard',
  124. 'build/include',
  125. 'build/include_alpha',
  126. 'build/include_order',
  127. 'build/include_what_you_use',
  128. 'build/namespaces',
  129. 'build/printf_format',
  130. 'build/storage_class',
  131. 'legal/copyright',
  132. 'readability/alt_tokens',
  133. 'readability/braces',
  134. 'readability/casting',
  135. 'readability/check',
  136. 'readability/constructors',
  137. 'readability/fn_size',
  138. 'readability/function',
  139. 'readability/multiline_comment',
  140. 'readability/multiline_string',
  141. 'readability/namespace',
  142. 'readability/nolint',
  143. 'readability/nul',
  144. 'readability/streams',
  145. 'readability/todo',
  146. 'readability/utf8',
  147. 'runtime/arrays',
  148. 'runtime/casting',
  149. 'runtime/explicit',
  150. 'runtime/int',
  151. 'runtime/init',
  152. 'runtime/invalid_increment',
  153. 'runtime/member_string_references',
  154. 'runtime/memset',
  155. 'runtime/operator',
  156. 'runtime/printf',
  157. 'runtime/printf_format',
  158. 'runtime/references',
  159. 'runtime/string',
  160. 'runtime/threadsafe_fn',
  161. 'runtime/vlog',
  162. 'whitespace/blank_line',
  163. 'whitespace/braces',
  164. 'whitespace/comma',
  165. 'whitespace/comments',
  166. 'whitespace/empty_conditional_body',
  167. 'whitespace/empty_loop_body',
  168. 'whitespace/end_of_line',
  169. 'whitespace/ending_newline',
  170. 'whitespace/forcolon',
  171. 'whitespace/indent',
  172. 'whitespace/line_length',
  173. 'whitespace/newline',
  174. 'whitespace/operators',
  175. 'whitespace/parens',
  176. 'whitespace/semicolon',
  177. 'whitespace/tab',
  178. 'whitespace/todo'
  179. ]
  180. # The default state of the category filter. This is overrided by the --filter=
  181. # flag. By default all errors are on, so only add here categories that should be
  182. # off by default (i.e., categories that must be enabled by the --filter= flags).
  183. # All entries here should start with a '-' or '+', as in the --filter= flag.
  184. _DEFAULT_FILTERS = ['-build/include_alpha']
  185. # We used to check for high-bit characters, but after much discussion we
  186. # decided those were OK, as long as they were in UTF-8 and didn't represent
  187. # hard-coded international strings, which belong in a separate i18n file.
  188. # C++ headers
  189. _CPP_HEADERS = frozenset([
  190. # Legacy
  191. 'algobase.h',
  192. 'algo.h',
  193. 'alloc.h',
  194. 'builtinbuf.h',
  195. 'bvector.h',
  196. 'complex.h',
  197. 'defalloc.h',
  198. 'deque.h',
  199. 'editbuf.h',
  200. 'fstream.h',
  201. 'function.h',
  202. 'hash_map',
  203. 'hash_map.h',
  204. 'hash_set',
  205. 'hash_set.h',
  206. 'hashtable.h',
  207. 'heap.h',
  208. 'indstream.h',
  209. 'iomanip.h',
  210. 'iostream.h',
  211. 'istream.h',
  212. 'iterator.h',
  213. 'list.h',
  214. 'map.h',
  215. 'multimap.h',
  216. 'multiset.h',
  217. 'ostream.h',
  218. 'pair.h',
  219. 'parsestream.h',
  220. 'pfstream.h',
  221. 'procbuf.h',
  222. 'pthread_alloc',
  223. 'pthread_alloc.h',
  224. 'rope',
  225. 'rope.h',
  226. 'ropeimpl.h',
  227. 'set.h',
  228. 'slist',
  229. 'slist.h',
  230. 'stack.h',
  231. 'stdiostream.h',
  232. 'stl_alloc.h',
  233. 'stl_relops.h',
  234. 'streambuf.h',
  235. 'stream.h',
  236. 'strfile.h',
  237. 'strstream.h',
  238. 'tempbuf.h',
  239. 'tree.h',
  240. 'type_traits.h',
  241. 'vector.h',
  242. # 17.6.1.2 C++ library headers
  243. 'algorithm',
  244. 'array',
  245. 'atomic',
  246. 'bitset',
  247. 'chrono',
  248. 'codecvt',
  249. 'complex',
  250. 'condition_variable',
  251. 'deque',
  252. 'exception',
  253. 'forward_list',
  254. 'fstream',
  255. 'functional',
  256. 'future',
  257. 'initializer_list',
  258. 'iomanip',
  259. 'ios',
  260. 'iosfwd',
  261. 'iostream',
  262. 'istream',
  263. 'iterator',
  264. 'limits',
  265. 'list',
  266. 'locale',
  267. 'map',
  268. 'memory',
  269. 'mutex',
  270. 'new',
  271. 'numeric',
  272. 'ostream',
  273. 'queue',
  274. 'random',
  275. 'ratio',
  276. 'regex',
  277. 'set',
  278. 'sstream',
  279. 'stack',
  280. 'stdexcept',
  281. 'streambuf',
  282. 'string',
  283. 'strstream',
  284. 'system_error',
  285. 'thread',
  286. 'tuple',
  287. 'typeindex',
  288. 'typeinfo',
  289. 'type_traits',
  290. 'unordered_map',
  291. 'unordered_set',
  292. 'utility',
  293. 'valarray',
  294. 'vector',
  295. # 17.6.1.2 C++ headers for C library facilities
  296. 'cassert',
  297. 'ccomplex',
  298. 'cctype',
  299. 'cerrno',
  300. 'cfenv',
  301. 'cfloat',
  302. 'cinttypes',
  303. 'ciso646',
  304. 'climits',
  305. 'clocale',
  306. 'cmath',
  307. 'csetjmp',
  308. 'csignal',
  309. 'cstdalign',
  310. 'cstdarg',
  311. 'cstdbool',
  312. 'cstddef',
  313. 'cstdint',
  314. 'cstdio',
  315. 'cstdlib',
  316. 'cstring',
  317. 'ctgmath',
  318. 'ctime',
  319. 'cuchar',
  320. 'cwchar',
  321. 'cwctype',
  322. ])
  323. # Assertion macros. These are defined in base/logging.h and
  324. # testing/base/gunit.h. Note that the _M versions need to come first
  325. # for substring matching to work.
  326. _CHECK_MACROS = [
  327. 'DCHECK', 'CHECK',
  328. 'EXPECT_TRUE_M', 'EXPECT_TRUE',
  329. 'ASSERT_TRUE_M', 'ASSERT_TRUE',
  330. 'EXPECT_FALSE_M', 'EXPECT_FALSE',
  331. 'ASSERT_FALSE_M', 'ASSERT_FALSE',
  332. ]
  333. # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
  334. _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
  335. for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
  336. ('>=', 'GE'), ('>', 'GT'),
  337. ('<=', 'LE'), ('<', 'LT')]:
  338. _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
  339. _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
  340. _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
  341. _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
  342. _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
  343. _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
  344. for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
  345. ('>=', 'LT'), ('>', 'LE'),
  346. ('<=', 'GT'), ('<', 'GE')]:
  347. _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
  348. _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
  349. _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
  350. _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
  351. # Alternative tokens and their replacements. For full list, see section 2.5
  352. # Alternative tokens [lex.digraph] in the C++ standard.
  353. #
  354. # Digraphs (such as '%:') are not included here since it's a mess to
  355. # match those on a word boundary.
  356. _ALT_TOKEN_REPLACEMENT = {
  357. 'and': '&&',
  358. 'bitor': '|',
  359. 'or': '||',
  360. 'xor': '^',
  361. 'compl': '~',
  362. 'bitand': '&',
  363. 'and_eq': '&=',
  364. 'or_eq': '|=',
  365. 'xor_eq': '^=',
  366. 'not': '!',
  367. 'not_eq': '!='
  368. }
  369. # Compile regular expression that matches all the above keywords. The "[ =()]"
  370. # bit is meant to avoid matching these keywords outside of boolean expressions.
  371. #
  372. # False positives include C-style multi-line comments and multi-line strings
  373. # but those have always been troublesome for cpplint.
  374. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
  375. r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
  376. # These constants define types of headers for use with
  377. # _IncludeState.CheckNextIncludeOrder().
  378. _C_SYS_HEADER = 1
  379. _CPP_SYS_HEADER = 2
  380. _LIKELY_MY_HEADER = 3
  381. _POSSIBLE_MY_HEADER = 4
  382. _OTHER_HEADER = 5
  383. # These constants define the current inline assembly state
  384. _NO_ASM = 0 # Outside of inline assembly block
  385. _INSIDE_ASM = 1 # Inside inline assembly block
  386. _END_ASM = 2 # Last line of inline assembly block
  387. _BLOCK_ASM = 3 # The whole block is an inline assembly block
  388. # Match start of assembly blocks
  389. _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
  390. r'(?:\s+(volatile|__volatile__))?'
  391. r'\s*[{(]')
  392. _regexp_compile_cache = {}
  393. # Finds occurrences of NOLINT or NOLINT(...).
  394. _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?')
  395. # {str, set(int)}: a map from error categories to sets of linenumbers
  396. # on which those errors are expected and should be suppressed.
  397. _error_suppressions = {}
  398. # The root directory used for deriving header guard CPP variable.
  399. # This is set by --root flag.
  400. _root = None
  401. # The allowed line length of files.
  402. # This is set by --linelength flag.
  403. _line_length = 80
  404. # The allowed extensions for file names
  405. # This is set by --extensions flag.
  406. _valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
  407. def ParseNolintSuppressions(filename, raw_line, linenum, error):
  408. """Updates the global list of error-suppressions.
  409. Parses any NOLINT comments on the current line, updating the global
  410. error_suppressions store. Reports an error if the NOLINT comment
  411. was malformed.
  412. Args:
  413. filename: str, the name of the input file.
  414. raw_line: str, the line of input text, with comments.
  415. linenum: int, the number of the current line.
  416. error: function, an error handler.
  417. """
  418. # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
  419. matched = _RE_SUPPRESSION.search(raw_line)
  420. if matched:
  421. category = matched.group(1)
  422. if category in (None, '(*)'): # => "suppress all"
  423. _error_suppressions.setdefault(None, set()).add(linenum)
  424. else:
  425. if category.startswith('(') and category.endswith(')'):
  426. category = category[1:-1]
  427. if category in _ERROR_CATEGORIES:
  428. _error_suppressions.setdefault(category, set()).add(linenum)
  429. else:
  430. error(filename, linenum, 'readability/nolint', 5,
  431. 'Unknown NOLINT error category: %s' % category)
  432. def ResetNolintSuppressions():
  433. "Resets the set of NOLINT suppressions to empty."
  434. _error_suppressions.clear()
  435. def IsErrorSuppressedByNolint(category, linenum):
  436. """Returns true if the specified error category is suppressed on this line.
  437. Consults the global error_suppressions map populated by
  438. ParseNolintSuppressions/ResetNolintSuppressions.
  439. Args:
  440. category: str, the category of the error.
  441. linenum: int, the current line number.
  442. Returns:
  443. bool, True iff the error should be suppressed due to a NOLINT comment.
  444. """
  445. return (linenum in _error_suppressions.get(category, set()) or
  446. linenum in _error_suppressions.get(None, set()))
  447. def Match(pattern, s):
  448. """Matches the string with the pattern, caching the compiled regexp."""
  449. # The regexp compilation caching is inlined in both Match and Search for
  450. # performance reasons; factoring it out into a separate function turns out
  451. # to be noticeably expensive.
  452. if pattern not in _regexp_compile_cache:
  453. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  454. return _regexp_compile_cache[pattern].match(s)
  455. def ReplaceAll(pattern, rep, s):
  456. """Replaces instances of pattern in a string with a replacement.
  457. The compiled regex is kept in a cache shared by Match and Search.
  458. Args:
  459. pattern: regex pattern
  460. rep: replacement text
  461. s: search string
  462. Returns:
  463. string with replacements made (or original string if no replacements)
  464. """
  465. if pattern not in _regexp_compile_cache:
  466. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  467. return _regexp_compile_cache[pattern].sub(rep, s)
  468. def Search(pattern, s):
  469. """Searches the string for the pattern, caching the compiled regexp."""
  470. if pattern not in _regexp_compile_cache:
  471. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  472. return _regexp_compile_cache[pattern].search(s)
  473. class _IncludeState(dict):
  474. """Tracks line numbers for includes, and the order in which includes appear.
  475. As a dict, an _IncludeState object serves as a mapping between include
  476. filename and line number on which that file was included.
  477. Call CheckNextIncludeOrder() once for each header in the file, passing
  478. in the type constants defined above. Calls in an illegal order will
  479. raise an _IncludeError with an appropriate error message.
  480. """
  481. # self._section will move monotonically through this set. If it ever
  482. # needs to move backwards, CheckNextIncludeOrder will raise an error.
  483. _INITIAL_SECTION = 0
  484. _MY_H_SECTION = 1
  485. _C_SECTION = 2
  486. _CPP_SECTION = 3
  487. _OTHER_H_SECTION = 4
  488. _TYPE_NAMES = {
  489. _C_SYS_HEADER: 'C system header',
  490. _CPP_SYS_HEADER: 'C++ system header',
  491. _LIKELY_MY_HEADER: 'header this file implements',
  492. _POSSIBLE_MY_HEADER: 'header this file may implement',
  493. _OTHER_HEADER: 'other header',
  494. }
  495. _SECTION_NAMES = {
  496. _INITIAL_SECTION: "... nothing. (This can't be an error.)",
  497. _MY_H_SECTION: 'a header this file implements',
  498. _C_SECTION: 'C system header',
  499. _CPP_SECTION: 'C++ system header',
  500. _OTHER_H_SECTION: 'other header',
  501. }
  502. def __init__(self):
  503. dict.__init__(self)
  504. self.ResetSection()
  505. def ResetSection(self):
  506. # The name of the current section.
  507. self._section = self._INITIAL_SECTION
  508. # The path of last found header.
  509. self._last_header = ''
  510. def SetLastHeader(self, header_path):
  511. self._last_header = header_path
  512. def CanonicalizeAlphabeticalOrder(self, header_path):
  513. """Returns a path canonicalized for alphabetical comparison.
  514. - replaces "-" with "_" so they both cmp the same.
  515. - removes '-inl' since we don't require them to be after the main header.
  516. - lowercase everything, just in case.
  517. Args:
  518. header_path: Path to be canonicalized.
  519. Returns:
  520. Canonicalized path.
  521. """
  522. return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
  523. def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
  524. """Check if a header is in alphabetical order with the previous header.
  525. Args:
  526. clean_lines: A CleansedLines instance containing the file.
  527. linenum: The number of the line to check.
  528. header_path: Canonicalized header to be checked.
  529. Returns:
  530. Returns true if the header is in alphabetical order.
  531. """
  532. # If previous section is different from current section, _last_header will
  533. # be reset to empty string, so it's always less than current header.
  534. #
  535. # If previous line was a blank line, assume that the headers are
  536. # intentionally sorted the way they are.
  537. if (self._last_header > header_path and
  538. not Match(r'^\s*$', clean_lines.elided[linenum - 1])):
  539. return False
  540. return True
  541. def CheckNextIncludeOrder(self, header_type):
  542. """Returns a non-empty error message if the next header is out of order.
  543. This function also updates the internal state to be ready to check
  544. the next include.
  545. Args:
  546. header_type: One of the _XXX_HEADER constants defined above.
  547. Returns:
  548. The empty string if the header is in the right order, or an
  549. error message describing what's wrong.
  550. """
  551. error_message = ('Found %s after %s' %
  552. (self._TYPE_NAMES[header_type],
  553. self._SECTION_NAMES[self._section]))
  554. last_section = self._section
  555. if header_type == _C_SYS_HEADER:
  556. if self._section <= self._C_SECTION:
  557. self._section = self._C_SECTION
  558. else:
  559. self._last_header = ''
  560. return error_message
  561. elif header_type == _CPP_SYS_HEADER:
  562. if self._section <= self._CPP_SECTION:
  563. self._section = self._CPP_SECTION
  564. else:
  565. self._last_header = ''
  566. return error_message
  567. elif header_type == _LIKELY_MY_HEADER:
  568. if self._section <= self._MY_H_SECTION:
  569. self._section = self._MY_H_SECTION
  570. else:
  571. self._section = self._OTHER_H_SECTION
  572. elif header_type == _POSSIBLE_MY_HEADER:
  573. if self._section <= self._MY_H_SECTION:
  574. self._section = self._MY_H_SECTION
  575. else:
  576. # This will always be the fallback because we're not sure
  577. # enough that the header is associated with this file.
  578. self._section = self._OTHER_H_SECTION
  579. else:
  580. assert header_type == _OTHER_HEADER
  581. self._section = self._OTHER_H_SECTION
  582. if last_section != self._section:
  583. self._last_header = ''
  584. return ''
  585. class _CppLintState(object):
  586. """Maintains module-wide state.."""
  587. def __init__(self):
  588. self.verbose_level = 1 # global setting.
  589. self.error_count = 0 # global count of reported errors
  590. # filters to apply when emitting error messages
  591. self.filters = _DEFAULT_FILTERS[:]
  592. self.counting = 'total' # In what way are we counting errors?
  593. self.errors_by_category = {} # string to int dict storing error counts
  594. # output format:
  595. # "emacs" - format that emacs can parse (default)
  596. # "vs7" - format that Microsoft Visual Studio 7 can parse
  597. self.output_format = 'emacs'
  598. def SetOutputFormat(self, output_format):
  599. """Sets the output format for errors."""
  600. self.output_format = output_format
  601. def SetVerboseLevel(self, level):
  602. """Sets the module's verbosity, and returns the previous setting."""
  603. last_verbose_level = self.verbose_level
  604. self.verbose_level = level
  605. return last_verbose_level
  606. def SetCountingStyle(self, counting_style):
  607. """Sets the module's counting options."""
  608. self.counting = counting_style
  609. def SetFilters(self, filters):
  610. """Sets the error-message filters.
  611. These filters are applied when deciding whether to emit a given
  612. error message.
  613. Args:
  614. filters: A string of comma-separated filters (eg "+whitespace/indent").
  615. Each filter should start with + or -; else we die.
  616. Raises:
  617. ValueError: The comma-separated filters did not all start with '+' or '-'.
  618. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
  619. """
  620. # Default filters always have less priority than the flag ones.
  621. self.filters = _DEFAULT_FILTERS[:]
  622. for filt in filters.split(','):
  623. clean_filt = filt.strip()
  624. if clean_filt:
  625. self.filters.append(clean_filt)
  626. for filt in self.filters:
  627. if not (filt.startswith('+') or filt.startswith('-')):
  628. raise ValueError('Every filter in --filters must start with + or -'
  629. ' (%s does not)' % filt)
  630. def ResetErrorCounts(self):
  631. """Sets the module's error statistic back to zero."""
  632. self.error_count = 0
  633. self.errors_by_category = {}
  634. def IncrementErrorCount(self, category):
  635. """Bumps the module's error statistic."""
  636. self.error_count += 1
  637. if self.counting in ('toplevel', 'detailed'):
  638. if self.counting != 'detailed':
  639. category = category.split('/')[0]
  640. if category not in self.errors_by_category:
  641. self.errors_by_category[category] = 0
  642. self.errors_by_category[category] += 1
  643. def PrintErrorCounts(self):
  644. """Print a summary of errors by category, and the total."""
  645. for category, count in self.errors_by_category.iteritems():
  646. sys.stderr.write('Category \'%s\' errors found: %d\n' %
  647. (category, count))
  648. sys.stderr.write('Total errors found: %d\n' % self.error_count)
  649. _cpplint_state = _CppLintState()
  650. def _OutputFormat():
  651. """Gets the module's output format."""
  652. return _cpplint_state.output_format
  653. def _SetOutputFormat(output_format):
  654. """Sets the module's output format."""
  655. _cpplint_state.SetOutputFormat(output_format)
  656. def _VerboseLevel():
  657. """Returns the module's verbosity setting."""
  658. return _cpplint_state.verbose_level
  659. def _SetVerboseLevel(level):
  660. """Sets the module's verbosity, and returns the previous setting."""
  661. return _cpplint_state.SetVerboseLevel(level)
  662. def _SetCountingStyle(level):
  663. """Sets the module's counting options."""
  664. _cpplint_state.SetCountingStyle(level)
  665. def _Filters():
  666. """Returns the module's list of output filters, as a list."""
  667. return _cpplint_state.filters
  668. def _SetFilters(filters):
  669. """Sets the module's error-message filters.
  670. These filters are applied when deciding whether to emit a given
  671. error message.
  672. Args:
  673. filters: A string of comma-separated filters (eg "whitespace/indent").
  674. Each filter should start with + or -; else we die.
  675. """
  676. _cpplint_state.SetFilters(filters)
  677. class _FunctionState(object):
  678. """Tracks current function name and the number of lines in its body."""
  679. _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
  680. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
  681. def __init__(self):
  682. self.in_a_function = False
  683. self.lines_in_function = 0
  684. self.current_function = ''
  685. def Begin(self, function_name):
  686. """Start analyzing function body.
  687. Args:
  688. function_name: The name of the function being tracked.
  689. """
  690. self.in_a_function = True
  691. self.lines_in_function = 0
  692. self.current_function = function_name
  693. def Count(self):
  694. """Count line in current function body."""
  695. if self.in_a_function:
  696. self.lines_in_function += 1
  697. def Check(self, error, filename, linenum):
  698. """Report if too many lines in function body.
  699. Args:
  700. error: The function to call with any errors found.
  701. filename: The name of the current file.
  702. linenum: The number of the line to check.
  703. """
  704. if Match(r'T(EST|est)', self.current_function):
  705. base_trigger = self._TEST_TRIGGER
  706. else:
  707. base_trigger = self._NORMAL_TRIGGER
  708. trigger = base_trigger * 2**_VerboseLevel()
  709. if self.lines_in_function > trigger:
  710. error_level = int(math.log(self.lines_in_function / base_trigger, 2))
  711. # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
  712. if error_level > 5:
  713. error_level = 5
  714. error(filename, linenum, 'readability/fn_size', error_level,
  715. 'Small and focused functions are preferred:'
  716. ' %s has %d non-comment lines'
  717. ' (error triggered by exceeding %d lines).' % (
  718. self.current_function, self.lines_in_function, trigger))
  719. def End(self):
  720. """Stop analyzing function body."""
  721. self.in_a_function = False
  722. class _IncludeError(Exception):
  723. """Indicates a problem with the include order in a file."""
  724. pass
  725. class FileInfo:
  726. """Provides utility functions for filenames.
  727. FileInfo provides easy access to the components of a file's path
  728. relative to the project root.
  729. """
  730. def __init__(self, filename):
  731. self._filename = filename
  732. def FullName(self):
  733. """Make Windows paths like Unix."""
  734. return os.path.abspath(self._filename).replace('\\', '/')
  735. def RepositoryName(self):
  736. """FullName after removing the local path to the repository.
  737. If we have a real absolute path name here we can try to do something smart:
  738. detecting the root of the checkout and truncating /path/to/checkout from
  739. the name so that we get header guards that don't include things like
  740. "C:\Documents and Settings\..." or "/home/username/..." in them and thus
  741. people on different computers who have checked the source out to different
  742. locations won't see bogus errors.
  743. """
  744. fullname = self.FullName()
  745. if os.path.exists(fullname):
  746. project_dir = os.path.dirname(fullname)
  747. if os.path.exists(os.path.join(project_dir, ".svn")):
  748. # If there's a .svn file in the current directory, we recursively look
  749. # up the directory tree for the top of the SVN checkout
  750. root_dir = project_dir
  751. one_up_dir = os.path.dirname(root_dir)
  752. while os.path.exists(os.path.join(one_up_dir, ".svn")):
  753. root_dir = os.path.dirname(root_dir)
  754. one_up_dir = os.path.dirname(one_up_dir)
  755. prefix = os.path.commonprefix([root_dir, project_dir])
  756. return fullname[len(prefix) + 1:]
  757. # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
  758. # searching up from the current path.
  759. root_dir = os.path.dirname(fullname)
  760. while (root_dir != os.path.dirname(root_dir) and
  761. not os.path.exists(os.path.join(root_dir, ".git")) and
  762. not os.path.exists(os.path.join(root_dir, ".hg")) and
  763. not os.path.exists(os.path.join(root_dir, ".svn"))):
  764. root_dir = os.path.dirname(root_dir)
  765. if (os.path.exists(os.path.join(root_dir, ".git")) or
  766. os.path.exists(os.path.join(root_dir, ".hg")) or
  767. os.path.exists(os.path.join(root_dir, ".svn"))):
  768. prefix = os.path.commonprefix([root_dir, project_dir])
  769. return fullname[len(prefix) + 1:]
  770. # Don't know what to do; header guard warnings may be wrong...
  771. return fullname
  772. def Split(self):
  773. """Splits the file into the directory, basename, and extension.
  774. For 'chrome/browser/browser.cc', Split() would
  775. return ('chrome/browser', 'browser', '.cc')
  776. Returns:
  777. A tuple of (directory, basename, extension).
  778. """
  779. googlename = self.RepositoryName()
  780. project, rest = os.path.split(googlename)
  781. return (project,) + os.path.splitext(rest)
  782. def BaseName(self):
  783. """File base name - text after the final slash, before the final period."""
  784. return self.Split()[1]
  785. def Extension(self):
  786. """File extension - text following the final period."""
  787. return self.Split()[2]
  788. def NoExtension(self):
  789. """File has no source file extension."""
  790. return '/'.join(self.Split()[0:2])
  791. def IsSource(self):
  792. """File has a source file extension."""
  793. return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
  794. def _ShouldPrintError(category, confidence, linenum):
  795. """If confidence >= verbose, category passes filter and is not suppressed."""
  796. # There are three ways we might decide not to print an error message:
  797. # a "NOLINT(category)" comment appears in the source,
  798. # the verbosity level isn't high enough, or the filters filter it out.
  799. if IsErrorSuppressedByNolint(category, linenum):
  800. return False
  801. if confidence < _cpplint_state.verbose_level:
  802. return False
  803. is_filtered = False
  804. for one_filter in _Filters():
  805. if one_filter.startswith('-'):
  806. if category.startswith(one_filter[1:]):
  807. is_filtered = True
  808. elif one_filter.startswith('+'):
  809. if category.startswith(one_filter[1:]):
  810. is_filtered = False
  811. else:
  812. assert False # should have been checked for in SetFilter.
  813. if is_filtered:
  814. return False
  815. return True
  816. def Error(filename, linenum, category, confidence, message):
  817. """Logs the fact we've found a lint error.
  818. We log where the error was found, and also our confidence in the error,
  819. that is, how certain we are this is a legitimate style regression, and
  820. not a misidentification or a use that's sometimes justified.
  821. False positives can be suppressed by the use of
  822. "cpplint(category)" comments on the offending line. These are
  823. parsed into _error_suppressions.
  824. Args:
  825. filename: The name of the file containing the error.
  826. linenum: The number of the line containing the error.
  827. category: A string used to describe the "category" this bug
  828. falls under: "whitespace", say, or "runtime". Categories
  829. may have a hierarchy separated by slashes: "whitespace/indent".
  830. confidence: A number from 1-5 representing a confidence score for
  831. the error, with 5 meaning that we are certain of the problem,
  832. and 1 meaning that it could be a legitimate construct.
  833. message: The error message.
  834. """
  835. if _ShouldPrintError(category, confidence, linenum):
  836. _cpplint_state.IncrementErrorCount(category)
  837. if _cpplint_state.output_format == 'vs7':
  838. sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
  839. filename, linenum, message, category, confidence))
  840. elif _cpplint_state.output_format == 'eclipse':
  841. sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
  842. filename, linenum, message, category, confidence))
  843. else:
  844. sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
  845. filename, linenum, message, category, confidence))
  846. # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
  847. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
  848. r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
  849. # Matches strings. Escape codes should already be removed by ESCAPES.
  850. _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
  851. # Matches characters. Escape codes should already be removed by ESCAPES.
  852. _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
  853. # Matches multi-line C++ comments.
  854. # This RE is a little bit more complicated than one might expect, because we
  855. # have to take care of space removals tools so we can handle comments inside
  856. # statements better.
  857. # The current rule is: We only clear spaces from both sides when we're at the
  858. # end of the line. Otherwise, we try to remove spaces from the right side,
  859. # if this doesn't work we try on left side but only if there's a non-character
  860. # on the right.
  861. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
  862. r"""(\s*/\*.*\*/\s*$|
  863. /\*.*\*/\s+|
  864. \s+/\*.*\*/(?=\W)|
  865. /\*.*\*/)""", re.VERBOSE)
  866. def IsCppString(line):
  867. """Does line terminate so, that the next symbol is in string constant.
  868. This function does not consider single-line nor multi-line comments.
  869. Args:
  870. line: is a partial line of code starting from the 0..n.
  871. Returns:
  872. True, if next character appended to 'line' is inside a
  873. string constant.
  874. """
  875. line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
  876. return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
  877. def CleanseRawStrings(raw_lines):
  878. """Removes C++11 raw strings from lines.
  879. Before:
  880. static const char kData[] = R"(
  881. multi-line string
  882. )";
  883. After:
  884. static const char kData[] = ""
  885. (replaced by blank line)
  886. "";
  887. Args:
  888. raw_lines: list of raw lines.
  889. Returns:
  890. list of lines with C++11 raw strings replaced by empty strings.
  891. """
  892. delimiter = None
  893. lines_without_raw_strings = []
  894. for line in raw_lines:
  895. if delimiter:
  896. # Inside a raw string, look for the end
  897. end = line.find(delimiter)
  898. if end >= 0:
  899. # Found the end of the string, match leading space for this
  900. # line and resume copying the original lines, and also insert
  901. # a "" on the last line.
  902. leading_space = Match(r'^(\s*)\S', line)
  903. line = leading_space.group(1) + '""' + line[end + len(delimiter):]
  904. delimiter = None
  905. else:
  906. # Haven't found the end yet, append a blank line.
  907. line = ''
  908. else:
  909. # Look for beginning of a raw string.
  910. # See 2.14.15 [lex.string] for syntax.
  911. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
  912. if matched:
  913. delimiter = ')' + matched.group(2) + '"'
  914. end = matched.group(3).find(delimiter)
  915. if end >= 0:
  916. # Raw string ended on same line
  917. line = (matched.group(1) + '""' +
  918. matched.group(3)[end + len(delimiter):])
  919. delimiter = None
  920. else:
  921. # Start of a multi-line raw string
  922. line = matched.group(1) + '""'
  923. lines_without_raw_strings.append(line)
  924. # TODO(unknown): if delimiter is not None here, we might want to
  925. # emit a warning for unterminated string.
  926. return lines_without_raw_strings
  927. def FindNextMultiLineCommentStart(lines, lineix):
  928. """Find the beginning marker for a multiline comment."""
  929. while lineix < len(lines):
  930. if lines[lineix].strip().startswith('/*'):
  931. # Only return this marker if the comment goes beyond this line
  932. if lines[lineix].strip().find('*/', 2) < 0:
  933. return lineix
  934. lineix += 1
  935. return len(lines)
  936. def FindNextMultiLineCommentEnd(lines, lineix):
  937. """We are inside a comment, find the end marker."""
  938. while lineix < len(lines):
  939. if lines[lineix].strip().endswith('*/'):
  940. return lineix
  941. lineix += 1
  942. return len(lines)
  943. def RemoveMultiLineCommentsFromRange(lines, begin, end):
  944. """Clears a range of lines for multi-line comments."""
  945. # Having // dummy comments makes the lines non-empty, so we will not get
  946. # unnecessary blank line warnings later in the code.
  947. for i in range(begin, end):
  948. lines[i] = '// dummy'
  949. def RemoveMultiLineComments(filename, lines, error):
  950. """Removes multiline (c-style) comments from lines."""
  951. lineix = 0
  952. while lineix < len(lines):
  953. lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
  954. if lineix_begin >= len(lines):
  955. return
  956. lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
  957. if lineix_end >= len(lines):
  958. error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
  959. 'Could not find end of multi-line comment')
  960. return
  961. RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
  962. lineix = lineix_end + 1
  963. def CleanseComments(line):
  964. """Removes //-comments and single-line C-style /* */ comments.
  965. Args:
  966. line: A line of C++ source.
  967. Returns:
  968. The line with single-line comments removed.
  969. """
  970. commentpos = line.find('//')
  971. if commentpos != -1 and not IsCppString(line[:commentpos]):
  972. line = line[:commentpos].rstrip()
  973. # get rid of /* ... */
  974. return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
  975. class CleansedLines(object):
  976. """Holds 3 copies of all lines with different preprocessing applied to them.
  977. 1) elided member contains lines without strings and comments,
  978. 2) lines member contains lines without comments, and
  979. 3) raw_lines member contains all the lines without processing.
  980. All these three members are of <type 'list'>, and of the same length.
  981. """
  982. def __init__(self, lines):
  983. self.elided = []
  984. self.lines = []
  985. self.raw_lines = lines
  986. self.num_lines = len(lines)
  987. self.lines_without_raw_strings = CleanseRawStrings(lines)
  988. for linenum in range(len(self.lines_without_raw_strings)):
  989. self.lines.append(CleanseComments(
  990. self.lines_without_raw_strings[linenum]))
  991. elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
  992. self.elided.append(CleanseComments(elided))
  993. def NumLines(self):
  994. """Returns the number of lines represented."""
  995. return self.num_lines
  996. @staticmethod
  997. def _CollapseStrings(elided):
  998. """Collapses strings and chars on a line to simple "" or '' blocks.
  999. We nix strings first so we're not fooled by text like '"http://"'
  1000. Args:
  1001. elided: The line being processed.
  1002. Returns:
  1003. The line with collapsed strings.
  1004. """
  1005. if not _RE_PATTERN_INCLUDE.match(elided):
  1006. # Remove escaped characters first to make quote/single quote collapsing
  1007. # basic. Things that look like escaped characters shouldn't occur
  1008. # outside of strings and chars.
  1009. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
  1010. elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
  1011. elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
  1012. return elided
  1013. def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
  1014. """Find the position just after the matching endchar.
  1015. Args:
  1016. line: a CleansedLines line.
  1017. startpos: start searching at this position.
  1018. depth: nesting level at startpos.
  1019. startchar: expression opening character.
  1020. endchar: expression closing character.
  1021. Returns:
  1022. On finding matching endchar: (index just after matching endchar, 0)
  1023. Otherwise: (-1, new depth at end of this line)
  1024. """
  1025. for i in xrange(startpos, len(line)):
  1026. if line[i] == startchar:
  1027. depth += 1
  1028. elif line[i] == endchar:
  1029. depth -= 1
  1030. if depth == 0:
  1031. return (i + 1, 0)
  1032. return (-1, depth)
  1033. def CloseExpression(clean_lines, linenum, pos):
  1034. """If input points to ( or { or [ or <, finds the position that closes it.
  1035. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
  1036. linenum/pos that correspond to the closing of the expression.
  1037. Args:
  1038. clean_lines: A CleansedLines instance containing the file.
  1039. linenum: The number of the line to check.
  1040. pos: A position on the line.
  1041. Returns:
  1042. A tuple (line, linenum, pos) pointer *past* the closing brace, or
  1043. (line, len(lines), -1) if we never find a close. Note we ignore
  1044. strings and comments when matching; and the line we return is the
  1045. 'cleansed' line at linenum.
  1046. """
  1047. line = clean_lines.elided[linenum]
  1048. startchar = line[pos]
  1049. if startchar not in '({[<':
  1050. return (line, clean_lines.NumLines(), -1)
  1051. if startchar == '(': endchar = ')'
  1052. if startchar == '[': endchar = ']'
  1053. if startchar == '{': endchar = '}'
  1054. if startchar == '<': endchar = '>'
  1055. # Check first line
  1056. (end_pos, num_open) = FindEndOfExpressionInLine(
  1057. line, pos, 0, startchar, endchar)
  1058. if end_pos > -1:
  1059. return (line, linenum, end_pos)
  1060. # Continue scanning forward
  1061. while linenum < clean_lines.NumLines() - 1:
  1062. linenum += 1
  1063. line = clean_lines.elided[linenum]
  1064. (end_pos, num_open) = FindEndOfExpressionInLine(
  1065. line, 0, num_open, startchar, endchar)
  1066. if end_pos > -1:
  1067. return (line, linenum, end_pos)
  1068. # Did not find endchar before end of file, give up
  1069. return (line, clean_lines.NumLines(), -1)
  1070. def FindStartOfExpressionInLine(line, endpos, depth, startchar, endchar):
  1071. """Find position at the matching startchar.
  1072. This is almost the reverse of FindEndOfExpressionInLine, but note
  1073. that the input position and returned position differs by 1.
  1074. Args:
  1075. line: a CleansedLines line.
  1076. endpos: start searching at this position.
  1077. depth: nesting level at endpos.
  1078. startchar: expression opening character.
  1079. endchar: expression closing character.
  1080. Returns:
  1081. On finding matching startchar: (index at matching startchar, 0)
  1082. Otherwise: (-1, new depth at beginning of this line)
  1083. """
  1084. for i in xrange(endpos, -1, -1):
  1085. if line[i] == endchar:
  1086. depth += 1
  1087. elif line[i] == startchar:
  1088. depth -= 1
  1089. if depth == 0:
  1090. return (i, 0)
  1091. return (-1, depth)
  1092. def ReverseCloseExpression(clean_lines, linenum, pos):
  1093. """If input points to ) or } or ] or >, finds the position that opens it.
  1094. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
  1095. linenum/pos that correspond to the opening of the expression.
  1096. Args:
  1097. clean_lines: A CleansedLines instance containing the file.
  1098. linenum: The number of the line to check.
  1099. pos: A position on the line.
  1100. Returns:
  1101. A tuple (line, linenum, pos) pointer *at* the opening brace, or
  1102. (line, 0, -1) if we never find the matching opening brace. Note
  1103. we ignore strings and comments when matching; and the line we
  1104. return is the 'cleansed' line at linenum.
  1105. """
  1106. line = clean_lines.elided[linenum]
  1107. endchar = line[pos]
  1108. if endchar not in ')}]>':
  1109. return (line, 0, -1)
  1110. if endchar == ')': startchar = '('
  1111. if endchar == ']': startchar = '['
  1112. if endchar == '}': startchar = '{'
  1113. if endchar == '>': startchar = '<'
  1114. # Check last line
  1115. (start_pos, num_open) = FindStartOfExpressionInLine(
  1116. line, pos, 0, startchar, endchar)
  1117. if start_pos > -1:
  1118. return (line, linenum, start_pos)
  1119. # Continue scanning backward
  1120. while linenum > 0:
  1121. linenum -= 1
  1122. line = clean_lines.elided[linenum]
  1123. (start_pos, num_open) = FindStartOfExpressionInLine(
  1124. line, len(line) - 1, num_open, startchar, endchar)
  1125. if start_pos > -1:
  1126. return (line, linenum, start_pos)
  1127. # Did not find startchar before beginning of file, give up
  1128. return (line, 0, -1)
  1129. def CheckForCopyright(filename, lines, error):
  1130. """Logs an error if no Copyright message appears at the top of the file."""
  1131. # We'll say it should occur by line 10. Don't forget there's a
  1132. # dummy line at the front.
  1133. for line in xrange(1, min(len(lines), 11)):
  1134. if re.search(r'Copyright', lines[line], re.I): break
  1135. else: # means no copyright line was found
  1136. error(filename, 0, 'legal/copyright', 5,
  1137. 'No copyright message found. '
  1138. 'You should have a line: "Copyright [year] <Copyright Owner>"')
  1139. def GetHeaderGuardCPPVariable(filename):
  1140. """Returns the CPP variable that should be used as a header guard.
  1141. Args:
  1142. filename: The name of a C++ header file.
  1143. Returns:
  1144. The CPP variable that should be used as a header guard in the
  1145. named file.
  1146. """
  1147. # Restores original filename in case that cpplint is invoked from Emacs's
  1148. # flymake.
  1149. filename = re.sub(r'_flymake\.h$', '.h', filename)
  1150. filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
  1151. fileinfo = FileInfo(filename)
  1152. file_path_from_root = fileinfo.RepositoryName()
  1153. if _root:
  1154. file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
  1155. return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
  1156. def CheckForHeaderGuard(filename, lines, error):
  1157. """Checks that the file contains a header guard.
  1158. Logs an error if no #ifndef header guard is present. For other
  1159. headers, checks that the full pathname is used.
  1160. Args:
  1161. filename: The name of the C++ header file.
  1162. lines: An array of strings, each representing a line of the file.
  1163. error: The function to call with any errors found.
  1164. """
  1165. cppvar = GetHeaderGuardCPPVariable(filename)
  1166. ifndef = None
  1167. ifndef_linenum = 0
  1168. define = None
  1169. endif = None
  1170. endif_linenum = 0
  1171. for linenum, line in enumerate(lines):
  1172. linesplit = line.split()
  1173. if len(linesplit) >= 2:
  1174. # find the first occurrence of #ifndef and #define, save arg
  1175. if not ifndef and linesplit[0] == '#ifndef':
  1176. # set ifndef to the header guard presented on the #ifndef line.
  1177. ifndef = linesplit[1]
  1178. ifndef_linenum = linenum
  1179. if not define and linesplit[0] == '#define':
  1180. define = linesplit[1]
  1181. # find the last occurrence of #endif, save entire line
  1182. if line.startswith('#endif'):
  1183. endif = line
  1184. endif_linenum = linenum
  1185. if not ifndef:
  1186. error(filename, 0, 'build/header_guard', 5,
  1187. 'No #ifndef header guard found, suggested CPP variable is: %s' %
  1188. cppvar)
  1189. return
  1190. if not define:
  1191. error(filename, 0, 'build/header_guard', 5,
  1192. 'No #define header guard found, suggested CPP variable is: %s' %
  1193. cppvar)
  1194. return
  1195. # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
  1196. # for backward compatibility.
  1197. if ifndef != cppvar:
  1198. error_level = 0
  1199. if ifndef != cppvar + '_':
  1200. error_level = 5
  1201. ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum,
  1202. error)
  1203. error(filename, ifndef_linenum, 'build/header_guard', error_level,
  1204. '#ifndef header guard has wrong style, please use: %s' % cppvar)
  1205. if define != ifndef:
  1206. error(filename, 0, 'build/header_guard', 5,
  1207. '#ifndef and #define don\'t match, suggested CPP variable is: %s' %
  1208. cppvar)
  1209. return
  1210. if endif != ('#endif // %s' % cppvar):
  1211. error_level = 0
  1212. if endif != ('#endif // %s' % (cppvar + '_')):
  1213. error_level = 5
  1214. ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum,
  1215. error)
  1216. error(filename, endif_linenum, 'build/header_guard', error_level,
  1217. '#endif line should be "#endif // %s"' % cppvar)
  1218. def CheckForBadCharacters(filename, lines, error):
  1219. """Logs an error for each line containing bad characters.
  1220. Two kinds of bad characters:
  1221. 1. Unicode replacement characters: These indicate that either the file
  1222. contained invalid UTF-8 (likely) or Unicode replacement characters (which
  1223. it shouldn't). Note that it's possible for this to throw off line
  1224. numbering if the invalid UTF-8 occurred adjacent to a newline.
  1225. 2. NUL bytes. These are problematic for some tools.
  1226. Args:
  1227. filename: The name of the current file.
  1228. lines: An array of strings, each representing a line of the file.
  1229. error: The function to call with any errors found.
  1230. """
  1231. for linenum, line in enumerate(lines):
  1232. if u'\ufffd' in line:
  1233. error(filename, linenum, 'readability/utf8', 5,
  1234. 'Line contains invalid UTF-8 (or Unicode replacement character).')
  1235. if '\0' in line:
  1236. error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
  1237. def CheckForNewlineAtEOF(filename, lines, error):
  1238. """Logs an error if there is no newline char at the end of the file.
  1239. Args:
  1240. filename: The name of the current file.
  1241. lines: An array of strings, each representing a line of the file.
  1242. error: The function to call with any errors found.
  1243. """
  1244. # The array lines() was created by adding two newlines to the
  1245. # original file (go figure), then splitting on \n.
  1246. # To verify that the file ends in \n, we just have to make sure the
  1247. # last-but-two element of lines() exists and is empty.
  1248. if len(lines) < 3 or lines[-2]:
  1249. error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
  1250. 'Could not find a newline character at the end of the file.')
  1251. def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
  1252. """Logs an error if we see /* ... */ or "..." that extend past one line.
  1253. /* ... */ comments are legit inside macros, for one line.
  1254. Otherwise, we prefer // comments, so it's ok to warn about the
  1255. other. Likewise, it's ok for strings to extend across multiple
  1256. lines, as long as a line continuation character (backslash)
  1257. terminates each line. Although not currently prohibited by the C++
  1258. style guide, it's ugly and unnecessary. We don't do well with either
  1259. in this lint program, so we warn about both.
  1260. Args:
  1261. filename: The name of the current file.
  1262. clean_lines: A CleansedLines instance containing the file.
  1263. linenum: The number of the line to check.
  1264. error: The function to call with any errors found.
  1265. """
  1266. line = clean_lines.elided[linenum]
  1267. # Remove all \\ (escaped backslashes) from the line. They are OK, and the
  1268. # second (escaped) slash may trigger later \" detection erroneously.
  1269. line = line.replace('\\\\', '')
  1270. if line.count('/*') > line.count('*/'):
  1271. error(filename, linenum, 'readability/multiline_comment', 5,
  1272. 'Complex multi-line /*...*/-style comment found. '
  1273. 'Lint may give bogus warnings. '
  1274. 'Consider replacing these with //-style comments, '
  1275. 'with #if 0...#endif, '
  1276. 'or with more clearly structured multi-line comments.')
  1277. if (line.count('"') - line.count('\\"')) % 2:
  1278. error(filename, linenum, 'readability/multiline_string', 5,
  1279. 'Multi-line string ("...") found. This lint script doesn\'t '
  1280. 'do well with such strings, and may give bogus warnings. '
  1281. 'Use C++11 raw strings or concatenation instead.')
  1282. threading_list = (
  1283. ('asctime(', 'asctime_r('),
  1284. ('ctime(', 'ctime_r('),
  1285. ('getgrgid(', 'getgrgid_r('),
  1286. ('getgrnam(', 'getgrnam_r('),
  1287. ('getlogin(', 'getlogin_r('),
  1288. ('getpwnam(', 'getpwnam_r('),
  1289. ('getpwuid(', 'getpwuid_r('),
  1290. ('gmtime(', 'gmtime_r('),
  1291. ('localtime(', 'localtime_r('),
  1292. ('rand(', 'rand_r('),
  1293. ('strtok(', 'strtok_r('),
  1294. ('ttyname(', 'ttyname_r('),
  1295. )
  1296. def CheckPosixThreading(filename, clean_lines, linenum, error):
  1297. """Checks for calls to thread-unsafe functions.
  1298. Much code has been originally written without consideration of
  1299. multi-threading. Also, engineers are relying on their old experience;
  1300. they have learned posix before threading extensions were added. These
  1301. tests guide the engineers to use thread-safe functions (when using
  1302. posix directly).
  1303. Args:
  1304. filename: The name of the current file.
  1305. clean_lines: A CleansedLines instance containing the file.
  1306. linenum: The number of the line to check.
  1307. error: The function to call with any errors found.
  1308. """
  1309. line = clean_lines.elided[linenum]
  1310. for single_thread_function, multithread_safe_function in threading_list:
  1311. ix = line.find(single_thread_function)
  1312. # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
  1313. if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
  1314. line[ix - 1] not in ('_', '.', '>'))):
  1315. error(filename, linenum, 'runtime/threadsafe_fn', 2,
  1316. 'Consider using ' + multithread_safe_function +
  1317. '...) instead of ' + single_thread_function +
  1318. '...) for improved thread safety.')
  1319. def CheckVlogArguments(filename, clean_lines, linenum, error):
  1320. """Checks that VLOG() is only used for defining a logging level.
  1321. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
  1322. VLOG(FATAL) are not.
  1323. Args:
  1324. filename: The name of the current file.
  1325. clean_lines: A CleansedLines instance containing the file.
  1326. linenum: The number of the line to check.
  1327. error: The function to call with any errors found.
  1328. """
  1329. line = clean_lines.elided[linenum]
  1330. if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
  1331. error(filename, linenum, 'runtime/vlog', 5,
  1332. 'VLOG() should be used with numeric verbosity level. '
  1333. 'Use LOG() if you want symbolic severity levels.')
  1334. # Matches invalid increment: *count++, which moves pointer instead of
  1335. # incrementing a value.
  1336. _RE_PATTERN_INVALID_INCREMENT = re.compile(
  1337. r'^\s*\*\w+(\+\+|--);')
  1338. def CheckInvalidIncrement(filename, clean_lines, linenum, error):
  1339. """Checks for invalid increment *count++.
  1340. For example following function:
  1341. void increment_counter(int* count) {
  1342. *count++;
  1343. }
  1344. is invalid, because it effectively does count++, moving pointer, and should
  1345. be replaced with ++*count, (*count)++ or *count += 1.
  1346. Args:
  1347. filename: The name of the current file.
  1348. clean_lines: A CleansedLines instance containing the file.
  1349. linenum: The number of the line to check.
  1350. error: The function to call with any errors found.
  1351. """
  1352. line = clean_lines.elided[linenum]
  1353. if _RE_PATTERN_INVALID_INCREMENT.match(line):
  1354. error(filename, linenum, 'runtime/invalid_increment', 5,
  1355. 'Changing pointer instead of value (or unused value of operator*).')
  1356. class _BlockInfo(object):
  1357. """Stores information about a generic block of code."""
  1358. def __init__(self, seen_open_brace):
  1359. self.seen_open_brace = seen_open_brace
  1360. self.open_parentheses = 0
  1361. self.inline_asm = _NO_ASM
  1362. def CheckBegin(self, filename, clean_lines, linenum, error):
  1363. """Run checks that applies to text up to the opening brace.
  1364. This is mostly for checking the text after the class identifier
  1365. and the "{", usually where the base class is specified. For other
  1366. blocks, there isn't much to check, so we always pass.
  1367. Args:
  1368. filename: The name of the current file.
  1369. clean_lines: A CleansedLines instance containing the file.
  1370. linenum: The number of the line to check.
  1371. error: The function to call with any errors found.
  1372. """
  1373. pass
  1374. def CheckEnd(self, filename, clean_lines, linenum, error):
  1375. """Run checks that applies to text after the closing brace.
  1376. This is mostly used for checking end of namespace comments.
  1377. Args:
  1378. filename: The name of the current file.
  1379. clean_lines: A CleansedLines instance containing the file.
  1380. linenum: The number of the line to check.
  1381. error: The function to call with any errors found.
  1382. """
  1383. pass
  1384. class _ClassInfo(_BlockInfo):
  1385. """Stores information about a class."""
  1386. def __init__(self, name, class_or_struct, clean_lines, linenum):
  1387. _BlockInfo.__init__(self, False)
  1388. self.name = name
  1389. self.starting_linenum = linenum
  1390. self.is_derived = False
  1391. if class_or_struct == 'struct':
  1392. self.access = 'public'
  1393. self.is_struct = True
  1394. else:
  1395. self.access = 'private'
  1396. self.is_struct = False
  1397. # Remember initial indentation level for this class. Using raw_lines here
  1398. # instead of elided to account for leading comments.
  1399. initial_indent = Match(r'^( *)\S', clean_lines.raw_lines[linenum])
  1400. if initial_indent:
  1401. self.class_indent = len(initial_indent.group(1))
  1402. else:
  1403. self.class_indent = 0
  1404. # Try to find the end of the class. This will be confused by things like:
  1405. # class A {
  1406. # } *x = { ...
  1407. #
  1408. # But it's still good enough for CheckSectionSpacing.
  1409. self.last_line = 0
  1410. depth = 0
  1411. for i in range(linenum, clean_lines.NumLines()):
  1412. line = clean_lines.elided[i]
  1413. depth += line.count('{') - line.count('}')
  1414. if not depth:
  1415. self.last_line = i
  1416. break
  1417. def CheckBegin(self, filename, clean_lines, linenum, error):
  1418. # Look for a bare ':'
  1419. if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
  1420. self.is_derived = True
  1421. def CheckEnd(self, filename, clean_lines, linenum, error):
  1422. # Check that closing brace is aligned with beginning of the class.
  1423. # Only do this if the closing brace is indented by only whitespaces.
  1424. # This means we will not check single-line class definitions.
  1425. indent = Match(r'^( *)\}', clean_lines.elided[linenum])
  1426. if indent and len(indent.group(1)) != self.class_indent:
  1427. if self.is_struct:
  1428. parent = 'struct ' + self.name
  1429. else:
  1430. parent = 'class ' + self.name
  1431. error(filename, linenum, 'whitespace/indent', 3,
  1432. 'Closing brace should be aligned with beginning of %s' % parent)
  1433. class _NamespaceInfo(_BlockInfo):
  1434. """Stores information about a namespace."""
  1435. def __init__(self, name, linenum):
  1436. _BlockInfo.__init__(self, False)
  1437. self.name = name or ''
  1438. self.starting_linenum = linenum
  1439. def CheckEnd(self, filename, clean_lines, linenum, error):
  1440. """Check end of namespace comments."""
  1441. line = clean_lines.raw_lines[linenum]
  1442. # Check how many lines is enclosed in this namespace. Don't issue
  1443. # warning for missing namespace comments if there aren't enough
  1444. # lines. However, do apply checks if there is already an end of
  1445. # namespace comment and it's incorrect.
  1446. #
  1447. # TODO(unknown): We always want to check end of namespace comments
  1448. # if a namespace is large, but sometimes we also want to apply the
  1449. # check if a short namespace contained nontrivial things (something
  1450. # other than forward declarations). There is currently no logic on
  1451. # deciding what these nontrivial things are, so this check is
  1452. # triggered by namespace size only, which works most of the time.
  1453. if (linenum - self.starting_linenum < 10
  1454. and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
  1455. return
  1456. # Look for matching comment at end of namespace.
  1457. #
  1458. # Note that we accept C style "/* */" comments for terminating
  1459. # namespaces, so that code that terminate namespaces inside
  1460. # preprocessor macros can be cpplint clean.
  1461. #
  1462. # We also accept stuff like "// end of namespace <name>." with the
  1463. # period at the end.
  1464. #
  1465. # Besides these, we don't accept anything else, otherwise we might
  1466. # get false negatives when existing comment is a substring of the
  1467. # expected namespace.
  1468. if self.name:
  1469. # Named namespace
  1470. if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
  1471. r'[\*/\.\\\s]*$'),
  1472. line):
  1473. error(filename, linenum, 'readability/namespace', 5,
  1474. 'Namespace should be terminated with "// namespace %s"' %
  1475. self.name)
  1476. else:
  1477. # Anonymous namespace
  1478. if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
  1479. error(filename, linenum, 'readability/namespace', 5,
  1480. 'Namespace should be terminated with "// namespace"')
  1481. class _PreprocessorInfo(object):
  1482. """Stores checkpoints of nesting stacks when #if/#else is seen."""
  1483. def __init__(self, stack_before_if):
  1484. # The entire nesting stack before #if
  1485. self.stack_before_if = stack_before_if
  1486. # The entire nesting stack up to #else
  1487. self.stack_before_else = []
  1488. # Whether we have already seen #else or #elif
  1489. self.seen_else = False
  1490. class _NestingState(object):
  1491. """Holds states related to parsing braces."""
  1492. def __init__(self):
  1493. # Stack for tracking all braces. An object is pushed whenever we
  1494. # see a "{", and popped when we see a "}". Only 3 types of
  1495. # objects are possible:
  1496. # - _ClassInfo: a class or struct.
  1497. # - _NamespaceInfo: a namespace.
  1498. # - _BlockInfo: some other type of block.
  1499. self.stack = []
  1500. # Stack of _PreprocessorInfo objects.
  1501. self.pp_stack = []
  1502. def SeenOpenBrace(self):
  1503. """Check if we have seen the opening brace for the innermost block.
  1504. Returns:
  1505. True if we have seen the opening brace, False if the innermost
  1506. block is still expecting an opening brace.
  1507. """
  1508. return (not self.stack) or self.stack[-1].seen_open_brace
  1509. def InNamespaceBody(self):
  1510. """Check if we are currently one level inside a namespace body.
  1511. Returns:
  1512. True if top of the stack is a namespace block, False otherwise.
  1513. """
  1514. return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
  1515. def UpdatePreprocessor(self, line):
  1516. """Update preprocessor stack.
  1517. We need to handle preprocessors due to classes like this:
  1518. #ifdef SWIG
  1519. struct ResultDetailsPageElementExtensionPoint {
  1520. #else
  1521. struct ResultDetailsPageElementExtensionPoint : public Extension {
  1522. #endif
  1523. We make the following assumptions (good enough for most files):
  1524. - Preprocessor condition evaluates to true from #if up to first
  1525. #else/#elif/#endif.
  1526. - Preprocessor condition evaluates to false from #else/#elif up
  1527. to #endif. We still perform lint checks on these lines, but
  1528. these do not affect nesting stack.
  1529. Args:
  1530. line: current line to check.
  1531. """
  1532. if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
  1533. # Beginning of #if block, save the nesting stack here. The saved
  1534. # stack will allow us to restore the parsing state in the #else case.
  1535. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
  1536. elif Match(r'^\s*#\s*(else|elif)\b', line):
  1537. # Beginning of #else block
  1538. if self.pp_stack:
  1539. if not self.pp_stack[-1].seen_else:
  1540. # This is the first #else or #elif block. Remember the
  1541. # whole nesting stack up to this point. This is what we
  1542. # keep after the #endif.
  1543. self.pp_stack[-1].seen_else = True
  1544. self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
  1545. # Restore the stack to how it was before the #if
  1546. self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
  1547. else:
  1548. # TODO(unknown): unexpected #else, issue warning?
  1549. pass
  1550. elif Match(r'^\s*#\s*endif\b', line):
  1551. # End of #if or #else blocks.
  1552. if self.pp_stack:
  1553. # If we saw an #else, we will need to restore the nesting
  1554. # stack to its former state before the #else, otherwise we
  1555. # will just continue from where we left off.
  1556. if self.pp_stack[-1].seen_else:
  1557. # Here we can just use a shallow copy since we are the last
  1558. # reference to it.
  1559. self.stack = self.pp_stack[-1].stack_before_else
  1560. # Drop the corresponding #if
  1561. self.pp_stack.pop()
  1562. else:
  1563. # TODO(unknown): unexpected #endif, issue warning?
  1564. pass
  1565. def Update(self, filename, clean_lines, linenum, error):
  1566. """Update nesting state with current line.
  1567. Args:
  1568. filename: The name of the current file.
  1569. clean_lines: A CleansedLines instance containing the file.
  1570. linenum: The number of the line to check.
  1571. error: The function to call with any errors found.
  1572. """
  1573. line = clean_lines.elided[linenum]
  1574. # Update pp_stack first
  1575. self.UpdatePreprocessor(line)
  1576. # Count parentheses. This is to avoid adding struct arguments to
  1577. # the nesting stack.
  1578. if self.stack:
  1579. inner_block = self.stack[-1]
  1580. depth_change = line.count('(') - line.count(')')
  1581. inner_block.open_parentheses += depth_change
  1582. # Also check if we are starting or ending an inline assembly block.
  1583. if inner_block.inline_asm in (_NO_ASM, _END_ASM):
  1584. if (depth_change != 0 and
  1585. inner_block.open_parentheses == 1 and
  1586. _MATCH_ASM.match(line)):
  1587. # Enter assembly block
  1588. inner_block.inline_asm = _INSIDE_ASM
  1589. else:
  1590. # Not entering assembly block. If previous line was _END_ASM,
  1591. # we will now shift to _NO_ASM state.
  1592. inner_block.inline_asm = _NO_ASM
  1593. elif (inner_block.inline_asm == _INSIDE_ASM and
  1594. inner_block.open_parentheses == 0):
  1595. # Exit assembly block
  1596. inner_block.inline_asm = _END_ASM
  1597. # Consume namespace declaration at the beginning of the line. Do
  1598. # this in a loop so that we catch same line declarations like this:
  1599. # namespace proto2 { namespace bridge { class MessageSet; } }
  1600. while True:
  1601. # Match start of namespace. The "\b\s*" below catches namespace
  1602. # declarations even if it weren't followed by a whitespace, this
  1603. # is so that we don't confuse our namespace checker. The
  1604. # missing spaces will be flagged by CheckSpacing.
  1605. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
  1606. if not namespace_decl_match:
  1607. break
  1608. new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
  1609. self.stack.append(new_namespace)
  1610. line = namespace_decl_match.group(2)
  1611. if line.find('{') != -1:
  1612. new_namespace.seen_open_brace = True
  1613. line = line[line.find('{') + 1:]
  1614. # Look for a class declaration in whatever is left of the line
  1615. # after parsing namespaces. The regexp accounts for decorated classes
  1616. # such as in:
  1617. # class LOCKABLE API Object {
  1618. # };
  1619. #
  1620. # Templates with class arguments may confuse the parser, for example:
  1621. # template <class T
  1622. # class Comparator = less<T>,
  1623. # class Vector = vector<T> >
  1624. # class HeapQueue {
  1625. #
  1626. # Because this parser has no nesting state about templates, by the
  1627. # time it saw "class Comparator", it may think that it's a new class.
  1628. # Nested templates have a similar problem:
  1629. # template <
  1630. # typename ExportedType,
  1631. # typename TupleType,
  1632. # template <typename, typename> class ImplTemplate>
  1633. #
  1634. # To avoid these cases, we ignore classes that are followed by '=' or '>'
  1635. class_decl_match = Match(
  1636. r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
  1637. r'(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)'
  1638. r'(([^=>]|<[^<>]*>|<[^<>]*<[^<>]*>\s*>)*)$', line)
  1639. if (class_decl_match and
  1640. (not self.stack or self.stack[-1].open_parentheses == 0)):
  1641. self.stack.append(_ClassInfo(
  1642. class_decl_match.group(4), class_decl_match.group(2),
  1643. clean_lines, linenum))
  1644. line = class_decl_match.group(5)
  1645. # If we have not yet seen the opening brace for the innermost block,
  1646. # run checks here.
  1647. if not self.SeenOpenBrace():
  1648. self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
  1649. # Update access control if we are inside a class/struct
  1650. if self.stack and isinstance(self.stack[-1], _ClassInfo):
  1651. classinfo = self.stack[-1]
  1652. access_match = Match(
  1653. r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
  1654. r':(?:[^:]|$)',
  1655. line)
  1656. if access_match:
  1657. classinfo.access = access_match.group(2)
  1658. # Check that access keywords are indented +1 space. Skip this
  1659. # check if the keywords are not preceded by whitespaces.
  1660. indent = access_match.group(1)
  1661. if (len(indent) != classinfo.class_indent + 1 and
  1662. Match(r'^\s*$', indent)):
  1663. if classinfo.is_struct:
  1664. parent = 'struct ' + classinfo.name
  1665. else:
  1666. parent = 'class ' + classinfo.name
  1667. slots = ''
  1668. if access_match.group(3):
  1669. slots = access_match.group(3)
  1670. error(filename, linenum, 'whitespace/indent', 3,
  1671. '%s%s: should be indented +1 space inside %s' % (
  1672. access_match.group(2), slots, parent))
  1673. # Consume braces or semicolons from what's left of the line
  1674. while True:
  1675. # Match first brace, semicolon, or closed parenthesis.
  1676. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
  1677. if not matched:
  1678. break
  1679. token = matched.group(1)
  1680. if token == '{':
  1681. # If namespace or class hasn't seen a opening brace yet, mark
  1682. # namespace/class head as complete. Push a new block onto the
  1683. # stack otherwise.
  1684. if not self.SeenOpenBrace():
  1685. self.stack[-1].seen_open_brace = True
  1686. else:
  1687. self.stack.append(_BlockInfo(True))
  1688. if _MATCH_ASM.match(line):
  1689. self.stack[-1].inline_asm = _BLOCK_ASM
  1690. elif token == ';' or token == ')':
  1691. # If we haven't seen an opening brace yet, but we already saw
  1692. # a semicolon, this is probably a forward declaration. Pop
  1693. # the stack for these.
  1694. #
  1695. # Similarly, if we haven't seen an opening brace yet, but we
  1696. # already saw a closing parenthesis, then these are probably
  1697. # function arguments with extra "class" or "struct" keywords.
  1698. # Also pop these stack for these.
  1699. if not self.SeenOpenBrace():
  1700. self.stack.pop()
  1701. else: # token == '}'
  1702. # Perform end of block checks and pop the stack.
  1703. if self.stack:
  1704. self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
  1705. self.stack.pop()
  1706. line = matched.group(2)
  1707. def InnermostClass(self):
  1708. """Get class info on the top of the stack.
  1709. Returns:
  1710. A _ClassInfo object if we are inside a class, or None otherwise.
  1711. """
  1712. for i in range(len(self.stack), 0, -1):
  1713. classinfo = self.stack[i - 1]
  1714. if isinstance(classinfo, _ClassInfo):
  1715. return classinfo
  1716. return None
  1717. def CheckCompletedBlocks(self, filename, error):
  1718. """Checks that all classes and namespaces have been completely parsed.
  1719. Call this when all lines in a file have been processed.
  1720. Args:
  1721. filename: The name of the current file.
  1722. error: The function to call with any errors found.
  1723. """
  1724. # Note: This test can result in false positives if #ifdef constructs
  1725. # get in the way of brace matching. See the testBuildClass test in
  1726. # cpplint_unittest.py for an example of this.
  1727. for obj in self.stack:
  1728. if isinstance(obj, _ClassInfo):
  1729. error(filename, obj.starting_linenum, 'build/class', 5,
  1730. 'Failed to find complete declaration of class %s' %
  1731. obj.name)
  1732. elif isinstance(obj, _NamespaceInfo):
  1733. error(filename, obj.starting_linenum, 'build/namespaces', 5,
  1734. 'Failed to find complete declaration of namespace %s' %
  1735. obj.name)
  1736. def CheckForNonStandardConstructs(filename, clean_lines, linenum,
  1737. nesting_state, error):
  1738. r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
  1739. Complain about several constructs which gcc-2 accepts, but which are
  1740. not standard C++. Warning about these in lint is one way to ease the
  1741. transition to new compilers.
  1742. - put storage class first (e.g. "static const" instead of "const static").
  1743. - "%lld" instead of %qd" in printf-type functions.
  1744. - "%1$d" is non-standard in printf-type functions.
  1745. - "\%" is an undefined character escape sequence.
  1746. - text after #endif is not allowed.
  1747. - invalid inner-style forward declaration.
  1748. - >? and <? operators, and their >?= and <?= cousins.
  1749. Additionally, check for constructor/destructor style violations and reference
  1750. members, as it is very convenient to do so while checking for
  1751. gcc-2 compliance.
  1752. Args:
  1753. filename: The name of the current file.
  1754. clean_lines: A CleansedLines instance containing the file.
  1755. linenum: The number of the line to check.
  1756. nesting_state: A _NestingState instance which maintains information about
  1757. the current stack of nested blocks being parsed.
  1758. error: A callable to which errors are reported, which takes 4 arguments:
  1759. filename, line number, error level, and message
  1760. """
  1761. # Remove comments from the line, but leave in strings for now.
  1762. line = clean_lines.lines[linenum]
  1763. if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
  1764. error(filename, linenum, 'runtime/printf_format', 3,
  1765. '%q in format strings is deprecated. Use %ll instead.')
  1766. if Search(r'printf\s*\(.*".*%\d+\$', line):
  1767. error(filename, linenum, 'runtime/printf_format', 2,
  1768. '%N$ formats are unconventional. Try rewriting to avoid them.')
  1769. # Remove escaped backslashes before looking for undefined escapes.
  1770. line = line.replace('\\\\', '')
  1771. if Search(r'("|\').*\\(%|\[|\(|{)', line):
  1772. error(filename, linenum, 'build/printf_format', 3,
  1773. '%, [, (, and { are undefined character escapes. Unescape them.')
  1774. # For the rest, work with both comments and strings removed.
  1775. line = clean_lines.elided[linenum]
  1776. if Search(r'\b(const|volatile|void|char|short|int|long'
  1777. r'|float|double|signed|unsigned'
  1778. r'|schar|u?int8|u?int16|u?int32|u?int64)'
  1779. r'\s+(register|static|extern|typedef)\b',
  1780. line):
  1781. error(filename, linenum, 'build/storage_class', 5,
  1782. 'Storage class (static, extern, typedef, etc) should be first.')
  1783. if Match(r'\s*#\s*endif\s*[^/\s]+', line):
  1784. error(filename, linenum, 'build/endif_comment', 5,
  1785. 'Uncommented text after #endif is non-standard. Use a comment.')
  1786. if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
  1787. error(filename, linenum, 'build/forward_decl', 5,
  1788. 'Inner-style forward declarations are invalid. Remove this line.')
  1789. if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
  1790. line):
  1791. error(filename, linenum, 'build/deprecated', 3,
  1792. '>? and <? (max and min) operators are non-standard and deprecated.')
  1793. if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
  1794. # TODO(unknown): Could it be expanded safely to arbitrary references,
  1795. # without triggering too many false positives? The first
  1796. # attempt triggered 5 warnings for mostly benign code in the regtest, hence
  1797. # the restriction.
  1798. # Here's the original regexp, for the reference:
  1799. # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
  1800. # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
  1801. error(filename, linenum, 'runtime/member_string_references', 2,
  1802. 'const string& members are dangerous. It is much better to use '
  1803. 'alternatives, such as pointers or simple constants.')
  1804. # Everything else in this function operates on class declarations.
  1805. # Return early if the top of the nesting stack is not a class, or if
  1806. # the class head is not completed yet.
  1807. classinfo = nesting_state.InnermostClass()
  1808. if not classinfo or not classinfo.seen_open_brace:
  1809. return
  1810. # The class may have been declared with namespace or classname qualifiers.
  1811. # The constructor and destructor will not have those qualifiers.
  1812. base_classname = classinfo.name.split('::')[-1]
  1813. # Look for single-argument constructors that aren't marked explicit.
  1814. # Technically a valid construct, but against style.
  1815. args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
  1816. % re.escape(base_classname),
  1817. line)
  1818. if (args and
  1819. args.group(1) != 'void' and
  1820. not Match(r'(const\s+)?%s(\s+const)?\s*(?:<\w+>\s*)?&'
  1821. % re.escape(base_classname), args.group(1).strip())):
  1822. error(filename, linenum, 'runtime/explicit', 5,
  1823. 'Single-argument constructors should be marked explicit.')
  1824. def CheckSpacingForFunctionCall(filename, line, linenum, error):
  1825. """Checks for the correctness of various spacing around function calls.
  1826. Args:
  1827. filename: The name of the current file.
  1828. line: The text of the line to check.
  1829. linenum: The number of the line to check.
  1830. error: The function to call with any errors found.
  1831. """
  1832. # Since function calls often occur inside if/for/while/switch
  1833. # expressions - which have their own, more liberal conventions - we
  1834. # first see if we should be looking inside such an expression for a
  1835. # function call, to which we can apply more strict standards.
  1836. fncall = line # if there's no control flow construct, look at whole line
  1837. for pattern in (r'\bif\s*\((.*)\)\s*{',
  1838. r'\bfor\s*\((.*)\)\s*{',
  1839. r'\bwhile\s*\((.*)\)\s*[{;]',
  1840. r'\bswitch\s*\((.*)\)\s*{'):
  1841. match = Search(pattern, line)
  1842. if match:
  1843. fncall = match.group(1) # look inside the parens for function calls
  1844. break
  1845. # Except in if/for/while/switch, there should never be space
  1846. # immediately inside parens (eg "f( 3, 4 )"). We make an exception
  1847. # for nested parens ( (a+b) + c ). Likewise, there should never be
  1848. # a space before a ( when it's a function argument. I assume it's a
  1849. # function argument when the char before the whitespace is legal in
  1850. # a function name (alnum + _) and we're not starting a macro. Also ignore
  1851. # pointers and references to arrays and functions coz they're too tricky:
  1852. # we use a very simple way to recognize these:
  1853. # " (something)(maybe-something)" or
  1854. # " (something)(maybe-something," or
  1855. # " (something)[something]"
  1856. # Note that we assume the contents of [] to be short enough that
  1857. # they'll never need to wrap.
  1858. if ( # Ignore control structures.
  1859. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
  1860. fncall) and
  1861. # Ignore pointers/references to functions.
  1862. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
  1863. # Ignore pointers/references to arrays.
  1864. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
  1865. if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
  1866. error(filename, linenum, 'whitespace/parens', 4,
  1867. 'Extra space after ( in function call')
  1868. elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
  1869. error(filename, linenum, 'whitespace/parens', 2,
  1870. 'Extra space after (')
  1871. if (Search(r'\w\s+\(', fncall) and
  1872. not Search(r'#\s*define|typedef', fncall) and
  1873. not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall)):
  1874. error(filename, linenum, 'whitespace/parens', 4,
  1875. 'Extra space before ( in function call')
  1876. # If the ) is followed only by a newline or a { + newline, assume it's
  1877. # part of a control statement (if/while/etc), and don't complain
  1878. if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
  1879. # If the closing parenthesis is preceded by only whitespaces,
  1880. # try to give a more descriptive error message.
  1881. if Search(r'^\s+\)', fncall):
  1882. error(filename, linenum, 'whitespace/parens', 2,
  1883. 'Closing ) should be moved to the previous line')
  1884. else:
  1885. error(filename, linenum, 'whitespace/parens', 2,
  1886. 'Extra space before )')
  1887. def IsBlankLine(line):
  1888. """Returns true if the given line is blank.
  1889. We consider a line to be blank if the line is empty or consists of
  1890. only white spaces.
  1891. Args:
  1892. line: A line of a string.
  1893. Returns:
  1894. True, if the given line is blank.
  1895. """
  1896. return not line or line.isspace()
  1897. def CheckForFunctionLengths(filename, clean_lines, linenum,
  1898. function_state, error):
  1899. """Reports for long function bodies.
  1900. For an overview why this is done, see:
  1901. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
  1902. Uses a simplistic algorithm assuming other style guidelines
  1903. (especially spacing) are followed.
  1904. Only checks unindented functions, so class members are unchecked.
  1905. Trivial bodies are unchecked, so constructors with huge initializer lists
  1906. may be missed.
  1907. Blank/comment lines are not counted so as to avoid encouraging the removal
  1908. of vertical space and comments just to get through a lint check.
  1909. NOLINT *on the last line of a function* disables this check.
  1910. Args:
  1911. filename: The name of the current file.
  1912. clean_lines: A CleansedLines instance containing the file.
  1913. linenum: The number of the line to check.
  1914. function_state: Current function name and lines in body so far.
  1915. error: The function to call with any errors found.
  1916. """
  1917. lines = clean_lines.lines
  1918. line = lines[linenum]
  1919. raw = clean_lines.raw_lines
  1920. raw_line = raw[linenum]
  1921. joined_line = ''
  1922. starting_func = False
  1923. regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
  1924. match_result = Match(regexp, line)
  1925. if match_result:
  1926. # If the name is all caps and underscores, figure it's a macro and
  1927. # ignore it, unless it's TEST or TEST_F.
  1928. function_name = match_result.group(1).split()[-1]
  1929. if function_name == 'TEST' or function_name == 'TEST_F' or (
  1930. not Match(r'[A-Z_]+$', function_name)):
  1931. starting_func = True
  1932. if starting_func:
  1933. body_found = False
  1934. for start_linenum in xrange(linenum, clean_lines.NumLines()):
  1935. start_line = lines[start_linenum]
  1936. joined_line += ' ' + start_line.lstrip()
  1937. if Search(r'(;|})', start_line): # Declarations and trivial functions
  1938. body_found = True
  1939. break # ... ignore
  1940. elif Search(r'{', start_line):
  1941. body_found = True
  1942. function = Search(r'((\w|:)*)\(', line).group(1)
  1943. if Match(r'TEST', function): # Handle TEST... macros
  1944. parameter_regexp = Search(r'(\(.*\))', joined_line)
  1945. if parameter_regexp: # Ignore bad syntax
  1946. function += parameter_regexp.group(1)
  1947. else:
  1948. function += '()'
  1949. function_state.Begin(function)
  1950. break
  1951. if not body_found:
  1952. # No body for the function (or evidence of a non-function) was found.
  1953. error(filename, linenum, 'readability/fn_size', 5,
  1954. 'Lint failed to find start of function body.')
  1955. elif Match(r'^\}\s*$', line): # function end
  1956. function_state.Check(error, filename, linenum)
  1957. function_state.End()
  1958. elif not Match(r'^\s*$', line):
  1959. function_state.Count() # Count non-blank/non-comment lines.
  1960. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
  1961. def CheckComment(comment, filename, linenum, error):
  1962. """Checks for common mistakes in TODO comments.
  1963. Args:
  1964. comment: The text of the comment from the line in question.
  1965. filename: The name of the current file.
  1966. linenum: The number of the line to check.
  1967. error: The function to call with any errors found.
  1968. """
  1969. match = _RE_PATTERN_TODO.match(comment)
  1970. if match:
  1971. # One whitespace is correct; zero whitespace is handled elsewhere.
  1972. leading_whitespace = match.group(1)
  1973. if len(leading_whitespace) > 1:
  1974. error(filename, linenum, 'whitespace/todo', 2,
  1975. 'Too many spaces before TODO')
  1976. username = match.group(2)
  1977. if not username:
  1978. error(filename, linenum, 'readability/todo', 2,
  1979. 'Missing username in TODO; it should look like '
  1980. '"// TODO(my_username): Stuff."')
  1981. middle_whitespace = match.group(3)
  1982. # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
  1983. if middle_whitespace != ' ' and middle_whitespace != '':
  1984. error(filename, linenum, 'whitespace/todo', 2,
  1985. 'TODO(my_username) should be followed by a space')
  1986. def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
  1987. """Checks for improper use of DISALLOW* macros.
  1988. Args:
  1989. filename: The name of the current file.
  1990. clean_lines: A CleansedLines instance containing the file.
  1991. linenum: The number of the line to check.
  1992. nesting_state: A _NestingState instance which maintains information about
  1993. the current stack of nested blocks being parsed.
  1994. error: The function to call with any errors found.
  1995. """
  1996. line = clean_lines.elided[linenum] # get rid of comments and strings
  1997. matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
  1998. r'DISALLOW_EVIL_CONSTRUCTORS|'
  1999. r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
  2000. if not matched:
  2001. return
  2002. if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
  2003. if nesting_state.stack[-1].access != 'private':
  2004. error(filename, linenum, 'readability/constructors', 3,
  2005. '%s must be in the private: section' % matched.group(1))
  2006. else:
  2007. # Found DISALLOW* macro outside a class declaration, or perhaps it
  2008. # was used inside a function when it should have been part of the
  2009. # class declaration. We could issue a warning here, but it
  2010. # probably resulted in a compiler error already.
  2011. pass
  2012. def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
  2013. """Find the corresponding > to close a template.
  2014. Args:
  2015. clean_lines: A CleansedLines instance containing the file.
  2016. linenum: Current line number.
  2017. init_suffix: Remainder of the current line after the initial <.
  2018. Returns:
  2019. True if a matching bracket exists.
  2020. """
  2021. line = init_suffix
  2022. nesting_stack = ['<']
  2023. while True:
  2024. # Find the next operator that can tell us whether < is used as an
  2025. # opening bracket or as a less-than operator. We only want to
  2026. # warn on the latter case.
  2027. #
  2028. # We could also check all other operators and terminate the search
  2029. # early, e.g. if we got something like this "a<b+c", the "<" is
  2030. # most likely a less-than operator, but then we will get false
  2031. # positives for default arguments and other template expressions.
  2032. match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
  2033. if match:
  2034. # Found an operator, update nesting stack
  2035. operator = match.group(1)
  2036. line = match.group(2)
  2037. if nesting_stack[-1] == '<':
  2038. # Expecting closing angle bracket
  2039. if operator in ('<', '(', '['):
  2040. nesting_stack.append(operator)
  2041. elif operator == '>':
  2042. nesting_stack.pop()
  2043. if not nesting_stack:
  2044. # Found matching angle bracket
  2045. return True
  2046. elif operator == ',':
  2047. # Got a comma after a bracket, this is most likely a template
  2048. # argument. We have not seen a closing angle bracket yet, but
  2049. # it's probably a few lines later if we look for it, so just
  2050. # return early here.
  2051. return True
  2052. else:
  2053. # Got some other operator.
  2054. return False
  2055. else:
  2056. # Expecting closing parenthesis or closing bracket
  2057. if operator in ('<', '(', '['):
  2058. nesting_stack.append(operator)
  2059. elif operator in (')', ']'):
  2060. # We don't bother checking for matching () or []. If we got
  2061. # something like (] or [), it would have been a syntax error.
  2062. nesting_stack.pop()
  2063. else:
  2064. # Scan the next line
  2065. linenum += 1
  2066. if linenum >= len(clean_lines.elided):
  2067. break
  2068. line = clean_lines.elided[linenum]
  2069. # Exhausted all remaining lines and still no matching angle bracket.
  2070. # Most likely the input was incomplete, otherwise we should have
  2071. # seen a semicolon and returned early.
  2072. return True
  2073. def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix):
  2074. """Find the corresponding < that started a template.
  2075. Args:
  2076. clean_lines: A CleansedLines instance containing the file.
  2077. linenum: Current line number.
  2078. init_prefix: Part of the current line before the initial >.
  2079. Returns:
  2080. True if a matching bracket exists.
  2081. """
  2082. line = init_prefix
  2083. nesting_stack = ['>']
  2084. while True:
  2085. # Find the previous operator
  2086. match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line)
  2087. if match:
  2088. # Found an operator, update nesting stack
  2089. operator = match.group(2)
  2090. line = match.group(1)
  2091. if nesting_stack[-1] == '>':
  2092. # Expecting opening angle bracket
  2093. if operator in ('>', ')', ']'):
  2094. nesting_stack.append(operator)
  2095. elif operator == '<':
  2096. nesting_stack.pop()
  2097. if not nesting_stack:
  2098. # Found matching angle bracket
  2099. return True
  2100. elif operator == ',':
  2101. # Got a comma before a bracket, this is most likely a
  2102. # template argument. The opening angle bracket is probably
  2103. # there if we look for it, so just return early here.
  2104. return True
  2105. else:
  2106. # Got some other operator.
  2107. return False
  2108. else:
  2109. # Expecting opening parenthesis or opening bracket
  2110. if operator in ('>', ')', ']'):
  2111. nesting_stack.append(operator)
  2112. elif operator in ('(', '['):
  2113. nesting_stack.pop()
  2114. else:
  2115. # Scan the previous line
  2116. linenum -= 1
  2117. if linenum < 0:
  2118. break
  2119. line = clean_lines.elided[linenum]
  2120. # Exhausted all earlier lines and still no matching angle bracket.
  2121. return False
  2122. def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
  2123. """Checks for the correctness of various spacing issues in the code.
  2124. Things we check for: spaces around operators, spaces after
  2125. if/for/while/switch, no spaces around parens in function calls, two
  2126. spaces between code and comment, don't start a block with a blank
  2127. line, don't end a function with a blank line, don't add a blank line
  2128. after public/protected/private, don't have too many blank lines in a row.
  2129. Args:
  2130. filename: The name of the current file.
  2131. clean_lines: A CleansedLines instance containing the file.
  2132. linenum: The number of the line to check.
  2133. nesting_state: A _NestingState instance which maintains information about
  2134. the current stack of nested blocks being parsed.
  2135. error: The function to call with any errors found.
  2136. """
  2137. # Don't use "elided" lines here, otherwise we can't check commented lines.
  2138. # Don't want to use "raw" either, because we don't want to check inside C++11
  2139. # raw strings,
  2140. raw = clean_lines.lines_without_raw_strings
  2141. line = raw[linenum]
  2142. # Before nixing comments, check if the line is blank for no good
  2143. # reason. This includes the first line after a block is opened, and
  2144. # blank lines at the end of a function (ie, right before a line like '}'
  2145. #
  2146. # Skip all the blank line checks if we are immediately inside a
  2147. # namespace body. In other words, don't issue blank line warnings
  2148. # for this block:
  2149. # namespace {
  2150. #
  2151. # }
  2152. #
  2153. # A warning about missing end of namespace comments will be issued instead.
  2154. if IsBlankLine(line) and not nesting_state.InNamespaceBody():
  2155. elided = clean_lines.elided
  2156. prev_line = elided[linenum - 1]
  2157. prevbrace = prev_line.rfind('{')
  2158. # TODO(unknown): Don't complain if line before blank line, and line after,
  2159. # both start with alnums and are indented the same amount.
  2160. # This ignores whitespace at the start of a namespace block
  2161. # because those are not usually indented.
  2162. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
  2163. # OK, we have a blank line at the start of a code block. Before we
  2164. # complain, we check if it is an exception to the rule: The previous
  2165. # non-empty line has the parameters of a function header that are indented
  2166. # 4 spaces (because they did not fit in a 80 column line when placed on
  2167. # the same line as the function name). We also check for the case where
  2168. # the previous line is indented 6 spaces, which may happen when the
  2169. # initializers of a constructor do not fit into a 80 column line.
  2170. exception = False
  2171. if Match(r' {6}\w', prev_line): # Initializer list?
  2172. # We are looking for the opening column of initializer list, which
  2173. # should be indented 4 spaces to cause 6 space indentation afterwards.
  2174. search_position = linenum-2
  2175. while (search_position >= 0
  2176. and Match(r' {6}\w', elided[search_position])):
  2177. search_position -= 1
  2178. exception = (search_position >= 0
  2179. and elided[search_position][:5] == ' :')
  2180. else:
  2181. # Search for the function arguments or an initializer list. We use a
  2182. # simple heuristic here: If the line is indented 4 spaces; and we have a
  2183. # closing paren, without the opening paren, followed by an opening brace
  2184. # or colon (for initializer lists) we assume that it is the last line of
  2185. # a function header. If we have a colon indented 4 spaces, it is an
  2186. # initializer list.
  2187. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
  2188. prev_line)
  2189. or Match(r' {4}:', prev_line))
  2190. if not exception:
  2191. error(filename, linenum, 'whitespace/blank_line', 2,
  2192. 'Redundant blank line at the start of a code block '
  2193. 'should be deleted.')
  2194. # Ignore blank lines at the end of a block in a long if-else
  2195. # chain, like this:
  2196. # if (condition1) {
  2197. # // Something followed by a blank line
  2198. #
  2199. # } else if (condition2) {
  2200. # // Something else
  2201. # }
  2202. if linenum + 1 < clean_lines.NumLines():
  2203. next_line = raw[linenum + 1]
  2204. if (next_line
  2205. and Match(r'\s*}', next_line)
  2206. and next_line.find('} else ') == -1):
  2207. error(filename, linenum, 'whitespace/blank_line', 3,
  2208. 'Redundant blank line at the end of a code block '
  2209. 'should be deleted.')
  2210. matched = Match(r'\s*(public|protected|private):', prev_line)
  2211. if matched:
  2212. error(filename, linenum, 'whitespace/blank_line', 3,
  2213. 'Do not leave a blank line after "%s:"' % matched.group(1))
  2214. # Next, we complain if there's a comment too near the text
  2215. commentpos = line.find('//')
  2216. if commentpos != -1:
  2217. # Check if the // may be in quotes. If so, ignore it
  2218. # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
  2219. if (line.count('"', 0, commentpos) -
  2220. line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
  2221. # Allow one space for new scopes, two spaces otherwise:
  2222. if (not Match(r'^\s*{ //', line) and
  2223. ((commentpos >= 1 and
  2224. line[commentpos-1] not in string.whitespace) or
  2225. (commentpos >= 2 and
  2226. line[commentpos-2] not in string.whitespace))):
  2227. error(filename, linenum, 'whitespace/comments', 2,
  2228. 'At least two spaces is best between code and comments')
  2229. # There should always be a space between the // and the comment
  2230. commentend = commentpos + 2
  2231. if commentend < len(line) and not line[commentend] == ' ':
  2232. # but some lines are exceptions -- e.g. if they're big
  2233. # comment delimiters like:
  2234. # //----------------------------------------------------------
  2235. # or are an empty C++ style Doxygen comment, like:
  2236. # ///
  2237. # or C++ style Doxygen comments placed after the variable:
  2238. # ///< Header comment
  2239. # //!< Header comment
  2240. # or they begin with multiple slashes followed by a space:
  2241. # //////// Header comment
  2242. match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
  2243. Search(r'^/$', line[commentend:]) or
  2244. Search(r'^!< ', line[commentend:]) or
  2245. Search(r'^/< ', line[commentend:]) or
  2246. Search(r'^/+ ', line[commentend:]))
  2247. if not match:
  2248. error(filename, linenum, 'whitespace/comments', 4,
  2249. 'Should have a space between // and comment')
  2250. CheckComment(line[commentpos:], filename, linenum, error)
  2251. line = clean_lines.elided[linenum] # get rid of comments and strings
  2252. # Don't try to do spacing checks for operator methods
  2253. line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
  2254. # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
  2255. # Otherwise not. Note we only check for non-spaces on *both* sides;
  2256. # sometimes people put non-spaces on one side when aligning ='s among
  2257. # many lines (not that this is behavior that I approve of...)
  2258. if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
  2259. error(filename, linenum, 'whitespace/operators', 4,
  2260. 'Missing spaces around =')
  2261. # It's ok not to have spaces around binary operators like + - * /, but if
  2262. # there's too little whitespace, we get concerned. It's hard to tell,
  2263. # though, so we punt on this one for now. TODO.
  2264. # You should always have whitespace around binary operators.
  2265. #
  2266. # Check <= and >= first to avoid false positives with < and >, then
  2267. # check non-include lines for spacing around < and >.
  2268. match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
  2269. if match:
  2270. error(filename, linenum, 'whitespace/operators', 3,
  2271. 'Missing spaces around %s' % match.group(1))
  2272. # We allow no-spaces around << when used like this: 10<<20, but
  2273. # not otherwise (particularly, not when used as streams)
  2274. # Also ignore using ns::operator<<;
  2275. match = Search(r'(operator|\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
  2276. if (match and
  2277. not (match.group(1).isdigit() and match.group(2).isdigit()) and
  2278. not (match.group(1) == 'operator' and match.group(2) == ';')):
  2279. error(filename, linenum, 'whitespace/operators', 3,
  2280. 'Missing spaces around <<')
  2281. elif not Match(r'#.*include', line):
  2282. # Avoid false positives on ->
  2283. reduced_line = line.replace('->', '')
  2284. # Look for < that is not surrounded by spaces. This is only
  2285. # triggered if both sides are missing spaces, even though
  2286. # technically should should flag if at least one side is missing a
  2287. # space. This is done to avoid some false positives with shifts.
  2288. match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
  2289. if (match and
  2290. not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
  2291. error(filename, linenum, 'whitespace/operators', 3,
  2292. 'Missing spaces around <')
  2293. # Look for > that is not surrounded by spaces. Similar to the
  2294. # above, we only trigger if both sides are missing spaces to avoid
  2295. # false positives with shifts.
  2296. match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
  2297. if (match and
  2298. not FindPreviousMatchingAngleBracket(clean_lines, linenum,
  2299. match.group(1))):
  2300. error(filename, linenum, 'whitespace/operators', 3,
  2301. 'Missing spaces around >')
  2302. # We allow no-spaces around >> for almost anything. This is because
  2303. # C++11 allows ">>" to close nested templates, which accounts for
  2304. # most cases when ">>" is not followed by a space.
  2305. #
  2306. # We still warn on ">>" followed by alpha character, because that is
  2307. # likely due to ">>" being used for right shifts, e.g.:
  2308. # value >> alpha
  2309. #
  2310. # When ">>" is used to close templates, the alphanumeric letter that
  2311. # follows would be part of an identifier, and there should still be
  2312. # a space separating the template type and the identifier.
  2313. # type<type<type>> alpha
  2314. match = Search(r'>>[a-zA-Z_]', line)
  2315. if match:
  2316. error(filename, linenum, 'whitespace/operators', 3,
  2317. 'Missing spaces around >>')
  2318. # There shouldn't be space around unary operators
  2319. match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
  2320. if match:
  2321. error(filename, linenum, 'whitespace/operators', 4,
  2322. 'Extra space for operator %s' % match.group(1))
  2323. # A pet peeve of mine: no spaces after an if, while, switch, or for
  2324. match = Search(r' (if\(|for\(|while\(|switch\()', line)
  2325. if match:
  2326. error(filename, linenum, 'whitespace/parens', 5,
  2327. 'Missing space before ( in %s' % match.group(1))
  2328. # For if/for/while/switch, the left and right parens should be
  2329. # consistent about how many spaces are inside the parens, and
  2330. # there should either be zero or one spaces inside the parens.
  2331. # We don't want: "if ( foo)" or "if ( foo )".
  2332. # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  2333. match = Search(r'\b(if|for|while|switch)\s*'
  2334. r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
  2335. line)
  2336. if match:
  2337. if len(match.group(2)) != len(match.group(4)):
  2338. if not (match.group(3) == ';' and
  2339. len(match.group(2)) == 1 + len(match.group(4)) or
  2340. not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
  2341. error(filename, linenum, 'whitespace/parens', 5,
  2342. 'Mismatching spaces inside () in %s' % match.group(1))
  2343. if len(match.group(2)) not in [0, 1]:
  2344. error(filename, linenum, 'whitespace/parens', 5,
  2345. 'Should have zero or one spaces inside ( and ) in %s' %
  2346. match.group(1))
  2347. # You should always have a space after a comma (either as fn arg or operator)
  2348. #
  2349. # This does not apply when the non-space character following the
  2350. # comma is another comma, since the only time when that happens is
  2351. # for empty macro arguments.
  2352. #
  2353. # We run this check in two passes: first pass on elided lines to
  2354. # verify that lines contain missing whitespaces, second pass on raw
  2355. # lines to confirm that those missing whitespaces are not due to
  2356. # elided comments.
  2357. if Search(r',[^,\s]', line) and Search(r',[^,\s]', raw[linenum]):
  2358. error(filename, linenum, 'whitespace/comma', 3,
  2359. 'Missing space after ,')
  2360. # You should always have a space after a semicolon
  2361. # except for few corner cases
  2362. # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
  2363. # space after ;
  2364. if Search(r';[^\s};\\)/]', line):
  2365. error(filename, linenum, 'whitespace/semicolon', 3,
  2366. 'Missing space after ;')
  2367. # Next we will look for issues with function calls.
  2368. CheckSpacingForFunctionCall(filename, line, linenum, error)
  2369. # Except after an opening paren, or after another opening brace (in case of
  2370. # an initializer list, for instance), you should have spaces before your
  2371. # braces. And since you should never have braces at the beginning of a line,
  2372. # this is an easy test.
  2373. match = Match(r'^(.*[^ ({]){', line)
  2374. if match:
  2375. # Try a bit harder to check for brace initialization. This
  2376. # happens in one of the following forms:
  2377. # Constructor() : initializer_list_{} { ... }
  2378. # Constructor{}.MemberFunction()
  2379. # Type variable{};
  2380. # FunctionCall(type{}, ...);
  2381. # LastArgument(..., type{});
  2382. # LOG(INFO) << type{} << " ...";
  2383. # map_of_type[{...}] = ...;
  2384. #
  2385. # We check for the character following the closing brace, and
  2386. # silence the warning if it's one of those listed above, i.e.
  2387. # "{.;,)<]".
  2388. #
  2389. # To account for nested initializer list, we allow any number of
  2390. # closing braces up to "{;,)<". We can't simply silence the
  2391. # warning on first sight of closing brace, because that would
  2392. # cause false negatives for things that are not initializer lists.
  2393. # Silence this: But not this:
  2394. # Outer{ if (...) {
  2395. # Inner{...} if (...){ // Missing space before {
  2396. # }; }
  2397. #
  2398. # There is a false negative with this approach if people inserted
  2399. # spurious semicolons, e.g. "if (cond){};", but we will catch the
  2400. # spurious semicolon with a separate check.
  2401. (endline, endlinenum, endpos) = CloseExpression(
  2402. clean_lines, linenum, len(match.group(1)))
  2403. trailing_text = ''
  2404. if endpos > -1:
  2405. trailing_text = endline[endpos:]
  2406. for offset in xrange(endlinenum + 1,
  2407. min(endlinenum + 3, clean_lines.NumLines() - 1)):
  2408. trailing_text += clean_lines.elided[offset]
  2409. if not Match(r'^[\s}]*[{.;,)<\]]', trailing_text):
  2410. error(filename, linenum, 'whitespace/braces', 5,
  2411. 'Missing space before {')
  2412. # Make sure '} else {' has spaces.
  2413. if Search(r'}else', line):
  2414. error(filename, linenum, 'whitespace/braces', 5,
  2415. 'Missing space before else')
  2416. # You shouldn't have spaces before your brackets, except maybe after
  2417. # 'delete []' or 'new char * []'.
  2418. if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
  2419. error(filename, linenum, 'whitespace/braces', 5,
  2420. 'Extra space before [')
  2421. # You shouldn't have a space before a semicolon at the end of the line.
  2422. # There's a special case for "for" since the style guide allows space before
  2423. # the semicolon there.
  2424. if Search(r':\s*;\s*$', line):
  2425. error(filename, linenum, 'whitespace/semicolon', 5,
  2426. 'Semicolon defining empty statement. Use {} instead.')
  2427. elif Search(r'^\s*;\s*$', line):
  2428. error(filename, linenum, 'whitespace/semicolon', 5,
  2429. 'Line contains only semicolon. If this should be an empty statement, '
  2430. 'use {} instead.')
  2431. elif (Search(r'\s+;\s*$', line) and
  2432. not Search(r'\bfor\b', line)):
  2433. error(filename, linenum, 'whitespace/semicolon', 5,
  2434. 'Extra space before last semicolon. If this should be an empty '
  2435. 'statement, use {} instead.')
  2436. # In range-based for, we wanted spaces before and after the colon, but
  2437. # not around "::" tokens that might appear.
  2438. if (Search('for *\(.*[^:]:[^: ]', line) or
  2439. Search('for *\(.*[^: ]:[^:]', line)):
  2440. error(filename, linenum, 'whitespace/forcolon', 2,
  2441. 'Missing space around colon in range-based for loop')
  2442. def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
  2443. """Checks for additional blank line issues related to sections.
  2444. Currently the only thing checked here is blank line before protected/private.
  2445. Args:
  2446. filename: The name of the current file.
  2447. clean_lines: A CleansedLines instance containing the file.
  2448. class_info: A _ClassInfo objects.
  2449. linenum: The number of the line to check.
  2450. error: The function to call with any errors found.
  2451. """
  2452. # Skip checks if the class is small, where small means 25 lines or less.
  2453. # 25 lines seems like a good cutoff since that's the usual height of
  2454. # terminals, and any class that can't fit in one screen can't really
  2455. # be considered "small".
  2456. #
  2457. # Also skip checks if we are on the first line. This accounts for
  2458. # classes that look like
  2459. # class Foo { public: ... };
  2460. #
  2461. # If we didn't find the end of the class, last_line would be zero,
  2462. # and the check will be skipped by the first condition.
  2463. if (class_info.last_line - class_info.starting_linenum <= 24 or
  2464. linenum <= class_info.starting_linenum):
  2465. return
  2466. matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
  2467. if matched:
  2468. # Issue warning if the line before public/protected/private was
  2469. # not a blank line, but don't do this if the previous line contains
  2470. # "class" or "struct". This can happen two ways:
  2471. # - We are at the beginning of the class.
  2472. # - We are forward-declaring an inner class that is semantically
  2473. # private, but needed to be public for implementation reasons.
  2474. # Also ignores cases where the previous line ends with a backslash as can be
  2475. # common when defining classes in C macros.
  2476. prev_line = clean_lines.lines[linenum - 1]
  2477. if (not IsBlankLine(prev_line) and
  2478. not Search(r'\b(class|struct)\b', prev_line) and
  2479. not Search(r'\\$', prev_line)):
  2480. # Try a bit harder to find the beginning of the class. This is to
  2481. # account for multi-line base-specifier lists, e.g.:
  2482. # class Derived
  2483. # : public Base {
  2484. end_class_head = class_info.starting_linenum
  2485. for i in range(class_info.starting_linenum, linenum):
  2486. if Search(r'\{\s*$', clean_lines.lines[i]):
  2487. end_class_head = i
  2488. break
  2489. if end_class_head < linenum - 1:
  2490. error(filename, linenum, 'whitespace/blank_line', 3,
  2491. '"%s:" should be preceded by a blank line' % matched.group(1))
  2492. def GetPreviousNonBlankLine(clean_lines, linenum):
  2493. """Return the most recent non-blank line and its line number.
  2494. Args:
  2495. clean_lines: A CleansedLines instance containing the file contents.
  2496. linenum: The number of the line to check.
  2497. Returns:
  2498. A tuple with two elements. The first element is the contents of the last
  2499. non-blank line before the current line, or the empty string if this is the
  2500. first non-blank line. The second is the line number of that line, or -1
  2501. if this is the first non-blank line.
  2502. """
  2503. prevlinenum = linenum - 1
  2504. while prevlinenum >= 0:
  2505. prevline = clean_lines.elided[prevlinenum]
  2506. if not IsBlankLine(prevline): # if not a blank line...
  2507. return (prevline, prevlinenum)
  2508. prevlinenum -= 1
  2509. return ('', -1)
  2510. def CheckBraces(filename, clean_lines, linenum, error):
  2511. """Looks for misplaced braces (e.g. at the end of line).
  2512. Args:
  2513. filename: The name of the current file.
  2514. clean_lines: A CleansedLines instance containing the file.
  2515. linenum: The number of the line to check.
  2516. error: The function to call with any errors found.
  2517. """
  2518. line = clean_lines.elided[linenum] # get rid of comments and strings
  2519. if Match(r'\s*{\s*$', line):
  2520. # We allow an open brace to start a line in the case where someone is using
  2521. # braces in a block to explicitly create a new scope, which is commonly used
  2522. # to control the lifetime of stack-allocated variables. Braces are also
  2523. # used for brace initializers inside function calls. We don't detect this
  2524. # perfectly: we just don't complain if the last non-whitespace character on
  2525. # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
  2526. # previous line starts a preprocessor block.
  2527. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  2528. if (not Search(r'[,;:}{(]\s*$', prevline) and
  2529. not Match(r'\s*#', prevline)):
  2530. error(filename, linenum, 'whitespace/braces', 4,
  2531. '{ should almost always be at the end of the previous line')
  2532. # An else clause should be on the same line as the preceding closing brace.
  2533. if Match(r'\s*else\s*', line):
  2534. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  2535. if Match(r'\s*}\s*$', prevline):
  2536. error(filename, linenum, 'whitespace/newline', 4,
  2537. 'An else should appear on the same line as the preceding }')
  2538. # If braces come on one side of an else, they should be on both.
  2539. # However, we have to worry about "else if" that spans multiple lines!
  2540. if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
  2541. if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
  2542. # find the ( after the if
  2543. pos = line.find('else if')
  2544. pos = line.find('(', pos)
  2545. if pos > 0:
  2546. (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
  2547. if endline[endpos:].find('{') == -1: # must be brace after if
  2548. error(filename, linenum, 'readability/braces', 5,
  2549. 'If an else has a brace on one side, it should have it on both')
  2550. else: # common case: else not followed by a multi-line if
  2551. error(filename, linenum, 'readability/braces', 5,
  2552. 'If an else has a brace on one side, it should have it on both')
  2553. # Likewise, an else should never have the else clause on the same line
  2554. if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
  2555. error(filename, linenum, 'whitespace/newline', 4,
  2556. 'Else clause should never be on same line as else (use 2 lines)')
  2557. # In the same way, a do/while should never be on one line
  2558. if Match(r'\s*do [^\s{]', line):
  2559. error(filename, linenum, 'whitespace/newline', 4,
  2560. 'do/while clauses should not be on a single line')
  2561. # Block bodies should not be followed by a semicolon. Due to C++11
  2562. # brace initialization, there are more places where semicolons are
  2563. # required than not, so we use a whitelist approach to check these
  2564. # rather than a blacklist. These are the places where "};" should
  2565. # be replaced by just "}":
  2566. # 1. Some flavor of block following closing parenthesis:
  2567. # for (;;) {};
  2568. # while (...) {};
  2569. # switch (...) {};
  2570. # Function(...) {};
  2571. # if (...) {};
  2572. # if (...) else if (...) {};
  2573. #
  2574. # 2. else block:
  2575. # if (...) else {};
  2576. #
  2577. # 3. const member function:
  2578. # Function(...) const {};
  2579. #
  2580. # 4. Block following some statement:
  2581. # x = 42;
  2582. # {};
  2583. #
  2584. # 5. Block at the beginning of a function:
  2585. # Function(...) {
  2586. # {};
  2587. # }
  2588. #
  2589. # Note that naively checking for the preceding "{" will also match
  2590. # braces inside multi-dimensional arrays, but this is fine since
  2591. # that expression will not contain semicolons.
  2592. #
  2593. # 6. Block following another block:
  2594. # while (true) {}
  2595. # {};
  2596. #
  2597. # 7. End of namespaces:
  2598. # namespace {};
  2599. #
  2600. # These semicolons seems far more common than other kinds of
  2601. # redundant semicolons, possibly due to people converting classes
  2602. # to namespaces. For now we do not warn for this case.
  2603. #
  2604. # Try matching case 1 first.
  2605. match = Match(r'^(.*\)\s*)\{', line)
  2606. if match:
  2607. # Matched closing parenthesis (case 1). Check the token before the
  2608. # matching opening parenthesis, and don't warn if it looks like a
  2609. # macro. This avoids these false positives:
  2610. # - macro that defines a base class
  2611. # - multi-line macro that defines a base class
  2612. # - macro that defines the whole class-head
  2613. #
  2614. # But we still issue warnings for macros that we know are safe to
  2615. # warn, specifically:
  2616. # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
  2617. # - TYPED_TEST
  2618. # - INTERFACE_DEF
  2619. # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
  2620. #
  2621. # We implement a whitelist of safe macros instead of a blacklist of
  2622. # unsafe macros, even though the latter appears less frequently in
  2623. # google code and would have been easier to implement. This is because
  2624. # the downside for getting the whitelist wrong means some extra
  2625. # semicolons, while the downside for getting the blacklist wrong
  2626. # would result in compile errors.
  2627. #
  2628. # In addition to macros, we also don't want to warn on compound
  2629. # literals.
  2630. closing_brace_pos = match.group(1).rfind(')')
  2631. opening_parenthesis = ReverseCloseExpression(
  2632. clean_lines, linenum, closing_brace_pos)
  2633. if opening_parenthesis[2] > -1:
  2634. line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
  2635. macro = Search(r'\b([A-Z_]+)\s*$', line_prefix)
  2636. if ((macro and
  2637. macro.group(1) not in (
  2638. 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
  2639. 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
  2640. 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
  2641. Search(r'\s+=\s*$', line_prefix)):
  2642. match = None
  2643. else:
  2644. # Try matching cases 2-3.
  2645. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
  2646. if not match:
  2647. # Try matching cases 4-6. These are always matched on separate lines.
  2648. #
  2649. # Note that we can't simply concatenate the previous line to the
  2650. # current line and do a single match, otherwise we may output
  2651. # duplicate warnings for the blank line case:
  2652. # if (cond) {
  2653. # // blank line
  2654. # }
  2655. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  2656. if prevline and Search(r'[;{}]\s*$', prevline):
  2657. match = Match(r'^(\s*)\{', line)
  2658. # Check matching closing brace
  2659. if match:
  2660. (endline, endlinenum, endpos) = CloseExpression(
  2661. clean_lines, linenum, len(match.group(1)))
  2662. if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
  2663. # Current {} pair is eligible for semicolon check, and we have found
  2664. # the redundant semicolon, output warning here.
  2665. #
  2666. # Note: because we are scanning forward for opening braces, and
  2667. # outputting warnings for the matching closing brace, if there are
  2668. # nested blocks with trailing semicolons, we will get the error
  2669. # messages in reversed order.
  2670. error(filename, endlinenum, 'readability/braces', 4,
  2671. "You don't need a ; after a }")
  2672. def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
  2673. """Look for empty loop/conditional body with only a single semicolon.
  2674. Args:
  2675. filename: The name of the current file.
  2676. clean_lines: A CleansedLines instance containing the file.
  2677. linenum: The number of the line to check.
  2678. error: The function to call with any errors found.
  2679. """
  2680. # Search for loop keywords at the beginning of the line. Because only
  2681. # whitespaces are allowed before the keywords, this will also ignore most
  2682. # do-while-loops, since those lines should start with closing brace.
  2683. #
  2684. # We also check "if" blocks here, since an empty conditional block
  2685. # is likely an error.
  2686. line = clean_lines.elided[linenum]
  2687. matched = Match(r'\s*(for|while|if)\s*\(', line)
  2688. if matched:
  2689. # Find the end of the conditional expression
  2690. (end_line, end_linenum, end_pos) = CloseExpression(
  2691. clean_lines, linenum, line.find('('))
  2692. # Output warning if what follows the condition expression is a semicolon.
  2693. # No warning for all other cases, including whitespace or newline, since we
  2694. # have a separate check for semicolons preceded by whitespace.
  2695. if end_pos >= 0 and Match(r';', end_line[end_pos:]):
  2696. if matched.group(1) == 'if':
  2697. error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
  2698. 'Empty conditional bodies should use {}')
  2699. else:
  2700. error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
  2701. 'Empty loop bodies should use {} or continue')
  2702. def CheckCheck(filename, clean_lines, linenum, error):
  2703. """Checks the use of CHECK and EXPECT macros.
  2704. Args:
  2705. filename: The name of the current file.
  2706. clean_lines: A CleansedLines instance containing the file.
  2707. linenum: The number of the line to check.
  2708. error: The function to call with any errors found.
  2709. """
  2710. # Decide the set of replacement macros that should be suggested
  2711. lines = clean_lines.elided
  2712. check_macro = None
  2713. start_pos = -1
  2714. for macro in _CHECK_MACROS:
  2715. i = lines[linenum].find(macro)
  2716. if i >= 0:
  2717. check_macro = macro
  2718. # Find opening parenthesis. Do a regular expression match here
  2719. # to make sure that we are matching the expected CHECK macro, as
  2720. # opposed to some other macro that happens to contain the CHECK
  2721. # substring.
  2722. matched = Match(r'^(.*\b' + check_macro + r'\s*)\(', lines[linenum])
  2723. if not matched:
  2724. continue
  2725. start_pos = len(matched.group(1))
  2726. break
  2727. if not check_macro or start_pos < 0:
  2728. # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
  2729. return
  2730. # Find end of the boolean expression by matching parentheses
  2731. (last_line, end_line, end_pos) = CloseExpression(
  2732. clean_lines, linenum, start_pos)
  2733. if end_pos < 0:
  2734. return
  2735. if linenum == end_line:
  2736. expression = lines[linenum][start_pos + 1:end_pos - 1]
  2737. else:
  2738. expression = lines[linenum][start_pos + 1:]
  2739. for i in xrange(linenum + 1, end_line):
  2740. expression += lines[i]
  2741. expression += last_line[0:end_pos - 1]
  2742. # Parse expression so that we can take parentheses into account.
  2743. # This avoids false positives for inputs like "CHECK((a < 4) == b)",
  2744. # which is not replaceable by CHECK_LE.
  2745. lhs = ''
  2746. rhs = ''
  2747. operator = None
  2748. while expression:
  2749. matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
  2750. r'==|!=|>=|>|<=|<|\()(.*)$', expression)
  2751. if matched:
  2752. token = matched.group(1)
  2753. if token == '(':
  2754. # Parenthesized operand
  2755. expression = matched.group(2)
  2756. (end, _) = FindEndOfExpressionInLine(expression, 0, 1, '(', ')')
  2757. if end < 0:
  2758. return # Unmatched parenthesis
  2759. lhs += '(' + expression[0:end]
  2760. expression = expression[end:]
  2761. elif token in ('&&', '||'):
  2762. # Logical and/or operators. This means the expression
  2763. # contains more than one term, for example:
  2764. # CHECK(42 < a && a < b);
  2765. #
  2766. # These are not replaceable with CHECK_LE, so bail out early.
  2767. return
  2768. elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
  2769. # Non-relational operator
  2770. lhs += token
  2771. expression = matched.group(2)
  2772. else:
  2773. # Relational operator
  2774. operator = token
  2775. rhs = matched.group(2)
  2776. break
  2777. else:
  2778. # Unparenthesized operand. Instead of appending to lhs one character
  2779. # at a time, we do another regular expression match to consume several
  2780. # characters at once if possible. Trivial benchmark shows that this
  2781. # is more efficient when the operands are longer than a single
  2782. # character, which is generally the case.
  2783. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
  2784. if not matched:
  2785. matched = Match(r'^(\s*\S)(.*)$', expression)
  2786. if not matched:
  2787. break
  2788. lhs += matched.group(1)
  2789. expression = matched.group(2)
  2790. # Only apply checks if we got all parts of the boolean expression
  2791. if not (lhs and operator and rhs):
  2792. return
  2793. # Check that rhs do not contain logical operators. We already know
  2794. # that lhs is fine since the loop above parses out && and ||.
  2795. if rhs.find('&&') > -1 or rhs.find('||') > -1:
  2796. return
  2797. # At least one of the operands must be a constant literal. This is
  2798. # to avoid suggesting replacements for unprintable things like
  2799. # CHECK(variable != iterator)
  2800. #
  2801. # The following pattern matches decimal, hex integers, strings, and
  2802. # characters (in that order).
  2803. lhs = lhs.strip()
  2804. rhs = rhs.strip()
  2805. match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
  2806. if Match(match_constant, lhs) or Match(match_constant, rhs):
  2807. # Note: since we know both lhs and rhs, we can provide a more
  2808. # descriptive error message like:
  2809. # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
  2810. # Instead of:
  2811. # Consider using CHECK_EQ instead of CHECK(a == b)
  2812. #
  2813. # We are still keeping the less descriptive message because if lhs
  2814. # or rhs gets long, the error message might become unreadable.
  2815. error(filename, linenum, 'readability/check', 2,
  2816. 'Consider using %s instead of %s(a %s b)' % (
  2817. _CHECK_REPLACEMENT[check_macro][operator],
  2818. check_macro, operator))
  2819. def CheckAltTokens(filename, clean_lines, linenum, error):
  2820. """Check alternative keywords being used in boolean expressions.
  2821. Args:
  2822. filename: The name of the current file.
  2823. clean_lines: A CleansedLines instance containing the file.
  2824. linenum: The number of the line to check.
  2825. error: The function to call with any errors found.
  2826. """
  2827. line = clean_lines.elided[linenum]
  2828. # Avoid preprocessor lines
  2829. if Match(r'^\s*#', line):
  2830. return
  2831. # Last ditch effort to avoid multi-line comments. This will not help
  2832. # if the comment started before the current line or ended after the
  2833. # current line, but it catches most of the false positives. At least,
  2834. # it provides a way to workaround this warning for people who use
  2835. # multi-line comments in preprocessor macros.
  2836. #
  2837. # TODO(unknown): remove this once cpplint has better support for
  2838. # multi-line comments.
  2839. if line.find('/*') >= 0 or line.find('*/') >= 0:
  2840. return
  2841. for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
  2842. error(filename, linenum, 'readability/alt_tokens', 2,
  2843. 'Use operator %s instead of %s' % (
  2844. _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
  2845. def GetLineWidth(line):
  2846. """Determines the width of the line in column positions.
  2847. Args:
  2848. line: A string, which may be a Unicode string.
  2849. Returns:
  2850. The width of the line in column positions, accounting for Unicode
  2851. combining characters and wide characters.
  2852. """
  2853. if isinstance(line, unicode):
  2854. width = 0
  2855. for uc in unicodedata.normalize('NFC', line):
  2856. if unicodedata.east_asian_width(uc) in ('W', 'F'):
  2857. width += 2
  2858. elif not unicodedata.combining(uc):
  2859. width += 1
  2860. return width
  2861. else:
  2862. return len(line)
  2863. def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
  2864. error):
  2865. """Checks rules from the 'C++ style rules' section of cppguide.html.
  2866. Most of these rules are hard to test (naming, comment style), but we
  2867. do what we can. In particular we check for 2-space indents, line lengths,
  2868. tab usage, spaces inside code, etc.
  2869. Args:
  2870. filename: The name of the current file.
  2871. clean_lines: A CleansedLines instance containing the file.
  2872. linenum: The number of the line to check.
  2873. file_extension: The extension (without the dot) of the filename.
  2874. nesting_state: A _NestingState instance which maintains information about
  2875. the current stack of nested blocks being parsed.
  2876. error: The function to call with any errors found.
  2877. """
  2878. # Don't use "elided" lines here, otherwise we can't check commented lines.
  2879. # Don't want to use "raw" either, because we don't want to check inside C++11
  2880. # raw strings,
  2881. raw_lines = clean_lines.lines_without_raw_strings
  2882. line = raw_lines[linenum]
  2883. if line.find('\t') != -1:
  2884. error(filename, linenum, 'whitespace/tab', 1,
  2885. 'Tab found; better to use spaces')
  2886. # One or three blank spaces at the beginning of the line is weird; it's
  2887. # hard to reconcile that with 2-space indents.
  2888. # NOTE: here are the conditions rob pike used for his tests. Mine aren't
  2889. # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
  2890. # if(RLENGTH > 20) complain = 0;
  2891. # if(match($0, " +(error|private|public|protected):")) complain = 0;
  2892. # if(match(prev, "&& *$")) complain = 0;
  2893. # if(match(prev, "\\|\\| *$")) complain = 0;
  2894. # if(match(prev, "[\",=><] *$")) complain = 0;
  2895. # if(match($0, " <<")) complain = 0;
  2896. # if(match(prev, " +for \\(")) complain = 0;
  2897. # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
  2898. initial_spaces = 0
  2899. cleansed_line = clean_lines.elided[linenum]
  2900. while initial_spaces < len(line) and line[initial_spaces] == ' ':
  2901. initial_spaces += 1
  2902. if line and line[-1].isspace():
  2903. error(filename, linenum, 'whitespace/end_of_line', 4,
  2904. 'Line ends in whitespace. Consider deleting these extra spaces.')
  2905. # There are certain situations we allow one space, notably for section labels
  2906. elif ((initial_spaces == 1 or initial_spaces == 3) and
  2907. not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
  2908. error(filename, linenum, 'whitespace/indent', 3,
  2909. 'Weird number of spaces at line-start. '
  2910. 'Are you using a 2-space indent?')
  2911. # Check if the line is a header guard.
  2912. is_header_guard = False
  2913. if file_extension == 'h':
  2914. cppvar = GetHeaderGuardCPPVariable(filename)
  2915. if (line.startswith('#ifndef %s' % cppvar) or
  2916. line.startswith('#define %s' % cppvar) or
  2917. line.startswith('#endif // %s' % cppvar)):
  2918. is_header_guard = True
  2919. # #include lines and header guards can be long, since there's no clean way to
  2920. # split them.
  2921. #
  2922. # URLs can be long too. It's possible to split these, but it makes them
  2923. # harder to cut&paste.
  2924. #
  2925. # The "$Id:...$" comment may also get very long without it being the
  2926. # developers fault.
  2927. if (not line.startswith('#include') and not is_header_guard and
  2928. not Match(r'^\s*//.*http(s?)://\S*$', line) and
  2929. not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
  2930. line_width = GetLineWidth(line)
  2931. extended_length = int((_line_length * 1.25))
  2932. if line_width > extended_length:
  2933. error(filename, linenum, 'whitespace/line_length', 4,
  2934. 'Lines should very rarely be longer than %i characters' %
  2935. extended_length)
  2936. elif line_width > _line_length:
  2937. error(filename, linenum, 'whitespace/line_length', 2,
  2938. 'Lines should be <= %i characters long' % _line_length)
  2939. if (cleansed_line.count(';') > 1 and
  2940. # for loops are allowed two ;'s (and may run over two lines).
  2941. cleansed_line.find('for') == -1 and
  2942. (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
  2943. GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
  2944. # It's ok to have many commands in a switch case that fits in 1 line
  2945. not ((cleansed_line.find('case ') != -1 or
  2946. cleansed_line.find('default:') != -1) and
  2947. cleansed_line.find('break;') != -1)):
  2948. error(filename, linenum, 'whitespace/newline', 0,
  2949. 'More than one command on the same line')
  2950. # Some more style checks
  2951. CheckBraces(filename, clean_lines, linenum, error)
  2952. CheckEmptyBlockBody(filename, clean_lines, linenum, error)
  2953. CheckAccess(filename, clean_lines, linenum, nesting_state, error)
  2954. CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
  2955. CheckCheck(filename, clean_lines, linenum, error)
  2956. CheckAltTokens(filename, clean_lines, linenum, error)
  2957. classinfo = nesting_state.InnermostClass()
  2958. if classinfo:
  2959. CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
  2960. _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
  2961. _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
  2962. # Matches the first component of a filename delimited by -s and _s. That is:
  2963. # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
  2964. # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
  2965. # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
  2966. # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
  2967. _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
  2968. def _DropCommonSuffixes(filename):
  2969. """Drops common suffixes like _test.cc or -inl.h from filename.
  2970. For example:
  2971. >>> _DropCommonSuffixes('foo/foo-inl.h')
  2972. 'foo/foo'
  2973. >>> _DropCommonSuffixes('foo/bar/foo.cc')
  2974. 'foo/bar/foo'
  2975. >>> _DropCommonSuffixes('foo/foo_internal.h')
  2976. 'foo/foo'
  2977. >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
  2978. 'foo/foo_unusualinternal'
  2979. Args:
  2980. filename: The input filename.
  2981. Returns:
  2982. The filename with the common suffix removed.
  2983. """
  2984. for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
  2985. 'inl.h', 'impl.h', 'internal.h'):
  2986. if (filename.endswith(suffix) and len(filename) > len(suffix) and
  2987. filename[-len(suffix) - 1] in ('-', '_')):
  2988. return filename[:-len(suffix) - 1]
  2989. return os.path.splitext(filename)[0]
  2990. def _IsTestFilename(filename):
  2991. """Determines if the given filename has a suffix that identifies it as a test.
  2992. Args:
  2993. filename: The input filename.
  2994. Returns:
  2995. True if 'filename' looks like a test, False otherwise.
  2996. """
  2997. if (filename.endswith('_test.cc') or
  2998. filename.endswith('_unittest.cc') or
  2999. filename.endswith('_regtest.cc')):
  3000. return True
  3001. else:
  3002. return False
  3003. def _ClassifyInclude(fileinfo, include, is_system):
  3004. """Figures out what kind of header 'include' is.
  3005. Args:
  3006. fileinfo: The current file cpplint is running over. A FileInfo instance.
  3007. include: The path to a #included file.
  3008. is_system: True if the #include used <> rather than "".
  3009. Returns:
  3010. One of the _XXX_HEADER constants.
  3011. For example:
  3012. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
  3013. _C_SYS_HEADER
  3014. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
  3015. _CPP_SYS_HEADER
  3016. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
  3017. _LIKELY_MY_HEADER
  3018. >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
  3019. ... 'bar/foo_other_ext.h', False)
  3020. _POSSIBLE_MY_HEADER
  3021. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
  3022. _OTHER_HEADER
  3023. """
  3024. # This is a list of all standard c++ header files, except
  3025. # those already checked for above.
  3026. is_cpp_h = include in _CPP_HEADERS
  3027. if is_system:
  3028. if is_cpp_h:
  3029. return _CPP_SYS_HEADER
  3030. else:
  3031. return _C_SYS_HEADER
  3032. # If the target file and the include we're checking share a
  3033. # basename when we drop common extensions, and the include
  3034. # lives in . , then it's likely to be owned by the target file.
  3035. target_dir, target_base = (
  3036. os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
  3037. include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
  3038. if target_base == include_base and (
  3039. include_dir == target_dir or
  3040. include_dir == os.path.normpath(target_dir + '/../public')):
  3041. return _LIKELY_MY_HEADER
  3042. # If the target and include share some initial basename
  3043. # component, it's possible the target is implementing the
  3044. # include, so it's allowed to be first, but we'll never
  3045. # complain if it's not there.
  3046. target_first_component = _RE_FIRST_COMPONENT.match(target_base)
  3047. include_first_component = _RE_FIRST_COMPONENT.match(include_base)
  3048. if (target_first_component and include_first_component and
  3049. target_first_component.group(0) ==
  3050. include_first_component.group(0)):
  3051. return _POSSIBLE_MY_HEADER
  3052. return _OTHER_HEADER
  3053. def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
  3054. """Check rules that are applicable to #include lines.
  3055. Strings on #include lines are NOT removed from elided line, to make
  3056. certain tasks easier. However, to prevent false positives, checks
  3057. applicable to #include lines in CheckLanguage must be put here.
  3058. Args:
  3059. filename: The name of the current file.
  3060. clean_lines: A CleansedLines instance containing the file.
  3061. linenum: The number of the line to check.
  3062. include_state: An _IncludeState instance in which the headers are inserted.
  3063. error: The function to call with any errors found.
  3064. """
  3065. fileinfo = FileInfo(filename)
  3066. line = clean_lines.lines[linenum]
  3067. # "include" should use the new style "foo/bar.h" instead of just "bar.h"
  3068. if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
  3069. error(filename, linenum, 'build/include', 4,
  3070. 'Include the directory when naming .h files')
  3071. # we shouldn't include a file more than once. actually, there are a
  3072. # handful of instances where doing so is okay, but in general it's
  3073. # not.
  3074. match = _RE_PATTERN_INCLUDE.search(line)
  3075. if match:
  3076. include = match.group(2)
  3077. is_system = (match.group(1) == '<')
  3078. if include in include_state:
  3079. error(filename, linenum, 'build/include', 4,
  3080. '"%s" already included at %s:%s' %
  3081. (include, filename, include_state[include]))
  3082. else:
  3083. include_state[include] = linenum
  3084. # We want to ensure that headers appear in the right order:
  3085. # 1) for foo.cc, foo.h (preferred location)
  3086. # 2) c system files
  3087. # 3) cpp system files
  3088. # 4) for foo.cc, foo.h (deprecated location)
  3089. # 5) other google headers
  3090. #
  3091. # We classify each include statement as one of those 5 types
  3092. # using a number of techniques. The include_state object keeps
  3093. # track of the highest type seen, and complains if we see a
  3094. # lower type after that.
  3095. error_message = include_state.CheckNextIncludeOrder(
  3096. _ClassifyInclude(fileinfo, include, is_system))
  3097. if error_message:
  3098. error(filename, linenum, 'build/include_order', 4,
  3099. '%s. Should be: %s.h, c system, c++ system, other.' %
  3100. (error_message, fileinfo.BaseName()))
  3101. canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
  3102. if not include_state.IsInAlphabeticalOrder(
  3103. clean_lines, linenum, canonical_include):
  3104. error(filename, linenum, 'build/include_alpha', 4,
  3105. 'Include "%s" not in alphabetical order' % include)
  3106. include_state.SetLastHeader(canonical_include)
  3107. # Look for any of the stream classes that are part of standard C++.
  3108. match = _RE_PATTERN_INCLUDE.match(line)
  3109. if match:
  3110. include = match.group(2)
  3111. if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
  3112. # Many unit tests use cout, so we exempt them.
  3113. if not _IsTestFilename(filename):
  3114. error(filename, linenum, 'readability/streams', 3,
  3115. 'Streams are highly discouraged.')
  3116. def _GetTextInside(text, start_pattern):
  3117. r"""Retrieves all the text between matching open and close parentheses.
  3118. Given a string of lines and a regular expression string, retrieve all the text
  3119. following the expression and between opening punctuation symbols like
  3120. (, [, or {, and the matching close-punctuation symbol. This properly nested
  3121. occurrences of the punctuations, so for the text like
  3122. printf(a(), b(c()));
  3123. a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
  3124. start_pattern must match string having an open punctuation symbol at the end.
  3125. Args:
  3126. text: The lines to extract text. Its comments and strings must be elided.
  3127. It can be single line and can span multiple lines.
  3128. start_pattern: The regexp string indicating where to start extracting
  3129. the text.
  3130. Returns:
  3131. The extracted text.
  3132. None if either the opening string or ending punctuation could not be found.
  3133. """
  3134. # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
  3135. # rewritten to use _GetTextInside (and use inferior regexp matching today).
  3136. # Give opening punctuations to get the matching close-punctuations.
  3137. matching_punctuation = {'(': ')', '{': '}', '[': ']'}
  3138. closing_punctuation = set(matching_punctuation.itervalues())
  3139. # Find the position to start extracting text.
  3140. match = re.search(start_pattern, text, re.M)
  3141. if not match: # start_pattern not found in text.
  3142. return None
  3143. start_position = match.end(0)
  3144. assert start_position > 0, (
  3145. 'start_pattern must ends with an opening punctuation.')
  3146. assert text[start_position - 1] in matching_punctuation, (
  3147. 'start_pattern must ends with an opening punctuation.')
  3148. # Stack of closing punctuations we expect to have in text after position.
  3149. punctuation_stack = [matching_punctuation[text[start_position - 1]]]
  3150. position = start_position
  3151. while punctuation_stack and position < len(text):
  3152. if text[position] == punctuation_stack[-1]:
  3153. punctuation_stack.pop()
  3154. elif text[position] in closing_punctuation:
  3155. # A closing punctuation without matching opening punctuations.
  3156. return None
  3157. elif text[position] in matching_punctuation:
  3158. punctuation_stack.append(matching_punctuation[text[position]])
  3159. position += 1
  3160. if punctuation_stack:
  3161. # Opening punctuations left without matching close-punctuations.
  3162. return None
  3163. # punctuations match.
  3164. return text[start_position:position - 1]
  3165. # Patterns for matching call-by-reference parameters.
  3166. #
  3167. # Supports nested templates up to 2 levels deep using this messy pattern:
  3168. # < (?: < (?: < [^<>]*
  3169. # >
  3170. # | [^<>] )*
  3171. # >
  3172. # | [^<>] )*
  3173. # >
  3174. _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
  3175. _RE_PATTERN_TYPE = (
  3176. r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
  3177. r'(?:\w|'
  3178. r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
  3179. r'::)+')
  3180. # A call-by-reference parameter ends with '& identifier'.
  3181. _RE_PATTERN_REF_PARAM = re.compile(
  3182. r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
  3183. r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
  3184. # A call-by-const-reference parameter either ends with 'const& identifier'
  3185. # or looks like 'const type& identifier' when 'type' is atomic.
  3186. _RE_PATTERN_CONST_REF_PARAM = (
  3187. r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
  3188. r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
  3189. def CheckLanguage(filename, clean_lines, linenum, file_extension,
  3190. include_state, nesting_state, error):
  3191. """Checks rules from the 'C++ language rules' section of cppguide.html.
  3192. Some of these rules are hard to test (function overloading, using
  3193. uint32 inappropriately), but we do the best we can.
  3194. Args:
  3195. filename: The name of the current file.
  3196. clean_lines: A CleansedLines instance containing the file.
  3197. linenum: The number of the line to check.
  3198. file_extension: The extension (without the dot) of the filename.
  3199. include_state: An _IncludeState instance in which the headers are inserted.
  3200. nesting_state: A _NestingState instance which maintains information about
  3201. the current stack of nested blocks being parsed.
  3202. error: The function to call with any errors found.
  3203. """
  3204. # If the line is empty or consists of entirely a comment, no need to
  3205. # check it.
  3206. line = clean_lines.elided[linenum]
  3207. if not line:
  3208. return
  3209. match = _RE_PATTERN_INCLUDE.search(line)
  3210. if match:
  3211. CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
  3212. return
  3213. # Reset include state across preprocessor directives. This is meant
  3214. # to silence warnings for conditional includes.
  3215. if Match(r'^\s*#\s*(?:ifdef|elif|else|endif)\b', line):
  3216. include_state.ResetSection()
  3217. # Make Windows paths like Unix.
  3218. fullname = os.path.abspath(filename).replace('\\', '/')
  3219. # TODO(unknown): figure out if they're using default arguments in fn proto.
  3220. # Check to see if they're using an conversion function cast.
  3221. # I just try to capture the most common basic types, though there are more.
  3222. # Parameterless conversion functions, such as bool(), are allowed as they are
  3223. # probably a member operator declaration or default constructor.
  3224. match = Search(
  3225. r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
  3226. r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
  3227. r'(\([^)].*)', line)
  3228. if match:
  3229. matched_new = match.group(1)
  3230. matched_type = match.group(2)
  3231. matched_funcptr = match.group(3)
  3232. # gMock methods are defined using some variant of MOCK_METHODx(name, type)
  3233. # where type may be float(), int(string), etc. Without context they are
  3234. # virtually indistinguishable from int(x) casts. Likewise, gMock's
  3235. # MockCallback takes a template parameter of the form return_type(arg_type),
  3236. # which looks much like the cast we're trying to detect.
  3237. #
  3238. # std::function<> wrapper has a similar problem.
  3239. #
  3240. # Return types for function pointers also look like casts if they
  3241. # don't have an extra space.
  3242. if (matched_new is None and # If new operator, then this isn't a cast
  3243. not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
  3244. Search(r'\bMockCallback<.*>', line) or
  3245. Search(r'\bstd::function<.*>', line)) and
  3246. not (matched_funcptr and
  3247. Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
  3248. matched_funcptr))):
  3249. # Try a bit harder to catch gmock lines: the only place where
  3250. # something looks like an old-style cast is where we declare the
  3251. # return type of the mocked method, and the only time when we
  3252. # are missing context is if MOCK_METHOD was split across
  3253. # multiple lines. The missing MOCK_METHOD is usually one or two
  3254. # lines back, so scan back one or two lines.
  3255. #
  3256. # It's not possible for gmock macros to appear in the first 2
  3257. # lines, since the class head + section name takes up 2 lines.
  3258. if (linenum < 2 or
  3259. not (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
  3260. clean_lines.elided[linenum - 1]) or
  3261. Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
  3262. clean_lines.elided[linenum - 2]))):
  3263. error(filename, linenum, 'readability/casting', 4,
  3264. 'Using deprecated casting style. '
  3265. 'Use static_cast<%s>(...) instead' %
  3266. matched_type)
  3267. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  3268. 'static_cast',
  3269. r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
  3270. # This doesn't catch all cases. Consider (const char * const)"hello".
  3271. #
  3272. # (char *) "foo" should always be a const_cast (reinterpret_cast won't
  3273. # compile).
  3274. if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  3275. 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
  3276. pass
  3277. else:
  3278. # Check pointer casts for other than string constants
  3279. CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
  3280. 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
  3281. # In addition, we look for people taking the address of a cast. This
  3282. # is dangerous -- casts can assign to temporaries, so the pointer doesn't
  3283. # point where you think.
  3284. match = Search(
  3285. r'(?:&\(([^)]+)\)[\w(])|'
  3286. r'(?:&(static|dynamic|down|reinterpret)_cast\b)', line)
  3287. if match and match.group(1) != '*':
  3288. error(filename, linenum, 'runtime/casting', 4,
  3289. ('Are you taking an address of a cast? '
  3290. 'This is dangerous: could be a temp var. '
  3291. 'Take the address before doing the cast, rather than after'))
  3292. # Create an extended_line, which is the concatenation of the current and
  3293. # next lines, for more effective checking of code that may span more than one
  3294. # line.
  3295. if linenum + 1 < clean_lines.NumLines():
  3296. extended_line = line + clean_lines.elided[linenum + 1]
  3297. else:
  3298. extended_line = line
  3299. # Check for people declaring static/global STL strings at the top level.
  3300. # This is dangerous because the C++ language does not guarantee that
  3301. # globals with constructors are initialized before the first access.
  3302. match = Match(
  3303. r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
  3304. line)
  3305. # Make sure it's not a function.
  3306. # Function template specialization looks like: "string foo<Type>(...".
  3307. # Class template definitions look like: "string Foo<Type>::Method(...".
  3308. #
  3309. # Also ignore things that look like operators. These are matched separately
  3310. # because operator names cross non-word boundaries. If we change the pattern
  3311. # above, we would decrease the accuracy of matching identifiers.
  3312. if (match and
  3313. not Search(r'\boperator\W', line) and
  3314. not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', match.group(3))):
  3315. error(filename, linenum, 'runtime/string', 4,
  3316. 'For a static/global string constant, use a C style string instead: '
  3317. '"%schar %s[]".' %
  3318. (match.group(1), match.group(2)))
  3319. if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
  3320. error(filename, linenum, 'runtime/init', 4,
  3321. 'You seem to be initializing a member variable with itself.')
  3322. if file_extension == 'h':
  3323. # TODO(unknown): check that 1-arg constructors are explicit.
  3324. # How to tell it's a constructor?
  3325. # (handled in CheckForNonStandardConstructs for now)
  3326. # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
  3327. # (level 1 error)
  3328. pass
  3329. # Check if people are using the verboten C basic types. The only exception
  3330. # we regularly allow is "unsigned short port" for port.
  3331. if Search(r'\bshort port\b', line):
  3332. if not Search(r'\bunsigned short port\b', line):
  3333. error(filename, linenum, 'runtime/int', 4,
  3334. 'Use "unsigned short" for ports, not "short"')
  3335. else:
  3336. match = Search(r'\b(short|long(?! +double)|long long)\b', line)
  3337. if match:
  3338. error(filename, linenum, 'runtime/int', 4,
  3339. 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
  3340. # When snprintf is used, the second argument shouldn't be a literal.
  3341. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
  3342. if match and match.group(2) != '0':
  3343. # If 2nd arg is zero, snprintf is used to calculate size.
  3344. error(filename, linenum, 'runtime/printf', 3,
  3345. 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
  3346. 'to snprintf.' % (match.group(1), match.group(2)))
  3347. # Check if some verboten C functions are being used.
  3348. if Search(r'\bsprintf\b', line):
  3349. error(filename, linenum, 'runtime/printf', 5,
  3350. 'Never use sprintf. Use snprintf instead.')
  3351. match = Search(r'\b(strcpy|strcat)\b', line)
  3352. if match:
  3353. error(filename, linenum, 'runtime/printf', 4,
  3354. 'Almost always, snprintf is better than %s' % match.group(1))
  3355. # Check if some verboten operator overloading is going on
  3356. # TODO(unknown): catch out-of-line unary operator&:
  3357. # class X {};
  3358. # int operator&(const X& x) { return 42; } // unary operator&
  3359. # The trick is it's hard to tell apart from binary operator&:
  3360. # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
  3361. if Search(r'\boperator\s*&\s*\(\s*\)', line):
  3362. error(filename, linenum, 'runtime/operator', 4,
  3363. 'Unary operator& is dangerous. Do not use it.')
  3364. # Check for suspicious usage of "if" like
  3365. # } if (a == b) {
  3366. if Search(r'\}\s*if\s*\(', line):
  3367. error(filename, linenum, 'readability/braces', 4,
  3368. 'Did you mean "else if"? If not, start a new line for "if".')
  3369. # Check for potential format string bugs like printf(foo).
  3370. # We constrain the pattern not to pick things like DocidForPrintf(foo).
  3371. # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
  3372. # TODO(sugawarayu): Catch the following case. Need to change the calling
  3373. # convention of the whole function to process multiple line to handle it.
  3374. # printf(
  3375. # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
  3376. printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
  3377. if printf_args:
  3378. match = Match(r'([\w.\->()]+)$', printf_args)
  3379. if match and match.group(1) != '__VA_ARGS__':
  3380. function_name = re.search(r'\b((?:string)?printf)\s*\(',
  3381. line, re.I).group(1)
  3382. error(filename, linenum, 'runtime/printf', 4,
  3383. 'Potential format string bug. Do %s("%%s", %s) instead.'
  3384. % (function_name, match.group(1)))
  3385. # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
  3386. match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
  3387. if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
  3388. error(filename, linenum, 'runtime/memset', 4,
  3389. 'Did you mean "memset(%s, 0, %s)"?'
  3390. % (match.group(1), match.group(2)))
  3391. if Search(r'\busing namespace\b', line):
  3392. error(filename, linenum, 'build/namespaces', 5,
  3393. 'Do not use namespace using-directives. '
  3394. 'Use using-declarations instead.')
  3395. # Detect variable-length arrays.
  3396. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
  3397. if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
  3398. match.group(3).find(']') == -1):
  3399. # Split the size using space and arithmetic operators as delimiters.
  3400. # If any of the resulting tokens are not compile time constants then
  3401. # report the error.
  3402. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
  3403. is_const = True
  3404. skip_next = False
  3405. for tok in tokens:
  3406. if skip_next:
  3407. skip_next = False
  3408. continue
  3409. if Search(r'sizeof\(.+\)', tok): continue
  3410. if Search(r'arraysize\(\w+\)', tok): continue
  3411. tok = tok.lstrip('(')
  3412. tok = tok.rstrip(')')
  3413. if not tok: continue
  3414. if Match(r'\d+', tok): continue
  3415. if Match(r'0[xX][0-9a-fA-F]+', tok): continue
  3416. if Match(r'k[A-Z0-9]\w*', tok): continue
  3417. if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
  3418. if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
  3419. # A catch all for tricky sizeof cases, including 'sizeof expression',
  3420. # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
  3421. # requires skipping the next token because we split on ' ' and '*'.
  3422. if tok.startswith('sizeof'):
  3423. skip_next = True
  3424. continue
  3425. is_const = False
  3426. break
  3427. if not is_const:
  3428. error(filename, linenum, 'runtime/arrays', 1,
  3429. 'Do not use variable-length arrays. Use an appropriately named '
  3430. "('k' followed by CamelCase) compile-time constant for the size.")
  3431. # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
  3432. # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
  3433. # in the class declaration.
  3434. match = Match(
  3435. (r'\s*'
  3436. r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
  3437. r'\(.*\);$'),
  3438. line)
  3439. if match and linenum + 1 < clean_lines.NumLines():
  3440. next_line = clean_lines.elided[linenum + 1]
  3441. # We allow some, but not all, declarations of variables to be present
  3442. # in the statement that defines the class. The [\w\*,\s]* fragment of
  3443. # the regular expression below allows users to declare instances of
  3444. # the class or pointers to instances, but not less common types such
  3445. # as function pointers or arrays. It's a tradeoff between allowing
  3446. # reasonable code and avoiding trying to parse more C++ using regexps.
  3447. if not Search(r'^\s*}[\w\*,\s]*;', next_line):
  3448. error(filename, linenum, 'readability/constructors', 3,
  3449. match.group(1) + ' should be the last thing in the class')
  3450. # Check for use of unnamed namespaces in header files. Registration
  3451. # macros are typically OK, so we allow use of "namespace {" on lines
  3452. # that end with backslashes.
  3453. if (file_extension == 'h'
  3454. and Search(r'\bnamespace\s*{', line)
  3455. and line[-1] != '\\'):
  3456. error(filename, linenum, 'build/namespaces', 4,
  3457. 'Do not use unnamed namespaces in header files. See '
  3458. 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
  3459. ' for more information.')
  3460. def CheckForNonConstReference(filename, clean_lines, linenum,
  3461. nesting_state, error):
  3462. """Check for non-const references.
  3463. Separate from CheckLanguage since it scans backwards from current
  3464. line, instead of scanning forward.
  3465. Args:
  3466. filename: The name of the current file.
  3467. clean_lines: A CleansedLines instance containing the file.
  3468. linenum: The number of the line to check.
  3469. nesting_state: A _NestingState instance which maintains information about
  3470. the current stack of nested blocks being parsed.
  3471. error: The function to call with any errors found.
  3472. """
  3473. # Do nothing if there is no '&' on current line.
  3474. line = clean_lines.elided[linenum]
  3475. if '&' not in line:
  3476. return
  3477. # Long type names may be broken across multiple lines, usually in one
  3478. # of these forms:
  3479. # LongType
  3480. # ::LongTypeContinued &identifier
  3481. # LongType::
  3482. # LongTypeContinued &identifier
  3483. # LongType<
  3484. # ...>::LongTypeContinued &identifier
  3485. #
  3486. # If we detected a type split across two lines, join the previous
  3487. # line to current line so that we can match const references
  3488. # accordingly.
  3489. #
  3490. # Note that this only scans back one line, since scanning back
  3491. # arbitrary number of lines would be expensive. If you have a type
  3492. # that spans more than 2 lines, please use a typedef.
  3493. if linenum > 1:
  3494. previous = None
  3495. if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
  3496. # previous_line\n + ::current_line
  3497. previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
  3498. clean_lines.elided[linenum - 1])
  3499. elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
  3500. # previous_line::\n + current_line
  3501. previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
  3502. clean_lines.elided[linenum - 1])
  3503. if previous:
  3504. line = previous.group(1) + line.lstrip()
  3505. else:
  3506. # Check for templated parameter that is split across multiple lines
  3507. endpos = line.rfind('>')
  3508. if endpos > -1:
  3509. (_, startline, startpos) = ReverseCloseExpression(
  3510. clean_lines, linenum, endpos)
  3511. if startpos > -1 and startline < linenum:
  3512. # Found the matching < on an earlier line, collect all
  3513. # pieces up to current line.
  3514. line = ''
  3515. for i in xrange(startline, linenum + 1):
  3516. line += clean_lines.elided[i].strip()
  3517. # Check for non-const references in function parameters. A single '&' may
  3518. # found in the following places:
  3519. # inside expression: binary & for bitwise AND
  3520. # inside expression: unary & for taking the address of something
  3521. # inside declarators: reference parameter
  3522. # We will exclude the first two cases by checking that we are not inside a
  3523. # function body, including one that was just introduced by a trailing '{'.
  3524. # TODO(unknwon): Doesn't account for preprocessor directives.
  3525. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
  3526. check_params = False
  3527. if not nesting_state.stack:
  3528. check_params = True # top level
  3529. elif (isinstance(nesting_state.stack[-1], _ClassInfo) or
  3530. isinstance(nesting_state.stack[-1], _NamespaceInfo)):
  3531. check_params = True # within class or namespace
  3532. elif Match(r'.*{\s*$', line):
  3533. if (len(nesting_state.stack) == 1 or
  3534. isinstance(nesting_state.stack[-2], _ClassInfo) or
  3535. isinstance(nesting_state.stack[-2], _NamespaceInfo)):
  3536. check_params = True # just opened global/class/namespace block
  3537. # We allow non-const references in a few standard places, like functions
  3538. # called "swap()" or iostream operators like "<<" or ">>". Do not check
  3539. # those function parameters.
  3540. #
  3541. # We also accept & in static_assert, which looks like a function but
  3542. # it's actually a declaration expression.
  3543. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
  3544. r'operator\s*[<>][<>]|'
  3545. r'static_assert|COMPILE_ASSERT'
  3546. r')\s*\(')
  3547. if Search(whitelisted_functions, line):
  3548. check_params = False
  3549. elif not Search(r'\S+\([^)]*$', line):
  3550. # Don't see a whitelisted function on this line. Actually we
  3551. # didn't see any function name on this line, so this is likely a
  3552. # multi-line parameter list. Try a bit harder to catch this case.
  3553. for i in xrange(2):
  3554. if (linenum > i and
  3555. Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
  3556. check_params = False
  3557. break
  3558. if check_params:
  3559. decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
  3560. for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
  3561. if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter):
  3562. error(filename, linenum, 'runtime/references', 2,
  3563. 'Is this a non-const reference? '
  3564. 'If so, make const or use a pointer: ' +
  3565. ReplaceAll(' *<', '<', parameter))
  3566. def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
  3567. error):
  3568. """Checks for a C-style cast by looking for the pattern.
  3569. Args:
  3570. filename: The name of the current file.
  3571. linenum: The number of the line to check.
  3572. line: The line of code to check.
  3573. raw_line: The raw line of code to check, with comments.
  3574. cast_type: The string for the C++ cast to recommend. This is either
  3575. reinterpret_cast, static_cast, or const_cast, depending.
  3576. pattern: The regular expression used to find C-style casts.
  3577. error: The function to call with any errors found.
  3578. Returns:
  3579. True if an error was emitted.
  3580. False otherwise.
  3581. """
  3582. match = Search(pattern, line)
  3583. if not match:
  3584. return False
  3585. # Exclude lines with sizeof, since sizeof looks like a cast.
  3586. sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
  3587. if sizeof_match:
  3588. return False
  3589. # operator++(int) and operator--(int)
  3590. if (line[0:match.start(1) - 1].endswith(' operator++') or
  3591. line[0:match.start(1) - 1].endswith(' operator--')):
  3592. return False
  3593. # A single unnamed argument for a function tends to look like old
  3594. # style cast. If we see those, don't issue warnings for deprecated
  3595. # casts, instead issue warnings for unnamed arguments where
  3596. # appropriate.
  3597. #
  3598. # These are things that we want warnings for, since the style guide
  3599. # explicitly require all parameters to be named:
  3600. # Function(int);
  3601. # Function(int) {
  3602. # ConstMember(int) const;
  3603. # ConstMember(int) const {
  3604. # ExceptionMember(int) throw (...);
  3605. # ExceptionMember(int) throw (...) {
  3606. # PureVirtual(int) = 0;
  3607. #
  3608. # These are functions of some sort, where the compiler would be fine
  3609. # if they had named parameters, but people often omit those
  3610. # identifiers to reduce clutter:
  3611. # (FunctionPointer)(int);
  3612. # (FunctionPointer)(int) = value;
  3613. # Function((function_pointer_arg)(int))
  3614. # <TemplateArgument(int)>;
  3615. # <(FunctionPointerTemplateArgument)(int)>;
  3616. remainder = line[match.end(0):]
  3617. if Match(r'^\s*(?:;|const\b|throw\b|=|>|\{|\))', remainder):
  3618. # Looks like an unnamed parameter.
  3619. # Don't warn on any kind of template arguments.
  3620. if Match(r'^\s*>', remainder):
  3621. return False
  3622. # Don't warn on assignments to function pointers, but keep warnings for
  3623. # unnamed parameters to pure virtual functions. Note that this pattern
  3624. # will also pass on assignments of "0" to function pointers, but the
  3625. # preferred values for those would be "nullptr" or "NULL".
  3626. matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
  3627. if matched_zero and matched_zero.group(1) != '0':
  3628. return False
  3629. # Don't warn on function pointer declarations. For this we need
  3630. # to check what came before the "(type)" string.
  3631. if Match(r'.*\)\s*$', line[0:match.start(0)]):
  3632. return False
  3633. # Don't warn if the parameter is named with block comments, e.g.:
  3634. # Function(int /*unused_param*/);
  3635. if '/*' in raw_line:
  3636. return False
  3637. # Passed all filters, issue warning here.
  3638. error(filename, linenum, 'readability/function', 3,
  3639. 'All parameters should be named in a function')
  3640. return True
  3641. # At this point, all that should be left is actual casts.
  3642. error(filename, linenum, 'readability/casting', 4,
  3643. 'Using C-style cast. Use %s<%s>(...) instead' %
  3644. (cast_type, match.group(1)))
  3645. return True
  3646. _HEADERS_CONTAINING_TEMPLATES = (
  3647. ('<deque>', ('deque',)),
  3648. ('<functional>', ('unary_function', 'binary_function',
  3649. 'plus', 'minus', 'multiplies', 'divides', 'modulus',
  3650. 'negate',
  3651. 'equal_to', 'not_equal_to', 'greater', 'less',
  3652. 'greater_equal', 'less_equal',
  3653. 'logical_and', 'logical_or', 'logical_not',
  3654. 'unary_negate', 'not1', 'binary_negate', 'not2',
  3655. 'bind1st', 'bind2nd',
  3656. 'pointer_to_unary_function',
  3657. 'pointer_to_binary_function',
  3658. 'ptr_fun',
  3659. 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
  3660. 'mem_fun_ref_t',
  3661. 'const_mem_fun_t', 'const_mem_fun1_t',
  3662. 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
  3663. 'mem_fun_ref',
  3664. )),
  3665. ('<limits>', ('numeric_limits',)),
  3666. ('<list>', ('list',)),
  3667. ('<map>', ('map', 'multimap',)),
  3668. ('<memory>', ('allocator',)),
  3669. ('<queue>', ('queue', 'priority_queue',)),
  3670. ('<set>', ('set', 'multiset',)),
  3671. ('<stack>', ('stack',)),
  3672. ('<string>', ('char_traits', 'basic_string',)),
  3673. ('<utility>', ('pair',)),
  3674. ('<vector>', ('vector',)),
  3675. # gcc extensions.
  3676. # Note: std::hash is their hash, ::hash is our hash
  3677. ('<hash_map>', ('hash_map', 'hash_multimap',)),
  3678. ('<hash_set>', ('hash_set', 'hash_multiset',)),
  3679. ('<slist>', ('slist',)),
  3680. )
  3681. _RE_PATTERN_STRING = re.compile(r'\bstring\b')
  3682. _re_pattern_algorithm_header = []
  3683. for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
  3684. 'transform'):
  3685. # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
  3686. # type::max().
  3687. _re_pattern_algorithm_header.append(
  3688. (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
  3689. _template,
  3690. '<algorithm>'))
  3691. _re_pattern_templates = []
  3692. for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
  3693. for _template in _templates:
  3694. _re_pattern_templates.append(
  3695. (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
  3696. _template + '<>',
  3697. _header))
  3698. def FilesBelongToSameModule(filename_cc, filename_h):
  3699. """Check if these two filenames belong to the same module.
  3700. The concept of a 'module' here is a as follows:
  3701. foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
  3702. same 'module' if they are in the same directory.
  3703. some/path/public/xyzzy and some/path/internal/xyzzy are also considered
  3704. to belong to the same module here.
  3705. If the filename_cc contains a longer path than the filename_h, for example,
  3706. '/absolute/path/to/base/sysinfo.cc', and this file would include
  3707. 'base/sysinfo.h', this function also produces the prefix needed to open the
  3708. header. This is used by the caller of this function to more robustly open the
  3709. header file. We don't have access to the real include paths in this context,
  3710. so we need this guesswork here.
  3711. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
  3712. according to this implementation. Because of this, this function gives
  3713. some false positives. This should be sufficiently rare in practice.
  3714. Args:
  3715. filename_cc: is the path for the .cc file
  3716. filename_h: is the path for the header path
  3717. Returns:
  3718. Tuple with a bool and a string:
  3719. bool: True if filename_cc and filename_h belong to the same module.
  3720. string: the additional prefix needed to open the header file.
  3721. """
  3722. if not filename_cc.endswith('.cc'):
  3723. return (False, '')
  3724. filename_cc = filename_cc[:-len('.cc')]
  3725. if filename_cc.endswith('_unittest'):
  3726. filename_cc = filename_cc[:-len('_unittest')]
  3727. elif filename_cc.endswith('_test'):
  3728. filename_cc = filename_cc[:-len('_test')]
  3729. filename_cc = filename_cc.replace('/public/', '/')
  3730. filename_cc = filename_cc.replace('/internal/', '/')
  3731. if not filename_h.endswith('.h'):
  3732. return (False, '')
  3733. filename_h = filename_h[:-len('.h')]
  3734. if filename_h.endswith('-inl'):
  3735. filename_h = filename_h[:-len('-inl')]
  3736. filename_h = filename_h.replace('/public/', '/')
  3737. filename_h = filename_h.replace('/internal/', '/')
  3738. files_belong_to_same_module = filename_cc.endswith(filename_h)
  3739. common_path = ''
  3740. if files_belong_to_same_module:
  3741. common_path = filename_cc[:-len(filename_h)]
  3742. return files_belong_to_same_module, common_path
  3743. def UpdateIncludeState(filename, include_state, io=codecs):
  3744. """Fill up the include_state with new includes found from the file.
  3745. Args:
  3746. filename: the name of the header to read.
  3747. include_state: an _IncludeState instance in which the headers are inserted.
  3748. io: The io factory to use to read the file. Provided for testability.
  3749. Returns:
  3750. True if a header was succesfully added. False otherwise.
  3751. """
  3752. headerfile = None
  3753. try:
  3754. headerfile = io.open(filename, 'r', 'utf8', 'replace')
  3755. except IOError:
  3756. return False
  3757. linenum = 0
  3758. for line in headerfile:
  3759. linenum += 1
  3760. clean_line = CleanseComments(line)
  3761. match = _RE_PATTERN_INCLUDE.search(clean_line)
  3762. if match:
  3763. include = match.group(2)
  3764. # The value formatting is cute, but not really used right now.
  3765. # What matters here is that the key is in include_state.
  3766. include_state.setdefault(include, '%s:%d' % (filename, linenum))
  3767. return True
  3768. def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
  3769. io=codecs):
  3770. """Reports for missing stl includes.
  3771. This function will output warnings to make sure you are including the headers
  3772. necessary for the stl containers and functions that you use. We only give one
  3773. reason to include a header. For example, if you use both equal_to<> and
  3774. less<> in a .h file, only one (the latter in the file) of these will be
  3775. reported as a reason to include the <functional>.
  3776. Args:
  3777. filename: The name of the current file.
  3778. clean_lines: A CleansedLines instance containing the file.
  3779. include_state: An _IncludeState instance.
  3780. error: The function to call with any errors found.
  3781. io: The IO factory to use to read the header file. Provided for unittest
  3782. injection.
  3783. """
  3784. required = {} # A map of header name to linenumber and the template entity.
  3785. # Example of required: { '<functional>': (1219, 'less<>') }
  3786. for linenum in xrange(clean_lines.NumLines()):
  3787. line = clean_lines.elided[linenum]
  3788. if not line or line[0] == '#':
  3789. continue
  3790. # String is special -- it is a non-templatized type in STL.
  3791. matched = _RE_PATTERN_STRING.search(line)
  3792. if matched:
  3793. # Don't warn about strings in non-STL namespaces:
  3794. # (We check only the first match per line; good enough.)
  3795. prefix = line[:matched.start()]
  3796. if prefix.endswith('std::') or not prefix.endswith('::'):
  3797. required['<string>'] = (linenum, 'string')
  3798. for pattern, template, header in _re_pattern_algorithm_header:
  3799. if pattern.search(line):
  3800. required[header] = (linenum, template)
  3801. # The following function is just a speed up, no semantics are changed.
  3802. if not '<' in line: # Reduces the cpu time usage by skipping lines.
  3803. continue
  3804. for pattern, template, header in _re_pattern_templates:
  3805. if pattern.search(line):
  3806. required[header] = (linenum, template)
  3807. # The policy is that if you #include something in foo.h you don't need to
  3808. # include it again in foo.cc. Here, we will look at possible includes.
  3809. # Let's copy the include_state so it is only messed up within this function.
  3810. include_state = include_state.copy()
  3811. # Did we find the header for this file (if any) and succesfully load it?
  3812. header_found = False
  3813. # Use the absolute path so that matching works properly.
  3814. abs_filename = FileInfo(filename).FullName()
  3815. # For Emacs's flymake.
  3816. # If cpplint is invoked from Emacs's flymake, a temporary file is generated
  3817. # by flymake and that file name might end with '_flymake.cc'. In that case,
  3818. # restore original file name here so that the corresponding header file can be
  3819. # found.
  3820. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
  3821. # instead of 'foo_flymake.h'
  3822. abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
  3823. # include_state is modified during iteration, so we iterate over a copy of
  3824. # the keys.
  3825. header_keys = include_state.keys()
  3826. for header in header_keys:
  3827. (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
  3828. fullpath = common_path + header
  3829. if same_module and UpdateIncludeState(fullpath, include_state, io):
  3830. header_found = True
  3831. # If we can't find the header file for a .cc, assume it's because we don't
  3832. # know where to look. In that case we'll give up as we're not sure they
  3833. # didn't include it in the .h file.
  3834. # TODO(unknown): Do a better job of finding .h files so we are confident that
  3835. # not having the .h file means there isn't one.
  3836. if filename.endswith('.cc') and not header_found:
  3837. return
  3838. # All the lines have been processed, report the errors found.
  3839. for required_header_unstripped in required:
  3840. template = required[required_header_unstripped][1]
  3841. if required_header_unstripped.strip('<>"') not in include_state:
  3842. error(filename, required[required_header_unstripped][0],
  3843. 'build/include_what_you_use', 4,
  3844. 'Add #include ' + required_header_unstripped + ' for ' + template)
  3845. _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
  3846. def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
  3847. """Check that make_pair's template arguments are deduced.
  3848. G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
  3849. specified explicitly, and such use isn't intended in any case.
  3850. Args:
  3851. filename: The name of the current file.
  3852. clean_lines: A CleansedLines instance containing the file.
  3853. linenum: The number of the line to check.
  3854. error: The function to call with any errors found.
  3855. """
  3856. line = clean_lines.elided[linenum]
  3857. match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
  3858. if match:
  3859. error(filename, linenum, 'build/explicit_make_pair',
  3860. 4, # 4 = high confidence
  3861. 'For C++11-compatibility, omit template arguments from make_pair'
  3862. ' OR use pair directly OR if appropriate, construct a pair directly')
  3863. def ProcessLine(filename, file_extension, clean_lines, line,
  3864. include_state, function_state, nesting_state, error,
  3865. extra_check_functions=[]):
  3866. """Processes a single line in the file.
  3867. Args:
  3868. filename: Filename of the file that is being processed.
  3869. file_extension: The extension (dot not included) of the file.
  3870. clean_lines: An array of strings, each representing a line of the file,
  3871. with comments stripped.
  3872. line: Number of line being processed.
  3873. include_state: An _IncludeState instance in which the headers are inserted.
  3874. function_state: A _FunctionState instance which counts function lines, etc.
  3875. nesting_state: A _NestingState instance which maintains information about
  3876. the current stack of nested blocks being parsed.
  3877. error: A callable to which errors are reported, which takes 4 arguments:
  3878. filename, line number, error level, and message
  3879. extra_check_functions: An array of additional check functions that will be
  3880. run on each source line. Each function takes 4
  3881. arguments: filename, clean_lines, line, error
  3882. """
  3883. raw_lines = clean_lines.raw_lines
  3884. ParseNolintSuppressions(filename, raw_lines[line], line, error)
  3885. nesting_state.Update(filename, clean_lines, line, error)
  3886. if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM:
  3887. return
  3888. CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
  3889. CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
  3890. CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
  3891. CheckLanguage(filename, clean_lines, line, file_extension, include_state,
  3892. nesting_state, error)
  3893. CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
  3894. CheckForNonStandardConstructs(filename, clean_lines, line,
  3895. nesting_state, error)
  3896. CheckVlogArguments(filename, clean_lines, line, error)
  3897. CheckPosixThreading(filename, clean_lines, line, error)
  3898. CheckInvalidIncrement(filename, clean_lines, line, error)
  3899. CheckMakePairUsesDeduction(filename, clean_lines, line, error)
  3900. for check_fn in extra_check_functions:
  3901. check_fn(filename, clean_lines, line, error)
  3902. def ProcessFileData(filename, file_extension, lines, error,
  3903. extra_check_functions=[]):
  3904. """Performs lint checks and reports any errors to the given error function.
  3905. Args:
  3906. filename: Filename of the file that is being processed.
  3907. file_extension: The extension (dot not included) of the file.
  3908. lines: An array of strings, each representing a line of the file, with the
  3909. last element being empty if the file is terminated with a newline.
  3910. error: A callable to which errors are reported, which takes 4 arguments:
  3911. filename, line number, error level, and message
  3912. extra_check_functions: An array of additional check functions that will be
  3913. run on each source line. Each function takes 4
  3914. arguments: filename, clean_lines, line, error
  3915. """
  3916. lines = (['// marker so line numbers and indices both start at 1'] + lines +
  3917. ['// marker so line numbers end in a known way'])
  3918. include_state = _IncludeState()
  3919. function_state = _FunctionState()
  3920. nesting_state = _NestingState()
  3921. ResetNolintSuppressions()
  3922. CheckForCopyright(filename, lines, error)
  3923. if file_extension == 'h':
  3924. CheckForHeaderGuard(filename, lines, error)
  3925. RemoveMultiLineComments(filename, lines, error)
  3926. clean_lines = CleansedLines(lines)
  3927. for line in xrange(clean_lines.NumLines()):
  3928. ProcessLine(filename, file_extension, clean_lines, line,
  3929. include_state, function_state, nesting_state, error,
  3930. extra_check_functions)
  3931. nesting_state.CheckCompletedBlocks(filename, error)
  3932. CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
  3933. # We check here rather than inside ProcessLine so that we see raw
  3934. # lines rather than "cleaned" lines.
  3935. CheckForBadCharacters(filename, lines, error)
  3936. CheckForNewlineAtEOF(filename, lines, error)
  3937. def ProcessFile(filename, vlevel, extra_check_functions=[]):
  3938. """Does google-lint on a single file.
  3939. Args:
  3940. filename: The name of the file to parse.
  3941. vlevel: The level of errors to report. Every error of confidence
  3942. >= verbose_level will be reported. 0 is a good default.
  3943. extra_check_functions: An array of additional check functions that will be
  3944. run on each source line. Each function takes 4
  3945. arguments: filename, clean_lines, line, error
  3946. """
  3947. _SetVerboseLevel(vlevel)
  3948. try:
  3949. # Support the UNIX convention of using "-" for stdin. Note that
  3950. # we are not opening the file with universal newline support
  3951. # (which codecs doesn't support anyway), so the resulting lines do
  3952. # contain trailing '\r' characters if we are reading a file that
  3953. # has CRLF endings.
  3954. # If after the split a trailing '\r' is present, it is removed
  3955. # below. If it is not expected to be present (i.e. os.linesep !=
  3956. # '\r\n' as in Windows), a warning is issued below if this file
  3957. # is processed.
  3958. if filename == '-':
  3959. lines = codecs.StreamReaderWriter(sys.stdin,
  3960. codecs.getreader('utf8'),
  3961. codecs.getwriter('utf8'),
  3962. 'replace').read().split('\n')
  3963. else:
  3964. lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
  3965. carriage_return_found = False
  3966. # Remove trailing '\r'.
  3967. for linenum in range(len(lines)):
  3968. if lines[linenum].endswith('\r'):
  3969. lines[linenum] = lines[linenum].rstrip('\r')
  3970. carriage_return_found = True
  3971. except IOError:
  3972. sys.stderr.write(
  3973. "Skipping input '%s': Can't open for reading\n" % filename)
  3974. return
  3975. # Note, if no dot is found, this will give the entire filename as the ext.
  3976. file_extension = filename[filename.rfind('.') + 1:]
  3977. # When reading from stdin, the extension is unknown, so no cpplint tests
  3978. # should rely on the extension.
  3979. if filename != '-' and file_extension not in _valid_extensions:
  3980. sys.stderr.write('Ignoring %s; not a valid file name '
  3981. '(%s)\n' % (filename, ', '.join(_valid_extensions)))
  3982. else:
  3983. ProcessFileData(filename, file_extension, lines, Error,
  3984. extra_check_functions)
  3985. if carriage_return_found and os.linesep != '\r\n':
  3986. # Use 0 for linenum since outputting only one error for potentially
  3987. # several lines.
  3988. Error(filename, 0, 'whitespace/newline', 1,
  3989. 'One or more unexpected \\r (^M) found;'
  3990. 'better to use only a \\n')
  3991. sys.stderr.write('Done processing %s\n' % filename)
  3992. def PrintUsage(message):
  3993. """Prints a brief usage string and exits, optionally with an error message.
  3994. Args:
  3995. message: The optional error message.
  3996. """
  3997. sys.stderr.write(_USAGE)
  3998. if message:
  3999. sys.exit('\nFATAL ERROR: ' + message)
  4000. else:
  4001. sys.exit(1)
  4002. def PrintCategories():
  4003. """Prints a list of all the error-categories used by error messages.
  4004. These are the categories used to filter messages via --filter.
  4005. """
  4006. sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
  4007. sys.exit(0)
  4008. def ParseArguments(args):
  4009. """Parses the command line arguments.
  4010. This may set the output format and verbosity level as side-effects.
  4011. Args:
  4012. args: The command line arguments:
  4013. Returns:
  4014. The list of filenames to lint.
  4015. """
  4016. try:
  4017. (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
  4018. 'counting=',
  4019. 'filter=',
  4020. 'root=',
  4021. 'linelength=',
  4022. 'extensions='])
  4023. except getopt.GetoptError:
  4024. PrintUsage('Invalid arguments.')
  4025. verbosity = _VerboseLevel()
  4026. output_format = _OutputFormat()
  4027. filters = ''
  4028. counting_style = ''
  4029. for (opt, val) in opts:
  4030. if opt == '--help':
  4031. PrintUsage(None)
  4032. elif opt == '--output':
  4033. if val not in ('emacs', 'vs7', 'eclipse'):
  4034. PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
  4035. output_format = val
  4036. elif opt == '--verbose':
  4037. verbosity = int(val)
  4038. elif opt == '--filter':
  4039. filters = val
  4040. if not filters:
  4041. PrintCategories()
  4042. elif opt == '--counting':
  4043. if val not in ('total', 'toplevel', 'detailed'):
  4044. PrintUsage('Valid counting options are total, toplevel, and detailed')
  4045. counting_style = val
  4046. elif opt == '--root':
  4047. global _root
  4048. _root = val
  4049. elif opt == '--linelength':
  4050. global _line_length
  4051. try:
  4052. _line_length = int(val)
  4053. except ValueError:
  4054. PrintUsage('Line length must be digits.')
  4055. elif opt == '--extensions':
  4056. global _valid_extensions
  4057. try:
  4058. _valid_extensions = set(val.split(','))
  4059. except ValueError:
  4060. PrintUsage('Extensions must be comma seperated list.')
  4061. if not filenames:
  4062. PrintUsage('No files were specified.')
  4063. _SetOutputFormat(output_format)
  4064. _SetVerboseLevel(verbosity)
  4065. _SetFilters(filters)
  4066. _SetCountingStyle(counting_style)
  4067. return filenames
  4068. def main():
  4069. filenames = ParseArguments(sys.argv[1:])
  4070. # Change stderr to write with replacement characters so we don't die
  4071. # if we try to print something containing non-ASCII characters.
  4072. sys.stderr = codecs.StreamReaderWriter(sys.stderr,
  4073. codecs.getreader('utf8'),
  4074. codecs.getwriter('utf8'),
  4075. 'replace')
  4076. _cpplint_state.ResetErrorCounts()
  4077. for filename in filenames:
  4078. ProcessFile(filename, _cpplint_state.verbose_level)
  4079. _cpplint_state.PrintErrorCounts()
  4080. sys.exit(_cpplint_state.error_count > 0)
  4081. if __name__ == '__main__':
  4082. main()