PageRenderTime 79ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/hooks/webkitpy/style/checkers/cpp.py

https://github.com/hwti/LunaSysMgr
Python | 3580 lines | 2922 code | 212 blank | 446 comment | 298 complexity | 265650f2e883796370c6cad485c6051a MD5 | raw file
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2009, 2010 Google Inc. All rights reserved.
  5. # Copyright (C) 2009 Torch Mobile Inc.
  6. # Copyright (C) 2009 Apple Inc. All rights reserved.
  7. # Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
  8. #
  9. # Redistribution and use in source and binary forms, with or without
  10. # modification, are permitted provided that the following conditions are
  11. # met:
  12. #
  13. # * Redistributions of source code must retain the above copyright
  14. # notice, this list of conditions and the following disclaimer.
  15. # * Redistributions in binary form must reproduce the above
  16. # copyright notice, this list of conditions and the following disclaimer
  17. # in the documentation and/or other materials provided with the
  18. # distribution.
  19. # * Neither the name of Google Inc. nor the names of its
  20. # contributors may be used to endorse or promote products derived from
  21. # this software without specific prior written permission.
  22. #
  23. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  24. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  25. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  26. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  27. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  28. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  29. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  30. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  31. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  32. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  33. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. # This is the modified version of Google's cpplint. The original code is
  35. # http://google-styleguide.googlecode.com/svn/trunk/cpplint/cpplint.py
  36. """Support for check-webkit-style."""
  37. import codecs
  38. import math # for log
  39. import os
  40. import os.path
  41. import re
  42. import sre_compile
  43. import string
  44. import sys
  45. import unicodedata
  46. from webkitpy.common.memoized import memoized
  47. # The key to use to provide a class to fake loading a header file.
  48. INCLUDE_IO_INJECTION_KEY = 'include_header_io'
  49. # Headers that we consider STL headers.
  50. _STL_HEADERS = frozenset([
  51. 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception',
  52. 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set',
  53. 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'pair.h',
  54. 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack',
  55. 'stl_alloc.h', 'stl_relops.h', 'type_traits.h',
  56. 'utility', 'vector', 'vector.h',
  57. ])
  58. # Non-STL C++ system headers.
  59. _CPP_HEADERS = frozenset([
  60. 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype',
  61. 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath',
  62. 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef',
  63. 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype',
  64. 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream',
  65. 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip',
  66. 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream.h',
  67. 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
  68. 'numeric', 'ostream.h', 'parsestream.h', 'pfstream.h', 'PlotFile.h',
  69. 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h',
  70. 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
  71. 'stdiostream.h', 'streambuf.h', 'stream.h', 'strfile.h', 'string',
  72. 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray',
  73. ])
  74. # Assertion macros. These are defined in base/logging.h and
  75. # testing/base/gunit.h. Note that the _M versions need to come first
  76. # for substring matching to work.
  77. _CHECK_MACROS = [
  78. 'DCHECK', 'CHECK',
  79. 'EXPECT_TRUE_M', 'EXPECT_TRUE',
  80. 'ASSERT_TRUE_M', 'ASSERT_TRUE',
  81. 'EXPECT_FALSE_M', 'EXPECT_FALSE',
  82. 'ASSERT_FALSE_M', 'ASSERT_FALSE',
  83. ]
  84. # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
  85. _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
  86. for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
  87. ('>=', 'GE'), ('>', 'GT'),
  88. ('<=', 'LE'), ('<', 'LT')]:
  89. _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
  90. _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
  91. _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
  92. _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
  93. _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
  94. _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
  95. for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
  96. ('>=', 'LT'), ('>', 'LE'),
  97. ('<=', 'GT'), ('<', 'GE')]:
  98. _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
  99. _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
  100. _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
  101. _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
  102. # These constants define types of headers for use with
  103. # _IncludeState.check_next_include_order().
  104. _CONFIG_HEADER = 0
  105. _PRIMARY_HEADER = 1
  106. _OTHER_HEADER = 2
  107. _MOC_HEADER = 3
  108. # A dictionary of items customize behavior for unit test. For example,
  109. # INCLUDE_IO_INJECTION_KEY allows providing a custom io class which allows
  110. # for faking a header file.
  111. _unit_test_config = {}
  112. # The regexp compilation caching is inlined in all regexp functions for
  113. # performance reasons; factoring it out into a separate function turns out
  114. # to be noticeably expensive.
  115. _regexp_compile_cache = {}
  116. def match(pattern, s):
  117. """Matches the string with the pattern, caching the compiled regexp."""
  118. if not pattern in _regexp_compile_cache:
  119. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  120. return _regexp_compile_cache[pattern].match(s)
  121. def search(pattern, s):
  122. """Searches the string for the pattern, caching the compiled regexp."""
  123. if not pattern in _regexp_compile_cache:
  124. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  125. return _regexp_compile_cache[pattern].search(s)
  126. def sub(pattern, replacement, s):
  127. """Substitutes occurrences of a pattern, caching the compiled regexp."""
  128. if not pattern in _regexp_compile_cache:
  129. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  130. return _regexp_compile_cache[pattern].sub(replacement, s)
  131. def subn(pattern, replacement, s):
  132. """Substitutes occurrences of a pattern, caching the compiled regexp."""
  133. if not pattern in _regexp_compile_cache:
  134. _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  135. return _regexp_compile_cache[pattern].subn(replacement, s)
  136. def iteratively_replace_matches_with_char(pattern, char_replacement, s):
  137. """Returns the string with replacement done.
  138. Every character in the match is replaced with char.
  139. Due to the iterative nature, pattern should not match char or
  140. there will be an infinite loop.
  141. Example:
  142. pattern = r'<[^>]>' # template parameters
  143. char_replacement = '_'
  144. s = 'A<B<C, D>>'
  145. Returns 'A_________'
  146. Args:
  147. pattern: The regex to match.
  148. char_replacement: The character to put in place of every
  149. character of the match.
  150. s: The string on which to do the replacements.
  151. Returns:
  152. True, if the given line is blank.
  153. """
  154. while True:
  155. matched = search(pattern, s)
  156. if not matched:
  157. return s
  158. start_match_index = matched.start(0)
  159. end_match_index = matched.end(0)
  160. match_length = end_match_index - start_match_index
  161. s = s[:start_match_index] + char_replacement * match_length + s[end_match_index:]
  162. def _rfind_in_lines(regex, lines, start_position, not_found_position):
  163. """Does a reverse find starting at start position and going backwards until
  164. a match is found.
  165. Returns the position where the regex ended.
  166. """
  167. # Put the regex in a group and proceed it with a greedy expression that
  168. # matches anything to ensure that we get the last possible match in a line.
  169. last_in_line_regex = r'.*(' + regex + ')'
  170. current_row = start_position.row
  171. # Start with the given row and trim off everything past what may be matched.
  172. current_line = lines[start_position.row][:start_position.column]
  173. while True:
  174. found_match = match(last_in_line_regex, current_line)
  175. if found_match:
  176. return Position(current_row, found_match.end(1))
  177. # A match was not found so continue backward.
  178. current_row -= 1
  179. if current_row < 0:
  180. return not_found_position
  181. current_line = lines[current_row]
  182. def _convert_to_lower_with_underscores(text):
  183. """Converts all text strings in camelCase or PascalCase to lowers with underscores."""
  184. # First add underscores before any capital letter followed by a lower case letter
  185. # as long as it is in a word.
  186. # (This put an underscore before Password but not P and A in WPAPassword).
  187. text = sub(r'(?<=[A-Za-z0-9])([A-Z])(?=[a-z])', r'_\1', text)
  188. # Next add underscores before capitals at the end of words if it was
  189. # preceeded by lower case letter or number.
  190. # (This puts an underscore before A in isA but not A in CBA).
  191. text = sub(r'(?<=[a-z0-9])([A-Z])(?=\b)', r'_\1', text)
  192. # Next add underscores when you have a captial letter which is followed by a capital letter
  193. # but is not proceeded by one. (This puts an underscore before A in 'WordADay').
  194. text = sub(r'(?<=[a-z0-9])([A-Z][A-Z_])', r'_\1', text)
  195. return text.lower()
  196. def _create_acronym(text):
  197. """Creates an acronym for the given text."""
  198. # Removes all lower case letters except those starting words.
  199. text = sub(r'(?<!\b)[a-z]', '', text)
  200. return text.upper()
  201. def up_to_unmatched_closing_paren(s):
  202. """Splits a string into two parts up to first unmatched ')'.
  203. Args:
  204. s: a string which is a substring of line after '('
  205. (e.g., "a == (b + c))").
  206. Returns:
  207. A pair of strings (prefix before first unmatched ')',
  208. remainder of s after first unmatched ')'), e.g.,
  209. up_to_unmatched_closing_paren("a == (b + c)) { ")
  210. returns "a == (b + c)", " {".
  211. Returns None, None if there is no unmatched ')'
  212. """
  213. i = 1
  214. for pos, c in enumerate(s):
  215. if c == '(':
  216. i += 1
  217. elif c == ')':
  218. i -= 1
  219. if i == 0:
  220. return s[:pos], s[pos + 1:]
  221. return None, None
  222. class _IncludeState(dict):
  223. """Tracks line numbers for includes, and the order in which includes appear.
  224. As a dict, an _IncludeState object serves as a mapping between include
  225. filename and line number on which that file was included.
  226. Call check_next_include_order() once for each header in the file, passing
  227. in the type constants defined above. Calls in an illegal order will
  228. raise an _IncludeError with an appropriate error message.
  229. """
  230. # self._section will move monotonically through this set. If it ever
  231. # needs to move backwards, check_next_include_order will raise an error.
  232. _INITIAL_SECTION = 0
  233. _CONFIG_SECTION = 1
  234. _PRIMARY_SECTION = 2
  235. _OTHER_SECTION = 3
  236. _TYPE_NAMES = {
  237. _CONFIG_HEADER: '',
  238. _PRIMARY_HEADER: 'header this file implements',
  239. _OTHER_HEADER: 'other header',
  240. _MOC_HEADER: 'moc file',
  241. }
  242. _SECTION_NAMES = {
  243. _INITIAL_SECTION: "... nothing.",
  244. _CONFIG_SECTION: "WebCore config.h.",
  245. _PRIMARY_SECTION: 'a header this file implements.',
  246. _OTHER_SECTION: 'other header.',
  247. }
  248. def __init__(self):
  249. dict.__init__(self)
  250. self._section = self._INITIAL_SECTION
  251. self._visited_primary_section = False
  252. self.header_types = dict();
  253. def visited_primary_section(self):
  254. return self._visited_primary_section
  255. def check_next_include_order(self, header_type, file_is_header, primary_header_exists):
  256. """Returns a non-empty error message if the next header is out of order.
  257. This function also updates the internal state to be ready to check
  258. the next include.
  259. Args:
  260. header_type: One of the _XXX_HEADER constants defined above.
  261. file_is_header: Whether the file that owns this _IncludeState is itself a header
  262. Returns:
  263. The empty string if the header is in the right order, or an
  264. error message describing what's wrong.
  265. """
  266. if header_type == _CONFIG_HEADER and file_is_header:
  267. return 'Header file should not contain WebCore config.h.'
  268. if header_type == _PRIMARY_HEADER and file_is_header:
  269. return 'Header file should not contain itself.'
  270. if header_type == _MOC_HEADER:
  271. return ''
  272. error_message = ''
  273. if self._section != self._OTHER_SECTION:
  274. before_error_message = ('Found %s before %s' %
  275. (self._TYPE_NAMES[header_type],
  276. self._SECTION_NAMES[self._section + 1]))
  277. after_error_message = ('Found %s after %s' %
  278. (self._TYPE_NAMES[header_type],
  279. self._SECTION_NAMES[self._section]))
  280. if header_type == _CONFIG_HEADER:
  281. if self._section >= self._CONFIG_SECTION:
  282. error_message = after_error_message
  283. self._section = self._CONFIG_SECTION
  284. elif header_type == _PRIMARY_HEADER:
  285. if self._section >= self._PRIMARY_SECTION:
  286. error_message = after_error_message
  287. # elif self._section < self._CONFIG_SECTION:
  288. # error_message = before_error_message
  289. self._section = self._PRIMARY_SECTION
  290. self._visited_primary_section = True
  291. else:
  292. assert header_type == _OTHER_HEADER
  293. if not file_is_header and self._section < self._PRIMARY_SECTION:
  294. if primary_header_exists:
  295. error_message = before_error_message
  296. self._section = self._OTHER_SECTION
  297. return error_message
  298. class Position(object):
  299. """Holds the position of something."""
  300. def __init__(self, row, column):
  301. self.row = row
  302. self.column = column
  303. def __str__(self):
  304. return '(%s, %s)' % (self.row, self.column)
  305. def __cmp__(self, other):
  306. return self.row.__cmp__(other.row) or self.column.__cmp__(other.column)
  307. class Parameter(object):
  308. """Information about one function parameter."""
  309. def __init__(self, parameter, parameter_name_index, row):
  310. self.type = parameter[:parameter_name_index].strip()
  311. # Remove any initializers from the parameter name (e.g. int i = 5).
  312. self.name = sub(r'=.*', '', parameter[parameter_name_index:]).strip()
  313. self.row = row
  314. @memoized
  315. def lower_with_underscores_name(self):
  316. """Returns the parameter name in the lower with underscores format."""
  317. return _convert_to_lower_with_underscores(self.name)
  318. class SingleLineView(object):
  319. """Converts multiple lines into a single line (with line breaks replaced by a
  320. space) to allow for easier searching."""
  321. def __init__(self, lines, start_position, end_position):
  322. """Create a SingleLineView instance.
  323. Args:
  324. lines: a list of multiple lines to combine into a single line.
  325. start_position: offset within lines of where to start the single line.
  326. end_position: just after where to end (like a slice operation).
  327. """
  328. # Get the rows of interest.
  329. trimmed_lines = lines[start_position.row:end_position.row + 1]
  330. # Remove the columns on the last line that aren't included.
  331. trimmed_lines[-1] = trimmed_lines[-1][:end_position.column]
  332. # Remove the columns on the first line that aren't included.
  333. trimmed_lines[0] = trimmed_lines[0][start_position.column:]
  334. # Create a single line with all of the parameters.
  335. self.single_line = ' '.join(trimmed_lines)
  336. # Keep the row lengths, so we can calculate the original row number
  337. # given a column in the single line (adding 1 due to the space added
  338. # during the join).
  339. self._row_lengths = [len(line) + 1 for line in trimmed_lines]
  340. self._starting_row = start_position.row
  341. def convert_column_to_row(self, single_line_column_number):
  342. """Convert the column number from the single line into the original
  343. line number.
  344. Special cases:
  345. * Columns in the added spaces are considered part of the previous line.
  346. * Columns beyond the end of the line are consider part the last line
  347. in the view."""
  348. total_columns = 0
  349. row_offset = 0
  350. while row_offset < len(self._row_lengths) - 1 and single_line_column_number >= total_columns + self._row_lengths[row_offset]:
  351. total_columns += self._row_lengths[row_offset]
  352. row_offset += 1
  353. return self._starting_row + row_offset
  354. def create_skeleton_parameters(all_parameters):
  355. """Converts a parameter list to a skeleton version.
  356. The skeleton only has one word for the parameter name, one word for the type,
  357. and commas after each parameter and only there. Everything in the skeleton
  358. remains in the same columns as the original."""
  359. all_simplifications = (
  360. # Remove template parameters, function declaration parameters, etc.
  361. r'(<[^<>]*?>)|(\([^\(\)]*?\))|(\{[^\{\}]*?\})',
  362. # Remove all initializers.
  363. r'=[^,]*',
  364. # Remove :: and everything before it.
  365. r'[^,]*::',
  366. # Remove modifiers like &, *.
  367. r'[&*]',
  368. # Remove const modifiers.
  369. r'\bconst\s+(?=[A-Za-z])',
  370. # Remove numerical modifiers like long.
  371. r'\b(unsigned|long|short)\s+(?=unsigned|long|short|int|char|double|float)')
  372. skeleton_parameters = all_parameters
  373. for simplification in all_simplifications:
  374. skeleton_parameters = iteratively_replace_matches_with_char(simplification, ' ', skeleton_parameters)
  375. # If there are any parameters, then add a , after the last one to
  376. # make a regular pattern of a , following every parameter.
  377. if skeleton_parameters.strip():
  378. skeleton_parameters += ','
  379. return skeleton_parameters
  380. def find_parameter_name_index(skeleton_parameter):
  381. """Determines where the parametere name starts given the skeleton parameter."""
  382. # The first space from the right in the simplified parameter is where the parameter
  383. # name starts unless the first space is before any content in the simplified parameter.
  384. before_name_index = skeleton_parameter.rstrip().rfind(' ')
  385. if before_name_index != -1 and skeleton_parameter[:before_name_index].strip():
  386. return before_name_index + 1
  387. return len(skeleton_parameter)
  388. def parameter_list(elided_lines, start_position, end_position):
  389. """Generator for a function's parameters."""
  390. # Create new positions that omit the outer parenthesis of the parameters.
  391. start_position = Position(row=start_position.row, column=start_position.column + 1)
  392. end_position = Position(row=end_position.row, column=end_position.column - 1)
  393. single_line_view = SingleLineView(elided_lines, start_position, end_position)
  394. skeleton_parameters = create_skeleton_parameters(single_line_view.single_line)
  395. end_index = -1
  396. while True:
  397. # Find the end of the next parameter.
  398. start_index = end_index + 1
  399. end_index = skeleton_parameters.find(',', start_index)
  400. # No comma means that all parameters have been parsed.
  401. if end_index == -1:
  402. return
  403. row = single_line_view.convert_column_to_row(end_index)
  404. # Parse the parameter into a type and parameter name.
  405. skeleton_parameter = skeleton_parameters[start_index:end_index]
  406. name_offset = find_parameter_name_index(skeleton_parameter)
  407. parameter = single_line_view.single_line[start_index:end_index]
  408. yield Parameter(parameter, name_offset, row)
  409. class _FunctionState(object):
  410. """Tracks current function name and the number of lines in its body.
  411. Attributes:
  412. min_confidence: The minimum confidence level to use while checking style.
  413. """
  414. _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
  415. _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
  416. def __init__(self, min_confidence):
  417. self.min_confidence = min_confidence
  418. self.current_function = ''
  419. self.in_a_function = False
  420. self.lines_in_function = 0
  421. # Make sure these will not be mistaken for real positions (even when a
  422. # small amount is added to them).
  423. self.body_start_position = Position(-1000, 0)
  424. self.end_position = Position(-1000, 0)
  425. def begin(self, function_name, function_name_start_position, body_start_position, end_position,
  426. parameter_start_position, parameter_end_position, clean_lines):
  427. """Start analyzing function body.
  428. Args:
  429. function_name: The name of the function being tracked.
  430. function_name_start_position: Position in elided where the function name starts.
  431. body_start_position: Position in elided of the { or the ; for a prototype.
  432. end_position: Position in elided just after the final } (or ; is.
  433. parameter_start_position: Position in elided of the '(' for the parameters.
  434. parameter_end_position: Position in elided just after the ')' for the parameters.
  435. clean_lines: A CleansedLines instance containing the file.
  436. """
  437. self.in_a_function = True
  438. self.lines_in_function = -1 # Don't count the open brace line.
  439. self.current_function = function_name
  440. self.function_name_start_position = function_name_start_position
  441. self.body_start_position = body_start_position
  442. self.end_position = end_position
  443. self.is_declaration = clean_lines.elided[body_start_position.row][body_start_position.column] == ';'
  444. self.parameter_start_position = parameter_start_position
  445. self.parameter_end_position = parameter_end_position
  446. self.is_pure = False
  447. if self.is_declaration:
  448. characters_after_parameters = SingleLineView(clean_lines.elided, parameter_end_position, body_start_position).single_line
  449. self.is_pure = bool(match(r'\s*=\s*0\s*', characters_after_parameters))
  450. self._clean_lines = clean_lines
  451. self._parameter_list = None
  452. def modifiers_and_return_type(self):
  453. """Returns the modifiers and the return type."""
  454. # Go backwards from where the function name is until we encounter one of several things:
  455. # ';' or '{' or '}' or 'private:', etc. or '#' or return Position(0, 0)
  456. elided = self._clean_lines.elided
  457. start_modifiers = _rfind_in_lines(r';|\{|\}|((private|public|protected):)|(#.*)',
  458. elided, self.parameter_start_position, Position(0, 0))
  459. return SingleLineView(elided, start_modifiers, self.function_name_start_position).single_line.strip()
  460. def parameter_list(self):
  461. if not self._parameter_list:
  462. # Store the final result as a tuple since that is immutable.
  463. self._parameter_list = tuple(parameter_list(self._clean_lines.elided, self.parameter_start_position, self.parameter_end_position))
  464. return self._parameter_list
  465. def count(self, line_number):
  466. """Count line in current function body."""
  467. if self.in_a_function and line_number >= self.body_start_position.row:
  468. self.lines_in_function += 1
  469. def check(self, error, line_number):
  470. """Report if too many lines in function body.
  471. Args:
  472. error: The function to call with any errors found.
  473. line_number: The number of the line to check.
  474. """
  475. if match(r'T(EST|est)', self.current_function):
  476. base_trigger = self._TEST_TRIGGER
  477. else:
  478. base_trigger = self._NORMAL_TRIGGER
  479. trigger = base_trigger * 2 ** self.min_confidence
  480. if self.lines_in_function > trigger:
  481. error_level = int(math.log(self.lines_in_function / base_trigger, 2))
  482. # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
  483. if error_level > 5:
  484. error_level = 5
  485. error(line_number, 'readability/fn_size', error_level,
  486. 'Small and focused functions are preferred:'
  487. ' %s has %d non-comment lines'
  488. ' (error triggered by exceeding %d lines).' % (
  489. self.current_function, self.lines_in_function, trigger))
  490. def end(self):
  491. """Stop analyzing function body."""
  492. self.in_a_function = False
  493. class _IncludeError(Exception):
  494. """Indicates a problem with the include order in a file."""
  495. pass
  496. class FileInfo:
  497. """Provides utility functions for filenames.
  498. FileInfo provides easy access to the components of a file's path
  499. relative to the project root.
  500. """
  501. def __init__(self, filename):
  502. self._filename = filename
  503. def full_name(self):
  504. """Make Windows paths like Unix."""
  505. return os.path.abspath(self._filename).replace('\\', '/')
  506. def repository_name(self):
  507. """Full name after removing the local path to the repository.
  508. If we have a real absolute path name here we can try to do something smart:
  509. detecting the root of the checkout and truncating /path/to/checkout from
  510. the name so that we get header guards that don't include things like
  511. "C:\Documents and Settings\..." or "/home/username/..." in them and thus
  512. people on different computers who have checked the source out to different
  513. locations won't see bogus errors.
  514. """
  515. fullname = self.full_name()
  516. if os.path.exists(fullname):
  517. project_dir = os.path.dirname(fullname)
  518. if os.path.exists(os.path.join(project_dir, ".svn")):
  519. # If there's a .svn file in the current directory, we
  520. # recursively look up the directory tree for the top
  521. # of the SVN checkout
  522. root_dir = project_dir
  523. one_up_dir = os.path.dirname(root_dir)
  524. while os.path.exists(os.path.join(one_up_dir, ".svn")):
  525. root_dir = os.path.dirname(root_dir)
  526. one_up_dir = os.path.dirname(one_up_dir)
  527. prefix = os.path.commonprefix([root_dir, project_dir])
  528. return fullname[len(prefix) + 1:]
  529. # Not SVN? Try to find a git top level directory by
  530. # searching up from the current path.
  531. root_dir = os.path.dirname(fullname)
  532. while (root_dir != os.path.dirname(root_dir)
  533. and not os.path.exists(os.path.join(root_dir, ".git"))):
  534. root_dir = os.path.dirname(root_dir)
  535. if os.path.exists(os.path.join(root_dir, ".git")):
  536. prefix = os.path.commonprefix([root_dir, project_dir])
  537. return fullname[len(prefix) + 1:]
  538. # Don't know what to do; header guard warnings may be wrong...
  539. return fullname
  540. def split(self):
  541. """Splits the file into the directory, basename, and extension.
  542. For 'chrome/browser/browser.cpp', Split() would
  543. return ('chrome/browser', 'browser', '.cpp')
  544. Returns:
  545. A tuple of (directory, basename, extension).
  546. """
  547. googlename = self.repository_name()
  548. project, rest = os.path.split(googlename)
  549. return (project,) + os.path.splitext(rest)
  550. def base_name(self):
  551. """File base name - text after the final slash, before the final period."""
  552. return self.split()[1]
  553. def extension(self):
  554. """File extension - text following the final period."""
  555. return self.split()[2]
  556. def no_extension(self):
  557. """File has no source file extension."""
  558. return '/'.join(self.split()[0:2])
  559. def is_source(self):
  560. """File has a source file extension."""
  561. return self.extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
  562. # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard.
  563. _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
  564. r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
  565. # Matches strings. Escape codes should already be removed by ESCAPES.
  566. _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
  567. # Matches characters. Escape codes should already be removed by ESCAPES.
  568. _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
  569. # Matches multi-line C++ comments.
  570. # This RE is a little bit more complicated than one might expect, because we
  571. # have to take care of space removals tools so we can handle comments inside
  572. # statements better.
  573. # The current rule is: We only clear spaces from both sides when we're at the
  574. # end of the line. Otherwise, we try to remove spaces from the right side,
  575. # if this doesn't work we try on left side but only if there's a non-character
  576. # on the right.
  577. _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
  578. r"""(\s*/\*.*\*/\s*$|
  579. /\*.*\*/\s+|
  580. \s+/\*.*\*/(?=\W)|
  581. /\*.*\*/)""", re.VERBOSE)
  582. def is_cpp_string(line):
  583. """Does line terminate so, that the next symbol is in string constant.
  584. This function does not consider single-line nor multi-line comments.
  585. Args:
  586. line: is a partial line of code starting from the 0..n.
  587. Returns:
  588. True, if next character appended to 'line' is inside a
  589. string constant.
  590. """
  591. line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
  592. return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
  593. def find_next_multi_line_comment_start(lines, line_index):
  594. """Find the beginning marker for a multiline comment."""
  595. while line_index < len(lines):
  596. if lines[line_index].strip().startswith('/*'):
  597. # Only return this marker if the comment goes beyond this line
  598. if lines[line_index].strip().find('*/', 2) < 0:
  599. return line_index
  600. line_index += 1
  601. return len(lines)
  602. def find_next_multi_line_comment_end(lines, line_index):
  603. """We are inside a comment, find the end marker."""
  604. while line_index < len(lines):
  605. if lines[line_index].strip().endswith('*/'):
  606. return line_index
  607. line_index += 1
  608. return len(lines)
  609. def remove_multi_line_comments_from_range(lines, begin, end):
  610. """Clears a range of lines for multi-line comments."""
  611. # Having // dummy comments makes the lines non-empty, so we will not get
  612. # unnecessary blank line warnings later in the code.
  613. for i in range(begin, end):
  614. lines[i] = '// dummy'
  615. def remove_multi_line_comments(lines, error):
  616. """Removes multiline (c-style) comments from lines."""
  617. line_index = 0
  618. while line_index < len(lines):
  619. line_index_begin = find_next_multi_line_comment_start(lines, line_index)
  620. if line_index_begin >= len(lines):
  621. return
  622. line_index_end = find_next_multi_line_comment_end(lines, line_index_begin)
  623. if line_index_end >= len(lines):
  624. error(line_index_begin + 1, 'readability/multiline_comment', 5,
  625. 'Could not find end of multi-line comment')
  626. return
  627. remove_multi_line_comments_from_range(lines, line_index_begin, line_index_end + 1)
  628. line_index = line_index_end + 1
  629. def cleanse_comments(line):
  630. """Removes //-comments and single-line C-style /* */ comments.
  631. Args:
  632. line: A line of C++ source.
  633. Returns:
  634. The line with single-line comments removed.
  635. """
  636. comment_position = line.find('//')
  637. if comment_position != -1 and not is_cpp_string(line[:comment_position]):
  638. line = line[:comment_position]
  639. # get rid of /* ... */
  640. return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
  641. class CleansedLines(object):
  642. """Holds 3 copies of all lines with different preprocessing applied to them.
  643. 1) elided member contains lines without strings and comments,
  644. 2) lines member contains lines without comments, and
  645. 3) raw member contains all the lines without processing.
  646. All these three members are of <type 'list'>, and of the same length.
  647. """
  648. def __init__(self, lines):
  649. self.elided = []
  650. self.lines = []
  651. self.raw_lines = lines
  652. self._num_lines = len(lines)
  653. for line_number in range(len(lines)):
  654. self.lines.append(cleanse_comments(lines[line_number]))
  655. elided = self.collapse_strings(lines[line_number])
  656. self.elided.append(cleanse_comments(elided))
  657. def num_lines(self):
  658. """Returns the number of lines represented."""
  659. return self._num_lines
  660. @staticmethod
  661. def collapse_strings(elided):
  662. """Collapses strings and chars on a line to simple "" or '' blocks.
  663. We nix strings first so we're not fooled by text like '"http://"'
  664. Args:
  665. elided: The line being processed.
  666. Returns:
  667. The line with collapsed strings.
  668. """
  669. if not _RE_PATTERN_INCLUDE.match(elided):
  670. # Remove escaped characters first to make quote/single quote collapsing
  671. # basic. Things that look like escaped characters shouldn't occur
  672. # outside of strings and chars.
  673. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
  674. elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
  675. elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
  676. return elided
  677. def close_expression(elided, position):
  678. """If input points to ( or { or [, finds the position that closes it.
  679. If elided[position.row][position.column] points to a '(' or '{' or '[',
  680. finds the line_number/pos that correspond to the closing of the expression.
  681. Args:
  682. elided: A CleansedLines.elided instance containing the file.
  683. position: The position of the opening item.
  684. Returns:
  685. The Position *past* the closing brace, or Position(len(elided), -1)
  686. if we never find a close. Note we ignore strings and comments when matching.
  687. """
  688. line = elided[position.row]
  689. start_character = line[position.column]
  690. if start_character == '(':
  691. enclosing_character_regex = r'[\(\)]'
  692. elif start_character == '[':
  693. enclosing_character_regex = r'[\[\]]'
  694. elif start_character == '{':
  695. enclosing_character_regex = r'[\{\}]'
  696. else:
  697. return Position(len(elided), -1)
  698. current_column = position.column + 1
  699. line_number = position.row
  700. net_open = 1
  701. for line in elided[position.row:]:
  702. line = line[current_column:]
  703. # Search the current line for opening and closing characters.
  704. while True:
  705. next_enclosing_character = search(enclosing_character_regex, line)
  706. # No more on this line.
  707. if not next_enclosing_character:
  708. break
  709. current_column += next_enclosing_character.end(0)
  710. line = line[next_enclosing_character.end(0):]
  711. if next_enclosing_character.group(0) == start_character:
  712. net_open += 1
  713. else:
  714. net_open -= 1
  715. if not net_open:
  716. return Position(line_number, current_column)
  717. # Proceed to the next line.
  718. line_number += 1
  719. current_column = 0
  720. # The given item was not closed.
  721. return Position(len(elided), -1)
  722. def check_for_copyright(lines, error):
  723. """Logs an error if no Copyright message appears at the top of the file."""
  724. # We'll say it should occur by line 10. Don't forget there's a
  725. # dummy line at the front.
  726. for line in xrange(1, min(len(lines), 11)):
  727. if re.search(r'Copyright', lines[line], re.I):
  728. break
  729. else: # means no copyright line was found
  730. error(0, 'legal/copyright', 5,
  731. 'No copyright message found. '
  732. 'You should have a line: "Copyright [year] <Copyright Owner>"')
  733. def get_header_guard_cpp_variable(filename):
  734. """Returns the CPP variable that should be used as a header guard.
  735. Args:
  736. filename: The name of a C++ header file.
  737. Returns:
  738. The CPP variable that should be used as a header guard in the
  739. named file.
  740. """
  741. # Restores original filename in case that style checker is invoked from Emacs's
  742. # flymake.
  743. filename = re.sub(r'_flymake\.h$', '.h', filename)
  744. standard_name = sub(r'[-.\s]', '_', os.path.basename(filename))
  745. # Files under WTF typically have header guards that start with WTF_.
  746. if '/wtf/' in filename:
  747. special_name = "WTF_" + standard_name
  748. else:
  749. special_name = standard_name
  750. return (special_name, standard_name)
  751. def check_for_header_guard(filename, lines, error):
  752. """Checks that the file contains a header guard.
  753. Logs an error if no #ifndef header guard is present. For other
  754. headers, checks that the full pathname is used.
  755. Args:
  756. filename: The name of the C++ header file.
  757. lines: An array of strings, each representing a line of the file.
  758. error: The function to call with any errors found.
  759. """
  760. cppvar = get_header_guard_cpp_variable(filename)
  761. ifndef = None
  762. ifndef_line_number = 0
  763. define = None
  764. for line_number, line in enumerate(lines):
  765. line_split = line.split()
  766. if len(line_split) >= 2:
  767. # find the first occurrence of #ifndef and #define, save arg
  768. if not ifndef and line_split[0] == '#ifndef':
  769. # set ifndef to the header guard presented on the #ifndef line.
  770. ifndef = line_split[1]
  771. ifndef_line_number = line_number
  772. if not define and line_split[0] == '#define':
  773. define = line_split[1]
  774. if define and ifndef:
  775. break
  776. if not ifndef or not define or ifndef != define:
  777. error(0, 'build/header_guard', 5,
  778. 'No #ifndef header guard found, suggested CPP variable is: %s' %
  779. cppvar[0])
  780. return
  781. # The guard should be File_h.
  782. if ifndef not in cppvar:
  783. error(ifndef_line_number, 'build/header_guard', 5,
  784. '#ifndef header guard has wrong style, please use: %s' % cppvar[0])
  785. def check_for_unicode_replacement_characters(lines, error):
  786. """Logs an error for each line containing Unicode replacement characters.
  787. These indicate that either the file contained invalid UTF-8 (likely)
  788. or Unicode replacement characters (which it shouldn't). Note that
  789. it's possible for this to throw off line numbering if the invalid
  790. UTF-8 occurred adjacent to a newline.
  791. Args:
  792. lines: An array of strings, each representing a line of the file.
  793. error: The function to call with any errors found.
  794. """
  795. for line_number, line in enumerate(lines):
  796. if u'\ufffd' in line:
  797. error(line_number, 'readability/utf8', 5,
  798. 'Line contains invalid UTF-8 (or Unicode replacement character).')
  799. def check_for_new_line_at_eof(lines, error):
  800. """Logs an error if there is no newline char at the end of the file.
  801. Args:
  802. lines: An array of strings, each representing a line of the file.
  803. error: The function to call with any errors found.
  804. """
  805. # The array lines() was created by adding two newlines to the
  806. # original file (go figure), then splitting on \n.
  807. # To verify that the file ends in \n, we just have to make sure the
  808. # last-but-two element of lines() exists and is empty.
  809. if len(lines) < 3 or lines[-2]:
  810. error(len(lines) - 2, 'whitespace/ending_newline', 5,
  811. 'Could not find a newline character at the end of the file.')
  812. def check_for_multiline_comments_and_strings(clean_lines, line_number, error):
  813. """Logs an error if we see /* ... */ or "..." that extend past one line.
  814. /* ... */ comments are legit inside macros, for one line.
  815. Otherwise, we prefer // comments, so it's ok to warn about the
  816. other. Likewise, it's ok for strings to extend across multiple
  817. lines, as long as a line continuation character (backslash)
  818. terminates each line. Although not currently prohibited by the C++
  819. style guide, it's ugly and unnecessary. We don't do well with either
  820. in this lint program, so we warn about both.
  821. Args:
  822. clean_lines: A CleansedLines instance containing the file.
  823. line_number: The number of the line to check.
  824. error: The function to call with any errors found.
  825. """
  826. line = clean_lines.elided[line_number]
  827. # Remove all \\ (escaped backslashes) from the line. They are OK, and the
  828. # second (escaped) slash may trigger later \" detection erroneously.
  829. line = line.replace('\\\\', '')
  830. if line.count('/*') > line.count('*/'):
  831. error(line_number, 'readability/multiline_comment', 5,
  832. 'Complex multi-line /*...*/-style comment found. '
  833. 'Lint may give bogus warnings. '
  834. 'Consider replacing these with //-style comments, '
  835. 'with #if 0...#endif, '
  836. 'or with more clearly structured multi-line comments.')
  837. if (line.count('"') - line.count('\\"')) % 2:
  838. error(line_number, 'readability/multiline_string', 5,
  839. 'Multi-line string ("...") found. This lint script doesn\'t '
  840. 'do well with such strings, and may give bogus warnings. They\'re '
  841. 'ugly and unnecessary, and you should use concatenation instead".')
  842. _THREADING_LIST = (
  843. ('asctime(', 'asctime_r('),
  844. ('ctime(', 'ctime_r('),
  845. ('getgrgid(', 'getgrgid_r('),
  846. ('getgrnam(', 'getgrnam_r('),
  847. ('getlogin(', 'getlogin_r('),
  848. ('getpwnam(', 'getpwnam_r('),
  849. ('getpwuid(', 'getpwuid_r('),
  850. ('gmtime(', 'gmtime_r('),
  851. ('localtime(', 'localtime_r('),
  852. ('rand(', 'rand_r('),
  853. ('readdir(', 'readdir_r('),
  854. ('strtok(', 'strtok_r('),
  855. ('ttyname(', 'ttyname_r('),
  856. )
  857. def check_posix_threading(clean_lines, line_number, error):
  858. """Checks for calls to thread-unsafe functions.
  859. Much code has been originally written without consideration of
  860. multi-threading. Also, engineers are relying on their old experience;
  861. they have learned posix before threading extensions were added. These
  862. tests guide the engineers to use thread-safe functions (when using
  863. posix directly).
  864. Args:
  865. clean_lines: A CleansedLines instance containing the file.
  866. line_number: The number of the line to check.
  867. error: The function to call with any errors found.
  868. """
  869. line = clean_lines.elided[line_number]
  870. for single_thread_function, multithread_safe_function in _THREADING_LIST:
  871. index = line.find(single_thread_function)
  872. # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
  873. if index >= 0 and (index == 0 or (not line[index - 1].isalnum()
  874. and line[index - 1] not in ('_', '.', '>'))):
  875. error(line_number, 'runtime/threadsafe_fn', 2,
  876. 'Consider using ' + multithread_safe_function +
  877. '...) instead of ' + single_thread_function +
  878. '...) for improved thread safety.')
  879. # Matches invalid increment: *count++, which moves pointer instead of
  880. # incrementing a value.
  881. _RE_PATTERN_INVALID_INCREMENT = re.compile(
  882. r'^\s*\*\w+(\+\+|--);')
  883. def check_invalid_increment(clean_lines, line_number, error):
  884. """Checks for invalid increment *count++.
  885. For example following function:
  886. void increment_counter(int* count) {
  887. *count++;
  888. }
  889. is invalid, because it effectively does count++, moving pointer, and should
  890. be replaced with ++*count, (*count)++ or *count += 1.
  891. Args:
  892. clean_lines: A CleansedLines instance containing the file.
  893. line_number: The number of the line to check.
  894. error: The function to call with any errors found.
  895. """
  896. line = clean_lines.elided[line_number]
  897. if _RE_PATTERN_INVALID_INCREMENT.match(line):
  898. error(line_number, 'runtime/invalid_increment', 5,
  899. 'Changing pointer instead of value (or unused value of operator*).')
  900. class _ClassInfo(object):
  901. """Stores information about a class."""
  902. def __init__(self, name, line_number):
  903. self.name = name
  904. self.line_number = line_number
  905. self.seen_open_brace = False
  906. self.is_derived = False
  907. self.virtual_method_line_number = None
  908. self.has_virtual_destructor = False
  909. self.brace_depth = 0
  910. class _ClassState(object):
  911. """Holds the current state of the parse relating to class declarations.
  912. It maintains a stack of _ClassInfos representing the parser's guess
  913. as to the current nesting of class declarations. The innermost class
  914. is at the top (back) of the stack. Typically, the stack will either
  915. be empty or have exactly one entry.
  916. """
  917. def __init__(self):
  918. self.classinfo_stack = []
  919. def check_finished(self, error):
  920. """Checks that all classes have been completely parsed.
  921. Call this when all lines in a file have been processed.
  922. Args:
  923. error: The function to call with any errors found.
  924. """
  925. if self.classinfo_stack:
  926. # Note: This test can result in false positives if #ifdef constructs
  927. # get in the way of brace matching. See the testBuildClass test in
  928. # cpp_style_unittest.py for an example of this.
  929. error(self.classinfo_stack[0].line_number, 'build/class', 5,
  930. 'Failed to find complete declaration of class %s' %
  931. self.classinfo_stack[0].name)
  932. class _FileState(object):
  933. def __init__(self, clean_lines, file_extension):
  934. self._did_inside_namespace_indent_warning = False
  935. self._clean_lines = clean_lines
  936. if file_extension in ['m', 'mm']:
  937. self._is_objective_c = True
  938. elif file_extension == 'h':
  939. # In the case of header files, it is unknown if the file
  940. # is objective c or not, so set this value to None and then
  941. # if it is requested, use heuristics to guess the value.
  942. self._is_objective_c = None
  943. else:
  944. self._is_objective_c = False
  945. self._is_c = file_extension == 'c'
  946. def set_did_inside_namespace_indent_warning(self):
  947. self._did_inside_namespace_indent_warning = True
  948. def did_inside_namespace_indent_warning(self):
  949. return self._did_inside_namespace_indent_warning
  950. def is_objective_c(self):
  951. if self._is_objective_c is None:
  952. for line in self._clean_lines.elided:
  953. # Starting with @ or #import seem like the best indications
  954. # that we have an Objective C file.
  955. if line.startswith("@") or line.startswith("#import"):
  956. self._is_objective_c = True
  957. break
  958. else:
  959. self._is_objective_c = False
  960. return self._is_objective_c
  961. def is_c_or_objective_c(self):
  962. """Return whether the file extension corresponds to C or Objective-C."""
  963. return self._is_c or self.is_objective_c()
  964. def check_for_non_standard_constructs(clean_lines, line_number,
  965. class_state, error):
  966. """Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
  967. Complain about several constructs which gcc-2 accepts, but which are
  968. not standard C++. Warning about these in lint is one way to ease the
  969. transition to new compilers.
  970. - put storage class first (e.g. "static const" instead of "const static").
  971. - "%lld" instead of %qd" in printf-type functions.
  972. - "%1$d" is non-standard in printf-type functions.
  973. - "\%" is an undefined character escape sequence.
  974. - text after #endif is not allowed.
  975. - invalid inner-style forward declaration.
  976. - >? and <? operators, and their >?= and <?= cousins.
  977. - classes with virtual methods need virtual destructors (compiler warning
  978. available, but not turned on yet.)
  979. Additionally, check for constructor/destructor style violations as it
  980. is very convenient to do so while checking for gcc-2 compliance.
  981. Args:
  982. clean_lines: A CleansedLines instance containing the file.
  983. line_number: The number of the line to check.
  984. class_state: A _ClassState instance which maintains information about
  985. the current stack of nested class declarations being parsed.
  986. error: A callable to which errors are reported, which takes parameters:
  987. line number, error level, and message
  988. """
  989. # Remove comments from the line, but leave in strings for now.
  990. line = clean_lines.lines[line_number]
  991. if search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
  992. error(line_number, 'runtime/printf_format', 3,
  993. '%q in format strings is deprecated. Use %ll instead.')
  994. if search(r'printf\s*\(.*".*%\d+\$', line):
  995. error(line_number, 'runtime/printf_format', 2,
  996. '%N$ formats are unconventional. Try rewriting to avoid them.')
  997. # Remove escaped backslashes before looking for undefined escapes.
  998. line = line.replace('\\\\', '')
  999. if search(r'("|\').*\\(%|\[|\(|{)', line):
  1000. error(line_number, 'build/printf_format', 3,
  1001. '%, [, (, and { are undefined character escapes. Unescape them.')
  1002. # For the rest, work with both comments and strings removed.
  1003. line = clean_lines.elided[line_number]
  1004. if search(r'\b(const|volatile|void|char|short|int|long'
  1005. r'|float|double|signed|unsigned'
  1006. r'|schar|u?int8|u?int16|u?int32|u?int64)'
  1007. r'\s+(auto|register|static|extern|typedef)\b',
  1008. line):
  1009. error(line_number, 'build/storage_class', 5,
  1010. 'Storage class (static, extern, typedef, etc) should be first.')
  1011. if match(r'\s*#\s*endif\s*[^/\s]+', line):
  1012. error(line_number, 'build/endif_comment', 5,
  1013. 'Uncommented text after #endif is non-standard. Use a comment.')
  1014. if match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
  1015. error(line_number, 'build/forward_decl', 5,
  1016. 'Inner-style forward declarations are invalid. Remove this line.')
  1017. if search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', line):
  1018. error(line_number, 'build/deprecated', 3,
  1019. '>? and <? (max and min) operators are non-standard and deprecated.')
  1020. # Track class entry and exit, and attempt to find cases within the
  1021. # class declaration that don't meet the C++ style
  1022. # guidelines. Tracking is very dependent on the code matching Google
  1023. # style guidelines, but it seems to perform well enough in testing
  1024. # to be a worthwhile addition to the checks.
  1025. classinfo_stack = class_state.classinfo_stack
  1026. # Look for a class declaration
  1027. class_decl_match = match(
  1028. r'\s*(template\s*<[\w\s<>,:]*>\s*)?(class|struct)\s+(\w+(::\w+)*)', line)
  1029. if class_decl_match:
  1030. classinfo_stack.append(_ClassInfo(class_decl_match.group(3), line_number))
  1031. # Everything else in this function uses the top of the stack if it's
  1032. # not empty.
  1033. if not classinfo_stack:
  1034. return
  1035. classinfo = classinfo_stack[-1]
  1036. # If the opening brace hasn't been seen look for it and also
  1037. # parent class declarations.
  1038. if not classinfo.seen_open_brace:
  1039. # If the line has a ';' in it, assume it's a forward declaration or
  1040. # a single-line class declaration, which we won't process.
  1041. if line.find(';') != -1:
  1042. classinfo_stack.pop()
  1043. return
  1044. classinfo.seen_open_brace = (line.find('{') != -1)
  1045. # Look for a bare ':'
  1046. if search('(^|[^:]):($|[^:])', line):
  1047. classinfo.is_derived = True
  1048. if not classinfo.seen_open_brace:
  1049. return # Everything else in this function is for after open brace
  1050. # The class may have been declared with namespace or classname qualifiers.
  1051. # The constructor and destructor will not have those qualifiers.
  1052. base_classname = classinfo.name.split('::')[-1]
  1053. # Look for single-argument constructors that aren't marked explicit.
  1054. # Technically a valid construct, but against style.
  1055. args = match(r'(?<!explicit)\s+%s\s*\(([^,()]+)\)'
  1056. % re.escape(base_classname),
  1057. line)
  1058. if (args
  1059. and args.group(1) != 'void'
  1060. and not match(r'(const\s+)?%s\s*&' % re.escape(base_classname),
  1061. args.group(1).strip())):
  1062. error(line_number, 'runtime/explicit', 5,
  1063. 'Single-argument constructors should be marked explicit.')
  1064. # Look for methods declared virtual.
  1065. if search(r'\bvirtual\b', line):
  1066. classinfo.virtual_method_line_number = line_number
  1067. # Only look for a destructor declaration on the same line. It would
  1068. # be extremely unlikely for the destructor declaration to occupy
  1069. # more than one line.
  1070. if search(r'~%s\s*\(' % base_classname, line):
  1071. classinfo.has_virtual_destructor = True
  1072. # Look for class end.
  1073. brace_depth = classinfo.brace_depth
  1074. brace_depth = brace_depth + line.count('{') - line.count('}')
  1075. if brace_depth <= 0:
  1076. classinfo = classinfo_stack.pop()
  1077. # Try to detect missing virtual destructor declarations.
  1078. # For now, only warn if a non-derived class with virtual methods lacks
  1079. # a virtual destructor. This is to make it less likely that people will
  1080. # declare derived virtual destructors without declaring the base
  1081. # destructor virtual.
  1082. if ((classinfo.virtual_method_line_number is not None)
  1083. and (not classinfo.has_virtual_destructor)
  1084. and (not classinfo.is_derived)): # Only warn for base classes
  1085. error(classinfo.line_number, 'runtime/virtual', 4,
  1086. 'The class %s probably needs a virtual destructor due to '
  1087. 'having virtual method(s), one declared at line %d.'
  1088. % (classinfo.name, classinfo.virtual_method_line_number))
  1089. else:
  1090. classinfo.brace_depth = brace_depth
  1091. def check_spacing_for_function_call(line, line_number, error):
  1092. """Checks for the correctness of various spacing around function calls.
  1093. Args:
  1094. line: The text of the line to check.
  1095. line_number: The number of the line to check.
  1096. error: The function to call with any errors found.
  1097. """
  1098. # Since function calls often occur inside if/for/foreach/while/switch
  1099. # expressions - which have their own, more liberal conventions - we
  1100. # first see if we should be looking inside such an expression for a
  1101. # function call, to which we can apply more strict standards.
  1102. function_call = line # if there's no control flow construct, look at whole line
  1103. for pattern in (r'\bif\s*\((.*)\)\s*{',
  1104. r'\bfor\s*\((.*)\)\s*{',
  1105. r'\bforeach\s*\((.*)\)\s*{',
  1106. r'\bwhile\s*\((.*)\)\s*[{;]',
  1107. r'\bswitch\s*\((.*)\)\s*{'):
  1108. matched = search(pattern, line)
  1109. if matched:
  1110. function_call = matched.group(1) # look inside the parens for function calls
  1111. break
  1112. # Except in if/for/foreach/while/switch, there should never be space
  1113. # immediately inside parens (eg "f( 3, 4 )"). We make an exception
  1114. # for nested parens ( (a+b) + c ). Likewise, there should never be
  1115. # a space before a ( when it's a function argument. I assume it's a
  1116. # function argument when the char before the whitespace is legal in
  1117. # a function name (alnum + _) and we're not starting a macro. Also ignore
  1118. # pointers and references to arrays and functions coz they're too tricky:
  1119. # we use a very simple way to recognize these:
  1120. # " (something)(maybe-something)" or
  1121. # " (something)(maybe-something," or
  1122. # " (something)[something]"
  1123. # Note that we assume the contents of [] to be short enough that
  1124. # they'll never need to wrap.
  1125. if ( # Ignore control structures.
  1126. not search(r'\b(if|for|foreach|while|switch|return|new|delete)\b', function_call)
  1127. # Ignore pointers/references to functions.
  1128. and not search(r' \([^)]+\)\([^)]*(\)|,$)', function_call)
  1129. # Ignore pointers/references to arrays.
  1130. and not search(r' \([^)]+\)\[[^\]]+\]', function_call)):
  1131. if search(r'\w\s*\([ \t](?!\s*\\$)', function_call): # a ( used for a fn call
  1132. error(line_number, 'whitespace/parens', 4,
  1133. 'Extra space after ( in function call')
  1134. elif search(r'\([ \t]+(?!(\s*\\)|\()', function_call):
  1135. error(line_number, 'whitespace/parens', 2,
  1136. 'Extra space after (')
  1137. if (search(r'\w\s+\(', function_call)
  1138. and not match(r'\s*(#|typedef)', function_call)):
  1139. error(line_number, 'whitespace/parens', 4,
  1140. 'Extra space before ( in function call')
  1141. # If the ) is followed only by a newline or a { + newline, assume it's
  1142. # part of a control statement (if/while/etc), and don't complain
  1143. if search(r'[^)\s]\s+\)(?!\s*$|{\s*$)', function_call):
  1144. error(line_number, 'whitespace/parens', 2,
  1145. 'Extra space before )')
  1146. def is_blank_line(line):
  1147. """Returns true if the given line is blank.
  1148. We consider a line to be blank if the line is empty or consists of
  1149. only white spaces.
  1150. Args:
  1151. line: A line of a string.
  1152. Returns:
  1153. True, if the given line is blank.
  1154. """
  1155. return not line or line.isspace()
  1156. def detect_functions(clean_lines, line_number, function_state, error):
  1157. """Finds where functions start and end.
  1158. Uses a simplistic algorithm assuming other style guidelines
  1159. (especially spacing) are followed.
  1160. Trivial bodies are unchecked, so constructors with huge initializer lists
  1161. may be missed.
  1162. Args:
  1163. clean_lines: A CleansedLines instance containing the file.
  1164. line_number: The number of the line to check.
  1165. function_state: Current function name and lines in body so far.
  1166. error: The function to call with any errors found.
  1167. """
  1168. # Are we now past the end of a function?
  1169. if function_state.end_position.row + 1 == line_number:
  1170. function_state.end()
  1171. # If we're in a function, don't try to detect a new one.
  1172. if function_state.in_a_function:
  1173. return
  1174. lines = clean_lines.lines
  1175. line = lines[line_number]
  1176. raw = clean_lines.raw_lines
  1177. raw_line = raw[line_number]
  1178. # Lines ending with a \ indicate a macro. Don't try to check them.
  1179. if raw_line.endswith('\\'):
  1180. return
  1181. regexp = r'\s*(\w(\w|::|\*|\&|\s|<|>|,|~|(operator\s*(/|-|=|!|\+)+))*)\(' # decls * & space::name( ...
  1182. match_result = match(regexp, line)
  1183. if not match_result:
  1184. return
  1185. # If the name is all caps and underscores, figure it's a macro and
  1186. # ignore it, unless it's TEST or TEST_F.
  1187. function_name = match_result.group(1).split()[-1]
  1188. if function_name != 'TEST' and function_name != 'TEST_F' and match(r'[A-Z_]+$', function_name):
  1189. return
  1190. joined_line = ''
  1191. for start_line_number in xrange(line_number, clean_lines.num_lines()):
  1192. start_line = clean_lines.elided[start_line_number]
  1193. joined_line += ' ' + start_line.lstrip()
  1194. body_match = search(r'{|;', start_line)
  1195. if body_match:
  1196. body_start_position = Position(start_line_number, body_match.start(0))
  1197. # Replace template constructs with _ so that no spaces remain in the function name,
  1198. # while keeping the column numbers of other characters the same as "line".
  1199. line_with_no_templates = iteratively_replace_matches_with_char(r'<[^<>]*>', '_', line)
  1200. match_function = search(r'((\w|:|<|>|,|~|(operator\s*(/|-|=|!|\+)+))*)\(', line_with_no_templates)
  1201. if not match_function:
  1202. return # The '(' must have been inside of a template.
  1203. # Use the column numbers from the modified line to find the
  1204. # function name in the original line.
  1205. function = line[match_function.start(1):match_function.end(1)]
  1206. function_name_start_position = Position(line_number, match_function.start(1))
  1207. if match(r'TEST', function): # Handle TEST... macros
  1208. parameter_regexp = search(r'(\(.*\))', joined_line)
  1209. if parameter_regexp: # Ignore bad syntax
  1210. function += parameter_regexp.group(1)
  1211. else:
  1212. function += '()'
  1213. parameter_start_position = Position(line_number, match_function.end(1))
  1214. parameter_end_position = close_expression(clean_lines.elided, parameter_start_position)
  1215. if parameter_end_position.row == len(clean_lines.elided):
  1216. # No end was found.
  1217. return
  1218. if start_line[body_start_position.column] == ';':
  1219. end_position = Position(body_start_position.row, body_start_position.column + 1)
  1220. else:
  1221. end_position = close_expression(clean_lines.elided, body_start_position)
  1222. # Check for nonsensical positions. (This happens in test cases which check code snippets.)
  1223. if parameter_end_position > body_start_position:
  1224. return
  1225. function_state.begin(function, function_name_start_position, body_start_position, end_position,
  1226. parameter_start_position, parameter_end_position, clean_lines)
  1227. return
  1228. # No body for the function (or evidence of a non-function) was found.
  1229. error(line_number, 'readability/fn_size', 5,
  1230. 'Lint failed to find start of function body.')
  1231. def check_for_function_lengths(clean_lines, line_number, function_state, error):
  1232. """Reports for long function bodies.
  1233. For an overview why this is done, see:
  1234. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
  1235. Blank/comment lines are not counted so as to avoid encouraging the removal
  1236. of vertical space and commments just to get through a lint check.
  1237. NOLINT *on the last line of a function* disables this check.
  1238. Args:
  1239. clean_lines: A CleansedLines instance containing the file.
  1240. line_number: The number of the line to check.
  1241. function_state: Current function name and lines in body so far.
  1242. error: The function to call with any errors found.
  1243. """
  1244. lines = clean_lines.lines
  1245. line = lines[line_number]
  1246. raw = clean_lines.raw_lines
  1247. raw_line = raw[line_number]
  1248. if function_state.end_position.row == line_number: # last line
  1249. if not search(r'\bNOLINT\b', raw_line):
  1250. function_state.check(error, line_number)
  1251. elif not match(r'^\s*$', line):
  1252. function_state.count(line_number) # Count non-blank/non-comment lines.
  1253. def _check_parameter_name_against_text(parameter, text, error):
  1254. """Checks to see if the parameter name is contained within the text.
  1255. Return false if the check failed (i.e. an error was produced).
  1256. """
  1257. # Treat 'lower with underscores' as a canonical form because it is
  1258. # case insensitive while still retaining word breaks. (This ensures that
  1259. # 'elate' doesn't look like it is duplicating of 'NateLate'.)
  1260. canonical_parameter_name = parameter.lower_with_underscores_name()
  1261. # Appends "object" to all text to catch variables that did the same (but only
  1262. # do this when the parameter name is more than a single character to avoid
  1263. # flagging 'b' which may be an ok variable when used in an rgba function).
  1264. if len(canonical_parameter_name) > 1:
  1265. text = sub(r'(\w)\b', r'\1Object', text)
  1266. canonical_text = _convert_to_lower_with_underscores(text)
  1267. # Used to detect cases like ec for ExceptionCode.
  1268. acronym = _create_acronym(text).lower()
  1269. if canonical_text.find(canonical_parameter_name) != -1 or acronym.find(canonical_parameter_name) != -1:
  1270. error(parameter.row, 'readability/parameter_name', 5,
  1271. 'The parameter name "%s" adds no information, so it should be removed.' % parameter.name)
  1272. return False
  1273. return True
  1274. def check_function_definition_and_pass_ptr(type_text, row, location_description, error):
  1275. """Check that function definitions for use Pass*Ptr instead of *Ptr.
  1276. Args:
  1277. type_text: A string containing the type. (For return values, it may contain more than the type.)
  1278. row: The row number of the type.
  1279. location_description: Used to indicate where the type is. This is either 'parameter' or 'return'.
  1280. error: The function to call with any errors found.
  1281. """
  1282. match_ref_or_own_ptr = '(?=\W|^)(Ref|Own)Ptr(?=\W)'
  1283. bad_type_usage = search(match_ref_or_own_ptr, type_text)
  1284. if not bad_type_usage or type_text.endswith('&'):
  1285. return
  1286. type_name = bad_type_usage.group(0)
  1287. error(row, 'readability/pass_ptr', 5,
  1288. 'The %s type should use Pass%s instead of %s.' % (location_description, type_name, type_name))
  1289. def check_function_definition(filename, file_extension, clean_lines, line_number, function_state, error):
  1290. """Check that function definitions for style issues.
  1291. Specifically, check that parameter names in declarations add information.
  1292. Args:
  1293. filename: Filename of the file that is being processed.
  1294. file_extension: The current file extension, without the leading dot.
  1295. clean_lines: A CleansedLines instance containing the file.
  1296. line_number: The number of the line to check.
  1297. function_state: Current function name and lines in body so far.
  1298. error: The function to call with any errors found.
  1299. """
  1300. if line_number != function_state.body_start_position.row:
  1301. return
  1302. modifiers_and_return_type = function_state.modifiers_and_return_type()
  1303. if filename.find('/chromium/') != -1 and search(r'\bWEBKIT_EXPORT\b', modifiers_and_return_type):
  1304. if filename.find('/chromium/public/') == -1:
  1305. error(function_state.function_name_start_position.row, 'readability/webkit_export', 5,
  1306. 'WEBKIT_EXPORT should only appear in the chromium public directory.')
  1307. elif not file_extension == "h":
  1308. error(function_state.function_name_start_position.row, 'readability/webkit_export', 5,
  1309. 'WEBKIT_EXPORT should only be used in header files.')
  1310. elif not function_state.is_declaration or search(r'\binline\b', modifiers_and_return_type):
  1311. error(function_state.function_name_start_position.row, 'readability/webkit_export', 5,
  1312. 'WEBKIT_EXPORT should not be used on a function with a body.')
  1313. elif function_state.is_pure:
  1314. error(function_state.function_name_start_position.row, 'readability/webkit_export', 5,
  1315. 'WEBKIT_EXPORT should not be used with a pure virtual function.')
  1316. check_function_definition_and_pass_ptr(modifiers_and_return_type, function_state.function_name_start_position.row, 'return', error)
  1317. parameter_list = function_state.parameter_list()
  1318. for parameter in parameter_list:
  1319. check_function_definition_and_pass_ptr(parameter.type, parameter.row, 'parameter', error)
  1320. # Do checks specific to function declarations and parameter names.
  1321. if not function_state.is_declaration or not parameter.name:
  1322. continue
  1323. # Check the parameter name against the function name for single parameter set functions.
  1324. if len(parameter_list) == 1 and match('set[A-Z]', function_state.current_function):
  1325. trimmed_function_name = function_state.current_function[len('set'):]
  1326. if not _check_parameter_name_against_text(parameter, trimmed_function_name, error):
  1327. continue # Since an error was noted for this name, move to the next parameter.
  1328. # Check the parameter name against the type.
  1329. if not _check_parameter_name_against_text(parameter, parameter.type, error):
  1330. continue # Since an error was noted for this name, move to the next parameter.
  1331. def check_pass_ptr_usage(clean_lines, line_number, function_state, error):
  1332. """Check for proper usage of Pass*Ptr.
  1333. Currently this is limited to detecting declarations of Pass*Ptr
  1334. variables inside of functions.
  1335. Args:
  1336. clean_lines: A CleansedLines instance containing the file.
  1337. line_number: The number of the line to check.
  1338. function_state: Current function name and lines in body so far.
  1339. error: The function to call with any errors found.
  1340. """
  1341. if not function_state.in_a_function:
  1342. return
  1343. lines = clean_lines.lines
  1344. line = lines[line_number]
  1345. if line_number > function_state.body_start_position.row:
  1346. matched_pass_ptr = match(r'^\s*Pass([A-Z][A-Za-z]*)Ptr<', line)
  1347. if matched_pass_ptr:
  1348. type_name = 'Pass%sPtr' % matched_pass_ptr.group(1)
  1349. error(line_number, 'readability/pass_ptr', 5,
  1350. 'Local variables should never be %s (see '
  1351. 'http://webkit.org/coding/RefPtr.html).' % type_name)
  1352. def check_spacing(file_extension, clean_lines, line_number, error):
  1353. """Checks for the correctness of various spacing issues in the code.
  1354. Things we check for: spaces around operators, spaces after
  1355. if/for/while/switch, no spaces around parens in function calls, two
  1356. spaces between code and comment, don't start a block with a blank
  1357. line, don't end a function with a blank line, don't have too many
  1358. blank lines in a row.
  1359. Args:
  1360. file_extension: The current file extension, without the leading dot.
  1361. clean_lines: A CleansedLines instance containing the file.
  1362. line_number: The number of the line to check.
  1363. error: The function to call with any errors found.
  1364. """
  1365. raw = clean_lines.raw_lines
  1366. line = raw[line_number]
  1367. # Before nixing comments, check if the line is blank for no good
  1368. # reason. This includes the first line after a block is opened, and
  1369. # blank lines at the end of a function (ie, right before a line like '}').
  1370. if is_blank_line(line):
  1371. elided = clean_lines.elided
  1372. previous_line = elided[line_number - 1]
  1373. previous_brace = previous_line.rfind('{')
  1374. # FIXME: Don't complain if line before blank line, and line after,
  1375. # both start with alnums and are indented the same amount.
  1376. # This ignores whitespace at the start of a namespace block
  1377. # because those are not usually indented.
  1378. if (previous_brace != -1 and previous_line[previous_brace:].find('}') == -1
  1379. and previous_line[:previous_brace].find('namespace') == -1):
  1380. # OK, we have a blank line at the start of a code block. Before we
  1381. # complain, we check if it is an exception to the rule: The previous
  1382. # non-empty line has the parameters of a function header that are indented
  1383. # 4 spaces (because they did not fit in a 80 column line when placed on
  1384. # the same line as the function name). We also check for the case where
  1385. # the previous line is indented 6 spaces, which may happen when the
  1386. # initializers of a constructor do not fit into a 80 column line.
  1387. exception = False
  1388. if match(r' {6}\w', previous_line): # Initializer list?
  1389. # We are looking for the opening column of initializer list, which
  1390. # should be indented 4 spaces to cause 6 space indentation afterwards.
  1391. search_position = line_number - 2
  1392. while (search_position >= 0
  1393. and match(r' {6}\w', elided[search_position])):
  1394. search_position -= 1
  1395. exception = (search_position >= 0
  1396. and elided[search_position][:5] == ' :')
  1397. else:
  1398. # Search for the function arguments or an initializer list. We use a
  1399. # simple heuristic here: If the line is indented 4 spaces; and we have a
  1400. # closing paren, without the opening paren, followed by an opening brace
  1401. # or colon (for initializer lists) we assume that it is the last line of
  1402. # a function header. If we have a colon indented 4 spaces, it is an
  1403. # initializer list.
  1404. exception = (match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
  1405. previous_line)
  1406. or match(r' {4}:', previous_line))
  1407. if not exception:
  1408. error(line_number, 'whitespace/blank_line', 2,
  1409. 'Blank line at the start of a code block. Is this needed?')
  1410. # This doesn't ignore whitespace at the end of a namespace block
  1411. # because that is too hard without pairing open/close braces;
  1412. # however, a special exception is made for namespace closing
  1413. # brackets which have a comment containing "namespace".
  1414. #
  1415. # Also, ignore blank lines at the end of a block in a long if-else
  1416. # chain, like this:
  1417. # if (condition1) {
  1418. # // Something followed by a blank line
  1419. #
  1420. # } else if (condition2) {
  1421. # // Something else
  1422. # }
  1423. if line_number + 1 < clean_lines.num_lines():
  1424. next_line = raw[line_number + 1]
  1425. if (next_line
  1426. and match(r'\s*}', next_line)
  1427. and next_line.find('namespace') == -1
  1428. and next_line.find('} else ') == -1):
  1429. error(line_number, 'whitespace/blank_line', 3,
  1430. 'Blank line at the end of a code block. Is this needed?')
  1431. # Next, we check for proper spacing with respect to comments.
  1432. comment_position = line.find('//')
  1433. if comment_position != -1:
  1434. # Check if the // may be in quotes. If so, ignore it
  1435. # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
  1436. if (line.count('"', 0, comment_position) - line.count('\\"', 0, comment_position)) % 2 == 0: # not in quotes
  1437. # Allow one space before end of line comment.
  1438. if (not match(r'^\s*$', line[:comment_position])
  1439. and (comment_position >= 1
  1440. and ((line[comment_position - 1] not in string.whitespace)
  1441. or (comment_position >= 2
  1442. and line[comment_position - 2] in string.whitespace)))):
  1443. error(line_number, 'whitespace/comments', 5,
  1444. 'One space before end of line comments')
  1445. # There should always be a space between the // and the comment
  1446. commentend = comment_position + 2
  1447. if commentend < len(line) and not line[commentend] == ' ':
  1448. # but some lines are exceptions -- e.g. if they're big
  1449. # comment delimiters like:
  1450. # //----------------------------------------------------------
  1451. # or they begin with multiple slashes followed by a space:
  1452. # //////// Header comment
  1453. matched = (search(r'[=/-]{4,}\s*$', line[commentend:])
  1454. or search(r'^/+ ', line[commentend:]))
  1455. if not matched:
  1456. error(line_number, 'whitespace/comments', 4,
  1457. 'Should have a space between // and comment')
  1458. # There should only be one space after punctuation in a comment.
  1459. if search(r'[.!?,;:]\s\s+\w', line[comment_position:]):
  1460. error(line_number, 'whitespace/comments', 5,
  1461. 'Should have only a single space after a punctuation in a comment.')
  1462. line = clean_lines.elided[line_number] # get rid of comments and strings
  1463. # Don't try to do spacing checks for operator methods
  1464. line = sub(r'operator(==|!=|<|<<|<=|>=|>>|>|\+=|-=|\*=|/=|%=|&=|\|=|^=|<<=|>>=)\(', 'operator\(', line)
  1465. # Don't try to do spacing checks for #include or #import statements at
  1466. # minimum because it messes up checks for spacing around /
  1467. if match(r'\s*#\s*(?:include|import)', line):
  1468. return
  1469. if search(r'[\w.]=[\w.]', line):
  1470. error(line_number, 'whitespace/operators', 4,
  1471. 'Missing spaces around =')
  1472. # FIXME: It's not ok to have spaces around binary operators like .
  1473. # You should always have whitespace around binary operators.
  1474. # Alas, we can't test < or > because they're legitimately used sans spaces
  1475. # (a->b, vector<int> a). The only time we can tell is a < with no >, and
  1476. # only if it's not template params list spilling into the next line.
  1477. matched = search(r'[^<>=!\s](==|!=|\+=|-=|\*=|/=|/|\|=|&=|<<=|>>=|<=|>=|\|\||\||&&|>>|<<)[^<>=!\s]', line)
  1478. if not matched:
  1479. # Note that while it seems that the '<[^<]*' term in the following
  1480. # regexp could be simplified to '<.*', which would indeed match
  1481. # the same class of strings, the [^<] means that searching for the
  1482. # regexp takes linear rather than quadratic time.
  1483. if not search(r'<[^<]*,\s*$', line): # template params spill
  1484. matched = search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line)
  1485. if matched:
  1486. error(line_number, 'whitespace/operators', 3,
  1487. 'Missing spaces around %s' % matched.group(1))
  1488. # There shouldn't be space around unary operators
  1489. matched = search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
  1490. if matched:
  1491. error(line_number, 'whitespace/operators', 4,
  1492. 'Extra space for operator %s' % matched.group(1))
  1493. # A pet peeve of mine: no spaces after an if, while, switch, or for
  1494. matched = search(r' (if\(|for\(|foreach\(|while\(|switch\()', line)
  1495. if matched:
  1496. error(line_number, 'whitespace/parens', 5,
  1497. 'Missing space before ( in %s' % matched.group(1))
  1498. # For if/for/foreach/while/switch, the left and right parens should be
  1499. # consistent about how many spaces are inside the parens, and
  1500. # there should either be zero or one spaces inside the parens.
  1501. # We don't want: "if ( foo)" or "if ( foo )".
  1502. # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
  1503. matched = search(r'\b(?P<statement>if|for|foreach|while|switch)\s*\((?P<remainder>.*)$', line)
  1504. if matched:
  1505. statement = matched.group('statement')
  1506. condition, rest = up_to_unmatched_closing_paren(matched.group('remainder'))
  1507. if condition is not None:
  1508. condition_match = search(r'(?P<leading>[ ]*)(?P<separator>.).*[^ ]+(?P<trailing>[ ]*)', condition)
  1509. if condition_match:
  1510. n_leading = len(condition_match.group('leading'))
  1511. n_trailing = len(condition_match.group('trailing'))
  1512. if n_leading != 0:
  1513. for_exception = statement == 'for' and condition.startswith(' ;')
  1514. if not for_exception:
  1515. error(line_number, 'whitespace/parens', 5,
  1516. 'Extra space after ( in %s' % statement)
  1517. if n_trailing != 0:
  1518. for_exception = statement == 'for' and condition.endswith('; ')
  1519. if not for_exception:
  1520. error(line_number, 'whitespace/parens', 5,
  1521. 'Extra space before ) in %s' % statement)
  1522. # Do not check for more than one command in macros
  1523. in_preprocessor_directive = match(r'\s*#', line)
  1524. if not in_preprocessor_directive and not match(r'((\s*{\s*}?)|(\s*;?))\s*\\?$', rest):
  1525. error(line_number, 'whitespace/parens', 4,
  1526. 'More than one command on the same line in %s' % statement)
  1527. # You should always have a space after a comma (either as fn arg or operator)
  1528. if search(r',[^\s]', line):
  1529. error(line_number, 'whitespace/comma', 3,
  1530. 'Missing space after ,')
  1531. matched = search(r'^\s*(?P<token1>[a-zA-Z0-9_\*&]+)\s\s+(?P<token2>[a-zA-Z0-9_\*&]+)', line)
  1532. if matched:
  1533. error(line_number, 'whitespace/declaration', 3,
  1534. 'Extra space between %s and %s' % (matched.group('token1'), matched.group('token2')))
  1535. if file_extension == 'cpp':
  1536. # C++ should have the & or * beside the type not the variable name.
  1537. matched = match(r'\s*\w+(?<!\breturn|\bdelete)\s+(?P<pointer_operator>\*|\&)\w+', line)
  1538. if matched:
  1539. error(line_number, 'whitespace/declaration', 3,
  1540. 'Declaration has space between type name and %s in %s' % (matched.group('pointer_operator'), matched.group(0).strip()))
  1541. elif file_extension == 'c':
  1542. # C Pointer declaration should have the * beside the variable not the type name.
  1543. matched = search(r'^\s*\w+\*\s+\w+', line)
  1544. if matched:
  1545. error(line_number, 'whitespace/declaration', 3,
  1546. 'Declaration has space between * and variable name in %s' % matched.group(0).strip())
  1547. # Next we will look for issues with function calls.
  1548. check_spacing_for_function_call(line, line_number, error)
  1549. # Except after an opening paren, you should have spaces before your braces.
  1550. # And since you should never have braces at the beginning of a line, this is
  1551. # an easy test.
  1552. if search(r'[^ ({]{', line):
  1553. error(line_number, 'whitespace/braces', 5,
  1554. 'Missing space before {')
  1555. # Make sure '} else {' has spaces.
  1556. if search(r'}else', line):
  1557. error(line_number, 'whitespace/braces', 5,
  1558. 'Missing space before else')
  1559. # You shouldn't have spaces before your brackets, except maybe after
  1560. # 'delete []' or 'new char * []'.
  1561. if search(r'\w\s+\[', line) and not search(r'delete\s+\[', line):
  1562. error(line_number, 'whitespace/braces', 5,
  1563. 'Extra space before [')
  1564. # There should always be a single space in between braces on the same line.
  1565. if search(r'\{\}', line):
  1566. error(line_number, 'whitespace/braces', 5, 'Missing space inside { }.')
  1567. if search(r'\{\s\s+\}', line):
  1568. error(line_number, 'whitespace/braces', 5, 'Too many spaces inside { }.')
  1569. # You shouldn't have a space before a semicolon at the end of the line.
  1570. # There's a special case for "for" since the style guide allows space before
  1571. # the semicolon there.
  1572. if search(r':\s*;\s*$', line):
  1573. error(line_number, 'whitespace/semicolon', 5,
  1574. 'Semicolon defining empty statement. Use { } instead.')
  1575. elif search(r'^\s*;\s*$', line):
  1576. error(line_number, 'whitespace/semicolon', 5,
  1577. 'Line contains only semicolon. If this should be an empty statement, '
  1578. 'use { } instead.')
  1579. elif (search(r'\s+;\s*$', line) and not search(r'\bfor\b', line)):
  1580. error(line_number, 'whitespace/semicolon', 5,
  1581. 'Extra space before last semicolon. If this should be an empty '
  1582. 'statement, use { } instead.')
  1583. elif (search(r'\b(for|while)\s*\(.*\)\s*;\s*$', line)
  1584. and line.count('(') == line.count(')')
  1585. # Allow do {} while();
  1586. and not search(r'}\s*while', line)):
  1587. error(line_number, 'whitespace/semicolon', 5,
  1588. 'Semicolon defining empty statement for this loop. Use { } instead.')
  1589. def get_previous_non_blank_line(clean_lines, line_number):
  1590. """Return the most recent non-blank line and its line number.
  1591. Args:
  1592. clean_lines: A CleansedLines instance containing the file contents.
  1593. line_number: The number of the line to check.
  1594. Returns:
  1595. A tuple with two elements. The first element is the contents of the last
  1596. non-blank line before the current line, or the empty string if this is the
  1597. first non-blank line. The second is the line number of that line, or -1
  1598. if this is the first non-blank line.
  1599. """
  1600. previous_line_number = line_number - 1
  1601. while previous_line_number >= 0:
  1602. previous_line = clean_lines.elided[previous_line_number]
  1603. if not is_blank_line(previous_line): # if not a blank line...
  1604. return (previous_line, previous_line_number)
  1605. previous_line_number -= 1
  1606. return ('', -1)
  1607. def check_namespace_indentation(clean_lines, line_number, file_extension, file_state, error):
  1608. """Looks for indentation errors inside of namespaces.
  1609. Args:
  1610. clean_lines: A CleansedLines instance containing the file.
  1611. line_number: The number of the line to check.
  1612. file_extension: The extension (dot not included) of the file.
  1613. file_state: A _FileState instance which maintains information about
  1614. the state of things in the file.
  1615. error: The function to call with any errors found.
  1616. """
  1617. line = clean_lines.elided[line_number] # Get rid of comments and strings.
  1618. namespace_match = match(r'(?P<namespace_indentation>\s*)namespace\s+\S+\s*{\s*$', line)
  1619. if not namespace_match:
  1620. return
  1621. current_indentation_level = len(namespace_match.group('namespace_indentation'))
  1622. if current_indentation_level > 0:
  1623. # Don't warn about an indented namespace if we already warned about indented code.
  1624. if not file_state.did_inside_namespace_indent_warning():
  1625. error(line_number, 'whitespace/indent', 4,
  1626. 'namespace should never be indented.')
  1627. return
  1628. looking_for_semicolon = False;
  1629. line_offset = 0
  1630. in_preprocessor_directive = False;
  1631. for current_line in clean_lines.elided[line_number + 1:]:
  1632. line_offset += 1
  1633. if not current_line.strip():
  1634. continue
  1635. if not current_indentation_level:
  1636. if not (in_preprocessor_directive or looking_for_semicolon):
  1637. if not match(r'\S', current_line) and not file_state.did_inside_namespace_indent_warning():
  1638. file_state.set_did_inside_namespace_indent_warning()
  1639. error(line_number + line_offset, 'whitespace/indent', 4,
  1640. 'Code inside a namespace should not be indented.')
  1641. if in_preprocessor_directive or (current_line.strip()[0] == '#'): # This takes care of preprocessor directive syntax.
  1642. in_preprocessor_directive = current_line[-1] == '\\'
  1643. else:
  1644. looking_for_semicolon = ((current_line.find(';') == -1) and (current_line.strip()[-1] != '}')) or (current_line[-1] == '\\')
  1645. else:
  1646. looking_for_semicolon = False; # If we have a brace we may not need a semicolon.
  1647. current_indentation_level += current_line.count('{') - current_line.count('}')
  1648. if current_indentation_level < 0:
  1649. break;
  1650. def check_using_std(clean_lines, line_number, file_state, error):
  1651. """Looks for 'using std::foo;' statements which should be replaced with 'using namespace std;'.
  1652. Args:
  1653. clean_lines: A CleansedLines instance containing the file.
  1654. line_number: The number of the line to check.
  1655. file_state: A _FileState instance which maintains information about
  1656. the state of things in the file.
  1657. error: The function to call with any errors found.
  1658. """
  1659. # This check doesn't apply to C or Objective-C implementation files.
  1660. if file_state.is_c_or_objective_c():
  1661. return
  1662. line = clean_lines.elided[line_number] # Get rid of comments and strings.
  1663. using_std_match = match(r'\s*using\s+std::(?P<method_name>\S+)\s*;\s*$', line)
  1664. if not using_std_match:
  1665. return
  1666. method_name = using_std_match.group('method_name')
  1667. error(line_number, 'build/using_std', 4,
  1668. "Use 'using namespace std;' instead of 'using std::%s;'." % method_name)
  1669. def check_max_min_macros(clean_lines, line_number, file_state, error):
  1670. """Looks use of MAX() and MIN() macros that should be replaced with std::max() and std::min().
  1671. Args:
  1672. clean_lines: A CleansedLines instance containing the file.
  1673. line_number: The number of the line to check.
  1674. file_state: A _FileState instance which maintains information about
  1675. the state of things in the file.
  1676. error: The function to call with any errors found.
  1677. """
  1678. # This check doesn't apply to C or Objective-C implementation files.
  1679. if file_state.is_c_or_objective_c():
  1680. return
  1681. line = clean_lines.elided[line_number] # Get rid of comments and strings.
  1682. max_min_macros_search = search(r'\b(?P<max_min_macro>(MAX|MIN))\s*\(', line)
  1683. if not max_min_macros_search:
  1684. return
  1685. max_min_macro = max_min_macros_search.group('max_min_macro')
  1686. max_min_macro_lower = max_min_macro.lower()
  1687. error(line_number, 'runtime/max_min_macros', 4,
  1688. 'Use std::%s() or std::%s<type>() instead of the %s() macro.'
  1689. % (max_min_macro_lower, max_min_macro_lower, max_min_macro))
  1690. def check_switch_indentation(clean_lines, line_number, error):
  1691. """Looks for indentation errors inside of switch statements.
  1692. Args:
  1693. clean_lines: A CleansedLines instance containing the file.
  1694. line_number: The number of the line to check.
  1695. error: The function to call with any errors found.
  1696. """
  1697. line = clean_lines.elided[line_number] # Get rid of comments and strings.
  1698. switch_match = match(r'(?P<switch_indentation>\s*)switch\s*\(.+\)\s*{\s*$', line)
  1699. if not switch_match:
  1700. return
  1701. switch_indentation = switch_match.group('switch_indentation')
  1702. inner_indentation = switch_indentation + ' ' * 4
  1703. line_offset = 0
  1704. encountered_nested_switch = False
  1705. for current_line in clean_lines.elided[line_number + 1:]:
  1706. line_offset += 1
  1707. # Skip not only empty lines but also those with preprocessor directives.
  1708. if current_line.strip() == '' or current_line.startswith('#'):
  1709. continue
  1710. if match(r'\s*switch\s*\(.+\)\s*{\s*$', current_line):
  1711. # Complexity alarm - another switch statement nested inside the one
  1712. # that we're currently testing. We'll need to track the extent of
  1713. # that inner switch if the upcoming label tests are still supposed
  1714. # to work correctly. Let's not do that; instead, we'll finish
  1715. # checking this line, and then leave it like that. Assuming the
  1716. # indentation is done consistently (even if incorrectly), this will
  1717. # still catch all indentation issues in practice.
  1718. encountered_nested_switch = True
  1719. current_indentation_match = match(r'(?P<indentation>\s*)(?P<remaining_line>.*)$', current_line);
  1720. current_indentation = current_indentation_match.group('indentation')
  1721. remaining_line = current_indentation_match.group('remaining_line')
  1722. # End the check at the end of the switch statement.
  1723. if remaining_line.startswith('}') and current_indentation == switch_indentation:
  1724. break
  1725. # Case and default branches should not be indented. The regexp also
  1726. # catches single-line cases like "default: break;" but does not trigger
  1727. # on stuff like "Document::Foo();".
  1728. elif match(r'(default|case\s+.*)\s*:([^:].*)?$', remaining_line):
  1729. if current_indentation != switch_indentation:
  1730. error(line_number + line_offset, 'whitespace/indent', 4,
  1731. 'A case label should not be indented, but line up with its switch statement.')
  1732. # Don't throw an error for multiple badly indented labels,
  1733. # one should be enough to figure out the problem.
  1734. break
  1735. # We ignore goto labels at the very beginning of a line.
  1736. elif match(r'\w+\s*:\s*$', remaining_line):
  1737. continue
  1738. # It's not a goto label, so check if it's indented at least as far as
  1739. # the switch statement plus one more level of indentation.
  1740. elif not current_indentation.startswith(inner_indentation):
  1741. error(line_number + line_offset, 'whitespace/indent', 4,
  1742. 'Non-label code inside switch statements should be indented.')
  1743. # Don't throw an error for multiple badly indented statements,
  1744. # one should be enough to figure out the problem.
  1745. break
  1746. if encountered_nested_switch:
  1747. break
  1748. def check_braces(clean_lines, line_number, error):
  1749. """Looks for misplaced braces (e.g. at the end of line).
  1750. Args:
  1751. clean_lines: A CleansedLines instance containing the file.
  1752. line_number: The number of the line to check.
  1753. error: The function to call with any errors found.
  1754. """
  1755. line = clean_lines.elided[line_number] # Get rid of comments and strings.
  1756. if match(r'\s*{\s*$', line):
  1757. # We allow an open brace to start a line in the case where someone
  1758. # is using braces for function definition or in a block to
  1759. # explicitly create a new scope, which is commonly used to control
  1760. # the lifetime of stack-allocated variables. We don't detect this
  1761. # perfectly: we just don't complain if the last non-whitespace
  1762. # character on the previous non-blank line is ';', ':', '{', '}',
  1763. # ')', or ') const' and doesn't begin with 'if|for|while|switch|else'.
  1764. # We also allow '#' for #endif and '=' for array initialization.
  1765. previous_line = get_previous_non_blank_line(clean_lines, line_number)[0]
  1766. if ((not search(r'[;:}{)=]\s*$|\)\s*const\s*$', previous_line)
  1767. or search(r'\b(if|for|foreach|while|switch|else)\b', previous_line))
  1768. and previous_line.find('#') < 0):
  1769. error(line_number, 'whitespace/braces', 4,
  1770. 'This { should be at the end of the previous line')
  1771. elif (search(r'\)\s*(const\s*)?{\s*$', line)
  1772. and line.count('(') == line.count(')')
  1773. and not search(r'\b(if|for|foreach|while|switch)\b', line)
  1774. and not match(r'\s+[A-Z_][A-Z_0-9]+\b', line)):
  1775. error(line_number, 'whitespace/braces', 4,
  1776. 'Place brace on its own line for function definitions.')
  1777. if (match(r'\s*}\s*(else\s*({\s*)?)?$', line) and line_number > 1):
  1778. # We check if a closed brace has started a line to see if a
  1779. # one line control statement was previous.
  1780. previous_line = clean_lines.elided[line_number - 2]
  1781. last_open_brace = previous_line.rfind('{')
  1782. if (last_open_brace != -1 and previous_line.find('}', last_open_brace) == -1
  1783. and search(r'\b(if|for|foreach|while|else)\b', previous_line)):
  1784. error(line_number, 'whitespace/braces', 4,
  1785. 'One line control clauses should not use braces.')
  1786. # An else clause should be on the same line as the preceding closing brace.
  1787. if match(r'\s*else\s*', line):
  1788. previous_line = get_previous_non_blank_line(clean_lines, line_number)[0]
  1789. if match(r'\s*}\s*$', previous_line):
  1790. error(line_number, 'whitespace/newline', 4,
  1791. 'An else should appear on the same line as the preceding }')
  1792. # Likewise, an else should never have the else clause on the same line
  1793. if search(r'\belse [^\s{]', line) and not search(r'\belse if\b', line):
  1794. error(line_number, 'whitespace/newline', 4,
  1795. 'Else clause should never be on same line as else (use 2 lines)')
  1796. # In the same way, a do/while should never be on one line
  1797. if match(r'\s*do [^\s{]', line):
  1798. error(line_number, 'whitespace/newline', 4,
  1799. 'do/while clauses should not be on a single line')
  1800. # Braces shouldn't be followed by a ; unless they're defining a struct
  1801. # or initializing an array.
  1802. # We can't tell in general, but we can for some common cases.
  1803. previous_line_number = line_number
  1804. while True:
  1805. (previous_line, previous_line_number) = get_previous_non_blank_line(clean_lines, previous_line_number)
  1806. if match(r'\s+{.*}\s*;', line) and not previous_line.count(';'):
  1807. line = previous_line + line
  1808. else:
  1809. break
  1810. if (search(r'{.*}\s*;', line)
  1811. and line.count('{') == line.count('}')
  1812. and not search(r'struct|class|enum|\s*=\s*{', line)):
  1813. error(line_number, 'readability/braces', 4,
  1814. "You don't need a ; after a }")
  1815. def check_exit_statement_simplifications(clean_lines, line_number, error):
  1816. """Looks for else or else-if statements that should be written as an
  1817. if statement when the prior if concludes with a return, break, continue or
  1818. goto statement.
  1819. Args:
  1820. clean_lines: A CleansedLines instance containing the file.
  1821. line_number: The number of the line to check.
  1822. error: The function to call with any errors found.
  1823. """
  1824. line = clean_lines.elided[line_number] # Get rid of comments and strings.
  1825. else_match = match(r'(?P<else_indentation>\s*)(\}\s*)?else(\s+if\s*\(|(?P<else>\s*(\{\s*)?\Z))', line)
  1826. if not else_match:
  1827. return
  1828. else_indentation = else_match.group('else_indentation')
  1829. inner_indentation = else_indentation + ' ' * 4
  1830. previous_lines = clean_lines.elided[:line_number]
  1831. previous_lines.reverse()
  1832. line_offset = 0
  1833. encountered_exit_statement = False
  1834. for current_line in previous_lines:
  1835. line_offset -= 1
  1836. # Skip not only empty lines but also those with preprocessor directives
  1837. # and goto labels.
  1838. if current_line.strip() == '' or current_line.startswith('#') or match(r'\w+\s*:\s*$', current_line):
  1839. continue
  1840. # Skip lines with closing braces on the original indentation level.
  1841. # Even though the styleguide says they should be on the same line as
  1842. # the "else if" statement, we also want to check for instances where
  1843. # the current code does not comply with the coding style. Thus, ignore
  1844. # these lines and proceed to the line before that.
  1845. if current_line == else_indentation + '}':
  1846. continue
  1847. current_indentation_match = match(r'(?P<indentation>\s*)(?P<remaining_line>.*)$', current_line);
  1848. current_indentation = current_indentation_match.group('indentation')
  1849. remaining_line = current_indentation_match.group('remaining_line')
  1850. # As we're going up the lines, the first real statement to encounter
  1851. # has to be an exit statement (return, break, continue or goto) -
  1852. # otherwise, this check doesn't apply.
  1853. if not encountered_exit_statement:
  1854. # We only want to find exit statements if they are on exactly
  1855. # the same level of indentation as expected from the code inside
  1856. # the block. If the indentation doesn't strictly match then we
  1857. # might have a nested if or something, which must be ignored.
  1858. if current_indentation != inner_indentation:
  1859. break
  1860. if match(r'(return(\W+.*)|(break|continue)\s*;|goto\s*\w+;)$', remaining_line):
  1861. encountered_exit_statement = True
  1862. continue
  1863. break
  1864. # When code execution reaches this point, we've found an exit statement
  1865. # as last statement of the previous block. Now we only need to make
  1866. # sure that the block belongs to an "if", then we can throw an error.
  1867. # Skip lines with opening braces on the original indentation level,
  1868. # similar to the closing braces check above. ("if (condition)\n{")
  1869. if current_line == else_indentation + '{':
  1870. continue
  1871. # Skip everything that's further indented than our "else" or "else if".
  1872. if current_indentation.startswith(else_indentation) and current_indentation != else_indentation:
  1873. continue
  1874. # So we've got a line with same (or less) indentation. Is it an "if"?
  1875. # If yes: throw an error. If no: don't throw an error.
  1876. # Whatever the outcome, this is the end of our loop.
  1877. if match(r'if\s*\(', remaining_line):
  1878. if else_match.start('else') != -1:
  1879. error(line_number + line_offset, 'readability/control_flow', 4,
  1880. 'An else statement can be removed when the prior "if" '
  1881. 'concludes with a return, break, continue or goto statement.')
  1882. else:
  1883. error(line_number + line_offset, 'readability/control_flow', 4,
  1884. 'An else if statement should be written as an if statement '
  1885. 'when the prior "if" concludes with a return, break, '
  1886. 'continue or goto statement.')
  1887. break
  1888. def replaceable_check(operator, macro, line):
  1889. """Determine whether a basic CHECK can be replaced with a more specific one.
  1890. For example suggest using CHECK_EQ instead of CHECK(a == b) and
  1891. similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE.
  1892. Args:
  1893. operator: The C++ operator used in the CHECK.
  1894. macro: The CHECK or EXPECT macro being called.
  1895. line: The current source line.
  1896. Returns:
  1897. True if the CHECK can be replaced with a more specific one.
  1898. """
  1899. # This matches decimal and hex integers, strings, and chars (in that order).
  1900. match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')'
  1901. # Expression to match two sides of the operator with something that
  1902. # looks like a literal, since CHECK(x == iterator) won't compile.
  1903. # This means we can't catch all the cases where a more specific
  1904. # CHECK is possible, but it's less annoying than dealing with
  1905. # extraneous warnings.
  1906. match_this = (r'\s*' + macro + r'\((\s*' +
  1907. match_constant + r'\s*' + operator + r'[^<>].*|'
  1908. r'.*[^<>]' + operator + r'\s*' + match_constant +
  1909. r'\s*\))')
  1910. # Don't complain about CHECK(x == NULL) or similar because
  1911. # CHECK_EQ(x, NULL) won't compile (requires a cast).
  1912. # Also, don't complain about more complex boolean expressions
  1913. # involving && or || such as CHECK(a == b || c == d).
  1914. return match(match_this, line) and not search(r'NULL|&&|\|\|', line)
  1915. def check_check(clean_lines, line_number, error):
  1916. """Checks the use of CHECK and EXPECT macros.
  1917. Args:
  1918. clean_lines: A CleansedLines instance containing the file.
  1919. line_number: The number of the line to check.
  1920. error: The function to call with any errors found.
  1921. """
  1922. # Decide the set of replacement macros that should be suggested
  1923. raw_lines = clean_lines.raw_lines
  1924. current_macro = ''
  1925. for macro in _CHECK_MACROS:
  1926. if raw_lines[line_number].find(macro) >= 0:
  1927. current_macro = macro
  1928. break
  1929. if not current_macro:
  1930. # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
  1931. return
  1932. line = clean_lines.elided[line_number] # get rid of comments and strings
  1933. # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc.
  1934. for operator in ['==', '!=', '>=', '>', '<=', '<']:
  1935. if replaceable_check(operator, current_macro, line):
  1936. error(line_number, 'readability/check', 2,
  1937. 'Consider using %s instead of %s(a %s b)' % (
  1938. _CHECK_REPLACEMENT[current_macro][operator],
  1939. current_macro, operator))
  1940. break
  1941. def check_for_comparisons_to_zero(clean_lines, line_number, error):
  1942. # Get the line without comments and strings.
  1943. line = clean_lines.elided[line_number]
  1944. # Include NULL here so that users don't have to convert NULL to 0 first and then get this error.
  1945. if search(r'[=!]=\s*(NULL|0|true|false)\W', line) or search(r'\W(NULL|0|true|false)\s*[=!]=', line):
  1946. if not search('LIKELY', line) and not search('UNLIKELY', line):
  1947. error(line_number, 'readability/comparison_to_zero', 5,
  1948. 'Tests for true/false, null/non-null, and zero/non-zero should all be done without equality comparisons.')
  1949. def check_for_null(clean_lines, line_number, file_state, error):
  1950. # This check doesn't apply to C or Objective-C implementation files.
  1951. if file_state.is_c_or_objective_c():
  1952. return
  1953. line = clean_lines.elided[line_number]
  1954. # Don't warn about NULL usage in g_*(). See Bug 32858 and 39372.
  1955. if search(r'\bg(_[a-z]+)+\b', line):
  1956. return
  1957. # Don't warn about NULL usage in gst_*_many(). See Bug 39740
  1958. if search(r'\bgst_\w+_many\b', line):
  1959. return
  1960. # Don't warn about NULL usage in some gst_structure_*(). See Bug 67194.
  1961. if search(r'\bgst_structure_[sg]et\b', line):
  1962. return
  1963. if search(r'\bgst_structure_remove_fields\b', line):
  1964. return
  1965. if search(r'\bgst_structure_new\b', line):
  1966. return
  1967. if search(r'\bgst_structure_id_new\b', line):
  1968. return
  1969. if search(r'\bgst_structure_id_[sg]et\b', line):
  1970. return
  1971. # Don't warn about NULL usage in g_str{join,concat}(). See Bug 34834
  1972. if search(r'\bg_str(join|concat)\b', line):
  1973. return
  1974. # Don't warn about NULL usage in gdk_pixbuf_save_to_*{join,concat}(). See Bug 43090.
  1975. if search(r'\bgdk_pixbuf_save_to\w+\b', line):
  1976. return
  1977. # Don't warn about NULL usage in gtk_widget_style_get(). See Bug 51758.
  1978. if search(r'\bgtk_widget_style_get\(\w+\b', line):
  1979. return
  1980. if search(r'\bNULL\b', line):
  1981. error(line_number, 'readability/null', 5, 'Use 0 instead of NULL.')
  1982. return
  1983. line = clean_lines.raw_lines[line_number]
  1984. # See if NULL occurs in any comments in the line. If the search for NULL using the raw line
  1985. # matches, then do the check with strings collapsed to avoid giving errors for
  1986. # NULLs occurring in strings.
  1987. if search(r'\bNULL\b', line) and search(r'\bNULL\b', CleansedLines.collapse_strings(line)):
  1988. error(line_number, 'readability/null', 4, 'Use 0 or null instead of NULL (even in *comments*).')
  1989. def get_line_width(line):
  1990. """Determines the width of the line in column positions.
  1991. Args:
  1992. line: A string, which may be a Unicode string.
  1993. Returns:
  1994. The width of the line in column positions, accounting for Unicode
  1995. combining characters and wide characters.
  1996. """
  1997. if isinstance(line, unicode):
  1998. width = 0
  1999. for c in unicodedata.normalize('NFC', line):
  2000. if unicodedata.east_asian_width(c) in ('W', 'F'):
  2001. width += 2
  2002. elif not unicodedata.combining(c):
  2003. width += 1
  2004. return width
  2005. return len(line)
  2006. def check_style(clean_lines, line_number, file_extension, class_state, file_state, error):
  2007. """Checks rules from the 'C++ style rules' section of cppguide.html.
  2008. Most of these rules are hard to test (naming, comment style), but we
  2009. do what we can. In particular we check for 4-space indents, line lengths,
  2010. tab usage, spaces inside code, etc.
  2011. Args:
  2012. clean_lines: A CleansedLines instance containing the file.
  2013. line_number: The number of the line to check.
  2014. file_extension: The extension (without the dot) of the filename.
  2015. class_state: A _ClassState instance which maintains information about
  2016. the current stack of nested class declarations being parsed.
  2017. file_state: A _FileState instance which maintains information about
  2018. the state of things in the file.
  2019. error: The function to call with any errors found.
  2020. """
  2021. raw_lines = clean_lines.raw_lines
  2022. line = raw_lines[line_number]
  2023. if line.find('\t') != -1:
  2024. error(line_number, 'whitespace/tab', 1,
  2025. 'Tab found; better to use spaces')
  2026. # One or three blank spaces at the beginning of the line is weird; it's
  2027. # hard to reconcile that with 4-space indents.
  2028. # NOTE: here are the conditions rob pike used for his tests. Mine aren't
  2029. # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
  2030. # if(RLENGTH > 20) complain = 0;
  2031. # if(match($0, " +(error|private|public|protected):")) complain = 0;
  2032. # if(match(prev, "&& *$")) complain = 0;
  2033. # if(match(prev, "\\|\\| *$")) complain = 0;
  2034. # if(match(prev, "[\",=><] *$")) complain = 0;
  2035. # if(match($0, " <<")) complain = 0;
  2036. # if(match(prev, " +for \\(")) complain = 0;
  2037. # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
  2038. initial_spaces = 0
  2039. cleansed_line = clean_lines.elided[line_number]
  2040. while initial_spaces < len(line) and line[initial_spaces] == ' ':
  2041. initial_spaces += 1
  2042. if line and line[-1].isspace():
  2043. error(line_number, 'whitespace/end_of_line', 4,
  2044. 'Line ends in whitespace. Consider deleting these extra spaces.')
  2045. # There are certain situations we allow one space, notably for labels
  2046. elif ((initial_spaces >= 1 and initial_spaces <= 3)
  2047. and not match(r'\s*\w+\s*:\s*$', cleansed_line)):
  2048. error(line_number, 'whitespace/indent', 3,
  2049. 'Weird number of spaces at line-start. '
  2050. 'Are you using a 4-space indent?')
  2051. # Labels should always be indented at least one space.
  2052. elif not initial_spaces and line[:2] != '//':
  2053. label_match = match(r'(?P<label>[^:]+):\s*$', line)
  2054. if label_match:
  2055. label = label_match.group('label')
  2056. # Only throw errors for stuff that is definitely not a goto label,
  2057. # because goto labels can in fact occur at the start of the line.
  2058. if label in ['public', 'private', 'protected'] or label.find(' ') != -1:
  2059. error(line_number, 'whitespace/labels', 4,
  2060. 'Labels should always be indented at least one space. '
  2061. 'If this is a member-initializer list in a constructor, '
  2062. 'the colon should be on the line after the definition header.')
  2063. if (cleansed_line.count(';') > 1
  2064. # for loops are allowed two ;'s (and may run over two lines).
  2065. and cleansed_line.find('for') == -1
  2066. and (get_previous_non_blank_line(clean_lines, line_number)[0].find('for') == -1
  2067. or get_previous_non_blank_line(clean_lines, line_number)[0].find(';') != -1)
  2068. # It's ok to have many commands in a switch case that fits in 1 line
  2069. and not ((cleansed_line.find('case ') != -1
  2070. or cleansed_line.find('default:') != -1)
  2071. and cleansed_line.find('break;') != -1)
  2072. # Also it's ok to have many commands in trivial single-line accessors in class definitions.
  2073. and not (match(r'.*\(.*\).*{.*.}', line)
  2074. and class_state.classinfo_stack
  2075. and line.count('{') == line.count('}'))
  2076. and not cleansed_line.startswith('#define ')):
  2077. error(line_number, 'whitespace/newline', 4,
  2078. 'More than one command on the same line')
  2079. if cleansed_line.strip().endswith('||') or cleansed_line.strip().endswith('&&'):
  2080. error(line_number, 'whitespace/operators', 4,
  2081. 'Boolean expressions that span multiple lines should have their '
  2082. 'operators on the left side of the line instead of the right side.')
  2083. # Some more style checks
  2084. check_namespace_indentation(clean_lines, line_number, file_extension, file_state, error)
  2085. check_using_std(clean_lines, line_number, file_state, error)
  2086. check_max_min_macros(clean_lines, line_number, file_state, error)
  2087. check_switch_indentation(clean_lines, line_number, error)
  2088. check_braces(clean_lines, line_number, error)
  2089. check_exit_statement_simplifications(clean_lines, line_number, error)
  2090. check_spacing(file_extension, clean_lines, line_number, error)
  2091. check_check(clean_lines, line_number, error)
  2092. check_for_comparisons_to_zero(clean_lines, line_number, error)
  2093. check_for_null(clean_lines, line_number, file_state, error)
  2094. _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
  2095. _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
  2096. # Matches the first component of a filename delimited by -s and _s. That is:
  2097. # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
  2098. # _RE_FIRST_COMPONENT.match('foo.cpp').group(0) == 'foo'
  2099. # _RE_FIRST_COMPONENT.match('foo-bar_baz.cpp').group(0) == 'foo'
  2100. # _RE_FIRST_COMPONENT.match('foo_bar-baz.cpp').group(0) == 'foo'
  2101. _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
  2102. def _drop_common_suffixes(filename):
  2103. """Drops common suffixes like _test.cpp or -inl.h from filename.
  2104. For example:
  2105. >>> _drop_common_suffixes('foo/foo-inl.h')
  2106. 'foo/foo'
  2107. >>> _drop_common_suffixes('foo/bar/foo.cpp')
  2108. 'foo/bar/foo'
  2109. >>> _drop_common_suffixes('foo/foo_internal.h')
  2110. 'foo/foo'
  2111. >>> _drop_common_suffixes('foo/foo_unusualinternal.h')
  2112. 'foo/foo_unusualinternal'
  2113. Args:
  2114. filename: The input filename.
  2115. Returns:
  2116. The filename with the common suffix removed.
  2117. """
  2118. for suffix in ('test.cpp', 'regtest.cpp', 'unittest.cpp',
  2119. 'inl.h', 'impl.h', 'internal.h'):
  2120. if (filename.endswith(suffix) and len(filename) > len(suffix)
  2121. and filename[-len(suffix) - 1] in ('-', '_')):
  2122. return filename[:-len(suffix) - 1]
  2123. return os.path.splitext(filename)[0]
  2124. def _classify_include(filename, include, is_system, include_state):
  2125. """Figures out what kind of header 'include' is.
  2126. Args:
  2127. filename: The current file cpp_style is running over.
  2128. include: The path to a #included file.
  2129. is_system: True if the #include used <> rather than "".
  2130. include_state: An _IncludeState instance in which the headers are inserted.
  2131. Returns:
  2132. One of the _XXX_HEADER constants.
  2133. For example:
  2134. >>> _classify_include('foo.cpp', 'config.h', False)
  2135. _CONFIG_HEADER
  2136. >>> _classify_include('foo.cpp', 'foo.h', False)
  2137. _PRIMARY_HEADER
  2138. >>> _classify_include('foo.cpp', 'bar.h', False)
  2139. _OTHER_HEADER
  2140. """
  2141. # If it is a system header we know it is classified as _OTHER_HEADER.
  2142. if is_system:
  2143. return _OTHER_HEADER
  2144. # If the include is named config.h then this is WebCore/config.h.
  2145. if include == "config.h":
  2146. return _CONFIG_HEADER
  2147. # There cannot be primary includes in header files themselves. Only an
  2148. # include exactly matches the header filename will be is flagged as
  2149. # primary, so that it triggers the "don't include yourself" check.
  2150. if filename.endswith('.h') and filename != include:
  2151. return _OTHER_HEADER;
  2152. # Qt's moc files do not follow the naming and ordering rules, so they should be skipped
  2153. if include.startswith('moc_') and include.endswith('.cpp'):
  2154. return _MOC_HEADER
  2155. if include.endswith('.moc'):
  2156. return _MOC_HEADER
  2157. # If the target file basename starts with the include we're checking
  2158. # then we consider it the primary header.
  2159. target_base = FileInfo(filename).base_name()
  2160. include_base = FileInfo(include).base_name()
  2161. # If we haven't encountered a primary header, then be lenient in checking.
  2162. if not include_state.visited_primary_section() and target_base.find(include_base) != -1:
  2163. return _PRIMARY_HEADER
  2164. # If we already encountered a primary header, perform a strict comparison.
  2165. # In case the two filename bases are the same then the above lenient check
  2166. # probably was a false positive.
  2167. elif include_state.visited_primary_section() and target_base == include_base:
  2168. if include == "ResourceHandleWin.h":
  2169. # FIXME: Thus far, we've only seen one example of these, but if we
  2170. # start to see more, please consider generalizing this check
  2171. # somehow.
  2172. return _OTHER_HEADER
  2173. return _PRIMARY_HEADER
  2174. return _OTHER_HEADER
  2175. def _does_primary_header_exist(filename):
  2176. """Return a primary header file name for a file, or empty string
  2177. if the file is not source file or primary header does not exist.
  2178. """
  2179. fileinfo = FileInfo(filename)
  2180. if not fileinfo.is_source():
  2181. return False
  2182. primary_header = fileinfo.no_extension() + ".h"
  2183. return os.path.isfile(primary_header)
  2184. def check_include_line(filename, file_extension, clean_lines, line_number, include_state, error):
  2185. """Check rules that are applicable to #include lines.
  2186. Strings on #include lines are NOT removed from elided line, to make
  2187. certain tasks easier. However, to prevent false positives, checks
  2188. applicable to #include lines in CheckLanguage must be put here.
  2189. Args:
  2190. filename: The name of the current file.
  2191. file_extension: The current file extension, without the leading dot.
  2192. clean_lines: A CleansedLines instance containing the file.
  2193. line_number: The number of the line to check.
  2194. include_state: An _IncludeState instance in which the headers are inserted.
  2195. error: The function to call with any errors found.
  2196. """
  2197. # FIXME: For readability or as a possible optimization, consider
  2198. # exiting early here by checking whether the "build/include"
  2199. # category should be checked for the given filename. This
  2200. # may involve having the error handler classes expose a
  2201. # should_check() method, in addition to the usual __call__
  2202. # method.
  2203. line = clean_lines.lines[line_number]
  2204. matched = _RE_PATTERN_INCLUDE.search(line)
  2205. if not matched:
  2206. return
  2207. include = matched.group(2)
  2208. is_system = (matched.group(1) == '<')
  2209. # Look for any of the stream classes that are part of standard C++.
  2210. if match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
  2211. error(line_number, 'readability/streams', 3,
  2212. 'Streams are highly discouraged.')
  2213. # Look for specific includes to fix.
  2214. if include.startswith('wtf/') and not is_system:
  2215. error(line_number, 'build/include', 4,
  2216. 'wtf includes should be <wtf/file.h> instead of "wtf/file.h".')
  2217. duplicate_header = include in include_state
  2218. if duplicate_header:
  2219. error(line_number, 'build/include', 4,
  2220. '"%s" already included at %s:%s' %
  2221. (include, filename, include_state[include]))
  2222. else:
  2223. include_state[include] = line_number
  2224. header_type = _classify_include(filename, include, is_system, include_state)
  2225. primary_header_exists = _does_primary_header_exist(filename)
  2226. include_state.header_types[line_number] = header_type
  2227. # Only proceed if this isn't a duplicate header.
  2228. if duplicate_header:
  2229. return
  2230. # We want to ensure that headers appear in the right order:
  2231. # 1) for implementation files: config.h, primary header, blank line, alphabetically sorted
  2232. # 2) for header files: alphabetically sorted
  2233. # The include_state object keeps track of the last type seen
  2234. # and complains if the header types are out of order or missing.
  2235. error_message = include_state.check_next_include_order(header_type,
  2236. file_extension == "h",
  2237. primary_header_exists)
  2238. # Check to make sure we have a blank line after primary header.
  2239. if not error_message and header_type == _PRIMARY_HEADER:
  2240. next_line = clean_lines.raw_lines[line_number + 1]
  2241. if not is_blank_line(next_line):
  2242. error(line_number, 'build/include_order', 4,
  2243. 'You should add a blank line after implementation file\'s own header.')
  2244. # Check to make sure all headers besides config.h and the primary header are
  2245. # alphabetically sorted. Skip Qt's moc files.
  2246. if not error_message and header_type == _OTHER_HEADER:
  2247. previous_line_number = line_number - 1;
  2248. previous_line = clean_lines.lines[previous_line_number]
  2249. previous_match = _RE_PATTERN_INCLUDE.search(previous_line)
  2250. while (not previous_match and previous_line_number > 0
  2251. and not search(r'\A(#if|#ifdef|#ifndef|#else|#elif|#endif)', previous_line)):
  2252. previous_line_number -= 1;
  2253. previous_line = clean_lines.lines[previous_line_number]
  2254. previous_match = _RE_PATTERN_INCLUDE.search(previous_line)
  2255. if previous_match:
  2256. previous_header_type = include_state.header_types[previous_line_number]
  2257. if previous_header_type == _OTHER_HEADER and previous_line.strip() > line.strip():
  2258. error(line_number, 'build/include_order', 4,
  2259. 'Alphabetical sorting problem.')
  2260. if error_message:
  2261. if file_extension == 'h':
  2262. error(line_number, 'build/include_order', 4,
  2263. '%s Should be: alphabetically sorted.' %
  2264. error_message)
  2265. else:
  2266. error(line_number, 'build/include_order', 4,
  2267. '%s Should be: primary header, blank line, and then alphabetically sorted.' %
  2268. error_message)
  2269. def check_language(filename, clean_lines, line_number, file_extension, include_state,
  2270. file_state, error):
  2271. """Checks rules from the 'C++ language rules' section of cppguide.html.
  2272. Some of these rules are hard to test (function overloading, using
  2273. uint32 inappropriately), but we do the best we can.
  2274. Args:
  2275. filename: The name of the current file.
  2276. clean_lines: A CleansedLines instance containing the file.
  2277. line_number: The number of the line to check.
  2278. file_extension: The extension (without the dot) of the filename.
  2279. include_state: An _IncludeState instance in which the headers are inserted.
  2280. file_state: A _FileState instance which maintains information about
  2281. the state of things in the file.
  2282. error: The function to call with any errors found.
  2283. """
  2284. # If the line is empty or consists of entirely a comment, no need to
  2285. # check it.
  2286. line = clean_lines.elided[line_number]
  2287. if not line:
  2288. return
  2289. matched = _RE_PATTERN_INCLUDE.search(line)
  2290. if matched:
  2291. check_include_line(filename, file_extension, clean_lines, line_number, include_state, error)
  2292. return
  2293. # FIXME: figure out if they're using default arguments in fn proto.
  2294. # Check to see if they're using an conversion function cast.
  2295. # I just try to capture the most common basic types, though there are more.
  2296. # Parameterless conversion functions, such as bool(), are allowed as they are
  2297. # probably a member operator declaration or default constructor.
  2298. matched = search(
  2299. r'\b(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line)
  2300. if matched:
  2301. # gMock methods are defined using some variant of MOCK_METHODx(name, type)
  2302. # where type may be float(), int(string), etc. Without context they are
  2303. # virtually indistinguishable from int(x) casts.
  2304. if not match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line):
  2305. error(line_number, 'readability/casting', 4,
  2306. 'Using deprecated casting style. '
  2307. 'Use static_cast<%s>(...) instead' %
  2308. matched.group(1))
  2309. check_c_style_cast(line_number, line, clean_lines.raw_lines[line_number],
  2310. 'static_cast',
  2311. r'\((int|float|double|bool|char|u?int(16|32|64))\)',
  2312. error)
  2313. # This doesn't catch all cases. Consider (const char * const)"hello".
  2314. check_c_style_cast(line_number, line, clean_lines.raw_lines[line_number],
  2315. 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
  2316. # In addition, we look for people taking the address of a cast. This
  2317. # is dangerous -- casts can assign to temporaries, so the pointer doesn't
  2318. # point where you think.
  2319. if search(
  2320. r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line):
  2321. error(line_number, 'runtime/casting', 4,
  2322. ('Are you taking an address of a cast? '
  2323. 'This is dangerous: could be a temp var. '
  2324. 'Take the address before doing the cast, rather than after'))
  2325. # Check for people declaring static/global STL strings at the top level.
  2326. # This is dangerous because the C++ language does not guarantee that
  2327. # globals with constructors are initialized before the first access.
  2328. matched = match(
  2329. r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
  2330. line)
  2331. # Make sure it's not a function.
  2332. # Function template specialization looks like: "string foo<Type>(...".
  2333. # Class template definitions look like: "string Foo<Type>::Method(...".
  2334. if matched and not match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)',
  2335. matched.group(3)):
  2336. error(line_number, 'runtime/string', 4,
  2337. 'For a static/global string constant, use a C style string instead: '
  2338. '"%schar %s[]".' %
  2339. (matched.group(1), matched.group(2)))
  2340. # Check that we're not using RTTI outside of testing code.
  2341. if search(r'\bdynamic_cast<', line):
  2342. error(line_number, 'runtime/rtti', 5,
  2343. 'Do not use dynamic_cast<>. If you need to cast within a class '
  2344. "hierarchy, use static_cast<> to upcast. Google doesn't support "
  2345. 'RTTI.')
  2346. if search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
  2347. error(line_number, 'runtime/init', 4,
  2348. 'You seem to be initializing a member variable with itself.')
  2349. if file_extension == 'h':
  2350. # FIXME: check that 1-arg constructors are explicit.
  2351. # How to tell it's a constructor?
  2352. # (handled in check_for_non_standard_constructs for now)
  2353. pass
  2354. # Check if people are using the verboten C basic types. The only exception
  2355. # we regularly allow is "unsigned short port" for port.
  2356. if search(r'\bshort port\b', line):
  2357. if not search(r'\bunsigned short port\b', line):
  2358. error(line_number, 'runtime/int', 4,
  2359. 'Use "unsigned short" for ports, not "short"')
  2360. # When snprintf is used, the second argument shouldn't be a literal.
  2361. matched = search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
  2362. if matched:
  2363. error(line_number, 'runtime/printf', 3,
  2364. 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
  2365. 'to snprintf.' % (matched.group(1), matched.group(2)))
  2366. # Check if some verboten C functions are being used.
  2367. if search(r'\bsprintf\b', line):
  2368. error(line_number, 'runtime/printf', 5,
  2369. 'Never use sprintf. Use snprintf instead.')
  2370. matched = search(r'\b(strcpy|strcat)\b', line)
  2371. if matched:
  2372. error(line_number, 'runtime/printf', 4,
  2373. 'Almost always, snprintf is better than %s' % matched.group(1))
  2374. if search(r'\bsscanf\b', line):
  2375. error(line_number, 'runtime/printf', 1,
  2376. 'sscanf can be ok, but is slow and can overflow buffers.')
  2377. # Check for suspicious usage of "if" like
  2378. # } if (a == b) {
  2379. if search(r'\}\s*if\s*\(', line):
  2380. error(line_number, 'readability/braces', 4,
  2381. 'Did you mean "else if"? If not, start a new line for "if".')
  2382. # Check for potential format string bugs like printf(foo).
  2383. # We constrain the pattern not to pick things like DocidForPrintf(foo).
  2384. # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
  2385. matched = re.search(r'\b((?:string)?printf)\s*\(([\w.\->()]+)\)', line, re.I)
  2386. if matched:
  2387. error(line_number, 'runtime/printf', 4,
  2388. 'Potential format string bug. Do %s("%%s", %s) instead.'
  2389. % (matched.group(1), matched.group(2)))
  2390. # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
  2391. matched = search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
  2392. if matched and not match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", matched.group(2)):
  2393. error(line_number, 'runtime/memset', 4,
  2394. 'Did you mean "memset(%s, 0, %s)"?'
  2395. % (matched.group(1), matched.group(2)))
  2396. # Detect variable-length arrays.
  2397. matched = match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
  2398. if (matched and matched.group(2) != 'return' and matched.group(2) != 'delete' and
  2399. matched.group(3).find(']') == -1):
  2400. # Split the size using space and arithmetic operators as delimiters.
  2401. # If any of the resulting tokens are not compile time constants then
  2402. # report the error.
  2403. tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', matched.group(3))
  2404. is_const = True
  2405. skip_next = False
  2406. for tok in tokens:
  2407. if skip_next:
  2408. skip_next = False
  2409. continue
  2410. if search(r'sizeof\(.+\)', tok):
  2411. continue
  2412. if search(r'arraysize\(\w+\)', tok):
  2413. continue
  2414. tok = tok.lstrip('(')
  2415. tok = tok.rstrip(')')
  2416. if not tok:
  2417. continue
  2418. if match(r'\d+', tok):
  2419. continue
  2420. if match(r'0[xX][0-9a-fA-F]+', tok):
  2421. continue
  2422. if match(r'k[A-Z0-9]\w*', tok):
  2423. continue
  2424. if match(r'(.+::)?k[A-Z0-9]\w*', tok):
  2425. continue
  2426. if match(r'(.+::)?[A-Z][A-Z0-9_]*', tok):
  2427. continue
  2428. # A catch all for tricky sizeof cases, including 'sizeof expression',
  2429. # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
  2430. # requires skipping the next token becasue we split on ' ' and '*'.
  2431. if tok.startswith('sizeof'):
  2432. skip_next = True
  2433. continue
  2434. is_const = False
  2435. break
  2436. if not is_const:
  2437. error(line_number, 'runtime/arrays', 1,
  2438. 'Do not use variable-length arrays. Use an appropriately named '
  2439. "('k' followed by CamelCase) compile-time constant for the size.")
  2440. # Check for use of unnamed namespaces in header files. Registration
  2441. # macros are typically OK, so we allow use of "namespace {" on lines
  2442. # that end with backslashes.
  2443. if (file_extension == 'h'
  2444. and search(r'\bnamespace\s*{', line)
  2445. and line[-1] != '\\'):
  2446. error(line_number, 'build/namespaces', 4,
  2447. 'Do not use unnamed namespaces in header files. See '
  2448. 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
  2449. ' for more information.')
  2450. # Check for plain bitfields declared without either "singed" or "unsigned".
  2451. # Most compilers treat such bitfields as signed, but there are still compilers like
  2452. # RVCT 4.0 that use unsigned by default.
  2453. matched = re.match(r'\s*((const|mutable)\s+)?(char|(short(\s+int)?)|int|long(\s+(long|int))?)\s+[a-zA-Z_][a-zA-Z0-9_]*\s*:\s*\d+\s*;', line)
  2454. if matched:
  2455. error(line_number, 'runtime/bitfields', 5,
  2456. 'Please declare integral type bitfields with either signed or unsigned.')
  2457. check_identifier_name_in_declaration(filename, line_number, line, file_state, error)
  2458. def check_identifier_name_in_declaration(filename, line_number, line, file_state, error):
  2459. """Checks if identifier names contain any underscores.
  2460. As identifiers in libraries we are using have a bunch of
  2461. underscores, we only warn about the declarations of identifiers
  2462. and don't check use of identifiers.
  2463. Args:
  2464. filename: The name of the current file.
  2465. line_number: The number of the line to check.
  2466. line: The line of code to check.
  2467. file_state: A _FileState instance which maintains information about
  2468. the state of things in the file.
  2469. error: The function to call with any errors found.
  2470. """
  2471. # We don't check a return statement.
  2472. if match(r'\s*(return|delete)\b', line):
  2473. return
  2474. # Basically, a declaration is a type name followed by whitespaces
  2475. # followed by an identifier. The type name can be complicated
  2476. # due to type adjectives and templates. We remove them first to
  2477. # simplify the process to find declarations of identifiers.
  2478. # Convert "long long", "long double", and "long long int" to
  2479. # simple types, but don't remove simple "long".
  2480. line = sub(r'long (long )?(?=long|double|int)', '', line)
  2481. # Convert unsigned/signed types to simple types, too.
  2482. line = sub(r'(unsigned|signed) (?=char|short|int|long)', '', line)
  2483. line = sub(r'\b(inline|using|static|const|volatile|auto|register|extern|typedef|restrict|struct|class|virtual)(?=\W)', '', line)
  2484. # Remove "new" and "new (expr)" to simplify, too.
  2485. line = sub(r'new\s*(\([^)]*\))?', '', line)
  2486. # Remove all template parameters by removing matching < and >.
  2487. # Loop until no templates are removed to remove nested templates.
  2488. while True:
  2489. line, number_of_replacements = subn(r'<([\w\s:]|::)+\s*[*&]*\s*>', '', line)
  2490. if not number_of_replacements:
  2491. break
  2492. # Declarations of local variables can be in condition expressions
  2493. # of control flow statements (e.g., "if (RenderObject* p = o->parent())").
  2494. # We remove the keywords and the first parenthesis.
  2495. #
  2496. # Declarations in "while", "if", and "switch" are different from
  2497. # other declarations in two aspects:
  2498. #
  2499. # - There can be only one declaration between the parentheses.
  2500. # (i.e., you cannot write "if (int i = 0, j = 1) {}")
  2501. # - The variable must be initialized.
  2502. # (i.e., you cannot write "if (int i) {}")
  2503. #
  2504. # and we will need different treatments for them.
  2505. line = sub(r'^\s*for\s*\(', '', line)
  2506. line, control_statement = subn(r'^\s*(while|else if|if|switch)\s*\(', '', line)
  2507. # Detect variable and functions.
  2508. type_regexp = r'\w([\w]|\s*[*&]\s*|::)+'
  2509. identifier_regexp = r'(?P<identifier>[\w:]+)'
  2510. maybe_bitfield_regexp = r'(:\s*\d+\s*)?'
  2511. character_after_identifier_regexp = r'(?P<character_after_identifier>[[;()=,])(?!=)'
  2512. declaration_without_type_regexp = r'\s*' + identifier_regexp + r'\s*' + maybe_bitfield_regexp + character_after_identifier_regexp
  2513. declaration_with_type_regexp = r'\s*' + type_regexp + r'\s' + declaration_without_type_regexp
  2514. is_function_arguments = False
  2515. number_of_identifiers = 0
  2516. while True:
  2517. # If we are seeing the first identifier or arguments of a
  2518. # function, there should be a type name before an identifier.
  2519. if not number_of_identifiers or is_function_arguments:
  2520. declaration_regexp = declaration_with_type_regexp
  2521. else:
  2522. declaration_regexp = declaration_without_type_regexp
  2523. matched = match(declaration_regexp, line)
  2524. if not matched:
  2525. return
  2526. identifier = matched.group('identifier')
  2527. character_after_identifier = matched.group('character_after_identifier')
  2528. # If we removed a non-for-control statement, the character after
  2529. # the identifier should be '='. With this rule, we can avoid
  2530. # warning for cases like "if (val & INT_MAX) {".
  2531. if control_statement and character_after_identifier != '=':
  2532. return
  2533. is_function_arguments = is_function_arguments or character_after_identifier == '('
  2534. # Remove "m_" and "s_" to allow them.
  2535. modified_identifier = sub(r'(^|(?<=::))[ms]_', '', identifier)
  2536. if not file_state.is_objective_c() and modified_identifier.find('_') >= 0:
  2537. # Various exceptions to the rule: JavaScript op codes functions, const_iterator.
  2538. if (not (filename.find('JavaScriptCore') >= 0 and modified_identifier.find('op_') >= 0)
  2539. and not (filename.find('gtk') >= 0 and modified_identifier.startswith('webkit_') >= 0)
  2540. and not modified_identifier.startswith('tst_')
  2541. and not modified_identifier.startswith('webkit_dom_object_')
  2542. and not modified_identifier.startswith('NPN_')
  2543. and not modified_identifier.startswith('NPP_')
  2544. and not modified_identifier.startswith('NP_')
  2545. and not modified_identifier.startswith('qt_')
  2546. and not modified_identifier.startswith('cairo_')
  2547. and not modified_identifier.startswith('Ecore_')
  2548. and not modified_identifier.startswith('Eina_')
  2549. and not modified_identifier.startswith('Evas_')
  2550. and not modified_identifier.find('::qt_') >= 0
  2551. and not modified_identifier == "const_iterator"
  2552. and not modified_identifier == "vm_throw"):
  2553. error(line_number, 'readability/naming', 4, identifier + " is incorrectly named. Don't use underscores in your identifier names.")
  2554. # Check for variables named 'l', these are too easy to confuse with '1' in some fonts
  2555. if modified_identifier == 'l':
  2556. error(line_number, 'readability/naming', 4, identifier + " is incorrectly named. Don't use the single letter 'l' as an identifier name.")
  2557. # There can be only one declaration in non-for-control statements.
  2558. if control_statement:
  2559. return
  2560. # We should continue checking if this is a function
  2561. # declaration because we need to check its arguments.
  2562. # Also, we need to check multiple declarations.
  2563. if character_after_identifier != '(' and character_after_identifier != ',':
  2564. return
  2565. number_of_identifiers += 1
  2566. line = line[matched.end():]
  2567. def check_c_style_cast(line_number, line, raw_line, cast_type, pattern,
  2568. error):
  2569. """Checks for a C-style cast by looking for the pattern.
  2570. This also handles sizeof(type) warnings, due to similarity of content.
  2571. Args:
  2572. line_number: The number of the line to check.
  2573. line: The line of code to check.
  2574. raw_line: The raw line of code to check, with comments.
  2575. cast_type: The string for the C++ cast to recommend. This is either
  2576. reinterpret_cast or static_cast, depending.
  2577. pattern: The regular expression used to find C-style casts.
  2578. error: The function to call with any errors found.
  2579. """
  2580. matched = search(pattern, line)
  2581. if not matched:
  2582. return
  2583. # e.g., sizeof(int)
  2584. sizeof_match = match(r'.*sizeof\s*$', line[0:matched.start(1) - 1])
  2585. if sizeof_match:
  2586. error(line_number, 'runtime/sizeof', 1,
  2587. 'Using sizeof(type). Use sizeof(varname) instead if possible')
  2588. return
  2589. remainder = line[matched.end(0):]
  2590. # The close paren is for function pointers as arguments to a function.
  2591. # eg, void foo(void (*bar)(int));
  2592. # The semicolon check is a more basic function check; also possibly a
  2593. # function pointer typedef.
  2594. # eg, void foo(int); or void foo(int) const;
  2595. # The equals check is for function pointer assignment.
  2596. # eg, void *(*foo)(int) = ...
  2597. #
  2598. # Right now, this will only catch cases where there's a single argument, and
  2599. # it's unnamed. It should probably be expanded to check for multiple
  2600. # arguments with some unnamed.
  2601. function_match = match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)))', remainder)
  2602. if function_match:
  2603. if (not function_match.group(3)
  2604. or function_match.group(3) == ';'
  2605. or raw_line.find('/*') < 0):
  2606. error(line_number, 'readability/function', 3,
  2607. 'All parameters should be named in a function')
  2608. return
  2609. # At this point, all that should be left is actual casts.
  2610. error(line_number, 'readability/casting', 4,
  2611. 'Using C-style cast. Use %s<%s>(...) instead' %
  2612. (cast_type, matched.group(1)))
  2613. _HEADERS_CONTAINING_TEMPLATES = (
  2614. ('<deque>', ('deque',)),
  2615. ('<functional>', ('unary_function', 'binary_function',
  2616. 'plus', 'minus', 'multiplies', 'divides', 'modulus',
  2617. 'negate',
  2618. 'equal_to', 'not_equal_to', 'greater', 'less',
  2619. 'greater_equal', 'less_equal',
  2620. 'logical_and', 'logical_or', 'logical_not',
  2621. 'unary_negate', 'not1', 'binary_negate', 'not2',
  2622. 'bind1st', 'bind2nd',
  2623. 'pointer_to_unary_function',
  2624. 'pointer_to_binary_function',
  2625. 'ptr_fun',
  2626. 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
  2627. 'mem_fun_ref_t',
  2628. 'const_mem_fun_t', 'const_mem_fun1_t',
  2629. 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
  2630. 'mem_fun_ref',
  2631. )),
  2632. ('<limits>', ('numeric_limits',)),
  2633. ('<list>', ('list',)),
  2634. ('<map>', ('map', 'multimap',)),
  2635. ('<memory>', ('allocator',)),
  2636. ('<queue>', ('queue', 'priority_queue',)),
  2637. ('<set>', ('set', 'multiset',)),
  2638. ('<stack>', ('stack',)),
  2639. ('<string>', ('char_traits', 'basic_string',)),
  2640. ('<utility>', ('pair',)),
  2641. ('<vector>', ('vector',)),
  2642. # gcc extensions.
  2643. # Note: std::hash is their hash, ::hash is our hash
  2644. ('<hash_map>', ('hash_map', 'hash_multimap',)),
  2645. ('<hash_set>', ('hash_set', 'hash_multiset',)),
  2646. ('<slist>', ('slist',)),
  2647. )
  2648. _HEADERS_ACCEPTED_BUT_NOT_PROMOTED = {
  2649. # We can trust with reasonable confidence that map gives us pair<>, too.
  2650. 'pair<>': ('map', 'multimap', 'hash_map', 'hash_multimap')
  2651. }
  2652. _RE_PATTERN_STRING = re.compile(r'\bstring\b')
  2653. _re_pattern_algorithm_header = []
  2654. for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
  2655. 'transform'):
  2656. # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
  2657. # type::max().
  2658. _re_pattern_algorithm_header.append(
  2659. (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
  2660. _template,
  2661. '<algorithm>'))
  2662. _re_pattern_templates = []
  2663. for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
  2664. for _template in _templates:
  2665. _re_pattern_templates.append(
  2666. (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
  2667. _template + '<>',
  2668. _header))
  2669. def files_belong_to_same_module(filename_cpp, filename_h):
  2670. """Check if these two filenames belong to the same module.
  2671. The concept of a 'module' here is a as follows:
  2672. foo.h, foo-inl.h, foo.cpp, foo_test.cpp and foo_unittest.cpp belong to the
  2673. same 'module' if they are in the same directory.
  2674. some/path/public/xyzzy and some/path/internal/xyzzy are also considered
  2675. to belong to the same module here.
  2676. If the filename_cpp contains a longer path than the filename_h, for example,
  2677. '/absolute/path/to/base/sysinfo.cpp', and this file would include
  2678. 'base/sysinfo.h', this function also produces the prefix needed to open the
  2679. header. This is used by the caller of this function to more robustly open the
  2680. header file. We don't have access to the real include paths in this context,
  2681. so we need this guesswork here.
  2682. Known bugs: tools/base/bar.cpp and base/bar.h belong to the same module
  2683. according to this implementation. Because of this, this function gives
  2684. some false positives. This should be sufficiently rare in practice.
  2685. Args:
  2686. filename_cpp: is the path for the .cpp file
  2687. filename_h: is the path for the header path
  2688. Returns:
  2689. Tuple with a bool and a string:
  2690. bool: True if filename_cpp and filename_h belong to the same module.
  2691. string: the additional prefix needed to open the header file.
  2692. """
  2693. if not filename_cpp.endswith('.cpp'):
  2694. return (False, '')
  2695. filename_cpp = filename_cpp[:-len('.cpp')]
  2696. if filename_cpp.endswith('_unittest'):
  2697. filename_cpp = filename_cpp[:-len('_unittest')]
  2698. elif filename_cpp.endswith('_test'):
  2699. filename_cpp = filename_cpp[:-len('_test')]
  2700. filename_cpp = filename_cpp.replace('/public/', '/')
  2701. filename_cpp = filename_cpp.replace('/internal/', '/')
  2702. if not filename_h.endswith('.h'):
  2703. return (False, '')
  2704. filename_h = filename_h[:-len('.h')]
  2705. if filename_h.endswith('-inl'):
  2706. filename_h = filename_h[:-len('-inl')]
  2707. filename_h = filename_h.replace('/public/', '/')
  2708. filename_h = filename_h.replace('/internal/', '/')
  2709. files_belong_to_same_module = filename_cpp.endswith(filename_h)
  2710. common_path = ''
  2711. if files_belong_to_same_module:
  2712. common_path = filename_cpp[:-len(filename_h)]
  2713. return files_belong_to_same_module, common_path
  2714. def update_include_state(filename, include_state, io=codecs):
  2715. """Fill up the include_state with new includes found from the file.
  2716. Args:
  2717. filename: the name of the header to read.
  2718. include_state: an _IncludeState instance in which the headers are inserted.
  2719. io: The io factory to use to read the file. Provided for testability.
  2720. Returns:
  2721. True if a header was succesfully added. False otherwise.
  2722. """
  2723. io = _unit_test_config.get(INCLUDE_IO_INJECTION_KEY, codecs)
  2724. header_file = None
  2725. try:
  2726. header_file = io.open(filename, 'r', 'utf8', 'replace')
  2727. except IOError:
  2728. return False
  2729. line_number = 0
  2730. for line in header_file:
  2731. line_number += 1
  2732. clean_line = cleanse_comments(line)
  2733. matched = _RE_PATTERN_INCLUDE.search(clean_line)
  2734. if matched:
  2735. include = matched.group(2)
  2736. # The value formatting is cute, but not really used right now.
  2737. # What matters here is that the key is in include_state.
  2738. include_state.setdefault(include, '%s:%d' % (filename, line_number))
  2739. return True
  2740. def check_for_include_what_you_use(filename, clean_lines, include_state, error):
  2741. """Reports for missing stl includes.
  2742. This function will output warnings to make sure you are including the headers
  2743. necessary for the stl containers and functions that you use. We only give one
  2744. reason to include a header. For example, if you use both equal_to<> and
  2745. less<> in a .h file, only one (the latter in the file) of these will be
  2746. reported as a reason to include the <functional>.
  2747. Args:
  2748. filename: The name of the current file.
  2749. clean_lines: A CleansedLines instance containing the file.
  2750. include_state: An _IncludeState instance.
  2751. error: The function to call with any errors found.
  2752. """
  2753. required = {} # A map of header name to line_number and the template entity.
  2754. # Example of required: { '<functional>': (1219, 'less<>') }
  2755. for line_number in xrange(clean_lines.num_lines()):
  2756. line = clean_lines.elided[line_number]
  2757. if not line or line[0] == '#':
  2758. continue
  2759. # String is special -- it is a non-templatized type in STL.
  2760. if _RE_PATTERN_STRING.search(line):
  2761. required['<string>'] = (line_number, 'string')
  2762. for pattern, template, header in _re_pattern_algorithm_header:
  2763. if pattern.search(line):
  2764. required[header] = (line_number, template)
  2765. # The following function is just a speed up, no semantics are changed.
  2766. if not '<' in line: # Reduces the cpu time usage by skipping lines.
  2767. continue
  2768. for pattern, template, header in _re_pattern_templates:
  2769. if pattern.search(line):
  2770. required[header] = (line_number, template)
  2771. # The policy is that if you #include something in foo.h you don't need to
  2772. # include it again in foo.cpp. Here, we will look at possible includes.
  2773. # Let's copy the include_state so it is only messed up within this function.
  2774. include_state = include_state.copy()
  2775. # Did we find the header for this file (if any) and succesfully load it?
  2776. header_found = False
  2777. # Use the absolute path so that matching works properly.
  2778. abs_filename = os.path.abspath(filename)
  2779. # For Emacs's flymake.
  2780. # If cpp_style is invoked from Emacs's flymake, a temporary file is generated
  2781. # by flymake and that file name might end with '_flymake.cpp'. In that case,
  2782. # restore original file name here so that the corresponding header file can be
  2783. # found.
  2784. # e.g. If the file name is 'foo_flymake.cpp', we should search for 'foo.h'
  2785. # instead of 'foo_flymake.h'
  2786. abs_filename = re.sub(r'_flymake\.cpp$', '.cpp', abs_filename)
  2787. # include_state is modified during iteration, so we iterate over a copy of
  2788. # the keys.
  2789. for header in include_state.keys(): #NOLINT
  2790. (same_module, common_path) = files_belong_to_same_module(abs_filename, header)
  2791. fullpath = common_path + header
  2792. if same_module and update_include_state(fullpath, include_state):
  2793. header_found = True
  2794. # If we can't find the header file for a .cpp, assume it's because we don't
  2795. # know where to look. In that case we'll give up as we're not sure they
  2796. # didn't include it in the .h file.
  2797. # FIXME: Do a better job of finding .h files so we are confident that
  2798. # not having the .h file means there isn't one.
  2799. if filename.endswith('.cpp') and not header_found:
  2800. return
  2801. # All the lines have been processed, report the errors found.
  2802. for required_header_unstripped in required:
  2803. template = required[required_header_unstripped][1]
  2804. if template in _HEADERS_ACCEPTED_BUT_NOT_PROMOTED:
  2805. headers = _HEADERS_ACCEPTED_BUT_NOT_PROMOTED[template]
  2806. if [True for header in headers if header in include_state]:
  2807. continue
  2808. if required_header_unstripped.strip('<>"') not in include_state:
  2809. error(required[required_header_unstripped][0],
  2810. 'build/include_what_you_use', 4,
  2811. 'Add #include ' + required_header_unstripped + ' for ' + template)
  2812. def process_line(filename, file_extension,
  2813. clean_lines, line, include_state, function_state,
  2814. class_state, file_state, error):
  2815. """Processes a single line in the file.
  2816. Args:
  2817. filename: Filename of the file that is being processed.
  2818. file_extension: The extension (dot not included) of the file.
  2819. clean_lines: An array of strings, each representing a line of the file,
  2820. with comments stripped.
  2821. line: Number of line being processed.
  2822. include_state: An _IncludeState instance in which the headers are inserted.
  2823. function_state: A _FunctionState instance which counts function lines, etc.
  2824. class_state: A _ClassState instance which maintains information about
  2825. the current stack of nested class declarations being parsed.
  2826. file_state: A _FileState instance which maintains information about
  2827. the state of things in the file.
  2828. error: A callable to which errors are reported, which takes arguments:
  2829. line number, error level, and message
  2830. """
  2831. raw_lines = clean_lines.raw_lines
  2832. detect_functions(clean_lines, line, function_state, error)
  2833. check_for_function_lengths(clean_lines, line, function_state, error)
  2834. if search(r'\bNOLINT\b', raw_lines[line]): # ignore nolint lines
  2835. return
  2836. if match(r'\s*\b__asm\b', raw_lines[line]): # Ignore asm lines as they format differently.
  2837. return
  2838. check_function_definition(filename, file_extension, clean_lines, line, function_state, error)
  2839. check_pass_ptr_usage(clean_lines, line, function_state, error)
  2840. check_for_multiline_comments_and_strings(clean_lines, line, error)
  2841. check_style(clean_lines, line, file_extension, class_state, file_state, error)
  2842. check_language(filename, clean_lines, line, file_extension, include_state,
  2843. file_state, error)
  2844. check_for_non_standard_constructs(clean_lines, line, class_state, error)
  2845. check_posix_threading(clean_lines, line, error)
  2846. check_invalid_increment(clean_lines, line, error)
  2847. def _process_lines(filename, file_extension, lines, error, min_confidence):
  2848. """Performs lint checks and reports any errors to the given error function.
  2849. Args:
  2850. filename: Filename of the file that is being processed.
  2851. file_extension: The extension (dot not included) of the file.
  2852. lines: An array of strings, each representing a line of the file, with the
  2853. last element being empty if the file is termined with a newline.
  2854. error: A callable to which errors are reported, which takes 4 arguments:
  2855. """
  2856. lines = (['// marker so line numbers and indices both start at 1'] + lines +
  2857. ['// marker so line numbers end in a known way'])
  2858. include_state = _IncludeState()
  2859. function_state = _FunctionState(min_confidence)
  2860. class_state = _ClassState()
  2861. check_for_copyright(lines, error)
  2862. if file_extension == 'h':
  2863. check_for_header_guard(filename, lines, error)
  2864. remove_multi_line_comments(lines, error)
  2865. clean_lines = CleansedLines(lines)
  2866. file_state = _FileState(clean_lines, file_extension)
  2867. for line in xrange(clean_lines.num_lines()):
  2868. process_line(filename, file_extension, clean_lines, line,
  2869. include_state, function_state, class_state, file_state, error)
  2870. class_state.check_finished(error)
  2871. check_for_include_what_you_use(filename, clean_lines, include_state, error)
  2872. # We check here rather than inside process_line so that we see raw
  2873. # lines rather than "cleaned" lines.
  2874. check_for_unicode_replacement_characters(lines, error)
  2875. check_for_new_line_at_eof(lines, error)
  2876. class CppChecker(object):
  2877. """Processes C++ lines for checking style."""
  2878. # This list is used to--
  2879. #
  2880. # (1) generate an explicit list of all possible categories,
  2881. # (2) unit test that all checked categories have valid names, and
  2882. # (3) unit test that all categories are getting unit tested.
  2883. #
  2884. categories = set([
  2885. 'build/class',
  2886. 'build/deprecated',
  2887. 'build/endif_comment',
  2888. 'build/forward_decl',
  2889. 'build/header_guard',
  2890. 'build/include',
  2891. 'build/include_order',
  2892. 'build/include_what_you_use',
  2893. 'build/namespaces',
  2894. 'build/printf_format',
  2895. 'build/storage_class',
  2896. 'build/using_std',
  2897. 'legal/copyright',
  2898. 'readability/braces',
  2899. 'readability/casting',
  2900. 'readability/check',
  2901. 'readability/comparison_to_zero',
  2902. 'readability/constructors',
  2903. 'readability/control_flow',
  2904. 'readability/fn_size',
  2905. 'readability/function',
  2906. 'readability/multiline_comment',
  2907. 'readability/multiline_string',
  2908. 'readability/parameter_name',
  2909. 'readability/naming',
  2910. 'readability/null',
  2911. 'readability/pass_ptr',
  2912. 'readability/streams',
  2913. 'readability/todo',
  2914. 'readability/utf8',
  2915. 'readability/webkit_export',
  2916. 'runtime/arrays',
  2917. 'runtime/bitfields',
  2918. 'runtime/casting',
  2919. 'runtime/explicit',
  2920. 'runtime/init',
  2921. 'runtime/int',
  2922. 'runtime/invalid_increment',
  2923. 'runtime/max_min_macros',
  2924. 'runtime/memset',
  2925. 'runtime/printf',
  2926. 'runtime/printf_format',
  2927. 'runtime/references',
  2928. 'runtime/rtti',
  2929. 'runtime/sizeof',
  2930. 'runtime/string',
  2931. 'runtime/threadsafe_fn',
  2932. 'runtime/virtual',
  2933. 'whitespace/blank_line',
  2934. 'whitespace/braces',
  2935. 'whitespace/comma',
  2936. 'whitespace/comments',
  2937. 'whitespace/declaration',
  2938. 'whitespace/end_of_line',
  2939. 'whitespace/ending_newline',
  2940. 'whitespace/indent',
  2941. 'whitespace/labels',
  2942. 'whitespace/line_length',
  2943. 'whitespace/newline',
  2944. 'whitespace/operators',
  2945. 'whitespace/parens',
  2946. 'whitespace/semicolon',
  2947. 'whitespace/tab',
  2948. 'whitespace/todo',
  2949. ])
  2950. def __init__(self, file_path, file_extension, handle_style_error,
  2951. min_confidence):
  2952. """Create a CppChecker instance.
  2953. Args:
  2954. file_extension: A string that is the file extension, without
  2955. the leading dot.
  2956. """
  2957. self.file_extension = file_extension
  2958. self.file_path = file_path
  2959. self.handle_style_error = handle_style_error
  2960. self.min_confidence = min_confidence
  2961. # Useful for unit testing.
  2962. def __eq__(self, other):
  2963. """Return whether this CppChecker instance is equal to another."""
  2964. if self.file_extension != other.file_extension:
  2965. return False
  2966. if self.file_path != other.file_path:
  2967. return False
  2968. if self.handle_style_error != other.handle_style_error:
  2969. return False
  2970. if self.min_confidence != other.min_confidence:
  2971. return False
  2972. return True
  2973. # Useful for unit testing.
  2974. def __ne__(self, other):
  2975. # Python does not automatically deduce __ne__() from __eq__().
  2976. return not self.__eq__(other)
  2977. def check(self, lines):
  2978. _process_lines(self.file_path, self.file_extension, lines,
  2979. self.handle_style_error, self.min_confidence)
  2980. # FIXME: Remove this function (requires refactoring unit tests).
  2981. def process_file_data(filename, file_extension, lines, error, min_confidence, unit_test_config):
  2982. global _unit_test_config
  2983. _unit_test_config = unit_test_config
  2984. checker = CppChecker(filename, file_extension, error, min_confidence)
  2985. checker.check(lines)
  2986. _unit_test_config = {}