• Home
  • Raw
  • Download

Lines Matching +full:- +full:- +full:match +full:- +full:filename

31 """Does google-lint on c++ files.
34 be in non-compliance with google style. It does not attempt to fix
35 up these problems -- the point is to educate. It does also not
63 Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
64 [--counting=total|toplevel|detailed] [--root=subdir]
65 [--linelength=digits] [--headers=x,y,...]
66 [--quiet]
70 https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
72 Every problem is given a confidence score from 1-5, with 5 meaning we are
76 To suppress false-positive errors of a certain category, add a
82 extensions with the --extensions flag.
91 Specify a number 0-5 to restrict errors to certain verbosity levels.
96 filter=-x,+y,...
97 Specify a comma-separated list of category-filters to apply: only
101 "-FOO" and "FOO" means "do not print categories that start with FOO".
104 Examples: --filter=-whitespace,+whitespace/braces
105 --filter=whitespace,runtime/printf,+runtime/printf_format
106 --filter=-,+build/include_what_you_use
109 --filter=
114 the top-level categories like 'build' and 'whitespace' will
131 --root=chrome => BROWSER_UI_BROWSER_H_
132 --root=chrome/browser => UI_BROWSER_H_
133 --root=.. => SRC_CHROME_BROWSER_UI_BROWSER_H_
140 --linelength=120
146 --extensions=hpp,cpp
150 automatically added to --extensions list.
153 --headers=hpp,hxx
154 --headers=hpp
156 cpplint.py supports per-directory configurations specified in CPPLINT.cfg
161 filter=+filter1,-filter2,...
169 is usually placed in the top-level project directory.
171 The "filter" option is similar in function to --filter flag. It specifies
173 through --filter command-line flag.
181 The "root" option is similar in function to the --root flag (see example
184 The "headers" option is similar in function to the --headers flag
188 sub-directories, unless overridden by a nested configuration file.
191 filter=-build/include_order,+build/include_alpha
197 file is located) and all sub-directories.
201 # We want an explicit list so we can list them all in cpplint --filter=.
273 # These error categories are no longer enforced by cpplint, but for backwards-
280 # The default state of the category filter. This is overridden by the --filter=
282 # off by default (i.e., categories that must be enabled by the --filter= flags).
283 # All entries here should start with a '-' or '+', as in the --filter= flag.
284 _DEFAULT_FILTERS = ['-build/include_alpha']
296 # We used to check for high-bit characters, but after much discussion we
297 # decided those were OK, as long as they were in UTF-8 and didn't represent
298 # hard-coded international strings, which belong in a separate i18n file.
453 # - Anything not following google file name conventions (containing an
455 # - Lua headers.
457 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
494 # match those on a word boundary.
512 # False positives include C-style multi-line comments and multi-line strings
532 # Match start of assembly blocks
537 # Match strings that indicate we're working on a C (not C++) file.
541 # Match string that indicates we're working on a Linux Kernel file.
551 # This is set by --root flag.
556 # This is set by --linelength flag.
560 # This is set by --extensions flag.
564 # This is set by --headers flag.
583 def ParseNolintSuppressions(filename, raw_line, linenum, error): argument
584 """Updates the global list of line error-suppressions.
591 filename: str, the name of the input file.
607 category = category[1:-1]
611 error(filename, linenum, 'readability/nolint', 5,
657 def Match(pattern, s): function
659 # The regexp compilation caching is inlined in both Match and Search for
664 return _regexp_compile_cache[pattern].match(s)
670 The compiled regex is kept in a cache shared by Match and Search.
742 Line number of previous occurrence, or -1 if the header has not
749 return -1
767 self.include_list[-1] = []
775 - replaces "-" with "_" so they both cmp the same.
776 - removes '-inl' since we don't require them to be after the main header.
777 - lowercase everything, just in case.
785 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
804 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
809 """Returns a non-empty error message if the next header is out of order.
863 """Maintains module-wide state.."""
874 self.quiet = False # Suppress non-error messagess?
877 # "emacs" - format that emacs can parse (default)
878 # "vs7" - format that Microsoft Visual Studio 7 can parse
902 """Sets the error-message filters.
908 filters: A string of comma-separated filters (eg "+whitespace/indent").
909 Each filter should start with + or -; else we die.
912 ValueError: The comma-separated filters did not all start with '+' or '-'.
913 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
920 """ Adds more filters to the existing list of error-message filters. """
926 if not (filt.startswith('+') or filt.startswith('-')):
927 raise ValueError('Every filter in --filters must start with + or -'
1002 """Sets the module's error-message filters.
1008 filters: A string of comma-separated filters (eg "whitespace/indent").
1009 Each filter should start with + or -; else we die.
1020 filters: A string of comma-separated filters (eg "whitespace/indent").
1021 Each filter should start with + or -; else we die.
1036 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
1059 def Check(self, error, filename, linenum): argument
1064 filename: The name of the current file.
1070 if Match(r'T(EST|est)', self.current_function):
1081 error(filename, linenum, 'readability/fn_size', error_level,
1083 ' %s has %d non-comment lines'
1104 def __init__(self, filename): argument
1105 self._filename = filename
1172 """File base name - text after the final slash, before the final period."""
1176 """File extension - text following the final period."""
1202 if one_filter.startswith('-'):
1216 def Error(filename, linenum, category, confidence, message): argument
1228 filename: The name of the file containing the error.
1233 confidence: A number from 1-5 representing a confidence score for
1242 filename, linenum, category, message, confidence))
1245 filename, linenum, message, category, confidence))
1248 filename, linenum, message, category, confidence))
1253 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
1254 # Match a single C style comment on the same line.
1256 # Matches multi-line C style comments.
1262 # if this doesn't work we try on left side but only if there's a non-character
1274 This function does not consider single-line nor multi-line comments.
1284 line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
1285 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1293 multi-line string
1315 # Found the end of the string, match leading space for this
1318 leading_space = Match(r'^(\s*)\S', line)
1339 matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1341 not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
1352 # Start of a multi-line raw string
1385 """Clears a range of lines for multi-line comments."""
1386 # Having // dummy comments makes the lines non-empty, so we will not get
1392 def RemoveMultiLineComments(filename, lines, error): argument
1393 """Removes multiline (c-style) comments from lines."""
1401 error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
1402 'Could not find end of multi-line comment')
1409 """Removes //-comments and single-line C-style /* */ comments.
1415 The line with single-line comments removed.
1418 if commentpos != -1 and not IsCppString(line[:commentpos]):
1463 if _RE_PATTERN_INCLUDE.match(elided):
1477 match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
1478 if not match:
1481 head, quote, tail = match.groups()
1502 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1503 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1529 On finding an unclosed expression: (-1, None)
1530 Otherwise: (-1, new stack at end of this line)
1539 if i > 0 and line[i - 1] == '<':
1541 if stack and stack[-1] == '<':
1544 return (-1, None)
1556 while stack and stack[-1] == '<':
1559 return (-1, None)
1560 if ((stack[-1] == '(' and char == ')') or
1561 (stack[-1] == '[' and char == ']') or
1562 (stack[-1] == '{' and char == '}')):
1568 return (-1, None)
1572 # Ignore "->" and operator functions
1574 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1580 if stack[-1] == '<':
1588 while stack and stack[-1] == '<':
1591 return (-1, None)
1594 return (-1, stack)
1615 (line, len(lines), -1) if we never find a close. Note we ignore
1621 if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
1622 return (line, clean_lines.NumLines(), -1)
1626 if end_pos > -1:
1630 while stack and linenum < clean_lines.NumLines() - 1:
1634 if end_pos > -1:
1638 return (line, clean_lines.NumLines(), -1)
1654 On finding an unclosed expression: (-1, None)
1655 Otherwise: (-1, new stack at beginning of this line)
1666 # Ignore it if it's a "->" or ">=" or "operator>"
1668 (line[i - 1] == '-' or
1669 Match(r'\s>=\s', line[i - 1:]) or
1671 i -= 1
1676 if i > 0 and line[i - 1] == '<':
1678 i -= 1
1682 if stack and stack[-1] == '>':
1691 while stack and stack[-1] == '>':
1694 return (-1, None)
1695 if ((char == '(' and stack[-1] == ')') or
1696 (char == '[' and stack[-1] == ']') or
1697 (char == '{' and stack[-1] == '}')):
1703 return (-1, None)
1708 while stack and stack[-1] == '>':
1711 return (-1, None)
1713 i -= 1
1715 return (-1, stack)
1731 (line, 0, -1) if we never find the matching opening brace. Note
1737 return (line, 0, -1)
1741 if start_pos > -1:
1746 linenum -= 1
1748 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
1749 if start_pos > -1:
1753 return (line, 0, -1)
1756 def CheckForCopyright(filename, lines, error): argument
1764 error(filename, 0, 'legal/copyright', 5,
1778 indent = Match(r'^( *)\S', line)
1809 def GetHeaderGuardCPPVariable(filename): argument
1813 filename: The name of a C++ header file.
1821 # Restores original filename in case that cpplint is invoked from Emacs's
1823 filename = re.sub(r'_flymake\.h$', '.h', filename)
1824 filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
1826 filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
1828 fileinfo = FileInfo(filename)
1836 # Process the file path with the --root flag if it was set.
1843 # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
1846 # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
1850 # --root=subdir , lstrips subdir from the header guard
1861 # --root=.. , will prepend the outer directory to the header guard
1878 # --root=FAKE_DIR is ignored
1882 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
1885 def CheckForHeaderGuard(filename, clean_lines, error): argument
1892 filename: The name of the C++ header file.
1908 cppvar = GetHeaderGuardCPPVariable(filename)
1931 error(filename, 0, 'build/header_guard', 5,
1943 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
1945 error(filename, ifndef_linenum, 'build/header_guard', error_level,
1949 ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
1951 match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
1952 if match:
1953 if match.group(1) == '_':
1955 error(filename, endif_linenum, 'build/header_guard', 0,
1963 for i in xrange(1, len(raw_lines) - 1):
1965 if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
1970 match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
1971 if match:
1972 if match.group(1) == '_':
1974 error(filename, endif_linenum, 'build/header_guard', 0,
1979 error(filename, endif_linenum, 'build/header_guard', 5,
1983 def CheckHeaderFileIncluded(filename, include_state, error): argument
1987 fileinfo = FileInfo(filename)
1991 headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
2003 error(filename, first_include, 'build/include', 5,
2008 def CheckForBadCharacters(filename, lines, error): argument
2014 contained invalid UTF-8 (likely) or Unicode replacement characters (which
2016 numbering if the invalid UTF-8 occurred adjacent to a newline.
2021 filename: The name of the current file.
2027 error(filename, linenum, 'readability/utf8', 5,
2028 'Line contains invalid UTF-8 (or Unicode replacement character).')
2030 error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
2033 def CheckForNewlineAtEOF(filename, lines, error): argument
2037 filename: The name of the current file.
2045 # last-but-two element of lines() exists and is empty.
2046 if len(lines) < 3 or lines[-2]:
2047 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
2051 def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): argument
2063 filename: The name of the current file.
2075 error(filename, linenum, 'readability/multiline_comment', 5,
2076 'Complex multi-line /*...*/-style comment found. '
2078 'Consider replacing these with //-style comments, '
2080 'or with more clearly structured multi-line comments.')
2082 if (line.count('"') - line.count('\\"')) % 2:
2083 error(filename, linenum, 'readability/multiline_string', 5,
2084 'Multi-line string ("...") found. This lint script doesn\'t '
2089 # (non-threadsafe name, thread-safe alternative, validation pattern)
2092 # _rand(); // false positive due to substring match.
2093 # ->rand(); // some member function rand().
2101 _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
2119 def CheckPosixThreading(filename, clean_lines, linenum, error): argument
2120 """Checks for calls to thread-unsafe functions.
2123 multi-threading. Also, engineers are relying on their old experience;
2125 tests guide the engineers to use thread-safe functions (when using
2129 filename: The name of the current file.
2139 error(filename, linenum, 'runtime/threadsafe_fn', 2,
2145 def CheckVlogArguments(filename, clean_lines, linenum, error): argument
2152 filename: The name of the current file.
2159 error(filename, linenum, 'runtime/vlog', 5,
2166 r'^\s*\*\w+(\+\+|--);')
2169 def CheckInvalidIncrement(filename, clean_lines, linenum, error): argument
2180 filename: The name of the current file.
2186 if _RE_PATTERN_INVALID_INCREMENT.match(line):
2187 error(filename, linenum, 'runtime/invalid_increment', 5,
2195 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2202 return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
2215 def CheckBegin(self, filename, clean_lines, linenum, error): argument
2223 filename: The name of the current file.
2230 def CheckEnd(self, filename, clean_lines, linenum, error): argument
2236 filename: The name of the current file.
2290 depth += line.count('{') - line.count('}')
2295 def CheckBegin(self, filename, clean_lines, linenum, error): argument
2300 def CheckEnd(self, filename, clean_lines, linenum, error): argument
2304 for i in xrange(linenum - 1, self.starting_linenum, -1):
2305 match = Search(
2309 if match:
2311 error(filename, i, 'readability/constructors', 3,
2312 match.group(1) + ' should be the last thing in the class')
2315 if not Match(r'^\s*$', clean_lines.elided[i]):
2320 # This means we will not check single-line class definitions.
2321 indent = Match(r'^( *)\}', clean_lines.elided[linenum])
2327 error(filename, linenum, 'whitespace/indent', 3,
2339 def CheckEnd(self, filename, clean_lines, linenum, error): argument
2354 if (linenum - self.starting_linenum < 10
2355 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
2372 if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
2375 error(filename, linenum, 'readability/namespace', 5,
2380 if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
2383 if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
2384 error(filename, linenum, 'readability/namespace', 5,
2388 error(filename, linenum, 'readability/namespace', 5,
2413 # - _ClassInfo: a class or struct.
2414 # - _NamespaceInfo: a namespace.
2415 # - _BlockInfo: some other type of block.
2439 return (not self.stack) or self.stack[-1].seen_open_brace
2447 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2455 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2463 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2471 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2486 match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
2487 if not match:
2491 token = match.group(1)
2492 pos += len(match.group(0))
2517 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2536 - Preprocessor condition evaluates to true from #if up to first
2539 - Preprocessor condition evaluates to false from #else/#elif up
2546 if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
2550 elif Match(r'^\s*#\s*(else|elif)\b', line):
2553 if not self.pp_stack[-1].seen_else:
2557 self.pp_stack[-1].seen_else = True
2558 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2561 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2565 elif Match(r'^\s*#\s*endif\b', line):
2571 if self.pp_stack[-1].seen_else:
2574 self.stack = self.pp_stack[-1].stack_before_else
2582 def Update(self, filename, clean_lines, linenum, error): argument
2586 filename: The name of the current file.
2599 self.previous_stack_top = self.stack[-1]
2609 inner_block = self.stack[-1]
2610 depth_change = line.count('(') - line.count(')')
2617 _MATCH_ASM.match(line)):
2633 # Match start of namespace. The "\b\s*" below catches namespace
2637 namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
2645 if line.find('{') != -1:
2654 class_decl_match = Match(
2656 r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
2659 (not self.stack or self.stack[-1].open_parentheses == 0)):
2679 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2682 if self.stack and isinstance(self.stack[-1], _ClassInfo):
2683 classinfo = self.stack[-1]
2684 access_match = Match(
2695 Match(r'^\s*$', indent)):
2703 error(filename, linenum, 'whitespace/indent', 3,
2709 # Match first brace, semicolon, or closed parenthesis.
2710 matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
2720 self.stack[-1].seen_open_brace = True
2721 elif Match(r'^extern\s*"[^"]*"\s*\{', line):
2725 if _MATCH_ASM.match(line):
2726 self.stack[-1].inline_asm = _BLOCK_ASM
2742 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2752 for i in range(len(self.stack), 0, -1):
2753 classinfo = self.stack[i - 1]
2758 def CheckCompletedBlocks(self, filename, error): argument
2763 filename: The name of the current file.
2771 error(filename, obj.starting_linenum, 'build/class', 5,
2775 error(filename, obj.starting_linenum, 'build/namespaces', 5,
2780 def CheckForNonStandardConstructs(filename, clean_lines, linenum, argument
2782 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
2784 Complain about several constructs which gcc-2 accepts, but which are
2787 - put storage class first (e.g. "static const" instead of "const static").
2788 - "%lld" instead of %qd" in printf-type functions.
2789 - "%1$d" is non-standard in printf-type functions.
2790 - "\%" is an undefined character escape sequence.
2791 - text after #endif is not allowed.
2792 - invalid inner-style forward declaration.
2793 - >? and <? operators, and their >?= and <?= cousins.
2797 gcc-2 compliance.
2800 filename: The name of the current file.
2806 filename, line number, error level, and message
2812 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
2813 error(filename, linenum, 'runtime/printf_format', 3,
2817 error(filename, linenum, 'runtime/printf_format', 2,
2824 error(filename, linenum, 'build/printf_format', 3,
2835 error(filename, linenum, 'build/storage_class', 5,
2836 'Storage-class specifier (static, extern, typedef, etc) should be '
2839 if Match(r'\s*#\s*endif\s*[^/\s]+', line):
2840 error(filename, linenum, 'build/endif_comment', 5,
2841 'Uncommented text after #endif is non-standard. Use a comment.')
2843 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
2844 error(filename, linenum, 'build/forward_decl', 5,
2845 'Inner-style forward declarations are invalid. Remove this line.')
2847 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
2849 error(filename, linenum, 'build/deprecated', 3,
2850 '>? and <? (max and min) operators are non-standard and deprecated.')
2860 error(filename, linenum, 'runtime/member_string_references', 2,
2873 base_classname = classinfo.name.split('::')[-1]
2875 # Look for single-argument constructors that aren't marked explicit.
2877 explicit_constructor_match = Match(
2914 len(defaulted_args) >= len(constructor_args) - 1))
2920 Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
2928 error(filename, linenum, 'runtime/explicit', 5,
2932 error(filename, linenum, 'runtime/explicit', 5,
2933 'Single-parameter constructors should be marked explicit.')
2936 error(filename, linenum, 'runtime/explicit', 5,
2937 'Zero-parameter constructors should not be marked explicit.')
2940 def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): argument
2944 filename: The name of the current file.
2952 # expressions - which have their own, more liberal conventions - we
2960 match = Search(pattern, line)
2961 if match:
2962 fncall = match.group(1) # look inside the parens for function calls
2973 # " (something)(maybe-something)" or
2974 # " (something)(maybe-something," or
2986 error(filename, linenum, 'whitespace/parens', 4,
2989 error(filename, linenum, 'whitespace/parens', 2,
2999 error(filename, linenum, 'whitespace/parens', 0,
3002 error(filename, linenum, 'whitespace/parens', 4,
3010 error(filename, linenum, 'whitespace/parens', 2,
3013 error(filename, linenum, 'whitespace/parens', 2,
3032 def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, argument
3036 nesting_state.stack[-1].check_namespace_indentation and
3038 nesting_state.previous_stack_top == nesting_state.stack[-2])
3042 CheckItemIndentationInNamespace(filename, clean_lines.elided,
3046 def CheckForFunctionLengths(filename, clean_lines, linenum, argument
3051 https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
3063 filename: The name of the current file.
3075 match_result = Match(regexp, line)
3079 function_name = match_result.group(1).split()[-1]
3081 not Match(r'[A-Z_]+$', function_name)):
3095 if Match(r'TEST', function): # Handle TEST... macros
3104 # No body for the function (or evidence of a non-function) was found.
3105 error(filename, linenum, 'readability/fn_size', 5,
3107 elif Match(r'^\}\s*$', line): # function end
3108 function_state.Check(error, filename, linenum)
3110 elif not Match(r'^\s*$', line):
3111 function_state.Count() # Count non-blank/non-comment lines.
3117 def CheckComment(line, filename, linenum, next_line_start, error): argument
3122 filename: The name of the current file.
3124 next_line_start: The first non-whitespace column of the next line.
3128 if commentpos != -1:
3132 if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3134 line[commentpos-1] not in string.whitespace) or
3136 line[commentpos-2] not in string.whitespace))):
3137 error(filename, linenum, 'whitespace/comments', 2,
3142 match = _RE_PATTERN_TODO.match(comment)
3143 if match:
3145 leading_whitespace = match.group(1)
3147 error(filename, linenum, 'whitespace/todo', 2,
3150 username = match.group(2)
3152 error(filename, linenum, 'readability/todo', 2,
3156 middle_whitespace = match.group(3)
3157 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3159 error(filename, linenum, 'whitespace/todo', 2,
3165 if (Match(r'//[^ ]*\w', comment) and
3166 not Match(r'(///|//\!)(\s+|$)', comment)):
3167 error(filename, linenum, 'whitespace/comments', 4,
3171 def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): argument
3181 filename: The name of the current file.
3214 prev_line = elided[linenum - 1]
3220 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
3223 # non-empty line has the parameters of a function header that are indented
3229 if Match(r' {6}\w', prev_line): # Initializer list?
3232 search_position = linenum-2
3234 and Match(r' {6}\w', elided[search_position])):
3235 search_position -= 1
3245 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3247 or Match(r' {4}:', prev_line))
3250 error(filename, linenum, 'whitespace/blank_line', 2,
3253 # Ignore blank lines at the end of a block in a long if-else
3264 and Match(r'\s*}', next_line)
3265 and next_line.find('} else ') == -1):
3266 error(filename, linenum, 'whitespace/blank_line', 3,
3270 matched = Match(r'\s*(public|protected|private):', prev_line)
3272 error(filename, linenum, 'whitespace/blank_line', 3,
3279 next_line_start = len(next_line) - len(next_line.lstrip())
3280 CheckComment(line, filename, linenum, next_line_start, error)
3288 error(filename, linenum, 'whitespace/braces', 5,
3291 # In range-based for, we wanted spaces before and after the colon, but
3295 error(filename, linenum, 'whitespace/forcolon', 2,
3296 'Missing space around colon in range-based for loop')
3299 def CheckOperatorSpacing(filename, clean_lines, linenum, error): argument
3303 filename: The name of the current file.
3317 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3318 if match:
3319 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3323 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3324 # Otherwise not. Note we only check for non-spaces on *both* sides;
3325 # sometimes people put non-spaces on one side when aligning ='s among
3333 error(filename, linenum, 'whitespace/operators', 4,
3336 # It's ok not to have spaces around binary operators like + - * /, but if
3343 # check non-include lines for spacing around < and >.
3351 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
3352 if match:
3353 error(filename, linenum, 'whitespace/operators', 3,
3354 'Missing spaces around %s' % match.group(1))
3355 elif not Match(r'#.*include', line):
3360 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3361 if match:
3363 clean_lines, linenum, len(match.group(1)))
3364 if end_pos <= -1:
3365 error(filename, linenum, 'whitespace/operators', 3,
3371 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3372 if match:
3374 clean_lines, linenum, len(match.group(1)))
3375 if start_pos <= -1:
3376 error(filename, linenum, 'whitespace/operators', 3,
3379 # We allow no-spaces around << when used like this: 10<<20, but
3384 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
3385 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
3386 not (match.group(1) == 'operator' and match.group(2) == ';')):
3387 error(filename, linenum, 'whitespace/operators', 3,
3390 # We allow no-spaces around >> for almost anything. This is because
3402 match = Search(r'>>[a-zA-Z_]', line)
3403 if match:
3404 error(filename, linenum, 'whitespace/operators', 3,
3408 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3409 if match:
3410 error(filename, linenum, 'whitespace/operators', 4,
3411 'Extra space for operator %s' % match.group(1))
3414 def CheckParenthesisSpacing(filename, clean_lines, linenum, error): argument
3418 filename: The name of the current file.
3426 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3427 if match:
3428 error(filename, linenum, 'whitespace/parens', 5,
3429 'Missing space before ( in %s' % match.group(1))
3436 match = Search(r'\b(if|for|while|switch)\s*'
3439 if match:
3440 if len(match.group(2)) != len(match.group(4)):
3441 if not (match.group(3) == ';' and
3442 len(match.group(2)) == 1 + len(match.group(4)) or
3443 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
3444 error(filename, linenum, 'whitespace/parens', 5,
3445 'Mismatching spaces inside () in %s' % match.group(1))
3446 if len(match.group(2)) not in [0, 1]:
3447 error(filename, linenum, 'whitespace/parens', 5,
3449 match.group(1))
3452 def CheckCommaSpacing(filename, clean_lines, linenum, error): argument
3456 filename: The name of the current file.
3466 # This does not apply when the non-space character following the
3476 error(filename, linenum, 'whitespace/comma', 3,
3484 error(filename, linenum, 'whitespace/semicolon', 3,
3500 last_word = Match(r'^.*(\b\S+)$', expr)
3506 # Match native types and stdint types
3507 if _TYPES.match(token):
3510 # Try a bit harder to match templated types. Walk up the nesting
3515 block_index = len(nesting_state.stack) - 1
3530 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3535 first_line -= 1
3539 block_index -= 1
3546 block_index -= 1
3551 def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error): argument
3555 filename: The name of the current file.
3570 match = Match(r'^(.*[^ ({>]){', line)
3572 if match:
3601 leading_text = match.group(1)
3603 clean_lines, linenum, len(match.group(1)))
3605 if endpos > -1:
3608 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3613 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3615 error(filename, linenum, 'whitespace/braces', 5,
3620 error(filename, linenum, 'whitespace/braces', 5,
3627 error(filename, linenum, 'whitespace/semicolon', 5,
3630 error(filename, linenum, 'whitespace/semicolon', 5,
3635 error(filename, linenum, 'whitespace/semicolon', 5,
3658 def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): argument
3664 filename: The name of the current file.
3681 if (class_info.last_line - class_info.starting_linenum <= 24 or
3685 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3690 # - We are at the beginning of the class.
3691 # - We are forward-declaring an inner class that is semantically
3695 prev_line = clean_lines.lines[linenum - 1]
3700 # account for multi-line base-specifier lists, e.g.:
3708 if end_class_head < linenum - 1:
3709 error(filename, linenum, 'whitespace/blank_line', 3,
3714 """Return the most recent non-blank line and its line number.
3722 non-blank line before the current line, or the empty string if this is the
3723 first non-blank line. The second is the line number of that line, or -1
3724 if this is the first non-blank line.
3727 prevlinenum = linenum - 1
3732 prevlinenum -= 1
3733 return ('', -1)
3736 def CheckBraces(filename, clean_lines, linenum, error): argument
3740 filename: The name of the current file.
3748 if Match(r'\s*{\s*$', line):
3751 # to control the lifetime of stack-allocated variables. Braces are also
3753 # perfectly: we just don't complain if the last non-whitespace character on
3754 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
3760 not Match(r'\s*#', prevline) and
3761 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
3762 error(filename, linenum, 'whitespace/braces', 4,
3766 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
3768 if Match(r'\s*}\s*$', prevline):
3769 error(filename, linenum, 'whitespace/newline', 4,
3774 if Search(r'else if\s*\(', line): # could be multi-line if
3781 brace_on_right = endline[endpos:].find('{') != -1
3783 error(filename, linenum, 'readability/braces', 5,
3785 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3786 error(filename, linenum, 'readability/braces', 5,
3791 error(filename, linenum, 'whitespace/newline', 4,
3795 if Match(r'\s*do [^\s{]', line):
3796 error(filename, linenum, 'whitespace/newline', 4,
3799 # Check single-line if/else bodies. The style guide says 'curly braces are not
3800 # required for single-line statements'. We additionally allow multi-line,
3807 if if_else_match and not Match(r'\s*#', line):
3813 pos = if_match.end() - 1
3816 # line. If found, this isn't a single-statement conditional.
3817 if (not Match(r'\s*{', endline[endpos:])
3818 and not (Match(r'\s*$', endline[endpos:])
3819 and endlinenum < (len(clean_lines.elided) - 1)
3820 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
3827 # We allow a mix of whitespace and closing braces (e.g. for one-liner
3830 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
3834 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
3836 error(filename, linenum, 'readability/braces', 4,
3838 elif endlinenum < len(clean_lines.elided) - 1:
3843 # if that *doesn't* match the else, regardless of whether it's the
3845 if (if_match and Match(r'\s*else\b', next_line)
3847 error(filename, linenum, 'readability/braces', 4,
3851 error(filename, linenum, 'readability/braces', 4,
3855 def CheckTrailingSemicolon(filename, clean_lines, linenum, error): argument
3859 filename: The name of the current file.
3895 # Note that naively checking for the preceding "{" will also match
3896 # braces inside multi-dimensional arrays, but this is fine since
3911 match = Match(r'^(.*\)\s*)\{', line)
3912 if match:
3916 # - macro that defines a base class
3917 # - multi-line macro that defines a base class
3918 # - macro that defines the whole class-head
3922 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
3923 # - TYPED_TEST
3924 # - INTERFACE_DEF
3925 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
3935 # - Compound literals
3936 # - Lambdas
3937 # - alignas specifier with anonymous structs
3938 # - decltype
3939 closing_brace_pos = match.group(1).rfind(')')
3942 if opening_parenthesis[2] > -1:
3944 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
3945 func = Match(r'^(.*\])\s*$', line_prefix)
3955 match = None
3956 if (match and
3958 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
3959 # Multi-line lambda-expression
3960 match = None
3963 # Try matching cases 2-3.
3964 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
3965 if not match:
3966 # Try matching cases 4-6. These are always matched on separate lines.
3969 # current line and do a single match, otherwise we may output
3976 match = Match(r'^(\s*)\{', line)
3979 if match:
3981 clean_lines, linenum, len(match.group(1)))
3982 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
3993 ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
3995 ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,
3998 error(filename, endlinenum, 'readability/braces', 4,
4002 def CheckEmptyBlockBody(filename, clean_lines, linenum, error): argument
4006 filename: The name of the current file.
4014 # do-while-loops, since those lines should start with closing brace.
4019 matched = Match(r'\s*(for|while|if)\s*\(', line)
4028 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
4030 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
4033 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
4079 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4083 body = opening_line[opening_pos+1:closing_pos-1]
4102 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
4107 """Find a replaceable CHECK-like macro.
4112 (macro name, start position), or (None, -1) if no replaceable
4118 # Find opening parenthesis. Do a regular expression match here
4122 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
4126 return (None, -1)
4129 def CheckCheck(filename, clean_lines, linenum, error): argument
4133 filename: The name of the current file.
4154 if not Match(r'\s*;', last_line[end_pos:]):
4158 expression = lines[linenum][start_pos + 1:end_pos - 1]
4163 expression += last_line[0:end_pos - 1]
4172 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4191 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4192 # Non-relational operator
4202 # at a time, we do another regular expression match to consume several
4206 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4208 matched = Match(r'^(\s*\S)(.*)$', expression)
4220 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4231 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4232 if Match(match_constant, lhs) or Match(match_constant, rhs):
4241 error(filename, linenum, 'readability/check', 2,
4247 def CheckAltTokens(filename, clean_lines, linenum, error): argument
4251 filename: The name of the current file.
4259 if Match(r'^\s*#', line):
4262 # Last ditch effort to avoid multi-line comments. This will not help
4266 # multi-line comments in preprocessor macros.
4269 # multi-line comments.
4273 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4274 error(filename, linenum, 'readability/alt_tokens', 2,
4276 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4296 # https://mail.python.org/pipermail/python-list/2012-August/628809.html
4304 width -= 1
4306 # Android prebuilt python ends up CHECK-failing here due to how it's compiled.
4314 def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, argument
4319 do what we can. In particular we check for 2-space indents, line lengths,
4323 filename: The name of the current file.
4326 file_extension: The extension (without the dot) of the filename.
4337 prev = raw_lines[linenum - 1] if linenum > 0 else ''
4339 if line.find('\t') != -1:
4340 error(filename, linenum, 'whitespace/tab', 1,
4344 # hard to reconcile that with 2-space indents.
4348 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4349 # if(match(prev, "&& *$")) complain = 0;
4350 # if(match(prev, "\\|\\| *$")) complain = 0;
4351 # if(match(prev, "[\",=><] *$")) complain = 0;
4352 # if(match($0, " <<")) complain = 0;
4353 # if(match(prev, " +for \\(")) complain = 0;
4354 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
4362 # section labels, and also lines containing multi-line raw strings.
4365 # because the rules for how to indent those are non-trivial.
4368 not Match(scope_or_label_pattern, cleansed_line) and
4370 Match(r'^\s*""', line))):
4371 error(filename, linenum, 'whitespace/indent', 3,
4372 'Weird number of spaces at line-start. '
4373 'Are you using a 2-space indent?')
4375 if line and line[-1].isspace():
4376 error(filename, linenum, 'whitespace/end_of_line', 4,
4382 cppvar = GetHeaderGuardCPPVariable(filename)
4396 not Match(r'^\s*//.*http(s?)://\S*$', line) and
4397 not Match(r'^\s*//\s*[^\s]*$', line) and
4398 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
4401 error(filename, linenum, 'whitespace/line_length', 2,
4406 cleansed_line.find('for') == -1 and
4407 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4408 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4410 not ((cleansed_line.find('case ') != -1 or
4411 cleansed_line.find('default:') != -1) and
4412 cleansed_line.find('break;') != -1)):
4413 error(filename, linenum, 'whitespace/newline', 0,
4417 CheckBraces(filename, clean_lines, linenum, error)
4418 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
4419 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
4420 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
4421 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4422 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4423 CheckCommaSpacing(filename, clean_lines, linenum, error)
4424 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
4425 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
4426 CheckCheck(filename, clean_lines, linenum, error)
4427 CheckAltTokens(filename, clean_lines, linenum, error)
4430 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
4434 # Matches the first component of a filename delimited by -s and _s. That is:
4435 # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4436 # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4437 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4438 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4439 _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4442 def _DropCommonSuffixes(filename): argument
4443 """Drops common suffixes like _test.cc or -inl.h from filename.
4446 >>> _DropCommonSuffixes('foo/foo-inl.h')
4456 filename: The input filename.
4459 The filename with the common suffix removed.
4463 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4464 filename[-len(suffix) - 1] in ('-', '_')):
4465 return filename[:-len(suffix) - 1]
4466 return os.path.splitext(filename)[0]
4518 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4519 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4529 def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): argument
4537 filename: The name of the current file.
4543 fileinfo = FileInfo(filename)
4553 match = Match(r'#include\s*"([^/]+\.h)"', line)
4554 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
4555 error(filename, linenum, 'build/include', 4,
4561 match = _RE_PATTERN_INCLUDE.search(line)
4562 if match:
4563 include = match.group(2)
4564 is_system = (match.group(1) == '<')
4567 error(filename, linenum, 'build/include', 4,
4569 (include, filename, duplicate_line))
4572 error(filename, linenum, 'build/include', 4,
4574 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4575 include_state.include_list[-1].append((include, linenum))
4591 error(filename, linenum, 'build/include_order', 4,
4597 error(filename, linenum, 'build/include_alpha', 4,
4608 (, [, or {, and the matching close-punctuation symbol. This properly nested
4612 start_pattern must match string having an open punctuation symbol at the end.
4626 # Give opening punctuations to get the matching close-punctuations.
4631 match = re.search(start_pattern, text, re.M)
4632 if not match: # start_pattern not found in text.
4634 start_position = match.end(0)
4638 assert text[start_position - 1] in matching_punctuation, (
4641 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4644 if text[position] == punctuation_stack[-1]:
4653 # Opening punctuations left without matching close-punctuations.
4655 # punctuations match.
4656 return text[start_position:position - 1]
4659 # Patterns for matching call-by-reference parameters.
4668 _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4674 # A call-by-reference parameter ends with '& identifier'.
4678 # A call-by-const-reference parameter either ends with 'const& identifier'
4688 def CheckLanguage(filename, clean_lines, linenum, file_extension, argument
4696 filename: The name of the current file.
4699 file_extension: The extension (without the dot) of the filename.
4711 match = _RE_PATTERN_INCLUDE.search(line)
4712 if match:
4713 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4718 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4719 if match:
4720 include_state.ResetSection(match.group(1))
4723 fullname = os.path.abspath(filename).replace('\\', '/')
4726 CheckCasts(filename, clean_lines, linenum, error)
4727 CheckGlobalStatic(filename, clean_lines, linenum, error)
4728 CheckPrintf(filename, clean_lines, linenum, error)
4731 # TODO(unknown): check that 1-arg constructors are explicit.
4742 error(filename, linenum, 'runtime/int', 4,
4745 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4746 if match:
4747 error(filename, linenum, 'runtime/int', 4,
4748 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4751 # TODO(unknown): catch out-of-line unary operator&:
4757 error(filename, linenum, 'runtime/operator', 4,
4763 error(filename, linenum, 'readability/braces', 4,
4768 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
4775 match = Match(r'([\w.\->()]+)$', printf_args)
4776 if match and match.group(1) != '__VA_ARGS__':
4779 error(filename, linenum, 'runtime/printf', 4,
4781 % (function_name, match.group(1)))
4784 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4785 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4786 error(filename, linenum, 'runtime/memset', 4,
4788 % (match.group(1), match.group(2)))
4791 error(filename, linenum, 'build/namespaces', 5,
4792 'Do not use namespace using-directives. '
4793 'Use using-declarations instead.')
4795 # Detect variable-length arrays.
4796 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4797 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4798 match.group(3).find(']') == -1):
4802 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4816 if Match(r'\d+', tok): continue
4817 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4818 if Match(r'k[A-Z0-9]\w*', tok): continue
4819 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4820 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4830 error(filename, linenum, 'runtime/arrays', 1,
4831 'Do not use variable-length arrays. Use an appropriately named '
4832 "('k' followed by CamelCase) compile-time constant for the size.")
4839 and line[-1] != '\\'):
4840 error(filename, linenum, 'build/namespaces', 4,
4842 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
4846 def CheckGlobalStatic(filename, clean_lines, linenum, error): argument
4850 filename: The name of the current file.
4857 # Match two lines at a time to support multiline declarations
4866 # TODO(unknown): File bugs for clang-tidy to find these.
4867 match = Match(
4869 r'([a-zA-Z0-9_:]+)\b(.*)',
4873 # - String pointers (as opposed to values).
4879 # - Functions and template specializations.
4883 # - Operators. These are matched separately because operator names
4884 # cross non-word boundaries, and trying to match both operators
4888 if (match and
4891 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4893 error(filename, linenum, 'runtime/string', 4,
4896 (match.group(1), match.group(2) or '', match.group(3)))
4898 error(filename, linenum, 'runtime/string', 4,
4901 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4902 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
4903 error(filename, linenum, 'runtime/init', 4,
4907 def CheckPrintf(filename, clean_lines, linenum, error): argument
4911 filename: The name of the current file.
4919 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4920 if match and match.group(2) != '0':
4922 error(filename, linenum, 'runtime/printf', 3,
4924 'to snprintf.' % (match.group(1), match.group(2)))
4928 error(filename, linenum, 'runtime/printf', 5,
4930 match = Search(r'\b(strcpy|strcat)\s*\(', line)
4931 if match:
4932 error(filename, linenum, 'runtime/printf', 4,
4933 'Almost always, snprintf is better than %s' % match.group(1))
4944 virt-specifier.
4947 for i in xrange(linenum, max(-1, linenum - 10), -1):
4948 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4949 if match:
4952 clean_lines, i, len(match.group(1)))
4959 """Check if current line contains an out-of-line method definition.
4965 True if current line contains an out-of-line method definition.
4968 for i in xrange(linenum, max(-1, linenum - 10), -1):
4969 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4970 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4984 for i in xrange(linenum, 1, -1):
4987 remove_function_body = Match(r'^(.*)\{\s*$', line)
4999 # brace-initialized member in constructor initializer list.
5003 # - A closing brace or semicolon, probably the end of the previous
5005 # - An opening brace, probably the start of current class or namespace.
5016 def CheckForNonConstReference(filename, clean_lines, linenum, argument
5018 """Check for non-const references.
5024 filename: The name of the current file.
5037 # a choice, so any non-const references should not be blamed on
5042 # Don't warn on out-of-line method definitions, as we would warn on the
5043 # in-line declaration, if it isn't marked with 'override'.
5057 # line to current line so that we can match const references
5065 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
5068 clean_lines.elided[linenum - 1])
5069 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5072 clean_lines.elided[linenum - 1])
5078 if endpos > -1:
5081 if startpos > -1 and startline < linenum:
5088 # Check for non-const references in function parameters. A single '&' may
5109 for i in xrange(linenum - 1, max(0, linenum - 10), -1):
5113 if Match(r'^\s*:\s+\S', previous_line):
5124 # We allow non-const references in a few standard places, like functions
5139 # multi-line parameter list. Try a bit harder to catch this case.
5142 Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
5147 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5148 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
5149 error(filename, linenum, 'runtime/references', 2,
5150 'Is this a non-const reference? '
5155 def CheckCasts(filename, clean_lines, linenum, error): argument
5159 filename: The name of the current file.
5170 match = Search(
5175 if match and not expecting_function:
5176 matched_type = match.group(2)
5179 # - New operators
5180 # - Template arguments with function types
5182 # For template arguments, we match on types immediately following
5185 # template argument. False negative with less-than comparison is
5190 matched_new_or_template = match.group(1)
5194 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5198 # - Function pointers
5199 # - Casts to pointer types
5200 # - Placement new
5201 # - Alias declarations
5202 matched_funcptr = match.group(3)
5205 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5208 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5210 error(filename, linenum, 'readability/casting', 4,
5216 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
5223 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5228 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5232 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5235 # Some non-identifier character is required before the '&' for the
5242 match = Search(
5245 if match:
5250 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5251 if match:
5252 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5257 if y2 < clean_lines.NumLines() - 1:
5259 if Match(r'\s*(?:->|\[)', extended_line):
5263 error(filename, linenum, 'readability/casting', 4,
5268 error(filename, linenum, 'runtime/casting', 4,
5274 def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): argument
5275 """Checks for a C-style cast by looking for the pattern.
5278 filename: The name of the current file.
5283 pattern: The regular expression used to find C-style casts.
5291 match = Search(pattern, line)
5292 if not match:
5296 context = line[0:match.start(1) - 1]
5297 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5303 for i in xrange(linenum - 1, max(0, linenum - 5), -1):
5305 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
5308 # operator++(int) and operator--(int)
5309 if context.endswith(' operator++') or context.endswith(' operator--'):
5314 remainder = line[match.end(0):]
5315 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
5320 error(filename, linenum, 'readability/casting', 4,
5321 'Using C-style cast. Use %s<%s>(...) instead' %
5322 (cast_type, match.group(1)))
5339 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5341 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5342 clean_lines.elided[linenum - 1]) or
5343 Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5344 clean_lines.elided[linenum - 2]) or
5346 clean_lines.elided[linenum - 1]))))
5402 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5423 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5452 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5455 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
5461 filename_h = filename_h[:-len('.h')]
5462 if filename_h.endswith('-inl'):
5463 filename_h = filename_h[:-len('-inl')]
5470 common_path = filename_cc[:-len(filename_h)]
5474 def UpdateIncludeState(filename, include_dict, io=codecs): argument
5478 filename: the name of the header to read.
5487 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5494 match = _RE_PATTERN_INCLUDE.search(clean_line)
5495 if match:
5496 include = match.group(2)
5501 def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, argument
5512 filename: The name of the current file.
5527 # String is special -- it is a non-templatized type in STL.
5530 # Don't warn about strings in non-STL namespaces:
5531 # (We check only the first match per line; good enough.)
5547 # Don't warn about IWYU in non-STL namespaces:
5548 # (We check only the first match per line; good enough.)
5563 abs_filename = FileInfo(filename).FullName()
5588 if filename.endswith('.cc') and not header_found:
5595 error(filename, required[required_header_unstripped][0],
5603 def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): argument
5610 filename: The name of the current file.
5616 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5617 if match:
5618 error(filename, linenum, 'build/explicit_make_pair',
5620 'For C++11-compatibility, omit template arguments from make_pair'
5624 def CheckRedundantVirtual(filename, clean_lines, linenum, error): argument
5625 """Check if line contains a redundant "virtual" function-specifier.
5628 filename: The name of the current file.
5635 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
5638 # Ignore "virtual" keywords that are near access-specifiers. These
5639 # are only used in class base-specifier and do not apply to member
5642 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5648 if Match(r'^.*[^:]:[^:].*$', line): return
5655 end_col = -1
5656 end_line = -1
5660 parameter_list = Match(r'^([^(]*)\(', line)
5662 # Match parentheses to find the end of the parameter list
5675 match = Search(r'\b(override|final)\b', line)
5676 if match:
5677 error(filename, linenum, 'readability/inheritance', 4,
5679 'already declared as "%s"' % match.group(1)))
5688 def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): argument
5689 """Check if line contains a redundant "override" or "final" virt-specifier.
5692 filename: The name of the current file.
5698 # the declarator ends and where the virt-specifier starts to avoid
5705 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5712 error(filename, linenum, 'readability/inheritance', 4,
5732 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5738 nesting_state.stack[-1].check_namespace_indentation and
5739 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5775 def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, argument
5778 if Match(r'^\s+', line):
5779 error(filename, linenum, 'runtime/indentation_namespace', 4,
5783 def ProcessLine(filename, file_extension, clean_lines, line, argument
5789 filename: Filename of the file that is being processed.
5799 filename, line number, error level, and message
5802 arguments: filename, clean_lines, line, error
5805 ParseNolintSuppressions(filename, raw_lines[line], line, error)
5806 nesting_state.Update(filename, clean_lines, line, error)
5807 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5810 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
5811 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
5812 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
5813 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
5815 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
5816 CheckForNonStandardConstructs(filename, clean_lines, line,
5818 CheckVlogArguments(filename, clean_lines, line, error)
5819 CheckPosixThreading(filename, clean_lines, line, error)
5820 CheckInvalidIncrement(filename, clean_lines, line, error)
5821 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
5822 CheckRedundantVirtual(filename, clean_lines, line, error)
5823 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
5825 check_fn(filename, clean_lines, line, error)
5827 def FlagCxx11Features(filename, clean_lines, linenum, error): argument
5831 filename: The name of the current file.
5838 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5842 error(filename, linenum, 'build/c++tr1', 5,
5857 error(filename, linenum, 'build/c++11', 5,
5862 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5873 error(filename, linenum, 'build/c++11', 5,
5874 ('std::%s is an unapproved C++11 class or function. Send c-style '
5879 def FlagCxx14Features(filename, clean_lines, linenum, error): argument
5883 filename: The name of the current file.
5890 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5894 error(filename, linenum, 'build/c++14', 5,
5898 def ProcessFileData(filename, file_extension, lines, error, argument
5903 filename: Filename of the file that is being processed.
5908 filename, line number, error level, and message
5911 arguments: filename, clean_lines, line, error
5922 CheckForCopyright(filename, lines, error)
5924 RemoveMultiLineComments(filename, lines, error)
5928 CheckForHeaderGuard(filename, clean_lines, error)
5931 ProcessLine(filename, file_extension, clean_lines, line,
5934 FlagCxx11Features(filename, clean_lines, line, error)
5935 nesting_state.CheckCompletedBlocks(filename, error)
5937 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
5941 CheckHeaderFileIncluded(filename, include_state, error)
5945 CheckForBadCharacters(filename, lines, error)
5947 CheckForNewlineAtEOF(filename, lines, error)
5949 def ProcessConfigOverrides(filename): argument
5953 filename: The name of the file being processed by the linter.
5956 False if the current |filename| should not be processed further.
5959 abs_filename = os.path.abspath(filename)
5995 if pattern.match(base_name):
5997 # Suppress "Ignoring file" warning when using --quiet.
6002 (filename, cfg_file, base_name, val))
6026 # Apply all the accumulated filters in reverse order (top-level directory
6034 def ProcessFile(filename, vlevel, extra_check_functions=[]): argument
6035 """Does google-lint on a single file.
6038 filename: The name of the file to parse.
6045 arguments: filename, clean_lines, line, error
6052 if not ProcessConfigOverrides(filename):
6059 # Support the UNIX convention of using "-" for stdin. Note that
6066 if filename == '-':
6072 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
6075 # The -1 accounts for the extra trailing blank line we get from split()
6076 for linenum in range(len(lines) - 1):
6085 "Skipping input '%s': Can't open for reading\n" % filename)
6089 # Note, if no dot is found, this will give the entire filename as the ext.
6090 file_extension = filename[filename.rfind('.') + 1:]
6094 if filename != '-' and file_extension not in _valid_extensions:
6096 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
6098 ProcessFileData(filename, file_extension, lines, Error,
6101 # If end-of-line sequences are a mix of LF and CR-LF, issue
6104 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6109 # end-of-line sequence should be, since that will return the
6110 # server-side end-of-line sequence.
6116 Error(filename, linenum, 'whitespace/newline', 1,
6119 # Suppress printing anything if --quiet was passed unless the error
6122 sys.stdout.write('Done processing %s\n' % filename)
6140 """Prints a list of all the error-categories used by error messages.
6142 These are the categories used to filter messages via --filter.
6151 This may set the output format and verbosity level as side-effects.
6178 if opt == '--help':
6180 elif opt == '--output':
6184 elif opt == '--quiet':
6186 elif opt == '--verbose':
6188 elif opt == '--filter':
6192 elif opt == '--counting':
6196 elif opt == '--root':
6199 elif opt == '--linelength':
6205 elif opt == '--extensions':
6211 elif opt == '--headers':
6230 # if we try to print something containing non-ASCII characters.
6237 for filename in filenames:
6238 ProcessFile(filename, _cpplint_state.verbose_level)
6239 # If --quiet is passed, suppress printing error count unless there are errors.