• 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 // <empty> 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
4303 width -= 1
4311 def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, argument
4316 do what we can. In particular we check for 2-space indents, line lengths,
4320 filename: The name of the current file.
4323 file_extension: The extension (without the dot) of the filename.
4334 prev = raw_lines[linenum - 1] if linenum > 0 else ''
4336 if line.find('\t') != -1:
4337 error(filename, linenum, 'whitespace/tab', 1,
4341 # hard to reconcile that with 2-space indents.
4345 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4346 # if(match(prev, "&& *$")) complain = 0;
4347 # if(match(prev, "\\|\\| *$")) complain = 0;
4348 # if(match(prev, "[\",=><] *$")) complain = 0;
4349 # if(match($0, " <<")) complain = 0;
4350 # if(match(prev, " +for \\(")) complain = 0;
4351 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
4359 # section labels, and also lines containing multi-line raw strings.
4362 # because the rules for how to indent those are non-trivial.
4365 not Match(scope_or_label_pattern, cleansed_line) and
4367 Match(r'^\s*""', line))):
4368 error(filename, linenum, 'whitespace/indent', 3,
4369 'Weird number of spaces at line-start. '
4370 'Are you using a 2-space indent?')
4372 if line and line[-1].isspace():
4373 error(filename, linenum, 'whitespace/end_of_line', 4,
4379 cppvar = GetHeaderGuardCPPVariable(filename)
4393 not Match(r'^\s*//.*http(s?)://\S*$', line) and
4394 not Match(r'^\s*//\s*[^\s]*$', line) and
4395 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
4398 error(filename, linenum, 'whitespace/line_length', 2,
4403 cleansed_line.find('for') == -1 and
4404 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4405 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4407 not ((cleansed_line.find('case ') != -1 or
4408 cleansed_line.find('default:') != -1) and
4409 cleansed_line.find('break;') != -1)):
4410 error(filename, linenum, 'whitespace/newline', 0,
4414 CheckBraces(filename, clean_lines, linenum, error)
4415 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
4416 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
4417 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
4418 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4419 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4420 CheckCommaSpacing(filename, clean_lines, linenum, error)
4421 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
4422 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
4423 CheckCheck(filename, clean_lines, linenum, error)
4424 CheckAltTokens(filename, clean_lines, linenum, error)
4427 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
4431 # Matches the first component of a filename delimited by -s and _s. That is:
4432 # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4433 # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4434 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4435 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4436 _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4439 def _DropCommonSuffixes(filename): argument
4440 """Drops common suffixes like _test.cc or -inl.h from filename.
4443 >>> _DropCommonSuffixes('foo/foo-inl.h')
4453 filename: The input filename.
4456 The filename with the common suffix removed.
4460 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4461 filename[-len(suffix) - 1] in ('-', '_')):
4462 return filename[:-len(suffix) - 1]
4463 return os.path.splitext(filename)[0]
4515 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4516 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4526 def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): argument
4534 filename: The name of the current file.
4540 fileinfo = FileInfo(filename)
4550 match = Match(r'#include\s*"([^/]+\.h)"', line)
4551 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
4552 error(filename, linenum, 'build/include', 4,
4558 match = _RE_PATTERN_INCLUDE.search(line)
4559 if match:
4560 include = match.group(2)
4561 is_system = (match.group(1) == '<')
4564 error(filename, linenum, 'build/include', 4,
4566 (include, filename, duplicate_line))
4569 error(filename, linenum, 'build/include', 4,
4571 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4572 include_state.include_list[-1].append((include, linenum))
4588 error(filename, linenum, 'build/include_order', 4,
4594 error(filename, linenum, 'build/include_alpha', 4,
4605 (, [, or {, and the matching close-punctuation symbol. This properly nested
4609 start_pattern must match string having an open punctuation symbol at the end.
4623 # Give opening punctuations to get the matching close-punctuations.
4628 match = re.search(start_pattern, text, re.M)
4629 if not match: # start_pattern not found in text.
4631 start_position = match.end(0)
4635 assert text[start_position - 1] in matching_punctuation, (
4638 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4641 if text[position] == punctuation_stack[-1]:
4650 # Opening punctuations left without matching close-punctuations.
4652 # punctuations match.
4653 return text[start_position:position - 1]
4656 # Patterns for matching call-by-reference parameters.
4665 _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4671 # A call-by-reference parameter ends with '& identifier'.
4675 # A call-by-const-reference parameter either ends with 'const& identifier'
4685 def CheckLanguage(filename, clean_lines, linenum, file_extension, argument
4693 filename: The name of the current file.
4696 file_extension: The extension (without the dot) of the filename.
4708 match = _RE_PATTERN_INCLUDE.search(line)
4709 if match:
4710 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4715 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4716 if match:
4717 include_state.ResetSection(match.group(1))
4720 fullname = os.path.abspath(filename).replace('\\', '/')
4723 CheckCasts(filename, clean_lines, linenum, error)
4724 CheckGlobalStatic(filename, clean_lines, linenum, error)
4725 CheckPrintf(filename, clean_lines, linenum, error)
4728 # TODO(unknown): check that 1-arg constructors are explicit.
4739 error(filename, linenum, 'runtime/int', 4,
4742 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4743 if match:
4744 error(filename, linenum, 'runtime/int', 4,
4745 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4748 # TODO(unknown): catch out-of-line unary operator&:
4754 error(filename, linenum, 'runtime/operator', 4,
4760 error(filename, linenum, 'readability/braces', 4,
4765 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
4772 match = Match(r'([\w.\->()]+)$', printf_args)
4773 if match and match.group(1) != '__VA_ARGS__':
4776 error(filename, linenum, 'runtime/printf', 4,
4778 % (function_name, match.group(1)))
4781 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4782 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4783 error(filename, linenum, 'runtime/memset', 4,
4785 % (match.group(1), match.group(2)))
4788 error(filename, linenum, 'build/namespaces', 5,
4789 'Do not use namespace using-directives. '
4790 'Use using-declarations instead.')
4792 # Detect variable-length arrays.
4793 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4794 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4795 match.group(3).find(']') == -1):
4799 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4813 if Match(r'\d+', tok): continue
4814 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4815 if Match(r'k[A-Z0-9]\w*', tok): continue
4816 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4817 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4827 error(filename, linenum, 'runtime/arrays', 1,
4828 'Do not use variable-length arrays. Use an appropriately named '
4829 "('k' followed by CamelCase) compile-time constant for the size.")
4836 and line[-1] != '\\'):
4837 error(filename, linenum, 'build/namespaces', 4,
4839 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
4843 def CheckGlobalStatic(filename, clean_lines, linenum, error): argument
4847 filename: The name of the current file.
4854 # Match two lines at a time to support multiline declarations
4863 # TODO(unknown): File bugs for clang-tidy to find these.
4864 match = Match(
4866 r'([a-zA-Z0-9_:]+)\b(.*)',
4870 # - String pointers (as opposed to values).
4876 # - Functions and template specializations.
4880 # - Operators. These are matched separately because operator names
4881 # cross non-word boundaries, and trying to match both operators
4885 if (match and
4888 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4890 error(filename, linenum, 'runtime/string', 4,
4893 (match.group(1), match.group(2) or '', match.group(3)))
4895 error(filename, linenum, 'runtime/string', 4,
4898 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4899 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
4900 error(filename, linenum, 'runtime/init', 4,
4904 def CheckPrintf(filename, clean_lines, linenum, error): argument
4908 filename: The name of the current file.
4916 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4917 if match and match.group(2) != '0':
4919 error(filename, linenum, 'runtime/printf', 3,
4921 'to snprintf.' % (match.group(1), match.group(2)))
4925 error(filename, linenum, 'runtime/printf', 5,
4927 match = Search(r'\b(strcpy|strcat)\s*\(', line)
4928 if match:
4929 error(filename, linenum, 'runtime/printf', 4,
4930 'Almost always, snprintf is better than %s' % match.group(1))
4941 virt-specifier.
4944 for i in xrange(linenum, max(-1, linenum - 10), -1):
4945 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4946 if match:
4949 clean_lines, i, len(match.group(1)))
4956 """Check if current line contains an out-of-line method definition.
4962 True if current line contains an out-of-line method definition.
4965 for i in xrange(linenum, max(-1, linenum - 10), -1):
4966 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4967 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4981 for i in xrange(linenum, 1, -1):
4984 remove_function_body = Match(r'^(.*)\{\s*$', line)
4996 # brace-initialized member in constructor initializer list.
5000 # - A closing brace or semicolon, probably the end of the previous
5002 # - An opening brace, probably the start of current class or namespace.
5013 def CheckForNonConstReference(filename, clean_lines, linenum, argument
5015 """Check for non-const references.
5021 filename: The name of the current file.
5034 # a choice, so any non-const references should not be blamed on
5039 # Don't warn on out-of-line method definitions, as we would warn on the
5040 # in-line declaration, if it isn't marked with 'override'.
5054 # line to current line so that we can match const references
5062 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
5065 clean_lines.elided[linenum - 1])
5066 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5069 clean_lines.elided[linenum - 1])
5075 if endpos > -1:
5078 if startpos > -1 and startline < linenum:
5085 # Check for non-const references in function parameters. A single '&' may
5106 for i in xrange(linenum - 1, max(0, linenum - 10), -1):
5110 if Match(r'^\s*:\s+\S', previous_line):
5121 # We allow non-const references in a few standard places, like functions
5136 # multi-line parameter list. Try a bit harder to catch this case.
5139 Search(allowed_functions, clean_lines.elided[linenum - i - 1])):
5144 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5145 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
5146 error(filename, linenum, 'runtime/references', 2,
5147 'Is this a non-const reference? '
5152 def CheckCasts(filename, clean_lines, linenum, error): argument
5156 filename: The name of the current file.
5167 match = Search(
5172 if match and not expecting_function:
5173 matched_type = match.group(2)
5176 # - New operators
5177 # - Template arguments with function types
5179 # For template arguments, we match on types immediately following
5182 # template argument. False negative with less-than comparison is
5187 matched_new_or_template = match.group(1)
5191 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5195 # - Function pointers
5196 # - Casts to pointer types
5197 # - Placement new
5198 # - Alias declarations
5199 matched_funcptr = match.group(3)
5202 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5205 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5207 error(filename, linenum, 'readability/casting', 4,
5213 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
5220 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5225 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5229 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5232 # Some non-identifier character is required before the '&' for the
5239 match = Search(
5242 if match:
5247 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5248 if match:
5249 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5254 if y2 < clean_lines.NumLines() - 1:
5256 if Match(r'\s*(?:->|\[)', extended_line):
5260 error(filename, linenum, 'readability/casting', 4,
5265 error(filename, linenum, 'runtime/casting', 4,
5271 def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): argument
5272 """Checks for a C-style cast by looking for the pattern.
5275 filename: The name of the current file.
5280 pattern: The regular expression used to find C-style casts.
5288 match = Search(pattern, line)
5289 if not match:
5293 context = line[0:match.start(1) - 1]
5294 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5300 for i in xrange(linenum - 1, max(0, linenum - 5), -1):
5302 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
5305 # operator++(int) and operator--(int)
5306 if context.endswith(' operator++') or context.endswith(' operator--'):
5311 remainder = line[match.end(0):]
5312 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
5317 error(filename, linenum, 'readability/casting', 4,
5318 'Using C-style cast. Use %s<%s>(...) instead' %
5319 (cast_type, match.group(1)))
5336 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5338 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5339 clean_lines.elided[linenum - 1]) or
5340 Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5341 clean_lines.elided[linenum - 2]) or
5343 clean_lines.elided[linenum - 1]))))
5399 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5420 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5449 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5452 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
5458 filename_h = filename_h[:-len('.h')]
5459 if filename_h.endswith('-inl'):
5460 filename_h = filename_h[:-len('-inl')]
5467 common_path = filename_cc[:-len(filename_h)]
5471 def UpdateIncludeState(filename, include_dict, io=codecs): argument
5475 filename: the name of the header to read.
5484 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5491 match = _RE_PATTERN_INCLUDE.search(clean_line)
5492 if match:
5493 include = match.group(2)
5498 def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, argument
5509 filename: The name of the current file.
5524 # String is special -- it is a non-templatized type in STL.
5527 # Don't warn about strings in non-STL namespaces:
5528 # (We check only the first match per line; good enough.)
5544 # Don't warn about IWYU in non-STL namespaces:
5545 # (We check only the first match per line; good enough.)
5560 abs_filename = FileInfo(filename).FullName()
5585 if filename.endswith('.cc') and not header_found:
5592 error(filename, required[required_header_unstripped][0],
5600 def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): argument
5607 filename: The name of the current file.
5613 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5614 if match:
5615 error(filename, linenum, 'build/explicit_make_pair',
5617 'For C++11-compatibility, omit template arguments from make_pair'
5621 def CheckRedundantVirtual(filename, clean_lines, linenum, error): argument
5622 """Check if line contains a redundant "virtual" function-specifier.
5625 filename: The name of the current file.
5632 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
5635 # Ignore "virtual" keywords that are near access-specifiers. These
5636 # are only used in class base-specifier and do not apply to member
5639 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5645 if Match(r'^.*[^:]:[^:].*$', line): return
5652 end_col = -1
5653 end_line = -1
5657 parameter_list = Match(r'^([^(]*)\(', line)
5659 # Match parentheses to find the end of the parameter list
5672 match = Search(r'\b(override|final)\b', line)
5673 if match:
5674 error(filename, linenum, 'readability/inheritance', 4,
5676 'already declared as "%s"' % match.group(1)))
5685 def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): argument
5686 """Check if line contains a redundant "override" or "final" virt-specifier.
5689 filename: The name of the current file.
5695 # the declarator ends and where the virt-specifier starts to avoid
5702 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5709 error(filename, linenum, 'readability/inheritance', 4,
5729 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5735 nesting_state.stack[-1].check_namespace_indentation and
5736 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5772 def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, argument
5775 if Match(r'^\s+', line):
5776 error(filename, linenum, 'runtime/indentation_namespace', 4,
5780 def ProcessLine(filename, file_extension, clean_lines, line, argument
5786 filename: Filename of the file that is being processed.
5796 filename, line number, error level, and message
5799 arguments: filename, clean_lines, line, error
5802 ParseNolintSuppressions(filename, raw_lines[line], line, error)
5803 nesting_state.Update(filename, clean_lines, line, error)
5804 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5807 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
5808 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
5809 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
5810 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
5812 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
5813 CheckForNonStandardConstructs(filename, clean_lines, line,
5815 CheckVlogArguments(filename, clean_lines, line, error)
5816 CheckPosixThreading(filename, clean_lines, line, error)
5817 CheckInvalidIncrement(filename, clean_lines, line, error)
5818 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
5819 CheckRedundantVirtual(filename, clean_lines, line, error)
5820 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
5822 check_fn(filename, clean_lines, line, error)
5824 def FlagCxx11Features(filename, clean_lines, linenum, error): argument
5828 filename: The name of the current file.
5835 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5839 error(filename, linenum, 'build/c++tr1', 5,
5854 error(filename, linenum, 'build/c++11', 5,
5859 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5870 error(filename, linenum, 'build/c++11', 5,
5871 ('std::%s is an unapproved C++11 class or function. Send c-style '
5876 def FlagCxx14Features(filename, clean_lines, linenum, error): argument
5880 filename: The name of the current file.
5887 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5891 error(filename, linenum, 'build/c++14', 5,
5895 def ProcessFileData(filename, file_extension, lines, error, argument
5900 filename: Filename of the file that is being processed.
5905 filename, line number, error level, and message
5908 arguments: filename, clean_lines, line, error
5919 CheckForCopyright(filename, lines, error)
5921 RemoveMultiLineComments(filename, lines, error)
5925 CheckForHeaderGuard(filename, clean_lines, error)
5928 ProcessLine(filename, file_extension, clean_lines, line,
5931 FlagCxx11Features(filename, clean_lines, line, error)
5932 nesting_state.CheckCompletedBlocks(filename, error)
5934 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
5938 CheckHeaderFileIncluded(filename, include_state, error)
5942 CheckForBadCharacters(filename, lines, error)
5944 CheckForNewlineAtEOF(filename, lines, error)
5946 def ProcessConfigOverrides(filename): argument
5950 filename: The name of the file being processed by the linter.
5953 False if the current |filename| should not be processed further.
5956 abs_filename = os.path.abspath(filename)
5992 if pattern.match(base_name):
5994 # Suppress "Ignoring file" warning when using --quiet.
5999 (filename, cfg_file, base_name, val))
6023 # Apply all the accumulated filters in reverse order (top-level directory
6031 def ProcessFile(filename, vlevel, extra_check_functions=[]): argument
6032 """Does google-lint on a single file.
6035 filename: The name of the file to parse.
6042 arguments: filename, clean_lines, line, error
6049 if not ProcessConfigOverrides(filename):
6056 # Support the UNIX convention of using "-" for stdin. Note that
6063 if filename == '-':
6069 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
6072 # The -1 accounts for the extra trailing blank line we get from split()
6073 for linenum in range(len(lines) - 1):
6082 "Skipping input '%s': Can't open for reading\n" % filename)
6086 # Note, if no dot is found, this will give the entire filename as the ext.
6087 file_extension = filename[filename.rfind('.') + 1:]
6091 if filename != '-' and file_extension not in _valid_extensions:
6093 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
6095 ProcessFileData(filename, file_extension, lines, Error,
6098 # If end-of-line sequences are a mix of LF and CR-LF, issue
6101 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6106 # end-of-line sequence should be, since that will return the
6107 # server-side end-of-line sequence.
6113 Error(filename, linenum, 'whitespace/newline', 1,
6116 # Suppress printing anything if --quiet was passed unless the error
6119 sys.stdout.write('Done processing %s\n' % filename)
6137 """Prints a list of all the error-categories used by error messages.
6139 These are the categories used to filter messages via --filter.
6148 This may set the output format and verbosity level as side-effects.
6175 if opt == '--help':
6177 elif opt == '--output':
6181 elif opt == '--quiet':
6183 elif opt == '--verbose':
6185 elif opt == '--filter':
6189 elif opt == '--counting':
6193 elif opt == '--root':
6196 elif opt == '--linelength':
6202 elif opt == '--extensions':
6208 elif opt == '--headers':
6227 # if we try to print something containing non-ASCII characters.
6234 for filename in filenames:
6235 ProcessFile(filename, _cpplint_state.verbose_level)
6236 # If --quiet is passed, suppress printing error count unless there are errors.