• Home
  • Raw
  • Download

Lines Matching +full:check +full:- +full:whitespace

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
45 # pylint: disable=consider-using-f-string
47 # pylint: disable=invalid-name
72 # -- pylint: disable=redefined-builtin
77 Syntax: cpplint.py [--verbose=#] [--output=emacs|eclipse|vs7|junit|sed|gsed]
78 [--filter=-x,+y,...]
79 [--counting=total|toplevel|detailed] [--root=subdir]
80 [--repository=path]
81 [--linelength=digits] [--headers=x,y,...]
82 [--recursive]
83 [--exclude=path]
84 [--extensions=hpp,cpp,...]
85 [--includeorder=default|standardcfirst]
86 [--quiet]
87 [--version]
96 Every problem is given a confidence score from 1-5, with 5 meaning we are
100 To suppress false-positive errors of a certain category, add a
107 Change the extensions with the --extensions flag.
123 Specify a number 0-5 to restrict errors to certain verbosity levels.
130 filter=-x,+y,...
131 Specify a comma-separated list of category-filters to apply: only
134 "[whitespace/indent]".) Filters are evaluated left to right.
135 "-FOO" means "do not print categories that start with FOO".
138 Examples: --filter=-whitespace,+whitespace/braces
139 --filter=-whitespace,-runtime/printf,+runtime/printf_format
140 --filter=-,+build/include_what_you_use
143 --filter=
148 the top-level categories like 'build' and 'whitespace' will
159 with SVN). In addition, users of non-mainstream version control systems
165 with no --repository flag, the header guard CPP variable will be:
170 If Alice uses the --repository=trunk flag and Bob omits the flag or
171 uses --repository=. then the header guard CPP variable will be:
180 .git, .hg, or .svn but can also be controlled with the --repository flag.
189 --root=chrome => BROWSER_UI_BROWSER_H_
190 --root=chrome/browser => UI_BROWSER_H_
191 --root=.. => SRC_CHROME_BROWSER_UI_BROWSER_H_
198 --linelength=120
213 --exclude=one.cc
214 --exclude=src/*.cc
215 --exclude=src/*.cc --exclude=test/*.cc
218 The allowed file extensions that cpplint will check
221 --extensions=%s
225 bracket includes with file extension are c-system-headers (default),
228 standardcfirst means to instead use an allow-list of known c headers and
230 included are those of the C-standard lib and closely related ones.
234 automatically added to --extensions list.
238 --headers=%s
239 --headers=hpp,hxx
240 --headers=hpp
242 cpplint.py supports per-directory configurations specified in CPPLINT.cfg
247 filter=+filter1,-filter2,...
255 is usually placed in the top-level project directory.
257 The "filter" option is similar in function to --filter flag. It specifies
259 through --filter command-line flag.
267 The "root" option is similar in function to the --root flag (see example
270 The "headers" option is similar in function to the --headers flag
274 sub-directories, unless overridden by a nested configuration file.
277 filter=-build/include_order,+build/include_alpha
283 file is located) and all sub-directories.
287 # We want an explicit list so we can list them all in cpplint --filter=.
314 'readability/check',
342 'whitespace/blank_line',
343 'whitespace/braces',
344 'whitespace/comma',
345 'whitespace/comments',
346 'whitespace/empty_conditional_body',
347 'whitespace/empty_if_body',
348 'whitespace/empty_loop_body',
349 'whitespace/end_of_line',
350 'whitespace/ending_newline',
351 'whitespace/forcolon',
352 'whitespace/indent',
353 'whitespace/line_length',
354 'whitespace/newline',
355 'whitespace/operators',
356 'whitespace/parens',
357 'whitespace/semicolon',
358 'whitespace/tab',
359 'whitespace/todo',
362 # keywords to use with --outputs which generate stdout for machine processing
369 # These error categories are no longer enforced by cpplint, but for backwards-
376 # The default state of the category filter. This is overridden by the --filter=
378 # off by default (i.e., categories that must be enabled by the --filter= flags).
379 # All entries here should start with a '-' or '+', as in the --filter= flag.
380 _DEFAULT_FILTERS = ['-build/include_alpha']
389 'whitespace/tab',
392 # We used to check for high-bit characters, but after much discussion we
393 # decided those were OK, as long as they were in UTF-8 and didn't represent
394 # hard-coded international strings, which belong in a separate i18n file.
658 'gnu-versions.h',
681 'stdc-predef.h',
705 "asm-generic",
741 # - Anything not following google file name conventions (containing an
743 # - Lua headers.
745 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
751 # Pattern that matches only complete whitespace, possibly across multiple lines.
757 'DCHECK', 'CHECK',
762 # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
769 _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
801 # False positives include C-style multi-line comments and multi-line strings
845 'Line ends in whitespace. Consider deleting these extra spaces.': r's/\s*$//',
857 # This is set by --root flag.
863 # This is set by the --repository flag.
866 # Files to exclude from linting. This is set by the --exclude flag.
869 # Whether to supress all PrintInfo messages, UNRELATED to --quiet flag
873 # This is set by --linelength flag.
882 # -- pylint: disable=redefined-builtin
888 # -- pylint: disable=redefined-builtin
892 # -- pylint: disable=no-member
908 # This is set by --headers flag.
942 # This is set by --extensions flag
953 PrintUsage('Extensions should be a comma-separated list of values;'
961 """Updates the global list of line error-suppressions.
984 category = category[1:-1]
1119 """Check if a header has already been included.
1122 header: header to check.
1124 Line number of previous occurrence, or -1 if the header has not
1131 return -1
1149 self.include_list[-1] = []
1157 - replaces "-" with "_" so they both cmp the same.
1158 - removes '-inl' since we don't require them to be after the main header.
1159 - lowercase everything, just in case.
1167 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
1170 """Check if a header is in alphabetical order with the previous header.
1174 linenum: The number of the line to check.
1186 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
1191 """Returns a non-empty error message if the next header is out of order.
1193 This function also updates the internal state to be ready to check
1251 """Maintains module-wide state.."""
1262 self.quiet = False # Suppress non-error messagess?
1265 # "emacs" - format that emacs can parse (default)
1266 # "eclipse" - format that eclipse can parse
1267 # "vs7" - format that Microsoft Visual Studio 7 can parse
1268 # "junit" - format that Jenkins, Bamboo, etc can parse
1269 # "sed" - returns a gnu sed command to fix the problem
1270 # "gsed" - like sed, but names the command gsed, e.g. for macOS homebrew users
1299 """Sets the error-message filters.
1305 filters: A string of comma-separated filters (eg "+whitespace/indent").
1306 Each filter should start with + or -; else we die.
1309 ValueError: The comma-separated filters did not all start with '+' or '-'.
1310 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
1317 """ Adds more filters to the existing list of error-message filters. """
1323 if not (filt.startswith('+') or filt.startswith('-')):
1324 raise ValueError('Every filter in --filters must start with + or -'
1359 # _quiet does not represent --quiet flag.
1414 xml_decl = '<?xml version="1.0" encoding="UTF-8" ?>\n'
1415 return xml_decl + xml.etree.ElementTree.tostring(testsuite, 'utf-8').decode('utf-8')
1460 """Sets the module's error-message filters.
1466 filters: A string of comma-separated filters (eg "whitespace/indent").
1467 Each filter should start with + or -; else we die.
1478 filters: A string of comma-separated filters (eg "whitespace/indent").
1479 Each filter should start with + or -; else we die.
1494 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
1517 def Check(self, error, filename, linenum): member in _FunctionState
1523 linenum: The number of the line to check.
1541 ' %s has %d non-comment lines'
1644 """File base name - text after the final slash, before the final period."""
1648 """File extension - text following the final period, includes that period."""
1674 if one_filter.startswith('-'):
1703 falls under: "whitespace", say, or "runtime". Categories
1704 may have a hierarchy separated by slashes: "whitespace/indent".
1705 confidence: A number from 1-5 representing a confidence score for
1723 sys.stdout.write(_cpplint_state.output_format + " -i '%s%s' %s # %s [%s] [%d]\n" % (
1735 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
1738 # Matches multi-line C style comments.
1744 # if this doesn't work we try on left side but only if there's a non-character
1756 This function does not consider single-line nor multi-line comments.
1767 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1775 multi-line string
1814 # Once we have matched a raw string, we check the prefix of the
1820 # we don't want to check comments that are inside raw strings.
1834 # Start of a multi-line raw string
1867 """Clears a range of lines for multi-line comments."""
1868 # Having // <empty> comments makes the lines non-empty, so we will not get
1875 """Removes multiline (c-style) comments from lines."""
1884 'Could not find end of multi-line comment')
1891 """Removes //-comments and single-line C-style /* */ comments.
1897 The line with single-line comments removed.
1900 if commentpos != -1 and not IsCppString(line[:commentpos]):
1923 # # pylint: disable=consider-using-enumerate
1978 # Found single quote, check nearby text to eliminate digit separators.
1985 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1986 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
2012 On finding an unclosed expression: (-1, None)
2013 Otherwise: (-1, new stack at end of this line)
2022 if i > 0 and line[i - 1] == '<':
2024 if stack and stack[-1] == '<':
2027 return (-1, None)
2039 while stack and stack[-1] == '<':
2042 return (-1, None)
2043 if ((stack[-1] == '(' and char == ')') or
2044 (stack[-1] == '[' and char == ']') or
2045 (stack[-1] == '{' and char == '}')):
2051 return (-1, None)
2055 # Ignore "->" and operator functions
2057 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
2063 if stack[-1] == '<':
2071 while stack and stack[-1] == '<':
2074 return (-1, None)
2077 return (-1, stack)
2093 linenum: The number of the line to check.
2098 (line, len(lines), -1) if we never find a close. Note we ignore
2105 return (line, clean_lines.NumLines(), -1)
2107 # Check first line
2109 if end_pos > -1:
2113 while stack and linenum < clean_lines.NumLines() - 1:
2117 if end_pos > -1:
2121 return (line, clean_lines.NumLines(), -1)
2137 On finding an unclosed expression: (-1, None)
2138 Otherwise: (-1, new stack at beginning of this line)
2149 # Ignore it if it's a "->" or ">=" or "operator>"
2151 (line[i - 1] == '-' or
2152 Match(r'\s>=\s', line[i - 1:]) or
2154 i -= 1
2159 if i > 0 and line[i - 1] == '<':
2161 i -= 1
2165 if stack and stack[-1] == '>':
2174 while stack and stack[-1] == '>':
2177 return (-1, None)
2178 if ((char == '(' and stack[-1] == ')') or
2179 (char == '[' and stack[-1] == ']') or
2180 (char == '{' and stack[-1] == '}')):
2186 return (-1, None)
2191 while stack and stack[-1] == '>':
2194 return (-1, None)
2196 i -= 1
2198 return (-1, stack)
2209 linenum: The number of the line to check.
2214 (line, 0, -1) if we never find the matching opening brace. Note
2220 return (line, 0, -1)
2222 # Check last line
2224 if start_pos > -1:
2229 linenum -= 1
2231 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
2232 if start_pos > -1:
2236 return (line, 0, -1)
2256 line: A string to check.
2319 # Process the file path with the --root flag if it was set.
2326 # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
2329 # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
2333 # --root=subdir , lstrips subdir from the header guard
2344 # --root=.. , will prepend the outer directory to the header guard
2362 # --root=FAKE_DIR is ignored
2366 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
2381 # Don't check for header guards if there are error suppression
2437 # Check for "//" comments on endif line.
2452 for i in xrange(1, len(raw_lines) - 1):
2475 # Do not check test files
2481 basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
2511 contained invalid UTF-8 (likely) or Unicode replacement characters (which
2513 numbering if the invalid UTF-8 occurred adjacent to a newline.
2525 'Line contains invalid UTF-8 (or Unicode replacement character).')
2542 # last-but-two element of lines() exists and is empty.
2543 if len(lines) < 3 or lines[-2]:
2544 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
2562 linenum: The number of the line to check.
2573 'Complex multi-line /*...*/-style comment found. '
2575 'Consider replacing these with //-style comments, '
2577 'or with more clearly structured multi-line comments.')
2579 if (line.count('"') - line.count('\\"')) % 2:
2581 'Multi-line string ("...") found. This lint script doesn\'t '
2586 # (non-threadsafe name, thread-safe alternative, validation pattern)
2590 # ->rand(); // some member function rand().
2598 _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
2617 """Checks for calls to thread-unsafe functions.
2620 multi-threading. Also, engineers are relying on their old experience;
2622 tests guide the engineers to use thread-safe functions (when using
2628 linenum: The number of the line to check.
2633 # Additional pattern matching check to confirm that this is the
2651 linenum: The number of the line to check.
2663 r'^\s*\*\w+(\+\+|--);')
2679 linenum: The number of the line to check.
2692 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2717 blocks, there isn't much to check, so we always pass.
2722 linenum: The number of the line to check.
2735 linenum: The number of the line to check.
2787 depth += line.count('{') - line.count('}')
2801 for i in xrange(linenum - 1, self.starting_linenum, -1):
2815 # Check that closing brace is aligned with beginning of the class.
2817 # This means we will not check single-line class definitions.
2824 error(filename, linenum, 'whitespace/indent', 3,
2837 """Check end of namespace comments."""
2840 # Check how many lines is enclosed in this namespace. Don't issue
2845 # TODO(unknown): We always want to check end of namespace comments
2847 # check if a short namespace contained nontrivial things (something
2849 # deciding what these nontrivial things are, so this check is
2851 if (linenum - self.starting_linenum < 10
2910 # - _ClassInfo: a class or struct.
2911 # - _NamespaceInfo: a namespace.
2912 # - _BlockInfo: some other type of block.
2919 # scope at the beginning of the line. This check is simplified by
2930 """Check if we have seen the opening brace for the innermost block.
2936 return (not self.stack) or self.stack[-1].seen_open_brace
2939 """Check if we are currently one level inside a namespace body.
2944 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2947 """Check if we are currently one level inside an 'extern "C"' block.
2952 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2955 """Check if we are currently one level inside a class or struct declaration.
2960 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2963 """Check if we are currently one level inside an inline ASM block.
2968 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2971 """Check if current position is inside template argument list.
2975 linenum: The number of the line to check.
3003 # Check if token is an unmatched '<'.
3014 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
3033 - Preprocessor condition evaluates to true from #if up to first
3036 - Preprocessor condition evaluates to false from #else/#elif up
3041 line: current line to check.
3050 if not self.pp_stack[-1].seen_else:
3054 self.pp_stack[-1].seen_else = True
3055 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
3058 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
3068 if self.pp_stack[-1].seen_else:
3071 self.stack = self.pp_stack[-1].stack_before_else
3085 linenum: The number of the line to check.
3096 self.previous_stack_top = self.stack[-1]
3106 inner_block = self.stack[-1]
3107 depth_change = line.count('(') - line.count(')')
3110 # Also check if we are starting or ending an inline assembly block.
3131 # declarations even if it weren't followed by a whitespace, this
3142 if line.find('{') != -1:
3153 r'(class|struct)\s+(?:[a-zA-Z0-9_]+\s+)*(\w+(?:::\w+)*))'
3156 (not self.stack or self.stack[-1].open_parentheses == 0)):
3176 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
3179 if self.stack and isinstance(self.stack[-1], _ClassInfo):
3180 classinfo = self.stack[-1]
3188 # Check that access keywords are indented +1 space. Skip this
3189 # check if the keywords are not preceded by whitespaces.
3200 error(filename, linenum, 'whitespace/indent', 3,
3217 self.stack[-1].seen_open_brace = True
3223 self.stack[-1].inline_asm = _BLOCK_ASM
3239 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
3249 for i in range(len(self.stack), 0, -1):
3250 classinfo = self.stack[i - 1]
3279 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
3281 Complain about several constructs which gcc-2 accepts, but which are
3284 - put storage class first (e.g. "static const" instead of "const static").
3285 - "%lld" instead of %qd" in printf-type functions.
3286 - "%1$d" is non-standard in printf-type functions.
3287 - "\%" is an undefined character escape sequence.
3288 - text after #endif is not allowed.
3289 - invalid inner-style forward declaration.
3290 - >? and <? operators, and their >?= and <?= cousins.
3292 Additionally, check for constructor/destructor style violations and reference
3294 gcc-2 compliance.
3299 linenum: The number of the line to check.
3309 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
3333 'Storage-class specifier (static, extern, typedef, etc) should be '
3338 'Uncommented text after #endif is non-standard. Use a comment.')
3342 'Inner-style forward declarations are invalid. Remove this line.')
3344 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
3347 '>? and <? (max and min) operators are non-standard and deprecated.')
3370 base_classname = classinfo.name.split('::')[-1]
3372 # Look for single-argument constructors that aren't marked explicit.
3412 len(defaulted_args) >= len(constructor_args) - 1) or
3435 'Single-parameter constructors should be marked explicit.')
3439 'Zero-parameter constructors should not be marked explicit.')
3448 linenum: The number of the line to check.
3454 # expressions - which have their own, more liberal conventions - we
3471 # function argument when the char before the whitespace is legal in
3475 # " (something)(maybe-something)" or
3476 # " (something)(maybe-something," or
3488 error(filename, linenum, 'whitespace/parens', 4,
3491 error(filename, linenum, 'whitespace/parens', 2,
3501 error(filename, linenum, 'whitespace/parens', 0,
3504 error(filename, linenum, 'whitespace/parens', 4,
3512 error(filename, linenum, 'whitespace/parens', 2,
3515 error(filename, linenum, 'whitespace/parens', 2,
3538 nesting_state.stack[-1].check_namespace_indentation and
3540 nesting_state.previous_stack_top == nesting_state.stack[-2])
3553 https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
3561 of vertical space and comments just to get through a lint check.
3562 NOLINT *on the last line of a function* disables this check.
3567 linenum: The number of the line to check.
3581 function_name = match_result.group(1).split()[-1]
3583 not Match(r'[A-Z_]+$', function_name)):
3606 # No body for the function (or evidence of a non-function) was found.
3610 function_state.Check(error, filename, linenum)
3613 function_state.Count() # Count non-blank/non-comment lines.
3625 linenum: The number of the line to check.
3626 next_line_start: The first non-whitespace column of the next line.
3630 if commentpos != -1:
3631 # Check if the // may be in quotes. If so, ignore it
3636 line[commentpos-1] not in string.whitespace) or
3638 line[commentpos-2] not in string.whitespace))):
3639 error(filename, linenum, 'whitespace/comments', 2,
3646 # One whitespace is correct; zero whitespace is handled elsewhere.
3649 error(filename, linenum, 'whitespace/todo', 2,
3659 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3661 error(filename, linenum, 'whitespace/todo', 2,
3669 error(filename, linenum, 'whitespace/comments', 4,
3676 Things we check for: spaces around operators, spaces after
3685 linenum: The number of the line to check.
3691 # Don't use "elided" lines here, otherwise we can't check commented lines.
3692 # Don't want to use "raw" either, because we don't want to check inside C++11
3697 # Before nixing comments, check if the line is blank for no good
3716 prev_line = elided[linenum - 1]
3720 # This ignores whitespace at the start of a namespace block
3722 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
3724 # complain, we check if it is an exception to the rule: The previous
3725 # non-empty line has the parameters of a function header that are indented
3727 # the same line as the function name). We also check for the case where
3734 search_position = linenum-2
3737 search_position -= 1
3752 error(filename, linenum, 'whitespace/blank_line', 2,
3755 # Ignore blank lines at the end of a block in a long if-else
3767 and next_line.find('} else ') == -1):
3768 error(filename, linenum, 'whitespace/blank_line', 3,
3774 error(filename, linenum, 'whitespace/blank_line', 3,
3777 # Next, check comments
3781 next_line_start = len(next_line) - len(next_line.lstrip())
3791 error(filename, linenum, 'whitespace/braces', 5,
3794 # In range-based for, we wanted spaces before and after the colon, but
3798 error(filename, linenum, 'whitespace/forcolon', 2,
3799 'Missing space around colon in range-based for loop')
3808 linenum: The number of the line to check.
3826 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3827 # Otherwise not. Note we only check for non-spaces on *both* sides;
3828 # sometimes people put non-spaces on one side when aligning ='s among
3836 error(filename, linenum, 'whitespace/operators', 4,
3839 # It's ok not to have spaces around binary operators like + - * /, but if
3840 # there's too little whitespace, we get concerned. It's hard to tell,
3843 # You should always have whitespace around binary operators.
3845 # Check <= and >= first to avoid false positives with < and >, then
3846 # check non-include lines for spacing around < and >.
3856 error(filename, linenum, 'whitespace/operators', 3,
3867 if end_pos <= -1:
3868 error(filename, linenum, 'whitespace/operators', 3,
3874 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3878 if start_pos <= -1:
3879 error(filename, linenum, 'whitespace/operators', 3,
3882 # We allow no-spaces around << when used like this: 10<<20, but
3890 error(filename, linenum, 'whitespace/operators', 3,
3893 # We allow no-spaces around >> for almost anything. This is because
3905 match = Search(r'>>[a-zA-Z_]', line)
3907 error(filename, linenum, 'whitespace/operators', 3,
3911 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3913 error(filename, linenum, 'whitespace/operators', 4,
3923 linenum: The number of the line to check.
3931 error(filename, linenum, 'whitespace/parens', 5,
3947 error(filename, linenum, 'whitespace/parens', 5,
3950 error(filename, linenum, 'whitespace/parens', 5,
3961 linenum: The number of the line to check.
3969 # This does not apply when the non-space character following the
3973 # We run this check in two passes: first pass on elided lines to
3979 error(filename, linenum, 'whitespace/comma', 3,
3987 error(filename, linenum, 'whitespace/semicolon', 3,
3992 """Check if expression looks like a type name, returns true if so.
3998 expr: The expression to check.
4018 block_index = len(nesting_state.stack) - 1
4033 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
4038 first_line -= 1
4041 # there are probably no template things to check for this block
4042 block_index -= 1
4049 block_index -= 1
4060 linenum: The number of the line to check.
4076 # Try a bit harder to check for brace initialization. This
4088 # We check for the character following the closing brace, and
4103 # spurious semicolon with a separate check.
4108 if endpos > -1:
4111 min(endlinenum + 3, clean_lines.NumLines() - 1)):
4118 error(filename, linenum, 'whitespace/braces', 5,
4123 error(filename, linenum, 'whitespace/braces', 5,
4130 error(filename, linenum, 'whitespace/semicolon', 5,
4133 error(filename, linenum, 'whitespace/semicolon', 5,
4138 error(filename, linenum, 'whitespace/semicolon', 5,
4144 """Check if the token ending on (linenum, column) is decltype().
4148 linenum: the number of the line to check.
4149 column: end column of the token to check.
4169 linenum: The number of the line to check.
4182 # and the check will be skipped by the first condition.
4183 if (class_info.last_line - class_info.starting_linenum <= 24 or
4192 # - We are at the beginning of the class.
4193 # - We are forward-declaring an inner class that is semantically
4197 prev_line = clean_lines.lines[linenum - 1]
4202 # account for multi-line base-specifier lists, e.g.:
4210 if end_class_head < linenum - 1:
4211 error(filename, linenum, 'whitespace/blank_line', 3,
4216 """Return the most recent non-blank line and its line number.
4220 linenum: The number of the line to check.
4224 non-blank line before the current line, or the empty string if this is the
4225 first non-blank line. The second is the line number of that line, or -1
4226 if this is the first non-blank line.
4229 prevlinenum = linenum - 1
4234 prevlinenum -= 1
4235 return ('', -1)
4244 linenum: The number of the line to check.
4253 # to control the lifetime of stack-allocated variables. Braces are also
4255 # perfectly: we just don't complain if the last non-whitespace character on
4256 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
4263 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
4264 error(filename, linenum, 'whitespace/braces', 4,
4271 error(filename, linenum, 'whitespace/newline', 4,
4276 if Search(r'else if\s*\(', line): # could be multi-line if
4283 brace_on_right = endline[endpos:].find('{') != -1
4293 error(filename, linenum, 'whitespace/newline', 4,
4298 error(filename, linenum, 'whitespace/newline', 4,
4301 # Check single-line if/else bodies. The style guide says 'curly braces are not
4302 # required for single-line statements'. We additionally allow multi-line,
4306 # lower than the if. We also check for ambiguous if/else nesting without
4315 pos = if_match.end() - 1
4317 # Check for an opening brace, either directly after the if or on the next
4318 # line. If found, this isn't a single-statement conditional.
4321 and endlinenum < (len(clean_lines.elided) - 1)
4329 # We allow a mix of whitespace and closing braces (e.g. for one-liner
4340 elif endlinenum < len(clean_lines.elided) - 1:
4363 linenum: The number of the line to check.
4398 # braces inside multi-dimensional arrays, but this is fine since
4415 # Matched closing parenthesis (case 1). Check the token before the
4418 # - macro that defines a base class
4419 # - multi-line macro that defines a base class
4420 # - macro that defines the whole class-head
4424 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
4425 # - TYPED_TEST
4426 # - INTERFACE_DEF
4427 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
4437 # - Compound literals
4438 # - Lambdas
4439 # - alignas specifier with anonymous structs
4440 # - decltype
4444 if opening_parenthesis[2] > -1:
4446 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
4460 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
4461 # Multi-line lambda-expression
4465 # Try matching cases 2-3.
4468 # Try matching cases 4-6. These are always matched on separate lines.
4480 # Check matching closing brace
4484 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
4485 # Current {} pair is eligible for semicolon check, and we have found
4493 # We need to check the line forward for NOLINT
4495 ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
4510 linenum: The number of the line to check.
4516 # do-while-loops, since those lines should start with closing brace.
4518 # We also check "if" blocks here, since an empty conditional block
4528 # No warning for all other cases, including whitespace or newline, since we
4529 # have a separate check for semicolons preceded by whitespace.
4532 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
4535 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
4538 # Check for if statements that have completely empty bodies (no comments)
4545 # Loop until EOF or find anything that's not whitespace or opening {.
4581 bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4585 body = opening_line[opening_pos+1:closing_pos-1]
4587 # Check if the body is empty
4593 # Loop until EOF or find anything that's not whitespace or else clause.
4604 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
4609 """Find a replaceable CHECK-like macro.
4614 (macro name, start position), or (None, -1) if no replaceable
4621 # to make sure that we are matching the expected CHECK macro, as
4622 # opposed to some other macro that happens to contain the CHECK
4628 return (None, -1)
4632 """Checks the use of CHECK and EXPECT macros.
4637 linenum: The number of the line to check.
4653 # If the check macro is followed by something other than a
4660 expression = lines[linenum][start_pos + 1:end_pos - 1]
4665 expression += last_line[0:end_pos - 1]
4668 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4674 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4689 # CHECK(42 < a && a < b);
4693 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4694 # Non-relational operator
4708 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4720 # Check that rhs do not contain logical operators. We already know
4722 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4727 # CHECK(variable != iterator)
4733 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4737 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4739 # Consider using CHECK_EQ instead of CHECK(a == b)
4743 error(filename, linenum, 'readability/check', 2,
4750 """Check alternative keywords being used in boolean expressions.
4755 linenum: The number of the line to check.
4764 # Last ditch effort to avoid multi-line comments. This will not help
4768 # multi-line comments in preprocessor macros.
4771 # multi-line comments.
4798 # https://mail.python.org/pipermail/python-list/2012-August/628809.html
4805 width -= 1
4818 do what we can. In particular we check for 2-space indents, line lengths,
4824 linenum: The number of the line to check.
4831 # Don't use "elided" lines here, otherwise we can't check commented lines.
4832 # Don't want to use "raw" either, because we don't want to check inside C++11
4836 prev = raw_lines[linenum - 1] if linenum > 0 else ''
4838 if line.find('\t') != -1:
4839 error(filename, linenum, 'whitespace/tab', 1,
4843 # hard to reconcile that with 2-space indents.
4861 # section labels, and also lines containing multi-line raw strings.
4862 # We also don't check for lines that look like continuation lines
4864 # because the rules for how to indent those are non-trivial.
4870 error(filename, linenum, 'whitespace/indent', 3,
4871 'Weird number of spaces at line-start. '
4872 'Are you using a 2-space indent?')
4874 if line and line[-1].isspace():
4875 error(filename, linenum, 'whitespace/end_of_line', 4,
4876 'Line ends in whitespace. Consider deleting these extra spaces.')
4878 # Check if the line is a header guard.
4900 not Match(r'^// \$Id:.*#[0-9]+ \$$', line) and
4904 error(filename, linenum, 'whitespace/line_length', 2,
4912 cleansed_line.find('for') == -1 and
4913 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4914 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4916 not ((cleansed_line.find('case ') != -1 or
4917 cleansed_line.find('default:') != -1) and
4918 cleansed_line.find('break;') != -1)):
4919 error(filename, linenum, 'whitespace/newline', 0,
4940 # Matches the first component of a filename delimited by -s and _s. That is:
4943 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4944 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4945 _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4949 """Drops common suffixes like _test.cc or -inl.h from filename.
4952 >>> _DropCommonSuffixes('foo/foo-inl.h')
4973 filename[-len(suffix) - 1] in ('-', '_')):
4974 return filename[:-len(suffix) - 1]
5009 # Mark include as C header if in list or in a known folder for standard-ish C headers.
5054 """Check rules that are applicable to #include lines.
5063 linenum: The number of the line to check.
5071 # Only do this check if the included header follows google naming
5110 basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
5118 include_state.include_list[-1].append((include, linenum))
5151 (, [, or {, and the matching close-punctuation symbol. This properly nested
5169 # Give opening punctuations to get the matching close-punctuations.
5181 assert text[start_position - 1] in matching_punctuation, (
5184 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
5187 if text[position] == punctuation_stack[-1]:
5196 # Opening punctuations left without matching close-punctuations.
5199 return text[start_position:position - 1]
5202 # Patterns for matching call-by-reference parameters.
5211 _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
5217 # A call-by-reference parameter ends with '& identifier'.
5221 # A call-by-const-reference parameter either ends with 'const& identifier'
5241 linenum: The number of the line to check.
5249 # check it.
5272 # TODO(unknown): check that 1-arg constructors are explicit.
5275 # TODO(unknown): check that classes declare or disable copy/assign
5279 # Check if people are using the verboten C basic types. The only exception
5291 # Check if some verboten operator overloading is going on
5292 # TODO(unknown): catch out-of-line unary operator&:
5301 # Check for suspicious usage of "if" like
5307 # Check for potential format string bugs like printf(foo).
5309 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
5316 match = Match(r'([\w.\->()]+)$', printf_args)
5324 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
5326 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
5334 'Do not use namespace using-directives. '
5335 'Use using-declarations instead.')
5338 'Do not use namespace using-directives. '
5339 'Use using-declarations instead.')
5341 # Detect variable-length arrays.
5342 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
5344 match.group(3).find(']') == -1):
5348 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
5363 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
5364 if Match(r'k[A-Z0-9]\w*', tok): continue
5365 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
5366 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
5377 'Do not use variable-length arrays. Use an appropriately named '
5378 "('k' followed by CamelCase) compile-time constant for the size.")
5380 # Check for use of unnamed namespaces in header files. Registration
5385 and line[-1] != '\\'):
5388 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
5393 """Check for unsafe global or static objects.
5398 linenum: The number of the line to check.
5407 # Check for people declaring static/global STL strings at the top level.
5412 # TODO(unknown): File bugs for clang-tidy to find these.
5415 r'([a-zA-Z0-9_:]+)\b(.*)',
5419 # - String pointers (as opposed to values).
5425 # - Functions and template specializations.
5429 # - Operators. These are matched separately because operator names
5430 # cross non-word boundaries, and trying to match both operators
5437 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
5447 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
5448 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
5454 """Check for printf related issues.
5459 linenum: The number of the line to check.
5465 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
5472 # Check if some verboten C functions are being used.
5483 """Check if current line contains an inherited function.
5487 linenum: The number of the line to check.
5490 virt-specifier.
5493 for i in xrange(linenum, max(-1, linenum - 10), -1):
5505 """Check if current line contains an out-of-line method definition.
5509 linenum: The number of the line to check.
5511 True if current line contains an out-of-line method definition.
5514 for i in xrange(linenum, max(-1, linenum - 10), -1):
5521 """Check if current line is inside constructor initializer list.
5525 linenum: The number of the line to check.
5530 for i in xrange(linenum, 1, -1):
5545 # brace-initialized member in constructor initializer list.
5549 # - A closing brace or semicolon, probably the end of the previous
5551 # - An opening brace, probably the start of current class or namespace.
5564 """Check for non-const references.
5572 linenum: The number of the line to check.
5583 # a choice, so any non-const references should not be blamed on
5588 # Don't warn on out-of-line method definitions, as we would warn on the
5589 # in-line declaration, if it isn't marked with 'override'.
5614 clean_lines.elided[linenum - 1])
5615 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5618 clean_lines.elided[linenum - 1])
5622 # Check for templated parameter that is split across multiple lines
5624 if endpos > -1:
5627 if startpos > -1 and startline < linenum:
5634 # Check for non-const references in function parameters. A single '&' may
5651 # We don't need to check the current line, since the '&' would
5655 for i in xrange(linenum - 1, max(0, linenum - 10), -1):
5670 # We allow non-const references in a few standard places, like functions
5671 # called "swap()" or iostream operators like "<<" or ">>". Do not check
5685 # multi-line parameter list. Try a bit harder to catch this case.
5688 Search(allowed_functions, clean_lines.elided[linenum - i - 1])):
5696 'Is this a non-const reference? '
5707 linenum: The number of the line to check.
5712 # Check to see if they're using an conversion function cast.
5725 # - New operators
5726 # - Template arguments with function types
5731 # template argument. False negative with less-than comparison is
5744 # - Function pointers
5745 # - Casts to pointer types
5746 # - Placement new
5747 # - Alias declarations
5773 # Check pointer casts for other than string constants
5778 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5781 # Some non-identifier character is required before the '&' for the
5803 if y2 < clean_lines.NumLines() - 1:
5805 if Match(r'\s*(?:->|\[)', extended_line):
5821 """Checks for a C-style cast by looking for the pattern.
5826 linenum: The number of the line to check.
5829 pattern: The regular expression used to find C-style casts.
5842 context = line[0:match.start(1) - 1]
5843 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5849 for i in xrange(linenum - 1, max(0, linenum - 5), -1):
5851 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
5854 # operator++(int) and operator--(int)
5855 if context.endswith(' operator++') or context.endswith(' operator--'):
5861 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
5867 'Using C-style cast. Use %s<%s>(...) instead' %
5878 linenum: The number of the line to check.
5888 clean_lines.elided[linenum - 1]) or
5890 clean_lines.elided[linenum - 2]) or
5892 clean_lines.elided[linenum - 1]))))
5948 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5954 # Match set<type>, but not foo->set<type>, foo.set<type>
5976 """Check if these two filenames belong to the same module.
5979 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
6012 filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))]
6015 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
6020 filename_h = filename_h[:-(len(fileinfo_h.Extension()))]
6021 if filename_h.endswith('-inl'):
6022 filename_h = filename_h[:-len('-inl')]
6029 common_path = filename_cc[:-len(filename_h)]
6087 # String is special -- it is a non-templatized type in STL.
6090 # Don't warn about strings in non-STL namespaces:
6091 # (We check only the first match per line; good enough.)
6107 # Don't warn about IWYU in non-STL namespaces:
6108 # (We check only the first match per line; good enough.)
6166 """Check that make_pair's template arguments are deduced.
6174 linenum: The number of the line to check.
6182 'For C++11-compatibility, omit template arguments from make_pair'
6187 """Check if line contains a redundant "virtual" function-specifier.
6192 linenum: The number of the line to check.
6200 # Ignore "virtual" keywords that are near access-specifiers. These
6201 # are only used in class base-specifier and do not apply to member
6217 end_col = -1
6218 end_line = -1
6243 # Set end_col to check whole lines after we are done with the
6251 """Check if line contains a redundant "override" or "final" virt-specifier.
6256 linenum: The number of the line to check.
6260 # the declarator ends and where the virt-specifier starts to avoid
6267 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
6272 # Check that at most one of "override" or "final" is present, not both
6294 isinstance(nesting_state.stack[-1], _NamespaceInfo))
6298 nesting_state.stack[-1].check_namespace_indentation and
6299 isinstance(nesting_state.stack[-2], _NamespaceInfo))
6304 """This method determines if we should apply our namespace indentation check.
6315 True if we should apply our namespace indentation check. Currently, it
6325 # If we are in a macro, we do not want to check the namespace indentation.
6360 extra_check_functions: An array of additional check functions that will be
6394 linenum: The number of the line to check.
6435 ('std::%s is an unapproved C++11 class or function. Send c-style '
6446 linenum: The number of the line to check.
6470 extra_check_functions: An array of additional check functions that will be
6500 # Check that the .cc file has included its header if it exists.
6504 # We check here rather than inside ProcessLine so that we see raw
6534 with open(cfg_file, encoding='utf-8') as file_handle:
6558 # Suppress "Ignoring file" warning when using --quiet.
6591 # Apply all the accumulated filters in reverse order (top-level directory
6600 """Does google-lint on a single file.
6608 extra_check_functions: An array of additional check functions that will be
6624 # Support the UNIX convention of using "-" for stdin. Note that
6631 if filename == '-':
6641 # The -1 accounts for the extra trailing blank line we get from split()
6642 for linenum in range(len(lines) - 1):
6660 if filename != '-' and file_extension not in GetAllExtensions():
6667 # If end-of-line sequences are a mix of LF and CR-LF, issue
6670 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6675 # end-of-line sequence should be, since that will return the
6676 # server-side end-of-line sequence.
6679 # check whether the file is mostly CRLF or just LF, and warn on the
6682 Error(filename, linenum, 'whitespace/newline', 1,
6685 # Suppress printing anything if --quiet was passed unless the error
6715 """Prints a list of all the error-categories used by error messages.
6717 These are the categories used to filter messages via --filter.
6726 This may set the output format and verbosity level as side-effects.
6760 if opt == '--help':
6762 if opt == '--version':
6764 elif opt == '--output':
6769 elif opt == '--quiet':
6771 elif opt == '--verbose' or opt == '--v':
6773 elif opt == '--filter':
6777 elif opt == '--counting':
6781 elif opt == '--root':
6784 elif opt == '--repository':
6787 elif opt == '--linelength':
6793 elif opt == '--exclude':
6798 elif opt == '--extensions':
6800 elif opt == '--headers':
6802 elif opt == '--recursive':
6804 elif opt == '--includeorder':
6857 """Filters out files listed in the --exclude command line switch. File paths
6889 # if we try to print something containing non-ASCII characters.
6895 # If --quiet is passed, suppress printing error count unless there are errors.