• Home
  • Raw
  • Download

Lines Matching +full:missing +full:- +full:braces

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
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
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=.
312 'readability/braces',
343 'whitespace/braces',
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']
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)$')
801 # False positives include C-style multi-line comments and multi-line strings
843 'Missing space before {': r's/\([^ ]\){/\1 {/',
847 'Missing space after ,': r's/,\([^ ]\)/, \1/g',
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]
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()
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.
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.
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('-'):
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
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
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)
2098 (line, len(lines), -1) if we never find a close. Note we ignore
2105 return (line, clean_lines.NumLines(), -1)
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)
2214 (line, 0, -1) if we never find the matching opening brace. Note
2220 return (line, 0, -1)
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)
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() + '_'
2452 for i in xrange(1, len(raw_lines) - 1):
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,
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
2663 r'^\s*\*\w+(\+\+|--);')
2692 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2787 depth += line.count('{') - line.count('}')
2801 for i in xrange(linenum - 1, self.starting_linenum, -1):
2817 # This means we will not check single-line class definitions.
2841 # warning for missing namespace comments if there aren't enough
2851 if (linenum - self.starting_linenum < 10
2904 """Holds states related to parsing braces."""
2907 # Stack for tracking all braces. An object is pushed whenever we
2910 # - _ClassInfo: a class or struct.
2911 # - _NamespaceInfo: a namespace.
2912 # - _BlockInfo: some other type of block.
2936 return (not self.stack) or self.stack[-1].seen_open_brace
2944 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2952 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2960 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2968 return self.stack and self.stack[-1].inline_asm != _NO_ASM
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
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
3096 self.previous_stack_top = self.stack[-1]
3106 inner_block = self.stack[-1]
3107 depth_change = line.count('(') - line.count(')')
3133 # missing spaces will be flagged by CheckSpacing.
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]
3204 # Consume braces or semicolons from what's left of the line
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.
3294 gcc-2 compliance.
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.')
3454 # expressions - which have their own, more liberal conventions - we
3475 # " (something)(maybe-something)" or
3476 # " (something)(maybe-something," or
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
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.
3613 function_state.Count() # Count non-blank/non-comment lines.
3626 next_line_start: The first non-whitespace column of the next line.
3630 if commentpos != -1:
3636 line[commentpos-1] not in string.whitespace) or
3638 line[commentpos-2] not in string.whitespace))):
3655 'Missing username in TODO; it should look like '
3659 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3708 # A warning about missing end of namespace comments will be issued instead.
3716 prev_line = elided[linenum - 1]
3722 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
3725 # non-empty line has the parameters of a function header that are indented
3734 search_position = linenum-2
3737 search_position -= 1
3755 # Ignore blank lines at the end of a block in a long if-else
3767 and next_line.find('} else ') == -1):
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
3799 'Missing space around colon in range-based for loop')
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
3837 'Missing spaces around =')
3839 # It's ok not to have spaces around binary operators like + - * /, but if
3846 # check non-include lines for spacing around < and >.
3857 'Missing spaces around %s' % match.group(1))
3860 # triggered if both sides are missing spaces, even though
3861 # technically should should flag if at least one side is missing a
3867 if end_pos <= -1:
3869 'Missing spaces around <')
3872 # above, we only trigger if both sides are missing spaces to avoid
3874 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3878 if start_pos <= -1:
3880 'Missing spaces around >')
3882 # We allow no-spaces around << when used like this: 10<<20, but
3891 'Missing spaces around <<')
3893 # We allow no-spaces around >> for almost anything. This is because
3905 match = Search(r'>>[a-zA-Z_]', line)
3908 'Missing spaces around >>')
3911 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3932 'Missing space before ( in %s' % match.group(1))
3969 # This does not apply when the non-space character following the
3974 # verify that lines contain missing whitespaces, second pass on raw
3975 # lines to confirm that those missing whitespaces are not due to
3980 'Missing space after ,')
3988 'Missing space after ;')
4018 block_index = len(nesting_state.stack) - 1
4033 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
4038 first_line -= 1
4042 block_index -= 1
4049 block_index -= 1
4069 # braces when they are delimiting blocks, classes, namespaces etc.
4070 # And since you should never have braces at the beginning of a line,
4071 # this is an easy test. Except that braces used for initialization don't
4093 # closing braces up to "{;,)<". We can't simply silence the
4098 # Inner{...} if (...){ // Missing space before {
4108 if endpos > -1:
4111 min(endlinenum + 3, clean_lines.NumLines() - 1)):
4118 error(filename, linenum, 'whitespace/braces', 5,
4119 'Missing space before {')
4123 error(filename, linenum, 'whitespace/braces', 5,
4124 'Missing space before else')
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:
4216 """Return the most recent non-blank line and its line number.
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)
4239 """Looks for misplaced braces (e.g. at the end of line).
4252 # braces in a block to explicitly create a new scope, which is commonly used
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,
4274 # If braces come on one side of an else, they should be on both.
4276 if Search(r'else if\s*\(', line): # could be multi-line if
4283 brace_on_right = endline[endpos:].find('{') != -1
4285 error(filename, linenum, 'readability/braces', 5,
4288 error(filename, linenum, 'readability/braces', 5,
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,
4307 # braces.
4315 pos = if_match.end() - 1
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
4338 error(filename, linenum, 'readability/braces', 4,
4339 'If/else bodies with multiple statements require braces')
4340 elif endlinenum < len(clean_lines.elided) - 1:
4349 error(filename, linenum, 'readability/braces', 4,
4351 'Ambiguous nested if/else chains require braces.')
4353 error(filename, linenum, 'readability/braces', 4,
4354 'If/else bodies with multiple statements require braces')
4398 # braces inside multi-dimensional arrays, but this is fine since
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.
4484 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
4488 # Note: because we are scanning forward for opening braces, and
4495 ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
4500 error(filename, endlinenum, 'readability/braces', 4,
4516 # do-while-loops, since those lines should start with closing brace.
4581 bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4585 body = opening_line[opening_pos+1:closing_pos-1]
4609 """Find a replaceable CHECK-like macro.
4614 (macro name, start position), or (None, -1) if no replaceable
4628 return (None, -1)
4660 expression = lines[linenum][start_pos + 1:end_pos - 1]
4665 expression += last_line[0:end_pos - 1]
4674 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4693 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4694 # Non-relational operator
4708 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4722 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4733 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
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,
4836 prev = raw_lines[linenum - 1] if linenum > 0 else ''
4838 if line.find('\t') != -1:
4843 # hard to reconcile that with 2-space indents.
4861 # section labels, and also lines containing multi-line raw strings.
4864 # because the rules for how to indent those are non-trivial.
4871 'Weird number of spaces at line-start. '
4872 'Are you using a 2-space indent?')
4874 if line and line[-1].isspace():
4900 not Match(r'^// \$Id:.*#[0-9]+ \$$', line) and
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)):
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.
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'
5272 # TODO(unknown): check that 1-arg constructors are explicit.
5292 # TODO(unknown): catch out-of-line unary operator&:
5304 error(filename, linenum, 'readability/braces', 4,
5309 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
5316 match = Match(r'([\w.\->()]+)$', printf_args)
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.")
5385 and line[-1] != '\\'):
5388 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
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)):
5465 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
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.
5511 True if current line contains an out-of-line method definition.
5514 for i in xrange(linenum, max(-1, linenum - 10), -1):
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.
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])
5624 if endpos > -1:
5627 if startpos > -1 and startline < linenum:
5634 # Check for non-const references in function parameters. A single '&' may
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
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? '
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
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.
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' %
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>
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)]
6063 """Reports for missing stl includes.
6087 # String is special -- it is a non-templatized type in STL.
6090 # Don't warn about strings in non-STL namespaces:
6107 # Don't warn about IWYU in non-STL namespaces:
6182 'For C++11-compatibility, omit template arguments from make_pair'
6187 """Check if line contains a redundant "virtual" function-specifier.
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
6251 """Check if line contains a redundant "override" or "final" virt-specifier.
6260 # the declarator ends and where the virt-specifier starts to avoid
6267 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
6294 isinstance(nesting_state.stack[-1], _NamespaceInfo))
6298 nesting_state.stack[-1].check_namespace_indentation and
6299 isinstance(nesting_state.stack[-2], _NamespaceInfo))
6435 ('std::%s is an unapproved C++11 class or function. Send c-style '
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.
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.
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.