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

6325 lines
236 KiB

  1. #!/usr/bin/env python
  2. #
  3. # Copyright (c) 2009 Google Inc. All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """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. Assuming 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. cpplint.py supports per-directory configurations specified in CPPLINT.cfg
  113. files. CPPLINT.cfg file can contain a number of key=value pairs.
  114. Currently the following options are supported:
  115. set noparent
  116. filter=+filter1,-filter2,...
  117. exclude_files=regex
  118. linelength=80
  119. "set noparent" option prevents cpplint from traversing directory tree
  120. upwards looking for more .cfg files in parent directories. This option
  121. is usually placed in the top-level project directory.
  122. The "filter" option is similar in function to --filter flag. It specifies
  123. message filters in addition to the |_DEFAULT_FILTERS| and those specified
  124. through --filter command-line flag.
  125. "exclude_files" allows to specify a regular expression to be matched against
  126. a file name. If the expression matches, the file is skipped and not run
  127. through liner.
  128. "linelength" allows to specify the allowed line length for the project.
  129. CPPLINT.cfg has an effect on files in the same directory and all
  130. sub-directories, unless overridden by a nested configuration file.
  131. Example file:
  132. filter=-build/include_order,+build/include_alpha
  133. exclude_files=.*\.cc
  134. The above example disables build/include_order warning and enables
  135. build/include_alpha as well as excludes all .cc from being
  136. processed by linter, in the current directory (where the .cfg
  137. file is located) and all sub-directories.
  138. """
  139. # We categorize each error message we print. Here are the categories.
  140. # We want an explicit list so we can list them all in cpplint --filter=.
  141. # If you add a new error message with a new category, add it to the list
  142. # here! cpplint_unittest.py should tell you if you forget to do this.
  143. _ERROR_CATEGORIES = [
  144. 'build/class',
  145. 'build/c++11',
  146. 'build/deprecated',
  147. 'build/endif_comment',
  148. 'build/explicit_make_pair',
  149. 'build/forward_decl',
  150. 'build/header_guard',
  151. 'build/include',
  152. 'build/include_alpha',
  153. 'build/include_order',
  154. 'build/include_what_you_use',
  155. 'build/namespaces',
  156. 'build/printf_format',
  157. 'build/storage_class',
  158. 'legal/copyright',
  159. 'readability/alt_tokens',
  160. 'readability/braces',
  161. 'readability/casting',
  162. 'readability/check',
  163. 'readability/constructors',
  164. 'readability/fn_size',
  165. 'readability/function',
  166. 'readability/inheritance',
  167. 'readability/multiline_comment',
  168. 'readability/multiline_string',
  169. 'readability/namespace',
  170. 'readability/nolint',
  171. 'readability/nul',
  172. 'readability/strings',
  173. 'readability/todo',
  174. 'readability/utf8',
  175. 'runtime/arrays',
  176. 'runtime/casting',
  177. 'runtime/explicit',
  178. 'runtime/int',
  179. 'runtime/init',
  180. 'runtime/invalid_increment',
  181. 'runtime/member_string_references',
  182. 'runtime/memset',
  183. 'runtime/indentation_namespace',
  184. 'runtime/operator',
  185. 'runtime/printf',
  186. 'runtime/printf_format',
  187. 'runtime/references',
  188. 'runtime/string',
  189. 'runtime/threadsafe_fn',
  190. 'runtime/vlog',
  191. 'whitespace/blank_line',
  192. 'whitespace/braces',
  193. 'whitespace/comma',
  194. 'whitespace/comments',
  195. 'whitespace/empty_conditional_body',
  196. 'whitespace/empty_loop_body',
  197. 'whitespace/end_of_line',
  198. 'whitespace/ending_newline',
  199. 'whitespace/forcolon',
  200. 'whitespace/indent',
  201. 'whitespace/line_length',
  202. 'whitespace/newline',
  203. 'whitespace/operators',
  204. 'whitespace/parens',
  205. 'whitespace/semicolon',
  206. 'whitespace/tab',
  207. 'whitespace/todo',
  208. ]
  209. # These error categories are no longer enforced by cpplint, but for backwards-
  210. # compatibility they may still appear in NOLINT comments.
  211. _LEGACY_ERROR_CATEGORIES = [
  212. 'readability/streams',
  213. ]
  214. # The default state of the category filter. This is overridden by the --filter=
  215. # flag. By default all errors are on, so only add here categories that should be
  216. # off by default (i.e., categories that must be enabled by the --filter= flags).
  217. # All entries here should start with a '-' or '+', as in the --filter= flag.
  218. _DEFAULT_FILTERS = ['-build/include_alpha']
  219. # We used to check for high-bit characters, but after much discussion we
  220. # decided those were OK, as long as they were in UTF-8 and didn't represent
  221. # hard-coded international strings, which belong in a separate i18n file.
  222. # C++ headers
  223. _CPP_HEADERS = frozenset([
  224. # Legacy
  225. 'algobase.h',
  226. 'algo.h',
  227. 'alloc.h',
  228. 'builtinbuf.h',
  229. 'bvector.h',
  230. 'complex.h',
  231. 'defalloc.h',
  232. 'deque.h',
  233. 'editbuf.h',
  234. 'fstream.h',
  235. 'function.h',
  236. 'hash_map',
  237. 'hash_map.h',
  238. 'hash_set',
  239. 'hash_set.h',
  240. 'hashtable.h',
  241. 'heap.h',
  242. 'indstream.h',
  243. 'iomanip.h',
  244. 'iostream.h',
  245. 'istream.h',
  246. 'iterator.h',
  247. 'list.h',
  248. 'map.h',
  249. 'multimap.h',
  250. 'multiset.h',
  251. 'ostream.h',
  252. 'pair.h',
  253. 'parsestream.h',
  254. 'pfstream.h',
  255. 'procbuf.h',
  256. 'pthread_alloc',
  257. 'pthread_alloc.h',
  258. 'rope',
  259. 'rope.h',
  260. 'ropeimpl.h',
  261. 'set.h',
  262. 'slist',
  263. 'slist.h',
  264. 'stack.h',
  265. 'stdiostream.h',
  266. 'stl_alloc.h',
  267. 'stl_relops.h',
  268. 'streambuf.h',
  269. 'stream.h',
  270. 'strfile.h',
  271. 'strstream.h',
  272. 'tempbuf.h',
  273. 'tree.h',
  274. 'type_traits.h',
  275. 'vector.h',
  276. # 17.6.1.2 C++ library headers
  277. 'algorithm',
  278. 'array',
  279. 'atomic',
  280. 'bitset',
  281. 'chrono',
  282. 'codecvt',
  283. 'complex',
  284. 'condition_variable',
  285. 'deque',
  286. 'exception',
  287. 'forward_list',
  288. 'fstream',
  289. 'functional',
  290. 'future',
  291. 'initializer_list',
  292. 'iomanip',
  293. 'ios',
  294. 'iosfwd',
  295. 'iostream',
  296. 'istream',
  297. 'iterator',
  298. 'limits',
  299. 'list',
  300. 'locale',
  301. 'map',
  302. 'memory',
  303. 'mutex',
  304. 'new',
  305. 'numeric',
  306. 'ostream',
  307. 'queue',
  308. 'random',
  309. 'ratio',
  310. 'regex',
  311. 'set',
  312. 'sstream',
  313. 'stack',
  314. 'stdexcept',
  315. 'streambuf',
  316. 'string',
  317. 'strstream',
  318. 'system_error',
  319. 'thread',
  320. 'tuple',
  321. 'typeindex',
  322. 'typeinfo',
  323. 'type_traits',
  324. 'unordered_map',
  325. 'unordered_set',
  326. 'utility',
  327. 'valarray',
  328. 'vector',
  329. # 17.6.1.2 C++ headers for C library facilities
  330. 'cassert',
  331. 'ccomplex',
  332. 'cctype',
  333. 'cerrno',
  334. 'cfenv',
  335. 'cfloat',
  336. 'cinttypes',
  337. 'ciso646',
  338. 'climits',
  339. 'clocale',
  340. 'cmath',
  341. 'csetjmp',
  342. 'csignal',
  343. 'cstdalign',
  344. 'cstdarg',
  345. 'cstdbool',
  346. 'cstddef',
  347. 'cstdint',
  348. 'cstdio',
  349. 'cstdlib',
  350. 'cstring',
  351. 'ctgmath',
  352. 'ctime',
  353. 'cuchar',
  354. 'cwchar',
  355. 'cwctype',
  356. ])
  357. # These headers are excluded from [build/include] and [build/include_order]
  358. # checks:
  359. # - Anything not following google file name conventions (containing an
  360. # uppercase character, such as Python.h or nsStringAPI.h, for example).
  361. # - Lua headers.
  362. # - rdkafka.cpp header, because it would be located in different directories depending
  363. # on whether it's pulled from librdkafka sources or librdkafka-dev package.
  364. _THIRD_PARTY_HEADERS_PATTERN = re.compile(
  365. r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h|rdkafkacpp\.h)$')
  366. # Assertion macros. These are defined in base/logging.h and
  367. # testing/base/gunit.h. Note that the _M versions need to come first
  368. # for substring matching to work.
  369. _CHECK_MACROS = [
  370. 'DCHECK', 'CHECK',
  371. 'EXPECT_TRUE_M', 'EXPECT_TRUE',
  372. 'ASSERT_TRUE_M', 'ASSERT_TRUE',
  373. 'EXPECT_FALSE_M', 'EXPECT_FALSE',
  374. 'ASSERT_FALSE_M', 'ASSERT_FALSE',
  375. ]
  376. # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
  377. _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
  378. for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
  379. ('>=', 'GE'), ('>', 'GT'),
  380. ('<=', 'LE'), ('<', 'LT')]:
  381. _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
  382. _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
  383. _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
  384. _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
  385. _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
  386. _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
  387. for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
  388. ('>=', 'LT'), ('>', 'LE'),
  389. ('<=', 'GT'), ('<', 'GE')]:
  390. _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
  391. _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
  392. _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
  393. _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
  394. # Alternative tokens and their replacements. For full list, see section 2.5
  395. # Alternative tokens [lex.digraph] in the C++ standard.
  396. #
  397. # Digraphs (such as '%:') are not included here since it's a mess to
  398. # match those on a word boundary.
  399. _ALT_TOKEN_REPLACEMENT = {
  400. 'and': '&&',
  401. 'bitor': '|',
  402. 'or': '||',
  403. 'xor': '^',
  404. 'compl': '~',
  405. 'bitand': '&',
  406. 'and_eq': '&=',
  407. 'or_eq': '|=',
  408. 'xor_eq': '^=',
  409. 'not': '!',
  410. 'not_eq': '!='
  411. }
  412. # Compile regular expression that matches all the above keywords. The "[ =()]"
  413. # bit is meant to avoid matching these keywords outside of boolean expressions.
  414. #
  415. # False positives include C-style multi-line comments and multi-line strings
  416. # but those have always been troublesome for cpplint.
  417. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
  418. r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
  419. # These constants define types of headers for use with
  420. # _IncludeState.CheckNextIncludeOrder().
  421. _C_SYS_HEADER = 1
  422. _CPP_SYS_HEADER = 2
  423. _LIKELY_MY_HEADER = 3
  424. _POSSIBLE_MY_HEADER = 4
  425. _OTHER_HEADER = 5
  426. # These constants define the current inline assembly state
  427. _NO_ASM = 0 # Outside of inline assembly block
  428. _INSIDE_ASM = 1 # Inside inline assembly block
  429. _END_ASM = 2 # Last line of inline assembly block
  430. _BLOCK_ASM = 3 # The whole block is an inline assembly block
  431. # Match start of assembly blocks
  432. _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
  433. r'(?:\s+(volatile|__volatile__))?'
  434. r'\s*[{(]')
  435. _regexp_compile_cache = {}
  436. # {str, set(int)}: a map from error categories to sets of linenumbers
  437. # on which those errors are expected and should be suppressed.
  438. _error_suppressions = {}
  439. # The root directory used for deriving header guard CPP variable.
  440. # This is set by --root flag.
  441. _root = None
  442. # The allowed line length of files.
  443. # This is set by --linelength flag.
  444. _line_length = 80
  445. # The allowed extensions for file names
  446. # This is set by --extensions flag.
  447. _valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
  448. def ParseNolintSuppressions(filename, raw_line, linenum, error):
  449. """Updates the global list of error-suppressions.
  450. Parses any NOLINT comments on the current line, updating the global
  451. error_suppressions store. Reports an error if the NOLINT comment
  452. was malformed.
  453. Args:
  454. filename: str, the name of the input file.
  455. raw_line: str, the line of input text, with comments.
  456. linenum: int, the number of the current line.
  457. error: function, an error handler.
  458. """
  459. matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
  460. if matched:
  461. if matched.group(1):
  462. suppressed_line = linenum + 1
  463. else:
  464. suppressed_line = linenum
  465. category = matched.group(2)
  466. if category in (None, '(*)'): # => "suppress all"
  467. _error_suppressions.setdefault(None, set()).add(suppressed_line)
  468. else:
  469. if category.startswith('(') and category.endswith(')'):
  470. category = category[1:-1]
  471. if category in _ERROR_CATEGORIES:
  472. _error_suppressions.setdefault(category, set()).add(suppressed_line)
  473. elif category not in _LEGACY_ERROR_CATEGORIES:
  474. error(filename, linenum, 'readability/nolint', 5,
  475. 'Unknown NOLINT error category: %s' % category)
  476. def ResetNolintSuppressions():
  477. """Resets the set of NOLINT suppressions to empty."""
  478. _error_suppressions.clear()
  479. def IsErrorSuppressedByNolint(category, linenum):
  480. """Returns true if the specified error category is suppressed on this line.
  481. Consults the global error_suppressions map populated by
  482. ParseNolintSuppressions/ResetNolintSuppressions.
  483. Args:
  484. category: str, the category of the error.
  485. linenum: int, the current line number.
  486. Returns:
  487. bool, True iff the error should be suppressed due to a NOLINT comment.
  488. """
  489. return (linenum in _error_suppressions.get(category, set()) or
  490. linenum in _error_suppressions.get(None, set()))
  491. def Match(pattern, s):
  492. """Matches the string with the pattern, caching the compiled regexp."""
  493. # The regexp compilation caching is inlined in both Match and Search for
  494. # performance reasons; factoring it out into a separate function turns out
  495. # to be noticeably expensive.
  496. if pattern not in _regexp_compile_cache:
  497. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  498. return _regexp_compile_cache[pattern].match(s)
  499. def ReplaceAll(pattern, rep, s):
  500. """Replaces instances of pattern in a string with a replacement.
  501. The compiled regex is kept in a cache shared by Match and Search.
  502. Args:
  503. pattern: regex pattern
  504. rep: replacement text
  505. s: search string
  506. Returns:
  507. string with replacements made (or original string if no replacements)
  508. """
  509. if pattern not in _regexp_compile_cache:
  510. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  511. return _regexp_compile_cache[pattern].sub(rep, s)
  512. def Search(pattern, s):
  513. """Searches the string for the pattern, caching the compiled regexp."""
  514. if pattern not in _regexp_compile_cache:
  515. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  516. return _regexp_compile_cache[pattern].search(s)
  517. class _IncludeState(object):
  518. """Tracks line numbers for includes, and the order in which includes appear.
  519. include_list contains list of lists of (header, line number) pairs.
  520. It's a lists of lists rather than just one flat list to make it
  521. easier to update across preprocessor boundaries.
  522. Call CheckNextIncludeOrder() once for each header in the file, passing
  523. in the type constants defined above. Calls in an illegal order will
  524. raise an _IncludeError with an appropriate error message.
  525. """
  526. # self._section will move monotonically through this set. If it ever
  527. # needs to move backwards, CheckNextIncludeOrder will raise an error.
  528. _INITIAL_SECTION = 0
  529. _MY_H_SECTION = 1
  530. _C_SECTION = 2
  531. _CPP_SECTION = 3
  532. _OTHER_H_SECTION = 4
  533. _TYPE_NAMES = {
  534. _C_SYS_HEADER: 'C system header',
  535. _CPP_SYS_HEADER: 'C++ system header',
  536. _LIKELY_MY_HEADER: 'header this file implements',
  537. _POSSIBLE_MY_HEADER: 'header this file may implement',
  538. _OTHER_HEADER: 'other header',
  539. }
  540. _SECTION_NAMES = {
  541. _INITIAL_SECTION: "... nothing. (This can't be an error.)",
  542. _MY_H_SECTION: 'a header this file implements',
  543. _C_SECTION: 'C system header',
  544. _CPP_SECTION: 'C++ system header',
  545. _OTHER_H_SECTION: 'other header',
  546. }
  547. def __init__(self):
  548. self.include_list = [[]]
  549. self.ResetSection('')
  550. def FindHeader(self, header):
  551. """Check if a header has already been included.
  552. Args:
  553. header: header to check.
  554. Returns:
  555. Line number of previous occurrence, or -1 if the header has not
  556. been seen before.
  557. """
  558. for section_list in self.include_list:
  559. for f in section_list:
  560. if f[0] == header:
  561. return f[1]
  562. return -1
  563. def ResetSection(self, directive):
  564. """Reset section checking for preprocessor directive.
  565. Args:
  566. directive: preprocessor directive (e.g. "if", "else").
  567. """
  568. # The name of the current section.
  569. self._section = self._INITIAL_SECTION
  570. # The path of last found header.
  571. self._last_header = ''
  572. # Update list of includes. Note that we never pop from the
  573. # include list.
  574. if directive in ('if', 'ifdef', 'ifndef'):
  575. self.include_list.append([])
  576. elif directive in ('else', 'elif'):
  577. self.include_list[-1] = []
  578. def SetLastHeader(self, header_path):
  579. self._last_header = header_path
  580. def CanonicalizeAlphabeticalOrder(self, header_path):
  581. """Returns a path canonicalized for alphabetical comparison.
  582. - replaces "-" with "_" so they both cmp the same.
  583. - removes '-inl' since we don't require them to be after the main header.
  584. - lowercase everything, just in case.
  585. Args:
  586. header_path: Path to be canonicalized.
  587. Returns:
  588. Canonicalized path.
  589. """
  590. return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
  591. def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
  592. """Check if a header is in alphabetical order with the previous header.
  593. Args:
  594. clean_lines: A CleansedLines instance containing the file.
  595. linenum: The number of the line to check.
  596. header_path: Canonicalized header to be checked.
  597. Returns:
  598. Returns true if the header is in alphabetical order.
  599. """
  600. # If previous section is different from current section, _last_header will
  601. # be reset to empty string, so it's always less than current header.
  602. #
  603. # If previous line was a blank line, assume that the headers are
  604. # intentionally sorted the way they are.
  605. if (self._last_header > header_path and
  606. Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
  607. return False
  608. return True
  609. def CheckNextIncludeOrder(self, header_type):
  610. """Returns a non-empty error message if the next header is out of order.
  611. This function also updates the internal state to be ready to check
  612. the next include.
  613. Args:
  614. header_type: One of the _XXX_HEADER constants defined above.
  615. Returns:
  616. The empty string if the header is in the right order, or an
  617. error message describing what's wrong.
  618. """
  619. error_message = ('Found %s after %s' %
  620. (self._TYPE_NAMES[header_type],
  621. self._SECTION_NAMES[self._section]))
  622. last_section = self._section
  623. if header_type == _C_SYS_HEADER:
  624. if self._section <= self._C_SECTION:
  625. self._section = self._C_SECTION
  626. else:
  627. self._last_header = ''
  628. return error_message
  629. elif header_type == _CPP_SYS_HEADER:
  630. if self._section <= self._CPP_SECTION:
  631. self._section = self._CPP_SECTION
  632. else:
  633. self._last_header = ''
  634. return error_message
  635. elif header_type == _LIKELY_MY_HEADER:
  636. if self._section <= self._MY_H_SECTION:
  637. self._section = self._MY_H_SECTION
  638. else:
  639. self._section = self._OTHER_H_SECTION
  640. elif header_type == _POSSIBLE_MY_HEADER:
  641. if self._section <= self._MY_H_SECTION:
  642. self._section = self._MY_H_SECTION
  643. else:
  644. # This will always be the fallback because we're not sure
  645. # enough that the header is associated with this file.
  646. self._section = self._OTHER_H_SECTION
  647. else:
  648. assert header_type == _OTHER_HEADER
  649. self._section = self._OTHER_H_SECTION
  650. if last_section != self._section:
  651. self._last_header = ''
  652. return ''
  653. class _CppLintState(object):
  654. """Maintains module-wide state.."""
  655. def __init__(self):
  656. self.verbose_level = 1 # global setting.
  657. self.error_count = 0 # global count of reported errors
  658. # filters to apply when emitting error messages
  659. self.filters = _DEFAULT_FILTERS[:]
  660. # backup of filter list. Used to restore the state after each file.
  661. self._filters_backup = self.filters[:]
  662. self.counting = 'total' # In what way are we counting errors?
  663. self.errors_by_category = {} # string to int dict storing error counts
  664. # output format:
  665. # "emacs" - format that emacs can parse (default)
  666. # "vs7" - format that Microsoft Visual Studio 7 can parse
  667. self.output_format = 'emacs'
  668. def SetOutputFormat(self, output_format):
  669. """Sets the output format for errors."""
  670. self.output_format = output_format
  671. def SetVerboseLevel(self, level):
  672. """Sets the module's verbosity, and returns the previous setting."""
  673. last_verbose_level = self.verbose_level
  674. self.verbose_level = level
  675. return last_verbose_level
  676. def SetCountingStyle(self, counting_style):
  677. """Sets the module's counting options."""
  678. self.counting = counting_style
  679. def SetFilters(self, filters):
  680. """Sets the error-message filters.
  681. These filters are applied when deciding whether to emit a given
  682. error message.
  683. Args:
  684. filters: A string of comma-separated filters (eg "+whitespace/indent").
  685. Each filter should start with + or -; else we die.
  686. Raises:
  687. ValueError: The comma-separated filters did not all start with '+' or '-'.
  688. E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
  689. """
  690. # Default filters always have less priority than the flag ones.
  691. self.filters = _DEFAULT_FILTERS[:]
  692. self.AddFilters(filters)
  693. def AddFilters(self, filters):
  694. """ Adds more filters to the existing list of error-message filters. """
  695. for filt in filters.split(','):
  696. clean_filt = filt.strip()
  697. if clean_filt:
  698. self.filters.append(clean_filt)
  699. for filt in self.filters:
  700. if not (filt.startswith('+') or filt.startswith('-')):
  701. raise ValueError('Every filter in --filters must start with + or -'
  702. ' (%s does not)' % filt)
  703. def BackupFilters(self):
  704. """ Saves the current filter list to backup storage."""
  705. self._filters_backup = self.filters[:]
  706. def RestoreFilters(self):
  707. """ Restores filters previously backed up."""
  708. self.filters = self._filters_backup[:]
  709. def ResetErrorCounts(self):
  710. """Sets the module's error statistic back to zero."""
  711. self.error_count = 0
  712. self.errors_by_category = {}
  713. def IncrementErrorCount(self, category):
  714. """Bumps the module's error statistic."""
  715. self.error_count += 1
  716. if self.counting in ('toplevel', 'detailed'):
  717. if self.counting != 'detailed':
  718. category = category.split('/')[0]
  719. if category not in self.errors_by_category:
  720. self.errors_by_category[category] = 0
  721. self.errors_by_category[category] += 1
  722. def PrintErrorCounts(self):
  723. """Print a summary of errors by category, and the total."""
  724. for category, count in self.errors_by_category.iteritems():
  725. sys.stderr.write('Category \'%s\' errors found: %d\n' %
  726. (category, count))
  727. sys.stderr.write('Total errors found: %d\n' % self.error_count)
  728. _cpplint_state = _CppLintState()
  729. def _OutputFormat():
  730. """Gets the module's output format."""
  731. return _cpplint_state.output_format
  732. def _SetOutputFormat(output_format):
  733. """Sets the module's output format."""
  734. _cpplint_state.SetOutputFormat(output_format)
  735. def _VerboseLevel():
  736. """Returns the module's verbosity setting."""
  737. return _cpplint_state.verbose_level
  738. def _SetVerboseLevel(level):
  739. """Sets the module's verbosity, and returns the previous setting."""
  740. return _cpplint_state.SetVerboseLevel(level)
  741. def _SetCountingStyle(level):
  742. """Sets the module's counting options."""
  743. _cpplint_state.SetCountingStyle(level)
  744. def _Filters():
  745. """Returns the module's list of output filters, as a list."""
  746. return _cpplint_state.filters
  747. def _SetFilters(filters):
  748. """Sets the module's error-message filters.
  749. These filters are applied when deciding whether to emit a given
  750. error message.
  751. Args:
  752. filters: A string of comma-separated filters (eg "whitespace/indent").
  753. Each filter should start with + or -; else we die.
  754. """
  755. _cpplint_state.SetFilters(filters)
  756. def _AddFilters(filters):
  757. """Adds more filter overrides.
  758. Unlike _SetFilters, this function does not reset the current list of filters
  759. available.
  760. Args:
  761. filters: A string of comma-separated filters (eg "whitespace/indent").
  762. Each filter should start with + or -; else we die.
  763. """
  764. _cpplint_state.AddFilters(filters)
  765. def _BackupFilters():
  766. """ Saves the current filter list to backup storage."""
  767. _cpplint_state.BackupFilters()
  768. def _RestoreFilters():
  769. """ Restores filters previously backed up."""
  770. _cpplint_state.RestoreFilters()
  771. class _FunctionState(object):
  772. """Tracks current function name and the number of lines in its body."""
  773. _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
  774. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
  775. def __init__(self):
  776. self.in_a_function = False
  777. self.lines_in_function = 0
  778. self.current_function = ''
  779. def Begin(self, function_name):
  780. """Start analyzing function body.
  781. Args:
  782. function_name: The name of the function being tracked.
  783. """
  784. self.in_a_function = True
  785. self.lines_in_function = 0
  786. self.current_function = function_name
  787. def Count(self):
  788. """Count line in current function body."""
  789. if self.in_a_function:
  790. self.lines_in_function += 1
  791. def Check(self, error, filename, linenum):
  792. """Report if too many lines in function body.
  793. Args:
  794. error: The function to call with any errors found.
  795. filename: The name of the current file.
  796. linenum: The number of the line to check.
  797. """
  798. if Match(r'T(EST|est)', self.current_function):
  799. base_trigger = self._TEST_TRIGGER
  800. else:
  801. base_trigger = self._NORMAL_TRIGGER
  802. trigger = base_trigger * 2**_VerboseLevel()
  803. if self.lines_in_function > trigger:
  804. error_level = int(math.log(self.lines_in_function / base_trigger, 2))
  805. # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
  806. if error_level > 5:
  807. error_level = 5
  808. error(filename, linenum, 'readability/fn_size', error_level,
  809. 'Small and focused functions are preferred:'
  810. ' %s has %d non-comment lines'
  811. ' (error triggered by exceeding %d lines).' % (
  812. self.current_function, self.lines_in_function, trigger))
  813. def End(self):
  814. """Stop analyzing function body."""
  815. self.in_a_function = False
  816. class _IncludeError(Exception):
  817. """Indicates a problem with the include order in a file."""
  818. pass
  819. class FileInfo(object):
  820. """Provides utility functions for filenames.
  821. FileInfo provides easy access to the components of a file's path
  822. relative to the project root.
  823. """
  824. def __init__(self, filename):
  825. self._filename = filename
  826. def FullName(self):
  827. """Make Windows paths like Unix."""
  828. return os.path.abspath(self._filename).replace('\\', '/')
  829. def RepositoryName(self):
  830. """FullName after removing the local path to the repository.
  831. If we have a real absolute path name here we can try to do something smart:
  832. detecting the root of the checkout and truncating /path/to/checkout from
  833. the name so that we get header guards that don't include things like
  834. "C:\Documents and Settings\..." or "/home/username/..." in them and thus
  835. people on different computers who have checked the source out to different
  836. locations won't see bogus errors.
  837. """
  838. fullname = self.FullName()
  839. if os.path.exists(fullname):
  840. project_dir = os.path.dirname(fullname)
  841. if os.path.exists(os.path.join(project_dir, ".svn")):
  842. # If there's a .svn file in the current directory, we recursively look
  843. # up the directory tree for the top of the SVN checkout
  844. root_dir = project_dir
  845. one_up_dir = os.path.dirname(root_dir)
  846. while os.path.exists(os.path.join(one_up_dir, ".svn")):
  847. root_dir = os.path.dirname(root_dir)
  848. one_up_dir = os.path.dirname(one_up_dir)
  849. prefix = os.path.commonprefix([root_dir, project_dir])
  850. return fullname[len(prefix) + 1:]
  851. # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
  852. # searching up from the current path.
  853. root_dir = os.path.dirname(fullname)
  854. while (root_dir != os.path.dirname(root_dir) and
  855. not os.path.exists(os.path.join(root_dir, ".git")) and
  856. not os.path.exists(os.path.join(root_dir, ".hg")) and
  857. not os.path.exists(os.path.join(root_dir, ".svn"))):
  858. root_dir = os.path.dirname(root_dir)
  859. if (os.path.exists(os.path.join(root_dir, ".git")) or
  860. os.path.exists(os.path.join(root_dir, ".hg")) or
  861. os.path.exists(os.path.join(root_dir, ".svn"))):
  862. prefix = os.path.commonprefix([root_dir, project_dir])
  863. return fullname[len(prefix) + 1:]
  864. # Don't know what to do; header guard warnings may be wrong...
  865. return fullname
  866. def Split(self):
  867. """Splits the file into the directory, basename, and extension.
  868. For 'chrome/browser/browser.cc', Split() would
  869. return ('chrome/browser', 'browser', '.cc')
  870. Returns:
  871. A tuple of (directory, basename, extension).
  872. """
  873. googlename = self.RepositoryName()
  874. project, rest = os.path.split(googlename)
  875. return (project,) + os.path.splitext(rest)
  876. def BaseName(self):
  877. """File base name - text after the final slash, before the final period."""
  878. return self.Split()[1]
  879. def Extension(self):
  880. """File extension - text following the final period."""
  881. return self.Split()[2]
  882. def NoExtension(self):
  883. """File has no source file extension."""
  884. return '/'.join(self.Split()[0:2])
  885. def IsSource(self):
  886. """File has a source file extension."""
  887. return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
  888. def _ShouldPrintError(category, confidence, linenum):
  889. """If confidence >= verbose, category passes filter and is not suppressed."""
  890. # There are three ways we might decide not to print an error message:
  891. # a "NOLINT(category)" comment appears in the source,
  892. # the verbosity level isn't high enough, or the filters filter it out.
  893. if IsErrorSuppressedByNolint(category, linenum):
  894. return False
  895. if confidence < _cpplint_state.verbose_level:
  896. return False
  897. is_filtered = False
  898. for one_filter in _Filters():
  899. if one_filter.startswith('-'):
  900. if category.startswith(one_filter[1:]):
  901. is_filtered = True
  902. elif one_filter.startswith('+'):
  903. if category.startswith(one_filter[1:]):
  904. is_filtered = False
  905. else:
  906. assert False # should have been checked for in SetFilter.
  907. if is_filtered:
  908. return False
  909. return True
  910. def Error(filename, linenum, category, confidence, message):
  911. """Logs the fact we've found a lint error.
  912. We log where the error was found, and also our confidence in the error,
  913. that is, how certain we are this is a legitimate style regression, and
  914. not a misidentification or a use that's sometimes justified.
  915. False positives can be suppressed by the use of
  916. "cpplint(category)" comments on the offending line. These are
  917. parsed into _error_suppressions.
  918. Args:
  919. filename: The name of the file containing the error.
  920. linenum: The number of the line containing the error.
  921. category: A string used to describe the "category" this bug
  922. falls under: "whitespace", say, or "runtime". Categories
  923. may have a hierarchy separated by slashes: "whitespace/indent".
  924. confidence: A number from 1-5 representing a confidence score for
  925. the error, with 5 meaning that we are certain of the problem,
  926. and 1 meaning that it could be a legitimate construct.
  927. message: The error message.
  928. """
  929. if _ShouldPrintError(category, confidence, linenum):
  930. _cpplint_state.IncrementErrorCount(category)
  931. if _cpplint_state.output_format == 'vs7':
  932. sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
  933. filename, linenum, message, category, confidence))
  934. elif _cpplint_state.output_format == 'eclipse':
  935. sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
  936. filename, linenum, message, category, confidence))
  937. else:
  938. sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
  939. filename, linenum, message, category, confidence))
  940. # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
  941. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
  942. r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
  943. # Match a single C style comment on the same line.
  944. _RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
  945. # Matches multi-line C style comments.
  946. # This RE is a little bit more complicated than one might expect, because we
  947. # have to take care of space removals tools so we can handle comments inside
  948. # statements better.
  949. # The current rule is: We only clear spaces from both sides when we're at the
  950. # end of the line. Otherwise, we try to remove spaces from the right side,
  951. # if this doesn't work we try on left side but only if there's a non-character
  952. # on the right.
  953. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
  954. r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
  955. _RE_PATTERN_C_COMMENTS + r'\s+|' +
  956. r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
  957. _RE_PATTERN_C_COMMENTS + r')')
  958. def IsCppString(line):
  959. """Does line terminate so, that the next symbol is in string constant.
  960. This function does not consider single-line nor multi-line comments.
  961. Args:
  962. line: is a partial line of code starting from the 0..n.
  963. Returns:
  964. True, if next character appended to 'line' is inside a
  965. string constant.
  966. """
  967. line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
  968. return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
  969. def CleanseRawStrings(raw_lines):
  970. """Removes C++11 raw strings from lines.
  971. Before:
  972. static const char kData[] = R"(
  973. multi-line string
  974. )";
  975. After:
  976. static const char kData[] = ""
  977. (replaced by blank line)
  978. "";
  979. Args:
  980. raw_lines: list of raw lines.
  981. Returns:
  982. list of lines with C++11 raw strings replaced by empty strings.
  983. """
  984. delimiter = None
  985. lines_without_raw_strings = []
  986. for line in raw_lines:
  987. if delimiter:
  988. # Inside a raw string, look for the end
  989. end = line.find(delimiter)
  990. if end >= 0:
  991. # Found the end of the string, match leading space for this
  992. # line and resume copying the original lines, and also insert
  993. # a "" on the last line.
  994. leading_space = Match(r'^(\s*)\S', line)
  995. line = leading_space.group(1) + '""' + line[end + len(delimiter):]
  996. delimiter = None
  997. else:
  998. # Haven't found the end yet, append a blank line.
  999. line = '""'
  1000. # Look for beginning of a raw string, and replace them with
  1001. # empty strings. This is done in a loop to handle multiple raw
  1002. # strings on the same line.
  1003. while delimiter is None:
  1004. # Look for beginning of a raw string.
  1005. # See 2.14.15 [lex.string] for syntax.
  1006. matched = Match(r'^(.*)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
  1007. if matched:
  1008. delimiter = ')' + matched.group(2) + '"'
  1009. end = matched.group(3).find(delimiter)
  1010. if end >= 0:
  1011. # Raw string ended on same line
  1012. line = (matched.group(1) + '""' +
  1013. matched.group(3)[end + len(delimiter):])
  1014. delimiter = None
  1015. else:
  1016. # Start of a multi-line raw string
  1017. line = matched.group(1) + '""'
  1018. else:
  1019. break
  1020. lines_without_raw_strings.append(line)
  1021. # TODO(unknown): if delimiter is not None here, we might want to
  1022. # emit a warning for unterminated string.
  1023. return lines_without_raw_strings
  1024. def FindNextMultiLineCommentStart(lines, lineix):
  1025. """Find the beginning marker for a multiline comment."""
  1026. while lineix < len(lines):
  1027. if lines[lineix].strip().startswith('/*'):
  1028. # Only return this marker if the comment goes beyond this line
  1029. if lines[lineix].strip().find('*/', 2) < 0:
  1030. return lineix
  1031. lineix += 1
  1032. return len(lines)
  1033. def FindNextMultiLineCommentEnd(lines, lineix):
  1034. """We are inside a comment, find the end marker."""
  1035. while lineix < len(lines):
  1036. if lines[lineix].strip().endswith('*/'):
  1037. return lineix
  1038. lineix += 1
  1039. return len(lines)
  1040. def RemoveMultiLineCommentsFromRange(lines, begin, end):
  1041. """Clears a range of lines for multi-line comments."""
  1042. # Having // dummy comments makes the lines non-empty, so we will not get
  1043. # unnecessary blank line warnings later in the code.
  1044. for i in range(begin, end):
  1045. lines[i] = '/**/'
  1046. def RemoveMultiLineComments(filename, lines, error):
  1047. """Removes multiline (c-style) comments from lines."""
  1048. lineix = 0
  1049. while lineix < len(lines):
  1050. lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
  1051. if lineix_begin >= len(lines):
  1052. return
  1053. lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
  1054. if lineix_end >= len(lines):
  1055. error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
  1056. 'Could not find end of multi-line comment')
  1057. return
  1058. RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
  1059. lineix = lineix_end + 1
  1060. def CleanseComments(line):
  1061. """Removes //-comments and single-line C-style /* */ comments.
  1062. Args:
  1063. line: A line of C++ source.
  1064. Returns:
  1065. The line with single-line comments removed.
  1066. """
  1067. commentpos = line.find('//')
  1068. if commentpos != -1 and not IsCppString(line[:commentpos]):
  1069. line = line[:commentpos].rstrip()
  1070. # get rid of /* ... */
  1071. return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
  1072. class CleansedLines(object):
  1073. """Holds 4 copies of all lines with different preprocessing applied to them.
  1074. 1) elided member contains lines without strings and comments.
  1075. 2) lines member contains lines without comments.
  1076. 3) raw_lines member contains all the lines without processing.
  1077. 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
  1078. strings removed.
  1079. All these members are of <type 'list'>, and of the same length.
  1080. """
  1081. def __init__(self, lines):
  1082. self.elided = []
  1083. self.lines = []
  1084. self.raw_lines = lines
  1085. self.num_lines = len(lines)
  1086. self.lines_without_raw_strings = CleanseRawStrings(lines)
  1087. for linenum in range(len(self.lines_without_raw_strings)):
  1088. self.lines.append(CleanseComments(
  1089. self.lines_without_raw_strings[linenum]))
  1090. elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
  1091. self.elided.append(CleanseComments(elided))
  1092. def NumLines(self):
  1093. """Returns the number of lines represented."""
  1094. return self.num_lines
  1095. @staticmethod
  1096. def _CollapseStrings(elided):
  1097. """Collapses strings and chars on a line to simple "" or '' blocks.
  1098. We nix strings first so we're not fooled by text like '"http://"'
  1099. Args:
  1100. elided: The line being processed.
  1101. Returns:
  1102. The line with collapsed strings.
  1103. """
  1104. if _RE_PATTERN_INCLUDE.match(elided):
  1105. return elided
  1106. # Remove escaped characters first to make quote/single quote collapsing
  1107. # basic. Things that look like escaped characters shouldn't occur
  1108. # outside of strings and chars.
  1109. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
  1110. # Replace quoted strings and digit separators. Both single quotes
  1111. # and double quotes are processed in the same loop, otherwise
  1112. # nested quotes wouldn't work.
  1113. collapsed = ''
  1114. while True:
  1115. # Find the first quote character
  1116. match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
  1117. if not match:
  1118. collapsed += elided
  1119. break
  1120. head, quote, tail = match.groups()
  1121. if quote == '"':
  1122. # Collapse double quoted strings
  1123. second_quote = tail.find('"')
  1124. if second_quote >= 0:
  1125. collapsed += head + '""'
  1126. elided = tail[second_quote + 1:]
  1127. else:
  1128. # Unmatched double quote, don't bother processing the rest
  1129. # of the line since this is probably a multiline string.
  1130. collapsed += elided
  1131. break
  1132. else:
  1133. # Found single quote, check nearby text to eliminate digit separators.
  1134. #
  1135. # There is no special handling for floating point here, because
  1136. # the integer/fractional/exponent parts would all be parsed
  1137. # correctly as long as there are digits on both sides of the
  1138. # separator. So we are fine as long as we don't see something
  1139. # like "0.'3" (gcc 4.9.0 will not allow this literal).
  1140. if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
  1141. match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
  1142. collapsed += head + match_literal.group(1).replace("'", '')
  1143. elided = match_literal.group(2)
  1144. else:
  1145. second_quote = tail.find('\'')
  1146. if second_quote >= 0:
  1147. collapsed += head + "''"
  1148. elided = tail[second_quote + 1:]
  1149. else:
  1150. # Unmatched single quote
  1151. collapsed += elided
  1152. break
  1153. return collapsed
  1154. def FindEndOfExpressionInLine(line, startpos, stack):
  1155. """Find the position just after the end of current parenthesized expression.
  1156. Args:
  1157. line: a CleansedLines line.
  1158. startpos: start searching at this position.
  1159. stack: nesting stack at startpos.
  1160. Returns:
  1161. On finding matching end: (index just after matching end, None)
  1162. On finding an unclosed expression: (-1, None)
  1163. Otherwise: (-1, new stack at end of this line)
  1164. """
  1165. for i in xrange(startpos, len(line)):
  1166. char = line[i]
  1167. if char in '([{':
  1168. # Found start of parenthesized expression, push to expression stack
  1169. stack.append(char)
  1170. elif char == '<':
  1171. # Found potential start of template argument list
  1172. if i > 0 and line[i - 1] == '<':
  1173. # Left shift operator
  1174. if stack and stack[-1] == '<':
  1175. stack.pop()
  1176. if not stack:
  1177. return (-1, None)
  1178. elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
  1179. # operator<, don't add to stack
  1180. continue
  1181. else:
  1182. # Tentative start of template argument list
  1183. stack.append('<')
  1184. elif char in ')]}':
  1185. # Found end of parenthesized expression.
  1186. #
  1187. # If we are currently expecting a matching '>', the pending '<'
  1188. # must have been an operator. Remove them from expression stack.
  1189. while stack and stack[-1] == '<':
  1190. stack.pop()
  1191. if not stack:
  1192. return (-1, None)
  1193. if ((stack[-1] == '(' and char == ')') or
  1194. (stack[-1] == '[' and char == ']') or
  1195. (stack[-1] == '{' and char == '}')):
  1196. stack.pop()
  1197. if not stack:
  1198. return (i + 1, None)
  1199. else:
  1200. # Mismatched parentheses
  1201. return (-1, None)
  1202. elif char == '>':
  1203. # Found potential end of template argument list.
  1204. # Ignore "->" and operator functions
  1205. if (i > 0 and
  1206. (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
  1207. continue
  1208. # Pop the stack if there is a matching '<'. Otherwise, ignore
  1209. # this '>' since it must be an operator.
  1210. if stack:
  1211. if stack[-1] == '<':
  1212. stack.pop()
  1213. if not stack:
  1214. return (i + 1, None)
  1215. elif char == ';':
  1216. # Found something that look like end of statements. If we are currently
  1217. # expecting a '>', the matching '<' must have been an operator, since
  1218. # template argument list should not contain statements.
  1219. while stack and stack[-1] == '<':
  1220. stack.pop()
  1221. if not stack:
  1222. return (-1, None)
  1223. # Did not find end of expression or unbalanced parentheses on this line
  1224. return (-1, stack)
  1225. def CloseExpression(clean_lines, linenum, pos):
  1226. """If input points to ( or { or [ or <, finds the position that closes it.
  1227. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
  1228. linenum/pos that correspond to the closing of the expression.
  1229. TODO(unknown): cpplint spends a fair bit of time matching parentheses.
  1230. Ideally we would want to index all opening and closing parentheses once
  1231. and have CloseExpression be just a simple lookup, but due to preprocessor
  1232. tricks, this is not so easy.
  1233. Args:
  1234. clean_lines: A CleansedLines instance containing the file.
  1235. linenum: The number of the line to check.
  1236. pos: A position on the line.
  1237. Returns:
  1238. A tuple (line, linenum, pos) pointer *past* the closing brace, or
  1239. (line, len(lines), -1) if we never find a close. Note we ignore
  1240. strings and comments when matching; and the line we return is the
  1241. 'cleansed' line at linenum.
  1242. """
  1243. line = clean_lines.elided[linenum]
  1244. if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
  1245. return (line, clean_lines.NumLines(), -1)
  1246. # Check first line
  1247. (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
  1248. if end_pos > -1:
  1249. return (line, linenum, end_pos)
  1250. # Continue scanning forward
  1251. while stack and linenum < clean_lines.NumLines() - 1:
  1252. linenum += 1
  1253. line = clean_lines.elided[linenum]
  1254. (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
  1255. if end_pos > -1:
  1256. return (line, linenum, end_pos)
  1257. # Did not find end of expression before end of file, give up
  1258. return (line, clean_lines.NumLines(), -1)
  1259. def FindStartOfExpressionInLine(line, endpos, stack):
  1260. """Find position at the matching start of current expression.
  1261. This is almost the reverse of FindEndOfExpressionInLine, but note
  1262. that the input position and returned position differs by 1.
  1263. Args:
  1264. line: a CleansedLines line.
  1265. endpos: start searching at this position.
  1266. stack: nesting stack at endpos.
  1267. Returns:
  1268. On finding matching start: (index at matching start, None)
  1269. On finding an unclosed expression: (-1, None)
  1270. Otherwise: (-1, new stack at beginning of this line)
  1271. """
  1272. i = endpos
  1273. while i >= 0:
  1274. char = line[i]
  1275. if char in ')]}':
  1276. # Found end of expression, push to expression stack
  1277. stack.append(char)
  1278. elif char == '>':
  1279. # Found potential end of template argument list.
  1280. #
  1281. # Ignore it if it's a "->" or ">=" or "operator>"
  1282. if (i > 0 and
  1283. (line[i - 1] == '-' or
  1284. Match(r'\s>=\s', line[i - 1:]) or
  1285. Search(r'\boperator\s*$', line[0:i]))):
  1286. i -= 1
  1287. else:
  1288. stack.append('>')
  1289. elif char == '<':
  1290. # Found potential start of template argument list
  1291. if i > 0 and line[i - 1] == '<':
  1292. # Left shift operator
  1293. i -= 1
  1294. else:
  1295. # If there is a matching '>', we can pop the expression stack.
  1296. # Otherwise, ignore this '<' since it must be an operator.
  1297. if stack and stack[-1] == '>':
  1298. stack.pop()
  1299. if not stack:
  1300. return (i, None)
  1301. elif char in '([{':
  1302. # Found start of expression.
  1303. #
  1304. # If there are any unmatched '>' on the stack, they must be
  1305. # operators. Remove those.
  1306. while stack and stack[-1] == '>':
  1307. stack.pop()
  1308. if not stack:
  1309. return (-1, None)
  1310. if ((char == '(' and stack[-1] == ')') or
  1311. (char == '[' and stack[-1] == ']') or
  1312. (char == '{' and stack[-1] == '}')):
  1313. stack.pop()
  1314. if not stack:
  1315. return (i, None)
  1316. else:
  1317. # Mismatched parentheses
  1318. return (-1, None)
  1319. elif char == ';':
  1320. # Found something that look like end of statements. If we are currently
  1321. # expecting a '<', the matching '>' must have been an operator, since
  1322. # template argument list should not contain statements.
  1323. while stack and stack[-1] == '>':
  1324. stack.pop()
  1325. if not stack:
  1326. return (-1, None)
  1327. i -= 1
  1328. return (-1, stack)
  1329. def ReverseCloseExpression(clean_lines, linenum, pos):
  1330. """If input points to ) or } or ] or >, finds the position that opens it.
  1331. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
  1332. linenum/pos that correspond to the opening of the expression.
  1333. Args:
  1334. clean_lines: A CleansedLines instance containing the file.
  1335. linenum: The number of the line to check.
  1336. pos: A position on the line.
  1337. Returns:
  1338. A tuple (line, linenum, pos) pointer *at* the opening brace, or
  1339. (line, 0, -1) if we never find the matching opening brace. Note
  1340. we ignore strings and comments when matching; and the line we
  1341. return is the 'cleansed' line at linenum.
  1342. """
  1343. line = clean_lines.elided[linenum]
  1344. if line[pos] not in ')}]>':
  1345. return (line, 0, -1)
  1346. # Check last line
  1347. (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
  1348. if start_pos > -1:
  1349. return (line, linenum, start_pos)
  1350. # Continue scanning backward
  1351. while stack and linenum > 0:
  1352. linenum -= 1
  1353. line = clean_lines.elided[linenum]
  1354. (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
  1355. if start_pos > -1:
  1356. return (line, linenum, start_pos)
  1357. # Did not find start of expression before beginning of file, give up
  1358. return (line, 0, -1)
  1359. def CheckForCopyright(filename, lines, error):
  1360. """Logs an error if no Copyright message appears at the top of the file."""
  1361. # We'll say it should occur by line 10. Don't forget there's a
  1362. # dummy line at the front.
  1363. for line in xrange(1, min(len(lines), 11)):
  1364. if re.search(r'Copyright', lines[line], re.I): break
  1365. else: # means no copyright line was found
  1366. error(filename, 0, 'legal/copyright', 5,
  1367. 'No copyright message found. '
  1368. 'You should have a line: "Copyright [year] <Copyright Owner>"')
  1369. def GetIndentLevel(line):
  1370. """Return the number of leading spaces in line.
  1371. Args:
  1372. line: A string to check.
  1373. Returns:
  1374. An integer count of leading spaces, possibly zero.
  1375. """
  1376. indent = Match(r'^( *)\S', line)
  1377. if indent:
  1378. return len(indent.group(1))
  1379. else:
  1380. return 0
  1381. def GetHeaderGuardCPPVariable(filename):
  1382. """Returns the CPP variable that should be used as a header guard.
  1383. Args:
  1384. filename: The name of a C++ header file.
  1385. Returns:
  1386. The CPP variable that should be used as a header guard in the
  1387. named file.
  1388. """
  1389. # Restores original filename in case that cpplint is invoked from Emacs's
  1390. # flymake.
  1391. filename = re.sub(r'_flymake\.h$', '.h', filename)
  1392. filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
  1393. # Replace 'c++' with 'cpp'.
  1394. filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
  1395. fileinfo = FileInfo(filename)
  1396. file_path_from_root = fileinfo.RepositoryName()
  1397. if _root:
  1398. file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
  1399. return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
  1400. def CheckForHeaderGuard(filename, clean_lines, error):
  1401. """Checks that the file contains a header guard.
  1402. Logs an error if no #ifndef header guard is present. For other
  1403. headers, checks that the full pathname is used.
  1404. Args:
  1405. filename: The name of the C++ header file.
  1406. clean_lines: A CleansedLines instance containing the file.
  1407. error: The function to call with any errors found.
  1408. """
  1409. # Don't check for header guards if there are error suppression
  1410. # comments somewhere in this file.
  1411. #
  1412. # Because this is silencing a warning for a nonexistent line, we
  1413. # only support the very specific NOLINT(build/header_guard) syntax,
  1414. # and not the general NOLINT or NOLINT(*) syntax.
  1415. raw_lines = clean_lines.lines_without_raw_strings
  1416. for i in raw_lines:
  1417. if Search(r'//\s*NOLINT\(build/header_guard\)', i):
  1418. return
  1419. cppvar = GetHeaderGuardCPPVariable(filename)
  1420. ifndef = ''
  1421. ifndef_linenum = 0
  1422. define = ''
  1423. endif = ''
  1424. endif_linenum = 0
  1425. for linenum, line in enumerate(raw_lines):
  1426. linesplit = line.split()
  1427. if len(linesplit) >= 2:
  1428. # find the first occurrence of #ifndef and #define, save arg
  1429. if not ifndef and linesplit[0] == '#ifndef':
  1430. # set ifndef to the header guard presented on the #ifndef line.
  1431. ifndef = linesplit[1]
  1432. ifndef_linenum = linenum
  1433. if not define and linesplit[0] == '#define':
  1434. define = linesplit[1]
  1435. # find the last occurrence of #endif, save entire line
  1436. if line.startswith('#endif'):
  1437. endif = line
  1438. endif_linenum = linenum
  1439. if not ifndef or not define or ifndef != define:
  1440. error(filename, 0, 'build/header_guard', 5,
  1441. 'No #ifndef header guard found, suggested CPP variable is: %s' %
  1442. cppvar)
  1443. return
  1444. # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
  1445. # for backward compatibility.
  1446. if ifndef != cppvar:
  1447. error_level = 0
  1448. if ifndef != cppvar + '_':
  1449. error_level = 5
  1450. ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
  1451. error)
  1452. error(filename, ifndef_linenum, 'build/header_guard', error_level,
  1453. '#ifndef header guard has wrong style, please use: %s' % cppvar)
  1454. # Check for "//" comments on endif line.
  1455. ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
  1456. error)
  1457. match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
  1458. if match:
  1459. if match.group(1) == '_':
  1460. # Issue low severity warning for deprecated double trailing underscore
  1461. error(filename, endif_linenum, 'build/header_guard', 0,
  1462. '#endif line should be "#endif // %s"' % cppvar)
  1463. return
  1464. # Didn't find the corresponding "//" comment. If this file does not
  1465. # contain any "//" comments at all, it could be that the compiler
  1466. # only wants "/**/" comments, look for those instead.
  1467. no_single_line_comments = True
  1468. for i in xrange(1, len(raw_lines) - 1):
  1469. line = raw_lines[i]
  1470. if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
  1471. no_single_line_comments = False
  1472. break
  1473. if no_single_line_comments:
  1474. match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
  1475. if match:
  1476. if match.group(1) == '_':
  1477. # Low severity warning for double trailing underscore
  1478. error(filename, endif_linenum, 'build/header_guard', 0,
  1479. '#endif line should be "#endif /* %s */"' % cppvar)
  1480. return
  1481. # Didn't find anything
  1482. error(filename, endif_linenum, 'build/header_guard', 5,
  1483. '#endif line should be "#endif // %s"' % cppvar)
  1484. def CheckHeaderFileIncluded(filename, include_state, error):
  1485. """Logs an error if a .cc file does not include its header."""
  1486. # Do not check test files
  1487. if filename.endswith('_test.cc') or filename.endswith('_unittest.cc'):
  1488. return
  1489. fileinfo = FileInfo(filename)
  1490. headerfile = filename[0:len(filename) - 2] + 'h'
  1491. if not os.path.exists(headerfile):
  1492. return
  1493. headername = FileInfo(headerfile).RepositoryName()
  1494. first_include = 0
  1495. for section_list in include_state.include_list:
  1496. for f in section_list:
  1497. if headername in f[0] or f[0] in headername:
  1498. return
  1499. if not first_include:
  1500. first_include = f[1]
  1501. error(filename, first_include, 'build/include', 5,
  1502. '%s should include its header file %s' % (fileinfo.RepositoryName(),
  1503. headername))
  1504. def CheckForBadCharacters(filename, lines, error):
  1505. """Logs an error for each line containing bad characters.
  1506. Two kinds of bad characters:
  1507. 1. Unicode replacement characters: These indicate that either the file
  1508. contained invalid UTF-8 (likely) or Unicode replacement characters (which
  1509. it shouldn't). Note that it's possible for this to throw off line
  1510. numbering if the invalid UTF-8 occurred adjacent to a newline.
  1511. 2. NUL bytes. These are problematic for some tools.
  1512. Args:
  1513. filename: The name of the current file.
  1514. lines: An array of strings, each representing a line of the file.
  1515. error: The function to call with any errors found.
  1516. """
  1517. for linenum, line in enumerate(lines):
  1518. if u'\ufffd' in line:
  1519. error(filename, linenum, 'readability/utf8', 5,
  1520. 'Line contains invalid UTF-8 (or Unicode replacement character).')
  1521. if '\0' in line:
  1522. error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
  1523. def CheckForNewlineAtEOF(filename, lines, error):
  1524. """Logs an error if there is no newline char at the end of the file.
  1525. Args:
  1526. filename: The name of the current file.
  1527. lines: An array of strings, each representing a line of the file.
  1528. error: The function to call with any errors found.
  1529. """
  1530. # The array lines() was created by adding two newlines to the
  1531. # original file (go figure), then splitting on \n.
  1532. # To verify that the file ends in \n, we just have to make sure the
  1533. # last-but-two element of lines() exists and is empty.
  1534. if len(lines) < 3 or lines[-2]:
  1535. error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
  1536. 'Could not find a newline character at the end of the file.')
  1537. def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
  1538. """Logs an error if we see /* ... */ or "..." that extend past one line.
  1539. /* ... */ comments are legit inside macros, for one line.
  1540. Otherwise, we prefer // comments, so it's ok to warn about the
  1541. other. Likewise, it's ok for strings to extend across multiple
  1542. lines, as long as a line continuation character (backslash)
  1543. terminates each line. Although not currently prohibited by the C++
  1544. style guide, it's ugly and unnecessary. We don't do well with either
  1545. in this lint program, so we warn about both.
  1546. Args:
  1547. filename: The name of the current file.
  1548. clean_lines: A CleansedLines instance containing the file.
  1549. linenum: The number of the line to check.
  1550. error: The function to call with any errors found.
  1551. """
  1552. line = clean_lines.elided[linenum]
  1553. # Remove all \\ (escaped backslashes) from the line. They are OK, and the
  1554. # second (escaped) slash may trigger later \" detection erroneously.
  1555. line = line.replace('\\\\', '')
  1556. if line.count('/*') > line.count('*/'):
  1557. error(filename, linenum, 'readability/multiline_comment', 5,
  1558. 'Complex multi-line /*...*/-style comment found. '
  1559. 'Lint may give bogus warnings. '
  1560. 'Consider replacing these with //-style comments, '
  1561. 'with #if 0...#endif, '
  1562. 'or with more clearly structured multi-line comments.')
  1563. if (line.count('"') - line.count('\\"')) % 2:
  1564. error(filename, linenum, 'readability/multiline_string', 5,
  1565. 'Multi-line string ("...") found. This lint script doesn\'t '
  1566. 'do well with such strings, and may give bogus warnings. '
  1567. 'Use C++11 raw strings or concatenation instead.')
  1568. # (non-threadsafe name, thread-safe alternative, validation pattern)
  1569. #
  1570. # The validation pattern is used to eliminate false positives such as:
  1571. # _rand(); // false positive due to substring match.
  1572. # ->rand(); // some member function rand().
  1573. # ACMRandom rand(seed); // some variable named rand.
  1574. # ISAACRandom rand(); // another variable named rand.
  1575. #
  1576. # Basically we require the return value of these functions to be used
  1577. # in some expression context on the same line by matching on some
  1578. # operator before the function name. This eliminates constructors and
  1579. # member function calls.
  1580. _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
  1581. _THREADING_LIST = (
  1582. ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
  1583. ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
  1584. ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
  1585. ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
  1586. ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
  1587. ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
  1588. ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
  1589. ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
  1590. ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
  1591. ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
  1592. ('strtok(', 'strtok_r(',
  1593. _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
  1594. ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
  1595. )
  1596. def CheckPosixThreading(filename, clean_lines, linenum, error):
  1597. """Checks for calls to thread-unsafe functions.
  1598. Much code has been originally written without consideration of
  1599. multi-threading. Also, engineers are relying on their old experience;
  1600. they have learned posix before threading extensions were added. These
  1601. tests guide the engineers to use thread-safe functions (when using
  1602. posix directly).
  1603. Args:
  1604. filename: The name of the current file.
  1605. clean_lines: A CleansedLines instance containing the file.
  1606. linenum: The number of the line to check.
  1607. error: The function to call with any errors found.
  1608. """
  1609. line = clean_lines.elided[linenum]
  1610. for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
  1611. # Additional pattern matching check to confirm that this is the
  1612. # function we are looking for
  1613. if Search(pattern, line):
  1614. error(filename, linenum, 'runtime/threadsafe_fn', 2,
  1615. 'Consider using ' + multithread_safe_func +
  1616. '...) instead of ' + single_thread_func +
  1617. '...) for improved thread safety.')
  1618. def CheckVlogArguments(filename, clean_lines, linenum, error):
  1619. """Checks that VLOG() is only used for defining a logging level.
  1620. For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
  1621. VLOG(FATAL) are not.
  1622. Args:
  1623. filename: The name of the current file.
  1624. clean_lines: A CleansedLines instance containing the file.
  1625. linenum: The number of the line to check.
  1626. error: The function to call with any errors found.
  1627. """
  1628. line = clean_lines.elided[linenum]
  1629. if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
  1630. error(filename, linenum, 'runtime/vlog', 5,
  1631. 'VLOG() should be used with numeric verbosity level. '
  1632. 'Use LOG() if you want symbolic severity levels.')
  1633. # Matches invalid increment: *count++, which moves pointer instead of
  1634. # incrementing a value.
  1635. _RE_PATTERN_INVALID_INCREMENT = re.compile(
  1636. r'^\s*\*\w+(\+\+|--);')
  1637. def CheckInvalidIncrement(filename, clean_lines, linenum, error):
  1638. """Checks for invalid increment *count++.
  1639. For example following function:
  1640. void increment_counter(int* count) {
  1641. *count++;
  1642. }
  1643. is invalid, because it effectively does count++, moving pointer, and should
  1644. be replaced with ++*count, (*count)++ or *count += 1.
  1645. Args:
  1646. filename: The name of the current file.
  1647. clean_lines: A CleansedLines instance containing the file.
  1648. linenum: The number of the line to check.
  1649. error: The function to call with any errors found.
  1650. """
  1651. line = clean_lines.elided[linenum]
  1652. if _RE_PATTERN_INVALID_INCREMENT.match(line):
  1653. error(filename, linenum, 'runtime/invalid_increment', 5,
  1654. 'Changing pointer instead of value (or unused value of operator*).')
  1655. def IsMacroDefinition(clean_lines, linenum):
  1656. if Search(r'^#define', clean_lines[linenum]):
  1657. return True
  1658. if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
  1659. return True
  1660. return False
  1661. def IsForwardClassDeclaration(clean_lines, linenum):
  1662. return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
  1663. class _BlockInfo(object):
  1664. """Stores information about a generic block of code."""
  1665. def __init__(self, seen_open_brace):
  1666. self.seen_open_brace = seen_open_brace
  1667. self.open_parentheses = 0
  1668. self.inline_asm = _NO_ASM
  1669. self.check_namespace_indentation = False
  1670. def CheckBegin(self, filename, clean_lines, linenum, error):
  1671. """Run checks that applies to text up to the opening brace.
  1672. This is mostly for checking the text after the class identifier
  1673. and the "{", usually where the base class is specified. For other
  1674. blocks, there isn't much to check, so we always pass.
  1675. Args:
  1676. filename: The name of the current file.
  1677. clean_lines: A CleansedLines instance containing the file.
  1678. linenum: The number of the line to check.
  1679. error: The function to call with any errors found.
  1680. """
  1681. pass
  1682. def CheckEnd(self, filename, clean_lines, linenum, error):
  1683. """Run checks that applies to text after the closing brace.
  1684. This is mostly used for checking end of namespace comments.
  1685. Args:
  1686. filename: The name of the current file.
  1687. clean_lines: A CleansedLines instance containing the file.
  1688. linenum: The number of the line to check.
  1689. error: The function to call with any errors found.
  1690. """
  1691. pass
  1692. def IsBlockInfo(self):
  1693. """Returns true if this block is a _BlockInfo.
  1694. This is convenient for verifying that an object is an instance of
  1695. a _BlockInfo, but not an instance of any of the derived classes.
  1696. Returns:
  1697. True for this class, False for derived classes.
  1698. """
  1699. return self.__class__ == _BlockInfo
  1700. class _ExternCInfo(_BlockInfo):
  1701. """Stores information about an 'extern "C"' block."""
  1702. def __init__(self):
  1703. _BlockInfo.__init__(self, True)
  1704. class _ClassInfo(_BlockInfo):
  1705. """Stores information about a class."""
  1706. def __init__(self, name, class_or_struct, clean_lines, linenum):
  1707. _BlockInfo.__init__(self, False)
  1708. self.name = name
  1709. self.starting_linenum = linenum
  1710. self.is_derived = False
  1711. self.check_namespace_indentation = True
  1712. if class_or_struct == 'struct':
  1713. self.access = 'public'
  1714. self.is_struct = True
  1715. else:
  1716. self.access = 'private'
  1717. self.is_struct = False
  1718. # Remember initial indentation level for this class. Using raw_lines here
  1719. # instead of elided to account for leading comments.
  1720. self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
  1721. # Try to find the end of the class. This will be confused by things like:
  1722. # class A {
  1723. # } *x = { ...
  1724. #
  1725. # But it's still good enough for CheckSectionSpacing.
  1726. self.last_line = 0
  1727. depth = 0
  1728. for i in range(linenum, clean_lines.NumLines()):
  1729. line = clean_lines.elided[i]
  1730. depth += line.count('{') - line.count('}')
  1731. if not depth:
  1732. self.last_line = i
  1733. break
  1734. def CheckBegin(self, filename, clean_lines, linenum, error):
  1735. # Look for a bare ':'
  1736. if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
  1737. self.is_derived = True
  1738. def CheckEnd(self, filename, clean_lines, linenum, error):
  1739. # If there is a DISALLOW macro, it should appear near the end of
  1740. # the class.
  1741. seen_last_thing_in_class = False
  1742. for i in xrange(linenum - 1, self.starting_linenum, -1):
  1743. match = Search(
  1744. r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
  1745. self.name + r'\)',
  1746. clean_lines.elided[i])
  1747. if match:
  1748. if seen_last_thing_in_class:
  1749. error(filename, i, 'readability/constructors', 3,
  1750. match.group(1) + ' should be the last thing in the class')
  1751. break
  1752. if not Match(r'^\s*$', clean_lines.elided[i]):
  1753. seen_last_thing_in_class = True
  1754. # Check that closing brace is aligned with beginning of the class.
  1755. # Only do this if the closing brace is indented by only whitespaces.
  1756. # This means we will not check single-line class definitions.
  1757. indent = Match(r'^( *)\}', clean_lines.elided[linenum])
  1758. if indent and len(indent.group(1)) != self.class_indent:
  1759. if self.is_struct:
  1760. parent = 'struct ' + self.name
  1761. else:
  1762. parent = 'class ' + self.name
  1763. error(filename, linenum, 'whitespace/indent', 3,
  1764. 'Closing brace should be aligned with beginning of %s' % parent)
  1765. class _NamespaceInfo(_BlockInfo):
  1766. """Stores information about a namespace."""
  1767. def __init__(self, name, linenum):
  1768. _BlockInfo.__init__(self, False)
  1769. self.name = name or ''
  1770. self.starting_linenum = linenum
  1771. self.check_namespace_indentation = True
  1772. def CheckEnd(self, filename, clean_lines, linenum, error):
  1773. """Check end of namespace comments."""
  1774. line = clean_lines.raw_lines[linenum]
  1775. # Check how many lines is enclosed in this namespace. Don't issue
  1776. # warning for missing namespace comments if there aren't enough
  1777. # lines. However, do apply checks if there is already an end of
  1778. # namespace comment and it's incorrect.
  1779. #
  1780. # TODO(unknown): We always want to check end of namespace comments
  1781. # if a namespace is large, but sometimes we also want to apply the
  1782. # check if a short namespace contained nontrivial things (something
  1783. # other than forward declarations). There is currently no logic on
  1784. # deciding what these nontrivial things are, so this check is
  1785. # triggered by namespace size only, which works most of the time.
  1786. if (linenum - self.starting_linenum < 10
  1787. and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
  1788. return
  1789. # Look for matching comment at end of namespace.
  1790. #
  1791. # Note that we accept C style "/* */" comments for terminating
  1792. # namespaces, so that code that terminate namespaces inside
  1793. # preprocessor macros can be cpplint clean.
  1794. #
  1795. # We also accept stuff like "// end of namespace <name>." with the
  1796. # period at the end.
  1797. #
  1798. # Besides these, we don't accept anything else, otherwise we might
  1799. # get false negatives when existing comment is a substring of the
  1800. # expected namespace.
  1801. if self.name:
  1802. # Named namespace
  1803. if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
  1804. r'[\*/\.\\\s]*$'),
  1805. line):
  1806. error(filename, linenum, 'readability/namespace', 5,
  1807. 'Namespace should be terminated with "// namespace %s"' %
  1808. self.name)
  1809. else:
  1810. # Anonymous namespace
  1811. if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
  1812. # If "// namespace anonymous" or "// anonymous namespace (more text)",
  1813. # mention "// anonymous namespace" as an acceptable form
  1814. if Match(r'}.*\b(namespace anonymous|anonymous namespace)\b', line):
  1815. error(filename, linenum, 'readability/namespace', 5,
  1816. 'Anonymous namespace should be terminated with "// namespace"'
  1817. ' or "// anonymous namespace"')
  1818. else:
  1819. error(filename, linenum, 'readability/namespace', 5,
  1820. 'Anonymous namespace should be terminated with "// namespace"')
  1821. class _PreprocessorInfo(object):
  1822. """Stores checkpoints of nesting stacks when #if/#else is seen."""
  1823. def __init__(self, stack_before_if):
  1824. # The entire nesting stack before #if
  1825. self.stack_before_if = stack_before_if
  1826. # The entire nesting stack up to #else
  1827. self.stack_before_else = []
  1828. # Whether we have already seen #else or #elif
  1829. self.seen_else = False
  1830. class NestingState(object):
  1831. """Holds states related to parsing braces."""
  1832. def __init__(self):
  1833. # Stack for tracking all braces. An object is pushed whenever we
  1834. # see a "{", and popped when we see a "}". Only 3 types of
  1835. # objects are possible:
  1836. # - _ClassInfo: a class or struct.
  1837. # - _NamespaceInfo: a namespace.
  1838. # - _BlockInfo: some other type of block.
  1839. self.stack = []
  1840. # Top of the previous stack before each Update().
  1841. #
  1842. # Because the nesting_stack is updated at the end of each line, we
  1843. # had to do some convoluted checks to find out what is the current
  1844. # scope at the beginning of the line. This check is simplified by
  1845. # saving the previous top of nesting stack.
  1846. #
  1847. # We could save the full stack, but we only need the top. Copying
  1848. # the full nesting stack would slow down cpplint by ~10%.
  1849. self.previous_stack_top = []
  1850. # Stack of _PreprocessorInfo objects.
  1851. self.pp_stack = []
  1852. def SeenOpenBrace(self):
  1853. """Check if we have seen the opening brace for the innermost block.
  1854. Returns:
  1855. True if we have seen the opening brace, False if the innermost
  1856. block is still expecting an opening brace.
  1857. """
  1858. return (not self.stack) or self.stack[-1].seen_open_brace
  1859. def InNamespaceBody(self):
  1860. """Check if we are currently one level inside a namespace body.
  1861. Returns:
  1862. True if top of the stack is a namespace block, False otherwise.
  1863. """
  1864. return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
  1865. def InExternC(self):
  1866. """Check if we are currently one level inside an 'extern "C"' block.
  1867. Returns:
  1868. True if top of the stack is an extern block, False otherwise.
  1869. """
  1870. return self.stack and isinstance(self.stack[-1], _ExternCInfo)
  1871. def InClassDeclaration(self):
  1872. """Check if we are currently one level inside a class or struct declaration.
  1873. Returns:
  1874. True if top of the stack is a class/struct, False otherwise.
  1875. """
  1876. return self.stack and isinstance(self.stack[-1], _ClassInfo)
  1877. def InAsmBlock(self):
  1878. """Check if we are currently one level inside an inline ASM block.
  1879. Returns:
  1880. True if the top of the stack is a block containing inline ASM.
  1881. """
  1882. return self.stack and self.stack[-1].inline_asm != _NO_ASM
  1883. def InTemplateArgumentList(self, clean_lines, linenum, pos):
  1884. """Check if current position is inside template argument list.
  1885. Args:
  1886. clean_lines: A CleansedLines instance containing the file.
  1887. linenum: The number of the line to check.
  1888. pos: position just after the suspected template argument.
  1889. Returns:
  1890. True if (linenum, pos) is inside template arguments.
  1891. """
  1892. while linenum < clean_lines.NumLines():
  1893. # Find the earliest character that might indicate a template argument
  1894. line = clean_lines.elided[linenum]
  1895. match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
  1896. if not match:
  1897. linenum += 1
  1898. pos = 0
  1899. continue
  1900. token = match.group(1)
  1901. pos += len(match.group(0))
  1902. # These things do not look like template argument list:
  1903. # class Suspect {
  1904. # class Suspect x; }
  1905. if token in ('{', '}', ';'): return False
  1906. # These things look like template argument list:
  1907. # template <class Suspect>
  1908. # template <class Suspect = default_value>
  1909. # template <class Suspect[]>
  1910. # template <class Suspect...>
  1911. if token in ('>', '=', '[', ']', '.'): return True
  1912. # Check if token is an unmatched '<'.
  1913. # If not, move on to the next character.
  1914. if token != '<':
  1915. pos += 1
  1916. if pos >= len(line):
  1917. linenum += 1
  1918. pos = 0
  1919. continue
  1920. # We can't be sure if we just find a single '<', and need to
  1921. # find the matching '>'.
  1922. (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
  1923. if end_pos < 0:
  1924. # Not sure if template argument list or syntax error in file
  1925. return False
  1926. linenum = end_line
  1927. pos = end_pos
  1928. return False
  1929. def UpdatePreprocessor(self, line):
  1930. """Update preprocessor stack.
  1931. We need to handle preprocessors due to classes like this:
  1932. #ifdef SWIG
  1933. struct ResultDetailsPageElementExtensionPoint {
  1934. #else
  1935. struct ResultDetailsPageElementExtensionPoint : public Extension {
  1936. #endif
  1937. We make the following assumptions (good enough for most files):
  1938. - Preprocessor condition evaluates to true from #if up to first
  1939. #else/#elif/#endif.
  1940. - Preprocessor condition evaluates to false from #else/#elif up
  1941. to #endif. We still perform lint checks on these lines, but
  1942. these do not affect nesting stack.
  1943. Args:
  1944. line: current line to check.
  1945. """
  1946. if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
  1947. # Beginning of #if block, save the nesting stack here. The saved
  1948. # stack will allow us to restore the parsing state in the #else case.
  1949. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
  1950. elif Match(r'^\s*#\s*(else|elif)\b', line):
  1951. # Beginning of #else block
  1952. if self.pp_stack:
  1953. if not self.pp_stack[-1].seen_else:
  1954. # This is the first #else or #elif block. Remember the
  1955. # whole nesting stack up to this point. This is what we
  1956. # keep after the #endif.
  1957. self.pp_stack[-1].seen_else = True
  1958. self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
  1959. # Restore the stack to how it was before the #if
  1960. self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
  1961. else:
  1962. # TODO(unknown): unexpected #else, issue warning?
  1963. pass
  1964. elif Match(r'^\s*#\s*endif\b', line):
  1965. # End of #if or #else blocks.
  1966. if self.pp_stack:
  1967. # If we saw an #else, we will need to restore the nesting
  1968. # stack to its former state before the #else, otherwise we
  1969. # will just continue from where we left off.
  1970. if self.pp_stack[-1].seen_else:
  1971. # Here we can just use a shallow copy since we are the last
  1972. # reference to it.
  1973. self.stack = self.pp_stack[-1].stack_before_else
  1974. # Drop the corresponding #if
  1975. self.pp_stack.pop()
  1976. else:
  1977. # TODO(unknown): unexpected #endif, issue warning?
  1978. pass
  1979. # TODO(unknown): Update() is too long, but we will refactor later.
  1980. def Update(self, filename, clean_lines, linenum, error):
  1981. """Update nesting state with current line.
  1982. Args:
  1983. filename: The name of the current file.
  1984. clean_lines: A CleansedLines instance containing the file.
  1985. linenum: The number of the line to check.
  1986. error: The function to call with any errors found.
  1987. """
  1988. line = clean_lines.elided[linenum]
  1989. # Remember top of the previous nesting stack.
  1990. #
  1991. # The stack is always pushed/popped and not modified in place, so
  1992. # we can just do a shallow copy instead of copy.deepcopy. Using
  1993. # deepcopy would slow down cpplint by ~28%.
  1994. if self.stack:
  1995. self.previous_stack_top = self.stack[-1]
  1996. else:
  1997. self.previous_stack_top = None
  1998. # Update pp_stack
  1999. self.UpdatePreprocessor(line)
  2000. # Count parentheses. This is to avoid adding struct arguments to
  2001. # the nesting stack.
  2002. if self.stack:
  2003. inner_block = self.stack[-1]
  2004. depth_change = line.count('(') - line.count(')')
  2005. inner_block.open_parentheses += depth_change
  2006. # Also check if we are starting or ending an inline assembly block.
  2007. if inner_block.inline_asm in (_NO_ASM, _END_ASM):
  2008. if (depth_change != 0 and
  2009. inner_block.open_parentheses == 1 and
  2010. _MATCH_ASM.match(line)):
  2011. # Enter assembly block
  2012. inner_block.inline_asm = _INSIDE_ASM
  2013. else:
  2014. # Not entering assembly block. If previous line was _END_ASM,
  2015. # we will now shift to _NO_ASM state.
  2016. inner_block.inline_asm = _NO_ASM
  2017. elif (inner_block.inline_asm == _INSIDE_ASM and
  2018. inner_block.open_parentheses == 0):
  2019. # Exit assembly block
  2020. inner_block.inline_asm = _END_ASM
  2021. # Consume namespace declaration at the beginning of the line. Do
  2022. # this in a loop so that we catch same line declarations like this:
  2023. # namespace proto2 { namespace bridge { class MessageSet; } }
  2024. while True:
  2025. # Match start of namespace. The "\b\s*" below catches namespace
  2026. # declarations even if it weren't followed by a whitespace, this
  2027. # is so that we don't confuse our namespace checker. The
  2028. # missing spaces will be flagged by CheckSpacing.
  2029. namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
  2030. if not namespace_decl_match:
  2031. break
  2032. new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
  2033. self.stack.append(new_namespace)
  2034. line = namespace_decl_match.group(2)
  2035. if line.find('{') != -1:
  2036. new_namespace.seen_open_brace = True
  2037. line = line[line.find('{') + 1:]
  2038. # Look for a class declaration in whatever is left of the line
  2039. # after parsing namespaces. The regexp accounts for decorated classes
  2040. # such as in:
  2041. # class LOCKABLE API Object {
  2042. # };
  2043. class_decl_match = Match(
  2044. r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
  2045. r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
  2046. r'(.*)$', line)
  2047. if (class_decl_match and
  2048. (not self.stack or self.stack[-1].open_parentheses == 0)):
  2049. # We do not want to accept classes that are actually template arguments:
  2050. # template <class Ignore1,
  2051. # class Ignore2 = Default<Args>,
  2052. # template <Args> class Ignore3>
  2053. # void Function() {};
  2054. #
  2055. # To avoid template argument cases, we scan forward and look for
  2056. # an unmatched '>'. If we see one, assume we are inside a
  2057. # template argument list.
  2058. end_declaration = len(class_decl_match.group(1))
  2059. if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
  2060. self.stack.append(_ClassInfo(
  2061. class_decl_match.group(3), class_decl_match.group(2),
  2062. clean_lines, linenum))
  2063. line = class_decl_match.group(4)
  2064. # If we have not yet seen the opening brace for the innermost block,
  2065. # run checks here.
  2066. if not self.SeenOpenBrace():
  2067. self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
  2068. # Update access control if we are inside a class/struct
  2069. if self.stack and isinstance(self.stack[-1], _ClassInfo):
  2070. classinfo = self.stack[-1]
  2071. access_match = Match(
  2072. r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
  2073. r':(?:[^:]|$)',
  2074. line)
  2075. if access_match:
  2076. classinfo.access = access_match.group(2)
  2077. # Check that access keywords are indented +1 space. Skip this
  2078. # check if the keywords are not preceded by whitespaces.
  2079. indent = access_match.group(1)
  2080. if (len(indent) != classinfo.class_indent + 1 and
  2081. Match(r'^\s*$', indent)):
  2082. if classinfo.is_struct:
  2083. parent = 'struct ' + classinfo.name
  2084. else:
  2085. parent = 'class ' + classinfo.name
  2086. slots = ''
  2087. if access_match.group(3):
  2088. slots = access_match.group(3)
  2089. error(filename, linenum, 'whitespace/indent', 3,
  2090. '%s%s: should be indented +1 space inside %s' % (
  2091. access_match.group(2), slots, parent))
  2092. # Consume braces or semicolons from what's left of the line
  2093. while True:
  2094. # Match first brace, semicolon, or closed parenthesis.
  2095. matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
  2096. if not matched:
  2097. break
  2098. token = matched.group(1)
  2099. if token == '{':
  2100. # If namespace or class hasn't seen a opening brace yet, mark
  2101. # namespace/class head as complete. Push a new block onto the
  2102. # stack otherwise.
  2103. if not self.SeenOpenBrace():
  2104. self.stack[-1].seen_open_brace = True
  2105. elif Match(r'^extern\s*"[^"]*"\s*\{', line):
  2106. self.stack.append(_ExternCInfo())
  2107. else:
  2108. self.stack.append(_BlockInfo(True))
  2109. if _MATCH_ASM.match(line):
  2110. self.stack[-1].inline_asm = _BLOCK_ASM
  2111. elif token == ';' or token == ')':
  2112. # If we haven't seen an opening brace yet, but we already saw
  2113. # a semicolon, this is probably a forward declaration. Pop
  2114. # the stack for these.
  2115. #
  2116. # Similarly, if we haven't seen an opening brace yet, but we
  2117. # already saw a closing parenthesis, then these are probably
  2118. # function arguments with extra "class" or "struct" keywords.
  2119. # Also pop these stack for these.
  2120. if not self.SeenOpenBrace():
  2121. self.stack.pop()
  2122. else: # token == '}'
  2123. # Perform end of block checks and pop the stack.
  2124. if self.stack:
  2125. self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
  2126. self.stack.pop()
  2127. line = matched.group(2)
  2128. def InnermostClass(self):
  2129. """Get class info on the top of the stack.
  2130. Returns:
  2131. A _ClassInfo object if we are inside a class, or None otherwise.
  2132. """
  2133. for i in range(len(self.stack), 0, -1):
  2134. classinfo = self.stack[i - 1]
  2135. if isinstance(classinfo, _ClassInfo):
  2136. return classinfo
  2137. return None
  2138. def CheckCompletedBlocks(self, filename, error):
  2139. """Checks that all classes and namespaces have been completely parsed.
  2140. Call this when all lines in a file have been processed.
  2141. Args:
  2142. filename: The name of the current file.
  2143. error: The function to call with any errors found.
  2144. """
  2145. # Note: This test can result in false positives if #ifdef constructs
  2146. # get in the way of brace matching. See the testBuildClass test in
  2147. # cpplint_unittest.py for an example of this.
  2148. for obj in self.stack:
  2149. if isinstance(obj, _ClassInfo):
  2150. error(filename, obj.starting_linenum, 'build/class', 5,
  2151. 'Failed to find complete declaration of class %s' %
  2152. obj.name)
  2153. elif isinstance(obj, _NamespaceInfo):
  2154. error(filename, obj.starting_linenum, 'build/namespaces', 5,
  2155. 'Failed to find complete declaration of namespace %s' %
  2156. obj.name)
  2157. def CheckForNonStandardConstructs(filename, clean_lines, linenum,
  2158. nesting_state, error):
  2159. r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
  2160. Complain about several constructs which gcc-2 accepts, but which are
  2161. not standard C++. Warning about these in lint is one way to ease the
  2162. transition to new compilers.
  2163. - put storage class first (e.g. "static const" instead of "const static").
  2164. - "%lld" instead of %qd" in printf-type functions.
  2165. - "%1$d" is non-standard in printf-type functions.
  2166. - "\%" is an undefined character escape sequence.
  2167. - text after #endif is not allowed.
  2168. - invalid inner-style forward declaration.
  2169. - >? and <? operators, and their >?= and <?= cousins.
  2170. Additionally, check for constructor/destructor style violations and reference
  2171. members, as it is very convenient to do so while checking for
  2172. gcc-2 compliance.
  2173. Args:
  2174. filename: The name of the current file.
  2175. clean_lines: A CleansedLines instance containing the file.
  2176. linenum: The number of the line to check.
  2177. nesting_state: A NestingState instance which maintains information about
  2178. the current stack of nested blocks being parsed.
  2179. error: A callable to which errors are reported, which takes 4 arguments:
  2180. filename, line number, error level, and message
  2181. """
  2182. # Remove comments from the line, but leave in strings for now.
  2183. line = clean_lines.lines[linenum]
  2184. if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
  2185. error(filename, linenum, 'runtime/printf_format', 3,
  2186. '%q in format strings is deprecated. Use %ll instead.')
  2187. if Search(r'printf\s*\(.*".*%\d+\$', line):
  2188. error(filename, linenum, 'runtime/printf_format', 2,
  2189. '%N$ formats are unconventional. Try rewriting to avoid them.')
  2190. # Remove escaped backslashes before looking for undefined escapes.
  2191. line = line.replace('\\\\', '')
  2192. if Search(r'("|\').*\\(%|\[|\(|{)', line):
  2193. error(filename, linenum, 'build/printf_format', 3,
  2194. '%, [, (, and { are undefined character escapes. Unescape them.')
  2195. # For the rest, work with both comments and strings removed.
  2196. line = clean_lines.elided[linenum]
  2197. if Search(r'\b(const|volatile|void|char|short|int|long'
  2198. r'|float|double|signed|unsigned'
  2199. r'|schar|u?int8|u?int16|u?int32|u?int64)'
  2200. r'\s+(register|static|extern|typedef)\b',
  2201. line):
  2202. error(filename, linenum, 'build/storage_class', 5,
  2203. 'Storage class (static, extern, typedef, etc) should be first.')
  2204. if Match(r'\s*#\s*endif\s*[^/\s]+', line):
  2205. error(filename, linenum, 'build/endif_comment', 5,
  2206. 'Uncommented text after #endif is non-standard. Use a comment.')
  2207. if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
  2208. error(filename, linenum, 'build/forward_decl', 5,
  2209. 'Inner-style forward declarations are invalid. Remove this line.')
  2210. if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
  2211. line):
  2212. error(filename, linenum, 'build/deprecated', 3,
  2213. '>? and <? (max and min) operators are non-standard and deprecated.')
  2214. if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
  2215. # TODO(unknown): Could it be expanded safely to arbitrary references,
  2216. # without triggering too many false positives? The first
  2217. # attempt triggered 5 warnings for mostly benign code in the regtest, hence
  2218. # the restriction.
  2219. # Here's the original regexp, for the reference:
  2220. # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
  2221. # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
  2222. error(filename, linenum, 'runtime/member_string_references', 2,
  2223. 'const string& members are dangerous. It is much better to use '
  2224. 'alternatives, such as pointers or simple constants.')
  2225. # Everything else in this function operates on class declarations.
  2226. # Return early if the top of the nesting stack is not a class, or if
  2227. # the class head is not completed yet.
  2228. classinfo = nesting_state.InnermostClass()
  2229. if not classinfo or not classinfo.seen_open_brace:
  2230. return
  2231. # The class may have been declared with namespace or classname qualifiers.
  2232. # The constructor and destructor will not have those qualifiers.
  2233. base_classname = classinfo.name.split('::')[-1]
  2234. # Look for single-argument constructors that aren't marked explicit.
  2235. # Technically a valid construct, but against style. Also look for
  2236. # non-single-argument constructors which are also technically valid, but
  2237. # strongly suggest something is wrong.
  2238. explicit_constructor_match = Match(
  2239. r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*'
  2240. r'\(((?:[^()]|\([^()]*\))*)\)'
  2241. % re.escape(base_classname),
  2242. line)
  2243. if explicit_constructor_match:
  2244. is_marked_explicit = explicit_constructor_match.group(1)
  2245. if not explicit_constructor_match.group(2):
  2246. constructor_args = []
  2247. else:
  2248. constructor_args = explicit_constructor_match.group(2).split(',')
  2249. # collapse arguments so that commas in template parameter lists and function
  2250. # argument parameter lists don't split arguments in two
  2251. i = 0
  2252. while i < len(constructor_args):
  2253. constructor_arg = constructor_args[i]
  2254. while (constructor_arg.count('<') > constructor_arg.count('>') or
  2255. constructor_arg.count('(') > constructor_arg.count(')')):
  2256. constructor_arg += ',' + constructor_args[i + 1]
  2257. del constructor_args[i + 1]
  2258. constructor_args[i] = constructor_arg
  2259. i += 1
  2260. defaulted_args = [arg for arg in constructor_args if '=' in arg]
  2261. noarg_constructor = (not constructor_args or # empty arg list
  2262. # 'void' arg specifier
  2263. (len(constructor_args) == 1 and
  2264. constructor_args[0].strip() == 'void'))
  2265. onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
  2266. not noarg_constructor) or
  2267. # all but at most one arg defaulted
  2268. (len(constructor_args) >= 1 and
  2269. not noarg_constructor and
  2270. len(defaulted_args) >= len(constructor_args) - 1))
  2271. initializer_list_constructor = bool(
  2272. onearg_constructor and
  2273. Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
  2274. copy_constructor = bool(
  2275. onearg_constructor and
  2276. Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
  2277. % re.escape(base_classname), constructor_args[0].strip()))
  2278. if (not is_marked_explicit and
  2279. onearg_constructor and
  2280. not initializer_list_constructor and
  2281. not copy_constructor):
  2282. if defaulted_args:
  2283. error(filename, linenum, 'runtime/explicit', 5,
  2284. 'Constructors callable with one argument '
  2285. 'should be marked explicit.')
  2286. else:
  2287. error(filename, linenum, 'runtime/explicit', 5,
  2288. 'Single-parameter constructors should be marked explicit.')
  2289. elif is_marked_explicit and not onearg_constructor:
  2290. if noarg_constructor:
  2291. error(filename, linenum, 'runtime/explicit', 5,
  2292. 'Zero-parameter constructors should not be marked explicit.')
  2293. else:
  2294. error(filename, linenum, 'runtime/explicit', 0,
  2295. 'Constructors that require multiple arguments '
  2296. 'should not be marked explicit.')
  2297. def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
  2298. """Checks for the correctness of various spacing around function calls.
  2299. Args:
  2300. filename: The name of the current file.
  2301. clean_lines: A CleansedLines instance containing the file.
  2302. linenum: The number of the line to check.
  2303. error: The function to call with any errors found.
  2304. """
  2305. line = clean_lines.elided[linenum]
  2306. # Since function calls often occur inside if/for/while/switch
  2307. # expressions - which have their own, more liberal conventions - we
  2308. # first see if we should be looking inside such an expression for a
  2309. # function call, to which we can apply more strict standards.
  2310. fncall = line # if there's no control flow construct, look at whole line
  2311. for pattern in (r'\bif\s*\((.*)\)\s*{',
  2312. r'\bfor\s*\((.*)\)\s*{',
  2313. r'\bwhile\s*\((.*)\)\s*[{;]',
  2314. r'\bswitch\s*\((.*)\)\s*{'):
  2315. match = Search(pattern, line)
  2316. if match:
  2317. fncall = match.group(1) # look inside the parens for function calls
  2318. break
  2319. # Except in if/for/while/switch, there should never be space
  2320. # immediately inside parens (eg "f( 3, 4 )"). We make an exception
  2321. # for nested parens ( (a+b) + c ). Likewise, there should never be
  2322. # a space before a ( when it's a function argument. I assume it's a
  2323. # function argument when the char before the whitespace is legal in
  2324. # a function name (alnum + _) and we're not starting a macro. Also ignore
  2325. # pointers and references to arrays and functions coz they're too tricky:
  2326. # we use a very simple way to recognize these:
  2327. # " (something)(maybe-something)" or
  2328. # " (something)(maybe-something," or
  2329. # " (something)[something]"
  2330. # Note that we assume the contents of [] to be short enough that
  2331. # they'll never need to wrap.
  2332. if ( # Ignore control structures.
  2333. not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
  2334. fncall) and
  2335. # Ignore pointers/references to functions.
  2336. not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
  2337. # Ignore pointers/references to arrays.
  2338. not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
  2339. if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
  2340. error(filename, linenum, 'whitespace/parens', 4,
  2341. 'Extra space after ( in function call')
  2342. elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
  2343. error(filename, linenum, 'whitespace/parens', 2,
  2344. 'Extra space after (')
  2345. if (Search(r'\w\s+\(', fncall) and
  2346. not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
  2347. not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
  2348. not Search(r'\bcase\s+\(', fncall)):
  2349. # TODO(unknown): Space after an operator function seem to be a common
  2350. # error, silence those for now by restricting them to highest verbosity.
  2351. if Search(r'\boperator_*\b', line):
  2352. error(filename, linenum, 'whitespace/parens', 0,
  2353. 'Extra space before ( in function call')
  2354. else:
  2355. error(filename, linenum, 'whitespace/parens', 4,
  2356. 'Extra space before ( in function call')
  2357. # If the ) is followed only by a newline or a { + newline, assume it's
  2358. # part of a control statement (if/while/etc), and don't complain
  2359. if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
  2360. # If the closing parenthesis is preceded by only whitespaces,
  2361. # try to give a more descriptive error message.
  2362. if Search(r'^\s+\)', fncall):
  2363. error(filename, linenum, 'whitespace/parens', 2,
  2364. 'Closing ) should be moved to the previous line')
  2365. else:
  2366. error(filename, linenum, 'whitespace/parens', 2,
  2367. 'Extra space before )')
  2368. def IsBlankLine(line):
  2369. """Returns true if the given line is blank.
  2370. We consider a line to be blank if the line is empty or consists of
  2371. only white spaces.
  2372. Args:
  2373. line: A line of a string.
  2374. Returns:
  2375. True, if the given line is blank.
  2376. """
  2377. return not line or line.isspace()
  2378. def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
  2379. error):
  2380. is_namespace_indent_item = (
  2381. len(nesting_state.stack) > 1 and
  2382. nesting_state.stack[-1].check_namespace_indentation and
  2383. isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
  2384. nesting_state.previous_stack_top == nesting_state.stack[-2])
  2385. if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
  2386. clean_lines.elided, line):
  2387. CheckItemIndentationInNamespace(filename, clean_lines.elided,
  2388. line, error)
  2389. def CheckForFunctionLengths(filename, clean_lines, linenum,
  2390. function_state, error):
  2391. """Reports for long function bodies.
  2392. For an overview why this is done, see:
  2393. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
  2394. Uses a simplistic algorithm assuming other style guidelines
  2395. (especially spacing) are followed.
  2396. Only checks unindented functions, so class members are unchecked.
  2397. Trivial bodies are unchecked, so constructors with huge initializer lists
  2398. may be missed.
  2399. Blank/comment lines are not counted so as to avoid encouraging the removal
  2400. of vertical space and comments just to get through a lint check.
  2401. NOLINT *on the last line of a function* disables this check.
  2402. Args:
  2403. filename: The name of the current file.
  2404. clean_lines: A CleansedLines instance containing the file.
  2405. linenum: The number of the line to check.
  2406. function_state: Current function name and lines in body so far.
  2407. error: The function to call with any errors found.
  2408. """
  2409. lines = clean_lines.lines
  2410. line = lines[linenum]
  2411. joined_line = ''
  2412. starting_func = False
  2413. regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
  2414. match_result = Match(regexp, line)
  2415. if match_result:
  2416. # If the name is all caps and underscores, figure it's a macro and
  2417. # ignore it, unless it's TEST or TEST_F.
  2418. function_name = match_result.group(1).split()[-1]
  2419. if function_name == 'TEST' or function_name == 'TEST_F' or (
  2420. not Match(r'[A-Z_]+$', function_name)):
  2421. starting_func = True
  2422. if starting_func:
  2423. body_found = False
  2424. for start_linenum in xrange(linenum, clean_lines.NumLines()):
  2425. start_line = lines[start_linenum]
  2426. joined_line += ' ' + start_line.lstrip()
  2427. if Search(r'(;|})', start_line): # Declarations and trivial functions
  2428. body_found = True
  2429. break # ... ignore
  2430. elif Search(r'{', start_line):
  2431. body_found = True
  2432. function = Search(r'((\w|:)*)\(', line).group(1)
  2433. if Match(r'TEST', function): # Handle TEST... macros
  2434. parameter_regexp = Search(r'(\(.*\))', joined_line)
  2435. if parameter_regexp: # Ignore bad syntax
  2436. function += parameter_regexp.group(1)
  2437. else:
  2438. function += '()'
  2439. function_state.Begin(function)
  2440. break
  2441. if not body_found:
  2442. # No body for the function (or evidence of a non-function) was found.
  2443. error(filename, linenum, 'readability/fn_size', 5,
  2444. 'Lint failed to find start of function body.')
  2445. elif Match(r'^\}\s*$', line): # function end
  2446. function_state.Check(error, filename, linenum)
  2447. function_state.End()
  2448. elif not Match(r'^\s*$', line):
  2449. function_state.Count() # Count non-blank/non-comment lines.
  2450. _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
  2451. def CheckComment(line, filename, linenum, next_line_start, error):
  2452. """Checks for common mistakes in comments.
  2453. Args:
  2454. line: The line in question.
  2455. filename: The name of the current file.
  2456. linenum: The number of the line to check.
  2457. next_line_start: The first non-whitespace column of the next line.
  2458. error: The function to call with any errors found.
  2459. """
  2460. commentpos = line.find('//')
  2461. if commentpos != -1:
  2462. # Check if the // may be in quotes. If so, ignore it
  2463. # Comparisons made explicit for clarity -- pylint: disable=g-explicit-bool-comparison
  2464. if (line.count('"', 0, commentpos) -
  2465. line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
  2466. # Allow one space for new scopes, two spaces otherwise:
  2467. if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
  2468. ((commentpos >= 1 and
  2469. line[commentpos-1] not in string.whitespace) or
  2470. (commentpos >= 2 and
  2471. line[commentpos-2] not in string.whitespace))):
  2472. error(filename, linenum, 'whitespace/comments', 2,
  2473. 'At least two spaces is best between code and comments')
  2474. # Checks for common mistakes in TODO comments.
  2475. comment = line[commentpos:]
  2476. match = _RE_PATTERN_TODO.match(comment)
  2477. if match:
  2478. # One whitespace is correct; zero whitespace is handled elsewhere.
  2479. leading_whitespace = match.group(1)
  2480. if len(leading_whitespace) > 1:
  2481. error(filename, linenum, 'whitespace/todo', 2,
  2482. 'Too many spaces before TODO')
  2483. username = match.group(2)
  2484. if not username:
  2485. error(filename, linenum, 'readability/todo', 2,
  2486. 'Missing username in TODO; it should look like '
  2487. '"// TODO(my_username): Stuff."')
  2488. middle_whitespace = match.group(3)
  2489. # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
  2490. if middle_whitespace != ' ' and middle_whitespace != '':
  2491. error(filename, linenum, 'whitespace/todo', 2,
  2492. 'TODO(my_username) should be followed by a space')
  2493. # If the comment contains an alphanumeric character, there
  2494. # should be a space somewhere between it and the // unless
  2495. # it's a /// or //! Doxygen comment.
  2496. if (Match(r'//[^ ]*\w', comment) and
  2497. not Match(r'(///|//\!)(\s+|$)', comment)):
  2498. error(filename, linenum, 'whitespace/comments', 4,
  2499. 'Should have a space between // and comment')
  2500. def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
  2501. """Checks for improper use of DISALLOW* macros.
  2502. Args:
  2503. filename: The name of the current file.
  2504. clean_lines: A CleansedLines instance containing the file.
  2505. linenum: The number of the line to check.
  2506. nesting_state: A NestingState instance which maintains information about
  2507. the current stack of nested blocks being parsed.
  2508. error: The function to call with any errors found.
  2509. """
  2510. line = clean_lines.elided[linenum] # get rid of comments and strings
  2511. matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
  2512. r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
  2513. if not matched:
  2514. return
  2515. if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
  2516. if nesting_state.stack[-1].access != 'private':
  2517. error(filename, linenum, 'readability/constructors', 3,
  2518. '%s must be in the private: section' % matched.group(1))
  2519. else:
  2520. # Found DISALLOW* macro outside a class declaration, or perhaps it
  2521. # was used inside a function when it should have been part of the
  2522. # class declaration. We could issue a warning here, but it
  2523. # probably resulted in a compiler error already.
  2524. pass
  2525. def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
  2526. """Checks for the correctness of various spacing issues in the code.
  2527. Things we check for: spaces around operators, spaces after
  2528. if/for/while/switch, no spaces around parens in function calls, two
  2529. spaces between code and comment, don't start a block with a blank
  2530. line, don't end a function with a blank line, don't add a blank line
  2531. after public/protected/private, don't have too many blank lines in a row.
  2532. Args:
  2533. filename: The name of the current file.
  2534. clean_lines: A CleansedLines instance containing the file.
  2535. linenum: The number of the line to check.
  2536. nesting_state: A NestingState instance which maintains information about
  2537. the current stack of nested blocks being parsed.
  2538. error: The function to call with any errors found.
  2539. """
  2540. # Don't use "elided" lines here, otherwise we can't check commented lines.
  2541. # Don't want to use "raw" either, because we don't want to check inside C++11
  2542. # raw strings,
  2543. raw = clean_lines.lines_without_raw_strings
  2544. line = raw[linenum]
  2545. # Before nixing comments, check if the line is blank for no good
  2546. # reason. This includes the first line after a block is opened, and
  2547. # blank lines at the end of a function (ie, right before a line like '}'
  2548. #
  2549. # Skip all the blank line checks if we are immediately inside a
  2550. # namespace body. In other words, don't issue blank line warnings
  2551. # for this block:
  2552. # namespace {
  2553. #
  2554. # }
  2555. #
  2556. # A warning about missing end of namespace comments will be issued instead.
  2557. #
  2558. # Also skip blank line checks for 'extern "C"' blocks, which are formatted
  2559. # like namespaces.
  2560. if (IsBlankLine(line) and
  2561. not nesting_state.InNamespaceBody() and
  2562. not nesting_state.InExternC()):
  2563. elided = clean_lines.elided
  2564. prev_line = elided[linenum - 1]
  2565. prevbrace = prev_line.rfind('{')
  2566. # TODO(unknown): Don't complain if line before blank line, and line after,
  2567. # both start with alnums and are indented the same amount.
  2568. # This ignores whitespace at the start of a namespace block
  2569. # because those are not usually indented.
  2570. if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
  2571. # OK, we have a blank line at the start of a code block. Before we
  2572. # complain, we check if it is an exception to the rule: The previous
  2573. # non-empty line has the parameters of a function header that are indented
  2574. # 4 spaces (because they did not fit in a 80 column line when placed on
  2575. # the same line as the function name). We also check for the case where
  2576. # the previous line is indented 6 spaces, which may happen when the
  2577. # initializers of a constructor do not fit into a 80 column line.
  2578. exception = False
  2579. if Match(r' {6}\w', prev_line): # Initializer list?
  2580. # We are looking for the opening column of initializer list, which
  2581. # should be indented 4 spaces to cause 6 space indentation afterwards.
  2582. search_position = linenum-2
  2583. while (search_position >= 0
  2584. and Match(r' {6}\w', elided[search_position])):
  2585. search_position -= 1
  2586. exception = (search_position >= 0
  2587. and elided[search_position][:5] == ' :')
  2588. else:
  2589. # Search for the function arguments or an initializer list. We use a
  2590. # simple heuristic here: If the line is indented 4 spaces; and we have a
  2591. # closing paren, without the opening paren, followed by an opening brace
  2592. # or colon (for initializer lists) we assume that it is the last line of
  2593. # a function header. If we have a colon indented 4 spaces, it is an
  2594. # initializer list.
  2595. exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
  2596. prev_line)
  2597. or Match(r' {4}:', prev_line))
  2598. if not exception:
  2599. error(filename, linenum, 'whitespace/blank_line', 2,
  2600. 'Redundant blank line at the start of a code block '
  2601. 'should be deleted.')
  2602. # Ignore blank lines at the end of a block in a long if-else
  2603. # chain, like this:
  2604. # if (condition1) {
  2605. # // Something followed by a blank line
  2606. #
  2607. # } else if (condition2) {
  2608. # // Something else
  2609. # }
  2610. if linenum + 1 < clean_lines.NumLines():
  2611. next_line = raw[linenum + 1]
  2612. if (next_line
  2613. and Match(r'\s*}', next_line)
  2614. and next_line.find('} else ') == -1):
  2615. error(filename, linenum, 'whitespace/blank_line', 3,
  2616. 'Redundant blank line at the end of a code block '
  2617. 'should be deleted.')
  2618. matched = Match(r'\s*(public|protected|private):', prev_line)
  2619. if matched:
  2620. error(filename, linenum, 'whitespace/blank_line', 3,
  2621. 'Do not leave a blank line after "%s:"' % matched.group(1))
  2622. # Next, check comments
  2623. next_line_start = 0
  2624. if linenum + 1 < clean_lines.NumLines():
  2625. next_line = raw[linenum + 1]
  2626. next_line_start = len(next_line) - len(next_line.lstrip())
  2627. CheckComment(line, filename, linenum, next_line_start, error)
  2628. # get rid of comments and strings
  2629. line = clean_lines.elided[linenum]
  2630. # You shouldn't have spaces before your brackets, except maybe after
  2631. # 'delete []' or 'return []() {};'
  2632. if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
  2633. error(filename, linenum, 'whitespace/braces', 5,
  2634. 'Extra space before [')
  2635. # In range-based for, we wanted spaces before and after the colon, but
  2636. # not around "::" tokens that might appear.
  2637. if (Search(r'for *\(.*[^:]:[^: ]', line) or
  2638. Search(r'for *\(.*[^: ]:[^:]', line)):
  2639. error(filename, linenum, 'whitespace/forcolon', 2,
  2640. 'Missing space around colon in range-based for loop')
  2641. def CheckOperatorSpacing(filename, clean_lines, linenum, error):
  2642. """Checks for horizontal spacing around operators.
  2643. Args:
  2644. filename: The name of the current file.
  2645. clean_lines: A CleansedLines instance containing the file.
  2646. linenum: The number of the line to check.
  2647. error: The function to call with any errors found.
  2648. """
  2649. line = clean_lines.elided[linenum]
  2650. # Don't try to do spacing checks for operator methods. Do this by
  2651. # replacing the troublesome characters with something else,
  2652. # preserving column position for all other characters.
  2653. #
  2654. # The replacement is done repeatedly to avoid false positives from
  2655. # operators that call operators.
  2656. while True:
  2657. match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
  2658. if match:
  2659. line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
  2660. else:
  2661. break
  2662. # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
  2663. # Otherwise not. Note we only check for non-spaces on *both* sides;
  2664. # sometimes people put non-spaces on one side when aligning ='s among
  2665. # many lines (not that this is behavior that I approve of...)
  2666. if ((Search(r'[\w.]=', line) or
  2667. Search(r'=[\w.]', line))
  2668. and not Search(r'\b(if|while|for) ', line)
  2669. # Operators taken from [lex.operators] in C++11 standard.
  2670. and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
  2671. and not Search(r'operator=', line)):
  2672. error(filename, linenum, 'whitespace/operators', 4,
  2673. 'Missing spaces around =')
  2674. # It's ok not to have spaces around binary operators like + - * /, but if
  2675. # there's too little whitespace, we get concerned. It's hard to tell,
  2676. # though, so we punt on this one for now. TODO.
  2677. # You should always have whitespace around binary operators.
  2678. #
  2679. # Check <= and >= first to avoid false positives with < and >, then
  2680. # check non-include lines for spacing around < and >.
  2681. #
  2682. # If the operator is followed by a comma, assume it's be used in a
  2683. # macro context and don't do any checks. This avoids false
  2684. # positives.
  2685. #
  2686. # Note that && is not included here. Those are checked separately
  2687. # in CheckRValueReference
  2688. match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
  2689. if match:
  2690. error(filename, linenum, 'whitespace/operators', 3,
  2691. 'Missing spaces around %s' % match.group(1))
  2692. elif not Match(r'#.*include', line):
  2693. # Look for < that is not surrounded by spaces. This is only
  2694. # triggered if both sides are missing spaces, even though
  2695. # technically should should flag if at least one side is missing a
  2696. # space. This is done to avoid some false positives with shifts.
  2697. match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
  2698. if match:
  2699. (_, _, end_pos) = CloseExpression(
  2700. clean_lines, linenum, len(match.group(1)))
  2701. if end_pos <= -1:
  2702. error(filename, linenum, 'whitespace/operators', 3,
  2703. 'Missing spaces around <')
  2704. # Look for > that is not surrounded by spaces. Similar to the
  2705. # above, we only trigger if both sides are missing spaces to avoid
  2706. # false positives with shifts.
  2707. match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
  2708. if match:
  2709. (_, _, start_pos) = ReverseCloseExpression(
  2710. clean_lines, linenum, len(match.group(1)))
  2711. if start_pos <= -1:
  2712. error(filename, linenum, 'whitespace/operators', 3,
  2713. 'Missing spaces around >')
  2714. # We allow no-spaces around << when used like this: 10<<20, but
  2715. # not otherwise (particularly, not when used as streams)
  2716. #
  2717. # We also allow operators following an opening parenthesis, since
  2718. # those tend to be macros that deal with operators.
  2719. match = Search(r'(operator|[^\s(<])(?:L|UL|ULL|l|ul|ull)?<<([^\s,=<])', line)
  2720. if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
  2721. not (match.group(1) == 'operator' and match.group(2) == ';')):
  2722. error(filename, linenum, 'whitespace/operators', 3,
  2723. 'Missing spaces around <<')
  2724. # We allow no-spaces around >> for almost anything. This is because
  2725. # C++11 allows ">>" to close nested templates, which accounts for
  2726. # most cases when ">>" is not followed by a space.
  2727. #
  2728. # We still warn on ">>" followed by alpha character, because that is
  2729. # likely due to ">>" being used for right shifts, e.g.:
  2730. # value >> alpha
  2731. #
  2732. # When ">>" is used to close templates, the alphanumeric letter that
  2733. # follows would be part of an identifier, and there should still be
  2734. # a space separating the template type and the identifier.
  2735. # type<type<type>> alpha
  2736. match = Search(r'>>[a-zA-Z_]', line)
  2737. if match:
  2738. error(filename, linenum, 'whitespace/operators', 3,
  2739. 'Missing spaces around >>')
  2740. # There shouldn't be space around unary operators
  2741. match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
  2742. if match:
  2743. error(filename, linenum, 'whitespace/operators', 4,
  2744. 'Extra space for operator %s' % match.group(1))
  2745. def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
  2746. """Checks for horizontal spacing around parentheses.
  2747. Args:
  2748. filename: The name of the current file.
  2749. clean_lines: A CleansedLines instance containing the file.
  2750. linenum: The number of the line to check.
  2751. error: The function to call with any errors found.
  2752. """
  2753. line = clean_lines.elided[linenum]
  2754. # No spaces after an if, while, switch, or for
  2755. match = Search(r' (if\(|for\(|while\(|switch\()', line)
  2756. if match:
  2757. error(filename, linenum, 'whitespace/parens', 5,
  2758. 'Missing space before ( in %s' % match.group(1))
  2759. # For if/for/while/switch, the left and right parens should be
  2760. # consistent about how many spaces are inside the parens, and
  2761. # there should either be zero or one spaces inside the parens.
  2762. # We don't want: "if ( foo)" or "if ( foo )".
  2763. # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  2764. match = Search(r'\b(if|for|while|switch)\s*'
  2765. r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
  2766. line)
  2767. if match:
  2768. if len(match.group(2)) != len(match.group(4)):
  2769. if not (match.group(3) == ';' and
  2770. len(match.group(2)) == 1 + len(match.group(4)) or
  2771. not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
  2772. error(filename, linenum, 'whitespace/parens', 5,
  2773. 'Mismatching spaces inside () in %s' % match.group(1))
  2774. if len(match.group(2)) not in [0, 1]:
  2775. error(filename, linenum, 'whitespace/parens', 5,
  2776. 'Should have zero or one spaces inside ( and ) in %s' %
  2777. match.group(1))
  2778. def CheckCommaSpacing(filename, clean_lines, linenum, error):
  2779. """Checks for horizontal spacing near commas and semicolons.
  2780. Args:
  2781. filename: The name of the current file.
  2782. clean_lines: A CleansedLines instance containing the file.
  2783. linenum: The number of the line to check.
  2784. error: The function to call with any errors found.
  2785. """
  2786. raw = clean_lines.lines_without_raw_strings
  2787. line = clean_lines.elided[linenum]
  2788. # You should always have a space after a comma (either as fn arg or operator)
  2789. #
  2790. # This does not apply when the non-space character following the
  2791. # comma is another comma, since the only time when that happens is
  2792. # for empty macro arguments.
  2793. #
  2794. # We run this check in two passes: first pass on elided lines to
  2795. # verify that lines contain missing whitespaces, second pass on raw
  2796. # lines to confirm that those missing whitespaces are not due to
  2797. # elided comments.
  2798. if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
  2799. Search(r',[^,\s]', raw[linenum])):
  2800. error(filename, linenum, 'whitespace/comma', 3,
  2801. 'Missing space after ,')
  2802. # You should always have a space after a semicolon
  2803. # except for few corner cases
  2804. # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
  2805. # space after ;
  2806. if Search(r';[^\s};\\)/]', line):
  2807. error(filename, linenum, 'whitespace/semicolon', 3,
  2808. 'Missing space after ;')
  2809. def CheckBracesSpacing(filename, clean_lines, linenum, error):
  2810. """Checks for horizontal spacing near commas.
  2811. Args:
  2812. filename: The name of the current file.
  2813. clean_lines: A CleansedLines instance containing the file.
  2814. linenum: The number of the line to check.
  2815. error: The function to call with any errors found.
  2816. """
  2817. line = clean_lines.elided[linenum]
  2818. # Except after an opening paren, or after another opening brace (in case of
  2819. # an initializer list, for instance), you should have spaces before your
  2820. # braces. And since you should never have braces at the beginning of a line,
  2821. # this is an easy test.
  2822. match = Match(r'^(.*[^ ({>]){', line)
  2823. if match:
  2824. # Try a bit harder to check for brace initialization. This
  2825. # happens in one of the following forms:
  2826. # Constructor() : initializer_list_{} { ... }
  2827. # Constructor{}.MemberFunction()
  2828. # Type variable{};
  2829. # FunctionCall(type{}, ...);
  2830. # LastArgument(..., type{});
  2831. # LOG(INFO) << type{} << " ...";
  2832. # map_of_type[{...}] = ...;
  2833. # ternary = expr ? new type{} : nullptr;
  2834. # OuterTemplate<InnerTemplateConstructor<Type>{}>
  2835. #
  2836. # We check for the character following the closing brace, and
  2837. # silence the warning if it's one of those listed above, i.e.
  2838. # "{.;,)<>]:".
  2839. #
  2840. # To account for nested initializer list, we allow any number of
  2841. # closing braces up to "{;,)<". We can't simply silence the
  2842. # warning on first sight of closing brace, because that would
  2843. # cause false negatives for things that are not initializer lists.
  2844. # Silence this: But not this:
  2845. # Outer{ if (...) {
  2846. # Inner{...} if (...){ // Missing space before {
  2847. # }; }
  2848. #
  2849. # There is a false negative with this approach if people inserted
  2850. # spurious semicolons, e.g. "if (cond){};", but we will catch the
  2851. # spurious semicolon with a separate check.
  2852. (endline, endlinenum, endpos) = CloseExpression(
  2853. clean_lines, linenum, len(match.group(1)))
  2854. trailing_text = ''
  2855. if endpos > -1:
  2856. trailing_text = endline[endpos:]
  2857. for offset in xrange(endlinenum + 1,
  2858. min(endlinenum + 3, clean_lines.NumLines() - 1)):
  2859. trailing_text += clean_lines.elided[offset]
  2860. if not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text):
  2861. error(filename, linenum, 'whitespace/braces', 5,
  2862. 'Missing space before {')
  2863. # Make sure '} else {' has spaces.
  2864. if Search(r'}else', line):
  2865. error(filename, linenum, 'whitespace/braces', 5,
  2866. 'Missing space before else')
  2867. # You shouldn't have a space before a semicolon at the end of the line.
  2868. # There's a special case for "for" since the style guide allows space before
  2869. # the semicolon there.
  2870. if Search(r':\s*;\s*$', line):
  2871. error(filename, linenum, 'whitespace/semicolon', 5,
  2872. 'Semicolon defining empty statement. Use {} instead.')
  2873. elif Search(r'^\s*;\s*$', line):
  2874. error(filename, linenum, 'whitespace/semicolon', 5,
  2875. 'Line contains only semicolon. If this should be an empty statement, '
  2876. 'use {} instead.')
  2877. elif (Search(r'\s+;\s*$', line) and
  2878. not Search(r'\bfor\b', line)):
  2879. error(filename, linenum, 'whitespace/semicolon', 5,
  2880. 'Extra space before last semicolon. If this should be an empty '
  2881. 'statement, use {} instead.')
  2882. def IsDecltype(clean_lines, linenum, column):
  2883. """Check if the token ending on (linenum, column) is decltype().
  2884. Args:
  2885. clean_lines: A CleansedLines instance containing the file.
  2886. linenum: the number of the line to check.
  2887. column: end column of the token to check.
  2888. Returns:
  2889. True if this token is decltype() expression, False otherwise.
  2890. """
  2891. (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
  2892. if start_col < 0:
  2893. return False
  2894. if Search(r'\bdecltype\s*$', text[0:start_col]):
  2895. return True
  2896. return False
  2897. def IsTemplateParameterList(clean_lines, linenum, column):
  2898. """Check if the token ending on (linenum, column) is the end of template<>.
  2899. Args:
  2900. clean_lines: A CleansedLines instance containing the file.
  2901. linenum: the number of the line to check.
  2902. column: end column of the token to check.
  2903. Returns:
  2904. True if this token is end of a template parameter list, False otherwise.
  2905. """
  2906. (_, startline, startpos) = ReverseCloseExpression(
  2907. clean_lines, linenum, column)
  2908. if (startpos > -1 and
  2909. Search(r'\btemplate\s*$', clean_lines.elided[startline][0:startpos])):
  2910. return True
  2911. return False
  2912. def IsRValueType(typenames, clean_lines, nesting_state, linenum, column):
  2913. """Check if the token ending on (linenum, column) is a type.
  2914. Assumes that text to the right of the column is "&&" or a function
  2915. name.
  2916. Args:
  2917. typenames: set of type names from template-argument-list.
  2918. clean_lines: A CleansedLines instance containing the file.
  2919. nesting_state: A NestingState instance which maintains information about
  2920. the current stack of nested blocks being parsed.
  2921. linenum: the number of the line to check.
  2922. column: end column of the token to check.
  2923. Returns:
  2924. True if this token is a type, False if we are not sure.
  2925. """
  2926. prefix = clean_lines.elided[linenum][0:column]
  2927. # Get one word to the left. If we failed to do so, this is most
  2928. # likely not a type, since it's unlikely that the type name and "&&"
  2929. # would be split across multiple lines.
  2930. match = Match(r'^(.*)(\b\w+|[>*)&])\s*$', prefix)
  2931. if not match:
  2932. return False
  2933. # Check text following the token. If it's "&&>" or "&&," or "&&...", it's
  2934. # most likely a rvalue reference used inside a template.
  2935. suffix = clean_lines.elided[linenum][column:]
  2936. if Match(r'&&\s*(?:[>,]|\.\.\.)', suffix):
  2937. return True
  2938. # Check for known types and end of templates:
  2939. # int&& variable
  2940. # vector<int>&& variable
  2941. #
  2942. # Because this function is called recursively, we also need to
  2943. # recognize pointer and reference types:
  2944. # int* Function()
  2945. # int& Function()
  2946. if (match.group(2) in typenames or
  2947. match.group(2) in ['char', 'char16_t', 'char32_t', 'wchar_t', 'bool',
  2948. 'short', 'int', 'long', 'signed', 'unsigned',
  2949. 'float', 'double', 'void', 'auto', '>', '*', '&']):
  2950. return True
  2951. # If we see a close parenthesis, look for decltype on the other side.
  2952. # decltype would unambiguously identify a type, anything else is
  2953. # probably a parenthesized expression and not a type.
  2954. if match.group(2) == ')':
  2955. return IsDecltype(
  2956. clean_lines, linenum, len(match.group(1)) + len(match.group(2)) - 1)
  2957. # Check for casts and cv-qualifiers.
  2958. # match.group(1) remainder
  2959. # -------------- ---------
  2960. # const_cast< type&&
  2961. # const type&&
  2962. # type const&&
  2963. if Search(r'\b(?:const_cast\s*<|static_cast\s*<|dynamic_cast\s*<|'
  2964. r'reinterpret_cast\s*<|\w+\s)\s*$',
  2965. match.group(1)):
  2966. return True
  2967. # Look for a preceding symbol that might help differentiate the context.
  2968. # These are the cases that would be ambiguous:
  2969. # match.group(1) remainder
  2970. # -------------- ---------
  2971. # Call ( expression &&
  2972. # Declaration ( type&&
  2973. # sizeof ( type&&
  2974. # if ( expression &&
  2975. # while ( expression &&
  2976. # for ( type&&
  2977. # for( ; expression &&
  2978. # statement ; type&&
  2979. # block { type&&
  2980. # constructor { expression &&
  2981. start = linenum
  2982. line = match.group(1)
  2983. match_symbol = None
  2984. while start >= 0:
  2985. # We want to skip over identifiers and commas to get to a symbol.
  2986. # Commas are skipped so that we can find the opening parenthesis
  2987. # for function parameter lists.
  2988. match_symbol = Match(r'^(.*)([^\w\s,])[\w\s,]*$', line)
  2989. if match_symbol:
  2990. break
  2991. start -= 1
  2992. line = clean_lines.elided[start]
  2993. if not match_symbol:
  2994. # Probably the first statement in the file is an rvalue reference
  2995. return True
  2996. if match_symbol.group(2) == '}':
  2997. # Found closing brace, probably an indicate of this:
  2998. # block{} type&&
  2999. return True
  3000. if match_symbol.group(2) == ';':
  3001. # Found semicolon, probably one of these:
  3002. # for(; expression &&
  3003. # statement; type&&
  3004. # Look for the previous 'for(' in the previous lines.
  3005. before_text = match_symbol.group(1)
  3006. for i in xrange(start - 1, max(start - 6, 0), -1):
  3007. before_text = clean_lines.elided[i] + before_text
  3008. if Search(r'for\s*\([^{};]*$', before_text):
  3009. # This is the condition inside a for-loop
  3010. return False
  3011. # Did not find a for-init-statement before this semicolon, so this
  3012. # is probably a new statement and not a condition.
  3013. return True
  3014. if match_symbol.group(2) == '{':
  3015. # Found opening brace, probably one of these:
  3016. # block{ type&& = ... ; }
  3017. # constructor{ expression && expression }
  3018. # Look for a closing brace or a semicolon. If we see a semicolon
  3019. # first, this is probably a rvalue reference.
  3020. line = clean_lines.elided[start][0:len(match_symbol.group(1)) + 1]
  3021. end = start
  3022. depth = 1
  3023. while True:
  3024. for ch in line:
  3025. if ch == ';':
  3026. return True
  3027. elif ch == '{':
  3028. depth += 1
  3029. elif ch == '}':
  3030. depth -= 1
  3031. if depth == 0:
  3032. return False
  3033. end += 1
  3034. if end >= clean_lines.NumLines():
  3035. break
  3036. line = clean_lines.elided[end]
  3037. # Incomplete program?
  3038. return False
  3039. if match_symbol.group(2) == '(':
  3040. # Opening parenthesis. Need to check what's to the left of the
  3041. # parenthesis. Look back one extra line for additional context.
  3042. before_text = match_symbol.group(1)
  3043. if linenum > 1:
  3044. before_text = clean_lines.elided[linenum - 1] + before_text
  3045. before_text = match_symbol.group(1)
  3046. # Patterns that are likely to be types:
  3047. # [](type&&
  3048. # for (type&&
  3049. # sizeof(type&&
  3050. # operator=(type&&
  3051. #
  3052. if Search(r'(?:\]|\bfor|\bsizeof|\boperator\s*\S+\s*)\s*$', before_text):
  3053. return True
  3054. # Patterns that are likely to be expressions:
  3055. # if (expression &&
  3056. # while (expression &&
  3057. # : initializer(expression &&
  3058. # , initializer(expression &&
  3059. # ( FunctionCall(expression &&
  3060. # + FunctionCall(expression &&
  3061. # + (expression &&
  3062. #
  3063. # The last '+' represents operators such as '+' and '-'.
  3064. if Search(r'(?:\bif|\bwhile|[-+=%^(<!?:,&*]\s*)$', before_text):
  3065. return False
  3066. # Something else. Check that tokens to the left look like
  3067. # return_type function_name
  3068. match_func = Match(r'^(.*\S.*)\s+\w(?:\w|::)*(?:<[^<>]*>)?\s*$',
  3069. match_symbol.group(1))
  3070. if match_func:
  3071. # Check for constructors, which don't have return types.
  3072. if Search(r'\b(?:explicit|inline)$', match_func.group(1)):
  3073. return True
  3074. implicit_constructor = Match(r'\s*(\w+)\((?:const\s+)?(\w+)', prefix)
  3075. if (implicit_constructor and
  3076. implicit_constructor.group(1) == implicit_constructor.group(2)):
  3077. return True
  3078. return IsRValueType(typenames, clean_lines, nesting_state, linenum,
  3079. len(match_func.group(1)))
  3080. # Nothing before the function name. If this is inside a block scope,
  3081. # this is probably a function call.
  3082. return not (nesting_state.previous_stack_top and
  3083. nesting_state.previous_stack_top.IsBlockInfo())
  3084. if match_symbol.group(2) == '>':
  3085. # Possibly a closing bracket, check that what's on the other side
  3086. # looks like the start of a template.
  3087. return IsTemplateParameterList(
  3088. clean_lines, start, len(match_symbol.group(1)))
  3089. # Some other symbol, usually something like "a=b&&c". This is most
  3090. # likely not a type.
  3091. return False
  3092. def IsDeletedOrDefault(clean_lines, linenum):
  3093. """Check if current constructor or operator is deleted or default.
  3094. Args:
  3095. clean_lines: A CleansedLines instance containing the file.
  3096. linenum: The number of the line to check.
  3097. Returns:
  3098. True if this is a deleted or default constructor.
  3099. """
  3100. open_paren = clean_lines.elided[linenum].find('(')
  3101. if open_paren < 0:
  3102. return False
  3103. (close_line, _, close_paren) = CloseExpression(
  3104. clean_lines, linenum, open_paren)
  3105. if close_paren < 0:
  3106. return False
  3107. return Match(r'\s*=\s*(?:delete|default)\b', close_line[close_paren:])
  3108. def IsRValueAllowed(clean_lines, linenum, typenames):
  3109. """Check if RValue reference is allowed on a particular line.
  3110. Args:
  3111. clean_lines: A CleansedLines instance containing the file.
  3112. linenum: The number of the line to check.
  3113. typenames: set of type names from template-argument-list.
  3114. Returns:
  3115. True if line is within the region where RValue references are allowed.
  3116. """
  3117. # Allow region marked by PUSH/POP macros
  3118. for i in xrange(linenum, 0, -1):
  3119. line = clean_lines.elided[i]
  3120. if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line):
  3121. if not line.endswith('PUSH'):
  3122. return False
  3123. for j in xrange(linenum, clean_lines.NumLines(), 1):
  3124. line = clean_lines.elided[j]
  3125. if Match(r'GOOGLE_ALLOW_RVALUE_REFERENCES_(?:PUSH|POP)', line):
  3126. return line.endswith('POP')
  3127. # Allow operator=
  3128. line = clean_lines.elided[linenum]
  3129. if Search(r'\boperator\s*=\s*\(', line):
  3130. return IsDeletedOrDefault(clean_lines, linenum)
  3131. # Allow constructors
  3132. match = Match(r'\s*(?:[\w<>]+::)*([\w<>]+)\s*::\s*([\w<>]+)\s*\(', line)
  3133. if match and match.group(1) == match.group(2):
  3134. return IsDeletedOrDefault(clean_lines, linenum)
  3135. if Search(r'\b(?:explicit|inline)\s+[\w<>]+\s*\(', line):
  3136. return IsDeletedOrDefault(clean_lines, linenum)
  3137. if Match(r'\s*[\w<>]+\s*\(', line):
  3138. previous_line = 'ReturnType'
  3139. if linenum > 0:
  3140. previous_line = clean_lines.elided[linenum - 1]
  3141. if Match(r'^\s*$', previous_line) or Search(r'[{}:;]\s*$', previous_line):
  3142. return IsDeletedOrDefault(clean_lines, linenum)
  3143. # Reject types not mentioned in template-argument-list
  3144. while line:
  3145. match = Match(r'^.*?(\w+)\s*&&(.*)$', line)
  3146. if not match:
  3147. break
  3148. if match.group(1) not in typenames:
  3149. return False
  3150. line = match.group(2)
  3151. # All RValue types that were in template-argument-list should have
  3152. # been removed by now. Those were allowed, assuming that they will
  3153. # be forwarded.
  3154. #
  3155. # If there are no remaining RValue types left (i.e. types that were
  3156. # not found in template-argument-list), flag those as not allowed.
  3157. return line.find('&&') < 0
  3158. def GetTemplateArgs(clean_lines, linenum):
  3159. """Find list of template arguments associated with this function declaration.
  3160. Args:
  3161. clean_lines: A CleansedLines instance containing the file.
  3162. linenum: Line number containing the start of the function declaration,
  3163. usually one line after the end of the template-argument-list.
  3164. Returns:
  3165. Set of type names, or empty set if this does not appear to have
  3166. any template parameters.
  3167. """
  3168. # Find start of function
  3169. func_line = linenum
  3170. while func_line > 0:
  3171. line = clean_lines.elided[func_line]
  3172. if Match(r'^\s*$', line):
  3173. return set()
  3174. if line.find('(') >= 0:
  3175. break
  3176. func_line -= 1
  3177. if func_line == 0:
  3178. return set()
  3179. # Collapse template-argument-list into a single string
  3180. argument_list = ''
  3181. match = Match(r'^(\s*template\s*)<', clean_lines.elided[func_line])
  3182. if match:
  3183. # template-argument-list on the same line as function name
  3184. start_col = len(match.group(1))
  3185. _, end_line, end_col = CloseExpression(clean_lines, func_line, start_col)
  3186. if end_col > -1 and end_line == func_line:
  3187. start_col += 1 # Skip the opening bracket
  3188. argument_list = clean_lines.elided[func_line][start_col:end_col]
  3189. elif func_line > 1:
  3190. # template-argument-list one line before function name
  3191. match = Match(r'^(.*)>\s*$', clean_lines.elided[func_line - 1])
  3192. if match:
  3193. end_col = len(match.group(1))
  3194. _, start_line, start_col = ReverseCloseExpression(
  3195. clean_lines, func_line - 1, end_col)
  3196. if start_col > -1:
  3197. start_col += 1 # Skip the opening bracket
  3198. while start_line < func_line - 1:
  3199. argument_list += clean_lines.elided[start_line][start_col:]
  3200. start_col = 0
  3201. start_line += 1
  3202. argument_list += clean_lines.elided[func_line - 1][start_col:end_col]
  3203. if not argument_list:
  3204. return set()
  3205. # Extract type names
  3206. typenames = set()
  3207. while True:
  3208. match = Match(r'^[,\s]*(?:typename|class)(?:\.\.\.)?\s+(\w+)(.*)$',
  3209. argument_list)
  3210. if not match:
  3211. break
  3212. typenames.add(match.group(1))
  3213. argument_list = match.group(2)
  3214. return typenames
  3215. def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error):
  3216. """Check for rvalue references.
  3217. Args:
  3218. filename: The name of the current file.
  3219. clean_lines: A CleansedLines instance containing the file.
  3220. linenum: The number of the line to check.
  3221. nesting_state: A NestingState instance which maintains information about
  3222. the current stack of nested blocks being parsed.
  3223. error: The function to call with any errors found.
  3224. """
  3225. # Find lines missing spaces around &&.
  3226. # TODO(unknown): currently we don't check for rvalue references
  3227. # with spaces surrounding the && to avoid false positives with
  3228. # boolean expressions.
  3229. line = clean_lines.elided[linenum]
  3230. match = Match(r'^(.*\S)&&', line)
  3231. if not match:
  3232. match = Match(r'(.*)&&\S', line)
  3233. if (not match) or '(&&)' in line or Search(r'\boperator\s*$', match.group(1)):
  3234. return
  3235. # Either poorly formed && or an rvalue reference, check the context
  3236. # to get a more accurate error message. Mostly we want to determine
  3237. # if what's to the left of "&&" is a type or not.
  3238. typenames = GetTemplateArgs(clean_lines, linenum)
  3239. and_pos = len(match.group(1))
  3240. if IsRValueType(typenames, clean_lines, nesting_state, linenum, and_pos):
  3241. if not IsRValueAllowed(clean_lines, linenum, typenames):
  3242. error(filename, linenum, 'build/c++11', 3,
  3243. 'RValue references are an unapproved C++ feature.')
  3244. else:
  3245. error(filename, linenum, 'whitespace/operators', 3,
  3246. 'Missing spaces around &&')
  3247. def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
  3248. """Checks for additional blank line issues related to sections.
  3249. Currently the only thing checked here is blank line before protected/private.
  3250. Args:
  3251. filename: The name of the current file.
  3252. clean_lines: A CleansedLines instance containing the file.
  3253. class_info: A _ClassInfo objects.
  3254. linenum: The number of the line to check.
  3255. error: The function to call with any errors found.
  3256. """
  3257. # Skip checks if the class is small, where small means 25 lines or less.
  3258. # 25 lines seems like a good cutoff since that's the usual height of
  3259. # terminals, and any class that can't fit in one screen can't really
  3260. # be considered "small".
  3261. #
  3262. # Also skip checks if we are on the first line. This accounts for
  3263. # classes that look like
  3264. # class Foo { public: ... };
  3265. #
  3266. # If we didn't find the end of the class, last_line would be zero,
  3267. # and the check will be skipped by the first condition.
  3268. if (class_info.last_line - class_info.starting_linenum <= 24 or
  3269. linenum <= class_info.starting_linenum):
  3270. return
  3271. matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
  3272. if matched:
  3273. # Issue warning if the line before public/protected/private was
  3274. # not a blank line, but don't do this if the previous line contains
  3275. # "class" or "struct". This can happen two ways:
  3276. # - We are at the beginning of the class.
  3277. # - We are forward-declaring an inner class that is semantically
  3278. # private, but needed to be public for implementation reasons.
  3279. # Also ignores cases where the previous line ends with a backslash as can be
  3280. # common when defining classes in C macros.
  3281. prev_line = clean_lines.lines[linenum - 1]
  3282. if (not IsBlankLine(prev_line) and
  3283. not Search(r'\b(class|struct)\b', prev_line) and
  3284. not Search(r'\\$', prev_line)):
  3285. # Try a bit harder to find the beginning of the class. This is to
  3286. # account for multi-line base-specifier lists, e.g.:
  3287. # class Derived
  3288. # : public Base {
  3289. end_class_head = class_info.starting_linenum
  3290. for i in range(class_info.starting_linenum, linenum):
  3291. if Search(r'\{\s*$', clean_lines.lines[i]):
  3292. end_class_head = i
  3293. break
  3294. if end_class_head < linenum - 1:
  3295. error(filename, linenum, 'whitespace/blank_line', 3,
  3296. '"%s:" should be preceded by a blank line' % matched.group(1))
  3297. def GetPreviousNonBlankLine(clean_lines, linenum):
  3298. """Return the most recent non-blank line and its line number.
  3299. Args:
  3300. clean_lines: A CleansedLines instance containing the file contents.
  3301. linenum: The number of the line to check.
  3302. Returns:
  3303. A tuple with two elements. The first element is the contents of the last
  3304. non-blank line before the current line, or the empty string if this is the
  3305. first non-blank line. The second is the line number of that line, or -1
  3306. if this is the first non-blank line.
  3307. """
  3308. prevlinenum = linenum - 1
  3309. while prevlinenum >= 0:
  3310. prevline = clean_lines.elided[prevlinenum]
  3311. if not IsBlankLine(prevline): # if not a blank line...
  3312. return (prevline, prevlinenum)
  3313. prevlinenum -= 1
  3314. return ('', -1)
  3315. def CheckBraces(filename, clean_lines, linenum, error):
  3316. """Looks for misplaced braces (e.g. at the end of line).
  3317. Args:
  3318. filename: The name of the current file.
  3319. clean_lines: A CleansedLines instance containing the file.
  3320. linenum: The number of the line to check.
  3321. error: The function to call with any errors found.
  3322. """
  3323. line = clean_lines.elided[linenum] # get rid of comments and strings
  3324. if Match(r'\s*{\s*$', line):
  3325. # We allow an open brace to start a line in the case where someone is using
  3326. # braces in a block to explicitly create a new scope, which is commonly used
  3327. # to control the lifetime of stack-allocated variables. Braces are also
  3328. # used for brace initializers inside function calls. We don't detect this
  3329. # perfectly: we just don't complain if the last non-whitespace character on
  3330. # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
  3331. # previous line starts a preprocessor block.
  3332. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  3333. if (not Search(r'[,;:}{(]\s*$', prevline) and
  3334. not Match(r'\s*#', prevline)):
  3335. error(filename, linenum, 'whitespace/braces', 4,
  3336. '{ should almost always be at the end of the previous line')
  3337. # An else clause should be on the same line as the preceding closing brace.
  3338. if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
  3339. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  3340. if Match(r'\s*}\s*$', prevline):
  3341. error(filename, linenum, 'whitespace/newline', 4,
  3342. 'An else should appear on the same line as the preceding }')
  3343. # If braces come on one side of an else, they should be on both.
  3344. # However, we have to worry about "else if" that spans multiple lines!
  3345. if Search(r'else if\s*\(', line): # could be multi-line if
  3346. brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
  3347. # find the ( after the if
  3348. pos = line.find('else if')
  3349. pos = line.find('(', pos)
  3350. if pos > 0:
  3351. (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
  3352. brace_on_right = endline[endpos:].find('{') != -1
  3353. if brace_on_left != brace_on_right: # must be brace after if
  3354. error(filename, linenum, 'readability/braces', 5,
  3355. 'If an else has a brace on one side, it should have it on both')
  3356. elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
  3357. error(filename, linenum, 'readability/braces', 5,
  3358. 'If an else has a brace on one side, it should have it on both')
  3359. # Likewise, an else should never have the else clause on the same line
  3360. if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
  3361. error(filename, linenum, 'whitespace/newline', 4,
  3362. 'Else clause should never be on same line as else (use 2 lines)')
  3363. # In the same way, a do/while should never be on one line
  3364. if Match(r'\s*do [^\s{]', line):
  3365. error(filename, linenum, 'whitespace/newline', 4,
  3366. 'do/while clauses should not be on a single line')
  3367. # Check single-line if/else bodies. The style guide says 'curly braces are not
  3368. # required for single-line statements'. We additionally allow multi-line,
  3369. # single statements, but we reject anything with more than one semicolon in
  3370. # it. This means that the first semicolon after the if should be at the end of
  3371. # its line, and the line after that should have an indent level equal to or
  3372. # lower than the if. We also check for ambiguous if/else nesting without
  3373. # braces.
  3374. if_else_match = Search(r'\b(if\s*\(|else\b)', line)
  3375. if if_else_match and not Match(r'\s*#', line):
  3376. if_indent = GetIndentLevel(line)
  3377. endline, endlinenum, endpos = line, linenum, if_else_match.end()
  3378. if_match = Search(r'\bif\s*\(', line)
  3379. if if_match:
  3380. # This could be a multiline if condition, so find the end first.
  3381. pos = if_match.end() - 1
  3382. (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
  3383. # Check for an opening brace, either directly after the if or on the next
  3384. # line. If found, this isn't a single-statement conditional.
  3385. if (not Match(r'\s*{', endline[endpos:])
  3386. and not (Match(r'\s*$', endline[endpos:])
  3387. and endlinenum < (len(clean_lines.elided) - 1)
  3388. and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
  3389. while (endlinenum < len(clean_lines.elided)
  3390. and ';' not in clean_lines.elided[endlinenum][endpos:]):
  3391. endlinenum += 1
  3392. endpos = 0
  3393. if endlinenum < len(clean_lines.elided):
  3394. endline = clean_lines.elided[endlinenum]
  3395. # We allow a mix of whitespace and closing braces (e.g. for one-liner
  3396. # methods) and a single \ after the semicolon (for macros)
  3397. endpos = endline.find(';')
  3398. if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
  3399. # Semicolon isn't the last character, there's something trailing.
  3400. # Output a warning if the semicolon is not contained inside
  3401. # a lambda expression.
  3402. if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
  3403. endline):
  3404. error(filename, linenum, 'readability/braces', 4,
  3405. 'If/else bodies with multiple statements require braces')
  3406. elif endlinenum < len(clean_lines.elided) - 1:
  3407. # Make sure the next line is dedented
  3408. next_line = clean_lines.elided[endlinenum + 1]
  3409. next_indent = GetIndentLevel(next_line)
  3410. # With ambiguous nested if statements, this will error out on the
  3411. # if that *doesn't* match the else, regardless of whether it's the
  3412. # inner one or outer one.
  3413. if (if_match and Match(r'\s*else\b', next_line)
  3414. and next_indent != if_indent):
  3415. error(filename, linenum, 'readability/braces', 4,
  3416. 'Else clause should be indented at the same level as if. '
  3417. 'Ambiguous nested if/else chains require braces.')
  3418. elif next_indent > if_indent:
  3419. error(filename, linenum, 'readability/braces', 4,
  3420. 'If/else bodies with multiple statements require braces')
  3421. def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
  3422. """Looks for redundant trailing semicolon.
  3423. Args:
  3424. filename: The name of the current file.
  3425. clean_lines: A CleansedLines instance containing the file.
  3426. linenum: The number of the line to check.
  3427. error: The function to call with any errors found.
  3428. """
  3429. line = clean_lines.elided[linenum]
  3430. # Block bodies should not be followed by a semicolon. Due to C++11
  3431. # brace initialization, there are more places where semicolons are
  3432. # required than not, so we use a whitelist approach to check these
  3433. # rather than a blacklist. These are the places where "};" should
  3434. # be replaced by just "}":
  3435. # 1. Some flavor of block following closing parenthesis:
  3436. # for (;;) {};
  3437. # while (...) {};
  3438. # switch (...) {};
  3439. # Function(...) {};
  3440. # if (...) {};
  3441. # if (...) else if (...) {};
  3442. #
  3443. # 2. else block:
  3444. # if (...) else {};
  3445. #
  3446. # 3. const member function:
  3447. # Function(...) const {};
  3448. #
  3449. # 4. Block following some statement:
  3450. # x = 42;
  3451. # {};
  3452. #
  3453. # 5. Block at the beginning of a function:
  3454. # Function(...) {
  3455. # {};
  3456. # }
  3457. #
  3458. # Note that naively checking for the preceding "{" will also match
  3459. # braces inside multi-dimensional arrays, but this is fine since
  3460. # that expression will not contain semicolons.
  3461. #
  3462. # 6. Block following another block:
  3463. # while (true) {}
  3464. # {};
  3465. #
  3466. # 7. End of namespaces:
  3467. # namespace {};
  3468. #
  3469. # These semicolons seems far more common than other kinds of
  3470. # redundant semicolons, possibly due to people converting classes
  3471. # to namespaces. For now we do not warn for this case.
  3472. #
  3473. # Try matching case 1 first.
  3474. match = Match(r'^(.*\)\s*)\{', line)
  3475. if match:
  3476. # Matched closing parenthesis (case 1). Check the token before the
  3477. # matching opening parenthesis, and don't warn if it looks like a
  3478. # macro. This avoids these false positives:
  3479. # - macro that defines a base class
  3480. # - multi-line macro that defines a base class
  3481. # - macro that defines the whole class-head
  3482. #
  3483. # But we still issue warnings for macros that we know are safe to
  3484. # warn, specifically:
  3485. # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
  3486. # - TYPED_TEST
  3487. # - INTERFACE_DEF
  3488. # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
  3489. #
  3490. # We implement a whitelist of safe macros instead of a blacklist of
  3491. # unsafe macros, even though the latter appears less frequently in
  3492. # google code and would have been easier to implement. This is because
  3493. # the downside for getting the whitelist wrong means some extra
  3494. # semicolons, while the downside for getting the blacklist wrong
  3495. # would result in compile errors.
  3496. #
  3497. # In addition to macros, we also don't want to warn on
  3498. # - Compound literals
  3499. # - Lambdas
  3500. # - alignas specifier with anonymous structs:
  3501. closing_brace_pos = match.group(1).rfind(')')
  3502. opening_parenthesis = ReverseCloseExpression(
  3503. clean_lines, linenum, closing_brace_pos)
  3504. if opening_parenthesis[2] > -1:
  3505. line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
  3506. macro = Search(r'\b([A-Z_]+)\s*$', line_prefix)
  3507. func = Match(r'^(.*\])\s*$', line_prefix)
  3508. if ((macro and
  3509. macro.group(1) not in (
  3510. 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
  3511. 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
  3512. 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
  3513. (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
  3514. Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
  3515. Search(r'\s+=\s*$', line_prefix)):
  3516. match = None
  3517. if (match and
  3518. opening_parenthesis[1] > 1 and
  3519. Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
  3520. # Multi-line lambda-expression
  3521. match = None
  3522. else:
  3523. # Try matching cases 2-3.
  3524. match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
  3525. if not match:
  3526. # Try matching cases 4-6. These are always matched on separate lines.
  3527. #
  3528. # Note that we can't simply concatenate the previous line to the
  3529. # current line and do a single match, otherwise we may output
  3530. # duplicate warnings for the blank line case:
  3531. # if (cond) {
  3532. # // blank line
  3533. # }
  3534. prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
  3535. if prevline and Search(r'[;{}]\s*$', prevline):
  3536. match = Match(r'^(\s*)\{', line)
  3537. # Check matching closing brace
  3538. if match:
  3539. (endline, endlinenum, endpos) = CloseExpression(
  3540. clean_lines, linenum, len(match.group(1)))
  3541. if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
  3542. # Current {} pair is eligible for semicolon check, and we have found
  3543. # the redundant semicolon, output warning here.
  3544. #
  3545. # Note: because we are scanning forward for opening braces, and
  3546. # outputting warnings for the matching closing brace, if there are
  3547. # nested blocks with trailing semicolons, we will get the error
  3548. # messages in reversed order.
  3549. error(filename, endlinenum, 'readability/braces', 4,
  3550. "You don't need a ; after a }")
  3551. def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
  3552. """Look for empty loop/conditional body with only a single semicolon.
  3553. Args:
  3554. filename: The name of the current file.
  3555. clean_lines: A CleansedLines instance containing the file.
  3556. linenum: The number of the line to check.
  3557. error: The function to call with any errors found.
  3558. """
  3559. # Search for loop keywords at the beginning of the line. Because only
  3560. # whitespaces are allowed before the keywords, this will also ignore most
  3561. # do-while-loops, since those lines should start with closing brace.
  3562. #
  3563. # We also check "if" blocks here, since an empty conditional block
  3564. # is likely an error.
  3565. line = clean_lines.elided[linenum]
  3566. matched = Match(r'\s*(for|while|if)\s*\(', line)
  3567. if matched:
  3568. # Find the end of the conditional expression
  3569. (end_line, end_linenum, end_pos) = CloseExpression(
  3570. clean_lines, linenum, line.find('('))
  3571. # Output warning if what follows the condition expression is a semicolon.
  3572. # No warning for all other cases, including whitespace or newline, since we
  3573. # have a separate check for semicolons preceded by whitespace.
  3574. if end_pos >= 0 and Match(r';', end_line[end_pos:]):
  3575. if matched.group(1) == 'if':
  3576. error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
  3577. 'Empty conditional bodies should use {}')
  3578. else:
  3579. error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
  3580. 'Empty loop bodies should use {} or continue')
  3581. def FindCheckMacro(line):
  3582. """Find a replaceable CHECK-like macro.
  3583. Args:
  3584. line: line to search on.
  3585. Returns:
  3586. (macro name, start position), or (None, -1) if no replaceable
  3587. macro is found.
  3588. """
  3589. for macro in _CHECK_MACROS:
  3590. i = line.find(macro)
  3591. if i >= 0:
  3592. # Find opening parenthesis. Do a regular expression match here
  3593. # to make sure that we are matching the expected CHECK macro, as
  3594. # opposed to some other macro that happens to contain the CHECK
  3595. # substring.
  3596. matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
  3597. if not matched:
  3598. continue
  3599. return (macro, len(matched.group(1)))
  3600. return (None, -1)
  3601. def CheckCheck(filename, clean_lines, linenum, error):
  3602. """Checks the use of CHECK and EXPECT macros.
  3603. Args:
  3604. filename: The name of the current file.
  3605. clean_lines: A CleansedLines instance containing the file.
  3606. linenum: The number of the line to check.
  3607. error: The function to call with any errors found.
  3608. """
  3609. # Decide the set of replacement macros that should be suggested
  3610. lines = clean_lines.elided
  3611. (check_macro, start_pos) = FindCheckMacro(lines[linenum])
  3612. if not check_macro:
  3613. return
  3614. # Find end of the boolean expression by matching parentheses
  3615. (last_line, end_line, end_pos) = CloseExpression(
  3616. clean_lines, linenum, start_pos)
  3617. if end_pos < 0:
  3618. return
  3619. # If the check macro is followed by something other than a
  3620. # semicolon, assume users will log their own custom error messages
  3621. # and don't suggest any replacements.
  3622. if not Match(r'\s*;', last_line[end_pos:]):
  3623. return
  3624. if linenum == end_line:
  3625. expression = lines[linenum][start_pos + 1:end_pos - 1]
  3626. else:
  3627. expression = lines[linenum][start_pos + 1:]
  3628. for i in xrange(linenum + 1, end_line):
  3629. expression += lines[i]
  3630. expression += last_line[0:end_pos - 1]
  3631. # Parse expression so that we can take parentheses into account.
  3632. # This avoids false positives for inputs like "CHECK((a < 4) == b)",
  3633. # which is not replaceable by CHECK_LE.
  3634. lhs = ''
  3635. rhs = ''
  3636. operator = None
  3637. while expression:
  3638. matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
  3639. r'==|!=|>=|>|<=|<|\()(.*)$', expression)
  3640. if matched:
  3641. token = matched.group(1)
  3642. if token == '(':
  3643. # Parenthesized operand
  3644. expression = matched.group(2)
  3645. (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
  3646. if end < 0:
  3647. return # Unmatched parenthesis
  3648. lhs += '(' + expression[0:end]
  3649. expression = expression[end:]
  3650. elif token in ('&&', '||'):
  3651. # Logical and/or operators. This means the expression
  3652. # contains more than one term, for example:
  3653. # CHECK(42 < a && a < b);
  3654. #
  3655. # These are not replaceable with CHECK_LE, so bail out early.
  3656. return
  3657. elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
  3658. # Non-relational operator
  3659. lhs += token
  3660. expression = matched.group(2)
  3661. else:
  3662. # Relational operator
  3663. operator = token
  3664. rhs = matched.group(2)
  3665. break
  3666. else:
  3667. # Unparenthesized operand. Instead of appending to lhs one character
  3668. # at a time, we do another regular expression match to consume several
  3669. # characters at once if possible. Trivial benchmark shows that this
  3670. # is more efficient when the operands are longer than a single
  3671. # character, which is generally the case.
  3672. matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
  3673. if not matched:
  3674. matched = Match(r'^(\s*\S)(.*)$', expression)
  3675. if not matched:
  3676. break
  3677. lhs += matched.group(1)
  3678. expression = matched.group(2)
  3679. # Only apply checks if we got all parts of the boolean expression
  3680. if not (lhs and operator and rhs):
  3681. return
  3682. # Check that rhs do not contain logical operators. We already know
  3683. # that lhs is fine since the loop above parses out && and ||.
  3684. if rhs.find('&&') > -1 or rhs.find('||') > -1:
  3685. return
  3686. # At least one of the operands must be a constant literal. This is
  3687. # to avoid suggesting replacements for unprintable things like
  3688. # CHECK(variable != iterator)
  3689. #
  3690. # The following pattern matches decimal, hex integers, strings, and
  3691. # characters (in that order).
  3692. lhs = lhs.strip()
  3693. rhs = rhs.strip()
  3694. match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
  3695. if Match(match_constant, lhs) or Match(match_constant, rhs):
  3696. # Note: since we know both lhs and rhs, we can provide a more
  3697. # descriptive error message like:
  3698. # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
  3699. # Instead of:
  3700. # Consider using CHECK_EQ instead of CHECK(a == b)
  3701. #
  3702. # We are still keeping the less descriptive message because if lhs
  3703. # or rhs gets long, the error message might become unreadable.
  3704. error(filename, linenum, 'readability/check', 2,
  3705. 'Consider using %s instead of %s(a %s b)' % (
  3706. _CHECK_REPLACEMENT[check_macro][operator],
  3707. check_macro, operator))
  3708. def CheckAltTokens(filename, clean_lines, linenum, error):
  3709. """Check alternative keywords being used in boolean expressions.
  3710. Args:
  3711. filename: The name of the current file.
  3712. clean_lines: A CleansedLines instance containing the file.
  3713. linenum: The number of the line to check.
  3714. error: The function to call with any errors found.
  3715. """
  3716. line = clean_lines.elided[linenum]
  3717. # Avoid preprocessor lines
  3718. if Match(r'^\s*#', line):
  3719. return
  3720. # Last ditch effort to avoid multi-line comments. This will not help
  3721. # if the comment started before the current line or ended after the
  3722. # current line, but it catches most of the false positives. At least,
  3723. # it provides a way to workaround this warning for people who use
  3724. # multi-line comments in preprocessor macros.
  3725. #
  3726. # TODO(unknown): remove this once cpplint has better support for
  3727. # multi-line comments.
  3728. if line.find('/*') >= 0 or line.find('*/') >= 0:
  3729. return
  3730. for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
  3731. error(filename, linenum, 'readability/alt_tokens', 2,
  3732. 'Use operator %s instead of %s' % (
  3733. _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
  3734. def GetLineWidth(line):
  3735. """Determines the width of the line in column positions.
  3736. Args:
  3737. line: A string, which may be a Unicode string.
  3738. Returns:
  3739. The width of the line in column positions, accounting for Unicode
  3740. combining characters and wide characters.
  3741. """
  3742. if isinstance(line, unicode):
  3743. width = 0
  3744. for uc in unicodedata.normalize('NFC', line):
  3745. if unicodedata.east_asian_width(uc) in ('W', 'F'):
  3746. width += 2
  3747. elif not unicodedata.combining(uc):
  3748. width += 1
  3749. return width
  3750. else:
  3751. return len(line)
  3752. def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
  3753. error):
  3754. """Checks rules from the 'C++ style rules' section of cppguide.html.
  3755. Most of these rules are hard to test (naming, comment style), but we
  3756. do what we can. In particular we check for 2-space indents, line lengths,
  3757. tab usage, spaces inside code, etc.
  3758. Args:
  3759. filename: The name of the current file.
  3760. clean_lines: A CleansedLines instance containing the file.
  3761. linenum: The number of the line to check.
  3762. file_extension: The extension (without the dot) of the filename.
  3763. nesting_state: A NestingState instance which maintains information about
  3764. the current stack of nested blocks being parsed.
  3765. error: The function to call with any errors found.
  3766. """
  3767. # Don't use "elided" lines here, otherwise we can't check commented lines.
  3768. # Don't want to use "raw" either, because we don't want to check inside C++11
  3769. # raw strings,
  3770. raw_lines = clean_lines.lines_without_raw_strings
  3771. line = raw_lines[linenum]
  3772. if line.find('\t') != -1:
  3773. error(filename, linenum, 'whitespace/tab', 1,
  3774. 'Tab found; better to use spaces')
  3775. # One or three blank spaces at the beginning of the line is weird; it's
  3776. # hard to reconcile that with 2-space indents.
  3777. # NOTE: here are the conditions rob pike used for his tests. Mine aren't
  3778. # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
  3779. # if(RLENGTH > 20) complain = 0;
  3780. # if(match($0, " +(error|private|public|protected):")) complain = 0;
  3781. # if(match(prev, "&& *$")) complain = 0;
  3782. # if(match(prev, "\\|\\| *$")) complain = 0;
  3783. # if(match(prev, "[\",=><] *$")) complain = 0;
  3784. # if(match($0, " <<")) complain = 0;
  3785. # if(match(prev, " +for \\(")) complain = 0;
  3786. # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
  3787. scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
  3788. classinfo = nesting_state.InnermostClass()
  3789. initial_spaces = 0
  3790. cleansed_line = clean_lines.elided[linenum]
  3791. while initial_spaces < len(line) and line[initial_spaces] == ' ':
  3792. initial_spaces += 1
  3793. if line and line[-1].isspace():
  3794. error(filename, linenum, 'whitespace/end_of_line', 4,
  3795. 'Line ends in whitespace. Consider deleting these extra spaces.')
  3796. # There are certain situations we allow one space, notably for
  3797. # section labels, and also lines containing multi-line raw strings.
  3798. elif ((initial_spaces == 1 or initial_spaces == 3) and
  3799. not Match(scope_or_label_pattern, cleansed_line) and
  3800. not (clean_lines.raw_lines[linenum] != line and
  3801. Match(r'^\s*""', line))):
  3802. error(filename, linenum, 'whitespace/indent', 3,
  3803. 'Weird number of spaces at line-start. '
  3804. 'Are you using a 2-space indent?')
  3805. # Check if the line is a header guard.
  3806. is_header_guard = False
  3807. if file_extension == 'h':
  3808. cppvar = GetHeaderGuardCPPVariable(filename)
  3809. if (line.startswith('#ifndef %s' % cppvar) or
  3810. line.startswith('#define %s' % cppvar) or
  3811. line.startswith('#endif // %s' % cppvar)):
  3812. is_header_guard = True
  3813. # #include lines and header guards can be long, since there's no clean way to
  3814. # split them.
  3815. #
  3816. # URLs can be long too. It's possible to split these, but it makes them
  3817. # harder to cut&paste.
  3818. #
  3819. # The "$Id:...$" comment may also get very long without it being the
  3820. # developers fault.
  3821. if (not line.startswith('#include') and not is_header_guard and
  3822. not Match(r'^\s*//.*http(s?)://\S*$', line) and
  3823. not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
  3824. line_width = GetLineWidth(line)
  3825. extended_length = int((_line_length * 1.25))
  3826. if line_width > extended_length:
  3827. error(filename, linenum, 'whitespace/line_length', 4,
  3828. 'Lines should very rarely be longer than %i characters' %
  3829. extended_length)
  3830. elif line_width > _line_length:
  3831. error(filename, linenum, 'whitespace/line_length', 2,
  3832. 'Lines should be <= %i characters long' % _line_length)
  3833. if (cleansed_line.count(';') > 1 and
  3834. # for loops are allowed two ;'s (and may run over two lines).
  3835. cleansed_line.find('for') == -1 and
  3836. (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
  3837. GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
  3838. # It's ok to have many commands in a switch case that fits in 1 line
  3839. not ((cleansed_line.find('case ') != -1 or
  3840. cleansed_line.find('default:') != -1) and
  3841. cleansed_line.find('break;') != -1)):
  3842. error(filename, linenum, 'whitespace/newline', 0,
  3843. 'More than one command on the same line')
  3844. # Some more style checks
  3845. CheckBraces(filename, clean_lines, linenum, error)
  3846. CheckTrailingSemicolon(filename, clean_lines, linenum, error)
  3847. CheckEmptyBlockBody(filename, clean_lines, linenum, error)
  3848. CheckAccess(filename, clean_lines, linenum, nesting_state, error)
  3849. CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
  3850. CheckOperatorSpacing(filename, clean_lines, linenum, error)
  3851. CheckParenthesisSpacing(filename, clean_lines, linenum, error)
  3852. CheckCommaSpacing(filename, clean_lines, linenum, error)
  3853. CheckBracesSpacing(filename, clean_lines, linenum, error)
  3854. CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
  3855. CheckRValueReference(filename, clean_lines, linenum, nesting_state, error)
  3856. CheckCheck(filename, clean_lines, linenum, error)
  3857. CheckAltTokens(filename, clean_lines, linenum, error)
  3858. classinfo = nesting_state.InnermostClass()
  3859. if classinfo:
  3860. CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
  3861. _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
  3862. # Matches the first component of a filename delimited by -s and _s. That is:
  3863. # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
  3864. # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
  3865. # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
  3866. # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
  3867. _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
  3868. def _DropCommonSuffixes(filename):
  3869. """Drops common suffixes like _test.cc or -inl.h from filename.
  3870. For example:
  3871. >>> _DropCommonSuffixes('foo/foo-inl.h')
  3872. 'foo/foo'
  3873. >>> _DropCommonSuffixes('foo/bar/foo.cc')
  3874. 'foo/bar/foo'
  3875. >>> _DropCommonSuffixes('foo/foo_internal.h')
  3876. 'foo/foo'
  3877. >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
  3878. 'foo/foo_unusualinternal'
  3879. Args:
  3880. filename: The input filename.
  3881. Returns:
  3882. The filename with the common suffix removed.
  3883. """
  3884. for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
  3885. 'inl.h', 'impl.h', 'internal.h'):
  3886. if (filename.endswith(suffix) and len(filename) > len(suffix) and
  3887. filename[-len(suffix) - 1] in ('-', '_')):
  3888. return filename[:-len(suffix) - 1]
  3889. return os.path.splitext(filename)[0]
  3890. def _IsTestFilename(filename):
  3891. """Determines if the given filename has a suffix that identifies it as a test.
  3892. Args:
  3893. filename: The input filename.
  3894. Returns:
  3895. True if 'filename' looks like a test, False otherwise.
  3896. """
  3897. if (filename.endswith('_test.cc') or
  3898. filename.endswith('_unittest.cc') or
  3899. filename.endswith('_regtest.cc')):
  3900. return True
  3901. else:
  3902. return False
  3903. def _ClassifyInclude(fileinfo, include, is_system):
  3904. """Figures out what kind of header 'include' is.
  3905. Args:
  3906. fileinfo: The current file cpplint is running over. A FileInfo instance.
  3907. include: The path to a #included file.
  3908. is_system: True if the #include used <> rather than "".
  3909. Returns:
  3910. One of the _XXX_HEADER constants.
  3911. For example:
  3912. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
  3913. _C_SYS_HEADER
  3914. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
  3915. _CPP_SYS_HEADER
  3916. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
  3917. _LIKELY_MY_HEADER
  3918. >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
  3919. ... 'bar/foo_other_ext.h', False)
  3920. _POSSIBLE_MY_HEADER
  3921. >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
  3922. _OTHER_HEADER
  3923. """
  3924. # This is a list of all standard c++ header files, except
  3925. # those already checked for above.
  3926. is_cpp_h = include in _CPP_HEADERS
  3927. if is_system:
  3928. if is_cpp_h:
  3929. return _CPP_SYS_HEADER
  3930. else:
  3931. return _C_SYS_HEADER
  3932. # If the target file and the include we're checking share a
  3933. # basename when we drop common extensions, and the include
  3934. # lives in . , then it's likely to be owned by the target file.
  3935. target_dir, target_base = (
  3936. os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
  3937. include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
  3938. if target_base == include_base and (
  3939. include_dir == target_dir or
  3940. include_dir == os.path.normpath(target_dir + '/../public')):
  3941. return _LIKELY_MY_HEADER
  3942. # If the target and include share some initial basename
  3943. # component, it's possible the target is implementing the
  3944. # include, so it's allowed to be first, but we'll never
  3945. # complain if it's not there.
  3946. target_first_component = _RE_FIRST_COMPONENT.match(target_base)
  3947. include_first_component = _RE_FIRST_COMPONENT.match(include_base)
  3948. if (target_first_component and include_first_component and
  3949. target_first_component.group(0) ==
  3950. include_first_component.group(0)):
  3951. return _POSSIBLE_MY_HEADER
  3952. return _OTHER_HEADER
  3953. def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
  3954. """Check rules that are applicable to #include lines.
  3955. Strings on #include lines are NOT removed from elided line, to make
  3956. certain tasks easier. However, to prevent false positives, checks
  3957. applicable to #include lines in CheckLanguage must be put here.
  3958. Args:
  3959. filename: The name of the current file.
  3960. clean_lines: A CleansedLines instance containing the file.
  3961. linenum: The number of the line to check.
  3962. include_state: An _IncludeState instance in which the headers are inserted.
  3963. error: The function to call with any errors found.
  3964. """
  3965. fileinfo = FileInfo(filename)
  3966. line = clean_lines.lines[linenum]
  3967. # "include" should use the new style "foo/bar.h" instead of just "bar.h"
  3968. # Only do this check if the included header follows google naming
  3969. # conventions. If not, assume that it's a 3rd party API that
  3970. # requires special include conventions.
  3971. #
  3972. # We also make an exception for Lua headers, which follow google
  3973. # naming convention but not the include convention.
  3974. match = Match(r'#include\s*"([^/]+\.h)"', line)
  3975. if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
  3976. error(filename, linenum, 'build/include', 4,
  3977. 'Include the directory when naming .h files')
  3978. # we shouldn't include a file more than once. actually, there are a
  3979. # handful of instances where doing so is okay, but in general it's
  3980. # not.
  3981. match = _RE_PATTERN_INCLUDE.search(line)
  3982. if match:
  3983. include = match.group(2)
  3984. is_system = (match.group(1) == '<')
  3985. duplicate_line = include_state.FindHeader(include)
  3986. if duplicate_line >= 0:
  3987. error(filename, linenum, 'build/include', 4,
  3988. '"%s" already included at %s:%s' %
  3989. (include, filename, duplicate_line))
  3990. elif (include.endswith('.cc') and
  3991. os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
  3992. error(filename, linenum, 'build/include', 4,
  3993. 'Do not include .cc files from other packages')
  3994. elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
  3995. include_state.include_list[-1].append((include, linenum))
  3996. # We want to ensure that headers appear in the right order:
  3997. # 1) for foo.cc, foo.h (preferred location)
  3998. # 2) c system files
  3999. # 3) cpp system files
  4000. # 4) for foo.cc, foo.h (deprecated location)
  4001. # 5) other google headers
  4002. #
  4003. # We classify each include statement as one of those 5 types
  4004. # using a number of techniques. The include_state object keeps
  4005. # track of the highest type seen, and complains if we see a
  4006. # lower type after that.
  4007. error_message = include_state.CheckNextIncludeOrder(
  4008. _ClassifyInclude(fileinfo, include, is_system))
  4009. if error_message:
  4010. error(filename, linenum, 'build/include_order', 4,
  4011. '%s. Should be: %s.h, c system, c++ system, other.' %
  4012. (error_message, fileinfo.BaseName()))
  4013. canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
  4014. if not include_state.IsInAlphabeticalOrder(
  4015. clean_lines, linenum, canonical_include):
  4016. error(filename, linenum, 'build/include_alpha', 4,
  4017. 'Include "%s" not in alphabetical order' % include)
  4018. include_state.SetLastHeader(canonical_include)
  4019. def _GetTextInside(text, start_pattern):
  4020. r"""Retrieves all the text between matching open and close parentheses.
  4021. Given a string of lines and a regular expression string, retrieve all the text
  4022. following the expression and between opening punctuation symbols like
  4023. (, [, or {, and the matching close-punctuation symbol. This properly nested
  4024. occurrences of the punctuations, so for the text like
  4025. printf(a(), b(c()));
  4026. a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
  4027. start_pattern must match string having an open punctuation symbol at the end.
  4028. Args:
  4029. text: The lines to extract text. Its comments and strings must be elided.
  4030. It can be single line and can span multiple lines.
  4031. start_pattern: The regexp string indicating where to start extracting
  4032. the text.
  4033. Returns:
  4034. The extracted text.
  4035. None if either the opening string or ending punctuation could not be found.
  4036. """
  4037. # TODO(unknown): Audit cpplint.py to see what places could be profitably
  4038. # rewritten to use _GetTextInside (and use inferior regexp matching today).
  4039. # Give opening punctuations to get the matching close-punctuations.
  4040. matching_punctuation = {'(': ')', '{': '}', '[': ']'}
  4041. closing_punctuation = set(matching_punctuation.itervalues())
  4042. # Find the position to start extracting text.
  4043. match = re.search(start_pattern, text, re.M)
  4044. if not match: # start_pattern not found in text.
  4045. return None
  4046. start_position = match.end(0)
  4047. assert start_position > 0, (
  4048. 'start_pattern must ends with an opening punctuation.')
  4049. assert text[start_position - 1] in matching_punctuation, (
  4050. 'start_pattern must ends with an opening punctuation.')
  4051. # Stack of closing punctuations we expect to have in text after position.
  4052. punctuation_stack = [matching_punctuation[text[start_position - 1]]]
  4053. position = start_position
  4054. while punctuation_stack and position < len(text):
  4055. if text[position] == punctuation_stack[-1]:
  4056. punctuation_stack.pop()
  4057. elif text[position] in closing_punctuation:
  4058. # A closing punctuation without matching opening punctuations.
  4059. return None
  4060. elif text[position] in matching_punctuation:
  4061. punctuation_stack.append(matching_punctuation[text[position]])
  4062. position += 1
  4063. if punctuation_stack:
  4064. # Opening punctuations left without matching close-punctuations.
  4065. return None
  4066. # punctuations match.
  4067. return text[start_position:position - 1]
  4068. # Patterns for matching call-by-reference parameters.
  4069. #
  4070. # Supports nested templates up to 2 levels deep using this messy pattern:
  4071. # < (?: < (?: < [^<>]*
  4072. # >
  4073. # | [^<>] )*
  4074. # >
  4075. # | [^<>] )*
  4076. # >
  4077. _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
  4078. _RE_PATTERN_TYPE = (
  4079. r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
  4080. r'(?:\w|'
  4081. r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
  4082. r'::)+')
  4083. # A call-by-reference parameter ends with '& identifier'.
  4084. _RE_PATTERN_REF_PARAM = re.compile(
  4085. r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
  4086. r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
  4087. # A call-by-const-reference parameter either ends with 'const& identifier'
  4088. # or looks like 'const type& identifier' when 'type' is atomic.
  4089. _RE_PATTERN_CONST_REF_PARAM = (
  4090. r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
  4091. r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
  4092. def CheckLanguage(filename, clean_lines, linenum, file_extension,
  4093. include_state, nesting_state, error):
  4094. """Checks rules from the 'C++ language rules' section of cppguide.html.
  4095. Some of these rules are hard to test (function overloading, using
  4096. uint32 inappropriately), but we do the best we can.
  4097. Args:
  4098. filename: The name of the current file.
  4099. clean_lines: A CleansedLines instance containing the file.
  4100. linenum: The number of the line to check.
  4101. file_extension: The extension (without the dot) of the filename.
  4102. include_state: An _IncludeState instance in which the headers are inserted.
  4103. nesting_state: A NestingState instance which maintains information about
  4104. the current stack of nested blocks being parsed.
  4105. error: The function to call with any errors found.
  4106. """
  4107. # If the line is empty or consists of entirely a comment, no need to
  4108. # check it.
  4109. line = clean_lines.elided[linenum]
  4110. if not line:
  4111. return
  4112. match = _RE_PATTERN_INCLUDE.search(line)
  4113. if match:
  4114. CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
  4115. return
  4116. # Reset include state across preprocessor directives. This is meant
  4117. # to silence warnings for conditional includes.
  4118. match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
  4119. if match:
  4120. include_state.ResetSection(match.group(1))
  4121. # Make Windows paths like Unix.
  4122. fullname = os.path.abspath(filename).replace('\\', '/')
  4123. # Perform other checks now that we are sure that this is not an include line
  4124. CheckCasts(filename, clean_lines, linenum, error)
  4125. CheckGlobalStatic(filename, clean_lines, linenum, error)
  4126. CheckPrintf(filename, clean_lines, linenum, error)
  4127. if file_extension == 'h':
  4128. # TODO(unknown): check that 1-arg constructors are explicit.
  4129. # How to tell it's a constructor?
  4130. # (handled in CheckForNonStandardConstructs for now)
  4131. # TODO(unknown): check that classes declare or disable copy/assign
  4132. # (level 1 error)
  4133. pass
  4134. # Check if people are using the verboten C basic types. The only exception
  4135. # we regularly allow is "unsigned short port" for port.
  4136. if Search(r'\bshort port\b', line):
  4137. if not Search(r'\bunsigned short port\b', line):
  4138. error(filename, linenum, 'runtime/int', 4,
  4139. 'Use "unsigned short" for ports, not "short"')
  4140. else:
  4141. match = Search(r'\b(short|long(?! +double)|long long)\b', line)
  4142. if match:
  4143. error(filename, linenum, 'runtime/int', 4,
  4144. 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
  4145. # Check if some verboten operator overloading is going on
  4146. # TODO(unknown): catch out-of-line unary operator&:
  4147. # class X {};
  4148. # int operator&(const X& x) { return 42; } // unary operator&
  4149. # The trick is it's hard to tell apart from binary operator&:
  4150. # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
  4151. if Search(r'\boperator\s*&\s*\(\s*\)', line):
  4152. error(filename, linenum, 'runtime/operator', 4,
  4153. 'Unary operator& is dangerous. Do not use it.')
  4154. # Check for suspicious usage of "if" like
  4155. # } if (a == b) {
  4156. if Search(r'\}\s*if\s*\(', line):
  4157. error(filename, linenum, 'readability/braces', 4,
  4158. 'Did you mean "else if"? If not, start a new line for "if".')
  4159. # Check for potential format string bugs like printf(foo).
  4160. # We constrain the pattern not to pick things like DocidForPrintf(foo).
  4161. # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
  4162. # TODO(unknown): Catch the following case. Need to change the calling
  4163. # convention of the whole function to process multiple line to handle it.
  4164. # printf(
  4165. # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
  4166. printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
  4167. if printf_args:
  4168. match = Match(r'([\w.\->()]+)$', printf_args)
  4169. if match and match.group(1) != '__VA_ARGS__':
  4170. function_name = re.search(r'\b((?:string)?printf)\s*\(',
  4171. line, re.I).group(1)
  4172. error(filename, linenum, 'runtime/printf', 4,
  4173. 'Potential format string bug. Do %s("%%s", %s) instead.'
  4174. % (function_name, match.group(1)))
  4175. # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
  4176. match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
  4177. if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
  4178. error(filename, linenum, 'runtime/memset', 4,
  4179. 'Did you mean "memset(%s, 0, %s)"?'
  4180. % (match.group(1), match.group(2)))
  4181. if Search(r'\busing namespace\b', line):
  4182. error(filename, linenum, 'build/namespaces', 5,
  4183. 'Do not use namespace using-directives. '
  4184. 'Use using-declarations instead.')
  4185. # Detect variable-length arrays.
  4186. match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
  4187. if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
  4188. match.group(3).find(']') == -1):
  4189. # Split the size using space and arithmetic operators as delimiters.
  4190. # If any of the resulting tokens are not compile time constants then
  4191. # report the error.
  4192. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
  4193. is_const = True
  4194. skip_next = False
  4195. for tok in tokens:
  4196. if skip_next:
  4197. skip_next = False
  4198. continue
  4199. if Search(r'sizeof\(.+\)', tok): continue
  4200. if Search(r'arraysize\(\w+\)', tok): continue
  4201. tok = tok.lstrip('(')
  4202. tok = tok.rstrip(')')
  4203. if not tok: continue
  4204. if Match(r'\d+', tok): continue
  4205. if Match(r'0[xX][0-9a-fA-F]+', tok): continue
  4206. if Match(r'k[A-Z0-9]\w*', tok): continue
  4207. if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
  4208. if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
  4209. # A catch all for tricky sizeof cases, including 'sizeof expression',
  4210. # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
  4211. # requires skipping the next token because we split on ' ' and '*'.
  4212. if tok.startswith('sizeof'):
  4213. skip_next = True
  4214. continue
  4215. is_const = False
  4216. break
  4217. if not is_const:
  4218. error(filename, linenum, 'runtime/arrays', 1,
  4219. 'Do not use variable-length arrays. Use an appropriately named '
  4220. "('k' followed by CamelCase) compile-time constant for the size.")
  4221. # Check for use of unnamed namespaces in header files. Registration
  4222. # macros are typically OK, so we allow use of "namespace {" on lines
  4223. # that end with backslashes.
  4224. if (file_extension == 'h'
  4225. and Search(r'\bnamespace\s*{', line)
  4226. and line[-1] != '\\'):
  4227. error(filename, linenum, 'build/namespaces', 4,
  4228. 'Do not use unnamed namespaces in header files. See '
  4229. 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
  4230. ' for more information.')
  4231. def CheckGlobalStatic(filename, clean_lines, linenum, error):
  4232. """Check for unsafe global or static objects.
  4233. Args:
  4234. filename: The name of the current file.
  4235. clean_lines: A CleansedLines instance containing the file.
  4236. linenum: The number of the line to check.
  4237. error: The function to call with any errors found.
  4238. """
  4239. line = clean_lines.elided[linenum]
  4240. # Match two lines at a time to support multiline declarations
  4241. if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
  4242. line += clean_lines.elided[linenum + 1].strip()
  4243. # Check for people declaring static/global STL strings at the top level.
  4244. # This is dangerous because the C++ language does not guarantee that
  4245. # globals with constructors are initialized before the first access.
  4246. match = Match(
  4247. r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
  4248. line)
  4249. # Remove false positives:
  4250. # - String pointers (as opposed to values).
  4251. # string *pointer
  4252. # const string *pointer
  4253. # string const *pointer
  4254. # string *const pointer
  4255. #
  4256. # - Functions and template specializations.
  4257. # string Function<Type>(...
  4258. # string Class<Type>::Method(...
  4259. #
  4260. # - Operators. These are matched separately because operator names
  4261. # cross non-word boundaries, and trying to match both operators
  4262. # and functions at the same time would decrease accuracy of
  4263. # matching identifiers.
  4264. # string Class::operator*()
  4265. if (match and
  4266. not Search(r'\bstring\b(\s+const)?\s*\*\s*(const\s+)?\w', line) and
  4267. not Search(r'\boperator\W', line) and
  4268. not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(3))):
  4269. error(filename, linenum, 'runtime/string', 4,
  4270. 'For a static/global string constant, use a C style string instead: '
  4271. '"%schar %s[]".' %
  4272. (match.group(1), match.group(2)))
  4273. if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
  4274. error(filename, linenum, 'runtime/init', 4,
  4275. 'You seem to be initializing a member variable with itself.')
  4276. def CheckPrintf(filename, clean_lines, linenum, error):
  4277. """Check for printf related issues.
  4278. Args:
  4279. filename: The name of the current file.
  4280. clean_lines: A CleansedLines instance containing the file.
  4281. linenum: The number of the line to check.
  4282. error: The function to call with any errors found.
  4283. """
  4284. line = clean_lines.elided[linenum]
  4285. # When snprintf is used, the second argument shouldn't be a literal.
  4286. match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
  4287. if match and match.group(2) != '0':
  4288. # If 2nd arg is zero, snprintf is used to calculate size.
  4289. error(filename, linenum, 'runtime/printf', 3,
  4290. 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
  4291. 'to snprintf.' % (match.group(1), match.group(2)))
  4292. # Check if some verboten C functions are being used.
  4293. if Search(r'\bsprintf\s*\(', line):
  4294. error(filename, linenum, 'runtime/printf', 5,
  4295. 'Never use sprintf. Use snprintf instead.')
  4296. match = Search(r'\b(strcpy|strcat)\s*\(', line)
  4297. if match:
  4298. error(filename, linenum, 'runtime/printf', 4,
  4299. 'Almost always, snprintf is better than %s' % match.group(1))
  4300. def IsDerivedFunction(clean_lines, linenum):
  4301. """Check if current line contains an inherited function.
  4302. Args:
  4303. clean_lines: A CleansedLines instance containing the file.
  4304. linenum: The number of the line to check.
  4305. Returns:
  4306. True if current line contains a function with "override"
  4307. virt-specifier.
  4308. """
  4309. # Scan back a few lines for start of current function
  4310. for i in xrange(linenum, max(-1, linenum - 10), -1):
  4311. match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
  4312. if match:
  4313. # Look for "override" after the matching closing parenthesis
  4314. line, _, closing_paren = CloseExpression(
  4315. clean_lines, i, len(match.group(1)))
  4316. return (closing_paren >= 0 and
  4317. Search(r'\boverride\b', line[closing_paren:]))
  4318. return False
  4319. def IsOutOfLineMethodDefinition(clean_lines, linenum):
  4320. """Check if current line contains an out-of-line method definition.
  4321. Args:
  4322. clean_lines: A CleansedLines instance containing the file.
  4323. linenum: The number of the line to check.
  4324. Returns:
  4325. True if current line contains an out-of-line method definition.
  4326. """
  4327. # Scan back a few lines for start of current function
  4328. for i in xrange(linenum, max(-1, linenum - 10), -1):
  4329. if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
  4330. return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
  4331. return False
  4332. def IsInitializerList(clean_lines, linenum):
  4333. """Check if current line is inside constructor initializer list.
  4334. Args:
  4335. clean_lines: A CleansedLines instance containing the file.
  4336. linenum: The number of the line to check.
  4337. Returns:
  4338. True if current line appears to be inside constructor initializer
  4339. list, False otherwise.
  4340. """
  4341. for i in xrange(linenum, 1, -1):
  4342. line = clean_lines.elided[i]
  4343. if i == linenum:
  4344. remove_function_body = Match(r'^(.*)\{\s*$', line)
  4345. if remove_function_body:
  4346. line = remove_function_body.group(1)
  4347. if Search(r'\s:\s*\w+[({]', line):
  4348. # A lone colon tend to indicate the start of a constructor
  4349. # initializer list. It could also be a ternary operator, which
  4350. # also tend to appear in constructor initializer lists as
  4351. # opposed to parameter lists.
  4352. return True
  4353. if Search(r'\}\s*,\s*$', line):
  4354. # A closing brace followed by a comma is probably the end of a
  4355. # brace-initialized member in constructor initializer list.
  4356. return True
  4357. if Search(r'[{};]\s*$', line):
  4358. # Found one of the following:
  4359. # - A closing brace or semicolon, probably the end of the previous
  4360. # function.
  4361. # - An opening brace, probably the start of current class or namespace.
  4362. #
  4363. # Current line is probably not inside an initializer list since
  4364. # we saw one of those things without seeing the starting colon.
  4365. return False
  4366. # Got to the beginning of the file without seeing the start of
  4367. # constructor initializer list.
  4368. return False
  4369. def CheckForNonConstReference(filename, clean_lines, linenum,
  4370. nesting_state, error):
  4371. """Check for non-const references.
  4372. Separate from CheckLanguage since it scans backwards from current
  4373. line, instead of scanning forward.
  4374. Args:
  4375. filename: The name of the current file.
  4376. clean_lines: A CleansedLines instance containing the file.
  4377. linenum: The number of the line to check.
  4378. nesting_state: A NestingState instance which maintains information about
  4379. the current stack of nested blocks being parsed.
  4380. error: The function to call with any errors found.
  4381. """
  4382. # Do nothing if there is no '&' on current line.
  4383. line = clean_lines.elided[linenum]
  4384. if '&' not in line:
  4385. return
  4386. # If a function is inherited, current function doesn't have much of
  4387. # a choice, so any non-const references should not be blamed on
  4388. # derived function.
  4389. if IsDerivedFunction(clean_lines, linenum):
  4390. return
  4391. # Don't warn on out-of-line method definitions, as we would warn on the
  4392. # in-line declaration, if it isn't marked with 'override'.
  4393. if IsOutOfLineMethodDefinition(clean_lines, linenum):
  4394. return
  4395. # Long type names may be broken across multiple lines, usually in one
  4396. # of these forms:
  4397. # LongType
  4398. # ::LongTypeContinued &identifier
  4399. # LongType::
  4400. # LongTypeContinued &identifier
  4401. # LongType<
  4402. # ...>::LongTypeContinued &identifier
  4403. #
  4404. # If we detected a type split across two lines, join the previous
  4405. # line to current line so that we can match const references
  4406. # accordingly.
  4407. #
  4408. # Note that this only scans back one line, since scanning back
  4409. # arbitrary number of lines would be expensive. If you have a type
  4410. # that spans more than 2 lines, please use a typedef.
  4411. if linenum > 1:
  4412. previous = None
  4413. if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
  4414. # previous_line\n + ::current_line
  4415. previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
  4416. clean_lines.elided[linenum - 1])
  4417. elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
  4418. # previous_line::\n + current_line
  4419. previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
  4420. clean_lines.elided[linenum - 1])
  4421. if previous:
  4422. line = previous.group(1) + line.lstrip()
  4423. else:
  4424. # Check for templated parameter that is split across multiple lines
  4425. endpos = line.rfind('>')
  4426. if endpos > -1:
  4427. (_, startline, startpos) = ReverseCloseExpression(
  4428. clean_lines, linenum, endpos)
  4429. if startpos > -1 and startline < linenum:
  4430. # Found the matching < on an earlier line, collect all
  4431. # pieces up to current line.
  4432. line = ''
  4433. for i in xrange(startline, linenum + 1):
  4434. line += clean_lines.elided[i].strip()
  4435. # Check for non-const references in function parameters. A single '&' may
  4436. # found in the following places:
  4437. # inside expression: binary & for bitwise AND
  4438. # inside expression: unary & for taking the address of something
  4439. # inside declarators: reference parameter
  4440. # We will exclude the first two cases by checking that we are not inside a
  4441. # function body, including one that was just introduced by a trailing '{'.
  4442. # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
  4443. if (nesting_state.previous_stack_top and
  4444. not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
  4445. isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
  4446. # Not at toplevel, not within a class, and not within a namespace
  4447. return
  4448. # Avoid initializer lists. We only need to scan back from the
  4449. # current line for something that starts with ':'.
  4450. #
  4451. # We don't need to check the current line, since the '&' would
  4452. # appear inside the second set of parentheses on the current line as
  4453. # opposed to the first set.
  4454. if linenum > 0:
  4455. for i in xrange(linenum - 1, max(0, linenum - 10), -1):
  4456. previous_line = clean_lines.elided[i]
  4457. if not Search(r'[),]\s*$', previous_line):
  4458. break
  4459. if Match(r'^\s*:\s+\S', previous_line):
  4460. return
  4461. # Avoid preprocessors
  4462. if Search(r'\\\s*$', line):
  4463. return
  4464. # Avoid constructor initializer lists
  4465. if IsInitializerList(clean_lines, linenum):
  4466. return
  4467. # We allow non-const references in a few standard places, like functions
  4468. # called "swap()" or iostream operators like "<<" or ">>". Do not check
  4469. # those function parameters.
  4470. #
  4471. # We also accept & in static_assert, which looks like a function but
  4472. # it's actually a declaration expression.
  4473. whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
  4474. r'operator\s*[<>][<>]|'
  4475. r'static_assert|COMPILE_ASSERT'
  4476. r')\s*\(')
  4477. if Search(whitelisted_functions, line):
  4478. return
  4479. elif not Search(r'\S+\([^)]*$', line):
  4480. # Don't see a whitelisted function on this line. Actually we
  4481. # didn't see any function name on this line, so this is likely a
  4482. # multi-line parameter list. Try a bit harder to catch this case.
  4483. for i in xrange(2):
  4484. if (linenum > i and
  4485. Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
  4486. return
  4487. decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
  4488. for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
  4489. if not Match(_RE_PATTERN_CONST_REF_PARAM, parameter):
  4490. error(filename, linenum, 'runtime/references', 2,
  4491. 'Is this a non-const reference? '
  4492. 'If so, make const or use a pointer: ' +
  4493. ReplaceAll(' *<', '<', parameter))
  4494. def CheckCasts(filename, clean_lines, linenum, error):
  4495. """Various cast related checks.
  4496. Args:
  4497. filename: The name of the current file.
  4498. clean_lines: A CleansedLines instance containing the file.
  4499. linenum: The number of the line to check.
  4500. error: The function to call with any errors found.
  4501. """
  4502. line = clean_lines.elided[linenum]
  4503. # Check to see if they're using an conversion function cast.
  4504. # I just try to capture the most common basic types, though there are more.
  4505. # Parameterless conversion functions, such as bool(), are allowed as they are
  4506. # probably a member operator declaration or default constructor.
  4507. match = Search(
  4508. r'(\bnew\s+|\S<\s*(?:const\s+)?)?\b'
  4509. r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
  4510. r'(\([^)].*)', line)
  4511. expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
  4512. if match and not expecting_function:
  4513. matched_type = match.group(2)
  4514. # matched_new_or_template is used to silence two false positives:
  4515. # - New operators
  4516. # - Template arguments with function types
  4517. #
  4518. # For template arguments, we match on types immediately following
  4519. # an opening bracket without any spaces. This is a fast way to
  4520. # silence the common case where the function type is the first
  4521. # template argument. False negative with less-than comparison is
  4522. # avoided because those operators are usually followed by a space.
  4523. #
  4524. # function<double(double)> // bracket + no space = false positive
  4525. # value < double(42) // bracket + space = true positive
  4526. matched_new_or_template = match.group(1)
  4527. # Avoid arrays by looking for brackets that come after the closing
  4528. # parenthesis.
  4529. if Match(r'\([^()]+\)\s*\[', match.group(3)):
  4530. return
  4531. # Other things to ignore:
  4532. # - Function pointers
  4533. # - Casts to pointer types
  4534. # - Placement new
  4535. # - Alias declarations
  4536. matched_funcptr = match.group(3)
  4537. if (matched_new_or_template is None and
  4538. not (matched_funcptr and
  4539. (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
  4540. matched_funcptr) or
  4541. matched_funcptr.startswith('(*)'))) and
  4542. not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
  4543. not Search(r'new\(\S+\)\s*' + matched_type, line)):
  4544. error(filename, linenum, 'readability/casting', 4,
  4545. 'Using deprecated casting style. '
  4546. 'Use static_cast<%s>(...) instead' %
  4547. matched_type)
  4548. if not expecting_function:
  4549. CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
  4550. r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
  4551. # This doesn't catch all cases. Consider (const char * const)"hello".
  4552. #
  4553. # (char *) "foo" should always be a const_cast (reinterpret_cast won't
  4554. # compile).
  4555. if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
  4556. r'\((char\s?\*+\s?)\)\s*"', error):
  4557. pass
  4558. else:
  4559. # Check pointer casts for other than string constants
  4560. CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
  4561. r'\((\w+\s?\*+\s?)\)', error)
  4562. # In addition, we look for people taking the address of a cast. This
  4563. # is dangerous -- casts can assign to temporaries, so the pointer doesn't
  4564. # point where you think.
  4565. #
  4566. # Some non-identifier character is required before the '&' for the
  4567. # expression to be recognized as a cast. These are casts:
  4568. # expression = &static_cast<int*>(temporary());
  4569. # function(&(int*)(temporary()));
  4570. #
  4571. # This is not a cast:
  4572. # reference_type&(int* function_param);
  4573. match = Search(
  4574. r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
  4575. r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
  4576. if match:
  4577. # Try a better error message when the & is bound to something
  4578. # dereferenced by the casted pointer, as opposed to the casted
  4579. # pointer itself.
  4580. parenthesis_error = False
  4581. match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
  4582. if match:
  4583. _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
  4584. if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
  4585. _, y2, x2 = CloseExpression(clean_lines, y1, x1)
  4586. if x2 >= 0:
  4587. extended_line = clean_lines.elided[y2][x2:]
  4588. if y2 < clean_lines.NumLines() - 1:
  4589. extended_line += clean_lines.elided[y2 + 1]
  4590. if Match(r'\s*(?:->|\[)', extended_line):
  4591. parenthesis_error = True
  4592. if parenthesis_error:
  4593. error(filename, linenum, 'readability/casting', 4,
  4594. ('Are you taking an address of something dereferenced '
  4595. 'from a cast? Wrapping the dereferenced expression in '
  4596. 'parentheses will make the binding more obvious'))
  4597. else:
  4598. error(filename, linenum, 'runtime/casting', 4,
  4599. ('Are you taking an address of a cast? '
  4600. 'This is dangerous: could be a temp var. '
  4601. 'Take the address before doing the cast, rather than after'))
  4602. def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
  4603. """Checks for a C-style cast by looking for the pattern.
  4604. Args:
  4605. filename: The name of the current file.
  4606. clean_lines: A CleansedLines instance containing the file.
  4607. linenum: The number of the line to check.
  4608. cast_type: The string for the C++ cast to recommend. This is either
  4609. reinterpret_cast, static_cast, or const_cast, depending.
  4610. pattern: The regular expression used to find C-style casts.
  4611. error: The function to call with any errors found.
  4612. Returns:
  4613. True if an error was emitted.
  4614. False otherwise.
  4615. """
  4616. line = clean_lines.elided[linenum]
  4617. match = Search(pattern, line)
  4618. if not match:
  4619. return False
  4620. # Exclude lines with keywords that tend to look like casts
  4621. context = line[0:match.start(1) - 1]
  4622. if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
  4623. return False
  4624. # Try expanding current context to see if we one level of
  4625. # parentheses inside a macro.
  4626. if linenum > 0:
  4627. for i in xrange(linenum - 1, max(0, linenum - 5), -1):
  4628. context = clean_lines.elided[i] + context
  4629. if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
  4630. return False
  4631. # operator++(int) and operator--(int)
  4632. if context.endswith(' operator++') or context.endswith(' operator--'):
  4633. return False
  4634. # A single unnamed argument for a function tends to look like old
  4635. # style cast. If we see those, don't issue warnings for deprecated
  4636. # casts, instead issue warnings for unnamed arguments where
  4637. # appropriate.
  4638. #
  4639. # These are things that we want warnings for, since the style guide
  4640. # explicitly require all parameters to be named:
  4641. # Function(int);
  4642. # Function(int) {
  4643. # ConstMember(int) const;
  4644. # ConstMember(int) const {
  4645. # ExceptionMember(int) throw (...);
  4646. # ExceptionMember(int) throw (...) {
  4647. # PureVirtual(int) = 0;
  4648. # [](int) -> bool {
  4649. #
  4650. # These are functions of some sort, where the compiler would be fine
  4651. # if they had named parameters, but people often omit those
  4652. # identifiers to reduce clutter:
  4653. # (FunctionPointer)(int);
  4654. # (FunctionPointer)(int) = value;
  4655. # Function((function_pointer_arg)(int))
  4656. # Function((function_pointer_arg)(int), int param)
  4657. # <TemplateArgument(int)>;
  4658. # <(FunctionPointerTemplateArgument)(int)>;
  4659. remainder = line[match.end(0):]
  4660. if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
  4661. remainder):
  4662. # Looks like an unnamed parameter.
  4663. # Don't warn on any kind of template arguments.
  4664. if Match(r'^\s*>', remainder):
  4665. return False
  4666. # Don't warn on assignments to function pointers, but keep warnings for
  4667. # unnamed parameters to pure virtual functions. Note that this pattern
  4668. # will also pass on assignments of "0" to function pointers, but the
  4669. # preferred values for those would be "nullptr" or "NULL".
  4670. matched_zero = Match(r'^\s=\s*(\S+)\s*;', remainder)
  4671. if matched_zero and matched_zero.group(1) != '0':
  4672. return False
  4673. # Don't warn on function pointer declarations. For this we need
  4674. # to check what came before the "(type)" string.
  4675. if Match(r'.*\)\s*$', line[0:match.start(0)]):
  4676. return False
  4677. # Don't warn if the parameter is named with block comments, e.g.:
  4678. # Function(int /*unused_param*/);
  4679. raw_line = clean_lines.raw_lines[linenum]
  4680. if '/*' in raw_line:
  4681. return False
  4682. # Passed all filters, issue warning here.
  4683. error(filename, linenum, 'readability/function', 3,
  4684. 'All parameters should be named in a function')
  4685. return True
  4686. # At this point, all that should be left is actual casts.
  4687. error(filename, linenum, 'readability/casting', 4,
  4688. 'Using C-style cast. Use %s<%s>(...) instead' %
  4689. (cast_type, match.group(1)))
  4690. return True
  4691. def ExpectingFunctionArgs(clean_lines, linenum):
  4692. """Checks whether where function type arguments are expected.
  4693. Args:
  4694. clean_lines: A CleansedLines instance containing the file.
  4695. linenum: The number of the line to check.
  4696. Returns:
  4697. True if the line at 'linenum' is inside something that expects arguments
  4698. of function types.
  4699. """
  4700. line = clean_lines.elided[linenum]
  4701. return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
  4702. (linenum >= 2 and
  4703. (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
  4704. clean_lines.elided[linenum - 1]) or
  4705. Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
  4706. clean_lines.elided[linenum - 2]) or
  4707. Search(r'\bstd::m?function\s*\<\s*$',
  4708. clean_lines.elided[linenum - 1]))))
  4709. _HEADERS_CONTAINING_TEMPLATES = (
  4710. ('<deque>', ('deque',)),
  4711. ('<functional>', ('unary_function', 'binary_function',
  4712. 'plus', 'minus', 'multiplies', 'divides', 'modulus',
  4713. 'negate',
  4714. 'equal_to', 'not_equal_to', 'greater', 'less',
  4715. 'greater_equal', 'less_equal',
  4716. 'logical_and', 'logical_or', 'logical_not',
  4717. 'unary_negate', 'not1', 'binary_negate', 'not2',
  4718. 'bind1st', 'bind2nd',
  4719. 'pointer_to_unary_function',
  4720. 'pointer_to_binary_function',
  4721. 'ptr_fun',
  4722. 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
  4723. 'mem_fun_ref_t',
  4724. 'const_mem_fun_t', 'const_mem_fun1_t',
  4725. 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
  4726. 'mem_fun_ref',
  4727. )),
  4728. ('<limits>', ('numeric_limits',)),
  4729. ('<list>', ('list',)),
  4730. ('<map>', ('map', 'multimap',)),
  4731. ('<memory>', ('allocator',)),
  4732. ('<queue>', ('queue', 'priority_queue',)),
  4733. ('<set>', ('set', 'multiset',)),
  4734. ('<stack>', ('stack',)),
  4735. ('<string>', ('char_traits', 'basic_string',)),
  4736. ('<tuple>', ('tuple',)),
  4737. ('<utility>', ('pair',)),
  4738. ('<vector>', ('vector',)),
  4739. # gcc extensions.
  4740. # Note: std::hash is their hash, ::hash is our hash
  4741. ('<hash_map>', ('hash_map', 'hash_multimap',)),
  4742. ('<hash_set>', ('hash_set', 'hash_multiset',)),
  4743. ('<slist>', ('slist',)),
  4744. )
  4745. _RE_PATTERN_STRING = re.compile(r'\bstring\b')
  4746. _re_pattern_algorithm_header = []
  4747. for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
  4748. 'transform'):
  4749. # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
  4750. # type::max().
  4751. _re_pattern_algorithm_header.append(
  4752. (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
  4753. _template,
  4754. '<algorithm>'))
  4755. _re_pattern_templates = []
  4756. for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
  4757. for _template in _templates:
  4758. _re_pattern_templates.append(
  4759. (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
  4760. _template + '<>',
  4761. _header))
  4762. def FilesBelongToSameModule(filename_cc, filename_h):
  4763. """Check if these two filenames belong to the same module.
  4764. The concept of a 'module' here is a as follows:
  4765. foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
  4766. same 'module' if they are in the same directory.
  4767. some/path/public/xyzzy and some/path/internal/xyzzy are also considered
  4768. to belong to the same module here.
  4769. If the filename_cc contains a longer path than the filename_h, for example,
  4770. '/absolute/path/to/base/sysinfo.cc', and this file would include
  4771. 'base/sysinfo.h', this function also produces the prefix needed to open the
  4772. header. This is used by the caller of this function to more robustly open the
  4773. header file. We don't have access to the real include paths in this context,
  4774. so we need this guesswork here.
  4775. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
  4776. according to this implementation. Because of this, this function gives
  4777. some false positives. This should be sufficiently rare in practice.
  4778. Args:
  4779. filename_cc: is the path for the .cc file
  4780. filename_h: is the path for the header path
  4781. Returns:
  4782. Tuple with a bool and a string:
  4783. bool: True if filename_cc and filename_h belong to the same module.
  4784. string: the additional prefix needed to open the header file.
  4785. """
  4786. if not filename_cc.endswith('.cc'):
  4787. return (False, '')
  4788. filename_cc = filename_cc[:-len('.cc')]
  4789. if filename_cc.endswith('_unittest'):
  4790. filename_cc = filename_cc[:-len('_unittest')]
  4791. elif filename_cc.endswith('_test'):
  4792. filename_cc = filename_cc[:-len('_test')]
  4793. filename_cc = filename_cc.replace('/public/', '/')
  4794. filename_cc = filename_cc.replace('/internal/', '/')
  4795. if not filename_h.endswith('.h'):
  4796. return (False, '')
  4797. filename_h = filename_h[:-len('.h')]
  4798. if filename_h.endswith('-inl'):
  4799. filename_h = filename_h[:-len('-inl')]
  4800. filename_h = filename_h.replace('/public/', '/')
  4801. filename_h = filename_h.replace('/internal/', '/')
  4802. files_belong_to_same_module = filename_cc.endswith(filename_h)
  4803. common_path = ''
  4804. if files_belong_to_same_module:
  4805. common_path = filename_cc[:-len(filename_h)]
  4806. return files_belong_to_same_module, common_path
  4807. def UpdateIncludeState(filename, include_dict, io=codecs):
  4808. """Fill up the include_dict with new includes found from the file.
  4809. Args:
  4810. filename: the name of the header to read.
  4811. include_dict: a dictionary in which the headers are inserted.
  4812. io: The io factory to use to read the file. Provided for testability.
  4813. Returns:
  4814. True if a header was successfully added. False otherwise.
  4815. """
  4816. headerfile = None
  4817. try:
  4818. headerfile = io.open(filename, 'r', 'utf8', 'replace')
  4819. except IOError:
  4820. return False
  4821. linenum = 0
  4822. for line in headerfile:
  4823. linenum += 1
  4824. clean_line = CleanseComments(line)
  4825. match = _RE_PATTERN_INCLUDE.search(clean_line)
  4826. if match:
  4827. include = match.group(2)
  4828. include_dict.setdefault(include, linenum)
  4829. return True
  4830. def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
  4831. io=codecs):
  4832. """Reports for missing stl includes.
  4833. This function will output warnings to make sure you are including the headers
  4834. necessary for the stl containers and functions that you use. We only give one
  4835. reason to include a header. For example, if you use both equal_to<> and
  4836. less<> in a .h file, only one (the latter in the file) of these will be
  4837. reported as a reason to include the <functional>.
  4838. Args:
  4839. filename: The name of the current file.
  4840. clean_lines: A CleansedLines instance containing the file.
  4841. include_state: An _IncludeState instance.
  4842. error: The function to call with any errors found.
  4843. io: The IO factory to use to read the header file. Provided for unittest
  4844. injection.
  4845. """
  4846. required = {} # A map of header name to linenumber and the template entity.
  4847. # Example of required: { '<functional>': (1219, 'less<>') }
  4848. for linenum in xrange(clean_lines.NumLines()):
  4849. line = clean_lines.elided[linenum]
  4850. if not line or line[0] == '#':
  4851. continue
  4852. # String is special -- it is a non-templatized type in STL.
  4853. matched = _RE_PATTERN_STRING.search(line)
  4854. if matched:
  4855. # Don't warn about strings in non-STL namespaces:
  4856. # (We check only the first match per line; good enough.)
  4857. prefix = line[:matched.start()]
  4858. if prefix.endswith('std::') or not prefix.endswith('::'):
  4859. required['<string>'] = (linenum, 'string')
  4860. for pattern, template, header in _re_pattern_algorithm_header:
  4861. if pattern.search(line):
  4862. required[header] = (linenum, template)
  4863. # The following function is just a speed up, no semantics are changed.
  4864. if not '<' in line: # Reduces the cpu time usage by skipping lines.
  4865. continue
  4866. for pattern, template, header in _re_pattern_templates:
  4867. if pattern.search(line):
  4868. required[header] = (linenum, template)
  4869. # The policy is that if you #include something in foo.h you don't need to
  4870. # include it again in foo.cc. Here, we will look at possible includes.
  4871. # Let's flatten the include_state include_list and copy it into a dictionary.
  4872. include_dict = dict([item for sublist in include_state.include_list
  4873. for item in sublist])
  4874. # Did we find the header for this file (if any) and successfully load it?
  4875. header_found = False
  4876. # Use the absolute path so that matching works properly.
  4877. abs_filename = FileInfo(filename).FullName()
  4878. # For Emacs's flymake.
  4879. # If cpplint is invoked from Emacs's flymake, a temporary file is generated
  4880. # by flymake and that file name might end with '_flymake.cc'. In that case,
  4881. # restore original file name here so that the corresponding header file can be
  4882. # found.
  4883. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
  4884. # instead of 'foo_flymake.h'
  4885. abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
  4886. # include_dict is modified during iteration, so we iterate over a copy of
  4887. # the keys.
  4888. header_keys = include_dict.keys()
  4889. for header in header_keys:
  4890. (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
  4891. fullpath = common_path + header
  4892. if same_module and UpdateIncludeState(fullpath, include_dict, io):
  4893. header_found = True
  4894. # If we can't find the header file for a .cc, assume it's because we don't
  4895. # know where to look. In that case we'll give up as we're not sure they
  4896. # didn't include it in the .h file.
  4897. # TODO(unknown): Do a better job of finding .h files so we are confident that
  4898. # not having the .h file means there isn't one.
  4899. if filename.endswith('.cc') and not header_found:
  4900. return
  4901. # All the lines have been processed, report the errors found.
  4902. for required_header_unstripped in required:
  4903. template = required[required_header_unstripped][1]
  4904. if required_header_unstripped.strip('<>"') not in include_dict:
  4905. error(filename, required[required_header_unstripped][0],
  4906. 'build/include_what_you_use', 4,
  4907. 'Add #include ' + required_header_unstripped + ' for ' + template)
  4908. _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
  4909. def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
  4910. """Check that make_pair's template arguments are deduced.
  4911. G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
  4912. specified explicitly, and such use isn't intended in any case.
  4913. Args:
  4914. filename: The name of the current file.
  4915. clean_lines: A CleansedLines instance containing the file.
  4916. linenum: The number of the line to check.
  4917. error: The function to call with any errors found.
  4918. """
  4919. line = clean_lines.elided[linenum]
  4920. match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
  4921. if match:
  4922. error(filename, linenum, 'build/explicit_make_pair',
  4923. 4, # 4 = high confidence
  4924. 'For C++11-compatibility, omit template arguments from make_pair'
  4925. ' OR use pair directly OR if appropriate, construct a pair directly')
  4926. def CheckDefaultLambdaCaptures(filename, clean_lines, linenum, error):
  4927. """Check that default lambda captures are not used.
  4928. Args:
  4929. filename: The name of the current file.
  4930. clean_lines: A CleansedLines instance containing the file.
  4931. linenum: The number of the line to check.
  4932. error: The function to call with any errors found.
  4933. """
  4934. line = clean_lines.elided[linenum]
  4935. # A lambda introducer specifies a default capture if it starts with "[="
  4936. # or if it starts with "[&" _not_ followed by an identifier.
  4937. match = Match(r'^(.*)\[\s*(?:=|&[^\w])', line)
  4938. if match:
  4939. # Found a potential error, check what comes after the lambda-introducer.
  4940. # If it's not open parenthesis (for lambda-declarator) or open brace
  4941. # (for compound-statement), it's not a lambda.
  4942. line, _, pos = CloseExpression(clean_lines, linenum, len(match.group(1)))
  4943. if pos >= 0 and Match(r'^\s*[{(]', line[pos:]):
  4944. error(filename, linenum, 'build/c++11',
  4945. 4, # 4 = high confidence
  4946. 'Default lambda captures are an unapproved C++ feature.')
  4947. def CheckRedundantVirtual(filename, clean_lines, linenum, error):
  4948. """Check if line contains a redundant "virtual" function-specifier.
  4949. Args:
  4950. filename: The name of the current file.
  4951. clean_lines: A CleansedLines instance containing the file.
  4952. linenum: The number of the line to check.
  4953. error: The function to call with any errors found.
  4954. """
  4955. # Look for "virtual" on current line.
  4956. line = clean_lines.elided[linenum]
  4957. virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
  4958. if not virtual: return
  4959. # Ignore "virtual" keywords that are near access-specifiers. These
  4960. # are only used in class base-specifier and do not apply to member
  4961. # functions.
  4962. if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
  4963. Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
  4964. return
  4965. # Ignore the "virtual" keyword from virtual base classes. Usually
  4966. # there is a column on the same line in these cases (virtual base
  4967. # classes are rare in google3 because multiple inheritance is rare).
  4968. if Match(r'^.*[^:]:[^:].*$', line): return
  4969. # Look for the next opening parenthesis. This is the start of the
  4970. # parameter list (possibly on the next line shortly after virtual).
  4971. # TODO(unknown): doesn't work if there are virtual functions with
  4972. # decltype() or other things that use parentheses, but csearch suggests
  4973. # that this is rare.
  4974. end_col = -1
  4975. end_line = -1
  4976. start_col = len(virtual.group(2))
  4977. for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):
  4978. line = clean_lines.elided[start_line][start_col:]
  4979. parameter_list = Match(r'^([^(]*)\(', line)
  4980. if parameter_list:
  4981. # Match parentheses to find the end of the parameter list
  4982. (_, end_line, end_col) = CloseExpression(
  4983. clean_lines, start_line, start_col + len(parameter_list.group(1)))
  4984. break
  4985. start_col = 0
  4986. if end_col < 0:
  4987. return # Couldn't find end of parameter list, give up
  4988. # Look for "override" or "final" after the parameter list
  4989. # (possibly on the next few lines).
  4990. for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):
  4991. line = clean_lines.elided[i][end_col:]
  4992. match = Search(r'\b(override|final)\b', line)
  4993. if match:
  4994. error(filename, linenum, 'readability/inheritance', 4,
  4995. ('"virtual" is redundant since function is '
  4996. 'already declared as "%s"' % match.group(1)))
  4997. # Set end_col to check whole lines after we are done with the
  4998. # first line.
  4999. end_col = 0
  5000. if Search(r'[^\w]\s*$', line):
  5001. break
  5002. def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
  5003. """Check if line contains a redundant "override" or "final" virt-specifier.
  5004. Args:
  5005. filename: The name of the current file.
  5006. clean_lines: A CleansedLines instance containing the file.
  5007. linenum: The number of the line to check.
  5008. error: The function to call with any errors found.
  5009. """
  5010. # Look for closing parenthesis nearby. We need one to confirm where
  5011. # the declarator ends and where the virt-specifier starts to avoid
  5012. # false positives.
  5013. line = clean_lines.elided[linenum]
  5014. declarator_end = line.rfind(')')
  5015. if declarator_end >= 0:
  5016. fragment = line[declarator_end:]
  5017. else:
  5018. if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
  5019. fragment = line
  5020. else:
  5021. return
  5022. # Check that at most one of "override" or "final" is present, not both
  5023. if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
  5024. error(filename, linenum, 'readability/inheritance', 4,
  5025. ('"override" is redundant since function is '
  5026. 'already declared as "final"'))
  5027. # Returns true if we are at a new block, and it is directly
  5028. # inside of a namespace.
  5029. def IsBlockInNameSpace(nesting_state, is_forward_declaration):
  5030. """Checks that the new block is directly in a namespace.
  5031. Args:
  5032. nesting_state: The _NestingState object that contains info about our state.
  5033. is_forward_declaration: If the class is a forward declared class.
  5034. Returns:
  5035. Whether or not the new block is directly in a namespace.
  5036. """
  5037. if is_forward_declaration:
  5038. if len(nesting_state.stack) >= 1 and (
  5039. isinstance(nesting_state.stack[-1], _NamespaceInfo)):
  5040. return True
  5041. else:
  5042. return False
  5043. return (len(nesting_state.stack) > 1 and
  5044. nesting_state.stack[-1].check_namespace_indentation and
  5045. isinstance(nesting_state.stack[-2], _NamespaceInfo))
  5046. def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
  5047. raw_lines_no_comments, linenum):
  5048. """This method determines if we should apply our namespace indentation check.
  5049. Args:
  5050. nesting_state: The current nesting state.
  5051. is_namespace_indent_item: If we just put a new class on the stack, True.
  5052. If the top of the stack is not a class, or we did not recently
  5053. add the class, False.
  5054. raw_lines_no_comments: The lines without the comments.
  5055. linenum: The current line number we are processing.
  5056. Returns:
  5057. True if we should apply our namespace indentation check. Currently, it
  5058. only works for classes and namespaces inside of a namespace.
  5059. """
  5060. is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
  5061. linenum)
  5062. if not (is_namespace_indent_item or is_forward_declaration):
  5063. return False
  5064. # If we are in a macro, we do not want to check the namespace indentation.
  5065. if IsMacroDefinition(raw_lines_no_comments, linenum):
  5066. return False
  5067. return IsBlockInNameSpace(nesting_state, is_forward_declaration)
  5068. # Call this method if the line is directly inside of a namespace.
  5069. # If the line above is blank (excluding comments) or the start of
  5070. # an inner namespace, it cannot be indented.
  5071. def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
  5072. error):
  5073. line = raw_lines_no_comments[linenum]
  5074. if Match(r'^\s+', line):
  5075. error(filename, linenum, 'runtime/indentation_namespace', 4,
  5076. 'Do not indent within a namespace')
  5077. def ProcessLine(filename, file_extension, clean_lines, line,
  5078. include_state, function_state, nesting_state, error,
  5079. extra_check_functions=[]):
  5080. """Processes a single line in the file.
  5081. Args:
  5082. filename: Filename of the file that is being processed.
  5083. file_extension: The extension (dot not included) of the file.
  5084. clean_lines: An array of strings, each representing a line of the file,
  5085. with comments stripped.
  5086. line: Number of line being processed.
  5087. include_state: An _IncludeState instance in which the headers are inserted.
  5088. function_state: A _FunctionState instance which counts function lines, etc.
  5089. nesting_state: A NestingState instance which maintains information about
  5090. the current stack of nested blocks being parsed.
  5091. error: A callable to which errors are reported, which takes 4 arguments:
  5092. filename, line number, error level, and message
  5093. extra_check_functions: An array of additional check functions that will be
  5094. run on each source line. Each function takes 4
  5095. arguments: filename, clean_lines, line, error
  5096. """
  5097. raw_lines = clean_lines.raw_lines
  5098. ParseNolintSuppressions(filename, raw_lines[line], line, error)
  5099. nesting_state.Update(filename, clean_lines, line, error)
  5100. CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
  5101. error)
  5102. if nesting_state.InAsmBlock(): return
  5103. CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
  5104. CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
  5105. CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
  5106. CheckLanguage(filename, clean_lines, line, file_extension, include_state,
  5107. nesting_state, error)
  5108. CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
  5109. CheckForNonStandardConstructs(filename, clean_lines, line,
  5110. nesting_state, error)
  5111. CheckVlogArguments(filename, clean_lines, line, error)
  5112. CheckPosixThreading(filename, clean_lines, line, error)
  5113. CheckInvalidIncrement(filename, clean_lines, line, error)
  5114. CheckMakePairUsesDeduction(filename, clean_lines, line, error)
  5115. CheckDefaultLambdaCaptures(filename, clean_lines, line, error)
  5116. CheckRedundantVirtual(filename, clean_lines, line, error)
  5117. CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
  5118. for check_fn in extra_check_functions:
  5119. check_fn(filename, clean_lines, line, error)
  5120. def FlagCxx11Features(filename, clean_lines, linenum, error):
  5121. """Flag those c++11 features that we only allow in certain places.
  5122. Args:
  5123. filename: The name of the current file.
  5124. clean_lines: A CleansedLines instance containing the file.
  5125. linenum: The number of the line to check.
  5126. error: The function to call with any errors found.
  5127. """
  5128. line = clean_lines.elided[linenum]
  5129. # Flag unapproved C++11 headers.
  5130. include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
  5131. if include and include.group(1) in ('cfenv',
  5132. 'condition_variable',
  5133. 'fenv.h',
  5134. 'future',
  5135. 'mutex',
  5136. 'thread',
  5137. 'chrono',
  5138. 'ratio',
  5139. 'regex',
  5140. 'system_error',
  5141. ):
  5142. error(filename, linenum, 'build/c++11', 5,
  5143. ('<%s> is an unapproved C++11 header.') % include.group(1))
  5144. # The only place where we need to worry about C++11 keywords and library
  5145. # features in preprocessor directives is in macro definitions.
  5146. if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
  5147. # These are classes and free functions. The classes are always
  5148. # mentioned as std::*, but we only catch the free functions if
  5149. # they're not found by ADL. They're alphabetical by header.
  5150. for top_name in (
  5151. # type_traits
  5152. 'alignment_of',
  5153. 'aligned_union',
  5154. ):
  5155. if Search(r'\bstd::%s\b' % top_name, line):
  5156. error(filename, linenum, 'build/c++11', 5,
  5157. ('std::%s is an unapproved C++11 class or function. Send c-style '
  5158. 'an example of where it would make your code more readable, and '
  5159. 'they may let you use it.') % top_name)
  5160. def ProcessFileData(filename, file_extension, lines, error,
  5161. extra_check_functions=[]):
  5162. """Performs lint checks and reports any errors to the given error function.
  5163. Args:
  5164. filename: Filename of the file that is being processed.
  5165. file_extension: The extension (dot not included) of the file.
  5166. lines: An array of strings, each representing a line of the file, with the
  5167. last element being empty if the file is terminated with a newline.
  5168. error: A callable to which errors are reported, which takes 4 arguments:
  5169. filename, line number, error level, and message
  5170. extra_check_functions: An array of additional check functions that will be
  5171. run on each source line. Each function takes 4
  5172. arguments: filename, clean_lines, line, error
  5173. """
  5174. lines = (['// marker so line numbers and indices both start at 1'] + lines +
  5175. ['// marker so line numbers end in a known way'])
  5176. include_state = _IncludeState()
  5177. function_state = _FunctionState()
  5178. nesting_state = NestingState()
  5179. ResetNolintSuppressions()
  5180. CheckForCopyright(filename, lines, error)
  5181. RemoveMultiLineComments(filename, lines, error)
  5182. clean_lines = CleansedLines(lines)
  5183. if file_extension == 'h':
  5184. CheckForHeaderGuard(filename, clean_lines, error)
  5185. for line in xrange(clean_lines.NumLines()):
  5186. ProcessLine(filename, file_extension, clean_lines, line,
  5187. include_state, function_state, nesting_state, error,
  5188. extra_check_functions)
  5189. FlagCxx11Features(filename, clean_lines, line, error)
  5190. nesting_state.CheckCompletedBlocks(filename, error)
  5191. CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
  5192. # Check that the .cc file has included its header if it exists.
  5193. if file_extension == 'cc':
  5194. CheckHeaderFileIncluded(filename, include_state, error)
  5195. # We check here rather than inside ProcessLine so that we see raw
  5196. # lines rather than "cleaned" lines.
  5197. CheckForBadCharacters(filename, lines, error)
  5198. CheckForNewlineAtEOF(filename, lines, error)
  5199. def ProcessConfigOverrides(filename):
  5200. """ Loads the configuration files and processes the config overrides.
  5201. Args:
  5202. filename: The name of the file being processed by the linter.
  5203. Returns:
  5204. False if the current |filename| should not be processed further.
  5205. """
  5206. abs_filename = os.path.abspath(filename)
  5207. cfg_filters = []
  5208. keep_looking = True
  5209. while keep_looking:
  5210. abs_path, base_name = os.path.split(abs_filename)
  5211. if not base_name:
  5212. break # Reached the root directory.
  5213. cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
  5214. abs_filename = abs_path
  5215. if not os.path.isfile(cfg_file):
  5216. continue
  5217. try:
  5218. with open(cfg_file) as file_handle:
  5219. for line in file_handle:
  5220. line, _, _ = line.partition('#') # Remove comments.
  5221. if not line.strip():
  5222. continue
  5223. name, _, val = line.partition('=')
  5224. name = name.strip()
  5225. val = val.strip()
  5226. if name == 'set noparent':
  5227. keep_looking = False
  5228. elif name == 'filter':
  5229. cfg_filters.append(val)
  5230. elif name == 'exclude_files':
  5231. # When matching exclude_files pattern, use the base_name of
  5232. # the current file name or the directory name we are processing.
  5233. # For example, if we are checking for lint errors in /foo/bar/baz.cc
  5234. # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
  5235. # file's "exclude_files" filter is meant to be checked against "bar"
  5236. # and not "baz" nor "bar/baz.cc".
  5237. if base_name:
  5238. pattern = re.compile(val)
  5239. if pattern.match(base_name):
  5240. sys.stderr.write('Ignoring "%s": file excluded by "%s". '
  5241. 'File path component "%s" matches '
  5242. 'pattern "%s"\n' %
  5243. (filename, cfg_file, base_name, val))
  5244. return False
  5245. elif name == 'linelength':
  5246. global _line_length
  5247. try:
  5248. _line_length = int(val)
  5249. except ValueError:
  5250. sys.stderr.write('Line length must be numeric.')
  5251. else:
  5252. sys.stderr.write(
  5253. 'Invalid configuration option (%s) in file %s\n' %
  5254. (name, cfg_file))
  5255. except IOError:
  5256. sys.stderr.write(
  5257. "Skipping config file '%s': Can't open for reading\n" % cfg_file)
  5258. keep_looking = False
  5259. # Apply all the accumulated filters in reverse order (top-level directory
  5260. # config options having the least priority).
  5261. for filter in reversed(cfg_filters):
  5262. _AddFilters(filter)
  5263. return True
  5264. def ProcessFile(filename, vlevel, extra_check_functions=[]):
  5265. """Does google-lint on a single file.
  5266. Args:
  5267. filename: The name of the file to parse.
  5268. vlevel: The level of errors to report. Every error of confidence
  5269. >= verbose_level will be reported. 0 is a good default.
  5270. extra_check_functions: An array of additional check functions that will be
  5271. run on each source line. Each function takes 4
  5272. arguments: filename, clean_lines, line, error
  5273. """
  5274. _SetVerboseLevel(vlevel)
  5275. _BackupFilters()
  5276. if not ProcessConfigOverrides(filename):
  5277. _RestoreFilters()
  5278. return
  5279. lf_lines = []
  5280. crlf_lines = []
  5281. try:
  5282. # Support the UNIX convention of using "-" for stdin. Note that
  5283. # we are not opening the file with universal newline support
  5284. # (which codecs doesn't support anyway), so the resulting lines do
  5285. # contain trailing '\r' characters if we are reading a file that
  5286. # has CRLF endings.
  5287. # If after the split a trailing '\r' is present, it is removed
  5288. # below.
  5289. if filename == '-':
  5290. lines = codecs.StreamReaderWriter(sys.stdin,
  5291. codecs.getreader('utf8'),
  5292. codecs.getwriter('utf8'),
  5293. 'replace').read().split('\n')
  5294. else:
  5295. lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
  5296. # Remove trailing '\r'.
  5297. # The -1 accounts for the extra trailing blank line we get from split()
  5298. for linenum in range(len(lines) - 1):
  5299. if lines[linenum].endswith('\r'):
  5300. lines[linenum] = lines[linenum].rstrip('\r')
  5301. crlf_lines.append(linenum + 1)
  5302. else:
  5303. lf_lines.append(linenum + 1)
  5304. except IOError:
  5305. sys.stderr.write(
  5306. "Skipping input '%s': Can't open for reading\n" % filename)
  5307. _RestoreFilters()
  5308. return
  5309. # Note, if no dot is found, this will give the entire filename as the ext.
  5310. file_extension = filename[filename.rfind('.') + 1:]
  5311. # When reading from stdin, the extension is unknown, so no cpplint tests
  5312. # should rely on the extension.
  5313. if filename != '-' and file_extension not in _valid_extensions:
  5314. sys.stderr.write('Ignoring %s; not a valid file name '
  5315. '(%s)\n' % (filename, ', '.join(_valid_extensions)))
  5316. else:
  5317. ProcessFileData(filename, file_extension, lines, Error,
  5318. extra_check_functions)
  5319. # If end-of-line sequences are a mix of LF and CR-LF, issue
  5320. # warnings on the lines with CR.
  5321. #
  5322. # Don't issue any warnings if all lines are uniformly LF or CR-LF,
  5323. # since critique can handle these just fine, and the style guide
  5324. # doesn't dictate a particular end of line sequence.
  5325. #
  5326. # We can't depend on os.linesep to determine what the desired
  5327. # end-of-line sequence should be, since that will return the
  5328. # server-side end-of-line sequence.
  5329. if lf_lines and crlf_lines:
  5330. # Warn on every line with CR. An alternative approach might be to
  5331. # check whether the file is mostly CRLF or just LF, and warn on the
  5332. # minority, we bias toward LF here since most tools prefer LF.
  5333. for linenum in crlf_lines:
  5334. Error(filename, linenum, 'whitespace/newline', 1,
  5335. 'Unexpected \\r (^M) found; better to use only \\n')
  5336. sys.stderr.write('Done processing %s\n' % filename)
  5337. _RestoreFilters()
  5338. def PrintUsage(message):
  5339. """Prints a brief usage string and exits, optionally with an error message.
  5340. Args:
  5341. message: The optional error message.
  5342. """
  5343. sys.stderr.write(_USAGE)
  5344. if message:
  5345. sys.exit('\nFATAL ERROR: ' + message)
  5346. else:
  5347. sys.exit(1)
  5348. def PrintCategories():
  5349. """Prints a list of all the error-categories used by error messages.
  5350. These are the categories used to filter messages via --filter.
  5351. """
  5352. sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
  5353. sys.exit(0)
  5354. def ParseArguments(args):
  5355. """Parses the command line arguments.
  5356. This may set the output format and verbosity level as side-effects.
  5357. Args:
  5358. args: The command line arguments:
  5359. Returns:
  5360. The list of filenames to lint.
  5361. """
  5362. try:
  5363. (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
  5364. 'counting=',
  5365. 'filter=',
  5366. 'root=',
  5367. 'linelength=',
  5368. 'extensions='])
  5369. except getopt.GetoptError:
  5370. PrintUsage('Invalid arguments.')
  5371. verbosity = _VerboseLevel()
  5372. output_format = _OutputFormat()
  5373. filters = ''
  5374. counting_style = ''
  5375. for (opt, val) in opts:
  5376. if opt == '--help':
  5377. PrintUsage(None)
  5378. elif opt == '--output':
  5379. if val not in ('emacs', 'vs7', 'eclipse'):
  5380. PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
  5381. output_format = val
  5382. elif opt == '--verbose':
  5383. verbosity = int(val)
  5384. elif opt == '--filter':
  5385. filters = val
  5386. if not filters:
  5387. PrintCategories()
  5388. elif opt == '--counting':
  5389. if val not in ('total', 'toplevel', 'detailed'):
  5390. PrintUsage('Valid counting options are total, toplevel, and detailed')
  5391. counting_style = val
  5392. elif opt == '--root':
  5393. global _root
  5394. _root = val
  5395. elif opt == '--linelength':
  5396. global _line_length
  5397. try:
  5398. _line_length = int(val)
  5399. except ValueError:
  5400. PrintUsage('Line length must be digits.')
  5401. elif opt == '--extensions':
  5402. global _valid_extensions
  5403. try:
  5404. _valid_extensions = set(val.split(','))
  5405. except ValueError:
  5406. PrintUsage('Extensions must be comma seperated list.')
  5407. if not filenames:
  5408. PrintUsage('No files were specified.')
  5409. _SetOutputFormat(output_format)
  5410. _SetVerboseLevel(verbosity)
  5411. _SetFilters(filters)
  5412. _SetCountingStyle(counting_style)
  5413. return filenames
  5414. def main():
  5415. filenames = ParseArguments(sys.argv[1:])
  5416. # Change stderr to write with replacement characters so we don't die
  5417. # if we try to print something containing non-ASCII characters.
  5418. sys.stderr = codecs.StreamReaderWriter(sys.stderr,
  5419. codecs.getreader('utf8'),
  5420. codecs.getwriter('utf8'),
  5421. 'replace')
  5422. _cpplint_state.ResetErrorCounts()
  5423. for filename in filenames:
  5424. ProcessFile(filename, _cpplint_state.verbose_level)
  5425. _cpplint_state.PrintErrorCounts()
  5426. sys.exit(_cpplint_state.error_count > 0)
  5427. if __name__ == '__main__':
  5428. main()