• Home
  • Raw
  • Download

Lines Matching +full:lint +full:- +full:cpp

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
67 # -- pylint: disable=redefined-builtin
72 Syntax: cpplint.py [--verbose=#] [--output=emacs|eclipse|vs7|junit]
73 [--filter=-x,+y,...]
74 [--counting=total|toplevel|detailed] [--root=subdir]
75 [--repository=path]
76 [--linelength=digits] [--headers=x,y,...]
77 [--recursive]
78 [--exclude=path]
79 [--extensions=hpp,cpp,...]
80 [--quiet]
81 [--version]
90 Every problem is given a confidence score from 1-5, with 5 meaning we are
94 To suppress false-positive errors of a certain category, add a
101 Change the extensions with the --extensions flag.
112 Specify a number 0-5 to restrict errors to certain verbosity levels.
119 filter=-x,+y,...
120 Specify a comma-separated list of category-filters to apply: only
124 "-FOO" and "FOO" means "do not print categories that start with FOO".
127 Examples: --filter=-whitespace,+whitespace/braces
128 --filter=whitespace,runtime/printf,+runtime/printf_format
129 --filter=-,+build/include_what_you_use
132 --filter=
137 the top-level categories like 'build' and 'whitespace' will
143 guard CPP variable. By default, this is determined by searching for a
145 given path is used instead. This option allows the header guard CPP
148 with SVN). In addition, users of non-mainstream version control systems
149 can use this flag to ensure readable header guard CPP variables.
154 with no --repository flag, the header guard CPP variable will be:
159 If Alice uses the --repository=trunk flag and Bob omits the flag or
160 uses --repository=. then the header guard CPP variable will be:
166 The root directory used for deriving header guard CPP variable.
169 .git, .hg, or .svn but can also be controlled with the --repository flag.
174 cwd=top/src), the header guard CPP variables for
178 --root=chrome => BROWSER_UI_BROWSER_H_
179 --root=chrome/browser => UI_BROWSER_H_
180 --root=.. => SRC_CHROME_BROWSER_UI_BROWSER_H_
187 --linelength=120
190 Search for files to lint recursively. Each directory given in the list
202 --exclude=one.cc
203 --exclude=src/*.cc
204 --exclude=src/*.cc --exclude=test/*.cc
210 --extensions=%s
214 automatically added to --extensions list.
218 --headers=%s
219 --headers=hpp,hxx
220 --headers=hpp
222 cpplint.py supports per-directory configurations specified in CPPLINT.cfg
227 filter=+filter1,-filter2,...
235 is usually placed in the top-level project directory.
237 The "filter" option is similar in function to --filter flag. It specifies
239 through --filter command-line flag.
247 The "root" option is similar in function to the --root flag (see example
250 The "headers" option is similar in function to the --headers flag
254 sub-directories, unless overridden by a nested configuration file.
257 filter=-build/include_order,+build/include_alpha
263 file is located) and all sub-directories.
267 # We want an explicit list so we can list them all in cpplint --filter=.
345 # These error categories are no longer enforced by cpplint, but for backwards-
352 # The default state of the category filter. This is overridden by the --filter=
354 # off by default (i.e., categories that must be enabled by the --filter= flags).
355 # All entries here should start with a '-' or '+', as in the --filter= flag.
356 _DEFAULT_FILTERS = ['-build/include_alpha']
368 # We used to check for high-bit characters, but after much discussion we
369 # decided those were OK, as long as they were in UTF-8 and didn't represent
370 # hard-coded international strings, which belong in a separate i18n file.
537 # - Anything not following google file name conventions (containing an
539 # - Lua headers.
541 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
597 # False positives include C-style multi-line comments and multi-line strings
635 r'\s\*[a-zA-Z_][0-9a-zA-Z_]*')
643 # The root directory used for deriving header guard CPP variable.
644 # This is set by --root flag.
650 # This is set by the --repository flag.
653 # Files to exclude from linting. This is set by the --exclude flag.
660 # This is set by --linelength flag.
666 # -- pylint: disable=redefined-builtin
672 # -- pylint: disable=redefined-builtin
676 # -- pylint: disable=no-member
692 # This is set by --headers flag.
717 # This is set by --extensions flag
720 ['c', 'cc', 'cpp', 'cxx', 'c++', 'cu']))
728 PrintUsage('Extensions should be a comma-separated list of values;'
729 'for example: extensions=hpp,cpp\n'
736 """Updates the global list of line error-suppressions.
759 category = category[1:-1]
770 Parses any lint directives in the file that have global effect.
896 Line number of previous occurrence, or -1 if the header has not
903 return -1
921 self.include_list[-1] = []
929 - replaces "-" with "_" so they both cmp the same.
930 - removes '-inl' since we don't require them to be after the main header.
931 - lowercase everything, just in case.
939 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
958 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
963 """Returns a non-empty error message if the next header is out of order.
1017 """Maintains module-wide state.."""
1028 self.quiet = False # Suppress non-error messagess?
1031 # "emacs" - format that emacs can parse (default)
1032 # "eclipse" - format that eclipse can parse
1033 # "vs7" - format that Microsoft Visual Studio 7 can parse
1034 # "junit" - format that Jenkins, Bamboo, etc can parse
1063 """Sets the error-message filters.
1069 filters: A string of comma-separated filters (eg "+whitespace/indent").
1070 Each filter should start with + or -; else we die.
1073 ValueError: The comma-separated filters did not all start with '+' or '-'.
1074 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
1081 """ Adds more filters to the existing list of error-message filters. """
1087 if not (filt.startswith('+') or filt.startswith('-')):
1088 raise ValueError('Every filter in --filters must start with + or -'
1176 xml_decl = '<?xml version="1.0" encoding="UTF-8" ?>\n'
1177 return xml_decl + xml.etree.ElementTree.tostring(testsuite, 'utf-8').decode('utf-8')
1222 """Sets the module's error-message filters.
1228 filters: A string of comma-separated filters (eg "whitespace/indent").
1229 Each filter should start with + or -; else we die.
1240 filters: A string of comma-separated filters (eg "whitespace/indent").
1241 Each filter should start with + or -; else we die.
1256 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
1303 ' %s has %d non-comment lines'
1406 """File base name - text after the final slash, before the final period."""
1410 """File extension - text following the final period, includes that period."""
1436 if one_filter.startswith('-'):
1451 """Logs the fact we've found a lint error.
1467 confidence: A number from 1-5 representing a confidence score for
1490 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
1493 # Matches multi-line C style comments.
1499 # if this doesn't work we try on left side but only if there's a non-character
1511 This function does not consider single-line nor multi-line comments.
1522 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1530 multi-line string
1589 # Start of a multi-line raw string
1622 """Clears a range of lines for multi-line comments."""
1623 # Having // dummy comments makes the lines non-empty, so we will not get
1630 """Removes multiline (c-style) comments from lines."""
1639 'Could not find end of multi-line comment')
1646 """Removes //-comments and single-line C-style /* */ comments.
1652 The line with single-line comments removed.
1655 if commentpos != -1 and not IsCppString(line[:commentpos]):
1739 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1740 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1766 On finding an unclosed expression: (-1, None)
1767 Otherwise: (-1, new stack at end of this line)
1776 if i > 0 and line[i - 1] == '<':
1778 if stack and stack[-1] == '<':
1781 return (-1, None)
1793 while stack and stack[-1] == '<':
1796 return (-1, None)
1797 if ((stack[-1] == '(' and char == ')') or
1798 (stack[-1] == '[' and char == ']') or
1799 (stack[-1] == '{' and char == '}')):
1805 return (-1, None)
1809 # Ignore "->" and operator functions
1811 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1817 if stack[-1] == '<':
1825 while stack and stack[-1] == '<':
1828 return (-1, None)
1831 return (-1, stack)
1852 (line, len(lines), -1) if we never find a close. Note we ignore
1859 return (line, clean_lines.NumLines(), -1)
1863 if end_pos > -1:
1867 while stack and linenum < clean_lines.NumLines() - 1:
1871 if end_pos > -1:
1875 return (line, clean_lines.NumLines(), -1)
1891 On finding an unclosed expression: (-1, None)
1892 Otherwise: (-1, new stack at beginning of this line)
1903 # Ignore it if it's a "->" or ">=" or "operator>"
1905 (line[i - 1] == '-' or
1906 Match(r'\s>=\s', line[i - 1:]) or
1908 i -= 1
1913 if i > 0 and line[i - 1] == '<':
1915 i -= 1
1919 if stack and stack[-1] == '>':
1928 while stack and stack[-1] == '>':
1931 return (-1, None)
1932 if ((char == '(' and stack[-1] == ')') or
1933 (char == '[' and stack[-1] == ']') or
1934 (char == '{' and stack[-1] == '}')):
1940 return (-1, None)
1945 while stack and stack[-1] == '>':
1948 return (-1, None)
1950 i -= 1
1952 return (-1, stack)
1968 (line, 0, -1) if we never find the matching opening brace. Note
1974 return (line, 0, -1)
1978 if start_pos > -1:
1983 linenum -= 1
1985 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
1986 if start_pos > -1:
1990 return (line, 0, -1)
2047 """Returns the CPP variable that should be used as a header guard.
2053 The CPP variable that should be used as a header guard in the
2062 # Replace 'c++' with 'cpp'.
2063 filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
2073 # Process the file path with the --root flag if it was set.
2080 # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
2083 # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
2087 # --root=subdir , lstrips subdir from the header guard
2098 # --root=.. , will prepend the outer directory to the header guard
2115 # --root=FAKE_DIR is ignored
2119 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
2174 'No #ifndef header guard found, suggested CPP variable is: %s' %
2205 for i in xrange(1, len(raw_lines) - 1):
2234 basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
2258 contained invalid UTF-8 (likely) or Unicode replacement characters (which
2260 numbering if the invalid UTF-8 occurred adjacent to a newline.
2272 'Line contains invalid UTF-8 (or Unicode replacement character).')
2282 bad_headers = set('%s.h' % name[:-6] for name in all_headers.keys()
2283 if name.endswith('-inl.h'))
2287 err = '%s includes both %s and %s-inl.h' % (filename, name, name)
2304 # last-but-two element of lines() exists and is empty.
2305 if len(lines) < 3 or lines[-2]:
2306 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
2319 in this lint program, so we warn about both.
2335 'Complex multi-line /*...*/-style comment found. '
2336 'Lint may give bogus warnings. '
2337 'Consider replacing these with //-style comments, '
2339 'or with more clearly structured multi-line comments.')
2341 if (line.count('"') - line.count('\\"')) % 2:
2343 'Multi-line string ("...") found. This lint script doesn\'t '
2348 # (non-threadsafe name, thread-safe alternative, validation pattern)
2352 # ->rand(); // some member function rand().
2360 _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
2379 """Checks for calls to thread-unsafe functions.
2382 multi-threading. Also, engineers are relying on their old experience;
2384 tests guide the engineers to use thread-safe functions (when using
2425 r'^\s*\*\w+(\+\+|--);')
2454 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2549 depth += line.count('{') - line.count('}')
2563 for i in xrange(linenum - 1, self.starting_linenum, -1):
2579 # This means we will not check single-line class definitions.
2613 if (linenum - self.starting_linenum < 10
2672 # - _ClassInfo: a class or struct.
2673 # - _NamespaceInfo: a namespace.
2674 # - _BlockInfo: some other type of block.
2698 return (not self.stack) or self.stack[-1].seen_open_brace
2706 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2714 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2722 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2730 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2776 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2795 - Preprocessor condition evaluates to true from #if up to first
2798 - Preprocessor condition evaluates to false from #else/#elif up
2799 to #endif. We still perform lint checks on these lines, but
2812 if not self.pp_stack[-1].seen_else:
2816 self.pp_stack[-1].seen_else = True
2817 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2820 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2830 if self.pp_stack[-1].seen_else:
2833 self.stack = self.pp_stack[-1].stack_before_else
2858 self.previous_stack_top = self.stack[-1]
2868 inner_block = self.stack[-1]
2869 depth_change = line.count('(') - line.count(')')
2904 if line.find('{') != -1:
2915 r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
2918 (not self.stack or self.stack[-1].open_parentheses == 0)):
2938 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2941 if self.stack and isinstance(self.stack[-1], _ClassInfo):
2942 classinfo = self.stack[-1]
2979 self.stack[-1].seen_open_brace = True
2985 self.stack[-1].inline_asm = _BLOCK_ASM
3001 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
3011 for i in range(len(self.stack), 0, -1):
3012 classinfo = self.stack[i - 1]
3041 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
3043 Complain about several constructs which gcc-2 accepts, but which are
3044 not standard C++. Warning about these in lint is one way to ease the
3046 - put storage class first (e.g. "static const" instead of "const static").
3047 - "%lld" instead of %qd" in printf-type functions.
3048 - "%1$d" is non-standard in printf-type functions.
3049 - "\%" is an undefined character escape sequence.
3050 - text after #endif is not allowed.
3051 - invalid inner-style forward declaration.
3052 - >? and <? operators, and their >?= and <?= cousins.
3056 gcc-2 compliance.
3071 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
3095 'Storage-class specifier (static, extern, typedef, etc) should be '
3100 'Uncommented text after #endif is non-standard. Use a comment.')
3104 'Inner-style forward declarations are invalid. Remove this line.')
3106 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
3109 '>? and <? (max and min) operators are non-standard and deprecated.')
3132 base_classname = classinfo.name.split('::')[-1]
3134 # Look for single-argument constructors that aren't marked explicit.
3174 len(defaulted_args) >= len(constructor_args) - 1) or
3197 'Single-parameter constructors should be marked explicit.')
3201 'Zero-parameter constructors should not be marked explicit.')
3216 # expressions - which have their own, more liberal conventions - we
3237 # " (something)(maybe-something)" or
3238 # " (something)(maybe-something," or
3300 nesting_state.stack[-1].check_namespace_indentation and
3302 nesting_state.previous_stack_top == nesting_state.stack[-2])
3323 of vertical space and comments just to get through a lint check.
3343 function_name = match_result.group(1).split()[-1]
3345 not Match(r'[A-Z_]+$', function_name)):
3368 # No body for the function (or evidence of a non-function) was found.
3370 'Lint failed to find start of function body.')
3375 function_state.Count() # Count non-blank/non-comment lines.
3388 next_line_start: The first non-whitespace column of the next line.
3392 if commentpos != -1:
3398 line[commentpos-1] not in string.whitespace) or
3400 line[commentpos-2] not in string.whitespace))):
3421 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3478 prev_line = elided[linenum - 1]
3484 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
3487 # non-empty line has the parameters of a function header that are indented
3496 search_position = linenum-2
3499 search_position -= 1
3517 # Ignore blank lines at the end of a block in a long if-else
3529 and next_line.find('} else ') == -1):
3543 next_line_start = len(next_line) - len(next_line.lstrip())
3555 # In range-based for, we wanted spaces before and after the colon, but
3560 'Missing space around colon in range-based for loop')
3587 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3588 # Otherwise not. Note we only check for non-spaces on *both* sides;
3589 # sometimes people put non-spaces on one side when aligning ='s among
3600 # It's ok not to have spaces around binary operators like + - * /, but if
3607 # check non-include lines for spacing around < and >.
3628 if end_pos <= -1:
3635 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3639 if start_pos <= -1:
3643 # We allow no-spaces around << when used like this: 10<<20, but
3654 # We allow no-spaces around >> for almost anything. This is because
3666 match = Search(r'>>[a-zA-Z_]', line)
3672 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3730 # This does not apply when the non-space character following the
3779 block_index = len(nesting_state.stack) - 1
3794 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3799 first_line -= 1
3803 block_index -= 1
3810 block_index -= 1
3869 if endpos > -1:
3872 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3944 if (class_info.last_line - class_info.starting_linenum <= 24 or
3953 # - We are at the beginning of the class.
3954 # - We are forward-declaring an inner class that is semantically
3958 prev_line = clean_lines.lines[linenum - 1]
3963 # account for multi-line base-specifier lists, e.g.:
3971 if end_class_head < linenum - 1:
3977 """Return the most recent non-blank line and its line number.
3985 non-blank line before the current line, or the empty string if this is the
3986 first non-blank line. The second is the line number of that line, or -1
3987 if this is the first non-blank line.
3990 prevlinenum = linenum - 1
3995 prevlinenum -= 1
3996 return ('', -1)
4014 # to control the lifetime of stack-allocated variables. Braces are also
4016 # perfectly: we just don't complain if the last non-whitespace character on
4017 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
4024 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
4037 if Search(r'else if\s*\(', line): # could be multi-line if
4044 brace_on_right = endline[endpos:].find('{') != -1
4062 # Check single-line if/else bodies. The style guide says 'curly braces are not
4063 # required for single-line statements'. We additionally allow multi-line,
4076 pos = if_match.end() - 1
4079 # line. If found, this isn't a single-statement conditional.
4082 and endlinenum < (len(clean_lines.elided) - 1)
4090 # We allow a mix of whitespace and closing braces (e.g. for one-liner
4101 elif endlinenum < len(clean_lines.elided) - 1:
4159 # braces inside multi-dimensional arrays, but this is fine since
4179 # - macro that defines a base class
4180 # - multi-line macro that defines a base class
4181 # - macro that defines the whole class-head
4185 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
4186 # - TYPED_TEST
4187 # - INTERFACE_DEF
4188 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
4198 # - Compound literals
4199 # - Lambdas
4200 # - alignas specifier with anonymous structs
4201 # - decltype
4205 if opening_parenthesis[2] > -1:
4207 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
4221 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
4222 # Multi-line lambda-expression
4226 # Try matching cases 2-3.
4229 # Try matching cases 4-6. These are always matched on separate lines.
4245 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
4256 ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
4277 # do-while-loops, since those lines should start with closing brace.
4342 bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4346 body = opening_line[opening_pos+1:closing_pos-1]
4370 """Find a replaceable CHECK-like macro.
4375 (macro name, start position), or (None, -1) if no replaceable
4389 return (None, -1)
4421 expression = lines[linenum][start_pos + 1:end_pos - 1]
4426 expression += last_line[0:end_pos - 1]
4435 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4454 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4455 # Non-relational operator
4469 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4483 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4494 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4525 # Last ditch effort to avoid multi-line comments. This will not help
4529 # multi-line comments in preprocessor macros.
4532 # multi-line comments.
4586 """Check for left-leaning pointer placement.
4624 # https://mail.python.org/pipermail/python-list/2012-August/628809.html
4631 width -= 1
4644 do what we can. In particular we check for 2-space indents, line lengths,
4662 prev = raw_lines[linenum - 1] if linenum > 0 else ''
4664 if line.find('\t') != -1:
4669 # hard to reconcile that with 2-space indents.
4687 # section labels, and also lines containing multi-line raw strings.
4690 # because the rules for how to indent those are non-trivial.
4697 'Weird number of spaces at line-start. '
4698 'Are you using a 2-space indent?')
4700 if line and line[-1].isspace():
4726 not Match(r'^// \$Id:.*#[0-9]+ \$$', line) and
4738 cleansed_line.find('for') == -1 and
4739 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4740 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4742 not ((cleansed_line.find('case ') != -1 or
4743 cleansed_line.find('default:') != -1) and
4744 cleansed_line.find('break;') != -1)):
4769 # Matches the first component of a filename delimited by -s and _s. That is:
4772 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4773 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4774 _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4778 """Drops common suffixes like _test.cc or -inl.h from filename.
4781 >>> _DropCommonSuffixes('foo/foo-inl.h')
4802 filename[-len(suffix) - 1] in ('-', '_')):
4803 return filename[:-len(suffix) - 1]
4928 basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
4936 include_state.include_list[-1].append((include, linenum))
4942 # 4) cpp system files
4968 (, [, or {, and the matching close-punctuation symbol. This properly nested
4986 # Give opening punctuations to get the matching close-punctuations.
4998 assert text[start_position - 1] in matching_punctuation, (
5001 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
5004 if text[position] == punctuation_stack[-1]:
5013 # Opening punctuations left without matching close-punctuations.
5016 return text[start_position:position - 1]
5019 # Patterns for matching call-by-reference parameters.
5028 _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
5034 # A call-by-reference parameter ends with '& identifier'.
5038 # A call-by-const-reference parameter either ends with 'const& identifier'
5089 # TODO(unknown): check that 1-arg constructors are explicit.
5109 # TODO(unknown): catch out-of-line unary operator&:
5126 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
5133 match = Match(r'([\w.\->()]+)$', printf_args)
5143 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
5151 'Do not use namespace using-directives. '
5152 'Use using-declarations instead.')
5155 'Do not use namespace using-directives. '
5156 'Use using-declarations instead.')
5158 # Detect variable-length arrays.
5159 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
5161 match.group(3).find(']') == -1):
5165 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
5180 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
5181 if Match(r'k[A-Z0-9]\w*', tok): continue
5182 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
5183 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
5194 'Do not use variable-length arrays. Use an appropriately named '
5195 "('k' followed by CamelCase) compile-time constant for the size.")
5202 and line[-1] != '\\'):
5229 # TODO(unknown): File bugs for clang-tidy to find these.
5232 r'([a-zA-Z0-9_:]+)\b(.*)',
5236 # - String pointers (as opposed to values).
5242 # - Functions and template specializations.
5246 # - Operators. These are matched separately because operator names
5247 # cross non-word boundaries, and trying to match both operators
5254 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
5264 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
5265 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
5282 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
5307 virt-specifier.
5310 for i in xrange(linenum, max(-1, linenum - 10), -1):
5322 """Check if current line contains an out-of-line method definition.
5328 True if current line contains an out-of-line method definition.
5331 for i in xrange(linenum, max(-1, linenum - 10), -1):
5347 for i in xrange(linenum, 1, -1):
5362 # brace-initialized member in constructor initializer list.
5366 # - A closing brace or semicolon, probably the end of the previous
5368 # - An opening brace, probably the start of current class or namespace.
5381 """Check for non-const references.
5400 # a choice, so any non-const references should not be blamed on
5405 # Don't warn on out-of-line method definitions, as we would warn on the
5406 # in-line declaration, if it isn't marked with 'override'.
5431 clean_lines.elided[linenum - 1])
5432 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5435 clean_lines.elided[linenum - 1])
5441 if endpos > -1:
5444 if startpos > -1 and startline < linenum:
5451 # Check for non-const references in function parameters. A single '&' may
5472 for i in xrange(linenum - 1, max(0, linenum - 10), -1):
5487 # We allow non-const references in a few standard places, like functions
5502 # multi-line parameter list. Try a bit harder to catch this case.
5505 Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
5513 'Is this a non-const reference? '
5542 # - New operators
5543 # - Template arguments with function types
5548 # template argument. False negative with less-than comparison is
5561 # - Function pointers
5562 # - Casts to pointer types
5563 # - Placement new
5564 # - Alias declarations
5595 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5598 # Some non-identifier character is required before the '&' for the
5620 if y2 < clean_lines.NumLines() - 1:
5622 if Match(r'\s*(?:->|\[)', extended_line):
5638 """Checks for a C-style cast by looking for the pattern.
5646 pattern: The regular expression used to find C-style casts.
5659 context = line[0:match.start(1) - 1]
5660 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5666 for i in xrange(linenum - 1, max(0, linenum - 5), -1):
5668 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
5671 # operator++(int) and operator--(int)
5672 if context.endswith(' operator++') or context.endswith(' operator--'):
5678 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
5684 'Using C-style cast. Use %s<%s>(...) instead' %
5705 clean_lines.elided[linenum - 1]) or
5707 clean_lines.elided[linenum - 2]) or
5709 clean_lines.elided[linenum - 1]))))
5765 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5771 # Match set<type>, but not foo->set<type>, foo.set<type>
5796 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5829 filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))]
5832 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
5837 filename_h = filename_h[:-(len(fileinfo_h.Extension()))]
5838 if filename_h.endswith('-inl'):
5839 filename_h = filename_h[:-len('-inl')]
5846 common_path = filename_cc[:-len(filename_h)]
5904 # String is special -- it is a non-templatized type in STL.
5907 # Don't warn about strings in non-STL namespaces:
5924 # Don't warn about IWYU in non-STL namespaces:
5999 'For C++11-compatibility, omit template arguments from make_pair'
6004 """Check if line contains a redundant "virtual" function-specifier.
6017 # Ignore "virtual" keywords that are near access-specifiers. These
6018 # are only used in class base-specifier and do not apply to member
6034 end_col = -1
6035 end_line = -1
6068 """Check if line contains a redundant "override" or "final" virt-specifier.
6077 # the declarator ends and where the virt-specifier starts to avoid
6084 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
6111 isinstance(nesting_state.stack[-1], _NamespaceInfo))
6115 nesting_state.stack[-1].check_namespace_indentation and
6116 isinstance(nesting_state.stack[-2], _NamespaceInfo))
6252 ('std::%s is an unapproved C++11 class or function. Send c-style '
6278 """Performs lint checks and reports any errors to the given error function.
6369 # For example, if we are checking for lint errors in /foo/bar/baz.cc
6377 # Suppress "Ignoring file" warning when using --quiet.
6408 # Apply all the accumulated filters in reverse order (top-level directory
6417 """Does google-lint on a single file.
6441 # Support the UNIX convention of using "-" for stdin. Note that
6448 if filename == '-':
6458 # The -1 accounts for the extra trailing blank line we get from split()
6459 for linenum in range(len(lines) - 1):
6477 if filename != '-' and file_extension not in GetAllExtensions():
6484 # If end-of-line sequences are a mix of LF and CR-LF, issue
6487 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6492 # end-of-line sequence should be, since that will return the
6493 # server-side end-of-line sequence.
6502 # Suppress printing anything if --quiet was passed unless the error
6532 """Prints a list of all the error-categories used by error messages.
6534 These are the categories used to filter messages via --filter.
6543 This may set the output format and verbosity level as side-effects.
6549 The list of filenames to lint.
6576 if opt == '--help':
6578 if opt == '--version':
6580 elif opt == '--output':
6585 elif opt == '--quiet':
6587 elif opt == '--verbose' or opt == '--v':
6589 elif opt == '--filter':
6593 elif opt == '--counting':
6597 elif opt == '--root':
6600 elif opt == '--repository':
6603 elif opt == '--linelength':
6609 elif opt == '--exclude':
6614 elif opt == '--extensions':
6616 elif opt == '--headers':
6618 elif opt == '--recursive':
6670 """Filters out files listed in the --exclude command line switch. File paths
6702 # if we try to print something containing non-ASCII characters.
6708 # If --quiet is passed, suppress printing error count unless there are errors.